kui_core/widgets.rs
1//! Stock widgets built from the primitives: buttons, toggles, text input,
2//! select, slider, splitter, tooltips, menus, a titlebar and virtual lists.
3//!
4//! Every widget here is a plain function over a [`Ui`] that opens ordinary
5//! nodes with ordinary [`NodeSpec`]s; there is no widget trait and no
6//! retained object. State lives in the core by key (focus, hover, an edit
7//! buffer, a scroll offset), and the app's model is the only other state.
8//! A custom widget follows the same pattern, and the `*_spec` functions
9//! ([`button_spec`], [`toggle_spec`], [`slider_spec`], [`menu_panel_spec`])
10//! are the starting points for one that should look like the stock set.
11//!
12//! ```rust
13//! use kui_core::{Core, NodeSpec, Size, Value, widgets};
14//!
15//! let mut core = Core::new();
16//! let mut ui = core.frame(Size::new(400.0, 300.0), 1.0);
17//! ui.configure_root(NodeSpec::column().fill().pad(12.0).gap(8.0));
18//!
19//! widgets::label(&mut ui, "Settings");
20//! let name = widgets::text_input(&mut ui, "name", "Ada");
21//! widgets::checkbox(&mut ui, "Dark mode", true, "toggle-dark");
22//! widgets::slider(&mut ui, "volume", 40.0, 0.0, 100.0, 1.0, "volume");
23//! widgets::button(&mut ui, "Save", Value::str("save"));
24//!
25//! assert_eq!(ui.edit_text(name).as_deref(), Some("Ada"));
26//! ui.finish();
27//! ```
28//!
29//! Each control posts the payload it was given as a
30//! [`UiEvent`](crate::input::UiEvent) when it is used, and the view redraws
31//! from its model; a checkbox does not flip itself.
32
33use crate::access::Role;
34use crate::color::Color;
35use crate::cursor::CursorShape;
36use crate::edit::EditOptions;
37use crate::geom::{Edges, Vec2};
38use crate::key::Key;
39use crate::menu::{MenuBar, MenuItem, MenuRole};
40use crate::metrics::Metrics;
41use crate::spec::{Align, FloatConfig, NodeSpec, Sizing, TextStyle};
42use crate::stats::{FrameSample, STATS_CAPACITY};
43use crate::theme::Theme;
44use crate::tree::OriginId;
45use crate::ui::Ui;
46use crate::value::Value;
47use crate::window::WindowButton;
48
49/// Floating latency HUD: `latency_graph` in a translucent panel pinned to a
50/// viewport corner, above all content and out of layout flow. Call anywhere
51/// in the view; pick the corner with `latency_hud_at`.
52pub fn latency_hud(ui: &mut Ui<'_>) {
53 latency_hud_at(ui, Align::End, Align::End);
54}
55
56pub fn latency_hud_at(ui: &mut Ui<'_>, x: Align, y: Align) {
57 // Under custom chrome the top of the viewport is the app's titlebar;
58 // keep the HUD below it.
59 let top_inset = if ui.env().window.custom_chrome {
60 titlebar_height(ui)
61 } else {
62 0.0
63 };
64 // The same attach points a float takes, which place the spreads and
65 // `Baseline` as the start or the centre (`layout::align_factor`).
66 let dx = match x {
67 Align::Start | Align::SpaceBetween | Align::Baseline => 12.0,
68 Align::Center | Align::SpaceAround | Align::SpaceEvenly => 0.0,
69 Align::End => -12.0,
70 };
71 let dy = match y {
72 Align::Start | Align::SpaceBetween | Align::Baseline => 12.0 + top_inset,
73 Align::Center | Align::SpaceAround | Align::SpaceEvenly => 0.0,
74 Align::End => -12.0,
75 };
76 // Translucent over whatever the app is painting, so the panel takes
77 // the theme's backmost surface and its strong border at the alphas
78 // the HUD has always used.
79 let t = ui.theme();
80 ui.with(
81 NodeSpec::column()
82 .float(
83 crate::spec::FloatConfig::viewport()
84 .inside(x, y)
85 .offset(dx, dy),
86 )
87 .pad(10.0)
88 .bg(t.bg.with_alpha(0.71))
89 .radius(8.0)
90 .border(1.0, t.border_strong.with_alpha(0.5)),
91 latency_graph,
92 );
93}
94
95/// Frame-latency graph: the last ~120 frames as stacked per-phase bars
96/// (input / view / layout / render, bottom to top) against the display's
97/// frame budget (`env.refresh_hz`, 120 Hz fallback) — a bar that blows the
98/// budget turns red. Feed `core.stats` (and `core.env`) from your frame
99/// driver (the built-in runner does this automatically).
100pub fn latency_graph(ui: &mut Ui<'_>) {
101 const GRAPH_H: f32 = 34.0;
102 const INPUT: Color = Color {
103 r: 0.45,
104 g: 0.85,
105 b: 0.55,
106 a: 1.0,
107 };
108 const VIEW: Color = Color {
109 r: 0.28,
110 g: 0.42,
111 b: 0.88,
112 a: 1.0,
113 };
114 const LAYOUT: Color = Color {
115 r: 0.60,
116 g: 0.42,
117 b: 0.88,
118 a: 1.0,
119 };
120 const RENDER: Color = Color {
121 r: 0.94,
122 g: 0.72,
123 b: 0.35,
124 a: 1.0,
125 };
126 const WAIT: Color = Color {
127 r: 0.42,
128 g: 0.45,
129 b: 0.52,
130 a: 0.7,
131 };
132 const OVER: Color = Color {
133 r: 0.91,
134 g: 0.36,
135 b: 0.36,
136 a: 1.0,
137 };
138
139 let theme = ui.theme();
140 let budget_ms = ui.env().frame_budget_ms(); // full graph height
141 let stats = &ui.core().stats;
142 let samples: Vec<FrameSample> = stats.iter().collect();
143 let (avg_work, max_work) = (stats.avg_work(), stats.max_work());
144 let avg_wait = if samples.is_empty() {
145 0.0
146 } else {
147 samples.iter().map(|s| s.wait_ms).sum::<f32>() / samples.len() as f32
148 };
149
150 // A development overlay, not app content: kept out of the access tree
151 // so a screen reader does not read frame timings between the controls.
152 ui.with(
153 NodeSpec::column()
154 .gap(3.0)
155 .cross_align(Align::End)
156 .role(crate::access::Role::None),
157 |ui| {
158 let mut label = format!("work {avg_work:.2}ms avg · {max_work:.2}ms max");
159 if avg_wait > 0.05 {
160 label.push_str(&format!(" · +{avg_wait:.2}ms vsync"));
161 }
162 ui.with(NodeSpec::row().gap(6.0).cross_align(Align::Center), |ui| {
163 ui.text(&label, TextStyle::new(10.0).color(theme.muted));
164 // "?" badge: hover for the color legend. Also the dynamic-float
165 // showcase — in the default bottom-right HUD the tooltip has no
166 // room below or to the right, so it flips above and slides left.
167 let badge = ui.child_key("kui:latency-legend");
168 let badge_bg =
169 theme
170 .muted
171 .with_alpha(if ui.is_hovered(badge) { 0.31 } else { 0.16 });
172 ui.with_keyed(
173 "kui:latency-legend",
174 NodeSpec::column()
175 .size(13.0, 13.0)
176 .center()
177 .bg(badge_bg)
178 .radius(6.5)
179 .hoverable(),
180 |ui| {
181 ui.text("?", TextStyle::new(9.0).color(theme.fg));
182 if ui.is_hovered(badge) {
183 tooltip_with(ui, |ui| {
184 ui.with(NodeSpec::column().gap(5.0), |ui| {
185 for (color, name) in [
186 (INPUT, "input — events & edits"),
187 (VIEW, "view — rebuilding the tree"),
188 (LAYOUT, "layout — sizing & positions"),
189 (RENDER, "render — encode + submit"),
190 (WAIT, "vsync wait (not work)"),
191 (OVER, "cap: work over frame budget"),
192 ] {
193 ui.with(
194 NodeSpec::row().gap(7.0).cross_align(Align::Center),
195 |ui| {
196 ui.leaf(
197 NodeSpec::column()
198 .size(9.0, 9.0)
199 .bg(color)
200 .radius(2.0),
201 );
202 ui.text(name, TextStyle::new(11.0).color(theme.fg));
203 },
204 );
205 }
206 });
207 });
208 }
209 },
210 );
211 });
212 ui.with(
213 NodeSpec::row()
214 .size(STATS_CAPACITY as f32 * 2.0, GRAPH_H)
215 .gap(1.0)
216 .main_align(Align::End)
217 .cross_align(Align::End)
218 .bg(theme.sunken.with_alpha(0.6))
219 .radius(3.0)
220 .clip(),
221 |ui| {
222 let px_per_ms = GRAPH_H / budget_ms;
223 for s in &samples {
224 // Phases keep their colors even over budget — a spike
225 // you can't attribute is a spike you can't fix. Work
226 // (not vsync pacing) over budget gets a red cap.
227 let over = s.work() > budget_ms;
228 ui.with(
229 NodeSpec::column()
230 .width(1.0)
231 .main_align(Align::End)
232 .max_height(GRAPH_H),
233 |ui| {
234 if over {
235 ui.leaf(NodeSpec::column().size(1.0, 3.0).bg(OVER));
236 }
237 // Column children run top->bottom; push in
238 // reverse so input sits at the bottom.
239 for (ms, color) in [
240 (s.wait_ms, WAIT),
241 (s.render_ms, RENDER),
242 (s.layout_ms, LAYOUT),
243 (s.view_ms, VIEW),
244 (s.input_ms, INPUT),
245 ] {
246 if ms <= 0.0 {
247 continue;
248 }
249 let h = (ms * px_per_ms).max(1.0);
250 ui.leaf(NodeSpec::column().size(1.0, h).bg(color));
251 }
252 },
253 );
254 }
255 },
256 );
257 },
258 );
259}
260
261/// Small floating label hanging below the node it's declared inside. The
262/// placement is dynamic (`FloatConfig::fit`): it flips above when the
263/// viewport bottom is too close and slides sideways off window edges.
264/// Typical use: `if ui.is_hovered(key) { widgets::tooltip(ui, "..."); }`
265pub fn tooltip(ui: &mut Ui<'_>, text: &str) {
266 let size = ui.metrics().hint_text;
267 tooltip_with(ui, |ui| {
268 ui.text(text, TextStyle::new(size));
269 });
270}
271
272/// [`tooltip`] chrome around arbitrary content (legends, shortcut hints, …).
273pub fn tooltip_with(ui: &mut Ui<'_>, content: impl FnOnce(&mut Ui<'_>)) {
274 let spec = tooltip_spec(ui);
275 ui.with(spec, content);
276}
277
278/// The hint the `tooltip` prop floats under a hovered node, and the stock
279/// button under a hovered button: [`tooltip`]'s chrome and text, kept out
280/// of the access tree (`Role::None`). The prop has already set the same
281/// string as the node's description, which is where a reader hears it;
282/// as content it would be read twice under a group and, under a control
283/// named from its content, become part of the *name* whenever the pointer
284/// crossed it. The `tooltip` element keeps its text, since
285/// it is drawn with no description behind it.
286pub(crate) fn hover_hint(ui: &mut Ui<'_>, text: &str) {
287 let size = ui.metrics().hint_text;
288 let spec = tooltip_spec(ui).role(crate::access::Role::None);
289 ui.text_in(spec, text, TextStyle::new(size));
290}
291
292/// [`hover_hint`] for a leaf — a `line`, a `polygon`, a `path`, a `cells`
293/// grid, an image, an editor — which holds no children for the hint to
294/// float as the last of (backlog RG113). The hint is opened beside the
295/// leaf, in the leaf's parent, and anchored to the leaf by key
296/// (`FloatAnchor::Node`), so it is laid out against the leaf's box once
297/// that is placed and lands below it as a box's lands below the box. Its
298/// key is the leaf's own child key: an auto-keyed one would take the
299/// parent's next sibling slot while the pointer is over the leaf and
300/// shift the key of every sibling declared after it.
301pub(crate) fn leaf_hint(ui: &mut Ui<'_>, leaf: Key, text: &str) {
302 let size = ui.metrics().hint_text;
303 let mut spec = tooltip_spec(ui).role(crate::access::Role::None);
304 if let Some(float) = spec.layout.float.as_mut() {
305 float.anchor = crate::spec::FloatAnchor::Node(leaf);
306 }
307 ui.core().open_key(leaf.str("tooltip"), spec);
308 ui.text(text, TextStyle::new(size));
309 ui.close();
310}
311
312fn tooltip_spec(ui: &Ui<'_>) -> NodeSpec {
313 let t = ui.theme();
314 let m = ui.metrics();
315 NodeSpec::column()
316 .float(crate::spec::FloatConfig::below().fit())
317 .pad_xy(m.hint_pad_x, m.hint_pad_y)
318 .bg(t.raised)
319 .radius(m.radius)
320 .border(1.0, t.border_strong)
321}
322
323/// A line of text in the default style: `ui.text(text, TextStyle::default())`.
324pub fn label(ui: &mut Ui<'_>, text: &str) {
325 ui.text(text, TextStyle::default());
326}
327
328/// Single-line text input with chrome (background, focus ring).
329/// Read the value with `ui.edit_text(key)`; "changed"/"submit" events arrive
330/// in `on_event` with this key. The `label` is the key and the accessible
331/// name both (`"search"`, `"name"`), so a screen reader has something to
332/// announce; use `ui.text_edit` with `NodeSpec::label` when they differ.
333pub fn text_input(ui: &mut Ui<'_>, label: &str, initial: &str) -> Key {
334 let key = ui.child_key(label);
335 let t = ui.theme();
336 let m = ui.metrics();
337 let border = if ui.is_focused(key) {
338 t.accent
339 } else {
340 t.border
341 };
342 ui.text_edit(
343 label,
344 initial,
345 &EditOptions {
346 multiline: false,
347 ..Default::default()
348 },
349 NodeSpec::column()
350 .grow_width()
351 .pad_xy(m.field_pad_x, m.field_pad_y)
352 .bg(t.sunken)
353 .radius(m.radius)
354 .border(1.0, border)
355 .clip()
356 .label(label),
357 )
358}
359
360/// What a select's trigger posts when it is clicked; the core takes it
361/// back and opens the menu (`Core::consume_select_events`).
362pub(crate) fn select_tag() -> Value {
363 Value::map([("select", Value::Bool(true))])
364}
365
366/// A choice among a few named options: a field that shows the one in
367/// force and, clicked, drops a menu of them all with the current one
368/// checked. `options` are the labels, `current` the index in force (or
369/// none). Keyed by `label`, which is the accessible name too.
370///
371/// The menu is the core's own — the same one a right-click opens
372/// (`Core::open_menu`): drawn in the frame, or the platform's where the
373/// host shows menus itself, dismissed by Escape or a press outside, its
374/// rows walked by the arrows. So the app holds no open state; what it
375/// hears is the choice, as the `menu` event a menu row posts, on this
376/// key: `{kind: "menu", role: "custom", item: <the option>}`. A view
377/// that then draws the select with the new `current` is the whole loop.
378///
379/// [`select_items`] is the same field over [`MenuItem`]s, for an option
380/// that posts an `id` of its own rather than its label.
381pub fn select(ui: &mut Ui<'_>, label: &str, options: &[&str], current: Option<usize>) -> Key {
382 let items: Vec<MenuItem> = options.iter().map(|o| MenuItem::new(*o)).collect();
383 select_items(ui, label, &items, current)
384}
385
386/// [`select`] over items the caller built: their labels are the rows,
387/// their `id`s what a choice posts, and the `current`th is drawn checked
388/// whatever the item said. A separator is a separator here too.
389pub fn select_items(
390 ui: &mut Ui<'_>,
391 label: &str,
392 items: &[MenuItem],
393 current: Option<usize>,
394) -> Key {
395 let t = ui.theme();
396 let m = ui.metrics();
397 select_with(
398 ui,
399 label,
400 items,
401 current,
402 select_spec(&t, &m),
403 TextStyle::new(m.chrome_text),
404 )
405}
406
407/// The stock select field's spec: a sunken field with the stock radius
408/// and padding, as [`button_spec`] is the stock button's. What
409/// [`select_with`] is handed by [`select_items`]; a caller with a spec
410/// of its own starts here and adds to it.
411pub fn select_spec(theme: &Theme, m: &Metrics) -> NodeSpec {
412 NodeSpec::row()
413 .pad_xy(m.field_pad_x, m.field_pad_y)
414 .gap(8.0)
415 .cross_align(Align::Center)
416 .bg(theme.sunken)
417 .hover_bg(theme.hover)
418 .radius(m.radius)
419}
420
421/// [`select_items`] with its spec and text style in the caller's hands —
422/// a compact field in a dense panel — the way [`button_with`] takes the
423/// button's. The border, the click, the role and the disclosure are
424/// added here whatever `spec` said.
425///
426/// A `current` that names no option (past the end, or a separator) is
427/// none, with a `select-current-ignored` warning on the field: the field
428/// is described by nothing and no row is checked.
429pub fn select_with(
430 ui: &mut Ui<'_>,
431 label: &str,
432 items: &[MenuItem],
433 current: Option<usize>,
434 spec: NodeSpec,
435 text: TextStyle,
436) -> Key {
437 let key = ui.child_key(label);
438 let current = current.filter(|&i| {
439 let separator = items
440 .get(i)
441 .is_some_and(|it| it.role == MenuRole::Separator);
442 let names_one = i < items.len() && !separator;
443 if !names_one {
444 ui.core().warn(crate::diag::select_current_ignored(
445 key,
446 label,
447 i,
448 items.len(),
449 separator,
450 ));
451 }
452 names_one
453 });
454 let t = ui.theme();
455 let shown = current
456 .and_then(|i| items.get(i))
457 .map_or("", |i| i.text())
458 .to_string();
459 let open = ui.core().menu().is_some_and(|menu| menu.target == key);
460 let border = if open || ui.is_focused(key) {
461 t.accent
462 } else {
463 t.border
464 };
465 // An option is chosen, never opened: rows it was handed with a submenu
466 // (a C `KuiMenuItem`'s `submenu`, a data option's `items`) are dropped,
467 // so `current` always names a row of this one menu (backlog RG150).
468 let menu: Vec<MenuItem> = items
469 .iter()
470 .enumerate()
471 .map(|(i, item)| {
472 let mut row = item.clone().checked(current == Some(i));
473 row.submenu = Vec::new();
474 row
475 })
476 .collect();
477 ui.core().declare_select(key, menu);
478 ui.with_keyed(
479 label,
480 spec.border(1.0, border)
481 .cursor(CursorShape::Pointer)
482 .on_click(select_tag())
483 // A button named by the field, described by the choice: what
484 // a reader says of a pop-up button, in the two slots a button
485 // has (`value` is a slider's and an editor's).
486 .role(Role::Button)
487 .label(label)
488 .description(shown.as_str())
489 .expanded(open),
490 |ui| {
491 ui.text(&shown, text.color(t.fg).nowrap());
492 // The disclosure: a small triangle, the mark every platform's
493 // pop-up field carries.
494 ui.text("\u{25BE}", text.color(t.muted));
495 },
496 )
497}
498
499/// Default titlebar height, logical px, where the strip is the app's
500/// alone. Follows platform conventions (as measured by gpui): 32 on
501/// Windows (the native caption height), 34 elsewhere. The stock
502/// [`Metrics`] carries the same number as `titlebar_h`, and the titlebar
503/// draws from *that*, so an app that set its own metrics lays out against
504/// `ui.metrics().titlebar_h` rather than this constant — and where the OS
505/// keeps controls of its own over the strip, against [`titlebar_height`].
506pub const TITLEBAR_H: f32 = Metrics::comfortable().titlebar_h;
507
508/// The height the titlebar strip draws at — what an app laying out its
509/// own strip, or something under it, should read instead of
510/// `ui.metrics().titlebar_h`. Where the OS keeps controls of its own over
511/// the strip (`env.window.native_controls`: the macOS traffic lights under
512/// custom chrome) the strip is the OS's own titlebar, as tall as the
513/// keep-out rect says that titlebar is, so the strip's content centres on
514/// the buttons the OS centred in it. Everywhere else the strip is the app's alone and
515/// `Metrics::titlebar_h` is its height. A keep-out with no height (a host
516/// that reported a width only) falls back to the metric.
517pub fn titlebar_height(ui: &Ui<'_>) -> f32 {
518 match ui.env().window.native_controls {
519 Some(r) if r.h > 0.0 => r.h,
520 _ => ui.metrics().titlebar_h,
521 }
522}
523
524/// A cross-platform titlebar: a full-width drag strip with the window title
525/// left-aligned next to the window controls. Reads `env.window` and adapts
526/// by itself — under macOS custom chrome it insets past the native traffic
527/// lights and draws no buttons; under custom chrome elsewhere it appends
528/// minimize/maximize/close; under native decorations it is just a drag
529/// strip (no duplicate buttons).
530///
531/// Typical use, as the first child of a full-height root:
532/// `widgets::titlebar(ui, "my app")`.
533pub fn titlebar(ui: &mut Ui<'_>, title: &str) {
534 let focused = ui.env().focused;
535 let title = title.to_string();
536 titlebar_with(ui, move |ui| {
537 // A background window's title recedes; the OS does the same.
538 let t = ui.theme();
539 let size = ui.metrics().chrome_text;
540 let color = if focused { t.fg } else { t.faint };
541 ui.text_in(
542 NodeSpec::row().fill().cross_align(Align::Center),
543 &title,
544 TextStyle::new(size).color(color).ellipsis(),
545 );
546 });
547}
548
549/// Titlebar with custom content (tabs, a search box, …) between the
550/// platform inset and the window buttons. The whole strip is a drag
551/// handle; interactive children declared inside it sit on top and win
552/// hit-testing, so buttons in a titlebar just work.
553pub fn titlebar_with(ui: &mut Ui<'_>, content: impl FnOnce(&mut Ui<'_>)) {
554 let win = ui.env().window;
555 let h = titlebar_height(ui);
556 ui.with_keyed(
557 "kui:titlebar",
558 NodeSpec::row()
559 .grow_width()
560 .height(h)
561 .cross_align(Align::Center)
562 .window_drag(),
563 |ui| {
564 // Keep clear of controls the OS draws over our content (the
565 // reported rect already includes the trailing gap); without
566 // them, a plain leading margin.
567 let inset = win.native_controls.map_or(12.0, |r| r.x + r.w);
568 ui.leaf(NodeSpec::row().width(inset));
569 content(ui);
570 window_buttons(ui);
571 },
572 );
573}
574
575/// The minimize/maximize/close cluster. Renders nothing when the OS already
576/// provides controls (native decorations, or macOS traffic lights), so it
577/// is always safe to call. It grows to the height it is given — the
578/// strip's, in [`titlebar_with`] — and is a titlebar tall where nothing
579/// gives it one, since a grow child adds nothing to a fit parent's
580/// height.
581pub fn window_buttons(ui: &mut Ui<'_>) {
582 let win = ui.env().window;
583 if !win.custom_chrome || win.native_controls.is_some() {
584 return;
585 }
586 let h = titlebar_height(ui);
587 ui.with(NodeSpec::row().grow_height().min_height(h), |ui| {
588 window_button(ui, WindowButton::Minimize, win.maximized);
589 window_button(ui, WindowButton::Maximize, win.maximized);
590 window_button(ui, WindowButton::Close, win.maximized);
591 });
592}
593
594fn window_button(ui: &mut Ui<'_>, button: WindowButton, maximized: bool) {
595 let label = match button {
596 WindowButton::Minimize => "kui:win-min",
597 WindowButton::Maximize => "kui:win-max",
598 WindowButton::Close => "kui:win-close",
599 };
600 let key = ui.child_key(label);
601 let (hovered, pressed) = (ui.is_hovered(key), ui.is_pressed(key));
602 let t = ui.theme();
603 let fg = t.fg;
604 // Close is the one button that keeps a colour of its own on both
605 // bases — it is the platform's signal, not the palette's — but it is
606 // the theme's danger rather than a second red.
607 let (bg, fg) = match button {
608 WindowButton::Close if pressed => (t.danger.mix(Color::BLACK, 0.15), Color::WHITE),
609 WindowButton::Close if hovered => (t.danger, Color::WHITE),
610 _ if pressed => (t.pressed, fg),
611 _ if hovered => (t.hover, fg),
612 _ => (Color::TRANSPARENT, fg),
613 };
614 ui.with_keyed(
615 label,
616 NodeSpec::row()
617 .width(46.0)
618 .grow_height()
619 .center()
620 .bg(bg)
621 .window_button(button),
622 |ui| match button {
623 WindowButton::Minimize => {
624 ui.leaf(NodeSpec::row().size(10.0, 1.0).bg(fg));
625 }
626 WindowButton::Maximize if maximized => {
627 // Restore: two offset outlines.
628 ui.with(NodeSpec::column().size(10.0, 10.0), |ui| {
629 for (x, y) in [(Align::End, Align::Start), (Align::Start, Align::End)] {
630 ui.leaf(
631 NodeSpec::column()
632 .size(7.5, 7.5)
633 .border(1.0, fg)
634 .float(crate::spec::FloatConfig::parent().inside(x, y)),
635 );
636 }
637 });
638 }
639 WindowButton::Maximize => {
640 ui.leaf(NodeSpec::column().size(9.0, 9.0).border(1.0, fg));
641 }
642 WindowButton::Close => {
643 // The multiplication sign inks only about 0.42 em, so it
644 // needs a far larger em than the 9-10px bar and box beside
645 // it to read as the same size. It also rides the math axis,
646 // which sits a little under the middle of the line box, so
647 // the bottom padding lifts it back onto the button center.
648 const EM: f32 = 23.0;
649 ui.text_in(
650 NodeSpec::row().padding(Edges {
651 b: EM * 0.25,
652 ..Edges::default()
653 }),
654 "\u{00d7}",
655 TextStyle::new(EM).line_height(EM).color(fg),
656 );
657 }
658 },
659 );
660}
661
662/// The standard button's spec: hover and pressed backgrounds are declared
663/// on the node and resolved by the core, so every binding's button is this
664/// same data. Add the label as a child.
665///
666/// The three backgrounds are the theme's accent trio (`accent`,
667/// `accent_hover`, `accent_pressed`): the OS's accent where the host
668/// reports one, the app's where it set or pinned one, and kui's blue
669/// otherwise. Takes the theme and the metrics rather than reading them, so
670/// `widgets::button_spec(&ui.theme(), &ui.metrics())` is the idiom. The
671/// derivation for any other base colour is [`button_palette`].
672pub fn button_spec(theme: &Theme, m: &Metrics) -> NodeSpec {
673 NodeSpec::row()
674 .pad_xy(m.control_pad_x, m.control_pad_y)
675 .bg(theme.accent)
676 .hover_bg(theme.accent_hover)
677 .pressed_bg(theme.accent_pressed)
678 .radius(m.radius)
679 .center()
680}
681
682/// A button's three backgrounds from one base colour: the base, a hover a
683/// step toward white, a pressed a step toward black. The steps are the
684/// distances the stock button's own trio sits at, so an accent-painted
685/// button reads as the same control in a different colour.
686///
687/// Public because "a button in *this* colour" is the same question with a
688/// different answer, and the arithmetic should not be re-guessed per app.
689pub fn button_palette(base: Color) -> (Color, Color, Color) {
690 (
691 base,
692 base.mix(Color::WHITE, 0.09),
693 base.mix(Color::BLACK, 0.10),
694 )
695}
696
697/// Black or white, whichever a reader can see on `bg`.
698///
699/// The split is at `Color::luminance` 0.4 rather than at the midpoint:
700/// white text needs a darker background than black text needs a light one,
701/// and the accents that land near the line (macOS's yellow at 0.72, its
702/// orange at 0.44) come out the way the platform paints them. It is the
703/// stock button's answer, not a general contrast checker — a palette that
704/// cares should say what its label colour is.
705pub fn readable_on(bg: Color) -> Color {
706 if bg.luminance() > 0.4 {
707 Color::BLACK
708 } else {
709 Color::WHITE
710 }
711}
712
713/// The stock button's text size — [`Metrics::default`]'s `control_text`;
714/// the widget itself reads `ui.metrics()`.
715pub const BUTTON_TEXT: f32 = Metrics::comfortable().control_text;
716/// What a disabled stock button's opacity is multiplied by. The core makes
717/// it inert and drops its hover and pressed backgrounds, and nothing else
718/// would show a sighted user the state a reader is told.
719pub const BUTTON_DISABLED_OPACITY: f32 = 0.5;
720
721/// A push button showing `text`, keyed by it; a click posts `payload` as
722/// a [`UiEvent`](crate::input::UiEvent) on the button's key.
723///
724/// ```rust
725/// # use kui_core::{Core, NodeSpec, Size, widgets};
726/// # let mut core = Core::new();
727/// # let mut ui = core.frame(Size::new(200.0, 100.0), 1.0);
728/// widgets::button(&mut ui, "Save", "save");
729/// // The same button with its spec in hand: a tooltip and a stable key.
730/// let (t, m) = (ui.theme(), ui.metrics());
731/// widgets::button_with(&mut ui, "save-2", "Save", widgets::button_spec(&t, &m).on_click("save"), Some("Ctrl+S"));
732/// # ui.finish();
733/// ```
734///
735/// A label that changes re-keys the node (a new node, so it loses keyboard
736/// focus and a screen reader's cursor); declare such a button with
737/// [`button_with`] and a key of its own. The pointer over it is the hand
738/// (`CursorShape::Pointer`): the core implies no shape from an `on_click`,
739/// and the stock button is the one place the hand is declared for you.
740pub fn button(ui: &mut Ui<'_>, text: &str, payload: impl Into<Value>) {
741 let (theme, m) = (ui.theme(), ui.metrics());
742 button_with(
743 ui,
744 text,
745 text,
746 button_spec(&theme, &m).on_click(payload.into()),
747 None,
748 );
749}
750
751/// [`button`] with its spec in the caller's hands: `spec` is [`button_spec`]
752/// plus what the caller declared on it — the `on_click`, and the rows the
753/// stock button admits in every binding (`schema::BUTTON_ROWS_JSX`): a
754/// `label` when the text is not the name, a `description`, `disabled`,
755/// and the hover tracking and description a `tooltip` sets, whose float
756/// is `hint` — drawn under the button while it is hovered, as every
757/// binding's `tooltip` prop floats one. Keyed by `key`, so a label that
758/// changes need not re-key the node. A disabled button is dimmed
759/// ([`BUTTON_DISABLED_OPACITY`]) as well as inert.
760///
761/// This is what `<button>`, `button { }` and `kui_button_with` lower to,
762/// so a binding cannot end up with a button of its own.
763pub fn button_with(ui: &mut Ui<'_>, key: &str, text: &str, spec: NodeSpec, hint: Option<&str>) {
764 button_body(ui, Ident::Label(key), text, spec, hint);
765}
766
767/// [`button_with`] keyed by a data index rather than a label — a row of a
768/// virtual list (`Ui::open_indexed`), so the button keeps its focus, its
769/// hover and its tweens as the built range slides and the same text on
770/// two rows is two nodes. What `<button index>` and
771/// `button { index = }` lower to.
772pub fn button_indexed(ui: &mut Ui<'_>, index: u64, text: &str, spec: NodeSpec, hint: Option<&str>) {
773 button_body(ui, Ident::Index(index), text, spec, hint);
774}
775
776/// How a button is keyed: by the label its `key` declares, or by the
777/// data index its `index` declares.
778enum Ident<'a> {
779 Label(&'a str),
780 Index(u64),
781}
782
783/// A widget that takes a `hint` floats it itself, so a spec that also
784/// declared [`NodeSpec::tooltip`] does not float a second one.
785fn own_hint(spec: &mut NodeSpec, hint: Option<&str>) {
786 if hint.is_some() && spec.access().tooltip {
787 spec.access_mut().tooltip = false;
788 }
789}
790
791fn button_body(ui: &mut Ui<'_>, ident: Ident<'_>, text: &str, spec: NodeSpec, hint: Option<&str>) {
792 let theme = ui.theme();
793 // `accent` asks for the whole family, not just the background the
794 // core would substitute for any node: a button whose hover and pressed
795 // shades stayed put would flash under a yellow accent. On a stock
796 // spec it changes nothing — `button_spec` paints from the theme's
797 // trio already (AR41) — and on a spec whose caller set its own `bg`
798 // it is the ask to take the theme's instead. The family is the
799 // *theme's*, and the theme always has one, so there is no
800 // gate here: kui's blue is the accent nobody chose.
801 let spec = if spec.accent {
802 spec.bg(theme.accent)
803 .hover_bg(theme.accent_hover)
804 .pressed_bg(theme.accent_pressed)
805 } else {
806 spec
807 };
808 let spec = if spec.disabled {
809 let o = spec.style.opacity * theme.disabled_opacity;
810 spec.opacity(o)
811 } else {
812 spec
813 };
814 // The hand is declared, never derived from the `on_click`
815 // (`crate::cursor`), and the stock button is where it is declared: a
816 // caller's own `cursor` stands, and an inert button is the arrow — the
817 // click it refuses is not one to point at.
818 let spec = if spec.cursor.is_none() && !spec.disabled {
819 spec.cursor(CursorShape::Pointer)
820 } else {
821 spec
822 };
823 // The hint floats out of the access tree (`hover_hint`), so it is
824 // heard only as the description: a caller that passed one without
825 // `apply_tooltip` on the spec still has it said. A declared
826 // description stands, as it does over the prop.
827 let mut spec = match hint {
828 Some(hint) if spec.access().description.is_none() => spec.apply_tooltip(hint),
829 _ => spec,
830 };
831 own_hint(&mut spec, hint);
832 // Whatever the background ended up being: white on the stock blue as
833 // it has always been, black on an accent light enough to need it.
834 let label = readable_on(spec.style.bg);
835 let size = ui.metrics().control_text;
836 let node = match ident {
837 Ident::Label(key) => ui.child_key(key),
838 Ident::Index(i) => ui.child_key_indexed(i),
839 };
840 let body = |ui: &mut Ui<'_>| {
841 ui.text(text, TextStyle::new(size).color(label));
842 if let Some(hint) = hint
843 && ui.is_hovered(node)
844 {
845 hover_hint(ui, hint);
846 }
847 };
848 match ident {
849 Ident::Label(key) => {
850 ui.with_keyed(key, spec, body);
851 }
852 Ident::Index(i) => {
853 ui.with_indexed(i, spec, body);
854 }
855 }
856}
857
858// -- Stock controls ---------------------------------------------------------
859// The stock controls over the roles: checkbox, radio, switch
860// and slider, composed over the roles the core already reads. The state is
861// the app's and rides on the spec — `checked`, `mixed`, `value_now` — so a
862// control is drawn from what the view declared this frame, and a toggle's
863// press is its `on_click` like any button's. One definition per control:
864// every binding's element lowers to the `*_with` here.
865
866/// The side of a stock control's box — a checkbox, a radio's circle, a
867/// switch's height, a slider's thumb — from the metrics' control text, so
868/// `compact` and `scaled` move it with the stock button: 16 px at the
869/// comfortable density, 14 at the compact one.
870pub fn control_box(m: &Metrics) -> f32 {
871 (m.control_text + 1.0).round()
872}
873
874/// Which toggle a [`toggle_with`] draws.
875#[derive(Clone, Copy, Debug, PartialEq, Eq)]
876pub enum Toggle {
877 Checkbox,
878 Radio,
879 Switch,
880}
881
882impl Toggle {
883 /// The role it declares, whatever the spec said.
884 pub fn role(self) -> Role {
885 match self {
886 Toggle::Checkbox => Role::Checkbox,
887 Toggle::Radio => Role::Radio,
888 Toggle::Switch => Role::Switch,
889 }
890 }
891
892 /// The element's name in every binding.
893 pub fn name(self) -> &'static str {
894 match self {
895 Toggle::Checkbox => "checkbox",
896 Toggle::Radio => "radio",
897 Toggle::Switch => "switch",
898 }
899 }
900}
901
902/// A stock toggle's spec — the row its indicator and label sit in — as
903/// [`button_spec`] is the button's. A caller with a spec of its own starts
904/// here and adds the state (`checked`, `mixed`), the `on_click` and the
905/// access rows to it.
906pub fn toggle_spec(m: &Metrics) -> NodeSpec {
907 NodeSpec::row()
908 .gap((control_box(m) / 2.0).round())
909 .cross_align(Align::Center)
910}
911
912/// A checkbox labelled `text`, keyed by it, drawn from `checked`; a press
913/// — pointer, Space, Enter or assistive technology — posts `payload`,
914/// and the view flips its model and draws it again.
915pub fn checkbox(ui: &mut Ui<'_>, text: &str, checked: bool, payload: impl Into<Value>) -> Key {
916 let m = ui.metrics();
917 toggle_with(
918 ui,
919 Toggle::Checkbox,
920 text,
921 text,
922 toggle_spec(&m).checked(checked).on_click(payload.into()),
923 None,
924 )
925}
926
927/// A radio labelled `text`, keyed by it; see [`checkbox`]. Radios belong in
928/// a [`radio_group_with`], whose arrows move the choice.
929pub fn radio(ui: &mut Ui<'_>, text: &str, checked: bool, payload: impl Into<Value>) -> Key {
930 let m = ui.metrics();
931 toggle_with(
932 ui,
933 Toggle::Radio,
934 text,
935 text,
936 toggle_spec(&m).checked(checked).on_click(payload.into()),
937 None,
938 )
939}
940
941/// A switch labelled `text`, keyed by it; see [`checkbox`].
942pub fn switch(ui: &mut Ui<'_>, text: &str, on: bool, payload: impl Into<Value>) -> Key {
943 let m = ui.metrics();
944 toggle_with(
945 ui,
946 Toggle::Switch,
947 text,
948 text,
949 toggle_spec(&m).checked(on).on_click(payload.into()),
950 None,
951 )
952}
953
954/// A toggle with its spec in the caller's hands, the way [`button_with`]
955/// takes the button's: `spec` is [`toggle_spec`] plus the state and the
956/// rows the element admits — `checked`, `mixed` (a checkbox's third
957/// state), `on_click`, `label`, `description`, `disabled`, and `hint`, the
958/// tooltip drawn while it is hovered. The role is `kind`'s whatever the
959/// spec said. Keyed by `key`; an empty `text` draws the indicator alone,
960/// which then wants a `label`. A disabled toggle is dimmed as well as
961/// inert. This is what `<checkbox>`, `<radio>`, `<switch>` and their Lua
962/// and C doors lower to.
963pub fn toggle_with(
964 ui: &mut Ui<'_>,
965 kind: Toggle,
966 key: &str,
967 text: &str,
968 spec: NodeSpec,
969 hint: Option<&str>,
970) -> Key {
971 let t = ui.theme();
972 let m = ui.metrics();
973 let node = ui.child_key(key);
974 let ax = spec.access();
975 let mixed = ax.mixed && kind == Toggle::Checkbox;
976 let on = ax.checked || mixed;
977 let disabled = spec.disabled;
978 let hovered = !disabled && ui.is_hovered(node);
979 let mut spec = spec.role(kind.role());
980 own_hint(&mut spec, hint);
981 if disabled {
982 let o = spec.style.opacity * t.disabled_opacity;
983 spec = spec.opacity(o);
984 } else if spec.cursor.is_none() {
985 spec = spec.cursor(CursorShape::Pointer);
986 }
987 let b = control_box(&m);
988 ui.with_keyed(key, spec, |ui| {
989 let edge = if on || hovered {
990 t.accent
991 } else {
992 t.border_strong
993 };
994 match kind {
995 Toggle::Checkbox | Toggle::Radio => {
996 let radius = if kind == Toggle::Radio {
997 b / 2.0
998 } else {
999 m.radius_inner.min(b / 4.0)
1000 };
1001 let face = NodeSpec::row()
1002 .size(b, b)
1003 .radius(radius)
1004 .border(1.0, edge)
1005 .bg(if on { t.accent } else { t.sunken })
1006 .center();
1007 ui.with(face, |ui| {
1008 if !on {
1009 return;
1010 }
1011 if kind == Toggle::Radio {
1012 let d = (b * 0.4).round();
1013 ui.leaf(NodeSpec::row().size(d, d).radius(d / 2.0).bg(t.on_accent));
1014 } else if mixed {
1015 ui.leaf(
1016 NodeSpec::row()
1017 .size((b * 0.5).round(), 2.0)
1018 .radius(1.0)
1019 .bg(t.on_accent),
1020 );
1021 } else {
1022 // Drawn, not a glyph: the same mark at every size
1023 // and in every font.
1024 ui.polyline(
1025 &[
1026 Vec2::new(b * 0.26, b * 0.52),
1027 Vec2::new(b * 0.43, b * 0.69),
1028 Vec2::new(b * 0.75, b * 0.33),
1029 ],
1030 crate::line::Stroke::new((b / 8.0).max(1.5), t.on_accent),
1031 NodeSpec::default(),
1032 );
1033 }
1034 });
1035 }
1036 Toggle::Switch => {
1037 let track = NodeSpec::row()
1038 .size((b * 1.75).round(), b)
1039 .pad(2.0)
1040 .radius(b / 2.0)
1041 .bg(if on { t.accent } else { t.border_strong })
1042 .main_align(if on { Align::End } else { Align::Start })
1043 .cross_align(Align::Center)
1044 .transition(120.0);
1045 ui.with_keyed("track", track, |ui| {
1046 let k = b - 4.0;
1047 ui.leaf_keyed(
1048 "knob",
1049 NodeSpec::row()
1050 .size(k, k)
1051 .radius(k / 2.0)
1052 .bg(t.on_accent)
1053 .transition(120.0)
1054 .slide(),
1055 );
1056 });
1057 }
1058 }
1059 if !text.is_empty() {
1060 ui.text(text, TextStyle::new(m.control_text).color(t.fg));
1061 }
1062 if let Some(hint) = hint
1063 && ui.is_hovered(node)
1064 {
1065 tooltip(ui, hint);
1066 }
1067 })
1068}
1069
1070/// The stock radio group's spec: a column of radios. What
1071/// [`radio_group_with`] is handed by [`radio_group`].
1072pub fn radio_group_spec(m: &Metrics) -> NodeSpec {
1073 NodeSpec::column().gap((control_box(m) / 2.0).round())
1074}
1075
1076/// A radio group named `label`: one Tab stop whose arrows, Home and End
1077/// move the choice among the radios `f` declares and press the one they
1078/// land on, so a group of radios whose
1079/// payloads each set the choice answers the keyboard with no more code.
1080/// The role and the name are the group's whatever `spec` said; a `row`
1081/// spec lays the radios out across, and its arrows run across with it. A
1082/// spec with no gap takes [`radio_group_spec`]'s, so a binding that built
1083/// the spec from its rows — where `dir="row"` starts one from nothing —
1084/// gets the stock spacing without restating it.
1085pub fn radio_group_with(
1086 ui: &mut Ui<'_>,
1087 label: &str,
1088 spec: NodeSpec,
1089 f: impl FnOnce(&mut Ui<'_>),
1090) -> Key {
1091 let spec = radio_group_open_spec(&ui.metrics(), label, spec);
1092 ui.with_keyed(label, spec, f)
1093}
1094
1095/// The spec a radio group named `label` opens with: `spec` with the
1096/// group's role and name, and the stock gap where it has none. What
1097/// [`radio_group_with`] opens, and what C's `kui_radio_group_open` does,
1098/// whose radios are declared between it and `kui_close`.
1099pub fn radio_group_open_spec(m: &Metrics, label: &str, spec: NodeSpec) -> NodeSpec {
1100 let mut spec = spec.role(Role::RadioGroup).label(label);
1101 if spec.layout.gap == 0.0 {
1102 spec.layout.gap = radio_group_spec(m).layout.gap;
1103 }
1104 spec
1105}
1106
1107/// A radio group over named options: `current` is the one in force, and a
1108/// choice posts `payload(i)`. Each radio is keyed by its index, so two
1109/// options with one label are two radios.
1110pub fn radio_group(
1111 ui: &mut Ui<'_>,
1112 label: &str,
1113 options: &[&str],
1114 current: Option<usize>,
1115 payload: impl Fn(usize) -> Value,
1116) -> Key {
1117 let m = ui.metrics();
1118 radio_group_with(ui, label, radio_group_spec(&m), |ui| {
1119 for (i, option) in options.iter().enumerate() {
1120 let key = format!("{i}");
1121 toggle_with(
1122 ui,
1123 Toggle::Radio,
1124 &key,
1125 option,
1126 toggle_spec(&m)
1127 .checked(current == Some(i))
1128 .on_click(payload(i)),
1129 None,
1130 );
1131 }
1132 })
1133}
1134
1135/// The stock slider's spec: a row as wide as a menu and as tall as its
1136/// thumb, padded by half the thumb on either side so the thumb's centre
1137/// is under the pointer at both ends — the content box is the track the
1138/// core reads a press along. A caller sizing its
1139/// own slider changes the width and keeps the padding.
1140pub fn slider_spec(m: &Metrics) -> NodeSpec {
1141 let b = control_box(m);
1142 NodeSpec::row()
1143 .size(m.menu_width, b)
1144 .pad_xy(b / 2.0, 0.0)
1145 .cross_align(Align::Center)
1146}
1147
1148/// A slider named `label` over `min..=max`, at `value`, moving by `step`.
1149/// Its changes arrive as `{kind: "change", value, phase, tag}` with `tag`
1150/// — from the pointer, the arrows, the Page keys, Home / End and
1151/// assistive technology alike — and the view stores `value` and draws the
1152/// slider again at it.
1153pub fn slider(
1154 ui: &mut Ui<'_>,
1155 label: &str,
1156 value: f32,
1157 min: f32,
1158 max: f32,
1159 step: f32,
1160 tag: impl Into<Value>,
1161) -> Key {
1162 let m = ui.metrics();
1163 slider_with(
1164 ui,
1165 label,
1166 slider_spec(&m)
1167 .value_now(value)
1168 .value_min(min)
1169 .value_max(max)
1170 .value_step(step)
1171 .on_change(tag.into()),
1172 None,
1173 )
1174}
1175
1176/// A slider with its spec in the caller's hands: [`slider_spec`] plus the
1177/// value rows (`value_now`, `value_min`, `value_max`, `value_step`,
1178/// `value_text`), `on_change`, `description`, `disabled`, a width, and
1179/// `hint`, the tooltip drawn while it is hovered. Keyed by `label`, which
1180/// is its accessible name unless the spec carries a `label` of its own.
1181/// The role is the slider's whatever the spec said. What `<slider>` and
1182/// its Lua and C doors lower to.
1183pub fn slider_with(ui: &mut Ui<'_>, label: &str, spec: NodeSpec, hint: Option<&str>) -> Key {
1184 let t = ui.theme();
1185 let m = ui.metrics();
1186 let node = ui.child_key(label);
1187 let ax = spec.access();
1188 let fraction = crate::slider::SliderRange::of(ax).map_or(0.0, |r| {
1189 let now = ax.value_now.map_or(r.min, crate::slider::exact);
1190 ((now - r.min) / (r.max - r.min)).clamp(0.0, 1.0) as f32
1191 });
1192 let named = ax.label.is_some();
1193 let disabled = spec.disabled;
1194 let mut spec = spec.role(Role::Slider);
1195 own_hint(&mut spec, hint);
1196 if !named {
1197 spec = spec.label(label);
1198 }
1199 if disabled {
1200 let o = spec.style.opacity * t.disabled_opacity;
1201 spec = spec.opacity(o);
1202 } else if spec.cursor.is_none() {
1203 spec = spec.cursor(CursorShape::Pointer);
1204 }
1205 let b = control_box(&m);
1206 ui.with_keyed(label, spec, |ui| {
1207 let track = NodeSpec::row()
1208 .grow_width()
1209 .height(4.0)
1210 .radius(2.0)
1211 .bg(t.border_strong);
1212 ui.with(track, |ui| {
1213 let fill = NodeSpec::row()
1214 .width(Sizing::Percent(fraction))
1215 .grow_height()
1216 .radius(2.0)
1217 .bg(t.accent);
1218 ui.with(fill, |ui| {
1219 // Hung off the fill's end, so it sits where the value is
1220 // with no arithmetic of the view's.
1221 ui.leaf(
1222 NodeSpec::row()
1223 .size(b, b)
1224 .radius(b / 2.0)
1225 .bg(t.on_accent)
1226 .border(1.0, t.border_strong)
1227 .float(
1228 FloatConfig::parent()
1229 .at(Align::End, Align::Center)
1230 .self_at(Align::Center, Align::Center),
1231 ),
1232 );
1233 });
1234 });
1235 if let Some(hint) = hint
1236 && ui.is_hovered(node)
1237 {
1238 tooltip(ui, hint);
1239 }
1240 })
1241}
1242
1243// -- Splitter ---------------------------------------------------------------
1244
1245/// A divider between two panes that the pointer drags:
1246/// `thickness` px across, growing along the rest of its parent, in the
1247/// theme's border colour and its accent while hovered or held, with the
1248/// resize arrows, and `tag` as its `on_drag`. `dir` is the parent's: in a
1249/// `Dir::Row` the panes sit side by side and the bar stands between them;
1250/// in a `Dir::Column` it lies across. A press on it leaves the keyboard
1251/// where it was (`keep_focus`), as a divider beside an editor should.
1252///
1253/// The split is the app's: `ev.drag()` on the tag's event, and
1254/// `Drag::ratio()` is the pointer's place across the parent — `.x` for a
1255/// row's split, `.y` for a column's — which is the new fraction as it is.
1256/// Returns the bar's key.
1257pub fn splitter(
1258 ui: &mut Ui<'_>,
1259 label: &str,
1260 dir: crate::spec::Dir,
1261 thickness: f32,
1262 tag: impl Into<Value>,
1263) -> Key {
1264 let t = ui.theme();
1265 let bar = match dir {
1266 crate::spec::Dir::Row => NodeSpec::column()
1267 .size(thickness, Sizing::GROW)
1268 .cursor(CursorShape::EwResize),
1269 crate::spec::Dir::Column => NodeSpec::column()
1270 .size(Sizing::GROW, thickness)
1271 .cursor(CursorShape::NsResize),
1272 };
1273 ui.leaf_keyed(
1274 label,
1275 bar.bg(t.border)
1276 .hover_bg(t.accent)
1277 .pressed_bg(t.accent)
1278 .on_drag(tag)
1279 .keep_focus(),
1280 )
1281}
1282
1283// -- Context menus ----------------------------------------------------------
1284// The menu every app was writing for itself. It is
1285// exported rather than hidden inside the core's automatic path, and the
1286// automatic path calls exactly this — so an app that answers its own
1287// `onContextMenu` to add two items of its own gets the layout, the
1288// keyboard, the dismissal and the access rows without rewriting them, and
1289// the corpus tests one menu rather than two.
1290
1291/// Menu chrome, in one place so a native renderer's absence still looks
1292/// deliberate rather than improvised.
1293pub const MENU_WIDTH: f32 = Metrics::comfortable().menu_width;
1294pub const MENU_TEXT: f32 = Metrics::comfortable().chrome_text;
1295/// The reserved label the stock menu is keyed under. A menu the core
1296/// opened is found by key, not by guessing at payloads, so an app is free
1297/// to post whatever it likes from its own items.
1298pub const MENU_KEY: &str = "kui.menu";
1299
1300/// Draws a context menu at `at` (logical viewport px) and returns the key
1301/// of its root. A float anchored to the viewport rather than to a parent,
1302/// because a context menu belongs at the pointer and not under whatever
1303/// node happens to enclose it; `fit` is what keeps it in the window, which
1304/// for a menu near the bottom edge means flipping above the point.
1305///
1306/// It declares `modal`, so a press outside it or Escape emits a `dismiss`
1307/// event on it rather than through a dismissal rule of its own; the caller
1308/// closes it when that dismissal arrives. The rows are `menuItem`s under a
1309/// `menu`, which is what makes the arrow keys work and what a screen reader
1310/// reads.
1311///
1312/// Each chosen row posts the item's `id`, or its label when it declares
1313/// none. A `Separator` posts nothing and takes no focus.
1314pub fn context_menu(ui: &mut Ui<'_>, at: Vec2, items: &[MenuItem]) -> Key {
1315 let t = ui.theme();
1316 let m = ui.metrics();
1317 // The menu's nodes are the core's, not the host's: opened under their
1318 // own origin, so the core takes their events back by it.
1319 let saved = ui.origin();
1320 ui.set_origin(OriginId::MENU);
1321 // The menu floats against the window, not the host area (a menu the
1322 // platform showed would not stop at a dock's edge either, and the
1323 // devtools' own select opens one inside the dock): the host's point
1324 // becomes the window's.
1325 let at = at.plus(ui.core().dt_shift());
1326 let root = menu_panel(
1327 ui,
1328 MENU_KEY,
1329 menu_panel_spec(&t, &m)
1330 .float(
1331 FloatConfig::viewport()
1332 // Top-left of the menu at the top-left of the
1333 // viewport, then offset to the point: the placement
1334 // every context menu has, with `fit` flipping it up
1335 // or clamping it in when the point is near an edge.
1336 .inside(Align::Start, Align::Start)
1337 .offset(at.x, at.y)
1338 .fit(),
1339 )
1340 .modal(Value::str(MENU_KEY))
1341 .label("Menu"),
1342 items,
1343 );
1344 ui.set_origin(saved);
1345 root
1346}
1347
1348/// The panel every menu is: a fixed-width column of rows, in the palette
1349/// the stock menu paints. What the caller adds is where it goes and what
1350/// scope it belongs to — a context menu floats at the pointer and declares
1351/// its own `modal`; the menu bar's drops out of its title and lives inside
1352/// the bar's. Takes the palette and the metrics rather than reading them,
1353/// because a caller that has a `Ui` in one hand cannot lend it to this and
1354/// to `menu_panel` in the same expression; `let t = ui.theme();` first is
1355/// the idiom.
1356pub fn menu_panel_spec(t: &Theme, m: &Metrics) -> NodeSpec {
1357 NodeSpec::column()
1358 .role(Role::Menu)
1359 // As wide as its widest row and never narrower than the metric: a
1360 // long accelerator beside a long label widens the menu rather than
1361 // wrapping either onto a second line (backlog F127). Rows grow to
1362 // the panel, so their right edges line up.
1363 .width(Sizing::Fit)
1364 .min_width(m.menu_width)
1365 .pad(MENU_PANEL_PAD)
1366 .gap(1.0)
1367 .bg(t.raised)
1368 .border(1.0, t.border_strong)
1369 .radius(m.radius)
1370}
1371
1372/// Builds the rows of one menu into `spec`, keyed under `label`, and
1373/// reports the keys they took. The one place a menu's rows are drawn:
1374/// both menus kui has are this function with a different container.
1375///
1376/// A row with a submenu ([`MenuItem::submenu`]) is drawn with a chevron.
1377/// In the core's own menus — the context menu and the drawn bar's — its
1378/// menu opens beside it, as another of these panels, when the pointer
1379/// rests on it, it is clicked, or the keyboard opens it (Enter, the Right
1380/// arrow); an app drawing this panel itself gets the chevron and opens
1381/// nothing, since the open submenus are the core's state.
1382pub fn menu_panel(ui: &mut Ui<'_>, label: &str, spec: NodeSpec, items: &[MenuItem]) -> Key {
1383 menu_level(ui, label, label, spec, items, &[])
1384}
1385
1386/// One level of a menu: `items` built into `spec` under `label`, at `path`
1387/// — empty for the menu itself, the rows opened on the way for a submenu.
1388/// `root` is the outermost panel's label, which names the hover groups.
1389fn menu_level(
1390 ui: &mut Ui<'_>,
1391 root: &str,
1392 label: &str,
1393 spec: NodeSpec,
1394 items: &[MenuItem],
1395 path: &[usize],
1396) -> Key {
1397 let t = ui.theme();
1398 let m = ui.metrics();
1399 // Never wider than the window, less a margin each side: a row wider
1400 // than that — a recent file's whole path — ellipsizes its label
1401 // instead of running the panel, and its accelerator, off the edge
1402 // (backlog RG150). A ceiling the caller declared that is narrower
1403 // stands.
1404 let ceiling = (ui.viewport().w - 2.0 * MENU_EDGE).max(m.menu_width);
1405 let spec = if spec.layout.max_w >= 0.0 && spec.layout.max_w > ceiling {
1406 spec.max_width(ceiling)
1407 } else {
1408 spec
1409 };
1410 // What a row's label may take of it: the panel's inside, less the
1411 // row's padding, the gutter and the accelerator or chevron with their
1412 // gaps. A row is sized from its content (the panel is `Fit` over its
1413 // rows), so the label is what is bounded, and it ellipsizes there. A
1414 // ceiling the caller declared as a size expression is read against
1415 // the window where that is the panel's room — a float anchored to the
1416 // viewport, as the core's own menus are — and left to the window's
1417 // ceiling where layout will read it against a parent this build has
1418 // not placed yet (backlog RG154).
1419 let in_viewport = spec
1420 .layout
1421 .float
1422 .is_some_and(|f| f.anchor == crate::spec::FloatAnchor::Viewport);
1423 let cap = if spec.layout.max_w >= 0.0 {
1424 spec.layout.max_w
1425 } else if let Some(calc) = crate::spec::max_calc(spec.layout.max_w)
1426 && in_viewport
1427 {
1428 calc.resolve(ui.viewport().w).min(ceiling)
1429 } else {
1430 ceiling
1431 };
1432 let inside = cap - 2.0 * (MENU_PANEL_PAD + 1.0) - 2.0 * m.menu_pad_x;
1433 // A wash rather than a fill, so a row's label stays readable on both
1434 // bases without the view guessing a frame ahead of the core — see
1435 // `Theme::accent_soft`.
1436 let accent = t.accent_soft;
1437 // A gutter for the checkmarks, and only where a row has one: a menu of
1438 // plain commands is not indented for a column nothing uses, and one
1439 // with a setting in it keeps every label on the same left edge whether
1440 // the setting is on or off.
1441 let gutter = items.iter().any(|i| i.checked);
1442 // Which of the core's menus this is, by the origin its nodes open
1443 // under: only those have submenu state to open and close.
1444 let surface = crate::runtime::MenuSurface::of(ui.origin());
1445 let group = |i: usize| format!("{root}/{path:?}/{i}");
1446 // Where the pointer rests opens or closes a submenu, resolved before
1447 // anything is built — the frame that notices the hover draws what it
1448 // opened, as the bar's titles do. The outermost level brackets the
1449 // build, so a build with the pointer on no row at all is known.
1450 if let Some(s) = surface
1451 && path.is_empty()
1452 {
1453 ui.core().submenu_pass(s, true);
1454 }
1455 if let Some(s) = surface {
1456 for (i, item) in items.iter().enumerate() {
1457 if item.selectable() && ui.is_group_hovered(NodeSpec::hover_group_id(&group(i))) {
1458 let row: Vec<usize> = path.iter().copied().chain([i]).collect();
1459 ui.core().submenu_hovered(s, &row, item.has_submenu());
1460 }
1461 }
1462 }
1463 let open_here = surface.and_then(|s| ui.core().submenu_open_at(s, path));
1464 let mut first_key = None;
1465 let root_key = ui.with_keyed(label, spec, |ui| {
1466 let mut first = path.is_empty();
1467 for (i, item) in items.iter().enumerate() {
1468 // Hide and its two neighbours are a Mac's application's to
1469 // perform: a menu kui draws does not offer them (backlog F152).
1470 if !item.role.drawn() {
1471 continue;
1472 }
1473 if item.role == MenuRole::Separator {
1474 ui.leaf_indexed(
1475 i as u64,
1476 NodeSpec::row()
1477 .grow_width()
1478 .height(1.0)
1479 .bg(t.border)
1480 // Not a row anything reads out: a divider is
1481 // paint, and a screen reader hearing "separator"
1482 // between every pair of items is noise.
1483 .role(Role::None),
1484 );
1485 continue;
1486 }
1487 // The row posts which item it is; the core takes the event back
1488 // by origin, performs the item — or opens its submenu — and
1489 // what the app hears is the item's own `id` on the node the
1490 // menu was about.
1491 let payload = menu_row_tag(i, path);
1492 let opens = item.has_submenu();
1493 let is_open = opens && open_here == Some(i);
1494 let mut spec = NodeSpec::row()
1495 .role(Role::MenuItem)
1496 .label(item.text())
1497 .grow_width()
1498 // Its content as a floor, which is what a fit panel is
1499 // sized from: a grow child alone contributes nothing.
1500 .min_width(crate::spec::Bound::Fit)
1501 .pad_xy(m.menu_pad_x, m.menu_pad_y)
1502 .gap(MENU_ROW_GAP)
1503 .radius(m.radius_inner)
1504 .main_align(Align::Start)
1505 .cross_align(Align::Center);
1506 if item.checked {
1507 // The gutter's checkmark is paint; this is the same fact for
1508 // a screen reader, which reads a row that carries one as
1509 // checked rather than as "✓ Wrap".
1510 spec = spec.checked(true);
1511 }
1512 if item.enabled {
1513 spec = spec.on_click(payload).hover_bg(accent).focus_bg(accent);
1514 if surface.is_some() {
1515 spec = spec.hover_group(&group(i));
1516 }
1517 // The first row that can take focus is where the modal opens:
1518 // a menu whose keyboard starts nowhere makes the arrow keys
1519 // feel like they missed. A submenu is no modal of its own;
1520 // the keyboard that opens one puts focus in it.
1521 if first {
1522 spec = spec.initial_focus();
1523 first = false;
1524 }
1525 } else {
1526 spec = spec.disabled(true).opacity(t.disabled_opacity);
1527 }
1528 if opens {
1529 // A reader hears it as a row that opens something, and
1530 // whether it is open; the open one keeps the wash while the
1531 // pointer is in its submenu, so the way back is visible.
1532 spec = spec.expanded(is_open);
1533 if is_open {
1534 spec = spec.bg(accent);
1535 }
1536 }
1537 let tail = if opens {
1538 Some(std::borrow::Cow::Borrowed(MENU_CHEVRON))
1539 } else {
1540 item.accel_label()
1541 };
1542 let row = |ui: &mut Ui<'_>| {
1543 let tail_style = TextStyle::new(m.chrome_text).color(t.muted).nowrap();
1544 let mut label_max = inside;
1545 if gutter {
1546 label_max -= MENU_CHECK_W + MENU_ROW_GAP;
1547 }
1548 // The accelerator takes what the label's floor leaves it,
1549 // and ellipsizes past that: in a window narrower than the
1550 // accelerator and its gaps, the label used to shrink to
1551 // nothing and the accelerator ran past the panel anyway
1552 // (backlog RG154).
1553 let tail_max =
1554 (label_max - 2.0 * MENU_ROW_GAP - MENU_ACCEL_GAP - MENU_LABEL_MIN).max(0.0);
1555 if let Some(tail) = &tail {
1556 let w = ui.measure_text(tail, &tail_style, None).width.min(tail_max);
1557 label_max -= 2.0 * MENU_ROW_GAP + MENU_ACCEL_GAP + w;
1558 }
1559 if gutter {
1560 ui.with(NodeSpec::row().width(MENU_CHECK_W), |ui| {
1561 if item.checked {
1562 ui.text("\u{2713}", TextStyle::new(m.chrome_text).color(t.fg));
1563 }
1564 });
1565 }
1566 // One line each, whatever the panel's width: the panel is
1567 // sized to fit them, and a row that wrapped would be read as
1568 // two.
1569 ui.text_in(
1570 NodeSpec::row().max_width(label_max.max(0.0)),
1571 item.text(),
1572 TextStyle::new(m.chrome_text)
1573 .color(t.fg)
1574 .nowrap()
1575 .ellipsis(),
1576 );
1577 // Pushed to the right edge by a grow spacer, so the label
1578 // stays where the eye expects it whatever follows it; at
1579 // least `MENU_ACCEL_GAP` wide, so the widest label and the
1580 // widest accelerator never touch. A submenu's row has its
1581 // chevron there and no accelerator: it binds nothing.
1582 if let Some(tail) = &tail {
1583 ui.leaf(NodeSpec::row().grow_width().min_width(MENU_ACCEL_GAP));
1584 ui.text_in(
1585 NodeSpec::row().max_width(tail_max),
1586 tail,
1587 tail_style.ellipsis(),
1588 );
1589 }
1590 };
1591 let key = if opens {
1592 // A wrapper the submenu drops out of, so the panel is the
1593 // row's *sibling* — the menu bar's reason: a `menuItem` is
1594 // named from its content, and a menu inside one would be
1595 // read as part of its name — and floats against the row's
1596 // own box.
1597 let mut key = Key::ROOT;
1598 ui.with_indexed(
1599 i as u64,
1600 NodeSpec::row()
1601 .grow_width()
1602 .min_width(crate::spec::Bound::Fit),
1603 |ui| {
1604 key = ui.with_keyed(MENU_ROW_KEY, spec, row);
1605 if is_open && item.enabled {
1606 let sub: Vec<usize> = path.iter().copied().chain([i]).collect();
1607 menu_level(
1608 ui,
1609 root,
1610 MENU_SUB_KEY,
1611 menu_panel_spec(&t, &m)
1612 .label(item.text())
1613 // A region of its own, so a press on its
1614 // padding or a dead row is inside the
1615 // menu — as the outer panel's `modal`
1616 // makes it there — and not the press
1617 // outside that dismisses it.
1618 .hoverable()
1619 .float(
1620 // Beside the row, its first row level
1621 // with this one (the panel's padding
1622 // above it), flipped to the other side
1623 // at the window's edge.
1624 FloatConfig::parent()
1625 .at(Align::End, Align::Start)
1626 .self_at(Align::Start, Align::Start)
1627 .offset(MENU_PANEL_PAD, -MENU_PANEL_PAD)
1628 .fit(),
1629 ),
1630 &item.submenu,
1631 &sub,
1632 );
1633 }
1634 },
1635 );
1636 key
1637 } else {
1638 ui.with_indexed(i as u64, spec, row)
1639 };
1640 if item.enabled && first_key.is_none() {
1641 first_key = Some(key);
1642 }
1643 }
1644 });
1645 // The keyboard opened this submenu (Enter, the Right arrow): the
1646 // first row it can take is where it lands, now that it exists.
1647 if let (Some(s), Some(key)) = (surface, first_key)
1648 && !path.is_empty()
1649 {
1650 ui.core().submenu_drawn(s, path, key);
1651 }
1652 if let Some(s) = surface
1653 && path.is_empty()
1654 {
1655 ui.core().submenu_pass(s, false);
1656 }
1657 root_key
1658}
1659
1660/// The padding inside a menu's panel, logical px: what a submenu is offset
1661/// by so its first row sits level with the row that opened it.
1662const MENU_PANEL_PAD: f32 = 4.0;
1663
1664/// How far a menu at its widest stays from each side of the window.
1665pub const MENU_EDGE: f32 = 8.0;
1666
1667/// The least a row's label keeps when its accelerator would take the rest:
1668/// a few glyphs and the ellipsis at the chrome size. Past this the
1669/// accelerator is what ellipsizes.
1670pub const MENU_LABEL_MIN: f32 = 48.0;
1671
1672/// Between a row's checkmark, label, spacer and accelerator.
1673const MENU_ROW_GAP: f32 = 8.0;
1674
1675/// The chevron a submenu's row draws where an accelerator would be.
1676pub const MENU_CHEVRON: &str = "\u{203a}";
1677/// The label a submenu's row is keyed under, inside its wrapper.
1678const MENU_ROW_KEY: &str = "row";
1679/// The label a submenu's panel is keyed under, beside its row.
1680const MENU_SUB_KEY: &str = "sub";
1681
1682/// What a menu row's click carries: its index in its menu's items, and —
1683/// for a row of a submenu — the rows opened on the way to it, for the core
1684/// to read back (`Core::take_surface_events`). The title of a menu-bar
1685/// menu carries its index the same way, under `title`. A top-level row
1686/// carries `row` alone, as it always did.
1687fn menu_row_tag(i: usize, path: &[usize]) -> Value {
1688 let row = ("row", Value::Int(i as i64));
1689 if path.is_empty() {
1690 Value::map([row])
1691 } else {
1692 Value::map([
1693 row,
1694 (
1695 "path",
1696 Value::List(path.iter().map(|&p| Value::Int(p as i64)).collect()),
1697 ),
1698 ])
1699 }
1700}
1701
1702fn menu_title_tag(i: usize) -> Value {
1703 Value::map([("title", Value::Int(i as i64))])
1704}
1705
1706/// The reserved label the drawn menu bar is keyed under, the way
1707/// [`MENU_KEY`] is the open menu's.
1708pub const MENU_BAR_KEY: &str = "kui.menubar";
1709/// The label its dropped menu is keyed under, beside the open title.
1710const MENU_BAR_PANEL_KEY: &str = "kui.menubar.menu";
1711/// The label each title is keyed under, inside its own wrapper.
1712const MENU_BAR_TITLE_KEY: &str = "kui.menubar.title";
1713
1714/// The hover group a title and its menu share, so the widget can ask
1715/// whether the pointer is on the `i`th title without knowing its key.
1716fn group_name(i: usize) -> String {
1717 format!("{MENU_BAR_KEY}.{i}")
1718}
1719/// The bar's height, logical px — a little under a titlebar's, which is
1720/// what every platform that draws one in the window does.
1721pub const MENU_BAR_H: f32 = Metrics::comfortable().menu_bar_h;
1722
1723/// The application menu: `bar` is what the app's menu *is*, and calling
1724/// this is where its titles go when they have to be drawn in the window.
1725///
1726/// One call and not two, because the declaration and the placement are one
1727/// decision. **It draws nothing where the platform owns the bar** — macOS,
1728/// where the driver hands this same declaration to `NSApp` — so the call
1729/// still says what the menu is and the strip simply is not there; that is
1730/// the contract [`window_buttons`] has under native decorations, and it is
1731/// what makes one view portable. An empty `bar` takes the menu away.
1732///
1733/// Declared every frame, and diffed: an unchanged menu costs a comparison
1734/// and rebuilds nothing.
1735///
1736/// Everything below a title is the stock menu: the same rows, roles,
1737/// accelerators and access tree the context menu draws, through the same
1738/// [`menu_panel`]. What is the bar's own is the scope — while a menu is
1739/// open the *bar* is the frame's modal, not the dropdown, so hovering
1740/// across the titles moves the open menu the way a menu bar does, a press
1741/// on the open title closes it, and Escape or a press in the app below
1742/// dismisses it as any modal is dismissed.
1743///
1744/// Typical use, as the first child of a full-height root, under the
1745/// titlebar if there is one:
1746/// `widgets::menu_bar(ui, self.menu());`
1747pub fn menu_bar(ui: &mut Ui<'_>, bar: MenuBar) {
1748 // Declaring it is this call's first half, and drawing it the second:
1749 // where the platform owns the bar there is no second half, and the
1750 // frame has still said what the app's menu is.
1751 ui.core().declare_menu_bar(bar);
1752 if ui.core().native_menu_bar() {
1753 return;
1754 }
1755 let Some(bar) = ui.core().menu_bar().cloned() else {
1756 return;
1757 };
1758 if bar.menus.is_empty() {
1759 return;
1760 }
1761 let t = ui.theme();
1762 let m = ui.metrics();
1763 let accent = t.accent_soft;
1764 let mut open = ui.core().menu_bar_open();
1765 // The bar's nodes are the core's, opened under their own origin (see
1766 // `OriginId::MENU_BAR`), so the core takes their events back by it.
1767 let saved = ui.origin();
1768 ui.set_origin(OriginId::MENU_BAR);
1769 let mut spec = NodeSpec::row()
1770 .grow_width()
1771 .height(m.menu_bar_h)
1772 .cross_align(Align::Center)
1773 .pad_xy(4.0, 0.0)
1774 .gap(2.0)
1775 .bg(t.bg)
1776 .role(Role::Menu)
1777 .label("Menu bar");
1778 if open.is_some() {
1779 // The bar and not the dropdown is the modal while a menu is open:
1780 // the titles have to stay live for the hover to walk them, and the
1781 // app below has to be as inert as it is under any other menu.
1782 spec = spec.modal(Value::str(MENU_BAR_KEY));
1783 }
1784 let root = ui.with_keyed(MENU_BAR_KEY, spec, |ui| {
1785 // Hovering another title while a menu is open moves the open menu
1786 // to it, which is what a menu bar does everywhere. Resolved before
1787 // anything is built, so the frame that notices the hover is the
1788 // frame that draws the new menu and not the one after it — and
1789 // asked by *group* rather than by key, since a title's key is
1790 // inside a wrapper this loop has not opened yet.
1791 if open.is_some() {
1792 for (i, menu) in bar.menus.iter().enumerate() {
1793 let hovered = ui.is_group_hovered(NodeSpec::hover_group_id(&group_name(i)));
1794 if open != Some(i) && menu.enabled && !menu.items.is_empty() && hovered {
1795 open = Some(i);
1796 ui.core().set_menu_bar_open(open);
1797 }
1798 }
1799 }
1800 for (i, menu) in bar.menus.iter().enumerate() {
1801 let live = menu.enabled && !menu.items.is_empty();
1802 let is_open = open == Some(i);
1803 // A wrapper the menu drops out of, so the panel is a *sibling*
1804 // of the title and not a child of it: a `menuItem` is a
1805 // name-from-content role, and a menu nested inside one would be
1806 // read as part of its name and never reached on its own.
1807 ui.with_indexed(i as u64, NodeSpec::row(), |ui| {
1808 let mut spec = NodeSpec::row()
1809 .role(Role::MenuItem)
1810 .label(menu.label.as_str())
1811 // Two px shorter than a row's, so the bar's height and
1812 // not the title's padding decides the strip.
1813 .pad_xy(m.menu_pad_x, (m.menu_pad_y - 2.0).max(0.0))
1814 .radius(m.radius_inner)
1815 .cross_align(Align::Center);
1816 if live {
1817 // Which title this is: the core takes the event back
1818 // by origin and opens or closes the `i`th menu.
1819 spec = spec
1820 .on_click(menu_title_tag(i))
1821 .hover_group(&group_name(i))
1822 .hover_bg(accent)
1823 .focus_bg(accent);
1824 if is_open {
1825 spec = spec.bg(accent);
1826 }
1827 } else {
1828 spec = spec.disabled(true).opacity(t.disabled_opacity);
1829 }
1830 ui.text_in_keyed(
1831 MENU_BAR_TITLE_KEY,
1832 spec,
1833 menu.label.as_str(),
1834 TextStyle::new(m.chrome_text).color(t.fg),
1835 );
1836 if is_open {
1837 // Out of the title's bottom-left corner, and `fit` to
1838 // slide back in at the right-hand end of the bar.
1839 menu_panel(
1840 ui,
1841 MENU_BAR_PANEL_KEY,
1842 menu_panel_spec(&t, &m).label(menu.label.as_str()).float(
1843 FloatConfig::parent()
1844 .at(Align::Start, Align::End)
1845 .self_at(Align::Start, Align::Start)
1846 .offset(0.0, 2.0)
1847 .fit(),
1848 ),
1849 &menu.items,
1850 );
1851 }
1852 });
1853 }
1854 });
1855 ui.set_origin(saved);
1856 ui.core().set_menu_bar_root(root);
1857}
1858
1859/// The checkmark gutter's width, logical px.
1860const MENU_CHECK_W: f32 = 14.0;
1861
1862/// The least room between a row's label and its accelerator, logical px,
1863/// beside the row's own gap on either side: about what AppKit leaves
1864/// before a key equivalent.
1865pub const MENU_ACCEL_GAP: f32 = 16.0;
1866
1867// -- Virtual lists ----------------------------------------------------------
1868// The core culls glyphs by viewport but builds every child a view declares,
1869// so a ten-thousand-row log costs ten thousand rows of build and layout on
1870// every frame — most of a 120 Hz budget spent on rows nobody can see. A view
1871// that knows the container's height and offset can declare a screenful and
1872// two spacers instead. `Core::scroll_geometry` is that knowledge; this is
1873// the arithmetic, for the case where every row is the same height.
1874
1875/// The half-open range of rows a container of `rows` rows, each `row_h`
1876/// logical px tall, has any reason to build — those crossing the visible
1877/// band, plus `overscan` on each side — given the geometry of the frame
1878/// before. Pure arithmetic, exposed for views that build their own
1879/// container instead of using [`uniform_list`].
1880///
1881/// `vh` is the container's height, and `pad_t` the padding above the first
1882/// row. `None` geometry means no layout has resolved the container yet:
1883/// the caller decides what the first frame builds.
1884pub fn visible_rows(
1885 offset_y: f32,
1886 vh: f32,
1887 pad_t: f32,
1888 row_h: f32,
1889 rows: usize,
1890 overscan: usize,
1891) -> std::ops::Range<usize> {
1892 if rows == 0 || row_h <= 0.0 {
1893 return 0..0;
1894 }
1895 // Flow coordinates: row i spans [i*row_h, (i+1)*row_h), and layout puts
1896 // the flow's origin at pad_t - offset_y inside the container's box, so
1897 // the visible window is [offset_y - pad_t, that + vh).
1898 let top = offset_y - pad_t;
1899 let first = (top / row_h).floor().max(0.0) as usize;
1900 let last = ((top + vh.max(0.0)) / row_h).ceil().max(0.0) as usize;
1901 let first = first.saturating_sub(overscan).min(rows);
1902 let last = last.saturating_add(overscan).min(rows);
1903 first..last.max(first)
1904}
1905
1906/// A vertically scrolling column of `rows` uniform rows that builds only the
1907/// visible ones. `row(ui, i)` declares row `i`; it must come out exactly
1908/// `row_h` logical px tall, since that is the arithmetic placing every row
1909/// above and below it.
1910///
1911/// The container is `spec` forced to a scrolling column with no gap — put
1912/// the spacing inside `row_h` (a row that pads itself) rather than in a
1913/// `gap`, so one number describes the stride. Rows are opened with
1914/// [`Ui::open_indexed`] at their *data* index, so a row keeps its key, and
1915/// with it its hover, focus, edit buffer and tweens, as the built range
1916/// slides over it. Above and below sit two empty spacers holding the space
1917/// of the rows not built, so the content height, the scrollbar and
1918/// `set_scroll` all behave as if the whole list were there.
1919///
1920/// The geometry it slices by is the previous frame's, so the first frame —
1921/// before any layout has resolved the container — slices by the viewport
1922/// height instead and asks for one more frame; a resize is one frame late
1923/// and covered by the two rows of overscan. Returns the container's key,
1924/// for `set_scroll` (`Vec2::new(0.0, i as f32 * row_h)` scrolls row `i` to
1925/// the top, which is how you reach a row that is not built — `reveal` of an
1926/// unbuilt row finds nothing).
1927pub fn uniform_list(
1928 ui: &mut Ui<'_>,
1929 label: &str,
1930 spec: NodeSpec,
1931 rows: usize,
1932 row_h: f32,
1933 row: impl FnMut(&mut Ui<'_>, usize),
1934) -> Key {
1935 uniform_list_with(ui, label, spec, rows, row_h, |_| NodeSpec::column(), row)
1936}
1937
1938/// [`uniform_list`] with each row's own node spelled by `row_spec(i)` —
1939/// the click, the zebra stripe, the hover background, the role a row
1940/// carries — where the plain form's rows are bare and the callback nests
1941/// a second node inside each to carry them. The height is
1942/// forced to `row_h`, the stride the arithmetic assumes, and a width the
1943/// spec leaves `fit` grows across the list.
1944pub fn uniform_list_with(
1945 ui: &mut Ui<'_>,
1946 label: &str,
1947 spec: NodeSpec,
1948 rows: usize,
1949 row_h: f32,
1950 mut row_spec: impl FnMut(usize) -> NodeSpec,
1951 mut row: impl FnMut(&mut Ui<'_>, usize),
1952) -> Key {
1953 const OVERSCAN: usize = 2;
1954
1955 let key = ui.child_key(label);
1956 let pad_t = spec.layout.padding.t;
1957 // Both numbers from the same frame: the geometry's offset is clamped to
1958 // that frame's travel, so a `set_scroll(key, huge)` between frames
1959 // slices the end of the list instead of a megabyte past it.
1960 let (offset_y, vh, first_frame) = match ui.scroll_geometry(key) {
1961 Some(g) => (g.offset.y, g.rect.h, false),
1962 // Nothing laid out yet: the container cannot be taller than the
1963 // window in the ordinary case, so a screenful is a safe over-build
1964 // for one frame.
1965 None => (ui.scroll_offset(key).y, ui.viewport().h, true),
1966 };
1967 let range = visible_rows(offset_y, vh, pad_t, row_h, rows, OVERSCAN);
1968
1969 ui.with_keyed(label, spec.scroll_y().gap(0.0), |ui| {
1970 // The whole list's size, built or not: what Select All inside a
1971 // `selectable` list spans.
1972 ui.row_count(rows as u64);
1973 // Keyed, not auto-keyed: an auto key is a sibling index, and the
1974 // rows already occupy that namespace at their data indices — an
1975 // auto-keyed spacer next to a built row 0 would be row 0's key.
1976 let lead = range.start as f32 * row_h;
1977 if lead > 0.0 {
1978 ui.leaf_keyed("lead", spacer_spec(lead));
1979 }
1980 for i in range.clone() {
1981 let mut spec = row_spec(i).height(row_h);
1982 if spec.layout.width == Sizing::Fit {
1983 spec = spec.grow_width();
1984 }
1985 ui.with_indexed(i as u64, spec, |ui| row(ui, i));
1986 }
1987 let tail = (rows - range.end) as f32 * row_h;
1988 if tail > 0.0 {
1989 ui.leaf_keyed("tail", spacer_spec(tail));
1990 }
1991 });
1992
1993 // Sliced by a screenful's guess, with no layout of its own yet: the
1994 // next frame slices by its geometry. kui's ask, not the app's, so a
1995 // trace names it for what it is.
1996 if first_frame {
1997 ui.owe_frame("list first frame");
1998 }
1999 key
2000}
2001
2002/// Scrolls the [`uniform_list`] labelled `label` so row `i` shows, when
2003/// it does not already: to the middle of the list, so a jump lands with
2004/// rows on both sides of it. Call it before the list is
2005/// declared, in the same parent — the frame that scrolls then slices its
2006/// rows by the offset it scrolls to, instead of a frame late. Returns
2007/// whether it scrolled. The first frame, before the list has laid out,
2008/// has no geometry and scrolls nothing; the row arithmetic assumes the
2009/// list's rows start at its content top and fill its box, as they do
2010/// without padding. A row past the list's content — an index past its
2011/// end — scrolls nothing and answers false, as does a `row_h` that is
2012/// not positive.
2013///
2014/// `Ui::reveal` cannot do this for a row that is not built, and a
2015/// virtual list builds only what shows.
2016pub fn reveal_row(ui: &mut Ui<'_>, label: &str, i: usize, row_h: f32) -> bool {
2017 let key = ui.child_key(label);
2018 let Some(g) = ui.scroll_geometry(key) else {
2019 return false;
2020 };
2021 let y = i as f32 * row_h;
2022 if row_h <= 0.0 || y + row_h > g.content.h + 0.5 {
2023 return false;
2024 }
2025 if g.offset.y <= y && y + row_h <= g.offset.y + g.rect.h {
2026 return false;
2027 }
2028 let to = (y + row_h / 2.0 - g.rect.h / 2.0).max(0.0);
2029 ui.set_scroll(key, Vec2::new(g.offset.x, to));
2030 true
2031}
2032
2033/// How many whole rows of `row_h` the [`uniform_list`] labelled `label`
2034/// shows as of the last layout — a PageDown's stride. 0 before it has
2035/// laid out, and for a `row_h` that is not positive.
2036pub fn rows_in_view(ui: &mut Ui<'_>, label: &str, row_h: f32) -> usize {
2037 let key = ui.child_key(label);
2038 if row_h <= 0.0 {
2039 return 0;
2040 }
2041 ui.scroll_geometry(key)
2042 .map_or(0, |g| (g.rect.h / row_h).floor().max(0.0) as usize)
2043}
2044
2045/// Each row's own node in the variable-height `list`: the wrapper the
2046/// callback builds inside, sized to the height the arithmetic assumes.
2047fn row_spec(h: f32) -> NodeSpec {
2048 NodeSpec::column().grow_width().height(h)
2049}
2050
2051fn spacer_spec(h: f32) -> NodeSpec {
2052 NodeSpec::column().grow_width().height(h)
2053}
2054
2055// -- Variable-height virtual lists ------------------------------------------
2056// `uniform_list` takes one stride and every row must come out that tall,
2057// which is the log viewer, the data table and the chat history whose rows are
2058// one line. A row that wraps, a card with an image, a message that is
2059// sometimes three lines: none of those have a stride, and the three things
2060// the uniform arithmetic does with `i * row_h` — the lead spacer, the search
2061// from an offset to the first visible row, and "scroll to row i" — have no
2062// closed form without one. Prefix sums are the closed form, and
2063// `RowHeights` is where they live.
2064//
2065// Heights come from the caller, measured only for the rows the frame needs:
2066// `measure_text` gives layout's own number for a text row (wrap, max_lines
2067// and the shaping cache included), so a row measured and then drawn shapes
2068// once. Everything not measured yet stands at an estimate, and the estimate
2069// is the mean of what has been measured — which means it *moves*, and moving
2070// it changes the height of every row above the window as well as below.
2071// That is what the anchor is for.
2072
2073/// The heights a [`list`] slices by: a measured number per row
2074/// where one is known, an estimate everywhere else, and the prefix sums over
2075/// both.
2076///
2077/// The app owns it and hands the same one back every frame — a widget
2078/// composed from primitives keeps no state of its own, which is what keeps
2079/// it reachable from a scripting frontend. Rebuild it (or [`Self::clear`])
2080/// when the rows themselves change.
2081#[derive(Clone, Debug)]
2082pub struct RowHeights {
2083 /// One per row; `f32::NAN` for a row nothing has measured yet.
2084 h: Vec<f32>,
2085 /// The prefix sums, split so that the estimate is applied at the query
2086 /// rather than baked in: `m[i]` is the measured height in rows `0..i`
2087 /// and `u[i]` how many of those rows have none. A moving mean then costs
2088 /// nothing to fold in — which matters, because every measurement moves
2089 /// it, and a mean baked into the sums would dirty all of them.
2090 m: Vec<f32>,
2091 u: Vec<u32>,
2092 /// How many entries of `m` / `u` are valid, counting from 0. Filled
2093 /// on demand and only as far as a query asks, so a list scrolled to row
2094 /// 30 never sums the 9,970 below it; a measurement at row `i` truncates
2095 /// this to `i + 1`, since nothing at or below `i` changed.
2096 clean: usize,
2097 /// What the caller guessed before anything was measured.
2098 seed: f32,
2099 /// Running mean of the measured rows — the estimate for the rest.
2100 sum: f32,
2101 n: usize,
2102 /// The content width the cached heights were measured at. A different
2103 /// one rewraps every row, so it drops them all.
2104 width: f32,
2105 /// Where the last search landed. Scrolling is local, so the next one
2106 /// gallops out from here instead of bisecting the whole list — which is
2107 /// what keeps the lazy `ensure` above from being filled past what is
2108 /// being looked at, and what a bisection from 0..len would defeat by
2109 /// probing the middle every time.
2110 last: usize,
2111}
2112
2113impl RowHeights {
2114 /// `rows` rows, none measured, each standing at `estimate` logical px
2115 /// until it is. The estimate only has to be the right order of
2116 /// magnitude: it decides how wrong the scrollbar is before the list has
2117 /// been scrolled through, and nothing else.
2118 pub fn new(rows: usize, estimate: f32) -> Self {
2119 RowHeights {
2120 h: vec![f32::NAN; rows],
2121 m: vec![0.0],
2122 u: vec![0],
2123 clean: 1,
2124 seed: estimate.max(1.0),
2125 sum: 0.0,
2126 n: 0,
2127 width: f32::NAN,
2128 last: 0,
2129 }
2130 }
2131
2132 pub fn len(&self) -> usize {
2133 self.h.len()
2134 }
2135
2136 pub fn is_empty(&self) -> bool {
2137 self.h.is_empty()
2138 }
2139
2140 /// Grows or shrinks to `rows`, keeping what is still in range — rows
2141 /// appended to a log keep every height already measured, and cost
2142 /// nothing until something asks about them. A list whose rows *changed*
2143 /// rather than grew wants [`Self::clear`].
2144 pub fn set_len(&mut self, rows: usize) {
2145 if rows == self.h.len() {
2146 return;
2147 }
2148 for i in rows..self.h.len() {
2149 self.forget(i);
2150 }
2151 self.h.resize(rows, f32::NAN);
2152 self.clean = self.clean.min(rows + 1);
2153 }
2154
2155 /// Forgets every measurement, keeping the length and the seed — the call
2156 /// for a list whose contents changed under the same indices.
2157 pub fn clear(&mut self) {
2158 self.h.fill(f32::NAN);
2159 self.sum = 0.0;
2160 self.n = 0;
2161 self.clean = 1;
2162 }
2163
2164 /// Records row `i`'s height. Rows measured this way are what the
2165 /// estimate for the others is the mean of.
2166 pub fn set(&mut self, i: usize, h: f32) {
2167 if i >= self.h.len() || !h.is_finite() || h < 0.0 {
2168 return;
2169 }
2170 self.forget(i);
2171 self.h[i] = h;
2172 self.sum += h;
2173 self.n += 1;
2174 // Everything up to and including row `i`'s own top is unchanged.
2175 self.clean = self.clean.min(i + 1);
2176 }
2177
2178 fn forget(&mut self, i: usize) {
2179 let old = self.h[i];
2180 if !old.is_nan() {
2181 self.sum -= old;
2182 self.n -= 1;
2183 self.h[i] = f32::NAN;
2184 self.clean = self.clean.min(i + 1);
2185 }
2186 }
2187
2188 /// Row `i`'s height as it was measured, or `None` for one standing at
2189 /// the estimate.
2190 pub fn measured(&self, i: usize) -> Option<f32> {
2191 self.h.get(i).copied().filter(|h| !h.is_nan())
2192 }
2193
2194 /// Row `i`'s height: measured, or the estimate.
2195 pub fn get(&self, i: usize) -> f32 {
2196 self.measured(i).unwrap_or_else(|| self.estimate())
2197 }
2198
2199 /// What an unmeasured row stands at: the mean of the measured ones, or
2200 /// the caller's seed before there are any.
2201 pub fn estimate(&self) -> f32 {
2202 if self.n == 0 {
2203 self.seed
2204 } else {
2205 self.sum / self.n as f32
2206 }
2207 }
2208
2209 /// The width the measurements were taken at, or `NaN` before any.
2210 pub fn width(&self) -> f32 {
2211 self.width
2212 }
2213
2214 /// Declares the content width the next measurements are for. A width
2215 /// that differs from the cached one drops every height — the rows wrap
2216 /// differently now — and returns true. [`list`] calls this from
2217 /// the container's own laid-out box.
2218 pub fn set_width(&mut self, w: f32) -> bool {
2219 if !w.is_finite() || w <= 0.0 || (self.width - w).abs() < 0.5 {
2220 return false;
2221 }
2222 let had = self.n > 0;
2223 self.width = w;
2224 if had {
2225 self.clear();
2226 }
2227 true
2228 }
2229
2230 /// Fills the prefix sums up to `i` if they do not reach it yet.
2231 fn ensure(&mut self, i: usize) {
2232 let want = i.min(self.h.len()) + 1;
2233 if self.clean >= want {
2234 return;
2235 }
2236 self.m.truncate(self.clean);
2237 self.u.truncate(self.clean);
2238 self.m.reserve(want - self.clean);
2239 self.u.reserve(want - self.clean);
2240 let (mut acc, mut est) = (self.m[self.clean - 1], self.u[self.clean - 1]);
2241 for &h in &self.h[self.clean - 1..want - 1] {
2242 if h.is_nan() {
2243 est += 1;
2244 } else {
2245 acc += h;
2246 }
2247 self.m.push(acc);
2248 self.u.push(est);
2249 }
2250 self.clean = want;
2251 }
2252
2253 /// The top of row `i` in content coordinates — the height of everything
2254 /// above it. `offset_of(len())` is the whole list's height.
2255 pub fn offset_of(&mut self, i: usize) -> f32 {
2256 let i = i.min(self.h.len());
2257 self.ensure(i);
2258 self.m[i] + self.u[i] as f32 * self.estimate()
2259 }
2260
2261 /// The list's total height, measured and estimated together — what the
2262 /// two spacers and the scrollbar are made of. Kept as it goes, so the
2263 /// tail spacer costs nothing however long the list is.
2264 pub fn total(&self) -> f32 {
2265 self.sum + (self.h.len() - self.n) as f32 * self.estimate()
2266 }
2267
2268 /// The row `y` (content coordinates) lands in: the last row whose top is
2269 /// at or above it, clamped to the list. The binary search that replaces
2270 /// `y / row_h`.
2271 pub fn row_at(&mut self, y: f32) -> usize {
2272 let rows = self.h.len();
2273 if rows == 0 || y <= 0.0 {
2274 self.last = 0;
2275 return 0;
2276 }
2277 // `offset_of` is non-decreasing, so what is wanted is the last row
2278 // whose top is at or below `y`. Row 0's top is 0, so it always
2279 // qualifies and the bracket below always closes.
2280 let mut lo = self.last.min(rows - 1);
2281 let mut hi;
2282 if self.offset_of(lo) > y {
2283 hi = lo;
2284 let mut step = 1usize;
2285 while lo > 0 {
2286 lo = lo.saturating_sub(step);
2287 if self.offset_of(lo) <= y {
2288 break;
2289 }
2290 hi = lo;
2291 step *= 2;
2292 }
2293 } else {
2294 hi = (lo + 1).min(rows);
2295 let mut step = 1usize;
2296 while hi < rows && self.offset_of(hi) <= y {
2297 lo = hi;
2298 hi = (hi + step).min(rows);
2299 step *= 2;
2300 }
2301 }
2302 while lo + 1 < hi {
2303 let mid = lo + (hi - lo) / 2;
2304 if self.offset_of(mid) <= y {
2305 lo = mid;
2306 } else {
2307 hi = mid;
2308 }
2309 }
2310 self.last = lo;
2311 lo
2312 }
2313}
2314
2315/// A vertically scrolling column of rows of *different* heights that builds
2316/// only the visible ones — [`uniform_list`] where no single stride
2317/// describes the list.
2318///
2319/// `measure(ui, i, width)` returns row `i`'s height at that content width,
2320/// and is called only for rows the frame is about to build that `heights`
2321/// has no number for; `ui.measure_text(.., Some(width))` is layout's own
2322/// answer for a text row, wrap and all, and shapes through the same cache
2323/// the row's draw will hit. What it returns is the height the row *gets*:
2324/// each row's node is fixed to it, so the arithmetic above and below can
2325/// never disagree with the layout, the way `uniform_list`'s stride cannot.
2326/// A row that would rather size itself has to say what that size is here.
2327///
2328/// `row(ui, i)` declares row `i` inside that node, exactly as
2329/// `uniform_list`'s does, and rows are opened with [`Ui::open_indexed`] at
2330/// their data index, so a row keeps its hover, focus, edit buffer and tweens
2331/// as the built range slides over it.
2332///
2333/// **What it does that the uniform one never has to:** every row not yet
2334/// measured stands at the mean of the ones that are, so measuring the rows
2335/// this frame builds changes the height of every row it does not — the ones
2336/// above the window included. Left alone that slides the content out from
2337/// under the pointer on the frame it learns anything. So the widget takes
2338/// the row the window starts in and how far into it, measures, and then puts
2339/// that pair back: `Core::set_scroll` from inside a view lands on the frame
2340/// being built (the positions pass reads the store after the view has run),
2341/// so the corrected frame is the only one ever seen. What does move is the
2342/// scrollbar, which is the honest thing to move — the list really did just
2343/// learn it is a different length.
2344///
2345/// Returns the container's key, for `set_scroll` — and "scroll to row `i`"
2346/// is `set_scroll(key, Vec2::new(0.0, heights.offset_of(i)))`, exact for a
2347/// measured row and converging over a frame or two for one that is not.
2348pub fn list(
2349 ui: &mut Ui<'_>,
2350 label: &str,
2351 spec: NodeSpec,
2352 heights: &mut RowHeights,
2353 mut measure: impl FnMut(&mut Ui<'_>, usize, f32) -> f32,
2354 mut row: impl FnMut(&mut Ui<'_>, usize),
2355) -> Key {
2356 let key = ui.child_key(label);
2357 let mut slice = heights.slice(ListReading::of(ui, key, spec.layout.padding));
2358 loop {
2359 let pending = slice.unmeasured(heights);
2360 if pending.is_empty() {
2361 break;
2362 }
2363 for i in pending {
2364 let h = measure(ui, i, slice.width());
2365 heights.set(i, h);
2366 }
2367 if !slice.reslice(heights) {
2368 break;
2369 }
2370 }
2371 let plan = slice.finish(heights);
2372 // A write from inside a view lands on the frame being built: the
2373 // positions pass reads the store after the view has run. So the frame
2374 // that learned the rows are a different size is drawn already
2375 // corrected, and the uncorrected one is never seen. A shift, not a
2376 // `set_scroll`: the correction moves the coordinates under the
2377 // content, so it is never eased on a container with a `transition`,
2378 // and mid-glide it moves the leg with it rather than ending the leg
2379 // where the content stands (RG18).
2380 if let Some((drawn, target)) = plan.shift {
2381 ui.shift_scroll(key, Vec2::new(0.0, drawn), Vec2::new(0.0, target));
2382 }
2383
2384 ui.with_keyed(label, spec.scroll_y().gap(0.0), |ui| {
2385 ui.row_count(heights.len() as u64);
2386 if plan.lead > 0.0 {
2387 ui.leaf_keyed("lead", spacer_spec(plan.lead));
2388 }
2389 for i in plan.range.clone() {
2390 ui.with_indexed(i as u64, row_spec(heights.get(i)), |ui| row(ui, i));
2391 }
2392 if plan.tail > 0.0 {
2393 ui.leaf_keyed("tail", spacer_spec(plan.tail));
2394 }
2395 });
2396
2397 // As `uniform_list`'s first frame.
2398 if plan.first_frame {
2399 ui.owe_frame("list first frame");
2400 }
2401 key
2402}
2403
2404/// What a variable-height list reads before it slices: the container's
2405/// last layout, where its scroll is going, the window, and the padding
2406/// its rows sit inside. [`list`] takes it from the frame
2407/// ([`Self::of`]); a binding builds it from the same readings its view
2408/// already has (`scrollGeometry`, `scrollOffset`, the viewport), so the
2409/// arithmetic after it is this module's in every language.
2410#[derive(Clone, Copy, Debug, Default)]
2411pub struct ListReading {
2412 /// `scroll_geometry` of the container, `None` before a layout has
2413 /// resolved it — the first frame.
2414 pub geometry: Option<crate::scroll::ScrollGeometry>,
2415 /// `scroll_offset(key).y`: the retained offset, which is where an
2416 /// eased leg is going when it differs from `geometry.offset`.
2417 pub scroll_y: f32,
2418 /// The window, logical px: what the first frame slices by.
2419 pub viewport: crate::geom::Size,
2420 /// The container's top padding and its horizontal padding together.
2421 pub pad_t: f32,
2422 pub pad_x: f32,
2423 /// Rows built past each end of the window; 2 unless a view says.
2424 pub overscan: usize,
2425}
2426
2427impl ListReading {
2428 /// The reading for the container `key`, with `pad` its padding, from
2429 /// the frame being built.
2430 pub fn of(ui: &Ui<'_>, key: Key, pad: crate::geom::Edges) -> Self {
2431 ListReading {
2432 geometry: ui.scroll_geometry(key),
2433 scroll_y: ui.scroll_offset(key).y,
2434 viewport: ui.viewport(),
2435 pad_t: pad.t,
2436 pad_x: pad.x(),
2437 overscan: 2,
2438 }
2439 }
2440}
2441
2442/// One frame's slicing of a variable-height list, between the reading and
2443/// the rows: which rows to measure, and — once they are — where the window
2444/// lands and what to build. Made by [`RowHeights::slice`]; see [`list`]
2445/// for the loop that drives it, which every binding's port repeats.
2446#[derive(Clone, Debug)]
2447pub struct ListSlice {
2448 range: std::ops::Range<usize>,
2449 /// The row the window starts in, and how far into it: the pair the
2450 /// correction puts back where it was.
2451 anchor: usize,
2452 into: f32,
2453 top: f32,
2454 /// What the passes move `top` away from. The correction is for a
2455 /// *measurement* moving the numbers — not for the clamp to zero, which
2456 /// on a list shorter than its box (offset 0, padding 6) makes `top +
2457 /// pad_t` differ from the offset every frame, and a correction every
2458 /// frame is a frame requested every frame.
2459 top_before: f32,
2460 /// Where an eased leg (F80) is going, when that is somewhere other
2461 /// than where the content is drawn: a second anchor, so the row under
2462 /// the target stays the target however the measurements move the rows
2463 /// between the two (RG18). The target, its row, and how far into it.
2464 target: Option<(f32, usize, f32)>,
2465 vh: f32,
2466 width: f32,
2467 overscan: usize,
2468 passes: usize,
2469 first_frame: bool,
2470}
2471
2472/// What a [`ListSlice`] comes to: the rows to build, the two spacers'
2473/// heights, and the scroll correction the frame needs (see [`list`]).
2474#[derive(Clone, Debug, PartialEq)]
2475pub struct ListPlan {
2476 pub range: std::ops::Range<usize>,
2477 pub lead: f32,
2478 pub tail: f32,
2479 /// `(drawn, target)` on y, for `Ui::shift_scroll`, when measuring moved
2480 /// the rows; `None` when nothing needs correcting.
2481 pub shift: Option<(f32, f32)>,
2482 /// Sliced by the window, not a layout: the frame after it has to run.
2483 pub first_frame: bool,
2484}
2485
2486/// Measuring changes the heights the range was sliced from, which can widen
2487/// it; four passes is far more than a screenful ever needs and bounds the
2488/// work whatever the measurements do.
2489const LIST_PASSES: usize = 4;
2490
2491impl RowHeights {
2492 /// Starts a frame's slicing from `reading`: the content width (a new one
2493 /// drops every height, since the rows rewrap), the anchors, and the
2494 /// first range.
2495 pub fn slice(&mut self, reading: ListReading) -> ListSlice {
2496 let mut target_y = None;
2497 let (offset_y, vh, cw, first_frame) = match reading.geometry {
2498 Some(g) => {
2499 let t = reading.scroll_y.clamp(0.0, g.max_offset.y);
2500 if (t - g.offset.y).abs() > 0.5 {
2501 target_y = Some(t);
2502 }
2503 (g.offset.y, g.rect.h, g.rect.w - reading.pad_x, false)
2504 }
2505 // Nothing laid out yet: a screenful of the viewport is a safe
2506 // over-build for one frame, and the width is its width.
2507 None => (
2508 reading.scroll_y,
2509 reading.viewport.h,
2510 reading.viewport.w - reading.pad_x,
2511 true,
2512 ),
2513 };
2514 // A resize rewraps every row, so the cache is void; the frame after
2515 // it measures a screenful again.
2516 self.set_width(cw);
2517 let top = (offset_y - reading.pad_t).max(0.0);
2518 let anchor = self.row_at(top);
2519 let into = top - self.offset_of(anchor);
2520 let target = target_y.map(|t| {
2521 let t = (t - reading.pad_t).max(0.0);
2522 let row = self.row_at(t);
2523 (t, row, t - self.offset_of(row))
2524 });
2525 let range = visible_range(self, top, vh, reading.overscan);
2526 ListSlice {
2527 range,
2528 anchor,
2529 into,
2530 top,
2531 top_before: top,
2532 target,
2533 vh,
2534 width: cw,
2535 overscan: reading.overscan,
2536 passes: 0,
2537 first_frame,
2538 }
2539 }
2540}
2541
2542impl ListSlice {
2543 /// The content width the rows are measured at.
2544 pub fn width(&self) -> f32 {
2545 self.width
2546 }
2547
2548 /// The rows of the current range nothing has measured: measure each,
2549 /// [`RowHeights::set`] it, then [`Self::reslice`]. Empty is done.
2550 pub fn unmeasured(&self, heights: &RowHeights) -> Vec<usize> {
2551 self.range
2552 .clone()
2553 .filter(|&i| heights.measured(i).is_none())
2554 .collect()
2555 }
2556
2557 /// After measuring: puts the anchor row back where it was and slices
2558 /// again. Measuring moved the numbers the slice was taken from — this
2559 /// row's own, the rows above it, and (through the mean) every row
2560 /// nobody has measured at all — so what is under the pointer would
2561 /// otherwise slide out from under it. True when the range moved and
2562 /// its new rows want measuring, within the pass budget.
2563 pub fn reslice(&mut self, heights: &mut RowHeights) -> bool {
2564 self.passes += 1;
2565 self.top = heights.offset_of(self.anchor) + self.into;
2566 let next = visible_range(heights, self.top, self.vh, self.overscan);
2567 if next == self.range {
2568 return false;
2569 }
2570 self.range = next;
2571 self.passes < LIST_PASSES
2572 }
2573
2574 /// The rows to build, the spacers, and the correction.
2575 pub fn finish(self, heights: &mut RowHeights) -> ListPlan {
2576 let drawn = self.top - self.top_before;
2577 let target = match self.target {
2578 Some((t, row, into)) => heights.offset_of(row) + into - t,
2579 None => drawn,
2580 };
2581 let lead = heights.offset_of(self.range.start);
2582 let tail = heights.total() - heights.offset_of(self.range.end);
2583 ListPlan {
2584 range: self.range,
2585 lead,
2586 tail,
2587 shift: (drawn.abs() > 0.01 || target.abs() > 0.01).then_some((drawn, target)),
2588 first_frame: self.first_frame,
2589 }
2590 }
2591}
2592
2593/// The rows crossing `[top, top + vh)` plus `overscan` on each side, by
2594/// prefix-sum search. The variable-height [`visible_rows`].
2595fn visible_range(
2596 heights: &mut RowHeights,
2597 top: f32,
2598 vh: f32,
2599 overscan: usize,
2600) -> std::ops::Range<usize> {
2601 let rows = heights.len();
2602 if rows == 0 {
2603 return 0..0;
2604 }
2605 let first = heights.row_at(top).saturating_sub(overscan);
2606 let last = (heights.row_at(top + vh.max(0.0)) + 1 + overscan).min(rows);
2607 first..last.max(first)
2608}