Skip to main content

waft_test/
menus.rs

1//! The system's menus in memory, as a host draws none: a menu bar and a Dock menu that keep what
2//! the framework set, menus opened at a point or at a tray icon that keep what they were shown and
3//! answer the choice the test gave, and tray icons that keep their image, tooltip and attached
4//! menu while they are there. A test chooses an item of the menu bar as the user would through
5//! the client's `menu_selected`. The menu bar keeps the keys the app offers it, and takes those
6//! whose key is one of the shortcuts the test gave.
7
8use std::cell::{Cell, RefCell};
9use std::rc::Rc;
10
11use waft_embedder::{
12    AttachedMenu, DockMenu, IconImage, KeyData, KeyEventType, MenuAtIcon, MenuBar, MenuEntry,
13    MenuId, MenuShortcut, Offset, PopupMenuFuture, PopupMenus, TrayIcon, TrayIconError,
14    TrayIconFuture, TrayIconId, TrayIcons, ViewId,
15};
16
17/// A menu bar that keeps the menus last set. Every clone is the same menu bar.
18#[derive(Clone, Default)]
19pub struct MockMenuBar(Rc<RefCell<MenuBarState>>);
20
21#[derive(Default)]
22struct MenuBarState {
23    menus: Vec<MenuEntry>,
24    sets: usize,
25    /// The shortcuts whose keys the menu bar takes.
26    shortcuts: Vec<MenuShortcut>,
27    /// The keys offered, in order.
28    offered: Vec<KeyData>,
29}
30
31impl MockMenuBar {
32    pub fn new() -> MockMenuBar {
33        MockMenuBar::default()
34    }
35
36    /// A menu bar that takes a key-down offered (`perform_key_equivalent`) whose logical key is
37    /// one of `shortcuts`' keys. A key's data carries no modifiers, which a host's menu bar reads
38    /// from the system's own event, so the mock matches the key alone.
39    pub fn taking(self, shortcuts: impl IntoIterator<Item = MenuShortcut>) -> MockMenuBar {
40        self.0.borrow_mut().shortcuts = shortcuts.into_iter().collect();
41        self
42    }
43
44    /// The keys offered, in order, taken or not.
45    pub fn offered(&self) -> Vec<KeyData> {
46        self.0.borrow().offered.clone()
47    }
48
49    /// The menus last set.
50    pub fn menus(&self) -> Vec<MenuEntry> {
51        self.0.borrow().menus.clone()
52    }
53
54    /// How many times the menus were set.
55    pub fn sets(&self) -> usize {
56        self.0.borrow().sets
57    }
58
59    /// The id of the entry reached by `path`, its labels from a top-level menu down, as the user
60    /// finds it.
61    pub fn id_of(&self, path: &[&str]) -> Option<MenuId> {
62        id_at(&self.0.borrow().menus, path)
63    }
64}
65
66/// The id of the entry of `entries` reached by `path`'s labels.
67fn id_at(entries: &[MenuEntry], path: &[&str]) -> Option<MenuId> {
68    let (first, rest) = path.split_first()?;
69    entries.iter().find_map(|entry| match entry {
70        MenuEntry::Submenu {
71            id, label, entries, ..
72        } if label == first => {
73            if rest.is_empty() {
74                Some(*id)
75            } else {
76                id_at(entries, rest)
77            }
78        }
79        MenuEntry::Item { id, item } if item.label == *first && rest.is_empty() => Some(*id),
80        _ => None,
81    })
82}
83
84impl MenuBar for MockMenuBar {
85    fn set_menus(&self, menus: &[MenuEntry]) {
86        let mut state = self.0.borrow_mut();
87        state.menus = menus.to_vec();
88        state.sets += 1;
89    }
90
91    fn perform_key_equivalent(&self, key: &KeyData) -> bool {
92        let mut state = self.0.borrow_mut();
93        state.offered.push(key.clone());
94        key.event_type != KeyEventType::Up
95            && state
96                .shortcuts
97                .iter()
98                .any(|shortcut| shortcut.key == key.logical)
99    }
100}
101
102/// A Dock menu that keeps the menu last set. Every clone is the same menu.
103#[derive(Clone, Default)]
104pub struct MockDockMenu(Rc<RefCell<Vec<MenuEntry>>>);
105
106impl MockDockMenu {
107    pub fn new() -> MockDockMenu {
108        MockDockMenu::default()
109    }
110
111    /// The menu last set.
112    pub fn menu(&self) -> Vec<MenuEntry> {
113        self.0.borrow().clone()
114    }
115}
116
117impl DockMenu for MockDockMenu {
118    fn set_menu(&self, menu: &[MenuEntry]) {
119        *self.0.borrow_mut() = menu.to_vec();
120    }
121}
122
123/// One menu the framework opened at a point in a view.
124#[derive(Clone, Debug, PartialEq)]
125pub struct ShownMenu {
126    pub view: ViewId,
127    pub at: Offset,
128    pub menu: Vec<MenuEntry>,
129}
130
131/// Menus opened at a point, each answered at once with the choice the test gave, and kept. Every
132/// clone is the same.
133#[derive(Clone, Default)]
134pub struct MockPopupMenus(Rc<PopupMenusState>);
135
136#[derive(Default)]
137struct PopupMenusState {
138    shown: RefCell<Vec<ShownMenu>>,
139    choice: Cell<Option<MenuId>>,
140}
141
142impl MockPopupMenus {
143    pub fn new() -> MockPopupMenus {
144        MockPopupMenus::default()
145    }
146
147    /// Answers every menu opened from now on with `choice`, as a user choosing the item or, for
148    /// none, closing the menu.
149    pub fn answering(self, choice: Option<MenuId>) -> MockPopupMenus {
150        self.0.choice.set(choice);
151        self
152    }
153
154    /// The menus opened, in order.
155    pub fn shown(&self) -> Vec<ShownMenu> {
156        self.0.shown.borrow().clone()
157    }
158}
159
160impl PopupMenus for MockPopupMenus {
161    fn show(&self, view: ViewId, at: Offset, menu: &[MenuEntry]) -> PopupMenuFuture {
162        self.0.shown.borrow_mut().push(ShownMenu {
163            view,
164            at,
165            menu: menu.to_vec(),
166        });
167        Box::pin(std::future::ready(self.0.choice.get()))
168    }
169}
170
171/// Tray icons kept while they are there, each with what the framework set, its menus opened at it
172/// answered with the choice the test gave. An icon is answered at once, and offers both kinds of
173/// menu, as macOS's status items do, unless the test leaves one out, as Windows and Linux do, or
174/// has the tray refuse icons. Every clone is the same tray.
175#[derive(Clone)]
176pub struct MockTrayIcons(Rc<TrayState>);
177
178struct TrayState {
179    next_id: Cell<TrayIconId>,
180    icons: RefCell<Vec<Rc<IconState>>>,
181    choice: Cell<Option<MenuId>>,
182    attached_menus: Cell<bool>,
183    menus_at_icon: Cell<bool>,
184    /// Why the tray refuses icons, if it does.
185    refusal: RefCell<Option<String>>,
186}
187
188impl Default for MockTrayIcons {
189    fn default() -> MockTrayIcons {
190        MockTrayIcons(Rc::new(TrayState {
191            next_id: Cell::default(),
192            icons: RefCell::default(),
193            choice: Cell::default(),
194            attached_menus: Cell::new(true),
195            menus_at_icon: Cell::new(true),
196            refusal: RefCell::default(),
197        }))
198    }
199}
200
201/// What a tray icon shows.
202struct IconState {
203    id: TrayIconId,
204    image: RefCell<IconImage>,
205    tooltip: RefCell<Option<String>>,
206    attached: RefCell<Vec<MenuEntry>>,
207    shown: RefCell<Vec<Vec<MenuEntry>>>,
208}
209
210/// A tray icon as the test reads it back.
211#[derive(Clone, Debug, PartialEq)]
212pub struct ShownTrayIcon {
213    pub id: TrayIconId,
214    pub image: IconImage,
215    pub tooltip: Option<String>,
216    /// The menu the system would open by itself.
217    pub attached_menu: Vec<MenuEntry>,
218    /// The menus the app opened at it, in order.
219    pub menus_opened: Vec<Vec<MenuEntry>>,
220}
221
222impl MockTrayIcons {
223    pub fn new() -> MockTrayIcons {
224        MockTrayIcons::default()
225    }
226
227    /// Answers every menu opened at an icon from now on with `choice`.
228    pub fn answering(self, choice: Option<MenuId>) -> MockTrayIcons {
229        self.0.choice.set(choice);
230        self
231    }
232
233    /// Icons with no menu the system opens by itself, as Windows' notification-area icons.
234    pub fn without_attached_menus(self) -> MockTrayIcons {
235        self.0.attached_menus.set(false);
236        self
237    }
238
239    /// Icons the app cannot open a menu at, as Linux's StatusNotifierItems.
240    pub fn without_menus_at_icon(self) -> MockTrayIcons {
241        self.0.menus_at_icon.set(false);
242        self
243    }
244
245    /// A tray that shows no icon, answering each with `reason`.
246    pub fn refusing(self, reason: impl Into<String>) -> MockTrayIcons {
247        *self.0.refusal.borrow_mut() = Some(reason.into());
248        self
249    }
250
251    /// The icons there now, in the order added.
252    pub fn icons(&self) -> Vec<ShownTrayIcon> {
253        self.0
254            .icons
255            .borrow()
256            .iter()
257            .map(|icon| ShownTrayIcon {
258                id: icon.id,
259                image: icon.image.borrow().clone(),
260                tooltip: icon.tooltip.borrow().clone(),
261                attached_menu: icon.attached.borrow().clone(),
262                menus_opened: icon.shown.borrow().clone(),
263            })
264            .collect()
265    }
266}
267
268impl TrayIcons for MockTrayIcons {
269    fn add(&self, image: &IconImage, tooltip: Option<&str>) -> TrayIconFuture {
270        if let Some(reason) = self.0.refusal.borrow().clone() {
271            return Box::pin(std::future::ready(Err(TrayIconError::Failed(reason))));
272        }
273        let id = self.0.next_id.get() + 1;
274        self.0.next_id.set(id);
275        let icon = Rc::new(IconState {
276            id,
277            image: RefCell::new(image.clone()),
278            tooltip: RefCell::new(tooltip.map(str::to_owned)),
279            attached: RefCell::default(),
280            shown: RefCell::default(),
281        });
282        self.0.icons.borrow_mut().push(Rc::clone(&icon));
283        let icon: Box<dyn TrayIcon> = Box::new(MockTrayIcon {
284            tray: Rc::clone(&self.0),
285            icon,
286        });
287        Box::pin(std::future::ready(Ok(icon)))
288    }
289}
290
291/// An icon of a [`MockTrayIcons`], gone from it when dropped.
292struct MockTrayIcon {
293    tray: Rc<TrayState>,
294    icon: Rc<IconState>,
295}
296
297impl TrayIcon for MockTrayIcon {
298    fn id(&self) -> TrayIconId {
299        self.icon.id
300    }
301
302    fn set_image(&self, image: &IconImage) {
303        *self.icon.image.borrow_mut() = image.clone();
304    }
305
306    fn set_tooltip(&self, tooltip: Option<&str>) {
307        *self.icon.tooltip.borrow_mut() = tooltip.map(str::to_owned);
308    }
309
310    fn attached_menu(&self) -> Option<&dyn AttachedMenu> {
311        self.tray.attached_menus.get().then_some(self)
312    }
313
314    fn menu_at_icon(&self) -> Option<&dyn MenuAtIcon> {
315        self.tray.menus_at_icon.get().then_some(self)
316    }
317}
318
319impl AttachedMenu for MockTrayIcon {
320    fn set_menu(&self, menu: &[MenuEntry]) {
321        *self.icon.attached.borrow_mut() = menu.to_vec();
322    }
323}
324
325impl MenuAtIcon for MockTrayIcon {
326    fn show(&self, menu: &[MenuEntry]) -> PopupMenuFuture {
327        self.icon.shown.borrow_mut().push(menu.to_vec());
328        Box::pin(std::future::ready(self.tray.choice.get()))
329    }
330}
331
332impl Drop for MockTrayIcon {
333    fn drop(&mut self) {
334        self.tray
335            .icons
336            .borrow_mut()
337            .retain(|icon| icon.id != self.icon.id);
338    }
339}
340
341#[cfg(test)]
342mod tests {
343    use std::sync::Arc;
344
345    use waft_embedder::{MenuItem, ShortcutModifiers};
346
347    use super::*;
348
349    fn image() -> IconImage {
350        IconImage {
351            width: 1,
352            height: 1,
353            rgba: Arc::from([0u8, 0, 0, 255]),
354            template: true,
355        }
356    }
357
358    #[test]
359    fn the_menu_bar_finds_an_item_by_its_labels() {
360        let bar = MockMenuBar::new();
361        bar.set_menus(&[MenuEntry::Submenu {
362            id: 1,
363            label: "File".to_owned(),
364            enabled: true,
365            entries: vec![MenuEntry::Item {
366                id: 2,
367                item: MenuItem::new("Open"),
368            }],
369        }]);
370        assert_eq!(bar.id_of(&["File", "Open"]), Some(2));
371        assert_eq!(bar.id_of(&["File"]), Some(1));
372        assert_eq!(bar.id_of(&["Edit"]), None);
373        assert_eq!(bar.sets(), 1);
374    }
375
376    #[test]
377    fn the_menu_bar_keeps_the_keys_offered_and_takes_its_shortcuts_keys() {
378        let open = MenuShortcut {
379            key: 'o' as u64,
380            modifiers: ShortcutModifiers {
381                meta: true,
382                ..ShortcutModifiers::default()
383            },
384        };
385        let bar = MockMenuBar::new().taking([open]);
386        let key = |logical: char, event_type| KeyData {
387            event_type,
388            logical: logical as u64,
389            physical: 0x0007_0012,
390            ..KeyData::default()
391        };
392        assert!(bar.perform_key_equivalent(&key('o', KeyEventType::Down)));
393        assert!(!bar.perform_key_equivalent(&key('p', KeyEventType::Down)));
394        assert!(!bar.perform_key_equivalent(&key('o', KeyEventType::Up)));
395        assert_eq!(bar.offered().len(), 3);
396    }
397
398    #[test]
399    fn an_icon_offers_the_menus_its_tray_was_given() {
400        let windows = now(MockTrayIcons::new()
401            .without_attached_menus()
402            .add(&image(), None))
403        .expect("an icon");
404        assert!(windows.attached_menu().is_none() && windows.menu_at_icon().is_some());
405        let linux = now(MockTrayIcons::new()
406            .without_menus_at_icon()
407            .add(&image(), None))
408        .expect("an icon");
409        assert!(linux.attached_menu().is_some() && linux.menu_at_icon().is_none());
410        let refused = now(MockTrayIcons::new().refusing("no tray").add(&image(), None));
411        assert_eq!(
412            refused.err(),
413            Some(TrayIconError::Failed("no tray".to_owned()))
414        );
415    }
416
417    #[test]
418    fn a_tray_icon_is_there_until_dropped() {
419        let tray = MockTrayIcons::new().answering(Some(5));
420        let icon = now(tray.add(&image(), Some("Status"))).expect("an icon");
421        icon.attached_menu()
422            .expect("an attached menu")
423            .set_menu(&[MenuEntry::Separator]);
424        let choice = icon.menu_at_icon().expect("a menu at the icon").show(&[]);
425        assert_eq!(now(choice), Some(5), "the test's choice answers it");
426        let shown = tray.icons();
427        assert_eq!(shown.len(), 1);
428        assert_eq!(shown[0].tooltip.as_deref(), Some("Status"));
429        assert_eq!(shown[0].attached_menu, [MenuEntry::Separator]);
430        drop(icon);
431        assert!(tray.icons().is_empty());
432    }
433
434    /// `future`'s output: these answer in the call.
435    fn now<T>(mut future: std::pin::Pin<Box<dyn std::future::Future<Output = T>>>) -> T {
436        let mut context = std::task::Context::from_waker(std::task::Waker::noop());
437        match future.as_mut().poll(&mut context) {
438            std::task::Poll::Ready(output) => output,
439            std::task::Poll::Pending => panic!("answers in the call"),
440        }
441    }
442}