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
//! The `Backend` trait — one implementation per platform target (TUI, GTK,
//! Win-GUI, and eventually macOS). Apps write render code once, parameterised
//! over `<B: Backend>`; every backend rasterises the same primitive
//! descriptions with platform-native drawing + input. See
//! `quadraui/docs/decisions/BACKEND_TRAIT_PROPOSAL.md` §4 for design rationale.
//!
//! Every `draw_<name>` method is the low-level rasteriser entry point for its
//! primitive, always public. Prefer [`crate::frame::ScreenLayout`] +
//! [`crate::frame::Surface`] to assemble a top-level screen from multiple
//! primitives — it routes every backend through the same call site. `draw_*`
//! stays directly reachable for rasteriser tests and compose helpers.
//!
//! ## Coordinate frames for `*_layout` methods
//!
//! Every `Backend::<name>_layout` method documents which of two frames its
//! `hit_regions` / `bounds` fields are in:
//!
//! - **LOCAL** — relative to `rect`'s origin; `(0, 0)` is `rect`'s top-left
//!   corner. Used by primitives a parent composer paints inline and
//!   localises clicks for before calling `hit_test`.
//! - **ABSOLUTE** — shifted by `rect.x` / `rect.y`, i.e. target-surface
//!   coordinates comparable directly against raw click coordinates. Used by
//!   primitives painted as a freestanding widget at their own screen rect.
//!
//! A third case returns no coordinates at all — `diff_view_layout` returns
//! row *counts*, not positions — and its own doc says so explicitly.
//!
//! Both frames are legitimate; what this file enforces is that each method's
//! doc states its frame and every backend implementation actually returns
//! that frame (see `quadraui/docs/PRIMITIVE_RULES.md` "Coordinate frames for
//! `*_layout` methods" for the authoring rule).

use std::cell::RefCell;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;

use crate::dispatch::DragState;
use crate::event::{Point, Rect, UiEvent, UserPayload, Viewport};
use crate::focus::FocusManager;
use crate::interaction::InteractionState;
use crate::modal_stack::ModalStack;
use crate::primitives::activity_bar::{ActivityBarRowHit, ActivityBarStyle};
use crate::primitives::board::{BoardLayout, BoardModel};
use crate::primitives::button::{Button, ButtonLayout};
use crate::primitives::canvas::{Canvas, CanvasLayout};
use crate::primitives::chart::{Chart, ChartLayout};
use crate::primitives::combo_box::{ComboBox, ComboBoxLayout};
use crate::primitives::command_center::{CommandCenter, CommandCenterLayout};
use crate::primitives::command_line::{CommandLine, CommandLineLayout};
use crate::primitives::completions::{Completions, CompletionsLayout};
use crate::primitives::context_menu::{ContextMenu, ContextMenuGlyphs, ContextMenuLayout};
use crate::primitives::data_table::{DataTable, DataTableGlyphs, DataTableLayout};
use crate::primitives::date_picker::{DatePicker, DatePickerLayout};
use crate::primitives::dialog::{Dialog, DialogLayout, DialogSeverity};
use crate::primitives::diff_view::{DiffMode, DiffView, DiffViewLayout};
use crate::primitives::drop_zone::DropOverlay;
use crate::primitives::editor::{CursorShape as EditorCursorShape, Editor, EditorLayout};
use crate::primitives::find_replace::FindReplacePanel;
use crate::primitives::float::{Float, FloatLayout};
use crate::primitives::form::FormLayout;
use crate::primitives::image::{Image, ImageSource};
use crate::primitives::list::ListViewLayout;
use crate::primitives::menu_bar::{MenuBar, MenuBarLayout};
use crate::primitives::message_list::MessageList;
use crate::primitives::minimap::{Minimap, MinimapLayout, MinimapScale};
use crate::primitives::multi_section_view::{
    MsvLayoutMetrics, MultiSectionView, MultiSectionViewLayout,
};
use crate::primitives::number_input::{NumberInput, NumberInputLayout};
use crate::primitives::panel::{Panel, PanelLayout};
use crate::primitives::pipeline_view::{PipelineView, PipelineViewLayout};
use crate::primitives::progress::{ProgressBar, ProgressBarLayout};
use crate::primitives::radio_group::{RadioGroup, RadioGroupLayout};
use crate::primitives::rich_text_popup::{RichTextPopup, RichTextPopupLayout};
use crate::primitives::scrollbar::Scrollbar;
use crate::primitives::sidebar_panel::{SidebarPanel, SidebarPanelLayout};
use crate::primitives::spinner::{Spinner, SpinnerLayout};
use crate::primitives::split::{Split, SplitLayout};
use crate::primitives::split_tree::{SplitTree, SplitTreeLayout};
use crate::primitives::status_bar::StatusBarLayout;
use crate::primitives::switch::{Switch, SwitchLayout};
// `TabBarHits` is `#[deprecated]` — this trait still returns it from six
// methods below, so the import itself needs the same allow every use site
// does.
#[allow(deprecated)]
use crate::primitives::tab_bar::{TabBarGlyphs, TabBarHits, TabBarLayout, TabChrome, TabIcon};
use crate::primitives::text_display::TextDisplayLayout;
use crate::primitives::text_input::{TextInput, TextInputLayout};
use crate::primitives::toast::{ToastOverlay, ToastStackLayout};
use crate::primitives::toolbar::{Toolbar, ToolbarLayout, ToolbarPaintOptions};
use crate::primitives::tooltip::{Tooltip, TooltipChrome, TooltipLayout};
use crate::primitives::tree::TreeViewLayout;
use crate::types::{Color, WidgetId};
use crate::{
    Accelerator, AcceleratorId, ActivityBar, Form, ListView, Palette, PaletteLayout, StatusBar,
    TabBar, Terminal, TextDisplay, TreeView,
};
use serde::{Deserialize, Serialize};

/// Which edge or corner of a window a resize gesture originates from.
/// Mirrors `gdk4::SurfaceEdge` 1:1 (see [`Backend::begin_window_resize`]) so
/// the GTK backend's conversion is a plain match with no ambiguity, but the
/// type itself is backend-neutral — TUI and other backends just no-op.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResizeEdge {
    North,
    South,
    East,
    West,
    NorthEast,
    NorthWest,
    SouthEast,
    SouthWest,
}

/// OS mouse-pointer glyph hint (see [`Backend::set_cursor`]).
///
/// Deliberately named `PointerShape`, not `CursorShape` — that name is
/// already taken by [`crate::primitives::editor::CursorShape`] (the
/// text-editor caret shape, re-exported as `EditorCursorShape`), which is an
/// unrelated concept (text caret vs. OS mouse pointer).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PointerShape {
    /// The platform's normal arrow/default pointer.
    Default,
    /// A directional resize pointer for the given window edge/corner.
    Resize(ResizeEdge),
}

/// Window-state control surface — set/get the title, size, position and
/// tri-state chrome (fullscreen/always-on-top/minimize) of the OS window a
/// backend owns, once a real window exists.
///
/// Reached through [`Backend::window`], which returns `Option<&mut dyn
/// WindowControl>` rather than requiring every backend to implement this
/// trait unconditionally: `None` is the honest, structural answer for a
/// backend with no OS window at all, or for one before its window is
/// constructed.
///
/// Individual methods still return [`ServiceResult<()>`] rather than a bare
/// `bool`/no-op, because `Backend::window` returning `Some` only promises
/// *some* window-control surface is real, not that every method on it is —
/// a given platform may lack a native call for one method and must report
/// [`BackendError::Unsupported`] for just that call rather than faking
/// success or hiding the whole surface.
///
/// Every method defaults to `Err(BackendError::Unsupported)`: a backend that
/// implements `WindowControl` at all overrides only the methods it can
/// genuinely back with a native call.
pub trait WindowControl {
    /// Set the window's title / (GTK) taskbar label / (macOS) titlebar
    /// text / (Win) `WM_SETTEXT` caption.
    ///
    /// TUI's one genuine `WindowControl` capability: `TuiBackend` emits the
    /// OSC 0/2 terminal escape sequence (crossterm's `SetTitle`) to retitle
    /// the terminal emulator's tab/window, the terminal-native equivalent of
    /// a desktop window's title.
    fn set_title(&mut self, _title: &str) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// Resize the window's content area to `width` × `height`, in the
    /// backend's native units (DIPs on GTK/Win/macOS).
    fn set_size(&mut self, _width: f32, _height: f32) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// Floor the window's resizable range at `width` × `height` —
    /// [`Self::set_size`]/[`Self::set_bounds`] cannot shrink it smaller
    /// than this, and neither can the user.
    fn set_min_size(&mut self, _width: f32, _height: f32) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// Cap the window's resizable range at `width` × `height` —
    /// [`Self::set_size`]/[`Self::set_bounds`] cannot grow it larger than
    /// this, and neither can the user.
    fn set_max_size(&mut self, _width: f32, _height: f32) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// The window's current position + size, in the backend's native
    /// units. Position is screen-relative where the platform exposes one
    /// at all — see overriding backends' docs for platforms (GTK4/Wayland)
    /// that structurally cannot report a position and what they return
    /// instead.
    fn bounds(&self) -> ServiceResult<Rect> {
        Err(BackendError::Unsupported)
    }

    /// Move and/or resize the window to `bounds` in one call.
    fn set_bounds(&mut self, _bounds: Rect) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// Center the window on its current monitor.
    fn center(&mut self) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// Enter (`true`) or exit (`false`) fullscreen. Idempotent — calling
    /// with the state the window is already in is not an error.
    fn set_fullscreen(&mut self, _fullscreen: bool) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// Whether the window is currently maximized/zoomed. Read-only and
    /// side-effect-free, so it can be polled from a paint path (e.g. to
    /// pick a maximize/restore glyph) without racing
    /// [`Backend::toggle_window_maximize`], which only reports whether its
    /// flip succeeded, not which state it landed in.
    fn is_maximized(&self) -> ServiceResult<bool> {
        Err(BackendError::Unsupported)
    }

    /// Pin (`true`) or unpin (`false`) the window above all others.
    ///
    /// Not available on GTK4/Wayland: Wayland's window-stacking model has
    /// no client-requestable always-on-top protocol, so `GtkBackend`
    /// reports [`BackendError::Unsupported`] there rather than silently
    /// doing nothing.
    fn set_always_on_top(&mut self, _on_top: bool) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// Show (`true`) or hide (`false`) the window's native chrome
    /// (titlebar + border) without changing its content area. Lets a host
    /// that paints its own titlebar turn the native one off, rather than
    /// showing two titlebars stacked on top of each other.
    fn set_decorated(&mut self, _decorated: bool) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// Minimize (iconify) the window.
    fn minimize(&mut self) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// Restore a minimized window to its prior size/position.
    fn restore(&mut self) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// Hide the window (removes it from the screen and taskbar/dock
    /// without minimizing) — [`Self::show`] is the inverse.
    fn hide(&mut self) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// Show a window previously hidden via [`Self::hide`].
    fn show(&mut self) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// Bring the window to the front and give it keyboard focus.
    fn focus(&mut self) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }
}

/// Tray / status-bar icon control surface — set the icon, tooltip, and
/// right-click menu of an OS notification-area/menu-bar icon, once one
/// exists.
///
/// Reached through [`Backend::tray`], which returns `Option<&mut dyn
/// TrayService>`: the same structural-absence pattern as
/// [`Backend::window`]/[`WindowControl`]. `None` on a backend with no tray
/// facility at all, or before a lazily-created tray icon exists. Every
/// method still returns [`ServiceResult<()>`] rather than a bare `bool`,
/// since a backend can genuinely implement part of this surface (a status
/// item with an icon but no attached menu) without the whole surface being
/// fake.
///
/// Every method defaults to `Err(BackendError::Unsupported)` — a backend
/// that implements `TrayService` at all overrides only the methods it can
/// genuinely back with a native call.
///
/// [`Self::set_icon`] takes an [`ImageSource`], the same source type
/// [`crate::primitives::image::Image`] decodes behind `Backend::draw_image`.
/// [`Self::set_menu`] takes a [`ContextMenu`], the same primitive
/// [`Backend::show_context_menu`] renders natively, so there is one menu
/// vocabulary and one `WidgetId` activation path
/// (`UiEvent::ContextMenuItemActivated`) shared between a right-click
/// context menu and a tray menu.
pub trait TrayService {
    /// Set (or replace) the tray icon's image. The first successful call
    /// is what makes the icon appear at all on backends that create the
    /// underlying OS resource lazily (macOS's `NSStatusItem`, Windows'
    /// `Shell_NotifyIconW` slot) — a host that never calls this never
    /// shows anything in the tray, rather than showing an empty/default
    /// icon.
    fn set_icon(&mut self, _icon: ImageSource) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// Set the icon's hover tooltip text.
    fn set_tooltip(&mut self, _tooltip: &str) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// Attach (or replace) the icon's right-click/click menu. Passing a
    /// menu with no items is not the same as never calling this method —
    /// backends that model "no menu attached" and "menu attached with
    /// zero items" differently should treat an empty
    /// [`ContextMenu::items`] as detaching the menu.
    fn set_menu(&mut self, _menu: &ContextMenu) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }
}

/// Colour fidelity a render target actually supports.
///
/// Unlike every `bool` field on [`BackendCaps`], this is not a "this
/// backend implements method X" promise — it's a runtime-detected (or
/// test-overridden) property of the *output device* a frame paints to.
/// GTK/Win-GUI/macOS are pixel-native, so they always report
/// [`Self::TrueColor`]. TUI is the one backend where this varies: a
/// real terminal may be 24-bit (`COLORTERM=truecolor`/`24bit`), 256-colour
/// (`TERM` containing `256color` — including inside tmux without
/// passthrough, which is the common case that motivated this), or
/// 16-colour ANSI (everything else — the conservative fallback for an
/// unrecognised `TERM`). See `crate::tui::caps::detect_color_depth` for
/// the detection logic and `crate::tui::color` for the SGR-quantisation
/// this value drives.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorDepth {
    /// Palette narrowed to the 16 basic ANSI colours. The safe fallback for
    /// a terminal this backend cannot positively identify as supporting
    /// more. This narrows the *palette*, not the escape-sequence family:
    /// crossterm emits these named colours via the same extended
    /// `38;5;n` / `48;5;n` form as [`Self::Indexed256`] (see
    /// `crate::tui::color::rgb_to_ansi16`), never classic `30-37` /
    /// `90-97` codes.
    Ansi16,
    /// 8-bit / 256-colour indexed (SGR `38;5;n` / `48;5;n`).
    Indexed256,
    /// 24-bit truecolor (SGR `38;2;r;g;b` / `48;2;r;g;b`). The default for
    /// every non-terminal backend.
    TrueColor,
}

impl Default for ColorDepth {
    /// `TrueColor` — the honest value for every pixel-native backend
    /// (GTK/Win/macOS).
    fn default() -> Self {
        Self::TrueColor
    }
}

/// What a backend actually implements, beyond the required trait surface.
///
/// Several `Backend` methods take a no-op (or `false`) default so a new
/// backend compiles before every optional feature is wired up. Each
/// backend's [`Backend::backend_caps`] is the declared, honest answer —
/// "these are the optional surfaces I actually implement" — so the
/// conformance runner can skip a scenario that needs one, with a named
/// reason, instead of either silently passing or spuriously failing.
///
/// A plain bitflag-shaped struct — one `bool` field per capability — rather
/// than the `bitflags` crate: small enough that a dependency buys nothing
/// but the `|` operator. Every field maps to zero or more `Backend` /
/// [`PlatformServices`] methods (documented per field below) that a
/// `BackendCaps` field of `true` promises are overridden away from their
/// no-op default.
///
/// This struct's fields are the *only* capability vocabulary: a scenario's
/// `requires` list matches against exactly these fields, and `BackendReg::caps`
/// is [`Backend::backend_caps`] itself, so there is no second, hand-maintained
/// list to drift out of sync.
///
/// A `true` here is a claim about source, not a hope: `tests/conformance/caps.rs`
/// mechanically checks it for every backend in the tree (including Win/macOS,
/// which have no conformance driver yet) — a declared capability whose
/// methods are still the trait's no-op default fails, and so does an
/// undeclared capability whose methods are overridden. Each field's doc
/// comment below names the methods that check reads; a capability that
/// cannot be checked that way says so explicitly there and in `CAP_CONTRACTS`.
///
/// Construct with [`BackendCaps::empty`] (or `..BackendCaps::empty()` in
/// struct-update syntax) plus the fields a given backend actually
/// implements — see `TuiBackend::backend_caps` / `GtkBackend::backend_caps`
/// for worked examples. `#[non_exhaustive]`-free on purpose: this is
/// in-tree-only (no external `Backend` implementors, `BACKEND.md`), so a new
/// field is a breaking change to every backend impl by design, the same
/// trade-off the `Backend` trait itself makes for a new `draw_*` method.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct BackendCaps {
    /// This backend delivers pointer press/release events
    /// ([`crate::UiEvent::MouseDown`] / [`crate::UiEvent::MouseUp`]) from
    /// its native event source, so click-driven scenarios mean something
    /// on it.
    ///
    /// Not mechanically checkable: the methods that produce these
    /// ([`Backend::poll_events`] / [`Backend::wait_events`]) are
    /// *required*, so every backend "overrides" them — including the Win
    /// stub, whose bodies are `todo!()`. See `CAP_CONTRACTS`.
    pub mouse: bool,
    /// This backend delivers [`crate::UiEvent::Scroll`] from its native
    /// event source (wheel, trackpad, or terminal scroll reporting).
    /// Same non-checkability as [`Self::mouse`].
    pub scroll: bool,
    /// This backend delivers [`crate::UiEvent::MouseMoved`] while a
    /// button is held, so a press → move → release sequence is a real
    /// drag rather than two unrelated clicks. Same non-checkability as
    /// [`Self::mouse`].
    pub drag: bool,
    /// [`Backend::register_text_region`] / [`Backend::cancel_text_selection_drag`]
    /// are overridden — mouse-drag text selection highlighting is real,
    /// not a silently-dropped registration.
    pub text_selection: bool,
    /// [`Backend::install_menu_bar`] and/or [`Backend::show_context_menu`]
    /// are overridden — this backend can paint a native OS menu.
    pub native_menu: bool,
    /// At least one of [`Backend::begin_window_drag`],
    /// [`Backend::toggle_window_maximize`], [`Backend::begin_window_resize`]
    /// is overridden — client-side-decoration window chrome (drag-to-move,
    /// double-click-to-maximize, edge resize) is wired to a real window.
    pub window_chrome: bool,
    /// [`Backend::set_cursor`] is overridden — hinting the OS pointer
    /// glyph actually changes what the user sees, rather than being a
    /// `false`-returning no-op.
    pub pointer_cursor: bool,
    /// This backend positions a native IME composition window (preedit) at
    /// the caret. `false` on every backend today — reserved for a future
    /// `Backend::set_ime_cursor_area` method (see `docs/IME_INPUT_PROPOSAL.md`).
    /// Composed text arrives pre-resolved from the OS regardless, so this
    /// tracks *positioning* the IME candidate window, not whether typing
    /// composed characters works at all.
    pub ime: bool,
    /// [`PlatformServices::show_file_open_dialog`] /
    /// [`PlatformServices::show_file_save_dialog`] show a real native
    /// dialog rather than unconditionally returning `None`. Unlike the
    /// fields above these two `PlatformServices` methods have no no-op
    /// default (the trait requires every backend to implement them), so
    /// this flag distinguishes "returns `None` because the user
    /// cancelled" from "returns `None` because there is no dialog at
    /// all" — the same distinction §5a exists to make visible.
    ///
    /// Not mechanically checkable for the same reason: every backend
    /// implements both methods, so their *presence* proves nothing and
    /// only running a native dialog would tell the two apart. See
    /// `CAP_CONTRACTS`.
    pub file_dialogs: bool,
    /// [`PlatformServices::show_folder_open_dialog`] shows a real native
    /// directory chooser rather than unconditionally returning `None`.
    /// Split out from [`Self::file_dialogs`] rather than
    /// folded into it: a backend can plausibly have one native facility
    /// without the other, and a host reading this flag needs the honest,
    /// narrower answer — "can I open a *directory* chooser", not "does
    /// this backend have *some* file-picker facility".
    ///
    /// Not mechanically checkable for the same reason as
    /// [`Self::file_dialogs`]: every backend implements the method, so its
    /// *presence* proves nothing. See `CAP_CONTRACTS`.
    pub folder_dialogs: bool,
    /// [`PlatformServices::show_message_dialog`] shows a real native
    /// alert/message dialog rather than unconditionally returning
    /// `None`. Same no-default, same `None`-is-ambiguous shape as
    /// [`Self::file_dialogs`] — this flag is the caller's only way to
    /// tell "the user dismissed it" from "this backend has no native
    /// alert facility".
    ///
    /// [`crate::primitives::dialog::native_dialog_options`] is the pure
    /// mapping from a [`Dialog`] descriptor to [`MessageDialogOptions`],
    /// and returns `None` for a dialog carrying a
    /// [`crate::primitives::dialog::DialogTable`] or
    /// [`crate::primitives::dialog::DialogInput`] — no native alert
    /// facility hosts either, so those dialogs stay in-canvas
    /// (`draw_dialog`) even on a backend where this flag is `true`.
    ///
    /// Not mechanically checkable for the same reason as
    /// [`Self::file_dialogs`]: every backend implements the method, so
    /// its *presence* proves nothing. See `CAP_CONTRACTS`.
    pub native_dialogs: bool,
    /// [`PlatformServices::send_notification`] dispatches a real system
    /// notification rather than silently discarding it. Not mechanically
    /// checkable, same as [`Self::file_dialogs`].
    pub notifications: bool,
    /// Both [`Backend::register_font_from_memory`] and
    /// [`Backend::set_nerd_font_fallback`] are overridden — this backend
    /// can register an app-supplied font's raw bytes *and* resolve
    /// Nerd-Font (or other PUA-codepoint) glyphs to a real fallback
    /// family, instead of painting tofu. Requires both methods, not
    /// either: a backend that wires only one half still leaves a gap this
    /// flag must not paper over.
    pub app_font_registration: bool,
    /// [`Backend::window`] is overridden and returns `Some` at least
    /// sometimes — this backend has a real [`WindowControl`] surface
    /// rather than the trait's always-`None` default.
    ///
    /// Doesn't promise every [`WindowControl`] method succeeds — see
    /// that trait's own doc for why individual methods (GTK's
    /// always-on-top, notably) still fail honestly with
    /// [`BackendError::Unsupported`] even on a backend that declares this
    /// `true`.
    pub window_control: bool,
    /// [`Backend::tray`] is overridden and returns `Some` at least
    /// sometimes — this backend has a real [`TrayService`] surface rather
    /// than the trait's always-`None` default.
    ///
    /// Doesn't promise every [`TrayService`] method succeeds, same caveat
    /// as [`Self::window_control`]. TUI declares this `false`
    /// permanently — see [`Backend::tray`]'s doc for why that is a
    /// structural fact, not a gap to close.
    pub tray: bool,
    /// [`Backend::set_editor_font`] and [`Backend::set_ui_font`] are both
    /// overridden — this backend resolves CSS/Pango generic family tokens
    /// (`monospace`, `sans-serif`, `system-ui`; see
    /// [`crate::GenericFamily`]) to a real native font instead of
    /// silently discarding whatever `family`/`font_desc` string a caller
    /// handed it. `false` on TUI permanently — a terminal cell grid has
    /// no font concept to resolve a family token into, the same
    /// structural reason both methods take the trait's no-op default
    /// there (see each method's own doc).
    pub generic_font_families: bool,
    /// This render target's actual colour fidelity — see [`ColorDepth`].
    /// Not part of the bool-capability vocabulary below ([`Self::names`] /
    /// [`Self::has`] / [`Self::vocabulary`] / `ALL_NAMES`): those model
    /// "does this backend implement optional surface X", a static
    /// per-backend fact `tests/conformance/caps.rs` can mechanically
    /// check by asking whether a method was overridden. This field is a
    /// runtime-detected (or test-overridden) property of the terminal
    /// the process happens to be running in, so it has no "overridden
    /// method" to check against and is exempt from that machinery —
    /// see `backend_caps_tests::all_names_lists_every_field_exactly_once`'s
    /// exhaustive destructure below for where it is still forced into
    /// view.
    pub color_depth: ColorDepth,
    /// Whether the kitty keyboard protocol (progressive keyboard
    /// enhancement — unambiguous modifier keys, key-release events) is
    /// actually active on this backend right now.
    ///
    /// Not part of the bool-capability vocabulary below, for the same
    /// reason as [`Self::color_depth`]: a runtime-detected (or
    /// test-overridden) property of the *terminal* a TUI session happens
    /// to be running in, not a static "does this backend implement method
    /// X" fact. `false` on every non-TUI backend (none speak a terminal
    /// protocol). On TUI it is `true` only when [`crate::tui::run`]
    /// actually pushed the protocol's enhancement flags — see
    /// `crate::tui::caps::probe_kitty_keyboard` for how that is decided,
    /// and `crate::tui::backend::TuiBackend::set_kitty_keyboard` for where
    /// the live answer lands here. Check this before relying on a gesture
    /// that needs the protocol (e.g. Ctrl+Enter distinct from Enter) and
    /// fall back to an always-available binding (Alt+Enter) when it's
    /// `false` — see `docs/KITTY_KEYBOARD_PROTOCOL.md`'s degrade table for
    /// which real terminals land on which side.
    pub kitty_keyboard: bool,
    /// Whether SGR-Pixels mouse mode (`?1016h` — pixel-resolution mouse
    /// coordinates instead of whole-cell ones) is actually active on this
    /// backend right now.
    ///
    /// Not part of the bool-capability vocabulary below, for the same
    /// reason as [`Self::kitty_keyboard`]. `false` on every non-TUI
    /// backend. On TUI it is `true` only when both
    /// `crate::tui::caps::probe_sgr_pixel_mouse`'s live DECRQM round trip
    /// answered yes *and* the terminal's real per-cell pixel size could be
    /// determined — see
    /// `crate::tui::backend::TuiBackend::set_sgr_pixel_mouse` for where the
    /// live answer lands here, and
    /// `crate::tui::backend::TuiBackend::cell_pixel_size` for the divisor a
    /// gesture that wants pixel-accurate dragging (a scrollbar or minimap
    /// thumb) needs alongside this flag — the coordinate itself is already
    /// scaled by the time it reaches [`crate::UiEvent::MouseMoved`]/etc.,
    /// but a caller computing its own drag delta in *pixels* rather than
    /// *cells* still needs the cell size to convert back.
    pub sgr_pixel_mouse: bool,
}

/// A capability name paired with the accessor that reads it off a
/// `BackendCaps` value — see [`BackendCaps::ALL_NAMES`].
type NamedCap = (&'static str, fn(&BackendCaps) -> bool);

impl BackendCaps {
    /// No optional capability implemented. The honest starting point for
    /// a new backend — every field defaults to `false` the same way the
    /// `Backend` methods they mirror default to a no-op.
    pub const fn empty() -> Self {
        Self {
            mouse: false,
            scroll: false,
            drag: false,
            text_selection: false,
            native_menu: false,
            window_chrome: false,
            pointer_cursor: false,
            ime: false,
            file_dialogs: false,
            folder_dialogs: false,
            native_dialogs: false,
            notifications: false,
            app_font_registration: false,
            window_control: false,
            tray: false,
            generic_font_families: false,
            color_depth: ColorDepth::TrueColor,
            kitty_keyboard: false,
            sgr_pixel_mouse: false,
        }
    }

    /// Every capability name this instance declares, in field-declaration
    /// order — the vocabulary a conformance scenario's `requires` list
    /// matches capability names against, and what a skip row names as
    /// missing.
    pub fn names(&self) -> Vec<&'static str> {
        Self::ALL_NAMES
            .iter()
            .copied()
            .filter(|(_, get)| get(self))
            .map(|(name, _)| name)
            .collect()
    }

    /// Whether this instance declares `cap` (one of [`Self::vocabulary`]'s
    /// names). Unknown names answer `false` rather than panicking, so a
    /// typo'd `requires` entry reads as "missing", not a crash — the
    /// typo itself is caught separately, and by name, by
    /// `conformance::every_requires_names_a_known_capability`, which
    /// checks each `requires` entry against [`Self::vocabulary`].
    pub fn has(&self, cap: &str) -> bool {
        Self::ALL_NAMES
            .iter()
            .any(|(name, get)| *name == cap && get(self))
    }

    /// Every capability name that exists at all, declared or not, in
    /// field-declaration order.
    ///
    /// This is the closed vocabulary a conformance scenario's `requires`
    /// list may draw from. [`Self::names`] is the subset one backend
    /// answers `true` for; this is the whole alphabet, so a `requires`
    /// entry outside it can be reported as a typo rather than silently
    /// skipping every backend forever.
    pub fn vocabulary() -> Vec<&'static str> {
        Self::ALL_NAMES.iter().map(|(name, _)| *name).collect()
    }

    /// Every capability name paired with the accessor that reads it off a
    /// `BackendCaps` value — the single source of truth [`Self::names`],
    /// [`Self::has`] and [`Self::vocabulary`] all fold over, so the three
    /// can never disagree about the vocabulary.
    const ALL_NAMES: &'static [NamedCap] = &[
        ("mouse", |c| c.mouse),
        ("scroll", |c| c.scroll),
        ("drag", |c| c.drag),
        ("text_selection", |c| c.text_selection),
        ("native_menu", |c| c.native_menu),
        ("window_chrome", |c| c.window_chrome),
        ("pointer_cursor", |c| c.pointer_cursor),
        ("ime", |c| c.ime),
        ("file_dialogs", |c| c.file_dialogs),
        ("folder_dialogs", |c| c.folder_dialogs),
        ("native_dialogs", |c| c.native_dialogs),
        ("notifications", |c| c.notifications),
        ("app_font_registration", |c| c.app_font_registration),
        ("window_control", |c| c.window_control),
        ("tray", |c| c.tray),
        ("generic_font_families", |c| c.generic_font_families),
    ];
}

// Sealed-trait pattern (Rust API Guidelines C-SEALED): `sealed` is
// `pub(crate)`, so `Sealed` is nameable from anywhere in this crate (every
// in-tree backend implements it below) but not from outside it. That is
// the enforcement mechanism behind the stance this module documents on
// `Backend` itself, `docs/PRIMITIVE_RULES.md` rule 7, and `BACKEND.md`:
// four in-tree backends, no external implementors, ever.
pub(crate) mod sealed {
    /// Unnameable outside this crate — see [`super::Backend`]'s "Sealed"
    /// docs.
    pub trait Sealed {}
}

/// A backend-reported failure at a frame, event-loop, or
/// [`PlatformServices`]/[`Clipboard`] seam (design D-009 in
/// `docs/decisions/DECISIONS.md`).
///
/// Not used by `draw_*` methods or the four CSD `bool` methods
/// (`begin_window_drag`, `toggle_window_maximize`, `begin_window_resize`,
/// `set_cursor`) — D-009's "Why not Result-ify `draw_*` / the CSD bools"
/// section explains why both stay exactly as they are. `Clone`, not
/// `std::error::Error`: `context` is a short, ungrepped human string for
/// logs/error UI, not a machine-matched code — backend authors compose it
/// from whatever the native API gave them (`HRESULT`, `GError`, `errno`)
/// with `format!`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BackendError {
    /// This backend has no implementation of the surface being asked
    /// for. Prefer a [`BackendCaps`] field where the gap is a whole
    /// method; reach for this only where the gap is data-dependent
    /// within a method `BackendCaps` already declares supported (e.g. a
    /// `MessageDialogOptions` shape this backend's native dialog API
    /// can't represent, even though `native_dialogs` is `true`).
    Unsupported,
    /// A native call failed for a reason this backend cannot recover
    /// from inside the current call. `context` names the failing
    /// native call/API, e.g. `"IDXGISwapChain::Present"`,
    /// `"GtkFileChooserNative"`, `"CreateNotifyIcon"`.
    PlatformFailure {
        /// The failing native call or API, for logs/error UI — not a
        /// machine-matched code.
        context: String,
    },
    /// The render surface/device was lost mid-frame (D3D
    /// `DXGI_ERROR_DEVICE_REMOVED`/`D2DERR_RECREATE_TARGET`, a destroyed
    /// GTK `GdkSurface`, …) and must be recreated before the next
    /// `begin_frame`. Distinct from `PlatformFailure` because callers
    /// handle it differently — recreate-and-retry, not log-and-continue.
    /// `WinBackend::end_frame` is the one in-tree producer today: it
    /// drops the render target and reports this via `last_error()`, and
    /// `WinBackend::ensure_surface` (called from `win::run`'s
    /// `WM_PAINT`/`WM_SIZE` handlers) recreates it before the next frame
    /// paints.
    SurfaceLost,
}

/// The `Result` type every [`BackendError`]-fallible seam returns —
/// `PlatformServices`/`Clipboard` `_result`-suffixed twin methods (D-009
/// seam 2) and any future one like them.
pub type ServiceResult<T> = Result<T, BackendError>;

/// Bundled font metrics for one call to [`Backend::measure`] — the two
/// numbers ([`Backend::char_width`] and [`Backend::line_height`]) every
/// primitive's `*Measure` type is actually built from. A primitive's
/// `XMeasure::from_metrics(&Metrics)` constructor (see
/// [`crate::TextInputMeasure::from_metrics`] for the pattern) turns it
/// into that primitive's own measure shape without the app touching
/// `char_width` / `line_height` by name.
///
/// `#[non_exhaustive]`: this is in-tree-only today (no external `Backend`
/// implementors construct it — only [`Backend::measure`]'s default body
/// does), but consumers (`coord-tui`, `vimcode`) *do* read the two public
/// fields, so a later field addition should stay source-compatible with
/// field-access call sites instead of becoming a silent breaking change.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Metrics {
    /// Same value [`Backend::char_width`] returns.
    pub char_width: f32,
    /// Same value [`Backend::line_height`] returns.
    pub line_height: f32,
}

/// This backend's platform-native font defaults for the editor and UI
/// (chrome) roles — [`Backend::default_fonts`].
///
/// Exists so a consumer can seed its own font settings from the
/// platform-appropriate convention (`Menlo 12` on macOS, `Consolas 14`
/// on Windows, `monospace 14` on Linux/GTK) without branching on
/// `cfg!(target_os)` in otherwise backend-generic code.
///
/// These are **static, backend-type-level facts** — the value this
/// backend *would* use before any [`Backend::set_editor_font`] /
/// [`Backend::set_ui_font`] call, not this instance's current,
/// possibly-overridden state. Calling `default_fonts()` after a
/// `set_editor_font`/`set_ui_font` call still returns the same
/// platform default it always did; there is no accessor for "what is
/// this backend's font right now" (a consumer that calls
/// `set_editor_font` already knows the value it passed in). A
/// consumer's own setting should be compared against this value to
/// decide whether the *user* has overridden the platform default —
/// "still equal to `default_fonts()`" means "no user override yet,
/// keep tracking platform defaults across a future backend change";
/// anything else means the user chose something and future backend
/// changes must not stomp on it.
///
/// TUI returns an all-sentinel value (empty family strings, `0.0`
/// sizes) — a terminal cell grid has no font concept to default,
/// mirroring the no-op default [`Backend::set_editor_font`] /
/// [`Backend::set_ui_font`] take there. Use [`Backend::line_height`] /
/// [`Backend::char_width`] for TUI's actual fixed-cell metrics
/// instead.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct PlatformFontDefaults {
    /// Platform-native default monospace family for editor content
    /// (e.g. `"Menlo"`, `"Consolas"`, `"Monospace"`). Empty on TUI.
    pub editor_family: String,
    /// Point size paired with [`Self::editor_family`]. `0.0` on TUI.
    pub editor_size_pt: f32,
    /// Platform-native default UI/chrome family (e.g. the resolved
    /// CoreText system font name, `"Segoe UI"`, `"Sans"`). Empty on
    /// TUI.
    pub ui_family: String,
    /// Point size paired with [`Self::ui_family`]. `0.0` on TUI.
    pub ui_size_pt: f32,
}

/// The rects passed to [`Backend::invalidate_rect`] since the last
/// [`Self::clear`].
///
/// Pure bookkeeping — see [`Backend::invalidate_rect`]'s doc for why this
/// log doesn't itself trigger any native repaint. Every backend owns one
/// (via [`crate::backend_core::BackendCore`]) and returns it unchanged from
/// [`Backend::invalidation_log`].
#[derive(Debug, Clone, Default, PartialEq)]
pub struct InvalidationLog {
    rects: Vec<Rect>,
}

impl InvalidationLog {
    /// An empty log.
    pub fn new() -> Self {
        Self::default()
    }

    /// Record a dirty rect.
    pub fn push(&mut self, rect: Rect) {
        self.rects.push(rect);
    }

    /// All recorded rects, oldest first.
    pub fn rects(&self) -> &[Rect] {
        &self.rects
    }

    /// Drop every recorded rect.
    pub fn clear(&mut self) {
        self.rects.clear();
    }

    /// Whether any rect has been recorded since the last [`Self::clear`].
    pub fn is_empty(&self) -> bool {
        self.rects.is_empty()
    }

    /// How many rects have been recorded since the last [`Self::clear`].
    pub fn len(&self) -> usize {
        self.rects.len()
    }
}

/// Framework-level policy for whether a context menu (or, follow-up
/// work permitting, a menu bar) shows as a real OS menu or as an
/// in-window painted popup.
///
/// Set via [`Backend::set_menu_style`] (defaults to `Auto`), resolved
/// per backend via [`Backend::effective_menu_style`] / [`Self::resolve`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum MenuStyle {
    /// Native where the backend can do it ([`BackendCaps::native_menu`]
    /// is `true` — macOS today), painted everywhere else (GTK, Win-GUI,
    /// and always TUI). This is VS Code's own off-macOS default: custom
    /// chrome everywhere except macOS.
    #[default]
    Auto,
    /// Prefer a real OS menu. Falls back to painted on any backend that
    /// doesn't declare [`BackendCaps::native_menu`] — this variant never
    /// results in "nothing shows".
    Native,
    /// Always paint in-window, even on a backend (macOS) that could show
    /// a native menu.
    Custom,
}

/// What [`MenuStyle::resolve`] decided for a given [`BackendCaps`] —
/// the two presentations [`crate::compose::ContextMenuController::open`]
/// actually chooses between.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResolvedMenuStyle {
    /// Show via the backend's real OS menu machinery
    /// ([`Backend::show_context_menu`] on macOS).
    Native,
    /// Paint in-window — [`crate::compose::ContextMenuController`] (or
    /// an app's own state + [`Backend::draw_context_menu`]) owns this
    /// path.
    Custom,
}

impl MenuStyle {
    /// Resolve this style against a backend's declared capabilities.
    ///
    /// Pure and total — every `(MenuStyle, BackendCaps)` pair maps to
    /// exactly one [`ResolvedMenuStyle`], with no "shows nothing" case:
    ///
    /// | style    | `caps.native_menu == true` | `caps.native_menu == false` |
    /// |----------|-----------------------------|------------------------------|
    /// | `Auto`   | `Native`                    | `Custom`                    |
    /// | `Native` | `Native`                    | `Custom` (fallback)         |
    /// | `Custom` | `Custom`                    | `Custom`                    |
    ///
    /// `Auto` and `Native` are deliberately identical here: today's one
    /// `native_menu` backend (macOS) is exactly the case the issue
    /// calls out for `Auto`, so no per-backend special-casing is needed
    /// beyond the capability flag every backend already declares
    /// honestly (`tests/conformance`'s `CAP_CONTRACTS` machinery).
    pub fn resolve(self, caps: &BackendCaps) -> ResolvedMenuStyle {
        match self {
            MenuStyle::Custom => ResolvedMenuStyle::Custom,
            MenuStyle::Auto | MenuStyle::Native => {
                if caps.native_menu {
                    ResolvedMenuStyle::Native
                } else {
                    ResolvedMenuStyle::Custom
                }
            }
        }
    }
}

#[cfg(test)]
mod menu_style_tests {
    use super::{BackendCaps, MenuStyle, ResolvedMenuStyle};

    fn caps(native_menu: bool) -> BackendCaps {
        BackendCaps {
            native_menu,
            ..BackendCaps::empty()
        }
    }

    #[test]
    fn auto_resolves_native_when_caps_declare_native_menu() {
        assert_eq!(
            MenuStyle::Auto.resolve(&caps(true)),
            ResolvedMenuStyle::Native
        );
    }

    #[test]
    fn auto_resolves_custom_when_caps_lack_native_menu() {
        assert_eq!(
            MenuStyle::Auto.resolve(&caps(false)),
            ResolvedMenuStyle::Custom
        );
    }

    #[test]
    fn native_resolves_native_when_caps_declare_native_menu() {
        assert_eq!(
            MenuStyle::Native.resolve(&caps(true)),
            ResolvedMenuStyle::Native
        );
    }

    #[test]
    fn native_falls_back_to_custom_when_caps_lack_native_menu() {
        assert_eq!(
            MenuStyle::Native.resolve(&caps(false)),
            ResolvedMenuStyle::Custom
        );
    }

    #[test]
    fn custom_resolves_custom_when_caps_declare_native_menu() {
        assert_eq!(
            MenuStyle::Custom.resolve(&caps(true)),
            ResolvedMenuStyle::Custom
        );
    }

    #[test]
    fn custom_resolves_custom_when_caps_lack_native_menu() {
        assert_eq!(
            MenuStyle::Custom.resolve(&caps(false)),
            ResolvedMenuStyle::Custom
        );
    }

    #[test]
    fn default_is_auto() {
        assert_eq!(MenuStyle::default(), MenuStyle::Auto);
    }
}

/// One implementation per platform. TUI, GTK, Win-GUI, and (v1.x) macOS.
///
/// # Sealed — no implementations outside this crate
///
/// `Backend` cannot be implemented downstream: it requires the private
/// supertrait [`sealed::Sealed`], which lives in a `pub(crate)` module and
/// so cannot even be *named*, let alone implemented, from another crate.
/// This makes real what `docs/PRIMITIVE_RULES.md` rule 7 already asserts in
/// prose — "adding a required `Backend` method is not a breaking change,
/// because there are no external implementors to break." Concretely: a new
/// primitive adds a new required `draw_<name>` method to this trait, with
/// no default and no version-bump ceremony, and every in-tree backend
/// (TUI, GTK, Win-GUI, macOS) must fill it in or fail to compile — see
/// `docs/BACKEND.md` and the "Adding a primitive is a breaking change to
/// this trait — intentional" note under *Drawing* below.
///
/// If you want quadraui to render onto a target none of the four in-tree
/// backends cover, the supported path is contributing a fifth in-tree
/// backend (`BACKEND.md` walks through the shape; `docs/BACKEND.md`
/// covers the trait's event-loop/hook conventions) — not an out-of-tree
/// `impl Backend`, which sealing rules out entirely. An out-of-tree impl
/// would have no way to keep up with a trait that gains required methods
/// in ordinary, non-major-bump PRs; sealing turns that into a compile
/// error today instead of a silent trap the first time this crate cuts a
/// release.
///
/// ```compile_fail
/// // Rejected: `Backend`'s private supertrait `sealed::Sealed` can't be
/// // named outside this crate, so no out-of-crate type can satisfy it —
/// // this minimal impl fails to compile for that reason (on top of the
/// // missing method bodies, which a real attempt would also have to
/// // supply and which sealing makes irrelevant to write).
/// struct MyBackend;
/// impl quadraui::Backend for MyBackend {}
/// ```
pub trait Backend: sealed::Sealed {
    // ─── Frame + viewport ──────────────────────────────────────────────
    /// Viewport geometry in native units. TUI: cells; GTK/Win-GUI/macOS:
    /// pixel-ish units with `scale` set to the DPI ratio.
    fn viewport(&self) -> Viewport;

    /// Begin a frame. Backends may set up the render target, clear, etc.
    fn begin_frame(&mut self, viewport: Viewport);

    /// Flush the current frame to screen.
    fn end_frame(&mut self);

    // ─── Theming ───────────────────────────────────────────────────────
    /// Set the active [`crate::Theme`] on the backend.
    ///
    /// Apps that use a single theme call this once from `setup()`; apps
    /// that vary the theme per-pane call it at the start of each pane's
    /// render pass (e.g. to darken the background of a detail pane).
    ///
    /// Default: no-op. Backends that carry a `current_theme` field
    /// (TUI, GTK, macOS) override this to store the value so subsequent
    /// `draw_*` calls consume the updated palette.
    fn set_theme(&mut self, _theme: crate::Theme) {}

    /// Read back the backend's currently active [`crate::Theme`] — the
    /// last value passed to [`Self::set_theme`], or the backend's own
    /// default if it was never called.
    ///
    /// Lets shared compose code (e.g. `AppShell::render`) source its
    /// chrome colours from the same palette every `draw_*` call already
    /// paints with, instead of hardcoding literals — without needing a
    /// `Theme` threaded through every call site that only has a
    /// `&dyn Backend` in scope.
    ///
    /// Default: [`crate::Theme::default()`]. Backends that carry a
    /// `current_theme` field (TUI, GTK, macOS, Win) override this to
    /// return it — the same field `set_theme` writes.
    fn theme(&self) -> crate::Theme {
        crate::Theme::default()
    }

    /// Set the active [`crate::Style`] on the backend — the non-colour
    /// geometry tokens [`crate::Theme`] deliberately doesn't carry (see
    /// that type's module doc for why it's a separate struct). Same
    /// call-once-or-per-pane contract as [`Self::set_theme`].
    ///
    /// Default: no-op. Backends that carry a `current_style` field (TUI,
    /// GTK, macOS, Win-GUI) override this to store the value so subsequent
    /// `draw_*` calls consume it — see `Style`'s module doc for each
    /// token's TUI story (no-op, cell-quantised or pre-blended).
    fn set_style(&mut self, _style: crate::Style) {}

    /// Read back the backend's currently active [`crate::Style`] — the
    /// last value passed to [`Self::set_style`], or the backend's own
    /// default if it was never called. Mirrors [`Self::theme`]'s
    /// contract and rationale.
    ///
    /// Default: [`crate::Style::default()`].
    fn style(&self) -> crate::Style {
        crate::Style::default()
    }

    /// Sync the nerd-fonts flag so icon-bearing surfaces (`draw_tree`,
    /// `draw_multi_section_view`, `draw_activity_bar`, etc.) render
    /// `Icon::glyph` when `true` and `Icon::fallback` when `false`.
    ///
    /// `TuiBackend` starts at `false` (fallback): Nerd Font availability in
    /// a terminal is outside the app's control, so the safe default shows
    /// a plain-but-correct glyph rather than risking tofu; hosts that know
    /// or probe for Nerd Font support opt in explicitly. `GtkBackend`,
    /// `MacBackend` and `WinBackend` start at `true`: each bundles and
    /// self-registers the `codicon` font at construction, so glyphs always
    /// paint correctly with no opt-in required.
    ///
    /// The backend does not re-derive this flag on its own each frame —
    /// whatever was last set stays set. If the setting can change at
    /// runtime (a settings toggle, a probe that resolves after the first
    /// frame), call this from `render_content()` every frame rather than
    /// once from `setup()`.
    ///
    /// Default: no-op. Backends that always use one icon form (e.g. a
    /// headless test backend) can accept this default.
    fn set_nerd_fonts(&mut self, _enabled: bool) {}

    /// Whatever was last handed to [`Self::set_nerd_fonts`].
    ///
    /// Hosts need this to resolve a [`crate::ToolbarIcons`] table at the
    /// point of use — `icons.apply(&bar, backend.nerd_fonts_enabled())` —
    /// without having to mirror the flag in their own state. `Toolbar`
    /// icons are plain strings, so the glyph-or-fallback
    /// choice has to be made before the `Toolbar` reaches the backend;
    /// this is how the caller learns which one to bake in.
    ///
    /// Default: `false`, matching `set_nerd_fonts`'s no-op default — a
    /// backend that ignores the setter reports the ASCII form, which is
    /// what it actually paints.
    fn nerd_fonts_enabled(&self) -> bool {
        false
    }

    /// Override the font that paints editor content (family name + size
    /// in points).
    ///
    /// Backends that build a shared per-frame text layout (GTK's Pango
    /// layout) resolve `line_height()` / `char_width()` from this same
    /// font on every frame, so painted glyphs and click-to-column math
    /// (e.g. `editor_col_at_x`) always derive from one source of truth.
    /// `family` should name a monospace font: primitives that map columns
    /// to pixels (`draw_editor`'s `scroll_left * char_width`, etc.) assume
    /// uniform glyph width.
    ///
    /// Call once from `setup()` for a static font, or again any time the
    /// app's font preference changes at runtime (e.g. a zoom-in
    /// keybinding) — the change takes effect on the next repaint.
    ///
    /// Default: no-op. Fixed-cell backends (TUI) have no font concept —
    /// every glyph already occupies exactly one terminal cell.
    fn set_editor_font(&mut self, _family: &str, _size_pt: f32) {}

    /// Override the font that paints **chrome** — status bar, tab bar,
    /// tree, menu bar, dialogs, rich-text popups — as opposed to
    /// [`Self::set_editor_font`], which only affects editor content.
    /// `font_desc` is a Pango-style font description string (e.g.
    /// `"Sans 11"`, `"Cantarell 12"`); unlike the editor font it need not
    /// be monospace, since chrome primitives don't do column math against
    /// it.
    ///
    /// Call once from `setup()` for a static UI font, or again any time
    /// the app's chrome-font preference changes at runtime — the change
    /// takes effect on the next repaint.
    ///
    /// Default: no-op. Fixed-cell backends (TUI) have no font concept —
    /// every glyph already occupies exactly one terminal cell.
    fn set_ui_font(&mut self, _font_desc: &str) {}

    /// This backend's platform-native font defaults for the editor and
    /// UI roles — see [`PlatformFontDefaults`]'s doc for the full
    /// contract.
    ///
    /// No default body: every in-tree backend has a real, distinct
    /// answer (unlike [`Self::set_editor_font`]/[`Self::set_ui_font`],
    /// where a no-op is a legitimate default for a backend with no font
    /// concept at all) — TUI's answer is the explicit sentinel
    /// [`PlatformFontDefaults`] documents, not an inherited no-op.
    fn default_fonts(&self) -> PlatformFontDefaults;

    /// Register an application-supplied font (raw TTF/OTF bytes) with the
    /// platform font manager, kept alive as long as the program runs —
    /// no filesystem write, no user font directory, no `fc-cache`-style
    /// daemon. Lets an app that wants icon glyphs to resolve on
    /// macOS/Win-GUI hand the backend its own font bytes (e.g. an
    /// `include_bytes!`-embedded subset) before [`Self::set_nerd_font_fallback`]
    /// names a family for [`Self::draw_tree`]/[`Self::draw_activity_bar`]/etc.
    /// to resolve glyphs against.
    ///
    /// Returns the family name(s) the font registered under (read back
    /// from the font's own name table), or `None` if `bytes` isn't a font
    /// this backend's platform font manager can parse, or registration
    /// failed.
    ///
    /// Call once from `setup()`, before [`Self::set_nerd_font_fallback`].
    ///
    /// `bytes` does **not** need to outlive this call — any backend whose
    /// platform font manager keeps a raw, uncopied pointer into `bytes`
    /// past the call (Win-GUI's DirectWrite `IDWriteInMemoryFontFileLoader`
    /// does this) is responsible for making its own owned copy and
    /// keeping it alive for the process lifetime, mirroring the macOS
    /// backend's `Arc<Vec<u8>>` copy into `CGDataProvider::from_buffer`.
    ///
    /// Default: no-op, returns `None`. TUI takes this default — a
    /// fixed-cell backend has no font concept at all. GTK overrides it via
    /// `FcConfigAppFontAddFile`, and macOS via Core Text directly — see
    /// `crate::gtk::app_font`'s module doc.
    fn register_font_from_memory(&mut self, _bytes: &[u8]) -> Option<Vec<String>> {
        None
    }

    /// Set the font family consulted for characters the primary
    /// (editor/UI) font cannot cover.
    ///
    /// `family` is looked up first among any fonts this backend
    /// registered via [`Self::register_font_from_memory`], then (for a
    /// backend that supports it) the platform's own installed fonts — so
    /// this also works for a system-installed Nerd Font with no
    /// `register_font_from_memory` call at all.
    ///
    /// Call once from `setup()` for a static fallback, or again any time
    /// the app's font preference changes at runtime.
    ///
    /// Default: no-op. GTK overrides it even though it already has a
    /// working fallback via `crate::gtk::NERD_FONT_FALLBACK_FAMILY`, so
    /// that family is *settable* through this portable entry point on
    /// every backend, including GTK. TUI takes the default for the same
    /// fixed-cell reason [`Self::set_ui_font`] does.
    fn set_nerd_font_fallback(&mut self, _family: &str) {}

    /// Answer whether `family` is already installed on this platform as a
    /// system font. [`Self::register_font_from_memory`] only reports
    /// fonts the *app* bundled and registered itself; this is its
    /// complement, a query against whatever the platform's own font
    /// manager already knows about, with no registration side effect.
    ///
    /// A caller deciding whether to enable Nerd-Font-glyph rendering
    /// should check, in order: an app-bundled
    /// [`Self::register_font_from_memory`] call already succeeded (that
    /// font is guaranteed complete and versioned with the app); else this
    /// method for a system-installed one; else fall back to plain glyphs.
    ///
    /// Returns `Some(true)`/`Some(false)` on a backend that can enumerate
    /// installed font families (GTK via Fontconfig, macOS via Core Text,
    /// Win-GUI via DirectWrite's system font collection). Returns `None`
    /// when the question is unanswerable — today, only TUI, which takes
    /// this default. `None` means "don't know", never "false".
    fn has_font_family(&self, _family: &str) -> Option<bool> {
        None
    }

    // ─── Text selection ────────────────────────────────────────────────
    /// Register a selectable text region for the current frame.
    ///
    /// Call once per selectable content area during render (in paint
    /// order: back regions first, front regions last). The backend
    /// records the region so that click dispatch via
    /// [`crate::dispatch::dispatch_click`] can begin a
    /// [`crate::DragTarget::TextSelection`] drag when the user clicks
    /// inside the bounds.
    ///
    /// The TUI backend additionally applies per-frame selection
    /// highlights (inverted cells over the selected range) and extracts
    /// text on Ctrl-C. GTK/macOS backends can use it for native
    /// selection support. The registration is cleared at the start of
    /// each frame (`begin_frame`), so apps must call this every frame
    /// for regions that should be selectable.
    ///
    /// Default: no-op. Backends that implement selection highlight
    /// override this to accumulate regions for the current frame.
    fn register_text_region(&mut self, _region: crate::dispatch::TextRegion) {}

    /// Record one hit-testable widget zone painted during the current
    /// frame — the `WidgetId`-keyed counterpart to
    /// [`Self::register_text_region`], and the source
    /// [`crate::testing::FrameInventory::zones`] reads from.
    ///
    /// Call once per zone during render (chrome composers like
    /// [`crate::compose::app_shell::AppShell::render`] call this for
    /// each `WidgetId`-bearing region they lay out — activity-bar items,
    /// sidebar panels, the status bar, and so on). The registration is
    /// cleared at the start of each frame by `begin_frame`, mirroring
    /// `register_text_region`'s lifecycle.
    ///
    /// Default: no-op. `TuiBackend`/`GtkBackend` override this to
    /// accumulate the current frame's zones for `ConformanceDriver::inventory`.
    fn register_zone(&mut self, _id: WidgetId, _bounds: Rect) {}

    /// Cancel any in-progress text-selection drag without clearing the
    /// currently displayed selection highlight.
    ///
    /// ## When to call this
    ///
    /// `apply_dispatch` (inside `Backend::wait_events`) speculatively starts
    /// a [`crate::DragTarget::TextSelection`] drag whenever a `MouseDown`
    /// lands on a registered [`crate::dispatch::TextRegion`], *before* the
    /// app's `handle()` is called. Apps that host an embedded terminal with
    /// mouse reporting enabled should call this method after a successful
    /// [`crate::terminal_engine::TerminalSession::forward_mouse`] return
    /// (`true`) so that subsequent `MouseMoved` events do not emit spurious
    /// [`crate::UiEvent::TextSelectionChanged`] events.
    ///
    /// ```ignore
    /// // Inside your AppLogic::handle() / ShellApp::handle():
    /// if in_term_area {
    ///     if sess.forward_mouse(kind, button, col, row, mods) {
    ///         // Cancel the speculative drag the runner started; don't clear
    ///         // any previously finalised selection display.
    ///         backend.cancel_text_selection_drag();
    ///         return Reaction::Redraw;
    ///     }
    /// }
    /// ```
    ///
    /// Default: no-op. The TUI backend cancels the `DragTarget::TextSelection`
    /// drag state without touching the `active_selection` field, preserving
    /// any previously finalised selection highlight on screen.
    fn cancel_text_selection_drag(&mut self) {}

    // ─── Events + keybindings ──────────────────────────────────────────
    /// Drain all queued native events. Returns a fully-translated
    /// `Vec<UiEvent>` ready for app dispatch. Never blocks.
    fn poll_events(&mut self) -> Vec<UiEvent>;

    /// Block for up to `timeout` waiting for at least one event. Returns an
    /// empty `Vec` on timeout. Used by apps that don't want to busy-poll.
    fn wait_events(&mut self, timeout: Duration) -> Vec<UiEvent>;

    /// Return a `Send + Sync` handle a **background thread** can call to
    /// deliver a value to the app and wake this backend's event loop so the
    /// value is observed promptly.
    ///
    /// Every other `Backend` method requires `&mut self` or `&self` on the
    /// thread that owns the event loop; this is the one exception,
    /// deliberately shaped for a thread that has neither. Call the
    /// returned closure with a [`UserPayload`] from any thread (including
    /// the owning one) at any time, including before the event loop has
    /// started or after the app has exited (a call after exit is simply
    /// dropped — there is no receiver left to observe it):
    ///
    /// ```ignore
    /// let waker = backend.waker();
    /// std::thread::spawn(move || {
    ///     let result = do_expensive_work();
    ///     waker(UserPayload::new(result));
    /// });
    /// ```
    ///
    /// The backend wakes its event loop and delivers the payload as
    /// [`UiEvent::User`] to [`crate::runner::AppLogic::handle`] — see that
    /// variant's doc for the full contract.
    ///
    /// GTK/macOS/Windows implementations use their native thread-safe "run
    /// this on the UI thread" primitive (`glib::MainContext::invoke`,
    /// `dispatch2::DispatchQueue::main`, `PostMessageW`, respectively) to
    /// force a prompt wake from off-thread. TUI feeds the payload into the
    /// queue its bounded poll already drains, backed by a coarse idle-poll
    /// fallback ceiling every backend keeps (`crate::runtime::IDLE_POLL_CEILING`)
    /// as a safety net — see [`crate::runner::AppLogic::tick`]'s
    /// per-backend cadence table for the current state of all four.
    ///
    /// Implementations must be safe to call from any thread, at any time,
    /// any number of times, including concurrently with each other and
    /// with the owning thread's own use of `self` — that's the entire
    /// point of handing out a `Send + Sync` closure instead of a method on
    /// `&self`/`&mut self`. Backends satisfy this by never touching their
    /// own `!Send` event queue (`Rc<RefCell<VecDeque<UiEvent>>>` on GTK/
    /// macOS/Windows) directly from the returned closure; they stage into
    /// a `Send + Sync` inbox instead ([`crate::runtime::UserEventQueue`])
    /// and drain that inbox back on the owning thread, the same place they
    /// already drain their native event source.
    fn waker(&self) -> Arc<dyn Fn(UserPayload) + Send + Sync>;

    /// Arm a scheduled wake: after `delay`, make sure the event loop wakes
    /// up and [`crate::runner::AppLogic::tick`] (or the app's `handle`
    /// dispatch, for whichever native event the wake rides in on) runs
    /// again.
    ///
    /// This is [`Self::waker`]'s sibling for app-driven scheduling rather
    /// than a background thread: "the app itself knows it wants to be
    /// woken again in `delay`, without resorting to a fixed poll cadence
    /// to eventually notice" — a spinner's next frame, a caret blink
    /// toggle, a countdown tick.
    ///
    /// Called by the runner from [`crate::runner::Reaction::RedrawAfter`]
    /// (via [`crate::runner::AppLogic::tick`]/`handle`'s return value) —
    /// apps normally reach this indirectly by returning that `Reaction`
    /// rather than calling it directly, but nothing stops a direct call
    /// (e.g. from [`crate::runner::AppLogic::setup`], which has no
    /// `Reaction` return value of its own, to bootstrap a self-rearming
    /// animation chain before the first native event arrives).
    ///
    /// Per the doc on [`crate::runner::Reaction::RedrawAfter`]: the
    /// backend may wake earlier than `delay` for unrelated reasons (a
    /// native event, a `waker` call, another still-pending request) but
    /// never later, and is not required to cancel or coalesce overlapping
    /// requests — calling this every tick while the app has ongoing
    /// time-driven state (the chained-rearm pattern) is the intended
    /// usage, not redundant.
    ///
    /// # Per-backend mechanism
    ///
    /// "A scheduled frame and a thread wake are the same mechanism on
    /// most backends" (the issue's framing): GTK/macOS/Windows implement
    /// this with a real native one-shot timer
    /// (`glib::timeout_add_local_once` / `dispatch_after` / `SetTimer`)
    /// whose fire callback invokes the *same* wake path [`Self::waker`]
    /// posts to from a background thread. TUI is the exception — it has
    /// no native run loop to arm a timer against (its "event loop" is
    /// just [`Self::wait_events`] called in a `loop {}`), so its
    /// implementation records the deadline and folds it into the next
    /// `wait_events` call's timeout instead; see
    /// `crate::runtime::FrameScheduler`.
    ///
    /// This one-shot timer is independent of, and doesn't replace, the
    /// separate always-repeating idle-poll fallback every backend keeps
    /// (`crate::runtime::IDLE_POLL_CEILING` — see
    /// [`crate::runner::AppLogic::tick`]'s per-backend cadence table):
    /// this method exists for an app that knows the *exact* interval it
    /// wants to be woken after, the fallback for an app that doesn't ask
    /// at all.
    ///
    /// `WinBackend`'s implementation clamps `delay` to `u32::MAX`
    /// milliseconds (~49.7 days) — `SetTimer`'s elapse parameter is a
    /// 32-bit millisecond count — rather than erroring on a longer
    /// request; no caller asks for anything close to that today.
    fn request_frame_in(&self, delay: Duration);

    /// Ask the backend to paint the *next* frame as if the physical
    /// display were blank, discarding whatever incremental-diff cache it
    /// keeps against the real screen.
    ///
    /// This exists for exactly one situation: the backend's own idea of
    /// "what's on screen" has drifted from what's actually there, through
    /// no fault of the app's rendered state (which is already correct —
    /// a plain [`Reaction::Redraw`][crate::runner::Reaction::Redraw] would
    /// change nothing, because the diff against the *stale* cache still
    /// concludes those cells don't need repainting). On TUI, that drift
    /// is `ratatui::Terminal`'s `Buffer` vs. the real terminal: a PTY
    /// pane writing directly to the shared terminal, a resize escape
    /// sequence the terminal applies before ratatui's own resize
    /// handling catches up, or a dismissed popup can each leave stale
    /// glyphs in cells ratatui's diff believes are already correct and
    /// therefore skips. `TuiBackend::request_full_repaint` itself only
    /// latches a flag (read back via `take_full_repaint_requested`); the
    /// actual `ratatui::Terminal::clear()` call — exactly what
    /// `Terminal::clear()` gives a raw (non-runner) ratatui app — lives in
    /// each render-path caller that consumes that flag before its next
    /// `terminal.draw(...)`: `tui::run::run_inner`'s frame loop for the
    /// live runner, `crate::tui::testing::TuiDriver::render` for the
    /// headless `TestBackend` driver, and `crate::tui::vt_testing::TuiVtDriver::render`
    /// for the headless vt100 driver (so a driver test can assert this
    /// was requested without a real terminal to observe the clear on).
    ///
    /// Default: no-op. GTK's `DrawingArea` repaints in full every frame
    /// via Cairo — there is no incremental diff to desync in the first
    /// place, so `GtkBackend` doesn't override this. A future diff-based
    /// renderer (a terminal-multiplexer-aware Win-GUI console mode, say)
    /// gets the same hook for free by overriding this method instead of
    /// needing a new one.
    ///
    /// Idempotent and cheap to call more than once before the next frame
    /// — a second call while one is already pending changes nothing, the
    /// same "may act as if called once" contract
    /// [`Self::request_frame_in`] documents for overlapping requests.
    fn request_full_repaint(&mut self) {}

    /// Record that `rect` needs repainting, for a future partial-repaint
    /// path to consume.
    ///
    /// This is a **bookkeeping hook, not a native repaint call** — calling
    /// it does not itself invalidate anything on screen. It only appends
    /// `rect` to the backend's [`InvalidationLog`] (read back via
    /// [`Self::invalidation_log`]), the same "latch now, act later" shape
    /// [`Self::request_full_repaint`] already uses for its flag: the actual
    /// native partial-repaint call (GTK's `queue_draw_area` — removed in
    /// GTK4, so GTK can only ever invalidate the whole viewport; AppKit's
    /// `setNeedsDisplay(_:in:)`; Win32's `InvalidateRect(hwnd, Some(&rect),
    /// …)`) is follow-on work for whichever render-path caller decides to
    /// wire it up, not this seam. Chrome-motion callers (see
    /// [`crate::transition::Transition`]) call this once per frame with the
    /// animating widget's dirty rect so that future caller can exist without
    /// another `Backend` method.
    ///
    /// Every backend implements this as a one-line delegation to
    /// [`crate::backend_core::BackendCore::record_invalidation`] — there is
    /// no useful no-op default, since the whole point is that the rect ends
    /// up in the log every backend shares.
    fn invalidate_rect(&mut self, rect: Rect);

    /// The log of rects passed to [`Self::invalidate_rect`] since the last
    /// [`InvalidationLog::clear`].
    ///
    /// Exists so tests (and, eventually, a partial-repaint render path) can
    /// observe what chrome motion asked to have redrawn without the backend
    /// needing to expose any native handle.
    fn invalidation_log(&self) -> &InvalidationLog;

    /// Register an accelerator. The backend stores it and emits
    /// [`UiEvent::Accelerator`] when the native key event matches.
    fn register_accelerator(&mut self, acc: &Accelerator);

    /// Remove a previously-registered accelerator.
    fn unregister_accelerator(&mut self, id: &AcceleratorId);

    // ─── Native menu installation ──────────────────────────────────────
    /// Install `bar` as the platform's native menu bar.
    ///
    /// macOS (`MacBackend`) walks `bar.items` → `NSMenu` / `NSMenuItem`
    /// hierarchy and assigns to `NSApp.mainMenu`. A standard app menu
    /// (Hide / Quit etc.) is auto-prepended. Activations arrive on the
    /// event queue as [`UiEvent::MenuActivated`].
    ///
    /// TUI / GTK / Win-GUI: no-op default. Apps that want an in-window
    /// menu keep calling `draw_menu_bar` from their render path; `WinBackend`
    /// and `GtkBackend` both use the same drawn-menu-row + `draw_menu_bar`
    /// approach, since a native menu bar would conflict with their custom
    /// window chrome.
    ///
    /// Apps typically call this once during `AppLogic::setup`. Re-calling
    /// replaces the previously-installed menu wholesale.
    fn install_menu_bar(&mut self, _bar: &crate::primitives::menu_bar::MenuBar) {}

    /// Show `menu` as a native right-click context menu at `anchor`
    /// (view-local coordinates).
    ///
    /// macOS (`MacBackend`) builds an `NSMenu` from `menu.items` and
    /// runs `popUpMenuPositioningItem_atLocation_inView` — AppKit takes
    /// over with a modal event loop until the user picks an item or
    /// dismisses. Activation pushes
    /// [`UiEvent::ContextMenuItemActivated`]; dismissal pushes
    /// [`UiEvent::ContextMenuDismissed`].
    ///
    /// TUI / GTK / Win-GUI: no-op default. Apps that want a painted
    /// right-click menu on those backends continue to manage their
    /// own `ContextMenu` state and call `draw_context_menu` from
    /// their render path — or let
    /// [`crate::compose::ContextMenuController`] own that state for
    /// them (it calls this method for the `Native` half of the
    /// resolved style and manages painting/hit-testing itself for the
    /// `Custom` half).
    ///
    /// This is the **low-level, always-native** building block — kept
    /// working unchanged for apps that want to call it directly and
    /// accept "no-op off macOS". [`crate::compose::ContextMenuController::open`]
    /// is the **style-aware, one-call** entry point new code should
    /// prefer: it calls this method itself on the `Native` path and
    /// owns the painted state `Custom` needs on every other backend.
    ///
    /// Apps typically invoke this from a `MouseDown { button: Right }`
    /// handler.
    fn show_context_menu(
        &mut self,
        _menu: &crate::primitives::context_menu::ContextMenu,
        _anchor: crate::event::Point,
    ) {
    }

    // ─── MenuStyle ───────────────────────────────────────────────────────
    /// This backend's current [`MenuStyle`] setting. Defaults to
    /// [`MenuStyle::Auto`] on every backend. Set via
    /// [`Self::set_menu_style`]; resolve to an actual presentation via
    /// [`Self::effective_menu_style`].
    ///
    /// The trait default returns `MenuStyle::Auto` unconditionally —
    /// every real backend (`TuiBackend`/`GtkBackend`/`MacBackend`/
    /// `WinBackend`) overrides this alongside [`Self::set_menu_style`]
    /// to actually persist the value (both delegate to
    /// [`crate::backend_core::BackendCore`]). A test double that
    /// doesn't override either method behaves as if the style were
    /// permanently `Auto` — consistent, not silently broken, since
    /// `Auto` is also the crate-wide default.
    fn menu_style(&self) -> MenuStyle {
        MenuStyle::Auto
    }

    /// Change this backend's [`MenuStyle`] at runtime. See
    /// [`Self::menu_style`] for the default-no-op-without-override
    /// caveat on test doubles.
    fn set_menu_style(&mut self, _style: MenuStyle) {}

    /// [`Self::menu_style`] resolved against this backend's declared
    /// [`BackendCaps`] via [`MenuStyle::resolve`] — what
    /// [`crate::compose::ContextMenuController::open`] uses to decide
    /// native vs. painted. Exposed so apps and tests can check the live
    /// decision (e.g. to render "menu: native" in a status bar) without
    /// duplicating the resolution rule.
    ///
    /// Generic over every backend for free: built purely from
    /// [`Self::menu_style`] + [`Self::backend_caps`], both of which
    /// every backend already has to supply. No backend needs to
    /// override this.
    ///
    /// # Why the "one call" entry point lives on
    /// [`crate::compose::ContextMenuController`], not here
    ///
    /// A `Backend`-trait default method has nowhere to keep "a menu is
    /// currently open, painted, and hit-testable" state — that's a
    /// per-call-site concern, and every [`MenuStyle`] must never show
    /// nothing, including on the painted `Custom` path. So this trait
    /// intentionally does **not** grow an `open_context_menu` method;
    /// [`crate::compose::ContextMenuController::open`] is the real
    /// one-call entry point — it owns the state `Custom` needs, calls
    /// [`Self::show_context_menu`] itself for `Native`, and its
    /// `handle`/`render` cover both paths uniformly.
    fn effective_menu_style(&self) -> ResolvedMenuStyle {
        self.menu_style().resolve(&self.backend_caps())
    }

    // ─── Window chrome (CSD) ────────────────────────────────────────────
    /// Begin an OS-native window drag-to-move gesture, using the raw
    /// device/button/timestamp captured from the most recent primary-button
    /// press.
    ///
    /// For apps that draw their own client-side titlebar (`ShellConfig::
    /// with_title_bar` + `window.set_decorated(false)`) into
    /// `AppShellLayout::title_bar_bounds` and want the empty part of that
    /// band to drag the window like a native titlebar. Call from
    /// [`crate::shell::ShellApp::handle`] when a `MouseDown` lands in
    /// [`crate::shell::ShellContext::in_title_bar`] outside any interactive
    /// segment (menu item, min/max/close button).
    ///
    /// `GtkBackend` arms a deferred `gdk4::Toplevel::begin_move` call, using
    /// the press context `gtk::run`'s click controller stashes just before
    /// the press is translated to a portable [`UiEvent`] — GDK
    /// requires the *originating* event's device/timestamp, not synthesized
    /// values, or the drag silently no-ops on some compositors. The actual
    /// `begin_move` call only fires once the pointer moves past the drag
    /// threshold (mirroring native `gtk4::WindowHandle`'s `GestureDrag`
    /// `drag-begin` gating); calling this from a `MouseDown` handler does
    /// not itself start an interactive move grab, so a press that turns out
    /// to be the first half of a double-click still reaches the app as
    /// `UiEvent::DoubleClick`.
    ///
    /// Returns `false` when the backend owns no window (TUI, and any
    /// backend before its window is constructed) or no primed press context
    /// is available. Callers should treat `false` as a no-op, not an error.
    /// A `true` return means the drag request was accepted/armed, not that
    /// the window has necessarily started moving yet.
    fn begin_window_drag(&mut self) -> bool {
        false
    }

    /// Toggle the OS window between maximized and restored — the
    /// double-click-to-maximize half of the CSD-titlebar gesture pair
    /// (see [`Self::begin_window_drag`]).
    ///
    /// Call from `ShellApp::handle` on a `DoubleClick` landing in the empty
    /// part of the titlebar band. Returns `false` on backends with no
    /// window (TUI); `true` once the toggle happened.
    fn toggle_window_maximize(&mut self) -> bool {
        false
    }

    /// Begin an OS-native window resize gesture from the given edge, using
    /// the raw device/button/timestamp captured from the most recent
    /// primary-button press (same mechanism as [`Self::begin_window_drag`]).
    ///
    /// For apps that draw their own client-side titlebar and want to offer
    /// edge/corner resize the way native `gtk4::WindowHandle` /
    /// `GDK_SURFACE_EDGE_*` decorations do for free. Apps are expected to
    /// hit-test the pointer against their own window bounds each frame
    /// (see [`crate::shell::ShellContext::window_edge`]) and call this from
    /// a `MouseDown` handler when the press lands within resize-margin
    /// distance of an edge.
    ///
    /// Unlike [`Self::begin_window_drag`], this does not need to defer past
    /// a movement threshold: there is no competing "double-click on an edge
    /// means something else" gesture to protect (double-click-to-maximize
    /// only applies to the empty titlebar band), so `GtkBackend` calls
    /// `gdk4::Toplevel::begin_resize` directly from the stashed press
    /// context.
    ///
    /// Returns `false` when the backend owns no window (TUI, and any
    /// backend before its window is constructed) or no primed press context
    /// is available. Callers should treat `false` as a no-op, not an error.
    fn begin_window_resize(&mut self, _edge: ResizeEdge) -> bool {
        false
    }

    /// Hint the OS mouse-pointer glyph, e.g. to show a resize cursor while
    /// hovering a window edge (see [`Self::begin_window_resize`]).
    ///
    /// Call from `ShellApp::handle` on every `UiEvent::MouseMoved`, passing
    /// [`PointerShape::Resize`] when [`crate::shell::ShellContext::window_edge`]
    /// returns `Some`, else [`PointerShape::Default`] to restore the normal
    /// pointer. Returns `false` on backends with no native pointer concept
    /// (TUI) or no window yet; `true` once the pointer glyph was applied.
    fn set_cursor(&mut self, _shape: PointerShape) -> bool {
        false
    }

    /// Inset at the leading edge of the title-bar band
    /// ([`crate::compose::app_shell::AppShellLayout::title_bar_bounds`])
    /// occupied by backend-drawn window controls, in the same native
    /// units every other `Rect` this trait returns uses. `Rect::default()`
    /// means the backend puts nothing of its own into that band, so the
    /// app may paint the whole width of `title_bar_bounds`. That is the
    /// answer on TUI (no window concept at all), and on GTK/Win-GUI,
    /// which don't honour
    /// [`crate::shell::ShellConfig::client_side_titlebar`] yet and so
    /// always keep their window controls in native chrome *outside* the
    /// app's content area (see `ACCEPTED_DEFAULTS` in
    /// `tests/conformance/caps.rs` — when either grows client-side
    /// decorations it has to override this and delete its entry).
    ///
    /// macOS is the one case where a non-empty inset does **not** imply
    /// the app must paint its own controls — quite the opposite: a
    /// non-empty return there means AppKit's native traffic lights
    /// (close/minimize/zoom) are floating over that region and the app
    /// must paint nothing underneath, not that it owns drawing them (see
    /// [`crate::shell::ShellConfig::client_side_titlebar`]'s doc for why
    /// macOS keeps them native rather than app-drawn).
    ///
    /// Defaulted, not required (`PRIMITIVE_RULES.md` rule 7): unlike
    /// [`Self::draw_focus_ring`], a backend that doesn't override this
    /// yet is indistinguishable from one that correctly draws no window
    /// controls, so there is no portability hazard in leaving it
    /// no-op — only a backend that actually reserves native chrome space
    /// (macOS) needs to override it.
    fn titlebar_control_inset(&self) -> Rect {
        Rect::default()
    }

    // ─── Window control ──────────────────────────────────────────────────
    /// This backend's window-state control surface, or `None` when this
    /// backend has no OS window to control right now.
    ///
    /// `None` is the *structural* absence: TUI (no OS window concept at
    /// all, though see [`WindowControl::set_title`] for the one thing it
    /// genuinely can do) and any windowed backend before its window is
    /// constructed both answer `None` here, and a caller that only ever
    /// sees `Option` cannot forget to check it the way a
    /// silently-false-returning capability flag can be forgotten. See
    /// [`WindowControl`]'s own doc for why individual methods on the
    /// returned trait object still report [`ServiceResult`] rather than
    /// being infallible once `Some` is reached.
    ///
    /// `&mut self`, not `&self`: every [`WindowControl`] method mutates
    /// OS window state, so the borrow this returns has to allow that.
    ///
    /// Default: `None` — a backend that hasn't wired a `WindowControl`
    /// impl yet is indistinguishable from one that genuinely has no
    /// window, which is the honest answer either way.
    fn window(&mut self) -> Option<&mut dyn WindowControl> {
        None
    }

    // ─── Tray / status-bar icon ─────────────────────────────────────────
    /// This backend's tray/status-bar icon control surface, or `None`
    /// when this backend has no way to show one right now.
    ///
    /// `None` is the *structural* absence [`Self::window`] already
    /// established for [`WindowControl`]: a backend that hasn't wired a
    /// [`TrayService`] impl yet is indistinguishable from one with no
    /// tray facility at all, which is the honest default before a given
    /// backend's implementation lands.
    ///
    /// **TUI is genuinely, permanently `None` here** — not merely
    /// "not implemented yet" the way [`WindowControl::set_title`] still
    /// found one real capability (`OSC 0/2`) for a backend with no OS
    /// window at all. A terminal has no notification-area/menu-bar
    /// concept whatsoever, so there is no terminal-native analogue this
    /// method could ever back with a real call — unlike `window()`,
    /// which TUI overrides to return `Some` for its one genuine
    /// capability, `tray()` stays at this trait's default on `TuiBackend`
    /// forever. This is exactly why the compose layer's `hide_to_tray`
    /// helper (a host convenience that hides the window and relies on
    /// the tray icon being the only way back) must refuse to run when
    /// `tray()` is `None`: on TUI, hiding "to the tray" would simply
    /// make the app vanish with no way back.
    ///
    /// `&mut self`, not `&self` — same reasoning as [`Self::window`]:
    /// every [`TrayService`] method mutates OS tray state.
    ///
    /// Default: `None`.
    fn tray(&mut self) -> Option<&mut dyn TrayService> {
        None
    }

    // ─── Modal-overlay tracking ────────────────────────────────────────
    /// Shared handle to the backend's modal stack, usable across
    /// unrelated `&mut dyn Backend` (or `&dyn Backend`) borrows. Apps
    /// push when a palette / dialog / context-menu opens and pop when
    /// it closes; quadraui's dispatcher consults the stack so events
    /// inside an open modal can't fall through to widgets behind it.
    ///
    /// This is a shared `Rc<RefCell<ModalStack>>` rather than a plain
    /// `&mut ModalStack`, because the latter ties its lifetime to the
    /// borrow that produced it and so cannot be stashed and used again
    /// later from an unrelated borrow scope — exactly the
    /// stash-then-reuse pattern GTK hosts (and quadraui's own
    /// `gtk::run`) depend on:
    ///
    /// ```ignore
    /// let stack_rc = backend.modal_stack_handle(); // stash, drop the borrow
    /// // ... other code, other borrows of `backend` in between ...
    /// stack_rc.borrow_mut().push(...);             // use it later
    /// ```
    ///
    /// Every in-tree backend implements this by owning its modal stack
    /// behind `Rc<RefCell<ModalStack>>` and cloning the `Rc` here — see
    /// `GtkBackend::modal_stack_handle` for the pattern this trait method
    /// generalises. No default: a host holding only `&mut dyn Backend`
    /// needs this to work identically on every backend, so a backend
    /// that forgets to wire it up should fail to compile rather than
    /// silently hand back a handle to a stack nobody else observes.
    ///
    /// Reentrant mutation goes through `RefCell`'s normal runtime borrow
    /// check: a stale `borrow_mut()` still alive when another call tries
    /// to borrow again panics loudly.
    ///
    /// See [`ModalStack`] and [`crate::dispatch::dispatch_mouse_down`]
    /// for the routing contract.
    fn modal_stack_handle(&self) -> Rc<RefCell<ModalStack>>;

    /// Shared handle to the drag state, with the same stash-then-reuse
    /// contract as [`Self::modal_stack_handle`]. See that method's docs
    /// for the pattern and rationale.
    fn drag_state_handle(&self) -> Rc<RefCell<DragState>>;

    // ─── Focus ───────────────────────────────────────────────────────────
    /// Read-only access to this backend's [`FocusManager`] — the single
    /// owner of "what widget currently has keyboard focus". See
    /// [`crate::focus`]'s module doc for the full design and the six
    /// ad-hoc representations it replaces.
    ///
    /// Deliberately `&FocusManager`, not `&mut`: the only code that
    /// mutates it is the shared Tab/Shift+Tab intercept in
    /// [`crate::runtime::preprocess_event`], reached through the
    /// crate-private `PreprocessBackend::focus_manager_mut` — apps read
    /// the current focus here, they don't set it directly. No default:
    /// every backend owns exactly one `FocusManager`, constructed
    /// alongside its other per-frame state.
    fn focus_manager(&self) -> &FocusManager;

    /// Paint the focus-ring convention around `rect` — a themed,
    /// border-only stroke (`Theme::accent_fg`) with no fill, so the
    /// focused widget's own content keeps showing through underneath.
    /// Called by the runner once per frame, immediately after
    /// `AppLogic::render`, whenever [`Self::focus_manager`]`().focused()`
    /// names a widget this frame's tab stops resolve a rect for — apps
    /// never call this directly.
    ///
    /// No default impl — every backend implementer sees this as a
    /// compile error and fills in a real rasteriser
    /// (`docs/decisions/BACKEND_TRAIT_PROPOSAL.md` §4, `PRIMITIVE_RULES.md` rule 7).
    /// Do not add a no-op default here; see
    /// `docs/SMELL_AUDIT_2026-07.md` PORT-01 for why that pattern is a
    /// portability risk, not a precedent to follow.
    fn draw_focus_ring(&mut self, rect: Rect);

    // ─── Error reporting (D-009) ─────────────────────────────────────────
    /// The most recent [`BackendError`] this backend recorded, if any,
    /// since the last time this method was called.
    ///
    /// One polled method, not a `Result`-returning `begin_frame`/
    /// `end_frame`/`poll_events`/`wait_events` each: those four calls
    /// funnel into the same internal field, because a caller that wants
    /// to notice backend trouble at all polls once per loop iteration
    /// (after `end_frame`, conventionally) and doesn't need to know which
    /// of the four calls produced it — `PlatformFailure`'s `context`
    /// string carries that detail when it matters. See D-009 in
    /// `docs/decisions/DECISIONS.md` for why a `Result`-returning
    /// signature on those four methods was rejected as too costly for
    /// every caller, for a failure class only Win-GUI produces today.
    ///
    /// Default: always `None` — a backend that never sets an internal
    /// error field (TUI, GTK, macOS today) answers this exactly like it
    /// doesn't exist, at zero cost to existing callers. `WinBackend`
    /// overrides this: it sets an internal field from `end_frame` when
    /// `EndDraw` fails (device lost / `D2DERR_RECREATE_TARGET`) and
    /// clears it here — clear-on-read, matching every other "drain and
    /// reset" method already on this trait (`poll_events` itself).
    fn last_error(&mut self) -> Option<BackendError> {
        None
    }

    // ─── Platform services ─────────────────────────────────────────────
    /// Clipboard, file dialogs, notifications, URL opening, platform name.
    fn services(&self) -> &dyn PlatformServices;

    // ─── Paint surface ──────────────────────────────────────────────────
    /// This backend's [`crate::PaintSurface`] — the ~15-verb drawing
    /// primitive seam every `primitives::*::native_surface_paint` helper
    /// paints through — or `None` on a backend with no pixel canvas to
    /// offer one against.
    ///
    /// Mirrors [`Self::window`] and [`Self::services`]'s shape exactly:
    /// `Option`, not a required method, because `None` here is a
    /// *structural* absence, not a missing override — see
    /// [`crate::PaintSurface`]'s module doc, "Why TUI stays out", for why
    /// [`crate::tui::backend::TuiBackend`] can never meaningfully answer
    /// `Some` (a cell grid has no sub-cell `Rect` to paint into). A
    /// caller that only ever sees `Option` cannot forget to check it the
    /// way a silently-false-returning capability flag can be forgotten.
    ///
    /// `&mut self`, not `&self`: every [`crate::PaintSurface`] method
    /// mutates the render target — matches [`Self::window`]'s identical
    /// reasoning for `WindowControl`.
    ///
    /// Default: `None`. [`crate::gtk::backend::GtkBackend`],
    /// [`crate::macos::backend::MacBackend`] and
    /// [`crate::win::backend::WinBackend`] each override this to return
    /// `Some(self)`, since each already implements [`crate::PaintSurface`]
    /// directly on its own backend struct (see that trait's `impl` block
    /// in each backend module).
    fn paint_surface(&mut self) -> Option<&mut dyn crate::PaintSurface> {
        None
    }

    // ─── Capability declaration ─────────────────────────────────────────
    /// This backend's declared [`BackendCaps`] — which optional surfaces
    /// it actually implements, versus which ones are still sitting on the
    /// trait's no-op default.
    ///
    /// No default impl: every backend states its own caps explicitly
    /// (`Backend` has no external implementors — `BACKEND.md` — so there
    /// is no "safe" default to fall back to; `BackendCaps::empty()` would
    /// silently under-report a backend that forgot to update this after
    /// overriding a new optional method, exactly the honesty gap this
    /// method exists to close). See `TuiBackend::backend_caps` /
    /// `GtkBackend::backend_caps` for how a real backend derives this
    /// from what it actually overrides.
    fn backend_caps(&self) -> BackendCaps;

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

    /// Height of one standard text row in the backend's native units.
    /// TUI: `1.0` (one terminal cell). GTK: Pango-resolved line height
    /// in pixels (~14–20 depending on font). Win-GUI (future):
    /// DirectWrite line height in DIPs.
    ///
    /// Apps that need portable rect sizing use this instead of
    /// hardcoded constants. Example: `let status_h = backend.line_height() * 1.5;`
    /// gives 1.5 cells on TUI, ~24px on GTK, proportional DIPs on
    /// Win-GUI — all from the same code path.
    fn line_height(&self) -> f32;

    /// Approximate monospace character width in surface-native units.
    /// TUI returns `1.0` (one cell); GTK returns the Pango
    /// `approximate_char_width` in DIPs.
    ///
    /// Apps use this alongside [`Self::line_height`] for portable
    /// horizontal layout. Example:
    /// `let viewport_cols = ((rect.width - gutter) / backend.char_width()).floor();`
    fn char_width(&self) -> f32;

    /// Line height of the chrome / UI font, in surface-native units.
    ///
    /// Chrome elements — tab strips, breadcrumb bars, status bars —
    /// are sized and painted against the system UI font, whose metrics
    /// can differ from the editor (monospace) font that
    /// [`Self::line_height`] reports.  Backends that maintain a
    /// separate chrome font override this; the default returns
    /// [`Self::line_height`] so fixed-cell backends (TUI) and
    /// backends whose chrome and editor fonts share a line height
    /// work unchanged.
    fn chrome_line_height(&self) -> f32 {
        self.line_height()
    }

    /// Override the cached line height (in this backend's native units)
    /// that [`Self::line_height`] reports and every `draw_*` rasteriser
    /// paints against.
    ///
    /// This exists because the three pixel backends resolve their own
    /// line height each frame from a live font (GTK's Pango layout,
    /// macOS's `CTFont`, Win-GUI's DirectWrite text format) — a host that
    /// needs to *re-apply* the current value immediately before a
    /// click-time hit test (undoing any drift between the paint pass and
    /// the event that follows it) had no portable way to do so before
    /// this method: `GtkBackend::set_current_line_height` /
    /// `MacBackend::set_current_line_height` /
    /// `WinBackend::set_current_line_height` were each real, but only
    /// reachable through the concrete backend type, not through `&mut
    /// dyn Backend` — `vimcode`'s `TextMetricsBackend` supertrait
    /// (`src/app.rs`) exists only to paper over that gap, and this method
    /// is what lets it be deleted.
    ///
    /// Default: no-op. TUI is a fixed-cell backend — its line height is
    /// `1.0` by construction, and there is no font-derived value for a
    /// host to re-apply.
    fn set_current_line_height(&mut self, _line_height: f32) {}

    /// Override the cached character width (in this backend's native
    /// units) that [`Self::char_width`] reports — the `char_width` twin
    /// of [`Self::set_current_line_height`]; see that method's doc for
    /// the full rationale.
    ///
    /// Default: no-op. TUI is a fixed-cell backend — its character width
    /// is `1.0` by construction, and there is no font-derived value for a
    /// host to re-apply.
    fn set_current_char_width(&mut self, _char_width: f32) {}

    /// The advance, in this backend's native units, of the font
    /// [`Self::draw_list`] actually paints `ListView` row text with.
    ///
    /// This is **not** always the same number [`Self::char_width`]
    /// returns. `char_width` reports the *editor* font's advance, but
    /// `draw_list` paints chrome (list rows are UI content, not editor
    /// content), and on a pixel backend "chrome
    /// font" can be a proportional face (GTK's default `ui_font` is
    /// `"Sans 11"`, macOS's is the CoreText system UI font) with a
    /// different — usually narrower — average glyph advance than the
    /// monospace editor face `char_width` measures. A consumer that
    /// divides a list's pixel width by [`Self::char_width`] to decide
    /// how many characters of row text fit under-fills the row by
    /// whatever ratio separates the two fonts.
    ///
    /// Call this instead of [`Self::char_width`] when budgeting text for
    /// a `ListView` row. It is still only an *average* advance — a
    /// proportional font has no single width that wraps text exactly
    /// the way a monospace grid does — but it is the right font's
    /// average, which `char_width` is not.
    ///
    /// TUI returns the same `1.0` as `char_width` (one cell either way).
    /// Win-GUI currently returns the same value as `char_width` too:
    /// `draw_list` there still paints with the editor `DWrite` format,
    /// not `chrome_dwrite` (see `WinBackend::chrome_dwrite`'s doc) — the
    /// two will need to diverge together the day that rasteriser moves
    /// to chrome text, so this method is required (no default) on every
    /// backend rather than assumed equal to `char_width`.
    fn list_char_width(&self) -> f32;

    /// [`Self::char_width`] and [`Self::line_height`] bundled into one
    /// [`Metrics`] value, for apps that need both instead of calling each
    /// method separately.
    ///
    /// Default impl composes the two required methods above, so it
    /// returns each backend's real metrics automatically — no backend
    /// needs to override this to get real numbers instead of defaults.
    /// A primitive's `XMeasure::from_metrics(&backend.measure())` avoids
    /// hand-building that `*Measure` literal from `backend.line_height()`
    /// / `backend.char_width()` directly, or approximating one of them.
    fn measure(&self) -> Metrics {
        Metrics {
            char_width: self.char_width(),
            line_height: self.line_height(),
        }
    }

    /// Real `(width, height)`, in this backend's native units, of `text`
    /// rendered in `role`'s font.
    ///
    /// Lets an app building a `*Layout` for a primitive with no
    /// `Backend::X_layout` entry point of its own ([`Dialog`] and
    /// [`ContextMenu`] are the two in this crate — see
    /// [`Dialog::measure_generic`] / [`ContextMenu::measure_generic_width`])
    /// ask "how wide does this label render in the chrome font" without
    /// falling back to `char_width() * label.chars().count()`, which is
    /// wrong for a proportional chrome font (GTK's default `ui_font` is
    /// `"Sans 11"`, macOS's is the CoreText system UI font).
    ///
    /// D-014 (`docs/decisions/DECISIONS.md`) settles the TUI story as
    /// **degrade, not full parity**: GUI backends return the font's real
    /// shaped advance; TUI returns
    /// [`crate::text_util::display_width`]'s cell count with a `height`
    /// of `1.0`. `role` is accepted but has nothing to select between on
    /// TUI — a terminal cell grid has one font by definition (see
    /// [`crate::FontRole`]'s module doc).
    ///
    /// No default: every in-tree backend measures for real — `GtkBackend`
    /// via a scratch `pango::Layout` built from the role's
    /// `FontDescription`, `MacBackend` via `macos::text::measure_text`
    /// against `chrome_font`/`current_font`, `WinBackend` via
    /// `DWrite::measure_text` against `chrome_dwrite`/`dwrite` (falling
    /// back to a `char_width`-scaled estimate before a surface attaches,
    /// matching every other pre-attach degrade on that backend).
    fn measure_text(&self, text: &str, role: crate::FontRole) -> (f32, f32);

    /// Width this backend reserves for its own native scrollbar overlay
    /// alongside scrollable content — e.g. a GTK `ScrolledWindow`'s
    /// overlay scrollbar, drawn on top of the content edge rather than
    /// laid out beside it. A caller computing a content viewport width
    /// (`rect.width - backend.scrollbar_reserve()`) gets the right
    /// answer without asking which backend it's talking to.
    ///
    /// Distinct from [`Self::terminal_scrollbar_default_width`]: that one
    /// is the gutter width of the `Terminal` *primitive*'s own scrollbar,
    /// which paints inside `draw_terminal`'s allotted rect and applies
    /// even to TUI (which draws it as a real column). This one is
    /// surrounding OS/toolkit scrollbar chrome that no primitive
    /// controls — TUI has none of that, so it reserves nothing.
    ///
    /// Default `0.0`, correct for TUI and any backend with no overlay
    /// scrollbar chrome to dodge. GTK overrides this to reserve room for
    /// its `ScrolledWindow` overlay scrollbar.
    fn scrollbar_reserve(&self) -> f32 {
        0.0
    }

    /// Space, in this backend's native units, that [`Self::draw_context_menu`]
    /// needs reserved along every edge of a [`crate::ContextMenu`] before
    /// the menu's own layout is computed — i.e. how far a caller building
    /// the `viewport` rect passed to [`crate::ContextMenu::layout`] /
    /// [`crate::ContextMenu::layout_at`] must inset that viewport on each
    /// side so the resulting [`crate::ContextMenuLayout`] (its `bounds`,
    /// `visible_items`, and `hit_regions`) already accounts for the chrome
    /// this backend paints outside the item area.
    ///
    /// [`Self::context_menu_viewport`] builds that inset rect; prefer it
    /// over applying this value by hand.
    ///
    /// Every pixel backend strokes the menu's border centred on
    /// `bounds` (see `native_surface_paint::paint`'s `surface_stroke_rounded_rect`
    /// call), so the default `0.0` is correct for GTK, Win-GUI, and
    /// macOS. The TUI rasteriser instead paints the border on a whole
    /// cell *outside* `bounds` on every side; when a menu is anchored or
    /// clamped flush against a viewport edge there is no outside cell
    /// left for that border to occupy without this inset, so
    /// [`crate::tui::backend::TuiBackend`] overrides this to `1.0` (one
    /// cell) and the caller shrinks the viewport it hands to layout
    /// accordingly. Doing the inset here — in the geometry `hit_test`
    /// reads — rather than only shifting where the TUI rasteriser paints
    /// keeps painted rows and hit-tested rows in agreement.
    fn context_menu_border_inset(&self) -> f32 {
        0.0
    }

    /// The rect to pass as `viewport` to [`crate::ContextMenu::layout`] /
    /// [`crate::ContextMenu::layout_at`]: this backend's full
    /// [`Self::viewport`], inset on all four sides by
    /// [`Self::context_menu_border_inset`] so the chrome
    /// [`Self::draw_context_menu`] paints outside the item area has room
    /// on every edge, however the menu ends up placed.
    ///
    /// Callers that own a `Backend` handle should use this instead of
    /// building the rect themselves — it is the one place the inset is
    /// applied, so a backend changing its chrome does not have to chase
    /// every menu call site. On backends whose inset is `0.0` (every
    /// pixel backend) the result is just the viewport as a rect.
    ///
    /// A caller working from some sub-region rather than the whole
    /// surface (a split pane, a popup already offset inside the window)
    /// insets that region the same way, by
    /// [`Self::context_menu_border_inset`] on each side.
    fn context_menu_viewport(&self) -> Rect {
        let vp = self.viewport();
        let inset = self.context_menu_border_inset();
        Rect::new(
            inset,
            inset,
            (vp.width - inset * 2.0).max(0.0),
            (vp.height - inset * 2.0).max(0.0),
        )
    }

    /// Whether this backend can render individual text rows at a larger
    /// font size (per-line scale), so layouts should reserve taller
    /// vertical space for scaled rows.
    ///
    /// Returns `true` for backends that honour per-line font-size scale
    /// (GTK applies a Pango scale attr, so a 2.0× heading row draws at
    /// twice the line height). Returns `false` for fixed-cell backends
    /// like TUI, where a terminal cell can't grow — those render scaled
    /// rows at the normal cell height (bold heading text, no extra
    /// space). Primitives that carry per-line scale (e.g.
    /// [`RichTextPopup::line_scales`][crate::RichTextPopup]) feed this
    /// into their `*Measure` so the shared layout reserves the right
    /// height per backend without the consumer branching on backend
    /// type.
    ///
    /// Default `false` — only backends that actually scale glyphs
    /// override it.
    fn scales_text_rows(&self) -> bool {
        false
    }

    /// Snap a proposed height (in logical units — the same units as
    /// [`Self::line_height`]) to what this backend will actually paint.
    ///
    /// Cell-grid backends (TUI) quantize to whole rows; pixel backends
    /// paint fractional heights exactly and return the input unchanged.
    ///
    /// This is the sanctioned replacement for consumer-side `.round()` on
    /// a `line_height`-derived extent. Call this instead of modelling the
    /// rounding yourself, so the layout math and the hit-test can't drift
    /// apart:
    ///
    /// ```ignore
    /// let tab_bar_h = backend.snap_height(backend.line_height() * 1.4);
    /// ```
    ///
    /// Default: returns `h` unchanged (correct for every pixel backend).
    /// Only [`crate::tui::backend::TuiBackend`] overrides it.
    fn snap_height(&self, h: f32) -> f32 {
        h
    }

    // ─── Drawing — one method per primitive ────────────────────────────
    //
    // Implementations are thin wrappers around each backend crate's
    // internal `pub fn draw_*` free functions. Example:
    //
    //   impl Backend for WinBackend {
    //       fn draw_tree(&mut self, rect: Rect, tree: &TreeView) {
    //           quadraui_win::draw_tree(self.ctx(), tree, self.theme(), rect);
    //       }
    //       // ... one per primitive
    //   }
    //
    // Adding a primitive is a breaking change to this trait — intentional
    // (see `docs/decisions/BACKEND_TRAIT_PROPOSAL.md` §4). Backends opt in to the new
    // primitive in the same PR that adds it to the trait.
    /// Paint `tree` into `rect`. Non-header row height defaults to a
    /// backend-native derivation from `line_height` (GTK/macOS:
    /// `line_height * 1.4`; TUI: fixed 1 cell) but a host can pin it via
    /// [`TreeStyle::row_height`](crate::types::TreeStyle::row_height)
    /// instead — e.g. to match a fixed design-system row pitch
    /// independent of editor font size. TUI ignores the override
    /// (a terminal cell can't be subdivided).
    fn draw_tree(&mut self, rect: Rect, tree: &TreeView);
    fn draw_list(&mut self, rect: Rect, list: &ListView);
    /// Draw `table` into `rect` and return its layout for hit-testing.
    /// Coordinate frame: **LOCAL** — `hit_regions` / row bounds are
    /// relative to `rect`'s origin, matching [`Self::data_table_layout`].
    fn draw_data_table(
        &mut self,
        rect: Rect,
        table: &DataTable,
        hovered_idx: Option<usize>,
    ) -> DataTableLayout;
    /// Draw `table` into `rect` with an optional [`DataTableGlyphs`]
    /// override for the sort-ascending/sort-descending arrows. Returns
    /// its layout for hit-testing, same contract as [`Self::draw_data_table`].
    ///
    /// Added rather than folded into [`Self::draw_data_table`]'s
    /// signature, and given a default body, so it breaks no existing
    /// `Backend` implementor and no existing call site.
    ///
    /// The default body **ignores `glyphs`** and delegates to
    /// [`Self::draw_data_table`], i.e. renders the default sort arrows.
    /// That is the correct fallback for a backend that hasn't opted in
    /// to overrides yet. The TUI backend overrides it and honours
    /// `glyphs` in full.
    fn draw_data_table_with_glyphs(
        &mut self,
        rect: Rect,
        table: &DataTable,
        hovered_idx: Option<usize>,
        glyphs: Option<&DataTableGlyphs>,
    ) -> DataTableLayout {
        let _ = glyphs;
        self.draw_data_table(rect, table, hovered_idx)
    }
    /// Compute the data-table layout without painting. Coordinate frame:
    /// **LOCAL** — relative to `rect`'s origin, `(0, 0)` at `rect`'s
    /// top-left; callers subtract `rect.x` / `rect.y` from absolute
    /// click coordinates before calling `hit_test` (see the module doc's
    /// *Coordinate frames* section).
    fn data_table_layout(&self, rect: Rect, table: &DataTable) -> DataTableLayout;
    /// Horizontal scrollbar geometry for `list` rendered into `rect`, or
    /// `None` when its content fits. Each backend supplies its native row
    /// height; the resolved track + thumb are the same values the
    /// rasteriser paints, so consumers hit-test the returned thumb to
    /// implement drag without re-deriving geometry. Mirrors
    /// [`Backend::data_table_layout`]; see [`ListView::hscrollbar`].
    fn list_hscrollbar(&self, rect: Rect, list: &ListView) -> Option<Scrollbar>;
    /// Vertical scrollbar geometry for `list` rendered into `rect`, or
    /// `None` when `show_v_scrollbar` is `false` or all items fit. Each
    /// backend supplies its native row height; the resolved track + thumb
    /// are the same values the rasteriser paints, so consumers hit-test
    /// the returned thumb to implement drag without re-deriving geometry.
    /// Mirrors [`Backend::list_hscrollbar`]; see [`ListView::vscrollbar`].
    fn list_vscrollbar(&self, rect: Rect, list: &ListView) -> Option<Scrollbar>;
    /// Compute the list layout without painting — the no-paint twin of
    /// [`Self::draw_list`]. `draw_list` and this method route through the
    /// same backend-internal resolver (`tui_list_layout` / `gtk_list_layout`
    /// / `win_list_layout` / `mac_list_layout`), so paint and no-paint
    /// can't drift apart. Every pixel backend's resolver shares its
    /// h-scrollbar row reservation via `primitives::layout_metrics::list_layout`.
    ///
    /// Coordinate frame: **LOCAL** — relative to `rect`'s origin, `(0, 0)`
    /// at `rect`'s top-left; does **not** account for
    /// [`ListView::bordered`]'s 1-cell/1px border inset, matching every
    /// backend's `draw_list`.
    fn list_layout(&self, rect: Rect, list: &ListView) -> ListViewLayout;
    fn draw_form(&mut self, rect: Rect, form: &Form);
    fn draw_palette(&mut self, rect: Rect, palette: &Palette);

    /// Compute the palette layout without painting — the no-paint twin
    /// of [`Self::draw_palette`]. Every backend's `palette_layout` shares
    /// its row/column arithmetic with its own `draw_palette`
    /// (`tui_palette_layout`, `gtk_palette_layout`, `mac_palette_layout`,
    /// `win_palette_layout`), so paint and no-paint can't drift apart —
    /// see `docs/decisions/DECISIONS.md` D-007 "Palette: deferred, not
    /// missed" for the rationale.
    ///
    /// Coordinate frame: **LOCAL** — relative to `rect`'s origin, `(0, 0)`
    /// at `rect`'s top-left, matching [`Palette::layout`]'s native
    /// contract. Callers subtract `rect.x` / `rect.y` from an absolute
    /// click coordinate before calling [`PaletteLayout::hit_test`]
    /// (`PRIMITIVE_RULES.md`'s coordinate-frame convention).
    ///
    /// TUI's implementation never reports [`PaletteLayout::scrollbar`]
    /// (always `None`) — see `tui::palette::tui_palette_layout`'s doc for
    /// why reporting one would invent a second thumb-position formula
    /// disagreeing with what TUI actually paints.
    fn palette_layout(&self, rect: Rect, palette: &Palette) -> PaletteLayout;

    /// Draw settings-panel chrome: a header row and, when `rect.height`
    /// leaves room for it, a search input row beneath it, designed to
    /// sit immediately above a [`Form`] body. See
    /// `tui::draw_settings_chrome` / `gtk::draw_settings_chrome` for the
    /// exact row layout, `" / "`-prefixed prompt construction, and
    /// placeholder logic.
    ///
    /// **Height contract:** the header row always paints at one
    /// `line_height`. The search row paints only when `rect.height`
    /// covers a second row (every implementer uses the same
    /// `line_height * 1.5` threshold, matching TUI's `area.height < 2`
    /// cell check) — a caller that reserves a single row (e.g.
    /// [`crate::compose::sidebar_panel_body::SidebarPanelChrome::Header`])
    /// gets a header-only strip, not a second, unrequested row painted
    /// past the rect the caller reserved.
    ///
    /// No default impl — every backend implementer sees this as a compile
    /// error and fills in a real rasteriser (`docs/decisions/BACKEND_TRAIT_PROPOSAL.md`
    /// §4, `PRIMITIVE_RULES.md` rule 7). Do not add a no-op default here;
    /// see `docs/SMELL_AUDIT_2026-07.md` PORT-01 for why that pattern is a
    /// portability risk, not a precedent to follow.
    fn draw_settings_chrome(
        &mut self,
        rect: Rect,
        header_text: &str,
        query: &str,
        placeholder: &str,
        active: bool,
    );

    // Layout-passthrough primitives (per docs/decisions/BACKEND_TRAIT_PROPOSAL.md
    // §6.2). Each backend computes the primitive's layout internally
    // using its native measurer (cells for TUI, Pango / DirectWrite /
    // Core Text pixels for the others) — apps don't have access to
    // those handles, so layout precomputation can't live caller-side.
    //
    // Methods that produce hit-region data (clickable segments,
    // close-button rects, link rects) return it directly so callers
    // route clicks against the same data the rasteriser paints with.
    /// Draw a status bar, reading hover/pressed state from a single
    /// [`InteractionState`] keyed by [`WidgetId`].
    ///
    /// The rasteriser tints the background of the clickable segment
    /// whose `action_id` matches `interaction.hovered()` /
    /// `interaction.pressed()` — the primitive itself carries no mouse
    /// state. Returns hit regions in **bar-local coordinates**
    /// (relative to `rect.x` / `rect.y`) for each segment carrying an
    /// `action_id`. Caller dispatches clicks against the returned list.
    ///
    /// This is the implemented method; the positional
    /// [`Self::draw_status_bar`] is a deprecated shim over it.
    fn draw_status_bar_interactive(
        &mut self,
        rect: Rect,
        bar: &StatusBar,
        interaction: &InteractionState,
    ) -> StatusBarLayout;

    /// Like [`Self::draw_status_bar_interactive`], but scales the chrome
    /// font this one call paints with, without touching the ambient
    /// [`Self::set_ui_font`] state every *other* status bar (or any other
    /// [`crate::font_role::ChromePrimitive::StatusBar`] paint) draws in
    /// this frame.
    ///
    /// `font_scale` multiplies the backend's current UI font's point
    /// size for this call only — `1.0` behaves identically to
    /// [`Self::draw_status_bar_interactive`]; `0.85` paints ~15% smaller,
    /// e.g. a breadcrumb strip that wants to sit visually subordinate to
    /// a full-size status bar without either one needing its own
    /// `set_ui_font` call (which would perturb every other chrome
    /// primitive too — see [`Self::set_ui_font`]'s own doc).
    ///
    /// Default: ignores `font_scale` and forwards to
    /// [`Self::draw_status_bar_interactive`] unscaled — the honest
    /// default for TUI (a fixed-cell backend has no font size to scale)
    /// and any future backend that hasn't wired real per-call scaling
    /// yet. Additive over `draw_status_bar_interactive`, not a
    /// replacement for it, so every existing in-tree and downstream call
    /// site keeps compiling unchanged.
    ///
    /// `font_scale` is expected to be a small positive multiplier (e.g.
    /// `0.5`–`2.0`); implementations clamp a degenerate value (`0.0` or
    /// negative) to a small positive floor rather than handing it
    /// unchecked to the native font API — see the GTK and macOS backends'
    /// own `status_bar_paint_scaled` for the specific floor each uses.
    fn draw_status_bar_interactive_scaled(
        &mut self,
        rect: Rect,
        bar: &StatusBar,
        interaction: &InteractionState,
        _font_scale: f32,
    ) -> StatusBarLayout {
        self.draw_status_bar_interactive(rect, bar, interaction)
    }

    /// Draw a status bar with hover/pressed supplied positionally.
    ///
    /// # Deprecated
    ///
    /// Superseded by [`Self::draw_status_bar_interactive`], which reads
    /// the same two values out of one [`InteractionState`] keyed by
    /// [`WidgetId`] instead of two positional `Option<&WidgetId>` slots.
    /// Kept because the sealed milestone acceptance slices
    /// `tests/acceptance/ms-11/{structural_parity,c0_paint_smoke}.rs`
    /// still call it positionally and this crate cannot edit anything
    /// under `tests/acceptance/` (see `quadraui/tests/acceptance.rs`'s
    /// module doc). Removal target: whichever Gate A pass migrates those
    /// two slices off the positional call, not before v0.2.0.
    #[deprecated(
        since = "0.0.1",
        note = "use `draw_status_bar_interactive` (hover/pressed come from an `InteractionState` keyed by `WidgetId`) — issue #819; removal target: once the sealed `tests/acceptance/ms-11` slices that still call this positionally migrate, not before v0.2.0"
    )]
    fn draw_status_bar(
        &mut self,
        rect: Rect,
        bar: &StatusBar,
        hovered_id: Option<&WidgetId>,
        pressed_id: Option<&WidgetId>,
    ) -> StatusBarLayout {
        let interaction = InteractionState::from_parts(hovered_id.cloned(), pressed_id.cloned());
        self.draw_status_bar_interactive(rect, bar, &interaction)
    }

    /// Draw a tab bar. `hovered_close_tab` carries per-frame hover
    /// state so the rasteriser can paint a hover background behind the
    /// hovered tab's close glyph (the primitive itself carries no
    /// mouse state). Returns [`TabBarHits`] for click dispatch +
    /// scroll-offset reconciliation.
    ///
    /// `TabBarHits` itself is `#[deprecated]` — see that struct's doc for
    /// why the six-method/four-backend swap to [`TabBarLayout`] is
    /// separate follow-up work.
    #[allow(deprecated)]
    fn draw_tab_bar(
        &mut self,
        rect: Rect,
        bar: &TabBar,
        hovered_close_tab: Option<usize>,
    ) -> TabBarHits;
    /// Draw a tab bar, returning [`TabBarLayout`] instead of the
    /// deprecated [`TabBarHits`]. Added *alongside* [`Self::draw_tab_bar`]
    /// rather than in place of it, so no existing caller breaks.
    /// Paints exactly what [`Self::draw_tab_bar`] paints (icon-less
    /// sidecar of [`Self::draw_tab_bar_icons_layout`]); the two must never
    /// drift apart, same invariant [`Self::draw_tab_bar`] already holds
    /// against [`Self::draw_tab_bar_icons`].
    ///
    /// Returned in [`TabBarLayout`]'s own **bar-relative** coordinate
    /// space (origin at `rect`'s top-left) — see that struct's doc. This
    /// is deliberately *not* the target-surface-absolute space
    /// [`TabBarHits`] uses; the two return types have different,
    /// independently-documented contracts, and this method follows
    /// `TabBarLayout`'s.
    ///
    /// No default impl — every backend implementer sees this as a
    /// compile error and fills in a real rasteriser, mirroring
    /// [`Self::draw_tab_bar`]'s own no-default rule (rule 7).
    fn draw_tab_bar_layout(
        &mut self,
        rect: Rect,
        bar: &TabBar,
        hovered_close_tab: Option<usize>,
    ) -> TabBarLayout;
    /// Draw a tab bar with per-tab icon glyphs — VS Code's coloured
    /// language/file-type badge on each tab.
    ///
    /// `icons` is a **sidecar slice parallel to `bar.tabs`**: entry `i`
    /// decorates tab `i`, `None` (or an index past the slice's end)
    /// means "no icon", and `&[]` is exactly equivalent to
    /// [`Self::draw_tab_bar`]. Resolve entries with
    /// [`crate::tab_icon_at`] / [`crate::tab_icon_cols`] rather than
    /// indexing, so every backend shares one short-slice convention.
    ///
    /// The icons ride *beside* the primitive instead of inside
    /// [`crate::TabItem`] because a new field on that struct is a hard
    /// break for both downstream consumers and the sealed acceptance
    /// slices, which build it with exhaustive literals — whereas a new
    /// `Backend` method with no default breaks nobody
    /// (`PRIMITIVE_RULES.md` rule 8's blast-radius table). See
    /// [`crate::TabIcon`] for the full rationale.
    ///
    /// Implementors: put the real rasteriser **here** and let
    /// [`Self::draw_tab_bar`] forward with `&[]`, so an icon-less bar
    /// and an icon bar can never drift apart. An icon must widen its
    /// tab by exactly what the paint reserves, so close-button and
    /// tab-slot hit geometry stay on the glyphs the user sees; icon-less
    /// tabs must keep byte-identical geometry to `draw_tab_bar`.
    ///
    /// No default impl — every backend implementer sees this as a
    /// compile error and fills in a real rasteriser
    /// (`docs/decisions/BACKEND_TRAIT_PROPOSAL.md` §4, `PRIMITIVE_RULES.md` rule 7).
    ///
    /// `TabBarHits` is `#[deprecated]` — see [`Self::draw_tab_bar`].
    #[allow(deprecated)]
    fn draw_tab_bar_icons(
        &mut self,
        rect: Rect,
        bar: &TabBar,
        icons: &[Option<TabIcon>],
        hovered_close_tab: Option<usize>,
    ) -> TabBarHits;
    /// Draw a tab bar with per-tab icon glyphs, returning [`TabBarLayout`]
    /// instead of the deprecated [`TabBarHits`]. The icon-aware twin of
    /// [`Self::draw_tab_bar_layout`], exactly as
    /// [`Self::draw_tab_bar_icons`] is the twin of [`Self::draw_tab_bar`]
    /// — same `icons` sidecar convention, same bar-relative coordinate
    /// space as [`Self::draw_tab_bar_layout`].
    ///
    /// No default impl — same rule-7 reasoning as
    /// [`Self::draw_tab_bar_icons`].
    fn draw_tab_bar_icons_layout(
        &mut self,
        rect: Rect,
        bar: &TabBar,
        icons: &[Option<TabIcon>],
        hovered_close_tab: Option<usize>,
    ) -> TabBarLayout;
    /// Draw a tab bar with an explicit [`TabChrome`] request: which
    /// decoration, if any, should enclose the active tab's full content
    /// (label *and* close glyph).
    ///
    /// Added rather than folded into [`Self::draw_tab_bar`]'s signature,
    /// and given a default body, so it breaks no existing `Backend`
    /// implementor and no existing call site — see `primitives::tab_bar`'s
    /// [`TabChrome`] doc, which mirrors [`crate::TooltipChrome`]'s shape
    /// for exactly this reason.
    ///
    /// The default body **ignores `chrome`** and delegates to
    /// [`Self::draw_tab_bar`], i.e. renders [`crate::TabFrame::None`] —
    /// the correct fallback for a backend with no frame vocabulary of its
    /// own. The TUI and GTK backends override it and honour
    /// [`crate::TabFrame::Brackets`] in full.
    ///
    /// `TabBarHits` is `#[deprecated]` — see [`Self::draw_tab_bar`].
    #[allow(deprecated)]
    fn draw_tab_bar_with_chrome(
        &mut self,
        rect: Rect,
        bar: &TabBar,
        hovered_close_tab: Option<usize>,
        chrome: &TabChrome,
    ) -> TabBarHits {
        let _ = chrome;
        self.draw_tab_bar(rect, bar, hovered_close_tab)
    }
    /// Draw a tab bar with an explicit [`TabChrome`] request, returning
    /// [`TabBarLayout`] instead of the deprecated [`TabBarHits`] — the
    /// `TabBarLayout`-returning twin of [`Self::draw_tab_bar_with_chrome`].
    ///
    /// Default body **ignores `chrome`** and delegates to
    /// [`Self::draw_tab_bar_layout`], matching
    /// [`Self::draw_tab_bar_with_chrome`]'s own default exactly.
    fn draw_tab_bar_with_chrome_layout(
        &mut self,
        rect: Rect,
        bar: &TabBar,
        hovered_close_tab: Option<usize>,
        chrome: &TabChrome,
    ) -> TabBarLayout {
        let _ = chrome;
        self.draw_tab_bar_layout(rect, bar, hovered_close_tab)
    }
    /// Draw a tab bar with an explicit [`TabChrome`] request, plus an
    /// optional [`TabBarGlyphs`] override for the close/dirty glyphs.
    ///
    /// Added rather than folded into [`Self::draw_tab_bar_with_chrome`]'s
    /// signature, and given a default body, so it breaks no existing
    /// `Backend` implementor and no existing call site.
    ///
    /// The default body **ignores `glyphs`** and delegates to
    /// [`Self::draw_tab_bar_with_chrome`], i.e. renders the default
    /// close/dirty glyphs. That is the correct fallback for a backend
    /// that hasn't opted in to overrides yet. The TUI backend overrides
    /// it and honours `glyphs` in full.
    ///
    /// `TabBarHits` is `#[deprecated]` — see [`Self::draw_tab_bar`].
    #[allow(deprecated)]
    fn draw_tab_bar_with_chrome_and_glyphs(
        &mut self,
        rect: Rect,
        bar: &TabBar,
        hovered_close_tab: Option<usize>,
        chrome: &TabChrome,
        glyphs: Option<&TabBarGlyphs>,
    ) -> TabBarHits {
        let _ = glyphs;
        self.draw_tab_bar_with_chrome(rect, bar, hovered_close_tab, chrome)
    }
    /// Draw an activity bar. `hovered_idx` carries per-frame hover
    /// state so the rasteriser can paint a tint on the hovered row.
    /// Returns per-row hit regions for click + tooltip dispatch.
    ///
    /// # Coordinate space — **relative to `rect`**
    ///
    /// Each [`ActivityBarRowHit`]'s `y_start` / `y_end` is measured from
    /// the **top edge of `rect`**: the first row starts at `0.0` no
    /// matter where the bar sits on the target surface. Implementors
    /// must **not** fold `rect.y` into the returned spans, even though
    /// they need the absolute value to paint. Callers add the bar origin
    /// themselves (`hit.y_start + rect.y`).
    ///
    /// Note this is deliberately the *opposite* convention from
    /// [`Self::tab_bar_layout`] / [`Self::draw_tab_bar`], whose
    /// [`TabBarHits`] spans are absolute. The split is historical but now
    /// pinned: the activity bar's space is what GTK, macOS, and the
    /// shared [`activity_bar_hits`] helper already produced, and what
    /// `AppShell` assumes in both its click and hover readers.
    ///
    /// [`Self::activity_bar_layout`] must return the same space. A
    /// drifting backend fails
    /// `tui::activity_bar::tests::hit_regions_are_bar_relative_not_absolute`
    /// / `hit_regions_do_not_move_when_the_bar_does`, plus the
    /// `activity_click_*_parity` / `activity_hover_*_parity` cross-backend
    /// tests in `tests/cross_backend_parity.rs`.
    fn draw_activity_bar(
        &mut self,
        rect: Rect,
        bar: &ActivityBar,
        hovered_idx: Option<usize>,
    ) -> Vec<ActivityBarRowHit>;

    /// Draw an activity bar with an explicit [`ActivityBarStyle`] request —
    /// currently just the active item's row-fill colour, VS Code style
    /// (no line, a soft chip on the row itself).
    ///
    /// Added rather than folded into [`Self::draw_activity_bar`]'s
    /// signature, and given a default body, so it breaks no existing
    /// `Backend` implementor and no existing call site — mirrors
    /// [`crate::TooltipChrome`] / [`Self::draw_tooltip_with_chrome`] and
    /// [`TabChrome`] / [`Self::draw_tab_bar_with_chrome`], which solve the
    /// identical "additive field would break exhaustive downstream
    /// literals" problem for `Tooltip` and `TabBar`. See
    /// [`ActivityBarStyle`]'s doc for the full reasoning.
    ///
    /// The default body **ignores `style`** and delegates to
    /// [`Self::draw_activity_bar`] — the correct fallback for a backend
    /// with no fill vocabulary of its own. The TUI, GTK, and macOS
    /// backends override it and honour `style.active_bg` in full; Win
    /// takes the default for now (every `draw_*` method there is a
    /// stub).
    fn draw_activity_bar_with_style(
        &mut self,
        rect: Rect,
        bar: &ActivityBar,
        hovered_idx: Option<usize>,
        style: &ActivityBarStyle,
    ) -> Vec<ActivityBarRowHit> {
        let _ = style;
        self.draw_activity_bar(rect, bar, hovered_idx)
    }

    /// Compute the status bar layout without painting. Same measurement
    /// logic as `draw_status_bar` — call after `ScreenLayout::draw()` to
    /// recover hit regions for click dispatch.
    ///
    /// Returns `hit_regions` in the same **bar-local** space as
    /// [`Self::draw_status_bar`] (relative to `rect.x` / `rect.y`): every
    /// backend returns the primitive's own unshifted `StatusBar::layout`
    /// output, so paint and no-paint already agree and no backend folds
    /// the origin in.
    fn status_bar_layout(&self, rect: Rect, bar: &StatusBar) -> StatusBarLayout;

    /// Compute the tab bar layout without painting. Returns the same
    /// `TabBarHits` as `draw_tab_bar` — slot positions, close bounds, and
    /// right-segment bounds are all in **target-surface (absolute)
    /// coordinates**, i.e. shifted by `rect.x` / `rect.y` so callers can
    /// compare them directly against raw click coordinates without any
    /// further adjustment. Every backend routes through
    /// [`shift_tab_bar_hits`], the same helper the rasterisers use. Note
    /// the tab bar's absolute convention is the opposite of
    /// [`Self::draw_activity_bar`]'s bar-relative one — deliberate, and
    /// stated on both.
    ///
    /// `TabBarHits` is `#[deprecated]` — see [`Self::draw_tab_bar`].
    #[allow(deprecated)]
    fn tab_bar_layout(&self, rect: Rect, bar: &TabBar) -> TabBarHits;

    /// Compute the tab bar layout without painting, returning
    /// [`TabBarLayout`] instead of the deprecated [`TabBarHits`]. The
    /// `TabBarLayout`-returning twin of [`Self::tab_bar_layout`], added
    /// alongside it rather than in place of it — every backend already
    /// resolves this geometry internally before narrowing it down to
    /// `TabBarHits`; this exposes it directly.
    ///
    /// Returned in `TabBarLayout`'s own **bar-relative** space — see that
    /// struct's doc — which is the *opposite* convention from
    /// [`Self::tab_bar_layout`]'s documented absolute one. This is not a
    /// coordinate-space bug: the two return types each follow their own
    /// struct's contract, same split `TabBarLayout`'s own doc draws
    /// against `Self::draw_activity_bar` / `Self::activity_bar_layout`.
    /// A caller wanting an absolute point adds the bar's own `rect.x` /
    /// `rect.y` origin, exactly as [`TabBarLayout::tab_center`] /
    /// [`TabBarLayout::tab_close_center`]'s docs already describe for
    /// `TuiDriver` / `GtkDriver`.
    ///
    /// No default impl — same rule-7 reasoning as
    /// [`Self::tab_bar_layout_icons`].
    fn resolve_tab_bar_layout(&self, rect: Rect, bar: &TabBar) -> TabBarLayout;

    /// Compute the tab bar layout without painting, for a bar painted
    /// with per-tab icons. The no-paint twin of
    /// [`Self::draw_tab_bar_icons`], exactly as [`Self::tab_bar_layout`]
    /// is the twin of [`Self::draw_tab_bar`] — same absolute-coordinate
    /// contract, same `icons` sidecar convention.
    ///
    /// A caller that paints with icons **must** route its no-paint click
    /// geometry through this method rather than [`Self::tab_bar_layout`]:
    /// the icon reservation widens every decorated tab, so the icon-less
    /// twin would report slot and close-button bounds shifted left of
    /// the painted glyphs. `&[]` makes the two identical.
    ///
    /// No default impl — same rule-7 reasoning as
    /// [`Self::draw_tab_bar_icons`].
    ///
    /// `TabBarHits` is `#[deprecated]` — see [`Self::draw_tab_bar`].
    #[allow(deprecated)]
    fn tab_bar_layout_icons(
        &self,
        rect: Rect,
        bar: &TabBar,
        icons: &[Option<TabIcon>],
    ) -> TabBarHits;

    /// Compute the tab bar layout without painting, for a bar painted
    /// with per-tab icons, returning [`TabBarLayout`] instead of the
    /// deprecated [`TabBarHits`]. The icon-aware twin of
    /// [`Self::resolve_tab_bar_layout`], exactly as
    /// [`Self::tab_bar_layout_icons`] is the twin of
    /// [`Self::tab_bar_layout`] — same `icons` sidecar convention, same
    /// bar-relative coordinate space as [`Self::resolve_tab_bar_layout`].
    ///
    /// No default impl — same rule-7 reasoning as
    /// [`Self::tab_bar_layout_icons`].
    fn resolve_tab_bar_layout_icons(
        &self,
        rect: Rect,
        bar: &TabBar,
        icons: &[Option<TabIcon>],
    ) -> TabBarLayout;

    /// Compute the tab bar layout without painting, for a bar painted
    /// with [`Self::draw_tab_bar_with_chrome`]. The no-paint twin of that
    /// method, exactly as [`Self::tab_bar_layout`] is the twin of
    /// [`Self::draw_tab_bar`] — same absolute-coordinate contract.
    ///
    /// A caller that paints with chrome **must** route its no-paint click
    /// geometry through this method rather than [`Self::tab_bar_layout`]:
    /// [`crate::TabFrame::Brackets`] widens the active tab and moves its
    /// close-button hit region, so the chrome-less twin would report it
    /// shifted from the painted glyph.
    ///
    /// Default body ignores `chrome` and delegates to
    /// [`Self::tab_bar_layout`], matching [`Self::draw_tab_bar_with_chrome`]'s
    /// default.
    ///
    /// `TabBarHits` is `#[deprecated]` — see [`Self::draw_tab_bar`].
    #[allow(deprecated)]
    fn tab_bar_layout_with_chrome(
        &self,
        rect: Rect,
        bar: &TabBar,
        chrome: &TabChrome,
    ) -> TabBarHits {
        let _ = chrome;
        self.tab_bar_layout(rect, bar)
    }

    /// Compute the tab bar layout without painting, for a bar painted
    /// with chrome, returning [`TabBarLayout`] instead of the deprecated
    /// [`TabBarHits`] — the `TabBarLayout`-returning twin of
    /// [`Self::tab_bar_layout_with_chrome`].
    ///
    /// Default body ignores `chrome` and delegates to
    /// [`Self::resolve_tab_bar_layout`], matching
    /// [`Self::tab_bar_layout_with_chrome`]'s own default exactly.
    fn resolve_tab_bar_layout_with_chrome(
        &self,
        rect: Rect,
        bar: &TabBar,
        chrome: &TabChrome,
    ) -> TabBarLayout {
        let _ = chrome;
        self.resolve_tab_bar_layout(rect, bar)
    }

    /// Compute activity bar row hit regions without painting. Returns
    /// the same **bar-relative** spans as [`Self::draw_activity_bar`] —
    /// `y_start` / `y_end` measured from `rect.y`, first row at `0.0`.
    /// See that method for the full contract.
    fn activity_bar_layout(&self, rect: Rect, bar: &ActivityBar) -> Vec<ActivityBarRowHit>;

    /// Draw a terminal cell grid. No hit-region data is returned;
    /// terminal selection is driven by mouse drag against cell
    /// dimensions, which the app already tracks.
    fn draw_terminal(&mut self, rect: Rect, term: &Terminal);
    /// The reserved width of a `Terminal`'s scrollbar gutter when
    /// [`TerminalScrollbar::width`](crate::primitives::terminal::TerminalScrollbar::width)
    /// is `None`, in this backend's own surface-native unit. Every
    /// `draw_terminal` implementation falls back to a
    /// hardcoded default when the caller didn't specify a width, and
    /// that default is backend-shaped, not uniform: TUI's cells *are*
    /// the coordinate system, so its gutter is exactly one column
    /// (`src/tui/terminal.rs`'s `sb_cols: … .unwrap_or(1)`); GTK, macOS,
    /// and Win all measure in pixels and use 8px
    /// (`src/gtk/backend.rs`, `src/macos/backend.rs`,
    /// `src/win/backend.rs`, each `sb_width: … .unwrap_or(8.0)`).
    /// [`Self::terminal_layout`]'s default body calls this so its
    /// scrollbar reservation matches whichever default the paint path
    /// actually used, instead of silently assuming the pixel-backend
    /// value for every backend (or ignoring the reservation entirely).
    ///
    /// Default: `8.0`, matching GTK/macOS/Win. TUI overrides this to
    /// `1.0` — see `TuiBackend::terminal_scrollbar_default_width`.
    fn terminal_scrollbar_default_width(&self) -> f32 {
        8.0
    }
    /// Compute the viewport → grid conversion [`Self::draw_terminal`]
    /// implicitly uses. Uses this backend's own [`Self::char_width`] /
    /// [`Self::line_height`] as the cell dimensions — TUI's `(1.0, 1.0)`
    /// reproduces its uniform cell grid exactly; pixel backends get the
    /// same font metrics `draw_terminal`'s cell iteration assumes.
    ///
    /// When `term.scrollbar` is `Some`, the viewport width fed to
    /// [`crate::primitives::terminal::Terminal::layout`] is first reduced
    /// by the scrollbar's reserved width — `sb.width` when set, else
    /// [`Self::terminal_scrollbar_default_width`] — exactly as every
    /// backend's real `draw_terminal` reserves that gutter *before*
    /// iterating cells (`cell_area_w = area.width.saturating_sub(sb_cols)`
    /// on TUI; `cell_area_w = (rect.width - sb_width).max(0.0)` on
    /// GTK/macOS/Win). Skipping this step would report `grid_cols` wide
    /// enough to claim the scrollbar gutter itself as a clickable cell.
    ///
    /// Coordinate frame: **LOCAL** — relative to `rect`'s origin; see
    /// [`crate::primitives::terminal::TerminalLayout::hit_test`] /
    /// [`crate::primitives::terminal::TerminalLayout::cell_bounds`],
    /// neither of which fold in an origin offset.
    ///
    /// Default body: uniform for every backend, since it's a pure
    /// function of the metrics above plus [`Self::terminal_scrollbar_default_width`]
    /// — no backend needs to override this.
    fn terminal_layout(
        &self,
        rect: Rect,
        term: &Terminal,
    ) -> crate::primitives::terminal::TerminalLayout {
        let sb_reserved = match &term.scrollbar {
            Some(sb) => sb
                .width
                .map(|w| w as f32)
                .unwrap_or_else(|| self.terminal_scrollbar_default_width()),
            None => 0.0,
        };
        let cell_area_w = (rect.width - sb_reserved).max(0.0);
        term.layout(
            cell_area_w,
            rect.height,
            self.char_width(),
            self.line_height(),
        )
    }
    /// Draw a vertical divider between two split terminal panes.
    /// `rect.x` is the divider's column, `rect.y` its top row, and
    /// `rect.height` its length; `rect.width` is ignored — the
    /// divider is always a single cell (TUI) or 1px (GTK/macOS) wide.
    /// See `tui::draw_terminal_divider` / `gtk::draw_terminal_divider`
    /// for the exact glyph/fill painted.
    ///
    /// No default impl — every backend implementer sees this as a
    /// compile error and fills in a real rasteriser
    /// (`docs/decisions/BACKEND_TRAIT_PROPOSAL.md` §4, `PRIMITIVE_RULES.md` rule 7).
    /// Do not add a no-op default here; see
    /// `docs/SMELL_AUDIT_2026-07.md` PORT-01 for why that pattern is a
    /// portability risk, not a precedent to follow.
    fn draw_terminal_divider(&mut self, rect: Rect);
    /// Fill `rect` edge-to-edge with a solid `color` — no text, no
    /// segments, no per-row seams. For chrome elements that are a plain
    /// color block (e.g. `AppShell`'s sidebar/editor resize divider),
    /// not a widget.
    ///
    /// A single fill over the *whole* rect is exact on every backend
    /// (unlike faking it as N stacked one-row `StatusBar`s, which paints
    /// short of a pixel backend's own row pitch and leaves gaps between
    /// rows) and strictly cheaper than N layouts per frame.
    ///
    /// No default impl — every backend implementer sees this as a
    /// compile error and fills in a real rasteriser
    /// (`docs/decisions/BACKEND_TRAIT_PROPOSAL.md` §4, `PRIMITIVE_RULES.md` rule 7).
    fn draw_solid_fill(&mut self, rect: Rect, color: Color);
    /// Draw a `TextDisplay` (streaming-text panel — log viewer, output
    /// pane, YAML view, etc). No hit-region data is returned;
    /// `TextDisplay` itself is non-interactive (selection / scroll
    /// happen at the panel chrome level, not at the line/span level).
    fn draw_text_display(&mut self, rect: Rect, td: &TextDisplay);

    /// Draw a [`CommandLine`] bar (editor `:` / `/` / `?` prompt or
    /// message display). Fills `rect` with the command line background,
    /// renders text (left- or right-aligned), and optionally draws an
    /// insert cursor at `cursor_offset`.
    fn draw_command_line(&mut self, rect: Rect, cmd: &CommandLine);

    /// Draw a [`CommandLine`] bar exactly like [`Self::draw_command_line`],
    /// additionally painting a selection highlight behind the text for
    /// `selection` (a `(start, end)` byte-offset pair into `cmd.text`,
    /// either order — same contract as
    /// [`crate::primitives::command_line::CommandLineLayout::selection_bounds`],
    /// which supplies the rect this paints). `None` (or an empty/
    /// zero-width range) paints identically to `draw_command_line`.
    ///
    /// This is a **new method, not a new `CommandLine` field or a changed
    /// `draw_command_line` signature** — `CommandLine` is an all-`pub`-field,
    /// exhaustively-constructed-by-consumers primitive (see
    /// `crate::primitives::text_input`'s module doc for why that makes a
    /// field addition breaking under `PRIMITIVE_RULES.md` rule 8), so the
    /// selection a host is tracking is threaded through as an argument
    /// instead — the same non-breaking shape `TextInput`/`TextEditor`
    /// established.
    fn draw_command_line_selection(
        &mut self,
        rect: Rect,
        cmd: &CommandLine,
        selection: Option<(usize, usize)>,
    );

    /// Compute the click/selection layout `draw_command_line` paints from.
    /// Hosts call this to hit-test a click to a **byte offset** in
    /// `cmd.text` (`CommandLineLayout::hit_test`) and to turn a selection
    /// range back into a paintable rect
    /// (`CommandLineLayout::selection_bounds`), without re-deriving glyph
    /// metrics or repainting. Every backend exposes the same
    /// character-offset mapping, so a host can share one selection
    /// implementation across all of them.
    ///
    /// Coordinate frame: **ABSOLUTE** — shifted by `rect.x` / `rect.y`;
    /// callers compare directly against raw click coordinates, matching
    /// [`Self::text_input_layout`].
    fn command_line_layout(&self, rect: Rect, cmd: &CommandLine) -> CommandLineLayout;

    /// Compute the text-display layout the rasteriser would produce for
    /// `td` in `rect`, using the backend's native metrics. Hosts call
    /// this to drive hit-testing for scrollbar drag interaction without
    /// re-deriving metrics — paint and click consume one layout per
    /// frame, the source-of-truth contract.
    ///
    /// Coordinate frame: **LOCAL** — relative to `rect`'s origin.
    fn text_display_layout(&self, rect: Rect, td: &TextDisplay) -> TextDisplayLayout;

    /// Draw a [`TextInput`] (multi-line text entry) and return the
    /// resolved layout for hit-testing. Backends paint the border,
    /// text lines, cursor, and placeholder (when active).
    ///
    /// Coordinate frame: **ABSOLUTE** — `content_bounds` / hit regions
    /// are shifted by `rect.x` / `rect.y`, matching [`Self::text_input_layout`].
    fn draw_text_input(&mut self, rect: Rect, ti: &TextInput) -> TextInputLayout;

    /// Compute the layout `draw_text_input` would produce. Used by
    /// hosts to route clicks without re-rendering.
    ///
    /// Coordinate frame: **ABSOLUTE** — shifted by `rect.x` / `rect.y`;
    /// callers compare directly against raw click coordinates.
    fn text_input_layout(&self, rect: Rect, ti: &TextInput) -> TextInputLayout;

    /// Draw a [`NumberInput`] at its caller-resolved `layout`: the text
    /// area plus the increment/decrement stepper buttons. The caller
    /// computes `layout` itself via [`NumberInput::layout`] — no
    /// separate `number_input_layout` accessor exists, mirroring
    /// [`Self::draw_tooltip`] and [`Self::draw_completions`], whose
    /// layouts are likewise host-resolved rather than backend-resolved.
    ///
    /// Required, no default (`PRIMITIVE_RULES.md` rule 7): every
    /// in-tree backend must rasterise this primitive itself rather than
    /// silently painting nothing.
    fn draw_number_input(&mut self, number_input: &NumberInput, layout: &NumberInputLayout);

    /// Draw a [`ComboBox`] at its caller-resolved `layout`: the field
    /// plus, when open, the filtered dropdown. The caller computes
    /// `layout` itself via [`ComboBox::layout`] — no separate
    /// `combo_box_layout` accessor exists, same host-resolves-layout
    /// shape as [`Self::draw_number_input`].
    ///
    /// Required, no default (`PRIMITIVE_RULES.md` rule 7) — same
    /// "every backend must rasterise it" reasoning as
    /// [`Self::draw_number_input`].
    fn draw_combo_box(&mut self, combo_box: &ComboBox, layout: &ComboBoxLayout);

    /// Draw a [`DatePicker`] at its caller-resolved `layout`: the
    /// month/year header with prev/next controls, the 42-cell day grid,
    /// and — when `layout.time_bounds` is `Some` — the time field. The
    /// caller computes `layout` itself via [`DatePicker::layout`], same
    /// host-resolves-layout shape as [`Self::draw_combo_box`].
    ///
    /// Required, no default (`PRIMITIVE_RULES.md` rule 7) — same
    /// "every backend must rasterise it" reasoning as
    /// [`Self::draw_combo_box`].
    fn draw_date_picker(&mut self, date_picker: &DatePicker, layout: &DatePickerLayout);

    /// Draw a [`Tooltip`] popup at its caller-resolved layout, with the
    /// default chrome ([`crate::TooltipBorder::Full`], no title). The
    /// caller computes anchor + viewport + content measurement and
    /// asks `tooltip.layout(...)` for the bounds. Tooltips are
    /// non-interactive — no hit data returned.
    ///
    /// To ask for a different border, or for a title in the top rule,
    /// call [`Backend::draw_tooltip_with_chrome`].
    fn draw_tooltip(&mut self, tooltip: &Tooltip, layout: &TooltipLayout);

    /// Draw a [`Tooltip`] popup with an explicit [`TooltipChrome`]
    /// request: which border to stroke (`Sides` / `Full` / `None`) and an
    /// optional title to embed in `Full`'s top rule.
    ///
    /// Added rather than folded into [`Backend::draw_tooltip`]'s
    /// signature, and given a default body, so it breaks no existing
    /// `Backend` implementor and no existing call site — see
    /// `primitives::tooltip`'s module doc.
    ///
    /// The default body **ignores `chrome`** and delegates to
    /// `draw_tooltip`, i.e. renders `TooltipChrome::default()`. That is
    /// the correct fallback for a backend that has no chrome vocabulary
    /// of its own, but it does mean a `Sides`/`None`/title request is
    /// silently dropped by any backend that hasn't overridden this.
    /// The TUI, GTK and macOS backends all override it and honour the
    /// request in full.
    fn draw_tooltip_with_chrome(
        &mut self,
        tooltip: &Tooltip,
        layout: &TooltipLayout,
        chrome: &TooltipChrome,
    ) {
        let _ = chrome;
        self.draw_tooltip(tooltip, layout);
    }

    /// Draw a [`ContextMenu`] popup at its caller-resolved layout.
    /// Returns the per-clickable-item hit rectangles + their
    /// `WidgetId`s so the caller's click handler can resolve mouse
    /// events without re-running layout.
    fn draw_context_menu(
        &mut self,
        menu: &ContextMenu,
        layout: &ContextMenuLayout,
    ) -> Vec<(Rect, WidgetId)>;

    /// Draw a [`ContextMenu`] popup with an optional [`ContextMenuGlyphs`]
    /// override for the checked-item check mark and submenu pull-right
    /// arrow.
    ///
    /// Added rather than folded into [`Self::draw_context_menu`]'s
    /// signature, and given a default body, so it breaks no existing
    /// `Backend` implementor and no existing call site.
    ///
    /// The default body **ignores `glyphs`** and delegates to
    /// [`Self::draw_context_menu`], i.e. renders the default check mark
    /// and submenu arrow. That is the correct fallback for a backend
    /// that hasn't opted in to overrides yet. The TUI backend overrides
    /// it and honours `glyphs` in full.
    fn draw_context_menu_with_glyphs(
        &mut self,
        menu: &ContextMenu,
        layout: &ContextMenuLayout,
        glyphs: Option<&ContextMenuGlyphs>,
    ) -> Vec<(Rect, WidgetId)> {
        let _ = glyphs;
        self.draw_context_menu(menu, layout)
    }

    /// Draw a [`Dialog`] popup at its caller-resolved layout. Returns
    /// the per-button hit rectangles in the same order as
    /// `dialog.buttons`'s visible entries so the caller's click
    /// handler can resolve a click to a button without re-running
    /// layout. Mirrors [`draw_context_menu`](Self::draw_context_menu).
    fn draw_dialog(&mut self, dialog: &Dialog, layout: &DialogLayout) -> Vec<Rect>;

    /// Draw a [`Float`]'s chrome — background fill + optional border
    /// stroke — at its caller-resolved layout. Like
    /// [`Self::draw_tooltip`]/[`Self::draw_context_menu`]/
    /// [`Self::draw_dialog`] above, the caller computes the layout
    /// itself (`float.layout(viewport, measure)`, see [`Float`]'s own
    /// module doc) rather than this trait exposing a separate
    /// `float_layout` method — there is nothing backend-specific left
    /// to compute once the caller has resolved the anchor.
    ///
    /// **Content is NOT painted here.** A `Float` is pure chrome, same
    /// contract as [`Self::draw_panel`] — the host paints its own
    /// content (a tree, a list, a form, plain text — whatever the
    /// which-key hint / jump label / sticky header / floating terminal
    /// actually needs) into `layout.content_bounds` after this call
    /// returns.
    ///
    /// No default impl — every backend implementer sees this as a
    /// compile error, same as [`Self::draw_image`] (`PRIMITIVE_RULES.md`
    /// rule 7). Shared across GTK/macOS/Win via
    /// [`crate::primitives::float::native_surface_paint::paint`], the
    /// same zero-backend-specific-policy pattern as `Canvas`/`Panel`;
    /// TUI has its own cell-based rasteriser in
    /// [`crate::tui::draw_float`].
    fn draw_float(&mut self, float: &Float, layout: &FloatLayout);

    /// Draw a [`MultiSectionView`]. The backend computes the layout
    /// internally with native metrics (cells for TUI, pixels +
    /// `line_height` for GTK) and dispatches each section's body to
    /// the appropriate inner-primitive painter (tree, list, etc.).
    /// Hosts that need to hit-test clicks call [`Self::msv_layout`]
    /// for the same layout instance.
    fn draw_multi_section_view(&mut self, rect: Rect, view: &MultiSectionView);

    /// Compute the layout the rasteriser would produce for `view` in
    /// `rect`, using the backend's native metrics. Hosts call this
    /// to drive hit-testing without re-deriving metrics — paint and
    /// click consume one layout per frame, the source-of-truth
    /// contract `MultiSectionView` exists to enforce.
    ///
    /// Coordinate frame: **ABSOLUTE** — `hit_regions` / body bounds are
    /// shifted by `rect.x` / `rect.y`; callers compare them directly
    /// against raw click coordinates.
    fn msv_layout(&self, rect: Rect, view: &MultiSectionView) -> MultiSectionViewLayout;

    /// Return the layout metrics this backend uses for MSV layout.
    /// Compose helpers cache these to compute layouts without a Backend
    /// reference at event-handling time.
    fn msv_metrics(&self) -> MsvLayoutMetrics;

    /// Compute the tree layout the rasteriser would produce. Used by
    /// hosts (especially MSV consumers) to resolve body clicks down
    /// to row indices without re-deriving the row pitch (1 cell
    /// uniform on TUI; `1.0×`/`1.4×` line_height by `Decoration` on
    /// GTK).
    ///
    /// Coordinate frame: **LOCAL** — `visible_rows.bounds` / `hit_regions`
    /// are relative to `rect`'s origin (`(0, 0)` at `rect`'s top-left);
    /// callers subtract `rect.x` / `rect.y` from absolute click
    /// coordinates before calling `hit_test` (see
    /// `primitives::layout_metrics::tree_layout`'s doc for why this frame
    /// is load-bearing).
    fn tree_layout(&self, rect: Rect, tree: &TreeView) -> TreeViewLayout;

    /// Vertical scrollbar geometry for `tree` rendered into `rect`, or
    /// `None` when the tree is empty or all rows fit. Each backend
    /// supplies its native row height; the resolved track + thumb are the
    /// same values a rasteriser would paint, so consumers hit-test the
    /// returned thumb to implement drag without re-deriving geometry.
    ///
    /// This mirrors [`Backend::list_hscrollbar`] /
    /// [`Backend::list_vscrollbar`]'s already-established shape: a
    /// layout-level scroll extent the host hit-tests against, passed to
    /// the existing [`Scrollbar`] primitive. Whether the host also needs
    /// to *paint* a scrollbar from this geometry via
    /// [`Backend::draw_scrollbar`] depends on
    /// [`Self::tree_paints_own_scrollbar`]: on backends where
    /// [`Self::draw_tree`] already paints an overlay scrollbar, this
    /// geometry exists purely for hit-testing and the host must not
    /// paint its own on top (that would double-paint it) — see
    /// [`TreeView::vscrollbar`].
    fn tree_vscrollbar(&self, rect: Rect, tree: &TreeView) -> Option<Scrollbar>;

    /// Whether [`Self::draw_tree`] already paints a vertical scrollbar
    /// overlay for an overflowing tree, so hosts (e.g.
    /// [`crate::compose::TreeController`]) must not also reserve a
    /// column for one or separately call [`Self::draw_scrollbar`] with
    /// the geometry from [`Self::tree_vscrollbar`] — doing so paints the
    /// scrollbar twice.
    ///
    /// GTK, macOS and Win paint the overlay inside `draw_tree` itself and
    /// override this to `true`. TUI has no such overlay — scrolling a
    /// tree in a terminal has no spare pixels for one — so it keeps the
    /// default `false` and relies on the host to reserve a column and
    /// paint the scrollbar explicitly.
    fn tree_paints_own_scrollbar(&self) -> bool {
        false
    }

    /// Compute the form layout the rasteriser would produce for `form`
    /// in `rect`, using the backend's native metrics. Hosts call this
    /// to drive hit-testing — especially for `ToggleGroup` and
    /// `ButtonRow` fields where per-item hit regions depend on
    /// backend-specific text measurement.
    ///
    /// Coordinate frame: **LOCAL** — relative to `rect`'s origin.
    fn form_layout(&self, rect: Rect, form: &Form) -> FormLayout;

    /// Draw an [`Editor`]. Returns paint-side data the host needs
    /// for chrome alignment (cursor pixel position for caret blink
    /// overlays, etc.). Asymmetric across backends: TUI populates
    /// the result; GTK paints its own caret and returns the default.
    fn draw_editor(&mut self, rect: Rect, editor: &Editor) -> EditorPaintResult;

    /// Set the width, in this backend's native pixel units, of the
    /// vertical scrollbar column every subsequent [`Self::draw_editor`]
    /// (and [`Self::editor_layout`]) reserves and paints for an
    /// overflowing buffer. `None` restores the default: a column one
    /// [`Self::char_width`] wide.
    ///
    /// GUI hosts call this once at setup — e.g. `Some(14.0)` to match
    /// VS Code's fixed 14px editor scrollbar regardless of font size.
    /// See [`Editor::layout_with_options_and_v_scrollbar_w`] for the
    /// geometry. The GTK, macOS and Win backends honour it; TUI keeps its
    /// one-cell scrollbar column and ignores it (the default body is a
    /// no-op).
    fn set_editor_v_scrollbar_width(&mut self, _px: Option<f32>) {}

    /// The width last set through [`Self::set_editor_v_scrollbar_width`],
    /// or `None` when unset or ignored by this backend (the default
    /// body). [`Self::editor_layout`] reads this so hit-testing agrees
    /// with what [`Self::draw_editor`] painted.
    fn editor_v_scrollbar_width(&self) -> Option<f32> {
        None
    }

    /// Set the width, in this backend's native pixel units, of a strip
    /// every subsequent [`Self::draw_editor`] (and [`Self::editor_layout`])
    /// reserves between the editor's text area and its vertical
    /// scrollbar. `None` (the default) reserves nothing — `text_bounds`
    /// runs flush to the scrollbar exactly as before this method existed.
    ///
    /// See [`Editor::layout_with_options_and_reserve`]'s `right_reserve_w`
    /// doc for the exact geometry: the vertical scrollbar keeps hugging
    /// the viewport's true right edge regardless of this value, and the
    /// reserved strip is the gap between the narrowed text area and that
    /// scrollbar. A host docking a minimap strip next to the editor calls
    /// this instead of narrowing the `rect` it hands to `draw_editor` —
    /// narrowing `rect` directly would relocate the scrollbar along with
    /// the minimap, which is the behaviour this method exists to avoid.
    fn set_editor_right_reserve_w(&mut self, _px: Option<f32>) {}

    /// The width last set through [`Self::set_editor_right_reserve_w`],
    /// or `None` when unset or ignored by this backend (the default
    /// body). [`Self::editor_layout`] reads this so hit-testing agrees
    /// with what [`Self::draw_editor`] painted.
    fn editor_right_reserve_w(&self) -> Option<f32> {
        None
    }

    /// Compute the editor viewport layout (gutter / text / scrollbar
    /// bounds) without painting — the no-paint twin of [`Self::draw_editor`].
    /// Uses this backend's own [`Self::char_width`] /
    /// [`Self::line_height`] as the cell metrics — the same values
    /// `draw_editor` resolves them to on every backend that implements it
    /// today (`GtkBackend`/`WinBackend`/`MacBackend` all pass
    /// `current_char_width` / `current_line_height`, which is exactly what
    /// [`Self::char_width`] / [`Self::line_height`] return; TUI's fixed
    /// `(1.0, 1.0)` matches its uniform cell grid).
    ///
    /// Coordinate frame: **ABSOLUTE** — `text_bounds` / `gutter_bounds` /
    /// scrollbar bounds are shifted by `rect.x` / `rect.y`, matching
    /// [`Self::editor_col_at_x`]'s "x is an absolute (surface-space)
    /// coordinate" contract.
    ///
    /// Default body: uniform for every backend, since it's a pure
    /// function of the two metrics above — no backend needs to override
    /// this.
    ///
    /// **Caller invariant:** `rect` here must be the same rect the
    /// backend actually paints with. This holds by construction on TUI
    /// (`draw_editor` takes the `rect` argument directly), but on GTK
    /// `GtkBackend::draw_editor` ignores its own `rect` parameter
    /// (`let _ = rect;`) and paints at `editor.rect` instead
    /// (`src/gtk/editor.rs`). The two happen to always match in every
    /// call site today, but nothing enforces it — pass a `rect` that
    /// diverges from `editor.rect` and this method's return value quietly
    /// stops matching what GTK painted.
    fn editor_layout(&self, rect: Rect, editor: &Editor) -> EditorLayout {
        editor.layout_with_options_and_reserve(
            rect,
            self.char_width(),
            self.line_height(),
            crate::primitives::editor::EditorPaintOptions::default(),
            self.editor_v_scrollbar_width(),
            self.editor_right_reserve_w().unwrap_or(0.0),
        )
    }

    /// Resolve a click x-coordinate to a text column on one visible row
    /// of an [`Editor`], honouring the same glyph-advance metrics
    /// [`Self::draw_editor`] painted that row with (bold / italic /
    /// `font_scale` spans on GTK's Pango layout; uniform monospace
    /// cells on TUI) — keeping paint and click resolution in agreement.
    ///
    /// `layout` is the [`EditorLayout`] `editor.layout(...)` produced
    /// for the same viewport/metrics the caller painted with.
    /// `view_row` indexes into `editor.lines` (0 = topmost visible row
    /// — the same row [`crate::primitives::editor::EditorLayout::hit_test`]
    /// resolves from a y-coordinate). `x` is an absolute (surface-space)
    /// coordinate, matching the `x` passed to `hit_test`.
    ///
    /// Returns the resolved character column *within the buffer line*
    /// (already folds in `layout.scroll_left` and the row's
    /// `segment_col_offset` for wrap-continuation rows) — callers
    /// combine it with `hit_test`'s resolved `line` to get a full
    /// buffer position:
    ///
    /// ```ignore
    /// if let EditorHit::BufferPos { line, .. } = layout.hit_test(x, y) {
    ///     let view_row = line - layout.scroll_top;
    ///     let col = backend.editor_col_at_x(&layout, &editor, view_row, x);
    ///     // (line, col) is the resolved buffer position.
    /// }
    /// ```
    ///
    /// Default implementation delegates to
    /// [`EditorLayout::col_at_x`] (uniform monospace division) —
    /// correct for TUI and any backend whose configured font renders
    /// every glyph at the same advance width. `GtkBackend` overrides
    /// this with an exact Pango `xy_to_index` resolution against the
    /// same per-span-attributed layout `draw_editor` painted with, so
    /// a line containing bold / italic / `font_scale` spans (e.g. a
    /// markdown heading) resolves clicks against its *actual* painted
    /// glyph positions instead of a uniform grid.
    fn editor_col_at_x(
        &self,
        layout: &EditorLayout,
        editor: &Editor,
        view_row: usize,
        x: f32,
    ) -> usize {
        layout.col_at_x(editor, view_row, x)
    }

    /// Drive the terminal/OS **hardware** caret to match an
    /// [`Editor`]'s [`EditorCursorShape`] — block for Normal/Visual, bar
    /// for Insert, underline for a pending replace-char command. This is
    /// a distinct surface from the caret [`Self::draw_editor`] *paints*
    /// into the frame buffer: GTK/Win/macOS already paint their own caret
    /// there and have no separate hardware cursor to steer, so the
    /// default here is a genuine, permanent no-op for them — not a gap
    /// to fill in later, the same "structurally absent, not merely
    /// unimplemented" reasoning [`Backend::tray`] uses for TUI.
    ///
    /// **TUI is the one backend that overrides this**, emitting
    /// DECSCUSR (`ESC [ n SP q`) via crossterm's `SetCursorStyle` to
    /// steer the terminal emulator's own cursor glyph — the one place
    /// that writes this escape sequence, so consumer code never has to.
    ///
    /// Not [`Self::draw_editor`]'s job to call this itself: painting
    /// happens every frame regardless of whether the shape changed,
    /// while retitling the hardware caret is a comparatively heavy
    /// terminal write hosts should only issue on an actual shape
    /// change. Callers own that debouncing (see
    /// `crate::tui::testing` for why driver tests never exercise the
    /// write path at all — there is no real terminal under
    /// `TestBackend`).
    fn set_caret_shape(&mut self, _shape: EditorCursorShape) {}

    /// Draw a [`MessageList`] (chat-style streaming row history).
    /// The backend pulls panel background from its current theme;
    /// hosts that want a custom panel bg compose the primitive
    /// directly via the backend crate's free function.
    fn draw_message_list(&mut self, rect: Rect, list: &MessageList);

    /// Draw a [`RichTextPopup`] at its caller-resolved layout, in the
    /// chrome (UI) font — [`crate::ChromePrimitive::RichTextPopup`]'s
    /// classification. Mirrors [`draw_tooltip`](Self::draw_tooltip):
    /// host computes anchor + viewport + measure and asks
    /// `popup.layout(...)` for the bounds. Link hit regions are
    /// tracked on the backend's internal state; hosts that need them
    /// query via the backend-specific accessor today (link-hit-test
    /// trait method is a follow-up).
    ///
    /// To render editor content (hover docs, signatures, diagnostics)
    /// in the editor's own font instead, call
    /// [`Backend::draw_rich_text_popup_with_font_role`] with
    /// [`crate::FontRole::Editor`].
    fn draw_rich_text_popup(&mut self, popup: &RichTextPopup, layout: &RichTextPopupLayout);

    /// Draw a [`RichTextPopup`] with an explicit [`crate::FontRole`]
    /// request: paint its content in the chrome (UI) font or the
    /// editor's own monospace font, instead of always the chrome font
    /// [`Self::draw_rich_text_popup`] uses. Lets a consumer render
    /// editor content (hover docs, signatures, diagnostics) with the
    /// editor's metrics so link hit-testing stays in sync with the
    /// glyphs actually painted, while another popup instance (e.g.
    /// settings help text) keeps the chrome font.
    ///
    /// Added rather than folded into [`Self::draw_rich_text_popup`]'s
    /// signature, and given a default body, so that this capability
    /// breaks no existing `Backend` implementor and no existing call
    /// site — a new required field on [`RichTextPopup`] itself would
    /// break every downstream consumer constructing one with an
    /// exhaustive literal (see `CLAUDE.md`'s *Downstream consumers*
    /// section). Mirrors [`Self::draw_tooltip_with_chrome`]'s
    /// [`crate::TooltipChrome`] precedent for the same reason.
    ///
    /// The default body **ignores `role`** and delegates to
    /// `draw_rich_text_popup`, i.e. always paints the chrome font. That
    /// is the correct fallback for a backend with no font-role
    /// vocabulary of its own. GTK, macOS and Win-GUI all override it and
    /// honour [`crate::FontRole::Editor`]; TUI has one font per cell and
    /// keeps the default.
    fn draw_rich_text_popup_with_font_role(
        &mut self,
        popup: &RichTextPopup,
        layout: &RichTextPopupLayout,
        role: crate::FontRole,
    ) {
        let _ = role;
        self.draw_rich_text_popup(popup, layout);
    }

    /// Draw a [`FindReplacePanel`] (find/replace overlay sitting
    /// above the editor). The backend pulls the editor-relative
    /// origin from `rect.x` (TUI's `editor_left` parameter is
    /// derived from `rect`); hosts that want a non-default offset
    /// compose the panel into a sub-rect.
    fn draw_find_replace(&mut self, rect: Rect, panel: &FindReplacePanel);

    /// Draw a [`Completions`] popup at its caller-resolved layout.
    /// Mirrors [`draw_tooltip`](Self::draw_tooltip): host computes
    /// anchor + viewport + measure and asks `completions.layout(...)`
    /// for the bounds.
    fn draw_completions(&mut self, completions: &Completions, layout: &CompletionsLayout);

    /// Draw a [`Scrollbar`] (standalone primitive, vs the
    /// per-section scrollbars MSV paints internally). The backend
    /// pulls cell/pixel background from its current theme.
    fn draw_scrollbar(&mut self, rect: Rect, scrollbar: &Scrollbar);

    /// Draw a [`DropOverlay`] on top of the current frame during a
    /// tab drag. Renders the highlight rect (tinted background) and/or
    /// insertion bar (thin line at the drop position).
    fn draw_drop_overlay(&mut self, overlay: &DropOverlay);

    /// Draw a [`MenuBar`]. The backend computes the layout internally
    /// with native metrics (cells for TUI, Pango pixels for GTK) and
    /// returns the [`MenuBarLayout`] so hosts can route clicks via
    /// `layout.hit_test(x, y)` without re-deriving metrics. Same
    /// coordinate frame as [`Self::menu_bar_layout`] (ABSOLUTE).
    fn draw_menu_bar(&mut self, rect: Rect, bar: &MenuBar) -> MenuBarLayout;

    /// Compute the menu-bar layout the rasteriser would produce for
    /// `bar` in `rect`, using the backend's native metrics. Hosts
    /// call this in click handlers to resolve hits against the same
    /// layout that was painted — never re-derive with a hand-rolled
    /// measurer.
    ///
    /// Coordinate frame: **ABSOLUTE** — shifted by `rect.x` / `rect.y`.
    fn menu_bar_layout(&self, rect: Rect, bar: &MenuBar) -> MenuBarLayout;

    /// Draw a [`Split`] divider. The backend computes the layout with
    /// its native divider thickness (1 cell for TUI, ~4px for GTK)
    /// and returns the [`SplitLayout`] so hosts can route clicks and
    /// drive drag operations. Pane content is NOT drawn — hosts paint
    /// into `layout.first_bounds` / `layout.second_bounds`. Same
    /// coordinate frame as [`Self::split_layout`] (ABSOLUTE).
    fn draw_split(&mut self, rect: Rect, split: &Split) -> SplitLayout;

    /// Compute the split layout without painting. Hosts call this in
    /// drag handlers to recompute the ratio from cursor position.
    ///
    /// Coordinate frame: **ABSOLUTE** — `first_bounds` / `divider_bounds`
    /// / `second_bounds` are shifted by `rect.x` / `rect.y`.
    fn split_layout(&self, rect: Rect, split: &Split) -> SplitLayout;

    /// Draw a [`SplitTree`]'s dividers. The backend computes the
    /// layout with its native divider thickness (1 cell for TUI, ~4px
    /// for GTK) and returns the [`SplitTreeLayout`] so hosts can route
    /// clicks (via [`SplitTreeLayout::hit_test_divider`] /
    /// [`SplitTreeLayout::hit_test_divider_cell`] /
    /// [`SplitTreeLayout::hit_test_leaf`]) and drive drag operations
    /// via [`crate::DragTarget::SplitDivider`]. Leaf content is NOT
    /// drawn — hosts paint into each `layout.leaves[i].1` rect. Same
    /// coordinate frame as [`Self::split_tree_layout`] (ABSOLUTE).
    fn draw_split_tree(&mut self, rect: Rect, tree: &SplitTree) -> SplitTreeLayout;

    /// Compute the split-tree layout without painting. Hosts call this
    /// in drag handlers to recompute a divider's ratio from cursor
    /// position without re-painting.
    ///
    /// Coordinate frame: **ABSOLUTE** — leaf / divider bounds are
    /// shifted by `rect.x` / `rect.y`.
    fn split_tree_layout(&self, rect: Rect, tree: &SplitTree) -> SplitTreeLayout;

    /// Draw a [`Panel`] chrome (title bar + action buttons). The
    /// backend computes the layout with its native title-bar height
    /// (1 cell for TUI, line_height for GTK) and returns the
    /// [`PanelLayout`] so hosts can route clicks to actions, title
    /// bar, or content. Content is NOT drawn — hosts paint into
    /// `layout.content_bounds`. Same coordinate frame as
    /// [`Self::panel_layout`] (ABSOLUTE).
    fn draw_panel(&mut self, rect: Rect, panel: &Panel) -> PanelLayout;

    /// Compute the panel layout without painting. Hosts call this in
    /// click handlers to resolve hits without re-deriving metrics.
    ///
    /// Coordinate frame: **ABSOLUTE** — `title_bar_bounds` / action /
    /// `content_bounds` are shifted by `rect.x` / `rect.y`.
    fn panel_layout(&self, rect: Rect, panel: &Panel) -> PanelLayout;

    /// Draw a [`ToastOverlay`] overlay. The backend computes the layout
    /// with its native toast dimensions (cell-width boxes for TUI,
    /// pixel boxes for GTK) and returns the [`ToastStackLayout`] so
    /// hosts can route clicks to dismiss, action, or body. Same
    /// coordinate frame as [`Self::toast_stack_layout`] (ABSOLUTE).
    fn draw_toast_overlay(&mut self, rect: Rect, stack: &ToastOverlay) -> ToastStackLayout;

    /// Compute the toast-stack layout without painting. Hosts call
    /// this in click handlers to resolve hits.
    ///
    /// Coordinate frame: **ABSOLUTE** — shifted by `rect.x` / `rect.y`.
    fn toast_stack_layout(&self, rect: Rect, stack: &ToastOverlay) -> ToastStackLayout;

    /// Draw a [`PipelineView`] (horizontal multi-stage workflow widget).
    /// The backend paints stage boxes, status icons, labels, optional
    /// action buttons, and arrow connectors. Returns the
    /// [`PipelineViewLayout`] so hosts can route clicks via
    /// `layout.hit_test(x, y)` without re-deriving metrics. Same
    /// coordinate frame as [`Self::pipeline_view_layout`] (ABSOLUTE).
    fn draw_pipeline_view(&mut self, rect: Rect, view: &PipelineView) -> PipelineViewLayout;

    /// Compute pipeline-view layout without painting. Hosts call this in
    /// click handlers to resolve hits against the same layout that was
    /// painted — never re-derive with a hand-rolled measurer.
    ///
    /// Coordinate frame: **ABSOLUTE** — shifted by `rect.x` / `rect.y`.
    fn pipeline_view_layout(&self, rect: Rect, view: &PipelineView) -> PipelineViewLayout;

    /// Draw a [`DiffView`] (two-pane side-by-side or unified diff viewer).
    /// Hunks are app-computed via [`crate::diff::compute_hunks`]; the backend
    /// only rasterises. Returns [`DiffViewLayout`] for scroll clamping.
    fn draw_diff_view(&mut self, rect: Rect, view: &DiffView) -> DiffViewLayout;

    /// Compute the diff-view layout without painting — the no-paint twin
    /// of [`Self::draw_diff_view`]. `visible_rows` uses this
    /// backend's [`Self::line_height`] exactly as every backend's
    /// `draw_diff_view` does today: in [`DiffMode::SideBySide`] one
    /// `line_height` band is reserved for the header row when either
    /// label is set (`view.left_label` / `view.right_label`); in
    /// [`DiffMode::Unified`] every row — including each hunk's `@@ … @@`
    /// header — scrolls as content, so no band is reserved.
    /// `total_rows` matches [`DiffViewLayout::total_rows`]'s documented
    /// contract (`view.total_rows()` in side-by-side mode, `+
    /// hunk_count` in unified mode for the synthesized header lines).
    ///
    /// Frame: no coordinates are returned — `visible_rows` /
    /// `total_rows` are counts, not positions — so there is no LOCAL vs
    /// ABSOLUTE distinction to state.
    ///
    /// Default body: uniform for every backend, since it's a pure
    /// function of `rect`, `view`, and `Self::line_height` — no backend
    /// needs to override this.
    fn diff_view_layout(&self, rect: Rect, view: &DiffView) -> DiffViewLayout {
        if rect.width <= 0.0 || rect.height <= 0.0 {
            return DiffViewLayout {
                visible_rows: 0,
                total_rows: view.total_rows(),
            };
        }
        let lh = self.line_height();
        match view.mode {
            DiffMode::SideBySide => {
                let has_header = view.left_label.is_some() || view.right_label.is_some();
                let header_h = if has_header { lh } else { 0.0 };
                let content_h = (rect.height - header_h).max(0.0);
                let visible_rows = if lh > 0.0 {
                    (content_h / lh).floor() as usize
                } else {
                    0
                };
                DiffViewLayout {
                    visible_rows,
                    total_rows: view.total_rows(),
                }
            }
            DiffMode::Unified => {
                let visible_rows = if lh > 0.0 {
                    (rect.height / lh).floor() as usize
                } else {
                    0
                };
                let total_rows: usize = view.hunks.iter().map(|h| h.rows.len() + 1).sum();
                DiffViewLayout {
                    visible_rows,
                    total_rows,
                }
            }
        }
    }

    /// Draw a [`ProgressBar`]. The backend paints the track, fill,
    /// optional label, and optional cancel affordance. Returns the
    /// [`ProgressBarLayout`] so hosts can route clicks. Same
    /// coordinate frame as [`Self::progress_layout`] (ABSOLUTE).
    fn draw_progress(&mut self, rect: Rect, bar: &ProgressBar) -> ProgressBarLayout;

    /// Compute progress-bar layout without painting.
    ///
    /// Coordinate frame: **ABSOLUTE** — shifted by `rect.x` / `rect.y`.
    fn progress_layout(&self, rect: Rect, bar: &ProgressBar) -> ProgressBarLayout;

    /// Draw a [`Spinner`] (indeterminate activity indicator). Returns
    /// the [`SpinnerLayout`] for host hit-testing. Same coordinate
    /// frame as [`Self::spinner_layout`] (ABSOLUTE).
    fn draw_spinner(&mut self, rect: Rect, spinner: &Spinner) -> SpinnerLayout;

    /// Compute spinner layout without painting.
    ///
    /// Coordinate frame: **ABSOLUTE** — shifted by `rect.x` / `rect.y`.
    fn spinner_layout(&self, rect: Rect, spinner: &Spinner) -> SpinnerLayout;

    /// Draw a [`Button`]. Returns the [`ButtonLayout`] so hosts can
    /// route clicks. Same coordinate frame as [`Self::button_layout`]
    /// (ABSOLUTE).
    fn draw_button(&mut self, rect: Rect, button: &Button) -> ButtonLayout;

    /// Compute button layout without painting.
    ///
    /// Coordinate frame: **ABSOLUTE** — shifted by `rect.x` / `rect.y`.
    fn button_layout(&self, rect: Rect, button: &Button) -> ButtonLayout;

    /// Draw a [`RadioGroup`] (a vertical list of mutually-exclusive
    /// options). Returns the [`RadioGroupLayout`] so hosts can route
    /// clicks. Same coordinate frame as [`Self::radio_group_layout`]
    /// (ABSOLUTE).
    fn draw_radio_group(&mut self, rect: Rect, group: &RadioGroup) -> RadioGroupLayout;

    /// Compute radio-group layout without painting. Each backend
    /// supplies its own per-option measure (text extents, cell counts,
    /// or a nominal fallback) — see the implementation for the shape.
    ///
    /// Coordinate frame: **ABSOLUTE** — shifted by `rect.x` / `rect.y`.
    fn radio_group_layout(&self, rect: Rect, group: &RadioGroup) -> RadioGroupLayout;

    /// Draw a [`Switch`] (a standalone on/off toggle). Returns the
    /// [`SwitchLayout`] so hosts can route clicks. Same coordinate
    /// frame as [`Self::switch_layout`] (ABSOLUTE).
    fn draw_switch(&mut self, rect: Rect, switch: &Switch) -> SwitchLayout;

    /// Compute switch layout without painting.
    ///
    /// Coordinate frame: **ABSOLUTE** — shifted by `rect.x` / `rect.y`.
    fn switch_layout(&self, rect: Rect, switch: &Switch) -> SwitchLayout;

    /// Draw a [`CommandCenter`] (nav arrows + search box). Returns the
    /// [`CommandCenterLayout`] so hosts can route clicks. Same
    /// coordinate frame as [`Self::command_center_layout`] (ABSOLUTE).
    fn draw_command_center(&mut self, rect: Rect, cc: &CommandCenter) -> CommandCenterLayout;

    /// Compute command-center layout without painting.
    ///
    /// Coordinate frame: **ABSOLUTE** — shifted by `rect.x` / `rect.y`.
    fn command_center_layout(&self, rect: Rect, cc: &CommandCenter) -> CommandCenterLayout;

    /// Draw a [`Toolbar`] (horizontal strip of action buttons above a
    /// content area — distinct from `StatusBar` which is read-only),
    /// reading hover/pressed state from a single [`InteractionState`]
    /// keyed by [`WidgetId`].
    ///
    /// The rasteriser tints the background of the button whose id
    /// matches `interaction.hovered()` / `interaction.pressed()`.
    /// Returns the [`ToolbarLayout`] so hosts can route clicks via
    /// `layout.hit_test(x, y)` without re-deriving metrics. Same
    /// coordinate frame as [`Self::toolbar_layout`] (ABSOLUTE).
    ///
    /// Equivalent to [`Self::draw_toolbar_with_options`] with
    /// [`ToolbarPaintOptions::default()`] — kept as a separate,
    /// **unchanged** method (rather than growing this one's argument
    /// list) so every existing caller keeps compiling untouched. Both
    /// known downstream consumers call this method with exactly these
    /// three arguments (`coord-tui`'s `app/render.rs` +
    /// `app/dialogs.rs`), so adding a parameter here is an `E0061`
    /// break for them — see [`ToolbarPaintOptions`]'s own doc and
    /// `CLAUDE.md`'s *Downstream consumers* rule 2.
    ///
    /// Backends implement [`Self::draw_toolbar_with_options`]; this is
    /// a forwarding default.
    fn draw_toolbar_interactive(
        &mut self,
        rect: Rect,
        bar: &Toolbar,
        interaction: &InteractionState,
    ) -> ToolbarLayout {
        self.draw_toolbar_with_options(rect, bar, interaction, ToolbarPaintOptions::default())
    }

    /// [`Self::draw_toolbar_interactive`], plus [`ToolbarPaintOptions`]
    /// a host can set to override otherwise-fixed paint decisions —
    /// currently just `valign`, which resolves where button/label text
    /// paints within a slot taller than one text row.
    ///
    /// `Toolbar` itself can't carry this: both known downstream
    /// consumers build it with exhaustive struct literals — see
    /// [`ToolbarPaintOptions`]'s own doc.
    ///
    /// This is the implemented method — every `Backend` writes its
    /// rasteriser here, and [`Self::draw_toolbar_interactive`] forwards
    /// into it with [`ToolbarPaintOptions::default()`] (`ToolbarVAlign::Top`,
    /// byte-identical to the plain paint on a 1-row slot).
    fn draw_toolbar_with_options(
        &mut self,
        rect: Rect,
        bar: &Toolbar,
        interaction: &InteractionState,
        options: ToolbarPaintOptions,
    ) -> ToolbarLayout;

    /// Compute toolbar layout without painting. Hosts call this after
    /// `ScreenLayout::draw()` to recover hit regions for click dispatch.
    ///
    /// Coordinate frame: **ABSOLUTE** — shifted by `rect.x` / `rect.y`.
    fn toolbar_layout(&self, rect: Rect, bar: &Toolbar) -> ToolbarLayout;

    /// Draw a [`SidebarPanel`] — optional header toolbar + content
    /// region. Backends paint the toolbar slot only; the content rect
    /// is returned in `SidebarPanelLayout.content_bounds` for the
    /// host to paint into (tree / list / form / etc). Mirrors the
    /// `Panel` rasteriser contract.
    ///
    /// `interaction`'s hovered / pressed [`WidgetId`]s are forwarded to
    /// the nested toolbar paint for hover / pressed tints. Same
    /// coordinate frame as [`Self::sidebar_panel_layout`]
    /// (ABSOLUTE).
    ///
    /// This is the implemented method.
    fn draw_sidebar_panel_interactive(
        &mut self,
        rect: Rect,
        panel: &SidebarPanel,
        interaction: &InteractionState,
    ) -> SidebarPanelLayout;

    /// Compute sidebar-panel layout without painting. Hosts call this
    /// in click handlers to resolve hits to the toolbar / content /
    /// outside without re-deriving metrics.
    ///
    /// Coordinate frame: **ABSOLUTE** — `content_bounds` / toolbar
    /// bounds are shifted by `rect.x` / `rect.y`.
    fn sidebar_panel_layout(&self, rect: Rect, panel: &SidebarPanel) -> SidebarPanelLayout;

    /// Draw a [`Chart`] (sparkline, line, or bar). `hovered_point`
    /// carries per-frame hover state (series_idx, data_idx) so the
    /// rasteriser can highlight the data point under the cursor.
    /// Returns the [`ChartLayout`] so hosts can route clicks and
    /// resolve nearest-point from mouse position. Same coordinate
    /// frame as [`Self::chart_layout`] (ABSOLUTE).
    fn draw_chart(
        &mut self,
        rect: Rect,
        chart: &Chart,
        hovered_point: Option<(usize, usize)>,
        crosshair_x: Option<f64>,
    ) -> ChartLayout;

    /// Compute chart layout without painting.
    ///
    /// Coordinate frame: **ABSOLUTE** — `bounds` / `hit_regions` /
    /// `data_point_positions` are shifted by `rect.x` / `rect.y`.
    fn chart_layout(&self, rect: Rect, chart: &Chart) -> ChartLayout;

    /// Draw a [`BoardModel`] (kanban/pipeline board widget).
    ///
    /// The backend paints columns side by side, each with a header title
    /// and a vertical stack of card boxes. Each card shows the issue
    /// title, an inline badge row, and an optional `hint` callout strip.
    /// The selected card is highlighted.
    ///
    /// Returns a [`BoardLayout`] so hosts can route clicks via
    /// `layout.hit_test(x, y)` and implement selection-follow clamping
    /// (DataTable pattern: host reads `layout.columns[i].visible_cards`
    /// and adjusts `column.scroll_offset` accordingly).
    ///
    /// No default impl — every backend implementer sees this as a compile
    /// error and fills in a real rasteriser (`PRIMITIVE_RULES.md` rule 7).
    /// A no-op default here would let a backend silently paint an empty
    /// board instead of failing to build.
    fn draw_board(&mut self, rect: Rect, model: &BoardModel) -> BoardLayout;

    /// Compute the board layout without painting — the no-paint twin of
    /// [`Self::draw_board`]. Each backend routes through the exact same
    /// helper `draw_board` calls
    /// internally, using its own [`crate::primitives::board::BoardMeasure`]
    /// (column/card sizing is backend-native, like `TreeStyle::row_height`
    /// — not derivable from [`Self::char_width`] / [`Self::line_height`]
    /// alone), so paint and no-paint can't drift apart.
    ///
    /// Coordinate frame: **ABSOLUTE** — `columns[i].bounds` / card bounds
    /// are shifted by `rect.x` / `rect.y`, matching [`BoardLayout::hit_test`].
    ///
    /// No default impl, same rule-7 reasoning as [`Self::draw_board`]: a
    /// backend that forgets to override this would otherwise silently
    /// report an empty board's worth of hit regions.
    fn board_layout(&self, rect: Rect, model: &BoardModel) -> BoardLayout;

    /// Draw a [`Minimap`] (code-overview density view). GTK and Win-GUI
    /// both tile rows at a fixed pitch and paint one colour block per
    /// non-blank character column ([`crate::MinimapSizing::FixedPitch`]);
    /// TUI packs `U+2800`-block braille dots, also at a fixed pitch — one
    /// cell row per minimap row. All three techniques consume the exact
    /// same [`Minimap`] data — the primitive owns the sampling and
    /// colour-aggregation math (`sample_blocks` / `aggregate_spans`) and
    /// the legibility/render-mode threshold and span-lookup helpers too
    /// (`crate::primitives::minimap`), so no backend re-derives any of it.
    ///
    /// Returns [`MinimapPaintResult`] carrying the resolved
    /// [`MinimapLayout`] so hosts can route clicks via
    /// `result.layout.hit_test(x, y)` without re-deriving geometry.
    /// Same coordinate frame as [`Self::minimap_layout`] (ABSOLUTE).
    ///
    /// No default impl — every backend implementer sees this as a
    /// compile error and fills in a real rasteriser (`PRIMITIVE_RULES.md`
    /// rule 7).
    fn draw_minimap(&mut self, rect: Rect, minimap: &Minimap) -> MinimapPaintResult;

    /// The [`MinimapScale`] [`Self::draw_minimap`]/[`Self::minimap_layout`]
    /// resolve their row pitch (and, for a pixel backend, per-column
    /// width) from. Default-provided, returning [`MinimapScale::One`] —
    /// the fixed pitch every backend paints at unless a host also calls
    /// [`Self::set_minimap_scale`]. TUI's braille rasteriser has no font
    /// to scale and never overrides either method — see
    /// [`crate::primitives::minimap::MinimapScale`]'s doc for why this
    /// lives here rather than as a field on [`Minimap`] itself.
    fn minimap_scale(&self) -> MinimapScale {
        MinimapScale::One
    }

    /// Set the [`MinimapScale`] a later [`Self::draw_minimap`]/
    /// [`Self::minimap_layout`] call resolves its row pitch from. Default
    /// no-op: a backend that never overrides [`Self::minimap_scale`] has
    /// nowhere to store this and nothing reads it back. GTK, Win-GUI, and
    /// macOS override both methods to back a real field; a host picks
    /// VS Code's own default (`MinimapScale::Two`) once, at startup, the
    /// same way it configures `dpi_scale` or the editor font.
    fn set_minimap_scale(&mut self, _scale: MinimapScale) {}

    /// The [`crate::MinimapSizing`] a later [`Self::draw_minimap`]/
    /// [`Self::minimap_layout`] call resolves its row pitch *strategy*
    /// from — orthogonal to [`Self::minimap_scale`], which only picks the
    /// pixel/cell size of one row. Default-provided, returning `None`,
    /// meaning "use this rasteriser's own hardcoded default sizing"
    /// (TUI: [`crate::MinimapSizing::FixedPitch`]`(1.0)`) — a host that
    /// never calls [`Self::set_minimap_sizing`] sees exactly the behaviour
    /// it always has. `Some(sizing)` overrides that default, e.g. with
    /// [`crate::MinimapSizing::RepeatToFill`] to stretch a short file
    /// across a tall strip.
    fn minimap_sizing(&self) -> Option<crate::primitives::minimap::MinimapSizing> {
        None
    }

    /// Set the [`crate::MinimapSizing`] [`Self::draw_minimap`]/
    /// [`Self::minimap_layout`] resolve their row-pitch strategy from.
    /// Default no-op, mirroring [`Self::set_minimap_scale`]: a backend
    /// that never overrides [`Self::minimap_sizing`] has nowhere to store
    /// this and nothing reads it back.
    fn set_minimap_sizing(&mut self, _sizing: Option<crate::primitives::minimap::MinimapSizing>) {}

    /// Compute [`Minimap`] layout without painting — mirrors
    /// [`Backend::chart_layout`] / [`Backend::tree_layout`]. Apps call
    /// this from `AppLogic::handle` (which only has `&mut self`, not the
    /// `MinimapPaintResult` `render` produced) to hit-test a click
    /// against the same geometry the last paint used.
    ///
    /// Coordinate frame: **ABSOLUTE** — shifted by `rect.x` / `rect.y`.
    /// Real on every backend, including macOS, which computes this exact
    /// geometry whether or not a paint has run yet.
    fn minimap_layout(&self, rect: Rect, minimap: &Minimap) -> MinimapLayout;

    /// Paint `image` within `rect`, honoring `image.fit` (see
    /// [`Image::layout`] for the geometry). GTK decodes `image.source`
    /// through `gdk_pixbuf` and paints real pixels; Win and macOS are
    /// scoped out for now — rather than a reachable `todo!()`,
    /// `MacBackend::draw_image` reports [`ImagePaintResult::Unsupported`]
    /// and paints nothing, the same signal TUI's categorical case already
    /// uses below. This method has no default (rule 7 below still
    /// applies to it), so every backend implementer still sees a compile
    /// error until it picks one of these two honest outcomes.
    ///
    /// **TUI cannot rasterise an image** — there is no pixel grid to
    /// draw into, and `Image` deliberately does not attempt an ASCII-art
    /// decoder (see `primitives::image` module docs' scope
    /// guard). It paints [`Image::fallback_text`] instead, centered in
    /// `rect`, and reports [`ImagePaintResult::Unsupported`] rather than
    /// a silent no-op, so TUI genuinely says it can't do this. A GTK
    /// decode failure (bad path, corrupt bytes) also reports
    /// `Unsupported` and paints nothing, and macOS reports `Unsupported`
    /// unconditionally for the same reason — so a host can tell "no
    /// pixels appeared" apart from a successful paint without inspecting
    /// pixels itself.
    ///
    /// No default impl — every backend implementer sees this as a
    /// compile error and fills in a real rasteriser, or an explicit
    /// `todo!()` if the primitive is out of scope for that backend for
    /// now (`PRIMITIVE_RULES.md` rule 7).
    fn draw_image(&mut self, rect: Rect, image: &Image) -> ImagePaintResult;

    /// Paint a [`Canvas`]'s `ops` into `rect`. Every `DrawOp` coordinate
    /// is LOCAL to `rect` — see [`Canvas`]'s own module doc for the full
    /// coordinate-frame contract.
    ///
    /// The three pixel backends (GTK/macOS/Win) share one
    /// implementation, [`crate::primitives::canvas::native_surface_paint::paint`],
    /// routed through [`crate::paint_surface::PaintSurface`] — there is
    /// no backend-specific *policy* here, only a passthrough, unlike
    /// [`Self::draw_panel`]/[`Self::draw_toast_overlay`] which resolve
    /// theme colours and chrome metrics. TUI has no pixel grid, so it
    /// rasterises the same ops into cells instead of reporting
    /// `Unsupported` — see [`Canvas`]'s module doc's degrade table
    /// (design decision D-014: `Canvas` is a **degrade** capability, not
    /// N/A).
    ///
    /// No default impl — every backend implementer sees this as a
    /// compile error, same as [`Self::draw_image`] (`PRIMITIVE_RULES.md`
    /// rule 7).
    fn draw_canvas(&mut self, rect: Rect, canvas: &Canvas) -> CanvasLayout;

    /// Compute the canvas layout without painting.
    ///
    /// Coordinate frame: **ABSOLUTE** — `bounds` is exactly `rect` —
    /// see [`CanvasLayout`]'s own doc for why no backend has any
    /// further metric to add.
    ///
    /// Defaulted: a pure function of `rect` alone (`CanvasLayout {
    /// bounds: rect }`), with no backend-specific input at all — a
    /// stronger case for a default body than `terminal_layout`/
    /// `editor_layout` (`tests/conformance/caps.rs`'s `ACCEPTED_DEFAULTS`),
    /// which still depend on `char_width()`/`line_height()`. Every
    /// backend takes this default; see `ACCEPTED_DEFAULTS`'s
    /// `canvas_layout` entries for the from-scratch justification each
    /// one records.
    fn canvas_layout(&self, rect: Rect, canvas: &Canvas) -> CanvasLayout {
        let _ = canvas;
        CanvasLayout { bounds: rect }
    }
}

/// Paint-side data returned by [`Backend::draw_minimap`]. See
/// [`EditorPaintResult`] for the sibling pattern this mirrors.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct MinimapPaintResult {
    pub layout: MinimapLayout,
    /// Whether this call actually rasterised pixels into the target
    /// rect. `true` on every backend, including macOS's own Core
    /// Graphics/Core Text rasteriser (`crate::macos::minimap::draw_minimap`).
    /// `layout` is always the real geometry
    /// [`Backend::minimap_layout`] would also return (the shared
    /// `Minimap::layout_with_sizing` logic, not a stub), regardless of
    /// `painted`, so a host can always hit-test clicks against it. The
    /// bool-on-a-struct shape (rather than an enum like
    /// [`ImagePaintResult`]) is because this method already returns a
    /// struct carrying a layout; `painted` draws the same
    /// Unsupported-vs-real distinction that enum's `Unsupported` variant
    /// draws for `draw_image` (which still uses that shape — macOS has
    /// no `NSImage` decoder yet, a separate, still-open gap). Defaults
    /// to `false` via `#[derive(Default)]` — the honest "nothing
    /// happened yet" starting point, same reasoning as
    /// [`BackendCaps::empty`].
    pub painted: bool,
}

/// Paint-side result of [`Backend::draw_image`]. Deliberately a plain
/// enum, not a struct carrying a layout like [`MinimapPaintResult`] —
/// [`Image::layout`] is pure geometry with no backend-specific
/// measurement step (unlike `Minimap`'s TUI/GTK sampling density), so
/// callers needing the target rect call that directly instead of
/// threading it through the paint result.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImagePaintResult {
    /// The backend rasterised actual image pixels into the target rect.
    Painted,
    /// The backend could not (or, for TUI/macOS, categorically can not)
    /// rasterise pixels. TUI paints `image.fallback_text` instead; GTK on
    /// a decode failure and macOS unconditionally (no `NSImage` decoder
    /// wired up yet) both paint nothing. See
    /// [`Backend::draw_image`]'s doc comment.
    Unsupported,
}

// ── Shared layout helpers ───────────────────────────────────────────────

/// Shift every x-span in `hits` right by `dx`.
///
/// [`tab_bar_hits_from_layout`] yields **bar-relative** x (the primitive
/// measures from `0.0`), but the [`TabBarHits`] contract is
/// target-surface (absolute) coordinates. Rasterisers and the no-paint
/// `tab_bar_layout` variants both call this with `rect.x` so the two
/// paths return the same space.
///
/// `TabBarHits` is `#[deprecated]` — see its doc for the replacement
/// plan.
#[allow(deprecated)]
pub fn shift_tab_bar_hits(hits: &mut TabBarHits, dx: f64) {
    if dx == 0.0 {
        return;
    }
    for sp in &mut hits.slot_positions {
        // `(0.0, 0.0)` is the sentinel for tabs scrolled out of view —
        // leave it recognisable rather than shifting it to `(dx, dx)`.
        if *sp != (0.0, 0.0) {
            sp.0 += dx;
            sp.1 += dx;
        }
    }
    for cb in hits.close_bounds.iter_mut().flatten() {
        cb.0 += dx;
        cb.1 += dx;
    }
    for rb in &mut hits.right_segment_bounds {
        rb.0 += dx;
        rb.1 += dx;
    }
}

/// Convert a `TabBarLayout` to the legacy `TabBarHits` struct.
///
/// Spans are **bar-relative** on return; callers that owe the
/// [`TabBarHits`] absolute contract must follow up with
/// [`shift_tab_bar_hits`] using `rect.x`.
///
/// `TabBarHits`'s `f64` coordinate fields predate the crate's f32-native
/// convention (`Point`/`Rect`), and this converter is the thing that
/// keeps constructing them. Full retirement of `TabBarHits` itself (the
/// `f64` fields, and the six `Backend` trait methods that return it) is
/// a separate, much larger follow-up: `vimcode` holds a real,
/// non-doc-only dependency on `TabBarHits`'s field types
/// (`src/core/engine/mod.rs`, `src/core/engine/terminal_ops.rs`,
/// `src/gtk/mod.rs`), and two of the four backends (`macos::tab_bar`,
/// `win::tab_bar`) construct `TabBarHits` directly without ever computing
/// an intermediate `TabBarLayout`, so a safe migration needs new native
/// per-backend rasterisers, not just a signature change.
///
/// `TabBarHits` is `#[deprecated]`; this converter is the one place
/// in-tree still allowed to construct it.
#[allow(deprecated)]
pub fn tab_bar_hits_from_layout(layout: &TabBarLayout, bar: &TabBar) -> TabBarHits {
    let mut slot_positions = vec![(0.0, 0.0); bar.tabs.len()];
    let mut close_bounds = vec![None; bar.tabs.len()];
    let mut right_segment_bounds = Vec::new();

    for vt in &layout.visible_tabs {
        let b = vt.bounds;
        slot_positions[vt.tab_idx] = (b.x as f64, (b.x + b.width) as f64);
        if let Some(cb) = vt.close_bounds {
            close_bounds[vt.tab_idx] = Some((cb.x as f64, (cb.x + cb.width) as f64));
        }
    }
    for vs in &layout.visible_segments {
        let b = vs.bounds;
        right_segment_bounds.push((b.x as f64, (b.x + b.width) as f64));
    }

    TabBarHits {
        slot_positions,
        close_bounds,
        right_segment_bounds,
        available_cols: layout.bar_width as usize,
        correct_scroll_offset: layout.resolved_scroll_offset,
    }
}

/// Compute activity bar hit regions from geometry (no paint).
///
/// Spans are **relative to `rect`** per the [`Backend::draw_activity_bar`]
/// contract: the first top-pinned row starts at `0.0` and only `rect.height`
/// is consulted (to pin the bottom group), never `rect.y`.
pub fn activity_bar_hits(rect: Rect, bar: &ActivityBar, lh: f32) -> Vec<ActivityBarRowHit> {
    let mut hits = Vec::new();
    let mut y = 0.0_f32;
    for item in &bar.top_items {
        hits.push(ActivityBarRowHit {
            id: item.id,
            tooltip: item.tooltip.clone(),
            y_start: y,
            y_end: y + lh,
        });
        y += lh;
    }
    let bottom_start = rect.height - bar.bottom_items.len() as f32 * lh;
    let mut by = bottom_start.max(y);
    for item in &bar.bottom_items {
        hits.push(ActivityBarRowHit {
            id: item.id,
            tooltip: item.tooltip.clone(),
            y_start: by,
            y_end: by + lh,
        });
        by += lh;
    }
    hits
}

/// Paint-side data returned by [`Backend::draw_editor`]. Carries
/// information the host needs to align external chrome (caret blink
/// overlay, virtual-text positioning) with the editor's painted
/// content. Backends that paint their own caret (GTK) populate the
/// default; backends that delegate caret rendering to the host (TUI
/// terminal cursor) populate the actual cursor cell.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct EditorPaintResult {
    /// Cursor's painted position in backend-native units, if the host is
    /// responsible for terminal-cursor positioning. `None` when the
    /// backend painted its own caret OR when the cursor is outside the
    /// viewport. TUI rounds to the nearest cell internally before
    /// returning, then widens the cell coordinates back into this
    /// field's `f32` unit.
    pub cursor_position_native: Option<Point>,
}

/// Trait for content that can render itself into a rect using any backend.
///
/// Implement this on your tab-content types and place them in
/// [`crate::compose::bottom_panel::BottomPanelTab::content`] to supply
/// the body that renders inside the panel when the tab is active.
///
/// # Rules
///
/// - Implementations **must not** borrow app state — each render is a
///   snapshot draw, same rule as every other `draw_*` primitive.
/// - Implementations **must be `Send + 'static`** so they can be stored
///   inside `ShellAdapter` which the runner moves into a thread.
///
/// # Example
///
/// ```ignore
/// struct LogPanel { lines: Vec<String> }
///
/// impl BackendWidget for LogPanel {
///     fn render(&self, backend: &mut dyn Backend, rect: Rect) {
///         let td = TextDisplay { id: "log".into(), lines: self.lines.iter()
///             .map(|l| TextDisplayLine { spans: vec![StyledSpan::plain(l)], .. })
///             .collect(), .. };
///         backend.draw_text_display(rect, &td);
///     }
/// }
/// ```
pub trait BackendWidget: Send + 'static {
    /// Render this widget's content into `rect` using `backend`.
    ///
    /// Called once per frame when this tab is the active tab in a
    /// [`crate::compose::bottom_panel::BottomPanelConfig`].
    fn render(&self, backend: &mut dyn Backend, rect: Rect);
}

/// Platform services the backend exposes to apps: clipboard, file
/// dialogs, message/alert dialogs, notifications, URL opening, and the
/// OS credential store ([`Self::secret_store`]).
pub trait PlatformServices {
    fn clipboard(&self) -> &dyn Clipboard;

    /// Show a native file-open dialog (blocking). Returns `None` if the
    /// user cancelled. TUI backends have no native dialog to show and
    /// unconditionally return `None` (no stderr hint is written); apps
    /// should provide an in-TUI picker instead.
    fn show_file_open_dialog(&self, opts: FileDialogOptions) -> Option<PathBuf>;

    /// Show a native file-save dialog.
    fn show_file_save_dialog(&self, opts: FileDialogOptions) -> Option<PathBuf>;

    /// Show a native directory-select dialog (blocking). Returns `None`
    /// if the user cancelled.
    ///
    /// Reuses [`FileDialogOptions`] rather than a narrower type: only
    /// [`FileDialogOptions::title`] and [`FileDialogOptions::initial_dir`]
    /// apply to a directory chooser. [`FileDialogOptions::filters`] and
    /// [`FileDialogOptions::initial_filename`] are meaningless for a
    /// directory (no extension, no "file name" field to seed) and every
    /// implementation of this method ignores them — callers should just
    /// leave them at their `Default` rather than populating them.
    ///
    /// TUI backends have no native dialog to show and unconditionally
    /// return `None` (no stderr hint is written), same as
    /// [`Self::show_file_open_dialog`] — apps should provide an in-canvas
    /// picker instead. Callers distinguish "no native chooser at all"
    /// from "the user cancelled" via [`BackendCaps::folder_dialogs`], the
    /// same way they already do for [`BackendCaps::file_dialogs`].
    fn show_folder_open_dialog(&self, opts: FileDialogOptions) -> Option<PathBuf>;

    /// Show a native message/alert dialog (blocking). Returns the id of
    /// the button the user chose, or `None` if the dialog was dismissed
    /// without choosing one (Escape, close box) **or** this backend has
    /// no native alert facility at all — mirrors
    /// [`Self::show_file_open_dialog`]'s `None` shape exactly. Callers
    /// separate the two via [`BackendCaps::native_dialogs`], the same
    /// way they already do for [`BackendCaps::file_dialogs`].
    ///
    /// This is a parallel path alongside the in-canvas [`Dialog`]
    /// primitive (`Backend::draw_dialog`), not a replacement for it:
    /// [`crate::primitives::dialog::native_dialog_options`] decides,
    /// per-dialog, whether a given [`Dialog`] can go native at all —
    /// callers should consult that before calling this method, and fall
    /// back to `draw_dialog` when it returns `None`. TUI backends have
    /// no native dialog to show and unconditionally return `None` (no
    /// stderr hint is written); the in-canvas `Dialog` primitive stays
    /// the TUI path.
    fn show_message_dialog(&self, opts: MessageDialogOptions) -> Option<MessageDialogChoice>;

    /// Dispatch a system notification — see [`Notification`]'s doc for
    /// `icon`/`actions`/`silent`/`tag`.
    ///
    /// A click on the notification (its body, or one of `n`'s declared
    /// actions) should push [`UiEvent::NotificationActivated`] where the
    /// backend has a native channel for it — today only GTK does (see
    /// `gtk::services`'s module doc); macOS's unbundled `osascript`
    /// fallback and Win's `Shell_NotifyIconW` balloon fallback have no
    /// click-through of their own to report through, and honestly do not
    /// emit the event rather than faking it (each backend's
    /// `send_notification` doc explains why, and what a real
    /// implementation there would need).
    fn send_notification(&self, n: Notification);

    /// Open a URL in the platform's default browser.
    fn open_url(&self, url: &str);

    /// Fallible twin of [`Self::open_url`] (D-009 seam-2's `_result`-twin
    /// pattern — the same shape [`Clipboard::write_text_result`] already
    /// carries): reports [`BackendError::Unsupported`] on a backend with
    /// no way to open a URL at all, instead of `open_url`'s silent no-op.
    /// `open_url` itself keeps its infallible signature unchanged so both
    /// existing consumers (which only ever call `open_url`) keep
    /// compiling untouched.
    ///
    /// Default: calls `open_url` and returns `Ok(())` — a backend whose
    /// `open_url` is a real implementation (GTK via
    /// `gio::AppInfo::launch_default_for_uri`, Win-GUI via
    /// `ShellExecuteW`, macOS via `open`) answers exactly like this method
    /// doesn't exist, at zero cost. `TuiPlatformServices` is the one
    /// override: TUI shells out to the platform's URL opener
    /// (`xdg-open`/`open`/`cmd /c start`) with an OSC 8 hyperlink
    /// fallback, and only reports `Err(BackendError::Unsupported)` when
    /// neither reaches anything (see `tui::services`'s module doc,
    /// "URL opening").
    fn open_url_result(&self, url: &str) -> ServiceResult<()> {
        self.open_url(url);
        Ok(())
    }

    /// Reveal `path` in the platform's file manager with it selected —
    /// "Reveal in Finder" / "Show in Explorer" / "Show in Files"
    /// (Electron's `shell.showItemInFolder`).
    ///
    /// Default: `Err(BackendError::Unsupported)`, the same "future
    /// backend compiles before it has an opinion" placeholder
    /// [`Self::system_theme`]'s default doc explains. GTK, macOS, and
    /// Win-GUI each override this with a real implementation. TUI also
    /// has a real degrade (`crate::desktop::reveal_in_file_manager`:
    /// `open -R` / Explorer `/select,` / D-Bus `ShowItems`, falling back
    /// to opening the parent directory) — the desktop session underneath
    /// the terminal can do this even though the terminal itself can't,
    /// the same reasoning `open_url_result` applies to launching a
    /// browser (see `tui::services`'s module doc's "`shell.*` parity"
    /// section).
    fn reveal_in_file_manager(&self, path: &Path) -> ServiceResult<()> {
        let _ = path;
        Err(BackendError::Unsupported)
    }

    /// Open `path` with the platform's default handler for its type —
    /// Electron's `shell.openPath`. Distinct from [`Self::open_url`]:
    /// that method takes a URL string and always goes through the
    /// scheme's registered handler (a browser for `https://`, a mail
    /// client for `mailto:`); this one takes a filesystem path directly.
    ///
    /// Default: `Err(BackendError::Unsupported)`, same placeholder
    /// reasoning as [`Self::reveal_in_file_manager`]. GTK, macOS, and
    /// Win-GUI override with a real implementation. TUI *also* overrides
    /// this one — see `tui::services::TuiPlatformServices::open_path`'s
    /// doc for why a terminal can still shell out to `xdg-open`/`open`
    /// even though it has no browser for [`Self::open_url`] to hand a URL
    /// to.
    fn open_path(&self, path: &Path) -> ServiceResult<()> {
        let _ = path;
        Err(BackendError::Unsupported)
    }

    /// Move `path` to the platform trash/recycle bin — recoverable,
    /// unlike deleting it outright — Electron's `shell.trashItem`.
    ///
    /// Default: `Err(BackendError::Unsupported)`, same placeholder
    /// reasoning as [`Self::reveal_in_file_manager`]. Every backend in
    /// this crate overrides it with the *same* implementation
    /// ([`crate::desktop::move_to_trash`]): the cross-platform `trash`
    /// crate already wraps `NSWorkspace`'s Objective-C
    /// `-trashItemAtURL:resultingItemURL:error:`, `gio::File::trash`'s
    /// freedesktop.org trash-spec equivalent, and
    /// `SHFileOperationW(FOF_ALLOWUNDO)` internally, and needs only a
    /// filesystem — no live desktop/window-server session — on any of
    /// the three. So TUI gets the exact same real implementation as the
    /// other three, not a degraded one (see the module doc's "TUI story"
    /// note this issue itself made about this method).
    fn move_to_trash(&self, path: &Path) -> ServiceResult<()> {
        let _ = path;
        Err(BackendError::Unsupported)
    }

    /// Ring the terminal bell / play the system alert sound — Electron's
    /// `shell.beep`.
    ///
    /// Default: `Err(BackendError::Unsupported)`, same placeholder
    /// reasoning as [`Self::reveal_in_file_manager`]. Every backend
    /// overrides it — TUI's BEL is arguably the most honest of the four:
    /// it's a terminal's *only* notification channel, so this is full
    /// support there, not a degrade.
    fn beep(&self) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// Query the OS-level light/dark preference, accent colour, and
    /// high-contrast setting.
    ///
    /// Returns [`BackendError::Unsupported`] rather than a guessed value on
    /// a backend/session with no way to answer — unlike
    /// [`Self::show_file_open_dialog`]'s ambiguous `None` (which needed a
    /// dedicated `BackendCaps` flag to disambiguate "cancelled" from "no
    /// native facility"), a `Result` already carries that distinction in
    /// its own type, so this method gets no `BackendCaps` field of its own.
    ///
    /// Default: always `Err(BackendError::Unsupported)` — the honest
    /// starting point (rule 2's "new function alongside the old one" isn't
    /// in play here since no downstream consumer implements
    /// `PlatformServices`, per `CLAUDE.md`'s *Downstream consumers* table,
    /// but a default still means a future fifth backend compiles before it
    /// has an opinion). Every backend in this crate overrides it:
    ///
    /// - **TUI** (`TuiPlatformServices`, `tui::caps`) — honest degrade,
    ///   same detect/probe split as [`crate::backend::BackendCaps::kitty_keyboard`]:
    ///   an environment-only heuristic (`COLORFGBG`) parsed by
    ///   `tui::caps::detect_system_theme_from`. No OS accent colour or
    ///   high-contrast signal exists in a terminal, so those fields are
    ///   always `None`/`false` there. Returns `Unsupported` when
    ///   `COLORFGBG` is unset or unparseable — a terminal that never sets
    ///   it genuinely gives no signal, so guessing would be no more honest
    ///   than refusing.
    /// - **GTK** — `gtk4::Settings::gtk-application-prefer-dark-theme` /
    ///   `gtk-theme-name` (no accent-colour API without libadwaita).
    /// - **macOS** — `NSApp.effectiveAppearance` / `NSColor::controlAccentColor`.
    /// - **Win-GUI** — `UISettings::GetColorValue` (`Background`/`Accent`
    ///   `UIColorType`s).
    ///
    /// No backend pushes [`crate::UiEvent::SystemThemeChanged`] on a live OS
    /// theme change yet (same "declare the gap, don't fake it" posture as
    /// [`crate::UiEvent::WindowStateChanged`], which also has zero producers
    /// today) — this method is a poll-on-demand query, not a subscription.
    fn system_theme(&self) -> ServiceResult<SystemTheme> {
        Err(BackendError::Unsupported)
    }

    /// The OS credential store — Keychain (macOS), Secret Service
    /// (Linux), Windows Credential Manager — for apps that hold an API
    /// token, a password, or an OAuth refresh token and would otherwise
    /// have no choice but to invent their own storage or write it to
    /// plaintext config.
    ///
    /// This one is **backend-independent**: the returned [`SecretStore`]
    /// is backed by the cross-platform `keyring` crate directly, not by a
    /// per-backend native implementation, so it needs no override in
    /// `tui`/`gtk`/`macos`/`win::services` — the same default body serves
    /// all four. `keyring` itself needs no window, no display server, and
    /// no desktop session (its Linux store talks to the Secret Service
    /// over D-Bus, not through any GUI toolkit), so this is **full
    /// support on TUI**, not a degrade. See [`SecretStore`]'s own doc for
    /// the get/set/delete shape.
    ///
    /// Default: a `keyring`-backed [`SecretStore`] when this crate was
    /// built with any of the `tui`/`gtk`/`macos`/`win` features (the same
    /// four that already pull in the cross-platform `trash` crate for
    /// [`Self::move_to_trash`] — see that dependency's Cargo.toml comment
    /// for why the list is exactly those four); a `SecretStore` whose
    /// every method returns `Err(BackendError::Unsupported)` when none of
    /// them are enabled (a bare `cargo check -p quadraui` with no
    /// features, which this crate supports — see `lib.rs`'s unconditional
    /// `pub mod backend;`). No in-tree backend overrides this — there is
    /// nothing backend-specific left to override.
    fn secret_store(&self) -> &dyn SecretStore {
        static STORE: KeyringSecretStore = KeyringSecretStore;
        &STORE
    }

    /// Enumerate every connected display — bounds, usable work area, DPI
    /// scale, and which one is primary. Needed to restore saved window
    /// bounds after a monitor change, place a new window sensibly, or
    /// position a popup near the cursor across displays. See
    /// [`Display`]'s own doc for the field-by-field contract, including
    /// the GTK/Wayland work-area caveat.
    ///
    /// Default: `Err(BackendError::Unsupported)`, the same placeholder
    /// reasoning [`Self::reveal_in_file_manager`]'s doc explains. Every
    /// backend in this crate overrides it:
    ///
    /// - **macOS** — `NSScreen::screens()`, `frame()`/`visibleFrame()` for
    ///   `bounds`/`work_area`, `backingScaleFactor()` for `scale`.
    ///   `screens()[0]` is always the screen containing the menu bar —
    ///   used as `primary` (distinct from `NSScreen::mainScreen()`, which
    ///   tracks the *key window*'s screen, not the platform's primary
    ///   one).
    /// - **GTK** — `gdk::Display::monitors()` + `Monitor::geometry()` /
    ///   `scale_factor()`. No work-area API exists in GDK4 at all
    ///   (removed from GDK3 entirely, not just absent on Wayland) — GTK's
    ///   `work_area` is always a copy of `bounds` on every desktop. No
    ///   primary-monitor flag either; index `0` (enumeration order) is
    ///   used as a best-effort proxy — see
    ///   [`crate::gtk::services::GtkPlatformServices::displays`]'s doc.
    /// - **Win-GUI** — `EnumDisplayMonitors` + `GetMonitorInfoW` for
    ///   `bounds`/`work_area`/`primary` (`rcMonitor`/`rcWork`/
    ///   `MONITORINFOF_PRIMARY`), `GetDpiForMonitor` for `scale`
    ///   (`dpi / USER_DEFAULT_SCREEN_DPI`).
    /// - **TUI** — a truthful degrade, not `Unsupported`: one [`Display`]
    ///   whose `bounds`/`work_area` are both the terminal's cell grid
    ///   (`0, 0, width, height`, the same cell units
    ///   [`Backend::viewport`] reports), `scale: 1.0`, `primary: true` —
    ///   see [`crate::tui::services`]'s module doc.
    fn displays(&self) -> ServiceResult<Vec<Display>> {
        Err(BackendError::Unsupported)
    }

    /// The mouse cursor's current position in screen coordinates — the
    /// same coordinate system [`Self::displays`]'s `bounds`/`work_area`
    /// use, so a caller can directly test which [`Display`] currently
    /// contains the cursor (e.g. positioning a popup near the cursor
    /// across displays).
    ///
    /// Default: `Err(BackendError::Unsupported)`, same placeholder
    /// posture as [`Self::displays`]. **GTK and TUI both keep this
    /// default, for real (not placeholder) reasons documented on each
    /// override:** GDK4 removed the global/root-window pointer-position
    /// query entirely (`Surface::device_position` is *surface-relative*
    /// only, and GDK4 surfaces don't expose their own screen origin
    /// either — a real protocol-level Wayland restriction, not a missing
    /// binding); a terminal has no synchronous "where is the mouse right
    /// now" query at all — only `UiEvent::MouseMoved`, delivered when the
    /// terminal's mouse-tracking mode is on. macOS
    /// (`NSEvent::mouseLocation()`) and Win-GUI (`GetCursorPos`) both
    /// override with a real answer.
    fn cursor_screen_point(&self) -> ServiceResult<Point> {
        Err(BackendError::Unsupported)
    }

    /// Platform identifier — matches the `BackendNative.backend` field.
    /// One of `"tui"`, `"gtk"`, `"win-gui"`, `"macos"`.
    fn platform_name(&self) -> &'static str;
}

/// A single named entry in the OS credential store, keyed by `service` +
/// `account` — [`PlatformServices::secret_store`].
///
/// Deliberately small and string-keyed, mirroring the `keyring` crate's
/// own `Entry::new(service, username)` shape it wraps: an app names its
/// own `service` (e.g. `"my-app"`) and one `account` per credential it
/// wants to keep separate (e.g. a username, or a fixed string like
/// `"api-token"` for an app with only one secret). There is no "list all
/// entries" method — none of macOS Keychain, Windows Credential Manager,
/// or Secret Service expose a *portable* enumeration API without extra
/// per-platform querying `keyring` itself doesn't attempt, so this trait
/// doesn't promise one either.
///
/// `get` returns `Ok(None)` for "no entry has ever been set" — the same
/// "nothing here, not a failure" idiom [`Clipboard::read_text`] already
/// uses — reserving `Err` for a real platform failure (the credential
/// store is locked, unreachable, or returned malformed data). `set` and
/// `delete` have no such "nothing to report" case: a write either
/// succeeds or fails, and deleting an entry that was never set is a real,
/// reportable outcome (`Err`), not silently `Ok(())` — the same "surface
/// the native call's actual outcome rather than papering over it" stance
/// [`PlatformServices::move_to_trash`]'s own doc and test already take
/// for a nonexistent path.
pub trait SecretStore {
    /// Read the secret stored for `service` + `account`. `Ok(None)` when
    /// no entry has ever been set (or it was already deleted); `Err` on a
    /// real platform failure.
    fn get(&self, service: &str, account: &str) -> ServiceResult<Option<String>>;

    /// Write `secret` for `service` + `account`, creating the entry if it
    /// doesn't exist or overwriting it if it does.
    fn set(&self, service: &str, account: &str, secret: &str) -> ServiceResult<()>;

    /// Delete the entry for `service` + `account`. `Err` if no such entry
    /// exists — see this trait's own doc for why that's a real outcome
    /// here, not a no-op success.
    fn delete(&self, service: &str, account: &str) -> ServiceResult<()>;
}

/// `SecretStore` backed by the cross-platform `keyring` crate — the one
/// implementation [`PlatformServices::secret_store`]'s default vends on
/// every backend, TUI included (see that method's doc for why no backend
/// needs its own override).
///
/// A zero-sized marker, not a handle: `keyring::Entry` is cheap to build
/// per call (it does no I/O until `get_password`/`set_password`/
/// `delete_credential` is actually invoked) and this crate has no
/// process-wide keyring state of its own to cache — every call opens a
/// fresh `Entry` for exactly the `service`/`account` pair it was asked
/// for.
#[cfg(any(feature = "tui", feature = "gtk", feature = "macos", feature = "win"))]
struct KeyringSecretStore;

#[cfg(any(feature = "tui", feature = "gtk", feature = "macos", feature = "win"))]
impl SecretStore for KeyringSecretStore {
    fn get(&self, service: &str, account: &str) -> ServiceResult<Option<String>> {
        let entry = keyring::Entry::new(service, account).map_err(keyring_error_to_backend)?;
        match entry.get_password() {
            Ok(secret) => Ok(Some(secret)),
            Err(keyring::Error::NoEntry) => Ok(None),
            Err(e) => Err(keyring_error_to_backend(e)),
        }
    }

    fn set(&self, service: &str, account: &str, secret: &str) -> ServiceResult<()> {
        let entry = keyring::Entry::new(service, account).map_err(keyring_error_to_backend)?;
        entry.set_password(secret).map_err(keyring_error_to_backend)
    }

    fn delete(&self, service: &str, account: &str) -> ServiceResult<()> {
        let entry = keyring::Entry::new(service, account).map_err(keyring_error_to_backend)?;
        entry.delete_credential().map_err(keyring_error_to_backend)
    }
}

/// Map a `keyring` crate error onto this crate's own error vocabulary.
/// `keyring::Error` has no equivalent of [`BackendError::Unsupported`] —
/// every variant is a real failure of *some* underlying store operation
/// (see [`keyring::Error`]'s own doc) — so every arm becomes
/// [`BackendError::PlatformFailure`] with the `Display` text as context;
/// [`keyring::Error::NoEntry`] is handled separately by
/// [`KeyringSecretStore::get`] before it would ever reach here.
#[cfg(any(feature = "tui", feature = "gtk", feature = "macos", feature = "win"))]
fn keyring_error_to_backend(e: keyring::Error) -> BackendError {
    BackendError::PlatformFailure {
        context: format!("keyring: {e}"),
    }
}

/// `SecretStore` fallback for a build with none of the
/// `tui`/`gtk`/`macos`/`win` features enabled — the `keyring` crate isn't
/// even a dependency in that configuration (see its Cargo.toml gate), so
/// there is no store to reach; every method honestly reports
/// [`BackendError::Unsupported`] rather than the crate failing to build
/// at all. See [`PlatformServices::secret_store`]'s doc for why a bare,
/// feature-less `cargo check -p quadraui` must still compile this trait's
/// default method.
#[cfg(not(any(feature = "tui", feature = "gtk", feature = "macos", feature = "win")))]
struct KeyringSecretStore;

#[cfg(not(any(feature = "tui", feature = "gtk", feature = "macos", feature = "win")))]
impl SecretStore for KeyringSecretStore {
    fn get(&self, _service: &str, _account: &str) -> ServiceResult<Option<String>> {
        Err(BackendError::Unsupported)
    }

    fn set(&self, _service: &str, _account: &str, _secret: &str) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    fn delete(&self, _service: &str, _account: &str) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }
}

/// One connected display — bounds, usable work area, DPI scale, and
/// primary-monitor flag ([`PlatformServices::displays`]).
///
/// `bounds` and `work_area` share the backend's native coordinate system —
/// the same "TUI: cells; GTK/macOS/Win: pixels" convention every other
/// [`Rect`] in this crate already uses. Coordinates are relative to the
/// platform's own virtual-desktop origin, not necessarily `(0, 0)` — a
/// monitor to the left of or above the primary sits at negative `x`/`y`
/// (macOS additionally uses AppKit's bottom-left-origin, y-up convention
/// for both fields — the same one [`PlatformServices::cursor_screen_point`]
/// returns coordinates in on that backend, so the two stay directly
/// comparable there).
///
/// Not `Serialize`/`Deserialize`: unlike [`SystemTheme`], nothing carries
/// a `Display` inside a [`crate::UiEvent`] payload —
/// [`crate::UiEvent::DisplaysChanged`] is a bare change notification a
/// caller reacts to by calling [`PlatformServices::displays`] again, not a
/// snapshot delivery.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Display {
    /// The monitor's full bounds, including any OS chrome (taskbar / menu
    /// bar + Dock / panels) that overlaps it.
    pub bounds: Rect,
    /// The usable area inside `bounds` — excludes the taskbar (Windows),
    /// menu bar + Dock (macOS), and panels (GTK/X11 desktop
    /// environments that report one). **Not available on GTK** — GDK4
    /// exposes no work-area API at all (removed from GDK3, not just
    /// absent on Wayland specifically; see
    /// [`crate::gtk::services::GtkPlatformServices::displays`]'s doc), so
    /// the GTK backend always reports a copy of `bounds` here rather than
    /// faking a value on some desktops and not others.
    pub work_area: Rect,
    /// This monitor's DPI/backing scale factor — the same units as
    /// [`crate::event::Viewport::scale`] and
    /// [`crate::event::UiEvent::DpiChanged`]'s payload.
    pub scale: f32,
    /// `true` for the platform's primary/main display. Exactly one
    /// [`Display`] in [`PlatformServices::displays`]'s returned `Vec` has
    /// this set on macOS, Win-GUI, and TUI. **GTK is a best-effort
    /// exception** — GDK4 has no native "primary monitor" concept to
    /// report at all, so the GTK backend marks index `0` (enumeration
    /// order) as `primary` rather than reporting `false` on every entry;
    /// see [`crate::gtk::services::GtkPlatformServices::displays`]'s doc.
    pub primary: bool,
}

/// The OS-level theme preference [`PlatformServices::system_theme`]
/// reports — light/dark, accent colour, and high-contrast.
///
/// Deliberately flat and small, mirroring [`Notification`]'s shape: this is
/// a snapshot an app reads once per query (or once per
/// [`crate::UiEvent::SystemThemeChanged`], once some backend emits it), not
/// a live-updating handle. `Serialize`/`Deserialize` (unlike the other
/// `PlatformServices` option/config structs in this module) because it also
/// travels inside [`crate::UiEvent::SystemThemeChanged`], and every
/// `UiEvent` payload satisfies that bound — see `event.rs`'s module doc.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct SystemTheme {
    /// `true` when the OS is set to a dark appearance (Windows "Dark" app
    /// mode, macOS Dark Appearance, GTK's `prefer-dark-theme`, or — on TUI —
    /// `COLORFGBG`'s background index reads as dark).
    pub dark: bool,
    /// The OS accent colour, when the platform exposes one and the backend
    /// can read it. `None` on backends/platforms with no accent-colour
    /// concept (TUI always; GTK today, absent libadwaita) rather than a
    /// guessed default — callers should fall back to their own accent
    /// colour, not treat `None` as black/transparent.
    pub accent: Option<Color>,
    /// `true` when the OS high-contrast accessibility setting is active
    /// (Windows High Contrast mode, GTK's `HighContrast*` theme names).
    /// Always `false` on TUI — a terminal has no equivalent OS-level
    /// setting to query.
    pub high_contrast: bool,
}

/// Decoded RGBA8 pixel buffer for a clipboard image round-trip
/// ([`Clipboard::read_image`] / [`Clipboard::write_image`]).
///
/// Deliberately a bare pixel buffer, not [`ImageSource`] — the type
/// [`TrayService::set_icon`] shares with `Backend::draw_image` per that
/// trait's own doc note. `ImageSource::Bytes`/`Path` describe *where an
/// image comes from* (encoded bytes a backend still has to sniff and
/// decode); a clipboard image is already-decoded pixels the moment it
/// comes off the OS clipboard (`CF_DIB` on Windows, an `NSImage` bitmap
/// on macOS, a decoded PNG atom on Linux) — there is nothing left to
/// decode, so a bare pixel buffer is the honest shape here instead of
/// forcing a round trip through an encoded format.
#[derive(Debug, Clone, PartialEq)]
pub struct RgbaImage {
    pub width: u32,
    pub height: u32,
    /// Straight (non-premultiplied) RGBA8 pixels, row-major, top-to-bottom,
    /// left-to-right. Always `width * height * 4` bytes long.
    pub pixels: Vec<u8>,
}

/// One data format present on the clipboard right now — the vocabulary
/// [`Clipboard::formats`] reports over.
///
/// No `Html` variant: [`Clipboard::write_html`] has no `read_html` twin
/// (no in-tree caller needs to read HTML back off the clipboard, only
/// write it), so [`Clipboard::formats`]'s generic default — which only
/// probes formats it has a matching `read_*` method to probe with — has
/// nothing to detect HTML presence with. A backend that can tell HTML is
/// on the clipboard may still surface that by overriding `formats`
/// itself; this enum only names what the default can honestly report.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClipboardFormat {
    /// Plain text — what [`Clipboard::read_text`] returns `Some` for.
    Text,
    /// A raster image — what [`Clipboard::read_image`] returns `Ok` for.
    Image,
    /// A non-empty file-path list (a Finder/Explorer copy) — what
    /// [`Clipboard::read_file_list`] returns a non-empty `Ok` for.
    FileList,
}

/// Trait object-safe clipboard access.
pub trait Clipboard {
    /// Read the current clipboard contents as plain text. `None` on
    /// empty / non-text clipboard or platform error.
    fn read_text(&self) -> Option<String>;

    /// Write plain text to the clipboard.
    fn write_text(&self, text: &str);

    /// Fallible twin of [`Self::write_text`] (D-009 seam 2's `_result`-twin
    /// pattern): same effect, but surfaces a failure a caller can observe
    /// instead of silently discarding it. `write_text` itself keeps its
    /// infallible signature unchanged so every existing call site keeps
    /// compiling with no use for a failure reason.
    ///
    /// Default: calls `write_text` and always returns `Ok(())` — a
    /// backend that never overrides this answers exactly like it doesn't
    /// exist, at zero cost to existing implementors (TUI, GTK, macOS
    /// today swallow the underlying `arboard`/Cocoa error the same way
    /// `write_text` always has). `WinBackend`'s `WinClipboard` overrides
    /// this with the real `OpenClipboard`/`GlobalAlloc`/`SetClipboardData`
    /// failure it can now tell apart from success.
    fn write_text_result(&self, text: &str) -> ServiceResult<()> {
        self.write_text(text);
        Ok(())
    }

    /// Read the X11/Wayland **PRIMARY** selection — the platform
    /// convention behind middle-click paste, distinct from
    /// [`read_text`](Self::read_text)'s CLIPBOARD selection (populated by
    /// an explicit copy). Backed by whatever text was last *selected*
    /// (drag-select, double-click), with no separate copy action needed.
    ///
    /// Defaults to `None` — most platforms (Windows, macOS, TUI-over-any-
    /// terminal) have no PRIMARY-selection concept at all, so this is
    /// only meaningfully overridden by the GTK backend on Linux/BSD.
    fn read_primary_selection(&self) -> Option<String> {
        None
    }

    /// Read the current clipboard contents as a decoded RGBA image.
    ///
    /// Default: `Err(BackendError::Unsupported)` — kept **defaulted**,
    /// unlike the rest of [`PlatformServices`]'s required methods, so
    /// every existing `impl Clipboard` (TUI, GTK, macOS, Win) keeps
    /// compiling unchanged; but the default is `Err`, not `Ok(None)` /
    /// `None`, so a backend that never overrides this is honest per call
    /// ("I cannot do this") rather than indistinguishable from "the
    /// clipboard happens to be empty right now" the way an `Option`
    /// return would read. TUI never overrides this — OSC 52 (its only
    /// remote-reachable clipboard channel) has no image form, so TUI's
    /// clipboard is text-only by construction, not by omission.
    fn read_image(&self) -> ServiceResult<RgbaImage> {
        Err(BackendError::Unsupported)
    }

    /// Write an RGBA image to the clipboard.
    ///
    /// Default: `Err(BackendError::Unsupported)` — see [`Self::read_image`].
    fn write_image(&self, _image: &RgbaImage) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// Write HTML to the clipboard, with a plain-text `alt_text`
    /// fallback for a paste target that only understands text — the same
    /// "rich content + text degrade" shape every native clipboard API
    /// exposes this as (`NSPasteboard` HTML + string types, GTK's
    /// `text/html` + `UTF8_STRING` targets, Win32's `CF_HTML` +
    /// `CF_UNICODETEXT`).
    ///
    /// Default: `Err(BackendError::Unsupported)` — see [`Self::read_image`].
    /// There is deliberately no `read_html` twin; see
    /// [`ClipboardFormat`]'s doc for why.
    fn write_html(&self, _html: &str, _alt_text: &str) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// Read the list of file paths currently on the clipboard (a
    /// Finder/Explorer copy).
    ///
    /// Default: `Err(BackendError::Unsupported)` — see [`Self::read_image`].
    fn read_file_list(&self) -> ServiceResult<Vec<PathBuf>> {
        Err(BackendError::Unsupported)
    }

    /// Which formats the clipboard currently holds.
    ///
    /// Default: probes [`Self::read_text`], [`Self::read_image`], and
    /// [`Self::read_file_list`] **through `self`** — so on a backend that
    /// overrides those, this default already reports real data without
    /// needing its own override — and reports [`ClipboardFormat::Text`] /
    /// [`ClipboardFormat::Image`] / [`ClipboardFormat::FileList`] for
    /// whichever succeeded. On a backend that overrides none of the
    /// three (plain TUI), this correctly degrades to "`Text` if there is
    /// any, otherwise nothing". A backend may still override this
    /// directly to avoid paying for three real clipboard round trips just
    /// to answer "what's there", or to report a format its `read_*`
    /// methods can't (there is none today, but a future one might).
    fn formats(&self) -> Vec<ClipboardFormat> {
        let mut out = Vec::new();
        if self.read_text().is_some() {
            out.push(ClipboardFormat::Text);
        }
        if self.read_image().is_ok() {
            out.push(ClipboardFormat::Image);
        }
        if matches!(self.read_file_list(), Ok(list) if !list.is_empty()) {
            out.push(ClipboardFormat::FileList);
        }
        out
    }

    /// Clear the clipboard of all content, regardless of format.
    ///
    /// Default: `Err(BackendError::Unsupported)` — see [`Self::read_image`].
    fn clear(&self) -> ServiceResult<()> {
        Err(BackendError::Unsupported)
    }
}

/// Options for [`PlatformServices::show_file_open_dialog`],
/// [`PlatformServices::show_file_save_dialog`], and
/// [`PlatformServices::show_folder_open_dialog`].
#[derive(Debug, Clone, Default)]
pub struct FileDialogOptions {
    /// Dialog window title.
    pub title: Option<String>,
    /// Suggested starting directory.
    pub initial_dir: Option<PathBuf>,
    /// Suggested file name (save dialog only — ignored by
    /// [`PlatformServices::show_file_open_dialog`] and
    /// [`PlatformServices::show_folder_open_dialog`]).
    pub initial_filename: Option<String>,
    /// File type filters — `(display_name, &[ext])` pairs. Ignored by
    /// [`PlatformServices::show_folder_open_dialog`]: a directory has no
    /// extension to filter on.
    pub filters: Vec<(String, Vec<String>)>,
}

/// Options for [`PlatformServices::show_message_dialog`]. Produced from
/// a [`Dialog`] descriptor by
/// [`crate::primitives::dialog::native_dialog_options`], or built
/// directly by a caller that just wants a native alert with no
/// in-canvas fallback.
#[derive(Debug, Clone)]
pub struct MessageDialogOptions {
    /// Dialog title / primary message text.
    pub title: String,
    /// Body / secondary detail text.
    pub body: String,
    /// Action buttons. Order is caller-declared intent, not necessarily
    /// paint order — [`crate::gtk::services::GtkPlatformServices`], for
    /// instance, re-orders these per GNOME HIG (cancel leftmost, default
    /// rightmost) before handing them to the native widget.
    pub buttons: Vec<MessageDialogButton>,
    /// Optional severity tint — backends may use this to pick an icon.
    /// `None` = neutral. Mirrors [`DialogSeverity`], the in-canvas
    /// `Dialog`'s equivalent field.
    pub severity: Option<DialogSeverity>,
}

/// One button in a [`MessageDialogOptions`] button row. Mirrors
/// [`crate::primitives::dialog::DialogButton`]'s id/label/default/cancel
/// shape (minus `tint`, which no native alert facility exposes).
#[derive(Debug, Clone)]
pub struct MessageDialogButton {
    pub id: WidgetId,
    pub label: String,
    /// When true, Enter (or the platform's default-action gesture)
    /// activates this button.
    pub is_default: bool,
    /// When true, Escape (or the platform's cancel gesture) activates
    /// this button.
    pub is_cancel: bool,
}

/// The [`WidgetId`] of the [`MessageDialogButton`] the user chose from a
/// [`PlatformServices::show_message_dialog`] call. A plain alias rather
/// than a wrapper type: callers already hold the
/// `Vec<MessageDialogButton>` they passed in and match the result
/// against each button's `id` directly.
pub type MessageDialogChoice = WidgetId;

/// A system notification request: title/body/urgent plus
/// `icon`/`actions`/`silent`/`tag`.
///
/// `title`, `body`, and `urgent` stay `pub` fields, so code outside this
/// module that already holds a `Notification` (from [`Self::new`]) can
/// still read or directly assign them (`n.urgent = true`). The other four
/// fields are deliberately **not** `pub`: growing an already-`pub`-field
/// struct either breaks every existing exhaustive struct literal outright
/// (`E0063`) or, via `#[non_exhaustive]`, breaks it a different way
/// (`E0639`) — both hard breaks with no deprecation shim. Reached instead
/// through [`Self::new`] plus the chainable `with_*` builder methods
/// below, so a future field can be added the same way again without ever
/// repeating this struct's original mistake of an all-`pub`-field
/// literal.
#[derive(Debug, Clone)]
pub struct Notification {
    pub title: String,
    pub body: String,
    /// Whether the notification is high-priority (e.g. error). Backends
    /// may use this to pick a different icon or sound.
    pub urgent: bool,
    icon: Option<ImageSource>,
    actions: Vec<(WidgetId, String)>,
    silent: bool,
    tag: Option<String>,
}

impl Notification {
    /// A plain notification with no icon, actions, tag, or silent flag —
    /// `urgent: false`. Chain the `with_*` methods below to add any of
    /// those.
    pub fn new(title: impl Into<String>, body: impl Into<String>) -> Self {
        Self {
            title: title.into(),
            body: body.into(),
            urgent: false,
            icon: None,
            actions: Vec::new(),
            silent: false,
            tag: None,
        }
    }

    /// Attach an icon. The same [`ImageSource`] shape
    /// [`TrayService::set_icon`] takes — raw encoded bytes or a
    /// filesystem path, sniffed/decoded by whichever backend can honor
    /// it. Backends with no icon facility (TUI's toast degrade, today's
    /// macOS `osascript` path) ignore this.
    #[must_use]
    pub fn with_icon(mut self, icon: ImageSource) -> Self {
        self.icon = Some(icon);
        self
    }

    /// Register an action button, `id` first so it reads the same order
    /// as [`UiEvent::NotificationActivated`]'s payload
    /// (`action: Some(id)`) that firing it produces. Call multiple times
    /// for multiple buttons; order is preserved. Backends that can't
    /// natively attach actions to a notification (macOS's unbundled
    /// `osascript` fallback, Win's balloon-tip fallback) drop these
    /// silently — see each backend's `send_notification` doc.
    #[must_use]
    pub fn with_action(mut self, id: WidgetId, label: impl Into<String>) -> Self {
        self.actions.push((id, label.into()));
        self
    }

    /// Suppress the notification sound, on backends that have a sound to
    /// suppress: Win's balloon sets `NIIF_NOSOUND` when this is `true`,
    /// and macOS's `osascript` fallback only adds a `sound name` clause
    /// when this is `false` (see `win::services`/`macos::services`'s
    /// `send_notification` docs). GTK's `gio::Notification` has no sound
    /// control of its own at all — the desktop shell decides — so this
    /// has nothing to bind to there.
    #[must_use]
    pub fn with_silent(mut self, silent: bool) -> Self {
        self.silent = silent;
        self
    }

    /// An app-chosen tag, round-tripped unchanged through
    /// [`UiEvent::NotificationActivated::tag`] so an app that fires
    /// several notifications can tell which one a later activation
    /// belongs to without inventing its own id scheme. Also the identity
    /// [`PlatformServices::send_notification`] may use to replace an
    /// already-visible notification with the same tag, on backends that
    /// support that (GTK: `gio::Application::send_notification`'s `id`
    /// parameter does this natively).
    #[must_use]
    pub fn with_tag(mut self, tag: impl Into<String>) -> Self {
        self.tag = Some(tag.into());
        self
    }

    /// The icon set via [`Self::with_icon`], if any.
    pub fn icon(&self) -> Option<&ImageSource> {
        self.icon.as_ref()
    }

    /// The action buttons registered via [`Self::with_action`], in
    /// registration order.
    pub fn actions(&self) -> &[(WidgetId, String)] {
        &self.actions
    }

    /// Whether [`Self::with_silent`] was set.
    pub fn is_silent(&self) -> bool {
        self.silent
    }

    /// The tag set via [`Self::with_tag`], if any.
    pub fn tag(&self) -> Option<&str> {
        self.tag.as_deref()
    }
}

#[cfg(test)]
mod notification_tests {
    use super::Notification;
    use crate::primitives::image::ImageSource;
    use crate::types::WidgetId;

    #[test]
    fn new_has_no_icon_actions_tag_and_is_not_silent_or_urgent() {
        let n = Notification::new("t", "b");
        assert_eq!(n.title, "t");
        assert_eq!(n.body, "b");
        assert!(!n.urgent);
        assert!(n.icon().is_none());
        assert!(n.actions().is_empty());
        assert!(!n.is_silent());
        assert!(n.tag().is_none());
    }

    #[test]
    fn with_icon_is_read_back_by_icon() {
        let n = Notification::new("t", "b").with_icon(ImageSource::Bytes(vec![1, 2, 3]));
        assert_eq!(n.icon(), Some(&ImageSource::Bytes(vec![1, 2, 3])));
    }

    #[test]
    fn with_action_appends_in_registration_order() {
        let n = Notification::new("t", "b")
            .with_action(WidgetId::new("first"), "First")
            .with_action(WidgetId::new("second"), "Second");
        assert_eq!(
            n.actions(),
            &[
                (WidgetId::new("first"), "First".to_string()),
                (WidgetId::new("second"), "Second".to_string()),
            ]
        );
    }

    #[test]
    fn with_silent_is_read_back_by_is_silent() {
        assert!(Notification::new("t", "b").with_silent(true).is_silent());
        assert!(!Notification::new("t", "b").with_silent(false).is_silent());
    }

    #[test]
    fn with_tag_is_read_back_by_tag() {
        let n = Notification::new("t", "b").with_tag("build-status");
        assert_eq!(n.tag(), Some("build-status"));
    }
}

#[cfg(test)]
mod backend_caps_tests {
    use super::BackendCaps;

    #[test]
    fn empty_declares_nothing() {
        assert!(BackendCaps::empty().names().is_empty());
        assert!(!BackendCaps::empty().has("text_selection"));
    }

    #[test]
    fn names_round_trips_through_has() {
        let caps = BackendCaps {
            text_selection: true,
            file_dialogs: true,
            ..BackendCaps::empty()
        };
        let names = caps.names();
        assert_eq!(names, vec!["text_selection", "file_dialogs"]);
        for name in &names {
            assert!(caps.has(name), "{name:?} in names() but has() disagrees");
        }
        // Every other capability name is honestly absent.
        for (name, _) in BackendCaps::ALL_NAMES {
            if !names.contains(name) {
                assert!(!caps.has(name), "{name:?} not in names() but has() = true");
            }
        }
    }

    #[test]
    fn has_is_false_not_a_panic_for_an_unknown_name() {
        assert!(!BackendCaps::empty().has("not_a_real_capability"));
    }

    /// A capability name paired with a setter for the field it names —
    /// the write-side mirror of [`super::NamedCap`]'s read-side accessor.
    type NamedSetter = (&'static str, fn(&mut BackendCaps));

    /// Every capability name paired with a setter for the field it is
    /// supposed to read. Deliberately written out rather than derived
    /// from `ALL_NAMES`: this table's whole job is to be an *independent*
    /// statement of the field↔name mapping, so a copy-paste slip in
    /// `ALL_NAMES` (two entries reading the same field — the classic way
    /// a bitflag table goes wrong) has something to disagree with.
    const SETTERS: &[NamedSetter] = &[
        ("mouse", |c| c.mouse = true),
        ("scroll", |c| c.scroll = true),
        ("drag", |c| c.drag = true),
        ("text_selection", |c| c.text_selection = true),
        ("native_menu", |c| c.native_menu = true),
        ("window_chrome", |c| c.window_chrome = true),
        ("pointer_cursor", |c| c.pointer_cursor = true),
        ("ime", |c| c.ime = true),
        ("file_dialogs", |c| c.file_dialogs = true),
        ("folder_dialogs", |c| c.folder_dialogs = true),
        ("native_dialogs", |c| c.native_dialogs = true),
        ("notifications", |c| c.notifications = true),
        ("app_font_registration", |c| c.app_font_registration = true),
        ("window_control", |c| c.window_control = true),
        ("tray", |c| c.tray = true),
        ("generic_font_families", |c| c.generic_font_families = true),
    ];

    #[test]
    fn all_names_lists_every_field_exactly_once() {
        // Exhaustive destructure on purpose: adding a `BackendCaps` field
        // without adding it to `SETTERS` (and therefore to the `want`
        // list below, and therefore to `ALL_NAMES`) is a *compile* error
        // here. A field missing from `ALL_NAMES` would otherwise be
        // invisible to `names()`/`has()`/`vocabulary()` — and so to every
        // scenario `requires` gate and to the C0 honesty check.
        //
        // `color_depth`, `kitty_keyboard`, and `sgr_pixel_mouse` are the
        // deliberate exceptions: none is a bool *capability* in the "does
        // this backend implement optional surface X" sense (see each
        // field's doc comment on `BackendCaps`) — all three are
        // runtime-detected properties of the terminal a TUI session
        // happens to be running in. They are named here — forcing a future
        // field addition to make a conscious choice about which bucket it
        // belongs in — but intentionally left out of
        // `SETTERS`/`want`/`ALL_NAMES`.
        let BackendCaps {
            mouse: _,
            scroll: _,
            drag: _,
            text_selection: _,
            native_menu: _,
            window_chrome: _,
            pointer_cursor: _,
            ime: _,
            file_dialogs: _,
            folder_dialogs: _,
            native_dialogs: _,
            notifications: _,
            app_font_registration: _,
            window_control: _,
            tray: _,
            generic_font_families: _,
            color_depth: _,
            kitty_keyboard: _,
            sgr_pixel_mouse: _,
        } = BackendCaps::empty();

        let want: Vec<&str> = SETTERS.iter().map(|(n, _)| *n).collect();
        let got: Vec<&str> = BackendCaps::ALL_NAMES.iter().map(|(n, _)| *n).collect();
        assert_eq!(got, want);
        assert_eq!(BackendCaps::vocabulary(), want);
    }

    #[test]
    fn each_accessor_reads_its_own_field() {
        for (name, set) in SETTERS {
            let mut caps = BackendCaps::empty();
            set(&mut caps);
            assert_eq!(
                caps.names(),
                vec![*name],
                "setting only `{name}` should make exactly `{name}` declared — an `ALL_NAMES` \
                 accessor is reading the wrong field"
            );
            assert!(caps.has(name));
        }
    }

    #[test]
    fn vocabulary_is_the_superset_names_draws_from() {
        let vocab = BackendCaps::vocabulary();
        let mut all = BackendCaps::empty();
        for (_, set) in SETTERS {
            set(&mut all);
        }
        assert_eq!(
            all.names(),
            vocab,
            "with every field true, `names()` must be the whole vocabulary"
        );
    }
}

#[cfg(test)]
mod clipboard_default_tests {
    //! Coverage for [`Clipboard`]'s defaulted methods
    //! (`read_image`/`write_image`/`write_html`/`read_file_list`/
    //! `formats`/`clear`), backend-agnostic: a bare fake `impl Clipboard`
    //! that overrides nothing but `read_text`/`write_text` stands in for
    //! "a backend that hasn't touched this surface at all" (the whole
    //! point of keeping these methods defaulted rather than required —
    //! every existing implementor keeps compiling). Real
    //! per-backend wiring (arboard-backed image/html/file-list on
    //! macOS/GTK, `CF_HDROP` file-list + `EmptyClipboard` on Win) is
    //! covered in each backend's own `services.rs` tests instead, since
    //! it needs that backend's real native clipboard.
    use super::*;
    use std::cell::RefCell;

    /// Minimal `Clipboard` impl backed by an in-process `RefCell<Option<String>>`
    /// — enough to exercise every trait *default* without touching any OS
    /// clipboard API.
    #[derive(Default)]
    struct FakeTextOnlyClipboard {
        text: RefCell<Option<String>>,
    }

    impl Clipboard for FakeTextOnlyClipboard {
        fn read_text(&self) -> Option<String> {
            self.text.borrow().clone()
        }

        fn write_text(&self, text: &str) {
            *self.text.borrow_mut() = Some(text.to_string());
        }
    }

    #[test]
    fn image_html_file_list_and_clear_default_to_unsupported() {
        let cb = FakeTextOnlyClipboard::default();
        assert_eq!(cb.read_image(), Err(BackendError::Unsupported));
        assert_eq!(
            cb.write_image(&RgbaImage {
                width: 1,
                height: 1,
                pixels: vec![0, 0, 0, 255],
            }),
            Err(BackendError::Unsupported)
        );
        assert_eq!(
            cb.write_html("<b>hi</b>", "hi"),
            Err(BackendError::Unsupported)
        );
        assert_eq!(cb.read_file_list(), Err(BackendError::Unsupported));
        assert_eq!(cb.clear(), Err(BackendError::Unsupported));
    }

    #[test]
    fn formats_is_empty_when_clipboard_is_empty() {
        let cb = FakeTextOnlyClipboard::default();
        assert!(cb.formats().is_empty());
    }

    #[test]
    fn formats_reports_text_once_written_and_nothing_else() {
        let cb = FakeTextOnlyClipboard::default();
        cb.write_text("hello");
        // Image/file-list stay `Unsupported` on this fake, so `formats`
        // must not report them just because text is present.
        assert_eq!(cb.formats(), vec![ClipboardFormat::Text]);
    }

    /// A fake that also backs `read_image`/`read_file_list`, to prove
    /// `formats`'s default dispatches through `self` (i.e. reaches an
    /// override) rather than hardcoding the trait's own default bodies.
    #[derive(Default)]
    struct FakeFullClipboard {
        text: RefCell<Option<String>>,
        image: RefCell<Option<RgbaImage>>,
        file_list: RefCell<Vec<PathBuf>>,
    }

    impl Clipboard for FakeFullClipboard {
        fn read_text(&self) -> Option<String> {
            self.text.borrow().clone()
        }

        fn write_text(&self, text: &str) {
            *self.text.borrow_mut() = Some(text.to_string());
        }

        fn read_image(&self) -> ServiceResult<RgbaImage> {
            self.image.borrow().clone().ok_or(BackendError::Unsupported)
        }

        fn read_file_list(&self) -> ServiceResult<Vec<PathBuf>> {
            Ok(self.file_list.borrow().clone())
        }
    }

    #[test]
    fn formats_dispatches_through_overrides_for_image_and_file_list() {
        let cb = FakeFullClipboard::default();
        assert!(cb.formats().is_empty());

        *cb.image.borrow_mut() = Some(RgbaImage {
            width: 2,
            height: 2,
            pixels: vec![0; 16],
        });
        assert_eq!(cb.formats(), vec![ClipboardFormat::Image]);

        cb.file_list.borrow_mut().push(PathBuf::from("/tmp/a.txt"));
        assert_eq!(
            cb.formats(),
            vec![ClipboardFormat::Image, ClipboardFormat::FileList]
        );

        cb.write_text("hi");
        assert_eq!(
            cb.formats(),
            vec![
                ClipboardFormat::Text,
                ClipboardFormat::Image,
                ClipboardFormat::FileList
            ]
        );
    }

    #[test]
    fn empty_file_list_does_not_count_as_the_file_list_format() {
        let cb = FakeFullClipboard::default();
        // `read_file_list` returns `Ok(vec![])` (empty, but not
        // `Unsupported`) — `formats` must treat that the same as "no
        // file list present", not report `ClipboardFormat::FileList`.
        assert!(cb.formats().is_empty());
    }
}

/// Coverage for [`KeyringSecretStore`] — the real, `keyring`-backed
/// implementation [`PlatformServices::secret_store`]'s default vends.
/// Tests a real round trip against this host's actual
/// credential store, same headless-skip posture as `desktop.rs`'s
/// `move_to_trash_tests`: a store that's genuinely unreachable (no D-Bus
/// session, a locked/sandboxed keychain) is an environment limitation,
/// not a bug in this code, so those cases skip with an explanation
/// rather than fail.
///
/// **That posture has to hold for *every* step of a round trip, not just
/// the first one** — the lesson of this module's own CI failure. "No
/// usable credential store" is not one binary condition a test can check
/// up front and then assume away: a Secret Service can be *reachable*
/// (so `set` creates a collection and succeeds) while every subsequent
/// read is gated behind an interactive unlock prompt that a headless
/// runner can never answer (so `get` fails ~25s later). `ci.yml`'s `gtk`
/// job is exactly that host and nothing else in the fleet is: its
/// `apt-get install libgtk-4-dev libpango1.0-dev libcairo2-dev` pulls
/// `gnome-keyring` + a session bus into the runner transitively, which
/// the otherwise-identical `tui` job never gets. So `set`-then-fail is
/// reachable on one Linux CI leg and not the other, and a test that
/// hard-asserts on anything after a successful `set` is asserting on the
/// runner's apt closure. Every store call below therefore treats `Err`
/// as a skip; only *wrong values* from a store that answered are
/// failures.
#[cfg(all(
    test,
    any(feature = "tui", feature = "gtk", feature = "macos", feature = "win")
))]
mod secret_store_tests {
    use super::*;

    /// Every entry this module's tests touch shares this service name and
    /// gets its own `account`, namespaced by process id plus a
    /// test-specific suffix so concurrent test runs (and re-runs against
    /// a real, persistent OS credential store) never collide with each
    /// other or leave state a later run trips over.
    const SERVICE: &str = "quadraui-958-secret-store-test";

    fn unique_account(suffix: &str) -> String {
        format!("account-{}-{suffix}", std::process::id())
    }

    /// `Ok(v)` ⇒ the store answered, keep asserting on `v`. `Err` ⇒ this
    /// host has no usable credential store *for this operation*, so
    /// report why and let the caller bail out — see the module doc for
    /// why that judgement is made per call rather than once up front.
    #[allow(clippy::print_stderr)]
    fn answered<T>(op: &str, result: ServiceResult<T>) -> Option<T> {
        match result {
            Ok(v) => Some(v),
            Err(e) => {
                eprintln!(
                    "skipping: secret_store {op} failed in this environment ({e:?}) — \
                     no reachable/unlockable keyring (no D-Bus session, or a collection \
                     that only an interactive prompt can unlock)"
                );
                None
            }
        }
    }

    /// Set → get → delete → get against a fresh service/account pair.
    /// Any step that the host's store can't service skips the rest — see
    /// the module doc. A store that *answers* with the wrong secret (or
    /// still has one after `delete`) is always a real failure.
    #[test]
    fn round_trip_set_get_delete() {
        let store = KeyringSecretStore;
        let account = unique_account("round-trip");

        if answered("set()", store.set(SERVICE, &account, "s3cr3t")).is_none() {
            return;
        }

        let Some(read_back) = answered("get()", store.get(SERVICE, &account)) else {
            // The write landed but can't be read back here; don't leave
            // it behind for whatever runs next against this store.
            let _ = store.delete(SERVICE, &account);
            return;
        };
        assert_eq!(
            read_back,
            Some("s3cr3t".to_string()),
            "get() must return exactly what set() just wrote"
        );

        if answered("delete()", store.delete(SERVICE, &account)).is_none() {
            return;
        }

        let Some(after_delete) = answered("get() after delete()", store.get(SERVICE, &account))
        else {
            return;
        };
        assert_eq!(
            after_delete, None,
            "get() after delete() must report no entry, not the deleted secret"
        );
    }

    /// A service/account pair that was never set reads as `Ok(None)` —
    /// this trait's "nothing here, not a failure" idiom (see
    /// [`SecretStore`]'s own doc) — not `Err`. Tolerates `Err` from the
    /// underlying store as an environment-limitation skip, same as
    /// [`round_trip_set_get_delete`], but a `Some` would mean a leaked
    /// entry from a previous run and is always a real failure.
    #[test]
    fn get_on_an_entry_that_was_never_set_reports_no_entry() {
        let store = KeyringSecretStore;
        let account = unique_account("never-set");

        let Some(found) = answered("get()", store.get(SERVICE, &account)) else {
            return;
        };
        assert_eq!(
            found, None,
            "fresh service/account pair should have no entry — leftover from a previous \
             test run?"
        );
    }

    /// Deleting an entry that doesn't exist is a real, reported failure —
    /// not silently `Ok(())` — matching
    /// [`PlatformServices::move_to_trash`]'s identical stance for a
    /// nonexistent path (see [`SecretStore`]'s own doc).
    ///
    /// This one needs no environment skip and deliberately doesn't have
    /// one: `Err` is the assertion, and an unreachable store produces
    /// `Err` too, so the test is meaningful where a store exists and
    /// vacuously true (never wrong) where one doesn't.
    #[test]
    fn delete_on_a_nonexistent_entry_is_a_reported_failure() {
        let store = KeyringSecretStore;
        let account = unique_account("delete-missing");

        assert!(
            store.delete(SERVICE, &account).is_err(),
            "delete() on an entry that was never set must not report success"
        );
    }

    /// [`keyring_error_to_backend`] folds every `keyring::Error` onto
    /// [`BackendError::PlatformFailure`], keeping the crate's own
    /// `Display` text as context — deterministic coverage that holds on
    /// a runner with no credential store at all, where every test above
    /// skips.
    #[test]
    fn keyring_errors_become_platform_failures_carrying_their_display_text() {
        let mapped = keyring_error_to_backend(keyring::Error::NoEntry);
        let BackendError::PlatformFailure { context } = mapped else {
            panic!("every keyring::Error must map to PlatformFailure, got {mapped:?}");
        };
        assert!(
            context.starts_with("keyring: "),
            "context must name the failing subsystem, got {context:?}"
        );
        assert!(
            context.len() > "keyring: ".len(),
            "context must keep the keyring error's own Display text, got {context:?}"
        );
    }
}

/// [`KeyringSecretStore`]'s fallback for a build with none of the
/// `tui`/`gtk`/`macos`/`win` features enabled — see that variant's own
/// doc. Exercised by `cargo test --no-default-features` (not part of
/// this crate's CI quality gate, which always enables at least `tui`,
/// but still a real, buildable configuration this crate supports).
#[cfg(all(
    test,
    not(any(feature = "tui", feature = "gtk", feature = "macos", feature = "win"))
))]
mod secret_store_unsupported_tests {
    use super::*;

    #[test]
    fn every_method_reports_unsupported_without_a_keyring_backend() {
        let store = KeyringSecretStore;
        assert_eq!(store.get("svc", "acct"), Err(BackendError::Unsupported));
        assert_eq!(
            store.set("svc", "acct", "secret"),
            Err(BackendError::Unsupported)
        );
        assert_eq!(store.delete("svc", "acct"), Err(BackendError::Unsupported));
    }
}