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