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