icedwright-semantics 0.0.1

The icedwright semantic tree: inference from recorded widget operations, stable node paths, hit testing, diffs and YAML
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
//! The semantic tree: an arena of nodes with roles, names, states, relations and geometry.

use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt;

use icedwright_protocol::{WidgetId, WindowId};
use icedwright_types::{Checked, CursorSeen, Point, Rect, Role, StateName, StateValue, Vector};
use serde::{Deserialize, Serialize};

use crate::path::NodePath;

/// A node's index in one tree. Never compare ids from different snapshots; use [`NodePath`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct NodeId(pub(crate) u32);

impl NodeId {
    /// The index into [`SemanticTree::iter`]'s order.
    #[must_use]
    pub const fn index(self) -> usize {
        self.0 as usize
    }
}

impl fmt::Display for NodeId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "e{}", self.0)
    }
}

/// The name other parts of icedwright use for a node.
pub type SemanticNode = Node;

/// A value a node reports.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Value {
    /// A text value.
    Text(String),
    /// A number within an optional range.
    Number {
        /// The current value.
        now: f64,
        /// The lowest value.
        min: Option<f64>,
        /// The highest value.
        max: Option<f64>,
        /// The step between values.
        step: Option<f64>,
    },
}

/// Which source set a state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StateSource {
    /// An application annotation.
    Annotation,
    /// A component library's annotation.
    Component,
    /// Inference from built-in widget operations.
    Inferred,
    /// Derived from the rest of the tree.
    Derived,
}

/// A node's states. `None` means no source could say; derived states are always known.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct States {
    /// Takes no input.
    pub disabled: Option<bool>,
    /// Shows a value that cannot be changed.
    pub readonly: Option<bool>,
    /// Checked, unchecked or mixed.
    pub checked: Option<Checked>,
    /// A toggle button is pressed.
    pub pressed: Option<bool>,
    /// Content or a popup is shown.
    pub expanded: Option<bool>,
    /// Selected in its container.
    pub selected: Option<bool>,
    /// Has keyboard focus.
    pub focused: Option<bool>,
    /// The current item in a set.
    pub current: Option<bool>,
    /// Loading or updating.
    pub busy: Option<bool>,
    /// Must be filled in.
    pub required: Option<bool>,
    /// Its value is rejected.
    pub invalid: Option<bool>,
    /// Takes more than one line.
    pub multiline: Option<bool>,
    /// Allows more than one selected item.
    pub multiselectable: Option<bool>,
    /// Everything outside it is inert while it is shown.
    pub modal: bool,
    /// Can take keyboard focus.
    pub focusable: bool,
    /// Explicitly hidden, zero-sized, or under a hidden ancestor.
    pub hidden: bool,
    /// Has size but is clipped out by a scrollable or the window.
    pub offscreen: bool,
    /// Outside the topmost modal.
    pub inert: bool,
    sources: BTreeMap<StateName, StateSource>,
}

impl States {
    /// The value of a state, or `None` when no source reports it.
    #[must_use]
    pub fn get(&self, state: StateName) -> Option<StateValue> {
        let flag = |on: bool| Some(StateValue::Bool(on));
        match state {
            StateName::Disabled => self.disabled.map(StateValue::Bool),
            StateName::Readonly => self.readonly.map(StateValue::Bool),
            StateName::Checked => self.checked.map(StateValue::from),
            StateName::Pressed => self.pressed.map(StateValue::Bool),
            StateName::Expanded => self.expanded.map(StateValue::Bool),
            StateName::Selected => self.selected.map(StateValue::Bool),
            StateName::Focused => self.focused.map(StateValue::Bool),
            StateName::Current => self.current.map(StateValue::Bool),
            StateName::Busy => self.busy.map(StateValue::Bool),
            StateName::Required => self.required.map(StateValue::Bool),
            StateName::Invalid => self.invalid.map(StateValue::Bool),
            StateName::Multiline => self.multiline.map(StateValue::Bool),
            StateName::Multiselectable => self.multiselectable.map(StateValue::Bool),
            StateName::Modal => flag(self.modal),
            StateName::Focusable => flag(self.focusable),
            StateName::Hidden => flag(self.hidden),
            StateName::Offscreen => flag(self.offscreen),
            StateName::Inert => flag(self.inert),
            _ => None,
        }
    }

    /// Sets a state and records its source. A mixed value on a state other than
    /// [`StateName::Checked`] sets it to true.
    pub fn set(&mut self, state: StateName, value: StateValue, source: StateSource) {
        let on = value.as_bool().unwrap_or(true);
        match state {
            StateName::Disabled => self.disabled = Some(on),
            StateName::Readonly => self.readonly = Some(on),
            StateName::Checked => self.checked = Some(value.as_checked()),
            StateName::Pressed => self.pressed = Some(on),
            StateName::Expanded => self.expanded = Some(on),
            StateName::Selected => self.selected = Some(on),
            StateName::Focused => self.focused = Some(on),
            StateName::Current => self.current = Some(on),
            StateName::Busy => self.busy = Some(on),
            StateName::Required => self.required = Some(on),
            StateName::Invalid => self.invalid = Some(on),
            StateName::Multiline => self.multiline = Some(on),
            StateName::Multiselectable => self.multiselectable = Some(on),
            StateName::Modal => self.modal = on,
            StateName::Focusable => self.focusable = on,
            StateName::Hidden => self.hidden = on,
            StateName::Offscreen => self.offscreen = on,
            StateName::Inert => self.inert = on,
            _ => return,
        }
        self.sources.insert(state, source);
    }

    /// Provenance of a known state, or `None` when the state itself is `None`. A derived flag
    /// no source set reports [`StateSource::Derived`].
    #[must_use]
    pub fn source(&self, state: StateName) -> Option<StateSource> {
        self.get(state)?;
        Some(
            self.sources
                .get(&state)
                .copied()
                .unwrap_or(StateSource::Derived),
        )
    }

    /// Every state with a value, in [`StateName::ALL`] order.
    pub fn known(&self) -> impl Iterator<Item = (StateName, StateValue)> + '_ {
        StateName::ALL
            .iter()
            .filter_map(|state| self.get(*state).map(|value| (*state, value)))
    }
}

/// Resolved relations to other nodes in the same tree.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Relations {
    /// Nodes whose text names this one.
    pub labelled_by: Vec<NodeId>,
    /// Nodes whose text describes this one.
    pub described_by: Vec<NodeId>,
    /// Nodes this one controls.
    pub controls: Vec<NodeId>,
    /// Logical children that live elsewhere, such as an overlay panel.
    pub owns: Vec<NodeId>,
    /// The inverse of `owns`.
    pub owner: Option<NodeId>,
}

impl Relations {
    /// Whether there are no relations at all.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.labelled_by.is_empty()
            && self.described_by.is_empty()
            && self.controls.is_empty()
            && self.owns.is_empty()
            && self.owner.is_none()
    }
}

/// Level, position in its set and set size, from annotations.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct SetInfo {
    /// The heading or tree level, from 1.
    pub level: Option<u16>,
    /// Position in the set, from 1.
    pub position: Option<u32>,
    /// The set's size.
    pub size: Option<u32>,
}

/// Which sources contributed a node's non-state fields.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct SourceSet {
    /// An application annotation.
    pub annotation: bool,
    /// A component annotation.
    pub component: bool,
    /// Inference from built-in operations.
    pub inferred: bool,
    /// The value is the visible text of an unannotated text input, which may be its
    /// placeholder.
    pub visible_text: bool,
}

/// The operation callback an inferred node came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum OperationKind {
    /// `container`, or a `traverse` with nothing reported first.
    Container,
    /// `scrollable`.
    Scrollable,
    /// `focusable`.
    Focusable,
    /// `text_input`.
    TextInput,
    /// `text`.
    Text,
    /// `custom` with something other than an annotation.
    Custom,
    /// The window itself.
    Window,
}

impl OperationKind {
    /// The name `of_type` matches.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            OperationKind::Container => "container",
            OperationKind::Scrollable => "scrollable",
            OperationKind::Focusable => "focusable",
            OperationKind::TextInput => "text_input",
            OperationKind::Text => "text",
            OperationKind::Custom => "custom",
            OperationKind::Window => "window",
        }
    }
}

/// What reported a node, for `of_type` and the inspector.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Kind {
    /// Inference from an operation callback.
    Inferred(OperationKind),
    /// An application annotation, `"app"` unless it names a kind.
    Annotated(Cow<'static, str>),
    /// A component annotation, such as `"iced_cube::tree"`.
    Component(Cow<'static, str>),
}

impl fmt::Display for Kind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Kind::Inferred(kind) => f.write_str(kind.name()),
            Kind::Annotated(name) | Kind::Component(name) => f.write_str(name),
        }
    }
}

/// Where a node's accessible name came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NameSource {
    /// It has no name.
    #[default]
    None,
    /// An explicit `.name(..)`.
    Annotation,
    /// The nodes in `labelled_by`.
    LabelledBy,
    /// A node that declared `.label_for(..)` with this node's key.
    LabelFor,
    /// The text of its descendants.
    Content,
    /// Its tooltip.
    Tooltip,
    /// Its annotated placeholder.
    Placeholder,
    /// A text node's own content.
    Text,
}

/// The overlay layer a node is in.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize,
)]
#[serde(rename_all = "snake_case")]
pub enum Layer {
    /// The window's base content.
    #[default]
    Base,
    /// An overlay, by nesting depth from 1.
    Overlay(u16),
}

/// A node's own scroll state.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Scroll {
    /// The content's bounds.
    pub content_bounds: Rect,
    /// The scroll translation.
    pub translation: Vector,
}

/// A scrollable enclosing a node.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ScrollAncestor {
    /// Its position among scrollable callbacks across the interface.
    pub ordinal: u32,
    /// Its bounds in window coordinates.
    pub bounds: Rect,
    /// Its content's bounds.
    pub content_bounds: Rect,
    /// Its scroll translation.
    pub translation: Vector,
}

/// Caret positions in a text node, from annotations.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct TextGeometry {
    /// Byte offset to caret top, sorted by offset.
    pub carets: Vec<(usize, Point)>,
}

impl TextGeometry {
    /// The caret top at a byte offset.
    #[must_use]
    pub fn caret(&self, byte: usize) -> Option<Point> {
        self.carets
            .binary_search_by_key(&byte, |(offset, _)| *offset)
            .ok()
            .and_then(|i| self.carets.get(i))
            .map(|(_, point)| *point)
    }
}

/// One node.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Node {
    /// Its index in this tree.
    pub id: NodeId,
    /// Its role.
    pub role: Role,
    /// Its accessible name, as reported.
    pub name: Option<String>,
    /// Where the name came from.
    pub name_source: NameSource,
    /// Its description.
    pub description: Option<String>,
    /// Its value.
    pub value: Option<Value>,
    /// Its placeholder.
    pub placeholder: Option<String>,
    /// Its tooltip.
    pub tooltip: Option<String>,
    /// Its states.
    pub states: States,
    /// Its relations.
    pub relations: Relations,
    /// Level and position in its set.
    pub set: SetInfo,
    /// Its test id.
    pub test_id: Option<String>,
    /// Its widget id.
    pub widget_id: Option<WidgetId>,
    /// What reported it.
    pub kind: Kind,
    /// Which sources contributed fields.
    pub sources: SourceSet,
    /// Component extras, such as a tab's `unsaved`.
    pub props: BTreeMap<String, String>,
    /// Text size in logical pixels, from annotations only.
    pub text_size: Option<f32>,
    /// Caret positions, from annotations only.
    pub text_geometry: Option<TextGeometry>,
    /// The cursor kind handed to it this frame, for annotated nodes.
    pub cursor_seen: Option<CursorSeen>,
    /// Window coordinates, scroll translation applied.
    pub bounds: Rect,
    /// The part not clipped by an enclosing scrollable or the window.
    pub visible_bounds: Option<Rect>,
    /// Its own scroll state, if it scrolls.
    pub scroll: Option<Scroll>,
    /// Enclosing scrollables, innermost last.
    pub scroll_ancestors: Vec<ScrollAncestor>,
    /// Its position among focusable callbacks across the interface.
    pub focusable_ordinal: Option<u32>,
    /// Its overlay layer.
    pub layer: Layer,
    /// Its window.
    pub window: WindowId,
    /// Operation order, which is paint order within a layer.
    pub order: u32,
    /// Its parent in the arena.
    pub parent: Option<NodeId>,
    /// Its children in the arena.
    pub children: Vec<NodeId>,
    /// Index path in the raw tree it came from.
    pub raw: Vec<u32>,
    /// An unnamed generic, transparent to queries and YAML.
    pub ignored: bool,
    /// Its stable path.
    pub path: NodePath,
}

impl Node {
    pub(crate) fn blank(role: Role, kind: Kind, window: WindowId) -> Self {
        Self {
            id: NodeId(0),
            role,
            name: None,
            name_source: NameSource::None,
            description: None,
            value: None,
            placeholder: None,
            tooltip: None,
            states: States::default(),
            relations: Relations::default(),
            set: SetInfo::default(),
            test_id: None,
            widget_id: None,
            kind,
            sources: SourceSet::default(),
            props: BTreeMap::new(),
            text_size: None,
            text_geometry: None,
            cursor_seen: None,
            bounds: Rect::ZERO,
            visible_bounds: None,
            scroll: None,
            scroll_ancestors: Vec::new(),
            focusable_ordinal: None,
            layer: Layer::Base,
            window,
            order: 0,
            parent: None,
            children: Vec::new(),
            raw: Vec::new(),
            ignored: false,
            path: NodePath::default(),
        }
    }
}

/// Something worth knowing about how a tree was built. Audits report these.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum TreeWarning {
    /// A relation named a key no node has; the relation was dropped.
    UnresolvedKey {
        /// The key.
        key: String,
        /// The node that named it.
        at: NodePath,
    },
    /// Two nodes declared the same key; the first keeps it.
    DuplicateKey {
        /// The key.
        key: String,
        /// The second node.
        at: NodePath,
    },
    /// An `owns` edge would make a cycle, or the target already had an owner; it was dropped.
    OwnsCycle {
        /// The node whose edge was dropped.
        at: NodePath,
    },
    /// An annotation's level was 0; ARIA levels start at 1.
    InvalidLevel {
        /// The node.
        at: NodePath,
    },
    /// A test id has characters outside `[a-z0-9._-]`.
    InvalidTestId {
        /// The node.
        at: NodePath,
        /// The id.
        id: String,
    },
    /// An annotation carried a role name this version does not know.
    UnknownRole {
        /// The node.
        at: NodePath,
    },
}

/// The semantic tree of every window.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct SemanticTree {
    pub(crate) nodes: Vec<Node>,
    pub(crate) roots: Vec<NodeId>,
    pub(crate) warnings: Vec<TreeWarning>,
    pub(crate) texts: Vec<String>,
}

impl SemanticTree {
    /// The node with this id, or `None` for an id from another tree that is out of range.
    #[must_use]
    pub fn get(&self, id: NodeId) -> Option<&Node> {
        self.nodes.get(id.index())
    }

    /// One `Window` node per window.
    #[must_use]
    pub fn roots(&self) -> &[NodeId] {
        &self.roots
    }

    /// Warnings from building the tree.
    #[must_use]
    pub fn warnings(&self) -> &[TreeWarning] {
        &self.warnings
    }

    /// Every node, in operation order.
    pub fn iter(&self) -> impl Iterator<Item = &Node> {
        self.nodes.iter()
    }

    /// The number of nodes, ignored ones included.
    #[must_use]
    pub fn len(&self) -> usize {
        self.nodes.len()
    }

    /// Whether the tree has no nodes.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.nodes.is_empty()
    }

    /// Every node below `id` in depth-first order, following `owns` into owned subtrees.
    /// Each node appears once.
    pub fn descendants(&self, id: NodeId) -> impl Iterator<Item = NodeId> + '_ {
        let mut seen = vec![false; self.nodes.len()];
        if let Some(flag) = seen.get_mut(id.index()) {
            *flag = true;
        }
        let mut stack: Vec<NodeId> = self.next_level(id).rev().collect();
        std::iter::from_fn(move || {
            while let Some(next) = stack.pop() {
                let Some(flag) = seen.get_mut(next.index()) else {
                    continue;
                };
                if *flag {
                    continue;
                }
                *flag = true;
                stack.extend(self.next_level(next).rev());
                return Some(next);
            }
            None
        })
    }

    fn next_level(&self, id: NodeId) -> impl DoubleEndedIterator<Item = NodeId> + '_ {
        let node = self.get(id);
        let children = node.map(|n| n.children.as_slice()).unwrap_or_default();
        let owns = node
            .map(|n| n.relations.owns.as_slice())
            .unwrap_or_default();
        children.iter().chain(owns).copied()
    }

    /// The parents of `id`, nearest first.
    pub fn ancestors(&self, id: NodeId) -> impl Iterator<Item = NodeId> + '_ {
        let mut current = self.get(id).and_then(|n| n.parent);
        std::iter::from_fn(move || {
            let next = current?;
            current = self.get(next).and_then(|n| n.parent);
            Some(next)
        })
    }

    /// The node's own text joined with its non-hidden descendants' text in tree order.
    #[must_use]
    pub fn text_content(&self, id: NodeId) -> &str {
        self.texts.get(id.index()).map_or("", String::as_str)
    }

    /// The node at a path from this or another snapshot.
    #[must_use]
    pub fn find_path(&self, path: &NodePath) -> Option<NodeId> {
        self.nodes.iter().find(|n| &n.path == path).map(|n| n.id)
    }

    /// The node at a path, as a node.
    #[must_use]
    pub fn node_at(&self, path: &NodePath) -> Option<&Node> {
        self.find_path(path).and_then(|id| self.get(id))
    }

    /// The node recorded at a raw index path, or the deepest node whose raw path is a prefix
    /// of it, which is the node that absorbed or merged that raw call.
    #[must_use]
    pub fn by_raw(&self, raw: &[u32]) -> Option<NodeId> {
        self.nodes
            .iter()
            .filter(|n| raw.starts_with(&n.raw))
            .max_by_key(|n| n.raw.len())
            .map(|n| n.id)
    }

    /// The window's root node.
    #[must_use]
    pub fn window(&self, id: WindowId) -> Option<NodeId> {
        self.roots
            .iter()
            .copied()
            .find(|root| self.get(*root).is_some_and(|n| n.window == id))
    }

    /// Rewrites the number of every `WidgetId::Unique` through `renumber`. iced numbers unique
    /// ids from one process-wide counter, so a trace renumbers them to compare across runs.
    pub fn renumber_widget_ids(&mut self, mut renumber: impl FnMut(usize) -> usize) {
        for node in &mut self.nodes {
            if let Some(WidgetId::Unique(n)) = &mut node.widget_id {
                *n = renumber(*n);
            }
        }
    }
}