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    /// The app keeps running while no window is open (until `quit`).
181    runs_without_windows: bool,
182    /// `quit` was called: the run loop ends after this turn.
183    quit_requested: bool,
184    commit_scheduler: Option<Rc<dyn Fn()>>,
185    commit_scheduled: bool,
186    /// The app's language last given to the backend.
187    language: Option<crate::l10n::LanguageIdentifier>,
188    /// Its direction, which windows' content inherits.
189    rtl: bool,
190    /// Sizes views watch (`use_size`, `use_viewport`).
191    observers: BTreeMap<u64, Observer>,
192    next_observer: u64,
193}
194
195/// A size a view watches: the node's it targets now, and the last reported.
196struct Observer {
197    target: Box<dyn Fn() -> Option<NodeId>>,
198    size: mitsuami_reactive::Signal<Size>,
199    last: Size,
200}
201
202/// Handle to a UI instance: one backend, its windows and their node trees.
203/// Cheap to clone; all clones share the same state.
204#[derive(Clone)]
205pub struct Ui {
206    inner: Rc<RefCell<Inner>>,
207    /// Kept apart from `inner`: tasks run while the tree is free to borrow.
208    executor: Rc<Executor>,
209    /// Kept apart too: replies may arrive at any time.
210    services: Rc<RefCell<Box<dyn Services>>>,
211    /// Kept apart too: messages are formatted while the tree is borrowed
212    /// (backends title menus in `apply`).
213    l10n: Rc<crate::l10n::Localization>,
214}
215
216/// Non-owning [`Ui`] handle, for closures stored inside the tree itself.
217#[derive(Clone)]
218pub struct WeakUi {
219    inner: Weak<RefCell<Inner>>,
220    executor: Weak<Executor>,
221    services: Weak<RefCell<Box<dyn Services>>>,
222    l10n: Weak<crate::l10n::Localization>,
223}
224
225impl WeakUi {
226    pub fn upgrade(&self) -> Option<Ui> {
227        Some(Ui {
228            inner: self.inner.upgrade()?,
229            executor: self.executor.upgrade()?,
230            services: self.services.upgrade()?,
231            l10n: self.l10n.upgrade()?,
232        })
233    }
234}
235
236/// Snapshot of one native node, for inspection tools and tests.
237#[derive(Clone, Debug, PartialEq)]
238pub struct NodeInfo {
239    pub id: NodeId,
240    pub kind: WidgetKind,
241    pub props: Vec<Prop>,
242    pub test_id: Option<String>,
243    /// In window coordinates.
244    pub frame: Rect,
245    pub children: Vec<NodeInfo>,
246}
247
248impl Ui {
249    pub fn new(backend: impl Backend + 'static) -> Ui {
250        let mut backend: Box<dyn Backend> = Box::new(backend);
251        let events = EventSink::default();
252        backend.init(events.clone());
253        let metrics = backend.metrics();
254        let services = Rc::new(RefCell::new(backend.services()));
255        let l10n = crate::l10n::Localization::new(backend.locale());
256        let ui = Ui {
257            executor: Rc::default(),
258            services,
259            l10n,
260            inner: Rc::new(RefCell::new(Inner {
261                backend,
262                events,
263                metrics,
264                nodes: BTreeMap::new(),
265                // Frames are rounded from where nodes are in their window
266                // (`collect_frames`), not each on its own.
267                taffy: {
268                    let mut taffy = TaffyTree::new();
269                    taffy.disable_rounding();
270                    taffy
271                },
272                next_id: 1,
273                pending: Vec::new(),
274                created: Default::default(),
275                pending_focus: Vec::new(),
276                pending_selections: Vec::new(),
277                windows: Vec::new(),
278                destroyed_windows: Vec::new(),
279                styles_dirty: true,
280                resync: BTreeSet::new(),
281                focus_orders: BTreeMap::new(),
282                focus_dirty: true,
283                focused: BTreeMap::new(),
284                menu_handlers: BTreeMap::new(),
285                menu_effects: BTreeMap::new(),
286                next_menu_id: 1,
287                menu_queue: Default::default(),
288                quit_items: BTreeMap::new(),
289                notification_handlers: BTreeMap::new(),
290                next_notification_handler: 1,
291                notification_queue: Default::default(),
292                next_notification: 1,
293                runs_without_windows: false,
294                quit_requested: false,
295                commit_scheduler: None,
296                commit_scheduled: false,
297                language: None,
298                rtl: false,
299                observers: BTreeMap::new(),
300                next_observer: 1,
301            })),
302        };
303        // The next commit gives the backend the new language.
304        let weak = ui.downgrade();
305        ui.l10n.set_on_change(move |_, _| {
306            if let Some(ui) = weak.upgrade() {
307                ui.changed();
308            }
309        });
310        ui
311    }
312
313    pub fn downgrade(&self) -> WeakUi {
314        WeakUi {
315            inner: Rc::downgrade(&self.inner),
316            executor: Rc::downgrade(&self.executor),
317            services: Rc::downgrade(&self.services),
318            l10n: Rc::downgrade(&self.l10n),
319        }
320    }
321
322    // ---------------------------------------------------------------- tasks
323
324    pub(crate) fn executor(&self) -> &Executor {
325        &self.executor
326    }
327
328    /// Runs `future` on the UI thread, polled from [`Ui::tick`]. Unlike the
329    /// free [`spawn_local`](crate::task::spawn_local), it is not tied to a
330    /// reactive scope; cancel it with the returned handle.
331    pub fn spawn_local(&self, future: impl std::future::Future<Output = ()> + 'static) -> TaskHandle {
332        self.spawn_in(future, None)
333    }
334
335    pub(crate) fn spawn_in(
336        &self,
337        future: impl std::future::Future<Output = ()> + 'static,
338        owner: Option<mitsuami_reactive::Owner>,
339    ) -> TaskHandle {
340        let id = self.executor.spawn(Box::pin(future), owner);
341        self.changed();
342        TaskHandle::new(id, self.downgrade())
343    }
344
345    /// A future that completes after `duration` on this `Ui`'s clock.
346    pub fn sleep(&self, duration: std::time::Duration) -> Sleep {
347        Sleep::new(self.clone(), duration)
348    }
349
350    /// Replaces the clock timers use (tests install a [`ManualClock`](crate::task::ManualClock)).
351    pub fn set_clock(&self, clock: Rc<dyn Clock>) {
352        self.executor.set_clock(clock);
353    }
354
355    /// How to make the UI thread's run loop turn from any thread; called
356    /// when a task is woken (e.g. by background work finishing).
357    pub fn set_waker(&self, wake: std::sync::Arc<dyn Fn() + Send + Sync>) {
358        self.executor.set_wake_ui(wake);
359    }
360
361    /// Time until the next timer fires (zero if overdue), for run loops to
362    /// schedule a wake-up.
363    pub fn time_to_next_timer(&self) -> Option<std::time::Duration> {
364        let now = self.executor.now();
365        self.executor.next_deadline().map(|deadline| deadline.saturating_sub(now))
366    }
367
368    /// The app's id, name and icon, for the platform to show. Set it
369    /// before the app's first window; `App` does.
370    pub fn set_app_info(&self, info: AppInfo) {
371        self.inner.borrow_mut().backend.set_app_info(&info);
372    }
373
374    /// Tasks that have not finished yet.
375    pub fn pending_tasks(&self) -> usize {
376        self.executor.task_count()
377    }
378
379    pub fn events(&self) -> EventSink {
380        self.inner.borrow().events.clone()
381    }
382
383    pub fn metrics(&self) -> PlatformMetrics {
384        self.inner.borrow().metrics.clone()
385    }
386
387    // --------------------------------------------------------- localization
388
389    /// The app's translations (`locales!`). Set them before the app's
390    /// first window; `App` does. The language is chosen from them again.
391    pub fn set_locales(&self, locales: crate::l10n::Locales) {
392        self.l10n.set_locales(locales);
393    }
394
395    /// The languages to choose the app's from, most wanted first, in place
396    /// of the user's: an app's own language setting, or a test's. `None`:
397    /// the user's, as the platform lists them.
398    pub fn set_languages(&self, languages: Option<Vec<String>>) {
399        self.l10n.set_requested(languages);
400    }
401
402    /// The app's language: the first of the user's it has translations
403    /// for, else its fallback. Tracked.
404    pub fn language(&self) -> crate::l10n::LanguageIdentifier {
405        self.l10n.current()
406    }
407
408    /// Messages missing from every language, and messages that failed to
409    /// format, since the last call. Tests fail on them.
410    pub fn take_l10n_errors(&self) -> Vec<String> {
411        self.l10n.take_errors()
412    }
413
414    /// Native backends call this to learn when a commit is needed. The
415    /// callback should schedule [`Ui::commit`] on the run loop (e.g. before
416    /// the next frame). Without a scheduler, callers commit explicitly.
417    pub fn set_commit_scheduler(&self, schedule: impl Fn() + 'static) {
418        self.inner.borrow_mut().commit_scheduler = Some(Rc::new(schedule));
419    }
420
421    fn changed(&self) {
422        let schedule = {
423            let mut inner = self.inner.borrow_mut();
424            if inner.commit_scheduled {
425                return;
426            }
427            inner.commit_scheduled = true;
428            inner.commit_scheduler.clone()
429        };
430        if let Some(schedule) = schedule {
431            schedule();
432        }
433    }
434}