Skip to main content

egui_pop_api/
menus.rs

1//! Menus drawn from their declarations, with egui's own menus
2//! ([`egui::containers::menu::MenuButton`], `SubMenuButton`'s
3//! [`egui::containers::menu::SubMenu`], [`egui::Popup`]): egui's
4//! keyboard navigation and accessibility come with them.
5//!
6//! A command item shows the command's title, its first key binding (from
7//! the keymap, so a menu never shows a key that does not work) and a tick
8//! when its `checked` clause holds; it is greyed, with the reason, where
9//! the command does not apply. Clicking runs the command as the user, in
10//! the context the menu opened in.
11//!
12//! Every row starts with the **gutter** (`docs/icons.md`, section 5): a
13//! column of fixed width ([`Kit::menu_gutter`], scaled by the density)
14//! holding the command's icon ([`CommandSpec::icon`](egui_pop_model::commands::CommandSpec::icon), or `icon_on` while
15//! checked), the tick of a checked item without an icon, the dot of a
16//! chosen radio item, or the spinner of a running command; a checked
17//! command with an icon shows it framed (`menu-item-gutter`'s `selected`
18//! state), as Word does. Labels start after it whether a row has an icon
19//! or not, so they align; shortcuts keep a right-aligned column, before
20//! the submenu arrows' column. Labels, keys and notes are in egui's `Body`
21//! text style (as egui's own menus, not `Button`); a theme's
22//! `menu-item.key-font-size` draws the keys and notes smaller, and the ↗
23//! of an entry opening a link with them. The [`SETTING_ICONS`] setting turns the
24//! icons off (the gutter is then kept only in a menu with a check or radio
25//! item) or follows the platform. The gutter is decorative: AccessKit
26//! reads the title, and a check or radio item as checked or not.
27//!
28//! A list item (`MenuItem::list`) is filled by the list provider of its
29//! name (`Ctx::list_provider`), asked when the menu opens and never on
30//! every frame: the recent files, the profiles. Each entry it gives runs
31//! a command with its arguments; the `lists` debug collector shows what
32//! each provider gave last.
33//!
34//! - [`bar`] draws a menu as a menu bar (the shell draws `app.main`),
35//!   moving the menus that do not fit into a "…" menu;
36//! - [`show`] draws a menu's items inside an open menu or popup;
37//! - [`context_menu`] opens a declared menu on a widget's secondary click
38//!   (or Shift+F10 and the `Menu` key while it has the focus),
39//!   and [`context_menu_with`] with arguments of the moment (the clicked
40//!   row's path), merged into every item's command and seen by the `when`
41//!   clauses as `args.<key>`; not where a widget claimed the secondary
42//!   click for itself (`egui_pop_core::pointer::claim`);
43//! - [`popup_at`] opens a declared menu as a popup under a rectangle or
44//!   at a point (a logo, `Alt+Space`); egui-pop draws it until an item is
45//!   chosen, a click lands outside or Escape is pressed;
46//! - [`submenu`] adds a submenu item to a menu drawn by hand (a context
47//!   menu built in a closure), in the declared menus' look, opened by the
48//!   pointer resting on it or by the keyboard, closed one level by Escape.
49//!
50//! Opening a menu by [`popup_at`] or a context menu runs the
51//! [`STEP_OPEN`] step (ADR 0011): a plugin may veto it or change its
52//! arguments.
53//!
54//! ```
55//! use egui_pop_api::{AppHandle, menus};
56//! use egui_pop_model::ids::MenuId;
57//!
58//! const ROW: MenuId = MenuId::from_static("demo.row");
59//!
60//! fn row(ui: &mut egui::Ui, app: &AppHandle, path: &str) {
61//!     let r = ui.label("Right-click me");
62//!     menus::context_menu_with(&r, app, &ROW, serde_json::json!({ "path": path }));
63//! }
64//! ```
65
66use egui_pop_core::kit::{Component, Glyph, Kit, Part, State, Tone};
67use std::cell::RefCell;
68use std::collections::{BTreeMap, HashMap};
69use std::fmt;
70use std::rc::Rc;
71use std::sync::Arc;
72
73use egui::AtomExt as _;
74use egui::containers::menu::{MenuButton, MenuConfig, MenuState, SubMenu};
75use egui::{
76    Atom, Button, Color32, Context, Id, Pos2, Rect, Response, RichText, Shape, Stroke, Ui, vec2,
77};
78use egui_pop_core::icon::{Icon, IconRef};
79use egui_pop_core::state::Slot;
80use egui_pop_core::strings;
81
82/// What a context menu opened with (its `when` context and arguments,
83/// `None` when vetoed), per widget.
84const CONTEXT_MENU: Slot<Option<(WhenContext, Json)>> = Slot::new("api.menus.context");
85/// A dynamic list's items and the pass they were listed on, per menu
86/// and list.
87const LIST: Slot<(u64, Vec<ListItem>)> = Slot::new("api.menus.list");
88use egui_pop_core::theme::{ScopedTheme, Tokens};
89use egui_pop_model::ids::{CommandId, MenuId, OwnerId, SettingId, StepId};
90use egui_pop_model::menus::{Item, Shown, show_items};
91use egui_pop_model::when::{When, WhenContext};
92use serde::Serialize;
93use serde_json::{Map, Value as Json, json};
94
95use bus_contract::ListenOpts;
96use egui_pop_core::overlay::Closing;
97
98use crate::app::{AppHandle, Request};
99use crate::bus::{PopupClose, REGISTRY, Reason, WindowKind, WindowRequest};
100use crate::steps::Outcome;
101use crate::strings as txt;
102
103/// How deep submenus may nest before the rest is cut (a menu naming
104/// itself as a submenu).
105const MAX_DEPTH: u32 = 8;
106
107/// A menu opens as a popup or a context menu: `{"menu": id, "args":
108/// arguments, "how": "popup" | "context"}`. A veto keeps it closed, a
109/// redirect changes its arguments.
110pub const STEP_OPEN: StepId = StepId::from_static("menu.open");
111
112/// The setting: whether menus show the commands' icons in their gutter,
113/// `on` (the default, Word's look), `off`, or `platform` ([`MenuIcons`]).
114pub const SETTING_ICONS: SettingId = SettingId::from_static("menus.icons");
115
116/// What the [`SETTING_ICONS`] setting asks for.
117#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
118pub enum MenuIcons {
119    /// The icons the commands declare, in a gutter every row keeps.
120    #[default]
121    On,
122    /// No icons; ticks and radio dots keep the gutter, reserved only in a
123    /// menu that holds a check or radio item.
124    Off,
125    /// `on` on Windows, macOS and KDE Plasma (following its
126    /// `ShowIconsInMenuItems`), `off` on GNOME.
127    Platform,
128}
129
130impl MenuIcons {
131    /// The setting's choices, in order.
132    pub const CHOICES: [&'static str; 3] = ["on", "off", "platform"];
133
134    pub fn as_str(self) -> &'static str {
135        match self {
136            MenuIcons::On => "on",
137            MenuIcons::Off => "off",
138            MenuIcons::Platform => "platform",
139        }
140    }
141
142    pub fn parse(s: &str) -> Option<MenuIcons> {
143        [MenuIcons::On, MenuIcons::Off, MenuIcons::Platform]
144            .into_iter()
145            .find(|m| m.as_str() == s)
146    }
147
148    /// Whether menus show icons: `platform` asks the desktop (read once).
149    pub fn shows(self) -> bool {
150        match self {
151            MenuIcons::On => true,
152            MenuIcons::Off => false,
153            MenuIcons::Platform => {
154                static PLATFORM: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
155                *PLATFORM.get_or_init(|| {
156                    let desktop = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default();
157                    platform_shows_icons(&desktop, || read_config("kdeglobals"))
158                })
159            }
160        }
161    }
162}
163
164/// Whether the platform shows icons in menus, from the desktop
165/// (`XDG_CURRENT_DESKTOP`) and KDE's `kdeglobals`: not on GNOME; on KDE
166/// Plasma as its `ShowIconsInMenuItems` (group `KDE`) says, yes when it
167/// does not say; yes elsewhere (Windows, macOS, other desktops).
168pub fn platform_shows_icons(desktop: &str, kdeglobals: impl FnOnce() -> Option<String>) -> bool {
169    if cfg!(any(windows, target_os = "macos")) {
170        return true;
171    }
172    let desktop = desktop.to_uppercase();
173    if desktop.split(':').any(|d| d == "KDE") {
174        return kdeglobals().and_then(|text| kde_show_icons(&text)) != Some(false);
175    }
176    !desktop.split(':').any(|d| d == "GNOME")
177}
178
179/// `ShowIconsInMenuItems` in the `[KDE]` group of a `kdeglobals` text.
180fn kde_show_icons(text: &str) -> Option<bool> {
181    let mut group = "";
182    let mut found = None;
183    for line in text.lines().map(str::trim) {
184        if let Some(g) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
185            group = g;
186        } else if group == "KDE"
187            && let Some((key, value)) = line.split_once('=')
188            && key.trim() == "ShowIconsInMenuItems"
189        {
190            found = match value.trim() {
191                "true" => Some(true),
192                "false" => Some(false),
193                _ => found,
194            };
195        }
196    }
197    found
198}
199
200/// A file of the user's configuration directory, as text.
201fn read_config(name: &str) -> Option<String> {
202    let config = std::env::var("XDG_CONFIG_HOME")
203        .ok()
204        .filter(|c| !c.is_empty())
205        .map(std::path::PathBuf::from)
206        .or_else(|| {
207            std::env::var("HOME")
208                .ok()
209                .map(|h| std::path::Path::new(&h).join(".config"))
210        })?;
211    std::fs::read_to_string(config.join(name)).ok()
212}
213
214/// What the [`SETTING_ICONS`] setting says now.
215pub fn menu_icons(app: &AppHandle) -> MenuIcons {
216    egui_pop_core::lock(&app.store())
217        .get(&format!("settings/{SETTING_ICONS}"))
218        .and_then(|e| e.value.as_choice().and_then(MenuIcons::parse))
219        .unwrap_or_default()
220}
221
222/// An entry a list provider gives when its menu opens.
223#[derive(Clone, Debug, PartialEq, Serialize)]
224pub struct ListItem {
225    pub label: String,
226    /// Its icon; agents read its name (the `lists` collector).
227    #[serde(skip_serializing_if = "Option::is_none")]
228    pub icon: Option<Icon>,
229    /// What it runs, with its arguments.
230    pub command: CommandId,
231    pub args: Json,
232    /// Shown ticked (the profile in use).
233    pub checked: bool,
234    /// Greyed when false (with no reason: the label says it).
235    pub enabled: bool,
236}
237
238impl ListItem {
239    pub fn new(label: &str, command: CommandId, args: Json) -> Self {
240        Self {
241            label: label.into(),
242            icon: None,
243            command,
244            args,
245            checked: false,
246            enabled: true,
247        }
248    }
249
250    /// Its icon, by value or by name (`"history"`, `"phosphor:file-image"`,
251    /// `"my-plugin:album"`). A name that does not resolve is reported (the
252    /// `icons` collector) and the entry shows no icon.
253    pub fn icon(mut self, icon: impl Into<egui_pop_core::icon::IconRef>) -> Self {
254        self.icon = icon.into().resolve("menu list item");
255        self
256    }
257
258    pub fn checked(mut self, on: bool) -> Self {
259        self.checked = on;
260        self
261    }
262
263    /// Greyed: a placeholder ("No recent file").
264    pub fn disabled(mut self) -> Self {
265        self.enabled = false;
266        self
267    }
268}
269
270/// A list provider: the entries of a list, in the context the menu opens
271/// in.
272pub type ListFn = Rc<dyn Fn(&AppHandle, &WhenContext) -> Vec<ListItem>>;
273
274/// A registered list provider.
275#[derive(Clone)]
276pub(crate) struct Provider {
277    pub name: String,
278    pub f: ListFn,
279}
280
281impl fmt::Debug for Provider {
282    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
283        write!(f, "list provider {}", self.name)
284    }
285}
286
287/// What a list provider gave last, as the `lists` collector shows it.
288#[derive(Clone, Debug, PartialEq, Serialize)]
289pub struct ListTrace {
290    pub name: String,
291    pub owner: OwnerId,
292    pub items: Vec<ListItem>,
293}
294
295/// Draws a menu as a bar of menu buttons: each item a submenu opening a
296/// popup. The menus that do not fit go into a "…" menu (see
297/// [`bar_within`]).
298pub fn bar(ui: &mut Ui, app: &AppHandle, menu: &MenuId) {
299    bar_within(ui, app, menu, 0.0);
300}
301
302/// Draws a menu as a bar of menu buttons, keeping `reserve` points free
303/// at its end (what the bar shows after its menus).
304///
305/// The menus that fit stay in the bar, from the start; the others become
306/// submenus of a "…" entry ([`Icon::More`]), with their titles and their
307/// `when` clauses. When no menu fits besides it, the whole menu is one
308/// entry ([`Icon::Menu`]). Each label is measured once, again only when
309/// the language, the kit or the scale changes.
310///
311/// Each menu has an access key: the first letter of its label not taken
312/// by a menu before it. Alt and that letter open the menu, in the bar or
313/// inside "…", and the letter is underlined while Alt is held; F10 opens
314/// the first menu, as on Windows and in Qt and GTK. A key binding on the
315/// same keys wins. The arrows then go through the menu. Where each menu went,
316/// and its access key, is [`bar_layout`] (the `menu_bar` debug
317/// collector).
318pub fn bar_within(ui: &mut Ui, app: &AppHandle, menu: &MenuId, reserve: f32) {
319    let cx = app.when_context();
320    let ctx = ui.ctx().clone();
321    let shown: Vec<(MenuId, String, bool)> = show_items(&app.menu(menu), &cx)
322        .into_iter()
323        .filter_map(|shown| match shown {
324            Shown::Item {
325                item: Item::Submenu { menu: sub, label },
326                enabled,
327                ..
328            } => Some((sub, label, enabled)),
329            _ => None,
330        })
331        .collect();
332    let font = egui::TextStyle::Button.resolve(ui.style());
333    let caches = app.local::<BarCaches>();
334    let mut caches = caches.0.borrow_mut();
335    let cache = caches.entry(menu.clone()).or_default();
336    cache.prepare(&ctx, font, &shown);
337    let pad = ui.spacing().button_padding.x * 2.0;
338    let gap = ui.spacing().item_spacing.x;
339    let side = Tokens::of(&ctx).size.icon_inline;
340    let widths: Vec<f32> = cache.menus.iter().map(|m| m.width + pad).collect();
341    let available = ui.available_width();
342    let kept = fit(&widths, gap, side + pad, available - reserve);
343    cache.fitted = Some(Fitted {
344        widths,
345        gap,
346        more: side + pad,
347        available,
348        kept,
349    });
350    // Alt and an access key: the menu it opens, if enabled. F10: the first.
351    let pressed = ui.input_mut(|i| {
352        let by_letter = cache.menus.iter().position(|m| {
353            m.enabled
354                && m.key
355                    .and_then(|k| egui::Key::from_name(&k.to_ascii_uppercase().to_string()))
356                    .is_some_and(|k| i.consume_key(egui::Modifiers::ALT, k))
357        });
358        by_letter.or_else(|| {
359            let first = cache.menus.iter().position(|m| m.enabled)?;
360            // F10 alone: egui matches keys ignoring Shift, and Shift+F10 is
361            // the context menu key.
362            (!i.modifiers.any() && i.consume_key(egui::Modifiers::NONE, egui::Key::F10))
363                .then_some(first)
364        })
365    });
366    let alt = ui.input(|i| i.modifiers.alt);
367    for (i, m) in cache.menus[..kept].iter().enumerate() {
368        ui.add_enabled_ui(m.enabled, |ui| {
369            let id = ui.next_auto_id();
370            if pressed == Some(i) {
371                egui::Popup::open_id(&ctx, id.with("popup"));
372            }
373            let label = access_label(ui, &m.label, m.key.filter(|_| alt));
374            let (r, _) =
375                MenuButton::new(label).ui(ui, |ui| items(ui, app, &m.menu, &cx, &Json::Null, 0));
376            follow_menu(&ctx, id.with("popup"), &m.label);
377            access_key(&ctx, r.id, m.key);
378        });
379    }
380    let hidden = &cache.menus[kept..];
381    if !hidden.is_empty() {
382        let (icon, name) = if kept == 0 {
383            (Icon::Menu, cache.main_name.clone())
384        } else {
385            (Icon::More, cache.more_name.clone())
386        };
387        let open = pressed.and_then(|i| i.checked_sub(kept));
388        let id = ui.next_auto_id();
389        if open.is_some() {
390            egui::Popup::open_id(&ctx, id.with("popup"));
391        }
392        let mark = Id::unique(("egui_pop_menu_more", menu.as_str()));
393        let button = Button::new(Atom::custom(egui::IdSalt::new(mark), vec2(side, side)));
394        let (r, _) = MenuButton::from_button(button).ui(ui, |ui| {
395            for (i, m) in hidden.iter().enumerate() {
396                ui.add_enabled_ui(m.enabled, |ui| {
397                    let id = ui.next_auto_id();
398                    if open == Some(i) {
399                        // Opened by its access key: its submenu shows at once.
400                        let sub = SubMenu::id_from_widget_id(id);
401                        MenuState::mark_shown(ui.ctx(), sub);
402                        MenuState::from_ui(ui, |state, _| state.open_item = Some(sub));
403                    }
404                    declared_submenu(ui, app, &m.menu, &m.label, &cx, &Json::Null, 0, &TITLES);
405                    access_key(ui.ctx(), id, m.key);
406                });
407            }
408        });
409        follow_menu(&ctx, id.with("popup"), &name);
410        let rect = Rect::from_center_size(r.rect.center(), vec2(side, side));
411        icon.paint(ui.painter(), rect, ui.style().interact(&r).text_color());
412        r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &name));
413        r.on_hover_text(name);
414    }
415    let layout = BarLayout {
416        bar: cache.menus[..kept].iter().map(|m| m.menu.clone()).collect(),
417        overflow: hidden.iter().map(|m| m.menu.clone()).collect(),
418        collapsed: kept == 0 && !hidden.is_empty(),
419        keys: cache
420            .menus
421            .iter()
422            .filter_map(|m| Some((m.menu.to_string(), m.key?.to_string())))
423            .collect(),
424    };
425    drop(caches);
426    app.local::<BarLayouts>()
427        .0
428        .borrow_mut()
429        .insert(menu.to_string(), layout);
430}
431
432/// The command items of a menu that apply now, as [`bar_end`] draws
433/// them.
434fn end_items(app: &AppHandle, menu: &MenuId) -> Vec<(CommandId, Json, Option<String>, bool, bool)> {
435    show_items(&app.menu(menu), &app.when_context())
436        .into_iter()
437        .filter_map(|s| match s {
438            Shown::Item {
439                item: Item::Command { id, args, label },
440                enabled: true,
441                checked,
442                checkable,
443                ..
444            } => Some((id, args, label, checked, checkable)),
445            _ => None,
446        })
447        .collect()
448}
449
450/// Whether [`bar_end`] would draw something for this menu now.
451pub fn has_end_items(app: &AppHandle, menu: &MenuId) -> bool {
452    !end_items(app, menu).is_empty()
453}
454
455/// Draws a menu's command items as icon buttons at the end of a bar
456/// (the shell's menu bar draws [`MENU_BAR_END`](crate::app::MENU_BAR_END)
457/// there), in the menu's order: each the command's icon (its `icon_on`
458/// while its `checked` clause holds, the button then drawn selected),
459/// its title and first key binding in the tooltip. An item whose command
460/// does not apply (its `when`) is left out, not greyed: a bar's end shows
461/// what can be done. A command without an icon shows its title. Laid
462/// out from the end: call it in a right-to-left `Ui`. Returns the width
463/// it took.
464pub fn bar_end(ui: &mut Ui, app: &AppHandle, menu: &MenuId) -> f32 {
465    let ctx = ui.ctx().clone();
466    let side = Tokens::of(&ctx).size.icon_inline;
467    let items = end_items(app, menu);
468    let r = ui.scope(|ui| {
469        // From the end: the last item first, so they read in order.
470        for (id, args, label, checked, checkable) in items.iter().rev() {
471            let spec = app.command(id);
472            // The application's live text (`pop.command.label`) first.
473            let live = app.command_text(id);
474            let name = live.title.unwrap_or_else(|| {
475                let english = label
476                    .clone()
477                    .or_else(|| spec.as_ref().map(|c| c.title.clone()))
478                    .unwrap_or_else(|| id.to_string());
479                strings::command_title(&ctx, id.as_str(), &english)
480            });
481            let action = live.tooltip.unwrap_or_else(|| name.clone());
482            let tip = match app.keys_for(id).first() {
483                Some(keys) => strings::tr_args(
484                    &ctx,
485                    &txt::TOOLBAR_WITH_KEY,
486                    &[("action", &action), ("keys", keys)],
487                ),
488                None => action,
489            };
490            let icon = spec
491                .as_ref()
492                .and_then(|c| c.icon_for(*checked))
493                .and_then(|n| Icon::by_name(crate::layout_controls::command_icon(app, id, n)));
494            let r = match icon {
495                Some(icon) => {
496                    let mark = Id::unique(("egui_pop_menu_bar_end", id.as_str()));
497                    let button =
498                        Button::new(Atom::custom(egui::IdSalt::new(mark), vec2(side, side)))
499                            .selected(*checked);
500                    let r = ui.add(button);
501                    let rect = Rect::from_center_size(r.rect.center(), vec2(side, side));
502                    icon.paint(ui.painter(), rect, ui.style().interact(&r).text_color());
503                    egui_pop_core::icon::registry::record(&ctx, "menu bar", &name, icon.name());
504                    r
505                }
506                None => ui.add(Button::new(name.as_str()).selected(*checked)),
507            };
508            if *id == crate::devtools::inspect::CMD_INSPECT {
509                // Pressed while inspecting, it leaves the mode rather
510                // than being picked.
511                egui_pop_core::inspect::pass_through(&ctx, r.rect);
512            }
513            let enabled = r.enabled();
514            if *checkable {
515                r.widget_info(|| {
516                    egui::WidgetInfo::selected(egui::Role::Button, enabled, *checked, &name)
517                });
518            } else {
519                r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, &name));
520            }
521            if r.on_hover_text(tip).clicked() {
522                app.run(id.clone(), args.clone());
523            }
524        }
525    });
526    r.response.rect.width()
527}
528
529/// Where a menu bar drew its menus last.
530#[derive(Clone, Debug, Default, PartialEq, Serialize)]
531pub struct BarLayout {
532    /// The menus in the bar, in order.
533    pub bar: Vec<MenuId>,
534    /// The menus inside "…" (or the single entry), in order.
535    pub overflow: Vec<MenuId>,
536    /// No menu fit besides "…": the whole menu is one entry.
537    pub collapsed: bool,
538    /// Each menu's access key (Alt and the letter), by menu id.
539    pub keys: BTreeMap<String, String>,
540}
541
542/// Where a menu drawn as a bar ([`bar`], the shell's `app.main`) put its
543/// menus last, if it was drawn.
544pub fn bar_layout(app: &AppHandle, menu: &MenuId) -> Option<BarLayout> {
545    app.local::<BarLayouts>()
546        .0
547        .borrow()
548        .get(menu.as_str())
549        .cloned()
550}
551
552/// Every menu bar's last layout, by menu id (the `menu_bar` collector).
553pub(crate) fn bar_layouts(app: &AppHandle) -> BTreeMap<String, BarLayout> {
554    app.local::<BarLayouts>().0.borrow().clone()
555}
556
557#[derive(Default)]
558struct BarLayouts(RefCell<BTreeMap<String, BarLayout>>);
559
560#[derive(Default)]
561struct BarCaches(RefCell<HashMap<MenuId, BarCache>>);
562
563/// A menu bar's menus, translated and measured: laid out again only when
564/// their labels, the kit, the scale or the strings provider change.
565#[derive(Default)]
566struct BarCache {
567    /// The kit the labels were measured for, kept: compared by address,
568    /// which a kit dropped could otherwise lend to the next one.
569    kit: Option<Arc<Kit>>,
570    /// The pixels per point, the strings provider and the font the labels
571    /// were measured for.
572    key: Option<(u32, Option<usize>, egui::FontId)>,
573    menus: Vec<BarMenu>,
574    /// The names of "…" and of the single entry.
575    more_name: String,
576    main_name: String,
577    /// The last layout's measures.
578    fitted: Option<Fitted>,
579}
580
581/// What a bar's last layout was made from.
582struct Fitted {
583    widths: Vec<f32>,
584    gap: f32,
585    more: f32,
586    available: f32,
587    kept: usize,
588}
589
590struct BarMenu {
591    menu: MenuId,
592    /// The label as declared: translated again only when it changes.
593    english: String,
594    label: String,
595    enabled: bool,
596    /// The label's width, without the button's padding.
597    width: f32,
598    key: Option<char>,
599}
600
601impl BarCache {
602    fn prepare(&mut self, ctx: &Context, font: egui::FontId, shown: &[(MenuId, String, bool)]) {
603        let kit = Kit::of(ctx);
604        let key = (
605            ctx.pixels_per_point().to_bits(),
606            strings::provider_id(ctx),
607            font.clone(),
608        );
609        let same = self.key.as_ref() == Some(&key)
610            && self.kit.as_ref().is_some_and(|k| Arc::ptr_eq(k, &kit))
611            && self.menus.len() == shown.len()
612            && self
613                .menus
614                .iter()
615                .zip(shown)
616                .all(|(m, (id, english, _))| m.menu == *id && m.english == *english);
617        if same {
618            for (m, (_, _, enabled)) in self.menus.iter_mut().zip(shown) {
619                m.enabled = *enabled;
620            }
621            return;
622        }
623        self.key = Some(key);
624        self.kit = Some(kit);
625        // Asked with the labels, so that they all come in the same pass.
626        self.more_name = strings::tr(ctx, &txt::MENU_MORE);
627        self.main_name = strings::tr(ctx, &txt::MENU_MAIN);
628        let mut taken = Vec::new();
629        self.menus = shown
630            .iter()
631            .map(|(menu, english, enabled)| {
632                let label = strings::menu_label(ctx, menu.as_str(), english);
633                let width = ctx
634                    .fonts_mut(|f| {
635                        f.layout_no_wrap(label.clone(), font.clone(), Color32::PLACEHOLDER)
636                    })
637                    .size()
638                    .x;
639                let key = access_letter(&label, &taken);
640                taken.extend(key);
641                BarMenu {
642                    menu: menu.clone(),
643                    english: english.clone(),
644                    label,
645                    enabled: *enabled,
646                    width,
647                    key,
648                }
649            })
650            .collect();
651    }
652}
653
654/// Whether a bar drawn last pass would keep another number of menus
655/// with `reserve` points kept free at its end.
656pub(crate) fn refit_needed(app: &AppHandle, menu: &MenuId, reserve: f32) -> bool {
657    let caches = app.local::<BarCaches>();
658    let caches = caches.0.borrow();
659    caches
660        .get(menu)
661        .and_then(|c| c.fitted.as_ref())
662        .is_some_and(|f| fit(&f.widths, f.gap, f.more, f.available - reserve) != f.kept)
663}
664
665/// A menu's label with its access letter underlined, as Windows and Qt show
666/// it while Alt is held; the label alone without a letter.
667fn access_label(ui: &Ui, label: &str, key: Option<char>) -> egui::WidgetText {
668    // The letter is the first of its kind in the label (`access_letter`).
669    let at = key.and_then(|k| {
670        label
671            .char_indices()
672            .find(|(_, c)| c.to_lowercase().eq(k.to_lowercase()))
673            .map(|(i, c)| (i, i + c.len_utf8()))
674    });
675    let Some((from, to)) = at else {
676        return label.into();
677    };
678    let mut job = egui::text::LayoutJob::default();
679    let font = egui::FontSelection::Style(egui::TextStyle::Button);
680    for (text, underline) in [
681        (&label[..from], false),
682        (&label[from..to], true),
683        (&label[to..], false),
684    ] {
685        let text = RichText::new(text);
686        let text = if underline { text.underline() } else { text };
687        text.append_to(&mut job, ui.style(), font.clone(), egui::Align::Center);
688    }
689    job.into()
690}
691
692/// A label's access key: its first letter or digit not taken, lower case.
693fn access_letter(label: &str, taken: &[char]) -> Option<char> {
694    label
695        .chars()
696        .filter(char::is_ascii_alphanumeric)
697        .map(|c| c.to_ascii_lowercase())
698        .find(|c| !taken.contains(c))
699}
700
701/// Gives a widget its access key in the accessibility tree.
702fn access_key(ctx: &Context, id: Id, key: Option<char>) {
703    if let Some(k) = key {
704        ctx.accesskit_node_builder(id, |node| node.set_access_key(k.to_string()));
705    }
706}
707
708/// How many menus of these widths stay in a bar of `room` points, items
709/// `gap` apart, the rest going into a "…" entry `more` wide: all of them
710/// when they fit, 0 when none fits besides "…".
711fn fit(widths: &[f32], gap: f32, more: f32, room: f32) -> usize {
712    let all: f32 = widths.iter().sum::<f32>() + gap * widths.len().saturating_sub(1) as f32;
713    if all <= room {
714        return widths.len();
715    }
716    let mut used = more;
717    widths
718        .iter()
719        .take_while(|w| {
720            used += *w + gap;
721            used <= room
722        })
723        .count()
724}
725
726/// Draws a menu's items in the current `Ui` (an open menu or popup), in
727/// the current context.
728pub fn show(ui: &mut Ui, app: &AppHandle, menu: &MenuId) {
729    let cx = app.when_context();
730    show_in(ui, app, menu, &cx);
731}
732
733/// Draws a menu's items, evaluated in a given context.
734pub fn show_in(ui: &mut Ui, app: &AppHandle, menu: &MenuId, cx: &WhenContext) {
735    show_with(ui, app, menu, cx, &Json::Null);
736}
737
738/// Draws a menu's items in the current context, with arguments merged
739/// into every command an item runs and seen by `when` clauses as
740/// `args.<key>` (a menu `egui_stack` opens: a docked tab's).
741pub(crate) fn show_args(ui: &mut Ui, app: &AppHandle, menu: &MenuId, args: &Json) {
742    show_with(ui, app, menu, &with_args(&app.when_context(), args), args);
743}
744
745/// Draws a menu's items in a context, with arguments merged into every
746/// command an item runs.
747fn show_with(ui: &mut Ui, app: &AppHandle, menu: &MenuId, cx: &WhenContext, args: &Json) {
748    ui.scope(|ui| {
749        egui::containers::menu::menu_style(ui.style_mut());
750        ui.with_layout(egui::Layout::top_down_justified(egui::Align::Min), |ui| {
751            items(ui, app, menu, cx, args, 0);
752        });
753    });
754}
755
756/// A menu bar's menu (egui's popup `id`) on the overlays' watch: on the
757/// bus, opened and closed.
758fn follow_menu(ctx: &Context, id: Id, label: &str) {
759    let open = egui::Popup::is_id_open(ctx, id);
760    egui_pop_core::overlay::follow_popup(ctx, id, label, open, None);
761}
762
763/// Opens a declared menu on the widget's secondary click (or a long
764/// touch). Its items are evaluated in the context of the moment it
765/// opened, and their commands run in it. It does not open where a widget
766/// inside claimed the secondary click (`egui_pop_core::pointer::claim`).
767pub fn context_menu(response: &Response, app: &AppHandle, menu: &MenuId) {
768    context_menu_with(response, app, menu, Json::Null);
769}
770
771/// As [`context_menu`], with arguments of this call (the clicked row's
772/// path): merged into every item's command arguments, and seen by `when`
773/// clauses as `args.<key>`.
774pub fn context_menu_with(response: &Response, app: &AppHandle, menu: &MenuId, args: Json) {
775    let by_key =
776        response.has_focus() && egui_pop_core::pointer::claim::menu_key(&response.ctx, true);
777    context_menu_opened(response, app, menu, args, by_key);
778}
779
780/// As [`context_menu_with`], `by_key` saying that the keyboard opens it now
781/// (Shift+F10 or the `Menu` key, read with
782/// [`claim::menu_key`](egui_pop_core::pointer::claim::menu_key)): for a row of
783/// a widget that keeps the focus itself, a tree's cursor row.
784pub fn context_menu_opened(
785    response: &Response,
786    app: &AppHandle,
787    menu: &MenuId,
788    args: Json,
789    by_key: bool,
790) {
791    let key = CONTEXT_MENU.keyed(response.id);
792    if by_key || egui_pop_core::pointer::claim::opens_context_menu(response) {
793        let opened = open_step(app, menu, args, "context");
794        let state = opened.map(|args| (with_args(&app.when_context(), &args), args));
795        key.set(&response.ctx, state);
796    }
797    egui_pop_core::pointer::claim::context_menu_opened(response, by_key, |ui| {
798        let state = key
799            .get(ui.ctx())
800            .unwrap_or_else(|| Some((app.when_context(), Json::Null)));
801        match state {
802            Some((cx, args)) => items(ui, app, menu, &cx, &args, 0),
803            // Vetoed: it closes at once.
804            None => ui.close(),
805        }
806    });
807}
808
809/// A menu open as a popup.
810#[derive(Clone, Debug)]
811pub(crate) struct Popup {
812    pub menu: MenuId,
813    pub under: Rect,
814    pub args: Json,
815    pub context: WhenContext,
816    /// The scoped theme it was opened in (a theme editor's preview): it
817    /// is drawn in it, though drawn later, out of the scope.
818    pub scope: Option<ScopedTheme>,
819    /// The window it opens in: the active one when it opened.
820    pub window: egui::ViewportId,
821}
822
823/// Where a popup menu opens: under a rectangle (a button, a logo), or at
824/// a point.
825#[derive(Clone, Copy, Debug, PartialEq)]
826pub struct At(pub Rect);
827
828impl From<Rect> for At {
829    fn from(r: Rect) -> Self {
830        At(r)
831    }
832}
833
834impl From<Pos2> for At {
835    fn from(p: Pos2) -> Self {
836        At(Rect::from_min_size(p, egui::Vec2::ZERO))
837    }
838}
839
840/// The popup's egui id.
841pub(crate) fn popup_id() -> Id {
842    Id::unique("egui_pop.menu.popup")
843}
844
845/// Opens a declared menu as a popup under a rectangle or at a point,
846/// evaluated in the context of now; egui-pop draws it from the next
847/// frame until an item is chosen, a click lands outside or Escape is
848/// pressed. One popup at a time: another replaces it. It opens in the
849/// window the user works in ([`AppHandle::active_window`]: a detached
850/// panel's window when it was opened from there), the rectangle in that
851/// window's points, and goes to the main window if that window closes.
852/// Opened while a [`ScopedTheme`] draws (a theme editor's preview), it
853/// is drawn in that theme. Returns whether it opened (a hook on
854/// [`STEP_OPEN`] may veto it).
855pub fn popup_at(app: &AppHandle, menu: &MenuId, at: impl Into<At>) -> bool {
856    popup_at_with(app, menu, at, Json::Null)
857}
858
859/// As [`popup_at`], with arguments merged into the items' commands.
860pub fn popup_at_with(app: &AppHandle, menu: &MenuId, at: impl Into<At>, args: Json) -> bool {
861    let Some(args) = open_step(app, menu, args, "popup") else {
862        return false;
863    };
864    // One at a time: the one open closes first.
865    end_popup(app, Reason::Command, "replaced");
866    let popup = Popup {
867        menu: menu.clone(),
868        under: at.into().0,
869        context: with_args(&app.when_context(), &args),
870        args,
871        scope: ScopedTheme::current(&app.egui()),
872        window: app.active_window(),
873    };
874    let req = popup_request(app, &popup, Reason::Command);
875    app.set_popup(Some(popup));
876    if !app.request_popup_open(req) {
877        app.set_popup(None);
878        return false;
879    }
880    app.egui().request_repaint();
881    true
882}
883
884/// The popup menu's owner on the bus ([`POPUP_LISTENER`]).
885pub const POPUP_OWNER: &str = "egui_pop.menus";
886/// The start of the popup menu's popup id: `menu@<window>`.
887pub const POPUP_PREFIX: &str = "menu@";
888/// The popup menu's listener on `pop.popup.close`: closed by anyone (Escape,
889/// an item chosen, its window closing under it), it is no longer open,
890/// in that call.
891pub const POPUP_LISTENER: &str = "pop.menus.popup";
892
893/// The popup menu's request, in the window it shows in.
894fn popup_request(app: &AppHandle, popup: &Popup, reason: Reason) -> WindowRequest {
895    let parent = app.registry_window_of(app.still_open(popup.window));
896    WindowRequest::new(
897        format!("{POPUP_PREFIX}{parent}"),
898        WindowKind::Popup,
899        POPUP_OWNER,
900        reason,
901    )
902    .parent(parent)
903}
904
905/// Closes the popup menu open, by its `pop.popup.close`.
906fn end_popup(app: &AppHandle, reason: Reason, how: &str) {
907    let Some(p) = app.popup() else { return };
908    if !app.request_popup_close(popup_request(app, &p, reason).how(how)) {
909        app.set_popup(None);
910    }
911}
912
913/// Registers [`POPUP_LISTENER`].
914pub(crate) fn listen_popup(kernel: &dyn bus_contract::Bus) {
915    let l = kernel.listen::<PopupClose>(
916        POPUP_LISTENER,
917        ListenOpts::new().owner(POPUP_OWNER).before(REGISTRY),
918        |req, did| {
919            if !req.window.starts_with(POPUP_PREFIX) {
920                return Ok(());
921            }
922            let Some(app) = crate::bus::asking() else {
923                return Ok(());
924            };
925            if app.popup().is_some() {
926                app.set_popup(None);
927                did.push(format!("{POPUP_LISTENER}: closed"));
928            }
929            Ok(())
930        },
931    );
932    debug_assert!(l.is_ok(), "{l:?}");
933}
934
935/// The menu open as a popup, if one is.
936pub fn popup_open(app: &AppHandle) -> Option<MenuId> {
937    app.popup().map(|p| p.menu)
938}
939
940/// The window the popup menu shows in, if one is open: the one it was
941/// opened in, or the main window once that one is closed.
942pub fn popup_window(app: &AppHandle) -> Option<egui::ViewportId> {
943    app.popup().map(|p| app.still_open(p.window))
944}
945
946/// Closes the popup menu, if one is open (its `pop.popup.close`).
947pub fn close_popup(app: &AppHandle) {
948    end_popup(app, Reason::Command, "owner");
949}
950
951/// Draws the popup menu while it is open, in the window it belongs to
952/// (the shell calls it in each window's pass).
953pub(crate) fn draw_popup(ctx: &Context, app: &AppHandle) {
954    let Some(p) = app.popup() else { return };
955    if app.still_open(p.window) != ctx.viewport_id() {
956        return;
957    }
958    let draw = || {
959        let mut open = true;
960        egui::Popup::new(
961            popup_id(),
962            ctx.clone(),
963            p.under,
964            egui::LayerId::background(),
965        )
966        .kind(egui::PopupKind::Menu)
967        .open_bool(&mut open)
968        .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
969        .show(|ui| {
970            // The kit's least width, else egui-pop's 200 points.
971            let least = Kit::of(ui.ctx()).menu_item.data.width;
972            ui.set_min_width(if least > 0.0 { least } else { 200.0 });
973            show_with(ui, app, &p.menu, &p.context, &p.args);
974        });
975        open
976    };
977    let open = match &p.scope {
978        Some(scope) => scope.within(ctx, draw),
979        None => draw(),
980    };
981    if !open {
982        let how = egui_pop_core::overlay::closing_seen(ctx, popup_id());
983        let reason = match how {
984            Closing::Escape | Closing::Outside | Closing::Chosen => Reason::User,
985            _ => Reason::Command,
986        };
987        end_popup(app, reason, how.as_str());
988    }
989}
990
991/// Runs the opening step; the arguments to open with, or `None` when a
992/// hook vetoed it.
993fn open_step(app: &AppHandle, menu: &MenuId, args: Json, how: &str) -> Option<Json> {
994    let out = app.step(
995        &STEP_OPEN,
996        json!({ "menu": menu, "args": args, "how": how }),
997        |_, a| Ok(a["args"].clone()),
998    );
999    match out {
1000        Outcome::Done(Ok(args)) => Some(args),
1001        Outcome::Done(Err(_)) | Outcome::Vetoed { .. } => None,
1002    }
1003}
1004
1005/// A context with arguments as `args.<key>` keys (scalars only).
1006pub(crate) fn with_args(cx: &WhenContext, args: &Json) -> WhenContext {
1007    let mut cx = cx.clone();
1008    if let Json::Object(m) = args {
1009        for (k, v) in m {
1010            let text = match v {
1011                Json::String(s) => s.clone(),
1012                Json::Bool(_) | Json::Number(_) => v.to_string(),
1013                _ => continue,
1014            };
1015            cx.set(&format!("args.{k}"), &text);
1016        }
1017    }
1018    cx
1019}
1020
1021/// An item's arguments with a call's merged in (the call's win).
1022pub(crate) fn merge(item: &Json, extra: &Json) -> Json {
1023    match (item, extra) {
1024        (_, Json::Null) => item.clone(),
1025        (Json::Null, _) => extra.clone(),
1026        (Json::Object(a), Json::Object(b)) => {
1027            let mut m: Map<String, Json> = a.clone();
1028            m.extend(b.iter().map(|(k, v)| (k.clone(), v.clone())));
1029            Json::Object(m)
1030        }
1031        _ => item.clone(),
1032    }
1033}
1034
1035fn items(ui: &mut Ui, app: &AppHandle, menu: &MenuId, cx: &WhenContext, args: &Json, depth: u32) {
1036    if depth > MAX_DEPTH {
1037        ui.weak(strings::tr_args(
1038            ui.ctx(),
1039            &txt::MENU_TOO_DEEP,
1040            &[("menu", menu.as_str())],
1041        ));
1042        return;
1043    }
1044    let list = app.menu(menu);
1045    if list.is_empty() {
1046        ui.weak(strings::tr(ui.ctx(), &txt::MENU_EMPTY));
1047        return;
1048    }
1049    rows(ui, app, menu, show_items(&list, cx), cx, args, depth);
1050}
1051
1052/// Draws a menu's rows already evaluated in a context (some of a menu's
1053/// items: a toolbar's overflow), with arguments merged into every
1054/// command an item runs.
1055pub(crate) fn rows(
1056    ui: &mut Ui,
1057    app: &AppHandle,
1058    menu: &MenuId,
1059    shown: Vec<Shown>,
1060    cx: &WhenContext,
1061    args: &Json,
1062    depth: u32,
1063) {
1064    // The lists' entries first: the columns depend on them.
1065    let lists: HashMap<String, Vec<ListItem>> = shown
1066        .iter()
1067        .filter_map(|s| match s {
1068            Shown::Item {
1069                item: Item::List { name },
1070                ..
1071            } => Some((name.clone(), list_entries(ui, app, menu, name, cx))),
1072            _ => None,
1073        })
1074        .collect();
1075    let columns = Columns::of(ui.ctx(), app, &shown, &lists);
1076    let separator = item_metrics(ui);
1077    for shown in shown {
1078        match shown {
1079            Shown::Separator => {
1080                ui.add(separator_line(separator));
1081            }
1082            Shown::Item {
1083                item,
1084                enabled,
1085                checked,
1086                checkable,
1087                radio,
1088            } => match item {
1089                Item::Command {
1090                    id,
1091                    args: own,
1092                    label,
1093                } => {
1094                    let row = Row {
1095                        menu,
1096                        id: &id,
1097                        label,
1098                        icon: RowIcon::Command,
1099                        enabled,
1100                        checked,
1101                        checkable,
1102                        radio,
1103                    };
1104                    if app_command_row(ui, app, cx, &columns, row) {
1105                        app.request_run_in(id.clone(), merge(&own, args), cx.clone());
1106                        ui.close();
1107                    }
1108                }
1109                Item::Submenu { menu: sub, label } => {
1110                    let label = strings::menu_label(ui.ctx(), sub.as_str(), &label);
1111                    let label_x = ui
1112                        .add_enabled_ui(enabled, |ui| {
1113                            declared_submenu(ui, app, &sub, &label, cx, args, depth, &columns)
1114                        })
1115                        .inner;
1116                    record_row(
1117                        ui.ctx(),
1118                        RowTrace {
1119                            menu: menu.clone(),
1120                            label,
1121                            icon: None,
1122                            mark: Mark::None,
1123                            label_x,
1124                            gutter: columns.gutter,
1125                        },
1126                    );
1127                }
1128                Item::List { name } => {
1129                    for entry in lists.get(&name).cloned().unwrap_or_default() {
1130                        let row = Row {
1131                            menu,
1132                            id: &entry.command,
1133                            label: Some(entry.label.clone()),
1134                            icon: RowIcon::Own(entry.icon),
1135                            enabled: enabled && entry.enabled,
1136                            checked: entry.checked,
1137                            checkable: entry.checked,
1138                            radio: false,
1139                        };
1140                        if app_command_row(ui, app, cx, &columns, row) {
1141                            app.request_run_in(
1142                                entry.command.clone(),
1143                                merge(&entry.args, args),
1144                                cx.clone(),
1145                            );
1146                            ui.close();
1147                        }
1148                    }
1149                }
1150            },
1151        }
1152    }
1153}
1154
1155/// Sets a menu's metrics from the kit's `menu-item` on the menu's `Ui`:
1156/// its least width (`width`), a row's height (`height`) and the label's
1157/// room (`padding-x`, `padding-y`); each left to egui when not given.
1158/// Returns how far a separator grows past the rows into the menu's
1159/// margin, from `menu-item.separator-inset` (0: edge to edge); `None`:
1160/// egui's separator.
1161fn item_metrics(ui: &mut Ui) -> Option<f32> {
1162    let kit = Kit::of(ui.ctx());
1163    let data = &kit.menu_item.data;
1164    if data.width > 0.0 {
1165        ui.set_min_width(data.width);
1166    }
1167    let s = ui.spacing_mut();
1168    if data.height > 0.0 {
1169        s.interact_size.y = data.height;
1170    }
1171    if data.padding_x > 0.0 {
1172        s.button_padding.x = data.padding_x;
1173    }
1174    if data.padding_y > 0.0 {
1175        s.button_padding.y = data.padding_y;
1176    }
1177    // The menu's frame keeps its margin around the rows: the line grows
1178    // into it, up to the inset asked.
1179    let margin = ui.style().spacing.menu_margin.leftf();
1180    Tokens::of(ui.ctx())
1181        .resolved()
1182        .dimension("menu-item.separator-inset")
1183        .map(|inset| margin - inset.max(0.0))
1184}
1185
1186/// A menu's separator, grown by `grow` past the rows ([`item_metrics`]).
1187fn separator_line(grow: Option<f32>) -> egui::Separator {
1188    let separator = egui::Separator::default().horizontal();
1189    match grow {
1190        Some(g) if g >= 0.0 => separator.grow(g),
1191        Some(g) => separator.shrink(-g),
1192        None => separator,
1193    }
1194}
1195
1196/// How the rows of one menu line up: worked out once for the whole menu,
1197/// so every row starts its label at the same x.
1198#[derive(Clone, Copy, Debug, PartialEq)]
1199struct Columns {
1200    /// The gutter's width; zero when the menu keeps none.
1201    gutter: f32,
1202    /// The commands' icons are shown.
1203    icons: bool,
1204    /// A column at the end for submenu arrows (blank on other rows).
1205    arrow: bool,
1206}
1207
1208impl Columns {
1209    fn of(
1210        ctx: &Context,
1211        app: &AppHandle,
1212        shown: &[Shown],
1213        lists: &HashMap<String, Vec<ListItem>>,
1214    ) -> Columns {
1215        let icons = menu_icons(app).shows();
1216        let mut marks = false;
1217        let mut arrow = false;
1218        for s in shown {
1219            let Shown::Item {
1220                item, checkable, ..
1221            } = s
1222            else {
1223                continue;
1224            };
1225            match item {
1226                Item::Command { id, .. } => marks |= *checkable || app.running(id),
1227                Item::Submenu { .. } => arrow = true,
1228                Item::List { name } => {
1229                    marks |= lists
1230                        .get(name)
1231                        .is_some_and(|l| l.iter().any(|e| e.checked || app.running(&e.command)));
1232                }
1233            }
1234        }
1235        let t = Tokens::of(ctx);
1236        // A kit whose gutter is 0 keeps none: no icons, no marks.
1237        let none = t.resolved().dimension("menu-item-gutter.width") == Some(0.0);
1238        let gutter = if !none && (icons || marks) {
1239            Kit::of(ctx).menu_gutter(&t)
1240        } else {
1241            0.0
1242        };
1243        Columns {
1244            gutter,
1245            icons: icons && !none,
1246            arrow,
1247        }
1248    }
1249
1250    /// The gutter's atom, first in a row; none when the menu keeps no
1251    /// gutter.
1252    fn gutter_atom(&self, id: Id, side: f32) -> Option<Atom<'static>> {
1253        (self.gutter > 0.0).then(|| Atom::custom(egui::IdSalt::new(id), vec2(self.gutter, side)))
1254    }
1255}
1256
1257/// The overflow's rows: the menu bar's titles, without a gutter.
1258const TITLES: Columns = Columns {
1259    gutter: 0.0,
1260    icons: false,
1261    arrow: true,
1262};
1263
1264/// Where a row's icon comes from.
1265#[derive(Clone, Copy, Debug)]
1266enum RowIcon {
1267    /// The command's (`icon`, `icon_on` while checked).
1268    Command,
1269    /// Its own (a list entry's): never its command's.
1270    Own(Option<Icon>),
1271}
1272
1273/// What a row's gutter holds, as agents read it ([`rows_drawn`]).
1274#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
1275#[serde(rename_all = "lowercase")]
1276pub enum Mark {
1277    /// Nothing: no icon, not checked.
1278    None,
1279    /// The command's icon.
1280    Icon,
1281    /// The icon, framed: a checked command with an icon.
1282    Framed,
1283    /// A tick: a checked item without an icon.
1284    Check,
1285    /// A dot: the chosen item of a radio group, without an icon.
1286    Radio,
1287    /// The spinner of a running command.
1288    Busy,
1289}
1290
1291/// A menu row as it was drawn, for agents and tests.
1292#[derive(Clone, Debug, PartialEq, Serialize)]
1293pub struct RowTrace {
1294    /// The menu it is in.
1295    pub menu: MenuId,
1296    /// Its label.
1297    pub label: String,
1298    /// The name of the icon it shows, if any (framed or not).
1299    #[serde(skip_serializing_if = "Option::is_none")]
1300    pub icon: Option<String>,
1301    pub mark: Mark,
1302    /// Where its label starts, in points from the row's left edge.
1303    pub label_x: f32,
1304    /// The gutter's width (zero when the menu keeps none).
1305    pub gutter: f32,
1306}
1307
1308/// The rows drawn this pass and the last complete pass's.
1309const ROWS: Slot<(u64, Vec<RowTrace>, Vec<RowTrace>)> = Slot::new("api.menus.rows");
1310
1311/// The most rows kept per pass.
1312const ROWS_MAX: usize = 512;
1313
1314pub(crate) fn record_row(ctx: &Context, row: RowTrace) {
1315    let now = ctx.cumulative_pass_nr();
1316    ROWS.update(ctx, |(pass, building, last)| {
1317        if *pass != now {
1318            *last = if *pass + 1 == now {
1319                std::mem::take(building)
1320            } else {
1321                Vec::new()
1322            };
1323            building.clear();
1324            *pass = now;
1325        }
1326        if building.len() < ROWS_MAX {
1327            building.push(row);
1328        }
1329    });
1330}
1331
1332/// The menu rows drawn in the last complete pass (every open menu's,
1333/// and menus drawn in place): their labels, icons, gutter marks and
1334/// where their labels start, so an agent or a test reads what a menu
1335/// shows without pixels.
1336pub fn rows_drawn(ctx: &Context) -> Vec<RowTrace> {
1337    let now = ctx.cumulative_pass_nr();
1338    ROWS.update(ctx, |(pass, building, last)| {
1339        if *pass + 1 == now {
1340            building.clone()
1341        } else if *pass == now {
1342            last.clone()
1343        } else {
1344            Vec::new()
1345        }
1346    })
1347}
1348
1349/// A list's entries: asked of its provider when the menu opens (the
1350/// first frame it is drawn), kept while it stays open.
1351fn list_entries(
1352    ui: &Ui,
1353    app: &AppHandle,
1354    menu: &MenuId,
1355    name: &str,
1356    cx: &WhenContext,
1357) -> Vec<ListItem> {
1358    let key = LIST.keyed((menu.as_str(), name));
1359    let pass = ui.ctx().cumulative_pass_nr();
1360    let kept = key.get(ui.ctx()).filter(|(at, _)| at + 1 >= pass);
1361    let entries = match kept {
1362        Some((_, entries)) => entries,
1363        None => app.list_items(name, cx),
1364    };
1365    key.set(ui.ctx(), (pass, entries.clone()));
1366    entries
1367}
1368
1369/// A command row as a menu draws it.
1370struct Row<'a> {
1371    menu: &'a MenuId,
1372    id: &'a CommandId,
1373    label: Option<String>,
1374    icon: RowIcon,
1375    enabled: bool,
1376    checked: bool,
1377    checkable: bool,
1378    radio: bool,
1379}
1380
1381/// Draws a declared command's row; whether it was clicked.
1382fn app_command_row(
1383    ui: &mut Ui,
1384    app: &AppHandle,
1385    cx: &WhenContext,
1386    columns: &Columns,
1387    row: Row<'_>,
1388) -> bool {
1389    let t = Tokens::of(ui.ctx());
1390    let ctx = ui.ctx().clone();
1391    let side = t.size.icon_inline;
1392    let Row {
1393        menu,
1394        id,
1395        label,
1396        icon,
1397        enabled,
1398        checked,
1399        checkable,
1400        radio,
1401    } = row;
1402    let spec = app.command(id);
1403    let (title, why) = match &spec {
1404        Some(s) => {
1405            let when = When::parse(&s.when);
1406            let applies = s.when.is_empty() || when.as_ref().is_ok_and(|w| w.eval(cx));
1407            let why = (!applies)
1408                .then(
1409                    || match when.as_ref().ok().and_then(|w| other_window(app, w, cx)) {
1410                        Some(window) => {
1411                            strings::tr_args(&ctx, &txt::MENU_IN_WINDOW, &[("window", &window)])
1412                        }
1413                        None => {
1414                            strings::tr_args(&ctx, &txt::MENU_DOES_NOT_APPLY, &[("when", &s.when)])
1415                        }
1416                    },
1417                )
1418                .or_else(|| (!enabled).then(|| strings::tr(&ctx, &txt::MENU_NOT_AVAILABLE)));
1419            (
1420                label.clone().unwrap_or_else(|| app.command_menu_title(s)),
1421                why,
1422            )
1423        }
1424        None => (
1425            id.to_string(),
1426            Some(strings::tr_args(
1427                &ctx,
1428                &txt::MENU_NO_COMMAND,
1429                &[("id", id.as_str())],
1430            )),
1431        ),
1432    };
1433    // A run waiting for its result greys the item.
1434    let why = why.or_else(|| {
1435        app.running(id)
1436            .then(|| strings::tr(&ctx, &txt::MENU_RUNNING))
1437    });
1438    let failed = app
1439        .history()
1440        .iter()
1441        .rev()
1442        .find(|r| r.id == *id)
1443        .and_then(|r| r.result.clone().err());
1444    // The icon shown: the command's (its "on" one while checked), or a
1445    // list entry's own; none when the setting hides icons.
1446    let icon: Option<(Icon, String)> = if columns.icons {
1447        match icon {
1448            RowIcon::Command => spec
1449                .as_ref()
1450                .and_then(|s| s.icon_for(checked))
1451                .map(|name| crate::layout_controls::command_icon(app, id, name))
1452                .map(|name| (IconRef::from(name).or_placeholder("menu"), name.to_string())),
1453            RowIcon::Own(i) => i.map(|i| (i, i.name().to_string())),
1454        }
1455    } else {
1456        None
1457    };
1458    let tick = Id::unique(("egui_pop_menu_tick", menu.as_str(), id.as_str(), &title));
1459    let text_id = tick.with("label");
1460    let blank = tick.with("arrow");
1461    let kit = Kit::of(&ctx);
1462    let item = &kit.menu_item;
1463    let shortcut = app.keys_for(id).first().cloned();
1464    let note = spec.as_ref().and_then(|s| s.menu_note.clone());
1465    let link = spec.as_ref().is_some_and(|s| s.opens_link);
1466    let link_id = tick.with("link");
1467    let key_size = key_font_size(&ctx);
1468    // egui lays the item out and takes its clicks; the kit paints its box
1469    // under it (`slot`), in the state egui's button draws with.
1470    let slot = ui.painter().add(Shape::Noop);
1471    let (r, state) = ui
1472        .add_enabled_ui(why.is_none(), |ui| {
1473            let state = item_state(ui, ui.next_auto_id());
1474            let label = item_text(ui, item, state, title.as_str());
1475            let mut atoms: Vec<Atom<'_>> = Vec::with_capacity(5);
1476            atoms.extend(columns.gutter_atom(tick, side));
1477            atoms.push(label.atom_id(egui::IdSalt::new(text_id)));
1478            if shortcut.is_some() || note.is_some() || link || columns.arrow {
1479                atoms.push(Atom::grow());
1480            }
1481            let muted = item.style_toned(Tone::Muted, state).text;
1482            let meta = |text: &str| {
1483                let t = RichText::new(text).color(muted);
1484                match key_size {
1485                    Some(size) => t.size(size),
1486                    None => t,
1487                }
1488            };
1489            if let Some(k) = shortcut {
1490                atoms.push(meta(&k).into());
1491            }
1492            if let Some(n) = &note {
1493                atoms.push(meta(n).into());
1494            }
1495            if link {
1496                // Three quarters of the keys' font size when the theme
1497                // sizes them, as a glyph among them; else of an icon's.
1498                let s = key_size.unwrap_or(side) * 0.75;
1499                atoms.push(Atom::custom(egui::IdSalt::new(link_id), vec2(s, s)));
1500            }
1501            if columns.arrow {
1502                atoms.push(Atom::custom(egui::IdSalt::new(blank), vec2(side, side)));
1503            }
1504            let button = Button::new(egui::Atoms::from(atoms))
1505                .fill(Color32::TRANSPARENT)
1506                .stroke(Stroke::NONE);
1507            (button.atom_ui(ui), state)
1508        })
1509        .inner;
1510    paint_item(ui, item, slot, r.response.rect, state);
1511    if let Some(rect) = r.rect(egui::IdSalt::new(link_id)) {
1512        paint_link(
1513            ui.painter(),
1514            rect,
1515            item.style_toned(Tone::Muted, state).text,
1516        );
1517    }
1518    // A run waiting for the host: a spinner in the gutter, after the
1519    // delay.
1520    let busy = crate::busy::busy_shown(app, &ctx, tick, id);
1521    if app.running(id) {
1522        ctx.accesskit_node_builder(r.response.id, |node| node.set_busy());
1523    }
1524    let mark = match (busy, checked, &icon) {
1525        (true, ..) => Mark::Busy,
1526        (false, true, Some(_)) => Mark::Framed,
1527        (false, true, None) if radio => Mark::Radio,
1528        (false, true, None) => Mark::Check,
1529        (false, false, Some(_)) => Mark::Icon,
1530        (false, false, None) => Mark::None,
1531    };
1532    if let Some(rect) = r.rect(egui::IdSalt::new(tick)) {
1533        // The mark keeps the item's resting colour (greyed when
1534        // disabled), never a tone: high contrast keeps the text's.
1535        let disabled = why.is_some();
1536        let color = item.style(State::REST.with(State::DISABLED, disabled)).text;
1537        let square = Rect::from_center_size(rect.center(), vec2(side, side));
1538        let painter = ui.painter();
1539        if mark == Mark::Framed {
1540            let frame = Rect::from_center_size(
1541                rect.center(),
1542                vec2(rect.width(), rect.width().min(r.response.rect.height())),
1543            );
1544            kit.menu_item_gutter.paint(
1545                &egui_pop_core::kit::KitCx {
1546                    painter,
1547                    ppp: ctx.pixels_per_point(),
1548                },
1549                &Part {
1550                    rect: frame,
1551                    room: frame,
1552                    state: State::SELECTED.with(State::DISABLED, disabled),
1553                    label: None,
1554                },
1555            );
1556        }
1557        match mark {
1558            Mark::Busy => egui_pop_core::progress::paint_spinner(ui, square, color),
1559            Mark::Check => kit.glyph(Glyph::Check).paint(painter, square, color),
1560            Mark::Radio => kit.glyph(Glyph::Radio).paint(painter, square, color),
1561            Mark::Icon | Mark::Framed => {
1562                if let Some((i, _)) = &icon {
1563                    i.paint(painter, square, color);
1564                }
1565            }
1566            Mark::None => {}
1567        }
1568    }
1569    if let Some((_, name)) = &icon {
1570        egui_pop_core::icon::registry::record(&ctx, "menu", &title, name);
1571    }
1572    record_row(
1573        &ctx,
1574        RowTrace {
1575            menu: menu.clone(),
1576            label: title.clone(),
1577            icon: icon.as_ref().map(|(_, n)| n.clone()),
1578            mark,
1579            label_x: r
1580                .rect(egui::IdSalt::new(text_id))
1581                .map_or(0.0, |l| l.left() - r.response.rect.left()),
1582            gutter: columns.gutter,
1583        },
1584    );
1585    let mut response = r.response;
1586    if checkable {
1587        // Named by the text it shows, as a plain row: the application's
1588        // live title (`pop.command.label`) when it gives one.
1589        let (on, name) = (why.is_none(), title.clone());
1590        let kind = if radio {
1591            egui::Role::RadioButton
1592        } else {
1593            egui::Role::CheckBox
1594        };
1595        response.widget_info(|| egui::WidgetInfo::selected(kind, on, checked, &name));
1596    }
1597    if let Some(why) = why {
1598        response = response.on_disabled_hover_text(why);
1599    } else if let Some(e) = failed {
1600        response = response.on_hover_text(strings::tr_args(
1601            &ctx,
1602            &txt::MENU_LAST_RUN_FAILED,
1603            &[("error", &e)],
1604        ));
1605    } else if let Some(tip) = spec
1606        .map(|s| app.command_tooltip(&s))
1607        .filter(|t| !t.is_empty())
1608    {
1609        response = response.on_hover_text(tip);
1610    }
1611    response.clicked()
1612}
1613
1614/// The title of the open window, other than the one of `cx`, where a
1615/// clause that does not apply in `cx` would: a command of another window
1616/// (`appWindow == 'main'`), greyed in this one with where it runs.
1617fn other_window(app: &AppHandle, when: &When, cx: &WhenContext) -> Option<String> {
1618    let here = cx.get(crate::windows::CONTEXT_APP_WINDOW);
1619    app.windows()
1620        .into_iter()
1621        .filter(|w| w.id.as_str() != here)
1622        .find(|w| {
1623            let mut there = cx.clone();
1624            there.set(crate::windows::CONTEXT_APP_WINDOW, w.id.as_str());
1625            when.eval(&there)
1626        })
1627        .map(|w| w.title)
1628}
1629
1630/// The ↗ ending an entry that opens a page outside the application: an
1631/// arrow up and to the right, drawn rather than a glyph a font may lack,
1632/// in the keys' colour; three quarters of `menu-item.key-font-size`
1633/// across when the theme sets it, else of an inline icon.
1634fn paint_link(painter: &egui::Painter, rect: Rect, color: Color32) {
1635    let r = rect.shrink(rect.width() * 0.15);
1636    let stroke = Stroke::new((r.width() / 8.0).max(1.0), color);
1637    painter.line_segment([r.left_bottom(), r.right_top()], stroke);
1638    let head = r.width() * 0.55;
1639    painter.line_segment([r.right_top(), r.right_top() + vec2(-head, 0.0)], stroke);
1640    painter.line_segment([r.right_top(), r.right_top() + vec2(0.0, head)], stroke);
1641}
1642
1643/// The state a menu item's egui button draws with this pass: its
1644/// response from the last one, as egui's `Button` reads it.
1645fn item_state(ui: &Ui, id: Id) -> State {
1646    ui.ctx()
1647        .read_response(id)
1648        .map_or(State::REST, |r| State::from_response(&r))
1649        .with(State::DISABLED, !ui.is_enabled())
1650}
1651
1652/// A menu item's label in its state's colour. A disabled item keeps its
1653/// resting colour: egui greys a disabled item itself.
1654fn item_text(ui: &Ui, item: &Component, state: State, text: &str) -> RichText {
1655    let colour = if ui.is_enabled() {
1656        item.style(state).text
1657    } else {
1658        item.style(State::REST).text
1659    };
1660    RichText::new(text).color(colour)
1661}
1662
1663/// The size of a menu's keys and notes, `menu-item.key-font-size`; `None`
1664/// when the theme gives none: the label's size, the `Body` text style.
1665fn key_font_size(ctx: &egui::Context) -> Option<f32> {
1666    Tokens::of(ctx)
1667        .resolved()
1668        .dimension("menu-item.key-font-size")
1669        .filter(|s| *s > 0.0)
1670}
1671
1672/// Paints a menu item's box under what egui drew of it.
1673fn paint_item(ui: &Ui, item: &Component, slot: egui::layers::ShapeIdx, rect: Rect, state: State) {
1674    item.paint_under(
1675        ui,
1676        slot,
1677        &Part {
1678            rect,
1679            room: rect,
1680            state,
1681            label: None,
1682        },
1683        None,
1684    );
1685}
1686
1687/// A command row in a menu drawn by hand (a popup or context menu built
1688/// in a closure), drawn as the declared menus' command rows: the kit's
1689/// `menu-item`, its label at the start, `shortcut` (the keys' text, such
1690/// as `Ctrl+C`) muted at the end in the menu's key font. Greyed and not
1691/// clickable while `disabled` gives why, the reason in its tooltip.
1692/// Assistive technology reads a menu item named by `label`, its
1693/// shortcut as its keyboard shortcut.
1694///
1695/// The caller acts on a click and closes the menu (`ui.close()`), as in
1696/// any egui menu.
1697///
1698/// Need (dialog): a command row with its shortcut in a menu drawn by hand.
1699///
1700/// ```
1701/// use egui_pop_api::menus;
1702///
1703/// fn row_menu(ui: &mut egui::Ui, can_paste: bool) {
1704///     if menus::command_row(ui, "Copy", Some("Ctrl+C"), None).clicked() {
1705///         ui.close();
1706///     }
1707///     let why = (!can_paste).then_some("Nothing to paste");
1708///     if menus::command_row(ui, "Paste", Some("Ctrl+V"), why).clicked() {
1709///         ui.close();
1710///     }
1711/// }
1712/// ```
1713pub fn command_row(
1714    ui: &mut Ui,
1715    label: &str,
1716    shortcut: Option<&str>,
1717    disabled: Option<&str>,
1718) -> Response {
1719    let ctx = ui.ctx().clone();
1720    let kit = Kit::of(&ctx);
1721    let item = &kit.menu_item;
1722    let key_size = key_font_size(&ctx);
1723    let my_id = ui.next_auto_id();
1724    let text_id = my_id.with("label");
1725    let slot = ui.painter().add(Shape::Noop);
1726    let (r, state) = ui
1727        .add_enabled_ui(disabled.is_none(), |ui| {
1728            let state = item_state(ui, ui.next_auto_id());
1729            let mut atoms: Vec<Atom<'_>> = Vec::with_capacity(3);
1730            atoms.push(item_text(ui, item, state, label).atom_id(egui::IdSalt::new(text_id)));
1731            if let Some(keys) = shortcut {
1732                let muted = item.style_toned(Tone::Muted, state).text;
1733                let text = RichText::new(keys).color(muted);
1734                let text = match key_size {
1735                    Some(size) => text.size(size),
1736                    None => text,
1737                };
1738                atoms.push(Atom::grow());
1739                atoms.push(text.into());
1740            }
1741            let button = Button::new(egui::Atoms::from(atoms))
1742                .fill(Color32::TRANSPARENT)
1743                .stroke(Stroke::NONE);
1744            (button.atom_ui(ui), state)
1745        })
1746        .inner;
1747    paint_item(ui, item, slot, r.response.rect, state);
1748    let response = r.response;
1749    ctx.accesskit_node_builder(response.id, |node| {
1750        node.set_role(egui::accesskit::Role::MenuItem);
1751        node.set_label(label);
1752        if let Some(keys) = shortcut {
1753            node.set_keyboard_shortcut(keys);
1754        }
1755    });
1756    match disabled {
1757        Some(why) => response.on_disabled_hover_text(why),
1758        None => response,
1759    }
1760}
1761
1762/// A submenu button with a painted arrow in the menu's last column,
1763/// opening on hover as egui's `SubMenuButton` does; where its label
1764/// starts in the row.
1765#[allow(
1766    clippy::too_many_arguments,
1767    reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
1768)]
1769fn declared_submenu(
1770    ui: &mut Ui,
1771    app: &AppHandle,
1772    menu: &MenuId,
1773    label: &str,
1774    cx: &WhenContext,
1775    args: &Json,
1776    depth: u32,
1777    columns: &Columns,
1778) -> f32 {
1779    let t = Tokens::of(ui.ctx());
1780    let side = t.size.icon_inline;
1781    let my_id = ui.next_auto_id();
1782    let open = MenuState::from_ui(ui, |state, _| {
1783        state.open_item == Some(SubMenu::id_from_widget_id(my_id))
1784    });
1785    let space = Id::unique(("egui_pop_menu_space", menu.as_str()));
1786    let arrow = Id::unique(("egui_pop_menu_arrow", menu.as_str()));
1787    let text_id = space.with("label");
1788    let kit = Kit::of(ui.ctx());
1789    let item = &kit.menu_item;
1790    let slot = ui.painter().add(Shape::Noop);
1791    // Selected while its submenu is open.
1792    let state = item_state(ui, my_id).with(State::SELECTED, open);
1793    let mut atoms: Vec<Atom<'_>> = Vec::with_capacity(4);
1794    atoms.extend(columns.gutter_atom(space, side));
1795    atoms.push(item_text(ui, item, state, label).atom_id(egui::IdSalt::new(text_id)));
1796    atoms.push(Atom::grow());
1797    atoms.push(Atom::custom(egui::IdSalt::new(arrow), vec2(side, side)));
1798    let button = Button::new(egui::Atoms::from(atoms))
1799        .fill(Color32::TRANSPARENT)
1800        .stroke(Stroke::NONE);
1801    let r = button.atom_ui(ui);
1802    paint_item(ui, item, slot, r.response.rect, state);
1803    if let Some(rect) = r.rect(egui::IdSalt::new(arrow)) {
1804        kit.glyph(Glyph::Submenu).paint(
1805            ui.painter(),
1806            rect.shrink(rect.width() * 0.15),
1807            t.text.muted,
1808        );
1809    }
1810    SubMenu::default()
1811        .config(MenuConfig::find(ui))
1812        .show(ui, &r.response, |ui| {
1813            items(ui, app, menu, cx, args, depth + 1)
1814        });
1815    r.rect(egui::IdSalt::new(text_id))
1816        .map_or(0.0, |l| l.left() - r.response.rect.left())
1817}
1818
1819/// What a hand-drawn submenu item remembers between passes (per item).
1820#[derive(Clone, Copy, Debug, Default)]
1821struct Hover {
1822    /// When the pointer came to rest on the item.
1823    since: Option<f64>,
1824    /// Escape closed the submenu: the pointer resting there does not open
1825    /// it again until it moves.
1826    held: bool,
1827}
1828
1829const SUBMENU_HOVER: Slot<Hover> = Slot::new("api.menus.submenu_hover");
1830
1831/// A submenu item in a menu drawn by hand (a context menu built in a
1832/// closure, `egui_pop_core::pointer::claim::context_menu`), drawn as the
1833/// declared menus' submenu items: the kit's `menu-item` with the submenu
1834/// arrow, `selected` while its submenu is open. `add` draws the submenu's
1835/// rows; it runs only while the submenu is open, and its value comes back
1836/// in the response's `inner`.
1837///
1838/// - The pointer resting on the item `motion.submenu.delay` (200 ms)
1839///   opens it; a click opens it at once.
1840/// - On the keyboard, Right, Enter or Space on the item opens it with the
1841///   focus on its first row; Left in the submenu closes it, back on the
1842///   item; Escape closes one level (this submenu, not the menu holding
1843///   it).
1844/// - Assistive technology reads a menu item named by `label`, with a
1845///   menu popup, expanded while open.
1846///
1847/// Choosing a row in the submenu closes every level: the row calls
1848/// `ui.close()`, as in any egui menu.
1849///
1850/// Need (dialog): a submenu in a context menu drawn by hand.
1851///
1852/// ```
1853/// use egui_pop_api::menus;
1854///
1855/// fn row_menu(ui: &mut egui::Ui, auto: &mut bool) {
1856///     if ui.button("Rename").clicked() {
1857///         ui.close();
1858///     }
1859///     menus::submenu(ui, "Import automatically", |ui| {
1860///         if ui.radio_value(auto, false, "Off").clicked()
1861///             | ui.radio_value(auto, true, "On plug-in").clicked()
1862///         {
1863///             ui.close();
1864///         }
1865///     });
1866/// }
1867/// ```
1868pub fn submenu<R>(
1869    ui: &mut Ui,
1870    label: &str,
1871    add: impl FnOnce(&mut Ui) -> R,
1872) -> egui::InnerResponse<Option<R>> {
1873    let ctx = ui.ctx().clone();
1874    let t = Tokens::of(&ctx);
1875    let side = t.size.icon_inline;
1876    let my_id = ui.next_auto_id();
1877    let sub_id = SubMenu::id_from_widget_id(my_id);
1878    let is_open = |ui: &Ui| MenuState::from_ui(ui, |state, _| state.open_item == Some(sub_id));
1879    let mut open = is_open(ui);
1880    // Escape closes the deepest open level alone: taken here, before the
1881    // submenu's popup and the menu holding it see it (egui closes them
1882    // all).
1883    let escaped = open
1884        && MenuState::is_deepest_open_sub_menu(&ctx, sub_id)
1885        && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape));
1886    let slot = SUBMENU_HOVER.keyed(my_id);
1887    if escaped {
1888        MenuState::from_ui(ui, |state, _| state.open_item = None);
1889        ui.memory_mut(|m| m.request_focus(my_id));
1890        slot.set(
1891            &ctx,
1892            Hover {
1893                since: None,
1894                held: true,
1895            },
1896        );
1897        open = false;
1898    }
1899
1900    let arrow = my_id.with("arrow");
1901    let text_id = my_id.with("label");
1902    let kit = Kit::of(&ctx);
1903    let item = &kit.menu_item;
1904    let paint_slot = ui.painter().add(Shape::Noop);
1905    let state = item_state(ui, my_id).with(State::SELECTED, open);
1906    let atoms: Vec<Atom<'_>> = vec![
1907        item_text(ui, item, state, label).atom_id(egui::IdSalt::new(text_id)),
1908        Atom::grow(),
1909        Atom::custom(egui::IdSalt::new(arrow), vec2(side, side)),
1910    ];
1911    let button = Button::new(egui::Atoms::from(atoms))
1912        .fill(Color32::TRANSPARENT)
1913        .stroke(Stroke::NONE);
1914    let r = button.atom_ui(ui);
1915    let response = r.response.clone();
1916    paint_item(ui, item, paint_slot, response.rect, state);
1917    if let Some(rect) = r.rect(egui::IdSalt::new(arrow)) {
1918        kit.glyph(Glyph::Submenu).paint(
1919            ui.painter(),
1920            rect.shrink(rect.width() * 0.15),
1921            t.text.muted,
1922        );
1923    }
1924
1925    // The pointer opens it after resting on the item.
1926    let now = ctx.input(|i| i.time);
1927    let moved = ctx.input(|i| i.pointer.delta() != egui::Vec2::ZERO);
1928    let hovered = response.contains_pointer();
1929    let delay = f64::from(t.motion.submenu_delay);
1930    let hover = slot.update(&ctx, |h| {
1931        if h.held && (moved || !hovered) {
1932            h.held = false;
1933        }
1934        if !hovered || h.held {
1935            h.since = None;
1936        } else if h.since.is_none() {
1937            h.since = Some(now);
1938        }
1939        *h
1940    });
1941    let rested = hover.since.is_some_and(|s| now - s >= delay);
1942    if let Some(s) = hover.since.filter(|_| !rested) {
1943        ctx.request_repaint_after_secs((s + delay - now).max(0.0) as f32);
1944    }
1945    let focused = response.has_focus();
1946    let keyboard = focused
1947        && !escaped
1948        && (ui.input(|i| i.key_pressed(egui::Key::ArrowRight))
1949            || (response.clicked() && !response.clicked_by(egui::PointerButton::Primary)));
1950    let clicked = response.clicked_by(egui::PointerButton::Primary);
1951    let inner = if !escaped && (open || keyboard || clicked || rested) {
1952        SubMenu::default()
1953            .config(MenuConfig::find(ui))
1954            .show(ui, &response, add)
1955            .map(|shown| shown.inner)
1956    } else {
1957        None
1958    };
1959    let expanded = is_open(ui);
1960    ctx.accesskit_node_builder(response.id, |node| {
1961        node.set_role(egui::accesskit::Role::MenuItem);
1962        node.set_has_popup(egui::accesskit::HasPopup::Menu);
1963        node.set_expanded(expanded);
1964    });
1965    egui::InnerResponse::new(inner, response)
1966}
1967
1968impl AppHandle {
1969    /// Asks for a command to run as the user in a given context (a menu
1970    /// opened there), before the next frame.
1971    pub fn request_run_in(&self, command: CommandId, args: Json, context: WhenContext) {
1972        self.push_request(Request::RunIn {
1973            command,
1974            args,
1975            origin: egui_pop_model::commands::Origin::User,
1976            context,
1977        });
1978    }
1979}