Skip to main content

mitsuami_core/ui/
services.rs

1//! Platform services on a `Ui`: the clipboard, dialogs, the trash,
2//! launching, notifications, later launches, menus, the tray icon and
3//! quitting.
4
5use std::rc::Rc;
6
7use crate::command::UiEvent;
8use crate::services::{
9    Alert, Launch, MenuBar, MenuBarData, MenuRole, Notification, OpenFile, Reopen, SaveFile, ServiceError, Services,
10    TrayData, TrayIcon, reply_future,
11};
12use crate::widget::NodeId;
13
14use super::{Handler0, NotificationHandler, ReopenHandler, Ui};
15
16impl Ui {
17    /// Replaces the platform services (tests install a scripted fake).
18    pub fn set_services(&self, services: Box<dyn Services>) {
19        *self.services.borrow_mut() = services;
20    }
21
22    pub fn clipboard_text(&self) -> impl std::future::Future<Output = Option<String>> + use<> {
23        let (reply, text) = reply_future();
24        self.services.borrow_mut().clipboard_text(reply);
25        text
26    }
27
28    /// Puts text on the clipboard. The write is issued right away; await
29    /// the result to learn whether it worked.
30    pub fn set_clipboard_text(
31        &self,
32        text: &str,
33    ) -> impl std::future::Future<Output = Result<(), ServiceError>> + use<> {
34        let (reply, done) = reply_future();
35        self.services.borrow_mut().set_clipboard_text(text, reply);
36        done
37    }
38
39    /// Shows an alert; resolves to the index of the chosen button.
40    pub fn alert(&self, parent: Option<NodeId>, alert: Alert) -> impl std::future::Future<Output = usize> + use<> {
41        let (reply, answer) = reply_future();
42        self.services.borrow_mut().alert(parent, &alert, reply);
43        answer
44    }
45
46    /// Resolves to the chosen paths, or `None` if cancelled.
47    pub fn open_file(
48        &self,
49        parent: Option<NodeId>,
50        request: OpenFile,
51    ) -> impl std::future::Future<Output = Option<Vec<std::path::PathBuf>>> + use<> {
52        let (reply, answer) = reply_future();
53        self.services.borrow_mut().open_file(parent, &request, reply);
54        answer
55    }
56
57    pub fn save_file(
58        &self,
59        parent: Option<NodeId>,
60        request: SaveFile,
61    ) -> impl std::future::Future<Output = Option<std::path::PathBuf>> + use<> {
62        let (reply, answer) = reply_future();
63        self.services.borrow_mut().save_file(parent, &request, reply);
64        answer
65    }
66
67    /// Moves files and folders to the trash; see [`Services::trash`].
68    pub fn trash(
69        &self,
70        parent: Option<NodeId>,
71        paths: Vec<std::path::PathBuf>,
72    ) -> impl std::future::Future<Output = Result<(), ServiceError>> + use<> {
73        let (reply, done) = reply_future();
74        self.services.borrow_mut().trash(parent, &paths, reply);
75        done
76    }
77
78    /// Opens a file, folder or URL in another app; see [`Services::launch`].
79    pub fn launch(
80        &self,
81        parent: Option<NodeId>,
82        target: Launch,
83    ) -> impl std::future::Future<Output = Result<(), ServiceError>> + use<> {
84        let (reply, done) = reply_future();
85        self.services.borrow_mut().launch(parent, &target, reply);
86        done
87    }
88
89    /// Shows a notification outside the app's windows; see
90    /// [`Services::notify`]. Resolves once the platform has it.
91    pub fn notify(
92        &self,
93        mut notification: Notification,
94    ) -> impl std::future::Future<Output = Result<(), ServiceError>> + use<> {
95        if notification.id.is_none() {
96            let mut inner = self.inner.borrow_mut();
97            notification.id = Some(format!("mitsuami-{}", inner.next_notification));
98            inner.next_notification += 1;
99        }
100        let (reply, done) = reply_future();
101        self.services.borrow_mut().notify(&notification, self.notification_activated(), reply);
102        done
103    }
104
105    /// Takes away the notification with this id, if it's still there.
106    pub fn withdraw_notification(&self, id: &str) {
107        self.services.borrow_mut().withdraw_notification(id);
108    }
109
110    /// Runs `handler` with a notification's id when the user clicks it,
111    /// until the current scope ends. The platform has brought the app
112    /// forward by then; the app shows what the notification was about.
113    pub fn on_notification_activated(&self, handler: impl Fn(&str) + 'static) {
114        // In the scope it was installed from, so it can spawn tasks that
115        // live as long as it, as menu items do.
116        let scope = mitsuami_reactive::Owner::current();
117        let handler: NotificationHandler = Rc::new(move |id| match scope {
118            Some(scope) if scope.is_alive() => scope.with(|| handler(id)),
119            _ => handler(id),
120        });
121        let token = {
122            let mut inner = self.inner.borrow_mut();
123            let token = inner.next_notification_handler;
124            inner.next_notification_handler += 1;
125            inner.notification_handlers.insert(token, handler);
126            token
127        };
128        let ui = self.downgrade();
129        mitsuami_reactive::on_cleanup(move || {
130            if let Some(ui) = ui.upgrade() {
131                ui.inner.borrow_mut().notification_handlers.remove(&token);
132            }
133        });
134    }
135
136    /// What platforms call with the id of the notification clicked.
137    fn notification_activated(&self) -> Rc<dyn Fn(String)> {
138        let weak = self.downgrade();
139        Rc::new(move |id| {
140            if let Some(ui) = weak.upgrade() {
141                ui.inner.borrow_mut().notification_queue.push_back(id);
142                ui.changed();
143            }
144        })
145    }
146
147    /// Runs `handler` each time a single-instance app is launched again,
148    /// with what the launch passed on, until the current scope ends. The
149    /// backend has brought the last active window forward by then, with
150    /// the platform's activation token; an app with none opens one here,
151    /// and the token is still there for it. Without a handler, a launch
152    /// only brings the window forward. On macOS a click on the Dock icon
153    /// comes here too: it's how macOS apps reopen a closed window.
154    pub fn on_reopen(&self, handler: impl Fn(&Reopen) + 'static) {
155        let scope = mitsuami_reactive::Owner::current();
156        let handler: ReopenHandler = Rc::new(move |reopen| match scope {
157            Some(scope) if scope.is_alive() => scope.with(|| handler(reopen)),
158            _ => handler(reopen),
159        });
160        let token = {
161            let mut inner = self.inner.borrow_mut();
162            let token = inner.next_reopen_handler;
163            inner.next_reopen_handler += 1;
164            inner.reopen_handlers.insert(token, handler);
165            token
166        };
167        let ui = self.downgrade();
168        mitsuami_reactive::on_cleanup(move || {
169            if let Some(ui) = ui.upgrade() {
170                ui.inner.borrow_mut().reopen_handlers.remove(&token);
171            }
172        });
173    }
174
175    /// What backends call, on the main thread, when the app is launched
176    /// again, once they've brought its window forward: the `on_reopen`
177    /// handlers run in the next turn.
178    pub fn reopen(&self, reopen: Reopen) {
179        self.inner.borrow_mut().reopen_queue.push_back(reopen);
180        self.changed();
181    }
182
183    /// Installs the app's menus, replacing the ones installed before.
184    /// Their reactive parts (titles, enabled and checked states, which
185    /// items there are) are sent to the platform again when they change,
186    /// for as long as the current scope lives.
187    pub fn set_menu(&self, menu: MenuBar) {
188        self.install_menu(None, menu);
189    }
190
191    /// Installs a window's own menus, shown with the app's, until the
192    /// current scope ends. A [`MenuBar`] in the window's content does this.
193    pub fn set_window_menu(&self, window: NodeId, menu: MenuBar) {
194        self.install_menu(Some(window), menu);
195        let ui = self.downgrade();
196        mitsuami_reactive::on_cleanup(move || {
197            if let Some(ui) = ui.upgrade() {
198                ui.remove_menu(Some(window));
199            }
200        });
201    }
202
203    fn install_menu(&self, target: Option<NodeId>, menu: MenuBar) {
204        // Handlers run in the scope the menu was installed from, so they
205        // can spawn tasks that live as long as it.
206        let scope = mitsuami_reactive::Owner::current();
207        let activate = self.menu_activate();
208        // Weak: menus installed outside any scope (a C caller's) keep their
209        // effect, which mustn't keep the `Ui` and the platform alive.
210        let weak = self.downgrade();
211        let mut ids = Vec::new();
212        let effect = mitsuami_reactive::effect(move || {
213            // Backends title some items themselves (AppKit's Quit, GNOME's
214            // and KDE's), in the app's language.
215            crate::l10n::track();
216            let Some(ui) = weak.upgrade() else { return };
217            let mut new_id = || {
218                let mut inner = ui.inner.borrow_mut();
219                inner.next_menu_id += 1;
220                inner.next_menu_id - 1
221            };
222            let (data, handlers) = menu.collect(&mut ids, &mut new_id);
223            let handlers = handlers
224                .into_iter()
225                .map(|(id, handler)| {
226                    let handler: Handler0 = Rc::new(move || match scope {
227                        Some(scope) if scope.is_alive() => scope.with(|| handler()),
228                        _ => handler(),
229                    });
230                    (id, handler)
231                })
232                .collect();
233            let quit = data.clone().take_role(MenuRole::Quit).filter(|item| item.enabled).map(|item| item.id);
234            let mut inner = ui.inner.borrow_mut();
235            inner.menu_handlers.insert(target, handlers);
236            match quit {
237                Some(id) => _ = inner.quit_items.insert(target, id),
238                None => _ = inner.quit_items.remove(&target),
239            }
240            drop(inner);
241            ui.services.borrow_mut().set_menu(target, &data, activate.clone());
242        });
243        if let Some(replaced) = self.inner.borrow_mut().menu_effects.insert(target, effect) {
244            replaced.dispose();
245        }
246    }
247
248    /// Removes a window's menus, when the scope that installed them ends.
249    fn remove_menu(&self, target: Option<NodeId>) {
250        let effect = {
251            let mut inner = self.inner.borrow_mut();
252            inner.menu_handlers.remove(&target);
253            inner.quit_items.remove(&target);
254            inner.menu_effects.remove(&target)
255        };
256        if let Some(effect) = effect {
257            effect.dispose();
258            self.services.borrow_mut().set_menu(target, &MenuBarData::default(), self.menu_activate());
259        }
260    }
261
262    /// Shows the app's icon in the platform's tray until the current scope
263    /// ends, replacing the one shown before. Its reactive parts (title,
264    /// icon, tooltip, the menu's items) are sent to the platform again
265    /// when they change. Where there's no tray to show it in (plain GNOME,
266    /// or a Linux tray host that isn't running yet), it shows once one
267    /// comes: see [`tray_shown`](Self::tray_shown).
268    pub fn set_tray(&self, tray: TrayIcon) {
269        let scope = mitsuami_reactive::Owner::current();
270        let activate = self.menu_activate();
271        let shown = self.tray_shown_reporter();
272        let weak = self.downgrade();
273        let mut ids = Vec::new();
274        // What the platform shows, so a change that leaves it the same
275        // (a hidden item's title) isn't sent again; with the app info's
276        // version, as a tray without an icon shows the app's.
277        let mut sent: Option<(TrayData, u64)> = None;
278        let effect = mitsuami_reactive::effect(move || {
279            let Some(ui) = weak.upgrade() else { return };
280            let mut new_id = || {
281                let mut inner = ui.inner.borrow_mut();
282                inner.next_menu_id += 1;
283                inner.next_menu_id - 1
284            };
285            let (menu, handlers) = tray.menu.collect_entries(&mut ids, &mut new_id);
286            let data = TrayData {
287                title: tray.title.get(),
288                icon: tray.icon.as_ref().map(|icon| icon.get()),
289                tooltip: tray.tooltip.get(),
290                menu,
291            };
292            ui.inner.borrow_mut().tray_handlers = handlers
293                .into_iter()
294                .map(|(id, handler)| {
295                    let handler: Handler0 = Rc::new(move || match scope {
296                        Some(scope) if scope.is_alive() => scope.with(|| handler()),
297                        _ => handler(),
298                    });
299                    (id, handler)
300                })
301                .collect();
302            let app_info = ui.inner.borrow().app_info_changes;
303            let sending = (data, app_info.get());
304            if sent.as_ref() != Some(&sending) {
305                // Batched: the backend reports `tray_shown` from inside, and
306                // effects watching it may call services themselves.
307                mitsuami_reactive::batch(|| {
308                    ui.services.borrow_mut().set_tray(Some(&sending.0), activate.clone(), shown.clone())
309                });
310                sent = Some(sending);
311            }
312        });
313        let token = {
314            let mut inner = self.inner.borrow_mut();
315            let token = inner.next_tray;
316            inner.next_tray += 1;
317            token
318        };
319        if let Some((_, replaced)) = self.inner.borrow_mut().tray_effect.replace((token, effect)) {
320            replaced.dispose();
321        }
322        let ui = self.downgrade();
323        mitsuami_reactive::on_cleanup(move || {
324            if let Some(ui) = ui.upgrade() {
325                ui.remove_tray(token);
326            }
327        });
328    }
329
330    /// Takes the tray icon away when the scope that installed it ends,
331    /// unless another replaced it since.
332    fn remove_tray(&self, token: u64) {
333        let effect = {
334            let mut inner = self.inner.borrow_mut();
335            if inner.tray_effect.as_ref().is_none_or(|(shown, _)| *shown != token) {
336                return;
337            }
338            inner.tray_handlers.clear();
339            inner.tray_effect.take().map(|(_, effect)| effect)
340        };
341        if let Some(effect) = effect {
342            effect.dispose();
343        }
344        mitsuami_reactive::batch(|| {
345            self.services.borrow_mut().set_tray(None, self.menu_activate(), self.tray_shown_reporter())
346        });
347    }
348
349    /// Whether the tray icon is showing right now: false before the app
350    /// sets one, where the platform has no tray (plain GNOME), and while a
351    /// Linux tray host is away. An app that hides its window on close only
352    /// when there's a tray to bring it back watches it. The signal lives as
353    /// long as the Ui.
354    pub fn tray_shown(&self) -> mitsuami_reactive::Signal<bool> {
355        self.inner.borrow().tray_shown
356    }
357
358    /// What platforms call when the icon starts or stops showing.
359    fn tray_shown_reporter(&self) -> Rc<dyn Fn(bool)> {
360        let weak = self.downgrade();
361        Rc::new(move |shown| {
362            if let Some(ui) = weak.upgrade() {
363                let signal = ui.inner.borrow().tray_shown;
364                if signal.get_untracked() != shown {
365                    signal.set(shown);
366                }
367                ui.changed();
368            }
369        })
370    }
371
372    /// Keeps the app running while no window is open, until [`Ui::quit`]:
373    /// for an app that waits before it shows one, as for a notification's
374    /// click or a request from another process. Without, an app ends when
375    /// its last window closes.
376    pub fn set_runs_without_windows(&self, runs: bool) {
377        self.inner.borrow_mut().runs_without_windows = runs;
378        self.changed();
379    }
380
381    /// Ends the app once this turn of its run loop is done, with any
382    /// windows still open, without asking them first (unlike
383    /// [`Ui::request_quit`]).
384    pub fn quit(&self) {
385        self.inner.borrow_mut().quit_requested = true;
386        self.changed();
387    }
388
389    /// Whether the run loop should end now: [`Ui::quit`] was called, or no
390    /// window is open and the app doesn't run without them. Backends ask
391    /// after each turn, and before running at all.
392    pub fn should_end(&self) -> bool {
393        let inner = self.inner.borrow();
394        inner.quit_requested || (inner.windows.is_empty() && !inner.runs_without_windows)
395    }
396
397    /// Quitting as the platform asks for it from outside the app's menus
398    /// (macOS's Dock, logging out, the session ending): the app's Quit item,
399    /// as if chosen, if it has one; otherwise every window is asked to
400    /// close, as by its close button. Either way the app decides, and it
401    /// ends when its last window closes. Backends call it, then see
402    /// whether windows are left.
403    pub fn request_quit(&self) {
404        let (quit, events, windows) = {
405            let inner = self.inner.borrow();
406            // The app's own item first, else a window's.
407            let quit = inner.quit_items.get(&None).or_else(|| inner.quit_items.values().next()).copied();
408            (quit, inner.events.clone(), inner.windows.clone())
409        };
410        match quit {
411            Some(id) => self.inner.borrow_mut().menu_queue.push_back(id),
412            None => {
413                for window in windows {
414                    events.emit(window, UiEvent::WindowCloseRequested);
415                }
416            }
417        }
418        self.changed();
419    }
420
421    /// What platforms call with the id of the item chosen.
422    fn menu_activate(&self) -> Rc<dyn Fn(u32)> {
423        let weak = self.downgrade();
424        Rc::new(move |id| {
425            if let Some(ui) = weak.upgrade() {
426                ui.inner.borrow_mut().menu_queue.push_back(id);
427                ui.changed();
428            }
429        })
430    }
431}