mitsuami-core 2.5.0

Node tree, layout, styles, units, a11y model and backend contract for mitsuami
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! The update pipeline: dispatching events, committing, and the run-loop
//! turn.

use crate::a11y::{A11yAction, ActionError};

use crate::command::{Command, EventValue, UiEvent};
use crate::widget::{NodeId, Prop, WidgetKind};

use super::{Fit, Inner, Ui};

impl Ui {
    /// Drains native events and dispatches them to handlers. Handlers run in
    /// one reactive batch per event.
    pub fn process_events(&self) {
        crate::task::with_current(self, || self.dispatch_events());
    }

    fn dispatch_events(&self) {
        loop {
            let chosen = {
                let mut inner = self.inner.borrow_mut();
                let id = inner.menu_queue.pop_front();
                id.and_then(|id| {
                    let mut bars = inner.menu_handlers.values().chain(std::iter::once(&inner.tray_handlers));
                    bars.find_map(|handlers| handlers.get(&id)).cloned()
                })
            };
            if let Some(handler) = chosen {
                mitsuami_reactive::batch(|| handler());
                continue;
            }
            let clicked = {
                let mut inner = self.inner.borrow_mut();
                let id = inner.notification_queue.pop_front();
                id.map(|id| (id, inner.notification_handlers.values().cloned().collect::<Vec<_>>()))
            };
            if let Some((id, handlers)) = clicked {
                mitsuami_reactive::batch(|| handlers.iter().for_each(|handler| handler(&id)));
                continue;
            }
            let reopened = {
                let mut inner = self.inner.borrow_mut();
                let reopen = inner.reopen_queue.pop_front();
                reopen.map(|reopen| (reopen, inner.reopen_handlers.values().cloned().collect::<Vec<_>>()))
            };
            if let Some((reopen, handlers)) = reopened {
                mitsuami_reactive::batch(|| handlers.iter().for_each(|handler| handler(&reopen)));
                continue;
            }
            let next = self.inner.borrow().events.pop();
            let Some((id, event)) = next else { break };
            let (handlers, drawn) = {
                let mut inner = self.inner.borrow_mut();
                inner.absorb(id, &event);
                let node = inner.nodes.get(&id);
                let drawn = node.and_then(|n| n.drawn().map(|c| (c.clone(), n.frame.size)));
                let mut handlers = node.map(|n| n.handlers.clone()).unwrap_or_default();
                if matches!(event, UiEvent::WindowActiveChanged(_)) {
                    for (surface, node) in &inner.nodes {
                        if node.kind == WidgetKind::GpuSurface && inner.window_of(*surface) == Some(id) {
                            handlers.extend(node.handlers.iter().cloned());
                        }
                    }
                }
                (handlers, drawn)
            };
            // A drawn widget decides what a pointer event means, with the
            // tree free to borrow.
            let meaning = match (&event, drawn) {
                (UiEvent::Pointer(pointer), Some((custom, size))) => custom.pointer(size, pointer),
                _ => None,
            };
            self.changed();
            for event in std::iter::once(event).chain(meaning.map(UiEvent::Custom)) {
                mitsuami_reactive::batch(|| {
                    for handler in &handlers {
                        handler(&event);
                    }
                });
            }
        }
    }

    /// Brings the native tree up to date: styles, structure, props, layout.
    pub fn commit(&self) {
        // Dialogs on windows that are going close first, while their
        // windows are still there; their replies only wake tasks.
        let gone = std::mem::take(&mut self.inner.borrow_mut().destroyed_windows);
        for window in gone {
            self.services.borrow_mut().window_destroyed(window);
        }
        let language = self.l10n.language();
        let mut inner = self.inner.borrow_mut();
        inner.commit_scheduled = false;
        if inner.language.as_ref() != Some(&language) {
            let rtl = crate::l10n::is_rtl(&language);
            inner.backend.set_locale(&language, rtl);
            inner.language = Some(language);
            if inner.rtl != rtl {
                inner.rtl = rtl;
                inner.styles_dirty = true;
            }
        }
        let refocus = std::mem::take(&mut inner.focus_dirty) || inner.styles_dirty || !inner.resync.is_empty();
        if inner.styles_dirty {
            inner.resolve_styles();
        }
        inner.resync_all();
        if refocus {
            inner.sync_focus_orders();
        }
        // Before focus: the focus goes into the window that comes forward.
        let mut presented = Vec::new();
        for id in std::mem::take(&mut inner.pending_present) {
            if let Some(window) = inner.window_of(id).filter(|w| !presented.contains(w)) {
                presented.push(window);
                inner.pending.push(Command::Present { window });
            }
        }
        for id in std::mem::take(&mut inner.pending_focus) {
            if inner.nodes.contains_key(&id) {
                inner.pending.push(Command::Focus { id });
            }
        }
        for (id, range) in std::mem::take(&mut inner.pending_selections) {
            let Some(node) = inner.nodes.get(&id) else { continue };
            // Graphemes of the text the field has now, in its `char`s.
            let text = crate::find_prop!(node.props, Value).unwrap_or_default();
            let range = crate::graphemes::chars_of(&text, range);
            inner.pending.push(Command::SelectText { id, range });
        }
        let batch = std::mem::take(&mut inner.pending);
        inner.created.clear();
        if !batch.is_empty() {
            inner.backend.apply(&batch);
        }
        inner.layout();
        let frames = std::mem::take(&mut inner.pending);
        if !frames.is_empty() {
            inner.backend.apply(&frames);
        }
    }

    /// One run-loop turn: dispatch events and commit, repeating while the
    /// commit itself produced new events (e.g. a window resize) or new sizes
    /// views watch, until idle. Backends call this from their run loop,
    /// before it goes to sleep.
    pub fn tick(&self) {
        const MAX_TURNS: usize = 64;
        // Views that change with their size can change it again. Past this,
        // sizes wait for the next turn, as browsers' `ResizeObserver` does,
        // so a view that never settles doesn't hold the run loop.
        const MAX_SIZE_REPORTS: usize = 8;
        let mut reports = 0;
        for turn in 0..MAX_TURNS {
            // Tasks other threads woke run on the first turn only; one they
            // wake again meanwhile waits for the next tick (`task.rs`).
            self.executor.run_ready(self, turn == 0);
            self.process_events();
            self.commit();
            // Views change with their sizes before anything is shown.
            if reports < MAX_SIZE_REPORTS && self.report_sizes() {
                reports += 1;
                continue;
            }
            let idle = {
                let inner = self.inner.borrow();
                inner.events.is_empty()
                    && inner.menu_queue.is_empty()
                    && inner.notification_queue.is_empty()
                    && inner.reopen_queue.is_empty()
            };
            if idle && !self.executor.has_ready() {
                return;
            }
        }
    }

    /// Asks the backend to perform an accessibility action, then dispatches
    /// the events it produced.
    ///
    /// Custom widgets the backend can't act on get the event their shared
    /// definition gives the action (e.g. `Increment` → a new value).
    pub fn perform(&self, id: NodeId, action: &A11yAction) -> Result<(), ActionError> {
        let (result, custom) = {
            let mut inner = self.inner.borrow_mut();
            let result = inner.backend.perform(id, action);
            (result, inner.nodes.get(&id).and_then(|n| n.custom()).cloned())
        };
        // The widget's definition runs with the tree free to borrow.
        let result = match (result, custom) {
            (Err(ActionError::Unsupported), Some(custom)) => match custom.action(action) {
                Some(event) => {
                    self.inner.borrow().events.emit(id, UiEvent::Custom(event));
                    Ok(())
                }
                None => Err(ActionError::Unsupported),
            },
            (result, _) => result,
        };
        self.process_events();
        result
    }

    /// Synthesizes raw input on a native control, then dispatches the events
    /// it produced.
    pub fn synthesize(&self, id: NodeId, input: &crate::backend::SyntheticInput) -> Result<(), ActionError> {
        let result = self.inner.borrow_mut().backend.synthesize(id, input);
        self.process_events();
        result
    }
}

impl Inner {
    /// Updates core state from events the native side already reflects, so
    /// echoing the value back is a no-op.
    fn absorb(&mut self, id: NodeId, event: &UiEvent) {
        match event {
            UiEvent::Changed(value) => {
                let Some(node) = self.nodes.get_mut(&id) else { return };
                let prop = match (node.kind, value) {
                    (
                        WidgetKind::TextInput
                        | WidgetKind::PasswordInput
                        | WidgetKind::SearchInput
                        | WidgetKind::TextArea,
                        EventValue::Text(text),
                    ) => Prop::Value(text.clone()),
                    (WidgetKind::Checkbox | WidgetKind::Switch | WidgetKind::ToggleButton, EventValue::Bool(b)) => {
                        Prop::Checked(*b)
                    }
                    (WidgetKind::List | WidgetKind::Table | WidgetKind::Tree, EventValue::Rows(rows)) => {
                        Prop::Selected(rows.clone())
                    }
                    (WidgetKind::Table, EventValue::Sort(sort)) => Prop::Sort(Some(*sort)),
                    (
                        WidgetKind::Select
                        | WidgetKind::RadioGroup
                        | WidgetKind::Sidebar
                        | WidgetKind::Tabs
                        | WidgetKind::DocumentTabs,
                        EventValue::Index(index),
                    ) => Prop::SelectedIndex(Some(*index)),
                    (WidgetKind::Slider | WidgetKind::NumberInput, EventValue::Number(number)) => Prop::Number(*number),
                    (WidgetKind::ColorWell, EventValue::Color(color)) => Prop::ColorValue(*color),
                    // The divider the user dragged: the panes follow.
                    (WidgetKind::Split, EventValue::Number(number)) => {
                        self.styles_dirty = true;
                        Prop::Number(*number)
                    }
                    _ => return,
                };
                // A click takes a checkbox out of the mixed state, on every
                // platform.
                if node.kind == WidgetKind::Checkbox && crate::find_prop!(node.props, Mixed) == Some(true) {
                    node.props.retain(|p| !matches!(p, Prop::Mixed(_)));
                    node.props.push(Prop::Mixed(false));
                }
                // A tab view's page shown is in the Tab order.
                self.focus_dirty |= matches!(prop, Prop::SelectedIndex(_));
                // The user's choice can change the widget's size as the app's
                // can (`set_prop`), which won't see a change when it's echoed.
                if prop.affects_measure(node.kind)
                    && let Some(t) = node.taffy
                {
                    let _ = self.taffy.mark_dirty(t);
                }
                node.props.retain(|p| p.key() != prop.key());
                node.props.push(prop);
            }
            UiEvent::PointerLockEnded
            | UiEvent::KeyboardGrabEnded
            | UiEvent::FullScreenChanged(_)
            | UiEvent::MaximizedChanged(_)
            | UiEvent::FrameChanged(_)
            | UiEvent::SidebarShownChanged(_)
            | UiEvent::PopoverShownChanged(_) => {
                let Some(node) = self.nodes.get_mut(&id) else { return };
                let prop = match event {
                    UiEvent::PointerLockEnded => Prop::PointerLock(false),
                    UiEvent::KeyboardGrabEnded => Prop::KeyboardGrab(false),
                    UiEvent::FullScreenChanged(on) => Prop::FullScreen(*on),
                    UiEvent::MaximizedChanged(on) => Prop::Maximized(*on),
                    UiEvent::FrameChanged(frame) => Prop::Frame(*frame),
                    UiEvent::SidebarShownChanged(shown) => Prop::SidebarShown(*shown),
                    UiEvent::PopoverShownChanged(shown) => Prop::PopoverShown(*shown),
                    _ => unreachable!(),
                };
                node.props.retain(|p| p.key() != prop.key());
                node.props.push(prop);
            }
            // The platform shows the tab moved: its title goes with it, and
            // the chosen tab stays chosen wherever it is now.
            UiEvent::TabMoved { from, to } => {
                let Some(node) = self.nodes.get_mut(&id) else { return };
                let Some(mut titles) = crate::find_prop!(node.props, TabTitles) else { return };
                if *from >= titles.len() || *to >= titles.len() {
                    return;
                }
                let title = titles.remove(*from);
                titles.insert(*to, title);
                let chosen = crate::find_prop!(node.props, SelectedIndex)
                    .flatten()
                    .map(|i| crate::widget::moved_index(i, *from, *to));
                node.props.retain(|p| !matches!(p, Prop::TabTitles(_) | Prop::SelectedIndex(_)));
                node.props.push(Prop::TabTitles(titles));
                node.props.push(Prop::SelectedIndex(chosen));
            }
            UiEvent::FocusIn => {
                if let Some(window) = self.window_of(id) {
                    self.focused.insert(window, id);
                }
            }
            UiEvent::FocusOut => self.focused.retain(|_, focused| *focused != id),
            UiEvent::Scrolled(offset) => {
                if let Some(node) = self.nodes.get_mut(&id) {
                    node.scroll_offset = *offset;
                }
            }
            UiEvent::RowWidth(width) => {
                if let Some(node) = self.nodes.get_mut(&id) {
                    node.row_width = Some(*width);
                }
            }
            UiEvent::ViewportInsets(insets) => {
                if let Some(node) = self.nodes.get_mut(&id)
                    && node.viewport_insets != *insets
                {
                    node.viewport_insets = *insets;
                    // The style's padding takes them.
                    self.styles_dirty = true;
                }
            }
            UiEvent::ColumnWidths(widths) => {
                if let Some(node) = self.nodes.get_mut(&id) {
                    node.column_widths = Some(widths.clone());
                }
            }
            UiEvent::TreeIndent(indent) => {
                if let Some(node) = self.nodes.get_mut(&id) {
                    node.tree_indent = *indent;
                }
            }
            // The platform shows the row open or closed already; its
            // children come with the rows the tree sends next.
            UiEvent::RowExpanded(row, open) => {
                if let Some(node) = self.nodes.get_mut(&id)
                    && let Some(Prop::TreeRows(rows)) = node.props.iter_mut().find(|p| matches!(p, Prop::TreeRows(_)))
                    && let Some(tree_row) = rows.iter_mut().find(|r| r.row == *row)
                {
                    tree_row.expanded = *open;
                }
            }
            UiEvent::RowHeight(row, height) => {
                if let Some(node) = self.nodes.get_mut(&id) {
                    node.row_heights.insert(*row, *height);
                }
            }
            UiEvent::RowHidden(row) => {
                if let Some(node) = self.nodes.get_mut(&id) {
                    node.row_heights.remove(row);
                }
            }
            UiEvent::WindowResized(size) => {
                if let Some(node) = self.nodes.get_mut(&id) {
                    // A following window's height is one the core asked for
                    // (grown to the minimum, as platforms grow it), or the
                    // user's, which ends following if it's to end.
                    if let Fit::Follow { until_resized } = node.fit
                        && !node.in_full_screen()
                        && !node.heights.is_empty()
                    {
                        let min = crate::find_prop!(node.props, MinSize).map_or(0.0, |m| m.height);
                        match node.heights.iter().rposition(|h| (h.max(min) - size.height).abs() < 1.0) {
                            Some(reported) => drop(node.heights.drain(..reported)),
                            None if until_resized => {
                                node.fit = Fit::None;
                                node.heights.clear();
                            }
                            None => {}
                        }
                    }
                    node.window_size = *size;
                    self.styles_dirty = true;
                }
            }
            UiEvent::Remeasure => {
                if let Some(t) = self.nodes.get(&id).and_then(|n| n.taffy) {
                    let _ = self.taffy.mark_dirty(t);
                }
            }
            UiEvent::MetricsChanged => {
                self.metrics = self.backend.metrics();
                self.styles_dirty = true;
                for node in self.nodes.values_mut() {
                    node.drawn_at = None;
                    if let Some(t) = node.taffy {
                        let _ = self.taffy.mark_dirty(t);
                    }
                }
            }
            _ => {}
        }
    }
}