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        let (ui, services) = (self.clone(), self.services.clone());
113        let mut ids = Vec::new();
114        let effect = mitsuami_reactive::effect(move || {
115            // Backends title some items themselves (AppKit's Quit, GNOME's
116            // and KDE's), in the app's language.
117            crate::l10n::track();
118            let mut new_id = || {
119                let mut inner = ui.inner.borrow_mut();
120                inner.next_menu_id += 1;
121                inner.next_menu_id - 1
122            };
123            let (data, handlers) = menu.collect(&mut ids, &mut new_id);
124            let handlers = handlers
125                .into_iter()
126                .map(|(id, handler)| {
127                    let handler: Handler0 = Rc::new(move || match scope {
128                        Some(scope) if scope.is_alive() => scope.with(|| handler()),
129                        _ => handler(),
130                    });
131                    (id, handler)
132                })
133                .collect();
134            let quit = data.clone().take_role(MenuRole::Quit).filter(|item| item.enabled).map(|item| item.id);
135            let mut inner = ui.inner.borrow_mut();
136            inner.menu_handlers.insert(target, handlers);
137            match quit {
138                Some(id) => _ = inner.quit_items.insert(target, id),
139                None => _ = inner.quit_items.remove(&target),
140            }
141            drop(inner);
142            services.borrow_mut().set_menu(target, &data, activate.clone());
143        });
144        if let Some(replaced) = self.inner.borrow_mut().menu_effects.insert(target, effect) {
145            replaced.dispose();
146        }
147    }
148
149    /// Removes a window's menus, when the scope that installed them ends.
150    fn remove_menu(&self, target: Option<NodeId>) {
151        let effect = {
152            let mut inner = self.inner.borrow_mut();
153            inner.menu_handlers.remove(&target);
154            inner.quit_items.remove(&target);
155            inner.menu_effects.remove(&target)
156        };
157        if let Some(effect) = effect {
158            effect.dispose();
159            self.services.borrow_mut().set_menu(target, &MenuBarData::default(), self.menu_activate());
160        }
161    }
162
163    /// Quitting as the platform asks for it from outside the app's menus
164    /// (macOS's Dock, logging out, the session ending): the app's Quit item,
165    /// as if chosen, if it has one; otherwise every window is asked to
166    /// close, as by its close button. Either way the app decides, and it
167    /// ends when its last window closes. Backends call it, then see
168    /// whether windows are left.
169    pub fn request_quit(&self) {
170        let (quit, events, windows) = {
171            let inner = self.inner.borrow();
172            // The app's own item first, else a window's.
173            let quit = inner.quit_items.get(&None).or_else(|| inner.quit_items.values().next()).copied();
174            (quit, inner.events.clone(), inner.windows.clone())
175        };
176        match quit {
177            Some(id) => self.inner.borrow_mut().menu_queue.push_back(id),
178            None => {
179                for window in windows {
180                    events.emit(window, UiEvent::WindowCloseRequested);
181                }
182            }
183        }
184        self.changed();
185    }
186
187    /// What platforms call with the id of the item chosen.
188    fn menu_activate(&self) -> Rc<dyn Fn(u32)> {
189        let weak = self.downgrade();
190        Rc::new(move |id| {
191            if let Some(ui) = weak.upgrade() {
192                ui.inner.borrow_mut().menu_queue.push_back(id);
193                ui.changed();
194            }
195        })
196    }
197}