Skip to main content

icedwright_semantics/
query.rs

1//! Hit testing and diffs between snapshots.
2
3use 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    /// The node drawn on top at `point`: the deepest node whose visible bounds contain it,
15    /// from the highest layer down. Ignored generics count, because they still paint.
16    #[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/// A node present in both snapshots whose fields differ.
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29pub struct NodeChange {
30    /// Its path, the same in both.
31    pub path: NodePath,
32    /// The fields that differ, by name.
33    pub fields: Vec<Cow<'static, str>>,
34}
35
36/// What changed between two snapshots, keyed by node path. Ignored generics are left out.
37#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
38pub struct TreeDiff {
39    /// Paths only in the later snapshot.
40    pub added: Vec<NodePath>,
41    /// Paths only in the earlier snapshot.
42    pub removed: Vec<NodePath>,
43    /// Paths in both whose nodes differ.
44    pub changed: Vec<NodeChange>,
45}
46
47impl TreeDiff {
48    /// Whether nothing changed.
49    #[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/// Nodes added, removed and changed between two snapshots.
76#[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}