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
//! macOS rasteriser for [`crate::StatusBar`].
//!
//! Painting is handled by the shared
//! [`crate::primitives::status_bar::native_surface_paint::paint`].
//! This module carries [`mac_status_bar_layout`] for layout computation
//! and hit-test queries; `MIN_GAP_PX` is this module's measurer constant.
//!
//! ## Bold segments
//!
//! Bold on a segment is ignored on this backend:
//! [`PaintSurface::surface_measure_text_styled`]'s default
//! (drop `bold`, forward to [`PaintSurface::surface_measure_text`])
//! reproduces this behavior. Bold support requires materialising a bold
//! variant of the active font via `CTFontCreateCopyWithSymbolicTraits`.
//!
//! [`Backend`]: crate::Backend
//! [`PaintSurface`]: crate::paint_surface::PaintSurface
//! [`PaintSurface::surface_measure_text_styled`]: crate::paint_surface::PaintSurface::surface_measure_text_styled
//! [`PaintSurface::surface_measure_text`]: crate::paint_surface::PaintSurface::surface_measure_text

use core_text::font::CTFont;

use crate::primitives::status_bar::{
    StatusSegmentMeasure, PIXEL_EDGE_INSET, PIXEL_SEGMENT_PADDING,
};
use crate::{StatusBar, StatusBarLayout};

/// 16-point minimum gap between left and right segment groups. Still
/// used by [`mac_status_bar_layout`] — the shared
/// [`crate::primitives::status_bar::native_surface_paint::paint`] carries
/// its own independent copy of the same value (see that module's doc).
pub(crate) const MIN_GAP_PX: f32 = 16.0;

/// Compute the layout for `bar` at `width` × `line_height`, without painting.
///
/// This is the no-paint twin backing [`crate::Backend::status_bar_layout`].
/// Hit regions are in **bar-local coordinates** (relative to the bar's
/// origin); the primitive measures from `0.0` and nothing here folds the
/// origin in.
pub fn mac_status_bar_layout(
    font: &CTFont,
    width: f64,
    line_height: f64,
    bar: &StatusBar,
) -> StatusBarLayout {
    // Degenerate rect: reproduce exactly what the shared `paint` returns
    // so the paint and no-paint paths never disagree.
    if width <= 0.0 || line_height <= 0.0 {
        return bar.layout_padded(
            width.max(0.0) as f32,
            line_height.max(0.0) as f32,
            MIN_GAP_PX,
            PIXEL_EDGE_INSET,
            PIXEL_SEGMENT_PADDING,
            |_| StatusSegmentMeasure::new(0.0),
        );
    }
    // Measure each visible segment via Core Text. `bold` is ignored — see
    // this module's doc, "Bold segments".
    let measure = |seg: &crate::primitives::status_bar::StatusBarSegment| -> StatusSegmentMeasure {
        let (w, _) = super::text::measure_text(font, &seg.text);
        StatusSegmentMeasure::new(w as f32)
    };
    // `layout_padded` (not plain `layout`) so this no-paint twin
    // agrees with the shared `native_surface_paint::paint`'s outer edge
    // inset + per-segment padding — see that fn's doc.
    bar.layout_padded(
        width as f32,
        line_height as f32,
        MIN_GAP_PX,
        PIXEL_EDGE_INSET,
        PIXEL_SEGMENT_PADDING,
        measure,
    )
}

#[cfg(test)]
mod tests {
    use super::super::headless::BitmapSurface;
    use super::super::text::make_font;
    use super::super::MacBackend;
    use super::*;
    use crate::event::{Rect as QRect, Viewport};
    use crate::primitives::status_bar::StatusBarHit;
    use crate::primitives::status_bar::StatusBarSegment;
    use crate::primitives::status_bar::StatusSegmentSide;
    use crate::theme::Theme;
    use crate::types::{Color, WidgetId};
    use crate::Backend;

    const W: u32 = 320;
    const H: u32 = 24;
    const FONT_SIZE: f64 = 14.0;

    fn font() -> CTFont {
        make_font("Menlo", FONT_SIZE).expect("Menlo installed on every macOS host")
    }

    /// A backend with **both** font slots set to the harness font.
    ///
    /// The status bar paints and measures through `MacBackend::chrome_font` /
    /// `chrome_line_height`, not the editor `current_font`. `MacBackend::new`
    /// seeds chrome with the ~11pt system UI font, whose line height is under
    /// half of this module's `H = 24` surface. Setting both keeps every
    /// assertion about status-bar geometry at a known `FONT_SIZE`.
    fn backend_with_test_fonts() -> MacBackend {
        let mut backend = MacBackend::new();
        backend.set_current_font(font());
        backend.set_chrome_font(font());
        backend
    }

    /// Three-segment bar:
    /// - Left[0]: "(L) " sentinel with bg `(10, 20, 30)` — sets the
    ///   bar fill (first segment's bg) to a colour distinct from the
    ///   clickable segment, so paint-shift mutations can't hide
    ///   behind a matching bar fill.
    /// - Left[1]: " Save " clickable, bg `(40, 80, 120)`.
    /// - Right[0]: " 1:1 " non-clickable, bg `(40, 80, 120)`.
    ///
    /// Leading/trailing spaces give glyph-free padding pixels for
    /// bg-colour probing — same trick the TUI reference tests use.
    fn sample_bar() -> StatusBar {
        StatusBar {
            id: WidgetId::new("status"),
            left_segments: vec![
                StatusBarSegment {
                    text: "(L) ".into(),
                    fg: Color::rgb(255, 255, 255),
                    bg: Color::rgb(10, 20, 30),
                    bold: false,
                    action_id: None,
                },
                StatusBarSegment {
                    text: " Save ".into(),
                    fg: Color::rgb(255, 255, 255),
                    bg: Color::rgb(40, 80, 120),
                    bold: false,
                    action_id: Some(WidgetId::new("status:save")),
                },
            ],
            right_segments: vec![StatusBarSegment {
                text: " 1:1 ".into(),
                fg: Color::rgb(255, 255, 255),
                bg: Color::rgb(40, 80, 120),
                bold: false,
                action_id: None,
            }],
        }
    }

    /// Paint a bar through the full `MacBackend::draw_status_bar`
    /// path and return both the surface (for pixel inspection) and
    /// the layout (for hit_test). Establishes the harness shape every
    /// chrome rasteriser test follows.
    fn paint_via_backend(bar: &StatusBar) -> (BitmapSurface, StatusBarLayout) {
        paint_via_backend_at(bar, 0.0, 0.0)
    }

    /// Like [`paint_via_backend`] but paints at an arbitrary `(x, y)`
    /// origin instead of always `(0, 0)`. Lets tests exercise the
    /// paint-time `x`/`y` shift independently of the bar-local
    /// `StatusBarLayout` it returns.
    fn paint_via_backend_at(bar: &StatusBar, x: f32, y: f32) -> (BitmapSurface, StatusBarLayout) {
        let surface = BitmapSurface::new(W, H);
        // Clear so we can distinguish "painted by status_bar" from
        // "untouched memory" cleanly.
        surface.fill(0.0, 0.0, 0.0, 0.0);

        let mut backend = backend_with_test_fonts();
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));

        let layout = std::cell::RefCell::new(None);
        backend.enter_frame_scope(surface.context_ptr(), |b| {
            let l = b.draw_status_bar_interactive(
                QRect::new(x, y, W as f32 - x, H as f32 - y),
                bar,
                &crate::InteractionState::new(),
            );
            *layout.borrow_mut() = Some(l);
        });
        backend.end_frame();
        (surface, layout.into_inner().unwrap())
    }

    /// Probe a column near the leading space of the clickable "Save"
    /// segment — a glyph-free padding region that exposes the
    /// segment's bg fill without interference from rasterised text.
    /// Sample near the top edge where line_height is guaranteed
    /// painted and glyphs (anchored at the ascent baseline) don't
    /// reach.
    fn probe_save_segment_bg(surface: &BitmapSurface, layout: &StatusBarLayout) -> (u8, u8, u8) {
        let save = layout
            .visible_segments
            .iter()
            .filter(|vs| vs.side == StatusSegmentSide::Left)
            .nth(1)
            .expect("save segment visible");
        let probe_x = (save.bounds.x as u32) + 1;
        let probe_y = 2;
        let (r, g, b, _) = surface.pixel(probe_x, probe_y);
        (r, g, b)
    }

    #[test]
    fn paints_segment_backgrounds() {
        let bar = sample_bar();
        let (surface, layout) = paint_via_backend(&bar);
        assert_eq!(
            probe_save_segment_bg(&surface, &layout),
            (40, 80, 120),
            "left-segment bg should match StatusBarSegment.bg",
        );
    }

    /// Shared body for `round_trip_click_hits_clickable_segment` and its
    /// `_at_nonzero_origin` sibling. Paints `sample_bar()` at
    /// `(origin_x, origin_y)`, then round-trips an absolute click through
    /// localisation the way a real host does before calling `hit_test`, and
    /// checks the *painted* segment lands at the origin-shifted absolute
    /// position. Guards against a paint/layout frame mismatch.
    fn round_trip_click_hits_clickable_segment_at(origin_x: f32, origin_y: f32) {
        let bar = sample_bar();
        let (surface, layout) = paint_via_backend_at(&bar, origin_x, origin_y);

        let save = layout
            .visible_segments
            .iter()
            .filter(|vs| vs.side == StatusSegmentSide::Left)
            .nth(1)
            .expect("save segment visible");

        // Paint-vs-layout frame check: the segment's bg must be painted
        // at the origin-shifted absolute x, not at the bar-local x.
        let probe_x = (origin_x + save.bounds.x) as u32 + 1;
        let probe_y = origin_y as u32 + 2;
        let (r, g, b, _) = surface.pixel(probe_x, probe_y);
        assert_eq!(
            (r, g, b),
            (40, 80, 120),
            "painted Save segment bg should be at absolute x = origin_x + local bounds.x",
        );

        // Round trip: absolute click position -> localise like a real
        // host -> hit_test against the bar-local layout.
        let abs_x = origin_x + save.bounds.x + save.bounds.width * 0.5;
        let abs_y = origin_y + save.bounds.y + save.bounds.height * 0.5;
        let local_x = abs_x - origin_x;
        let local_y = abs_y - origin_y;
        let hit = layout.hit_test(local_x, local_y);
        assert_eq!(
            hit,
            StatusBarHit::Segment(WidgetId::new("status:save")),
            "expected clickable Save segment hit at local ({}, {})",
            local_x,
            local_y,
        );

        // Sanity check: the right segment is non-clickable, so a hit
        // inside its bounds must return Empty.
        let right = layout
            .visible_segments
            .iter()
            .find(|vs| vs.side == StatusSegmentSide::Right)
            .expect("right segment visible");
        let right_hit = layout.hit_test(
            right.bounds.x + right.bounds.width * 0.5,
            right.bounds.y + right.bounds.height * 0.5,
        );
        assert_eq!(
            right_hit,
            StatusBarHit::Empty,
            "non-clickable right segment must hit Empty",
        );
    }

    #[test]
    fn round_trip_click_hits_clickable_segment() {
        round_trip_click_hits_clickable_segment_at(0.0, 0.0);
    }

    #[test]
    fn round_trip_click_hits_clickable_segment_at_nonzero_origin() {
        // The origin-(0,0) variant above can't exercise localisation —
        // `abs_x - x` is a no-op when `x == 0`. Paint at a non-zero
        // origin so the round trip only passes if paint and layout agree
        // on which frame `x`/`y` apply in.
        round_trip_click_hits_clickable_segment_at(7.0, 4.0);
    }

    #[test]
    fn empty_bar_falls_back_to_theme_background() {
        // No segments → fill colour comes from theme.background.
        let bar = StatusBar {
            id: WidgetId::new("empty"),
            left_segments: vec![],
            right_segments: vec![],
        };
        let surface = BitmapSurface::new(W, H);
        surface.fill(0.0, 0.0, 0.0, 0.0);

        let mut backend = backend_with_test_fonts();
        backend.set_current_theme(Theme {
            background: Color::rgb(1, 2, 3),
            ..Theme::default()
        });
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
        backend.enter_frame_scope(surface.context_ptr(), |b| {
            b.draw_status_bar_interactive(
                QRect::new(0.0, 0.0, W as f32, H as f32),
                &bar,
                &crate::InteractionState::new(),
            );
        });
        backend.end_frame();

        // Every pixel should carry the theme bg.
        let (r, g, b, _) = surface.pixel(W / 2, H / 2);
        assert_eq!(
            (r, g, b),
            (1, 2, 3),
            "empty bar should be filled with theme.background",
        );
    }

    #[test]
    fn hover_tint_lightens_clickable_segment_bg() {
        // Paint with `hovered_id = "status:save"` and assert the bg
        // sample comes back lighter than the un-tinted version.
        let bar = sample_bar();

        let mut backend = backend_with_test_fonts();
        backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));

        let surface = BitmapSurface::new(W, H);
        surface.fill(0.0, 0.0, 0.0, 0.0);
        let hovered = WidgetId::new("status:save");
        let layout = std::cell::RefCell::new(None);
        backend.enter_frame_scope(surface.context_ptr(), |b| {
            let l = b.draw_status_bar_interactive(
                QRect::new(0.0, 0.0, W as f32, H as f32),
                &bar,
                &crate::InteractionState::from_parts(Some(hovered.clone()), None),
            );
            *layout.borrow_mut() = Some(l);
        });
        backend.end_frame();

        let layout = layout.into_inner().unwrap();
        let (r, g, b) = probe_save_segment_bg(&surface, &layout);
        // Base colour is (40, 80, 120). `lighten(0.05)` moves each
        // channel 5% of the way to 255. Each channel should be
        // strictly greater than the base.
        assert!(
            r > 40 && g > 80 && b > 120,
            "hover-tinted bg ({}, {}, {}) should be lighter than base (40, 80, 120)",
            r,
            g,
            b,
        );
    }

    /// `Backend::status_bar_layout` must return exactly what
    /// `draw_status_bar` painted — both route through
    /// `mac_status_bar_layout`, and this pins that.
    #[test]
    fn layout_twin_matches_the_painted_layout() {
        let bar = sample_bar();
        let (_surface, painted) = paint_via_backend(&bar);

        // No `mut`: `status_bar_layout` is the `&self` no-paint twin, and
        // the helper does all the mutating (`-D warnings` denies
        // `unused_mut`).
        let backend = backend_with_test_fonts();
        let computed = backend.status_bar_layout(QRect::new(0.0, 0.0, W as f32, H as f32), &bar);

        assert_eq!(
            painted.visible_segments.len(),
            computed.visible_segments.len(),
        );
        for (p, c) in painted
            .visible_segments
            .iter()
            .zip(computed.visible_segments.iter())
        {
            assert_eq!(p.segment_idx, c.segment_idx);
            assert_eq!(p.side, c.side);
            assert!((p.bounds.x - c.bounds.x).abs() < 0.001);
            assert!((p.bounds.width - c.bounds.width).abs() < 0.001);
        }
    }

    /// The no-paint twin is also origin-independent: hit regions are
    /// bar-local, so painting at a non-zero origin does not move them.
    #[test]
    fn layout_twin_is_bar_local_at_a_nonzero_origin() {
        let bar = sample_bar();
        let (_surface, painted) = paint_via_backend_at(&bar, 0.0, 0.0);
        let backend = backend_with_test_fonts();
        let computed = backend.status_bar_layout(QRect::new(17.0, 3.0, W as f32, H as f32), &bar);
        for (p, c) in painted
            .visible_segments
            .iter()
            .zip(computed.visible_segments.iter())
        {
            assert!(
                (p.bounds.x - c.bounds.x).abs() < 0.001,
                "segment x moved with the origin: {} vs {}",
                p.bounds.x,
                c.bounds.x,
            );
        }
    }
}