Skip to main content

native_gui_core/
menus.rs

1use crate::artprov::IconRole;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
4pub struct MenuId(pub u64);
5
6impl MenuId {
7    /// Returns the raw numeric identifier.
8    pub const fn get(self) -> u64 {
9        self.0
10    }
11}
12
13impl std::fmt::Display for MenuId {
14    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
15        write!(f, "menu {}", self.0)
16    }
17}
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
20pub struct MenuItemId(pub u64);
21
22impl MenuItemId {
23    /// Returns the raw numeric identifier.
24    pub const fn get(self) -> u64 {
25        self.0
26    }
27}
28
29impl std::fmt::Display for MenuItemId {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        write!(f, "menu item {}", self.0)
32    }
33}
34
35/// In-memory specification and descriptor of one menu item.
36///
37/// Models native or simulated menu items across platforms: unique [`MenuItemId`],
38/// visible label text (with access-key mnemonics), optional keyboard accelerator
39/// shortcut (e.g. `"Ctrl+N"`), optional stock-art icon ([`IconRole`]), enabled/checked
40/// states, and visibility.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct MenuItemSpec {
43    /// Stable application-facing item identifier.
44    pub id: MenuItemId,
45    /// Visible text/label (also carries mnemonic access-key markers such as `&File`).
46    pub label: String,
47    /// Optional keyboard accelerator shortcut string (e.g. `"Ctrl+N"`).
48    pub shortcut: Option<String>,
49    /// Optional stock-art icon role resolved by the art provider.
50    pub icon: Option<IconRole>,
51    /// Whether the menu item can be activated.
52    pub enabled: bool,
53    /// Whether the menu item is visible.
54    pub visible: bool,
55    /// Whether the menu item supports a checked/toggle state.
56    pub checkable: bool,
57    /// Current checked state for checkable items.
58    pub checked: bool,
59    /// Optional submenu identifier attached to this item.
60    pub submenu: Option<MenuId>,
61}
62
63impl MenuItemSpec {
64    /// Creates an enabled, visible, plain menu item specification.
65    pub fn new(id: MenuItemId, label: impl Into<String>) -> Self {
66        Self {
67            id,
68            label: label.into(),
69            shortcut: None,
70            icon: None,
71            enabled: true,
72            visible: true,
73            checkable: false,
74            checked: false,
75            submenu: None,
76        }
77    }
78
79    /// Creates an unassigned menu item specification with a placeholder ID (0).
80    pub fn unassigned(label: impl Into<String>) -> Self {
81        Self::new(MenuItemId(0), label)
82    }
83
84    /// Sets the keyboard shortcut hint (e.g. `"Ctrl+N"`).
85    pub fn with_shortcut(mut self, shortcut: impl Into<String>) -> Self {
86        self.shortcut = Some(shortcut.into());
87        self
88    }
89
90    /// Sets the stock-art icon role.
91    pub fn with_icon(mut self, icon: IconRole) -> Self {
92        self.icon = Some(icon);
93        self
94    }
95
96    /// Sets or clears the stock-art icon role with an optional value.
97    pub fn with_optional_icon(mut self, icon: Option<IconRole>) -> Self {
98        self.icon = icon;
99        self
100    }
101
102    /// Sets the stock-art icon role from its stable identifier (e.g. `"new"`, `"open"`).
103    pub fn with_icon_identifier(mut self, identifier: &str) -> Self {
104        self.icon = IconRole::ALL
105            .iter()
106            .copied()
107            .find(|r| r.as_str() == identifier);
108        self
109    }
110
111    /// Sets the enabled state.
112    pub fn with_enabled(mut self, enabled: bool) -> Self {
113        self.enabled = enabled;
114        self
115    }
116
117    /// Sets the visibility state.
118    pub fn with_visible(mut self, visible: bool) -> Self {
119        self.visible = visible;
120        self
121    }
122
123    /// Marks the menu item as checkable.
124    pub fn with_checkable(mut self) -> Self {
125        self.checkable = true;
126        self
127    }
128
129    /// Sets the checked state (and marks the item as checkable).
130    pub fn with_checked(mut self, checked: bool) -> Self {
131        self.checkable = true;
132        self.checked = checked;
133        self
134    }
135
136    /// Sets the attached submenu id.
137    pub fn with_submenu(mut self, submenu: MenuId) -> Self {
138        self.submenu = Some(submenu);
139        self
140    }
141
142    /// Sets the visible label.
143    pub fn with_label(mut self, label: impl Into<String>) -> Self {
144        self.label = label.into();
145        self
146    }
147
148    /// Sets the visible text (alias for [`Self::with_label`]).
149    pub fn with_text(mut self, text: impl Into<String>) -> Self {
150        self.label = text.into();
151        self
152    }
153
154    /// Returns the item's identifier.
155    pub const fn id(&self) -> MenuItemId {
156        self.id
157    }
158
159    /// Returns the item's visible label.
160    pub fn label(&self) -> &str {
161        &self.label
162    }
163
164    /// Returns the item's text (alias for [`Self::label`]).
165    pub fn text(&self) -> &str {
166        &self.label
167    }
168
169    /// Sets the item's visible label.
170    pub fn set_label(&mut self, label: impl Into<String>) {
171        self.label = label.into();
172    }
173
174    /// Sets the item's visible text (alias for [`Self::set_label`]).
175    pub fn set_text(&mut self, text: impl Into<String>) {
176        self.label = text.into();
177    }
178
179    /// Returns the optional keyboard shortcut hint.
180    pub fn shortcut(&self) -> Option<&str> {
181        self.shortcut.as_deref()
182    }
183
184    /// Sets the optional keyboard shortcut.
185    pub fn set_shortcut(&mut self, shortcut: Option<String>) {
186        self.shortcut = shortcut;
187    }
188
189    /// Returns the assigned stock-art icon role, if any.
190    pub const fn icon(&self) -> Option<IconRole> {
191        self.icon
192    }
193
194    /// Returns the stable string identifier of the icon, if one is set.
195    pub fn icon_identifier(&self) -> Option<&'static str> {
196        self.icon.map(|r| r.as_str())
197    }
198
199    /// Sets or clears the stock-art icon role.
200    pub fn set_icon(&mut self, icon: Option<IconRole>) {
201        self.icon = icon;
202    }
203
204    /// Returns true if this menu item has an assigned stock-art icon.
205    pub const fn has_icon(&self) -> bool {
206        self.icon.is_some()
207    }
208
209    /// Returns true if this item is enabled.
210    pub const fn is_enabled(&self) -> bool {
211        self.enabled
212    }
213
214    /// Sets the enabled state.
215    pub fn set_enabled(&mut self, enabled: bool) {
216        self.enabled = enabled;
217    }
218
219    /// Returns true if this item is checkable.
220    pub const fn is_checkable(&self) -> bool {
221        self.checkable
222    }
223
224    /// Returns true if this item is currently checked.
225    pub const fn is_checked(&self) -> bool {
226        self.checked
227    }
228
229    /// Sets the checked state.
230    pub fn set_checked(&mut self, checked: bool) {
231        self.checked = checked;
232    }
233
234    /// Returns the attached submenu id, if any.
235    pub const fn submenu(&self) -> Option<MenuId> {
236        self.submenu
237    }
238
239    /// Returns the label translated to the specified lane access-key style.
240    pub fn translated_label(&self, style: AccessKeyStyle) -> String {
241        translate_access_keys(&self.label, style)
242    }
243}
244
245impl Default for MenuItemSpec {
246    fn default() -> Self {
247        Self {
248            id: MenuItemId(0),
249            label: String::new(),
250            shortcut: None,
251            icon: None,
252            enabled: true,
253            visible: true,
254            checkable: false,
255            checked: false,
256            submenu: None,
257        }
258    }
259}
260
261/// Type alias for [`MenuItemSpec`], serving as a descriptor for menu items.
262pub type MenuItemDescriptor = MenuItemSpec;
263
264/// An item or divider within a menu structure.
265#[derive(Debug, Clone, PartialEq, Eq)]
266pub enum MenuItem {
267    /// An actionable or checkable menu command.
268    Item(MenuItemSpec),
269    /// A visual divider separating item groups.
270    Separator,
271    /// A nested submenu grouping child items.
272    Submenu {
273        id: MenuId,
274        label: String,
275        icon: Option<IconRole>,
276        items: Vec<MenuItem>,
277    },
278}
279
280impl MenuItem {
281    /// Wraps a [`MenuItemSpec`] as a menu item.
282    pub fn item(spec: MenuItemSpec) -> Self {
283        Self::Item(spec)
284    }
285
286    /// Creates a visual separator item.
287    pub const fn separator() -> Self {
288        Self::Separator
289    }
290
291    /// Creates a submenu entry.
292    pub fn submenu(id: MenuId, label: impl Into<String>, items: Vec<MenuItem>) -> Self {
293        Self::Submenu {
294            id,
295            label: label.into(),
296            icon: None,
297            items,
298        }
299    }
300
301    /// Sets or replaces the icon role for an item or submenu.
302    pub fn with_icon(mut self, icon: IconRole) -> Self {
303        match &mut self {
304            Self::Item(spec) => {
305                spec.icon = Some(icon);
306            }
307            Self::Submenu { icon: sub_icon, .. } => {
308                *sub_icon = Some(icon);
309            }
310            Self::Separator => {}
311        }
312        self
313    }
314
315    /// Returns the icon role if present.
316    pub fn icon(&self) -> Option<IconRole> {
317        match self {
318            Self::Item(spec) => spec.icon,
319            Self::Submenu { icon, .. } => *icon,
320            Self::Separator => None,
321        }
322    }
323}
324
325impl From<MenuItemSpec> for MenuItem {
326    fn from(spec: MenuItemSpec) -> Self {
327        Self::Item(spec)
328    }
329}
330
331/// Specification for a menu or submenu hierarchy.
332#[derive(Debug, Clone, PartialEq, Eq, Default)]
333pub struct MenuSpec {
334    /// Unique menu identifier, if registered.
335    pub id: Option<MenuId>,
336    /// Optional menu title (for submenus or top-level bar items).
337    pub title: Option<String>,
338    /// Items contained within this menu.
339    pub items: Vec<MenuItemSpec>,
340}
341
342impl MenuSpec {
343    pub fn new() -> Self {
344        Self::default()
345    }
346
347    pub fn with_id(mut self, id: MenuId) -> Self {
348        self.id = Some(id);
349        self
350    }
351
352    pub fn with_title(mut self, title: impl Into<String>) -> Self {
353        self.title = Some(title.into());
354        self
355    }
356
357    pub fn with_item(mut self, item: MenuItemSpec) -> Self {
358        self.items.push(item);
359        self
360    }
361
362    pub fn add_item(&mut self, item: MenuItemSpec) {
363        self.items.push(item);
364    }
365}
366
367/// How a shared menu label renders its access-key marker.
368///
369/// The portable convention is the Win32-native spelling: a `&` before the
370/// mnemonic character, for example `"&File"` or `"New &Folder"`. `&&`
371/// escapes a literal ampersand. Backends translate the marker to their
372/// toolkit's spelling before creating the native menu item:
373///
374/// - Win32 supports the marker as written ([`AccessKeyStyle::Ampersand`])
375///   and Windows underlines the key and opens the menu with `Alt`.
376/// - GTK underlines the character after `_`, so the marker is rewritten
377///   ([`AccessKeyStyle::Underscore`]).
378/// - macOS menus carry no mnemonic underlines; the marker is stripped so a
379///   stray `&` never reaches the title ([`AccessKeyStyle::Plain`]).
380///
381/// A label without a marker passes through every style unchanged.
382#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
383pub enum AccessKeyStyle {
384    /// Keep the `&` marker as written (Win32 menus).
385    Ampersand,
386    /// Rewrite `&X` to `_X` (GTK menus).
387    Underscore,
388    /// Strip the marker (macOS menus).
389    Plain,
390}
391
392/// Translates a shared menu label's access-key marker to a lane style.
393///
394/// See [`AccessKeyStyle`] for the convention. The translation is
395/// deliberately total: labels without a marker are returned unchanged, `&&`
396/// always renders a literal `&`, and a trailing `&` stays as written.
397pub fn translate_access_keys(label: &str, style: AccessKeyStyle) -> String {
398    let marker = match style {
399        AccessKeyStyle::Ampersand => return label.to_owned(),
400        AccessKeyStyle::Underscore => Some('_'),
401        AccessKeyStyle::Plain => None,
402    };
403
404    let mut out = String::with_capacity(label.len());
405    let mut chars = label.chars().peekable();
406    while let Some(ch) = chars.next() {
407        if ch != '&' {
408            out.push(ch);
409            continue;
410        }
411        match chars.peek() {
412            Some('&') => {
413                // `&&` is the escape for a literal ampersand.
414                out.push('&');
415                chars.next();
416            }
417            Some(next) => {
418                if let Some(marker) = marker {
419                    out.push(marker);
420                }
421                let next = *next;
422                chars.next();
423                out.push(next);
424            }
425            None => out.push('&'),
426        }
427    }
428    out
429}
430
431#[cfg(test)]
432mod tests {
433    use super::{translate_access_keys, AccessKeyStyle};
434
435    #[test]
436    fn access_key_markers_translate_per_lane_style() {
437        assert_eq!(
438            translate_access_keys("&File", AccessKeyStyle::Ampersand),
439            "&File"
440        );
441        assert_eq!(
442            translate_access_keys("&File", AccessKeyStyle::Underscore),
443            "_File"
444        );
445        assert_eq!(
446            translate_access_keys("&File", AccessKeyStyle::Plain),
447            "File"
448        );
449        assert_eq!(
450            translate_access_keys("New &Folder", AccessKeyStyle::Underscore),
451            "New _Folder"
452        );
453        assert_eq!(
454            translate_access_keys("New &Folder", AccessKeyStyle::Plain),
455            "New Folder"
456        );
457    }
458
459    #[test]
460    fn access_key_translation_handles_escapes_and_plain_labels() {
461        // `&&` stays a literal ampersand in every style.
462        assert_eq!(
463            translate_access_keys("Find && Replace", AccessKeyStyle::Underscore),
464            "Find & Replace"
465        );
466        assert_eq!(
467            translate_access_keys("Find && Replace", AccessKeyStyle::Plain),
468            "Find & Replace"
469        );
470        // Labels without markers pass through untouched.
471        assert_eq!(
472            translate_access_keys("Refresh", AccessKeyStyle::Underscore),
473            "Refresh"
474        );
475        assert_eq!(
476            translate_access_keys("Refresh", AccessKeyStyle::Ampersand),
477            "Refresh"
478        );
479        // A trailing marker cannot reference a character; keep it literal.
480        assert_eq!(
481            translate_access_keys("Odd &", AccessKeyStyle::Underscore),
482            "Odd &"
483        );
484    }
485
486    #[test]
487    fn menu_item_spec_builder_and_icon_metadata() {
488        use crate::artprov::IconRole;
489        use crate::menus::{MenuItemId, MenuItemSpec};
490
491        let spec = MenuItemSpec::new(MenuItemId(1), "&New")
492            .with_shortcut("Ctrl+N")
493            .with_icon(IconRole::New)
494            .with_enabled(true)
495            .with_checkable()
496            .with_checked(false);
497
498        assert_eq!(spec.id(), MenuItemId(1));
499        assert_eq!(spec.label(), "&New");
500        assert_eq!(spec.text(), "&New");
501        assert_eq!(spec.shortcut(), Some("Ctrl+N"));
502        assert_eq!(spec.icon(), Some(IconRole::New));
503        assert_eq!(spec.icon_identifier(), Some("new"));
504        assert!(spec.has_icon());
505        assert!(spec.is_enabled());
506        assert!(spec.is_checkable());
507        assert!(!spec.is_checked());
508        assert_eq!(spec.translated_label(AccessKeyStyle::Underscore), "_New");
509        assert_eq!(spec.translated_label(AccessKeyStyle::Plain), "New");
510    }
511
512    #[test]
513    fn menu_item_descriptor_alias_and_icon_mutation() {
514        use crate::artprov::IconRole;
515        use crate::menus::{MenuItemDescriptor, MenuItemId};
516
517        let mut desc: MenuItemDescriptor = MenuItemDescriptor::new(MenuItemId(2), "Save");
518        assert_eq!(desc.icon(), None);
519        assert!(!desc.has_icon());
520        assert_eq!(desc.icon_identifier(), None);
521
522        desc.set_icon(Some(IconRole::Save));
523        assert_eq!(desc.icon(), Some(IconRole::Save));
524        assert_eq!(desc.icon_identifier(), Some("save"));
525        assert!(desc.has_icon());
526
527        desc.set_icon(None);
528        assert_eq!(desc.icon(), None);
529        assert!(!desc.has_icon());
530
531        let desc2 = desc.with_icon_identifier("open");
532        assert_eq!(desc2.icon(), Some(IconRole::Open));
533        assert_eq!(desc2.icon_identifier(), Some("open"));
534    }
535
536    #[test]
537    fn menu_item_all_stock_icon_roles_supported() {
538        use crate::artprov::IconRole;
539        use crate::menus::{MenuItemId, MenuItemSpec};
540
541        for &role in &IconRole::ALL {
542            let spec = MenuItemSpec::new(MenuItemId(100), "Action").with_icon(role);
543            assert_eq!(spec.icon(), Some(role));
544            assert_eq!(spec.icon_identifier(), Some(role.as_str()));
545            assert!(spec.has_icon());
546        }
547    }
548
549    #[test]
550    fn menu_structure_composition_with_icons() {
551        use crate::artprov::IconRole;
552        use crate::menus::{MenuId, MenuItem, MenuItemId, MenuItemSpec, MenuSpec};
553
554        let item1 = MenuItemSpec::new(MenuItemId(10), "Cut")
555            .with_shortcut("Ctrl+X")
556            .with_icon(IconRole::Delete);
557        let item2 = MenuItemSpec::new(MenuItemId(11), "Copy")
558            .with_shortcut("Ctrl+C")
559            .with_icon(IconRole::Copy);
560
561        let menu_item1 = MenuItem::item(item1.clone());
562        assert_eq!(menu_item1.icon(), Some(IconRole::Delete));
563
564        let sep = MenuItem::separator();
565        assert_eq!(sep.icon(), None);
566
567        let submenu = MenuItem::submenu(MenuId(2), "More", vec![MenuItem::item(item2.clone())])
568            .with_icon(IconRole::Preferences);
569        assert_eq!(submenu.icon(), Some(IconRole::Preferences));
570
571        let menu_spec = MenuSpec::new()
572            .with_id(MenuId(1))
573            .with_title("Edit")
574            .with_item(item1)
575            .with_item(item2);
576        assert_eq!(menu_spec.items.len(), 2);
577        assert_eq!(menu_spec.items[0].icon, Some(IconRole::Delete));
578        assert_eq!(menu_spec.items[1].icon, Some(IconRole::Copy));
579    }
580}