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
//! TUI implementation of [`crate::Backend`].
//!
//! `TuiBackend` owns the persistent UI state the trait requires —
//! viewport dimensions, modal stack, drag state, accelerator registry,
//! platform services — plus a transient frame pointer set inside
//! [`Self::enter_frame_scope`] so trait `draw_*` methods can reach
//! the ratatui `&mut Frame<'_>` (which only exists inside
//! `terminal.draw(|frame| …)`'s closure).
//!
//! ### Frame-scope mechanism
//!
//! ratatui's `terminal.draw(|frame| …)` API only yields `&mut Frame`
//! inside the closure, so `TuiBackend` can't hold one across method
//! calls. Instead [`Self::enter_frame_scope`] takes the frame, stashes
//! a type-erased `*mut ()` in `current_frame_ptr`, runs the caller's
//! closure (where trait `draw_*` methods can reach the frame via
//! [`Self::current_frame_mut`]), and clears the pointer on exit.
//! The pointer is null outside the scope, so the safe accessor
//! returns `None` and `draw_*` methods can detect misuse.
//!
//! ### What the trait covers
//!
//! As of #13 the `Backend` trait covers every primitive that has
//! TUI + GTK rasterisers. New primitives must add a trait method as
//! part of the same change that adds the rasteriser (see CLAUDE.md
//! Primitive Authoring Rule #7). Generic `<B: Backend>` render code
//! works against `TuiBackend`, `GtkBackend`, the test `MockBackend`,
//! and any future Win-GUI / macOS backend implementer.
//!
//! Drag-state observation is normally a backend implementation
//! detail — only `crate::dispatch::*` needs to inspect it directly.
//! It's still reachable via [`crate::Backend::drag_state_handle`]
//! so `&mut dyn Backend` / `&dyn Backend`
//! consumers (e.g. a `ShellApp`'s mouse-dispatch logic) can reach it
//! without downcasting to the concrete backend.
//!
//! Event flow goes through the trait: [`Self::wait_events`] reads
//! crossterm events, translates them via
//! [`super::events::crossterm_to_uievents`], then runs
//! [`Self::apply_accelerators`] to rewrite registered key bindings as
//! [`UiEvent::Accelerator`] before returning. The event loop in
//! [`super::event_loop`] consumes those `UiEvent`s via
//! [`Backend::wait_events`].

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

use crate::backend::{activity_bar_hits, tab_bar_hits_from_layout, ColorDepth};
use crate::dispatch::TextRegion;
use crate::testing::ZoneRec;
use crate::{
    Accelerator, AcceleratorId, ActivityBar, Backend, Color, CommandLine, DragState, Form,
    ListView, MenuBar, ModalStack, Palette, PlatformServices, Point, Rect as QRect, Split,
    StatusBar, TabBar, TabBarLayout, TabChrome, TabFrame, Terminal as TerminalPrim,
    TerminalCellSize, TextDisplay, TreeView, UiEvent, Viewport, WidgetId,
};
// `KeyBinding`/`DragTarget`/`AcceleratorScope` are only referenced by
// `#[cfg(test)]` code below — `route_pointer` absorbed
// `apply_dispatch`'s own `DragTarget::TextSelection` match, and
// `register_accelerator`/`match_keypress` moved their `AcceleratorScope`
// check into `BackendCore` — so this file's non-test code no
// longer names either type directly. Gate the import so a non-test
// build doesn't flag it as unused.
#[cfg(test)]
use crate::{AcceleratorScope, DragTarget, KeyBinding};
use ratatui::layout::Rect;
use ratatui::Frame;

use super::services::TuiPlatformServices;
use super::text::display_width;

/// Minimum gap (in cells) between left and right status-bar halves
/// before priority drop kicks in. Mirrors `crate::gtk::status_bar`'s
/// `MIN_GAP_PX = 16.0`. Irrelevant for bars without right segments.
const MIN_GAP_CELLS: f32 = 2.0;

/// TUI backend implementing [`crate::Backend`].
///
/// Owns the persistent UI state the trait requires plus a transient
/// "current frame" pointer + theme set inside
/// [`Self::enter_frame_scope`]. The pointer is type-erased
/// (`*mut ()`) and cleared on scope exit; safe accessors deref it
/// only while the scope is active.
///
/// The ratatui `Terminal` is **not** owned here — it stays as a local
/// in [`super::event_loop`]. See `docs/decisions/BACKEND_TRAIT_PROPOSAL.md` §11 for
/// rationale and the eventual migration plan.
pub struct TuiBackend {
    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 same shape `GtkBackend` uses for its own callback-driven
    /// access.
    modal_stack: Rc<RefCell<ModalStack>>,
    /// See `modal_stack`'s doc comment — same rationale.
    drag_state: Rc<RefCell<DragState>>,
    /// Accelerator registry + text-selection bookkeeping — see
    /// [`crate::backend_core::BackendCore`]'s module doc. Replaces the
    /// formerly TUI-local `accelerators`/`parsed_accelerators` fields
    /// verbatim, plus (below) the formerly separate `text_selection`
    /// field.
    core: crate::backend_core::BackendCore,
    services: TuiPlatformServices,
    /// Type-erased `&mut Frame<'_>` pointer; non-null only inside
    /// [`Self::enter_frame_scope`]. `Cell` (not `RefCell`) because
    /// trait methods borrow `&mut self` already; we only need
    /// shared-cell semantics for `Copy`-able pointer values.
    current_frame_ptr: Cell<*mut ()>,
    /// Theme captured by the most recent
    /// [`Self::set_current_theme`] call. Defaults to
    /// `crate::Theme::default()` until set.
    current_theme: crate::Theme,
    /// Style captured by the most recent
    /// [`Self::set_current_style`] call. Defaults to
    /// `crate::Style::default()` until set.
    current_style: crate::Style,
    /// Whether the rasterisers should use Nerd Font glyphs (`true`)
    /// or ASCII fallbacks (`false`). Apps set this from their own
    /// settings via [`Self::set_nerd_fonts`]; defaults to `false`.
    nerd_fonts_enabled: bool,
    double_click: super::events::DoubleClickDetector,
    /// Whether [`Self::translate_injected`] should run raw `MouseDown`
    /// pairs through [`Self::double_click`]'s folding logic. Defaults to
    /// `true` (matches production `poll_events`/`wait_events`, which
    /// always fold). [`super::testing::TuiDriver::set_double_click_folding`]
    /// flips this to `false` so a test that means two distinct clicks
    /// isn't at the mercy of `Instant::now()` landing two
    /// calls inside the 400ms window under load. Only `translate_injected`
    /// (the driver's path) honours this — `poll_events`/`wait_events`
    /// (the live terminal runner) always fold, since a real user's two
    /// clicks should still coalesce.
    double_click_folding: bool,
    /// Widget zones registered during the current frame via
    /// [`crate::Backend::register_zone`]. Cleared at the start of each
    /// frame by [`Self::begin_frame`], mirroring `text_regions`. Read by
    /// [`crate::tui::testing::TuiDriver::inventory`] to populate
    /// [`crate::testing::FrameInventory::zones`].
    zones: Vec<ZoneRec>,
    /// Text extracted from the last rendered buffer for the active
    /// selection. Populated by `apply_selection_highlight` (which has
    /// access to the live buffer inside `terminal.draw`). After the
    /// draw closure returns ratatui swaps its double-buffer, so
    /// `terminal.current_buffer_mut()` would return an empty buffer —
    /// caching here is the only reliable way to get the text.
    cached_selection_text: String,
    /// `WidgetId` of the `ActivityBar` that declared `is_keyboard_focused`
    /// during the most recent render pass. Set by `draw_activity_bar`;
    /// cleared at the start of each frame by `begin_frame` (same lifecycle
    /// as `text_regions`). When `Some`, `apply_dispatch` converts incoming
    /// `KeyPressed` events to `UiEvent::ActivityBar(id, KeyPressed { … })`
    /// so app logic receives activity-bar keys through a typed channel.
    focused_activity_bar: Option<WidgetId>,
    /// Screen-space `(x, y)` for `Frame::set_cursor_position`, cached from
    /// the most recent [`Backend::draw_editor`] call **that reported a
    /// `Some` position** this frame.
    ///
    /// `draw_editor` only has access to the ratatui buffer, not the `Frame`
    /// itself (see [`Self::current_frame_mut`]'s note on why trait methods
    /// can't reach `Frame::set_cursor_position` directly), so it stashes
    /// the position here. [`super::run::render_frame`] takes it via
    /// [`Self::take_last_cursor_position`] after the render closure returns
    /// and applies it to the real `Frame`, mirroring how
    /// `apply_selection_highlight` bridges buffer-only paint to a
    /// frame-level side effect.
    ///
    /// Cleared at the start of every frame by [`Self::begin_frame`] (same
    /// lifecycle as `text_regions`) so a frame that doesn't paint an editor
    /// doesn't inherit a stale cursor position from the previous one. Within
    /// a frame, the `draw_editor` call site only overwrites this on a
    /// `Some` result — a frame can call `draw_editor` once
    /// per window (e.g. a split), and only the active window ever reports
    /// `Some`; an inactive window's later, cursor-less call must not
    /// clobber an active window's `Some` recorded earlier in the same
    /// frame regardless of paint order.
    last_cursor_position: Option<(u16, u16)>,
    /// `(bar rect, resolved layout)` from the most recent `draw_tab_bar`
    /// call, per tab-bar `WidgetId`. Cleared at the start of every frame
    /// by [`Self::begin_frame`] (same lifecycle as `zones`) so a tab bar
    /// that stops painting doesn't leave a stale entry that would resolve
    /// a tab no longer on screen.
    ///
    /// `TabBarLayout`'s own `visible_tabs`/`close_bounds` rects are
    /// bar-relative (origin at the bar's own top-left) — the same
    /// convention `crate::tui::draw_tab_bar` paints with (it adds
    /// `area.x`/`area.y` itself). [`Self::cached_tab_bar_layout`] hands
    /// back the paired rect so callers can shift into absolute
    /// screen-space coordinates. Read by
    /// [`crate::tui::testing::TuiDriver::tab_center`] /
    /// [`crate::tui::testing::TuiDriver::tab_close_center`]
    /// — every tab paints the same close glyph, so `find` can't
    /// disambiguate tab 3's target from tab 0's the way it can for
    /// uniquely-labeled text.
    tab_bar_layouts: HashMap<WidgetId, (QRect, TabBarLayout)>,
    /// Colour fidelity this backend's rasterisers should quantise to —
    /// see [`crate::backend::ColorDepth`]. Detected from the process
    /// environment (`COLORTERM`/`TERM`) at construction time via
    /// [`super::caps::detect_color_depth`]; overridable via
    /// [`Self::set_color_depth`] for tests and hosts that already know
    /// their terminal's real capability.
    color_depth: ColorDepth,
    /// Whether the kitty keyboard protocol is actually active — seeded
    /// from [`super::caps::detect_kitty_keyboard`]'s cheap environment
    /// heuristic at construction time, then overwritten by
    /// [`super::run::run`] via [`Self::set_kitty_keyboard`] once it has
    /// [`super::caps::probe_kitty_keyboard`]'s live, authoritative answer.
    /// Exposed to apps via
    /// [`crate::backend::BackendCaps::kitty_keyboard`] — see that field's
    /// doc for why this exists.
    kitty_keyboard: bool,
    /// Whether mouse reporting is actually active for this session.
    /// Defaults to `true`; [`super::run::run_with`] sets this to `false`
    /// when the caller opts into `RunConfig { mouse: false, .. }` — the
    /// "capture refused" `no-mouse` mode — so the terminal
    /// never gets `EnableMouseCapture` and every Tier-1 gesture must have
    /// a key path instead.
    ///
    /// Deliberately **not** folded into
    /// [`crate::backend::BackendCaps::mouse`]/`scroll`/`drag`: those three
    /// are a static per-backend-*type* fact
    /// (`tests/conformance/caps.rs`'s `source_parsed_caps_match_the_running_backend`
    /// mechanically parses `backend_caps()`'s source for literal `: true,`
    /// declarations and would flag a field that reads from `self` as
    /// drift), the same distinction that already keeps
    /// [`Self::kitty_keyboard`] a plain inherent accessor rather than
    /// folded into the bool-capability vocabulary. Read via
    /// [`Self::mouse_enabled`].
    mouse_enabled: bool,
    /// Whether SGR-Pixels mouse mode (`?1016h`) is actually active for this
    /// session — seeded from
    /// [`super::caps::detect_sgr_pixel_mouse`]'s cheap environment
    /// heuristic at construction time, then overwritten by
    /// [`super::run::run_with`] via [`Self::set_sgr_pixel_mouse`] once it
    /// has [`super::caps::probe_sgr_pixel_mouse`]'s live, authoritative
    /// answer *and* a usable [`Self::cell_pixel_size`] — see that method's
    /// doc for why both are required, not just the probe. Exposed to apps
    /// via [`crate::backend::BackendCaps::sgr_pixel_mouse`]; same
    /// runtime-detected-terminal-property exemption from the bool
    /// capability vocabulary as [`Self::kitty_keyboard`] (see that field's
    /// doc).
    sgr_pixel_mouse: bool,
    /// The pixel size of one terminal cell, used to divide a SGR-Pixels
    /// mouse report's raw pixel `column`/`row` back into a fractional cell
    /// coordinate — see
    /// [`super::events::crossterm_mouse_to_uievent_scaled`]. Defaults to
    /// `TerminalCellSize::new(1.0, 1.0)`, the identity divisor that keeps
    /// every coordinate byte-identical to cell-mode's whole-cell values
    /// when [`Self::sgr_pixel_mouse`] is `false` (the overwhelmingly common
    /// case — most terminals don't advertise mode 1016 at all).
    /// [`super::run::run_with`] overwrites this once at startup (from a
    /// real `window_size()` query) and again on every `Event::Resize`, since
    /// a font-size change alters the cell's pixel dimensions without
    /// changing the grid's row/column count.
    cell_pixel_size: TerminalCellSize,
    /// Whether this session's terminal correctly renders SGR 58
    /// (`Cell::underline_color`) in the semicolon form crossterm emits,
    /// seeded from
    /// [`super::caps::detect_underline_color_support`] at construction
    /// time, overridable via [`Self::set_underline_color_supported`] for
    /// tests that want to exercise the Windows/ConPTY degrade without an
    /// actual Windows host. `false` means
    /// [`Self::strip_unsupported_underline_colors`] clears every painted
    /// cell's `underline_color` back to `Reset` each frame, instead of
    /// leaving behind the colour ConPTY misparses as blink/faint.
    underline_color_supported: bool,
    /// 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 (issue
    /// #831) — see [`crate::runtime::UserEventQueue`]'s doc. [`Self::waker`]
    /// clones this `Arc` into the closure it hands out; [`Self::poll_events`]/
    /// [`Self::wait_events`] drain it into `UiEvent::User`, appended after
    /// whatever crossterm produced this call, on every call. Before
    /// quadraui#832, TUI's live runner polled unconditionally every 16ms
    /// (`tui::run::POLL_TIMEOUT`), which incidentally bounded a background
    /// wake's latency without any native interrupt of the blocking
    /// crossterm read. Since #832 the idle poll is coarser
    /// (`crate::runtime::IDLE_POLL_CEILING`, 250ms) — still no native
    /// interrupt exists (unlike GTK/macOS/Windows, see `Backend::waker`'s
    /// doc for why those three need one), so a background-only wake with
    /// no scheduled frame and no concurrent input now has up to that
    /// ceiling of latency instead of 16ms. A documented, deliberate
    /// tradeoff — see [`Self::request_frame_in`]'s doc.
    user_events: std::sync::Arc<crate::runtime::UserEventQueue>,
    /// Pending [`Self::request_frame_in`] deadline — see
    /// [`crate::runtime::FrameScheduler`]'s doc for why TUI needs this
    /// where GTK/macOS/Windows instead arm a real native timer directly
    /// from `request_frame_in`. Consulted by the live runner
    /// (`tui::run::run_inner`) each loop iteration, via
    /// [`Self::frame_poll_timeout`]/[`Self::clear_frame_deadline_if_due`],
    /// to compute the next `wait_events` timeout.
    /// [`crate::tui::testing::TuiDriver`]'s headless loop is scripted
    /// rather than timer-driven, so it never *waits* on this deadline —
    /// but it does arm it (its `dispatch`/`pump_user_events`/`tick` call
    /// `request_frame_in` exactly where the live loop does), and tests
    /// read it back through [`Self::frame_requests`] /
    /// [`Self::pending_frame_delay`].
    frame_scheduler: crate::runtime::FrameScheduler,
    /// Pending [`Backend::request_full_repaint`] request —
    /// set by that method, consumed once by [`Self::take_full_repaint_requested`]
    /// right before the next frame paints. See that method's doc for the
    /// two call sites that consume it: the live runner's
    /// `tui::run::run_inner` frame loop, and
    /// [`crate::tui::testing::TuiDriver::render`] on the headless path.
    full_repaint_requested: bool,
    /// Latched `true` once [`Self::poll_events`]/[`Self::wait_events`]
    /// detect that the input fd (stdin — a real terminal or pty slave) is
    /// permanently gone: hung up, with no bytes left to read. Never
    /// cleared once set — there is no path back from "the fd is gone" to
    /// "input is working again." Read by
    /// [`super::run::TuiRunner::run_one`] to turn the condition into a
    /// clean [`crate::runner::StepOutcome::Exited`] instead of looping
    /// back into another `wait_events`/`poll_events` call. See
    /// [`Self::input_gone`]'s doc and the `stdin_hung_up` guard (below in
    /// this file) for the full rationale.
    input_gone: bool,
    /// Row-pitch strategy [`Backend::draw_minimap`]/[`Backend::minimap_layout`]
    /// resolve from, set via [`Backend::set_minimap_sizing`]. `None` (the
    /// default) means "use this rasteriser's own hardcoded default" —
    /// [`crate::tui::tui_minimap_layout`]'s `FixedPitch(1.0)` — so a host
    /// that never calls the setter sees byte-for-byte the same layout and
    /// paint as before this field existed.
    minimap_sizing: Option<crate::primitives::minimap::MinimapSizing>,
    /// Column count reserved between the editor's text area and its
    /// vertical scrollbar, set via
    /// [`Backend::set_editor_right_reserve_w`]. `None` (the default)
    /// reserves nothing — [`Self::draw_editor`]/[`Backend::editor_layout`]
    /// paint and hit-test exactly as before this field existed. The
    /// setter quantises to a whole cell at set-time (one TUI cell is one
    /// pixel unit here, so this is a no-op for already-integral input),
    /// which is what keeps this value's two readers in agreement:
    /// [`Backend::editor_layout`]'s default body folds the raw `f32` in
    /// directly, while [`crate::tui::draw_editor_with_reserve`] takes a
    /// `u16` and would otherwise round independently (and possibly
    /// differently, for a non-integral input) from what `editor_layout`
    /// saw.
    editor_right_reserve_w: Option<f32>,
}

impl TuiBackend {
    /// Construct the backend with default viewport (80×24) and
    /// default quadraui theme. The caller calls [`Backend::begin_frame`]
    /// each frame (after `terminal.size()`) to keep
    /// [`Backend::viewport`] in sync, and [`Self::set_current_theme`]
    /// before drawing so the trait `draw_*` methods see the right
    /// palette.
    pub fn new() -> Self {
        Self {
            viewport: Viewport::default(),
            modal_stack: Rc::new(RefCell::new(ModalStack::new())),
            drag_state: Rc::new(RefCell::new(DragState::new())),
            core: crate::backend_core::BackendCore::default(),
            services: TuiPlatformServices::new(),
            current_frame_ptr: Cell::new(std::ptr::null_mut()),
            current_theme: crate::Theme::default(),
            current_style: crate::Style::default(),
            nerd_fonts_enabled: false,
            double_click: super::events::DoubleClickDetector::new(),
            double_click_folding: true,
            zones: Vec::new(),
            cached_selection_text: String::new(),
            focused_activity_bar: None,
            last_cursor_position: None,
            tab_bar_layouts: HashMap::new(),
            color_depth: super::caps::detect_color_depth(),
            kitty_keyboard: super::caps::detect_kitty_keyboard(),
            mouse_enabled: true,
            sgr_pixel_mouse: super::caps::detect_sgr_pixel_mouse(),
            cell_pixel_size: TerminalCellSize::new(1.0, 1.0),
            underline_color_supported: super::caps::detect_underline_color_support(),
            focus: crate::focus::FocusManager::new(),
            user_events: crate::runtime::UserEventQueue::new(),
            frame_scheduler: crate::runtime::FrameScheduler::new(),
            full_repaint_requested: false,
            input_gone: false,
            minimap_sizing: None,
            editor_right_reserve_w: None,
        }
    }

    /// The colour depth [`Backend::backend_caps`] currently reports —
    /// see [`crate::backend::ColorDepth`] and [`Self::set_color_depth`].
    pub fn color_depth(&self) -> ColorDepth {
        self.color_depth
    }

    /// How long the run loop may block in [`Backend::wait_events`] before
    /// it needs to re-check state — the pending
    /// [`Backend::request_frame_in`] deadline's remaining time, clamped to
    /// `ceiling`, or `ceiling` itself if nothing is pending. See
    /// [`crate::runtime::FrameScheduler::poll_timeout`].
    pub(crate) fn frame_poll_timeout(&self, ceiling: Duration) -> Duration {
        self.frame_scheduler.poll_timeout(ceiling)
    }

    /// Clear the pending [`Backend::request_frame_in`] deadline if it has
    /// passed. Call once per loop iteration right after `wait_events`
    /// returns, before dispatching events or calling `tick` — see
    /// [`crate::runtime::FrameScheduler::clear_if_due`].
    pub(crate) fn clear_frame_deadline_if_due(&mut self) {
        self.frame_scheduler.clear_if_due();
    }

    /// Consume the pending [`Backend::request_full_repaint`] request,
    /// if any — returns `true` and clears it, or `false`
    /// if nothing was requested since the last call.
    ///
    /// Call once per loop iteration, right before painting the next
    /// frame: a `true` result means the caller should clear its
    /// `ratatui::Terminal`'s diff cache (`Terminal::clear()`) before that
    /// frame's `terminal.draw(...)` call, exactly what a raw ratatui
    /// app's own `Terminal::clear()` gives it. See
    /// `tui::run::run_inner`'s frame loop and
    /// [`crate::tui::testing::TuiDriver::render`] for the two consumers —
    /// both must call this, not read `full_repaint_requested` directly,
    /// so the request is never double-applied.
    pub(crate) fn take_full_repaint_requested(&mut self) -> bool {
        std::mem::take(&mut self.full_repaint_requested)
    }

    /// Whether [`Self::poll_events`]/[`Self::wait_events`] have detected
    /// that the input fd is permanently gone — see the `input_gone`
    /// field's doc comment for the full rationale. A plain read, not a
    /// `take`: once true, it stays true for the rest of this backend's
    /// lifetime, so every subsequent `run_one` check sees the same
    /// answer.
    ///
    /// `pub`, not `pub(crate)` — unlike the other internal-plumbing
    /// accessors on this impl, a host embedding [`super::run::TuiRunner`]
    /// directly via `step`/`pump` has a legitimate reason to read this
    /// off [`super::run::TuiRunner::backend`] after seeing
    /// [`super::run::StepOutcome::Exited`], to tell "the app chose to
    /// exit" apart from "the input source disappeared out from under
    /// us."
    pub fn input_gone(&self) -> bool {
        self.input_gone
    }

    /// How many times [`Backend::request_frame_in`] has been called on
    /// this backend since it was constructed.
    ///
    /// Real hosts never need this — it exists so a headless
    /// [`crate::tui::testing::TuiDriver`] test can assert on an app's
    /// *scheduling* behaviour, which is otherwise invisible: an app that
    /// re-arms itself every tick and one that relies on a fixed idle
    /// cadence paint identical screens and return identical
    /// [`crate::Reaction`]s. Counting the calls (rather than reading
    /// [`Self::pending_frame_delay`]) is what makes the chained-re-arm
    /// pattern testable, because repeated requests at the same interval
    /// coalesce to one deadline — see
    /// [`crate::runtime::FrameScheduler`].
    ///
    /// Monotonic: a fired deadline clears the pending wake, 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. Also test-facing — the live runner uses the `pub(crate)`
    /// [`Self::frame_poll_timeout`] instead, which clamps to the idle
    /// ceiling and so can't distinguish "nothing scheduled" from
    /// "scheduled beyond the ceiling".
    pub fn pending_frame_delay(&self) -> Option<Duration> {
        self.frame_scheduler.pending_delay()
    }

    /// Override the detected colour depth. Real hosts never need this —
    /// [`Self::new`] already detects it from the environment — but tests
    /// that want to force a specific SGR shape or any in-process test
    /// asserting quantised output call this to pin the value instead of
    /// depending on the process's real `TERM`/`COLORTERM`.
    pub fn set_color_depth(&mut self, depth: ColorDepth) {
        self.color_depth = depth;
    }

    /// The kitty-keyboard-protocol state [`Backend::backend_caps`]
    /// currently reports — see
    /// [`crate::backend::BackendCaps::kitty_keyboard`] and
    /// [`Self::set_kitty_keyboard`].
    pub fn kitty_keyboard(&self) -> bool {
        self.kitty_keyboard
    }

    /// Override the kitty-keyboard-protocol flag. [`super::run::run`]
    /// calls this once at startup with
    /// [`super::caps::probe_kitty_keyboard`]'s live answer, overwriting
    /// the environment-only guess [`Self::new`] seeded it with. Also the
    /// hook a test (or a host that already knows its terminal's real
    /// capability) uses to pin the value without touching a real terminal.
    pub fn set_kitty_keyboard(&mut self, supported: bool) {
        self.kitty_keyboard = supported;
    }

    /// Drain pending [`crate::UiEvent::User`] payloads without touching
    /// crossterm — the same [`Self::user_events`] queue [`Backend::poll_events`]/
    /// [`Backend::wait_events`] fold in, exposed standalone for
    /// [`super::testing::TuiDriver`]. The driver runs against
    /// ratatui's `TestBackend`, never a live terminal, so it has no
    /// crossterm event source to poll for a background-thread wake to ride
    /// in on — this lets it observe the wake directly instead.
    pub(crate) fn drain_user_events(&mut self) -> Vec<UiEvent> {
        let mut out = Vec::new();
        self.user_events.drain_into(&mut out);
        out
    }

    /// Whether mouse reporting is active this session — see
    /// [`Self::set_mouse_enabled`]'s doc for why this is a plain inherent
    /// accessor rather than a [`crate::backend::BackendCaps`] field.
    pub fn mouse_enabled(&self) -> bool {
        self.mouse_enabled
    }

    /// Concrete (non-trait-object) handle on the platform services, so
    /// [`super::run::run_with`] can call
    /// [`super::services::TuiPlatformServices::set_dialog_surface`] —
    /// the `&dyn PlatformServices` [`Backend::services`] returns can't
    /// reach that inherent method. Mirrors
    /// `GtkPlatformServices::gtk_clipboard`'s reason for existing, minus
    /// the `#[cfg(test)]` gate: this one is called from production, not
    /// only tests.
    pub(crate) fn tui_services(&self) -> &TuiPlatformServices {
        &self.services
    }

    /// Override whether this session has mouse reporting.
    /// [`super::run::run_with`] calls this with `false` when the caller
    /// opts into `no-mouse` mode (`RunConfig { mouse: false, .. }`),
    /// so the terminal is never asked to enable mouse capture. Also the
    /// hook a test uses to simulate "capture refused" without a real terminal.
    pub fn set_mouse_enabled(&mut self, enabled: bool) {
        self.mouse_enabled = enabled;
    }

    /// Whether SGR-Pixels mouse mode is actually active this session — see
    /// [`crate::backend::BackendCaps::sgr_pixel_mouse`] and
    /// [`Self::set_sgr_pixel_mouse`].
    pub fn sgr_pixel_mouse(&self) -> bool {
        self.sgr_pixel_mouse
    }

    /// Override the SGR-Pixels-mouse-mode flag. [`super::run::run_with`]
    /// calls this once at startup with the combined answer of
    /// [`super::caps::probe_sgr_pixel_mouse`] *and* a successfully-resolved
    /// [`Self::cell_pixel_size`] — a live-supporting terminal whose pixel
    /// cell size can't be determined must still land on `false` here (see
    /// that run site's doc for why). Also the hook a test uses to pin the
    /// value without a real terminal.
    pub fn set_sgr_pixel_mouse(&mut self, enabled: bool) {
        self.sgr_pixel_mouse = enabled;
    }

    /// The pixel size of one terminal cell — see [`Self::set_cell_pixel_size`].
    /// Only meaningful (as an actual pixel measurement, not the identity
    /// divisor) when [`Self::sgr_pixel_mouse`] is `true`.
    pub fn cell_pixel_size(&self) -> TerminalCellSize {
        self.cell_pixel_size
    }

    /// Override the cell pixel size used to scale SGR-Pixels mouse reports
    /// back into fractional cell coordinates. [`super::run::run_with`]
    /// calls this from a real `window_size()` query at startup and again on
    /// every settled `Event::Resize` (a font-size change alters pixel
    /// dimensions without changing the grid's row/column count). Also the
    /// hook a test uses to exercise pixel-mode scaling without a real terminal.
    pub fn set_cell_pixel_size(&mut self, size: TerminalCellSize) {
        self.cell_pixel_size = size;
    }

    /// Whether this session's terminal correctly renders SGR 58
    /// (`underline_color`) — see [`Self::set_underline_color_supported`]
    /// and `super::caps`'s module doc.
    pub fn underline_color_supported(&self) -> bool {
        self.underline_color_supported
    }

    /// Override the detected underline-colour-support flag. Real hosts
    /// never need this — [`Self::new`] already detects it from
    /// `cfg!(windows)` — but a test that wants to exercise the
    /// Windows/ConPTY degrade without an actual Windows
    /// host calls this to force the unsupported path.
    pub fn set_underline_color_supported(&mut self, supported: bool) {
        self.underline_color_supported = supported;
    }

    /// Clear every painted cell's `underline_color` back to
    /// [`ratatui::style::Color::Reset`] when this session's terminal
    /// cannot correctly render SGR 58 — a no-op when
    /// [`Self::underline_color_supported`] is `true`.
    ///
    /// Runs once per frame, over the whole buffer, from
    /// [`super::run::paint_frame`] right after every rasteriser for the
    /// frame has painted — not threaded as a parameter through
    /// `draw_tab_bar`/`draw_editor`/`draw_terminal` (the three call
    /// sites that currently set `underline_color`). A
    /// single per-frame sweep here can't miss a call site a
    /// future primitive adds, costs nothing beyond one extra `bool`
    /// branch per cell on the common (`true`) case, and is exactly what
    /// `TuiDriver`-based tests observe too, since both the live runner
    /// and the headless driver share this same `paint_frame` call.
    pub(crate) fn strip_unsupported_underline_colors(&self, buf: &mut ratatui::buffer::Buffer) {
        if self.underline_color_supported {
            return;
        }
        for cell in &mut buf.content {
            cell.underline_color = ratatui::style::Color::Reset;
        }
    }

    /// Enter the frame-scope: stash the `&mut Frame<'_>` pointer for
    /// trait `draw_*` methods to access, run `f`, then clear the
    /// pointer. **Must** be called from inside a
    /// `terminal.draw(|frame| …)` closure.
    ///
    /// Type-erased through `*mut ()` because `Frame<'a>` carries a
    /// lifetime parameter we don't want to thread onto `TuiBackend`.
    /// Safety relies on three invariants enforced by this function's
    /// shape:
    ///   1. The pointer is set immediately before running `f` and
    ///      cleared immediately after, including on panic (via
    ///      [`scopeguard`]-style restore).
    ///   2. `f` cannot move the pointer out — it only sees it via
    ///      [`Self::current_frame_mut`] which returns a fresh
    ///      `&mut Frame<'_>` borrow scoped to the call.
    ///   3. `enter_frame_scope` calls don't nest meaningfully —
    ///      the inner call would overwrite the pointer with the
    ///      same `&mut` (already aliased) which Rust's borrow-checker
    ///      forbids at the caller side.
    pub fn enter_frame_scope<R>(
        &mut self,
        frame: &mut Frame<'_>,
        f: impl FnOnce(&mut Self) -> R,
    ) -> R {
        let ptr = frame as *mut Frame<'_> as *mut ();
        let prev = self.current_frame_ptr.replace(ptr);
        let result = f(self);
        self.current_frame_ptr.set(prev);
        result
    }

    /// Get the current frame inside [`Self::enter_frame_scope`], or
    /// `None` outside it. Trait `draw_*` methods call this and bail
    /// (panic in dev, silent return otherwise) if `None`: each call site
    /// matches that contract via `debug_assert!` plus a graceful
    /// per-method default, not a bare `.expect()` that would panic in
    /// every build profile.
    fn current_frame_mut(&mut self) -> Option<&mut Frame<'static>> {
        let ptr = self.current_frame_ptr.get();
        if ptr.is_null() {
            None
        } else {
            // SAFETY: `enter_frame_scope` set this from a real
            // `&mut Frame<'_>` and won't return until the scope
            // ends, at which point the pointer is cleared. Outside
            // the scope `ptr` is null and we return `None`.
            // The `'static` lifetime here is a fiction — the borrow
            // is actually scoped to the enclosing
            // `enter_frame_scope` call. Methods using this never let
            // the borrow escape past their own return.
            Some(unsafe { &mut *(ptr as *mut Frame<'static>) })
        }
    }

    /// Update the cached quadraui theme. Call once per frame from
    /// `paint`, before any `backend.draw_*` calls. Subsequent
    /// `draw_*` invocations consume the stored theme.
    pub fn set_current_theme(&mut self, theme: crate::Theme) {
        self.current_theme = theme;
    }

    /// Update the cached quadraui style. Call once per frame from
    /// `paint`, before any `backend.draw_*` calls. Subsequent
    /// `draw_*` invocations consume the stored style — currently only
    /// [`Self::draw_palette`] reads it, via
    /// [`crate::Style::backdrop_opacity`].
    pub fn set_current_style(&mut self, style: crate::Style) {
        self.current_style = style;
    }

    /// Widget zones registered via [`crate::Backend::register_zone`] during
    /// the current frame. Read by
    /// [`crate::tui::testing::TuiDriver::inventory`] to populate
    /// [`crate::testing::FrameInventory::zones`].
    pub(crate) fn zones(&self) -> &[ZoneRec] {
        &self.zones
    }

    /// The `(bar rect, resolved layout)` cached from the most recent
    /// `draw_tab_bar` call for tab bar `id` this frame, or `None` if that
    /// bar didn't paint this frame. See [`Self::tab_bar_layouts`]'s docs
    /// for the coordinate-space contract. Read by
    /// [`crate::tui::testing::TuiDriver::tab_center`] /
    /// [`crate::tui::testing::TuiDriver::tab_close_center`].
    pub(crate) fn cached_tab_bar_layout(&self, id: &WidgetId) -> Option<(QRect, &TabBarLayout)> {
        self.tab_bar_layouts
            .get(id)
            .map(|(rect, layout)| (*rect, layout))
    }

    // ── 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 `apply_selection_highlight`/`extract_selection_text`
    // (live-ratatui-buffer extraction, TUI-only — see that module's doc)
    // is a thin delegation.

    /// Every `TextRegion` registered so far this frame. Test-only: unlike
    /// `GtkBackend`'s twin (read by `gtk::run`/`GtkDriver`), nothing in the
    /// live TUI runner needs this outside `self` — [`Self::apply_dispatch`]
    /// reads `self.core.text_selection.text_regions` directly.
    #[cfg(test)]
    pub(crate) fn text_regions(&self) -> &[TextRegion] {
        &self.core.text_selection.text_regions
    }

    /// 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 the runner
    /// 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: Point,
        focus: Point,
    ) {
        self.core.set_active_text_selection(region, anchor, focus);
    }

    /// Clear the active text selection and, if a `TextSelection` drag is
    /// in progress, end it. Called by the runner on `MouseDown` or after
    /// Ctrl-C copies the selection.
    pub(crate) fn clear_text_selection(&mut self) {
        let mut drag_state = self.drag_state.borrow_mut();
        self.core.clear_text_selection(&mut drag_state);
    }

    /// Clear only the displayed selection highlight without touching drag
    /// state. Used by the run loop on `MouseDown` so that the drag just
    /// initiated by `dispatch_click` is not immediately cancelled.
    pub(crate) fn clear_selection_display(&mut self) {
        self.core.clear_selection_display();
    }

    /// End any in-progress `TextSelection` drag without clearing the
    /// displayed `active_selection`. Called by the `Backend` trait impl of
    /// [`Backend::cancel_text_selection_drag`] so apps can abort a
    /// speculative drag (started by `apply_dispatch` before the app had a
    /// chance to forward the click to a PTY) while preserving any
    /// previously finalised selection highlight on screen.
    fn cancel_text_selection_drag_impl(&mut self) {
        let mut drag_state = self.drag_state.borrow_mut();
        self.core.cancel_text_selection_drag(&mut drag_state);
    }

    /// Invert (highlight) the cells in the ratatui buffer that fall
    /// within the active text selection range, and cache the extracted
    /// text in `self.cached_selection_text`.
    ///
    /// Must be called inside `terminal.draw(|frame| …)` after
    /// `app.render`. The cache is necessary because ratatui swaps its
    /// double-buffer after `draw` returns, so `terminal.current_buffer_mut()`
    /// would return an empty buffer by the time Ctrl-C fires.
    pub(crate) fn apply_selection_highlight(&mut self, buf: &mut ratatui::buffer::Buffer) {
        let sel = match self.core.text_selection.active_text_selection() {
            Some(s) => s,
            None => return,
        };
        let region = match self.core.text_selection.find_region(&sel.region) {
            Some(r) => r,
            None => return,
        };
        let bounds = crate::event::Rect::new(
            region.bounds.x,
            region.bounds.y,
            region.bounds.width,
            region.bounds.height,
        );
        let ranges = crate::dispatch::text_selection_line_range(sel.anchor, sel.focus, bounds);
        let area = buf.area;

        // Cache text before inverting so we read the original cell content.
        // `text_selection_line_range` reports cell-space columns as f32;
        // TUI cells are always whole units, so round-trip
        // through `u16` for buffer indexing.
        let mut lines: Vec<String> = Vec::with_capacity(ranges.len());
        for &(row, col_start, col_end) in &ranges {
            if row >= area.y + area.height {
                continue;
            }
            let mut line = String::new();
            for col in (col_start as u16)..(col_end as u16) {
                if col < area.x + area.width {
                    line.push_str(buf[(col, row)].symbol());
                }
            }
            let trimmed = line.trim_end_matches(|c: char| c.is_whitespace() || c == '\0');
            lines.push(trimmed.to_string());
        }
        self.cached_selection_text = lines.join("\n");

        // Now invert cells for the highlight.
        for (row, col_start, col_end) in ranges {
            for col in (col_start as u16)..(col_end as u16) {
                if col < area.x + area.width && row < area.y + area.height {
                    let cell = &mut buf[(col, row)];
                    let fg = cell.fg;
                    let bg = cell.bg;
                    cell.fg = bg;
                    cell.bg = fg;
                }
            }
        }
    }

    /// Return a clone of the selection text cached by the last
    /// `apply_selection_highlight` call. Named `cached_selection_text`
    /// rather than `take_*` because the value is cloned, not consumed —
    /// the cache persists until the selection is cleared.
    pub(crate) fn cached_selection_text(&self) -> String {
        self.cached_selection_text.clone()
    }

    /// Take the editor cursor position cached by the most recent
    /// [`Backend::draw_editor`] call this frame, leaving `None` behind.
    ///
    /// Called by [`super::run::render_frame`] once per frame, after the
    /// render closure returns but still inside `terminal.draw(|frame| …)`,
    /// so it can apply `frame.set_cursor_position(pos)` — the only place
    /// with access to the real `Frame`. "Take" (not a plain
    /// getter) because the value is frame-scoped: [`Self::begin_frame`]
    /// clears it again before the next `draw_editor` call, so nothing relies
    /// on the value surviving past this one read.
    pub(crate) fn take_last_cursor_position(&mut self) -> Option<(u16, u16)> {
        self.last_cursor_position.take()
    }

    /// Set the active selection to cover the entire visible content of the
    /// most-recently focused `TextRegion`. Returns `true` when a region was
    /// found and the selection was set; `false` when no region can be
    /// resolved (zero registered regions, or multiple with no prior
    /// interaction).
    ///
    /// Target resolution order:
    /// 1. [`Self::last_text_region_id`] if the region is still registered
    ///    this frame.
    /// 2. The sole registered region (if exactly one exists).
    /// 3. Returns `false` — caller should fall through to the app.
    ///
    /// # Viewport-only limitation
    ///
    /// `TextRegion.bounds` is the painted viewport. For scrolled panels
    /// (e.g. long issue bodies) only the on-screen rows are selected.
    /// Full-document select-all requires `TextRegion` to carry
    /// total-content rows; a follow-up issue tracks this.
    ///
    /// # `last_text_region_id` persistence
    ///
    /// [`Self::last_text_region_id`] is intentionally NOT cleared on
    /// `clear_text_selection` / `clear_selection_display` so Ctrl-A
    /// still targets the right region after Ctrl-C or a plain click.
    /// A future multi-panel focus model may need to revise this.
    // TODO: full-document select-all requires TextRegion to carry
    // total-content rows; for now this selects only the visible
    // viewport (bounds).
    pub(crate) fn select_all_text_region(&mut self) -> bool {
        self.core.select_all_text_region()
    }

    /// `WidgetId` of the `ActivityBar` that declared
    /// `is_keyboard_focused = true` during the most recent render pass,
    /// if any. TUI itself never calls this: [`Self::apply_dispatch`] already
    /// redirects a focused bar's `KeyPressed` to `UiEvent::ActivityBar` one layer
    /// upstream of `dispatch_event`, so by the time an event reaches
    /// `preprocess_event` a `KeyPressed` on TUI never has a bar focused —
    /// the shared step's `KeyPressed` guard just never matches here. See
    /// `PreprocessBackend for TuiBackend`'s doc.
    pub(crate) fn focused_activity_bar_id(&self) -> Option<&WidgetId> {
        self.focused_activity_bar.as_ref()
    }

    /// Read the selected cells back from `buf`, trim trailing whitespace
    /// per line, and return the joined text (lines separated by `\n`).
    ///
    /// Falls back to an empty `String` when there is no active selection
    /// or the region id can no longer be found in the registered regions.
    ///
    /// Only used in tests — production code uses the text cached by
    /// `apply_selection_highlight` (the live buffer is unavailable after
    /// `terminal.draw` swaps ratatui's double-buffer).
    #[cfg(test)]
    pub(crate) fn extract_selection_text(&self, buf: &ratatui::buffer::Buffer) -> String {
        let sel = match self.core.text_selection.active_text_selection() {
            Some(s) => s,
            None => return String::new(),
        };
        let region = match self.core.text_selection.find_region(&sel.region) {
            Some(r) => r,
            None => return String::new(),
        };
        let bounds = crate::event::Rect::new(
            region.bounds.x,
            region.bounds.y,
            region.bounds.width,
            region.bounds.height,
        );
        let ranges = crate::dispatch::text_selection_line_range(sel.anchor, sel.focus, bounds);
        let area = buf.area;
        let mut lines: Vec<String> = Vec::with_capacity(ranges.len());
        for (row, col_start, col_end) in ranges {
            if row >= area.y + area.height {
                continue;
            }
            let mut line = String::new();
            for col in (col_start as u16)..(col_end as u16) {
                if col < area.x + area.width {
                    line.push_str(buf[(col, row)].symbol());
                }
            }
            // Trim trailing whitespace and NUL padding per line.
            let trimmed = line.trim_end_matches(|c: char| c.is_whitespace() || c == '\0');
            lines.push(trimmed.to_string());
        }
        lines.join("\n")
    }

    // ── Accelerators ───────────────────────────────────────────────────────

    /// Walk `events` and rewrite any `UiEvent::KeyPressed` whose key +
    /// modifiers match a registered `Global`-scope accelerator into
    /// `UiEvent::Accelerator(id, modifiers)`. Widget- and Mode-scoped
    /// accelerators are skipped here — the backend doesn't know which widget
    /// has focus or what mode the app is in. Apps that want those scopes match
    /// against `KeyPressed` themselves once they have that context.
    ///
    /// Run raw translated events through the dispatch layer so that
    /// `MouseDown` on a text region begins a `TextSelection` drag and
    /// `MouseMoved` (with button held) emits `TextSelectionChanged`.
    ///
    /// `MouseDown`/`MouseMoved`/`MouseUp` all route through
    /// [`crate::dispatch::route_pointer`] — the same one
    /// pointer-routing sequence `gtk::run`/`macos::run`/`win::run` use, so
    /// this is no longer a fourth from-scratch copy.
    ///
    /// # TODO: scrollbar dispatch
    ///
    /// Scroll-surface arbitration is not wired here yet — scroll surfaces
    /// are not registered per-frame by `TuiBackend`. `route_pointer` always
    /// passes an empty slice to `dispatch_click`'s `scroll_surfaces` param
    /// (see that function's doc), so text regions work correctly today and
    /// scrollbar drags are unaffected (they continue to be handled by
    /// app-side hit-tests as before). The consequence is that the
    /// "scrollbar wins over an overlapping text region" acceptance
    /// criterion is not enforced in TUI.
    fn apply_dispatch(&mut self, raw: Vec<UiEvent>) -> Vec<UiEvent> {
        let mut out = Vec::with_capacity(raw.len());
        for event in raw {
            match event {
                UiEvent::MouseDown { .. }
                | UiEvent::MouseMoved { .. }
                | UiEvent::MouseUp { .. } => {
                    let modal_stack = self.modal_stack.borrow();
                    let mut drag_state = self.drag_state.borrow_mut();
                    out.extend(crate::dispatch::route_pointer(
                        &modal_stack,
                        &mut drag_state,
                        &mut self.core.text_selection,
                        event,
                    ));
                }
                // When an ActivityBar has `is_keyboard_focused`, redirect
                // raw `KeyPressed` events to it so the app receives
                // `UiEvent::ActivityBar(id, KeyPressed { … })` instead of
                // `UiEvent::KeyPressed { … }`. This runs before the
                // accelerator pass so the bar can intercept any key.
                UiEvent::KeyPressed {
                    key,
                    modifiers,
                    repeat,
                } => {
                    if let Some(id) = self.focused_activity_bar {
                        let key_str =
                            crate::primitives::activity_bar::key_to_activity_bar_string(&key);
                        out.push(UiEvent::ActivityBar(
                            id,
                            crate::ActivityBarEvent::KeyPressed {
                                key: key_str,
                                modifiers,
                            },
                        ));
                    } else {
                        out.push(UiEvent::KeyPressed {
                            key,
                            modifiers,
                            repeat,
                        });
                    }
                }
                other => out.push(other),
            }
        }
        out
    }

    /// Run injected (synthetic) raw events through the same translation
    /// pipeline [`Backend::wait_events`] applies to crossterm input —
    /// drag-state dispatch, accelerator matching, double-click folding —
    /// minus the terminal read. Used by the headless
    /// [`super::testing::TuiDriver`] so scripted mouse drags exercise the
    /// real `DragState` / text-selection machinery instead of bypassing
    /// it. Mirrors [`Self::drain_native_batch`]'s post-read pipeline
    /// exactly.
    pub(crate) fn translate_injected(&mut self, raw: Vec<UiEvent>) -> Vec<UiEvent> {
        let mut out = self.apply_dispatch(raw);
        self.apply_accelerators(&mut out);
        if self.double_click_folding {
            self.double_click.process(&mut out);
        }
        out
    }

    /// Toggle whether [`Self::translate_injected`] folds a `MouseDown`
    /// into a `DoubleClick` when it lands within the detector's time/radius
    /// window of the previous one. Driver-facing knob for
    /// [`super::testing::TuiDriver::set_double_click_folding`]
    /// — disable it so a test that dispatches two deliberate single clicks
    /// in immediate succession gets two `MouseDown`s, not a coin-flip on
    /// wall-clock timing.
    pub(crate) fn set_double_click_folding(&mut self, enabled: bool) {
        self.double_click_folding = enabled;
    }

    /// Rewrite matching `UiEvent::KeyPressed` events as
    /// `UiEvent::Accelerator`. See [`crate::backend_core::BackendCore::apply_accelerators`].
    fn apply_accelerators(&self, events: &mut [UiEvent]) {
        self.core.apply_accelerators(events);
    }

    /// See [`crate::backend_core::BackendCore::match_keypress`].
    fn match_keypress(
        &self,
        key: &crate::Key,
        modifiers: crate::Modifiers,
    ) -> Option<AcceleratorId> {
        self.core.match_keypress(key, modifiers)
    }

    /// Delegates exactly one `ratatui::crossterm::event::poll(poll_timeout)`
    /// call, then — only if it reports readiness — drains and processes
    /// the resulting batch of native events. Shared by both
    /// [`Backend::wait_events`] outcomes that already know, by the time
    /// they call this, what to hand crossterm: `Duration::ZERO` when
    /// [`wait_for_stdin_ready`] already confirmed real data is queued
    /// with no hangup bit set (`StdinReadiness::Ready`), or the caller's
    /// own full `timeout` for the deliberate `Unguarded` fallback (a
    /// non-tty stdin, or a non-unix target) that still needs crossterm's
    /// own blocking wait. Both call sites share this one implementation.
    fn drain_native_batch(&mut self, poll_timeout: Duration) -> Vec<UiEvent> {
        match ratatui::crossterm::event::poll(poll_timeout) {
            Ok(true) => {}
            Ok(false) => {
                let mut out = Vec::new();
                self.user_events.drain_into(&mut out);
                return out;
            }
            // An error here isn't a confirmed hangup
            // (`wait_for_stdin_ready`'s own guard already catches that
            // case when it's active) — surface anything already queued
            // rather than retrying.
            Err(_) => {
                let mut out = Vec::new();
                self.user_events.drain_into(&mut out);
                return out;
            }
        }
        let mut raw = Vec::new();
        match ratatui::crossterm::event::read() {
            Ok(ev) => raw.extend(super::events::crossterm_to_uievents_scaled(
                ev,
                self.cell_pixel_size,
            )),
            Err(_) => {
                // Even a crossterm read error shouldn't drop a background wake that
                // arrived in the same window — still surface anything already queued.
                let mut out = Vec::new();
                self.user_events.drain_into(&mut out);
                return out;
            }
        }
        // Drain the rest of the queue without blocking.
        while ratatui::crossterm::event::poll(Duration::ZERO).unwrap_or(false) {
            match ratatui::crossterm::event::read() {
                Ok(ev) => raw.extend(super::events::crossterm_to_uievents_scaled(
                    ev,
                    self.cell_pixel_size,
                )),
                Err(_) => break,
            }
        }
        // See `recover_leaked_sgr_mouse_fragments`'s doc.
        let raw = recover_leaked_sgr_mouse_fragments(raw, self.cell_pixel_size);
        let coalesced = coalesce_mouse_moved(raw);
        let mut out = self.apply_dispatch(coalesced);
        self.apply_accelerators(&mut out);
        self.double_click.process(&mut out);
        self.user_events.drain_into(&mut out);
        out
    }
}

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

impl crate::runtime::PreprocessBackend for TuiBackend {
    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.cached_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)
    }

    /// No-op passthrough — see this impl block's own doc and
    /// `PreprocessBackend::fold_double_click`'s doc for why. TUI folds
    /// double-clicks earlier, once per batch of translated crossterm
    /// events in [`Self::translate_injected`]/`Backend::wait_events`
    /// (via [`Self::double_click`]'s own `DoubleClickDetector`), before
    /// any individual event reaches `dispatch_event`/`preprocess_event`.
    /// Folding again here — even against a *fresh* detector instance —
    /// would silently coin-flip on whichever fold ran first; reusing
    /// `self.double_click` instead would double-consume the same
    /// detector state the batch pass already advanced. Either way is
    /// wrong, so this stays a deliberate identity function.
    fn fold_double_click(&mut self, ev: UiEvent) -> UiEvent {
        ev
    }

    /// TUI-only override: tolerates a stray Shift and accepts `'C'` (CapsLock)
    /// as well as `'c'`. Real terminals attach modifier noise to Ctrl-C
    /// that the crate-wide strict default would silently drop, turning
    /// a real copy request into a no-op.
    fn is_copy_keypress(&self, key: &crate::Key, modifiers: &crate::Modifiers) -> bool {
        matches!(key, crate::Key::Char('c') | crate::Key::Char('C'))
            && modifiers.ctrl
            && !modifiers.alt
            && !modifiers.cmd
    }
}

/// Convert a [`crate::Rect`] (f32 coordinates) to a
/// [`ratatui::layout::Rect`] (u16). Any negative values clamp to 0;
/// fractional widths/heights round to nearest. Used by every trait
/// `draw_*` method to translate the trait's `Rect` argument.
fn q_rect_to_ratatui(r: QRect) -> Rect {
    let x = r.x.max(0.0).round() as u16;
    let y = r.y.max(0.0).round() as u16;
    let w = r.width.max(0.0).round() as u16;
    let h = r.height.max(0.0).round() as u16;
    Rect::new(x, y, w, h)
}

/// Shared tab-width measurement for [`TuiBackend::draw_tab_bar_with_chrome`]
/// and its glyph-override sibling. A bracket-framed active tab reserves
/// one extra column on each side of its ordinary close-column
/// reservation — see `tui::tab_bar`'s module doc for the cell-by-cell
/// breakdown — and a glyph override only ever substitutes a single-cell
/// glyph, never the reserved width, so both callers measure through this
/// one helper rather than two copies that could drift apart.
fn tab_bar_chrome_layout(bar: &TabBar, area: Rect, chrome: &TabChrome) -> TabBarLayout {
    let close_cols = if bar.show_tab_close {
        crate::tui::TAB_CLOSE_COLS as usize
    } else {
        0
    };
    let brackets = matches!(chrome.active_frame, TabFrame::Brackets);
    let tab_widths: Vec<usize> = bar
        .tabs
        .iter()
        .map(|t| {
            let has_close = bar.show_tab_close && t.is_closable;
            let is_bracket = brackets && t.is_active;
            let base = display_width(&t.label);
            if is_bracket && has_close {
                // '[' + glyph(1) + ']' , replacing the plain
                // glyph+separator reservation.
                base + 1 + 1 + 1
            } else if is_bracket {
                // '[' + ']' around a label with no close button.
                base + 2
            } else if has_close {
                base + close_cols
            } else {
                // No close button and no bracket framing to supply a
                // visual boundary — reserve a column for the separator
                // glyph so adjacent labels don't run together.
                base + crate::tui::TAB_SEPARATOR_COLS as usize
            }
        })
        .collect();
    bar.layout(
        area.width as f32,
        area.height as f32,
        0.0,
        |i| {
            let has_close = bar.show_tab_close && bar.tabs[i].is_closable;
            let is_bracket = brackets && bar.tabs[i].is_active;
            if is_bracket && has_close {
                crate::TabMeasure::new(tab_widths[i] as f32, 1.0).with_trailing(1.0)
            } else if has_close {
                crate::TabMeasure::new(tab_widths[i] as f32, close_cols as f32)
            } else {
                crate::TabMeasure::new(tab_widths[i] as f32, 0.0)
            }
        },
        |i| crate::SegmentMeasure::new(bar.right_segments[i].width_cells as f32),
    )
}

/// Reassemble one leaked SGR mouse escape sequence out of a run of
/// individual `KeyPressed(Char(_))` events, if `events[0]` opens one.
///
/// `events[0]` must already be `KeyPressed(Char('['))` — the caller checks
/// that cheaply before calling in. This confirms the very next event is
/// `Char('<')` (the SGR-extended marker; the legacy X10/`rxvt` mouse
/// encodings aren't affected by the race this recovers from, so they're
/// out of scope), then scans forward for a run of `Char(_)` events made
/// only of ASCII digits and `;`, terminated by `Char('M')` or `Char('m')`
/// — exactly the tail of `ESC [ < Cb ; Cx ; Cy (M|m)` with its leading
/// `ESC` already consumed. Any event that isn't a plain, non-repeat
/// `KeyPressed(Char(_))`, any character outside that alphabet, or running
/// past the bound before finding a terminator aborts the match (`None`) —
/// the run is left untouched as ordinary keystrokes.
///
/// See [`recover_leaked_sgr_mouse_fragments`] for why this exists at all.
/// `cell_size` is forwarded verbatim to [`decode_sgr_mouse_report`] — see
/// that function's doc.
fn try_reassemble_sgr_mouse(
    events: &[UiEvent],
    cell_size: TerminalCellSize,
) -> Option<(usize, UiEvent)> {
    let UiEvent::KeyPressed {
        key: crate::Key::Char('<'),
        repeat: false,
        ..
    } = events.get(1)?
    else {
        return None;
    };

    let mut body = String::new();
    let mut consumed = 2; // the '[' the caller matched, plus the '<' above.
    let mut terminator = None;
    // A real `Cb;Cx;Cy` triple never needs more than a handful of digits —
    // cap the scan well above that so a run of unrelated real keystrokes
    // (someone actually typing "<1234...") can't be walked indefinitely.
    for ev in events.iter().skip(2).take(24) {
        let UiEvent::KeyPressed {
            key: crate::Key::Char(c),
            repeat: false,
            ..
        } = ev
        else {
            return None;
        };
        consumed += 1;
        if *c == 'M' || *c == 'm' {
            terminator = Some(*c);
            break;
        }
        if c.is_ascii_digit() || *c == ';' {
            body.push(*c);
        } else {
            return None;
        }
    }
    let terminator = terminator?;

    let mut parts = body.split(';');
    let cb: u16 = parts.next()?.parse().ok()?;
    let x: u16 = parts.next()?.parse().ok()?;
    let y: u16 = parts.next()?.parse().ok()?;
    if parts.next().is_some() {
        return None;
    }

    let event = decode_sgr_mouse_report(cb, x, y, terminator == 'm', cell_size)?;
    Some((consumed, event))
}

/// Decode one already-parsed `Cb ; Cx ; Cy` SGR mouse triple into a
/// [`UiEvent`], via the same crossterm plumbing a well-formed escape
/// sequence would have used
/// ([`super::events::crossterm_mouse_to_uievent_scaled`]). `cell_size`
/// should be [`Self::cell_pixel_size`](TuiBackend::cell_pixel_size) when
/// this recovery path fires on a session with SGR-Pixels mode active,
/// or the identity `TerminalCellSize::new(1.0, 1.0)`
/// otherwise — this recovery path decodes raw `Cx`/`Cy` exactly as
/// received, whichever unit the terminal is actually reporting in.
///
/// The `Cb` bit layout replicated here (button number in bits 0–1 and
/// 6–7, drag flag in bit 5, modifiers in bits 2–4) is xterm's public SGR
/// mouse-tracking protocol, not a crossterm implementation detail — see
/// <http://www.xfree86.org/current/ctlseqs.html#Mouse%20Tracking> — so
/// this mirrors crossterm's own (private) `parse_cb` deliberately rather
/// than reusing it.
fn decode_sgr_mouse_report(
    cb: u16,
    x: u16,
    y: u16,
    is_release: bool,
    cell_size: TerminalCellSize,
) -> Option<UiEvent> {
    use ratatui::crossterm::event::{
        KeyModifiers, MouseButton as CtMouseButton, MouseEvent as CtMouseEvent, MouseEventKind,
    };

    let button_number = ((cb & 0b11) | ((cb & 0b1100_0000) >> 4)) as u8;
    let dragging = cb & 0b0010_0000 != 0;
    let mut modifiers = KeyModifiers::empty();
    if cb & 0b0000_0100 != 0 {
        modifiers |= KeyModifiers::SHIFT;
    }
    if cb & 0b0000_1000 != 0 {
        modifiers |= KeyModifiers::ALT;
    }
    if cb & 0b0001_0000 != 0 {
        modifiers |= KeyModifiers::CONTROL;
    }

    let kind = match (button_number, dragging) {
        (0, false) => MouseEventKind::Down(CtMouseButton::Left),
        (1, false) => MouseEventKind::Down(CtMouseButton::Middle),
        (2, false) => MouseEventKind::Down(CtMouseButton::Right),
        (0, true) => MouseEventKind::Drag(CtMouseButton::Left),
        (1, true) => MouseEventKind::Drag(CtMouseButton::Middle),
        (2, true) => MouseEventKind::Drag(CtMouseButton::Right),
        (3, false) => MouseEventKind::Up(CtMouseButton::Left),
        (3, true) | (4, true) | (5, true) => MouseEventKind::Moved,
        (4, false) => MouseEventKind::ScrollUp,
        (5, false) => MouseEventKind::ScrollDown,
        (6, false) => MouseEventKind::ScrollLeft,
        (7, false) => MouseEventKind::ScrollRight,
        _ => return None,
    };
    // SGR mode ends the sequence with lowercase `m` for a release, since
    // `Cb`'s button-3 slot can't otherwise distinguish which button went
    // up (mirrors crossterm's own `parse_csi_sgr_mouse`).
    let kind = if is_release {
        match kind {
            MouseEventKind::Down(b) => MouseEventKind::Up(b),
            other => other,
        }
    } else {
        kind
    };

    super::events::crossterm_mouse_to_uievent_scaled(
        CtMouseEvent {
            kind,
            column: x.saturating_sub(1),
            row: y.saturating_sub(1),
            modifiers,
        },
        cell_size,
    )
}

/// Recover an SGR mouse escape sequence that leaked into individual
/// `KeyPressed(Char(_))` events.
///
/// crossterm's own terminal-input reader disambiguates a lone `ESC` byte
/// by whether more bytes are *already* available in the same read — not
/// by waiting for them. When the OS delivers `ESC [ < Cb ; Cx ; Cy (M|m)`
/// (a real mouse-motion/click report) split across two reads right after
/// that leading `ESC` — which happens under perfectly ordinary scheduling
/// jitter, not just a contrived race — crossterm commits to "standalone
/// Escape key" for the lone byte and then decodes the *rest* of the
/// report byte-by-byte as ordinary printable characters, since `[` isn't
/// a recognised lead byte on its own. Observed live: the literal text
/// `[<35;10;5M` typed into whatever has focus, e.g. coord-tui's chat
/// input (see #293's repro). The `Escape` itself still fires correctly —
/// it's only the report's tail that leaks — but landing in a focused
/// `TextInput` right before it makes `Escape` look like it "didn't
/// register" (it cleared/typed-into the just-polluted field instead of
/// doing whatever an already-empty field would have triggered).
///
/// This can't be fixed by *not asking for* motion reports (mode 1003):
/// hover state ([`super::toolbar_hover_tracker`] and friends) is a real,
/// shipped TUI feature that depends on no-button `MouseMoved` events, so
/// disabling any-motion tracking would trade this bug for silently
/// breaking every hover affordance. Instead, this runs over each frame's
/// already-drained batch of native events (still the same-frame window
/// crossterm's own race lands in) and reconstitutes any leaked report
/// back into the mouse event it should have been — before
/// [`coalesce_mouse_moved`] and [`TuiBackend::apply_dispatch`] ever see
/// it, so a recovered event flows through the exact same pipeline a
/// cleanly decoded one would.
///
/// `cell_size` is forwarded to [`try_reassemble_sgr_mouse`]/
/// [`decode_sgr_mouse_report`] — pass
/// [`TuiBackend::cell_pixel_size`] so a leaked SGR-Pixels report recovers to
/// the same fractional coordinate a cleanly decoded one would have.
fn recover_leaked_sgr_mouse_fragments(
    events: Vec<UiEvent>,
    cell_size: TerminalCellSize,
) -> Vec<UiEvent> {
    let mut out = Vec::with_capacity(events.len());
    let mut i = 0;
    while i < events.len() {
        let opens_escape = matches!(
            events[i],
            UiEvent::KeyPressed {
                key: crate::Key::Char('['),
                repeat: false,
                ..
            }
        );
        if opens_escape {
            if let Some((consumed, mouse_event)) = try_reassemble_sgr_mouse(&events[i..], cell_size)
            {
                out.push(mouse_event);
                i += consumed;
                continue;
            }
        }
        out.push(events[i].clone());
        i += 1;
    }
    out
}

/// Coalesce consecutive `MouseMoved` events in a raw batch, keeping only
/// the last in each consecutive run.  A non-`MouseMoved` event breaks a
/// run; the flushed move and the other event are both preserved in order.
///
/// Applied before [`TuiBackend::apply_dispatch`] so that a burst of N
/// `MouseMoved` events (e.g. a fast drag) results in a single
/// `dispatch_mouse_drag` call at the final cursor position, preventing N
/// redundant selection updates or SGR-cursor writes to embedded PTYs.
///
/// # Ordering guarantee
///
/// `MouseDown … MouseMoved* … MouseUp` bursts survive intact — only
/// intermediate positions within a consecutive run are elided.
fn coalesce_mouse_moved(raw: Vec<UiEvent>) -> Vec<UiEvent> {
    let mut out = Vec::with_capacity(raw.len());
    let mut pending_move: Option<UiEvent> = None;
    for ev in raw {
        match ev {
            UiEvent::MouseMoved { .. } => {
                // Replace pending move with the newer position.
                pending_move = Some(ev);
            }
            other => {
                // Flush the pending move before the non-move event so
                // ordering is preserved (e.g. MouseDown before MouseMoved).
                if let Some(m) = pending_move.take() {
                    out.push(m);
                }
                out.push(other);
            }
        }
    }
    // Flush any trailing move (common case: burst ends with a move).
    if let Some(m) = pending_move.take() {
        out.push(m);
    }
    out
}

// `TuiBackend::wait_events` never slices its idle wait into fixed-size
// chunks with a `stdin_hung_up` re-check *between* them. Crossterm's own
// dead-pty busy-loop, once entered, never returns — so a hangup landing
// while a delegated crossterm call is already blocked inside it stays
// invisible for the entire remaining life of that call, which, if the
// hangup is what would wake it, is unbounded.
//
// `wait_for_stdin_ready` (below in this file) closes that window rather
// than merely narrowing it: `wait_events` never hands crossterm a
// blocking call at all. It blocks on this crate's *own* `poll(2)` call
// against the exact same fd, for the caller's real remaining timeout,
// and only ever delegates to crossterm with `Duration::ZERO`
// (guaranteed non-blocking) once that call has already confirmed
// `POLLIN` with no hangup bit set. A hangup that lands while
// `wait_for_stdin_ready`'s own `poll(2)` call is blocked is exactly the
// event that wakes it — the kernel reports `POLLHUP` on a hung-up fd
// the instant it happens, not on some later sampling interval, so there
// is no window for a hangup to land invisibly.

/// Outcome of a single [`poll_fd_revents`] call. Splitting `Interrupted`
/// out from `Error` lets [`wait_for_stdin_ready`]'s retry loop treat
/// `EINTR` (worth retrying — a signal says nothing about the fd) and a
/// persistent `poll(2)` failure (never worth retrying — the fd, or
/// `poll(2)` itself, is broken, and looping on it would spin for the
/// rest of the deadline, or forever with no deadline at all)
/// differently. [`stdin_hung_up`] and `caps::query_sgr_pixel_decrqm`
/// don't loop on a single call, so they fold all three non-`Ready`
/// outcomes into "no readiness information yet" via
/// [`PollOutcome::revents`].
#[cfg(unix)]
pub(crate) enum PollOutcome {
    /// `poll(2)` reported the fd ready; the bitmask it set.
    Ready(libc::c_short),
    /// `poll(2)` reached `timeout_ms` with the fd never ready.
    TimedOut,
    /// `poll(2)` itself failed with `EINTR` — a signal arrived, not a
    /// fact about the fd.
    Interrupted,
    /// `poll(2)` itself failed with anything other than `EINTR`.
    Error,
}

#[cfg(unix)]
impl PollOutcome {
    /// Collapse `TimedOut`/`Interrupted`/`Error` into `None` for a caller
    /// that makes a single call and doesn't need to tell them apart.
    pub(crate) fn revents(self) -> Option<libc::c_short> {
        match self {
            PollOutcome::Ready(revents) => Some(revents),
            PollOutcome::TimedOut | PollOutcome::Interrupted | PollOutcome::Error => None,
        }
    }
}

/// Poll `fd` for up to `timeout_ms` milliseconds (`0` is a non-blocking
/// readiness check, never a wait). See [`PollOutcome`] for what each
/// result means.
#[cfg(unix)]
pub(crate) fn poll_fd_revents(fd: std::os::unix::io::RawFd, timeout_ms: i32) -> PollOutcome {
    let mut pollfd = libc::pollfd {
        fd,
        events: libc::POLLIN,
        revents: 0,
    };
    // SAFETY: `pollfd` is a single valid `libc::pollfd` on the stack;
    // `poll(2)` only reads/writes through the pointer+length (1) it's
    // given, for the duration of this call.
    let ready = unsafe { libc::poll(&mut pollfd, 1, timeout_ms) };
    if ready == 0 {
        return PollOutcome::TimedOut;
    }
    if ready < 0 {
        return if std::io::Error::last_os_error().kind() == std::io::ErrorKind::Interrupted {
            PollOutcome::Interrupted
        } else {
            PollOutcome::Error
        };
    }
    PollOutcome::Ready(pollfd.revents)
}

/// Dead-PTY busy-loop guard — a workaround for a real
/// third-party defect in crossterm, kept here until crossterm's own
/// `UnixInternalEventSource` breaks out of its TTY-readiness read loop
/// on `Ok(0)` (EOF) the same way it already does on
/// `ErrorKind::WouldBlock`; remove this guard once that lands and this
/// crate's crossterm pin picks it up.
///
/// `pub(crate)`: every call site in this crate that delegates to a
/// crossterm function able to reach `try_read` needs this same check
/// first, not just [`TuiBackend::poll_events`]/[`TuiBackend::wait_events`]
/// below — currently also `caps::probe_kitty_keyboard` (a *different*
/// crossterm entry point, `supports_keyboard_enhancement`, which reaches
/// the identical vulnerable loop via its own internal `poll_internal`/
/// `read_internal`, not through this backend at all) and
/// `services::next_dialog_events`'s nested dialog loop.
///
/// crossterm 0.29's unix event source
/// (`UnixInternalEventSource::try_read`, `src/event/source/unix/mio.rs`)
/// has that read loop with no break arm for `Ok(0)` — it falls through
/// with no break and no event, so the loop calls `read()` again
/// immediately. Once a pty's master side is fully closed, every
/// `read()` on the slave returns `Ok(0)` forever (confirmed empirically
/// — Linux does **not** turn this into an `EIO`), and mio's own
/// `poll()` keeps reporting the fd "ready" regardless of requested
/// timeout (a hangup condition is always "ready" to `poll(2)`/`epoll`).
/// The result is a genuine, unbounded, un-rate-limited spin inside
/// `crossterm::event::poll`/`read` with **no way for the caller to
/// interrupt it** — once that call is made, control never returns to
/// us.
///
/// This matters specifically for a pty that was never the process's
/// *controlling* terminal (no implicit `SIGHUP` backstop on hangup —
/// e.g. a pty wired up via `std::process::Command` without `setsid`/
/// `TIOCSCTTY`, which is exactly what drives a headless `vcd` session).
/// A real controlling terminal's hangup kills the process outright via
/// the default `SIGHUP` disposition, long before this code would ever
/// run.
///
/// The fix lives here, not in crossterm (third-party; this defect has
/// not been filed against crossterm upstream as of this writing —
/// filing it is an operator decision, and this guard stands on its own
/// regardless of whether that happens): check *our own* `poll(2)` on
/// the fd, non-blocking, **before** ever calling into
/// `ratatui::crossterm::event::poll`/`read`. Any of `POLLHUP`/
/// `POLLERR`/`POLLNVAL` means "this fd's far end is gone and it will
/// never produce another real event" — crossterm is never entered at
/// all once this check has run and seen the hangup, which is what makes
/// this a guard rather than a mitigation for every check that observes
/// it. [`TuiBackend::poll_events`] calls this directly, non-blocking,
/// because it never blocks at all (it only drains what crossterm
/// already has queued) — there is no window to close there in the
/// first place. [`TuiBackend::wait_events`], which *does* need to
/// block, never calls this function's non-blocking form in a loop
/// around a delegated crossterm call — see [`wait_for_stdin_ready`]
/// below, which performs the same `isatty`/`EIO`/`poll(2)` judgement
/// but blocks *itself*, on this crate's own `poll(2)` syscall, for the
/// caller's real remaining timeout, so a hangup that lands while idle
/// is the very thing that wakes it rather than something it has to
/// race a delegated crossterm call to notice.
///
/// Only guards when stdin is itself the terminal (`isatty(0)`), with one
/// deliberate exception: on Linux, closing a pty's master side runs
/// `tty_vhangup()` on the slave, which swaps in `hung_up_tty_fops` —
/// every ioctl on that fd, including the `TCGETS` that `isatty` performs
/// under the hood, then fails with `EIO`, so `isatty` itself reports
/// "not a tty" at exactly the moment this guard most needs it to say the
/// opposite. Treating a bare `isatty` failure as "stdin isn't a tty" is
/// therefore wrong for that one case; this function keeps checking when
/// `isatty` failed with `EIO` specifically, and only backs off for every
/// other failure (`ENOTTY`, `EINVAL`, `EBADF` — a pipe, a regular file, a
/// closed fd — none of which `tty_vhangup` ever produces). Those other
/// failures are the case crossterm's own `tty_fd()`
/// (`src/terminal/sys/file_descriptor.rs`) also treats as "not a tty": it
/// borrows fd 0 when `isatty` succeeds and opens `/dev/tty` directly
/// otherwise, so polling fd 0 unconditionally there would make a hangup
/// decision about a fd crossterm may not even be reading from — e.g.
/// stdin redirected from a pipe whose writer already exited, with a
/// perfectly live controlling terminal still open on `/dev/tty`. This
/// does not extend to covering a dead `/dev/tty` when stdin isn't a tty
/// at all, which stays out of scope here.
///
/// `POLLIN` is not a useful signal to subtract from the hangup check
/// above. A real macOS repro (`posix_openpt`/`grantpt`/`unlockpt`,
/// close the master, `poll()` the slave with zero bytes ever written in
/// either direction) shows `revents` coming back `POLLIN | POLLHUP` —
/// `0x11` — even though there is nothing to read at all. `POLLIN` means
/// "a `read()` would not block," and a read that returns `Ok(0)` (EOF)
/// satisfies that exactly as much as a read that returns real bytes —
/// `poll(2)` cannot tell the two apart, only an actual `read()` call
/// can, and this function deliberately never performs one (see below).
/// So this guard cannot promise delivery of a few legitimate bytes that
/// happened to be queued in the exact instant the far end hung up; it
/// promises no busy-spin, ever, on either Unix platform this crate
/// targets — a strictly better outcome than calling into crossterm to
/// find out which case it was, which is itself the unbounded-hang risk.
///
/// Deliberately **not** a raw `read()` probe instead of `poll()`: doing
/// our own `read()` here would, on every ordinary non-hungup call (i.e.
/// nearly all of them), either race crossterm's own read of the exact
/// same fd or require re-implementing crossterm's ANSI parser to avoid
/// dropping whatever bytes we stole from it. `poll()` is non-destructive
/// — it never consumes a byte — which is exactly why it's safe to call
/// on *every* `poll_events`/`wait_events` invocation, not just a
/// suspected-dead one.
///
/// Returns `false` (never guards) when `poll(2)` itself times out or
/// errors (e.g. `EINTR`) — neither is a confirmed hangup, and the normal
/// crossterm path handles both already.
#[cfg(unix)]
pub(crate) fn stdin_hung_up() -> bool {
    use std::os::unix::io::AsRawFd;

    if !stdin_guard_active() {
        return false;
    }

    let stdin = std::io::stdin();
    let fd = stdin.as_raw_fd();
    match poll_fd_revents(fd, 0).revents() {
        Some(revents) => revents & (libc::POLLHUP | libc::POLLERR | libc::POLLNVAL) != 0,
        None => false,
    }
}

/// Non-unix hosts (Windows, via ConPTY) use a completely different
/// crossterm event source (`src/event/sys/windows`, native console
/// input APIs) that doesn't share this `read()`-loop shape at all. Never
/// guards there.
#[cfg(not(unix))]
pub(crate) fn stdin_hung_up() -> bool {
    false
}

/// Whether this crate can make a reliable hang-up judgement about
/// `STDIN_FILENO` at all — the `isatty(0)` check plus the one
/// deliberate `EIO` exception, shared by [`stdin_hung_up`] (non-blocking
/// form, above) and [`wait_for_stdin_ready`] (blocking form, below) so
/// the two can never drift apart on which fds they're willing to guard.
/// See `stdin_hung_up`'s doc for the full rationale — in short: only
/// when stdin is itself a tty, *except* that a vhangup'd pty slave fails
/// `isatty`'s underlying `TCGETS` ioctl with `EIO` rather than reporting
/// "not a tty" the ordinary way, so that specific failure is kept in
/// rather than treated as "back off."
#[cfg(unix)]
fn stdin_guard_active() -> bool {
    // SAFETY: `isatty` only reads the fd-number argument; no pointer
    // involved.
    let is_tty = unsafe { libc::isatty(libc::STDIN_FILENO) } == 1;
    is_tty || std::io::Error::last_os_error().raw_os_error() == Some(libc::EIO)
}

/// Outcome of [`wait_for_stdin_ready`] — what [`TuiBackend::wait_events`]
/// (and `TuiPlatformServices::next_dialog_events` in `super::services`)
/// does next, instead of ever handing crossterm a blocking call itself.
#[cfg_attr(not(unix), allow(dead_code))]
pub(crate) enum StdinReadiness {
    /// `poll(2)` reported the fd readable with no hangup bit set. Safe
    /// to delegate exactly one `Duration::ZERO` (non-blocking)
    /// `ratatui::crossterm::event::poll`/`read` pair — but `POLLIN`
    /// alone can't distinguish real bytes from an EOF read that simply
    /// hasn't set a hangup bit yet (see [`stdin_hung_up`]'s doc), so the
    /// delegated call isn't guaranteed to produce a complete event.
    /// [`TuiBackend::wait_events`] re-polls on an empty drain rather
    /// than assuming one is always there.
    Ready,
    /// stdin's far end is permanently gone — see [`stdin_hung_up`]'s doc.
    HungUp,
    /// Neither of the above happened before the requested deadline.
    TimedOut,
    /// This crate has no reliable hang-up signal for the current fd
    /// (non-tty stdin that isn't the `tty_vhangup` `EIO` case, or a
    /// non-unix target). The caller should fall back to delegating the
    /// *entire* wait straight to crossterm, exactly as it would without
    /// this guard existing at all — see [`stdin_guard_active`]'s doc for
    /// why this is deliberately scoped to ttys, and the
    /// `#[cfg(not(unix))]` arm below for why non-unix targets are
    /// unconditionally unguarded.
    Unguarded,
}

/// Blocks — via this crate's own `poll(2)` on `STDIN_FILENO`, never by
/// delegating to crossterm — until stdin becomes ready, hangs up, or
/// `deadline` passes, whichever comes first. [`TuiBackend::wait_events`]
/// never slices its idle wait into fixed chunks with a
/// [`stdin_hung_up`] re-check between them: a hang-up is visible to
/// `poll(2)` **the instant it happens**, even while a call is already
/// parked in the kernel waiting on it, so the hang-up itself is the
/// wakeup rather than something a later poll has to happen to
/// re-discover. Contrast crossterm's own reactor, which (per
/// [`stdin_hung_up`]'s doc) can enter a state it never returns from once
/// it starts reading a hung-up fd — this function never calls into that
/// code path at all when it detects the hangup itself.
///
/// `deadline`: `None` blocks indefinitely — still immediately
/// interruptible by a hangup, since `-1` is `poll(2)`'s ordinary "no
/// timeout" request, not a special case this function has to retry
/// around. `Some` blocks until that `Instant`, retrying around `EINTR`
/// (a signal is not a confirmed hangup, nor a confirmed timeout)
/// without ever blocking past it.
#[cfg(unix)]
pub(crate) fn wait_for_stdin_ready(deadline: Option<Instant>) -> StdinReadiness {
    use std::os::unix::io::AsRawFd;

    if !stdin_guard_active() {
        return StdinReadiness::Unguarded;
    }

    let fd = std::io::stdin().as_raw_fd();
    loop {
        let (timeout_ms, at_or_past_deadline) = match deadline {
            Some(deadline) => {
                let remaining = deadline.saturating_duration_since(Instant::now());
                // Round up rather than truncate: a sub-millisecond
                // remainder would otherwise become a `poll(fd, 0)) while
                // `at_or_past_deadline` is still `false`, producing a
                // tight retry spin for that last fractional millisecond.
                let ms =
                    remaining.as_millis() + u128::from(remaining.subsec_nanos() % 1_000_000 != 0);
                let clamped_ms = if ms > i32::MAX as u128 {
                    i32::MAX
                } else {
                    ms as i32
                };
                (clamped_ms, remaining.is_zero())
            }
            // `-1` to `poll(2)` blocks indefinitely — still woken
            // instantly by a hangup, so there is nothing to retry or
            // bound here.
            None => (-1, false),
        };
        match poll_fd_revents(fd, timeout_ms) {
            PollOutcome::Ready(revents) => {
                return if revents & (libc::POLLHUP | libc::POLLERR | libc::POLLNVAL) != 0 {
                    StdinReadiness::HungUp
                } else {
                    StdinReadiness::Ready
                };
            }
            PollOutcome::TimedOut | PollOutcome::Interrupted => {
                // A genuine timeout confirms nothing beyond "not yet";
                // `EINTR` confirms even less (a signal arrived, not a
                // fact about the fd) — both are worth retrying for
                // whatever time is left, or indefinitely when `deadline`
                // is `None`. Once `deadline` (when given) has passed,
                // that's a real timeout.
                if at_or_past_deadline {
                    return StdinReadiness::TimedOut;
                }
                continue;
            }
            // `poll(2)` itself failed with something other than
            // `EINTR` — a persistent condition (e.g. a bad fd) that
            // retrying would not resolve. Give up rather than spin for
            // the rest of the deadline (or forever, when there is none).
            PollOutcome::Error => return StdinReadiness::TimedOut,
        }
    }
}

/// Non-unix hosts never guard — see [`stdin_hung_up`]'s `#[cfg(not(unix))]`
/// doc. `wait_events` falls back to delegating the whole wait straight
/// to crossterm there.
#[cfg(not(unix))]
pub(crate) fn wait_for_stdin_ready(_deadline: Option<Instant>) -> StdinReadiness {
    StdinReadiness::Unguarded
}

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

impl Backend for TuiBackend {
    fn viewport(&self) -> Viewport {
        self.viewport
    }

    fn begin_frame(&mut self, viewport: Viewport) {
        self.viewport = viewport;
        // Clear per-frame text regions so stale registrations from the
        // previous frame don't linger.
        self.core.begin_frame();
        // Clear per-frame widget zones for the same reason. Same
        // lifecycle as text_regions.
        self.zones.clear();
        // Clear the focused activity bar — re-set by draw_activity_bar
        // during the render pass if still focused.
        self.focused_activity_bar = None;
        // Clear the cached editor cursor position — re-set by draw_editor
        // during the render pass if an editor paints this frame. Without
        // this a frame that stops painting an editor (e.g. it's hidden)
        // would keep showing the terminal cursor at the last-known spot.
        self.last_cursor_position = None;
        // Clear per-frame tab-bar layout cache for the same reason as
        // `zones` — a bar that stops painting must stop resolving
        // `tab_center`/`tab_close_center` too.
        self.tab_bar_layouts.clear();
        // Clear last frame's modal paint marks so this frame has
        // to earn them again (via draw_dialog/draw_palette/draw_context_menu).
        self.modal_stack.borrow_mut().reset_frame_paint();
    }

    fn register_text_region(&mut self, region: TextRegion) {
        self.core.register_text_region(region);
    }

    fn register_zone(&mut self, id: WidgetId, bounds: QRect) {
        self.zones.push(ZoneRec { id, bounds });
    }

    fn cancel_text_selection_drag(&mut self) {
        self.cancel_text_selection_drag_impl();
    }

    fn end_frame(&mut self) {
        // No-op. The frame's actual flush happens when ratatui's
        // `terminal.draw(|frame| …)` closure returns; this method
        // exists for parity with backends that need explicit flush.
        //
        // In debug builds, warn about any modal that's registered
        // in the ModalStack (and therefore hit-testable) but that this
        // frame's `AppLogic::render` never painted — the "registered but
        // invisible" defect class made detectable instead
        // of silently shipping.
        #[cfg(debug_assertions)]
        for id in self.modal_stack.borrow().unpainted_ids() {
            crate::diagnostics::emit(crate::modal_stack::ModalStack::unpainted_modal_message(&id));
        }
    }

    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
    }

    fn set_nerd_fonts(&mut self, enabled: bool) {
        self.nerd_fonts_enabled = enabled;
    }

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

    fn poll_events(&mut self) -> Vec<UiEvent> {
        // Refuse to delegate into crossterm at all once the input fd has
        // hung up with nothing left to read — see `stdin_hung_up`'s doc
        // for why entering crossterm's own poll/read here risks an
        // unbounded busy-spin we have no way to interrupt once inside
        // it.
        if stdin_hung_up() {
            self.input_gone = true;
            let mut out = Vec::new();
            self.user_events.drain_into(&mut out);
            return out;
        }
        // Drain every queued crossterm event; never blocks. Each native event
        // translates to zero, one, or more `UiEvent`s via
        // [`super::events::crossterm_to_uievents_scaled`] (dividing a mouse
        // report's raw `column`/`row` by `self.cell_pixel_size` — the identity
        // divisor unless SGR-Pixels mode is active), then runs through the dispatch
        // layer (text-region hit-test, drag state) and [`Self::apply_accelerators`].
        // Consecutive `MouseMoved` events are coalesced to the final position
        // before dispatch.
        let mut raw = Vec::new();
        while ratatui::crossterm::event::poll(Duration::ZERO).unwrap_or(false) {
            match ratatui::crossterm::event::read() {
                Ok(ev) => raw.extend(super::events::crossterm_to_uievents_scaled(
                    ev,
                    self.cell_pixel_size,
                )),
                Err(_) => break,
            }
        }
        // See `recover_leaked_sgr_mouse_fragments`'s doc: recover
        // any SGR mouse report that crossterm's own reader split around
        // its leading `ESC`, before it reaches coalescing/dispatch as
        // stray printable characters.
        let raw = recover_leaked_sgr_mouse_fragments(raw, self.cell_pixel_size);
        let coalesced = coalesce_mouse_moved(raw);
        let mut out = self.apply_dispatch(coalesced);
        self.apply_accelerators(&mut out);
        self.double_click.process(&mut out);
        // Fold in any `UiEvent::User` payloads a background thread queued via
        // `waker()` since the last drain. Unconditional (not gated on `raw` being
        // non-empty) so a background-only wake with no concurrent keyboard/mouse
        // activity still surfaces here.
        self.user_events.drain_into(&mut out);
        out
    }

    fn wait_events(&mut self, timeout: Duration) -> Vec<UiEvent> {
        // Already latched by an earlier call. A caller going through
        // `TuiRunner::run_one` never gets here again (it checks
        // `input_gone()` and exits first), but a host embedding
        // `TuiRunner` that calls `pump` directly and ignores both
        // `StepOutcome::Exited` and `input_gone()` would otherwise call
        // `stdin_hung_up()` below — a zero-timeout, instant-return
        // poll(2) — in a tight loop regardless of the `timeout` it
        // passed in. Honour `timeout` here instead, so that caller
        // sleeps rather than spinning at full CPU.
        if self.input_gone {
            if !timeout.is_zero() {
                std::thread::sleep(timeout);
            }
            let mut out = Vec::new();
            self.user_events.drain_into(&mut out);
            return out;
        }
        // Crossterm buffers any native event it reads but doesn't match
        // during a filtered read (e.g. the cursor-position / keyboard-
        // enhancement / DECRQM probes this crate's own capability
        // negotiation performs) and its own `poll` consults that buffer
        // before ever touching the fd again — so a real keypress/resize/
        // paste can already be sitting there with the fd itself fully
        // drained. A non-blocking drain here surfaces exactly that case
        // before this function ever blocks on the fd below; a hangup
        // still takes priority and ends the wait outright rather than
        // risking a delegated crossterm call against a hung-up fd.
        if stdin_hung_up() {
            self.input_gone = true;
            let mut out = Vec::new();
            self.user_events.drain_into(&mut out);
            return out;
        }
        let immediate = self.drain_native_batch(Duration::ZERO);
        if !immediate.is_empty() {
            return immediate;
        }

        // Block up to `timeout` for the first native event, then drain
        // the remainder of the queue non-blocking so a burst of events
        // (e.g. a fast mouse drag) is processed in a single frame instead
        // of one event per render cycle.  Consecutive `MouseMoved` events
        // are coalesced to the final position before dispatch, preventing
        // N redundant selection updates or SGR-cursor writes to embedded
        // PTYs.  Returns an empty `Vec` on timeout.
        //
        // This never hands crossterm a blocking call. Instead it blocks
        // on this crate's own [`wait_for_stdin_ready`] — a direct
        // `poll(2)` on the exact same fd — for the real remaining
        // timeout, and only ever delegates to crossterm with
        // `Duration::ZERO` once that call has already confirmed data is
        // queued with no hangup bit set. See that function's doc for why
        // this makes the hangup itself the wakeup instead of racing a
        // periodic re-check against an in-flight crossterm call.
        //
        // `checked_add` rather than a bare `Instant + Duration`: this is
        // a public trait method a consumer can call with any `Duration`
        // up to `Duration::MAX`, and that addition panics on overflow.
        // `None` (overflowed) is treated as "no deadline" below —
        // [`wait_for_stdin_ready`] blocks indefinitely in that case,
        // still immediately interruptible by a hangup.
        let deadline = Instant::now().checked_add(timeout);
        // `wait_for_stdin_ready` itself blocks for the *entire* deadline
        // (retrying only around `EINTR`), so no surrounding loop is
        // needed to reach that deadline — only the `Ready` arm below
        // loops, and only to retry a readiness signal that didn't yield
        // a complete event.
        loop {
            match wait_for_stdin_ready(deadline) {
                StdinReadiness::HungUp => {
                    self.input_gone = true;
                    let mut out = Vec::new();
                    self.user_events.drain_into(&mut out);
                    return out;
                }
                StdinReadiness::TimedOut => {
                    // Crossterm timed out with no native input, but a background thread may
                    // have called `waker()` during the wait — this is the primary path a pure
                    // background-thread wake takes, since it has no crossterm event of its own
                    // to ride in on.
                    let mut out = Vec::new();
                    self.user_events.drain_into(&mut out);
                    return out;
                }
                StdinReadiness::Ready => {
                    // Already confirmed queued and hangup-free —
                    // `Duration::ZERO` here is guaranteed non-blocking.
                    // A readiness signal doesn't always carry a complete
                    // event (e.g. a split escape/SGR-mouse sequence
                    // crossterm's reader read half of) — when the drain
                    // comes back empty, loop back and wait out whatever
                    // of `deadline` remains instead of returning early.
                    let out = self.drain_native_batch(Duration::ZERO);
                    if out.is_empty() {
                        continue;
                    }
                    return out;
                }
                // No reliable hangup signal for this fd (non-tty stdin
                // outside the `tty_vhangup` `EIO` case, or a non-unix
                // target) — fall back to delegating the whole wait
                // straight to crossterm. `wait_for_stdin_ready` returns
                // this immediately (it never blocks on the `Unguarded`
                // path), so `timeout` itself — not a recomputed
                // remainder — is still the right duration to hand
                // crossterm here.
                StdinReadiness::Unguarded => return self.drain_native_batch(timeout),
            }
        }
    }

    /// See [`crate::Backend::waker`]'s doc for the full cross-backend
    /// contract. TUI's implementation is the simplest of the four: the
    /// live runner's `wait_events` call already blocks for at most
    /// [`super::run::POLL_TIMEOUT`] (16ms) before looping back around, so
    /// feeding the payload into [`Self::user_events`] — drained
    /// unconditionally by both [`Self::poll_events`] and
    /// [`Self::wait_events`] above — is sufficient on its own; there is no
    /// blocking native read to interrupt the way GTK/macOS/Windows have.
    fn waker(&self) -> std::sync::Arc<dyn Fn(crate::UserPayload) + Send + Sync> {
        let queue = std::sync::Arc::clone(&self.user_events);
        std::sync::Arc::new(move |payload: crate::UserPayload| {
            queue.push(payload.into_arc());
        })
    }

    fn request_frame_in(&self, delay: Duration) {
        // See `crate::runtime::FrameScheduler`'s doc: TUI has no native
        // run loop to arm a timer against, so this just records the
        // deadline; the live runner (`tui::run::run_inner`) folds it into
        // its next `wait_events` timeout via `Self::frame_poll_timeout`/
        // `Self::clear_frame_deadline_if_due`. `TuiDriver`'s headless
        // loop is scripted rather than timer-driven, so it doesn't
        // consult this at all — a test that wants to observe a
        // `RedrawAfter` chain calls `AppLogic::tick` directly instead.
        self.frame_scheduler.request(delay);
    }

    /// Sets [`Self::full_repaint_requested`], consumed by
    /// [`Self::take_full_repaint_requested`] right before the next frame
    /// paints — see [`crate::Backend::request_full_repaint`]'s doc for
    /// the full contract and why TUI is the one backend that needs this
    fn request_full_repaint(&mut self) {
        self.full_repaint_requested = true;
    }

    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);
    }

    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: QRect) {
        let theme = self.current_theme;
        let area = q_rect_to_ratatui(rect);
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_focus_ring called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::draw_focus_ring(frame.buffer_mut(), area, &theme);
        // A chrome-only paint (no text of its own) is only "observable" via a
        // registered zone — mirrors `draw_terminal_divider`'s identical
        // registration above.
        self.register_zone(WidgetId::new("chrome:focus-ring"), rect);
    }

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

    /// Honest per-method, not aspirational.
    ///
    /// - `mouse` / `scroll` / `drag`: `tui::run` sends crossterm's
    ///   `EnableMouseCapture` on entry, and
    ///   `tui::events::crossterm_mouse_to_uievent` maps
    ///   `MouseEventKind::{Down,Up,Drag,ScrollUp,ScrollDown,…}` to the
    ///   matching `UiEvent`, so all three input kinds are real *when this
    ///   backend type's usual runner is used*. This is a static
    ///   per-backend-type fact, not this session's actual configuration —
    ///   see [`Self::mouse_enabled`] for the runtime answer:
    ///   `tui::run::run_with(app, RunConfig { mouse: false, .. })`
    ///   (`no-mouse` mode, quadraui#828, for hosts where capture is
    ///   refused or unavailable) never negotiates capture with the
    ///   terminal at all, so no mouse-derived `UiEvent` ever arrives that
    ///   session even though this field still reads `true` — the same
    ///   split [`Self::kitty_keyboard`] already draws between "can this
    ///   backend type" and "is it active right now".
    /// - `text_selection`: `register_text_region` /
    ///   `cancel_text_selection_drag` are both overridden below —
    ///   mouse-drag selection highlight is real. Also reachable with no
    ///   mouse at all, via Ctrl-A (select-all) plus Ctrl-C (see
    ///   `crate::runtime::preprocess_event`'s Ctrl-A interception) — the
    ///   `no-mouse` mode key path for Tier-1's drag-select gesture.
    /// - `notifications`: **deliberately still `false`**, even though
    ///   `TuiPlatformServices::send_notification` is no
    ///   longer a no-op — it now makes a genuine best-effort attempt (OSC
    ///   9/777 escape plus a native `osascript`/`notify-send` fallback;
    ///   see that method's doc and the module doc's "Notifications"
    ///   section). The reason this flag stays `false` anyway:
    ///   [`crate::compose::notification::notify_or_toast`] branches on exactly
    ///   this bit to decide whether it may skip its guaranteed, always-
    ///   visible, hit-testable in-canvas `Toast` degrade. Both of
    ///   `send_notification`'s legs are silent on failure — no OSC-
    ///   capable terminal *and* no `notify-send`/`osascript` on the
    ///   `$PATH` is the ordinary case for a vanilla terminal or a
    ///   headless/CI container, which is a far more common way to run
    ///   this backend than GTK or a native macOS/Windows app is to run
    ///   without *any* desktop notification facility at all. Reporting
    ///   `true` here would let `notify_or_toast` swap a guaranteed toast
    ///   for a coin flip that can silently deliver nothing, which is a
    ///   regression, not an upgrade, for that class of host. Apps that
    ///   want the best-effort native/OSC path specifically (accepting
    ///   the silent-failure risk) can still call
    ///   [`crate::backend::PlatformServices::send_notification`]
    ///   directly — this flag only gates the `notify_or_toast` helper's
    ///   choice, not the method's availability.
    /// - everything else: **not** declared. No window to
    ///   drag/resize/maximize, no native pointer glyph, no native menu,
    ///   no IME positioning, and every `PlatformServices` dialog method
    ///   unconditionally returns `None`
    ///   (`TuiPlatformServices::show_file_open_dialog` /
    ///   `show_file_save_dialog` / `show_folder_open_dialog` /
    ///   `show_message_dialog`). The in-canvas `Dialog` primitive
    ///   (`draw_dialog`) stays the only dialog path on this backend,
    ///   same posture for `folder_dialogs`:
    ///   hosts keep whatever in-canvas picker they
    ///   already have.
    fn backend_caps(&self) -> crate::backend::BackendCaps {
        crate::backend::BackendCaps {
            mouse: true,
            scroll: true,
            drag: true,
            text_selection: true,
            // `window` is overridden below and always returns `Some` —
            // see `impl WindowControl for TuiBackend`'s doc for why
            // `set_title` (OSC 0/2 via crossterm's `SetTitle`) is the one
            // genuine capability behind it, with every other
            // `WindowControl` method staying `Unsupported` on a backend
            // with no OS window.
            window_control: true,
            // `notifications` deliberately stays `false` — see this
            // method's doc above for why a real `send_notification`
            // implementation doesn't earn this flag on this backend.
            color_depth: self.color_depth,
            kitty_keyboard: self.kitty_keyboard,
            sgr_pixel_mouse: self.sgr_pixel_mouse,
            ..crate::backend::BackendCaps::empty()
        }
    }

    fn line_height(&self) -> f32 {
        1.0
    }

    fn char_width(&self) -> f32 {
        1.0
    }

    /// One terminal cell, same as [`Self::char_width`] — `draw_list`
    /// paints every row on the same fixed character grid `char_width`
    /// measures, so there is no mismatch on TUI: a column is a column
    /// regardless of which primitive it belongs to.
    fn list_char_width(&self) -> f32 {
        1.0
    }

    /// `role` is ignored — a terminal cell grid has one font by
    /// definition (see [`crate::FontRole`]'s module doc) — and `height`
    /// is always one cell. `width` is [`display_width`]'s cell count,
    /// the same value every TUI layout already derived from
    /// `char_width() * text.chars().count()` before this method existed
    /// (TUI's story is "degrade", i.e. stay char-cell while GUI backends
    /// go proportional — this call site is bit-for-bit unchanged).
    fn measure_text(&self, text: &str, _role: crate::FontRole) -> (f32, f32) {
        (display_width(text) as f32, 1.0)
    }

    /// All-sentinel — see [`crate::backend::PlatformFontDefaults`]'s
    /// doc: a terminal cell grid has no font concept to default, the
    /// same structural reason [`Self::set_editor_font`]/
    /// [`Self::set_ui_font`] take the trait's no-op default here. Use
    /// [`Self::line_height`]/[`Self::char_width`] for the real
    /// fixed-cell metrics instead.
    fn default_fonts(&self) -> crate::backend::PlatformFontDefaults {
        crate::backend::PlatformFontDefaults {
            editor_family: String::new(),
            editor_size_pt: 0.0,
            ui_family: String::new(),
            ui_size_pt: 0.0,
        }
    }

    /// TUI's terminal scrollbar gutter is one character cell, not GTK's
    /// 8px default — matching `src/tui/terminal.rs`'s
    /// `sb_cols: … .unwrap_or(1)` default.
    fn terminal_scrollbar_default_width(&self) -> f32 {
        1.0
    }

    fn snap_height(&self, h: f32) -> f32 {
        // Mirrors the height component of `q_rect_to_ratatui` exactly —
        // same `.max(0.0).round()` — so a height computed via this method
        // always matches what a rect with that height paints as. A unit
        // test below pins the two against each other so they can't drift
        h.max(0.0).round()
    }

    /// `draw_context_menu` paints the menu's border on a whole cell
    /// outside `layout.bounds`, one cell on every side — a one-character
    /// reservation on each viewport edge keeps that border cell on-screen
    /// when the menu is anchored flush against any of them.
    fn context_menu_border_inset(&self) -> f32 {
        super::context_menu::BORDER_INSET
    }

    // ─── Drawing ───────────────────────────────────────────────────────────
    //
    // Implementations call into the public `crate::tui::draw_*` free
    // functions; this trait impl is the thin wrapper. The frame is
    // stashed by `enter_frame_scope`; the theme by `set_current_theme`.
    // Calling these outside `enter_frame_scope` is a programmer error: a
    // `debug_assert!` makes it loud in dev builds, per
    // `current_frame_mut`'s doc; release builds degrade instead of
    // aborting — a void method silently skips the paint, a
    // layout-returning method falls back to its pure `*_layout`/
    // `*_hits`-style twin (or an already-computed local `layout`) so a
    // host that queries geometry still gets a real answer, and
    // `draw_minimap`/`draw_image` report `painted: false`/`Unsupported`
    // exactly as their "no rasteriser available" paths already do
    // elsewhere.

    fn draw_tree(&mut self, rect: QRect, tree: &TreeView) {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let nerd_fonts = self.nerd_fonts_enabled;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_tree called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::draw_tree(frame.buffer_mut(), area, tree, &theme, nerd_fonts);
    }

    fn draw_list(&mut self, rect: QRect, list: &ListView) {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let nerd_fonts = self.nerd_fonts_enabled;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_list called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::draw_list(frame.buffer_mut(), area, list, &theme, nerd_fonts);
    }

    fn draw_data_table(
        &mut self,
        rect: QRect,
        table: &crate::DataTable,
        hovered_idx: Option<usize>,
    ) -> crate::DataTableLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_data_table called outside enter_frame_scope"
            );
            return self.data_table_layout(rect, table);
        };
        crate::tui::draw_data_table(frame.buffer_mut(), area, table, &theme, hovered_idx)
    }

    fn draw_data_table_with_glyphs(
        &mut self,
        rect: QRect,
        table: &crate::DataTable,
        hovered_idx: Option<usize>,
        glyphs: Option<&crate::primitives::data_table::DataTableGlyphs>,
    ) -> crate::DataTableLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let nerd_fonts = self.nerd_fonts_enabled;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_data_table_with_glyphs called outside enter_frame_scope"
            );
            return self.data_table_layout(rect, table);
        };
        crate::tui::draw_data_table_with_glyphs(
            frame.buffer_mut(),
            area,
            table,
            &theme,
            hovered_idx,
            glyphs,
            nerd_fonts,
        )
    }

    fn data_table_layout(&self, rect: QRect, table: &crate::DataTable) -> crate::DataTableLayout {
        // Must go through the same resolver `draw_data_table` uses — in
        // particular the cell-granular `h_scroll.round()`. This is the
        // cache-free, layout-on-demand path real apps hit-test through, so
        // resolving the geometry independently here can cause fractional
        // `h_scroll` mismatches.
        let area = q_rect_to_ratatui(rect);
        crate::tui::data_table_layout(area, table)
    }

    fn list_hscrollbar(&self, rect: QRect, list: &ListView) -> Option<crate::Scrollbar> {
        // Snap through the same u16 cell truncation `draw_list` uses so
        // the consumer's thumb hit-region matches the painted thumb.
        let area = q_rect_to_ratatui(rect);
        list.hscrollbar(
            crate::event::Rect::new(
                area.x as f32,
                area.y as f32,
                area.width as f32,
                area.height as f32,
            ),
            1.0,
        )
    }

    fn list_vscrollbar(&self, rect: QRect, list: &ListView) -> Option<crate::Scrollbar> {
        // Snap through the same u16 cell truncation `draw_list` uses so
        // the consumer's thumb hit-region matches the painted thumb.
        let area = q_rect_to_ratatui(rect);
        list.vscrollbar(
            crate::event::Rect::new(
                area.x as f32,
                area.y as f32,
                area.width as f32,
                area.height as f32,
            ),
            1.0,
        )
    }

    fn list_layout(&self, rect: QRect, list: &ListView) -> crate::ListViewLayout {
        crate::tui::tui_list_layout(q_rect_to_ratatui(rect), list)
    }

    fn draw_form(&mut self, rect: QRect, form: &Form) {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_form called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::draw_form(frame.buffer_mut(), area, form, &theme);
    }

    fn draw_palette(&mut self, rect: QRect, palette: &Palette) {
        // Mark before borrowing the frame — a modal-stack entry
        // whose id matches this palette is now known-painted this frame.
        self.modal_stack.borrow_mut().mark_painted(&palette.id);
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let style = self.current_style;
        let nerd_fonts = self.nerd_fonts_enabled;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_palette called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::draw_palette_with_style(
            frame.buffer_mut(),
            area,
            palette,
            &theme,
            &style,
            nerd_fonts,
        );
    }

    fn palette_layout(&self, rect: QRect, palette: &Palette) -> crate::PaletteLayout {
        crate::tui::tui_palette_layout(q_rect_to_ratatui(rect), palette)
    }

    fn draw_settings_chrome(
        &mut self,
        rect: QRect,
        header_text: &str,
        query: &str,
        placeholder: &str,
        active: bool,
    ) {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_settings_chrome called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::draw_settings_chrome(
            frame.buffer_mut(),
            area,
            header_text,
            query,
            placeholder,
            active,
            &theme,
        );
    }

    // ─── Layout-passthrough primitives — Stage 3 / trait migration ──────
    //
    // These take a pre-computed `*Layout` in their existing TUI
    // shims. Migrating them through the trait needs either the
    // trait to take `&Layout` (per `docs/decisions/BACKEND_TRAIT_PROPOSAL.md` §6.2)
    // or a per-method recompute. Deferred until Stage 3.

    // Phase B.5b Stage 9: trait extended with `&Layout` parameters
    // per `docs/decisions/BACKEND_TRAIT_PROPOSAL.md` §6.2. The TUI free functions
    // for these primitives take `&Layout` directly — the trait impls
    // are now thin pass-throughs, mirroring the GTK impls in
    // `gtk/backend.rs`.

    fn draw_status_bar_interactive(
        &mut self,
        rect: QRect,
        bar: &StatusBar,
        interaction: &crate::interaction::InteractionState,
    ) -> crate::StatusBarLayout {
        let (hovered_id, pressed_id) = (interaction.hovered(), interaction.pressed());
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let layout = bar.layout(area.width as f32, 1.0, MIN_GAP_CELLS, |seg| {
            crate::StatusSegmentMeasure::new(seg.text.chars().count() as f32)
        });
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_status_bar called outside enter_frame_scope"
            );
            return layout;
        };
        crate::tui::draw_status_bar(
            frame.buffer_mut(),
            area,
            bar,
            &layout,
            &theme,
            hovered_id,
            pressed_id,
        )
    }

    #[allow(deprecated)] // returns the deprecated `TabBarHits` — issue #823
    fn draw_tab_bar(
        &mut self,
        rect: QRect,
        bar: &TabBar,
        hovered_close_tab: Option<usize>,
    ) -> crate::TabBarHits {
        // Icon-less bars are the empty-sidecar case of the icon path, so
        // there is exactly one measurer + one paint loop to keep in sync.
        self.draw_tab_bar_icons(rect, bar, &[], hovered_close_tab)
    }

    /// Issue #919's `TabBarLayout`-returning counterpart to
    /// [`Self::draw_tab_bar`] above — same icon-less-sidecar delegation.
    fn draw_tab_bar_layout(
        &mut self,
        rect: QRect,
        bar: &TabBar,
        hovered_close_tab: Option<usize>,
    ) -> TabBarLayout {
        self.draw_tab_bar_icons_layout(rect, bar, &[], hovered_close_tab)
    }

    #[allow(deprecated)] // returns the deprecated `TabBarHits` — issue #823
    fn draw_tab_bar_icons(
        &mut self,
        rect: QRect,
        bar: &TabBar,
        icons: &[Option<crate::TabIcon>],
        _hovered_close_tab: Option<usize>,
    ) -> crate::TabBarHits {
        // TUI doesn't render close-button hover bg; the parameter is
        // accepted for trait parity with GTK.
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        // Cell-unit measurer mirrors `render_impl::render_tab_bar`.
        // Respect per-tab `is_closable`: non-closable tabs get no close-column
        // reservation even when `show_tab_close` is set on the bar.
        let close_cols = if bar.show_tab_close {
            crate::tui::TAB_CLOSE_COLS as usize
        } else {
            0
        };
        // Measure in display columns, not `char`s — a CJK/emoji
        // glyph occupies two columns, and `draw_tab_bar_icons` paints
        // with `char_cell_width` strides, so the budget must agree. Also
        // add `tab_icon_cols` so a tab's optional icon glyph + gap
        // is reserved the same way the GTK rasteriser reserves its own
        // Pango-measured icon width.
        let tab_widths: Vec<usize> = bar
            .tabs
            .iter()
            .enumerate()
            .map(|(i, t)| {
                let tab_close = if bar.show_tab_close && t.is_closable {
                    close_cols
                } else {
                    0
                };
                // No close button to reserve? Reserve a separator column
                // instead, so adjacent labels on a bar with
                // `show_tab_close: false` (or a non-closable tab) paint
                // with a visible boundary rather than running together.
                let sep = if tab_close == 0 {
                    crate::tui::TAB_SEPARATOR_COLS as usize
                } else {
                    0
                };
                display_width(&t.label) + tab_close + sep + crate::tab_icon_cols(icons, i) as usize
            })
            .collect();
        let layout = bar.layout(
            area.width as f32,
            area.height as f32,
            0.0, // no scroll arrows in TUI
            |i| {
                let tab_close_cols = if bar.show_tab_close && bar.tabs[i].is_closable {
                    close_cols
                } else {
                    0
                };
                crate::TabMeasure::new(tab_widths[i] as f32, tab_close_cols as f32)
            },
            |i| crate::SegmentMeasure::new(bar.right_segments[i].width_cells as f32),
        );
        // Cache the resolved layout for this bar's WidgetId before it's
        // consumed below — `TuiDriver::tab_center`/`tab_close_center`
        // resolve against this, since a driver sitting
        // outside the app has no other way to reach a specific tab's
        // geometry (every tab paints the same close glyph, so `find`
        // can't disambiguate tab N's target).
        self.tab_bar_layouts.insert(bar.id, (rect, layout.clone()));
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_tab_bar called outside enter_frame_scope"
            );
            // `tab_bar_layout_icons` is the pure (no-frame) twin that resolves the
            // identical `TabBarHits` geometry.
            return self.tab_bar_layout_icons(rect, bar, icons);
        };
        crate::tui::draw_tab_bar_icons(frame.buffer_mut(), area, bar, icons, &layout, &theme)
    }

    /// Issue #919's `TabBarLayout`-returning counterpart to
    /// [`Self::draw_tab_bar_icons`] above. Computes the identical
    /// `layout` that method's paint loop consumes, paints from it via
    /// the same [`crate::tui::draw_tab_bar_icons`] call (discarding its
    /// `TabBarHits` return value — this method's contract is the
    /// `TabBarLayout` it hands back instead), and caches it under
    /// `bar.id` exactly as [`Self::draw_tab_bar_icons`] does, so
    /// `TuiDriver::tab_center`/`tab_close_center` keep working
    /// regardless of which of the two paint entry points a caller used
    /// this frame.
    fn draw_tab_bar_icons_layout(
        &mut self,
        rect: QRect,
        bar: &TabBar,
        icons: &[Option<crate::TabIcon>],
        _hovered_close_tab: Option<usize>,
    ) -> TabBarLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let close_cols = if bar.show_tab_close {
            crate::tui::TAB_CLOSE_COLS as usize
        } else {
            0
        };
        let tab_widths: Vec<usize> = bar
            .tabs
            .iter()
            .enumerate()
            .map(|(i, t)| {
                let tab_close = if bar.show_tab_close && t.is_closable {
                    close_cols
                } else {
                    0
                };
                // No close button to reserve? Reserve a separator column
                // instead, so adjacent labels on a bar with
                // `show_tab_close: false` (or a non-closable tab) paint
                // with a visible boundary rather than running together.
                let sep = if tab_close == 0 {
                    crate::tui::TAB_SEPARATOR_COLS as usize
                } else {
                    0
                };
                display_width(&t.label) + tab_close + sep + crate::tab_icon_cols(icons, i) as usize
            })
            .collect();
        let layout = bar.layout(
            area.width as f32,
            area.height as f32,
            0.0,
            |i| {
                let tab_close_cols = if bar.show_tab_close && bar.tabs[i].is_closable {
                    close_cols
                } else {
                    0
                };
                crate::TabMeasure::new(tab_widths[i] as f32, tab_close_cols as f32)
            },
            |i| crate::SegmentMeasure::new(bar.right_segments[i].width_cells as f32),
        );
        self.tab_bar_layouts.insert(bar.id, (rect, layout.clone()));
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_tab_bar_icons_layout called outside enter_frame_scope"
            );
            return layout;
        };
        #[allow(deprecated)] // discarded `TabBarHits` — issue #823
        let _ =
            crate::tui::draw_tab_bar_icons(frame.buffer_mut(), area, bar, icons, &layout, &theme);
        layout
    }

    #[allow(deprecated)] // returns the deprecated `TabBarHits` — issue #823
    fn draw_tab_bar_with_chrome(
        &mut self,
        rect: QRect,
        bar: &TabBar,
        _hovered_close_tab: Option<usize>,
        chrome: &TabChrome,
    ) -> crate::TabBarHits {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let layout = tab_bar_chrome_layout(bar, area, chrome);
        self.tab_bar_layouts.insert(bar.id, (rect, layout.clone()));
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_tab_bar_with_chrome called outside enter_frame_scope"
            );
            // `tab_bar_layout_with_chrome` is the pure (no-frame) twin that resolves
            // the identical `TabBarHits` geometry, brackets included.
            return self.tab_bar_layout_with_chrome(rect, bar, chrome);
        };
        crate::tui::draw_tab_bar_with_chrome(frame.buffer_mut(), area, bar, chrome, &layout, &theme)
    }

    /// [`Self::draw_tab_bar_with_chrome`] plus an optional
    /// [`crate::primitives::tab_bar::TabBarGlyphs`] override for the
    /// close/dirty marks, honoured in full here (unlike the trait
    /// default, which ignores `glyphs`).
    ///
    /// Shares [`tab_bar_chrome_layout`] with [`Self::draw_tab_bar_with_chrome`]
    /// — an override only ever substitutes a single-cell glyph, it never
    /// changes a tab's reserved width — so the two methods measure through
    /// the same helper rather than risking the arithmetic drifting apart.
    #[allow(deprecated)] // returns the deprecated `TabBarHits` — issue #823
    fn draw_tab_bar_with_chrome_and_glyphs(
        &mut self,
        rect: QRect,
        bar: &TabBar,
        _hovered_close_tab: Option<usize>,
        chrome: &TabChrome,
        glyphs: Option<&crate::primitives::tab_bar::TabBarGlyphs>,
    ) -> crate::TabBarHits {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let nerd_fonts = self.nerd_fonts_enabled;
        let layout = tab_bar_chrome_layout(bar, area, chrome);
        self.tab_bar_layouts.insert(bar.id, (rect, layout.clone()));
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_tab_bar_with_chrome_and_glyphs called outside enter_frame_scope"
            );
            return self.tab_bar_layout_with_chrome(rect, bar, chrome);
        };
        crate::tui::draw_tab_bar_icons_with_chrome_and_glyphs(
            frame.buffer_mut(),
            area,
            bar,
            &[],
            chrome,
            &layout,
            &theme,
            glyphs,
            nerd_fonts,
        )
    }

    /// Issue #919's `TabBarLayout`-returning counterpart to
    /// [`Self::draw_tab_bar_with_chrome`] above — overridden (rather than
    /// taking the trait default) because TUI, like GTK, honours
    /// [`crate::TabFrame::Brackets`] and must reserve the same
    /// bracket-widened columns its Hits-returning sibling does.
    fn draw_tab_bar_with_chrome_layout(
        &mut self,
        rect: QRect,
        bar: &TabBar,
        _hovered_close_tab: Option<usize>,
        chrome: &TabChrome,
    ) -> TabBarLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let close_cols = if bar.show_tab_close {
            crate::tui::TAB_CLOSE_COLS as usize
        } else {
            0
        };
        let brackets = matches!(chrome.active_frame, TabFrame::Brackets);
        let tab_widths: Vec<usize> = bar
            .tabs
            .iter()
            .map(|t| {
                let has_close = bar.show_tab_close && t.is_closable;
                let is_bracket = brackets && t.is_active;
                let base = display_width(&t.label);
                if is_bracket && has_close {
                    base + 1 + 1 + 1
                } else if is_bracket {
                    base + 2
                } else if has_close {
                    base + close_cols
                } else {
                    // No close button and no bracket framing to supply a
                    // visual boundary — reserve a column for the separator
                    // glyph so adjacent labels don't run together.
                    base + crate::tui::TAB_SEPARATOR_COLS as usize
                }
            })
            .collect();
        let layout = bar.layout(
            area.width as f32,
            area.height as f32,
            0.0,
            |i| {
                let has_close = bar.show_tab_close && bar.tabs[i].is_closable;
                let is_bracket = brackets && bar.tabs[i].is_active;
                if is_bracket && has_close {
                    crate::TabMeasure::new(tab_widths[i] as f32, 1.0).with_trailing(1.0)
                } else if has_close {
                    crate::TabMeasure::new(tab_widths[i] as f32, close_cols as f32)
                } else {
                    crate::TabMeasure::new(tab_widths[i] as f32, 0.0)
                }
            },
            |i| crate::SegmentMeasure::new(bar.right_segments[i].width_cells as f32),
        );
        self.tab_bar_layouts.insert(bar.id, (rect, layout.clone()));
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_tab_bar_with_chrome_layout called outside enter_frame_scope"
            );
            return layout;
        };
        #[allow(deprecated)] // discarded `TabBarHits` — issue #823
        let _ = crate::tui::draw_tab_bar_with_chrome(
            frame.buffer_mut(),
            area,
            bar,
            chrome,
            &layout,
            &theme,
        );
        layout
    }

    fn draw_activity_bar(
        &mut self,
        rect: QRect,
        bar: &ActivityBar,
        hovered_idx: Option<usize>,
    ) -> Vec<crate::ActivityBarRowHit> {
        // Track keyboard focus: if this bar declares `is_keyboard_focused`,
        // record its id so `apply_dispatch` can convert incoming `KeyPressed`
        // events to `UiEvent::ActivityBar(id, KeyPressed { … })`.
        if bar.is_keyboard_focused {
            self.focused_activity_bar = Some(bar.id);
        }
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let nerd_fonts = self.nerd_fonts_enabled;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_activity_bar called outside enter_frame_scope"
            );
            return self.activity_bar_layout(rect, bar);
        };
        crate::tui::draw_activity_bar(
            frame.buffer_mut(),
            area,
            bar,
            &theme,
            hovered_idx,
            nerd_fonts,
        )
    }

    fn draw_activity_bar_with_style(
        &mut self,
        rect: QRect,
        bar: &ActivityBar,
        hovered_idx: Option<usize>,
        style: &crate::ActivityBarStyle,
    ) -> Vec<crate::ActivityBarRowHit> {
        // Track keyboard focus: if this bar declares `is_keyboard_focused`,
        // record its id so `apply_dispatch` can convert incoming `KeyPressed`
        // events to `UiEvent::ActivityBar(id, KeyPressed { … })`.
        if bar.is_keyboard_focused {
            self.focused_activity_bar = Some(bar.id);
        }
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let nerd_fonts = self.nerd_fonts_enabled;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_activity_bar_with_style called outside enter_frame_scope"
            );
            return self.activity_bar_layout(rect, bar);
        };
        crate::tui::draw_activity_bar_with_style(
            frame.buffer_mut(),
            area,
            bar,
            style,
            &theme,
            hovered_idx,
            nerd_fonts,
        )
    }

    fn status_bar_layout(&self, rect: QRect, bar: &StatusBar) -> crate::StatusBarLayout {
        bar.layout(rect.width, 1.0, MIN_GAP_CELLS, |seg| {
            crate::StatusSegmentMeasure::new(seg.text.chars().count() as f32)
        })
    }

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

    /// Issue #919's `TabBarLayout`-returning counterpart to
    /// [`Self::tab_bar_layout`] above.
    fn resolve_tab_bar_layout(&self, rect: QRect, bar: &TabBar) -> TabBarLayout {
        self.resolve_tab_bar_layout_icons(rect, bar, &[])
    }

    #[allow(deprecated)] // returns the deprecated `TabBarHits` — issue #823
    fn tab_bar_layout_icons(
        &self,
        rect: QRect,
        bar: &TabBar,
        icons: &[Option<crate::TabIcon>],
    ) -> crate::TabBarHits {
        let close_cols = if bar.show_tab_close {
            crate::tui::TAB_CLOSE_COLS as usize
        } else {
            0
        };
        // Compute per-tab widths respecting `is_closable`: non-closable tabs
        // get no close-column reservation even when `show_tab_close` is set.
        // Measured in display columns, not `char`s — see the twin
        // computation in `draw_tab_bar_icons` above for why. The
        // `tab_icon_cols` term is that twin's too: the no-paint
        // path must reserve the icon exactly as the paint does, or click
        // routing lands left of the glyphs the user sees.
        let tab_widths: Vec<usize> = bar
            .tabs
            .iter()
            .enumerate()
            .map(|(i, t)| {
                let tab_close = if bar.show_tab_close && t.is_closable {
                    close_cols
                } else {
                    0
                };
                // No close button to reserve? Reserve a separator column
                // instead, so adjacent labels on a bar with
                // `show_tab_close: false` (or a non-closable tab) paint
                // with a visible boundary rather than running together.
                let sep = if tab_close == 0 {
                    crate::tui::TAB_SEPARATOR_COLS as usize
                } else {
                    0
                };
                display_width(&t.label) + tab_close + sep + crate::tab_icon_cols(icons, i) as usize
            })
            .collect();
        let layout = bar.layout(
            rect.width,
            rect.height,
            0.0,
            |i| {
                let tab_close_cols = if bar.show_tab_close && bar.tabs[i].is_closable {
                    close_cols
                } else {
                    0
                };
                crate::TabMeasure::new(tab_widths[i] as f32, tab_close_cols as f32)
            },
            |i| crate::SegmentMeasure::new(bar.right_segments[i].width_cells as f32),
        );

        let mut hits = tab_bar_hits_from_layout(&layout, bar);
        // `TabBarHits` are target-surface (absolute) coordinates per the
        // trait doc — the same space `draw_tab_bar` returns. Without this
        // the no-paint path returned bar-relative x, off by `rect.x`
        // (nonzero for any tab bar right of a sidebar). Issue #552.
        crate::backend::shift_tab_bar_hits(&mut hits, rect.x as f64);

        let active_idx = bar.tabs.iter().position(|t| t.is_active);
        let reserved: usize = bar
            .right_segments
            .iter()
            .map(|s| s.width_cells as usize)
            .sum();
        let effective_tab_area = (rect.width as usize).saturating_sub(reserved);

        hits.correct_scroll_offset = if let Some(active) = active_idx {
            TabBar::fit_active_scroll_offset(active, bar.tabs.len(), effective_tab_area, |i| {
                tab_widths[i]
            })
        } else {
            bar.scroll_offset
        };

        hits
    }

    /// Issue #919's `TabBarLayout`-returning counterpart to
    /// [`Self::tab_bar_layout_icons`] above. Computes the exact same
    /// `layout` that method narrows down to `TabBarHits` and returns it
    /// verbatim, bar-relative (not shifted by `rect.x`, unlike the
    /// `TabBarHits` twin — see [`crate::Backend::resolve_tab_bar_layout`]'s
    /// doc for why).
    fn resolve_tab_bar_layout_icons(
        &self,
        rect: QRect,
        bar: &TabBar,
        icons: &[Option<crate::TabIcon>],
    ) -> TabBarLayout {
        let close_cols = if bar.show_tab_close {
            crate::tui::TAB_CLOSE_COLS as usize
        } else {
            0
        };
        let tab_widths: Vec<usize> = bar
            .tabs
            .iter()
            .enumerate()
            .map(|(i, t)| {
                let tab_close = if bar.show_tab_close && t.is_closable {
                    close_cols
                } else {
                    0
                };
                // No close button to reserve? Reserve a separator column
                // instead, so adjacent labels on a bar with
                // `show_tab_close: false` (or a non-closable tab) paint
                // with a visible boundary rather than running together.
                let sep = if tab_close == 0 {
                    crate::tui::TAB_SEPARATOR_COLS as usize
                } else {
                    0
                };
                display_width(&t.label) + tab_close + sep + crate::tab_icon_cols(icons, i) as usize
            })
            .collect();
        bar.layout(
            rect.width,
            rect.height,
            0.0,
            |i| {
                let tab_close_cols = if bar.show_tab_close && bar.tabs[i].is_closable {
                    close_cols
                } else {
                    0
                };
                crate::TabMeasure::new(tab_widths[i] as f32, tab_close_cols as f32)
            },
            |i| crate::SegmentMeasure::new(bar.right_segments[i].width_cells as f32),
        )
    }

    #[allow(deprecated)] // returns the deprecated `TabBarHits` — issue #823
    fn tab_bar_layout_with_chrome(
        &self,
        rect: QRect,
        bar: &TabBar,
        chrome: &TabChrome,
    ) -> crate::TabBarHits {
        let close_cols = if bar.show_tab_close {
            crate::tui::TAB_CLOSE_COLS as usize
        } else {
            0
        };
        let brackets = matches!(chrome.active_frame, TabFrame::Brackets);
        // Mirrors `draw_tab_bar_with_chrome`'s measurer exactly — the
        // no-paint twin must reserve the same columns the paint path did.
        let tab_widths: Vec<usize> = bar
            .tabs
            .iter()
            .map(|t| {
                let has_close = bar.show_tab_close && t.is_closable;
                let is_bracket = brackets && t.is_active;
                let base = display_width(&t.label);
                if is_bracket && has_close {
                    base + 1 + 1 + 1
                } else if is_bracket {
                    base + 2
                } else if has_close {
                    base + close_cols
                } else {
                    // No close button and no bracket framing to supply a
                    // visual boundary — reserve a column for the separator
                    // glyph so adjacent labels don't run together.
                    base + crate::tui::TAB_SEPARATOR_COLS as usize
                }
            })
            .collect();
        let layout = bar.layout(
            rect.width,
            rect.height,
            0.0,
            |i| {
                let has_close = bar.show_tab_close && bar.tabs[i].is_closable;
                let is_bracket = brackets && bar.tabs[i].is_active;
                if is_bracket && has_close {
                    crate::TabMeasure::new(tab_widths[i] as f32, 1.0).with_trailing(1.0)
                } else if has_close {
                    crate::TabMeasure::new(tab_widths[i] as f32, close_cols as f32)
                } else {
                    crate::TabMeasure::new(tab_widths[i] as f32, 0.0)
                }
            },
            |i| crate::SegmentMeasure::new(bar.right_segments[i].width_cells as f32),
        );

        let mut hits = tab_bar_hits_from_layout(&layout, bar);
        crate::backend::shift_tab_bar_hits(&mut hits, rect.x as f64);

        let active_idx = bar.tabs.iter().position(|t| t.is_active);
        let reserved: usize = bar
            .right_segments
            .iter()
            .map(|s| s.width_cells as usize)
            .sum();
        let effective_tab_area = (rect.width as usize).saturating_sub(reserved);

        hits.correct_scroll_offset = if let Some(active) = active_idx {
            TabBar::fit_active_scroll_offset(active, bar.tabs.len(), effective_tab_area, |i| {
                tab_widths[i]
            })
        } else {
            bar.scroll_offset
        };

        hits
    }

    /// Issue #919's `TabBarLayout`-returning counterpart to
    /// [`Self::tab_bar_layout_with_chrome`] above — overridden (rather
    /// than the trait default) for the same reason
    /// [`Self::draw_tab_bar_with_chrome_layout`] is: TUI honours
    /// [`crate::TabFrame::Brackets`] and must reserve the bracket-widened
    /// columns.
    fn resolve_tab_bar_layout_with_chrome(
        &self,
        rect: QRect,
        bar: &TabBar,
        chrome: &TabChrome,
    ) -> TabBarLayout {
        let close_cols = if bar.show_tab_close {
            crate::tui::TAB_CLOSE_COLS as usize
        } else {
            0
        };
        let brackets = matches!(chrome.active_frame, TabFrame::Brackets);
        let tab_widths: Vec<usize> = bar
            .tabs
            .iter()
            .map(|t| {
                let has_close = bar.show_tab_close && t.is_closable;
                let is_bracket = brackets && t.is_active;
                let base = display_width(&t.label);
                if is_bracket && has_close {
                    base + 1 + 1 + 1
                } else if is_bracket {
                    base + 2
                } else if has_close {
                    base + close_cols
                } else {
                    // No close button and no bracket framing to supply a
                    // visual boundary — reserve a column for the separator
                    // glyph so adjacent labels don't run together.
                    base + crate::tui::TAB_SEPARATOR_COLS as usize
                }
            })
            .collect();
        bar.layout(
            rect.width,
            rect.height,
            0.0,
            |i| {
                let has_close = bar.show_tab_close && bar.tabs[i].is_closable;
                let is_bracket = brackets && bar.tabs[i].is_active;
                if is_bracket && has_close {
                    crate::TabMeasure::new(tab_widths[i] as f32, 1.0).with_trailing(1.0)
                } else if has_close {
                    crate::TabMeasure::new(tab_widths[i] as f32, close_cols as f32)
                } else {
                    crate::TabMeasure::new(tab_widths[i] as f32, 0.0)
                }
            },
            |i| crate::SegmentMeasure::new(bar.right_segments[i].width_cells as f32),
        )
    }

    fn activity_bar_layout(&self, rect: QRect, bar: &ActivityBar) -> Vec<crate::ActivityBarRowHit> {
        let lh = 1.0_f32;
        activity_bar_hits(rect, bar, lh)
    }

    fn draw_terminal(&mut self, rect: QRect, term: &TerminalPrim) {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_terminal called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::draw_terminal(frame.buffer_mut(), area, term, &theme);
    }

    fn draw_terminal_divider(&mut self, rect: QRect) {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_terminal_divider called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::draw_terminal_divider(frame.buffer_mut(), area.x, area.y, area.height, &theme);
        // The primitive takes no `WidgetId` of its own (there is at
        // most one divider on screen at a time), so register a fixed
        // chrome id — otherwise this frame is indistinguishable from one
        // where the no-op trait default silently dropped the call (C0
        // paint smoke, contract §5b).
        self.register_zone(WidgetId::new("chrome:terminal-divider"), rect);
    }

    fn draw_solid_fill(&mut self, rect: QRect, color: Color) {
        let area = q_rect_to_ratatui(rect);
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_solid_fill called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::draw_solid_fill(frame.buffer_mut(), area, color);
        // Chrome-only paint (no text of its own) — only "observable"
        // via a registered zone, mirroring `draw_terminal_divider`'s
        // identical registration above. Callers that need a *semantic*
        // id for click routing (e.g. `AppShell`'s divider) register their
        // own zone on top of this one; this fixed id just proves the
        // frame isn't the no-op trait default silently dropping the call
        // (C0 paint smoke, contract §5b).
        self.register_zone(WidgetId::new("chrome:solid-fill"), rect);
    }

    fn draw_text_display(&mut self, rect: QRect, td: &TextDisplay) {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_text_display called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::draw_text_display(frame.buffer_mut(), area, td, &theme);
    }

    fn draw_command_line(&mut self, rect: QRect, cmd: &CommandLine) {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_command_line called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::command_line::draw_command_line(frame.buffer_mut(), area, cmd, &theme);
    }

    fn draw_command_line_selection(
        &mut self,
        rect: QRect,
        cmd: &CommandLine,
        selection: Option<(usize, usize)>,
    ) {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_command_line_selection called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::command_line::draw_command_line_selection(
            frame.buffer_mut(),
            area,
            cmd,
            &theme,
            selection,
        );
    }

    fn command_line_layout(
        &self,
        rect: QRect,
        cmd: &CommandLine,
    ) -> crate::primitives::command_line::CommandLineLayout {
        let area = q_rect_to_ratatui(rect);
        crate::tui::command_line::tui_command_line_layout(cmd, area)
    }

    fn text_display_layout(
        &self,
        rect: QRect,
        td: &TextDisplay,
    ) -> crate::primitives::text_display::TextDisplayLayout {
        let area = q_rect_to_ratatui(rect);
        crate::tui::tui_text_display_layout(td, area)
    }

    fn draw_text_input(
        &mut self,
        rect: QRect,
        ti: &crate::primitives::text_input::TextInput,
    ) -> crate::primitives::text_input::TextInputLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_text_input called outside enter_frame_scope"
            );
            return self.text_input_layout(rect, ti);
        };
        crate::tui::draw_text_input(frame.buffer_mut(), area, ti, &theme)
    }

    fn text_input_layout(
        &self,
        rect: QRect,
        ti: &crate::primitives::text_input::TextInput,
    ) -> crate::primitives::text_input::TextInputLayout {
        let area = q_rect_to_ratatui(rect);
        crate::tui::tui_text_input_layout(ti, area)
    }

    fn draw_tooltip(&mut self, tooltip: &crate::Tooltip, layout: &crate::TooltipLayout) {
        self.draw_tooltip_with_chrome(tooltip, layout, &crate::TooltipChrome::default());
    }

    fn draw_tooltip_with_chrome(
        &mut self,
        tooltip: &crate::Tooltip,
        layout: &crate::TooltipLayout,
        chrome: &crate::TooltipChrome,
    ) {
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_tooltip called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::draw_tooltip_with_chrome(frame.buffer_mut(), tooltip, layout, chrome, &theme);
        // Register the tooltip's own surface so a structural-parity
        // observer (`ConformanceDriver::inventory().zones()`) can see the
        // tooltip was drawn at all, not just infer it from text presence —
        // `screen_has("Keybindings")` stayed true on both backends through
        // #541 even though only one of them drew the chrome around it.
        //
        // Register `tooltip_painted_bounds`, not the raw float
        // `layout.bounds` — `draw_tooltip` rounds to whole cells before
        // painting, and registering the unrounded rect would report a
        // surface that doesn't match what was actually drawn.
        self.register_zone(tooltip.id, crate::tui::tooltip_painted_bounds(layout));
    }

    fn draw_context_menu(
        &mut self,
        menu: &crate::ContextMenu,
        layout: &crate::ContextMenuLayout,
    ) -> Vec<(QRect, crate::WidgetId)> {
        // See draw_palette for why this happens before the frame borrow.
        self.modal_stack.borrow_mut().mark_painted(&menu.id);
        let theme = self.current_theme;
        // Issue #1117: the returned `Vec` is derived from `layout` (an
        // argument, not frame state) below regardless of whether painting
        // happens, so a missing frame only skips the paint, not the hit
        // data a host still needs to route clicks.
        if let Some(frame) = self.current_frame_mut() {
            crate::tui::draw_context_menu(frame.buffer_mut(), menu, layout, &theme);
        } else {
            debug_assert!(
                false,
                "TuiBackend::draw_context_menu called outside enter_frame_scope"
            );
        }
        // TUI rasteriser doesn't return hit data — derive from layout.
        // The primitive's hit_test() is the canonical way; this Vec
        // is here for trait parity with GTK.
        let _ = menu;
        layout
            .hit_regions
            .iter()
            .filter_map(|(rect, hit)| match hit {
                crate::primitives::context_menu::ContextMenuHit::Item(id) => Some((*rect, *id)),
                _ => None,
            })
            .collect()
    }

    fn draw_context_menu_with_glyphs(
        &mut self,
        menu: &crate::ContextMenu,
        layout: &crate::ContextMenuLayout,
        glyphs: Option<&crate::primitives::context_menu::ContextMenuGlyphs>,
    ) -> Vec<(QRect, crate::WidgetId)> {
        // See draw_palette for why this happens before the frame borrow.
        self.modal_stack.borrow_mut().mark_painted(&menu.id);
        let theme = self.current_theme;
        let nerd_fonts = self.nerd_fonts_enabled;
        if let Some(frame) = self.current_frame_mut() {
            crate::tui::draw_context_menu_with_glyphs(
                frame.buffer_mut(),
                menu,
                layout,
                &theme,
                glyphs,
                nerd_fonts,
            );
        } else {
            debug_assert!(
                false,
                "TuiBackend::draw_context_menu_with_glyphs called outside enter_frame_scope"
            );
        }
        layout
            .hit_regions
            .iter()
            .filter_map(|(rect, hit)| match hit {
                crate::primitives::context_menu::ContextMenuHit::Item(id) => Some((*rect, *id)),
                _ => None,
            })
            .collect()
    }

    fn draw_dialog(
        &mut self,
        dialog: &crate::primitives::dialog::Dialog,
        layout: &crate::primitives::dialog::DialogLayout,
    ) -> Vec<QRect> {
        // See draw_palette for why this happens before the frame borrow.
        self.modal_stack.borrow_mut().mark_painted(&dialog.id);
        let theme = self.current_theme;
        // Issue #1117: same rationale as `draw_context_menu` just above —
        // the returned `Vec` comes from `layout`, not frame state.
        if let Some(frame) = self.current_frame_mut() {
            crate::tui::draw_dialog(frame.buffer_mut(), dialog, layout, &theme);
        } else {
            debug_assert!(
                false,
                "TuiBackend::draw_dialog called outside enter_frame_scope"
            );
        }
        // Derive button rects from the layout (TUI rasteriser doesn't
        // return them; the primitive owns the layout).
        layout
            .visible_buttons
            .iter()
            .map(|vis| vis.bounds)
            .collect()
    }

    fn draw_float(
        &mut self,
        float: &crate::primitives::float::Float,
        layout: &crate::primitives::float::FloatLayout,
    ) {
        // See draw_palette for why this happens before the frame borrow.
        self.modal_stack.borrow_mut().mark_painted(&float.id);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_float called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::draw_float(frame.buffer_mut(), float, layout, &theme);
        // Same convention `draw_scrollbar` uses for a chrome-only
        // primitive: register the float's own bounds under its id so
        // it's inventory-observable even when `border: false` leaves no
        // painted glyph behind.
        self.register_zone(float.id, layout.bounds);
    }

    // ─── #13: trait coverage for the rest of the rasterised primitives ──

    fn draw_multi_section_view(
        &mut self,
        rect: QRect,
        view: &crate::primitives::multi_section_view::MultiSectionView,
    ) {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let nerd_fonts = self.nerd_fonts_enabled;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_multi_section_view called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::draw_multi_section_view(frame.buffer_mut(), area, view, &theme, nerd_fonts);
    }

    fn msv_layout(
        &self,
        rect: QRect,
        view: &crate::primitives::multi_section_view::MultiSectionView,
    ) -> crate::primitives::multi_section_view::MultiSectionViewLayout {
        let area = q_rect_to_ratatui(rect);
        crate::tui::tui_msv_layout(view, area)
    }

    fn msv_metrics(&self) -> crate::primitives::multi_section_view::MsvLayoutMetrics {
        crate::primitives::multi_section_view::MsvLayoutMetrics {
            header_size: 1.0,
            divider_size: 0.0,
            scrollbar_size: 1.0,
            cell_quantum: 1.0,
        }
    }

    fn tree_layout(&self, rect: QRect, tree: &TreeView) -> crate::primitives::tree::TreeViewLayout {
        let area = q_rect_to_ratatui(rect);
        crate::tui::tui_tree_layout(tree, area)
    }

    fn tree_vscrollbar(&self, rect: QRect, tree: &TreeView) -> Option<crate::Scrollbar> {
        // TUI rows are uniform 1-cell tall (see `tui_tree_layout`'s doc).
        let area = q_rect_to_ratatui(rect);
        tree.vscrollbar_with_track_width(
            crate::event::Rect::new(
                area.x as f32,
                area.y as f32,
                area.width as f32,
                area.height as f32,
            ),
            1.0,
            1.0,
        )
    }

    fn form_layout(&self, rect: QRect, form: &Form) -> crate::primitives::form::FormLayout {
        let area = q_rect_to_ratatui(rect);
        crate::tui::tui_form_layout(form, area)
    }

    fn draw_editor(
        &mut self,
        rect: QRect,
        editor: &crate::primitives::editor::Editor,
    ) -> crate::backend::EditorPaintResult {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let right_reserve = self.editor_right_reserve_w.unwrap_or(0.0).max(0.0).round() as u16;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_editor called outside enter_frame_scope"
            );
            return crate::backend::EditorPaintResult::default();
        };
        let tui_result = crate::tui::draw_editor_with_reserve(
            frame.buffer_mut(),
            area,
            editor,
            &theme,
            right_reserve,
        );
        // Cache for `render_frame` — `draw_editor` only sees
        // the buffer, not the `Frame`, so it can't call
        // `Frame::set_cursor_position` itself. See
        // `last_cursor_position`'s field doc for the full handoff.
        //
        // Only overwrite on `Some`: a frame can call
        // `draw_editor` once per window (e.g. a split), and only the active
        // window's editor ever reports a `Some` cursor position — inactive
        // windows correctly report `None` (see `RenderedWindow.cursor`'s
        // `is_active` gating on the consumer side). Whichever call happened
        // to run last used to win unconditionally, so an inactive window's
        // `None` could clobber the active window's `Some` recorded earlier
        // in the same frame, hiding the caret whenever paint order didn't
        // happen to place the active window last. `begin_frame`
        // already resets this to `None` at frame-start, so within a frame we
        // only ever want to move from `None` to `Some`, never back.
        if tui_result.cursor_position.is_some() {
            self.last_cursor_position = tui_result.cursor_position;
        }
        crate::backend::EditorPaintResult {
            // `tui_result.cursor_position` is the TUI-internal, already
            // cell-rounded `(u16, u16)` shape `Frame::set_cursor_position`
            // needs (see `last_cursor_position`'s doc); widen to the
            // portable `Point` for the trait's return value.
            cursor_position_native: tui_result
                .cursor_position
                .map(|(x, y)| crate::event::Point::new(x as f32, y as f32)),
        }
    }

    /// Steers the terminal emulator's hardware caret via DECSCUSR
    /// (crossterm's `SetCursorStyle`) — see [`Backend::set_caret_shape`]'s
    /// doc for why TUI is the one backend that overrides this (issue
    /// #1015). Always the non-blinking ("Steady*") variant of the
    /// requested shape: [`crate::primitives::editor::CursorShape`] carries
    /// no blink flag of its own, so picking a fixed, deterministic style
    /// per shape is the honest mapping rather than guessing a blink
    /// preference this primitive doesn't model.
    ///
    /// Best-effort, matching [`crate::backend::WindowControl::set_title`]'s
    /// `TuiBackend` impl: both write straight to `std::io::stdout()` with
    /// no `self.live`-style guard (this backend has no such flag — see
    /// its struct doc), because a write failure here has no distinct
    /// recovery a caller could act on differently from "the escape
    /// sequence didn't land." Errors are swallowed rather than
    /// propagated, matching this trait method's `()` return.
    fn set_caret_shape(&mut self, shape: crate::EditorCursorShape) {
        use ratatui::crossterm::cursor::SetCursorStyle;
        use ratatui::crossterm::execute;
        let style = match shape {
            crate::EditorCursorShape::Block => SetCursorStyle::SteadyBlock,
            crate::EditorCursorShape::Bar => SetCursorStyle::SteadyBar,
            crate::EditorCursorShape::Underline => SetCursorStyle::SteadyUnderScore,
        };
        let _ = execute!(std::io::stdout(), style);
    }

    fn draw_message_list(
        &mut self,
        rect: QRect,
        list: &crate::primitives::message_list::MessageList,
    ) {
        let area = q_rect_to_ratatui(rect);
        let panel_bg = self.current_theme.background;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_message_list called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::draw_message_list(frame.buffer_mut(), area, list, panel_bg);
    }

    fn draw_rich_text_popup(
        &mut self,
        popup: &crate::primitives::rich_text_popup::RichTextPopup,
        layout: &crate::primitives::rich_text_popup::RichTextPopupLayout,
    ) {
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_rich_text_popup called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::draw_rich_text_popup(frame.buffer_mut(), popup, layout, &theme);
    }

    fn draw_find_replace(
        &mut self,
        rect: QRect,
        panel: &crate::primitives::find_replace::FindReplacePanel,
    ) {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        // TUI free function takes `editor_left: u16` for editor-relative
        // positioning. The trait abstraction passes the panel's full
        // rect; downstream consumers that want a non-zero editor offset
        // should compose into a sub-rect.
        let editor_left = area.x;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_find_replace called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::draw_find_replace(frame.buffer_mut(), area, panel, &theme, editor_left);
    }

    fn draw_completions(
        &mut self,
        completions: &crate::primitives::completions::Completions,
        layout: &crate::primitives::completions::CompletionsLayout,
    ) {
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_completions called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::draw_completions(frame.buffer_mut(), completions, layout, &theme);
    }

    fn draw_number_input(
        &mut self,
        number_input: &crate::primitives::number_input::NumberInput,
        layout: &crate::primitives::number_input::NumberInputLayout,
    ) {
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_number_input called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::draw_number_input(frame.buffer_mut(), number_input, layout, &theme);
        self.register_zone(number_input.id, layout.bounds);
    }

    fn draw_combo_box(
        &mut self,
        combo_box: &crate::primitives::combo_box::ComboBox,
        layout: &crate::primitives::combo_box::ComboBoxLayout,
    ) {
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_combo_box called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::draw_combo_box(frame.buffer_mut(), combo_box, layout, &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;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_date_picker called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::draw_date_picker(frame.buffer_mut(), date_picker, layout, &theme);
        self.register_zone(date_picker.id, layout.bounds());
    }

    fn draw_scrollbar(
        &mut self,
        _rect: QRect,
        scrollbar: &crate::primitives::scrollbar::Scrollbar,
    ) {
        let theme = self.current_theme;
        let cell_bg = theme.background;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_scrollbar called outside enter_frame_scope"
            );
            return;
        };
        // The standalone TUI scrollbar primitive paints from its own
        // `track` bounds; `rect` is unused (the primitive owns layout).
        // Forward-compat parameter for backends that need a clip rect.
        crate::tui::draw_scrollbar(frame.buffer_mut(), scrollbar, &theme, cell_bg);
        // A scrollbar paints only glyphs (thumb/track), so on a
        // pixel backend it would otherwise be indistinguishable from the
        // no-op default. Register the primitive's own id at its own
        // track bounds (not `_rect`, which the primitive ignores).
        self.register_zone(scrollbar.id, scrollbar.track);
    }

    fn draw_drop_overlay(&mut self, overlay: &crate::primitives::drop_zone::DropOverlay) {
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_drop_overlay called outside enter_frame_scope"
            );
            return;
        };
        crate::tui::draw_drop_overlay(frame.buffer_mut(), overlay, &theme);
        // `DropOverlay` carries no `WidgetId` (there is at most one
        // overlay active at a time), so register a fixed chrome id at
        // whichever sub-rect it actually drew — otherwise this frame is
        // indistinguishable from one where the no-op default silently
        // dropped the call (C0 paint smoke, contract §5b).
        if let Some(bounds) = overlay.highlight.or(overlay.insertion_bar) {
            self.register_zone(WidgetId::new("chrome:drop-overlay"), bounds);
        }
    }

    fn draw_menu_bar(
        &mut self,
        rect: QRect,
        bar: &MenuBar,
    ) -> crate::primitives::menu_bar::MenuBarLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_menu_bar called outside enter_frame_scope"
            );
            return self.menu_bar_layout(rect, bar);
        };
        crate::tui::draw_menu_bar(frame.buffer_mut(), area, bar, &theme)
    }

    fn menu_bar_layout(
        &self,
        rect: QRect,
        bar: &MenuBar,
    ) -> crate::primitives::menu_bar::MenuBarLayout {
        let area = q_rect_to_ratatui(rect);
        crate::tui::tui_menu_bar_layout(bar, area)
    }

    fn draw_split(&mut self, rect: QRect, split: &Split) -> crate::primitives::split::SplitLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_split called outside enter_frame_scope"
            );
            // No zone registration either — nothing was actually painted.
            return self.split_layout(rect, split);
        };
        let layout = crate::tui::draw_split(frame.buffer_mut(), area, split, &theme);
        // `Split` paints a divider only — no text of its own — so a
        // registered zone is the only way this frame is attributable to
        // the primitive rather than indistinguishable from the trait's
        // no-op default (C0 paint smoke, contract §5b).
        self.register_zone(split.id, rect);
        layout
    }

    fn split_layout(&self, rect: QRect, split: &Split) -> crate::primitives::split::SplitLayout {
        let area = q_rect_to_ratatui(rect);
        crate::tui::tui_split_layout(split, area)
    }

    fn draw_split_tree(
        &mut self,
        rect: QRect,
        tree: &crate::primitives::split_tree::SplitTree,
    ) -> crate::primitives::split_tree::SplitTreeLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_split_tree called outside enter_frame_scope"
            );
            // No zone registration either — nothing was actually painted.
            return self.split_tree_layout(rect, tree);
        };
        let layout = crate::tui::draw_split_tree(frame.buffer_mut(), area, tree, &theme);
        // Dividers only, and `SplitTree` (unlike `Split`) carries no
        // id of its own — register a fixed chrome id, same pattern as
        // `draw_terminal_divider` / `draw_drop_overlay`.
        self.register_zone(WidgetId::new("chrome:split-tree"), rect);
        layout
    }

    fn split_tree_layout(
        &self,
        rect: QRect,
        tree: &crate::primitives::split_tree::SplitTree,
    ) -> crate::primitives::split_tree::SplitTreeLayout {
        let area = q_rect_to_ratatui(rect);
        crate::tui::tui_split_tree_layout(tree, area)
    }

    fn draw_panel(
        &mut self,
        rect: QRect,
        panel: &crate::primitives::panel::Panel,
    ) -> crate::primitives::panel::PanelLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_panel called outside enter_frame_scope"
            );
            return self.panel_layout(rect, panel);
        };
        crate::tui::draw_panel(frame.buffer_mut(), area, panel, &theme)
    }

    fn panel_layout(
        &self,
        rect: QRect,
        panel: &crate::primitives::panel::Panel,
    ) -> crate::primitives::panel::PanelLayout {
        let area = q_rect_to_ratatui(rect);
        crate::tui::tui_panel_layout(panel, area)
    }

    fn draw_canvas(
        &mut self,
        rect: QRect,
        canvas: &crate::primitives::canvas::Canvas,
    ) -> crate::primitives::canvas::CanvasLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_canvas called outside enter_frame_scope"
            );
            return self.canvas_layout(rect, canvas);
        };
        crate::tui::draw_canvas(frame.buffer_mut(), area, canvas, &theme)
    }

    fn draw_toast_overlay(
        &mut self,
        rect: QRect,
        stack: &crate::primitives::toast::ToastOverlay,
    ) -> crate::primitives::toast::ToastStackLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_toast_stack called outside enter_frame_scope"
            );
            return self.toast_stack_layout(rect, stack);
        };
        crate::tui::draw_toast_stack(frame.buffer_mut(), area, stack, &theme)
    }

    fn toast_stack_layout(
        &self,
        rect: QRect,
        stack: &crate::primitives::toast::ToastOverlay,
    ) -> crate::primitives::toast::ToastStackLayout {
        let area = q_rect_to_ratatui(rect);
        crate::tui::tui_toast_stack_layout(stack, area)
    }

    fn draw_pipeline_view(
        &mut self,
        rect: QRect,
        view: &crate::primitives::pipeline_view::PipelineView,
    ) -> crate::primitives::pipeline_view::PipelineViewLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_pipeline_view called outside enter_frame_scope"
            );
            return self.pipeline_view_layout(rect, view);
        };
        crate::tui::draw_pipeline_view(frame.buffer_mut(), area, view, &theme)
    }

    fn pipeline_view_layout(
        &self,
        rect: QRect,
        view: &crate::primitives::pipeline_view::PipelineView,
    ) -> crate::primitives::pipeline_view::PipelineViewLayout {
        let area = q_rect_to_ratatui(rect);
        crate::tui::tui_pipeline_view_layout(view, area)
    }

    fn draw_progress(
        &mut self,
        rect: QRect,
        bar: &crate::primitives::progress::ProgressBar,
    ) -> crate::primitives::progress::ProgressBarLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_progress called outside enter_frame_scope"
            );
            return self.progress_layout(rect, bar);
        };
        crate::tui::draw_progress(frame.buffer_mut(), area, bar, &theme)
    }

    fn progress_layout(
        &self,
        rect: QRect,
        bar: &crate::primitives::progress::ProgressBar,
    ) -> crate::primitives::progress::ProgressBarLayout {
        let area = q_rect_to_ratatui(rect);
        crate::tui::tui_progress_layout(bar, area)
    }

    fn draw_spinner(
        &mut self,
        rect: QRect,
        spinner: &crate::primitives::spinner::Spinner,
    ) -> crate::primitives::spinner::SpinnerLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_spinner called outside enter_frame_scope"
            );
            return self.spinner_layout(rect, spinner);
        };
        crate::tui::draw_spinner(frame.buffer_mut(), area, spinner, &theme)
    }

    fn spinner_layout(
        &self,
        rect: QRect,
        spinner: &crate::primitives::spinner::Spinner,
    ) -> crate::primitives::spinner::SpinnerLayout {
        let area = q_rect_to_ratatui(rect);
        crate::tui::tui_spinner_layout(spinner, area)
    }

    fn draw_button(
        &mut self,
        rect: QRect,
        button: &crate::primitives::button::Button,
    ) -> crate::primitives::button::ButtonLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_button called outside enter_frame_scope"
            );
            return self.button_layout(rect, button);
        };
        crate::tui::draw_button(frame.buffer_mut(), area, button, &theme)
    }

    fn button_layout(
        &self,
        rect: QRect,
        button: &crate::primitives::button::Button,
    ) -> crate::primitives::button::ButtonLayout {
        let area = q_rect_to_ratatui(rect);
        crate::tui::tui_button_layout(button, area)
    }

    fn draw_radio_group(
        &mut self,
        rect: QRect,
        group: &crate::primitives::radio_group::RadioGroup,
    ) -> crate::primitives::radio_group::RadioGroupLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_radio_group called outside enter_frame_scope"
            );
            return self.radio_group_layout(rect, group);
        };
        crate::tui::draw_radio_group(frame.buffer_mut(), area, group, &theme)
    }

    fn radio_group_layout(
        &self,
        rect: QRect,
        group: &crate::primitives::radio_group::RadioGroup,
    ) -> crate::primitives::radio_group::RadioGroupLayout {
        let area = q_rect_to_ratatui(rect);
        crate::tui::tui_radio_group_layout(group, area)
    }

    fn draw_switch(
        &mut self,
        rect: QRect,
        switch: &crate::primitives::switch::Switch,
    ) -> crate::primitives::switch::SwitchLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_switch called outside enter_frame_scope"
            );
            return self.switch_layout(rect, switch);
        };
        crate::tui::draw_switch(frame.buffer_mut(), area, switch, &theme)
    }

    fn switch_layout(
        &self,
        rect: QRect,
        switch: &crate::primitives::switch::Switch,
    ) -> crate::primitives::switch::SwitchLayout {
        let area = q_rect_to_ratatui(rect);
        crate::tui::tui_switch_layout(switch, area)
    }

    fn draw_command_center(
        &mut self,
        rect: QRect,
        cc: &crate::primitives::command_center::CommandCenter,
    ) -> crate::primitives::command_center::CommandCenterLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_command_center called outside enter_frame_scope"
            );
            return self.command_center_layout(rect, cc);
        };
        crate::tui::draw_command_center(frame.buffer_mut(), area, cc, &theme)
    }

    fn command_center_layout(
        &self,
        rect: QRect,
        cc: &crate::primitives::command_center::CommandCenter,
    ) -> crate::primitives::command_center::CommandCenterLayout {
        let area = q_rect_to_ratatui(rect);
        crate::tui::tui_command_center_layout(cc, area)
    }

    fn draw_chart(
        &mut self,
        rect: QRect,
        chart: &crate::primitives::chart::Chart,
        hovered_point: Option<(usize, usize)>,
        crosshair_x: Option<f64>,
    ) -> crate::primitives::chart::ChartLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_chart called outside enter_frame_scope"
            );
            return self.chart_layout(rect, chart);
        };
        crate::tui::draw_chart(
            frame.buffer_mut(),
            area,
            chart,
            &theme,
            hovered_point,
            crosshair_x,
        )
    }

    fn chart_layout(
        &self,
        rect: QRect,
        chart: &crate::primitives::chart::Chart,
    ) -> crate::primitives::chart::ChartLayout {
        let area = q_rect_to_ratatui(rect);
        crate::tui::tui_chart_layout(chart, area)
    }

    fn draw_toolbar_with_options(
        &mut self,
        rect: QRect,
        bar: &crate::primitives::toolbar::Toolbar,
        interaction: &crate::interaction::InteractionState,
        options: crate::primitives::toolbar::ToolbarPaintOptions,
    ) -> crate::primitives::toolbar::ToolbarLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_toolbar_with_options called outside enter_frame_scope"
            );
            return self.toolbar_layout(rect, bar);
        };
        crate::tui::draw_toolbar_with_options(
            frame.buffer_mut(),
            area,
            bar,
            &theme,
            interaction.hovered(),
            interaction.pressed(),
            options,
        )
    }

    fn toolbar_layout(
        &self,
        rect: QRect,
        bar: &crate::primitives::toolbar::Toolbar,
    ) -> crate::primitives::toolbar::ToolbarLayout {
        let area = q_rect_to_ratatui(rect);
        crate::tui::tui_toolbar_layout(bar, area)
    }

    fn draw_sidebar_panel_interactive(
        &mut self,
        rect: QRect,
        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());
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_sidebar_panel called outside enter_frame_scope"
            );
            return self.sidebar_panel_layout(rect, panel);
        };
        crate::tui::draw_sidebar_panel(
            frame.buffer_mut(),
            area,
            panel,
            &theme,
            hovered_toolbar_id,
            pressed_toolbar_id,
        )
    }

    fn sidebar_panel_layout(
        &self,
        rect: QRect,
        panel: &crate::primitives::sidebar_panel::SidebarPanel,
    ) -> crate::primitives::sidebar_panel::SidebarPanelLayout {
        let area = q_rect_to_ratatui(rect);
        crate::tui::tui_sidebar_panel_layout(panel, area)
    }

    fn draw_diff_view(
        &mut self,
        rect: QRect,
        view: &crate::primitives::diff_view::DiffView,
    ) -> crate::primitives::diff_view::DiffViewLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_diff_view called outside enter_frame_scope"
            );
            return self.diff_view_layout(rect, view);
        };
        crate::tui::draw_diff_view(frame.buffer_mut(), area, view, &theme)
    }

    fn draw_board(
        &mut self,
        rect: QRect,
        model: &crate::primitives::board::BoardModel,
    ) -> crate::primitives::board::BoardLayout {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_board called outside enter_frame_scope"
            );
            return self.board_layout(rect, model);
        };
        crate::tui::draw_board(frame.buffer_mut(), area, model, &theme)
    }

    fn board_layout(
        &self,
        rect: QRect,
        model: &crate::primitives::board::BoardModel,
    ) -> crate::primitives::board::BoardLayout {
        crate::tui::tui_board_layout(model, q_rect_to_ratatui(rect))
    }

    fn draw_minimap(
        &mut self,
        rect: QRect,
        minimap: &crate::primitives::minimap::Minimap,
    ) -> crate::backend::MinimapPaintResult {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let sizing = self.minimap_sizing;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_minimap called outside enter_frame_scope"
            );
            // Mirrors `MacBackend`'s pre-#802 `painted: false` report — the
            // real layout, nothing rasterised, no zone registered.
            return crate::backend::MinimapPaintResult {
                layout: self.minimap_layout(rect, minimap),
                painted: false,
            };
        };
        let layout = match sizing {
            Some(sizing) => {
                let cols_per_cell =
                    crate::tui::minimap::resolve_cols_per_cell(minimap, area.width as usize);
                crate::tui::draw_minimap_with_sizing(
                    frame.buffer_mut(),
                    area,
                    minimap,
                    &theme,
                    cols_per_cell,
                    sizing,
                )
            }
            None => crate::tui::draw_minimap(frame.buffer_mut(), area, minimap, &theme),
        };
        self.register_zone(minimap.id, rect);
        crate::backend::MinimapPaintResult {
            layout,
            painted: true,
        }
    }

    fn minimap_layout(
        &self,
        rect: QRect,
        minimap: &crate::primitives::minimap::Minimap,
    ) -> crate::primitives::minimap::MinimapLayout {
        let area = q_rect_to_ratatui(rect);
        match self.minimap_sizing {
            Some(sizing) => crate::tui::tui_minimap_layout_with_sizing(minimap, area, sizing),
            None => crate::tui::tui_minimap_layout(minimap, area),
        }
    }

    fn minimap_sizing(&self) -> Option<crate::primitives::minimap::MinimapSizing> {
        self.minimap_sizing
    }

    fn set_minimap_sizing(&mut self, sizing: Option<crate::primitives::minimap::MinimapSizing>) {
        self.minimap_sizing = sizing;
    }

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

    fn set_editor_right_reserve_w(&mut self, px: Option<f32>) {
        // Quantise to a whole cell at set-time (one TUI cell == one pixel
        // unit here), so the stored value already matches what
        // `draw_editor_with_reserve`'s `.round() as u16` produces. Without
        // this, a non-integral `px` (e.g. `Some(2.5)`) would round one way
        // for `editor_layout`'s raw-`f32` fold and round again
        // (independently) for the `u16` cast, and the two could disagree.
        self.editor_right_reserve_w = px.map(|v| v.max(0.0).round());
    }

    fn draw_image(
        &mut self,
        rect: QRect,
        image: &crate::primitives::image::Image,
    ) -> crate::backend::ImagePaintResult {
        let area = q_rect_to_ratatui(rect);
        let theme = self.current_theme;
        let Some(frame) = self.current_frame_mut() else {
            debug_assert!(
                false,
                "TuiBackend::draw_image called outside enter_frame_scope"
            );
            // Mirrors the win/macOS "no rasteriser" report —
            // no zone registered either, since nothing was painted.
            return crate::backend::ImagePaintResult::Unsupported;
        };
        let result = crate::tui::draw_image(frame.buffer_mut(), area, image, &theme);
        self.register_zone(image.id, rect);
        result
    }

    // ─── Window control ─────────────────────────────────────────────────
    fn window(&mut self) -> Option<&mut dyn crate::backend::WindowControl> {
        Some(self)
    }
}

/// TUI's `WindowControl` surface — a terminal has no OS window, so this
/// overrides exactly one method ([`WindowControl::set_title`], via the
/// OSC 0/2 escape sequence) and leaves every other method on the trait's
/// `Unsupported` default. See [`Backend::window`]'s doc on `TuiBackend`
/// for why the getter still returns `Some` rather than `None` — the
/// title-set capability is real, not a stand-in for "no window", even
/// though the size/position/fullscreen/minimize/always-on-top surface
/// genuinely has no terminal equivalent.
impl crate::backend::WindowControl for TuiBackend {
    /// Retitles the terminal emulator's tab/window via crossterm's
    /// `SetTitle` (OSC 0/2). Whether the *emulator* honours it (some
    /// terminals ignore OSC 0/2 entirely, or only in specific modes) is
    /// outside crossterm's — and this backend's — control; the write
    /// itself succeeding is all this method can promise.
    fn set_title(&mut self, title: &str) -> crate::backend::ServiceResult<()> {
        use ratatui::crossterm::execute;
        use ratatui::crossterm::terminal::SetTitle;
        execute!(std::io::stdout(), SetTitle(title)).map_err(|e| {
            crate::backend::BackendError::PlatformFailure {
                context: format!("crossterm SetTitle: {e}"),
            }
        })
    }
}

// ─── Cross-backend validation tests ──────────────────────────────────────────
//
// Phase B.4 Stage 3b: prove the `Backend` trait is genuinely consumable
// by app code that's *generic* over the backend, not just by `TuiBackend`
// specifically. A minimal `MockBackend` records each `draw_*` call into
// a `Vec<DrawCall>`; a generic `<B: Backend>` helper invokes the trait
// methods; assertions verify the calls landed.
//
// This is the architectural proof point Stage 3 was designed around:
// once the trait works against TuiBackend AND a foreign mock, future
// backends (GtkBackend in B.5, WinBackend in B.6, MacOSBackend in B.7)
// drop in without forking the app's render code.

#[cfg(test)]
mod tests {
    use super::*;
    use crate::backend::{
        Clipboard, FileDialogOptions, MessageDialogChoice, MessageDialogOptions, Notification,
    };
    use crate::{
        ListItem, ListView, Palette, PaletteItem, StyledSpan, StyledText, TerminalCursorShape,
        WidgetId,
    };

    /// Records every draw call so tests can assert what the trait
    /// boundary actually delivers.
    #[derive(Debug, Clone, PartialEq)]
    enum DrawCall {
        List { rect: QRect, item_count: usize },
        Palette { rect: QRect, item_count: usize },
    }

    struct NoopClipboard;
    impl Clipboard for NoopClipboard {
        fn read_text(&self) -> Option<String> {
            None
        }
        fn write_text(&self, _t: &str) {}
    }

    struct MockServices {
        clipboard: NoopClipboard,
    }
    impl MockServices {
        fn new() -> Self {
            Self {
                clipboard: NoopClipboard,
            }
        }
    }
    impl PlatformServices for MockServices {
        fn clipboard(&self) -> &dyn Clipboard {
            &self.clipboard
        }
        fn show_file_open_dialog(&self, _opts: FileDialogOptions) -> Option<std::path::PathBuf> {
            None
        }
        fn show_file_save_dialog(&self, _opts: FileDialogOptions) -> Option<std::path::PathBuf> {
            None
        }
        fn show_folder_open_dialog(&self, _opts: FileDialogOptions) -> Option<std::path::PathBuf> {
            None
        }
        fn show_message_dialog(&self, _opts: MessageDialogOptions) -> Option<MessageDialogChoice> {
            None
        }
        fn send_notification(&self, _n: Notification) {}
        fn open_url(&self, _url: &str) {}
        fn platform_name(&self) -> &'static str {
            "mock"
        }
    }

    /// An empty [`TabBarLayout`] for this mock's issue #919 stubs —
    /// `TabBarLayout` has no `Default` impl (unlike `TabBarHits`), so the
    /// inert-but-real return value needs a literal.
    fn mock_empty_tab_bar_layout() -> TabBarLayout {
        TabBarLayout {
            bar_width: 0.0,
            bar_height: 0.0,
            visible_tabs: Vec::new(),
            visible_segments: Vec::new(),
            scroll_left: None,
            scroll_right: None,
            hit_regions: Vec::new(),
            resolved_scroll_offset: 0,
        }
    }

    struct MockBackend {
        calls: Vec<DrawCall>,
        modal_stack: Rc<RefCell<ModalStack>>,
        drag_state: Rc<RefCell<DragState>>,
        services: MockServices,
        viewport: Viewport,
        theme: crate::Theme,
        focus: crate::focus::FocusManager,
        invalidation_log: crate::backend::InvalidationLog,
    }

    impl MockBackend {
        fn new() -> Self {
            Self {
                calls: Vec::new(),
                modal_stack: Rc::new(RefCell::new(ModalStack::new())),
                drag_state: Rc::new(RefCell::new(DragState::new())),
                services: MockServices::new(),
                viewport: Viewport::new(80.0, 24.0, 1.0),
                theme: crate::Theme::default(),
                focus: crate::focus::FocusManager::new(),
                invalidation_log: crate::backend::InvalidationLog::new(),
            }
        }
    }

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

    impl Backend for MockBackend {
        fn viewport(&self) -> Viewport {
            self.viewport
        }
        fn begin_frame(&mut self, viewport: Viewport) {
            self.viewport = viewport;
        }
        fn end_frame(&mut self) {}
        fn set_theme(&mut self, theme: crate::Theme) {
            self.theme = theme;
        }
        fn poll_events(&mut self) -> Vec<UiEvent> {
            Vec::new()
        }
        fn wait_events(&mut self, _t: Duration) -> Vec<UiEvent> {
            Vec::new()
        }
        fn waker(&self) -> std::sync::Arc<dyn Fn(crate::UserPayload) + Send + Sync> {
            // `MockBackend` only records `draw_*` calls for assertions — no
            // event loop for a wake to reach. No-op, matching `poll_events`/
            // `wait_events` above. Real cross-thread wake delivery is
            // covered against `TuiBackend` itself, not this recorder.
            std::sync::Arc::new(|_payload| {})
        }
        fn request_frame_in(&self, _delay: Duration) {
            // No event loop to wake, same rationale as `waker` above.
        }
        fn register_accelerator(&mut self, _a: &Accelerator) {}
        fn unregister_accelerator(&mut self, _id: &AcceleratorId) {}
        fn invalidate_rect(&mut self, rect: crate::event::Rect) {
            self.invalidation_log.push(rect);
        }
        fn invalidation_log(&self) -> &crate::backend::InvalidationLog {
            &self.invalidation_log
        }
        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, _r: QRect) {}
        fn services(&self) -> &dyn PlatformServices {
            &self.services
        }

        fn backend_caps(&self) -> crate::backend::BackendCaps {
            crate::backend::BackendCaps::empty()
        }

        fn draw_list(&mut self, rect: QRect, list: &ListView) {
            self.calls.push(DrawCall::List {
                rect,
                item_count: list.items.len(),
            });
        }

        fn draw_data_table(
            &mut self,
            _rect: QRect,
            _table: &crate::DataTable,
            _hovered_idx: Option<usize>,
        ) -> crate::DataTableLayout {
            crate::DataTableLayout {
                header_height: 0.0,
                row_height: 0.0,
                columns: Vec::new(),
                visible_rows: 0,
                viewport_width: 0.0,
                viewport_height: 0.0,
                scrollbar_width: 0.0,
                content_width: 0.0,
                h_scrollbar_height: 0.0,
                footer_height: 0.0,
                h_scroll: 0.0,
            }
        }
        fn data_table_layout(
            &self,
            _rect: QRect,
            _table: &crate::DataTable,
        ) -> crate::DataTableLayout {
            crate::DataTableLayout {
                header_height: 0.0,
                row_height: 0.0,
                columns: Vec::new(),
                visible_rows: 0,
                viewport_width: 0.0,
                viewport_height: 0.0,
                scrollbar_width: 0.0,
                content_width: 0.0,
                h_scrollbar_height: 0.0,
                footer_height: 0.0,
                h_scroll: 0.0,
            }
        }
        fn list_hscrollbar(&self, _rect: QRect, _list: &ListView) -> Option<crate::Scrollbar> {
            None
        }
        fn list_vscrollbar(&self, _rect: QRect, _list: &ListView) -> Option<crate::Scrollbar> {
            None
        }
        fn list_layout(&self, rect: QRect, list: &ListView) -> crate::ListViewLayout {
            crate::tui::tui_list_layout(q_rect_to_ratatui(rect), list)
        }
        fn draw_palette(&mut self, rect: QRect, palette: &Palette) {
            self.calls.push(DrawCall::Palette {
                rect,
                item_count: palette.items.len(),
            });
        }
        fn palette_layout(&self, rect: QRect, palette: &Palette) -> crate::PaletteLayout {
            crate::tui::tui_palette_layout(q_rect_to_ratatui(rect), palette)
        }

        // The other 7 trait methods are unimplemented — this mock only
        // records the ones the cross-backend test actually exercises.
        fn draw_tree(&mut self, _r: QRect, _t: &TreeView) {}
        fn draw_form(&mut self, _r: QRect, _f: &Form) {}
        fn draw_settings_chrome(
            &mut self,
            _r: QRect,
            _header_text: &str,
            _query: &str,
            _placeholder: &str,
            _active: bool,
        ) {
        }
        fn draw_status_bar_interactive(
            &mut self,
            _r: QRect,
            _b: &StatusBar,
            _interaction: &crate::interaction::InteractionState,
        ) -> crate::StatusBarLayout {
            crate::StatusBarLayout {
                bar_width: 0.0,
                bar_height: 0.0,
                visible_segments: Vec::new(),
                hit_regions: Vec::new(),
                resolved_right_start: 0,
            }
        }
        #[allow(deprecated)] // `TabBarHits` is `#[deprecated]`
        fn draw_tab_bar(
            &mut self,
            _r: QRect,
            _b: &TabBar,
            _hovered_close_tab: Option<usize>,
        ) -> crate::TabBarHits {
            crate::TabBarHits::default()
        }
        #[allow(deprecated)] // `TabBarHits` is `#[deprecated]`
        fn draw_tab_bar_icons(
            &mut self,
            _r: QRect,
            _b: &TabBar,
            _icons: &[Option<crate::TabIcon>],
            _hovered_close_tab: Option<usize>,
        ) -> crate::TabBarHits {
            crate::TabBarHits::default()
        }
        fn draw_tab_bar_layout(
            &mut self,
            _r: QRect,
            _b: &TabBar,
            _hovered_close_tab: Option<usize>,
        ) -> TabBarLayout {
            mock_empty_tab_bar_layout()
        }
        fn draw_tab_bar_icons_layout(
            &mut self,
            _r: QRect,
            _b: &TabBar,
            _icons: &[Option<crate::TabIcon>],
            _hovered_close_tab: Option<usize>,
        ) -> TabBarLayout {
            mock_empty_tab_bar_layout()
        }
        fn draw_activity_bar(
            &mut self,
            _r: QRect,
            _b: &ActivityBar,
            _h: Option<usize>,
        ) -> Vec<crate::ActivityBarRowHit> {
            Vec::new()
        }
        fn draw_terminal(&mut self, _r: QRect, _t: &TerminalPrim) {}
        fn draw_terminal_divider(&mut self, _r: QRect) {}
        fn draw_solid_fill(&mut self, _r: QRect, _c: Color) {}
        fn draw_text_display(&mut self, _r: QRect, _t: &TextDisplay) {}
        fn draw_command_line(&mut self, _r: QRect, _c: &CommandLine) {}
        fn draw_command_line_selection(
            &mut self,
            _r: QRect,
            _c: &CommandLine,
            _s: Option<(usize, usize)>,
        ) {
        }
        fn command_line_layout(
            &self,
            _r: QRect,
            _c: &CommandLine,
        ) -> crate::primitives::command_line::CommandLineLayout {
            Default::default()
        }
        fn status_bar_layout(&self, _r: QRect, _b: &StatusBar) -> crate::StatusBarLayout {
            crate::StatusBarLayout {
                bar_width: 0.0,
                bar_height: 0.0,
                visible_segments: Vec::new(),
                hit_regions: Vec::new(),
                resolved_right_start: 0,
            }
        }
        #[allow(deprecated)] // `TabBarHits` is `#[deprecated]`
        fn tab_bar_layout(&self, _r: QRect, _b: &TabBar) -> crate::TabBarHits {
            crate::TabBarHits::default()
        }
        #[allow(deprecated)] // `TabBarHits` is `#[deprecated]`
        fn tab_bar_layout_icons(
            &self,
            _r: QRect,
            _b: &TabBar,
            _icons: &[Option<crate::TabIcon>],
        ) -> crate::TabBarHits {
            crate::TabBarHits::default()
        }
        fn resolve_tab_bar_layout(&self, _r: QRect, _b: &TabBar) -> TabBarLayout {
            mock_empty_tab_bar_layout()
        }
        fn resolve_tab_bar_layout_icons(
            &self,
            _r: QRect,
            _b: &TabBar,
            _icons: &[Option<crate::TabIcon>],
        ) -> TabBarLayout {
            mock_empty_tab_bar_layout()
        }
        fn activity_bar_layout(
            &self,
            _r: QRect,
            _b: &ActivityBar,
        ) -> Vec<crate::ActivityBarRowHit> {
            Vec::new()
        }
        fn text_display_layout(
            &self,
            r: QRect,
            td: &TextDisplay,
        ) -> crate::primitives::text_display::TextDisplayLayout {
            td.layout(r.width, r.height, |_| {
                crate::primitives::text_display::TextDisplayLineMeasure::new(1.0)
            })
        }
        fn draw_text_input(
            &mut self,
            r: QRect,
            ti: &crate::primitives::text_input::TextInput,
        ) -> crate::primitives::text_input::TextInputLayout {
            ti.layout(
                r,
                crate::primitives::text_input::TextInputMeasure::new(1.0, 1.0),
            )
        }
        fn text_input_layout(
            &self,
            r: QRect,
            ti: &crate::primitives::text_input::TextInput,
        ) -> crate::primitives::text_input::TextInputLayout {
            ti.layout(
                r,
                crate::primitives::text_input::TextInputMeasure::new(1.0, 1.0),
            )
        }
        fn draw_number_input(&mut self, _n: &crate::NumberInput, _l: &crate::NumberInputLayout) {}
        fn draw_combo_box(&mut self, _c: &crate::ComboBox, _l: &crate::ComboBoxLayout) {}
        fn draw_date_picker(&mut self, _d: &crate::DatePicker, _l: &crate::DatePickerLayout) {}
        fn draw_tooltip(&mut self, _t: &crate::Tooltip, _l: &crate::TooltipLayout) {}
        fn draw_context_menu(
            &mut self,
            _m: &crate::ContextMenu,
            _l: &crate::ContextMenuLayout,
        ) -> Vec<(QRect, crate::WidgetId)> {
            Vec::new()
        }
        fn draw_dialog(
            &mut self,
            _d: &crate::primitives::dialog::Dialog,
            _l: &crate::primitives::dialog::DialogLayout,
        ) -> Vec<QRect> {
            Vec::new()
        }
        fn draw_float(
            &mut self,
            _f: &crate::primitives::float::Float,
            _l: &crate::primitives::float::FloatLayout,
        ) {
        }

        fn char_width(&self) -> f32 {
            1.0
        }
        fn line_height(&self) -> f32 {
            1.0
        }
        fn list_char_width(&self) -> f32 {
            1.0
        }

        fn measure_text(&self, text: &str, _role: crate::FontRole) -> (f32, f32) {
            (text.chars().count() as f32, 1.0)
        }

        fn default_fonts(&self) -> crate::backend::PlatformFontDefaults {
            crate::backend::PlatformFontDefaults {
                editor_family: String::new(),
                editor_size_pt: 0.0,
                ui_family: String::new(),
                ui_size_pt: 0.0,
            }
        }

        // ── #13: stubs for the trait methods added with this issue ──

        fn draw_multi_section_view(
            &mut self,
            _r: QRect,
            _v: &crate::primitives::multi_section_view::MultiSectionView,
        ) {
        }

        fn msv_layout(
            &self,
            r: QRect,
            v: &crate::primitives::multi_section_view::MultiSectionView,
        ) -> crate::primitives::multi_section_view::MultiSectionViewLayout {
            // Mock returns the primitive's natural layout with default
            // metrics — sufficient for cross-backend compile checks.
            v.layout(
                r,
                crate::primitives::multi_section_view::MsvLayoutMetrics::default(),
                |_| crate::primitives::multi_section_view::SectionMeasure::default(),
            )
        }

        fn msv_metrics(&self) -> crate::primitives::multi_section_view::MsvLayoutMetrics {
            crate::primitives::multi_section_view::MsvLayoutMetrics::default()
        }

        fn tree_layout(&self, r: QRect, t: &TreeView) -> crate::primitives::tree::TreeViewLayout {
            t.layout(r.width, r.height, |_| {
                crate::primitives::tree::TreeRowMeasure::new(1.0)
            })
        }

        fn tree_vscrollbar(&self, r: QRect, t: &TreeView) -> Option<crate::Scrollbar> {
            t.vscrollbar_with_track_width(r, 1.0, 1.0)
        }

        fn form_layout(&self, r: QRect, form: &Form) -> crate::primitives::form::FormLayout {
            let area = q_rect_to_ratatui(r);
            crate::tui::tui_form_layout(form, area)
        }

        fn draw_editor(
            &mut self,
            _r: QRect,
            _e: &crate::primitives::editor::Editor,
        ) -> crate::backend::EditorPaintResult {
            crate::backend::EditorPaintResult::default()
        }

        fn draw_message_list(
            &mut self,
            _r: QRect,
            _l: &crate::primitives::message_list::MessageList,
        ) {
        }

        fn draw_rich_text_popup(
            &mut self,
            _p: &crate::primitives::rich_text_popup::RichTextPopup,
            _l: &crate::primitives::rich_text_popup::RichTextPopupLayout,
        ) {
        }

        fn draw_find_replace(
            &mut self,
            _r: QRect,
            _p: &crate::primitives::find_replace::FindReplacePanel,
        ) {
        }

        fn draw_completions(
            &mut self,
            _c: &crate::primitives::completions::Completions,
            _l: &crate::primitives::completions::CompletionsLayout,
        ) {
        }

        fn draw_scrollbar(&mut self, _r: QRect, _s: &crate::primitives::scrollbar::Scrollbar) {}
        fn draw_drop_overlay(&mut self, _o: &crate::primitives::drop_zone::DropOverlay) {}

        fn draw_menu_bar(
            &mut self,
            _r: QRect,
            bar: &MenuBar,
        ) -> crate::primitives::menu_bar::MenuBarLayout {
            let bounds = crate::event::Rect::new(_r.x, _r.y, _r.width, _r.height);
            bar.layout(bounds, |_| {
                crate::primitives::menu_bar::MenuBarItemMeasure::new(0.0)
            })
        }

        fn menu_bar_layout(
            &self,
            _r: QRect,
            bar: &MenuBar,
        ) -> crate::primitives::menu_bar::MenuBarLayout {
            let bounds = crate::event::Rect::new(_r.x, _r.y, _r.width, _r.height);
            bar.layout(bounds, |_| {
                crate::primitives::menu_bar::MenuBarItemMeasure::new(0.0)
            })
        }

        fn draw_split(
            &mut self,
            _r: QRect,
            split: &Split,
        ) -> crate::primitives::split::SplitLayout {
            let bounds = crate::event::Rect::new(_r.x, _r.y, _r.width, _r.height);
            split.layout(bounds, crate::primitives::split::SplitMeasure::new(1.0))
        }

        fn split_layout(&self, _r: QRect, split: &Split) -> crate::primitives::split::SplitLayout {
            let bounds = crate::event::Rect::new(_r.x, _r.y, _r.width, _r.height);
            split.layout(bounds, crate::primitives::split::SplitMeasure::new(1.0))
        }

        fn draw_split_tree(
            &mut self,
            _r: QRect,
            tree: &crate::primitives::split_tree::SplitTree,
        ) -> crate::primitives::split_tree::SplitTreeLayout {
            let bounds = crate::event::Rect::new(_r.x, _r.y, _r.width, _r.height);
            tree.layout(
                bounds,
                crate::primitives::split_tree::SplitTreeMeasure::new(1.0),
            )
        }

        fn split_tree_layout(
            &self,
            _r: QRect,
            tree: &crate::primitives::split_tree::SplitTree,
        ) -> crate::primitives::split_tree::SplitTreeLayout {
            let bounds = crate::event::Rect::new(_r.x, _r.y, _r.width, _r.height);
            tree.layout(
                bounds,
                crate::primitives::split_tree::SplitTreeMeasure::new(1.0),
            )
        }

        fn draw_panel(
            &mut self,
            _r: QRect,
            panel: &crate::primitives::panel::Panel,
        ) -> crate::primitives::panel::PanelLayout {
            let bounds = crate::event::Rect::new(_r.x, _r.y, _r.width, _r.height);
            panel.layout(bounds, crate::primitives::panel::PanelMeasure::new(1.0))
        }

        fn panel_layout(
            &self,
            _r: QRect,
            panel: &crate::primitives::panel::Panel,
        ) -> crate::primitives::panel::PanelLayout {
            let bounds = crate::event::Rect::new(_r.x, _r.y, _r.width, _r.height);
            panel.layout(bounds, crate::primitives::panel::PanelMeasure::new(1.0))
        }

        fn draw_canvas(
            &mut self,
            r: QRect,
            canvas: &crate::primitives::canvas::Canvas,
        ) -> crate::primitives::canvas::CanvasLayout {
            let bounds = crate::event::Rect::new(r.x, r.y, r.width, r.height);
            canvas.layout(bounds)
        }

        fn draw_toast_overlay(
            &mut self,
            _r: QRect,
            stack: &crate::primitives::toast::ToastOverlay,
        ) -> crate::primitives::toast::ToastStackLayout {
            stack.layout(_r.x, _r.y, _r.width, _r.height, 1.0, 1.0, |_| {
                crate::primitives::toast::ToastMeasure::new(40.0, 1.0)
            })
        }

        fn toast_stack_layout(
            &self,
            _r: QRect,
            stack: &crate::primitives::toast::ToastOverlay,
        ) -> crate::primitives::toast::ToastStackLayout {
            stack.layout(_r.x, _r.y, _r.width, _r.height, 1.0, 1.0, |_| {
                crate::primitives::toast::ToastMeasure::new(40.0, 1.0)
            })
        }

        fn draw_pipeline_view(
            &mut self,
            _r: QRect,
            view: &crate::primitives::pipeline_view::PipelineView,
        ) -> crate::primitives::pipeline_view::PipelineViewLayout {
            view.layout(
                _r.x,
                _r.y,
                crate::primitives::pipeline_view::PipelineViewMeasure::new(
                    _r.width, _r.height, 4.0, 10.0,
                ),
            )
        }

        fn pipeline_view_layout(
            &self,
            _r: QRect,
            view: &crate::primitives::pipeline_view::PipelineView,
        ) -> crate::primitives::pipeline_view::PipelineViewLayout {
            view.layout(
                _r.x,
                _r.y,
                crate::primitives::pipeline_view::PipelineViewMeasure::new(
                    _r.width, _r.height, 4.0, 10.0,
                ),
            )
        }

        fn draw_progress(
            &mut self,
            _r: QRect,
            bar: &crate::primitives::progress::ProgressBar,
        ) -> crate::primitives::progress::ProgressBarLayout {
            bar.layout(
                _r.x,
                _r.y,
                crate::primitives::progress::ProgressBarMeasure::new(_r.width, _r.height),
            )
        }

        fn progress_layout(
            &self,
            _r: QRect,
            bar: &crate::primitives::progress::ProgressBar,
        ) -> crate::primitives::progress::ProgressBarLayout {
            bar.layout(
                _r.x,
                _r.y,
                crate::primitives::progress::ProgressBarMeasure::new(_r.width, _r.height),
            )
        }

        fn draw_spinner(
            &mut self,
            _r: QRect,
            spinner: &crate::primitives::spinner::Spinner,
        ) -> crate::primitives::spinner::SpinnerLayout {
            spinner.layout(
                _r.x,
                _r.y,
                crate::primitives::spinner::SpinnerMeasure::new(_r.width, 1.0),
            )
        }

        fn spinner_layout(
            &self,
            _r: QRect,
            spinner: &crate::primitives::spinner::Spinner,
        ) -> crate::primitives::spinner::SpinnerLayout {
            spinner.layout(
                _r.x,
                _r.y,
                crate::primitives::spinner::SpinnerMeasure::new(_r.width, 1.0),
            )
        }

        fn draw_button(
            &mut self,
            r: QRect,
            button: &crate::primitives::button::Button,
        ) -> crate::primitives::button::ButtonLayout {
            button.layout(crate::event::Rect::new(r.x, r.y, r.width, r.height))
        }

        fn button_layout(
            &self,
            r: QRect,
            button: &crate::primitives::button::Button,
        ) -> crate::primitives::button::ButtonLayout {
            button.layout(crate::event::Rect::new(r.x, r.y, r.width, r.height))
        }

        fn draw_radio_group(
            &mut self,
            r: QRect,
            group: &crate::primitives::radio_group::RadioGroup,
        ) -> crate::primitives::radio_group::RadioGroupLayout {
            let bounds = crate::event::Rect::new(r.x, r.y, r.width, r.height);
            group.layout(
                bounds,
                |_option: &crate::primitives::radio_group::RadioOption| {
                    crate::primitives::radio_group::RadioOptionMeasure {
                        width: bounds.width,
                        height: 1.0,
                    }
                },
            )
        }

        fn radio_group_layout(
            &self,
            r: QRect,
            group: &crate::primitives::radio_group::RadioGroup,
        ) -> crate::primitives::radio_group::RadioGroupLayout {
            let bounds = crate::event::Rect::new(r.x, r.y, r.width, r.height);
            group.layout(
                bounds,
                |_option: &crate::primitives::radio_group::RadioOption| {
                    crate::primitives::radio_group::RadioOptionMeasure {
                        width: bounds.width,
                        height: 1.0,
                    }
                },
            )
        }

        fn draw_switch(
            &mut self,
            r: QRect,
            switch: &crate::primitives::switch::Switch,
        ) -> crate::primitives::switch::SwitchLayout {
            switch.layout(crate::event::Rect::new(r.x, r.y, r.width, r.height))
        }

        fn switch_layout(
            &self,
            r: QRect,
            switch: &crate::primitives::switch::Switch,
        ) -> crate::primitives::switch::SwitchLayout {
            switch.layout(crate::event::Rect::new(r.x, r.y, r.width, r.height))
        }

        fn draw_command_center(
            &mut self,
            _r: QRect,
            cc: &crate::primitives::command_center::CommandCenter,
        ) -> crate::primitives::command_center::CommandCenterLayout {
            cc.layout(
                crate::event::Rect::new(_r.x, _r.y, _r.width, _r.height),
                crate::primitives::command_center::CommandCenterMeasure {
                    arrow_width: 2.0,
                    gap: 1.0,
                    search_box_width: 0.0,
                    height: 1.0,
                },
            )
        }

        fn command_center_layout(
            &self,
            _r: QRect,
            cc: &crate::primitives::command_center::CommandCenter,
        ) -> crate::primitives::command_center::CommandCenterLayout {
            cc.layout(
                crate::event::Rect::new(_r.x, _r.y, _r.width, _r.height),
                crate::primitives::command_center::CommandCenterMeasure {
                    arrow_width: 2.0,
                    gap: 1.0,
                    search_box_width: 0.0,
                    height: 1.0,
                },
            )
        }

        fn draw_chart(
            &mut self,
            _r: QRect,
            chart: &crate::primitives::chart::Chart,
            _hovered_point: Option<(usize, usize)>,
            _crosshair_x: Option<f64>,
        ) -> crate::primitives::chart::ChartLayout {
            chart.layout(
                _r.x,
                _r.y,
                crate::primitives::chart::ChartMeasure {
                    width: _r.width,
                    height: _r.height,
                    char_width: 1.0,
                    line_height: 1.0,
                },
            )
        }

        fn chart_layout(
            &self,
            _r: QRect,
            chart: &crate::primitives::chart::Chart,
        ) -> crate::primitives::chart::ChartLayout {
            chart.layout(
                _r.x,
                _r.y,
                crate::primitives::chart::ChartMeasure {
                    width: _r.width,
                    height: _r.height,
                    char_width: 1.0,
                    line_height: 1.0,
                },
            )
        }

        fn draw_toolbar_with_options(
            &mut self,
            r: QRect,
            bar: &crate::primitives::toolbar::Toolbar,
            _interaction: &crate::interaction::InteractionState,
            _options: crate::primitives::toolbar::ToolbarPaintOptions,
        ) -> crate::primitives::toolbar::ToolbarLayout {
            bar.layout(r.x, r.y, r.width, r.height, |_| {
                crate::primitives::toolbar::ToolbarItemMeasure::new(0.0)
            })
        }

        fn toolbar_layout(
            &self,
            r: QRect,
            bar: &crate::primitives::toolbar::Toolbar,
        ) -> crate::primitives::toolbar::ToolbarLayout {
            bar.layout(r.x, r.y, r.width, r.height, |_| {
                crate::primitives::toolbar::ToolbarItemMeasure::new(0.0)
            })
        }

        fn draw_sidebar_panel_interactive(
            &mut self,
            r: QRect,
            panel: &crate::primitives::sidebar_panel::SidebarPanel,
            _interaction: &crate::interaction::InteractionState,
        ) -> crate::primitives::sidebar_panel::SidebarPanelLayout {
            panel.layout(
                r,
                crate::primitives::sidebar_panel::SidebarPanelMeasure::new(1.0, 0.0),
                |_| crate::primitives::toolbar::ToolbarItemMeasure::new(0.0),
            )
        }

        fn sidebar_panel_layout(
            &self,
            r: QRect,
            panel: &crate::primitives::sidebar_panel::SidebarPanel,
        ) -> crate::primitives::sidebar_panel::SidebarPanelLayout {
            panel.layout(
                r,
                crate::primitives::sidebar_panel::SidebarPanelMeasure::new(1.0, 0.0),
                |_| crate::primitives::toolbar::ToolbarItemMeasure::new(0.0),
            )
        }

        fn draw_diff_view(
            &mut self,
            _r: QRect,
            view: &crate::primitives::diff_view::DiffView,
        ) -> crate::primitives::diff_view::DiffViewLayout {
            crate::primitives::diff_view::DiffViewLayout {
                visible_rows: 0,
                total_rows: view.total_rows(),
            }
        }

        fn draw_board(
            &mut self,
            r: QRect,
            model: &crate::primitives::board::BoardModel,
        ) -> crate::primitives::board::BoardLayout {
            crate::primitives::board::board_layout(
                model,
                r.x,
                r.y,
                r.width,
                r.height,
                crate::primitives::board::BoardMeasure::new(
                    crate::tui::board::TUI_BOARD_COL_MIN_CELLS,
                    1.0,
                    1.0,
                    crate::tui::board::TUI_BOARD_CARD_H,
                    0.0,
                ),
            )
        }

        fn board_layout(
            &self,
            r: QRect,
            model: &crate::primitives::board::BoardModel,
        ) -> crate::primitives::board::BoardLayout {
            crate::primitives::board::board_layout(
                model,
                r.x,
                r.y,
                r.width,
                r.height,
                crate::primitives::board::BoardMeasure::new(
                    crate::tui::board::TUI_BOARD_COL_MIN_CELLS,
                    1.0,
                    1.0,
                    crate::tui::board::TUI_BOARD_CARD_H,
                    0.0,
                ),
            )
        }

        fn draw_minimap(
            &mut self,
            _r: QRect,
            _m: &crate::primitives::minimap::Minimap,
        ) -> crate::backend::MinimapPaintResult {
            crate::backend::MinimapPaintResult::default()
        }

        fn minimap_layout(
            &self,
            _r: QRect,
            _m: &crate::primitives::minimap::Minimap,
        ) -> crate::primitives::minimap::MinimapLayout {
            crate::primitives::minimap::MinimapLayout::default()
        }

        fn draw_image(
            &mut self,
            _r: QRect,
            _i: &crate::primitives::image::Image,
        ) -> crate::backend::ImagePaintResult {
            crate::backend::ImagePaintResult::Unsupported
        }
    }

    /// Generic helper — the minimal "app render code" that consumes
    /// `Backend` through `<B>`. Future backends slot in here without
    /// changes.
    fn paint_overlays<B: Backend>(backend: &mut B, palette: &Palette, list: &ListView) {
        backend.draw_palette(QRect::new(10.0, 5.0, 60.0, 14.0), palette);
        backend.draw_list(QRect::new(0.0, 20.0, 80.0, 4.0), list);
    }

    fn sample_palette() -> Palette {
        Palette {
            id: WidgetId::new("test:palette"),
            title: "Pick one".to_string(),
            query: String::new(),
            query_cursor: 0,
            items: vec![
                PaletteItem {
                    text: StyledText {
                        spans: vec![StyledSpan::plain("alpha")],
                    },
                    detail: None,
                    icon: None,
                    match_positions: Vec::new(),
                    depth: 0,
                    expandable: false,
                    expanded: false,
                },
                PaletteItem {
                    text: StyledText {
                        spans: vec![StyledSpan::plain("beta")],
                    },
                    detail: None,
                    icon: None,
                    match_positions: Vec::new(),
                    depth: 0,
                    expandable: false,
                    expanded: false,
                },
            ],
            selected_idx: 0,
            scroll_offset: 0,
            total_count: 2,
            has_focus: true,
            show_query: true,
            create_label: None,
            preview: None,
            mode: crate::primitives::palette::PaletteMode::List,
        }
    }

    fn sample_list() -> ListView {
        ListView {
            id: WidgetId::new("test:list"),
            title: None,
            items: vec![ListItem {
                text: StyledText {
                    spans: vec![StyledSpan::plain("only")],
                },
                icon: None,
                detail: None,
                decoration: crate::Decoration::Normal,
            }],
            selected_idx: 0,
            scroll_offset: 0,
            has_focus: true,
            bordered: false,
            h_scroll: 0,
            max_content_width: None,
            show_v_scrollbar: false,
        }
    }

    #[test]
    fn paint_overlays_records_through_mock_backend() {
        let mut mock = MockBackend::new();
        let palette = sample_palette();
        let list = sample_list();

        paint_overlays(&mut mock, &palette, &list);

        assert_eq!(mock.calls.len(), 2);
        assert!(matches!(
            mock.calls[0],
            DrawCall::Palette { item_count: 2, .. }
        ));
        assert!(matches!(
            mock.calls[1],
            DrawCall::List { item_count: 1, .. }
        ));
    }

    #[test]
    fn paint_overlays_compiles_against_tui_backend() {
        // Compile-only assertion — the same generic function used with
        // MockBackend above is also valid for TuiBackend. We don't run
        // the draws (they require an active frame scope) but the type
        // monomorphisation proves the trait constraint is satisfied
        // for every backend impl.
        let _: fn(&mut TuiBackend, &Palette, &ListView) = paint_overlays::<TuiBackend>;
    }

    /// `Backend::set_style` → `TuiBackend::current_style` →
    /// `TuiBackend::draw_palette` must carry a caller-set
    /// `backdrop_opacity` all the way to the painted buffer — proving
    /// the live-style wiring, not just the free `draw_palette_with_style`
    /// function called directly with an explicit `&Style` (as the
    /// `tui::palette` module's own tests do).
    #[test]
    fn draw_palette_paints_with_backend_live_style() {
        use ratatui::backend::TestBackend;

        let mut backend = TuiBackend::new();
        backend.set_style(crate::Style::default().with_backdrop_opacity(0.5));
        let palette = sample_palette();
        let rect = QRect::new(0.0, 0.0, 20.0, 10.0);

        let mut terminal =
            ratatui::Terminal::new(TestBackend::new(20, 10)).expect("TestBackend terminal");
        terminal
            .draw(|frame| {
                backend.enter_frame_scope(frame, |b| {
                    b.draw_palette(rect, &palette);
                });
            })
            .expect("draw");

        let theme = crate::Theme::default();
        let expected_bg = crate::tui::ratatui_color(theme.background.blend(theme.surface_bg, 0.5));
        // (1, 1) sits inside the border, below the title row — a cell
        // only ever painted with the blended backdrop fill.
        let buf = terminal.backend().buffer();
        assert_eq!(buf[(1, 1)].bg, expected_bg);
    }

    #[test]
    fn mock_backend_modal_stack_routes_through_trait() {
        // Modal stack is on the trait too — backends that implement it
        // wire into `crate::dispatch::dispatch_mouse_down` automatically.
        let mock = MockBackend::new();
        mock.modal_stack_handle()
            .borrow_mut()
            .push(WidgetId::new("test:popup"), QRect::new(0.0, 0.0, 10.0, 5.0));
        assert_eq!(mock.modal_stack_handle().borrow().len(), 1);
    }

    /// `TuiBackend::modal_stack_handle` must hand back a
    /// handle that shares state with the backend's own modal stack (the
    /// same guarantee `GtkBackend::modal_stack_handle` already proves in
    /// `gtk::backend::tests::gtk_backend_modal_stack_handle_shares_state`)
    /// — two independently-obtained handles must observe each other's
    /// writes, not two disconnected copies.
    #[test]
    fn tui_backend_modal_stack_handle_shares_state() {
        let backend = TuiBackend::new();
        let h1 = backend.modal_stack_handle();
        let h2 = backend.modal_stack_handle();
        h1.borrow_mut()
            .push(WidgetId::new("test:popup"), QRect::new(0.0, 0.0, 10.0, 5.0));
        assert_eq!(h2.borrow().len(), 1);
    }

    /// The bridge methods this issue removed
    /// (`modal_stack_mut()` / `drag_and_modal_mut()`) synthesized a
    /// `&mut ModalStack` via `unsafe { Rc::as_ptr(..) }`, which bypassed
    /// `RefCell`'s runtime borrow check entirely — two live mutable
    /// aliases would silently corrupt state instead of panicking. Now
    /// that `modal_stack_handle()` is the only way to reach the stack,
    /// holding a `borrow_mut()` while a second one is taken through the
    /// same (or another) handle must panic loudly, not alias silently.
    #[test]
    #[should_panic(expected = "already borrowed")]
    fn modal_stack_handle_reentrant_borrow_mut_panics_loudly() {
        let backend = TuiBackend::new();
        let handle = backend.modal_stack_handle();
        let _first = handle.borrow_mut();
        let _second = handle.borrow_mut(); // must panic: real double-borrow check
    }

    /// Issue #1132, D-014's "degrade" story: TUI's `measure_text` ignores
    /// `role` (one font by definition on a terminal grid) and reports
    /// [`display_width`]'s cell count for both — a CJK string must come
    /// back wider than its `chars().count()` would suggest, same as
    /// every other TUI cell-width call site.
    #[test]
    fn tui_backend_measure_text_uses_display_width_and_ignores_role() {
        let backend = TuiBackend::new();

        let (w, h) = Backend::measure_text(&backend, "ab日本", crate::FontRole::Chrome);
        assert_eq!(w, 6.0, "2 ASCII + 2 double-width CJK cells = 6");
        assert_eq!(h, 1.0);

        let (chrome_w, _) = Backend::measure_text(&backend, "ab日本", crate::FontRole::Chrome);
        let (editor_w, _) = Backend::measure_text(&backend, "ab日本", crate::FontRole::Editor);
        assert_eq!(chrome_w, editor_w, "role has nothing to select on TUI");
    }

    /// `Backend::context_menu_viewport` is the surface a caller lays a
    /// context menu out in: the viewport inset on all four sides by
    /// `context_menu_border_inset`, so the chrome the rasteriser paints
    /// *outside* the menu's item region has a cell to live on. TUI's box
    /// border is one cell, so each edge moves in by one and both
    /// dimensions shrink by two.
    #[test]
    fn tui_backend_context_menu_viewport_reserves_border_on_all_four_sides() {
        let mut backend = TuiBackend::new();
        backend.begin_frame(Viewport::new(80.0, 24.0, 1.0));

        assert_eq!(
            Backend::context_menu_border_inset(&backend),
            1.0,
            "TUI paints a one-cell box border outside the item region"
        );
        assert_eq!(
            Backend::context_menu_viewport(&backend),
            QRect::new(1.0, 1.0, 78.0, 22.0),
            "all four edges must be reserved, not just the top-left"
        );
    }

    /// A viewport too small to hold the chrome must degrade to an empty
    /// surface rather than a negative-width rect (which would make the
    /// menu's own clamping arithmetic nonsense).
    #[test]
    fn tui_backend_context_menu_viewport_clamps_tiny_viewport_to_empty() {
        let mut backend = TuiBackend::new();
        backend.begin_frame(Viewport::new(1.0, 1.0, 1.0));

        let vp = Backend::context_menu_viewport(&backend);
        assert_eq!(vp.width, 0.0, "width cannot go negative: {vp:?}");
        assert_eq!(vp.height, 0.0, "height cannot go negative: {vp:?}");
    }

    /// A backend that paints its menu chrome *inside* the item region
    /// reserves nothing: with the default `0.0` inset the menu surface
    /// is the whole viewport, so the shared helper is a no-op there.
    #[test]
    fn default_border_inset_leaves_the_whole_viewport_for_the_menu() {
        let backend = MockBackend::new();

        assert_eq!(Backend::context_menu_border_inset(&backend), 0.0);
        assert_eq!(
            Backend::context_menu_viewport(&backend),
            QRect::new(0.0, 0.0, 80.0, 24.0)
        );
    }

    /// Issue #1156: TUI has no font concept at all, so `default_fonts()`
    /// returns the documented all-sentinel value rather than inheriting
    /// any real platform convention.
    #[test]
    fn tui_backend_default_fonts_is_all_sentinel() {
        let backend = TuiBackend::new();
        let defaults = Backend::default_fonts(&backend);
        assert_eq!(defaults.editor_family, "");
        assert_eq!(defaults.editor_size_pt, 0.0);
        assert_eq!(defaults.ui_family, "");
        assert_eq!(defaults.ui_size_pt, 0.0);
    }

    /// The whole point of `modal_stack_handle` is that
    /// the handle outlives the borrow that produced it — this is the
    /// stash-then-reuse pattern GTK hosts
    /// (and vimcode's macOS host, once #699 lands there too) depend on.
    /// Prove it compiles and behaves through `&mut dyn Backend`, not
    /// just the concrete `TuiBackend` type.
    #[test]
    fn modal_stack_handle_outlives_the_backend_borrow_through_the_trait() {
        let mut backend = TuiBackend::new();
        let stack_rc = {
            let dyn_backend: &mut dyn Backend = &mut backend;
            dyn_backend.modal_stack_handle() // stash, then the `&mut dyn Backend` borrow ends
        };
        // `backend` is usable again here — the handle didn't keep it borrowed.
        backend.begin_frame(Viewport::new(80.0, 24.0, 1.0));
        stack_rc
            .borrow_mut()
            .push(WidgetId::new("test:popup"), QRect::new(0.0, 0.0, 10.0, 5.0));
        assert_eq!(backend.modal_stack_handle().borrow().len(), 1);
    }

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

    /// `TuiBackend::draw_dialog` must mark the modal
    /// stack entry it paints, so `ModalStack::unpainted_ids` can catch a
    /// backend that registers a modal for hit-testing but never actually
    /// paints it — vimcode#587's exact failure shape ("registered but
    /// invisible"), reproduced here at the backend-wiring level rather
    /// than `ModalStack` in isolation (already covered in
    /// `crate::modal_stack::tests`).
    #[test]
    fn draw_dialog_marks_its_modal_stack_entry_painted() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let dialog_id = WidgetId::new("confirm");
        let dialog = crate::Dialog {
            id: dialog_id.clone(),
            title: crate::StyledText::plain("Confirm"),
            body: vec![crate::StyledText::plain("Really?")],
            table: None,
            buttons: vec![crate::DialogButton {
                id: WidgetId::new("ok"),
                label: "OK".into(),
                is_default: true,
                is_cancel: false,
                tint: None,
            }],
            severity: None,
            vertical_buttons: false,
            input: None,
        };
        let measure = crate::DialogMeasure {
            width: 40.0,
            title_height: 1.0,
            body_height: 1.0,
            table_height: 0.0,
            input_height: 0.0,
            button_row_height: 1.0,
            button_width: 10.0,
            button_gap: 2.0,
            padding: 1.0,
        };
        let viewport_rect = QRect::new(0.0, 0.0, 80.0, 24.0);
        let layout = dialog.layout(viewport_rect, measure, |_| {
            crate::ToolbarItemMeasure::new(0.0)
        });

        let mut backend = TuiBackend::new();
        backend.begin_frame(Viewport::new(80.0, 24.0, 1.0));
        backend
            .modal_stack_handle()
            .borrow_mut()
            .push(dialog_id.clone(), layout.bounds);

        // Registered but not yet drawn this frame — exactly the drift
        // #455 wants surfaced.
        assert_eq!(
            backend.modal_stack_handle().borrow().unpainted_ids(),
            vec![dialog_id.clone()]
        );

        let mut terminal = Terminal::new(TestBackend::new(80, 24)).expect("test terminal");
        terminal
            .draw(|frame| {
                backend.enter_frame_scope(frame, |b| {
                    b.draw_dialog(&dialog, &layout);
                });
            })
            .expect("draw");

        // draw_dialog ran through the real trait method and marked its
        // own id painted — the drift is gone for this frame.
        assert!(backend
            .modal_stack_handle()
            .borrow()
            .unpainted_ids()
            .is_empty());

        // The next frame must reset the mark: a backend that stops
        // calling draw_dialog (even though the modal stays registered)
        // has to be caught again, not remembered as painted forever.
        backend.begin_frame(Viewport::new(80.0, 24.0, 1.0));
        assert_eq!(
            backend.modal_stack_handle().borrow().unpainted_ids(),
            vec![dialog_id]
        );
    }

    // ─── Stage 6: accelerator matching ──────────────────────────────────────

    use crate::{Key, Modifiers, NamedKey};

    fn ctrl_p_keypress() -> UiEvent {
        UiEvent::KeyPressed {
            key: Key::Char('p'),
            modifiers: Modifiers {
                ctrl: true,
                ..Default::default()
            },
            repeat: false,
        }
    }

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

    /// Four `Fixed(30.0)` columns (content boundaries 0/30/60/90/120)
    /// in a 60-wide viewport — the #550 repro geometry.
    fn wide_hscroll_table() -> crate::DataTable {
        crate::DataTable {
            id: WidgetId::new("wide-hscroll"),
            columns: ["a", "b", "c", "d"]
                .iter()
                .map(|t| crate::Column {
                    title: (*t).into(),
                    width: crate::ColumnWidth::Fixed(30.0),
                    align: crate::ColumnAlign::Left,
                })
                .collect(),
            rows: vec![crate::DataRow {
                cells: vec![
                    StyledText::plain("a-one"),
                    StyledText::plain("b-two"),
                    StyledText::plain("c-three"),
                    StyledText::plain("d-four"),
                ],
                decoration: crate::Decoration::Normal,
            }],
            selected_idx: None,
            scroll_offset: 0,
            sort: None,
            has_focus: false,
            show_scrollbar: false,
            min_total_width: Some(120.0),
            h_scroll: 0.0,
            column_overrides: Vec::new(),
            footer: None,
        }
    }

    /// #550 round 3: `Backend::data_table_layout` is the *cache-free,
    /// layout-on-demand* hit-test path (see
    /// `examples/common/data_table_app.rs`, which calls it from every
    /// mouse handler without repainting). It resolved geometry with its
    /// own `table.layout(..)` call and so returned the raw fractional
    /// `h_scroll`, while `draw_data_table` painted at the rounded one —
    /// reopening the original defect through a second entry point.
    #[test]
    fn data_table_layout_rounds_h_scroll_like_the_renderer() {
        let backend = TuiBackend::new();
        let rect = QRect::new(0.0, 0.0, 60.0, 3.0);
        let mut table = wide_hscroll_table();

        // A trackpad/wheel h-scroll lands on an arbitrary fraction; the
        // example's `UiEvent::Scroll` handler does no rounding at all.
        table.h_scroll = 23.7;
        let layout = backend.data_table_layout(rect, &table);
        assert_eq!(
            layout.h_scroll, 24.0,
            "layout-on-demand must carry the same rounded offset the renderer paints at"
        );

        // The review's exact repro value, and the click it misroutes.
        table.h_scroll = 15.6;
        let layout = backend.data_table_layout(rect, &table);
        assert_eq!(layout.h_scroll, 16.0);
        assert_eq!(
            layout.column_hit(14.0),
            Some(1),
            "integer click x=14 sits on c1 as painted at h_scroll=15.6"
        );
        assert_ne!(
            layout.column_hit(14.0),
            Some(0),
            "un-rounded 15.6 would put this at content x=29.6, inside c0"
        );
    }

    /// The two TUI entry points must be interchangeable: a consumer that
    /// hit-tests against a repaint-free layout has to land on exactly
    /// what the last `draw_data_table` put on screen.
    #[test]
    fn data_table_layout_matches_draw_data_table_at_every_fractional_offset() {
        let backend = TuiBackend::new();
        let rect = QRect::new(0.0, 0.0, 60.0, 3.0);
        let area = q_rect_to_ratatui(rect);
        let mut table = wide_hscroll_table();

        for tenths in 0..=600u32 {
            table.h_scroll = tenths as f32 / 10.0;
            let on_demand = backend.data_table_layout(rect, &table);
            let mut buf = ratatui::buffer::Buffer::empty(area);
            let painted =
                crate::tui::draw_data_table(&mut buf, area, &table, &backend.current_theme, None);
            assert_eq!(
                on_demand, painted,
                "layouts diverged at h_scroll = {}",
                table.h_scroll
            );
        }
    }

    #[test]
    fn accelerator_match_replaces_keypressed_with_accelerator() {
        let mut backend = TuiBackend::new();
        backend.register_accelerator(&make_acc("tui.fuzzy_finder", "<C-p>"));

        let mut events = vec![ctrl_p_keypress()];
        backend.apply_accelerators(&mut events);

        assert_eq!(events.len(), 1);
        match &events[0] {
            UiEvent::Accelerator(id, mods) => {
                assert_eq!(id.as_str(), "tui.fuzzy_finder");
                assert!(mods.ctrl);
            }
            other => panic!("expected Accelerator, got {:?}", other),
        }
    }

    #[test]
    fn accelerator_match_named_keys() {
        let mut backend = TuiBackend::new();
        backend.register_accelerator(&make_acc("debug.continue", "<F5>"));

        let mut events = vec![UiEvent::KeyPressed {
            key: Key::Named(NamedKey::F(5)),
            modifiers: Modifiers::default(),
            repeat: false,
        }];
        backend.apply_accelerators(&mut events);

        match &events[0] {
            UiEvent::Accelerator(id, _) => assert_eq!(id.as_str(), "debug.continue"),
            other => panic!("expected Accelerator, got {:?}", other),
        }
    }

    #[test]
    fn accelerator_match_uppercase_letter_normalised() {
        // `<C-S-T>` and a Shift+T keypress (which arrives as Char('T')
        // from crossterm with SHIFT in modifiers) must match.
        let mut backend = TuiBackend::new();
        backend.register_accelerator(&make_acc("test.upper", "<C-S-T>"));

        let mut events = vec![UiEvent::KeyPressed {
            key: Key::Char('T'),
            modifiers: Modifiers {
                ctrl: true,
                shift: true,
                ..Default::default()
            },
            repeat: false,
        }];
        backend.apply_accelerators(&mut events);

        match &events[0] {
            UiEvent::Accelerator(id, _) => assert_eq!(id.as_str(), "test.upper"),
            other => panic!("expected Accelerator, got {:?}", other),
        }
    }

    #[test]
    fn accelerator_no_match_stays_keypressed() {
        let mut backend = TuiBackend::new();
        backend.register_accelerator(&make_acc("tui.fuzzy_finder", "<C-p>"));

        let mut events = vec![UiEvent::KeyPressed {
            key: Key::Char('q'),
            modifiers: Modifiers {
                ctrl: true,
                ..Default::default()
            },
            repeat: false,
        }];
        backend.apply_accelerators(&mut events);

        assert!(matches!(events[0], UiEvent::KeyPressed { .. }));
    }

    #[test]
    fn accelerator_modifier_mismatch_no_match() {
        // `<C-p>` should NOT fire on `p` alone (no modifiers).
        let mut backend = TuiBackend::new();
        backend.register_accelerator(&make_acc("tui.fuzzy_finder", "<C-p>"));

        let mut events = vec![UiEvent::KeyPressed {
            key: Key::Char('p'),
            modifiers: Modifiers::default(),
            repeat: false,
        }];
        backend.apply_accelerators(&mut events);

        assert!(matches!(events[0], UiEvent::KeyPressed { .. }));
    }

    #[test]
    fn accelerator_unregister_removes_match() {
        let mut backend = TuiBackend::new();
        backend.register_accelerator(&make_acc("tui.fuzzy_finder", "<C-p>"));
        backend.unregister_accelerator(&AcceleratorId::new("tui.fuzzy_finder"));

        let mut events = vec![ctrl_p_keypress()];
        backend.apply_accelerators(&mut events);

        assert!(matches!(events[0], UiEvent::KeyPressed { .. }));
    }

    #[test]
    fn accelerator_re_register_replaces_binding() {
        // Registering the same id twice should swap the binding, not
        // accumulate stale entries.
        let mut backend = TuiBackend::new();
        backend.register_accelerator(&make_acc("test.toggle", "<C-p>"));
        backend.register_accelerator(&make_acc("test.toggle", "<C-q>"));

        let mut events = vec![ctrl_p_keypress()];
        backend.apply_accelerators(&mut events);
        assert!(
            matches!(events[0], UiEvent::KeyPressed { .. }),
            "old binding must not match after re-register"
        );

        let mut events = vec![UiEvent::KeyPressed {
            key: Key::Char('q'),
            modifiers: Modifiers {
                ctrl: true,
                ..Default::default()
            },
            repeat: false,
        }];
        backend.apply_accelerators(&mut events);
        assert!(matches!(&events[0], UiEvent::Accelerator(id, _) if id.as_str() == "test.toggle"));
    }

    #[test]
    fn accelerator_widget_scope_skipped() {
        // Backend doesn't know which widget has focus; widget-scoped
        // accelerators must NOT match here. The app keeps inline
        // matching for those.
        let mut backend = TuiBackend::new();
        backend.register_accelerator(&Accelerator {
            id: AcceleratorId::new("widget.local"),
            binding: KeyBinding::Literal("<C-p>".into()),
            scope: AcceleratorScope::Widget(WidgetId::new("test:input")),
            label: None,
        });

        let mut events = vec![ctrl_p_keypress()];
        backend.apply_accelerators(&mut events);

        assert!(matches!(events[0], UiEvent::KeyPressed { .. }));
    }

    // ── Text selection / highlight round-trip tests ──────────────────────────

    /// Build a minimal ratatui buffer filled with known text, set up a
    /// text selection, and verify that:
    ///   1. `apply_selection_highlight` inverts the selected cells.
    ///   2. `extract_selection_text` returns the trimmed, newline-joined text.
    #[test]
    fn selection_highlight_and_extract_round_trip() {
        use ratatui::buffer::Buffer;
        use ratatui::layout::Rect as RRect;
        use ratatui::style::Color as RC;

        // 10 wide × 3 tall buffer filled with known characters.
        let area = RRect::new(0, 0, 10, 3);
        let mut buf = Buffer::empty(area);

        // Row 0: "hello     " (trailing spaces)
        // Row 1: "world     "
        // Row 2: "!         "
        for (col, ch) in "hello     ".chars().enumerate() {
            buf[(col as u16, 0)]
                .set_char(ch)
                .set_fg(RC::White)
                .set_bg(RC::Black);
        }
        for (col, ch) in "world     ".chars().enumerate() {
            buf[(col as u16, 1)]
                .set_char(ch)
                .set_fg(RC::White)
                .set_bg(RC::Black);
        }
        for (col, ch) in "!         ".chars().enumerate() {
            buf[(col as u16, 2)]
                .set_char(ch)
                .set_fg(RC::White)
                .set_bg(RC::Black);
        }

        // Register text region and set selection: anchor at (0,0), focus at (0,2).
        // That covers rows 0–2, starting from col 0.
        let mut backend = TuiBackend::new();
        backend.register_text_region(crate::dispatch::TextRegion {
            id: WidgetId::new("log:body"),
            bounds: crate::event::Rect::new(0.0, 0.0, 10.0, 3.0),
            lines: vec![],
        });
        backend.set_active_text_selection(
            WidgetId::new("log:body"),
            Point::new(0.0, 0.0),
            Point::new(0.0, 2.0),
        );

        // 1. Extract text before highlight (cells still normal).
        let text = backend.extract_selection_text(&buf);
        // anchor(0,0) → focus(0,2):
        //   row 0: col 0..10 → "hello     " trimmed → "hello"
        //   row 1: col 0..10 → "world     " trimmed → "world"
        //   row 2: col 0..1  → "!" trimmed → "!"
        assert_eq!(text, "hello\nworld\n!");

        // 2. Apply highlight — selected cells should swap fg/bg.
        backend.apply_selection_highlight(&mut buf);
        // Spot-check: (0,0) should be inverted (fg=Black, bg=White).
        assert_eq!(buf[(0u16, 0u16)].fg, RC::Black);
        assert_eq!(buf[(0u16, 0u16)].bg, RC::White);
        // A cell outside the last row's range (col 1 of row 2 is outside
        // 0..1, so col=1 should be un-inverted).
        assert_eq!(buf[(1u16, 2u16)].fg, RC::White);
        assert_eq!(buf[(1u16, 2u16)].bg, RC::Black);
    }

    #[test]
    fn selection_clears_on_clear_text_selection() {
        let mut backend = TuiBackend::new();
        backend.set_active_text_selection(
            WidgetId::new("r"),
            Point::new(0.0, 0.0),
            Point::new(5.0, 0.0),
        );
        assert!(backend.active_text_selection().is_some());
        backend.clear_text_selection();
        assert!(backend.active_text_selection().is_none());
        // Drag state should also be cleared if it was a TextSelection.
        backend
            .drag_state
            .borrow_mut()
            .begin(DragTarget::TextSelection {
                region: WidgetId::new("r"),
                anchor: Point::new(0.0, 0.0),
            });
        backend.clear_text_selection();
        assert!(!backend.drag_state.borrow().is_active());
    }

    #[test]
    fn text_regions_cleared_on_begin_frame() {
        let mut backend = TuiBackend::new();
        backend.register_text_region(crate::dispatch::TextRegion {
            id: WidgetId::new("r"),
            bounds: crate::event::Rect::new(0.0, 0.0, 40.0, 20.0),
            lines: vec![],
        });
        assert_eq!(backend.text_regions().len(), 1);
        backend.begin_frame(Viewport::default());
        assert_eq!(
            backend.text_regions().len(),
            0,
            "text_regions must be cleared on begin_frame"
        );
    }

    /// Verify that `select_all_text_region` sets the full viewport bounds as
    /// the active selection. This directly tests the core acceptance criterion:
    /// "Ctrl-A sets the expected full range; extracted text == full region
    /// content" (the extraction half is covered by the round-trip test above).
    #[test]
    fn select_all_text_region_sets_full_bounds() {
        let mut backend = TuiBackend::new();
        backend.register_text_region(crate::dispatch::TextRegion {
            id: WidgetId::new("body"),
            bounds: crate::event::Rect::new(0.0, 0.0, 10.0, 5.0),
            lines: vec![],
        });
        assert!(
            backend.select_all_text_region(),
            "should return true when exactly one region is registered"
        );
        let sel = backend
            .active_text_selection()
            .expect("selection should be active after select_all_text_region");
        assert_eq!(
            sel.anchor,
            Point::new(0.0, 0.0),
            "anchor should be at top-left of region bounds"
        );
        assert_eq!(
            sel.focus,
            Point::new(10.0, 5.0),
            "focus should be at bottom-right of region bounds"
        );
    }

    /// Verify that `select_all_text_region` returns `false` when no regions
    /// are registered, and the fallthrough path is taken.
    #[test]
    fn select_all_text_region_returns_false_when_no_regions() {
        let mut backend = TuiBackend::new();
        assert!(
            !backend.select_all_text_region(),
            "should return false with no registered regions"
        );
        assert!(
            backend.active_text_selection().is_none(),
            "no selection should be set when select_all returns false"
        );
    }

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

    /// `begin_frame` clears the focused activity bar so stale state from
    /// the previous render doesn't persist.
    #[test]
    fn focused_activity_bar_cleared_on_begin_frame() {
        let mut backend = TuiBackend::new();
        backend.focused_activity_bar = Some(WidgetId::new("demo:bar"));
        backend.begin_frame(Viewport::default());
        assert!(
            backend.focused_activity_bar.is_none(),
            "focused_activity_bar must be cleared by begin_frame"
        );
    }

    /// When an `ActivityBar` with `is_keyboard_focused = true` is drawn,
    /// `apply_dispatch` converts the next `KeyPressed` into
    /// `UiEvent::ActivityBar(id, ActivityBarEvent::KeyPressed { … })`.
    #[test]
    fn activity_bar_focused_redirects_key_presses() {
        use crate::ActivityBarEvent;

        let mut backend = TuiBackend::new();
        // Simulate the render pass recording a focused bar.
        backend.focused_activity_bar = Some(WidgetId::new("demo:bar"));

        let raw = vec![UiEvent::KeyPressed {
            key: Key::Char('j'),
            modifiers: Modifiers::default(),
            repeat: false,
        }];
        let out = backend.apply_dispatch(raw);
        assert_eq!(
            out.len(),
            1,
            "one input event must produce one output event"
        );
        match &out[0] {
            UiEvent::ActivityBar(id, ActivityBarEvent::KeyPressed { key, modifiers }) => {
                assert_eq!(id.as_str(), "demo:bar");
                assert_eq!(key, "j");
                assert_eq!(*modifiers, Modifiers::default());
            }
            other => panic!("expected UiEvent::ActivityBar KeyPressed, got {other:?}"),
        }
    }

    /// Without a focused activity bar, raw `KeyPressed` events pass through
    /// unchanged (no accidental interception).
    #[test]
    fn activity_bar_unfocused_passes_key_presses_through() {
        let mut backend = TuiBackend::new();
        // No focused bar.
        assert!(backend.focused_activity_bar.is_none());

        let raw = vec![UiEvent::KeyPressed {
            key: Key::Char('j'),
            modifiers: Modifiers::default(),
            repeat: false,
        }];
        let out = backend.apply_dispatch(raw);
        assert_eq!(out.len(), 1);
        assert!(
            matches!(
                &out[0],
                UiEvent::KeyPressed {
                    key: Key::Char('j'),
                    ..
                }
            ),
            "key must pass through unchanged when no bar is focused"
        );
    }

    /// `key_to_activity_bar_string` maps printable chars and common
    /// named keys to their expected string forms.
    #[test]
    fn key_to_activity_bar_string_maps_correctly() {
        use crate::primitives::activity_bar::key_to_activity_bar_string;

        assert_eq!(key_to_activity_bar_string(&Key::Char('j')), "j");
        assert_eq!(key_to_activity_bar_string(&Key::Char('K')), "K");
        assert_eq!(
            key_to_activity_bar_string(&Key::Named(NamedKey::Escape)),
            "Escape"
        );
        assert_eq!(
            key_to_activity_bar_string(&Key::Named(NamedKey::Enter)),
            "Enter"
        );
        assert_eq!(key_to_activity_bar_string(&Key::Named(NamedKey::Up)), "Up");
        assert_eq!(
            key_to_activity_bar_string(&Key::Named(NamedKey::Down)),
            "Down"
        );
    }

    // ── coalesce_mouse_moved tests ────────────────────────────────────────────

    /// A burst of N consecutive `MouseMoved` events collapses to a single
    /// event at the final position.
    #[test]
    fn coalesce_collapses_consecutive_mouse_moved() {
        use crate::ButtonMask;
        let raw = vec![
            UiEvent::MouseMoved {
                position: Point::new(1.0, 1.0),
                buttons: ButtonMask::default(),
            },
            UiEvent::MouseMoved {
                position: Point::new(2.0, 1.0),
                buttons: ButtonMask::default(),
            },
            UiEvent::MouseMoved {
                position: Point::new(3.0, 1.0),
                buttons: ButtonMask::default(),
            },
        ];
        let out = coalesce_mouse_moved(raw);
        assert_eq!(out.len(), 1, "three consecutive moves must collapse to one");
        assert!(
            matches!(&out[0], UiEvent::MouseMoved { position, .. } if position.x == 3.0),
            "surviving event must carry the final position (x=3), got {:?}",
            out
        );
    }

    /// A `MouseDown … MouseMoved×N … MouseUp` burst collapses the moves
    /// to the final position while preserving relative order with the
    /// flanking down/up events.
    #[test]
    fn coalesce_preserves_ordering_around_down_and_up() {
        use crate::{ButtonMask, Modifiers, MouseButton};
        let raw = vec![
            UiEvent::MouseDown {
                widget: None,
                button: MouseButton::Left,
                position: Point::new(0.0, 0.0),
                modifiers: Modifiers::default(),
            },
            UiEvent::MouseMoved {
                position: Point::new(1.0, 0.0),
                buttons: ButtonMask {
                    left: true,
                    ..ButtonMask::default()
                },
            },
            UiEvent::MouseMoved {
                position: Point::new(2.0, 0.0),
                buttons: ButtonMask {
                    left: true,
                    ..ButtonMask::default()
                },
            },
            UiEvent::MouseMoved {
                position: Point::new(3.0, 0.0),
                buttons: ButtonMask {
                    left: true,
                    ..ButtonMask::default()
                },
            },
            UiEvent::MouseUp {
                widget: None,
                button: MouseButton::Left,
                position: Point::new(3.0, 0.0),
            },
        ];
        let out = coalesce_mouse_moved(raw);
        assert_eq!(out.len(), 3, "expected [Down, Moved, Up], got {out:?}");
        assert!(
            matches!(&out[0], UiEvent::MouseDown { .. }),
            "first event must be MouseDown"
        );
        assert!(
            matches!(&out[1], UiEvent::MouseMoved { position, .. } if position.x == 3.0),
            "middle event must be the final MouseMoved (x=3), got {:?}",
            out[1]
        );
        assert!(
            matches!(&out[2], UiEvent::MouseUp { .. }),
            "last event must be MouseUp"
        );
    }

    /// `MouseMoved` events separated by a non-move event are NOT merged —
    /// each consecutive run collapses independently.
    #[test]
    fn coalesce_does_not_merge_moves_separated_by_other_events() {
        use crate::{ButtonMask, Modifiers};
        let raw = vec![
            UiEvent::MouseMoved {
                position: Point::new(1.0, 0.0),
                buttons: ButtonMask::default(),
            },
            UiEvent::MouseMoved {
                position: Point::new(2.0, 0.0),
                buttons: ButtonMask::default(),
            },
            UiEvent::KeyPressed {
                key: Key::Char('x'),
                modifiers: Modifiers::default(),
                repeat: false,
            },
            UiEvent::MouseMoved {
                position: Point::new(5.0, 0.0),
                buttons: ButtonMask::default(),
            },
            UiEvent::MouseMoved {
                position: Point::new(6.0, 0.0),
                buttons: ButtonMask::default(),
            },
        ];
        let out = coalesce_mouse_moved(raw);
        // Expected: [Moved(2.0), Key('x'), Moved(6.0)]
        assert_eq!(out.len(), 3, "expected 3 events, got {out:?}");
        assert!(
            matches!(&out[0], UiEvent::MouseMoved { position, .. } if position.x == 2.0),
            "first run must collapse to x=2, got {:?}",
            out[0]
        );
        assert!(
            matches!(&out[1], UiEvent::KeyPressed { .. }),
            "middle event must be KeyPressed"
        );
        assert!(
            matches!(&out[2], UiEvent::MouseMoved { position, .. } if position.x == 6.0),
            "second run must collapse to x=6, got {:?}",
            out[2]
        );
    }

    // ── recover_leaked_sgr_mouse_fragments tests ────────────────────────────

    /// The identity cell size — every pre-#1048 `recover_leaked_sgr_mouse_fragments`
    /// test below passes this so its cell-mode assertions stay
    /// byte-identical to before that parameter existed.
    const UNSCALED_TEST_CELL: TerminalCellSize = TerminalCellSize {
        width: 1.0,
        height: 1.0,
    };

    /// Builds a run of `KeyPressed(Char(_))` events, one per `char` in `s`
    /// — the shape crossterm's reader produces when it decodes a leaked
    /// escape-sequence tail byte-by-byte as ordinary text.
    fn char_run(s: &str) -> Vec<UiEvent> {
        s.chars()
            .map(|c| UiEvent::KeyPressed {
                key: Key::Char(c),
                modifiers: Modifiers::default(),
                repeat: false,
            })
            .collect()
    }

    /// A leaked pure-motion report (`Cb=35`, the exact shape #293 was
    /// filed against) reassembles into the `MouseMoved` it should have
    /// decoded as, with no leftover `KeyPressed` events.
    #[test]
    fn recovers_leaked_pure_motion_report() {
        use crate::ButtonMask;
        let raw = char_run("[<35;10;5M");
        let out = recover_leaked_sgr_mouse_fragments(raw, UNSCALED_TEST_CELL);
        assert_eq!(
            out.len(),
            1,
            "expected exactly one recovered event: {out:?}"
        );
        assert!(
            matches!(
                &out[0],
                UiEvent::MouseMoved { position, buttons }
                    if position.x == 9.0 && position.y == 4.0 && *buttons == ButtonMask::default()
            ),
            "expected MouseMoved(9,4) with no buttons held, got {:?}",
            out[0]
        );
    }

    /// A non-identity `cell_size` threads all the way
    /// through `recover_leaked_sgr_mouse_fragments` →
    /// `try_reassemble_sgr_mouse` → `decode_sgr_mouse_report` →
    /// `crossterm_mouse_to_uievent_scaled`, recovering the same fractional
    /// coordinate a cleanly decoded SGR-Pixels report would have produced —
    /// not just the cell-mode identity path every other test in this
    /// section exercises.
    #[test]
    fn recovers_leaked_pure_motion_report_scaled_to_pixel_cell_size() {
        let raw = char_run("[<35;10;5M");
        let cell = TerminalCellSize::new(10.0, 20.0);
        let out = recover_leaked_sgr_mouse_fragments(raw, cell);
        assert!(
            matches!(
                &out[..],
                [UiEvent::MouseMoved { position, .. }]
                    if (position.x - 0.9).abs() < f32::EPSILON
                        && (position.y - 0.2).abs() < f32::EPSILON
            ),
            "expected MouseMoved(0.9, 0.2) after dividing pixel report (9,4) by cell (10,20), \
             got {out:?}"
        );
    }

    /// The leading `Escape` this race dispatches standalone is preserved
    /// verbatim, immediately followed by the recovered mouse event — the
    /// exact batch shape `wait_events`/`poll_events` hands to
    /// `coalesce_mouse_moved` once the leak is fixed.
    #[test]
    fn preserves_a_genuine_leading_escape_before_the_recovered_report() {
        let mut raw = vec![UiEvent::KeyPressed {
            key: Key::Named(NamedKey::Escape),
            modifiers: Modifiers::default(),
            repeat: false,
        }];
        raw.extend(char_run("[<35;10;5M"));
        let out = recover_leaked_sgr_mouse_fragments(raw, UNSCALED_TEST_CELL);
        assert_eq!(out.len(), 2, "expected [Escape, MouseMoved]: {out:?}");
        assert!(matches!(
            &out[0],
            UiEvent::KeyPressed {
                key: Key::Named(NamedKey::Escape),
                ..
            }
        ));
        assert!(matches!(&out[1], UiEvent::MouseMoved { .. }));
    }

    /// A left-button press (`Cb=0`) and its SGR release (`Cb=0`, lowercase
    /// `m`) both reassemble correctly — release flips `Down` to `Up`,
    /// matching crossterm's own `parse_csi_sgr_mouse`.
    #[test]
    fn recovers_leaked_click_down_and_up() {
        use crate::MouseButton;
        let down = recover_leaked_sgr_mouse_fragments(char_run("[<0;3;4M"), UNSCALED_TEST_CELL);
        assert!(
            matches!(
                &down[..],
                [UiEvent::MouseDown { button: MouseButton::Left, position, .. }]
                    if position.x == 2.0 && position.y == 3.0
            ),
            "expected a single MouseDown(2,3): {down:?}"
        );

        let up = recover_leaked_sgr_mouse_fragments(char_run("[<0;3;4m"), UNSCALED_TEST_CELL);
        assert!(
            matches!(
                &up[..],
                [UiEvent::MouseUp { button: MouseButton::Left, position, .. }]
                    if position.x == 2.0 && position.y == 3.0
            ),
            "expected a single MouseUp(2,3): {up:?}"
        );
    }

    /// A drag report (`Cb=32`, left button held while moving) reassembles
    /// with the held button carried on `buttons`, mirroring
    /// `crossterm_mouse_to_uievent`'s `Drag` handling.
    #[test]
    fn recovers_leaked_drag_report() {
        let out = recover_leaked_sgr_mouse_fragments(char_run("[<32;7;8M"), UNSCALED_TEST_CELL);
        assert!(
            matches!(
                &out[..],
                [UiEvent::MouseMoved { position, buttons }]
                    if position.x == 6.0 && position.y == 7.0 && buttons.left
            ),
            "expected a single held-left MouseMoved(6,7): {out:?}"
        );
    }

    /// A real user typing a literal `[<...` that never completes into a
    /// well-formed SGR triple (no `M`/`m` terminator, or a `;`-delimited
    /// group that isn't three integers) must not be touched — the whole
    /// run survives as ordinary `KeyPressed` events.
    #[test]
    fn leaves_non_matching_bracket_runs_untouched() {
        let raw = char_run("[<12;34");
        let out = recover_leaked_sgr_mouse_fragments(raw.clone(), UNSCALED_TEST_CELL);
        assert_eq!(
            out, raw,
            "an incomplete/unterminated run must pass through verbatim"
        );

        let raw = char_run("[hello");
        let out = recover_leaked_sgr_mouse_fragments(raw.clone(), UNSCALED_TEST_CELL);
        assert_eq!(
            out, raw,
            "'[' not followed by '<' must pass through verbatim"
        );
    }

    /// Events unrelated to the leak (plain keystrokes, real mouse events)
    /// pass through untouched, and multiple independent leaks in one
    /// batch each recover independently.
    #[test]
    fn passes_through_unrelated_events_and_recovers_multiple_leaks_in_one_batch() {
        let mut raw = vec![UiEvent::KeyPressed {
            key: Key::Char('h'),
            modifiers: Modifiers::default(),
            repeat: false,
        }];
        raw.extend(char_run("[<35;10;5M"));
        raw.push(UiEvent::KeyPressed {
            key: Key::Char('i'),
            modifiers: Modifiers::default(),
            repeat: false,
        });
        raw.extend(char_run("[<35;11;6M"));

        let out = recover_leaked_sgr_mouse_fragments(raw, UNSCALED_TEST_CELL);
        assert_eq!(
            out.len(),
            4,
            "expected [Char(h), Moved, Char(i), Moved]: {out:?}"
        );
        assert!(matches!(
            &out[0],
            UiEvent::KeyPressed {
                key: Key::Char('h'),
                ..
            }
        ));
        assert!(matches!(&out[1], UiEvent::MouseMoved { position, .. } if position.x == 9.0));
        assert!(matches!(
            &out[2],
            UiEvent::KeyPressed {
                key: Key::Char('i'),
                ..
            }
        ));
        assert!(matches!(&out[3], UiEvent::MouseMoved { position, .. } if position.x == 10.0));
    }

    // ── Issue #552 sibling audit: tab-bar hit geometry ──────────────
    //
    // `TabBarHits` is documented as **target-surface (absolute)**
    // coordinates — the opposite convention from `ActivityBarRowHit`,
    // which is bar-relative. `draw_tab_bar` honoured that on both TUI and
    // GTK by shifting the primitive's bar-relative output by the bar's
    // origin. `Backend::tab_bar_layout` honoured it on neither: it
    // returned `tab_bar_hits_from_layout` verbatim, so the no-paint path
    // was off by `rect.x` — nonzero for any tab bar sitting right of a
    // sidebar, which is every AppShell layout.
    //
    // Same class of defect as #552 itself (a hit-region seam silently
    // disagreeing about coordinate space), one primitive over, found by
    // the audit the issue asked for. Both backends now route through the
    // shared `backend::shift_tab_bar_hits`.

    fn audit_bar() -> TabBar {
        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,
                },
                crate::primitives::tab_bar::TabItem {
                    label: "lib.rs".into(),
                    is_active: false,
                    is_dirty: false,
                    is_preview: false,
                    is_closable: true,
                },
            ],
            right_segments: vec![],
            active_accent: None,
            scroll_offset: 0,
            show_tab_close: true,
            compact: false,
        }
    }

    /// The glyph-override `Backend` trait methods are reachable through
    /// `TuiBackend` and actually honour an app-supplied override — not
    /// just present with an ignored default body. Drives all three
    /// through a real frame scope, the same production path `AppLogic`
    /// implementations use.
    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` — issue #823
    fn backend_trait_glyph_overrides_are_reachable_and_honoured() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut backend = TuiBackend::new();
        backend.begin_frame(Viewport::new(80.0, 24.0, 1.0));
        let bar = audit_bar();
        let tab_glyphs = crate::primitives::tab_bar::TabBarGlyphs::new().with_close_glyph("x");

        let menu = crate::ContextMenu {
            id: WidgetId::new("menu"),
            items: vec![crate::primitives::context_menu::ContextMenuItem {
                id: Some(WidgetId::new("wrap")),
                label: StyledText {
                    spans: vec![StyledSpan::plain("Word Wrap")],
                },
                checked: Some(true),
                ..Default::default()
            }],
            selected_idx: 0,
            bg: None,
            placement: crate::primitives::context_menu::ContextMenuPlacement::default(),
        };
        let menu_layout = menu.layout(
            2.0,
            1.0,
            crate::event::Rect::new(0.0, 0.0, 30.0, 10.0),
            20.0,
            |_| crate::primitives::context_menu::ContextMenuItemMeasure::new(1.0),
        );
        let menu_glyphs =
            crate::primitives::context_menu::ContextMenuGlyphs::new().with_checked_glyph("+");

        let table = crate::DataTable {
            id: WidgetId::new("table"),
            columns: vec![crate::primitives::data_table::Column {
                title: "Name".into(),
                width: crate::primitives::data_table::ColumnWidth::Flex(1.0),
                align: crate::primitives::data_table::ColumnAlign::Left,
            }],
            rows: vec![],
            selected_idx: None,
            scroll_offset: 0,
            sort: Some((0, crate::primitives::data_table::SortDirection::Ascending)),
            has_focus: false,
            show_scrollbar: false,
            min_total_width: None,
            h_scroll: 0.0,
            column_overrides: Vec::new(),
            footer: None,
        };
        let table_glyphs =
            crate::primitives::data_table::DataTableGlyphs::new().with_sort_ascending_glyph("^");

        // Each primitive paints into its own terminal — a shared one would
        // let whichever paints last overwrite the others' rows, which
        // would make this a test of paint order, not of reachability.
        let mut tab_terminal = Terminal::new(TestBackend::new(80, 24)).expect("test terminal");
        tab_terminal
            .draw(|frame| {
                backend.enter_frame_scope(frame, |b| {
                    b.draw_tab_bar_with_chrome_and_glyphs(
                        QRect::new(0.0, 0.0, 40.0, 1.0),
                        &bar,
                        None,
                        &TabChrome::default(),
                        Some(&tab_glyphs),
                    );
                });
            })
            .expect("draw");
        let tab_screen = screen_text(tab_terminal.backend().buffer());
        assert!(
            tab_screen.contains('x'),
            "overridden tab close glyph should reach the screen, got: {tab_screen}"
        );
        assert!(
            !tab_screen.contains(crate::tui::tab_bar::TAB_CLOSE_CHAR),
            "default tab close glyph should not leak through the override, got: {tab_screen}"
        );

        let mut menu_terminal = Terminal::new(TestBackend::new(80, 24)).expect("test terminal");
        menu_terminal
            .draw(|frame| {
                backend.enter_frame_scope(frame, |b| {
                    b.draw_context_menu_with_glyphs(&menu, &menu_layout, Some(&menu_glyphs));
                });
            })
            .expect("draw");
        let menu_screen = screen_text(menu_terminal.backend().buffer());
        assert!(
            menu_screen.contains('+'),
            "overridden context-menu checked glyph should reach the screen, \
             got: {menu_screen}"
        );
        assert!(
            !menu_screen.contains('✓'),
            "default context-menu checked glyph should not leak through the \
             override, got: {menu_screen}"
        );

        let mut table_terminal = Terminal::new(TestBackend::new(80, 24)).expect("test terminal");
        table_terminal
            .draw(|frame| {
                backend.enter_frame_scope(frame, |b| {
                    b.draw_data_table_with_glyphs(
                        QRect::new(0.0, 0.0, 40.0, 5.0),
                        &table,
                        None,
                        Some(&table_glyphs),
                    );
                });
            })
            .expect("draw");
        let table_screen = screen_text(table_terminal.backend().buffer());
        assert!(
            table_screen.contains('^'),
            "overridden data-table sort glyph should reach the screen, got: \
             {table_screen}"
        );
        assert!(
            !table_screen.contains('▲'),
            "default data-table sort-ascending glyph should not leak through \
             the override, got: {table_screen}"
        );
    }

    fn screen_text(buf: &ratatui::buffer::Buffer) -> String {
        buf.content.iter().fold(String::new(), |mut s, cell| {
            s.push_str(cell.symbol());
            s
        })
    }

    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` — issue #823
    fn tab_bar_layout_returns_absolute_x_not_bar_relative() {
        let backend = TuiBackend::new();
        let bar = audit_bar();

        let at_origin = backend.tab_bar_layout(QRect::new(0.0, 0.0, 40.0, 1.0), &bar);
        let shifted = backend.tab_bar_layout(QRect::new(12.0, 0.0, 40.0, 1.0), &bar);

        assert!(
            !at_origin.slot_positions.is_empty(),
            "sanity: some tabs should be laid out"
        );
        for (i, (base, moved)) in at_origin
            .slot_positions
            .iter()
            .zip(shifted.slot_positions.iter())
            .enumerate()
        {
            if *base == (0.0, 0.0) {
                // Scrolled-out sentinel — must stay recognisable, not
                // become (12.0, 12.0).
                assert_eq!(
                    *moved,
                    (0.0, 0.0),
                    "tab {i}: the scrolled-out sentinel must not be shifted"
                );
                continue;
            }
            assert_eq!(
                (moved.0, moved.1),
                (base.0 + 12.0, base.1 + 12.0),
                "tab {i}: `tab_bar_layout` is documented to return \
                 target-surface coordinates, so moving the bar right by 12 \
                 must move its hit spans right by 12 (issue #552 audit)"
            );
        }
    }

    /// The no-paint path must agree with the painting path, since callers
    /// use them interchangeably to route the same clicks. Runs
    /// `draw_tab_bar` through a real frame scope so it goes down the
    /// production rasteriser, not a reimplementation of it.
    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` — issue #823
    fn tab_bar_layout_agrees_with_draw_tab_bar_on_coordinate_space() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut backend = TuiBackend::new();
        backend.begin_frame(Viewport::new(80.0, 24.0, 1.0));
        let bar = audit_bar();
        // Nonzero x: the whole point. At x = 0 the two paths agreed even
        // before the fix, which is exactly how the defect stayed hidden.
        let rect = QRect::new(12.0, 0.0, 40.0, 1.0);

        let from_layout = backend.tab_bar_layout(rect, &bar);

        let mut terminal = Terminal::new(TestBackend::new(80, 24)).expect("test terminal");
        let mut painted = None;
        terminal
            .draw(|frame| {
                painted =
                    Some(backend.enter_frame_scope(frame, |b| b.draw_tab_bar(rect, &bar, None)));
            })
            .expect("draw");
        let from_paint = painted.expect("draw closure ran");

        assert!(
            from_paint.slot_positions.iter().any(|s| *s != (0.0, 0.0)),
            "sanity: the rasteriser should have placed at least one tab"
        );
        assert_eq!(
            from_layout.slot_positions, from_paint.slot_positions,
            "`tab_bar_layout` and `draw_tab_bar` must report tab slots in \
             the same coordinate space (issue #552 audit)"
        );
        assert_eq!(
            from_layout.close_bounds, from_paint.close_bounds,
            "close-button spans must match between the paint and no-paint \
             paths too"
        );
    }

    /// Issue #919: the new `TabBarLayout`-returning accessors must report
    /// the exact geometry their deprecated `TabBarHits`-returning siblings
    /// do — same pattern as `gtk::testing::tab_bar_layout_twin_matches_painted_geometry_headless`.
    /// `TabBarLayout`'s own bounds are **bar-relative** (see its doc), so
    /// this adds `rect.x` back before comparing against the absolute
    /// `TabBarHits` contract.
    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` — issue #823
    fn resolve_tab_bar_layout_matches_tab_bar_layout_hits_geometry() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut backend = TuiBackend::new();
        backend.begin_frame(Viewport::new(80.0, 24.0, 1.0));
        let bar = audit_bar();
        let rect = QRect::new(12.0, 0.0, 40.0, 1.0);

        let hits = backend.tab_bar_layout(rect, &bar);
        let resolved = backend.resolve_tab_bar_layout(rect, &bar);

        let mut terminal = Terminal::new(TestBackend::new(80, 24)).expect("test terminal");
        let mut painted_hits = None;
        let mut painted_layout = None;
        terminal
            .draw(|frame| {
                backend.enter_frame_scope(frame, |b| {
                    painted_hits = Some(b.draw_tab_bar(rect, &bar, None));
                    painted_layout = Some(b.draw_tab_bar_layout(rect, &bar, None));
                });
            })
            .expect("draw");
        let painted_hits = painted_hits.expect("draw closure ran");
        let painted_layout = painted_layout.expect("draw closure ran");

        assert!(
            !resolved.visible_tabs.is_empty(),
            "sanity: some tabs should be laid out"
        );

        for vt in &resolved.visible_tabs {
            let expected = (
                (rect.x + vt.bounds.x) as f64,
                (rect.x + vt.bounds.x + vt.bounds.width) as f64,
            );
            assert_eq!(
                hits.slot_positions[vt.tab_idx], expected,
                "tab {}: `resolve_tab_bar_layout` (shifted by rect.x) must \
                 match `tab_bar_layout`'s absolute slot",
                vt.tab_idx
            );
            let expected_close = vt
                .close_bounds
                .map(|cb| ((rect.x + cb.x) as f64, (rect.x + cb.x + cb.width) as f64));
            assert_eq!(
                hits.close_bounds[vt.tab_idx], expected_close,
                "tab {}: close-button span must match too",
                vt.tab_idx
            );
        }

        // The paint path's `TabBarLayout` twin must report the same
        // bar-relative geometry the paint path's `TabBarHits` reports
        // once shifted back by `rect.x` — i.e. painting through either
        // entry point produces one, indivisible geometry.
        for vt in &painted_layout.visible_tabs {
            let expected = (
                (rect.x + vt.bounds.x) as f64,
                (rect.x + vt.bounds.x + vt.bounds.width) as f64,
            );
            assert_eq!(
                painted_hits.slot_positions[vt.tab_idx], expected,
                "tab {}: `draw_tab_bar_layout` (shifted by rect.x) must \
                 match `draw_tab_bar`'s absolute slot",
                vt.tab_idx
            );
        }

        assert_eq!(
            resolved.visible_tabs, painted_layout.visible_tabs,
            "the no-paint and paint `TabBarLayout` accessors must agree \
             on geometry for the same bar and rect"
        );
    }

    /// `Backend::snap_height` must agree with `q_rect_to_ratatui`'s height
    /// rounding for every height a rect can carry, since it exists to let
    /// consumers predict that rounding without reimplementing it.
    /// If the two ever drift, a consumer's pre-snapped
    /// layout height stops matching what the rasteriser actually paints —
    /// the exact one-row misalignment that bit coord-tui in #464 and #995.
    #[test]
    fn snap_height_matches_q_rect_to_ratatui_height_rounding() {
        let backend = TuiBackend::new();
        for h in [
            0.0_f32, 0.2, 0.49, 0.5, 0.51, 1.0, 1.4, 1.6, 2.5, 13.999, -1.0, -0.4,
        ] {
            let snapped = backend.snap_height(h);
            let via_rect = q_rect_to_ratatui(QRect::new(0.0, 0.0, 0.0, h)).height;
            assert_eq!(
                snapped as u16, via_rect,
                "snap_height({h}) = {snapped}, but q_rect_to_ratatui reports \
                 height {via_rect} for the same input"
            );
        }
    }

    /// TUI has no windowing scrollbar overlay to dodge, so it
    /// relies on `Backend::scrollbar_reserve`'s trait default (0.0)
    /// rather than overriding it — unlike GTK (see
    /// `GtkBackend::scrollbar_reserve`, 8.0).
    #[test]
    fn tui_backend_scrollbar_reserve_uses_the_zero_default() {
        let backend = TuiBackend::new();
        assert_eq!(Backend::scrollbar_reserve(&backend), 0.0);
    }

    /// Issue #1045 item 2: TUI is a fixed-cell backend with no font size
    /// to scale, so it doesn't override
    /// `Backend::draw_status_bar_interactive_scaled` — this pins that the
    /// trait's own default (ignore `font_scale`, forward unscaled) is
    /// what actually runs, by checking a scaled call paints byte-for-byte
    /// the same layout an unscaled call does.
    #[test]
    fn tui_backend_draw_status_bar_interactive_scaled_uses_the_unscaled_default() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let bar = crate::primitives::status_bar::StatusBar {
            id: WidgetId::new("status"),
            left_segments: vec![crate::primitives::status_bar::StatusBarSegment {
                text: "READY".into(),
                fg: crate::Color::rgb(255, 255, 255),
                bg: crate::Color::rgb(0, 0, 0),
                bold: false,
                action_id: None,
            }],
            right_segments: vec![],
        };
        let rect = QRect::new(0.0, 0.0, 40.0, 1.0);
        let interaction = crate::InteractionState::new();

        let mut unscaled_backend = TuiBackend::new();
        let mut scaled_backend = TuiBackend::new();
        let mut terminal = Terminal::new(TestBackend::new(80, 24)).expect("test terminal");
        let unscaled_result = std::cell::RefCell::new(None);
        let scaled_result = std::cell::RefCell::new(None);
        terminal
            .draw(|frame| {
                let unscaled = unscaled_backend.enter_frame_scope(frame, |b| {
                    b.draw_status_bar_interactive(rect, &bar, &interaction)
                });
                *unscaled_result.borrow_mut() = Some(unscaled);
                let scaled = scaled_backend.enter_frame_scope(frame, |b| {
                    b.draw_status_bar_interactive_scaled(rect, &bar, &interaction, 0.5)
                });
                *scaled_result.borrow_mut() = Some(scaled);
            })
            .expect("draw");

        assert_eq!(
            unscaled_result.into_inner().unwrap(),
            scaled_result.into_inner().unwrap(),
            "TUI has no font to scale; the default impl must ignore font_scale entirely"
        );
    }

    /// A pixel backend must not quantize — `snap_height` returns the input
    /// unchanged via the trait's default impl. `MockBackend` doesn't
    /// override `snap_height`, so it stands in for "any backend that only
    /// paints pixels/DIPs" here.
    #[test]
    fn snap_height_default_impl_is_identity() {
        let backend = MockBackend::new();
        for h in [0.0_f32, 0.4, 1.6, 13.999, -1.0] {
            assert_eq!(
                Backend::snap_height(&backend, h),
                h,
                "default snap_height impl must be identity for pixel backends"
            );
        }
    }

    /// TUI has no native alert facility — `backend_caps`
    /// must not claim `native_dialogs`, and `services().show_message_dialog`
    /// must actually return `None` regardless of what's asked for. Both
    /// halves of the same honesty contract `file_dialogs` already has.
    #[test]
    fn tui_backend_declares_no_native_dialogs() {
        let backend = TuiBackend::new();
        assert!(
            !backend.backend_caps().native_dialogs,
            "TUI has no native alert facility; native_dialogs must stay false"
        );
        let opts = MessageDialogOptions {
            title: "Unsaved Changes".to_string(),
            body: "Do you want to save?".to_string(),
            buttons: Vec::new(),
            severity: None,
        };
        assert!(backend.services().show_message_dialog(opts).is_none());
    }

    /// Issue #506: `list_layout` is documented **LOCAL** — a caller
    /// subtracts `rect.x`/`rect.y` itself before hit-testing — so a
    /// non-zero origin must not change the returned geometry at all
    /// (same regression shape as `gtk_backend_data_table_layout_ignores_rect_origin`).
    #[test]
    fn list_layout_ignores_rect_origin() {
        let backend = TuiBackend::new();
        let list = sample_list();

        let at_origin = backend.list_layout(QRect::new(0.0, 0.0, 20.0, 5.0), &list);
        let shifted = backend.list_layout(QRect::new(7.0, 3.0, 20.0, 5.0), &list);

        assert_eq!(
            at_origin, shifted,
            "list_layout must ignore rect.x/rect.y (LOCAL frame, issue #505)"
        );
        assert!(
            !at_origin.visible_items.is_empty(),
            "sanity: the sample list has an item to lay out"
        );
    }

    /// `list_layout` must be the exact resolver `draw_list` uses
    /// internally, not a parallel reimplementation that can drift from
    /// it (`PRIMITIVE_RULES.md` rule 5) — paint into a real `Buffer` (the
    /// same free-fn path `crate::tui::draw_list` uses) and compare the
    /// helper both paths share.
    #[test]
    fn list_layout_matches_draw_list_resolver() {
        let backend = TuiBackend::new();
        let list = sample_list();
        let rect = QRect::new(3.0, 1.0, 20.0, 5.0);
        let area = q_rect_to_ratatui(rect);

        let no_paint = backend.list_layout(rect, &list);

        // `draw_list` returns `()`, but it computes its geometry by
        // calling `tui_list_layout(area, list)` internally (see
        // `tui/list.rs::draw_list`) — the same helper `list_layout`
        // calls. Paint into a real buffer (proving it doesn't panic on
        // the shared geometry) and assert the helper output directly.
        let mut buf = ratatui::buffer::Buffer::empty(area);
        crate::tui::draw_list(&mut buf, area, &list, &backend.current_theme, false);
        let via_paint_helper = crate::tui::tui_list_layout(area, &list);

        assert_eq!(
            no_paint, via_paint_helper,
            "list_layout must equal the exact helper draw_list uses internally"
        );
        assert!(
            !no_paint.visible_items.is_empty(),
            "sanity: the sample list has an item to lay out"
        );
    }

    /// Issue #506: `board_layout` is documented **ABSOLUTE** — bounds
    /// are shifted by `rect.x`/`rect.y`, matching `BoardLayout::hit_test`'s
    /// contract that a caller compares it directly against raw click
    /// coordinates. Also proves `board_layout` and `draw_board` agree
    /// byte-for-byte, since both route through `tui_board_layout`.
    #[test]
    fn board_layout_is_absolute_and_matches_draw_board() {
        let backend = TuiBackend::new();
        let model = crate::primitives::board::BoardModel {
            id: WidgetId::new("test:board"),
            columns: vec![crate::primitives::board::BoardColumn {
                id: WidgetId::new("col:a"),
                title: "Backlog".into(),
                cards: vec![crate::primitives::board::BoardCard {
                    id: WidgetId::new("card:1"),
                    title: "Do the thing".into(),
                    labels: vec![],
                    badges: vec![],
                    hint: None,
                }],
                scroll_offset: 0,
            }],
            selected_card_id: None,
            col_scroll_offset: 0,
        };
        let rect = QRect::new(5.0, 2.0, 40.0, 12.0);
        let area = q_rect_to_ratatui(rect);

        let no_paint = backend.board_layout(rect, &model);
        assert_eq!(
            no_paint.bounds,
            crate::event::Rect::new(rect.x, rect.y, rect.width, rect.height),
            "board_layout must fold rect's origin into `bounds` (ABSOLUTE, issue #505)"
        );

        let mut buf = ratatui::buffer::Buffer::empty(area);
        let painted = crate::tui::draw_board(&mut buf, area, &model, &backend.current_theme);
        assert_eq!(
            no_paint, painted,
            "board_layout must equal the exact layout draw_board painted with"
        );
    }

    /// Issue #506 review fix: `terminal_layout`'s default body must
    /// reserve the same scrollbar gutter width `draw_terminal` reserves
    /// before iterating cells (`cell_area_w =
    /// area.width.saturating_sub(sb_cols)`, `src/tui/terminal.rs`), or a
    /// click on the gutter resolves to `TerminalHit::Cell` when the
    /// paint path shows a scrollbar there, not a cell — "paint and
    /// no-paint silently disagree" (rule 5).
    #[test]
    fn terminal_layout_reserves_scrollbar_gutter_matching_draw_terminal() {
        let backend = TuiBackend::new();
        let cell = crate::TerminalCell {
            text: "x".to_string(),
            fg: crate::Color::rgb(200, 200, 200),
            bg: crate::Color::rgb(20, 20, 20),
            bold: false,
            italic: false,
            underline: false,
            dim: false,
            selected: false,
            is_cursor: false,
            is_find_match: false,
            is_find_active: false,
            cursor_shape: TerminalCursorShape::Block,
            cursor_blinking: false,
        };
        let term = TerminalPrim {
            id: WidgetId::new("t"),
            cells: vec![vec![cell; 20]; 5],
            scrollbar: Some(crate::TerminalScrollbar {
                total_lines: 100,
                visible_lines: 5,
                scroll_offset: 0,
                inverted: false,
                // `None` — draw_terminal's `sb_cols: … .unwrap_or(1)` fallback,
                // which `terminal_scrollbar_default_width` must reproduce.
                width: None,
            }),
        };
        let rect = QRect::new(0.0, 0.0, 10.0, 5.0);
        let area = q_rect_to_ratatui(rect);

        let layout = backend.terminal_layout(rect, &term);
        assert_eq!(
            layout.grid_cols, 9,
            "terminal_layout must reserve the 1-column scrollbar gutter (TUI's \
             terminal_scrollbar_default_width), not the full unreduced rect.width"
        );
        assert_eq!(
            layout.hit_test(9.0, 0.0),
            crate::primitives::terminal::TerminalHit::Empty,
            "a click at x=9 (the scrollbar gutter column) must not resolve to a grid cell"
        );

        // Confirm against the real paint path: column 9 is where
        // draw_terminal paints the scrollbar track, not cell glyphs.
        let mut buf = ratatui::buffer::Buffer::empty(area);
        crate::tui::draw_terminal(&mut buf, area, &term, &backend.current_theme);
        assert_ne!(
            buf[(area.x + 9, area.y)].symbol(),
            "x",
            "column 9 is draw_terminal's scrollbar gutter — it must not show painted cell \
             content, matching terminal_layout's grid_cols=9 exclusion of that column"
        );
    }

    /// Minimal two-row-hunk `DiffView` fixture for `diff_view_layout`
    /// parity tests below.
    fn sample_diff_view(mode: crate::DiffMode, left_label: Option<String>) -> crate::DiffView {
        crate::DiffView {
            id: WidgetId::new("diff"),
            left: String::new(),
            right: String::new(),
            left_label,
            right_label: None,
            hunks: vec![crate::DiffHunk {
                left_start: 1,
                right_start: 1,
                rows: vec![
                    crate::DiffRow {
                        left: Some("alpha".into()),
                        right: Some("ALPHA".into()),
                        kind: crate::DiffRowKind::Changed,
                    },
                    crate::DiffRow {
                        left: Some("beta".into()),
                        right: Some("beta".into()),
                        kind: crate::DiffRowKind::Same,
                    },
                ],
            }],
            mode,
            editability: crate::DiffEditability::ReadOnly,
            scroll_offset: 0,
            focused_pane: crate::DiffPane::Left,
            has_focus: false,
        }
    }

    /// Issue #506 review fix: `diff_view_layout` is claimed to be
    /// "verified byte-for-byte against each backend's real paint
    /// formula" — this is the test that makes that claim true rather
    /// than aspirational. `draw_diff_view` returns its `DiffViewLayout`
    /// directly, so this compares the no-paint default body against the
    /// exact value the real paint path produced, in `SideBySide` mode
    /// with a header row reserved.
    #[test]
    fn diff_view_layout_matches_draw_diff_view_side_by_side_with_header() {
        let backend = TuiBackend::new();
        let view = sample_diff_view(crate::DiffMode::SideBySide, Some("left.txt".into()));
        let rect = QRect::new(0.0, 0.0, 40.0, 5.0);
        let area = q_rect_to_ratatui(rect);

        let no_paint = backend.diff_view_layout(rect, &view);

        let mut buf = ratatui::buffer::Buffer::empty(area);
        let painted = crate::tui::draw_diff_view(&mut buf, area, &view, &backend.current_theme);

        assert_eq!(
            no_paint, painted,
            "diff_view_layout must equal the exact layout draw_diff_view painted with"
        );
        assert_eq!(
            no_paint.visible_rows, 4,
            "a 5-row rect minus a 1-row header (left_label is set) leaves 4 content rows"
        );
    }

    /// Same parity check in `Unified` mode, where no header row is
    /// reserved and `total_rows` folds in one synthesized `@@` header
    /// line per hunk.
    #[test]
    fn diff_view_layout_matches_draw_diff_view_unified() {
        let backend = TuiBackend::new();
        let view = sample_diff_view(crate::DiffMode::Unified, None);
        let rect = QRect::new(0.0, 0.0, 40.0, 5.0);
        let area = q_rect_to_ratatui(rect);

        let no_paint = backend.diff_view_layout(rect, &view);

        let mut buf = ratatui::buffer::Buffer::empty(area);
        let painted = crate::tui::draw_diff_view(&mut buf, area, &view, &backend.current_theme);

        assert_eq!(
            no_paint, painted,
            "diff_view_layout must equal the exact layout draw_diff_view painted with (unified \
             mode reserves no header band)"
        );
    }

    /// Minimal blank `EditorLine` for `editor_layout` parity tests below
    /// — content doesn't matter, only that `lines.len()` matches the
    /// viewport row count so `draw_editor` doesn't early-`break`.
    fn blank_editor_line(idx: usize) -> crate::EditorLine {
        crate::EditorLine {
            raw_text: String::new(),
            gutter_text: String::new(),
            spans: Vec::new(),
            line_idx: idx,
            is_current_line: false,
            is_fold_header: false,
            folded_line_count: 0,
            git_diff: None,
            diff_status: None,
            diagnostics: Vec::new(),
            spell_errors: Vec::new(),
            is_breakpoint: false,
            is_conditional_bp: false,
            is_dap_current: false,
            is_wrap_continuation: false,
            segment_col_offset: 0,
            annotation: None,
            ghost_suffix: None,
            is_ghost_continuation: false,
            indent_guides: Vec::new(),
            colorcolumns: Vec::new(),
        }
    }

    /// Issue #506 review fix: `editor_layout` is claimed to be
    /// "verified byte-for-byte against each backend's real paint
    /// formula" — this test makes that claim true for TUI. TUI's
    /// `draw_editor` re-derives its own scrollbar-presence formula by
    /// hand rather than calling `Editor::layout` (`src/tui/editor.rs`:
    /// `has_scrollbar = total_lines > viewport_lines && area.width >
    /// gutter_w + 1`, v-scrollbar track at `(area.x + area.width - 1,
    /// area.y, 1, track_h)`); this test pins `editor_layout`'s
    /// `v_scrollbar_bounds` against that exact independently-derived
    /// track, so the two can't silently drift apart.
    #[test]
    fn editor_layout_matches_draw_editor_scrollbar_track() {
        let backend = TuiBackend::new();
        let rect = QRect::new(2.0, 1.0, 20.0, 5.0);
        let editor = crate::Editor {
            id: WidgetId::new("ed"),
            rect,
            lines: (0..5).map(blank_editor_line).collect(),
            cursor: None,
            extra_cursors: Vec::new(),
            selection: None,
            extra_selections: Vec::new(),
            yank_highlight: None,
            scroll_top: 0,
            scroll_left: 0,
            // > viewport_lines (5) so a v-scrollbar is present.
            total_lines: 100,
            // Small enough that no h-scrollbar is triggered, keeping
            // TUI's two-pass visible_lines/text_h resolution collapsed
            // to a single pass (see `Editor::layout`'s doc).
            max_col: 4,
            gutter_char_width: 0,
            is_active: true,
            show_active_bg: false,
            has_git_diff: false,
            has_breakpoints: false,
            diagnostic_gutter: HashMap::new(),
            code_action_lines: std::collections::HashSet::new(),
            bracket_match_positions: Vec::new(),
            active_indent_col: None,
            tabstop: 4,
            cursorline: false,
            lightbulb_glyph: '!',
        };

        let layout = backend.editor_layout(rect, &editor);
        let vsb = layout
            .v_scrollbar_bounds
            .expect("100 lines in a 5-row viewport must trigger a v-scrollbar");
        assert_eq!(
            vsb,
            crate::event::Rect::new(rect.x + rect.width - 1.0, rect.y, 1.0, rect.height),
            "editor_layout's v_scrollbar_bounds must match draw_editor's own track formula \
             `(area.x + area.width - 1, area.y, 1, track_h)` (src/tui/editor.rs)"
        );

        // Paint via the exact free fn TuiBackend::draw_editor calls —
        // proves the shared scrollbar-presence formula doesn't panic
        // against this geometry, and that the hit-test the layout
        // exposes resolves at the painted track's own origin.
        let area = q_rect_to_ratatui(rect);
        let mut buf = ratatui::buffer::Buffer::empty(area);
        crate::tui::draw_editor(&mut buf, area, &editor, &backend.current_theme);

        assert_eq!(
            layout.hit_test(vsb.x, vsb.y),
            crate::EditorHit::VScrollbar,
            "a click at the painted scrollbar track's origin must resolve via editor_layout's \
             own hit_test as VScrollbar"
        );
    }

    /// `Backend::set_editor_right_reserve_w`/`editor_right_reserve_w` must
    /// round-trip, default to `None`, and `TuiBackend::editor_layout` must
    /// fold the stored value into `Editor::layout_with_options_and_reserve`
    /// so `text_bounds`/`h_scrollbar_bounds` narrow by the reserve while
    /// `v_scrollbar_bounds` keeps hugging the true right edge — matching
    /// `draw_editor`'s own `right_reserve` handling (`src/tui/editor.rs`).
    /// `max_col` is large enough (relative to the 20-column viewport) that
    /// an h-scrollbar is actually present in both the baseline and the
    /// reserved layout, so `h_scrollbar_bounds` narrowing is a real
    /// assertion rather than a vacuous `None`. The paint call at the end
    /// cross-checks `editor_layout` against `draw_editor` at this same
    /// *non-zero* reserve, not just at `0` (which is all
    /// `editor_layout_matches_draw_editor_scrollbar_track` above covers).
    #[test]
    fn editor_right_reserve_w_narrows_layout_without_moving_scrollbar() {
        let mut backend = TuiBackend::new();
        assert_eq!(
            backend.editor_right_reserve_w(),
            None,
            "a host that never calls the setter must see no reserve"
        );

        let rect = QRect::new(2.0, 1.0, 20.0, 5.0);
        let editor = crate::Editor {
            id: WidgetId::new("ed"),
            rect,
            lines: (0..5).map(blank_editor_line).collect(),
            cursor: None,
            extra_cursors: Vec::new(),
            selection: None,
            extra_selections: Vec::new(),
            yank_highlight: None,
            scroll_top: 0,
            scroll_left: 0,
            total_lines: 100,
            // > the ~16-19 visible columns left after the gutter/
            // scrollbar/reserve in both the baseline and reserved
            // layouts below, so an h-scrollbar is present in both.
            max_col: 40,
            gutter_char_width: 0,
            is_active: true,
            show_active_bg: false,
            has_git_diff: false,
            has_breakpoints: false,
            diagnostic_gutter: HashMap::new(),
            code_action_lines: std::collections::HashSet::new(),
            bracket_match_positions: Vec::new(),
            active_indent_col: None,
            tabstop: 4,
            cursorline: false,
            lightbulb_glyph: '!',
        };

        let baseline = backend.editor_layout(rect, &editor);

        backend.set_editor_right_reserve_w(Some(3.0));
        assert_eq!(backend.editor_right_reserve_w(), Some(3.0));
        let reserved = backend.editor_layout(rect, &editor);

        let vsb = baseline
            .v_scrollbar_bounds
            .expect("100 lines in a 5-row viewport must trigger a v-scrollbar");
        assert_eq!(
            reserved.v_scrollbar_bounds,
            Some(vsb),
            "v_scrollbar_bounds must stay put — right_reserve_w only narrows the text area"
        );
        assert_eq!(
            reserved.text_bounds.width,
            baseline.text_bounds.width - 3.0,
            "text_bounds must narrow by exactly the stored reserve"
        );

        let baseline_hsb = baseline
            .h_scrollbar_bounds
            .expect("max_col 40 over a narrow viewport must trigger an h-scrollbar");
        let reserved_hsb = reserved
            .h_scrollbar_bounds
            .expect("the reserve narrows visible_cols further, still triggering an h-scrollbar");
        assert_eq!(
            reserved_hsb.width,
            baseline_hsb.width - 3.0,
            "h_scrollbar_bounds must narrow by exactly the stored reserve, same as text_bounds"
        );

        // Cross-check against the real `draw_editor` paint at this same
        // non-zero reserve: `v_scrollbar_bounds` must match the track
        // `draw_editor` actually painted (area.x + area.width - 1, …),
        // same invariant as the reserve-0 test above but exercised here
        // with `right_reserve = 3`.
        let area = q_rect_to_ratatui(rect);
        let mut buf = ratatui::buffer::Buffer::empty(area);
        crate::tui::draw_editor_with_reserve(&mut buf, area, &editor, &backend.current_theme, 3);
        assert_eq!(
            vsb.x,
            rect.x + rect.width - 1.0,
            "v_scrollbar_bounds's x must match draw_editor's track formula \
             (area.x + area.width - 1) even with a non-zero reserve"
        );
    }

    /// An inactive window's `None` cursor must not clobber
    /// an active window's `Some` position recorded earlier in the same
    /// frame. A split has one `draw_editor` call per window; only the
    /// active window's `Editor.cursor` is `Some` (the consumer only ever
    /// sets `RenderedWindow.cursor` for the active window), so the
    /// inactive window's call correctly reports `None` — but before this
    /// fix `last_cursor_position` was overwritten unconditionally on every
    /// call, so whichever window painted *last* decided the whole frame's
    /// caret, not whichever window was actually active. This reproduces
    /// vimcode#1039's "active window, wrong paint order ⇒ no caret" shape
    /// by painting the active window first and the inactive window
    /// second.
    #[test]
    fn draw_editor_none_does_not_clobber_earlier_some_cursor_in_same_frame() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let rect = QRect::new(0.0, 0.0, 20.0, 5.0);
        let active_editor = crate::Editor {
            id: WidgetId::new("active"),
            rect,
            lines: (0..5).map(blank_editor_line).collect(),
            cursor: Some(crate::EditorCursor {
                pos: crate::EditorCursorPos {
                    view_line: 0,
                    col: 0,
                },
                shape: crate::EditorCursorShape::Bar,
            }),
            extra_cursors: Vec::new(),
            selection: None,
            extra_selections: Vec::new(),
            yank_highlight: None,
            scroll_top: 0,
            scroll_left: 0,
            total_lines: 5,
            max_col: 4,
            gutter_char_width: 0,
            is_active: true,
            show_active_bg: false,
            has_git_diff: false,
            has_breakpoints: false,
            diagnostic_gutter: HashMap::new(),
            code_action_lines: std::collections::HashSet::new(),
            bracket_match_positions: Vec::new(),
            active_indent_col: None,
            tabstop: 4,
            cursorline: false,
            lightbulb_glyph: '!',
        };
        let mut inactive_editor = active_editor.clone();
        inactive_editor.id = WidgetId::new("inactive");
        inactive_editor.cursor = None;
        inactive_editor.is_active = false;

        let mut backend = TuiBackend::new();
        backend.begin_frame(Viewport::new(20.0, 5.0, 1.0));

        let mut terminal = Terminal::new(TestBackend::new(20, 5)).expect("test terminal");
        terminal
            .draw(|frame| {
                backend.enter_frame_scope(frame, |b| {
                    // Active window paints first and reports `Some` —
                    // mirrors vimcode's pre-workaround fixed paint order
                    // (left, then right), which broke whenever the left
                    // (active) window wasn't the one painted last.
                    let active_result = b.draw_editor(rect, &active_editor);
                    assert_eq!(
                        active_result.cursor_position_native,
                        Some(crate::event::Point::new(0.0, 0.0))
                    );

                    // Inactive window paints second and correctly reports
                    // `None` — this must not clobber the cache.
                    let inactive_result = b.draw_editor(rect, &inactive_editor);
                    assert_eq!(inactive_result.cursor_position_native, None);
                });
            })
            .expect("draw");

        assert_eq!(
            backend.take_last_cursor_position(),
            Some((0, 0)),
            "an inactive window's None cursor_position must not clobber the active \
             window's Some position recorded earlier in the same frame (quadraui#1002)"
        );
    }

    // ── mouse_enabled / `no-mouse` mode ─────────────────────────────────

    /// `TuiBackend::new()` defaults to mouse reporting enabled — matches
    /// [`super::run::RunConfig::default`] (`mouse: true`), so a backend
    /// nobody has called `set_mouse_enabled` on behaves exactly as it did
    /// before `no-mouse` mode existed. `backend_caps().mouse` stays `true`
    /// regardless (it is the static per-backend-*type* fact, not this
    /// session's config — see `backend_caps`'s doc).
    #[test]
    fn mouse_enabled_defaults_to_true() {
        let backend = TuiBackend::new();
        assert!(backend.mouse_enabled());
        assert!(backend.backend_caps().mouse);
    }

    /// `set_mouse_enabled(false)` — what `run_with(app, RunConfig { mouse:
    /// false, .. })` calls before entering the frame loop — flips the
    /// session-level accessor without touching `backend_caps()`, which
    /// stays a static per-backend-type declaration (see
    /// `mouse_enabled` field's doc for why `tests/conformance/caps.rs`'s
    /// source-parsing check requires that split).
    #[test]
    fn set_mouse_enabled_false_is_a_session_level_toggle_only() {
        let mut backend = TuiBackend::new();
        backend.set_mouse_enabled(false);
        assert!(!backend.mouse_enabled());
        assert!(
            backend.backend_caps().mouse,
            "backend_caps().mouse is a static per-backend-type fact, unaffected by \
             set_mouse_enabled"
        );
    }

    /// Round-trip: re-enabling restores the original state —
    /// `set_mouse_enabled` is a plain toggle, not a one-way ratchet.
    #[test]
    fn set_mouse_enabled_true_restores_state() {
        let mut backend = TuiBackend::new();
        backend.set_mouse_enabled(false);
        backend.set_mouse_enabled(true);
        assert!(backend.mouse_enabled());
    }

    // ── SGR-Pixels mouse mode ────────────────────────────────────────────

    /// `cell_pixel_size` defaults to the identity divisor — a backend
    /// nobody has called `set_cell_pixel_size` on must leave every mouse
    /// coordinate byte-identical to pre-#1048 cell-mode behaviour, since
    /// `sgr_pixel_mouse` also defaults to whatever the environment
    /// heuristic says (`false` in a `cargo test` process with no relevant
    /// env vars set).
    #[test]
    fn cell_pixel_size_defaults_to_identity() {
        let backend = TuiBackend::new();
        assert_eq!(backend.cell_pixel_size(), TerminalCellSize::new(1.0, 1.0));
    }

    /// `set_sgr_pixel_mouse`/`set_cell_pixel_size` round-trip through their
    /// accessors and surface via `backend_caps().sgr_pixel_mouse` — the
    /// same session-level-toggle shape `set_mouse_enabled` already has,
    /// except this one *does* affect `backend_caps()` (see that field's
    /// doc: a runtime-detected terminal property, not a static
    /// per-backend-type fact).
    #[test]
    fn set_sgr_pixel_mouse_and_cell_size_round_trip() {
        let mut backend = TuiBackend::new();
        assert!(!backend.backend_caps().sgr_pixel_mouse);

        backend.set_sgr_pixel_mouse(true);
        backend.set_cell_pixel_size(TerminalCellSize::new(9.0, 18.0));
        assert!(backend.sgr_pixel_mouse());
        assert!(backend.backend_caps().sgr_pixel_mouse);
        assert_eq!(backend.cell_pixel_size(), TerminalCellSize::new(9.0, 18.0));

        backend.set_sgr_pixel_mouse(false);
        assert!(!backend.backend_caps().sgr_pixel_mouse);
    }

    /// A `TuiBackend` configured for SGR-Pixels mode divides a live mouse
    /// report's raw pixel `column`/`row` by the configured cell size —
    /// this is the same code path `poll_events`/`wait_events` drive with
    /// `self.cell_pixel_size`, exercised here directly since those two
    /// need a real crossterm event source `cargo test` doesn't have.
    #[test]
    fn cell_pixel_size_scales_a_live_mouse_report() {
        use ratatui::crossterm::event::{MouseButton as CtMouseButton, MouseEvent, MouseEventKind};

        let mut backend = TuiBackend::new();
        backend.set_sgr_pixel_mouse(true);
        backend.set_cell_pixel_size(TerminalCellSize::new(8.0, 16.0));

        let raw = MouseEvent {
            kind: MouseEventKind::Down(CtMouseButton::Left),
            column: 40,
            row: 24,
            modifiers: ratatui::crossterm::event::KeyModifiers::empty(),
        };
        let ev =
            super::super::events::crossterm_mouse_to_uievent_scaled(raw, backend.cell_pixel_size())
                .unwrap();
        match ev {
            UiEvent::MouseDown { position, .. } => {
                assert_eq!(position.x, 5.0); // 40 / 8
                assert_eq!(position.y, 1.5); // 24 / 16
            }
            other => panic!("unexpected variant: {:?}", other),
        }
    }

    // ── request_frame_in ────────────────────────────────────────────────

    /// With nothing requested, the poll timeout is the full ceiling —
    /// this is the "idle app doesn't poll tightly" behavior the issue's
    /// acceptance criterion asks for, made concrete at the `TuiBackend`
    /// level (`tui::run::run_inner` is what actually calls
    /// `wait_events` with this value).
    #[test]
    fn no_request_frame_in_call_uses_the_full_ceiling() {
        let backend = TuiBackend::new();
        assert_eq!(
            backend.frame_poll_timeout(Duration::from_millis(250)),
            Duration::from_millis(250)
        );
    }

    /// `request_frame_in` shortens the next poll timeout to (at most) the
    /// requested delay.
    #[test]
    fn request_frame_in_shortens_the_poll_timeout() {
        let backend = TuiBackend::new();
        Backend::request_frame_in(&backend, Duration::from_millis(10));
        let timeout = backend.frame_poll_timeout(Duration::from_millis(250));
        assert!(
            timeout <= Duration::from_millis(10),
            "expected a short timeout, got {timeout:?}"
        );
    }

    /// `clear_frame_deadline_if_due` is a no-op before the deadline has
    /// elapsed — the run loop must not busy-spin at a near-zero timeout
    /// immediately after arming a longer-lived request.
    #[test]
    fn clear_frame_deadline_if_due_is_a_noop_before_the_deadline() {
        let mut backend = TuiBackend::new();
        Backend::request_frame_in(&backend, Duration::from_secs(60));
        backend.clear_frame_deadline_if_due();
        let timeout = backend.frame_poll_timeout(Duration::from_millis(1));
        assert!(
            timeout <= Duration::from_millis(1),
            "the still-pending far-future deadline must keep governing the \
             ceiling-clamped timeout, got {timeout:?}"
        );
    }

    /// Once cleared, a fresh ceiling-bound timeout returns — proves
    /// `clear_frame_deadline_if_due` actually clears rather than just
    /// reading the deadline.
    #[test]
    fn clear_frame_deadline_if_due_clears_an_elapsed_deadline() {
        let mut backend = TuiBackend::new();
        Backend::request_frame_in(&backend, Duration::ZERO);
        std::thread::sleep(Duration::from_millis(1));
        backend.clear_frame_deadline_if_due();
        assert_eq!(
            backend.frame_poll_timeout(Duration::from_millis(250)),
            Duration::from_millis(250)
        );
    }

    /// Issue #1037: `take_full_repaint_requested` answers `false` until
    /// `Backend::request_full_repaint` has been called, `true` exactly
    /// once after, then `false` again — a caller that consumes it twice
    /// (e.g. a bug re-checking after already clearing the terminal) must
    /// not see a stale `true`.
    #[test]
    fn take_full_repaint_requested_is_consumed_exactly_once() {
        let mut backend = TuiBackend::new();
        assert!(
            !backend.take_full_repaint_requested(),
            "nothing requested yet"
        );

        Backend::request_full_repaint(&mut backend);
        assert!(
            backend.take_full_repaint_requested(),
            "a pending request must be observed"
        );
        assert!(
            !backend.take_full_repaint_requested(),
            "the request must be cleared after the first consumption"
        );
    }

    // ─── Issue #1117: setup-order panics degrade instead of aborting ────
    //
    // `.expect()` used to fire in every build profile, not just debug —
    // `current_frame_mut`'s own doc claimed "panic in dev, silent return
    // otherwise" while every real call site ignored that and panicked
    // unconditionally. The fix routes through `debug_assert!` (loud in
    // dev, matching every sibling "outside enter_frame_scope" contract
    // elsewhere in this file/`gtk`/`macos`) plus a per-method graceful
    // default. `cargo test`'s default profile has `debug_assertions`
    // on, so the panic-in-dev half is exercised by an ordinary
    // `#[should_panic]` test below; the release half — the actual
    // behavioural change — needs `debug_assertions` off to reach the
    // non-panicking branch at all, so those tests are gated
    // `cfg(not(debug_assertions))` and verified with:
    //   RUSTFLAGS="-C debug-assertions=off" cargo test --features tui \
    //     -p quadraui --lib tui::backend::tests::draw_ -- --ignored
    // (they aren't `--ignored`; that invocation is just illustrative —
    // any `cargo test` run built with debug-assertions off runs them
    // normally). They compile to nothing, and therefore never run,
    // under this repo's ordinary `cargo test --features tui` gate.

    fn empty_tree() -> TreeView {
        TreeView {
            id: WidgetId::new("tree:empty"),
            rows: Vec::new(),
            selection_mode: crate::types::SelectionMode::default(),
            selected_path: None,
            scroll_offset: 0,
            style: crate::TreeStyle::default(),
            has_focus: false,
        }
    }

    // Gated on `debug_assertions` to mirror its release-mode sibling below:
    // the loud-panic contract only exists while `debug_assert!` is live, so
    // an ungated `#[should_panic]` here fails any `cargo test --release`.
    #[test]
    #[cfg(debug_assertions)]
    #[should_panic(expected = "TuiBackend::draw_tree called outside enter_frame_scope")]
    fn draw_tree_outside_frame_scope_panics_loudly_in_dev() {
        let mut backend = TuiBackend::new();
        // No `enter_frame_scope` — `debug_assert!` must still catch this
        // during development, exactly as the old `.expect()` did.
        backend.draw_tree(QRect::new(0.0, 0.0, 10.0, 5.0), &empty_tree());
    }

    #[test]
    #[cfg(not(debug_assertions))]
    fn draw_tree_outside_frame_scope_does_not_panic_in_release() {
        let mut backend = TuiBackend::new();
        // Must not panic in release builds.
        backend.draw_tree(QRect::new(0.0, 0.0, 10.0, 5.0), &empty_tree());
    }

    #[test]
    #[cfg(not(debug_assertions))]
    fn draw_pipeline_view_outside_frame_scope_degrades_to_pure_layout() {
        let mut backend = TuiBackend::new();
        let view = crate::primitives::pipeline_view::PipelineView {
            id: WidgetId::new("pipeline"),
            stages: Vec::new(),
            focused_stage: None,
        };
        let rect = QRect::new(0.0, 0.0, 40.0, 10.0);

        let degraded = backend.draw_pipeline_view(rect, &view);
        let pure = backend.pipeline_view_layout(rect, &view);
        assert_eq!(
            degraded, pure,
            "a missing frame must fall back to exactly what the pure \
             `pipeline_view_layout` twin would have computed"
        );
    }

    #[test]
    #[cfg(not(debug_assertions))]
    fn draw_minimap_outside_frame_scope_reports_not_painted() {
        let mut backend = TuiBackend::new();
        let minimap = crate::primitives::minimap::Minimap {
            id: WidgetId::new("minimap"),
            lines: Vec::new(),
            syntax_spans: Vec::new(),
            visible_row_start: 0,
            visible_row_count: 0,
            total_buffer_lines: 0,
        };
        let rect = QRect::new(0.0, 0.0, 10.0, 20.0);

        let result = backend.draw_minimap(rect, &minimap);
        assert!(
            !result.painted,
            "no frame means nothing was actually rasterised"
        );
        assert_eq!(
            result.layout,
            backend.minimap_layout(rect, &minimap),
            "the reported layout must still be the real geometry, not a stub"
        );
    }

    #[test]
    #[cfg(not(debug_assertions))]
    fn draw_image_outside_frame_scope_reports_unsupported() {
        let mut backend = TuiBackend::new();
        let image = crate::primitives::image::Image {
            id: WidgetId::new("image"),
            source: crate::primitives::image::ImageSource::Bytes(Vec::new()),
            intrinsic_size: None,
            fit: crate::primitives::image::ImageFit::Contain,
            fallback_text: "[image]".to_string(),
        };
        let rect = QRect::new(0.0, 0.0, 10.0, 10.0);

        assert_eq!(
            backend.draw_image(rect, &image),
            crate::backend::ImagePaintResult::Unsupported,
            "mirrors the win/macOS \"no rasteriser available\" report (issue #924)"
        );
    }

    // ── Underline-colour (SGR 58) ConPTY misparse ───────
    //
    // ConPTY only recognises SGR 58 in the colon form; crossterm's
    // `SetUnderlineColor` only ever emits the semicolon form, so ConPTY
    // drops the `58` and reinterprets the trailing numbers as unrelated
    // SGR attributes (blink/faint) — see `tui::caps`'s module doc. These
    // tests exercise the fix end to end: a real `AppLogic` painting the
    // two primitives the issue names (the active tab's accent underline,
    // an editor's diagnostic + spell-error underlines), driven through
    // the exact `paint_frame` the live runner and `TuiDriver` both call.

    /// `TabBar` with one active tab and an accent colour — the fixture
    /// `tab_bar::draw_tab_bar`'s `set_cell_styled` call sets
    /// `Cell::underline_color` for.
    fn underline_fixture_tab_bar() -> TabBar {
        TabBar {
            id: WidgetId::new("tabs"),
            tabs: vec![crate::primitives::tab_bar::TabItem {
                label: "app.rs".into(),
                is_active: true,
                is_dirty: false,
                is_preview: false,
                is_closable: true,
            }],
            right_segments: vec![],
            active_accent: Some(crate::Color::rgb(80, 160, 255)),
            scroll_offset: 0,
            show_tab_close: true,
            compact: false,
        }
    }

    /// One-line `Editor` carrying a diagnostic and a spell error at
    /// distinct columns — the two decoration categories `editor::draw_editor`
    /// sets `Cell::underline_color` for.
    fn underline_fixture_editor() -> crate::Editor {
        let line = crate::EditorLine {
            raw_text: "x".repeat(20),
            gutter_text: String::new(),
            spans: Vec::new(),
            line_idx: 0,
            is_current_line: false,
            is_fold_header: false,
            folded_line_count: 0,
            git_diff: None,
            diff_status: None,
            diagnostics: vec![crate::DiagnosticMark {
                start_col: 2,
                end_col: 5,
                severity: crate::DiagnosticSeverity::Error,
                message: String::new(),
            }],
            spell_errors: vec![crate::SpellMark {
                start_col: 8,
                end_col: 10,
            }],
            is_breakpoint: false,
            is_conditional_bp: false,
            is_dap_current: false,
            is_wrap_continuation: false,
            segment_col_offset: 0,
            annotation: None,
            ghost_suffix: None,
            is_ghost_continuation: false,
            indent_guides: Vec::new(),
            colorcolumns: Vec::new(),
        };
        crate::Editor {
            id: WidgetId::new("ed"),
            rect: QRect::new(0.0, 1.0, 20.0, 4.0),
            lines: vec![line],
            cursor: None,
            extra_cursors: Vec::new(),
            selection: None,
            extra_selections: Vec::new(),
            yank_highlight: None,
            scroll_top: 0,
            scroll_left: 0,
            total_lines: 1,
            max_col: 20,
            gutter_char_width: 0,
            is_active: true,
            show_active_bg: false,
            has_git_diff: false,
            has_breakpoints: false,
            diagnostic_gutter: HashMap::new(),
            code_action_lines: std::collections::HashSet::new(),
            bracket_match_positions: Vec::new(),
            active_indent_col: None,
            tabstop: 4,
            cursorline: false,
            lightbulb_glyph: '!',
        }
    }

    /// Paints [`underline_fixture_tab_bar`] + [`underline_fixture_editor`]
    /// through the real `Backend` trait methods — the production call
    /// path, not the free rasteriser functions directly.
    struct UnderlineFixtureApp;
    impl crate::runner::AppLogic for UnderlineFixtureApp {
        type AreaId = ();
        fn render(&self, backend: &mut dyn crate::backend::Backend, _area: ()) {
            let bar = underline_fixture_tab_bar();
            backend.draw_tab_bar(QRect::new(0.0, 0.0, 20.0, 1.0), &bar, None);
            let editor = underline_fixture_editor();
            backend.draw_editor(editor.rect, &editor);
        }
        fn handle(
            &mut self,
            _event: crate::UiEvent,
            _backend: &mut dyn crate::backend::Backend,
        ) -> crate::runner::Reaction {
            crate::runner::Reaction::Continue
        }
    }

    /// Sanity half of the acceptance test: with the *default* (non-Windows)
    /// caps, [`UnderlineFixtureApp`] must still leave a real,
    /// non-`Reset` `underline_color` painted somewhere — otherwise the
    /// "stripped on Windows" assertion below would pass vacuously even
    /// if `draw_tab_bar`/`draw_editor` stopped setting `underline_color`
    /// at all. This is also the explicit non-regression case the issue
    /// asks for: a non-Windows terminal's accent underline must be
    /// unaffected by this fix.
    #[test]
    fn non_windows_caps_leave_underline_colors_intact() {
        use ratatui::backend::TestBackend;

        let mut backend = TuiBackend::new();
        // The default is platform-detected: off on Windows (ConPTY
        // misparses SGR 58), on everywhere else. Pin that, then force
        // "supported" so this non-regression case runs on every CI leg —
        // including windows-latest.
        assert_eq!(
            backend.underline_color_supported(),
            !cfg!(windows),
            "default underline-colour support must be off exactly on Windows"
        );
        backend.set_underline_color_supported(true);
        let mut terminal =
            ratatui::Terminal::new(TestBackend::new(20, 5)).expect("TestBackend terminal");
        super::super::run::paint_frame(&mut terminal, &mut backend, &UnderlineFixtureApp)
            .expect("TestBackend render is infallible");

        let buf = terminal.backend().buffer();
        assert!(
            buf.content
                .iter()
                .any(|c| c.underline_color != ratatui::style::Color::Reset),
            "fixture sanity: expected at least one cell with underline_color set \
             when underline colour support is on"
        );
    }

    /// Core acceptance case: with capabilities
    /// representing Windows/ConPTY (`underline_color_supported ==
    /// false`), no cell painted by the active tab's accent underline or
    /// the editor's diagnostic/spell-error underlines may carry a
    /// non-`Reset` `underline_color` after a real frame paints.
    #[test]
    fn windows_conpty_caps_strip_every_underline_color() {
        use ratatui::backend::TestBackend;

        let mut backend = TuiBackend::new();
        backend.set_underline_color_supported(false);

        let mut terminal =
            ratatui::Terminal::new(TestBackend::new(20, 5)).expect("TestBackend terminal");
        super::super::run::paint_frame(&mut terminal, &mut backend, &UnderlineFixtureApp)
            .expect("TestBackend render is infallible");

        let buf = terminal.backend().buffer();
        for (i, cell) in buf.content.iter().enumerate() {
            assert_eq!(
                cell.underline_color,
                ratatui::style::Color::Reset,
                "cell {i} still carries underline_color {:?} on simulated Windows/ConPTY caps",
                cell.underline_color
            );
        }
    }

    /// The byte-level half of the acceptance test: the real
    /// ANSI stream a `CrosstermBackend` would send to the terminal must
    /// contain no `ESC[58` (SGR 58, underline colour) at all when
    /// capabilities represent Windows/ConPTY — the exact sequence ConPTY
    /// misparses as blink/faint — and must still contain one on
    /// non-Windows caps, so the fix doesn't silently regress every other
    /// platform's accent underline.
    #[test]
    fn windows_conpty_caps_emit_no_sgr_58_bytes() {
        use ratatui::backend::CrosstermBackend;
        use std::cell::RefCell;
        use std::io;
        use std::rc::Rc;

        /// `io::Write` sink that just retains every byte written —
        /// enough to assert on the raw escape sequence, unlike
        /// `vt_testing::VtSink` (which feeds a `vt100::Parser` and keeps
        /// no raw bytes around to inspect).
        #[derive(Clone, Default)]
        struct RawSink(Rc<RefCell<Vec<u8>>>);
        impl io::Write for RawSink {
            fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
                self.0.borrow_mut().extend_from_slice(buf);
                Ok(buf.len())
            }
            fn flush(&mut self) -> io::Result<()> {
                Ok(())
            }
        }

        for (supported, should_contain_sgr_58) in [(true, true), (false, false)] {
            let sink = RawSink::default();
            let crossterm_backend = CrosstermBackend::new(sink.clone());
            let mut terminal = ratatui::Terminal::with_options(
                crossterm_backend,
                ratatui::TerminalOptions {
                    viewport: ratatui::Viewport::Fixed(Rect::new(0, 0, 20, 5)),
                },
            )
            .expect("CrosstermBackend + Viewport::Fixed never queries a real terminal");

            let mut backend = TuiBackend::new();
            backend.set_underline_color_supported(supported);
            super::super::run::paint_frame(&mut terminal, &mut backend, &UnderlineFixtureApp)
                .expect("CrosstermBackend render into an in-memory sink is infallible");

            let bytes = sink.0.borrow();
            let contains_sgr_58 = bytes.windows(4).any(|w| w == b"\x1b[58");
            assert_eq!(
                contains_sgr_58, should_contain_sgr_58,
                "underline_color_supported={supported}: expected ESC[58 presence to be \
                 {should_contain_sgr_58}, got {contains_sgr_58}"
            );
        }
    }
}

/// Property tests for the SGR mouse-report decode path:
/// `cb`/`x`/`y` come from a real terminal's escape-sequence reply — bytes
/// this crate does not control, parsed as plain decimal numbers by
/// `try_reassemble_sgr_mouse`'s caller before reaching here — so this
/// must never panic on any `u16` triple, not just the well-formed button
/// codes the hand-picked fixtures above exercise.
#[cfg(test)]
mod proptests {
    use super::*;
    use crate::primitives::terminal::TerminalCellSize;
    use proptest::prelude::*;

    proptest! {
        /// Every `(cb, x, y, is_release)` combination — including `Cb`
        /// values with no assigned button/modifier meaning and `x`/`y`
        /// at the very top of `u16` (`saturating_sub(1)` must not
        /// underflow-panic) — must decode without panicking.
        #[test]
        fn decode_sgr_mouse_report_never_panics(
            cb in any::<u16>(),
            x in any::<u16>(),
            y in any::<u16>(),
            is_release in any::<bool>(),
        ) {
            let cell_size = TerminalCellSize::new(1.0, 1.0);
            let _ = decode_sgr_mouse_report(cb, x, y, is_release, cell_size);
        }

        /// Same, but with a degenerate (zero) cell size — the divide that
        /// turns pixel coordinates back into fractional cells
        /// (`super::events::crossterm_mouse_to_uievent_scaled`) must not
        /// panic (float division by zero is `inf`/`NaN` in Rust, not a
        /// panic, but this pins that it stays that way rather than a
        /// future refactor introducing an integer path).
        #[test]
        fn decode_sgr_mouse_report_never_panics_with_zero_cell_size(
            cb in any::<u16>(),
            x in any::<u16>(),
            y in any::<u16>(),
        ) {
            let cell_size = TerminalCellSize::new(0.0, 0.0);
            let _ = decode_sgr_mouse_report(cb, x, y, false, cell_size);
        }
    }
}