quadraui 0.6.1

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
//! macOS rasteriser for [`crate::primitives::editor::Editor`].
//!
//! Port of `crate::gtk::editor::draw_editor`: background (incl. DAP
//! stopped-line / diff / cursorline priority), per-line text via Core
//! Text, selection overlays (`selection`, `extra_selections`,
//! `yank_highlight`), line-number gutter, vertical scrollbar, and the
//! primary cursor (Block / Bar / Underline). Returns a default
//! [`EditorPaintResult`] — macOS, like GTK, paints its own caret rather
//! than delegating to a terminal cursor.
//!
//! ## Scrollbar
//!
//! `Editor::layout`'s `v_scrollbar_bounds` reserves the column (so
//! `EditorLayout::hit_test` and the content clip below already know
//! about it) and [`draw_editor_with_options_and_v_scrollbar_w`] paints
//! into it, mirroring `gtk::editor::draw_editor_with_options`'s "Scrollbars"
//! section: geometry comes from
//! [`Editor::layout_with_options_and_v_scrollbar_w`] (the same layout
//! hit-testing uses), the text clip is narrowed to
//! `text_bounds` so no glyph paints under the reserved column, and the
//! column itself is painted afterwards through the shared
//! [`crate::primitives::scrollbar::native_surface_paint::paint`] via the
//! [`super::surface::CgSurface`] adapter — the same pattern
//! `macos::data_table` uses to paint an embedded scrollbar from a bare
//! `ctx: CGContextRef`. The `v_scrollbar_w` argument lets a host
//! override the column's width (e.g. VS Code's fixed 14px, set via
//! [`crate::Backend::set_editor_v_scrollbar_width`]) instead of the
//! `cell_width` default; [`EditorPaintOptions::suppress_v_scrollbar`]
//! continues to opt out entirely for a `Minimap`-as-scrollbar host, same
//! as GTK.
//!
//! ## Scope omissions (follow-up)
//!
//! Deferred to subsequent tickets; each ships when a
//! kubeui-class consumer exercises it on macOS:
//!
//! - **Diagnostics + spell underlines** — wavy/dotted underlines via
//!   `kCTUnderlineStyleAttributeName` (deferred with attrs).
//! - **Indent guides, color columns, bracket-match alpha rects**.
//! - **AI ghost text + multi-cursor secondary carets**.
//! - **Gutter chrome** beyond line numbers — breakpoint glyph, git
//!   column, diagnostic dot, lightbulb glyph.

use core_graphics::sys::CGContextRef;
use core_text::font::CTFont;

use super::cg::*;
use super::surface::CgSurface;
use super::text::{draw_text, measure_text};
use crate::backend::EditorPaintResult;
use crate::primitives::editor::{
    CursorShape, DiffLine, Editor, EditorLine, EditorPaintOptions, EditorSelection, SelectionKind,
};
use crate::primitives::scrollbar::{native_surface_paint, Scrollbar};
use crate::text_util::snap_to_char_boundary;
use crate::theme::Theme;
use crate::types::Color;

/// Paint `editor` onto `ctx`. Returns the default
/// [`EditorPaintResult`] — macOS paints its own caret.
///
/// 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.
///
/// # Safety
///
/// `ctx` must be a valid `CGContextRef` borrowed for the duration of
/// the call.
pub unsafe fn draw_editor(
    ctx: CGContextRef,
    font: &CTFont,
    editor: &Editor,
    theme: &Theme,
    char_width: f64,
    line_height: f64,
) -> EditorPaintResult {
    draw_editor_with_options(
        ctx,
        font,
        editor,
        theme,
        char_width,
        line_height,
        EditorPaintOptions::default(),
    )
}

/// [`draw_editor`], plus [`EditorPaintOptions`] a host can set to
/// override otherwise-automatic paint decisions — `suppress_v_scrollbar`.
/// See the module doc's "Scrollbar" section.
///
/// Equivalent to [`draw_editor_with_options_and_v_scrollbar_w`] with
/// `v_scrollbar_w: None` (a `char_width`-wide scrollbar column).
///
/// # Safety
///
/// `ctx` must be a valid `CGContextRef` borrowed for the duration of
/// the call.
#[allow(clippy::too_many_arguments)]
pub unsafe fn draw_editor_with_options(
    ctx: CGContextRef,
    font: &CTFont,
    editor: &Editor,
    theme: &Theme,
    char_width: f64,
    line_height: f64,
    options: EditorPaintOptions,
) -> EditorPaintResult {
    draw_editor_with_options_and_v_scrollbar_w(
        ctx,
        font,
        editor,
        theme,
        char_width,
        line_height,
        options,
        None,
    )
}

/// [`draw_editor_with_options`], plus a host-settable vertical scrollbar
/// width in points — see
/// [`Editor::layout_with_options_and_v_scrollbar_w`] for the geometry
/// and the module doc's "Scrollbar" section for the paint. `None` sizes
/// the column at `char_width`. `MacBackend::draw_editor` calls this with
/// the width set through [`crate::Backend::set_editor_v_scrollbar_width`].
///
/// # Safety
///
/// `ctx` must be a valid `CGContextRef` borrowed for the duration of
/// the call.
#[allow(clippy::too_many_arguments)]
pub unsafe fn draw_editor_with_options_and_v_scrollbar_w(
    ctx: CGContextRef,
    font: &CTFont,
    editor: &Editor,
    theme: &Theme,
    char_width: f64,
    line_height: f64,
    options: EditorPaintOptions,
    v_scrollbar_w: Option<f32>,
) -> EditorPaintResult {
    let rect = &editor.rect;
    if rect.width <= 0.0 || rect.height <= 0.0 {
        return EditorPaintResult::default();
    }

    let x = rect.x as f64;
    let y = rect.y as f64;
    let w = rect.width as f64;
    let h = rect.height as f64;

    CGContextSaveGState(ctx);
    CGContextClipToRect(ctx, super::cg::rect(x, y, w, h));

    let bg = if editor.show_active_bg {
        theme.editor_active_background
    } else {
        theme.background
    };
    fill_rect(ctx, x, y, w, h, bg);

    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 = x + gutter_width - h_scroll_offset;

    // Shared by the gutter, body-text, and block-cursor glyph paints
    // below — computed once here and threaded into `paint_line_text`
    // rather than re-derived per call, so all three read the same value.
    let v_offset = text_v_offset(font, line_height);

    // Computed once up front, before any text paints, 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 "Scrollbar" 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,
    );

    // Cursorline / diff / DAP stopped-line backgrounds — painted before
    // text. Priority mirrors GTK: DAP-stopped > diff status >
    // cursorline (crate::gtk::editor::draw_editor).
    //
    // Stops 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.
    let row_bg_w =
        (editor_geom.text_bounds.x as f64 + editor_geom.text_bounds.width as f64 - x).max(0.0);
    for (view_idx, line) in editor.lines.iter().enumerate() {
        let row_bg = if line.is_dap_current {
            Some(theme.dap_stopped_bg)
        } else if let Some(diff_status) = line.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 line.is_current_line && editor.is_active && editor.cursorline {
            Some(theme.cursorline_bg)
        } else {
            None
        };
        if let Some(color) = row_bg {
            let line_y = y + view_idx as f64 * line_height;
            fill_rect(ctx, x, line_y, row_bg_w, line_height, color);
        }
    }

    // Selection overlays — painted before text so text reads on top,
    // matching GTK's ordering (see module doc on crate::gtk::editor).
    if let Some(sel) = &editor.selection {
        draw_visual_selection(
            ctx,
            font,
            sel,
            &editor.lines,
            x,
            y,
            w,
            line_height,
            text_x_offset,
            theme.selection,
            theme.selection_alpha as f64,
        );
    }
    for esel in &editor.extra_selections {
        draw_visual_selection(
            ctx,
            font,
            esel,
            &editor.lines,
            x,
            y,
            w,
            line_height,
            text_x_offset,
            theme.selection,
            theme.selection_alpha as f64,
        );
    }
    if let Some(yh) = &editor.yank_highlight {
        draw_visual_selection(
            ctx,
            font,
            yh,
            &editor.lines,
            x,
            y,
            w,
            line_height,
            text_x_offset,
            theme.yank_highlight_bg,
            theme.yank_highlight_alpha as f64,
        );
    }

    // Gutter — right-aligned line number text. Painted unclipped (it
    // sits entirely left of the text-area clip established below, so a
    // scrollbar-column clip there would never touch it anyway).
    for (view_idx, line) in editor.lines.iter().enumerate() {
        let line_y = y + view_idx as f64 * line_height;
        if line_y >= y + h {
            break;
        }
        if gutter_width > 0.0 && !line.gutter_text.is_empty() {
            let (gtw, _) = measure_text(font, &line.gutter_text);
            let gx = x + gutter_width - gtw - 4.0;
            draw_text(
                ctx,
                font,
                &line.gutter_text,
                gx.max(x + 2.0),
                line_y + v_offset,
                color_to_cg(theme.line_number_fg),
            );
        }
    }

    // ── 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
    // `w - gutter_width`, mirroring `gtk::editor::draw_editor_with_options`
    // — text stops short of the scrollbar column instead of painting
    // glyphs the scrollbar then overlays.
    CGContextSaveGState(ctx);
    CGContextClipToRect(
        ctx,
        super::cg::rect(x + gutter_width, y, editor_geom.text_bounds.width as f64, h),
    );
    for (view_idx, line) in editor.lines.iter().enumerate() {
        let line_y = y + view_idx as f64 * line_height;
        if line_y >= y + h {
            break;
        }

        // Lay the line out as contiguous, non-overlapping runs (gaps in
        // `theme.foreground`, spans in their own colour) so every glyph
        // is painted exactly once — see `paint_line_text`'s doc for the
        // invariant this maintains.
        let raw_x = text_x_offset;
        paint_line_text(
            ctx,
            font,
            line,
            raw_x,
            line_y,
            v_offset,
            line_height,
            theme.foreground,
        );
    }
    CGContextRestoreGState(ctx);

    // Vertical scrollbar — painted after text (into the reserved column
    // the clip above left untouched), before the cursor, mirroring
    // `gtk::editor::draw_editor_with_options`'s z-order (see module
    // doc's "Scrollbar" section).
    if let Some(v_track) = editor_geom.v_scrollbar_bounds {
        let sb = Scrollbar::vertical(
            "macos: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 surface = CgSurface {
            ctx,
            font: Some(font),
        };
        native_surface_paint::paint(&sb, &mut surface, theme);
    }

    // Primary cursor.
    if let Some(cursor) = editor.cursor {
        if cursor.pos.view_line < editor.lines.len() {
            let line = &editor.lines[cursor.pos.view_line];
            let prefix_end = char_byte_offset(&line.raw_text, cursor.pos.col);
            let prefix = &line.raw_text[..prefix_end];
            let (prefix_w, _) = measure_text(font, prefix);
            let cur_x = text_x_offset + prefix_w;
            let cur_y = y + cursor.pos.view_line as f64 * line_height;
            match cursor.shape {
                CursorShape::Block => {
                    // The cursor rect itself stays full-row (unchanged);
                    // only the glyph repainted on top of it is
                    // text-relative, so it gets the same `v_offset` the
                    // body-text paint above uses, to stay aligned.
                    fill_rect(ctx, cur_x, cur_y, char_width, line_height, theme.cursor);
                    // Re-paint the glyph under the cursor in background
                    // colour so it reads against the cursor fill.
                    let ch = line.raw_text[prefix_end..]
                        .chars()
                        .next()
                        .map(|c| c.to_string())
                        .unwrap_or_default();
                    if !ch.is_empty() {
                        draw_text(
                            ctx,
                            font,
                            &ch,
                            cur_x,
                            cur_y + v_offset,
                            color_to_cg(theme.background),
                        );
                    }
                }
                CursorShape::Bar => {
                    fill_rect(ctx, cur_x, cur_y, 2.0, line_height, theme.cursor);
                }
                CursorShape::Underline => {
                    let underline_h = (line_height * 0.12).max(1.0);
                    fill_rect(
                        ctx,
                        cur_x,
                        cur_y + line_height - underline_h,
                        char_width,
                        underline_h,
                        theme.cursor,
                    );
                }
            }
        }
    }

    CGContextRestoreGState(ctx);
    EditorPaintResult::default()
}

/// Vertical distance from a row's top edge to the top of the glyph cell
/// that centres `font`'s own natural line height inside `line_height`.
///
/// A host sets the editor's row pitch (`line_height`) independently of
/// the font's natural height — vimcode's VS Code-style 18px rows over a
/// 12pt Menlo whose ascent + descent + leading is ~14px — so a glyph
/// drawn straight at the row's top edge (`draw_text`'s `y` is the cell's
/// top, per that fn's doc) sits high in its row, with all the slack
/// below it. Every text paint inside one row — gutter line number, body
/// text, the glyph repainted under a block cursor — adds this offset, so
/// they share a baseline and the row reads centred.
///
/// Negative when `line_height` is *tighter* than the font's natural
/// height, which lifts the glyph by the overflow's half so the row still
/// reads centred rather than clipping only its bottom.
fn text_v_offset(font: &CTFont, line_height: f64) -> f64 {
    (line_height - (font.ascent() + font.descent() + font.leading())) / 2.0
}

/// Paint `line.raw_text` as a sequence of contiguous, non-overlapping
/// runs: gaps between (and around) `line.spans` in `default_fg`, each
/// span in its own `style.fg` (with `style.bg` filled first, if set).
///
/// Every glyph in the line is painted by exactly one [`draw_text`] call,
/// because the runs partition `text` with no overlapping coverage. Core
/// Text anti-aliases glyph edges with partial coverage; compositing two
/// glyph draws at the same position would turn edge alpha `a` into
/// `1-(1-a)²`, saturating the soft edge pixels and making strokes look
/// thicker and stair-stepped. Mirrors [`crate::win::editor`]'s
/// `paint_line_text`, which coalesces spans into non-overlapping runs
/// for the same reason; GTK's rasteriser holds the invariant by painting
/// the whole line in one pass via a single Pango layout with a
/// `PangoAttrList`.
///
/// Spans are expected to be sorted by `start_byte` and non-overlapping
/// (the shape every span producer — syntax highlighting, search
/// matches — emits in practice, mirroring `crate::win::editor`'s same
/// assumption). An out-of-order or overlapping span is tolerated
/// defensively: any portion already covered by an earlier run is
/// skipped rather than re-painted.
///
/// Only the glyph draw is nudged down from `line_y` by `v_offset`
/// ([`text_v_offset`], computed once by the caller so every text paint
/// in the row agrees), so it sits centred in `line_height`; the
/// span-background fill stays anchored at `line_y`/`line_height` so it
/// still covers the full row.
#[allow(clippy::too_many_arguments)]
unsafe fn paint_line_text(
    ctx: CGContextRef,
    font: &CTFont,
    line: &EditorLine,
    raw_x: f64,
    line_y: f64,
    v_offset: f64,
    line_height: f64,
    default_fg: Color,
) {
    let text = &line.raw_text;
    if text.is_empty() {
        return;
    }

    let mut ordered_spans: Vec<(usize, usize, Color, Option<Color>)> = line
        .spans
        .iter()
        .filter_map(|span| {
            let start = snap_to_char_boundary(text, span.start_byte);
            let end = snap_to_char_boundary(text, span.end_byte);
            (start < end).then_some((start, end, span.style.fg, span.style.bg))
        })
        .collect();
    ordered_spans.sort_by_key(|&(start, _, _, _)| start);

    // Paint the run `text[from..to]` at its own x position (derived
    // from measuring the prefix `text[..from]`, same baseline the
    // original per-span code used) in `fg`, filling `bg` first when
    // present.
    let paint_run = |from: usize, to: usize, fg: Color, bg: Option<Color>| {
        if from >= to {
            return;
        }
        let (prefix_w, _) = measure_text(font, &text[..from]);
        let run_x = raw_x + prefix_w;
        let slice = &text[from..to];
        if let Some(bg) = bg {
            let (run_w, _) = measure_text(font, slice);
            fill_rect(ctx, run_x, line_y, run_w, line_height, bg);
        }
        draw_text(ctx, font, slice, run_x, line_y + v_offset, color_to_cg(fg));
    };

    let mut cursor = 0usize;
    for (start, end, fg, bg) in ordered_spans {
        let start = start.max(cursor);
        if start >= end {
            // Fully consumed by an earlier (overlapping) run.
            continue;
        }
        if start > cursor {
            paint_run(cursor, start, default_fg, None);
        }
        paint_run(start, end, fg, bg);
        cursor = end;
    }
    if cursor < text.len() {
        paint_run(cursor, text.len(), default_fg, None);
    }
}

/// Byte offset corresponding to the `col`-th character of `s`. Saturates
/// at `s.len()` for out-of-range columns.
fn char_byte_offset(s: &str, col: usize) -> usize {
    s.char_indices().nth(col).map(|(b, _)| b).unwrap_or(s.len())
}

/// Paint one visual-selection overlay (`editor.selection`,
/// `extra_selections`, or `yank_highlight` — they share a shape) across
/// `lines`. Port of `crate::gtk::editor::draw_visual_selection`, using
/// Core Text glyph-run measurement in place of Pango's
/// `index_to_pos`/`pixel_size`. 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.
#[allow(clippy::too_many_arguments)]
unsafe fn draw_visual_selection(
    ctx: CGContextRef,
    font: &CTFont,
    sel: &EditorSelection,
    lines: &[EditorLine],
    x: f64,
    y: f64,
    w: f64,
    line_height: f64,
    text_x_offset: f64,
    color: Color,
    alpha: f64,
) {
    for (view_idx, rl) in lines.iter().enumerate() {
        let Some(cols) = sel.cols_on(rl) else {
            continue;
        };
        let line_y = y + view_idx as f64 * line_height;

        if sel.kind == SelectionKind::Line {
            let highlight_width = w - (text_x_offset - x);
            fill_rect_alpha(
                ctx,
                text_x_offset,
                line_y,
                highlight_width,
                line_height,
                color,
                alpha,
            );
            continue;
        }

        let start_byte = char_byte_offset(&rl.raw_text, cols.start);
        let (prefix_w, _) = measure_text(font, &rl.raw_text[..start_byte]);
        let start_x = text_x_offset + prefix_w;

        let width = if cols.extends_beyond {
            // Selection runs past this visual segment's text — extend
            // the highlight to the end of the rendered line content
            // (matches GTK's use of the Pango layout's full pixel
            // width in this branch).
            let (line_w, _) = measure_text(font, &rl.raw_text);
            (text_x_offset + line_w - start_x).max(0.0)
        } else {
            let end_byte = char_byte_offset(&rl.raw_text, cols.end);
            let (end_w, _) = measure_text(font, &rl.raw_text[..end_byte]);
            (text_x_offset + end_w - start_x).max(0.0)
        };
        if width > 0.0 {
            fill_rect_alpha(ctx, start_x, line_y, width, line_height, color, alpha);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::super::headless::BitmapSurface;
    use super::super::text::{font_metrics, make_font};
    use super::super::MacBackend;
    use super::*;
    use crate::event::{Rect as QRect, Viewport};
    use crate::primitives::editor::{
        CursorPos, EditorCursor, EditorLine, EditorStyledSpan as ESpan, Style,
    };
    use crate::theme::Theme;
    use crate::Backend;
    use std::collections::{HashMap, HashSet};

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

    fn font() -> CTFont {
        make_font("Menlo", 14.0).expect("Menlo installed")
    }

    fn one_line(text: &str) -> EditorLine {
        EditorLine {
            raw_text: text.into(),
            gutter_text: "1".into(),
            spans: vec![],
            line_idx: 0,
            is_current_line: true,
            is_fold_header: false,
            folded_line_count: 0,
            git_diff: None,
            diff_status: None,
            diagnostics: vec![],
            spell_errors: vec![],
            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![],
            colorcolumns: vec![],
        }
    }

    fn editor_with_cursor(text: &str, shape: CursorShape, col: usize) -> Editor {
        Editor {
            id: "editor:0".into(),
            rect: QRect::new(0.0, 0.0, W as f32, H as f32),
            lines: vec![one_line(text)],
            cursor: Some(EditorCursor {
                pos: CursorPos { view_line: 0, col },
                shape,
            }),
            extra_cursors: vec![],
            selection: None,
            extra_selections: vec![],
            yank_highlight: None,
            scroll_top: 0,
            scroll_left: 0,
            total_lines: 1,
            max_col: text.chars().count(),
            gutter_char_width: 3,
            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![],
            active_indent_col: None,
            tabstop: 4,
            cursorline: false,
            lightbulb_glyph: '!',
        }
    }

    fn paint_via_backend(editor: &Editor) -> BitmapSurface {
        let surface = BitmapSurface::new(W, H);
        surface.fill(0.0, 0.0, 0.0, 0.0);
        let mut backend = MacBackend::new();
        backend.set_current_font(font());
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.enter_frame_scope(surface.context_ptr(), |b| {
            b.draw_editor(editor.rect, editor);
        });
        backend.end_frame();
        surface
    }

    #[test]
    fn block_cursor_paints_theme_cursor_color() {
        let editor = editor_with_cursor("let x = 1;", CursorShape::Block, 0);
        let surface = paint_via_backend(&editor);
        let theme = Theme::default();
        let metrics = font_metrics(&font());
        // Cursor lands at column 0 in gutter-offset coords. Gutter is
        // 3 char_widths, so cursor starts at 3*char_width on x.
        let cx = (3.0 * metrics.char_width) as u32 + 1;
        let cy = (metrics.line_height / 2.0) as u32;
        let (r, g, b, _) = surface.pixel(cx, cy);
        assert_eq!(
            (r, g, b),
            (theme.cursor.r, theme.cursor.g, theme.cursor.b),
            "block cursor pixel at ({}, {}) should be theme.cursor",
            cx,
            cy,
        );
    }

    #[test]
    fn cursorline_highlight_painted_when_active() {
        let mut editor = editor_with_cursor("let x = 1;", CursorShape::Bar, 0);
        editor.cursorline = true;
        let surface = paint_via_backend(&editor);
        let theme = Theme::default();
        // Probe far to the right of any glyph or cursor.
        let px = W - 4;
        let py = 4_u32;
        let (r, g, b, _) = surface.pixel(px, py);
        assert_eq!(
            (r, g, b),
            (
                theme.cursorline_bg.r,
                theme.cursorline_bg.g,
                theme.cursorline_bg.b
            ),
        );
    }

    #[test]
    fn span_bg_paints_over_raw_run() {
        // A line whose first 3 bytes carry a coloured background — the
        // probe inside that range should read the span bg, not the
        // editor bg.
        let mut line = one_line("alpha beta");
        line.spans = vec![ESpan {
            start_byte: 0,
            end_byte: 3,
            style: Style {
                fg: Color::rgb(255, 255, 255),
                bg: Some(Color::rgb(50, 100, 150)),
                bold: false,
                italic: false,
                font_scale: 1.0,
            },
        }];
        let mut editor = editor_with_cursor("alpha beta", CursorShape::Bar, 99);
        editor.lines = vec![line];
        let surface = paint_via_backend(&editor);
        let metrics = font_metrics(&font());
        // The span covers raw_text[0..3] ("alp"). Probe at the very
        // top scanline (y=0) of the line — above any glyph ink and
        // its anti-aliased boundary, fully inside the span bg.
        let text_start = 3.0 * metrics.char_width;
        let px = (text_start + metrics.char_width * 0.5) as u32;
        let py = 0_u32;
        let (r, g, b, _) = surface.pixel(px, py);
        // Span bg painted over editor bg.
        assert_eq!((r, g, b), (50, 100, 150));
    }

    /// A span covering the entire line must still paint the line's text
    /// exactly once, not as an overlapping pair of runs. Core Text's
    /// recorded [`TextRun`]s (via `start_recording_text`/
    /// `MacBackend::text_runs`) let this be asserted directly: exactly
    /// one run for the line's text, regardless of how many spans cover
    /// it.
    #[test]
    fn span_covering_whole_line_paints_exactly_one_text_run() {
        let mut line = one_line("alpha beta");
        line.spans = vec![ESpan {
            start_byte: 0,
            end_byte: line.raw_text.len(),
            style: Style {
                fg: Color::rgb(200, 100, 50),
                bg: None,
                bold: false,
                italic: false,
                font_scale: 1.0,
            },
        }];
        // `Bar` cursor at an out-of-range column: the cursor overlay
        // never draws a glyph of its own (only `Block` repaints one),
        // so the only `draw_text` calls for "alpha beta" come from the
        // line-text painter under test.
        let mut editor = editor_with_cursor("alpha beta", CursorShape::Bar, 99);
        editor.lines = vec![line];

        let surface = BitmapSurface::new(W, H);
        surface.fill(0.0, 0.0, 0.0, 0.0);
        let mut backend = MacBackend::new();
        backend.set_current_font(font());
        backend.set_painted_text_recording(true);
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.enter_frame_scope(surface.context_ptr(), |b| {
            b.draw_editor(editor.rect, &editor);
        });
        backend.end_frame();

        let whole_line_runs: Vec<_> = backend
            .text_runs()
            .iter()
            .filter(|run| run.text == "alpha beta")
            .collect();
        assert_eq!(
            whole_line_runs.len(),
            1,
            "\"alpha beta\" should be painted exactly once (overlapping raw-run + \
             span-overlay would record it twice at the same position), got: {:?}",
            whole_line_runs,
        );
    }

    /// A span covering only part of the line must leave the uncovered
    /// gaps painted too, and each run — gap or span — must appear
    /// exactly once with no overlap. Pins both: the recorded
    /// [`TextRun`]s for `"alpha beta"` with `spans = [0..5]` must be
    /// exactly the gap `" beta"` and the span `"alpha"`, each starting
    /// where the previous one ends.
    #[test]
    fn span_covering_part_of_line_leaves_gap_runs_contiguous() {
        let mut line = one_line("alpha beta");
        line.spans = vec![ESpan {
            start_byte: 0,
            end_byte: 5,
            style: Style {
                fg: Color::rgb(200, 100, 50),
                bg: None,
                bold: false,
                italic: false,
                font_scale: 1.0,
            },
        }];
        let mut editor = editor_with_cursor("alpha beta", CursorShape::Bar, 99);
        editor.lines = vec![line];

        let surface = BitmapSurface::new(W, H);
        surface.fill(0.0, 0.0, 0.0, 0.0);
        let mut backend = MacBackend::new();
        backend.set_current_font(font());
        backend.set_painted_text_recording(true);
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.enter_frame_scope(surface.context_ptr(), |b| {
            b.draw_editor(editor.rect, &editor);
        });
        backend.end_frame();

        let metrics = font_metrics(&font());
        let text_start = 3.0 * metrics.char_width; // gutter_char_width = 3

        let span_runs: Vec<_> = backend
            .text_runs()
            .iter()
            .filter(|run| run.text == "alpha")
            .collect();
        assert_eq!(
            span_runs.len(),
            1,
            "the span \"alpha\" should be painted exactly once, got: {:?}",
            span_runs,
        );
        assert!(
            (span_runs[0].bounds.x as f64 - text_start).abs() < 0.5,
            "the span run should start at the line's text origin, got x={}",
            span_runs[0].bounds.x,
        );

        let gap_runs: Vec<_> = backend
            .text_runs()
            .iter()
            .filter(|run| run.text == " beta")
            .collect();
        assert_eq!(
            gap_runs.len(),
            1,
            "the uncovered gap \" beta\" should still be painted exactly \
             once, got: {:?}",
            gap_runs,
        );
        let gap_x_expected = text_start + 5.0 * metrics.char_width;
        assert!(
            (gap_runs[0].bounds.x as f64 - gap_x_expected).abs() < 0.5,
            "the gap run should start right after the span ends, got x={}, expected={}",
            gap_runs[0].bounds.x,
            gap_x_expected,
        );
    }

    /// `StyledSpan` byte offsets must be snapped to char boundaries.
    /// A span landing mid-multibyte-character (é / CJK / emoji)
    /// could panic `&line.raw_text[..start]` / `[start..end]`.
    /// This test exercises multibyte spans and a multibyte cursor
    /// column via `char_byte_offset`.
    #[test]
    fn multibyte_span_and_cursor_do_not_panic() {
        // "café🎉 beta" — byte 4 sits inside the 2-byte 'é' (starts at
        // byte 3); byte 8 sits inside the 4-byte emoji (starts at byte 6).
        let text = "café🎉 beta";
        assert!(!text.is_char_boundary(4));
        assert!(!text.is_char_boundary(8));

        let mut line = one_line(text);
        line.spans = vec![ESpan {
            start_byte: 4,
            end_byte: 8,
            style: Style {
                fg: Color::rgb(255, 255, 255),
                bg: Some(Color::rgb(50, 100, 150)),
                bold: false,
                italic: false,
                font_scale: 1.0,
            },
        }];
        // Cursor column 3 lands on 'é' (a char index, not a byte
        // offset) — `char_byte_offset` must resolve it to a boundary.
        let mut editor = editor_with_cursor(text, CursorShape::Block, 3);
        editor.lines = vec![line];

        // Must not panic.
        let _surface = paint_via_backend(&editor);
    }

    #[test]
    fn empty_editor_returns_default_paint_result() {
        let editor = Editor {
            id: "editor:empty".into(),
            rect: QRect::new(0.0, 0.0, 0.0, 0.0),
            lines: vec![],
            cursor: None,
            extra_cursors: vec![],
            selection: None,
            extra_selections: vec![],
            yank_highlight: None,
            scroll_top: 0,
            scroll_left: 0,
            total_lines: 0,
            max_col: 0,
            gutter_char_width: 0,
            is_active: false,
            show_active_bg: false,
            has_git_diff: false,
            has_breakpoints: false,
            diagnostic_gutter: HashMap::new(),
            code_action_lines: HashSet::new(),
            bracket_match_positions: vec![],
            active_indent_col: None,
            tabstop: 4,
            cursorline: false,
            lightbulb_glyph: '!',
        };
        let surface = BitmapSurface::new(10, 10);
        surface.fill(0.0, 0.0, 0.0, 0.0);
        let mut backend = MacBackend::new();
        backend.set_current_font(font());
        backend.begin_frame(Viewport::new(10.0, 10.0, 1.0));
        let result = std::cell::RefCell::new(None);
        backend.enter_frame_scope(surface.context_ptr(), |b| {
            *result.borrow_mut() = Some(b.draw_editor(editor.rect, &editor));
        });
        backend.end_frame();
        assert_eq!(result.into_inner().unwrap(), EditorPaintResult::default(),);
    }

    /// `a` and `b` agree within `tol` — used for alpha-blended overlay
    /// pixels, where the exact composited value depends on CG's
    /// blending internals and only the *direction* (blended toward the
    /// overlay colour) is being asserted.
    fn approx(a: u8, b: u8, tol: u8) -> bool {
        a.abs_diff(b) <= tol
    }

    /// `editor.selection` must be read by the rasteriser.
    /// A `Line`-kind selection should paint `theme.selection`
    /// alpha-blended over the background, not the plain background.
    #[test]
    fn line_selection_paints_over_background() {
        let mut editor = editor_with_cursor("let x = 1;", CursorShape::Bar, 99);
        editor.selection = Some(EditorSelection {
            kind: SelectionKind::Line,
            start_line: 0,
            start_col: 0,
            end_line: 0,
            end_col: 0,
        });
        let surface = paint_via_backend(&editor);
        let theme = Theme::default();

        // Far right of any glyph ink, same probe spot as the cursorline
        // test — inside the full-width Line-selection highlight.
        let (r, g, b, _) = surface.pixel(W - 4, 4);
        assert_ne!(
            (r, g, b),
            (theme.background.r, theme.background.g, theme.background.b),
            "selected row should not read as plain background"
        );
        let expected_r = (theme.selection.r as f32 * theme.selection_alpha
            + theme.background.r as f32 * (1.0 - theme.selection_alpha))
            as u8;
        let expected_g = (theme.selection.g as f32 * theme.selection_alpha
            + theme.background.g as f32 * (1.0 - theme.selection_alpha))
            as u8;
        let expected_b = (theme.selection.b as f32 * theme.selection_alpha
            + theme.background.b as f32 * (1.0 - theme.selection_alpha))
            as u8;
        assert!(
            approx(r, expected_r, 4) && approx(g, expected_g, 4) && approx(b, expected_b, 4),
            "expected ~({expected_r}, {expected_g}, {expected_b}), got ({r}, {g}, {b})"
        );
    }

    /// `yank_highlight` on `Editor` must be read by the rasteriser.
    /// The yank overlay paints its own themed colour,
    /// distinct from a plain `editor.selection` overlay.
    #[test]
    fn yank_highlight_paints_distinct_color() {
        let mut editor = editor_with_cursor("let x = 1;", CursorShape::Bar, 99);
        editor.yank_highlight = Some(EditorSelection {
            kind: SelectionKind::Line,
            start_line: 0,
            start_col: 0,
            end_line: 0,
            end_col: 0,
        });
        let surface = paint_via_backend(&editor);
        let theme = Theme::default();

        let (r, g, b, _) = surface.pixel(W - 4, 4);
        assert_ne!(
            (r, g, b),
            (theme.background.r, theme.background.g, theme.background.b),
            "yanked row should not read as plain background"
        );
        let expected_r = (theme.yank_highlight_bg.r as f32 * theme.yank_highlight_alpha
            + theme.background.r as f32 * (1.0 - theme.yank_highlight_alpha))
            as u8;
        let expected_g = (theme.yank_highlight_bg.g as f32 * theme.yank_highlight_alpha
            + theme.background.g as f32 * (1.0 - theme.yank_highlight_alpha))
            as u8;
        let expected_b = (theme.yank_highlight_bg.b as f32 * theme.yank_highlight_alpha
            + theme.background.b as f32 * (1.0 - theme.yank_highlight_alpha))
            as u8;
        assert!(
            approx(r, expected_r, 4) && approx(g, expected_g, 4) && approx(b, expected_b, 4),
            "expected ~({expected_r}, {expected_g}, {expected_b}), got ({r}, {g}, {b})"
        );
    }

    /// A `Char`-kind selection must only highlight the selected column
    /// range — columns outside it stay plain background.
    #[test]
    fn char_selection_highlights_only_selected_columns() {
        let mut editor = editor_with_cursor("alpha beta", CursorShape::Bar, 99);
        editor.selection = Some(EditorSelection {
            kind: SelectionKind::Char,
            start_line: 0,
            start_col: 0,
            end_line: 0,
            end_col: 2, // inclusive -> covers chars 0..=2, "alp"
        });
        let surface = paint_via_backend(&editor);
        let theme = Theme::default();
        let metrics = font_metrics(&font());
        let text_start = 3.0 * metrics.char_width; // gutter width

        // Inside the selected range (char index 1, "l").
        let in_px = (text_start + metrics.char_width * 1.5) as u32;
        let (r, g, b, _) = surface.pixel(in_px, 0);
        assert_ne!(
            (r, g, b),
            (theme.background.r, theme.background.g, theme.background.b),
            "column inside selection should be highlighted"
        );

        // Outside the selected range (char index 6, "e" of "beta").
        let out_px = (text_start + metrics.char_width * 6.5) as u32;
        let (r2, g2, b2, _) = surface.pixel(out_px, 0);
        assert_eq!(
            (r2, g2, b2),
            (theme.background.r, theme.background.g, theme.background.b),
            "column outside selection should stay plain background"
        );
    }

    /// Diff backgrounds (`DiffLine::Added` / `Removed` / `Padding`)
    /// must be painted by the rasteriser. Diff status takes priority
    /// over cursorline, matching `crate::gtk::editor::draw_editor`'s
    /// priority order.
    #[test]
    fn diff_added_background_overrides_cursorline() {
        let mut line = one_line("added line");
        line.diff_status = Some(DiffLine::Added);
        let mut editor = editor_with_cursor("added line", CursorShape::Bar, 99);
        editor.lines = vec![line];
        editor.cursorline = true; // would paint cursorline_bg if diff didn't win
        let surface = paint_via_backend(&editor);
        let theme = Theme::default();

        let (r, g, b, _) = surface.pixel(W - 4, 4);
        assert_eq!(
            (r, g, b),
            (
                theme.diff_added_bg.r,
                theme.diff_added_bg.g,
                theme.diff_added_bg.b
            ),
            "diff-added row should paint theme.diff_added_bg, not cursorline_bg"
        );
    }

    /// Scan `surface` for the vertical extent of non-background ink
    /// inside `[x_start, x_end) × [y_start, y_end)` — the smallest `top`
    /// and largest `bottom` row (inclusive) where any pixel in the
    /// column range differs from `bg` by more than a small
    /// anti-aliasing tolerance. `None` if the window contains no ink.
    fn ink_vertical_extent(
        surface: &BitmapSurface,
        x_start: u32,
        x_end: u32,
        y_start: u32,
        y_end: u32,
        bg: Color,
    ) -> Option<(u32, u32)> {
        const TOL: i32 = 8;
        let mut extent: Option<(u32, u32)> = None;
        for y in y_start..y_end {
            let has_ink = (x_start..x_end).any(|x| {
                let (r, g, b, _) = surface.pixel(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 editor's row pitch ([`Backend::set_current_line_height`]) is
    /// a host decision, independent of the font's own natural line
    /// height: a 12pt Menlo's ~14px of ascent + descent + leading inside
    /// a VS Code-style 18px row leaves ~4px of slack. Both halves of the
    /// contract that slack is split *evenly* are pinned here:
    ///
    /// - Widening the pitch from the font's natural height to 18px moves
    ///   the body glyph's ink down by half the slack that added — ink
    ///   anchored to the row's top edge instead wouldn't move at all.
    /// - At 18px the gutter number and the body text — the identical
    ///   glyph, `"7"`, hence identical ink — occupy exactly the same
    ///   rows, i.e. they share a baseline.
    ///
    /// Asserting on the *shift* rather than on the ink's absolute
    /// midpoint is deliberate: a digit has no descender, so its ink sits
    /// in the upper part of its glyph cell and its own midpoint is
    /// legitimately above the row's, by a glyph-shape-dependent amount
    /// no centring rule should be read as promising.
    #[test]
    fn body_text_centred_in_row_and_shares_baseline_with_gutter() {
        const ROW_PITCH: f64 = 18.0;
        let metrics = font_metrics(&make_font("Menlo", 12.0).expect("Menlo installed"));
        let natural_pitch = metrics.line_height;
        assert!(
            natural_pitch < ROW_PITCH,
            "fixture needs a font natural line height ({natural_pitch}) shorter \
             than the row pitch ({ROW_PITCH}) to leave any slack to centre in",
        );

        let theme = Theme::default();
        let gutter_chars = 2usize;
        let paint_at_pitch = |pitch: f64| {
            let mut line = one_line("7");
            line.gutter_text = "7".into();
            let mut editor = editor_with_cursor("7", CursorShape::Bar, 99);
            editor.cursor = None; // isolate glyph ink from any cursor paint
            editor.lines = vec![line];
            editor.gutter_char_width = gutter_chars;

            let surface = BitmapSurface::new(W, H);
            surface.fill(
                theme.background.r as f64 / 255.0,
                theme.background.g as f64 / 255.0,
                theme.background.b as f64 / 255.0,
                1.0,
            );
            let mut backend = MacBackend::new();
            backend.set_current_font(make_font("Menlo", 12.0).expect("Menlo installed"));
            backend.set_current_line_height(pitch);
            backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
            backend.enter_frame_scope(surface.context_ptr(), |b| {
                b.draw_editor(editor.rect, &editor);
            });
            backend.end_frame();
            surface
        };

        let char_w = metrics.char_width;
        let gutter_w = gutter_chars as f64 * char_w;
        let body_ink = |surface: &BitmapSurface, pitch: f64| {
            ink_vertical_extent(
                surface,
                gutter_w.round() as u32,
                (gutter_w + char_w).round() as u32,
                0,
                pitch.ceil() as u32,
                theme.background,
            )
            .expect("body glyph should paint some ink")
        };

        let natural = body_ink(&paint_at_pitch(natural_pitch), natural_pitch);
        let wide_surface = paint_at_pitch(ROW_PITCH);
        let wide = body_ink(&wide_surface, ROW_PITCH);

        let expected_shift = (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() <= 1.0
                && (bottom_shift - expected_shift).abs() <= 1.0,
            "widening the row pitch from {natural_pitch} to {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 = ink_vertical_extent(
            &wide_surface,
            0,
            gutter_w.round() as u32,
            0,
            ROW_PITCH as u32,
            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:?}"
        );
    }

    // ── Vertical scrollbar ────────────────────────────────────────────────
    //
    // Mirrors `gtk::editor::draw_editor_with_options`'s own scroll-test
    // harness: blank lines, no gutter, explicit `char_width`/`line_height`
    // passed directly to `draw_editor_with_options` (independent of the
    // real font's own metrics, same as `font` is only used for glyph
    // measurement/paint here, not for the geometry grid) — so the only
    // thing in play is the scrollbar-column geometry itself.

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

    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` with no gutter,
    /// so the only geometry in play is the scrollbar reservation itself.
    fn scroll_test_editor(total_lines: usize, num_lines: usize) -> Editor {
        Editor {
            id: "editor:scroll".into(),
            rect: QRect::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: 0,
            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: '!',
        }
    }

    /// Paint `editor` with `options` via [`draw_editor_with_options`]
    /// directly on a fresh headless surface — bypassing `MacBackend`
    /// entirely, the same way `gtk::editor`'s own scroll tests bypass
    /// `GtkBackend` (its trait-level `draw_editor` has no options
    /// parameter; see `EditorPaintOptions`'s doc for why).
    fn scroll_test_paint(editor: &Editor, options: EditorPaintOptions) -> BitmapSurface {
        scroll_test_paint_with_v_scrollbar_w(editor, options, None)
    }

    /// [`scroll_test_paint`], plus a scrollbar-width override via
    /// [`draw_editor_with_options_and_v_scrollbar_w`].
    fn scroll_test_paint_with_v_scrollbar_w(
        editor: &Editor,
        options: EditorPaintOptions,
        v_scrollbar_w: Option<f32>,
    ) -> BitmapSurface {
        let surface = BitmapSurface::new(SCROLL_TEST_W, SCROLL_TEST_H);
        surface.fill(0.0, 0.0, 0.0, 0.0);
        let f = font();
        let theme = Theme::default();
        unsafe {
            draw_editor_with_options_and_v_scrollbar_w(
                surface.context_ptr(),
                &f,
                editor,
                &theme,
                SCROLL_TEST_CHAR_W,
                SCROLL_TEST_LINE_H,
                options,
                v_scrollbar_w,
            );
        }
        surface
    }

    /// A buffer taller than the viewport must tint the reserved
    /// rightmost `cell_width`-wide column; a buffer that fits must not.
    #[test]
    fn draw_editor_paints_vertical_scrollbar_when_buffer_overflows() {
        let bg = Theme::default().background;
        let overflowing = scroll_test_editor(50, 5);
        let surface = scroll_test_paint(&overflowing, EditorPaintOptions::default());
        // Solidly inside the reserved v-scrollbar column (x in [192, 200))
        // and mid-track vertically.
        let (r, g, b, _) = surface.pixel(198, 40);
        assert_ne!(
            (r, g, b),
            (bg.r, bg.g, bg.b),
            "vertical scrollbar track should tint this pixel when total_lines overflows the viewport"
        );

        let fits = scroll_test_editor(3, 3);
        let surface2 = scroll_test_paint(&fits, EditorPaintOptions::default());
        let (r2, g2, b2, _) = surface2.pixel(198, 40);
        assert_eq!(
            (r2, g2, b2),
            (bg.r, bg.g, bg.b),
            "no vertical scrollbar should paint when the buffer fits the viewport"
        );
    }

    /// `EditorPaintOptions::suppress_v_scrollbar` stops the macOS
    /// rasteriser from painting the column too, mirroring GTK's opt-out
    /// for a `Minimap`-as-scrollbar host.
    #[test]
    fn draw_editor_with_options_suppress_v_scrollbar_paints_no_column() {
        let bg = Theme::default().background;
        let overflowing = scroll_test_editor(50, 5);
        let surface = scroll_test_paint(
            &overflowing,
            EditorPaintOptions {
                suppress_v_scrollbar: true,
                ..Default::default()
            },
        );
        let (r, g, b, _) = surface.pixel(198, 40);
        assert_eq!(
            (r, g, b),
            (bg.r, bg.g, bg.b),
            "suppress_v_scrollbar should stop the vertical scrollbar from painting even though \
             total_lines overflows the viewport"
        );
    }

    /// A `v_scrollbar_w` override widens the painted column to a
    /// host-chosen pixel width (e.g. VS Code's fixed 14px) instead of
    /// `cell_width`. Viewport is `SCROLL_TEST_W`
    /// = 200, `SCROLL_TEST_CHAR_W` = 8.0: the default column spans
    /// `[192, 200)`; a 14px override spans `[186, 200)`. `x = 188` sits
    /// in the gap between those two spans — plain background at
    /// baseline, inside the track once widened.
    #[test]
    fn draw_editor_v_scrollbar_w_widens_painted_column() {
        let bg = Theme::default().background;
        let overflowing = scroll_test_editor(50, 5);

        let baseline = scroll_test_paint(&overflowing, EditorPaintOptions::default());
        let (r, g, b, _) = baseline.pixel(188, 40);
        assert_eq!(
            (r, g, b),
            (bg.r, bg.g, bg.b),
            "x=188 sits outside the default 8px-wide column, [192, 200)"
        );

        let widened = scroll_test_paint_with_v_scrollbar_w(
            &overflowing,
            EditorPaintOptions::default(),
            Some(14.0),
        );
        let (r2, g2, b2, _) = widened.pixel(188, 40);
        assert_ne!(
            (r2, g2, b2),
            (bg.r, bg.g, bg.b),
            "a Some(14.0) v_scrollbar_w should widen the painted track to cover x=188 ([186, 200))"
        );
    }

    /// Companion to the widened-track test: the same `v_scrollbar_w`
    /// override that widens the painted scrollbar also narrows the text
    /// clip by the same amount, so a full-line background span never
    /// bleeds into the wider reserved column. Uses a real line with a
    /// full-line background span rather than
    /// `scroll_test_editor`'s blank fixture, since clip narrowing is
    /// otherwise invisible with no content to clip.
    #[test]
    fn draw_editor_v_scrollbar_w_narrows_text_clip() {
        let mut editor = scroll_test_editor(50, 5);
        // Spaces, not glyphs: the background fill is what's under test,
        // not anti-aliased ink from a probe landing mid-stroke.
        let text = " ".repeat(40);
        editor.lines[2] = EditorLine {
            spans: vec![ESpan {
                start_byte: 0,
                end_byte: text.len(),
                style: Style {
                    fg: Color::rgb(255, 255, 255),
                    bg: Some(Color::rgb(10, 200, 10)),
                    bold: false,
                    italic: false,
                    font_scale: 1.0,
                },
            }],
            raw_text: text,
            ..blank_line(2)
        };

        // Baseline: the span's background fills right up to the default
        // 8px-wide column's left edge (x=192), covering x=188.
        let baseline = scroll_test_paint(&editor, EditorPaintOptions::default());
        let (r, g, b, _) = baseline.pixel(188, 40);
        assert_eq!(
            (r, g, b),
            (10, 200, 10),
            "baseline text clip should reach x=188 (span bg), just short of the 8px column"
        );

        // Widened: the text clip now stops 14px short of the right
        // edge, so the same pixel (188) falls outside the (shrunk) text
        // area — it reads as the scrollbar track tint instead.
        let widened = scroll_test_paint_with_v_scrollbar_w(
            &editor,
            EditorPaintOptions::default(),
            Some(14.0),
        );
        let (r2, g2, b2, _) = widened.pixel(188, 40);
        assert_ne!(
            (r2, g2, b2),
            (10, 200, 10),
            "a Some(14.0) v_scrollbar_w should narrow the text clip so x=188 no longer shows span bg"
        );
    }

    /// Paint `editor` through `MacBackend::draw_editor` after
    /// `set_editor_v_scrollbar_width(v_scrollbar_w)` — the path a host
    /// actually reaches, as opposed to calling the rasteriser directly.
    fn scroll_test_paint_via_backend(editor: &Editor, v_scrollbar_w: Option<f32>) -> BitmapSurface {
        let surface = BitmapSurface::new(SCROLL_TEST_W, SCROLL_TEST_H);
        surface.fill(0.0, 0.0, 0.0, 0.0);
        let mut backend = MacBackend::new();
        backend.set_current_font(font());
        backend.set_editor_v_scrollbar_width(v_scrollbar_w);
        backend.begin_frame(Viewport::new(
            SCROLL_TEST_W as f32,
            SCROLL_TEST_H as f32,
            1.0,
        ));
        backend.enter_frame_scope(surface.context_ptr(), |b| {
            b.draw_editor(editor.rect, editor);
        });
        backend.end_frame();
        surface
    }

    /// Core Graphics anti-aliases a fill's boundary, bleeding a level or
    /// two of track colour into the neighbouring text-area pixel, so an
    /// exact `== background` on a pixel adjacent to the column edge is
    /// not a stable assertion across hosts. The scrollbar track sits
    /// ~20 levels per channel clear of the background in every shipped
    /// theme, far outside this tolerance, so "background" and "track"
    /// stay unambiguous.
    const SCROLL_TEST_AA_TOLERANCE: i32 = 4;

    /// Whether the pixel at `(x, y)` is the editor background rather
    /// than scrollbar track, tolerant of edge anti-aliasing.
    fn scroll_test_pixel_is_bg(surface: &BitmapSurface, x: u32, y: u32) -> bool {
        let bg = Theme::default().background;
        let (r, g, b, _) = surface.pixel(x, y);
        (r as i32 - bg.r as i32).abs() <= SCROLL_TEST_AA_TOLERANCE
            && (g as i32 - bg.g as i32).abs() <= SCROLL_TEST_AA_TOLERANCE
            && (b as i32 - bg.b as i32).abs() <= SCROLL_TEST_AA_TOLERANCE
    }

    /// `Backend::set_editor_v_scrollbar_width(Some(14.0))` makes
    /// `MacBackend::draw_editor` paint a scrollbar column exactly 14px
    /// wide — `[186, 200)` in a 200px viewport — regardless of the
    /// font's own char width, and `Backend::editor_layout` reports the
    /// same column for hit-testing.
    #[test]
    fn backend_set_editor_v_scrollbar_width_paints_14px_column() {
        let overflowing = scroll_test_editor(50, 5);
        let surface = scroll_test_paint_via_backend(&overflowing, Some(14.0));
        let y = SCROLL_TEST_H - 4;
        for x in 186..SCROLL_TEST_W {
            assert!(
                !scroll_test_pixel_is_bg(&surface, x, y),
                "x={x} lies inside the 14px scrollbar column [186, 200) and should be tinted"
            );
        }
        // Three pixels clear of the column edge at x=186, so edge
        // anti-aliasing cannot reach the probe.
        assert!(
            scroll_test_pixel_is_bg(&surface, 183, y),
            "x=183 lies left of the 14px scrollbar column and should be plain background"
        );

        let mut backend = MacBackend::new();
        backend.set_current_font(font());
        backend.set_editor_v_scrollbar_width(Some(14.0));
        assert_eq!(backend.editor_v_scrollbar_width(), Some(14.0));
        let layout = backend.editor_layout(overflowing.rect, &overflowing);
        let vsb = layout.v_scrollbar_bounds.expect("buffer overflows");
        assert_eq!(vsb.width, 14.0);
        assert_eq!(vsb.x, SCROLL_TEST_W as f32 - 14.0);
    }

    /// Without `set_editor_v_scrollbar_width`, the backend path keeps a
    /// column one `char_width` wide: narrower than the 14px override, so
    /// the pixels the override would have tinted stay background.
    #[test]
    fn backend_default_editor_v_scrollbar_width_is_one_char() {
        let overflowing = scroll_test_editor(50, 5);

        // The default column is `char_width` wide, which the real font
        // supplies — derive the boundary from the backend rather than
        // assuming a glyph advance.
        let mut backend = MacBackend::new();
        backend.set_current_font(font());
        assert_eq!(backend.editor_v_scrollbar_width(), None);
        let char_w = backend.char_width();
        assert!(
            char_w > 0.0 && char_w < 14.0,
            "fixture needs a default column narrower than the 14px override, got {char_w}"
        );

        let surface = scroll_test_paint_via_backend(&overflowing, None);
        let y = SCROLL_TEST_H - 4;
        // Three pixels clear of the column's left edge, inside what the
        // 14px override would have tinted.
        let text_area_x = (SCROLL_TEST_W as f32 - char_w).floor() as u32 - 3;
        assert!(
            scroll_test_pixel_is_bg(&surface, text_area_x, y),
            "default column is {char_w}px wide, so x={text_area_x} is text-area background"
        );
        assert!(
            !scroll_test_pixel_is_bg(&surface, SCROLL_TEST_W - 2, y),
            "the default column still paints at the right edge"
        );
    }

    /// A host can hand `draw_editor` an `editor.rect` wider than the
    /// real window (e.g. a rounding/DPI mismatch upstream of this
    /// backend). `draw_editor` must still paint the scrollbar track fully
    /// inside the real viewport rather than laying it out past the right
    /// edge, where only a sliver (or nothing at all) would be visible.
    ///
    /// `editor.rect` here is 20px wider than the real 200x80 viewport
    /// `scroll_test_paint_via_backend` paints into. Without the clamp,
    /// the 14px column would land at `x = 0 + 220 - 14 = 206` —
    /// entirely outside the painted surface's `[0, 200)`. The clamp in
    /// `draw_editor` shrinks `editor.rect` back inside `self.viewport`,
    /// so the column lands at `[186, 200)` — the same span the in-bounds
    /// `_paints_14px_column` test above asserts.
    ///
    /// This only covers the paint path. `Backend::editor_layout` (the
    /// no-paint hit-test twin, `src/backend.rs`) is shared, trait-default
    /// code and is not overridden here — its own doc documents that
    /// passing it a `rect` which disagrees with what was actually
    /// painted is an uncovered caller invariant.
    #[test]
    fn backend_clamps_oversized_editor_rect_to_viewport() {
        let mut oversized = scroll_test_editor(50, 5);
        oversized.rect.width = SCROLL_TEST_W as f32 + 20.0;

        let surface = scroll_test_paint_via_backend(&oversized, Some(14.0));
        let y = SCROLL_TEST_H - 4;
        for x in 186..SCROLL_TEST_W {
            assert!(
                !scroll_test_pixel_is_bg(&surface, x, y),
                "x={x} lies inside the 14px scrollbar column [186, 200) and should be \
                 tinted — editor.rect ({}px) is wider than the real 200px viewport, so an \
                 unclamped draw_editor would have laid this column out past the window edge",
                oversized.rect.width
            );
        }
        assert!(
            scroll_test_pixel_is_bg(&surface, 183, y),
            "x=183 lies left of the 14px scrollbar column and should be plain background"
        );
    }
}