quadraui 0.6.0

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
//! GTK rasteriser for [`crate::DataTable`].
//!
//! Renders column headers with Pango-measured text and sort indicators,
//! then body rows with per-cell text aligned within resolved column
//! bounds. Uses Pango for measurement and Cairo for painting.

use gtk4::cairo::Context;
use gtk4::pango;

use super::{cairo_rgb, set_source};
use crate::primitives::data_table::{ColumnAlign, DataTable, DataTableLayout, SortDirection};
use crate::primitives::layout_metrics::pixel_data_table_layout;
use crate::theme::Theme;

/// Horizontal gap between a sorted column's title and its codicon
/// sort-direction glyph.
const SORT_GAP: f64 = 4.0;

/// Draw a `DataTable` onto `cr`. Returns the layout used for painting.
#[allow(clippy::too_many_arguments)]
pub fn draw_data_table(
    cr: &Context,
    pango_layout: &pango::Layout,
    x: f64,
    y: f64,
    width: f64,
    height: f64,
    table: &DataTable,
    theme: &Theme,
    line_height: f64,
    hovered_idx: Option<usize>,
) -> DataTableLayout {
    draw_data_table_with_glyphs(
        cr,
        pango_layout,
        x,
        y,
        width,
        height,
        table,
        theme,
        line_height,
        hovered_idx,
        None,
        false,
    )
}

/// Identical to [`draw_data_table`], plus an optional
/// [`crate::primitives::data_table::DataTableGlyphs`] override for the
/// header's sort-direction glyph and the `nerd_fonts_enabled` flag (see
/// [`crate::Backend::nerd_fonts_enabled`]) that selects each override
/// [`crate::primitives::Icon`]'s `glyph` vs. `fallback` form. `glyphs: None`
/// (what [`draw_data_table`] passes) renders byte-for-byte the same as
/// today's codicon defaults.
#[allow(clippy::too_many_arguments)]
pub fn draw_data_table_with_glyphs(
    cr: &Context,
    pango_layout: &pango::Layout,
    x: f64,
    y: f64,
    width: f64,
    height: f64,
    table: &DataTable,
    theme: &Theme,
    line_height: f64,
    hovered_idx: Option<usize>,
    glyphs: Option<&crate::primitives::data_table::DataTableGlyphs>,
    nerd_fonts_enabled: bool,
) -> DataTableLayout {
    pango_layout.set_attributes(None);
    let measure = super::toolbar::PangoMeasure {
        pango_layout: Some(pango_layout),
        char_width: 0.0,
    };
    let layout = pixel_data_table_layout(
        table,
        width as f32,
        height as f32,
        line_height as f32,
        &measure,
    );
    let header_height = layout.header_height as f64;

    if width <= 0.0 || height <= 0.0 {
        return layout;
    }

    cr.save().ok();
    cr.rectangle(x, y, width, height);
    cr.clip();

    // ── Header background ─────────────────────────────────────────────
    let (hbr, hbg, hbb) = cairo_rgb(theme.tab_bar_bg);
    cr.set_source_rgb(hbr, hbg, hbb);
    cr.rectangle(x, y, width, header_height);
    cr.fill().ok();

    // ── Header text ───────────────────────────────────────────────────
    let h_off = table.h_scroll as f64;
    set_source(cr, theme.foreground);
    let bold_attrs = pango::AttrList::new();
    bold_attrs.insert(pango::AttrInt::new_weight(pango::Weight::Bold));

    // The sort indicator is a codicon glyph, not a plain `â–²`/`â–¼`
    // baked into the title string — it needs its own
    // codicon-fallback-wrapped `FontDescription` (the bold-weight
    // `AttrList` above is orthogonal: an `AttrList` restyles whatever
    // family is already on `pango_layout`, it cannot add a fallback
    // family), so title and glyph are measured and painted as two runs
    // instead of one concatenated string.
    let base_font = pango_layout.font_description().unwrap_or_default();
    let mut bold_icon_font = base_font.clone();
    bold_icon_font.set_weight(pango::Weight::Bold);
    let bold_icon_font = super::with_nerd_font_fallback(&bold_icon_font);

    // Resolved once, outside the per-column loop below — these two
    // values are constant across the whole header row.
    let sort_ascending_glyph: std::borrow::Cow<'_, str> = glyphs
        .and_then(crate::primitives::data_table::DataTableGlyphs::sort_ascending_glyph)
        .map(|icon| std::borrow::Cow::Borrowed(icon.resolve(nerd_fonts_enabled)))
        .unwrap_or(std::borrow::Cow::Owned(
            crate::codicon::SORT_ASCENDING.to_string(),
        ));
    let sort_descending_glyph: std::borrow::Cow<'_, str> = glyphs
        .and_then(crate::primitives::data_table::DataTableGlyphs::sort_descending_glyph)
        .map(|icon| std::borrow::Cow::Borrowed(icon.resolve(nerd_fonts_enabled)))
        .unwrap_or(std::borrow::Cow::Owned(
            crate::codicon::SORT_DESCENDING.to_string(),
        ));

    for (col_idx, rc) in layout.columns.iter().enumerate() {
        if col_idx >= table.columns.len() || rc.width <= 0.0 {
            break;
        }
        let col = &table.columns[col_idx];
        let sort_glyph: Option<&str> = match &table.sort {
            Some((si, dir)) if *si == col_idx => Some(match dir {
                SortDirection::Ascending => sort_ascending_glyph.as_ref(),
                SortDirection::Descending => sort_descending_glyph.as_ref(),
            }),
            _ => None,
        };

        pango_layout.set_font_description(Some(&base_font));
        pango_layout.set_text(&col.title);
        pango_layout.set_attributes(Some(&bold_attrs));
        let (title_w, _) = pango_layout.pixel_size();

        let sort_glyph_str = sort_glyph.map(|g| g.to_string());
        let sort_w = if let Some(ref g) = sort_glyph_str {
            pango_layout.set_font_description(Some(&bold_icon_font));
            pango_layout.set_attributes(None);
            pango_layout.set_text(g);
            pango_layout.pixel_size().0 as f64
        } else {
            0.0
        };
        let text_w = title_w as f64
            + if sort_glyph_str.is_some() {
                SORT_GAP + sort_w
            } else {
                0.0
            };

        let col_x = x + rc.x as f64 - h_off;
        let col_w = rc.width as f64;

        cr.save().ok();
        cr.rectangle(col_x, y, col_w, header_height);
        cr.clip();

        let text_x = match col.align {
            ColumnAlign::Left => col_x,
            ColumnAlign::Center => col_x + (col_w - text_w) / 2.0,
            ColumnAlign::Right => col_x + col_w - text_w,
        };

        pango_layout.set_font_description(Some(&base_font));
        pango_layout.set_attributes(Some(&bold_attrs));
        pango_layout.set_text(&col.title);
        cr.move_to(text_x, y);
        super::painted_text::show_layout(cr, pango_layout);

        if let Some(ref g) = sort_glyph_str {
            pango_layout.set_font_description(Some(&bold_icon_font));
            pango_layout.set_attributes(None);
            pango_layout.set_text(g);
            cr.move_to(text_x + title_w as f64 + SORT_GAP, y);
            super::painted_text::show_layout(cr, pango_layout);
        }

        cr.restore().ok();
    }
    pango_layout.set_font_description(Some(&base_font));
    pango_layout.set_attributes(None);

    // ── Header column separators ──────────────────────────────────────
    set_source(cr, theme.separator);
    for (col_idx, rc) in layout.columns.iter().enumerate() {
        if col_idx + 1 >= layout.columns.len() {
            break;
        }
        let sep_x = x + (rc.x + rc.width) as f64 - h_off;
        cr.rectangle(sep_x - 0.5, y, 1.0, header_height);
        cr.fill().ok();
    }

    // ── Body rows ─────────────────────────────────────────────────────
    let body_y = y + header_height;
    let visible = layout
        .visible_rows
        .min(table.rows.len().saturating_sub(table.scroll_offset));

    for row_idx in 0..visible {
        let abs_idx = table.scroll_offset + row_idx;
        let row = &table.rows[abs_idx];
        let row_y = body_y + row_idx as f64 * line_height;
        let is_selected = table.selected_idx == Some(abs_idx);
        let is_hovered = hovered_idx == Some(abs_idx) && !is_selected;

        if is_selected {
            let (sr, sg, sb) = cairo_rgb(theme.selection_bg);
            cr.set_source_rgba(sr, sg, sb, theme.selection_alpha as f64);
            cr.rectangle(x, row_y, width, line_height);
            cr.fill().ok();
        } else if is_hovered {
            let (hr, hg, hb) = cairo_rgb(theme.tab_bar_bg);
            cr.set_source_rgba(hr, hg, hb, 0.5);
            cr.rectangle(x, row_y, width, line_height);
            cr.fill().ok();
        }

        for (col_idx, rc) in layout.columns.iter().enumerate() {
            let styled = match row.cells.get(col_idx) {
                Some(c) if !c.spans.is_empty() => c,
                _ => continue,
            };
            if rc.width <= 0.0 {
                continue;
            }

            let col_w = rc.width as f64;
            let col_x = x + rc.x as f64 - h_off;
            let is_muted = row.decoration == crate::types::Decoration::Muted;

            cr.save().ok();
            cr.rectangle(col_x, row_y, col_w, line_height);
            cr.clip();

            let full_text: String = styled.spans.iter().map(|s| s.text.as_str()).collect();
            pango_layout.set_text(&full_text);
            pango_layout.set_attributes(None);
            let (text_w, _) = pango_layout.pixel_size();

            let align = table
                .columns
                .get(col_idx)
                .map(|c| c.align)
                .unwrap_or(ColumnAlign::Left);
            let text_x = match align {
                ColumnAlign::Left => col_x,
                ColumnAlign::Center => col_x + (col_w - text_w as f64) / 2.0,
                ColumnAlign::Right => col_x + col_w - text_w as f64,
            };

            // Per-span colored text via Pango attributes.
            let attrs = pango::AttrList::new();
            let mut byte_offset = 0u32;
            for span in &styled.spans {
                let span_bytes = span.text.len() as u32;
                if !is_muted {
                    if let Some(fg) = span.fg {
                        let mut color_attr = pango::AttrColor::new_foreground(
                            fg.r as u16 * 257,
                            fg.g as u16 * 257,
                            fg.b as u16 * 257,
                        );
                        color_attr.set_start_index(byte_offset);
                        color_attr.set_end_index(byte_offset + span_bytes);
                        attrs.insert(color_attr);
                    }
                }
                byte_offset += span_bytes;
            }
            if is_muted {
                set_source(cr, theme.muted_fg);
            } else {
                set_source(cr, theme.foreground);
            }
            pango_layout.set_attributes(Some(&attrs));
            cr.move_to(text_x, row_y);
            super::painted_text::show_layout(cr, pango_layout);
            pango_layout.set_attributes(None);
            cr.restore().ok();
        }

        // Body column separators — drawn after the cell text (not clipped
        // to a per-column rect the way the text is) so a cell whose text
        // exactly fills its column never paints over the divider.
        set_source(cr, theme.separator);
        for (col_idx, rc) in layout.columns.iter().enumerate() {
            if col_idx + 1 >= layout.columns.len() || rc.width <= 0.0 {
                continue;
            }
            let sep_x = x + (rc.x + rc.width) as f64 - h_off;
            cr.rectangle(sep_x - 0.5, row_y, 1.0, line_height);
            cr.fill().ok();
        }
    }

    // ── Scrollbar ──────────────────────────────────────────────────────
    let footer_h = layout.footer_height as f64;
    if table.show_scrollbar
        && table.rows.len() > layout.visible_rows
        && layout.scrollbar_width > 0.0
    {
        let sb_x = x + width - layout.scrollbar_width as f64;
        let sb_track = crate::event::Rect::new(
            sb_x as f32,
            (y + header_height) as f32,
            layout.scrollbar_width,
            (height - header_height - footer_h).max(0.0) as f32,
        );
        let sb = crate::primitives::scrollbar::Scrollbar::vertical(
            table.id,
            sb_track,
            table.scroll_offset as f32,
            table.rows.len() as f32,
            layout.visible_rows as f32,
            line_height as f32,
        );
        let mut raw = super::surface::CairoSurface {
            cr,
            layout: None,
            translucent_fill: true,
        };
        crate::primitives::scrollbar::native_surface_paint::paint(&sb, &mut raw, theme);
    }

    // ── Horizontal scrollbar ─────────────────────────────────────────
    if layout.h_scrollbar_height > 0.0 && layout.content_width > 0.0 {
        let hsb_y = y + height - footer_h - layout.h_scrollbar_height as f64;
        let track_w = (width - layout.scrollbar_width as f64).max(1.0);
        let hsb_track = crate::event::Rect::new(
            x as f32,
            hsb_y as f32,
            track_w as f32,
            layout.h_scrollbar_height,
        );
        let visible_w = track_w as f32;
        let hsb = crate::primitives::scrollbar::Scrollbar::horizontal(
            table.id,
            hsb_track,
            table.h_scroll,
            layout.content_width,
            visible_w,
            line_height as f32,
        );
        let mut raw = super::surface::CairoSurface {
            cr,
            layout: None,
            translucent_fill: true,
        };
        crate::primitives::scrollbar::native_surface_paint::paint(&hsb, &mut raw, theme);
    }

    // ── Footer (pinned summary row) ─────────────────────────────────
    if let Some(footer) = &table.footer {
        if footer_h > 0.0 {
            // `footer_h` reserves `line_height * 2.0` (see
            // `DataTable::layout`): a divider row plus the content
            // row. Fill the whole band, but keep text in the bottom
            // `line_height` sub-band so it sits flush with the
            // viewport edge, matching the TUI rasteriser.
            let footer_band_top = y + height - footer_h;
            let footer_y = y + height - line_height;

            // Divider rule at the top of the reserved footer band.
            set_source(cr, theme.separator);
            cr.rectangle(x, footer_band_top - 0.5, width, 1.0);
            cr.fill().ok();

            let (fbr, fbg, fbb) = cairo_rgb(theme.tab_bar_bg);
            cr.set_source_rgb(fbr, fbg, fbb);
            cr.rectangle(x, footer_band_top, width, footer_h);
            cr.fill().ok();

            for (col_idx, rc) in layout.columns.iter().enumerate() {
                let styled = match footer.cells.get(col_idx) {
                    Some(c) if !c.spans.is_empty() => c,
                    _ => continue,
                };
                if rc.width <= 0.0 {
                    continue;
                }

                let col_w = rc.width as f64;
                let col_x = x + rc.x as f64 - h_off;

                cr.save().ok();
                cr.rectangle(col_x, footer_y, col_w, line_height);
                cr.clip();

                let full_text: String = styled.spans.iter().map(|s| s.text.as_str()).collect();
                pango_layout.set_text(&full_text);
                pango_layout.set_attributes(Some(&bold_attrs));
                let (text_w, _) = pango_layout.pixel_size();

                let align = table
                    .columns
                    .get(col_idx)
                    .map(|c| c.align)
                    .unwrap_or(ColumnAlign::Left);
                let text_x = match align {
                    ColumnAlign::Left => col_x,
                    ColumnAlign::Center => col_x + (col_w - text_w as f64) / 2.0,
                    ColumnAlign::Right => col_x + col_w - text_w as f64,
                };

                // Bold weight for the whole cell (subtle style hook that
                // separates the footer from body rows), plus per-span
                // colour overrides.
                let attrs = pango::AttrList::new();
                attrs.insert(pango::AttrInt::new_weight(pango::Weight::Bold));
                let mut byte_offset = 0u32;
                for span in &styled.spans {
                    let span_bytes = span.text.len() as u32;
                    if let Some(fg) = span.fg {
                        let mut color_attr = pango::AttrColor::new_foreground(
                            fg.r as u16 * 257,
                            fg.g as u16 * 257,
                            fg.b as u16 * 257,
                        );
                        color_attr.set_start_index(byte_offset);
                        color_attr.set_end_index(byte_offset + span_bytes);
                        attrs.insert(color_attr);
                    }
                    byte_offset += span_bytes;
                }
                set_source(cr, theme.foreground);
                pango_layout.set_attributes(Some(&attrs));
                cr.move_to(text_x, footer_y);
                super::painted_text::show_layout(cr, pango_layout);
                pango_layout.set_attributes(None);
                cr.restore().ok();
            }
        }
    }

    cr.restore().ok();
    layout
}

/// Compute layout without painting (for hit-test from handle()).
pub fn gtk_data_table_layout(
    pango_layout: &pango::Layout,
    table: &DataTable,
    width: f64,
    height: f64,
    line_height: f64,
) -> DataTableLayout {
    pango_layout.set_attributes(None);
    let measure = super::toolbar::PangoMeasure {
        pango_layout: Some(pango_layout),
        char_width: 0.0,
    };
    pixel_data_table_layout(
        table,
        width as f32,
        height as f32,
        line_height as f32,
        &measure,
    )
}

// ── Tests ──────────────────────────────────────────────────────────────────
//
// Headless paint tests (see `gtk/tab_bar.rs` for the pattern this follows):
// a Cairo `ImageSurface`, no display, pixel readback. Gated on the `gtk`
// feature so `cargo test --features tui` alone (this repo's coord
// `test_command`) never runs them — `cargo test --features gtk,tui` does.
//
// Defect 1 (body clipping) is already correct on this backend —
// `cr.clip()` around each body cell — so the guard here just pins it
// against a future refactor dropping the clip. Defect 2 (body
// separators) was genuinely missing and is fixed alongside these tests.

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::data_table::{Column, ColumnWidth, DataRow};
    use crate::theme::Theme;
    use crate::types::{Color, Decoration, StyledText, WidgetId};
    use pangocairo::cairo::{Context, Format, ImageSurface};

    const W: i32 = 300;
    const H: i32 = 100;
    const LINE_H: f64 = 16.0;

    /// Read an RGB triple from an ARgb32 surface at pixel (x, y). Same
    /// byte layout as `gtk/tab_bar.rs`'s test helper and `GtkDriver::pixel`.
    fn pixel(data: &[u8], stride: usize, x: i32, y: i32) -> (u8, u8, u8) {
        let off = y as usize * stride + x as usize * 4;
        (data[off + 2], data[off + 1], data[off])
    }

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

    fn three_col_table(a: &str, b: &str, c: &str) -> DataTable {
        DataTable {
            id: WidgetId::new("clip-test"),
            columns: vec![
                Column {
                    title: "A".into(),
                    width: ColumnWidth::Flex(1.0),
                    align: ColumnAlign::Left,
                },
                Column {
                    title: "B".into(),
                    width: ColumnWidth::Flex(1.0),
                    align: ColumnAlign::Left,
                },
                Column {
                    title: "C".into(),
                    width: ColumnWidth::Flex(1.0),
                    align: ColumnAlign::Left,
                },
            ],
            rows: vec![DataRow {
                cells: vec![
                    StyledText::plain(a),
                    StyledText::plain(b),
                    StyledText::plain(c),
                ],
                decoration: Decoration::Normal,
            }],
            selected_idx: None,
            scroll_offset: 0,
            sort: None,
            has_focus: false,
            show_scrollbar: false,
            min_total_width: None,
            h_scroll: 0.0,
            column_overrides: Vec::new(),
            footer: None,
        }
    }

    /// Paint `table` into a fresh `theme.background`-filled surface and
    /// return the raw pixel buffer alongside the resolved layout.
    fn paint(table: &DataTable, theme: &Theme) -> (Vec<u8>, i32, DataTableLayout) {
        let mut surface = ImageSurface::create(Format::ARgb32, W, H).expect("create ImageSurface");
        let table_layout;
        {
            let cr = Context::new(&surface).expect("Context::new");
            let (br, bg, bb) = cairo_rgb(theme.background);
            cr.set_source_rgb(br, bg, bb);
            cr.paint().ok();

            let pango_layout = pangocairo::functions::create_layout(&cr);
            table_layout = draw_data_table(
                &cr,
                &pango_layout,
                0.0,
                0.0,
                W as f64,
                H as f64,
                table,
                theme,
                LINE_H,
                None,
            );
        }
        surface.flush();
        let stride = surface.stride();
        let data = surface.data().expect("surface data").to_vec();
        (data, stride, table_layout)
    }

    /// An over-long *middle* column's text must stay inside its own
    /// column's `cr.clip()` rect to prevent overflow into neighbours.
    #[test]
    fn body_cell_wider_than_column_does_not_paint_into_neighbour() {
        let long = "this-value-is-far-wider-than-its-resolved-column-share-by-a-lot";
        let table = three_col_table("A", long, "C");
        let theme = Theme::default();
        let (data, stride, layout) = paint(&table, &theme);

        let c_col = &layout.columns[2];
        // A point safely inside column C, well past where its own "C"
        // glyph paints, must be untouched background — not B's overflow.
        let probe_x = (c_col.x + c_col.width - 4.0) as i32;
        let probe_y = (layout.header_height as f64 + LINE_H / 2.0) as i32;
        let px = pixel(&data, stride as usize, probe_x, probe_y);
        assert_eq!(
            px,
            rgb(theme.background),
            "pixel inside column C ({probe_x},{probe_y}) should be background, \
             not B's overflow text bleeding through the clip"
        );
    }

    /// A sorted column paints a codicon sort-direction glyph
    /// after its title, in the same column's header band — not a plain
    /// `â–²`/`â–¼` baked into the title string. Probes the band right after
    /// the lone-letter title's own ink (well short of the column's
    /// separator) for *something* painted there only when `sort` names
    /// that column, mirroring `draw_context_menu_paints_submenu_arrow_not_shown_on_plain_leaf`'s
    /// "band differs only when the affordance should show" shape.
    #[test]
    fn sorted_column_paints_a_glyph_after_its_title_unsorted_does_not() {
        let theme = Theme::default();

        let mut sorted = three_col_table("A", "B", "C");
        sorted.sort = Some((0, SortDirection::Ascending));
        let (sorted_data, stride, layout) = paint(&sorted, &theme);

        let unsorted = three_col_table("A", "B", "C");
        let (unsorted_data, stride2, _) = paint(&unsorted, &theme);
        assert_eq!(stride, stride2, "same canvas size, same stride");

        let col0 = &layout.columns[0];
        let x0 = col0.x as i32;
        // Stop short of column 0's right-edge separator, which `sort`
        // cannot move either way.
        let x1 = (col0.x + col0.width - 2.0) as i32;
        let header_y_lo = 1_i32;
        let header_y_hi = (layout.header_height as i32 - 1).max(header_y_lo + 1);

        // Sorting column 0 only adds ink after its title — it must not
        // repaint column 0's background or move the title itself, so
        // every pixel up to *some* x within the column stays identical
        // between the two renders, and at least one pixel past that
        // differs (the glyph `sorted` painted that `unsorted` did not).
        let differs_at = |x: i32| {
            (header_y_lo..header_y_hi).any(|y| {
                pixel(&sorted_data, stride as usize, x, y)
                    != pixel(&unsorted_data, stride2 as usize, x, y)
            })
        };

        assert!(
            !differs_at(x0),
            "column 0's leading edge (under the title's own first glyph) must render \
             identically whether or not it is the sort column"
        );
        assert!(
            (x0..x1).any(differs_at),
            "sorting column 0 should paint a glyph somewhere in x={x0}..{x1} that the \
             unsorted render does not"
        );
    }

    /// Body rows draw a 1px separator at the same x as the header.
    ///
    /// The separator rect straddles a half-pixel boundary (`sep_x - 0.5`
    /// to `sep_x + 0.5`), so with antialiasing on, the pixel column at
    /// `sep_x` is a 50/50 blend of `theme.separator` over the background.
    #[test]
    fn body_row_draws_separator_at_same_x_as_header() {
        let table = three_col_table("A", "B", "C");
        let theme = Theme::default();
        let (data, stride, layout) = paint(&table, &theme);

        let sep_x = (layout.columns[0].x + layout.columns[0].width) as i32;
        let header_y = (layout.header_height as f64 / 2.0) as i32;
        let body_y = (layout.header_height as f64 + LINE_H / 2.0) as i32;

        let header_px = pixel(&data, stride as usize, sep_x, header_y);
        let body_px = pixel(&data, stride as usize, sep_x, body_y);
        assert_ne!(
            header_px,
            rgb(theme.background),
            "sanity check: header separator pixel should differ from background"
        );
        assert_eq!(
            body_px, header_px,
            "body row should draw the same separator at sep_x={sep_x} the header uses: \
             header pixel {header_px:?}, body pixel {body_px:?}"
        );
        assert_ne!(
            body_px,
            rgb(theme.background),
            "separator pixel must differ from the row background"
        );
    }

    /// Acceptance: a cell whose text reaches all the way to its column's
    /// right edge must not paint over the divider — no zero-gap
    /// abutment even in the tightest case. The fix draws the separator
    /// *after* the cell text for exactly this reason.
    #[test]
    fn separator_survives_a_cell_that_fills_its_entire_column() {
        let filling = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
        let table = three_col_table(filling, "B", "C");
        let theme = Theme::default();
        let (data, stride, layout) = paint(&table, &theme);

        let sep_x = (layout.columns[0].x + layout.columns[0].width) as i32;
        let header_y = (layout.header_height as f64 / 2.0) as i32;
        let body_y = (layout.header_height as f64 + LINE_H / 2.0) as i32;

        // Compare against this same render's header separator pixel
        // (see the blending note above) rather than a hardcoded colour:
        // if the fill text painted over the divider, `body_px` would
        // read as foreground ink instead of matching the header's blend.
        let header_px = pixel(&data, stride as usize, sep_x, header_y);
        let body_px = pixel(&data, stride as usize, sep_x, body_y);
        assert_eq!(
            body_px, header_px,
            "separator must survive even when the left column's text fills the \
             entire column width: header pixel {header_px:?}, body pixel {body_px:?}"
        );
    }
}

/// Multi-select click wiring over [`crate::gtk::testing::GtkDriver`].
///
/// `DataTable` stays purely declarative (no selection-set field of its
/// own — see `crate::types::apply_selection_gesture`'s doc), so the app
/// owns the selected-index set and the gesture anchor, resolves each
/// `MouseDown` to a row via [`crate::primitives::data_table::DataTableLayout::hit_test`],
/// derives the gesture from the event's `Modifiers`, and emits
/// `DataTableEvent::SelectionSet` with the resulting indices. Mirrors
/// [`super::list::multi_select_driver_tests`] and
/// [`super::tree::multi_select_driver_tests`]'s shape.
#[cfg(test)]
mod multi_select_driver_tests {
    use crate::gtk::testing::GtkDriver;
    use crate::primitives::data_table::ColumnMeasure;
    use crate::runner::{AppLogic, Reaction};
    use crate::{
        apply_selection_gesture, Backend, Column, DataRow, DataTable, DataTableEvent, DataTableHit,
        Decoration, Modifiers, MouseButton, Point, Rect, SelectionGesture, StyledText, WidgetId,
    };

    const VIEWPORT_W: f32 = 40.0;
    const VIEWPORT_H: f32 = 10.0;
    const ROW_H: f32 = 1.0;
    const HEADER_H: f32 = 1.0;
    const SCROLLBAR_W: f32 = 1.0;

    fn row(label: &str) -> DataRow {
        DataRow {
            cells: vec![StyledText::plain(label.to_string())],
            decoration: Decoration::Normal,
        }
    }

    fn sample_table() -> DataTable {
        DataTable {
            id: WidgetId::new("dt"),
            columns: vec![Column {
                title: "Name".to_string(),
                width: Default::default(),
                align: Default::default(),
            }],
            rows: (0..5).map(|i| row(&format!("row {i}"))).collect(),
            selected_idx: None,
            scroll_offset: 0,
            sort: None,
            has_focus: true,
            show_scrollbar: false,
            min_total_width: None,
            h_scroll: 0.0,
            column_overrides: vec![],
            footer: None,
        }
    }

    struct TableApp {
        table: DataTable,
        selected: Vec<usize>,
        anchor: usize,
        events: Vec<DataTableEvent>,
    }

    impl TableApp {
        fn new() -> Self {
            Self {
                table: sample_table(),
                selected: Vec::new(),
                anchor: 0,
                events: Vec::new(),
            }
        }
    }

    impl AppLogic for TableApp {
        type AreaId = ();

        fn render(&self, backend: &mut dyn Backend, _area: ()) {
            backend.draw_data_table(
                Rect::new(0.0, 0.0, VIEWPORT_W, VIEWPORT_H),
                &self.table,
                None,
            );
        }

        fn handle(&mut self, event: crate::UiEvent, _backend: &mut dyn Backend) -> Reaction {
            let crate::UiEvent::MouseDown {
                position,
                modifiers,
                ..
            } = event
            else {
                return Reaction::Continue;
            };
            let layout =
                self.table
                    .layout(VIEWPORT_W, VIEWPORT_H, ROW_H, HEADER_H, SCROLLBAR_W, |_| {
                        ColumnMeasure::new(20.0)
                    });
            let hit = layout.hit_test(
                position.x,
                position.y,
                self.table.scroll_offset,
                self.table.rows.len(),
            );
            let idx = match hit {
                DataTableHit::Row { idx } => idx,
                _ => return Reaction::Continue,
            };
            let gesture = SelectionGesture::from_modifiers(modifiers);
            let indices = apply_selection_gesture(&self.selected, self.anchor, idx, gesture);
            self.selected = indices.clone();
            if !matches!(gesture, SelectionGesture::Range) {
                self.anchor = idx;
            }
            self.events.push(DataTableEvent::SelectionSet { indices });
            Reaction::Redraw
        }
    }

    fn mouse_down(x: f32, y: f32, modifiers: Modifiers) -> crate::UiEvent {
        crate::UiEvent::MouseDown {
            widget: None,
            button: MouseButton::Left,
            position: Point::new(x, y),
            modifiers,
        }
    }

    #[test]
    fn plain_click_replaces_selection() {
        let mut driver = GtkDriver::new(TableApp::new(), 80, 40);
        driver.dispatch(mouse_down(
            2.0,
            HEADER_H + 2.0 * ROW_H,
            Modifiers::default(),
        ));
        assert_eq!(driver.app().selected, vec![2]);
    }

    #[test]
    fn ctrl_click_toggles_rows_into_a_multi_selection() {
        let mut driver = GtkDriver::new(TableApp::new(), 80, 40);
        driver.set_double_click_folding(false);
        driver.dispatch(mouse_down(2.0, HEADER_H, Modifiers::default()));
        let ctrl = Modifiers {
            ctrl: true,
            ..Default::default()
        };
        driver.dispatch(mouse_down(2.0, HEADER_H + 2.0 * ROW_H, ctrl));
        assert_eq!(driver.app().selected, vec![0, 2]);
        driver.dispatch(mouse_down(2.0, HEADER_H + 2.0 * ROW_H, ctrl));
        assert_eq!(driver.app().selected, vec![0]);
        assert_eq!(
            driver.app().events.last(),
            Some(&DataTableEvent::SelectionSet { indices: vec![0] })
        );
    }

    #[test]
    fn shift_click_selects_the_range_from_the_anchor() {
        let mut driver = GtkDriver::new(TableApp::new(), 80, 40);
        driver.set_double_click_folding(false);
        driver.dispatch(mouse_down(2.0, HEADER_H, Modifiers::default()));
        let shift = Modifiers {
            shift: true,
            ..Default::default()
        };
        driver.dispatch(mouse_down(2.0, HEADER_H + 3.0 * ROW_H, shift));
        assert_eq!(driver.app().selected, vec![0, 1, 2, 3]);
        assert_eq!(
            driver.app().events.last(),
            Some(&DataTableEvent::SelectionSet {
                indices: vec![0, 1, 2, 3]
            })
        );
    }

    #[test]
    fn cmd_click_toggles_the_same_as_ctrl_click() {
        let mut driver = GtkDriver::new(TableApp::new(), 80, 40);
        driver.set_double_click_folding(false);
        driver.dispatch(mouse_down(2.0, HEADER_H + ROW_H, Modifiers::default()));
        driver.dispatch(mouse_down(
            2.0,
            HEADER_H + 4.0 * ROW_H,
            Modifiers {
                cmd: true,
                ..Default::default()
            },
        ));
        assert_eq!(driver.app().selected, vec![1, 4]);
    }
}