craft-menu: the menu model is plain data, from_items groups rows in one pass, tidy works in place

This commit is contained in:
aiongg
2026-11-20 18:16:52 +00:00
parent 47379d792c
commit 49758ecee8
3 changed files with 76 additions and 66 deletions
+4 -2
View File
@@ -389,7 +389,9 @@ fn shown_on(bar: &MenuBar, target: Target) -> MenuBar {
Node::Standard { .. } if !appkit => None,
other => Some(other.clone()),
});
tidy(shown.collect())
let mut kept: Vec<Node> = shown.collect();
tidy(&mut kept);
kept
}
let on = target.platforms();
let menus = bar.menus.iter().map(|m| Menu { children: keep(&m.children, on, target == Target::Mac), ..m.clone() }).collect();
@@ -428,7 +430,7 @@ fn ensure_menu<'b>(bar: &'b mut MenuBar, role: MenuRole, english: &'static str,
/// Tidy every menu and drop the ones the moves emptied, unless `keep_empty`.
fn finish(bar: &mut MenuBar, keep_empty: impl Fn(&Menu) -> bool) {
for m in &mut bar.menus {
m.children = tidy(std::mem::take(&mut m.children));
tidy(&mut m.children);
}
bar.menus.retain(|m| !m.children.is_empty() || keep_empty(m));
}
+68 -62
View File
@@ -1,6 +1,7 @@
//! The menu tree, the flat rows it can be built from, and the keys that tell a backend what
//! changed.
use std::collections::HashMap;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::ops::BitOr;
@@ -8,7 +9,7 @@ use craft_keymap::{Chord, CommandRef, Mods};
use craft_theme::Srgba;
/// The app's menus, in order, and its open documents.
#[derive(Clone, Debug, Default, PartialEq, craft_ui::contract::MemoProps)]
#[derive(Clone, Debug, Default, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
#[non_exhaustive]
pub struct MenuBar {
/// The top-level menus, left to right.
@@ -18,7 +19,7 @@ pub struct MenuBar {
}
/// An open document, listed in the Window menu.
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
#[non_exhaustive]
pub struct Document {
/// What choosing it runs (bring the document to the front).
@@ -51,7 +52,7 @@ impl Document {
}
/// A top-level menu.
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
#[non_exhaustive]
pub struct Menu {
/// The title in the bar.
@@ -64,7 +65,7 @@ pub struct Menu {
/// What a top-level menu is for, set by the app. macOS treats the app, Window and Help menus
/// specially; File is where the system Close Window item goes.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
#[non_exhaustive]
pub enum MenuRole {
/// Any menu without a fixed place.
@@ -85,7 +86,7 @@ pub enum MenuRole {
}
/// The platforms an item or submenu is shown on. All of them by default.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
pub struct Platforms(u8);
impl Platforms {
@@ -132,7 +133,7 @@ impl BitOr for Platforms {
}
/// One entry of a menu.
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
#[non_exhaustive]
pub enum Node {
/// An item the user can choose.
@@ -162,7 +163,7 @@ pub enum Node {
}
/// One menu item: a command with its label, shortcut and state.
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
#[non_exhaustive]
pub struct Item {
/// What the item runs: the app's command (`file.open`), with its parameters
@@ -198,7 +199,7 @@ pub struct Item {
/// The command a row runs while `mods` are held as it is chosen (Alt on Merge Visible runs Stamp
/// Visible).
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)]
#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
#[non_exhaustive]
pub struct Alternate {
/// The modifiers that select the alternate.
@@ -222,7 +223,7 @@ impl Alternate {
}
/// A plain item, or one with a checked state.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
#[non_exhaustive]
pub enum ItemKind {
/// An ordinary item.
@@ -247,7 +248,7 @@ impl ItemKind {
/// Items the layouts put in fixed places. The app tags its own About, Settings, Quit, Appearance
/// and Language items; the Mac layout adds Hide and Minimize.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
#[non_exhaustive]
pub enum ItemRole {
/// The About item.
@@ -268,7 +269,7 @@ pub enum ItemRole {
}
/// The items AppKit provides.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
#[non_exhaustive]
pub enum Standard {
#[allow(missing_docs)]
@@ -307,7 +308,7 @@ pub(crate) fn label_or_system(label: &str, english: &str, system: impl FnOnce(&s
/// The commands of the items the crate adds itself. The crate runs them; an app sees them only
/// in a layout's result.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)]
#[non_exhaustive]
pub enum Builtin {
/// Hide the app: a custom item, because AppKit's own always takes ⌘H, which apps often bind.
@@ -653,73 +654,78 @@ impl Row {
/// The menus as a tree, from flat rows, in the order an in-window bar draws them: one menu per
/// entry of `tops`, and at each depth leaves and separators in order, with a submenu where its
/// first row is. The result is [`tidy`].
/// first row is. The result is [`tidy`]. Each row is visited once per depth of its path.
pub fn from_items(tops: &[&str], rows: &[Row]) -> MenuBar {
/// One entry of a level in order: a row of the level itself, or the group of rows under a submenu name.
enum Slot<'r> {
Leaf(&'r Row),
Group(&'r str, Vec<&'r Row>),
}
fn level(rows: &[&Row], depth: usize) -> Vec<Node> {
let mut out = Vec::new();
let mut shown: Vec<&str> = Vec::new();
let mut slots: Vec<Slot<'_>> = Vec::new();
let mut groups: HashMap<&str, usize> = HashMap::new();
for it in rows {
if it.path.len() == depth {
if it.label == "---" {
out.push(Node::Separator);
} else {
out.push(Node::Item(Item {
shortcut: it.shortcut,
enabled: it.enabled,
kind: it.kind,
tint: it.tint,
tooltip: it.tooltip.clone(),
alternate: it.alternate.clone(),
..Item::new(it.command.clone(), it.label.clone())
}));
}
slots.push(Slot::Leaf(it));
} else if let Some(name) = it.path.get(depth) {
let name = name.as_str();
if shown.contains(&name) {
continue;
let at = *groups.entry(name.as_str()).or_insert_with(|| {
slots.push(Slot::Group(name.as_str(), Vec::new()));
slots.len() - 1
});
if let Slot::Group(_, members) = &mut slots[at] {
members.push(it);
}
shown.push(name);
let child: Vec<&Row> = rows.iter().copied().filter(|c| c.path.get(depth).map(String::as_str) == Some(name)).collect();
out.push(Node::submenu(name, level(&child, depth + 1)));
}
}
tidy(out)
let mut out = Vec::with_capacity(slots.len());
for slot in slots {
match slot {
Slot::Leaf(it) if it.label == "---" => out.push(Node::Separator),
Slot::Leaf(it) => out.push(Node::Item(Item {
shortcut: it.shortcut,
enabled: it.enabled,
kind: it.kind,
tint: it.tint,
tooltip: it.tooltip.clone(),
alternate: it.alternate.clone(),
..Item::new(it.command.clone(), it.label.clone())
})),
Slot::Group(name, members) => out.push(Node::submenu(name, level(&members, depth + 1))),
}
}
tidy(&mut out);
out
}
let menus = tops
.iter()
.map(|top| {
let rows: Vec<&Row> = rows.iter().filter(|r| r.path.first().map(String::as_str) == Some(*top)).collect();
Menu::new(*top, level(&rows, 1))
})
.collect();
let mut by_top: HashMap<&str, Vec<&Row>> = HashMap::new();
for row in rows {
if let Some(top) = row.path.first() {
by_top.entry(top.as_str()).or_default().push(row);
}
}
let menus = tops.iter().map(|top| Menu::new(*top, level(by_top.get(top).map_or(&[][..], Vec::as_slice), 1))).collect();
MenuBar { menus, documents: Vec::new() }
}
/// Drop separators at the start or end of a level and collapse runs of them, and drop empty
/// submenus, at every depth. A submenu holding only a disabled placeholder (`No Recent Files`)
/// submenus, at every depth, in place. A submenu holding only a disabled placeholder (`No Recent Files`)
/// stays.
pub fn tidy(nodes: Vec<Node>) -> Vec<Node> {
let mut out: Vec<Node> = Vec::with_capacity(nodes.len());
for n in nodes {
let n = match n {
Node::Submenu { label, children, role, platforms } => {
let children = tidy(children);
if children.is_empty() {
continue;
}
Node::Submenu { label, children, role, platforms }
pub fn tidy(nodes: &mut Vec<Node>) {
let mut previous_separator = true;
nodes.retain_mut(|node| {
if let Node::Submenu { children, .. } = node {
tidy(children);
if children.is_empty() {
return false;
}
other => other,
};
if matches!(n, Node::Separator) && matches!(out.last(), None | Some(Node::Separator)) {
continue;
}
out.push(n);
let separator = matches!(node, Node::Separator);
let keep = !(separator && previous_separator);
previous_separator = separator;
keep
});
while matches!(nodes.last(), Some(Node::Separator)) {
nodes.pop();
}
while matches!(out.last(), Some(Node::Separator)) {
out.pop();
}
out
}
/// A hash of everything a native menu can only change by rebuilding: menus, roles, item
+4 -2
View File
@@ -131,7 +131,8 @@ impl ThemeMenu {
nodes.extend(self.mode_groups(|_| true));
nodes.push(Node::Separator);
nodes.push(Node::Item(Item::new(ThemeChoice::NextMode.command(), labels.toggle.as_str())));
tidy(nodes)
tidy(&mut nodes);
nodes
}
/// The rows for a quick menu: the Appearance Settings row running `settings`, then the
@@ -139,7 +140,8 @@ impl ThemeMenu {
pub fn favorite_items(&self, labels: &ThemeLabels, settings: CommandRef) -> Vec<Node> {
let mut nodes = vec![Node::Item(Item::new(settings, labels.settings.as_str())), Node::Separator];
nodes.extend(self.mode_groups(|r| self.favorites.contains(&r.id)));
tidy(nodes)
tidy(&mut nodes);
nodes
}
/// The "Appearance" submenu, tagged [`crate::ItemRole::Appearance`].