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, EventValue::Rows(rows)) => Prop::Selected(rows.clone()),
193                    (WidgetKind::Table, EventValue::Sort(sort)) => Prop::Sort(Some(*sort)),
194                    (
195                        WidgetKind::Select
196                        | WidgetKind::RadioGroup
197                        | WidgetKind::Sidebar
198                        | WidgetKind::Tabs
199                        | WidgetKind::DocumentTabs,
200                        EventValue::Index(index),
201                    ) => Prop::SelectedIndex(Some(*index)),
202                    (WidgetKind::Slider | WidgetKind::NumberInput, EventValue::Number(number)) => Prop::Number(*number),
203                    _ => return,
204                };
205                // A click takes a checkbox out of the mixed state, on every
206                // platform.
207                if node.kind == WidgetKind::Checkbox && crate::find_prop!(node.props, Mixed) == Some(true) {
208                    node.props.retain(|p| !matches!(p, Prop::Mixed(_)));
209                    node.props.push(Prop::Mixed(false));
210                }
211                // A tab view's page shown is in the Tab order.
212                self.focus_dirty |= matches!(prop, Prop::SelectedIndex(_));
213                node.props.retain(|p| p.key() != prop.key());
214                node.props.push(prop);
215            }
216            UiEvent::PointerLockEnded
217            | UiEvent::KeyboardGrabEnded
218            | UiEvent::FullScreenChanged(_)
219            | UiEvent::MaximizedChanged(_)
220            | UiEvent::SidebarShownChanged(_) => {
221                let Some(node) = self.nodes.get_mut(&id) else { return };
222                let prop = match event {
223                    UiEvent::PointerLockEnded => Prop::PointerLock(false),
224                    UiEvent::KeyboardGrabEnded => Prop::KeyboardGrab(false),
225                    UiEvent::FullScreenChanged(on) => Prop::FullScreen(*on),
226                    UiEvent::MaximizedChanged(on) => Prop::Maximized(*on),
227                    UiEvent::SidebarShownChanged(shown) => Prop::SidebarShown(*shown),
228                    _ => unreachable!(),
229                };
230                node.props.retain(|p| p.key() != prop.key());
231                node.props.push(prop);
232            }
233            // The platform shows the tab moved: its title goes with it, and
234            // the chosen tab stays chosen wherever it is now.
235            UiEvent::TabMoved { from, to } => {
236                let Some(node) = self.nodes.get_mut(&id) else { return };
237                let Some(mut titles) = crate::find_prop!(node.props, TabTitles) else { return };
238                if *from >= titles.len() || *to >= titles.len() {
239                    return;
240                }
241                let title = titles.remove(*from);
242                titles.insert(*to, title);
243                let chosen = crate::find_prop!(node.props, SelectedIndex)
244                    .flatten()
245                    .map(|i| crate::widget::moved_index(i, *from, *to));
246                node.props.retain(|p| !matches!(p, Prop::TabTitles(_) | Prop::SelectedIndex(_)));
247                node.props.push(Prop::TabTitles(titles));
248                node.props.push(Prop::SelectedIndex(chosen));
249            }
250            UiEvent::FocusIn => {
251                if let Some(window) = self.window_of(id) {
252                    self.focused.insert(window, id);
253                }
254            }
255            UiEvent::FocusOut => self.focused.retain(|_, focused| *focused != id),
256            UiEvent::Scrolled(offset) => {
257                if let Some(node) = self.nodes.get_mut(&id) {
258                    node.scroll_offset = *offset;
259                }
260            }
261            UiEvent::RowWidth(width) => {
262                if let Some(node) = self.nodes.get_mut(&id) {
263                    node.row_width = Some(*width);
264                }
265            }
266            UiEvent::ViewportInsets(insets) => {
267                if let Some(node) = self.nodes.get_mut(&id)
268                    && node.viewport_insets != *insets
269                {
270                    node.viewport_insets = *insets;
271                    // The style's padding takes them.
272                    self.styles_dirty = true;
273                }
274            }
275            UiEvent::ColumnWidths(widths) => {
276                if let Some(node) = self.nodes.get_mut(&id) {
277                    node.column_widths = Some(widths.clone());
278                }
279            }
280            UiEvent::WindowResized(size) => {
281                if let Some(node) = self.nodes.get_mut(&id) {
282                    // A following window's height is one the core asked for
283                    // (grown to the minimum, as platforms grow it), or the
284                    // user's, which ends following if it's to end.
285                    if let Fit::Follow { until_resized } = node.fit
286                        && !node.in_full_screen()
287                        && !node.heights.is_empty()
288                    {
289                        let min = crate::find_prop!(node.props, MinSize).map_or(0.0, |m| m.height);
290                        match node.heights.iter().rposition(|h| (h.max(min) - size.height).abs() < 1.0) {
291                            Some(reported) => drop(node.heights.drain(..reported)),
292                            None if until_resized => {
293                                node.fit = Fit::None;
294                                node.heights.clear();
295                            }
296                            None => {}
297                        }
298                    }
299                    node.window_size = *size;
300                    self.styles_dirty = true;
301                }
302            }
303            UiEvent::Remeasure => {
304                if let Some(t) = self.nodes.get(&id).and_then(|n| n.taffy) {
305                    let _ = self.taffy.mark_dirty(t);
306                }
307            }
308            UiEvent::MetricsChanged => {
309                self.metrics = self.backend.metrics();
310                self.styles_dirty = true;
311                for node in self.nodes.values_mut() {
312                    node.drawn_at = None;
313                    if let Some(t) = node.taffy {
314                        let _ = self.taffy.mark_dirty(t);
315                    }
316                }
317            }
318            _ => {}
319        }
320    }
321}