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
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
//! `WinBackend` — Direct2D + DirectWrite implementation of [`Backend`].
//!
//! The render target, text infrastructure, and rasterisers are described in
//! the "Implementation notes" section below.

use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
use std::time::{Duration, Instant};

use crate::backend::{
    Backend, BackendError, EditorPaintResult, PlatformServices, PointerShape, ServiceResult,
    WindowControl,
};
use crate::dispatch::{DoubleClickDetector, DragState, TextRegion};
use crate::event::{Point, Rect, UiEvent, Viewport};
#[cfg(target_os = "windows")]
use crate::generic_font::GenericFamily;
use crate::modal_stack::ModalStack;
use crate::paint_surface::PaintSurface;
use crate::primitives::activity_bar::ActivityBarRowHit;
use crate::primitives::button::{Button, ButtonLayout};
use crate::primitives::command_center::{CommandCenter, CommandCenterHit, CommandCenterLayout};
use crate::primitives::completions::{Completions, CompletionsLayout};
use crate::primitives::context_menu::{ContextMenu, ContextMenuLayout};
use crate::primitives::dialog::{Dialog, DialogLayout};
use crate::primitives::editor::Editor;
use crate::primitives::find_replace::FindReplacePanel;
use crate::primitives::form::{Form, FormLayout};
use crate::primitives::menu_bar::{MenuBar, MenuBarLayout};
// Only referenced (as a bare name) inside `draw_form`'s
// `target_os = "windows"` arm, which pattern-matches
// `ToolbarButton::Action`/`ToolbarButton::Label` directly — every other
// `ToolbarButton` use in this file goes through
// `crate::primitives::toolbar::measure_button`'s inferred closure
// parameter, which needs no import of its own.
use crate::primitives::message_list::MessageList;
use crate::primitives::multi_section_view::{
    MsvLayoutMetrics, MultiSectionView, MultiSectionViewLayout,
};
use crate::primitives::panel::{Panel, PanelLayout};
use crate::primitives::progress::{ProgressBar, ProgressBarLayout};
use crate::primitives::radio_group::{
    RadioGroup, RadioGroupLayout, RadioOption, RadioOptionMeasure,
};
use crate::primitives::rich_text_popup::{RichTextPopup, RichTextPopupLayout};
use crate::primitives::scrollbar::Scrollbar;
use crate::primitives::spinner::{Spinner, SpinnerLayout};
use crate::primitives::split::{Split, SplitLayout};
use crate::primitives::status_bar::{StatusBarHit, StatusBarLayout};
use crate::primitives::switch::{Switch, SwitchLayout};
#[cfg(target_os = "windows")]
use crate::primitives::toolbar::ToolbarButton;
// `TabBarHits` is `#[deprecated]` — the `Backend` trait still returns it
// alongside newer `TabBarLayout`-returning counterparts. The import needs
// the same allow every use site below does.
#[allow(deprecated)]
use crate::primitives::tab_bar::TabBarHits;
use crate::primitives::text_display::{TextDisplayLayout, TextDisplayLineMeasure};
use crate::primitives::toast::{ToastOverlay, ToastStackLayout};
use crate::primitives::tooltip::{Tooltip, TooltipLayout};
use crate::primitives::tree::TreeViewLayout;
use crate::types::WidgetId;
use crate::{
    Accelerator, AcceleratorId, ActivityBar, Key, ListView, Modifiers, Palette, StatusBar, TabBar,
    TabBarLayout, TabChrome, Terminal, TextDisplay, TooltipChrome, TreeView, UserPayload,
};
#[cfg(target_os = "windows")]
use crate::{FieldKind, Theme};
// `AcceleratorScope` is only referenced by `#[cfg(test)]` code below.
// Gate the import so a non-test build doesn't flag it as unused.
#[cfg(test)]
use crate::AcceleratorScope;

use super::services::WinPlatformServices;

// ─── Cross-platform fallback measurement ────────────────────────────────
//
// Every `draw_*`/`*_layout` method below that needs a text-width
// measurement gated on `self.dwrite` being `Some` — built once by
// `attach_surface`/`attach_headless`, both `target_os = "windows"`-only —
// and fell through to an unconditional `todo!()` otherwise. That `None`
// state isn't Windows-vs-not: it's also the state a fresh
// `WinBackend::new()` starts in (on *any* platform) and the state
// `end_frame` drops back to after a device-lost `EndDraw` failure, so a
// live Windows host hit the same panic a Linux `cargo test --features
// win` run does. `nominal_text_width`/`NominalTextMeasure` give every
// such site a plausible, finite substitute (`char_width` per character,
// no real glyph metrics) instead — real widths resume automatically once
// a surface exists.
fn nominal_text_width(text: &str, char_width: f32) -> f32 {
    text.chars().count() as f32 * char_width
}

/// [`crate::primitives::layout_metrics::TextMeasure`] impl backed by
/// [`nominal_text_width`] for `*_layout` fallbacks that need a
/// `&dyn TextMeasure` rather than a bare width.
struct NominalTextMeasure {
    char_width: f32,
}

impl crate::primitives::layout_metrics::TextMeasure for NominalTextMeasure {
    fn width_of(&self, text: &str) -> f32 {
        nominal_text_width(text, self.char_width)
    }
}

/// [`super::status_bar::StatusMeasure`] impl backed by
/// [`nominal_text_width`] — `bold` is ignored, a known gap in the
/// nominal fallback (see `super::status_bar::StatusMeasure`'s doc for why
/// bold-awareness needs its own trait).
impl super::status_bar::StatusMeasure for NominalTextMeasure {
    fn width_of(&self, text: &str, _bold: bool) -> f32 {
        nominal_text_width(text, self.char_width)
    }
}

/// [`super::spinner::SpinnerMeasureSource`] impl backed by
/// [`nominal_text_width`] for the width and a fixed `line_height` for the
/// height (`DWrite::measure_text` isn't available yet) — matches the
/// pre-#1078 `win_spinner_nominal_layout`'s behaviour exactly.
struct NominalSpinnerMeasure {
    char_width: f32,
    line_height: f32,
}

impl super::spinner::SpinnerMeasureSource for NominalSpinnerMeasure {
    fn measure(&self, text: &str) -> (f32, f32) {
        (nominal_text_width(text, self.char_width), self.line_height)
    }
}

// ─── Direct2D bootstrap ─────────────────────────────────────────────────
//
// Real WinAPI/Direct2D calls only compile where the `windows` crate
// actually has bindings, i.e. `target_os = "windows"` (see
// `Cargo.toml`'s target-specific `windows` dependency). Everywhere else
// — including a plain `cargo check --features win` on Linux — the
// `Backend` trait methods below fall back to the original `todo!()`
// stub bodies, which is what keeps this file's per-repo "every trait
// method has a WinBackend impl" compile gate (`ci.yml`'s "Compile check
// (win feature)" step) meaningful without a Windows runner.
#[cfg(target_os = "windows")]
use windows::core::Result as WinResult;
#[cfg(target_os = "windows")]
use windows::Win32::Foundation::{HWND, LPARAM, RECT, WPARAM};
#[cfg(target_os = "windows")]
use windows::Win32::Graphics::Direct2D::Common::{
    D2D1_ALPHA_MODE_UNKNOWN, D2D1_PIXEL_FORMAT, D2D_SIZE_U,
};
#[cfg(target_os = "windows")]
use windows::Win32::Graphics::Direct2D::{
    D2D1CreateFactory, ID2D1DCRenderTarget, ID2D1Factory, ID2D1HwndRenderTarget, ID2D1RenderTarget,
    D2D1_FACTORY_TYPE_SINGLE_THREADED, D2D1_HWND_RENDER_TARGET_PROPERTIES,
    D2D1_RENDER_TARGET_PROPERTIES,
};
#[cfg(target_os = "windows")]
use windows::Win32::Graphics::DirectWrite::{IDWriteFontCollection1, IDWriteFontFallback};
#[cfg(target_os = "windows")]
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_B8G8R8A8_UNORM;
// `MonitorFromWindow`/`GetMonitorInfoW`/`MONITORINFO` live under `Gdi`
// in the `windows` crate, not `WindowsAndMessaging`, though they're
// conceptually "window" APIs — already-enabled `Win32_Graphics_Gdi`
// feature (Cargo.toml), no new feature needed.
#[cfg(target_os = "windows")]
use windows::Win32::Graphics::Gdi::{
    GetMonitorInfoW, MonitorFromWindow, MONITORINFO, MONITOR_DEFAULTTONEAREST,
};
#[cfg(target_os = "windows")]
use windows::Win32::UI::HiDpi::GetDpiForWindow;
#[cfg(target_os = "windows")]
use windows::Win32::UI::WindowsAndMessaging::{
    GetClientRect, GetWindowLongPtrW, GetWindowRect, IsZoomed, LoadCursorW, PostMessageW,
    SetCursor, SetForegroundWindow, SetTimer, SetWindowLongPtrW, SetWindowPos, SetWindowTextW,
    ShowWindow, GWL_STYLE, HWND_NOTOPMOST, HWND_TOPMOST, IDC_ARROW, IDC_SIZENESW, IDC_SIZENS,
    IDC_SIZENWSE, IDC_SIZEWE, SWP_FRAMECHANGED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOSIZE,
    SWP_NOZORDER, SW_HIDE, SW_MAXIMIZE, SW_MINIMIZE, SW_RESTORE, SW_SHOW, WS_CAPTION,
    WS_OVERLAPPEDWINDOW,
};

#[cfg(target_os = "windows")]
use super::text::{new_brush_cache, BrushCache, DWrite};

/// Default editor font family for the Win-GUI backend — the historical
/// default monospace face shipped with every Windows version since Vista,
/// same role as GTK's hardcoded `"Monospace"` fontconfig alias.
#[cfg(target_os = "windows")]
const DEFAULT_EDITOR_FONT_FAMILY: &str = "Consolas";

/// Default chrome (UI) font family for the Win-GUI backend until
/// [`Backend::set_ui_font`] overrides it — the system UI font on
/// every Windows version since Vista, same role as GTK's `"Sans 11"`
/// fallback for `ui_font`.
#[cfg(target_os = "windows")]
const DEFAULT_UI_FONT_FAMILY: &str = "Segoe UI";

/// Default chrome font size in points, paired with
/// [`DEFAULT_UI_FONT_FAMILY`] — matches [`WinBackend::editor_font_size_pt`]'s
/// default.
#[cfg(target_os = "windows")]
const DEFAULT_UI_FONT_SIZE_PT: f32 = 11.0;

/// Parse a Pango-style font description (e.g. `"Segoe UI 11"`) into a
/// DirectWrite-ready `(family, size_pt)` pair. A trailing whitespace-separated
/// numeric token is the point size (defaulting to [`DEFAULT_UI_FONT_SIZE_PT`]),
/// and everything before it is a comma-separated family fallback list, taking
/// the first entry. A CSS/Pango generic token resolves to its DirectWrite
/// default; a concrete name is trusted as-is. Falls back to
/// `(DEFAULT_UI_FONT_FAMILY, DEFAULT_UI_FONT_SIZE_PT)` when `desc` has no
/// usable family at all.
#[cfg(target_os = "windows")]
fn parse_ui_font_desc(desc: &str) -> (String, f32) {
    let desc = desc.trim();
    let (family_part, size_pt) = match desc.rfind(' ') {
        Some(idx) if desc[idx + 1..].trim().parse::<f32>().is_ok() => {
            let (family, size_str) = desc.split_at(idx);
            (
                family.trim(),
                size_str
                    .trim()
                    .parse::<f32>()
                    .expect("just matched by the guard above"),
            )
        }
        _ => (desc, DEFAULT_UI_FONT_SIZE_PT),
    };
    let first = family_part
        .split(',')
        .map(str::trim)
        .find(|f| !f.is_empty());
    match first {
        None => (DEFAULT_UI_FONT_FAMILY.to_string(), DEFAULT_UI_FONT_SIZE_PT),
        Some(candidate) => match GenericFamily::parse(candidate) {
            Some(GenericFamily::Monospace) => (DEFAULT_EDITOR_FONT_FAMILY.to_string(), size_pt),
            Some(GenericFamily::SansSerif | GenericFamily::SystemUi) => {
                (DEFAULT_UI_FONT_FAMILY.to_string(), size_pt)
            }
            None => (candidate.to_string(), size_pt),
        },
    }
}

/// A live Direct2D render target: either a window-bound
/// `ID2D1HwndRenderTarget` or an offscreen `ID2D1DCRenderTarget` for
/// headless tests. Every rasteriser only needs the shared `ID2D1RenderTarget`
/// base interface — both derive from it and forward via `Deref` — so none of
/// the `&surface.target` call sites need to know which kind they're painting
/// onto. The exception is [`WinBackend::resize_surface`]'s `Resize` call,
/// which is declared only on `ID2D1HwndRenderTarget` and so matches the
/// variant directly.
#[cfg(target_os = "windows")]
enum RenderTarget {
    Hwnd(ID2D1HwndRenderTarget),
    Dc(ID2D1DCRenderTarget),
}

#[cfg(target_os = "windows")]
impl std::ops::Deref for RenderTarget {
    type Target = ID2D1RenderTarget;

    fn deref(&self) -> &ID2D1RenderTarget {
        match self {
            RenderTarget::Hwnd(target) => target,
            RenderTarget::Dc(target) => target,
        }
    }
}

/// The live Direct2D handles behind a real Win32 window, or an
/// offscreen headless surface. Only exists once
/// [`WinBackend::attach_surface`] or [`WinBackend::attach_headless`] has
/// run — a `WinBackend` constructed standalone (before either has run)
/// has `surface: None` and every draw call degrades to its no-paint
/// fallback until a later issue lands a real rasteriser.
#[cfg(target_os = "windows")]
struct Surface {
    /// Kept alive only because `ID2D1HwndRenderTarget` was created from
    /// it — never called again after `attach_surface` populates `target`.
    /// `None` for [`WinBackend::attach_headless`]: `ID2D1DCRenderTarget`
    /// keeps its own creating factory alive internally, and the caller
    /// (`super::testing::HeadlessSurface`) already owns a reference of
    /// its own, so there's no second factory to keep alive here.
    #[allow(dead_code)]
    factory: Option<ID2D1Factory>,
    target: RenderTarget,
    /// Brushes created against `target`, reused across frames.
    /// Lives and dies with this `Surface`, so a recreated target always
    /// starts from an empty cache — see `super::text`'s `Brush cache`
    /// section for how paint helpers reach it.
    brushes: BrushCache,
}

/// Position tolerance, in DIPs, for [`WinBackend::fold_double_click`]'s
/// [`DoubleClickDetector`].
///
/// `win::events`' `win_button_down` (via `super::msg::point_from_lparam`)
/// divides device pixels by the window's DPI scale before building a
/// `Point`, so `MouseDown` positions here are point-precision DIPs — not
/// TUI's whole character cells — same situation `MacBackend` documents for
/// its own `MAC_DOUBLE_CLICK_RADIUS`. The detector's default radius
/// (`crate::dispatch::DOUBLE_CLICK_RADIUS`, 1.5, tuned for TUI's integral
/// cell grid) is far tighter than two real clicks can reliably land
/// within, so this reuses the same heuristic value macOS settled on rather
/// than inventing a third unverified constant.
const WIN_DOUBLE_CLICK_RADIUS: f32 = 4.0;

/// Custom `wndproc` message posted via `PostMessageW` to wake a possibly-
/// blocked message loop from a background thread. `win::run`'s `wndproc`
/// match arm on this value drains and dispatches — see that arm's doc.
/// Applications can use `WM_APP` (`0x8000`) through `0xBFFF`; the `windows`
/// crate has no `WM_APP` constant of its own, so this is defined locally.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
pub(crate) const WM_QUADRAUI_USER_EVENT: u32 = 0x8000 + 1;

/// `NOTIFYICONDATAW::uCallbackMessage` — the message
/// `Shell_NotifyIconW`'s tray icon posts back to this app's `HWND` on
/// every mouse event over the icon (`lparam` carries the Win32 mouse
/// message: `WM_LBUTTONUP`/`WM_RBUTTONUP`/etc — see
/// `super::tray::tray_click_button`'s doc for the decode). `win::run`'s
/// `wndproc` match arm on this value is what actually decodes and
/// dispatches — see that arm's doc. Same `WM_APP`-range numbering
/// rationale as [`WM_QUADRAUI_USER_EVENT`] above, offset by one so the
/// two custom messages never collide.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
pub(crate) const WM_QUADRAUI_TRAY_CALLBACK: u32 = 0x8000 + 2;

/// `SetTimer`/`KillTimer`'s `nIDEvent` for [`WinBackend::request_frame_in`]'s
/// one-shot scheduled-wake timer — the sibling of
/// [`WM_QUADRAUI_USER_EVENT`] for a scheduled frame rather than a
/// cross-thread wake. Distinct from `win::run`'s `SMOKE_TIMER_ID` (1) and
/// `RESIZE_TIMER_ID` (2) — Win32 timer ids are scoped per-`hwnd`, and any
/// of the three can legitimately be live on the same window at once.
/// `win::run`'s `wndproc` `WM_TIMER` arm on this id is what actually
/// kills the timer and re-dispatches, mirroring `WM_QUADRAUI_USER_EVENT`'s
/// arm.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
pub(crate) const FRAME_TIMER_ID: usize = 3;

pub struct WinBackend {
    viewport: Viewport,
    /// `Rc<RefCell<>>` (not a plain field) so [`Backend::modal_stack_handle`]
    /// can hand back a handle that outlives any single `&mut self`
    /// borrow — the shape `GtkBackend`/`TuiBackend`/`MacBackend` already
    /// use for this.
    modal_stack: Rc<RefCell<ModalStack>>,
    /// See `modal_stack`'s doc comment — same rationale.
    drag_state: Rc<RefCell<DragState>>,
    /// Folds a `MouseDown` translated from `WM_LBUTTONDOWN`/`WM_RBUTTONDOWN`/
    /// etc. into `DoubleClick` when it lands within the time/position
    /// window of the previous click. `win::run`'s `wndproc`
    /// dispatches synchronously per Win32 message — same model as
    /// `macos::run` per `NSEvent` — so this runs on one event at a time
    /// via [`Self::fold_double_click`] rather than `TuiBackend`'s
    /// per-poll batch. Mirrors `MacBackend::double_click`; deliberately
    /// *not* a new `WM_*BUTTONDBLCLK` translator — see that issue for why.
    double_click: DoubleClickDetector,
    /// Accelerator registry + text-selection bookkeeping — see
    /// [`crate::backend_core::BackendCore`]'s module doc. Replaces the
    /// formerly Win-local `accelerators`/`parsed_accelerators` fields
    /// verbatim, plus (below) the formerly separate `text_selection`
    /// field.
    core: crate::backend_core::BackendCore,
    /// `WidgetId` of the [`ActivityBar`] that declared
    /// `is_keyboard_focused = true` during the most recent
    /// [`Backend::draw_activity_bar`] call, or `None` if no bar is focused.
    /// Read by `win::run::dispatch_event` to redirect a `KeyPressed` into
    /// `UiEvent::ActivityBar(...)` instead of reaching `AppLogic::handle`
    /// as a raw key — the Win-GUI twin of `GtkBackend`/`MacBackend`'s
    /// `focused_activity_bar`. Without it, `ShellAdapter`'s activity-bar
    /// keyboard navigation is unreachable on this backend.
    focused_activity_bar: Option<WidgetId>,
    /// Queue-adapter between event producers and the trait's poll-style
    /// [`Backend::poll_events`]/[`Backend::wait_events`] — the
    /// `docs/BACKEND.md` "option A event queue" shape, same
    /// `Rc<RefCell<VecDeque<UiEvent>>>` field GTK/macOS ship
    /// (`GtkBackend::events`/`MacBackend::events`). `Rc<RefCell<>>` (not a
    /// plain field) so a producer holding only an [`Self::events_handle`]
    /// clone — a future `wndproc` wiring, or a test via [`Self::push_event`]
    /// — can push without a `&mut WinBackend` borrow. Not `target_os`-gated:
    /// the queue itself is plain `VecDeque<UiEvent>` with no WinAPI
    /// dependency, same rationale as `current_pointer_shape` above — only a
    /// real Win32 producer wiring this queue to `wndproc`'s live message
    /// pump would need a real host, and nothing does that yet (see
    /// `win::run`'s "Dispatch model" module doc: the live message loop
    /// still dispatches directly to `AppLogic::handle`, mirroring GTK's own
    /// "ships the API but producer wiring is separate work" posture).
    events: Rc<RefCell<VecDeque<UiEvent>>>,
    services: WinPlatformServices,
    current_line_height: f32,
    current_char_width: f32,
    /// Editor vertical scrollbar column width set through
    /// [`Backend::set_editor_v_scrollbar_width`]; `None` = one
    /// `current_char_width` wide.
    editor_v_scrollbar_w: Option<f32>,
    /// [`crate::backend::Backend::minimap_scale`]'s backing field — read by
    /// [`Backend::draw_minimap`]/[`Backend::minimap_layout`] to resolve the
    /// row pitch and per-column width. Defaults to
    /// [`crate::primitives::minimap::MinimapScale::One`], so a host that
    /// never calls [`Backend::set_minimap_scale`] sees no behaviour change.
    /// Not `target_os`-gated: `MinimapScale` has no WinAPI dependency.
    minimap_scale: crate::primitives::minimap::MinimapScale,
    /// DPI ratio (`GetDpiForWindow(hwnd) / 96.0`). Mirrored into
    /// `viewport.scale` on every attach/resize/`WM_DPICHANGED` so
    /// `Backend::viewport()` and this field never drift. Kept as its own
    /// field (rather than always re-deriving from `viewport.scale`)
    /// because `WM_DPICHANGED` updates it independently of a resize.
    /// `cfg`-gated like `surface` below — nothing outside the
    /// `target_os = "windows"` methods reads or writes it, so on every
    /// other host it would otherwise be dead code.
    #[cfg(target_os = "windows")]
    dpi_scale: f32,
    #[cfg(target_os = "windows")]
    surface: Option<Surface>,
    /// The `ID2D1DCRenderTarget` [`Self::attach_headless`] was given,
    /// kept alongside (not inside) `surface` so [`Self::ensure_surface`]
    /// can rebuild `surface` after `end_frame`'s device-lost recovery
    /// drops it — mirroring `hwnd` below, which does the same job for a
    /// real window. `None` for a `WinBackend` that never called
    /// `attach_headless` (every live app, `attach_surface`'s `hwnd`
    /// path) — cloning an `ID2D1DCRenderTarget` is a cheap COM `AddRef`,
    /// same rationale as `Surface`'s own `factory: None` comment for why
    /// this needs no separate factory to keep alive.
    #[cfg(target_os = "windows")]
    headless_target: Option<ID2D1DCRenderTarget>,
    /// The last `HWND` a surface was successfully attached to, kept
    /// *outside* `Surface` (and outlasting it) so a dropped surface
    /// (`end_frame`'s device-lost recovery) can still be re-created by
    /// [`Self::ensure_surface`] without needing `win::run` to thread the
    /// `HWND` back through a second time. `None` until the first
    /// `attach_surface` call succeeds.
    #[cfg(target_os = "windows")]
    hwnd: Option<HWND>,
    /// Tray/status-bar icon state — see [`super::tray`]'s
    /// module doc and `impl TrayService for WinBackend` below.
    #[cfg(target_os = "windows")]
    tray: super::tray::WinTrayState,
    /// Window rect + `GWL_STYLE` value saved when entering fullscreen, so
    /// exiting can restore both — Win-GUI's fullscreen is a manual
    /// `WS_OVERLAPPEDWINDOW` style strip + `SetWindowPos` to the monitor
    /// rect, not a single reversible OS call the way GTK or AppKit provide.
    /// `None` outside fullscreen.
    #[cfg(target_os = "windows")]
    fullscreen_saved: Option<(RECT, isize)>,
    /// Live, thread-safe mirror of `hwnd`'s raw handle value, read fresh on
    /// every invocation of the [`Self::waker`] closure. `HWND` itself isn't
    /// `Send`, so it can't be captured directly into the `Send + Sync`
    /// closure — but `waker()` is callable during `AppLogic::setup`, *before*
    /// [`Self::attach_surface`] has run. A closure capturing `self.hwnd`
    /// as a one-time snapshot would permanently bake in "no window", silently
    /// dropping every future wake nudge since a live `GetMessageW` loop
    /// blocks indefinitely with no other way to notice a queued payload.
    /// An `AtomicIsize` shared between `self` and the closure lets the
    /// closure re-read the *current* value at invocation time, mirroring the
    /// live-lookup pattern `GtkBackend::waker` and `MacBackend::waker` use.
    /// `0` means "no window yet", mirroring `hwnd`'s own `None` — a real
    /// `HWND` is never null.
    #[cfg(target_os = "windows")]
    hwnd_raw: std::sync::Arc<std::sync::atomic::AtomicIsize>,
    /// DirectWrite factory + `IDWriteTextFormat` for the current editor
    /// font (`editor_font_family`/`editor_font_size_pt`). `None` until
    /// [`Self::attach_surface`] creates it — same lifecycle as `surface`,
    /// and recreated alongside it whenever [`Self::ensure_surface`]'s
    /// device-lost recovery re-attaches.
    #[cfg(target_os = "windows")]
    dwrite: Option<DWrite>,
    /// Font family used to paint text via DirectWrite. Defaults to
    /// [`DEFAULT_EDITOR_FONT_FAMILY`]. Set via [`Backend::set_editor_font`];
    /// read when constructing the `IDWriteTextFormat` — mirrors GTK's
    /// `editor_font_family`. `cfg`-gated like `dwrite`.
    #[cfg(target_os = "windows")]
    editor_font_family: String,
    /// Editor font size in points, paired with `editor_font_family`.
    /// Defaults to `11.0`, matching GTK's default.
    #[cfg(target_os = "windows")]
    editor_font_size_pt: f32,
    /// DirectWrite factory + `IDWriteTextFormat` for the current chrome
    /// (UI) font (`ui_font_family`/`ui_font_size_pt`) — the chrome twin
    /// of `dwrite` above. `None` until [`Self::attach_surface`] creates
    /// it; recreated alongside it the same way. Read via
    /// [`Self::chrome_dwrite`]; `Dialog` and every other
    /// `ChromePrimitive` rasteriser (`Tree`, `List`, `MenuBar`,
    /// `ContextMenu`, `CommandCenter`, `MultiSectionView`,
    /// `SidebarPanel`, `StatusBar`, `ActivityBar`, `Toolbar`, `TabBar`)
    /// paint chrome text through this handle, falling back to the
    /// editor `dwrite` handle if no live chrome one exists yet —
    /// matching GTK's `ui_font` swap and macOS's `chrome_font`.
    /// `RichTextPopup` paints through this handle too, but only for
    /// [`crate::FontRole::Chrome`] (the default, via plain
    /// `draw_rich_text_popup`) — a caller that asks for
    /// [`crate::FontRole::Editor`] via
    /// `Backend::draw_rich_text_popup_with_font_role` is routed to the
    /// editor `dwrite` handle instead.
    #[cfg(target_os = "windows")]
    chrome_dwrite: Option<DWrite>,
    /// Chrome font family, parsed from the Pango-style description
    /// [`Backend::set_ui_font`] receives via [`parse_ui_font_desc`].
    /// Defaults to [`DEFAULT_UI_FONT_FAMILY`]. `cfg`-gated like
    /// `editor_font_family`: nothing outside the `target_os = "windows"`
    /// methods reads or writes it.
    #[cfg(target_os = "windows")]
    ui_font_family: String,
    /// Chrome font size in points, paired with `ui_font_family`. Defaults
    /// to [`DEFAULT_UI_FONT_SIZE_PT`].
    #[cfg(target_os = "windows")]
    ui_font_size_pt: f32,
    /// Live font fallback built by [`Backend::set_nerd_font_fallback`]
    /// — `None` until that method is called. Read by
    /// [`Self::attach_surface`]/[`Self::attach_headless`] when they build
    /// [`DWrite`] for the editor/chrome fonts, so a `set_nerd_font_fallback`
    /// call made before either (the documented "call once from `setup()`"
    /// convention every font setter on this backend shares) is baked into
    /// both `IDWriteTextFormat`s at construction. Like `editor_font_family`
    /// above, a live surface does not rebuild immediately on a later
    /// change — same accepted limitation `set_editor_font`'s doc already
    /// names.
    #[cfg(target_os = "windows")]
    nerd_font_fallback: Option<IDWriteFontFallback>,
    /// Private font collection built by the most recent
    /// [`Backend::register_font_from_memory`] call, if any — passed to
    /// [`crate::win::text::build_nerd_font_fallback`] so a later
    /// `set_nerd_font_fallback(family)` resolves `family` against the
    /// font this process actually registered rather than a same-named
    /// system font. Only the most recent registration is
    /// kept: nothing in this backend's contract promises more than one
    /// app-registered font resolves at a time, mirroring
    /// `MacBackend`/vimcode's own single-subset-font usage.
    #[cfg(target_os = "windows")]
    registered_font_collection: Option<IDWriteFontCollection1>,
    /// Private font collection for the bundled codicon font, built once
    /// by [`Self::new`] via [`crate::win::text::register_font_from_memory`] —
    /// kept separate from `registered_font_collection`,
    /// which is reserved for the app's own
    /// [`Backend::register_font_from_memory`] calls and is overwritten
    /// by each one; this field must survive those calls so
    /// [`Self::nerd_font_fallback`] can always resolve the codicon
    /// family regardless of what the app has registered since. No
    /// equivalent to `registered_font_bytes`'s owned-copy dance is
    /// needed: [`crate::codicon::FONT_BYTES`] is `'static` (compiled
    /// into the binary's own data section), so it already outlives
    /// every `IDWriteFontFile`/collection/fallback built from it for the
    /// rest of the process.
    #[cfg(target_os = "windows")]
    codicon_font_collection: Option<IDWriteFontCollection1>,
    /// Every byte buffer ever handed to a
    /// [`Backend::register_font_from_memory`] call, in an owned copy
    /// that is **appended** here and never overwritten or dropped for
    /// the rest of the process's lifetime.
    ///
    /// This is not a cosmetic cache: `IDWriteInMemoryFontFileLoader::
    /// CreateInMemoryFontFileReference` (`win::text::register_font_from_memory`)
    /// does **not** copy the `fontData` it's given — the memory it
    /// points at must stay valid for as long as the `IDWriteFontFile` it
    /// returns, and everything built from that file (the private
    /// collection, any `IDWriteFontFallback` built against it, any live
    /// `IDWriteTextFormat`/`IDWriteTextLayout` that resolves through
    /// that fallback), remains alive — and DirectWrite gives this
    /// backend no callback for when that chain is actually done with
    /// the pointer (the API's `ownerObject` parameter exists precisely
    /// to supply one, but this backend passes `None` for it — see
    /// `register_font_from_memory`'s doc below).
    ///
    /// Rather than implement a custom `IUnknown` just to receive that
    /// signal, this field sidesteps the problem: nothing is ever freed.
    /// Each [`Backend::register_font_from_memory`] call's bytes are
    /// copied into a fresh `Vec` and pushed here *before* DirectWrite
    /// ever sees a pointer into it (never the caller's original `bytes`
    /// slice, which the trait's own doc explicitly allows to be a local
    /// dropped immediately after the call returns), and the entry is
    /// kept even if a later call replaces
    /// `registered_font_collection` — matching the "left registered for
    /// the process lifetime" posture `register_font_from_memory`
    /// already documents for the font-file loader itself.
    #[cfg(target_os = "windows")]
    registered_font_bytes: Vec<Vec<u8>>,
    /// The active [`crate::Theme`], set via [`Backend::set_theme`] and
    /// read by every `draw_*` rasteriser. Not `cfg`-gated: `Theme` is a plain,
    /// portable value with no WinAPI dependency — same rationale as
    /// `current_pointer_shape` — so this stays testable on every host.
    current_theme: crate::theme::Theme,
    /// Captured once per frame, mirroring `current_theme` — see
    /// [`crate::Style`]'s module doc for why this is a separate field
    /// rather than folded into `Theme`.
    current_style: crate::Style,
    /// The `PointerShape` [`Backend::set_cursor`] last applied — read back
    /// by `win::run`'s `WM_SETCURSOR` handler so the pointer glyph
    /// stays put across every `WM_SETCURSOR` Windows sends for the
    /// client area (on every mouse move, not just the ones that also
    /// deliver `WM_MOUSEMOVE`), instead of snapping back to the window
    /// class's `IDC_ARROW` the instant `DefWindowProcW` would otherwise
    /// handle it. Not `cfg`-gated like `surface`/`dwrite` above: the enum
    /// itself is a plain, portable value with no WinAPI dependency, and
    /// [`Backend::set_cursor`] (below) always records it regardless of
    /// host — only *applying* it via `SetCursor` is Windows-only.
    current_pointer_shape: PointerShape,
    /// Whether [`Self::begin_frame`]/[`Self::end_frame`] should bracket
    /// the frame in the shared paint-time text-run recording sink
    /// (`crate::testing::install_text_run_sink`/`take_text_run_sink`) and
    /// drain it into [`Self::text_runs`] — mirrors
    /// `GtkBackend::painted_text_recording` / `MacBackend::painted_text_recording`.
    /// Off by default: a live app never reads `text_runs`, and recording
    /// every run would allocate a `String` per painted text run per
    /// frame. [`super::testing::WinDriver`] turns it on.
    /// Not `target_os`-gated: the flag itself is a plain `bool` with no
    /// WinAPI dependency, only the paint calls that would ever populate
    /// anything are.
    painted_text_recording: bool,
    /// Text runs recorded during the last frame, when
    /// `painted_text_recording` is on — the `WinDriver::find`/`find_bounds`
    /// /`inventory`/`screen_has` backing store. Populated
    /// by draining the shared sink at the end of [`Self::end_frame`];
    /// mirrors `MacBackend::text_runs`'s lifecycle. Not `target_os`-gated
    /// for the same reason as `painted_text_recording` above.
    text_runs: Vec<crate::testing::TextRun>,
    /// Mirrors `TuiBackend::nerd_fonts_enabled` / `GtkBackend::nerd_fonts_enabled`
    /// / `MacBackend::nerd_fonts_enabled`. Picks `Icon::glyph` vs `Icon::fallback`
    /// in `draw_tree`. Set via [`Backend::set_nerd_fonts`]; defaults to `true`
    /// on this backend. Not `target_os`-gated: the flag itself has no WinAPI
    /// dependency, same rationale as `current_pointer_shape` — only the
    /// DirectWrite paint call that reads it needs a real host.
    nerd_fonts_enabled: bool,
    /// The most recent [`BackendError`] recorded by `end_frame`, drained and
    /// cleared by [`Backend::last_error`]. Not `target_os`-gated: the field
    /// itself has no WinAPI dependency, same rationale as `current_pointer_shape`
    /// — only the `EndDraw` call that would populate it needs a real host.
    last_error: Option<BackendError>,
    /// Single owner of keyboard focus — see
    /// [`crate::focus`]'s module doc. Mutated only by the shared
    /// Tab/Shift+Tab intercept in [`crate::runtime::preprocess_event`]
    /// via [`crate::runtime::PreprocessBackend::focus_manager_mut`];
    /// read elsewhere via [`Backend::focus_manager`].
    focus: crate::focus::FocusManager,
    /// Thread-safe inbox for [`crate::UiEvent::User`] payloads — see
    /// [`crate::runtime::UserEventQueue`]'s doc. Not `target_os`-gated: the
    /// queue has no WinAPI dependency, same rationale as `events` above; only
    /// [`Self::waker`]'s `PostMessageW` nudge needs a real host.
    user_events: std::sync::Arc<crate::runtime::UserEventQueue>,
    /// Zones registered this frame via [`Backend::register_zone`] —
    /// `WinBackend`'s twin of `GtkBackend::zones`/`MacBackend::zones`.
    /// Cleared at the start of every frame by [`Self::begin_frame`], same
    /// lifecycle as `GtkBackend::zones`. Not `target_os`-gated: the zone list
    /// is a plain `Vec` with no WinAPI dependency. `pub(crate)` so
    /// [`super::testing::WinDriver::inventory`] can read it back.
    pub(crate) zones: Vec<crate::testing::ZoneRec>,
    /// Test-facing [`Backend::request_frame_in`] call-count/deadline
    /// bookkeeping, mirroring
    /// [`crate::tui::TuiBackend`]'s own `frame_scheduler` field — see
    /// [`crate::runtime::FrameScheduler`]'s doc for why Windows, which
    /// already has a real native timer (`SetTimer`/`WM_TIMER`, armed
    /// directly from [`Self::request_frame_in`]), still needs this: that
    /// real timer is a no-op before [`Self::attach_surface`] has ever
    /// run (no `HWND` yet), which is exactly the state a headless
    /// [`super::testing::WinDriver`] test runs in. `request_frame_in`
    /// records into this unconditionally, `hwnd` or not; read back via
    /// [`Self::frame_requests`]/[`Self::pending_frame_delay`]. Not
    /// `target_os`-gated: a plain value with no WinAPI dependency, same
    /// rationale as `zones`/`user_events` above.
    frame_scheduler: crate::runtime::FrameScheduler,
    /// Backend-neutral caret-blink phase for `MultiSectionView` aux-row
    /// text inputs (`SectionAux::Input`/`Search`) — see
    /// [`crate::caret_blink`]'s module doc for the state machine and the
    /// Windows-specific wiring it prescribes. `super::run`'s
    /// `CARET_BLINK_TIMER_ID` timer, armed once at startup, ticks this
    /// every [`crate::caret_blink::CaretBlinkState::period`] via
    /// `WM_TIMER` and invalidates the window when the phase flips;
    /// `super::run::dispatch_event` calls [`Self::note_caret_activity`]
    /// on `KeyPressed`/`CharTyped` so the caret holds solid while typing,
    /// mirroring `MacBackend`'s `caret_visible`/`paused_until` cells and
    /// `GtkBackend::caret_blink`. Not `target_os`-gated: a plain value
    /// with no WinAPI dependency, same rationale as `zones`/`user_events`
    /// above.
    caret_blink: crate::caret_blink::CaretBlinkState,
}

impl WinBackend {
    pub fn new() -> Self {
        // Self-register the bundled codicon font and seed a
        // codicon-only `nerd_font_fallback` before anything paints —
        // mirrors `crate::gtk::app_font::ensure_codicon_registered`'s
        // "degrade, don't fail" posture: a registration failure just
        // leaves both locals `None`, so the worst case is a missing
        // codicon falling through to tofu rather than this constructor
        // failing outright. Real `IDWriteFactory`/
        // `IDWriteInMemoryFontFileLoader` calls, so this can only run
        // for real on `target_os = "windows"`; elsewhere (`cargo check
        // --features win` on Linux) this whole block is compiled out,
        // matching every other real WinAPI call in this constructor.
        #[cfg(target_os = "windows")]
        let (codicon_font_collection, nerd_font_fallback) =
            match crate::win::text::register_font_from_memory(crate::codicon::FONT_BYTES) {
                Ok((collection, _names)) => {
                    let fallback = crate::win::text::build_nerd_font_fallback_multi(&[(
                        crate::codicon::FONT_FAMILY,
                        Some(&collection),
                    )])
                    .ok();
                    (Some(collection), fallback)
                }
                Err(_) => (None, None),
            };

        Self {
            viewport: Viewport::new(0.0, 0.0, 1.0),
            modal_stack: Rc::new(RefCell::new(ModalStack::new())),
            drag_state: Rc::new(RefCell::new(DragState::new())),
            double_click: DoubleClickDetector::with_radius(WIN_DOUBLE_CLICK_RADIUS),
            core: crate::backend_core::BackendCore::default(),
            focused_activity_bar: None,
            events: Rc::new(RefCell::new(VecDeque::new())),
            services: WinPlatformServices::new(),
            current_line_height: 16.0,
            current_char_width: 8.0,
            editor_v_scrollbar_w: None,
            minimap_scale: crate::primitives::minimap::MinimapScale::default(),
            #[cfg(target_os = "windows")]
            dpi_scale: 1.0,
            #[cfg(target_os = "windows")]
            surface: None,
            #[cfg(target_os = "windows")]
            headless_target: None,
            #[cfg(target_os = "windows")]
            hwnd: None,
            #[cfg(target_os = "windows")]
            tray: super::tray::WinTrayState::default(),
            #[cfg(target_os = "windows")]
            fullscreen_saved: None,
            #[cfg(target_os = "windows")]
            hwnd_raw: std::sync::Arc::new(std::sync::atomic::AtomicIsize::new(0)),
            #[cfg(target_os = "windows")]
            dwrite: None,
            #[cfg(target_os = "windows")]
            editor_font_family: DEFAULT_EDITOR_FONT_FAMILY.to_string(),
            #[cfg(target_os = "windows")]
            editor_font_size_pt: 11.0,
            #[cfg(target_os = "windows")]
            chrome_dwrite: None,
            #[cfg(target_os = "windows")]
            ui_font_family: DEFAULT_UI_FONT_FAMILY.to_string(),
            #[cfg(target_os = "windows")]
            ui_font_size_pt: DEFAULT_UI_FONT_SIZE_PT,
            #[cfg(target_os = "windows")]
            nerd_font_fallback,
            #[cfg(target_os = "windows")]
            registered_font_collection: None,
            #[cfg(target_os = "windows")]
            codicon_font_collection,
            #[cfg(target_os = "windows")]
            registered_font_bytes: Vec::new(),
            current_theme: crate::theme::Theme::default(),
            current_style: crate::Style::default(),
            current_pointer_shape: PointerShape::Default,
            painted_text_recording: false,
            text_runs: Vec::new(),
            nerd_fonts_enabled: true,
            last_error: None,
            focus: crate::focus::FocusManager::new(),
            user_events: crate::runtime::UserEventQueue::new(),
            zones: Vec::new(),
            frame_scheduler: crate::runtime::FrameScheduler::new(),
            caret_blink: crate::caret_blink::CaretBlinkState::default(),
        }
    }

    /// Drain pending [`crate::UiEvent::User`] payloads — the same
    /// [`Self::user_events`] queue [`Backend::poll_events`] folds in,
    /// exposed standalone so `win::run`'s `WM_QUADRAUI_USER_EVENT` handler
    /// can drain-and-dispatch directly without going through
    /// the otherwise-vestigial `poll_events`/`wait_events` pair (see that
    /// pair's doc for why the live `wndproc` doesn't normally call them).
    ///
    /// Only called from `wndproc`, which is entirely
    /// `#[cfg(target_os = "windows")]`-gated — see [`WM_QUADRAUI_USER_EVENT`]'s
    /// doc for why that reads as dead code on a non-Windows `cargo check`
    /// and isn't.
    #[cfg_attr(not(target_os = "windows"), allow(dead_code))]
    pub(crate) fn drain_user_events(&mut self) -> Vec<UiEvent> {
        let mut out = Vec::new();
        self.user_events.drain_into(&mut out);
        out
    }

    /// Update the cached DirectWrite line height (in DIPs). Mirrors
    /// `GtkBackend::set_current_line_height` — normally set once by
    /// [`Self::attach_surface`] from real font metrics, but exposed
    /// publicly (like GTK's) so tests and callers can override it
    /// directly.
    pub fn set_current_line_height(&mut self, line_height: f32) {
        self.current_line_height = line_height;
    }

    /// Update the cached DirectWrite approximate-char-width (in DIPs).
    /// Mirrors `GtkBackend::set_current_char_width`.
    pub fn set_current_char_width(&mut self, char_width: f32) {
        self.current_char_width = char_width;
    }

    /// Update the cached theme. Ergonomic concrete-type sibling of
    /// [`Backend::set_theme`] — mirrors `GtkBackend::set_current_theme`
    pub fn set_current_theme(&mut self, theme: crate::theme::Theme) {
        self.current_theme = theme;
    }

    /// Read-only accessor for the cached theme. Mirrors
    /// `GtkBackend::current_theme`.
    pub fn current_theme(&self) -> &crate::theme::Theme {
        &self.current_theme
    }

    /// Update the cached style. Mirrors [`Self::set_current_theme`] —
    /// see [`crate::Style`]'s module doc.
    pub fn set_current_style(&mut self, style: crate::Style) {
        self.current_style = style;
    }

    /// Read-only accessor for the cached style. Mirrors
    /// [`Self::current_theme`].
    pub fn current_style(&self) -> &crate::Style {
        &self.current_style
    }

    /// Live DirectWrite handles for the current chrome (UI) font, once
    /// [`Self::attach_surface`]/[`Self::attach_headless`] has built them —
    /// `None` beforehand, same lifecycle as the editor `dwrite` field.
    /// See `chrome_dwrite`'s field doc for the full list of `draw_*`
    /// rasterisers that consume this.
    ///
    /// All 13 `ChromePrimitive`s (`crate::font_role`) paint through this
    /// handle, matching GTK's `ui_font` swap and macOS's `chrome_font`.
    #[cfg(target_os = "windows")]
    pub fn chrome_dwrite(&self) -> Option<&DWrite> {
        self.chrome_dwrite.as_ref()
    }

    /// Create a single-threaded `ID2D1Factory` and an `ID2D1HwndRenderTarget`
    /// sized to `hwnd`'s current client rect, and store both on `self`.
    /// Also seeds [`Backend::viewport`][crate::backend::Backend::viewport]
    /// with the window's real pixel size and DPI scale.
    #[cfg(target_os = "windows")]
    pub(crate) fn attach_surface(&mut self, hwnd: HWND) -> WinResult<()> {
        let factory: ID2D1Factory =
            // SAFETY: `D2D1CreateFactory` takes a plain enum and an
            // `Option<*const D2D1_FACTORY_OPTIONS>`; `None` is the
            // documented "use defaults" sentinel, not a dereferenced
            // pointer.
            unsafe { D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, None)? };

        let mut rect = RECT::default();
        // SAFETY: `hwnd` is the caller's live window (this is called once,
        // right after `CreateWindowExW` succeeds — see this function's
        // doc); `rect` is stack-local and outlives the call.
        unsafe { GetClientRect(hwnd, &mut rect)? };
        let width = (rect.right - rect.left).max(1) as u32;
        let height = (rect.bottom - rect.top).max(1) as u32;

        let render_props = D2D1_RENDER_TARGET_PROPERTIES {
            pixelFormat: D2D1_PIXEL_FORMAT {
                format: DXGI_FORMAT_B8G8R8A8_UNORM,
                alphaMode: D2D1_ALPHA_MODE_UNKNOWN,
            },
            ..Default::default()
        };
        let hwnd_props = D2D1_HWND_RENDER_TARGET_PROPERTIES {
            hwnd,
            pixelSize: D2D_SIZE_U { width, height },
            ..Default::default()
        };
        // SAFETY: `render_props`/`hwnd_props` are stack-local structs read
        // synchronously by this call; `hwnd_props.hwnd` is the same live
        // `hwnd` this function was called with.
        let target = unsafe { factory.CreateHwndRenderTarget(&render_props, &hwnd_props)? };

        self.dpi_scale = dpi_scale_for_window(hwnd);
        self.viewport = Viewport::new(width as f32, height as f32, self.dpi_scale);
        self.surface = Some(Surface {
            factory: Some(factory),
            target: RenderTarget::Hwnd(target),
            brushes: new_brush_cache(),
        });
        self.hwnd = Some(hwnd);
        // Keep the waker's live mirror in sync — see `Self::hwnd_raw`'s doc
        // for why this can't just be read off `self.hwnd` from inside the closure.
        self.hwnd_raw
            .store(hwnd.0 as isize, std::sync::atomic::Ordering::Release);
        // Give `WinPlatformServices` the live window so file dialogs
        // open parented to it and notifications have an owning `HWND` —
        // mirrors `GtkBackend::set_window` calling
        // `GtkPlatformServices::set_window` right after its own window is
        // constructed.
        self.services.set_window(hwnd);

        // DirectWrite bootstrap: build the factory + text format for
        // the currently-configured editor font and seed `line_height()` /
        // `char_width()` from its real font metrics, same role as
        // `gtk::run::render_frame`'s per-frame Pango metrics resolve —
        // except here it only needs to happen once per surface, since
        // DirectWrite text formats aren't tied to the Direct2D device the
        // way the render target is.
        let (dwrite, line_height, char_width) = DWrite::new(
            &self.editor_font_family,
            self.editor_font_size_pt,
            self.nerd_font_fallback.as_ref(),
        )?;
        self.dwrite = Some(dwrite);
        self.current_line_height = line_height;
        self.current_char_width = char_width;

        // Chrome (UI) font bootstrap — same DirectWrite dance as
        // the editor font above, but for `ui_font_family`/`ui_font_size_pt`.
        // `line_height`/`char_width` from this format aren't needed:
        // those are always resolved from the editor font, so they're
        // discarded here rather than overwriting `self.current_line_height`.
        let (chrome_dwrite, _, _) = DWrite::new(
            &self.ui_font_family,
            self.ui_font_size_pt,
            self.nerd_font_fallback.as_ref(),
        )?;
        self.chrome_dwrite = Some(chrome_dwrite);

        Ok(())
    }

    /// Attach an offscreen `ID2D1DCRenderTarget` instead of a live
    /// window's — the headless twin of [`Self::attach_surface`],
    /// used only by [`super::testing::driver_with_shell`] /
    /// [`super::testing::WinDriver`] so a `WinBackend`'s already-landed
    /// rasterisers can paint somewhere a test can read pixels
    /// back from, without a live `HWND`.
    ///
    /// `target` is expected to be [`super::testing::HeadlessSurface::target`]
    /// cloned (a cheap `AddRef` — Direct2D COM interfaces are reference
    /// counted, and `HeadlessSurface` keeps the authoritative reference
    /// plus the backing DIB section alive for as long as it lives). This
    /// method deliberately skips everything HWND-specific that
    /// [`Self::attach_surface`] does: `GetClientRect`,
    /// `dpi_scale_for_window`, and `WinPlatformServices::set_window`.
    /// `self.hwnd` stays `None`, so [`Self::ensure_surface`]'s
    /// device-lost recovery (which only knows how to reattach to a
    /// `hwnd`) correctly stays a no-op for a headless surface — a
    /// `HeadlessSurface` doesn't hit device loss the way a live
    /// compositor can.
    #[cfg(target_os = "windows")]
    pub(crate) fn attach_headless(
        &mut self,
        target: ID2D1DCRenderTarget,
        width: u32,
        height: u32,
    ) -> WinResult<()> {
        self.dpi_scale = 1.0;
        self.viewport = Viewport::new(width as f32, height as f32, self.dpi_scale);
        // Keep a second clone around (cheap COM `AddRef`) so
        // `ensure_surface` can rebuild `surface` after `end_frame`'s
        // device-lost recovery drops it, even though headless mode has
        // no `hwnd` to reattach through — see the
        // `headless_target` field doc.
        self.headless_target = Some(target.clone());
        self.surface = Some(Surface {
            factory: None,
            target: RenderTarget::Dc(target),
            brushes: new_brush_cache(),
        });

        // Same DirectWrite bootstrap as `attach_surface` — text formats
        // aren't tied to which kind of render target they paint onto.
        let (dwrite, line_height, char_width) = DWrite::new(
            &self.editor_font_family,
            self.editor_font_size_pt,
            self.nerd_font_fallback.as_ref(),
        )?;
        self.dwrite = Some(dwrite);
        self.current_line_height = line_height;
        self.current_char_width = char_width;

        // Chrome (UI) font bootstrap — see `attach_surface`'s comment.
        let (chrome_dwrite, _, _) = DWrite::new(
            &self.ui_font_family,
            self.ui_font_size_pt,
            self.nerd_font_fallback.as_ref(),
        )?;
        self.chrome_dwrite = Some(chrome_dwrite);

        Ok(())
    }

    /// `(width, height)` DIPs of `text` measured against the current
    /// editor font. Returns `(0.0, 0.0)` if no surface has attached yet.
    #[cfg(target_os = "windows")]
    pub fn measure_text(&self, text: &str) -> (f32, f32) {
        self.dwrite
            .as_ref()
            .and_then(|d| d.measure_text(text).ok())
            .unwrap_or((0.0, 0.0))
    }

    /// Paint `text` inside `rect` (DIPs) in `color` onto the live render
    /// target. No-op if no surface/DirectWrite handle is attached yet.
    #[cfg(target_os = "windows")]
    pub fn draw_text(&self, text: &str, rect: Rect, color: crate::Color) {
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            let _ = dwrite.draw_text(&surface.target, text, rect, color);
        }
    }

    /// Re-create the render target after a prior `EndDraw` failure
    /// dropped it — the actual implementation of the recovery path
    /// [`Backend::end_frame`]'s docs promise. `win::run` calls this from
    /// its `WM_PAINT` and `WM_SIZE` handlers before touching the surface,
    /// so a lost surface comes back on the next paint or resize instead
    /// of leaving the window permanently blank.
    ///
    /// A no-op returning `Ok(())` if a surface is already live, and a
    /// no-op returning `Ok(())` if neither a window nor a headless target
    /// has ever attached one yet (nothing to recover to — covers the
    /// synchronous `WM_SIZE` Windows fires from inside `CreateWindowExW`,
    /// before `run_inner` has a `HWND` to attach at all).
    ///
    /// Headless surfaces ([`Self::attach_headless`], `WinDriver`) recover
    /// through `headless_target` instead of `hwnd`: before
    /// this, a headless surface dropped by `end_frame`'s device-lost path
    /// stayed `None` forever, since `hwnd` is never set in headless mode
    /// — the exact gap that made this method's recovery unreachable from
    /// a test. Checked first because it's the cheaper, more specific
    /// case; a `WinBackend` only ever has one of the two attached at a
    /// time.
    #[cfg(target_os = "windows")]
    pub(crate) fn ensure_surface(&mut self) -> WinResult<()> {
        if self.surface.is_some() {
            return Ok(());
        }
        if let Some(target) = self.headless_target.clone() {
            self.surface = Some(Surface {
                factory: None,
                target: RenderTarget::Dc(target),
                brushes: new_brush_cache(),
            });
            return Ok(());
        }
        match self.hwnd {
            Some(hwnd) => self.attach_surface(hwnd),
            None => Ok(()),
        }
    }

    /// Test-only hook: force `self.surface` back to the
    /// "not attached" state a genuine `EndDraw` failure (device lost /
    /// `D2DERR_RECREATE_TARGET`) leaves it in — see [`Self::end_frame`]'s
    /// doc — without needing a real Direct2D error to get there.
    ///
    /// `self.surface`/`self.hwnd`/`self.headless_target` are all private
    /// to this module, so nothing outside it — including
    /// `super::testing::WinDriver`, the one place a downstream crate can
    /// reach a `WinBackend` at all — can reproduce this state directly.
    /// [`super::testing::WinDriver::drop_surface`] is this method's only
    /// caller, and exists to close exactly that gap: before it, the only
    /// way any test (in-crate or down) could observe
    /// [`Backend::draw_minimap`]'s (or any other `draw_*`'s)
    /// `painted: false` fallback was to never attach a surface in the
    /// first place (`draw_minimap_with_no_surface_reports_unpainted_and_agrees_with_minimap_layout`,
    /// below) — proving the fallback on a backend that *had* a surface
    /// and then lost it (the actual, narrower reported bug) was
    /// impossible from outside this file. `self.hwnd`/`self.headless_target`
    /// are left untouched, same as the real `EndDraw`-failure path in
    /// [`Self::end_frame`], so [`Self::ensure_surface`] (called by every
    /// production `WM_PAINT`/`WM_SIZE` handler, and by
    /// [`super::testing::WinDriver::render`] before every frame) still
    /// recreates it on the next call, exactly like the real failure this
    /// simulates.
    #[cfg(target_os = "windows")]
    pub(crate) fn drop_surface_for_testing(&mut self) {
        self.surface = None;
    }

    /// Resize the live render target to `width` x `height` device pixels.
    /// Called from `win::run`'s `WM_SIZE` handler.
    ///
    /// A no-op on the render-target side if no surface is attached yet —
    /// Windows can fire an initial `WM_SIZE` synchronously from inside
    /// `CreateWindowExW`, before the caller has the `HWND` back to pass to
    /// [`Self::attach_surface`]. The viewport is still updated so
    /// `Backend::viewport()` reflects the window's real size as soon as
    /// it's known.
    ///
    /// Also a no-op on the render-target side for a [`RenderTarget::Dc`]
    /// surface: `ID2D1DCRenderTarget` is bound once to a fixed-size DIB
    /// section and never resized.
    #[cfg(target_os = "windows")]
    pub(crate) fn resize_surface(&mut self, width: u32, height: u32) -> WinResult<()> {
        let width = width.max(1);
        let height = height.max(1);
        if let Some(surface) = &self.surface {
            if let RenderTarget::Hwnd(target) = &surface.target {
                let size = D2D_SIZE_U { width, height };
                // SAFETY: `target` is a live `ID2D1HwndRenderTarget` COM
                // object (this crate's `windows-rs` bindings hold a strong
                // reference for as long as `self.surface` does); `Resize`
                // takes `size` by const reference and has no other
                // precondition.
                unsafe { target.Resize(&size)? };
            }
        }
        self.viewport = Viewport::new(width as f32, height as f32, self.dpi_scale);
        Ok(())
    }

    /// Update the cached DPI scale (`WM_DPICHANGED`) without touching the
    /// render target's pixel size — the caller is responsible for
    /// resizing separately, once it has applied the new-DPI suggested
    /// window rect Windows hands back with that message.
    #[cfg(target_os = "windows")]
    pub(crate) fn set_dpi_scale(&mut self, scale: f32) {
        self.dpi_scale = scale;
        self.viewport.scale = scale;
    }

    // ── ActivityBar keyboard focus ────────────────────────────────────

    /// `WidgetId` of the [`ActivityBar`] that declared
    /// `is_keyboard_focused = true` during the most recent
    /// [`Backend::draw_activity_bar`] call, or `None` if no bar is
    /// focused. Read by `win::run::dispatch_event` — see
    /// `focused_activity_bar`'s field doc for the full contract. Not
    /// `target_os`-gated: the field itself is a plain `Option<WidgetId>`
    /// with no Direct2D dependency, so this reads correctly even before
    /// any surface has attached.
    pub(crate) fn focused_activity_bar_id(&self) -> Option<&WidgetId> {
        self.focused_activity_bar.as_ref()
    }

    // ── Double-click folding ───────────────────────────────────────────

    /// Fold a `MouseDown` into `DoubleClick` if it lands within the
    /// detector's time/position window of the previous click. Every other
    /// variant passes through unchanged. `win::run::dispatch_event` calls
    /// this on each translated Win32 mouse-button message before handing
    /// it to `AppLogic` — mirrors `MacBackend::fold_double_click`. Not
    /// `target_os`-gated: `DoubleClickDetector::process` has no WinAPI
    /// dependency, so this compiles and behaves identically on every host.
    pub(crate) fn fold_double_click(&mut self, ev: UiEvent) -> UiEvent {
        let mut events = [ev];
        self.double_click.process(&mut events);
        let [ev] = events;
        ev
    }

    // ── Accelerator matching ──────────────────────────────────────────
    //
    // The registry itself lives in [`crate::backend_core::BackendCore`]
    // — both methods below are thin delegations.

    /// Look up a registered `Global`-scope accelerator for a
    /// `(key, modifiers)` pair. Not `target_os`-gated for the same reason
    /// as `focused_activity_bar_id` above.
    pub(crate) fn match_keypress(&self, key: &Key, modifiers: Modifiers) -> Option<AcceleratorId> {
        self.core.match_keypress(key, modifiers)
    }

    /// Rewrite matching `KeyPressed` events to `UiEvent::Accelerator` in
    /// place — the `docs/BACKEND.md` "Event poll / wait" step 3, run by
    /// [`Backend::poll_events`]/[`Backend::wait_events`] over
    /// whatever this call drained from [`Self::events`].
    /// `win::run::dispatch_event`'s synchronous per-message path calls
    /// [`Self::match_keypress`] directly instead of going through this,
    /// since it already has one event at a time rather than a batch.
    pub(crate) fn apply_accelerators(&self, events: &mut [UiEvent]) {
        self.core.apply_accelerators(events);
    }

    // ── Event queue adapter ─────────────────────────────────────────────

    /// Shared handle to the backend's event queue, for a future producer
    /// (a live `wndproc` wiring, or any other event source) to clone and
    /// push into without needing a `&mut WinBackend` borrow. Mirrors
    /// `GtkBackend::events_handle`/`MacBackend::events_handle`. Not
    /// `target_os`-gated: `Rc<RefCell<VecDeque<UiEvent>>>` has no WinAPI
    /// dependency.
    pub fn events_handle(&self) -> Rc<RefCell<VecDeque<UiEvent>>> {
        self.events.clone()
    }

    /// Push one event onto the adapter queue, drained by
    /// [`Backend::poll_events`]/[`Backend::wait_events`]. The producer side
    /// of the queue pattern — mirrors `MacBackend::push_event`.
    pub fn push_event(&self, ev: UiEvent) {
        self.events.borrow_mut().push_back(ev);
    }

    /// Re-apply `current_pointer_shape` via `SetCursor`/`LoadCursorW`.
    /// Called both by [`Backend::set_cursor`] (an app-driven
    /// change) and by `win::run`'s `WM_SETCURSOR` handler (Windows
    /// re-asking "what cursor belongs here?" on every mouse move over the
    /// client area) — see `current_pointer_shape`'s field doc for why
    /// both call sites need to exist.
    #[cfg(target_os = "windows")]
    pub(crate) fn apply_current_cursor(&self) {
        // SAFETY: `LoadCursorW(None, ...)` loads a built-in system cursor
        // by predefined id — see `run.rs::run_inner`'s identical call for
        // the same reasoning; `SetCursor` takes the resulting `HCURSOR`
        // (or `None` on load failure, itself a documented valid input
        // meaning "no cursor") by value.
        unsafe {
            let _ = SetCursor(
                LoadCursorW(
                    None,
                    pointer_shape_to_win32_cursor(self.current_pointer_shape),
                )
                .ok(),
            );
        }
    }

    // ── Custom-caption hit testing ───────────────────────────────────────

    /// Reserved [`WidgetId`] a host registers (via [`Backend::register_zone`])
    /// for the drawn title-bar band it wants Windows to treat as a native
    /// caption — the drag-to-move / double-click-to-maximize row. Matches
    /// [`crate::compose::app_shell::AppShell`]'s own `"app-shell:title-bar"`
    /// zone id, so a host built on `AppShell` gets [`Self::nc_hit_test`]
    /// for free; a bespoke host (one that doesn't use `AppShell`) opts in
    /// with one `register_zone` call of its own each frame.
    pub const TITLE_BAR_DRAG_ZONE: &'static str = "app-shell:title-bar";

    /// Classify a client-area point (DIPs, same units [`Backend::viewport`]
    /// reports) for `win::run`'s `WM_NCHITTEST` handler:
    ///
    /// - `None` — the point isn't inside [`Self::TITLE_BAR_DRAG_ZONE`] at
    ///   all (no zone registered this frame, or the point falls outside
    ///   it). The caller should leave `DefWindowProcW`'s own answer alone
    ///   — resize border, below-the-band content, native caption buttons,
    ///   etc.
    /// - `Some(true)` — the point is in the band and not covered by any
    ///   more specific zone, so it should report `HTCAPTION`: dragging it
    ///   moves the window and double-clicking it maximizes/restores,
    ///   exactly like a native titlebar (`DefWindowProcW`'s own
    ///   non-client move loop handles both once this returns `HTCAPTION`
    ///   — see the `Backend::toggle_window_maximize` override's doc for
    ///   why no `begin_window_drag`/`begin_window_resize` call is needed
    ///   here).
    /// - `Some(false)` — the point is in the band but also inside another
    ///   registered zone strictly smaller than the band (a button, the
    ///   command-centre search box, or any other interactive widget a
    ///   host paints into the row) — report `HTCLIENT` instead, so the
    ///   click reaches that widget as an ordinary `UiEvent::MouseDown`
    ///   rather than being swallowed by the OS move/maximize gesture.
    ///
    /// Zones whose bounds are *not* strictly smaller than the band (e.g.
    /// `AppShell`'s own `"app-shell:window"` whole-window zone, which
    /// necessarily contains every point in the band too) are never
    /// treated as an exclusion — otherwise every point in the band would
    /// read as "covered by another zone" and this would always answer
    /// `Some(false)`, exactly the double-titlebar bug this issue exists
    /// to fix.
    pub fn nc_hit_test(&self, x: f32, y: f32) -> Option<bool> {
        let point = Point::new(x, y);
        let band = self
            .zones
            .iter()
            .find(|z| z.id.as_str() == Self::TITLE_BAR_DRAG_ZONE)?;
        if !band.bounds.contains(point) {
            return None;
        }
        let band_area = band.bounds.width * band.bounds.height;
        let excluded = self.zones.iter().any(|z| {
            z.id.as_str() != Self::TITLE_BAR_DRAG_ZONE
                && z.bounds.contains(point)
                && z.bounds.width * z.bounds.height < band_area
        });
        Some(!excluded)
    }

    // ── Band-content zone registration ──────────────────────────────────
    //
    // These three helpers register zones at the one place each widget's real
    // screen bounds are known: right after its `draw_*` call. Called
    // unconditionally — a zone outside the band is simply never found by
    // `nc_hit_test`'s `band.bounds.contains(point)` check, so this is harmless
    // for the common case and mirrors how `AppShell::render` already registers
    // every activity-bar item's zone regardless of position.

    /// Register one zone per clickable [`MenuBarLayout`] item — the
    /// File/Edit/... labels in the drawn menu row. See the section doc
    /// above.
    fn register_menu_bar_item_zones(&mut self, layout: &MenuBarLayout) {
        for item in &layout.visible_items {
            if item.clickable {
                self.register_zone(item.id, item.bounds);
            }
        }
    }

    /// Register one zone per clickable [`StatusBarLayout`] segment — the
    /// vimcode inline minimize/maximize/close buttons are ordinary
    /// `action_id`-bearing status-bar segments drawn into the title-bar
    /// band. See the section doc above.
    ///
    /// Unlike [`Self::register_menu_bar_item_zones`]/
    /// [`Self::register_command_center_zones`], `StatusBar::layout`/
    /// `layout_padded` (`primitives/status_bar.rs`) returns bounds in
    /// **bar-local** coordinates — origin `(0, 0)` at the bar's own
    /// top-left, by design (see `compose::status_bar_interaction::
    /// StatusBarInteraction::hit_test`, which subtracts the bar's own
    /// `x`/`y` from an incoming click position for exactly this reason).
    /// `rect` is the same absolute `Rect` the caller passed into
    /// `draw_status_bar_interactive`, so every `bounds` here must be
    /// translated by `rect.x`/`rect.y` before being handed to
    /// `register_zone`, which — like `nc_hit_test`'s `z.bounds.contains`
    /// check — compares against absolute, window-space coordinates
    fn register_status_bar_segment_zones(&mut self, rect: Rect, layout: &StatusBarLayout) {
        for (bounds, hit) in &layout.hit_regions {
            if let StatusBarHit::Segment(id) = hit {
                self.register_zone(
                    *id,
                    Rect::new(
                        rect.x + bounds.x,
                        rect.y + bounds.y,
                        bounds.width,
                        bounds.height,
                    ),
                );
            }
        }
    }

    /// Register a zone for each present [`CommandCenterLayout`] hit
    /// region (back/forward nav arrows, the search box) — the
    /// command-centre strip the issue names explicitly. `CommandCenterHit`
    /// carries no `WidgetId` of its own, so each zone is keyed off `cc`'s
    /// id with a fixed suffix, mirroring `"titlebar:minimize-button"`-style
    /// synthetic ids already used by this file's unit tests below.
    fn register_command_center_zones(&mut self, cc_id: &WidgetId, layout: &CommandCenterLayout) {
        for (bounds, hit) in &layout.hit_regions {
            let suffix = match hit {
                CommandCenterHit::Back => "back",
                CommandCenterHit::Forward => "forward",
                CommandCenterHit::SearchBox => "search",
                CommandCenterHit::Bar | CommandCenterHit::Outside => continue,
            };
            self.register_zone(
                WidgetId::new(format!("{}:{}", cc_id.as_str(), suffix)),
                *bounds,
            );
        }
    }

    // ── Paint-time text-run recording ───────────────────────────────────

    /// Enable/disable the paint-time text-run recording that backs
    /// [`super::testing::WinDriver::find`]/`find_bounds`/`inventory`/
    /// `screen_has`. Off by default. Not `target_os`-gated: the
    /// `painted_text_recording` field it writes has no WinAPI dependency,
    /// and its caller [`super::testing::WinDriver::new`] exists on every
    /// host too, so this must compile everywhere `WinDriver` does.
    pub(crate) fn set_painted_text_recording(&mut self, enabled: bool) {
        self.painted_text_recording = enabled;
    }

    /// Text runs recorded during the last [`Self::begin_frame`]/
    /// [`Self::end_frame`] bracket, when [`Self::set_painted_text_recording`]
    /// is on. Not `target_os`-gated, for the same reason that method
    /// isn't — see its doc.
    pub(crate) fn text_runs(&self) -> &[crate::testing::TextRun] {
        &self.text_runs
    }

    // ── request_frame_in scheduling ─────────────────────────────────────

    /// How many times [`Backend::request_frame_in`] has been called on
    /// this backend since it was constructed — [`crate::tui::TuiBackend::
    /// frame_requests`]'s twin for Win-GUI.
    ///
    /// Real hosts never need this. It exists so a headless
    /// [`super::testing::WinDriver`] test can assert on an app's
    /// *scheduling* behaviour even though [`Self::request_frame_in`]'s
    /// real `SetTimer` arm is a no-op before [`Self::attach_surface`]
    /// has ever run (no live `HWND` yet — exactly `WinDriver`'s
    /// situation) — see [`Self::frame_scheduler`]'s field doc. Not
    /// `target_os`-gated, for the same reason
    /// [`Self::set_painted_text_recording`] isn't: the field it reads has
    /// no WinAPI dependency, and its caller exists on every host `win`
    /// compiles on.
    ///
    /// Monotonic: a fired deadline clears the pending wake (see
    /// [`Self::pending_frame_delay`]), not the count.
    pub fn frame_requests(&self) -> u64 {
        self.frame_scheduler.requests()
    }

    /// Time remaining until the pending [`Backend::request_frame_in`]
    /// deadline, or `None` when no frame is scheduled — the companion to
    /// [`Self::frame_requests`]: that one proves *how often* an app
    /// asked, this one proves *what interval* it asked for. Not
    /// `target_os`-gated, same reason as [`Self::frame_requests`].
    pub fn pending_frame_delay(&self) -> Option<Duration> {
        self.frame_scheduler.pending_delay()
    }

    // ── Caret blink ──────────────────────────────────────────────────────
    //
    // Thin delegation onto `self.caret_blink` — see that field's doc for
    // the full `CARET_BLINK_TIMER_ID` wiring in `super::run`.

    /// Whether the `MultiSectionView` aux-row caret should currently
    /// paint — read by [`super::multi_section_view::draw_multi_section_view`]
    /// via [`Self::draw_multi_section_view`].
    ///
    /// `#[allow(dead_code)]`: this method's only non-test callers —
    /// [`Self::draw_multi_section_view`]'s `target_os = "windows"` arm and
    /// `mod win32`'s `WM_TIMER` handler — are both windows-gated, so on a
    /// non-Windows host (`cargo check --features win` on the
    /// `ubuntu-latest` CI leg) it has no caller outside this file's own
    /// `#[cfg(test)]` module and would trip `-D warnings`' dead-code lint
    /// there despite being genuinely used on the `windows-latest` leg —
    /// same rationale as `win::run::dispatch_event`'s identical allow.
    #[allow(dead_code)]
    pub(crate) fn caret_visible(&self) -> bool {
        self.caret_blink.visible()
    }

    /// Advance the caret-blink phase to `now`. Called from
    /// `super::run`'s `CARET_BLINK_TIMER_ID` `WM_TIMER` handler; returns
    /// `true` when the phase flipped, telling the caller to invalidate
    /// the window.
    ///
    /// `#[allow(dead_code)]`: see [`Self::caret_visible`]'s doc — this
    /// method's only non-test caller is windows-gated too.
    #[allow(dead_code)]
    pub(crate) fn tick_caret_blink(&mut self, now: Instant) -> bool {
        self.caret_blink.tick(now)
    }

    /// The configured caret-blink period — the interval `super::run`
    /// arms `CARET_BLINK_TIMER_ID` at.
    ///
    /// `#[allow(dead_code)]`: see [`Self::caret_visible`]'s doc — this
    /// method's only non-test caller is windows-gated too.
    #[allow(dead_code)]
    pub(crate) fn caret_blink_period(&self) -> Duration {
        self.caret_blink.period()
    }

    /// Record typing activity at `now`, holding the caret solid for a
    /// typing pause. Called from `super::run::dispatch_event` on
    /// `KeyPressed`/`CharTyped`.
    pub(crate) fn note_caret_activity(&mut self, now: Instant) {
        self.caret_blink.on_activity(now);
    }

    /// Test-only: force the caret-blink phase to `visible` for
    /// reproducible paint snapshots, mirroring
    /// `MacBackend::set_caret_visible`/`GtkBackend::set_caret_visible`.
    #[cfg(test)]
    pub(crate) fn set_caret_visible(&mut self, visible: bool) {
        if self.caret_blink.visible() != visible {
            let far_future = Instant::now() + Duration::from_secs(3600);
            self.caret_blink.tick(far_future);
        }
    }

    // ── Text selection ───────────────────────────────────────────────────
    //
    // The region registry + active-selection state machine, plus the
    // accelerator registry alongside it, live in
    // [`crate::backend_core::BackendCore`] — every method below
    // except [`Self::apply_selection_highlight`]/[`Self::extract_selection_text`]
    // (Direct2D painting / `TextRegion::lines` extraction, this backend's
    // own — mirrors `GtkBackend`'s pixel-based twins via the shared
    // `BackendCore::selection_highlight_rects`/`extract_selection_text_pixel`
    // helpers) is a thin delegation.

    /// Mutable access to the [`crate::text_selection::TextSelectionState`]
    /// — the shape [`crate::dispatch::route_pointer`] needs to both read
    /// `text_regions` and call `track_focused_text_region` without separate
    /// accessors. Mirrors `GtkBackend::text_selection_state_mut`.
    pub(crate) fn text_selection_state_mut(
        &mut self,
    ) -> &mut crate::text_selection::TextSelectionState {
        &mut self.core.text_selection
    }

    /// Return the current active text selection, if any.
    pub(crate) fn active_text_selection(
        &self,
    ) -> Option<&crate::text_selection::ActiveTextSelection> {
        self.core.active_text_selection()
    }

    /// Update (or start) the active text selection. Called by
    /// `win::run::dispatch_event` when a [`UiEvent::TextSelectionChanged`]
    /// event arrives, and by [`Self::select_all_text_region`].
    pub(crate) fn set_active_text_selection(
        &mut self,
        region: WidgetId,
        anchor: crate::event::Point,
        focus: crate::event::Point,
    ) {
        self.core.set_active_text_selection(region, anchor, focus);
    }

    /// Clear the active text selection highlight only (does NOT end an
    /// in-progress `TextSelection` drag). Called before dispatching a new
    /// mouse-down so the old highlight disappears without interrupting the
    /// drag that is about to start. Mirrors `GtkBackend::clear_selection_display`.
    pub(crate) fn clear_selection_display(&mut self) {
        self.core.clear_selection_display();
    }

    /// Clear the active text selection and end any in-progress
    /// `TextSelection` drag. Called after Ctrl-C copies the selection or
    /// on a plain click outside any text region.
    pub(crate) fn clear_text_selection(&mut self) {
        let mut drag = self.drag_state.borrow_mut();
        self.core.clear_text_selection(&mut drag);
    }

    /// End any in-progress `TextSelection` drag without clearing the
    /// displayed selection. Backs the `Backend` trait's
    /// `cancel_text_selection_drag` override — apps hosting an embedded
    /// terminal call it to abort a speculative drag before forwarding a
    /// click to a PTY. Mirrors `GtkBackend::cancel_text_selection_drag_impl`/
    /// `TuiBackend::cancel_text_selection_drag_impl`.
    fn cancel_text_selection_drag_impl(&mut self) {
        let mut drag = self.drag_state.borrow_mut();
        self.core.cancel_text_selection_drag(&mut drag);
    }

    /// Set the active selection to cover the entire visible content of the
    /// most-recently focused `TextRegion` (the Ctrl-A target). See
    /// [`crate::text_selection::TextSelectionState::select_all_text_region`]
    /// for the resolution order and the viewport-only limitation.
    pub(crate) fn select_all_text_region(&mut self) -> bool {
        self.core.select_all_text_region()
    }

    /// Extract the selected text from the active selection's `TextRegion`
    /// using its stored `lines` (Win-GUI is pixel-based, like GTK — see
    /// `TextRegion::lines`'s doc). Empty when there is no active selection,
    /// the region isn't registered this frame, or it has no `lines`
    /// content.
    pub(crate) fn extract_selection_text(&self) -> String {
        self.core
            .extract_selection_text_pixel(self.current_line_height, self.current_char_width)
    }

    /// Paint the active text-selection highlight on top of the frame's
    /// already-painted content. Must be called after `app.render` inside
    /// the same `begin_frame`/`end_frame` bracket (`win::run::render_frame`)
    /// — mirrors `GtkBackend::apply_selection_highlight`'s Cairo twin and
    /// `TuiBackend::apply_selection_highlight`'s cell-invert twin, except
    /// Direct2D's `FillRectangle` paints directly onto `self.surface`
    /// rather than needing an external target handle. No-op when there is
    /// no active selection, the region isn't registered this frame, metrics
    /// aren't known yet, or (off Windows / before a surface is attached)
    /// there is nothing to paint into.
    ///
    /// The rect resolution is
    /// [`crate::backend_core::BackendCore::selection_highlight_rects`] —
    /// shared with `GtkBackend`/`MacBackend`'s twins; only the
    /// `super::text::fill_rect` Direct2D calls below are Win-GUI-specific
    /// real toolkit code.
    pub(crate) fn apply_selection_highlight(&self) {
        let Some(rects) = self
            .core
            .selection_highlight_rects(self.current_line_height, self.current_char_width)
        else {
            return;
        };
        #[cfg(target_os = "windows")]
        if let Some(surface) = &self.surface {
            let highlight = self.current_theme.text_selection_highlight();
            for rect in rects {
                let _ = super::text::fill_rect(&surface.target, rect, highlight);
            }
        }
        #[cfg(not(target_os = "windows"))]
        {
            let _ = rects;
        }
    }
}

/// `GetDpiForWindow(hwnd) / 96.0` — the ratio `Viewport::scale` carries
/// for this backend. The divide and its zero-DPI fallback live in
/// [`crate::win::msg::dpi_ratio`] so they stay unit-tested off Windows;
#[cfg(target_os = "windows")]
fn dpi_scale_for_window(hwnd: HWND) -> f32 {
    // SAFETY: `GetDpiForWindow` takes only a handle and returns a `u32` by
    // value — `hwnd` is the caller's live window, and there is no other
    // precondition.
    crate::win::msg::dpi_ratio(unsafe { GetDpiForWindow(hwnd) })
}

/// Resolve [`WinBackend::hwnd_raw`]'s current raw value back into an
/// `HWND`, or `None` if no window has attached yet (`0`). Split out of
/// [`WinBackend::waker`]'s closure so the "read the live handle" step is
/// a plain, directly unit-testable function.
#[cfg(target_os = "windows")]
fn live_hwnd(hwnd_raw: &std::sync::atomic::AtomicIsize) -> Option<HWND> {
    let raw = hwnd_raw.load(std::sync::atomic::Ordering::Acquire);
    if raw == 0 {
        None
    } else {
        Some(HWND(raw as *mut core::ffi::c_void))
    }
}

/// Map a [`PointerShape`] to the Win32 `IDC_*` cursor-resource `PCWSTR`
/// [`LoadCursorW`] expects. Win32's stock cursor set has no separate NE-only
/// vs. SW-only (or NW-only vs. SE-only) diagonal-resize glyph — `IDC_SIZENESW`
/// and `IDC_SIZENWSE` are each shared between their two opposite corners at the
/// OS resource level. Every [`crate::backend::ResizeEdge`] variant still gets a
/// direction-correct cursor; only the specific `IDC_*` resource is shared per
/// diagonal.
#[cfg(target_os = "windows")]
fn pointer_shape_to_win32_cursor(shape: PointerShape) -> windows::core::PCWSTR {
    use crate::backend::ResizeEdge;
    match shape {
        PointerShape::Default => IDC_ARROW,
        PointerShape::Resize(ResizeEdge::North) | PointerShape::Resize(ResizeEdge::South) => {
            IDC_SIZENS
        }
        PointerShape::Resize(ResizeEdge::East) | PointerShape::Resize(ResizeEdge::West) => {
            IDC_SIZEWE
        }
        PointerShape::Resize(ResizeEdge::NorthEast)
        | PointerShape::Resize(ResizeEdge::SouthWest) => IDC_SIZENESW,
        PointerShape::Resize(ResizeEdge::NorthWest)
        | PointerShape::Resize(ResizeEdge::SouthEast) => IDC_SIZENWSE,
    }
}

impl Default for WinBackend {
    fn default() -> Self {
        Self::new()
    }
}

impl crate::runtime::PreprocessBackend for WinBackend {
    fn active_text_selection(&self) -> Option<&crate::text_selection::ActiveTextSelection> {
        self.active_text_selection()
    }

    fn set_active_text_selection(&mut self, region: WidgetId, anchor: Point, focus: Point) {
        self.set_active_text_selection(region, anchor, focus)
    }

    fn clear_text_selection(&mut self) {
        self.clear_text_selection()
    }

    fn clear_selection_display(&mut self) {
        self.clear_selection_display()
    }

    fn select_all_text_region(&mut self) -> bool {
        self.select_all_text_region()
    }

    fn selection_text_for_copy(&self) -> String {
        self.extract_selection_text()
    }

    fn focused_activity_bar_id(&self) -> Option<&WidgetId> {
        self.focused_activity_bar_id()
    }

    fn focus_manager_mut(&mut self) -> &mut crate::focus::FocusManager {
        &mut self.focus
    }

    fn match_keypress(
        &self,
        key: &crate::Key,
        modifiers: crate::Modifiers,
    ) -> Option<AcceleratorId> {
        self.match_keypress(key, modifiers)
    }

    fn fold_double_click(&mut self, ev: UiEvent) -> UiEvent {
        self.fold_double_click(ev)
    }
}

impl crate::backend::sealed::Sealed for WinBackend {}

impl Backend for WinBackend {
    // ─── Frame + viewport ─────────────────────────────────────────────

    fn viewport(&self) -> Viewport {
        self.viewport
    }

    fn begin_frame(&mut self, viewport: Viewport) {
        self.viewport = viewport;
        // Clear the focused activity bar — re-set by `draw_activity_bar`
        // during this frame's render pass if still focused. Same
        // lifecycle as `GtkBackend`/`MacBackend`'s `focused_activity_bar`
        self.focused_activity_bar = None;
        // Clear per-frame text regions so stale registrations from the
        // previous frame don't linger. Mirrors `GtkBackend`/`TuiBackend`'s
        // identical `begin_frame` clear.
        self.core.begin_frame();
        // Clear last frame's `register_zone` entries — a zone a widget stops
        // painting must stop resolving hit tests too. Mirrors
        // `GtkBackend::begin_frame`'s identical `self.zones.clear()`.
        self.zones.clear();
        // Install the shared paint-time text-run recording sink for the
        // duration of this frame — drained into `self.text_runs` by
        // `end_frame` below. Mirrors `MacBackend::enter_frame_scope`'s
        // start/stop bracket; Win-GUI needs no closure-based
        // frame scope of its own, since `draw_*` trait methods already
        // have `&mut self` throughout the frame.
        if self.painted_text_recording {
            let _ = crate::testing::install_text_run_sink();
        }
        #[cfg(target_os = "windows")]
        if let Some(surface) = &self.surface {
            // `BeginDraw`/`Clear` are infallible on `ID2D1RenderTarget`
            // (device-lost errors only surface later, from `EndDraw` —
            // handled in `end_frame` below).
            //
            // SAFETY: `surface.target` is a live `ID2D1RenderTarget` COM
            // object for as long as `self.surface` holds it; `BeginDraw`
            // takes no arguments and its only precondition (must be
            // paired with a later `EndDraw`, never called twice without
            // one in between) is upheld by `end_frame` below being this
            // frame's only other caller.
            unsafe {
                surface.target.BeginDraw();
            }
            // Route this frame's paint helpers through the surface's
            // brush cache; `end_frame` deactivates it.
            super::text::activate_brush_cache(&surface.target, &surface.brushes);
            // Use the theme's background colour instead of a hard-coded dark
            // shade — unpainted areas must show the correct background on light
            // themes too.
            let clear_color = super::text::color_to_d2d(self.current_theme.background);
            // SAFETY: same live `surface.target` as `BeginDraw` above,
            // now inside the `BeginDraw`/`EndDraw` bracket that call
            // opened; `clear_color` is a stack-local `D2D1_COLOR_F`
            // passed by reference for the duration of the call.
            unsafe {
                surface.target.Clear(Some(&clear_color));
            }
        }
        // A non-Windows host never has Direct2D types to call
        // `BeginDraw`/`Clear` against at all — same "nothing to paint
        // onto" posture as the `self.surface.is_none()` case above, not a
        // gap this issue's fallbacks need to fake. The
        // `#[cfg]` still binds directly to this statement (not a sibling
        // unused-param line), unlike the bug this issue otherwise fixes —
        // see the module-level issue doc.
        #[cfg(not(target_os = "windows"))]
        {}
    }

    fn end_frame(&mut self) {
        // Drain the sink `begin_frame` installed, if recording was on —
        // see that method's doc for why this needs no closure-based frame
        // scope the way GTK/macOS's `enter_frame_scope` does.
        if self.painted_text_recording {
            self.text_runs = crate::testing::take_text_run_sink(None);
        }
        #[cfg(target_os = "windows")]
        super::text::deactivate_brush_cache();
        #[cfg(target_os = "windows")]
        if let Some(surface) = &self.surface {
            // `EndDraw` fails for two distinct reasons, both handled the
            // same way here — the well-known `D2DERR_RECREATE_TARGET`
            // (GPU driver reset, remote-desktop session change, etc.) and
            // anything else — since either way the render target must be
            // rebuilt before the next frame can paint onto it. Drop the
            // surface rather than silently pretending the frame
            // presented, or letting the next frame paint onto a target
            // Direct2D has already discarded. `self.hwnd`/`headless_target`
            // (set by `attach_surface`/`attach_headless`, untouched here)
            // survive the drop, so the next `WM_PAINT`/`WM_SIZE` reaching
            // `win::run` (or the next `WinDriver::render`, issue #805)
            // actually recreates it via `Self::ensure_surface` — see that
            // method's docs.
            //
            // Now reported through the trait's error channel (issue
            // #507/#805, `docs/decisions/DECISIONS.md` D-009) instead of
            // silently dropping on the floor: `last_error()` hands the
            // caller `BackendError::SurfaceLost`, and `diagnostics::emit`
            // gives a host with a sink installed (`src/diagnostics.rs`)
            // a chance to log it even if nothing ever polls
            // `last_error()`.
            //
            // SAFETY: `surface.target` is the same live COM object
            // `begin_frame`'s `BeginDraw` call opened a draw bracket on;
            // `EndDraw(None, None)` (no tag pointers requested back) is
            // the documented way to close it without the optional
            // per-primitive-tag diagnostics.
            if unsafe { surface.target.EndDraw(None, None) }.is_err() {
                self.surface = None;
                self.last_error = Some(BackendError::SurfaceLost);
                crate::diagnostics::emit(
                    "quadraui win backend: EndDraw failed (device lost / \
                     D2DERR_RECREATE_TARGET) — render target dropped, will \
                     recreate via ensure_surface on the next frame",
                );
            }
        }
        // See `begin_frame`'s matching comment.
        #[cfg(not(target_os = "windows"))]
        {}
    }

    // ─── Theming ────────────────────────────────────────────────────────

    /// Store the theme so the `draw_*` rasterisers below use it instead of
    /// falling back to `Theme::default()`. Mirrors `GtkBackend::set_theme`
    /// and `MacBackend::set_theme`.
    fn set_theme(&mut self, theme: crate::Theme) {
        self.set_current_theme(theme);
    }

    fn theme(&self) -> crate::Theme {
        self.current_theme
    }

    fn set_style(&mut self, style: crate::Style) {
        self.set_current_style(style);
    }

    fn style(&self) -> crate::Style {
        self.current_style
    }

    /// Store the nerd-fonts flag so `draw_tree` paints `Icon::glyph`
    /// instead of always falling back to `Icon::fallback`.
    /// Mirrors `TuiBackend::set_nerd_fonts`/`GtkBackend::set_nerd_fonts`/
    /// `MacBackend::set_nerd_fonts` — see [`Backend::set_nerd_fonts`]'s
    /// doc for why every backend defaults this to `false`.
    fn set_nerd_fonts(&mut self, enabled: bool) {
        self.nerd_fonts_enabled = enabled;
    }

    fn nerd_fonts_enabled(&self) -> bool {
        self.nerd_fonts_enabled
    }

    /// Store the chrome font description for the next
    /// [`Self::attach_surface`]/[`Self::attach_headless`] call to build a
    /// chrome `IDWriteTextFormat` from, parsed via
    /// [`parse_ui_font_desc`]. Same "doesn't rebuild a live surface's
    /// text format immediately" limitation as [`Self::set_editor_font`] —
    /// see that method's doc.
    fn set_ui_font(&mut self, font_desc: &str) {
        #[cfg(target_os = "windows")]
        {
            let (family, size_pt) = parse_ui_font_desc(font_desc);
            self.ui_font_family = family;
            self.ui_font_size_pt = size_pt;
        }
        #[cfg(not(target_os = "windows"))]
        {
            let _ = font_desc;
        }
    }

    /// Win-GUI's platform-native convention: `Consolas
    /// 14` for editor content, `Segoe UI 13` for UI chrome — VS Code's
    /// own Windows defaults, and the same family names
    /// `DEFAULT_EDITOR_FONT_FAMILY`/`DEFAULT_UI_FONT_FAMILY` already
    /// fall back to (sizes differ: those exist for the "unset" runtime
    /// default, `11pt`, not to model this platform recommendation).
    /// Plain literals rather than those `cfg(target_os = "windows")`
    /// consts themselves — unlike [`Self::set_ui_font`] above, this
    /// method has no DirectWrite call to gate, and must type-check on
    /// every host per this crate's cross-platform commitment (see
    /// `CLAUDE.md`'s Win-GUI section).
    fn default_fonts(&self) -> crate::backend::PlatformFontDefaults {
        crate::backend::PlatformFontDefaults {
            editor_family: "Consolas".to_string(),
            editor_size_pt: 14.0,
            ui_family: "Segoe UI".to_string(),
            ui_size_pt: 13.0,
        }
    }

    /// Register `bytes` with DirectWrite via
    /// [`crate::win::text::register_font_from_memory`] — no
    /// filesystem write, process-lifetime only. Stores the resulting
    /// private `IDWriteFontCollection1` (so a later
    /// [`Self::set_nerd_font_fallback`] resolves against the font that
    /// was actually registered).
    ///
    /// Copies `bytes` into `self.registered_font_bytes` *first*, then
    /// calls `text::register_font_from_memory` with a pointer into that
    /// owned copy — never `bytes` itself. `bytes` is the caller's slice
    /// and, per this trait method's doc, may be a local the caller drops
    /// the instant this call returns; `CreateInMemoryFontFileReference`
    /// does not copy its input, so handing it a pointer into a
    /// caller-owned, possibly-transient buffer would leave DirectWrite
    /// holding a dangling pointer the moment that buffer is freed. See
    /// `registered_font_bytes`'s field doc for the rest of this
    /// backend's lifetime story.
    fn register_font_from_memory(&mut self, bytes: &[u8]) -> Option<Vec<String>> {
        #[cfg(target_os = "windows")]
        {
            self.registered_font_bytes.push(bytes.to_vec());
            let owned: &[u8] = self
                .registered_font_bytes
                .last()
                .expect("just pushed a value above");
            match crate::win::text::register_font_from_memory(owned) {
                Ok((collection, names)) => {
                    self.registered_font_collection = Some(collection);
                    Some(names)
                }
                Err(_) => {
                    // Registration failed, so nothing references this
                    // copy — but there's no live pointer into it either,
                    // and leaving it in place (rather than popping it
                    // back off) keeps this method's error path as simple
                    // as its success path. See `registered_font_bytes`'s
                    // field doc: entries are never removed anyway.
                    None
                }
            }
        }
        #[cfg(not(target_os = "windows"))]
        {
            let _ = bytes;
            None
        }
    }

    /// Answers via [`crate::win::text::has_font_family`]:
    /// DirectWrite's system font collection lookup (`FindFamilyName`),
    /// distinct from `register_font_from_memory`'s private,
    /// app-registered collection. `Err` (a DirectWrite factory/
    /// collection failure, not "family not found" — that's `Ok(false)`)
    /// degrades to `None`, same "don't fail, don't know" posture as
    /// every other fallible-but-non-critical Win-GUI query.
    fn has_font_family(&self, family: &str) -> Option<bool> {
        #[cfg(target_os = "windows")]
        {
            crate::win::text::has_font_family(family).ok()
        }
        #[cfg(not(target_os = "windows"))]
        {
            let _ = family;
            None
        }
    }

    /// Build a Nerd-Font (or other PUA-codepoint) fallback for `family`
    /// via [`crate::win::text::build_nerd_font_fallback`] and store it
    /// for the next [`Self::attach_surface`]/[`Self::attach_headless`]
    /// call to bake into both `IDWriteTextFormat`s. Resolves
    /// against `registered_font_collection` when a prior
    /// [`Self::register_font_from_memory`] call populated one, otherwise
    /// against the system font collection — see
    /// `build_nerd_font_fallback`'s doc. Same "doesn't rebuild a live
    /// surface immediately" limitation as [`Self::set_editor_font`].
    fn set_nerd_font_fallback(&mut self, family: &str) {
        #[cfg(target_os = "windows")]
        {
            // `build_nerd_font_fallback_multi` with both
            // mappings, not a bare `build_nerd_font_fallback(family,
            // ...)` — a single `IDWriteFontFallback` is a full
            // replacement when stored into `self.nerd_font_fallback`
            // (DirectWrite text formats carry exactly one), so
            // rebuilding from `family` alone here would drop the
            // bundled codicon mapping `Self::new` seeded.
            let built = crate::win::text::build_nerd_font_fallback_multi(&[
                (family, self.registered_font_collection.as_ref()),
                (
                    crate::codicon::FONT_FAMILY,
                    self.codicon_font_collection.as_ref(),
                ),
            ]);
            match built {
                Ok(fallback) => self.nerd_font_fallback = Some(fallback),
                Err(err) => {
                    // This trait method returns `()`, so there's no
                    // `Result`/`Option` to hand a caller the way
                    // `register_font_from_memory` does — but silently
                    // dropping the built fallback with no diagnostic at
                    // all left a caller no way to learn this didn't take
                    // effect. Emit via
                    // `crate::diagnostics` (never a raw `eprintln!` —
                    // this is live library code a host may be running
                    // with the terminal in raw mode, see that module's
                    // doc) and keep whatever fallback, if any, was
                    // already active.
                    crate::diagnostics::emit(format!(
                        "quadraui: set_nerd_font_fallback({family:?}) failed to build a font \
                         fallback ({err:?}); icon glyphs may render as tofu"
                    ));
                }
            }
        }
        #[cfg(not(target_os = "windows"))]
        {
            let _ = family;
        }
    }

    // ─── Events + keybindings ─────────────────────────────────────────

    /// Drain [`Self::events`] and run the result through
    /// [`Self::apply_accelerators`]. Never blocks — a plain `VecDeque` drain.
    /// Nothing feeds this queue from the live `wndproc` yet — see [`Self::events`]'s
    /// field doc and `win::run`'s "Dispatch model" module doc. A driver or other
    /// caller that pushes via [`Self::push_event`] gets a real, non-panicking
    /// drain.
    fn poll_events(&mut self) -> Vec<UiEvent> {
        let mut out: Vec<UiEvent> = self.events.borrow_mut().drain(..).collect();
        self.apply_accelerators(&mut out);
        // Fold in any `UiEvent::User` payloads a background thread queued via
        // `waker()` since the last drain. The live `wndproc` calls
        // `Self::drain_user_events` directly instead, but this keeps `poll_events`
        // correct for any other caller (a driver, a test).
        self.user_events.drain_into(&mut out);
        out
    }

    /// Same drain as [`Self::poll_events`] — `_timeout` is accepted (per
    /// the trait signature) but never waited out. A Win32 message loop
    /// has no native "block up to N ms for the next message" primitive
    /// that fits this poll-style trait (`MsgWaitForMultipleObjects` waits
    /// on kernel handles, not "either a message or a timeout elapses
    /// with the queue left untouched"), and nothing in this backend
    /// drives a real `HWND`'s message queue from here — the live
    /// `wndproc` pump stays the direct-dispatch path (see
    /// [`Self::poll_events`]'s doc). Returning a plain drain rather than
    /// spinning `GetMessageW` (a real, uninterruptible block with no
    /// timeout at all) mirrors `MacBackend::wait_events`'s identical
    /// "today this is a plain drain" posture — both callback-driven
    /// backends where the native run loop, not this trait method, is
    /// what actually waits.
    fn wait_events(&mut self, _timeout: Duration) -> Vec<UiEvent> {
        self.poll_events()
    }

    /// See [`Backend::waker`]'s doc for the full cross-backend contract.
    /// A live `GetMessageW` loop blocks *indefinitely* for the next Win32
    /// message with no timeout at all — the most severe case of the four
    /// backends (TUI/GTK both re-poll on a bounded interval regardless;
    /// see `Backend::waker`'s doc). `PostMessageW` is Win32's own
    /// documented thread-safe "queue a message for this window, waking a
    /// blocked `GetMessageW`" primitive, posting
    /// [`WM_QUADRAUI_USER_EVENT`] — `win::run`'s `wndproc` match arm on
    /// that value is what actually drains [`Self::user_events`] and
    /// dispatches, since `wndproc` already has direct access to the app/
    /// backend state a live message carries with it (unlike GTK, which
    /// needs the `WakeId`/thread-local `wake_callback` indirection because
    /// its wake primitive's callback has no such access — see
    /// `GtkBackend::waker`'s doc).
    ///
    /// `self.hwnd` is `None` until [`Self::attach_surface`] runs (or on
    /// any non-Windows host, where it never exists at all — see that
    /// field's doc) — the closure is a documented no-op in that case,
    /// same posture as `RecordingBackend::waker` and
    /// `GtkBackend::waker`'s "no `wake_callback` installed yet" case: a
    /// payload still lands in [`Self::user_events`] for any later
    /// `poll_events` caller, there is just no live window to nudge yet.
    /// That no-op is *transient*, not permanent: the closure reads
    /// [`Self::hwnd_raw`] fresh on every call rather than snapshotting
    /// `self.hwnd` once at `waker()` call time, so a waker obtained
    /// during `AppLogic::setup` (before `attach_surface` has run) still
    /// wakes the loop correctly once a real window exists — see
    /// `hwnd_raw`'s doc for the full rationale and the GTK/macOS
    /// precedent this mirrors.
    fn waker(&self) -> std::sync::Arc<dyn Fn(UserPayload) + Send + Sync> {
        let queue = std::sync::Arc::clone(&self.user_events);
        #[cfg(target_os = "windows")]
        {
            // `HWND` wraps a raw pointer and isn't `Send`, but the numeric
            // handle value is — Win32 handles are opaque integers the OS
            // resolves, not memory this process dereferences directly, so
            // round-tripping through `isize` and reconstructing `HWND` on
            // the other side is exactly as valid as the original value.
            // `PostMessageW` is documented safe to call against a window
            // owned by a different thread than the caller (that's its
            // entire purpose here). `hwnd_raw` is the same `Arc` `self`
            // holds (not a value copied out of it), so this closure sees
            // whatever `attach_surface` stores into it later, however
            // long after this closure was created.
            let hwnd_raw = std::sync::Arc::clone(&self.hwnd_raw);
            std::sync::Arc::new(move |payload: UserPayload| {
                queue.push(payload.into_arc());
                if let Some(hwnd) = live_hwnd(&hwnd_raw) {
                    // SAFETY: `hwnd` came from `live_hwnd`, which reads
                    // `hwnd_raw` fresh on every call — see the doc comment
                    // above for why round-tripping through `isize` this
                    // way is valid even from a background thread, and why
                    // `PostMessageW` (documented as thread-safe to call
                    // against another thread's window) is the right
                    // primitive here rather than `SendMessageW`.
                    unsafe {
                        let _ =
                            PostMessageW(Some(hwnd), WM_QUADRAUI_USER_EVENT, WPARAM(0), LPARAM(0));
                    }
                }
            })
        }
        #[cfg(not(target_os = "windows"))]
        {
            std::sync::Arc::new(move |payload: UserPayload| {
                queue.push(payload.into_arc());
            })
        }
    }

    /// See [`Backend::request_frame_in`]'s doc for the cross-backend
    /// contract. Unlike [`Self::waker`] this always runs
    /// synchronously on the thread that owns the message loop — called
    /// directly from event/tick handling, never from a background
    /// thread — so it needs none of `waker`'s cross-thread `AtomicIsize`
    /// live-mirror machinery: a plain read of `self.hwnd` is safe.
    /// Arms [`FRAME_TIMER_ID`] via `SetTimer`, the same Win32
    /// one-shot-timer primitive `win::run`'s resize-settle debounce uses;
    /// `win::run::wndproc`'s `WM_TIMER` arm on that id is what actually
    /// fires `AppLogic::tick`/re-dispatches, mirroring `WM_QUADRAUI_USER_EVENT`'s
    /// arm for `waker`.
    ///
    /// A no-op before [`Self::attach_surface`] has ever run (`self.hwnd`
    /// is still `None`) — same posture as `waker`'s "no window to nudge
    /// yet" case, except here there is no queued payload to preserve for
    /// later delivery: a `request_frame_in` call with no window is simply
    /// lost, matching [`crate::runner::Reaction::RedrawAfter`]'s "may
    /// wake earlier... but never required to fire at all before a native
    /// event exists to carry it" posture — there is no event loop yet for
    /// an unattached backend to wake.
    ///
    /// Records into [`Self::frame_scheduler`] unconditionally, `hwnd` or
    /// not — that bookkeeping is test-facing only (see
    /// [`Self::frame_requests`]/[`Self::pending_frame_delay`]) and must
    /// not depend on the real `SetTimer` arm below, which stays exactly
    /// as no-op-before-attach as before.
    fn request_frame_in(&self, delay: Duration) {
        self.frame_scheduler.request(delay);
        #[cfg(target_os = "windows")]
        {
            if let Some(hwnd) = self.hwnd {
                // SAFETY: this runs synchronously on the thread that owns
                // the message loop (per the doc comment above), so
                // `self.hwnd` is a live window read on its own thread;
                // `lpTimerFunc: None` posts `WM_TIMER` through the normal
                // message queue rather than invoking a raw function
                // pointer.
                unsafe {
                    SetTimer(
                        Some(hwnd),
                        FRAME_TIMER_ID,
                        delay.as_millis().min(u32::MAX as u128) as u32,
                        None,
                    );
                }
            }
        }
    }

    fn invalidate_rect(&mut self, rect: crate::event::Rect) {
        self.core.record_invalidation(rect);
    }

    fn invalidation_log(&self) -> &crate::backend::InvalidationLog {
        self.core.invalidation_log()
    }

    fn register_accelerator(&mut self, acc: &Accelerator) {
        self.core.register_accelerator(acc);
    }

    fn unregister_accelerator(&mut self, id: &AcceleratorId) {
        self.core.unregister_accelerator(id);
    }

    /// Persists via `self.core`, same one-liner delegation as the
    /// accelerator methods above.
    fn menu_style(&self) -> crate::backend::MenuStyle {
        self.core.menu_style()
    }

    fn set_menu_style(&mut self, style: crate::backend::MenuStyle) {
        self.core.set_menu_style(style);
    }

    // ─── Text selection ─────────────────────────────────────────────────

    /// Overrides the trait's no-op default — see [`Self::text_regions`]
    /// and `crate::text_selection::TextSelectionState`.
    fn register_text_region(&mut self, region: TextRegion) {
        self.core.register_text_region(region);
    }

    /// Overrides the trait's no-op default — see
    /// [`Self::cancel_text_selection_drag_impl`].
    fn cancel_text_selection_drag(&mut self) {
        self.cancel_text_selection_drag_impl();
    }

    // ─── Zone registration ──────────────────────────────────────────────────
    //
    // Overrides the trait's no-op default. Every `draw_*` rasteriser on this
    // backend that already called `self.register_zone(...)` used to have that
    // call silently swallowed; this is the first thing that reads `self.zones`
    // back.

    /// Overrides the trait's no-op default. Every `draw_*` rasteriser that
    /// already called `self.register_zone(...)` used to have that call silently
    /// swallowed. This reads `self.zones` back via [`Self::nc_hit_test`]'s
    /// `WM_NCHITTEST` classification. Mirrors `GtkBackend::register_zone` and
    /// `MacBackend::register_zone`.
    fn register_zone(&mut self, id: WidgetId, bounds: Rect) {
        self.zones.push(crate::testing::ZoneRec { id, bounds });
    }

    // ─── Modal-overlay tracking ───────────────────────────────────────

    fn modal_stack_handle(&self) -> Rc<RefCell<ModalStack>> {
        self.modal_stack.clone()
    }

    fn drag_state_handle(&self) -> Rc<RefCell<DragState>> {
        self.drag_state.clone()
    }

    fn focus_manager(&self) -> &crate::focus::FocusManager {
        &self.focus
    }

    fn draw_focus_ring(&mut self, rect: Rect) {
        let theme = self.current_theme;
        let stroke_width = self.current_style.focus_ring_width;
        self.surface_stroke_rect(rect, theme.accent_fg, stroke_width);
        self.register_zone(WidgetId::new("chrome:focus-ring"), rect);
    }

    // ─── Error reporting ────────────────────────────────────────────

    /// Drain the `BackendError` `end_frame` recorded on a failed
    /// `EndDraw`, if any, since the last call. Mirrors
    /// [`Self::attach_surface`]/[`Self::attach_headless`]'s "surface is
    /// gone, `ensure_surface` recreates it lazily" recovery: this is the
    /// method a caller polls to learn that happened at all.
    fn last_error(&mut self) -> Option<BackendError> {
        self.last_error.take()
    }

    // ─── Platform services ────────────────────────────────────────────

    fn services(&self) -> &dyn PlatformServices {
        &self.services
    }

    // ─── Paint surface ─────────────────────────────────────────────────

    /// `WinBackend` implements [`PaintSurface`] directly (see this
    /// module's own `impl PaintSurface for WinBackend` block below), so
    /// this always answers `Some(self)` — never the `None` default
    /// `Backend::paint_surface` falls back to. Each verb degrades on its
    /// own (see e.g. `surface_measure_text`'s doc) when `self.surface`/
    /// `self.dwrite` aren't attached yet, matching `Backend::draw_*`'s
    /// existing "no surface yet" posture — there is no additional check
    /// to make here.
    fn paint_surface(&mut self) -> Option<&mut dyn PaintSurface> {
        Some(self)
    }

    // ─── Cursor ───────────────────────────────────────────────────────

    /// Maps `shape` onto a `SetCursor(LoadCursorW(..))` call via
    /// [`pointer_shape_to_win32_cursor`] and records it in
    /// `current_pointer_shape` so `win::run`'s `WM_SETCURSOR` handler can
    /// keep re-applying the same shape for as long as the pointer stays
    /// over the client area — see that field's doc comment for why a
    /// one-shot `SetCursor` call here isn't enough on its own. Always
    /// records the shape (portable, no WinAPI dependency); only the
    /// `SetCursor` call itself is Windows-only, mirroring every other
    /// `#[cfg(target_os = "windows")]` split in this file.
    fn set_cursor(&mut self, shape: PointerShape) -> bool {
        self.current_pointer_shape = shape;
        #[cfg(target_os = "windows")]
        {
            if self.hwnd.is_none() {
                // No window yet — matches `GtkBackend::set_cursor`'s
                // and `MacBackend::set_cursor`'s identical no-window
                // no-op posture.
                return false;
            }
            self.apply_current_cursor();
            true
        }
        #[cfg(not(target_os = "windows"))]
        {
            false
        }
    }

    // ─── Window control ─────────────────────────────────────────────────
    fn window(&mut self) -> Option<&mut dyn crate::backend::WindowControl> {
        #[cfg(target_os = "windows")]
        {
            self.hwnd?;
            Some(self)
        }
        #[cfg(not(target_os = "windows"))]
        {
            None
        }
    }

    // ─── Tray / status-bar icon ─────────────────────────────────────────
    /// Gated on `self.hwnd` for the same reason as [`Self::window`]:
    /// `Shell_NotifyIconW` needs a real `HWND` to own the icon and
    /// receive its callback message, which only exists once
    /// `attach_surface` has run.
    fn tray(&mut self) -> Option<&mut dyn crate::backend::TrayService> {
        #[cfg(target_os = "windows")]
        {
            self.hwnd?;
            Some(self)
        }
        #[cfg(not(target_os = "windows"))]
        {
            None
        }
    }

    // ─── Capability declaration ──────────────────────────────────────────

    /// Honest, not aspirational: the window + render-target bootstrap
    /// (`begin_frame`/`end_frame`) and the three window-lifecycle events
    /// the message loop itself needs (`WindowResized`/`DpiChanged`/
    /// `WindowClose`); the rest of the input table — mouse buttons/
    /// motion/wheel, `WM_KEYDOWN`/`WM_CHAR`, and focus — all dispatched
    /// directly from `win::run`'s `WndProc`; the queue-adapter drain is
    /// wired but nothing feeds that queue from the live `WndProc` yet.
    ///
    /// `mouse`/`scroll`/`drag` are declared `true`: the translators are
    /// wired (`WM_LBUTTONDOWN`/`WM_LBUTTONUP`/`WM_MOUSEMOVE`/
    /// `WM_MOUSEWHEEL`/`WM_MOUSEHWHEEL` all reach `dispatch_event`), and
    /// the painted-text sink means a scenario that now runs instead of
    /// skipping fails on real signal rather than panicking.
    ///
    /// `text_selection` is declared `true`: `register_text_region`/
    /// `cancel_text_selection_drag` are both overridden, backed by the
    /// same `crate::text_selection::TextSelectionState` `GtkBackend`/
    /// `TuiBackend` embed, so `panel.drag_select_copy` (which
    /// `requires: ["text_selection"]`) now runs instead of skipping.
    fn backend_caps(&self) -> crate::backend::BackendCaps {
        // A genuine struct literal (not `let mut caps = ...; caps.field =
        // true;`), matching every other backend's `backend_caps` shape —
        // `tests/conformance/caps.rs`'s `BackendSource::declared` parses
        // this method's source for `<field>: true,` lines, so an
        // assignment-statement form would silently parse as declaring nothing.
        #[cfg(target_os = "windows")]
        {
            // File dialogs (`IFileOpenDialog`/`IFileSaveDialog`) and
            // notifications (`Shell_NotifyIconW`) go through COM/Shell APIs
            // independent of the Direct2D rasteriser, so they're honestly `true`
            // on Windows itself.
            //
            // `folder_dialogs`: the same `IFileOpenDialog`, with
            // `FOS_PICKFOLDERS` set — see
            // `src/win/services.rs::win_show_folder_open_dialog`.
            //
            // `native_dialogs`: `show_message_dialog` now shows a real
            // `TaskDialogIndirect` alert and returns the chosen button's id —
            // see `src/win/services.rs::win_show_message_dialog`. `CAP_CONTRACTS`'s
            // `native_dialogs` entry is `Unprovable` (every backend implements it),
            // so this declaration isn't source-checked; it's true because the
            // alert is real.
            //
            // `pointer_cursor`: `set_cursor` now drives a real
            // `SetCursor`/`WM_SETCURSOR` round-trip instead of the trait's no-op
            // default — see `Self::set_cursor` / `Self::apply_current_cursor`.
            //
            // `mouse`/`scroll`/`drag`: the translators are wired —
            // `WM_LBUTTONDOWN`/`WM_LBUTTONUP`/`WM_MOUSEMOVE` reach
            // `dispatch_event` as `MouseDown`/`MouseUp`/`MouseMoved`, and
            // `WM_MOUSEWHEEL`/`WM_MOUSEHWHEEL` reach it as `Scroll` — so a
            // press → move → release sequence is a real drag.
            //
            // `text_selection`: `register_text_region` and
            // `cancel_text_selection_drag` are both overridden, backed by the
            // shared `crate::text_selection::TextSelectionState` GTK/TUI also
            // embed — `panel.drag_select_copy` (which `requires: ["text_selection"]`)
            // now runs instead of skipping.
            crate::backend::BackendCaps {
                file_dialogs: true,
                folder_dialogs: true,
                native_dialogs: true,
                notifications: true,
                pointer_cursor: true,
                mouse: true,
                scroll: true,
                drag: true,
                text_selection: true,
                // `register_font_from_memory`/`set_nerd_font_fallback`:
                // both overridden above, backed by real
                // DirectWrite calls (`crate::win::text::register_font_from_memory`
                // / `build_nerd_font_fallback`) rather than the trait's
                // no-op default.
                app_font_registration: true,
                // `generic_font_families`: `set_editor_font`/
                // `set_ui_font` are both overridden above and now resolve
                // CSS/Pango generic tokens to their DirectWrite defaults
                // (`DEFAULT_EDITOR_FONT_FAMILY`/`DEFAULT_UI_FONT_FAMILY`)
                // via `parse_ui_font_desc`/`GenericFamily::parse` instead
                // of treating them as an unresolvable literal family name.
                generic_font_families: true,
                // `window` is overridden below and returns
                // `Some` once `attach_surface` has stashed a real
                // `HWND` — see `impl WindowControl for WinBackend`'s doc
                // for which methods it backs with real `SetWindowPos`/
                // `ShowWindow`/`SetWindowTextW` calls versus report
                // `Unsupported` (`set_min_size`/`set_max_size`, which
                // would need `WM_GETMINMAXINFO` wired into `win::run`'s
                // `wndproc` to mean anything during a live interactive
                // resize — tracked as follow-up, not silently faked
                // here as a one-shot clamp).
                window_control: true,
                // `tray` is overridden below and returns
                // `Some` once `attach_surface` has stashed a real
                // `HWND` — see `impl TrayService for WinBackend`'s doc
                // for the real `Shell_NotifyIconW`/`TrackPopupMenuEx`
                // calls backing each method.
                tray: true,
                // `native_menu`: a real `HMENU` used to be built and attached here
                // via `SetMenu`, but that sits in the *non-client* area — exactly
                // the strip the `WM_NCCALCSIZE` handler (below) reclaims for the
                // app's own drawn caption. With both landed, the native menu was
                // permanently covered by the drawn band and unreachable, and
                // `window_chrome`'s custom caption stays; a native menu would need
                // the native caption back. So Win-GUI now matches `GtkBackend`/
                // `TuiBackend`: no `Backend` override at all, taking the trait's
                // no-op default — `install_menu_bar` callers get a painted in-window
                // `MenuBar` (`draw_menu_bar`) instead. Left `false` rather than
                // declared and unprovable — the honesty check requires *no*
                // `install_menu_bar`/`show_context_menu` override to back a `false`
                // here, which holds: this backend has neither.
                //
                // `window_chrome`: `toggle_window_maximize` is overridden below (real
                // `IsZoomed`/`ShowWindow` calls), and `win::run`'s `wndproc` now
                // handles `WM_NCCALCSIZE`/`WM_NCHITTEST` to fold a host's drawn
                // title-bar band into the native caption the way `GtkBackend`'s CSD
                // titlebar already does — see [`Self::nc_hit_test`]'s doc for the
                // classification and `App::render_content`'s doc for the consumer-side
                // branch this un-gates. Declaring this before `win::run` grew that
                // handling would have just stacked a second, always-drawn band under
                // the real native caption instead of replacing it.
                window_chrome: true,
                ..crate::backend::BackendCaps::empty()
            }
        }
        #[cfg(not(target_os = "windows"))]
        {
            crate::backend::BackendCaps::empty()
        }
    }

    // ─── Window chrome ──────────────────────────────────────────────────
    //
    // Unlike `GtkBackend`/`MacBackend`, Win-GUI keeps its native
    // `WS_OVERLAPPEDWINDOW` non-client frame (`win::run`'s window creation
    // — this issue's other half handles only `WM_NCCALCSIZE`/
    // `WM_NCHITTEST`, not `WS_POPUP`/undecorated CSD). Windows itself
    // still owns drag-to-move and double-click-to-maximize for any point
    // `WM_NCHITTEST` classifies as `HTCAPTION` (`win::run`'s `wndproc`,
    // via `Self::nc_hit_test`) — `DefWindowProcW`'s own non-client move
    // loop handles both without this backend ever calling
    // `Backend::begin_window_drag`/`begin_window_resize`, so only
    // `toggle_window_maximize` below is overridden: a host that wants a
    // "Maximize" menu item or keybinding alongside the pointer gesture has
    // something real to call. `CAP_CONTRACTS`'s `window_chrome` entry is
    // `Proof::Any` — one overridden method is enough to make the
    // `backend_caps` declaration honest.

    /// `IsZoomed`/`ShowWindow(SW_MAXIMIZE/SW_RESTORE)` — mirrors
    /// `GtkBackend::toggle_window_maximize`/`MacBackend::toggle_window_maximize`.
    /// Returns `false` when this backend owns no window yet (matching
    /// every other backend's `begin_window_drag`-family contract).
    fn toggle_window_maximize(&mut self) -> bool {
        #[cfg(target_os = "windows")]
        {
            let Some(hwnd) = self.hwnd else {
                return false;
            };
            // SAFETY: `hwnd` is `self.hwnd`, this backend's own live
            // window; both calls take only a handle (plus, for
            // `ShowWindow`, a plain show-command enum).
            let target = if unsafe { IsZoomed(hwnd) }.as_bool() {
                SW_RESTORE
            } else {
                SW_MAXIMIZE
            };
            // SAFETY: same as `IsZoomed` above — `hwnd` is still
            // `self.hwnd`.
            unsafe {
                let _ = ShowWindow(hwnd, target);
            }
            true
        }
        #[cfg(not(target_os = "windows"))]
        {
            false
        }
    }

    // ─── Measurement ──────────────────────────────────────────────────

    fn line_height(&self) -> f32 {
        self.current_line_height
    }

    fn char_width(&self) -> f32 {
        self.current_char_width
    }

    /// Forwards to [`Self::set_current_line_height`] — the
    /// `Backend`-trait-object-reachable twin of that inherent method, the
    /// Win-GUI counterpart of `GtkBackend`'s / `MacBackend`'s overrides of
    /// the same trait method.
    fn set_current_line_height(&mut self, line_height: f32) {
        WinBackend::set_current_line_height(self, line_height);
    }

    /// Forwards to [`Self::set_current_char_width`] — see
    /// [`Backend::set_current_line_height`]'s doc.
    fn set_current_char_width(&mut self, char_width: f32) {
        WinBackend::set_current_char_width(self, char_width);
    }

    /// Same value as [`Self::char_width`] (the *editor* font's advance)
    /// even though [`Self::draw_list`] (`super::list::draw_list`) now
    /// paints row text through `self.chrome_dwrite` — this
    /// backend has no `chrome_char_width` field of its own to report
    /// instead (unlike `GtkBackend::current_chrome_char_width`, a real
    /// per-frame Pango re-measurement of `ui_font`). A consumer budgeting
    /// `ListView` row width against this value may therefore get a
    /// slightly wrong estimate when the chrome and editor fonts differ
    /// in advance width; adding a real `chrome_char_width` field
    /// (mirroring GTK's) is tracked separately, unchanged by this
    /// issue.
    fn list_char_width(&self) -> f32 {
        self.current_char_width
    }

    /// Real DirectWrite measurement via `DWrite::measure_text` against
    /// `chrome_dwrite`/`dwrite` — the same per-role handle
    /// [`Self::surface_draw_text_run_with_role`] already resolves,
    /// including its "chrome falls back to the editor handle
    /// if no live chrome one exists yet" degrade. Before a surface has
    /// attached (`dwrite`/`chrome_dwrite` both still `None`, e.g. an app
    /// measuring a `Dialog` before the first frame), falls back to a
    /// `current_char_width`-scaled estimate — the same "degrade, don't
    /// panic" convention [`Self::draw_tree`]'s own doc describes for the
    /// pre-attach window on this backend.
    fn measure_text(&self, text: &str, role: crate::FontRole) -> (f32, f32) {
        #[cfg(target_os = "windows")]
        {
            let dwrite = match role {
                crate::FontRole::Chrome => self.chrome_dwrite.as_ref().or(self.dwrite.as_ref()),
                crate::FontRole::Editor => self.dwrite.as_ref(),
            };
            if let Some(dwrite) = dwrite {
                if let Ok((w, h)) = dwrite.measure_text(text) {
                    return (w, h);
                }
            }
        }
        let _ = role;
        (
            text.chars().count() as f32 * self.current_char_width,
            self.current_line_height,
        )
    }

    /// Store the editor font family + size for the next
    /// [`Self::attach_surface`]/[`Self::ensure_surface`] call to build an
    /// `IDWriteTextFormat` from. Mirrors `GtkBackend::set_editor_font`:
    /// a live surface doesn't rebuild its `IDWriteTextFormat`
    /// immediately on a runtime font change — same limitation the GTK
    /// backend has today (its Pango layout is rebuilt fresh every frame
    /// from these fields instead, which this backend's once-per-surface
    /// DirectWrite bootstrap doesn't yet mirror). A future issue can wire
    /// a live-reload path through `win::run`'s `WM_PAINT` handler if that
    /// gap needs closing.
    fn set_editor_font(&mut self, family: &str, size_pt: f32) {
        #[cfg(target_os = "windows")]
        {
            // A CSS/Pango generic token resolves to its DirectWrite default
            // immediately — `monospace` has no installed-family lookup to run,
            // only `DEFAULT_EDITOR_FONT_FAMILY` to substitute in. `sans-serif`/
            // `system-ui` aren't monospace (this method's doc requires that), but
            // there's no error channel to reject the mismatch through, so they
            // resolve honestly to the chrome default rather than being treated as
            // an unknown literal family name.
            self.editor_font_family = match GenericFamily::parse(family) {
                Some(GenericFamily::Monospace) => DEFAULT_EDITOR_FONT_FAMILY.to_string(),
                Some(GenericFamily::SansSerif | GenericFamily::SystemUi) => {
                    DEFAULT_UI_FONT_FAMILY.to_string()
                }
                None => family.to_string(),
            };
            self.editor_font_size_pt = size_pt;
        }
        #[cfg(not(target_os = "windows"))]
        {
            let _ = (family, size_pt);
        }
    }

    // ─── Drawing ──────────────────────────────────────────────────────

    /// Real Direct2D/DirectWrite rasteriser via `win::tree` once a
    /// surface is attached. See [`Self::draw_status_bar`]'s doc for the
    /// "surface not attached yet" fallback posture. `draw_tree` returns
    /// `()` per the trait (unlike the chrome rasterisers) — hosts get
    /// hit-test data from [`Self::tree_layout`] instead.
    ///
    /// `Tree` is `ChromePrimitive::Tree` — row labels/badges/
    /// chevrons are chrome, not editor content, same "whole-primitive
    /// font swap, `line_height` stays at the editor's own metrics" shape
    /// `MacBackend::draw_tree`/`GtkBackend::draw_tree` already ship —
    /// paints through `chrome_dwrite`, falling back to the
    /// editor `dwrite` handle if no live chrome one exists yet (same
    /// "degrade, don't panic" convention as
    /// `surface_draw_text_run_with_role`).
    fn draw_tree(&mut self, rect: Rect, tree: &TreeView) {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            let dwrite = self.chrome_dwrite.as_ref().unwrap_or(dwrite);
            super::tree::draw_tree(
                &surface.target,
                dwrite,
                rect,
                tree,
                self.current_line_height,
                self.nerd_fonts_enabled,
                &self.current_theme,
            );
            return;
        }
        // No surface/DWrite yet (fresh backend, device lost, or a
        // non-Windows host, where this module never compiles) — paint
        // nothing rather than panic; the next real
        // `attach_surface`/`attach_headless` resumes painting.
        let _ = (rect, tree);
    }

    /// see [`Self::draw_tree`]'s doc. `List` is
    /// `ChromePrimitive::List` — see `draw_tree`'s note for the
    /// font-swap shape.
    fn draw_list(&mut self, rect: Rect, list: &ListView) {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            let dwrite = self.chrome_dwrite.as_ref().unwrap_or(dwrite);
            super::list::draw_list(
                &surface.target,
                dwrite,
                rect,
                list,
                self.current_line_height,
            );
            return;
        }
        // See `draw_tree`'s doc for why this degrades to a no-op instead
        // of panicking.
        let _ = (rect, list);
    }

    /// See [`Self::draw_status_bar`]'s doc for the "surface not
    /// attached yet" fallback posture.
    /// `DataTable` is not `ChromePrimitive`/`EditorClassPrimitive`-listed
    /// — it's chrome by the `crate::font_role` module's default (see that
    /// module's doc) — so this passes `chrome_dwrite`, falling back to
    /// the editor `dwrite` handle if no live chrome one exists yet, same
    /// "degrade, don't panic" convention as
    /// `Self::surface_draw_text_run_with_role`. [`super::data_table::draw_data_table`]
    /// builds its own [`super::surface::D2dSurface`] adapter from
    /// whichever `dwrite` is passed in here rather than reaching
    /// `WinBackend`'s own [`PaintSurface`] impl, so inverting that impl's
    /// default alone would not have fixed this call site.
    fn draw_data_table(
        &mut self,
        rect: Rect,
        table: &crate::DataTable,
        hovered_idx: Option<usize>,
    ) -> crate::DataTableLayout {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            let dwrite = self.chrome_dwrite.as_ref().unwrap_or(dwrite);
            return super::data_table::draw_data_table(
                &surface.target,
                dwrite,
                rect,
                table,
                self.current_line_height,
                hovered_idx,
            );
        }
        // No surface/DWrite yet — compute the real layout via the same
        // nominal measurer `data_table_layout` falls back to, and paint
        // nothing. `hovered_idx` only affects painting, so
        // it's unused on this path.
        let _ = hovered_idx;
        super::data_table::win_data_table_layout(
            &NominalTextMeasure {
                char_width: self.current_char_width,
            },
            rect,
            table,
            self.current_line_height,
        )
    }

    /// [`Self::draw_data_table`], but honouring an optional
    /// [`crate::primitives::data_table::DataTableGlyphs`] override for the
    /// sort-direction glyphs — `glyphs: None` reproduces
    /// [`Self::draw_data_table`] exactly.
    fn draw_data_table_with_glyphs(
        &mut self,
        rect: Rect,
        table: &crate::DataTable,
        hovered_idx: Option<usize>,
        glyphs: Option<&crate::primitives::data_table::DataTableGlyphs>,
    ) -> crate::DataTableLayout {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            let dwrite = self.chrome_dwrite.as_ref().unwrap_or(dwrite);
            return super::data_table::draw_data_table_with_glyphs(
                &surface.target,
                dwrite,
                rect,
                table,
                self.current_line_height,
                hovered_idx,
                glyphs,
                self.nerd_fonts_enabled,
            );
        }
        #[cfg(not(target_os = "windows"))]
        let _ = glyphs;
        self.draw_data_table(rect, table, hovered_idx)
    }

    /// Pure measurement — only needs `self.dwrite`, not a live
    /// render target. See [`Self::status_bar_layout`]'s doc. Prefers
    /// `chrome_dwrite`, matching [`Self::draw_data_table`]'s paint font
    /// — both must resolve the same handle or column widths measured
    /// here would disagree with what the paint actually fits.
    fn data_table_layout(&self, rect: Rect, table: &crate::DataTable) -> crate::DataTableLayout {
        #[cfg(target_os = "windows")]
        if let Some(dwrite) = self.chrome_dwrite.as_ref().or(self.dwrite.as_ref()) {
            return super::data_table::win_data_table_layout(
                dwrite,
                rect,
                table,
                self.current_line_height,
            );
        }
        super::data_table::win_data_table_layout(
            &NominalTextMeasure {
                char_width: self.current_char_width,
            },
            rect,
            table,
            self.current_line_height,
        )
    }

    /// GTK's twin (`GtkBackend::list_hscrollbar`) builds the
    /// `Scrollbar` directly from `self.current_char_width` rather than
    /// delegating to [`ListView::hscrollbar`] — that primitive method
    /// treats `max_content_width` as already being in the caller's
    /// native unit (correct for TUI's 1-char-per-cell grid, wrong for a
    /// pixel backend where chars must first be scaled by char width).
    /// Cross-platform: no Direct2D/DirectWrite call needed, so this
    /// compiles (and is exercised by `cargo check --features win`) on
    /// every host, not just `target_os = "windows"`.
    fn list_hscrollbar(&self, rect: Rect, list: &ListView) -> Option<crate::Scrollbar> {
        let char_w = self.current_char_width;
        let max_w_chars = list.max_content_width? as f32;
        let content_px = max_w_chars * char_w;
        let border_inset = if list.bordered { char_w } else { 0.0 };
        let visible_px = (rect.width - 2.0 * border_inset).max(0.0);
        if content_px <= visible_px {
            return None;
        }
        let row_h = self.current_line_height;
        let track = crate::primitives::list::hscrollbar_track(rect, list.bordered, char_w, row_h);
        Some(crate::Scrollbar::horizontal(
            list.id,
            track,
            list.h_scroll as f32 * char_w,
            content_px,
            visible_px,
            row_h,
        ))
    }

    /// `vscrollbar` deals purely in row counts/row-height, so
    /// unlike [`Self::list_hscrollbar`] the primitive's own geometry
    /// method is unit-correct for every backend — see
    /// [`ListView::vscrollbar`]. Cross-platform, same reasoning as
    /// `list_hscrollbar`.
    fn list_vscrollbar(&self, rect: Rect, list: &ListView) -> Option<crate::Scrollbar> {
        list.vscrollbar(rect, self.current_line_height)
    }

    fn list_layout(&self, rect: Rect, list: &ListView) -> crate::ListViewLayout {
        // `win_list_layout` is pure geometry — no Direct2D/DirectWrite type
        // in its signature — so it can be called directly instead of being
        // duplicated inline here.
        super::list::win_list_layout(
            list,
            rect,
            self.current_line_height,
            self.current_char_width,
        )
    }

    /// See [`Self::draw_tree`]'s doc.
    ///
    /// Shared field-kind painting lives in
    /// [`crate::primitives::form::paint`] now — see that fn's doc for
    /// why `FieldKind::Toolbar` is painted here instead (as plain
    /// per-button text, matching this backend's behaviour —
    /// `win::toolbar`'s full chrome isn't wired into `Form` fields; see
    /// `win::form`'s module doc), after `paint` releases its exclusive
    /// borrow of `self`.
    fn draw_form(&mut self, rect: Rect, form: &Form) {
        #[cfg(target_os = "windows")]
        if self.dwrite.is_some() && self.surface.is_some() {
            // `Form` is chrome, not editor content (it's not in
            // `crate::font_role::EditorClassPrimitive::ALL`) — prefer
            // `chrome_dwrite`, falling back to the editor `dwrite` handle
            // if no live chrome one exists yet, same "degrade, don't
            // panic" convention as `Self::surface_draw_text_run_with_role`.
            // `crate::primitives::form::paint` below paints through
            // `self` (now chrome-resolving by default — see
            // `impl PaintSurface for WinBackend`'s doc), so this layout
            // must measure against the same handle or field widths would
            // disagree with what the paint actually fits.
            let dwrite = self
                .chrome_dwrite
                .as_ref()
                .or(self.dwrite.as_ref())
                .expect("checked Some by the `if` guard above");
            let flayout =
                super::form::win_form_layout(dwrite, rect, form, self.current_line_height);
            let theme = Theme::default();
            let origin = Point::new(rect.x, rect.y);
            crate::primitives::form::paint(form, &flayout, self, &theme, origin);

            // A toolbar button's label is chrome too — read through
            // `chrome_dwrite` (falling back to `dwrite`) directly rather
            // than the inherent `Self::measure_text`/`Self::draw_text`
            // helpers, which always resolve the editor handle. Hoisted
            // above the loop (rather than re-derived per `vf`): the `if`
            // guard above already proved both `self.surface` and
            // `self.dwrite` are `Some` for the whole method body, so
            // re-checking per-iteration can never actually fail.
            let surface = self
                .surface
                .as_ref()
                .expect("checked Some by the `if` guard above");
            let dwrite = self
                .chrome_dwrite
                .as_ref()
                .or(self.dwrite.as_ref())
                .expect("checked Some by the `if` guard above");
            let line_height = self.current_line_height;
            let char_width = self.current_char_width;

            for vf in &flayout.visible_fields {
                let Some(field) = form.fields.get(vf.field_idx) else {
                    continue;
                };
                let FieldKind::Toolbar(toolbar) = &field.kind else {
                    continue;
                };
                let field_fg = if field.disabled {
                    theme.muted_fg
                } else {
                    theme.foreground
                };
                for (item_id, item_rect) in &vf.item_bounds {
                    let btn = toolbar.buttons.iter().find_map(|b| {
                        super::form::toolbar_item(&field.id, b)
                            .filter(|(id, _)| id == item_id)
                            .map(|_| b)
                    });
                    let r = Rect::new(
                        origin.x + item_rect.x,
                        origin.y + item_rect.y,
                        item_rect.width,
                        item_rect.height,
                    );
                    // Degrade to the same nominal char-width estimate
                    // every other font-role call site in this impl falls
                    // back to on a measurement failure (see
                    // `Self::surface_measure_text`'s doc) rather than a
                    // zero size, which would collapse the label to a
                    // zero-width paint instead of a plausible guess.
                    match btn {
                        Some(ToolbarButton::Action { label, enabled, .. }) => {
                            let fg = if *enabled { field_fg } else { theme.muted_fg };
                            let (tw, th) = dwrite.measure_text(label).unwrap_or_else(|_| {
                                (nominal_text_width(label, char_width), line_height)
                            });
                            let ty = r.y + (r.height - th) / 2.0;
                            let _ = dwrite.draw_text(
                                &surface.target,
                                label,
                                Rect::new(r.x, ty, tw, th),
                                fg,
                            );
                        }
                        Some(ToolbarButton::Label { text, fg }) => {
                            let color = fg.unwrap_or(field_fg);
                            let (tw, th) = dwrite.measure_text(text).unwrap_or_else(|_| {
                                (nominal_text_width(text, char_width), line_height)
                            });
                            let ty = r.y + (r.height - th) / 2.0;
                            let _ = dwrite.draw_text(
                                &surface.target,
                                text,
                                Rect::new(r.x, ty, tw, th),
                                color,
                            );
                        }
                        _ => {}
                    }
                }
            }
            return;
        }
        // See `draw_tree`'s doc for why this degrades to a no-op instead
        // of panicking.
        let _ = (rect, form);
    }

    /// Real Direct2D/DirectWrite rasteriser via `win::palette` once a
    /// surface is attached. See [`Self::draw_status_bar`]'s doc for the
    /// "surface not attached yet" fallback posture.
    fn draw_palette(&mut self, rect: Rect, palette: &Palette) {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            // `Palette` is chrome by the `crate::font_role` module's
            // default (not `EditorClassPrimitive`-listed) — prefer
            // `chrome_dwrite`, falling back to the editor `dwrite`
            // handle, same "degrade, don't panic" convention as
            // `Self::surface_draw_text_run_with_role`. `win::palette`
            // builds its own adapter from whichever handle is passed in
            // here rather than reaching `WinBackend`'s own
            // [`PaintSurface`] impl.
            let dwrite = self.chrome_dwrite.as_ref().unwrap_or(dwrite);
            let line_height = self.current_line_height;
            if rect.width < 20.0 || rect.height < line_height * 4.0 {
                return;
            }
            let theme = crate::theme::Theme::default();
            let style = self.style();
            let (palette_layout, rows_h) = crate::primitives::palette::native_surface_paint::layout(
                rect.width,
                rect.height,
                palette,
                line_height,
            );
            // Calls the shared paint directly (rather than
            // through `super::palette::draw_palette`, whose public
            // signature stays additive-only and so cannot take a live
            // `&Style`) so this live backend path honours
            // `Self::set_style` overrides.
            let mut surf = super::surface::D2dSurface {
                target: &surface.target,
                dwrite: Some(dwrite),
            };
            crate::primitives::palette::native_surface_paint::paint(
                palette,
                rect,
                &palette_layout,
                rows_h,
                line_height,
                self.nerd_fonts_enabled,
                &mut surf,
                &theme,
                &style,
            );
            return;
        }
        // See `draw_tree`'s doc for why this degrades to a no-op instead
        // of panicking.
        let _ = (rect, palette);
    }

    /// Pure geometry — needs no live surface, unlike
    /// [`Self::draw_palette`], so this doesn't gate on one being attached.
    /// `win::palette` itself is Windows-only (real `Direct2D`/`DirectWrite`
    /// types), same `#[cfg(target_os = "windows")]` split every other
    /// method on this impl uses to stay a type-check-only stub elsewhere —
    /// so this calls the shared, target-agnostic
    /// [`crate::primitives::palette::native_surface_paint::layout`]
    /// directly rather than reaching into that Windows-only
    /// module.
    fn palette_layout(&self, rect: Rect, palette: &Palette) -> crate::PaletteLayout {
        crate::primitives::palette::native_surface_paint::layout(
            rect.width,
            rect.height,
            palette,
            self.current_line_height,
        )
        .0
    }

    /// See [`Self::draw_status_bar`]'s doc for the "surface not
    /// attached yet" fallback posture.
    fn draw_settings_chrome(
        &mut self,
        rect: Rect,
        header_text: &str,
        query: &str,
        placeholder: &str,
        active: bool,
    ) {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            // The settings header/search box is chrome — same
            // `chrome_dwrite`-preferring swap as `Self::draw_palette`.
            let dwrite = self.chrome_dwrite.as_ref().unwrap_or(dwrite);
            super::form::draw_settings_chrome(
                &surface.target,
                dwrite,
                rect,
                self.current_line_height,
                header_text,
                query,
                placeholder,
                active,
            );
            return;
        }
        // See `draw_tree`'s doc for why this degrades to a no-op instead
        // of panicking.
        let _ = (rect, header_text, query, placeholder, active);
    }

    /// Real Direct2D/DirectWrite rasteriser via `win::status_bar`
    /// once a surface is attached. Falls back to
    /// [`super::status_bar::win_status_bar_layout`] with a
    /// [`NominalTextMeasure`] otherwise —
    /// `self.surface`/`self.dwrite` are always populated together by
    /// [`Self::attach_surface`], so that only happens for a standalone
    /// `WinBackend` no window has ever attached to yet.
    ///
    /// `StatusBar` is `ChromePrimitive::StatusBar` — the segment
    /// text is chrome, not editor content, so this paints through
    /// [`ChromeSurface`] (routes text through `chrome_dwrite`, falling
    /// back to the editor `dwrite` handle) rather than `self` directly
    /// (which would paint through `self.dwrite`, the *editor* font, via
    /// `WinBackend`'s own [`PaintSurface`] impl) — mirrors
    /// `MacBackend::status_bar_paint_scaled`'s identical `ChromeSurface`
    /// switch.
    fn draw_status_bar_interactive(
        &mut self,
        rect: Rect,
        bar: &StatusBar,
        interaction: &crate::interaction::InteractionState,
    ) -> StatusBarLayout {
        let (hovered_id, pressed_id) = (interaction.hovered(), interaction.pressed());
        #[cfg(target_os = "windows")]
        if self.surface.is_some() && self.dwrite.is_some() {
            let theme = self.current_theme;
            let mut surface = ChromeSurface { backend: self };
            let layout = crate::primitives::status_bar::native_surface_paint::paint(
                bar,
                &mut surface,
                &theme,
                rect.x,
                rect.y,
                rect.width,
                rect.height,
                hovered_id,
                pressed_id,
            );
            // A status-bar segment drawn inside the AppShell
            // title-bar band (e.g. vimcode's inline minimize/maximize/
            // close buttons) needs its own `register_zone` entry — see
            // `Self::nc_hit_test`'s doc — or the whole band keeps
            // reading as `HTCAPTION` and the OS swallows the click
            // before it ever reaches the segment as a `MouseDown`.
            // Harmless outside the band: `nc_hit_test` only treats a
            // zone as an exclusion when it falls inside the registered
            // `TITLE_BAR_DRAG_ZONE`.
            self.register_status_bar_segment_zones(rect, &layout);
            return layout;
        }
        // No surface/DWrite yet — compute the real layout via the same
        // nominal measurer `status_bar_layout` falls back to, and paint
        // nothing. `hovered_id`/`pressed_id` only affect
        // painting, so they're unused on this path.
        let _ = (hovered_id, pressed_id);
        let layout = super::status_bar::win_status_bar_layout(
            &NominalTextMeasure {
                char_width: self.current_char_width,
            },
            rect,
            bar,
        );
        self.register_status_bar_segment_zones(rect, &layout);
        layout
    }

    #[allow(deprecated)] // returns the deprecated `TabBarHits` — issue #823
    fn draw_tab_bar(
        &mut self,
        rect: Rect,
        bar: &TabBar,
        hovered_close_tab: Option<usize>,
    ) -> TabBarHits {
        // Icon-less bars are the empty-sidecar case of the icon path (see
        // `crate::Backend::draw_tab_bar_icons`'s doc) — one paint loop to
        // keep in sync, same as `GtkBackend`/`TuiBackend`.
        self.draw_tab_bar_icons(rect, bar, &[], hovered_close_tab)
    }

    /// `TabBarLayout`-returning counterpart to [`Self::draw_tab_bar`].
    fn draw_tab_bar_layout(
        &mut self,
        rect: Rect,
        bar: &TabBar,
        hovered_close_tab: Option<usize>,
    ) -> TabBarLayout {
        self.draw_tab_bar_icons_layout(rect, bar, &[], hovered_close_tab)
    }

    /// See [`Self::draw_status_bar`]'s doc for the "surface not
    /// attached yet" fallback posture.
    ///
    /// `TabBar` is `ChromePrimitive::TabBar` — see
    /// [`Self::draw_tree`]'s note for the font-swap shape. The
    /// no-paint [`Self::tab_bar_layout_icons`] twin swaps the same way,
    /// so hit-testing agrees with what this paints.
    #[allow(deprecated)] // returns the deprecated `TabBarHits` — issue #823
    fn draw_tab_bar_icons(
        &mut self,
        rect: Rect,
        bar: &TabBar,
        icons: &[Option<crate::TabIcon>],
        hovered_close_tab: Option<usize>,
    ) -> TabBarHits {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            let dwrite = self.chrome_dwrite.as_ref().unwrap_or(dwrite);
            return super::tab_bar::draw_tab_bar_icons(
                &surface.target,
                dwrite,
                rect,
                bar,
                icons,
                hovered_close_tab,
                &self.current_theme,
            );
        }
        // No surface/DWrite yet — compute the real layout via the same
        // nominal measurer `tab_bar_layout_icons` falls back to, and
        // paint nothing. `hovered_close_tab` only affects
        // painting, so it's unused on this path.
        let _ = hovered_close_tab;
        super::tab_bar::win_tab_bar_layout_icons(
            &NominalTextMeasure {
                char_width: self.current_char_width,
            },
            rect,
            bar,
            icons,
        )
    }

    /// See [`Self::draw_status_bar`]'s doc for the "surface not
    /// attached yet" fallback posture. `TabBarLayout`-returning
    /// counterpart to [`Self::draw_tab_bar_icons`] above.
    fn draw_tab_bar_icons_layout(
        &mut self,
        rect: Rect,
        bar: &TabBar,
        icons: &[Option<crate::TabIcon>],
        hovered_close_tab: Option<usize>,
    ) -> TabBarLayout {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            let dwrite = self.chrome_dwrite.as_ref().unwrap_or(dwrite);
            return super::tab_bar::draw_tab_bar_icons_layout(
                &surface.target,
                dwrite,
                rect,
                bar,
                icons,
                hovered_close_tab,
                &self.current_theme,
            );
        }
        // See `draw_tab_bar_icons`'s doc.
        let _ = hovered_close_tab;
        super::tab_bar::win_tab_bar_native_layout_icons(
            &NominalTextMeasure {
                char_width: self.current_char_width,
            },
            rect,
            bar,
            icons,
        )
    }

    /// [`Self::draw_tab_bar_icons`], but honouring an optional
    /// [`crate::primitives::tab_bar::TabBarGlyphs`] override for the
    /// close/dirty mark — `glyphs: None` reproduces
    /// [`Self::draw_tab_bar_icons`] exactly. `chrome` is unused: the
    /// Windows rasteriser has no bracket-chrome support (see
    /// `super::tab_bar`'s module doc), matching the trait default's
    /// own posture of ignoring `chrome` on backends without it.
    #[allow(deprecated)] // returns the deprecated `TabBarHits` — issue #823
    fn draw_tab_bar_with_chrome_and_glyphs(
        &mut self,
        rect: Rect,
        bar: &TabBar,
        hovered_close_tab: Option<usize>,
        chrome: &TabChrome,
        glyphs: Option<&crate::primitives::tab_bar::TabBarGlyphs>,
    ) -> TabBarHits {
        let _ = chrome;
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            let dwrite = self.chrome_dwrite.as_ref().unwrap_or(dwrite);
            return super::tab_bar::draw_tab_bar_icons_with_glyphs(
                &surface.target,
                dwrite,
                rect,
                bar,
                &[],
                hovered_close_tab,
                &self.current_theme,
                glyphs,
                self.nerd_fonts_enabled,
            );
        }
        #[cfg(not(target_os = "windows"))]
        let _ = glyphs;
        self.draw_tab_bar_icons(rect, bar, &[], hovered_close_tab)
    }

    /// See [`Self::draw_status_bar`]'s doc for the "surface not
    /// attached yet" fallback posture.
    ///
    /// `ActivityBar` is `ChromePrimitive::ActivityBar` — see
    /// [`Self::draw_tree`]'s note for the font-swap shape.
    fn draw_activity_bar(
        &mut self,
        rect: Rect,
        bar: &ActivityBar,
        hovered_idx: Option<usize>,
    ) -> Vec<ActivityBarRowHit> {
        // Track keyboard focus so `win::run::dispatch_event` can redirect
        // the next `KeyPressed` into this bar — same contract
        // `GtkBackend`/`MacBackend::draw_activity_bar` implement. Runs
        // regardless of whether a surface is attached yet.
        if bar.is_keyboard_focused {
            self.focused_activity_bar = Some(bar.id);
        }
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            let dwrite = self.chrome_dwrite.as_ref().unwrap_or(dwrite);
            return super::activity_bar::draw_activity_bar(
                &surface.target,
                dwrite,
                rect,
                bar,
                hovered_idx,
                &self.current_theme,
            );
        }
        // No surface/DWrite yet — return the real (pure-geometry) hit
        // list via `activity_bar_layout` and paint nothing.
        // `hovered_idx` only affects painting, so it's unused on this
        // path.
        let _ = hovered_idx;
        self.activity_bar_layout(rect, bar)
    }

    /// Pure measurement — only needs `self.dwrite`, not a live
    /// render target, so this works as soon as a surface has ever been
    /// attached (DirectWrite handles outlive device loss; see
    /// `Self::ensure_surface`'s docs).
    ///
    /// measures with `chrome_dwrite` (falling back to `dwrite`),
    /// matching [`Self::draw_status_bar_interactive`]'s paint font — a
    /// no-paint caller (hit-testing without repainting) must resolve the
    /// same segment widths the paint path produced, same contract
    /// `GtkBackend::status_bar_layout`'s `ui_font` swap documents.
    fn status_bar_layout(&self, rect: Rect, bar: &StatusBar) -> StatusBarLayout {
        #[cfg(target_os = "windows")]
        if let Some(dwrite) = self.chrome_dwrite.as_ref().or(self.dwrite.as_ref()) {
            return super::status_bar::win_status_bar_layout(dwrite, rect, bar);
        }
        super::status_bar::win_status_bar_layout(
            &NominalTextMeasure {
                char_width: self.current_char_width,
            },
            rect,
            bar,
        )
    }

    #[allow(deprecated)] // returns the deprecated `TabBarHits` — issue #823
    fn tab_bar_layout(&self, rect: Rect, bar: &TabBar) -> TabBarHits {
        self.tab_bar_layout_icons(rect, bar, &[])
    }

    /// `TabBarLayout`-returning counterpart to [`Self::tab_bar_layout`].
    fn resolve_tab_bar_layout(&self, rect: Rect, bar: &TabBar) -> TabBarLayout {
        self.resolve_tab_bar_layout_icons(rect, bar, &[])
    }

    /// See [`Self::status_bar_layout`]'s doc for why this only needs
    /// `self.dwrite`; see that method's doc for why this prefers
    /// `chrome_dwrite` — must agree with [`Self::draw_tab_bar_icons`]'s
    /// paint font.
    #[allow(deprecated)] // returns the deprecated `TabBarHits` — issue #823
    fn tab_bar_layout_icons(
        &self,
        rect: Rect,
        bar: &TabBar,
        icons: &[Option<crate::TabIcon>],
    ) -> TabBarHits {
        #[cfg(target_os = "windows")]
        if let Some(dwrite) = self.chrome_dwrite.as_ref().or(self.dwrite.as_ref()) {
            return super::tab_bar::win_tab_bar_layout_icons(dwrite, rect, bar, icons);
        }
        super::tab_bar::win_tab_bar_layout_icons(
            &NominalTextMeasure {
                char_width: self.current_char_width,
            },
            rect,
            bar,
            icons,
        )
    }

    /// See [`Self::status_bar_layout`]'s doc for why this only needs
    /// `self.dwrite`. `TabBarLayout`-returning counterpart to
    /// [`Self::tab_bar_layout_icons`] above; see that method's doc for
    /// why this prefers `chrome_dwrite`.
    fn resolve_tab_bar_layout_icons(
        &self,
        rect: Rect,
        bar: &TabBar,
        icons: &[Option<crate::TabIcon>],
    ) -> TabBarLayout {
        #[cfg(target_os = "windows")]
        if let Some(dwrite) = self.chrome_dwrite.as_ref().or(self.dwrite.as_ref()) {
            return super::tab_bar::win_tab_bar_native_layout_icons(dwrite, rect, bar, icons);
        }
        super::tab_bar::win_tab_bar_native_layout_icons(
            &NominalTextMeasure {
                char_width: self.current_char_width,
            },
            rect,
            bar,
            icons,
        )
    }

    /// Activity-bar layout needs no measurer at all (uniform
    /// `ACTIVITY_ROW_DIP` row height), so unlike its siblings this
    /// doesn't even need `self.dwrite` — only kept behind the
    /// `target_os = "windows"` gate for consistency with every other
    /// method in this file.
    fn activity_bar_layout(&self, rect: Rect, bar: &ActivityBar) -> Vec<ActivityBarRowHit> {
        // Pure geometry (uniform `ACTIVITY_ROW_DIP` row height, no measurer
        // at all) — this is computed directly instead of reaching into the
        // Windows-only module. `ACTIVITY_ROW_DIP`'s value (48.0) matches the
        // module's per `PRIMITIVE_RULES.md`#713.
        const ACTIVITY_ROW_DIP: f32 = 48.0;
        bar.layout(rect.width, rect.height, ACTIVITY_ROW_DIP)
            .visible_items
            .into_iter()
            .map(|vi| {
                let item = match vi.side {
                    crate::primitives::activity_bar::ActivitySide::Top => {
                        &bar.top_items[vi.item_idx]
                    }
                    crate::primitives::activity_bar::ActivitySide::Bottom => {
                        &bar.bottom_items[vi.item_idx]
                    }
                };
                ActivityBarRowHit {
                    y_start: vi.bounds.y,
                    y_end: vi.bounds.y + vi.bounds.height,
                    id: item.id,
                    tooltip: item.tooltip.clone(),
                }
            })
            .collect()
    }

    /// Real Direct2D/DirectWrite rasteriser via `win::terminal` once a
    /// surface is attached. Mirrors `GtkBackend::draw_terminal`'s
    /// scrollbar handling (subtract the gutter from the cell area, paint
    /// cells, then paint the scrollbar over the freed strip) but skips
    /// the dirty-row cache — see `win::terminal`'s module doc for why
    /// that's a deliberate follow-up. See [`Self::draw_status_bar`]'s
    /// doc for the "surface not attached yet" fallback posture.
    /// Shared cell-grid painting lives in
    /// [`crate::primitives::terminal::paint`] now — see that fn's doc
    /// for the divergences (per-cell bold/italic/underline styling)
    /// resolved while unifying `gtk::terminal::draw_terminal_cells`,
    /// `macos::terminal::draw_terminal_cells` and
    /// `win::terminal::draw_terminal_cells` into one implementation.
    fn draw_terminal(&mut self, rect: Rect, term: &Terminal) {
        #[cfg(target_os = "windows")]
        if self.surface.is_some() {
            let lh = self.current_line_height;
            let cw = self.current_char_width;
            let theme = self.current_theme;

            let sb_width = match &term.scrollbar {
                Some(sb) => sb.width.map(|w| w as f32).unwrap_or(8.0),
                None => 0.0,
            };
            let cell_area_w = (rect.width - sb_width).max(0.0);

            // The terminal is editor-class — paint through
            // `EditorSurface` so its cell glyphs keep painting in the
            // editor font even though `WinBackend`'s own `PaintSurface`
            // impl now defaults to `chrome_dwrite` (see that impl's
            // doc).
            let mut surface = EditorSurface { backend: self };
            crate::primitives::terminal::paint(
                term,
                &mut surface,
                &theme,
                rect.x,
                rect.y,
                cell_area_w,
                rect.height,
                lh,
                cw,
                None,
            );

            if let Some(ref sb_state) = term.scrollbar {
                let sb = crate::primitives::scrollbar::Scrollbar::vertical(
                    term.id,
                    Rect::new(rect.x + cell_area_w, rect.y, sb_width, rect.height),
                    sb_state.effective_scroll_offset() as f32,
                    sb_state.total_lines as f32,
                    sb_state.visible_lines as f32,
                    lh,
                );
                crate::primitives::scrollbar::native_surface_paint::paint(&sb, self, &theme);
            }
            return;
        }
        // See `draw_tree`'s doc for why this degrades to a no-op instead
        // of panicking.
        let _ = (rect, term);
    }

    /// See [`Self::draw_status_bar`]'s doc for the "surface not
    /// attached yet" fallback posture. `Terminal` paints no text, so
    /// unlike most of that method's siblings this doesn't need
    /// `self.dwrite`.
    fn draw_terminal_divider(&mut self, rect: Rect) {
        #[cfg(target_os = "windows")]
        if self.surface.is_some() {
            let theme = self.current_theme;
            crate::primitives::terminal::paint_divider(self, rect.x, rect.y, rect.height, &theme);
            return;
        }
        // See `draw_tree`'s doc for why this degrades to a no-op instead
        // of panicking.
        let _ = rect;
    }

    /// See [`Backend::draw_solid_fill`]'s doc — a pixel backend
    /// can honor `rect` exactly via `PaintSurface::surface_fill_rect`,
    /// which already degrades to a no-op when no surface is attached
    /// (see its own doc), so this can call it unconditionally — same
    /// shape as [`Self::draw_focus_ring`] above.
    fn draw_solid_fill(&mut self, rect: Rect, color: crate::Color) {
        self.surface_fill_rect(rect, color);
        self.register_zone(WidgetId::new("chrome:solid-fill"), rect);
    }

    /// Real Direct2D/DirectWrite rasteriser via `win::text_display`
    /// once a surface is attached. See [`Self::draw_status_bar`]'s doc
    /// for the "surface not attached yet" fallback posture.
    ///
    /// Shared text-display painting lives in
    /// [`crate::primitives::text_display::paint`] now — see that fn's
    /// doc for the divergence (this backend's `StyledSpan::bold`
    /// support, dropped since `PaintSurface` has no weight parameter)
    /// resolved while unifying `gtk::text_display::draw_text_display`,
    /// `macos::text_display::draw_text_display` and
    /// `win::text_display::draw_text_display` into one implementation.
    fn draw_text_display(&mut self, rect: Rect, td: &TextDisplay) {
        #[cfg(target_os = "windows")]
        if self.surface.is_some() {
            let theme = self.current_theme;
            let line_height = self.current_line_height;
            let char_width = self.current_char_width;
            // The text display is editor-class — see the matching
            // comment on `Self::draw_terminal` / `EditorSurface`'s own
            // doc.
            let mut surface = EditorSurface { backend: self };
            crate::primitives::text_display::paint(
                td,
                rect,
                &mut surface,
                &theme,
                line_height,
                char_width,
            );
            return;
        }
        // See `draw_tree`'s doc for why this degrades to a no-op instead
        // of panicking.
        let _ = (rect, td);
    }

    /// Real Direct2D/DirectWrite rasteriser via `win::command_line`
    /// once a surface is attached. See [`Self::draw_status_bar`]'s doc
    /// for the "surface not attached yet" fallback posture.
    fn draw_command_line(
        &mut self,
        rect: Rect,
        cmd: &crate::primitives::command_line::CommandLine,
    ) {
        self.draw_command_line_selection(rect, cmd, None);
    }

    /// Real selection-highlight paint via the shared
    /// `primitives::command_line::native_surface_paint::paint`. See
    /// `win::command_line`'s module doc. Same "surface not attached yet"
    /// degrade-to-no-op posture as before.
    fn draw_command_line_selection(
        &mut self,
        rect: Rect,
        cmd: &crate::primitives::command_line::CommandLine,
        selection: Option<(usize, usize)>,
    ) {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            super::command_line::draw_command_line_selection(
                &surface.target,
                dwrite,
                rect,
                cmd,
                &self.current_theme,
                self.current_char_width,
                selection,
            );
            return;
        }
        // See `draw_tree`'s doc for why this degrades to a no-op instead
        // of panicking.
        let _ = (rect, cmd, selection);
    }

    /// Pure measurement — only needs `current_char_width`, not a
    /// live render target or `self.dwrite` (mirrors
    /// `Self::text_display_layout`'s doc for why this only needs the
    /// `target_os = "windows"` gate every method in this file shares). No
    /// `return` in the `windows` arm — see [`Self::activity_bar_layout`]'s
    /// doc for why.
    fn command_line_layout(
        &self,
        rect: Rect,
        cmd: &crate::primitives::command_line::CommandLine,
    ) -> crate::primitives::command_line::CommandLineLayout {
        // Pure measurement (only `current_char_width`, no `self.dwrite`)
        // — computed directly rather than reaching into the Windows-only
        // `super::command_line` module.
        cmd.layout(
            rect,
            crate::primitives::command_line::CommandLineMeasure::new(self.current_char_width),
        )
    }

    /// Pure measurement — only needs `line_height`, not a live
    /// render target or `self.dwrite` (mirrors `MacBackend::text_display_layout`
    /// / `GtkBackend::text_display_layout`, both row-count-based rather
    /// than real text measurement) — but still lives in a Windows-only
    /// module, so this only needs the `target_os = "windows"` gate every
    /// method in this file shares. No `return` in the `windows` arm —
    /// see [`Self::activity_bar_layout`]'s doc for why.
    fn text_display_layout(&self, rect: Rect, td: &TextDisplay) -> TextDisplayLayout {
        // Pure measurement (row-count estimate off `line_height`/
        // `char_width`, no real text layout) — mirrors the shape of layout
        // functions in `super::text_display` (same scrollbar-gutter constants,
        // duplicated by value per `PRIMITIVE_RULES.md`#713), computed directly
        // instead of reaching into that Windows-only module.
        const SCROLLBAR_GUTTER_DIP: f32 = 12.0;
        const SCROLLBAR_MIN_THUMB_DIP: f32 = 8.0;
        let line_height = self.current_line_height;
        let char_width = self.current_char_width;
        let body_h = if td.title.is_some() {
            (rect.height - line_height).max(0.0)
        } else {
            rect.height
        };
        if body_h <= 0.0 {
            return td.layout(0.0, 0.0, |_| TextDisplayLineMeasure::new(line_height));
        }
        let body_width_px = if td.show_scrollbar {
            (rect.width - SCROLLBAR_GUTTER_DIP).max(0.0)
        } else {
            rect.width
        };
        let col_budget = crate::primitives::text_display::px_to_cols(body_width_px, char_width);
        let measure = |i: usize| {
            let rows = crate::primitives::text_display::wrap_row_count(&td.lines[i], col_budget);
            TextDisplayLineMeasure::new(rows as f32 * line_height)
        };
        if td.show_scrollbar {
            td.layout_with_scrollbar(
                rect.width,
                body_h,
                SCROLLBAR_GUTTER_DIP,
                SCROLLBAR_MIN_THUMB_DIP,
                measure,
            )
        } else {
            td.layout(rect.width, body_h, measure)
        }
    }

    /// Real Direct2D/DirectWrite rasteriser via `win::text_input`
    /// once a surface is attached. See [`Self::draw_status_bar`]'s doc
    /// for the "surface not attached yet" fallback posture.
    fn draw_text_input(
        &mut self,
        rect: Rect,
        ti: &crate::primitives::text_input::TextInput,
    ) -> crate::primitives::text_input::TextInputLayout {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            // `TextInput` is chrome, not `EditorClassPrimitive`-listed —
            // same `chrome_dwrite`-preferring swap as `Self::draw_palette`.
            let dwrite = self.chrome_dwrite.as_ref().unwrap_or(dwrite);
            return super::text_input::draw_text_input(
                &surface.target,
                dwrite,
                rect,
                ti,
                &self.current_theme,
                self.current_line_height,
                self.current_char_width,
            );
        }
        // Pure geometry — `TextInput::layout` needs only `line_height`/
        // `char_width`, no real text measurement; paints
        // nothing since there's no surface to paint onto.
        ti.layout(
            rect,
            crate::primitives::text_input::TextInputMeasure::new(
                self.current_line_height,
                self.current_char_width,
            ),
        )
    }

    /// Pure measurement — only needs `current_line_height`/
    /// `current_char_width`, not a live render target or `self.dwrite`
    /// (mirrors [`Self::command_line_layout`]'s doc for why this only
    /// needs the `target_os = "windows"` gate every method in this file
    /// shares). No `return` in the `windows` arm — see
    /// [`Self::activity_bar_layout`]'s doc for why.
    fn text_input_layout(
        &self,
        rect: Rect,
        ti: &crate::primitives::text_input::TextInput,
    ) -> crate::primitives::text_input::TextInputLayout {
        ti.layout(
            rect,
            crate::primitives::text_input::TextInputMeasure::new(
                self.current_line_height,
                self.current_char_width,
            ),
        )
    }

    /// Real Direct2D/DirectWrite rasteriser via `win::tooltip` once a
    /// surface is attached. Renders `TooltipChrome::default()` — see
    /// [`Self::draw_tooltip_with_chrome`] for the full-chrome entry point.
    /// See [`Self::draw_status_bar`]'s doc for the "surface not attached
    /// yet" fallback posture.
    fn draw_tooltip(&mut self, tooltip: &Tooltip, layout: &TooltipLayout) {
        self.draw_tooltip_with_chrome(tooltip, layout, &TooltipChrome::default());
    }

    /// See [`Self::draw_tooltip`]'s doc. Overridden (rather than
    /// relying on the trait's default delegate-to-`draw_tooltip` body) so
    /// a `Sides`/`None`/title chrome request is honoured, matching the
    /// TUI, GTK and macOS backends (see `Backend::draw_tooltip_with_chrome`'s
    /// doc).
    fn draw_tooltip_with_chrome(
        &mut self,
        tooltip: &Tooltip,
        layout: &TooltipLayout,
        chrome: &TooltipChrome,
    ) {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            // Tooltip text is chrome, not `EditorClassPrimitive`-listed —
            // same `chrome_dwrite`-preferring swap as `Self::draw_palette`.
            let dwrite = self.chrome_dwrite.as_ref().unwrap_or(dwrite);
            // Calls the shared paint directly (rather than through
            // `super::tooltip::draw_tooltip_with_chrome`, whose public
            // signature stays additive-only and so cannot take a live
            // `&Style`) so this live backend path honours
            // `Self::set_style` overrides — see that free function's own
            // doc. `Theme::default()` matches what this module's own
            // doc documents ("`WinBackend` does not yet carry a live
            // `Theme`").
            let theme = crate::theme::Theme::default();
            let style = self.style();
            let mut surf = super::surface::D2dSurface {
                target: &surface.target,
                dwrite: Some(dwrite),
            };
            crate::primitives::tooltip::native_surface_paint::paint(
                tooltip,
                layout,
                chrome,
                self.current_line_height,
                self.current_char_width,
                &mut surf,
                &theme,
                &style,
            );
            return;
        }
        // See `draw_tree`'s doc for why this degrades to a no-op instead
        // of panicking.
        let _ = (tooltip, layout, chrome);
    }

    /// Real Direct2D/DirectWrite rasteriser via `win::context_menu`
    /// once a surface is attached. `layout` is fully resolved upstream
    /// (see `crate::compose::menu_system`) — this only paints it and
    /// collects the per-clickable-item hit rectangles. See
    /// [`Self::draw_status_bar`]'s doc for the "surface not attached yet"
    /// fallback posture.
    ///
    /// `ContextMenu` is `ChromePrimitive::ContextMenu` (whole
    /// primitive, same posture as `draw_dialog`'s fix — `layout`
    /// is pre-resolved upstream, so only the paint font needs to change
    /// here) — paints through `chrome_dwrite`, falling back to the
    /// editor `dwrite` handle if no live chrome one exists yet.
    fn draw_context_menu(
        &mut self,
        menu: &ContextMenu,
        layout: &ContextMenuLayout,
    ) -> Vec<(Rect, WidgetId)> {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            let dwrite = self.chrome_dwrite.as_ref().unwrap_or(dwrite);
            let style = self.style();
            // Calls the shared paint directly (rather than
            // through `super::context_menu::draw_context_menu`, whose
            // public signature stays additive-only and so cannot take a
            // live `&Style`) so this live backend path honours
            // `Self::set_style` overrides.
            let mut surf = super::surface::D2dSurface {
                target: &surface.target,
                dwrite: Some(dwrite),
            };
            return crate::primitives::context_menu::native_surface_paint::paint(
                menu,
                layout,
                crate::accelerator::Platform::Windows,
                &mut surf,
                &self.current_theme,
                &style,
            );
        }
        // `layout` is already fully resolved — the hit-rect list is a pure
        // extraction from it, no text measurement involved, so this doesn't
        // need a surface/DWrite at all. Painting is skipped; only the hit
        // rects are returned.
        layout
            .visible_items
            .iter()
            .filter(|vis| vis.clickable)
            .filter_map(|vis| menu.items[vis.item_idx].id.map(|id| (vis.bounds, id)))
            .collect()
    }

    /// [`Self::draw_context_menu`], but honouring an optional
    /// [`crate::primitives::context_menu::ContextMenuGlyphs`] override for
    /// the check-mark / submenu-arrow glyphs — `glyphs: None` reproduces
    /// [`Self::draw_context_menu`] exactly.
    fn draw_context_menu_with_glyphs(
        &mut self,
        menu: &ContextMenu,
        layout: &ContextMenuLayout,
        glyphs: Option<&crate::primitives::context_menu::ContextMenuGlyphs>,
    ) -> Vec<(Rect, WidgetId)> {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            let dwrite = self.chrome_dwrite.as_ref().unwrap_or(dwrite);
            let style = self.style();
            let mut surf = super::surface::D2dSurface {
                target: &surface.target,
                dwrite: Some(dwrite),
            };
            return crate::primitives::context_menu::native_surface_paint::paint_with_glyphs(
                menu,
                layout,
                crate::accelerator::Platform::Windows,
                &mut surf,
                &self.current_theme,
                &style,
                glyphs,
                self.nerd_fonts_enabled,
            );
        }
        #[cfg(not(target_os = "windows"))]
        let _ = glyphs;
        self.draw_context_menu(menu, layout)
    }

    /// Real Direct2D/DirectWrite rasteriser via `win::dialog` once a
    /// surface is attached. `layout` is fully resolved upstream (see
    /// [`crate::primitives::dialog::Dialog::layout`]) — this only paints
    /// it and returns the per-button hit rectangles in
    /// `layout.visible_buttons` order. See [`Self::draw_status_bar`]'s
    /// doc for the "surface not attached yet" fallback posture.
    ///
    /// `Dialog` is `ChromePrimitive::Dialog` (whole primitive, matching
    /// macOS's existing fix) — see `draw_tree`'s comment for the font
    /// swap. Passes `chrome_dwrite`, falling back to the editor `dwrite`
    /// handle if no live chrome one exists yet, same "degrade, don't
    /// panic" convention as `surface_draw_text_run_with_role`'s Windows
    /// override — this is `chrome_dwrite`'s first real caller (see that
    /// field's own doc).
    fn draw_dialog(&mut self, dialog: &Dialog, layout: &DialogLayout) -> Vec<Rect> {
        #[cfg(target_os = "windows")]
        if let Some(surface) = &self.surface {
            let dwrite = self.chrome_dwrite.as_ref().or(self.dwrite.as_ref());
            if let Some(dwrite) = dwrite {
                let style = self.style();
                return super::dialog::draw_dialog_with_style(
                    &surface.target,
                    dwrite,
                    dialog,
                    layout,
                    self.current_line_height,
                    &style,
                );
            }
        }
        // `layout` is already fully resolved (see this fn's doc) — the
        // per-button hit rects are a pure extraction from
        // `layout.visible_buttons`, no text measurement involved, so this
        // doesn't need a surface/DWrite at all. Painting is
        // skipped; only the hit rects are returned.
        let _ = dialog;
        layout
            .visible_buttons
            .iter()
            .map(|vis| vis.bounds)
            .collect()
    }

    /// Unlike [`Self::draw_dialog`] above, this needs no
    /// `#[cfg(target_os = "windows")]`/"no surface yet" branch at all:
    /// every [`PaintSurface`] verb
    /// [`crate::primitives::float::native_surface_paint::paint`] calls
    /// already degrades to a no-op when `self.surface`/`self.dwrite` are
    /// absent (see e.g. [`Self::surface_fill_rect`]'s own doc), so
    /// calling it unconditionally is correct on every target — same
    /// reasoning as [`Self::draw_canvas`]'s own doc.
    fn draw_float(
        &mut self,
        float: &crate::primitives::float::Float,
        layout: &crate::primitives::float::FloatLayout,
    ) {
        self.modal_stack.borrow_mut().mark_painted(&float.id);
        let theme = self.current_theme;
        crate::primitives::float::native_surface_paint::paint(float, layout, self, &theme);
        // Same convention `draw_image`/`draw_solid_fill` use for a
        // chrome-only primitive: register the float's own bounds under
        // its id so it's inventory-observable.
        self.register_zone(float.id, layout.bounds);
    }

    /// Same "no `target_os` gate needed" shape as [`Self::draw_float`]
    /// above: [`crate::primitives::number_input::native_surface_paint::paint`]
    /// degrades to a no-op through this backend's own [`PaintSurface`]
    /// impl when there is no live surface/DWrite yet.
    fn draw_number_input(
        &mut self,
        number_input: &crate::primitives::number_input::NumberInput,
        layout: &crate::primitives::number_input::NumberInputLayout,
    ) {
        let theme = self.current_theme;
        crate::primitives::number_input::native_surface_paint::paint(
            number_input,
            layout,
            self,
            &theme,
        );
        self.register_zone(number_input.id, layout.bounds);
    }

    /// Same shape as [`Self::draw_number_input`] above.
    fn draw_combo_box(
        &mut self,
        combo_box: &crate::primitives::combo_box::ComboBox,
        layout: &crate::primitives::combo_box::ComboBoxLayout,
    ) {
        let theme = self.current_theme;
        crate::primitives::combo_box::native_surface_paint::paint(combo_box, layout, self, &theme);
        self.register_zone(combo_box.id, layout.field_bounds);
    }

    fn draw_date_picker(
        &mut self,
        date_picker: &crate::primitives::date_picker::DatePicker,
        layout: &crate::primitives::date_picker::DatePickerLayout,
    ) {
        let theme = self.current_theme;
        crate::primitives::date_picker::native_surface_paint::paint(
            date_picker,
            layout,
            self,
            &theme,
        );
        self.register_zone(date_picker.id, layout.bounds());
    }

    /// Real Direct2D/DirectWrite rasteriser via `win::multi_section_view`
    /// once a surface is attached. See [`Self::draw_status_bar`]'s doc for
    /// the "surface not attached yet" fallback posture.
    ///
    /// `MultiSectionView` is `ChromePrimitive::MultiSectionView`
    /// — section headers and the `Tree`/`List` bodies it dispatches to
    /// are sidebar chrome, not editor content, same "whole-primitive
    /// font swap, `line_height`/`char_width` stay at the editor's own
    /// values (embedded `Chart`/editor-adjacent content still measures
    /// against those)" shape `MacBackend::draw_multi_section_view`
    /// already ships — paints through `chrome_dwrite`,
    /// falling back to the editor `dwrite` handle if no live chrome one
    /// exists yet.
    fn draw_multi_section_view(&mut self, rect: Rect, view: &MultiSectionView) {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            let dwrite = self.chrome_dwrite.as_ref().unwrap_or(dwrite);
            let caret_visible = self.caret_visible();
            super::multi_section_view::draw_multi_section_view(
                &surface.target,
                dwrite,
                rect,
                view,
                self.current_line_height,
                self.current_char_width,
                caret_visible,
            );
            return;
        }
        // See `draw_tree`'s doc for why this degrades to a no-op instead
        // of panicking.
        let _ = (rect, view);
    }

    /// Like [`Self::tree_layout`], this is pure measurement — only
    /// needs `line_height`, not a live render target or `self.dwrite`
    /// (`win_msv_layout`'s `body_measure` is row-count-based, not real
    /// text measurement, mirroring `MacBackend::msv_layout`/
    /// `GtkBackend::msv_layout`) — but still lives in a Windows-only
    /// module, so this only needs the `target_os = "windows"` gate every
    /// method in this file shares. No `return` in the `windows` arm
    /// (unlike [`Self::draw_multi_section_view`] above): on
    /// `target_os = "windows"` the `not(windows)` block below is
    /// stripped, so this block *is* the tail expression and an explicit
    /// `return` trips `clippy::needless_return` under CI's `-D warnings`
    /// — see [`Self::activity_bar_layout`]'s doc for the same pattern.
    fn msv_layout(&self, rect: Rect, view: &MultiSectionView) -> MultiSectionViewLayout {
        // `crate::primitives::layout_metrics::msv_layout` is fully
        // portable (row-count estimate, no Direct2D/DirectWrite type) —
        // call it directly instead of reaching into the Windows-only
        // `super::multi_section_view` module.
        crate::primitives::layout_metrics::msv_layout(view, rect, self.current_line_height as f64)
    }

    /// See [`Self::msv_layout`]'s doc for both the "no measurer
    /// needed, but still Windows-only" posture and the no-`return`
    /// pattern. `allow_resize` is hardcoded `false` here (no `view` to
    /// read it from), matching `MacBackend::msv_metrics`/
    /// `GtkBackend::msv_metrics`'s identical shortcut. Callers that need
    /// the resize-aware divider size should go through
    /// [`Self::msv_layout`] instead.
    fn msv_metrics(&self) -> MsvLayoutMetrics {
        // Portable — see `msv_layout`'s doc.
        crate::primitives::layout_metrics::msv_metrics(self.current_line_height as f64, false)
    }

    /// Pure measurement — only needs `self.dwrite`, not a live render
    /// target. See [`Self::data_table_layout`]'s doc. Prefers
    /// `chrome_dwrite`, matching [`Self::draw_tree`]'s paint font — both
    /// must resolve the same handle or the chevron boundary measured
    /// here would disagree with what the paint actually fits.
    fn tree_layout(&self, rect: Rect, tree: &TreeView) -> TreeViewLayout {
        #[cfg(target_os = "windows")]
        if let Some(dwrite) = self.chrome_dwrite.as_ref().or(self.dwrite.as_ref()) {
            return super::tree::win_tree_layout_measured(
                dwrite,
                rect,
                tree,
                self.current_line_height,
            );
        }
        // No live DWrite handle yet (fresh backend, device lost, or a
        // non-Windows host, where `win::tree` never compiles) — nominal
        // char-width estimate for the chevron glyph instead; real
        // per-glyph measurement resumes once
        // `attach_surface`/`attach_headless` builds one.
        crate::primitives::layout_metrics::tree_layout_measured(
            tree,
            rect,
            self.current_line_height as f64,
            &NominalTextMeasure {
                char_width: self.current_char_width,
            },
        )
    }

    /// `vscrollbar` deals purely in row counts/row-height, so
    /// (like [`Self::list_vscrollbar`]) the primitive's own geometry
    /// method is unit-correct for every backend — see
    /// [`TreeView::vscrollbar`]. Cross-platform, no Direct2D/DirectWrite
    /// call needed, so this compiles (and is exercised by
    /// `cargo check --features win`) on every host, not just
    /// `target_os = "windows"`.
    ///
    /// The `row_height` passed in must match `Self::tree_layout`'s own
    /// per-row pitch, not the raw `line_height` — `TreeView` rows pitch
    /// at `line_height * 1.4` (or `TreeStyle::row_height`), unlike
    /// `ListView` items which really are `line_height` tall; see
    /// `layout_metrics::tree_row_pitch`'s doc.
    fn tree_vscrollbar(&self, rect: Rect, tree: &TreeView) -> Option<crate::Scrollbar> {
        let row_h = crate::primitives::layout_metrics::tree_row_pitch(
            tree,
            self.current_line_height as f64,
        );
        tree.vscrollbar_with_track_width(
            rect,
            row_h as f32,
            crate::primitives::layout_metrics::pixel::TREE_VSCROLLBAR_WIDTH,
        )
    }

    fn tree_paints_own_scrollbar(&self) -> bool {
        true
    }

    /// Pure measurement — only needs `self.dwrite`, not a live
    /// render target. See [`Self::status_bar_layout`]'s doc. Prefers
    /// `chrome_dwrite`, matching [`Self::draw_form`]'s paint font — both
    /// must resolve the same handle or field widths measured here would
    /// disagree with what the paint actually fits.
    fn form_layout(&self, rect: Rect, form: &Form) -> FormLayout {
        #[cfg(target_os = "windows")]
        if let Some(dwrite) = self.chrome_dwrite.as_ref().or(self.dwrite.as_ref()) {
            return super::form::win_form_layout(dwrite, rect, form, self.current_line_height);
        }
        // No live DWrite handle — nominal char-width estimate instead;
        // real per-glyph measurement resumes once
        // `attach_surface`/`attach_headless` builds one.
        let row_h =
            crate::primitives::layout_metrics::form_row_height(self.current_line_height as f64);
        let measure = NominalTextMeasure {
            char_width: self.current_char_width,
        };
        form.layout(rect.width, rect.height, |i| {
            crate::primitives::layout_metrics::form_field_measure(&form.fields[i], row_h, &measure)
        })
    }

    /// See [`Self::draw_status_bar`]'s doc for the "surface not
    /// attached yet" fallback posture. `rect` is unused on the painted
    /// path — `editor.rect` is authoritative (mirrors
    /// `GtkBackend::draw_editor`, which does the same).
    ///
    /// The vertical scrollbar column (sized by
    /// [`Self::set_editor_v_scrollbar_width`]) is painted after the
    /// rasteriser returns, through [`Self::draw_scrollbar`] — see
    /// `win::editor`'s "Scrollbar" module doc.
    fn draw_editor(&mut self, rect: Rect, editor: &Editor) -> EditorPaintResult {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            let _ = rect;
            let options = crate::primitives::editor::EditorPaintOptions::default();
            let result = super::editor::draw_editor_with_options_and_v_scrollbar_w(
                &surface.target,
                dwrite,
                editor,
                self.current_char_width,
                self.current_line_height,
                &self.current_theme,
                options,
                self.editor_v_scrollbar_w,
            );
            let layout = editor.layout_with_options_and_v_scrollbar_w(
                editor.rect,
                self.current_char_width,
                self.current_line_height,
                options,
                self.editor_v_scrollbar_w,
            );
            if let Some(v_track) = layout.v_scrollbar_bounds {
                let sb = Scrollbar::vertical(
                    "win:editor:v_scrollbar",
                    v_track,
                    editor.scroll_top as f32,
                    editor.total_lines as f32,
                    layout.visible_lines as f32,
                    self.current_line_height,
                );
                self.draw_scrollbar(v_track, &sb);
            }
            return result;
        }
        // No surface/DWrite yet — paint nothing and report no cursor
        // position, matching every other backend's "nothing painted" shape.
        let _ = (rect, editor);
        EditorPaintResult::default()
    }

    fn set_editor_v_scrollbar_width(&mut self, px: Option<f32>) {
        self.editor_v_scrollbar_w = px;
    }

    fn editor_v_scrollbar_width(&self) -> Option<f32> {
        self.editor_v_scrollbar_w
    }

    /// Real Direct2D/DirectWrite rasteriser via `win::message_list`
    /// once a surface is attached. Mirrors `GtkBackend::draw_message_list`
    /// / `MacBackend::draw_message_list` — no panel-background fill here;
    /// hosts that want one paint it before calling (see
    /// `win::message_list`'s module doc). See [`Self::draw_status_bar`]'s
    /// doc for the "surface not attached yet" fallback posture.
    fn draw_message_list(&mut self, rect: Rect, list: &MessageList) {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            // `MessageList` rows are chrome, not `EditorClassPrimitive`-
            // listed — same `chrome_dwrite`-preferring swap as
            // `Self::draw_palette`.
            let dwrite = self.chrome_dwrite.as_ref().unwrap_or(dwrite);
            super::message_list::draw_message_list(
                &surface.target,
                dwrite,
                list,
                rect.x,
                rect.y,
                rect.y + rect.height,
                self.current_line_height,
            );
            return;
        }
        // See `draw_tree`'s doc for why this degrades to a no-op instead
        // of panicking.
        let _ = (rect, list);
    }

    /// Real Direct2D/DirectWrite rasteriser via `win::rich_text_popup`
    /// once a surface is attached. The rasteriser returns per-link hit
    /// regions for its own tests; the trait signature discards them (same
    /// posture as `GtkBackend::draw_rich_text_popup` — hosts that need
    /// link hit-testing query `popup.layout(...).hit_test(...)` directly).
    /// See [`Self::draw_status_bar`]'s doc for the "surface not attached
    /// yet" fallback posture.
    /// `RichTextPopup` is `ChromePrimitive::RichTextPopup` (whole
    /// primitive, matching macOS's existing fix — see `draw_tree`'s
    /// comment for the font swap). Passes `chrome_dwrite`, falling back
    /// to the editor `dwrite` handle if no live chrome one exists yet,
    /// same "degrade, don't panic" convention as
    /// `surface_draw_text_run_with_role`'s Windows override.
    fn draw_rich_text_popup(&mut self, popup: &RichTextPopup, layout: &RichTextPopupLayout) {
        #[cfg(target_os = "windows")]
        if let Some(surface) = &self.surface {
            // Falls back to the editor `dwrite` handle if no live chrome
            // one exists yet, same "degrade, don't panic" convention as
            // `surface_draw_text_run_with_role`'s Windows override.
            let dwrite = self.chrome_dwrite.as_ref().or(self.dwrite.as_ref());
            if let Some(dwrite) = dwrite {
                let _ = super::rich_text_popup::draw_rich_text_popup(
                    &surface.target,
                    dwrite,
                    popup,
                    layout,
                );
                return;
            }
        }
        // See `draw_tree`'s doc for why this degrades to a no-op instead
        // of panicking.
        let _ = (popup, layout);
    }

    /// Draw a [`RichTextPopup`] with an explicit [`crate::FontRole`]:
    /// `FontRole::Chrome` behaves exactly like plain
    /// `draw_rich_text_popup` above; `FontRole::Editor` always uses the
    /// editor `dwrite` handle instead of falling back to it only when no
    /// chrome handle exists, the same resolution `Self::measure_text`
    /// uses per role.
    fn draw_rich_text_popup_with_font_role(
        &mut self,
        popup: &RichTextPopup,
        layout: &RichTextPopupLayout,
        role: crate::FontRole,
    ) {
        if role == crate::FontRole::Chrome {
            self.draw_rich_text_popup(popup, layout);
            return;
        }
        #[cfg(target_os = "windows")]
        if let Some(surface) = &self.surface {
            if let Some(dwrite) = self.dwrite.as_ref() {
                let _ = super::rich_text_popup::draw_rich_text_popup(
                    &surface.target,
                    dwrite,
                    popup,
                    layout,
                );
                return;
            }
        }
        let _ = (popup, layout);
    }

    /// Real Direct2D/DirectWrite
    /// rendering via [`crate::primitives::find_replace::paint`] once a
    /// surface is attached. See [`Self::draw_status_bar`]'s doc for the
    /// "surface not attached yet" fallback posture.
    fn draw_find_replace(&mut self, rect: Rect, panel: &FindReplacePanel) {
        #[cfg(target_os = "windows")]
        if self.surface.is_some() && self.dwrite.is_some() {
            let _ = rect;
            let theme = self.current_theme;
            crate::primitives::find_replace::paint(panel, self, &theme);
            return;
        }
        // See `draw_tree`'s doc for why this degrades to a no-op instead
        // of panicking.
        let _ = (rect, panel);
    }

    /// Real Direct2D/DirectWrite rasteriser via `win::completions`
    /// once a surface is attached. See [`Self::draw_status_bar`]'s doc
    /// for the "surface not attached yet" fallback posture.
    fn draw_completions(&mut self, completions: &Completions, layout: &CompletionsLayout) {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            // The completions popup is chrome, not
            // `EditorClassPrimitive`-listed — same `chrome_dwrite`-
            // preferring swap as `Self::draw_palette`.
            let dwrite = self.chrome_dwrite.as_ref().unwrap_or(dwrite);
            super::completions::draw_completions(
                &surface.target,
                dwrite,
                completions,
                layout,
                &self.current_theme,
            );
            return;
        }
        // See `draw_tree`'s doc for why this degrades to a no-op instead
        // of panicking.
        let _ = (completions, layout);
    }

    /// Real Direct2D rasteriser via `win::scrollbar` once a surface
    /// is attached. See [`Self::draw_status_bar`]'s doc for the "surface
    /// not attached yet" fallback posture. `rect` is unused on the
    /// painted path — `scrollbar.track` is authoritative, mirroring
    /// `MacBackend::draw_scrollbar`/`GtkBackend::draw_scrollbar`.
    fn draw_scrollbar(&mut self, rect: Rect, scrollbar: &Scrollbar) {
        #[cfg(target_os = "windows")]
        if self.surface.is_some() {
            let _ = rect;
            let theme = self.current_theme;
            crate::primitives::scrollbar::native_surface_paint::paint(scrollbar, self, &theme);
            return;
        }
        // See `draw_tree`'s doc for why this degrades to a no-op instead
        // of panicking.
        let _ = (rect, scrollbar);
    }

    /// Paint via the shared
    /// [`crate::primitives::drop_zone::native_surface_paint::paint`]
    /// once a surface is attached — mirrors [`Self::draw_scrollbar`].
    /// See [`Self::draw_status_bar`]'s doc for the "surface not attached
    /// yet" fallback posture.
    fn draw_drop_overlay(&mut self, overlay: &crate::primitives::drop_zone::DropOverlay) {
        #[cfg(target_os = "windows")]
        if self.surface.is_some() {
            let theme = self.current_theme;
            crate::primitives::drop_zone::native_surface_paint::paint(overlay, self, &theme);
            return;
        }
        // See `draw_tree`'s doc for why this degrades to a no-op instead
        // of panicking.
        let _ = overlay;
    }

    /// See [`Self::draw_status_bar`]'s doc for the "surface not
    /// attached yet" fallback posture.
    ///
    /// `MenuBar` is `ChromePrimitive::MenuBar` — see
    /// [`Self::draw_tree`]'s note for the font-swap shape. Unlike
    /// `draw_tree`, `win_menu_bar_layout` (called internally by
    /// `super::menu_bar::draw_menu_bar`) does real `TextMeasure`
    /// measurement against whichever `DWrite` handle is passed, so
    /// passing `chrome_dwrite` here keeps layout and paint in agreement
    /// — see [`Self::menu_bar_layout`]'s doc for the no-paint twin that
    /// must resolve the same widths.
    fn draw_menu_bar(&mut self, rect: Rect, bar: &MenuBar) -> MenuBarLayout {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            let dwrite = self.chrome_dwrite.as_ref().unwrap_or(dwrite);
            let layout = super::menu_bar::draw_menu_bar(
                &surface.target,
                dwrite,
                rect,
                bar,
                &self.current_theme,
            );
            // See "Band-content zone registration" above —
            // without this, every point over "File"/"Edit"/... reads as
            // `HTCAPTION` and the OS swallows the click before the app
            // ever sees it.
            self.register_menu_bar_item_zones(&layout);
            return layout;
        }
        // No surface/DWrite yet — compute the real layout via the same
        // nominal measurer `menu_bar_layout` falls back to, and paint
        // nothing.
        let layout = super::menu_bar::win_menu_bar_layout(
            &NominalTextMeasure {
                char_width: self.current_char_width,
            },
            rect,
            bar,
        );
        self.register_menu_bar_item_zones(&layout);
        layout
    }

    /// See [`Self::status_bar_layout`]'s doc for why this only needs
    /// `self.dwrite`. Prefers `chrome_dwrite`, matching
    /// [`Self::draw_menu_bar`]'s paint font.
    fn menu_bar_layout(&self, rect: Rect, bar: &MenuBar) -> MenuBarLayout {
        #[cfg(target_os = "windows")]
        if let Some(dwrite) = self.chrome_dwrite.as_ref().or(self.dwrite.as_ref()) {
            return super::menu_bar::win_menu_bar_layout(dwrite, rect, bar);
        }
        super::menu_bar::win_menu_bar_layout(
            &NominalTextMeasure {
                char_width: self.current_char_width,
            },
            rect,
            bar,
        )
    }

    /// See [`Self::draw_status_bar`]'s doc for the "surface not
    /// attached yet" fallback posture. `Split` paints no text, so unlike
    /// most of that method's siblings this doesn't need `self.dwrite`.
    fn draw_split(&mut self, rect: Rect, split: &Split) -> SplitLayout {
        #[cfg(target_os = "windows")]
        if self.surface.is_some() {
            let layout = super::split::win_split_layout(rect, split);
            // `self.current_theme` is the live theme `Backend::set_theme`
            // writes, same as every other rasteriser in this file.
            let theme = self.current_theme;
            crate::primitives::split::native_surface_paint::paint(&layout, self, &theme);
            return layout;
        }
        // No surface yet — return the real (pure-geometry) layout via
        // `split_layout` and paint nothing.
        self.split_layout(rect, split)
    }

    /// Pure geometry — no measurer at all (uniform divider thickness),
    /// so unlike most `*_layout` siblings this doesn't even need
    /// `self.dwrite`, only kept behind the `target_os = "windows"` gate
    /// for consistency with every other method in this file.
    ///
    /// This used to duplicate `super::split::win_split_layout`'s
    /// `DIVIDER_DIP` constant by value (per `PRIMITIVE_RULES.md`#713, to
    /// avoid reaching into the Windows-only `super::split` module).
    /// [`crate::primitives::layout_metrics::pixel_split_layout`] is plain,
    /// platform-independent geometry, so it can be called directly here
    /// with no such tradeoff — one shared divider-thickness constant.
    /// instead of two.
    fn split_layout(&self, rect: Rect, split: &Split) -> SplitLayout {
        crate::primitives::layout_metrics::pixel_split_layout(split, rect)
    }

    /// See [`Self::draw_split`]'s doc for the "surface not attached
    /// yet" fallback posture. `SplitTree` paints no text, so unlike most
    /// of that method's siblings this doesn't need `self.dwrite`.
    fn draw_split_tree(
        &mut self,
        rect: Rect,
        tree: &crate::primitives::split_tree::SplitTree,
    ) -> crate::primitives::split_tree::SplitTreeLayout {
        #[cfg(target_os = "windows")]
        if self.surface.is_some() {
            let layout = super::split_tree::win_split_tree_layout(rect, tree);
            // `self.current_theme` is the live theme `Backend::set_theme`
            // writes, same as every other rasteriser in this file.
            let theme = self.current_theme;
            crate::primitives::split_tree::native_surface_paint::paint(&layout, self, &theme);
            return layout;
        }
        // No surface yet — return the real (pure-geometry) layout via
        // `split_tree_layout` and paint nothing.
        self.split_tree_layout(rect, tree)
    }

    /// Pure geometry — no measurer at all (uniform divider
    /// thickness), so unlike most `*_layout` siblings this doesn't even
    /// need `self.dwrite`, only kept behind the `target_os = "windows"`
    /// gate for consistency with every other method in this file. See
    /// [`Self::split_layout`]'s doc for why this now
    /// delegates to the shared, platform-independent
    /// [`crate::primitives::layout_metrics::pixel_split_tree_layout`]
    /// instead of duplicating `super::split_tree`'s `DIVIDER_DIP` by
    /// value.
    fn split_tree_layout(
        &self,
        rect: Rect,
        tree: &crate::primitives::split_tree::SplitTree,
    ) -> crate::primitives::split_tree::SplitTreeLayout {
        crate::primitives::layout_metrics::pixel_split_tree_layout(tree, rect)
    }

    /// Paint via the shared
    /// [`crate::primitives::board::native_surface_paint::paint`] once a
    /// surface is attached — mirrors [`Self::draw_diff_view`]. See that
    /// fn's doc for the four named divergences (column-header overflow;
    /// card-title wrapping; rounded vs. straight card borders;
    /// per-element font size) found while unifying
    /// `gtk::board::draw_board`, `macos::board::draw_board` and
    /// `win::board::draw_board` into one implementation. See
    /// [`Self::draw_status_bar`]'s doc for the "surface not attached yet"
    /// fallback posture.
    fn draw_board(&mut self, rect: Rect, model: &crate::BoardModel) -> crate::BoardLayout {
        #[cfg(target_os = "windows")]
        if self.surface.is_some() && self.dwrite.is_some() {
            let theme = self.current_theme;
            return crate::primitives::board::native_surface_paint::paint(
                model, self, &theme, rect,
            );
        }
        // No surface/DWrite yet — return the real (pure-geometry) layout
        // via `board_layout` and paint nothing.
        self.board_layout(rect, model)
    }

    /// Pure geometry — `board_layout` needs no measurer at all
    /// (fixed DIP constants, same posture as
    /// [`Self::pipeline_view_layout`]'s doc), only kept behind the
    /// `target_os = "windows"` gate for consistency with every other
    /// method in this file. No `return` in the `windows` arm — see
    /// [`Self::activity_bar_layout`]'s doc for why.
    fn board_layout(&self, rect: Rect, model: &crate::BoardModel) -> crate::BoardLayout {
        // Pure geometry (fixed DIP constants) — lifted the
        // `BoardMeasure::new(BOARD_*_PX...)` construction into
        // `crate::primitives::layout_metrics::pixel_board_layout`, callable
        // directly here (no Windows-only type in its signature) rather than
        // reaching into that Windows-only module.
        crate::primitives::layout_metrics::pixel_board_layout(
            model,
            rect.x,
            rect.y,
            rect.width,
            rect.height,
        )
    }

    /// Real Direct2D/DirectWrite rasteriser via `win::minimap` once a
    /// surface is attached — see [`Self::draw_status_bar`]'s doc for the
    /// "surface not attached yet" fallback posture.
    fn draw_minimap(
        &mut self,
        rect: Rect,
        minimap: &crate::primitives::minimap::Minimap,
    ) -> crate::backend::MinimapPaintResult {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            let layout = super::minimap::draw_minimap_scaled(
                &surface.target,
                dwrite,
                rect,
                minimap,
                &self.current_theme,
                self.minimap_scale,
            );
            return crate::backend::MinimapPaintResult {
                layout,
                painted: true,
            };
        }
        // No surface/DWrite yet — same treatment as `MacBackend::draw_minimap`:
        // real geometry via `minimap_layout`, `painted: false`, nothing drawn.
        crate::backend::MinimapPaintResult {
            layout: self.minimap_layout(rect, minimap),
            painted: false,
        }
    }

    /// Pure geometry — `minimap_layout` needs no measurer at all
    /// (fixed DIP constants, same posture as
    /// [`Self::board_layout`]'s doc), only kept behind the
    /// `target_os = "windows"` gate for consistency with every other
    /// method in this file.
    fn minimap_layout(
        &self,
        rect: Rect,
        minimap: &crate::primitives::minimap::Minimap,
    ) -> crate::primitives::minimap::MinimapLayout {
        // Pure geometry (fixed DIP constants) — `Minimap::layout_with_sizing`
        // needs no Direct2D/DirectWrite type, so this is computed directly
        // instead of reaching into the Windows-only `super::minimap` module.
        // One buffer line per painted row (no cross-line colour reduction),
        // same `LINES_PER_ROW` value that module uses. `self.minimap_scale`'s
        // own `row_pitch_px` replaces the bare `ROW_PITCH_PX` constant this
        // used before, so this pure-geometry path and `super::minimap`'s real
        // paint path always resolve the same pitch.
        minimap.layout_with_sizing(
            rect,
            1,
            crate::primitives::minimap::MinimapSizing::FixedPitch(
                self.minimap_scale.row_pitch_px() as f32,
            ),
        )
    }

    fn minimap_scale(&self) -> crate::primitives::minimap::MinimapScale {
        self.minimap_scale
    }

    fn set_minimap_scale(&mut self, scale: crate::primitives::minimap::MinimapScale) {
        self.minimap_scale = scale;
    }

    /// See [`Self::draw_status_bar`]'s doc for the "surface not
    /// attached yet" fallback posture. Only needs `self.surface` (not
    /// `self.dwrite` too) — WIC decoding and `DrawBitmap` are pure
    /// Direct2D, no text measurement involved.
    fn draw_image(
        &mut self,
        rect: Rect,
        image: &crate::primitives::image::Image,
    ) -> crate::backend::ImagePaintResult {
        #[cfg(target_os = "windows")]
        if let Some(surface) = &self.surface {
            return super::image::draw_image(&surface.target, rect, image);
        }
        // No surface yet — matches `MacBackend::draw_image`'s categorical
        // `Unsupported`: no pixels to rasterise onto, so report it
        // rather than panic.
        let _ = (rect, image);
        crate::backend::ImagePaintResult::Unsupported
    }

    /// See [`Self::draw_status_bar`]'s doc for the "surface not
    /// attached yet" fallback posture.
    fn draw_panel(&mut self, rect: Rect, panel: &Panel) -> PanelLayout {
        #[cfg(target_os = "windows")]
        if self.surface.is_some() && self.dwrite.is_some() {
            let line_height = self.current_line_height;
            let layout = super::panel::win_panel_layout(rect, panel, line_height);
            // `self.current_theme` is the live theme `Backend::set_theme`
            // writes, same as `draw_toast_overlay` above.
            let theme = self.current_theme;
            crate::primitives::panel::native_surface_paint::paint(panel, &layout, self, &theme);
            return layout;
        }
        // No surface/DWrite yet — return the real (pure-geometry) layout
        // via `panel_layout` and paint nothing.
        self.panel_layout(rect, panel)
    }

    /// Pure geometry — `Panel::layout` needs only `line_height`,
    /// not text measurement, so this needs no `self.dwrite`/surface at
    /// all — computed directly rather than reaching into
    /// the Windows-only `super::panel` module.
    fn panel_layout(&self, rect: Rect, panel: &Panel) -> PanelLayout {
        let line_height = self.current_line_height;
        let measure = crate::primitives::panel::PanelMeasure::new(if panel.title.is_some() {
            line_height
        } else {
            0.0
        });
        panel.layout(rect, measure)
    }

    /// Unlike [`Self::draw_panel`]/[`Self::draw_toast_overlay`] above,
    /// this needs no `#[cfg(target_os = "windows")]`/"no surface yet"
    /// branch at all: every [`PaintSurface`] verb
    /// [`crate::primitives::canvas::native_surface_paint::paint`] calls
    /// already degrades to a no-op when `self.surface`/`self.dwrite` are
    /// absent (see e.g. [`Self::surface_fill_rect`]'s own doc), so
    /// calling it unconditionally is correct on every target: a real
    /// paint once attached, and the same graceful "nothing happened yet"
    /// this file's other rasterisers reach for explicitly.
    fn draw_canvas(
        &mut self,
        rect: Rect,
        canvas: &crate::primitives::canvas::Canvas,
    ) -> crate::primitives::canvas::CanvasLayout {
        let layout = canvas.layout(rect);
        crate::primitives::canvas::native_surface_paint::paint(canvas, &layout, self);
        layout
    }

    /// See [`Self::draw_status_bar`]'s doc for the "surface not attached
    /// yet" fallback posture. Paints via the shared
    /// [`crate::primitives::toast::native_surface_paint::paint`] now,
    /// passing `&self.current_theme` — see `super::toast`'s module doc
    /// for why the previous free function never did.
    fn draw_toast_overlay(&mut self, rect: Rect, stack: &ToastOverlay) -> ToastStackLayout {
        #[cfg(target_os = "windows")]
        if self.surface.is_some() && self.dwrite.is_some() {
            let theme = self.current_theme;
            let style = self.style();
            let line_height = self.current_line_height;
            return crate::primitives::toast::native_surface_paint::paint(
                stack,
                self,
                &theme,
                &style,
                rect.x,
                rect.y,
                rect.width,
                rect.height,
                line_height,
            );
        }
        // No surface/DWrite yet — compute the real layout via the same
        // nominal measurer `toast_stack_layout` falls back to, and paint
        // nothing.
        super::toast::win_toast_stack_layout(
            &NominalTextMeasure {
                char_width: self.current_char_width,
            },
            rect,
            stack,
            self.current_line_height,
        )
    }

    /// Pure measurement — only needs `self.dwrite`, not a live
    /// render target, so this works as soon as a surface has ever been
    /// attached — same posture as [`Self::status_bar_layout`]. Prefers
    /// `chrome_dwrite`, matching `Self::draw_toast_overlay`'s paint font
    /// (chrome by `WinBackend`'s own [`PaintSurface`] default — see that
    /// impl's doc) — both must resolve the same handle or the toast's
    /// measured width would disagree with what the paint actually fits.
    fn toast_stack_layout(&self, rect: Rect, stack: &ToastOverlay) -> ToastStackLayout {
        #[cfg(target_os = "windows")]
        if let Some(dwrite) = self.chrome_dwrite.as_ref().or(self.dwrite.as_ref()) {
            return super::toast::win_toast_stack_layout(
                dwrite,
                rect,
                stack,
                self.current_line_height,
            );
        }
        super::toast::win_toast_stack_layout(
            &NominalTextMeasure {
                char_width: self.current_char_width,
            },
            rect,
            stack,
            self.current_line_height,
        )
    }

    /// Real Direct2D/DirectWrite rasteriser via `win::pipeline_view`
    /// once a surface is attached. See [`Self::draw_status_bar`]'s doc for
    /// the "surface not attached yet" fallback posture.
    /// Paint via the shared
    /// [`crate::primitives::pipeline_view::native_surface_paint::paint`]
    /// once a surface is attached — mirrors [`Self::draw_diff_view`]. See
    /// that fn's doc for the seven named divergences found while
    /// unifying `gtk::pipeline_view::draw_pipeline_view`,
    /// `macos::pipeline_view::draw_pipeline_view` and
    /// `win::pipeline_view::draw_pipeline_view` into one implementation.
    /// See [`Self::draw_status_bar`]'s doc for the "surface not attached
    /// yet" fallback posture.
    fn draw_pipeline_view(
        &mut self,
        rect: Rect,
        view: &crate::primitives::pipeline_view::PipelineView,
    ) -> crate::primitives::pipeline_view::PipelineViewLayout {
        #[cfg(target_os = "windows")]
        if self.surface.is_some() && self.dwrite.is_some() {
            let theme = self.current_theme;
            return crate::primitives::pipeline_view::native_surface_paint::paint(
                view, self, &theme, rect,
            );
        }
        // No surface/DWrite yet — return the real (pure-geometry) layout
        // via `pipeline_view_layout` and paint nothing.
        self.pipeline_view_layout(rect, view)
    }

    /// Pure geometry — `PipelineView::layout` needs no measurer at all
    /// (fixed DIP constants for arrow/action-height), so this needs no
    /// `self.dwrite`/surface at all.
    ///
    /// This used to duplicate `super::pipeline_view`'s
    /// `WIN_ARROW_WIDTH_DIP` / `WIN_ACTION_HEIGHT_DIP` /
    /// `WIN_FOCUS_INDICATOR_H` constants by value (per
    /// `PRIMITIVE_RULES.md`#713, to avoid reaching into that
    /// Windows-only module).
    /// [`crate::primitives::layout_metrics::pixel_pipeline_view_layout`]
    /// is plain, platform-independent geometry, so it can be called
    /// directly here instead — one shared set of constants.
    fn pipeline_view_layout(
        &self,
        rect: Rect,
        view: &crate::primitives::pipeline_view::PipelineView,
    ) -> crate::primitives::pipeline_view::PipelineViewLayout {
        crate::primitives::layout_metrics::pixel_pipeline_view_layout(
            view,
            rect.x,
            rect.y,
            rect.width,
            rect.height,
        )
    }

    /// Paint via the shared
    /// [`crate::primitives::progress::native_surface_paint::paint`] once
    /// a surface is attached — mirrors [`Self::draw_diff_view`]. The
    /// Windows backend now passes `self.current_theme` instead of painting
    /// `Theme::default()`, matching the macOS and GTK backends. See
    /// [`Self::draw_status_bar`]'s doc for the "surface not attached yet"
    /// fallback posture.
    fn draw_progress(&mut self, rect: Rect, bar: &ProgressBar) -> ProgressBarLayout {
        #[cfg(target_os = "windows")]
        if self.surface.is_some() && self.dwrite.is_some() {
            let theme = self.current_theme;
            let style = self.style();
            return crate::primitives::progress::native_surface_paint::paint(
                bar, self, &theme, rect, &style,
            );
        }
        // No surface/DWrite yet — return the real (pure-geometry) layout
        // via `progress_layout` and paint nothing.
        self.progress_layout(rect, bar)
    }

    /// Pure geometry — `ProgressBar::layout` needs no measurer at all
    /// (uniform cancel-affordance width), so this needs no
    /// `self.dwrite`/surface at all.
    ///
    /// This used to duplicate `super::progress`'s `CANCEL_WIDTH_DIP`
    /// constant by value (per `PRIMITIVE_RULES.md`#713, to avoid reaching
    /// into that Windows-only module).
    /// [`crate::primitives::layout_metrics::pixel_progress_layout`] is
    /// plain, platform-independent geometry, so it can be called directly
    /// here instead — one shared constant.
    fn progress_layout(&self, rect: Rect, bar: &ProgressBar) -> ProgressBarLayout {
        crate::primitives::layout_metrics::pixel_progress_layout(
            bar,
            rect.x,
            rect.y,
            rect.width,
            rect.height,
        )
    }

    /// See [`Self::draw_status_bar`]'s doc for the "surface not
    /// attached yet" fallback posture.
    fn draw_spinner(&mut self, rect: Rect, spinner: &Spinner) -> SpinnerLayout {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            // The spinner's label (e.g. "Indexing…") is chrome, not
            // `EditorClassPrimitive`-listed — same `chrome_dwrite`-
            // preferring swap as `Self::draw_palette`.
            let dwrite = self.chrome_dwrite.as_ref().unwrap_or(dwrite);
            return super::spinner::draw_spinner(&surface.target, dwrite, rect, spinner);
        }
        // No surface/DWrite yet — compute the real layout via the same
        // nominal measurer `spinner_layout` falls back to, and paint
        // nothing.
        super::spinner::win_spinner_layout(
            &NominalSpinnerMeasure {
                char_width: self.current_char_width,
                line_height: self.current_line_height,
            },
            rect,
            spinner,
        )
    }

    /// Pure measurement — only needs `self.dwrite`, not a live
    /// render target, so this works as soon as a surface has ever been
    /// attached — same posture as [`Self::status_bar_layout`]. Prefers
    /// `chrome_dwrite`, matching [`Self::draw_spinner`]'s paint font.
    fn spinner_layout(&self, rect: Rect, spinner: &Spinner) -> SpinnerLayout {
        #[cfg(target_os = "windows")]
        if let Some(dwrite) = self.chrome_dwrite.as_ref().or(self.dwrite.as_ref()) {
            return super::spinner::win_spinner_layout(dwrite, rect, spinner);
        }
        super::spinner::win_spinner_layout(
            &NominalSpinnerMeasure {
                char_width: self.current_char_width,
                line_height: self.current_line_height,
            },
            rect,
            spinner,
        )
    }

    /// See [`Self::draw_status_bar`]'s doc for the "surface not
    /// attached yet" fallback posture.
    ///
    /// `CommandCenter` is `ChromePrimitive::CommandCenter` — see
    /// [`Self::draw_tree`]'s note for the font-swap shape.
    /// `char_width` (the search-box width estimate's own input) stays
    /// at the editor's value, same as [`Self::command_center_layout`]
    /// already uses — only the paint font changes here, matching
    /// `GtkBackend::draw_command_center`'s identical split (layout
    /// estimate stays char-width-based; only the Pango paint swaps to
    /// `ui_font`).
    fn draw_command_center(&mut self, rect: Rect, cc: &CommandCenter) -> CommandCenterLayout {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            let dwrite = self.chrome_dwrite.as_ref().unwrap_or(dwrite);
            let layout = super::command_center::draw_command_center(
                &surface.target,
                dwrite,
                self.current_char_width,
                self.current_line_height,
                rect,
                cc,
                &self.current_theme,
            );
            // See "Band-content zone registration" above — the
            // command-centre search box the issue names explicitly.
            self.register_command_center_zones(&cc.id, &layout);
            return layout;
        }
        // No surface yet — return the real (pure `char_width` estimate)
        // layout via `command_center_layout` and paint nothing.
        let layout = self.command_center_layout(rect, cc);
        self.register_command_center_zones(&cc.id, &layout);
        layout
    }

    /// Pure `char_width` estimate (via the shared
    /// [`crate::primitives::command_center::CommandCenterMeasure::from_char_width`]
    /// formula) — no live `DWrite` measurer is needed at all, so this is
    /// computed directly rather than reaching into the Windows-only
    /// `super::command_center` module.
    fn command_center_layout(&self, rect: Rect, cc: &CommandCenter) -> CommandCenterLayout {
        cc.layout(
            rect,
            crate::primitives::command_center::CommandCenterMeasure::from_char_width(
                &cc.search_label,
                self.current_char_width,
                rect.height,
            ),
        )
    }

    /// Paint via the shared
    /// [`crate::primitives::button::native_surface_paint::paint`] once a
    /// surface is attached — mirrors [`Self::draw_progress`]. See
    /// [`Self::draw_status_bar`]'s doc for the "surface not attached yet"
    /// fallback posture.
    fn draw_button(&mut self, rect: Rect, button: &Button) -> ButtonLayout {
        #[cfg(target_os = "windows")]
        if self.surface.is_some() && self.dwrite.is_some() {
            let theme = self.current_theme;
            let style = self.style();
            let layout = crate::primitives::button::native_surface_paint::paint(
                button, self, &theme, rect, &style,
            );
            self.register_zone(button.id, rect);
            return layout;
        }
        // No surface/DWrite yet — return the real (pure-geometry) layout
        // via `button_layout` and paint nothing.
        let layout = self.button_layout(rect, button);
        self.register_zone(button.id, rect);
        layout
    }
    fn button_layout(&self, rect: Rect, button: &Button) -> ButtonLayout {
        button.layout(rect)
    }
    /// See [`Self::draw_button`]'s doc. The per-option measure is
    /// nominal (`rect.width` × the chrome line height) since there is
    /// no native text-metrics surface to measure against yet.
    fn draw_radio_group(&mut self, rect: Rect, group: &RadioGroup) -> RadioGroupLayout {
        #[cfg(target_os = "windows")]
        if self.surface.is_some() && self.dwrite.is_some() {
            let theme = self.current_theme;
            let row_height = self.current_line_height;
            let layout = crate::primitives::radio_group::native_surface_paint::paint(
                group, self, &theme, rect, row_height,
            );
            for (option, item) in group.options.iter().zip(layout.items.iter()) {
                self.register_zone(option.id, *item);
            }
            return layout;
        }
        // No surface/DWrite yet — return the real (pure-geometry) layout
        // via `radio_group_layout` and paint nothing.
        let layout = self.radio_group_layout(rect, group);
        for (option, item) in group.options.iter().zip(layout.items.iter()) {
            self.register_zone(option.id, *item);
        }
        layout
    }
    fn radio_group_layout(&self, rect: Rect, group: &RadioGroup) -> RadioGroupLayout {
        let row_height = self.current_line_height;
        group.layout(rect, |_option: &RadioOption| RadioOptionMeasure {
            width: rect.width,
            height: row_height,
        })
    }
    /// See [`Self::draw_button`]'s doc. Chrome-only (no label of its
    /// own), so this also registers a click zone over the whole `rect` —
    /// same "paint + register" pairing as [`Self::draw_button`].
    fn draw_switch(&mut self, rect: Rect, switch: &Switch) -> SwitchLayout {
        #[cfg(target_os = "windows")]
        if self.surface.is_some() && self.dwrite.is_some() {
            let theme = self.current_theme;
            let layout =
                crate::primitives::switch::native_surface_paint::paint(switch, self, &theme, rect);
            self.register_zone(switch.id, rect);
            return layout;
        }
        // No surface/DWrite yet — return the real (pure-geometry) layout
        // via `switch_layout` and paint nothing.
        let layout = self.switch_layout(rect, switch);
        self.register_zone(switch.id, rect);
        layout
    }
    fn switch_layout(&self, rect: Rect, switch: &Switch) -> SwitchLayout {
        switch.layout(rect)
    }

    /// See [`Self::draw_status_bar`]'s doc for the "surface not
    /// attached yet" fallback posture.
    ///
    /// `Toolbar` is `ChromePrimitive::Toolbar` — see
    /// [`Self::draw_menu_bar`]'s note for why passing
    /// `chrome_dwrite` here keeps `win_toolbar_layout`'s internal
    /// measurement and the paint in agreement; see
    /// [`Self::toolbar_layout`]'s doc for the no-paint twin that must
    /// resolve the same widths.
    fn draw_toolbar_with_options(
        &mut self,
        rect: Rect,
        bar: &crate::primitives::toolbar::Toolbar,
        interaction: &crate::interaction::InteractionState,
        options: crate::primitives::toolbar::ToolbarPaintOptions,
    ) -> crate::primitives::toolbar::ToolbarLayout {
        let (hovered_id, pressed_id) = (interaction.hovered(), interaction.pressed());
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.surface, &self.dwrite) {
            let dwrite = self.chrome_dwrite.as_ref().unwrap_or(dwrite);
            return super::toolbar::draw_toolbar_with_options(
                &surface.target,
                dwrite,
                rect,
                bar,
                hovered_id,
                pressed_id,
                options,
            );
        }
        // No surface/DWrite yet — compute the real layout via the same
        // nominal measurer `toolbar_layout` falls back to, and paint
        // nothing. `hovered_id`/`pressed_id`/`options` only
        // affect painting, so they're unused on this path.
        let _ = (hovered_id, pressed_id, options);
        self.toolbar_layout(rect, bar)
    }

    /// See [`Self::status_bar_layout`]'s doc for why this only
    /// needs `self.dwrite`. Prefers `chrome_dwrite`, matching
    /// [`Self::draw_toolbar_with_options`]'s paint font.
    fn toolbar_layout(
        &self,
        rect: Rect,
        bar: &crate::primitives::toolbar::Toolbar,
    ) -> crate::primitives::toolbar::ToolbarLayout {
        #[cfg(target_os = "windows")]
        if let Some(dwrite) = self.chrome_dwrite.as_ref().or(self.dwrite.as_ref()) {
            return super::toolbar::win_toolbar_layout(dwrite, rect, bar);
        }
        // No live DWrite handle — nominal char-width estimate instead
        let measure = NominalTextMeasure {
            char_width: self.current_char_width,
        };
        bar.layout(rect.x, rect.y, rect.width, rect.height, |btn| {
            crate::primitives::toolbar::ToolbarItemMeasure::new(
                crate::primitives::toolbar::measure_button(&measure, btn),
            )
        })
    }

    /// See [`Self::draw_status_bar`]'s doc for the "surface
    /// not attached yet" fallback posture. `SidebarPanel` embeds a
    /// [`crate::primitives::toolbar::Toolbar`] header, painted here via
    /// the shared
    /// [`crate::primitives::sidebar_panel::native_surface_paint::paint`]
    /// rather than a per-backend `toolbar::draw_toolbar` call.
    ///
    /// `SidebarPanel` is `ChromePrimitive::SidebarPanel` (whole
    /// primitive, including its embedded toolbar header) — see
    /// [`Self::draw_status_bar_interactive`]'s doc for why this paints
    /// through [`ChromeSurface`] instead of `self` directly.
    fn draw_sidebar_panel_interactive(
        &mut self,
        rect: Rect,
        panel: &crate::primitives::sidebar_panel::SidebarPanel,
        interaction: &crate::interaction::InteractionState,
    ) -> crate::primitives::sidebar_panel::SidebarPanelLayout {
        let (hovered_toolbar_id, pressed_toolbar_id) =
            (interaction.hovered(), interaction.pressed());
        #[cfg(target_os = "windows")]
        if self.surface.is_some() && self.dwrite.is_some() {
            let line_height = self.current_line_height;
            // `self.current_theme` is the live theme `Backend::set_theme`
            // writes, same as `WinBackend::draw_panel` above.
            let theme = self.current_theme;
            let mut surface = ChromeSurface { backend: self };
            return crate::primitives::sidebar_panel::native_surface_paint::paint(
                panel,
                &mut surface,
                &theme,
                rect,
                line_height,
                hovered_toolbar_id,
                pressed_toolbar_id,
            );
        }
        // No surface/DWrite yet — compute the real layout via the same
        // nominal measurer `sidebar_panel_layout` falls back to, and
        // paint nothing. `hovered_toolbar_id`/
        // `pressed_toolbar_id` only affect painting, so they're unused
        // on this path.
        let _ = (hovered_toolbar_id, pressed_toolbar_id);
        self.sidebar_panel_layout(rect, panel)
    }

    /// See [`Self::toolbar_layout`]'s doc for why this only needs
    /// `self.dwrite` (text measurement for the nested toolbar's button
    /// widths), not a live render target. Prefers `chrome_dwrite`,
    /// matching [`Self::draw_sidebar_panel_interactive`]'s paint font.
    fn sidebar_panel_layout(
        &self,
        rect: Rect,
        panel: &crate::primitives::sidebar_panel::SidebarPanel,
    ) -> crate::primitives::sidebar_panel::SidebarPanelLayout {
        #[cfg(target_os = "windows")]
        if let Some(dwrite) = self.chrome_dwrite.as_ref().or(self.dwrite.as_ref()) {
            return super::sidebar_panel::win_sidebar_panel_layout(
                dwrite,
                self.current_line_height,
                rect,
                panel,
            );
        }
        // No live DWrite handle — nominal char-width estimate instead
        let measure = NominalTextMeasure {
            char_width: self.current_char_width,
        };
        panel.layout(
            rect,
            crate::primitives::sidebar_panel::SidebarPanelMeasure::new(
                self.current_line_height,
                0.0,
            ),
            |btn| {
                crate::primitives::toolbar::ToolbarItemMeasure::new(
                    crate::primitives::toolbar::measure_button(&measure, btn),
                )
            },
        )
    }

    /// `diff_view_layout` is **not** overridden on this backend —
    /// see `win::diff_view`'s module doc for why the trait default stays
    /// the honest answer even after the shared `DiffView::layout` landed.
    ///
    /// Paint via the shared
    /// [`crate::primitives::diff_view::native_surface_paint::paint`]
    /// once a surface is attached — mirrors [`Self::draw_scrollbar`]. See
    /// that fn's doc for the two named divergences (row/header text
    /// vertical alignment; header-label ellipsize vs. hard-clip) found
    /// while unifying `gtk::diff_view::draw_diff_view`,
    /// `macos::diff_view::draw_diff_view` and
    /// `win::diff_view::draw_diff_view` into one implementation. See
    /// [`Self::draw_status_bar`]'s doc for the "surface not attached yet"
    /// fallback posture.
    fn draw_diff_view(
        &mut self,
        rect: Rect,
        view: &crate::primitives::diff_view::DiffView,
    ) -> crate::primitives::diff_view::DiffViewLayout {
        #[cfg(target_os = "windows")]
        if self.surface.is_some() && self.dwrite.is_some() {
            let theme = self.current_theme;
            let line_height = self.current_line_height;
            // The diff view is editor-class — see the matching comment
            // on `Self::draw_terminal` / `EditorSurface`'s own doc.
            let mut surface = EditorSurface { backend: self };
            return crate::primitives::diff_view::native_surface_paint::paint(
                view,
                &mut surface,
                &theme,
                rect,
                line_height,
            );
        }
        // No surface/DWrite yet — the trait's own default
        // `diff_view_layout` (not overridden here — see this fn's doc)
        // already computes the real row-based layout with no measurer
        // at all, so delegate to it and paint nothing.
        Backend::diff_view_layout(self, rect, view)
    }

    /// See [`Self::draw_status_bar`]'s doc for the "surface not attached
    /// yet" fallback posture.
    ///
    /// Shared chart painting lives in [`crate::primitives::chart::paint`]
    /// now — see that fn's doc for the divergences (the quadraui clip,
    /// most notably — Windows never had one before this) resolved while
    /// unifying `gtk::chart::draw_chart`, `macos::chart::draw_chart` and
    /// `win::chart::draw_chart` into one implementation. Keeps
    /// `Theme::default()` rather than `self.current_theme`, matching
    /// `WinBackend::draw_form`'s own migration — see that fn's doc.
    fn draw_chart(
        &mut self,
        rect: Rect,
        chart: &crate::primitives::chart::Chart,
        hovered_point: Option<(usize, usize)>,
        crosshair_x: Option<f64>,
    ) -> crate::primitives::chart::ChartLayout {
        #[cfg(target_os = "windows")]
        if self.surface.is_some() {
            let layout = self.chart_layout(rect, chart);
            let theme = Theme::default();
            crate::primitives::chart::paint(
                chart,
                &layout,
                self,
                &theme,
                hovered_point,
                crosshair_x,
            );
            return layout;
        }
        // No surface yet — return the real (pure `char_width`/
        // `line_height` estimate) layout via `chart_layout` and paint
        // nothing.
        let _ = (hovered_point, crosshair_x);
        self.chart_layout(rect, chart)
    }

    /// Like [`Self::tree_layout`], no measurer is needed — chart
    /// tick-label sizing only uses `char_width`/`line_height`, both
    /// already cross-platform fields — so this needs no `self.dwrite`/
    /// surface at all, computed directly rather than
    /// reaching into the Windows-only `super::chart` module.
    fn chart_layout(
        &self,
        rect: Rect,
        chart: &crate::primitives::chart::Chart,
    ) -> crate::primitives::chart::ChartLayout {
        crate::primitives::layout_metrics::pixel_chart_layout(
            chart,
            rect.x,
            rect.y,
            rect.width,
            rect.height,
            self.current_line_height,
            self.current_char_width,
        )
    }
}

/// Win-GUI's `WindowControl` surface. Every method guards on
/// `self.hwnd` the same way [`Backend::set_cursor`] does — cheap defense
/// against a caller that stashed the trait object past a window teardown,
/// even though [`Backend::window`] only ever hands one out once `hwnd` is
/// `Some`. `bounds`/`set_bounds`/`set_size` operate on the **outer window
/// rect** (`GetWindowRect`/`SetWindowPos` semantics — includes the
/// title bar and borders), not the client area: computing an exact
/// client-area size would need an `AdjustWindowRectEx` round-trip through
/// the window's current style, which this issue doesn't attempt — see
/// [`Self::bounds`]'s own doc.
///
/// All coordinates cross the DIP ⇄ physical-pixel boundary via
/// [`WinBackend::dpi_scale`], the same field [`Backend::viewport`]'s
/// `scale` mirrors — so a caller working in this crate's native units
/// (DIPs, per every other backend) gets consistent numbers back from
/// [`Self::bounds`] regardless of the monitor's DPI.
impl WindowControl for WinBackend {
    fn set_title(&mut self, title: &str) -> ServiceResult<()> {
        #[cfg(target_os = "windows")]
        {
            let hwnd = self.hwnd.ok_or(BackendError::Unsupported)?;
            let wide = win_wide_nul_terminated(title);
            // SAFETY: `hwnd` is `self.hwnd`, this backend's own live
            // window; `wide` is a `\0`-terminated `Vec<u16>` still in
            // scope, so `wide.as_ptr()` stays valid for the duration of
            // this synchronous call.
            unsafe { SetWindowTextW(hwnd, windows::core::PCWSTR::from_raw(wide.as_ptr())) }.map_err(
                |e| BackendError::PlatformFailure {
                    context: format!("SetWindowTextW: {e}"),
                },
            )
        }
        #[cfg(not(target_os = "windows"))]
        {
            let _ = title;
            Err(BackendError::Unsupported)
        }
    }

    fn set_size(&mut self, width: f32, height: f32) -> ServiceResult<()> {
        #[cfg(target_os = "windows")]
        {
            let hwnd = self.hwnd.ok_or(BackendError::Unsupported)?;
            let scale = self.dpi_scale;
            // SAFETY: `hwnd` is `self.hwnd`, this backend's own live
            // window; `SetWindowPos` takes only handles and plain
            // integers/flags here (`hWndInsertAfter: None` since
            // `SWP_NOZORDER` makes it ignored anyway).
            unsafe {
                SetWindowPos(
                    hwnd,
                    None,
                    0,
                    0,
                    (width * scale).round() as i32,
                    (height * scale).round() as i32,
                    SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE,
                )
            }
            .map_err(|e| BackendError::PlatformFailure {
                context: format!("SetWindowPos: {e}"),
            })
        }
        #[cfg(not(target_os = "windows"))]
        {
            let _ = (width, height);
            Err(BackendError::Unsupported)
        }
    }

    /// **Not available.** A real minimum-size *floor* has to keep holding
    /// during live interactive resize, which Win32 only offers through
    /// `WM_GETMINMAXINFO` — a `wndproc` message this issue doesn't wire
    /// into `win::run` (out of this issue's file list, which names only
    /// `src/win/backend.rs`). A one-shot `SetWindowPos` clamp applied
    /// only at call time would silently stop enforcing the moment the
    /// user next drags an edge, which is a worse lie than declaring the
    /// gap outright — see this trait's own doc for why every method here
    /// prefers `Unsupported` over a partial, silently-abandoned effect.
    fn set_min_size(&mut self, _width: f32, _height: f32) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// **Not available**, same `WM_GETMINMAXINFO` reasoning as
    /// [`Self::set_min_size`].
    fn set_max_size(&mut self, _width: f32, _height: f32) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// The outer window rect (`GetWindowRect`), converted from physical
    /// pixels to DIPs via [`WinBackend::dpi_scale`] — see this `impl`
    /// block's own doc for why this is the outer rect, not the client
    /// area.
    fn bounds(&self) -> ServiceResult<Rect> {
        #[cfg(target_os = "windows")]
        {
            let hwnd = self.hwnd.ok_or(BackendError::Unsupported)?;
            let mut rect = RECT::default();
            // SAFETY: `hwnd` is `self.hwnd`, this backend's own live
            // window; `rect` is stack-local and outlives the call.
            unsafe { GetWindowRect(hwnd, &mut rect) }.map_err(|e| {
                BackendError::PlatformFailure {
                    context: format!("GetWindowRect: {e}"),
                }
            })?;
            let scale = self.dpi_scale.max(0.01);
            Ok(Rect::new(
                rect.left as f32 / scale,
                rect.top as f32 / scale,
                (rect.right - rect.left) as f32 / scale,
                (rect.bottom - rect.top) as f32 / scale,
            ))
        }
        #[cfg(not(target_os = "windows"))]
        {
            Err(BackendError::Unsupported)
        }
    }

    fn set_bounds(&mut self, bounds: Rect) -> ServiceResult<()> {
        #[cfg(target_os = "windows")]
        {
            let hwnd = self.hwnd.ok_or(BackendError::Unsupported)?;
            let scale = self.dpi_scale;
            // SAFETY: `hwnd` is `self.hwnd`, this backend's own live
            // window; only handles and plain integers/flags cross this
            // call.
            unsafe {
                SetWindowPos(
                    hwnd,
                    None,
                    (bounds.x * scale).round() as i32,
                    (bounds.y * scale).round() as i32,
                    (bounds.width * scale).round() as i32,
                    (bounds.height * scale).round() as i32,
                    SWP_NOZORDER | SWP_NOACTIVATE,
                )
            }
            .map_err(|e| BackendError::PlatformFailure {
                context: format!("SetWindowPos: {e}"),
            })
        }
        #[cfg(not(target_os = "windows"))]
        {
            let _ = bounds;
            Err(BackendError::Unsupported)
        }
    }

    fn center(&mut self) -> ServiceResult<()> {
        #[cfg(target_os = "windows")]
        {
            let hwnd = self.hwnd.ok_or(BackendError::Unsupported)?;
            let mut window_rect = RECT::default();
            // SAFETY: `hwnd` is `self.hwnd`, this backend's own live
            // window; `window_rect` is stack-local and outlives the call.
            unsafe { GetWindowRect(hwnd, &mut window_rect) }.map_err(|e| {
                BackendError::PlatformFailure {
                    context: format!("GetWindowRect: {e}"),
                }
            })?;
            let monitor_rect = win_monitor_rect(hwnd)?;
            let w = window_rect.right - window_rect.left;
            let h = window_rect.bottom - window_rect.top;
            let mw = monitor_rect.right - monitor_rect.left;
            let mh = monitor_rect.bottom - monitor_rect.top;
            // SAFETY: `hwnd` is `self.hwnd`, this backend's own live
            // window; only handles and plain integers/flags cross this
            // call.
            unsafe {
                SetWindowPos(
                    hwnd,
                    None,
                    monitor_rect.left + (mw - w) / 2,
                    monitor_rect.top + (mh - h) / 2,
                    0,
                    0,
                    SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE,
                )
            }
            .map_err(|e| BackendError::PlatformFailure {
                context: format!("SetWindowPos: {e}"),
            })
        }
        #[cfg(not(target_os = "windows"))]
        {
            Err(BackendError::Unsupported)
        }
    }

    /// Manual `WS_OVERLAPPEDWINDOW` style strip + `SetWindowPos` to the
    /// nearest monitor's full rect — Win32 has no single reversible
    /// "fullscreen" call the way GTK's `fullscreen`/`unfullscreen` or
    /// AppKit's `toggleFullScreen:` are, so [`WinBackend::fullscreen_saved`]
    /// does the remembering `toggleFullScreen:`'s own window-manager state
    /// would otherwise do for free. Idempotent: entering while already
    /// fullscreen, or exiting while not, is a no-op `Ok(())` rather than
    /// clobbering the saved rect with an already-fullscreen one.
    fn set_fullscreen(&mut self, fullscreen: bool) -> ServiceResult<()> {
        #[cfg(target_os = "windows")]
        {
            let hwnd = self.hwnd.ok_or(BackendError::Unsupported)?;
            if fullscreen {
                if self.fullscreen_saved.is_some() {
                    return Ok(());
                }
                let mut rect = RECT::default();
                // SAFETY: (every `unsafe` block in this arm) `hwnd` is
                // `self.hwnd`, this backend's own live window, for the
                // whole call; `rect` is stack-local; `GetWindowLongPtrW`/
                // `SetWindowLongPtrW` exchange plain `isize` bitmasks (no
                // pointer), and `SetWindowPos` below takes only handles
                // and integers.
                unsafe { GetWindowRect(hwnd, &mut rect) }.map_err(|e| {
                    BackendError::PlatformFailure {
                        context: format!("GetWindowRect: {e}"),
                    }
                })?;
                // SAFETY: see this arm's opening comment above.
                let style = unsafe { GetWindowLongPtrW(hwnd, GWL_STYLE) };
                self.fullscreen_saved = Some((rect, style));
                let stripped = style & !(WS_OVERLAPPEDWINDOW.0 as isize);
                // SAFETY: see this arm's opening comment above.
                unsafe { SetWindowLongPtrW(hwnd, GWL_STYLE, stripped) };
                let monitor_rect = win_monitor_rect(hwnd)?;
                // SAFETY: see this arm's opening comment above.
                unsafe {
                    SetWindowPos(
                        hwnd,
                        None,
                        monitor_rect.left,
                        monitor_rect.top,
                        monitor_rect.right - monitor_rect.left,
                        monitor_rect.bottom - monitor_rect.top,
                        SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED,
                    )
                }
                .map_err(|e| BackendError::PlatformFailure {
                    context: format!("SetWindowPos: {e}"),
                })
            } else {
                let Some((rect, style)) = self.fullscreen_saved.take() else {
                    return Ok(());
                };
                // SAFETY: `hwnd` is `self.hwnd`; `style` is the exact
                // `isize` bitmask `GetWindowLongPtrW` returned when this
                // window entered fullscreen (saved above), so restoring
                // it verbatim is exactly what `SetWindowLongPtrW`
                // documents this call for.
                unsafe { SetWindowLongPtrW(hwnd, GWL_STYLE, style) };
                // SAFETY: `hwnd` is `self.hwnd`; only handles and plain
                // integers/flags cross this call.
                unsafe {
                    SetWindowPos(
                        hwnd,
                        None,
                        rect.left,
                        rect.top,
                        rect.right - rect.left,
                        rect.bottom - rect.top,
                        SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED,
                    )
                }
                .map_err(|e| BackendError::PlatformFailure {
                    context: format!("SetWindowPos: {e}"),
                })
            }
        }
        #[cfg(not(target_os = "windows"))]
        {
            let _ = fullscreen;
            Err(BackendError::Unsupported)
        }
    }

    /// `IsZoomed` — Win32's own maximize-state query, the
    /// same notion `ShowWindow(SW_MAXIMIZE)`/[`Self::restore`] flip.
    fn is_maximized(&self) -> ServiceResult<bool> {
        #[cfg(target_os = "windows")]
        {
            let hwnd = self.hwnd.ok_or(BackendError::Unsupported)?;
            // SAFETY: `hwnd` is `self.hwnd`, this backend's own live
            // window; `IsZoomed` takes only a handle.
            Ok(unsafe { IsZoomed(hwnd) }.as_bool())
        }
        #[cfg(not(target_os = "windows"))]
        {
            Err(BackendError::Unsupported)
        }
    }

    /// `SetWindowPos(HWND_TOPMOST/HWND_NOTOPMOST)` — the one always-on-top
    /// mechanism among the four in-tree backends that actually works
    /// (contrast [`crate::gtk::backend::GtkBackend`]'s `Unsupported` on
    /// GTK4/Wayland).
    fn set_always_on_top(&mut self, on_top: bool) -> ServiceResult<()> {
        #[cfg(target_os = "windows")]
        {
            let hwnd = self.hwnd.ok_or(BackendError::Unsupported)?;
            let insert_after = if on_top { HWND_TOPMOST } else { HWND_NOTOPMOST };
            // SAFETY: `hwnd` is `self.hwnd`, this backend's own live
            // window; `insert_after` is one of the two predefined
            // `HWND_TOPMOST`/`HWND_NOTOPMOST` sentinel values, not a
            // window handle that needs to be independently live.
            unsafe {
                SetWindowPos(
                    hwnd,
                    Some(insert_after),
                    0,
                    0,
                    0,
                    0,
                    SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE,
                )
            }
            .map_err(|e| BackendError::PlatformFailure {
                context: format!("SetWindowPos: {e}"),
            })
        }
        #[cfg(not(target_os = "windows"))]
        {
            let _ = on_top;
            Err(BackendError::Unsupported)
        }
    }

    /// Toggles the `WS_CAPTION` style bit — backs the client-side-
    /// decoration path. `WS_CAPTION` carries both the titlebar and
    /// (implicitly, per Win32's style-bit dependencies) the thin sizing
    /// border that comes with it, so clearing it removes the whole native
    /// non-client frame a host painting its own titlebar wants gone.
    /// `SWP_FRAMECHANGED` forces Windows to recompute the non-client area
    /// from the new style — same requirement `set_fullscreen`'s own
    /// `SetWindowPos` calls already document.
    fn set_decorated(&mut self, decorated: bool) -> ServiceResult<()> {
        #[cfg(target_os = "windows")]
        {
            let hwnd = self.hwnd.ok_or(BackendError::Unsupported)?;
            // SAFETY: (every `unsafe` block in this arm) `hwnd` is
            // `self.hwnd`, this backend's own live window; `GetWindowLongPtrW`/
            // `SetWindowLongPtrW` exchange plain `isize` bitmasks, and
            // `SetWindowPos` below takes only handles and integers/flags.
            let style = unsafe { GetWindowLongPtrW(hwnd, GWL_STYLE) };
            let new_style = if decorated {
                style | (WS_CAPTION.0 as isize)
            } else {
                style & !(WS_CAPTION.0 as isize)
            };
            // SAFETY: see this arm's opening comment above.
            unsafe { SetWindowLongPtrW(hwnd, GWL_STYLE, new_style) };
            // SAFETY: see this arm's opening comment above.
            unsafe {
                SetWindowPos(
                    hwnd,
                    None,
                    0,
                    0,
                    0,
                    0,
                    SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED,
                )
            }
            .map_err(|e| BackendError::PlatformFailure {
                context: format!("SetWindowPos: {e}"),
            })
        }
        #[cfg(not(target_os = "windows"))]
        {
            let _ = decorated;
            Err(BackendError::Unsupported)
        }
    }

    fn minimize(&mut self) -> ServiceResult<()> {
        #[cfg(target_os = "windows")]
        {
            let hwnd = self.hwnd.ok_or(BackendError::Unsupported)?;
            // SAFETY: `hwnd` is `self.hwnd`, this backend's own live
            // window; `ShowWindow` takes only a handle and a plain
            // show-command enum.
            unsafe {
                let _ = ShowWindow(hwnd, SW_MINIMIZE);
            }
            Ok(())
        }
        #[cfg(not(target_os = "windows"))]
        {
            Err(BackendError::Unsupported)
        }
    }

    /// `ShowWindow(SW_RESTORE)` undoes both a minimize and a maximize —
    /// matching `GtkBackend::restore`'s "restores from either state"
    /// posture (see that method's doc for why).
    fn restore(&mut self) -> ServiceResult<()> {
        #[cfg(target_os = "windows")]
        {
            let hwnd = self.hwnd.ok_or(BackendError::Unsupported)?;
            // SAFETY: `hwnd` is `self.hwnd`, this backend's own live
            // window; `ShowWindow` takes only a handle and a plain
            // show-command enum.
            unsafe {
                let _ = ShowWindow(hwnd, SW_RESTORE);
            }
            Ok(())
        }
        #[cfg(not(target_os = "windows"))]
        {
            Err(BackendError::Unsupported)
        }
    }

    fn hide(&mut self) -> ServiceResult<()> {
        #[cfg(target_os = "windows")]
        {
            let hwnd = self.hwnd.ok_or(BackendError::Unsupported)?;
            // SAFETY: `hwnd` is `self.hwnd`, this backend's own live
            // window; `ShowWindow` takes only a handle and a plain
            // show-command enum.
            unsafe {
                let _ = ShowWindow(hwnd, SW_HIDE);
            }
            Ok(())
        }
        #[cfg(not(target_os = "windows"))]
        {
            Err(BackendError::Unsupported)
        }
    }

    fn show(&mut self) -> ServiceResult<()> {
        #[cfg(target_os = "windows")]
        {
            let hwnd = self.hwnd.ok_or(BackendError::Unsupported)?;
            // SAFETY: `hwnd` is `self.hwnd`, this backend's own live
            // window; `ShowWindow` takes only a handle and a plain
            // show-command enum.
            unsafe {
                let _ = ShowWindow(hwnd, SW_SHOW);
            }
            Ok(())
        }
        #[cfg(not(target_os = "windows"))]
        {
            Err(BackendError::Unsupported)
        }
    }

    fn focus(&mut self) -> ServiceResult<()> {
        #[cfg(target_os = "windows")]
        {
            let hwnd = self.hwnd.ok_or(BackendError::Unsupported)?;
            // SAFETY: `hwnd` is `self.hwnd`, this backend's own live
            // window; `SetForegroundWindow` takes only a handle.
            unsafe {
                let _ = SetForegroundWindow(hwnd);
            }
            Ok(())
        }
        #[cfg(not(target_os = "windows"))]
        {
            Err(BackendError::Unsupported)
        }
    }
}

/// Win-GUI's `TrayService` surface, backed by
/// `Shell_NotifyIconW` — see [`super::tray`]'s module doc for the full
/// design (icon decode, the menu-vs-plain-click sequencing, why
/// `ContextMenuDismissed` fires here unlike macOS). Every method just
/// forwards to a free function in that module and a `self.hwnd`
/// guard, the same "thin impl on the struct, real logic in a sibling
/// module" shape [`WindowControl for WinBackend`](WindowControl) above
/// already uses for `super::tray`'s sibling gaps.
impl crate::backend::TrayService for WinBackend {
    fn set_icon(&mut self, icon: crate::primitives::image::ImageSource) -> ServiceResult<()> {
        #[cfg(target_os = "windows")]
        {
            let hwnd = self.hwnd.ok_or(BackendError::Unsupported)?;
            super::tray::set_icon(&mut self.tray, hwnd, icon)
        }
        #[cfg(not(target_os = "windows"))]
        {
            let _ = icon;
            Err(BackendError::Unsupported)
        }
    }

    fn set_tooltip(&mut self, tooltip: &str) -> ServiceResult<()> {
        #[cfg(target_os = "windows")]
        {
            let hwnd = self.hwnd.ok_or(BackendError::Unsupported)?;
            super::tray::set_tooltip(&mut self.tray, hwnd, tooltip)
        }
        #[cfg(not(target_os = "windows"))]
        {
            let _ = tooltip;
            Err(BackendError::Unsupported)
        }
    }

    fn set_menu(
        &mut self,
        menu: &crate::primitives::context_menu::ContextMenu,
    ) -> ServiceResult<()> {
        #[cfg(target_os = "windows")]
        {
            let hwnd = self.hwnd.ok_or(BackendError::Unsupported)?;
            super::tray::set_menu(&mut self.tray, hwnd, menu)
        }
        #[cfg(not(target_os = "windows"))]
        {
            let _ = menu;
            Err(BackendError::Unsupported)
        }
    }
}

impl WinBackend {
    /// The currently-attached tray menu, if any — read by `win::run`'s
    /// `WM_QUADRAUI_TRAY_CALLBACK` wndproc arm to decide whether a tray
    /// click should show a menu or dispatch `UiEvent::TrayClicked`. See
    /// [`super::tray::attached_menu`].
    #[cfg(target_os = "windows")]
    pub(crate) fn tray_menu(&self) -> Option<crate::primitives::context_menu::ContextMenu> {
        super::tray::attached_menu(&self.tray)
    }
}

/// UTF-16, NUL-terminated — the framing every `PCWSTR`-taking Win32
/// call in this backend needs. The one implementation shared crate-wide.
#[cfg(target_os = "windows")]
use crate::desktop::wide_nul_terminated as win_wide_nul_terminated;

/// The nearest monitor's full rect (not the work area — `set_fullscreen`
/// wants to cover the taskbar too) for the monitor `hwnd` is currently
/// on, via `MonitorFromWindow(MONITOR_DEFAULTTONEAREST)` +
/// `GetMonitorInfoW`. Shared by [`WindowControl::center`] (work area
/// would arguably be more correct there, but a single helper covering
/// both callers is a smaller diff than two, and centering a couple of
/// taskbar-heights off from work-area-perfect is a cosmetic gap, not a
/// correctness one) and [`WindowControl::set_fullscreen`].
#[cfg(target_os = "windows")]
fn win_monitor_rect(hwnd: HWND) -> ServiceResult<RECT> {
    // SAFETY: `hwnd` is the caller's live window; `MonitorFromWindow`
    // with `MONITOR_DEFAULTTONEAREST` never fails (it falls back to the
    // nearest monitor rather than erroring), so there is no failure mode
    // to guard against here beyond the type system already requiring a
    // live `HWND`.
    let hmonitor = unsafe { MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST) };
    let mut info = MONITORINFO {
        cbSize: std::mem::size_of::<MONITORINFO>() as u32,
        ..Default::default()
    };
    // SAFETY: `hmonitor` came from `MonitorFromWindow` just above;
    // `info.cbSize` is set to `MONITORINFO`'s size immediately above —
    // the documented Win32 idiom for telling `GetMonitorInfoW` which
    // struct variant was passed (mirrors `services.rs::win_displays`'s
    // identical `MONITORINFOEXW` idiom).
    unsafe { GetMonitorInfoW(hmonitor, &mut info) }
        .ok()
        .map_err(|e| BackendError::PlatformFailure {
            context: format!("GetMonitorInfoW: {e}"),
        })?;
    Ok(info.rcMonitor)
}

// ─── PaintSurface ──────────────────────────────────────────────────────────
//
// The ~15-verb drawing surface underneath `Backend::draw_*`, extracted from
// helpers this backend already had: `super::text::fill_rect`/`stroke_rect`/
// `push_clip`/`pop_clip`/`draw_line` and the inherent `Self::measure_text`/
// `Self::draw_text` (both already `Rect`-taking). Every verb either forwards
// to the identically-named `Backend` method (frame lifecycle, measurement,
// viewport, image) or to the same free function/inherent method a real
// `draw_*` rasteriser would call. Same `#[cfg(target_os = "windows")]` split
// and no-op/nominal-estimate fallback as every other method on this backend.
// See the module doc's "Implementation notes" for why that keeps `cargo check
// --features win` meaningful on Linux. See `paint_surface`'s module doc for
// the full scope note and why these methods are `surface_`-prefixed instead of
// colliding with `Backend`'s.
//
// The default is chrome: the four text-shaped verbs resolve `chrome_dwrite`,
// falling back to the editor `dwrite` handle only when no live chrome handle
// exists yet — the same default `MacBackend`'s and `GtkBackend`'s own
// `PaintSurface` impls carry. [`EditorSurface`] (below) is the opt-out adapter
// the three editor-class call sites that reach this trait wrap `self` in
// instead, mirroring `MacBackend::EditorSurface`/`GtkBackend::EditorSurface`.
// [`ChromeSurface`] (also below) still exists for call sites that already wrap
// `self` in it — harmless, since it resolves the same default plain `self` does.
impl PaintSurface for WinBackend {
    fn surface_begin_frame(&mut self, viewport: Viewport) {
        Backend::begin_frame(self, viewport);
    }

    fn surface_end_frame(&mut self) {
        Backend::end_frame(self);
    }

    fn surface_viewport(&self) -> Viewport {
        Backend::viewport(self)
    }

    fn surface_line_height(&self) -> f32 {
        Backend::line_height(self)
    }

    fn surface_char_width(&self) -> f32 {
        Backend::char_width(self)
    }

    /// `self` is the surface every non-editor-class primitive
    /// measures/paints through unwrapped (`draw_data_table`'s shared
    /// paint helper, `draw_panel`, `draw_toast_overlay`, …), so this
    /// resolves `chrome_dwrite` — falling back to the editor `dwrite`
    /// handle only when no live chrome handle exists yet, the same
    /// "degrade, don't panic" convention
    /// [`Self::surface_draw_text_run_with_role`] already documents —
    /// rather than `dwrite` unconditionally. See [`EditorSurface`]'s doc
    /// for the three editor-class primitives that opt back into the
    /// editor font via a dedicated adapter instead, and
    /// `crate::font_role`'s module doc for why a non-editor-class
    /// primitive must never resolve the editor font.
    fn surface_measure_text(&self, text: &str) -> (f32, f32) {
        #[cfg(target_os = "windows")]
        if let Some(d) = self.chrome_dwrite.as_ref().or(self.dwrite.as_ref()) {
            if let Ok(m) = d.measure_text(text) {
                return m;
            }
        }
        // No live DWrite handle (fresh backend, device lost, or a
        // non-Windows host where this never compiles) — a measurement
        // can't be faked meaningfully, but a wrong-but-finite nominal
        // per-character estimate beats a dead process. Real
        // widths resume once a surface exists.
        (
            nominal_text_width(text, self.current_char_width),
            self.current_line_height,
        )
    }

    /// Overrides the default (which drops `bold`) —
    /// `DWrite::measure_text_styled` already exists on this backend,
    /// matching what `win::status_bar::draw_status_bar` measured
    /// before its paint moved to
    /// `primitives::status_bar::native_surface_paint::paint`. Also
    /// resolves `chrome_dwrite` now, matching
    /// [`Self::surface_measure_text`]'s doc above.
    fn surface_measure_text_styled(&self, text: &str, bold: bool) -> (f32, f32) {
        #[cfg(not(target_os = "windows"))]
        let _ = bold;
        #[cfg(target_os = "windows")]
        if let Some(d) = self.chrome_dwrite.as_ref().or(self.dwrite.as_ref()) {
            if let Ok(m) = d.measure_text_styled(text, bold) {
                return m;
            }
        }
        // See `surface_measure_text`'s doc for why this nominal estimate
        // (rather than `(0.0, 0.0)`) is the chosen degrade.
        (
            nominal_text_width(text, self.current_char_width),
            self.current_line_height,
        )
    }

    fn surface_fill_rect(&mut self, rect: Rect, color: crate::Color) {
        #[cfg(target_os = "windows")]
        if let Some(surface) = &self.surface {
            let _ = super::text::fill_rect(&surface.target, rect, color);
            return;
        }
        // See `WinBackend::draw_tree`'s doc for why this degrades to a
        // no-op instead of panicking.
        let _ = (rect, color);
    }

    /// `super::text::fill_rounded_rect` is the
    /// `FillRoundedRectangle` twin of `fill_rect` above — same
    /// no-surface degrade as every other verb here.
    fn surface_fill_rounded_rect(&mut self, rect: Rect, radius: f32, color: crate::Color) {
        #[cfg(target_os = "windows")]
        if let Some(surface) = &self.surface {
            let _ = super::text::fill_rounded_rect(&surface.target, rect, radius, color);
            return;
        }
        // See `WinBackend::draw_tree`'s doc for why this degrades to a
        // no-op instead of panicking.
        let _ = (rect, radius, color);
    }

    fn surface_stroke_rect(&mut self, rect: Rect, color: crate::Color, stroke_width: f32) {
        #[cfg(target_os = "windows")]
        if let Some(surface) = &self.surface {
            let _ = super::text::stroke_rect(&surface.target, rect, color, stroke_width);
            return;
        }
        // See `WinBackend::draw_tree`'s doc for why this degrades to a
        // no-op instead of panicking.
        let _ = (rect, color, stroke_width);
    }

    /// `super::text::stroke_rounded_rect` is the
    /// `DrawRoundedRectangle` twin of `stroke_rect` above — same
    /// no-surface degrade as every other verb here.
    fn surface_stroke_rounded_rect(
        &mut self,
        rect: Rect,
        radius: f32,
        color: crate::Color,
        stroke_width: f32,
    ) {
        #[cfg(target_os = "windows")]
        if let Some(surface) = &self.surface {
            let _ = super::text::stroke_rounded_rect(
                &surface.target,
                rect,
                radius,
                color,
                stroke_width,
            );
            return;
        }
        // See `WinBackend::draw_tree`'s doc for why this degrades to a
        // no-op instead of panicking.
        let _ = (rect, radius, color, stroke_width);
    }

    /// See [`Self::surface_measure_text`]'s doc for why this resolves
    /// `chrome_dwrite` rather than the editor `dwrite` handle
    /// unconditionally.
    fn surface_draw_text_run(&mut self, rect: Rect, text: &str, color: crate::Color) {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (
            &self.surface,
            self.chrome_dwrite.as_ref().or(self.dwrite.as_ref()),
        ) {
            let _ = dwrite.draw_text(&surface.target, text, rect, color);
            return;
        }
        // No live surface/DWrite handle — degrades to a no-op rather
        // than panicking, matching every other verb on this impl.
        let _ = (rect, text, color);
    }

    /// Overrides the default (which drops styling) for `bold`
    #[allow(clippy::too_many_arguments)]
    fn surface_draw_text_run_styled(
        &mut self,
        rect: Rect,
        text: &str,
        color: crate::Color,
        bold: bool,
        italic: bool,
        underline: bool,
        scale_x: f32,
    ) {
        let _ = (italic, underline);
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (
            &self.surface,
            self.chrome_dwrite.as_ref().or(self.dwrite.as_ref()),
        ) {
            if (scale_x - 1.0).abs() > f32::EPSILON {
                super::text::with_horizontal_scale(&surface.target, scale_x, rect.x, || {
                    let _ = dwrite.draw_text_styled(&surface.target, text, rect, color, bold);
                });
            } else {
                let _ = dwrite.draw_text_styled(&surface.target, text, rect, color, bold);
            }
            return;
        }
        // See `WinBackend::draw_tree`'s doc for why this degrades to a
        // no-op instead of panicking.
        let _ = (rect, text, color, bold, scale_x);
    }

    /// Overrides the default (which ignores `role`) to select `chrome_dwrite`
    fn surface_draw_text_run_with_role(
        &mut self,
        rect: Rect,
        text: &str,
        color: crate::Color,
        role: crate::FontRole,
        italic: bool,
    ) {
        let _ = italic;
        #[cfg(target_os = "windows")]
        if let Some(surface) = &self.surface {
            // Chrome text falls back to the editor `dwrite` handle if no
            // live chrome one exists yet — same "degrade, don't panic"
            // convention as `WinBackend::draw_tree`'s doc describes.
            let dwrite = match role {
                crate::FontRole::Chrome => self.chrome_dwrite.as_ref().or(self.dwrite.as_ref()),
                crate::FontRole::Editor => self.dwrite.as_ref(),
            };
            if let Some(dwrite) = dwrite {
                let _ = dwrite.draw_text(&surface.target, text, rect, color);
                return;
            }
        }
        // See `WinBackend::draw_tree`'s doc for why this degrades to a
        // no-op instead of panicking.
        let _ = (rect, text, color, role);
    }

    /// Overrides the default only to document why it needn't
    /// change anything — `DWrite::new` already bakes
    /// [`Self::set_nerd_font_fallback`]'s `IDWriteFontFallback` into
    /// every `IDWriteTextFormat` it builds (editor and chrome alike) via
    /// `IDWriteTextFormat1::SetFontFallback`, so
    /// [`Self::surface_draw_text_run`] already resolves an icon glyph
    /// the same way this verb would.
    fn surface_draw_icon_glyph(&mut self, rect: Rect, text: &str, color: crate::Color) {
        self.surface_draw_text_run(rect, text, color)
    }

    fn surface_draw_line(
        &mut self,
        from: Point,
        to: Point,
        color: crate::Color,
        stroke_width: f32,
    ) {
        #[cfg(target_os = "windows")]
        if let Some(surface) = &self.surface {
            let _ = super::text::draw_line(
                &surface.target,
                from.x,
                from.y,
                to.x,
                to.y,
                color,
                stroke_width,
            );
            return;
        }
        // See `WinBackend::draw_tree`'s doc for why this degrades to a
        // no-op instead of panicking.
        let _ = (from, to, color, stroke_width);
    }

    fn surface_push_clip(&mut self, rect: Rect) {
        #[cfg(target_os = "windows")]
        if let Some(surface) = &self.surface {
            super::text::push_clip(&surface.target, rect);
            return;
        }
        // See `WinBackend::draw_tree`'s doc for why this degrades to a
        // no-op instead of panicking.
        let _ = rect;
    }

    fn surface_pop_clip(&mut self) {
        #[cfg(target_os = "windows")]
        if let Some(surface) = &self.surface {
            super::text::pop_clip(&surface.target);
        }
        // See `WinBackend::draw_tree`'s doc for why this degrades to a
        // no-op instead of panicking.
    }

    fn surface_draw_image(
        &mut self,
        rect: Rect,
        image: &crate::primitives::image::Image,
    ) -> crate::backend::ImagePaintResult {
        Backend::draw_image(self, rect, image)
    }
}

/// Win-GUI twin of `MacBackend`'s `ChromeSurface` (see that
/// struct's own doc) — wraps a `&mut WinBackend` so a primitive already
/// migrated onto [`PaintSurface`] (today: [`Self::draw_status_bar_interactive`],
/// [`Self::draw_sidebar_panel_interactive`]) paints through
/// `chrome_dwrite` (falling back to the editor `dwrite` handle if no
/// live chrome one exists yet — same "degrade, don't panic" convention
/// as `WinBackend::surface_draw_text_run_with_role`) instead of
/// `WinBackend`'s own [`PaintSurface`] impl above, which always
/// resolves the editor `dwrite` handle. Only the four text-shaped
/// methods below differ; every other verb forwards straight to
/// `self.backend`.
///
/// Line height / char width are **not** swapped — row geometry stays
/// seeded from the editor font's own metrics even while painting chrome
/// text, matching [`Self::draw_dialog`]'s already-shipped behaviour (see
/// that method's own test, "the row's clip box" paragraph, for why that
/// divergence is already accepted on this backend). A future issue that
/// gives `WinBackend` its own `chrome_line_height`/`chrome_char_width`
/// fields — mirroring `MacBackend::chrome_line_height`/
/// `chrome_char_width` — can revisit this; it is out of this issue's
/// scope.
// `ChromeSurface` is only ever constructed inside a `#[cfg(target_os =
// "windows")]` block, so a non-Windows `--features win` check never
// constructs it. This mirrors the identical
// `#[cfg_attr(not(target_os = "windows"), allow(dead_code))]` already used
// elsewhere in this file for the same reason.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
struct ChromeSurface<'a> {
    backend: &'a mut WinBackend,
}

impl PaintSurface for ChromeSurface<'_> {
    fn surface_begin_frame(&mut self, viewport: Viewport) {
        self.backend.surface_begin_frame(viewport)
    }

    fn surface_end_frame(&mut self) {
        self.backend.surface_end_frame()
    }

    fn surface_viewport(&self) -> Viewport {
        self.backend.surface_viewport()
    }

    fn surface_line_height(&self) -> f32 {
        self.backend.surface_line_height()
    }

    fn surface_char_width(&self) -> f32 {
        self.backend.surface_char_width()
    }

    fn surface_measure_text(&self, text: &str) -> (f32, f32) {
        #[cfg(target_os = "windows")]
        if let Some(d) = self
            .backend
            .chrome_dwrite
            .as_ref()
            .or(self.backend.dwrite.as_ref())
        {
            if let Ok(m) = d.measure_text(text) {
                return m;
            }
        }
        self.backend.surface_measure_text(text)
    }

    fn surface_measure_text_styled(&self, text: &str, bold: bool) -> (f32, f32) {
        #[cfg(target_os = "windows")]
        if let Some(d) = self
            .backend
            .chrome_dwrite
            .as_ref()
            .or(self.backend.dwrite.as_ref())
        {
            if let Ok(m) = d.measure_text_styled(text, bold) {
                return m;
            }
        }
        self.backend.surface_measure_text_styled(text, bold)
    }

    fn surface_fill_rect(&mut self, rect: Rect, color: crate::Color) {
        self.backend.surface_fill_rect(rect, color)
    }

    fn surface_fill_rounded_rect(&mut self, rect: Rect, radius: f32, color: crate::Color) {
        self.backend.surface_fill_rounded_rect(rect, radius, color)
    }

    fn surface_stroke_rect(&mut self, rect: Rect, color: crate::Color, stroke_width: f32) {
        self.backend.surface_stroke_rect(rect, color, stroke_width)
    }

    fn surface_stroke_rounded_rect(
        &mut self,
        rect: Rect,
        radius: f32,
        color: crate::Color,
        stroke_width: f32,
    ) {
        self.backend
            .surface_stroke_rounded_rect(rect, radius, color, stroke_width)
    }

    fn surface_draw_text_run(&mut self, rect: Rect, text: &str, color: crate::Color) {
        #[cfg(target_os = "windows")]
        if let Some(surface) = &self.backend.surface {
            let dwrite = self
                .backend
                .chrome_dwrite
                .as_ref()
                .or(self.backend.dwrite.as_ref());
            if let Some(dwrite) = dwrite {
                let _ = dwrite.draw_text(&surface.target, text, rect, color);
                return;
            }
        }
        // See `WinBackend::draw_tree`'s doc for why this degrades to a
        // no-op instead of panicking.
        let _ = (rect, text, color);
    }

    /// Chrome twin of `WinBackend`'s own #810 override — same
    /// `italic`/`underline`-unsupported posture, same `scale_x` support
    /// via `super::text::with_horizontal_scale`, just against
    /// `chrome_dwrite` (falling back to `dwrite`).
    #[allow(clippy::too_many_arguments)]
    fn surface_draw_text_run_styled(
        &mut self,
        rect: Rect,
        text: &str,
        color: crate::Color,
        bold: bool,
        italic: bool,
        underline: bool,
        scale_x: f32,
    ) {
        let _ = (italic, underline);
        #[cfg(target_os = "windows")]
        if let Some(surface) = &self.backend.surface {
            let dwrite = self
                .backend
                .chrome_dwrite
                .as_ref()
                .or(self.backend.dwrite.as_ref());
            if let Some(dwrite) = dwrite {
                if (scale_x - 1.0).abs() > f32::EPSILON {
                    super::text::with_horizontal_scale(&surface.target, scale_x, rect.x, || {
                        let _ = dwrite.draw_text_styled(&surface.target, text, rect, color, bold);
                    });
                } else {
                    let _ = dwrite.draw_text_styled(&surface.target, text, rect, color, bold);
                }
                return;
            }
        }
        // See `WinBackend::draw_tree`'s doc for why this degrades to a
        // no-op instead of panicking.
        let _ = (rect, text, color, bold, scale_x);
    }

    fn surface_draw_line(
        &mut self,
        from: Point,
        to: Point,
        color: crate::Color,
        stroke_width: f32,
    ) {
        self.backend
            .surface_draw_line(from, to, color, stroke_width)
    }

    fn surface_push_clip(&mut self, rect: Rect) {
        self.backend.surface_push_clip(rect)
    }

    fn surface_pop_clip(&mut self) {
        self.backend.surface_pop_clip()
    }

    fn surface_draw_image(
        &mut self,
        rect: Rect,
        image: &crate::primitives::image::Image,
    ) -> crate::backend::ImagePaintResult {
        self.backend.surface_draw_image(rect, image)
    }
}

/// The editor-class twin of [`ChromeSurface`] just above — the Win-GUI
/// twin of `MacBackend::EditorSurface`/`GtkBackend::EditorSurface` (see
/// those types' own docs). That adapter exists to reach `chrome_dwrite`
/// from a primitive-generic call site; this one exists to reach the
/// editor `dwrite` handle from one, since `WinBackend`'s own
/// [`PaintSurface`] impl (above) now defaults to `chrome_dwrite` and a
/// handful of primitives still need the editor font. The terminal and
/// the plain text display paint through this trait and need
/// `EditorSurface`; the diff view also paints through this trait and
/// needs it too. The full-screen editor paints through its own dedicated
/// DirectWrite calls instead of this trait at all (see
/// [`WinBackend::draw_editor`]), so it needs neither adapter. The
/// minimap and the command line are `crate::font_role::EditorClassPrimitive`
/// too, but both reach their own dedicated `win::minimap`/
/// `win::command_line` module functions directly with the editor
/// `dwrite` handle (see [`WinBackend::draw_minimap`]/
/// [`WinBackend::draw_command_line_selection`]) rather than through this
/// trait, so they need no adapter here either.
///
/// Every font-agnostic method (fills, strokes, clip, lines, images, frame
/// lifecycle) forwards straight through to [`WinBackend`]'s own impl,
/// which doesn't read the font either way. Line height / char width are
/// **not** overridden, the same posture [`ChromeSurface`]'s own doc
/// documents for the opposite direction — row geometry stays seeded from
/// the editor font's own metrics regardless of which adapter wraps
/// `self`, since `WinBackend` has no separate `chrome_line_height`/
/// `chrome_char_width` fields to diverge from it (out of this issue's
/// scope — see [`ChromeSurface`]'s doc).
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
struct EditorSurface<'a> {
    backend: &'a mut WinBackend,
}

impl PaintSurface for EditorSurface<'_> {
    fn surface_begin_frame(&mut self, viewport: Viewport) {
        self.backend.surface_begin_frame(viewport)
    }

    fn surface_end_frame(&mut self) {
        self.backend.surface_end_frame()
    }

    fn surface_viewport(&self) -> Viewport {
        self.backend.surface_viewport()
    }

    fn surface_line_height(&self) -> f32 {
        self.backend.surface_line_height()
    }

    fn surface_char_width(&self) -> f32 {
        self.backend.surface_char_width()
    }

    /// Forces the editor `dwrite` handle explicitly rather than
    /// `WinBackend`'s own (now chrome-resolving) default — see this
    /// type's own doc.
    fn surface_measure_text(&self, text: &str) -> (f32, f32) {
        #[cfg(target_os = "windows")]
        if let Some(d) = self.backend.dwrite.as_ref() {
            if let Ok(m) = d.measure_text(text) {
                return m;
            }
        }
        (
            nominal_text_width(text, self.backend.current_char_width),
            self.backend.current_line_height,
        )
    }

    /// See [`Self::surface_measure_text`]'s doc for why this forces the
    /// editor `dwrite` handle explicitly.
    fn surface_measure_text_styled(&self, text: &str, bold: bool) -> (f32, f32) {
        #[cfg(not(target_os = "windows"))]
        let _ = bold;
        #[cfg(target_os = "windows")]
        if let Some(d) = self.backend.dwrite.as_ref() {
            if let Ok(m) = d.measure_text_styled(text, bold) {
                return m;
            }
        }
        (
            nominal_text_width(text, self.backend.current_char_width),
            self.backend.current_line_height,
        )
    }

    fn surface_fill_rect(&mut self, rect: Rect, color: crate::Color) {
        self.backend.surface_fill_rect(rect, color)
    }

    fn surface_fill_rounded_rect(&mut self, rect: Rect, radius: f32, color: crate::Color) {
        self.backend.surface_fill_rounded_rect(rect, radius, color)
    }

    fn surface_stroke_rect(&mut self, rect: Rect, color: crate::Color, stroke_width: f32) {
        self.backend.surface_stroke_rect(rect, color, stroke_width)
    }

    fn surface_stroke_rounded_rect(
        &mut self,
        rect: Rect,
        radius: f32,
        color: crate::Color,
        stroke_width: f32,
    ) {
        self.backend
            .surface_stroke_rounded_rect(rect, radius, color, stroke_width)
    }

    /// See [`Self::surface_measure_text`]'s doc for why this forces the
    /// editor `dwrite` handle explicitly.
    fn surface_draw_text_run(&mut self, rect: Rect, text: &str, color: crate::Color) {
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.backend.surface, self.backend.dwrite.as_ref())
        {
            let _ = dwrite.draw_text(&surface.target, text, rect, color);
            return;
        }
        // No live editor `dwrite` handle — degrades to a no-op rather
        // than panicking, matching every other verb on this adapter.
        let _ = (rect, text, color);
    }

    /// The editor-`dwrite` twin of `WinBackend`'s own (now
    /// chrome-resolving) override — same `italic`/`underline`-
    /// unsupported posture, same `scale_x` support via
    /// `super::text::with_horizontal_scale`, just forced onto the editor
    /// `dwrite` handle instead of `chrome_dwrite`.
    #[allow(clippy::too_many_arguments)]
    fn surface_draw_text_run_styled(
        &mut self,
        rect: Rect,
        text: &str,
        color: crate::Color,
        bold: bool,
        italic: bool,
        underline: bool,
        scale_x: f32,
    ) {
        let _ = (italic, underline);
        #[cfg(target_os = "windows")]
        if let (Some(surface), Some(dwrite)) = (&self.backend.surface, self.backend.dwrite.as_ref())
        {
            if (scale_x - 1.0).abs() > f32::EPSILON {
                super::text::with_horizontal_scale(&surface.target, scale_x, rect.x, || {
                    let _ = dwrite.draw_text_styled(&surface.target, text, rect, color, bold);
                });
            } else {
                let _ = dwrite.draw_text_styled(&surface.target, text, rect, color, bold);
            }
            return;
        }
        // No live editor `dwrite` handle — degrades to a no-op rather
        // than panicking, matching every other verb on this adapter.
        let _ = (rect, text, color, bold, scale_x);
    }

    fn surface_draw_line(
        &mut self,
        from: Point,
        to: Point,
        color: crate::Color,
        stroke_width: f32,
    ) {
        self.backend
            .surface_draw_line(from, to, color, stroke_width)
    }

    fn surface_push_clip(&mut self, rect: Rect) {
        self.backend.surface_push_clip(rect)
    }

    fn surface_pop_clip(&mut self) {
        self.backend.surface_pop_clip()
    }

    fn surface_draw_image(
        &mut self,
        rect: Rect,
        image: &crate::primitives::image::Image,
    ) -> crate::backend::ImagePaintResult {
        self.backend.surface_draw_image(rect, image)
    }
}

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

    /// Build a flat tree of `n_rows` leaf rows for `tree_vscrollbar`
    /// integration tests.
    fn flat_tree(n_rows: usize) -> TreeView {
        TreeView {
            id: WidgetId::new("test:tree:vscrollbar"),
            rows: (0..n_rows)
                .map(|i| crate::primitives::tree::TreeRow {
                    path: vec![i as u16],
                    indent: 0,
                    icon: None,
                    text: crate::types::StyledText::plain(format!("row{i}")),
                    badge: None,
                    is_expanded: None,
                    decoration: crate::types::Decoration::Normal,
                    edit: None,
                })
                .collect(),
            selection_mode: crate::types::SelectionMode::Single,
            selected_path: None,
            scroll_offset: 0,
            style: crate::types::TreeStyle::default(),
            has_focus: false,
        }
    }

    /// `tree_vscrollbar` must use the `line_height * 1.4` pitch
    /// `layout_metrics::tree_layout` paints for non-header rows, not the raw
    /// `line_height`. With 15 rows at the real 22.4px→22px pitch, only 13 fit
    /// into a 300px-tall viewport (300/22 = 13), so an overflow scrollbar must
    /// appear — the raw-`line_height` math (300/16 = 18) would have wrongly
    /// reported "everything fits". The row pitch governs the minimum thumb
    /// length, not the track's (fixed 10px) width. Cross-platform: no
    /// `target_os = "windows"` gate needed — see `tree_vscrollbar`'s doc.
    #[test]
    fn win_backend_tree_vscrollbar_uses_tree_layout_row_pitch_not_raw_line_height() {
        let backend = WinBackend::new();
        let tree = flat_tree(15);
        let rect = Rect::new(0.0, 0.0, 20.0, 300.0);

        let sb = Backend::tree_vscrollbar(&backend, rect, &tree)
            .expect("15 rows at the real 22px row pitch overflow a 300px viewport");

        let expected_row_h = ((backend.current_line_height as f64 * 1.4).round()) as f32;
        assert_eq!(
            sb.track.width,
            crate::primitives::layout_metrics::pixel::TREE_VSCROLLBAR_WIDTH,
            "track width must stay the fixed VS Code list/tree scrollbar width"
        );
        assert!(
            sb.thumb_len >= expected_row_h,
            "minimum thumb length (and row pitch) must match tree_layout's \
             non-header item_height, not the raw line_height"
        );
    }

    /// Pre-attach fallback: before a surface/DirectWrite
    /// handle exists (`dwrite`/`chrome_dwrite` both `None`, the state any
    /// fresh `WinBackend` starts in, and the only state this crate's
    /// non-Windows CI leg ever exercises for this method — see
    /// `Backend::measure_text`'s doc), `measure_text` degrades to a
    /// `current_char_width`-scaled estimate, matching every other
    /// pre-attach degrade on this backend. Cross-platform: no
    /// `target_os = "windows"` gate needed, same rationale as
    /// `win_backend_tree_vscrollbar_uses_tree_layout_row_pitch_not_raw_line_height`
    /// above.
    #[test]
    fn win_backend_measure_text_falls_back_to_char_width_before_a_surface_attaches() {
        let mut backend = WinBackend::new();
        backend.current_char_width = 9.0;
        backend.current_line_height = 18.0;

        let (w, h) = Backend::measure_text(&backend, "abcd", crate::FontRole::Chrome);
        assert_eq!(w, 4.0 * 9.0);
        assert_eq!(h, 18.0);
    }

    /// Once a headless surface attaches, `measure_text` must
    /// resolve a genuinely different `IDWriteTextFormat` per
    /// [`crate::FontRole`] — `chrome_dwrite` for
    /// [`crate::FontRole::Chrome`], `dwrite` for
    /// [`crate::FontRole::Editor`] — mirroring
    /// `measure_text_resolves_a_different_font_per_role` in
    /// `macos::backend`'s own test module. Windows-only: DirectWrite
    /// isn't available to attach a real surface against on the ubuntu
    /// `cargo check --features win` leg.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_measure_text_resolves_a_different_font_per_role() {
        use crate::win::testing::HeadlessSurface;

        let surface = HeadlessSurface::new(100, 100).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend.set_editor_font(DEFAULT_EDITOR_FONT_FAMILY, 10.0);
        backend.set_ui_font(&format!("{DEFAULT_UI_FONT_FAMILY} 40"));
        backend
            .attach_headless(surface.target().clone(), 100, 100)
            .expect("attach headless surface");

        let (chrome_w, _) = Backend::measure_text(&backend, "quadraui", crate::FontRole::Chrome);
        let (editor_w, _) = Backend::measure_text(&backend, "quadraui", crate::FontRole::Editor);

        assert!(
            chrome_w > editor_w * 2.0,
            "a 40pt chrome font should measure \"quadraui\" much wider than a \
             10pt editor font: chrome_w={chrome_w}, editor_w={editor_w}"
        );
    }

    /// Repainting the same frame twice must
    /// not create any new `ID2D1SolidColorBrush`es, and painting the
    /// first frame must create no more brushes than the number of
    /// distinct colors it actually drew. Before `super::text`'s brush
    /// cache, every `surface_fill_rect` call below (a stand-in for a
    /// chrome rasteriser's per-primitive fill/stroke/text calls, all of
    /// which go through the same `get_or_create_brush` choke point) would
    /// have created and dropped its own brush, so this would have failed
    /// with `created_frame_1 == 12` (one per fill call) and
    /// `created_frame_2 == 12` again — the exact "brushes scale with
    /// primitive count, not color count" problem this issue measured at
    /// 647 brushes/frame on a real 1639x1079 window.
    #[cfg(target_os = "windows")]
    #[test]
    fn repaint_reuses_cached_brushes_creating_no_new_ones() {
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 64;
        const H: u32 = 64;
        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        // Three distinct colors, each painted four times — more
        // primitives than colors, mirroring a real chrome rasteriser
        // painting many same-colored fills/strokes/text runs per frame.
        let colors = [
            crate::Color::rgb(10, 20, 30),
            crate::Color::rgb(200, 50, 50),
            crate::Color::rgb(0, 128, 255),
        ];
        const FILLS_PER_COLOR: usize = 4;

        let paint_frame = |backend: &mut WinBackend| {
            backend.surface_begin_frame(Viewport::new(W as f32, H as f32, 1.0));
            for (i, &color) in colors.iter().enumerate() {
                for j in 0..FILLS_PER_COLOR {
                    let x = (i * FILLS_PER_COLOR + j) as f32 * 2.0;
                    backend.surface_fill_rect(Rect::new(x, 0.0, 2.0, 2.0), color);
                }
            }
            backend.surface_end_frame();
        };

        crate::win::text::reset_brush_creation_count();

        paint_frame(&mut backend);
        let created_frame_1 = crate::win::text::brush_creation_count();
        assert!(
            created_frame_1 > 0 && created_frame_1 as usize <= colors.len(),
            "painting {} distinct colors ({} fills total) should create at most \
             {} brushes (one per distinct color), got {created_frame_1}",
            colors.len(),
            colors.len() * FILLS_PER_COLOR,
            colors.len()
        );

        paint_frame(&mut backend);
        let created_frame_2 = crate::win::text::brush_creation_count() - created_frame_1;
        assert_eq!(
            created_frame_2,
            0,
            "repainting the exact same colors in frame 2 must create zero new brushes \
             (cache miss count went from {created_frame_1} to \
             {})",
            crate::win::text::brush_creation_count()
        );

        // Render-target recreate (the `EndDraw`-failure path): the new
        // surface starts with an empty cache, so the next frame re-creates
        // exactly one brush per color, and the frame after that none.
        backend.drop_surface_for_testing();
        backend.ensure_surface().expect("recreate headless surface");
        crate::win::text::reset_brush_creation_count();
        paint_frame(&mut backend);
        assert_eq!(
            crate::win::text::brush_creation_count() as usize,
            colors.len(),
            "a recreated render target must not reuse the old target's brushes"
        );
        paint_frame(&mut backend);
        assert_eq!(
            crate::win::text::brush_creation_count() as usize,
            colors.len(),
            "repainting after a recreate must hit the new surface's cache"
        );

        // Outside a backend frame no cache is active, so helpers painting
        // straight onto the target create one-off brushes, as before.
        crate::win::text::reset_brush_creation_count();
        surface
            .paint(|target| {
                crate::win::text::fill_rect(target, Rect::new(0.0, 0.0, 2.0, 2.0), colors[0])
                    .expect("fill_rect");
                crate::win::text::fill_rect(target, Rect::new(2.0, 0.0, 2.0, 2.0), colors[0])
                    .expect("fill_rect");
            })
            .expect("headless paint");
        assert_eq!(crate::win::text::brush_creation_count(), 2);
    }

    /// `default_fonts()` reports Win-GUI's VS-Code-alignment convention
    /// (`Consolas 14`/`Segoe UI 13`) — cross-platform, no `target_os =
    /// "windows"` gate needed, same rationale as
    /// `win_backend_tree_vscrollbar_uses_tree_layout_row_pitch_not_raw_line_height` above.
    #[test]
    fn win_backend_default_fonts_reports_platform_convention() {
        let backend = WinBackend::new();
        let defaults = Backend::default_fonts(&backend);
        assert_eq!(defaults.editor_family, "Consolas");
        assert_eq!(defaults.editor_size_pt, 14.0);
        assert_eq!(defaults.ui_family, "Segoe UI");
        assert_eq!(defaults.ui_size_pt, 13.0);
    }

    /// A prior `set_editor_font`/`set_ui_font` call must not perturb
    /// `default_fonts()` — it reports a static platform fact, not this
    /// instance's current, possibly-overridden state (see
    /// `PlatformFontDefaults`'s doc). Cross-platform: `set_editor_font`/
    /// `set_ui_font` are real, stateful implementations here (unlike
    /// TUI's no-ops), so this is worth checking even off `target_os =
    /// "windows"`, same rationale as
    /// `win_backend_default_fonts_reports_platform_convention` above.
    #[test]
    fn win_backend_default_fonts_is_unaffected_by_set_editor_font_and_set_ui_font() {
        let mut backend = WinBackend::new();
        Backend::set_editor_font(&mut backend, "Fira Code", 40.0);
        Backend::set_ui_font(&mut backend, "Cantarell 30");
        let defaults = Backend::default_fonts(&backend);
        assert_eq!(defaults.editor_family, "Consolas");
        assert_eq!(defaults.editor_size_pt, 14.0);
        assert_eq!(defaults.ui_family, "Segoe UI");
        assert_eq!(defaults.ui_size_pt, 13.0);
    }

    /// A host-set `TreeStyle::row_height` must be honored
    /// by `tree_vscrollbar`, exactly as `tree_layout`/`draw_tree` honor
    /// it — not silently ignored in favor of `line_height`. It governs the
    /// minimum thumb length, not the track's (fixed 10px) width.
    #[test]
    fn win_backend_tree_vscrollbar_honors_tree_style_row_height_override() {
        let backend = WinBackend::new();
        let mut tree = flat_tree(15);
        tree.style.row_height = Some(50);
        let rect = Rect::new(0.0, 0.0, 20.0, 300.0);

        let sb = Backend::tree_vscrollbar(&backend, rect, &tree)
            .expect("15 rows at a 50px override overflow a 300px viewport (6 visible)");
        assert_eq!(
            sb.track.width,
            crate::primitives::layout_metrics::pixel::TREE_VSCROLLBAR_WIDTH
        );
        assert!(sb.thumb_len >= 50.0);
    }

    /// `parse_ui_font_desc` splits a Pango-style comma-separated fallback list
    /// and takes the first candidate — generic or concrete — instead of treating
    /// the whole list as one unmatchable literal family name.
    #[cfg(target_os = "windows")]
    #[test]
    fn parse_ui_font_desc_splits_a_comma_separated_fallback_list() {
        assert_eq!(
            parse_ui_font_desc("Segoe UI, Tahoma, Sans 12"),
            ("Segoe UI".to_string(), 12.0)
        );
        // No trailing size at all — the real-world shape this issue was
        // filed over (vimcode's `UI_FONT_FAMILY` constants carry no
        // size, only a comma-separated family list).
        assert_eq!(
            parse_ui_font_desc("Segoe UI, Tahoma, Sans"),
            ("Segoe UI".to_string(), DEFAULT_UI_FONT_SIZE_PT)
        );
    }

    /// A CSS/Pango generic token resolves to its DirectWrite default
    /// (`DEFAULT_EDITOR_FONT_FAMILY`/`DEFAULT_UI_FONT_FAMILY`) rather than being
    /// treated as a literal, unmatchable family name — including when it's the
    /// first entry of a comma-separated list.
    #[cfg(target_os = "windows")]
    #[test]
    fn parse_ui_font_desc_resolves_generic_tokens() {
        assert_eq!(
            parse_ui_font_desc("monospace 13"),
            (DEFAULT_EDITOR_FONT_FAMILY.to_string(), 13.0)
        );
        assert_eq!(
            parse_ui_font_desc("sans-serif 13"),
            (DEFAULT_UI_FONT_FAMILY.to_string(), 13.0)
        );
        assert_eq!(
            parse_ui_font_desc("system-ui 13"),
            (DEFAULT_UI_FONT_FAMILY.to_string(), 13.0)
        );
        // Pango's own alias spellings resolve the same way.
        assert_eq!(
            parse_ui_font_desc("Monospace, Sans 13"),
            (DEFAULT_EDITOR_FONT_FAMILY.to_string(), 13.0)
        );
    }

    /// `set_editor_font("monospace", …)` resolves through the same
    /// `GenericFamily` path as `parse_ui_font_desc` —
    /// `editor_font_family` must land on `DEFAULT_EDITOR_FONT_FAMILY`,
    /// not the literal string `"monospace"`.
    #[cfg(target_os = "windows")]
    #[test]
    fn set_editor_font_resolves_the_monospace_generic_token() {
        let mut b = WinBackend::new();
        Backend::set_editor_font(&mut b, "monospace", 14.0);
        assert_eq!(b.editor_font_family, DEFAULT_EDITOR_FONT_FAMILY);
        assert_eq!(b.editor_font_size_pt, 14.0);
    }

    /// `WinBackend::modal_stack_handle` must hand back a
    /// handle that shares state with the backend's own modal stack —
    /// same guarantee already proved for `GtkBackend`
    /// (`gtk::backend::tests::gtk_backend_modal_stack_handle_shares_state`),
    /// `TuiBackend`
    /// (`tui::backend::tests::tui_backend_modal_stack_handle_shares_state`),
    /// and `MacBackend`
    /// (`macos::backend::tests::mac_backend_modal_stack_handle_shares_state`).
    /// Pure-Rust `Rc<RefCell<>>` plumbing, so this runs on every host —
    /// no `target_os = "windows"` gate needed, unlike most of this file.
    #[test]
    fn win_backend_modal_stack_handle_shares_state() {
        let backend = WinBackend::new();
        let h1 = backend.modal_stack_handle();
        let h2 = backend.modal_stack_handle();
        h1.borrow_mut()
            .push(WidgetId::new("test:popup"), Rect::new(0.0, 0.0, 10.0, 5.0));
        assert_eq!(h2.borrow().len(), 1);
    }

    /// `is_maximized`/`set_decorated` guard on the (target-gated)
    /// `hwnd` field the same way every other `WindowControl` method here
    /// does. `WinBackend::new()` never sets `hwnd`, on Windows or off, so
    /// both must report `Unsupported` rather than panic — no
    /// `target_os = "windows"` gate needed, same reasoning as
    /// `win_backend_modal_stack_handle_shares_state` above.
    #[test]
    fn win_backend_is_maximized_err_without_window() {
        let b = WinBackend::new();
        assert!(matches!(
            WindowControl::is_maximized(&b),
            Err(BackendError::Unsupported)
        ));
    }

    #[test]
    fn win_backend_set_decorated_err_without_window() {
        let mut b = WinBackend::new();
        assert!(matches!(
            WindowControl::set_decorated(&mut b, false),
            Err(BackendError::Unsupported)
        ));
    }

    /// Pins the Windows column of the shared `hscrollbar_track` fix
    /// as the reference behaviour macOS's copy had silently dropped —
    /// `list_hscrollbar` insets the track by one char width on each side
    /// (and moves it up one row) for a `bordered` list, so the thumb sits
    /// inside the border rather than overpainting it. Pure geometry, no
    /// `target_os = "windows"` gate needed.
    #[test]
    fn win_backend_list_hscrollbar_insets_track_for_bordered_list() {
        let mut b = WinBackend::new();
        b.set_current_char_width(8.0);
        b.set_current_line_height(16.0);
        let rect = Rect::new(0.0, 0.0, 200.0, 100.0);
        let list = |bordered: bool| -> ListView {
            ListView {
                id: WidgetId::new("l"),
                title: None,
                items: vec![crate::ListItem {
                    text: crate::types::StyledText::plain(&"x".repeat(40)),
                    detail: None,
                    icon: None,
                    decoration: crate::types::Decoration::default(),
                }],
                selected_idx: 0,
                scroll_offset: 0,
                has_focus: true,
                bordered,
                h_scroll: 0,
                max_content_width: Some(40),
                show_v_scrollbar: false,
            }
        };

        let flat_sb = b
            .list_hscrollbar(rect, &list(false))
            .expect("overflowing content should yield a scrollbar");
        assert_eq!(flat_sb.track.x, 0.0);
        assert_eq!(flat_sb.track.width, 200.0);

        let bordered_sb = b
            .list_hscrollbar(rect, &list(true))
            .expect("overflowing content should yield a scrollbar");
        assert_eq!(bordered_sb.track.x, 8.0);
        assert_eq!(bordered_sb.track.width, 184.0);
        assert_eq!(bordered_sb.track.y, 100.0 - 2.0 * 16.0);
        assert!(bordered_sb.track.x >= rect.x + 8.0);
        assert!(bordered_sb.track.x + bordered_sb.track.width <= rect.x + rect.width - 8.0);
    }

    /// The stash-then-reuse pattern this issue exists to
    /// unblock — obtain the handle through `&mut dyn Backend`, drop
    /// that borrow, and use the handle afterwards from an unrelated
    /// borrow scope.
    #[test]
    fn modal_stack_handle_outlives_the_backend_borrow_through_the_trait() {
        let mut backend = WinBackend::new();
        let stack_rc = {
            let dyn_backend: &mut dyn Backend = &mut backend;
            dyn_backend.modal_stack_handle()
        };
        stack_rc
            .borrow_mut()
            .push(WidgetId::new("test:popup"), Rect::new(0.0, 0.0, 10.0, 5.0));
        assert_eq!(backend.modal_stack_handle().borrow().len(), 1);
    }

    /// Same shared-state guarantee as
    /// `win_backend_modal_stack_handle_shares_state`, for
    /// `drag_state_handle`.
    #[test]
    fn win_backend_drag_state_handle_shares_state() {
        let backend = WinBackend::new();
        let h1 = backend.drag_state_handle();
        let h2 = backend.drag_state_handle();
        h1.borrow_mut()
            .begin(crate::dispatch::DragTarget::TextSelection {
                region: WidgetId::new("r"),
                anchor: crate::event::Point::new(0.0, 0.0),
            });
        assert!(h2.borrow().is_active());
    }

    // ── Accelerator matching + ActivityBar keyboard focus ──────────────
    //
    // Pure `HashMap`/`Vec`/`Option<WidgetId>` logic, no Direct2D — runs
    // on every host, same as the handle-sharing tests above. Mirrors
    // `macos::backend::tests`' `match_keypress_*` suite (Ctrl instead of
    // Cmd, since Win-GUI has no macOS-style universal-binding modifier
    // translation).

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

    /// The registry itself now lives in `BackendCore` — its
    /// `contains_key`/`len()` aren't reachable from here anymore, so this
    /// observes the same round trip behaviourally via `match_keypress`.
    #[test]
    fn register_and_unregister_accelerator_round_trip() {
        let mut b = WinBackend::new();
        let a = acc("save", "<C-s>");
        b.register_accelerator(&a);
        let ctrl_s = Modifiers {
            ctrl: true,
            ..Default::default()
        };
        assert_eq!(
            b.match_keypress(&Key::Char('s'), ctrl_s),
            Some(AcceleratorId::new("save"))
        );
        b.unregister_accelerator(&AcceleratorId::new("save"));
        assert_eq!(b.match_keypress(&Key::Char('s'), ctrl_s), None);
    }

    #[test]
    fn match_keypress_finds_registered_global_binding() {
        let mut b = WinBackend::new();
        b.register_accelerator(&acc("save", "<C-s>"));
        let id = b.match_keypress(
            &Key::Char('s'),
            Modifiers {
                ctrl: true,
                ..Default::default()
            },
        );
        assert_eq!(id, Some(AcceleratorId::new("save")));
    }

    #[test]
    fn match_keypress_modifier_mismatch_no_match() {
        let mut b = WinBackend::new();
        b.register_accelerator(&acc("save", "<C-s>"));
        // Same key, wrong modifiers (Alt instead of Ctrl).
        let id = b.match_keypress(
            &Key::Char('s'),
            Modifiers {
                alt: true,
                ..Default::default()
            },
        );
        assert_eq!(id, None);
    }

    #[test]
    fn match_keypress_skips_non_global_scope() {
        let mut b = WinBackend::new();
        b.register_accelerator(&Accelerator {
            id: AcceleratorId::new("find-in-tree"),
            binding: crate::KeyBinding::Literal("<C-f>".to_string()),
            scope: AcceleratorScope::Widget(WidgetId::new("tree")),
            label: None,
        });
        let id = b.match_keypress(
            &Key::Char('f'),
            Modifiers {
                ctrl: true,
                ..Default::default()
            },
        );
        assert_eq!(id, None);
    }

    #[test]
    fn match_keypress_re_register_replaces_binding() {
        let mut b = WinBackend::new();
        b.register_accelerator(&acc("save", "<C-s>"));
        b.register_accelerator(&acc("save", "<C-S-s>"));
        assert_eq!(
            b.match_keypress(
                &Key::Char('s'),
                Modifiers {
                    ctrl: true,
                    ..Default::default()
                }
            ),
            None,
            "old binding must no longer match after re-registration",
        );
        assert_eq!(
            b.match_keypress(
                &Key::Char('s'),
                Modifiers {
                    ctrl: true,
                    shift: true,
                    ..Default::default()
                }
            ),
            Some(AcceleratorId::new("save")),
        );
    }

    // ── Double-click folding ────────────────────────────────────────────
    //
    // Pure `DoubleClickDetector` logic, no Direct2D — runs on every host.
    // Mirrors `macos::backend::tests`' `fold_double_click_*` suite.

    fn win_mouse_down(x: f32, y: f32) -> UiEvent {
        UiEvent::MouseDown {
            widget: None,
            button: crate::MouseButton::Left,
            position: crate::event::Point::new(x, y),
            modifiers: Modifiers::default(),
        }
    }

    #[test]
    fn fold_double_click_second_click_same_position_becomes_double_click() {
        let mut b = WinBackend::new();
        let first = b.fold_double_click(win_mouse_down(5.0, 3.0));
        assert!(matches!(first, UiEvent::MouseDown { .. }));

        let second = b.fold_double_click(win_mouse_down(5.0, 3.0));
        assert!(
            matches!(second, UiEvent::DoubleClick { .. }),
            "second click at the same position should fold to DoubleClick"
        );
    }

    #[test]
    fn fold_double_click_different_position_stays_mouse_down() {
        let mut b = WinBackend::new();
        let _ = b.fold_double_click(win_mouse_down(5.0, 3.0));
        let second = b.fold_double_click(win_mouse_down(50.0, 30.0));
        assert!(matches!(second, UiEvent::MouseDown { .. }));
    }

    #[test]
    fn fold_double_click_passes_non_mouse_down_events_through() {
        let mut b = WinBackend::new();
        let ev = b.fold_double_click(UiEvent::WindowFocused(true));
        assert_eq!(ev, UiEvent::WindowFocused(true));
    }

    // ── Event queue adapter ──────────────────────────────────────────────
    //
    // Before this issue, `WinBackend::poll_events`/`wait_events` were
    // unconditional `todo!()` — calling either panicked immediately,
    // which is exactly what every test in this section would have hit
    // (`RED`) before the queue-adapter implementation below landed.
    // Pure `VecDeque`/`HashMap` logic, no Direct2D — runs on every host,
    // mirrors `macos::backend::tests::poll_events_drains_queue_fifo` and
    // the `docs/BACKEND.md` "option A event queue" contract `GtkBackend`
    // ships.

    #[test]
    fn poll_events_drains_queue_fifo() {
        let b = WinBackend::new();
        b.push_event(win_mouse_down(1.0, 2.0));
        b.push_event(UiEvent::WindowFocused(true));
        // `poll_events` takes `&mut self`, so re-acquire after the
        // (shared-ref) `push_event` calls above — mirrors
        // `MacBackend`'s identical test structure.
        let mut b = b;
        let evs = b.poll_events();
        assert_eq!(evs.len(), 2);
        assert!(matches!(evs[0], UiEvent::MouseDown { .. }));
        assert!(matches!(evs[1], UiEvent::WindowFocused(true)));
        // Second drain yields nothing — draining doesn't panic on an
        // empty queue either.
        assert!(b.poll_events().is_empty());
    }

    // ── Background-thread wake ──────────────────────────────────────────
    //
    // `WinBackend::waker`'s `PostMessageW` half only exists under
    // `cfg(target_os = "windows")` and needs a real `HWND`/message loop to
    // exercise for real (that's `ci.yml`'s windows-latest leg's job, via
    // `wndproc`'s `WM_QUADRAUI_USER_EVENT` arm). What's host-independent
    // and testable here is the `UserEventQueue` plumbing every platform's
    // `waker()` shares — `self.hwnd` is `None` on this host regardless
    // (never attached to a real window), which is exactly the "no live
    // window to nudge yet" branch `waker`'s doc describes.

    /// A payload pushed from a background thread through the closure
    /// `Backend::waker()` hands out lands in `poll_events()`'s output as a
    /// `UiEvent::User`, even with no `HWND` attached (`self.hwnd == None`
    /// on every host this test runs on) — the queue half of `waker()`
    /// doesn't depend on a live window at all.
    #[test]
    fn waker_payload_reaches_poll_events_as_user_event() {
        let backend = WinBackend::new();
        let waker = Backend::waker(&backend);

        let handle = std::thread::spawn(move || {
            waker(crate::UserPayload::new("from background".to_string()));
        });
        handle.join().expect("background thread must not panic");

        let mut backend = backend;
        let events = backend.poll_events();
        assert_eq!(events.len(), 1);
        match &events[0] {
            UiEvent::User(payload) => {
                assert_eq!(
                    payload.downcast_ref::<String>().map(String::as_str),
                    Some("from background")
                );
            }
            other => panic!("expected UiEvent::User, got {other:?}"),
        }
    }

    /// `request_frame_in` before any window is attached
    /// (`self.hwnd == None` on every host this test runs on, including a
    /// real Windows one that just hasn't called `attach_surface` yet)
    /// must be a safe no-op, not a panic — mirrors `waker`'s "no wake
    /// target yet" posture. There is nothing further to assert on a
    /// non-Windows host: no `SetTimer` call is reachable at all here (see
    /// `Backend::request_frame_in`'s doc for the real one-shot-timer
    /// behavior, exercised for real only on `windows-latest`).
    #[test]
    fn request_frame_in_before_a_window_is_attached_does_not_panic() {
        let backend = WinBackend::new();
        Backend::request_frame_in(&backend, Duration::from_millis(50));
    }

    /// `frame_requests`/`pending_frame_delay` must observe
    /// every `request_frame_in` call even with no `HWND` attached — the
    /// whole point of this bookkeeping existing alongside the real
    /// `SetTimer` arm (which stays silently no-op in this exact state,
    /// per the test above). Mirrors `TuiBackend`'s identically-shaped
    /// `frame_requests`/`pending_frame_delay` unit coverage.
    #[test]
    fn frame_requests_and_pending_delay_observe_calls_with_no_hwnd() {
        let backend = WinBackend::new();
        assert_eq!(backend.frame_requests(), 0);
        assert!(backend.pending_frame_delay().is_none());

        Backend::request_frame_in(&backend, Duration::from_millis(50));
        assert_eq!(backend.frame_requests(), 1);
        assert!(backend.pending_frame_delay().is_some());

        // A second call at the same interval coalesces to the earlier
        // deadline but still increments the call count — the
        // chained-re-arm behaviour `TuiBackend`'s own test documents.
        Backend::request_frame_in(&backend, Duration::from_millis(50));
        assert_eq!(backend.frame_requests(), 2);
    }

    /// A closure obtained before `attach_surface` ever runs must notice a
    /// window attaching later. `attach_surface` itself needs a real `HWND`/D2D
    /// device and can't run on this host, so this test drives `hwnd_raw` (the
    /// live mirror `attach_surface` writes into) and `live_hwnd` (the read
    /// `waker`'s closure performs on every call) directly — the same two pieces
    /// of state the closure actually touches, without needing `PostMessageW` to
    /// succeed against a real window. Windows-only: `hwnd_raw`/`live_hwnd` don't
    /// exist on other hosts (see `hwnd_raw`'s field doc).
    #[cfg(target_os = "windows")]
    #[test]
    fn waker_resolves_hwnd_set_after_the_waker_was_obtained() {
        let backend = WinBackend::new();

        // Simulates: `waker()` called during `AppLogic::setup`, before
        // `attach_surface` has ever run.
        assert!(
            live_hwnd(&backend.hwnd_raw).is_none(),
            "no window attached yet"
        );

        // Simulates: `win::run::run_inner` later calls `attach_surface`,
        // which stores the real `HWND` into the same `Arc` the closure
        // holds — not into a value the closure already snapshotted.
        let fake_hwnd_value: isize = 0xDEAD_BEEFusize as isize;
        backend
            .hwnd_raw
            .store(fake_hwnd_value, std::sync::atomic::Ordering::Release);

        // The live read now sees the attached window — proving a waker
        // instance obtained pre-attach isn't permanently stuck on `None`.
        let resolved = live_hwnd(&backend.hwnd_raw).expect("window is now attached");
        assert_eq!(resolved.0 as isize, fake_hwnd_value);
    }

    #[test]
    fn poll_events_does_not_panic_on_empty_queue() {
        // `poll_events` must not panic with nothing queued.
        let mut b = WinBackend::new();
        assert!(b.poll_events().is_empty());
    }

    #[test]
    fn wait_events_does_not_panic_and_drains_like_poll_events() {
        // `wait_events` must not panic with nothing queued. No true blocking
        // primitive is wired up (see `Backend::wait_events`'s doc on `WinBackend`),
        // so a queued event is still returned immediately rather than lost.
        let mut b = WinBackend::new();
        assert!(b.wait_events(Duration::from_millis(50)).is_empty());

        b.push_event(win_mouse_down(1.0, 2.0));
        let evs = b.wait_events(Duration::from_millis(50));
        assert_eq!(evs.len(), 1);
        assert!(matches!(evs[0], UiEvent::MouseDown { .. }));
    }

    #[test]
    fn poll_events_and_wait_events_agree_for_the_same_sequence() {
        // Acceptance bar: the queue-adapter behaviour must match
        // `GtkBackend`'s for the same event sequence. `GtkBackend::
        // poll_events`/`wait_events` are both a plain drain + the same
        // `apply_accelerators` pass over the batch (see
        // `gtk::backend::GtkBackend::{poll_events,wait_events}`); this
        // pins `WinBackend` doing byte-for-byte the same thing for a
        // fixed input rather than the two diverging (e.g. one applying
        // accelerators and the other not).
        let seq = |mut b: WinBackend| -> WinBackend {
            b.register_accelerator(&acc("save", "<C-s>"));
            b.push_event(UiEvent::KeyPressed {
                key: Key::Char('s'),
                modifiers: Modifiers {
                    ctrl: true,
                    ..Default::default()
                },
                repeat: false,
            });
            b.push_event(win_mouse_down(1.0, 2.0));
            b
        };

        let mut by_poll = seq(WinBackend::new());
        let via_poll = by_poll.poll_events();

        let mut by_wait = seq(WinBackend::new());
        let via_wait = by_wait.wait_events(Duration::from_millis(0));

        assert_eq!(via_poll, via_wait);
        assert_eq!(
            via_poll[0],
            UiEvent::Accelerator(
                AcceleratorId::new("save"),
                Modifiers {
                    ctrl: true,
                    ..Default::default()
                }
            ),
            "registered KeyPressed must rewrite to Accelerator, matching \
             GtkBackend::apply_accelerators",
        );
        assert!(matches!(via_poll[1], UiEvent::MouseDown { .. }));
    }

    #[test]
    fn focused_activity_bar_id_starts_none() {
        let b = WinBackend::new();
        assert!(b.focused_activity_bar_id().is_none());
    }

    #[test]
    fn draw_activity_bar_tracks_keyboard_focus() {
        let mut b = WinBackend::new();
        let bar = ActivityBar {
            id: WidgetId::new("demo:bar"),
            top_items: Vec::new(),
            bottom_items: Vec::new(),
            active_accent: None,
            selection_bg: None,
            is_keyboard_focused: true,
        };
        // No surface attached — every real Direct2D call in
        // `draw_activity_bar` is behind `#[cfg(target_os = "windows")]`
        // and this test isn't, so on a non-Windows host it falls to the
        // `todo!()` stub *after* the focus-tracking below has already
        // run (see that method's doc). Catch the panic so this test
        // proves the tracking half of the contract everywhere, while
        // `win::testing`'s headless-surface driver tests prove the paint
        // half for real on Windows.
        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            b.draw_activity_bar(Rect::new(0.0, 0.0, 40.0, 200.0), &bar, None);
        }));
        assert_eq!(
            b.focused_activity_bar_id(),
            Some(&WidgetId::new("demo:bar"))
        );
    }

    #[test]
    fn begin_frame_clears_focused_activity_bar() {
        let mut b = WinBackend::new();
        b.focused_activity_bar = Some(WidgetId::new("demo:bar"));
        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            b.begin_frame(Viewport::new(80.0, 24.0, 1.0));
        }));
        assert!(
            b.focused_activity_bar_id().is_none(),
            "focused_activity_bar must be cleared by begin_frame"
        );
    }

    // ─── #1199: window_chrome ───────────────────────────────────────────

    /// `CAP_CONTRACTS`'s `window_chrome` entry is `Proof::Any` — this is
    /// the one method that makes `backend_caps().window_chrome: true`
    /// honest (see that struct literal's doc). No window on any test
    /// host (real Windows CI included — this unit test never calls
    /// `attach_surface`), so this stays `false` the same way
    /// `MacBackend::toggle_window_maximize_false_without_window` does.
    #[test]
    fn toggle_window_maximize_false_without_window() {
        let mut b = WinBackend::new();
        assert!(!Backend::toggle_window_maximize(&mut b));
    }

    #[test]
    fn backend_caps_declares_window_chrome() {
        let b = WinBackend::new();
        #[cfg(target_os = "windows")]
        assert!(
            b.backend_caps().window_chrome,
            "issue #1199: WinBackend must declare window_chrome now that \
             toggle_window_maximize is overridden and win::run handles \
             WM_NCCALCSIZE/WM_NCHITTEST"
        );
        #[cfg(not(target_os = "windows"))]
        assert!(
            !b.backend_caps().window_chrome,
            "off-Windows backend_caps() is BackendCaps::empty() — see that method's doc"
        );
    }

    /// A native `HMENU` sits in the non-client area, which `window_chrome`'s
    /// custom caption permanently covers, so the native menu bar is unreachable —
    /// this asserts `native_menu: false` and `window_chrome: true`. The
    /// `tests/conformance/caps.rs` generic check
    /// `backends_declare_only_what_they_override` ties override existence to
    /// `native_menu: false` (no `install_menu_bar`/`show_context_menu` override
    /// may exist); this test pins the declared values themselves.
    #[test]
    fn backend_caps_declares_no_native_menu_but_keeps_window_chrome() {
        let b = WinBackend::new();
        #[cfg(target_os = "windows")]
        {
            assert!(
                !b.backend_caps().native_menu,
                "issue #1228: a native HMENU sits in the non-client area that the drawn \
                 caption (#1199) permanently covers, so Win-GUI must not claim native_menu \
                 — install_menu_bar is the trait's no-op default now, matching GtkBackend/\
                 TuiBackend"
            );
            assert!(
                b.backend_caps().window_chrome,
                "issue #1228 keeps the drawn caption from #1199 — only the native menu bar \
                 half of #1200 was reverted"
            );
        }
        #[cfg(not(target_os = "windows"))]
        assert!(
            !b.backend_caps().native_menu && !b.backend_caps().window_chrome,
            "off-Windows backend_caps() is BackendCaps::empty() — see that method's doc"
        );
    }

    /// `GetMenu(hwnd)` must be null on a real window — a caller that invokes
    /// `Backend::install_menu_bar` unaware `native_menu` went false must still
    /// get a no-op, matching the behaviour of other backends without a native
    /// menu bar. `WM_NCHITTEST`'s "drawn close button → `HTCLIENT`, empty band →
    /// `HTCAPTION`" behaviour is covered separately by
    /// [`nc_hit_test_client_on_an_inline_button`] / [`nc_hit_test_caption_in_the_empty_band`].
    /// Real hardware isn't needed to prove pure geometry, only to prove `GetMenu`.
    #[cfg(target_os = "windows")]
    #[test]
    fn install_menu_bar_never_attaches_a_native_menu_to_a_live_window() {
        use windows::core::PCWSTR;
        use windows::Win32::Foundation::HINSTANCE;
        use windows::Win32::System::LibraryLoader::GetModuleHandleW;
        use windows::Win32::UI::WindowsAndMessaging::{
            CreateWindowExW, DefWindowProcW, DestroyWindow, GetMenu, RegisterClassExW,
            CW_USEDEFAULT, WINDOW_EX_STYLE, WNDCLASSEXW,
        };

        unsafe extern "system" fn test_wndproc(
            hwnd: HWND,
            msg: u32,
            wparam: WPARAM,
            lparam: LPARAM,
        ) -> windows::Win32::Foundation::LRESULT {
            // SAFETY: `hwnd`/`msg`/`wparam`/`lparam` are this call's own
            // parameters, forwarded unchanged — same as every
            // `DefWindowProcW` stand-in elsewhere in this module's tests.
            unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }
        }

        // SAFETY: `GetModuleHandleW(PCWSTR::null())` is the documented
        // idiom for "this process's own module handle" — same as
        // `win::run::run_inner`'s identical call.
        let hinstance: HINSTANCE = unsafe { GetModuleHandleW(PCWSTR::null()) }
            .expect("GetModuleHandleW(None) always succeeds for the current process")
            .into();
        let class_name = win_wide_nul_terminated("quadraui_test_1228_no_native_menu_wndclass");
        let wc = WNDCLASSEXW {
            cbSize: std::mem::size_of::<WNDCLASSEXW>() as u32,
            lpfnWndProc: Some(test_wndproc),
            hInstance: hinstance,
            lpszClassName: PCWSTR::from_raw(class_name.as_ptr()),
            ..Default::default()
        };
        // Ignore the return value: a second test in this same process
        // re-registering the same class name fails
        // (`ERROR_CLASS_ALREADY_EXISTS`), which is harmless here — only
        // the handle `CreateWindowExW` resolves by name matters, not
        // which call minted the class.
        //
        // SAFETY: `wc` is a fully-initialized `WNDCLASSEXW` on the stack,
        // still in scope; `RegisterClassExW` reads it synchronously and
        // does not retain the pointer. `class_name.as_ptr()` (via
        // `lpszClassName`) stays valid because `class_name` outlives this
        // call.
        unsafe {
            let _ = RegisterClassExW(&wc);
        }

        // SAFETY: `class_name` is a `Vec<u16>` that outlives this call, so
        // `class_name.as_ptr()` stays valid; `hinstance` came from the
        // successful `GetModuleHandleW` above; `lpCreateParams: None`
        // means this test window never populates `GWLP_USERDATA`, which
        // is fine since `test_wndproc` above never reads it.
        let hwnd = unsafe {
            CreateWindowExW(
                WINDOW_EX_STYLE::default(),
                PCWSTR::from_raw(class_name.as_ptr()),
                PCWSTR::null(),
                WS_OVERLAPPEDWINDOW,
                CW_USEDEFAULT,
                CW_USEDEFAULT,
                CW_USEDEFAULT,
                CW_USEDEFAULT,
                None,
                None,
                Some(hinstance),
                None,
            )
        }
        .expect(
            "CreateWindowExW for an unshown top-level test window must succeed on real \
             Windows hardware",
        );

        let mut backend = WinBackend::new();
        backend.hwnd = Some(hwnd);

        // SAFETY: `hwnd` is this test's own live window from
        // `CreateWindowExW` above — reading its current menu handle has
        // no precondition beyond that.
        let menu_before = unsafe { GetMenu(hwnd) };
        assert!(
            menu_before.is_invalid(),
            "a freshly created window must start with no menu at all"
        );

        // A caller that invokes `Backend::install_menu_bar` — matching a caller
        // that hasn't noticed `native_menu` went false, or a cross-backend app
        // that calls this unconditionally on every backend — must get the same
        // no-op every other backend without a native menu bar gives it.
        {
            use crate::primitives::menu_bar::MenuBarItem;
            Backend::install_menu_bar(
                &mut backend,
                &MenuBar {
                    id: WidgetId::new("menubar"),
                    items: vec![MenuBarItem {
                        id: WidgetId::new("file"),
                        label: "&File".to_string(),
                        disabled: false,
                        submenu: None,
                    }],
                    open_item: None,
                    focused_item: None,
                },
            );
        }

        // SAFETY: same as above — `hwnd` is still this test's own live
        // window.
        let menu_after = unsafe { GetMenu(hwnd) };
        assert!(
            menu_after.is_invalid(),
            "issue #1228: install_menu_bar is the trait's no-op default on Win-GUI now — \
             GetMenu(hwnd) must stay null even after a caller invokes it"
        );

        // SAFETY: `hwnd` is this test's own still-live window from
        // `CreateWindowExW` above; `test_wndproc` (unlike the real
        // `win::run::wndproc`) never reads `GWLP_USERDATA`, so there is
        // no boxed state that must outlive this call the way
        // `run_inner`'s shutdown path requires.
        unsafe {
            let _ = DestroyWindow(hwnd);
        }
    }

    /// `register_zone` must record the zone into the backend's state.
    #[test]
    fn register_zone_records_the_zone() {
        let mut b = WinBackend::new();
        Backend::register_zone(
            &mut b,
            WidgetId::new("demo:zone"),
            Rect::new(1.0, 2.0, 3.0, 4.0),
        );
        assert_eq!(b.zones.len(), 1);
        assert_eq!(b.zones[0].id, WidgetId::new("demo:zone"));
        assert_eq!(b.zones[0].bounds, Rect::new(1.0, 2.0, 3.0, 4.0));
    }

    /// `begin_frame` must clear last frame's zones the same way it clears
    /// `focused_activity_bar` above — a zone a widget stops painting must
    /// stop resolving `nc_hit_test` too.
    #[test]
    fn begin_frame_clears_zones() {
        let mut b = WinBackend::new();
        Backend::register_zone(
            &mut b,
            WidgetId::new("demo:zone"),
            Rect::new(0.0, 0.0, 1.0, 1.0),
        );
        assert_eq!(b.zones.len(), 1);
        let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            b.begin_frame(Viewport::new(80.0, 24.0, 1.0));
        }));
        assert!(
            b.zones.is_empty(),
            "begin_frame must clear last frame's zones"
        );
    }

    /// No `TITLE_BAR_DRAG_ZONE` registered this frame — every point
    /// answers `None`, so `win::run`'s `WM_NCHITTEST` handler leaves
    /// `DefWindowProcW`'s own answer alone.
    #[test]
    fn nc_hit_test_none_with_no_band_registered() {
        let b = WinBackend::new();
        assert_eq!(b.nc_hit_test(10.0, 10.0), None);
    }

    /// A point outside the registered band is `None` even once a band
    /// exists — same "leave DefWindowProcW alone" contract.
    #[test]
    fn nc_hit_test_none_outside_the_band() {
        let mut b = WinBackend::new();
        Backend::register_zone(
            &mut b,
            WidgetId::new(WinBackend::TITLE_BAR_DRAG_ZONE),
            Rect::new(0.0, 0.0, 800.0, 32.0),
        );
        assert_eq!(b.nc_hit_test(10.0, 100.0), None);
    }

    /// The empty part of the drawn band reports `Some(true)` (`HTCAPTION`)
    /// — the Test section's acceptance scenario, first half.
    #[test]
    fn nc_hit_test_caption_in_the_empty_band() {
        let mut b = WinBackend::new();
        Backend::register_zone(
            &mut b,
            WidgetId::new(WinBackend::TITLE_BAR_DRAG_ZONE),
            Rect::new(0.0, 0.0, 800.0, 32.0),
        );
        assert_eq!(b.nc_hit_test(400.0, 16.0), Some(true));
    }

    /// A smaller zone registered inside the band (an inline min/max/close
    /// button, the command-centre search box) excludes its own footprint
    /// — `Some(false)` (`HTCLIENT`), so the click reaches the widget as a
    /// normal `UiEvent::MouseDown` instead of starting an OS move/maximize
    /// gesture. Second half of the Test section's acceptance scenario.
    #[test]
    fn nc_hit_test_client_on_an_inline_button() {
        let mut b = WinBackend::new();
        Backend::register_zone(
            &mut b,
            WidgetId::new(WinBackend::TITLE_BAR_DRAG_ZONE),
            Rect::new(0.0, 0.0, 800.0, 32.0),
        );
        Backend::register_zone(
            &mut b,
            WidgetId::new("titlebar:minimize-button"),
            Rect::new(700.0, 4.0, 24.0, 24.0),
        );
        // Inside the button.
        assert_eq!(b.nc_hit_test(712.0, 16.0), Some(false));
        // Outside the button but still in the band.
        assert_eq!(b.nc_hit_test(100.0, 16.0), Some(true));
    }

    /// End-to-end regression: nothing ever registered a zone for the real
    /// widgets a host paints inside the title-bar band — this test drives the
    /// real paint path: register the band, call `Backend::draw_menu_bar` with a
    /// real `MenuBar` sitting inside it, and confirm a click on the label now
    /// excludes itself from `HTCAPTION` — with no hand-registered zone of its own.
    #[test]
    fn draw_menu_bar_registers_its_own_item_zones_inside_the_band() {
        let mut b = WinBackend::new();
        let band = Rect::new(0.0, 0.0, 800.0, 32.0);
        Backend::register_zone(&mut b, WidgetId::new(WinBackend::TITLE_BAR_DRAG_ZONE), band);

        let bar = MenuBar {
            id: WidgetId::new("bar"),
            items: vec![
                crate::primitives::menu_bar::MenuBarItem {
                    id: WidgetId::new("bar:file"),
                    label: "&File".into(),
                    disabled: false,
                    submenu: None,
                },
                crate::primitives::menu_bar::MenuBarItem {
                    id: WidgetId::new("bar:edit"),
                    label: "&Edit".into(),
                    disabled: false,
                    submenu: None,
                },
            ],
            open_item: None,
            focused_item: None,
        };
        let layout = Backend::draw_menu_bar(&mut b, Rect::new(0.0, 0.0, 300.0, 32.0), &bar);
        let file_item = layout
            .visible_items
            .iter()
            .find(|v| v.id == WidgetId::new("bar:file"))
            .expect("File item must be visible at this width");
        let (cx, cy) = (
            file_item.bounds.x + file_item.bounds.width / 2.0,
            file_item.bounds.y + file_item.bounds.height / 2.0,
        );
        // On "File": the OS must not swallow this as a caption drag.
        assert_eq!(b.nc_hit_test(cx, cy), Some(false));
        // Still empty band space well past the drawn items.
        assert_eq!(b.nc_hit_test(790.0, 16.0), Some(true));
    }

    /// Same regression as above for `Backend::draw_status_bar_interactive`
    /// — vimcode's inline minimize/maximize/close buttons are ordinary
    /// `action_id` status-bar segments drawn into the band.
    #[test]
    fn draw_status_bar_interactive_registers_its_own_segment_zones_inside_the_band() {
        let mut b = WinBackend::new();
        let band = Rect::new(0.0, 0.0, 800.0, 32.0);
        Backend::register_zone(&mut b, WidgetId::new(WinBackend::TITLE_BAR_DRAG_ZONE), band);

        let bar = StatusBar {
            id: WidgetId::new("titlebar:controls"),
            left_segments: vec![],
            right_segments: vec![
                crate::primitives::status_bar::StatusBarSegment {
                    text: "_".into(),
                    fg: crate::types::Color::rgb(255, 255, 255),
                    bg: crate::types::Color::rgb(0, 0, 0),
                    bold: false,
                    action_id: Some(WidgetId::new("titlebar:minimize")),
                },
                crate::primitives::status_bar::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(WidgetId::new("titlebar:close")),
                },
            ],
        };
        let interaction = crate::interaction::InteractionState::new();
        let status_rect = Rect::new(600.0, 0.0, 200.0, 32.0);
        let layout = Backend::draw_status_bar_interactive(&mut b, status_rect, &bar, &interaction);
        let (close_rect, hit) = layout
            .hit_regions
            .iter()
            .find(|(_, hit)| {
                matches!(hit, StatusBarHit::Segment(id) if *id == WidgetId::new("titlebar:close"))
            })
            .expect("close segment must be a registered hit region");
        let _ = hit;
        // `close_rect` is bar-local (the layout's own,
        // documented contract — see `register_status_bar_segment_zones`'s
        // doc). The probe point must be derived independently of that
        // bar-local layout by adding `status_rect`'s own absolute origin
        // back in, not by reusing whatever the (potentially still buggy)
        // registered zone reports — otherwise a future regression of this
        // exact "local vs. absolute" shape could ship past this test
        // again undetected.
        let (cx, cy) = (
            status_rect.x + close_rect.x + close_rect.width / 2.0,
            status_rect.y + close_rect.y + close_rect.height / 2.0,
        );
        // On the close button's real, absolute screen position: must
        // reach the app as a normal click, not get swallowed as a
        // caption drag.
        assert_eq!(b.nc_hit_test(cx, cy), Some(false));
        assert_eq!(b.nc_hit_test(10.0, 16.0), Some(true));
    }

    /// The regression above with a non-zero `rect.x`/
    /// `rect.y` specifically targeted — the exact gap that let the bug
    /// ship past `draw_status_bar_interactive_registers_its_own_segment_
    /// zones_inside_the_band` above, whose non-zero `rect.x` alone wasn't
    /// enough because its probe point was derived from the same
    /// (buggy) bar-local layout the production code also mis-registered.
    /// This test instead asserts directly on the *registered* zone's
    /// `bounds`, bypassing `nc_hit_test` band containment entirely, so it
    /// cannot pass "for the wrong reason."
    #[test]
    fn register_status_bar_segment_zones_translates_bar_local_bounds_by_rect_origin() {
        let mut b = WinBackend::new();
        let bar = StatusBar {
            id: WidgetId::new("titlebar:controls"),
            left_segments: vec![],
            right_segments: vec![crate::primitives::status_bar::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(WidgetId::new("titlebar:close")),
            }],
        };
        let interaction = crate::interaction::InteractionState::new();
        // Non-zero x and y, matching real-world geometry (a controls bar anchored
        // near the window's right edge).
        let status_rect = Rect::new(850.0, 4.0, 150.0, 28.0);
        let layout = Backend::draw_status_bar_interactive(&mut b, status_rect, &bar, &interaction);
        let (close_rect, _) = layout
            .hit_regions
            .iter()
            .find(|(_, hit)| {
                matches!(hit, StatusBarHit::Segment(id) if *id == WidgetId::new("titlebar:close"))
            })
            .expect("close segment must be a registered hit region");

        let registered = b
            .zones
            .iter()
            .find(|z| z.id == WidgetId::new("titlebar:close"))
            .expect("close segment zone must be registered")
            .bounds;

        // The registered zone's bounds must be `status_rect`'s absolute
        // origin plus the layout's bar-local bounds — not the bar-local
        // bounds verbatim (the pre-fix behaviour, which left the zone
        // overlapping whatever was painted at the left edge of the band
        // instead of the button's real position near the right edge).
        assert_eq!(registered.x, status_rect.x + close_rect.x);
        assert_eq!(registered.y, status_rect.y + close_rect.y);
        assert_eq!(registered.width, close_rect.width);
        assert_eq!(registered.height, close_rect.height);
        assert!(
            registered.x > 0.0,
            "regression guard: bar-local bounds alone would be well under \
             status_rect.x's 850.0, not reflecting the real absolute position"
        );
    }

    /// Same regression for `Backend::draw_command_center` — the
    /// command-centre search box the issue names explicitly.
    #[test]
    fn draw_command_center_registers_its_own_zones_inside_the_band() {
        let mut b = WinBackend::new();
        let band = Rect::new(0.0, 0.0, 800.0, 32.0);
        Backend::register_zone(&mut b, WidgetId::new(WinBackend::TITLE_BAR_DRAG_ZONE), band);

        let cc = CommandCenter {
            id: WidgetId::new("titlebar:cc"),
            back_enabled: true,
            forward_enabled: true,
            search_label: "project-name".into(),
        };
        let layout = Backend::draw_command_center(&mut b, Rect::new(300.0, 0.0, 400.0, 32.0), &cc);
        let search = layout.search_bounds.expect("search box must be laid out");
        let (cx, cy) = (
            search.x + search.width / 2.0,
            search.y + search.height / 2.0,
        );
        // On the search box: must reach the app as a normal click.
        assert_eq!(b.nc_hit_test(cx, cy), Some(false));
        assert_eq!(b.nc_hit_test(1.0, 16.0), Some(true));
    }

    /// When the Command Center's container is wider than its centred content,
    /// the left/right padding inside the container — but still inside the drag
    /// band — must read `Some(true)` (`HTCAPTION`), not get swallowed by an
    /// over-eager exclusion. The blank strip the Command Center's padding should
    /// leave `HTCAPTION` must stay that way. The probes inside the search box
    /// alone can't catch a content block that over-fills its container or a
    /// container with unclaimed room — this test probes the gap between the
    /// container's left edge and the centred content instead.
    #[test]
    fn draw_command_center_leaves_its_own_container_padding_as_caption() {
        let mut b = WinBackend::new();
        let band = Rect::new(0.0, 0.0, 900.0, 32.0);
        Backend::register_zone(&mut b, WidgetId::new(WinBackend::TITLE_BAR_DRAG_ZONE), band);

        // A short label floors at `CommandCenterMeasure`'s 280px minimum
        // search-box width, so the centred content (2 arrows + 2 gaps +
        // the 280px floor) is well short of the 400px-wide container
        // below — leaving real padding on both sides to probe.
        let cc = CommandCenter {
            id: WidgetId::new("titlebar:cc"),
            back_enabled: true,
            forward_enabled: true,
            search_label: "x".into(),
        };
        let container = Rect::new(300.0, 0.0, 400.0, 32.0);
        let layout = Backend::draw_command_center(&mut b, container, &cc);

        let back = layout.back_bounds.expect("back arrow must be laid out");
        assert!(
            back.x > container.x,
            "fixture must actually leave left padding to probe (back.x={}, container.x={})",
            back.x,
            container.x
        );

        // In the container, left of the back arrow, still inside the
        // drag band: must read as a draggable caption point, not get
        // excluded by a zone that over-claims the container's own
        // padding.
        let pad_x = (container.x + back.x) / 2.0;
        assert_eq!(b.nc_hit_test(pad_x, 16.0), Some(true));
    }

    /// A coarser zone that contains the whole band (e.g. `AppShell`'s own
    /// `"app-shell:window"` whole-window zone) must **not** be treated as
    /// an exclusion — otherwise every point in the band would read as
    /// "covered by another zone" and this would always answer
    /// `Some(false)`, the exact double-titlebar bug this issue exists to
    /// fix. Only zones strictly *smaller* than the band count.
    #[test]
    fn nc_hit_test_ignores_zones_at_least_as_large_as_the_band() {
        let mut b = WinBackend::new();
        Backend::register_zone(
            &mut b,
            WidgetId::new("app-shell:window"),
            Rect::new(0.0, 0.0, 800.0, 600.0),
        );
        Backend::register_zone(
            &mut b,
            WidgetId::new(WinBackend::TITLE_BAR_DRAG_ZONE),
            Rect::new(0.0, 0.0, 800.0, 32.0),
        );
        assert_eq!(b.nc_hit_test(400.0, 16.0), Some(true));
    }

    /// `PointerShape` -> Win32 `IDC_*` cursor-resource mapping
    /// covers every variant, mirroring
    /// `gtk::backend::tests::pointer_shape_cursor_name_maps_every_variant`.
    /// Windows-only: unlike GTK's CSS-keyword table, the mapping function
    /// itself uses real `windows`-crate types (`PCWSTR`), so this only
    /// compiles (and only runs) once `target_os = "windows"` also
    /// compiles the rest of this file's real WinAPI calls — see the
    /// module docs' "on Linux every real WinAPI call compiles to its
    /// `todo!()` fallback body" note; the `x86_64-pc-windows-msvc`
    /// cross-target `cargo check`/`clippy` runs in this repo's own dev
    /// loop (not `ci.yml`, which only runs the real Windows job) type-
    /// check it without executing it.
    #[cfg(target_os = "windows")]
    #[test]
    fn pointer_shape_to_win32_cursor_maps_every_variant() {
        // Uses the shared `desktop::all_pointer_shapes()` scaffold instead of
        // hand-listing all 9 `Default` + `Resize(edge)` combinations.
        let expected = [
            IDC_ARROW,
            IDC_SIZENS,   // North
            IDC_SIZENS,   // South
            IDC_SIZEWE,   // East
            IDC_SIZEWE,   // West
            IDC_SIZENESW, // NorthEast
            IDC_SIZENWSE, // NorthWest
            IDC_SIZENWSE, // SouthEast
            IDC_SIZENESW, // SouthWest
        ];
        for (shape, expected) in crate::desktop::all_pointer_shapes()
            .iter()
            .zip(expected.iter())
        {
            assert_eq!(pointer_shape_to_win32_cursor(*shape), *expected);
        }
    }

    /// `Backend::set_theme` must reach the rasterisers, not just be stored and
    /// ignored — a real `HeadlessSurface` pixel probe. Tests
    /// [`super::terminal::draw_terminal_divider`]'s painted pixel: a single flat
    /// `theme.separator` fill with no blending, so a non-default theme's colour
    /// must come through pixel-exact if `set_theme` is wired at all.
    #[cfg(target_os = "windows")]
    #[test]
    fn set_theme_reaches_the_rasterisers() {
        use crate::theme::Theme;
        use crate::types::Color;
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 32;
        const H: u32 = 32;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let custom_separator = Color::rgb(0x12, 0x34, 0x56);
        assert_ne!(
            custom_separator,
            Theme::default().separator,
            "test fixture bug: the probe colour must differ from the default theme's, or a \
             hardcoded `Theme::default()` would pass this test too"
        );
        backend.set_theme(Theme {
            separator: custom_separator,
            ..Theme::default()
        });

        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        // 1 DIP wide at x=0, spanning the full probe height — see
        // `crate::terminal_style::divider_geometry`.
        backend.draw_terminal_divider(Rect::new(0.0, 0.0, 1.0, H as f32));
        backend.end_frame();

        let px = surface.pixel_at(0, H / 2);
        assert_eq!(
            (px.r, px.g, px.b),
            (custom_separator.r, custom_separator.g, custom_separator.b),
            "painted pixel must reflect the theme set via `set_theme`, not `Theme::default()`",
        );
    }

    /// `activity_bar`/`menu_bar`/`context_menu`/`completions`/`find_replace` must
    /// read `WinBackend::current_theme`, not each build their own
    /// `Theme::default()` — a dark-themed app must get a dark activity bar,
    /// menu bar, context menu, completions popup and find/replace panel. Tests
    /// with a theme colour that differs from the default, and demands the
    /// non-default colour show up pixel-exact, the same shape
    /// [`set_theme_reaches_the_rasterisers`] established.
    #[cfg(target_os = "windows")]
    #[test]
    fn set_theme_reaches_the_activity_bar() {
        use crate::theme::Theme;
        use crate::types::Color;
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 40;
        const H: u32 = 40;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let custom_bg = Color::rgb(0x11, 0x22, 0x33);
        assert_ne!(
            custom_bg,
            Theme::default().tab_bar_bg,
            "test fixture bug: the probe colour must differ from the default theme's"
        );
        backend.set_theme(Theme {
            tab_bar_bg: custom_bg,
            ..Theme::default()
        });

        let bar = ActivityBar {
            id: WidgetId::new("bar"),
            top_items: Vec::new(),
            bottom_items: Vec::new(),
            active_accent: None,
            selection_bg: None,
            is_keyboard_focused: false,
        };

        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.draw_activity_bar(Rect::new(0.0, 0.0, W as f32, H as f32), &bar, None);
        backend.end_frame();

        let px = surface.pixel_at(W / 2, H / 2);
        assert_eq!(
            (px.r, px.g, px.b),
            (custom_bg.r, custom_bg.g, custom_bg.b),
            "activity bar background must reflect the live theme, not `Theme::default()`",
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn set_theme_reaches_the_menu_bar() {
        use crate::theme::Theme;
        use crate::types::Color;
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 100;
        const H: u32 = 24;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let custom_bg = Color::rgb(0x44, 0x55, 0x66);
        assert_ne!(
            custom_bg,
            Theme::default().tab_bar_bg,
            "test fixture bug: the probe colour must differ from the default theme's"
        );
        backend.set_theme(Theme {
            tab_bar_bg: custom_bg,
            ..Theme::default()
        });

        let bar = MenuBar {
            id: WidgetId::new("bar"),
            items: Vec::new(),
            open_item: None,
            focused_item: None,
        };

        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.draw_menu_bar(Rect::new(0.0, 0.0, W as f32, H as f32), &bar);
        backend.end_frame();

        let px = surface.pixel_at(W / 2, H / 2);
        assert_eq!(
            (px.r, px.g, px.b),
            (custom_bg.r, custom_bg.g, custom_bg.b),
            "menu bar background must reflect the live theme, not `Theme::default()`",
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn set_theme_reaches_the_context_menu() {
        use crate::primitives::context_menu::{
            ContextMenuItem, ContextMenuItemMeasure, ContextMenuPlacement,
        };
        use crate::theme::Theme;
        use crate::types::{Color, StyledText};
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 100;
        const H: u32 = 100;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let custom_bg = Color::rgb(0x77, 0x88, 0x99);
        assert_ne!(
            custom_bg,
            Theme::default().hover_bg,
            "test fixture bug: the probe colour must differ from the default theme's"
        );
        backend.set_theme(Theme {
            hover_bg: custom_bg,
            ..Theme::default()
        });

        // Two real items, because `ContextMenu::layout_at` derives the
        // popup's height from the summed per-item measures: an empty
        // `items` gives `bounds.height == 0`, `draw_context_menu`
        // early-returns without painting a single pixel, and the probe
        // reads `begin_frame`'s clear colour instead of the fill under
        // test. Each item carries an `id` (an `id`-less item *is* the
        // separator — `ContextMenuItem::is_separator`), a one-char label
        // so no glyph reaches the probe column, and no
        // `detail`/`key_equivalent` so no right-aligned shortcut paints
        // either. `bg` stays `None` so the fill falls back to
        // `theme.hover_bg`.
        let item = |id: &str, label: &str| ContextMenuItem {
            id: Some(WidgetId::new(id)),
            label: StyledText::plain(label),
            ..Default::default()
        };
        let menu = ContextMenu {
            id: WidgetId::new("ctx"),
            items: vec![item("a", "A"), item("b", "B")],
            selected_idx: 0,
            bg: None,
            placement: ContextMenuPlacement::AnchorPoint,
        };
        let viewport = Rect::new(0.0, 0.0, W as f32, H as f32);
        let layout = menu.layout(4.0, 4.0, viewport, 60.0, |_| {
            ContextMenuItemMeasure::new(20.0)
        });

        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.draw_context_menu(&menu, &layout);
        backend.end_frame();

        assert!(
            layout.bounds.width > 0.0 && layout.bounds.height > 0.0,
            "test fixture bug: empty menu bounds"
        );
        // Probe the *second* row: `selected_idx` is 0, so row 0 is
        // covered by the `theme.selected_bg` highlight. Three-quarters
        // across the row keeps clear of the left-aligned label and of
        // the border stroke on either edge. Derived from the layout, not
        // hardcoded.
        let row = layout
            .visible_items
            .get(1)
            .expect("test fixture bug: second menu row not visible")
            .bounds;
        let px = surface.pixel_at(
            (row.x + row.width * 0.75) as u32,
            (row.y + row.height / 2.0) as u32,
        );
        assert_eq!(
            (px.r, px.g, px.b),
            (custom_bg.r, custom_bg.g, custom_bg.b),
            "context menu background must reflect the live theme, not `Theme::default()`",
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn set_theme_reaches_the_completions() {
        use crate::primitives::completions::{CompletionItem, CompletionItemMeasure};
        use crate::theme::Theme;
        use crate::types::{Color, StyledText};
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 200;
        const H: u32 = 100;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let custom_bg = Color::rgb(0xaa, 0xbb, 0xcc);
        assert_ne!(
            custom_bg,
            Theme::default().completion_bg,
            "test fixture bug: the probe colour must differ from the default theme's"
        );
        backend.set_theme(Theme {
            completion_bg: custom_bg,
            ..Theme::default()
        });

        // Two real items, because `Completions::layout` sums the
        // per-item measures to size the popup: an empty `items` gives
        // `bounds.height == 0`, `draw_completions` early-returns without
        // painting anything, and the probe reads `begin_frame`'s clear
        // colour instead of the fill under test. `detail` stays `None`
        // so no right-aligned text paints into the probe column.
        let item = |label: &str| CompletionItem {
            label: StyledText::plain(label),
            detail: None,
            documentation: None,
            kind: Default::default(),
            icon: None,
        };
        let completions = Completions {
            id: WidgetId::new("comp"),
            items: vec![item("alpha"), item("beta")],
            selected_idx: 0,
            scroll_offset: 0,
            has_focus: true,
        };
        let viewport = Rect::new(0.0, 0.0, W as f32, H as f32);
        let layout = completions.layout(10.0, 10.0, 16.0, viewport, 120.0, 60.0, |_| {
            CompletionItemMeasure::new(16.0)
        });

        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.draw_completions(&completions, &layout);
        backend.end_frame();

        assert!(
            layout.bounds.width > 0.0 && layout.bounds.height > 0.0,
            "test fixture bug: empty popup bounds"
        );
        // Probe the *second* row: `selected_idx` is 0, so row 0 carries
        // the `theme.completion_selected_bg` highlight. Three-quarters
        // across the row clears the left-aligned `" {label}"` text and
        // the border stroke on either edge. Derived from the layout, not
        // hardcoded.
        let row = layout
            .visible_items
            .get(1)
            .expect("test fixture bug: second completion row not visible")
            .bounds;
        let px = surface.pixel_at(
            (row.x + row.width * 0.75) as u32,
            (row.y + row.height / 2.0) as u32,
        );
        assert_eq!(
            (px.r, px.g, px.b),
            (custom_bg.r, custom_bg.g, custom_bg.b),
            "completions popup background must reflect the live theme, not `Theme::default()`",
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn set_theme_reaches_the_find_replace() {
        use crate::primitives::find_replace::compute_hit_regions;
        use crate::theme::Theme;
        use crate::types::Color;
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 600;
        const H: u32 = 200;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let custom_bg = Color::rgb(0x22, 0x44, 0x66);
        assert_ne!(
            custom_bg,
            Theme::default().surface_bg,
            "test fixture bug: the probe colour must differ from the default theme's"
        );
        backend.set_theme(Theme {
            surface_bg: custom_bg,
            ..Theme::default()
        });

        let (hit_regions, _input_width) = compute_hit_regions(50, false, "1 of 3", 2, 2);
        let panel = FindReplacePanel {
            query: "needle".into(),
            replacement: String::new(),
            show_replace: false,
            focus: 0,
            cursor: 3,
            sel_anchor: None,
            match_info: "1 of 3".into(),
            case_sensitive: false,
            whole_word: false,
            use_regex: false,
            preserve_case: false,
            in_selection: false,
            group_bounds: Rect::new(0.0, 0.0, W as f32, H as f32),
            panel_width: 50,
            replace_one_glyph: "R1".into(),
            replace_all_glyph: "R*".into(),
            hit_regions,
        };

        // Reads the cell metrics off the backend rather than assuming
        // `WinBackend::new`'s 16.0/8.0 defaults: `attach_headless`
        // overwrites `current_line_height`/`current_char_width` with the
        // *measured* DirectWrite metrics of the editor font, and those
        // are what `Backend::draw_find_replace` then hands
        // `crate::primitives::find_replace::paint`. Hardcoding
        // 16.0/8.0 here would put the probe at coordinates the painter
        // never painted on any host whose font measures differently.
        let cw = backend.char_width().max(1.0);
        let lh = backend.line_height().max(1.0);
        let popup_w = panel.panel_width as f32 * cw;
        // `show_replace` is false, so one input row + 2 rows of chrome.
        let popup_h = 3.0 * lh;
        let popup_x = (panel.group_bounds.x + panel.group_bounds.width - popup_w - 10.0)
            .max(panel.group_bounds.x);
        let popup_y = panel.group_bounds.y + 2.0;
        assert!(
            popup_w > 8.0
                && popup_h > 8.0
                && popup_x + popup_w <= W as f32
                && popup_y + popup_h <= H as f32,
            "test fixture bug: popup {popup_w}x{popup_h} at ({popup_x}, {popup_y}) (cell \
             {cw}x{lh}) does not fit the {W}x{H} probe surface",
        );

        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.draw_find_replace(Rect::new(0.0, 0.0, W as f32, H as f32), &panel);
        backend.end_frame();

        // 4 DIPs inside the popup's bottom-right corner: past the border
        // stroke, and below the single (`show_replace == false`) row of
        // hit regions, which all sit at `row == 0` — so nothing but the
        // background fill can have painted here.
        let px = surface.pixel_at(
            (popup_x + popup_w - 4.0) as u32,
            (popup_y + popup_h - 4.0) as u32,
        );
        assert_eq!(
            (px.r, px.g, px.b),
            (custom_bg.r, custom_bg.g, custom_bg.b),
            "find/replace panel background must reflect the live theme, not `Theme::default()`",
        );
    }

    /// `draw_editor` must read the live theme from `WinBackend::current_theme`
    /// rather than building its own `Theme::default()`, so a dark-themed app
    /// gets a dark editor background after `:colorscheme`/`set_theme`. Same
    /// pixel-probe pattern as the activity bar's `set_theme` coverage.
    #[cfg(target_os = "windows")]
    #[test]
    fn set_theme_reaches_the_editor() {
        use crate::primitives::editor::Editor;
        use crate::theme::Theme;
        use crate::types::{Color, WidgetId};
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 80;
        const H: u32 = 40;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let custom_bg = Color::rgb(0x77, 0x88, 0x99);
        assert_ne!(
            custom_bg,
            Theme::default().background,
            "test fixture bug: the probe colour must differ from the default theme's"
        );
        backend.set_theme(Theme {
            background: custom_bg,
            ..Theme::default()
        });

        let rect = Rect::new(0.0, 0.0, W as f32, H as f32);
        let editor = Editor::new(WidgetId::new("editor"), rect);

        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        let _ = backend.draw_editor(rect, &editor);
        backend.end_frame();

        let px = surface.pixel_at(W / 2, H / 2);
        assert_eq!(
            (px.r, px.g, px.b),
            (custom_bg.r, custom_bg.g, custom_bg.b),
            "editor background must reflect the live theme, not `Theme::default()`",
        );
    }

    /// `Backend::set_editor_v_scrollbar_width(Some(14.0))` makes
    /// `WinBackend::draw_editor` paint a scrollbar column exactly 14 DIPs
    /// wide — `[186, 200)` in a 200-DIP viewport — instead of one
    /// `current_char_width` (8 DIPs), and `Backend::editor_layout`
    /// reports the same column for hit-testing.
    #[cfg(target_os = "windows")]
    #[test]
    fn set_editor_v_scrollbar_width_paints_14px_column() {
        use crate::primitives::editor::Editor;
        use crate::theme::Theme;
        use crate::types::WidgetId;
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 200;
        const H: u32 = 80;

        let rect = Rect::new(0.0, 0.0, W as f32, H as f32);
        let mut editor = Editor::new(WidgetId::new("editor"), rect);
        editor.total_lines = 50;
        let bg = Theme::default().background;
        let bg = (bg.r, bg.g, bg.b);

        let paint = |v_scrollbar_w: Option<f32>| {
            let surface = HeadlessSurface::new(W, H).expect("create headless surface");
            let mut backend = WinBackend::new();
            backend
                .attach_headless(surface.target().clone(), W, H)
                .expect("attach headless surface");
            backend.set_editor_v_scrollbar_width(v_scrollbar_w);
            backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
            let _ = backend.draw_editor(rect, &editor);
            backend.end_frame();
            surface
        };
        let probe = |surface: &HeadlessSurface, x: u32| {
            let px = surface.pixel_at(x, H - 4);
            (px.r, px.g, px.b)
        };
        // Direct2D anti-aliases a fill's boundary pixel, bleeding a level or
        // two of track colour into the neighbouring text-area pixel, so an
        // exact `== bg` on a pixel next to the column edge is not a stable
        // assertion. The track (40, 44, 56) is ~20 levels per channel clear
        // of the background (20, 22, 30), far outside this tolerance, so
        // "background" and "track" stay unambiguous.
        const AA_TOLERANCE: i32 = 4;
        let is_bg = |px: (u8, u8, u8)| {
            (px.0 as i32 - bg.0 as i32).abs() <= AA_TOLERANCE
                && (px.1 as i32 - bg.1 as i32).abs() <= AA_TOLERANCE
                && (px.2 as i32 - bg.2 as i32).abs() <= AA_TOLERANCE
        };

        let widened = paint(Some(14.0));
        assert!(
            is_bg(probe(&widened, 183)),
            "x=183 lies left of the 14px column at [186, 200)"
        );
        for x in 186..W {
            assert!(
                !is_bg(probe(&widened, x)),
                "x={x} lies inside the 14px column [186, 200)"
            );
        }

        let default = paint(None);
        assert!(
            is_bg(probe(&default, 189)),
            "default column is 8px: x=189 is text area"
        );
        assert!(
            !is_bg(probe(&default, 194)),
            "default column is 8px: x=194 is track"
        );

        let mut backend = WinBackend::new();
        backend.set_editor_v_scrollbar_width(Some(14.0));
        assert_eq!(backend.editor_v_scrollbar_width(), Some(14.0));
        let vsb = Backend::editor_layout(&backend, rect, &editor)
            .v_scrollbar_bounds
            .expect("buffer overflows");
        assert_eq!((vsb.x, vsb.width), (186.0, 14.0));
    }

    /// `draw_tree` (the Explorer sidebar's own content rasteriser) must read
    /// the live theme from `WinBackend::current_theme` rather than building
    /// its own `Theme::default()`.
    #[cfg(target_os = "windows")]
    #[test]
    fn set_theme_reaches_the_tree() {
        use crate::theme::Theme;
        use crate::types::Color;
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 80;
        const H: u32 = 40;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let custom_bg = Color::rgb(0xaa, 0xbb, 0xcc);
        assert_ne!(
            custom_bg,
            Theme::default().tab_bar_bg,
            "test fixture bug: the probe colour must differ from the default theme's"
        );
        backend.set_theme(Theme {
            tab_bar_bg: custom_bg,
            ..Theme::default()
        });

        let tree = flat_tree(1);
        let rect = Rect::new(0.0, 0.0, W as f32, H as f32);

        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.draw_tree(rect, &tree);
        backend.end_frame();

        // Sample past the single row's band — still inside the tree's
        // own background fill, clear of any row chrome.
        let px = surface.pixel_at(W / 2, H - 2);
        assert_eq!(
            (px.r, px.g, px.b),
            (custom_bg.r, custom_bg.g, custom_bg.b),
            "Explorer sidebar (tree) background must reflect the live theme, not `Theme::default()`",
        );
    }

    /// `paint_tab_bar_icons_from_layout` must read the live theme from
    /// `WinBackend::current_theme` rather than building its own
    /// `Theme::default()`.
    #[cfg(target_os = "windows")]
    #[test]
    fn set_theme_reaches_the_tab_bar() {
        use crate::theme::Theme;
        use crate::types::Color;
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 100;
        const H: u32 = 24;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let custom_bg = Color::rgb(0x33, 0x66, 0x99);
        assert_ne!(
            custom_bg,
            Theme::default().tab_bar_bg,
            "test fixture bug: the probe colour must differ from the default theme's"
        );
        backend.set_theme(Theme {
            tab_bar_bg: custom_bg,
            ..Theme::default()
        });

        #[allow(deprecated)]
        let tab_bar = TabBar {
            id: WidgetId::new("tab-bar"),
            tabs: Vec::new(),
            scroll_offset: 0,
            right_segments: Vec::new(),
            active_accent: None,
            show_tab_close: false,
            compact: false,
        };
        let rect = Rect::new(0.0, 0.0, W as f32, H as f32);

        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        #[allow(deprecated)]
        let _ = backend.draw_tab_bar(rect, &tab_bar, None);
        backend.end_frame();

        let px = surface.pixel_at(W / 2, H / 2);
        assert_eq!(
            (px.r, px.g, px.b),
            (custom_bg.r, custom_bg.g, custom_bg.b),
            "tab bar background must reflect the live theme, not `Theme::default()`",
        );
    }

    /// `draw_panel`'s title-bar chrome must paint from the live theme
    /// rather than a hardcoded `Theme::default()`.
    #[cfg(target_os = "windows")]
    #[test]
    fn set_theme_reaches_the_panel() {
        use crate::primitives::panel::Panel;
        use crate::theme::Theme;
        use crate::types::{Color, StyledText, WidgetId};
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 100;
        const H: u32 = 60;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let custom_separator = Color::rgb(0x12, 0x99, 0x34);
        assert_ne!(
            custom_separator,
            Theme::default().separator,
            "test fixture bug: the probe colour must differ from the default theme's"
        );
        backend.set_theme(Theme {
            separator: custom_separator,
            ..Theme::default()
        });

        let panel = Panel {
            id: WidgetId::new("panel"),
            title: Some(StyledText::plain("Terminal")),
            actions: Vec::new(),
            accent: None,
            collapsed: false,
        };
        let rect = Rect::new(0.0, 0.0, W as f32, H as f32);

        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        let layout = backend.draw_panel(rect, &panel);
        backend.end_frame();

        let tb = layout
            .title_bar_bounds
            .expect("panel has a title, so a title bar is reserved");
        // Sample near the title bar's right edge, not its horizontal
        // centre: `paint`'s title text starts at `tb.x + 4.0` and
        // "Terminal" is wide enough on a real Windows font to reach
        // past the centre of this 100-DIP-wide panel, so a centre
        // sample lands on anti-aliased glyph ink (a blend of
        // `theme.foreground` and the fill) rather than the solid
        // `title_bg` fill this test means to probe. Text metrics are a
        // stub off-Windows, so this only matters on real Windows runs.
        let px = surface.pixel_at(
            (tb.x + tb.width - 2.0) as u32,
            (tb.y + tb.height / 2.0) as u32,
        );
        assert_eq!(
            (px.r, px.g, px.b),
            (custom_separator.r, custom_separator.g, custom_separator.b),
            "panel title-bar background must reflect the live theme, not `Theme::default()`",
        );
    }

    /// `draw_sidebar_panel_interactive`'s embedded toolbar chrome must
    /// paint from the live theme rather than a hardcoded `Theme::default()`.
    #[cfg(target_os = "windows")]
    #[test]
    fn set_theme_reaches_the_sidebar_panel_toolbar() {
        use crate::theme::Theme;
        use crate::types::{Color, WidgetId};
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 100;
        const H: u32 = 60;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let custom_header_bg = Color::rgb(0x55, 0x11, 0x77);
        assert_ne!(
            custom_header_bg,
            Theme::default().header_bg,
            "test fixture bug: the probe colour must differ from the default theme's"
        );
        backend.set_theme(Theme {
            header_bg: custom_header_bg,
            ..Theme::default()
        });

        let panel = crate::primitives::sidebar_panel::SidebarPanel {
            id: WidgetId::new("sidebar-panel"),
            toolbar: Some(crate::primitives::toolbar::Toolbar {
                id: WidgetId::new("toolbar"),
                buttons: Vec::new(),
                bg: None,
                focused_index: None,
            }),
            toolbar_height: Some(24.0),
        };
        let rect = Rect::new(0.0, 0.0, W as f32, H as f32);
        let interaction = crate::interaction::InteractionState::default();

        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        let layout = backend.draw_sidebar_panel_interactive(rect, &panel, &interaction);
        backend.end_frame();

        let tb = layout
            .toolbar_bounds
            .expect("panel has a toolbar, so a toolbar slot is reserved");
        let px = surface.pixel_at(
            (tb.x + tb.width / 2.0) as u32,
            (tb.y + tb.height / 2.0) as u32,
        );
        assert_eq!(
            (px.r, px.g, px.b),
            (custom_header_bg.r, custom_header_bg.g, custom_header_bg.b),
            "sidebar panel toolbar background must reflect the live theme, not `Theme::default()`",
        );
    }

    /// `draw_split`'s divider chrome must paint from the live theme rather
    /// than a hardcoded `Theme::default()`.
    #[cfg(target_os = "windows")]
    #[test]
    fn set_theme_reaches_the_split() {
        use crate::primitives::split::{Split, SplitDirection};
        use crate::theme::Theme;
        use crate::types::{Color, WidgetId};
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 100;
        const H: u32 = 60;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let custom_separator = Color::rgb(0x44, 0x22, 0x88);
        assert_ne!(
            custom_separator,
            Theme::default().separator,
            "test fixture bug: the probe colour must differ from the default theme's"
        );
        backend.set_theme(Theme {
            separator: custom_separator,
            ..Theme::default()
        });

        let split = Split {
            id: WidgetId::new("split"),
            direction: SplitDirection::Horizontal,
            ratio: 0.5,
            first_min: 0.0,
            second_min: 0.0,
        };
        let rect = Rect::new(0.0, 0.0, W as f32, H as f32);

        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        let layout = backend.draw_split(rect, &split);
        backend.end_frame();

        let db = layout.divider_bounds;
        let px = surface.pixel_at(
            (db.x + db.width / 2.0) as u32,
            (db.y + db.height / 2.0) as u32,
        );
        assert_eq!(
            (px.r, px.g, px.b),
            (custom_separator.r, custom_separator.g, custom_separator.b),
            "split divider must reflect the live theme, not `Theme::default()`",
        );
    }

    /// `draw_split_tree`'s divider chrome must paint from the live theme
    /// rather than a hardcoded `Theme::default()`.
    #[cfg(target_os = "windows")]
    #[test]
    fn set_theme_reaches_the_split_tree() {
        use crate::primitives::split::SplitDirection;
        use crate::primitives::split_tree::SplitTree;
        use crate::theme::Theme;
        use crate::types::{Color, WidgetId};
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 100;
        const H: u32 = 60;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let custom_separator = Color::rgb(0x66, 0x33, 0x99);
        assert_ne!(
            custom_separator,
            Theme::default().separator,
            "test fixture bug: the probe colour must differ from the default theme's"
        );
        backend.set_theme(Theme {
            separator: custom_separator,
            ..Theme::default()
        });

        let tree = SplitTree::split(
            SplitDirection::Horizontal,
            0.5,
            SplitTree::leaf(WidgetId::new("left")),
            SplitTree::leaf(WidgetId::new("right")),
        );
        let rect = Rect::new(0.0, 0.0, W as f32, H as f32);

        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        let layout = backend.draw_split_tree(rect, &tree);
        backend.end_frame();

        let div = layout
            .dividers
            .first()
            .expect("one divider between two leaves");
        let (cx, cy) = match div.direction {
            SplitDirection::Horizontal => (
                div.position + div.thickness / 2.0,
                div.cross_start + div.cross_size / 2.0,
            ),
            SplitDirection::Vertical => (
                div.cross_start + div.cross_size / 2.0,
                div.position + div.thickness / 2.0,
            ),
        };
        let px = surface.pixel_at(cx as u32, cy as u32);
        assert_eq!(
            (px.r, px.g, px.b),
            (custom_separator.r, custom_separator.g, custom_separator.b),
            "split-tree divider must reflect the live theme, not `Theme::default()`",
        );
    }

    // ── PaintSurface (#807, Phase 1) ────────────────────────────────────────
    //
    // Real Direct2D execution — `#[cfg(target_os = "windows")]`-gated because
    // `attach_headless`/`HeadlessSurface` only exist on that target; `cargo
    // check --features win` on Linux still type-checks the impl block above.

    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_paint_surface_fill_rect_paints_solid_color() {
        use crate::types::Color;
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 32;
        const H: u32 = 32;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let red = Color::rgb(200, 20, 20);
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.surface_fill_rect(Rect::new(0.0, 0.0, W as f32, H as f32), red);
        backend.end_frame();

        let px = surface.pixel_at(5, 5);
        assert_eq!(
            (px.r, px.g, px.b),
            (red.r, red.g, red.b),
            "surface_fill_rect must paint the solid color it was given"
        );
    }

    /// The colour an unpainted pixel carries after [`Backend::begin_frame`] on a
    /// freshly-attached [`HeadlessSurface`].
    ///
    /// Win-GUI's `begin_frame` issues a `Clear` with its placeholder background,
    /// so "untouched" is **not** `(0, 0, 0)` the way it is for the GTK twins of the
    /// tests below — those probe a zeroed `cairo::ImageSurface` that nothing
    /// clears. Reading one pixel from a live empty frame keeps these assertions
    /// honest whichever colour that clear grows into.
    #[cfg(target_os = "windows")]
    fn cleared_frame_background(width: u32, height: u32) -> (u8, u8, u8) {
        use crate::win::testing::HeadlessSurface;

        let surface = HeadlessSurface::new(width, height).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), width, height)
            .expect("attach headless surface");
        backend.begin_frame(Viewport::new(width as f32, height as f32, 1.0));
        backend.end_frame();
        let px = surface.pixel_at(0, 0);
        (px.r, px.g, px.b)
    }

    /// [`cleared_frame_background`] samples a single pixel as "the
    /// background every other headless test compares against"; this is
    /// the test that proves one pixel is enough, i.e. that
    /// [`Backend::begin_frame`]'s `Clear` really covers the whole render
    /// target rather than some sub-rect.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_begin_frame_clears_the_whole_surface_uniformly() {
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 16;
        const H: u32 = 16;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.end_frame();

        let expected = cleared_frame_background(W, H);
        for y in 0..H {
            for x in 0..W {
                let px = surface.pixel_at(x, y);
                assert_eq!(
                    (px.r, px.g, px.b),
                    expected,
                    "begin_frame's Clear must cover every pixel — ({x}, {y}) differs, so \
                     sampling one pixel as 'the background' would be wrong"
                );
            }
        }
    }

    /// Real `FillRoundedRectangle` execution, mirroring
    /// `gtk_backend_paint_surface_fill_rounded_rect_clips_the_corners` —
    /// a centre pixel must land the fill colour, and a corner pixel well
    /// inside a generous radius must stay at [`begin_frame`](Backend::begin_frame)'s
    /// clear colour (see [`cleared_frame_background`] for why that isn't
    /// black here, unlike the GTK twin), or this would just be
    /// `surface_fill_rect` under a new name.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_paint_surface_fill_rounded_rect_clips_the_corners() {
        use crate::types::Color;
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 40;
        const H: u32 = 40;

        let background = cleared_frame_background(W, H);
        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let red = Color::rgb(200, 20, 20);
        assert_ne!(
            background,
            (red.r, red.g, red.b),
            "the fill colour must differ from the frame's clear colour, or \
             'this corner stayed untouched' is unprovable"
        );
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.surface_fill_rounded_rect(Rect::new(0.0, 0.0, W as f32, H as f32), 15.0, red);
        backend.end_frame();

        let centre = surface.pixel_at(20, 20);
        assert_eq!(
            (centre.r, centre.g, centre.b),
            (red.r, red.g, red.b),
            "surface_fill_rounded_rect must paint the solid color at the box's centre"
        );
        let corner = surface.pixel_at(1, 1);
        assert_eq!(
            (corner.r, corner.g, corner.b),
            background,
            "a corner pixel well inside a radius-15 fillet on a 40x40 box must stay at \
             the frame's clear colour — otherwise this is just `surface_fill_rect` \
             under a new name"
        );
    }

    /// Real `DrawRoundedRectangle` execution, the stroke twin of
    /// `win_backend_paint_surface_fill_rounded_rect_clips_the_corners` —
    /// the straight middle of an edge lands the stroke colour, a corner
    /// well inside the fillet stays at the clear colour, and so does the
    /// box's own centre (proving this strokes rather than fills).
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_paint_surface_stroke_rounded_rect_clips_the_corners() {
        use crate::types::Color;
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 40;
        const H: u32 = 40;

        let background = cleared_frame_background(W, H);
        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let blue = Color::rgb(60, 120, 220);
        assert_ne!(
            background,
            (blue.r, blue.g, blue.b),
            "the stroke colour must differ from the frame's clear colour"
        );
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.surface_stroke_rounded_rect(
            Rect::new(0.0, 0.0, W as f32, H as f32),
            15.0,
            blue,
            4.0,
        );
        backend.end_frame();

        let edge = surface.pixel_at(20, 1);
        assert_eq!(
            (edge.r, edge.g, edge.b),
            (blue.r, blue.g, blue.b),
            "the straight middle of the top edge must land the stroke colour"
        );
        let corner = surface.pixel_at(1, 1);
        assert_eq!(
            (corner.r, corner.g, corner.b),
            background,
            "a corner pixel well inside a radius-15 fillet on a 40x40 box must stay at \
             the frame's clear colour"
        );
        let centre = surface.pixel_at(20, 20);
        assert_eq!(
            (centre.r, centre.g, centre.b),
            background,
            "the box's centre, far from any stroke, must stay at the frame's clear \
             colour — otherwise this is `surface_fill_rounded_rect` under a new name"
        );
    }

    /// `surface_draw_shadow` has no `WinBackend` override — it
    /// inherits `PaintSurface`'s default, composed out of
    /// `surface_fill_rounded_rect`. Proves that default verb genuinely
    /// paints on Direct2D's own render target, the Win-GUI twin of
    /// `gtk_backend_paint_surface_draw_shadow_elevation_three_paints_below_the_box`.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_paint_surface_draw_shadow_elevation_three_paints_below_the_box() {
        use crate::types::Color;
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 40;
        const H: u32 = 40;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let white = Color::rgb(255, 255, 255);
        let shadow = Color::rgba(0, 0, 0, 200);
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.surface_fill_rect(Rect::new(0.0, 0.0, W as f32, H as f32), white);
        backend.surface_draw_shadow(Rect::new(5.0, 5.0, 20.0, 20.0), 6.0, 3, shadow);
        backend.end_frame();

        let px = surface.pixel_at(15, 29);
        assert_ne!(
            (px.r, px.g, px.b),
            (white.r, white.g, white.b),
            "a pixel just below the box's bottom edge must pick up shadow ink at \
             elevation 3"
        );
    }

    /// `surface_fill_rect_alpha` has no `WinBackend` override —
    /// it inherits `PaintSurface`'s default, which forwards to
    /// `surface_fill_rect` with `color.a` replaced. This proves that
    /// default genuinely blends on Direct2D's own compositing pipeline
    /// (not merely that the Rust dispatch is correct), the Win-GUI twin
    /// of `gtk_backend_paint_surface_fill_rect_alpha_blends_with_the_background`.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_paint_surface_fill_rect_alpha_blends_with_the_background() {
        use crate::types::Color;
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 40;
        const H: u32 = 40;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let white = Color::rgb(255, 255, 255);
        let red = Color::rgb(200, 20, 20);
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.surface_fill_rect(Rect::new(0.0, 0.0, W as f32, H as f32), white);
        backend.surface_fill_rect_alpha(Rect::new(0.0, 0.0, W as f32, H as f32), red, 0.5);
        backend.end_frame();

        let px = surface.pixel_at(20, 20);
        assert!(
            (px.r, px.g, px.b) != (white.r, white.g, white.b)
                && (px.r, px.g, px.b) != (red.r, red.g, red.b),
            "a 50%-alpha fill over an opaque background must land a real blend, not the \
             background or the fill colour verbatim: got ({}, {}, {})",
            px.r,
            px.g,
            px.b
        );
        // Real source-over compositing of 50%-alpha red onto opaque white
        // lands roughly halfway between the two on every channel. The
        // bands are deliberately generous rather than exact: which colour
        // space Direct2D blends in (gamma-encoded for this target's
        // non-`_SRGB` `DXGI_FORMAT_B8G8R8A8_UNORM`, linear for an `_SRGB`
        // one) shifts the midpoint without changing what's being asserted
        // — that a blend happened at all, and towards the right end of
        // each channel.
        assert!(
            (200..=245).contains(&px.r),
            "red channel should sit between the fill's 200 and white's 255: got {}",
            px.r
        );
        assert!(
            (100..=200).contains(&px.g) && (100..=200).contains(&px.b),
            "green/blue channels should sit between the fill's 20 and white's 255: \
             got ({}, {})",
            px.g,
            px.b
        );
    }

    /// `role` must select a genuinely different live `IDWriteTextFormat`
    /// (the `chrome_dwrite` handle vs the editor `dwrite` one), not a documented
    /// no-op — proven by a huge chrome font size versus a tiny editor font size
    /// painting visibly different amounts of ink for the same glyph. Win-GUI twin
    /// of `gtk_backend_paint_surface_draw_text_run_with_role_uses_the_requested_fonts_size`.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_paint_surface_draw_text_run_with_role_uses_the_requested_fonts_size() {
        use crate::types::Color;
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 80;
        const H: u32 = 80;

        // "Ink" is any pixel the glyph moved off `begin_frame`'s clear
        // colour — not "any pixel brighter than black", which on this
        // backend counts the whole cleared surface (see
        // `cleared_frame_background`).
        fn ink_pixel_count(surface: &HeadlessSurface, background: (u8, u8, u8)) -> u32 {
            let mut count = 0;
            for y in 0..H {
                for x in 0..W {
                    let px = surface.pixel_at(x, y);
                    if (px.r, px.g, px.b) != background {
                        count += 1;
                    }
                }
            }
            count
        }

        let background = cleared_frame_background(W, H);
        let white = Color::rgb(255, 255, 255);

        // `set_editor_font`/`set_ui_font` must precede `attach_headless`
        // — that's where the `IDWriteTextFormat` pair is built from these
        // fields (see `set_editor_font`'s doc).
        let chrome_surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend.set_editor_font(DEFAULT_UI_FONT_FAMILY, 6.0);
        backend.set_ui_font(&format!("{DEFAULT_UI_FONT_FAMILY} 60"));
        backend
            .attach_headless(chrome_surface.target().clone(), W, H)
            .expect("attach headless surface");
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.surface_draw_text_run_with_role(
            Rect::new(2.0, 2.0, 76.0, 76.0),
            "A",
            white,
            crate::FontRole::Chrome,
            false,
        );
        backend.end_frame();
        let chrome_ink = ink_pixel_count(&chrome_surface, background);

        let editor_surface = HeadlessSurface::new(W, H).expect("create headless surface");
        backend
            .attach_headless(editor_surface.target().clone(), W, H)
            .expect("attach headless surface");
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.surface_draw_text_run_with_role(
            Rect::new(2.0, 2.0, 76.0, 76.0),
            "A",
            white,
            crate::FontRole::Editor,
            false,
        );
        backend.end_frame();
        let editor_ink = ink_pixel_count(&editor_surface, background);

        assert!(
            chrome_ink > editor_ink * 4,
            "FontRole::Chrome (60pt) must paint far more ink than FontRole::Editor \
             (6pt) for the same glyph: chrome={chrome_ink}, editor={editor_ink}"
        );
        assert!(editor_ink > 0, "FontRole::Editor must still paint real ink");
    }

    /// `WinBackend::draw_dialog` now passes `chrome_dwrite` for body text, so it
    /// should render at the *chrome* font's size, not the editor's.
    ///
    /// The editor font size is held **fixed** across both runs — only the chrome
    /// (ui) font size varies. If it were still painted through the editor `dwrite`
    /// handle, both runs would paint identical ink regardless of the chrome size.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_dialog_paints_body_text_in_the_chrome_fonts_size() {
        use crate::primitives::dialog::DialogMeasure;
        use crate::primitives::toolbar::ToolbarItemMeasure;
        use crate::theme::Theme;
        use crate::types::{StyledText, WidgetId};
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 100;
        const H: u32 = 100;
        const EDITOR_SIZE_PT: f32 = 14.0;

        fn body_only_dialog() -> Dialog {
            Dialog {
                id: WidgetId::new("d"),
                title: StyledText::plain(""),
                body: vec![StyledText::plain("A")],
                buttons: vec![],
                severity: None,
                vertical_buttons: false,
                table: None,
                input: None,
            }
        }

        fn body_layout() -> DialogLayout {
            let dialog = body_only_dialog();
            let viewport = Rect::new(0.0, 0.0, W as f32, H as f32);
            let measure = DialogMeasure {
                width: W as f32,
                title_height: 0.0,
                body_height: 90.0,
                table_height: 0.0,
                input_height: 0.0,
                button_row_height: 0.0,
                button_width: 0.0,
                button_gap: 0.0,
                padding: 4.0,
            };
            dialog.layout(viewport, measure, |_| ToolbarItemMeasure::new(0.0))
        }

        /// Rightmost ink column within `body_bounds` that differs from
        /// `theme.surface_bg` — i.e. the right edge of the body text's
        /// glyph ink, relative to `body_bounds.x`. Horizontal extent,
        /// not pixel *count*: `body_bounds`' row height is always the
        /// (fixed, in this test) editor font's line height — see this
        /// test's own doc — so a much taller chrome glyph gets vertically
        /// clipped by `D2D1_DRAW_TEXT_OPTIONS_CLIP` regardless of its
        /// point size, making a raw ink-pixel *count* comparison weak.
        /// Its *width* is never clipped (the row is far wider than one
        /// glyph), and a larger font paints a strictly wider glyph for
        /// any real typeface.
        fn body_ink_right_edge(surface: &HeadlessSurface, body_bounds: Rect) -> i32 {
            let bg = Theme::default().surface_bg;
            let mut last = 0i32;
            for y in body_bounds.y as u32..(body_bounds.y + body_bounds.height) as u32 {
                for x in body_bounds.x as u32..(body_bounds.x + body_bounds.width) as u32 {
                    let px = surface.pixel_at(x, y);
                    if (px.r, px.g, px.b) != (bg.r, bg.g, bg.b) {
                        last = last.max(x as i32 - body_bounds.x as i32);
                    }
                }
            }
            last
        }

        fn paint_with_chrome_size(chrome_size_pt: f32, layout: &DialogLayout) -> i32 {
            let surface = HeadlessSurface::new(W, H).expect("create headless surface");
            let mut backend = WinBackend::new();
            backend.set_editor_font(DEFAULT_UI_FONT_FAMILY, EDITOR_SIZE_PT);
            backend.set_ui_font(&format!("{DEFAULT_UI_FONT_FAMILY} {chrome_size_pt}"));
            backend
                .attach_headless(surface.target().clone(), W, H)
                .expect("attach headless surface");
            backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
            let _ = Backend::draw_dialog(&mut backend, &body_only_dialog(), layout);
            backend.end_frame();
            body_ink_right_edge(&surface, layout.body_bounds)
        }

        let layout = body_layout();

        let right_tiny_chrome = paint_with_chrome_size(6.0, &layout);
        let right_huge_chrome = paint_with_chrome_size(40.0, &layout);

        assert!(
            right_huge_chrome > right_tiny_chrome * 2,
            "with the editor font size held fixed at {EDITOR_SIZE_PT}pt, only varying \
             the chrome font size (6pt vs 40pt), the dialog body's glyph should paint \
             far wider at the larger chrome size — proves draw_dialog paints body text \
             via chrome_dwrite, not the (unchanged) editor dwrite handle \
             (right_tiny_chrome={right_tiny_chrome}, right_huge_chrome={right_huge_chrome})"
        );
        assert!(
            right_tiny_chrome > 0,
            "the tiny-chrome run must still paint some real ink, or this comparison \
             proves nothing"
        );
    }

    /// `Backend::draw_rich_text_popup_with_font_role` must select a genuinely
    /// different live `IDWriteTextFormat`, not a documented no-op. Plain
    /// `draw_rich_text_popup` (no role argument) must paint through the chrome
    /// handle, and `draw_rich_text_popup_with_font_role(.., FontRole::Editor)`
    /// must paint through the editor handle instead.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_rich_text_popup_honours_font_role() {
        use crate::primitives::rich_text_popup::{
            PopupPlacement, RichTextPopup, RichTextPopupMeasure,
        };
        use crate::types::{Color, StyledText, WidgetId};
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 120;
        const H: u32 = 120;
        const EDITOR_SIZE_PT: f32 = 6.0;
        const CHROME_SIZE_PT: f32 = 40.0;
        let bg = Color::rgb(0, 0, 0);
        let fg = Color::rgb(255, 255, 255);

        fn popup(bg: Color, fg: Color) -> RichTextPopup {
            RichTextPopup {
                id: WidgetId::new("rtp:font-role"),
                lines: vec![StyledText::plain("M")],
                line_text: vec!["M".to_string()],
                line_scales: vec![],
                scroll_top: 0,
                max_visible_rows: 4,
                has_focus: false,
                selection: None,
                links: vec![],
                focused_link: None,
                placement: PopupPlacement::Below,
                padding: 0.0,
                fg: Some(fg),
                bg: Some(bg),
            }
        }

        fn ink_right_edge(surface: &HeadlessSurface, bounds: Rect, bg: (u8, u8, u8)) -> i32 {
            let mut last = 0i32;
            for y in bounds.y as u32..(bounds.y + bounds.height) as u32 {
                for x in bounds.x as u32..(bounds.x + bounds.width) as u32 {
                    let px = surface.pixel_at(x, y);
                    if (px.r, px.g, px.b) != bg {
                        last = last.max(x as i32 - bounds.x as i32);
                    }
                }
            }
            last
        }

        fn paint_with_role(role: Option<crate::FontRole>, bg: Color, fg: Color) -> (i32, Rect) {
            let surface = HeadlessSurface::new(W, H).expect("create headless surface");
            let mut backend = WinBackend::new();
            backend.set_editor_font(DEFAULT_UI_FONT_FAMILY, EDITOR_SIZE_PT);
            backend.set_ui_font(&format!("{DEFAULT_UI_FONT_FAMILY} {CHROME_SIZE_PT}"));
            backend
                .attach_headless(surface.target().clone(), W, H)
                .expect("attach headless surface");
            backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
            let p = popup(bg, fg);
            let measure = RichTextPopupMeasure::new(100.0, 90.0);
            let layout = p.layout(
                2.0,
                2.0,
                Rect::new(0.0, 0.0, W as f32, H as f32),
                measure,
                |_, s, e| (e - s) as f32,
            );
            let content = layout.content_bounds;
            match role {
                Some(role) => {
                    Backend::draw_rich_text_popup_with_font_role(&mut backend, &p, &layout, role)
                }
                None => Backend::draw_rich_text_popup(&mut backend, &p, &layout),
            }
            backend.end_frame();
            (
                ink_right_edge(&surface, content, (bg.r, bg.g, bg.b)),
                content,
            )
        }

        // `None` = plain `draw_rich_text_popup` (today's call site, no
        // role argument at all) — must still paint the chrome font.
        let (chrome_right, _) = paint_with_role(None, bg, fg);
        let (editor_right, _) = paint_with_role(Some(crate::FontRole::Editor), bg, fg);

        assert!(
            editor_right > 0,
            "FontRole::Editor must still paint real ink, got {editor_right}"
        );
        assert!(
            chrome_right > editor_right * 2,
            "with the editor font size held fixed at {EDITOR_SIZE_PT}pt, plain \
             draw_rich_text_popup (no role argument) painting the {CHROME_SIZE_PT}pt \
             chrome font should paint a far wider glyph than FontRole::Editor: \
             chrome_right={chrome_right}, editor_right={editor_right}"
        );
    }

    // ── the eleven remaining `ChromePrimitive` rasterisers ──────
    //
    // `Dialog`/`RichTextPopup` (above) and the `FontRole::Chrome`
    // plumbing itself were already wired; this closes the
    // gap for the rest of `font_role::ChromePrimitive::ALL`: `Tree`,
    // `List`, `MenuBar`, `ContextMenu`, `CommandCenter`,
    // `MultiSectionView`, `SidebarPanel`, `StatusBar`, `ActivityBar`,
    // `Toolbar`, `TabBar`.
    //
    // Each test below fails first: pre-change, every one of these always
    // painted through the editor `dwrite` handle regardless of
    // `set_ui_font`, so two renders that differ *only* in chrome font
    // size were byte-identical. Diffing the whole painted frame (rather
    // than measuring one glyph's ink extent, `win_backend_draw_dialog_paints_body_text_in_the_chrome_fonts_size`'s
    // approach above) is primitive-agnostic: it needs no per-primitive
    // knowledge of background colour or exact glyph bounds, just "this
    // primitive paints some real text".
    #[cfg(target_os = "windows")]
    fn chrome_font_diff_pixel_count(
        w: u32,
        h: u32,
        ui_font_a: &str,
        ui_font_b: &str,
        paint: impl Fn(&mut WinBackend),
    ) -> u32 {
        use crate::win::testing::HeadlessSurface;

        fn render(
            w: u32,
            h: u32,
            ui_font: &str,
            paint: &dyn Fn(&mut WinBackend),
        ) -> HeadlessSurface {
            let surface = HeadlessSurface::new(w, h).expect("create headless surface");
            let mut backend = WinBackend::new();
            // Editor font held fixed across both renders — only the
            // chrome (`ui_font`) one varies, same discipline
            // `win_backend_draw_dialog_paints_body_text_in_the_chrome_fonts_size`
            // documents.
            backend.set_editor_font(DEFAULT_UI_FONT_FAMILY, 10.0);
            backend.set_ui_font(ui_font);
            backend
                .attach_headless(surface.target().clone(), w, h)
                .expect("attach headless surface");
            backend.begin_frame(Viewport::new(w as f32, h as f32, 1.0));
            paint(&mut backend);
            backend.end_frame();
            surface
        }
        let a = render(w, h, ui_font_a, &paint);
        let b = render(w, h, ui_font_b, &paint);
        let mut diff = 0u32;
        for y in 0..h {
            for x in 0..w {
                if a.pixel_at(x, y) != b.pixel_at(x, y) {
                    diff += 1;
                }
            }
        }
        diff
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_tree_paints_row_text_in_the_chrome_fonts_size() {
        let tree = flat_tree(3);
        let diff = chrome_font_diff_pixel_count(
            200,
            120,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                backend.draw_tree(Rect::new(0.0, 0.0, 200.0, 120.0), &tree);
            },
        );
        assert!(
            diff > 0,
            "#1266: varying only the chrome font size must repaint different pixels — \
             draw_tree must paint row text through chrome_dwrite, not the (unchanged) \
             editor dwrite handle"
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_list_paints_row_text_in_the_chrome_fonts_size() {
        let list = ListView {
            id: WidgetId::new("list"),
            title: None,
            items: vec![
                crate::primitives::list::ListItem {
                    text: crate::types::StyledText::plain("alpha"),
                    icon: None,
                    detail: None,
                    decoration: crate::types::Decoration::Normal,
                },
                crate::primitives::list::ListItem {
                    text: crate::types::StyledText::plain("beta"),
                    icon: None,
                    detail: None,
                    decoration: crate::types::Decoration::Normal,
                },
            ],
            selected_idx: 0,
            scroll_offset: 0,
            has_focus: false,
            bordered: false,
            h_scroll: 0,
            max_content_width: None,
            show_v_scrollbar: false,
        };
        let diff = chrome_font_diff_pixel_count(
            200,
            120,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                backend.draw_list(Rect::new(0.0, 0.0, 200.0, 120.0), &list);
            },
        );
        assert!(
            diff > 0,
            "#1266: draw_list must paint row text through chrome_dwrite, not the \
             (unchanged) editor dwrite handle"
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_menu_bar_paints_item_labels_in_the_chrome_fonts_size() {
        let bar = MenuBar {
            id: WidgetId::new("bar"),
            items: vec![crate::primitives::menu_bar::MenuBarItem {
                id: WidgetId::new("bar:file"),
                label: "&File".into(),
                disabled: false,
                submenu: None,
            }],
            open_item: None,
            focused_item: None,
        };
        let diff = chrome_font_diff_pixel_count(
            300,
            32,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                let _ = backend.draw_menu_bar(Rect::new(0.0, 0.0, 300.0, 32.0), &bar);
            },
        );
        assert!(
            diff > 0,
            "#1266: draw_menu_bar must paint item labels through chrome_dwrite, not \
             the (unchanged) editor dwrite handle"
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_context_menu_paints_item_labels_in_the_chrome_fonts_size() {
        let menu = ContextMenu {
            id: WidgetId::new("ctx"),
            items: vec![crate::primitives::context_menu::ContextMenuItem {
                id: Some(WidgetId::new("ctx:copy")),
                label: crate::types::StyledText::plain("copy"),
                ..Default::default()
            }],
            selected_idx: 0,
            bg: None,
            placement: crate::primitives::context_menu::ContextMenuPlacement::AnchorPoint,
        };
        let viewport = Rect::new(0.0, 0.0, 200.0, 100.0);
        let layout = menu.layout(10.0, 10.0, viewport, 120.0, |_| {
            crate::primitives::context_menu::ContextMenuItemMeasure::new(20.0)
        });
        let diff = chrome_font_diff_pixel_count(
            200,
            100,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                let _ = backend.draw_context_menu(&menu, &layout);
            },
        );
        assert!(
            diff > 0,
            "#1266: draw_context_menu must paint item labels through chrome_dwrite, \
             not the (unchanged) editor dwrite handle"
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_command_center_paints_the_search_label_in_the_chrome_fonts_size() {
        let cc = CommandCenter {
            id: WidgetId::new("cc"),
            back_enabled: true,
            forward_enabled: true,
            search_label: "project-name".into(),
        };
        let diff = chrome_font_diff_pixel_count(
            300,
            32,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                let _ = backend.draw_command_center(Rect::new(0.0, 0.0, 300.0, 32.0), &cc);
            },
        );
        assert!(
            diff > 0,
            "#1266: draw_command_center must paint the search label through \
             chrome_dwrite, not the (unchanged) editor dwrite handle"
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_multi_section_view_paints_header_titles_in_the_chrome_fonts_size() {
        let view = MultiSectionView {
            id: WidgetId::new("msv"),
            sections: vec![crate::primitives::multi_section_view::Section {
                id: "alpha".into(),
                header: crate::primitives::multi_section_view::SectionHeader {
                    icon: None,
                    title: crate::types::StyledText::plain("alpha"),
                    badge: None,
                    actions: vec![],
                    show_chevron: true,
                },
                body: crate::primitives::multi_section_view::SectionBody::Text(vec![
                    crate::types::StyledText::plain("line one"),
                ]),
                aux: None,
                size: crate::primitives::multi_section_view::SectionSize::EqualShare,
                collapsed: false,
                min_size: None,
                max_size: None,
            }],
            active_section: Some(0),
            axis: crate::primitives::multi_section_view::Axis::Vertical,
            allow_resize: false,
            allow_collapse: true,
            scroll_mode: crate::primitives::multi_section_view::ScrollMode::PerSection,
            has_focus: true,
            panel_scroll: 0.0,
        };
        let diff = chrome_font_diff_pixel_count(
            200,
            150,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                backend.draw_multi_section_view(Rect::new(0.0, 0.0, 200.0, 150.0), &view);
            },
        );
        assert!(
            diff > 0,
            "#1266: draw_multi_section_view must paint section header titles through \
             chrome_dwrite, not the (unchanged) editor dwrite handle"
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_sidebar_panel_interactive_paints_the_toolbar_label_in_the_chrome_fonts_size(
    ) {
        let panel = crate::primitives::sidebar_panel::SidebarPanel {
            id: WidgetId::new("sb"),
            toolbar: Some(crate::primitives::toolbar::Toolbar {
                id: WidgetId::new("sb:toolbar"),
                buttons: vec![ToolbarButton::Action {
                    id: WidgetId::new("sb:refine"),
                    label: "Refine".into(),
                    icon: None,
                    key_hint: None,
                    enabled: true,
                    is_active: false,
                    tooltip: String::new(),
                }],
                bg: None,
                focused_index: None,
            }),
            toolbar_height: None,
        };
        let interaction = crate::interaction::InteractionState::new();
        let diff = chrome_font_diff_pixel_count(
            200,
            100,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                let _ = backend.draw_sidebar_panel_interactive(
                    Rect::new(0.0, 0.0, 200.0, 100.0),
                    &panel,
                    &interaction,
                );
            },
        );
        assert!(
            diff > 0,
            "#1266: draw_sidebar_panel_interactive must paint the embedded toolbar's \
             label through ChromeSurface (chrome_dwrite), not WinBackend's own \
             PaintSurface impl (the editor dwrite handle)"
        );
    }

    /// `Palette` builds its own `win::palette` adapter from whichever
    /// `dwrite` handle `WinBackend::draw_palette` passes in, so this call
    /// site isn't fixed by `impl PaintSurface for WinBackend`'s own
    /// default — it needs the direct `chrome_dwrite`-preferring swap
    /// this test pins.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_palette_paints_entries_in_the_chrome_fonts_size() {
        let palette = Palette {
            id: WidgetId::new("palette:commands"),
            title: "Commands".to_string(),
            query: String::new(),
            query_cursor: 0,
            items: vec![crate::primitives::palette::PaletteItem {
                text: crate::types::StyledText::plain("Save File"),
                detail: None,
                icon: None,
                match_positions: Vec::new(),
                depth: 0,
                expandable: false,
                expanded: false,
            }],
            selected_idx: 0,
            scroll_offset: 0,
            total_count: 1,
            has_focus: true,
            show_query: true,
            create_label: None,
            preview: None,
            mode: Default::default(),
        };
        let diff = chrome_font_diff_pixel_count(
            200,
            120,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                backend.draw_palette(Rect::new(0.0, 0.0, 200.0, 120.0), &palette);
            },
        );
        assert!(
            diff > 0,
            "varying only the chrome font size must repaint different pixels — \
             draw_palette must paint item text through chrome_dwrite, not the \
             (unchanged) editor dwrite handle"
        );
    }

    /// `Panel`'s title paints through `surface_draw_text_run` (plain
    /// `self`, not a per-call adapter), so this is fixed purely by
    /// `impl PaintSurface for WinBackend`'s inverted default — no
    /// per-call-site change needed, unlike `draw_palette` above.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_panel_paints_title_in_the_chrome_fonts_size() {
        let panel = Panel {
            id: WidgetId::new("panel"),
            title: Some(crate::types::StyledText::plain("Explorer")),
            actions: Vec::new(),
            accent: None,
            collapsed: false,
        };
        let diff = chrome_font_diff_pixel_count(
            200,
            80,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                let _ = backend.draw_panel(Rect::new(0.0, 0.0, 200.0, 80.0), &panel);
            },
        );
        assert!(
            diff > 0,
            "varying only the chrome font size must repaint different pixels — \
             draw_panel must paint the title through chrome_dwrite (WinBackend's \
             own PaintSurface default), not the editor dwrite handle"
        );
    }

    /// Same "builds its own adapter from the passed `dwrite`" shape as
    /// `draw_palette` above.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_spinner_paints_label_in_the_chrome_fonts_size() {
        let spinner = Spinner {
            id: WidgetId::new("spinner"),
            label: "Indexing…".to_string(),
            frame_idx: 0,
            accent: None,
        };
        let diff = chrome_font_diff_pixel_count(
            200,
            40,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                let _ = backend.draw_spinner(Rect::new(0.0, 0.0, 200.0, 40.0), &spinner);
            },
        );
        assert!(
            diff > 0,
            "varying only the chrome font size must repaint different pixels — \
             draw_spinner must paint its label through chrome_dwrite, not the \
             (unchanged) editor dwrite handle"
        );
    }

    /// The editor-class twin of the three tests above: `TextDisplay`
    /// paints through `EditorSurface`, so unlike `Panel`/`Palette`/
    /// `Spinner` its rendered pixels must stay identical regardless of
    /// the chrome font size — only the editor font (held fixed by
    /// `chrome_font_diff_pixel_count`) should affect it.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_text_display_does_not_vary_with_chrome_font_size() {
        let td = TextDisplay {
            id: WidgetId::new("log"),
            lines: vec![crate::primitives::text_display::TextDisplayLine {
                spans: vec![crate::types::StyledSpan::plain("hello world")],
                decoration: crate::types::Decoration::Normal,
                timestamp: None,
            }],
            scroll_offset: 0,
            auto_scroll: true,
            max_lines: 0,
            has_focus: false,
            title: None,
            show_scrollbar: false,
        };
        let diff = chrome_font_diff_pixel_count(
            200,
            40,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                backend.draw_text_display(Rect::new(0.0, 0.0, 200.0, 40.0), &td);
            },
        );
        assert_eq!(
            diff, 0,
            "draw_text_display is editor-class — it must keep painting through \
             EditorSurface (the editor dwrite handle) regardless of the chrome \
             font's size"
        );
    }

    /// `Terminal`'s other call site through `EditorSurface` — see
    /// [`win_backend_draw_text_display_does_not_vary_with_chrome_font_size`]'s
    /// doc for why this must stay pixel-identical across chrome font
    /// sizes.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_terminal_does_not_vary_with_chrome_font_size() {
        let term = Terminal {
            id: WidgetId::new("terminal"),
            cells: vec![vec![crate::primitives::terminal::TerminalCell {
                text: "Z".to_string(),
                fg: crate::Color::rgb(220, 220, 220),
                bg: crate::Color::rgb(30, 30, 30),
                bold: false,
                italic: false,
                underline: false,
                dim: false,
                selected: false,
                is_cursor: false,
                cursor_shape: crate::primitives::terminal::TerminalCursorShape::Block,
                cursor_blinking: false,
                is_find_match: false,
                is_find_active: false,
            }]],
            scrollbar: None,
        };
        let diff = chrome_font_diff_pixel_count(
            200,
            40,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                backend.draw_terminal(Rect::new(0.0, 0.0, 200.0, 40.0), &term);
            },
        );
        assert_eq!(
            diff, 0,
            "draw_terminal is editor-class — it must keep painting cell glyphs \
             through EditorSurface (the editor dwrite handle) regardless of the \
             chrome font's size"
        );
    }

    /// `DiffView`'s call site through `EditorSurface` — same contract as
    /// [`win_backend_draw_terminal_does_not_vary_with_chrome_font_size`]
    /// above.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_diff_view_does_not_vary_with_chrome_font_size() {
        let view = crate::primitives::diff_view::DiffView {
            id: WidgetId::new("diff"),
            left: "hello world".to_string(),
            right: "other".to_string(),
            left_label: None,
            right_label: None,
            hunks: vec![crate::primitives::diff_view::DiffHunk {
                left_start: 1,
                right_start: 1,
                rows: vec![crate::primitives::diff_view::DiffRow {
                    left: Some("hello world".to_string()),
                    right: Some("other".to_string()),
                    kind: crate::primitives::diff_view::DiffRowKind::Changed,
                }],
            }],
            mode: crate::primitives::diff_view::DiffMode::SideBySide,
            editability: crate::primitives::diff_view::DiffEditability::ReadOnly,
            scroll_offset: 0,
            focused_pane: crate::primitives::diff_view::DiffPane::Left,
            has_focus: false,
        };
        let diff = chrome_font_diff_pixel_count(
            200,
            80,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                let _ = backend.draw_diff_view(Rect::new(0.0, 0.0, 200.0, 80.0), &view);
            },
        );
        assert_eq!(
            diff, 0,
            "draw_diff_view is editor-class — it must keep painting through \
             EditorSurface (the editor dwrite handle) regardless of the chrome \
             font's size"
        );
    }

    /// `DataTable` builds its own `super::surface::D2dSurface` adapter
    /// from whichever `dwrite` handle `WinBackend::draw_data_table` passes
    /// in, so this call site isn't fixed by `impl PaintSurface for
    /// WinBackend`'s own default — it needs the direct
    /// `chrome_dwrite`-preferring swap this test pins.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_data_table_paints_cell_text_in_the_chrome_fonts_size() {
        let table = crate::DataTable {
            id: WidgetId::new("table"),
            columns: vec![crate::Column {
                title: "col".to_string(),
                width: crate::ColumnWidth::Flex(1.0),
                align: crate::ColumnAlign::Left,
            }],
            rows: vec![crate::DataRow {
                cells: vec![crate::types::StyledText::plain("alpha")],
                decoration: crate::types::Decoration::Normal,
            }],
            selected_idx: None,
            scroll_offset: 0,
            sort: None,
            has_focus: false,
            show_scrollbar: false,
            min_total_width: None,
            h_scroll: 0.0,
            column_overrides: vec![],
            footer: None,
        };
        let diff = chrome_font_diff_pixel_count(
            200,
            120,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                let _ = backend.draw_data_table(Rect::new(0.0, 0.0, 200.0, 120.0), &table, None);
            },
        );
        assert!(
            diff > 0,
            "varying only the chrome font size must repaint different pixels — \
             draw_data_table must paint cell text through chrome_dwrite, not the \
             (unchanged) editor dwrite handle"
        );
    }

    /// `Form`'s `FieldKind::Toolbar` branch reads `chrome_dwrite`
    /// directly (bypassing the inherent `Self::measure_text`/
    /// `Self::draw_text` helpers, which always resolve the editor
    /// handle) rather than through `impl PaintSurface for WinBackend`'s
    /// own (now chrome-resolving) default — see `Self::draw_form`'s doc.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_form_paints_toolbar_button_label_in_the_chrome_fonts_size() {
        let form = Form {
            id: WidgetId::new("settings"),
            fields: vec![crate::FormField {
                id: WidgetId::new("settings:toolbar"),
                label: crate::types::StyledText::default(),
                kind: FieldKind::Toolbar(crate::Toolbar {
                    id: WidgetId::new("settings:toolbar:bar"),
                    buttons: vec![ToolbarButton::Action {
                        id: WidgetId::new("settings:toolbar:refine"),
                        label: "Refine".into(),
                        icon: None,
                        key_hint: None,
                        enabled: true,
                        is_active: false,
                        tooltip: String::new(),
                    }],
                    bg: None,
                    focused_index: None,
                }),
                hint: crate::types::StyledText::default(),
                disabled: false,
                validation: None,
            }],
            focused_field: None,
            scroll_offset: 0,
            has_focus: false,
        };
        let diff = chrome_font_diff_pixel_count(
            200,
            80,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                backend.draw_form(Rect::new(0.0, 0.0, 200.0, 80.0), &form);
            },
        );
        assert!(
            diff > 0,
            "varying only the chrome font size must repaint different pixels — \
             draw_form must paint the toolbar button's label through \
             chrome_dwrite, not the (unchanged) editor dwrite handle"
        );
    }

    /// Same "builds its own adapter from the passed `dwrite`" shape as
    /// `draw_data_table` above.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_toast_overlay_paints_title_in_the_chrome_fonts_size() {
        let stack = ToastOverlay {
            id: WidgetId::new("toast-stack"),
            corner: crate::ToastCorner::BottomRight,
            toasts: vec![crate::Toast {
                id: WidgetId::new("toast"),
                title: "Saved".to_string(),
                body: String::new(),
                severity: crate::ToastSeverity::Info,
                actions: vec![],
                accent: None,
            }],
            focus: None,
        };
        let diff = chrome_font_diff_pixel_count(
            360,
            120,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                let _ = backend.draw_toast_overlay(Rect::new(0.0, 0.0, 360.0, 120.0), &stack);
            },
        );
        assert!(
            diff > 0,
            "varying only the chrome font size must repaint different pixels — \
             draw_toast_overlay must paint the toast's title through \
             chrome_dwrite (WinBackend's own PaintSurface default), not the \
             editor dwrite handle"
        );
    }

    /// Same "builds its own adapter from the passed `dwrite`" shape as
    /// `draw_data_table` above.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_text_input_paints_text_in_the_chrome_fonts_size() {
        let mut ti = crate::TextInput::new(WidgetId::new("ti"));
        ti.lines = vec!["hello world".to_string()];
        ti.has_focus = true;
        let diff = chrome_font_diff_pixel_count(
            200,
            40,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                let _ = backend.draw_text_input(Rect::new(0.0, 0.0, 200.0, 40.0), &ti);
            },
        );
        assert!(
            diff > 0,
            "varying only the chrome font size must repaint different pixels — \
             draw_text_input must paint its text through chrome_dwrite, not the \
             (unchanged) editor dwrite handle"
        );
    }

    /// Same "builds its own adapter from the passed `dwrite`" shape as
    /// `draw_data_table` above. `Backend::draw_tooltip`'s default body
    /// delegates to `Self::draw_tooltip_with_chrome` (see that method's
    /// doc), so this exercises the same `chrome_dwrite`-preferring swap.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_tooltip_paints_text_in_the_chrome_fonts_size() {
        let mut tooltip = Tooltip::new(WidgetId::new("tip"), "Explain this control");
        tooltip.placement = crate::TooltipPlacement::Bottom;
        let anchor = Rect::new(10.0, 4.0, 60.0, 20.0);
        let viewport = Rect::new(0.0, 0.0, 200.0, 120.0);
        let measure = crate::TooltipMeasure::new(160.0, 60.0);
        let layout = tooltip.layout(anchor, viewport, measure, 4.0);
        let diff = chrome_font_diff_pixel_count(
            200,
            120,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                backend.draw_tooltip(&tooltip, &layout);
            },
        );
        assert!(
            diff > 0,
            "varying only the chrome font size must repaint different pixels — \
             draw_tooltip (via draw_tooltip_with_chrome) must paint its text \
             through chrome_dwrite, not the (unchanged) editor dwrite handle"
        );
    }

    /// Same "builds its own adapter from the passed `dwrite`" shape as
    /// `draw_data_table` above.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_completions_paints_item_labels_in_the_chrome_fonts_size() {
        let item = |label: &str| crate::CompletionItem {
            label: crate::types::StyledText::plain(label),
            detail: None,
            documentation: None,
            kind: Default::default(),
            icon: None,
        };
        let completions = Completions {
            id: WidgetId::new("comp"),
            items: vec![item("alpha"), item("beta")],
            selected_idx: 0,
            scroll_offset: 0,
            has_focus: true,
        };
        let viewport = Rect::new(0.0, 0.0, 200.0, 120.0);
        let layout = completions.layout(10.0, 10.0, 16.0, viewport, 120.0, 60.0, |_| {
            crate::CompletionItemMeasure::new(16.0)
        });
        let diff = chrome_font_diff_pixel_count(
            200,
            120,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                backend.draw_completions(&completions, &layout);
            },
        );
        assert!(
            diff > 0,
            "varying only the chrome font size must repaint different pixels — \
             draw_completions must paint item labels through chrome_dwrite, not \
             the (unchanged) editor dwrite handle"
        );
    }

    /// Same "builds its own adapter from the passed `dwrite`" shape as
    /// `draw_data_table` above.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_message_list_paints_row_text_in_the_chrome_fonts_size() {
        let list = MessageList {
            id: WidgetId::new("messages"),
            rows: vec![crate::MessageRow::new(
                "hello world",
                crate::Color::rgb(255, 255, 255),
                0.0,
            )],
            scroll_top: 0,
        };
        let diff = chrome_font_diff_pixel_count(
            200,
            80,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                backend.draw_message_list(Rect::new(0.0, 0.0, 200.0, 80.0), &list);
            },
        );
        assert!(
            diff > 0,
            "varying only the chrome font size must repaint different pixels — \
             draw_message_list must paint row text through chrome_dwrite, not \
             the (unchanged) editor dwrite handle"
        );
    }

    /// Same "builds its own adapter from the passed `dwrite`" shape as
    /// `draw_data_table` above.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_settings_chrome_paints_header_in_the_chrome_fonts_size() {
        let diff = chrome_font_diff_pixel_count(
            200,
            60,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                backend.draw_settings_chrome(
                    Rect::new(0.0, 0.0, 200.0, 60.0),
                    "Settings",
                    "",
                    "Search",
                    false,
                );
            },
        );
        assert!(
            diff > 0,
            "varying only the chrome font size must repaint different pixels — \
             draw_settings_chrome must paint the header text through \
             chrome_dwrite, not the (unchanged) editor dwrite handle"
        );
    }

    // ── no-paint `*_layout` twins: pure measurement, proven via a
    // measured value rather than painted pixels ─────────────────────
    //
    // Each of the four methods below has its own `chrome_dwrite`-
    // preferring swap, independent of the paint-side swap its
    // `draw_*` twin above carries (see each method's own doc for why
    // both must resolve the same handle). `chrome_font_diff_layout`
    // attaches a live chrome/editor `DWrite` pair the same way
    // `chrome_font_diff_pixel_count` does, but returns a measured
    // value from each run instead of a rendered frame — the right
    // oracle for a method that computes geometry without painting
    // anything.

    /// Measurement-twin of `chrome_font_diff_pixel_count` (see that fn's
    /// doc): attaches a live chrome/editor `DWrite` pair — same
    /// discipline, editor font held fixed, only the chrome `ui_font`
    /// varies — and returns whatever `measure` computes from each, for a
    /// `*_layout` twin that measures geometry without painting.
    #[cfg(target_os = "windows")]
    fn chrome_font_diff_layout<T>(
        ui_font_a: &str,
        ui_font_b: &str,
        measure: impl Fn(&WinBackend) -> T,
    ) -> (T, T) {
        use crate::win::testing::HeadlessSurface;

        fn make<T>(ui_font: &str, measure: &dyn Fn(&WinBackend) -> T) -> T {
            let w = 64u32;
            let h = 64u32;
            let surface = HeadlessSurface::new(w, h).expect("create headless surface");
            let mut backend = WinBackend::new();
            backend.set_editor_font(DEFAULT_UI_FONT_FAMILY, 10.0);
            backend.set_ui_font(ui_font);
            backend
                .attach_headless(surface.target().clone(), w, h)
                .expect("attach headless surface");
            measure(&backend)
        }
        (make(ui_font_a, &measure), make(ui_font_b, &measure))
    }

    /// `data_table_layout` must measure a `ColumnWidth::Content` column
    /// against the same `chrome_dwrite`-preferring handle
    /// `Self::draw_data_table` paints with — see that method's doc.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_data_table_layout_measures_a_content_column_in_the_chrome_fonts_size() {
        let table = crate::DataTable {
            id: WidgetId::new("table"),
            columns: vec![
                crate::Column {
                    title: "a rather long column title".to_string(),
                    width: crate::ColumnWidth::Content {
                        min: 0.0,
                        max: 4000.0,
                    },
                    align: crate::ColumnAlign::Left,
                },
                // The layout's last column absorbs any slack up to
                // `viewport_width`, so the measured column must not be last
                // or both runs read back the full viewport width
                // regardless of font.
                crate::Column {
                    title: String::new(),
                    width: crate::ColumnWidth::Fixed(0.0),
                    align: crate::ColumnAlign::Left,
                },
            ],
            rows: vec![],
            selected_idx: None,
            scroll_offset: 0,
            sort: None,
            has_focus: false,
            show_scrollbar: false,
            min_total_width: None,
            h_scroll: 0.0,
            column_overrides: vec![],
            footer: None,
        };
        let (small, big) = chrome_font_diff_layout(
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                // `remaining` (here `viewport_width`, since there's no
                // scrollbar) clamps a `Content` column's measured width
                // — wide enough that even the 40pt run's real measured
                // width never saturates that clamp, or both runs would
                // read back the same clamped-to-`remaining` value
                // regardless of font.
                backend
                    .data_table_layout(Rect::new(0.0, 0.0, 4000.0, 200.0), &table)
                    .columns[0]
                    .width
            },
        );
        assert!(
            big > small * 2.0,
            "data_table_layout must measure the Content column through \
             chrome_dwrite, not the (unchanged) editor dwrite handle: \
             small={small}, big={big}"
        );
    }

    /// `form_layout` must measure a `FieldKind::Toolbar` item against the
    /// same `chrome_dwrite`-preferring handle `Self::draw_form` paints
    /// with — see that method's doc.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_form_layout_measures_a_toolbar_item_in_the_chrome_fonts_size() {
        let form = Form {
            id: WidgetId::new("settings"),
            fields: vec![crate::FormField {
                id: WidgetId::new("settings:toolbar"),
                label: crate::types::StyledText::default(),
                kind: FieldKind::Toolbar(crate::Toolbar {
                    id: WidgetId::new("settings:toolbar:bar"),
                    buttons: vec![ToolbarButton::Action {
                        id: WidgetId::new("settings:toolbar:refine"),
                        label: "Refine".into(),
                        icon: None,
                        key_hint: None,
                        enabled: true,
                        is_active: false,
                        tooltip: String::new(),
                    }],
                    bg: None,
                    focused_index: None,
                }),
                hint: crate::types::StyledText::default(),
                disabled: false,
                validation: None,
            }],
            focused_field: None,
            scroll_offset: 0,
            has_focus: false,
        };
        let (small, big) = chrome_font_diff_layout(
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                let flayout = backend.form_layout(Rect::new(0.0, 0.0, 300.0, 80.0), &form);
                flayout.visible_fields[0].item_bounds[0].1.width
            },
        );
        assert!(
            big > small * 2.0,
            "form_layout must measure the toolbar button through \
             chrome_dwrite, not the (unchanged) editor dwrite handle: \
             small={small}, big={big}"
        );
    }

    /// `toast_stack_layout` must wrap the toast's body against the same
    /// `chrome_dwrite`-preferring handle `Self::draw_toast_overlay`
    /// paints with — see that method's doc.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_toast_stack_layout_wraps_body_in_the_chrome_fonts_size() {
        let stack = ToastOverlay {
            id: WidgetId::new("toast-stack"),
            corner: crate::ToastCorner::BottomRight,
            toasts: vec![crate::Toast {
                id: WidgetId::new("toast"),
                title: "Saved".to_string(),
                body: "one two three four five six seven eight nine ten eleven twelve".to_string(),
                severity: crate::ToastSeverity::Info,
                actions: vec![],
                accent: None,
            }],
            focus: None,
        };
        let (small_h, big_h) = chrome_font_diff_layout(
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                backend
                    .toast_stack_layout(Rect::new(0.0, 0.0, 400.0, 400.0), &stack)
                    .visible_toasts[0]
                    .bounds
                    .height
            },
        );
        assert!(
            big_h > small_h,
            "toast_stack_layout must wrap the toast body through chrome_dwrite, \
             not the (unchanged) editor dwrite handle: small_h={small_h}, \
             big_h={big_h}"
        );
    }

    /// `spinner_layout` must measure the spinner's label against the
    /// same `chrome_dwrite`-preferring handle `Self::draw_spinner` paints
    /// with — see that method's doc.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_spinner_layout_measures_label_in_the_chrome_fonts_size() {
        let spinner = Spinner {
            id: WidgetId::new("spinner"),
            label: "Indexing…".to_string(),
            frame_idx: 0,
            accent: None,
        };
        let (small, big) = chrome_font_diff_layout(
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                backend
                    .spinner_layout(Rect::new(0.0, 0.0, 200.0, 40.0), &spinner)
                    .bounds
                    .width
            },
        );
        assert!(
            big > small * 2.0,
            "spinner_layout must measure the label through chrome_dwrite, not \
             the (unchanged) editor dwrite handle: small={small}, big={big}"
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_status_bar_interactive_paints_segment_text_in_the_chrome_fonts_size() {
        let bar = StatusBar {
            id: WidgetId::new("status"),
            left_segments: vec![crate::primitives::status_bar::StatusBarSegment {
                text: "main.rs".into(),
                fg: crate::types::Color::rgb(255, 255, 255),
                bg: crate::types::Color::rgb(0, 0, 0),
                bold: false,
                action_id: None,
            }],
            right_segments: vec![],
        };
        let interaction = crate::interaction::InteractionState::new();
        let diff = chrome_font_diff_pixel_count(
            300,
            24,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                let _ = backend.draw_status_bar_interactive(
                    Rect::new(0.0, 0.0, 300.0, 24.0),
                    &bar,
                    &interaction,
                );
            },
        );
        assert!(
            diff > 0,
            "#1266: draw_status_bar_interactive must paint segment text through \
             ChromeSurface (chrome_dwrite), not WinBackend's own PaintSurface impl \
             (the editor dwrite handle)"
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_activity_bar_paints_icon_glyphs_in_the_chrome_fonts_size() {
        // the icon glyph always paints at a fixed, VS-Code-parity
        // *size* (`ActivityBarStyle::resolved_icon_size_px`), independent
        // of whichever `dwrite` handle's own point size is passed in —
        // see `win::activity_bar`'s module doc — so varying only the
        // chrome *size* (this test's siblings' approach) would prove
        // nothing here even post-change. `win::activity_bar::draw_activity_bar`
        // rebuilds its icon-sized `DWrite` via `dwrite.with_size`, which
        // preserves `dwrite`'s own *family* — so varying the chrome
        // *family* instead (holding the editor font fixed) still
        // distinguishes "paints through chrome_dwrite" from "paints
        // through the editor dwrite handle regardless of `set_ui_font`".
        let bar = ActivityBar {
            id: WidgetId::new("activity"),
            top_items: vec![crate::primitives::activity_bar::ActivityItem {
                id: WidgetId::new("activity:explorer"),
                icon: crate::types::Icon::new("", "E"),
                tooltip: String::new(),
                is_active: false,
                is_keyboard_selected: false,
            }],
            bottom_items: Vec::new(),
            active_accent: None,
            selection_bg: None,
            is_keyboard_focused: false,
        };
        let diff =
            chrome_font_diff_pixel_count(60, 200, "Segoe UI 12", "Courier New 12", |backend| {
                let _ = backend.draw_activity_bar(Rect::new(0.0, 0.0, 60.0, 200.0), &bar, None);
            });
        assert!(
            diff > 0,
            "#1266: draw_activity_bar must paint icon glyphs through chrome_dwrite (whose \
             family — not its point size, fixed by #1157's icon-size override — this test \
             varies), not the (unchanged) editor dwrite handle"
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_toolbar_interactive_paints_button_labels_in_the_chrome_fonts_size() {
        let bar = crate::primitives::toolbar::Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![ToolbarButton::Action {
                id: WidgetId::new("tb:on"),
                label: "On".into(),
                icon: None,
                key_hint: None,
                enabled: true,
                is_active: false,
                tooltip: String::new(),
            }],
            bg: None,
            focused_index: None,
        };
        let interaction = crate::interaction::InteractionState::new();
        let diff = chrome_font_diff_pixel_count(
            100,
            32,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                let _ = backend.draw_toolbar_interactive(
                    Rect::new(0.0, 0.0, 100.0, 32.0),
                    &bar,
                    &interaction,
                );
            },
        );
        assert!(
            diff > 0,
            "#1266: draw_toolbar_interactive must paint button labels through \
             chrome_dwrite, not the (unchanged) editor dwrite handle"
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` — issue #823
    fn win_backend_draw_tab_bar_paints_tab_labels_in_the_chrome_fonts_size() {
        let bar = TabBar {
            id: WidgetId::new("tabs"),
            tabs: vec![crate::primitives::tab_bar::TabItem {
                label: "main.rs".into(),
                is_active: true,
                is_dirty: false,
                is_preview: false,
                is_closable: true,
            }],
            scroll_offset: 0,
            right_segments: Vec::new(),
            active_accent: None,
            show_tab_close: true,
            compact: false,
        };
        let diff = chrome_font_diff_pixel_count(
            300,
            30,
            &format!("{DEFAULT_UI_FONT_FAMILY} 6.0"),
            &format!("{DEFAULT_UI_FONT_FAMILY} 40.0"),
            |backend| {
                let _ = backend.draw_tab_bar(Rect::new(0.0, 0.0, 300.0, 30.0), &bar, None);
            },
        );
        assert!(
            diff > 0,
            "#1266: draw_tab_bar must paint tab labels through chrome_dwrite, not the \
             (unchanged) editor dwrite handle"
        );
    }

    /// `surface_draw_icon_glyph` forwards to `surface_draw_text_run`
    /// on this backend (DirectWrite's font-fallback cascade is already
    /// baked into every `IDWriteTextFormat` — see the trait override's
    /// doc) — this proves that forward actually paints real ink rather
    /// than silently no-opping. Win-GUI twin of
    /// `gtk_backend_paint_surface_draw_icon_glyph_paints_real_ink`.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_paint_surface_draw_icon_glyph_paints_real_ink() {
        use crate::types::Color;
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 40;
        const H: u32 = 40;

        let background = cleared_frame_background(W, H);
        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let white = Color::rgb(255, 255, 255);
        assert_ne!(
            background,
            (white.r, white.g, white.b),
            "the glyph colour must differ from the frame's clear colour, or \
             'it painted ink' is unprovable"
        );
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.surface_draw_icon_glyph(Rect::new(2.0, 2.0, 30.0, 30.0), "i", white);
        backend.end_frame();

        // Pixels the glyph moved off `begin_frame`'s clear colour — not a
        // channel sum against black, which every cleared pixel would pass
        // (see `cleared_frame_background`).
        let mut ink = 0u32;
        for y in 0..H {
            for x in 0..W {
                let px = surface.pixel_at(x, y);
                if (px.r, px.g, px.b) != background {
                    ink += 1;
                }
            }
        }
        assert!(
            ink > 0,
            "surface_draw_icon_glyph must paint real ink through the fallback-baked \
             DirectWrite text format, not silently no-op"
        );
    }

    /// Exercise every remaining `PaintSurface` method at least once end-to-end
    /// (frame lifecycle, measurement, stroke, line, clip push/pop, text run,
    /// rounded rect, alpha fill, role text, icon glyph, image) so an
    /// implementation bug (wrong arg order, a missing surface guard, a panic
    /// inside the `todo!()` split) fails a test instead of shipping silently.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_paint_surface_verbs_do_not_panic() {
        use crate::types::Color;
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 64;
        const H: u32 = 64;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let viewport = Viewport::new(W as f32, H as f32, 1.0);
        backend.surface_begin_frame(viewport);
        assert_eq!(
            backend.surface_viewport(),
            viewport,
            "surface_viewport must forward to Backend::begin_frame's stored value"
        );
        assert_eq!(
            backend.surface_line_height(),
            Backend::line_height(&backend)
        );
        assert_eq!(backend.surface_char_width(), Backend::char_width(&backend));

        let blue = Color::rgb(20, 20, 200);
        let white = Color::rgb(255, 255, 255);
        backend.surface_stroke_rect(Rect::new(0.0, 0.0, 40.0, 40.0), blue, 2.0);
        backend.surface_draw_line(Point::new(0.0, 0.0), Point::new(40.0, 40.0), blue, 1.0);
        backend.surface_push_clip(Rect::new(0.0, 0.0, 40.0, 40.0));
        backend.surface_draw_text_run(Rect::new(2.0, 2.0, 30.0, 10.0), "hi", white);
        backend.surface_pop_clip();
        // The four new verbs, exercised here too (pixel-precision
        // coverage of each lives in the dedicated tests above).
        backend.surface_fill_rounded_rect(Rect::new(44.0, 0.0, 16.0, 16.0), 4.0, blue);
        backend.surface_fill_rect_alpha(Rect::new(44.0, 20.0, 16.0, 16.0), blue, 0.5);
        backend.surface_draw_text_run_with_role(
            Rect::new(2.0, 14.0, 30.0, 10.0),
            "hi",
            white,
            crate::FontRole::Chrome,
            false,
        );
        backend.surface_draw_icon_glyph(Rect::new(2.0, 26.0, 10.0, 10.0), "i", white);

        let (w, h) = backend.surface_measure_text("hi");
        assert!(
            w > 0.0 && h > 0.0,
            "surface_measure_text must report a nonzero footprint for non-empty \
             text: got ({w}, {h})"
        );

        let image = crate::primitives::image::Image {
            id: WidgetId::new("test:native-surface-image"),
            source: crate::primitives::image::ImageSource::Bytes(Vec::new()),
            intrinsic_size: Some((8, 8)),
            fit: crate::primitives::image::ImageFit::Contain,
            fallback_text: "[i]".to_string(),
        };
        // Direct2D bitmap decode fails on empty bytes on the real path
        // too — this call only needs to prove it reaches the same code
        // `Backend::draw_image` does, not any particular decode outcome.
        let _ = backend.surface_draw_image(Rect::new(0.0, 40.0, 8.0, 8.0), &image);

        backend.surface_end_frame();
    }

    // ── #810: draw_chart real-pixel driver tests ──────────────────────────────
    //
    // Drive the real `Backend::draw_chart` → `primitives::chart::paint` path
    // end to end, the same shape `set_theme_reaches_the_find_replace` above uses.

    #[cfg(target_os = "windows")]
    fn chart_line_fixture(data: Vec<f64>) -> crate::primitives::chart::Chart {
        use crate::primitives::chart::{ChartKind, Series};
        crate::primitives::chart::Chart {
            id: WidgetId::new("chart"),
            kind: ChartKind::Line,
            series: vec![Series {
                label: "A".into(),
                data,
                color: None,
                fill: false,
            }],
            x_label: None,
            y_label: None,
            y_range: None,
            x_range: None,
            show_legend: false,
            y_ticks: Some(0),
            x_ticks: Some(0),
            show_grid: false,
        }
    }

    /// Paint↔hover round trip: a nearest-point lookup at a data point's
    /// resolved screen position must resolve back to that point, and
    /// painting with it as `hovered_point` must not panic.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_chart_paint_and_nearest_point_round_trip() {
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 200;
        const H: u32 = 100;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let chart = chart_line_fixture(vec![1.0, 5.0, 2.0, 8.0, 3.0]);
        let rect = Rect::new(0.0, 0.0, W as f32, H as f32);

        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        let layout = backend.draw_chart(rect, &chart, None, None);
        backend.end_frame();

        assert_eq!(layout.data_point_positions.len(), 5);
        for &(si, di, x, y) in &layout.data_point_positions {
            let nearest = layout.nearest_point(x, y, 1.0);
            assert_eq!(nearest, Some((si, di)));
        }

        // Painting with a hover marker + crosshair must not panic.
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.draw_chart(rect, &chart, Some((0, 0)), Some(1.0));
        backend.end_frame();
    }

    /// No-paint layout must agree byte-for-byte with what `draw_chart`
    /// painted — the same contract `primitives::form::paint` documents
    /// ("paint and hit-test can never disagree").
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_chart_no_paint_layout_matches_paint_layout() {
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 200;
        const H: u32 = 100;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let chart = chart_line_fixture(vec![1.0, 4.0, 2.0]);
        let rect = Rect::new(0.0, 0.0, W as f32, H as f32);

        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        let painted = backend.draw_chart(rect, &chart, None, None);
        backend.end_frame();

        let no_paint = backend.chart_layout(rect, &chart);
        assert_eq!(painted, no_paint);
    }

    /// `win::chart::draw_chart` never clipped before #810 unified all three
    /// backends onto the shared `primitives::chart::paint`, which always brackets
    /// its body in `surface_push_clip`/`surface_pop_clip`. Mirrors
    /// `gtk::backend::tests::gtk_backend_draw_chart_hover_marker_does_not_escape_chart_rect`
    /// pixel-for-pixel (same fixture, same geometry).
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_chart_hover_marker_does_not_escape_chart_rect() {
        use crate::primitives::chart::{ChartKind, Series};
        use crate::win::testing::HeadlessSurface;
        use crate::Color;

        // origin=1.0 at index 0 → top edge; 0.0 at index 1 → bottom
        // edge. n=2 → index 0's x is the plot area's left edge. So data
        // point (0, 0) sits exactly at the chart's top-left corner.
        let chart = crate::primitives::chart::Chart {
            id: WidgetId::new("chart"),
            kind: ChartKind::Sparkline,
            series: vec![Series {
                label: "a".into(),
                data: vec![10.0, 0.0],
                color: None,
                fill: false,
            }],
            x_label: None,
            y_label: None,
            y_range: Some((0.0, 10.0)),
            x_range: None,
            show_legend: false,
            y_ticks: Some(0),
            x_ticks: Some(0),
            show_grid: false,
        };

        const CANVAS_W: u32 = 40;
        const CANVAS_H: u32 = 40;
        let sentinel = Color::rgb(0, 0, 0);
        let (chart_x, chart_y, chart_w, chart_h) = (10.0_f32, 10.0_f32, 20.0_f32, 20.0_f32);

        let surface = HeadlessSurface::new(CANVAS_W, CANVAS_H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), CANVAS_W, CANVAS_H)
            .expect("attach headless surface");

        backend.begin_frame(Viewport::new(CANVAS_W as f32, CANVAS_H as f32, 1.0));
        backend.surface_fill_rect(
            Rect::new(0.0, 0.0, CANVAS_W as f32, CANVAS_H as f32),
            sentinel,
        );
        backend.draw_chart(
            Rect::new(chart_x, chart_y, chart_w, chart_h),
            &chart,
            Some((0, 0)),
            None,
        );
        backend.end_frame();

        // Inside the marker's 8-unit-radius ring, centred at the chart's
        // own top-left corner (10, 10), but outside the chart's rect.
        let px = surface.pixel_at(5, 5);
        assert_eq!(
            (px.r, px.g, px.b),
            (sentinel.r, sentinel.g, sentinel.b),
            "hover marker must not paint outside the chart's own rect",
        );
    }

    /// `WinBackend::surface_measure_text_styled`'s bold override must ask
    /// DirectWrite for a wider bold measurement, not just a synthetic bonus.
    /// Mirrors `gtk::backend::tests::gtk_backend_draw_status_bar_bold_segment_measures_wider`:
    /// paints the same text through the real `Backend::draw_status_bar` path once
    /// bold, once not, and asserts the bold segment's resolved (painted) width is
    /// strictly wider.
    ///
    /// **Both the editor and chrome fonts are overridden on purpose — don't drop
    /// either call.** `PaintSurface::surface_measure_text_styled` measures through
    /// `self.dwrite` (the editor font); `Backend::draw_status_bar_interactive`
    /// measures/paints through `chrome_dwrite` instead. Both must be set to the
    /// *same* `FONT`/`SIZE_PT` or the comparison would drift.
    ///
    /// `DEFAULT_EDITOR_FONT_FAMILY` (`"Consolas"`) is monospaced and shares **one
    /// advance width across every weight** by design, so `measure_text_styled(t, true)`
    /// and `measure_text_styled(t, false)` return identical widths there regardless
    /// of how faithfully the `bold` flag is threaded through. This test drives a
    /// *proportional* font (`"Segoe UI"` — the `DEFAULT_UI_FONT_FAMILY`) where
    /// "bold is wider" is a property the font can actually express.
    ///
    /// This chrome primitive measures through `chrome_dwrite`, so the fixture sets
    /// `set_ui_font` to match the bold-override font.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_status_bar_bold_segment_measures_wider() {
        // `DWrite` (and `DEFAULT_UI_FONT_FAMILY` below) come from this
        // module's own `use super::*` — both are `cfg(target_os =
        // "windows")` items, same as this test.
        use crate::primitives::status_bar::{StatusBar, StatusBarSegment};
        use crate::win::testing::HeadlessSurface;
        use crate::Color;

        const W: u32 = 400;
        const H: u32 = 20;
        const TEXT: &str = "READY";
        // Proportional, and present on every supported Windows — see this
        // test's doc for why the default (monospaced) editor font cannot
        // express the property under test.
        const FONT: &str = DEFAULT_UI_FONT_FAMILY;
        // Deliberately larger than `DEFAULT_UI_FONT_SIZE_PT`: the
        // bold/regular advance-width delta scales with the em size, so a
        // bigger size keeps the difference comfortably above float noise.
        const SIZE_PT: f32 = 20.0;

        // Fixture guard: if DirectWrite itself reports the same width for
        // both weights of `FONT`, the assertion below would be
        // unsatisfiable and its failure would say nothing about the
        // override under test. Fail with a message that names *that*
        // instead.
        let (probe, _, _) = DWrite::new(FONT, SIZE_PT, None).expect("create probe DWrite");
        let (probe_regular, _) = probe
            .measure_text_styled(TEXT, false)
            .expect("measure regular");
        let (probe_bold, _) = probe.measure_text_styled(TEXT, true).expect("measure bold");
        assert!(
            probe_bold > probe_regular,
            "test fixture bug: `{FONT}` must measure bold text wider than regular for this \
             assertion to mean anything (regular={probe_regular}, bold={probe_bold}) — pick a \
             proportional font that distinguishes weights"
        );

        let width_for = |bold: bool| {
            let surface = HeadlessSurface::new(W, H).expect("create headless surface");
            let mut backend = WinBackend::new();
            // Must precede `attach_headless`: that's where the
            // `IDWriteTextFormat` pair `self.dwrite` wraps is built from
            // `editor_font_family`/`editor_font_size_pt` (see
            // `set_editor_font`'s doc — a live surface doesn't rebuild
            // them on a later font change).
            backend.set_editor_font(FONT, SIZE_PT);
            // `draw_status_bar_interactive` now measures/paints
            // through `chrome_dwrite`, not `self.dwrite` — see this
            // test's own doc. Set to the same `FONT`/`SIZE_PT` as the
            // editor font above (and the probe `DWrite` instance), or
            // the final `assert_eq!` below would compare against the
            // wrong font entirely.
            backend.set_ui_font(&format!("{FONT} {SIZE_PT}"));
            backend
                .attach_headless(surface.target().clone(), W, H)
                .expect("attach headless surface");
            backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
            let layout = backend.draw_status_bar_interactive(
                Rect::new(0.0, 0.0, W as f32, H as f32),
                &StatusBar {
                    id: WidgetId::new("test:status-bar"),
                    left_segments: vec![StatusBarSegment {
                        text: TEXT.into(),
                        fg: Color::rgb(255, 255, 255),
                        bg: Color::rgb(0, 0, 0),
                        bold,
                        action_id: None,
                    }],
                    right_segments: vec![],
                },
                &crate::InteractionState::new(),
            );
            backend.end_frame();
            layout.visible_segments[0].bounds.width
        };

        let regular_width = width_for(false);
        let bold_width = width_for(true);
        assert!(
            bold_width > regular_width,
            "a bold segment must measure (and paint) wider than the same text non-bold: \
             regular={regular_width}, bold={bold_width}"
        );
        // …and the widths that reached the layout are the *same* ones
        // DirectWrite reports for each weight — proves the override
        // forwards to `measure_text_styled` rather than merely producing
        // some pair of different numbers.
        //
        // Issue #1155: a segment's `bounds` is its measured text width
        // plus `PIXEL_SEGMENT_PADDING` on *both* sides (pixel backends
        // call `StatusBar::layout_padded`), so the comparison is against
        // the probe widths grown by that known, constant amount — the
        // per-weight *delta* this test is really about is unaffected by it.
        const PAD: f32 = 2.0 * crate::primitives::status_bar::PIXEL_SEGMENT_PADDING;
        assert_eq!(
            (regular_width, bold_width),
            (probe_regular + PAD, probe_bold + PAD),
            "resolved segment widths must match DirectWrite's own per-weight measurement \
             plus #1155's per-segment padding"
        );
    }

    // ── #929: register_font_from_memory / set_nerd_font_fallback ────────────

    /// Garbage bytes aren't a font Core Graphics/DirectWrite can parse —
    /// `register_font_from_memory` must report that as `None` rather than
    /// panicking or returning a bogus family list. Doesn't need a real
    /// font file fixture (which this suite has none of), so it covers the
    /// one path that's fully exercisable without one.
    #[cfg(target_os = "windows")]
    #[test]
    fn register_font_from_memory_rejects_bytes_that_are_not_a_font() {
        let mut backend = WinBackend::new();
        let garbage = [0u8; 64];
        assert!(
            backend.register_font_from_memory(&garbage).is_none(),
            "64 zero bytes are not a parseable font — must report None, not a fabricated family"
        );
    }

    /// `register_font_from_memory` must copy `bytes` into self-owned storage
    /// *before* the caller's buffer can be dropped, not after — otherwise a
    /// caller passing a short-lived local (the shape this trait method's own doc
    /// explicitly permits) leaves DirectWrite holding a dangling pointer. This
    /// asserts the fix: `bytes` is copied into `registered_font_bytes` before
    /// the caller's buffer goes out of scope, and that copy is a distinct
    /// allocation from the caller's.
    #[cfg(target_os = "windows")]
    #[test]
    fn register_font_from_memory_copies_bytes_before_the_callers_buffer_can_be_dropped() {
        let mut backend = WinBackend::new();
        {
            // Scoped so `transient` is dropped at the end of this block,
            // before any assertion below runs — mirroring the exact
            // "call once from setup(), then drop the source buffer"
            // shape the trait doc permits.
            let transient = vec![0xABu8; 64];
            let _ = backend.register_font_from_memory(&transient);
        }
        assert_eq!(
            backend.registered_font_bytes.len(),
            1,
            "the call must copy bytes into backend-owned storage regardless of whether \
             registration itself succeeds"
        );
        assert_eq!(
            backend.registered_font_bytes[0],
            vec![0xABu8; 64],
            "the stored copy must match what was passed in, read back from backend-owned \
             memory rather than the (by now dropped) caller buffer"
        );
    }

    /// `set_nerd_font_fallback` works with no prior
    /// `register_font_from_memory` call at all — it should resolve
    /// `family` against the *system* font collection (see
    /// `crate::win::text::build_nerd_font_fallback`'s doc), which is the
    /// shape an app pointing at an already-installed Nerd Font uses.
    /// Asserts the whole pipeline (`set_nerd_font_fallback` ->
    /// `attach_headless` -> `DWrite::new` baking the fallback into both
    /// `IDWriteTextFormat`s -> a real paint) survives end to end and
    /// keeps painting ordinary text correctly — the regression this test
    /// guards is "wiring a fallback breaks normal (non-fallback) text",
    /// not "the fallback glyph is pixel-identical to some reference",
    /// which would need an embedded custom font fixture this suite
    /// doesn't have.
    #[cfg(target_os = "windows")]
    #[test]
    fn set_nerd_font_fallback_against_the_system_collection_does_not_break_normal_paint() {
        use crate::win::testing::HeadlessSurface;
        use crate::Color;

        const W: u32 = 200;
        const H: u32 = 30;
        const TEXT: &str = "OK";

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        // "Segoe UI Symbol" ships on every supported Windows version and
        // is a real, distinct family from the default UI font — a
        // plausible stand-in for an app-installed Nerd Font pointed at
        // via a plain family name with no `register_font_from_memory`
        // call. Must precede `attach_headless`, same "bake at surface
        // construction" convention as `set_editor_font`/`set_ui_font`.
        backend.set_nerd_font_fallback("Segoe UI Symbol");
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach_headless must still succeed with a fallback wired in");

        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        let sentinel = Color::rgb(0, 0, 0);
        backend.surface_fill_rect(Rect::new(0.0, 0.0, W as f32, H as f32), sentinel);
        backend.draw_text(
            TEXT,
            Rect::new(4.0, 4.0, W as f32 - 8.0, H as f32 - 8.0),
            Color::rgb(255, 255, 255),
        );
        backend.end_frame();

        let (w, h) = backend.measure_text(TEXT);
        assert!(
            w > 0.0 && h > 0.0,
            "ordinary text must still measure to a real, positive size with a fallback wired \
             in (w={w}, h={h})"
        );

        // At least one non-background pixel landed inside the paint
        // target — a coarse but real proof that `draw_text` actually
        // painted glyphs rather than silently no-op'ing once a fallback
        // was attached.
        let mut painted_something = false;
        'outer: for y in 0..H {
            for x in 0..W {
                let px = surface.pixel_at(x, y);
                if (px.r, px.g, px.b) != (sentinel.r, sentinel.g, sentinel.b) {
                    painted_something = true;
                    break 'outer;
                }
            }
        }
        assert!(
            painted_something,
            "draw_text must paint something other than the sentinel background"
        );
    }

    // ── bundled codicon font self-registration ───────────────────────────

    /// `WinBackend::new` self-registers the bundled codicon font and
    /// seeds a codicon-only `nerd_font_fallback` before any app code
    /// runs — no app configuration required.
    #[cfg(target_os = "windows")]
    #[test]
    fn new_self_registers_codicon_and_seeds_a_fallback() {
        let backend = WinBackend::new();
        assert!(
            backend.codicon_font_collection.is_some(),
            "WinBackend::new() must self-register the bundled codicon font"
        );
        assert!(
            backend.nerd_font_fallback.is_some(),
            "a codicon-only fallback must be seeded even before any app \
             set_nerd_font_fallback call"
        );
    }

    /// `nerd_fonts_enabled` defaults to `true` on this backend — see
    /// the field's own doc for why that default differs from TUI's.
    #[test]
    fn nerd_fonts_enabled_defaults_to_true() {
        let backend = WinBackend::new();
        assert!(backend.nerd_fonts_enabled());
    }

    /// `set_nerd_font_fallback` must not drop the bundled codicon
    /// mapping `Self::new` seeded — `build_nerd_font_fallback_multi`
    /// rebuilds the whole `IDWriteFontFallback` from scratch each call
    /// (DirectWrite text formats carry exactly one), so this guards
    /// against a future edit that narrows it back down to just the
    /// app's own family. Painting the codicon close glyph through a
    /// `DWrite` built *after* an app `set_nerd_font_fallback` call must
    /// still produce real ink, not tofu.
    #[cfg(target_os = "windows")]
    #[test]
    fn set_nerd_font_fallback_keeps_the_codicon_mapping() {
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 40;
        const H: u32 = 40;
        const BG: crate::Color = crate::Color::rgb(10, 20, 30);

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend.set_nerd_font_fallback("Segoe UI Symbol");
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach_headless");

        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.surface_fill_rect(Rect::new(0.0, 0.0, W as f32, H as f32), BG);
        let glyph = crate::codicon::CLOSE.to_string();
        backend.draw_text(
            &glyph,
            Rect::new(4.0, 4.0, W as f32 - 8.0, H as f32 - 8.0),
            crate::Color::rgb(220, 40, 40),
        );
        backend.end_frame();

        let mut painted_something = false;
        'outer: for y in 0..H {
            for x in 0..W {
                let px = surface.pixel_at(x, y);
                if (px.r, px.g, px.b) != (BG.r, BG.g, BG.b) {
                    painted_something = true;
                    break 'outer;
                }
            }
        }
        assert!(
            painted_something,
            "the codicon close glyph must still paint real ink after an app \
             set_nerd_font_fallback call, not just before one"
        );
    }

    // ── #1024: has_font_family ───────────────────────────────────────────────

    /// "Segoe UI" ships on every supported Windows version — a real
    /// system-installed family that `has_font_family` must report as
    /// present via `FindFamilyName`, not just "resolved to something".
    #[cfg(target_os = "windows")]
    #[test]
    fn has_font_family_finds_a_real_system_family() {
        let backend = WinBackend::new();
        assert_eq!(
            backend.has_font_family("Segoe UI"),
            Some(true),
            "Segoe UI ships on every supported Windows version"
        );
    }

    /// A family name nothing is installed under must report `Some(false)`
    /// — a successful DirectWrite lookup that found nothing, not `None`
    /// ("don't know"). Conflating the two would be exactly the bug this
    /// issue's `Backend::has_font_family` doc warns callers not to make.
    #[cfg(target_os = "windows")]
    #[test]
    fn has_font_family_is_some_false_for_a_name_nothing_is_installed_under() {
        let backend = WinBackend::new();
        assert_eq!(
            backend.has_font_family("Definitely Not A Real Font Family Quadraui 1024"),
            Some(false)
        );
    }

    // ── #810: draw_text_display real-pixel driver tests ───────────────────────
    //
    // Drive the real `Backend::draw_text_display` →
    // `primitives::text_display::paint` path end to end.

    #[cfg(target_os = "windows")]
    fn td_line(text: &str) -> crate::primitives::text_display::TextDisplayLine {
        crate::primitives::text_display::TextDisplayLine {
            spans: vec![crate::types::StyledSpan::plain(text)],
            decoration: crate::types::Decoration::Normal,
            timestamp: None,
        }
    }

    #[cfg(target_os = "windows")]
    fn make_td(lines: usize, show_scrollbar: bool) -> crate::primitives::text_display::TextDisplay {
        crate::primitives::text_display::TextDisplay {
            id: WidgetId::new("td"),
            lines: (0..lines).map(|i| td_line(&format!("ln{i}"))).collect(),
            scroll_offset: 0,
            auto_scroll: false,
            max_lines: 0,
            has_focus: false,
            title: None,
            show_scrollbar,
        }
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_text_display_background_fills_theme_background() {
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 240;
        const H: u32 = 160;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let td = make_td(0, false);
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.draw_text_display(Rect::new(0.0, 0.0, W as f32, H as f32), &td);
        backend.end_frame();

        let theme = Theme::default();
        let px = surface.pixel_at(W / 2, H / 2);
        assert_eq!(
            (px.r, px.g, px.b),
            (theme.background.r, theme.background.g, theme.background.b)
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_text_display_scrollbar_gutter_and_thumb_paint() {
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 240;
        const H: u32 = 160;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let td = make_td(100, true);
        let rect = Rect::new(0.0, 0.0, W as f32, H as f32);
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.draw_text_display(rect, &td);
        let layout = backend.text_display_layout(rect, &td);
        backend.end_frame();

        let theme = Theme::default();

        let gutter = layout.scrollbar_bounds.expect("gutter present");
        let probe_x = (gutter.x + gutter.width / 2.0) as u32;
        let probe_y = (gutter.y + gutter.height - 2.0) as u32;
        let px = surface.pixel_at(probe_x, probe_y);
        assert_eq!(
            (px.r, px.g, px.b),
            (
                theme.scrollbar_track.r,
                theme.scrollbar_track.g,
                theme.scrollbar_track.b
            )
        );

        let thumb = layout.thumb_bounds.expect("thumb present");
        let probe_x = (thumb.x + thumb.width / 2.0) as u32;
        let probe_y = (thumb.y + thumb.height / 2.0) as u32;
        let px = surface.pixel_at(probe_x, probe_y);
        assert_eq!(
            (px.r, px.g, px.b),
            (
                theme.scrollbar_thumb.r,
                theme.scrollbar_thumb.g,
                theme.scrollbar_thumb.b
            )
        );
    }

    /// Paint at a non-zero rect origin with a title row present, then
    /// round-trip an absolute click the way a real host does — layout helpers
    /// must return coords in the same frame across backends.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_text_display_layout_hit_test_resolves_lines_at_nonzero_origin() {
        use crate::primitives::text_display::TextDisplayHit;
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 240;
        const H: u32 = 160;
        const LINE_HEIGHT: f32 = 16.0;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let mut td = make_td(20, false);
        td.title = Some(crate::types::StyledText::plain("Logs"));

        let rect_x = 9.0_f32;
        let rect_y = 17.0_f32;
        let rect = Rect::new(rect_x, rect_y, W as f32 - rect_x, H as f32 - rect_y);
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.draw_text_display(rect, &td);
        let layout = backend.text_display_layout(rect, &td);
        backend.end_frame();

        let body_y = rect_y + LINE_HEIGHT;
        let vis = &layout.visible_lines[0];
        assert_eq!(
            vis.bounds.y, 0.0,
            "visible_lines bounds.y must be body-local"
        );

        let abs_x = rect_x + vis.bounds.x + vis.bounds.width * 0.5;
        let abs_y = body_y + vis.bounds.y + vis.bounds.height * 0.5;
        let local_x = abs_x - rect_x;
        let local_y = abs_y - body_y;
        match layout.hit_test(local_x, local_y) {
            TextDisplayHit::Line(idx) => assert_eq!(idx, vis.line_idx),
            other => panic!("expected Line, got {:?}", other),
        }
    }

    /// No-paint layout must agree byte-for-byte with what
    /// `draw_text_display` painted.
    #[cfg(target_os = "windows")]
    #[test]
    fn win_backend_draw_text_display_no_paint_layout_matches_paint_layout() {
        use crate::win::testing::HeadlessSurface;

        const W: u32 = 240;
        const H: u32 = 160;

        let surface = HeadlessSurface::new(W, H).expect("create headless surface");
        let mut backend = WinBackend::new();
        backend
            .attach_headless(surface.target().clone(), W, H)
            .expect("attach headless surface");

        let td = make_td(30, true);
        let rect = Rect::new(0.0, 0.0, W as f32, H as f32);
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.draw_text_display(rect, &td);
        let painted = backend.text_display_layout(rect, &td);
        backend.end_frame();

        let no_paint = backend.text_display_layout(rect, &td);
        assert_eq!(painted, no_paint);
    }

    // ─── Issue #924: no-surface fallback survives instead of panicking ────────

    fn sample_minimap() -> crate::primitives::minimap::Minimap {
        crate::primitives::minimap::Minimap {
            id: WidgetId::new("minimap"),
            lines: (0..40)
                .map(|i| crate::primitives::minimap::MinimapLine {
                    text: format!("line {i}"),
                    line_idx: i,
                })
                .collect(),
            syntax_spans: Vec::new(),
            visible_row_start: 0,
            visible_row_count: 10,
            total_buffer_lines: 40,
        }
    }

    fn sample_panel() -> Panel {
        Panel {
            id: WidgetId::new("panel"),
            title: None,
            actions: Vec::new(),
            accent: None,
            collapsed: false,
        }
    }

    /// A `WinBackend` that has never had `attach_surface`/`attach_headless`
    /// called — the same surface-less state a fresh `WinBackend::new()` starts in
    /// and the state `end_frame` drops back to after a device-lost `EndDraw`
    /// failure — must survive a full `begin_frame` -> a spread of draw/layout/paint
    /// calls -> `end_frame`, without panicking. No `target_os = "windows"` gate: the
    /// whole point is that this degrades instead of aborting on every host.
    #[test]
    fn win_backend_does_not_panic_with_no_surface_attached_across_a_full_frame() {
        let mut backend = WinBackend::new();
        let viewport = Viewport::new(400.0, 300.0, 1.0);
        Backend::begin_frame(&mut backend, viewport);

        let rect = Rect::new(0.0, 0.0, 200.0, 100.0);

        // `()` category. None of these types derive `Default`, so build
        // each with an empty/idle content set instead.
        let msv = MultiSectionView {
            id: WidgetId::new("msv"),
            sections: Vec::new(),
            active_section: None,
            axis: crate::primitives::multi_section_view::Axis::Vertical,
            allow_resize: false,
            allow_collapse: false,
            scroll_mode: crate::primitives::multi_section_view::ScrollMode::PerSection,
            has_focus: false,
            panel_scroll: 0.0,
        };
        backend.draw_multi_section_view(rect, &msv);

        // `Vec<ActivityBarRowHit>` category.
        let activity_bar = ActivityBar {
            id: WidgetId::new("activity-bar"),
            top_items: Vec::new(),
            bottom_items: Vec::new(),
            active_accent: None,
            selection_bg: None,
            is_keyboard_focused: false,
        };
        let _ = backend.draw_activity_bar(rect, &activity_bar, None);

        // `TabBarHits`/`TabBarLayout` category (nominal-measurer
        // fallback).
        #[allow(deprecated)]
        {
            let tab_bar = TabBar {
                id: WidgetId::new("tab-bar"),
                tabs: Vec::new(),
                scroll_offset: 0,
                right_segments: Vec::new(),
                active_accent: None,
                show_tab_close: false,
                compact: false,
            };
            let _ = backend.draw_tab_bar(rect, &tab_bar, None);
        }

        // `ToolbarLayout` category (nominal-measurer fallback via
        // `measure_button`).
        let toolbar = crate::primitives::toolbar::Toolbar {
            id: WidgetId::new("toolbar"),
            buttons: Vec::new(),
            bg: None,
            focused_index: None,
        };
        let interaction = crate::interaction::InteractionState::default();
        let _ = backend.draw_toolbar_interactive(rect, &toolbar, &interaction);

        // `PanelLayout` category (pure geometry, no measurer).
        let panel = sample_panel();
        let _ = backend.draw_panel(rect, &panel);

        // `MinimapPaintResult` category (`painted: false`, real layout).
        let minimap = sample_minimap();
        let _ = backend.draw_minimap(rect, &minimap);

        // `ImagePaintResult`/`EditorPaintResult` categories — trivial,
        // fixed fallback values (`Unsupported` / `::default()`), no
        // fixture needed to exercise the code path meaningfully; covered
        // by inspection, not repeated here.

        // `PaintSurface` measurement category (nominal char-width
        // estimate).
        let _ = PaintSurface::surface_measure_text(&backend, "hello");
        let _ = PaintSurface::surface_measure_text_styled(&backend, "hello", true);

        Backend::end_frame(&mut backend);
    }

    /// A layout returned with no surface attached reports real geometry
    /// and agrees with what [`WinBackend::draw_minimap`] itself reports as
    /// unpainted layout, upholding the "paint and no-paint query can't
    /// drift apart" contract that every backend upholds.
    #[test]
    fn draw_minimap_with_no_surface_reports_unpainted_and_agrees_with_minimap_layout() {
        let mut backend = WinBackend::new();
        let minimap = sample_minimap();
        let rect = Rect::new(0.0, 0.0, 20.0, 100.0);

        let result = backend.draw_minimap(rect, &minimap);

        assert!(
            !result.painted,
            "no surface attached — `painted` must honestly report `false`, not panic"
        );
        assert!(
            !result.layout.visible_lines.is_empty(),
            "the layout must still be real geometry, not an empty stub"
        );

        let no_paint = backend.minimap_layout(rect, &minimap);
        assert_eq!(
            result.layout, no_paint,
            "draw_minimap's returned layout must agree with minimap_layout's \
             standalone query"
        );
    }

    /// `set_minimap_scale`/`minimap_scale` must actually change the row
    /// pitch that `minimap_layout` resolves. This path needs no Windows
    /// surface, so it provides real signal on every host.
    #[test]
    fn set_minimap_scale_changes_the_resolved_row_pitch() {
        use crate::primitives::minimap::MinimapScale;

        let mut backend = WinBackend::new();
        let minimap = sample_minimap();
        let rect = Rect::new(0.0, 0.0, 20.0, 100.0);

        assert_eq!(backend.minimap_scale(), MinimapScale::One);
        let default_layout = backend.minimap_layout(rect, &minimap);
        assert_eq!(
            default_layout.visible_lines[0].bounds.height,
            MinimapScale::One.row_pitch_px() as f32
        );

        backend.set_minimap_scale(MinimapScale::Two);
        assert_eq!(backend.minimap_scale(), MinimapScale::Two);
        let scaled_layout = backend.minimap_layout(rect, &minimap);
        assert_eq!(
            scaled_layout.visible_lines[0].bounds.height,
            MinimapScale::Two.row_pitch_px() as f32
        );

        let result = backend.draw_minimap(rect, &minimap);
        assert_eq!(
            result.layout, scaled_layout,
            "draw_minimap's own (unpainted, no-surface) layout must also honor the \
             backend's minimap_scale"
        );
    }

    /// `draw_panel` with no surface must agree with `panel_layout`,
    /// upholding the same contract as the minimap test.
    #[test]
    fn draw_panel_with_no_surface_agrees_with_panel_layout() {
        let mut backend = WinBackend::new();
        let panel = sample_panel();
        let rect = Rect::new(0.0, 0.0, 200.0, 100.0);

        let painted = backend.draw_panel(rect, &panel);
        let no_paint = backend.panel_layout(rect, &panel);

        assert_eq!(
            painted, no_paint,
            "draw_panel's returned layout must agree with panel_layout's \
             standalone query"
        );
    }

    /// `draw_image` on a surface-less backend must report `Unsupported`
    /// rather than panic.
    #[test]
    fn draw_image_with_no_surface_reports_unsupported() {
        let mut backend = WinBackend::new();
        let image = crate::primitives::image::Image {
            id: WidgetId::new("img"),
            source: crate::primitives::image::ImageSource::Bytes(Vec::new()),
            intrinsic_size: None,
            fit: crate::primitives::image::ImageFit::Contain,
            fallback_text: "img".to_string(),
        };
        let rect = Rect::new(0.0, 0.0, 50.0, 50.0);

        let result = backend.draw_image(rect, &image);
        assert_eq!(result, crate::backend::ImagePaintResult::Unsupported);
    }

    // `draw_editor`'s no-surface fallback (`EditorPaintResult::default()`)
    // is a one-line, zero-logic return with nothing to get wrong beyond
    // what `cargo check`/`clippy` already verify — building a full
    // `Editor` fixture (~20 required fields) to cover it isn't worth the
    // weight; `EditorPaintResult`'s own `#[derive(Default)]` is exercised
    // directly wherever it's constructed (e.g. `Default::default()` in
    // `src/backend.rs`'s own tests).

    /// `PaintSurface::surface_measure_text`/`surface_measure_text_styled`
    /// on a surface-less backend must return a finite nominal estimate
    /// (`char_width` per character) instead of panicking, so a host doing
    /// hit-testing against the measurement gets a non-degenerate box.
    #[test]
    fn surface_measure_text_with_no_surface_returns_a_nominal_estimate() {
        let backend = WinBackend::new();
        let (w, h) = PaintSurface::surface_measure_text(&backend, "hello");
        assert_eq!(w, 5.0 * backend.current_char_width);
        assert_eq!(h, backend.current_line_height);

        let (w2, h2) = PaintSurface::surface_measure_text_styled(&backend, "hello", true);
        assert_eq!(w2, 5.0 * backend.current_char_width);
        assert_eq!(h2, backend.current_line_height);
    }

    // ── Caret blink ──────────────────────────────────────────────────────

    /// `WinBackend`'s caret-blink accessors forward to
    /// [`crate::caret_blink::CaretBlinkState`] faithfully: `tick_caret_blink`
    /// flips `caret_visible` after `caret_blink_period` elapses,
    /// `note_caret_activity` holds it solid through a typing pause, and
    /// `set_caret_visible` lets a test pin the phase directly — mirrors
    /// `GtkBackend`/`MacBackend`'s equivalent coverage for the same state
    /// machine.
    #[test]
    fn win_backend_caret_blink_methods_drive_the_shared_state_machine() {
        let mut backend = WinBackend::new();
        let period = backend.caret_blink_period();
        assert!(period > std::time::Duration::ZERO);

        backend.set_caret_visible(true);
        assert!(backend.caret_visible());
        backend.set_caret_visible(false);
        assert!(!backend.caret_visible());

        let start = Instant::now();
        let flipped = backend.tick_caret_blink(start + period);
        assert!(flipped, "a tick a full period later must flip the phase");
        assert!(backend.caret_visible());

        // A typing-pause bump holds the caret solid: a tick that would
        // otherwise flip it must now be a no-op.
        backend.note_caret_activity(start + period);
        let flipped_during_pause = backend.tick_caret_blink(start + period);
        assert!(
            !flipped_during_pause,
            "a tick during an active typing pause must not flip the phase"
        );
        assert!(backend.caret_visible());
    }
}