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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
//! The retained node tree and the update pipeline.
//!
//! The core tree is the source of truth. Backends mirror its *native* part:
//! every node except fragments, which are spliced into their nearest native
//! ancestor. Changes queue [`Command`]s; [`Ui::commit`] resolves styles, syncs
//! native children, applies the batch, runs layout and sends the new frames.

mod accessibility;
mod build;
mod focus;
mod layout;
mod pipeline;
mod queries;
mod scroll;
mod services;
mod styles;
mod tree;

use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet};
use std::rc::{Rc, Weak};

use taffy::TaffyTree;

use crate::a11y::A11yProps;
use crate::app_info::AppInfo;
use crate::backend::{Backend, EventSink, PlatformMetrics};
use crate::command::{Command, UiEvent};
use crate::custom::CustomProps;
use crate::geometry::{Insets, Point, Rect, Size};
use crate::services::Services;
use crate::style::Style;
use crate::task::{Clock, Executor, Sleep, TaskHandle};
use crate::widget::{NodeId, Prop, RowKey, WidgetKind};

/// A window's toolbar items and sidebar, and popovers, are the platform's
/// to place, around its content or by their parent: they aren't in their
/// parent's layout box.
fn in_chrome(kind: WidgetKind) -> bool {
    matches!(kind, WidgetKind::ToolbarItem | WidgetKind::Sidebar | WidgetKind::Popover)
}

pub(crate) type Handler = Rc<dyn Fn(&UiEvent)>;
type Handler0 = Rc<dyn Fn()>;
/// Runs with the id of a notification the user clicked.
type NotificationHandler = Rc<dyn Fn(&str)>;
/// Runs with a later launch of a single-instance app.
type ReopenHandler = Rc<dyn Fn(&crate::services::Reopen)>;

struct Node {
    kind: WidgetKind,
    parent: Option<NodeId>,
    children: Vec<NodeId>,
    /// Native nodes only: the flattened children last sent to the backend.
    native_children: Vec<NodeId>,
    native_parent: Option<NodeId>,
    props: Vec<Prop>,
    style: Style,
    a11y: A11yProps,
    test_id: Option<String>,
    tab_index: Option<u32>,
    handlers: Vec<Handler>,
    taffy: Option<taffy::NodeId>,
    /// Relative to the native parent.
    frame: Rect,
    /// Whether the backend has been sent a frame: a node laid out at zero
    /// (hidden from the start) still gets one, so the backend hides it.
    framed: bool,
    /// Windows only: content size.
    window_size: Size,
    /// Windows only: how the height follows the content.
    fit: Fit,
    /// Windows following their content only: the heights the core gave the
    /// window, oldest first: the last the platform reported, and the ones
    /// since that it hasn't yet.
    heights: Vec<f32>,
    /// ScrollViews, Lists and Tables only: how far the content is scrolled.
    scroll_offset: Point,
    /// Lists only: the width the platform gives their rows, if not their own.
    row_width: Option<f32>,
    /// Trees only: how far the platform indents their rows' content.
    tree_indent: crate::TreeIndent,
    /// ScrollViews only: where the platform's viewport is in the frame.
    viewport_insets: Insets,
    /// Tables only: the widths the platform gives their columns' cells.
    column_widths: Option<Vec<f32>>,
    /// Tables only: their rows' heights without their cells that fill
    /// them, as the platform reported them.
    row_heights: BTreeMap<RowKey, f32>,
    /// Tabs and groups only: the size of their tab strip, or heading, and
    /// border, with no content.
    strip: Size,
    /// Groups only: where the backend puts their content, if not where
    /// the metrics say.
    insets: Option<crate::Insets>,
    /// Drawn custom widgets only: the size their drawing was made at, until
    /// their props or the metrics change.
    drawn_at: Option<Size>,
}

/// How a window's height follows its content (`WindowSize`).
#[derive(Clone, Copy, Debug, PartialEq)]
enum Fit {
    None,
    /// At the first layout.
    Once,
    Follow {
        until_resized: bool,
    },
}

impl Node {
    fn in_full_screen(&self) -> bool {
        crate::find_prop!(self.props, FullScreen).unwrap_or(false)
    }

    fn prop(&self, key: &Prop) -> Option<&Prop> {
        self.props.iter().find(|p| p.key() == key.key())
    }

    fn custom(&self) -> Option<&CustomProps> {
        self.props.iter().find_map(|p| match p {
            Prop::Custom(custom) => Some(custom),
            _ => None,
        })
    }

    /// Drawn custom widgets are measured and drawn by the core.
    fn drawn(&self) -> Option<&CustomProps> {
        self.custom().filter(|c| c.is_drawn())
    }
}

struct Inner {
    backend: Box<dyn Backend>,
    events: EventSink,
    metrics: PlatformMetrics,
    nodes: BTreeMap<NodeId, Node>,
    taffy: TaffyTree<NodeId>,
    next_id: u32,
    pending: Vec<Command>,
    /// The nodes whose `Create` is in `pending`, so props set on the others
    /// don't look for theirs.
    created: std::collections::HashSet<NodeId>,
    /// Focus requests, sent after the structure of the batch: a node focused
    /// right after it's built isn't in a window yet.
    pending_focus: Vec<NodeId>,
    /// Nodes whose windows code asked to bring forward.
    pending_present: Vec<NodeId>,
    /// Text selections asked for, sent after the focus requests.
    pending_selections: Vec<(NodeId, std::ops::Range<usize>)>,
    windows: Vec<NodeId>,
    /// Windows destroyed since the last commit, whose dialogs the services
    /// close before the batch goes out.
    destroyed_windows: Vec<NodeId>,
    styles_dirty: bool,
    resync: BTreeSet<NodeId>,
    /// Each menu bar's item handlers: the app's (`None`) and windows'.
    menu_handlers: BTreeMap<Option<NodeId>, std::collections::HashMap<u32, Handler0>>,
    /// The effect keeping each menu bar up to date.
    menu_effects: BTreeMap<Option<NodeId>, mitsuami_reactive::Effect>,
    /// Menu item ids are unique across every bar.
    next_menu_id: u32,
    menu_queue: std::collections::VecDeque<u32>,
    /// The app's Quit item in each menu bar (the app's, `None`, or a
    /// window's), if it has one that's enabled.
    quit_items: BTreeMap<Option<NodeId>, u32>,
    /// What runs when the user clicks a notification, by the token
    /// `on_notification_activated` removes it with when its scope ends.
    notification_handlers: BTreeMap<u64, NotificationHandler>,
    next_notification_handler: u64,
    /// The ids of the notifications clicked, for the next dispatch.
    notification_queue: std::collections::VecDeque<String>,
    /// For the ids the core gives notifications the app didn't name.
    next_notification: u64,
    /// What runs when a single-instance app is launched again, by the
    /// token `on_reopen` removes it with when its scope ends.
    reopen_handlers: BTreeMap<u64, ReopenHandler>,
    next_reopen_handler: u64,
    /// Later launches the backend handed over, for the next dispatch.
    reopen_queue: std::collections::VecDeque<crate::services::Reopen>,
    /// The effect keeping the tray icon up to date, by the token its
    /// scope's cleanup checks it's still the one shown.
    tray_effect: Option<(u64, mitsuami_reactive::Effect)>,
    next_tray: u64,
    /// The tray menu's item handlers; ids are the menu bars'.
    tray_handlers: std::collections::HashMap<u32, Handler0>,
    /// Whether the tray icon is showing, as the backend says.
    tray_shown: mitsuami_reactive::Signal<bool>,
    /// Bumped by `set_app_info`: the tray shows the app's icon when it
    /// gives none, so it's sent again.
    app_info_changes: mitsuami_reactive::Signal<u64>,
    /// The root the Ui's own signals live in, disposed with it.
    _signals: SignalRoot,
    /// Last focus order sent, per window.
    focus_orders: BTreeMap<NodeId, Vec<NodeId>>,
    /// Whether a tab index, or what a page shown or a surface taking input
    /// changed since. The Tab order changes only with them, the tree and
    /// styles, so other commits don't walk every window for it.
    focus_dirty: bool,
    /// The focused control of each window, as reported by the backend.
    focused: BTreeMap<NodeId, NodeId>,
    /// The app keeps running while no window is open (until `quit`).
    runs_without_windows: bool,
    /// `quit` was called: the run loop ends after this turn.
    quit_requested: bool,
    commit_scheduler: Option<Rc<dyn Fn()>>,
    commit_scheduled: bool,
    /// The app's language last given to the backend.
    language: Option<crate::l10n::LanguageIdentifier>,
    /// Its direction, which windows' content inherits.
    rtl: bool,
    /// Sizes views watch (`use_size`, `use_viewport`).
    observers: BTreeMap<u64, Observer>,
    next_observer: u64,
}

/// A size a view watches: the node's it targets now, and the last reported.
struct Observer {
    target: Box<dyn Fn() -> Option<NodeId>>,
    size: mitsuami_reactive::Signal<Size>,
    last: Size,
}

/// Handle to a UI instance: one backend, its windows and their node trees.
/// Cheap to clone; all clones share the same state.
#[derive(Clone)]
pub struct Ui {
    inner: Rc<RefCell<Inner>>,
    /// Kept apart from `inner`: tasks run while the tree is free to borrow.
    executor: Rc<Executor>,
    /// Kept apart too: replies may arrive at any time.
    services: Rc<RefCell<Box<dyn Services>>>,
    /// Kept apart too: messages are formatted while the tree is borrowed
    /// (backends title menus in `apply`).
    l10n: Rc<crate::l10n::Localization>,
}

/// Non-owning [`Ui`] handle, for closures stored inside the tree itself.
#[derive(Clone)]
pub struct WeakUi {
    inner: Weak<RefCell<Inner>>,
    executor: Weak<Executor>,
    services: Weak<RefCell<Box<dyn Services>>>,
    l10n: Weak<crate::l10n::Localization>,
}

impl WeakUi {
    pub fn upgrade(&self) -> Option<Ui> {
        Some(Ui {
            inner: self.inner.upgrade()?,
            executor: self.executor.upgrade()?,
            services: self.services.upgrade()?,
            l10n: self.l10n.upgrade()?,
        })
    }
}

/// Snapshot of one native node, for inspection tools and tests.
#[derive(Clone, Debug, PartialEq)]
pub struct NodeInfo {
    pub id: NodeId,
    pub kind: WidgetKind,
    pub props: Vec<Prop>,
    pub test_id: Option<String>,
    /// In window coordinates.
    pub frame: Rect,
    pub children: Vec<NodeInfo>,
}

/// The Ui's own signals' root, disposed when the Ui goes (each `Ui` made
/// one root per signal before, kept until the thread ended, as tests make
/// many). Disposing does nothing once the thread's runtime is gone.
struct SignalRoot(mitsuami_reactive::Owner);

impl Drop for SignalRoot {
    fn drop(&mut self) {
        self.0.dispose();
    }
}

impl Ui {
    pub fn new(backend: impl Backend + 'static) -> Ui {
        let mut backend: Box<dyn Backend> = Box::new(backend);
        let events = EventSink::default();
        backend.init(events.clone());
        let metrics = backend.metrics();
        let services = Rc::new(RefCell::new(backend.services()));
        let l10n = crate::l10n::Localization::new(backend.locale());
        // In a root of their own: they live as long as the Ui, whatever
        // scope makes it.
        let signals = SignalRoot(mitsuami_reactive::Owner::new_root());
        let ui = Ui {
            executor: Rc::default(),
            services,
            l10n,
            inner: Rc::new(RefCell::new(Inner {
                backend,
                events,
                metrics,
                nodes: BTreeMap::new(),
                // Frames are rounded from where nodes are in their window
                // (`collect_frames`), not each on its own.
                taffy: {
                    let mut taffy = TaffyTree::new();
                    taffy.disable_rounding();
                    taffy
                },
                next_id: 1,
                pending: Vec::new(),
                created: Default::default(),
                pending_focus: Vec::new(),
                pending_present: Vec::new(),
                pending_selections: Vec::new(),
                windows: Vec::new(),
                destroyed_windows: Vec::new(),
                styles_dirty: true,
                resync: BTreeSet::new(),
                focus_orders: BTreeMap::new(),
                focus_dirty: true,
                focused: BTreeMap::new(),
                menu_handlers: BTreeMap::new(),
                menu_effects: BTreeMap::new(),
                next_menu_id: 1,
                menu_queue: Default::default(),
                quit_items: BTreeMap::new(),
                notification_handlers: BTreeMap::new(),
                next_notification_handler: 1,
                notification_queue: Default::default(),
                next_notification: 1,
                reopen_handlers: BTreeMap::new(),
                next_reopen_handler: 1,
                reopen_queue: Default::default(),
                tray_effect: None,
                next_tray: 1,
                tray_handlers: Default::default(),
                tray_shown: signals.0.with(|| mitsuami_reactive::signal(false)),
                app_info_changes: signals.0.with(|| mitsuami_reactive::signal(0)),
                _signals: signals,
                runs_without_windows: false,
                quit_requested: false,
                commit_scheduler: None,
                commit_scheduled: false,
                language: None,
                rtl: false,
                observers: BTreeMap::new(),
                next_observer: 1,
            })),
        };
        // The next commit gives the backend the new language.
        let weak = ui.downgrade();
        ui.l10n.set_on_change(move |_, _| {
            if let Some(ui) = weak.upgrade() {
                ui.changed();
            }
        });
        ui
    }

    pub fn downgrade(&self) -> WeakUi {
        WeakUi {
            inner: Rc::downgrade(&self.inner),
            executor: Rc::downgrade(&self.executor),
            services: Rc::downgrade(&self.services),
            l10n: Rc::downgrade(&self.l10n),
        }
    }

    // ---------------------------------------------------------------- tasks

    pub(crate) fn executor(&self) -> &Executor {
        &self.executor
    }

    /// Runs `future` on the UI thread, polled from [`Ui::tick`]. Unlike the
    /// free [`spawn_local`](crate::task::spawn_local), it is not tied to a
    /// reactive scope; cancel it with the returned handle.
    pub fn spawn_local(&self, future: impl std::future::Future<Output = ()> + 'static) -> TaskHandle {
        self.spawn_in(future, None)
    }

    pub(crate) fn spawn_in(
        &self,
        future: impl std::future::Future<Output = ()> + 'static,
        owner: Option<mitsuami_reactive::Owner>,
    ) -> TaskHandle {
        let id = self.executor.spawn(Box::pin(future), owner);
        self.changed();
        TaskHandle::new(id, self.downgrade())
    }

    /// A future that completes after `duration` on this `Ui`'s clock.
    pub fn sleep(&self, duration: std::time::Duration) -> Sleep {
        Sleep::new(self.clone(), duration)
    }

    /// Replaces the clock timers use (tests install a [`ManualClock`](crate::task::ManualClock)).
    pub fn set_clock(&self, clock: Rc<dyn Clock>) {
        self.executor.set_clock(clock);
    }

    /// How to make the UI thread's run loop turn from any thread; called
    /// when a task is woken (e.g. by background work finishing).
    pub fn set_waker(&self, wake: std::sync::Arc<dyn Fn() + Send + Sync>) {
        self.executor.set_wake_ui(wake);
    }

    /// Time until the next timer fires (zero if overdue), for run loops to
    /// schedule a wake-up.
    pub fn time_to_next_timer(&self) -> Option<std::time::Duration> {
        let now = self.executor.now();
        self.executor.next_deadline().map(|deadline| deadline.saturating_sub(now))
    }

    /// The app's id, name and icon, for the platform to show. Set it
    /// before the app's first window; `App` does.
    pub fn set_app_info(&self, info: AppInfo) {
        let changes = {
            let mut inner = self.inner.borrow_mut();
            inner.backend.set_app_info(&info);
            inner.app_info_changes
        };
        changes.update(|n| *n += 1);
    }

    /// Tasks that have not finished yet.
    pub fn pending_tasks(&self) -> usize {
        self.executor.task_count()
    }

    pub fn events(&self) -> EventSink {
        self.inner.borrow().events.clone()
    }

    pub fn metrics(&self) -> PlatformMetrics {
        self.inner.borrow().metrics.clone()
    }

    // --------------------------------------------------------- localization

    /// The app's translations (`locales!`). Set them before the app's
    /// first window; `App` does. The language is chosen from them again.
    pub fn set_locales(&self, locales: crate::l10n::Locales) {
        self.l10n.set_locales(locales);
    }

    /// The languages to choose the app's from, most wanted first, in place
    /// of the user's: an app's own language setting, or a test's. `None`:
    /// the user's, as the platform lists them.
    pub fn set_languages(&self, languages: Option<Vec<String>>) {
        self.l10n.set_requested(languages);
    }

    /// The app's language: the first of the user's it has translations
    /// for, else its fallback. Tracked.
    pub fn language(&self) -> crate::l10n::LanguageIdentifier {
        self.l10n.current()
    }

    /// Messages missing from every language, and messages that failed to
    /// format, since the last call. Tests fail on them.
    pub fn take_l10n_errors(&self) -> Vec<String> {
        self.l10n.take_errors()
    }

    /// Native backends call this to learn when a commit is needed. The
    /// callback should schedule [`Ui::commit`] on the run loop (e.g. before
    /// the next frame). Without a scheduler, callers commit explicitly.
    pub fn set_commit_scheduler(&self, schedule: impl Fn() + 'static) {
        self.inner.borrow_mut().commit_scheduler = Some(Rc::new(schedule));
    }

    fn changed(&self) {
        let schedule = {
            let mut inner = self.inner.borrow_mut();
            if inner.commit_scheduled {
                return;
            }
            inner.commit_scheduled = true;
            inner.commit_scheduler.clone()
        };
        if let Some(schedule) = schedule {
            schedule();
        }
    }
}