use std::collections::HashMap;
use icedwright_protocol::RawKey;
use icedwright_types::{Role, StateName, StateValue};
use crate::path::{NodePath, Segment};
use crate::tree::{NameSource, Node, NodeId, SemanticTree, StateSource, TreeWarning};
#[derive(Debug, Clone, Default)]
pub(crate) struct DraftKeys {
pub(crate) key: Option<RawKey>,
pub(crate) labelled_by: Vec<RawKey>,
pub(crate) label_for: Vec<RawKey>,
pub(crate) described_by: Vec<RawKey>,
pub(crate) controls: Vec<RawKey>,
pub(crate) owns: Vec<RawKey>,
}
#[derive(Debug, Clone)]
pub(crate) enum DraftWarning {
InvalidLevel,
InvalidTestId(String),
UnknownRole,
}
#[derive(Debug, Clone)]
pub(crate) struct Draft {
pub(crate) node: Node,
pub(crate) own_text: Option<String>,
pub(crate) keys: DraftKeys,
pub(crate) warnings: Vec<DraftWarning>,
pub(crate) children: Vec<Draft>,
}
impl Draft {
pub(crate) fn new(node: Node) -> Self {
Self {
node,
own_text: None,
keys: DraftKeys::default(),
warnings: Vec::new(),
children: Vec::new(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Mode {
Derive,
Keep,
}
#[must_use]
pub const fn named_from_content(role: Role) -> bool {
matches!(
role,
Role::Button
| Role::ToggleButton
| Role::Link
| Role::Tab
| Role::TreeItem
| Role::ListItem
| Role::ListOption
| Role::MenuItem
| Role::MenuItemCheckBox
| Role::MenuItemRadio
| Role::CheckBox
| Role::RadioButton
| Role::Switch
| Role::Cell
| Role::ColumnHeader
| Role::RowHeader
| Role::Heading
| Role::Tooltip
)
}
const fn is_text_role(role: Role) -> bool {
matches!(role, Role::Text | Role::Paragraph)
}
fn key_text(key: &RawKey) -> String {
match key {
RawKey::Name(name) => name.clone(),
RawKey::Unique(n) => format!("#{n}"),
}
}
struct Flat {
nodes: Vec<Node>,
own_texts: Vec<Option<String>>,
keys: Vec<DraftKeys>,
warnings: Vec<(NodeId, DraftWarning)>,
roots: Vec<NodeId>,
}
fn flatten(windows: Vec<Draft>) -> Flat {
let mut flat = Flat {
nodes: Vec::new(),
own_texts: Vec::new(),
keys: Vec::new(),
warnings: Vec::new(),
roots: Vec::new(),
};
for window in windows {
let id = push(&mut flat, window, None);
flat.roots.push(id);
}
flat
}
fn push(flat: &mut Flat, draft: Draft, parent: Option<NodeId>) -> NodeId {
let id = NodeId(u32::try_from(flat.nodes.len()).unwrap_or(u32::MAX));
let Draft {
mut node,
own_text,
keys,
warnings,
children,
} = draft;
node.id = id;
node.order = id.0;
node.parent = parent;
node.children.clear();
flat.nodes.push(node);
flat.own_texts.push(own_text);
flat.keys.push(keys);
flat.warnings.extend(warnings.into_iter().map(|w| (id, w)));
for child in children {
let child_id = push(flat, child, Some(id));
flat.nodes[id.index()].children.push(child_id);
}
id
}
enum PendingWarning {
Draft(DraftWarning),
UnresolvedKey(String),
DuplicateKey(String),
OwnsCycle,
}
pub(crate) fn finish(windows: Vec<Draft>, mode: Mode) -> SemanticTree {
let Flat {
nodes,
own_texts,
keys,
warnings: draft_warnings,
roots,
} = flatten(windows);
let mut tree = SemanticTree {
nodes,
roots,
warnings: Vec::new(),
texts: Vec::new(),
};
let mut pending: Vec<(NodeId, PendingWarning)> = draft_warnings
.into_iter()
.map(|(id, w)| (id, PendingWarning::Draft(w)))
.collect();
let mut label_for: Vec<Vec<NodeId>> = vec![Vec::new(); tree.nodes.len()];
if mode == Mode::Derive {
resolve_keys(&mut tree, &keys, &mut label_for, &mut pending);
derive_hidden(&mut tree);
derive_offscreen(&mut tree);
derive_inert(&mut tree);
}
compute_texts(&mut tree, &own_texts);
if mode == Mode::Derive {
compute_names(&mut tree, &label_for);
}
for node in &mut tree.nodes {
node.ignored = is_ignorable(node);
}
compute_paths(&mut tree);
tree.warnings = pending
.into_iter()
.map(|(id, warning)| to_tree_warning(&tree, id, warning))
.collect();
tree
}
fn to_tree_warning(tree: &SemanticTree, id: NodeId, warning: PendingWarning) -> TreeWarning {
let at = tree.get(id).map(|n| n.path.clone()).unwrap_or_default();
match warning {
PendingWarning::Draft(DraftWarning::InvalidLevel) => TreeWarning::InvalidLevel { at },
PendingWarning::Draft(DraftWarning::InvalidTestId(id)) => {
TreeWarning::InvalidTestId { at, id }
}
PendingWarning::Draft(DraftWarning::UnknownRole) => TreeWarning::UnknownRole { at },
PendingWarning::UnresolvedKey(key) => TreeWarning::UnresolvedKey { key, at },
PendingWarning::DuplicateKey(key) => TreeWarning::DuplicateKey { key, at },
PendingWarning::OwnsCycle => TreeWarning::OwnsCycle { at },
}
}
fn resolve_keys(
tree: &mut SemanticTree,
keys: &[DraftKeys],
label_for: &mut [Vec<NodeId>],
pending: &mut Vec<(NodeId, PendingWarning)>,
) {
let mut by_key: HashMap<&RawKey, NodeId> = HashMap::new();
for (index, draft) in keys.iter().enumerate() {
let Some(key) = &draft.key else { continue };
let id = tree.nodes[index].id;
if by_key.contains_key(key) {
pending.push((id, PendingWarning::DuplicateKey(key_text(key))));
continue;
}
by_key.insert(key, id);
}
let lookup = |id: NodeId, wanted: &[RawKey], pending: &mut Vec<(NodeId, PendingWarning)>| {
wanted
.iter()
.filter_map(|key| {
let found = by_key.get(key).copied();
if found.is_none() {
pending.push((id, PendingWarning::UnresolvedKey(key_text(key))));
}
found
})
.collect::<Vec<_>>()
};
let mut owns_edges = Vec::new();
for (index, draft) in keys.iter().enumerate() {
let id = tree.nodes[index].id;
let labelled_by = lookup(id, &draft.labelled_by, pending);
let described_by = lookup(id, &draft.described_by, pending);
let controls = lookup(id, &draft.controls, pending);
for target in lookup(id, &draft.label_for, pending) {
label_for[target.index()].push(id);
}
owns_edges.extend(
lookup(id, &draft.owns, pending)
.into_iter()
.map(|t| (id, t)),
);
let relations = &mut tree.nodes[index].relations;
relations.labelled_by = labelled_by;
relations.described_by = described_by;
relations.controls = controls;
}
for (owner, owned) in owns_edges {
if tree.nodes[owned.index()].relations.owner.is_some() || reaches(tree, owner, owned) {
pending.push((owner, PendingWarning::OwnsCycle));
continue;
}
tree.nodes[owner.index()].relations.owns.push(owned);
tree.nodes[owned.index()].relations.owner = Some(owner);
}
}
fn reaches(tree: &SemanticTree, from: NodeId, target: NodeId) -> bool {
let mut current = Some(from);
let mut steps = 0;
while let Some(id) = current {
if id == target {
return true;
}
steps += 1;
if steps > tree.nodes.len() {
return true;
}
let node = &tree.nodes[id.index()];
current = node.relations.owner.or(node.parent);
}
false
}
fn derive_hidden(tree: &mut SemanticTree) {
let mut blocks = vec![false; tree.nodes.len()];
for index in 0..tree.nodes.len() {
let node = &tree.nodes[index];
let is_window = node.role == Role::Window && node.parent.is_none();
let zero = !is_window && node.bounds.area() <= 0.0;
let explicit = node.states.hidden;
let inherited = node.parent.is_some_and(|p| blocks[p.index()]);
blocks[index] = explicit || inherited || (zero && node.role != Role::Generic);
let hidden = explicit || zero || inherited;
let source = if explicit {
node.states.source(StateName::Hidden)
} else {
None
};
let node = &mut tree.nodes[index];
node.states.set(
StateName::Hidden,
StateValue::Bool(hidden),
source.unwrap_or(StateSource::Derived),
);
}
}
fn derive_offscreen(tree: &mut SemanticTree) {
for node in &mut tree.nodes {
let offscreen = node.bounds.area() > 0.0 && node.visible_bounds.is_none();
node.states.set(
StateName::Offscreen,
StateValue::Bool(offscreen),
StateSource::Derived,
);
}
}
fn derive_inert(tree: &mut SemanticTree) {
for root in tree.roots.clone() {
let window: Vec<NodeId> = std::iter::once(root)
.chain(tree.descendants(root))
.collect();
let topmost = window
.iter()
.filter_map(|id| tree.get(*id))
.filter(|n| n.states.modal && !n.states.hidden)
.max_by_key(|n| (n.layer, n.order))
.map(|n| (n.id, n.layer));
let Some((modal, layer)) = topmost else {
continue;
};
let mut live = vec![false; tree.nodes.len()];
live[modal.index()] = true;
for id in tree.descendants(modal).chain(tree.ancestors(modal)) {
live[id.index()] = true;
}
for id in window {
let node = &mut tree.nodes[id.index()];
let above = node.layer > layer;
let inert = !live[id.index()] && !above;
node.states.set(
StateName::Inert,
StateValue::Bool(inert),
StateSource::Derived,
);
}
}
}
fn compute_texts(tree: &mut SemanticTree, own_texts: &[Option<String>]) {
let mut texts = vec![String::new(); tree.nodes.len()];
for index in (0..tree.nodes.len()).rev() {
let node = &tree.nodes[index];
let mut parts: Vec<&str> = Vec::new();
if let Some(own) = own_texts.get(index).and_then(Option::as_deref) {
parts.push(own);
}
for child in &node.children {
let child_node = &tree.nodes[child.index()];
if child_node.states.hidden {
continue;
}
parts.push(texts[child.index()].as_str());
}
let joined = parts
.into_iter()
.map(str::trim)
.filter(|p| !p.is_empty())
.collect::<Vec<_>>()
.join(" ");
texts[index] = joined;
}
tree.texts = texts;
}
fn label_text(tree: &SemanticTree, id: NodeId) -> String {
let text = tree.text_content(id);
if !text.is_empty() {
return text.to_owned();
}
tree.get(id)
.filter(|n| n.name_source == NameSource::Annotation)
.and_then(|n| n.name.clone())
.unwrap_or_default()
}
fn joined_labels(tree: &SemanticTree, ids: &[NodeId]) -> Option<String> {
let joined = ids
.iter()
.map(|id| label_text(tree, *id))
.filter(|t| !t.is_empty())
.collect::<Vec<_>>()
.join(" ");
(!joined.is_empty()).then_some(joined)
}
fn compute_names(tree: &mut SemanticTree, label_for: &[Vec<NodeId>]) {
for (index, labels) in label_for.iter().enumerate() {
let node = &tree.nodes[index];
let id = node.id;
let role = node.role;
let text = tree.text_content(id);
let name = if node.name.is_some() {
None
} else if let Some(name) = joined_labels(tree, &node.relations.labelled_by) {
Some((name, NameSource::LabelledBy))
} else if let Some(name) = joined_labels(tree, labels) {
Some((name, NameSource::LabelFor))
} else if is_text_role(role) && !text.is_empty() {
Some((text.to_owned(), NameSource::Text))
} else if named_from_content(role) && !text.is_empty() {
Some((text.to_owned(), NameSource::Content))
} else if let Some(tooltip) = &node.tooltip {
Some((tooltip.clone(), NameSource::Tooltip))
} else if role
.capabilities()
.contains(icedwright_types::role::Capabilities::EDITABLE)
{
node.placeholder
.clone()
.map(|placeholder| (placeholder, NameSource::Placeholder))
} else {
None
};
let description = if node.description.is_some() {
None
} else {
joined_labels(tree, &node.relations.described_by)
};
let node = &mut tree.nodes[index];
if let Some((name, source)) = name {
node.name = Some(name);
node.name_source = source;
}
if let Some(description) = description {
node.description = Some(description);
} else if node.description.is_none() && node.name_source != NameSource::Tooltip {
node.description = node.tooltip.clone();
}
}
}
fn is_ignorable(node: &Node) -> bool {
node.role == Role::Generic
&& node.parent.is_some()
&& node.widget_id.is_none()
&& node.test_id.is_none()
&& node.name.is_none()
&& node.relations.is_empty()
}
pub(crate) fn path_parent(tree: &SemanticTree, id: NodeId) -> Option<NodeId> {
let node = tree.get(id)?;
if let Some(owner) = node.relations.owner {
return Some(owner);
}
let mut current = node.parent;
while let Some(parent) = current {
let parent_node = tree.get(parent)?;
if !parent_node.ignored {
return Some(parent);
}
if let Some(owner) = parent_node.relations.owner {
return Some(owner);
}
current = parent_node.parent;
}
None
}
fn segment_of(node: &Node) -> Segment {
match &node.test_id {
Some(id) => Segment::TestId {
id: id.clone(),
index: 0,
},
None => Segment::Role {
role: node.role,
name: node.name.clone(),
index: 0,
},
}
}
fn compute_paths(tree: &mut SemanticTree) {
let count = tree.nodes.len();
let parents: Vec<Option<NodeId>> = (0..count)
.map(|i| path_parent(tree, tree.nodes[i].id))
.collect();
let mut segments: Vec<Segment> = tree.nodes.iter().map(segment_of).collect();
let mut seen: HashMap<Option<NodeId>, Vec<usize>> = HashMap::new();
for index in 0..count {
if tree.nodes[index].ignored {
continue;
}
let siblings = seen.entry(parents[index]).or_default();
let earlier = siblings
.iter()
.filter(|other| segments[**other].same_key(&segments[index]))
.count();
segments[index].set_index(u32::try_from(earlier).unwrap_or(u32::MAX));
siblings.push(index);
}
let mut paths: Vec<Option<NodePath>> = vec![None; count];
for index in 0..count {
let mut chain = vec![index];
let mut current = parents[index];
while let Some(parent) = current {
if paths[parent.index()].is_some() || chain.len() > count {
break;
}
chain.push(parent.index());
current = parents[parent.index()];
}
let mut base = current
.and_then(|p| paths[p.index()].clone())
.unwrap_or_default();
for link in chain.into_iter().rev() {
if paths[link].is_none() {
let path = if tree.nodes[link].ignored {
base.clone()
} else {
base.child(segments[link].clone())
};
paths[link] = Some(path);
}
base = paths[link].clone().unwrap_or_default();
}
}
for (node, path) in tree.nodes.iter_mut().zip(paths) {
node.path = path.unwrap_or_default();
}
}