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;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct NodeId(pub(crate) u32);
impl NodeId {
#[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)
}
}
pub type SemanticNode = Node;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Value {
Text(String),
Number {
now: f64,
min: Option<f64>,
max: Option<f64>,
step: Option<f64>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StateSource {
Annotation,
Component,
Inferred,
Derived,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct States {
pub disabled: Option<bool>,
pub readonly: Option<bool>,
pub checked: Option<Checked>,
pub pressed: Option<bool>,
pub expanded: Option<bool>,
pub selected: Option<bool>,
pub focused: Option<bool>,
pub current: Option<bool>,
pub busy: Option<bool>,
pub required: Option<bool>,
pub invalid: Option<bool>,
pub multiline: Option<bool>,
pub multiselectable: Option<bool>,
pub modal: bool,
pub focusable: bool,
pub hidden: bool,
pub offscreen: bool,
pub inert: bool,
sources: BTreeMap<StateName, StateSource>,
}
impl States {
#[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,
}
}
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);
}
#[must_use]
pub fn source(&self, state: StateName) -> Option<StateSource> {
self.get(state)?;
Some(
self.sources
.get(&state)
.copied()
.unwrap_or(StateSource::Derived),
)
}
pub fn known(&self) -> impl Iterator<Item = (StateName, StateValue)> + '_ {
StateName::ALL
.iter()
.filter_map(|state| self.get(*state).map(|value| (*state, value)))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Relations {
pub labelled_by: Vec<NodeId>,
pub described_by: Vec<NodeId>,
pub controls: Vec<NodeId>,
pub owns: Vec<NodeId>,
pub owner: Option<NodeId>,
}
impl Relations {
#[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()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct SetInfo {
pub level: Option<u16>,
pub position: Option<u32>,
pub size: Option<u32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct SourceSet {
pub annotation: bool,
pub component: bool,
pub inferred: bool,
pub visible_text: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum OperationKind {
Container,
Scrollable,
Focusable,
TextInput,
Text,
Custom,
Window,
}
impl OperationKind {
#[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",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Kind {
Inferred(OperationKind),
Annotated(Cow<'static, str>),
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),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NameSource {
#[default]
None,
Annotation,
LabelledBy,
LabelFor,
Content,
Tooltip,
Placeholder,
Text,
}
#[derive(
Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize,
)]
#[serde(rename_all = "snake_case")]
pub enum Layer {
#[default]
Base,
Overlay(u16),
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct Scroll {
pub content_bounds: Rect,
pub translation: Vector,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ScrollAncestor {
pub ordinal: u32,
pub bounds: Rect,
pub content_bounds: Rect,
pub translation: Vector,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct TextGeometry {
pub carets: Vec<(usize, Point)>,
}
impl TextGeometry {
#[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)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Node {
pub id: NodeId,
pub role: Role,
pub name: Option<String>,
pub name_source: NameSource,
pub description: Option<String>,
pub value: Option<Value>,
pub placeholder: Option<String>,
pub tooltip: Option<String>,
pub states: States,
pub relations: Relations,
pub set: SetInfo,
pub test_id: Option<String>,
pub widget_id: Option<WidgetId>,
pub kind: Kind,
pub sources: SourceSet,
pub props: BTreeMap<String, String>,
pub text_size: Option<f32>,
pub text_geometry: Option<TextGeometry>,
pub cursor_seen: Option<CursorSeen>,
pub bounds: Rect,
pub visible_bounds: Option<Rect>,
pub scroll: Option<Scroll>,
pub scroll_ancestors: Vec<ScrollAncestor>,
pub focusable_ordinal: Option<u32>,
pub layer: Layer,
pub window: WindowId,
pub order: u32,
pub parent: Option<NodeId>,
pub children: Vec<NodeId>,
pub raw: Vec<u32>,
pub ignored: bool,
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(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum TreeWarning {
UnresolvedKey {
key: String,
at: NodePath,
},
DuplicateKey {
key: String,
at: NodePath,
},
OwnsCycle {
at: NodePath,
},
InvalidLevel {
at: NodePath,
},
InvalidTestId {
at: NodePath,
id: String,
},
UnknownRole {
at: NodePath,
},
}
#[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 {
#[must_use]
pub fn get(&self, id: NodeId) -> Option<&Node> {
self.nodes.get(id.index())
}
#[must_use]
pub fn roots(&self) -> &[NodeId] {
&self.roots
}
#[must_use]
pub fn warnings(&self) -> &[TreeWarning] {
&self.warnings
}
pub fn iter(&self) -> impl Iterator<Item = &Node> {
self.nodes.iter()
}
#[must_use]
pub fn len(&self) -> usize {
self.nodes.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.nodes.is_empty()
}
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()
}
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)
})
}
#[must_use]
pub fn text_content(&self, id: NodeId) -> &str {
self.texts.get(id.index()).map_or("", String::as_str)
}
#[must_use]
pub fn find_path(&self, path: &NodePath) -> Option<NodeId> {
self.nodes.iter().find(|n| &n.path == path).map(|n| n.id)
}
#[must_use]
pub fn node_at(&self, path: &NodePath) -> Option<&Node> {
self.find_path(path).and_then(|id| self.get(id))
}
#[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)
}
#[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))
}
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);
}
}
}
}