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
//! Direct2D / DirectWrite rasteriser for [`crate::ListView`].
//!
//! Content painting (background, title, rows, h/v scrollbars) is shared via
//! [`crate::primitives::list::native_surface_paint::paint`] — see that fn's
//! module doc for what's shared and what stays per-backend. This module owns
//! the [`ListView::bordered`] frame itself: a plain (square-cornered) 1-DIP
//! rectangle border painted *after* the shared content paint. Painting the
//! border after, not before, matters: the shared `paint` unconditionally fills
//! the whole rect with `base_bg` as its first operation, which would erase a
//! border drawn beforehand.
//!
//! [`win_list_layout`] itself needs no Direct2D/DirectWrite type — it's pure
//! geometry over [`crate::primitives::layout_metrics::list_layout`], same as
//! `mac_list_layout` / `gtk_list_layout` — so only [`draw_list`] (the actual
//! Direct2D paint entry point) is `#[cfg(target_os = "windows")]`-gated;
//! `win_list_layout` compiles and runs everywhere. See `super::mod`'s `mod list;`
//! and `backend.rs`'s module docs. See `win::status_bar`'s module doc for why
//! colours come from `Theme::default()` rather than a live `WinBackend` theme field.
//!
//! # Scope for #26
//!
//! `bordered` lists get a plain (square-cornered) 1-DIP rectangle border rather
//! than GTK's rounded-rect stroke — Direct2D's rounded rectangle would need a
//! second brush/geometry path for no visual contract this issue depends on.
//! Nerd-Font icon glyphs are not distinguished from ASCII fallbacks — see
//! `win::tree`'s module doc for why.
//!
//! # H-scrollbar row reservation now shared
//!
//! [`win_list_layout`] now reserves a bottom row for an h-scrollbar by routing
//! through [`crate::primitives::layout_metrics::list_layout`] (with `border_inset`
//! derived from [`ListView::bordered`], matching [`BORDER_DIP`]), matching
//! `gtk_list_layout` / `mac_list_layout`. Windows now reserves the same row every
//! other pixel backend does, and [`draw_list`] passes `supports_hscrollbar: true`
//! to the shared paint to match.

use crate::event::Rect;
use crate::primitives::list::{ListView, ListViewLayout};

/// Border thickness (DIPs) for a `bordered` list — matches the 1-unit
/// inset [`ListView::layout`] itself bakes in for bordered lists, and
/// the `border_inset` [`win_list_layout`] passes to
/// [`crate::primitives::layout_metrics::list_layout`].
const BORDER_DIP: f32 = 1.0;

/// Compute a [`ListView`]'s layout without painting — the DirectWrite twin of
/// [`draw_list`]'s internal layout call. Pure geometry (no Direct2D/DirectWrite
/// type in its signature), so unlike [`draw_list`], this is not
/// `target_os = "windows"`-gated; see this module's doc.
///
/// `char_width` is used only for the h-scrollbar-overflow threshold check
/// (`ListView::max_content_width` is in character columns); pass a live
/// `DWrite`-measured glyph width when painting (see [`draw_list`]), or
/// [`crate::backend::Backend::char_width`]'s cached value for a no-paint layout,
/// matching every other pixel backend's `Backend::list_layout`.
/// ```text
/// $ grep -rn 'win_list_layout\|win_data_table_layout\|win_menu_bar_layout\|win_status_bar_layout\|win_spinner_layout\|win_toast_stack_layout\|win_tab_bar_layout\|win_tab_bar_layout_icons\|win_tab_bar_native_layout\|win_tab_bar_native_layout_icons' \
///     ~/src/coord-tui/src ~/src/vimcode/src
/// (no output — zero hits in both, for every symbol above)
/// ```
///
/// Both consumers reach the Win-GUI backend only through the `Backend`
/// trait (`WinBackend`) or `quadraui::win::shell_runner::run_with_shell` /
/// `quadraui::win::testing::driver_with_shell` — neither calls any raw
/// `win::*_layout` free function directly. Changing this signature is a
/// no-op for both today.
pub fn win_list_layout(
    list: &ListView,
    rect: Rect,
    line_height: f32,
    char_width: f32,
) -> ListViewLayout {
    let border_inset = if list.bordered {
        BORDER_DIP as f64
    } else {
        0.0
    };
    crate::primitives::layout_metrics::list_layout(
        list,
        rect.width as f64,
        rect.height as f64,
        line_height as f64,
        char_width as f64,
        border_inset,
    )
}

/// Draw a [`ListView`] into `rect` (DIPs) on `target`. Returns the resolved
/// [`ListViewLayout`] for host click dispatch (list-local coordinates, matching
/// every other backend's `draw_list` contract).
///
/// # Visual contract
///
/// - **Background:** `Theme::surface_bg` when `bordered`, else
///   `Theme::background`.
/// - **Selected row:** `Theme::selected_bg`.
/// - **Header-decorated row:** `Theme::header_bg` / `header_fg`.
/// - **Muted / Error / Warning rows:** `muted_fg` / `error_fg` / `warning_fg`
///   on the row's own background.
/// - **Detail span:** right-aligned in `muted_fg`, skipped when there isn't
///   room past the main text.
/// - **Vertical scrollbar:** painted via
///   [`crate::primitives::scrollbar::native_surface_paint::paint`] when
///   [`ListView::show_v_scrollbar`] calls for one.
#[cfg(target_os = "windows")]
pub fn draw_list(
    target: &windows::Win32::Graphics::Direct2D::ID2D1RenderTarget,
    dwrite: &super::text::DWrite,
    rect: Rect,
    list: &ListView,
    line_height: f32,
) -> ListViewLayout {
    use super::text::fill_rect;
    use crate::theme::Theme;

    let theme = Theme::default();
    let char_width = dwrite
        .measure_text("M")
        .map(|(w, _)| w)
        .unwrap_or(0.0)
        .max(1.0);
    let layout = win_list_layout(list, rect, line_height, char_width);

    let mut surface = super::surface::D2dSurface {
        target,
        dwrite: Some(dwrite),
    };
    crate::primitives::list::native_surface_paint::paint(
        list,
        rect,
        &layout,
        line_height,
        // Nerd-Font icon glyphs: this rasteriser has never distinguished
        // `Icon::glyph` from `Icon::fallback` (unlike `win::tree`, wired
        // in #804) — extending it is separate, unstarted scope (see this
        // module's doc). `false` preserves that exactly.
        /* nerd_fonts_enabled */
        false,
        /* supports_border */ true,
        // `win_list_layout` now reserves the h-scrollbar row via
        // the shared `layout_metrics::list_layout`, so painting one here
        // when it's needed matches the reservation instead of leaving an
        // unlabeled blank row.
        /* supports_hscrollbar */
        true,
        &mut surface,
        &theme,
    );

    // The `bordered` frame is drawn *after* the shared content paint so it
    // isn't erased by `native_surface_paint::paint`'s own initial full-`rect`
    // background fill (`surface_fill_rect(area, base_bg)`, `primitives/list.rs`).
    // This order mirrors `gtk::list::draw_list`, which strokes its border after
    // the content paint for the same reason.
    if list.bordered {
        let br = theme.border_fg;
        let _ = fill_rect(
            target,
            Rect::new(rect.x, rect.y, rect.width, BORDER_DIP),
            br,
        );
        let _ = fill_rect(
            target,
            Rect::new(
                rect.x,
                rect.y + rect.height - BORDER_DIP,
                rect.width,
                BORDER_DIP,
            ),
            br,
        );
        let _ = fill_rect(
            target,
            Rect::new(rect.x, rect.y, BORDER_DIP, rect.height),
            br,
        );
        let _ = fill_rect(
            target,
            Rect::new(
                rect.x + rect.width - BORDER_DIP,
                rect.y,
                BORDER_DIP,
                rect.height,
            ),
            br,
        );
    }

    layout
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{Decoration, StyledText, WidgetId};

    const W: f32 = 200.0;
    const H: f32 = 100.0;
    const LINE_HEIGHT: f32 = 14.0;
    const CHAR_WIDTH: f32 = 8.0;

    fn item(label: &str) -> crate::primitives::list::ListItem {
        crate::primitives::list::ListItem {
            text: StyledText::plain(label.to_string()),
            icon: None,
            detail: None,
            decoration: Decoration::Normal,
        }
    }

    fn make_list(items: Vec<crate::primitives::list::ListItem>) -> ListView {
        ListView {
            id: WidgetId::new("list"),
            title: None,
            items,
            selected_idx: 0,
            scroll_offset: 0,
            has_focus: true,
            bordered: false,
            h_scroll: 0,
            max_content_width: None,
            show_v_scrollbar: false,
        }
    }

    fn make_bordered_list(items: Vec<crate::primitives::list::ListItem>) -> ListView {
        ListView {
            id: WidgetId::new("list"),
            title: None,
            items,
            selected_idx: 0,
            scroll_offset: 0,
            has_focus: true,
            bordered: true,
            h_scroll: 0,
            max_content_width: None,
            show_v_scrollbar: false,
        }
    }

    /// `win_list_layout` must apply the exact same `border_inset`
    /// [`crate::primitives::layout_metrics::list_layout`] would given
    /// [`BORDER_DIP`] — this ensures both functions agree on the bordered list's
    /// layout. Runs on Linux: no Direct2D/DirectWrite type involved.
    #[test]
    fn win_list_layout_matches_layout_metrics_list_layout_border_inset() {
        let list = make_bordered_list(vec![item("alpha"), item("beta"), item("gamma")]);
        let rect = Rect::new(0.0, 0.0, W, H);

        let via_win = win_list_layout(&list, rect, LINE_HEIGHT, CHAR_WIDTH);
        let via_shared = crate::primitives::layout_metrics::list_layout(
            &list,
            W as f64,
            H as f64,
            LINE_HEIGHT as f64,
            CHAR_WIDTH as f64,
            BORDER_DIP as f64,
        );

        assert_eq!(
            via_win, via_shared,
            "win_list_layout must delegate to layout_metrics::list_layout \
             with border_inset == BORDER_DIP for a bordered list"
        );
    }

    /// Same invariant for the unbordered case (`border_inset` must be
    /// `0.0`), and a sanity check that the two differ from each other —
    /// otherwise the assertion above could pass for the wrong reason
    /// (both layouts ignoring the inset).
    #[test]
    fn win_list_layout_unbordered_has_no_inset_and_differs_from_bordered() {
        let bordered = make_bordered_list(vec![item("alpha"), item("beta")]);
        let unbordered = make_list(vec![item("alpha"), item("beta")]);
        let rect = Rect::new(0.0, 0.0, W, H);

        let via_win_unbordered = win_list_layout(&unbordered, rect, LINE_HEIGHT, CHAR_WIDTH);
        let via_shared_unbordered = crate::primitives::layout_metrics::list_layout(
            &unbordered,
            W as f64,
            H as f64,
            LINE_HEIGHT as f64,
            CHAR_WIDTH as f64,
            0.0,
        );
        assert_eq!(via_win_unbordered, via_shared_unbordered);

        let via_win_bordered = win_list_layout(&bordered, rect, LINE_HEIGHT, CHAR_WIDTH);
        assert_ne!(
            via_win_unbordered.visible_items[0].bounds, via_win_bordered.visible_items[0].bounds,
            "a bordered list must actually inset its rows relative to an \
             unbordered one"
        );
    }

    /// An overflowing `max_content_width` must reserve the bottom row for an
    /// h-scrollbar, exactly like `mac_list_layout` / `gtk_list_layout`.
    #[test]
    fn win_list_layout_reserves_hscrollbar_row_when_content_overflows() {
        let mut list = make_list((0..12).map(|i| item(&format!("row-{i}"))).collect());
        list.max_content_width = Some(1000); // guarantees overflow at any sane char_width
        let rect = Rect::new(0.0, 0.0, W, H);

        let overflowing = win_list_layout(&list, rect, LINE_HEIGHT, CHAR_WIDTH);
        list.max_content_width = None;
        let fitting = win_list_layout(&list, rect, LINE_HEIGHT, CHAR_WIDTH);

        assert!(
            overflowing.visible_items.len() < fitting.visible_items.len(),
            "an overflowing max_content_width must reserve a row, leaving \
             fewer visible items than the non-overflowing layout"
        );
    }

    #[cfg(target_os = "windows")]
    mod windows_only {
        use super::*;
        use crate::primitives::list::ListViewHit;
        use crate::win::testing::HeadlessSurface;
        use crate::win::text::DWrite;

        /// Paint↔click round trip: the selected row's background must be
        /// painted at its own bounds, and clicking each visible row's
        /// centre must hit_test back to that row.
        #[test]
        fn paint_and_hit_test_round_trip() {
            let surface = HeadlessSurface::new(W as u32, H as u32).expect("create surface");
            let (dwrite, _, _) = DWrite::new("Segoe UI", 10.0, None).expect("create DWrite");
            let list = make_list(vec![item("alpha"), item("beta"), item("gamma")]);
            let rect = Rect::new(0.0, 0.0, W, H);

            let layout = surface
                .paint(|target| {
                    draw_list(target, &dwrite, rect, &list, LINE_HEIGHT);
                })
                .map(|_| win_list_layout(&list, rect, LINE_HEIGHT, CHAR_WIDTH))
                .expect("paint list");

            assert_eq!(layout.visible_items.len(), 3);
            for vis in &layout.visible_items {
                let hit = layout.hit_test(
                    vis.bounds.x + vis.bounds.width / 2.0,
                    vis.bounds.y + vis.bounds.height / 2.0,
                );
                assert_eq!(hit, ListViewHit::Item(vis.item_idx));
            }

            let theme = crate::theme::Theme::default();
            let sel_bounds = layout.visible_items[0].bounds;
            let px = surface.pixel_at((sel_bounds.x + 1.0) as u32, (sel_bounds.y + 1.0) as u32);
            assert_eq!(
                (px.r, px.g, px.b),
                (
                    theme.selected_bg.r,
                    theme.selected_bg.g,
                    theme.selected_bg.b
                ),
                "selected row (idx 0) should paint selected_bg at its own bounds"
            );
        }

        /// Scroll-offset round trip.
        #[test]
        fn scroll_offset_paint_and_click_agree() {
            let mut list = make_list((0..6).map(|i| item(&format!("row-{i}"))).collect());
            list.scroll_offset = 2;
            let rect = Rect::new(0.0, 0.0, W, H);
            let layout = win_list_layout(&list, rect, LINE_HEIGHT, CHAR_WIDTH);
            let first = layout.visible_items.first().expect("has items");
            assert_eq!(first.item_idx, 2);
            let hit = layout.hit_test(
                first.bounds.x + 5.0,
                first.bounds.y + first.bounds.height / 2.0,
            );
            assert_eq!(hit, ListViewHit::Item(2));
        }

        /// A click below the last item returns `Empty`.
        #[test]
        fn click_below_last_item_returns_empty() {
            let list = make_list(vec![item("a"), item("b")]);
            let rect = Rect::new(0.0, 0.0, W, H);
            let layout = win_list_layout(&list, rect, LINE_HEIGHT, CHAR_WIDTH);
            let last = layout.visible_items.last().expect("has items");
            let hit = layout.hit_test(10.0, last.bounds.y + last.bounds.height + 5.0);
            assert_eq!(hit, ListViewHit::Empty);
        }

        /// No-paint layout must agree byte-for-byte with what `draw_list`
        /// painted, including a title row.
        #[test]
        fn no_paint_layout_matches_paint_layout() {
            let mut list = make_list(vec![item("alpha"), item("beta")]);
            list.title = Some(StyledText::plain("Files"));
            let rect = Rect::new(0.0, 0.0, W, H);
            let (dwrite, _, _) = DWrite::new("Segoe UI", 10.0, None).expect("create DWrite");
            let surface = HeadlessSurface::new(W as u32, H as u32).expect("create surface");

            let painted = surface
                .paint(|target| {
                    draw_list(target, &dwrite, rect, &list, LINE_HEIGHT);
                })
                .map(|_| {
                    let char_width = dwrite
                        .measure_text("M")
                        .map(|(w, _)| w)
                        .unwrap_or(0.0)
                        .max(1.0);
                    win_list_layout(&list, rect, LINE_HEIGHT, char_width)
                })
                .expect("paint");
            let char_width = dwrite
                .measure_text("M")
                .map(|(w, _)| w)
                .unwrap_or(0.0)
                .max(1.0);
            let no_paint = win_list_layout(&list, rect, LINE_HEIGHT, char_width);
            assert_eq!(painted, no_paint);
        }

        /// The vertical scrollbar's track and thumb are painted when
        /// [`ListView::show_v_scrollbar`] is true. This probes a pixel inside the
        /// resolved track rect to verify painting occurred.
        #[test]
        fn paints_vertical_scrollbar_track_when_enabled() {
            let mut list = make_list((0..30).map(|i| item(&format!("row-{i}"))).collect());
            list.show_v_scrollbar = true;
            let rect = Rect::new(0.0, 0.0, W, H);
            let expected = list
                .vscrollbar(rect, LINE_HEIGHT)
                .expect("30 rows in a 100px / 14px viewport must need a v-scrollbar");

            let (dwrite, _, _) = DWrite::new("Segoe UI", 10.0, None).expect("create DWrite");
            let surface = HeadlessSurface::new(W as u32, H as u32).expect("create surface");
            surface
                .paint(|target| {
                    draw_list(target, &dwrite, rect, &list, LINE_HEIGHT);
                })
                .expect("paint list");

            let theme = crate::theme::Theme::default();
            let probe_x = (expected.track.x + expected.track.width / 2.0) as u32;
            let probe_y = (expected.track.y + expected.track.height / 2.0) as u32;
            let px = surface.pixel_at(probe_x.min(W as u32 - 1), probe_y.min(H as u32 - 1));
            assert_ne!(
                (px.r, px.g, px.b),
                (theme.background.r, theme.background.g, theme.background.b),
                "expected the v-scrollbar track at ({probe_x}, {probe_y}) to be painted \
                 (non-background) — the #1075 regression this test guards"
            );
        }

        /// The `ListView::bordered` frame is drawn *after* the shared content
        /// paint, which unconditionally fills the whole `rect` with `base_bg` as its
        /// first operation. This test verifies all four edges still carry
        /// `theme.border_fg` after the shared paint has run.
        #[test]
        fn bordered_frame_survives_shared_content_paint() {
            let list = make_bordered_list(vec![item("alpha"), item("beta"), item("gamma")]);
            let rect = Rect::new(0.0, 0.0, W, H);

            let (dwrite, _, _) = DWrite::new("Segoe UI", 10.0, None).expect("create DWrite");
            let surface = HeadlessSurface::new(W as u32, H as u32).expect("create surface");
            surface
                .paint(|target| {
                    draw_list(target, &dwrite, rect, &list, LINE_HEIGHT);
                })
                .expect("paint list");

            let theme = crate::theme::Theme::default();
            let border = (theme.border_fg.r, theme.border_fg.g, theme.border_fg.b);
            let mid_x = (W / 2.0) as u32;
            let mid_y = (H / 2.0) as u32;

            let top = surface.pixel_at(mid_x, 0);
            let bottom = surface.pixel_at(mid_x, H as u32 - 1);
            let left = surface.pixel_at(0, mid_y);
            let right = surface.pixel_at(W as u32 - 1, mid_y);

            for (label, px) in [
                ("top", top),
                ("bottom", bottom),
                ("left", left),
                ("right", right),
            ] {
                assert_eq!(
                    (px.r, px.g, px.b),
                    border,
                    "{label} border edge should still be theme.border_fg after the shared \
                     content paint ran (#1075 review regression: the border was being \
                     painted before, then erased by native_surface_paint::paint's initial \
                     full-rect background fill)"
                );
            }
        }
    }
}

/// Multi-select click wiring over [`crate::win::testing::WinDriver`].
///
/// `ListView` 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 [`ListViewLayout::hit_test`], and derives the
/// gesture from the event's `Modifiers`. Mirrors `gtk::list`'s
/// `multi_select_driver_tests`, except `WinDriver` has no
/// `set_double_click_folding` toggle, so consecutive clicks that must stay
/// independent (rather than fold into a `DoubleClick`) are spaced more
/// than `WIN_DOUBLE_CLICK_RADIUS` DIPs apart on the x axis — row hit
/// testing only depends on y, so this keeps each click landing on its
/// intended row without tripping the shared `DoubleClickDetector`.
#[cfg(all(test, target_os = "windows"))]
mod multi_select_driver_tests {
    use crate::runner::{AppLogic, Reaction};
    use crate::win::testing::WinDriver;
    use crate::{
        apply_selection_gesture, Backend, Decoration, ListItem, ListItemMeasure, ListView,
        ListViewEvent, ListViewHit, Modifiers, MouseButton, Point, Rect, SelectionGesture,
        StyledText, UiEvent, WidgetId,
    };

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

    fn item(label: &str) -> ListItem {
        ListItem {
            text: StyledText::plain(label.to_string()),
            icon: None,
            detail: None,
            decoration: Decoration::Normal,
        }
    }

    fn sample_list() -> ListView {
        ListView {
            id: WidgetId::new("l"),
            title: None,
            items: (0..5).map(|i| item(&format!("row {i}"))).collect(),
            selected_idx: 0,
            scroll_offset: 0,
            has_focus: true,
            bordered: false,
            h_scroll: 0,
            max_content_width: None,
            show_v_scrollbar: false,
        }
    }

    struct ListApp {
        list: ListView,
        selected: Vec<usize>,
        anchor: usize,
        events: Vec<ListViewEvent>,
    }

    impl ListApp {
        fn new() -> Self {
            Self {
                list: sample_list(),
                selected: Vec::new(),
                anchor: 0,
                events: Vec::new(),
            }
        }
    }

    impl AppLogic for ListApp {
        type AreaId = ();

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

        fn handle(&mut self, event: UiEvent, _backend: &mut dyn Backend) -> Reaction {
            let UiEvent::MouseDown {
                position,
                modifiers,
                ..
            } = event
            else {
                return Reaction::Continue;
            };
            let layout = self
                .list
                .layout(VIEWPORT_W, VIEWPORT_H, 0.0, |_| ListItemMeasure::new(ROW_H));
            let ListViewHit::Item(idx) = layout.hit_test(position.x, position.y) else {
                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(ListViewEvent::SelectionSet { indices });
            Reaction::Redraw
        }
    }

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

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

    #[test]
    fn ctrl_click_toggles_rows_into_a_multi_selection() {
        let mut driver = WinDriver::new(ListApp::new(), 80, 40);
        driver.dispatch(mouse_down(2.0, 0.0, Modifiers::default()));
        let ctrl = Modifiers {
            ctrl: true,
            ..Default::default()
        };
        // x is spaced > WIN_DOUBLE_CLICK_RADIUS DIPs from the previous
        // click so the shared `DoubleClickDetector` doesn't fold these
        // back-to-back single clicks into a `DoubleClick`; y alone picks
        // the row.
        driver.dispatch(mouse_down(10.0, 2.0, ctrl));
        assert_eq!(driver.app().selected, vec![0, 2]);
        // Ctrl-click the same row again toggles it back off.
        driver.dispatch(mouse_down(18.0, 2.0, ctrl));
        assert_eq!(driver.app().selected, vec![0]);
        assert_eq!(
            driver.app().events.last(),
            Some(&ListViewEvent::SelectionSet { indices: vec![0] })
        );
    }

    #[test]
    fn shift_click_selects_the_range_from_the_anchor() {
        let mut driver = WinDriver::new(ListApp::new(), 80, 40);
        driver.dispatch(mouse_down(2.0, 0.0, Modifiers::default()));
        let shift = Modifiers {
            shift: true,
            ..Default::default()
        };
        driver.dispatch(mouse_down(10.0, 3.0, shift));
        assert_eq!(driver.app().selected, vec![0, 1, 2, 3]);
    }

    #[test]
    fn cmd_click_toggles_the_same_as_ctrl_click() {
        let mut driver = WinDriver::new(ListApp::new(), 80, 40);
        driver.dispatch(mouse_down(2.0, 1.0, Modifiers::default()));
        driver.dispatch(mouse_down(
            10.0,
            4.0,
            Modifiers {
                cmd: true,
                ..Default::default()
            },
        ));
        assert_eq!(driver.app().selected, vec![1, 4]);
    }
}