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
//! TUI rasteriser for [`crate::TreeView`].
//!
//! Per D6: this function asks the primitive for a [`crate::TreeViewLayout`]
//! using a uniform 1-cell-per-row measurer (TUI rows are always 1 cell
//! tall) and paints the resolved positions verbatim. The GTK rasteriser
//! supplies a different per-row measurer (header rows 1× line_height,
//! leaves 1.4×) — that's a backend-specific decision the rasteriser
//! owns, not the primitive. `TreeStyle::row_height` is a GUI-pixel
//! override; a terminal cell can't be subdivided, so TUI intentionally
//! ignores it and always measures 1 cell per row.

use ratatui::buffer::Buffer;
use ratatui::layout::Rect;

use super::{draw_styled_text, qc, ratatui_color, set_cell};
use crate::primitives::tree::{TreeRowEditState, TreeRowMeasure, TreeView, TreeViewLayout};
use crate::theme::Theme;
use crate::types::Decoration;

/// Draw a [`TreeView`] into `area` on `buf`.
///
/// # Visual contract
///
/// - **Header rows** (`Decoration::Header`): rendered with
///   [`Theme::header_bg`] / [`Theme::header_fg`] (the SC panel's
///   section titles).
/// - **Selected row** (when `tree.has_focus`): rendered with
///   [`Theme::selected_bg`] and the row's `default_fg`.
/// - **Other rows**: rendered with [`Theme::tab_bar_bg`] /
///   [`Theme::foreground`]. Branches and leaves get the same row
///   styling — `is_expanded`-ness only affects chevron rendering, not
///   visual emphasis.
/// - **Indent:** `tree.style.indent` cells per depth level.
/// - **Chevrons:** [`tree.style.chevron_expanded`] /
///   [`tree.style.chevron_collapsed`] for branches when
///   `tree.style.show_chevrons` is true; leaves get a 2-cell leading
///   gap for visual alignment.
/// - **Icon:** `row.icon.glyph` when `nerd_fonts_enabled`, else the
///   ASCII fallback. Painted in `icon.color` when set, else the
///   row's `default_fg`.
/// - **Badge** (right-aligned within row): rendered in
///   `badge.fg`/`badge.bg` (falling back to [`Theme::muted_fg`] /
///   row bg) when there's room past the text.
///
/// Doesn't draw a scrollbar — scrollbars are a later primitive stage.
pub fn draw_tree(
    buf: &mut Buffer,
    area: Rect,
    tree: &TreeView,
    theme: &Theme,
    nerd_fonts_enabled: bool,
) {
    if area.width == 0 || area.height == 0 {
        return;
    }

    let row_bg = ratatui_color(theme.tab_bar_bg);
    let hdr_bg = ratatui_color(theme.header_bg);
    let hdr_fg = ratatui_color(theme.header_fg);
    let item_fg = ratatui_color(theme.foreground);
    let sel_bg = ratatui_color(theme.selected_bg);
    let inactive_sel_bg = ratatui_color(theme.inactive_selected_bg);
    let text_sel_bg = ratatui_color(theme.selection_bg);
    let dim_fg = ratatui_color(theme.muted_fg);

    let indent_cells = tree.style.indent as usize;

    let layout = tui_tree_layout(tree, area);

    for visible_row in &layout.visible_rows {
        let row = &tree.rows[visible_row.row_idx];
        let y = area.y + visible_row.bounds.y.round() as u16;
        if y >= area.y + area.height {
            break;
        }

        let is_header = matches!(row.decoration, Decoration::Header);
        let path_selected = tree.selected_path.as_ref().is_some_and(|p| p == &row.path);
        let is_selected = tree.has_focus && path_selected;
        let is_inactive_selected = !tree.has_focus && path_selected;

        let (default_fg, bg) = match (is_header, is_selected, is_inactive_selected) {
            (_, true, _) => (hdr_fg, sel_bg),
            (_, _, true) => (item_fg, inactive_sel_bg),
            (true, _, _) => (hdr_fg, hdr_bg),
            _ => (item_fg, row_bg),
        };

        for x in area.x..area.x + area.width {
            set_cell(buf, x, y, ' ', default_fg, bg);
        }

        let mut col: usize = 0;
        let indent_spaces = (row.indent as usize) * indent_cells;
        col += indent_spaces;

        if let Some(expanded) = row.is_expanded {
            if tree.style.show_chevrons {
                let chevron = if expanded {
                    &tree.style.chevron_expanded
                } else {
                    &tree.style.chevron_collapsed
                };
                for ch in chevron.chars() {
                    if col >= area.width as usize {
                        break;
                    }
                    set_cell(buf, area.x + col as u16, y, ch, default_fg, bg);
                    col += 1;
                }
                if col < area.width as usize {
                    set_cell(buf, area.x + col as u16, y, ' ', default_fg, bg);
                    col += 1;
                }
            }
        } else {
            // Leaves: small leading gap for readability.
            col += 2.min(area.width as usize - col.min(area.width as usize));
        }

        if let Some(ref icon) = row.icon {
            let glyph = if nerd_fonts_enabled {
                &icon.glyph
            } else {
                &icon.fallback
            };
            let icon_fg = icon.color.map(ratatui_color).unwrap_or(default_fg);
            for ch in glyph.chars() {
                if col >= area.width as usize {
                    break;
                }
                set_cell(buf, area.x + col as u16, y, ch, icon_fg, bg);
                col += 1;
            }
            if col < area.width as usize {
                set_cell(buf, area.x + col as u16, y, ' ', default_fg, bg);
                col += 1;
            }
        }

        if let Some(ref edit) = row.edit {
            paint_edit_input(buf, area, y, col, edit, default_fg, bg, text_sel_bg, dim_fg);
        } else {
            let text_start = col;

            // Reserve room for the right-aligned badge *before*
            // painting the label, clamping the label to end at least one
            // blank column short of the badge. The label must not overwrite
            // the badge; a gap indicates when the label is truncated.
            let badge_start_col = row
                .badge
                .as_ref()
                .map(|badge| (area.width as usize).saturating_sub(badge.text.chars().count()));
            let draw_badge = badge_start_col.is_some_and(|start| start > text_start);
            let max_text_col = if draw_badge {
                // Reserve one blank gap column between the label and the
                // badge; never go below `text_start` (a zero-width label
                // is still valid when the badge leaves no room at all).
                badge_start_col
                    .expect("draw_badge is only true when badge_start_col is Some")
                    .saturating_sub(1)
                    .max(text_start)
            } else {
                area.width as usize
            };

            let text_area = Rect {
                x: area.x,
                y: area.y,
                width: max_text_col as u16,
                height: area.height,
            };
            draw_styled_text(
                buf,
                text_area,
                y,
                col,
                &row.text,
                default_fg,
                bg,
                row.decoration,
                dim_fg,
            );

            let label_truncated = draw_badge
                && max_text_col > text_start
                && text_start + row.text.visible_width() > max_text_col;
            if label_truncated {
                // Overwrite the label's last painted cell with `…`,
                // reusing whatever fg/bg that cell already has so
                // per-span colouring (e.g. a muted/error label) survives
                // the clamp untouched.
                let ellipsis_col = area.x + (max_text_col - 1) as u16;
                // Use the bounds-checked `Buffer::cell` accessor rather than
                // direct indexing: `area` is caller-supplied (see
                // `crate::tui::backend::draw_tree` / `multi_section_view.rs`)
                // and isn't guaranteed to stay within the real buffer's own
                // `area` across a resize race or a stale cached rect. Direct
                // indexing panics in that case; `cell()` returns `None` and
                // we fall back to the row's default colours instead.
                let (ellipsis_fg, ellipsis_bg) = buf
                    .cell((ellipsis_col, y))
                    .map(|existing| (existing.fg, existing.bg))
                    .unwrap_or((default_fg, bg));
                set_cell(buf, ellipsis_col, y, '…', ellipsis_fg, ellipsis_bg);
            }

            if draw_badge {
                let badge = row.badge.as_ref().expect("draw_badge implies row.badge");
                let badge_start_col =
                    badge_start_col.expect("draw_badge is only true when badge_start_col is Some");
                let badge_fg = badge.fg.map(qc).unwrap_or(dim_fg);
                let badge_bg = badge.bg.map(qc).unwrap_or(bg);
                for (bx, ch) in (badge_start_col..).zip(badge.text.chars()) {
                    if bx >= area.width as usize {
                        break;
                    }
                    set_cell(buf, area.x + bx as u16, y, ch, badge_fg, badge_bg);
                }
            }
        }

        let _ = col;
    }
}

#[allow(clippy::too_many_arguments)]
fn paint_edit_input(
    buf: &mut Buffer,
    area: Rect,
    y: u16,
    start_col: usize,
    edit: &TreeRowEditState,
    fg: ratatui::style::Color,
    bg: ratatui::style::Color,
    sel_bg: ratatui::style::Color,
    dim_fg: ratatui::style::Color,
) {
    if edit.text.is_empty() {
        if let Some(ref ph) = edit.placeholder {
            for (col, ch) in (start_col..).zip(ph.chars()) {
                if col >= area.width as usize {
                    break;
                }
                set_cell(buf, area.x + col as u16, y, ch, dim_fg, bg);
            }
        }
        // Cursor at position 0 (inverted space).
        if start_col < area.width as usize {
            set_cell(buf, area.x + start_col as u16, y, ' ', bg, fg);
        }
        return;
    }

    let (sel_lo, sel_hi) = match edit.selection_anchor {
        Some(a) if a != edit.cursor => (a.min(edit.cursor), a.max(edit.cursor)),
        _ => (0, 0),
    };
    let has_selection = sel_hi > sel_lo;

    let mut byte = 0usize;
    for (col, ch) in (start_col..).zip(edit.text.chars()) {
        if col >= area.width as usize {
            break;
        }
        let in_sel = has_selection && byte >= sel_lo && byte < sel_hi;
        let cell_bg = if in_sel { sel_bg } else { bg };
        set_cell(buf, area.x + col as u16, y, ch, fg, cell_bg);
        byte += ch.len_utf8();
    }

    // Block cursor: find char index for cursor byte offset, invert that cell.
    let mut cursor_char_idx = 0usize;
    let mut b = 0usize;
    for ch in edit.text.chars() {
        if b >= edit.cursor {
            break;
        }
        b += ch.len_utf8();
        cursor_char_idx += 1;
    }
    let cursor_col = start_col + cursor_char_idx;
    if cursor_col < area.width as usize {
        let ch = edit.text.chars().nth(cursor_char_idx).unwrap_or(' ');
        set_cell(buf, area.x + cursor_col as u16, y, ch, bg, fg);
    }
}

/// Compute the layout the TUI rasteriser would produce for `tree` in
/// `area`. Hosts and tests call this to drive hit-testing without
/// re-deriving metrics that could drift from paint. `draw_tree` uses
/// this same helper internally so paint and hit_test consume one
/// layout instance produced by one set of metrics — the source-of-
/// truth contract.
///
/// TUI rows are uniform 1-cell tall. The layout is in tree-local coords
/// (origin at 0,0); convert absolute click coords by subtracting
/// `area.x` / `area.y` before calling [`TreeViewLayout::hit_test`].
///
/// Branch rows (`is_expanded.is_some()`) get a split hit region: the
/// cells covered by the painted chevron glyph + trailing space produce
/// [`crate::primitives::tree::TreeViewHit::Chevron`]; the rest of the
/// row produces [`crate::primitives::tree::TreeViewHit::Row`].
pub fn tui_tree_layout(tree: &TreeView, area: Rect) -> TreeViewLayout {
    let indent_cells = tree.style.indent as f32;
    let chevron_w = if tree.style.show_chevrons {
        // chevron glyph width (chars) + 1 trailing space cell
        tree.style.chevron_expanded.chars().count() as f32 + 1.0
    } else {
        0.0
    };
    tree.layout(area.width as f32, area.height as f32, |i| {
        let row = &tree.rows[i];
        let chevron_end_x = if row.is_expanded.is_some() && chevron_w > 0.0 {
            Some(row.indent as f32 * indent_cells + chevron_w)
        } else {
            None
        };
        TreeRowMeasure {
            height: 1.0,
            chevron_end_x,
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::tree::{TreeRow, TreeView};
    use crate::types::{StyledSpan, StyledText, TreeStyle, WidgetId};

    fn row(path: &[u16], indent: u16, label: &str, expanded: Option<bool>) -> TreeRow {
        TreeRow {
            path: path.to_vec(),
            indent,
            text: StyledText {
                spans: vec![StyledSpan::plain(label)],
            },
            icon: None,
            badge: None,
            is_expanded: expanded,
            decoration: Decoration::Normal,
            edit: None,
        }
    }

    fn make_tree() -> TreeView {
        TreeView {
            id: WidgetId::new("tree"),
            rows: vec![
                row(&[0], 0, "src", Some(true)),
                row(&[0, 0], 1, "main.rs", None),
                row(&[0, 1], 1, "lib.rs", None),
            ],
            selection_mode: crate::types::SelectionMode::default(),
            selected_path: Some(vec![0, 0]),
            scroll_offset: 0,
            has_focus: true,
            style: TreeStyle::default(),
        }
    }

    fn cell_char(buf: &Buffer, x: u16, y: u16) -> char {
        buf[(x, y)].symbol().chars().next().unwrap_or(' ')
    }

    #[test]
    fn paints_branch_with_chevron_and_leaves_indented() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 30, 5));
        let tree = make_tree();
        draw_tree(
            &mut buf,
            Rect::new(0, 0, 30, 5),
            &tree,
            &Theme::default(),
            false,
        );

        // Row 0 ("src"): branch, expanded — chevron at col 0.
        // TreeStyle::default() chevron_expanded is 'â–¾'.
        assert_eq!(
            cell_char(&buf, 0, 0),
            tree.style.chevron_expanded.chars().next().unwrap()
        );
        // "src" should appear after the chevron + space.
        let src_row: String = (2..5).map(|x| cell_char(&buf, x, 0)).collect();
        assert_eq!(src_row, "src");

        // Row 1 ("main.rs"): leaf, indent=1 → starts at col 2 (indent_cells default).
        // Leaves get a 2-cell leading gap on top of indent.
        // Default TreeStyle::indent is 2.
        let leaf_label_start = 2 + 2;
        let main: String = (leaf_label_start..(leaf_label_start + 7))
            .map(|x| cell_char(&buf, x as u16, 1))
            .collect();
        assert_eq!(main, "main.rs");
    }

    #[test]
    fn selected_row_uses_selected_bg() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 30, 5));
        let tree = make_tree();
        let theme = Theme {
            selected_bg: crate::types::Color::rgb(99, 0, 0),
            ..Theme::default()
        };
        draw_tree(&mut buf, Rect::new(0, 0, 30, 5), &tree, &theme, false);
        // Row 1 ("main.rs") is selected — its bg should be (99, 0, 0).
        let bg = buf[(0u16, 1u16)].bg;
        assert_eq!(bg, ratatui::style::Color::Rgb(99, 0, 0));
    }

    #[test]
    fn header_row_uses_header_bg_when_unselected() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 30, 3));
        let tree = TreeView {
            id: WidgetId::new("tree"),
            rows: vec![TreeRow {
                path: vec![0],
                indent: 0,
                text: StyledText {
                    spans: vec![StyledSpan::plain("CHANGES")],
                },
                icon: None,
                badge: None,
                is_expanded: Some(true),
                decoration: Decoration::Header,
                edit: None,
            }],
            selection_mode: crate::types::SelectionMode::default(),
            selected_path: None,
            scroll_offset: 0,
            has_focus: false,
            style: TreeStyle::default(),
        };
        let theme = Theme {
            header_bg: crate::types::Color::rgb(7, 7, 7),
            ..Theme::default()
        };
        draw_tree(&mut buf, Rect::new(0, 0, 30, 3), &tree, &theme, false);
        let bg = buf[(0u16, 0u16)].bg;
        assert_eq!(bg, ratatui::style::Color::Rgb(7, 7, 7));
    }

    #[test]
    fn zero_size_is_a_no_op() {
        let mut buf = Buffer::empty(Rect::new(0, 0, 10, 5));
        let tree = make_tree();
        draw_tree(
            &mut buf,
            Rect::new(0, 0, 0, 5),
            &tree,
            &Theme::default(),
            false,
        );
        assert_eq!(cell_char(&buf, 0, 0), ' ');
    }

    #[test]
    fn icon_color_paints_icon_cell_in_that_color_else_default_fg() {
        use crate::types::{Color, Icon};

        let colored = Color::rgb(200, 30, 30);
        let mut tree = make_tree();
        // Row 1 ("main.rs") gets a colored icon; row 2 ("lib.rs") gets an
        // uncolored one — same glyph, only the color field differs.
        tree.rows[1].icon = Some(Icon::new("R", "R").with_color(colored));
        tree.rows[2].icon = Some(Icon::new("R", "R"));

        let theme = Theme::default();
        let mut buf = Buffer::empty(Rect::new(0, 0, 30, 5));
        draw_tree(&mut buf, Rect::new(0, 0, 30, 5), &tree, &theme, true);

        // Leaves: indent=1 → col 2 (indent_cells) + 2-cell leading gap = col 4.
        let icon_col = 2 + 2;
        assert_eq!(
            buf[(icon_col as u16, 1u16)].fg,
            ratatui_color(colored),
            "row with Icon::color set should paint the icon glyph in that color"
        );
        assert_eq!(
            buf[(icon_col as u16, 2u16)].fg,
            ratatui_color(theme.foreground),
            "row without Icon::color should paint the icon glyph in the default fg, unchanged"
        );
    }

    /// A label too long to fit before a right-aligned
    /// badge must be clamped to end at least one blank column short of
    /// the badge, with the clamped label ending in `…` — not overwritten
    /// by the badge with no gap or truncation indicator (vimcode's
    /// Explorer showed `BACKEND_SPECU`, where the trailing `U` was
    /// actually the git-untracked badge glued onto the label).
    #[test]
    fn long_label_with_badge_leaves_gap_and_ellipsizes() {
        use crate::types::Badge;

        let mut tree = make_tree();
        // Row 1 ("main.rs", a leaf at indent=1) gets an over-long label
        // and a one-character badge.
        tree.rows[1].text = StyledText::plain("BACKEND_SPECULATIVE_EXECUTION_MODULE");
        tree.rows[1].badge = Some(Badge::plain("U"));

        let width = 20u16;
        let mut buf = Buffer::empty(Rect::new(0, 0, width, 5));
        draw_tree(
            &mut buf,
            Rect::new(0, 0, width, 5),
            &tree,
            &Theme::default(),
            false,
        );

        let text = row_text(&buf, 1);

        // Badge "U" (1 col) is painted at the row's very last column.
        let badge_col = width - 1;
        assert_eq!(
            cell_char(&buf, badge_col, 1),
            'U',
            "expected the badge in the last column, row text: {text:?}"
        );
        // The column immediately before the badge is blank — the
        // mandatory gap column, never glued to the badge.
        assert_eq!(
            cell_char(&buf, badge_col - 1, 1),
            ' ',
            "expected a blank gap column before the badge, row text: {text:?}"
        );
        // The label was truncated somewhere before the gap, and the
        // truncation is marked with an ellipsis, not a hard cut.
        assert!(
            text.contains('…'),
            "expected the clamped label to end in an ellipsis, row text: {text:?}"
        );
        // The ellipsis sits immediately before the gap column (the label's
        // last painted cell).
        assert_eq!(
            cell_char(&buf, badge_col - 2, 1),
            '…',
            "expected the ellipsis directly before the gap column, row text: {text:?}"
        );
    }

    #[test]
    fn long_label_ellipsis_tolerates_oversized_area_without_panicking() {
        use crate::types::Badge;

        let mut tree = make_tree();
        tree.rows[1].text = StyledText::plain("BACKEND_SPECULATIVE_EXECUTION_MODULE");
        tree.rows[1].badge = Some(Badge::plain("U"));

        // `area` is caller-supplied and can legitimately exceed the real
        // buffer's own bounds (a resize race, an off-by-one in a caller's
        // layout math, or a stale cached rect). Ellipsis painting must
        // clamp the column to the buffer's actual bounds.
        let mut buf = Buffer::empty(Rect::new(0, 0, 10, 5));
        draw_tree(
            &mut buf,
            Rect::new(0, 0, 40, 5),
            &tree,
            &Theme::default(),
            false,
        );
    }

    // ── Paint↔click round-trip harness ─────────────────────────────────────
    //
    // Per the Session 346 course correction (PLAN.md "🧭 Course
    // correction"): primitives that promise paint/click consistency
    // need empirical verification, not just structural design. These
    // tests paint a `TreeView` into a `ratatui::Buffer`, find the cells
    // the rasteriser actually wrote glyphs into, then hit_test those
    // exact coordinates against the layout the rasteriser used and
    // assert the hit identifies the painted-into row. If paint and
    // click ever drift in the TUI tree rasteriser, one of these fails.
    //
    // TreeView uses tree-local coords (origin at 0,0) for `hit_test`,
    // unlike `MultiSectionView` which uses absolute coords. The harness
    // converts between them by subtracting `area.x`/`area.y` from the
    // painted absolute y. Same source-of-truth contract; different
    // origin convention.
    //
    // Mirrors the MultiSectionView harness shape so future
    // primitives can copy this pattern.

    use crate::primitives::tree::TreeViewHit;
    use crate::tui::tree::tui_tree_layout;
    use crate::types::TreePath;

    fn row_text(buf: &Buffer, y: u16) -> String {
        let area = buf.area;
        (area.x..area.x + area.width)
            .map(|x| cell_char(buf, x, y))
            .collect()
    }

    fn find_row_with(buf: &Buffer, needle: &str) -> Option<u16> {
        let area = buf.area;
        (area.y..area.y + area.height).find(|&y| row_text(buf, y).contains(needle))
    }

    fn long_tree(n: usize) -> TreeView {
        let labels: Vec<String> = (0..n).map(|i| format!("item-{i:02}")).collect();
        let rows: Vec<TreeRow> = labels
            .iter()
            .enumerate()
            .map(|(i, label)| TreeRow {
                path: vec![i as u16] as TreePath,
                indent: 0,
                text: StyledText {
                    spans: vec![StyledSpan::plain(label.clone())],
                },
                icon: None,
                badge: None,
                is_expanded: None,
                decoration: Decoration::Normal,
                edit: None,
            })
            .collect();
        TreeView {
            id: WidgetId::new("long"),
            rows,
            selection_mode: crate::types::SelectionMode::default(),
            selected_path: None,
            scroll_offset: 0,
            has_focus: false,
            style: TreeStyle::default(),
        }
    }

    fn paint_then_layout(
        buf: &mut Buffer,
        area: Rect,
        tree: &TreeView,
        theme: &Theme,
        nerd_fonts_enabled: bool,
    ) -> TreeViewLayout {
        draw_tree(buf, area, tree, theme, nerd_fonts_enabled);
        tui_tree_layout(tree, area)
    }

    /// Round-trip: paint, find each row's label in the buffer, hit_test
    /// the same coordinate, assert the hit identifies the correct row.
    /// Accepts both `Row(idx)` and `Chevron(idx)` as valid hits — the
    /// test verifies row-position consistency, not whether the click
    /// landed on the chevron or the body.
    // Parametrized over the area's origin — LESSONS.md "Layout helpers
    // must return coords in the same frame across backends".
    // This harness already subtracts `area.y` before calling `hit_test`
    // (tree-local coords), but every pre-existing call site used
    // `Rect::new(0, 0, ...)`, so the subtraction was never exercised with
    // a non-zero value. Re-run at a non-zero origin to close that gap.
    fn clicks_land_on_painted_row_at(origin_x: u16, origin_y: u16) {
        let area = Rect::new(origin_x, origin_y, 30, 8);
        let mut buf = Buffer::empty(area);
        let tree = long_tree(5);
        let layout = paint_then_layout(&mut buf, area, &tree, &Theme::default(), false);

        for visible in &layout.visible_rows {
            let needle = tree.rows[visible.row_idx]
                .text
                .spans
                .first()
                .map(|s| s.text.clone())
                .unwrap_or_default();
            let painted_y = find_row_with(&buf, &needle)
                .unwrap_or_else(|| panic!("row {} ({:?}) not painted", visible.row_idx, needle));
            // TreeView hit_test takes tree-local coords (origin at 0,0).
            let local_y = (painted_y - area.y) as f32;
            let hit = layout.hit_test(0.5, local_y);
            // Accept Chevron or Row — both carry the row index.
            let hit_idx = match hit {
                TreeViewHit::Row(idx) | TreeViewHit::Chevron(idx) => idx,
                other => panic!(
                    "row {} ({:?}) painted at y={} but hit_test returned {:?}",
                    visible.row_idx, needle, painted_y, other
                ),
            };
            assert_eq!(
                hit_idx, visible.row_idx,
                "row {} ({:?}) painted at y={} but hit_test pointed to row {}",
                visible.row_idx, needle, painted_y, hit_idx
            );
        }
    }

    #[test]
    fn clicks_land_on_painted_row() {
        clicks_land_on_painted_row_at(0, 0);
    }

    /// The same paint + hit_test round trip must hold when the tree
    /// isn't painted at the screen origin — exercises the `local_y =
    /// painted_y - area.y` subtraction with a non-zero `area.y`.
    #[test]
    fn clicks_land_on_painted_row_at_nonzero_origin() {
        clicks_land_on_painted_row_at(7, 13);
    }

    /// Click below the last visible row returns Empty.
    #[test]
    fn click_below_last_row_returns_empty() {
        let area = Rect::new(0, 0, 30, 8);
        let mut buf = Buffer::empty(area);
        // 2 rows in an 8-row viewport leaves 6 rows of empty space.
        let tree = long_tree(2);
        let layout = paint_then_layout(&mut buf, area, &tree, &Theme::default(), false);
        let hit = layout.hit_test(0.5, 5.0); // y=5, well below the 2 painted rows
        assert!(
            matches!(hit, TreeViewHit::Empty),
            "click at y=5 below last row returned {:?}",
            hit
        );
    }

    /// With `scroll_offset > 0`, painted row 0 must be `tree.rows[scroll_offset]`,
    /// and clicking it must return `Row(scroll_offset)` — NOT `Row(0)`.
    /// This is the bug class where paint advances by scroll_offset but
    /// click forgets, or vice versa.
    #[test]
    fn scroll_offset_paint_and_click_agree() {
        let area = Rect::new(0, 0, 30, 4);
        let mut buf = Buffer::empty(area);
        let mut tree = long_tree(10);
        tree.scroll_offset = 3;
        let layout = paint_then_layout(&mut buf, area, &tree, &Theme::default(), false);

        // Painted row 0 should be `tree.rows[3]` ("item-03").
        let painted_y = find_row_with(&buf, "item-03")
            .expect("scroll_offset=3 should make row 0 paint as 'item-03'");
        let local_y = (painted_y - area.y) as f32;
        let hit = layout.hit_test(0.5, local_y);
        assert!(
            matches!(hit, TreeViewHit::Row(3)),
            "scroll_offset=3: row painted as 'item-03' at y={}; expected Row(3), got {:?}",
            painted_y,
            hit
        );

        // Painted row 0 should NOT be the original "item-00" — that one
        // is scrolled out and shouldn't appear in the buffer at all.
        assert!(
            find_row_with(&buf, "item-00").is_none(),
            "item-00 should be scrolled out under scroll_offset=3 but appears in buffer"
        );
    }

    /// Header rows (Decoration::Header) and leaf rows are equally
    /// hit-testable. Mixed-row trees should round-trip cleanly across
    /// every visible row regardless of decoration.
    #[test]
    fn header_and_leaf_rows_both_hit_testable() {
        let area = Rect::new(0, 0, 30, 6);
        let mut buf = Buffer::empty(area);
        let tree = TreeView {
            id: WidgetId::new("mixed"),
            rows: vec![
                TreeRow {
                    path: vec![0],
                    indent: 0,
                    text: StyledText {
                        spans: vec![StyledSpan::plain("CHANGES")],
                    },
                    icon: None,
                    badge: None,
                    is_expanded: Some(true),
                    decoration: Decoration::Header,
                    edit: None,
                },
                row(&[0, 0], 1, "alpha", None),
                row(&[0, 1], 1, "beta", None),
            ],
            selection_mode: crate::types::SelectionMode::default(),
            selected_path: None,
            scroll_offset: 0,
            has_focus: false,
            style: TreeStyle::default(),
        };
        let layout = paint_then_layout(&mut buf, area, &tree, &Theme::default(), false);

        for (expected_idx, needle) in [(0usize, "CHANGES"), (1, "alpha"), (2, "beta")] {
            let painted_y =
                find_row_with(&buf, needle).unwrap_or_else(|| panic!("row {needle:?} not painted"));
            let local_y = (painted_y - area.y) as f32;
            let hit = layout.hit_test(0.5, local_y);
            // Accept both Row and Chevron — the test verifies row identity.
            let hit_idx = match hit {
                TreeViewHit::Row(idx) | TreeViewHit::Chevron(idx) => idx,
                other => panic!(
                    "row {needle:?} painted at y={painted_y}: expected Row/Chevron({expected_idx}), got {other:?}"
                ),
            };
            assert_eq!(
                hit_idx, expected_idx,
                "row {needle:?} painted at y={painted_y}: expected idx={expected_idx}, got {hit_idx}"
            );
        }
    }

    // ── Chevron hit-test tests ──────────────────────────────────────
    //
    // These tests verify the split hit-region contract: clicking in the
    // leftmost cells of a branch row returns Chevron(idx); clicking to
    // the right (past the painted chevron) returns Row(idx); leaf rows
    // always return Row regardless of x position.

    /// Clicking in the chevron region of a branch row emits Chevron(idx).
    /// Default TreeStyle: indent=2, chevron_expanded='â–¾' (1 char) + 1
    /// space = chevron_end_x=2. So x=0 and x=1 are Chevron, x=2 is Row.
    #[test]
    fn chevron_click_on_branch_returns_chevron_hit() {
        let area = Rect::new(0, 0, 30, 5);
        let tree = TreeView {
            id: WidgetId::new("t"),
            rows: vec![
                row(&[0], 0, "src", Some(true)),  // branch, expanded
                row(&[0, 0], 1, "main.rs", None), // leaf
            ],
            selection_mode: crate::types::SelectionMode::default(),
            selected_path: None,
            scroll_offset: 0,
            has_focus: false,
            style: TreeStyle::default(),
        };
        let layout = tui_tree_layout(&tree, area);
        // indent=0, chevron='▾'(1 char)+1 space → chevron_end_x = 2.0
        // x=0 is inside [0, 2) → Chevron
        let hit = layout.hit_test(0.0, 0.0);
        assert!(
            matches!(hit, TreeViewHit::Chevron(0)),
            "x=0 on branch row 0 should return Chevron(0), got {:?}",
            hit
        );
        let hit2 = layout.hit_test(1.5, 0.0);
        assert!(
            matches!(hit2, TreeViewHit::Chevron(0)),
            "x=1.5 on branch row 0 should return Chevron(0), got {:?}",
            hit2
        );
    }

    /// Clicking past the chevron (in the body region) returns Row(idx).
    #[test]
    fn body_click_on_branch_returns_row_hit() {
        let area = Rect::new(0, 0, 30, 5);
        let tree = TreeView {
            id: WidgetId::new("t"),
            rows: vec![row(&[0], 0, "src", Some(true))],
            selection_mode: crate::types::SelectionMode::default(),
            selected_path: None,
            scroll_offset: 0,
            has_focus: false,
            style: TreeStyle::default(),
        };
        let layout = tui_tree_layout(&tree, area);
        // chevron_end_x = 2.0 → x >= 2.0 is Row region
        let hit = layout.hit_test(5.0, 0.0);
        assert!(
            matches!(hit, TreeViewHit::Row(0)),
            "x=5 past chevron should return Row(0), got {:?}",
            hit
        );
    }

    /// Clicking anywhere on a leaf row returns Row(idx).
    #[test]
    fn leaf_click_always_returns_row_hit() {
        let area = Rect::new(0, 0, 30, 5);
        let tree = TreeView {
            id: WidgetId::new("t"),
            rows: vec![row(&[0], 0, "main.rs", None)],
            selection_mode: crate::types::SelectionMode::default(),
            selected_path: None,
            scroll_offset: 0,
            has_focus: false,
            style: TreeStyle::default(),
        };
        let layout = tui_tree_layout(&tree, area);
        for x in [0.0_f32, 0.5, 1.0, 5.0, 15.0] {
            let hit = layout.hit_test(x, 0.0);
            assert!(
                matches!(hit, TreeViewHit::Row(0)),
                "leaf click at x={x} should return Row(0), got {:?}",
                hit
            );
        }
    }

    /// Header rows with is_expanded=Some(_) also get chevron split.
    #[test]
    fn header_branch_chevron_click_returns_chevron() {
        let area = Rect::new(0, 0, 30, 5);
        let tree = TreeView {
            id: WidgetId::new("t"),
            rows: vec![TreeRow {
                path: vec![0],
                indent: 0,
                text: StyledText {
                    spans: vec![StyledSpan::plain("CHANGES")],
                },
                icon: None,
                badge: None,
                is_expanded: Some(false),
                decoration: Decoration::Header,
                edit: None,
            }],
            selection_mode: crate::types::SelectionMode::default(),
            selected_path: None,
            scroll_offset: 0,
            has_focus: false,
            style: TreeStyle::default(),
        };
        let layout = tui_tree_layout(&tree, area);
        let hit = layout.hit_test(0.0, 0.0);
        assert!(
            matches!(hit, TreeViewHit::Chevron(0)),
            "header branch at x=0 should return Chevron(0), got {:?}",
            hit
        );
        // Body region is Row.
        let hit_body = layout.hit_test(10.0, 0.0);
        assert!(
            matches!(hit_body, TreeViewHit::Row(0)),
            "header branch body at x=10 should return Row(0), got {:?}",
            hit_body
        );
    }

    // ── Inline editing paint tests ──────────────────────────────────

    use crate::primitives::tree::TreeRowEditState;

    #[test]
    fn editing_row_shows_edit_text_not_original() {
        let area = Rect::new(0, 0, 30, 5);
        let mut buf = Buffer::empty(area);
        let mut tree = make_tree();
        // Put the second row (main.rs) into editing mode with different text.
        tree.rows[1].edit = Some(TreeRowEditState {
            text: "renamed.rs".into(),
            cursor: 10,
            selection_anchor: None,
            placeholder: None,
        });
        draw_tree(&mut buf, area, &tree, &Theme::default(), false);

        // "renamed.rs" should appear.
        assert!(
            find_row_with(&buf, "renamed.rs").is_some(),
            "editing row should show 'renamed.rs'"
        );
        // The original "main.rs" text should NOT appear on that row.
        // (find_row_with searches all rows, "main.rs" shouldn't be on any.)
        assert!(
            find_row_with(&buf, "main.rs").is_none(),
            "original label 'main.rs' should be replaced by edit text"
        );
    }

    #[test]
    fn editing_row_cursor_is_inverted() {
        let area = Rect::new(0, 0, 30, 3);
        let mut buf = Buffer::empty(area);
        let tree = TreeView {
            id: WidgetId::new("t"),
            rows: vec![TreeRow {
                path: vec![0],
                indent: 0,
                text: StyledText::plain("old"),
                icon: None,
                badge: None,
                is_expanded: None,
                decoration: Decoration::Normal,
                edit: Some(TreeRowEditState {
                    text: "ab".into(),
                    cursor: 2, // cursor at end (on the space after 'b')
                    selection_anchor: None,
                    placeholder: None,
                }),
            }],
            selection_mode: crate::types::SelectionMode::default(),
            selected_path: None,
            scroll_offset: 0,
            has_focus: false,
            style: TreeStyle::default(),
        };
        let theme = Theme::default();
        draw_tree(&mut buf, area, &tree, &theme, false);
        // The leaf has indent=0, no icon, no chevron → 2-cell gap then edit text.
        // Edit text "ab" at cols 2,3. Cursor at byte 2 → char index 2 → col 4.
        // Cursor cell should have inverted fg/bg.
        let row_bg = ratatui_color(theme.tab_bar_bg);
        let row_fg = ratatui_color(theme.foreground);
        let cursor_cell = &buf[(area.x + 4, 0u16)];
        assert_eq!(
            cursor_cell.fg, row_bg,
            "cursor cell fg should be the row bg (inverted)"
        );
        assert_eq!(
            cursor_cell.bg, row_fg,
            "cursor cell bg should be the row fg (inverted)"
        );
    }
}

/// Multi-select keyboard wiring over [`crate::tui::testing::TuiDriver`].
///
/// `TreeView` stays purely declarative — selection state lives on the app,
/// keyed by flattened-row index, and [`selected_paths_for_indices`] maps
/// that index set back to `TreePath`s before it's reported. TUI has no
/// mouse, so unlike the click-driven `crate::gtk::tree`/`crate::win::tree`
/// counterparts, a plain Up/Down only moves the keyboard cursor; Shift+Up/
/// Down extends a range from the anchor via
/// [`SelectionGesture::from_modifiers`], and Space toggles the cursor row
/// without moving it.
#[cfg(test)]
mod multi_select_driver_tests {
    use crate::primitives::tree::{selected_paths_for_indices, TreeRow, TreeView};
    use crate::runner::{AppLogic, Reaction};
    use crate::tui::testing::TuiDriver;
    use crate::{
        apply_selection_gesture, Backend, Decoration, Key, Modifiers, NamedKey, Rect,
        SelectionGesture, SelectionMode, StyledText, TreeEvent, TreePath, TreeStyle, UiEvent,
        WidgetId,
    };

    const VIEWPORT_W: u16 = 40;
    const VIEWPORT_H: u16 = 10;

    fn leaf(idx: u16, label: &str) -> TreeRow {
        TreeRow {
            path: vec![idx],
            indent: 0,
            icon: None,
            text: StyledText::plain(label.to_string()),
            badge: None,
            is_expanded: None,
            decoration: Decoration::Normal,
            edit: None,
        }
    }

    fn sample_tree() -> TreeView {
        TreeView {
            id: WidgetId::new("t"),
            rows: (0..5).map(|i| leaf(i, &format!("row {i}"))).collect(),
            selection_mode: SelectionMode::Multi,
            selected_path: None,
            scroll_offset: 0,
            style: TreeStyle::default(),
            has_focus: true,
        }
    }

    struct TreeApp {
        tree: TreeView,
        cursor: usize,
        selected: Vec<usize>,
        anchor: usize,
        events: Vec<TreeEvent>,
    }

    impl TreeApp {
        fn new() -> Self {
            Self {
                tree: sample_tree(),
                cursor: 0,
                selected: Vec::new(),
                anchor: 0,
                events: Vec::new(),
            }
        }

        fn selected_paths(&self) -> Vec<TreePath> {
            selected_paths_for_indices(&self.tree.rows, &self.selected)
        }
    }

    impl AppLogic for TreeApp {
        type AreaId = ();

        fn render(&self, backend: &mut dyn Backend, _area: ()) {
            backend.draw_tree(
                Rect::new(0.0, 0.0, VIEWPORT_W as f32, VIEWPORT_H as f32),
                &self.tree,
            );
        }

        fn handle(&mut self, event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
            let UiEvent::KeyPressed { key, modifiers, .. } = event else {
                return Reaction::Continue;
            };
            let last = self.tree.rows.len().saturating_sub(1);
            match key {
                Key::Named(NamedKey::Down) | Key::Named(NamedKey::Up) => {
                    let delta: isize = if key == Key::Named(NamedKey::Down) {
                        1
                    } else {
                        -1
                    };
                    self.cursor = (self.cursor as isize + delta).clamp(0, last as isize) as usize;
                    if !modifiers.shift {
                        // A plain move repositions the cursor only; the
                        // selection changes explicitly via Space/Shift.
                        return Reaction::Redraw;
                    }
                    let indices = apply_selection_gesture(
                        &self.selected,
                        self.anchor,
                        self.cursor,
                        SelectionGesture::Range,
                    );
                    self.selected = indices;
                    let paths = self.selected_paths();
                    self.events.push(TreeEvent::SelectionSet { paths });
                    Reaction::Redraw
                }
                Key::Char(' ') => {
                    let indices = apply_selection_gesture(
                        &self.selected,
                        self.anchor,
                        self.cursor,
                        SelectionGesture::Toggle,
                    );
                    self.selected = indices;
                    self.anchor = self.cursor;
                    let paths = self.selected_paths();
                    self.events.push(TreeEvent::SelectionSet { paths });
                    Reaction::Redraw
                }
                _ => Reaction::Continue,
            }
        }
    }

    fn key_event(key: Key, modifiers: Modifiers) -> UiEvent {
        UiEvent::KeyPressed {
            key,
            modifiers,
            repeat: false,
        }
    }

    fn driver() -> TuiDriver<TreeApp> {
        TuiDriver::new(TreeApp::new(), VIEWPORT_W, VIEWPORT_H)
    }

    #[test]
    fn plain_arrow_moves_the_cursor_without_changing_selection() {
        let mut driver = driver();
        driver.dispatch(key_event(Key::Named(NamedKey::Down), Modifiers::default()));
        assert_eq!(driver.app().cursor, 1);
        assert_eq!(driver.app().selected, Vec::<usize>::new());
    }

    #[test]
    fn space_toggles_rows_into_a_multi_selection() {
        let mut driver = driver();
        driver.dispatch(key_event(Key::Char(' '), Modifiers::default()));
        driver.dispatch(key_event(Key::Named(NamedKey::Down), Modifiers::default()));
        driver.dispatch(key_event(Key::Named(NamedKey::Down), Modifiers::default()));
        driver.dispatch(key_event(Key::Char(' '), Modifiers::default()));
        assert_eq!(driver.app().selected_paths(), vec![vec![0], vec![2]]);
        // Space toggles the same row back off.
        driver.dispatch(key_event(Key::Named(NamedKey::Up), Modifiers::default()));
        driver.dispatch(key_event(Key::Named(NamedKey::Up), Modifiers::default()));
        driver.dispatch(key_event(Key::Char(' '), Modifiers::default()));
        assert_eq!(driver.app().selected_paths(), vec![vec![2]]);
        assert_eq!(
            driver.app().events.last(),
            Some(&TreeEvent::SelectionSet {
                paths: vec![vec![2]]
            })
        );
    }

    #[test]
    fn shift_arrow_extends_a_range_from_the_anchor() {
        let mut driver = driver();
        driver.dispatch(key_event(Key::Char(' '), Modifiers::default()));
        let shift = Modifiers {
            shift: true,
            ..Default::default()
        };
        driver.dispatch(key_event(Key::Named(NamedKey::Down), shift));
        driver.dispatch(key_event(Key::Named(NamedKey::Down), shift));
        driver.dispatch(key_event(Key::Named(NamedKey::Down), shift));
        assert_eq!(
            driver.app().selected_paths(),
            vec![vec![0], vec![1], vec![2], vec![3]]
        );
        assert_eq!(
            driver.app().events.last(),
            Some(&TreeEvent::SelectionSet {
                paths: vec![vec![0], vec![1], vec![2], vec![3]]
            })
        );
    }
}