icedwright-semantics 0.0.1

The icedwright semantic tree: inference from recorded widget operations, stable node paths, hit testing, diffs and YAML
Documentation
//! Hit testing and diffs between snapshots.

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 {
    /// The node drawn on top at `point`: the deepest node whose visible bounds contain it,
    /// from the highest layer down. Ignored generics count, because they still paint.
    #[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)
    }
}

/// A node present in both snapshots whose fields differ.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NodeChange {
    /// Its path, the same in both.
    pub path: NodePath,
    /// The fields that differ, by name.
    pub fields: Vec<Cow<'static, str>>,
}

/// What changed between two snapshots, keyed by node path. Ignored generics are left out.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct TreeDiff {
    /// Paths only in the later snapshot.
    pub added: Vec<NodePath>,
    /// Paths only in the earlier snapshot.
    pub removed: Vec<NodePath>,
    /// Paths in both whose nodes differ.
    pub changed: Vec<NodeChange>,
}

impl TreeDiff {
    /// Whether nothing changed.
    #[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()
}

/// Nodes added, removed and changed between two snapshots.
#[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
}