Skip to main content

mitsuami_core/ui/
mod.rs

1//! The retained node tree and the update pipeline.
2//!
3//! The core tree is the source of truth. Backends mirror its *native* part:
4//! every node except fragments, which are spliced into their nearest native
5//! ancestor. Changes queue [`Command`]s; [`Ui::commit`] resolves styles, syncs
6//! native children, applies the batch, runs layout and sends the new frames.
7
8mod accessibility;
9mod build;
10mod focus;
11mod layout;
12mod pipeline;
13mod queries;
14mod scroll;
15mod services;
16mod styles;
17mod tree;
18
19use std::cell::RefCell;
20use std::collections::{BTreeMap, BTreeSet};
21use std::rc::{Rc, Weak};
22
23use taffy::TaffyTree;
24
25use crate::a11y::A11yProps;
26use crate::app_info::AppInfo;
27use crate::backend::{Backend, EventSink, PlatformMetrics};
28use crate::command::{Command, UiEvent};
29use crate::custom::CustomProps;
30use crate::geometry::{Insets, Point, Rect, Size};
31use crate::services::Services;
32use crate::style::Style;
33use crate::task::{Clock, Executor, Sleep, TaskHandle};
34use crate::widget::{NodeId, Prop, RowKey, WidgetKind};
35
36/// A window's toolbar items and sidebar, and popovers, are the platform's
37/// to place, around its content or by their parent: they aren't in their
38/// parent's layout box.
39fn in_chrome(kind: WidgetKind) -> bool {
40    matches!(kind, WidgetKind::ToolbarItem | WidgetKind::Sidebar | WidgetKind::Popover)
41}
42
43pub(crate) type Handler = Rc<dyn Fn(&UiEvent)>;
44type Handler0 = Rc<dyn Fn()>;
45/// Runs with the id of a notification the user clicked.
46type NotificationHandler = Rc<dyn Fn(&str)>;
47/// Runs with a later launch of a single-instance app.
48type ReopenHandler = Rc<dyn Fn(&crate::services::Reopen)>;
49
50struct Node {
51    kind: WidgetKind,
52    parent: Option<NodeId>,
53    children: Vec<NodeId>,
54    /// Native nodes only: the flattened children last sent to the backend.
55    native_children: Vec<NodeId>,
56    native_parent: Option<NodeId>,
57    props: Vec<Prop>,
58    style: Style,
59    a11y: A11yProps,
60    test_id: Option<String>,
61    tab_index: Option<u32>,
62    handlers: Vec<Handler>,
63    taffy: Option<taffy::NodeId>,
64    /// Relative to the native parent.
65    frame: Rect,
66    /// Whether the backend has been sent a frame: a node laid out at zero
67    /// (hidden from the start) still gets one, so the backend hides it.
68    framed: bool,
69    /// Windows only: content size.
70    window_size: Size,
71    /// Windows only: how the height follows the content.
72    fit: Fit,
73    /// Windows following their content only: the heights the core gave the
74    /// window, oldest first: the last the platform reported, and the ones
75    /// since that it hasn't yet.
76    heights: Vec<f32>,
77    /// ScrollViews, Lists and Tables only: how far the content is scrolled.
78    scroll_offset: Point,
79    /// Lists only: the width the platform gives their rows, if not their own.
80    row_width: Option<f32>,
81    /// Trees only: how far the platform indents their rows' content.
82    tree_indent: crate::TreeIndent,
83    /// ScrollViews only: where the platform's viewport is in the frame.
84    viewport_insets: Insets,
85    /// Tables only: the widths the platform gives their columns' cells.
86    column_widths: Option<Vec<f32>>,
87    /// Tables only: their rows' heights without their cells that fill
88    /// them, as the platform reported them.
89    row_heights: BTreeMap<RowKey, f32>,
90    /// Tabs and groups only: the size of their tab strip, or heading, and
91    /// border, with no content.
92    strip: Size,
93    /// Groups only: where the backend puts their content, if not where
94    /// the metrics say.
95    insets: Option<crate::Insets>,
96    /// Drawn custom widgets only: the size their drawing was made at, until
97    /// their props or the metrics change.
98    drawn_at: Option<Size>,
99}
100
101/// How a window's height follows its content (`WindowSize`).
102#[derive(Clone, Copy, Debug, PartialEq)]
103enum Fit {
104    None,
105    /// At the first layout.
106    Once,
107    Follow {
108        until_resized: bool,
109    },
110}
111
112impl Node {
113    fn in_full_screen(&self) -> bool {
114        crate::find_prop!(self.props, FullScreen).unwrap_or(false)
115    }
116
117    fn prop(&self, key: &Prop) -> Option<&Prop> {
118        self.props.iter().find(|p| p.key() == key.key())
119    }
120
121    fn custom(&self) -> Option<&CustomProps> {
122        self.props.iter().find_map(|p| match p {
123            Prop::Custom(custom) => Some(custom),
124            _ => None,
125        })
126    }
127
128    /// Drawn custom widgets are measured and drawn by the core.
129    fn drawn(&self) -> Option<&CustomProps> {
130        self.custom().filter(|c| c.is_drawn())
131    }
132}
133
134struct Inner {
135    backend: Box<dyn Backend>,
136    events: EventSink,
137    metrics: PlatformMetrics,
138    nodes: BTreeMap<NodeId, Node>,
139    taffy: TaffyTree<NodeId>,
140    next_id: u32,
141    pending: Vec<Command>,
142    /// The nodes whose `Create` is in `pending`, so props set on the others
143    /// don't look for theirs.
144    created: std::collections::HashSet<NodeId>,
145    /// Focus requests, sent after the structure of the batch: a node focused
146    /// right after it's built isn't in a window yet.
147    pending_focus: Vec<NodeId>,
148    /// Nodes whose windows code asked to bring forward.
149    pending_present: Vec<NodeId>,
150    /// Text selections asked for, sent after the focus requests.
151    pending_selections: Vec<(NodeId, std::ops::Range<usize>)>,
152    windows: Vec<NodeId>,
153    /// Windows destroyed since the last commit, whose dialogs the services
154    /// close before the batch goes out.
155    destroyed_windows: Vec<NodeId>,
156    styles_dirty: bool,
157    resync: BTreeSet<NodeId>,
158    /// Each menu bar's item handlers: the app's (`None`) and windows'.
159    menu_handlers: BTreeMap<Option<NodeId>, std::collections::HashMap<u32, Handler0>>,
160    /// The effect keeping each menu bar up to date.
161    menu_effects: BTreeMap<Option<NodeId>, mitsuami_reactive::Effect>,
162    /// Menu item ids are unique across every bar.
163    next_menu_id: u32,
164    menu_queue: std::collections::VecDeque<u32>,
165    /// The app's Quit item in each menu bar (the app's, `None`, or a
166    /// window's), if it has one that's enabled.
167    quit_items: BTreeMap<Option<NodeId>, u32>,
168    /// What runs when the user clicks a notification, by the token
169    /// `on_notification_activated` removes it with when its scope ends.
170    notification_handlers: BTreeMap<u64, NotificationHandler>,
171    next_notification_handler: u64,
172    /// The ids of the notifications clicked, for the next dispatch.
173    notification_queue: std::collections::VecDeque<String>,
174    /// For the ids the core gives notifications the app didn't name.
175    next_notification: u64,
176    /// What runs when a single-instance app is launched again, by the
177    /// token `on_reopen` removes it with when its scope ends.
178    reopen_handlers: BTreeMap<u64, ReopenHandler>,
179    next_reopen_handler: u64,
180    /// Later launches the backend handed over, for the next dispatch.
181    reopen_queue: std::collections::VecDeque<crate::services::Reopen>,
182    /// The effect keeping the tray icon up to date, by the token its
183    /// scope's cleanup checks it's still the one shown.
184    tray_effect: Option<(u64, mitsuami_reactive::Effect)>,
185    next_tray: u64,
186    /// The tray menu's item handlers; ids are the menu bars'.
187    tray_handlers: std::collections::HashMap<u32, Handler0>,
188    /// Whether the tray icon is showing, as the backend says.
189    tray_shown: mitsuami_reactive::Signal<bool>,
190    /// Bumped by `set_app_info`: the tray shows the app's icon when it
191    /// gives none, so it's sent again.
192    app_info_changes: mitsuami_reactive::Signal<u64>,
193    /// The root the Ui's own signals live in, disposed with it.
194    _signals: SignalRoot,
195    /// Last focus order sent, per window.
196    focus_orders: BTreeMap<NodeId, Vec<NodeId>>,
197    /// Whether a tab index, or what a page shown or a surface taking input
198    /// changed since. The Tab order changes only with them, the tree and
199    /// styles, so other commits don't walk every window for it.
200    focus_dirty: bool,
201    /// The focused control of each window, as reported by the backend.
202    focused: BTreeMap<NodeId, NodeId>,
203    /// The app keeps running while no window is open (until `quit`).
204    runs_without_windows: bool,
205    /// `quit` was called: the run loop ends after this turn.
206    quit_requested: bool,
207    commit_scheduler: Option<Rc<dyn Fn()>>,
208    commit_scheduled: bool,
209    /// The app's language last given to the backend.
210    language: Option<crate::l10n::LanguageIdentifier>,
211    /// Its direction, which windows' content inherits.
212    rtl: bool,
213    /// Sizes views watch (`use_size`, `use_viewport`).
214    observers: BTreeMap<u64, Observer>,
215    next_observer: u64,
216}
217
218/// A size a view watches: the node's it targets now, and the last reported.
219struct Observer {
220    target: Box<dyn Fn() -> Option<NodeId>>,
221    size: mitsuami_reactive::Signal<Size>,
222    last: Size,
223}
224
225/// Handle to a UI instance: one backend, its windows and their node trees.
226/// Cheap to clone; all clones share the same state.
227#[derive(Clone)]
228pub struct Ui {
229    inner: Rc<RefCell<Inner>>,
230    /// Kept apart from `inner`: tasks run while the tree is free to borrow.
231    executor: Rc<Executor>,
232    /// Kept apart too: replies may arrive at any time.
233    services: Rc<RefCell<Box<dyn Services>>>,
234    /// Kept apart too: messages are formatted while the tree is borrowed
235    /// (backends title menus in `apply`).
236    l10n: Rc<crate::l10n::Localization>,
237}
238
239/// Non-owning [`Ui`] handle, for closures stored inside the tree itself.
240#[derive(Clone)]
241pub struct WeakUi {
242    inner: Weak<RefCell<Inner>>,
243    executor: Weak<Executor>,
244    services: Weak<RefCell<Box<dyn Services>>>,
245    l10n: Weak<crate::l10n::Localization>,
246}
247
248impl WeakUi {
249    pub fn upgrade(&self) -> Option<Ui> {
250        Some(Ui {
251            inner: self.inner.upgrade()?,
252            executor: self.executor.upgrade()?,
253            services: self.services.upgrade()?,
254            l10n: self.l10n.upgrade()?,
255        })
256    }
257}
258
259/// Snapshot of one native node, for inspection tools and tests.
260#[derive(Clone, Debug, PartialEq)]
261pub struct NodeInfo {
262    pub id: NodeId,
263    pub kind: WidgetKind,
264    pub props: Vec<Prop>,
265    pub test_id: Option<String>,
266    /// In window coordinates.
267    pub frame: Rect,
268    pub children: Vec<NodeInfo>,
269}
270
271/// The Ui's own signals' root, disposed when the Ui goes (each `Ui` made
272/// one root per signal before, kept until the thread ended, as tests make
273/// many). Disposing does nothing once the thread's runtime is gone.
274struct SignalRoot(mitsuami_reactive::Owner);
275
276impl Drop for SignalRoot {
277    fn drop(&mut self) {
278        self.0.dispose();
279    }
280}
281
282impl Ui {
283    pub fn new(backend: impl Backend + 'static) -> Ui {
284        let mut backend: Box<dyn Backend> = Box::new(backend);
285        let events = EventSink::default();
286        backend.init(events.clone());
287        let metrics = backend.metrics();
288        let services = Rc::new(RefCell::new(backend.services()));
289        let l10n = crate::l10n::Localization::new(backend.locale());
290        // In a root of their own: they live as long as the Ui, whatever
291        // scope makes it.
292        let signals = SignalRoot(mitsuami_reactive::Owner::new_root());
293        let ui = Ui {
294            executor: Rc::default(),
295            services,
296            l10n,
297            inner: Rc::new(RefCell::new(Inner {
298                backend,
299                events,
300                metrics,
301                nodes: BTreeMap::new(),
302                // Frames are rounded from where nodes are in their window
303                // (`collect_frames`), not each on its own.
304                taffy: {
305                    let mut taffy = TaffyTree::new();
306                    taffy.disable_rounding();
307                    taffy
308                },
309                next_id: 1,
310                pending: Vec::new(),
311                created: Default::default(),
312                pending_focus: Vec::new(),
313                pending_present: Vec::new(),
314                pending_selections: Vec::new(),
315                windows: Vec::new(),
316                destroyed_windows: Vec::new(),
317                styles_dirty: true,
318                resync: BTreeSet::new(),
319                focus_orders: BTreeMap::new(),
320                focus_dirty: true,
321                focused: BTreeMap::new(),
322                menu_handlers: BTreeMap::new(),
323                menu_effects: BTreeMap::new(),
324                next_menu_id: 1,
325                menu_queue: Default::default(),
326                quit_items: BTreeMap::new(),
327                notification_handlers: BTreeMap::new(),
328                next_notification_handler: 1,
329                notification_queue: Default::default(),
330                next_notification: 1,
331                reopen_handlers: BTreeMap::new(),
332                next_reopen_handler: 1,
333                reopen_queue: Default::default(),
334                tray_effect: None,
335                next_tray: 1,
336                tray_handlers: Default::default(),
337                tray_shown: signals.0.with(|| mitsuami_reactive::signal(false)),
338                app_info_changes: signals.0.with(|| mitsuami_reactive::signal(0)),
339                _signals: signals,
340                runs_without_windows: false,
341                quit_requested: false,
342                commit_scheduler: None,
343                commit_scheduled: false,
344                language: None,
345                rtl: false,
346                observers: BTreeMap::new(),
347                next_observer: 1,
348            })),
349        };
350        // The next commit gives the backend the new language.
351        let weak = ui.downgrade();
352        ui.l10n.set_on_change(move |_, _| {
353            if let Some(ui) = weak.upgrade() {
354                ui.changed();
355            }
356        });
357        ui
358    }
359
360    pub fn downgrade(&self) -> WeakUi {
361        WeakUi {
362            inner: Rc::downgrade(&self.inner),
363            executor: Rc::downgrade(&self.executor),
364            services: Rc::downgrade(&self.services),
365            l10n: Rc::downgrade(&self.l10n),
366        }
367    }
368
369    // ---------------------------------------------------------------- tasks
370
371    pub(crate) fn executor(&self) -> &Executor {
372        &self.executor
373    }
374
375    /// Runs `future` on the UI thread, polled from [`Ui::tick`]. Unlike the
376    /// free [`spawn_local`](crate::task::spawn_local), it is not tied to a
377    /// reactive scope; cancel it with the returned handle.
378    pub fn spawn_local(&self, future: impl std::future::Future<Output = ()> + 'static) -> TaskHandle {
379        self.spawn_in(future, None)
380    }
381
382    pub(crate) fn spawn_in(
383        &self,
384        future: impl std::future::Future<Output = ()> + 'static,
385        owner: Option<mitsuami_reactive::Owner>,
386    ) -> TaskHandle {
387        let id = self.executor.spawn(Box::pin(future), owner);
388        self.changed();
389        TaskHandle::new(id, self.downgrade())
390    }
391
392    /// A future that completes after `duration` on this `Ui`'s clock.
393    pub fn sleep(&self, duration: std::time::Duration) -> Sleep {
394        Sleep::new(self.clone(), duration)
395    }
396
397    /// Replaces the clock timers use (tests install a [`ManualClock`](crate::task::ManualClock)).
398    pub fn set_clock(&self, clock: Rc<dyn Clock>) {
399        self.executor.set_clock(clock);
400    }
401
402    /// How to make the UI thread's run loop turn from any thread; called
403    /// when a task is woken (e.g. by background work finishing).
404    pub fn set_waker(&self, wake: std::sync::Arc<dyn Fn() + Send + Sync>) {
405        self.executor.set_wake_ui(wake);
406    }
407
408    /// Time until the next timer fires (zero if overdue), for run loops to
409    /// schedule a wake-up.
410    pub fn time_to_next_timer(&self) -> Option<std::time::Duration> {
411        let now = self.executor.now();
412        self.executor.next_deadline().map(|deadline| deadline.saturating_sub(now))
413    }
414
415    /// The app's id, name and icon, for the platform to show. Set it
416    /// before the app's first window; `App` does.
417    pub fn set_app_info(&self, info: AppInfo) {
418        let changes = {
419            let mut inner = self.inner.borrow_mut();
420            inner.backend.set_app_info(&info);
421            inner.app_info_changes
422        };
423        changes.update(|n| *n += 1);
424    }
425
426    /// Tasks that have not finished yet.
427    pub fn pending_tasks(&self) -> usize {
428        self.executor.task_count()
429    }
430
431    pub fn events(&self) -> EventSink {
432        self.inner.borrow().events.clone()
433    }
434
435    pub fn metrics(&self) -> PlatformMetrics {
436        self.inner.borrow().metrics.clone()
437    }
438
439    // --------------------------------------------------------- localization
440
441    /// The app's translations (`locales!`). Set them before the app's
442    /// first window; `App` does. The language is chosen from them again.
443    pub fn set_locales(&self, locales: crate::l10n::Locales) {
444        self.l10n.set_locales(locales);
445    }
446
447    /// The languages to choose the app's from, most wanted first, in place
448    /// of the user's: an app's own language setting, or a test's. `None`:
449    /// the user's, as the platform lists them.
450    pub fn set_languages(&self, languages: Option<Vec<String>>) {
451        self.l10n.set_requested(languages);
452    }
453
454    /// The app's language: the first of the user's it has translations
455    /// for, else its fallback. Tracked.
456    pub fn language(&self) -> crate::l10n::LanguageIdentifier {
457        self.l10n.current()
458    }
459
460    /// Messages missing from every language, and messages that failed to
461    /// format, since the last call. Tests fail on them.
462    pub fn take_l10n_errors(&self) -> Vec<String> {
463        self.l10n.take_errors()
464    }
465
466    /// Native backends call this to learn when a commit is needed. The
467    /// callback should schedule [`Ui::commit`] on the run loop (e.g. before
468    /// the next frame). Without a scheduler, callers commit explicitly.
469    pub fn set_commit_scheduler(&self, schedule: impl Fn() + 'static) {
470        self.inner.borrow_mut().commit_scheduler = Some(Rc::new(schedule));
471    }
472
473    fn changed(&self) {
474        let schedule = {
475            let mut inner = self.inner.borrow_mut();
476            if inner.commit_scheduled {
477                return;
478            }
479            inner.commit_scheduled = true;
480            inner.commit_scheduler.clone()
481        };
482        if let Some(schedule) = schedule {
483            schedule();
484        }
485    }
486}