use std::borrow::Cow;
use std::collections::HashMap;
use icedwright_protocol::WindowId;
use icedwright_types::Point;
use serde::{Deserialize, Serialize};
use crate::path::NodePath;
use crate::tree::{Node, NodeId, SemanticTree};
impl SemanticTree {
#[must_use]
pub fn hit_test(&self, window: WindowId, point: Point) -> Option<NodeId> {
self.nodes
.iter()
.filter(|n| n.window == window && !n.states.hidden)
.filter(|n| n.visible_bounds.is_some_and(|b| b.contains(point)))
.max_by_key(|n| (n.layer, n.order))
.map(|n| n.id)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NodeChange {
pub path: NodePath,
pub fields: Vec<Cow<'static, str>>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct TreeDiff {
pub added: Vec<NodePath>,
pub removed: Vec<NodePath>,
pub changed: Vec<NodeChange>,
}
impl TreeDiff {
#[must_use]
pub fn is_empty(&self) -> bool {
self.added.is_empty() && self.removed.is_empty() && self.changed.is_empty()
}
}
fn changed_fields(a: &Node, b: &Node) -> Vec<Cow<'static, str>> {
let checks: [(&'static str, bool); 10] = [
("description", a.description != b.description),
("value", a.value != b.value),
("placeholder", a.placeholder != b.placeholder),
("tooltip", a.tooltip != b.tooltip),
("states", a.states.known().ne(b.states.known())),
("set", a.set != b.set),
("props", a.props != b.props),
("bounds", a.bounds != b.bounds),
("visible_bounds", a.visible_bounds != b.visible_bounds),
("layer", a.layer != b.layer),
];
checks
.into_iter()
.filter(|(_, differs)| *differs)
.map(|(name, _)| Cow::Borrowed(name))
.collect()
}
#[must_use]
pub fn diff(before: &SemanticTree, after: &SemanticTree) -> TreeDiff {
let index = |tree: &'_ SemanticTree| {
let mut map: HashMap<NodePath, NodeId> = HashMap::new();
for node in tree.iter().filter(|n| !n.ignored) {
map.entry(node.path.clone()).or_insert(node.id);
}
map
};
let old = index(before);
let new = index(after);
let mut result = TreeDiff::default();
for node in before.iter().filter(|n| !n.ignored) {
if old.get(&node.path) != Some(&node.id) {
continue;
}
let Some(other) = new.get(&node.path).and_then(|id| after.get(*id)) else {
result.removed.push(node.path.clone());
continue;
};
let fields = changed_fields(node, other);
if !fields.is_empty() {
result.changed.push(NodeChange {
path: node.path.clone(),
fields,
});
}
}
for node in after.iter().filter(|n| !n.ignored) {
if new.get(&node.path) == Some(&node.id) && !old.contains_key(&node.path) {
result.added.push(node.path.clone());
}
}
result
}