quadraui 0.2.0

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
//! GTK rasteriser for the [`Editor`] primitive.
//!
//! Handles every editor paint category: backgrounds (active /
//! cursorline / DAP-stopped / diff), pre-text selection overlays
//! (drawn before the text so text reads on top in Cairo's painter
//! order), gutter (BP / git / line numbers right-aligned / diagnostic
//! dot / lightbulb), syntax-highlighted text via Pango attributes,
//! ghost continuation, inline annotations, indent guides, color
//! columns, bracket-match (alpha rect), wavy diagnostic underlines,
//! dotted spell underlines, cursor (Block alpha rect, Bar 2px,
//! Underline 12% line height), AI ghost text after the cursor, and
//! secondary cursors.
//!
//! ## Selection paint ordering vs TUI
//!
//! GTK paints selections **before** text. TUI paints selections
//! **after** text (modifies bg on cells whose chars are already in the
//! buffer). The divergence is intrinsic to the surfaces — Cairo paints
//! in order, while ratatui cells coalesce fg+bg+char. The data
//! primitive is shared; the paint approach is not. Don't try to
//! consolidate the orders across rasterisers.
//!
//! ## Status line
//!
//! The per-window status line is **not** painted by this rasteriser.
//! The host shrinks `editor.rect` for the status row before calling
//! `draw_editor` and paints the status line separately afterwards.
//!
//! ## Scrollbars
//!
//! `draw_editor` paints both scrollbars itself. Geometry comes from
//! [`Editor::layout`] (the same call hit-testing already uses, so
//! paint and click agree by construction), converted to
//! [`crate::primitives::scrollbar::Scrollbar`] and painted through
//! [`crate::primitives::scrollbar::native_surface_paint::paint`] via
//! the shared [`super::surface::CairoSurface`] adapter — the same
//! pattern `gtk::data_table` and `gtk::list` already use to paint an
//! embedded scrollbar from a bare `cr: &Context` rather than a live
//! `GtkBackend`.
//!
//! Unlike TUI's fixed-cell grid — where a cell can only ever hold one
//! glyph, so "paint the scrollbar after the text" is only possible
//! because `viewport_cols` was pre-narrowed by one column before any
//! text was painted into it — Cairo's pixel surface *can* paint one
//! thing directly on top of another. To still match TUI's actual
//! result (a reserved column, not a glyph visible under a translucent
//! track), this rasteriser narrows the **content clip** by the same
//! `editor_geom.text_bounds.width` [`Editor::layout`] computes for
//! hit-testing *before* painting any text/indent-guides/color-columns/
//! diagnostic+spell-underlines/bracket-match (see "Clip to text area"
//! below), then paints the scrollbar itself afterwards, once, directly
//! into the now-untouched column. "Paints after" here means "paints
//! into reserved pixels no glyph touched" — the same outcome as TUI's
//! narrowing, reached by clipping instead of by shrinking a cell count,
//! because that's what the two surfaces each make possible. Backgrounds
//! painted *before* the clip is installed (window/cursorline/diff/DAP
//! backgrounds, selection overlays) are deliberately left full-width,
//! matching TUI's own `line_bg`/`render_selection`, which paint the
//! full row before the scrollbar draw call overwrites whatever ended up
//! in its column — narrowing those too would just be extra clipping
//! for a region the scrollbar paints over regardless.
//!
//! ## Minimap interaction
//!
//! This rasteriser has no awareness of a `Minimap` primitive sitting
//! beside the editor — that would violate this crate's
//! primitive-distinctness rule (`DECISIONS.md`), the same reason the
//! status line isn't painted here either (see below). But
//! `Editor::layout`'s `has_v_scrollbar` fires whenever the buffer
//! overflows the viewport, with no awareness of whether a sibling
//! `Minimap` is already offering a scroll affordance. The minimap-as-
//! scrollbar case (VS-Code-style: the slider draws *over* the minimap,
//! which acts as the track), and narrowing `editor.rect` alone can't
//! suppress this rasteriser's own column without also strangling the
//! text viewport. [`crate::primitives::editor::EditorPaintOptions::
//! suppress_v_scrollbar`] is the opt-out: a host running its minimap
//! in scrollbar mode calls [`draw_editor_with_options`] with that flag
//! set, which makes `Editor::layout_with_options` return
//! `v_scrollbar_bounds: None` unconditionally — no column is reserved
//! by the content clip above, and this function skips the vertical
//! scrollbar paint entirely, leaving the minimap as the sole scroll
//! affordance. It isn't a field on `Editor` itself: both known
//! downstream consumers build `Editor` with exhaustive struct literals,
//! so a new field there would break them with `E0063`. `draw_editor`
//! (unchanged, plain-`Editor` signature) keeps calling through with the
//! default (`false`) options, so every existing caller is unaffected.

use crate::primitives::editor::{
    CursorShape, DiagnosticSeverity, DiffLine, Editor, EditorLayout, EditorLine,
    EditorPaintOptions, EditorSelection, EditorStyledSpan, GitLineStatus, SelectionKind,
};
use crate::primitives::scrollbar::Scrollbar;
use crate::theme::Theme;
use crate::types::Color;
use gtk4::cairo::Context;
use gtk4::pango::{self, AttrColor, AttrList};

/// Paint an [`Editor`] primitive into the supplied Cairo context.
///
/// `char_width` and `line_height` are surface-native pixel
/// measurements obtained from the host's font metrics — passed in so
/// the host's font/scale settings stay authoritative.
///
/// Equivalent to [`draw_editor_with_options`] with
/// `EditorPaintOptions::default()` — kept as a separate, unchanged
/// function (rather than growing this one's argument list) so every
/// existing caller keeps compiling untouched.
#[allow(clippy::too_many_arguments)]
pub fn draw_editor(
    cr: &Context,
    layout: &pango::Layout,
    font_metrics: &pango::FontMetrics,
    editor: &Editor,
    theme: &Theme,
    char_width: f64,
    line_height: f64,
) {
    draw_editor_with_options(
        cr,
        layout,
        font_metrics,
        editor,
        theme,
        char_width,
        line_height,
        EditorPaintOptions::default(),
    )
}

/// Paint context threaded through per-section helpers. Private —
/// an internal decomposition aid, not a new public shape.
struct EditorPaintCtx<'a> {
    cr: &'a Context,
    layout: &'a pango::Layout,
    font_metrics: &'a pango::FontMetrics,
    editor: &'a Editor,
    theme: &'a Theme,
    char_width: f64,
    line_height: f64,
    rect: &'a crate::Rect,
    gutter_width: f64,
    text_x_offset: f64,
    editor_geom: EditorLayout,
    text_v_offset: f64,
}

/// Vertical distance from a row's top edge to the top of the glyph cell
/// that centres `font_metrics`'s own natural line height inside
/// `line_height` — GTK's counterpart to
/// [`crate::macos::editor::text_v_offset`] (same formula, Pango units
/// instead of Core Text's). A host sets the editor's row pitch
/// (`line_height`) independently of the font's natural ascent +
/// descent — vimcode's VS Code-style 18px rows over a smaller editor
/// font leaves slack below a glyph painted straight at `cr.move_to`'s
/// row-top origin. Every text paint inside one row — gutter glyphs,
/// body text, ghost continuation, inline annotation, the code-action
/// lightbulb — adds this offset, so they share a baseline and the row
/// reads centred like VS Code, matching the diagnostic-dot centring
/// ([`paint_gutter_diagnostic_or_lightbulb`]) that already used
/// `line_height * 0.5` for its own, unrelated reason.
///
/// Negative when `line_height` is tighter than the font's natural
/// height — see `text_v_offset`'s macOS doc for why that's left
/// unclamped.
fn text_v_offset(font_metrics: &pango::FontMetrics, line_height: f64) -> f64 {
    let natural_height =
        (font_metrics.ascent() + font_metrics.descent()) as f64 / pango::SCALE as f64;
    (line_height - natural_height) / 2.0
}

/// [`draw_editor`], plus [`EditorPaintOptions`] a host can set to
/// override otherwise-automatic paint decisions — currently just
/// `suppress_v_scrollbar` (see the module doc's "Minimap
/// interaction" section).
///
/// Equivalent to [`draw_editor_with_options_and_v_scrollbar_w`] with
/// `v_scrollbar_w: None` (a `char_width`-wide scrollbar column).
#[allow(clippy::too_many_arguments)]
pub fn draw_editor_with_options(
    cr: &Context,
    layout: &pango::Layout,
    font_metrics: &pango::FontMetrics,
    editor: &Editor,
    theme: &Theme,
    char_width: f64,
    line_height: f64,
    options: EditorPaintOptions,
) {
    draw_editor_with_options_and_v_scrollbar_w(
        cr,
        layout,
        font_metrics,
        editor,
        theme,
        char_width,
        line_height,
        options,
        None,
    )
}

/// [`draw_editor_with_options`], plus a host-settable vertical scrollbar
/// width in pixels — see [`Editor::layout_with_options_and_v_scrollbar_w`]
/// for the geometry. `None` sizes the column at `char_width`.
/// `GtkBackend::draw_editor` calls this with the width set through
/// [`crate::Backend::set_editor_v_scrollbar_width`].
#[allow(clippy::too_many_arguments)]
pub fn draw_editor_with_options_and_v_scrollbar_w(
    cr: &Context,
    layout: &pango::Layout,
    font_metrics: &pango::FontMetrics,
    editor: &Editor,
    theme: &Theme,
    char_width: f64,
    line_height: f64,
    options: EditorPaintOptions,
    v_scrollbar_w: Option<f32>,
) {
    let rect = &editor.rect;
    let gutter_width = editor.gutter_char_width as f64 * char_width;
    let h_scroll_offset = editor.scroll_left as f64 * char_width;
    let text_x_offset = rect.x as f64 + gutter_width - h_scroll_offset;
    // Computed once up front (rather than after painting text, as a
    // prior revision of this function did) so the content clip below
    // can be narrowed by the same reserved scrollbar column the
    // scrollbar paint and `EditorLayout::hit_test` already agree on —
    // see the module doc's "Scrollbars" section.
    let editor_geom = editor.layout_with_options_and_v_scrollbar_w(
        *rect,
        char_width as f32,
        line_height as f32,
        options,
        v_scrollbar_w,
    );

    let text_v_offset = text_v_offset(font_metrics, line_height);

    let ctx = EditorPaintCtx {
        cr,
        layout,
        font_metrics,
        editor,
        theme,
        char_width,
        line_height,
        rect,
        gutter_width,
        text_x_offset,
        editor_geom,
        text_v_offset,
    };

    paint_window_background(&ctx);
    paint_line_backgrounds(&ctx);
    paint_selection_overlays(&ctx);
    paint_gutter(&ctx);

    // ── Clip to text area (excludes gutter AND the reserved vertical
    // scrollbar column, when present) ───────────────────────────────────
    //
    // Narrowed to `editor_geom.text_bounds.width` rather than the full
    // `rect.width - gutter_width`, mirroring `tui::editor::draw_editor`'s
    // `viewport_cols` narrowing — text/indent-guides/color-columns/
    // diagnostic+spell underlines/bracket-match stop short of the
    // scrollbar column instead of painting glyphs that the scrollbar
    // then overlays.
    cr.save().ok();
    cr.rectangle(
        rect.x as f64 + gutter_width,
        rect.y as f64,
        ctx.editor_geom.text_bounds.width as f64,
        rect.height as f64,
    );
    cr.clip();

    paint_text_lines(&ctx);

    cr.restore().ok();

    // Scrollbars are painted last among the "content" layers — after
    // text/selections, before the cursor — mirroring
    // `tui::editor::draw_editor`'s z-order; see module doc for the
    // shared-geometry rationale and the minimap boundary. The content
    // clip above already reserved this column, so this paints into
    // pixels no glyph touched, not over them.
    paint_scrollbars(&ctx);
    paint_primary_cursor(&ctx);
    paint_ai_ghost_text(&ctx);
    paint_secondary_cursors(&ctx);
}

// ── Window background ────────────────────────────────────────────────
fn paint_window_background(ctx: &EditorPaintCtx) {
    let EditorPaintCtx {
        cr, editor, theme, ..
    } = ctx;
    let rect = ctx.rect;
    let bg = if editor.show_active_bg {
        theme.editor_active_background
    } else {
        theme.background
    };
    let (br, bg_g, bb) = cairo_rgb(bg);
    cr.set_source_rgb(br, bg_g, bb);
    cr.rectangle(
        rect.x as f64,
        rect.y as f64,
        rect.width as f64,
        rect.height as f64,
    );
    cr.fill().ok();
}

// ── Cursorline / Diff / DAP stopped-line backgrounds ────────────────────
fn paint_line_backgrounds(ctx: &EditorPaintCtx) {
    let EditorPaintCtx {
        cr,
        editor,
        theme,
        line_height,
        ..
    } = ctx;
    let (cr, editor, theme, line_height) = (*cr, *editor, *theme, *line_height);
    let rect = ctx.rect;
    // Stop short of the reserved vertical scrollbar column, mirroring the
    // text clip below — `text_bounds.x + text_bounds.width` already
    // excludes `v_scrollbar_bounds` when present, so the fill never
    // bleeds under the scrollbar.
    let bg_right = ctx.editor_geom.text_bounds.x as f64 + ctx.editor_geom.text_bounds.width as f64;
    let bg_width = (bg_right - rect.x as f64).max(0.0);
    for (view_idx, rl) in editor.lines.iter().enumerate() {
        let y = rect.y as f64 + view_idx as f64 * line_height;
        let bg_color = if rl.is_dap_current {
            Some(theme.dap_stopped_bg)
        } else if let Some(diff_status) = rl.diff_status {
            match diff_status {
                DiffLine::Added => Some(theme.diff_added_bg),
                DiffLine::Removed => Some(theme.diff_removed_bg),
                DiffLine::Padding => Some(theme.diff_padding_bg),
                DiffLine::Same => None,
            }
        } else if rl.is_current_line && editor.is_active && editor.cursorline {
            Some(theme.cursorline_bg)
        } else {
            None
        };
        if let Some(color) = bg_color {
            let (dr, dg, db) = cairo_rgb(color);
            cr.set_source_rgb(dr, dg, db);
            cr.rectangle(rect.x as f64, y, bg_width, line_height);
            cr.fill().ok();
        }
    }
}

// ── Selection overlays (drawn before text so text is on top) ────────────
fn paint_selection_overlays(ctx: &EditorPaintCtx) {
    let EditorPaintCtx {
        cr,
        layout,
        editor,
        theme,
        line_height,
        text_x_offset,
        ..
    } = ctx;
    let (cr, layout, editor, theme, line_height, text_x_offset) =
        (*cr, *layout, *editor, *theme, *line_height, *text_x_offset);
    let rect = ctx.rect;
    if let Some(sel) = &editor.selection {
        draw_visual_selection(
            cr,
            layout,
            sel,
            &editor.lines,
            rect,
            line_height,
            text_x_offset,
            theme.selection,
            theme.selection_alpha as f64,
        );
    }
    for esel in &editor.extra_selections {
        draw_visual_selection(
            cr,
            layout,
            esel,
            &editor.lines,
            rect,
            line_height,
            text_x_offset,
            theme.selection,
            theme.selection_alpha as f64,
        );
    }
    if let Some(yh) = &editor.yank_highlight {
        draw_visual_selection(
            cr,
            layout,
            yh,
            &editor.lines,
            rect,
            line_height,
            text_x_offset,
            theme.yank_highlight_bg,
            theme.yank_highlight_alpha as f64,
        );
    }
}

// ── Gutter (bp + git + line numbers right-aligned + diag/lightbulb) ─────
fn paint_gutter(ctx: &EditorPaintCtx) {
    let EditorPaintCtx {
        editor,
        line_height,
        ..
    } = ctx;
    let (editor, line_height) = (*editor, *line_height);

    if editor.gutter_char_width == 0 {
        return;
    }

    for (view_idx, rl) in editor.lines.iter().enumerate() {
        let y = ctx.rect.y as f64 + view_idx as f64 * line_height;
        paint_gutter_row_number(ctx, rl, y);
        paint_gutter_diagnostic_or_lightbulb(ctx, rl, y);
    }
}

/// Breakpoint marker, git marker, and right-aligned line number for one
/// gutter row — the three columns that share the gutter `layout`'s
/// running `char_offset`.
fn paint_gutter_row_number(ctx: &EditorPaintCtx, rl: &EditorLine, y: f64) {
    let EditorPaintCtx {
        cr,
        layout,
        editor,
        theme,
        char_width,
        gutter_width,
        ..
    } = ctx;
    let (cr, layout, editor, theme, char_width, gutter_width) =
        (*cr, *layout, *editor, *theme, *char_width, *gutter_width);
    let rect = ctx.rect;
    // Every glyph painted by this function is text, so it shares the
    // row's `text_v_offset` — see that function's doc.
    let y = y + ctx.text_v_offset;
    let mut char_offset = 0usize;

    // Breakpoint column (leftmost when has_breakpoints).
    if editor.has_breakpoints {
        let bp_ch: String = rl.gutter_text.chars().take(1).collect();
        let bp_color = if rl.is_dap_current || rl.is_breakpoint {
            theme.diagnostic_error
        } else {
            theme.line_number_fg
        };
        layout.set_text(&bp_ch);
        layout.set_attributes(None);
        let (br, bg_c, bb) = cairo_rgb(bp_color);
        cr.set_source_rgb(br, bg_c, bb);
        cr.move_to(rect.x as f64 + 3.0, y);
        super::painted_text::show_layout(cr, layout);
        char_offset += 1;
    }

    // Git marker column.
    if editor.has_git_diff {
        let git_ch: String = rl.gutter_text.chars().skip(char_offset).take(1).collect();
        let git_color = match rl.git_diff {
            Some(GitLineStatus::Added) => theme.git_added,
            Some(GitLineStatus::Modified) => theme.git_modified,
            Some(GitLineStatus::Deleted) => theme.git_deleted,
            None => theme.line_number_fg,
        };
        layout.set_text(&git_ch);
        layout.set_attributes(None);
        let (gr, gg, gb) = cairo_rgb(git_color);
        cr.set_source_rgb(gr, gg, gb);
        cr.move_to(rect.x as f64 + char_offset as f64 * char_width + 3.0, y);
        super::painted_text::show_layout(cr, layout);
        char_offset += 1;

        // Fold + line numbers portion right-aligned.
        let rest: String = rl.gutter_text.chars().skip(char_offset).collect();
        layout.set_text(&rest);
        layout.set_attributes(None);
    } else if char_offset > 0 {
        let rest: String = rl.gutter_text.chars().skip(char_offset).collect();
        layout.set_text(&rest);
        layout.set_attributes(None);
    } else {
        layout.set_text(&rl.gutter_text);
        layout.set_attributes(None);
    }

    let (num_width, _) = layout.pixel_size();
    let num_x = rect.x as f64 + gutter_width - num_width as f64 - char_width + 3.0;

    let num_color = if editor.is_active && rl.is_current_line {
        theme.line_number_active_fg
    } else {
        theme.line_number_fg
    };
    let (nr, ng, nb) = cairo_rgb(num_color);
    cr.set_source_rgb(nr, ng, nb);
    cr.move_to(num_x, y);
    super::painted_text::show_layout(cr, layout);
}

/// Diagnostic gutter dot (overrides the lightbulb when both apply), or
/// the code-action lightbulb glyph, for one gutter row.
fn paint_gutter_diagnostic_or_lightbulb(ctx: &EditorPaintCtx, rl: &EditorLine, y: f64) {
    let EditorPaintCtx {
        cr,
        layout,
        editor,
        theme,
        line_height,
        ..
    } = ctx;
    let (cr, layout, editor, theme, line_height) = (*cr, *layout, *editor, *theme, *line_height);
    let rect = ctx.rect;

    if let Some(severity) = editor.diagnostic_gutter.get(&rl.line_idx) {
        let diag_color = match severity {
            DiagnosticSeverity::Error => theme.diagnostic_error,
            DiagnosticSeverity::Warning => theme.diagnostic_warning,
            DiagnosticSeverity::Information => theme.diagnostic_info,
            DiagnosticSeverity::Hint => theme.diagnostic_hint,
        };
        let (dr, dg, db) = cairo_rgb(diag_color);
        cr.set_source_rgb(dr, dg, db);
        let dot_r = line_height * 0.2;
        let dot_cx = rect.x as f64 + 3.0 + dot_r;
        let dot_cy = y + line_height * 0.5;
        cr.arc(dot_cx, dot_cy, dot_r, 0.0, 2.0 * std::f64::consts::PI);
        cr.fill().ok();
    } else if !rl.is_wrap_continuation
        && editor.code_action_lines.contains(&rl.line_idx)
        && editor.lightbulb_glyph != '\0'
    {
        let (lr, lg, lb) = cairo_rgb(theme.lightbulb);
        cr.set_source_rgb(lr, lg, lb);
        let bulb_layout = layout.clone();
        bulb_layout.set_text(&editor.lightbulb_glyph.to_string());
        // Text glyph, unlike the diagnostic dot above (which centres
        // itself via `line_height * 0.5`) — shares the row's
        // `text_v_offset`, same as the gutter number.
        cr.move_to(rect.x as f64 + 1.0, y + ctx.text_v_offset);
        super::painted_text::show_layout(cr, &bulb_layout);
    }
}

// ── Render each visible line (text, ghost, annotation, indent guides,
// color columns, bracket match, diagnostic + spell underlines) ─────────
fn paint_text_lines(ctx: &EditorPaintCtx) {
    let EditorPaintCtx {
        editor,
        line_height,
        ..
    } = ctx;
    let (editor, line_height) = (*editor, *line_height);

    for (view_idx, rl) in editor.lines.iter().enumerate() {
        let y = ctx.rect.y as f64 + view_idx as f64 * line_height;
        paint_line_text_ghost_and_annotation(ctx, rl, y);
        paint_line_indent_guides_and_colorcolumns(ctx, rl, y);
        paint_line_bracket_match(ctx, view_idx, y);

        // Restore layout to match rendered text (needed for correct
        // index_to_pos when font_scale != 1.0, e.g. markdown headings) —
        // the guides/colorcolumns/bracket-match painters above don't
        // touch `layout`'s text, but keeping this reset here (rather
        // than trusting that) matches the pre-split behaviour exactly.
        ctx.layout.set_text(&rl.raw_text);
        let line_attrs = build_pango_attrs(&rl.spans);
        ctx.layout.set_attributes(Some(&line_attrs));

        paint_line_diagnostic_underlines(ctx, rl, y);
        paint_line_spell_underlines(ctx, rl, y);
    }
}

/// Base syntax-highlighted text, ghost continuation (full line in ghost
/// colour), and inline annotation (e.g. git blame) — the three overlays
/// that share `layout`'s just-set `raw_text` + span attributes.
fn paint_line_text_ghost_and_annotation(ctx: &EditorPaintCtx, rl: &EditorLine, y: f64) {
    let EditorPaintCtx {
        cr,
        layout,
        theme,
        char_width,
        text_x_offset,
        ..
    } = ctx;
    let (cr, layout, theme, char_width, text_x_offset) =
        (*cr, *layout, *theme, *char_width, *text_x_offset);
    // Every glyph painted by this function is text, so it shares the
    // row's `text_v_offset` — see that function's doc.
    let y = y + ctx.text_v_offset;

    layout.set_text(&rl.raw_text);
    let attrs = build_pango_attrs(&rl.spans);
    layout.set_attributes(Some(&attrs));

    let (fr, fg_g, fb) = cairo_rgb(theme.foreground);
    cr.set_source_rgb(fr, fg_g, fb);
    cr.move_to(text_x_offset, y);
    super::painted_text::show_layout(cr, layout);

    // Ghost continuation lines — full line in ghost colour.
    if rl.is_ghost_continuation {
        if let Some(ghost) = &rl.ghost_suffix {
            let (gr, gg, gb) = cairo_rgb(theme.ghost_text_fg);
            cr.set_source_rgb(gr, gg, gb);
            cr.move_to(text_x_offset, y);
            layout.set_text(ghost);
            layout.set_attributes(None);
            super::painted_text::show_layout(cr, layout);
        }
    }

    // Inline annotation / virtual text (e.g. git blame).
    if let Some(ann) = &rl.annotation {
        let text_pixel_width = layout.pixel_size().0 as f64;
        let ann_x = text_x_offset + text_pixel_width + char_width * 2.0;
        let (ar, ag, ab) = cairo_rgb(theme.annotation_fg);
        cr.set_source_rgb(ar, ag, ab);
        cr.move_to(ann_x, y);
        layout.set_text(ann);
        layout.set_attributes(None);
        super::painted_text::show_layout(cr, layout);
    }
}

/// Indent guides (thin vertical lines) and color columns (tinted
/// background rects) for one line.
fn paint_line_indent_guides_and_colorcolumns(ctx: &EditorPaintCtx, rl: &EditorLine, y: f64) {
    let EditorPaintCtx {
        cr,
        editor,
        theme,
        char_width,
        line_height,
        text_x_offset,
        ..
    } = ctx;
    let (cr, editor, theme, char_width, line_height, text_x_offset) = (
        *cr,
        *editor,
        *theme,
        *char_width,
        *line_height,
        *text_x_offset,
    );

    // Indent guides: thin vertical lines at each guide column.
    if !rl.indent_guides.is_empty() {
        cr.set_line_width(1.0);
        for &guide_col in &rl.indent_guides {
            let is_active = editor.active_indent_col == Some(guide_col);
            let (gr, gg, gb) = if is_active {
                cairo_rgb(theme.indent_guide_active_fg)
            } else {
                cairo_rgb(theme.indent_guide_fg)
            };
            cr.set_source_rgb(gr, gg, gb);
            let gx = text_x_offset + guide_col as f64 * char_width;
            cr.move_to(gx, y);
            cr.line_to(gx, y + line_height);
            cr.stroke().ok();
        }
    }

    // Color columns: tinted background rectangle at each column.
    if !rl.colorcolumns.is_empty() {
        let (cr2, cg, cb) = cairo_rgb(theme.colorcolumn_bg);
        cr.set_source_rgb(cr2, cg, cb);
        for &cc_col in &rl.colorcolumns {
            let cx = text_x_offset + cc_col as f64 * char_width;
            cr.rectangle(cx, y, char_width, line_height);
            cr.fill().ok();
        }
    }
}

/// Bracket-match highlighting (semi-transparent rect) for one line.
fn paint_line_bracket_match(ctx: &EditorPaintCtx, view_idx: usize, y: f64) {
    let EditorPaintCtx {
        cr,
        editor,
        theme,
        char_width,
        line_height,
        text_x_offset,
        ..
    } = ctx;
    let (cr, editor, theme, char_width, line_height, text_x_offset) = (
        *cr,
        *editor,
        *theme,
        *char_width,
        *line_height,
        *text_x_offset,
    );

    for &(bm_view_line, bm_col) in &editor.bracket_match_positions {
        if bm_view_line == view_idx {
            let (br, bg_c, bb) = cairo_rgb(theme.bracket_match_bg);
            cr.set_source_rgba(br, bg_c, bb, 0.6);
            let bx = text_x_offset + bm_col as f64 * char_width;
            cr.rectangle(bx, y, char_width, line_height);
            cr.fill().ok();
        }
    }
}

/// Diagnostic underlines (wavy squiggle) for one line. Caller has
/// already reset `layout` to `rl.raw_text` so `index_to_pos` resolves
/// correctly.
fn paint_line_diagnostic_underlines(ctx: &EditorPaintCtx, rl: &EditorLine, y: f64) {
    let EditorPaintCtx {
        cr,
        layout,
        theme,
        line_height,
        text_x_offset,
        ..
    } = ctx;
    let (cr, layout, theme, line_height, text_x_offset) =
        (*cr, *layout, *theme, *line_height, *text_x_offset);

    for dm in &rl.diagnostics {
        let diag_color = match dm.severity {
            DiagnosticSeverity::Error => theme.diagnostic_error,
            DiagnosticSeverity::Warning => theme.diagnostic_warning,
            DiagnosticSeverity::Information => theme.diagnostic_info,
            DiagnosticSeverity::Hint => theme.diagnostic_hint,
        };
        let (dr, dg, db) = cairo_rgb(diag_color);
        cr.set_source_rgb(dr, dg, db);
        cr.set_line_width(1.0);

        let start_byte = rl
            .raw_text
            .char_indices()
            .nth(dm.start_col)
            .map(|(i, _)| i)
            .unwrap_or(rl.raw_text.len());
        let end_byte = rl
            .raw_text
            .char_indices()
            .nth(dm.end_col)
            .map(|(i, _)| i)
            .unwrap_or(rl.raw_text.len());

        let start_pos = layout.index_to_pos(start_byte as i32);
        let end_pos = layout.index_to_pos(end_byte as i32);
        let x0 = text_x_offset + start_pos.x() as f64 / pango::SCALE as f64;
        let x1 = text_x_offset + end_pos.x() as f64 / pango::SCALE as f64;
        let underline_y = y + line_height - 2.0;

        let wave_h = 1.5;
        let wave_len = 4.0;
        cr.move_to(x0, underline_y);
        let mut wx = x0;
        let mut up = true;
        while wx < x1 {
            let next_x = (wx + wave_len).min(x1);
            let cy = if up {
                underline_y - wave_h
            } else {
                underline_y + wave_h
            };
            cr.curve_to(
                wx + (next_x - wx) * 0.5,
                cy,
                wx + (next_x - wx) * 0.5,
                cy,
                next_x,
                underline_y,
            );
            wx = next_x;
            up = !up;
        }
        cr.stroke().ok();
    }
}

/// Spell error underlines (dotted) for one line. Caller has already
/// reset `layout` to `rl.raw_text` so `index_to_pos` resolves correctly.
fn paint_line_spell_underlines(ctx: &EditorPaintCtx, rl: &EditorLine, y: f64) {
    let EditorPaintCtx {
        cr,
        layout,
        theme,
        line_height,
        text_x_offset,
        ..
    } = ctx;
    let (cr, layout, theme, line_height, text_x_offset) =
        (*cr, *layout, *theme, *line_height, *text_x_offset);

    for sm in &rl.spell_errors {
        let (sr, sg, sb) = cairo_rgb(theme.spell_error);
        cr.set_source_rgb(sr, sg, sb);
        cr.set_line_width(1.0);

        let start_byte = rl
            .raw_text
            .char_indices()
            .nth(sm.start_col)
            .map(|(i, _)| i)
            .unwrap_or(rl.raw_text.len());
        let end_byte = rl
            .raw_text
            .char_indices()
            .nth(sm.end_col)
            .map(|(i, _)| i)
            .unwrap_or(rl.raw_text.len());

        let start_pos = layout.index_to_pos(start_byte as i32);
        let end_pos = layout.index_to_pos(end_byte as i32);
        let x0 = text_x_offset + start_pos.x() as f64 / pango::SCALE as f64;
        let x1 = text_x_offset + end_pos.x() as f64 / pango::SCALE as f64;
        let underline_y = y + line_height - 2.0;

        let dot_spacing = 3.0;
        let mut dx = x0;
        while dx < x1 {
            cr.rectangle(dx, underline_y, 1.0, 1.0);
            dx += dot_spacing;
        }
        cr.fill().ok();
    }
}

// ── Scrollbars ───────────────────────────────────────────────────────
fn paint_scrollbars(ctx: &EditorPaintCtx) {
    let EditorPaintCtx {
        cr,
        editor,
        theme,
        line_height,
        editor_geom,
        ..
    } = ctx;
    let (cr, editor, theme, line_height) = (*cr, *editor, *theme, *line_height);

    if let Some(v_track) = editor_geom.v_scrollbar_bounds {
        let sb = Scrollbar::vertical(
            "gtk:editor:v_scrollbar",
            v_track,
            editor.scroll_top as f32,
            editor.total_lines as f32,
            editor_geom.visible_lines as f32,
            line_height as f32,
        );
        let mut raw = super::surface::CairoSurface {
            cr,
            layout: None,
            translucent_fill: true,
        };
        crate::primitives::scrollbar::native_surface_paint::paint(&sb, &mut raw, theme);
    }
    if let Some(h_track) = editor_geom.h_scrollbar_bounds {
        let sb = Scrollbar::horizontal(
            "gtk:editor:h_scrollbar",
            h_track,
            editor.scroll_left as f32,
            editor.max_col as f32,
            editor_geom.visible_cols as f32,
            line_height as f32,
        );
        let mut raw = super::surface::CairoSurface {
            cr,
            layout: None,
            translucent_fill: true,
        };
        crate::primitives::scrollbar::native_surface_paint::paint(&sb, &mut raw, theme);
    }
}

// ── Cursor (Block alpha rect / Bar 2px / Underline 12% line height) ────
fn paint_primary_cursor(ctx: &EditorPaintCtx) {
    let EditorPaintCtx {
        cr,
        layout,
        font_metrics,
        editor,
        theme,
        line_height,
        text_x_offset,
        ..
    } = ctx;
    let (cr, layout, font_metrics, editor, theme, line_height, text_x_offset) = (
        *cr,
        *layout,
        *font_metrics,
        *editor,
        *theme,
        *line_height,
        *text_x_offset,
    );
    let rect = ctx.rect;

    let Some(cursor) = &editor.cursor else {
        return;
    };
    let Some(rl) = editor.lines.get(cursor.pos.view_line) else {
        return;
    };

    layout.set_text(&rl.raw_text);
    let cursor_attrs = build_pango_attrs(&rl.spans);
    layout.set_attributes(Some(&cursor_attrs));

    let render_col = if !editor.extra_selections.is_empty() && cursor.shape == CursorShape::Bar {
        cursor.pos.col + 1
    } else {
        cursor.pos.col
    };
    let byte_offset: usize = rl
        .raw_text
        .char_indices()
        .nth(render_col)
        .map(|(i, _)| i)
        .unwrap_or(rl.raw_text.len());

    let pos = layout.index_to_pos(byte_offset as i32);
    let cursor_x = text_x_offset + pos.x() as f64 / pango::SCALE as f64;
    let raw_w = pos.width() as f64 / pango::SCALE as f64;
    let cursor_y = rect.y as f64 + cursor.pos.view_line as f64 * line_height;

    let (cr_r, cr_g, cr_b) = cairo_rgb(theme.cursor);
    let char_w = if raw_w > 0.0 {
        raw_w
    } else {
        font_metrics.approximate_char_width() as f64 / pango::SCALE as f64
    };
    match cursor.shape {
        CursorShape::Block => {
            cr.set_source_rgba(cr_r, cr_g, cr_b, theme.cursor_normal_alpha as f64);
            cr.rectangle(cursor_x, cursor_y, char_w, line_height);
            cr.fill().ok();
        }
        CursorShape::Bar => {
            cr.set_source_rgb(cr_r, cr_g, cr_b);
            cr.rectangle(cursor_x, cursor_y, 2.0, line_height);
            cr.fill().ok();
        }
        CursorShape::Underline => {
            cr.set_source_rgb(cr_r, cr_g, cr_b);
            let bar_h = (line_height * 0.12).max(2.0);
            cr.rectangle(cursor_x, cursor_y + line_height - bar_h, char_w, bar_h);
            cr.fill().ok();
        }
    }
}

// ── AI ghost text (after cursor on cursor line) ─────────────────────────
fn paint_ai_ghost_text(ctx: &EditorPaintCtx) {
    let EditorPaintCtx {
        cr,
        layout,
        editor,
        theme,
        line_height,
        text_x_offset,
        ..
    } = ctx;
    let (cr, layout, editor, theme, line_height, text_x_offset) =
        (*cr, *layout, *editor, *theme, *line_height, *text_x_offset);
    let rect = ctx.rect;

    let Some(cursor) = &editor.cursor else {
        return;
    };
    let Some(rl) = editor.lines.get(cursor.pos.view_line) else {
        return;
    };
    let Some(ghost) = &rl.ghost_suffix else {
        return;
    };

    layout.set_text(&rl.raw_text);
    let ghost_line_attrs = build_pango_attrs(&rl.spans);
    layout.set_attributes(Some(&ghost_line_attrs));
    let byte_offset: usize = rl
        .raw_text
        .char_indices()
        .nth(cursor.pos.col)
        .map(|(i, _)| i)
        .unwrap_or(rl.raw_text.len());
    let pos = layout.index_to_pos(byte_offset as i32);
    let ghost_x = text_x_offset + pos.x() as f64 / pango::SCALE as f64;
    let ghost_y = rect.y as f64 + cursor.pos.view_line as f64 * line_height + ctx.text_v_offset;
    let (gr, gg, gb) = cairo_rgb(theme.ghost_text_fg);
    cr.set_source_rgb(gr, gg, gb);
    cr.move_to(ghost_x, ghost_y);
    layout.set_text(ghost);
    layout.set_attributes(None);
    super::painted_text::show_layout(cr, layout);
}

// ── Secondary cursors (multi-cursor) ─────────────────────────────────────
fn paint_secondary_cursors(ctx: &EditorPaintCtx) {
    let EditorPaintCtx {
        cr,
        layout,
        font_metrics,
        editor,
        theme,
        line_height,
        text_x_offset,
        ..
    } = ctx;
    let (cr, layout, font_metrics, editor, theme, line_height, text_x_offset) = (
        *cr,
        *layout,
        *font_metrics,
        *editor,
        *theme,
        *line_height,
        *text_x_offset,
    );
    let rect = ctx.rect;

    let extra_cursor_shape = editor
        .cursor
        .as_ref()
        .map(|c| c.shape)
        .unwrap_or(CursorShape::Bar);
    let has_extra_sels = !editor.extra_selections.is_empty();
    let fallback_char_w = font_metrics.approximate_char_width() as f64 / pango::SCALE as f64;
    let (cr_r, cr_g, cr_b) = cairo_rgb(theme.cursor);
    for extra_pos in &editor.extra_cursors {
        if let Some(rl) = editor.lines.get(extra_pos.view_line) {
            layout.set_text(&rl.raw_text);
            let extra_attrs = build_pango_attrs(&rl.spans);
            layout.set_attributes(Some(&extra_attrs));
            let render_col = if has_extra_sels && extra_cursor_shape == CursorShape::Bar {
                extra_pos.col + 1
            } else {
                extra_pos.col
            };
            let byte_offset: usize = rl
                .raw_text
                .char_indices()
                .nth(render_col)
                .map(|(i, _)| i)
                .unwrap_or(rl.raw_text.len());
            let pos = layout.index_to_pos(byte_offset as i32);
            let ex = text_x_offset + pos.x() as f64 / pango::SCALE as f64;
            let ew = {
                let w = pos.width() as f64 / pango::SCALE as f64;
                if w > 0.0 {
                    w
                } else {
                    fallback_char_w
                }
            };
            let ey = rect.y as f64 + extra_pos.view_line as f64 * line_height;
            match extra_cursor_shape {
                CursorShape::Bar => {
                    cr.set_source_rgb(cr_r, cr_g, cr_b);
                    cr.rectangle(ex, ey, 2.0, line_height);
                    cr.fill().ok();
                }
                CursorShape::Block => {
                    cr.set_source_rgba(cr_r, cr_g, cr_b, theme.cursor_normal_alpha as f64);
                    cr.rectangle(ex, ey, ew, line_height);
                    cr.fill().ok();
                }
                CursorShape::Underline => {
                    cr.set_source_rgb(cr_r, cr_g, cr_b);
                    let bar_h = (line_height * 0.12).max(2.0);
                    cr.rectangle(ex, ey + line_height - bar_h, ew, bar_h);
                    cr.fill().ok();
                }
            }
        }
    }
}

// ─── Private helpers ────────────────────────────────────────────────────

/// Same shape as `quadraui::gtk::cairo_rgb`, kept as a local helper so
/// this module's call sites stay terse.
fn cairo_rgb(c: Color) -> (f64, f64, f64) {
    (c.r as f64 / 255.0, c.g as f64 / 255.0, c.b as f64 / 255.0)
}

/// Convert a `quadraui::Color` into the 16-bit (0..65535) values
/// expected by Pango's `AttrColor` constructors.
fn pango_u16(c: Color) -> (u16, u16, u16) {
    (c.r as u16 * 257, c.g as u16 * 257, c.b as u16 * 257)
}

/// Build a Pango `AttrList` from the editor primitive's byte-range
/// spans. Mirrors `vimcode::gtk::draw::build_pango_attrs`.
fn build_pango_attrs(spans: &[EditorStyledSpan]) -> AttrList {
    let attrs = AttrList::new();
    for span in spans {
        let (fr, fg_g, fb) = pango_u16(span.style.fg);
        let mut fg_attr = AttrColor::new_foreground(fr, fg_g, fb);
        fg_attr.set_start_index(span.start_byte as u32);
        fg_attr.set_end_index(span.end_byte as u32);
        attrs.insert(fg_attr);

        if let Some(bg) = span.style.bg {
            let (br, bg_g, bb) = pango_u16(bg);
            let mut bg_attr = AttrColor::new_background(br, bg_g, bb);
            bg_attr.set_start_index(span.start_byte as u32);
            bg_attr.set_end_index(span.end_byte as u32);
            attrs.insert(bg_attr);
        }
        if span.style.bold {
            let mut w = pango::AttrInt::new_weight(pango::Weight::Bold);
            w.set_start_index(span.start_byte as u32);
            w.set_end_index(span.end_byte as u32);
            attrs.insert(w);
        }
        if span.style.italic {
            let mut s = pango::AttrInt::new_style(pango::Style::Italic);
            s.set_start_index(span.start_byte as u32);
            s.set_end_index(span.end_byte as u32);
            attrs.insert(s);
        }
        if (span.style.font_scale - 1.0).abs() > f32::EPSILON {
            let mut sc = pango::AttrFloat::new_scale(span.style.font_scale as f64);
            sc.set_start_index(span.start_byte as u32);
            sc.set_end_index(span.end_byte as u32);
            attrs.insert(sc);
        }
    }
    attrs
}

/// Resolve `x` (absolute/surface-space) to a character column within
/// `line.raw_text`, inverting the **exact** glyph geometry
/// [`draw_editor`] painted the line with.
///
/// `pango_layout`'s text and attributes are overwritten by this call
/// (`set_text` + [`build_pango_attrs`], mirroring `draw_editor`'s own
/// per-line setup) — pass a layout carrying the same font family/size
/// `draw_editor` painted with (the frame-scoped layout while still
/// inside `enter_frame_scope`, or the cached last-painted clone when
/// called at click-time outside any frame scope).
///
/// `editor_layout` supplies `text_bounds.x`, `scroll_left`, and
/// `cell_width` — the same values `draw_editor` used to compute
/// `text_x_offset`. Horizontal scroll is resolved in the *layout's*
/// local coordinate space (the Pango layout holds the line's full,
/// unscrolled `raw_text`; scrolling only changes where `draw_editor`
/// positions that layout on screen), so the returned column already
/// reflects `scroll_left` — do not add it again.
pub fn editor_col_at_x(
    pango_layout: &pango::Layout,
    line: &EditorLine,
    editor_layout: &EditorLayout,
    x: f32,
) -> usize {
    pango_layout.set_text(&line.raw_text);
    let attrs = build_pango_attrs(&line.spans);
    pango_layout.set_attributes(Some(&attrs));

    let cell_width = editor_layout.cell_width as f64;
    let local_x = (x as f64 - editor_layout.text_bounds.x as f64)
        + editor_layout.scroll_left as f64 * cell_width;
    let x_pango = (local_x.max(0.0) * pango::SCALE as f64).round() as i32;
    let (_inside, byte_index, _trailing) = pango_layout.xy_to_index(x_pango, 0);
    // Pango should only ever return a UTF-8 char-boundary-aligned index for
    // valid input, but we don't fully control its internals across
    // versions/locales — snap defensively rather than trust it blindly and
    // risk a panic on a non-boundary `byte_index`.
    let clamped =
        crate::text_util::snap_to_char_boundary(&line.raw_text, byte_index.max(0) as usize);
    line.raw_text[..clamped].chars().count() + line.segment_col_offset
}

/// Paint a visual selection range (Char / Line / Block) onto `cr`. Each
/// visual segment of a wrapped buffer line is highlighted independently
/// (one rectangle per matching view row). Column math — including
/// ghost-continuation / diff-padding row skipping and wrapped-segment
/// offsetting — comes from [`EditorSelection::cols_on`]; this
/// function only converts the returned columns to pixel positions.
/// Mirrors `vimcode::gtk::draw::draw_visual_selection`.
#[allow(clippy::too_many_arguments)]
fn draw_visual_selection(
    cr: &Context,
    layout: &pango::Layout,
    sel: &EditorSelection,
    lines: &[EditorLine],
    rect: &crate::event::Rect,
    line_height: f64,
    text_x_offset: f64,
    color: Color,
    alpha: f64,
) {
    let (sr, sg, sb) = cairo_rgb(color);
    cr.set_source_rgba(sr, sg, sb, alpha);

    for (view_idx, rl) in lines.iter().enumerate() {
        let Some(cols) = sel.cols_on(rl) else {
            continue;
        };

        let y = rect.y as f64 + view_idx as f64 * line_height;

        if sel.kind == SelectionKind::Line {
            let highlight_width = rect.width as f64 - (text_x_offset - rect.x as f64);
            cr.rectangle(text_x_offset, y, highlight_width, line_height);
            continue;
        }

        let line_text = &rl.raw_text;
        layout.set_text(line_text);
        layout.set_attributes(None);

        let start_byte = line_text
            .char_indices()
            .nth(cols.start)
            .map(|(i, _)| i)
            .unwrap_or(line_text.len());
        let start_pos = layout.index_to_pos(start_byte as i32);
        let start_x = text_x_offset + start_pos.x() as f64 / pango::SCALE as f64;

        if cols.extends_beyond {
            let (line_width, _) = layout.pixel_size();
            cr.rectangle(
                start_x,
                y,
                (text_x_offset + line_width as f64 - start_x).max(0.0),
                line_height,
            );
        } else {
            let end_byte = line_text
                .char_indices()
                .nth(cols.end)
                .map(|(i, _)| i)
                .unwrap_or(line_text.len());
            let end_pos = layout.index_to_pos(end_byte as i32);
            let end_x = text_x_offset + end_pos.x() as f64 / pango::SCALE as f64;
            cr.rectangle(start_x, y, end_x - start_x, line_height);
        }
    }
    cr.fill().ok();
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event::Rect;
    use crate::primitives::editor::{Editor, Style};
    use crate::types::Color;
    use pangocairo::cairo::{Context, Format, ImageSurface};
    use std::collections::{HashMap, HashSet};

    /// A line with three differently-styled spans (bold / italic /
    /// `font_scale`) so its painted glyph advances are *not* uniform —
    /// the exact case where the monospace `EditorLayout::col_at_x`
    /// fallback drifts from what `draw_editor` actually painted.
    fn styled_line() -> EditorLine {
        let plain = Style {
            fg: Color::rgb(220, 220, 220),
            bg: None,
            bold: false,
            italic: false,
            font_scale: 1.0,
        };
        EditorLine {
            raw_text: "let x = width; // note".into(),
            gutter_text: "  1".into(),
            spans: vec![
                EditorStyledSpan {
                    start_byte: 0,
                    end_byte: 3,
                    style: Style {
                        bold: true,
                        ..plain
                    },
                }, // "let"
                EditorStyledSpan {
                    start_byte: 8,
                    end_byte: 13,
                    style: Style {
                        italic: true,
                        ..plain
                    },
                }, // "width"
                EditorStyledSpan {
                    start_byte: 15,
                    end_byte: 22,
                    style: Style {
                        font_scale: 1.8,
                        ..plain
                    },
                }, // "// note"
            ],
            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(),
        }
    }

    fn headless_pango_layout() -> pango::Layout {
        let surface = ImageSurface::create(Format::ARgb32, 900, 60).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 12"));
        pango::Layout::new(&ctx)
    }

    /// Paint a styled, horizontally-scrolled line, then assert
    /// `editor_col_at_x` resolves every visible glyph's own painted x
    /// position back to its own column. A naive uniform-monospace
    /// resolver fails this for any glyph painted after the bold/italic/
    /// `font_scale` spans, since their advances differ from a
    /// plain-glyph cell width.
    #[test]
    fn editor_col_at_x_round_trips_styled_line_with_scroll() {
        // Two independent `pango::Layout`s from the same font context —
        // mirrors production, where the "ground truth" paint layout
        // (`draw_editor`'s frame-scoped layout) and the click-time probe
        // layout (`editor_col_at_x`'s argument, possibly the cached
        // clone) are distinct GObjects. Using one shared, mutable layout
        // for both would let `editor_col_at_x`'s internal `set_text` /
        // `set_attributes` calls silently overwrite the "ground truth"
        // measurements taken later in the loop — which is exactly what
        // happened when this test was first written with one shared
        // layout: it kept passing even with `set_attributes(None)`
        // hard-coded into `editor_col_at_x`, because the corrupted
        // shared state made "expected" and "actual" agree for the wrong
        // reason. Two layouts closes that hole.
        let truth_layout = headless_pango_layout();
        let probe_layout = headless_pango_layout();
        let line = styled_line();
        let editor = Editor {
            id: "ed".into(),
            rect: Rect::new(0.0, 0.0, 900.0, 60.0),
            lines: vec![line.clone()],
            cursor: None,
            extra_cursors: Vec::new(),
            selection: None,
            extra_selections: Vec::new(),
            yank_highlight: None,
            scroll_top: 0,
            scroll_left: 3,
            total_lines: 1,
            max_col: 30,
            gutter_char_width: 4,
            is_active: true,
            show_active_bg: false,
            has_git_diff: false,
            has_breakpoints: false,
            diagnostic_gutter: HashMap::new(),
            code_action_lines: HashSet::new(),
            bracket_match_positions: Vec::new(),
            active_indent_col: None,
            tabstop: 4,
            cursorline: true,
            lightbulb_glyph: '!',
        };

        let cell_width = 9.0_f32;
        let line_height = 18.0_f32;
        let viewport = Rect::new(0.0, 0.0, 900.0, 60.0);
        let editor_layout = editor.layout(viewport, cell_width, line_height);

        // Pass 1 — paint with attrs (identical setup to `draw_editor`'s
        // per-line loop) into `truth_layout` and record every glyph's
        // real painted x position *before* touching `probe_layout` at
        // all, so nothing later can contaminate these measurements.
        truth_layout.set_text(&line.raw_text);
        let attrs = build_pango_attrs(&line.spans);
        truth_layout.set_attributes(Some(&attrs));

        let text_x_offset =
            editor_layout.text_bounds.x as f64 - editor.scroll_left as f64 * cell_width as f64;

        let glyph_click_xs: Vec<(usize, char, f64)> = line
            .raw_text
            .char_indices()
            .enumerate()
            .map(|(char_idx, (byte_idx, ch))| {
                let pos = truth_layout.index_to_pos(byte_idx as i32);
                let glyph_left_x = text_x_offset + pos.x() as f64 / pango::SCALE as f64;
                let glyph_width = (pos.width() as f64 / pango::SCALE as f64).max(2.0);
                // Click a quarter-glyph past the leading edge — solidly
                // inside the glyph, clear of boundary-rounding ambiguity.
                (char_idx, ch, glyph_left_x + glyph_width * 0.25)
            })
            .collect();

        // Pass 2 — resolve each recorded click through the function
        // under test, which owns (and mutates) `probe_layout`.
        for (char_idx, ch, click_x) in glyph_click_xs {
            let resolved = editor_col_at_x(&probe_layout, &line, &editor_layout, click_x as f32);
            assert_eq!(
                resolved, char_idx,
                "glyph '{ch}' (char {char_idx}) at x={click_x} resolved to col {resolved}"
            );
        }
    }

    #[test]
    fn editor_col_at_x_adds_segment_col_offset_for_wrap_continuation() {
        let pango_layout = headless_pango_layout();
        let mut line = styled_line();
        line.is_wrap_continuation = true;
        line.segment_col_offset = 12;

        let editor = Editor {
            id: "ed".into(),
            rect: Rect::new(0.0, 0.0, 900.0, 60.0),
            lines: vec![line.clone()],
            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: 30,
            gutter_char_width: 4,
            is_active: true,
            show_active_bg: false,
            has_git_diff: false,
            has_breakpoints: false,
            diagnostic_gutter: HashMap::new(),
            code_action_lines: HashSet::new(),
            bracket_match_positions: Vec::new(),
            active_indent_col: None,
            tabstop: 4,
            cursorline: true,
            lightbulb_glyph: '!',
        };

        let cell_width = 9.0_f32;
        let viewport = Rect::new(0.0, 0.0, 900.0, 60.0);
        let editor_layout = editor.layout(viewport, cell_width, 18.0);

        // Click exactly at the text origin (col 0 of the visual segment)
        // — the resolved buffer column must be the segment offset.
        let resolved = editor_col_at_x(
            &pango_layout,
            &line,
            &editor_layout,
            editor_layout.text_bounds.x,
        );
        assert_eq!(resolved, 12);
    }

    /// When `editor_col_at_x`'s clamped byte index lands mid-character
    /// in a multibyte line (é / CJK / emoji), it must be snapped to a
    /// char boundary. Sweep the full width of a multibyte line and
    /// confirm every probe resolves without panicking.
    #[test]
    fn editor_col_at_x_multibyte_line_does_not_panic() {
        let pango_layout = headless_pango_layout();
        let mut line = styled_line();
        line.raw_text = "café 🎉 中文 done".into();
        line.spans = Vec::new();

        let editor = Editor {
            id: "ed".into(),
            rect: Rect::new(0.0, 0.0, 900.0, 60.0),
            lines: vec![line.clone()],
            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: 30,
            gutter_char_width: 4,
            is_active: true,
            show_active_bg: false,
            has_git_diff: false,
            has_breakpoints: false,
            diagnostic_gutter: HashMap::new(),
            code_action_lines: HashSet::new(),
            bracket_match_positions: Vec::new(),
            active_indent_col: None,
            tabstop: 4,
            cursorline: true,
            lightbulb_glyph: '!',
        };

        let cell_width = 9.0_f32;
        let viewport = Rect::new(0.0, 0.0, 900.0, 60.0);
        let editor_layout = editor.layout(viewport, cell_width, 18.0);

        // Sweep x from before the line start to well past its end —
        // every probe must resolve without panicking.
        let mut x = editor_layout.text_bounds.x - 5.0;
        while x < editor_layout.text_bounds.x + 300.0 {
            let _ = editor_col_at_x(&pango_layout, &line, &editor_layout, x);
            x += 1.0;
        }
    }

    // ── Scrollbar paint ─────────────────────────────────────────────────
    //
    // "State-derived paint geometry" (quadraui/docs/TESTING.md coverage
    // taxonomy row 3): set `total_lines`/`max_col` to a known overflow (or
    // non-overflow) state, paint into a headless Cairo `ImageSurface`, and
    // assert the scrollbar track's translucent tint is present (or absent)
    // at the exact pixel `Editor::layout`'s own geometry predicts — the
    // same geometry `EditorLayout::hit_test` uses, so paint and click can't
    // drift apart. Mirrors `gtk/data_table.rs`'s pixel-readback harness.

    const SCROLL_TEST_W: i32 = 200;
    const SCROLL_TEST_H: i32 = 80;
    const SCROLL_TEST_CHAR_W: f64 = 8.0;
    const SCROLL_TEST_LINE_H: f64 = 16.0;

    fn rgb(c: Color) -> (u8, u8, u8) {
        (c.r, c.g, c.b)
    }

    /// Read an RGB triple from an ARgb32 surface at pixel (x, y). Same
    /// byte layout as `gtk/data_table.rs`'s test helper and `GtkDriver::pixel`.
    fn scroll_test_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 blank_line(line_idx: usize) -> EditorLine {
        EditorLine {
            raw_text: String::new(),
            gutter_text: String::new(),
            spans: Vec::new(),
            line_idx,
            is_current_line: false,
            is_fold_header: false,
            folded_line_count: 0,
            git_diff: None,
            diff_status: None,
            diagnostics: Vec::new(),
            spell_errors: Vec::new(),
            is_breakpoint: false,
            is_conditional_bp: false,
            is_dap_current: false,
            is_wrap_continuation: false,
            segment_col_offset: 0,
            annotation: None,
            ghost_suffix: None,
            is_ghost_continuation: false,
            indent_guides: Vec::new(),
            colorcolumns: Vec::new(),
        }
    }

    /// Editor fixture at `SCROLL_TEST_W`x`SCROLL_TEST_H` (matching the
    /// surface size the tests below paint into) with no gutter, so the
    /// only geometry in play is the scrollbar reservation itself.
    fn scroll_test_editor(total_lines: usize, max_col: usize, num_lines: usize) -> Editor {
        Editor {
            id: "ed".into(),
            rect: Rect::new(0.0, 0.0, SCROLL_TEST_W as f32, SCROLL_TEST_H as f32),
            lines: (0..num_lines).map(blank_line).collect(),
            cursor: None,
            extra_cursors: Vec::new(),
            selection: None,
            extra_selections: Vec::new(),
            yank_highlight: None,
            scroll_top: 0,
            scroll_left: 0,
            total_lines,
            max_col,
            gutter_char_width: 0,
            is_active: true,
            show_active_bg: false,
            has_git_diff: false,
            has_breakpoints: false,
            diagnostic_gutter: HashMap::new(),
            code_action_lines: HashSet::new(),
            bracket_match_positions: Vec::new(),
            active_indent_col: None,
            tabstop: 4,
            cursorline: false,
            lightbulb_glyph: '\0',
        }
    }

    /// Paint `editor` into a fresh `theme.background`-filled surface and
    /// return the raw pixel buffer + stride. Mirrors `gtk/data_table.rs`'s
    /// identical test harness.
    fn scroll_test_paint(editor: &Editor, theme: &Theme) -> (Vec<u8>, i32) {
        let mut surface = ImageSurface::create(Format::ARgb32, SCROLL_TEST_W, SCROLL_TEST_H)
            .expect("create ImageSurface");
        {
            let cr = Context::new(&surface).expect("Context::new");
            let (br, bg, bb) = cairo_rgb(theme.background);
            cr.set_source_rgb(br, bg, bb);
            cr.paint().ok();

            let pango_layout = pangocairo::functions::create_layout(&cr);
            let pango_ctx = pango_layout.context();
            pango_ctx.set_font_description(&pango::FontDescription::from_string("Monospace 12"));
            let metrics = pango_ctx.metrics(None, None);

            draw_editor(
                &cr,
                &pango_layout,
                &metrics,
                editor,
                theme,
                SCROLL_TEST_CHAR_W,
                SCROLL_TEST_LINE_H,
            );
        }
        surface.flush();
        let stride = surface.stride();
        let data = surface.data().expect("surface data").to_vec();
        (data, stride)
    }

    /// [`scroll_test_paint`], but through [`draw_editor_with_options`] so
    /// tests can exercise [`EditorPaintOptions`].
    fn scroll_test_paint_with_options(
        editor: &Editor,
        theme: &Theme,
        options: EditorPaintOptions,
    ) -> (Vec<u8>, i32) {
        scroll_test_paint_with_v_scrollbar_w(editor, theme, options, None)
    }

    /// [`scroll_test_paint_with_options`], plus a scrollbar-width
    /// override via [`draw_editor_with_options_and_v_scrollbar_w`].
    fn scroll_test_paint_with_v_scrollbar_w(
        editor: &Editor,
        theme: &Theme,
        options: EditorPaintOptions,
        v_scrollbar_w: Option<f32>,
    ) -> (Vec<u8>, i32) {
        let mut surface = ImageSurface::create(Format::ARgb32, SCROLL_TEST_W, SCROLL_TEST_H)
            .expect("create ImageSurface");
        {
            let cr = Context::new(&surface).expect("Context::new");
            let (br, bg, bb) = cairo_rgb(theme.background);
            cr.set_source_rgb(br, bg, bb);
            cr.paint().ok();

            let pango_layout = pangocairo::functions::create_layout(&cr);
            let pango_ctx = pango_layout.context();
            pango_ctx.set_font_description(&pango::FontDescription::from_string("Monospace 12"));
            let metrics = pango_ctx.metrics(None, None);

            draw_editor_with_options_and_v_scrollbar_w(
                &cr,
                &pango_layout,
                &metrics,
                editor,
                theme,
                SCROLL_TEST_CHAR_W,
                SCROLL_TEST_LINE_H,
                options,
                v_scrollbar_w,
            );
        }
        surface.flush();
        let stride = surface.stride();
        let data = surface.data().expect("surface data").to_vec();
        (data, stride)
    }

    /// `gtk::draw_editor` must paint scrollbars when a buffer is taller
    /// than the viewport — a vertical scrollbar track in the reserved
    /// rightmost `char_width`-wide column; a buffer that fits must not
    /// tint that column at all.
    #[test]
    fn draw_editor_paints_vertical_scrollbar_when_buffer_overflows() {
        let theme = Theme::default();

        let overflowing = scroll_test_editor(50, 0, 5);
        let (data, stride) = scroll_test_paint(&overflowing, &theme);
        // Solidly inside the reserved v-scrollbar column (x in [192,200))
        // and mid-track vertically — see `Editor::layout`'s
        // `v_scrollbar_bounds` formula for why this pixel is in-track.
        let px = scroll_test_pixel(&data, stride as usize, 198, 40);
        assert_ne!(
            px,
            rgb(theme.background),
            "vertical scrollbar track should tint this pixel when total_lines overflows the viewport"
        );

        let fits = scroll_test_editor(3, 0, 3);
        let (data2, stride2) = scroll_test_paint(&fits, &theme);
        let px2 = scroll_test_pixel(&data2, stride2 as usize, 198, 40);
        assert_eq!(
            px2,
            rgb(theme.background),
            "no vertical scrollbar should paint when the buffer fits the viewport"
        );
    }

    /// The content clip must be **narrowed** by the reserved v-scrollbar
    /// column width, not merely overlaid afterwards — otherwise a
    /// translucent scrollbar track paints on top of glyphs the
    /// (unnarrowed) text loop already rendered underneath it, which is
    /// visible wherever the track/thumb isn't fully opaque. Fill every
    /// visible line with far more text than fits the viewport (so glyphs
    /// would reach all the way to the true right edge without the fix)
    /// and assert the reserved column's pixel is identical whether or
    /// not that text is present — the only way that can hold is if the
    /// text never reaches that column at all (narrowed out), since the
    /// scrollbar itself paints identically in both cases.
    #[test]
    fn draw_editor_scrollbar_column_unaffected_by_overflowing_text() {
        let theme = Theme::default();

        let mut with_text = scroll_test_editor(50, 0, 5);
        for line in with_text.lines.iter_mut() {
            // Comfortably wider than SCROLL_TEST_W under any reasonable
            // font metrics — text that would overflow past the reserved
            // scrollbar column if the clip were not narrowed.
            line.raw_text = "M".repeat(60);
        }
        let blank = scroll_test_editor(50, 0, 5);

        let (data_text, stride) = scroll_test_paint(&with_text, &theme);
        let (data_blank, stride2) = scroll_test_paint(&blank, &theme);
        assert_eq!(stride, stride2);

        // Same pixel the tests above assert is scrollbar-tinted.
        let px_text = scroll_test_pixel(&data_text, stride as usize, 198, 40);
        let px_blank = scroll_test_pixel(&data_blank, stride as usize, 198, 40);
        assert_eq!(
            px_text, px_blank,
            "scrollbar column pixel must be identical regardless of overflowing text — \
             the text loop should narrow around the reserved column instead of painting \
             glyphs the scrollbar then overlays (#968)"
        );
    }

    /// `paint_line_backgrounds` must narrow the cursorline/diff/DAP row
    /// fill to `text_bounds`, the same way the text clip is narrowed —
    /// otherwise the fill reaches the reserved v-scrollbar column and
    /// bleeds through the translucent scrollbar track. Paint a buffer
    /// with the cursorline active on the row under the scrollbar's
    /// mid-track pixel and assert that pixel is identical to the same
    /// pixel with no cursorline active at all: the only way a translucent
    /// track composited over two different row colours produces the same
    /// result is if neither row colour actually reaches that pixel.
    #[test]
    fn draw_editor_cursorline_background_does_not_bleed_into_scrollbar_column() {
        let theme = Theme::default();
        assert_ne!(
            theme.cursorline_bg, theme.background,
            "fixture assumption: cursorline_bg must differ from background for this test to \
             be meaningful"
        );

        let mut with_cursorline = scroll_test_editor(50, 0, 5);
        // Line at view index 2 covers y in [32, 48) — pixel y=40 below is
        // the same mid-track pixel the other scrollbar tests sample.
        with_cursorline.cursorline = true;
        with_cursorline.lines[2].is_current_line = true;

        let blank = scroll_test_editor(50, 0, 5);

        let (data_cursorline, stride) = scroll_test_paint(&with_cursorline, &theme);
        let (data_blank, stride2) = scroll_test_paint(&blank, &theme);
        assert_eq!(stride, stride2);

        let px_cursorline = scroll_test_pixel(&data_cursorline, stride as usize, 198, 40);
        let px_blank = scroll_test_pixel(&data_blank, stride as usize, 198, 40);
        assert_eq!(
            px_cursorline, px_blank,
            "scrollbar column pixel must be identical regardless of the cursorline background \
             on the row underneath it — the row fill should narrow around the reserved column \
             instead of bleeding into it"
        );
    }

    /// Passing `EditorPaintOptions { suppress_v_scrollbar: true, .. }`
    /// through `draw_editor_with_options` must stop the vertical
    /// scrollbar from painting at all, even though the buffer still
    /// overflows the viewport — this is the opt-out a host running a
    /// `Minimap`-as-scrollbar passes to avoid a redundant second
    /// affordance beside it. `draw_editor` (no options) must remain
    /// unaffected.
    #[test]
    fn draw_editor_with_options_suppress_v_scrollbar_paints_no_column() {
        let theme = Theme::default();
        let overflowing = scroll_test_editor(50, 0, 5);

        // Baseline: plain `draw_editor` still paints the column.
        let (data0, stride0) = scroll_test_paint(&overflowing, &theme);
        assert_ne!(
            scroll_test_pixel(&data0, stride0 as usize, 198, 40),
            rgb(theme.background)
        );

        let (data, stride) = scroll_test_paint_with_options(
            &overflowing,
            &theme,
            EditorPaintOptions {
                suppress_v_scrollbar: true,
            },
        );
        let px = scroll_test_pixel(&data, stride as usize, 198, 40);
        assert_eq!(
            px,
            rgb(theme.background),
            "suppress_v_scrollbar should stop the vertical scrollbar from painting even \
             though total_lines overflows the viewport"
        );
    }

    /// The GTK rasteriser's vertical scrollbar column honours a
    /// `v_scrollbar_w` override end-to-end — a wider override paints
    /// further out, matching the layout-level assertions in
    /// `primitives::editor`'s own tests.
    ///
    /// Viewport is `SCROLL_TEST_W` = 200px, `SCROLL_TEST_CHAR_W` = 8.0.
    /// The default column spans `[192, 200)`; a 14px override spans
    /// `[186, 200)`. `x = 188` falls in the gap between those two spans
    /// — plain text-area background at baseline, inside the track once
    /// widened.
    #[test]
    fn draw_editor_v_scrollbar_w_widens_painted_column() {
        let theme = Theme::default();
        let overflowing = scroll_test_editor(50, 0, 5);

        let (data0, stride0) = scroll_test_paint(&overflowing, &theme);
        let baseline_px = scroll_test_pixel(&data0, stride0 as usize, 188, 40);
        assert_eq!(
            baseline_px,
            rgb(theme.background),
            "x=188 sits outside the default 8px-wide column, [192, 200)"
        );

        let (data, stride) = scroll_test_paint_with_v_scrollbar_w(
            &overflowing,
            &theme,
            EditorPaintOptions::default(),
            Some(14.0),
        );
        let widened_px = scroll_test_pixel(&data, stride as usize, 188, 40);
        assert_ne!(
            widened_px,
            rgb(theme.background),
            "a Some(14.0) v_scrollbar_w should widen the painted track to cover x=188 ([186, 200))"
        );
    }

    /// Horizontal-overflow counterpart of the vertical scrollbar test:
    /// a line wider than the viewport must paint a horizontal scrollbar
    /// track in the reserved bottom `line_height`-tall row; a buffer
    /// whose longest line fits must not tint that row at all.
    #[test]
    fn draw_editor_paints_horizontal_scrollbar_when_line_overflows() {
        let theme = Theme::default();

        let overflowing = scroll_test_editor(3, 40, 3);
        let (data, stride) = scroll_test_paint(&overflowing, &theme);
        // Solidly inside the reserved h-scrollbar row (y in [64,80)) —
        // no v-scrollbar column here (total_lines fits), so the full
        // width is available for the horizontal track.
        let px = scroll_test_pixel(&data, stride as usize, 100, 70);
        assert_ne!(
            px,
            rgb(theme.background),
            "horizontal scrollbar track should tint this pixel when max_col overflows the viewport"
        );

        let fits = scroll_test_editor(3, 5, 3);
        let (data2, stride2) = scroll_test_paint(&fits, &theme);
        let px2 = scroll_test_pixel(&data2, stride2 as usize, 100, 70);
        assert_eq!(
            px2,
            rgb(theme.background),
            "no horizontal scrollbar should paint when every line fits the viewport"
        );
    }

    // ── Selection column math via `EditorSelection::cols_on` ────────────

    fn text_line(line_idx: usize, raw_text: &str) -> EditorLine {
        EditorLine {
            raw_text: raw_text.into(),
            ..blank_line(line_idx)
        }
    }

    /// One `Char` selection spanning buffer lines `[0, 2]` painted
    /// across a plain row, a wrapped-segment row, a ghost-continuation
    /// row, and a diff-padding row — the exact matrix
    /// `tests/conformance/editor.rs` proves against
    /// `EditorSelection::cols_on` directly, proven again here through a
    /// real Cairo paint so the backend's own call site is covered too.
    #[test]
    fn draw_editor_selection_respects_wrapped_ghost_and_diff_padding_rows() {
        let theme = Theme::default();

        let lines = vec![
            // Row 0: buffer line 0, plain, selection's own start line.
            text_line(0, "0123456789"),
            // Row 1: a wrap-continuation segment of buffer line 1,
            // starting at buffer column 5 — its own text is only 5
            // chars, entirely inside the selection.
            EditorLine {
                segment_col_offset: 5,
                is_wrap_continuation: true,
                ..text_line(1, "abcde")
            },
            // Row 2: the AI-ghost continuation of buffer line 1 — same
            // `line_idx` as row 1, but virtual, must never be selected.
            EditorLine {
                ghost_suffix: Some("ai suggestion".into()),
                ..text_line(1, "")
            },
            // Row 3: buffer line 2 (the selection's own end line), but a
            // diff-padding filler row — must never be selected either.
            EditorLine {
                diff_status: Some(DiffLine::Padding),
                ..text_line(2, "")
            },
        ];

        let mut editor = scroll_test_editor(4, 0, 4);
        editor.lines = lines;
        editor.selection = Some(EditorSelection {
            kind: SelectionKind::Char,
            start_line: 0,
            start_col: 0,
            end_line: 2,
            end_col: 10,
        });

        let (data, stride) = scroll_test_paint(&editor, &theme);
        let stride = stride as usize;
        let sample_x = 2; // just past the left text edge on every row
        let row_y = |row: i32| row * SCROLL_TEST_LINE_H as i32 + (SCROLL_TEST_LINE_H as i32 / 2);

        assert_ne!(
            scroll_test_pixel(&data, stride, sample_x, row_y(0)),
            rgb(theme.background),
            "row 0 (plain, selection's start line) should be tinted"
        );
        assert_ne!(
            scroll_test_pixel(&data, stride, sample_x, row_y(1)),
            rgb(theme.background),
            "row 1 (wrapped segment of a fully-selected line) should be tinted"
        );
        assert_eq!(
            scroll_test_pixel(&data, stride, sample_x, row_y(2)),
            rgb(theme.background),
            "row 2 (ghost continuation) must never be tinted by a selection"
        );
        assert_eq!(
            scroll_test_pixel(&data, stride, sample_x, row_y(3)),
            rgb(theme.diff_padding_bg),
            "row 3 (diff padding) must show only its diff background, not a selection tint"
        );
    }

    // ── Text/gutter vertical centring within a host-set row pitch ──────
    //
    // Mirrors `macos::editor::tests::body_text_centred_in_row_and_shares_baseline_with_gutter`:
    // paints the same digit glyph as both the gutter number and the
    // body text at two row pitches, and checks the ink shifts down by
    // half the pitch's slack over the font's own natural height, with
    // gutter and body sharing a baseline once the offset is applied.

    const CENTRE_TEST_W: i32 = 200;
    const CENTRE_TEST_ROW_PITCH: f64 = 24.0;

    /// `(ascent + descent, measured "7" width)` for "Monospace 12" —
    /// the real font metrics every `centre_test_paint` call below also
    /// resolves (same family/size), used here only to size the fixture.
    fn centre_test_metrics() -> (f64, f64) {
        let surface =
            ImageSurface::create(Format::ARgb32, CENTRE_TEST_W, 40).expect("create ImageSurface");
        let cr = Context::new(&surface).expect("Context::new");
        let pango_layout = pangocairo::functions::create_layout(&cr);
        let pango_ctx = pango_layout.context();
        pango_ctx.set_font_description(&pango::FontDescription::from_string("Monospace 12"));
        let metrics = pango_ctx.metrics(None, None);
        let natural_pitch = (metrics.ascent() + metrics.descent()) as f64 / pango::SCALE as f64;
        pango_layout.set_text("7");
        let char_w = pango_layout.pixel_size().0 as f64;
        (natural_pitch, char_w)
    }

    /// Paint a one-line editor (raw + gutter text both `"7"`) at row
    /// pitch `pitch`, returning the painted ARGB32 buffer + stride.
    fn centre_test_paint(pitch: f64, gutter_chars: usize) -> (Vec<u8>, i32) {
        let theme = Theme::default();
        let mut surface = ImageSurface::create(Format::ARgb32, CENTRE_TEST_W, pitch.ceil() as i32)
            .expect("create ImageSurface");
        {
            let cr = Context::new(&surface).expect("Context::new");
            let (br, bg, bb) = cairo_rgb(theme.background);
            cr.set_source_rgb(br, bg, bb);
            cr.paint().ok();

            let pango_layout = pangocairo::functions::create_layout(&cr);
            let pango_ctx = pango_layout.context();
            pango_ctx.set_font_description(&pango::FontDescription::from_string("Monospace 12"));
            let metrics = pango_ctx.metrics(None, None);
            pango_layout.set_text("7");
            let char_w = pango_layout.pixel_size().0 as f64;

            let mut line = blank_line(0);
            line.raw_text = "7".into();
            line.gutter_text = "7".into();
            let mut editor = scroll_test_editor(1, 1, 1);
            editor.lines = vec![line];
            editor.gutter_char_width = gutter_chars;
            editor.rect = Rect::new(0.0, 0.0, CENTRE_TEST_W as f32, pitch as f32);

            draw_editor_with_options_and_v_scrollbar_w(
                &cr,
                &pango_layout,
                &metrics,
                &editor,
                &theme,
                char_w,
                pitch,
                EditorPaintOptions::default(),
                None,
            );
        }
        surface.flush();
        let stride = surface.stride();
        let data = surface.data().expect("surface data").to_vec();
        (data, stride)
    }

    /// Scan `data` for the vertical extent of non-background ink inside
    /// `[x_start, x_end) × [y_start, y_end)` — GTK's counterpart to
    /// `macos::editor::tests::ink_vertical_extent`. `None` if the window
    /// contains no ink.
    fn centre_test_ink_extent(
        data: &[u8],
        stride: i32,
        x_start: i32,
        x_end: i32,
        y_start: i32,
        y_end: i32,
        bg: Color,
    ) -> Option<(i32, i32)> {
        const TOL: i32 = 24;
        let mut extent: Option<(i32, i32)> = None;
        for y in y_start..y_end {
            let has_ink = (x_start..x_end).any(|x| {
                let (r, g, b) = scroll_test_pixel(data, stride as usize, x, y);
                (r as i32 - bg.r as i32).abs() > TOL
                    || (g as i32 - bg.g as i32).abs() > TOL
                    || (b as i32 - bg.b as i32).abs() > TOL
            });
            if has_ink {
                extent = Some(match extent {
                    Some((top, _)) => (top, y),
                    None => (y, y),
                });
            }
        }
        extent
    }

    /// The AI ghost suggestion painted after the cursor sits on the same
    /// centred baseline as the typed text before it on that row.
    #[test]
    fn ai_ghost_text_after_cursor_shares_body_text_baseline() {
        use crate::primitives::editor::{CursorPos, CursorShape, EditorCursor};

        let mut theme = Theme::default();
        theme.ghost_text_fg = theme.foreground;
        let pitch = CENTRE_TEST_ROW_PITCH;
        let mut surface = ImageSurface::create(Format::ARgb32, CENTRE_TEST_W, pitch.ceil() as i32)
            .expect("create ImageSurface");
        let char_w;
        {
            let cr = Context::new(&surface).expect("Context::new");
            let (br, bg, bb) = cairo_rgb(theme.background);
            cr.set_source_rgb(br, bg, bb);
            cr.paint().ok();

            let pango_layout = pangocairo::functions::create_layout(&cr);
            let pango_ctx = pango_layout.context();
            pango_ctx.set_font_description(&pango::FontDescription::from_string("Monospace 12"));
            let metrics = pango_ctx.metrics(None, None);
            pango_layout.set_text("7");
            char_w = pango_layout.pixel_size().0 as f64;

            let mut line = blank_line(0);
            line.raw_text = "7".into();
            line.ghost_suffix = Some("7".into());
            let mut editor = scroll_test_editor(1, 1, 1);
            editor.lines = vec![line];
            editor.gutter_char_width = 0;
            editor.cursor = Some(EditorCursor {
                pos: CursorPos {
                    view_line: 0,
                    col: 1,
                },
                shape: CursorShape::Bar,
            });
            editor.rect = Rect::new(0.0, 0.0, CENTRE_TEST_W as f32, pitch as f32);

            draw_editor_with_options_and_v_scrollbar_w(
                &cr,
                &pango_layout,
                &metrics,
                &editor,
                &theme,
                char_w,
                pitch,
                EditorPaintOptions::default(),
                None,
            );
        }
        surface.flush();
        let stride = surface.stride();
        let data = surface.data().expect("surface data").to_vec();

        let body = centre_test_ink_extent(
            &data,
            stride,
            0,
            char_w.round() as i32 - 1,
            0,
            pitch as i32,
            theme.background,
        )
        .expect("typed glyph should paint ink");
        // Skip the 2px bar cursor at the start of the ghost cell.
        let ghost = centre_test_ink_extent(
            &data,
            stride,
            char_w.round() as i32 + 3,
            (2.0 * char_w).round() as i32,
            0,
            pitch as i32,
            theme.background,
        )
        .expect("ghost glyph should paint ink");
        assert!(
            (ghost.0 - body.0).abs() <= 1 && (ghost.1 - body.1).abs() <= 1,
            "ghost suggestion ink {ghost:?} should share the typed glyph's vertical extent {body:?}"
        );
    }

    #[test]
    fn draw_editor_body_text_centred_in_row_and_shares_baseline_with_gutter() {
        let theme = Theme::default();
        let (natural_pitch, char_w) = centre_test_metrics();
        assert!(
            natural_pitch < CENTRE_TEST_ROW_PITCH,
            "fixture needs a font natural line height ({natural_pitch}) shorter than the \
             row pitch ({CENTRE_TEST_ROW_PITCH}) to leave any slack to centre in",
        );

        let gutter_chars = 2usize;
        let gutter_w = gutter_chars as f64 * char_w;

        let (natural_data, natural_stride) = centre_test_paint(natural_pitch, gutter_chars);
        let natural = centre_test_ink_extent(
            &natural_data,
            natural_stride,
            gutter_w.round() as i32,
            (gutter_w + char_w).round() as i32,
            0,
            natural_pitch.ceil() as i32,
            theme.background,
        )
        .expect("body glyph should paint some ink at the natural pitch");

        let (wide_data, wide_stride) = centre_test_paint(CENTRE_TEST_ROW_PITCH, gutter_chars);
        let wide = centre_test_ink_extent(
            &wide_data,
            wide_stride,
            gutter_w.round() as i32,
            (gutter_w + char_w).round() as i32,
            0,
            CENTRE_TEST_ROW_PITCH as i32,
            theme.background,
        )
        .expect("body glyph should paint some ink at the wide pitch");

        let expected_shift = (CENTRE_TEST_ROW_PITCH - natural_pitch) / 2.0;
        let top_shift = wide.0 as f64 - natural.0 as f64;
        let bottom_shift = wide.1 as f64 - natural.1 as f64;
        assert!(
            (top_shift - expected_shift).abs() <= 2.0
                && (bottom_shift - expected_shift).abs() <= 2.0,
            "widening the row pitch from {natural_pitch} to {CENTRE_TEST_ROW_PITCH} should \
             move the body glyph down by half the added slack ({expected_shift}px), got top \
             {top_shift}px / bottom {bottom_shift}px (ink {natural:?} -> {wide:?})"
        );

        let gutter = centre_test_ink_extent(
            &wide_data,
            wide_stride,
            0,
            gutter_w.round() as i32,
            0,
            CENTRE_TEST_ROW_PITCH as i32,
            theme.background,
        )
        .expect("gutter glyph should paint some ink");
        assert_eq!(
            gutter, wide,
            "gutter number and body text (same glyph, \"7\") should share a baseline, got \
             gutter={gutter:?}, body={wide:?}"
        );
    }
}