Skip to main content

mitsuami_core/
services.rs

1//! Platform services: clipboard, dialogs and the menu bar.
2//!
3//! [`Services`] is the contract each platform implements, separately from
4//! the widget [`Backend`](crate::Backend). Tests install a scripted fake in
5//! its place, so they never open real dialogs or touch the real clipboard.
6//!
7//! App code uses the async functions here (`alert(...).await`, …) or the
8//! same methods on [`Ui`].
9
10use std::cell::RefCell;
11use std::future::Future;
12use std::path::PathBuf;
13use std::rc::Rc;
14use std::task::{Poll, Waker};
15
16use mitsuami_reactive::{IntoValue, Value};
17
18use crate::ui::Ui;
19use crate::widget::NodeId;
20
21/// Delivers the user's answer. Called once, possibly long after the request.
22pub type Reply<T> = Box<dyn FnOnce(T)>;
23
24#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
25pub enum AlertStyle {
26    #[default]
27    Info,
28    Warning,
29    /// Destructive or irreversible consequences.
30    Critical,
31}
32
33/// Why a service request failed.
34#[derive(Clone, Debug, PartialEq, Eq)]
35pub enum ServiceError {
36    /// The platform doesn't offer this service (or not right now).
37    Unavailable,
38    Failed(String),
39}
40
41impl std::fmt::Display for ServiceError {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        match self {
44            ServiceError::Unavailable => f.write_str("the service is not available"),
45            ServiceError::Failed(why) => write!(f, "the service failed: {why}"),
46        }
47    }
48}
49
50impl std::error::Error for ServiceError {}
51
52/// A message with buttons. The reply is the index of the chosen button.
53#[derive(Clone, Debug, PartialEq)]
54pub struct Alert {
55    pub title: String,
56    pub message: Option<String>,
57    /// In order of importance: the first is the default (Return) button.
58    pub buttons: Vec<String>,
59    pub style: AlertStyle,
60}
61
62impl Alert {
63    pub fn new(title: impl Into<String>) -> Alert {
64        Alert { title: title.into(), message: None, buttons: Vec::new(), style: AlertStyle::Info }
65    }
66
67    pub fn message(mut self, message: impl Into<String>) -> Alert {
68        self.message = Some(message.into());
69        self
70    }
71
72    pub fn button(mut self, title: impl Into<String>) -> Alert {
73        self.buttons.push(title.into());
74        self
75    }
76
77    pub fn style(mut self, style: AlertStyle) -> Alert {
78        self.style = style;
79        self
80    }
81
82    /// The buttons to show: "OK" when none were given.
83    pub fn effective_buttons(&self) -> Vec<String> {
84        if self.buttons.is_empty() { vec!["OK".to_string()] } else { self.buttons.clone() }
85    }
86}
87
88/// Files to offer in a file dialog, e.g. `FileFilter::new("Images", ["png", "jpg"])`.
89#[derive(Clone, Debug, PartialEq)]
90pub struct FileFilter {
91    pub name: String,
92    pub extensions: Vec<String>,
93}
94
95impl FileFilter {
96    pub fn new<S: Into<String>>(name: impl Into<String>, extensions: impl IntoIterator<Item = S>) -> FileFilter {
97        FileFilter { name: name.into(), extensions: extensions.into_iter().map(Into::into).collect() }
98    }
99}
100
101#[derive(Clone, Debug, Default, PartialEq)]
102pub struct OpenFile {
103    pub title: Option<String>,
104    pub multiple: bool,
105    /// Choose folders instead of files.
106    pub directories: bool,
107    pub filters: Vec<FileFilter>,
108}
109
110impl OpenFile {
111    pub fn new() -> OpenFile {
112        OpenFile::default()
113    }
114
115    pub fn title(mut self, title: impl Into<String>) -> OpenFile {
116        self.title = Some(title.into());
117        self
118    }
119
120    pub fn multiple(mut self) -> OpenFile {
121        self.multiple = true;
122        self
123    }
124
125    pub fn directories(mut self) -> OpenFile {
126        self.directories = true;
127        self
128    }
129
130    pub fn filter(mut self, filter: FileFilter) -> OpenFile {
131        self.filters.push(filter);
132        self
133    }
134}
135
136#[derive(Clone, Debug, Default, PartialEq)]
137pub struct SaveFile {
138    pub title: Option<String>,
139    pub default_name: Option<String>,
140    pub filters: Vec<FileFilter>,
141}
142
143impl SaveFile {
144    pub fn new() -> SaveFile {
145        SaveFile::default()
146    }
147
148    pub fn title(mut self, title: impl Into<String>) -> SaveFile {
149        self.title = Some(title.into());
150        self
151    }
152
153    pub fn name(mut self, name: impl Into<String>) -> SaveFile {
154        self.default_name = Some(name.into());
155        self
156    }
157
158    pub fn filter(mut self, filter: FileFilter) -> SaveFile {
159        self.filters.push(filter);
160        self
161    }
162}
163
164/// A keyboard shortcut. `primary` is ⌘ on macOS and Ctrl elsewhere.
165#[derive(Clone, Copy, Debug, PartialEq, Eq)]
166pub struct Shortcut {
167    pub key: char,
168    pub primary: bool,
169    pub shift: bool,
170    pub alt: bool,
171}
172
173impl Shortcut {
174    /// ⌘+key on macOS, Ctrl+key elsewhere.
175    pub fn primary(key: char) -> Shortcut {
176        Shortcut { key: key.to_ascii_lowercase(), primary: true, shift: false, alt: false }
177    }
178
179    pub fn shift(mut self) -> Shortcut {
180        self.shift = true;
181        self
182    }
183
184    pub fn alt(mut self) -> Shortcut {
185        self.alt = true;
186        self
187    }
188}
189
190/// The menu bar as data, for [`Services::set_menu`].
191#[derive(Clone, Debug, Default, PartialEq)]
192pub struct MenuBarData {
193    pub menus: Vec<MenuData>,
194}
195
196#[derive(Clone, Debug, PartialEq)]
197pub struct MenuData {
198    pub title: String,
199    pub entries: Vec<MenuEntry>,
200}
201
202#[derive(Clone, Debug, PartialEq)]
203pub enum MenuEntry {
204    Item { id: u32, title: String, shortcut: Option<Shortcut>, enabled: bool },
205    Separator,
206}
207
208/// What a platform provides beyond widgets.
209pub trait Services {
210    /// Reads the clipboard's text. Async because GTK and WinUI only read the
211    /// clipboard asynchronously; platforms that can may reply right away.
212    fn clipboard_text(&mut self, reply: Reply<Option<String>>);
213    /// Writes the clipboard (it can fail: e.g. another process holds it).
214    fn set_clipboard_text(&mut self, text: &str, reply: Reply<Result<(), ServiceError>>);
215
216    /// Shows an alert, attached to `parent` if given (a sheet on macOS) or
217    /// to the active window. Must not block: reply when the user answers.
218    fn alert(&mut self, parent: Option<NodeId>, alert: &Alert, reply: Reply<usize>);
219    /// Replies with the chosen paths, or `None` if cancelled.
220    fn open_file(&mut self, parent: Option<NodeId>, request: &OpenFile, reply: Reply<Option<Vec<PathBuf>>>);
221    fn save_file(&mut self, parent: Option<NodeId>, request: &SaveFile, reply: Reply<Option<PathBuf>>);
222
223    /// Installs the app's menus. Platforms keep their standard menus (e.g.
224    /// the macOS app and Edit menus) and call `activate` with an item's id
225    /// when it is chosen.
226    fn set_menu(&mut self, menu: &MenuBarData, activate: Rc<dyn Fn(u32)>);
227}
228
229// --------------------------------------------------------- menu builder
230
231type Handler = Rc<dyn Fn()>;
232/// Builds the menu data, reading reactive `enabled` states.
233pub(crate) type MenuDataFn = Rc<dyn Fn() -> MenuBarData>;
234
235/// A menu item: a title, an optional shortcut, a handler and an enabled
236/// state (static or reactive).
237pub struct MenuItem {
238    title: String,
239    shortcut: Option<Shortcut>,
240    enabled: Value<bool>,
241    handler: Handler,
242}
243
244impl MenuItem {
245    pub fn new(title: impl Into<String>, on_select: impl Fn() + 'static) -> MenuItem {
246        MenuItem { title: title.into(), shortcut: None, enabled: Value::Static(true), handler: Rc::new(on_select) }
247    }
248
249    pub fn shortcut(mut self, shortcut: Shortcut) -> MenuItem {
250        self.shortcut = Some(shortcut);
251        self
252    }
253
254    pub fn enabled(mut self, enabled: impl IntoValue<bool>) -> MenuItem {
255        self.enabled = enabled.into_value();
256        self
257    }
258}
259
260enum Entry {
261    Item(MenuItem),
262    Separator,
263}
264
265pub struct Menu {
266    title: String,
267    entries: Vec<Entry>,
268}
269
270impl Menu {
271    pub fn new(title: impl Into<String>) -> Menu {
272        Menu { title: title.into(), entries: Vec::new() }
273    }
274
275    pub fn item(mut self, item: MenuItem) -> Menu {
276        self.entries.push(Entry::Item(item));
277        self
278    }
279
280    pub fn separator(mut self) -> Menu {
281        self.entries.push(Entry::Separator);
282        self
283    }
284}
285
286/// The app's menus. Platforms add their standard ones around them.
287#[derive(Default)]
288pub struct MenuBar {
289    menus: Vec<Menu>,
290}
291
292impl MenuBar {
293    pub fn new() -> MenuBar {
294        MenuBar::default()
295    }
296
297    pub fn menu(mut self, menu: Menu) -> MenuBar {
298        self.menus.push(menu);
299        self
300    }
301
302    /// Splits into data (read reactively) and handlers by id.
303    pub(crate) fn into_parts(self) -> (MenuDataFn, Vec<(u32, Handler)>) {
304        let mut handlers = Vec::new();
305        let mut next_id = 1;
306        let mut menus = Vec::new();
307        for menu in self.menus {
308            let mut entries = Vec::new();
309            for entry in menu.entries {
310                match entry {
311                    Entry::Item(item) => {
312                        handlers.push((next_id, item.handler));
313                        entries.push((next_id, item.title, item.shortcut, Some(item.enabled)));
314                        next_id += 1;
315                    }
316                    Entry::Separator => entries.push((0, String::new(), None, None)),
317                }
318            }
319            menus.push((menu.title, entries));
320        }
321        let data = Rc::new(move || MenuBarData {
322            menus: menus
323                .iter()
324                .map(|(title, entries)| MenuData {
325                    title: title.clone(),
326                    entries: entries
327                        .iter()
328                        .map(|(id, title, shortcut, enabled)| match enabled {
329                            Some(enabled) => MenuEntry::Item {
330                                id: *id,
331                                title: title.clone(),
332                                shortcut: *shortcut,
333                                enabled: enabled.get(),
334                            },
335                            None => MenuEntry::Separator,
336                        })
337                        .collect(),
338                })
339                .collect(),
340        });
341        (data, handlers)
342    }
343}
344
345// ----------------------------------------------------------- async glue
346
347struct OneShot<T> {
348    value: Option<T>,
349    waker: Option<Waker>,
350}
351
352/// A reply callback and the future that resolves when it is called.
353pub(crate) fn reply_future<T: 'static>() -> (Reply<T>, impl Future<Output = T> + use<T>) {
354    let shared = Rc::new(RefCell::new(OneShot { value: None, waker: None }));
355    let sender = shared.clone();
356    let reply: Reply<T> = Box::new(move |value| {
357        let waker = {
358            let mut shared = sender.borrow_mut();
359            shared.value = Some(value);
360            shared.waker.take()
361        };
362        if let Some(waker) = waker {
363            waker.wake();
364        }
365    });
366    let future = std::future::poll_fn(move |cx| {
367        let mut shared = shared.borrow_mut();
368        match shared.value.take() {
369            Some(value) => Poll::Ready(value),
370            None => {
371                shared.waker = Some(cx.waker().clone());
372                Poll::Pending
373            }
374        }
375    });
376    (reply, future)
377}
378
379fn ui() -> Ui {
380    crate::task::current_ui()
381}
382
383pub fn clipboard_text() -> impl Future<Output = Option<String>> + use<> {
384    ui().clipboard_text()
385}
386
387/// Puts text on the clipboard right away; await to learn whether it worked.
388pub fn set_clipboard_text(text: &str) -> impl Future<Output = Result<(), ServiceError>> + use<> {
389    ui().set_clipboard_text(text)
390}
391
392/// Shows an alert on the active window; resolves to the chosen button's index.
393pub fn alert(alert: Alert) -> impl Future<Output = usize> + use<> {
394    ui().alert(None, alert)
395}
396
397pub fn open_file(request: OpenFile) -> impl Future<Output = Option<Vec<PathBuf>>> + use<> {
398    ui().open_file(None, request)
399}
400
401pub fn save_file(request: SaveFile) -> impl Future<Output = Option<PathBuf>> + use<> {
402    ui().save_file(None, request)
403}
404
405/// Installs the app's menus; see [`Ui::set_menu`].
406pub fn set_menu(menu: MenuBar) {
407    ui().set_menu(menu);
408}