Skip to main content

mitsuami_core/ui/
services.rs

1//! Platform services on a `Ui`: the clipboard, dialogs, the trash,
2//! launching, notifications, menus and quitting.
3
4use std::rc::Rc;
5
6use crate::command::UiEvent;
7use crate::services::{
8    Alert, Launch, MenuBar, MenuBarData, MenuRole, Notification, OpenFile, SaveFile, ServiceError, Services,
9    reply_future,
10};
11use crate::widget::NodeId;
12
13use super::{Handler0, NotificationHandler, Ui};
14
15impl Ui {
16    /// Replaces the platform services (tests install a scripted fake).
17    pub fn set_services(&self, services: Box<dyn Services>) {
18        *self.services.borrow_mut() = services;
19    }
20
21    pub fn clipboard_text(&self) -> impl std::future::Future<Output = Option<String>> + use<> {
22        let (reply, text) = reply_future();
23        self.services.borrow_mut().clipboard_text(reply);
24        text
25    }
26
27    /// Puts text on the clipboard. The write is issued right away; await
28    /// the result to learn whether it worked.
29    pub fn set_clipboard_text(
30        &self,
31        text: &str,
32    ) -> impl std::future::Future<Output = Result<(), ServiceError>> + use<> {
33        let (reply, done) = reply_future();
34        self.services.borrow_mut().set_clipboard_text(text, reply);
35        done
36    }
37
38    /// Shows an alert; resolves to the index of the chosen button.
39    pub fn alert(&self, parent: Option<NodeId>, alert: Alert) -> impl std::future::Future<Output = usize> + use<> {
40        let (reply, answer) = reply_future();
41        self.services.borrow_mut().alert(parent, &alert, reply);
42        answer
43    }
44
45    /// Resolves to the chosen paths, or `None` if cancelled.
46    pub fn open_file(
47        &self,
48        parent: Option<NodeId>,
49        request: OpenFile,
50    ) -> impl std::future::Future<Output = Option<Vec<std::path::PathBuf>>> + use<> {
51        let (reply, answer) = reply_future();
52        self.services.borrow_mut().open_file(parent, &request, reply);
53        answer
54    }
55
56    pub fn save_file(
57        &self,
58        parent: Option<NodeId>,
59        request: SaveFile,
60    ) -> impl std::future::Future<Output = Option<std::path::PathBuf>> + use<> {
61        let (reply, answer) = reply_future();
62        self.services.borrow_mut().save_file(parent, &request, reply);
63        answer
64    }
65
66    /// Moves files and folders to the trash; see [`Services::trash`].
67    pub fn trash(
68        &self,
69        parent: Option<NodeId>,
70        paths: Vec<std::path::PathBuf>,
71    ) -> impl std::future::Future<Output = Result<(), ServiceError>> + use<> {
72        let (reply, done) = reply_future();
73        self.services.borrow_mut().trash(parent, &paths, reply);
74        done
75    }
76
77    /// Opens a file, folder or URL in another app; see [`Services::launch`].
78    pub fn launch(
79        &self,
80        parent: Option<NodeId>,
81        target: Launch,
82    ) -> impl std::future::Future<Output = Result<(), ServiceError>> + use<> {
83        let (reply, done) = reply_future();
84        self.services.borrow_mut().launch(parent, &target, reply);
85        done
86    }
87
88    /// Shows a notification outside the app's windows; see
89    /// [`Services::notify`]. Resolves once the platform has it.
90    pub fn notify(
91        &self,
92        mut notification: Notification,
93    ) -> impl std::future::Future<Output = Result<(), ServiceError>> + use<> {
94        if notification.id.is_none() {
95            let mut inner = self.inner.borrow_mut();
96            notification.id = Some(format!("mitsuami-{}", inner.next_notification));
97            inner.next_notification += 1;
98        }
99        let (reply, done) = reply_future();
100        self.services.borrow_mut().notify(&notification, self.notification_activated(), reply);
101        done
102    }
103
104    /// Takes away the notification with this id, if it's still there.
105    pub fn withdraw_notification(&self, id: &str) {
106        self.services.borrow_mut().withdraw_notification(id);
107    }
108
109    /// Runs `handler` with a notification's id when the user clicks it,
110    /// until the current scope ends. The platform has brought the app
111    /// forward by then; the app shows what the notification was about.
112    pub fn on_notification_activated(&self, handler: impl Fn(&str) + 'static) {
113        // In the scope it was installed from, so it can spawn tasks that
114        // live as long as it, as menu items do.
115        let scope = mitsuami_reactive::Owner::current();
116        let handler: NotificationHandler = Rc::new(move |id| match scope {
117            Some(scope) if scope.is_alive() => scope.with(|| handler(id)),
118            _ => handler(id),
119        });
120        let token = {
121            let mut inner = self.inner.borrow_mut();
122            let token = inner.next_notification_handler;
123            inner.next_notification_handler += 1;
124            inner.notification_handlers.insert(token, handler);
125            token
126        };
127        let ui = self.downgrade();
128        mitsuami_reactive::on_cleanup(move || {
129            if let Some(ui) = ui.upgrade() {
130                ui.inner.borrow_mut().notification_handlers.remove(&token);
131            }
132        });
133    }
134
135    /// What platforms call with the id of the notification clicked.
136    fn notification_activated(&self) -> Rc<dyn Fn(String)> {
137        let weak = self.downgrade();
138        Rc::new(move |id| {
139            if let Some(ui) = weak.upgrade() {
140                ui.inner.borrow_mut().notification_queue.push_back(id);
141                ui.changed();
142            }
143        })
144    }
145
146    /// Installs the app's menus, replacing the ones installed before.
147    /// Their reactive parts (titles, enabled and checked states, which
148    /// items there are) are sent to the platform again when they change,
149    /// for as long as the current scope lives.
150    pub fn set_menu(&self, menu: MenuBar) {
151        self.install_menu(None, menu);
152    }
153
154    /// Installs a window's own menus, shown with the app's, until the
155    /// current scope ends. A [`MenuBar`] in the window's content does this.
156    pub fn set_window_menu(&self, window: NodeId, menu: MenuBar) {
157        self.install_menu(Some(window), menu);
158        let ui = self.downgrade();
159        mitsuami_reactive::on_cleanup(move || {
160            if let Some(ui) = ui.upgrade() {
161                ui.remove_menu(Some(window));
162            }
163        });
164    }
165
166    fn install_menu(&self, target: Option<NodeId>, menu: MenuBar) {
167        // Handlers run in the scope the menu was installed from, so they
168        // can spawn tasks that live as long as it.
169        let scope = mitsuami_reactive::Owner::current();
170        let activate = self.menu_activate();
171        // Weak: menus installed outside any scope (a C caller's) keep their
172        // effect, which mustn't keep the `Ui` and the platform alive.
173        let weak = self.downgrade();
174        let mut ids = Vec::new();
175        let effect = mitsuami_reactive::effect(move || {
176            // Backends title some items themselves (AppKit's Quit, GNOME's
177            // and KDE's), in the app's language.
178            crate::l10n::track();
179            let Some(ui) = weak.upgrade() else { return };
180            let mut new_id = || {
181                let mut inner = ui.inner.borrow_mut();
182                inner.next_menu_id += 1;
183                inner.next_menu_id - 1
184            };
185            let (data, handlers) = menu.collect(&mut ids, &mut new_id);
186            let handlers = handlers
187                .into_iter()
188                .map(|(id, handler)| {
189                    let handler: Handler0 = Rc::new(move || match scope {
190                        Some(scope) if scope.is_alive() => scope.with(|| handler()),
191                        _ => handler(),
192                    });
193                    (id, handler)
194                })
195                .collect();
196            let quit = data.clone().take_role(MenuRole::Quit).filter(|item| item.enabled).map(|item| item.id);
197            let mut inner = ui.inner.borrow_mut();
198            inner.menu_handlers.insert(target, handlers);
199            match quit {
200                Some(id) => _ = inner.quit_items.insert(target, id),
201                None => _ = inner.quit_items.remove(&target),
202            }
203            drop(inner);
204            ui.services.borrow_mut().set_menu(target, &data, activate.clone());
205        });
206        if let Some(replaced) = self.inner.borrow_mut().menu_effects.insert(target, effect) {
207            replaced.dispose();
208        }
209    }
210
211    /// Removes a window's menus, when the scope that installed them ends.
212    fn remove_menu(&self, target: Option<NodeId>) {
213        let effect = {
214            let mut inner = self.inner.borrow_mut();
215            inner.menu_handlers.remove(&target);
216            inner.quit_items.remove(&target);
217            inner.menu_effects.remove(&target)
218        };
219        if let Some(effect) = effect {
220            effect.dispose();
221            self.services.borrow_mut().set_menu(target, &MenuBarData::default(), self.menu_activate());
222        }
223    }
224
225    /// Quitting as the platform asks for it from outside the app's menus
226    /// (macOS's Dock, logging out, the session ending): the app's Quit item,
227    /// as if chosen, if it has one; otherwise every window is asked to
228    /// close, as by its close button. Either way the app decides, and it
229    /// ends when its last window closes. Backends call it, then see
230    /// whether windows are left.
231    pub fn request_quit(&self) {
232        let (quit, events, windows) = {
233            let inner = self.inner.borrow();
234            // The app's own item first, else a window's.
235            let quit = inner.quit_items.get(&None).or_else(|| inner.quit_items.values().next()).copied();
236            (quit, inner.events.clone(), inner.windows.clone())
237        };
238        match quit {
239            Some(id) => self.inner.borrow_mut().menu_queue.push_back(id),
240            None => {
241                for window in windows {
242                    events.emit(window, UiEvent::WindowCloseRequested);
243                }
244            }
245        }
246        self.changed();
247    }
248
249    /// What platforms call with the id of the item chosen.
250    fn menu_activate(&self) -> Rc<dyn Fn(u32)> {
251        let weak = self.downgrade();
252        Rc::new(move |id| {
253            if let Some(ui) = weak.upgrade() {
254                ui.inner.borrow_mut().menu_queue.push_back(id);
255                ui.changed();
256            }
257        })
258    }
259}