1use std::collections::HashMap;
6
7use icedwright_protocol::RawKey;
8use icedwright_types::{Role, StateName, StateValue};
9
10use crate::path::{NodePath, Segment};
11use crate::tree::{NameSource, Node, NodeId, SemanticTree, StateSource, TreeWarning};
12
13#[derive(Debug, Clone, Default)]
15pub(crate) struct DraftKeys {
16 pub(crate) key: Option<RawKey>,
17 pub(crate) labelled_by: Vec<RawKey>,
18 pub(crate) label_for: Vec<RawKey>,
19 pub(crate) described_by: Vec<RawKey>,
20 pub(crate) controls: Vec<RawKey>,
21 pub(crate) owns: Vec<RawKey>,
22}
23
24#[derive(Debug, Clone)]
26pub(crate) enum DraftWarning {
27 InvalidLevel,
28 InvalidTestId(String),
29 UnknownRole,
30}
31
32#[derive(Debug, Clone)]
34pub(crate) struct Draft {
35 pub(crate) node: Node,
36 pub(crate) own_text: Option<String>,
37 pub(crate) keys: DraftKeys,
38 pub(crate) warnings: Vec<DraftWarning>,
39 pub(crate) children: Vec<Draft>,
40}
41
42impl Draft {
43 pub(crate) fn new(node: Node) -> Self {
44 Self {
45 node,
46 own_text: None,
47 keys: DraftKeys::default(),
48 warnings: Vec::new(),
49 children: Vec::new(),
50 }
51 }
52}
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub(crate) enum Mode {
57 Derive,
58 Keep,
59}
60
61#[must_use]
63pub const fn named_from_content(role: Role) -> bool {
64 matches!(
65 role,
66 Role::Button
67 | Role::ToggleButton
68 | Role::Link
69 | Role::Tab
70 | Role::TreeItem
71 | Role::ListItem
72 | Role::ListOption
73 | Role::MenuItem
74 | Role::MenuItemCheckBox
75 | Role::MenuItemRadio
76 | Role::CheckBox
77 | Role::RadioButton
78 | Role::Switch
79 | Role::Cell
80 | Role::ColumnHeader
81 | Role::RowHeader
82 | Role::Heading
83 | Role::Tooltip
84 )
85}
86
87const fn is_text_role(role: Role) -> bool {
88 matches!(role, Role::Text | Role::Paragraph)
89}
90
91fn key_text(key: &RawKey) -> String {
92 match key {
93 RawKey::Name(name) => name.clone(),
94 RawKey::Unique(n) => format!("#{n}"),
95 }
96}
97
98struct Flat {
99 nodes: Vec<Node>,
100 own_texts: Vec<Option<String>>,
101 keys: Vec<DraftKeys>,
102 warnings: Vec<(NodeId, DraftWarning)>,
103 roots: Vec<NodeId>,
104}
105
106fn flatten(windows: Vec<Draft>) -> Flat {
107 let mut flat = Flat {
108 nodes: Vec::new(),
109 own_texts: Vec::new(),
110 keys: Vec::new(),
111 warnings: Vec::new(),
112 roots: Vec::new(),
113 };
114 for window in windows {
115 let id = push(&mut flat, window, None);
116 flat.roots.push(id);
117 }
118 flat
119}
120
121fn push(flat: &mut Flat, draft: Draft, parent: Option<NodeId>) -> NodeId {
122 let id = NodeId(u32::try_from(flat.nodes.len()).unwrap_or(u32::MAX));
123 let Draft {
124 mut node,
125 own_text,
126 keys,
127 warnings,
128 children,
129 } = draft;
130 node.id = id;
131 node.order = id.0;
132 node.parent = parent;
133 node.children.clear();
134 flat.nodes.push(node);
135 flat.own_texts.push(own_text);
136 flat.keys.push(keys);
137 flat.warnings.extend(warnings.into_iter().map(|w| (id, w)));
138 for child in children {
139 let child_id = push(flat, child, Some(id));
140 flat.nodes[id.index()].children.push(child_id);
141 }
142 id
143}
144
145enum PendingWarning {
146 Draft(DraftWarning),
147 UnresolvedKey(String),
148 DuplicateKey(String),
149 OwnsCycle,
150}
151
152pub(crate) fn finish(windows: Vec<Draft>, mode: Mode) -> SemanticTree {
153 let Flat {
154 nodes,
155 own_texts,
156 keys,
157 warnings: draft_warnings,
158 roots,
159 } = flatten(windows);
160 let mut tree = SemanticTree {
161 nodes,
162 roots,
163 warnings: Vec::new(),
164 texts: Vec::new(),
165 };
166 let mut pending: Vec<(NodeId, PendingWarning)> = draft_warnings
167 .into_iter()
168 .map(|(id, w)| (id, PendingWarning::Draft(w)))
169 .collect();
170
171 let mut label_for: Vec<Vec<NodeId>> = vec![Vec::new(); tree.nodes.len()];
172 if mode == Mode::Derive {
173 resolve_keys(&mut tree, &keys, &mut label_for, &mut pending);
174 derive_hidden(&mut tree);
175 derive_offscreen(&mut tree);
176 derive_inert(&mut tree);
177 }
178 compute_texts(&mut tree, &own_texts);
179 if mode == Mode::Derive {
180 compute_names(&mut tree, &label_for);
181 }
182 for node in &mut tree.nodes {
183 node.ignored = is_ignorable(node);
184 }
185 compute_paths(&mut tree);
186 tree.warnings = pending
187 .into_iter()
188 .map(|(id, warning)| to_tree_warning(&tree, id, warning))
189 .collect();
190 tree
191}
192
193fn to_tree_warning(tree: &SemanticTree, id: NodeId, warning: PendingWarning) -> TreeWarning {
194 let at = tree.get(id).map(|n| n.path.clone()).unwrap_or_default();
195 match warning {
196 PendingWarning::Draft(DraftWarning::InvalidLevel) => TreeWarning::InvalidLevel { at },
197 PendingWarning::Draft(DraftWarning::InvalidTestId(id)) => {
198 TreeWarning::InvalidTestId { at, id }
199 }
200 PendingWarning::Draft(DraftWarning::UnknownRole) => TreeWarning::UnknownRole { at },
201 PendingWarning::UnresolvedKey(key) => TreeWarning::UnresolvedKey { key, at },
202 PendingWarning::DuplicateKey(key) => TreeWarning::DuplicateKey { key, at },
203 PendingWarning::OwnsCycle => TreeWarning::OwnsCycle { at },
204 }
205}
206
207fn resolve_keys(
208 tree: &mut SemanticTree,
209 keys: &[DraftKeys],
210 label_for: &mut [Vec<NodeId>],
211 pending: &mut Vec<(NodeId, PendingWarning)>,
212) {
213 let mut by_key: HashMap<&RawKey, NodeId> = HashMap::new();
214 for (index, draft) in keys.iter().enumerate() {
215 let Some(key) = &draft.key else { continue };
216 let id = tree.nodes[index].id;
217 if by_key.contains_key(key) {
218 pending.push((id, PendingWarning::DuplicateKey(key_text(key))));
219 continue;
220 }
221 by_key.insert(key, id);
222 }
223 let lookup = |id: NodeId, wanted: &[RawKey], pending: &mut Vec<(NodeId, PendingWarning)>| {
224 wanted
225 .iter()
226 .filter_map(|key| {
227 let found = by_key.get(key).copied();
228 if found.is_none() {
229 pending.push((id, PendingWarning::UnresolvedKey(key_text(key))));
230 }
231 found
232 })
233 .collect::<Vec<_>>()
234 };
235 let mut owns_edges = Vec::new();
236 for (index, draft) in keys.iter().enumerate() {
237 let id = tree.nodes[index].id;
238 let labelled_by = lookup(id, &draft.labelled_by, pending);
239 let described_by = lookup(id, &draft.described_by, pending);
240 let controls = lookup(id, &draft.controls, pending);
241 for target in lookup(id, &draft.label_for, pending) {
242 label_for[target.index()].push(id);
243 }
244 owns_edges.extend(
245 lookup(id, &draft.owns, pending)
246 .into_iter()
247 .map(|t| (id, t)),
248 );
249 let relations = &mut tree.nodes[index].relations;
250 relations.labelled_by = labelled_by;
251 relations.described_by = described_by;
252 relations.controls = controls;
253 }
254 for (owner, owned) in owns_edges {
255 if tree.nodes[owned.index()].relations.owner.is_some() || reaches(tree, owner, owned) {
256 pending.push((owner, PendingWarning::OwnsCycle));
257 continue;
258 }
259 tree.nodes[owner.index()].relations.owns.push(owned);
260 tree.nodes[owned.index()].relations.owner = Some(owner);
261 }
262}
263
264fn reaches(tree: &SemanticTree, from: NodeId, target: NodeId) -> bool {
266 let mut current = Some(from);
267 let mut steps = 0;
268 while let Some(id) = current {
269 if id == target {
270 return true;
271 }
272 steps += 1;
273 if steps > tree.nodes.len() {
274 return true;
275 }
276 let node = &tree.nodes[id.index()];
277 current = node.relations.owner.or(node.parent);
278 }
279 false
280}
281
282fn derive_hidden(tree: &mut SemanticTree) {
283 let mut blocks = vec![false; tree.nodes.len()];
284 for index in 0..tree.nodes.len() {
285 let node = &tree.nodes[index];
286 let is_window = node.role == Role::Window && node.parent.is_none();
287 let zero = !is_window && node.bounds.area() <= 0.0;
288 let explicit = node.states.hidden;
289 let inherited = node.parent.is_some_and(|p| blocks[p.index()]);
290 blocks[index] = explicit || inherited || (zero && node.role != Role::Generic);
291 let hidden = explicit || zero || inherited;
292 let source = if explicit {
293 node.states.source(StateName::Hidden)
294 } else {
295 None
296 };
297 let node = &mut tree.nodes[index];
298 node.states.set(
299 StateName::Hidden,
300 StateValue::Bool(hidden),
301 source.unwrap_or(StateSource::Derived),
302 );
303 }
304}
305
306fn derive_offscreen(tree: &mut SemanticTree) {
307 for node in &mut tree.nodes {
308 let offscreen = node.bounds.area() > 0.0 && node.visible_bounds.is_none();
309 node.states.set(
310 StateName::Offscreen,
311 StateValue::Bool(offscreen),
312 StateSource::Derived,
313 );
314 }
315}
316
317fn derive_inert(tree: &mut SemanticTree) {
318 for root in tree.roots.clone() {
319 let window: Vec<NodeId> = std::iter::once(root)
320 .chain(tree.descendants(root))
321 .collect();
322 let topmost = window
323 .iter()
324 .filter_map(|id| tree.get(*id))
325 .filter(|n| n.states.modal && !n.states.hidden)
326 .max_by_key(|n| (n.layer, n.order))
327 .map(|n| (n.id, n.layer));
328 let Some((modal, layer)) = topmost else {
329 continue;
330 };
331 let mut live = vec![false; tree.nodes.len()];
332 live[modal.index()] = true;
333 for id in tree.descendants(modal).chain(tree.ancestors(modal)) {
334 live[id.index()] = true;
335 }
336 for id in window {
337 let node = &mut tree.nodes[id.index()];
338 let above = node.layer > layer;
339 let inert = !live[id.index()] && !above;
340 node.states.set(
341 StateName::Inert,
342 StateValue::Bool(inert),
343 StateSource::Derived,
344 );
345 }
346 }
347}
348
349fn compute_texts(tree: &mut SemanticTree, own_texts: &[Option<String>]) {
350 let mut texts = vec![String::new(); tree.nodes.len()];
351 for index in (0..tree.nodes.len()).rev() {
352 let node = &tree.nodes[index];
353 let mut parts: Vec<&str> = Vec::new();
354 if let Some(own) = own_texts.get(index).and_then(Option::as_deref) {
355 parts.push(own);
356 }
357 for child in &node.children {
358 let child_node = &tree.nodes[child.index()];
359 if child_node.states.hidden {
360 continue;
361 }
362 parts.push(texts[child.index()].as_str());
363 }
364 let joined = parts
365 .into_iter()
366 .map(str::trim)
367 .filter(|p| !p.is_empty())
368 .collect::<Vec<_>>()
369 .join(" ");
370 texts[index] = joined;
371 }
372 tree.texts = texts;
373}
374
375fn label_text(tree: &SemanticTree, id: NodeId) -> String {
376 let text = tree.text_content(id);
377 if !text.is_empty() {
378 return text.to_owned();
379 }
380 tree.get(id)
381 .filter(|n| n.name_source == NameSource::Annotation)
382 .and_then(|n| n.name.clone())
383 .unwrap_or_default()
384}
385
386fn joined_labels(tree: &SemanticTree, ids: &[NodeId]) -> Option<String> {
387 let joined = ids
388 .iter()
389 .map(|id| label_text(tree, *id))
390 .filter(|t| !t.is_empty())
391 .collect::<Vec<_>>()
392 .join(" ");
393 (!joined.is_empty()).then_some(joined)
394}
395
396fn compute_names(tree: &mut SemanticTree, label_for: &[Vec<NodeId>]) {
397 for (index, labels) in label_for.iter().enumerate() {
398 let node = &tree.nodes[index];
399 let id = node.id;
400 let role = node.role;
401 let text = tree.text_content(id);
402 let name = if node.name.is_some() {
403 None
404 } else if let Some(name) = joined_labels(tree, &node.relations.labelled_by) {
405 Some((name, NameSource::LabelledBy))
406 } else if let Some(name) = joined_labels(tree, labels) {
407 Some((name, NameSource::LabelFor))
408 } else if is_text_role(role) && !text.is_empty() {
409 Some((text.to_owned(), NameSource::Text))
410 } else if named_from_content(role) && !text.is_empty() {
411 Some((text.to_owned(), NameSource::Content))
412 } else if let Some(tooltip) = &node.tooltip {
413 Some((tooltip.clone(), NameSource::Tooltip))
414 } else if role
415 .capabilities()
416 .contains(icedwright_types::role::Capabilities::EDITABLE)
417 {
418 node.placeholder
419 .clone()
420 .map(|placeholder| (placeholder, NameSource::Placeholder))
421 } else {
422 None
423 };
424 let description = if node.description.is_some() {
425 None
426 } else {
427 joined_labels(tree, &node.relations.described_by)
428 };
429 let node = &mut tree.nodes[index];
430 if let Some((name, source)) = name {
431 node.name = Some(name);
432 node.name_source = source;
433 }
434 if let Some(description) = description {
435 node.description = Some(description);
436 } else if node.description.is_none() && node.name_source != NameSource::Tooltip {
437 node.description = node.tooltip.clone();
438 }
439 }
440}
441
442fn is_ignorable(node: &Node) -> bool {
443 node.role == Role::Generic
444 && node.parent.is_some()
445 && node.widget_id.is_none()
446 && node.test_id.is_none()
447 && node.name.is_none()
448 && node.relations.is_empty()
449}
450
451pub(crate) fn path_parent(tree: &SemanticTree, id: NodeId) -> Option<NodeId> {
454 let node = tree.get(id)?;
455 if let Some(owner) = node.relations.owner {
456 return Some(owner);
457 }
458 let mut current = node.parent;
459 while let Some(parent) = current {
460 let parent_node = tree.get(parent)?;
461 if !parent_node.ignored {
462 return Some(parent);
463 }
464 if let Some(owner) = parent_node.relations.owner {
465 return Some(owner);
466 }
467 current = parent_node.parent;
468 }
469 None
470}
471
472fn segment_of(node: &Node) -> Segment {
473 match &node.test_id {
474 Some(id) => Segment::TestId {
475 id: id.clone(),
476 index: 0,
477 },
478 None => Segment::Role {
479 role: node.role,
480 name: node.name.clone(),
481 index: 0,
482 },
483 }
484}
485
486fn compute_paths(tree: &mut SemanticTree) {
487 let count = tree.nodes.len();
488 let parents: Vec<Option<NodeId>> = (0..count)
489 .map(|i| path_parent(tree, tree.nodes[i].id))
490 .collect();
491 let mut segments: Vec<Segment> = tree.nodes.iter().map(segment_of).collect();
492 let mut seen: HashMap<Option<NodeId>, Vec<usize>> = HashMap::new();
493 for index in 0..count {
494 if tree.nodes[index].ignored {
495 continue;
496 }
497 let siblings = seen.entry(parents[index]).or_default();
498 let earlier = siblings
499 .iter()
500 .filter(|other| segments[**other].same_key(&segments[index]))
501 .count();
502 segments[index].set_index(u32::try_from(earlier).unwrap_or(u32::MAX));
503 siblings.push(index);
504 }
505 let mut paths: Vec<Option<NodePath>> = vec![None; count];
506 for index in 0..count {
507 let mut chain = vec![index];
508 let mut current = parents[index];
509 while let Some(parent) = current {
510 if paths[parent.index()].is_some() || chain.len() > count {
511 break;
512 }
513 chain.push(parent.index());
514 current = parents[parent.index()];
515 }
516 let mut base = current
517 .and_then(|p| paths[p.index()].clone())
518 .unwrap_or_default();
519 for link in chain.into_iter().rev() {
520 if paths[link].is_none() {
521 let path = if tree.nodes[link].ignored {
522 base.clone()
523 } else {
524 base.child(segments[link].clone())
525 };
526 paths[link] = Some(path);
527 }
528 base = paths[link].clone().unwrap_or_default();
529 }
530 }
531 for (node, path) in tree.nodes.iter_mut().zip(paths) {
532 node.path = path.unwrap_or_default();
533 }
534}