Skip to main content

egui_pop_model/
menus.rs

1//! Menus are declared, never drawn by whoever fills them: a menu is an id
2//! (`app.main`, `panel.tab`) to which the shell, a panel or a plugin
3//! contributes items. An item names a command (its title and keys come
4//! from the command and the keymap, so a menu never shows a key that does
5//! not work), a submenu, or a list the application fills when the menu
6//! opens (the themes, the recent files). Items sit in groups, separated
7//! when shown, and in an order within their group; a `when` clause hides
8//! or greys an item, a `checked` clause ticks it. A radio item
9//! ([`MenuItem::radio`]) is one choice of a group: its `checked` clause
10//! says whether it is the chosen one, shown with a dot instead of a tick.
11
12use serde::Serialize;
13use serde_json::Value as Json;
14
15use crate::ids::{CommandId, MenuId, OwnerId};
16use crate::registry::OwnedList;
17use crate::when::{When, WhenContext};
18
19/// What an item is.
20#[derive(Clone, Debug, PartialEq, Serialize)]
21#[serde(tag = "kind", rename_all = "lowercase")]
22pub enum Item {
23    /// A command, with the arguments it runs with, and a label of its
24    /// own (else the command's title).
25    Command {
26        id: CommandId,
27        args: Json,
28        #[serde(skip_serializing_if = "Option::is_none")]
29        label: Option<String>,
30    },
31    /// Another menu, shown under a label.
32    Submenu { menu: MenuId, label: String },
33    /// Entries the application makes when the menu opens.
34    List { name: String },
35}
36
37/// One contribution to a menu.
38#[derive(Clone, Debug, PartialEq, Serialize)]
39pub struct MenuItem {
40    pub menu: MenuId,
41    pub item: Item,
42    /// Items of a group are shown together; groups are separated and
43    /// ordered by name (`1_open`, `2_preferences`).
44    pub group: String,
45    pub order: i32,
46    /// Where it applies; empty: everywhere.
47    pub when: String,
48    /// Greyed rather than hidden when `when` does not hold.
49    pub grey: bool,
50    /// When it shows ticked; empty: never.
51    pub checked: String,
52    /// One choice of a group (a dot when chosen) rather than a toggle (a
53    /// tick); its `checked` clause says whether it is the chosen one.
54    #[serde(skip_serializing_if = "std::ops::Not::not")]
55    pub radio: bool,
56}
57
58impl MenuItem {
59    pub fn command(menu: MenuId, group: &str, order: i32, id: CommandId) -> Self {
60        Self {
61            menu,
62            item: Item::Command {
63                id,
64                args: Json::Null,
65                label: None,
66            },
67            group: group.into(),
68            order,
69            when: String::new(),
70            grey: true,
71            checked: String::new(),
72            radio: false,
73        }
74    }
75
76    pub fn submenu(menu: MenuId, group: &str, order: i32, sub: MenuId, label: &str) -> Self {
77        Self {
78            menu,
79            item: Item::Submenu {
80                menu: sub,
81                label: label.into(),
82            },
83            group: group.into(),
84            order,
85            when: String::new(),
86            grey: true,
87            checked: String::new(),
88            radio: false,
89        }
90    }
91
92    pub fn list(menu: MenuId, group: &str, order: i32, name: &str) -> Self {
93        Self {
94            item: Item::List { name: name.into() },
95            ..Self::submenu(menu.clone(), group, order, menu, "")
96        }
97    }
98
99    pub fn args(mut self, args: Json) -> Self {
100        if let Item::Command { args: a, .. } = &mut self.item {
101            *a = args;
102        }
103        self
104    }
105
106    /// Its own label (a command run with arguments: `50%`), instead of
107    /// the command's title.
108    pub fn label(mut self, label: &str) -> Self {
109        if let Item::Command { label: l, .. } = &mut self.item {
110            *l = Some(label.into());
111        }
112        self
113    }
114
115    pub fn when(mut self, when: &str, grey: bool) -> Self {
116        self.when = when.into();
117        self.grey = grey;
118        self
119    }
120
121    pub fn checked(mut self, when: &str) -> Self {
122        self.checked = when.into();
123        self
124    }
125
126    /// A radio item: one choice of a group, chosen while `when` holds
127    /// (`zoom == '100'`), shown with a dot instead of a tick. The items of
128    /// a group sit together; their clauses pick one of them.
129    pub fn radio(mut self, when: &str) -> Self {
130        self.checked = when.into();
131        self.radio = true;
132        self
133    }
134}
135
136/// An item as a menu shows it in a context.
137#[derive(Clone, Debug, PartialEq, Serialize)]
138#[serde(tag = "shown", rename_all = "lowercase")]
139pub enum Shown {
140    Item {
141        item: Item,
142        enabled: bool,
143        checked: bool,
144        /// It has a `checked` clause: a toggle, ticked or not.
145        checkable: bool,
146        /// A radio item: a dot when checked, never a tick.
147        #[serde(skip_serializing_if = "std::ops::Not::not")]
148        radio: bool,
149    },
150    Separator,
151}
152
153/// The menu contributions, each owned.
154#[derive(Debug, Default)]
155pub struct Menus {
156    items: OwnedList<MenuItem>,
157}
158
159/// Sorts items as menus show them: by group, then order.
160pub fn sort_items(items: &mut [MenuItem]) {
161    items.sort_by(|a, b| (&a.group, a.order).cmp(&(&b.group, b.order)));
162}
163
164/// The items of one menu in a context: groups in order, separated, items
165/// hidden or greyed by their `when`.
166pub fn show_items(items: &[MenuItem], cx: &WhenContext) -> Vec<Shown> {
167    let holds = |clause: &str| clause.is_empty() || When::parse(clause).is_ok_and(|w| w.eval(cx));
168    let mut items: Vec<&MenuItem> = items.iter().collect();
169    items.sort_by(|a, b| (&a.group, a.order).cmp(&(&b.group, b.order)));
170    let mut out = Vec::new();
171    let mut group: Option<&str> = None;
172    for i in items {
173        let applies = holds(&i.when);
174        if !applies && !i.grey {
175            continue;
176        }
177        if group.is_some_and(|g| g != i.group) {
178            out.push(Shown::Separator);
179        }
180        group = Some(&i.group);
181        out.push(Shown::Item {
182            item: i.item.clone(),
183            enabled: applies,
184            checked: !i.checked.is_empty() && holds(&i.checked),
185            checkable: !i.checked.is_empty(),
186            radio: i.radio,
187        });
188    }
189    out
190}
191
192impl Menus {
193    pub fn new() -> Self {
194        Self::default()
195    }
196
197    /// Adds an item; its clauses must parse.
198    pub fn contribute(&mut self, owner: &OwnerId, item: MenuItem) -> Result<(), String> {
199        for clause in [&item.when, &item.checked] {
200            When::parse(clause).map_err(|e| format!("menu `{}`: {e}", item.menu))?;
201        }
202        self.items.push(owner, item);
203        Ok(())
204    }
205
206    /// The items of a menu as declared, in contribution order.
207    pub fn items(&self, menu: &MenuId) -> Vec<MenuItem> {
208        self.items
209            .iter()
210            .filter(|s| s.item.menu == *menu)
211            .map(|s| s.item.clone())
212            .collect()
213    }
214
215    /// The items of a menu in a context.
216    pub fn show(&self, menu: &MenuId, cx: &WhenContext) -> Vec<Shown> {
217        show_items(&self.items(menu), cx)
218    }
219
220    /// Every menu id contributed to.
221    pub fn ids(&self) -> Vec<MenuId> {
222        let mut v: Vec<MenuId> = self.items.iter().map(|s| s.item.menu.clone()).collect();
223        v.sort();
224        v.dedup();
225        v
226    }
227
228    /// Removes an owner's items running a command; returns how many.
229    pub fn remove_command(&mut self, owner: &OwnerId, command: &CommandId) -> usize {
230        let before = self.items.len();
231        self.items.retain(|s| {
232            !(s.owner == *owner
233                && matches!(&s.item.item, Item::Command { id, .. } if id == command))
234        });
235        before - self.items.len()
236    }
237
238    /// Removes an owner's items; returns how many.
239    pub fn remove_owner(&mut self, owner: &OwnerId) -> usize {
240        self.items.remove_owner(owner)
241    }
242
243    pub fn len(&self) -> usize {
244        self.items.len()
245    }
246
247    pub fn is_empty(&self) -> bool {
248        self.items.is_empty()
249    }
250}