Skip to main content

mitsuami_core/ui/
services.rs

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