Skip to main content

xrack_layout/
menu.rs

1use crate::input::ElementId;
2use crate::{
3    ControlInput, LayoutNode, MenuShortcut, Point, Rect, Target, edit::SelectionState,
4    input::valid, place_in_direction, popup::PopupTypography, window_safe_area,
5};
6use std::sync::atomic::{AtomicU64, Ordering};
7use xrack_runtime::{
8    ControlAction, ImageAsset, LayoutDirection, Node, TextCommand, TextCommandAvailability,
9    is_window_overlay,
10};
11
12const ROW_HEIGHT: f32 = 28.0;
13const TOUCH_ROW_HEIGHT: f32 = 44.0;
14const MAX_VISIBLE_ROWS: usize = 14;
15const DEFAULT_MENU_FONT_SIZE: f32 = 15.0;
16
17fn menu_viewport(scene: &Node, layout: &LayoutNode) -> Rect {
18    window_safe_area(scene, layout.clip).inset(4.0)
19}
20
21fn row_height(menu: &Node, touch: bool, typography: PopupTypography) -> f32 {
22    let minimum = if touch { TOUCH_ROW_HEIGHT } else { ROW_HEIGHT };
23    rows(menu)
24        .filter(|(_, row)| row.kind != "MenuSeparator")
25        .map(|(_, row)| typography.size(row, DEFAULT_MENU_FONT_SIZE) * 1.4 + 6.0)
26        .fold(minimum, f32::max)
27}
28
29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
30pub enum MenuKey {
31    Up,
32    Down,
33    Left,
34    Right,
35    Home,
36    End,
37    Accept,
38    Escape,
39}
40
41pub struct MenuRow<'a> {
42    pub node: &'a Node,
43    pub label: &'a str,
44    pub font_size: f32,
45    pub icon: Option<ImageAsset>,
46    pub shortcut: Option<String>,
47    pub enabled: bool,
48    pub separator: bool,
49    pub submenu: bool,
50    pub checked: Option<bool>,
51    index: usize,
52}
53
54pub struct MenuPanel<'a> {
55    pub menu: &'a Node,
56    pub bounds: Rect,
57    pub layout_direction: LayoutDirection,
58    pub rows: Vec<MenuRow<'a>>,
59    pub highlighted: Option<usize>,
60    icon_column: bool,
61    first: usize,
62    row_count: usize,
63    path: Vec<usize>,
64    session: u64,
65}
66
67/// Identity of a displayed menu row, including the label used to guard late actions.
68#[derive(Clone, Debug, PartialEq, Eq)]
69pub struct MenuEntry {
70    pub path: Vec<usize>,
71    pub label: String,
72    pub kind: &'static str,
73    session: u64,
74}
75
76impl MenuPanel<'_> {
77    pub fn path(&self) -> &[usize] {
78        &self.path
79    }
80
81    pub fn session(&self) -> u64 {
82        self.session
83    }
84
85    pub fn can_scroll(&self, backward: bool) -> bool {
86        if backward {
87            self.first > 0
88        } else {
89            self.first + self.rows.len() < self.row_count
90        }
91    }
92
93    #[doc(hidden)]
94    pub fn visible_range(&self) -> std::ops::Range<usize> {
95        self.first..self.first + self.rows.len()
96    }
97
98    #[doc(hidden)]
99    pub fn row_count(&self) -> usize {
100        self.row_count
101    }
102
103    pub fn row_index(&self, slot: usize) -> usize {
104        self.rows[slot].index
105    }
106
107    pub fn entry(&self, slot: usize) -> MenuEntry {
108        let row = &self.rows[slot];
109        let mut path = self.path.clone();
110        path.push(row.index);
111        MenuEntry {
112            path,
113            label: row.label.to_owned(),
114            kind: row.node.kind,
115            session: self.session,
116        }
117    }
118
119    pub fn label_offset(&self) -> f32 {
120        if self.icon_column { 48.0 } else { 26.0 }
121    }
122
123    pub fn row_content_bounds(&self, slot: usize, start: f32, width: f32) -> Rect {
124        let row = self.row_bounds(slot);
125        let item = Rect::new(row.x + start, row.y, width.max(0.0), row.height);
126        place_in_direction(item, row, self.layout_direction)
127    }
128
129    pub fn icon_bounds(&self, slot: usize) -> Rect {
130        let row = self.row_bounds(slot);
131        let size = 16.0_f32.min(row.height).min((row.width - 26.0).max(0.0));
132        let column = self.row_content_bounds(slot, 24.0, size);
133        Rect::new(column.x, row.y + (row.height - size) * 0.5, size, size)
134    }
135    pub fn row_highlighted(&self, slot: usize) -> bool {
136        self.highlighted == Some(self.rows[slot].index)
137    }
138    pub fn row_bounds(&self, slot: usize) -> Rect {
139        let height = self.bounds.height / self.rows.len() as f32;
140        Rect::new(
141            self.bounds.x,
142            self.bounds.y + slot as f32 * height,
143            self.bounds.width,
144            height,
145        )
146    }
147
148    fn pick(&self, point: Point) -> Option<&MenuRow<'_>> {
149        if !self.bounds.contains(point) {
150            return None;
151        }
152        let slot =
153            ((point.y - self.bounds.y) / self.bounds.height * self.rows.len() as f32) as usize;
154        self.rows.get(slot)
155    }
156}
157
158#[derive(Clone, Debug)]
159struct Level {
160    path: Vec<usize>,
161    first: usize,
162    highlight: Option<usize>,
163    scrolled: bool,
164}
165
166#[derive(Clone, Debug)]
167struct PressedItem {
168    level: usize,
169    index: usize,
170    label: String,
171    kind: &'static str,
172    id: Option<ElementId>,
173    command: Option<xrack_runtime::ActionKey>,
174}
175
176#[derive(Clone, Debug)]
177pub(crate) struct MenuPopup {
178    pub trigger: Target,
179    point: Option<Point>,
180    levels: Vec<Level>,
181    pressed: Option<PressedItem>,
182    pub session: u64,
183    pub text: Option<TextMenu>,
184    pub(crate) touch: bool,
185}
186
187/// A text menu presented by a native host instead of the scene renderer.
188#[doc(hidden)]
189pub struct NativeTextMenu(pub(crate) MenuPopup);
190
191impl NativeTextMenu {
192    pub fn session(&self) -> u64 {
193        self.0.session
194    }
195
196    pub fn entries(&self) -> impl Iterator<Item = (usize, &'static str)> + '_ {
197        self.0.text.iter().flat_map(|text| {
198            TEXT_ENTRIES
199                .iter()
200                .zip(&text.menu.children)
201                .enumerate()
202                .filter_map(|(index, (entry, row))| {
203                    let (_, label, _) = (*entry)?;
204                    enabled(row).then_some((index, label))
205                })
206        })
207    }
208}
209
210#[derive(Clone, Debug)]
211pub(crate) struct MenuPan {
212    session: u64,
213    path: Vec<usize>,
214    remainder: f32,
215}
216
217impl MenuPan {
218    pub(crate) fn advance(
219        &mut self,
220        menu: &mut MenuPopup,
221        scene: &Node,
222        layout: &LayoutNode,
223        delta: f32,
224    ) -> bool {
225        if menu.session != self.session {
226            return false;
227        }
228        let Some(depth) = menu.levels.iter().position(|level| level.path == self.path) else {
229            return false;
230        };
231        let Some(node) = menu_at(scene, menu.text.as_ref(), &self.path) else {
232            return false;
233        };
234        let height = menu_viewport(scene, layout).height.max(1.0);
235        let row_height = row_height(node, menu.touch, layout.popup_typography()).min(height);
236        self.remainder += delta;
237        let rows = (self.remainder / row_height).trunc() as isize;
238        self.remainder %= row_height;
239        rows != 0 && menu.scroll_level(scene, layout, depth, rows, false)
240    }
241}
242
243#[derive(Clone, Debug)]
244pub(crate) struct TextMenu {
245    menu: Node,
246    pub value: String,
247    pub selection: SelectionState,
248    pub kind: &'static str,
249    pub writable: bool,
250    pub password: bool,
251    pub commands: TextCommandAvailability,
252}
253
254const TEXT_ENTRIES: [Option<(TextCommand, &str, &str)>; 8] = [
255    Some((TextCommand::Undo, "Undo", "Primary+Z")),
256    Some((TextCommand::Redo, "Redo", "Primary+Shift+Z")),
257    None,
258    Some((TextCommand::Cut, "Cut", "Primary+X")),
259    Some((TextCommand::Copy, "Copy", "Primary+C")),
260    Some((TextCommand::Paste, "Paste", "Primary+V")),
261    None,
262    Some((TextCommand::SelectAll, "Select All", "Primary+A")),
263];
264
265impl TextMenu {
266    pub fn new(
267        node: &Node,
268        value: String,
269        selection: SelectionState,
270        commands: TextCommandAvailability,
271    ) -> Self {
272        let writable = !node.text_read_only();
273        let password = node.is_password();
274        let mut menu = Node::new("Menu", None);
275        menu.properties
276            .insert("title", "Text editing".to_owned().into());
277        for entry in TEXT_ENTRIES {
278            let Some((command, label, shortcut)) = entry else {
279                menu.children.push(Node::new("MenuSeparator", None));
280                continue;
281            };
282            let enabled = match command {
283                TextCommand::Undo => commands.undo,
284                TextCommand::Redo => commands.redo,
285                TextCommand::Cut => commands.cut,
286                TextCommand::Copy => commands.copy,
287                TextCommand::Paste => writable,
288                TextCommand::SelectAll => !value.is_empty(),
289                _ => unreachable!(),
290            };
291            let mut item = Node::new("MenuItem", None);
292            item.properties.insert("text", label.to_owned().into());
293            item.properties
294                .insert("shortcut", shortcut.to_owned().into());
295            item.properties.insert("enabled", enabled.into());
296            menu.children.push(item);
297        }
298        Self {
299            menu,
300            value,
301            selection,
302            kind: node.kind,
303            writable,
304            password,
305            commands,
306        }
307    }
308}
309
310fn menu_at<'a>(scene: &'a Node, text: Option<&'a TextMenu>, path: &[usize]) -> Option<&'a Node> {
311    match text {
312        Some(text) => Some(&text.menu),
313        None => scene.at_path(path),
314    }
315}
316
317fn rows(menu: &Node) -> impl Iterator<Item = (usize, &Node)> {
318    menu.children.iter().enumerate().filter(|(_, row)| {
319        row.is_visible() && matches!(row.kind, "Menu" | "MenuItem" | "MenuSeparator")
320    })
321}
322
323fn enabled(row: &Node) -> bool {
324    row.kind != "MenuSeparator" && row.boolean("enabled", true)
325}
326
327fn label(row: &Node) -> &str {
328    if row.kind == "Menu" {
329        row.text("title").unwrap_or("")
330    } else {
331        row.text("text").unwrap_or("")
332    }
333}
334
335fn shortcut(row: &Node) -> Option<MenuShortcut> {
336    row.text("shortcut")?.parse().ok()
337}
338
339fn icon(row: &Node) -> Option<ImageAsset> {
340    row.image_asset("icon")
341        .filter(|image| !image.size().contains(&0))
342}
343
344fn visit_menu_shortcuts(
345    node: &Node,
346    path: &mut Vec<usize>,
347    visit: &mut impl FnMut(&Node, &[usize]),
348) {
349    if !node.is_visible() || !enabled(node) {
350        return;
351    }
352    if node.kind == "MenuItem" {
353        visit(node, path);
354        return;
355    }
356    for (index, row) in rows(node) {
357        path.push(index);
358        visit_menu_shortcuts(row, path, visit);
359        path.pop();
360    }
361}
362
363fn visit_presentations(
364    node: &Node,
365    layout: &LayoutNode,
366    path: &mut Vec<usize>,
367    visit: &mut impl FnMut(&Node, &[usize]),
368) {
369    if !layout.visible || !layout.enabled || Node::SCROLL_PARTS.contains(&node.kind) {
370        return;
371    }
372    if node.kind == "Shortcut" {
373        visit(node, path);
374        return;
375    }
376    let visible = layout.clip_rect(layout.bounds);
377    if visible.width <= 0.0 || visible.height <= 0.0 {
378        return;
379    }
380    if matches!(node.kind, "Button" | "ToolButton" | "RoundButton") && node.action.is_some() {
381        visit(node, path);
382    }
383    for (index, child, item) in layout.children_in_scene_order(node) {
384        if is_window_overlay(child.kind) {
385            continue;
386        }
387        path.push(index);
388        if node.kind == "MenuBar" {
389            let visible = item.clip_rect(item.bounds);
390            if item.visible && item.enabled && visible.width > 0.0 && visible.height > 0.0 {
391                visit_menu_shortcuts(child, path, visit);
392            }
393        } else {
394            visit_presentations(child, item, path, visit);
395        }
396        path.pop();
397    }
398}
399
400pub(crate) fn visit_shortcut_presentations(
401    scene: &Node,
402    layout: &LayoutNode,
403    scope: &[usize],
404    popup: Option<&MenuPopup>,
405    mut visit: impl FnMut(&Node, &[usize]),
406) {
407    if let Some(popup) = popup.filter(|popup| popup.point.is_some()) {
408        if popup.trigger.path.starts_with(scope)
409            && valid(&popup.trigger, scene, layout)
410            && let Some(level) = popup.levels.first()
411            && popup.text.is_none()
412            && let Some(node) = scene.interactive_at_path(&level.path)
413        {
414            visit_menu_shortcuts(node, &mut level.path.clone(), &mut visit);
415        }
416    } else if let Some((node, item)) = scene.at_path(scope).zip(layout.at_path(scope)) {
417        visit_presentations(node, item, &mut scope.to_vec(), &mut visit);
418    }
419}
420
421fn panel_bounds(
422    anchor: Rect,
423    viewport: Rect,
424    width: f32,
425    height: f32,
426    submenu: bool,
427    direction: LayoutDirection,
428) -> Rect {
429    let right = viewport.x + viewport.width;
430    let bottom = viewport.y + viewport.height;
431    let rtl = direction == LayoutDirection::RightToLeft;
432    let (x, y) = if submenu {
433        let edges = [anchor.x - width, anchor.x + anchor.width];
434        let spaces = [anchor.x - viewport.x, right - anchor.x - anchor.width];
435        let preferred = usize::from(!rtl);
436        let opposite = 1 - preferred;
437        let side = if spaces[preferred] < width && spaces[opposite] > spaces[preferred] {
438            opposite
439        } else {
440            preferred
441        };
442        (edges[side], anchor.y)
443    } else {
444        let next = anchor.y + anchor.height;
445        (
446            if rtl {
447                anchor.x + anchor.width - width
448            } else {
449                anchor.x
450            },
451            if next + height <= bottom || next - viewport.y <= bottom - anchor.y {
452                next
453            } else {
454                anchor.y - height
455            },
456        )
457    };
458    Rect::new(
459        x.clamp(viewport.x, right - width),
460        y.clamp(viewport.y, bottom - height),
461        width,
462        height,
463    )
464}
465
466impl MenuPopup {
467    pub fn open(
468        trigger: Target,
469        path: Vec<usize>,
470        point: Option<Point>,
471        scene: &Node,
472        layout: &LayoutNode,
473        text: Option<TextMenu>,
474        touch: bool,
475    ) -> Option<Self> {
476        static NEXT_SESSION: AtomicU64 = AtomicU64::new(1);
477        let mut popup = Self {
478            trigger,
479            point,
480            levels: vec![Level {
481                path,
482                first: 0,
483                highlight: None,
484                scrolled: false,
485            }],
486            pressed: None,
487            session: NEXT_SESSION.fetch_add(1, Ordering::Relaxed),
488            text,
489            touch,
490        };
491        popup.reconcile(scene, layout).then_some(popup)
492    }
493
494    pub fn bar_header(&self) -> Option<&[usize]> {
495        self.point.is_none().then_some(&self.trigger.path)
496    }
497    pub fn at_root(&self) -> bool {
498        self.levels.len() == 1
499    }
500
501    fn trigger_direction(&self, layout: &LayoutNode) -> LayoutDirection {
502        layout
503            .at_path(&self.trigger.path)
504            .map_or(LayoutDirection::LeftToRight, |item| item.layout_direction)
505    }
506
507    pub fn forward_key(&self, scene: &Node, layout: &LayoutNode) -> MenuKey {
508        let direction = self
509            .levels
510            .iter()
511            .rev()
512            .find_map(|level| menu_at(scene, self.text.as_ref(), &level.path)?.layout_direction())
513            .unwrap_or_else(|| self.trigger_direction(layout));
514        if direction == LayoutDirection::RightToLeft {
515            MenuKey::Left
516        } else {
517            MenuKey::Right
518        }
519    }
520
521    fn visible_count(viewport: Rect, count: usize, row_height: f32) -> usize {
522        ((viewport.height / row_height) as usize)
523            .clamp(1, MAX_VISIBLE_ROWS)
524            .min(count)
525    }
526
527    pub fn panels<'a>(&'a self, scene: &'a Node, layout: &LayoutNode) -> Vec<MenuPanel<'a>> {
528        let viewport = menu_viewport(scene, layout);
529        let typography = layout.popup_typography();
530        let show_shortcuts = !self.touch;
531        if viewport.width <= 0.0 || viewport.height <= 0.0 || !valid(&self.trigger, scene, layout) {
532            return Vec::new();
533        }
534        let mut anchor = if let Some(point) = self.point {
535            Rect::new(point.x, point.y, 0.0, 0.0)
536        } else if let Some(item) = layout.at_path(&self.trigger.path) {
537            item.window_bounds(item.bounds)
538        } else {
539            return Vec::new();
540        };
541        let mut panels = Vec::new();
542        let mut parent_direction = self.trigger_direction(layout);
543        for (index, level) in self.levels.iter().enumerate() {
544            let menu = self.text.as_ref().map_or_else(
545                || scene.interactive_at_path(&level.path),
546                |text| Some(&text.menu),
547            );
548            let Some(menu) = menu.filter(|menu| menu.kind == "Menu") else {
549                break;
550            };
551            let count = rows(menu).count();
552            if count == 0 {
553                break;
554            }
555            let row_height = row_height(menu, self.touch, typography);
556            let visible = Self::visible_count(viewport, count, row_height);
557            let first = level.first.min(count - visible);
558            let icon_column = rows(menu).any(|(_, row)| icon(row).is_some());
559            let width = rows(menu)
560                .map(|(_, row)| {
561                    let text_scale =
562                        typography.size(row, DEFAULT_MENU_FONT_SIZE) / DEFAULT_MENU_FONT_SIZE;
563                    let shortcut_width = if show_shortcuts {
564                        shortcut(row).map_or(0.0, |key| {
565                            key.to_string().len() as f32 * 8.0 * text_scale + 14.0
566                        })
567                    } else {
568                        0.0
569                    };
570                    label(row)
571                        .chars()
572                        .map(|ch| if ch.is_ascii() { 8.0 } else { 16.0 })
573                        .sum::<f32>()
574                        * text_scale
575                        + 54.0
576                        + if icon_column { 22.0 } else { 0.0 }
577                        + shortcut_width
578                })
579                .fold(174.0, f32::max)
580                .min(viewport.width);
581            let direction = menu.layout_direction().unwrap_or(parent_direction);
582            let bounds = panel_bounds(
583                anchor,
584                viewport,
585                width,
586                (visible as f32 * row_height).min(viewport.height),
587                index > 0,
588                if index == 0 {
589                    direction
590                } else {
591                    parent_direction
592                },
593            );
594            let panel = MenuPanel {
595                menu,
596                bounds,
597                layout_direction: direction,
598                highlighted: level.highlight,
599                icon_column,
600                first,
601                row_count: count,
602                path: level.path.clone(),
603                session: self.session,
604                rows: rows(menu)
605                    .skip(first)
606                    .take(visible)
607                    .map(|(index, row)| MenuRow {
608                        index,
609                        node: row,
610                        label: label(row),
611                        font_size: typography.size(row, DEFAULT_MENU_FONT_SIZE),
612                        icon: icon(row),
613                        shortcut: show_shortcuts
614                            .then(|| shortcut(row).map(|key| key.to_string()))
615                            .flatten(),
616                        enabled: enabled(row),
617                        separator: row.kind == "MenuSeparator",
618                        submenu: row.kind == "Menu",
619                        checked: row
620                            .boolean("checkable", false)
621                            .then(|| row.boolean("checked", false)),
622                    })
623                    .collect(),
624            };
625            let next = self
626                .levels
627                .get(index + 1)
628                .and_then(|child| child.path.last())
629                .copied();
630            let slot = panel
631                .rows
632                .iter()
633                .position(|row| Some(row.index) == next && row.submenu && row.enabled);
634            if let Some(slot) = slot {
635                anchor = panel.row_bounds(slot);
636            }
637            panels.push(panel);
638            parent_direction = direction;
639            if slot.is_none() {
640                break;
641            }
642        }
643        panels
644    }
645
646    pub fn reconcile(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
647        let viewport = menu_viewport(scene, layout);
648        let typography = layout.popup_typography();
649        for level in &mut self.levels {
650            let Some(menu) = menu_at(scene, self.text.as_ref(), &level.path) else {
651                break;
652            };
653            let count = rows(menu).count();
654            let visible =
655                Self::visible_count(viewport, count, row_height(menu, self.touch, typography));
656            level.first = level.first.min(count.saturating_sub(visible));
657            if !level.highlight.is_some_and(|index| {
658                menu.children
659                    .get(index)
660                    .is_some_and(|row| row.is_visible() && enabled(row))
661            }) {
662                let (first, limit) = if self.touch || level.scrolled {
663                    (level.first, visible)
664                } else {
665                    (0, count)
666                };
667                level.highlight = rows(menu)
668                    .skip(first)
669                    .take(limit)
670                    .find(|(_, row)| enabled(row))
671                    .map(|(index, _)| index);
672            }
673            if let Some(slot) = rows(menu).position(|(index, _)| Some(index) == level.highlight) {
674                level.first = level
675                    .first
676                    .max(slot.saturating_add(1).saturating_sub(visible))
677                    .min(slot);
678            }
679        }
680        let count = self.panels(scene, layout).len();
681        self.levels.truncate(count);
682        count != 0
683    }
684
685    pub fn hover(&mut self, scene: &Node, layout: &LayoutNode, point: Point) -> bool {
686        let panels = self.panels(scene, layout);
687        let Some((level, row)) = panels
688            .iter()
689            .enumerate()
690            .rev()
691            .find_map(|(level, panel)| panel.pick(point).map(|row| (level, row)))
692        else {
693            return false;
694        };
695        let index = row.index;
696        if !row.enabled || self.levels[level].highlight == Some(index) {
697            return false;
698        }
699        self.levels.truncate(level + 1);
700        self.levels[level].highlight = Some(index);
701        true
702    }
703
704    pub fn press(&mut self, scene: &Node, layout: &LayoutNode, point: Point) -> bool {
705        self.pressed = None;
706        self.hover(scene, layout, point);
707        let panels = self.panels(scene, layout);
708        let Some((level, row)) = panels
709            .iter()
710            .enumerate()
711            .rev()
712            .find_map(|(level, panel)| panel.pick(point).map(|row| (level, row)))
713        else {
714            return false;
715        };
716        if row.enabled {
717            self.pressed = Some(PressedItem {
718                level,
719                index: row.index,
720                label: row.label.into(),
721                kind: row.node.kind,
722                id: ElementId::of(row.node),
723                command: row.node.action,
724            });
725        }
726        true
727    }
728
729    pub fn release(
730        &mut self,
731        scene: &Node,
732        layout: &LayoutNode,
733        point: Point,
734    ) -> Option<Vec<usize>> {
735        let pressed = self.pressed.take()?;
736        let panels = self.panels(scene, layout);
737        let row = panels.get(pressed.level)?.pick(point)?;
738        if !row.enabled
739            || row.index != pressed.index
740            || row.label != pressed.label
741            || row.node.kind != pressed.kind
742            || row.node.element_id() != pressed.id.as_ref().map(ElementId::as_str)
743            || row.node.action != pressed.command
744        {
745            return None;
746        }
747        self.activate(scene, layout, pressed.level, pressed.index)
748    }
749
750    fn activate(
751        &mut self,
752        scene: &Node,
753        layout: &LayoutNode,
754        level: usize,
755        index: usize,
756    ) -> Option<Vec<usize>> {
757        let mut path = self.levels[level].path.clone();
758        if let Some(text) = &self.text {
759            let node = text.menu.children.get(index)?;
760            if !enabled(node) {
761                return None;
762            }
763            path.push(index);
764            return Some(path);
765        }
766        path.push(index);
767        let node = scene.interactive_at_path(&path)?;
768        match node.kind {
769            "MenuItem" => Some(path),
770            "Menu" => {
771                self.levels.truncate(level + 1);
772                self.levels.push(Level {
773                    path,
774                    first: 0,
775                    highlight: None,
776                    scrolled: false,
777                });
778                self.reconcile(scene, layout);
779                None
780            }
781            _ => None,
782        }
783    }
784
785    pub fn accessibility_entry(
786        &mut self,
787        scene: &Node,
788        layout: &LayoutNode,
789        trigger: &Target,
790        entry: &MenuEntry,
791        activate: bool,
792    ) -> Option<Vec<usize>> {
793        if &self.trigger != trigger || self.session != entry.session {
794            return None;
795        }
796        let (&index, parent) = entry.path.split_last()?;
797        let depth = self.panels(scene, layout).iter().position(|panel| {
798            panel.path == parent
799                && panel.rows.iter().any(|row| {
800                    row.enabled
801                        && row.index == index
802                        && row.label == entry.label
803                        && row.node.kind == entry.kind
804                })
805        })?;
806        self.pressed = None;
807        self.levels.truncate(depth + 1);
808        self.levels[depth].highlight = Some(index);
809        if activate {
810            self.activate(scene, layout, depth, index)
811        } else {
812            None
813        }
814    }
815
816    pub fn accessibility_close(
817        &mut self,
818        scene: &Node,
819        layout: &LayoutNode,
820        trigger: &Target,
821        path: &[usize],
822        session: u64,
823    ) -> Option<bool> {
824        if &self.trigger != trigger || self.session != session {
825            return None;
826        }
827        let depth = self
828            .panels(scene, layout)
829            .iter()
830            .position(|panel| panel.path == path)?;
831        self.pressed = None;
832        self.levels.truncate(depth);
833        Some(depth == 0)
834    }
835
836    pub fn accessibility_page(
837        &mut self,
838        scene: &Node,
839        layout: &LayoutNode,
840        trigger: &Target,
841        path: &[usize],
842        session: u64,
843        backward: bool,
844    ) -> bool {
845        if &self.trigger != trigger || self.session != session {
846            return false;
847        }
848        let panels = self.panels(scene, layout);
849        let Some((depth, panel)) = panels
850            .iter()
851            .enumerate()
852            .find(|(_, panel)| panel.path == path && panel.can_scroll(backward))
853        else {
854            return false;
855        };
856        let page = panel.rows.len() as isize;
857        self.pressed = None;
858        self.scroll_level(
859            scene,
860            layout,
861            depth,
862            if backward { -page } else { page },
863            backward,
864        )
865    }
866
867    pub fn enter_submenu(&mut self, scene: &Node, layout: &LayoutNode) -> bool {
868        let Some(level) = self.levels.last() else {
869            return false;
870        };
871        let Some(index) = level.highlight else {
872            return false;
873        };
874        if !menu_at(scene, self.text.as_ref(), &level.path)
875            .and_then(|menu| menu.children.get(index))
876            .is_some_and(|row| row.kind == "Menu" && row.is_visible() && enabled(row))
877        {
878            return false;
879        }
880        self.activate(scene, layout, self.levels.len() - 1, index);
881        true
882    }
883
884    pub fn key(&mut self, scene: &Node, layout: &LayoutNode, key: MenuKey) -> Option<Vec<usize>> {
885        let depth = self.levels.len().checked_sub(1)?;
886        let forward = self.forward_key(scene, layout);
887        let level = &mut self.levels[depth];
888        let menu = menu_at(scene, self.text.as_ref(), &level.path)?;
889        match key {
890            MenuKey::Accept => {
891                let index = level.highlight?;
892                return self.activate(scene, layout, depth, index);
893            }
894            MenuKey::Left | MenuKey::Right | MenuKey::Escape if depth > 0 && key != forward => {
895                self.levels.pop();
896            }
897            MenuKey::Up | MenuKey::Down | MenuKey::Home | MenuKey::End => {
898                let choices: Vec<_> = rows(menu)
899                    .filter(|(_, row)| enabled(row))
900                    .map(|(index, _)| index)
901                    .collect();
902                if choices.is_empty() {
903                    return None;
904                }
905                let current = choices
906                    .iter()
907                    .position(|index| Some(*index) == level.highlight);
908                let next = match key {
909                    MenuKey::Up => current.map_or(choices.len() - 1, |current| {
910                        (current + choices.len() - 1) % choices.len()
911                    }),
912                    MenuKey::Down => current.map_or(0, |current| (current + 1) % choices.len()),
913                    MenuKey::End => choices.len() - 1,
914                    _ => 0,
915                };
916                level.highlight = Some(choices[next]);
917                self.reconcile(scene, layout);
918            }
919            _ => {}
920        }
921        None
922    }
923
924    pub fn pan_at(&self, scene: &Node, layout: &LayoutNode, point: Point) -> Option<MenuPan> {
925        let panel = self
926            .panels(scene, layout)
927            .into_iter()
928            .rfind(|panel| panel.bounds.contains(point))?;
929        Some(MenuPan {
930            session: self.session,
931            path: panel.path,
932            remainder: 0.0,
933        })
934    }
935
936    pub fn scroll(
937        &mut self,
938        scene: &Node,
939        layout: &LayoutNode,
940        point: Option<Point>,
941        delta: isize,
942    ) {
943        let panels = self.panels(scene, layout);
944        let Some(depth) = panels
945            .iter()
946            .rposition(|panel| point.is_some_and(|point| panel.bounds.contains(point)))
947            .or_else(|| panels.len().checked_sub(1))
948        else {
949            return;
950        };
951        self.scroll_level(scene, layout, depth, delta, false);
952    }
953
954    fn scroll_level(
955        &mut self,
956        scene: &Node,
957        layout: &LayoutNode,
958        depth: usize,
959        delta: isize,
960        focus_last: bool,
961    ) -> bool {
962        let level = &mut self.levels[depth];
963        let Some(menu) = menu_at(scene, self.text.as_ref(), &level.path) else {
964            return false;
965        };
966        let count = rows(menu).count();
967        let visible = Self::visible_count(
968            menu_viewport(scene, layout),
969            count,
970            row_height(menu, self.touch, layout.popup_typography()),
971        );
972        let first = level.first;
973        let highlight = level.highlight;
974        level.first = first.saturating_add_signed(delta).min(count - visible);
975        level.scrolled |= level.first != first;
976        let mut choices = rows(menu)
977            .skip(level.first)
978            .take(visible)
979            .filter(|(_, row)| enabled(row))
980            .map(|(index, _)| index);
981        level.highlight = if focus_last {
982            choices.last()
983        } else {
984            choices.next()
985        };
986        let changed = level.first != first || level.highlight != highlight;
987        let removed = self.levels.len() > depth + 1;
988        self.levels.truncate(depth + 1);
989        changed || removed
990    }
991
992    pub fn input(&self, mut path: Vec<usize>) -> Option<ControlInput> {
993        let action = if self.text.is_some() {
994            let index = path.pop()?;
995            let (command, _, _) = TEXT_ENTRIES.get(index)?.as_ref()?;
996            ControlAction::TextCommand(*command)
997        } else {
998            ControlAction::ActivateMenuItem
999        };
1000        Some(ControlInput { path, action })
1001    }
1002
1003    pub fn text_shortcut(&self, key: MenuShortcut) -> Option<ControlInput> {
1004        let text = self.text.as_ref()?;
1005        let (index, _) =
1006            rows(&text.menu).find(|(_, row)| enabled(row) && shortcut(row) == Some(key))?;
1007        let mut path = self.trigger.path.clone();
1008        path.push(index);
1009        self.input(path)
1010    }
1011}
1012
1013#[cfg(test)]
1014mod tests {
1015    use super::*;
1016
1017    #[test]
1018    fn a_cascading_menu_prefers_the_inherited_side_and_fits_at_the_edge() {
1019        let viewport = Rect::new(4.0, 4.0, 420.0, 250.0);
1020        let rtl = LayoutDirection::RightToLeft;
1021        let ltr = LayoutDirection::LeftToRight;
1022        let width = 174.0;
1023        let middle = Rect::new(207.0, 40.0, 14.0, 28.0);
1024        assert_eq!(
1025            panel_bounds(middle, viewport, width, 56.0, true, rtl).x,
1026            33.0
1027        );
1028        assert_eq!(
1029            panel_bounds(middle, viewport, width, 56.0, true, ltr).x,
1030            221.0
1031        );
1032        let edge = Rect::new(6.0, 40.0, 174.0, 28.0);
1033        assert_eq!(
1034            panel_bounds(edge, viewport, width, 56.0, true, rtl).x,
1035            180.0
1036        );
1037        let far_edge = Rect::new(243.0, 40.0, 174.0, 28.0);
1038        assert_eq!(
1039            panel_bounds(far_edge, viewport, width, 56.0, true, ltr).x,
1040            69.0
1041        );
1042    }
1043}