Skip to main content

mitsuami_core/ui/
pipeline.rs

1//! The update pipeline: dispatching events, committing, and the run-loop
2//! turn.
3
4use crate::a11y::{A11yAction, ActionError};
5
6use crate::command::{Command, EventValue, UiEvent};
7use crate::widget::{NodeId, Prop, WidgetKind};
8
9use super::{Fit, Inner, Ui};
10
11impl Ui {
12    /// Drains native events and dispatches them to handlers. Handlers run in
13    /// one reactive batch per event.
14    pub fn process_events(&self) {
15        crate::task::with_current(self, || self.dispatch_events());
16    }
17
18    fn dispatch_events(&self) {
19        loop {
20            let chosen = {
21                let mut inner = self.inner.borrow_mut();
22                let id = inner.menu_queue.pop_front();
23                id.and_then(|id| inner.menu_handlers.values().find_map(|handlers| handlers.get(&id)).cloned())
24            };
25            if let Some(handler) = chosen {
26                mitsuami_reactive::batch(|| handler());
27                continue;
28            }
29            let clicked = {
30                let mut inner = self.inner.borrow_mut();
31                let id = inner.notification_queue.pop_front();
32                id.map(|id| (id, inner.notification_handlers.values().cloned().collect::<Vec<_>>()))
33            };
34            if let Some((id, handlers)) = clicked {
35                mitsuami_reactive::batch(|| handlers.iter().for_each(|handler| handler(&id)));
36                continue;
37            }
38            let next = self.inner.borrow().events.pop();
39            let Some((id, event)) = next else { break };
40            let (handlers, drawn) = {
41                let mut inner = self.inner.borrow_mut();
42                inner.absorb(id, &event);
43                let node = inner.nodes.get(&id);
44                let drawn = node.and_then(|n| n.drawn().map(|c| (c.clone(), n.frame.size)));
45                let mut handlers = node.map(|n| n.handlers.clone()).unwrap_or_default();
46                if matches!(event, UiEvent::WindowActiveChanged(_)) {
47                    for (surface, node) in &inner.nodes {
48                        if node.kind == WidgetKind::GpuSurface && inner.window_of(*surface) == Some(id) {
49                            handlers.extend(node.handlers.iter().cloned());
50                        }
51                    }
52                }
53                (handlers, drawn)
54            };
55            // A drawn widget decides what a pointer event means, with the
56            // tree free to borrow.
57            let meaning = match (&event, drawn) {
58                (UiEvent::Pointer(pointer), Some((custom, size))) => custom.pointer(size, pointer),
59                _ => None,
60            };
61            self.changed();
62            for event in std::iter::once(event).chain(meaning.map(UiEvent::Custom)) {
63                mitsuami_reactive::batch(|| {
64                    for handler in &handlers {
65                        handler(&event);
66                    }
67                });
68            }
69        }
70    }
71
72    /// Brings the native tree up to date: styles, structure, props, layout.
73    pub fn commit(&self) {
74        // Dialogs on windows that are going close first, while their
75        // windows are still there; their replies only wake tasks.
76        let gone = std::mem::take(&mut self.inner.borrow_mut().destroyed_windows);
77        for window in gone {
78            self.services.borrow_mut().window_destroyed(window);
79        }
80        let language = self.l10n.language();
81        let mut inner = self.inner.borrow_mut();
82        inner.commit_scheduled = false;
83        if inner.language.as_ref() != Some(&language) {
84            let rtl = crate::l10n::is_rtl(&language);
85            inner.backend.set_locale(&language, rtl);
86            inner.language = Some(language);
87            if inner.rtl != rtl {
88                inner.rtl = rtl;
89                inner.styles_dirty = true;
90            }
91        }
92        let refocus = std::mem::take(&mut inner.focus_dirty) || inner.styles_dirty || !inner.resync.is_empty();
93        if inner.styles_dirty {
94            inner.resolve_styles();
95        }
96        inner.resync_all();
97        if refocus {
98            inner.sync_focus_orders();
99        }
100        for id in std::mem::take(&mut inner.pending_focus) {
101            if inner.nodes.contains_key(&id) {
102                inner.pending.push(Command::Focus { id });
103            }
104        }
105        for (id, range) in std::mem::take(&mut inner.pending_selections) {
106            let Some(node) = inner.nodes.get(&id) else { continue };
107            // Graphemes of the text the field has now, in its `char`s.
108            let text = crate::find_prop!(node.props, Value).unwrap_or_default();
109            let range = crate::graphemes::chars_of(&text, range);
110            inner.pending.push(Command::SelectText { id, range });
111        }
112        let batch = std::mem::take(&mut inner.pending);
113        inner.created.clear();
114        if !batch.is_empty() {
115            inner.backend.apply(&batch);
116        }
117        inner.layout();
118        let frames = std::mem::take(&mut inner.pending);
119        if !frames.is_empty() {
120            inner.backend.apply(&frames);
121        }
122    }
123
124    /// One run-loop turn: dispatch events and commit, repeating while the
125    /// commit itself produced new events (e.g. a window resize) or new sizes
126    /// views watch, until idle. Backends call this from their run loop,
127    /// before it goes to sleep.
128    pub fn tick(&self) {
129        const MAX_TURNS: usize = 64;
130        // Views that change with their size can change it again. Past this,
131        // sizes wait for the next turn, as browsers' `ResizeObserver` does,
132        // so a view that never settles doesn't hold the run loop.
133        const MAX_SIZE_REPORTS: usize = 8;
134        let mut reports = 0;
135        for turn in 0..MAX_TURNS {
136            // Tasks other threads woke run on the first turn only; one they
137            // wake again meanwhile waits for the next tick (`task.rs`).
138            self.executor.run_ready(self, turn == 0);
139            self.process_events();
140            self.commit();
141            // Views change with their sizes before anything is shown.
142            if reports < MAX_SIZE_REPORTS && self.report_sizes() {
143                reports += 1;
144                continue;
145            }
146            let idle = {
147                let inner = self.inner.borrow();
148                inner.events.is_empty() && inner.menu_queue.is_empty() && inner.notification_queue.is_empty()
149            };
150            if idle && !self.executor.has_ready() {
151                return;
152            }
153        }
154    }
155
156    /// Asks the backend to perform an accessibility action, then dispatches
157    /// the events it produced.
158    ///
159    /// Custom widgets the backend can't act on get the event their shared
160    /// definition gives the action (e.g. `Increment` → a new value).
161    pub fn perform(&self, id: NodeId, action: &A11yAction) -> Result<(), ActionError> {
162        let (result, custom) = {
163            let mut inner = self.inner.borrow_mut();
164            let result = inner.backend.perform(id, action);
165            (result, inner.nodes.get(&id).and_then(|n| n.custom()).cloned())
166        };
167        // The widget's definition runs with the tree free to borrow.
168        let result = match (result, custom) {
169            (Err(ActionError::Unsupported), Some(custom)) => match custom.action(action) {
170                Some(event) => {
171                    self.inner.borrow().events.emit(id, UiEvent::Custom(event));
172                    Ok(())
173                }
174                None => Err(ActionError::Unsupported),
175            },
176            (result, _) => result,
177        };
178        self.process_events();
179        result
180    }
181
182    /// Synthesizes raw input on a native control, then dispatches the events
183    /// it produced.
184    pub fn synthesize(&self, id: NodeId, input: &crate::backend::SyntheticInput) -> Result<(), ActionError> {
185        let result = self.inner.borrow_mut().backend.synthesize(id, input);
186        self.process_events();
187        result
188    }
189}
190
191impl Inner {
192    /// Updates core state from events the native side already reflects, so
193    /// echoing the value back is a no-op.
194    fn absorb(&mut self, id: NodeId, event: &UiEvent) {
195        match event {
196            UiEvent::Changed(value) => {
197                let Some(node) = self.nodes.get_mut(&id) else { return };
198                let prop = match (node.kind, value) {
199                    (
200                        WidgetKind::TextInput
201                        | WidgetKind::PasswordInput
202                        | WidgetKind::SearchInput
203                        | WidgetKind::TextArea,
204                        EventValue::Text(text),
205                    ) => Prop::Value(text.clone()),
206                    (WidgetKind::Checkbox | WidgetKind::Switch | WidgetKind::ToggleButton, EventValue::Bool(b)) => {
207                        Prop::Checked(*b)
208                    }
209                    (WidgetKind::List | WidgetKind::Table | WidgetKind::Tree, EventValue::Rows(rows)) => {
210                        Prop::Selected(rows.clone())
211                    }
212                    (WidgetKind::Table, EventValue::Sort(sort)) => Prop::Sort(Some(*sort)),
213                    (
214                        WidgetKind::Select
215                        | WidgetKind::RadioGroup
216                        | WidgetKind::Sidebar
217                        | WidgetKind::Tabs
218                        | WidgetKind::DocumentTabs,
219                        EventValue::Index(index),
220                    ) => Prop::SelectedIndex(Some(*index)),
221                    (WidgetKind::Slider | WidgetKind::NumberInput, EventValue::Number(number)) => Prop::Number(*number),
222                    (WidgetKind::ColorWell, EventValue::Color(color)) => Prop::ColorValue(*color),
223                    // The divider the user dragged: the panes follow.
224                    (WidgetKind::Split, EventValue::Number(number)) => {
225                        self.styles_dirty = true;
226                        Prop::Number(*number)
227                    }
228                    _ => return,
229                };
230                // A click takes a checkbox out of the mixed state, on every
231                // platform.
232                if node.kind == WidgetKind::Checkbox && crate::find_prop!(node.props, Mixed) == Some(true) {
233                    node.props.retain(|p| !matches!(p, Prop::Mixed(_)));
234                    node.props.push(Prop::Mixed(false));
235                }
236                // A tab view's page shown is in the Tab order.
237                self.focus_dirty |= matches!(prop, Prop::SelectedIndex(_));
238                // The user's choice can change the widget's size as the app's
239                // can (`set_prop`), which won't see a change when it's echoed.
240                if prop.affects_measure(node.kind)
241                    && let Some(t) = node.taffy
242                {
243                    let _ = self.taffy.mark_dirty(t);
244                }
245                node.props.retain(|p| p.key() != prop.key());
246                node.props.push(prop);
247            }
248            UiEvent::PointerLockEnded
249            | UiEvent::KeyboardGrabEnded
250            | UiEvent::FullScreenChanged(_)
251            | UiEvent::MaximizedChanged(_)
252            | UiEvent::SidebarShownChanged(_)
253            | UiEvent::PopoverShownChanged(_) => {
254                let Some(node) = self.nodes.get_mut(&id) else { return };
255                let prop = match event {
256                    UiEvent::PointerLockEnded => Prop::PointerLock(false),
257                    UiEvent::KeyboardGrabEnded => Prop::KeyboardGrab(false),
258                    UiEvent::FullScreenChanged(on) => Prop::FullScreen(*on),
259                    UiEvent::MaximizedChanged(on) => Prop::Maximized(*on),
260                    UiEvent::SidebarShownChanged(shown) => Prop::SidebarShown(*shown),
261                    UiEvent::PopoverShownChanged(shown) => Prop::PopoverShown(*shown),
262                    _ => unreachable!(),
263                };
264                node.props.retain(|p| p.key() != prop.key());
265                node.props.push(prop);
266            }
267            // The platform shows the tab moved: its title goes with it, and
268            // the chosen tab stays chosen wherever it is now.
269            UiEvent::TabMoved { from, to } => {
270                let Some(node) = self.nodes.get_mut(&id) else { return };
271                let Some(mut titles) = crate::find_prop!(node.props, TabTitles) else { return };
272                if *from >= titles.len() || *to >= titles.len() {
273                    return;
274                }
275                let title = titles.remove(*from);
276                titles.insert(*to, title);
277                let chosen = crate::find_prop!(node.props, SelectedIndex)
278                    .flatten()
279                    .map(|i| crate::widget::moved_index(i, *from, *to));
280                node.props.retain(|p| !matches!(p, Prop::TabTitles(_) | Prop::SelectedIndex(_)));
281                node.props.push(Prop::TabTitles(titles));
282                node.props.push(Prop::SelectedIndex(chosen));
283            }
284            UiEvent::FocusIn => {
285                if let Some(window) = self.window_of(id) {
286                    self.focused.insert(window, id);
287                }
288            }
289            UiEvent::FocusOut => self.focused.retain(|_, focused| *focused != id),
290            UiEvent::Scrolled(offset) => {
291                if let Some(node) = self.nodes.get_mut(&id) {
292                    node.scroll_offset = *offset;
293                }
294            }
295            UiEvent::RowWidth(width) => {
296                if let Some(node) = self.nodes.get_mut(&id) {
297                    node.row_width = Some(*width);
298                }
299            }
300            UiEvent::ViewportInsets(insets) => {
301                if let Some(node) = self.nodes.get_mut(&id)
302                    && node.viewport_insets != *insets
303                {
304                    node.viewport_insets = *insets;
305                    // The style's padding takes them.
306                    self.styles_dirty = true;
307                }
308            }
309            UiEvent::ColumnWidths(widths) => {
310                if let Some(node) = self.nodes.get_mut(&id) {
311                    node.column_widths = Some(widths.clone());
312                }
313            }
314            UiEvent::TreeIndent(indent) => {
315                if let Some(node) = self.nodes.get_mut(&id) {
316                    node.tree_indent = *indent;
317                }
318            }
319            // The platform shows the row open or closed already; its
320            // children come with the rows the tree sends next.
321            UiEvent::RowExpanded(row, open) => {
322                if let Some(node) = self.nodes.get_mut(&id)
323                    && let Some(Prop::TreeRows(rows)) = node.props.iter_mut().find(|p| matches!(p, Prop::TreeRows(_)))
324                    && let Some(tree_row) = rows.iter_mut().find(|r| r.row == *row)
325                {
326                    tree_row.expanded = *open;
327                }
328            }
329            UiEvent::RowHeight(row, height) => {
330                if let Some(node) = self.nodes.get_mut(&id) {
331                    node.row_heights.insert(*row, *height);
332                }
333            }
334            UiEvent::RowHidden(row) => {
335                if let Some(node) = self.nodes.get_mut(&id) {
336                    node.row_heights.remove(row);
337                }
338            }
339            UiEvent::WindowResized(size) => {
340                if let Some(node) = self.nodes.get_mut(&id) {
341                    // A following window's height is one the core asked for
342                    // (grown to the minimum, as platforms grow it), or the
343                    // user's, which ends following if it's to end.
344                    if let Fit::Follow { until_resized } = node.fit
345                        && !node.in_full_screen()
346                        && !node.heights.is_empty()
347                    {
348                        let min = crate::find_prop!(node.props, MinSize).map_or(0.0, |m| m.height);
349                        match node.heights.iter().rposition(|h| (h.max(min) - size.height).abs() < 1.0) {
350                            Some(reported) => drop(node.heights.drain(..reported)),
351                            None if until_resized => {
352                                node.fit = Fit::None;
353                                node.heights.clear();
354                            }
355                            None => {}
356                        }
357                    }
358                    node.window_size = *size;
359                    self.styles_dirty = true;
360                }
361            }
362            UiEvent::Remeasure => {
363                if let Some(t) = self.nodes.get(&id).and_then(|n| n.taffy) {
364                    let _ = self.taffy.mark_dirty(t);
365                }
366            }
367            UiEvent::MetricsChanged => {
368                self.metrics = self.backend.metrics();
369                self.styles_dirty = true;
370                for node in self.nodes.values_mut() {
371                    node.drawn_at = None;
372                    if let Some(t) = node.taffy {
373                        let _ = self.taffy.mark_dirty(t);
374                    }
375                }
376            }
377            _ => {}
378        }
379    }
380}