Skip to main content

mitsuami_headless/
services.rs

1//! Scripted platform services for tests: records every request and lets
2//! the test answer it.
3
4use std::cell::RefCell;
5use std::collections::{BTreeMap, VecDeque};
6use std::path::PathBuf;
7use std::rc::Rc;
8
9use mitsuami_core::NodeId;
10use mitsuami_core::services::{
11    Alert, Launch, MenuBarData, MenuItemData, Notification, OpenFile, Reply, SaveFile, ServiceError, Services,
12    TrayData, find_menu_item,
13};
14
15/// A request waiting for the test to answer it.
16pub struct Pending<Request, Answer> {
17    pub request: Request,
18    pub parent: Option<NodeId>,
19    reply: Reply<Answer>,
20}
21
22impl<Request, Answer> Pending<Request, Answer> {
23    /// Answers as the user would. Call `settle` afterwards to let waiting
24    /// tasks continue.
25    pub fn respond(self, answer: Answer) {
26        (self.reply)(answer);
27    }
28}
29
30pub type PendingAlert = Pending<Alert, usize>;
31pub type PendingOpen = Pending<OpenFile, Option<Vec<PathBuf>>>;
32pub type PendingSave = Pending<SaveFile, Option<PathBuf>>;
33/// Items to move to the trash; the test moves them (or not) and answers.
34pub type PendingTrash = Pending<Vec<PathBuf>, Result<(), ServiceError>>;
35/// A file, folder or URL to open in another app.
36pub type PendingLaunch = Pending<Launch, Result<(), ServiceError>>;
37
38/// Takes out the requests asked for on `window`, keeping the others' order.
39fn take_on<Request, Answer>(
40    requests: &mut VecDeque<Pending<Request, Answer>>,
41    window: NodeId,
42) -> VecDeque<Pending<Request, Answer>> {
43    let (taken, kept) = std::mem::take(requests).into_iter().partition(|p| p.parent == Some(window));
44    *requests = kept;
45    taken
46}
47
48#[derive(Default)]
49struct State {
50    clipboard: Option<String>,
51    alerts: VecDeque<PendingAlert>,
52    opens: VecDeque<PendingOpen>,
53    saves: VecDeque<PendingSave>,
54    trashes: VecDeque<PendingTrash>,
55    launches: VecDeque<PendingLaunch>,
56    /// The notifications showing, oldest first.
57    notifications: Vec<Notification>,
58    /// What `notify` answers: the platform taking it, until a test says
59    /// the user turned notifications off.
60    notification_answer: Option<ServiceError>,
61    notification_activated: Option<Rc<dyn Fn(String)>>,
62    menu: Option<MenuBarData>,
63    window_menus: BTreeMap<NodeId, MenuBarData>,
64    activate: Option<Rc<dyn Fn(u32)>>,
65    tray: Option<TrayData>,
66    tray_activate: Option<Rc<dyn Fn(u32)>>,
67    tray_shown: Option<Rc<dyn Fn(bool)>>,
68    /// Whether the platform has somewhere to show it: a tray host is
69    /// running, until a test says it went.
70    tray_host_away: bool,
71}
72
73/// Install with [`Ui::set_services`](mitsuami_core::Ui::set_services).
74#[derive(Default)]
75pub struct FakeServices {
76    state: Rc<RefCell<State>>,
77}
78
79/// The test's side of [`FakeServices`].
80#[derive(Clone)]
81pub struct FakeServicesHandle {
82    state: Rc<RefCell<State>>,
83}
84
85impl FakeServices {
86    pub fn new() -> (FakeServices, FakeServicesHandle) {
87        let services = FakeServices::default();
88        let handle = FakeServicesHandle { state: services.state.clone() };
89        (services, handle)
90    }
91}
92
93impl FakeServicesHandle {
94    pub fn clipboard(&self) -> Option<String> {
95        self.state.borrow().clipboard.clone()
96    }
97
98    /// Puts text on the fake clipboard, as if copied from another app.
99    pub fn set_clipboard(&self, text: &str) {
100        self.state.borrow_mut().clipboard = Some(text.to_owned());
101    }
102
103    /// The oldest alert still waiting for an answer.
104    pub fn take_alert(&self) -> Option<PendingAlert> {
105        self.state.borrow_mut().alerts.pop_front()
106    }
107
108    pub fn take_open_file(&self) -> Option<PendingOpen> {
109        self.state.borrow_mut().opens.pop_front()
110    }
111
112    pub fn take_save_file(&self) -> Option<PendingSave> {
113        self.state.borrow_mut().saves.pop_front()
114    }
115
116    /// The oldest request to trash items. Nothing has been moved: the
117    /// test does what it wants the platform to have done, then answers.
118    pub fn take_trash(&self) -> Option<PendingTrash> {
119        self.state.borrow_mut().trashes.pop_front()
120    }
121
122    /// The oldest request to open something in another app.
123    pub fn take_launch(&self) -> Option<PendingLaunch> {
124        self.state.borrow_mut().launches.pop_front()
125    }
126
127    /// The notifications showing, oldest first: those withdrawn or
128    /// clicked are gone, and one replaced by another with its id is where
129    /// it was, with the new text.
130    pub fn notifications(&self) -> Vec<Notification> {
131        self.state.borrow().notifications.clone()
132    }
133
134    /// Makes `notify` fail with `error` from now on (`Cancelled`: the user
135    /// turned the app's notifications off; `Unavailable`: nothing to show
136    /// them), or show them again with `None`.
137    pub fn set_notification_error(&self, error: Option<ServiceError>) {
138        self.state.borrow_mut().notification_answer = error;
139    }
140
141    /// Clicks the notification with this id, as the user would: it goes
142    /// from the list and the app hears of it. Returns `false` if there's
143    /// none.
144    pub fn click_notification(&self, id: &str) -> bool {
145        let activated = {
146            let mut state = self.state.borrow_mut();
147            let Some(at) = state.notifications.iter().position(|n| n.id.as_deref() == Some(id)) else { return false };
148            state.notifications.remove(at);
149            state.notification_activated.clone()
150        };
151        if let Some(activated) = activated {
152            activated(id.to_owned());
153        }
154        true
155    }
156
157    /// Requests of any kind still waiting for an answer.
158    pub fn pending_requests(&self) -> usize {
159        let state = self.state.borrow();
160        state.alerts.len() + state.opens.len() + state.saves.len() + state.trashes.len() + state.launches.len()
161    }
162
163    /// The menus the app installed.
164    pub fn menu(&self) -> Option<MenuBarData> {
165        self.state.borrow().menu.clone()
166    }
167
168    /// A window's own menus (a `MenuBar` in its content), without the app's.
169    pub fn window_menu(&self, window: NodeId) -> Option<MenuBarData> {
170        self.state.borrow().window_menus.get(&window).cloned()
171    }
172
173    /// The item at `path`, e.g. `["File", "Open Recent", "notes.txt"]`:
174    /// a menu, its submenus, then the item's title. Looks in the app's
175    /// menus, then in each window's.
176    pub fn menu_item(&self, path: &[&str]) -> Option<MenuItemData> {
177        let state = self.state.borrow();
178        let (menu, rest) = path.split_first()?;
179        state.menu.iter().chain(state.window_menus.values()).flat_map(|bar| &bar.menus).find_map(|data| {
180            if data.title != *menu {
181                return None;
182            }
183            find_menu_item(&data.entries, rest).cloned()
184        })
185    }
186
187    /// Chooses the item at `path` (see [`menu_item`](Self::menu_item)),
188    /// like a click or its shortcut would. Returns `false` if there is no
189    /// such item or it is disabled.
190    pub fn choose_menu_item(&self, path: &[&str]) -> bool {
191        let Some(item) = self.menu_item(path).filter(|item| item.enabled) else { return false };
192        let Some(activate) = self.state.borrow().activate.clone() else { return false };
193        activate(item.id);
194        true
195    }
196}
197
198impl FakeServicesHandle {
199    /// The tray icon the app shows, if any.
200    pub fn tray(&self) -> Option<TrayData> {
201        self.state.borrow().tray.clone()
202    }
203
204    /// The tray menu's item at `path`: its submenus, then the item's title.
205    pub fn tray_item(&self, path: &[&str]) -> Option<MenuItemData> {
206        let state = self.state.borrow();
207        find_menu_item(&state.tray.as_ref()?.menu, path).cloned()
208    }
209
210    /// Chooses the tray menu's item at `path`, as a click on it would.
211    /// Returns `false` if there is no such item or it is disabled.
212    pub fn choose_tray_item(&self, path: &[&str]) -> bool {
213        let Some(item) = self.tray_item(path).filter(|item| item.enabled) else { return false };
214        let Some(activate) = self.state.borrow().tray_activate.clone() else { return false };
215        activate(item.id);
216        true
217    }
218
219    /// The tray's host goes away (`false`, as when a Linux panel quits) or
220    /// comes back: the app hears whether its icon shows.
221    pub fn set_tray_host(&self, running: bool) {
222        let shown = {
223            let mut state = self.state.borrow_mut();
224            state.tray_host_away = !running;
225            state.tray.as_ref().and(state.tray_shown.clone())
226        };
227        if let Some(shown) = shown {
228            shown(running);
229        }
230    }
231}
232
233impl Services for FakeServices {
234    fn clipboard_text(&mut self, reply: Reply<Option<String>>) {
235        let text = self.state.borrow().clipboard.clone();
236        reply(text);
237    }
238
239    fn set_clipboard_text(&mut self, text: &str, reply: Reply<Result<(), ServiceError>>) {
240        self.state.borrow_mut().clipboard = Some(text.to_owned());
241        reply(Ok(()));
242    }
243
244    fn alert(&mut self, parent: Option<NodeId>, alert: &Alert, reply: Reply<usize>) {
245        self.state.borrow_mut().alerts.push_back(Pending { request: alert.clone(), parent, reply });
246    }
247
248    fn open_file(&mut self, parent: Option<NodeId>, request: &OpenFile, reply: Reply<Option<Vec<PathBuf>>>) {
249        self.state.borrow_mut().opens.push_back(Pending { request: request.clone(), parent, reply });
250    }
251
252    fn save_file(&mut self, parent: Option<NodeId>, request: &SaveFile, reply: Reply<Option<PathBuf>>) {
253        self.state.borrow_mut().saves.push_back(Pending { request: request.clone(), parent, reply });
254    }
255
256    fn trash(&mut self, parent: Option<NodeId>, paths: &[PathBuf], reply: Reply<Result<(), ServiceError>>) {
257        self.state.borrow_mut().trashes.push_back(Pending { request: paths.to_vec(), parent, reply });
258    }
259
260    fn launch(&mut self, parent: Option<NodeId>, target: &Launch, reply: Reply<Result<(), ServiceError>>) {
261        self.state.borrow_mut().launches.push_back(Pending { request: target.clone(), parent, reply });
262    }
263
264    fn notify(
265        &mut self,
266        notification: &Notification,
267        activated: Rc<dyn Fn(String)>,
268        reply: Reply<Result<(), ServiceError>>,
269    ) {
270        let answer = {
271            let mut state = self.state.borrow_mut();
272            match state.notification_answer.clone() {
273                Some(error) => Err(error),
274                None => {
275                    match state.notifications.iter_mut().find(|n| n.id == notification.id) {
276                        Some(shown) => *shown = notification.clone(),
277                        None => state.notifications.push(notification.clone()),
278                    }
279                    state.notification_activated = Some(activated);
280                    Ok(())
281                }
282            }
283        };
284        reply(answer);
285    }
286
287    fn withdraw_notification(&mut self, id: &str) {
288        self.state.borrow_mut().notifications.retain(|n| n.id.as_deref() != Some(id));
289    }
290
291    /// Alerts and file dialogs asked for on the window answer as their
292    /// cancel would. Those without a parent stay: the fake doesn't know
293    /// which window is focused.
294    fn window_destroyed(&mut self, window: NodeId) {
295        let (alerts, opens, saves) = {
296            let mut state = self.state.borrow_mut();
297            (take_on(&mut state.alerts, window), take_on(&mut state.opens, window), take_on(&mut state.saves, window))
298        };
299        for alert in alerts {
300            let cancel = alert.request.effective_buttons().len() - 1;
301            alert.respond(cancel);
302        }
303        opens.into_iter().for_each(|open| open.respond(None));
304        saves.into_iter().for_each(|save| save.respond(None));
305    }
306
307    fn set_menu(&mut self, window: Option<NodeId>, menu: &MenuBarData, activate: Rc<dyn Fn(u32)>) {
308        let mut state = self.state.borrow_mut();
309        match window {
310            None => state.menu = Some(menu.clone()),
311            Some(window) if menu.menus.is_empty() => _ = state.window_menus.remove(&window),
312            Some(window) => _ = state.window_menus.insert(window, menu.clone()),
313        }
314        // Ids are unique across bars, and every bar reports to the same Ui.
315        state.activate = Some(activate);
316    }
317
318    fn set_tray(&mut self, tray: Option<&TrayData>, activate: Rc<dyn Fn(u32)>, shown: Rc<dyn Fn(bool)>) {
319        let showing = {
320            let mut state = self.state.borrow_mut();
321            state.tray = tray.cloned();
322            state.tray_activate = Some(activate);
323            state.tray_shown = Some(shown.clone());
324            tray.is_some() && !state.tray_host_away
325        };
326        shown(showing);
327    }
328}