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
//! Direct2D / DirectWrite rasteriser for [`crate::primitives::editor::Editor`]
//!
//! Positions come from [`Editor::layout`] (viewport / gutter / text
//! bounds, all in the caller's `cell_width`/`line_height` — uniform
//! monospace, same convention as TUI). Text and every other paint
//! category are done in this module via [`DWrite`] + [`fill_rect`] /
//! [`crate::types::Color::blend`].
//!
//! Only compiled on `target_os = "windows"` — see `super::mod`'s
//! `#[cfg(target_os = "windows")] mod editor;` and `backend.rs`'s
//! module docs.
//!
//! Takes the live theme as a `&Theme` parameter, matching every other
//! Win-GUI rasteriser's convention — the caller
//! ([`crate::win::WinBackend::draw_editor`]) passes `&self.current_theme`,
//! the same field `Backend::set_theme` writes.
//!
//! Implements line numbers, syntax-highlighted text, cursor, selections,
//! and diagnostics. Not yet painted (pre-existing GTK/TUI features out of
//! scope): git-diff gutter column, breakpoint gutter column,
//! DAP-current-line background, fold headers, AI ghost text, inline
//! annotations, bracket-match highlight, indent guides, colorcolumns,
//! spell-check underlines, and the code-action lightbulb glyph.
//! `EditorPaintResult::cursor_position_native` is always `None` — this
//! backend paints its own caret directly (via [`fill_rect`]), the same
//! posture `GtkBackend::draw_editor`'s doc documents for GTK.
//!
//! ## Scrollbar
//!
//! This rasteriser paints no vertical scrollbar itself — it takes a raw
//! `ID2D1RenderTarget`, not a `PaintSurface`.
//! [`draw_editor_with_options_and_v_scrollbar_w`] reserves the column:
//! it lays out through [`Editor::layout_with_options_and_v_scrollbar_w`]
//! and clips text and selections to the resulting `text_bounds`, so no
//! glyph paints under the column. `WinBackend::draw_editor` then paints
//! the column through `Backend::draw_scrollbar` (the shared
//! `scrollbar::native_surface_paint`), using the same layout, with the
//! width set through [`crate::Backend::set_editor_v_scrollbar_width`].

use windows::Win32::Graphics::Direct2D::ID2D1RenderTarget;

use super::text::{fill_rect, pop_clip, push_clip, DWrite};
use crate::backend::EditorPaintResult;
use crate::event::Rect;
use crate::primitives::editor::{
    CursorShape, DiagnosticSeverity, Editor, EditorLine, EditorPaintOptions, EditorSelection,
};
use crate::theme::Theme;
use crate::types::Color;

/// Draw an [`Editor`] viewport (`editor.rect`) on `target`, at uniform
/// `cell_width` / `line_height` (DIPs).
///
/// Equivalent to [`draw_editor_with_options_and_v_scrollbar_w`] with
/// `EditorPaintOptions::default()` and no scrollbar-width override.
///
/// # Visual contract
///
/// - **Background:** `Theme::editor_active_background` when
///   `editor.show_active_bg`, else `Theme::background`.
/// - **Cursorline:** `Theme::cursorline_bg` on `is_current_line` rows
///   when `editor.is_active && editor.cursorline`.
/// - **Selections** (primary + extra + yank highlight): `Theme::selection`
///   blended over the row background at `Theme::selection_alpha` (yank
///   uses `yank_highlight_bg` / `yank_highlight_alpha`). Painted before
///   text, same ordering as `gtk::editor`.
/// - **Gutter:** right-aligned `gutter_text`, `Theme::line_number_active_fg`
///   on the current line, else `Theme::line_number_fg`.
/// - **Text:** per-[`crate::primitives::editor::EditorStyledSpan`] colour
///   (`Theme::foreground` where unset), honouring `bold`.
/// - **Diagnostics:** a 2-DIP underline under `[start_col, end_col)` in
///   `Theme::diagnostic_error` / `_warning` / `_info` / `_hint`.
/// - **Cursor:** `Theme::cursor` blended at `Theme::cursor_normal_alpha`
///   for `Block`; a solid 2-DIP bar for `Bar`; a solid 2-DIP underline
///   for `Underline`.
pub fn draw_editor(
    target: &ID2D1RenderTarget,
    dwrite: &DWrite,
    editor: &Editor,
    cell_width: f32,
    line_height: f32,
    theme: &Theme,
) -> EditorPaintResult {
    draw_editor_with_options_and_v_scrollbar_w(
        target,
        dwrite,
        editor,
        cell_width,
        line_height,
        theme,
        EditorPaintOptions::default(),
        None,
    )
}

/// [`draw_editor`], plus [`EditorPaintOptions`] and a host-settable
/// vertical scrollbar width in DIPs (`None` = one `cell_width`). Both
/// feed [`Editor::layout_with_options_and_v_scrollbar_w`], so the text
/// clip stops short of the reserved column; see the module doc's
/// "Scrollbar" section for who paints the column itself.
#[allow(clippy::too_many_arguments)]
pub fn draw_editor_with_options_and_v_scrollbar_w(
    target: &ID2D1RenderTarget,
    dwrite: &DWrite,
    editor: &Editor,
    cell_width: f32,
    line_height: f32,
    theme: &Theme,
    options: EditorPaintOptions,
    v_scrollbar_w: Option<f32>,
) -> EditorPaintResult {
    let rect = editor.rect;
    let layout = editor.layout_with_options_and_v_scrollbar_w(
        rect,
        cell_width,
        line_height,
        options,
        v_scrollbar_w,
    );

    let bg = if editor.show_active_bg {
        theme.editor_active_background
    } else {
        theme.background
    };
    let _ = fill_rect(target, rect, bg);

    // Shared by the gutter, body-text, and block-cursor-glyph paints
    // below; see [`text_v_offset`]'s doc.
    let text_v_offset = text_v_offset(dwrite, line_height);

    // ── Cursorline (spans the gutter + text columns, including the
    //    gutter — same as `gtk::editor` — but stops short of the
    //    reserved vertical scrollbar column, so it's painted before any
    //    clip is pushed but still narrowed to `text_bounds`) ──────────
    let cursorline_w = (layout.text_bounds.x + layout.text_bounds.width - rect.x).max(0.0);
    for (view_idx, line) in editor.lines.iter().enumerate() {
        if line.is_current_line && editor.is_active && editor.cursorline {
            let y = rect.y + view_idx as f32 * line_height;
            let _ = fill_rect(
                target,
                Rect::new(rect.x, y, cursorline_w, line_height),
                theme.cursorline_bg,
            );
        }
    }

    // ── Selections (painted before text) ────────────────────────────
    // Clipped to `text_bounds`: a `SelectionKind::Line` row (or any
    // selection reaching the buffer line's raw length) can be wider
    // than the visible viewport, and must not bleed past its right
    // edge — the gutter is never touched since every selection rect's
    // left edge already starts at `text_bounds.x`.
    push_clip(target, layout.text_bounds);
    if let Some(sel) = &editor.selection {
        paint_selection(
            target,
            sel,
            &editor.lines,
            rect,
            line_height,
            layout.text_bounds.x,
            cell_width,
            theme.selection,
            theme.selection_alpha,
            theme.background,
        );
    }
    for sel in &editor.extra_selections {
        paint_selection(
            target,
            sel,
            &editor.lines,
            rect,
            line_height,
            layout.text_bounds.x,
            cell_width,
            theme.selection,
            theme.selection_alpha,
            theme.background,
        );
    }
    if let Some(sel) = &editor.yank_highlight {
        paint_selection(
            target,
            sel,
            &editor.lines,
            rect,
            line_height,
            layout.text_bounds.x,
            cell_width,
            theme.yank_highlight_bg,
            theme.yank_highlight_alpha,
            theme.background,
        );
    }
    pop_clip(target);

    // ── Gutter + text + diagnostics ──────────────────────────────────
    // The gutter number paints *outside* the `text_bounds` clip below
    // (it lives at `x < text_bounds.x`); text and diagnostics paint
    // *inside* it per line, so a long line's text can't bleed into the
    // gutter or past the viewport's right edge.
    for (view_idx, line) in editor.lines.iter().enumerate() {
        let y = rect.y + view_idx as f32 * line_height;

        if editor.gutter_char_width > 0 {
            let gutter_fg = if line.is_current_line {
                theme.line_number_active_fg
            } else {
                theme.line_number_fg
            };
            let gutter_w = editor.gutter_char_width as f32 * cell_width;
            let (gw, _) = dwrite.measure_text(&line.gutter_text).unwrap_or((0.0, 0.0));
            let gx = rect.x + (gutter_w - gw).max(0.0);
            let _ = dwrite.draw_text(
                target,
                &line.gutter_text,
                Rect::new(gx, y + text_v_offset, gw, line_height),
                gutter_fg,
            );
        }

        push_clip(target, layout.text_bounds);

        paint_line_text(
            target,
            dwrite,
            line,
            layout.text_bounds.x,
            y,
            line_height,
            text_v_offset,
            cell_width,
            editor.scroll_left,
            layout.visible_cols,
            theme.foreground,
        );

        for diag in &line.diagnostics {
            let start = diag.start_col.saturating_sub(editor.scroll_left);
            let end = diag.end_col.saturating_sub(editor.scroll_left);
            if end <= start {
                continue;
            }
            let color = match diag.severity {
                DiagnosticSeverity::Error => theme.diagnostic_error,
                DiagnosticSeverity::Warning => theme.diagnostic_warning,
                DiagnosticSeverity::Information => theme.diagnostic_info,
                DiagnosticSeverity::Hint => theme.diagnostic_hint,
            };
            let ux = layout.text_bounds.x + start as f32 * cell_width;
            let uw = (end - start) as f32 * cell_width;
            let _ = fill_rect(target, Rect::new(ux, y + line_height - 2.0, uw, 2.0), color);
        }

        pop_clip(target);
    }

    // ── Cursor ───────────────────────────────────────────────────────
    if let Some(cursor) = &editor.cursor {
        let y = rect.y + cursor.pos.view_line as f32 * line_height;
        let col = cursor.pos.col.saturating_sub(editor.scroll_left);
        let x = layout.text_bounds.x + col as f32 * cell_width;
        match cursor.shape {
            CursorShape::Block => {
                let color = bg.blend(theme.cursor, theme.cursor_normal_alpha as f64);
                let _ = fill_rect(target, Rect::new(x, y, cell_width, line_height), color);
                // Re-paint the glyph under the cursor in background
                // colour so it reads against the cursor fill — mirrors
                // `macos::editor::draw_editor`'s `CursorShape::Block` arm.
                // `cursor.pos.col` indexes the raw
                // (unscrolled) buffer line, matching `CursorPos::col`'s
                // doc; the glyph is painted back at the same scrolled
                // screen `(x, y)` the block fill just used.
                if let Some(line) = editor.lines.get(cursor.pos.view_line) {
                    let raw = line.raw_text.trim_end_matches('\n');
                    if let Some(ch) = raw.chars().nth(cursor.pos.col) {
                        let ch = ch.to_string();
                        // Text, not a row-sized fill — shares the row's
                        // `text_v_offset` like the gutter and body-text
                        // paints above, so the repainted glyph still
                        // lines up with its own un-cursored baseline.
                        let _ = dwrite.draw_text(
                            target,
                            &ch,
                            Rect::new(x, y + text_v_offset, cell_width, line_height),
                            theme.background,
                        );
                    }
                }
            }
            CursorShape::Bar => {
                let _ = fill_rect(target, Rect::new(x, y, 2.0, line_height), theme.cursor);
            }
            CursorShape::Underline => {
                let _ = fill_rect(
                    target,
                    Rect::new(x, y + line_height - 2.0, cell_width, 2.0),
                    theme.cursor,
                );
            }
        }
    }

    // GTK-style posture: this backend paints its own caret directly
    // (above), so there's no terminal-cursor position for the host to
    // reposition — see this module's doc.
    EditorPaintResult::default()
}

/// Vertical distance from a row's top edge to the top of the glyph box
/// that centres `dwrite`'s own natural line height inside `line_height`
/// — Win-GUI's counterpart to [`crate::macos::editor::text_v_offset`].
///
/// A host sets the editor's row pitch (`line_height`) independently of
/// the font's natural height (`DWrite::natural_line_height`, `ascent +
/// descent + lineGap` at this handle's size); DirectWrite's default
/// paragraph alignment is top (`DWRITE_PARAGRAPH_ALIGNMENT_NEAR`), so a
/// glyph box positioned straight at a row's top edge 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, matching VS Code.
///
/// 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 — same
/// unclamped posture as the macOS twin.
fn text_v_offset(dwrite: &DWrite, line_height: f32) -> f32 {
    (line_height - dwrite.natural_line_height()) / 2.0
}

/// Paint one selection range as a translucent overlay across the
/// visible `lines`, before text is painted. Column math — including
/// `SelectionKind::Block` vs `Char` distinctness, wrapped-segment
/// offsetting, and ghost-continuation / diff-padding row skipping —
/// comes from [`EditorSelection::cols_on`]; this function only
/// converts the returned segment-local columns to a fixed-cell-width
/// pixel rectangle (mirrors `tui::editor::render_selection`'s per-cell
/// approach rather than GTK/macOS's proportional text measurement,
/// since Win paints a uniform monospace grid same as TUI).
#[allow(clippy::too_many_arguments)]
fn paint_selection(
    target: &ID2D1RenderTarget,
    sel: &EditorSelection,
    lines: &[EditorLine],
    rect: Rect,
    line_height: f32,
    text_x: f32,
    cell_width: f32,
    color: Color,
    alpha: f32,
    bg: Color,
) {
    for (view_idx, line) in lines.iter().enumerate() {
        let Some(cols) = sel.cols_on(line) else {
            continue;
        };
        let y = rect.y + view_idx as f32 * line_height;
        let x = text_x + cols.start as f32 * cell_width;
        let w = (cols.end - cols.start) as f32 * cell_width;
        let blended = bg.blend(color, alpha as f64);
        let _ = fill_rect(target, Rect::new(x, y, w, line_height), blended);
    }
}

/// Paint `line`'s visible text window (`[scroll_left, scroll_left +
/// visible_cols)` characters) at `y`, splitting into contiguous runs by
/// [`crate::primitives::editor::EditorStyledSpan`] colour.
///
/// `text_v_offset` ([`text_v_offset`]) nudges every run's glyph box down
/// from `y` so it centres in `line_height` rather than sitting at the
/// row's raw top edge.
#[allow(clippy::too_many_arguments)]
fn paint_line_text(
    target: &ID2D1RenderTarget,
    dwrite: &DWrite,
    line: &EditorLine,
    text_x: f32,
    y: f32,
    line_height: f32,
    text_v_offset: f32,
    cell_width: f32,
    scroll_left: usize,
    visible_cols: usize,
    default_fg: Color,
) {
    let raw = line.raw_text.trim_end_matches('\n');
    let chars: Vec<(usize, char)> = raw.char_indices().collect();
    if chars.len() <= scroll_left {
        return;
    }
    let end = (scroll_left + visible_cols).min(chars.len());
    if end <= scroll_left {
        return;
    }

    // Resolve a colour + bold flag per visible character from
    // byte-range spans, then coalesce into runs so each DirectWrite
    // call paints a contiguous same-style substring.
    let style_at = |byte_off: usize| -> (Color, bool) {
        for span in &line.spans {
            if byte_off >= span.start_byte && byte_off < span.end_byte {
                return (span.style.fg, span.style.bold);
            }
        }
        (default_fg, false)
    };

    let mut run_start = scroll_left;
    let mut run_style = style_at(chars[scroll_left].0);
    let mut cursor_x = text_x;

    let flush = |from: usize, to: usize, style: (Color, bool), cursor_x: &mut f32| {
        if to <= from {
            return;
        }
        let start_byte = chars[from].0;
        let end_byte = chars.get(to).map(|(b, _)| *b).unwrap_or(raw.len());
        let text = &raw[start_byte..end_byte];
        let w = (to - from) as f32 * cell_width;
        let (_, h) = dwrite.measure_text(text).unwrap_or((0.0, line_height));
        let _ = dwrite.draw_text_styled(
            target,
            text,
            Rect::new(*cursor_x, y + text_v_offset, w, h.max(line_height)),
            style.0,
            style.1,
        );
        *cursor_x += w;
    };

    // Iterate the slice rather than the index range (`clippy::
    // needless_range_loop`, an error under CI's `-D warnings` and only
    // visible on the windows-latest leg): `skip`/`take` reproduce the
    // half-open `(scroll_left + 1)..end` window, and `enumerate` still
    // yields the absolute index the run bookkeeping needs.
    for (i, (byte_off, _)) in chars.iter().enumerate().take(end).skip(scroll_left + 1) {
        let s = style_at(*byte_off);
        if s != run_style {
            flush(run_start, i, run_style, &mut cursor_x);
            run_start = i;
            run_style = s;
        }
    }
    flush(run_start, end, run_style, &mut cursor_x);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::event::Rect as QRect;
    use crate::primitives::editor::{
        CursorPos, DiagnosticMark, DiffLine, EditorCursor, EditorStyledSpan, SelectionKind, Style,
    };
    use crate::types::WidgetId;
    use crate::win::testing::HeadlessSurface;

    const CELL_W: f32 = 8.0;
    const LINE_H: f32 = 16.0;

    fn plain_line(idx: usize, text: &str) -> EditorLine {
        EditorLine {
            raw_text: text.to_string(),
            gutter_text: format!("{:>3}", idx + 1),
            spans: vec![EditorStyledSpan {
                start_byte: 0,
                end_byte: text.len(),
                style: Style {
                    fg: Color::rgb(200, 200, 200),
                    bg: None,
                    bold: false,
                    italic: false,
                    font_scale: 1.0,
                },
            }],
            line_idx: idx,
            is_current_line: false,
            is_fold_header: false,
            folded_line_count: 0,
            git_diff: None,
            diff_status: None,
            diagnostics: Vec::new(),
            spell_errors: Vec::new(),
            is_breakpoint: false,
            is_conditional_bp: false,
            is_dap_current: false,
            is_wrap_continuation: false,
            segment_col_offset: 0,
            annotation: None,
            ghost_suffix: None,
            is_ghost_continuation: false,
            indent_guides: Vec::new(),
            colorcolumns: Vec::new(),
        }
    }

    fn editor(lines: Vec<EditorLine>) -> Editor {
        Editor {
            id: WidgetId::new("editor"),
            rect: QRect::new(0.0, 0.0, 200.0, 100.0),
            lines,
            cursor: None,
            extra_cursors: Vec::new(),
            selection: None,
            extra_selections: Vec::new(),
            yank_highlight: None,
            scroll_top: 0,
            scroll_left: 0,
            total_lines: 3,
            max_col: 20,
            gutter_char_width: 4,
            is_active: true,
            show_active_bg: false,
            has_git_diff: false,
            has_breakpoints: false,
            diagnostic_gutter: Default::default(),
            code_action_lines: Default::default(),
            bracket_match_positions: Vec::new(),
            active_indent_col: None,
            tabstop: 4,
            cursorline: true,
            lightbulb_glyph: '!',
        }
    }

    /// The `v_scrollbar_w` override narrows `text_bounds` by exactly
    /// its delta from `cell_width` — the layout
    /// `draw_editor_with_options_and_v_scrollbar_w` clips text to. Pure
    /// layout, no `HeadlessSurface`/`DWrite` needed.
    #[test]
    fn v_scrollbar_w_option_narrows_text_bounds() {
        let mut e = editor(vec![plain_line(0, "line one")]);
        e.total_lines = 50; // overflow: far more than the viewport's rows
        let rect = e.rect;

        let baseline = e.layout(rect, CELL_W, LINE_H);
        let baseline_vsb = baseline
            .v_scrollbar_bounds
            .expect("overflowing buffer reserves a vertical scrollbar column");
        assert_eq!(baseline_vsb.width, CELL_W);

        let widened = e.layout_with_options_and_v_scrollbar_w(
            rect,
            CELL_W,
            LINE_H,
            EditorPaintOptions::default(),
            Some(14.0),
        );
        let widened_vsb = widened
            .v_scrollbar_bounds
            .expect("still overflowing with the override applied");
        assert_eq!(widened_vsb.width, 14.0);
        assert_eq!(
            widened.text_bounds.width,
            baseline.text_bounds.width - (14.0 - CELL_W)
        );
    }

    /// Painting must not panic across a mix of plain lines, a cursor, a
    /// selection, and a diagnostic underline, and the gutter's line
    /// number must be visible pixels distinct from the background.
    #[test]
    fn paints_without_panicking_and_gutter_is_visible() {
        let surface = HeadlessSurface::new(200, 100).expect("create surface");
        let (dwrite, _, _) = DWrite::new("Consolas", 10.0, None).expect("create DWrite");
        let mut lines = vec![
            plain_line(0, "fn main() {"),
            plain_line(1, "    ok();"),
            plain_line(2, "}"),
        ];
        lines[0].is_current_line = true;
        lines[1].diagnostics.push(DiagnosticMark {
            start_col: 4,
            end_col: 6,
            severity: DiagnosticSeverity::Error,
            message: "unused".into(),
        });
        let mut e = editor(lines);
        e.cursor = Some(EditorCursor {
            pos: CursorPos {
                view_line: 0,
                col: 3,
            },
            shape: CursorShape::Bar,
        });
        e.selection = Some(EditorSelection {
            kind: SelectionKind::Char,
            start_line: 1,
            start_col: 0,
            end_line: 1,
            end_col: 4,
        });

        surface
            .paint(|target| {
                draw_editor(target, &dwrite, &e, CELL_W, LINE_H, &Theme::default());
            })
            .expect("paint editor");

        let theme = Theme::default();
        // Current-line gutter number is painted in `line_number_active_fg`,
        // distinct from the plain background. Scan the whole gutter
        // column (0..gutter width, the full first row's height) rather
        // than a guessed glyph position — real DirectWrite glyph
        // placement within that box isn't known ahead of a real
        // Windows font metrics pass.
        let gutter_w = (4.0 * CELL_W) as u32;
        let found = (0..gutter_w).any(|x| {
            (0..LINE_H as u32).any(|y| {
                let px = surface.pixel_at(x, y);
                (px.r, px.g, px.b)
                    == (
                        theme.line_number_active_fg.r,
                        theme.line_number_active_fg.g,
                        theme.line_number_active_fg.b,
                    )
            })
        });
        assert!(
            found,
            "current line's gutter number should paint line_number_active_fg somewhere in the gutter column"
        );
    }

    /// A `Line`-kind selection covers the full row width regardless of
    /// `start_col`/`end_col`.
    #[test]
    fn line_selection_spans_full_row() {
        let surface = HeadlessSurface::new(200, 100).expect("create surface");
        let (dwrite, _, _) = DWrite::new("Consolas", 10.0, None).expect("create DWrite");
        // 2 visible characters + 23 trailing spaces: `line_len` (25,
        // matching the selection's full-row width) is unaffected by the
        // trailing spaces, but space glyphs paint no ink — so the
        // sample point below lands on pure selection-tint background,
        // not real DirectWrite glyph rendering this test has no way to
        // predict pixel-for-pixel without a live Windows font pass.
        let text = format!("ab{}", " ".repeat(23));
        let lines = vec![plain_line(0, &text)];
        let mut e = editor(lines);
        e.selection = Some(EditorSelection {
            kind: SelectionKind::Line,
            start_line: 0,
            start_col: 2,
            end_line: 0,
            end_col: 3,
        });

        surface
            .paint(|target| {
                draw_editor(target, &dwrite, &e, CELL_W, LINE_H, &Theme::default());
            })
            .expect("paint editor");

        let theme = Theme::default();
        let text_x = (e.gutter_char_width as f32 * CELL_W) as u32;
        // Sample near the right edge of the viewport, well past
        // `end_col`'s column — a `Line` selection should still cover it.
        let sample_x = 180u32.max(text_x + 5);
        let px = surface.pixel_at(sample_x, 4);
        let expected = theme
            .background
            .blend(theme.selection, theme.selection_alpha as f64);
        assert_eq!((px.r, px.g, px.b), (expected.r, expected.g, expected.b));
    }

    /// `EditorSelection::cols_on` (shared with every other backend) correctly
    /// computes selection columns, accounting for wrapped ghosts, padding rows,
    /// and segment offsets. This proves it through a real Direct2D paint.
    #[test]
    fn selection_respects_wrapped_ghost_and_diff_padding_rows() {
        let surface = HeadlessSurface::new(200, 100).expect("create surface");
        let (dwrite, _, _) = DWrite::new("Consolas", 10.0, None).expect("create DWrite");

        let lines = vec![
            // Row 0: buffer line 0, plain, selection's own start line.
            // Visible glyphs only in the first two columns, spaces after
            // — the sample column below lands on inkless space cells so
            // the pixel is pure selection tint, not DirectWrite glyph
            // antialiasing (same trick as `line_selection_spans_full_row`).
            plain_line(0, &format!("01{}", " ".repeat(8))),
            // Row 1: a wrap-continuation segment of buffer line 1,
            // starting at buffer column 5 — its own text (10 chars,
            // same glyph-then-spaces shape) is entirely inside the
            // selection.
            EditorLine {
                segment_col_offset: 5,
                is_wrap_continuation: true,
                ..plain_line(1, &format!("ab{}", " ".repeat(8)))
            },
            // Row 2: the AI-ghost continuation of buffer line 1 — same
            // `line_idx` as row 1, but virtual, must never be selected.
            EditorLine {
                is_ghost_continuation: true,
                ghost_suffix: Some("ai suggestion".into()),
                ..plain_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),
                ..plain_line(2, "")
            },
        ];
        let mut e = editor(lines);
        e.total_lines = 4;
        e.selection = Some(EditorSelection {
            kind: SelectionKind::Char,
            start_line: 0,
            start_col: 0,
            end_line: 2,
            end_col: 10,
        });

        surface
            .paint(|target| {
                draw_editor(target, &dwrite, &e, CELL_W, LINE_H, &Theme::default());
            })
            .expect("paint editor");

        let theme = Theme::default();
        let blended = theme
            .background
            .blend(theme.selection, theme.selection_alpha as f64);
        let text_x = (e.gutter_char_width as f32 * CELL_W) as i32;
        // Middle of column 5: past the two visible glyphs, inside
        // every tinted row's selected range.
        let sample_x = (text_x as f32 + 5.0 * CELL_W + CELL_W / 2.0) as u32;
        let row_y = |row: i32| (row as f32 * LINE_H + LINE_H / 2.0) as u32;

        let row0 = surface.pixel_at(sample_x, row_y(0));
        assert_eq!(
            (row0.r, row0.g, row0.b),
            (blended.r, blended.g, blended.b),
            "row 0 (plain, selection's start line) should be tinted"
        );
        let row1 = surface.pixel_at(sample_x, row_y(1));
        assert_eq!(
            (row1.r, row1.g, row1.b),
            (blended.r, blended.g, blended.b),
            "row 1 (wrapped segment of a fully-selected line) should be tinted"
        );
        let row2 = surface.pixel_at(sample_x, row_y(2));
        assert_eq!(
            (row2.r, row2.g, row2.b),
            (theme.background.r, theme.background.g, theme.background.b),
            "row 2 (ghost continuation) must never be tinted by a selection"
        );
        let row3 = surface.pixel_at(sample_x, row_y(3));
        assert_eq!(
            (row3.r, row3.g, row3.b),
            (theme.background.r, theme.background.g, theme.background.b),
            "row 3 (diff padding) must never be tinted by a selection"
        );
    }

    /// `CursorShape::Block` opaquely covers the character with a filled rect,
    /// so the arm must re-paint the glyph on top in `theme.background`,
    /// mirroring `macos::editor::draw_editor`'s own `CursorShape::Block` arm.
    /// This test scans the cursor cell for any pixel that reads
    /// `theme.background` rather than guessing exact glyph ink placement —
    /// real DirectWrite glyph positioning isn't predictable off a live Windows
    /// font pass. Before the fix, `CursorShape::Block` fills the whole cell
    /// with a single opaque `theme.cursor`-blended colour.
    #[test]
    fn block_cursor_repaints_glyph_in_background_colour() {
        let surface = HeadlessSurface::new(200, 100).expect("create surface");
        let (dwrite, _, _) = DWrite::new("Consolas", 10.0, None).expect("create DWrite");
        let lines = vec![plain_line(0, "1789518172522")];
        let mut e = editor(lines);
        e.cursor = Some(EditorCursor {
            pos: CursorPos {
                view_line: 0,
                col: 0,
            },
            shape: CursorShape::Block,
        });

        surface
            .paint(|target| {
                draw_editor(target, &dwrite, &e, CELL_W, LINE_H, &Theme::default());
            })
            .expect("paint editor");

        let theme = Theme::default();
        let text_x = (e.gutter_char_width as f32 * CELL_W) as u32;
        let found = (text_x..text_x + CELL_W as u32).any(|x| {
            (0..LINE_H as u32).any(|y| {
                let px = surface.pixel_at(x, y);
                (px.r, px.g, px.b) == (theme.background.r, theme.background.g, theme.background.b)
            })
        });
        assert!(
            found,
            "block cursor should re-paint the covered glyph in \
             theme.background somewhere inside the cursor cell (col 0, \
             row 0) — got no such pixel, cursor fill likely still hides \
             the glyph entirely"
        );
    }

    /// The editor's row pitch is a host decision independent of
    /// `dwrite`'s own natural line height — mirrors
    /// `macos::editor::tests::body_text_centred_in_row_and_shares_baseline_with_gutter`
    /// and `gtk::editor::tests::draw_editor_body_text_centred_in_row_and_shares_baseline_with_gutter`:
    /// widening the pitch from the font's natural height to a VS
    /// Code-style wider row should move the body glyph's ink down by
    /// half the added slack, and the gutter number (same glyph, `"7"`)
    /// should land on the same rows as the body text once widened.
    #[test]
    fn body_text_centred_in_row_and_shares_baseline_with_gutter() {
        let (dwrite, natural_line_height, _) =
            DWrite::new("Consolas", 10.0, None).expect("create DWrite");
        const ROW_PITCH: f32 = 24.0;
        assert!(
            natural_line_height < ROW_PITCH,
            "fixture needs a font natural line height ({natural_line_height}) shorter than \
             the row pitch ({ROW_PITCH}) to leave any slack to centre in",
        );

        let gutter_chars = 2usize;
        let gutter_w = gutter_chars as f32 * CELL_W;
        let theme = Theme::default();

        let paint_at_pitch = |pitch: f32| -> HeadlessSurface {
            let surface =
                HeadlessSurface::new(200, pitch.ceil() as u32 + 8).expect("create surface");
            let mut line = plain_line(0, "7");
            line.gutter_text = "7".into();
            let mut e = editor(vec![line]);
            e.gutter_char_width = gutter_chars;
            e.rect = QRect::new(0.0, 0.0, 200.0, pitch + 8.0);
            surface
                .paint(|target| {
                    draw_editor(target, &dwrite, &e, CELL_W, pitch, &theme);
                })
                .expect("paint editor");
            surface
        };

        // Scan `surface` for the vertical extent of non-background ink
        // inside `[x_start, x_end) × [0, y_end)` — Win-GUI's counterpart
        // to the macOS/GTK twins' identically-named test helpers.
        let ink_extent = |surface: &HeadlessSurface, x_start: u32, x_end: u32, y_end: u32| {
            const TOL: i32 = 24;
            let mut extent: Option<(u32, u32)> = None;
            for y in 0..y_end {
                let has_ink = (x_start..x_end).any(|x| {
                    let px = surface.pixel_at(x, y);
                    (px.r as i32 - theme.background.r as i32).abs() > TOL
                        || (px.g as i32 - theme.background.g as i32).abs() > TOL
                        || (px.b as i32 - theme.background.b as i32).abs() > TOL
                });
                if has_ink {
                    extent = Some(match extent {
                        Some((top, _)) => (top, y),
                        None => (y, y),
                    });
                }
            }
            extent
        };

        let natural_surface = paint_at_pitch(natural_line_height);
        let natural = ink_extent(
            &natural_surface,
            gutter_w.round() as u32,
            (gutter_w + CELL_W).round() as u32,
            natural_line_height.ceil() as u32 + 8,
        )
        .expect("body glyph should paint some ink at the natural pitch");

        let wide_surface = paint_at_pitch(ROW_PITCH);
        let wide = ink_extent(
            &wide_surface,
            gutter_w.round() as u32,
            (gutter_w + CELL_W).round() as u32,
            ROW_PITCH as u32 + 8,
        )
        .expect("body glyph should paint some ink at the wide pitch");

        let expected_shift = (ROW_PITCH - natural_line_height) / 2.0;
        let top_shift = wide.0 as f32 - natural.0 as f32;
        let bottom_shift = wide.1 as f32 - natural.1 as f32;
        assert!(
            (top_shift - expected_shift).abs() <= 2.0
                && (bottom_shift - expected_shift).abs() <= 2.0,
            "widening the row pitch from {natural_line_height} 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_extent(
            &wide_surface,
            0,
            gutter_w.round() as u32,
            ROW_PITCH as u32 + 8,
        )
        .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:?}"
        );
    }
}