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.
1414 let cap = if spec.layout.max_w >= 0.0 {
1415 spec.layout.max_w
1416 } else {
1417 ceiling
1418 };
1419 let inside = cap - 2.0 * (MENU_PANEL_PAD + 1.0) - 2.0 * m.menu_pad_x;
1420 // A wash rather than a fill, so a row's label stays readable on both
1421 // bases without the view guessing a frame ahead of the core — see
1422 // `Theme::accent_soft`.
1423 let accent = t.accent_soft;
1424 // A gutter for the checkmarks, and only where a row has one: a menu of
1425 // plain commands is not indented for a column nothing uses, and one
1426 // with a setting in it keeps every label on the same left edge whether
1427 // the setting is on or off.
1428 let gutter = items.iter().any(|i| i.checked);
1429 // Which of the core's menus this is, by the origin its nodes open
1430 // under: only those have submenu state to open and close.
1431 let surface = crate::runtime::MenuSurface::of(ui.origin());
1432 let group = |i: usize| format!("{root}/{path:?}/{i}");
1433 // Where the pointer rests opens or closes a submenu, resolved before
1434 // anything is built — the frame that notices the hover draws what it
1435 // opened, as the bar's titles do. The outermost level brackets the
1436 // build, so a build with the pointer on no row at all is known.
1437 if let Some(s) = surface
1438 && path.is_empty()
1439 {
1440 ui.core().submenu_pass(s, true);
1441 }
1442 if let Some(s) = surface {
1443 for (i, item) in items.iter().enumerate() {
1444 if item.selectable() && ui.is_group_hovered(NodeSpec::hover_group_id(&group(i))) {
1445 let row: Vec<usize> = path.iter().copied().chain([i]).collect();
1446 ui.core().submenu_hovered(s, &row, item.has_submenu());
1447 }
1448 }
1449 }
1450 let open_here = surface.and_then(|s| ui.core().submenu_open_at(s, path));
1451 let mut first_key = None;
1452 let root_key = ui.with_keyed(label, spec, |ui| {
1453 let mut first = path.is_empty();
1454 for (i, item) in items.iter().enumerate() {
1455 if item.role == MenuRole::Separator {
1456 ui.leaf_indexed(
1457 i as u64,
1458 NodeSpec::row()
1459 .grow_width()
1460 .height(1.0)
1461 .bg(t.border)
1462 // Not a row anything reads out: a divider is
1463 // paint, and a screen reader hearing "separator"
1464 // between every pair of items is noise.
1465 .role(Role::None),
1466 );
1467 continue;
1468 }
1469 // The row posts which item it is; the core takes the event back
1470 // by origin, performs the item — or opens its submenu — and
1471 // what the app hears is the item's own `id` on the node the
1472 // menu was about.
1473 let payload = menu_row_tag(i, path);
1474 let opens = item.has_submenu();
1475 let is_open = opens && open_here == Some(i);
1476 let mut spec = NodeSpec::row()
1477 .role(Role::MenuItem)
1478 .label(item.text())
1479 .grow_width()
1480 // Its content as a floor, which is what a fit panel is
1481 // sized from: a grow child alone contributes nothing.
1482 .min_width(crate::spec::Bound::Fit)
1483 .pad_xy(m.menu_pad_x, m.menu_pad_y)
1484 .gap(MENU_ROW_GAP)
1485 .radius(m.radius_inner)
1486 .main_align(Align::Start)
1487 .cross_align(Align::Center);
1488 if item.checked {
1489 // The gutter's checkmark is paint; this is the same fact for
1490 // a screen reader, which reads a row that carries one as
1491 // checked rather than as "✓ Wrap".
1492 spec = spec.checked(true);
1493 }
1494 if item.enabled {
1495 spec = spec.on_click(payload).hover_bg(accent).focus_bg(accent);
1496 if surface.is_some() {
1497 spec = spec.hover_group(&group(i));
1498 }
1499 // The first row that can take focus is where the modal opens:
1500 // a menu whose keyboard starts nowhere makes the arrow keys
1501 // feel like they missed. A submenu is no modal of its own;
1502 // the keyboard that opens one puts focus in it.
1503 if first {
1504 spec = spec.initial_focus();
1505 first = false;
1506 }
1507 } else {
1508 spec = spec.disabled(true).opacity(t.disabled_opacity);
1509 }
1510 if opens {
1511 // A reader hears it as a row that opens something, and
1512 // whether it is open; the open one keeps the wash while the
1513 // pointer is in its submenu, so the way back is visible.
1514 spec = spec.expanded(is_open);
1515 if is_open {
1516 spec = spec.bg(accent);
1517 }
1518 }
1519 let tail = if opens {
1520 Some(std::borrow::Cow::Borrowed(MENU_CHEVRON))
1521 } else {
1522 item.accel_label()
1523 };
1524 let row = |ui: &mut Ui<'_>| {
1525 let tail_style = TextStyle::new(m.chrome_text).color(t.muted).nowrap();
1526 let mut label_max = inside;
1527 if gutter {
1528 label_max -= MENU_CHECK_W + MENU_ROW_GAP;
1529 }
1530 if let Some(tail) = &tail {
1531 let w = ui.measure_text(tail, &tail_style, None).width;
1532 label_max -= 2.0 * MENU_ROW_GAP + MENU_ACCEL_GAP + w;
1533 }
1534 if gutter {
1535 ui.with(NodeSpec::row().width(MENU_CHECK_W), |ui| {
1536 if item.checked {
1537 ui.text("\u{2713}", TextStyle::new(m.chrome_text).color(t.fg));
1538 }
1539 });
1540 }
1541 // One line each, whatever the panel's width: the panel is
1542 // sized to fit them, and a row that wrapped would be read as
1543 // two.
1544 ui.text_in(
1545 NodeSpec::row().max_width(label_max.max(0.0)),
1546 item.text(),
1547 TextStyle::new(m.chrome_text)
1548 .color(t.fg)
1549 .nowrap()
1550 .ellipsis(),
1551 );
1552 // Pushed to the right edge by a grow spacer, so the label
1553 // stays where the eye expects it whatever follows it; at
1554 // least `MENU_ACCEL_GAP` wide, so the widest label and the
1555 // widest accelerator never touch. A submenu's row has its
1556 // chevron there and no accelerator: it binds nothing.
1557 if let Some(tail) = &tail {
1558 ui.leaf(NodeSpec::row().grow_width().min_width(MENU_ACCEL_GAP));
1559 ui.text(tail, tail_style);
1560 }
1561 };
1562 let key = if opens {
1563 // A wrapper the submenu drops out of, so the panel is the
1564 // row's *sibling* — the menu bar's reason: a `menuItem` is
1565 // named from its content, and a menu inside one would be
1566 // read as part of its name — and floats against the row's
1567 // own box.
1568 let mut key = Key::ROOT;
1569 ui.with_indexed(
1570 i as u64,
1571 NodeSpec::row()
1572 .grow_width()
1573 .min_width(crate::spec::Bound::Fit),
1574 |ui| {
1575 key = ui.with_keyed(MENU_ROW_KEY, spec, row);
1576 if is_open && item.enabled {
1577 let sub: Vec<usize> = path.iter().copied().chain([i]).collect();
1578 menu_level(
1579 ui,
1580 root,
1581 MENU_SUB_KEY,
1582 menu_panel_spec(&t, &m)
1583 .label(item.text())
1584 // A region of its own, so a press on its
1585 // padding or a dead row is inside the
1586 // menu — as the outer panel's `modal`
1587 // makes it there — and not the press
1588 // outside that dismisses it.
1589 .hoverable()
1590 .float(
1591 // Beside the row, its first row level
1592 // with this one (the panel's padding
1593 // above it), flipped to the other side
1594 // at the window's edge.
1595 FloatConfig::parent()
1596 .at(Align::End, Align::Start)
1597 .self_at(Align::Start, Align::Start)
1598 .offset(MENU_PANEL_PAD, -MENU_PANEL_PAD)
1599 .fit(),
1600 ),
1601 &item.submenu,
1602 &sub,
1603 );
1604 }
1605 },
1606 );
1607 key
1608 } else {
1609 ui.with_indexed(i as u64, spec, row)
1610 };
1611 if item.enabled && first_key.is_none() {
1612 first_key = Some(key);
1613 }
1614 }
1615 });
1616 // The keyboard opened this submenu (Enter, the Right arrow): the
1617 // first row it can take is where it lands, now that it exists.
1618 if let (Some(s), Some(key)) = (surface, first_key)
1619 && !path.is_empty()
1620 {
1621 ui.core().submenu_drawn(s, path, key);
1622 }
1623 if let Some(s) = surface
1624 && path.is_empty()
1625 {
1626 ui.core().submenu_pass(s, false);
1627 }
1628 root_key
1629}
1630
1631/// The padding inside a menu's panel, logical px: what a submenu is offset
1632/// by so its first row sits level with the row that opened it.
1633const MENU_PANEL_PAD: f32 = 4.0;
1634
1635/// How far a menu at its widest stays from each side of the window.
1636pub const MENU_EDGE: f32 = 8.0;
1637
1638/// Between a row's checkmark, label, spacer and accelerator.
1639const MENU_ROW_GAP: f32 = 8.0;
1640
1641/// The chevron a submenu's row draws where an accelerator would be.
1642pub const MENU_CHEVRON: &str = "\u{203a}";
1643/// The label a submenu's row is keyed under, inside its wrapper.
1644const MENU_ROW_KEY: &str = "row";
1645/// The label a submenu's panel is keyed under, beside its row.
1646const MENU_SUB_KEY: &str = "sub";
1647
1648/// What a menu row's click carries: its index in its menu's items, and —
1649/// for a row of a submenu — the rows opened on the way to it, for the core
1650/// to read back (`Core::take_surface_events`). The title of a menu-bar
1651/// menu carries its index the same way, under `title`. A top-level row
1652/// carries `row` alone, as it always did.
1653fn menu_row_tag(i: usize, path: &[usize]) -> Value {
1654 let row = ("row", Value::Int(i as i64));
1655 if path.is_empty() {
1656 Value::map([row])
1657 } else {
1658 Value::map([
1659 row,
1660 (
1661 "path",
1662 Value::List(path.iter().map(|&p| Value::Int(p as i64)).collect()),
1663 ),
1664 ])
1665 }
1666}
1667
1668fn menu_title_tag(i: usize) -> Value {
1669 Value::map([("title", Value::Int(i as i64))])
1670}
1671
1672/// The reserved label the drawn menu bar is keyed under, the way
1673/// [`MENU_KEY`] is the open menu's.
1674pub const MENU_BAR_KEY: &str = "kui.menubar";
1675/// The label its dropped menu is keyed under, beside the open title.
1676const MENU_BAR_PANEL_KEY: &str = "kui.menubar.menu";
1677/// The label each title is keyed under, inside its own wrapper.
1678const MENU_BAR_TITLE_KEY: &str = "kui.menubar.title";
1679
1680/// The hover group a title and its menu share, so the widget can ask
1681/// whether the pointer is on the `i`th title without knowing its key.
1682fn group_name(i: usize) -> String {
1683 format!("{MENU_BAR_KEY}.{i}")
1684}
1685/// The bar's height, logical px — a little under a titlebar's, which is
1686/// what every platform that draws one in the window does.
1687pub const MENU_BAR_H: f32 = Metrics::comfortable().menu_bar_h;
1688
1689/// The application menu: `bar` is what the app's menu *is*, and calling
1690/// this is where its titles go when they have to be drawn in the window.
1691///
1692/// One call and not two, because the declaration and the placement are one
1693/// decision. **It draws nothing where the platform owns the bar** — macOS,
1694/// where the driver hands this same declaration to `NSApp` — so the call
1695/// still says what the menu is and the strip simply is not there; that is
1696/// the contract [`window_buttons`] has under native decorations, and it is
1697/// what makes one view portable. An empty `bar` takes the menu away.
1698///
1699/// Declared every frame, and diffed: an unchanged menu costs a comparison
1700/// and rebuilds nothing.
1701///
1702/// Everything below a title is the stock menu: the same rows, roles,
1703/// accelerators and access tree the context menu draws, through the same
1704/// [`menu_panel`]. What is the bar's own is the scope — while a menu is
1705/// open the *bar* is the frame's modal, not the dropdown, so hovering
1706/// across the titles moves the open menu the way a menu bar does, a press
1707/// on the open title closes it, and Escape or a press in the app below
1708/// dismisses it as any modal is dismissed.
1709///
1710/// Typical use, as the first child of a full-height root, under the
1711/// titlebar if there is one:
1712/// `widgets::menu_bar(ui, self.menu());`
1713pub fn menu_bar(ui: &mut Ui<'_>, bar: MenuBar) {
1714 // Declaring it is this call's first half, and drawing it the second:
1715 // where the platform owns the bar there is no second half, and the
1716 // frame has still said what the app's menu is.
1717 ui.core().declare_menu_bar(bar);
1718 if ui.core().native_menu_bar() {
1719 return;
1720 }
1721 let Some(bar) = ui.core().menu_bar().cloned() else {
1722 return;
1723 };
1724 if bar.menus.is_empty() {
1725 return;
1726 }
1727 let t = ui.theme();
1728 let m = ui.metrics();
1729 let accent = t.accent_soft;
1730 let mut open = ui.core().menu_bar_open();
1731 // The bar's nodes are the core's, opened under their own origin (see
1732 // `OriginId::MENU_BAR`), so the core takes their events back by it.
1733 let saved = ui.origin();
1734 ui.set_origin(OriginId::MENU_BAR);
1735 let mut spec = NodeSpec::row()
1736 .grow_width()
1737 .height(m.menu_bar_h)
1738 .cross_align(Align::Center)
1739 .pad_xy(4.0, 0.0)
1740 .gap(2.0)
1741 .bg(t.bg)
1742 .role(Role::Menu)
1743 .label("Menu bar");
1744 if open.is_some() {
1745 // The bar and not the dropdown is the modal while a menu is open:
1746 // the titles have to stay live for the hover to walk them, and the
1747 // app below has to be as inert as it is under any other menu.
1748 spec = spec.modal(Value::str(MENU_BAR_KEY));
1749 }
1750 let root = ui.with_keyed(MENU_BAR_KEY, spec, |ui| {
1751 // Hovering another title while a menu is open moves the open menu
1752 // to it, which is what a menu bar does everywhere. Resolved before
1753 // anything is built, so the frame that notices the hover is the
1754 // frame that draws the new menu and not the one after it — and
1755 // asked by *group* rather than by key, since a title's key is
1756 // inside a wrapper this loop has not opened yet.
1757 if open.is_some() {
1758 for (i, menu) in bar.menus.iter().enumerate() {
1759 let hovered = ui.is_group_hovered(NodeSpec::hover_group_id(&group_name(i)));
1760 if open != Some(i) && menu.enabled && !menu.items.is_empty() && hovered {
1761 open = Some(i);
1762 ui.core().set_menu_bar_open(open);
1763 }
1764 }
1765 }
1766 for (i, menu) in bar.menus.iter().enumerate() {
1767 let live = menu.enabled && !menu.items.is_empty();
1768 let is_open = open == Some(i);
1769 // A wrapper the menu drops out of, so the panel is a *sibling*
1770 // of the title and not a child of it: a `menuItem` is a
1771 // name-from-content role, and a menu nested inside one would be
1772 // read as part of its name and never reached on its own.
1773 ui.with_indexed(i as u64, NodeSpec::row(), |ui| {
1774 let mut spec = NodeSpec::row()
1775 .role(Role::MenuItem)
1776 .label(menu.label.as_str())
1777 // Two px shorter than a row's, so the bar's height and
1778 // not the title's padding decides the strip.
1779 .pad_xy(m.menu_pad_x, (m.menu_pad_y - 2.0).max(0.0))
1780 .radius(m.radius_inner)
1781 .cross_align(Align::Center);
1782 if live {
1783 // Which title this is: the core takes the event back
1784 // by origin and opens or closes the `i`th menu.
1785 spec = spec
1786 .on_click(menu_title_tag(i))
1787 .hover_group(&group_name(i))
1788 .hover_bg(accent)
1789 .focus_bg(accent);
1790 if is_open {
1791 spec = spec.bg(accent);
1792 }
1793 } else {
1794 spec = spec.disabled(true).opacity(t.disabled_opacity);
1795 }
1796 ui.text_in_keyed(
1797 MENU_BAR_TITLE_KEY,
1798 spec,
1799 menu.label.as_str(),
1800 TextStyle::new(m.chrome_text).color(t.fg),
1801 );
1802 if is_open {
1803 // Out of the title's bottom-left corner, and `fit` to
1804 // slide back in at the right-hand end of the bar.
1805 menu_panel(
1806 ui,
1807 MENU_BAR_PANEL_KEY,
1808 menu_panel_spec(&t, &m).label(menu.label.as_str()).float(
1809 FloatConfig::parent()
1810 .at(Align::Start, Align::End)
1811 .self_at(Align::Start, Align::Start)
1812 .offset(0.0, 2.0)
1813 .fit(),
1814 ),
1815 &menu.items,
1816 );
1817 }
1818 });
1819 }
1820 });
1821 ui.set_origin(saved);
1822 ui.core().set_menu_bar_root(root);
1823}
1824
1825/// The checkmark gutter's width, logical px.
1826const MENU_CHECK_W: f32 = 14.0;
1827
1828/// The least room between a row's label and its accelerator, logical px,
1829/// beside the row's own gap on either side: about what AppKit leaves
1830/// before a key equivalent.
1831pub const MENU_ACCEL_GAP: f32 = 16.0;
1832
1833// -- Virtual lists ----------------------------------------------------------
1834// The core culls glyphs by viewport but builds every child a view declares,
1835// so a ten-thousand-row log costs ten thousand rows of build and layout on
1836// every frame — most of a 120 Hz budget spent on rows nobody can see. A view
1837// that knows the container's height and offset can declare a screenful and
1838// two spacers instead. `Core::scroll_geometry` is that knowledge; this is
1839// the arithmetic, for the case where every row is the same height.
1840
1841/// The half-open range of rows a container of `rows` rows, each `row_h`
1842/// logical px tall, has any reason to build — those crossing the visible
1843/// band, plus `overscan` on each side — given the geometry of the frame
1844/// before. Pure arithmetic, exposed for views that build their own
1845/// container instead of using [`uniform_list`].
1846///
1847/// `vh` is the container's height, and `pad_t` the padding above the first
1848/// row. `None` geometry means no layout has resolved the container yet:
1849/// the caller decides what the first frame builds.
1850pub fn visible_rows(
1851 offset_y: f32,
1852 vh: f32,
1853 pad_t: f32,
1854 row_h: f32,
1855 rows: usize,
1856 overscan: usize,
1857) -> std::ops::Range<usize> {
1858 if rows == 0 || row_h <= 0.0 {
1859 return 0..0;
1860 }
1861 // Flow coordinates: row i spans [i*row_h, (i+1)*row_h), and layout puts
1862 // the flow's origin at pad_t - offset_y inside the container's box, so
1863 // the visible window is [offset_y - pad_t, that + vh).
1864 let top = offset_y - pad_t;
1865 let first = (top / row_h).floor().max(0.0) as usize;
1866 let last = ((top + vh.max(0.0)) / row_h).ceil().max(0.0) as usize;
1867 let first = first.saturating_sub(overscan).min(rows);
1868 let last = last.saturating_add(overscan).min(rows);
1869 first..last.max(first)
1870}
1871
1872/// A vertically scrolling column of `rows` uniform rows that builds only the
1873/// visible ones. `row(ui, i)` declares row `i`; it must come out exactly
1874/// `row_h` logical px tall, since that is the arithmetic placing every row
1875/// above and below it.
1876///
1877/// The container is `spec` forced to a scrolling column with no gap — put
1878/// the spacing inside `row_h` (a row that pads itself) rather than in a
1879/// `gap`, so one number describes the stride. Rows are opened with
1880/// [`Ui::open_indexed`] at their *data* index, so a row keeps its key, and
1881/// with it its hover, focus, edit buffer and tweens, as the built range
1882/// slides over it. Above and below sit two empty spacers holding the space
1883/// of the rows not built, so the content height, the scrollbar and
1884/// `set_scroll` all behave as if the whole list were there.
1885///
1886/// The geometry it slices by is the previous frame's, so the first frame —
1887/// before any layout has resolved the container — slices by the viewport
1888/// height instead and asks for one more frame; a resize is one frame late
1889/// and covered by the two rows of overscan. Returns the container's key,
1890/// for `set_scroll` (`Vec2::new(0.0, i as f32 * row_h)` scrolls row `i` to
1891/// the top, which is how you reach a row that is not built — `reveal` of an
1892/// unbuilt row finds nothing).
1893pub fn uniform_list(
1894 ui: &mut Ui<'_>,
1895 label: &str,
1896 spec: NodeSpec,
1897 rows: usize,
1898 row_h: f32,
1899 row: impl FnMut(&mut Ui<'_>, usize),
1900) -> Key {
1901 uniform_list_with(ui, label, spec, rows, row_h, |_| NodeSpec::column(), row)
1902}
1903
1904/// [`uniform_list`] with each row's own node spelled by `row_spec(i)` —
1905/// the click, the zebra stripe, the hover background, the role a row
1906/// carries — where the plain form's rows are bare and the callback nests
1907/// a second node inside each to carry them. The height is
1908/// forced to `row_h`, the stride the arithmetic assumes, and a width the
1909/// spec leaves `fit` grows across the list.
1910pub fn uniform_list_with(
1911 ui: &mut Ui<'_>,
1912 label: &str,
1913 spec: NodeSpec,
1914 rows: usize,
1915 row_h: f32,
1916 mut row_spec: impl FnMut(usize) -> NodeSpec,
1917 mut row: impl FnMut(&mut Ui<'_>, usize),
1918) -> Key {
1919 const OVERSCAN: usize = 2;
1920
1921 let key = ui.child_key(label);
1922 let pad_t = spec.layout.padding.t;
1923 // Both numbers from the same frame: the geometry's offset is clamped to
1924 // that frame's travel, so a `set_scroll(key, huge)` between frames
1925 // slices the end of the list instead of a megabyte past it.
1926 let (offset_y, vh, first_frame) = match ui.scroll_geometry(key) {
1927 Some(g) => (g.offset.y, g.rect.h, false),
1928 // Nothing laid out yet: the container cannot be taller than the
1929 // window in the ordinary case, so a screenful is a safe over-build
1930 // for one frame.
1931 None => (ui.scroll_offset(key).y, ui.viewport().h, true),
1932 };
1933 let range = visible_rows(offset_y, vh, pad_t, row_h, rows, OVERSCAN);
1934
1935 ui.with_keyed(label, spec.scroll_y().gap(0.0), |ui| {
1936 // The whole list's size, built or not: what Select All inside a
1937 // `selectable` list spans.
1938 ui.row_count(rows as u64);
1939 // Keyed, not auto-keyed: an auto key is a sibling index, and the
1940 // rows already occupy that namespace at their data indices — an
1941 // auto-keyed spacer next to a built row 0 would be row 0's key.
1942 let lead = range.start as f32 * row_h;
1943 if lead > 0.0 {
1944 ui.leaf_keyed("lead", spacer_spec(lead));
1945 }
1946 for i in range.clone() {
1947 let mut spec = row_spec(i).height(row_h);
1948 if spec.layout.width == Sizing::Fit {
1949 spec = spec.grow_width();
1950 }
1951 ui.with_indexed(i as u64, spec, |ui| row(ui, i));
1952 }
1953 let tail = (rows - range.end) as f32 * row_h;
1954 if tail > 0.0 {
1955 ui.leaf_keyed("tail", spacer_spec(tail));
1956 }
1957 });
1958
1959 // Sliced by a screenful's guess, with no layout of its own yet: the
1960 // next frame slices by its geometry. kui's ask, not the app's, so a
1961 // trace names it for what it is.
1962 if first_frame {
1963 ui.owe_frame("list first frame");
1964 }
1965 key
1966}
1967
1968/// Scrolls the [`uniform_list`] labelled `label` so row `i` shows, when
1969/// it does not already: to the middle of the list, so a jump lands with
1970/// rows on both sides of it. Call it before the list is
1971/// declared, in the same parent — the frame that scrolls then slices its
1972/// rows by the offset it scrolls to, instead of a frame late. Returns
1973/// whether it scrolled. The first frame, before the list has laid out,
1974/// has no geometry and scrolls nothing; the row arithmetic assumes the
1975/// list's rows start at its content top and fill its box, as they do
1976/// without padding. A row past the list's content — an index past its
1977/// end — scrolls nothing and answers false, as does a `row_h` that is
1978/// not positive.
1979///
1980/// `Ui::reveal` cannot do this for a row that is not built, and a
1981/// virtual list builds only what shows.
1982pub fn reveal_row(ui: &mut Ui<'_>, label: &str, i: usize, row_h: f32) -> bool {
1983 let key = ui.child_key(label);
1984 let Some(g) = ui.scroll_geometry(key) else {
1985 return false;
1986 };
1987 let y = i as f32 * row_h;
1988 if row_h <= 0.0 || y + row_h > g.content.h + 0.5 {
1989 return false;
1990 }
1991 if g.offset.y <= y && y + row_h <= g.offset.y + g.rect.h {
1992 return false;
1993 }
1994 let to = (y + row_h / 2.0 - g.rect.h / 2.0).max(0.0);
1995 ui.set_scroll(key, Vec2::new(g.offset.x, to));
1996 true
1997}
1998
1999/// How many whole rows of `row_h` the [`uniform_list`] labelled `label`
2000/// shows as of the last layout — a PageDown's stride. 0 before it has
2001/// laid out, and for a `row_h` that is not positive.
2002pub fn rows_in_view(ui: &mut Ui<'_>, label: &str, row_h: f32) -> usize {
2003 let key = ui.child_key(label);
2004 if row_h <= 0.0 {
2005 return 0;
2006 }
2007 ui.scroll_geometry(key)
2008 .map_or(0, |g| (g.rect.h / row_h).floor().max(0.0) as usize)
2009}
2010
2011/// Each row's own node in the variable-height `list`: the wrapper the
2012/// callback builds inside, sized to the height the arithmetic assumes.
2013fn row_spec(h: f32) -> NodeSpec {
2014 NodeSpec::column().grow_width().height(h)
2015}
2016
2017fn spacer_spec(h: f32) -> NodeSpec {
2018 NodeSpec::column().grow_width().height(h)
2019}
2020
2021// -- Variable-height virtual lists ------------------------------------------
2022// `uniform_list` takes one stride and every row must come out that tall,
2023// which is the log viewer, the data table and the chat history whose rows are
2024// one line. A row that wraps, a card with an image, a message that is
2025// sometimes three lines: none of those have a stride, and the three things
2026// the uniform arithmetic does with `i * row_h` — the lead spacer, the search
2027// from an offset to the first visible row, and "scroll to row i" — have no
2028// closed form without one. Prefix sums are the closed form, and
2029// `RowHeights` is where they live.
2030//
2031// Heights come from the caller, measured only for the rows the frame needs:
2032// `measure_text` gives layout's own number for a text row (wrap, max_lines
2033// and the shaping cache included), so a row measured and then drawn shapes
2034// once. Everything not measured yet stands at an estimate, and the estimate
2035// is the mean of what has been measured — which means it *moves*, and moving
2036// it changes the height of every row above the window as well as below.
2037// That is what the anchor is for.
2038
2039/// The heights a [`list`] slices by: a measured number per row
2040/// where one is known, an estimate everywhere else, and the prefix sums over
2041/// both.
2042///
2043/// The app owns it and hands the same one back every frame — a widget
2044/// composed from primitives keeps no state of its own, which is what keeps
2045/// it reachable from a scripting frontend. Rebuild it (or [`Self::clear`])
2046/// when the rows themselves change.
2047#[derive(Clone, Debug)]
2048pub struct RowHeights {
2049 /// One per row; `f32::NAN` for a row nothing has measured yet.
2050 h: Vec<f32>,
2051 /// The prefix sums, split so that the estimate is applied at the query
2052 /// rather than baked in: `m[i]` is the measured height in rows `0..i`
2053 /// and `u[i]` how many of those rows have none. A moving mean then costs
2054 /// nothing to fold in — which matters, because every measurement moves
2055 /// it, and a mean baked into the sums would dirty all of them.
2056 m: Vec<f32>,
2057 u: Vec<u32>,
2058 /// How many entries of `m` / `u` are valid, counting from 0. Filled
2059 /// on demand and only as far as a query asks, so a list scrolled to row
2060 /// 30 never sums the 9,970 below it; a measurement at row `i` truncates
2061 /// this to `i + 1`, since nothing at or below `i` changed.
2062 clean: usize,
2063 /// What the caller guessed before anything was measured.
2064 seed: f32,
2065 /// Running mean of the measured rows — the estimate for the rest.
2066 sum: f32,
2067 n: usize,
2068 /// The content width the cached heights were measured at. A different
2069 /// one rewraps every row, so it drops them all.
2070 width: f32,
2071 /// Where the last search landed. Scrolling is local, so the next one
2072 /// gallops out from here instead of bisecting the whole list — which is
2073 /// what keeps the lazy `ensure` above from being filled past what is
2074 /// being looked at, and what a bisection from 0..len would defeat by
2075 /// probing the middle every time.
2076 last: usize,
2077}
2078
2079impl RowHeights {
2080 /// `rows` rows, none measured, each standing at `estimate` logical px
2081 /// until it is. The estimate only has to be the right order of
2082 /// magnitude: it decides how wrong the scrollbar is before the list has
2083 /// been scrolled through, and nothing else.
2084 pub fn new(rows: usize, estimate: f32) -> Self {
2085 RowHeights {
2086 h: vec![f32::NAN; rows],
2087 m: vec![0.0],
2088 u: vec![0],
2089 clean: 1,
2090 seed: estimate.max(1.0),
2091 sum: 0.0,
2092 n: 0,
2093 width: f32::NAN,
2094 last: 0,
2095 }
2096 }
2097
2098 pub fn len(&self) -> usize {
2099 self.h.len()
2100 }
2101
2102 pub fn is_empty(&self) -> bool {
2103 self.h.is_empty()
2104 }
2105
2106 /// Grows or shrinks to `rows`, keeping what is still in range — rows
2107 /// appended to a log keep every height already measured, and cost
2108 /// nothing until something asks about them. A list whose rows *changed*
2109 /// rather than grew wants [`Self::clear`].
2110 pub fn set_len(&mut self, rows: usize) {
2111 if rows == self.h.len() {
2112 return;
2113 }
2114 for i in rows..self.h.len() {
2115 self.forget(i);
2116 }
2117 self.h.resize(rows, f32::NAN);
2118 self.clean = self.clean.min(rows + 1);
2119 }
2120
2121 /// Forgets every measurement, keeping the length and the seed — the call
2122 /// for a list whose contents changed under the same indices.
2123 pub fn clear(&mut self) {
2124 self.h.fill(f32::NAN);
2125 self.sum = 0.0;
2126 self.n = 0;
2127 self.clean = 1;
2128 }
2129
2130 /// Records row `i`'s height. Rows measured this way are what the
2131 /// estimate for the others is the mean of.
2132 pub fn set(&mut self, i: usize, h: f32) {
2133 if i >= self.h.len() || !h.is_finite() || h < 0.0 {
2134 return;
2135 }
2136 self.forget(i);
2137 self.h[i] = h;
2138 self.sum += h;
2139 self.n += 1;
2140 // Everything up to and including row `i`'s own top is unchanged.
2141 self.clean = self.clean.min(i + 1);
2142 }
2143
2144 fn forget(&mut self, i: usize) {
2145 let old = self.h[i];
2146 if !old.is_nan() {
2147 self.sum -= old;
2148 self.n -= 1;
2149 self.h[i] = f32::NAN;
2150 self.clean = self.clean.min(i + 1);
2151 }
2152 }
2153
2154 /// Row `i`'s height as it was measured, or `None` for one standing at
2155 /// the estimate.
2156 pub fn measured(&self, i: usize) -> Option<f32> {
2157 self.h.get(i).copied().filter(|h| !h.is_nan())
2158 }
2159
2160 /// Row `i`'s height: measured, or the estimate.
2161 pub fn get(&self, i: usize) -> f32 {
2162 self.measured(i).unwrap_or_else(|| self.estimate())
2163 }
2164
2165 /// What an unmeasured row stands at: the mean of the measured ones, or
2166 /// the caller's seed before there are any.
2167 pub fn estimate(&self) -> f32 {
2168 if self.n == 0 {
2169 self.seed
2170 } else {
2171 self.sum / self.n as f32
2172 }
2173 }
2174
2175 /// The width the measurements were taken at, or `NaN` before any.
2176 pub fn width(&self) -> f32 {
2177 self.width
2178 }
2179
2180 /// Declares the content width the next measurements are for. A width
2181 /// that differs from the cached one drops every height — the rows wrap
2182 /// differently now — and returns true. [`list`] calls this from
2183 /// the container's own laid-out box.
2184 pub fn set_width(&mut self, w: f32) -> bool {
2185 if !w.is_finite() || w <= 0.0 || (self.width - w).abs() < 0.5 {
2186 return false;
2187 }
2188 let had = self.n > 0;
2189 self.width = w;
2190 if had {
2191 self.clear();
2192 }
2193 true
2194 }
2195
2196 /// Fills the prefix sums up to `i` if they do not reach it yet.
2197 fn ensure(&mut self, i: usize) {
2198 let want = i.min(self.h.len()) + 1;
2199 if self.clean >= want {
2200 return;
2201 }
2202 self.m.truncate(self.clean);
2203 self.u.truncate(self.clean);
2204 self.m.reserve(want - self.clean);
2205 self.u.reserve(want - self.clean);
2206 let (mut acc, mut est) = (self.m[self.clean - 1], self.u[self.clean - 1]);
2207 for &h in &self.h[self.clean - 1..want - 1] {
2208 if h.is_nan() {
2209 est += 1;
2210 } else {
2211 acc += h;
2212 }
2213 self.m.push(acc);
2214 self.u.push(est);
2215 }
2216 self.clean = want;
2217 }
2218
2219 /// The top of row `i` in content coordinates — the height of everything
2220 /// above it. `offset_of(len())` is the whole list's height.
2221 pub fn offset_of(&mut self, i: usize) -> f32 {
2222 let i = i.min(self.h.len());
2223 self.ensure(i);
2224 self.m[i] + self.u[i] as f32 * self.estimate()
2225 }
2226
2227 /// The list's total height, measured and estimated together — what the
2228 /// two spacers and the scrollbar are made of. Kept as it goes, so the
2229 /// tail spacer costs nothing however long the list is.
2230 pub fn total(&self) -> f32 {
2231 self.sum + (self.h.len() - self.n) as f32 * self.estimate()
2232 }
2233
2234 /// The row `y` (content coordinates) lands in: the last row whose top is
2235 /// at or above it, clamped to the list. The binary search that replaces
2236 /// `y / row_h`.
2237 pub fn row_at(&mut self, y: f32) -> usize {
2238 let rows = self.h.len();
2239 if rows == 0 || y <= 0.0 {
2240 self.last = 0;
2241 return 0;
2242 }
2243 // `offset_of` is non-decreasing, so what is wanted is the last row
2244 // whose top is at or below `y`. Row 0's top is 0, so it always
2245 // qualifies and the bracket below always closes.
2246 let mut lo = self.last.min(rows - 1);
2247 let mut hi;
2248 if self.offset_of(lo) > y {
2249 hi = lo;
2250 let mut step = 1usize;
2251 while lo > 0 {
2252 lo = lo.saturating_sub(step);
2253 if self.offset_of(lo) <= y {
2254 break;
2255 }
2256 hi = lo;
2257 step *= 2;
2258 }
2259 } else {
2260 hi = (lo + 1).min(rows);
2261 let mut step = 1usize;
2262 while hi < rows && self.offset_of(hi) <= y {
2263 lo = hi;
2264 hi = (hi + step).min(rows);
2265 step *= 2;
2266 }
2267 }
2268 while lo + 1 < hi {
2269 let mid = lo + (hi - lo) / 2;
2270 if self.offset_of(mid) <= y {
2271 lo = mid;
2272 } else {
2273 hi = mid;
2274 }
2275 }
2276 self.last = lo;
2277 lo
2278 }
2279}
2280
2281/// A vertically scrolling column of rows of *different* heights that builds
2282/// only the visible ones — [`uniform_list`] where no single stride
2283/// describes the list.
2284///
2285/// `measure(ui, i, width)` returns row `i`'s height at that content width,
2286/// and is called only for rows the frame is about to build that `heights`
2287/// has no number for; `ui.measure_text(.., Some(width))` is layout's own
2288/// answer for a text row, wrap and all, and shapes through the same cache
2289/// the row's draw will hit. What it returns is the height the row *gets*:
2290/// each row's node is fixed to it, so the arithmetic above and below can
2291/// never disagree with the layout, the way `uniform_list`'s stride cannot.
2292/// A row that would rather size itself has to say what that size is here.
2293///
2294/// `row(ui, i)` declares row `i` inside that node, exactly as
2295/// `uniform_list`'s does, and rows are opened with [`Ui::open_indexed`] at
2296/// their data index, so a row keeps its hover, focus, edit buffer and tweens
2297/// as the built range slides over it.
2298///
2299/// **What it does that the uniform one never has to:** every row not yet
2300/// measured stands at the mean of the ones that are, so measuring the rows
2301/// this frame builds changes the height of every row it does not — the ones
2302/// above the window included. Left alone that slides the content out from
2303/// under the pointer on the frame it learns anything. So the widget takes
2304/// the row the window starts in and how far into it, measures, and then puts
2305/// that pair back: `Core::set_scroll` from inside a view lands on the frame
2306/// being built (the positions pass reads the store after the view has run),
2307/// so the corrected frame is the only one ever seen. What does move is the
2308/// scrollbar, which is the honest thing to move — the list really did just
2309/// learn it is a different length.
2310///
2311/// Returns the container's key, for `set_scroll` — and "scroll to row `i`"
2312/// is `set_scroll(key, Vec2::new(0.0, heights.offset_of(i)))`, exact for a
2313/// measured row and converging over a frame or two for one that is not.
2314pub fn list(
2315 ui: &mut Ui<'_>,
2316 label: &str,
2317 spec: NodeSpec,
2318 heights: &mut RowHeights,
2319 mut measure: impl FnMut(&mut Ui<'_>, usize, f32) -> f32,
2320 mut row: impl FnMut(&mut Ui<'_>, usize),
2321) -> Key {
2322 let key = ui.child_key(label);
2323 let mut slice = heights.slice(ListReading::of(ui, key, spec.layout.padding));
2324 loop {
2325 let pending = slice.unmeasured(heights);
2326 if pending.is_empty() {
2327 break;
2328 }
2329 for i in pending {
2330 let h = measure(ui, i, slice.width());
2331 heights.set(i, h);
2332 }
2333 if !slice.reslice(heights) {
2334 break;
2335 }
2336 }
2337 let plan = slice.finish(heights);
2338 // A write from inside a view lands on the frame being built: the
2339 // positions pass reads the store after the view has run. So the frame
2340 // that learned the rows are a different size is drawn already
2341 // corrected, and the uncorrected one is never seen. A shift, not a
2342 // `set_scroll`: the correction moves the coordinates under the
2343 // content, so it is never eased on a container with a `transition`,
2344 // and mid-glide it moves the leg with it rather than ending the leg
2345 // where the content stands (RG18).
2346 if let Some((drawn, target)) = plan.shift {
2347 ui.shift_scroll(key, Vec2::new(0.0, drawn), Vec2::new(0.0, target));
2348 }
2349
2350 ui.with_keyed(label, spec.scroll_y().gap(0.0), |ui| {
2351 ui.row_count(heights.len() as u64);
2352 if plan.lead > 0.0 {
2353 ui.leaf_keyed("lead", spacer_spec(plan.lead));
2354 }
2355 for i in plan.range.clone() {
2356 ui.with_indexed(i as u64, row_spec(heights.get(i)), |ui| row(ui, i));
2357 }
2358 if plan.tail > 0.0 {
2359 ui.leaf_keyed("tail", spacer_spec(plan.tail));
2360 }
2361 });
2362
2363 // As `uniform_list`'s first frame.
2364 if plan.first_frame {
2365 ui.owe_frame("list first frame");
2366 }
2367 key
2368}
2369
2370/// What a variable-height list reads before it slices: the container's
2371/// last layout, where its scroll is going, the window, and the padding
2372/// its rows sit inside. [`list`] takes it from the frame
2373/// ([`Self::of`]); a binding builds it from the same readings its view
2374/// already has (`scrollGeometry`, `scrollOffset`, the viewport), so the
2375/// arithmetic after it is this module's in every language.
2376#[derive(Clone, Copy, Debug, Default)]
2377pub struct ListReading {
2378 /// `scroll_geometry` of the container, `None` before a layout has
2379 /// resolved it — the first frame.
2380 pub geometry: Option<crate::scroll::ScrollGeometry>,
2381 /// `scroll_offset(key).y`: the retained offset, which is where an
2382 /// eased leg is going when it differs from `geometry.offset`.
2383 pub scroll_y: f32,
2384 /// The window, logical px: what the first frame slices by.
2385 pub viewport: crate::geom::Size,
2386 /// The container's top padding and its horizontal padding together.
2387 pub pad_t: f32,
2388 pub pad_x: f32,
2389 /// Rows built past each end of the window; 2 unless a view says.
2390 pub overscan: usize,
2391}
2392
2393impl ListReading {
2394 /// The reading for the container `key`, with `pad` its padding, from
2395 /// the frame being built.
2396 pub fn of(ui: &Ui<'_>, key: Key, pad: crate::geom::Edges) -> Self {
2397 ListReading {
2398 geometry: ui.scroll_geometry(key),
2399 scroll_y: ui.scroll_offset(key).y,
2400 viewport: ui.viewport(),
2401 pad_t: pad.t,
2402 pad_x: pad.x(),
2403 overscan: 2,
2404 }
2405 }
2406}
2407
2408/// One frame's slicing of a variable-height list, between the reading and
2409/// the rows: which rows to measure, and — once they are — where the window
2410/// lands and what to build. Made by [`RowHeights::slice`]; see [`list`]
2411/// for the loop that drives it, which every binding's port repeats.
2412#[derive(Clone, Debug)]
2413pub struct ListSlice {
2414 range: std::ops::Range<usize>,
2415 /// The row the window starts in, and how far into it: the pair the
2416 /// correction puts back where it was.
2417 anchor: usize,
2418 into: f32,
2419 top: f32,
2420 /// What the passes move `top` away from. The correction is for a
2421 /// *measurement* moving the numbers — not for the clamp to zero, which
2422 /// on a list shorter than its box (offset 0, padding 6) makes `top +
2423 /// pad_t` differ from the offset every frame, and a correction every
2424 /// frame is a frame requested every frame.
2425 top_before: f32,
2426 /// Where an eased leg (F80) is going, when that is somewhere other
2427 /// than where the content is drawn: a second anchor, so the row under
2428 /// the target stays the target however the measurements move the rows
2429 /// between the two (RG18). The target, its row, and how far into it.
2430 target: Option<(f32, usize, f32)>,
2431 vh: f32,
2432 width: f32,
2433 overscan: usize,
2434 passes: usize,
2435 first_frame: bool,
2436}
2437
2438/// What a [`ListSlice`] comes to: the rows to build, the two spacers'
2439/// heights, and the scroll correction the frame needs (see [`list`]).
2440#[derive(Clone, Debug, PartialEq)]
2441pub struct ListPlan {
2442 pub range: std::ops::Range<usize>,
2443 pub lead: f32,
2444 pub tail: f32,
2445 /// `(drawn, target)` on y, for `Ui::shift_scroll`, when measuring moved
2446 /// the rows; `None` when nothing needs correcting.
2447 pub shift: Option<(f32, f32)>,
2448 /// Sliced by the window, not a layout: the frame after it has to run.
2449 pub first_frame: bool,
2450}
2451
2452/// Measuring changes the heights the range was sliced from, which can widen
2453/// it; four passes is far more than a screenful ever needs and bounds the
2454/// work whatever the measurements do.
2455const LIST_PASSES: usize = 4;
2456
2457impl RowHeights {
2458 /// Starts a frame's slicing from `reading`: the content width (a new one
2459 /// drops every height, since the rows rewrap), the anchors, and the
2460 /// first range.
2461 pub fn slice(&mut self, reading: ListReading) -> ListSlice {
2462 let mut target_y = None;
2463 let (offset_y, vh, cw, first_frame) = match reading.geometry {
2464 Some(g) => {
2465 let t = reading.scroll_y.clamp(0.0, g.max_offset.y);
2466 if (t - g.offset.y).abs() > 0.5 {
2467 target_y = Some(t);
2468 }
2469 (g.offset.y, g.rect.h, g.rect.w - reading.pad_x, false)
2470 }
2471 // Nothing laid out yet: a screenful of the viewport is a safe
2472 // over-build for one frame, and the width is its width.
2473 None => (
2474 reading.scroll_y,
2475 reading.viewport.h,
2476 reading.viewport.w - reading.pad_x,
2477 true,
2478 ),
2479 };
2480 // A resize rewraps every row, so the cache is void; the frame after
2481 // it measures a screenful again.
2482 self.set_width(cw);
2483 let top = (offset_y - reading.pad_t).max(0.0);
2484 let anchor = self.row_at(top);
2485 let into = top - self.offset_of(anchor);
2486 let target = target_y.map(|t| {
2487 let t = (t - reading.pad_t).max(0.0);
2488 let row = self.row_at(t);
2489 (t, row, t - self.offset_of(row))
2490 });
2491 let range = visible_range(self, top, vh, reading.overscan);
2492 ListSlice {
2493 range,
2494 anchor,
2495 into,
2496 top,
2497 top_before: top,
2498 target,
2499 vh,
2500 width: cw,
2501 overscan: reading.overscan,
2502 passes: 0,
2503 first_frame,
2504 }
2505 }
2506}
2507
2508impl ListSlice {
2509 /// The content width the rows are measured at.
2510 pub fn width(&self) -> f32 {
2511 self.width
2512 }
2513
2514 /// The rows of the current range nothing has measured: measure each,
2515 /// [`RowHeights::set`] it, then [`Self::reslice`]. Empty is done.
2516 pub fn unmeasured(&self, heights: &RowHeights) -> Vec<usize> {
2517 self.range
2518 .clone()
2519 .filter(|&i| heights.measured(i).is_none())
2520 .collect()
2521 }
2522
2523 /// After measuring: puts the anchor row back where it was and slices
2524 /// again. Measuring moved the numbers the slice was taken from — this
2525 /// row's own, the rows above it, and (through the mean) every row
2526 /// nobody has measured at all — so what is under the pointer would
2527 /// otherwise slide out from under it. True when the range moved and
2528 /// its new rows want measuring, within the pass budget.
2529 pub fn reslice(&mut self, heights: &mut RowHeights) -> bool {
2530 self.passes += 1;
2531 self.top = heights.offset_of(self.anchor) + self.into;
2532 let next = visible_range(heights, self.top, self.vh, self.overscan);
2533 if next == self.range {
2534 return false;
2535 }
2536 self.range = next;
2537 self.passes < LIST_PASSES
2538 }
2539
2540 /// The rows to build, the spacers, and the correction.
2541 pub fn finish(self, heights: &mut RowHeights) -> ListPlan {
2542 let drawn = self.top - self.top_before;
2543 let target = match self.target {
2544 Some((t, row, into)) => heights.offset_of(row) + into - t,
2545 None => drawn,
2546 };
2547 let lead = heights.offset_of(self.range.start);
2548 let tail = heights.total() - heights.offset_of(self.range.end);
2549 ListPlan {
2550 range: self.range,
2551 lead,
2552 tail,
2553 shift: (drawn.abs() > 0.01 || target.abs() > 0.01).then_some((drawn, target)),
2554 first_frame: self.first_frame,
2555 }
2556 }
2557}
2558
2559/// The rows crossing `[top, top + vh)` plus `overscan` on each side, by
2560/// prefix-sum search. The variable-height [`visible_rows`].
2561fn visible_range(
2562 heights: &mut RowHeights,
2563 top: f32,
2564 vh: f32,
2565 overscan: usize,
2566) -> std::ops::Range<usize> {
2567 let rows = heights.len();
2568 if rows == 0 {
2569 return 0..0;
2570 }
2571 let first = heights.row_at(top).saturating_sub(overscan);
2572 let last = (heights.row_at(top + vh.max(0.0)) + 1 + overscan).min(rows);
2573 first..last.max(first)
2574}