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
46struct Node {
47    kind: WidgetKind,
48    parent: Option<NodeId>,
49    children: Vec<NodeId>,
50    /// Native nodes only: the flattened children last sent to the backend.
51    native_children: Vec<NodeId>,
52    native_parent: Option<NodeId>,
53    props: Vec<Prop>,
54    style: Style,
55    a11y: A11yProps,
56    test_id: Option<String>,
57    tab_index: Option<u32>,
58    handlers: Vec<Handler>,
59    taffy: Option<taffy::NodeId>,
60    /// Relative to the native parent.
61    frame: Rect,
62    /// Whether the backend has been sent a frame: a node laid out at zero
63    /// (hidden from the start) still gets one, so the backend hides it.
64    framed: bool,
65    /// Windows only: content size.
66    window_size: Size,
67    /// Windows only: how the height follows the content.
68    fit: Fit,
69    /// Windows following their content only: the heights the core gave the
70    /// window, oldest first: the last the platform reported, and the ones
71    /// since that it hasn't yet.
72    heights: Vec<f32>,
73    /// ScrollViews, Lists and Tables only: how far the content is scrolled.
74    scroll_offset: Point,
75    /// Lists only: the width the platform gives their rows, if not their own.
76    row_width: Option<f32>,
77    /// Trees only: how far the platform indents their rows' content.
78    tree_indent: crate::TreeIndent,
79    /// ScrollViews only: where the platform's viewport is in the frame.
80    viewport_insets: Insets,
81    /// Tables only: the widths the platform gives their columns' cells.
82    column_widths: Option<Vec<f32>>,
83    /// Tables only: their rows' heights without their cells that fill
84    /// them, as the platform reported them.
85    row_heights: BTreeMap<RowKey, f32>,
86    /// Tabs and groups only: the size of their tab strip, or heading, and
87    /// border, with no content.
88    strip: Size,
89    /// Groups only: where the backend puts their content, if not where
90    /// the metrics say.
91    insets: Option<crate::Insets>,
92    /// Drawn custom widgets only: the size their drawing was made at, until
93    /// their props or the metrics change.
94    drawn_at: Option<Size>,
95}
96
97/// How a window's height follows its content (`WindowSize`).
98#[derive(Clone, Copy, Debug, PartialEq)]
99enum Fit {
100    None,
101    /// At the first layout.
102    Once,
103    Follow {
104        until_resized: bool,
105    },
106}
107
108impl Node {
109    fn in_full_screen(&self) -> bool {
110        crate::find_prop!(self.props, FullScreen).unwrap_or(false)
111    }
112
113    fn prop(&self, key: &Prop) -> Option<&Prop> {
114        self.props.iter().find(|p| p.key() == key.key())
115    }
116
117    fn custom(&self) -> Option<&CustomProps> {
118        self.props.iter().find_map(|p| match p {
119            Prop::Custom(custom) => Some(custom),
120            _ => None,
121        })
122    }
123
124    /// Drawn custom widgets are measured and drawn by the core.
125    fn drawn(&self) -> Option<&CustomProps> {
126        self.custom().filter(|c| c.is_drawn())
127    }
128}
129
130struct Inner {
131    backend: Box<dyn Backend>,
132    events: EventSink,
133    metrics: PlatformMetrics,
134    nodes: BTreeMap<NodeId, Node>,
135    taffy: TaffyTree<NodeId>,
136    next_id: u32,
137    pending: Vec<Command>,
138    /// The nodes whose `Create` is in `pending`, so props set on the others
139    /// don't look for theirs.
140    created: std::collections::HashSet<NodeId>,
141    /// Focus requests, sent after the structure of the batch: a node focused
142    /// right after it's built isn't in a window yet.
143    pending_focus: Vec<NodeId>,
144    /// Text selections asked for, sent after the focus requests.
145    pending_selections: Vec<(NodeId, std::ops::Range<usize>)>,
146    windows: Vec<NodeId>,
147    /// Windows destroyed since the last commit, whose dialogs the services
148    /// close before the batch goes out.
149    destroyed_windows: Vec<NodeId>,
150    styles_dirty: bool,
151    resync: BTreeSet<NodeId>,
152    /// Each menu bar's item handlers: the app's (`None`) and windows'.
153    menu_handlers: BTreeMap<Option<NodeId>, std::collections::HashMap<u32, Handler0>>,
154    /// The effect keeping each menu bar up to date.
155    menu_effects: BTreeMap<Option<NodeId>, mitsuami_reactive::Effect>,
156    /// Menu item ids are unique across every bar.
157    next_menu_id: u32,
158    menu_queue: std::collections::VecDeque<u32>,
159    /// The app's Quit item in each menu bar (the app's, `None`, or a
160    /// window's), if it has one that's enabled.
161    quit_items: BTreeMap<Option<NodeId>, u32>,
162    /// Last focus order sent, per window.
163    focus_orders: BTreeMap<NodeId, Vec<NodeId>>,
164    /// Whether a tab index, or what a page shown or a surface taking input
165    /// changed since. The Tab order changes only with them, the tree and
166    /// styles, so other commits don't walk every window for it.
167    focus_dirty: bool,
168    /// The focused control of each window, as reported by the backend.
169    focused: BTreeMap<NodeId, NodeId>,
170    commit_scheduler: Option<Rc<dyn Fn()>>,
171    commit_scheduled: bool,
172    /// The app's language last given to the backend.
173    language: Option<crate::l10n::LanguageIdentifier>,
174    /// Its direction, which windows' content inherits.
175    rtl: bool,
176    /// Sizes views watch (`use_size`, `use_viewport`).
177    observers: BTreeMap<u64, Observer>,
178    next_observer: u64,
179}
180
181/// A size a view watches: the node's it targets now, and the last reported.
182struct Observer {
183    target: Box<dyn Fn() -> Option<NodeId>>,
184    size: mitsuami_reactive::Signal<Size>,
185    last: Size,
186}
187
188/// Handle to a UI instance: one backend, its windows and their node trees.
189/// Cheap to clone; all clones share the same state.
190#[derive(Clone)]
191pub struct Ui {
192    inner: Rc<RefCell<Inner>>,
193    /// Kept apart from `inner`: tasks run while the tree is free to borrow.
194    executor: Rc<Executor>,
195    /// Kept apart too: replies may arrive at any time.
196    services: Rc<RefCell<Box<dyn Services>>>,
197    /// Kept apart too: messages are formatted while the tree is borrowed
198    /// (backends title menus in `apply`).
199    l10n: Rc<crate::l10n::Localization>,
200}
201
202/// Non-owning [`Ui`] handle, for closures stored inside the tree itself.
203#[derive(Clone)]
204pub struct WeakUi {
205    inner: Weak<RefCell<Inner>>,
206    executor: Weak<Executor>,
207    services: Weak<RefCell<Box<dyn Services>>>,
208    l10n: Weak<crate::l10n::Localization>,
209}
210
211impl WeakUi {
212    pub fn upgrade(&self) -> Option<Ui> {
213        Some(Ui {
214            inner: self.inner.upgrade()?,
215            executor: self.executor.upgrade()?,
216            services: self.services.upgrade()?,
217            l10n: self.l10n.upgrade()?,
218        })
219    }
220}
221
222/// Snapshot of one native node, for inspection tools and tests.
223#[derive(Clone, Debug, PartialEq)]
224pub struct NodeInfo {
225    pub id: NodeId,
226    pub kind: WidgetKind,
227    pub props: Vec<Prop>,
228    pub test_id: Option<String>,
229    /// In window coordinates.
230    pub frame: Rect,
231    pub children: Vec<NodeInfo>,
232}
233
234impl Ui {
235    pub fn new(backend: impl Backend + 'static) -> Ui {
236        let mut backend: Box<dyn Backend> = Box::new(backend);
237        let events = EventSink::default();
238        backend.init(events.clone());
239        let metrics = backend.metrics();
240        let services = Rc::new(RefCell::new(backend.services()));
241        let l10n = crate::l10n::Localization::new(backend.locale());
242        let ui = Ui {
243            executor: Rc::default(),
244            services,
245            l10n,
246            inner: Rc::new(RefCell::new(Inner {
247                backend,
248                events,
249                metrics,
250                nodes: BTreeMap::new(),
251                // Frames are rounded from where nodes are in their window
252                // (`collect_frames`), not each on its own.
253                taffy: {
254                    let mut taffy = TaffyTree::new();
255                    taffy.disable_rounding();
256                    taffy
257                },
258                next_id: 1,
259                pending: Vec::new(),
260                created: Default::default(),
261                pending_focus: Vec::new(),
262                pending_selections: Vec::new(),
263                windows: Vec::new(),
264                destroyed_windows: Vec::new(),
265                styles_dirty: true,
266                resync: BTreeSet::new(),
267                focus_orders: BTreeMap::new(),
268                focus_dirty: true,
269                focused: BTreeMap::new(),
270                menu_handlers: BTreeMap::new(),
271                menu_effects: BTreeMap::new(),
272                next_menu_id: 1,
273                menu_queue: Default::default(),
274                quit_items: BTreeMap::new(),
275                commit_scheduler: None,
276                commit_scheduled: false,
277                language: None,
278                rtl: false,
279                observers: BTreeMap::new(),
280                next_observer: 1,
281            })),
282        };
283        // The next commit gives the backend the new language.
284        let weak = ui.downgrade();
285        ui.l10n.set_on_change(move |_, _| {
286            if let Some(ui) = weak.upgrade() {
287                ui.changed();
288            }
289        });
290        ui
291    }
292
293    pub fn downgrade(&self) -> WeakUi {
294        WeakUi {
295            inner: Rc::downgrade(&self.inner),
296            executor: Rc::downgrade(&self.executor),
297            services: Rc::downgrade(&self.services),
298            l10n: Rc::downgrade(&self.l10n),
299        }
300    }
301
302    // ---------------------------------------------------------------- tasks
303
304    pub(crate) fn executor(&self) -> &Executor {
305        &self.executor
306    }
307
308    /// Runs `future` on the UI thread, polled from [`Ui::tick`]. Unlike the
309    /// free [`spawn_local`](crate::task::spawn_local), it is not tied to a
310    /// reactive scope; cancel it with the returned handle.
311    pub fn spawn_local(&self, future: impl std::future::Future<Output = ()> + 'static) -> TaskHandle {
312        self.spawn_in(future, None)
313    }
314
315    pub(crate) fn spawn_in(
316        &self,
317        future: impl std::future::Future<Output = ()> + 'static,
318        owner: Option<mitsuami_reactive::Owner>,
319    ) -> TaskHandle {
320        let id = self.executor.spawn(Box::pin(future), owner);
321        self.changed();
322        TaskHandle::new(id, self.downgrade())
323    }
324
325    /// A future that completes after `duration` on this `Ui`'s clock.
326    pub fn sleep(&self, duration: std::time::Duration) -> Sleep {
327        Sleep::new(self.clone(), duration)
328    }
329
330    /// Replaces the clock timers use (tests install a [`ManualClock`](crate::task::ManualClock)).
331    pub fn set_clock(&self, clock: Rc<dyn Clock>) {
332        self.executor.set_clock(clock);
333    }
334
335    /// How to make the UI thread's run loop turn from any thread; called
336    /// when a task is woken (e.g. by background work finishing).
337    pub fn set_waker(&self, wake: std::sync::Arc<dyn Fn() + Send + Sync>) {
338        self.executor.set_wake_ui(wake);
339    }
340
341    /// Time until the next timer fires (zero if overdue), for run loops to
342    /// schedule a wake-up.
343    pub fn time_to_next_timer(&self) -> Option<std::time::Duration> {
344        let now = self.executor.now();
345        self.executor.next_deadline().map(|deadline| deadline.saturating_sub(now))
346    }
347
348    /// The app's id, name and icon, for the platform to show. Set it
349    /// before the app's first window; `App` does.
350    pub fn set_app_info(&self, info: AppInfo) {
351        self.inner.borrow_mut().backend.set_app_info(&info);
352    }
353
354    /// Tasks that have not finished yet.
355    pub fn pending_tasks(&self) -> usize {
356        self.executor.task_count()
357    }
358
359    pub fn events(&self) -> EventSink {
360        self.inner.borrow().events.clone()
361    }
362
363    pub fn metrics(&self) -> PlatformMetrics {
364        self.inner.borrow().metrics.clone()
365    }
366
367    // --------------------------------------------------------- localization
368
369    /// The app's translations (`locales!`). Set them before the app's
370    /// first window; `App` does. The language is chosen from them again.
371    pub fn set_locales(&self, locales: crate::l10n::Locales) {
372        self.l10n.set_locales(locales);
373    }
374
375    /// The languages to choose the app's from, most wanted first, in place
376    /// of the user's: an app's own language setting, or a test's. `None`:
377    /// the user's, as the platform lists them.
378    pub fn set_languages(&self, languages: Option<Vec<String>>) {
379        self.l10n.set_requested(languages);
380    }
381
382    /// The app's language: the first of the user's it has translations
383    /// for, else its fallback. Tracked.
384    pub fn language(&self) -> crate::l10n::LanguageIdentifier {
385        self.l10n.current()
386    }
387
388    /// Messages missing from every language, and messages that failed to
389    /// format, since the last call. Tests fail on them.
390    pub fn take_l10n_errors(&self) -> Vec<String> {
391        self.l10n.take_errors()
392    }
393
394    /// Native backends call this to learn when a commit is needed. The
395    /// callback should schedule [`Ui::commit`] on the run loop (e.g. before
396    /// the next frame). Without a scheduler, callers commit explicitly.
397    pub fn set_commit_scheduler(&self, schedule: impl Fn() + 'static) {
398        self.inner.borrow_mut().commit_scheduler = Some(Rc::new(schedule));
399    }
400
401    fn changed(&self) {
402        let schedule = {
403            let mut inner = self.inner.borrow_mut();
404            if inner.commit_scheduled {
405                return;
406            }
407            inner.commit_scheduled = true;
408            inner.commit_scheduler.clone()
409        };
410        if let Some(schedule) = schedule {
411            schedule();
412        }
413    }
414}