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
//! GTK rasteriser for [`crate::ListView`].
//!
//! Content painting (background, title, rows, h/v scrollbars) is in
//! the shared [`crate::primitives::list::native_surface_paint::paint`].
//! This module owns the [`ListView::bordered`] frame itself: a rounded-rectangle
//! clip + stroke (3px corner radius) around the shared content paint,
//! since no `PaintSurface` verb exists for a rounded stroke and GTK's
//! rounded frame is a real, documented visual divergence from Windows'
//! square one and macOS's absent one (see the shared `paint`'s module
//! doc).
//!
//! [`gtk_list_layout`] and the deprecated [`draw_list`] compatibility
//! shim live over the shared [`super::surface::CairoSurface`] adapter

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

use super::{cairo_rgb, rounded_rect_path};
use crate::primitives::list::{ListView, ListViewLayout};
use crate::theme::Theme;

/// Compute the GTK pixel-unit layout for a [`ListView`] without painting —
/// the same viewport reservation (border inset, h-scrollbar row)
/// [`draw_list`] applies internally before calling [`ListView::layout`].
/// `draw_list` calls this exact function (with its own live-measured
/// `char_width`) so paint and no-paint hit-testing can never drift apart
/// (`PRIMITIVE_RULES.md` rule 5).
///
/// The reservation math itself lives in
/// [`crate::primitives::layout_metrics::list_layout`] — shared
/// with `mac_list_layout` so both backends reserve the h-scrollbar row
/// identically instead of each carrying its own copy that can drift.
///
/// `char_width` is used only for the h-scrollbar-overflow threshold check
/// (`ListView::max_content_width` is in character columns); pass
/// [`crate::Backend::char_width`]'s cached value when no live
/// `pango::Layout` is available — the same approximation
/// `GtkBackend::list_hscrollbar` already uses for this exact check.
///
/// Coordinate frame: **LOCAL** — relative to `(0, 0)`, matching
/// `tui_list_layout` / `win_list_layout` / `mac_list_layout`. Does **not**
/// account for [`ListView::bordered`]'s 1px border inset — same as every
/// other backend's list-layout helper; a bordered list's caller adds that
/// inset itself (see `draw_list`'s `item_x_offset` / `item_y_offset`).
pub fn gtk_list_layout(
    w: f64,
    h: f64,
    list: &ListView,
    line_height: f64,
    char_width: f64,
) -> ListViewLayout {
    let border_inset: f64 = if list.bordered { 1.0 } else { 0.0 };
    crate::primitives::layout_metrics::list_layout(
        list,
        w,
        h,
        line_height,
        char_width,
        border_inset,
    )
}

/// Draw a [`ListView`] into `(x, y, w, h)` on `cr`.
///
/// Caller owns `layout`'s font choice — the rasteriser doesn't
/// switch fonts. `nerd_fonts_enabled` controls which icon variant
/// the consumer's icon registry exposes; pass `false` to always
/// use the ASCII fallback.
///
/// # Visual contract
///
/// - **Background:** [`Theme::background`] (matches the editor surface
///   the list is embedded in).
/// - **Optional title:** painted as a flat [`Theme::header_bg`] /
///   [`Theme::header_fg`] strip at the top.
/// - **Selected row:** [`Theme::selected_bg`] background and a `▶`
///   selection prefix.
/// - **Header decoration:** items with [`crate::types::Decoration::Header`]
///   use [`Theme::header_bg`] / [`Theme::header_fg`] (used by the source
///   control panel for section titles).
/// - **Per-item decoration → fg:** `Error → error_fg`, `Warning →
///   warning_fg`, `Muted → muted_fg`, `Header → header_fg`, others
///   → [`Theme::surface_fg`].
/// - **Detail span:** right-aligned in [`Theme::muted_fg`], skipped
///   when there isn't room past the main text.
/// - **Vertical / horizontal scrollbar:** painted via
///   [`crate::primitives::scrollbar::native_surface_paint::paint`] when
///   [`ListView::show_v_scrollbar`] / an overflowing
///   [`ListView::max_content_width`] call for one.
#[allow(clippy::too_many_arguments)]
pub fn draw_list(
    cr: &Context,
    layout: &pango::Layout,
    x: f64,
    y: f64,
    w: f64,
    h: f64,
    list: &ListView,
    theme: &Theme,
    line_height: f64,
    nerd_fonts_enabled: bool,
) {
    if w <= 0.0 || h <= 0.0 {
        return;
    }

    layout.set_attributes(None);

    // Measure a reference glyph for char-to-pixel conversion.  `h_scroll` is
    // expressed in character columns (same unit as TUI cells); GTK works in
    // pixels, so the shared paint multiplies by this before subtracting from
    // cursor_x — mirrored here only for `gtk_list_layout`'s own char-width
    // parameter, which must agree with what the shared paint measures.
    layout.set_text("M");
    let (cw_px, _) = layout.pixel_size();
    let char_w = cw_px.max(1) as f64;

    let list_layout = gtk_list_layout(w, h, list, line_height, char_w);

    if list.bordered {
        cr.save().ok();
        rounded_rect_path(cr, x, y, w, h, 3.0);
        cr.clip();
    }

    let area = crate::event::Rect::new(x as f32, y as f32, w as f32, h as f32);
    let mut surface = super::surface::CairoSurface {
        cr,
        layout: Some(layout),
        translucent_fill: true,
    };
    crate::primitives::list::native_surface_paint::paint(
        list,
        area,
        &list_layout,
        line_height as f32,
        nerd_fonts_enabled,
        /* supports_border */ true,
        /* supports_hscrollbar */ true,
        &mut surface,
        theme,
    );

    if list.bordered {
        cr.restore().ok();
        rounded_rect_path(cr, x + 0.5, y + 0.5, w - 1.0, h - 1.0, 3.0);
        let border_color = cairo_rgb(theme.border_fg);
        cr.set_source_rgb(border_color.0, border_color.1, border_color.2);
        cr.set_line_width(1.0);
        cr.stroke().ok();
    }

    layout.set_attributes(None);
}

// ── Tests ──────────────────────────────────────────────────────────────────
//
// This test paints through `draw_list` into a Cairo `ImageSurface`
// and probes a pixel inside the resolved v-scrollbar track rect.
#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::list::ListItem;
    use crate::types::{Color, Decoration, StyledText, WidgetId};
    use pangocairo::cairo::{Context, Format, ImageSurface};

    const W: i32 = 120;
    const H: i32 = 100;
    const LINE_HEIGHT: f64 = 10.0;

    fn test_theme() -> Theme {
        Theme {
            background: Color::rgb(255, 255, 255),
            surface_bg: Color::rgb(255, 255, 255),
            ..Theme::default()
        }
    }

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

    fn vlist(n: usize) -> ListView {
        ListView {
            id: WidgetId::new("l"),
            title: None,
            items: (0..n).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: true,
        }
    }

    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])
    }

    #[test]
    fn gtk_paints_vertical_scrollbar_track_when_enabled() {
        let list = vlist(30); // 30 rows in a 100px / 10px viewport overflow.
        let area = crate::event::Rect::new(0.0, 0.0, W as f32, H as f32);
        let expected = list
            .vscrollbar(area, LINE_HEIGHT as f32)
            .expect("30 rows in a 10-row viewport must need a v-scrollbar");

        let mut surface = ImageSurface::create(Format::ARgb32, W, H).expect("create ImageSurface");
        {
            let cr = Context::new(&surface).expect("Context::new");
            cr.set_source_rgb(1.0, 1.0, 1.0);
            cr.paint().ok();
            let pango_layout = pangocairo::functions::create_layout(&cr);
            draw_list(
                &cr,
                &pango_layout,
                0.0,
                0.0,
                W as f64,
                H as f64,
                &list,
                &test_theme(),
                LINE_HEIGHT,
                false,
            );
        }
        let stride = surface.stride() as usize;
        let data = surface.data().expect("surface data");

        let probe_x = (expected.track.x + expected.track.width / 2.0).round() as i32;
        let probe_y = (expected.track.y + expected.track.height / 2.0).round() as i32;
        let (r, g, b) = pixel(
            &data,
            stride,
            probe_x.clamp(0, W - 1),
            probe_y.clamp(0, H - 1),
        );
        assert_ne!(
            (r, g, b),
            (255, 255, 255),
            "expected the v-scrollbar track at ({probe_x}, {probe_y}) to be painted \
             (non-background), got white — the #1075 regression this test guards"
        );
    }
}

/// Multi-select click wiring over [`crate::gtk::testing::GtkDriver`].
///
/// `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`. This mirrors
/// [`super::combo_box`]'s toy-`AppLogic` driver-test shape, since
/// `ListView` has no `.click()` method of its own to delegate to.
#[cfg(test)]
mod multi_select_driver_tests {
    use crate::gtk::testing::GtkDriver;
    use crate::runner::{AppLogic, Reaction};
    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 = GtkDriver::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 = GtkDriver::new(ListApp::new(), 80, 40);
        // These rows sit well within the real double-click radius
        // (`GTK_DOUBLE_CLICK_RADIUS`), so without this, the detector would
        // fold the deliberate back-to-back single clicks below into a
        // `DoubleClick` instead of two independent `MouseDown`s.
        driver.set_double_click_folding(false);
        driver.dispatch(mouse_down(2.0, 0.0, Modifiers::default()));
        let ctrl = Modifiers {
            ctrl: true,
            ..Default::default()
        };
        driver.dispatch(mouse_down(2.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(2.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 = GtkDriver::new(ListApp::new(), 80, 40);
        driver.set_double_click_folding(false);
        driver.dispatch(mouse_down(2.0, 0.0, Modifiers::default()));
        let shift = Modifiers {
            shift: true,
            ..Default::default()
        };
        driver.dispatch(mouse_down(2.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 = GtkDriver::new(ListApp::new(), 80, 40);
        driver.set_double_click_folding(false);
        driver.dispatch(mouse_down(2.0, 1.0, Modifiers::default()));
        driver.dispatch(mouse_down(
            2.0,
            4.0,
            Modifiers {
                cmd: true,
                ..Default::default()
            },
        ));
        assert_eq!(driver.app().selected, vec![1, 4]);
    }
}