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