1use 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
15pub 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 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>>;
33pub type PendingTrash = Pending<Vec<PathBuf>, Result<(), ServiceError>>;
35pub type PendingLaunch = Pending<Launch, Result<(), ServiceError>>;
37
38fn 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 notifications: Vec<Notification>,
58 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#[derive(Default)]
69pub struct FakeServices {
70 state: Rc<RefCell<State>>,
71}
72
73#[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 pub fn set_clipboard(&self, text: &str) {
94 self.state.borrow_mut().clipboard = Some(text.to_owned());
95 }
96
97 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 pub fn take_trash(&self) -> Option<PendingTrash> {
113 self.state.borrow_mut().trashes.pop_front()
114 }
115
116 pub fn take_launch(&self) -> Option<PendingLaunch> {
118 self.state.borrow_mut().launches.pop_front()
119 }
120
121 pub fn notifications(&self) -> Vec<Notification> {
125 self.state.borrow().notifications.clone()
126 }
127
128 pub fn set_notification_error(&self, error: Option<ServiceError>) {
132 self.state.borrow_mut().notification_answer = error;
133 }
134
135 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 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 pub fn menu(&self) -> Option<MenuBarData> {
159 self.state.borrow().menu.clone()
160 }
161
162 pub fn window_menu(&self, window: NodeId) -> Option<MenuBarData> {
164 self.state.borrow().window_menus.get(&window).cloned()
165 }
166
167 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 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 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 state.activate = Some(activate);
275 }
276}