quadraui 0.6.0

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! Direct2D / DirectWrite rasteriser for [`crate::primitives::toolbar::Toolbar`].
//!
//! [`win_toolbar_layout`] stays here: [`Toolbar::layout`] (the D6 layout
//! API) does every positioning decision via the shared
//! [`crate::primitives::toolbar::measure_button`] formula, this
//! module just supplies the DirectWrite measurer. Content painting
//! moved to the shared
//! [`crate::primitives::toolbar::native_surface_paint::paint`], which
//! paints rounded highlight pills via
//! [`super::text::fill_rounded_rect`]. The focus ring stays a
//! **square** stroke on all three backends — [`PaintSurface`] has no
//! rounded-stroke verb.
//!
//! Only compiled on `target_os = "windows"` — see `super::mod`'s
//! `#[cfg(target_os = "windows")] mod toolbar;` and `backend.rs`'s
//! module docs for why the rest of this repo's `--features win` compile
//! gate stays meaningful without a Windows host.
//!
//! ## Per-state colouring
//!
//! Priority (highest first): pressed → hovered → focused → is_active →
//! enabled — identical to `gtk::toolbar` / `macos::toolbar`. See
//! [`crate::primitives::toolbar::native_surface_paint::paint`]'s module
//! doc for the full table.
//!
//! `bar_bg` is `Toolbar.bg.unwrap_or(theme.header_bg)`. `WinBackend` does
//! not yet carry a live [`Theme`] (see `win::status_bar`'s module doc),
//! so this rasteriser uses [`Theme::default`], the same posture every
//! other `win::` chrome rasteriser takes.

use windows::Win32::Graphics::Direct2D::ID2D1RenderTarget;

use super::text::DWrite;
use crate::event::Rect;
use crate::primitives::toolbar::{
    measure_button, native_surface_paint, Toolbar, ToolbarItemMeasure, ToolbarLayout,
    ToolbarPaintOptions,
};
use crate::theme::Theme;
use crate::types::WidgetId;

/// Compute the Win-GUI pixel/DIP layout for a [`Toolbar`] without
/// painting — the DirectWrite twin of [`draw_toolbar`]'s internal layout
/// call.
///
/// Coordinate frame: **ABSOLUTE** (`rect.x`/`rect.y` baked into every
/// item's `bounds`), matching [`crate::Backend::toolbar_layout`]'s
/// documented contract and `gtk_toolbar_layout` / `mac_toolbar_layout`.
///
/// `dwrite` itself is a [`crate::primitives::layout_metrics::TextMeasure`]
/// — no wrapper struct needed; see `win::text::DWrite`'s
/// `TextMeasure` impl doc for why the former per-module wrapper
/// (`win::form`/`win::toolbar`'s each having their own `DWriteMeasure`)
/// was deleted.
pub fn win_toolbar_layout(dwrite: &DWrite, rect: Rect, bar: &Toolbar) -> ToolbarLayout {
    bar.layout(rect.x, rect.y, rect.width, rect.height, |btn| {
        ToolbarItemMeasure::new(measure_button(dwrite, btn))
    })
}

/// Draw a [`Toolbar`] into `rect` (DIPs) on `target`. Returns the
/// resolved [`ToolbarLayout`] for host click dispatch.
///
/// Equivalent to [`draw_toolbar_with_options`] with
/// [`ToolbarPaintOptions::default()`] — kept as a separate, **unchanged**
/// function so every existing caller of this re-exported `pub fn` keeps
/// compiling untouched (`CLAUDE.md`'s *Downstream consumers* rule 2).
pub fn draw_toolbar(
    target: &ID2D1RenderTarget,
    dwrite: &DWrite,
    rect: Rect,
    bar: &Toolbar,
    hovered_id: Option<&WidgetId>,
    pressed_id: Option<&WidgetId>,
) -> ToolbarLayout {
    draw_toolbar_with_options(
        target,
        dwrite,
        rect,
        bar,
        hovered_id,
        pressed_id,
        ToolbarPaintOptions::default(),
    )
}

/// [`draw_toolbar`], plus [`ToolbarPaintOptions`]: `options.valign`
/// resolves where button/label text paints within a slot
/// taller than one line.
#[allow(clippy::too_many_arguments)]
pub fn draw_toolbar_with_options(
    target: &ID2D1RenderTarget,
    dwrite: &DWrite,
    rect: Rect,
    bar: &Toolbar,
    hovered_id: Option<&WidgetId>,
    pressed_id: Option<&WidgetId>,
    options: ToolbarPaintOptions,
) -> ToolbarLayout {
    let layout = win_toolbar_layout(dwrite, rect, bar);

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

    let theme = Theme::default();
    let mut surface = super::surface::D2dSurface {
        target,
        dwrite: Some(dwrite),
    };
    native_surface_paint::paint(
        bar,
        &layout,
        &mut surface,
        &theme,
        hovered_id,
        pressed_id,
        options,
    );

    layout
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::toolbar::{ToolbarButton, ToolbarHit};
    use crate::win::testing::HeadlessSurface;

    const W: f32 = 240.0;
    const H: f32 = 40.0;

    fn mk_action(id: &str, label: &str, enabled: bool) -> ToolbarButton {
        ToolbarButton::Action {
            id: WidgetId::new(id),
            label: label.into(),
            icon: None,
            key_hint: None,
            enabled,
            is_active: false,
            tooltip: String::new(),
        }
    }

    /// Two-button bar, both enabled, no separators/labels — so
    /// `visible_items` order matches `buttons` order 1:1.
    fn sample_bar() -> Toolbar {
        Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![
                mk_action("tb:refine", "Refine", true),
                mk_action("tb:drop", "Drop", true),
            ],
            bg: None,
            focused_index: None,
        }
    }

    fn paint_via_backend_at(bar: &Toolbar, x: f32, y: f32) -> ToolbarLayout {
        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 rect = Rect::new(x, y, W - x, H - y);

        surface
            .paint(|target| {
                draw_toolbar_with_options(
                    target,
                    &dwrite,
                    rect,
                    bar,
                    None,
                    None,
                    ToolbarPaintOptions::default(),
                );
            })
            .map(|_| win_toolbar_layout(&dwrite, rect, bar))
            .expect("paint toolbar")
    }

    /// `draw_toolbar` must paint and return a click-routable layout.
    #[test]
    fn round_trip_click_hits_enabled_button() {
        let bar = sample_bar();
        let layout = paint_via_backend_at(&bar, 0.0, 0.0);
        assert_eq!(layout.visible_items.len(), 2);

        let refine = &layout.visible_items[0];
        let hit = layout.hit_test(
            refine.bounds.x + refine.bounds.width * 0.5,
            refine.bounds.y + refine.bounds.height * 0.5,
        );
        assert_eq!(
            hit,
            ToolbarHit::Button(WidgetId::new("tb:refine")),
            "expected Refine button hit",
        );
    }

    /// Non-zero-origin layout: `Toolbar::layout` bakes `rect.x`/`rect.y`
    /// into every item's `bounds` (ABSOLUTE frame), matching the GTK/macOS/TUI twins.
    #[test]
    fn round_trip_click_hits_enabled_button_at_nonzero_origin() {
        let bar = sample_bar();
        let origin_x = 7.0_f32;
        let origin_y = 13.0_f32;
        let layout = paint_via_backend_at(&bar, origin_x, origin_y);

        let refine = &layout.visible_items[0];
        assert!(
            (refine.bounds.x - origin_x).abs() < 0.01,
            "first button should start at origin_x={}, got {}",
            origin_x,
            refine.bounds.x,
        );
        assert!(
            (refine.bounds.y - origin_y).abs() < 0.01,
            "first button should start at origin_y={}, got {}",
            origin_y,
            refine.bounds.y,
        );

        let hit = layout.hit_test(
            refine.bounds.x + refine.bounds.width * 0.5,
            refine.bounds.y + refine.bounds.height * 0.5,
        );
        assert_eq!(
            hit,
            ToolbarHit::Button(WidgetId::new("tb:refine")),
            "expected Refine button hit at non-zero origin",
        );
    }

    #[test]
    fn disabled_action_not_clickable_after_paint() {
        let bar = Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![mk_action("a", "Refine", false)],
            bg: None,
            focused_index: None,
        };
        let layout = paint_via_backend_at(&bar, 0.0, 0.0);
        let r = layout.visible_items[0].bounds;
        assert_eq!(
            layout.hit_test(r.x + 1.0, r.y + 1.0),
            ToolbarHit::Empty,
            "disabled action must not be clickable"
        );
    }

    #[test]
    fn separator_and_label_are_not_clickable() {
        let bar = Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![
                ToolbarButton::Separator,
                ToolbarButton::Label {
                    text: "2 of 5".into(),
                    fg: None,
                },
            ],
            bg: None,
            focused_index: None,
        };
        let layout = paint_via_backend_at(&bar, 0.0, 0.0);
        assert!(!layout.visible_items[0].clickable);
        assert!(!layout.visible_items[1].clickable);
        let r = layout.visible_items[1].bounds;
        assert_eq!(layout.hit_test(r.x, r.y), ToolbarHit::Empty);
    }

    /// No-paint layout must agree byte-for-byte with what `draw_toolbar`
    /// painted — same contract every other `win::` rasteriser's
    /// `no_paint_layout_matches_paint_layout` test proves (see
    /// `win::form`).
    #[test]
    fn no_paint_layout_matches_paint_layout() {
        let bar = sample_bar();
        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_toolbar_with_options(
                    target,
                    &dwrite,
                    rect,
                    &bar,
                    None,
                    None,
                    ToolbarPaintOptions::default(),
                );
            })
            .map(|_| win_toolbar_layout(&dwrite, rect, &bar))
            .expect("paint");
        let no_paint = win_toolbar_layout(&dwrite, rect, &bar);
        assert_eq!(painted, no_paint);
    }

    /// Pre-migration Windows painted the hover/pressed/
    /// active highlight as a plain rectangle (this module's own doc used
    /// to list "no rounded-rect helper exists yet" as a documented scope
    /// gap) — the shared `native_surface_paint::paint` now fills a real
    /// rounded pill via `surface_fill_rounded_rect`. A square fill would
    /// paint the inset rect's own extreme corner pixel; a rounded one
    /// (radius 4) leaves it unpainted, since that pixel sits outside the
    /// corner arc.
    #[test]
    fn active_button_highlight_has_rounded_corners_not_square() {
        let bar = Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![ToolbarButton::Action {
                id: WidgetId::new("tb:on"),
                label: "On".into(),
                icon: None,
                key_hint: None,
                enabled: true,
                is_active: true,
                tooltip: String::new(),
            }],
            bg: None,
            focused_index: None,
        };
        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_toolbar_with_options(
                    target,
                    &dwrite,
                    rect,
                    &bar,
                    None,
                    None,
                    ToolbarPaintOptions::default(),
                );
            })
            .expect("paint toolbar");
        let layout = win_toolbar_layout(&dwrite, rect, &bar);

        let theme = Theme::default();
        let item = &layout.visible_items[0].bounds;

        // The inset highlight rect starts at (item.x + 2, item.y + 2);
        // its very corner pixel sits outside a 4px-radius rounded
        // corner arc.
        let corner_x = (item.x + 2.0) as u32;
        let corner_y = (item.y + 2.0) as u32;
        let corner = surface.pixel_at(corner_x, corner_y);
        assert_ne!(
            (corner.r, corner.g, corner.b),
            (
                theme.selected_bg.r,
                theme.selected_bg.g,
                theme.selected_bg.b
            ),
            "highlight corner pixel should NOT be filled — rounded corner (quadraui#1081), not square",
        );

        // The inset rect must be filled solid in the highlight colour away
        // from the corners — proves this isn't just "nothing painted". Not the
        // button's exact geometric centre: that's where the "On" label's text
        // is centred (`tx = item.x + (item.width - tw) / 2`), and DirectWrite's
        // ClearType/greyscale anti-aliasing blends glyph ink into the surrounding
        // highlight fill, so the centre pixel is a mix of `theme.foreground` and
        // `theme.selected_bg`. `measure_button`'s `ACTION_H_PAD = 8.0` guarantees
        // the text always starts at `item.x + 8` regardless of font/glyph metrics
        // (`item.width == text_width + 2 * ACTION_H_PAD`, so
        // `tx == item.x + ACTION_H_PAD`), so the strip `[item.x + 2, item.x + 8)`
        // — between the inset's left edge and where the label starts — is always
        // text-free. `+ 5.0` sits in the middle of that strip; the y stays at
        // mid-height, comfortably clear of the top/bottom corner arcs (radius 4
        // on a 40px-tall bar).
        let cx = (item.x + 5.0) as u32;
        let cy = (item.y + item.height / 2.0) as u32;
        let centre = surface.pixel_at(cx, cy);
        assert_eq!(
            (centre.r, centre.g, centre.b),
            (
                theme.selected_bg.r,
                theme.selected_bg.g,
                theme.selected_bg.b
            ),
            "highlight fill should be solid away from the corners and the label text",
        );
    }

    /// Multi-row paint test (issue #260's test plan): paint the same bar
    /// into the same tall slot once per [`crate::primitives::toolbar::ToolbarVAlign`]
    /// variant and confirm the row of the first painted (non-background)
    /// pixel moves accordingly — `Top` paints highest, `Bottom` lowest.
    #[test]
    fn multi_row_valign_moves_painted_text_vertically() {
        use crate::primitives::toolbar::ToolbarVAlign;

        let bar = Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![ToolbarButton::Action {
                id: WidgetId::new("tb:go"),
                label: "Go".into(),
                icon: None,
                key_hint: None,
                enabled: true,
                is_active: false,
                tooltip: String::new(),
            }],
            bg: None,
            focused_index: None,
        };
        let theme = Theme::default();
        let rect = Rect::new(0.0, 0.0, W, H);
        let (dwrite, _, _) = DWrite::new("Segoe UI", 10.0, None).expect("create DWrite");

        let first_ink_row = |valign: ToolbarVAlign| -> u32 {
            let surface = HeadlessSurface::new(W as u32, H as u32).expect("create surface");
            surface
                .paint(|target| {
                    draw_toolbar_with_options(
                        target,
                        &dwrite,
                        rect,
                        &bar,
                        None,
                        None,
                        ToolbarPaintOptions { valign },
                    );
                })
                .expect("paint toolbar");
            for y in 0..H as u32 {
                for x in 0..W as u32 {
                    let px = surface.pixel_at(x, y);
                    if (px.r, px.g, px.b)
                        != (theme.header_bg.r, theme.header_bg.g, theme.header_bg.b)
                    {
                        return y;
                    }
                }
            }
            panic!("no ink painted for valign {valign:?}");
        };

        let top_row = first_ink_row(ToolbarVAlign::Top);
        let bottom_row = first_ink_row(ToolbarVAlign::Bottom);
        assert!(
            top_row < bottom_row,
            "Top should paint higher than Bottom (top={top_row}, bottom={bottom_row})"
        );
    }
}