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    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}
66
67/// Install with [`Ui::set_services`](mitsuami_core::Ui::set_services).
68#[derive(Default)]
69pub struct FakeServices {
70    state: Rc<RefCell<State>>,
71}
72
73/// The test's side of [`FakeServices`].
74#[derive(Clone)]
75pub struct FakeServicesHandle {
76    state: Rc<RefCell<State>>,
77}
78
79impl FakeServices {
80    pub fn new() -> (FakeServices, FakeServicesHandle) {
81        let services = FakeServices::default();
82        let handle = FakeServicesHandle { state: services.state.clone() };
83        (services, handle)
84    }
85}
86
87impl FakeServicesHandle {
88    pub fn clipboard(&self) -> Option<String> {
89        self.state.borrow().clipboard.clone()
90    }
91
92    /// Puts text on the fake clipboard, as if copied from another app.
93    pub fn set_clipboard(&self, text: &str) {
94        self.state.borrow_mut().clipboard = Some(text.to_owned());
95    }
96
97    /// The oldest alert still waiting for an answer.
98    pub fn take_alert(&self) -> Option<PendingAlert> {
99        self.state.borrow_mut().alerts.pop_front()
100    }
101
102    pub fn take_open_file(&self) -> Option<PendingOpen> {
103        self.state.borrow_mut().opens.pop_front()
104    }
105
106    pub fn take_save_file(&self) -> Option<PendingSave> {
107        self.state.borrow_mut().saves.pop_front()
108    }
109
110    /// The oldest request to trash items. Nothing has been moved: the
111    /// test does what it wants the platform to have done, then answers.
112    pub fn take_trash(&self) -> Option<PendingTrash> {
113        self.state.borrow_mut().trashes.pop_front()
114    }
115
116    /// The oldest request to open something in another app.
117    pub fn take_launch(&self) -> Option<PendingLaunch> {
118        self.state.borrow_mut().launches.pop_front()
119    }
120
121    /// The notifications showing, oldest first: those withdrawn or
122    /// clicked are gone, and one replaced by another with its id is where
123    /// it was, with the new text.
124    pub fn notifications(&self) -> Vec<Notification> {
125        self.state.borrow().notifications.clone()
126    }
127
128    /// Makes `notify` fail with `error` from now on (`Cancelled`: the user
129    /// turned the app's notifications off; `Unavailable`: nothing to show
130    /// them), or show them again with `None`.
131    pub fn set_notification_error(&self, error: Option<ServiceError>) {
132        self.state.borrow_mut().notification_answer = error;
133    }
134
135    /// Clicks the notification with this id, as the user would: it goes
136    /// from the list and the app hears of it. Returns `false` if there's
137    /// none.
138    pub fn click_notification(&self, id: &str) -> bool {
139        let activated = {
140            let mut state = self.state.borrow_mut();
141            let Some(at) = state.notifications.iter().position(|n| n.id.as_deref() == Some(id)) else { return false };
142            state.notifications.remove(at);
143            state.notification_activated.clone()
144        };
145        if let Some(activated) = activated {
146            activated(id.to_owned());
147        }
148        true
149    }
150
151    /// Requests of any kind still waiting for an answer.
152    pub fn pending_requests(&self) -> usize {
153        let state = self.state.borrow();
154        state.alerts.len() + state.opens.len() + state.saves.len() + state.trashes.len() + state.launches.len()
155    }
156
157    /// The menus the app installed.
158    pub fn menu(&self) -> Option<MenuBarData> {
159        self.state.borrow().menu.clone()
160    }
161
162    /// A window's own menus (a `MenuBar` in its content), without the app's.
163    pub fn window_menu(&self, window: NodeId) -> Option<MenuBarData> {
164        self.state.borrow().window_menus.get(&window).cloned()
165    }
166
167    /// The item at `path`, e.g. `["File", "Open Recent", "notes.txt"]`:
168    /// a menu, its submenus, then the item's title. Looks in the app's
169    /// menus, then in each window's.
170    pub fn menu_item(&self, path: &[&str]) -> Option<MenuItemData> {
171        let state = self.state.borrow();
172        let (menu, rest) = path.split_first()?;
173        state.menu.iter().chain(state.window_menus.values()).flat_map(|bar| &bar.menus).find_map(|data| {
174            if data.title != *menu {
175                return None;
176            }
177            find_menu_item(&data.entries, rest).cloned()
178        })
179    }
180
181    /// Chooses the item at `path` (see [`menu_item`](Self::menu_item)),
182    /// like a click or its shortcut would. Returns `false` if there is no
183    /// such item or it is disabled.
184    pub fn choose_menu_item(&self, path: &[&str]) -> bool {
185        let Some(item) = self.menu_item(path).filter(|item| item.enabled) else { return false };
186        let Some(activate) = self.state.borrow().activate.clone() else { return false };
187        activate(item.id);
188        true
189    }
190}
191
192impl Services for FakeServices {
193    fn clipboard_text(&mut self, reply: Reply<Option<String>>) {
194        let text = self.state.borrow().clipboard.clone();
195        reply(text);
196    }
197
198    fn set_clipboard_text(&mut self, text: &str, reply: Reply<Result<(), ServiceError>>) {
199        self.state.borrow_mut().clipboard = Some(text.to_owned());
200        reply(Ok(()));
201    }
202
203    fn alert(&mut self, parent: Option<NodeId>, alert: &Alert, reply: Reply<usize>) {
204        self.state.borrow_mut().alerts.push_back(Pending { request: alert.clone(), parent, reply });
205    }
206
207    fn open_file(&mut self, parent: Option<NodeId>, request: &OpenFile, reply: Reply<Option<Vec<PathBuf>>>) {
208        self.state.borrow_mut().opens.push_back(Pending { request: request.clone(), parent, reply });
209    }
210
211    fn save_file(&mut self, parent: Option<NodeId>, request: &SaveFile, reply: Reply<Option<PathBuf>>) {
212        self.state.borrow_mut().saves.push_back(Pending { request: request.clone(), parent, reply });
213    }
214
215    fn trash(&mut self, parent: Option<NodeId>, paths: &[PathBuf], reply: Reply<Result<(), ServiceError>>) {
216        self.state.borrow_mut().trashes.push_back(Pending { request: paths.to_vec(), parent, reply });
217    }
218
219    fn launch(&mut self, parent: Option<NodeId>, target: &Launch, reply: Reply<Result<(), ServiceError>>) {
220        self.state.borrow_mut().launches.push_back(Pending { request: target.clone(), parent, reply });
221    }
222
223    fn notify(
224        &mut self,
225        notification: &Notification,
226        activated: Rc<dyn Fn(String)>,
227        reply: Reply<Result<(), ServiceError>>,
228    ) {
229        let answer = {
230            let mut state = self.state.borrow_mut();
231            match state.notification_answer.clone() {
232                Some(error) => Err(error),
233                None => {
234                    match state.notifications.iter_mut().find(|n| n.id == notification.id) {
235                        Some(shown) => *shown = notification.clone(),
236                        None => state.notifications.push(notification.clone()),
237                    }
238                    state.notification_activated = Some(activated);
239                    Ok(())
240                }
241            }
242        };
243        reply(answer);
244    }
245
246    fn withdraw_notification(&mut self, id: &str) {
247        self.state.borrow_mut().notifications.retain(|n| n.id.as_deref() != Some(id));
248    }
249
250    /// Alerts and file dialogs asked for on the window answer as their
251    /// cancel would. Those without a parent stay: the fake doesn't know
252    /// which window is focused.
253    fn window_destroyed(&mut self, window: NodeId) {
254        let (alerts, opens, saves) = {
255            let mut state = self.state.borrow_mut();
256            (take_on(&mut state.alerts, window), take_on(&mut state.opens, window), take_on(&mut state.saves, window))
257        };
258        for alert in alerts {
259            let cancel = alert.request.effective_buttons().len() - 1;
260            alert.respond(cancel);
261        }
262        opens.into_iter().for_each(|open| open.respond(None));
263        saves.into_iter().for_each(|save| save.respond(None));
264    }
265
266    fn set_menu(&mut self, window: Option<NodeId>, menu: &MenuBarData, activate: Rc<dyn Fn(u32)>) {
267        let mut state = self.state.borrow_mut();
268        match window {
269            None => state.menu = Some(menu.clone()),
270            Some(window) if menu.menus.is_empty() => _ = state.window_menus.remove(&window),
271            Some(window) => _ = state.window_menus.insert(window, menu.clone()),
272        }
273        // Ids are unique across bars, and every bar reports to the same Ui.
274        state.activate = Some(activate);
275    }
276}