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
//! macOS rasteriser for [`crate::primitives::toolbar::Toolbar`].
//!
//! `mac_toolbar_layout` stays here — it needs Core Text's own
//! measurement to size each item. Content painting uses the shared
//! [`crate::primitives::toolbar::native_surface_paint::paint`], which
//! fills hover/pressed/active highlights via
//! [`crate::paint_surface::PaintSurface::surface_fill_rounded_rect`].
//! Per D6: layout policy lives in [`crate::primitives::toolbar::Toolbar::layout`];
//! this rasteriser now only builds the [`super::surface::CgSurface`]
//! adapter and delegates paint.
use core_graphics::sys::CGContextRef;
use core_text::font::CTFont;
use crate::primitives::toolbar::{
measure_button, native_surface_paint, Toolbar, ToolbarItemMeasure, ToolbarLayout,
ToolbarPaintOptions,
};
use crate::theme::Theme;
use crate::types::WidgetId;
/// Compute the macOS pixel-unit layout for a [`Toolbar`] without
/// painting. `font` is required for accurate text measurement.
pub fn mac_toolbar_layout(
bar: &Toolbar,
font: &CTFont,
x: f64,
y: f64,
w: f64,
h: f64,
) -> ToolbarLayout {
bar.layout(x as f32, y as f32, w as f32, h as f32, |btn| {
ToolbarItemMeasure::new(measure_button(font, btn))
})
}
/// Paint `bar` into `(x, y, w, h)` on `ctx`. Returns the resolved
/// layout 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).
///
/// # Safety
///
/// `ctx` must be a valid `CGContextRef` borrowed for the duration of
/// the call (typical: the frame-scope pointer stashed on
/// [`super::MacBackend`]).
#[allow(clippy::too_many_arguments)]
pub unsafe fn draw_toolbar(
ctx: CGContextRef,
font: &CTFont,
x: f64,
y: f64,
w: f64,
h: f64,
bar: &Toolbar,
theme: &Theme,
hovered_id: Option<&WidgetId>,
pressed_id: Option<&WidgetId>,
) -> ToolbarLayout {
draw_toolbar_with_options(
ctx,
font,
x,
y,
w,
h,
bar,
theme,
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.
///
/// # Safety
///
/// Same contract as [`draw_toolbar`] — `ctx` must be a valid
/// `CGContextRef` borrowed for the duration of the call.
#[allow(clippy::too_many_arguments)]
pub unsafe fn draw_toolbar_with_options(
ctx: CGContextRef,
font: &CTFont,
x: f64,
y: f64,
w: f64,
h: f64,
bar: &Toolbar,
theme: &Theme,
hovered_id: Option<&WidgetId>,
pressed_id: Option<&WidgetId>,
options: ToolbarPaintOptions,
) -> ToolbarLayout {
let layout = mac_toolbar_layout(bar, font, x, y, w, h);
if w <= 0.0 || h <= 0.0 {
return layout;
}
// `ns_push_clip`/`ns_pop_clip` bracket a `CGContextSaveGState`/
// `CGContextClipToRect`/`CGContextRestoreGState` triple — see their
// own docs. Matches this fn's pre-migration single save/clip/restore
// exactly.
super::backend::ns_push_clip(
ctx,
crate::event::Rect::new(x as f32, y as f32, w as f32, h as f32),
);
let mut surface = super::surface::CgSurface {
ctx,
font: Some(font),
};
native_surface_paint::paint(
bar,
&layout,
&mut surface,
theme,
hovered_id,
pressed_id,
options,
);
super::backend::ns_pop_clip(ctx);
layout
}
#[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::toolbar::{ToolbarButton, ToolbarHit};
use crate::types::WidgetId;
use crate::Backend;
const W: u32 = 240;
const H: u32 = 40;
fn font() -> CTFont {
make_font("Menlo", 14.0).expect("Menlo installed on every macOS host")
}
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 and index 0
/// is always the "Refine" action.
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,
}
}
/// Paint a bar through the full `MacBackend::draw_toolbar` path at
/// origin `(0, 0)` and return both the surface and the resolved
/// layout (for hit_test). Establishes the harness shape every
/// chrome rasteriser test in this crate follows (see e.g.
/// `macos::panel::tests::paint_via_backend`).
fn paint_via_backend(bar: &Toolbar) -> (BitmapSurface, ToolbarLayout) {
paint_via_backend_at(bar, 0.0, 0.0)
}
/// Like [`paint_via_backend`] but paints at an arbitrary `(x, y)`
/// origin. Unlike `StatusBar`/`TextDisplay` in this same module
/// family (bar/body-LOCAL layouts — see their doc comments),
/// `Toolbar::layout` bakes `x`/`y` straight into each item's
/// `bounds` (ABSOLUTE frame, matching `mac_toolbar_layout`'s doc
/// comment). This lets tests confirm painted buttons and the
/// returned layout still agree at a non-zero origin.
fn paint_via_backend_at(bar: &Toolbar, x: f32, y: f32) -> (BitmapSurface, ToolbarLayout) {
paint_via_backend_with_options(
bar,
x,
y,
crate::primitives::toolbar::ToolbarPaintOptions::default(),
)
}
/// Like [`paint_via_backend_at`] but with an explicit
/// [`crate::primitives::toolbar::ToolbarPaintOptions`] to test
/// each [`crate::primitives::toolbar::ToolbarVAlign`] variant.
fn paint_via_backend_with_options(
bar: &Toolbar,
x: f32,
y: f32,
options: crate::primitives::toolbar::ToolbarPaintOptions,
) -> (BitmapSurface, ToolbarLayout) {
paint_via_backend_full(bar, x, y, &crate::InteractionState::new(), options).0
}
/// Like [`paint_via_backend_with_options`] but reuses one `MacBackend`
/// across calls (so its per-widget animation state, e.g.
/// [`super::super::MacBackend`]'s hover-fade map, survives between
/// paints) and takes an explicit [`crate::InteractionState`]. Returns
/// the backend alongside the surface/layout so a caller can paint
/// again — immediately, or after a real sleep — to observe a
/// transition progress.
fn paint_via_backend_full(
bar: &Toolbar,
x: f32,
y: f32,
interaction: &crate::InteractionState,
options: crate::primitives::toolbar::ToolbarPaintOptions,
) -> ((BitmapSurface, ToolbarLayout), MacBackend) {
let mut backend = MacBackend::new();
backend.set_current_font(font());
backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
let (surface, layout) = paint_once(&mut backend, bar, x, y, interaction, options);
backend.end_frame();
((surface, layout), backend)
}
/// Repaint `bar` through an already-begun `backend`, for sampling a
/// second frame (e.g. after a real sleep) against the same backend's
/// retained animation state.
fn repaint(
backend: &mut MacBackend,
bar: &Toolbar,
x: f32,
y: f32,
interaction: &crate::InteractionState,
options: crate::primitives::toolbar::ToolbarPaintOptions,
) -> (BitmapSurface, ToolbarLayout) {
backend.begin_frame(Viewport::new(W as f32, H as f32, 1.0));
let (surface, layout) = paint_once(backend, bar, x, y, interaction, options);
backend.end_frame();
(surface, layout)
}
fn paint_once(
backend: &mut MacBackend,
bar: &Toolbar,
x: f32,
y: f32,
interaction: &crate::InteractionState,
options: crate::primitives::toolbar::ToolbarPaintOptions,
) -> (BitmapSurface, ToolbarLayout) {
let surface = BitmapSurface::new(W, H);
surface.fill(0.0, 0.0, 0.0, 0.0);
let layout = std::cell::RefCell::new(None);
backend.enter_frame_scope(surface.context_ptr(), |b| {
let l = b.draw_toolbar_with_options(
QRect::new(x, y, W as f32 - x, H as f32 - y),
bar,
interaction,
options,
);
*layout.borrow_mut() = Some(l);
});
(surface, layout.into_inner().unwrap())
}
#[test]
fn round_trip_click_hits_enabled_button() {
// Paint at origin (0, 0), then hit-test the centre of the
// first visible ("Refine") button's painted bounds. Assert the
// layout reports a hit on that button's id.
let bar = sample_bar();
let (_surface, layout) = paint_via_backend(&bar);
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",
);
}
#[test]
fn round_trip_click_hits_enabled_button_at_nonzero_origin() {
// Test that layout returns coordinates in the same frame as paint:
// both the painted button position and the `hit_test` round trip
// must agree on the same absolute frame at a non-zero origin.
let bar = sample_bar();
let origin_x = 7.0_f32;
let origin_y = 13.0_f32;
let (_surface, 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",
);
}
/// Pre-migration macOS painted the hover/pressed/
/// active highlight as a plain square rect (Core Graphics had no
/// rounded-fill convenience this file reached for) — 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 (surface, layout) = paint_via_backend(&bar);
let theme = Theme::default();
let item = &layout.visible_items[0];
// 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.bounds.x + 2.0) as u32;
let corner_y = (item.bounds.y + 2.0) as u32;
let (r, g, b, _) = surface.pixel(corner_x, corner_y);
assert_ne!(
(r, g, 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
// somewhere away from the corners — proves something was painted.
// Avoid the button's exact centre (text is centred there too).
// `measure_button`'s `ACTION_H_PAD = 8.0` means 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.bounds.x + 5.0) as u32;
let cy = (item.bounds.y + item.bounds.height / 2.0) as u32;
let (r, g, b, _) = surface.pixel(cx, cy);
assert_eq!(
(r, g, 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: 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 first_ink_row = |valign: ToolbarVAlign| -> u32 {
let (surface, _layout) = paint_via_backend_with_options(
&bar,
0.0,
0.0,
crate::primitives::toolbar::ToolbarPaintOptions { valign },
);
for y in 0..H {
for x in 0..W {
let (r, g, b, _) = surface.pixel(x, y);
if (r, g, 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})"
);
}
/// `MacBackend::draw_toolbar_with_options` fades a hovered button's
/// highlight in over `HOVER_FADE_DURATION` instead of snapping it to
/// full opacity on the first hovered frame: the very first paint of a
/// newly-hovered button should be visibly dimmer than
/// `theme.hover_bg`, since the fade has only just started.
#[test]
fn hover_highlight_is_dim_on_first_hovered_frame() {
let bar = Toolbar {
id: WidgetId::new("tb"),
buttons: vec![mk_action("tb:refine", "Refine", true)],
bg: None,
focused_index: None,
};
let theme = Theme::default();
let interaction =
crate::InteractionState::from_parts(Some(WidgetId::new("tb:refine")), None);
let ((surface, layout), _backend) =
paint_via_backend_full(&bar, 0.0, 0.0, &interaction, Default::default());
let item = &layout.visible_items[0];
// Sample the highlight fill away from the corners/label, matching
// `active_button_highlight_has_rounded_corners_not_square` above.
let cx = (item.bounds.x + 5.0) as u32;
let cy = (item.bounds.y + item.bounds.height / 2.0) as u32;
let (r, _g, _b, _a) = surface.pixel(cx, cy);
assert_ne!(
r, theme.hover_bg.r,
"first hovered frame should paint a partially faded-in highlight, not the full-opacity colour",
);
}
/// Once a button has been hovered for longer than the fade's
/// duration, the highlight should match the shared, static
/// `theme.hover_bg` fill exactly — the animation hands off to the
/// ordinary binary highlight once it finishes.
#[test]
fn hover_highlight_reaches_full_opacity_after_fade_duration() {
let bar = Toolbar {
id: WidgetId::new("tb"),
buttons: vec![mk_action("tb:refine", "Refine", true)],
bg: None,
focused_index: None,
};
let theme = Theme::default();
let interaction =
crate::InteractionState::from_parts(Some(WidgetId::new("tb:refine")), None);
let (_first, mut backend) =
paint_via_backend_full(&bar, 0.0, 0.0, &interaction, Default::default());
// `HOVER_FADE_DURATION` (120ms) plus generous margin for scheduler
// jitter — mirrors the sleep-based timing tests elsewhere in this
// crate (e.g. `tui::backend`, `win::run`).
std::thread::sleep(std::time::Duration::from_millis(200));
let (surface, layout) = repaint(
&mut backend,
&bar,
0.0,
0.0,
&interaction,
Default::default(),
);
let item = &layout.visible_items[0];
let cx = (item.bounds.x + 5.0) as u32;
let cy = (item.bounds.y + item.bounds.height / 2.0) as u32;
let (r, g, b, _a) = surface.pixel(cx, cy);
assert_eq!(
(r, g, b),
(theme.hover_bg.r, theme.hover_bg.g, theme.hover_bg.b),
"highlight should reach the static theme colour once the fade-in finishes",
);
}
}