icedwright-semantics 0.0.2

The icedwright semantic tree: inference from recorded widget operations, stable node paths, hit testing, diffs and YAML
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
//! Turning draft nodes into a finished tree: ids and order, relations, derived states, text
//! content, names, ignored generics and paths. `infer`, `TreeBuilder` and `yaml::read` all end
//! here, so their trees follow the same rules.

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};

/// Relation keys an annotation named, resolved once every node exists.
#[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>,
}

/// A warning about one node, given a path once paths exist.
#[derive(Debug, Clone)]
pub(crate) enum DraftWarning {
    InvalidLevel,
    InvalidTestId(String),
    UnknownRole,
}

/// A node before it has an id.
#[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(),
        }
    }
}

/// Whether the finishing pass derives states and names, or keeps what the drafts say.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Mode {
    Derive,
    Keep,
}

/// Whether a role takes its accessible name from the text of its descendants.
#[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);
    }
}

/// Whether walking up from `from` through parents and owners meets `target`.
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()
}

/// The node a path is written under: the owner of an owned node, else the nearest ancestor
/// that is not ignored.
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();
    }
}