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