icedwright_semantics/
query.rs1use std::borrow::Cow;
4use std::collections::HashMap;
5
6use icedwright_protocol::WindowId;
7use icedwright_types::Point;
8use serde::{Deserialize, Serialize};
9
10use crate::path::NodePath;
11use crate::tree::{Node, NodeId, SemanticTree};
12
13impl SemanticTree {
14 #[must_use]
17 pub fn hit_test(&self, window: WindowId, point: Point) -> Option<NodeId> {
18 self.nodes
19 .iter()
20 .filter(|n| n.window == window && !n.states.hidden)
21 .filter(|n| n.visible_bounds.is_some_and(|b| b.contains(point)))
22 .max_by_key(|n| (n.layer, n.order))
23 .map(|n| n.id)
24 }
25}
26
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29pub struct NodeChange {
30 pub path: NodePath,
32 pub fields: Vec<Cow<'static, str>>,
34}
35
36#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
38pub struct TreeDiff {
39 pub added: Vec<NodePath>,
41 pub removed: Vec<NodePath>,
43 pub changed: Vec<NodeChange>,
45}
46
47impl TreeDiff {
48 #[must_use]
50 pub fn is_empty(&self) -> bool {
51 self.added.is_empty() && self.removed.is_empty() && self.changed.is_empty()
52 }
53}
54
55fn changed_fields(a: &Node, b: &Node) -> Vec<Cow<'static, str>> {
56 let checks: [(&'static str, bool); 10] = [
57 ("description", a.description != b.description),
58 ("value", a.value != b.value),
59 ("placeholder", a.placeholder != b.placeholder),
60 ("tooltip", a.tooltip != b.tooltip),
61 ("states", a.states.known().ne(b.states.known())),
62 ("set", a.set != b.set),
63 ("props", a.props != b.props),
64 ("bounds", a.bounds != b.bounds),
65 ("visible_bounds", a.visible_bounds != b.visible_bounds),
66 ("layer", a.layer != b.layer),
67 ];
68 checks
69 .into_iter()
70 .filter(|(_, differs)| *differs)
71 .map(|(name, _)| Cow::Borrowed(name))
72 .collect()
73}
74
75#[must_use]
77pub fn diff(before: &SemanticTree, after: &SemanticTree) -> TreeDiff {
78 let index = |tree: &'_ SemanticTree| {
79 let mut map: HashMap<NodePath, NodeId> = HashMap::new();
80 for node in tree.iter().filter(|n| !n.ignored) {
81 map.entry(node.path.clone()).or_insert(node.id);
82 }
83 map
84 };
85 let old = index(before);
86 let new = index(after);
87 let mut result = TreeDiff::default();
88 for node in before.iter().filter(|n| !n.ignored) {
89 if old.get(&node.path) != Some(&node.id) {
90 continue;
91 }
92 let Some(other) = new.get(&node.path).and_then(|id| after.get(*id)) else {
93 result.removed.push(node.path.clone());
94 continue;
95 };
96 let fields = changed_fields(node, other);
97 if !fields.is_empty() {
98 result.changed.push(NodeChange {
99 path: node.path.clone(),
100 fields,
101 });
102 }
103 }
104 for node in after.iter().filter(|n| !n.ignored) {
105 if new.get(&node.path) == Some(&node.id) && !old.contains_key(&node.path) {
106 result.added.push(node.path.clone());
107 }
108 }
109 result
110}