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
//! TUI rasteriser for [`crate::ActivityBar`].
//!
//! Cell-based equivalent of the GTK activity-bar drawing path. Uses the
//! primitive's [`crate::ActivityBarLayout`] for positioning and paints
//! into a ratatui buffer. Activity bar width is caller-determined (typically
//! 4 cells: 1 accent + 2 icon + 1 separator).

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

use super::{qc, set_cell, set_cell_wide};
use crate::primitives::activity_bar::{
    ActivityBar, ActivityBarRowHit, ActivityBarStyle, ActivitySide,
};
use crate::text_util::char_cell_width;
use crate::theme::Theme;

/// Equivalent to [`draw_activity_bar_with_style`] with
/// `ActivityBarStyle::default()`, i.e. no active-row fill — see that
/// function for the full behaviour.
///
/// `nerd_fonts_enabled` picks which half of each item's [`crate::Icon`]
/// paints — `glyph` when `true`, `fallback` when `false`.
/// Pass the backend's own flag (`Backend::set_nerd_fonts`), same as
/// [`super::list::draw_list`].
#[allow(clippy::too_many_arguments)]
pub fn draw_activity_bar(
    buf: &mut Buffer,
    area: Rect,
    bar: &ActivityBar,
    theme: &Theme,
    hovered_idx: Option<usize>,
    nerd_fonts_enabled: bool,
) -> Vec<ActivityBarRowHit> {
    draw_activity_bar_with_style(
        buf,
        area,
        bar,
        &ActivityBarStyle::default(),
        theme,
        hovered_idx,
        nerd_fonts_enabled,
    )
}

/// [`draw_activity_bar`] with an explicit [`ActivityBarStyle`] request.
/// `ActivityBarStyle::default()` reproduces [`draw_activity_bar`]
/// cell for cell. See [`draw_activity_bar`] for `nerd_fonts_enabled`.
#[allow(clippy::too_many_arguments)]
pub fn draw_activity_bar_with_style(
    buf: &mut Buffer,
    area: Rect,
    bar: &ActivityBar,
    style: &ActivityBarStyle,
    theme: &Theme,
    hovered_idx: Option<usize>,
    nerd_fonts_enabled: bool,
) -> Vec<ActivityBarRowHit> {
    if area.width == 0 || area.height == 0 {
        return Vec::new();
    }

    let bg = qc(theme.tab_bar_bg);
    let sep = qc(theme.separator);
    // No theme fallback for either knob — `None` genuinely means
    // "don't paint this" for both the accent line and the row fill.
    let accent: Option<ratatui::style::Color> = bar.active_accent.map(qc);
    let active_bg: Option<ratatui::style::Color> = style.active_bg.map(qc);
    let active_fg = qc(theme.foreground);
    let inactive_fg = qc(theme.inactive_fg);
    let hover_bg = qc(theme.tab_bar_bg.lighten(0.10));
    // Explicit keyboard-selection background when the bar sets `selection_bg`.
    // `None` → fall back to `Modifier::REVERSED` after the icon paint (terminal-
    // agnostic inversion that works in every colour scheme).
    let sel_explicit_bg: Option<ratatui::style::Color> = bar.selection_bg.map(qc);

    // Fill background.
    for row in area.y..area.y + area.height {
        for col in area.x..area.x + area.width {
            set_cell(buf, col, row, ' ', bg, bg);
        }
    }

    // Right-edge separator column.
    let sep_col = area.x + area.width - 1;
    for row in area.y..area.y + area.height {
        set_cell(buf, sep_col, row, '│', sep, bg);
    }

    let layout = bar.layout(area.width as f32, area.height as f32, 1.0);

    let mut regions: Vec<ActivityBarRowHit> = Vec::new();
    let mut flat_idx: usize = 0;

    for vi in &layout.visible_items {
        let y = area.y + vi.bounds.y.round() as u16;
        if y >= area.y + area.height {
            continue;
        }

        let item = match vi.side {
            ActivitySide::Top => &bar.top_items[vi.item_idx],
            ActivitySide::Bottom => &bar.bottom_items[vi.item_idx],
        };

        let is_hovered = hovered_idx == Some(flat_idx);
        // Effective row background priority: explicit keyboard-selection >
        // hover > default. When keyboard-selected without an explicit
        // `selection_bg`, the row uses the default bg and REVERSED is applied
        // after the icon paint (so all cells invert, giving a clear cursor
        // in any terminal colour scheme).
        let row_bg = if item.is_keyboard_selected {
            sel_explicit_bg.unwrap_or(if is_hovered { hover_bg } else { bg })
        } else if is_hovered {
            hover_bg
        } else if item.is_active {
            active_bg.unwrap_or(bg)
        } else {
            bg
        };
        let fg = if item.is_active || is_hovered || item.is_keyboard_selected {
            active_fg
        } else {
            inactive_fg
        };

        // Row background fill (hover tint, explicit keyboard-selection bg,
        // or the active-row fill). All three use the same `row_bg` computed
        // above, but we only fill when there is actually a tint to apply.
        if is_hovered
            || (item.is_keyboard_selected && sel_explicit_bg.is_some())
            || (item.is_active && active_bg.is_some())
        {
            for col in area.x..sep_col {
                set_cell(buf, col, y, ' ', fg, row_bg);
            }
        }

        // Left-edge accent bar for active items — only when the bar opts in
        // via `active_accent`. `None` paints zero accent-line pixels.
        if item.is_active {
            if let Some(ac) = accent {
                set_cell(buf, area.x, y, '▎', ac, row_bg);
            }
        }

        // Icon glyph — centered in the available width (excluding accent
        // column and separator column). Picks `Icon::glyph` /
        // `Icon::fallback` per `nerd_fonts_enabled`; TUI paints
        // only the resolved string's first character.
        let icon_str = if nerd_fonts_enabled {
            item.icon.glyph.as_str()
        } else {
            item.icon.fallback.as_str()
        };
        let icon_ch = icon_str.chars().next().unwrap_or(' ');
        let content_start = area.x + 1; // after accent column
        let content_end = sep_col; // before separator
        let content_w = content_end.saturating_sub(content_start);
        let icon_w = char_cell_width(icon_ch).max(1);
        if content_w >= icon_w {
            let icon_x = content_start + (content_w - icon_w) / 2;
            if icon_w >= 2 {
                set_cell_wide(buf, icon_x, y, icon_ch, fg, row_bg);
            } else {
                set_cell(buf, icon_x, y, icon_ch, fg, row_bg);
            }
        }

        // Keyboard selection highlight — REVERSED fallback when no explicit
        // `selection_bg`. Applied last so it overrides any earlier colour.
        if item.is_keyboard_selected && sel_explicit_bg.is_none() {
            for col in area.x..sep_col {
                let cell = &mut buf[(col, y)];
                cell.modifier |= Modifier::REVERSED;
            }
        }

        // Hit regions are **bar-relative**, not absolute: report the
        // row offset within `area`, not the screen row `y` we painted at.
        let rel_y = (y - area.y) as f32;
        regions.push(ActivityBarRowHit {
            y_start: rel_y,
            y_end: rel_y + 1.0,
            id: item.id,
            tooltip: item.tooltip.clone(),
        });

        flat_idx += 1;
    }

    regions
}

// ── Tests ────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::activity_bar::ActivityItem;
    use crate::types::{Color, Icon, WidgetId};

    fn item(id: &str, icon: &str) -> ActivityItem {
        ActivityItem {
            id: WidgetId::new(id),
            icon: icon.into(),
            tooltip: format!("{id} tooltip"),
            is_active: false,
            is_keyboard_selected: false,
        }
    }

    fn bar() -> ActivityBar {
        ActivityBar {
            id: WidgetId::new("activity"),
            top_items: vec![item("explorer", "E"), item("search", "S"), item("git", "G")],
            bottom_items: vec![item("settings", "*")],
            active_accent: None,
            selection_bg: None,
            is_keyboard_focused: false,
        }
    }

    /// Hit regions are **bar-relative**, not absolute, so the top row
    /// starts at `0.0` no matter where the bar is painted.
    ///
    /// Looks rows up **by id** rather than by position: `visible_items`
    /// (and therefore this list) is bottom-pinned-first, not visual
    /// top-to-bottom order.
    #[test]
    fn hit_regions_are_bar_relative_not_absolute() {
        let b = bar();
        let theme = Theme::default();

        let mut buf = Buffer::empty(Rect::new(0, 0, 40, 20));
        let area = Rect::new(0, 3, 3, 10);
        let hits = draw_activity_bar(&mut buf, area, &b, &theme, None, false);

        let span = |id: &str| {
            let h = hits
                .iter()
                .find(|h| h.id.as_str() == id)
                .unwrap_or_else(|| panic!("no hit region for {id:?}"));
            (h.y_start, h.y_end)
        };

        assert_eq!(
            span("explorer"),
            (0.0, 1.0),
            "the top row must start at 0.0 relative to the bar, not at \
             area.y ({}) — folding the origin in here double-counts it \
             against AppShell's own `+ activity_bar_bounds.y` (issue #552)",
            area.y
        );
        assert_eq!(span("search"), (1.0, 2.0), "second row is one row down");
        assert_eq!(span("git"), (2.0, 3.0));
        // Bottom-pinned: `area.height` (10) - 1 row, still measured from
        // the bar's own top edge, not the screen's.
        assert_eq!(span("settings"), (9.0, 10.0));
    }

    /// The same regions must come back for *any* `area.y`. Pinning
    /// invariance rather than a single value is what stops the bug from
    /// reappearing: the pre-fix output was correct at `area.y == 0` (title
    /// bar hidden) and wrong everywhere else, which is exactly why every
    /// existing static test passed.
    #[test]
    fn hit_regions_do_not_move_when_the_bar_does() {
        let b = bar();
        let theme = Theme::default();

        let spans = |y: u16| {
            let mut buf = Buffer::empty(Rect::new(0, 0, 40, 30));
            let hits = draw_activity_bar(&mut buf, Rect::new(0, y, 3, 10), &b, &theme, None, false);
            hits.iter()
                .map(|h| (h.y_start, h.y_end))
                .collect::<Vec<_>>()
        };

        let at_zero = spans(0);
        assert!(!at_zero.is_empty(), "sanity: some rows were painted");
        for y in [1u16, 2, 5] {
            assert_eq!(
                spans(y),
                at_zero,
                "hit regions must be independent of the bar's screen origin; \
                 they differed at area.y = {y} (issue #552)"
            );
        }
    }

    /// Painting uses the absolute row; hit regions are bar-relative.
    #[test]
    fn icons_still_paint_at_the_absolute_row() {
        let b = bar();
        let theme = Theme::default();
        let mut buf = Buffer::empty(Rect::new(0, 0, 40, 20));
        let area = Rect::new(0, 3, 4, 10);
        draw_activity_bar(&mut buf, area, &b, &theme, None, false);

        let row_text = |y: u16| {
            (area.x..area.x + area.width)
                .map(|x| buf[(x, y)].symbol().to_string())
                .collect::<String>()
        };
        assert!(
            row_text(3).contains('E'),
            "first icon should paint on the bar's first *screen* row (3), \
             got {:?}",
            row_text(3)
        );
        assert!(
            row_text(4).contains('S'),
            "second icon on screen row 4, got {:?}",
            row_text(4)
        );
    }

    /// `nerd_fonts_enabled` picks `Icon::glyph` when `true` and
    /// `Icon::fallback` when `false` — the activity bar had no fallback
    /// path at all before this issue, painting whatever bare string it
    /// was handed on every backend regardless of Nerd Font availability.
    #[test]
    fn nerd_fonts_flag_selects_glyph_or_fallback() {
        let mut b = bar();
        b.top_items[0].icon = Icon::new("\u{f07c}", "E");
        let theme = Theme::default();

        let row_text = |nerd_fonts_enabled: bool| {
            let mut buf = Buffer::empty(Rect::new(0, 0, 40, 20));
            let area = Rect::new(0, 0, 4, 10);
            draw_activity_bar(&mut buf, area, &b, &theme, None, nerd_fonts_enabled);
            (area.x..area.x + area.width)
                .map(|x| buf[(x, area.y)].symbol().to_string())
                .collect::<String>()
        };

        assert!(
            row_text(true).contains('\u{f07c}'),
            "nerd_fonts_enabled: true should paint the glyph half of the Icon"
        );
        assert!(
            row_text(false).contains('E'),
            "nerd_fonts_enabled: false should paint the fallback half of the Icon"
        );
    }

    /// `style.active_bg: Some(..)` with `active_accent: None` fills the
    /// active row's cells with the requested colour and paints **zero**
    /// accent-line pixels — the accent column (`area.x`) must not carry
    /// the `'▎'` glyph, only the plain fill background.
    #[test]
    fn active_bg_fills_row_cells_with_zero_accent_glyph_when_accent_is_none() {
        let mut b = bar();
        b.top_items[0].is_active = true; // "explorer"
        let theme = Theme::default();
        let fill_color = Color::rgb(49, 50, 51);
        let style = ActivityBarStyle::new().with_active_bg(fill_color);

        let mut buf = Buffer::empty(Rect::new(0, 0, 40, 20));
        let area = Rect::new(0, 0, 3, 10);
        draw_activity_bar_with_style(&mut buf, area, &b, &style, &theme, None, false);

        let fill = qc(fill_color);
        assert_ne!(
            buf[(area.x, area.y)].symbol(),
            "▎",
            "active_accent is None: the accent column must not carry the \
             accent glyph (zero accent-line pixels)"
        );
        assert_eq!(
            buf[(area.x, area.y)].bg,
            fill,
            "accent column should carry the active_bg fill, not the plain bar bg"
        );
        let icon_col = area.x + 1;
        assert_eq!(
            buf[(icon_col, area.y)].bg,
            fill,
            "icon column should also carry the active_bg fill"
        );
    }

    /// The flip side: `active_accent: Some(..)` with no `style.active_bg`
    /// still paints the traditional accent glyph, and the row keeps the
    /// plain bar background elsewhere.
    #[test]
    fn active_accent_paints_glyph_when_set_with_no_active_bg() {
        let mut b = bar();
        b.top_items[0].is_active = true; // "explorer"
        b.active_accent = Some(Color::rgb(80, 140, 255));
        let theme = Theme::default();

        let mut buf = Buffer::empty(Rect::new(0, 0, 40, 20));
        let area = Rect::new(0, 0, 3, 10);
        draw_activity_bar_with_style(
            &mut buf,
            area,
            &b,
            &ActivityBarStyle::default(),
            &theme,
            None,
            false,
        );

        assert_eq!(
            buf[(area.x, area.y)].symbol(),
            "▎",
            "active_accent is set: the accent column should carry the accent glyph"
        );
        let icon_col = area.x + 1;
        assert_eq!(
            buf[(icon_col, area.y)].bg,
            qc(theme.tab_bar_bg),
            "with no active_bg, the icon column keeps the plain bar background"
        );
    }
}