mitsuami-headless 2.2.0

In-memory mitsuami backend with deterministic measurement, for tests
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
406
407
//! Applying commands, checking each against the protocol.

use std::collections::{BTreeMap, BTreeSet, HashSet};

use mitsuami_core::a11y::A11yProps;
use mitsuami_core::{
    Command, Insets, NodeId, Point, Prop, Rect, RowKey, SelectionMode, SurfaceHandle, UiEvent, WidgetKind, find_prop,
};

use super::state::violation;
use super::{HeadlessBackend, HeadlessNode, HeadlessSurface, State};

impl HeadlessBackend {
    pub(super) fn apply_batch(&mut self, batch: &[Command]) {
        let mut state = self.state.borrow_mut();
        // The nodes the batch named, and their parents: the lists to place
        // again and the nodes to check after it are among them.
        let mut touched = BTreeSet::new();
        // Children removed or destroyed, taken out of their parents'
        // lists together once a run of them ends: one at a time scanned
        // the siblings for each (`unlink`).
        let mut unlinked: BTreeMap<NodeId, HashSet<NodeId>> = BTreeMap::new();
        for command in batch {
            if state.recording {
                state.log.push(command.clone());
            }
            if !matches!(command, Command::Remove { .. } | Command::Destroy { .. }) {
                state.unlink(&mut unlinked);
            }
            state.touch(command, &mut touched);
            match command {
                Command::Create { id, kind, props } => {
                    if state.nodes.contains_key(id) {
                        violation(command, "node already exists");
                    }
                    if *kind == WidgetKind::Fragment {
                        violation(command, "fragments are core-only");
                    }
                    if matches!(kind, WidgetKind::Custom(_)) && find_prop!(props, Custom).is_none() {
                        violation(command, "custom widgets are created with their Prop::Custom");
                    }
                    if *kind == WidgetKind::Native && find_prop!(props, Native).is_none() {
                        violation(command, "native views are created with their Prop::Native");
                    }
                    state.nodes.insert(
                        *id,
                        HeadlessNode {
                            kind: *kind,
                            props: props.clone(),
                            a11y: A11yProps::default(),
                            frame: Rect::ZERO,
                            parent: None,
                            children: Vec::new(),
                            scroll_offset: Point::ZERO,
                            viewport_insets: Insets::ZERO,
                            shown: BTreeSet::new(),
                            placed: Vec::new(),
                            placed_index: Default::default(),
                            heights: BTreeMap::new(),
                            column_widths: Vec::new(),
                            natural_height: 0.0,
                            bare_heights: BTreeMap::new(),
                            surface: None,
                            windowed: None,
                            restored: None,
                        },
                    );
                    if find_prop!(props, Maximized) == Some(true) {
                        state.maximize(*id, true);
                    }
                    // A tree says how it indents its rows, as platforms do
                    // once they've made it.
                    if *kind == WidgetKind::Tree {
                        state.emit(*id, UiEvent::TreeIndent(super::metrics::TREE_INDENT));
                    }
                    // A log given its text and `FollowsEnd` starts at its end.
                    if *kind == WidgetKind::TextArea && find_prop!(props, FollowsEnd) == Some(true) {
                        state.follow_to_end(*id);
                    }
                    if *kind == WidgetKind::GpuSurface {
                        let surface = SurfaceHandle::new(HeadlessSurface);
                        state.nodes.get_mut(id).unwrap().surface = Some(surface.clone());
                        state.emit(*id, UiEvent::SurfaceReady(surface));
                        if find_prop!(props, KeyboardGrab) == Some(true) {
                            state.focus(*id);
                        }
                    }
                }
                Command::SetProp { id, prop } => {
                    state.node(*id, command);
                    // New text puts the caret at its end.
                    if let Prop::Value(text) = prop
                        && state.focused == Some(*id)
                        && find_prop!(state.nodes[id].props, Value).as_ref() != Some(text)
                    {
                        state.selection = None;
                    }
                    let text_area = state.nodes[id].kind == WidgetKind::TextArea;
                    let following = find_prop!(state.nodes[id].props, FollowsEnd) == Some(true);
                    if matches!(prop, Prop::Value(_)) && text_area {
                        state.set_text_area_value(*id, prop.clone());
                    } else if *prop == Prop::FollowsEnd(true) && text_area && !following {
                        // Turned on, it starts at its end.
                        state.set_prop(*id, prop.clone());
                        state.follow_to_end(*id);
                    } else {
                        state.set_prop(*id, prop.clone());
                    }
                    // A grab focuses its surface.
                    if *prop == Prop::KeyboardGrab(true) {
                        state.focus(*id);
                    }
                    match prop {
                        Prop::FullScreen(on) => state.fill_screen(*id, *on),
                        Prop::Maximized(on) => state.maximize(*id, *on),
                        Prop::MinSize(_) => {
                            let size = state.nodes[id].frame.size;
                            state.resize(*id, size);
                        }
                        _ => {}
                    }
                    if let Prop::TreeRows(rows) = prop {
                        super::lists::check_tree_rows(command, rows);
                    }
                    // The rows that load are rows that show, sent after them.
                    if let Prop::TreeLoading(loading) = prop {
                        let rows = super::lists::tree_rows(&state.nodes[id]);
                        if let Some(row) = loading.iter().find(|r| !rows.iter().any(|t| t.row == **r)) {
                            violation(command, &format!("loading tree row {row:?} doesn't show"));
                        }
                    }
                    // Like native lists, removing rows deselects them.
                    let rows: Option<Box<dyn Iterator<Item = RowKey>>> = match prop {
                        Prop::Rows(rows) => Some(Box::new(rows.iter().copied())),
                        Prop::TreeRows(rows) => Some(Box::new(rows.iter().map(|r| r.row))),
                        _ => None,
                    };
                    if let Some(rows) = rows {
                        let selected = find_prop!(state.nodes[id].props, Selected).unwrap_or_default();
                        let rows: BTreeSet<RowKey> = if selected.is_empty() { BTreeSet::new() } else { rows.collect() };
                        let kept: Vec<RowKey> = selected.iter().copied().filter(|k| rows.contains(k)).collect();
                        if kept != selected {
                            state.select(*id, kept);
                        }
                    }
                    // A mode that holds fewer rows lets go of the others:
                    // none, or all but the first.
                    if let Prop::SelectionMode(mode) = prop {
                        let selected = find_prop!(state.nodes[id].props, Selected).unwrap_or_default();
                        let kept = match mode {
                            SelectionMode::None => Vec::new(),
                            SelectionMode::Single => selected.iter().take(1).copied().collect(),
                            SelectionMode::Multiple => selected.clone(),
                        };
                        if kept != selected {
                            state.select(*id, kept);
                        }
                    }
                }
                Command::Insert { parent, child, index } => {
                    if let Some(p) = state.node(*child, command).parent {
                        violation(command, &format!("child is still attached to {p}"));
                    }
                    let parent_node = state.node(*parent, command);
                    if parent_node.kind == WidgetKind::ScrollView && !parent_node.children.is_empty() {
                        violation(command, "a ScrollView has a single native child (its content)");
                    }
                    let siblings = &mut state.node(*parent, command).children;
                    if *index > siblings.len() {
                        violation(command, &format!("index out of bounds (len {})", siblings.len()));
                    }
                    siblings.insert(*index, *child);
                    state.node(*child, command).parent = Some(*parent);
                }
                Command::Remove { parent, child } => {
                    state.node(*parent, command);
                    // Both sides of a link are kept together, so the child
                    // says whether it's in the parent's list.
                    if state.node(*child, command).parent != Some(*parent) {
                        violation(command, "not a child of this parent");
                    }
                    state.node(*child, command).parent = None;
                    unlinked.entry(*parent).or_default().insert(*child);
                }
                Command::Destroy { id } => {
                    let node = state.nodes.remove(id).unwrap_or_else(|| violation(command, "node does not exist"));
                    if let Some(parent) = node.parent.filter(|p| state.nodes.contains_key(p)) {
                        unlinked.entry(parent).or_default().insert(*id);
                    }
                    for child in node.children {
                        if let Some(child) = state.nodes.get_mut(&child) {
                            child.parent = None;
                        }
                    }
                    if state.focused == Some(*id) {
                        state.focused = None;
                    }
                    state.focus_orders.remove(id);
                }
                Command::SetFrame { id, frame } => {
                    let node = state.node(*id, command);
                    if node.kind == WidgetKind::Window {
                        violation(command, "window frames belong to the platform");
                    }
                    if node.kind == WidgetKind::Sidebar {
                        violation(command, "a sidebar's frame belongs to the platform");
                    }
                    // A text area's text scrolls no further than its end, and
                    // one following its end keeps to it as it's resized.
                    if node.kind == WidgetKind::TextArea {
                        let follows = find_prop!(node.props, FollowsEnd) == Some(true);
                        let was_at_end = node.scroll_offset.y >= state.text_area_end(*id) - 0.5;
                        state.nodes.get_mut(id).unwrap().frame = *frame;
                        let end = state.text_area_end(*id);
                        let offset = &mut state.nodes.get_mut(id).unwrap().scroll_offset;
                        offset.y = if follows && was_at_end { end } else { offset.y.min(end) };
                    } else {
                        node.frame = *frame;
                    }
                    state.size_surface(*id);
                }
                Command::SetA11y { id, a11y } => state.node(*id, command).a11y = a11y.clone(),
                Command::SetWindowSize { id, size } => {
                    state.node(*id, command);
                    state.resize(*id, *size);
                }
                Command::SetFocusOrder { window, order } => {
                    if state.node(*window, command).kind != WidgetKind::Window {
                        violation(command, "not a window");
                    }
                    for id in order {
                        state.node(*id, command);
                    }
                    state.focus_orders.insert(*window, order.clone());
                }
                Command::ScrollTo { id, offset } => {
                    if !state.node(*id, command).kind.scrolls() {
                        violation(command, "not a ScrollView, List or Table");
                    }
                    state.scroll(*id, *offset);
                }
                Command::Focus { id } => {
                    state.node(*id, command);
                    state.focus(*id);
                }
                Command::SelectText { id, range } => {
                    let node = state.node(*id, command);
                    if !matches!(
                        node.kind,
                        WidgetKind::TextInput
                            | WidgetKind::PasswordInput
                            | WidgetKind::SearchInput
                            | WidgetKind::TextArea
                    ) {
                        violation(command, "not a text field or text area");
                    }
                    let len = find_prop!(node.props, Value).map_or(0, |v| v.chars().count());
                    if range.start > range.end || range.end > len {
                        violation(command, "a selection past the text");
                    }
                    if state.focused != Some(*id) {
                        violation(command, "a selection of a field without focus");
                    }
                    state.selection = Some(range.clone());
                }
                Command::ScrollToRow { id, row } => {
                    if !state.node(*id, command).kind.has_rows() {
                        violation(command, "not a List or Table");
                    }
                    state.place_rows(*id);
                    state.reveal(*id, *row);
                }
            }
        }
        state.unlink(&mut unlinked);
        touched.retain(|id| state.nodes.contains_key(id));
        if let Some(last) = batch.last() {
            // New data, sizes or rows: what's in view may have changed. Only
            // in the lists the batch touched: the others are as they were.
            let lists: Vec<NodeId> = touched.iter().copied().filter(|id| state.nodes[id].kind.has_rows()).collect();
            for list in &lists {
                if state.nodes[list].kind == WidgetKind::Table {
                    state.size_columns(*list);
                }
                state.place_rows(*list);
            }
            state.check_lists(last, &touched);
            state.check_toolbars(last, &touched);
            state.check_tabs(last, &touched);
            for list in lists {
                let offset = state.nodes[&list].scroll_offset;
                let y = state.clamp_list(list, offset.y);
                if y != offset.y {
                    state.scroll(list, Point::new(offset.x, y));
                }
                state.show_rows(list);
            }
        }
    }
}

impl State {
    /// Adds the nodes a command names, and their parents (a list, for its
    /// hosts' frames and props), to `touched`.
    fn touch(&self, command: &Command, touched: &mut BTreeSet<NodeId>) {
        let ids = match command {
            Command::Create { id, .. }
            | Command::SetProp { id, .. }
            | Command::Destroy { id }
            | Command::SetFrame { id, .. }
            | Command::ScrollToRow { id, .. } => [Some(*id), None],
            Command::Insert { parent, child, .. } | Command::Remove { parent, child } => [Some(*parent), Some(*child)],
            _ => [None, None],
        };
        for id in ids.into_iter().flatten() {
            touched.insert(id);
            touched.extend(self.nodes.get(&id).and_then(|n| n.parent));
        }
    }

    /// Takes children removed or destroyed out of their parents' lists,
    /// each parent's once.
    fn unlink(&mut self, unlinked: &mut BTreeMap<NodeId, HashSet<NodeId>>) {
        for (parent, gone) in std::mem::take(unlinked) {
            if let Some(node) = self.nodes.get_mut(&parent) {
                node.children.retain(|c| !gone.contains(c));
            }
        }
    }

    /// Checks that toolbar items are in windows, after their content, and
    /// that a window has at most one sidebar, after them, whose selection
    /// is one of its items. Only `touched` nodes can have changed.
    pub(super) fn check_toolbars(&self, command: &Command, touched: &BTreeSet<NodeId>) {
        for (id, node) in touched.iter().map(|id| (id, &self.nodes[id])) {
            let kind = |c: &NodeId| self.nodes[c].kind;
            let sidebars = node.children.iter().filter(|c| kind(c) == WidgetKind::Sidebar).count();
            if sidebars > 0 && node.kind != WidgetKind::Window {
                violation(command, &format!("{id} has a sidebar but isn't a window"));
            }
            if sidebars > 1 {
                violation(command, &format!("window {id} has {sidebars} sidebars"));
            }
            if sidebars == 1 && node.children.last().map(kind) != Some(WidgetKind::Sidebar) {
                violation(command, &format!("window {id}'s sidebar isn't after its content and toolbar items"));
            }
            // A container's popovers come after its content.
            let popovers = node.children.iter().filter(|c| kind(c) == WidgetKind::Popover).count();
            if popovers > 0 && (!node.kind.is_container() || node.kind == WidgetKind::Window) {
                violation(command, &format!("{id} has a popover but isn't a container"));
            }
            if node.children[node.children.len() - popovers..].iter().any(|c| kind(c) != WidgetKind::Popover) {
                violation(command, &format!("{id}'s popovers aren't after its content"));
            }
            let children = &node.children[..node.children.len() - sidebars];
            let items = children.iter().filter(|c| kind(c) == WidgetKind::ToolbarItem).count();
            if items > 0 && node.kind != WidgetKind::Window {
                violation(command, &format!("{id} has toolbar items but isn't a window"));
            }
            let content = children.len() - items;
            if children[content..].iter().any(|c| kind(c) != WidgetKind::ToolbarItem) {
                violation(command, &format!("window {id}'s toolbar items aren't after its content"));
            }
            if node.kind == WidgetKind::Sidebar {
                let count: usize =
                    find_prop!(node.props, Sections).unwrap_or_default().iter().map(|s| s.items.len()).sum();
                if find_prop!(node.props, SelectedIndex).flatten().is_some_and(|i| i >= count) {
                    violation(command, &format!("sidebar {id}'s selection isn't one of its {count} items"));
                }
            }
        }
    }

    /// Checks that a tab view's children are page hosts, one per title,
    /// and that it shows one of them (none only without pages); and that
    /// document tabs have no children and choose one of their tabs.
    pub(super) fn check_tabs(&self, command: &Command, touched: &BTreeSet<NodeId>) {
        for (id, node) in touched.iter().map(|id| (id, &self.nodes[id])) {
            // Document tabs have no pages: one tab chosen, none only without.
            if node.kind == WidgetKind::DocumentTabs {
                if !node.children.is_empty() {
                    violation(command, &format!("document tabs {id} have children"));
                }
                let titles = find_prop!(node.props, TabTitles).unwrap_or_default().len();
                let chosen = find_prop!(node.props, SelectedIndex).flatten();
                if chosen.is_none_or(|i| i >= titles) != (titles == 0) {
                    violation(command, &format!("document tabs {id} choose {chosen:?} of their {titles} tabs"));
                }
            }
            if node.kind != WidgetKind::Tabs {
                continue;
            }
            if node.children.iter().any(|c| self.nodes[c].kind != WidgetKind::Container) {
                violation(command, &format!("tabs {id} has a child that isn't a page host (a Container)"));
            }
            let pages = node.children.len();
            let titles = find_prop!(node.props, TabTitles).unwrap_or_default().len();
            if titles != pages {
                violation(command, &format!("tabs {id} has {pages} pages but {titles} titles"));
            }
            let shown = find_prop!(node.props, SelectedIndex).flatten();
            if shown.is_none_or(|i| i >= pages) != (pages == 0) {
                violation(command, &format!("tabs {id} shows {shown:?} of its {pages} pages"));
            }
        }
    }
}