quadraui 0.6.1

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
//! GTK implementation of [`quadraui::Backend`].
//!
//! `GtkBackend` is the GTK equivalent of `tui_main::backend::TuiBackend`.
//! It owns the persistent UI state the trait requires (modal stack,
//! drag state, accelerator registry, viewport, platform services) plus
//! a transient frame-scope holding the active `&cairo::Context` and
//! `&pango::Layout` so trait `draw_*` methods can rasterise into the
//! GTK draw callback.
//!
//! ### Frame-scope mechanism (mirror of TUI)
//!
//! GTK's `set_draw_func(da, |da, cr, _w, _h| { … })` callback yields
//! `&cairo::Context` only inside the closure. `enter_frame_scope`
//! stashes type-erased pointers to the cairo context and the
//! per-frame `pango::Layout` (built once at frame start so every
//! `draw_*` reuses the same one), runs the caller's closure, then
//! clears the pointers on exit.
//!
//! ### Event loop adapter (Stage 4)
//!
//! GTK is callback-driven; the trait's `wait_events`/`poll_events`
//! are poll-driven. `events: Rc<RefCell<VecDeque<UiEvent>>>` is the
//! adapter: signal handlers (mouse, key, resize) push translated
//! [`UiEvent`]s onto the queue; `wait_events(timeout)` drains it,
//! using `glib::MainContext::iteration(false)` to give the main
//! loop a chance to fire pending callbacks if the queue is empty.
//!
//! Stage 1 ships the struct shape and stub trait impls; the queue is
//! present but no signal callback is wired up yet (Stage 4).
//!
//! ### Why `Rc<RefCell<...>>` everywhere
//!
//! GTK signal callbacks need shared mutable access to backend state
//! across many widget closures. `Rc<RefCell<>>` is the standard
//! pattern in `gtk4-rs`. The trait method receivers (`&mut self`) work
//! fine: the App component wraps `GtkBackend` in `Rc<RefCell<>>` and
//! borrows mutably for trait calls.

use std::cell::Cell;
use std::collections::{HashMap, VecDeque};
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;

use gtk4::cairo::Context;
use gtk4::gdk;
use gtk4::glib;
use gtk4::pango;
use gtk4::prelude::*;

use crate::backend::{activity_bar_hits, tab_bar_hits_from_layout, BackendError};
use crate::desktop::WindowDragArm;
use crate::dispatch::{DoubleClickDetector, TextRegion};
use crate::event::{Point, Rect};
use crate::paint_surface::PaintSurface;
use crate::testing::ZoneRec;
use crate::types::{Color, WidgetId};
use crate::{
    Accelerator, AcceleratorId, ActivityBar, Backend, CommandLine, DragState, FieldKind, Form,
    GenericFamily, ListView, MenuBar, ModalStack, Palette, PlatformServices, PointerShape,
    Rect as QRect, ResizeEdge, Split, StatusBar, TabBar, TabBarLayout, TabChrome,
    Terminal as TerminalPrim, TextDisplay, TreeView, UiEvent, UserPayload, Viewport,
};
// `AcceleratorScope`/`KeyBinding` are only used by `#[cfg(test)]`
// code below — they're gated to avoid unused import warnings.
// `register_accelerator`/`match_keypress` moved their bodies
// into `crate::backend_core::BackendCore`.
#[cfg(test)]
use crate::{AcceleratorScope, KeyBinding};

use super::services::GtkPlatformServices;

/// Position tolerance, in DIPs, for [`GtkBackend::fold_double_click`]'s
/// [`DoubleClickDetector`] — GTK's `MouseDown` positions are point-
/// precision pixels, the same coordinate system macOS/Win-GUI use, so
/// this mirrors `MAC_DOUBLE_CLICK_RADIUS`/`WIN_DOUBLE_CLICK_RADIUS`
/// rather than the tighter cell-tuned default
/// [`crate::dispatch::DoubleClickDetector::new`] otherwise picks.
/// Like other backends, GTK uses the shared [`DoubleClickDetector`]-backed
/// [`Self::fold_double_click`] via [`crate::runtime::preprocess_event`]
/// to give every backend one definition of "what counts as a double-click."
pub(crate) const GTK_DOUBLE_CLICK_RADIUS: f32 = 4.0;

/// One piece of text painted this frame, with its on-surface bounds in
/// backend (pixel) coordinates. Recorded via
/// [`GtkBackend::record_painted_text`] into [`GtkBackend::painted_text`].
/// Either a whole logical label by the trait method that painted it,
/// or per painted glyph run by [`super::painted_text`].
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct PaintedText {
    pub(crate) text: String,
    pub(crate) bounds: QRect,
}

/// Names one `GtkBackend`'s slot in [`WAKE_CALLBACKS`].
///
/// This is the *entire* payload [`GtkBackend::waker`]'s returned closure
/// carries across the thread boundary: a plain integer, trivially
/// `Send + Sync + Copy`. The `!Send` wake target it names never leaves
/// the thread that installed it — see [`WAKE_CALLBACKS`].
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub(crate) struct WakeId(u64);

impl WakeId {
    /// Hand out an id no other `GtkBackend` in this process has held.
    /// Process-wide (not per-thread) so an id is unambiguous even though
    /// the map it keys is thread-local — a stale id from a dropped
    /// backend can therefore never alias a live one's callback.
    fn next() -> Self {
        static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        Self(NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed))
    }
}

thread_local! {
    /// Wake targets installed by [`GtkBackend::set_wake_callback`], keyed
    /// by [`WakeId`] — the `Rc<dyn Fn()>` that
    /// `gtk::run::run_with`'s periodic drain closure also is.
    ///
    /// **Thread-local on purpose, and that is the whole soundness
    /// argument.** `waker()` must return a `Send + Sync` closure, but the
    /// only thing worth waking is a handle owned by the GTK main thread
    /// (`Rc<RefCell<GtkBackend>>`/`Rc<RefCell<App>>` — deliberately
    /// `!Send`, the same architectural fact that makes
    /// [`crate::runtime::UserEventQueue`] a separate `Send + Sync`
    /// staging area). Rather than smuggle that `Rc` through a hand-rolled
    /// `unsafe impl Send` wrapper — which has to answer "what happens when
    /// the last handle is dropped on a background thread?", and answers it
    /// either by racing `Rc`'s non-atomic refcount (unsound) or by
    /// blocking on the main loop (deadlocks whenever that loop isn't
    /// running) — the `Rc` simply never crosses the boundary at all. A
    /// background thread carries a `u64`; the lookup happens on whatever
    /// thread `glib::MainContext::invoke` runs the closure on, and only
    /// the installing thread's map has an entry, so a lookup from any
    /// other thread misses and no-ops instead of touching the `Rc`.
    ///
    /// The miss case is not a lost event: the payload is already in
    /// [`GtkBackend::user_events`] before the wake is even attempted, so
    /// `gtk::run::run_with`'s 33ms drain still delivers it — a wake that
    /// lands on the wrong thread degrades latency, never correctness.
    static WAKE_CALLBACKS: std::cell::RefCell<HashMap<WakeId, Rc<dyn Fn()>>> =
        std::cell::RefCell::new(HashMap::new());
}

/// Clone out the wake target `id` names, if this thread is the one that
/// installed it. Clones (rather than calling under the map's borrow) so a
/// callback that reaches back into this map — a nested drain that drops
/// or constructs a `GtkBackend`, say — can't hit a `RefCell` double-borrow
/// panic inside a non-unwindable GLib callback frame.
fn wake_callback_for(id: WakeId) -> Option<Rc<dyn Fn()>> {
    WAKE_CALLBACKS
        .try_with(|slots| slots.borrow().get(&id).map(Rc::clone))
        .unwrap_or(None)
}

/// GTK backend implementing [`quadraui::Backend`].
///
/// Field roles:
/// - `viewport` — width × height in DIPs, scale factor (HiDPI). Updated
///   each frame from the active DrawingArea's `width()` / `height()`.
/// - `modal_stack` — pushed by `App` on modal open, popped on close.
///   `quadraui::dispatch::dispatch_mouse_down` consults it.
/// - `drag_state` — at most one in-flight scrollbar drag. Set on
///   click-down on a scrollbar, read each drag-update, cleared on
///   mouse-up.
/// - `core` — registered keybindings + text-selection bookkeeping,
///   consolidated into [`crate::backend_core::BackendCore`].
///   `apply_accelerators` rewrites matching `KeyPressed` events to
///   `UiEvent::Accelerator(id, mods)` before they reach the app.
/// - `events` — adapter queue between GTK signal callbacks and the
///   trait's poll-style `wait_events`. Stage 4 wires up the producers.
/// - `current_*_ptr` — frame-scope pointers; non-null only inside
///   [`Self::enter_frame_scope`]. Type-erased through `*mut ()` to
///   avoid threading lifetime parameters onto the struct.
/// - `current_theme` — captured once per frame so `draw_*` calls don't
///   need to re-derive theme colors per primitive.
///
/// The `Rc<RefCell<>>` wrappers on `modal_stack` / `drag_state` /
/// `events` mirror the existing GTK App pattern — signal callbacks
/// clone the `Rc` into their captures and `borrow_mut()` when they
/// fire. The trait method bodies just dereference through.
pub struct GtkBackend {
    viewport: Viewport,
    /// Current GDK surface scale factor (HiDPI multiplier), tracked
    /// independently of `viewport`. `run.rs::render_frame`
    /// seeds every frame's `Viewport::scale` from this rather than a
    /// hardcoded `1.0`, and `gtk::run`'s `notify::scale-factor` handler
    /// (fired on a live monitor/DPI change, not just resize) updates it
    /// via [`Self::set_dpi_scale`] before dispatching
    /// `UiEvent::DpiChanged`. Defaults to `1.0`, matching every other
    /// backend's pre-realization placeholder.
    dpi_scale: f32,
    modal_stack: Rc<std::cell::RefCell<ModalStack>>,
    drag_state: Rc<std::cell::RefCell<DragState>>,
    /// Accelerator registry + text-selection bookkeeping — see
    /// [`crate::backend_core::BackendCore`]'s module doc. Replaces the
    /// formerly GTK-local `accelerators`/`parsed_accelerators` fields
    /// verbatim, plus (below) the formerly separate `text_selection`
    /// field.
    core: crate::backend_core::BackendCore,
    /// Adapter queue between GTK callbacks (producers) and
    /// `wait_events` / `poll_events` (consumers). Stage 4 wires the
    /// producers.
    events: Rc<std::cell::RefCell<VecDeque<UiEvent>>>,
    services: GtkPlatformServices,
    /// Type-erased `&cairo::Context` pointer; non-null only inside
    /// [`Self::enter_frame_scope`].
    current_cr_ptr: Cell<*const ()>,
    /// Type-erased `&pango::Layout` pointer; non-null only inside
    /// [`Self::enter_frame_scope`]. Built once per frame from the
    /// cairo context's pangocairo context, reused by every `draw_*`
    /// call so font-metrics setup doesn't repeat per primitive.
    current_layout_ptr: Cell<*const ()>,
    current_theme: crate::Theme,
    /// Captured once per frame, mirroring `current_theme` — see
    /// [`crate::Style`]'s module doc for why this is a separate field
    /// rather than folded into `Theme`.
    current_style: crate::Style,
    /// Decoded/scaled-`Pixbuf` cache for [`Backend::draw_image`]
    /// — see [`crate::image_cache`]'s module doc. Keyed on
    /// `(image.source, target size, dpi_scale)`; survives across frames
    /// (unlike `zones`), since the whole point is skipping a re-decode on
    /// a later paint of the same source.
    image_cache: crate::image_cache::ImageCache<gtk4::gdk_pixbuf::Pixbuf>,
    /// Cached glyph atlas for [`Backend::draw_minimap`]'s real-character
    /// rendering — see [`crate::primitives::minimap::MinimapAtlasCache`]'s
    /// module doc. Keyed on `(editor font family, dpi_scale)`; survives
    /// across frames, same lifecycle as `image_cache` above and for the
    /// same reason: the whole point is never re-shaping-and-downsampling
    /// the atlas on a later paint at the same family/scale.
    minimap_atlas_cache: crate::primitives::minimap::MinimapAtlasCache,
    /// [`crate::backend::Backend::minimap_scale`]'s backing field
    /// — read by [`Backend::draw_minimap`]/[`Backend::minimap_layout`]
    /// to resolve the row pitch (and, for the atlas, per-column width) a
    /// paint or layout call uses. Defaults to [`crate::primitives::minimap::MinimapScale::One`],
    /// the fixed pitch, so a host that never calls
    /// [`Backend::set_minimap_scale`] sees no behaviour change.
    minimap_scale: crate::primitives::minimap::MinimapScale,
    /// Per-frame Pango line height in DIPs. Set by the App in its
    /// draw closure (from font metrics) before any trait `draw_*`
    /// invocation. Every primitive that uses text metrics passes
    /// this through.
    current_line_height: f64,
    /// Per-frame Pango approximate-char-width in DIPs. Set by the
    /// App alongside `current_line_height`. Required by primitives
    /// that map cells to pixels (e.g. `draw_terminal`).
    current_char_width: f64,
    /// Editor vertical scrollbar column width set through
    /// [`Backend::set_editor_v_scrollbar_width`]; `None` = one
    /// `current_char_width` wide.
    editor_v_scrollbar_w: Option<f32>,
    /// Per-frame Pango advance for `ui_font` (the chrome twin of
    /// `current_char_width`), in DIPs — backs [`Backend::list_char_width`].
    /// `draw_list` paints row text in `ui_font`, not the editor font
    /// `current_char_width` measures, so a consumer sizing
    /// list content from `current_char_width` under-fills the row
    /// whenever the two fonts' advances differ. Refreshed once
    /// per frame by `gtk::run::render_frame` via
    /// [`Self::refresh_chrome_char_width`], the same way
    /// `current_char_width` is refreshed from the editor font.
    current_chrome_char_width: f64,
    /// Pango context for text measurement outside the draw callback.
    /// Set once via [`Self::set_pango_context`] during init; used by
    /// `form_layout()` and other `_layout()` methods that need exact
    /// Pango measurement rather than the `current_char_width` approximation.
    pango_ctx: Option<pango::Context>,
    /// Whether nerd-font glyphs should be used by primitives that
    /// have icon variants. Apps wire this from their own setting
    /// (vimcode reads `engine.settings.use_nerd_fonts`); kubeui has
    /// its own toggle. Mirrors the `TuiBackend` field of the same
    /// name.
    ///
    /// Defaults to `true` on this backend — unlike TUI,
    /// where a wrong `true` paints tofu for a terminal with no Nerd
    /// Font installed (see [`crate::Backend::set_nerd_fonts`]'s own
    /// doc for that risk calculus), a GTK host always has the bundled
    /// codicon font available (`GtkBackend::new` self-registers it
    /// unconditionally), so an app's own [`crate::Icon::glyph`] built
    /// from a codicon codepoint paints correctly with no app opt-in.
    /// An app whose own glyph choice assumes a *different*, uninstalled
    /// icon font can still call `set_nerd_fonts(false)` to opt back out.
    nerd_fonts_enabled: bool,
    /// Pango font description string for UI chrome (sans-serif text
    /// in title/buttons of `Dialog`, etc). Format is
    /// `"<family> <size>"` per Pango convention. Apps set this from
    /// their settings (vimcode passes `format!("{} {}", ui_font_family,
    /// ui_font_size)`). Falls back to `"Sans 11"` if unset.
    ui_font: String,
    /// Font family used to paint [`crate::primitives::editor::Editor`]
    /// content. Defaults to `"Monospace"` — the historical hardcoded
    /// value. Set via [`Backend::set_editor_font`]; `gtk/run.rs`'s draw
    /// closure reads it (via [`Self::editor_font_pango_string`]) every
    /// frame to build the shared editor `pango::Layout`, so painted
    /// glyphs and the `current_line_height` / `current_char_width`
    /// metrics resolved from the same font never drift apart.
    editor_font_family: String,
    /// Editor font size in points, paired with `editor_font_family`.
    /// Defaults to `11.0` (the historical hardcoded value).
    editor_font_size_pt: f32,
    /// Widget zones registered during the current frame via
    /// [`Backend::register_zone`]. Cleared at the start of each frame by
    /// [`Self::begin_frame`]. Parallels `TuiBackend::zones`. Read by
    /// [`super::testing::GtkDriver::inventory`] to populate
    /// [`crate::testing::FrameInventory::zones`].
    pub(crate) zones: Vec<ZoneRec>,
    /// The `(text, bounds)` map painted this frame — recorded by trait
    /// methods that compute a label's on-surface rect so
    /// [`super::testing::GtkDriver::find`] can locate a control without
    /// hardcoded coordinates. Cleared at the start of each frame by
    /// [`Self::begin_frame`]; mirrors `text_regions`' lifecycle. Coverage
    /// is incremental — only widgets whose trait method has been updated
    /// to call [`Self::record_painted_text`] appear here; see that method's docs.
    ///
    /// Also fed, per painted glyph run, by [`super::painted_text::show_layout`]
    /// — the choke point every GTK rasteriser routes its Pango painting through
    /// — so every text-bearing primitive reports in, not just those whose trait
    /// methods hand-roll a `record_painted_text` call. Hand-rolled (logical,
    /// hit-test-aligned) records land here first, ahead of the frame's glyph runs,
    /// so `find_bounds` keeps resolving them to the label rect a click needs.
    /// Requires [`Self::set_painted_text_recording`].
    pub(crate) painted_text: Vec<PaintedText>,
    /// Whether the per-glyph-run recording described on
    /// [`Self::painted_text`] is active. Off by default: a live app never
    /// reads `painted_text`, and recording every run would allocate a
    /// `String` per painted text run per frame.
    /// [`super::testing::GtkDriver`] turns it on.
    painted_text_recording: bool,
    /// `WidgetId` of the `ActivityBar` that declared `is_keyboard_focused`
    /// during the most recent render pass. Cleared by `begin_frame` and
    /// re-set by `draw_activity_bar`. The GTK runner reads this in the
    /// window-level key handler to convert `KeyPressed` events into
    /// `UiEvent::ActivityBar(id, ActivityBarEvent::KeyPressed { … })` so
    /// consumers receive typed key events without fighting GTK widget focus.
    focused_activity_bar: Option<WidgetId>,
    /// Top-level window handle, set once by `gtk::run::activate` via
    /// [`Self::set_window`]. `None` until the runner finishes constructing
    /// the window (and in unit tests, which never call `set_window`).
    /// Backs [`Backend::begin_window_drag`] / [`Backend::toggle_window_maximize`]
    /// — the CSD titlebar drag/maximize escape hatch.
    window: Option<gtk4::ApplicationWindow>,
    /// Raw GDK context (device, button, x, y, timestamp) of the most
    /// recent primary-button press, stashed by `gtk/run.rs`'s
    /// `GestureClick::connect_pressed` before the press is translated to a
    /// portable [`UiEvent`]. [`Backend::begin_window_drag`] consumes this
    /// (via `.take()`) to arm [`Self::armed_window_drag`] with the real
    /// device/timestamp the gesture requires — GDK ignores synthesized
    /// values on some compositors.
    pending_window_press: Option<(gdk::Device, i32, f64, f64, u32)>,
    /// Armed-but-not-yet-started window-drag request. Set by
    /// [`Backend::begin_window_drag`] from [`Self::pending_window_press`];
    /// consumed by [`Self::try_commit_window_drag`], which `gtk/run.rs`'s
    /// motion controller calls on every pointer move — it only actually commits
    /// (and calls the native `begin_move`) once the pointer has moved past the
    /// drag threshold since the arming press.
    ///
    /// This split exists because calling `gdk4::Toplevel::begin_move`
    /// synchronously on the very first press — before it's known whether
    /// a second press is coming — starts an interactive move grab that
    /// swallows the second press, so a double-click on a CSD titlebar
    /// never reaches the app as `UiEvent::DoubleClick`. This defers the
    /// move-start to a threshold-gated signal, mirroring native
    /// `gtk4::WindowHandle` behaviour. See [`WindowDragArm`]'s doc
    /// for the generalised rationale.
    armed_window_drag: WindowDragArm<(gdk::Device, i32, f64, f64, u32)>,
    /// Clone of the Pango layout `draw_menu_bar` actually painted with,
    /// stashed at the end of the frame's `enter_frame_scope` call.
    /// `menu_bar_layout` is invoked from click-time hit-testing
    /// (e.g. `MenuSystem::handle`), which runs *outside* any frame
    /// scope — `current_frame_refs()` is always `None` there. Without
    /// this cache the click-time measurement fell all the way back to
    /// `pango_ctx`, which carries a different font (`"Sans 11"`, set
    /// once at widget-init in `gtk::run::activate`) than the frame's
    /// live layout (`"Monospace 11"`, set fresh every `set_draw_func`
    /// call) — the two fonts have different glyph widths, so hit
    /// regions silently drifted off the painted labels. Caching the
    /// *exact* `pango::Layout` GObject used by the most recent paint
    /// (refcounted clone — cheap, and always reflects the current
    /// font/size) closes that gap: "cache at paint, hit-test at
    /// click" (see `quadraui/docs/LESSONS.md`).
    last_menu_bar_pango_layout: Option<pango::Layout>,
    /// Clone of the Pango layout `draw_editor` actually painted with,
    /// stashed at the end of the frame's `draw_editor` call. Mirrors
    /// [`Self::last_menu_bar_pango_layout`] for the same reason:
    /// `editor_col_at_x` is invoked from click-time hit-testing,
    /// which runs *outside* any frame scope — `current_frame_refs()` is
    /// `None` there, so falling back to `pango_ctx` would resolve
    /// against the wrong (UI, not editor) font and silently mis-place
    /// every click. Caching the exact layout GObject the most recent
    /// paint used (refcounted clone — cheap, always reflects the
    /// current editor font) closes that gap.
    last_editor_pango_layout: Option<pango::Layout>,
    /// `(bar rect, resolved layout)` from the most recent `draw_tab_bar`
    /// call, per tab-bar `WidgetId`. Cleared at the start of every frame
    /// by [`Self::begin_frame`] (same lifecycle as `zones`) so a tab bar
    /// that stops painting doesn't leave a stale entry that would resolve
    /// a tab no longer on screen.
    ///
    /// `TabBarLayout`'s own `visible_tabs`/`close_bounds` rects are
    /// bar-relative (origin at the bar's own top-left) — the same
    /// convention `crate::gtk::draw_tab_bar`'s `x_offset`/`y_offset`
    /// params paint against. [`Self::cached_tab_bar_layout`] hands back
    /// the paired rect so callers can shift into absolute screen-space
    /// coordinates. Read by [`super::testing::GtkDriver::tab_center`] /
    /// [`super::testing::GtkDriver::tab_close_center`].
    tab_bar_layouts: HashMap<WidgetId, (QRect, TabBarLayout)>,
    /// Monotonically increasing counter bumped once per [`Self::begin_frame`]
    /// call. Backs a dirty-row repaint fast path: a `TermPaintCache`
    /// entry is only reused when it was written during the *immediately
    /// preceding* frame (`painted_frame + 1 == frame_counter`). Any gap
    /// (the terminal pane went unpainted for a frame — e.g. a tab switch
    /// away and back) means some other primitive may have painted over
    /// those pixels in the meantime, so the cache is discarded and the
    /// next paint falls back to a full repaint.
    frame_counter: u64,
    /// Per-terminal-id cache of the most recently painted `Terminal`
    /// snapshot and the pixel geometry it was painted at — see
    /// [`Self::draw_terminal`] and `TermPaintCache`'s own docs.
    term_paint_cache: HashMap<WidgetId, TermPaintCache>,
    /// Folds a `MouseDown` into `DoubleClick` when it lands within
    /// [`GTK_DOUBLE_CLICK_RADIUS`]/400ms of the previous click at the
    /// same button — the shared mechanism every backend's
    /// `dispatch_event` now uses via [`Self::fold_double_click`].
    /// Mirrors `MacBackend::double_click`/
    /// `WinBackend::double_click`.
    double_click: DoubleClickDetector,
    /// Whether [`Self::fold_double_click`] is armed. Defaults to `true`
    /// (real double-click folding, matching the live GTK app and
    /// `TuiBackend`'s own default). [`super::testing::GtkDriver::set_double_click_folding`]
    /// turns it off so a test that dispatches two
    /// deliberate single clicks at the same spot in immediate succession
    /// — no real GDK press-count or wall-clock gap between them — gets
    /// two `MouseDown`s, not a coin-flip on `DoubleClickDetector`'s
    /// 400ms window. Mirrors `TuiBackend::double_click_folding` exactly.
    double_click_folding: bool,
    /// Single owner of keyboard focus — see
    /// [`crate::focus`]'s module doc. Mutated only by the shared
    /// Tab/Shift+Tab intercept in [`crate::runtime::preprocess_event`]
    /// via [`crate::runtime::PreprocessBackend::focus_manager_mut`];
    /// read elsewhere via [`Backend::focus_manager`].
    focus: crate::focus::FocusManager,
    /// Backend-neutral caret-blink phase for `MultiSectionView` aux-row
    /// text inputs (`SectionAux::Input`/`Search`) — see
    /// [`crate::caret_blink`]'s module doc for the state machine and the
    /// GTK-specific wiring it prescribes. `super::run::setup_caret_blink`
    /// ticks this once per [`crate::caret_blink::CaretBlinkState::period`]
    /// via a `glib::timeout_add_local` and queues a redraw when the phase
    /// flips; `super::run::dispatch_event` calls
    /// [`Self::note_caret_activity`] on `KeyPressed`/`CharTyped` so the
    /// caret holds solid while typing, mirroring `MacBackend`'s
    /// `caret_visible`/`paused_until` cells.
    caret_blink: crate::caret_blink::CaretBlinkState,
    /// Thread-safe inbox for [`crate::UiEvent::User`] payloads
    /// — see [`crate::runtime::UserEventQueue`]'s doc. [`Self::waker`]
    /// clones this `Arc` into the closure it hands out; [`Self::poll_events`]
    /// drains it into `UiEvent::User` alongside `events`, on the GTK main
    /// thread, same as any other queued event.
    user_events: Arc<crate::runtime::UserEventQueue>,
    /// This backend's slot in [`WAKE_CALLBACKS`], filled once by
    /// `gtk::run::run_with` via [`Self::set_wake_callback`] right after
    /// the periodic event-drain closure exists — see that closure's call
    /// site for why `waker()` needs a handle to it rather than
    /// reimplementing the drain inline. The slot stays empty until then
    /// (e.g. a `GtkBackend` constructed directly by a test, never handed
    /// to `gtk::run`); [`Self::waker`]'s returned closure is a documented
    /// no-op in that case, mirroring `RecordingBackend::waker`. Cleared
    /// again by this type's [`Drop`].
    wake_id: WakeId,
}

/// Releases this backend's [`WAKE_CALLBACKS`] slot, so the
/// installed `Rc<dyn Fn()>` — and everything it captures, which for
/// `gtk::run::run_with` is the whole app/backend graph — doesn't outlive
/// the backend it was installed for.
///
/// Always runs on the installing thread: `GtkBackend` holds `Rc`s and
/// GTK/GObject handles, so it is `!Send` and can only be dropped where it
/// was built. A [`Self::waker`] handle still alive on a background thread
/// keeps nothing here alive — it holds a [`WakeId`], not a reference —
/// so it can't resurrect the entry either; its later lookups simply miss.
impl Drop for GtkBackend {
    fn drop(&mut self) {
        // `try_with`: during thread teardown `WAKE_CALLBACKS` may already
        // be destroyed if a `GtkBackend` is itself parked in a
        // thread-local. Nothing to clean up in that case.
        let _ = WAKE_CALLBACKS.try_with(|slots| slots.borrow_mut().remove(&self.wake_id));
    }
}

/// Cached state from the most recent successful [`GtkBackend::draw_terminal`]
/// paint for one terminal id.
///
/// GTK retains the previous frame's pixels for anything a draw call
/// doesn't touch (see the ghosting note on [`GtkBackend::draw_terminal`]
/// and the resize-damage discussion in `gtk/run.rs`'s `connect_resize`
/// handler) — so as long as nothing else could have painted over a
/// terminal's rect since this snapshot was taken, rows whose cell content
/// hasn't changed can be skipped entirely rather than re-rasterised. The
/// `rect` / `line_height` / `char_width` / `cell_area_w` fields detect any
/// resize/reflow/scrollbar-toggle (which invalidates row alignment, not
/// just content); `painted_frame` / `modal_was_empty` detect anything else
/// that might have painted on top of this terminal's pixels between two
/// `draw_terminal` calls for the same id (a tab switch away and back, or a
/// dialog/palette/context-menu opening then closing); `theme` detects a
/// live theme swap (`Backend::set_theme`) between two paints, since
/// `dirty_rows` only diffs `TerminalCell` content and is blind to the
/// theme-derived colours `draw_terminal_cells` applies on top of unchanged
/// cells (`selected` / `is_cursor` / `is_find_match` overlays — see
/// `primitives/terminal.rs`'s module doc). Without this, selecting text
/// then toggling light/dark would leave the old theme's selection colour
/// on screen until some unrelated event forced a full repaint.
#[derive(Debug, Clone)]
struct TermPaintCache {
    term: TerminalPrim,
    rect: QRect,
    line_height: f64,
    char_width: f64,
    cell_area_w: f64,
    /// [`GtkBackend::frame_counter`] value when this snapshot was painted.
    painted_frame: u64,
    /// Whether `modal_stack` was empty at the time of that paint.
    modal_was_empty: bool,
    /// The theme in effect at the time of that paint. Compared by value
    /// (`Theme` is `Copy + PartialEq`) so *any* field change — not just the
    /// ones the terminal rasteriser currently reads — invalidates the fast
    /// path.
    theme: crate::Theme,
}

/// Adapts a live `pango::Layout` (falling back to `char_w` when no
/// Pango context is available, e.g. in headless tests) to the shared
/// [`crate::primitives::layout_metrics::TextMeasure`] trait so
/// `form_field_measure` never has to name a Pango type — mirrors
/// `macos::form::CtFontMeasure` / `win::form::DWriteMeasure`, which
/// exist for exactly this reason. Same width formula as
/// `GtkBackend::pango_str_width`.
struct PangoTextMeasure<'a> {
    layout: &'a Option<pango::Layout>,
    char_w: f32,
}

impl crate::primitives::layout_metrics::TextMeasure for PangoTextMeasure<'_> {
    fn width_of(&self, text: &str) -> f32 {
        if let Some(pl) = self.layout {
            pl.set_text(text);
            let (w, _) = pl.pixel_size();
            w as f32
        } else {
            (text.chars().count() as f32 * self.char_w).ceil() + 2.0
        }
    }
}

impl GtkBackend {
    /// Construct a fresh `GtkBackend`. The viewport defaults to
    /// (0, 0, 1.0); the App component overwrites it before the first
    /// frame via [`Backend::begin_frame`]. Call this once at App
    /// initialisation; share the resulting backend via
    /// `Rc<RefCell<GtkBackend>>` to every widget callback that needs
    /// access.
    pub fn new() -> Self {
        // Self-register the bundled codicon font unconditionally,
        // before anything paints — every chrome rasteriser that reaches
        // for a codicon glyph assumes it is already resolvable via
        // `crate::gtk::with_nerd_font_fallback`'s family list. Ignoring a
        // `false` return here is deliberate: a registration failure
        // leaves the Nerd-Font fallback chain exactly as it would be
        // without this call, so the worst case is a missing codicon
        // falling through to tofu rather than this constructor failing
        // outright (the same "degrade, don't fail" posture every other
        // optional font registration in this crate takes).
        super::app_font::ensure_codicon_registered();

        let events = Rc::new(std::cell::RefCell::new(VecDeque::new()));
        // Share the same queue with `GtkPlatformServices` so a
        // notification-action activation can push
        // `UiEvent::NotificationActivated` onto it — see
        // `gtk::services`'s module doc.
        let services = GtkPlatformServices::new();
        services.set_events_handle(events.clone());
        Self {
            viewport: Viewport::new(0.0, 0.0, 1.0),
            dpi_scale: 1.0,
            modal_stack: Rc::new(std::cell::RefCell::new(ModalStack::new())),
            drag_state: Rc::new(std::cell::RefCell::new(DragState::new())),
            core: crate::backend_core::BackendCore::default(),
            events,
            services,
            current_cr_ptr: Cell::new(std::ptr::null()),
            current_layout_ptr: Cell::new(std::ptr::null()),
            current_theme: crate::Theme::default(),
            current_style: crate::Style::default(),
            image_cache: crate::image_cache::ImageCache::default(),
            minimap_atlas_cache: crate::primitives::minimap::MinimapAtlasCache::default(),
            minimap_scale: crate::primitives::minimap::MinimapScale::default(),
            current_line_height: 16.0,
            current_char_width: 8.0,
            editor_v_scrollbar_w: None,
            // Arbitrary but plausible seed (mirrors `current_char_width`
            // above) — a real value is only established once
            // `refresh_chrome_char_width` runs inside a live frame; a
            // `GtkBackend` built directly by a test and never entered
            // into a frame scope just gets this placeholder back from
            // `list_char_width()`, same posture as `current_char_width`.
            current_chrome_char_width: 8.0,
            pango_ctx: None,
            nerd_fonts_enabled: true,
            ui_font: "Sans 11".to_string(),
            editor_font_family: "Monospace".to_string(),
            editor_font_size_pt: 11.0,
            zones: Vec::new(),
            painted_text: Vec::new(),
            painted_text_recording: false,
            focused_activity_bar: None,
            window: None,
            pending_window_press: None,
            armed_window_drag: WindowDragArm::new(),
            last_menu_bar_pango_layout: None,
            last_editor_pango_layout: None,
            tab_bar_layouts: HashMap::new(),
            frame_counter: 0,
            term_paint_cache: HashMap::new(),
            double_click: DoubleClickDetector::with_radius(GTK_DOUBLE_CLICK_RADIUS),
            double_click_folding: true,
            focus: crate::focus::FocusManager::new(),
            caret_blink: crate::caret_blink::CaretBlinkState::default(),
            user_events: crate::runtime::UserEventQueue::new(),
            wake_id: WakeId::next(),
        }
    }

    /// Install the closure [`Backend::waker`]'s returned handle invokes on
    /// the GTK main thread. `gtk::run::run_with` calls this
    /// once, right after building the periodic event-drain closure it also
    /// registers as a `glib::timeout_add_local` source — the same closure,
    /// reused, so a background-thread wake and the ordinary 33ms poll
    /// funnel through one dispatch path rather than two that could drift.
    ///
    /// A second call is a no-op — `run_with` only ever calls this once per
    /// backend instance, so a second call would only happen from a test
    /// wiring two runners to the same backend, which isn't a supported
    /// shape; the first installed target wins, as it did when this slot
    /// was a `OnceLock`.
    ///
    /// `callback` is stored in the [`WAKE_CALLBACKS`] thread-local of the
    /// calling thread — which must therefore be the GTK main thread, as it
    /// is for the sole production caller (`gtk::run::activate`, running
    /// inside `GtkApplication`'s `activate` signal). See that
    /// thread-local's doc for why the `!Send` `Rc` is parked there instead
    /// of being carried by [`Self::waker`]'s returned closure.
    pub(crate) fn set_wake_callback(&self, callback: Rc<dyn Fn()>) {
        let _ = WAKE_CALLBACKS.try_with(|slots| {
            slots.borrow_mut().entry(self.wake_id).or_insert(callback);
        });
    }

    /// Store the top-level window handle. Called once by `gtk::run::activate`
    /// right after the window is constructed. Backs
    /// [`Backend::begin_window_drag`] / [`Backend::toggle_window_maximize`],
    /// and hands the same window to [`GtkPlatformServices::set_window`] so
    /// file dialogs open parented to it.
    pub fn set_window(&mut self, window: gtk4::ApplicationWindow) {
        self.services.set_window(window.clone());
        self.window = Some(window);
    }

    /// Current tracked GDK scale factor — see [`Self::dpi_scale`]'s field
    /// doc. `gtk::run::render_frame` reads this every frame; it is not
    /// the same value as `self.viewport.scale` (which only updates when
    /// `begin_frame` runs) until the next paint has happened.
    pub(crate) fn dpi_scale(&self) -> f32 {
        self.dpi_scale
    }

    /// Update the tracked GDK scale factor — called from
    /// `gtk::run`'s `notify::scale-factor` handler and its debounced
    /// resize handler (both of which observe `DrawingArea::scale_factor()`)
    /// before dispatching the corresponding `UiEvent`. Does not itself
    /// touch `self.viewport` or trigger a repaint — mirrors
    /// `WinBackend::set_dpi_scale`'s "caller resizes/redraws separately"
    /// contract.
    pub(crate) fn set_dpi_scale(&mut self, scale: f32) {
        self.dpi_scale = scale;
    }

    /// Clone of the platform services' dialog-pump-depth counter — `> 0`
    /// while a [`GtkPlatformServices`] file dialog's nested-mainloop wait
    /// is in flight. `quadraui::gtk::run::activate` fetches this once
    /// during setup (before any event controller can re-enter) and
    /// clones it into every closure that calls `backend.borrow_mut()`,
    /// so those closures can no-op instead of double-borrowing the
    /// backend while `AppLogic::handle` (further up the call stack) is
    /// blocked inside the dialog pump.
    pub(crate) fn pump_depth(&self) -> crate::desktop::ModalPumpDepth {
        self.services.pump_depth()
    }

    /// Seed this backend's clipboard with deterministic in-memory
    /// contents, so a test can drive the Ctrl-V / Ctrl-Shift-V and
    /// middle-click paste paths without depending on the host's real
    /// clipboard state. Test-only.
    #[cfg(test)]
    pub(crate) fn install_test_clipboard(
        &self,
        contents: crate::gtk::services::TestClipboardContents,
    ) {
        self.services
            .gtk_clipboard()
            .install_test_contents(contents);
    }

    /// Stash the raw GDK context of a primary-button press. Called by
    /// `gtk/run.rs`'s `GestureClick::connect_pressed`, before the press is
    /// translated to a portable [`UiEvent`], so
    /// [`Backend::begin_window_drag`] can later request a native
    /// window-drag using the *originating* event's device/timestamp.
    /// Overwritten by the next press; harmless if never consumed.
    pub(crate) fn stash_window_press(
        &mut self,
        device: gdk::Device,
        button: i32,
        x: f64,
        y: f64,
        time: u32,
    ) {
        self.pending_window_press = Some((device, button, x, y, time));
    }

    /// Screen-space origin `(x, y)` of the press that armed the current
    /// window-drag request, if one is armed. Test-only: `gtk/run.rs`'s
    /// motion controller calls [`Self::try_commit_window_drag`] every move
    /// and lets [`WindowDragArm::commit_if_past_threshold`] do the threshold
    /// check.
    #[cfg(test)]
    pub(crate) fn armed_window_drag_origin(&self) -> Option<(f64, f64)> {
        self.armed_window_drag.origin()
    }

    /// Discard an armed-but-uncommitted window-drag request without
    /// starting a move. Called by `gtk/run.rs`'s `GestureClick::connect_released`
    /// handler: if the button goes up before the pointer ever moved past
    /// the drag threshold, the press was a plain click (or the first half
    /// of a double-click) and must not leave stale state around to be
    /// accidentally committed by an unrelated later hover-motion event
    pub(crate) fn discard_armed_window_drag(&mut self) {
        self.armed_window_drag.discard();
    }

    /// Threshold-gated commit of an armed window-drag request. Called by
    /// `gtk/run.rs`'s motion controller on every pointer move while a request
    /// is armed; `WindowDragArm` handles "still under threshold, stay armed"
    /// internally, so this is a plain no-op (returns `false`) on every call
    /// until the pointer actually crosses [`Self::window_drag_threshold_px`]
    /// from the arming press — see [`Self::armed_window_drag`] for why the
    /// commit is deferred at all instead of running synchronously from
    /// `Backend::begin_window_drag`.
    ///
    /// On a successful threshold-cross, calls `gdk4::Toplevel::begin_move`
    /// with the *originating* press's device/button/timestamp (GDK
    /// ignores synthesized values on some compositors) and returns `true`.
    /// Returns `false` (no-op) if no window is set, nothing is armed,
    /// or the armed request is still under threshold.
    pub(crate) fn try_commit_window_drag(&mut self, x: f64, y: f64) -> bool {
        let Some(window) = self.window.as_ref() else {
            self.armed_window_drag.discard();
            return false;
        };
        let threshold = self.window_drag_threshold_px();
        let Some((device, button, press_x, press_y, time)) = self
            .armed_window_drag
            .commit_if_past_threshold(x, y, threshold)
        else {
            return false;
        };
        // `ApplicationWindow` implements `Native` directly, so `.surface()`
        // is reachable without an upcast. `surface()` returns `None` when
        // the window isn't realized yet; when it is, only an actual toplevel
        // surface implements the `Toplevel` interface `begin_move` lives on.
        // Downcast can fail if the surface isn't a toplevel.
        match window
            .surface()
            .and_then(|s| s.downcast::<gdk::Toplevel>().ok())
        {
            Some(toplevel) => {
                toplevel.begin_move(&device, button, press_x, press_y, time);
                true
            }
            None => false,
        }
    }

    /// Pixel distance the pointer must travel from an armed press before
    /// [`Self::armed_window_drag`] is committed. Reads GTK's own
    /// `gtk-dnd-drag-threshold` setting (the same threshold `GestureDrag`
    /// uses natively) so the titlebar drag feels identical to any other
    /// GTK drag gesture; falls back to GTK's documented default (8px) when
    /// no window/display is available yet (e.g. in unit tests).
    pub(crate) fn window_drag_threshold_px(&self) -> f64 {
        const DEFAULT_THRESHOLD_PX: f64 = 8.0;
        match self.window.as_ref() {
            Some(w) => gtk4::Settings::for_display(&gtk4::prelude::WidgetExt::display(w))
                .gtk_dnd_drag_threshold() as f64,
            None => DEFAULT_THRESHOLD_PX,
        }
    }

    /// Update the cached UI font description string (Pango format,
    /// e.g. `"Cantarell 11"`). Call from the app's settings sync.
    ///
    /// Ergonomic concrete-type sibling of [`Backend::set_ui_font`]
    /// (`impl Into<String>` vs. `&str`) — kept so existing direct
    /// `GtkBackend` call sites (`gtk/run.rs`, tests) don't need a
    /// `.to_string()`. Callers holding only `&mut dyn Backend` use the
    /// trait method instead; both write the same field.
    pub fn set_ui_font(&mut self, ui_font: impl Into<String>) {
        self.ui_font = resolve_generic_families_gtk(&ui_font.into());
    }

    /// Current editor font as a Pango description string (`"<family>
    /// <size>"`). Defaults to `"Monospace 11"` until
    /// [`Backend::set_editor_font`] overrides it. `gtk/run.rs`'s draw
    /// closure reads this every frame to build the shared editor
    /// `pango::Layout`.
    ///
    /// Public since consumers may paint editor content themselves (bespoke
    /// Cairo, not [`Backend::draw_editor`]) and need this to build their own
    /// paint-time layout from the exact same family/size [`Self::editor_pango_layout`]
    /// resolves for click-time measurement.
    pub fn editor_font_pango_string(&self) -> String {
        format!("{} {}", self.editor_font_family, self.editor_font_size_pt)
    }

    /// Build a `pango::Layout` carrying the *live* editor font — the
    /// same `editor_font_family` / `editor_font_size_pt` [`Self::set_editor_font`]
    /// stores and `gtk/run.rs`'s per-frame draw closure reads via
    /// [`Self::editor_font_pango_string`] — from the stable widget Pango
    /// context ([`Self::set_pango_context`]).
    ///
    /// This is the entry point a GTK consumer needs to map a click
    /// x-coordinate to an editor column (via [`crate::gtk::editor_col_at_x`])
    /// without constructing a second, private `GtkBackend` purely to
    /// mimic the real one's font — pass the *same* `GtkBackend` the
    /// consumer already owns (or set the editor font on a bare one built
    /// just for this) and this always reflects the current
    /// [`Backend::set_editor_font`] call, at any size. It does not
    /// require an in-progress frame (unlike [`Self::create_stable_pango_layout`]
    /// composed with the raw `pango_ctx`, which carries whatever font the
    /// context was initialized with — historically the UI chrome font,
    /// not the editor font) and does not require having painted an
    /// editor this frame (unlike the `Backend::editor_col_at_x` trait
    /// method's `last_editor_pango_layout` cache, which is `None` until
    /// the first `draw_editor` call).
    ///
    /// Single-line, no-wrap (`set_width(-1)`), matching the recipe
    /// `gtk/run.rs::render_frame` uses to build the frame's shared editor
    /// layout — [`crate::gtk::editor_col_at_x`] resolves one line at a
    /// time and expects that shape. Returns `None` if no Pango context
    /// has been stored (mirrors [`Self::create_stable_pango_layout`]).
    pub fn editor_pango_layout(&self) -> Option<pango::Layout> {
        let ctx = self.pango_ctx.as_ref()?;
        let layout = pango::Layout::new(ctx);
        let font_desc = pango::FontDescription::from_string(&self.editor_font_pango_string());
        layout.set_font_description(Some(&font_desc));
        layout.set_width(-1);
        Some(layout)
    }

    /// Shared handle to the modal stack. The App and widget callbacks
    /// clone this to push/pop modals and to feed
    /// `dispatch::dispatch_mouse_down`. The trait's `modal_stack_handle`
    /// hands back the same handle.
    pub fn modal_stack_handle(&self) -> Rc<std::cell::RefCell<ModalStack>> {
        self.modal_stack.clone()
    }

    /// True if any modal is open (palette, dialog, context menu, …).
    /// Use this to gate hover triggers, focus-stealing animations, and
    /// other behaviours that should pause while a modal is up.
    ///
    /// Today only the picker pushes onto the stack; as additional modal
    /// types are migrated, this method will correctly cover them.
    #[allow(dead_code)]
    pub fn is_modal_open(&self) -> bool {
        !self.modal_stack.borrow().is_empty()
    }

    /// Shared handle to the drag state. Mouse-down on a scrollbar
    /// arms it via `borrow_mut().begin(...)`; mouse-drag-update reads
    /// it via `borrow()` to feed `dispatch::dispatch_mouse_drag`;
    /// mouse-up clears it.
    pub fn drag_state_handle(&self) -> Rc<std::cell::RefCell<DragState>> {
        self.drag_state.clone()
    }

    /// Shared handle to the event-queue adapter. Producer-side
    /// signal-callback closures (mouse/key/scroll on the editor
    /// DrawingArea, as of Phase B.5b Stage 1) clone this and push
    /// translated `UiEvent`s into the queue. Drained by
    /// `wait_events` / `poll_events`.
    pub fn events_handle(&self) -> Rc<std::cell::RefCell<VecDeque<UiEvent>>> {
        self.events.clone()
    }

    /// Push a single event onto the queue. Convenience for callbacks
    /// that have a `&GtkBackend` (or `&Rc<RefCell<GtkBackend>>`)
    /// reference and don't want to clone the events handle. Stage 5
    /// uses `events_handle()` directly inside captured closures
    /// because cloning the handle is cheaper than reaching the
    /// backend through `Rc<RefCell<>>`.
    #[allow(dead_code)]
    pub fn push_event(&self, ev: UiEvent) {
        self.events.borrow_mut().push_back(ev);
    }

    /// Update the cached theme. Call once per frame from the App's
    /// draw callback, before any trait `draw_*` invocations.
    #[allow(dead_code)]
    pub fn set_current_theme(&mut self, theme: crate::Theme) {
        self.current_theme = theme;
    }

    /// Read-only accessor for the cached theme. Used by the runner
    /// to paint a full-DA background before each frame.
    pub fn current_theme(&self) -> &crate::Theme {
        &self.current_theme
    }

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

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

    /// Push the app's chosen theme into GTK's own
    /// `gtk-application-prefer-dark-theme` setting, so native GTK chrome
    /// that this crate doesn't rasterise itself (the file dialog, as of
    /// this writing) follows the app's colours instead of the desktop default.
    /// This is the *push* direction; [`crate::gtk::services`]'s `system_theme`
    /// is the complementary *read* direction (OS → app), and landing one does
    /// not cover the other.
    ///
    /// Uses the parented window's own display when one is attached,
    /// falling back to [`gtk4::gdk::Display::default`] otherwise — the
    /// same fallback chain [`Self::window_drag_threshold_px`] and
    /// `GtkPlatformServices::beep`/`system_theme` use. No-op when neither
    /// exists (headless CI, no display connection): there is no
    /// `gtk4::Settings` to push into, and `set_theme`'s cached
    /// `current_theme` (which every rasteriser reads) is already updated
    /// by [`Self::set_current_theme`] regardless.
    fn push_native_theme_preference(&self, theme: crate::Theme) {
        // `gtk4::Settings::default()`/`for_display` both assert
        // `gtk4::init()` already ran (they panic, not `None`, when it
        // hasn't — see `assert_initialized_main_thread!` in gtk4-rs).
        // `GtkBackend` itself is constructible (and `Backend::set_theme`
        // callable) without a live GTK runtime — every paint/click unit
        // test in this module does exactly that — so this guard is load-
        // bearing, not defensive dead code.
        if !gtk4::is_initialized_main_thread() {
            return;
        }
        let settings = match self.window.as_ref() {
            Some(w) => Some(gtk4::Settings::for_display(
                &gtk4::prelude::WidgetExt::display(w),
            )),
            None => gtk4::Settings::default(),
        };
        if let Some(settings) = settings {
            settings.set_gtk_application_prefer_dark_theme(theme_prefers_dark(theme));
        }
    }

    /// Return the `WidgetId` of the `ActivityBar` that declared
    /// `is_keyboard_focused = true` during the most recent render pass,
    /// or `None` if no bar is focused. Called by the GTK runner's key
    /// handler to decide whether to redirect a `KeyPressed` event into
    /// `UiEvent::ActivityBar(id, ActivityBarEvent::KeyPressed { … })`.
    pub(crate) fn focused_activity_bar_id(&self) -> Option<&WidgetId> {
        self.focused_activity_bar.as_ref()
    }

    /// Update the cached Pango line height (in DIPs). Call once per
    /// frame from the App's draw callback (after measuring font
    /// metrics), before any trait `draw_*` invocations.
    #[allow(dead_code)]
    pub fn set_current_line_height(&mut self, line_height: f64) {
        self.current_line_height = line_height;
    }

    /// Update the cached Pango approximate-char-width (in DIPs).
    /// Call once per frame alongside [`Self::set_current_line_height`].
    /// Required by primitives that map cells to pixels (terminal).
    #[allow(dead_code)]
    pub fn set_current_char_width(&mut self, char_width: f64) {
        self.current_char_width = char_width;
    }

    /// Re-measure and cache `ui_font`'s real Pango advance into
    /// `current_chrome_char_width`, backing [`Backend::list_char_width`]
    /// — the chrome twin of [`Self::set_current_char_width`].
    ///
    /// Takes a live `layout` (the same shared per-frame layout every
    /// `draw_*` method borrows via `current_frame_refs`) because Pango
    /// text measurement needs a `pango::Context`-backed layout to read
    /// real hinted advances from, not just a font description. Saves and
    /// restores `layout`'s font description around the measurement, the
    /// same save/swap/restore shape [`Backend::draw_list`]'s own
    /// [`crate::gtk::GtkBackend`] impl uses to paint in `ui_font` without
    /// leaving it stuck on the shared layout afterward — so calling this
    /// mid-frame never disturbs whatever the caller had `layout` set to.
    ///
    /// Called once per frame by `gtk::run::render_frame`, right alongside
    /// [`Self::set_current_char_width`], so `list_char_width()` can never
    /// go stale after a runtime [`Backend::set_ui_font`] call the way a
    /// value cached only at `set_ui_font` time would (GTK's `ui_font` is
    /// a plain string, not a live `pango::FontDescription` with metrics
    /// attached, so there is no cheaper place to resolve this from).
    pub(crate) fn refresh_chrome_char_width(&mut self, layout: &pango::Layout) {
        let saved = layout.font_description();
        let chrome_desc = crate::gtk::chrome_font_description(&self.ui_font);
        layout.set_font_description(Some(&chrome_desc));
        self.current_chrome_char_width = measure_char_width_px(layout);
        layout.set_font_description(saved.as_ref());
    }

    /// Store the widget's Pango context for text measurement outside
    /// the draw callback. Call once during init (e.g. from the runner
    /// after `DrawingArea::realize`). The context carries the font
    /// configuration and is valid for the widget's lifetime.
    pub fn set_pango_context(&mut self, ctx: pango::Context) {
        self.pango_ctx = Some(ctx);
    }

    /// Create a `pango::Layout` from the stored Pango context (set via
    /// [`Self::set_pango_context`]). The layout inherits the stable font
    /// options from init, avoiding per-frame font-hinting variance that
    /// occurs when creating a context from a transient Cairo surface.
    /// Returns `None` if no Pango context has been stored.
    pub fn create_stable_pango_layout(&self) -> Option<pango::Layout> {
        self.pango_ctx.as_ref().map(pango::Layout::new)
    }

    /// A fresh layout on the stored Pango context carrying the chrome
    /// font (`chrome_font_description(&self.ui_font)`), for the no-paint
    /// `*_layout` twins of chrome rasterisers that paint in `ui_font`.
    /// Measuring with the context's own font instead lets the layout's
    /// column/label widths diverge from what the painter resolves on
    /// platforms where the two descriptions shape differently.
    fn chrome_measure_layout(&self) -> Option<pango::Layout> {
        let pl = self.pango_ctx.as_ref().map(pango::Layout::new)?;
        pl.set_font_description(Some(&crate::gtk::chrome_font_description(&self.ui_font)));
        Some(pl)
    }

    /// Measure a plain string width in pixels using Pango if
    /// available, falling back to `chars().count() * char_w`.
    fn pango_str_width(
        &self,
        pango_layout: &Option<pango::Layout>,
        text: &str,
        char_w: f32,
    ) -> f32 {
        if let Some(pl) = pango_layout {
            pl.set_text(text);
            let (w, _) = pl.pixel_size();
            w as f32
        } else {
            (text.chars().count() as f32 * char_w).ceil() + 2.0
        }
    }

    /// Enter the frame-scope: stash the cairo context + pango layout
    /// pointers, run `f`, then clear them. **Must** be called from
    /// inside a `set_draw_func(...)` closure where `cr` is alive.
    /// The pango layout is freshly created from `cr` via
    /// `pangocairo::create_context` so font-metrics setup is shared
    /// across every `draw_*` in this frame.
    ///
    /// Type-erased through `*const ()` because both `Context` and
    /// `Layout` are reference-counted GObjects whose Rust borrow
    /// lifetimes we don't want to thread onto the struct. Safety
    /// relies on:
    /// 1. The pointers are set immediately before `f` runs and
    ///    cleared after, including on panic.
    /// 2. `f` cannot move the pointers out — only read via the safe
    ///    accessors which return references scoped to the call.
    /// 3. Calls don't nest meaningfully (a nested `enter_frame_scope`
    ///    would alias the same `&Context`, which Rust forbids at
    ///    the caller side anyway).
    #[allow(dead_code)]
    pub fn enter_frame_scope<R>(
        &mut self,
        cr: &Context,
        layout: &pango::Layout,
        f: impl FnOnce(&mut Self) -> R,
    ) -> R {
        let cr_ptr = cr as *const Context as *const ();
        let layout_ptr = layout as *const pango::Layout as *const ();
        let prev_cr = self.current_cr_ptr.replace(cr_ptr);
        let prev_layout = self.current_layout_ptr.replace(layout_ptr);
        // Paint-time text recording is scoped to exactly
        // this paint pass: install the sink before the rasterisers run,
        // drain it after. See `painted_text`'s docs for why the drain
        // happens here (after the frame) rather than per `draw_*` call.
        let prev_sink = if self.painted_text_recording {
            Some(crate::testing::install_text_run_sink())
        } else {
            None
        };
        let result = f(self);
        if let Some(prev_sink) = prev_sink {
            for run in crate::testing::take_text_run_sink(prev_sink) {
                self.record_painted_text(&run.text, run.bounds);
            }
        }
        self.current_cr_ptr.set(prev_cr);
        self.current_layout_ptr.set(prev_layout);
        result
    }

    /// Enable/disable the per-glyph-run painted-text recording that backs
    /// [`super::testing::GtkDriver::find`]. Off by default
    /// — see [`Self::painted_text`].
    pub(crate) fn set_painted_text_recording(&mut self, enabled: bool) {
        self.painted_text_recording = enabled;
    }

    /// Read-only view of this frame's painted-text map, for in-crate
    /// tests that hold a `GtkBackend` directly rather than a
    /// [`super::testing::GtkDriver`].
    #[cfg(test)]
    pub(crate) fn painted_text_for_test(&self) -> &[PaintedText] {
        &self.painted_text
    }

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

    /// [`crate::TabBarHits`] derived from the layout `bar` was most
    /// recently *painted* with, in the same target-surface coordinates
    /// [`Backend::tab_bar_layout`] reports — or `None` when this frame
    /// painted no such bar, painted it at a different rect, or painted
    /// fewer tabs than `bar` now carries (a stale entry must never index
    /// past `bar.tabs`).
    ///
    /// Used by the no-paint `tab_bar_layout` twin when there is no Pango
    /// handle to measure with, so click routing follows painted pixels
    /// instead of a char-cell estimate that drifts with the host's UI
    /// font. Same "cache at paint, hit-test at click" pattern the rest of
    /// the backend uses.
    #[allow(deprecated)] // `TabBarHits` is `#[deprecated]`
    fn cached_tab_bar_hits(&self, rect: QRect, bar: &TabBar) -> Option<crate::TabBarHits> {
        let (cached_rect, layout) = self.tab_bar_layouts.get(&bar.id)?;
        if *cached_rect != rect {
            return None;
        }
        if layout
            .visible_tabs
            .iter()
            .any(|vt| vt.tab_idx >= bar.tabs.len())
        {
            return None;
        }
        let mut hits = crate::backend::tab_bar_hits_from_layout(layout, bar);
        // `TabBarLayout` is bar-relative; `TabBarHits` are target-surface
        // coordinates, exactly as the measured path below.
        crate::backend::shift_tab_bar_hits(&mut hits, rect.x as f64);
        Some(hits)
    }

    /// [`TabBarLayout`] most recently *painted* for `bar` at `rect`, or
    /// `None` on the same staleness conditions as [`Self::cached_tab_bar_hits`]
    /// — see that method's doc for the "no Pango handle" fallback this backs.
    /// `TabBarLayout` is already bar-relative, so unlike `cached_tab_bar_hits`
    /// there is no `TabBarHits` conversion or `rect.x` shift to apply.
    fn cached_tab_bar_layout_matching(&self, rect: QRect, bar: &TabBar) -> Option<TabBarLayout> {
        let (cached_rect, layout) = self.tab_bar_layouts.get(&bar.id)?;
        if *cached_rect != rect {
            return None;
        }
        if layout
            .visible_tabs
            .iter()
            .any(|vt| vt.tab_idx >= bar.tabs.len())
        {
            return None;
        }
        Some(layout.clone())
    }

    /// Get the current cairo context + pango layout inside the
    /// frame-scope, or `None` outside. Trait `draw_*` methods call
    /// this and bail (panic in dev) if the scope isn't active.
    fn current_frame_refs(&self) -> Option<(&Context, &pango::Layout)> {
        let cr_ptr = self.current_cr_ptr.get();
        let layout_ptr = self.current_layout_ptr.get();
        if cr_ptr.is_null() || layout_ptr.is_null() {
            return None;
        }
        // SAFETY: `enter_frame_scope` set both pointers from real
        // borrows of `&Context` / `&pango::Layout` and won't return
        // until the scope ends. Outside the scope both pointers are
        // null and we returned above.
        Some(unsafe {
            (
                &*(cr_ptr as *const Context),
                &*(layout_ptr as *const pango::Layout),
            )
        })
    }

    // ── Text selection ─────────────────────────────────────────────────────
    //
    // The region registry + active-selection state machine, plus the
    // accelerator registry alongside it, live in
    // [`crate::backend_core::BackendCore`] — every method below
    // is a thin delegation, kept as inherent methods (rather than
    // inlining `self.core.text_selection.foo()` at every call site) so
    // `gtk/run.rs` and this file's own tests don't need to know the field
    // exists. `apply_selection_highlight`/`extract_selection_text` stay
    // GTK-specific bodies below (Cairo painting / lines-based extraction,
    // sharing [`crate::backend_core::BackendCore::selection_highlight_rects`]/
    // [`crate::backend_core::BackendCore::extract_selection_text_pixel`]
    // with Win-GUI and macOS).

    /// Every `TextRegion` registered so far this frame. Test-only:
    /// direct text-region access is no longer needed outside this file's tests,
    /// as [`Self::text_selection_state_mut`] provides the needed mutable access.
    #[cfg(test)]
    pub(crate) fn text_regions(&self) -> &[TextRegion] {
        &self.core.text_selection.text_regions
    }

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

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

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

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

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

    /// End any in-progress `TextSelection` drag without clearing the
    /// displayed selection. Mirrors [`Self::clear_text_selection`] but
    /// preserves the highlight — called by the `Backend` trait impl of
    /// [`crate::Backend::cancel_text_selection_drag`] so apps hosting an
    /// embedded terminal can abort a speculative drag (started by
    /// `apply_dispatch` before the app forwards the click to a PTY) while
    /// keeping any previously finalised selection on screen.
    pub(crate) fn cancel_text_selection_drag_impl(&mut self) {
        let mut drag = self.drag_state.borrow_mut();
        self.core.cancel_text_selection_drag(&mut drag);
    }

    /// Record one painted label into [`Self::painted_text`] — the
    /// `(text, bounds)` map [`super::testing::GtkDriver::find`] scans.
    ///
    /// `bounds` is in backend (pixel) coordinates, matching what
    /// [`super::testing::GtkDriver::click`] expects.
    ///
    /// Two kinds of caller:
    /// 1. Trait methods that already compute a label's rect for
    ///    hit-testing ([`Backend::draw_status_bar`],
    ///    [`Backend::draw_data_table`], [`Backend::draw_pipeline_view`]).
    ///    These record the *logical* label — whole segment, whole cell —
    ///    at the rect the primitive's own `hit_test` uses, which is what
    ///    a `find`-driven click wants.
    /// 2. [`Self::enter_frame_scope`], draining the per-glyph-run sink
    ///    [`super::painted_text`] fills for *every* text-bearing
    ///    rasteriser. This is the coverage path; the
    ///    logical records above stay ahead of it in the map.
    ///
    /// Skips blank `text` so alignment pads and placeholder segments
    /// don't pollute `find` matches.
    pub(crate) fn record_painted_text(&mut self, text: &str, bounds: QRect) {
        if text.trim().is_empty() {
            return;
        }
        self.painted_text.push(PaintedText {
            text: text.to_string(),
            bounds,
        });
    }

    /// Paint the active text selection highlight onto `cr`. Must be called
    /// after `app.render` (so the highlight sits on top of the rendered
    /// content).
    ///
    /// The row/column → pixel-rect resolution is
    /// [`crate::backend_core::BackendCore::selection_highlight_rects`] —
    /// shared with `MacBackend`/`WinBackend`'s twins; only the
    /// actual `cr.rectangle`/`cr.fill()` Cairo calls below are GTK-specific
    /// real toolkit code. No-op when there is no active selection or the
    /// region id is not registered this frame.
    pub(crate) fn apply_selection_highlight(&self, cr: &Context) {
        let line_h = self.current_line_height as f32;
        let char_w = self.current_char_width as f32;
        let Some(rects) = self.core.selection_highlight_rects(line_h, char_w) else {
            return;
        };

        let color = self.current_theme.text_selection_highlight();
        cr.save().ok();
        crate::gtk::set_source_rgba(cr, color);
        for rect in rects {
            cr.rectangle(
                rect.x as f64,
                rect.y as f64,
                rect.width as f64,
                rect.height as f64,
            );
        }
        cr.fill().ok();
        cr.restore().ok();
    }

    /// Extract the selected text from the `TextRegion`'s stored lines using
    /// the current pixel anchor/focus. Returns an empty string when there is
    /// no active selection, the region is not registered this frame, or the
    /// region has no `lines` content. See
    /// [`crate::backend_core::BackendCore::extract_selection_text_pixel`] —
    /// shared with `MacBackend`/`WinBackend`'s identically-shaped twins.
    pub(crate) fn extract_selection_text(&self) -> String {
        self.core.extract_selection_text_pixel(
            self.current_line_height as f32,
            self.current_char_width as f32,
        )
    }

    /// Set the active selection to cover the entire visible content of the
    /// most-recently focused `TextRegion`. Returns `true` when a region was
    /// found and the selection was set; `false` when no region can be
    /// resolved (zero registered regions, or multiple with no prior
    /// interaction).
    ///
    /// Target resolution order:
    /// 1. [`Self::last_text_region_id`] if the region is still registered
    ///    this frame.
    /// 2. The sole registered region (if exactly one exists).
    /// 3. Returns `false` — caller should fall through to the app.
    ///
    /// Anchor is at the region's top-left pixel; focus is just past the
    /// bottom-right pixel so `apply_selection_highlight` covers every row.
    ///
    /// # Viewport-only limitation
    ///
    /// `TextRegion.bounds` is the painted viewport. For scrolled panels
    /// (e.g. long issue bodies) only the on-screen rows are selected.
    /// Full-document select-all requires `TextRegion` to carry
    /// total-content rows; a follow-up issue tracks this.
    // TODO: full-document select-all requires TextRegion to carry
    // total-content rows; for now this selects only the visible
    // viewport (bounds).
    pub(crate) fn select_all_text_region(&mut self) -> bool {
        self.core.select_all_text_region()
    }

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

    /// Fold a `MouseDown` into `DoubleClick` if it lands within
    /// [`GTK_DOUBLE_CLICK_RADIUS`]/400ms of the previous click at the same
    /// button. Every other variant passes through unchanged. Called from
    /// [`crate::runtime::preprocess_event`] (via GTK's `PreprocessBackend`
    /// impl) — mirrors `MacBackend::fold_double_click`/
    /// `WinBackend::fold_double_click`.
    pub(crate) fn fold_double_click(&mut self, ev: UiEvent) -> UiEvent {
        if !self.double_click_folding {
            return ev;
        }
        let mut events = [ev];
        self.double_click.process(&mut events);
        let [ev] = events;
        ev
    }

    /// Toggle whether [`Self::fold_double_click`] folds a `MouseDown` into
    /// `DoubleClick`. Driver-facing knob for
    /// [`super::testing::GtkDriver::set_double_click_folding`]
    /// — mirrors `TuiBackend::set_double_click_folding`.
    pub(crate) fn set_double_click_folding(&mut self, enabled: bool) {
        self.double_click_folding = enabled;
    }

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

    /// Current blink phase for `MultiSectionView` aux-row text inputs —
    /// threaded into [`crate::primitives::multi_section_view::native_surface_paint::paint_aux`]
    /// by [`Backend::draw_multi_section_view`]. See
    /// [`Self::caret_blink`]'s field doc for the wiring.
    pub(crate) fn caret_visible(&self) -> bool {
        self.caret_blink.visible()
    }

    /// Advance the blink clock. Called once per
    /// [`crate::caret_blink::CaretBlinkState::period`] by the
    /// `glib::timeout_add_local` `super::run::setup_caret_blink`
    /// installs; returns `true` when the phase flipped, so the caller
    /// knows to queue a redraw.
    pub(crate) fn tick_caret_blink(&mut self, now: std::time::Instant) -> bool {
        self.caret_blink.tick(now)
    }

    /// The interval `setup_caret_blink` schedules its recurring
    /// `glib::timeout_add_local` at — see [`crate::caret_blink::CaretBlinkState::period`].
    pub(crate) fn caret_blink_period(&self) -> std::time::Duration {
        self.caret_blink.period()
    }

    /// Hold the caret solid for a typing pause, matching AppKit's
    /// "caret stays visible while typing" convention. Called by the
    /// shared `dispatch_event` funnel on `UiEvent::KeyPressed`/
    /// `UiEvent::CharTyped` — mirrors `MacBackend`'s key handler in
    /// `macos::run::dispatch_event`.
    pub(crate) fn note_caret_activity(&mut self, now: std::time::Instant) {
        self.caret_blink.on_activity(now);
    }

    /// Test-only hook to pin the caret phase for deterministic paint
    /// snapshots — mirrors `MacBackend::set_caret_visible`. Built on
    /// [`crate::caret_blink::CaretBlinkState`]'s public `tick` rather than
    /// a new setter on that shared type: a far-future `now` always clears
    /// any pending typing-pause, so `tick` unconditionally flips
    /// `visible` when it doesn't already match `visible`.
    #[cfg(test)]
    pub(crate) fn set_caret_visible(&mut self, visible: bool) {
        if self.caret_blink.visible() != visible {
            let far_future = std::time::Instant::now() + std::time::Duration::from_secs(3600);
            self.caret_blink.tick(far_future);
        }
    }

    // ── Accelerators ────────────────────────────────────────────────────────
    //
    // The registry itself lives in [`crate::backend_core::BackendCore`]
    // — see that type's doc. Both methods below are thin
    // delegations, kept as inherent methods (rather than requiring every
    // call site to spell `self.core.foo()`) since the GTK key callback
    // (synchronous dispatch) and this file's own tests call
    // [`Self::match_keypress`] directly.

    /// Apply registered accelerators to a slice of UiEvents. Replaces
    /// matching `UiEvent::KeyPressed` events with
    /// `UiEvent::Accelerator(id, mods)`.
    #[allow(dead_code)]
    pub fn apply_accelerators(&self, events: &mut [UiEvent]) {
        self.core.apply_accelerators(events);
    }

    /// Look up a registered Global accelerator for a `(key, modifiers)`
    /// pair. Returns the matching `AcceleratorId` on first hit, or
    /// `None`. Used both by `apply_accelerators` (rewriting queue
    /// events) and by the GTK key callback (synchronous dispatch in
    /// B.5b Stage 2).
    pub fn match_keypress(
        &self,
        key: &crate::Key,
        modifiers: crate::Modifiers,
    ) -> Option<AcceleratorId> {
        self.core.match_keypress(key, modifiers)
    }

    /// Shared body of [`Backend::draw_status_bar_interactive`] /
    /// [`Backend::draw_status_bar_interactive_scaled`]. `font_scale` multiplies
    /// the chrome font's point size for this paint only — `1.0` is the unscaled case.
    fn status_bar_paint_scaled(
        &mut self,
        rect: QRect,
        bar: &StatusBar,
        interaction: &crate::interaction::InteractionState,
        font_scale: f32,
    ) -> crate::StatusBarLayout {
        let (hovered_id, pressed_id) = (interaction.hovered(), interaction.pressed());
        // Status bar segments are chrome, painted in `ui_font` —
        // `GtkBackend`'s own `PaintSurface` impl now resolves that font
        // straight from `self.ui_font` on every text verb (see the
        // cross-reference comment just above `impl PaintSurface for
        // GtkBackend` below), so there is no shared-layout font to swap
        // onto for the plain `font_scale == 1.0` case any more. A real
        // `font_scale` still needs a scoped override: save `self.ui_font`,
        // replace it with a size-scaled copy for the paint below, then
        // restore it so later draws in this frame aren't left painting
        // chrome text at the scaled size.
        let saved_ui_font = if font_scale != 1.0 {
            let mut scaled_desc = pango::FontDescription::from_string(&self.ui_font);
            // Pango sizes are in `PANGO_SCALE`-ths of a point — scale the
            // raw integer so a caller-friendly `f32` multiplier (e.g.
            // `0.85`) survives the round-trip without losing precision to
            // an intermediate point-size conversion. `.max(1)` guards
            // against a degenerate `font_scale` (e.g. `0.0`) collapsing
            // the description to Pango's own "unset" sentinel (`0`),
            // which would fall back to some other ambient size instead of
            // painting (nearly) nothing, the honest behaviour a caller
            // asking for size `~0` should get.
            let scaled = ((scaled_desc.size() as f32) * font_scale).round() as i32;
            scaled_desc.set_size(scaled.max(1));
            Some(std::mem::replace(
                &mut self.ui_font,
                scaled_desc.to_str().to_string(),
            ))
        } else {
            None
        };
        let theme = self.current_theme;
        // Use the rect's height for the background fill, matching other backends.
        // This ensures the fill exactly matches the provided rect.
        let line_height = rect.height;
        let bar_layout = crate::primitives::status_bar::native_surface_paint::paint(
            bar,
            self,
            &theme,
            rect.x,
            rect.y,
            rect.width,
            line_height,
            hovered_id,
            pressed_id,
        );
        if let Some(saved) = saved_ui_font {
            self.ui_font = saved;
        }
        // Record each visible segment's label into the painted-text map
        // that GtkDriver::find scans — resolve the text from `bar` via the
        // segment's side + index, since `VisibleStatusSegment` carries the
        // resolved bounds but not the label itself.
        //
        // `seg.bounds` (from `StatusBar::layout`) is bar-local:
        // `x` relative to this bar's own left edge, `y` always `0` relative to
        // its own top. Translate by `rect`'s origin to get absolute surface
        // coordinates, matching `Self::draw_data_table`'s convention.
        for seg in &bar_layout.visible_segments {
            let text = match seg.side {
                crate::primitives::status_bar::StatusSegmentSide::Left => {
                    bar.left_segments.get(seg.segment_idx).map(|s| &s.text)
                }
                crate::primitives::status_bar::StatusSegmentSide::Right => {
                    bar.right_segments.get(seg.segment_idx).map(|s| &s.text)
                }
            };
            if let Some(text) = text {
                let bounds = QRect::new(
                    rect.x + seg.bounds.x,
                    rect.y + seg.bounds.y,
                    seg.bounds.width,
                    seg.bounds.height,
                );
                self.record_painted_text(text, bounds);
            }
        }
        bar_layout
    }
}

/// Measure the true (fractional) monospace advance width for `layout`'s
/// current font, in device pixels — the single place this repo derives
/// `Backend::char_width()`'s seed value from Pango, so all paths
/// report consistent values for the same font.
///
/// `pango::Layout::pixel_size()` rounds to whole pixels. That's fine for
/// a single line's height, but wrong for `char_width()`: every consumer
/// divides a pixel width by it to recover a column count
/// (`available_width / char_width()`), and a monospace advance is not
/// always integral (8.4px, 9.6px, …). Rounding one glyph before that
/// division would lose a column's width across a realistic pane.
///
/// Mutates `layout`'s text and width; every current call site only holds
/// the layout to derive per-frame metrics before painting overwrites its
/// text anyway, so this is safe to call at the top of a draw closure.
/// `set_width(-1)` is applied defensively here (not just by callers) so a
/// future call site that reuses a width-constrained layout can't silently
/// get a wrapped (too-small) measurement back.
pub(crate) fn measure_char_width_px(layout: &pango::Layout) -> f64 {
    const RUN_LEN: usize = 100;
    layout.set_width(-1);
    layout.set_text(&"0".repeat(RUN_LEN));
    layout.size().0 as f64 / pango::SCALE as f64 / RUN_LEN as f64
}

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

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

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

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

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

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

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

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

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

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

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

/// Map a portable [`ResizeEdge`] to GDK's native `SurfaceEdge`, the
/// argument `gdk4::Toplevel::begin_resize` requires. 1:1 mapping —
/// `ResizeEdge` was deliberately named to mirror `SurfaceEdge`'s variants.
fn resize_edge_to_surface_edge(edge: ResizeEdge) -> gdk::SurfaceEdge {
    match edge {
        ResizeEdge::North => gdk::SurfaceEdge::North,
        ResizeEdge::South => gdk::SurfaceEdge::South,
        ResizeEdge::East => gdk::SurfaceEdge::East,
        ResizeEdge::West => gdk::SurfaceEdge::West,
        ResizeEdge::NorthEast => gdk::SurfaceEdge::NorthEast,
        ResizeEdge::NorthWest => gdk::SurfaceEdge::NorthWest,
        ResizeEdge::SouthEast => gdk::SurfaceEdge::SouthEast,
        ResizeEdge::SouthWest => gdk::SurfaceEdge::SouthWest,
    }
}

/// Map a [`PointerShape`] to the GTK/CSS cursor name `WidgetExt::
/// set_cursor_from_name` expects. Names are the standard CSS Basic
/// UI cursor keywords GTK's cursor theme lookup understands.
fn pointer_shape_cursor_name(shape: PointerShape) -> &'static str {
    match shape {
        PointerShape::Default => "default",
        PointerShape::Resize(ResizeEdge::North) => "n-resize",
        PointerShape::Resize(ResizeEdge::South) => "s-resize",
        PointerShape::Resize(ResizeEdge::East) => "e-resize",
        PointerShape::Resize(ResizeEdge::West) => "w-resize",
        PointerShape::Resize(ResizeEdge::NorthEast) => "ne-resize",
        PointerShape::Resize(ResizeEdge::NorthWest) => "nw-resize",
        PointerShape::Resize(ResizeEdge::SouthEast) => "se-resize",
        PointerShape::Resize(ResizeEdge::SouthWest) => "sw-resize",
    }
}

/// Whether `theme` reads as a dark theme, for
/// [`GtkBackend::push_native_theme_preference`]. `crate::Theme`
/// has no `is_light`/`is_dark` of its own (see that struct's doc on why
/// new fields are avoided), so this derives it from `background`'s
/// perceptual luminance — the same ITU-R BT.601 luma formula and 50%
/// threshold `win::services::system_theme_from_ui_colors` uses for the
/// read direction, so both backends agree on where the light/dark line
/// falls for the same colour.
fn theme_prefers_dark(theme: crate::Theme) -> bool {
    let bg = theme.background;
    let luma = (bg.r as u32 * 299 + bg.g as u32 * 587 + bg.b as u32 * 114) / 1000;
    luma < 128
}

/// Rewrite any `system-ui` generic family token in `desc` (a bare family
/// name, or a Pango-style `"family[,family...] [size]"` description —
/// [`Backend::set_editor_font`]/[`Backend::set_ui_font`]'s shapes) to
/// `"Sans"`, leaving everything else untouched.
///
/// GTK is nearly a no-op backend for generic family resolution: Pango
/// resolves `monospace`/`sans-serif` (fontconfig's own generic alias
/// spellings) and Pango's convenience aliases `Monospace`/`Sans` for the
/// same two requests correctly already, with no translation needed here
/// — that is what the issue's mapping table means by "fontconfig aliases
/// (already generic)". `system-ui` is the one CSS token fontconfig has
/// no alias for, so it maps onto `"Sans"`, the concrete family
/// fontconfig's `sans-serif` alias already resolves to (Linux desktop
/// environments have no second, more-chrome-specific default the way
/// CSS's `system-ui`/`sans-serif` distinction implies).
///
/// Trailing-size detection mirrors `macos`/`win`'s `parse_ui_font_desc`
/// (a whitespace-separated numeric last token), and the family portion
/// is split on commas so a `system-ui` entry anywhere in a fallback list
/// — not just a bare, single-family request — gets rewritten.
fn resolve_generic_families_gtk(desc: &str) -> String {
    let trimmed = desc.trim();
    let (family_part, rest) = match trimmed.rfind(' ') {
        Some(idx) if trimmed[idx + 1..].trim().parse::<f64>().is_ok() => trimmed.split_at(idx),
        _ => (trimmed, ""),
    };
    let resolved: Vec<String> = family_part
        .split(',')
        .map(|f| {
            let f = f.trim();
            match GenericFamily::parse(f) {
                Some(GenericFamily::SystemUi) => "Sans".to_string(),
                _ => f.to_string(),
            }
        })
        .collect();
    format!("{}{}", resolved.join(","), rest)
}

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

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

    fn begin_frame(&mut self, viewport: Viewport) {
        self.viewport = viewport;
        // Bump once per frame so `TermPaintCache::painted_frame`
        // can detect a terminal that went unpainted for a frame (see its
        // docs) — must happen before any `draw_terminal` call this frame.
        self.frame_counter = self.frame_counter.wrapping_add(1);
        // Clear per-frame text regions so stale registrations from the
        // previous frame don't linger. Mirrors TuiBackend::begin_frame.
        self.core.begin_frame();
        // Clear per-frame widget zones for the same reason. Same
        // lifecycle as text_regions.
        self.zones.clear();
        // Clear last frame's painted-text map — see `painted_text`'s docs.
        self.painted_text.clear();
        // Clear the focused activity bar — re-set by draw_activity_bar
        // during the render pass if still focused. Same lifecycle as
        // text_regions.
        self.focused_activity_bar = None;
        // Clear per-frame tab-bar layout cache for the same reason as
        // `zones` — a bar that stops painting must stop resolving
        // `tab_center`/`tab_close_center` too.
        self.tab_bar_layouts.clear();
        // Clear last frame's modal paint marks so this frame has
        // to earn them again (via draw_dialog/draw_palette/draw_context_menu).
        self.modal_stack.borrow_mut().reset_frame_paint();
    }

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

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

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

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

    fn set_theme(&mut self, theme: crate::Theme) {
        self.set_current_theme(theme);
        self.push_native_theme_preference(theme);
        // Keep the native-dialog CSS provider (sidebar, scrollbars, popover
        // content) in sync with every theme change — see
        // `GtkPlatformServices::set_theme`'s doc.
        self.services.set_theme(&theme);
    }

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

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

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

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

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

    fn set_editor_font(&mut self, family: &str, size_pt: f32) {
        self.editor_font_family = resolve_generic_families_gtk(family);
        self.editor_font_size_pt = size_pt;
    }

    fn set_ui_font(&mut self, font_desc: &str) {
        self.ui_font = resolve_generic_families_gtk(font_desc);
    }

    /// GTK's platform-native convention: `"Monospace"`/
    /// `"Sans"`, the same fontconfig generic aliases
    /// [`resolve_generic_families_gtk`] already resolves
    /// [`crate::GenericFamily::Monospace`]/[`crate::GenericFamily::SansSerif`]
    /// to — Pango/fontconfig picks the concrete installed face (Droid
    /// Sans Mono, DejaVu Sans Mono, whatever the distro ships) at
    /// render time, so there is no single concrete family name to
    /// return here the way macOS/Win-GUI have one. Sizes (14pt editor,
    /// 13pt UI) match the VS Code convention this issue's table
    /// documents — distinct from `editor_font_size_pt`/`ui_font`'s own
    /// 11pt un-set default above, which exists for headless-test
    /// convenience rather than to model a platform recommendation.
    fn default_fonts(&self) -> crate::backend::PlatformFontDefaults {
        crate::backend::PlatformFontDefaults {
            editor_family: "Monospace".to_string(),
            editor_size_pt: 14.0,
            ui_family: "Sans".to_string(),
            ui_size_pt: 13.0,
        }
    }

    /// Overrides [`crate::gtk::NERD_FONT_FALLBACK_FAMILY`] for every
    /// subsequent `with_nerd_font_fallback`/`chrome_font_description`/
    /// `tab_bar::tab_icon_font` call in this process. Process-
    /// wide rather than a field on `self` — see
    /// `crate::gtk::current_nerd_font_fallback_family`'s doc for why.
    fn set_nerd_font_fallback(&mut self, family: &str) {
        crate::gtk::set_current_nerd_font_fallback_family(family);
    }

    /// Registers `bytes` as a Fontconfig application font, and on macOS
    /// also with Core Text directly — see
    /// `crate::gtk::app_font::register_font_from_memory`'s module doc for
    /// why this needs a process-private temp file (Fontconfig has no
    /// in-memory registration entry point). GTK previously took the trait's
    /// no-op default here while declaring `app_font_registration: true`
    /// regardless — this method closes that gap.
    fn register_font_from_memory(&mut self, bytes: &[u8]) -> Option<Vec<String>> {
        super::app_font::register_font_from_memory(bytes)
    }

    /// Answers via Fontconfig's own match/substitution algorithm, and on
    /// macOS also via Core Text directly — see
    /// `crate::gtk::app_font::has_font_family`'s doc for why neither
    /// backend's plain match/create call can be used directly and why
    /// macOS needs both consulted.
    fn has_font_family(&self, family: &str) -> Option<bool> {
        Some(super::app_font::has_font_family(family))
    }

    fn poll_events(&mut self) -> Vec<UiEvent> {
        // Drain the queue without blocking. Stage 4 wires up the
        // signal-callback producers; until then this is always empty.
        let mut out: Vec<UiEvent> = self.events.borrow_mut().drain(..).collect();
        self.apply_accelerators(&mut out);
        // Fold in any `UiEvent::User` payloads queued via `waker()`.
        // This drain is called every tick regardless of whether `events`
        // had anything in it.
        self.user_events.drain_into(&mut out);
        out
    }

    fn wait_events(&mut self, _timeout: Duration) -> Vec<UiEvent> {
        // Stage 4 will:
        // 1. Drain the queue.
        // 2. If empty, run `glib::MainContext::iteration(false)` to
        //    let pending GTK callbacks fire, then drain again.
        // 3. Repeat with `iteration(true)` (blocking) up to `_timeout`
        //    if still empty.
        //
        // Today the GTK event loop runs natively (Relm4's internals
        // pump GTK signals), so `wait_events` is currently dormant —
        // the App component handles events via Relm4 messages, not
        // through the trait. Stage 4 flips this so the trait owns
        // event flow.
        let mut out: Vec<UiEvent> = self.events.borrow_mut().drain(..).collect();
        self.apply_accelerators(&mut out);
        self.user_events.drain_into(&mut out);
        out
    }

    /// See [`Backend::waker`]'s doc for the full cross-backend contract.
    /// GTK's implementation, unlike TUI's, can't rely on a short bounded
    /// poll alone: `gtk::run::run_with`'s periodic drain only fires every
    /// 33ms, and — more importantly — `glib::MainContext::iteration`
    /// genuinely blocks between GLib main-loop wakeups with no fixed
    /// ceiling when the loop has nothing else scheduled.
    /// `glib::MainContext::invoke` is GLib's purpose-built thread-safe
    /// "run this on the loop's owning thread, waking it if blocked" primitive.
    ///
    /// The invoked closure can't reach `Rc<RefCell<GtkBackend>>`/
    /// `Rc<RefCell<App>>` directly (neither is `Send`, and `waker()` only
    /// has `&self` in any case). It instead calls back into the `Rc<dyn Fn()>`
    /// that `gtk::run::run_with` hands to its periodic timer — see
    /// [`Self::set_wake_callback`]'s doc for why they share one closure.
    ///
    /// The returned closure carries only `Send + Sync` state: the payload
    /// queue's `Arc`, the `MainContext` handle, and a bare [`WakeId`]
    /// integer. The `!Send` wake target itself stays parked in the GTK
    /// main thread's [`WAKE_CALLBACKS`] map and is looked up by id *after*
    /// `invoke` has already put us back on that thread — so no `Rc` ever
    /// crosses a thread boundary. See [`WAKE_CALLBACKS`]'s doc for the full
    /// argument, including why a lookup miss costs latency rather than the
    /// event.
    fn waker(&self) -> Arc<dyn Fn(UserPayload) + Send + Sync> {
        let queue = Arc::clone(&self.user_events);
        let main_context = glib::MainContext::default();
        let wake_id = self.wake_id;
        Arc::new(move |payload: UserPayload| {
            queue.push(payload.into_arc());
            main_context.invoke(move || {
                if let Some(callback) = wake_callback_for(wake_id) {
                    callback();
                }
            });
        })
    }

    /// See [`Backend::request_frame_in`]'s doc for the cross-backend
    /// contract. Unlike [`Self::waker`] — which runs on a
    /// background thread and so must hop onto the GTK main thread via
    /// `glib::MainContext::invoke` before it can touch anything — this
    /// method already runs on the GTK main thread — called synchronously
    /// from event/tick handling — so it can arm a
    /// real one-shot timer directly: `glib::source::timeout_add_local_once`,
    /// the same primitive `gtk::run::run_with`'s resize-settle debounce
    /// uses. The fired callback reaches back into the app/backend graph
    /// through the *same* [`WAKE_CALLBACKS`] lookup `waker()`'s invoked
    /// closure uses — a scheduled frame and a thread wake really are the
    /// same mechanism here, just armed from two different starting
    /// threads.
    ///
    /// No dedup/cancellation against an already-armed request — see
    /// [`crate::runner::Reaction::RedrawAfter`]'s doc for why an
    /// occasional extra, harmless early wake is an accepted tradeoff for
    /// not needing to track "is there already a sooner one pending" state
    /// here.
    fn request_frame_in(&self, delay: Duration) {
        let wake_id = self.wake_id;
        glib::source::timeout_add_local_once(delay, move || {
            if let Some(callback) = wake_callback_for(wake_id) {
                callback();
            }
        });
    }

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

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

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

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

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

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

    fn modal_stack_handle(&self) -> Rc<std::cell::RefCell<ModalStack>> {
        // Trait-level entry point — delegates to the inherent
        // `GtkBackend::modal_stack_handle` (same clone), which is the
        // primary spelling for `GtkBackend`-typed callers.
        self.modal_stack.clone()
    }

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

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

    fn draw_focus_ring(&mut self, rect: QRect) {
        let theme = self.current_theme;
        let stroke_width = self.current_style.focus_ring_width;
        self.surface_stroke_rect(rect, theme.accent_fg, stroke_width);
        // A chrome-only paint (no text of its own) is only "observable"
        // via a registered zone.
        self.register_zone(WidgetId::new("chrome:focus-ring"), rect);
    }

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

    /// `GtkBackend` implements [`PaintSurface`] directly (see this
    /// module's own `impl PaintSurface for GtkBackend` block below), so
    /// this always answers `Some(self)` — never the `None` default
    /// `Backend::paint_surface` falls back to.
    fn paint_surface(&mut self) -> Option<&mut dyn PaintSurface> {
        Some(self)
    }

    /// Honest per-method, not aspirational.
    ///
    /// - `mouse` / `scroll` / `drag`: `gtk::run` attaches a `GestureClick`,
    ///   an `EventControllerScroll` (`BOTH_AXES`) and an
    ///   `EventControllerMotion` to the drawing area, so presses,
    ///   wheel/trackpad scroll and button-held motion all arrive as
    ///   `UiEvent`s.
    /// - `text_selection`: `register_text_region` and
    ///   `cancel_text_selection_drag` are both overridden below.
    /// - `native_menu`: **not** declared — `install_menu_bar` /
    ///   `show_context_menu` are still the trait's no-op default; GTK apps
    ///   paint their own `ContextMenu` (see `Backend::show_context_menu`
    ///   doc comment).
    /// - `window_chrome`: `begin_window_drag` / `toggle_window_maximize` /
    ///   `begin_window_resize` are all overridden.
    /// - `pointer_cursor`: `set_cursor` is overridden.
    /// - `ime`: not declared — no backend positions an IME composition
    ///   window yet (see [`crate::backend::BackendCaps::ime`]).
    /// - `file_dialogs` / `folder_dialogs`: `GtkPlatformServices`
    ///   uses real `gtk4::FileDialog` pickers, including `select_folder`
    ///   for the directory chooser (`src/gtk/services.rs`), not a stub.
    /// - `native_dialogs`: `GtkPlatformServices::show_message_dialog` uses
    ///   a real `gtk4::AlertDialog` (`src/gtk/services.rs`), pumped
    ///   through the same `pump_until_ready` + `pump_depth` guard the
    ///   file dialogs use.
    /// - `notifications`: `GtkPlatformServices::send_notification`
    ///   sends a real `gio::Notification` through the window's owning
    ///   `gtk4::Application` (`src/gtk/services.rs`), and activation routes
    ///   back through a `GAction` into [`crate::UiEvent::NotificationActivated`].
    ///   This is the one backend that declares the capability today.
    fn backend_caps(&self) -> crate::backend::BackendCaps {
        crate::backend::BackendCaps {
            mouse: true,
            scroll: true,
            drag: true,
            text_selection: true,
            window_chrome: true,
            pointer_cursor: true,
            file_dialogs: true,
            folder_dialogs: true,
            native_dialogs: true,
            notifications: true,
            // `app_font_registration`: `register_font_from_memory` and
            // `set_nerd_font_fallback` are both overridden — both halves
            // of the capability.
            app_font_registration: true,
            // `generic_font_families`: `set_editor_font`/
            // `set_ui_font` are both overridden below and now resolve
            // CSS/Pango generic tokens (`monospace`/`sans-serif`/
            // `system-ui`) via `resolve_generic_families_gtk` before
            // storing them — fontconfig already resolves the first two
            // natively, and `system-ui` is rewritten onto `Sans`.
            generic_font_families: true,
            // `window` is overridden below and returns
            // `Some` once `set_window` has stashed a real
            // `gtk4::ApplicationWindow` — see `impl WindowControl for
            // GtkBackend`'s doc for which methods that surface actually
            // backs (title/size/min-size/fullscreen/minimize/restore/
            // hide/show/focus) versus report `Unsupported` (position —
            // `bounds`/`set_bounds`/`center` — and `set_always_on_top`,
            // both structurally absent on GTK4/Wayland).
            window_control: true,
            ..crate::backend::BackendCaps::empty()
        }
    }

    fn begin_window_drag(&mut self) -> bool {
        // Do NOT call `gdk4::Toplevel::begin_move` synchronously.
        // Doing so on the very first press — before it's known whether
        // a second press is coming — starts an interactive move grab that
        // swallows the second press, so a double-click on a CSD titlebar
        // never reaches the app. Instead this arms `Self::armed_window_drag`;
        // `gtk/run.rs`'s motion controller commits it once the pointer has
        // moved past the drag threshold, mirroring how native `gtk4::WindowHandle`
        // defers its own move-start to a threshold-gated signal.
        if self.window.is_none() {
            return false;
        }
        let Some((device, button, x, y, time)) = self.pending_window_press.take() else {
            return false;
        };
        self.armed_window_drag
            .arm((device, button, x, y, time), x, y);
        true
    }

    fn toggle_window_maximize(&mut self) -> bool {
        let Some(window) = self.window.as_ref() else {
            return false;
        };
        if window.is_maximized() {
            window.unmaximize();
        } else {
            window.maximize();
        }
        true
    }

    fn begin_window_resize(&mut self, edge: ResizeEdge) -> bool {
        // Mirrors `begin_window_drag`'s no-window / no-pending-press guards,
        // but calls `gdk4::Toplevel::begin_resize` directly instead of
        // arming a deferred request: edges have no competing double-click
        // gesture to protect against.
        let Some(window) = self.window.as_ref() else {
            return false;
        };
        let Some((device, button, x, y, time)) = self.pending_window_press.take() else {
            return false;
        };
        match window
            .surface()
            .and_then(|s| s.downcast::<gdk::Toplevel>().ok())
        {
            Some(toplevel) => {
                toplevel.begin_resize(
                    resize_edge_to_surface_edge(edge),
                    Some(&device),
                    button,
                    x,
                    y,
                    time,
                );
                true
            }
            None => false,
        }
    }

    fn set_cursor(&mut self, shape: PointerShape) -> bool {
        // GTK CSS cursor names inherit from the window down to the
        // (cursor-less-by-default) content `DrawingArea`, so setting it on
        // the stored top-level window is enough to change the pointer
        // glyph anywhere over the content area.
        let Some(window) = self.window.as_ref() else {
            return false;
        };
        window.set_cursor_from_name(Some(pointer_shape_cursor_name(shape)));
        true
    }

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

    // ─── Drawing ───────────────────────────────────────────────────────────
    //
    // Stage 1 stubs. Stage 2 fills these in by folding the existing
    // `quadraui_gtk::draw_*` shims into the trait method bodies
    // (mirroring TUI Stage 2). For now they panic with a clear
    // "deferred" message — the GTK draw path doesn't go through the
    // trait yet, so these are unreachable in practice.

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

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

    /// Forwards to [`Self::set_current_line_height`] — the
    /// `Backend`-trait-object-reachable twin of that inherent method,
    /// which `vimcode`'s click-drift guard needs to re-apply
    /// metrics through `&mut dyn Backend` without a GTK-typed supertrait.
    fn set_current_line_height(&mut self, line_height: f32) {
        GtkBackend::set_current_line_height(self, line_height as f64);
    }

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

    /// `current_chrome_char_width`, not `current_char_width` —
    /// [`Self::draw_list`] paints row text with `ui_font`,
    /// and `current_chrome_char_width` is that font's real Pango
    /// advance, refreshed every frame by [`Self::refresh_chrome_char_width`]
    /// the same way `current_char_width` is refreshed from the editor
    /// font. See the field's doc for why the two can disagree.
    fn list_char_width(&self) -> f32 {
        self.current_chrome_char_width as f32
    }

    /// Real Pango measurement against a fresh `pango::Layout` built from
    /// `role`'s `FontDescription` — `crate::gtk::
    /// chrome_font_description(&self.ui_font)` for [`crate::FontRole::Chrome`],
    /// [`Self::editor_font_pango_string`] for [`crate::FontRole::Editor`],
    /// the same two descriptions [`Self::surface_draw_text_run_with_role`]
    /// already resolves per role. Built against the stable
    /// widget-realized `pango_ctx`, not the per-frame `cr`/`layout` pair
    /// from [`Self::current_frame_refs`] — same "works outside a frame
    /// too" posture as [`Self::data_table_layout`]'s own `pango_ctx` use,
    /// since an app computing a `Dialog`/`ContextMenu` measure has no
    /// live frame to borrow from.
    ///
    /// Falls back to a `char_width`-scaled estimate (mirroring
    /// `PangoTextMeasure`'s own pre-realization fallback) when no
    /// `pango_ctx` has been set yet — e.g. a `GtkBackend` queried before
    /// its widget realizes.
    fn measure_text(&self, text: &str, role: crate::FontRole) -> (f32, f32) {
        let Some(ctx) = self.pango_ctx.as_ref() else {
            let char_w = match role {
                crate::FontRole::Chrome => self.current_chrome_char_width as f32,
                crate::FontRole::Editor => self.current_char_width as f32,
            };
            return (
                (text.chars().count() as f32 * char_w).ceil() + 2.0,
                self.current_line_height as f32,
            );
        };
        let layout = pango::Layout::new(ctx);
        let desc = match role {
            crate::FontRole::Chrome => crate::gtk::chrome_font_description(&self.ui_font),
            crate::FontRole::Editor => {
                pango::FontDescription::from_string(&self.editor_font_pango_string())
            }
        };
        layout.set_font_description(Some(&desc));
        layout.set_text(text);
        let (w, h) = layout.pixel_size();
        (w as f32, h as f32)
    }

    /// GTK's `ScrolledWindow` overlay scrollbar draws on top of the
    /// content edge. CSS requests 4px but GTK may allocate slightly
    /// more; 8px is a safe reserve so text never renders behind it.
    fn scrollbar_reserve(&self) -> f32 {
        8.0
    }

    /// GTK applies per-line font scale via a Pango scale attr, so scaled
    /// rows (e.g. markdown headings) draw taller and layouts must
    /// reserve the extra height.
    fn scales_text_rows(&self) -> bool {
        true
    }

    fn draw_tree(&mut self, rect: QRect, tree: &TreeView) {
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_tree called outside enter_frame_scope");
        // Row labels, badges and chevrons are chrome, not editor
        // content — save the editor font on the shared layout, paint the
        // tree in `ui_font`, then restore so later draws in this frame
        // aren't left painting chrome-sized text. `gtk::draw_tree` itself
        // does all its own text measurement inline against `layout`, so
        // swapping the font here covers paint and measurement alike.
        let saved_font = layout.font_description();
        layout.set_font_description(Some(&ui_font_desc));
        crate::gtk::draw_tree(
            cr,
            layout,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
            tree,
            &self.current_theme,
            self.current_line_height,
            self.nerd_fonts_enabled,
        );
        layout.set_font_description(saved_font.as_ref());
    }

    fn draw_list(&mut self, rect: QRect, list: &ListView) {
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_list called outside enter_frame_scope");
        // Row labels and icon glyphs (`Icon::glyph`) are chrome, not
        // editor content — mirrors `Self::draw_tree`'s save/swap/restore
        // above. Before this, `draw_list` painted with whatever font the
        // shared layout happened to carry into the frame (typically the
        // editor font), which has no Nerd-Font fallback family, so an
        // icon glyph could render as tofu/blank depending on what else is
        // installed.
        let saved_font = layout.font_description();
        layout.set_font_description(Some(&ui_font_desc));
        crate::gtk::draw_list(
            cr,
            layout,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
            list,
            &self.current_theme,
            self.current_line_height,
            self.nerd_fonts_enabled,
        );
        layout.set_font_description(saved_font.as_ref());
    }

    fn draw_data_table(
        &mut self,
        rect: QRect,
        table: &crate::DataTable,
        hovered_idx: Option<usize>,
    ) -> crate::DataTableLayout {
        self.draw_data_table_with_glyphs(rect, table, hovered_idx, None)
    }

    /// [`Self::draw_data_table`] plus an optional
    /// [`crate::primitives::data_table::DataTableGlyphs`] override for the
    /// header's sort-direction glyph, honoured in full here (unlike the
    /// trait default, which ignores `glyphs`).
    fn draw_data_table_with_glyphs(
        &mut self,
        rect: QRect,
        table: &crate::DataTable,
        hovered_idx: Option<usize>,
        glyphs: Option<&crate::primitives::data_table::DataTableGlyphs>,
    ) -> crate::DataTableLayout {
        let lh = self.current_line_height;
        let theme = self.current_theme;
        let nerd_fonts_enabled = self.nerd_fonts_enabled;
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_data_table_with_glyphs called outside enter_frame_scope");
        // `DataTable` is chrome, not editor content — save the editor
        // font on the shared layout, paint the table in `ui_font`, then
        // restore, matching `Self::draw_tree`'s save/swap/restore.
        // `crate::gtk::draw_data_table_with_glyphs` derives its bold/icon
        // font variants from whatever base font `layout` carries in, so
        // without this swap it painted with whatever the ambient
        // per-frame font happened to be (the editor font by default).
        let saved_font = layout.font_description();
        layout.set_font_description(Some(&ui_font_desc));
        let table_layout = crate::gtk::draw_data_table_with_glyphs(
            cr,
            layout,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
            table,
            &theme,
            lh,
            hovered_idx,
            glyphs,
            nerd_fonts_enabled,
        );
        layout.set_font_description(saved_font.as_ref());

        // Record header + visible body + footer cell text into the
        // painted-text map that GtkDriver::find scans. Bounds are
        // derived from `table_layout` + the declarative `table`, not by
        // re-deriving Cairo/Pango geometry, so they can't drift from
        // what was actually drawn.
        let h_off = table.h_scroll as f64;
        let header_height = table_layout.header_height as f64;
        for (col_idx, rc) in table_layout.columns.iter().enumerate() {
            if rc.width <= 0.0 {
                continue;
            }
            if let Some(col) = table.columns.get(col_idx) {
                let bounds = QRect::new(
                    (rect.x as f64 + rc.x as f64 - h_off) as f32,
                    rect.y,
                    rc.width,
                    header_height as f32,
                );
                self.record_painted_text(&col.title, bounds);
            }
        }

        let row_height = table_layout.row_height as f64;
        let body_y = rect.y as f64 + header_height;
        let visible = table_layout
            .visible_rows
            .min(table.rows.len().saturating_sub(table.scroll_offset));
        for row_idx in 0..visible {
            let abs_idx = table.scroll_offset + row_idx;
            let row = &table.rows[abs_idx];
            let row_y = body_y + row_idx as f64 * row_height;
            for (col_idx, rc) in table_layout.columns.iter().enumerate() {
                if rc.width <= 0.0 {
                    continue;
                }
                let Some(cell) = row.cells.get(col_idx) else {
                    continue;
                };
                if cell.spans.is_empty() {
                    continue;
                }
                let text: String = cell.spans.iter().map(|s| s.text.as_str()).collect();
                if text.is_empty() {
                    continue;
                }
                let bounds = QRect::new(
                    (rect.x as f64 + rc.x as f64 - h_off) as f32,
                    row_y as f32,
                    rc.width,
                    row_height as f32,
                );
                self.record_painted_text(&text, bounds);
            }
        }

        if let Some(footer) = &table.footer {
            if table_layout.footer_height > 0.0 {
                let footer_y = rect.y as f64 + rect.height as f64 - row_height;
                for (col_idx, rc) in table_layout.columns.iter().enumerate() {
                    if rc.width <= 0.0 {
                        continue;
                    }
                    let Some(cell) = footer.cells.get(col_idx) else {
                        continue;
                    };
                    if cell.spans.is_empty() {
                        continue;
                    }
                    let text: String = cell.spans.iter().map(|s| s.text.as_str()).collect();
                    if text.is_empty() {
                        continue;
                    }
                    let bounds = QRect::new(
                        (rect.x as f64 + rc.x as f64 - h_off) as f32,
                        footer_y as f32,
                        rc.width,
                        row_height as f32,
                    );
                    self.record_painted_text(&text, bounds);
                }
            }
        }

        table_layout
    }

    /// Column headers are now measured via `pango::Layout` instead of
    /// byte length (which counted UTF-8 bytes rather than characters).
    /// Routes through [`crate::primitives::layout_metrics::pixel_data_table_layout`]
    /// with a real Pango measurer built from the widget-realized `pango_ctx`
    /// (falling back to a character estimate only when no context exists yet).
    fn data_table_layout(&self, rect: QRect, table: &crate::DataTable) -> crate::DataTableLayout {
        let char_w = self.current_char_width as f32;
        let pango_layout = self.chrome_measure_layout();
        let measure = PangoTextMeasure {
            layout: &pango_layout,
            char_w,
        };
        crate::primitives::layout_metrics::pixel_data_table_layout(
            table,
            rect.width,
            rect.height,
            self.current_line_height as f32,
            &measure,
        )
    }

    fn list_hscrollbar(&self, rect: QRect, list: &ListView) -> Option<crate::Scrollbar> {
        // `ListView::h_scroll` and `max_content_width` are in character columns,
        // but GTK works in pixels.  Convert with `current_char_width` so the
        // returned `Scrollbar` track/thumb are in pixel units — matching what
        // `gtk::draw_list` paints and what mouse-event coords use.
        let char_w = self.current_char_width as f32;
        let max_w_chars = list.max_content_width? as f32;
        let content_px = max_w_chars * char_w;
        let border_inset = if list.bordered { char_w } else { 0.0 };
        let visible_px = (rect.width - 2.0 * border_inset).max(0.0);
        if content_px <= visible_px {
            return None;
        }
        let row_h = self.line_height();
        let track = crate::primitives::list::hscrollbar_track(rect, list.bordered, char_w, row_h);
        Some(crate::Scrollbar::horizontal(
            list.id,
            track,
            list.h_scroll as f32 * char_w,
            content_px,
            visible_px,
            row_h,
        ))
    }

    fn list_vscrollbar(&self, rect: QRect, list: &ListView) -> Option<crate::Scrollbar> {
        // GTK ListView vertical-scrollbar rasteriser not yet implemented.
        // Delegate to the primitive's geometry method using pixel units:
        // each "row" is one line_height tall.
        list.vscrollbar(rect, self.line_height())
    }

    fn list_layout(&self, rect: QRect, list: &ListView) -> crate::ListViewLayout {
        crate::gtk::gtk_list_layout(
            rect.width as f64,
            rect.height as f64,
            list,
            self.current_line_height,
            self.current_char_width,
        )
    }

    /// Shared field-kind painting lives in
    /// [`crate::primitives::form::paint`] now — see that fn's doc for why
    /// `FieldKind::Toolbar` is the one variant painted here instead,
    /// after `paint` releases its exclusive borrow of `self`.
    fn draw_form(&mut self, rect: QRect, form: &Form) {
        let theme = self.current_theme;
        let flayout = self.form_layout(rect, form);
        let origin = Point::new(rect.x, rect.y);
        crate::primitives::form::paint(form, &flayout, self, &theme, origin);

        for vf in &flayout.visible_fields {
            let Some(field) = form.fields.get(vf.field_idx) else {
                continue;
            };
            let FieldKind::Toolbar(toolbar) = &field.kind else {
                continue;
            };
            let row_x = (origin.x + vf.bounds.x) as f64;
            let row_y = (origin.y + vf.bounds.y) as f64;
            let row_w = vf.bounds.width as f64;
            let row_h = vf.bounds.height as f64;

            let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
            let (cr, layout) = self
                .current_frame_refs()
                .expect("GtkBackend::draw_form called outside enter_frame_scope");
            // A `Toolbar` field's label and embedded toolbar are
            // chrome, like every other form field label `paint` above
            // already paints in `ui_font` via `GtkBackend`'s own
            // (chrome-defaulting) `PaintSurface` impl — save/swap/restore
            // around this raw `(cr, layout)` measurement + paint too, the
            // same shape `Self::draw_tree` uses, since neither this
            // method nor `crate::gtk::toolbar::draw_toolbar` goes through
            // `PaintSurface`.
            let saved_font = layout.font_description();
            layout.set_font_description(Some(&ui_font_desc));
            let label_text: String = field.label.spans.iter().map(|s| s.text.as_str()).collect();
            let no_label = label_text.is_empty();
            layout.set_text(&label_text);
            let (label_w, _) = layout.pixel_size();
            let toolbar_x = if no_label {
                row_x + 6.0
            } else {
                row_x + 6.0 + label_w as f64 + 12.0
            };
            let toolbar_w = row_x + row_w - toolbar_x;
            if toolbar_w > 0.0 {
                crate::gtk::toolbar::draw_toolbar(
                    cr, layout, toolbar_x, row_y, toolbar_w, row_h, toolbar, &theme, None, None,
                );
                layout.set_attributes(None);
            }
            layout.set_font_description(saved_font.as_ref());
        }
    }

    fn draw_palette(&mut self, rect: QRect, palette: &Palette) {
        // See `modal_stack.rs`'s "Paint-consistency detection" docs —
        // records that this palette's surface was actually painted this frame.
        self.modal_stack.borrow_mut().mark_painted(&palette.id);
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_palette called outside enter_frame_scope");
        // The command palette is chrome, not editor content — same
        // save/swap/restore as `Self::draw_tree`, since
        // `crate::gtk::draw_palette` paints directly against whatever
        // font `layout` carries in rather than going through
        // `PaintSurface`.
        let saved_font = layout.font_description();
        layout.set_font_description(Some(&ui_font_desc));
        // Calls the shared paint directly (rather than through
        // `crate::gtk::draw_palette`, whose public signature stays
        // additive-only and so cannot take a live `&Style`) so this live
        // backend path honours `Self::set_style` overrides.
        if rect.width >= 20.0 && rect.height >= self.current_line_height as f32 * 4.0 {
            let (palette_layout, rows_h) = crate::gtk::gtk_palette_layout(
                rect.width as f64,
                rect.height as f64,
                palette,
                self.current_line_height,
            );
            let area = crate::event::Rect::new(rect.x, rect.y, rect.width, rect.height);
            let style = self.style();
            let nerd_fonts_enabled = self.nerd_fonts_enabled;
            let mut surface = crate::gtk::surface::CairoSurface {
                cr,
                layout: Some(layout),
                translucent_fill: true,
            };
            crate::primitives::palette::native_surface_paint::paint(
                palette,
                area,
                &palette_layout,
                rows_h as f32,
                self.current_line_height as f32,
                nerd_fonts_enabled,
                &mut surface,
                &self.current_theme,
                &style,
            );
            layout.set_attributes(None);
        }
        layout.set_font_description(saved_font.as_ref());
    }

    fn palette_layout(&self, rect: QRect, palette: &Palette) -> crate::PaletteLayout {
        crate::gtk::gtk_palette_layout(
            rect.width as f64,
            rect.height as f64,
            palette,
            self.current_line_height,
        )
        .0
    }

    fn draw_settings_chrome(
        &mut self,
        rect: QRect,
        header_text: &str,
        query: &str,
        placeholder: &str,
        active: bool,
    ) {
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_settings_chrome called outside enter_frame_scope");
        // The settings panel header/search box is chrome, not editor
        // content — save the editor font on the shared layout, paint in
        // `ui_font`, then restore, matching `Self::draw_tree`'s
        // save/swap/restore.
        let saved_font = layout.font_description();
        layout.set_font_description(Some(&ui_font_desc));
        crate::gtk::draw_settings_chrome(
            cr,
            layout,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
            self.current_line_height,
            header_text,
            query,
            placeholder,
            active,
            &self.current_theme,
        );
        layout.set_font_description(saved_font.as_ref());
    }

    // ─── Layout-passthrough primitives ─────────────────────────────────────
    //
    // Phase B.5b Stage 9: trait extended with `&Layout` parameter per
    // `docs/decisions/BACKEND_TRAIT_PROPOSAL.md` §6.2. The current GTK rasterisers
    // (`quadraui_gtk::draw_status_bar` etc.) recompute their own
    // layout internally, so the `_layout` parameter is currently
    // ignored — kept for forward compatibility when the GTK
    // rasterisers are updated to consume it. Behaviour is unchanged.

    // Trait extended with `&Layout` parameter. Three of the five
    // primitives (status_bar, tab_bar, text_display) have quadraui-side
    // rasterisers that accept `crate::Theme`; the trait impls route through
    // them. The remaining two (activity_bar, terminal) have only in-tree
    // `quadraui_gtk::*` shims that take the legacy `render::Theme`; until
    // those are lifted into quadraui itself, the trait impls stay as stubs.
    // The GTK call sites continue to use the legacy shims directly.

    fn draw_status_bar_interactive(
        &mut self,
        rect: QRect,
        bar: &StatusBar,
        interaction: &crate::interaction::InteractionState,
    ) -> crate::StatusBarLayout {
        self.status_bar_paint_scaled(rect, bar, interaction, 1.0)
    }

    /// Same paint as [`Self::draw_status_bar_interactive`],
    /// scaling only this call's chrome font size. Both methods funnel
    /// through [`Self::status_bar_paint_scaled`] so a fix to one applies to
    /// both; `1.0` there is exactly this call with no scaling applied.
    fn draw_status_bar_interactive_scaled(
        &mut self,
        rect: QRect,
        bar: &StatusBar,
        interaction: &crate::interaction::InteractionState,
        font_scale: f32,
    ) -> crate::StatusBarLayout {
        self.status_bar_paint_scaled(rect, bar, interaction, font_scale)
    }

    // `status_bar_paint_scaled` — the shared body both methods above
    // funnel through — is defined in the inherent `impl GtkBackend` block.
    // A trait impl block may only contain that trait's own items.

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

    /// Counterpart to [`Self::draw_tab_bar`] that returns [`TabBarLayout`] instead.
    fn draw_tab_bar_layout(
        &mut self,
        rect: QRect,
        bar: &TabBar,
        hovered_close_tab: Option<usize>,
    ) -> TabBarLayout {
        self.draw_tab_bar_icons_layout(rect, bar, &[], hovered_close_tab)
    }

    #[allow(deprecated)] // returns the deprecated `TabBarHits` — issue #823
    fn draw_tab_bar_icons(
        &mut self,
        rect: QRect,
        bar: &TabBar,
        icons: &[Option<crate::TabIcon>],
        hovered_close_tab: Option<usize>,
    ) -> crate::TabBarHits {
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, pango_layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_tab_bar called outside enter_frame_scope");
        // Tab labels/segments are chrome, not editor content —
        // `gtk::draw_tab_bar_icons`'s own doc contract is "caller sets the
        // desired UI font on `layout` before calling", so set `ui_font`
        // here and restore the editor font afterward so later draws in
        // this same frame aren't left painting chrome-sized text.
        let saved_font = pango_layout.font_description();
        pango_layout.set_font_description(Some(&ui_font_desc));
        let (hits, resolved_layout) = crate::gtk::draw_tab_bar_icons(
            cr,
            pango_layout,
            rect.x as f64,
            rect.width as f64,
            self.current_line_height,
            rect.y as f64,
            rect.height as f64,
            bar,
            icons,
            &self.current_theme,
            hovered_close_tab,
        );
        pango_layout.set_font_description(saved_font.as_ref());
        // Cache the resolved layout for this bar's WidgetId —
        // `GtkDriver::tab_center`/`tab_close_center`
        // resolve against this, since a driver sitting outside the app
        // has no other way to reach a specific tab's geometry (every tab
        // paints the same close glyph, so `find` can't disambiguate tab
        // N's target).
        self.tab_bar_layouts.insert(bar.id, (rect, resolved_layout));
        hits
    }

    /// Counterpart to [`Self::draw_tab_bar_icons`] that returns [`TabBarLayout`] instead.
    fn draw_tab_bar_icons_layout(
        &mut self,
        rect: QRect,
        bar: &TabBar,
        icons: &[Option<crate::TabIcon>],
        hovered_close_tab: Option<usize>,
    ) -> TabBarLayout {
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, pango_layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_tab_bar_icons_layout called outside enter_frame_scope");
        let saved_font = pango_layout.font_description();
        pango_layout.set_font_description(Some(&ui_font_desc));
        #[allow(deprecated)] // discarded `TabBarHits` half of the pair — issue #823
        let (_hits, resolved_layout) = crate::gtk::draw_tab_bar_icons(
            cr,
            pango_layout,
            rect.x as f64,
            rect.width as f64,
            self.current_line_height,
            rect.y as f64,
            rect.height as f64,
            bar,
            icons,
            &self.current_theme,
            hovered_close_tab,
        );
        pango_layout.set_font_description(saved_font.as_ref());
        self.tab_bar_layouts
            .insert(bar.id, (rect, resolved_layout.clone()));
        resolved_layout
    }

    #[allow(deprecated)] // returns the deprecated `TabBarHits` — issue #823
    fn draw_tab_bar_with_chrome(
        &mut self,
        rect: QRect,
        bar: &TabBar,
        hovered_close_tab: Option<usize>,
        chrome: &TabChrome,
    ) -> crate::TabBarHits {
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, pango_layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_tab_bar_with_chrome called outside enter_frame_scope");
        let saved_font = pango_layout.font_description();
        pango_layout.set_font_description(Some(&ui_font_desc));
        let (hits, resolved_layout) = crate::gtk::draw_tab_bar_icons_with_chrome(
            cr,
            pango_layout,
            rect.x as f64,
            rect.width as f64,
            self.current_line_height,
            rect.y as f64,
            rect.height as f64,
            bar,
            &[],
            chrome,
            &self.current_theme,
            hovered_close_tab,
        );
        pango_layout.set_font_description(saved_font.as_ref());
        self.tab_bar_layouts.insert(bar.id, (rect, resolved_layout));
        hits
    }

    /// [`Self::draw_tab_bar_with_chrome`] plus an optional
    /// [`crate::primitives::tab_bar::TabBarGlyphs`] override for the
    /// close/dirty glyph, honoured in full here (unlike the trait default,
    /// which ignores `glyphs`).
    #[allow(deprecated)] // returns the deprecated `TabBarHits` — issue #823
    fn draw_tab_bar_with_chrome_and_glyphs(
        &mut self,
        rect: QRect,
        bar: &TabBar,
        hovered_close_tab: Option<usize>,
        chrome: &TabChrome,
        glyphs: Option<&crate::primitives::tab_bar::TabBarGlyphs>,
    ) -> crate::TabBarHits {
        let nerd_fonts_enabled = self.nerd_fonts_enabled;
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, pango_layout) = self.current_frame_refs().expect(
            "GtkBackend::draw_tab_bar_with_chrome_and_glyphs called outside enter_frame_scope",
        );
        let saved_font = pango_layout.font_description();
        pango_layout.set_font_description(Some(&ui_font_desc));
        let (hits, resolved_layout) = crate::gtk::draw_tab_bar_icons_with_chrome_and_glyphs(
            cr,
            pango_layout,
            rect.x as f64,
            rect.width as f64,
            self.current_line_height,
            rect.y as f64,
            rect.height as f64,
            bar,
            &[],
            chrome,
            &self.current_theme,
            hovered_close_tab,
            glyphs,
            nerd_fonts_enabled,
        );
        pango_layout.set_font_description(saved_font.as_ref());
        self.tab_bar_layouts.insert(bar.id, (rect, resolved_layout));
        hits
    }

    /// Counterpart to [`Self::draw_tab_bar_with_chrome`] that returns [`TabBarLayout`] instead.
    fn draw_tab_bar_with_chrome_layout(
        &mut self,
        rect: QRect,
        bar: &TabBar,
        hovered_close_tab: Option<usize>,
        chrome: &TabChrome,
    ) -> TabBarLayout {
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, pango_layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_tab_bar_with_chrome_layout called outside enter_frame_scope");
        let saved_font = pango_layout.font_description();
        pango_layout.set_font_description(Some(&ui_font_desc));
        #[allow(deprecated)] // discarded `TabBarHits` half of the pair — issue #823
        let (_hits, resolved_layout) = crate::gtk::draw_tab_bar_icons_with_chrome(
            cr,
            pango_layout,
            rect.x as f64,
            rect.width as f64,
            self.current_line_height,
            rect.y as f64,
            rect.height as f64,
            bar,
            &[],
            chrome,
            &self.current_theme,
            hovered_close_tab,
        );
        pango_layout.set_font_description(saved_font.as_ref());
        self.tab_bar_layouts
            .insert(bar.id, (rect, resolved_layout.clone()));
        resolved_layout
    }

    fn draw_activity_bar(
        &mut self,
        rect: QRect,
        bar: &ActivityBar,
        hovered_idx: Option<usize>,
    ) -> Vec<crate::ActivityBarRowHit> {
        // Track keyboard focus so the GTK runner's key handler can
        // redirect KeyPressed events to this bar.
        if bar.is_keyboard_focused {
            self.focused_activity_bar = Some(bar.id);
        }
        let (cr, layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_activity_bar called outside enter_frame_scope");
        cr.save().ok();
        cr.translate(rect.x as f64, rect.y as f64);
        let hits = crate::gtk::draw_activity_bar(
            cr,
            layout,
            rect.width as f64,
            rect.height as f64,
            bar,
            &self.current_theme,
            hovered_idx,
            self.nerd_fonts_enabled,
        );
        cr.restore().ok();
        hits
    }

    fn draw_activity_bar_with_style(
        &mut self,
        rect: QRect,
        bar: &ActivityBar,
        hovered_idx: Option<usize>,
        style: &crate::ActivityBarStyle,
    ) -> Vec<crate::ActivityBarRowHit> {
        // Track keyboard focus so the GTK runner's key handler can
        // redirect KeyPressed events to this bar.
        if bar.is_keyboard_focused {
            self.focused_activity_bar = Some(bar.id);
        }
        let (cr, layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_activity_bar_with_style called outside enter_frame_scope");
        cr.save().ok();
        cr.translate(rect.x as f64, rect.y as f64);
        let hits = crate::gtk::draw_activity_bar_with_style(
            cr,
            layout,
            rect.width as f64,
            rect.height as f64,
            bar,
            style,
            &self.current_theme,
            hovered_idx,
            self.nerd_fonts_enabled,
        );
        cr.restore().ok();
        hits
    }

    fn status_bar_layout(&self, rect: QRect, bar: &StatusBar) -> crate::StatusBarLayout {
        let char_w = self.current_char_width as f32;
        let lh = self.current_line_height as f32;
        let frame_layout = self.current_frame_refs().map(|(_, l)| l.clone());
        let pango_layout = frame_layout.or_else(|| self.pango_ctx.as_ref().map(pango::Layout::new));
        // Measure with `ui_font`, matching `draw_status_bar`'s paint
        // font — a no-paint caller (hit-testing without repainting) must
        // resolve the same segment widths the paint path produced.
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let saved_font = pango_layout.as_ref().and_then(|pl| pl.font_description());
        if let Some(pl) = &pango_layout {
            pl.set_font_description(Some(&ui_font_desc));
        }
        // `layout_padded` (not plain `layout`) so this no-paint
        // twin agrees with the shared `native_surface_paint::paint`'s
        // outer edge inset + per-segment padding — see that fn's doc.
        let result = bar.layout_padded(
            rect.width,
            lh,
            crate::gtk::MIN_GAP_PX,
            crate::primitives::status_bar::PIXEL_EDGE_INSET,
            crate::primitives::status_bar::PIXEL_SEGMENT_PADDING,
            |seg| {
                let text_w = self.pango_str_width(&pango_layout, &seg.text, char_w);
                crate::StatusSegmentMeasure::new(text_w)
            },
        );
        if let Some(pl) = &pango_layout {
            pl.set_font_description(saved_font.as_ref());
        }
        result
    }

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

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

    #[allow(deprecated)] // returns the deprecated `TabBarHits` — issue #823
    fn tab_bar_layout_icons(
        &self,
        rect: QRect,
        bar: &TabBar,
        icons: &[Option<crate::TabIcon>],
    ) -> crate::TabBarHits {
        let char_w = self.current_char_width as f32;
        let frame_layout = self.current_frame_refs().map(|(_, l)| l.clone());
        let pango_layout = frame_layout.or_else(|| self.pango_ctx.as_ref().map(pango::Layout::new));

        // No Pango handle at all — headless (`GtkDriver`) or a widget
        // that hasn't realised yet. The char-cell estimate further down
        // is the only measurement left, and it does *not* agree with the
        // Pango widths the paint path used, so every click lands left or
        // right of the glyph the user sees. Prefer the geometry the most
        // recent `draw_tab_bar` for this bar actually resolved — the same
        // per-frame cache `GtkDriver::tab_close_center` reads, so the
        // driver's reported close-button centre and this twin's close
        // region are the *same numbers* instead of two independent
        // guesses that only happen to overlap when the host's UI font is
        // close enough to the 8px nominal cell.
        if pango_layout.is_none() {
            if let Some(hits) = self.cached_tab_bar_hits(rect, bar) {
                return hits;
            }
        }

        // Tab labels/segments are chrome, painted with `ui_font` by
        // `gtk::draw_tab_bar_icons` (via `GtkBackend::draw_tab_bar_icons`,
        // which sets `ui_font` on the shared layout before calling in).
        // This no-paint twin must measure with the same font the paint
        // path uses, or its reported widths (and the icon-font it derives
        // from `base` below) drift from what's actually on screen —
        // restored to whatever was set before returning.
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let saved_font = pango_layout.as_ref().and_then(|pl| pl.font_description());
        if let Some(pl) = &pango_layout {
            pl.set_font_description(Some(&ui_font_desc));
        }

        // Icon reservation, measured with the same Nerd-Font swap
        // `gtk::draw_tab_bar_icons` paints with — the no-paint twin has to
        // reserve exactly what the paint does, or every click lands left
        // of the glyph the user sees. Measuring leaves the shared pango
        // layout on the icon font, so restore the caller's font before
        // the label / right-segment measurements below.
        let icon_extras: Vec<f32> = match &pango_layout {
            Some(pl) => {
                let base = pl.font_description().unwrap_or_default();
                let icon_font = crate::gtk::tab_bar::tab_icon_font(&base);
                let extras =
                    crate::gtk::tab_bar::tab_icon_extras(pl, &icon_font, bar.tabs.len(), icons);
                pl.set_font_description(Some(&base));
                extras.into_iter().map(|w| w as f32).collect()
            }
            // No pango handle (headless / pre-realise): mirror
            // `pango_str_width`'s own char-cell fallback so the two
            // estimates stay in the same units.
            None => (0..bar.tabs.len())
                .map(|i| match crate::tab_icon_at(icons, i) {
                    Some(icon) => {
                        (icon.glyph.chars().count() as f32 * char_w).ceil()
                            + 2.0
                            + crate::gtk::tab_bar::TAB_ICON_GAP as f32
                    }
                    None => 0.0,
                })
                .collect(),
        };

        let tab_pad: f32 = if bar.compact { 2.0 } else { 14.0 };
        let tab_inner_gap: f32 = if bar.compact { 4.0 } else { 10.0 };
        let tab_outer_gap: f32 = if bar.compact { 0.0 } else { 1.0 };

        let tab_name_widths: Vec<f32> = bar
            .tabs
            .iter()
            .map(|t| self.pango_str_width(&pango_layout, &t.label, char_w))
            .collect();

        // Single shared composition with `resolve_tab_bar_layout_icons` for close-button
        let measure = PangoTextMeasure {
            layout: &pango_layout,
            char_w,
        };
        let (layout, corrected_scroll_offset, available_cols) =
            crate::primitives::layout_metrics::pixel_tab_bar_layout(
                bar,
                rect.width,
                rect.height,
                tab_pad,
                tab_inner_gap,
                tab_outer_gap,
                &tab_name_widths,
                &icon_extras,
                &TabChrome::default(),
                &measure,
            );

        let mut hits = tab_bar_hits_from_layout(&layout, bar);
        // `TabBarHits` are target-surface coordinates; shift by rect.x to match.
        crate::backend::shift_tab_bar_hits(&mut hits, rect.x as f64);
        hits.correct_scroll_offset = corrected_scroll_offset;
        hits.available_cols = available_cols;

        if let Some(pl) = &pango_layout {
            pl.set_font_description(saved_font.as_ref());
        }

        hits
    }

    /// Counterpart to [`Self::tab_bar_layout_icons`] that returns [`TabBarLayout`] instead.
    fn resolve_tab_bar_layout_icons(
        &self,
        rect: QRect,
        bar: &TabBar,
        icons: &[Option<crate::TabIcon>],
    ) -> TabBarLayout {
        let char_w = self.current_char_width as f32;
        let frame_layout = self.current_frame_refs().map(|(_, l)| l.clone());
        let pango_layout = frame_layout.or_else(|| self.pango_ctx.as_ref().map(pango::Layout::new));

        if pango_layout.is_none() {
            if let Some(layout) = self.cached_tab_bar_layout_matching(rect, bar) {
                return layout;
            }
        }

        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let saved_font = pango_layout.as_ref().and_then(|pl| pl.font_description());
        if let Some(pl) = &pango_layout {
            pl.set_font_description(Some(&ui_font_desc));
        }

        let icon_extras: Vec<f32> = match &pango_layout {
            Some(pl) => {
                let base = pl.font_description().unwrap_or_default();
                let icon_font = crate::gtk::tab_bar::tab_icon_font(&base);
                let extras =
                    crate::gtk::tab_bar::tab_icon_extras(pl, &icon_font, bar.tabs.len(), icons);
                pl.set_font_description(Some(&base));
                extras.into_iter().map(|w| w as f32).collect()
            }
            None => (0..bar.tabs.len())
                .map(|i| match crate::tab_icon_at(icons, i) {
                    Some(icon) => {
                        (icon.glyph.chars().count() as f32 * char_w).ceil()
                            + 2.0
                            + crate::gtk::tab_bar::TAB_ICON_GAP as f32
                    }
                    None => 0.0,
                })
                .collect(),
        };

        let tab_pad: f32 = if bar.compact { 2.0 } else { 14.0 };
        let tab_inner_gap: f32 = if bar.compact { 4.0 } else { 10.0 };
        let tab_outer_gap: f32 = if bar.compact { 0.0 } else { 1.0 };

        let tab_name_widths: Vec<f32> = bar
            .tabs
            .iter()
            .map(|t| self.pango_str_width(&pango_layout, &t.label, char_w))
            .collect();

        // Single shared composition with `tab_bar_layout_icons` for close-button
        let measure = PangoTextMeasure {
            layout: &pango_layout,
            char_w,
        };
        let (layout, _corrected_scroll_offset, _available_cols) =
            crate::primitives::layout_metrics::pixel_tab_bar_layout(
                bar,
                rect.width,
                rect.height,
                tab_pad,
                tab_inner_gap,
                tab_outer_gap,
                &tab_name_widths,
                &icon_extras,
                &TabChrome::default(),
                &measure,
            );

        if let Some(pl) = &pango_layout {
            pl.set_font_description(saved_font.as_ref());
        }

        layout
    }

    #[allow(deprecated)] // returns the deprecated `TabBarHits` — issue #823
    fn tab_bar_layout_with_chrome(
        &self,
        rect: QRect,
        bar: &TabBar,
        chrome: &TabChrome,
    ) -> crate::TabBarHits {
        let char_w = self.current_char_width as f32;
        let frame_layout = self.current_frame_refs().map(|(_, l)| l.clone());
        let pango_layout = frame_layout.or_else(|| self.pango_ctx.as_ref().map(pango::Layout::new));

        // See `tab_bar_layout_icons` for why a missing Pango handle falls
        // back to the most recent paint's cached geometry rather than a
        // char-cell guess that would disagree with the bracket glyphs'
        // actual measured width.
        if pango_layout.is_none() {
            if let Some(hits) = self.cached_tab_bar_hits(rect, bar) {
                return hits;
            }
        }

        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let saved_font = pango_layout.as_ref().and_then(|pl| pl.font_description());
        if let Some(pl) = &pango_layout {
            pl.set_font_description(Some(&ui_font_desc));
        }

        let tab_pad: f32 = if bar.compact { 2.0 } else { 14.0 };
        let tab_inner_gap: f32 = if bar.compact { 4.0 } else { 10.0 };
        let tab_outer_gap: f32 = if bar.compact { 0.0 } else { 1.0 };

        let tab_name_widths: Vec<f32> = bar
            .tabs
            .iter()
            .map(|t| self.pango_str_width(&pango_layout, &t.label, char_w))
            .collect();
        // No icon sidecar on this path: zero-width icon reservation per tab.
        let icon_extras = vec![0.0_f32; bar.tabs.len()];

        // Single shared composition with `resolve_tab_bar_layout_with_chrome`.
        let measure = PangoTextMeasure {
            layout: &pango_layout,
            char_w,
        };
        let (layout, corrected_scroll_offset, available_cols) =
            crate::primitives::layout_metrics::pixel_tab_bar_layout(
                bar,
                rect.width,
                rect.height,
                tab_pad,
                tab_inner_gap,
                tab_outer_gap,
                &tab_name_widths,
                &icon_extras,
                chrome,
                &measure,
            );

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

        if let Some(pl) = &pango_layout {
            pl.set_font_description(saved_font.as_ref());
        }

        hits
    }

    /// Counterpart to [`Self::tab_bar_layout_with_chrome`] that returns [`TabBarLayout`] instead.
    fn resolve_tab_bar_layout_with_chrome(
        &self,
        rect: QRect,
        bar: &TabBar,
        chrome: &TabChrome,
    ) -> TabBarLayout {
        let char_w = self.current_char_width as f32;
        let frame_layout = self.current_frame_refs().map(|(_, l)| l.clone());
        let pango_layout = frame_layout.or_else(|| self.pango_ctx.as_ref().map(pango::Layout::new));

        if pango_layout.is_none() {
            if let Some(layout) = self.cached_tab_bar_layout_matching(rect, bar) {
                return layout;
            }
        }

        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let saved_font = pango_layout.as_ref().and_then(|pl| pl.font_description());
        if let Some(pl) = &pango_layout {
            pl.set_font_description(Some(&ui_font_desc));
        }

        let tab_pad: f32 = if bar.compact { 2.0 } else { 14.0 };
        let tab_inner_gap: f32 = if bar.compact { 4.0 } else { 10.0 };
        let tab_outer_gap: f32 = if bar.compact { 0.0 } else { 1.0 };

        let tab_name_widths: Vec<f32> = bar
            .tabs
            .iter()
            .map(|t| self.pango_str_width(&pango_layout, &t.label, char_w))
            .collect();
        let icon_extras = vec![0.0_f32; bar.tabs.len()];

        let measure = PangoTextMeasure {
            layout: &pango_layout,
            char_w,
        };
        let (layout, _corrected_scroll_offset, _available_cols) =
            crate::primitives::layout_metrics::pixel_tab_bar_layout(
                bar,
                rect.width,
                rect.height,
                tab_pad,
                tab_inner_gap,
                tab_outer_gap,
                &tab_name_widths,
                &icon_extras,
                chrome,
                &measure,
            );

        if let Some(pl) = &pango_layout {
            pl.set_font_description(saved_font.as_ref());
        }

        layout
    }

    fn activity_bar_layout(&self, rect: QRect, bar: &ActivityBar) -> Vec<crate::ActivityBarRowHit> {
        activity_bar_hits(rect, bar, crate::gtk::ACTIVITY_ROW_PX as f32)
    }

    fn draw_terminal(&mut self, rect: QRect, term: &TerminalPrim) {
        let lh = self.current_line_height;
        let cw = self.current_char_width;
        let theme = self.current_theme;

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

        // Dirty-row fast path. Reuse the previous frame's cache
        // entry for this terminal id only when every geometry input that
        // affects row alignment is unchanged, the theme hasn't changed
        // (a same-content row can still need repainting if a
        // `selected`/`is_cursor`/`is_find_match` overlay's colour moved),
        // *and* nothing else could have painted over these pixels since —
        // see `TermPaintCache`'s docs for what each guard rules out.
        // `dirty_rows` then comes back `Some(rows)` (paint only `rows`,
        // possibly empty) or `None` (row counts differ — full repaint).
        let modal_empty_now = self.modal_stack.borrow().is_empty();
        let frame_now = self.frame_counter;
        // Direct `==` on the `f64`/`Theme` fields below is safe only
        // because each is deterministically *recomputed* every frame
        // (from layout/font metrics or `set_theme`'s argument), never
        // accumulated. A future refactor that turns any of them into a
        // running sum would silently defeat the fast path (forcing extra
        // full repaints) rather than corrupt output — but it would no
        // longer be safe to compare this way.
        let dirty_rows: Option<Vec<usize>> =
            self.term_paint_cache.get(&term.id).and_then(|cached| {
                if cached.rect == rect
                    && cached.line_height == lh
                    && cached.char_width == cw
                    && cached.cell_area_w == cell_area_w
                    && cached.painted_frame.wrapping_add(1) == frame_now
                    && cached.modal_was_empty
                    && modal_empty_now
                    && cached.theme == theme
                {
                    term.dirty_rows(&cached.term)
                } else {
                    None
                }
            });

        match &dirty_rows {
            Some(rows) => {
                // Fast path: geometry is unchanged (checked above), so
                // there's no newly-exposed area needing the full-pane
                // clear below, and rows outside `rows` are assumed
                // already correct on GTK's persistent render surface —
                // skip them (and, when `rows` is empty, skip painting
                // entirely — e.g. a cursor-blink tick with no new PTY
                // output).
                if !rows.is_empty() {
                    // The terminal is editor-class — paint through
                    // `EditorSurface` so its cell glyphs keep painting
                    // in the editor font even though `GtkBackend`'s own
                    // `PaintSurface` impl now defaults to `ui_font` (see
                    // that impl's doc).
                    let mut surface = EditorSurface { backend: self };
                    crate::primitives::terminal::paint(
                        term,
                        &mut surface,
                        &theme,
                        rect.x,
                        rect.y,
                        cell_area_w as f32,
                        rect.height,
                        lh as f32,
                        cw as f32,
                        Some(rows),
                    );
                }
            }
            None => {
                // Clear the entire terminal pane to the terminal background before
                // painting cells. `primitives::terminal::paint` only
                // fills each *live* cell's own background, so without this any pixel
                // the current grid doesn't cover — a sub-cell sliver, the strip below
                // the last row, or (critically) a region GTK didn't re-clear on an
                // interactive-resize frame where the widget's cached render node is
                // partially reused — keeps showing glyphs from the pre-resize frame.
                // That was the "stale ~ / > prompt fragments stuck on rows that
                // should be blank after a shrink-then-expand" ghosting. vimcode's
                // bespoke renderer does the same full-pane fill first; the trait doc
                // on `primitives::terminal::paint` delegates this to the caller, and
                // the GTK backend is that caller. Filling with `theme.background`
                // rather than a hardcoded `rgb(30, 30, 30)` keeps
                // this blank-area fill consistent with whatever palette the app
                // built — a light theme no longer shows a dark terminal pane
                // through every uncovered pixel.
                self.surface_fill_rect(rect, theme.background);

                // See the matching comment on the fast-path call above
                // — the terminal needs `EditorSurface`, not bare
                // `self`.
                let mut surface = EditorSurface { backend: self };
                crate::primitives::terminal::paint(
                    term,
                    &mut surface,
                    &theme,
                    rect.x,
                    rect.y,
                    cell_area_w as f32,
                    rect.height,
                    lh as f32,
                    cw as f32,
                    None,
                );
            }
        }

        if let Some(ref sb_state) = term.scrollbar {
            let sb = crate::primitives::scrollbar::Scrollbar::vertical(
                term.id,
                crate::event::Rect::new(
                    rect.x + cell_area_w as f32,
                    rect.y,
                    sb_width as f32,
                    rect.height,
                ),
                sb_state.effective_scroll_offset() as f32,
                sb_state.total_lines as f32,
                sb_state.visible_lines as f32,
                lh as f32,
            );
            crate::primitives::scrollbar::native_surface_paint::paint(&sb, self, &theme);
        }

        // Terminal cell glyphs now reach painted-text tracking via
        // `surface_draw_text_run_styled`, closing the gap that existed before
        // `primitives::terminal::paint` unified all backend implementations.
        self.register_zone(term.id, rect);

        // Remember this frame's snapshot and geometry so the next
        // `draw_terminal` call for this id can attempt the fast path.
        self.term_paint_cache.insert(
            term.id,
            TermPaintCache {
                term: term.clone(),
                rect,
                line_height: lh,
                char_width: cw,
                cell_area_w,
                painted_frame: frame_now,
                modal_was_empty: modal_empty_now,
                theme,
            },
        );
    }

    /// Shared divider painting lives in
    /// [`crate::primitives::terminal::paint_divider`] now.
    fn draw_terminal_divider(&mut self, rect: QRect) {
        let theme = self.current_theme;
        crate::primitives::terminal::paint_divider(self, rect.x, rect.y, rect.height, &theme);
        // The primitive takes no `WidgetId` of its own (there is at
        // most one divider on screen at a time), so register a fixed
        // chrome id — on a pixel backend this paints strokes only, so
        // without a zone the frame is indistinguishable from one where
        // the no-op trait default silently dropped the call (C0 paint
        // smoke, contract §5b).
        self.register_zone(WidgetId::new("chrome:terminal-divider"), rect);
    }

    /// A pixel backend can honor `rect` exactly, unlike the old
    /// per-row `StatusBar` hack this replaces — see
    /// `Backend::draw_solid_fill`'s doc for why that hack produced a
    /// dashed divider here specifically.
    fn draw_solid_fill(&mut self, rect: QRect, color: Color) {
        self.surface_fill_rect(rect, color);
        // Chrome-only paint (no text of its own) — see
        // `TuiBackend::draw_solid_fill`'s identical registration for why.
        self.register_zone(WidgetId::new("chrome:solid-fill"), rect);
    }

    /// Shared text-display painting lives in
    /// [`crate::primitives::text_display::paint`] now — see that fn's
    /// doc for the divergence (Windows's bold-span support) resolved
    /// while unifying `gtk::text_display::draw_text_display`,
    /// `macos::text_display::draw_text_display` and
    /// `win::text_display::draw_text_display` into one implementation.
    fn draw_text_display(&mut self, rect: QRect, td: &TextDisplay) {
        let theme = self.current_theme;
        let line_height = self.current_line_height as f32;
        let char_width = self.current_char_width as f32;
        // The text display is editor-class — see the matching comment
        // on `Self::draw_terminal` / `EditorSurface`'s own doc.
        let mut surface = EditorSurface { backend: self };
        crate::primitives::text_display::paint(
            td,
            rect,
            &mut surface,
            &theme,
            line_height,
            char_width,
        );
    }

    fn draw_command_line(&mut self, rect: QRect, cmd: &CommandLine) {
        let (cr, layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_command_line called outside enter_frame_scope");
        crate::gtk::command_line::draw_command_line(
            cr,
            layout,
            cmd,
            &self.current_theme,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            self.current_line_height,
            self.current_char_width as f32,
        );
    }

    fn draw_command_line_selection(
        &mut self,
        rect: QRect,
        cmd: &CommandLine,
        selection: Option<(usize, usize)>,
    ) {
        let (cr, layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_command_line_selection called outside enter_frame_scope");
        crate::gtk::command_line::draw_command_line_selection(
            cr,
            layout,
            cmd,
            &self.current_theme,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            self.current_line_height,
            self.current_char_width as f32,
            selection,
        );
    }

    fn command_line_layout(
        &self,
        rect: QRect,
        cmd: &CommandLine,
    ) -> crate::primitives::command_line::CommandLineLayout {
        crate::gtk::command_line::gtk_command_line_layout(
            cmd,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            self.current_line_height,
            self.current_char_width as f32,
        )
    }

    fn text_display_layout(
        &self,
        rect: QRect,
        td: &TextDisplay,
    ) -> crate::primitives::text_display::TextDisplayLayout {
        crate::gtk::gtk_text_display_layout(
            td,
            rect,
            self.current_line_height,
            self.current_char_width,
        )
    }

    fn draw_text_input(
        &mut self,
        rect: QRect,
        ti: &crate::primitives::text_input::TextInput,
    ) -> crate::primitives::text_input::TextInputLayout {
        let theme = self.current_theme;
        let lh = self.current_line_height;
        let cw = self.current_char_width;
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, pango_layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_text_input called outside enter_frame_scope");
        // `TextInput` is chrome (not in
        // `crate::font_role::EditorClassPrimitive::ALL`) — same
        // save/swap/restore as `Self::draw_tree`, since
        // `crate::gtk::draw_text_input` paints directly against whatever
        // font `pango_layout` carries in rather than going through
        // `PaintSurface`.
        let saved_font = pango_layout.font_description();
        pango_layout.set_font_description(Some(&ui_font_desc));
        let result = crate::gtk::draw_text_input(cr, pango_layout, rect, ti, &theme, lh, cw);
        pango_layout.set_font_description(saved_font.as_ref());
        result
    }

    fn text_input_layout(
        &self,
        rect: QRect,
        ti: &crate::primitives::text_input::TextInput,
    ) -> crate::primitives::text_input::TextInputLayout {
        crate::gtk::gtk_text_input_layout(
            ti,
            rect,
            self.current_line_height as f32,
            self.current_char_width as f32,
        )
    }

    fn draw_number_input(
        &mut self,
        number_input: &crate::primitives::number_input::NumberInput,
        layout: &crate::primitives::number_input::NumberInputLayout,
    ) {
        // `NumberInput`'s stepper glyphs and field text are chrome, not
        // editor content — `self`'s own `PaintSurface::surface_draw_text_run`
        // already forces `ui_font`, same as `Self::draw_panel` /
        // `Self::draw_scrollbar`'s unwrapped-`self` shape, so no explicit
        // font save/swap/restore is needed here.
        let theme = self.current_theme;
        crate::primitives::number_input::native_surface_paint::paint(
            number_input,
            layout,
            self,
            &theme,
        );
        self.register_zone(number_input.id, layout.bounds);
    }

    fn draw_combo_box(
        &mut self,
        combo_box: &crate::primitives::combo_box::ComboBox,
        layout: &crate::primitives::combo_box::ComboBoxLayout,
    ) {
        // Same unwrapped-`self` shape as `Self::draw_number_input` above —
        // field and dropdown-row labels are chrome text.
        let theme = self.current_theme;
        crate::primitives::combo_box::native_surface_paint::paint(combo_box, layout, self, &theme);
        self.register_zone(combo_box.id, layout.field_bounds);
    }

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

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

    fn draw_tooltip_with_chrome(
        &mut self,
        tooltip: &crate::Tooltip,
        layout_arg: &crate::TooltipLayout,
        chrome: &crate::TooltipChrome,
    ) {
        let style = self.style();
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, pango_layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_tooltip called outside enter_frame_scope");
        // Tooltip text is chrome, not editor content — save the editor
        // font on the shared layout, paint in `ui_font`, then restore,
        // matching `Self::draw_tree`'s save/swap/restore.
        let saved_font = pango_layout.font_description();
        pango_layout.set_font_description(Some(&ui_font_desc));
        // Calls the shared paint directly (rather than through
        // `crate::gtk::draw_tooltip_with_chrome`, whose public signature
        // stays additive-only and so cannot take a live `&Style`) so
        // this live backend path honours `Self::set_style` overrides —
        // see `crate::gtk::draw_tooltip_with_chrome`'s own doc.
        let mut surface = crate::gtk::surface::CairoSurface {
            cr,
            layout: Some(pango_layout),
            translucent_fill: true,
        };
        crate::primitives::tooltip::native_surface_paint::paint(
            tooltip,
            layout_arg,
            chrome,
            self.current_line_height as f32,
            self.current_char_width as f32,
            &mut surface,
            &self.current_theme,
            &style,
        );
        pango_layout.set_attributes(None);
        pango_layout.set_font_description(saved_font.as_ref());
        // Register the tooltip's own surface — see the matching
        // comment on `TuiBackend::draw_tooltip`. GTK already painted a
        // full 4-sided box here before TUI did; this just makes
        // that box observable to a structural-parity assertion.
        self.register_zone(tooltip.id, layout_arg.bounds);
    }

    fn draw_context_menu(
        &mut self,
        menu: &crate::ContextMenu,
        layout_arg: &crate::ContextMenuLayout,
    ) -> Vec<(QRect, crate::WidgetId)> {
        // See draw_palette for why this happens before the frame borrow.
        self.modal_stack.borrow_mut().mark_painted(&menu.id);
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, pango_layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_context_menu called outside enter_frame_scope");
        // Dropdown items are chrome, not editor content — save/swap/restore like
        // `Self::draw_menu_bar`, so the bar and dropdown agree within a single frame.
        // Calls the shared paint directly so this live backend path honours
        // `Self::set_style` overrides.
        let saved_font = pango_layout.font_description();
        pango_layout.set_font_description(Some(&ui_font_desc));
        // Calls the shared paint directly (rather than through
        // `crate::gtk::draw_context_menu`, whose public signature stays
        // additive-only and so cannot take a live `&Style`) so this live
        // backend path honours `Self::set_style` overrides.
        let style = self.style();
        let mut surface = crate::gtk::surface::CairoSurface {
            cr,
            layout: Some(pango_layout),
            translucent_fill: true,
        };
        let hits = crate::primitives::context_menu::native_surface_paint::paint(
            menu,
            layout_arg,
            crate::accelerator::Platform::Linux,
            &mut surface,
            &self.current_theme,
            &style,
        );
        pango_layout.set_attributes(None);
        pango_layout.set_font_description(saved_font.as_ref());
        hits
    }

    /// [`Self::draw_context_menu`] plus an optional
    /// [`crate::primitives::context_menu::ContextMenuGlyphs`] override for
    /// the checked-item check mark and submenu pull-right arrow, honoured
    /// in full here (unlike the trait default, which ignores `glyphs`).
    fn draw_context_menu_with_glyphs(
        &mut self,
        menu: &crate::ContextMenu,
        layout_arg: &crate::ContextMenuLayout,
        glyphs: Option<&crate::primitives::context_menu::ContextMenuGlyphs>,
    ) -> Vec<(QRect, crate::WidgetId)> {
        // See draw_palette for why this happens before the frame borrow.
        self.modal_stack.borrow_mut().mark_painted(&menu.id);
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, pango_layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_context_menu_with_glyphs called outside enter_frame_scope");
        let saved_font = pango_layout.font_description();
        pango_layout.set_font_description(Some(&ui_font_desc));
        // Calls the shared paint directly (rather than through
        // `crate::gtk::draw_context_menu`, whose public signature stays
        // additive-only and so cannot take a live `&Style`) so this live
        // backend path honours `Self::set_style` overrides.
        let style = self.style();
        let nerd_fonts_enabled = self.nerd_fonts_enabled;
        let mut surface = crate::gtk::surface::CairoSurface {
            cr,
            layout: Some(pango_layout),
            translucent_fill: true,
        };
        let hits = crate::primitives::context_menu::native_surface_paint::paint_with_glyphs(
            menu,
            layout_arg,
            crate::accelerator::Platform::Linux,
            &mut surface,
            &self.current_theme,
            &style,
            glyphs,
            nerd_fonts_enabled,
        );
        pango_layout.set_attributes(None);
        pango_layout.set_font_description(saved_font.as_ref());
        hits
    }

    fn draw_dialog(
        &mut self,
        dialog: &crate::Dialog,
        dialog_layout: &crate::DialogLayout,
    ) -> Vec<QRect> {
        // See draw_palette for why this happens before the frame borrow.
        self.modal_stack.borrow_mut().mark_painted(&dialog.id);
        let line_height = self.current_line_height;
        let theme = self.current_theme;
        let style = self.style();
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, pango_layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_dialog called outside enter_frame_scope");
        // Calls the shared paint directly (rather than through
        // `crate::gtk::draw_dialog`, whose public signature stays
        // additive-only and so cannot take a live `&Style`) so this live
        // backend path honours `Self::set_style` overrides — the
        // font-swap/toolbar-sub-paint/restore steps below mirror that
        // free function's own body exactly.
        let saved_font = pango_layout.font_description();
        pango_layout.set_font_description(Some(&ui_font_desc));
        let mut surface = crate::gtk::surface::CairoSurface {
            cr,
            layout: Some(pango_layout),
            translucent_fill: true,
        };
        let rects = crate::primitives::dialog::native_surface_paint::paint(
            dialog,
            dialog_layout,
            line_height as f32,
            &mut surface,
            &theme,
            &style,
        );
        if let (Some(input_b), Some(crate::primitives::dialog::DialogInput::Toolbar(toolbar))) =
            (dialog_layout.input_bounds, dialog.input.as_ref())
        {
            crate::gtk::toolbar::draw_toolbar(
                cr,
                pango_layout,
                input_b.x as f64,
                input_b.y as f64,
                input_b.width as f64,
                input_b.height as f64,
                toolbar,
                &theme,
                None,
                None,
            );
        }
        pango_layout.set_attributes(None);
        pango_layout.set_font_description(saved_font.as_ref());
        rects
    }

    fn draw_float(
        &mut self,
        float: &crate::primitives::float::Float,
        layout: &crate::primitives::float::FloatLayout,
    ) {
        // See draw_palette for why this happens before the frame borrow.
        self.modal_stack.borrow_mut().mark_painted(&float.id);
        let theme = self.current_theme;
        crate::primitives::float::native_surface_paint::paint(float, layout, self, &theme);
        // Same convention `draw_scrollbar` uses for a chrome-only
        // primitive with no painted text of its own: register the
        // float's own bounds under its id so it's inventory-observable.
        self.register_zone(float.id, layout.bounds);
    }

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

    fn draw_multi_section_view(
        &mut self,
        rect: QRect,
        view: &crate::primitives::multi_section_view::MultiSectionView,
    ) {
        let line_height = self.current_line_height;
        let theme = self.current_theme;
        let nerd_fonts = self.nerd_fonts_enabled;
        let caret_visible = self.caret_visible();
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_multi_section_view called outside enter_frame_scope");
        // Section headers and `Tree`/`List` body rows (icon glyphs
        // included) are sidebar chrome, not editor content — same
        // save/swap/restore `Self::draw_tree`/`Self::draw_list` use.
        // `SectionBody::Terminal`/`Custom` are host-painted no-ops here
        // (see `gtk::draw_multi_section_view`'s own body dispatch), so
        // they're unaffected by the swap.
        let saved_font = layout.font_description();
        layout.set_font_description(Some(&ui_font_desc));
        crate::gtk::draw_multi_section_view(
            cr,
            layout,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
            view,
            &theme,
            line_height,
            nerd_fonts,
            caret_visible,
        );
        layout.set_font_description(saved_font.as_ref());
    }

    fn msv_layout(
        &self,
        rect: QRect,
        view: &crate::primitives::multi_section_view::MultiSectionView,
    ) -> crate::primitives::multi_section_view::MultiSectionViewLayout {
        crate::gtk::gtk_msv_layout(view, rect, self.current_line_height)
    }

    fn msv_metrics(&self) -> crate::primitives::multi_section_view::MsvLayoutMetrics {
        crate::gtk::multi_section_view::metrics_for(self.current_line_height, false)
    }

    /// Mirrors [`Self::form_layout`]'s pattern: measures the chevron
    /// glyph actually configured on `tree.style` through a real Pango
    /// layout (via [`Self::chrome_measure_layout`]) instead of
    /// `gtk_tree_layout`'s `line_height * 0.65` estimate, so a caller
    /// hit-testing outside a paint frame agrees with what
    /// `Self::draw_tree` paints.
    fn tree_layout(&self, rect: QRect, tree: &TreeView) -> crate::primitives::tree::TreeViewLayout {
        let char_w = self.current_char_width;
        let pango_layout = self.chrome_measure_layout();
        crate::gtk::gtk_tree_layout_measured(
            tree,
            rect,
            self.current_line_height,
            pango_layout.as_ref(),
            char_w,
        )
    }

    fn tree_vscrollbar(&self, rect: QRect, tree: &TreeView) -> Option<crate::Scrollbar> {
        // GTK tree vertical-scrollbar rasteriser not yet implemented.
        // Delegate to the primitive's geometry method, but using the same
        // per-row pitch `Self::tree_layout` (via `layout_metrics::tree_layout`)
        // actually paints — not the raw `line_height`. Unlike `ListView`
        // (whose items really are `line_height` tall, see
        // `GtkBackend::list_vscrollbar`), `TreeView` rows pitch at
        // `line_height * 1.4` (or `TreeStyle::row_height`); see
        // `layout_metrics::tree_row_pitch`'s doc.
        let row_h =
            crate::primitives::layout_metrics::tree_row_pitch(tree, self.current_line_height);
        tree.vscrollbar_with_track_width(
            rect,
            row_h as f32,
            crate::primitives::layout_metrics::pixel::TREE_VSCROLLBAR_WIDTH,
        )
    }

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

    /// Delegates to [`crate::primitives::layout_metrics::form_field_measure`]
    /// — the shared measurer that `macos::form::mac_form_layout` and
    /// `win::form::win_form_layout` already use. Measures one row per field,
    /// matching what GTK paints.
    fn form_layout(&self, rect: QRect, form: &Form) -> crate::primitives::form::FormLayout {
        let row_h = crate::primitives::layout_metrics::form_row_height(self.current_line_height);
        let char_w = self.current_char_width as f32;
        let pango_layout = self.chrome_measure_layout();
        let measure = PangoTextMeasure {
            layout: &pango_layout,
            char_w,
        };

        form.layout(rect.width, rect.height, |i| {
            crate::primitives::layout_metrics::form_field_measure(&form.fields[i], row_h, &measure)
        })
    }

    fn draw_editor(
        &mut self,
        rect: QRect,
        editor: &crate::primitives::editor::Editor,
    ) -> crate::backend::EditorPaintResult {
        let line_height = self.current_line_height;
        let char_width = self.current_char_width;
        let theme = self.current_theme;
        let (cr, pango_layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_editor called outside enter_frame_scope");
        // GTK draw_editor needs FontMetrics; resolve from the layout's
        // font description. The TUI return type carries a TUI-specific
        // cursor cell — GTK paints its own caret, so we return the
        // default. Future GTK refinement can populate fields if hosts
        // need GTK-side cursor pixel coordinates.
        let pango_ctx = pango_layout.context();
        let font_desc = pango_layout
            .font_description()
            .or_else(|| pango_ctx.font_description());
        let metrics = pango_ctx.metrics(font_desc.as_ref(), None);
        super::editor::draw_editor_with_options_and_v_scrollbar_w(
            cr,
            pango_layout,
            &metrics,
            editor,
            &theme,
            char_width,
            line_height,
            crate::primitives::editor::EditorPaintOptions::default(),
            self.editor_v_scrollbar_w,
        );
        // Stash the exact layout just painted with — see the field doc
        // on `last_editor_pango_layout` for why this is necessary
        // rather than relying on `current_frame_refs()` alone.
        self.last_editor_pango_layout = Some(pango_layout.clone());
        let _ = rect;
        crate::backend::EditorPaintResult::default()
    }

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

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

    fn editor_col_at_x(
        &self,
        layout: &crate::primitives::editor::EditorLayout,
        editor: &crate::primitives::editor::Editor,
        view_row: usize,
        x: f32,
    ) -> usize {
        let Some(line) = editor.lines.get(view_row) else {
            return layout.col_at_x(editor, view_row, x);
        };
        let frame_layout = self.current_frame_refs().map(|(_, l)| l.clone());
        let pango_layout = frame_layout
            .or_else(|| self.last_editor_pango_layout.clone())
            // Applies the live editor font, so clicks resolve against the correct
            // glyph widths even when no editor frame has been painted yet.
            .or_else(|| self.editor_pango_layout());
        let Some(pango_layout) = pango_layout else {
            return layout.col_at_x(editor, view_row, x);
        };
        crate::gtk::editor_col_at_x(&pango_layout, line, layout, x)
    }

    fn draw_message_list(
        &mut self,
        rect: QRect,
        list: &crate::primitives::message_list::MessageList,
    ) {
        let line_height = self.current_line_height;
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, pango_layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_message_list called outside enter_frame_scope");
        // MessageList rows are chrome, not editor content — save the
        // editor font on the shared layout, paint in `ui_font`, then
        // restore, matching `Self::draw_tree`'s save/swap/restore.
        let saved_font = pango_layout.font_description();
        pango_layout.set_font_description(Some(&ui_font_desc));
        crate::gtk::draw_message_list(
            cr,
            pango_layout,
            list,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            (rect.y + rect.height) as f64,
            line_height,
        );
        pango_layout.set_font_description(saved_font.as_ref());
    }

    fn draw_rich_text_popup(
        &mut self,
        popup: &crate::primitives::rich_text_popup::RichTextPopup,
        layout_arg: &crate::primitives::rich_text_popup::RichTextPopupLayout,
    ) {
        let theme = self.current_theme;
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, pango_layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_rich_text_popup called outside enter_frame_scope");
        // GTK rasteriser returns link bounds; for trait parity we
        // discard them. Hosts that need link hit-testing query the
        // primitive's own `popup.layout(...).hit_test(...)` API.
        let _ = crate::gtk::draw_rich_text_popup(
            cr,
            pango_layout,
            &ui_font_desc,
            popup,
            layout_arg,
            &theme,
        );
    }

    fn draw_rich_text_popup_with_font_role(
        &mut self,
        popup: &crate::primitives::rich_text_popup::RichTextPopup,
        layout_arg: &crate::primitives::rich_text_popup::RichTextPopupLayout,
        role: crate::FontRole,
    ) {
        // `role` picks which live font this call paints
        // the popup's content in — `FontRole::Chrome` keeps `ui_font`
        // (same as plain `draw_rich_text_popup`); `FontRole::Editor`
        // swaps in the editor's own Pango description, the same
        // resolution `Self::measure_text`/
        // `Self::surface_draw_text_run_with_role` already use per role.
        if role == crate::FontRole::Chrome {
            self.draw_rich_text_popup(popup, layout_arg);
            return;
        }
        let theme = self.current_theme;
        let font_desc = pango::FontDescription::from_string(&self.editor_font_pango_string());
        let (cr, pango_layout) = self.current_frame_refs().expect(
            "GtkBackend::draw_rich_text_popup_with_font_role called outside enter_frame_scope",
        );
        let _ = crate::gtk::draw_rich_text_popup(
            cr,
            pango_layout,
            &font_desc,
            popup,
            layout_arg,
            &theme,
        );
    }

    fn draw_find_replace(
        &mut self,
        rect: QRect,
        panel: &crate::primitives::find_replace::FindReplacePanel,
    ) {
        let theme = self.current_theme;
        debug_assert!(
            self.current_frame_refs().is_some(),
            "GtkBackend::draw_find_replace called outside enter_frame_scope",
        );
        // The panel positions itself via its own anchor logic (see
        // `primitives::find_replace::paint`); `rect` is currently
        // unused (forward-compat for a host-resolved layout per
        // BACKEND_TRAIT_PROPOSAL §6.2).
        let _ = rect;
        crate::primitives::find_replace::paint(panel, self, &theme);
    }

    fn draw_completions(
        &mut self,
        completions: &crate::primitives::completions::Completions,
        layout_arg: &crate::primitives::completions::CompletionsLayout,
    ) {
        let theme = self.current_theme;
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, pango_layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_completions called outside enter_frame_scope");
        // The completions popup is chrome, not editor content — same
        // save/swap/restore as `Self::draw_tree`, since
        // `crate::gtk::draw_completions` paints directly against
        // whatever font `pango_layout` carries in rather than going
        // through `PaintSurface`.
        let saved_font = pango_layout.font_description();
        pango_layout.set_font_description(Some(&ui_font_desc));
        crate::gtk::draw_completions(cr, pango_layout, completions, layout_arg, &theme);
        pango_layout.set_font_description(saved_font.as_ref());
    }

    fn draw_scrollbar(
        &mut self,
        _rect: QRect,
        scrollbar: &crate::primitives::scrollbar::Scrollbar,
    ) {
        let theme = self.current_theme;
        crate::primitives::scrollbar::native_surface_paint::paint(scrollbar, self, &theme);
        // A scrollbar strokes/fills only — no text — so on this
        // pixel backend it would otherwise be indistinguishable from the
        // no-op default. Register the primitive's own id at its own
        // track bounds (not `_rect`, which the primitive ignores).
        self.register_zone(scrollbar.id, scrollbar.track);
    }

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

    fn draw_menu_bar(
        &mut self,
        rect: QRect,
        bar: &MenuBar,
    ) -> crate::primitives::menu_bar::MenuBarLayout {
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_menu_bar called outside enter_frame_scope");
        // Menu bar item labels are chrome — save the editor font on the shared
        // layout, paint in `ui_font`, then restore. The `layout.clone()` stashed
        // below no longer carries `ui_font` by the time it's read back out.
        let saved_font = layout.font_description();
        layout.set_font_description(Some(&ui_font_desc));
        let result = crate::gtk::draw_menu_bar(
            cr,
            layout,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
            bar,
            &self.current_theme,
        );
        layout.set_font_description(saved_font.as_ref());
        // Stash the exact layout just painted with — see the field doc
        // on `last_menu_bar_pango_layout` for why this is necessary
        // rather than relying on `current_frame_refs()` alone.
        let painted_layout = layout.clone();
        self.last_menu_bar_pango_layout = Some(painted_layout);
        result
    }

    fn menu_bar_layout(
        &self,
        rect: QRect,
        bar: &MenuBar,
    ) -> crate::primitives::menu_bar::MenuBarLayout {
        let bounds = crate::event::Rect::new(rect.x, rect.y, rect.width, rect.height);
        let char_w = self.current_char_width as f32;
        let frame_layout = self.current_frame_refs().map(|(_, l)| l.clone());
        // Click-time hit-testing (e.g. `MenuSystem::handle`) calls this
        // outside any `enter_frame_scope`, so `frame_layout` is always
        // `None` then. Prefer the layout `draw_menu_bar` last painted
        // with (same font/size as what's on screen) over the
        // widget-init `pango_ctx`, which can carry a different font —
        // see `last_menu_bar_pango_layout`'s doc comment.
        let pango_layout = frame_layout
            .or_else(|| self.last_menu_bar_pango_layout.clone())
            .or_else(|| self.pango_ctx.as_ref().map(pango::Layout::new));
        // Menu items are chrome, measured in `ui_font` to match
        // `draw_menu_bar`'s paint font. Forced explicitly rather than
        // trusted from whichever layout object was resolved above —
        // `last_menu_bar_pango_layout` is a GObject alias of the shared
        // frame layout, so by the time this runs (possibly a later frame,
        // click-time-only) its *current* font state, not a snapshot from
        // when it was cached, is whatever the most recent draw call left
        // it as.
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let saved_font = pango_layout.as_ref().and_then(|pl| pl.font_description());
        if let Some(pl) = &pango_layout {
            pl.set_font_description(Some(&ui_font_desc));
        }
        let result = bar.layout(bounds, |i| {
            let text: String = bar.items[i].label.chars().filter(|&c| c != '&').collect();
            let text_w = self.pango_str_width(&pango_layout, &text, char_w);
            crate::primitives::menu_bar::MenuBarItemMeasure::new(text_w + 16.0)
        });
        if let Some(pl) = &pango_layout {
            pl.set_font_description(saved_font.as_ref());
        }
        result
    }

    fn draw_split(&mut self, rect: QRect, split: &Split) -> crate::primitives::split::SplitLayout {
        let theme = self.current_theme;
        let layout = crate::gtk::gtk_split_layout(
            split,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
        );
        crate::primitives::split::native_surface_paint::paint(&layout, self, &theme);
        // `Split` paints a divider only — no text of its own — so a
        // registered zone is the only way this frame is attributable to
        // the primitive rather than indistinguishable from the trait's
        // no-op default (C0 paint smoke, contract §5b).
        self.register_zone(split.id, rect);
        layout
    }

    fn split_layout(&self, rect: QRect, split: &Split) -> crate::primitives::split::SplitLayout {
        crate::gtk::gtk_split_layout(
            split,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
        )
    }

    fn draw_split_tree(
        &mut self,
        rect: QRect,
        tree: &crate::primitives::split_tree::SplitTree,
    ) -> crate::primitives::split_tree::SplitTreeLayout {
        let theme = self.current_theme;
        let layout = crate::gtk::gtk_split_tree_layout(
            tree,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
        );
        crate::primitives::split_tree::native_surface_paint::paint(&layout, self, &theme);
        // Dividers only, and `SplitTree` (unlike `Split`) carries no
        // id of its own — register a fixed chrome id, same pattern as
        // `draw_terminal_divider` / `draw_drop_overlay`.
        self.register_zone(WidgetId::new("chrome:split-tree"), rect);
        layout
    }

    fn split_tree_layout(
        &self,
        rect: QRect,
        tree: &crate::primitives::split_tree::SplitTree,
    ) -> crate::primitives::split_tree::SplitTreeLayout {
        crate::gtk::gtk_split_tree_layout(
            tree,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
        )
    }

    fn draw_panel(
        &mut self,
        rect: QRect,
        panel: &crate::primitives::panel::Panel,
    ) -> crate::primitives::panel::PanelLayout {
        let line_height = self.current_line_height;
        let theme = self.current_theme;
        let layout = crate::gtk::gtk_panel_layout(
            panel,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
            line_height,
        );
        crate::primitives::panel::native_surface_paint::paint(panel, &layout, self, &theme);
        layout
    }

    fn panel_layout(
        &self,
        rect: QRect,
        panel: &crate::primitives::panel::Panel,
    ) -> crate::primitives::panel::PanelLayout {
        crate::gtk::gtk_panel_layout(
            panel,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
            self.current_line_height,
        )
    }

    fn draw_canvas(
        &mut self,
        rect: QRect,
        canvas: &crate::primitives::canvas::Canvas,
    ) -> crate::primitives::canvas::CanvasLayout {
        let layout = canvas.layout(rect);
        crate::primitives::canvas::native_surface_paint::paint(canvas, &layout, self);
        layout
    }

    fn draw_toast_overlay(
        &mut self,
        rect: QRect,
        stack: &crate::primitives::toast::ToastOverlay,
    ) -> crate::primitives::toast::ToastStackLayout {
        // `PaintSurface::surface_fill_rect`/`surface_draw_text_run` (etc) each require
        // an active frame internally, so this method needs no separate cr/pango fetch.
        let theme = self.current_theme;
        let style = self.style();
        let line_height = self.current_line_height as f32;
        crate::primitives::toast::native_surface_paint::paint(
            stack,
            self,
            &theme,
            &style,
            rect.x,
            rect.y,
            rect.width,
            rect.height,
            line_height,
        )
    }

    /// Paint via the shared [`crate::primitives::pipeline_view::native_surface_paint::paint`].
    /// Every text run goes through [`Self::surface_draw_text_run`], which is already
    /// recorded into the painted-text map for testing.
    fn draw_pipeline_view(
        &mut self,
        rect: QRect,
        view: &crate::primitives::pipeline_view::PipelineView,
    ) -> crate::primitives::pipeline_view::PipelineViewLayout {
        let theme = self.current_theme;
        crate::primitives::pipeline_view::native_surface_paint::paint(view, self, &theme, rect)
    }

    fn pipeline_view_layout(
        &self,
        rect: QRect,
        view: &crate::primitives::pipeline_view::PipelineView,
    ) -> crate::primitives::pipeline_view::PipelineViewLayout {
        crate::gtk::gtk_pipeline_view_layout(
            view,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
        )
    }

    /// Paint via the shared [`crate::primitives::progress::native_surface_paint::paint`].
    fn draw_progress(
        &mut self,
        rect: QRect,
        bar: &crate::primitives::progress::ProgressBar,
    ) -> crate::primitives::progress::ProgressBarLayout {
        let theme = self.current_theme;
        let style = self.style();
        crate::primitives::progress::native_surface_paint::paint(bar, self, &theme, rect, &style)
    }

    fn progress_layout(
        &self,
        rect: QRect,
        bar: &crate::primitives::progress::ProgressBar,
    ) -> crate::primitives::progress::ProgressBarLayout {
        crate::gtk::gtk_progress_layout(
            bar,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
        )
    }

    fn draw_spinner(
        &mut self,
        rect: QRect,
        spinner: &crate::primitives::spinner::Spinner,
    ) -> crate::primitives::spinner::SpinnerLayout {
        let theme = self.current_theme;
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, pango_layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_spinner called outside enter_frame_scope");
        // Spinner's label (e.g. "Indexing…") is chrome, not editor
        // content — save the editor font on the shared layout, paint in
        // `ui_font`, then restore, matching `Self::draw_tree`'s
        // save/swap/restore.
        let saved_font = pango_layout.font_description();
        pango_layout.set_font_description(Some(&ui_font_desc));
        let spinner_layout = crate::gtk::draw_spinner(
            cr,
            pango_layout,
            rect.x as f64,
            rect.y as f64,
            spinner,
            &theme,
        );
        pango_layout.set_font_description(saved_font.as_ref());
        spinner_layout
    }

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

    /// Paint via the shared [`crate::primitives::button::native_surface_paint::paint`].
    fn draw_button(
        &mut self,
        rect: QRect,
        button: &crate::primitives::button::Button,
    ) -> crate::primitives::button::ButtonLayout {
        let theme = self.current_theme;
        let style = self.style();
        let layout = crate::primitives::button::native_surface_paint::paint(
            button, self, &theme, rect, &style,
        );
        self.register_zone(button.id, rect);
        layout
    }

    fn button_layout(
        &self,
        rect: QRect,
        button: &crate::primitives::button::Button,
    ) -> crate::primitives::button::ButtonLayout {
        button.layout(rect)
    }

    /// Paint via the shared [`crate::primitives::radio_group::native_surface_paint::paint`].
    /// The per-option measure is nominal (`rect.width` × the chrome
    /// line height) since there is no native text-metrics surface to
    /// measure against yet.
    fn draw_radio_group(
        &mut self,
        rect: QRect,
        group: &crate::primitives::radio_group::RadioGroup,
    ) -> crate::primitives::radio_group::RadioGroupLayout {
        let theme = self.current_theme;
        let row_height = self.current_line_height as f32;
        let layout = crate::primitives::radio_group::native_surface_paint::paint(
            group, self, &theme, rect, row_height,
        );
        for (option, item) in group.options.iter().zip(layout.items.iter()) {
            self.register_zone(option.id, *item);
        }
        layout
    }

    fn radio_group_layout(
        &self,
        rect: QRect,
        group: &crate::primitives::radio_group::RadioGroup,
    ) -> crate::primitives::radio_group::RadioGroupLayout {
        let row_height = self.current_line_height as f32;
        group.layout(
            rect,
            |_option: &crate::primitives::radio_group::RadioOption| {
                crate::primitives::radio_group::RadioOptionMeasure {
                    width: rect.width,
                    height: row_height,
                }
            },
        )
    }

    /// Paint via the shared [`crate::primitives::switch::native_surface_paint::paint`].
    /// Chrome-only (no label of its own), so this also registers a
    /// click zone — same "paint + register" pairing as
    /// [`Self::draw_focus_ring`].
    fn draw_switch(
        &mut self,
        rect: QRect,
        switch: &crate::primitives::switch::Switch,
    ) -> crate::primitives::switch::SwitchLayout {
        let theme = self.current_theme;
        let layout =
            crate::primitives::switch::native_surface_paint::paint(switch, self, &theme, rect);
        self.register_zone(switch.id, rect);
        layout
    }

    fn switch_layout(
        &self,
        rect: QRect,
        switch: &crate::primitives::switch::Switch,
    ) -> crate::primitives::switch::SwitchLayout {
        switch.layout(rect)
    }

    fn toast_stack_layout(
        &self,
        rect: QRect,
        stack: &crate::primitives::toast::ToastOverlay,
    ) -> crate::primitives::toast::ToastStackLayout {
        // Layout-only path measures via a real `pango::Layout` when available,
        // falling back to `PangoTextMeasure`'s character count estimate otherwise.
        let char_w = self.current_char_width as f32;
        let pango_layout = self.chrome_measure_layout();
        let measure = PangoTextMeasure {
            layout: &pango_layout,
            char_w,
        };
        crate::primitives::layout_metrics::pixel_toast_stack_layout(
            stack,
            &measure,
            rect.x,
            rect.y,
            rect.width,
            rect.height,
            self.current_line_height as f32,
        )
    }

    fn draw_command_center(
        &mut self,
        rect: QRect,
        cc: &crate::primitives::command_center::CommandCenter,
    ) -> crate::primitives::command_center::CommandCenterLayout {
        let line_height = self.current_line_height;
        let theme = self.current_theme;
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, pango_layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_command_center called outside enter_frame_scope");
        // The back/forward arrows and search label are chrome, not editor content.
        // Save/swap/restore the font like other chrome primitives for consistency.
        let saved_font = pango_layout.font_description();
        pango_layout.set_font_description(Some(&ui_font_desc));
        let layout = crate::gtk::draw_command_center(
            cr,
            pango_layout,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
            cc,
            &theme,
            line_height,
        );
        pango_layout.set_font_description(saved_font.as_ref());
        layout
    }

    fn command_center_layout(
        &self,
        rect: QRect,
        cc: &crate::primitives::command_center::CommandCenter,
    ) -> crate::primitives::command_center::CommandCenterLayout {
        // Search-box width comes from the shared char-width formula
        // (`CommandCenterMeasure::from_char_width`) rather than an inline
        // copy — this no-paint query has no live Pango layout on hand
        // (unlike `draw_command_center`'s `gtk_command_center_layout`,
        // which measures the label's real pixel width), so it estimates
        // from `current_char_width` exactly like `win::command_center`
        // does from its own DirectWrite char width.
        let char_w = self.current_char_width as f32;
        let bounds = crate::event::Rect::new(rect.x, rect.y, rect.width, rect.height);
        cc.layout(
            bounds,
            crate::primitives::command_center::CommandCenterMeasure::from_char_width(
                &cc.search_label,
                char_w,
                rect.height,
            ),
        )
    }

    /// Shared chart painting lives in [`crate::primitives::chart::paint`] now.
    fn draw_chart(
        &mut self,
        rect: QRect,
        chart: &crate::primitives::chart::Chart,
        hovered_point: Option<(usize, usize)>,
        crosshair_x: Option<f64>,
    ) -> crate::primitives::chart::ChartLayout {
        let theme = self.current_theme;
        let layout = self.chart_layout(rect, chart);
        crate::primitives::chart::paint(chart, &layout, self, &theme, hovered_point, crosshair_x);
        layout
    }

    fn chart_layout(
        &self,
        rect: QRect,
        chart: &crate::primitives::chart::Chart,
    ) -> crate::primitives::chart::ChartLayout {
        crate::gtk::gtk_chart_layout(
            chart,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
            self.current_line_height,
            self.current_char_width,
        )
    }

    fn draw_toolbar_with_options(
        &mut self,
        rect: QRect,
        bar: &crate::primitives::toolbar::Toolbar,
        interaction: &crate::interaction::InteractionState,
        options: crate::primitives::toolbar::ToolbarPaintOptions,
    ) -> crate::primitives::toolbar::ToolbarLayout {
        let (hovered_id, pressed_id) = (interaction.hovered(), interaction.pressed());
        let theme = self.current_theme;
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let (cr, pango_layout) = self
            .current_frame_refs()
            .expect("GtkBackend::draw_toolbar_with_options called outside enter_frame_scope");
        // Action labels and `Toolbar::Action` icon glyphs are chrome,
        // not editor content — mirrors `Self::draw_list`/`Self::draw_tree`'s
        // save/swap/restore. Before this, the toolbar painted with
        // whatever font the shared layout happened to carry into the frame
        // (typically the editor font, set once at frame start in
        // `gtk/run.rs`), which has no Nerd-Font fallback family, so an
        // icon glyph in `ToolbarButton::Action.icon` could render as
        // tofu/blank depending on what else is installed.
        let saved_font = pango_layout.font_description();
        pango_layout.set_font_description(Some(&ui_font_desc));
        let layout = crate::gtk::draw_toolbar_with_options(
            cr,
            pango_layout,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
            bar,
            &theme,
            hovered_id,
            pressed_id,
            options,
        );
        pango_layout.set_font_description(saved_font.as_ref());
        layout
    }

    fn toolbar_layout(
        &self,
        rect: QRect,
        bar: &crate::primitives::toolbar::Toolbar,
    ) -> crate::primitives::toolbar::ToolbarLayout {
        let char_w = self.current_char_width;
        let frame_layout = self.current_frame_refs().map(|(_, l)| l.clone());
        let pango_layout = frame_layout.or_else(|| self.pango_ctx.as_ref().map(pango::Layout::new));
        // Measure with `ui_font`, matching `Self::draw_toolbar`'s paint font.
        // Hit-testing without repainting must resolve the same button widths the
        // paint path produced.
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let saved_font = pango_layout.as_ref().and_then(|pl| pl.font_description());
        if let Some(pl) = &pango_layout {
            pl.set_font_description(Some(&ui_font_desc));
        }
        let result = crate::gtk::gtk_toolbar_layout(
            bar,
            pango_layout.as_ref(),
            char_w,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
        );
        if let Some(pl) = &pango_layout {
            pl.set_font_description(saved_font.as_ref());
        }
        result
    }

    fn draw_sidebar_panel_interactive(
        &mut self,
        rect: QRect,
        panel: &crate::primitives::sidebar_panel::SidebarPanel,
        interaction: &crate::interaction::InteractionState,
    ) -> crate::primitives::sidebar_panel::SidebarPanelLayout {
        let (hovered_toolbar_id, pressed_toolbar_id) =
            (interaction.hovered(), interaction.pressed());
        let theme = self.current_theme;
        let line_height = self.current_line_height;
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        // `SidebarPanel` composes a `Toolbar` header — its
        // icon glyphs are chrome, not editor content — so the same
        // save/swap/restore `Self::draw_toolbar` does has to happen here
        // too (the shared `native_surface_paint::paint` below measures
        // and draws text via `Self::surface_measure_text`/
        // `surface_draw_text_run`, which just use whatever font is live
        // on this shared `pango_layout`).
        let saved_font = {
            let (_cr, pango_layout) = self
                .current_frame_refs()
                .expect("GtkBackend::draw_sidebar_panel called outside enter_frame_scope");
            let saved = pango_layout.font_description();
            pango_layout.set_font_description(Some(&ui_font_desc));
            saved
        };
        let layout = crate::primitives::sidebar_panel::native_surface_paint::paint(
            panel,
            self,
            &theme,
            rect,
            line_height as f32,
            hovered_toolbar_id,
            pressed_toolbar_id,
        );
        {
            let (_cr, pango_layout) = self
                .current_frame_refs()
                .expect("GtkBackend::draw_sidebar_panel called outside enter_frame_scope");
            pango_layout.set_font_description(saved_font.as_ref());
        }
        layout
    }

    fn sidebar_panel_layout(
        &self,
        rect: QRect,
        panel: &crate::primitives::sidebar_panel::SidebarPanel,
    ) -> crate::primitives::sidebar_panel::SidebarPanelLayout {
        let char_w = self.current_char_width;
        let line_h = self.current_line_height;
        let frame_layout = self.current_frame_refs().map(|(_, l)| l.clone());
        let pango_layout = frame_layout.or_else(|| self.pango_ctx.as_ref().map(pango::Layout::new));
        // The panel's header is a `Toolbar`, so its measured button
        // widths must come from the same `ui_font`
        // `Self::draw_sidebar_panel` now paints with — see
        // `Self::toolbar_layout` above.
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let saved_font = pango_layout.as_ref().and_then(|pl| pl.font_description());
        if let Some(pl) = &pango_layout {
            pl.set_font_description(Some(&ui_font_desc));
        }
        let result = crate::gtk::gtk_sidebar_panel_layout(
            panel,
            pango_layout.as_ref(),
            char_w,
            line_h,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
        );
        if let Some(pl) = &pango_layout {
            pl.set_font_description(saved_font.as_ref());
        }
        result
    }

    /// Paint via the shared
    /// [`crate::primitives::diff_view::native_surface_paint::paint`] —
    /// see that fn's doc for the two named divergences (row/header text
    /// vertical alignment; header-label ellipsize vs. hard-clip) found
    /// while unifying `gtk::diff_view::draw_diff_view`,
    /// `macos::diff_view::draw_diff_view` and
    /// `win::diff_view::draw_diff_view` into one implementation.
    fn draw_diff_view(
        &mut self,
        rect: QRect,
        view: &crate::primitives::diff_view::DiffView,
    ) -> crate::primitives::diff_view::DiffViewLayout {
        let theme = self.current_theme;
        let line_height = self.current_line_height as f32;
        // The diff view is editor-class — see the matching comment on
        // `Self::draw_terminal` / `EditorSurface`'s own doc.
        let mut surface = EditorSurface { backend: self };
        crate::primitives::diff_view::native_surface_paint::paint(
            view,
            &mut surface,
            &theme,
            rect,
            line_height,
        )
    }

    /// Paint via the shared
    /// [`crate::primitives::board::native_surface_paint::paint`] — see
    /// that fn's doc for the four named divergences (column-header
    /// overflow; card-title wrapping; rounded vs. straight card borders;
    /// per-element font size) found while unifying
    /// `gtk::board::draw_board`, `macos::board::draw_board` and
    /// `win::board::draw_board` into one implementation.
    fn draw_board(
        &mut self,
        rect: QRect,
        model: &crate::primitives::board::BoardModel,
    ) -> crate::primitives::board::BoardLayout {
        let theme = self.current_theme;
        crate::primitives::board::native_surface_paint::paint(model, self, &theme, rect)
    }

    fn board_layout(
        &self,
        rect: QRect,
        model: &crate::primitives::board::BoardModel,
    ) -> crate::primitives::board::BoardLayout {
        crate::gtk::gtk_board_layout(
            model,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
        )
    }

    fn draw_minimap(
        &mut self,
        rect: QRect,
        minimap: &crate::primitives::minimap::Minimap,
    ) -> crate::backend::MinimapPaintResult {
        let theme = self.current_theme;
        let dpi_scale = self.dpi_scale as f64;
        // Uses `super::minimap::draw_minimap_cached` for the glyph atlas cache.
        // Reads raw pointers directly so `cr`/`pango_layout` don't collide with
        // the `&mut self.minimap_atlas_cache` borrow this method also needs.
        let cr_ptr = self.current_cr_ptr.get();
        let layout_ptr = self.current_layout_ptr.get();
        assert!(
            !cr_ptr.is_null() && !layout_ptr.is_null(),
            "GtkBackend::draw_minimap called outside enter_frame_scope"
        );
        // SAFETY: `enter_frame_scope` set both pointers from real, live
        // `&Context`/`&pango::Layout` borrows and won't return until the
        // scope ends -- the same invariant `current_frame_refs` relies
        // on.
        let cr = unsafe { &*(cr_ptr as *const Context) };
        let pango_layout = unsafe { &*(layout_ptr as *const pango::Layout) };
        let layout = crate::gtk::minimap::draw_minimap_cached(
            cr,
            pango_layout,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
            minimap,
            &theme,
            &mut self.minimap_atlas_cache,
            dpi_scale,
            self.minimap_scale,
        );
        self.register_zone(minimap.id, rect);
        crate::backend::MinimapPaintResult {
            layout,
            painted: true,
        }
    }

    fn draw_image(
        &mut self,
        rect: QRect,
        image: &crate::primitives::image::Image,
    ) -> crate::backend::ImagePaintResult {
        let cr_ptr = self.current_cr_ptr.get();
        assert!(
            !cr_ptr.is_null(),
            "GtkBackend::draw_image called outside enter_frame_scope"
        );
        // SAFETY: `enter_frame_scope` set `current_cr_ptr` from a real, live `&Context`
        // and won't return until the scope ends. Read the raw pointer directly to avoid
        // colliding with the `&mut self.image_cache` borrow this method also needs.
        let cr = unsafe { &*(cr_ptr as *const Context) };
        let dpi_scale = self.dpi_scale;
        // Uses `super::image::draw_image_cached` for the decode cache.
        let result =
            super::image::draw_image_cached(cr, rect, image, &mut self.image_cache, dpi_scale);
        self.register_zone(image.id, rect);
        result
    }

    fn minimap_layout(
        &self,
        rect: QRect,
        minimap: &crate::primitives::minimap::Minimap,
    ) -> crate::primitives::minimap::MinimapLayout {
        crate::gtk::minimap::gtk_minimap_layout_scaled(
            minimap,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
            self.minimap_scale,
        )
    }

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

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

/// GTK's `WindowControl` surface. Backed by `gtk4::Window`'s
/// own methods wherever GTK4 exposes one; everything GTK4 structurally
/// can't do reports [`BackendError::Unsupported`] honestly rather than
/// silently no-op'ing — see each method's doc for which bucket it's in.
///
/// Every method guards on `self.window.is_some()` the same way
/// [`Backend::set_cursor`]/[`Backend::toggle_window_maximize`] do, even
/// though `Backend::window` only ever hands out `&mut dyn WindowControl`
/// once `self.window` is `Some` — cheap defense against a caller that
/// stashed the trait object past a window teardown, matching this
/// backend's existing posture everywhere else it touches `self.window`.
impl crate::backend::WindowControl for GtkBackend {
    fn set_title(&mut self, title: &str) -> crate::backend::ServiceResult<()> {
        let window = self.window.as_ref().ok_or(BackendError::Unsupported)?;
        window.set_title(Some(title));
        Ok(())
    }

    fn set_size(&mut self, width: f32, height: f32) -> crate::backend::ServiceResult<()> {
        let window = self.window.as_ref().ok_or(BackendError::Unsupported)?;
        window.set_default_size(width.round() as i32, height.round() as i32);
        Ok(())
    }

    /// `gtk4::Widget::set_size_request` — GTK4's only minimum-size
    /// primitive; there is no separate "resizable floor" concept beyond
    /// it.
    fn set_min_size(&mut self, width: f32, height: f32) -> crate::backend::ServiceResult<()> {
        let window = self.window.as_ref().ok_or(BackendError::Unsupported)?;
        window.set_size_request(width.round() as i32, height.round() as i32);
        Ok(())
    }

    /// **Not available.** GTK4 removed the GTK3 `GDK_HINT_MAX_SIZE`
    /// geometry-hint mechanism outright — there is no maximum-size API
    /// left to call.
    fn set_max_size(&mut self, _width: f32, _height: f32) -> crate::backend::ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// Size-only: GTK4 (and Wayland in particular, which every current
    /// desktop compositor speaks) exposes **no way for a client to learn
    /// its own on-screen position** — the position-hint APIs GTK3 had
    /// were removed as a matter of Wayland security policy, not GTK
    /// preference. `x`/`y` are always `0.0`, meaning "unknown", not "at
    /// the screen origin" — callers that need real position should treat
    /// this backend as one where position is structurally unavailable,
    /// not zero.
    fn bounds(&self) -> crate::backend::ServiceResult<Rect> {
        let window = self.window.as_ref().ok_or(BackendError::Unsupported)?;
        Ok(Rect::new(
            0.0,
            0.0,
            window.width() as f32,
            window.height() as f32,
        ))
    }

    /// **Not available**, for the same reason [`Self::bounds`] can't
    /// report a position: there is no GTK4 API to move a top-level
    /// window at all (Wayland has no client-side move protocol). Use
    /// [`Self::set_size`] instead when only the size half is needed.
    fn set_bounds(&mut self, _bounds: Rect) -> crate::backend::ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// **Not available** — centering requires knowing (and setting) a
    /// screen position, which GTK4/Wayland exposes neither half of; see
    /// [`Self::bounds`].
    fn center(&mut self) -> crate::backend::ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    fn set_fullscreen(&mut self, fullscreen: bool) -> crate::backend::ServiceResult<()> {
        let window = self.window.as_ref().ok_or(BackendError::Unsupported)?;
        if fullscreen {
            window.fullscreen();
        } else {
            window.unfullscreen();
        }
        Ok(())
    }

    /// `gtk4::Window::is_maximized`.
    fn is_maximized(&self) -> crate::backend::ServiceResult<bool> {
        let window = self.window.as_ref().ok_or(BackendError::Unsupported)?;
        Ok(window.is_maximized())
    }

    /// **Not available on GTK4/Wayland** — see this trait method's own doc comment
    /// for the X11-only-via-`gdk_x11` background.
    fn set_always_on_top(&mut self, _on_top: bool) -> crate::backend::ServiceResult<()> {
        Err(BackendError::Unsupported)
    }

    /// `gtk4::Window::set_decorated` — backs vimcode's client-side-decoration path:
    /// turning this off lets the app paint its own titlebar without GTK's native one.
    fn set_decorated(&mut self, decorated: bool) -> crate::backend::ServiceResult<()> {
        let window = self.window.as_ref().ok_or(BackendError::Unsupported)?;
        window.set_decorated(decorated);
        Ok(())
    }

    fn minimize(&mut self) -> crate::backend::ServiceResult<()> {
        let window = self.window.as_ref().ok_or(BackendError::Unsupported)?;
        window.minimize();
        Ok(())
    }

    /// Undoes both a minimize (`unminimize`) and a maximize
    /// (`unmaximize`, if currently maximized) — matching Electron's
    /// `BrowserWindow.restore()`, which likewise restores from either
    /// state rather than tracking which one the window was actually in.
    fn restore(&mut self) -> crate::backend::ServiceResult<()> {
        let window = self.window.as_ref().ok_or(BackendError::Unsupported)?;
        window.unminimize();
        if window.is_maximized() {
            window.unmaximize();
        }
        Ok(())
    }

    fn hide(&mut self) -> crate::backend::ServiceResult<()> {
        let window = self.window.as_ref().ok_or(BackendError::Unsupported)?;
        // `WidgetExt::hide` is deprecated since GTK 4.10 in favour of
        // `set_visible(false)` — same effect, current API.
        window.set_visible(false);
        Ok(())
    }

    fn show(&mut self) -> crate::backend::ServiceResult<()> {
        let window = self.window.as_ref().ok_or(BackendError::Unsupported)?;
        window.set_visible(true);
        Ok(())
    }

    /// `gtk4::Window::present` — raises the window and gives it input
    /// focus, the same call [`Backend::toggle_window_maximize`]'s
    /// double-click-to-maximize sibling gestures rely on elsewhere in
    /// this backend for "bring to front".
    fn focus(&mut self) -> crate::backend::ServiceResult<()> {
        let window = self.window.as_ref().ok_or(BackendError::Unsupported)?;
        window.present();
        Ok(())
    }
}

/// The GTK twin of `macos::backend::EditorSurface`. Adapts
/// `&mut GtkBackend` to [`PaintSurface`], routing text measurement and
/// painting through [`GtkBackend::editor_font_pango_string`] explicitly
/// rather than `GtkBackend`'s own [`PaintSurface`] impl (below), which
/// now defaults every non-editor-class primitive to `ui_font` (the
/// chrome font — see `crate::font_role`'s module doc). The terminal, the
/// plain text display and the diff view are the three
/// `crate::font_role::EditorClassPrimitive`s that paint through this
/// trait on this backend (`draw_editor`, `draw_minimap` and
/// `draw_command_line` paint through the raw `(cr, layout)` pair
/// directly instead — see those methods — so they never pick up
/// `GtkBackend`'s own `PaintSurface` impl in the first place and need no
/// adapter here), so each wraps `self` in this type before calling into
/// its shared `primitives::*::paint`/`native_surface_paint::paint`
/// helper.
///
/// `surface_line_height`/`surface_char_width` are not overridden:
/// `GtkBackend`'s own impl of those two already reports
/// `current_line_height`/`current_char_width`, which *are* the editor
/// font's metrics (refreshed every frame from `editor_font_pango_string`
/// by `gtk/run.rs::render_frame`), so forwarding is already correct —
/// unlike the chrome text verbs below, there is no ambient-vs-explicit
/// gap to close for row pitch. Every other font-agnostic verb (fills,
/// strokes, clip, lines, images, frame lifecycle) forwards straight
/// through for the same reason.
///
/// Also not overridden: `surface_measure_text_styled` and
/// `surface_draw_icon_glyph`. The trait defaults for both forward to
/// `surface_measure_text`/`surface_draw_text_run` respectively, which
/// *this* impl does override to resolve the editor font — so today's
/// behaviour is correct by construction, not by an explicit override
/// here. That's a latent gap, not a bug yet: none of
/// `terminal::paint`/`text_display::paint`/
/// `diff_view::native_surface_paint::paint` (the three callers that wrap
/// themselves in this adapter) call either method today. If one of them
/// starts calling `surface_measure_text_styled` (e.g. to measure a bold
/// terminal run) or `surface_draw_icon_glyph`, add an explicit override
/// here so the result still resolves the editor font rather than
/// silently depending on the trait default continuing to route through
/// the two methods above. `macos::backend::EditorSurface` has the same
/// gap for the same reason (same two methods un-overridden there too).
struct EditorSurface<'a> {
    backend: &'a mut GtkBackend,
}

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

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

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

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

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

    /// Forces `editor_font_pango_string()` explicitly rather than
    /// trusting the shared layout's ambient font — the editor twin of
    /// `GtkBackend::surface_measure_text`'s own explicit chrome force
    /// (see that method's doc for why ambient trust is the bug this
    /// issue closes), so a caller mid-frame never finds this adapter's
    /// result depends on draw order.
    fn surface_measure_text(&self, text: &str) -> (f32, f32) {
        let (_cr, layout) = self
            .backend
            .current_frame_refs()
            .expect("EditorSurface::surface_measure_text called outside enter_frame_scope");
        let saved = layout.font_description();
        let editor_desc =
            pango::FontDescription::from_string(&self.backend.editor_font_pango_string());
        layout.set_font_description(Some(&editor_desc));
        layout.set_text(text);
        layout.set_attributes(None);
        let (w, h) = layout.pixel_size();
        layout.set_font_description(saved.as_ref());
        (w as f32, h as f32)
    }

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

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

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

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

    /// See [`Self::surface_measure_text`]'s doc for why this forces
    /// `editor_font_pango_string()` explicitly.
    fn surface_draw_text_run(&mut self, rect: QRect, text: &str, color: Color) {
        let (cr, layout) = self
            .backend
            .current_frame_refs()
            .expect("EditorSurface::surface_draw_text_run called outside enter_frame_scope");
        let saved = layout.font_description();
        let editor_desc =
            pango::FontDescription::from_string(&self.backend.editor_font_pango_string());
        layout.set_font_description(Some(&editor_desc));
        layout.set_text(text);
        layout.set_attributes(None);
        crate::gtk::set_source(cr, color);
        cr.move_to(rect.x as f64, rect.y as f64);
        super::painted_text::show_layout(cr, layout);
        layout.set_font_description(saved.as_ref());
    }

    /// The editor-font twin of `GtkBackend`'s own (now chrome-forcing)
    /// override — same styling/`scale_x` support, the shape
    /// `primitives::terminal::paint`'s per-cell glyph styling (ANSI
    /// bold/italic/underline) and wide-glyph advance fix need, just
    /// forced onto `editor_font_pango_string()` instead of `ui_font`.
    #[allow(clippy::too_many_arguments)]
    fn surface_draw_text_run_styled(
        &mut self,
        rect: QRect,
        text: &str,
        color: Color,
        bold: bool,
        italic: bool,
        underline: bool,
        scale_x: f32,
    ) {
        let (cr, layout) = self
            .backend
            .current_frame_refs()
            .expect("EditorSurface::surface_draw_text_run_styled called outside enter_frame_scope");
        let saved = layout.font_description();
        let editor_desc =
            pango::FontDescription::from_string(&self.backend.editor_font_pango_string());
        layout.set_font_description(Some(&editor_desc));
        layout.set_text(text);
        let attrs = pango::AttrList::new();
        if bold {
            attrs.insert(pango::AttrInt::new_weight(pango::Weight::Bold));
        }
        if italic {
            attrs.insert(pango::AttrInt::new_style(pango::Style::Italic));
        }
        if underline {
            attrs.insert(pango::AttrInt::new_underline(pango::Underline::Single));
        }
        layout.set_attributes(Some(&attrs));
        crate::gtk::set_source(cr, color);
        if (scale_x - 1.0).abs() > f32::EPSILON {
            cr.save().ok();
            cr.translate(rect.x as f64, rect.y as f64);
            cr.scale(scale_x as f64, 1.0);
            cr.move_to(0.0, 0.0);
            super::painted_text::show_layout(cr, layout);
            cr.restore().ok();
        } else {
            cr.move_to(rect.x as f64, rect.y as f64);
            super::painted_text::show_layout(cr, layout);
        }
        layout.set_attributes(None);
        layout.set_font_description(saved.as_ref());
    }

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

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

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

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

// PaintSurface implementation: extracted from private helpers.
// Every text verb forces `ui_font` (chrome) explicitly rather than trusting
// the ambient per-frame layout font. `Self::status_bar_paint_scaled` relies
// on this: every text verb resolves `self.ui_font` fresh on every call.
impl PaintSurface for GtkBackend {
    fn surface_begin_frame(&mut self, viewport: Viewport) {
        Backend::begin_frame(self, viewport);
    }

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

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

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

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

    /// `self` is the surface every non-editor-class
    /// primitive measures/paints through unwrapped (`draw_panel`,
    /// `draw_toast_overlay`, `draw_split`, …), so this forces `ui_font`
    /// (the chrome font) explicitly rather than trusting whatever font
    /// the shared per-frame layout happens to carry in — that ambient
    /// font is the *editor* font by default (`gtk/run.rs::render_frame`
    /// seeds it fresh from `editor_font_pango_string` every frame), so
    /// measuring without forcing chrome here silently measured chrome
    /// text against editor metrics. Saves and restores the layout's font
    /// description around the measurement, the same save/swap/restore
    /// shape [`Self::draw_tree`] already uses for painting, so a caller
    /// mid-frame never finds the shared layout left on `ui_font` after
    /// this returns. See [`EditorSurface`]'s doc for the three
    /// editor-class primitives that opt back into the editor font via a
    /// dedicated adapter instead, and `crate::font_role`'s module doc
    /// for why a non-editor-class primitive must never resolve the
    /// editor font.
    fn surface_measure_text(&self, text: &str) -> (f32, f32) {
        let (_cr, layout) = self
            .current_frame_refs()
            .expect("GtkBackend::surface_measure_text called outside enter_frame_scope");
        let saved = layout.font_description();
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        layout.set_font_description(Some(&ui_font_desc));
        layout.set_text(text);
        layout.set_attributes(None);
        let (w, h) = layout.pixel_size();
        layout.set_font_description(saved.as_ref());
        (w as f32, h as f32)
    }

    /// Overrides the default (which drops `bold`) — a bold Pango
    /// `AttrList` weight, matching what `gtk::status_bar::draw_status_bar`
    /// measured before its paint moved to
    /// `primitives::status_bar::native_surface_paint::paint`. Also
    /// forces `ui_font` now, matching [`Self::surface_measure_text`]'s
    /// doc above.
    fn surface_measure_text_styled(&self, text: &str, bold: bool) -> (f32, f32) {
        let (_cr, layout) = self
            .current_frame_refs()
            .expect("GtkBackend::surface_measure_text_styled called outside enter_frame_scope");
        let saved = layout.font_description();
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        layout.set_font_description(Some(&ui_font_desc));
        layout.set_text(text);
        if bold {
            let attrs = pango::AttrList::new();
            attrs.insert(pango::AttrInt::new_weight(pango::Weight::Bold));
            layout.set_attributes(Some(&attrs));
        } else {
            layout.set_attributes(None);
        }
        let (w, h) = layout.pixel_size();
        layout.set_attributes(None);
        layout.set_font_description(saved.as_ref());
        (w as f32, h as f32)
    }

    fn surface_fill_rect(&mut self, rect: QRect, color: Color) {
        let (cr, _layout) = self
            .current_frame_refs()
            .expect("GtkBackend::surface_fill_rect called outside enter_frame_scope");
        // `set_source_rgba`, not `set_source` — see that fn's doc
        // for why a translucent fill must honour `color.a`
        // here to match macOS/Windows's `PaintSurface::surface_fill_rect`.
        crate::gtk::set_source_rgba(cr, color);
        cr.rectangle(
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
        );
        cr.fill().ok();
    }

    /// `crate::gtk::rounded_rect_path` was already private plumbing
    /// for the context menu / `ListView` / command-center rasterisers —
    /// this is the first `PaintSurface` verb to expose it. `radius` is
    /// clamped to half of `rect`'s shorter side, matching this trait
    /// method's own doc for why (an unclamped radius overlaps the
    /// opposite corner's arc on every one of the three native path APIs).
    fn surface_fill_rounded_rect(&mut self, rect: QRect, radius: f32, color: Color) {
        let (cr, _layout) = self
            .current_frame_refs()
            .expect("GtkBackend::surface_fill_rounded_rect called outside enter_frame_scope");
        let r = (radius as f64)
            .min(rect.width as f64 / 2.0)
            .min(rect.height as f64 / 2.0)
            .max(0.0);
        crate::gtk::set_source_rgba(cr, color);
        crate::gtk::rounded_rect_path(
            cr,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
            r,
        );
        cr.fill().ok();
    }

    fn surface_stroke_rect(&mut self, rect: QRect, color: Color, stroke_width: f32) {
        let (cr, _layout) = self
            .current_frame_refs()
            .expect("GtkBackend::surface_stroke_rect called outside enter_frame_scope");
        crate::gtk::set_source(cr, color);
        cr.set_line_width(stroke_width as f64);
        cr.rectangle(
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
        );
        cr.stroke().ok();
    }

    /// [`Self::surface_fill_rounded_rect`]'s stroke twin — same
    /// `crate::gtk::rounded_rect_path` recipe, `cr.stroke()` instead of
    /// `cr.fill()`.
    fn surface_stroke_rounded_rect(
        &mut self,
        rect: QRect,
        radius: f32,
        color: Color,
        stroke_width: f32,
    ) {
        let (cr, _layout) = self
            .current_frame_refs()
            .expect("GtkBackend::surface_stroke_rounded_rect called outside enter_frame_scope");
        let r = (radius as f64)
            .min(rect.width as f64 / 2.0)
            .min(rect.height as f64 / 2.0)
            .max(0.0);
        crate::gtk::set_source(cr, color);
        cr.set_line_width(stroke_width as f64);
        crate::gtk::rounded_rect_path(
            cr,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
            r,
        );
        cr.stroke().ok();
    }

    /// Forces `ui_font` explicitly — see
    /// [`Self::surface_measure_text`]'s doc for why, and [`EditorSurface`]
    /// for the adapter the three editor-class primitives (`draw_terminal`,
    /// `draw_text_display`, `draw_diff_view`) wrap `self` in instead so
    /// their glyphs keep painting in the editor font.
    fn surface_draw_text_run(&mut self, rect: QRect, text: &str, color: Color) {
        let (cr, layout) = self
            .current_frame_refs()
            .expect("GtkBackend::surface_draw_text_run called outside enter_frame_scope");
        let saved = layout.font_description();
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        layout.set_font_description(Some(&ui_font_desc));
        layout.set_text(text);
        layout.set_attributes(None);
        crate::gtk::set_source(cr, color);
        cr.move_to(rect.x as f64, rect.y as f64);
        super::painted_text::show_layout(cr, layout);
        layout.set_font_description(saved.as_ref());
    }

    /// Overrides the default (which drops styling) — Pango's
    /// `AttrList` can apply all three, matching what
    /// `gtk::terminal::draw_terminal_cells` did per-cell before its
    /// paint moved to `primitives::terminal::paint`. Also forces
    /// `ui_font` now, matching [`Self::surface_draw_text_run`]'s doc
    /// above — the one caller that needs this *not* to happen
    /// (`draw_terminal`'s per-cell glyphs) goes through [`EditorSurface`]
    /// instead of bare `self`.
    #[allow(clippy::too_many_arguments)]
    fn surface_draw_text_run_styled(
        &mut self,
        rect: QRect,
        text: &str,
        color: Color,
        bold: bool,
        italic: bool,
        underline: bool,
        scale_x: f32,
    ) {
        let (cr, layout) = self
            .current_frame_refs()
            .expect("GtkBackend::surface_draw_text_run_styled called outside enter_frame_scope");
        let saved = layout.font_description();
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        layout.set_font_description(Some(&ui_font_desc));
        layout.set_text(text);
        let attrs = pango::AttrList::new();
        if bold {
            attrs.insert(pango::AttrInt::new_weight(pango::Weight::Bold));
        }
        if italic {
            attrs.insert(pango::AttrInt::new_style(pango::Style::Italic));
        }
        if underline {
            attrs.insert(pango::AttrInt::new_underline(pango::Underline::Single));
        }
        layout.set_attributes(Some(&attrs));
        crate::gtk::set_source(cr, color);
        if (scale_x - 1.0).abs() > f32::EPSILON {
            cr.save().ok();
            cr.translate(rect.x as f64, rect.y as f64);
            cr.scale(scale_x as f64, 1.0);
            cr.move_to(0.0, 0.0);
            super::painted_text::show_layout(cr, layout);
            cr.restore().ok();
        } else {
            cr.move_to(rect.x as f64, rect.y as f64);
            super::painted_text::show_layout(cr, layout);
        }
        layout.set_attributes(None);
        layout.set_font_description(saved.as_ref());
    }

    /// Overrides the default (which ignores `role`) — this is the
    /// one real backend where chrome and editor text already resolve to
    /// two genuinely different `pango::FontDescription`s
    /// (`crate::gtk::chrome_font_description(&self.ui_font)` vs
    /// `self.editor_font_pango_string()`), so a `dyn PaintSurface`
    /// caller that only held the trait default could never reach the
    /// chrome one. Saves and restores the layout's font description
    /// around the call, mirroring the save/restore recipe every
    /// `chrome_font_desc`-swapping `draw_*` method in this file already
    /// repeats by hand (e.g. `draw_tree`).
    fn surface_draw_text_run_with_role(
        &mut self,
        rect: QRect,
        text: &str,
        color: Color,
        role: crate::FontRole,
        italic: bool,
    ) {
        let (cr, layout) = self
            .current_frame_refs()
            .expect("GtkBackend::surface_draw_text_run_with_role called outside enter_frame_scope");
        let saved = layout.font_description();
        let desc = match role {
            crate::FontRole::Chrome => crate::gtk::chrome_font_description(&self.ui_font),
            crate::FontRole::Editor => {
                pango::FontDescription::from_string(&self.editor_font_pango_string())
            }
        };
        layout.set_font_description(Some(&desc));
        layout.set_text(text);
        if italic {
            let attrs = pango::AttrList::new();
            attrs.insert(pango::AttrInt::new_style(pango::Style::Italic));
            layout.set_attributes(Some(&attrs));
        } else {
            layout.set_attributes(None);
        }
        crate::gtk::set_source(cr, color);
        cr.move_to(rect.x as f64, rect.y as f64);
        super::painted_text::show_layout(cr, layout);
        layout.set_attributes(None);
        layout.set_font_description(saved.as_ref());
    }

    /// Overrides the default (which assumes the current font
    /// already resolves the fallback family) — `GtkBackend`'s per-frame
    /// editor `pango::Layout` (built fresh every frame by
    /// `gtk/run.rs::render_frame` from `editor_font_pango_string`, with
    /// no fallback appended) is the one real backend where that
    /// assumption is false; see this trait method's own doc for why
    /// macOS/Win-GUI take the default instead. Temporarily wraps `ui_font`
    /// (not the ambient layout font — every real call site is a
    /// chrome primitive's icon glyph, see this method's callers in
    /// `primitives::{panel,palette,context_menu,tree}`) with
    /// [`crate::gtk::with_nerd_font_fallback`] so `text`'s glyph (e.g. a
    /// Nerd Font Private-Use-Area codepoint) resolves even when the
    /// primary family can't cover it, then restores the layout's prior
    /// description.
    fn surface_draw_icon_glyph(&mut self, rect: QRect, text: &str, color: Color) {
        let (cr, layout) = self
            .current_frame_refs()
            .expect("GtkBackend::surface_draw_icon_glyph called outside enter_frame_scope");
        let saved = layout.font_description();
        let ui_font_desc = crate::gtk::chrome_font_description(&self.ui_font);
        let with_fallback = crate::gtk::with_nerd_font_fallback(&ui_font_desc);
        layout.set_font_description(Some(&with_fallback));
        layout.set_text(text);
        layout.set_attributes(None);
        crate::gtk::set_source(cr, color);
        cr.move_to(rect.x as f64, rect.y as f64);
        super::painted_text::show_layout(cr, layout);
        layout.set_font_description(saved.as_ref());
    }

    fn surface_draw_line(&mut self, from: Point, to: Point, color: Color, stroke_width: f32) {
        let (cr, _layout) = self
            .current_frame_refs()
            .expect("GtkBackend::surface_draw_line called outside enter_frame_scope");
        crate::gtk::set_source(cr, color);
        cr.set_line_width(stroke_width as f64);
        cr.move_to(from.x as f64, from.y as f64);
        cr.line_to(to.x as f64, to.y as f64);
        cr.stroke().ok();
    }

    fn surface_push_clip(&mut self, rect: QRect) {
        let (cr, _layout) = self
            .current_frame_refs()
            .expect("GtkBackend::surface_push_clip called outside enter_frame_scope");
        cr.save().ok();
        cr.rectangle(
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
        );
        cr.clip();
    }

    fn surface_pop_clip(&mut self) {
        let (cr, _layout) = self
            .current_frame_refs()
            .expect("GtkBackend::surface_pop_clip called outside enter_frame_scope");
        cr.restore().ok();
    }

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

// ─── Cross-backend validation tests ──────────────────────────────────────────
//
// Phase B.5 Stage 2: prove the same generic `<B: Backend>` paint
// helper that's already validated on `TuiBackend` (B.4 Stage 3b)
// works against `GtkBackend`. This is a compile-only assertion —
// running the draws would require an active cairo Context, which
// belongs in a real GTK test harness. The compile-only proof is
// enough for the trait constraint check.

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{MenuBarItem, TerminalCell, TerminalCursorShape, WidgetId};

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

    #[test]
    fn paint_overlays_compiles_against_gtk_backend() {
        let _: fn(&mut GtkBackend, &Palette, &ListView) = paint_overlays::<GtkBackend>;
    }

    // ── issue #1143: MinimapScale ────────────────────────────────────────

    /// `set_minimap_scale`/`minimap_scale` must actually change the row
    /// pitch `Backend::minimap_layout` resolves — no live cairo frame
    /// needed, since `minimap_layout` is pure geometry (mirrors
    /// `WinBackend`'s own `set_minimap_scale_changes_the_resolved_row_pitch`).
    #[test]
    fn set_minimap_scale_changes_the_resolved_row_pitch() {
        use crate::primitives::minimap::{Minimap, MinimapLine, MinimapScale};

        let mut backend = GtkBackend::new();
        let minimap = Minimap {
            id: WidgetId::new("mm"),
            lines: vec![MinimapLine {
                text: "fn main() {}".to_string(),
                line_idx: 0,
            }],
            syntax_spans: Vec::new(),
            visible_row_start: 0,
            visible_row_count: 1,
            total_buffer_lines: 1,
        };
        let rect = QRect::new(0.0, 0.0, 20.0, 100.0);

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

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

    /// `GtkBackend` declares `app_font_registration: true` and
    /// overrides both `register_font_from_memory` and
    /// `set_nerd_font_fallback` above.
    #[test]
    fn gtk_backend_declares_app_font_registration_capability() {
        let b = GtkBackend::new();
        assert!(
            b.backend_caps().app_font_registration,
            "#1013: GtkBackend must declare app_font_registration now that \
             register_font_from_memory/set_nerd_font_fallback are both overridden"
        );
    }

    // `GtkBackend` has no `fn tray` override, so both halves of the
    // trait default apply: `tray()` returns `None` and
    // `backend_caps().tray` is `false`.

    /// There is no `gtk/tray.rs` and `GtkBackend` has no `fn tray`
    /// override, so both halves of the trait default apply: `tray()`
    /// returns `None` and `backend_caps().tray` is `false`. The 2026-09-26
    /// framework audit flagged this pair as unverified; this pins the
    /// honest answer as a concrete runtime assertion, on top of (not
    /// instead of) `tests/conformance/caps.rs`'s generic source-parsed
    /// "declared ⇔ overridden" check for the `tray` capability across
    /// every backend.
    #[test]
    fn gtk_backend_reports_no_tray_support() {
        let mut b = GtkBackend::new();
        assert!(
            !b.backend_caps().tray,
            "#1131: GtkBackend has no tray() override, so backend_caps().tray must stay false"
        );
        assert!(
            b.tray().is_none(),
            "#1131: GtkBackend::tray() must honestly report Unsupported (None) — \
             there is no gtk/tray.rs backing it"
        );
    }

    /// Garbage bytes are not a font Fontconfig's FreeType backend can
    /// parse — `register_font_from_memory` must report that as `None`,
    /// not a fabricated family, matching `MacBackend`/`WinBackend`'s own
    /// rejection tests for the same input shape.
    #[test]
    fn gtk_backend_register_font_from_memory_rejects_bytes_that_are_not_a_font() {
        let mut b = GtkBackend::new();
        let garbage = [0u8; 64];
        assert!(
            b.register_font_from_memory(&garbage).is_none(),
            "64 zero bytes are not a parseable font — must report None, not a fabricated family"
        );
    }

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

    /// `GtkBackend::new` self-registers the bundled codicon font before
    /// any app code runs, so the family is resolvable for painting with
    /// no app configuration — the GUI half of the contract
    /// `codicon::FONT_FAMILY` documents.
    ///
    /// Deliberately probes with [`crate::gtk::app_font::has_font_family`]
    /// rather than calling `ensure_codicon_registered()` again:
    /// `ensure_codicon_registered()` *performs* the registration on
    /// first call, so asserting its own return value would pass even
    /// if `GtkBackend::new()` never called it — this test's probe must
    /// not be able to do the registration itself, or deleting the
    /// `new()` call site couldn't fail it.
    #[test]
    fn gtk_backend_new_self_registers_the_bundled_codicon_font() {
        let _ = GtkBackend::new();
        assert!(
            crate::gtk::app_font::has_font_family(crate::codicon::FONT_FAMILY),
            "GtkBackend::new() must leave the bundled codicon font registered"
        );
    }

    /// `nerd_fonts_enabled` defaults to `true` on this backend — see the
    /// field's own doc for why that default differs from TUI's. Mirrors
    /// `WinBackend`'s own `nerd_fonts_enabled_defaults_to_true`.
    #[test]
    fn gtk_backend_nerd_fonts_enabled_defaults_to_true() {
        let b = GtkBackend::new();
        assert!(
            b.nerd_fonts_enabled(),
            "icons are on by default on this GUI backend — the bundled \
             codicon font is always available here"
        );
    }

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

    /// A family name nothing is installed under must report `Some(false)`
    /// — a real, answered "no", not `None` ("don't know"). GTK is one of
    /// the backends that can enumerate installed families, so it must
    /// never take the trait's `None` default.
    #[test]
    fn gtk_backend_has_font_family_is_some_false_for_a_name_nothing_is_installed_under() {
        let b = GtkBackend::new();
        assert_eq!(
            b.has_font_family("Definitely Not A Real Font Family Quadraui 1024"),
            Some(false)
        );
    }

    #[test]
    fn gtk_backend_modal_stack_handle_shares_state() {
        let backend = GtkBackend::new();
        let h1 = backend.modal_stack_handle();
        let h2 = backend.modal_stack_handle();
        // Both handles point at the same `RefCell<ModalStack>`.
        h1.borrow_mut()
            .push(WidgetId::new("test:popup"), QRect::new(0.0, 0.0, 10.0, 5.0));
        assert_eq!(h2.borrow().len(), 1);
    }

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

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

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

    #[test]
    fn gtk_backend_is_modal_open_tracks_stack() {
        let backend = GtkBackend::new();
        assert!(!backend.is_modal_open());
        backend
            .modal_stack_handle()
            .borrow_mut()
            .push(WidgetId::new("test:modal"), QRect::new(0.0, 0.0, 10.0, 5.0));
        assert!(backend.is_modal_open());
        backend
            .modal_stack_handle()
            .borrow_mut()
            .pop(&WidgetId::new("test:modal"));
        assert!(!backend.is_modal_open());
    }

    #[test]
    fn gtk_backend_push_event_round_trip() {
        let backend = GtkBackend::new();
        backend.push_event(crate::UiEvent::WindowFocused(true));
        let q = backend.events_handle();
        assert_eq!(q.borrow().len(), 1);
    }

    // ── Background-thread wake ──────────────────────────────────────────

    /// A payload pushed from a background thread through the closure
    /// `Backend::waker()` hands out lands in `poll_events()`'s output as a
    /// `UiEvent::User` — the same `Send + Sync` staging queue every
    /// backend's `waker()` shares (`crate::runtime::UserEventQueue`),
    /// exercised end-to-end against a real `GtkBackend` instance rather
    /// than the queue alone.
    #[test]
    fn waker_payload_reaches_poll_events_as_user_event() {
        let mut backend = GtkBackend::new();
        let waker = Backend::waker(&backend);

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

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

    /// Run `f` while this thread owns the default GLib main context, so
    /// the `glib::MainContext::invoke` inside `waker()` takes its
    /// synchronous path (`g_main_context_invoke_full` calls the closure
    /// inline when the calling thread *is* the context's owner) instead of
    /// queueing an idle source no one in a bare `cargo test` process would
    /// ever dispatch.
    ///
    /// Without this, "did the wake fire?" assertions are a race against
    /// the rest of the harness: `invoke`'s other inline path needs the
    /// context to have *no* owner, and cargo runs these tests in parallel
    /// with others that acquire it for microseconds at a time (any
    /// `poll_events` → `MainContext::iteration`). That lost race showed up
    /// as roughly a 1-in-25 spurious failure of the assertion below.
    /// Acquiring first turns it into the deterministic owner path.
    fn with_owned_main_context<R>(f: impl FnOnce() -> R) -> R {
        let ctx = glib::MainContext::default();
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
        loop {
            if let Ok(_guard) = ctx.acquire() {
                return f();
            }
            assert!(
                std::time::Instant::now() < deadline,
                "another thread held the default GLib main context for 10s"
            );
            std::thread::yield_now();
        }
    }

    /// `set_wake_callback` installs the handle `waker()`'s returned
    /// closure invokes via `glib::MainContext::invoke`; owning the context
    /// for the duration (see [`with_owned_main_context`]) makes that
    /// invocation synchronous, so this asserts without spinning an actual
    /// GTK main loop.
    #[test]
    fn waker_invokes_installed_wake_callback() {
        let backend = GtkBackend::new();
        let called = Rc::new(Cell::new(false));
        let called_from_callback = called.clone();
        backend.set_wake_callback(Rc::new(move || called_from_callback.set(true)));

        let waker = Backend::waker(&backend);
        with_owned_main_context(|| waker(crate::UserPayload::new(())));

        assert!(
            called.get(),
            "waker() must invoke the wake_callback installed via set_wake_callback"
        );
    }

    /// Before `set_wake_callback` is ever called (a `GtkBackend`
    /// constructed directly, never handed to `gtk::run`), `waker()` must
    /// not panic — it silently has nothing to wake.
    #[test]
    fn waker_does_not_panic_before_wake_callback_is_installed() {
        let backend = GtkBackend::new();
        let waker = Backend::waker(&backend);
        waker(crate::UserPayload::new(1_i32));
    }

    /// `request_frame_in` must be callable — before or
    /// after `set_wake_callback` — without panicking. `glib::source::
    /// timeout_add_local_once` only *schedules* the one-shot timer; it
    /// returns immediately without running the main loop, so this is
    /// safe to call from a plain unit test with no GTK application or
    /// running loop behind it, same posture as `waker_does_not_panic_
    /// before_wake_callback_is_installed` above.
    ///
    /// Deliberately doesn't pump `glib::MainContext::default()` to prove
    /// the timer actually *fires*: that context is one process-wide
    /// object shared by every test in this binary, and earlier draft of
    /// this test (`ctx.iteration(true)` in a loop) crashed the whole test
    /// binary (`SIGABRT`, "already acquired by another thread" /
    /// GLib-internal aborts) racing concurrently-running tests for
    /// ownership — mirroring why this file has no analogous "does the
    /// resize-settle timer actually fire" unit test either (see
    /// `gtk::run`'s `RESIZE_TIMER_ID`/`timeout_add_local_once` call):
    /// that tier of proof belongs to a live/example-driven test, not a
    /// `cargo test --lib` unit test contending for the global context.
    #[test]
    fn request_frame_in_does_not_panic_with_or_without_a_wake_callback_installed() {
        // `timeout_add_local_once` panics ("default main context already
        // acquired by another thread") if a parallel test happens to own
        // the default context at that instant — the same race
        // `with_owned_main_context` documents. Own it for the call.
        let backend = GtkBackend::new();
        with_owned_main_context(|| Backend::request_frame_in(&backend, Duration::from_millis(50)));

        let fired = Rc::new(Cell::new(false));
        let fired_from_callback = Rc::clone(&fired);
        backend.set_wake_callback(Rc::new(move || fired_from_callback.set(true)));
        with_owned_main_context(|| Backend::request_frame_in(&backend, Duration::from_millis(50)));
    }

    /// A `waker()` handle is `Send + Sync`, so the last handle can
    /// die on a background thread. Nothing in that drop may touch the
    /// `!Send` `Rc<dyn Fn()>` wake target, because decrementing
    /// `Rc`'s non-atomic refcount from two threads at once is a data
    /// race. The strong count must be untouched by anything the
    /// background thread did, and the drop must not block.
    #[test]
    fn dropping_the_last_waker_handle_off_thread_never_touches_the_wake_callback() {
        let backend = GtkBackend::new();
        let callback: Rc<dyn Fn()> = Rc::new(|| {});
        backend.set_wake_callback(Rc::clone(&callback));
        let installed = Rc::strong_count(&callback);
        assert_eq!(installed, 2, "one clone here, one in the thread-local");

        let waker = Backend::waker(&backend);
        std::thread::spawn(move || drop(waker))
            .join()
            .expect("dropping the last waker handle off-thread must not panic or hang");

        assert_eq!(
            Rc::strong_count(&callback),
            installed,
            "a background thread dropping its waker handle must not touch the UI thread's Rc"
        );

        // ...and the wake target is still installed and callable here.
        assert!(super::wake_callback_for(backend.wake_id).is_some());
    }

    /// Two backends on one thread keep separate wake targets — the
    /// thread-local map is shared, so the [`WakeId`] keying is what stops
    /// one backend's `waker()` from firing another's callback.
    #[test]
    fn each_backend_wakes_only_its_own_callback() {
        let first = GtkBackend::new();
        let second = GtkBackend::new();
        let first_calls = Rc::new(Cell::new(0));
        let second_calls = Rc::new(Cell::new(0));
        let f = first_calls.clone();
        first.set_wake_callback(Rc::new(move || f.set(f.get() + 1)));
        let s = second_calls.clone();
        second.set_wake_callback(Rc::new(move || s.set(s.get() + 1)));

        with_owned_main_context(|| Backend::waker(&second)(crate::UserPayload::new(())));

        assert_eq!(first_calls.get(), 0, "first backend must not be woken");
        assert_eq!(second_calls.get(), 1, "second backend must be woken once");
    }

    /// Dropping a `GtkBackend` releases its wake-target slot, so the
    /// installed closure — which in `gtk::run::run_with` captures the
    /// whole app/backend graph — doesn't outlive the backend, and a
    /// long-lived process that builds many backends doesn't accumulate
    /// them.
    #[test]
    fn dropping_the_backend_releases_its_wake_callback_slot() {
        let callback: Rc<dyn Fn()> = Rc::new(|| {});
        let backend = GtkBackend::new();
        let wake_id = backend.wake_id;
        backend.set_wake_callback(Rc::clone(&callback));
        assert_eq!(Rc::strong_count(&callback), 2);

        drop(backend);

        assert_eq!(
            Rc::strong_count(&callback),
            1,
            "the thread-local's clone must be released with the backend"
        );
        assert!(super::wake_callback_for(wake_id).is_none());
    }

    /// GTK reserves room for its `ScrolledWindow` overlay
    /// scrollbar so a caller's content viewport width
    /// (`rect.width - backend.scrollbar_reserve()`) never renders text
    /// behind the overlay — see the trait default (0.0) that TUI relies
    /// on instead.
    #[test]
    fn gtk_backend_scrollbar_reserve_is_nonzero() {
        let backend = GtkBackend::new();
        assert_eq!(Backend::scrollbar_reserve(&backend), 8.0);
    }

    /// With no window set (the state of every unit test and every
    /// backend before `gtk::run::activate` calls `set_window`),
    /// `begin_window_drag` must no-op rather than panic.
    #[test]
    fn gtk_backend_begin_window_drag_false_without_window() {
        let mut backend = GtkBackend::new();
        assert!(!Backend::begin_window_drag(&mut backend));
    }

    /// `begin_window_drag` also no-ops when a window is present but
    /// no press was ever stashed (e.g. called from a non-mouse-driven
    /// path) — there's no real device/timestamp to hand GDK.
    #[test]
    fn gtk_backend_begin_window_drag_false_without_pending_press() {
        let mut backend = GtkBackend::new();
        assert!(backend.pending_window_press.is_none());
        assert!(!Backend::begin_window_drag(&mut backend));
    }

    /// `armed_window_drag_origin` must be `None` when nothing has been
    /// armed (the state of every unit test and every fresh backend).
    #[test]
    fn gtk_backend_armed_window_drag_origin_none_when_unarmed() {
        let backend = GtkBackend::new();
        assert!(backend.armed_window_drag_origin().is_none());
    }

    /// `discard_armed_window_drag` clears an armed request, and the
    /// origin reads back `None` afterwards — this is what
    /// `gtk/run.rs`'s `connect_released` relies on to stop a plain
    /// click (or the first half of a double-click) from being committed
    /// by a later, unrelated hover-motion event.
    #[test]
    fn gtk_backend_discard_armed_window_drag_clears_state() {
        let mut backend = GtkBackend::new();
        // No real `gdk::Device` is constructible headlessly, so this test
        // exercises the discard path directly against the private field
        // rather than going through `Backend::begin_window_drag` (which
        // requires a real window).
        assert!(backend.armed_window_drag_origin().is_none());
        backend.discard_armed_window_drag();
        assert!(backend.armed_window_drag_origin().is_none());
    }

    /// `try_commit_window_drag` must no-op (rather than panic) with no
    /// window set, mirroring `begin_window_drag`'s no-window no-op.
    #[test]
    fn gtk_backend_try_commit_window_drag_false_without_window() {
        let mut backend = GtkBackend::new();
        assert!(!backend.try_commit_window_drag(0.0, 0.0));
    }

    /// `try_commit_window_drag` must no-op when a window is present but
    /// nothing is armed (e.g. `connect_motion` fires before any
    /// title-bar press ever called `begin_window_drag`).
    #[test]
    fn gtk_backend_try_commit_window_drag_false_without_armed_request() {
        let mut backend = GtkBackend::new();
        assert!(!backend.armed_window_drag.is_armed());
        assert!(!backend.try_commit_window_drag(0.0, 0.0));
    }

    /// `window_drag_threshold_px` must fall back to GTK's documented
    /// default (8px) rather than panic when no window/display is
    /// available yet (every unit test).
    #[test]
    fn gtk_backend_window_drag_threshold_px_defaults_without_window() {
        let backend = GtkBackend::new();
        assert_eq!(backend.window_drag_threshold_px(), 8.0);
    }

    /// With no window set, `toggle_window_maximize` must no-op
    /// rather than panic.
    #[test]
    fn gtk_backend_toggle_window_maximize_false_without_window() {
        let mut backend = GtkBackend::new();
        assert!(!Backend::toggle_window_maximize(&mut backend));
    }

    /// `is_maximized`/`set_decorated` guard on `self.window` the
    /// same way every other `WindowControl` method here does — no real
    /// `gtk4::Window` exists in a headless unit test, so both must report
    /// `Unsupported` rather than panic.
    #[test]
    fn gtk_backend_is_maximized_err_without_window() {
        let backend = GtkBackend::new();
        assert!(matches!(
            crate::backend::WindowControl::is_maximized(&backend),
            Err(BackendError::Unsupported)
        ));
    }

    #[test]
    fn gtk_backend_set_decorated_err_without_window() {
        let mut backend = GtkBackend::new();
        assert!(matches!(
            crate::backend::WindowControl::set_decorated(&mut backend, false),
            Err(BackendError::Unsupported)
        ));
    }

    /// With no window set (every unit test), `begin_window_resize`
    /// must no-op rather than panic, mirroring `begin_window_drag`'s
    /// no-window guard.
    #[test]
    fn gtk_backend_begin_window_resize_false_without_window() {
        let mut backend = GtkBackend::new();
        assert!(!Backend::begin_window_resize(
            &mut backend,
            ResizeEdge::South
        ));
    }

    /// `begin_window_resize` also no-ops when a window is present but
    /// no press was ever stashed — there's no real device/timestamp to hand
    /// GDK, same rationale as `begin_window_drag`'s equivalent guard.
    #[test]
    fn gtk_backend_begin_window_resize_false_without_pending_press() {
        let mut backend = GtkBackend::new();
        assert!(backend.pending_window_press.is_none());
        assert!(!Backend::begin_window_resize(
            &mut backend,
            ResizeEdge::SouthEast
        ));
    }

    /// With no window set, `set_cursor` must no-op rather than panic.
    #[test]
    fn gtk_backend_set_cursor_false_without_window() {
        let mut backend = GtkBackend::new();
        assert!(!Backend::set_cursor(&mut backend, PointerShape::Default));
        assert!(!Backend::set_cursor(
            &mut backend,
            PointerShape::Resize(ResizeEdge::North)
        ));
    }

    /// `ResizeEdge` maps 1:1 onto `gdk4::SurfaceEdge` — exercise
    /// every variant so an accidental swap (e.g. `NorthEast` <->
    /// `SouthWest`) fails loudly instead of silently resizing the wrong
    /// corner on a real compositor.
    #[test]
    fn resize_edge_to_surface_edge_maps_every_variant() {
        // Iterates the shared enum-walk scaffold (`desktop::ALL_RESIZE_EDGES`)
        // instead of hand-listing all 8 variants, so a new `ResizeEdge`
        // variant added there is automatically exercised here too.
        let expected = [
            gdk::SurfaceEdge::North,
            gdk::SurfaceEdge::South,
            gdk::SurfaceEdge::East,
            gdk::SurfaceEdge::West,
            gdk::SurfaceEdge::NorthEast,
            gdk::SurfaceEdge::NorthWest,
            gdk::SurfaceEdge::SouthEast,
            gdk::SurfaceEdge::SouthWest,
        ];
        for (edge, expected) in crate::desktop::ALL_RESIZE_EDGES.iter().zip(expected.iter()) {
            assert_eq!(resize_edge_to_surface_edge(*edge), *expected);
        }
    }

    /// `PointerShape` -> GTK cursor-name mapping covers every
    /// variant with the expected CSS Basic UI keyword.
    #[test]
    fn pointer_shape_cursor_name_maps_every_variant() {
        // Iterates `desktop::all_pointer_shapes()` instead of
        // hand-listing all 9 `Default` + `Resize(edge)` combinations.
        let expected = [
            "default",
            "n-resize",
            "s-resize",
            "e-resize",
            "w-resize",
            "ne-resize",
            "nw-resize",
            "se-resize",
            "sw-resize",
        ];
        for (shape, expected) in crate::desktop::all_pointer_shapes()
            .iter()
            .zip(expected.iter())
        {
            assert_eq!(pointer_shape_cursor_name(*shape), *expected);
        }
    }

    /// The registry itself now lives in `BackendCore` — its
    /// `len()`s aren't reachable from here anymore, so this observes the
    /// same round trip behaviourally: registering makes the binding
    /// match, unregistering makes it stop matching.
    #[test]
    fn gtk_backend_register_accelerator_round_trip() {
        let mut backend = GtkBackend::new();
        backend.register_accelerator(&Accelerator {
            id: AcceleratorId::new("test.save"),
            binding: KeyBinding::Save,
            scope: AcceleratorScope::Global,
            label: None,
        });
        assert_eq!(
            backend.match_keypress(
                &crate::Key::Char('s'),
                crate::Modifiers {
                    ctrl: true,
                    ..Default::default()
                }
            ),
            Some(AcceleratorId::new("test.save"))
        );
        backend.unregister_accelerator(&AcceleratorId::new("test.save"));
        assert_eq!(
            backend.match_keypress(
                &crate::Key::Char('s'),
                crate::Modifiers {
                    ctrl: true,
                    ..Default::default()
                }
            ),
            None
        );
    }

    /// Regression test for B5b.2: parse_key_binding correctness for the
    /// two terminal-shortcut strings. If `<C-t>` parses to a binding that
    /// matches Ctrl+Shift+T (or vice versa), the accelerator dispatch
    /// will flip.
    #[test]
    fn parse_binding_terminal_strings_distinct() {
        let p_ct = crate::parse_key_binding("<C-t>").expect("<C-t>");
        assert!(p_ct.modifiers.ctrl);
        assert!(
            !p_ct.modifiers.shift,
            "<C-t> must NOT have shift, got {:?}",
            p_ct
        );
        assert_eq!(p_ct.key, "t");

        let p_cst = crate::parse_key_binding("<C-S-t>").expect("<C-S-t>");
        assert!(p_cst.modifiers.ctrl);
        assert!(
            p_cst.modifiers.shift,
            "<C-S-t> must have shift, got {:?}",
            p_cst
        );
        assert_eq!(p_cst.key, "t");
    }

    /// Regression test: the lookup used by the GTK key handler must
    /// return distinct ids for `<C-t>` vs `<C-S-t>`. Previously the
    /// inputs were swapped at runtime — Ctrl+T fired the maximize
    /// action and Ctrl+Shift+T fired the open action.
    #[test]
    fn gtk_backend_match_keypress_distinguishes_ctrl_vs_ctrl_shift() {
        let mut backend = GtkBackend::new();
        backend.register_accelerator(&Accelerator {
            id: AcceleratorId::new("gtk.panel.open_terminal"),
            binding: KeyBinding::Literal("<C-t>".into()),
            scope: AcceleratorScope::Global,
            label: None,
        });
        backend.register_accelerator(&Accelerator {
            id: AcceleratorId::new("terminal.toggle_maximize"),
            binding: KeyBinding::Literal("<C-S-t>".into()),
            scope: AcceleratorScope::Global,
            label: None,
        });

        let ctrl_only = crate::Modifiers {
            ctrl: true,
            shift: false,
            alt: false,
            cmd: false,
        };
        let ctrl_shift = crate::Modifiers {
            ctrl: true,
            shift: true,
            alt: false,
            cmd: false,
        };

        // Ctrl+T → open_terminal
        let open = backend.match_keypress(&crate::Key::Char('t'), ctrl_only);
        assert_eq!(
            open.as_ref().map(|i| i.as_str()),
            Some("gtk.panel.open_terminal"),
            "Ctrl+T should match open_terminal, got {:?}",
            open
        );

        // Ctrl+Shift+T → toggle_maximize
        let max = backend.match_keypress(&crate::Key::Char('t'), ctrl_shift);
        assert_eq!(
            max.as_ref().map(|i| i.as_str()),
            Some("terminal.toggle_maximize"),
            "Ctrl+Shift+T should match terminal.toggle_maximize, got {:?}",
            max
        );

        // Also try with the GDK-style uppercase 'T' for the shift case —
        // gdk_key_to_quadraui_key returns Key::Char('T') when shift is held.
        let max_upper = backend.match_keypress(&crate::Key::Char('T'), ctrl_shift);
        assert_eq!(
            max_upper.as_ref().map(|i| i.as_str()),
            Some("terminal.toggle_maximize"),
            "Ctrl+Shift+T (with uppercase T) should match terminal.toggle_maximize, got {:?}",
            max_upper
        );
    }

    /// A `FieldKind::TextArea` must measure exactly one row — matching
    /// what `gtk::form::draw_form` actually paints — so a click on the
    /// field painted immediately below it hits that field, not the
    /// `TextArea`'s hit region. The layout measurer and painter must
    /// track each other: before the fix, `GtkBackend::form_layout` sized
    /// `TextArea` as `row_h * visible_rows`, while the painter only ever
    /// advanced one `row_h` per field, causing a mismatch.
    #[test]
    fn gtk_form_layout_textarea_does_not_swallow_the_next_fields_row() {
        use crate::primitives::form::{FieldKind, Form, FormField, FormHit};
        use crate::types::StyledText;

        let mut backend = GtkBackend::new();
        // No Pango context — fallback char-width path is exercised.
        backend.current_char_width = 8.0;
        backend.current_line_height = 20.0;

        let form = Form {
            id: WidgetId::new("settings"),
            fields: vec![
                FormField {
                    id: WidgetId::new("notes"),
                    label: StyledText::plain("Notes"),
                    kind: FieldKind::TextArea {
                        value: "line one".into(),
                        placeholder: String::new(),
                        cursor: None,
                        visible_rows: 4,
                    },
                    hint: StyledText::default(),
                    disabled: false,
                    validation: None,
                },
                FormField {
                    id: WidgetId::new("enabled"),
                    label: StyledText::plain("Enabled"),
                    kind: FieldKind::Toggle { value: true },
                    hint: StyledText::default(),
                    disabled: false,
                    validation: None,
                },
            ],
            focused_field: None,
            scroll_offset: 0,
            has_focus: false,
        };

        let rect = QRect::new(0.0, 0.0, 400.0, 200.0);
        let layout = backend.form_layout(rect, &form);

        assert_eq!(
            layout.visible_fields.len(),
            2,
            "both fields should be visible"
        );
        let notes = &layout.visible_fields[0];
        let enabled = &layout.visible_fields[1];

        let row_h = crate::primitives::layout_metrics::form_row_height(backend.current_line_height);
        assert_eq!(
            notes.bounds.height, row_h,
            "TextArea must measure one row_h, matching gtk::form::draw_form's single-row paint"
        );

        // A click at the centre of the field painted right below the
        // TextArea must hit that field, not the TextArea — pre-fix this
        // resolved to "notes" for the whole `visible_rows * row_h` band.
        let cx = enabled.bounds.x + enabled.bounds.width * 0.5;
        let cy = enabled.bounds.y + enabled.bounds.height * 0.5;
        assert_eq!(
            layout.hit_test(cx, cy),
            FormHit::Field(WidgetId::new("enabled")),
            "click below the TextArea should hit the field actually painted there"
        );
    }

    /// `FieldKind::Toolbar` fields must produce per-button `FormItemMeasure`
    /// entries so that `FormLayout::hit_test` resolves a click to the
    /// button's action id (not the field id). This is the GTK side of the
    /// paint↔click round-trip test that Blocker 2 in the review was about.
    #[test]
    fn gtk_form_layout_toolbar_field_produces_per_button_hit_regions() {
        use crate::primitives::form::{FieldKind, Form, FormField, FormHit};
        use crate::primitives::toolbar::{Toolbar, ToolbarButton};
        use crate::types::StyledText;

        let mut backend = GtkBackend::new();
        // No Pango context — fallback char-width path is exercised.
        backend.current_char_width = 8.0;
        backend.current_line_height = 20.0;

        let form = Form {
            id: WidgetId::new("settings"),
            fields: vec![FormField {
                id: WidgetId::new("actions"),
                label: StyledText::plain(""),
                kind: FieldKind::Toolbar(Toolbar {
                    id: WidgetId::new("tb"),
                    buttons: vec![
                        ToolbarButton::Action {
                            id: WidgetId::new("reset"),
                            label: "Reset".into(),
                            icon: None,
                            key_hint: None,
                            enabled: true,
                            is_active: false,
                            tooltip: String::new(),
                        },
                        ToolbarButton::Action {
                            id: WidgetId::new("export"),
                            label: "Export".into(),
                            icon: None,
                            key_hint: None,
                            enabled: true,
                            is_active: false,
                            tooltip: String::new(),
                        },
                    ],
                    bg: None,
                    focused_index: None,
                }),
                hint: StyledText::default(),
                disabled: false,
                validation: None,
            }],
            focused_field: None,
            scroll_offset: 0,
            has_focus: false,
        };

        let rect = QRect::new(0.0, 0.0, 400.0, 80.0);
        let layout = backend.form_layout(rect, &form);

        // Must have exactly one visible field.
        assert_eq!(layout.visible_fields.len(), 1, "expected one visible field");
        let vf = &layout.visible_fields[0];

        // Must have per-button item_bounds (not empty).
        assert!(
            !vf.item_bounds.is_empty(),
            "FieldKind::Toolbar must produce non-empty item_bounds on GTK"
        );
        assert_eq!(
            vf.item_bounds.len(),
            2,
            "expected 2 item_bounds for 2 action buttons"
        );

        // item_bounds ids must match action ids.
        assert_eq!(vf.item_bounds[0].0.as_str(), "reset");
        assert_eq!(vf.item_bounds[1].0.as_str(), "export");

        // Clicking near the left of the first button should resolve to "reset".
        let first_btn = vf.item_bounds[0].1;
        let hit = layout.hit_test(first_btn.x + 1.0, first_btn.y + 1.0);
        assert_eq!(
            hit,
            FormHit::Field(WidgetId::new("reset")),
            "click on first button must resolve to 'reset', not 'actions' (the field id)"
        );

        // Clicking near the left of the second button should resolve to "export".
        let second_btn = vf.item_bounds[1].1;
        let hit2 = layout.hit_test(second_btn.x + 1.0, second_btn.y + 1.0);
        assert_eq!(
            hit2,
            FormHit::Field(WidgetId::new("export")),
            "click on second button must resolve to 'export'"
        );
    }

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

    fn text_region(id: &str, x: f32, y: f32, w: f32, h: f32, lines: Vec<&str>) -> TextRegion {
        TextRegion {
            id: WidgetId::new(id),
            bounds: QRect::new(x, y, w, h),
            lines: lines.into_iter().map(|s| s.to_string()).collect(),
        }
    }

    #[test]
    fn gtk_text_regions_accumulated_per_frame() {
        let mut backend = GtkBackend::new();
        backend.register_text_region(text_region("r1", 0.0, 0.0, 100.0, 50.0, vec![]));
        backend.register_text_region(text_region("r2", 0.0, 50.0, 100.0, 50.0, vec![]));
        assert_eq!(backend.text_regions().len(), 2);
        assert_eq!(backend.text_regions()[0].id.as_str(), "r1");
        assert_eq!(backend.text_regions()[1].id.as_str(), "r2");
    }

    #[test]
    fn gtk_text_regions_cleared_on_begin_frame() {
        let mut backend = GtkBackend::new();
        backend.register_text_region(text_region("r", 0.0, 0.0, 200.0, 100.0, vec![]));
        assert_eq!(backend.text_regions().len(), 1);
        backend.begin_frame(crate::Viewport::new(800.0, 600.0, 1.0));
        assert_eq!(
            backend.text_regions().len(),
            0,
            "text_regions must be cleared on begin_frame"
        );
    }

    #[test]
    fn gtk_active_selection_set_and_cleared() {
        let mut backend = GtkBackend::new();
        assert!(backend.active_text_selection().is_none());

        backend.set_active_text_selection(
            WidgetId::new("body"),
            Point { x: 10.0, y: 0.0 },
            Point { x: 80.0, y: 16.0 },
        );
        assert!(backend.active_text_selection().is_some());

        backend.clear_selection_display();
        assert!(backend.active_text_selection().is_none());
    }

    #[test]
    fn gtk_clear_text_selection_ends_drag() {
        let mut backend = GtkBackend::new();
        // Arm a TextSelection drag.
        backend.drag_state_handle().borrow_mut().begin(
            crate::dispatch::DragTarget::TextSelection {
                region: WidgetId::new("body"),
                anchor: Point { x: 0.0, y: 0.0 },
            },
        );
        backend.set_active_text_selection(
            WidgetId::new("body"),
            Point { x: 0.0, y: 0.0 },
            Point { x: 50.0, y: 0.0 },
        );
        assert!(backend.drag_state_handle().borrow().is_active());

        backend.clear_text_selection();
        assert!(backend.active_text_selection().is_none());
        assert!(
            !backend.drag_state_handle().borrow().is_active(),
            "clear_text_selection must also end the drag"
        );
    }

    #[test]
    fn gtk_clear_selection_display_does_not_end_drag() {
        let mut backend = GtkBackend::new();
        backend.drag_state_handle().borrow_mut().begin(
            crate::dispatch::DragTarget::TextSelection {
                region: WidgetId::new("body"),
                anchor: Point { x: 0.0, y: 0.0 },
            },
        );
        backend.set_active_text_selection(
            WidgetId::new("body"),
            Point { x: 0.0, y: 0.0 },
            Point { x: 50.0, y: 0.0 },
        );
        backend.clear_selection_display();
        // Drag should still be active — clear_selection_display only removes
        // the highlight, not the drag state.
        assert!(
            backend.drag_state_handle().borrow().is_active(),
            "clear_selection_display must NOT end the drag"
        );
    }

    #[test]
    fn gtk_extract_selection_text_single_row() {
        // Region at (0,0), 200×16px. char_width=8, line_height=16.
        // Anchor at x=0 (col 0), focus at x=40 (col 5 in cell space).
        // text_selection_line_range adds +1 to focus col (half-open),
        // so the extracted range is cols 0..6 = "Hello,"
        let mut backend = GtkBackend::new();
        backend.current_line_height = 16.0;
        backend.current_char_width = 8.0;
        backend.register_text_region(text_region(
            "body",
            0.0,
            0.0,
            200.0,
            16.0,
            vec!["Hello, world!"],
        ));
        backend.set_active_text_selection(
            WidgetId::new("body"),
            Point { x: 0.0, y: 0.0 },  // col 0
            Point { x: 40.0, y: 0.0 }, // col 5 → range 0..6
        );
        let text = backend.extract_selection_text();
        // cols 0..6 of "Hello, world!" = "Hello," (6 chars)
        assert_eq!(
            text, "Hello,",
            "expected first 6 chars (cols 0..6), got {text:?}"
        );
    }

    #[test]
    fn gtk_extract_selection_text_multi_row() {
        // Region at (0,0), 200×32px. char_width=8, line_height=16.
        // Row 0: "ABCDE", Row 1: "FGHIJ".
        let mut backend = GtkBackend::new();
        backend.current_line_height = 16.0;
        backend.current_char_width = 8.0;
        backend.register_text_region(text_region(
            "body",
            0.0,
            0.0,
            200.0,
            32.0,
            vec!["ABCDE", "FGHIJ"],
        ));
        backend.set_active_text_selection(
            WidgetId::new("body"),
            Point { x: 0.0, y: 0.0 },   // anchor: col 0, row 0
            Point { x: 40.0, y: 16.0 }, // focus: col 5, row 1
        );
        let text = backend.extract_selection_text();
        // First row: cols 0..25 (region end) → "ABCDE" trimmed.
        // Last row: cols 0..5 → "FGHIJ".
        assert!(
            text.contains("ABCDE"),
            "expected ABCDE in result, got {text:?}"
        );
        assert!(
            text.contains("FGHIJ"),
            "expected FGHIJ in result, got {text:?}"
        );
    }

    #[test]
    fn gtk_extract_selection_text_empty_when_no_selection() {
        let backend = GtkBackend::new();
        assert_eq!(backend.extract_selection_text(), "");
    }

    #[test]
    fn gtk_extract_selection_text_empty_when_no_lines() {
        let mut backend = GtkBackend::new();
        backend.current_line_height = 16.0;
        backend.current_char_width = 8.0;
        // Register region with no lines (TUI-only path)
        backend.register_text_region(text_region("body", 0.0, 0.0, 200.0, 32.0, vec![]));
        backend.set_active_text_selection(
            WidgetId::new("body"),
            Point { x: 0.0, y: 0.0 },
            Point { x: 40.0, y: 0.0 },
        );
        assert_eq!(
            backend.extract_selection_text(),
            "",
            "empty lines → empty extraction"
        );
    }

    /// Verify that `select_all_text_region` sets the full viewport bounds as
    /// the active selection. This directly tests the core acceptance criterion:
    /// "Ctrl-A sets the expected full range; extracted text == full region
    /// content."
    #[test]
    fn gtk_select_all_text_region_sets_full_bounds() {
        let mut backend = GtkBackend::new();
        backend.register_text_region(text_region("body", 0.0, 0.0, 10.0, 5.0, vec![]));
        assert!(
            backend.select_all_text_region(),
            "should return true when exactly one region is registered"
        );
        let sel = backend
            .active_text_selection()
            .expect("selection should be active after select_all_text_region");
        assert_eq!(
            sel.anchor,
            Point { x: 0.0, y: 0.0 },
            "anchor should be at top-left of region bounds"
        );
        assert_eq!(
            sel.focus,
            Point { x: 10.0, y: 5.0 },
            "focus should be at bottom-right of region bounds"
        );
    }

    /// Verify that `select_all_text_region` returns `false` when no regions
    /// are registered, and leaves no selection active.
    #[test]
    fn gtk_select_all_text_region_returns_false_when_no_regions() {
        let mut backend = GtkBackend::new();
        assert!(
            !backend.select_all_text_region(),
            "should return false with no registered regions"
        );
        assert!(
            backend.active_text_selection().is_none(),
            "no selection should be set when select_all returns false"
        );
    }

    #[test]
    fn gtk_selection_highlight_geometry_single_row() {
        // Verify that selection highlight produces non-empty ranges for a
        // simple single-row selection. We test via text_selection_line_range
        // since we cannot drive a real Cairo context in unit tests.
        //
        // Region at (10, 20), 200×16px. char_width=8, line_height=16.
        // Anchor (x=10, y=20) = col 0 in cell space.
        // Focus  (x=50, y=20) = col 5 in cell space.
        let line_h = 16.0_f32;
        let char_w = 8.0_f32;
        let bounds = QRect::new(10.0, 20.0, 200.0, 16.0);
        let anchor = Point { x: 10.0, y: 20.0 };
        let focus = Point { x: 50.0, y: 20.0 };

        let bx = bounds.x;
        let by = bounds.y;
        let cell_bounds =
            crate::event::Rect::new(0.0, 0.0, bounds.width / char_w, bounds.height / line_h);
        let anchor_cell = Point {
            x: (anchor.x - bx) / char_w,
            y: (anchor.y - by) / line_h,
        };
        let focus_cell = Point {
            x: (focus.x - bx) / char_w,
            y: (focus.y - by) / line_h,
        };
        let ranges =
            crate::dispatch::text_selection_line_range(anchor_cell, focus_cell, cell_bounds);

        // text_selection_line_range adds +1 to focus col (half-open range).
        // focus at x=50 → cell col 5; col_end = 5 + 1 = 6.
        assert_eq!(ranges.len(), 1, "single-row selection → 1 range entry");
        let (row_cell, col_start, col_end) = ranges[0];
        assert_eq!(row_cell, 0, "row should be cell row 0");
        assert_eq!(col_start, 0.0, "col_start should be 0");
        assert_eq!(col_end, 6.0, "col_end = focus_col(5) + 1 = 6 (half-open)");

        // Verify pixel coordinates: 6 cols × 8px = 48px wide.
        let px_x = bounds.x as f64 + col_start as f64 * char_w as f64;
        let px_y = bounds.y as f64 + row_cell as f64 * line_h as f64;
        let px_w = (col_end - col_start) as f64 * char_w as f64;
        assert!(
            (px_x - 10.0).abs() < 0.5,
            "pixel x should be 10, got {px_x}"
        );
        assert!(
            (px_y - 20.0).abs() < 0.5,
            "pixel y should be 20, got {px_y}"
        );
        assert!(
            (px_w - 48.0).abs() < 0.5,
            "pixel width should be 48 (6 cols × 8px), got {px_w}"
        );
    }

    /// `apply_selection_highlight`'s real Cairo paint, checked against a
    /// headless `ImageSurface` — the pixel-level counterpart to
    /// `gtk_selection_highlight_geometry_single_row`'s pure-math version.
    /// This test verifies that the method resolves rects via
    /// `BackendCore::selection_highlight_rects` and colour via
    /// `Theme::text_selection_highlight`, painting the same pixels as
    /// before that refactoring.
    #[test]
    fn gtk_apply_selection_highlight_paints_over_the_background() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        const W: i32 = 100;
        // Two rows tall so there's an unselected row below the selected
        // one to probe as a "must stay untouched" control.
        const H: i32 = 40;

        let mut backend = GtkBackend::new();
        backend.set_current_line_height(20.0);
        backend.set_current_char_width(10.0);
        backend.register_text_region(TextRegion {
            id: WidgetId::new("body"),
            bounds: QRect::new(0.0, 0.0, W as f32, H as f32),
            lines: vec!["hello world".to_string()],
        });
        // Anchor/focus both land in row 0 (y < 20) — only the top row is
        // selected.
        backend.set_active_text_selection(
            WidgetId::new("body"),
            Point::new(0.0, 0.0),
            Point::new(50.0, 1.0),
        );

        let mut surface = ImageSurface::create(Format::ARgb32, W, H).expect("create ImageSurface");
        {
            let cr = Context::new(&surface).expect("Context::new");
            // Flat, glyph-free background fill so any probe pixel is
            // unambiguous — mirrors the macOS twin's `BG` fill.
            cr.set_source_rgb(10.0 / 255.0, 10.0 / 255.0, 10.0 / 255.0);
            cr.paint().ok();
        }
        surface.flush();

        let before = pixel_argb(&mut surface, 5, 5);
        assert_eq!(
            before,
            (10, 10, 10),
            "the probe pixel must sit on the flat background fill before painting"
        );

        {
            let cr = Context::new(&surface).expect("Context::new");
            backend.apply_selection_highlight(&cr);
        }
        surface.flush();

        let after = pixel_argb(&mut surface, 5, 5);
        assert_ne!(
            before, after,
            "apply_selection_highlight must paint over the background at a selected pixel"
        );
        // The highlight is translucent blue (`Theme::text_selection_highlight`)
        // — blue must rise noticeably.
        assert!(
            after.2 > before.2 + 15,
            "blue channel must rise noticeably after painting the highlight, before={before:?} after={after:?}"
        );

        let outside = pixel_argb(&mut surface, 5, 25);
        assert_eq!(
            outside, before,
            "a pixel in the unselected second row must stay untouched"
        );
    }

    /// ARGB32 is little-endian `B, G, R, A` per Cairo's own convention
    /// (matches every other `surface.data()` probe in this module).
    fn pixel_argb(surface: &mut pangocairo::cairo::ImageSurface, x: i32, y: i32) -> (u8, u8, u8) {
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        let off = y as usize * stride + x as usize * 4;
        (data[off + 2], data[off + 1], data[off])
    }

    /// `menu_bar_layout` must force `ui_font` onto whichever layout it
    /// resolves, so the resolved object's own font no longer reaches the
    /// measurement. Outside vs. inside a frame scope with a
    /// wildly-different editor font (`"Sans 8"` vs. `"Sans 40"`) must
    /// measure *identically*, because both paths measure `ui_font`
    /// (`"Sans 11"` by default), not whatever the resolved layout's own
    /// font description says.
    #[test]
    fn gtk_backend_menu_bar_layout_ignores_resolved_layouts_own_font() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let surface = ImageSurface::create(Format::ARgb32, 400, 40).expect("create ImageSurface");
        let cr = Context::new(&surface).expect("Context::new");

        // pango 0.22 (gtk4 0.11 bump) tightened
        // `Context::set_font_description` from `Option<&FontDescription>`
        // to `&FontDescription` — every call site below through this test
        // module drops the now-redundant `Some(...)` wrapper.
        // `Layout::set_font_description` is unaffected and keeps `Option`.
        let small_ctx = pangocairo::functions::create_context(&cr);
        small_ctx.set_font_description(&pango::FontDescription::from_string("Sans 8"));

        let large_ctx = pangocairo::functions::create_context(&cr);
        large_ctx.set_font_description(&pango::FontDescription::from_string("Sans 40"));
        let large_layout = pango::Layout::new(&large_ctx);

        let mut backend = GtkBackend::new();
        backend.set_pango_context(small_ctx);

        let bar = MenuBar {
            id: WidgetId::new("test:menu-bar"),
            items: vec![MenuBarItem {
                id: WidgetId::new("test:menu-bar:file"),
                label: "&File".to_string(),
                disabled: false,
                submenu: None,
            }],
            open_item: None,
            focused_item: None,
        };
        let rect = QRect::new(0.0, 0.0, 400.0, 20.0);

        // Outside any frame scope: resolves to the small `pango_ctx`
        // object, but its font must be ignored in favour of `ui_font`.
        let small_ctx_width = backend.menu_bar_layout(rect, &bar).visible_items[0]
            .bounds
            .width;

        // Inside a frame scope with a much larger live layout: its own
        // "Sans 40" font must likewise be ignored in favour of `ui_font`.
        let large_layout_width = backend.enter_frame_scope(&cr, &large_layout, |b| {
            b.menu_bar_layout(rect, &bar).visible_items[0].bounds.width
        });

        assert!(
            (large_layout_width - small_ctx_width).abs() < 0.5,
            "menu_bar_layout must measure with `ui_font` regardless of \
             which layout object it resolves to: small_ctx_width={small_ctx_width}, \
             large_layout_width={large_layout_width}"
        );
    }

    /// `measure_char_width_px` must preserve the true
    /// fractional glyph advance instead of `pixel_size()`'s whole-pixel
    /// rounding. As `measure_char_width_px_matches_pixel_size_for_the_real_editor_font`
    /// below demonstrates (automated, not hand-checked), the real editor
    /// font resolves to exactly-integral advances at every commonly
    /// configured size on this build host, so comparing the fixed
    /// measurement against the old buggy one on a plain layout of that
    /// font would pass vacuously and prove nothing. A letter-spacing
    /// attribute forces a deterministically non-integral advance on *any*
    /// host/font, independent of hinting — which is what makes the second
    /// assertion below able to fail if `measure_char_width_px` is ever
    /// regressed back to `layout.pixel_size()` on a single glyph.
    #[test]
    fn measure_char_width_px_preserves_fractional_advance_forced_by_letter_spacing() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let surface = ImageSurface::create(Format::ARgb32, 4000, 40).expect("create ImageSurface");
        let cr = Context::new(&surface).expect("Context::new");
        let ctx = pangocairo::functions::create_context(&cr);
        ctx.set_font_description(&pango::FontDescription::from_string("Monospace 11"));
        let layout = pango::Layout::new(&ctx);
        layout.set_width(-1);

        // A third-of-a-pixel letter-spacing attribute over the whole run:
        // whatever the base glyph advance is, adding a non-integral offset
        // per glyph makes the *run's* average advance non-integral too,
        // deterministically.
        let attrs = pango::AttrList::new();
        let mut spacing = pango::AttrInt::new_letter_spacing(pango::SCALE / 3);
        spacing.set_start_index(0);
        spacing.set_end_index(u32::MAX);
        attrs.insert(spacing);
        layout.set_attributes(Some(&attrs));

        let via_fn = measure_char_width_px(&layout);

        // Independent re-derivation of the formula `measure_char_width_px`
        // is supposed to implement — pins the exact algorithm, not just its
        // outcome, so a future edit can't silently swap back to
        // `layout.pixel_size()` on a single glyph without this failing.
        layout.set_text(&"0".repeat(100));
        let raw = layout.size().0 as f64 / pango::SCALE as f64 / 100.0;
        assert!(
            (via_fn - raw).abs() < 1e-9,
            "measure_char_width_px should equal a 100-glyph run's raw \
             width / 100: via_fn={via_fn}, raw={raw}"
        );

        // The result must carry a real fractional part. `layout.pixel_size()`
        // always returns a whole number, so this fails immediately if
        // `measure_char_width_px` uses it.
        assert!(
            (via_fn - via_fn.round()).abs() > 0.05,
            "letter-spacing should force a non-integral advance that \
             whole-pixel rounding would lose; got {via_fn}"
        );
    }

    /// A pane exactly as wide as a known-length line of monospace
    /// glyphs must report that many columns through `px_to_cols` —
    /// the same formula `available_width / char_width()` every consumer
    /// uses — not fewer, which is the empty-right-margin symptom.
    #[test]
    fn char_width_and_px_to_cols_agree_with_what_pango_actually_painted() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let surface = ImageSurface::create(Format::ARgb32, 4000, 40).expect("create ImageSurface");
        let cr = Context::new(&surface).expect("Context::new");
        let ctx = pangocairo::functions::create_context(&cr);
        ctx.set_font_description(&pango::FontDescription::from_string("Monospace 11"));
        let layout = pango::Layout::new(&ctx);
        layout.set_width(-1);

        let char_w = measure_char_width_px(&layout);

        const N: usize = 137;
        layout.set_text(&"0".repeat(N));
        // Unrounded painted width of the N-glyph line — the pane a real
        // consumer would size to fit this line exactly.
        let pane_w = layout.size().0 as f64 / pango::SCALE as f64;

        let cols = crate::primitives::text_display::px_to_cols(pane_w as f32, char_w as f32);
        assert_eq!(
            cols, N,
            "a pane exactly filled by {N} monospace glyphs should report \
             {N} columns via char_width()/px_to_cols, got {cols} \
             (char_w={char_w}, pane_w={pane_w})"
        );
    }

    /// For the actual runtime editor font — `gtk/run.rs`'s hardcoded
    /// `"Monospace N"`, which fontconfig resolves to DejaVu Sans Mono
    /// on this build host — compare `layout.pixel_size().0` (old, buggy),
    /// a single glyph's raw Pango-unit width, and a 100-glyph run's
    /// average, at every commonly configured editor size. The test
    /// confirms the advance for this font is already integral at all
    /// sizes 9-16pt, so this change does not alter the value in
    /// practice.
    #[test]
    fn measure_char_width_px_matches_pixel_size_for_the_real_editor_font() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        // Mirrors the range `ShellConfig::with_editor_font` /
        // `core::settings::default_ui_font_size` realistically produce —
        // see the "editor font" comment in `gtk/run.rs::render_frame`.
        for size in [9, 10, 11, 12, 13, 14, 16] {
            let surface =
                ImageSurface::create(Format::ARgb32, 4000, 40).expect("create ImageSurface");
            let cr = Context::new(&surface).expect("Context::new");
            let ctx = pangocairo::functions::create_context(&cr);
            ctx.set_font_description(&pango::FontDescription::from_string(&format!(
                "Monospace {size}"
            )));
            let layout = pango::Layout::new(&ctx);
            layout.set_width(-1);

            layout.set_text("0");
            let pixel_size = layout.pixel_size().0;
            let single_raw = layout.size().0 as f64 / pango::SCALE as f64;
            let run_avg = measure_char_width_px(&layout);

            eprintln!(
                "quadraui#910 size={size}: pixel_size().0={pixel_size} \
                 single_raw={single_raw:.6} run_avg(100)={run_avg:.6}"
            );

            assert!(
                (single_raw - pixel_size as f64).abs() < 1e-9
                    && (run_avg - pixel_size as f64).abs() < 1e-9,
                "quadraui#910: expected pixel_size(), single-glyph raw \
                 width, and the 100-glyph average to disagree here (that \
                 would demonstrate the fractional-advance bug for the \
                 real editor font) — instead they agree exactly at \
                 size={size}: pixel_size={pixel_size}, \
                 single_raw={single_raw}, run_avg={run_avg}. If this \
                 assertion ever fails, that's the disagreement #910 \
                 predicted; capture the printed numbers for the PR/issue \
                 and treat #910 as confirmed rather than closed."
            );
        }
    }

    /// `menu_bar_layout` is called from `MenuSystem::handle` outside any
    /// `enter_frame_scope`, so `current_frame_refs()` is always `None`
    /// at click time. The invariant is: whatever `draw_menu_bar` actually
    /// painted with, `menu_bar_layout` must measure identically at click
    /// time, even with a wildly different *editor* font live in between
    /// (proving click-time measurement tracks `ui_font`, not the editor
    /// font at click time).
    #[test]
    fn gtk_backend_menu_bar_layout_matches_last_paint_outside_frame_scope() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let surface = ImageSurface::create(Format::ARgb32, 400, 40).expect("create ImageSurface");
        let cr = Context::new(&surface).expect("Context::new");

        let large_ctx = pangocairo::functions::create_context(&cr);
        large_ctx.set_font_description(&pango::FontDescription::from_string("Sans 40"));
        let large_layout = pango::Layout::new(&large_ctx);

        let mut backend = GtkBackend::new();
        backend.set_pango_context(pangocairo::functions::create_context(&cr));

        let bar = MenuBar {
            id: WidgetId::new("test:menu-bar"),
            items: vec![MenuBarItem {
                id: WidgetId::new("test:menu-bar:file"),
                label: "&File".to_string(),
                disabled: false,
                submenu: None,
            }],
            open_item: None,
            focused_item: None,
        };
        let rect = QRect::new(0.0, 0.0, 400.0, 20.0);

        // Paint (inside a frame scope) with a huge *editor* font, exactly
        // like `gtk::run::activate`'s draw callback does — `ui_font`
        // stays at the "Sans 11" default throughout.
        let painted_width = backend.enter_frame_scope(&cr, &large_layout, |b| {
            b.draw_menu_bar(rect, &bar).visible_items[0].bounds.width
        });

        // Click-time dispatch happens from `AppLogic::handle`, which runs
        // outside any frame scope (real event handlers never wrap their
        // body in `enter_frame_scope` — only the draw callback does).
        // Simulate that here: no frame scope is active, and the live
        // editor font (had one been resolvable here) would still be the
        // huge one above — `ui_font` must be what's measured regardless.
        let click_time_width = backend.menu_bar_layout(rect, &bar).visible_items[0]
            .bounds
            .width;

        assert!(
            (click_time_width - painted_width).abs() < 0.5,
            "menu_bar_layout at click time must match what draw_menu_bar \
             actually painted: painted={painted_width}, click_time={click_time_width}"
        );

        // Positive control: `ui_font` is not inert — changing it alone must
        // visibly change the measured width, even though the giant editor
        // font above did not.
        Backend::set_ui_font(&mut backend, "Sans 40");
        let ui_font_changed_width = backend.menu_bar_layout(rect, &bar).visible_items[0]
            .bounds
            .width;
        assert!(
            ui_font_changed_width > painted_width * 1.5,
            "changing `ui_font` alone must visibly widen the measured menu \
             item: default_ui_font={painted_width}, ui_font_Sans_40={ui_font_changed_width}"
        );
    }

    /// A fresh backend must resolve to the historical hardcoded
    /// default ("Monospace 11") so `gtk/run.rs` reading
    /// `editor_font_pango_string()` reproduces today's behaviour for apps
    /// that never call `set_editor_font`.
    #[test]
    fn gtk_backend_editor_font_defaults_to_monospace_11() {
        let backend = GtkBackend::new();
        assert_eq!(backend.editor_font_pango_string(), "Monospace 11");
    }

    /// `Backend::set_editor_font` must update the string
    /// `gtk/run.rs`'s draw closure reads every frame, so an app-supplied
    /// family/size takes effect on the next repaint.
    #[test]
    fn gtk_backend_set_editor_font_overrides_default() {
        let mut backend = GtkBackend::new();
        Backend::set_editor_font(&mut backend, "DejaVu Sans Mono", 16.0);
        assert_eq!(backend.editor_font_pango_string(), "DejaVu Sans Mono 16");
    }

    /// Setting the editor font must not perturb the separate UI chrome
    /// font (`ui_font` / `set_ui_font`) — the two are independent knobs.
    #[test]
    fn gtk_backend_set_editor_font_does_not_affect_ui_font() {
        let mut backend = GtkBackend::new();
        backend.set_ui_font("Cantarell 12");
        Backend::set_editor_font(&mut backend, "Fira Code", 13.0);
        assert_eq!(backend.ui_font, "Cantarell 12");
        assert_eq!(backend.editor_font_pango_string(), "Fira Code 13");
    }

    /// `default_fonts()` reports GTK's fontconfig-alias platform
    /// convention (`Monospace`/`Sans`, 14pt/13pt), matching this crate's
    /// VS-Code-alignment table — not this instance's own
    /// `editor_font_family`/`ui_font` state, which stays at its own
    /// separate 11pt un-set default.
    #[test]
    fn gtk_backend_default_fonts_reports_platform_convention() {
        let backend = GtkBackend::new();
        let defaults = Backend::default_fonts(&backend);
        assert_eq!(defaults.editor_family, "Monospace");
        assert_eq!(defaults.editor_size_pt, 14.0);
        assert_eq!(defaults.ui_family, "Sans");
        assert_eq!(defaults.ui_size_pt, 13.0);
    }

    /// A prior `set_editor_font`/`set_ui_font` call must not perturb
    /// `default_fonts()` — it reports a static platform fact, not this
    /// instance's current, possibly-overridden state (see
    /// `PlatformFontDefaults`'s doc).
    #[test]
    fn gtk_backend_default_fonts_is_unaffected_by_set_editor_font_and_set_ui_font() {
        let mut backend = GtkBackend::new();
        Backend::set_editor_font(&mut backend, "Fira Code", 20.0);
        Backend::set_ui_font(&mut backend, "Cantarell 30");
        let defaults = Backend::default_fonts(&backend);
        assert_eq!(defaults.editor_family, "Monospace");
        assert_eq!(defaults.editor_size_pt, 14.0);
        assert_eq!(defaults.ui_family, "Sans");
        assert_eq!(defaults.ui_size_pt, 13.0);
    }

    /// `monospace`/`sans-serif` (and Pango's own `Monospace`/`Sans`
    /// aliases) already resolve correctly via fontconfig — GTK stores them
    /// unchanged.
    #[test]
    fn gtk_backend_passes_through_tokens_fontconfig_already_understands() {
        let mut backend = GtkBackend::new();
        Backend::set_editor_font(&mut backend, "monospace", 14.0);
        assert_eq!(backend.editor_font_pango_string(), "monospace 14");

        Backend::set_ui_font(&mut backend, "sans-serif 11");
        assert_eq!(backend.ui_font, "sans-serif 11");

        Backend::set_ui_font(&mut backend, "Monospace 11");
        assert_eq!(backend.ui_font, "Monospace 11");

        backend.set_ui_font("Sans 11");
        assert_eq!(backend.ui_font, "Sans 11");
    }

    /// `system-ui` has no fontconfig alias, so GTK rewrites it to `"Sans"`
    /// — the concrete family fontconfig's own `sans-serif` alias already
    /// resolves to — both via the trait methods and the ergonomic
    /// inherent `set_ui_font` sibling.
    #[test]
    fn gtk_backend_resolves_system_ui_to_sans() {
        let mut backend = GtkBackend::new();
        Backend::set_editor_font(&mut backend, "system-ui", 12.0);
        assert_eq!(backend.editor_font_pango_string(), "Sans 12");

        Backend::set_ui_font(&mut backend, "system-ui 11");
        assert_eq!(backend.ui_font, "Sans 11");

        backend.set_ui_font("system-ui 13");
        assert_eq!(backend.ui_font, "Sans 13");
    }

    /// `system-ui` embedded later in a Pango-style comma-separated
    /// fallback list is rewritten in place — Pango already resolves the
    /// rest of the list itself, this backend only needs to translate the
    /// one token fontconfig has no alias for.
    #[test]
    fn gtk_backend_resolves_system_ui_within_a_comma_list() {
        let mut backend = GtkBackend::new();
        Backend::set_ui_font(&mut backend, "Cantarell, system-ui, Sans 12");
        assert_eq!(backend.ui_font, "Cantarell,Sans,Sans 12");
    }

    /// A GTK consumer that paints its editor content itself (bespoke
    /// Cairo, not [`Backend::draw_editor`]) must be able to resolve
    /// `Backend::editor_col_at_x` off a single `GtkBackend` it owns —
    /// no `enter_frame_scope`, no prior `draw_editor` call to populate
    /// `last_editor_pango_layout`. The fallback builds a bare
    /// `pango::Layout` straight off `pango_ctx`, so the result must track
    /// `Backend::set_editor_font` at two different sizes, not a font
    /// baked in once at setup.
    #[test]
    fn gtk_backend_editor_col_at_x_tracks_set_editor_font_without_a_frame() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let surface = ImageSurface::create(Format::ARgb32, 400, 40).expect("create ImageSurface");
        let cr = Context::new(&surface).expect("Context::new");
        // The only click-time setup a consumer needs: the stable widget
        // Pango context, exactly as `gtk::run::activate` seeds it on
        // `DrawingArea` realize via `set_pango_context`.
        let stable_ctx = pangocairo::functions::create_context(&cr);
        let mut backend = GtkBackend::new();
        backend.set_pango_context(stable_ctx);

        let line = crate::EditorLine {
            raw_text: "abcdefghijklmnopqrstuvwxyz".to_string(),
            gutter_text: String::new(),
            spans: Vec::new(),
            line_idx: 0,
            is_current_line: false,
            is_fold_header: false,
            folded_line_count: 0,
            git_diff: None,
            diff_status: None,
            diagnostics: Vec::new(),
            spell_errors: Vec::new(),
            is_breakpoint: false,
            is_conditional_bp: false,
            is_dap_current: false,
            is_wrap_continuation: false,
            segment_col_offset: 0,
            annotation: None,
            ghost_suffix: None,
            is_ghost_continuation: false,
            indent_guides: Vec::new(),
            colorcolumns: Vec::new(),
        };
        let editor = crate::Editor {
            id: WidgetId::new("ed"),
            rect: Rect::new(0.0, 0.0, 400.0, 40.0),
            lines: vec![line],
            cursor: None,
            extra_cursors: Vec::new(),
            selection: None,
            extra_selections: Vec::new(),
            yank_highlight: None,
            scroll_top: 0,
            scroll_left: 0,
            total_lines: 1,
            max_col: 26,
            gutter_char_width: 0,
            is_active: true,
            show_active_bg: false,
            has_git_diff: false,
            has_breakpoints: false,
            diagnostic_gutter: std::collections::HashMap::new(),
            code_action_lines: std::collections::HashSet::new(),
            bracket_match_positions: Vec::new(),
            active_indent_col: None,
            tabstop: 4,
            cursorline: false,
            lightbulb_glyph: '!',
        };
        // No gutter, no scroll: `EditorLayout::text_bounds.x` is 0 and
        // `col_at_x`'s scroll term drops out, so `editor_layout` needn't
        // be recomputed per font size below — the glyph-level resolution
        // (`pango::Layout::xy_to_index`) is where the live font actually
        // matters, not this geometry.
        let editor_layout = Backend::editor_layout(&backend, editor.rect, &editor);
        let click_x = 80.0_f32;

        Backend::set_editor_font(&mut backend, "Monospace", 8.0);
        let small_font_col =
            Backend::editor_col_at_x(&backend, &editor_layout, &editor, 0, click_x);

        Backend::set_editor_font(&mut backend, "Monospace", 32.0);
        let large_font_col =
            Backend::editor_col_at_x(&backend, &editor_layout, &editor, 0, click_x);

        assert!(
            small_font_col > 0 && small_font_col < 26,
            "a small font must fit several but not all 26 chars before x=80: got {small_font_col}"
        );
        assert!(
            large_font_col < small_font_col,
            "a 4x larger editor font must fit strictly fewer characters before the same \
             x=80 click: small_font(8pt)={small_font_col}, large_font(32pt)={large_font_col}"
        );
    }

    // --- #624: chrome primitives must paint/measure with `ui_font`, not
    // whatever font the frame's editor-content layout happens to carry.
    // Each test below paints the same bar/tree twice, inside frame scopes
    // whose live layout carries wildly different "editor" font sizes
    // (mirroring two different `set_editor_font` sizes) with `ui_font` left
    // at its default — the painted glyph extent must be identical across
    // both. A third measurement then changes `ui_font` alone as a positive
    // control: the extent must visibly change, proving `ui_font` is
    // actually read, not just insulated from the editor font by accident.

    fn ui_font_test_surface_and_contexts() -> (
        pangocairo::cairo::ImageSurface,
        pango::FontDescription,
        pango::FontDescription,
    ) {
        (
            pangocairo::cairo::ImageSurface::create(pangocairo::cairo::Format::ARgb32, 400, 40)
                .expect("create ImageSurface"),
            pango::FontDescription::from_string("Sans 8"),
            pango::FontDescription::from_string("Sans 40"),
        )
    }

    #[test]
    fn gtk_backend_draw_status_bar_uses_ui_font_not_editor_font() {
        let (surface, small_editor_font, large_editor_font) = ui_font_test_surface_and_contexts();
        let cr = pangocairo::cairo::Context::new(&surface).expect("Context::new");

        let bar = StatusBar {
            id: WidgetId::new("test:status-bar"),
            left_segments: vec![crate::primitives::status_bar::StatusBarSegment {
                text: "READY".to_string(),
                fg: crate::types::Color::rgb(255, 255, 255),
                bg: crate::types::Color::rgb(0, 0, 0),
                bold: false,
                action_id: None,
            }],
            right_segments: vec![],
        };
        let rect = QRect::new(0.0, 0.0, 400.0, 20.0);

        let width_at = |editor_font: &pango::FontDescription| {
            let pango_ctx = pangocairo::functions::create_context(&cr);
            pango_ctx.set_font_description(editor_font);
            let layout = pango::Layout::new(&pango_ctx);
            let mut backend = GtkBackend::new();
            backend.enter_frame_scope(&cr, &layout, |b| {
                b.draw_status_bar_interactive(rect, &bar, &crate::InteractionState::new())
                    .visible_segments[0]
                    .bounds
                    .width
            })
        };

        let small_editor_width = width_at(&small_editor_font);
        let large_editor_width = width_at(&large_editor_font);
        assert!(
            (small_editor_width - large_editor_width).abs() < 0.5,
            "status bar segment width must be editor-font-size independent: \
             small_editor={small_editor_width}, large_editor={large_editor_width}"
        );

        let ui_font_width = {
            let pango_ctx = pangocairo::functions::create_context(&cr);
            pango_ctx.set_font_description(&small_editor_font);
            let layout = pango::Layout::new(&pango_ctx);
            let mut backend = GtkBackend::new();
            Backend::set_ui_font(&mut backend, "Sans 40");
            backend.enter_frame_scope(&cr, &layout, |b| {
                b.draw_status_bar_interactive(rect, &bar, &crate::InteractionState::new())
                    .visible_segments[0]
                    .bounds
                    .width
            })
        };
        assert!(
            ui_font_width > small_editor_width * 1.5,
            "changing ui_font alone must visibly widen the painted segment: \
             default_ui_font={small_editor_width}, ui_font_Sans_40={ui_font_width}"
        );
    }

    /// `draw_status_bar_interactive_scaled` paints narrower text at a
    /// smaller `font_scale`, and an unscaled paint immediately after a
    /// scaled one must come back to exactly its own pre-scaled width —
    /// proving the per-call scale doesn't leak into the backend's ambient
    /// `ui_font` for later paints this frame.
    #[test]
    fn gtk_backend_draw_status_bar_interactive_scaled_shrinks_without_perturbing_later_unscaled_paints(
    ) {
        let (surface, font, _) = ui_font_test_surface_and_contexts();
        let cr = pangocairo::cairo::Context::new(&surface).expect("Context::new");
        let pango_ctx = pangocairo::functions::create_context(&cr);
        pango_ctx.set_font_description(&font);
        let layout = pango::Layout::new(&pango_ctx);

        let bar = StatusBar {
            id: WidgetId::new("test:status-bar"),
            left_segments: vec![crate::primitives::status_bar::StatusBarSegment {
                text: "READY".to_string(),
                fg: crate::types::Color::rgb(255, 255, 255),
                bg: crate::types::Color::rgb(0, 0, 0),
                bold: false,
                action_id: None,
            }],
            right_segments: vec![],
        };
        let rect = QRect::new(0.0, 0.0, 400.0, 20.0);

        let mut backend = GtkBackend::new();
        Backend::set_ui_font(&mut backend, "Sans 40");
        let (unscaled_w, scaled_w, unscaled_w_again) =
            backend.enter_frame_scope(&cr, &layout, |b| {
                let unscaled_w = b
                    .draw_status_bar_interactive(rect, &bar, &crate::InteractionState::new())
                    .visible_segments[0]
                    .bounds
                    .width;
                let scaled_w = b
                    .draw_status_bar_interactive_scaled(
                        rect,
                        &bar,
                        &crate::InteractionState::new(),
                        0.5,
                    )
                    .visible_segments[0]
                    .bounds
                    .width;
                let unscaled_w_again = b
                    .draw_status_bar_interactive(rect, &bar, &crate::InteractionState::new())
                    .visible_segments[0]
                    .bounds
                    .width;
                (unscaled_w, scaled_w, unscaled_w_again)
            });

        assert!(
            scaled_w < unscaled_w * 0.75,
            "font_scale=0.5 should paint noticeably narrower: {scaled_w} vs {unscaled_w}",
        );
        assert!(
            (unscaled_w_again - unscaled_w).abs() < 0.5,
            "an unscaled paint after a scaled one must match the original unscaled width \
             — ui_font state must be restored, not left scaled: \
             {unscaled_w_again} vs {unscaled_w}",
        );
    }

    /// Driver-tier proof that `GtkBackend::surface_measure_text_styled`'s
    /// bold override actually does something against a real `pango::Layout`.
    /// Paints the same text through the real `Backend::draw_status_bar`
    /// path once bold, once not, and asserts the bold segment's resolved
    /// (painted) width is strictly wider.
    #[test]
    fn gtk_backend_draw_status_bar_bold_segment_measures_wider() {
        let (surface, font, _) = ui_font_test_surface_and_contexts();
        let cr = pangocairo::cairo::Context::new(&surface).expect("Context::new");
        let rect = QRect::new(0.0, 0.0, 400.0, 20.0);

        let width_for = |bold: bool| {
            let pango_ctx = pangocairo::functions::create_context(&cr);
            pango_ctx.set_font_description(&font);
            let layout = pango::Layout::new(&pango_ctx);
            let mut backend = GtkBackend::new();
            let bar = StatusBar {
                id: WidgetId::new("test:status-bar"),
                left_segments: vec![crate::primitives::status_bar::StatusBarSegment {
                    text: "READY".to_string(),
                    fg: crate::types::Color::rgb(255, 255, 255),
                    bg: crate::types::Color::rgb(0, 0, 0),
                    bold,
                    action_id: None,
                }],
                right_segments: vec![],
            };
            backend.enter_frame_scope(&cr, &layout, |b| {
                b.draw_status_bar_interactive(rect, &bar, &crate::InteractionState::new())
                    .visible_segments[0]
                    .bounds
                    .width
            })
        };

        let regular_width = width_for(false);
        let bold_width = width_for(true);
        assert!(
            bold_width > regular_width,
            "a bold segment must measure (and paint) wider than the same text non-bold: \
             regular={regular_width}, bold={bold_width}"
        );
    }

    /// Driver-tier proof for the zero/negative-size guard in
    /// `primitives::status_bar::native_surface_paint::paint`. A literal
    /// `width = 0.0` can't tell whether the guard runs because Cairo's
    /// `cr.clip()` already suppresses every subsequent fill for zero-area
    /// paths. A *negative* width doesn't have that property: Cairo's
    /// `rectangle()` traces a real path mirrored leftward, which `cr.clip()`
    /// clips to instead, and a subsequent `cr.fill()` paints it. That is
    /// exactly the regression the guard exists to prevent.
    #[test]
    fn gtk_backend_draw_status_bar_negative_width_does_not_paint() {
        let canvas_w = 40;
        let canvas_h = 40;
        let sentinel: (u8, u8, u8) = (7, 8, 9);

        let mut backend = GtkBackend::new();
        backend.set_current_theme(crate::Theme::default());
        Backend::begin_frame(
            &mut backend,
            Viewport::new(canvas_w as f32, canvas_h as f32, 1.0),
        );
        let mut surface = pangocairo::cairo::ImageSurface::create(
            pangocairo::cairo::Format::ARgb32,
            canvas_w,
            canvas_h,
        )
        .expect("create ImageSurface");
        {
            let cr = pangocairo::cairo::Context::new(&surface).expect("Context::new");
            cr.set_source_rgb(
                sentinel.0 as f64 / 255.0,
                sentinel.1 as f64 / 255.0,
                sentinel.2 as f64 / 255.0,
            );
            cr.rectangle(0.0, 0.0, canvas_w as f64, canvas_h as f64);
            cr.fill().ok();

            let bar = StatusBar {
                id: WidgetId::new("test:status-bar"),
                left_segments: vec![crate::primitives::status_bar::StatusBarSegment {
                    text: "READY".to_string(),
                    fg: crate::types::Color::rgb(255, 255, 255),
                    bg: crate::types::Color::rgb(200, 0, 0),
                    bold: false,
                    action_id: None,
                }],
                right_segments: vec![],
            };
            let pango_layout = pangocairo::functions::create_layout(&cr);
            backend.enter_frame_scope(&cr, &pango_layout, |b| {
                // Negative width: `rect.x = 20` mirrors to a real
                // [5, 20) x [10, 25) area on a positive-width backend, but
                // must paint nothing at all once the guard short-circuits.
                b.draw_status_bar_interactive(
                    QRect::new(20.0, 10.0, -15.0, 15.0),
                    &bar,
                    &crate::InteractionState::new(),
                );
            });
        }
        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        for y in 0..canvas_h {
            for x in 0..canvas_w {
                assert_eq!(
                    chart_pixel(&data, stride, x, y),
                    sentinel,
                    "pixel ({x}, {y}) must stay untouched: a negative width must \
                     short-circuit to the no-paint layout, not mirror into a real \
                     paintable rect",
                );
            }
        }
    }

    /// A `rect` taller than `current_line_height` must be filled in full,
    /// not just up to `current_line_height`. Uses an empty-segments bar so
    /// the fill falls back to `theme.background`; the sentinel colour must
    /// not survive anywhere in the rect, including rows below the old
    /// `current_line_height` cutoff.
    #[test]
    fn gtk_backend_draw_status_bar_fills_the_whole_rect_height_not_just_line_height() {
        let canvas_w = 40;
        let canvas_h = 40;
        let sentinel: (u8, u8, u8) = (7, 8, 9);
        let bg = crate::types::Color::rgb(236, 236, 236);

        let mut backend = GtkBackend::new();
        backend.set_current_theme(crate::Theme {
            background: bg,
            ..crate::Theme::default()
        });
        // Small line height so the rect below is deliberately taller.
        backend.set_current_line_height(6.0);
        Backend::begin_frame(
            &mut backend,
            Viewport::new(canvas_w as f32, canvas_h as f32, 1.0),
        );
        let mut surface = pangocairo::cairo::ImageSurface::create(
            pangocairo::cairo::Format::ARgb32,
            canvas_w,
            canvas_h,
        )
        .expect("create ImageSurface");
        {
            let cr = pangocairo::cairo::Context::new(&surface).expect("Context::new");
            cr.set_source_rgb(
                sentinel.0 as f64 / 255.0,
                sentinel.1 as f64 / 255.0,
                sentinel.2 as f64 / 255.0,
            );
            cr.rectangle(0.0, 0.0, canvas_w as f64, canvas_h as f64);
            cr.fill().ok();

            let bar = StatusBar {
                id: WidgetId::new("test:status-bar"),
                left_segments: vec![],
                right_segments: vec![],
            };
            let pango_layout = pangocairo::functions::create_layout(&cr);
            backend.enter_frame_scope(&cr, &pango_layout, |b| {
                b.draw_status_bar_interactive(
                    QRect::new(0.0, 0.0, canvas_w as f32, canvas_h as f32),
                    &bar,
                    &crate::InteractionState::new(),
                );
            });
        }
        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        // Bottom row — well below where `current_line_height` (6.0) would have
        // stopped filling before this fix.
        let bottom_row = canvas_h - 2;
        for x in 0..canvas_w {
            assert_eq!(
                chart_pixel(&data, stride, x, bottom_row),
                (bg.r, bg.g, bg.b),
                "pixel ({x}, {bottom_row}) must show the theme background — a rect \
                 taller than current_line_height must be filled in full, not left \
                 showing the sentinel colour",
            );
        }
    }

    #[test]
    fn gtk_backend_draw_tab_bar_uses_ui_font_not_editor_font() {
        let (surface, small_editor_font, large_editor_font) = ui_font_test_surface_and_contexts();
        let cr = pangocairo::cairo::Context::new(&surface).expect("Context::new");

        let bar = TabBar {
            id: WidgetId::new("test:tabs"),
            tabs: vec![crate::primitives::tab_bar::TabItem {
                label: "main.rs".to_string(),
                is_active: true,
                is_dirty: false,
                is_preview: false,
                is_closable: false,
            }],
            scroll_offset: 0,
            right_segments: vec![],
            active_accent: None,
            show_tab_close: false,
            compact: false,
        };
        let rect = QRect::new(0.0, 0.0, 400.0, 24.0);

        let width_at = |editor_font: &pango::FontDescription, ui_font: Option<&str>| {
            let pango_ctx = pangocairo::functions::create_context(&cr);
            pango_ctx.set_font_description(editor_font);
            let layout = pango::Layout::new(&pango_ctx);
            let mut backend = GtkBackend::new();
            if let Some(f) = ui_font {
                Backend::set_ui_font(&mut backend, f);
            }
            backend.enter_frame_scope(&cr, &layout, |b| {
                b.draw_tab_bar(rect, &bar, None);
                b.cached_tab_bar_layout(&bar.id)
                    .expect("draw_tab_bar caches its layout")
                    .1
                    .visible_tabs[0]
                    .bounds
                    .width
            })
        };

        let small_editor_width = width_at(&small_editor_font, None);
        let large_editor_width = width_at(&large_editor_font, None);
        assert!(
            (small_editor_width - large_editor_width).abs() < 0.5,
            "tab width must be editor-font-size independent: \
             small_editor={small_editor_width}, large_editor={large_editor_width}"
        );

        let ui_font_width = width_at(&small_editor_font, Some("Sans 40"));
        assert!(
            ui_font_width > small_editor_width * 1.5,
            "changing ui_font alone must visibly widen the painted tab: \
             default_ui_font={small_editor_width}, ui_font_Sans_40={ui_font_width}"
        );
    }

    /// `draw_tab_bar_with_chrome_and_glyphs`'s `TabBarGlyphs` override
    /// replaces the close-button glyph; `None` and an empty override (no
    /// fields set) must paint byte-identical to each other, and a
    /// populated `with_close_glyph` override must visibly change the
    /// painted ink.
    #[test]
    fn gtk_backend_draw_tab_bar_honors_close_glyph_override() {
        const W: i32 = 300;
        const H: i32 = 40;

        let bar = TabBar {
            id: WidgetId::new("test:tabs-glyphs"),
            tabs: vec![crate::primitives::tab_bar::TabItem {
                label: "main.rs".to_string(),
                is_active: true,
                is_dirty: false,
                is_preview: false,
                is_closable: true,
            }],
            scroll_offset: 0,
            right_segments: vec![],
            active_accent: None,
            show_tab_close: true,
            compact: false,
        };
        let chrome =
            crate::primitives::tab_bar::TabChrome::new(crate::primitives::tab_bar::TabFrame::None);
        let rect = QRect::new(0.0, 0.0, W as f32, H as f32);

        let render = |glyphs: Option<&crate::TabBarGlyphs>| {
            let mut surface =
                pangocairo::cairo::ImageSurface::create(pangocairo::cairo::Format::ARgb32, W, H)
                    .expect("create ImageSurface");
            {
                let cr = pangocairo::cairo::Context::new(&surface).expect("Context::new");
                cr.set_source_rgb(1.0, 1.0, 1.0);
                cr.paint().ok();
                let pango_ctx = pangocairo::functions::create_context(&cr);
                pango_ctx.set_font_description(&pango::FontDescription::from_string("Sans 8"));
                let layout = pango::Layout::new(&pango_ctx);
                let mut backend = GtkBackend::new();
                Backend::set_current_line_height(&mut backend, 20.0);
                backend.enter_frame_scope(&cr, &layout, |b| {
                    b.draw_tab_bar_with_chrome_and_glyphs(rect, &bar, None, &chrome, glyphs);
                });
            }
            surface.flush();
            let stride = surface.stride() as usize;
            let data = surface.data().expect("surface data");
            data[..(H as usize) * stride].to_vec()
        };

        let default_pixels = render(None);
        let empty_override_pixels = render(Some(&crate::TabBarGlyphs::new()));
        assert_eq!(
            default_pixels, empty_override_pixels,
            "an empty TabBarGlyphs override must paint byte-identical to None"
        );

        let overridden = crate::TabBarGlyphs::new().with_close_glyph("X");
        let override_pixels = render(Some(&overridden));
        assert_ne!(
            default_pixels, override_pixels,
            "a close_glyph override must change the painted close-button glyph"
        );
    }

    #[test]
    fn gtk_backend_draw_tree_uses_ui_font_not_editor_font() {
        let small_editor_font = pango::FontDescription::from_string("Sans 8");
        let large_editor_font = pango::FontDescription::from_string("Sans 40");
        const W: i32 = 1600;
        const H: i32 = 60;

        let row_text_extent = |editor_font: &pango::FontDescription, ui_font: Option<&str>| {
            let mut surface =
                pangocairo::cairo::ImageSurface::create(pangocairo::cairo::Format::ARgb32, W, H)
                    .expect("create ImageSurface");
            let tree = TreeView {
                id: WidgetId::new("test:tree"),
                rows: vec![crate::primitives::tree::TreeRow {
                    path: vec![0],
                    indent: 0,
                    icon: None,
                    text: crate::types::StyledText::plain("m".to_string()),
                    badge: None,
                    is_expanded: None,
                    decoration: crate::types::Decoration::Normal,
                    edit: None,
                }],
                selection_mode: crate::types::SelectionMode::Single,
                selected_path: None,
                scroll_offset: 0,
                style: crate::types::TreeStyle::default(),
                has_focus: false,
            };
            let rect = QRect::new(0.0, 0.0, W as f32, H as f32);
            {
                let cr = pangocairo::cairo::Context::new(&surface).expect("Context::new");
                cr.set_source_rgb(1.0, 1.0, 1.0);
                cr.paint().ok();
                let pango_ctx = pangocairo::functions::create_context(&cr);
                pango_ctx.set_font_description(editor_font);
                let layout = pango::Layout::new(&pango_ctx);
                let mut backend = GtkBackend::new();
                // White `tab_bar_bg` so the row's own background fill
                // doesn't itself read as "non-white" and saturate the
                // rightmost-painted-pixel scan below.
                backend.set_current_theme(crate::Theme {
                    tab_bar_bg: crate::types::Color::rgb(255, 255, 255),
                    background: crate::types::Color::rgb(255, 255, 255),
                    foreground: crate::types::Color::rgb(0, 0, 0),
                    ..crate::Theme::default()
                });
                if let Some(f) = ui_font {
                    Backend::set_ui_font(&mut backend, f);
                }
                backend.enter_frame_scope(&cr, &layout, |b| {
                    b.draw_tree(rect, &tree);
                });
            }
            surface.flush();
            let stride = surface.stride() as usize;
            let data = surface.data().expect("surface data");
            // Rightmost non-white pixel within the first (only) row's
            // vertical span — proxy for the painted label's glyph extent.
            // `gtk_tree_layout`'s row 0 spans `[0, line_height * 1.4)`;
            // `current_line_height` defaults to 16px, so y=10 is always
            // inside it regardless of which font is under test.
            let y = 10usize;
            (0..W as usize)
                .rev()
                .find(|&x| {
                    let off = y * stride + x * 4;
                    !(data[off] == 255 && data[off + 1] == 255 && data[off + 2] == 255)
                })
                .unwrap_or(0)
        };

        let small_editor_extent = row_text_extent(&small_editor_font, None);
        let large_editor_extent = row_text_extent(&large_editor_font, None);
        assert!(
            small_editor_extent.abs_diff(large_editor_extent) <= 1,
            "tree row glyph extent must be editor-font-size independent: \
             small_editor={small_editor_extent}, large_editor={large_editor_extent}"
        );

        let ui_font_extent = row_text_extent(&small_editor_font, Some("Sans 40"));
        assert!(
            ui_font_extent > small_editor_extent + 20,
            "changing ui_font alone must visibly widen the painted row label: \
             default_ui_font={small_editor_extent}, ui_font_Sans_40={ui_font_extent}"
        );
    }

    /// Same shape as `gtk_backend_draw_tree_uses_ui_font_not_editor_font`
    /// above, for `DataTable`. `DataTableLayout`'s own `find_bounds`
    /// equivalent (the bounds `draw_data_table`'s caller records into
    /// `painted_text`) is derived from the declarative layout, not
    /// re-measured Pango geometry (see `Self::draw_data_table`'s own
    /// doc comment on that recording), so it can't be used as a
    /// font-size oracle the way a `GtkDriver::find_bounds` probe can for
    /// most other chrome primitives — a pixel scan of the actually
    /// painted ink is the only oracle that answers "which font shaped
    /// this glyph" here.
    ///
    /// Pins `current_line_height` to a generous 60px (`draw_data_table`'s
    /// per-cell clip rect is exactly one `line_height` tall) so a large
    /// chrome glyph's ink isn't clipped away before the scan below ever
    /// sees it, and scans the whole row band (not one fixed `y`) since a
    /// much taller glyph's visible ink sits at a different vertical
    /// offset than a small one's.
    /// The no-paint `data_table_layout` twin must resolve the same
    /// content-sized column geometry `draw_data_table` paints with, even
    /// when the stored Pango context carries a font unlike `ui_font` —
    /// otherwise click hit-testing and separator positions drift off the
    /// painted columns.
    #[test]
    fn gtk_backend_data_table_layout_matches_painted_columns() {
        const W: i32 = 1200;
        const H: i32 = 200;
        let surface =
            pangocairo::cairo::ImageSurface::create(pangocairo::cairo::Format::ARgb32, W, H)
                .expect("create ImageSurface");
        let table = crate::DataTable {
            id: WidgetId::new("test:data-table-parity"),
            columns: vec![
                crate::Column {
                    title: "Name".to_string(),
                    width: crate::ColumnWidth::Content {
                        min: 0.0,
                        max: 1000.0,
                    },
                    align: crate::ColumnAlign::Left,
                },
                crate::Column {
                    title: "Status".to_string(),
                    width: crate::ColumnWidth::Flex(1.0),
                    align: crate::ColumnAlign::Left,
                },
            ],
            rows: vec![crate::DataRow {
                cells: vec![
                    crate::types::StyledText::plain("a-fairly-long-pod-name-xyz".to_string()),
                    crate::types::StyledText::plain("Running".to_string()),
                ],
                decoration: crate::types::Decoration::Normal,
            }],
            selected_idx: None,
            scroll_offset: 0,
            sort: None,
            has_focus: false,
            show_scrollbar: false,
            min_total_width: None,
            h_scroll: 0.0,
            column_overrides: vec![],
            footer: None,
        };
        let rect = QRect::new(0.0, 0.0, W as f32, H as f32);
        let cr = pangocairo::cairo::Context::new(&surface).expect("Context::new");
        let stored_ctx = pangocairo::functions::create_context(&cr);
        stored_ctx.set_font_description(&pango::FontDescription::from_string("Monospace 8"));
        let frame_ctx = pangocairo::functions::create_context(&cr);
        frame_ctx.set_font_description(&pango::FontDescription::from_string("Monospace 8"));
        let frame_layout = pango::Layout::new(&frame_ctx);

        let mut backend = GtkBackend::new();
        backend.set_pango_context(stored_ctx);
        Backend::set_current_line_height(&mut backend, 20.0);
        Backend::set_ui_font(&mut backend, "Sans 20");

        let measured = backend.data_table_layout(rect, &table);
        let mut painted = None;
        backend.enter_frame_scope(&cr, &frame_layout, |b| {
            painted = Some(b.draw_data_table(rect, &table, None));
        });
        let painted = painted.expect("draw_data_table ran");
        let xs = |l: &crate::DataTableLayout| {
            l.columns.iter().map(|c| (c.x, c.width)).collect::<Vec<_>>()
        };
        assert_eq!(
            xs(&measured),
            xs(&painted),
            "data_table_layout must measure with the same chrome font draw_data_table paints with"
        );
    }

    /// `draw_data_table_with_glyphs`'s `DataTableGlyphs` override replaces
    /// the header's sort-direction glyph; `None` and an empty override
    /// (no fields set) must paint byte-identical to each other, and a
    /// populated `sort_ascending_glyph` override must visibly change the
    /// painted header ink.
    #[test]
    fn gtk_backend_draw_data_table_honors_sort_glyph_override() {
        const W: i32 = 400;
        const H: i32 = 100;

        let header_pixels = |glyphs: Option<&crate::DataTableGlyphs>| {
            let mut surface =
                pangocairo::cairo::ImageSurface::create(pangocairo::cairo::Format::ARgb32, W, H)
                    .expect("create ImageSurface");
            let table = crate::DataTable {
                id: WidgetId::new("test:data-table-glyphs"),
                columns: vec![crate::Column {
                    title: String::new(),
                    width: crate::ColumnWidth::Flex(1.0),
                    align: crate::ColumnAlign::Left,
                }],
                rows: vec![],
                selected_idx: None,
                scroll_offset: 0,
                sort: Some((0, crate::SortDirection::Ascending)),
                has_focus: false,
                show_scrollbar: false,
                min_total_width: None,
                h_scroll: 0.0,
                column_overrides: vec![],
                footer: None,
            };
            let rect = QRect::new(0.0, 0.0, W as f32, H as f32);
            let header_height;
            {
                let cr = pangocairo::cairo::Context::new(&surface).expect("Context::new");
                cr.set_source_rgb(1.0, 1.0, 1.0);
                cr.paint().ok();
                let pango_ctx = pangocairo::functions::create_context(&cr);
                pango_ctx.set_font_description(&pango::FontDescription::from_string("Sans 8"));
                let layout = pango::Layout::new(&pango_ctx);
                let mut backend = GtkBackend::new();
                Backend::set_current_line_height(&mut backend, 20.0);
                let mut painted = None;
                backend.enter_frame_scope(&cr, &layout, |b| {
                    painted = Some(b.draw_data_table_with_glyphs(rect, &table, None, glyphs));
                });
                header_height = painted
                    .expect("draw_data_table_with_glyphs ran")
                    .header_height;
            }
            surface.flush();
            let stride = surface.stride() as usize;
            let data = surface.data().expect("surface data");
            let rows = (header_height.ceil() as usize).max(1);
            data[..rows * stride].to_vec()
        };

        let default_pixels = header_pixels(None);
        let empty_override_pixels = header_pixels(Some(&crate::DataTableGlyphs::new()));
        assert_eq!(
            default_pixels, empty_override_pixels,
            "an empty DataTableGlyphs override must paint byte-identical to None"
        );

        let overridden = crate::DataTableGlyphs::new().with_sort_ascending_glyph("^");
        let override_pixels = header_pixels(Some(&overridden));
        assert_ne!(
            default_pixels, override_pixels,
            "a sort_ascending_glyph override must change the painted header glyph"
        );
    }

    #[test]
    fn gtk_backend_draw_data_table_uses_ui_font_not_editor_font() {
        let small_editor_font = pango::FontDescription::from_string("Sans 8");
        let large_editor_font = pango::FontDescription::from_string("Sans 40");
        const W: i32 = 1600;
        const H: i32 = 160;
        const PINNED_LINE_HEIGHT: f32 = 60.0;

        let cell_text_extent = |editor_font: &pango::FontDescription, ui_font: Option<&str>| {
            let mut surface =
                pangocairo::cairo::ImageSurface::create(pangocairo::cairo::Format::ARgb32, W, H)
                    .expect("create ImageSurface");
            let table = crate::DataTable {
                id: WidgetId::new("test:data-table"),
                columns: vec![crate::Column {
                    title: "col".to_string(),
                    width: crate::ColumnWidth::Flex(1.0),
                    align: crate::ColumnAlign::Left,
                }],
                rows: vec![crate::DataRow {
                    cells: vec![crate::types::StyledText::plain("m".to_string())],
                    decoration: crate::types::Decoration::Normal,
                }],
                selected_idx: None,
                scroll_offset: 0,
                sort: None,
                has_focus: false,
                show_scrollbar: false,
                min_total_width: None,
                h_scroll: 0.0,
                column_overrides: vec![],
                footer: None,
            };
            let rect = QRect::new(0.0, 0.0, W as f32, H as f32);
            {
                let cr = pangocairo::cairo::Context::new(&surface).expect("Context::new");
                // White everywhere, including the header band, so the
                // header's own `tab_bar_bg` fill doesn't itself read as
                // "non-white" and confuse the body-row ink scan below —
                // the body row (unlike the header) paints no background
                // fill of its own when neither selected nor hovered (see
                // `crate::gtk::draw_data_table`'s body-row loop).
                cr.set_source_rgb(1.0, 1.0, 1.0);
                cr.paint().ok();
                let pango_ctx = pangocairo::functions::create_context(&cr);
                pango_ctx.set_font_description(editor_font);
                let layout = pango::Layout::new(&pango_ctx);
                let mut backend = GtkBackend::new();
                Backend::set_current_line_height(&mut backend, PINNED_LINE_HEIGHT);
                backend.set_current_theme(crate::Theme {
                    tab_bar_bg: crate::types::Color::rgb(255, 255, 255),
                    background: crate::types::Color::rgb(255, 255, 255),
                    foreground: crate::types::Color::rgb(0, 0, 0),
                    ..crate::Theme::default()
                });
                if let Some(f) = ui_font {
                    Backend::set_ui_font(&mut backend, f);
                }
                backend.enter_frame_scope(&cr, &layout, |b| {
                    b.draw_data_table(rect, &table, None);
                });
            }
            surface.flush();
            let stride = surface.stride() as usize;
            let data = surface.data().expect("surface data");
            // Row 0's vertical span starts at `header_height`
            // (`(line_height * 1.2).round()` — see
            // `pixel_data_table_layout`) and is `PINNED_LINE_HEIGHT` tall.
            // Scanning the whole band (not one fixed `y`) is necessary
            // because a much taller glyph's visible ink sits at a
            // different offset within that band than a small one's.
            let row_top = (PINNED_LINE_HEIGHT * 1.2).round() as usize;
            let row_bottom = (row_top + PINNED_LINE_HEIGHT as usize).min(H as usize);
            (0..W as usize)
                .rev()
                .find(|&x| {
                    (row_top..row_bottom).any(|y| {
                        let off = y * stride + x * 4;
                        !(data[off] == 255 && data[off + 1] == 255 && data[off + 2] == 255)
                    })
                })
                .unwrap_or(0)
        };

        let small_editor_extent = cell_text_extent(&small_editor_font, None);
        let large_editor_extent = cell_text_extent(&large_editor_font, None);
        assert!(
            small_editor_extent.abs_diff(large_editor_extent) <= 1,
            "data table cell glyph extent must be editor-font-size independent: \
             small_editor={small_editor_extent}, large_editor={large_editor_extent}"
        );

        let ui_font_extent = cell_text_extent(&small_editor_font, Some("Sans 40"));
        assert!(
            ui_font_extent > small_editor_extent + 20,
            "changing ui_font alone must visibly widen the painted cell label: \
             default_ui_font={small_editor_extent}, ui_font_Sans_40={ui_font_extent}"
        );
    }

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

    /// `tree_vscrollbar` passes `line_height * 1.4` pitch (the actual row
    /// height `tree_layout` paints) as `TreeView::vscrollbar`'s
    /// `row_height`, not the raw `line_height`. With `current_line_height`
    /// at 16px default, 15 rows painted at the real 22.4px→22px pitch fit
    /// 13 into a 300px-tall viewport (300/22 = 13), so an overflow
    /// scrollbar must appear. The row pitch governs the minimum thumb
    /// length, not the track's (fixed 10px) width.
    #[test]
    fn gtk_backend_tree_vscrollbar_uses_tree_layout_row_pitch_not_raw_line_height() {
        let backend = GtkBackend::new();
        let tree = flat_tree(15);
        let rect = QRect::new(0.0, 0.0, 20.0, 300.0);

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

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

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

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

    /// `draw_list` paints item labels and icon glyphs with `ui_font`, not
    /// the editor-content layout's font. Paint the same single-item list
    /// under two wildly different "editor" font sizes with `ui_font` left
    /// at its default — the painted extent must be identical — then change
    /// `ui_font` alone as a positive control and see the extent move.
    #[test]
    fn gtk_backend_draw_list_uses_ui_font_not_editor_font() {
        let small_editor_font = pango::FontDescription::from_string("Sans 8");
        let large_editor_font = pango::FontDescription::from_string("Sans 40");
        const W: i32 = 1600;
        const H: i32 = 60;

        let row_text_extent = |editor_font: &pango::FontDescription, ui_font: Option<&str>| {
            let mut surface =
                pangocairo::cairo::ImageSurface::create(pangocairo::cairo::Format::ARgb32, W, H)
                    .expect("create ImageSurface");
            let list = ListView {
                id: WidgetId::new("test:list"),
                title: None,
                items: vec![crate::primitives::list::ListItem {
                    text: crate::types::StyledText::plain("m".to_string()),
                    icon: None,
                    detail: None,
                    decoration: crate::types::Decoration::Normal,
                }],
                selected_idx: 0,
                scroll_offset: 0,
                has_focus: false,
                bordered: false,
                h_scroll: 0,
                max_content_width: None,
                show_v_scrollbar: false,
            };
            let rect = QRect::new(0.0, 0.0, W as f32, H as f32);
            {
                let cr = pangocairo::cairo::Context::new(&surface).expect("Context::new");
                cr.set_source_rgb(1.0, 1.0, 1.0);
                cr.paint().ok();
                let pango_ctx = pangocairo::functions::create_context(&cr);
                pango_ctx.set_font_description(editor_font);
                let layout = pango::Layout::new(&pango_ctx);
                let mut backend = GtkBackend::new();
                // White `background` so the row's own fill doesn't itself
                // read as "non-white" and saturate the scan below.
                backend.set_current_theme(crate::Theme {
                    background: crate::types::Color::rgb(255, 255, 255),
                    foreground: crate::types::Color::rgb(0, 0, 0),
                    ..crate::Theme::default()
                });
                if let Some(f) = ui_font {
                    Backend::set_ui_font(&mut backend, f);
                }
                backend.enter_frame_scope(&cr, &layout, |b| {
                    b.draw_list(rect, &list);
                });
            }
            surface.flush();
            let stride = surface.stride() as usize;
            let data = surface.data().expect("surface data");
            // Rightmost non-white pixel within the first (only) row's
            // vertical span — proxy for the painted label's glyph extent.
            // `current_line_height` defaults to 16px, so y=10 sits inside
            // row 0 regardless of which font is under test.
            let y = 10usize;
            (0..W as usize)
                .rev()
                .find(|&x| {
                    let off = y * stride + x * 4;
                    !(data[off] == 255 && data[off + 1] == 255 && data[off + 2] == 255)
                })
                .unwrap_or(0)
        };

        let small_editor_extent = row_text_extent(&small_editor_font, None);
        let large_editor_extent = row_text_extent(&large_editor_font, None);
        assert!(
            small_editor_extent.abs_diff(large_editor_extent) <= 1,
            "list row glyph extent must be editor-font-size independent: \
             small_editor={small_editor_extent}, large_editor={large_editor_extent}"
        );

        let ui_font_extent = row_text_extent(&small_editor_font, Some("Sans 40"));
        assert!(
            ui_font_extent > small_editor_extent + 20,
            "changing ui_font alone must visibly widen the painted row label: \
             default_ui_font={small_editor_extent}, ui_font_Sans_40={ui_font_extent}"
        );
    }

    /// A consumer that budgets `ListView` row text from
    /// [`Backend::char_width`] under-fills the row, because `draw_list`
    /// paints in `ui_font`, not the editor font `char_width` measures.
    /// [`Backend::list_char_width`] exists so a consumer has a metric that
    /// agrees with what got painted. This test ties the two together
    /// mechanically, through the real per-frame `gtk::run::render_frame`
    /// path, so they can never silently diverge. Renders a real
    /// English-prose row label (proportional fonts don't wrap a synthetic
    /// `"MMMM…"` run the same way they wrap prose) with the editor font
    /// forced to a size wildly different from the `"Sans 11"` chrome
    /// default, then compares the label's actual painted width against
    /// both `list_char_width() * chars` and `char_width() * chars`.
    #[test]
    fn list_char_width_matches_what_draw_list_actually_paints() {
        use crate::runner::{AppLogic, Reaction};

        const ROW_TEXT: &str = "the quick brown fox jumps over";

        struct Fixture;
        impl AppLogic for Fixture {
            type AreaId = ();
            fn render(&self, backend: &mut dyn Backend, _area: ()) {
                let vp = backend.viewport();
                let list = ListView {
                    id: WidgetId::new("test:912:list-char-width"),
                    title: None,
                    items: vec![crate::primitives::list::ListItem {
                        text: crate::types::StyledText::plain(ROW_TEXT.to_string()),
                        icon: None,
                        detail: None,
                        decoration: crate::types::Decoration::Normal,
                    }],
                    selected_idx: 0,
                    scroll_offset: 0,
                    has_focus: false,
                    bordered: false,
                    h_scroll: 0,
                    max_content_width: None,
                    show_v_scrollbar: false,
                };
                let rect = QRect::new(0.0, 0.0, vp.width, vp.height);
                backend.draw_list(rect, &list);
            }
            fn handle(&mut self, _event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
                Reaction::Continue
            }
        }

        const W: i32 = 800;
        const H: i32 = 60;
        let surface =
            pangocairo::cairo::ImageSurface::create(pangocairo::cairo::Format::ARgb32, W, H)
                .expect("create ImageSurface");
        let mut backend = GtkBackend::new();
        backend.set_painted_text_recording(true);
        // Force the editor font to a wildly different size than the
        // ("Sans 11") chrome default — a bare "Monospace 11" vs. "Sans
        // 11" pairing isn't guaranteed to differ on every host (a
        // minimal fontconfig setup can resolve both generic aliases to
        // the same fallback face), which would make both assertions
        // below vacuously true. A 40pt/11pt size gap is guaranteed to
        // produce different advances regardless of which family either
        // alias resolves to, while `draw_list`'s painted width — which
        // paints in `ui_font`, not the editor font — must stay
        // exactly where it was.
        Backend::set_editor_font(&mut backend, "Monospace", 40.0);
        let cr = pangocairo::cairo::Context::new(&surface).expect("Context::new");
        crate::gtk::run::render_frame(&mut backend, &Fixture, &cr, W, H);

        let bounds = backend
            .painted_text_for_test()
            .iter()
            .find(|p| p.text == ROW_TEXT)
            .unwrap_or_else(|| {
                panic!("expected {ROW_TEXT:?} to have been recorded as painted text")
            })
            .bounds;

        let list_cw = Backend::list_char_width(&backend);
        let editor_cw = Backend::char_width(&backend);
        let chars = ROW_TEXT.chars().count() as f32;

        // Fixture assumption: the (forced-huge) editor font and the
        // ("Sans 11") chrome font must actually have visibly different
        // advances, or neither assertion below proves anything (they'd
        // both look "right" by accident).
        assert!(
            (editor_cw - list_cw).abs() > 0.5,
            "test fixture assumption broken: the editor font (forced to \
             \"Monospace 40\" above) and chrome font (\"Sans 11\") must \
             have visibly different advances for this test to prove \
             anything — editor_cw={editor_cw}, list_cw={list_cw}"
        );

        // `list_char_width()` — the font `draw_list` really painted with —
        // must predict the row's painted width at least as well as the
        // *editor* font's `char_width()` does. This is what regresses if
        // `draw_list`'s font ever changes without `list_char_width()`
        // following it (or vice versa): the naive `char_width()` budget would
        // silently start winning again.
        let list_predicted = list_cw * chars;
        let editor_predicted = editor_cw * chars;
        let list_err = (bounds.width - list_predicted).abs();
        let editor_err = (bounds.width - editor_predicted).abs();
        assert!(
            list_err < editor_err,
            "list_char_width() must predict draw_list's painted row width \
             better than char_width() does (quadraui#912) for {ROW_TEXT:?}: \
             painted_width={}, list_char_width()*{chars}={list_predicted} \
             (err={list_err}), char_width()*{chars}={editor_predicted} \
             (err={editor_err})",
            bounds.width,
        );
    }

    /// `draw_context_menu` paints dropdown item labels with `ui_font`, not
    /// the editor-content layout's font, so the bar and the dropdown under
    /// it visibly agree in the same frame. Paint a single-item dropdown
    /// under two wildly different "editor" font sizes with `ui_font` left
    /// at its default — the painted glyph extent must be identical — then
    /// change `ui_font` alone as a positive control and see the extent
    /// move.
    #[test]
    fn gtk_backend_draw_context_menu_uses_ui_font_not_editor_font() {
        let small_editor_font = pango::FontDescription::from_string("Sans 8");
        let large_editor_font = pango::FontDescription::from_string("Sans 40");
        const W: i32 = 1600;
        const H: i32 = 60;
        const ITEM_H: f32 = 40.0;

        let row_text_extent = |editor_font: &pango::FontDescription, ui_font: Option<&str>| {
            let mut surface =
                pangocairo::cairo::ImageSurface::create(pangocairo::cairo::Format::ARgb32, W, H)
                    .expect("create ImageSurface");
            let menu = crate::ContextMenu {
                id: WidgetId::new("test:menu"),
                items: vec![crate::primitives::context_menu::ContextMenuItem {
                    id: Some(WidgetId::new("test:menu:item")),
                    label: crate::types::StyledText::plain("mmmmmmmmmm".to_string()),
                    ..Default::default()
                }],
                // Out of range so no item ever paints as keyboard-selected —
                // the selection highlight isn't what this test measures.
                selected_idx: 1,
                bg: None,
                placement: crate::primitives::context_menu::ContextMenuPlacement::AnchorPoint,
            };
            let viewport = crate::event::Rect::new(0.0, 0.0, W as f32, H as f32);
            let menu_layout = menu.layout_at(
                crate::event::Rect::new(0.0, 0.0, 0.0, 0.0),
                viewport,
                300.0,
                |_| crate::primitives::context_menu::ContextMenuItemMeasure::new(ITEM_H),
            );
            {
                let cr = pangocairo::cairo::Context::new(&surface).expect("Context::new");
                cr.set_source_rgb(1.0, 1.0, 1.0);
                cr.paint().ok();
                let pango_ctx = pangocairo::functions::create_context(&cr);
                pango_ctx.set_font_description(editor_font);
                let layout = pango::Layout::new(&pango_ctx);
                let mut backend = GtkBackend::new();
                // White menu chrome so the box's own fill/border doesn't
                // itself read as "non-white" and saturate the scan below.
                backend.set_current_theme(crate::Theme {
                    hover_bg: crate::types::Color::rgb(255, 255, 255),
                    hover_border: crate::types::Color::rgb(255, 255, 255),
                    foreground: crate::types::Color::rgb(0, 0, 0),
                    ..crate::Theme::default()
                });
                if let Some(f) = ui_font {
                    Backend::set_ui_font(&mut backend, f);
                }
                backend.enter_frame_scope(&cr, &layout, |b| {
                    b.draw_context_menu(&menu, &menu_layout);
                });
            }
            surface.flush();
            let stride = surface.stride() as usize;
            let data = surface.data().expect("surface data");
            // Rightmost non-white pixel within the first (only) item
            // row's vertical span — proxy for the painted label's glyph
            // extent. The row spans `[0, ITEM_H)` regardless of font.
            let y = (ITEM_H / 2.0) as usize;
            (0..W as usize)
                .rev()
                .find(|&x| {
                    let off = y * stride + x * 4;
                    !(data[off] == 255 && data[off + 1] == 255 && data[off + 2] == 255)
                })
                .unwrap_or(0)
        };

        let small_editor_extent = row_text_extent(&small_editor_font, None);
        let large_editor_extent = row_text_extent(&large_editor_font, None);
        assert!(
            small_editor_extent.abs_diff(large_editor_extent) <= 1,
            "context menu item glyph extent must be editor-font-size independent: \
             small_editor={small_editor_extent}, large_editor={large_editor_extent}"
        );

        let ui_font_extent = row_text_extent(&small_editor_font, Some("Sans 40"));
        assert!(
            ui_font_extent > small_editor_extent + 20,
            "changing ui_font alone must visibly widen the painted item label: \
             default_ui_font={small_editor_extent}, ui_font_Sans_40={ui_font_extent}"
        );
    }

    /// `draw_context_menu_with_glyphs`'s `ContextMenuGlyphs` override
    /// replaces the checked-item check-mark glyph; `None` and an empty
    /// override (no fields set) must paint byte-identical to each other,
    /// and a populated `with_checked_glyph` override must visibly change
    /// the painted ink.
    #[test]
    fn gtk_backend_draw_context_menu_honors_checked_glyph_override() {
        const W: i32 = 300;
        const H: i32 = 40;
        const ITEM_H: f32 = 40.0;

        let menu = crate::ContextMenu {
            id: WidgetId::new("test:menu-glyphs"),
            items: vec![crate::primitives::context_menu::ContextMenuItem {
                id: Some(WidgetId::new("test:menu-glyphs:item")),
                label: crate::types::StyledText::plain("Word Wrap".to_string()),
                checked: Some(true),
                ..Default::default()
            }],
            selected_idx: 1,
            bg: None,
            placement: crate::primitives::context_menu::ContextMenuPlacement::AnchorPoint,
        };
        let viewport = crate::event::Rect::new(0.0, 0.0, W as f32, H as f32);
        let menu_layout = menu.layout_at(
            crate::event::Rect::new(0.0, 0.0, 0.0, 0.0),
            viewport,
            W as f32,
            |_| crate::primitives::context_menu::ContextMenuItemMeasure::new(ITEM_H),
        );

        let render = |glyphs: Option<&crate::primitives::context_menu::ContextMenuGlyphs>| {
            let mut surface =
                pangocairo::cairo::ImageSurface::create(pangocairo::cairo::Format::ARgb32, W, H)
                    .expect("create ImageSurface");
            {
                let cr = pangocairo::cairo::Context::new(&surface).expect("Context::new");
                cr.set_source_rgb(1.0, 1.0, 1.0);
                cr.paint().ok();
                let pango_ctx = pangocairo::functions::create_context(&cr);
                pango_ctx.set_font_description(&pango::FontDescription::from_string("Sans 8"));
                let layout = pango::Layout::new(&pango_ctx);
                let mut backend = GtkBackend::new();
                backend.enter_frame_scope(&cr, &layout, |b| {
                    b.draw_context_menu_with_glyphs(&menu, &menu_layout, glyphs);
                });
            }
            surface.flush();
            let stride = surface.stride() as usize;
            let data = surface.data().expect("surface data");
            data[..(H as usize) * stride].to_vec()
        };

        let default_pixels = render(None);
        let empty_override_pixels = render(Some(
            &crate::primitives::context_menu::ContextMenuGlyphs::new(),
        ));
        assert_eq!(
            default_pixels, empty_override_pixels,
            "an empty ContextMenuGlyphs override must paint byte-identical to None"
        );

        let overridden =
            crate::primitives::context_menu::ContextMenuGlyphs::new().with_checked_glyph("X");
        let override_pixels = render(Some(&overridden));
        assert_ne!(
            default_pixels, override_pixels,
            "a checked_glyph override must change the painted check-mark glyph"
        );
    }

    /// `draw_command_center` painted its arrows/search label with
    /// whatever font the frame's editor-content layout happened to
    /// carry, same gap as `draw_context_menu` above. Unlike the pixel-scan
    /// tests above, `gtk_command_center_layout` measures the search
    /// label's width against the same shared Pango layout it paints
    /// with, so the returned `search_bounds.width` is itself a direct
    /// font-size probe — no pixel scan needed.
    #[test]
    fn gtk_backend_draw_command_center_uses_ui_font_not_editor_font() {
        let small_editor_font = pango::FontDescription::from_string("Sans 8");
        let large_editor_font = pango::FontDescription::from_string("Sans 40");
        let surface =
            pangocairo::cairo::ImageSurface::create(pangocairo::cairo::Format::ARgb32, 400, 40)
                .expect("create ImageSurface");
        let cr = pangocairo::cairo::Context::new(&surface).expect("Context::new");
        let cc = crate::primitives::command_center::CommandCenter {
            id: WidgetId::new("test:command-center"),
            back_enabled: true,
            forward_enabled: true,
            search_label: "mmmmmmmmmm".to_string(),
        };
        let rect = QRect::new(0.0, 0.0, 400.0, 24.0);

        let search_width_at = |editor_font: &pango::FontDescription, ui_font: Option<&str>| {
            let pango_ctx = pangocairo::functions::create_context(&cr);
            pango_ctx.set_font_description(editor_font);
            let layout = pango::Layout::new(&pango_ctx);
            let mut backend = GtkBackend::new();
            if let Some(f) = ui_font {
                Backend::set_ui_font(&mut backend, f);
            }
            backend.enter_frame_scope(&cr, &layout, |b| {
                b.draw_command_center(rect, &cc)
                    .search_bounds
                    .expect("non-empty search_label produces search_bounds")
                    .width
            })
        };

        let small_editor_width = search_width_at(&small_editor_font, None);
        let large_editor_width = search_width_at(&large_editor_font, None);
        assert!(
            (small_editor_width - large_editor_width).abs() < 0.5,
            "command centre search box width must be editor-font-size independent: \
             small_editor={small_editor_width}, large_editor={large_editor_width}"
        );

        let ui_font_width = search_width_at(&small_editor_font, Some("Sans 40"));
        assert!(
            ui_font_width > small_editor_width * 1.5,
            "changing ui_font alone must visibly widen the painted search box: \
             default_ui_font={small_editor_width}, ui_font_Sans_40={ui_font_width}"
        );
    }

    /// `GtkBackend::command_center_layout` (the no-paint query path) must
    /// delegate straight to `CommandCenterMeasure::from_char_width` rather
    /// than keeping a private reimplementation of its formula. This test
    /// verifies the two agree, and asserts the same for
    /// `win::command_center::win_command_center_layout` against the
    /// identical shared constructor, so gtk and win compute the same
    /// command-center layout for the same char width.
    #[test]
    fn command_center_layout_delegates_to_shared_char_width_formula() {
        let mut backend = GtkBackend::new();
        backend.set_current_char_width(9.0);
        let cc = crate::primitives::command_center::CommandCenter {
            id: WidgetId::new("test:command-center"),
            back_enabled: true,
            forward_enabled: true,
            search_label: "project-name".to_string(),
        };
        let rect = QRect::new(3.0, 5.0, 400.0, 24.0);

        let layout = Backend::command_center_layout(&backend, rect, &cc);

        let expected = crate::primitives::command_center::CommandCenterMeasure::from_char_width(
            &cc.search_label,
            9.0,
            rect.height,
        );
        let search = layout
            .search_bounds
            .expect("non-empty search_label produces search_bounds");
        assert_eq!(search.width, expected.search_box_width);
    }

    fn ui_font_test_toolbar() -> crate::primitives::toolbar::Toolbar {
        crate::primitives::toolbar::Toolbar {
            id: WidgetId::new("test:toolbar"),
            buttons: vec![crate::primitives::toolbar::ToolbarButton::Action {
                id: WidgetId::new("test:toolbar:action"),
                label: "Refine".to_string(),
                icon: None,
                key_hint: None,
                enabled: true,
                is_active: false,
                tooltip: String::new(),
            }],
            bg: None,
            focused_index: None,
        }
    }

    /// `draw_toolbar` paints `ToolbarButton::Action` text with the UI font,
    /// not the editor font that may be live on the shared layout. Painted
    /// width must be independent of the editor font size, then move when
    /// `ui_font` itself changes. Same shape as
    /// `gtk_backend_draw_list_uses_ui_font_not_editor_font` above.
    #[test]
    fn gtk_backend_draw_toolbar_uses_ui_font_not_editor_font() {
        let (surface, small_editor_font, large_editor_font) = ui_font_test_surface_and_contexts();
        let cr = pangocairo::cairo::Context::new(&surface).expect("Context::new");
        let bar = ui_font_test_toolbar();
        let rect = QRect::new(0.0, 0.0, 400.0, 24.0);

        let width_at = |editor_font: &pango::FontDescription, ui_font: Option<&str>| {
            let pango_ctx = pangocairo::functions::create_context(&cr);
            pango_ctx.set_font_description(editor_font);
            let layout = pango::Layout::new(&pango_ctx);
            let mut backend = GtkBackend::new();
            if let Some(f) = ui_font {
                Backend::set_ui_font(&mut backend, f);
            }
            backend.enter_frame_scope(&cr, &layout, |b| {
                b.draw_toolbar_interactive(rect, &bar, &crate::InteractionState::new())
                    .visible_items[0]
                    .bounds
                    .width
            })
        };

        let small_editor_width = width_at(&small_editor_font, None);
        let large_editor_width = width_at(&large_editor_font, None);
        assert!(
            (small_editor_width - large_editor_width).abs() <= 1.0,
            "toolbar action width must be editor-font-size independent: \
             small_editor={small_editor_width}, large_editor={large_editor_width}"
        );

        let ui_font_width = width_at(&small_editor_font, Some("Sans 40"));
        assert!(
            ui_font_width > small_editor_width + 20.0,
            "changing ui_font alone must visibly widen the painted toolbar action: \
             default_ui_font={small_editor_width}, ui_font_Sans_40={ui_font_width}"
        );
    }

    /// Regression test: `draw_toolbar` paints with `ui_font` but
    /// `toolbar_layout` measures with the editor font outside frame scope.
    /// These must resolve identical button bounds, since hit-testing calls
    /// `Backend::toolbar_layout` between frames outside any
    /// `enter_frame_scope`. Deliberately measured with the editor font on
    /// both the frame layout and the stable `pango_ctx` so a regression
    /// that drops either swap shows up as a width mismatch.
    #[test]
    fn gtk_backend_toolbar_layout_matches_draw_toolbar_bounds_outside_frame() {
        let (surface, editor_font, _) = ui_font_test_surface_and_contexts();
        let cr = pangocairo::cairo::Context::new(&surface).expect("Context::new");
        let bar = ui_font_test_toolbar();
        let rect = QRect::new(0.0, 0.0, 400.0, 24.0);

        let pango_ctx = pangocairo::functions::create_context(&cr);
        pango_ctx.set_font_description(&editor_font);
        let layout = pango::Layout::new(&pango_ctx);
        let mut backend = GtkBackend::new();
        // Stable click-time context, as `gtk::run::activate` seeds it on
        // `DrawingArea` realize — also carrying the editor font, so the
        // hit-test path can only agree with paint by swapping onto
        // `ui_font` itself.
        let stable_ctx = pangocairo::functions::create_context(&cr);
        stable_ctx.set_font_description(&editor_font);
        backend.set_pango_context(stable_ctx);
        Backend::set_ui_font(&mut backend, "Sans 40");

        let painted = backend.enter_frame_scope(&cr, &layout, |b| {
            b.draw_toolbar_interactive(rect, &bar, &crate::InteractionState::new())
                .visible_items[0]
                .bounds
        });
        // Outside the frame scope — the click-time path.
        let hit_tested = Backend::toolbar_layout(&backend, rect, &bar).visible_items[0].bounds;

        assert!(
            (painted.width - hit_tested.width).abs() <= 1.0
                && (painted.x - hit_tested.x).abs() <= 1.0,
            "click-time toolbar_layout must resolve the same button bounds \
             draw_toolbar painted: painted={painted:?}, hit_tested={hit_tested:?}"
        );
    }

    /// `data_table_layout` is documented **LOCAL**:
    /// `GtkBackend`'s impl never reads `rect.x`/`rect.y` at all — it
    /// only forwards `rect.width`/`rect.height` to `DataTable::layout`
    /// — so a non-zero origin must produce byte-identical column/row
    /// geometry to the zero-origin case. This guards against a future
    /// edit that starts folding `rect.x`/`rect.y` in (an accidental
    /// switch to ABSOLUTE, the exact bug class `LESSONS.md`'s
    /// `mac_tree_layout` postmortem describes).
    #[test]
    fn gtk_backend_data_table_layout_ignores_rect_origin() {
        use crate::primitives::data_table::{Column, ColumnWidth, DataRow};
        use crate::types::StyledText;

        let table = crate::DataTable {
            id: WidgetId::new("dt"),
            columns: vec![Column {
                title: "Name".into(),
                width: ColumnWidth::Fixed(40.0),
                align: Default::default(),
            }],
            rows: vec![DataRow {
                cells: vec![StyledText::plain("a")],
                decoration: Default::default(),
            }],
            selected_idx: None,
            scroll_offset: 0,
            sort: None,
            has_focus: false,
            show_scrollbar: false,
            min_total_width: None,
            h_scroll: 0.0,
            column_overrides: vec![],
            footer: None,
        };

        let backend = GtkBackend::new();
        let at_origin =
            Backend::data_table_layout(&backend, QRect::new(0.0, 0.0, 100.0, 50.0), &table);
        let shifted =
            Backend::data_table_layout(&backend, QRect::new(7.0, 13.0, 100.0, 50.0), &table);

        assert_eq!(
            at_origin.columns, shifted.columns,
            "LOCAL data_table_layout must not shift column bounds by rect.x/rect.y"
        );
    }

    /// Regression test: a multi-byte column header must measure by
    /// **character count**, not UTF-8 byte length, on the click-routing
    /// path's no-live-Pango-context fallback measurer. `"日付"` is 2
    /// characters but 6 UTF-8 bytes; the measurer must match
    /// `PangoTextMeasure`'s `chars().count()`-based no-context estimate.
    #[test]
    fn gtk_backend_data_table_layout_measures_multibyte_header_by_char_count() {
        use crate::primitives::data_table::{Column, ColumnWidth, DataRow};
        use crate::types::StyledText;

        let title = "日付"; // 2 chars, 6 UTF-8 bytes
        let table = crate::DataTable {
            id: WidgetId::new("dt"),
            // A trailing `Fixed` column so `resolve_columns`'s pass 4
            // (#521 defect 2: stretch the *last* column to fill any
            // viewport leftover) grows that one instead of masking
            // the `Content` column's own measured width under test.
            columns: vec![
                Column {
                    title: title.into(),
                    width: ColumnWidth::Content {
                        min: 0.0,
                        max: 1000.0,
                    },
                    align: Default::default(),
                },
                Column {
                    title: "filler".into(),
                    width: ColumnWidth::Fixed(50.0),
                    align: Default::default(),
                },
            ],
            rows: vec![DataRow {
                cells: vec![StyledText::plain("x"), StyledText::plain("y")],
                decoration: Default::default(),
            }],
            selected_idx: None,
            scroll_offset: 0,
            sort: None,
            has_focus: false,
            show_scrollbar: false,
            min_total_width: None,
            h_scroll: 0.0,
            column_overrides: vec![],
            footer: None,
        };

        // Fresh backend: no `pango_ctx` set, so `data_table_layout` falls
        // back to the char-count estimate — exactly the path #1079's bug
        // lived in.
        let backend = GtkBackend::new();
        let layout =
            Backend::data_table_layout(&backend, QRect::new(0.0, 0.0, 500.0, 50.0), &table);

        let char_w = 8.0_f32; // `GtkBackend::new()`'s default `current_char_width`
        let byte_length_width = title.len() as f32 * char_w; // pre-#1079 bug's value
        let char_count_width = (title.chars().count() as f32 * char_w).ceil() + 2.0;

        assert_ne!(
            byte_length_width, char_count_width,
            "sanity: the two formulas must disagree for a multi-byte header"
        );
        assert_eq!(
            layout.columns[0].width, char_count_width,
            "multi-byte column header must measure by character count, not \
             UTF-8 byte length: got {}, expected the char-count estimate \
             {char_count_width} (byte-length bug would have produced {byte_length_width})",
            layout.columns[0].width,
        );
    }

    /// Before a widget realizes, `measure_text` must pick the
    /// *role*-appropriate cached advance (`current_chrome_char_width` for
    /// [`crate::FontRole::Chrome`], `current_char_width` for
    /// [`crate::FontRole::Editor`]) rather than the same one for both.
    /// The same mismatch hazard [`Backend::list_char_width`]'s doc describes.
    #[test]
    fn measure_text_fallback_picks_the_role_appropriate_char_width() {
        use crate::{Backend, FontRole};

        let mut backend = GtkBackend::new();
        backend.current_char_width = 8.0;
        backend.current_chrome_char_width = 20.0;
        backend.current_line_height = 16.0;

        let (chrome_w, chrome_h) = Backend::measure_text(&backend, "ab", FontRole::Chrome);
        let (editor_w, editor_h) = Backend::measure_text(&backend, "ab", FontRole::Editor);

        assert_eq!(chrome_w, (2.0_f32 * 20.0).ceil() + 2.0);
        assert_eq!(editor_w, (2.0_f32 * 8.0).ceil() + 2.0);
        assert_eq!(chrome_h, 16.0);
        assert_eq!(editor_h, 16.0);
    }

    /// `form_layout` is documented **LOCAL**: `GtkBackend`'s
    /// impl calls `form.layout(rect.width, rect.height, ..)` — `rect.x`/
    /// `rect.y` are never read — so a non-zero origin must produce
    /// byte-identical hit-region geometry to the zero-origin case.
    #[test]
    fn gtk_backend_form_layout_ignores_rect_origin() {
        use crate::primitives::form::{FieldKind, FormField};
        use crate::types::StyledText;

        let form = crate::primitives::form::Form {
            id: WidgetId::new("f"),
            fields: vec![FormField {
                id: WidgetId::new("f1"),
                label: StyledText::plain("Name"),
                kind: FieldKind::Label,
                hint: StyledText::plain(""),
                disabled: false,
                validation: None,
            }],
            focused_field: None,
            scroll_offset: 0,
            has_focus: false,
        };

        let backend = GtkBackend::new();
        let at_origin = Backend::form_layout(&backend, QRect::new(0.0, 0.0, 100.0, 50.0), &form);
        let shifted = Backend::form_layout(&backend, QRect::new(7.0, 13.0, 100.0, 50.0), &form);

        assert_eq!(
            at_origin.hit_regions, shifted.hit_regions,
            "LOCAL form_layout must not shift hit regions by rect.x/rect.y"
        );
    }

    /// `list_layout` is documented **LOCAL** — `GtkBackend`'s impl ignores
    /// `rect.x`/`rect.y` and calls `gtk_list_layout(rect.width, rect.height, ..)`.
    /// A non-zero origin must produce byte-identical geometry to the zero-origin
    /// case and match the exact `gtk_list_layout` helper `draw_list` uses.
    #[test]
    fn gtk_backend_list_layout_ignores_rect_origin_and_matches_helper() {
        let list = ListView {
            id: WidgetId::new("test:list"),
            title: None,
            items: vec![crate::primitives::list::ListItem {
                text: crate::types::StyledText::plain("only"),
                icon: None,
                detail: None,
                decoration: crate::types::Decoration::Normal,
            }],
            selected_idx: 0,
            scroll_offset: 0,
            has_focus: true,
            bordered: false,
            h_scroll: 0,
            max_content_width: None,
            show_v_scrollbar: false,
        };
        let backend = GtkBackend::new();

        let at_origin = Backend::list_layout(&backend, QRect::new(0.0, 0.0, 200.0, 100.0), &list);
        let shifted = Backend::list_layout(&backend, QRect::new(7.0, 13.0, 200.0, 100.0), &list);
        assert_eq!(
            at_origin, shifted,
            "LOCAL list_layout must not shift geometry by rect.x/rect.y"
        );

        let via_helper = crate::gtk::gtk_list_layout(
            200.0,
            100.0,
            &list,
            backend.current_line_height,
            backend.current_char_width,
        );
        assert_eq!(
            at_origin, via_helper,
            "list_layout must equal the exact helper draw_list uses internally"
        );
        assert!(
            !at_origin.visible_items.is_empty(),
            "sanity: the sample list has an item to lay out"
        );
    }

    /// The h-scrollbar row reservation must actually shrink the
    /// returned layout — not just avoid crashing — and `Backend::list_layout`
    /// must still equal the exact helper `draw_list` uses internally once
    /// that reservation is active. Companion to
    /// `gtk_backend_list_layout_ignores_rect_origin_and_matches_helper`
    /// above but with `max_content_width` forcing a scrollbar, so this
    /// specifically exercises the row-reservation math GTK now shares
    /// with macOS via `primitives::layout_metrics::list_layout` — a
    /// regression here would mean the two backends drifted apart again.
    #[test]
    fn gtk_backend_list_layout_reserves_hscrollbar_row_and_matches_helper() {
        let list = ListView {
            id: WidgetId::new("test:list"),
            title: None,
            items: (0..12)
                .map(|i| crate::primitives::list::ListItem {
                    text: crate::types::StyledText::plain(format!("row {i}")),
                    icon: None,
                    detail: None,
                    decoration: crate::types::Decoration::Normal,
                })
                .collect(),
            selected_idx: 0,
            scroll_offset: 0,
            has_focus: true,
            bordered: false,
            h_scroll: 0,
            // Way past any plausible visible width at the default 8px
            // char width, so this reliably forces the scrollbar.
            max_content_width: Some(1000),
            show_v_scrollbar: false,
        };
        let backend = GtkBackend::new();
        let rect = QRect::new(0.0, 0.0, 200.0, 100.0);

        let via_backend = Backend::list_layout(&backend, rect, &list);
        let via_helper = crate::gtk::gtk_list_layout(
            200.0,
            100.0,
            &list,
            backend.current_line_height,
            backend.current_char_width,
        );
        assert_eq!(
            via_backend, via_helper,
            "list_layout must equal the exact helper draw_list uses internally, \
             even when an h-scrollbar row is reserved"
        );

        // Sanity: the reservation actually happened — content stops
        // before filling the full 100px viewport height.
        let last = via_backend.visible_items.last().expect("has items");
        assert!(
            last.bounds.y + last.bounds.height <= 100.0 - backend.current_line_height as f32,
            "h-scrollbar row must be reserved: last row bottom = {}, \
             viewport height = 100, line_height = {}",
            last.bounds.y + last.bounds.height,
            backend.current_line_height,
        );
    }

    /// `board_layout` is documented **ABSOLUTE** — bounds are shifted by
    /// `rect.x`/`rect.y`, matching `BoardLayout::hit_test`'s contract.
    /// Both `board_layout` and `draw_board` route through `gtk_board_layout`.
    #[test]
    fn gtk_backend_board_layout_is_absolute_and_matches_helper() {
        let model = crate::primitives::board::BoardModel {
            id: WidgetId::new("test:board"),
            columns: vec![crate::primitives::board::BoardColumn {
                id: WidgetId::new("col:a"),
                title: "Backlog".into(),
                cards: vec![crate::primitives::board::BoardCard {
                    id: WidgetId::new("card:1"),
                    title: "Do the thing".into(),
                    labels: vec![],
                    badges: vec![],
                    hint: None,
                }],
                scroll_offset: 0,
            }],
            selected_card_id: None,
            col_scroll_offset: 0,
        };
        let backend = GtkBackend::new();
        let rect = QRect::new(5.0, 2.0, 400.0, 300.0);

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

        let via_helper = crate::gtk::gtk_board_layout(
            &model,
            rect.x as f64,
            rect.y as f64,
            rect.width as f64,
            rect.height as f64,
        );
        assert_eq!(
            no_paint, via_helper,
            "board_layout must equal the exact helper draw_board uses internally"
        );
    }

    /// `terminal_layout`'s default body must reserve the same scrollbar
    /// gutter width `draw_terminal` reserves before iterating cells
    /// (`cell_area_w = (rect.width - sb_width).max(0.0)`). Otherwise a click
    /// on the gutter resolves to `TerminalHit::Cell` when the paint path shows
    /// a scrollbar there. The last (gutter) column must not show the painted
    /// cell colour — this test proves that against real Cairo paint.
    #[test]
    fn gtk_backend_terminal_layout_reserves_scrollbar_gutter_matching_draw_terminal() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let bright = crate::types::Color::rgb(0, 255, 0);
        let cw = 10.0;
        let lh = 20.0;
        let w = 40;
        let h = 20;

        let mut backend = GtkBackend::new();
        backend.current_line_height = lh;
        backend.current_char_width = cw;
        let rect = QRect::new(0.0, 0.0, w as f32, h as f32);

        let cell = TerminalCell {
            text: " ".to_string(),
            fg: bright,
            bg: bright,
            bold: false,
            italic: false,
            underline: false,
            dim: false,
            selected: false,
            is_cursor: false,
            is_find_match: false,
            is_find_active: false,
            cursor_shape: TerminalCursorShape::Block,
            cursor_blinking: false,
        };
        let term = TerminalPrim {
            id: WidgetId::new("test:term-sb"),
            cells: vec![vec![cell; 4]],
            scrollbar: Some(crate::TerminalScrollbar {
                total_lines: 100,
                visible_lines: 1,
                scroll_offset: 0,
                inverted: false,
                // `None` — draw_terminal's `sb_width: … .unwrap_or(8.0)`
                // fallback, which `terminal_scrollbar_default_width` must
                // reproduce.
                width: None,
            }),
        };

        let layout = Backend::terminal_layout(&backend, rect, &term);
        // GTK's default scrollbar gutter is 8px: cell_area_w = 40 - 8 =
        // 32; grid_cols = floor(32 / char_width=10) = 3.
        assert_eq!(
            layout.grid_cols, 3,
            "terminal_layout must reserve the 8px scrollbar gutter default \
             (GtkBackend::terminal_scrollbar_default_width), matching draw_terminal's \
             `cell_area_w = (rect.width - sb_width).max(0.0)`"
        );
        assert_eq!(
            layout.hit_test(35.0, 0.0),
            crate::TerminalHit::Empty,
            "a click at x=35 (inside the 8px scrollbar gutter, cols 32..40) must not resolve to \
             a grid cell"
        );

        let mut surface = ImageSurface::create(Format::ARgb32, w, h).expect("create ImageSurface");
        {
            let cr = Context::new(&surface).expect("Context::new");
            let pango_layout = pangocairo::functions::create_layout(&cr);
            Backend::begin_frame(&mut backend, Viewport::new(w as f32, h as f32, 1.0));
            backend.enter_frame_scope(&cr, &pango_layout, |b| b.draw_terminal(rect, &term));
        }
        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        let probe = |x: i32, y: i32| -> (u8, u8, u8) {
            let off = y as usize * stride + x as usize * 4;
            (data[off + 2], data[off + 1], data[off])
        };

        assert_eq!(
            probe(5, 5),
            (0, 255, 0),
            "column 0 (inside grid_cols=3) must show the painted cell colour"
        );
        assert_ne!(
            probe(35, 5),
            (0, 255, 0),
            "x=35 sits inside draw_terminal's 8px scrollbar gutter — it must not show the \
             terminal cell colour, matching terminal_layout's grid_cols=3 exclusion of that \
             region"
        );
    }

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

    /// `diff_view_layout` is verified byte-for-byte against the real paint
    /// formula. Since #866, painting goes through `Backend::draw_diff_view`
    /// (the shared `primitives::diff_view::native_surface_paint::paint`),
    /// not a deprecated free-function shim. This routes through the real
    /// trait method, compares the no-paint default body against the exact
    /// value the real paint path produced, in `SideBySide` mode with a
    /// header row reserved.
    #[test]
    fn gtk_diff_view_layout_matches_draw_diff_view_side_by_side_with_header() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let mut backend = GtkBackend::new();
        backend.current_line_height = 20.0;
        let view = gtk_sample_diff_view(crate::DiffMode::SideBySide, Some("left.txt".into()));
        let rect = QRect::new(0.0, 0.0, 200.0, 100.0);

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

        let surface = ImageSurface::create(Format::ARgb32, 200, 100).expect("create ImageSurface");
        let cr = Context::new(&surface).expect("Context::new");
        let pango_layout = pangocairo::functions::create_layout(&cr);
        let painted = std::cell::RefCell::new(None);
        backend.enter_frame_scope(&cr, &pango_layout, |b| {
            *painted.borrow_mut() = Some(b.draw_diff_view(rect, &view));
        });
        let painted = painted.into_inner().expect("layout captured");

        assert_eq!(
            no_paint, painted,
            "diff_view_layout must equal the exact layout draw_diff_view painted with"
        );
        assert_eq!(
            no_paint.visible_rows, 4,
            "a 100px-tall rect minus a 20px header (left_label is set) leaves 4 content rows at \
             line_height=20"
        );
    }

    /// Same parity check in `Unified` mode, where no header row is
    /// reserved.
    #[test]
    fn gtk_diff_view_layout_matches_draw_diff_view_unified() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let mut backend = GtkBackend::new();
        backend.current_line_height = 20.0;
        let view = gtk_sample_diff_view(crate::DiffMode::Unified, None);
        let rect = QRect::new(0.0, 0.0, 200.0, 100.0);

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

        let surface = ImageSurface::create(Format::ARgb32, 200, 100).expect("create ImageSurface");
        let cr = Context::new(&surface).expect("Context::new");
        let pango_layout = pangocairo::functions::create_layout(&cr);
        let painted = std::cell::RefCell::new(None);
        backend.enter_frame_scope(&cr, &pango_layout, |b| {
            *painted.borrow_mut() = Some(b.draw_diff_view(rect, &view));
        });
        let painted = painted.into_inner().expect("layout captured");

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

    /// `editor_layout`'s default body must match the gutter/text geometry
    /// the paint path actually uses: `gutter_width = editor.gutter_char_width
    /// * char_width` and `text_x_offset = rect.x + gutter_width -
    /// h_scroll_offset`. The paint path uses `editor.rect`, not the `rect`
    /// argument, so callers must keep `editor.rect == rect` in sync.
    #[test]
    fn gtk_backend_editor_layout_matches_draw_editor_gutter_and_text_geometry() {
        let mut backend = GtkBackend::new();
        backend.current_char_width = 10.0;
        backend.current_line_height = 20.0;
        let rect = QRect::new(0.0, 0.0, 200.0, 100.0);
        let editor = crate::Editor {
            id: WidgetId::new("ed"),
            rect,
            lines: Vec::new(),
            cursor: None,
            extra_cursors: Vec::new(),
            selection: None,
            extra_selections: Vec::new(),
            yank_highlight: None,
            scroll_top: 0,
            scroll_left: 0,
            total_lines: 3,
            max_col: 4,
            gutter_char_width: 3,
            is_active: true,
            show_active_bg: false,
            has_git_diff: false,
            has_breakpoints: false,
            diagnostic_gutter: std::collections::HashMap::new(),
            code_action_lines: std::collections::HashSet::new(),
            bracket_match_positions: Vec::new(),
            active_indent_col: None,
            tabstop: 4,
            cursorline: false,
            lightbulb_glyph: '!',
        };

        let layout = Backend::editor_layout(&backend, rect, &editor);
        let gutter = layout
            .gutter_bounds
            .expect("gutter_char_width=3 must produce a gutter region");
        assert_eq!(
            gutter.width,
            editor.gutter_char_width as f32 * backend.current_char_width as f32,
            "editor_layout's gutter width must match draw_editor's `gutter_width = \
             editor.gutter_char_width * char_width` (src/gtk/editor.rs)"
        );
        assert_eq!(
            layout.text_bounds.x,
            rect.x + gutter.width,
            "editor_layout's text_bounds.x must match draw_editor's `text_x_offset = rect.x + \
             gutter_width` when scroll_left is 0 (src/gtk/editor.rs)"
        );

        // Paint via the real trait method with this exact geometry —
        // proves it doesn't panic and exercises the formula this test
        // pins.
        use pangocairo::cairo::{Context, Format, ImageSurface};
        let surface = ImageSurface::create(Format::ARgb32, 200, 100).expect("create ImageSurface");
        let cr = Context::new(&surface).expect("Context::new");
        let pango_layout = pangocairo::functions::create_layout(&cr);
        backend.enter_frame_scope(&cr, &pango_layout, |b| b.draw_editor(rect, &editor));
    }

    /// Paint an overflowing 200x80 editor through `GtkBackend::draw_editor`
    /// after `set_editor_v_scrollbar_width(v_scrollbar_w)`, returning
    /// the pixel colour at `(x, 76)` for each `x` in `xs` — a row inside
    /// the scrollbar track, below the thumb.
    fn editor_v_scrollbar_probe(v_scrollbar_w: Option<f32>, xs: &[i32]) -> Vec<(u8, u8, u8)> {
        use pangocairo::cairo::{Context, Format, ImageSurface};
        let rect = QRect::new(0.0, 0.0, 200.0, 80.0);
        let mut editor = crate::primitives::editor::Editor::new(WidgetId::new("ed"), rect);
        editor.total_lines = 50;
        let mut backend = GtkBackend::new();
        backend.set_editor_v_scrollbar_width(v_scrollbar_w);
        let mut surface =
            ImageSurface::create(Format::ARgb32, 200, 80).expect("create ImageSurface");
        {
            let cr = Context::new(&surface).expect("Context::new");
            let pango_layout = pangocairo::functions::create_layout(&cr);
            backend.enter_frame_scope(&cr, &pango_layout, |b| b.draw_editor(rect, &editor));
        }
        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        xs.iter()
            .map(|&x| {
                let off = 76 * stride + x as usize * 4;
                (data[off + 2], data[off + 1], data[off])
            })
            .collect()
    }

    /// `Backend::set_editor_v_scrollbar_width(Some(14.0))` makes
    /// `GtkBackend::draw_editor` paint a scrollbar column exactly 14px
    /// wide — `[186, 200)` in a 200px viewport — instead of one
    /// `current_char_width` (8px), and `Backend::editor_layout` reports
    /// the same column for hit-testing.
    #[test]
    fn gtk_backend_set_editor_v_scrollbar_width_paints_14px_column() {
        let bg = crate::Theme::default().background;
        let bg = (bg.r, bg.g, bg.b);
        let xs: Vec<i32> = (185..200).collect();
        let px = editor_v_scrollbar_probe(Some(14.0), &xs);
        assert_eq!(px[0], bg, "x=185 lies just left of the 14px column");
        for (x, p) in xs.iter().zip(&px).skip(1) {
            assert_ne!(*p, bg, "x={x} lies inside the 14px column [186, 200)");
        }

        let default_px = editor_v_scrollbar_probe(None, &[191, 192]);
        assert_eq!(
            default_px[0], bg,
            "default column is 8px: x=191 is text area"
        );
        assert_ne!(default_px[1], bg, "default column is 8px: x=192 is track");

        let mut backend = GtkBackend::new();
        backend.set_editor_v_scrollbar_width(Some(14.0));
        assert_eq!(backend.editor_v_scrollbar_width(), Some(14.0));
        let rect = QRect::new(0.0, 0.0, 200.0, 80.0);
        let mut editor = crate::primitives::editor::Editor::new(WidgetId::new("ed"), rect);
        editor.total_lines = 50;
        let vsb = Backend::editor_layout(&backend, rect, &editor)
            .v_scrollbar_bounds
            .expect("buffer overflows");
        assert_eq!((vsb.x, vsb.width), (186.0, 14.0));
    }

    /// `SidebarPanel` composes a `Toolbar` header internally — its button
    /// text is measured/drawn via `PaintSurface` methods that use whatever
    /// font is live on the shared `pango_layout`. The same editor-font leak
    /// the previous test guards against propagates here too unless
    /// `GtkBackend::draw_sidebar_panel` does its own save/swap/restore.
    #[test]
    fn gtk_backend_draw_sidebar_panel_toolbar_uses_ui_font_not_editor_font() {
        let (surface, small_editor_font, large_editor_font) = ui_font_test_surface_and_contexts();
        let cr = pangocairo::cairo::Context::new(&surface).expect("Context::new");
        let panel = crate::primitives::sidebar_panel::SidebarPanel {
            id: WidgetId::new("test:sidebar-panel"),
            toolbar: Some(ui_font_test_toolbar()),
            toolbar_height: None,
        };
        let rect = QRect::new(0.0, 0.0, 400.0, 200.0);

        let width_at = |editor_font: &pango::FontDescription, ui_font: Option<&str>| {
            let pango_ctx = pangocairo::functions::create_context(&cr);
            pango_ctx.set_font_description(editor_font);
            let layout = pango::Layout::new(&pango_ctx);
            let mut backend = GtkBackend::new();
            if let Some(f) = ui_font {
                Backend::set_ui_font(&mut backend, f);
            }
            backend.enter_frame_scope(&cr, &layout, |b| {
                b.draw_sidebar_panel_interactive(rect, &panel, &crate::InteractionState::new())
                    .toolbar_layout
                    .expect("panel has a toolbar")
                    .visible_items[0]
                    .bounds
                    .width
            })
        };

        let small_editor_width = width_at(&small_editor_font, None);
        let large_editor_width = width_at(&large_editor_font, None);
        assert!(
            (small_editor_width - large_editor_width).abs() <= 1.0,
            "sidebar-panel toolbar action width must be editor-font-size \
             independent: small_editor={small_editor_width}, \
             large_editor={large_editor_width}"
        );

        let ui_font_width = width_at(&small_editor_font, Some("Sans 40"));
        assert!(
            ui_font_width > small_editor_width + 20.0,
            "changing ui_font alone must visibly widen the painted \
             sidebar-panel toolbar action: default_ui_font={small_editor_width}, \
             ui_font_Sans_40={ui_font_width}"
        );
    }

    // --- #615: `tab_bar_layout` must shift by `rect.x` exactly once ---
    //
    // Ported from `tui_main::backend::TuiBackend`'s
    // `tab_bar_layout_returns_absolute_x_not_bar_relative` and
    // `tab_bar_layout_agrees_with_draw_tab_bar_on_coordinate_space`
    // (introduced for #552's audit). `GtkBackend::tab_bar_layout` had no
    // equivalent coverage, which is how #552's shared `shift_tab_bar_hits`
    // helper landed *alongside* a leftover hand-rolled `x_off` loop that
    // shifted every hit range a second time — every `TabBarHits` this
    // backend returned was one `rect.x` too far right whenever the bar
    // wasn't flush with the surface origin (i.e. whenever the sidebar was
    // open), silently breaking pixel-accurate close-button clicks.

    fn audit_bar() -> TabBar {
        TabBar {
            id: WidgetId::new("tabs"),
            tabs: vec![
                crate::primitives::tab_bar::TabItem {
                    label: "main.rs".into(),
                    is_active: true,
                    is_dirty: false,
                    is_preview: false,
                    is_closable: true,
                },
                crate::primitives::tab_bar::TabItem {
                    label: "lib.rs".into(),
                    is_active: false,
                    is_dirty: false,
                    is_preview: false,
                    is_closable: true,
                },
            ],
            right_segments: vec![],
            active_accent: None,
            scroll_offset: 0,
            show_tab_close: true,
            compact: false,
        }
    }

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

        let at_origin = backend.tab_bar_layout(QRect::new(0.0, 0.0, 400.0, 30.0), &bar);
        let shifted = backend.tab_bar_layout(QRect::new(418.0, 0.0, 400.0, 30.0), &bar);

        assert!(
            !at_origin.slot_positions.is_empty(),
            "sanity: some tabs should be laid out"
        );
        for (i, (base, moved)) in at_origin
            .slot_positions
            .iter()
            .zip(shifted.slot_positions.iter())
            .enumerate()
        {
            if *base == (0.0, 0.0) {
                // Scrolled-out sentinel — must stay recognisable, not
                // become (418.0, 418.0).
                assert_eq!(
                    *moved,
                    (0.0, 0.0),
                    "tab {i}: the scrolled-out sentinel must not be shifted"
                );
                continue;
            }
            assert_eq!(
                (moved.0, moved.1),
                (base.0 + 418.0, base.1 + 418.0),
                "tab {i}: `tab_bar_layout` is documented to return \
                 target-surface coordinates, so moving the bar right by \
                 418 must move its hit spans right by 418 exactly once \
                 (issue #615 — previously this backend applied the shift \
                 twice, via `shift_tab_bar_hits` and a leftover hand-rolled \
                 loop)"
            );
        }
    }

    /// The no-paint path must agree with the painting path, since callers
    /// use them interchangeably to route the same clicks. Both calls run
    /// inside the same `enter_frame_scope` so they measure text with the
    /// identical Pango layout — isolating the coordinate-shift bug from
    /// the separate frame-layout-vs-`pango_ctx` fallback behaviour
    /// already covered by the `menu_bar_layout` tests above.
    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` — issue #823
    fn gtk_backend_tab_bar_layout_agrees_with_draw_tab_bar_on_coordinate_space() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let surface = ImageSurface::create(Format::ARgb32, 800, 40).expect("create ImageSurface");
        let cr = Context::new(&surface).expect("Context::new");
        let pango_ctx = pangocairo::functions::create_context(&cr);
        let pango_layout = pango::Layout::new(&pango_ctx);

        let mut backend = GtkBackend::new();
        let bar = audit_bar();
        // Nonzero x: the whole point. At x = 0 the two paths agreed even
        // before the fix, which is exactly how the defect stayed hidden.
        let rect = QRect::new(418.0, 0.0, 400.0, 30.0);

        let (from_paint, from_layout) = backend.enter_frame_scope(&cr, &pango_layout, |b| {
            let painted = b.draw_tab_bar(rect, &bar, None);
            let layout = b.tab_bar_layout(rect, &bar);
            (painted, layout)
        });

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

    /// The icon-aware pair must agree the same way — and must
    /// actually differ from the icon-less pair, or the "reservation" is
    /// a no-op nobody would notice until a user clicked a decorated tab.
    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` — issue #823
    fn gtk_backend_tab_bar_layout_icons_agrees_with_draw_tab_bar_icons() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let surface = ImageSurface::create(Format::ARgb32, 800, 40).expect("create ImageSurface");
        let cr = Context::new(&surface).expect("Context::new");
        let pango_ctx = pangocairo::functions::create_context(&cr);
        let pango_layout = pango::Layout::new(&pango_ctx);

        let mut backend = GtkBackend::new();
        let bar = audit_bar();
        let icons = vec![
            Some(crate::TabIcon {
                glyph: "R".to_string(),
                color: crate::Color::rgb(222, 165, 132),
            }),
            None,
        ];
        let rect = QRect::new(418.0, 0.0, 400.0, 30.0);

        let (from_paint, from_layout, plain_layout) =
            backend.enter_frame_scope(&cr, &pango_layout, |b| {
                let painted = b.draw_tab_bar_icons(rect, &bar, &icons, None);
                let layout = b.tab_bar_layout_icons(rect, &bar, &icons);
                let plain = b.tab_bar_layout(rect, &bar);
                (painted, layout, plain)
            });

        assert_eq!(
            from_layout.slot_positions, from_paint.slot_positions,
            "`tab_bar_layout_icons` must report the same tab slots \
             `draw_tab_bar_icons` painted — a caller routing clicks \
             through the no-paint twin otherwise lands left of every \
             glyph on a decorated bar"
        );
        assert_eq!(
            from_layout.close_bounds, from_paint.close_bounds,
            "close-button spans must match between the icon-aware paint \
             and no-paint paths too"
        );
        assert_ne!(
            from_layout.slot_positions, plain_layout.slot_positions,
            "an icon on tab 0 must widen its slot, so the icon-aware \
             layout cannot equal the icon-less one"
        );
        // Tab 1 carries no icon, so only the *upstream* reservation moves
        // it: its width must be unchanged.
        let width = |s: &(f64, f64)| s.1 - s.0;
        assert!(
            (width(&from_layout.slot_positions[1]) - width(&plain_layout.slot_positions[1])).abs()
                < 0.001,
            "an undecorated tab must keep byte-identical width: {:?} vs {:?}",
            from_layout.slot_positions[1],
            plain_layout.slot_positions[1]
        );
    }

    /// `tab_bar_layout_with_chrome` must actually populate
    /// `TabBarHits::available_cols` with the shared helper's estimate, not
    /// leave it at the old bar-width-in-pixels placeholder. This compares
    /// against the known-good value from `tab_bar_layout` with equivalent
    /// inputs (no icons, default chrome).
    #[test]
    #[allow(deprecated)] // exercises the deprecated `TabBarHits` — issue #823
    fn gtk_backend_tab_bar_layout_with_chrome_populates_available_cols() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let surface = ImageSurface::create(Format::ARgb32, 800, 40).expect("create ImageSurface");
        let cr = Context::new(&surface).expect("Context::new");
        let pango_ctx = pangocairo::functions::create_context(&cr);
        let pango_layout = pango::Layout::new(&pango_ctx);

        let mut backend = GtkBackend::new();
        let bar = audit_bar();
        let rect = QRect::new(0.0, 0.0, 400.0, 30.0);

        let (from_chrome, from_plain) = backend.enter_frame_scope(&cr, &pango_layout, |b| {
            let chrome = b.tab_bar_layout_with_chrome(rect, &bar, &TabChrome::default());
            let plain = b.tab_bar_layout(rect, &bar);
            (chrome, plain)
        });

        assert!(
            from_chrome.available_cols > 0,
            "sanity: an 800px-wide surface must yield a nonzero character-column estimate"
        );
        assert_eq!(
            from_chrome.available_cols, from_plain.available_cols,
            "`tab_bar_layout_with_chrome` (default chrome, no icons) must \
             report the same `available_cols` as `tab_bar_layout` — both \
             route through the shared `pixel_tab_bar_layout` with \
             equivalent inputs, so a divergence means one of them still \
             discards the shared estimate instead of assigning it"
        );
    }

    // ── #417 dirty-row fast path ─────────────────────────────────────
    //
    // These tests drive `GtkBackend::draw_terminal` across several
    // frames against one shared `ImageSurface` — a fresh `cairo::Context`
    // per frame, same backing pixels, mirroring how GTK gives
    // `set_draw_func` a new `Context` every call while the widget's
    // render surface persists underneath (see the resize-ghosting note
    // on `draw_terminal` and `gtk/run.rs`'s `connect_resize` handler).
    // Between frames a throwaway `Context` paints a "corruption" colour
    // directly over one row's cell — standing in for whatever a *skipped*
    // repaint would fail to erase — so a passing test proves the row was
    // (or wasn't) actually touched by the following `draw_terminal` call,
    // not just that the end colour happens to match by coincidence.

    /// A one-cell row whose only visible output is a solid `bg` fill.
    ///
    /// `text` is a space **on purpose**, so `draw_terminal_cells` fills the
    /// cell rectangle and draws no glyph at all. These tests probe a
    /// *fixed* pixel inside a cell and assert it equals that row's
    /// background, but where a glyph's strokes land — and how far past the
    /// `line_height`-tall cell box they bleed — is a property of whatever
    /// font Pango happens to default to on the host, which is not the same
    /// on a dev machine and on the `gtk` CI runner.
    ///
    /// That is not hypothetical: the first cut of these tests used
    /// `text: "X"` with a contrasting `fg`. The local default (`serif 12`)
    /// rasterises `X` into rows 6..=17 of a 20px cell with a natural height
    /// of 23px, so it cleared the row-relative y=5 probe by *one* pixel
    /// above and bled 3px into the row below — passing locally by a margin
    /// no font is obliged to reproduce, and failing on CI. Re-running these
    /// tests with the layout forced to `monospace 22` reproduces the CI
    /// failure exactly (the row above's glyph bleeds down over the probed
    /// pixel), which is what this shape rules out for good.
    ///
    /// Glyph rasterisation under the dirty-row filter is covered — with
    /// real glyphs — by `gtk::terminal::tests`, whose probes are positioned
    /// so no neighbouring row can paint over them.
    fn term_row_417(bg: crate::types::Color) -> Vec<TerminalCell> {
        vec![TerminalCell {
            text: " ".to_string(),
            fg: bg,
            bg,
            bold: false,
            italic: false,
            underline: false,
            dim: false,
            selected: false,
            is_cursor: false,
            is_find_match: false,
            is_find_active: false,
            cursor_shape: TerminalCursorShape::Block,
            cursor_blinking: false,
        }]
    }

    /// Read an RGB triple from an ARgb32 surface at pixel (x, y).
    fn probe_pixel_417(data: &[u8], stride: usize, x: i32, y: i32) -> (u8, u8, u8) {
        let off = y as usize * stride + x as usize * 4;
        (data[off + 2], data[off + 1], data[off])
    }

    /// Paint a solid colour directly over `(x, y, w, h)` on `surface`,
    /// bypassing `draw_terminal` entirely — the "corruption" stand-in
    /// described above.
    fn paint_corruption_417(
        surface: &pangocairo::cairo::ImageSurface,
        x: f64,
        y: f64,
        w: f64,
        h: f64,
        color: crate::types::Color,
    ) {
        let cr = pangocairo::cairo::Context::new(surface).expect("Context::new");
        cr.rectangle(x, y, w, h);
        cr.set_source_rgb(
            color.r as f64 / 255.0,
            color.g as f64 / 255.0,
            color.b as f64 / 255.0,
        );
        cr.fill().ok();
    }

    const TERM_417_W: i32 = 40;
    const TERM_417_H: i32 = 40;
    const TERM_417_LH: f64 = 20.0;
    const TERM_417_CW: f64 = 10.0;

    #[test]
    fn draw_terminal_fast_path_does_not_repaint_unchanged_rows() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let red = crate::types::Color::rgb(200, 0, 0);
        let blue = crate::types::Color::rgb(0, 0, 200);
        let green = crate::types::Color::rgb(0, 200, 0);
        let magenta = crate::types::Color::rgb(200, 0, 200);

        let mut backend = GtkBackend::new();
        backend.current_line_height = TERM_417_LH;
        backend.current_char_width = TERM_417_CW;
        let mut surface = ImageSurface::create(Format::ARgb32, TERM_417_W, TERM_417_H)
            .expect("create ImageSurface");
        let rect = QRect::new(0.0, 0.0, TERM_417_W as f32, TERM_417_H as f32);
        let id = WidgetId::new("test:term");

        // Frame 1: full paint — row 0 red, row 1 blue.
        let term1 = TerminalPrim {
            id: id.clone(),
            cells: vec![term_row_417(red), term_row_417(blue)],
            scrollbar: None,
        };
        {
            let cr = Context::new(&surface).expect("Context::new");
            let layout = pangocairo::functions::create_layout(&cr);
            Backend::begin_frame(
                &mut backend,
                Viewport::new(TERM_417_W as f32, TERM_417_H as f32, 1.0),
            );
            backend.enter_frame_scope(&cr, &layout, |b| b.draw_terminal(rect, &term1));
        }

        // Stand-in for "whatever a skipped repaint would fail to erase":
        // paint row 1's cell magenta directly, bypassing draw_terminal.
        paint_corruption_417(
            &surface,
            0.0,
            TERM_417_LH,
            TERM_417_CW,
            TERM_417_LH,
            magenta,
        );

        // Frame 2: row 0 changes to green; row 1's `TerminalCell` is
        // byte-identical to frame 1's, so `dirty_rows` must report only
        // row 0 — the fast path should leave row 1 (now magenta) alone.
        let term2 = TerminalPrim {
            id: id.clone(),
            cells: vec![term_row_417(green), term_row_417(blue)],
            scrollbar: None,
        };
        {
            let cr = Context::new(&surface).expect("Context::new");
            let layout = pangocairo::functions::create_layout(&cr);
            Backend::begin_frame(
                &mut backend,
                Viewport::new(TERM_417_W as f32, TERM_417_H as f32, 1.0),
            );
            backend.enter_frame_scope(&cr, &layout, |b| b.draw_terminal(rect, &term2));
        }

        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        assert_eq!(
            probe_pixel_417(&data, stride, 5, 5),
            (green.r, green.g, green.b),
            "row 0 (dirty) must be repainted with its new colour"
        );
        assert_eq!(
            probe_pixel_417(&data, stride, 5, TERM_417_LH as i32 + 5),
            (magenta.r, magenta.g, magenta.b),
            "row 1 (clean) must not be touched by the fast path — the \
             corruption colour proves draw_terminal skipped it entirely"
        );
    }

    #[test]
    fn draw_terminal_full_repaint_after_a_skipped_frame() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let red = crate::types::Color::rgb(200, 0, 0);
        let blue = crate::types::Color::rgb(0, 0, 200);
        let magenta = crate::types::Color::rgb(200, 0, 200);

        let mut backend = GtkBackend::new();
        backend.current_line_height = TERM_417_LH;
        backend.current_char_width = TERM_417_CW;
        let mut surface = ImageSurface::create(Format::ARgb32, TERM_417_W, TERM_417_H)
            .expect("create ImageSurface");
        let rect = QRect::new(0.0, 0.0, TERM_417_W as f32, TERM_417_H as f32);
        let id = WidgetId::new("test:term");
        let term = TerminalPrim {
            id: id.clone(),
            cells: vec![term_row_417(red), term_row_417(blue)],
            scrollbar: None,
        };
        let viewport = Viewport::new(TERM_417_W as f32, TERM_417_H as f32, 1.0);

        // Frame 1: full paint.
        {
            let cr = Context::new(&surface).expect("Context::new");
            let layout = pangocairo::functions::create_layout(&cr);
            Backend::begin_frame(&mut backend, viewport);
            backend.enter_frame_scope(&cr, &layout, |b| b.draw_terminal(rect, &term));
        }

        // Simulate something else painting over row 1 while this
        // terminal pane goes unpainted for a frame (e.g. a tab switch
        // away and back) — `begin_frame` fires with no matching
        // `draw_terminal` call for this id, opening the gap the
        // `painted_frame` guard exists to catch.
        Backend::begin_frame(&mut backend, viewport);
        paint_corruption_417(
            &surface,
            0.0,
            TERM_417_LH,
            TERM_417_CW,
            TERM_417_LH,
            magenta,
        );

        // Frame 3: content is byte-identical to frame 1's, but the
        // one-frame gap must force a full repaint rather than trusting
        // the (now stale) cache.
        {
            let cr = Context::new(&surface).expect("Context::new");
            let layout = pangocairo::functions::create_layout(&cr);
            Backend::begin_frame(&mut backend, viewport);
            backend.enter_frame_scope(&cr, &layout, |b| b.draw_terminal(rect, &term));
        }

        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        assert_eq!(
            probe_pixel_417(&data, stride, 5, TERM_417_LH as i32 + 5),
            (blue.r, blue.g, blue.b),
            "a paint gap must force a full repaint, erasing whatever \
             painted over this terminal's pixels while it was skipped"
        );
    }

    #[test]
    fn draw_terminal_full_repaint_after_a_modal_opened_and_closed() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let red = crate::types::Color::rgb(200, 0, 0);
        let blue = crate::types::Color::rgb(0, 0, 200);
        let magenta = crate::types::Color::rgb(200, 0, 200);

        let mut backend = GtkBackend::new();
        backend.current_line_height = TERM_417_LH;
        backend.current_char_width = TERM_417_CW;
        let mut surface = ImageSurface::create(Format::ARgb32, TERM_417_W, TERM_417_H)
            .expect("create ImageSurface");
        let rect = QRect::new(0.0, 0.0, TERM_417_W as f32, TERM_417_H as f32);
        let id = WidgetId::new("test:term");
        let term = TerminalPrim {
            id: id.clone(),
            cells: vec![term_row_417(red), term_row_417(blue)],
            scrollbar: None,
        };
        let viewport = Viewport::new(TERM_417_W as f32, TERM_417_H as f32, 1.0);

        // Frame 1: full paint, no modal open.
        {
            let cr = Context::new(&surface).expect("Context::new");
            let layout = pangocairo::functions::create_layout(&cr);
            Backend::begin_frame(&mut backend, viewport);
            backend.enter_frame_scope(&cr, &layout, |b| b.draw_terminal(rect, &term));
        }

        // Frame 2: a context menu / dialog / palette opens and overlaps
        // the terminal pane, painting after it in z-order.
        backend
            .modal_stack_handle()
            .borrow_mut()
            .push(WidgetId::new("test:menu"), QRect::new(0.0, 0.0, 10.0, 10.0));
        {
            let cr = Context::new(&surface).expect("Context::new");
            let layout = pangocairo::functions::create_layout(&cr);
            Backend::begin_frame(&mut backend, viewport);
            backend.enter_frame_scope(&cr, &layout, |b| b.draw_terminal(rect, &term));
        }
        paint_corruption_417(
            &surface,
            0.0,
            TERM_417_LH,
            TERM_417_CW,
            TERM_417_LH,
            magenta,
        );

        // Frame 3: the modal closes. Content is unchanged, but the
        // modal's paint over row 1 in frame 2 means the cache from
        // *before* the modal opened can't be trusted — it must force a
        // full repaint rather than skip row 1.
        backend.modal_stack_handle().borrow_mut().pop_top();
        {
            let cr = Context::new(&surface).expect("Context::new");
            let layout = pangocairo::functions::create_layout(&cr);
            Backend::begin_frame(&mut backend, viewport);
            backend.enter_frame_scope(&cr, &layout, |b| b.draw_terminal(rect, &term));
        }

        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        assert_eq!(
            probe_pixel_417(&data, stride, 5, TERM_417_LH as i32 + 5),
            (blue.r, blue.g, blue.b),
            "closing a modal that overlapped the terminal must force a \
             full repaint, erasing its overlay"
        );
    }

    #[test]
    fn draw_terminal_full_repaint_after_theme_change() {
        // Regression test for the #417 review finding: `set_theme` (a
        // consumer-callable trait method — a live dark/light toggle) was
        // not plumbed into `TermPaintCache`'s validity guard. `dirty_rows`
        // only diffs `TerminalCell` content, so a theme swap with
        // byte-identical cells between two frames used to be invisible to
        // the fast path — leaving stale theme-derived overlay colours
        // (`selected` / `is_cursor` / `is_find_match`, see
        // `primitives/terminal.rs`) on screen. This proves a theme change
        // alone now forces a full repaint, even with unchanged content and
        // no modal/gap in between.
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let red = crate::types::Color::rgb(200, 0, 0);
        let blue = crate::types::Color::rgb(0, 0, 200);
        let magenta = crate::types::Color::rgb(200, 0, 200);

        let mut backend = GtkBackend::new();
        backend.current_line_height = TERM_417_LH;
        backend.current_char_width = TERM_417_CW;
        let mut surface = ImageSurface::create(Format::ARgb32, TERM_417_W, TERM_417_H)
            .expect("create ImageSurface");
        let rect = QRect::new(0.0, 0.0, TERM_417_W as f32, TERM_417_H as f32);
        let id = WidgetId::new("test:term");
        let term = TerminalPrim {
            id: id.clone(),
            cells: vec![term_row_417(red), term_row_417(blue)],
            scrollbar: None,
        };
        let viewport = Viewport::new(TERM_417_W as f32, TERM_417_H as f32, 1.0);

        // Frame 1: full paint under the default (dark) theme.
        {
            let cr = Context::new(&surface).expect("Context::new");
            let layout = pangocairo::functions::create_layout(&cr);
            Backend::begin_frame(&mut backend, viewport);
            backend.enter_frame_scope(&cr, &layout, |b| b.draw_terminal(rect, &term));
        }

        // Simulate a skipped repaint of row 1 so the test can tell "was
        // this row actually repainted" from "did it just happen to still
        // be correct" — same technique as the sibling tests above.
        paint_corruption_417(
            &surface,
            0.0,
            TERM_417_LH,
            TERM_417_CW,
            TERM_417_LH,
            magenta,
        );

        // Frame 2: content is byte-identical to frame 1's — no scroll, no
        // new PTY bytes, no modal — but the app calls `set_theme` (e.g. a
        // dark/light toggle) in between. This alone must force a full
        // repaint rather than trusting the (now theme-stale) cache.
        Backend::set_theme(
            &mut backend,
            crate::Theme {
                background: crate::types::Color::rgb(255, 255, 255),
                foreground: crate::types::Color::rgb(0, 0, 0),
                ..crate::Theme::default()
            },
        );
        {
            let cr = Context::new(&surface).expect("Context::new");
            let layout = pangocairo::functions::create_layout(&cr);
            Backend::begin_frame(&mut backend, viewport);
            backend.enter_frame_scope(&cr, &layout, |b| b.draw_terminal(rect, &term));
        }

        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        assert_eq!(
            probe_pixel_417(&data, stride, 5, TERM_417_LH as i32 + 5),
            (blue.r, blue.g, blue.b),
            "a theme change must force a full repaint even with unchanged \
             cell content, so theme-derived overlay colours never go stale"
        );
    }

    /// The full-pane blank-area clear in `draw_terminal` must use the
    /// active theme's background, not a hardcoded dark colour. A light
    /// theme's terminal pane must show the correct colour wherever the cell
    /// grid doesn't cover the full rect.
    #[test]
    fn draw_terminal_blank_area_fill_uses_theme_background() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let light_bg = crate::types::Color::rgb(250, 250, 245);
        let red = crate::types::Color::rgb(200, 0, 0);

        let mut backend = GtkBackend::new();
        backend.current_line_height = TERM_417_LH;
        backend.current_char_width = TERM_417_CW;
        Backend::set_theme(
            &mut backend,
            crate::Theme {
                background: light_bg,
                foreground: crate::types::Color::rgb(20, 20, 20),
                ..crate::Theme::light_default()
            },
        );
        let mut surface = ImageSurface::create(Format::ARgb32, TERM_417_W, TERM_417_H)
            .expect("create ImageSurface");
        let rect = QRect::new(0.0, 0.0, TERM_417_W as f32, TERM_417_H as f32);
        let id = WidgetId::new("test:term");

        // Only row 0 has content (`TERM_417_H` / `TERM_417_LH` = 2 rows
        // tall) — row 1's `y` range is never touched by any cell paint,
        // so it must come from the blank-area fill.
        let term = TerminalPrim {
            id: id.clone(),
            cells: vec![term_row_417(red)],
            scrollbar: None,
        };
        let viewport = Viewport::new(TERM_417_W as f32, TERM_417_H as f32, 1.0);

        {
            let cr = Context::new(&surface).expect("Context::new");
            let layout = pangocairo::functions::create_layout(&cr);
            Backend::begin_frame(&mut backend, viewport);
            backend.enter_frame_scope(&cr, &layout, |b| b.draw_terminal(rect, &term));
        }

        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        assert_eq!(
            probe_pixel_417(&data, stride, 5, TERM_417_LH as i32 + 5),
            (light_bg.r, light_bg.g, light_bg.b),
            "the blank area below the last content row must be filled \
             with the theme's background, not a hardcoded dark literal"
        );
    }

    // ── PaintSurface (#807, Phase 1) ────────────────────────────────

    #[test]
    fn gtk_backend_paint_surface_fill_rect_paints_solid_color() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let mut surface =
            ImageSurface::create(Format::ARgb32, 40, 40).expect("create ImageSurface");
        let mut backend = GtkBackend::new();
        let red = Color::rgb(200, 20, 20);

        {
            // `cr`/`pango_layout` must drop before `surface.data()` below —
            // cairo's `ImageSurface::data()` needs an exclusive reference,
            // which a live `Context` still borrowing `surface` denies
            // (mirrors `gtk_backend_theme_change_forces_full_repaint...`'s
            // block-scoped `cr` a few tests up).
            let cr = Context::new(&surface).expect("Context::new");
            let pango_ctx = pangocairo::functions::create_context(&cr);
            let pango_layout = pango::Layout::new(&pango_ctx);
            backend.enter_frame_scope(&cr, &pango_layout, |b| {
                b.surface_fill_rect(QRect::new(0.0, 0.0, 40.0, 40.0), red);
            });
        }

        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        assert_eq!(
            probe_pixel_417(&data, stride, 5, 5),
            (red.r, red.g, red.b),
            "surface_fill_rect must paint the solid color it was given"
        );
    }

    /// Not a pixel-precision test for every verb (that's `fill_rect`'s job
    /// above) — this exercises every remaining `PaintSurface` method at
    /// least once end-to-end (frame lifecycle, measurement, stroke, line,
    /// clip push/pop, text run, image) so the trait has a real caller
    /// (dead_code would otherwise fire — nothing else calls
    /// `PaintSurface` methods yet, by Phase 1's design) and so an
    /// implementation bug (wrong arg order, a swapped field, a panic
    /// inside the frame-scope guard) fails a test instead of shipping
    /// silently.
    #[test]
    fn gtk_backend_paint_surface_verbs_do_not_panic() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let surface = ImageSurface::create(Format::ARgb32, 100, 60).expect("create ImageSurface");
        let cr = Context::new(&surface).expect("Context::new");
        let pango_ctx = pangocairo::functions::create_context(&cr);
        let pango_layout = pango::Layout::new(&pango_ctx);
        let mut backend = GtkBackend::new();
        let viewport = Viewport::new(100.0, 60.0, 1.0);

        backend.surface_begin_frame(viewport);
        assert_eq!(
            backend.surface_viewport(),
            viewport,
            "surface_viewport must forward to Backend::begin_frame's stored value"
        );
        assert_eq!(
            backend.surface_line_height(),
            Backend::line_height(&backend)
        );
        assert_eq!(backend.surface_char_width(), Backend::char_width(&backend));

        backend.enter_frame_scope(&cr, &pango_layout, |b| {
            let blue = Color::rgb(20, 20, 200);
            let white = Color::rgb(255, 255, 255);
            b.surface_stroke_rect(QRect::new(0.0, 0.0, 40.0, 40.0), blue, 2.0);
            b.surface_draw_line(Point::new(0.0, 0.0), Point::new(40.0, 40.0), blue, 1.0);
            b.surface_push_clip(QRect::new(0.0, 0.0, 40.0, 40.0));
            b.surface_draw_text_run(QRect::new(2.0, 2.0, 30.0, 10.0), "hi", white);
            b.surface_pop_clip();

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

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

        backend.surface_end_frame();
    }

    // ── Style ─────────────────────────────────────────────────────────

    /// `Backend::draw_focus_ring` reads `Style::focus_ring_width`, not a
    /// hardcoded literal — proven by painting the same rect at two very
    /// different stroke widths and probing a pixel that only the wider
    /// one reaches. A probe point close to a corner would also pick up
    /// the perpendicular edge's own band, so this checks the midpoint of
    /// the top edge instead, straight-line distance only.
    #[test]
    fn gtk_backend_draw_focus_ring_honors_style_focus_ring_width() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        // Rect top edge sits at y = 5; midpoint of the top edge is at
        // x = 20. Cairo centers a stroked path on the line, so a stroke
        // of width `w` covers `y` in `[5 - w/2, 5 + w/2]`. At `y = 10`
        // (5 px below the edge): the default `2.0` width's half-width of
        // `1.0` falls well short (`[4, 6]`), but a `14.0` width's
        // half-width of `7.0` reaches it (`[-2, 12]`).
        const RECT: QRect = QRect::new(5.0, 5.0, 30.0, 30.0);
        const PROBE_X: i32 = 20;
        const PROBE_Y: i32 = 10;

        let paint_with_width = |focus_ring_width: f32| -> (u8, u8, u8) {
            let mut surface =
                ImageSurface::create(Format::ARgb32, 40, 40).expect("create ImageSurface");
            let mut backend = GtkBackend::new();
            let theme = crate::Theme {
                accent_fg: Color::rgb(140, 200, 240),
                ..crate::Theme::default()
            };
            backend.set_theme(theme);
            backend.set_style(crate::Style::default().with_focus_ring_width(focus_ring_width));

            {
                let cr = Context::new(&surface).expect("Context::new");
                // White background so the unpainted-vs-painted probe
                // doesn't rely on cairo's zero-initialized (black,
                // transparent) default — distinguishing "untouched" from
                // "painted dark" would otherwise be ambiguous.
                cr.set_source_rgb(1.0, 1.0, 1.0);
                cr.paint().ok();
                let pango_ctx = pangocairo::functions::create_context(&cr);
                let pango_layout = pango::Layout::new(&pango_ctx);
                backend.enter_frame_scope(&cr, &pango_layout, |b| {
                    b.draw_focus_ring(RECT);
                });
            }

            surface.flush();
            let stride = surface.stride() as usize;
            let data = surface.data().expect("surface data");
            probe_pixel_417(&data, stride, PROBE_X, PROBE_Y)
        };

        let white = (255, 255, 255);
        let accent = (140, 200, 240);

        assert_eq!(
            paint_with_width(2.0),
            white,
            "default-weight focus ring must not reach 5px inside the edge"
        );
        assert_eq!(
            paint_with_width(14.0),
            accent,
            "a style-overridden wider focus ring must reach 5px inside the edge"
        );
    }

    // ── #1073: surface_fill_rounded_rect / surface_fill_rect_alpha /
    //    surface_draw_text_run_with_role / surface_draw_icon_glyph ──────

    /// A corner pixel well inside the fillet radius must stay untouched
    /// while the box's centre paints solid — proving the corners are
    /// genuinely rounded, not just a rectangle with a misleading name.
    #[test]
    fn gtk_backend_paint_surface_fill_rounded_rect_clips_the_corners() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let mut surface =
            ImageSurface::create(Format::ARgb32, 40, 40).expect("create ImageSurface");
        let mut backend = GtkBackend::new();
        let red = Color::rgb(200, 20, 20);

        {
            let cr = Context::new(&surface).expect("Context::new");
            let pango_ctx = pangocairo::functions::create_context(&cr);
            let pango_layout = pango::Layout::new(&pango_ctx);
            backend.enter_frame_scope(&cr, &pango_layout, |b| {
                b.surface_fill_rounded_rect(QRect::new(0.0, 0.0, 40.0, 40.0), 15.0, red);
            });
        }

        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        assert_eq!(
            probe_pixel_417(&data, stride, 20, 20),
            (red.r, red.g, red.b),
            "surface_fill_rounded_rect must paint the solid color at the box's centre"
        );
        assert_eq!(
            probe_pixel_417(&data, stride, 1, 1),
            (0, 0, 0),
            "a corner pixel well inside a radius-15 fillet on a 40x40 box must stay \
             untouched — otherwise this is just `surface_fill_rect` under a new name"
        );
    }

    /// `surface_stroke_rounded_rect` must paint a real rounded
    /// stroke, not a plain rectangle — a point on the (straight) side of
    /// the box must land the stroke colour, a corner pixel well inside
    /// the fillet radius must stay untouched (same proof shape as
    /// `gtk_backend_paint_surface_fill_rounded_rect_clips_the_corners`),
    /// and the box's centre — far from any stroke — must also stay
    /// untouched, proving this is a stroke and not a fill.
    #[test]
    fn gtk_backend_paint_surface_stroke_rounded_rect_clips_the_corners() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let mut surface =
            ImageSurface::create(Format::ARgb32, 40, 40).expect("create ImageSurface");
        let mut backend = GtkBackend::new();
        let blue = Color::rgb(60, 120, 220);

        {
            let cr = Context::new(&surface).expect("Context::new");
            let pango_ctx = pangocairo::functions::create_context(&cr);
            let pango_layout = pango::Layout::new(&pango_ctx);
            backend.enter_frame_scope(&cr, &pango_layout, |b| {
                b.surface_stroke_rounded_rect(QRect::new(0.0, 0.0, 40.0, 40.0), 15.0, blue, 4.0);
            });
        }

        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        assert_eq!(
            probe_pixel_417(&data, stride, 20, 1),
            (blue.r, blue.g, blue.b),
            "the straight middle of the top edge must land the stroke colour"
        );
        assert_eq!(
            probe_pixel_417(&data, stride, 1, 1),
            (0, 0, 0),
            "a corner pixel well inside a radius-15 fillet on a 40x40 box must stay \
             untouched"
        );
        assert_eq!(
            probe_pixel_417(&data, stride, 20, 20),
            (0, 0, 0),
            "the box's centre, far from any stroke, must stay untouched — otherwise \
             this is `surface_fill_rounded_rect` under a new name"
        );
    }

    /// `surface_draw_shadow`'s default decomposes into
    /// `surface_fill_rounded_rect` layers — elevation `0` must paint
    /// nothing at all (the explicit "no shadow" tier), proven by the
    /// whole surface staying at its untouched clear value.
    #[test]
    fn gtk_backend_paint_surface_draw_shadow_elevation_zero_is_a_no_op() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let mut surface =
            ImageSurface::create(Format::ARgb32, 40, 40).expect("create ImageSurface");
        let mut backend = GtkBackend::new();
        let shadow = Color::rgba(0, 0, 0, 128);

        {
            let cr = Context::new(&surface).expect("Context::new");
            let pango_ctx = pangocairo::functions::create_context(&cr);
            let pango_layout = pango::Layout::new(&pango_ctx);
            backend.enter_frame_scope(&cr, &pango_layout, |b| {
                b.surface_draw_shadow(QRect::new(10.0, 10.0, 20.0, 20.0), 6.0, 0, shadow);
            });
        }

        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        assert_eq!(
            probe_pixel_417(&data, stride, 20, 20),
            (0, 0, 0),
            "elevation 0 must paint nothing — the box's own centre must stay at the \
             surface's untouched clear value"
        );
    }

    /// A nonzero elevation must actually paint something below
    /// the box — proven by a pixel just under the box's bottom edge
    /// (inside the shadow's spread/offset, outside the box itself)
    /// picking up ink it didn't have before. Fills the whole canvas
    /// white first — a black-on-transparent probe would read `(0, 0,
    /// 0)` either way (cairo premultiplies, so a zero-RGB source over a
    /// zero-alpha destination is indistinguishable from "nothing
    /// painted"), so this needs a non-black backdrop to actually prove
    /// the layer composited.
    #[test]
    fn gtk_backend_paint_surface_draw_shadow_elevation_three_paints_below_the_box() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let mut surface =
            ImageSurface::create(Format::ARgb32, 40, 40).expect("create ImageSurface");
        let mut backend = GtkBackend::new();
        let white = Color::rgb(255, 255, 255);
        let shadow = Color::rgba(0, 0, 0, 200);

        {
            let cr = Context::new(&surface).expect("Context::new");
            let pango_ctx = pangocairo::functions::create_context(&cr);
            let pango_layout = pango::Layout::new(&pango_ctx);
            backend.enter_frame_scope(&cr, &pango_layout, |b| {
                b.surface_fill_rect(QRect::new(0.0, 0.0, 40.0, 40.0), white);
                b.surface_draw_shadow(QRect::new(5.0, 5.0, 20.0, 20.0), 6.0, 3, shadow);
            });
        }

        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        assert_ne!(
            probe_pixel_417(&data, stride, 15, 29),
            (white.r, white.g, white.b),
            "a pixel just below the box's bottom edge must pick up shadow ink at \
             elevation 3"
        );
    }

    /// `surface_draw_path`'s default decomposes a closed
    /// triangle into `surface_draw_line` segments — each edge's
    /// midpoint must land the stroke colour, proving `MoveTo`/`LineTo`/
    /// `Close` each actually painted a segment rather than being
    /// silently dropped.
    #[test]
    fn gtk_backend_paint_surface_draw_path_strokes_every_segment() {
        use crate::PathVerb;
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let mut surface =
            ImageSurface::create(Format::ARgb32, 40, 40).expect("create ImageSurface");
        let mut backend = GtkBackend::new();
        let green = Color::rgb(20, 180, 20);

        {
            let cr = Context::new(&surface).expect("Context::new");
            let pango_ctx = pangocairo::functions::create_context(&cr);
            let pango_layout = pango::Layout::new(&pango_ctx);
            backend.enter_frame_scope(&cr, &pango_layout, |b| {
                b.surface_draw_path(
                    &[
                        PathVerb::MoveTo(Point::new(5.0, 5.0)),
                        PathVerb::LineTo(Point::new(35.0, 5.0)),
                        PathVerb::LineTo(Point::new(20.0, 35.0)),
                        PathVerb::Close,
                    ],
                    green,
                    2.0,
                );
            });
        }

        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        // Top edge midpoint (MoveTo -> first LineTo) is axis-aligned, so
        // it paints the solid stroke colour with no antialiasing fuzz.
        assert_eq!(
            probe_pixel_417(&data, stride, 20, 5),
            (green.r, green.g, green.b),
            "the axis-aligned top edge must paint the solid stroke colour"
        );
        // The two diagonal edges antialias, so a probe near their
        // midpoint only lands a *partial* green/background blend, not
        // the solid colour — "not still (0, 0, 0)" is still a real
        // proof that `LineTo`/`Close` each painted a segment.
        assert_ne!(
            probe_pixel_417(&data, stride, 28, 20),
            (0, 0, 0),
            "the diagonal right edge (first LineTo -> second LineTo) must paint something"
        );
        assert_ne!(
            probe_pixel_417(&data, stride, 12, 20),
            (0, 0, 0),
            "the diagonal left edge (second LineTo -> Close) must paint something"
        );
    }

    /// A translucent `surface_fill_rect_alpha` fill over an opaque
    /// background must land a real alpha composite — neither the fill
    /// colour verbatim nor the background untouched.
    #[test]
    fn gtk_backend_paint_surface_fill_rect_alpha_blends_with_the_background() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let mut surface =
            ImageSurface::create(Format::ARgb32, 40, 40).expect("create ImageSurface");
        let mut backend = GtkBackend::new();
        let white = Color::rgb(255, 255, 255);
        let red = Color::rgb(200, 20, 20);

        {
            let cr = Context::new(&surface).expect("Context::new");
            let pango_ctx = pangocairo::functions::create_context(&cr);
            let pango_layout = pango::Layout::new(&pango_ctx);
            backend.enter_frame_scope(&cr, &pango_layout, |b| {
                b.surface_fill_rect(QRect::new(0.0, 0.0, 40.0, 40.0), white);
                b.surface_fill_rect_alpha(QRect::new(0.0, 0.0, 40.0, 40.0), red, 0.5);
            });
        }

        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        let (r, g, b) = probe_pixel_417(&data, stride, 20, 20);
        assert!(
            (r, g, b) != (white.r, white.g, white.b) && (r, g, b) != (red.r, red.g, red.b),
            "a 50%-alpha fill over an opaque background must land a real blend, \
             not the background or the fill colour verbatim: got ({r}, {g}, {b})"
        );
        // Real source-over compositing of 50%-alpha red onto opaque white
        // lands roughly halfway between the two on every channel.
        assert!(
            (200..245).contains(&r),
            "red channel should sit between the fill's 200 and white's 255: got {r}"
        );
        assert!(
            (100..160).contains(&g) && (100..160).contains(&b),
            "green/blue channels should sit roughly halfway between the fill's 20 \
             and white's 255: got ({g}, {b})"
        );
    }

    /// `role` must select a genuinely different live font, not just a
    /// documented no-op — proven here by a huge chrome-font size versus
    /// a tiny editor-font size painting visibly different amounts of ink
    /// for the same glyph.
    #[test]
    fn gtk_backend_paint_surface_draw_text_run_with_role_uses_the_requested_fonts_size() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        fn ink_pixel_count(surface: &mut ImageSurface) -> usize {
            surface.flush();
            let stride = surface.stride() as usize;
            let data = surface.data().expect("surface data");
            let mut count = 0;
            for y in 0..80 {
                for x in 0..80 {
                    let (r, g, b) = probe_pixel_417(&data, stride, x, y);
                    if r as u32 + g as u32 + b as u32 > 0 {
                        count += 1;
                    }
                }
            }
            count
        }

        let white = Color::rgb(255, 255, 255);

        let mut chrome_surface =
            ImageSurface::create(Format::ARgb32, 80, 80).expect("create ImageSurface");
        let mut backend = GtkBackend::new();
        backend.set_ui_font("Sans 48");
        backend.set_editor_font("Monospace", 6.0);
        {
            let cr = Context::new(&chrome_surface).expect("Context::new");
            let pango_ctx = pangocairo::functions::create_context(&cr);
            let pango_layout = pango::Layout::new(&pango_ctx);
            backend.enter_frame_scope(&cr, &pango_layout, |b| {
                b.surface_draw_text_run_with_role(
                    QRect::new(2.0, 2.0, 76.0, 76.0),
                    "A",
                    white,
                    crate::FontRole::Chrome,
                    false,
                );
            });
        }
        let chrome_ink = ink_pixel_count(&mut chrome_surface);

        let mut editor_surface =
            ImageSurface::create(Format::ARgb32, 80, 80).expect("create ImageSurface");
        {
            let cr = Context::new(&editor_surface).expect("Context::new");
            let pango_ctx = pangocairo::functions::create_context(&cr);
            let pango_layout = pango::Layout::new(&pango_ctx);
            backend.enter_frame_scope(&cr, &pango_layout, |b| {
                b.surface_draw_text_run_with_role(
                    QRect::new(2.0, 2.0, 76.0, 76.0),
                    "A",
                    white,
                    crate::FontRole::Editor,
                    false,
                );
            });
        }
        let editor_ink = ink_pixel_count(&mut editor_surface);

        assert!(
            chrome_ink > 0 && editor_ink > 0,
            "both roles must paint real ink: chrome={chrome_ink}, editor={editor_ink}"
        );
        assert!(
            chrome_ink > editor_ink * 3,
            "a 48pt chrome font must paint far more ink than a 6pt editor font for the \
             same glyph if `role` really selects a different live font: \
             chrome={chrome_ink}, editor={editor_ink}"
        );

        // Italic must not panic even though this backend paints it
        // via the same `pango::AttrList` recipe `surface_draw_text_run_styled`
        // already uses.
        let italic_surface =
            ImageSurface::create(Format::ARgb32, 80, 80).expect("create ImageSurface");
        let cr = Context::new(&italic_surface).expect("Context::new");
        let pango_ctx = pangocairo::functions::create_context(&cr);
        let pango_layout = pango::Layout::new(&pango_ctx);
        backend.enter_frame_scope(&cr, &pango_layout, |b| {
            b.surface_draw_text_run_with_role(
                QRect::new(2.0, 2.0, 76.0, 76.0),
                "A",
                white,
                crate::FontRole::Chrome,
                true,
            );
        });
    }

    /// [`Backend::draw_rich_text_popup_with_font_role`]
    /// must select a genuinely different live font, not a documented
    /// no-op — proven the same way as
    /// `gtk_backend_paint_surface_draw_text_run_with_role_uses_the_requested_fonts_size`:
    /// a huge chrome font versus a tiny editor font paints visibly
    /// different amounts of ink for the same popup content. Plain
    /// `draw_rich_text_popup` (no role argument) must still paint with
    /// the chrome font — proving the new method didn't change today's
    /// behaviour for existing call sites.
    #[test]
    fn gtk_rich_text_popup_font_role_selects_the_requested_fonts_size() {
        use crate::primitives::rich_text_popup::{
            PopupPlacement, RichTextPopup, RichTextPopupMeasure,
        };
        use crate::types::{StyledText, WidgetId};
        use crate::FontRole;
        use pangocairo::cairo::{Context, Format, ImageSurface};

        const W: i32 = 100;
        const H: i32 = 100;

        fn ink_pixel_count(surface: &mut ImageSurface) -> usize {
            surface.flush();
            let stride = surface.stride() as usize;
            let data = surface.data().expect("surface data");
            let mut count = 0;
            for y in 0..H {
                for x in 0..W {
                    let (r, g, b) = probe_pixel_417(&data, stride, x, y);
                    if r as u32 + g as u32 + b as u32 > 0 {
                        count += 1;
                    }
                }
            }
            count
        }

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

        fn paint(backend: &mut GtkBackend, role: Option<FontRole>) -> usize {
            let mut surface =
                ImageSurface::create(Format::ARgb32, W, H).expect("create ImageSurface");
            let p = popup();
            let viewport = QRect::new(0.0, 0.0, W as f32, H as f32);
            let measure = RichTextPopupMeasure::new(80.0, 80.0);
            let layout = p.layout(2.0, 2.0, viewport, measure, |_, s, e| (e - s) as f32);
            {
                let cr = Context::new(&surface).expect("Context::new");
                let pango_ctx = pangocairo::functions::create_context(&cr);
                let pango_layout = pango::Layout::new(&pango_ctx);
                backend.enter_frame_scope(&cr, &pango_layout, |b| match role {
                    Some(role) => b.draw_rich_text_popup_with_font_role(&p, &layout, role),
                    None => b.draw_rich_text_popup(&p, &layout),
                });
            }
            ink_pixel_count(&mut surface)
        }

        let mut backend = GtkBackend::new();
        backend.set_ui_font("Sans 48");
        backend.set_editor_font("Monospace", 6.0);

        // `None` = plain `draw_rich_text_popup` (today's call site, no
        // role argument at all) — must still paint the chrome font.
        let chrome_ink = paint(&mut backend, None);
        let editor_ink = paint(&mut backend, Some(FontRole::Editor));

        assert!(
            chrome_ink > 0 && editor_ink > 0,
            "both roles must paint real ink: chrome={chrome_ink}, editor={editor_ink}"
        );
        assert!(
            chrome_ink > editor_ink * 3,
            "a 48pt chrome font must paint far more ink than a 6pt editor font for the \
             same glyph if plain draw_rich_text_popup (no role argument) really selects \
             the chrome font: chrome={chrome_ink}, editor={editor_ink}"
        );
    }

    /// `surface_draw_icon_glyph` must reach real Cairo painting (through
    /// the fallback-wrapped font description) rather than silently
    /// dropping the call.
    #[test]
    fn gtk_backend_paint_surface_draw_icon_glyph_paints_real_ink() {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let mut surface =
            ImageSurface::create(Format::ARgb32, 40, 40).expect("create ImageSurface");
        let mut backend = GtkBackend::new();
        let white = Color::rgb(255, 255, 255);

        {
            let cr = Context::new(&surface).expect("Context::new");
            let pango_ctx = pangocairo::functions::create_context(&cr);
            let pango_layout = pango::Layout::new(&pango_ctx);
            backend.enter_frame_scope(&cr, &pango_layout, |b| {
                b.surface_draw_icon_glyph(QRect::new(2.0, 2.0, 30.0, 30.0), "i", white);
            });
        }

        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        let mut ink = 0u32;
        for y in 0..40 {
            for x in 0..40 {
                let (r, g, b) = probe_pixel_417(&data, stride, x, y);
                ink += r as u32 + g as u32 + b as u32;
            }
        }
        assert!(
            ink > 0,
            "surface_draw_icon_glyph must paint real ink through the fallback-wrapped \
             font description, not silently no-op"
        );
    }

    // ── find_replace (#809, `PaintSurface` Phase 2b) ──────────────────
    //
    // `gtk::find_replace` used to carry its own `#[cfg(test)]` module
    // with a `draw_find_replace_with_multibyte_query_does_not_panic`
    // test, exercising `gtk::find_replace::draw_find_replace` directly
    // against a bare Cairo `ImageSurface` — it never asserted rendered
    // pixels. That module (and the whole file) is deleted — the paint
    // logic it exercised now lives in
    // `crate::primitives::find_replace::paint`, covered on every host by
    // that module's own `RecordingSurface` tests. The test below goes a
    // step further than the deleted one did: it asserts real rendered
    // output (the popup background pixel), proving the *plumbing* —
    // `GtkBackend::draw_find_replace` really does reach `paint` and
    // `paint` really does land real Cairo pixels through `GtkBackend`'s
    // `PaintSurface` impl — not just that it doesn't panic.
    #[test]
    fn gtk_backend_draw_find_replace_paints_popup_background() {
        use crate::primitives::find_replace::{compute_hit_regions, FindReplacePanel};
        use pangocairo::cairo::{Context, Format, ImageSurface};

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

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

        let mut backend = GtkBackend::new();
        let theme = crate::Theme::default();
        backend.set_current_theme(theme);
        Backend::begin_frame(&mut backend, Viewport::new(W as f32, H as f32, 1.0));
        let mut surface = ImageSurface::create(Format::ARgb32, W, H).expect("create ImageSurface");
        {
            let cr = Context::new(&surface).expect("Context::new");
            let pango_layout = pangocairo::functions::create_layout(&cr);
            backend.enter_frame_scope(&cr, &pango_layout, |b| {
                b.draw_find_replace(QRect::new(0.0, 0.0, W as f32, H as f32), &panel);
            });
        }

        let cw = backend.char_width().max(1.0);
        let lh = backend.line_height().max(1.0);
        let popup_w = panel.panel_width as f32 * cw;
        let popup_h = 3.0 * lh; // show_replace == false: 1 content row + 2 border rows
        let popup_x = (panel.group_bounds.x + panel.group_bounds.width - popup_w - 10.0)
            .max(panel.group_bounds.x);
        let popup_y = panel.group_bounds.y + 2.0;

        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        let px = (
            (popup_x + popup_w - 4.0) as usize,
            (popup_y + popup_h - 4.0) as usize,
        );
        let offset = px.1 * stride + px.0 * 4;
        // Cairo `ARgb32` is premultiplied BGRA in native byte order.
        let (b8, g8, r8) = (data[offset], data[offset + 1], data[offset + 2]);
        assert_eq!(
            (r8, g8, b8),
            (theme.surface_bg.r, theme.surface_bg.g, theme.surface_bg.b),
            "find/replace popup background must be painted through GtkBackend's \
             real PaintSurface impl",
        );
    }

    /// Regression twin of `primitives::find_replace`'s own
    /// `multibyte_query_with_out_of_range_selection_does_not_panic`:
    /// that test proves the shared slicing logic is safe in the
    /// abstract; this proves real Pango measurement/drawing of the same
    /// multibyte text through `GtkBackend` doesn't panic either.
    #[test]
    fn gtk_backend_draw_find_replace_with_multibyte_query_does_not_panic() {
        use crate::primitives::find_replace::{compute_hit_regions, FindReplacePanel};
        use pangocairo::cairo::{Context, Format, ImageSurface};

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

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

        let mut backend = GtkBackend::new();
        let surface = ImageSurface::create(Format::ARgb32, W, H).expect("create ImageSurface");
        let cr = Context::new(&surface).expect("Context::new");
        let pango_layout = pangocairo::functions::create_layout(&cr);
        backend.enter_frame_scope(&cr, &pango_layout, |b| {
            b.draw_find_replace(QRect::new(0.0, 0.0, W as f32, H as f32), &panel);
        });
    }

    // ── #810: draw_chart real-pixel driver tests ────────────────────────
    //
    // Ported from the deleted `gtk::chart::tests` (that module painted
    // straight onto a Cairo `ImageSurface` via the since-deleted free
    // function `gtk::chart::draw_chart`) to instead drive the real
    // `Backend::draw_chart` → `primitives::chart::paint` path end to
    // end, the same shape `gtk_backend_draw_find_replace_*` above uses.

    use crate::primitives::chart::{Chart as ChartModel, ChartKind, Series, SERIES_COLORS};

    const CHART_W: i32 = 30;
    const CHART_H: i32 = 30;

    /// Read an RGB triple from an ARgb32 surface at pixel (x, y).
    fn chart_pixel(data: &[u8], stride: usize, x: i32, y: i32) -> (u8, u8, u8) {
        let off = y as usize * stride + x as usize * 4;
        (data[off + 2], data[off + 1], data[off])
    }

    fn chart_series(label: &str, data: Vec<f64>) -> Series {
        Series {
            label: label.into(),
            data,
            color: None,
            fill: false,
        }
    }

    fn chart_bar_chart(kind: ChartKind, series: Vec<Series>, y_range: (f64, f64)) -> ChartModel {
        ChartModel {
            id: WidgetId::new("chart"),
            kind,
            series,
            x_label: None,
            y_label: None,
            y_range: Some(y_range),
            x_range: None,
            show_legend: false,
            y_ticks: Some(0),
            x_ticks: Some(0),
            show_grid: false,
        }
    }

    fn paint_chart_via_backend(
        chart: &ChartModel,
        rect: QRect,
        hovered_point: Option<(usize, usize)>,
    ) -> pangocairo::cairo::ImageSurface {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let mut backend = GtkBackend::new();
        backend.set_current_theme(crate::Theme::default());
        Backend::begin_frame(
            &mut backend,
            Viewport::new(CHART_W as f32, CHART_H as f32, 1.0),
        );
        let surface =
            ImageSurface::create(Format::ARgb32, CHART_W, CHART_H).expect("create ImageSurface");
        {
            let cr = Context::new(&surface).expect("Context::new");
            let pango_layout = pangocairo::functions::create_layout(&cr);
            backend.enter_frame_scope(&cr, &pango_layout, |b| {
                b.draw_chart(rect, chart, hovered_point, None);
            });
        }
        surface.flush();
        surface
    }

    #[test]
    fn gtk_backend_draw_chart_stacked_bar_paints_each_series_in_its_own_color() {
        // Three equal-value series stacked in a single column, with an
        // explicit y_range so the geometry is exact: (0, 1/3), (1/3,
        // 2/3), (2/3, 1) bottom to top.
        let chart = chart_bar_chart(
            ChartKind::Bar,
            vec![
                chart_series("a", vec![1.0]),
                chart_series("b", vec![1.0]),
                chart_series("c", vec![1.0]),
            ],
            (0.0, 3.0),
        );
        let rect = QRect::new(0.0, 0.0, CHART_W as f32, CHART_H as f32);
        let mut surface = paint_chart_via_backend(&chart, rect, None);
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");

        let mid_x = 15;
        let bottom_y = 25;
        let mid_y = 15;
        let top_y = 5;

        assert_eq!(
            chart_pixel(&data, stride, mid_x, bottom_y),
            (SERIES_COLORS[0].r, SERIES_COLORS[0].g, SERIES_COLORS[0].b),
            "bottom segment should be series 0's colour"
        );
        assert_eq!(
            chart_pixel(&data, stride, mid_x, mid_y),
            (SERIES_COLORS[1].r, SERIES_COLORS[1].g, SERIES_COLORS[1].b),
            "middle segment should be series 1's colour"
        );
        assert_eq!(
            chart_pixel(&data, stride, mid_x, top_y),
            (SERIES_COLORS[2].r, SERIES_COLORS[2].g, SERIES_COLORS[2].b),
            "top segment should be series 2's colour"
        );
    }

    #[test]
    fn gtk_backend_draw_chart_grouped_bar_paints_series_side_by_side() {
        let chart = chart_bar_chart(
            ChartKind::BarGrouped,
            vec![
                chart_series("a", vec![1.0]),
                chart_series("b", vec![2.0]),
                chart_series("c", vec![3.0]),
            ],
            (0.0, 3.0),
        );
        let rect = QRect::new(0.0, 0.0, CHART_W as f32, CHART_H as f32);
        let mut surface = paint_chart_via_backend(&chart, rect, None);
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");

        let probe_y = 27;
        assert_eq!(
            chart_pixel(&data, stride, 6, probe_y),
            (SERIES_COLORS[0].r, SERIES_COLORS[0].g, SERIES_COLORS[0].b),
            "leftmost sub-bar should be series 0"
        );
        assert_eq!(
            chart_pixel(&data, stride, 15, probe_y),
            (SERIES_COLORS[1].r, SERIES_COLORS[1].g, SERIES_COLORS[1].b),
            "middle sub-bar should be series 1"
        );
        assert_eq!(
            chart_pixel(&data, stride, 23, probe_y),
            (SERIES_COLORS[2].r, SERIES_COLORS[2].g, SERIES_COLORS[2].b),
            "rightmost sub-bar should be series 2"
        );
    }

    /// Before unification, GTK's `draw_chart` had no clip, so overlay
    /// elements painted outside `plot_area` (legend, crosshair, hover
    /// marker) could bleed past the chart's rect. The unified
    /// `primitives::chart::paint` now owns this clip for every backend.
    /// This is the driver-tier proof for GTK.
    #[test]
    fn gtk_backend_draw_chart_hover_marker_does_not_escape_chart_rect() {
        // origin=1.0 at index 0 → top edge; 0.0 at index 1 → bottom
        // edge. n=2 → index 0's x is the plot area's left edge. So data
        // point (0, 0) sits exactly at the chart's top-left corner.
        let chart = chart_bar_chart(
            ChartKind::Sparkline,
            vec![chart_series("a", vec![10.0, 0.0])],
            (0.0, 10.0),
        );

        let canvas_w = 40;
        let canvas_h = 40;
        let sentinel: (u8, u8, u8) = (0, 0, 0);
        let (chart_x, chart_y, chart_w, chart_h) = (10.0, 10.0, 20.0, 20.0);

        let mut backend = GtkBackend::new();
        backend.set_current_theme(crate::Theme::default());
        Backend::begin_frame(
            &mut backend,
            Viewport::new(canvas_w as f32, canvas_h as f32, 1.0),
        );
        let mut surface = pangocairo::cairo::ImageSurface::create(
            pangocairo::cairo::Format::ARgb32,
            canvas_w,
            canvas_h,
        )
        .expect("create ImageSurface");
        {
            let cr = pangocairo::cairo::Context::new(&surface).expect("Context::new");
            cr.set_source_rgb(
                sentinel.0 as f64 / 255.0,
                sentinel.1 as f64 / 255.0,
                sentinel.2 as f64 / 255.0,
            );
            cr.rectangle(0.0, 0.0, canvas_w as f64, canvas_h as f64);
            cr.fill().ok();

            let pango_layout = pangocairo::functions::create_layout(&cr);
            backend.enter_frame_scope(&cr, &pango_layout, |b| {
                b.draw_chart(
                    QRect::new(chart_x, chart_y, chart_w, chart_h),
                    &chart,
                    Some((0, 0)),
                    None,
                );
            });
        }
        surface.flush();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");

        // Inside the marker's 8-unit-radius ring, centred at the chart's
        // own top-left corner (10, 10), but outside the chart's rect.
        let probe = (5, 5);
        assert_eq!(
            chart_pixel(&data, stride, probe.0, probe.1),
            sentinel,
            "hover marker must not paint outside the chart's own rect",
        );
    }

    // ── #810: draw_text_display real-pixel driver tests ─────────────────
    //
    // GTK had no pixel-level coverage for `draw_text_display` before
    // #810 (only `gtk::text_display::tests`'s pure-layout round trips);
    // macOS's and Windows's own equivalents already drove this through
    // their real backend, so this closes the GTK gap using the same
    // shape.

    use crate::primitives::text_display::{
        TextDisplay as TextDisplayModel, TextDisplayLine as TextDisplayLineModel,
    };

    const TD_W: i32 = 240;
    const TD_H: i32 = 160;

    fn td_line(text: &str) -> TextDisplayLineModel {
        TextDisplayLineModel {
            spans: vec![crate::types::StyledSpan::plain(text)],
            decoration: crate::types::Decoration::Normal,
            timestamp: None,
        }
    }

    fn make_td(lines: usize, show_scrollbar: bool) -> TextDisplayModel {
        TextDisplayModel {
            id: WidgetId::new("td"),
            lines: (0..lines).map(|i| td_line(&format!("ln{i}"))).collect(),
            scroll_offset: 0,
            auto_scroll: false,
            max_lines: 0,
            has_focus: false,
            title: None,
            show_scrollbar,
        }
    }

    fn paint_td_via_backend(td: &TextDisplayModel) -> pangocairo::cairo::ImageSurface {
        use pangocairo::cairo::{Context, Format, ImageSurface};

        let mut backend = GtkBackend::new();
        backend.set_current_theme(crate::Theme::default());
        Backend::begin_frame(&mut backend, Viewport::new(TD_W as f32, TD_H as f32, 1.0));
        let surface =
            ImageSurface::create(Format::ARgb32, TD_W, TD_H).expect("create ImageSurface");
        {
            let cr = Context::new(&surface).expect("Context::new");
            let pango_layout = pangocairo::functions::create_layout(&cr);
            backend.enter_frame_scope(&cr, &pango_layout, |b| {
                b.draw_text_display(QRect::new(0.0, 0.0, TD_W as f32, TD_H as f32), td);
            });
        }
        surface.flush();
        surface
    }

    #[test]
    fn gtk_backend_draw_text_display_background_fills_theme_background() {
        let td = make_td(0, false);
        let mut surface = paint_td_via_backend(&td);
        let theme = crate::Theme::default();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        let (x, y) = (TD_W / 2, TD_H / 2);
        let off = y as usize * stride + x as usize * 4;
        let (b8, g8, r8) = (data[off], data[off + 1], data[off + 2]);
        assert_eq!(
            (r8, g8, b8),
            (theme.background.r, theme.background.g, theme.background.b),
        );
    }

    #[test]
    fn gtk_backend_draw_text_display_scrollbar_gutter_and_thumb_paint() {
        let td = make_td(100, true);
        let mut surface = paint_td_via_backend(&td);
        let layout = crate::gtk::gtk_text_display_layout(
            &td,
            QRect::new(0.0, 0.0, TD_W as f32, TD_H as f32),
            16.0,
            8.0,
        );
        let theme = crate::Theme::default();
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");
        let pixel = |x: u32, y: u32| -> (u8, u8, u8) {
            let off = y as usize * stride + x as usize * 4;
            (data[off + 2], data[off + 1], data[off])
        };

        let thumb = layout.thumb_bounds.expect("thumb present");
        let (tr, tg, tb) = pixel(
            (thumb.x + thumb.width / 2.0) as u32,
            (thumb.y + thumb.height / 2.0) as u32,
        );
        assert_eq!(
            (tr, tg, tb),
            (
                theme.scrollbar_thumb.r,
                theme.scrollbar_thumb.g,
                theme.scrollbar_thumb.b
            ),
        );

        let gutter = layout.scrollbar_bounds.expect("gutter present");
        let (gr, gg, gb) = pixel(
            (gutter.x + gutter.width / 2.0) as u32,
            (gutter.y + gutter.height - 2.0) as u32,
        );
        assert_eq!(
            (gr, gg, gb),
            (
                theme.scrollbar_track.r,
                theme.scrollbar_track.g,
                theme.scrollbar_track.b
            ),
        );
    }

    // ── theme_prefers_dark ───────────────────────────────────────────────
    //
    // Pure luma mapping, unit-tested without a live GTK display —
    // mirrors `gtk::services::system_theme_from_gtk_settings_reports_*`'s
    // posture for the read-direction counterpart. The actual
    // `gtk4::Settings::set_gtk_application_prefer_dark_theme` push in
    // `push_native_theme_preference` needs a live display connection and
    // isn't covered by an automated test here — see this issue's
    // SMOKE_TESTS.

    #[test]
    fn theme_prefers_dark_reports_dark_for_a_black_background() {
        let theme = crate::Theme {
            background: crate::types::Color::rgb(0, 0, 0),
            ..crate::Theme::default()
        };
        assert!(theme_prefers_dark(theme));
    }

    #[test]
    fn theme_prefers_dark_reports_light_for_a_white_background() {
        let theme = crate::Theme {
            background: crate::types::Color::rgb(255, 255, 255),
            ..crate::Theme::default()
        };
        assert!(!theme_prefers_dark(theme));
    }

    #[test]
    fn theme_prefers_dark_matches_the_default_dark_theme() {
        // `Theme::default()` is documented as "a coherent dark palette"
        // (its own doc comment) — this pins that the derived dark/light
        // read agrees with that claim.
        assert!(theme_prefers_dark(crate::Theme::default()));
    }

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

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

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

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

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