Skip to main content

mitsuami_core/services/
mod.rs

1//! Platform services: clipboard, dialogs, the menu bar, the trash and
2//! opening files in other apps.
3//! Widgets' context menus are made of the same menus.
4//!
5//! [`Services`] is the contract each platform implements, separately from
6//! the widget [`Backend`](crate::Backend). Tests install a scripted fake in
7//! its place, so they never open real dialogs or touch the real clipboard.
8//!
9//! App code uses the async functions here (`alert(...).await`, …) or the
10//! same methods on [`Ui`](crate::Ui).
11
12mod dialogs;
13mod futures;
14mod menu;
15mod menu_collect;
16mod menu_data;
17
18pub use dialogs::{Alert, AlertStyle, FileFilter, Launch, OpenFile, SaveFile, existing_folder};
19pub(crate) use futures::reply_future;
20pub use futures::{
21    alert, clipboard_text, launch, launch_url, open_file, save_file, set_clipboard_text, set_menu, trash,
22};
23pub use menu::{Menu, MenuBar, MenuEntries, MenuItem, MenuSeparator, Menus};
24pub(crate) use menu_collect::install_context_menu;
25#[doc(hidden)]
26pub use menu_collect::{ItemMenus, install_button_menu};
27pub use menu_data::{
28    MenuBarData, MenuCheck, MenuData, MenuEntry, MenuItemData, MenuRole, Shortcut, find_menu_item, menu_item_by_id,
29};
30
31use std::path::PathBuf;
32use std::rc::Rc;
33
34use crate::widget::NodeId;
35
36/// Delivers the user's answer. Called once, possibly long after the request.
37pub type Reply<T> = Box<dyn FnOnce(T)>;
38
39/// Why a service request failed.
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub enum ServiceError {
42    /// The platform doesn't offer this service (or not right now).
43    Unavailable,
44    /// The user said no to a question the platform asked.
45    Cancelled,
46    Failed(String),
47}
48
49impl std::fmt::Display for ServiceError {
50    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51        match self {
52            ServiceError::Unavailable => f.write_str("the service is not available"),
53            ServiceError::Cancelled => f.write_str("the user cancelled"),
54            ServiceError::Failed(why) => write!(f, "the service failed: {why}"),
55        }
56    }
57}
58
59impl std::error::Error for ServiceError {}
60
61/// What a platform provides beyond widgets.
62pub trait Services {
63    /// Reads the clipboard's text. Async because GTK and WinUI only read the
64    /// clipboard asynchronously; platforms that can may reply right away.
65    fn clipboard_text(&mut self, reply: Reply<Option<String>>);
66    /// Writes the clipboard (it can fail: e.g. another process holds it).
67    fn set_clipboard_text(&mut self, text: &str, reply: Reply<Result<(), ServiceError>>);
68
69    /// Shows an alert, attached to `parent` if given (a sheet on macOS) or
70    /// to the active window. Must not block: reply when the user answers.
71    fn alert(&mut self, parent: Option<NodeId>, alert: &Alert, reply: Reply<usize>);
72    /// Replies with the chosen paths, or `None` if cancelled.
73    fn open_file(&mut self, parent: Option<NodeId>, request: &OpenFile, reply: Reply<Option<Vec<PathBuf>>>);
74    fn save_file(&mut self, parent: Option<NodeId>, request: &SaveFile, reply: Reply<Option<PathBuf>>);
75    /// A window is about to be destroyed: close the alerts and file
76    /// dialogs open on it (asked for with it as `parent`, or shown on it as
77    /// the focused window) and reply as their cancel would, the alert's last
78    /// button or no paths. Called before the window's `Destroy` goes to the
79    /// backend, outside `apply`, so the dialogs close while their window is
80    /// still there.
81    fn window_destroyed(&mut self, window: NodeId);
82
83    /// Moves files and folders to the user's trash, as the platform's file
84    /// manager does, so they can be put back from there. Items go one after
85    /// another; the reply comes once all have gone, or with the first
86    /// failure, and those before it stay in the trash. `Unavailable`: the
87    /// item's disk has no trash. `Cancelled`: the user said no where the
88    /// platform asks first (Windows, when its settings say so).
89    fn trash(&mut self, parent: Option<NodeId>, paths: &[PathBuf], reply: Reply<Result<(), ServiceError>>);
90
91    /// Opens a file, folder or URL in the app the platform picks for it,
92    /// as its file manager would on a double-click. The platform may ask
93    /// which app when none is set; `Cancelled` if the user dismissed it,
94    /// `Unavailable` if no app opens it. Replies once the platform has
95    /// handed it over, not when the app has opened it.
96    fn launch(&mut self, parent: Option<NodeId>, target: &Launch, reply: Reply<Result<(), ServiceError>>);
97
98    /// Installs a menu bar: the app's (`window` is `None`), or one
99    /// window's own menus, which it shows with the app's
100    /// ([`MenuBarData::merged`]). Called again whenever the bar changes;
101    /// an empty bar removes a window's menus. A window's menus may arrive
102    /// before the window is created, and after it's destroyed.
103    ///
104    /// Platforms keep their standard menus (e.g. the macOS app and Edit
105    /// menus) and call `activate` with an item's id when it is chosen.
106    fn set_menu(&mut self, window: Option<NodeId>, menu: &MenuBarData, activate: Rc<dyn Fn(u32)>);
107}