1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
15#[serde(transparent)]
16pub struct NodeId(pub(crate) u32);
17
18impl NodeId {
19 #[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
32pub type SemanticNode = Node;
34
35#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
37#[serde(rename_all = "snake_case")]
38pub enum Value {
39 Text(String),
41 Number {
43 now: f64,
45 min: Option<f64>,
47 max: Option<f64>,
49 step: Option<f64>,
51 },
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
56#[serde(rename_all = "snake_case")]
57pub enum StateSource {
58 Annotation,
60 Component,
62 Inferred,
64 Derived,
66}
67
68#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
70pub struct States {
71 pub disabled: Option<bool>,
73 pub readonly: Option<bool>,
75 pub checked: Option<Checked>,
77 pub pressed: Option<bool>,
79 pub expanded: Option<bool>,
81 pub selected: Option<bool>,
83 pub focused: Option<bool>,
85 pub current: Option<bool>,
87 pub busy: Option<bool>,
89 pub required: Option<bool>,
91 pub invalid: Option<bool>,
93 pub multiline: Option<bool>,
95 pub multiselectable: Option<bool>,
97 pub modal: bool,
99 pub focusable: bool,
101 pub hidden: bool,
103 pub offscreen: bool,
105 pub inert: bool,
107 sources: BTreeMap<StateName, StateSource>,
108}
109
110impl States {
111 #[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 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 #[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 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#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
189pub struct Relations {
190 pub labelled_by: Vec<NodeId>,
192 pub described_by: Vec<NodeId>,
194 pub controls: Vec<NodeId>,
196 pub owns: Vec<NodeId>,
198 pub owner: Option<NodeId>,
200}
201
202impl Relations {
203 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
216pub struct SetInfo {
217 pub level: Option<u16>,
219 pub position: Option<u32>,
221 pub size: Option<u32>,
223}
224
225#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
227pub struct SourceSet {
228 pub annotation: bool,
230 pub component: bool,
232 pub inferred: bool,
234 pub visible_text: bool,
237}
238
239#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
241#[serde(rename_all = "snake_case")]
242#[non_exhaustive]
243pub enum OperationKind {
244 Container,
246 Scrollable,
248 Focusable,
250 TextInput,
252 Text,
254 Custom,
256 Window,
258}
259
260impl OperationKind {
261 #[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#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
278#[serde(rename_all = "snake_case")]
279pub enum Kind {
280 Inferred(OperationKind),
282 Annotated(Cow<'static, str>),
284 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
299#[serde(rename_all = "snake_case")]
300pub enum NameSource {
301 #[default]
303 None,
304 Annotation,
306 LabelledBy,
308 LabelFor,
310 Content,
312 Tooltip,
314 Placeholder,
316 Text,
318}
319
320#[derive(
322 Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize,
323)]
324#[serde(rename_all = "snake_case")]
325pub enum Layer {
326 #[default]
328 Base,
329 Overlay(u16),
331}
332
333#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
335pub struct Scroll {
336 pub content_bounds: Rect,
338 pub translation: Vector,
340}
341
342#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
344pub struct ScrollAncestor {
345 pub ordinal: u32,
347 pub bounds: Rect,
349 pub content_bounds: Rect,
351 pub translation: Vector,
353}
354
355#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
357pub struct TextGeometry {
358 pub carets: Vec<(usize, Point)>,
360}
361
362impl TextGeometry {
363 #[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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
376pub struct Node {
377 pub id: NodeId,
379 pub role: Role,
381 pub name: Option<String>,
383 pub name_source: NameSource,
385 pub description: Option<String>,
387 pub value: Option<Value>,
389 pub placeholder: Option<String>,
391 pub tooltip: Option<String>,
393 pub states: States,
395 pub relations: Relations,
397 pub set: SetInfo,
399 pub test_id: Option<String>,
401 pub widget_id: Option<WidgetId>,
403 pub kind: Kind,
405 pub sources: SourceSet,
407 pub props: BTreeMap<String, String>,
409 pub text_size: Option<f32>,
411 pub text_geometry: Option<TextGeometry>,
413 pub cursor_seen: Option<CursorSeen>,
415 pub bounds: Rect,
417 pub visible_bounds: Option<Rect>,
419 pub scroll: Option<Scroll>,
421 pub scroll_ancestors: Vec<ScrollAncestor>,
423 pub focusable_ordinal: Option<u32>,
425 pub layer: Layer,
427 pub window: WindowId,
429 pub order: u32,
431 pub parent: Option<NodeId>,
433 pub children: Vec<NodeId>,
435 pub raw: Vec<u32>,
437 pub ignored: bool,
439 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
484#[serde(rename_all = "snake_case")]
485#[non_exhaustive]
486pub enum TreeWarning {
487 UnresolvedKey {
489 key: String,
491 at: NodePath,
493 },
494 DuplicateKey {
496 key: String,
498 at: NodePath,
500 },
501 OwnsCycle {
503 at: NodePath,
505 },
506 InvalidLevel {
508 at: NodePath,
510 },
511 InvalidTestId {
513 at: NodePath,
515 id: String,
517 },
518 UnknownRole {
520 at: NodePath,
522 },
523}
524
525#[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 #[must_use]
537 pub fn get(&self, id: NodeId) -> Option<&Node> {
538 self.nodes.get(id.index())
539 }
540
541 #[must_use]
543 pub fn roots(&self) -> &[NodeId] {
544 &self.roots
545 }
546
547 #[must_use]
549 pub fn warnings(&self) -> &[TreeWarning] {
550 &self.warnings
551 }
552
553 pub fn iter(&self) -> impl Iterator<Item = &Node> {
555 self.nodes.iter()
556 }
557
558 #[must_use]
560 pub fn len(&self) -> usize {
561 self.nodes.len()
562 }
563
564 #[must_use]
566 pub fn is_empty(&self) -> bool {
567 self.nodes.is_empty()
568 }
569
570 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 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 #[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 #[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 #[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 #[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 #[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 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}