mitsuami-core 0.0.1

Node tree, layout, styles, units, a11y model and backend contract for mitsuami
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
//! Platform services: clipboard, dialogs and the menu bar.
//!
//! [`Services`] is the contract each platform implements, separately from
//! the widget [`Backend`](crate::Backend). Tests install a scripted fake in
//! its place, so they never open real dialogs or touch the real clipboard.
//!
//! App code uses the async functions here (`alert(...).await`, …) or the
//! same methods on [`Ui`].

use std::cell::RefCell;
use std::future::Future;
use std::path::PathBuf;
use std::rc::Rc;
use std::task::{Poll, Waker};

use mitsuami_reactive::{IntoValue, Value};

use crate::ui::Ui;
use crate::widget::NodeId;

/// Delivers the user's answer. Called once, possibly long after the request.
pub type Reply<T> = Box<dyn FnOnce(T)>;

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum AlertStyle {
    #[default]
    Info,
    Warning,
    /// Destructive or irreversible consequences.
    Critical,
}

/// Why a service request failed.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ServiceError {
    /// The platform doesn't offer this service (or not right now).
    Unavailable,
    Failed(String),
}

impl std::fmt::Display for ServiceError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ServiceError::Unavailable => f.write_str("the service is not available"),
            ServiceError::Failed(why) => write!(f, "the service failed: {why}"),
        }
    }
}

impl std::error::Error for ServiceError {}

/// A message with buttons. The reply is the index of the chosen button.
#[derive(Clone, Debug, PartialEq)]
pub struct Alert {
    pub title: String,
    pub message: Option<String>,
    /// In order of importance: the first is the default (Return) button.
    pub buttons: Vec<String>,
    pub style: AlertStyle,
}

impl Alert {
    pub fn new(title: impl Into<String>) -> Alert {
        Alert { title: title.into(), message: None, buttons: Vec::new(), style: AlertStyle::Info }
    }

    pub fn message(mut self, message: impl Into<String>) -> Alert {
        self.message = Some(message.into());
        self
    }

    pub fn button(mut self, title: impl Into<String>) -> Alert {
        self.buttons.push(title.into());
        self
    }

    pub fn style(mut self, style: AlertStyle) -> Alert {
        self.style = style;
        self
    }

    /// The buttons to show: "OK" when none were given.
    pub fn effective_buttons(&self) -> Vec<String> {
        if self.buttons.is_empty() { vec!["OK".to_string()] } else { self.buttons.clone() }
    }
}

/// Files to offer in a file dialog, e.g. `FileFilter::new("Images", ["png", "jpg"])`.
#[derive(Clone, Debug, PartialEq)]
pub struct FileFilter {
    pub name: String,
    pub extensions: Vec<String>,
}

impl FileFilter {
    pub fn new<S: Into<String>>(name: impl Into<String>, extensions: impl IntoIterator<Item = S>) -> FileFilter {
        FileFilter { name: name.into(), extensions: extensions.into_iter().map(Into::into).collect() }
    }
}

#[derive(Clone, Debug, Default, PartialEq)]
pub struct OpenFile {
    pub title: Option<String>,
    pub multiple: bool,
    /// Choose folders instead of files.
    pub directories: bool,
    pub filters: Vec<FileFilter>,
}

impl OpenFile {
    pub fn new() -> OpenFile {
        OpenFile::default()
    }

    pub fn title(mut self, title: impl Into<String>) -> OpenFile {
        self.title = Some(title.into());
        self
    }

    pub fn multiple(mut self) -> OpenFile {
        self.multiple = true;
        self
    }

    pub fn directories(mut self) -> OpenFile {
        self.directories = true;
        self
    }

    pub fn filter(mut self, filter: FileFilter) -> OpenFile {
        self.filters.push(filter);
        self
    }
}

#[derive(Clone, Debug, Default, PartialEq)]
pub struct SaveFile {
    pub title: Option<String>,
    pub default_name: Option<String>,
    pub filters: Vec<FileFilter>,
}

impl SaveFile {
    pub fn new() -> SaveFile {
        SaveFile::default()
    }

    pub fn title(mut self, title: impl Into<String>) -> SaveFile {
        self.title = Some(title.into());
        self
    }

    pub fn name(mut self, name: impl Into<String>) -> SaveFile {
        self.default_name = Some(name.into());
        self
    }

    pub fn filter(mut self, filter: FileFilter) -> SaveFile {
        self.filters.push(filter);
        self
    }
}

/// A keyboard shortcut. `primary` is ⌘ on macOS and Ctrl elsewhere.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Shortcut {
    pub key: char,
    pub primary: bool,
    pub shift: bool,
    pub alt: bool,
}

impl Shortcut {
    /// ⌘+key on macOS, Ctrl+key elsewhere.
    pub fn primary(key: char) -> Shortcut {
        Shortcut { key: key.to_ascii_lowercase(), primary: true, shift: false, alt: false }
    }

    pub fn shift(mut self) -> Shortcut {
        self.shift = true;
        self
    }

    pub fn alt(mut self) -> Shortcut {
        self.alt = true;
        self
    }
}

/// The menu bar as data, for [`Services::set_menu`].
#[derive(Clone, Debug, Default, PartialEq)]
pub struct MenuBarData {
    pub menus: Vec<MenuData>,
}

#[derive(Clone, Debug, PartialEq)]
pub struct MenuData {
    pub title: String,
    pub entries: Vec<MenuEntry>,
}

#[derive(Clone, Debug, PartialEq)]
pub enum MenuEntry {
    Item { id: u32, title: String, shortcut: Option<Shortcut>, enabled: bool },
    Separator,
}

/// What a platform provides beyond widgets.
pub trait Services {
    /// Reads the clipboard's text. Async because GTK and WinUI only read the
    /// clipboard asynchronously; platforms that can may reply right away.
    fn clipboard_text(&mut self, reply: Reply<Option<String>>);
    /// Writes the clipboard (it can fail: e.g. another process holds it).
    fn set_clipboard_text(&mut self, text: &str, reply: Reply<Result<(), ServiceError>>);

    /// Shows an alert, attached to `parent` if given (a sheet on macOS) or
    /// to the active window. Must not block: reply when the user answers.
    fn alert(&mut self, parent: Option<NodeId>, alert: &Alert, reply: Reply<usize>);
    /// Replies with the chosen paths, or `None` if cancelled.
    fn open_file(&mut self, parent: Option<NodeId>, request: &OpenFile, reply: Reply<Option<Vec<PathBuf>>>);
    fn save_file(&mut self, parent: Option<NodeId>, request: &SaveFile, reply: Reply<Option<PathBuf>>);

    /// Installs the app's menus. Platforms keep their standard menus (e.g.
    /// the macOS app and Edit menus) and call `activate` with an item's id
    /// when it is chosen.
    fn set_menu(&mut self, menu: &MenuBarData, activate: Rc<dyn Fn(u32)>);
}

// --------------------------------------------------------- menu builder

type Handler = Rc<dyn Fn()>;
/// Builds the menu data, reading reactive `enabled` states.
pub(crate) type MenuDataFn = Rc<dyn Fn() -> MenuBarData>;

/// A menu item: a title, an optional shortcut, a handler and an enabled
/// state (static or reactive).
pub struct MenuItem {
    title: String,
    shortcut: Option<Shortcut>,
    enabled: Value<bool>,
    handler: Handler,
}

impl MenuItem {
    pub fn new(title: impl Into<String>, on_select: impl Fn() + 'static) -> MenuItem {
        MenuItem { title: title.into(), shortcut: None, enabled: Value::Static(true), handler: Rc::new(on_select) }
    }

    pub fn shortcut(mut self, shortcut: Shortcut) -> MenuItem {
        self.shortcut = Some(shortcut);
        self
    }

    pub fn enabled(mut self, enabled: impl IntoValue<bool>) -> MenuItem {
        self.enabled = enabled.into_value();
        self
    }
}

enum Entry {
    Item(MenuItem),
    Separator,
}

pub struct Menu {
    title: String,
    entries: Vec<Entry>,
}

impl Menu {
    pub fn new(title: impl Into<String>) -> Menu {
        Menu { title: title.into(), entries: Vec::new() }
    }

    pub fn item(mut self, item: MenuItem) -> Menu {
        self.entries.push(Entry::Item(item));
        self
    }

    pub fn separator(mut self) -> Menu {
        self.entries.push(Entry::Separator);
        self
    }
}

/// The app's menus. Platforms add their standard ones around them.
#[derive(Default)]
pub struct MenuBar {
    menus: Vec<Menu>,
}

impl MenuBar {
    pub fn new() -> MenuBar {
        MenuBar::default()
    }

    pub fn menu(mut self, menu: Menu) -> MenuBar {
        self.menus.push(menu);
        self
    }

    /// Splits into data (read reactively) and handlers by id.
    pub(crate) fn into_parts(self) -> (MenuDataFn, Vec<(u32, Handler)>) {
        let mut handlers = Vec::new();
        let mut next_id = 1;
        let mut menus = Vec::new();
        for menu in self.menus {
            let mut entries = Vec::new();
            for entry in menu.entries {
                match entry {
                    Entry::Item(item) => {
                        handlers.push((next_id, item.handler));
                        entries.push((next_id, item.title, item.shortcut, Some(item.enabled)));
                        next_id += 1;
                    }
                    Entry::Separator => entries.push((0, String::new(), None, None)),
                }
            }
            menus.push((menu.title, entries));
        }
        let data = Rc::new(move || MenuBarData {
            menus: menus
                .iter()
                .map(|(title, entries)| MenuData {
                    title: title.clone(),
                    entries: entries
                        .iter()
                        .map(|(id, title, shortcut, enabled)| match enabled {
                            Some(enabled) => MenuEntry::Item {
                                id: *id,
                                title: title.clone(),
                                shortcut: *shortcut,
                                enabled: enabled.get(),
                            },
                            None => MenuEntry::Separator,
                        })
                        .collect(),
                })
                .collect(),
        });
        (data, handlers)
    }
}

// ----------------------------------------------------------- async glue

struct OneShot<T> {
    value: Option<T>,
    waker: Option<Waker>,
}

/// A reply callback and the future that resolves when it is called.
pub(crate) fn reply_future<T: 'static>() -> (Reply<T>, impl Future<Output = T> + use<T>) {
    let shared = Rc::new(RefCell::new(OneShot { value: None, waker: None }));
    let sender = shared.clone();
    let reply: Reply<T> = Box::new(move |value| {
        let waker = {
            let mut shared = sender.borrow_mut();
            shared.value = Some(value);
            shared.waker.take()
        };
        if let Some(waker) = waker {
            waker.wake();
        }
    });
    let future = std::future::poll_fn(move |cx| {
        let mut shared = shared.borrow_mut();
        match shared.value.take() {
            Some(value) => Poll::Ready(value),
            None => {
                shared.waker = Some(cx.waker().clone());
                Poll::Pending
            }
        }
    });
    (reply, future)
}

fn ui() -> Ui {
    crate::task::current_ui()
}

pub fn clipboard_text() -> impl Future<Output = Option<String>> + use<> {
    ui().clipboard_text()
}

/// Puts text on the clipboard right away; await to learn whether it worked.
pub fn set_clipboard_text(text: &str) -> impl Future<Output = Result<(), ServiceError>> + use<> {
    ui().set_clipboard_text(text)
}

/// Shows an alert on the active window; resolves to the chosen button's index.
pub fn alert(alert: Alert) -> impl Future<Output = usize> + use<> {
    ui().alert(None, alert)
}

pub fn open_file(request: OpenFile) -> impl Future<Output = Option<Vec<PathBuf>>> + use<> {
    ui().open_file(None, request)
}

pub fn save_file(request: SaveFile) -> impl Future<Output = Option<PathBuf>> + use<> {
    ui().save_file(None, request)
}

/// Installs the app's menus; see [`Ui::set_menu`].
pub fn set_menu(menu: MenuBar) {
    ui().set_menu(menu);
}