Skip to main content

hypersig_desktop/
menu.rs

1//! The menu bar: the menus the application builds with [`Menu`], and on
2//! macOS the application, Edit, and Window menus around them.
3//!
4//! macOS sends Command-C, Command-V, and the other editing shortcuts to the
5//! menu, not to the web view, so without the Edit menu a text field takes no
6//! pasted text. Windows and Linux hand those keys to the web view themselves.
7
8use crate::item::MenuItem;
9
10/// A menu of the menu bar, for [`Os::menus`](crate::Os::menus).
11#[derive(Debug, Clone)]
12#[must_use = "a menu shows only when it is given to `Os::menus`"]
13pub struct Menu {
14    pub(crate) title: String,
15    pub(crate) entries: Vec<Entry>,
16}
17
18/// One line of a [`Menu`].
19#[derive(Debug, Clone)]
20pub(crate) enum Entry {
21    Item(MenuItem),
22    Separator,
23}
24
25impl Menu {
26    /// A menu titled `title`, such as "File", with no items yet.
27    pub fn new(title: impl Into<String>) -> Self {
28        Self {
29            title: title.into(),
30            entries: Vec::new(),
31        }
32    }
33
34    /// Adds `item` below the entries added before it.
35    pub fn item(mut self, item: &MenuItem) -> Self {
36        self.entries.push(Entry::Item(item.clone()));
37        self
38    }
39
40    /// Adds a line between the entries before it and those after it.
41    pub fn separator(mut self) -> Self {
42        self.entries.push(Entry::Separator);
43        self
44    }
45
46    /// The title the menu shows in the menu bar.
47    #[must_use]
48    pub fn title(&self) -> &str {
49        &self.title
50    }
51
52    /// The labels of the menu's items, in order, without the separators.
53    #[must_use]
54    pub fn labels(&self) -> Vec<&str> {
55        self.items().map(|item| item.label.as_str()).collect()
56    }
57
58    /// The menu's items, in order.
59    pub(crate) fn items(&self) -> impl Iterator<Item = &MenuItem> {
60        self.entries.iter().filter_map(|entry| match entry {
61            Entry::Item(item) => Some(item),
62            Entry::Separator => None,
63        })
64    }
65}
66
67#[cfg(target_os = "macos")]
68pub(crate) use system::QUIT;
69#[cfg(any(target_os = "macos", target_os = "linux"))]
70pub(crate) use system::bar;
71#[cfg(target_os = "linux")]
72pub(crate) use system::{attach, detach};
73
74/// The menu bar as muda builds it, on the systems where this crate shows one.
75#[cfg(any(target_os = "macos", target_os = "linux"))]
76mod system {
77    use muda::{MenuItem as SystemItem, PredefinedMenuItem, Submenu};
78
79    use super::{Entry, Menu};
80    use crate::error::Error;
81
82    /// The id of the item that quits, which the event loop answers.
83    #[cfg(target_os = "macos")]
84    pub(crate) const QUIT: &str = "hypersig-desktop-quit";
85
86    /// The menu bar holding `menus`, and on macOS the application and Edit
87    /// menus before them and the Window menu after them. The menu bar lasts
88    /// as long as the returned value.
89    ///
90    /// On macOS, quitting is an item of its own instead of the one macOS
91    /// provides, which ends the process at once, so that it stops the server
92    /// as closing the window does.
93    pub(crate) fn bar(menus: &[Menu]) -> Result<muda::Menu, Error> {
94        let bar = muda::Menu::new();
95        #[cfg(target_os = "macos")]
96        for leading in [application()?, edit()?] {
97            bar.append(&leading).map_err(Error::window)?;
98        }
99        for menu in menus {
100            bar.append(&submenu(menu)?).map_err(Error::window)?;
101        }
102        #[cfg(target_os = "macos")]
103        bar.append(&window()?).map_err(Error::window)?;
104        #[cfg(target_os = "macos")]
105        bar.init_for_nsapp();
106        Ok(bar)
107    }
108
109    /// Puts `bar` at the top of `window`, above the web view, unless it
110    /// holds no menu.
111    #[cfg(target_os = "linux")]
112    pub(crate) fn attach(bar: &muda::Menu, window: &tao::window::Window) {
113        use tao::platform::unix::WindowExtUnix as _;
114        if bar.items().is_empty() {
115            return;
116        }
117        if let Err(error) = bar.init_for_gtk_window(window.gtk_window(), window.default_vbox()) {
118            tracing::error!(%error, "the menu bar was not put in a window");
119        }
120    }
121
122    /// Takes `bar` out of `window`, where [`attach`] put it.
123    #[cfg(target_os = "linux")]
124    pub(crate) fn detach(bar: &muda::Menu, window: &tao::window::Window) {
125        use tao::platform::unix::WindowExtUnix as _;
126        if !bar.items().is_empty() {
127            let _ = bar.remove_for_gtk_window(window.gtk_window());
128        }
129    }
130
131    /// `menu` as a submenu of the bar.
132    fn submenu(menu: &Menu) -> Result<Submenu, Error> {
133        let submenu = Submenu::new(&menu.title, true);
134        for entry in &menu.entries {
135            match entry {
136                Entry::Item(item) => submenu
137                    .append(&SystemItem::with_id(
138                        item.id.clone(),
139                        &item.label,
140                        true,
141                        None,
142                    ))
143                    .map_err(Error::window)?,
144                Entry::Separator => submenu
145                    .append(&PredefinedMenuItem::separator())
146                    .map_err(Error::window)?,
147            }
148        }
149        Ok(submenu)
150    }
151
152    #[cfg(target_os = "macos")]
153    fn application() -> Result<Submenu, Error> {
154        let quit = SystemItem::with_id(
155            QUIT,
156            "Quit",
157            true,
158            Some(
159                "CmdOrCtrl+Q"
160                    .parse::<muda::accelerator::Accelerator>()
161                    .expect("CmdOrCtrl+Q is an accelerator"),
162            ),
163        );
164        Submenu::with_items(
165            "",
166            true,
167            &[
168                &PredefinedMenuItem::hide(None),
169                &PredefinedMenuItem::hide_others(None),
170                &PredefinedMenuItem::show_all(None),
171                &PredefinedMenuItem::separator(),
172                &quit,
173            ],
174        )
175        .map_err(Error::window)
176    }
177
178    #[cfg(target_os = "macos")]
179    fn edit() -> Result<Submenu, Error> {
180        Submenu::with_items(
181            "Edit",
182            true,
183            &[
184                &PredefinedMenuItem::undo(None),
185                &PredefinedMenuItem::redo(None),
186                &PredefinedMenuItem::separator(),
187                &PredefinedMenuItem::cut(None),
188                &PredefinedMenuItem::copy(None),
189                &PredefinedMenuItem::paste(None),
190                &PredefinedMenuItem::select_all(None),
191            ],
192        )
193        .map_err(Error::window)
194    }
195
196    #[cfg(target_os = "macos")]
197    fn window() -> Result<Submenu, Error> {
198        Submenu::with_items(
199            "Window",
200            true,
201            &[
202                &PredefinedMenuItem::minimize(None),
203                &PredefinedMenuItem::close_window(None),
204            ],
205        )
206        .map_err(Error::window)
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use super::Menu;
213    use crate::MenuItem;
214
215    #[test]
216    fn a_menu_keeps_its_items_in_order_without_the_separators() {
217        let open = MenuItem::new("Open");
218        let save = MenuItem::new("Save");
219        let file = Menu::new("File").item(&open).separator().item(&save);
220        assert_eq!(file.title(), "File");
221        assert_eq!(file.labels(), ["Open", "Save"]);
222    }
223}