mitsuami-core 2.5.2

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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//! Platform services on a `Ui`: the clipboard, dialogs, the trash,
//! launching, notifications, later launches, menus, the tray icon and
//! quitting.

use std::rc::Rc;

use crate::command::UiEvent;
use crate::services::{
    Alert, Launch, MenuBar, MenuBarData, MenuRole, Notification, OpenFile, Reopen, SaveFile, ServiceError, Services,
    TrayData, TrayIcon, reply_future,
};
use crate::widget::NodeId;

use super::{Handler0, NotificationHandler, ReopenHandler, Ui};

impl Ui {
    /// Replaces the platform services (tests install a scripted fake).
    pub fn set_services(&self, services: Box<dyn Services>) {
        *self.services.borrow_mut() = services;
    }

    pub fn clipboard_text(&self) -> impl std::future::Future<Output = Option<String>> + use<> {
        let (reply, text) = reply_future();
        self.services.borrow_mut().clipboard_text(reply);
        text
    }

    /// Puts text on the clipboard. The write is issued right away; await
    /// the result to learn whether it worked.
    pub fn set_clipboard_text(
        &self,
        text: &str,
    ) -> impl std::future::Future<Output = Result<(), ServiceError>> + use<> {
        let (reply, done) = reply_future();
        self.services.borrow_mut().set_clipboard_text(text, reply);
        done
    }

    /// Shows an alert; resolves to the index of the chosen button.
    pub fn alert(&self, parent: Option<NodeId>, alert: Alert) -> impl std::future::Future<Output = usize> + use<> {
        let (reply, answer) = reply_future();
        self.services.borrow_mut().alert(parent, &alert, reply);
        answer
    }

    /// Resolves to the chosen paths, or `None` if cancelled.
    pub fn open_file(
        &self,
        parent: Option<NodeId>,
        request: OpenFile,
    ) -> impl std::future::Future<Output = Option<Vec<std::path::PathBuf>>> + use<> {
        let (reply, answer) = reply_future();
        self.services.borrow_mut().open_file(parent, &request, reply);
        answer
    }

    pub fn save_file(
        &self,
        parent: Option<NodeId>,
        request: SaveFile,
    ) -> impl std::future::Future<Output = Option<std::path::PathBuf>> + use<> {
        let (reply, answer) = reply_future();
        self.services.borrow_mut().save_file(parent, &request, reply);
        answer
    }

    /// Moves files and folders to the trash; see [`Services::trash`].
    pub fn trash(
        &self,
        parent: Option<NodeId>,
        paths: Vec<std::path::PathBuf>,
    ) -> impl std::future::Future<Output = Result<(), ServiceError>> + use<> {
        let (reply, done) = reply_future();
        self.services.borrow_mut().trash(parent, &paths, reply);
        done
    }

    /// Opens a file, folder or URL in another app; see [`Services::launch`].
    pub fn launch(
        &self,
        parent: Option<NodeId>,
        target: Launch,
    ) -> impl std::future::Future<Output = Result<(), ServiceError>> + use<> {
        let (reply, done) = reply_future();
        self.services.borrow_mut().launch(parent, &target, reply);
        done
    }

    /// Shows a notification outside the app's windows; see
    /// [`Services::notify`]. Resolves once the platform has it.
    pub fn notify(
        &self,
        mut notification: Notification,
    ) -> impl std::future::Future<Output = Result<(), ServiceError>> + use<> {
        if notification.id.is_none() {
            let mut inner = self.inner.borrow_mut();
            notification.id = Some(format!("mitsuami-{}", inner.next_notification));
            inner.next_notification += 1;
        }
        let (reply, done) = reply_future();
        self.services.borrow_mut().notify(&notification, self.notification_activated(), reply);
        done
    }

    /// Takes away the notification with this id, if it's still there.
    pub fn withdraw_notification(&self, id: &str) {
        self.services.borrow_mut().withdraw_notification(id);
    }

    /// Runs `handler` with a notification's id when the user clicks it,
    /// until the current scope ends. The platform has brought the app
    /// forward by then; the app shows what the notification was about.
    pub fn on_notification_activated(&self, handler: impl Fn(&str) + 'static) {
        // In the scope it was installed from, so it can spawn tasks that
        // live as long as it, as menu items do.
        let scope = mitsuami_reactive::Owner::current();
        let handler: NotificationHandler = Rc::new(move |id| match scope {
            Some(scope) if scope.is_alive() => scope.with(|| handler(id)),
            _ => handler(id),
        });
        let token = {
            let mut inner = self.inner.borrow_mut();
            let token = inner.next_notification_handler;
            inner.next_notification_handler += 1;
            inner.notification_handlers.insert(token, handler);
            token
        };
        let ui = self.downgrade();
        mitsuami_reactive::on_cleanup(move || {
            if let Some(ui) = ui.upgrade() {
                ui.inner.borrow_mut().notification_handlers.remove(&token);
            }
        });
    }

    /// What platforms call with the id of the notification clicked.
    fn notification_activated(&self) -> Rc<dyn Fn(String)> {
        let weak = self.downgrade();
        Rc::new(move |id| {
            if let Some(ui) = weak.upgrade() {
                ui.inner.borrow_mut().notification_queue.push_back(id);
                ui.changed();
            }
        })
    }

    /// Runs `handler` each time a single-instance app is launched again,
    /// with what the launch passed on, until the current scope ends. The
    /// backend has brought the last active window forward by then, with
    /// the platform's activation token; an app with none opens one here,
    /// and the token is still there for it. Without a handler, a launch
    /// only brings the window forward. On macOS a click on the Dock icon
    /// comes here too: it's how macOS apps reopen a closed window.
    pub fn on_reopen(&self, handler: impl Fn(&Reopen) + 'static) {
        let scope = mitsuami_reactive::Owner::current();
        let handler: ReopenHandler = Rc::new(move |reopen| match scope {
            Some(scope) if scope.is_alive() => scope.with(|| handler(reopen)),
            _ => handler(reopen),
        });
        let token = {
            let mut inner = self.inner.borrow_mut();
            let token = inner.next_reopen_handler;
            inner.next_reopen_handler += 1;
            inner.reopen_handlers.insert(token, handler);
            token
        };
        let ui = self.downgrade();
        mitsuami_reactive::on_cleanup(move || {
            if let Some(ui) = ui.upgrade() {
                ui.inner.borrow_mut().reopen_handlers.remove(&token);
            }
        });
    }

    /// What backends call, on the main thread, when the app is launched
    /// again, once they've brought its window forward: the `on_reopen`
    /// handlers run in the next turn.
    pub fn reopen(&self, reopen: Reopen) {
        self.inner.borrow_mut().reopen_queue.push_back(reopen);
        self.changed();
    }

    /// Installs the app's menus, replacing the ones installed before.
    /// Their reactive parts (titles, enabled and checked states, which
    /// items there are) are sent to the platform again when they change,
    /// for as long as the current scope lives.
    pub fn set_menu(&self, menu: MenuBar) {
        self.install_menu(None, menu);
    }

    /// Installs a window's own menus, shown with the app's, until the
    /// current scope ends. A [`MenuBar`] in the window's content does this.
    pub fn set_window_menu(&self, window: NodeId, menu: MenuBar) {
        self.install_menu(Some(window), menu);
        let ui = self.downgrade();
        mitsuami_reactive::on_cleanup(move || {
            if let Some(ui) = ui.upgrade() {
                ui.remove_menu(Some(window));
            }
        });
    }

    fn install_menu(&self, target: Option<NodeId>, menu: MenuBar) {
        // Handlers run in the scope the menu was installed from, so they
        // can spawn tasks that live as long as it.
        let scope = mitsuami_reactive::Owner::current();
        let activate = self.menu_activate();
        // Weak: menus installed outside any scope (a C caller's) keep their
        // effect, which mustn't keep the `Ui` and the platform alive.
        let weak = self.downgrade();
        let mut ids = Vec::new();
        let effect = mitsuami_reactive::effect(move || {
            // Backends title some items themselves (AppKit's Quit, GNOME's
            // and KDE's), in the app's language.
            crate::l10n::track();
            let Some(ui) = weak.upgrade() else { return };
            let mut new_id = || {
                let mut inner = ui.inner.borrow_mut();
                inner.next_menu_id += 1;
                inner.next_menu_id - 1
            };
            let (data, handlers) = menu.collect(&mut ids, &mut new_id);
            let handlers = handlers
                .into_iter()
                .map(|(id, handler)| {
                    let handler: Handler0 = Rc::new(move || match scope {
                        Some(scope) if scope.is_alive() => scope.with(|| handler()),
                        _ => handler(),
                    });
                    (id, handler)
                })
                .collect();
            let quit = data.clone().take_role(MenuRole::Quit).filter(|item| item.enabled).map(|item| item.id);
            let mut inner = ui.inner.borrow_mut();
            inner.menu_handlers.insert(target, handlers);
            match quit {
                Some(id) => _ = inner.quit_items.insert(target, id),
                None => _ = inner.quit_items.remove(&target),
            }
            drop(inner);
            ui.services.borrow_mut().set_menu(target, &data, activate.clone());
        });
        if let Some(replaced) = self.inner.borrow_mut().menu_effects.insert(target, effect) {
            replaced.dispose();
        }
    }

    /// Removes a window's menus, when the scope that installed them ends.
    fn remove_menu(&self, target: Option<NodeId>) {
        let effect = {
            let mut inner = self.inner.borrow_mut();
            inner.menu_handlers.remove(&target);
            inner.quit_items.remove(&target);
            inner.menu_effects.remove(&target)
        };
        if let Some(effect) = effect {
            effect.dispose();
            self.services.borrow_mut().set_menu(target, &MenuBarData::default(), self.menu_activate());
        }
    }

    /// Shows the app's icon in the platform's tray until the current scope
    /// ends, replacing the one shown before. Its reactive parts (title,
    /// icon, tooltip, the menu's items) are sent to the platform again
    /// when they change. Where there's no tray to show it in (plain GNOME,
    /// or a Linux tray host that isn't running yet), it shows once one
    /// comes: see [`tray_shown`](Self::tray_shown).
    pub fn set_tray(&self, tray: TrayIcon) {
        let scope = mitsuami_reactive::Owner::current();
        let activate = self.menu_activate();
        let shown = self.tray_shown_reporter();
        let weak = self.downgrade();
        let mut ids = Vec::new();
        // What the platform shows, so a change that leaves it the same
        // (a hidden item's title) isn't sent again; with the app info's
        // version, as a tray without an icon shows the app's.
        let mut sent: Option<(TrayData, u64)> = None;
        let effect = mitsuami_reactive::effect(move || {
            let Some(ui) = weak.upgrade() else { return };
            let mut new_id = || {
                let mut inner = ui.inner.borrow_mut();
                inner.next_menu_id += 1;
                inner.next_menu_id - 1
            };
            let (menu, handlers) = tray.menu.collect_entries(&mut ids, &mut new_id);
            let data = TrayData {
                title: tray.title.get(),
                icon: tray.icon.as_ref().map(|icon| icon.get()),
                tooltip: tray.tooltip.get(),
                menu,
            };
            ui.inner.borrow_mut().tray_handlers = handlers
                .into_iter()
                .map(|(id, handler)| {
                    let handler: Handler0 = Rc::new(move || match scope {
                        Some(scope) if scope.is_alive() => scope.with(|| handler()),
                        _ => handler(),
                    });
                    (id, handler)
                })
                .collect();
            let app_info = ui.inner.borrow().app_info_changes;
            let sending = (data, app_info.get());
            if sent.as_ref() != Some(&sending) {
                // Batched: the backend reports `tray_shown` from inside, and
                // effects watching it may call services themselves.
                mitsuami_reactive::batch(|| {
                    ui.services.borrow_mut().set_tray(Some(&sending.0), activate.clone(), shown.clone())
                });
                sent = Some(sending);
            }
        });
        let token = {
            let mut inner = self.inner.borrow_mut();
            let token = inner.next_tray;
            inner.next_tray += 1;
            token
        };
        if let Some((_, replaced)) = self.inner.borrow_mut().tray_effect.replace((token, effect)) {
            replaced.dispose();
        }
        let ui = self.downgrade();
        mitsuami_reactive::on_cleanup(move || {
            if let Some(ui) = ui.upgrade() {
                ui.remove_tray(token);
            }
        });
    }

    /// Takes the tray icon away when the scope that installed it ends,
    /// unless another replaced it since.
    fn remove_tray(&self, token: u64) {
        let effect = {
            let mut inner = self.inner.borrow_mut();
            if inner.tray_effect.as_ref().is_none_or(|(shown, _)| *shown != token) {
                return;
            }
            inner.tray_handlers.clear();
            inner.tray_effect.take().map(|(_, effect)| effect)
        };
        if let Some(effect) = effect {
            effect.dispose();
        }
        mitsuami_reactive::batch(|| {
            self.services.borrow_mut().set_tray(None, self.menu_activate(), self.tray_shown_reporter())
        });
    }

    /// Whether the tray icon is showing right now: false before the app
    /// sets one, where the platform has no tray (plain GNOME), and while a
    /// Linux tray host is away. An app that hides its window on close only
    /// when there's a tray to bring it back watches it. The signal lives as
    /// long as the Ui.
    pub fn tray_shown(&self) -> mitsuami_reactive::Signal<bool> {
        self.inner.borrow().tray_shown
    }

    /// What platforms call when the icon starts or stops showing.
    fn tray_shown_reporter(&self) -> Rc<dyn Fn(bool)> {
        let weak = self.downgrade();
        Rc::new(move |shown| {
            if let Some(ui) = weak.upgrade() {
                let signal = ui.inner.borrow().tray_shown;
                if signal.get_untracked() != shown {
                    signal.set(shown);
                }
                ui.changed();
            }
        })
    }

    /// Keeps the app running while no window is open, until [`Ui::quit`]:
    /// for an app that waits before it shows one, as for a notification's
    /// click or a request from another process. Without, an app ends when
    /// its last window closes.
    pub fn set_runs_without_windows(&self, runs: bool) {
        self.inner.borrow_mut().runs_without_windows = runs;
        self.changed();
    }

    /// Ends the app once this turn of its run loop is done, with any
    /// windows still open, without asking them first (unlike
    /// [`Ui::request_quit`]).
    pub fn quit(&self) {
        self.inner.borrow_mut().quit_requested = true;
        self.changed();
    }

    /// Whether the run loop should end now: [`Ui::quit`] was called, or no
    /// window is open and the app doesn't run without them. Backends ask
    /// after each turn, and before running at all.
    pub fn should_end(&self) -> bool {
        let inner = self.inner.borrow();
        inner.quit_requested || (inner.windows.is_empty() && !inner.runs_without_windows)
    }

    /// Quitting as the platform asks for it from outside the app's menus
    /// (macOS's Dock, logging out, the session ending): the app's Quit item,
    /// as if chosen, if it has one; otherwise every window is asked to
    /// close, as by its close button. Either way the app decides, and it
    /// ends when its last window closes. Backends call it, then see
    /// whether windows are left.
    pub fn request_quit(&self) {
        let (quit, events, windows) = {
            let inner = self.inner.borrow();
            // The app's own item first, else a window's.
            let quit = inner.quit_items.get(&None).or_else(|| inner.quit_items.values().next()).copied();
            (quit, inner.events.clone(), inner.windows.clone())
        };
        match quit {
            Some(id) => self.inner.borrow_mut().menu_queue.push_back(id),
            None => {
                for window in windows {
                    events.emit(window, UiEvent::WindowCloseRequested);
                }
            }
        }
        self.changed();
    }

    /// What platforms call with the id of the item chosen.
    fn menu_activate(&self) -> Rc<dyn Fn(u32)> {
        let weak = self.downgrade();
        Rc::new(move |id| {
            if let Some(ui) = weak.upgrade() {
                ui.inner.borrow_mut().menu_queue.push_back(id);
                ui.changed();
            }
        })
    }
}