Skip to main content

kui_core/
widgets.rs

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