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, OpenFile, Reply, SaveFile, ServiceError, Services, find_menu_item,
12};
13
14/// A request waiting for the test to answer it.
15pub struct Pending<Request, Answer> {
16    pub request: Request,
17    pub parent: Option<NodeId>,
18    reply: Reply<Answer>,
19}
20
21impl<Request, Answer> Pending<Request, Answer> {
22    /// Answers as the user would. Call `settle` afterwards to let waiting
23    /// tasks continue.
24    pub fn respond(self, answer: Answer) {
25        (self.reply)(answer);
26    }
27}
28
29pub type PendingAlert = Pending<Alert, usize>;
30pub type PendingOpen = Pending<OpenFile, Option<Vec<PathBuf>>>;
31pub type PendingSave = Pending<SaveFile, Option<PathBuf>>;
32/// Items to move to the trash; the test moves them (or not) and answers.
33pub type PendingTrash = Pending<Vec<PathBuf>, Result<(), ServiceError>>;
34/// A file, folder or URL to open in another app.
35pub type PendingLaunch = Pending<Launch, Result<(), ServiceError>>;
36
37/// Takes out the requests asked for on `window`, keeping the others' order.
38fn take_on<Request, Answer>(
39    requests: &mut VecDeque<Pending<Request, Answer>>,
40    window: NodeId,
41) -> VecDeque<Pending<Request, Answer>> {
42    let (taken, kept) = std::mem::take(requests).into_iter().partition(|p| p.parent == Some(window));
43    *requests = kept;
44    taken
45}
46
47#[derive(Default)]
48struct State {
49    clipboard: Option<String>,
50    alerts: VecDeque<PendingAlert>,
51    opens: VecDeque<PendingOpen>,
52    saves: VecDeque<PendingSave>,
53    trashes: VecDeque<PendingTrash>,
54    launches: VecDeque<PendingLaunch>,
55    menu: Option<MenuBarData>,
56    window_menus: BTreeMap<NodeId, MenuBarData>,
57    activate: Option<Rc<dyn Fn(u32)>>,
58}
59
60/// Install with [`Ui::set_services`](mitsuami_core::Ui::set_services).
61#[derive(Default)]
62pub struct FakeServices {
63    state: Rc<RefCell<State>>,
64}
65
66/// The test's side of [`FakeServices`].
67#[derive(Clone)]
68pub struct FakeServicesHandle {
69    state: Rc<RefCell<State>>,
70}
71
72impl FakeServices {
73    pub fn new() -> (FakeServices, FakeServicesHandle) {
74        let services = FakeServices::default();
75        let handle = FakeServicesHandle { state: services.state.clone() };
76        (services, handle)
77    }
78}
79
80impl FakeServicesHandle {
81    pub fn clipboard(&self) -> Option<String> {
82        self.state.borrow().clipboard.clone()
83    }
84
85    /// Puts text on the fake clipboard, as if copied from another app.
86    pub fn set_clipboard(&self, text: &str) {
87        self.state.borrow_mut().clipboard = Some(text.to_owned());
88    }
89
90    /// The oldest alert still waiting for an answer.
91    pub fn take_alert(&self) -> Option<PendingAlert> {
92        self.state.borrow_mut().alerts.pop_front()
93    }
94
95    pub fn take_open_file(&self) -> Option<PendingOpen> {
96        self.state.borrow_mut().opens.pop_front()
97    }
98
99    pub fn take_save_file(&self) -> Option<PendingSave> {
100        self.state.borrow_mut().saves.pop_front()
101    }
102
103    /// The oldest request to trash items. Nothing has been moved: the
104    /// test does what it wants the platform to have done, then answers.
105    pub fn take_trash(&self) -> Option<PendingTrash> {
106        self.state.borrow_mut().trashes.pop_front()
107    }
108
109    /// The oldest request to open something in another app.
110    pub fn take_launch(&self) -> Option<PendingLaunch> {
111        self.state.borrow_mut().launches.pop_front()
112    }
113
114    /// Requests of any kind still waiting for an answer.
115    pub fn pending_requests(&self) -> usize {
116        let state = self.state.borrow();
117        state.alerts.len() + state.opens.len() + state.saves.len() + state.trashes.len() + state.launches.len()
118    }
119
120    /// The menus the app installed.
121    pub fn menu(&self) -> Option<MenuBarData> {
122        self.state.borrow().menu.clone()
123    }
124
125    /// A window's own menus (a `MenuBar` in its content), without the app's.
126    pub fn window_menu(&self, window: NodeId) -> Option<MenuBarData> {
127        self.state.borrow().window_menus.get(&window).cloned()
128    }
129
130    /// The item at `path`, e.g. `["File", "Open Recent", "notes.txt"]`:
131    /// a menu, its submenus, then the item's title. Looks in the app's
132    /// menus, then in each window's.
133    pub fn menu_item(&self, path: &[&str]) -> Option<MenuItemData> {
134        let state = self.state.borrow();
135        let (menu, rest) = path.split_first()?;
136        state.menu.iter().chain(state.window_menus.values()).flat_map(|bar| &bar.menus).find_map(|data| {
137            if data.title != *menu {
138                return None;
139            }
140            find_menu_item(&data.entries, rest).cloned()
141        })
142    }
143
144    /// Chooses the item at `path` (see [`menu_item`](Self::menu_item)),
145    /// like a click or its shortcut would. Returns `false` if there is no
146    /// such item or it is disabled.
147    pub fn choose_menu_item(&self, path: &[&str]) -> bool {
148        let Some(item) = self.menu_item(path).filter(|item| item.enabled) else { return false };
149        let Some(activate) = self.state.borrow().activate.clone() else { return false };
150        activate(item.id);
151        true
152    }
153}
154
155impl Services for FakeServices {
156    fn clipboard_text(&mut self, reply: Reply<Option<String>>) {
157        let text = self.state.borrow().clipboard.clone();
158        reply(text);
159    }
160
161    fn set_clipboard_text(&mut self, text: &str, reply: Reply<Result<(), ServiceError>>) {
162        self.state.borrow_mut().clipboard = Some(text.to_owned());
163        reply(Ok(()));
164    }
165
166    fn alert(&mut self, parent: Option<NodeId>, alert: &Alert, reply: Reply<usize>) {
167        self.state.borrow_mut().alerts.push_back(Pending { request: alert.clone(), parent, reply });
168    }
169
170    fn open_file(&mut self, parent: Option<NodeId>, request: &OpenFile, reply: Reply<Option<Vec<PathBuf>>>) {
171        self.state.borrow_mut().opens.push_back(Pending { request: request.clone(), parent, reply });
172    }
173
174    fn save_file(&mut self, parent: Option<NodeId>, request: &SaveFile, reply: Reply<Option<PathBuf>>) {
175        self.state.borrow_mut().saves.push_back(Pending { request: request.clone(), parent, reply });
176    }
177
178    fn trash(&mut self, parent: Option<NodeId>, paths: &[PathBuf], reply: Reply<Result<(), ServiceError>>) {
179        self.state.borrow_mut().trashes.push_back(Pending { request: paths.to_vec(), parent, reply });
180    }
181
182    fn launch(&mut self, parent: Option<NodeId>, target: &Launch, reply: Reply<Result<(), ServiceError>>) {
183        self.state.borrow_mut().launches.push_back(Pending { request: target.clone(), parent, reply });
184    }
185
186    /// Alerts and file dialogs asked for on the window answer as their
187    /// cancel would. Those without a parent stay: the fake doesn't know
188    /// which window is focused.
189    fn window_destroyed(&mut self, window: NodeId) {
190        let (alerts, opens, saves) = {
191            let mut state = self.state.borrow_mut();
192            (take_on(&mut state.alerts, window), take_on(&mut state.opens, window), take_on(&mut state.saves, window))
193        };
194        for alert in alerts {
195            let cancel = alert.request.effective_buttons().len() - 1;
196            alert.respond(cancel);
197        }
198        opens.into_iter().for_each(|open| open.respond(None));
199        saves.into_iter().for_each(|save| save.respond(None));
200    }
201
202    fn set_menu(&mut self, window: Option<NodeId>, menu: &MenuBarData, activate: Rc<dyn Fn(u32)>) {
203        let mut state = self.state.borrow_mut();
204        match window {
205            None => state.menu = Some(menu.clone()),
206            Some(window) if menu.menus.is_empty() => _ = state.window_menus.remove(&window),
207            Some(window) => _ = state.window_menus.insert(window, menu.clone()),
208        }
209        // Ids are unique across bars, and every bar reports to the same Ui.
210        state.activate = Some(activate);
211    }
212}