Skip to main content

icedwright_semantics/
tree.rs

1//! The semantic tree: an arena of nodes with roles, names, states, relations and geometry.
2
3use std::borrow::Cow;
4use std::collections::BTreeMap;
5use std::fmt;
6
7use icedwright_protocol::{WidgetId, WindowId};
8use icedwright_types::{Checked, CursorSeen, Point, Rect, Role, StateName, StateValue, Vector};
9use serde::{Deserialize, Serialize};
10
11use crate::path::NodePath;
12
13/// A node's index in one tree. Never compare ids from different snapshots; use [`NodePath`].
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
15#[serde(transparent)]
16pub struct NodeId(pub(crate) u32);
17
18impl NodeId {
19    /// The index into [`SemanticTree::iter`]'s order.
20    #[must_use]
21    pub const fn index(self) -> usize {
22        self.0 as usize
23    }
24}
25
26impl fmt::Display for NodeId {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        write!(f, "e{}", self.0)
29    }
30}
31
32/// The name other parts of icedwright use for a node.
33pub type SemanticNode = Node;
34
35/// A value a node reports.
36#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
37#[serde(rename_all = "snake_case")]
38pub enum Value {
39    /// A text value.
40    Text(String),
41    /// A number within an optional range.
42    Number {
43        /// The current value.
44        now: f64,
45        /// The lowest value.
46        min: Option<f64>,
47        /// The highest value.
48        max: Option<f64>,
49        /// The step between values.
50        step: Option<f64>,
51    },
52}
53
54/// Which source set a state.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57pub enum StateSource {
58    /// An application annotation.
59    Annotation,
60    /// A component library's annotation.
61    Component,
62    /// Inference from built-in widget operations.
63    Inferred,
64    /// Derived from the rest of the tree.
65    Derived,
66}
67
68/// A node's states. `None` means no source could say; derived states are always known.
69#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
70pub struct States {
71    /// Takes no input.
72    pub disabled: Option<bool>,
73    /// Shows a value that cannot be changed.
74    pub readonly: Option<bool>,
75    /// Checked, unchecked or mixed.
76    pub checked: Option<Checked>,
77    /// A toggle button is pressed.
78    pub pressed: Option<bool>,
79    /// Content or a popup is shown.
80    pub expanded: Option<bool>,
81    /// Selected in its container.
82    pub selected: Option<bool>,
83    /// Has keyboard focus.
84    pub focused: Option<bool>,
85    /// The current item in a set.
86    pub current: Option<bool>,
87    /// Loading or updating.
88    pub busy: Option<bool>,
89    /// Must be filled in.
90    pub required: Option<bool>,
91    /// Its value is rejected.
92    pub invalid: Option<bool>,
93    /// Takes more than one line.
94    pub multiline: Option<bool>,
95    /// Allows more than one selected item.
96    pub multiselectable: Option<bool>,
97    /// Everything outside it is inert while it is shown.
98    pub modal: bool,
99    /// Can take keyboard focus.
100    pub focusable: bool,
101    /// Explicitly hidden, zero-sized, or under a hidden ancestor.
102    pub hidden: bool,
103    /// Has size but is clipped out by a scrollable or the window.
104    pub offscreen: bool,
105    /// Outside the topmost modal.
106    pub inert: bool,
107    sources: BTreeMap<StateName, StateSource>,
108}
109
110impl States {
111    /// The value of a state, or `None` when no source reports it.
112    #[must_use]
113    pub fn get(&self, state: StateName) -> Option<StateValue> {
114        let flag = |on: bool| Some(StateValue::Bool(on));
115        match state {
116            StateName::Disabled => self.disabled.map(StateValue::Bool),
117            StateName::Readonly => self.readonly.map(StateValue::Bool),
118            StateName::Checked => self.checked.map(StateValue::from),
119            StateName::Pressed => self.pressed.map(StateValue::Bool),
120            StateName::Expanded => self.expanded.map(StateValue::Bool),
121            StateName::Selected => self.selected.map(StateValue::Bool),
122            StateName::Focused => self.focused.map(StateValue::Bool),
123            StateName::Current => self.current.map(StateValue::Bool),
124            StateName::Busy => self.busy.map(StateValue::Bool),
125            StateName::Required => self.required.map(StateValue::Bool),
126            StateName::Invalid => self.invalid.map(StateValue::Bool),
127            StateName::Multiline => self.multiline.map(StateValue::Bool),
128            StateName::Multiselectable => self.multiselectable.map(StateValue::Bool),
129            StateName::Modal => flag(self.modal),
130            StateName::Focusable => flag(self.focusable),
131            StateName::Hidden => flag(self.hidden),
132            StateName::Offscreen => flag(self.offscreen),
133            StateName::Inert => flag(self.inert),
134            _ => None,
135        }
136    }
137
138    /// Sets a state and records its source. A mixed value on a state other than
139    /// [`StateName::Checked`] sets it to true.
140    pub fn set(&mut self, state: StateName, value: StateValue, source: StateSource) {
141        let on = value.as_bool().unwrap_or(true);
142        match state {
143            StateName::Disabled => self.disabled = Some(on),
144            StateName::Readonly => self.readonly = Some(on),
145            StateName::Checked => self.checked = Some(value.as_checked()),
146            StateName::Pressed => self.pressed = Some(on),
147            StateName::Expanded => self.expanded = Some(on),
148            StateName::Selected => self.selected = Some(on),
149            StateName::Focused => self.focused = Some(on),
150            StateName::Current => self.current = Some(on),
151            StateName::Busy => self.busy = Some(on),
152            StateName::Required => self.required = Some(on),
153            StateName::Invalid => self.invalid = Some(on),
154            StateName::Multiline => self.multiline = Some(on),
155            StateName::Multiselectable => self.multiselectable = Some(on),
156            StateName::Modal => self.modal = on,
157            StateName::Focusable => self.focusable = on,
158            StateName::Hidden => self.hidden = on,
159            StateName::Offscreen => self.offscreen = on,
160            StateName::Inert => self.inert = on,
161            _ => return,
162        }
163        self.sources.insert(state, source);
164    }
165
166    /// Provenance of a known state, or `None` when the state itself is `None`. A derived flag
167    /// no source set reports [`StateSource::Derived`].
168    #[must_use]
169    pub fn source(&self, state: StateName) -> Option<StateSource> {
170        self.get(state)?;
171        Some(
172            self.sources
173                .get(&state)
174                .copied()
175                .unwrap_or(StateSource::Derived),
176        )
177    }
178
179    /// Every state with a value, in [`StateName::ALL`] order.
180    pub fn known(&self) -> impl Iterator<Item = (StateName, StateValue)> + '_ {
181        StateName::ALL
182            .iter()
183            .filter_map(|state| self.get(*state).map(|value| (*state, value)))
184    }
185}
186
187/// Resolved relations to other nodes in the same tree.
188#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
189pub struct Relations {
190    /// Nodes whose text names this one.
191    pub labelled_by: Vec<NodeId>,
192    /// Nodes whose text describes this one.
193    pub described_by: Vec<NodeId>,
194    /// Nodes this one controls.
195    pub controls: Vec<NodeId>,
196    /// Logical children that live elsewhere, such as an overlay panel.
197    pub owns: Vec<NodeId>,
198    /// The inverse of `owns`.
199    pub owner: Option<NodeId>,
200}
201
202impl Relations {
203    /// Whether there are no relations at all.
204    #[must_use]
205    pub fn is_empty(&self) -> bool {
206        self.labelled_by.is_empty()
207            && self.described_by.is_empty()
208            && self.controls.is_empty()
209            && self.owns.is_empty()
210            && self.owner.is_none()
211    }
212}
213
214/// Level, position in its set and set size, from annotations.
215#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
216pub struct SetInfo {
217    /// The heading or tree level, from 1.
218    pub level: Option<u16>,
219    /// Position in the set, from 1.
220    pub position: Option<u32>,
221    /// The set's size.
222    pub size: Option<u32>,
223}
224
225/// Which sources contributed a node's non-state fields.
226#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
227pub struct SourceSet {
228    /// An application annotation.
229    pub annotation: bool,
230    /// A component annotation.
231    pub component: bool,
232    /// Inference from built-in operations.
233    pub inferred: bool,
234    /// The value is the visible text of an unannotated text input, which may be its
235    /// placeholder.
236    pub visible_text: bool,
237}
238
239/// The operation callback an inferred node came from.
240#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
241#[serde(rename_all = "snake_case")]
242#[non_exhaustive]
243pub enum OperationKind {
244    /// `container`, or a `traverse` with nothing reported first.
245    Container,
246    /// `scrollable`.
247    Scrollable,
248    /// `focusable`.
249    Focusable,
250    /// `text_input`.
251    TextInput,
252    /// `text`.
253    Text,
254    /// `custom` with something other than an annotation.
255    Custom,
256    /// The window itself.
257    Window,
258}
259
260impl OperationKind {
261    /// The name `of_type` matches.
262    #[must_use]
263    pub const fn name(self) -> &'static str {
264        match self {
265            OperationKind::Container => "container",
266            OperationKind::Scrollable => "scrollable",
267            OperationKind::Focusable => "focusable",
268            OperationKind::TextInput => "text_input",
269            OperationKind::Text => "text",
270            OperationKind::Custom => "custom",
271            OperationKind::Window => "window",
272        }
273    }
274}
275
276/// What reported a node, for `of_type` and the inspector.
277#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
278#[serde(rename_all = "snake_case")]
279pub enum Kind {
280    /// Inference from an operation callback.
281    Inferred(OperationKind),
282    /// An application annotation, `"app"` unless it names a kind.
283    Annotated(Cow<'static, str>),
284    /// A component annotation, such as `"iced_cube::tree"`.
285    Component(Cow<'static, str>),
286}
287
288impl fmt::Display for Kind {
289    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
290        match self {
291            Kind::Inferred(kind) => f.write_str(kind.name()),
292            Kind::Annotated(name) | Kind::Component(name) => f.write_str(name),
293        }
294    }
295}
296
297/// Where a node's accessible name came from.
298#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
299#[serde(rename_all = "snake_case")]
300pub enum NameSource {
301    /// It has no name.
302    #[default]
303    None,
304    /// An explicit `.name(..)`.
305    Annotation,
306    /// The nodes in `labelled_by`.
307    LabelledBy,
308    /// A node that declared `.label_for(..)` with this node's key.
309    LabelFor,
310    /// The text of its descendants.
311    Content,
312    /// Its tooltip.
313    Tooltip,
314    /// Its annotated placeholder.
315    Placeholder,
316    /// A text node's own content.
317    Text,
318}
319
320/// The overlay layer a node is in.
321#[derive(
322    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize,
323)]
324#[serde(rename_all = "snake_case")]
325pub enum Layer {
326    /// The window's base content.
327    #[default]
328    Base,
329    /// An overlay, by nesting depth from 1.
330    Overlay(u16),
331}
332
333/// A node's own scroll state.
334#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
335pub struct Scroll {
336    /// The content's bounds.
337    pub content_bounds: Rect,
338    /// The scroll translation.
339    pub translation: Vector,
340}
341
342/// A scrollable enclosing a node.
343#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
344pub struct ScrollAncestor {
345    /// Its position among scrollable callbacks across the interface.
346    pub ordinal: u32,
347    /// Its bounds in window coordinates.
348    pub bounds: Rect,
349    /// Its content's bounds.
350    pub content_bounds: Rect,
351    /// Its scroll translation.
352    pub translation: Vector,
353}
354
355/// Caret positions in a text node, from annotations.
356#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
357pub struct TextGeometry {
358    /// Byte offset to caret top, sorted by offset.
359    pub carets: Vec<(usize, Point)>,
360}
361
362impl TextGeometry {
363    /// The caret top at a byte offset.
364    #[must_use]
365    pub fn caret(&self, byte: usize) -> Option<Point> {
366        self.carets
367            .binary_search_by_key(&byte, |(offset, _)| *offset)
368            .ok()
369            .and_then(|i| self.carets.get(i))
370            .map(|(_, point)| *point)
371    }
372}
373
374/// One node.
375#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
376pub struct Node {
377    /// Its index in this tree.
378    pub id: NodeId,
379    /// Its role.
380    pub role: Role,
381    /// Its accessible name, as reported.
382    pub name: Option<String>,
383    /// Where the name came from.
384    pub name_source: NameSource,
385    /// Its description.
386    pub description: Option<String>,
387    /// Its value.
388    pub value: Option<Value>,
389    /// Its placeholder.
390    pub placeholder: Option<String>,
391    /// Its tooltip.
392    pub tooltip: Option<String>,
393    /// Its states.
394    pub states: States,
395    /// Its relations.
396    pub relations: Relations,
397    /// Level and position in its set.
398    pub set: SetInfo,
399    /// Its test id.
400    pub test_id: Option<String>,
401    /// Its widget id.
402    pub widget_id: Option<WidgetId>,
403    /// What reported it.
404    pub kind: Kind,
405    /// Which sources contributed fields.
406    pub sources: SourceSet,
407    /// Component extras, such as a tab's `unsaved`.
408    pub props: BTreeMap<String, String>,
409    /// Text size in logical pixels, from annotations only.
410    pub text_size: Option<f32>,
411    /// Caret positions, from annotations only.
412    pub text_geometry: Option<TextGeometry>,
413    /// The cursor kind handed to it this frame, for annotated nodes.
414    pub cursor_seen: Option<CursorSeen>,
415    /// Window coordinates, scroll translation applied.
416    pub bounds: Rect,
417    /// The part not clipped by an enclosing scrollable or the window.
418    pub visible_bounds: Option<Rect>,
419    /// Its own scroll state, if it scrolls.
420    pub scroll: Option<Scroll>,
421    /// Enclosing scrollables, innermost last.
422    pub scroll_ancestors: Vec<ScrollAncestor>,
423    /// Its position among focusable callbacks across the interface.
424    pub focusable_ordinal: Option<u32>,
425    /// Its overlay layer.
426    pub layer: Layer,
427    /// Its window.
428    pub window: WindowId,
429    /// Operation order, which is paint order within a layer.
430    pub order: u32,
431    /// Its parent in the arena.
432    pub parent: Option<NodeId>,
433    /// Its children in the arena.
434    pub children: Vec<NodeId>,
435    /// Index path in the raw tree it came from.
436    pub raw: Vec<u32>,
437    /// An unnamed generic, transparent to queries and YAML.
438    pub ignored: bool,
439    /// Its stable path.
440    pub path: NodePath,
441}
442
443impl Node {
444    pub(crate) fn blank(role: Role, kind: Kind, window: WindowId) -> Self {
445        Self {
446            id: NodeId(0),
447            role,
448            name: None,
449            name_source: NameSource::None,
450            description: None,
451            value: None,
452            placeholder: None,
453            tooltip: None,
454            states: States::default(),
455            relations: Relations::default(),
456            set: SetInfo::default(),
457            test_id: None,
458            widget_id: None,
459            kind,
460            sources: SourceSet::default(),
461            props: BTreeMap::new(),
462            text_size: None,
463            text_geometry: None,
464            cursor_seen: None,
465            bounds: Rect::ZERO,
466            visible_bounds: None,
467            scroll: None,
468            scroll_ancestors: Vec::new(),
469            focusable_ordinal: None,
470            layer: Layer::Base,
471            window,
472            order: 0,
473            parent: None,
474            children: Vec::new(),
475            raw: Vec::new(),
476            ignored: false,
477            path: NodePath::default(),
478        }
479    }
480}
481
482/// Something worth knowing about how a tree was built. Audits report these.
483#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
484#[serde(rename_all = "snake_case")]
485#[non_exhaustive]
486pub enum TreeWarning {
487    /// A relation named a key no node has; the relation was dropped.
488    UnresolvedKey {
489        /// The key.
490        key: String,
491        /// The node that named it.
492        at: NodePath,
493    },
494    /// Two nodes declared the same key; the first keeps it.
495    DuplicateKey {
496        /// The key.
497        key: String,
498        /// The second node.
499        at: NodePath,
500    },
501    /// An `owns` edge would make a cycle, or the target already had an owner; it was dropped.
502    OwnsCycle {
503        /// The node whose edge was dropped.
504        at: NodePath,
505    },
506    /// An annotation's level was 0; ARIA levels start at 1.
507    InvalidLevel {
508        /// The node.
509        at: NodePath,
510    },
511    /// A test id has characters outside `[a-z0-9._-]`.
512    InvalidTestId {
513        /// The node.
514        at: NodePath,
515        /// The id.
516        id: String,
517    },
518    /// An annotation carried a role name this version does not know.
519    UnknownRole {
520        /// The node.
521        at: NodePath,
522    },
523}
524
525/// The semantic tree of every window.
526#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
527pub struct SemanticTree {
528    pub(crate) nodes: Vec<Node>,
529    pub(crate) roots: Vec<NodeId>,
530    pub(crate) warnings: Vec<TreeWarning>,
531    pub(crate) texts: Vec<String>,
532}
533
534impl SemanticTree {
535    /// The node with this id, or `None` for an id from another tree that is out of range.
536    #[must_use]
537    pub fn get(&self, id: NodeId) -> Option<&Node> {
538        self.nodes.get(id.index())
539    }
540
541    /// One `Window` node per window.
542    #[must_use]
543    pub fn roots(&self) -> &[NodeId] {
544        &self.roots
545    }
546
547    /// Warnings from building the tree.
548    #[must_use]
549    pub fn warnings(&self) -> &[TreeWarning] {
550        &self.warnings
551    }
552
553    /// Every node, in operation order.
554    pub fn iter(&self) -> impl Iterator<Item = &Node> {
555        self.nodes.iter()
556    }
557
558    /// The number of nodes, ignored ones included.
559    #[must_use]
560    pub fn len(&self) -> usize {
561        self.nodes.len()
562    }
563
564    /// Whether the tree has no nodes.
565    #[must_use]
566    pub fn is_empty(&self) -> bool {
567        self.nodes.is_empty()
568    }
569
570    /// Every node below `id` in depth-first order, following `owns` into owned subtrees.
571    /// Each node appears once.
572    pub fn descendants(&self, id: NodeId) -> impl Iterator<Item = NodeId> + '_ {
573        let mut seen = vec![false; self.nodes.len()];
574        if let Some(flag) = seen.get_mut(id.index()) {
575            *flag = true;
576        }
577        let mut stack: Vec<NodeId> = self.next_level(id).rev().collect();
578        std::iter::from_fn(move || {
579            while let Some(next) = stack.pop() {
580                let Some(flag) = seen.get_mut(next.index()) else {
581                    continue;
582                };
583                if *flag {
584                    continue;
585                }
586                *flag = true;
587                stack.extend(self.next_level(next).rev());
588                return Some(next);
589            }
590            None
591        })
592    }
593
594    fn next_level(&self, id: NodeId) -> impl DoubleEndedIterator<Item = NodeId> + '_ {
595        let node = self.get(id);
596        let children = node.map(|n| n.children.as_slice()).unwrap_or_default();
597        let owns = node
598            .map(|n| n.relations.owns.as_slice())
599            .unwrap_or_default();
600        children.iter().chain(owns).copied()
601    }
602
603    /// The parents of `id`, nearest first.
604    pub fn ancestors(&self, id: NodeId) -> impl Iterator<Item = NodeId> + '_ {
605        let mut current = self.get(id).and_then(|n| n.parent);
606        std::iter::from_fn(move || {
607            let next = current?;
608            current = self.get(next).and_then(|n| n.parent);
609            Some(next)
610        })
611    }
612
613    /// The node's own text joined with its non-hidden descendants' text in tree order.
614    #[must_use]
615    pub fn text_content(&self, id: NodeId) -> &str {
616        self.texts.get(id.index()).map_or("", String::as_str)
617    }
618
619    /// The node at a path from this or another snapshot.
620    #[must_use]
621    pub fn find_path(&self, path: &NodePath) -> Option<NodeId> {
622        self.nodes.iter().find(|n| &n.path == path).map(|n| n.id)
623    }
624
625    /// The node at a path, as a node.
626    #[must_use]
627    pub fn node_at(&self, path: &NodePath) -> Option<&Node> {
628        self.find_path(path).and_then(|id| self.get(id))
629    }
630
631    /// The node recorded at a raw index path, or the deepest node whose raw path is a prefix
632    /// of it, which is the node that absorbed or merged that raw call.
633    #[must_use]
634    pub fn by_raw(&self, raw: &[u32]) -> Option<NodeId> {
635        self.nodes
636            .iter()
637            .filter(|n| raw.starts_with(&n.raw))
638            .max_by_key(|n| n.raw.len())
639            .map(|n| n.id)
640    }
641
642    /// The window's root node.
643    #[must_use]
644    pub fn window(&self, id: WindowId) -> Option<NodeId> {
645        self.roots
646            .iter()
647            .copied()
648            .find(|root| self.get(*root).is_some_and(|n| n.window == id))
649    }
650
651    /// Rewrites the number of every `WidgetId::Unique` through `renumber`. iced numbers unique
652    /// ids from one process-wide counter, so a trace renumbers them to compare across runs.
653    pub fn renumber_widget_ids(&mut self, mut renumber: impl FnMut(usize) -> usize) {
654        for node in &mut self.nodes {
655            if let Some(WidgetId::Unique(n)) = &mut node.widget_id {
656                *n = renumber(*n);
657            }
658        }
659    }
660}