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