teksilo_core/widget_tree/accessibility_emit_impl.rs
1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! AccessKit node emission: the walker that turns the widget arena into
5//! `accesskit::Node` values — bounds, roles, properties, synthetic children,
6//! and the subtree-merge helpers it leans on.
7
8use super::*;
9
10use super::accessibility_impl::to_accesskit_rect;
11use crate::accessibility::{AccessNodeBuilder, to_accesskit_affine};
12
13/// The node an adapter tells a reader holds focus: the focused node's
14/// `active_descendant` when that names a node in the update, which is how
15/// `accesskit_consumer` resolves it (`tree.rs:537-543`, `node.rs:966-971`).
16fn focus_as_read(
17 nodes: &[(accesskit::NodeId, accesskit::Node)],
18 focus: accesskit::NodeId,
19) -> accesskit::NodeId {
20 nodes
21 .iter()
22 .find(|(id, _)| *id == focus)
23 .and_then(|(_, node)| node.active_descendant())
24 .filter(|descendant| nodes.iter().any(|(id, _)| id == descendant))
25 .unwrap_or(focus)
26}
27
28impl WidgetTree {
29 /// Walk the arena into a `TreeUpdate`.
30 ///
31 /// `speak` lets a message the framework's announcers hold ready enter the
32 /// update, which it then does unless the update moves focus; the last
33 /// element of the result says whether it did. A snapshot passes `false`
34 /// and describes the tree the adapters have. See [`crate::announcer`].
35 #[allow(clippy::type_complexity)]
36 pub(super) fn build_accessibility_tree(
37 &self,
38 speak: bool,
39 ) -> (
40 accesskit::TreeUpdate,
41 std::collections::HashMap<accesskit::NodeId, WidgetId>,
42 std::collections::HashMap<accesskit::NodeId, teksilo_canvas::Rect>,
43 super::accessibility_description_impl::DescriptionMemory,
44 bool,
45 ) {
46 use crate::accessibility::{root_node_id, widget_id_to_node_id};
47
48 let roots = self.arena.roots();
49 let mut nodes: Vec<(accesskit::NodeId, accesskit::Node)> = Vec::new();
50 let mut synthetic_parents: std::collections::HashMap<accesskit::NodeId, WidgetId> =
51 std::collections::HashMap::new();
52 // Global deduplication: AccessKit's consumer panics if the same child
53 // NodeId appears in more than one node's children list across a TreeUpdate.
54 // Track which widget first claimed each child so we can skip duplicates
55 // and emit a diagnostic pointing at the two conflicting parents.
56 let mut seen_children: std::collections::HashMap<accesskit::NodeId, WidgetId> =
57 std::collections::HashMap::new();
58 // Where each synthetic child sits inside its owner, for the ones
59 // that declared local bounds. A pure translation re-places them
60 // from here without walking again.
61 let mut local_bounds: std::collections::HashMap<accesskit::NodeId, teksilo_canvas::Rect> =
62 std::collections::HashMap::new();
63
64 let mut root = accesskit::Node::new(accesskit::Role::Window);
65 // Every rectangle below is logical; AccessKit wants physical. One
66 // transform here converts the whole tree, synthetic children included.
67 // See [`super::accessibility_impl::emit_root_transform`].
68 super::accessibility_impl::emit_root_transform(&mut root, self.device_scale_factor());
69 // Tag the root with the app's current locale (BCP-47, e.g. "fr-FR").
70 // AccessKit nodes inherit `language` from their ancestors, so setting
71 // it once on the Window node propagates to the whole tree. Without it,
72 // VoiceOver/Narrator have no language hint and fall back to a default
73 // (often English) TTS voice instead of the user's system voice. The
74 // locale is fed in by the app layer via `WidgetTree::set_locale`.
75 if let Some(locale) = self.locale_signal.get() {
76 root.set_language(locale);
77 }
78 // The window's name. On AT-SPI the root is the window, and its label
79 // is the only name `accesskit_atspi_common` gives the frame and sends
80 // with `window:activate` (`adapter.rs:551-560`): without it Orca
81 // announces every window as an unnamed "frame". Windows and macOS read
82 // the title from the native window instead (`accesskit_windows`
83 // `node.rs:1061-1068`; `accesskit_macos` `node.rs:316-321` drops a
84 // root window's title on purpose), so this changes nothing there.
85 if let Some(title) = self.window_title_for_accessibility() {
86 root.set_label(title);
87 }
88 for &root_id in &roots {
89 if self.arena.is_active(root_id) {
90 let child_nid = widget_id_to_node_id(root_id);
91 if seen_children.insert(child_nid, root_id).is_none() {
92 root.push_child(child_nid);
93 } else {
94 eprintln!(
95 "Teksilo bug: duplicate accessibility child {:?} in Window root — \
96 already claimed by another parent. Please file a bug report.",
97 root_id
98 );
99 }
100 }
101 }
102 nodes.push((root_node_id(), root));
103
104 // One pass, one set: a tooltip is placed once, on the first node that
105 // may have it, and the walk order makes that the owner rather than the
106 // anchor.
107 let mut handled_tooltips: std::collections::HashSet<WidgetId> =
108 std::collections::HashSet::new();
109 let mut proxies = ProxyLedger::default();
110 for &root_id in &roots {
111 self.build_accessibility_recursive(
112 root_id,
113 teksilo_canvas::Transform2D::IDENTITY,
114 &mut nodes,
115 &mut synthetic_parents,
116 &mut local_bounds,
117 &mut seen_children,
118 &mut handled_tooltips,
119 &mut proxies,
120 );
121 }
122
123 // A relation that names a composite names the proxy that stands for
124 // it: the composite's own node is structure, and the presentational
125 // pass below may drop it. Run before that pass, which keeps any node a
126 // relation still names.
127 proxies.redirect_relations(&mut nodes);
128
129 // The focused node, resolved to something this walk actually emitted.
130 //
131 // Active is necessary and not sufficient. A widget can be alive and
132 // still absent from the tree — inside an `access_exclude_subtree`, or
133 // left out of an ancestor's `accessibility_children` (which is how
134 // `SceneView` publishes fewer cards than it keeps warm). Naming it as
135 // the focus is not a missing link but a broken update: the consumer
136 // every platform adapter is built on resolves `focus` against the
137 // nodes it was handed and rejects a tree where it cannot.
138 //
139 // So walk up to the nearest ancestor that did emit, which is the node
140 // a screen reader would have put the user in anyway, and fall back to
141 // the window root only if nothing on the chain emitted. The set costs
142 // one pass over the nodes already built.
143 let emitted: std::collections::HashSet<accesskit::NodeId> =
144 nodes.iter().map(|(id, _)| *id).collect();
145 let focus = self
146 .focused
147 .filter(|id| self.arena.is_active(*id))
148 .and_then(|id| {
149 let mut current = Some(id);
150 while let Some(curr) = current {
151 let nid = widget_id_to_node_id(curr);
152 if emitted.contains(&nid) {
153 return Some(nid);
154 }
155 current = self.arena.parent(curr);
156 }
157 None
158 })
159 .unwrap_or_else(root_node_id);
160 // A composite that hands its node to a proxy hands it the focus too.
161 // An editor takes the keys on a wrapper whose node is structure and
162 // keeps its text on a body the keyboard never lands on; a reader reads
163 // the node named here when focus arrives, and `accesskit_atspi_common`
164 // sends caret and selection events only for that node
165 // (`adapter.rs:215-218`). Published on the wrapper, focus arrives on a
166 // node with no name and no text, and no caret move is ever reported.
167 let focus = Some(proxies.stand_in(focus))
168 .filter(|nid| emitted.contains(nid))
169 .unwrap_or(focus);
170
171 // Each row named here from its content, with the node its name was
172 // taken from: the row is read in that content's language.
173 let mut named_from: std::collections::HashMap<accesskit::NodeId, accesskit::NodeId> =
174 std::collections::HashMap::new();
175
176 // ── Name-from-content for row nodes ───────────────────────────
177 // A virtualized row is two nodes: a thin structural wrapper
178 // (`ListItemWrapper` / `TreeItemWrapper`) carrying the role, level
179 // and selected/expanded state, and the app's delegate widget below
180 // it carrying the visible label. ARIA computes an `option`'s /
181 // `treeitem`'s name from its contents; AccessKit does not. Without
182 // this pass the platform adapters announce a nameless "tree item",
183 // and any client that matches a role AND a label — a screen-reader
184 // search, the automation bridge's `find_node` — can never match a
185 // row, because the two live on different nodes.
186 //
187 // Fill each nameless row node's name in from its first named
188 // descendant, in the order they read. The descendant keeps its own
189 // name (as in a browser's accessibility tree, where the text that
190 // contributes to a computed name stays in the tree).
191 {
192 use accesskit::Role;
193 use std::collections::HashMap;
194
195 // Row roles that take their name from content. A row inside a
196 // row (a `TreeView` nests each row under its parent row on
197 // Windows and Linux) owns its own name: the search stops there
198 // and does not descend, which is what keeps a parent row's name
199 // its own content's rather than its first child row's.
200 fn names_from_content(role: Role) -> bool {
201 matches!(role, Role::TreeItem | Role::ListBoxOption)
202 }
203
204 let index: HashMap<accesskit::NodeId, usize> = nodes
205 .iter()
206 .enumerate()
207 .map(|(i, (nid, _))| (*nid, i))
208 .collect();
209
210 let mut hoisted: Vec<(usize, String, accesskit::NodeId)> = Vec::new();
211 for (i, (_, node)) in nodes.iter().enumerate() {
212 if !names_from_content(node.role()) || node.label().is_some() {
213 continue;
214 }
215 // Depth-first, children in document order.
216 let mut stack: Vec<accesskit::NodeId> =
217 node.children().iter().rev().copied().collect();
218 while let Some(nid) = stack.pop() {
219 let Some(&j) = index.get(&nid) else { continue };
220 let descendant = &nodes[j].1;
221 if names_from_content(descendant.role()) {
222 continue;
223 }
224 match descendant.label() {
225 Some(label) if !label.trim().is_empty() => {
226 hoisted.push((i, label.to_string(), nid));
227 break;
228 }
229 _ => stack.extend(descendant.children().iter().rev().copied()),
230 }
231 }
232 }
233 for (i, label, source) in hoisted {
234 named_from.insert(nodes[i].0, source);
235 nodes[i].1.set_label(label);
236 }
237 }
238
239 // ── Presentational-node pruning ───────────────────────────────
240 // Layout primitives (HStack/VStack/ZStack/Center/Padding/Expand/…)
241 // emit empty `GenericContainer` / `Unknown` AT nodes purely to
242 // carry visual structure. VoiceOver announces a `GenericContainer`
243 // as "group", so a Button whose chrome is composed from these
244 // primitives reads as "<label>, button, group". Browsers collapse
245 // such semantically-empty nodes out of the platform tree
246 // ("ignored" / "presentational" nodes); do the same — drop each
247 // empty container and PROMOTE its children to its parent (bounds
248 // are absolute, so promotion is structural only).
249 //
250 // A node is prunable only if it is a visible, content-free
251 // `GenericContainer`/`Unknown`: no name, value, live region,
252 // popup, relation, or focus/click action. The Window root, the
253 // focused node, and any relationship target are always kept.
254 {
255 use std::collections::{HashMap, HashSet};
256
257 // Nodes referenced by another node's relations must survive so
258 // the reference can't dangle.
259 let mut relation_targets: HashSet<accesskit::NodeId> = HashSet::new();
260 for (_, node) in &nodes {
261 relation_targets.extend(node.controls());
262 relation_targets.extend(node.described_by());
263 relation_targets.extend(node.labelled_by());
264 }
265
266 let prunable: HashSet<accesskit::NodeId> = nodes
267 .iter()
268 .filter(|(nid, node)| {
269 *nid != root_node_id()
270 && *nid != focus
271 && !relation_targets.contains(nid)
272 && is_presentational_container(node)
273 })
274 .map(|(nid, _)| *nid)
275 .collect();
276
277 if !prunable.is_empty() {
278 // Pre-pruning children lists, for chain resolution.
279 let children_map: HashMap<accesskit::NodeId, Vec<accesskit::NodeId>> = nodes
280 .iter()
281 .map(|(nid, node)| (*nid, node.children().to_vec()))
282 .collect();
283
284 // A kept node's effective children: each prunable child is
285 // replaced by its own (recursively resolved) kept children,
286 // so chains of empty containers collapse in one pass. The
287 // AT tree is acyclic, so the memo is the only guard needed.
288 fn resolve(
289 nid: accesskit::NodeId,
290 children_map: &HashMap<accesskit::NodeId, Vec<accesskit::NodeId>>,
291 prunable: &HashSet<accesskit::NodeId>,
292 memo: &mut HashMap<accesskit::NodeId, Vec<accesskit::NodeId>>,
293 ) -> Vec<accesskit::NodeId> {
294 if let Some(cached) = memo.get(&nid) {
295 return cached.clone();
296 }
297 let mut out = Vec::new();
298 if let Some(kids) = children_map.get(&nid) {
299 for &c in kids {
300 if prunable.contains(&c) {
301 out.extend(resolve(c, children_map, prunable, memo));
302 } else {
303 out.push(c);
304 }
305 }
306 }
307 memo.insert(nid, out.clone());
308 out
309 }
310
311 let mut memo: HashMap<accesskit::NodeId, Vec<accesskit::NodeId>> = HashMap::new();
312 for (nid, node) in &mut nodes {
313 if prunable.contains(nid) {
314 continue;
315 }
316 let resolved = resolve(*nid, &children_map, &prunable, &mut memo);
317 if children_map.get(nid) != Some(&resolved) {
318 node.set_children(resolved);
319 }
320 }
321 nodes.retain(|(nid, _)| !prunable.contains(nid));
322 }
323 }
324
325 // ── Strip dangling children ───────────────────────────────────
326 // A node's children list may name a NodeId that never reached this
327 // update. The walker's own pushes cannot do that (it pushes a child
328 // only after `arena.is_active`), but `attach_scene_child_under` can:
329 // it is called from a widget's `accessibility()` — which has no arena
330 // — to graft a *sibling* widget's node under a synthetic parent, and
331 // that widget may have gone dormant, in which case the walker emitted
332 // nothing for it.
333 //
334 // A dangling child is not a lost link, it is a broken tree: the
335 // consumer walks children to build the filtered tree every platform
336 // adapter reads, and a child it cannot resolve is an unreachable
337 // parent for everything below it. This is the structural twin of the
338 // relation strip immediately below, and it is enforced HERE rather
339 // than at each caller because a caller that could check would not
340 // need to ask: `Widget::accessibility` sees no arena by design, and
341 // a visibility gate written during layout settles after the widget
342 // that wrote it has already been asked for its node.
343 //
344 // Runs before the relation strip so a child removed here cannot be
345 // resurrected as a relation target by a later pass.
346 //
347 // Each emitted node's position in `nodes`, built once here and read by
348 // the two strips and the cell naming pass below: none of them adds,
349 // removes or reorders a node (the announcer nodes appended after the
350 // strips are absent from it, and no strip or cell looks for them).
351 let emitted: std::collections::HashMap<accesskit::NodeId, usize> = nodes
352 .iter()
353 .enumerate()
354 .map(|(i, (id, _))| (*id, i))
355 .collect();
356 for (_, node) in &mut nodes {
357 if node.children().iter().all(|c| emitted.contains_key(c)) {
358 continue;
359 }
360 let kept: Vec<_> = node
361 .children()
362 .iter()
363 .filter(|c| emitted.contains_key(*c))
364 .copied()
365 .collect();
366 node.set_children(kept);
367 }
368
369 // Strip relationship targets (controls, described_by, labelled_by) that
370 // reference NodeIds absent from the emitted tree. Dormant widgets (e.g.
371 // inactive tab panels) are excluded from the TreeUpdate; if a node still
372 // holds a `push_controlled` / `push_described_by` / `push_labelled_by`
373 // reference to one of them, accesskit_macos will unwrap() it and panic
374 // when VoiceOver follows the linked_ui_elements attribute.
375 //
376 // `labelled_by` is the one that costs a name rather than a link: the
377 // consumer concatenates its targets' values to build the node's name
378 // (`accesskit_consumer::node::write_label`), and a dangling target
379 // panics the iterator before it gets there.
380 for (_, node) in &mut nodes {
381 let controlled: Vec<_> = node
382 .controls()
383 .iter()
384 .filter(|id| emitted.contains_key(*id))
385 .copied()
386 .collect();
387 if controlled.len() != node.controls().len() {
388 node.set_controls(controlled);
389 }
390 let described: Vec<_> = node
391 .described_by()
392 .iter()
393 .filter(|id| emitted.contains_key(*id))
394 .copied()
395 .collect();
396 if described.len() != node.described_by().len() {
397 node.set_described_by(described);
398 }
399 let labelled: Vec<_> = node
400 .labelled_by()
401 .iter()
402 .filter(|id| emitted.contains_key(*id))
403 .copied()
404 .collect();
405 if labelled.len() != node.labelled_by().len() {
406 node.set_labelled_by(labelled);
407 }
408 }
409
410 // The framework's own live regions, last in the root's child list so
411 // they sit after the application's content in reading order: one node
412 // for each message spoken in the last few seconds, each from an id the
413 // tree has never used. See [`crate::announcer`] for why an
414 // announcement is a node that was never in the tree rather than a
415 // label edited in place or a node shown again.
416 //
417 // A message ready to enter does so only in an update that leaves
418 // focus where the last one put it: the adapters raise an update's
419 // announcements before its focus event, and a reader that stops to
420 // read the new focus cuts the message. Focus is compared as the
421 // consumer resolves it, so a list's new current row is a move.
422 let ready = speak
423 && (self.announcer_polite.entering().is_some()
424 || self.announcer_assertive.entering().is_some());
425 let moves_focus = ready
426 && self.cached_a11y.as_ref().is_some_and(|last| {
427 focus_as_read(&last.nodes, last.focus) != focus_as_read(&nodes, focus)
428 });
429 let admitted = ready && !moves_focus;
430 // What waits is heard after the arrival, by every reader.
431 let held: Vec<&str> = if moves_focus {
432 [
433 self.announcer_polite.entering(),
434 self.announcer_assertive.entering(),
435 ]
436 .into_iter()
437 .flatten()
438 .collect()
439 } else {
440 Vec::new()
441 };
442 let announcer_nodes: Vec<(accesskit::NodeId, accesskit::Node)> = self
443 .announcer_polite
444 .nodes(admitted)
445 .chain(self.announcer_assertive.nodes(admitted))
446 .collect();
447 if let Some((_, root)) = nodes.iter_mut().find(|(id, _)| *id == root_node_id()) {
448 for (id, _) in &announcer_nodes {
449 root.push_child(*id);
450 }
451 }
452 nodes.extend(announcer_nodes);
453
454 // A table cell is named after the text it shows, as ARIA names it
455 // from its content and the consumer does not. Before the description
456 // pass, which reads names; after the relation strip, so every target
457 // it adds is present.
458 super::accessibility_cell_name_impl::name_cells_from_content(&mut nodes, &emitted);
459 // A placeholder that repeats the field's name is read after it, once
460 // more. After the cells are named and before the description pass,
461 // with every `labelled_by` target present.
462 super::accessibility_placeholder_impl::drop_placeholders_repeating_the_name(&mut nodes);
463 // Each node's content language, where it differs from what it
464 // inherits. After the prune and the strips, so it is compared with
465 // the parent each node has in the tree as sent, and after the cells
466 // are named, since a node named from its content is read in that
467 // content's language.
468 self.emit_content_languages(&mut nodes, &named_from);
469
470 // Last, on the nodes this update carries: a `described_by` relation
471 // reaches no screen reader through AccessKit, so its targets' text is
472 // written onto the node's `description`, which every adapter exposes.
473 // After the relation strip, so every target named is present.
474 let descriptions = self.describe_from_relations(&mut nodes, focus, &held);
475
476 (
477 accesskit::TreeUpdate {
478 nodes,
479 tree: Some(accesskit::TreeInfo::new(root_node_id())),
480 tree_id: accesskit::TreeId::ROOT,
481 focus,
482 },
483 synthetic_parents,
484 local_bounds,
485 descriptions,
486 admitted,
487 )
488 }
489
490 #[allow(clippy::too_many_arguments)]
491 pub(super) fn build_accessibility_recursive(
492 &self,
493 id: WidgetId,
494 // The transform carrying this node's bounds space into the space its
495 // AccessKit parent is described in. Identity for all but the direct
496 // children of a content-transform node; see the `set_transform` call
497 // below for why it is emitted there and nowhere else.
498 content_to_parent: teksilo_canvas::Transform2D,
499 nodes: &mut Vec<(accesskit::NodeId, accesskit::Node)>,
500 synthetic_parents: &mut std::collections::HashMap<accesskit::NodeId, WidgetId>,
501 local_bounds: &mut std::collections::HashMap<accesskit::NodeId, teksilo_canvas::Rect>,
502 seen_children: &mut std::collections::HashMap<accesskit::NodeId, WidgetId>,
503 // Tooltips whose text has already been placed on a node this pass.
504 // One tooltip describes one control, so once an owner has taken it the
505 // anchor further down must not take it again -- a description announced
506 // twice on the way into a control is worse than one announced in the
507 // wrong place.
508 handled_tooltips: &mut std::collections::HashSet<WidgetId>,
509 // What composites above have handed down to the descendants that
510 // stand for them (`Widget::accessibility_proxy`).
511 proxies: &mut ProxyLedger,
512 ) {
513 use crate::accessibility::widget_id_to_node_id;
514 use crate::widget_builder::AccessSubtreeMode;
515
516 if !self.arena.is_active(id) {
517 return;
518 }
519
520 let node = self
521 .arena
522 .get(id)
523 .expect("widget id is not in the arena (destroyed?)");
524 let mut builder = AccessNodeBuilder::for_widget(id);
525 node.widget.accessibility(&mut builder);
526 // Same call, same place, as `build_overridden_builder` — the two builder
527 // paths are parallel by construction and a derivation added to one of them
528 // only is a node that reads differently to a test than to a screen reader.
529 self.announce_context_menu(id, &mut builder);
530 self.announce_focusable(id, &mut builder);
531
532 // Whatever the composites this node stands for handed down (see
533 // `Widget::accessibility_proxy`). Taken out of the ledger here, so a
534 // composite below that names a proxy of its own passes them on rather
535 // than leaving a second copy behind.
536 let standing_for = proxies.standing_for.remove(&id).unwrap_or_default();
537 let mut reserved_tooltip = proxies.tooltips.remove(&id);
538 let proxy = self.live_accessibility_proxy(id);
539
540 // Apply builder-level overrides AFTER the inner widget has
541 // emitted its defaults, so the overrides win for scalar fields
542 // and append on relationship lists.
543 //
544 // A composite with a proxy keeps none of them. Its node is structure,
545 // and what an application attached to it (the only id it can reach)
546 // belongs on the node that holds focus: its overrides, those it was
547 // handed from further up, and the tooltip it owns all move down to the
548 // proxy, which applies them after its own so the application still
549 // has the last word. The tooltip is marked handled now, because the
550 // walk passes the composite's chrome, where the tooltip is anchored,
551 // before it reaches the proxy.
552 match proxy {
553 Some(proxy_id) => {
554 let mut chain = Vec::with_capacity(standing_for.len() + 1);
555 chain.push(id);
556 chain.extend(standing_for.iter().copied());
557 // Two composites can name the same proxy: a `DateEdit` names
558 // its `TextInput`'s field, and so does the `TextInput`. The
559 // outer one was walked first and left its share already; it
560 // goes after this one's, since the order is innermost first.
561 if let Some(outer) = proxies.standing_for.remove(&proxy_id) {
562 chain.extend(outer);
563 }
564 proxies.standing_for.insert(proxy_id, chain);
565 if let Some(content) = reserved_tooltip
566 .take()
567 .or_else(|| self.tooltip_claim_for_proxy(id, handled_tooltips))
568 {
569 handled_tooltips.insert(content);
570 // An outer composite that names the same proxy reserved
571 // its tooltip first; keep it rather than overwrite it.
572 proxies.tooltips.entry(proxy_id).or_insert(content);
573 }
574 proxies
575 .nodes
576 .insert(widget_id_to_node_id(id), widget_id_to_node_id(proxy_id));
577 }
578 None => {
579 // The menu a composite owns is offered where its node went:
580 // focus arrives here now, and the dispatcher already finds the
581 // composite's factory from here by walking up.
582 for &composite in &standing_for {
583 self.announce_context_menu(composite, &mut builder);
584 }
585 // Before the overrides, so an application's own name still
586 // wins over the row label that replaces a default here.
587 self.yield_default_name(id, &standing_for, &mut builder);
588 self.apply_access_overrides(id, &mut builder);
589 for &composite in &standing_for {
590 self.apply_access_overrides(composite, &mut builder);
591 }
592 }
593 }
594
595 let subtree_mode = node.access_subtree;
596 // G17: a widget may present a different child ORDER to assistive tech
597 // than its paint / z-order child order — e.g. TableView / TreeTableView
598 // build body rows before the header for correct z-stacking, but the
599 // header must read first in the AT (and Tab) linear order. Honour the
600 // widget's `accessibility_children()` override when it provides one;
601 // otherwise use the arena's paint-order child list. Geometry and paint
602 // are untouched (they keep reading `arena.children`).
603 let at_children_owned;
604 let children: &[WidgetId] = match node.widget.accessibility_children() {
605 Some(v) => {
606 at_children_owned = v;
607 &at_children_owned
608 }
609 None => self.arena.children(id),
610 };
611
612 // Subtree dispatch:
613 // Inherit — push child NodeIds onto the parent and recurse normally
614 // Exclude — neither push nor recurse: descendants vanish from AT
615 // Merge — collect descendants' label/description/value/actions
616 // into THIS node, then prune (no push, no recurse)
617 // The children this node will recurse into: every active child it
618 // pushed or a redirect claimed (a claimed child is still built, under
619 // the node the claimer attaches it to), and never a duplicate. Since
620 // `accessibility_children` may name any descendant, two parents can
621 // claim one id; building it twice would emit its node twice.
622 let mut to_recurse: Vec<WidgetId> = Vec::new();
623 match subtree_mode {
624 AccessSubtreeMode::Inherit => {
625 for &child_id in children {
626 if self.arena.is_active(child_id) {
627 let child_nid = widget_id_to_node_id(child_id);
628 // Checked before the redirect, so a child claimed
629 // twice is reported and built once whichever way
630 // either claim came.
631 if let Some(&prior_parent) = seen_children.get(&child_nid) {
632 eprintln!(
633 "Teksilo bug: duplicate accessibility child {:?}: \
634 first claimed by parent {:?}, now also claimed by {:?}. \
635 Please file a bug report.",
636 child_id, prior_parent, id
637 );
638 continue;
639 }
640 // AT-redirect hook (scene logical-tree auto-graft):
641 // walk up the arena from `id` asking every
642 // opted-in ancestor whether it claims this
643 // descendant. First `Some(_)` wins, scanned
644 // bottom-up so closest ancestor takes
645 // priority. The immediate parent is queried
646 // first if it opts in, direct-child
647 // relocation being the special case of an
648 // ancestor walk of length zero.
649 //
650 // Performance: most widgets default
651 // `wants_descendant_redirects = false` and
652 // are skipped without calling the hook, so
653 // the walk is O(opted-in ancestors) per
654 // child push, typically 0 or 1 for a
655 // SceneView-rooted subtree.
656 seen_children.insert(child_nid, id);
657 to_recurse.push(child_id);
658 if self.ancestor_chain_redirects(id, child_id) {
659 continue;
660 }
661 builder.inner_mut().push_child(child_nid);
662 }
663 }
664 }
665 AccessSubtreeMode::Exclude => {
666 // No children pushed, no descendants recursed-into.
667 }
668 AccessSubtreeMode::Merge => {
669 merge_descendants_into(&mut builder, id, &self.arena);
670 }
671 }
672
673 let bounds = self.arena.bounds(id);
674 builder.inner_mut().set_bounds(to_accesskit_rect(bounds));
675 // …and, where those bounds are not already in window space, the
676 // transform that puts them there.
677 //
678 // A **content** transform node — `SceneView` is the only one today —
679 // declares that its children are laid out in a coordinate system of
680 // its own: a card at scene (100, 100) has arena bounds of (100, 100)
681 // whatever the camera is doing. Writing that rectangle out untouched
682 // told assistive technology the card was at window (100, 100), which
683 // is where it is only at pan zero: an explore-by-touch probe, a
684 // braille routing key and a magnifier following focus all resolved
685 // against a rectangle the card is not in.
686 //
687 // The fix is the mechanism AccessKit already has for exactly this.
688 // `Node::transform` applies "to any coordinates within this node and
689 // its descendants, including the `bounds` property of this node", and
690 // `bounds` are read "in the coordinate space of the nearest ancestor
691 // with a non-`None` transform". So the whole scene subtree needs ONE
692 // declaration, on each child at the boundary: every rectangle below it
693 // — a card, a label inside the card, a text run's per-character boxes
694 // — stays in scene coordinates and is projected by the consumer, which
695 // is also what makes `node_at_point` descend correctly (it feeds each
696 // child `inv(child.direct_transform()) * point`).
697 //
698 // Emitted at the boundary and only there: a grandchild that re-emitted
699 // it would compose it twice. And emitted for *content* transforms only
700 // — a `Scale` or `Rotate` scope is a visual effect applied to a widget
701 // whose bounds are already in window space, so its subtree's
702 // coordinates are unchanged and a screen reader is not asked to chase
703 // a 200 ms tween.
704 if !content_to_parent.is_identity() {
705 builder
706 .inner_mut()
707 .set_transform(to_accesskit_affine(content_to_parent));
708 }
709
710 // Framework-driven disabled gate. Respects an
711 // `access_disabled(false)` override that wants to clear
712 // arena-driven disabled state too — without this short-circuit,
713 // `clear_disabled()` in the override layer would be re-set here.
714 let force_clear_disabled =
715 self.access_disabled_override(id, proxy.is_some(), &standing_for) == Some(false);
716 if !self.arena.is_enabled(id) && !force_clear_disabled {
717 builder.set_disabled();
718 }
719
720 // ── the tooltip's text, onto the node that will be read ───────────
721 //
722 // Not necessarily the node the overlay hangs off. A composing control
723 // anchors the tooltip on an inner chrome node -- the thing with the
724 // right bounds to open against -- and keeps its role, its name and its
725 // focusability on its own outer node. Emitting on the anchor put the
726 // description on an unnamed box beside the control: present in the
727 // tree, attached to nothing anyone reads. Since a plain tooltip is
728 // never auto-shown on focus (see `docs/tooltips.md`), that description
729 // IS the whole non-pointer path for the tier, and it reached nobody.
730 //
731 // So a tooltip names an owner, and the owner is honoured here -- but
732 // only where exactly ONE tooltip claims it. `BuildContext` records the
733 // widget that was building, and one build can attach many tooltips: a
734 // list body pane attaches one per visible row, all of them naming the
735 // pane. Granting that would put one row's text on the pane and lose
736 // every other row's entirely. A contested claim is no claim, and each
737 // of those tooltips falls back to its own anchor, which is where they
738 // already were.
739 //
740 // A composite that handed its node to a proxy handed its tooltip with
741 // it, above; the proxy takes it here on the owner's terms (a node a
742 // reader stops on, with no description of its own), or falls back to
743 // the usual search.
744 let tooltip = if proxy.is_some() {
745 None
746 } else {
747 reserved_tooltip
748 .filter(|_| {
749 !is_presentational_container(builder.inner_mut())
750 && builder.inner_mut().description().is_none()
751 })
752 .or_else(|| self.tooltip_description_target(id, handled_tooltips, &mut builder))
753 };
754 if let Some(content_id) = tooltip {
755 if self
756 .tooltips
757 .iter()
758 .any(|t| t.content_id == content_id && t.overlay_id.is_some())
759 {
760 // Shown: the content node is live in the AT tree, so the
761 // richer `described_by` relation can point straight at it.
762 // Its text still reaches a reader as this node's description,
763 // which `describe_from_relations` writes from the relation at
764 // the end of the build: no adapter reads the relation itself,
765 // and showing the tooltip used to take away the only
766 // description the control had.
767 builder
768 .inner_mut()
769 .push_described_by(widget_id_to_node_id(self.tooltip_content_node(content_id)));
770 handled_tooltips.insert(content_id);
771 } else if let Some(text) = self.tooltip_access_description(content_id) {
772 // Not shown. `described_by` cannot be used — the content is a
773 // dormant node and absent from the AT tree — and a *plain*
774 // tooltip is never auto-shown on focus, so gating the relation
775 // on `overlay_id` left the whole tier (the majority of call
776 // sites) with no screen-reader path at all. Copy the text onto
777 // the control as a static description instead, which is what a
778 // keyboard-only or screen-reader user actually reaches.
779 builder.set_description(text);
780 handled_tooltips.insert(content_id);
781 }
782 }
783
784 // The fourth element holds the rects the widget declared for its
785 // synthetic children relative to its own origin, which is what lets
786 // a pure translation re-place the runs without a full walk. Recorded
787 // by `sync_accessibility`. `build` has already written each such
788 // child's bounds as that rect moved to the owner's origin, so the
789 // children carry rects in the same space as the owner's box: the
790 // root's space (window space before the root's scale), unless a
791 // content transform above the owner says otherwise.
792 let (node_id, ak_node, mut synthetic_children, synthetic_local_bounds) = builder.build(id);
793 // Those runs are put on whole device pixels here, where the scale is
794 // known; a re-placement after a scroll does the same from the same
795 // declared rects. A run handed in with absolute bounds is left as it
796 // is: a scroll shifts it by a delta, which would carry a snapped top
797 // off its pixel.
798 if !synthetic_local_bounds.is_empty()
799 && super::accessibility_impl::reports_in_window_space(&self.arena, id)
800 {
801 let local: std::collections::HashSet<accesskit::NodeId> =
802 synthetic_local_bounds.iter().map(|(sid, _)| *sid).collect();
803 let owner_box = ak_node.bounds();
804 for (syn_id, syn_node) in synthetic_children.iter_mut() {
805 if local.contains(syn_id) {
806 super::accessibility_impl::snap_text_run_top(
807 syn_node,
808 self.device_scale_factor,
809 owner_box,
810 );
811 }
812 }
813 }
814 nodes.push((node_id, ak_node));
815 local_bounds.extend(synthetic_local_bounds);
816 // Merge the widget's emitted synthetic children into the
817 // tree update and record their parent-widget mapping so
818 // `handle_accessibility_actions` can route incoming
819 // `ActionRequest`s targeting these child NodeIds back to
820 // the owning widget.
821 for (syn_id, syn_node) in synthetic_children {
822 nodes.push((syn_id, syn_node));
823 synthetic_parents.insert(syn_id, id);
824 }
825
826 // Recurse only for `Inherit` — `Exclude` and `Merge` prune
827 // descendants from the AT tree.
828 if matches!(subtree_mode, AccessSubtreeMode::Inherit) {
829 // What space this node hands its children. A content transform is
830 // the one kind that changes it; everything else — including a
831 // `Scale` / `Rotate` self transform — leaves its children in the
832 // space it was itself described in.
833 let child_space = if node.content_transform {
834 node.transform_prop
835 .as_ref()
836 .map(|p| p.get())
837 .unwrap_or(teksilo_canvas::Transform2D::IDENTITY)
838 } else {
839 teksilo_canvas::Transform2D::IDENTITY
840 };
841 for &child_id in &to_recurse {
842 self.build_accessibility_recursive(
843 child_id,
844 child_space,
845 nodes,
846 synthetic_parents,
847 local_bounds,
848 seen_children,
849 handled_tooltips,
850 proxies,
851 );
852 }
853 }
854 }
855
856 /// Walk the arena from `parent_id` up through ancestors, asking
857 /// each opted-in widget whether it claims `descendant` via
858 /// [`Widget::a11y_redirect_descendant`]. First widget that
859 /// returns `Some(_)` wins (closest-ancestor-first scan). Returns
860 /// `true` if any ancestor claimed the descendant — the caller
861 /// then skips the default child-list push.
862 ///
863 /// Cost: bounded by arena depth, but most widgets default
864 /// `wants_descendant_redirects = false` and short-circuit
865 /// without invoking the redirect hook itself. Trees with no
866 /// opted-in ancestors pay one `is_active` + one `Widget::
867 /// wants_descendant_redirects` call per ancestor — both
868 /// trivial — and walk to root.
869 ///
870 /// `parent_id` is queried *first* — direct-child relocation is
871 /// just the special case of an ancestor walk of length one.
872 fn ancestor_chain_redirects(&self, parent_id: WidgetId, descendant: WidgetId) -> bool {
873 let mut current = Some(parent_id);
874 while let Some(curr) = current {
875 let Some(curr_node) = self.arena.get(curr) else {
876 break;
877 };
878 if curr_node.widget.wants_descendant_redirects()
879 && curr_node
880 .widget
881 .a11y_redirect_descendant(curr, descendant)
882 .is_some()
883 {
884 return true;
885 }
886 current = self.arena.parent(curr);
887 }
888 false
889 }
890
891 /// Which tooltip's text this node should carry, if any.
892 ///
893 /// Two ways a node can come to own a tooltip's description, tried in that
894 /// order:
895 ///
896 /// * **as the claimed owner** -- the widget that was building when the
897 /// tooltip was attached. This is the case the whole mechanism exists
898 /// for: `Button` and the two dozen controls shaped like it hang the
899 /// overlay off an inner chrome node while their role and name live
900 /// out here. Granted only when this node is *unambiguously* the
901 /// owner: exactly one tooltip may claim it, and the node must be
902 /// something an assistive technology would actually stop on rather
903 /// than an anonymous box.
904 ///
905 /// * **as the anchor** -- the historic behaviour, and still correct for
906 /// a widget that anchors its tooltip on itself. Also the fallback for
907 /// everything the first case declines, so declining is always safe:
908 /// the worst it can do is leave the description exactly where it was
909 /// before any of this existed.
910 ///
911 /// The order matters and only works because of the walk's order. An
912 /// anchor is always a descendant of the widget that built it, and parents
913 /// are visited first, so an owner has already taken its tooltip (and said
914 /// so in `handled`) by the time the anchor is reached. Reverse the walk
915 /// and both would take it.
916 fn tooltip_description_target(
917 &self,
918 id: WidgetId,
919 handled: &std::collections::HashSet<WidgetId>,
920 builder: &mut AccessNodeBuilder,
921 ) -> Option<WidgetId> {
922 let mut claims = self
923 .tooltips
924 .iter()
925 .filter(|t| t.description_owner_id == id && !handled.contains(&t.content_id));
926 // `next()` twice rather than `count()`: one claim is the answer, two is
927 // a refusal, and there is nothing to learn from a third.
928 if let (Some(only), None) = (claims.next(), claims.next())
929 && only.anchor_id != id
930 // An anonymous container is not a place a description can be read
931 // from, and a widget whose own `accessibility()` leaves it one
932 // (`TextInput` says so out loud, keeping the real role on an inner
933 // field) is not the control being described either. Nothing is
934 // lost by declining: the anchor still takes it below.
935 && !is_presentational_container(builder.inner_mut())
936 // A description the widget wrote itself is the widget's own words
937 // about itself; a tooltip's is supplementary. Both land in the one
938 // scalar field, so the specific one wins. `MenuItem::trailing_hint`
939 // is the case that made this reachable.
940 && builder.inner_mut().description().is_none()
941 {
942 return Some(only.content_id);
943 }
944 self.tooltips
945 .iter()
946 .find(|t| t.anchor_id == id && !handled.contains(&t.content_id))
947 .map(|t| t.content_id)
948 }
949
950 /// Announce the context menu a widget owns, before any override runs.
951 ///
952 /// The dispatcher has always *serviced* `Action::ShowContextMenu` by falling
953 /// through to the node's `.context_menu(..)` factory, so an assistive
954 /// technology that tried the action got a menu. Nothing ever told it the
955 /// action was there, and an AT offers what a node advertises: the menu was
956 /// reachable and undiscoverable at the same time.
957 ///
958 /// That is not a cosmetic gap wherever a menu is the accessible route to
959 /// something else. A row that puts its actions on hover buttons has to hide
960 /// those buttons from the AT -- a control that exists only under a pointer
961 /// does not exist for a keyboard -- and offer the same actions on its context
962 /// menu instead. Unannounced, that leaves the actions with no route at all.
963 ///
964 /// Only where the node owns the factory ITSELF, not wherever the ancestor walk
965 /// would eventually find one: every descendant of a widget with a menu would
966 /// otherwise advertise it, and an AT would offer the same menu on a dozen
967 /// nested boxes. Applied BEFORE the overrides so `access_remove_action` still
968 /// takes it away, and so a widget wiring its own `on_access_action` handler is
969 /// not given a second one.
970 /// Announce that a focusable node can be focused, before any override runs.
971 ///
972 /// The sibling of [`Self::announce_context_menu`], for the same reason. The
973 /// dispatcher has always *serviced* `Action::Focus` for any node -- the
974 /// `AccessAction` arm calls `focus_with_origin_ops` itself rather than
975 /// handing the action to the widget -- so an assistive technology that tried
976 /// it got focus. Nothing told it the action was there, and an AT offers what
977 /// a node advertises: focus was reachable and undiscoverable at the same
978 /// time.
979 ///
980 /// Leaving it to each widget made it a rule that had to be remembered ~40
981 /// times and was not: every stock button remembered, while `ListView`,
982 /// `TreeView`, `TableView`, `TreeTableView`, `GridView`, `MenuList` and
983 /// `OverlayTrigger` did not -- so a screen reader could not put focus in a
984 /// list, a tree, a table, a grid or an open menu. Deriving it from the
985 /// arena's own focusable flag makes the advertisement true by construction
986 /// and keeps it true for widgets not yet written.
987 ///
988 /// Gated on the *arena* flag rather than on the widget's opinion, because
989 /// that flag is what `focus_with_origin_ops` will actually honour -- a node
990 /// that is not focusable would advertise an action that then declines to
991 /// land. Applied BEFORE the overrides, so `access_remove_action` can still
992 /// take it away.
993 fn announce_focusable(&self, id: WidgetId, builder: &mut AccessNodeBuilder) {
994 if self
995 .arena
996 .get(id)
997 .is_some_and(|node| self.is_node_focusable(node))
998 && !builder.actions().contains(&accesskit::Action::Focus)
999 {
1000 builder.add_action(accesskit::Action::Focus);
1001 }
1002 }
1003
1004 fn announce_context_menu(&self, id: WidgetId, builder: &mut AccessNodeBuilder) {
1005 let offers = |id: WidgetId| {
1006 self.arena.get(id).is_some_and(|node| {
1007 node.context_menu_factory.is_some() || node.context_menu_contribution.is_some()
1008 })
1009 };
1010 // A data view's own node offers the menu its current row would open
1011 // (the row, or the delegate or cell inside it, carries it).
1012 let reaches_one = || {
1013 let mut current = Some(self.resolve_context_menu_target(id));
1014 while let Some(at) = current {
1015 if offers(at) {
1016 return true;
1017 }
1018 if at == id {
1019 break;
1020 }
1021 current = self.arena.get(at).and_then(|node| node.parent);
1022 }
1023 false
1024 };
1025 if (offers(id) || reaches_one())
1026 && !builder
1027 .actions()
1028 .contains(&accesskit::Action::ShowContextMenu)
1029 {
1030 builder.add_action(accesskit::Action::ShowContextMenu);
1031 }
1032 }
1033
1034 /// Whether the node `id` publishes to assistive technology offers
1035 /// `Action::Focus`.
1036 ///
1037 /// Answered off the same builder the AT tree is emitted from — widget
1038 /// emission, then `announce_focusable`, then the app's overrides (which can
1039 /// both add an action and `access_remove_action` one) — so it is exactly
1040 /// what the assistive technology was told.
1041 ///
1042 /// This is the gate on the `Action::Focus` walk into a subtree. A focusable
1043 /// leaf gets the action from `announce_focusable` and resolves to itself; a
1044 /// composite that keeps focus on an inner leaf and publishes its own node
1045 /// (`ComboBox`, `DateEdit` and its siblings) adds the action in its own
1046 /// `accessibility()` and means the walk. `SpinBox` publishes through its
1047 /// field instead, which is focusable and resolves to itself. Everything
1048 /// else (a `Panel`, a `GroupBox`, a landmark, a label) offers no `Focus`,
1049 /// and moving focus into it would land the keyboard on a descendant the
1050 /// assistive technology could have named itself and did not.
1051 pub(crate) fn advertises_focus_action(&self, id: WidgetId) -> bool {
1052 self.arena.get(id).is_some()
1053 && self
1054 .build_overridden_builder(id)
1055 .actions()
1056 .contains(&accesskit::Action::Focus)
1057 }
1058
1059 pub(super) fn build_overridden_builder(&self, id: WidgetId) -> AccessNodeBuilder {
1060 use crate::widget_builder::AccessSubtreeMode;
1061 let node = self
1062 .arena
1063 .get(id)
1064 .expect("widget id is not in the arena (destroyed?)");
1065 // Every consumer of this builder reads scalars off it — role, name,
1066 // actions, the tri-state flags — and discards it. A name probe so a
1067 // text-bearing widget does not shape and emit runs nobody collects.
1068 let mut builder = AccessNodeBuilder::for_name_probe(id);
1069 node.widget.accessibility(&mut builder);
1070 self.announce_context_menu(id, &mut builder);
1071 self.announce_focusable(id, &mut builder);
1072 // The walker's rule, reached from the other end: it carries the
1073 // composites down to their proxy, this climbs from the node to them.
1074 if self.live_accessibility_proxy(id).is_none() {
1075 let behind = self.composites_standing_behind(id);
1076 for &composite in &behind {
1077 self.announce_context_menu(composite, &mut builder);
1078 }
1079 self.yield_default_name(id, &behind, &mut builder);
1080 self.apply_access_overrides(id, &mut builder);
1081 for composite in behind {
1082 self.apply_access_overrides(composite, &mut builder);
1083 }
1084 }
1085 if node.access_subtree == AccessSubtreeMode::Merge {
1086 merge_descendants_into(&mut builder, id, &self.arena);
1087 }
1088 builder
1089 }
1090
1091 /// Drop a name the widget set with
1092 /// [`AccessNodeBuilder::set_default_name`] when a `labelled_by` relation
1093 /// on the node, or on a composite it stands for, names it instead.
1094 ///
1095 /// The naming order is the one Qt and WinUI follow: a name the
1096 /// application gave (`access_label`, `access_customize`, applied after
1097 /// this) first, then the label the node is linked to, then the control's
1098 /// built-in default. `accesskit_consumer` reads a node's own name before
1099 /// its `labelled_by` targets, so a default left in place would hide the
1100 /// row label of a `FormLayout`: a date field in a "Birthday" row read
1101 /// "Date". A relation whose targets are all gone or nameless names
1102 /// nothing, and then the default stays.
1103 fn yield_default_name(
1104 &self,
1105 id: WidgetId,
1106 standing_for: &[WidgetId],
1107 builder: &mut AccessNodeBuilder,
1108 ) {
1109 if !builder.name_is_default() {
1110 return;
1111 }
1112 let named_by_relation = std::iter::once(id)
1113 .chain(standing_for.iter().copied())
1114 .filter_map(|owner| self.arena.get(owner)?.access_overrides.as_deref())
1115 .flat_map(|ov| ov.labelled_by.iter().copied())
1116 .any(|target| self.has_name_to_give(target));
1117 if named_by_relation {
1118 builder.clear_default_name();
1119 }
1120 }
1121
1122 /// Whether `target`, as the end of a `labelled_by` relation, gives the
1123 /// node pointing at it a name, read as `accesskit_consumer` reads it
1124 /// (`Node::write_label`): a `Role::Label` by its text, any other node by
1125 /// its own name alone, never by its own `labelled_by`.
1126 ///
1127 /// So a target that is not in the update (inactive, or under an excluded
1128 /// or merged ancestor) gives nothing, and neither does one whose own name
1129 /// is a default that yields to a relation of its own: the walk clears it,
1130 /// and the consumer does not follow that target's relation on. A relation
1131 /// that names a composite names the proxy standing for it (see
1132 /// `ProxyLedger::redirect_relations`), so the probe follows the proxy
1133 /// chain and applies the overrides the composites hand down.
1134 pub(crate) fn has_name_to_give(&self, target: WidgetId) -> bool {
1135 self.gives_name(target, &mut Vec::new())
1136 }
1137
1138 fn gives_name(&self, target: WidgetId, visited: &mut Vec<WidgetId>) -> bool {
1139 use crate::widget_builder::AccessSubtreeMode;
1140 if !self.arena.is_active(target) || visited.contains(&target) {
1141 return false;
1142 }
1143 visited.push(target);
1144 // An excluded or merged subtree emits no node for the target.
1145 let mut ancestor = self.arena.parent(target);
1146 while let Some(a) = ancestor {
1147 if self
1148 .arena
1149 .get(a)
1150 .is_some_and(|n| n.access_subtree != AccessSubtreeMode::Inherit)
1151 {
1152 return false;
1153 }
1154 ancestor = self.arena.parent(a);
1155 }
1156 let mut node_id = target;
1157 // A proxy is a strict descendant, so the chain is finite; the bound
1158 // is a guard, not a limit anyone reaches.
1159 for _ in 0..16 {
1160 match self.live_accessibility_proxy(node_id) {
1161 Some(proxy) => node_id = proxy,
1162 None => break,
1163 }
1164 }
1165 let Some(node) = self.arena.get(node_id) else {
1166 return false;
1167 };
1168 let mut builder = AccessNodeBuilder::for_name_probe(node_id);
1169 node.widget.accessibility(&mut builder);
1170 let behind = self.composites_standing_behind(node_id);
1171 if builder.name_is_default() {
1172 let yields = std::iter::once(node_id)
1173 .chain(behind.iter().copied())
1174 .filter_map(|owner| self.arena.get(owner)?.access_overrides.as_deref())
1175 .flat_map(|ov| ov.labelled_by.clone())
1176 .any(|t| self.gives_name(t, visited));
1177 if yields {
1178 builder.clear_default_name();
1179 }
1180 }
1181 self.apply_access_overrides(node_id, &mut builder);
1182 for composite in behind {
1183 self.apply_access_overrides(composite, &mut builder);
1184 }
1185 let non_empty = |s: Option<&str>| s.is_some_and(|s| !s.trim().is_empty());
1186 if builder.role() == accesskit::Role::Label {
1187 // The walker writes a label's text as its value, which is what
1188 // the consumer reads from it.
1189 non_empty(builder.name()) || non_empty(builder.value())
1190 } else {
1191 non_empty(builder.name())
1192 }
1193 }
1194
1195 /// Apply the builder-level overrides attached to `id` onto `builder`.
1196 ///
1197 /// `access_shortcut_id` is resolved here rather than in
1198 /// `AccessibilityOverrides::apply` because the override struct cannot reach
1199 /// the tree's `ShortcutRegistry`. Same mechanism as
1200 /// `MenuItem::for_shortcut(...)`: look up the effective primary keystroke
1201 /// and announce it through `KeyStroke`'s `Display`, or nothing when the id
1202 /// has no registered default.
1203 fn apply_access_overrides(&self, id: WidgetId, builder: &mut AccessNodeBuilder) {
1204 let Some(ov) = self
1205 .arena
1206 .get(id)
1207 .and_then(|node| node.access_overrides.as_deref())
1208 else {
1209 return;
1210 };
1211 ov.apply(builder);
1212 if let Some(ref sid) = ov.shortcut_id
1213 && let Some(eff) = self.shortcut_registry.effective(sid)
1214 && let Some(ks) = eff.primary
1215 {
1216 builder.set_keyboard_shortcut(ks.to_string());
1217 }
1218 }
1219
1220 /// The descendant `id` hands its accessibility node to, if it names one
1221 /// the walk will honour: see [`Widget::accessibility_proxy`].
1222 ///
1223 /// A strict, live descendant that the walk reaches: `id` and every widget
1224 /// between the two walked normally. An excluded or merged subtree emits no
1225 /// node for the proxy to carry anything on, wherever it sits on the way
1226 /// down, so the overrides stay where they were attached.
1227 pub(crate) fn live_accessibility_proxy(&self, id: WidgetId) -> Option<WidgetId> {
1228 use crate::widget_builder::AccessSubtreeMode;
1229 let node = self.arena.get(id)?;
1230 if node.access_subtree != AccessSubtreeMode::Inherit {
1231 return None;
1232 }
1233 let proxy = node.widget.accessibility_proxy()?;
1234 if proxy == id || !self.arena.is_active(proxy) {
1235 return None;
1236 }
1237 // Climb from the proxy to `id`, which is the descendant check, and
1238 // refuse at the first widget in between that stops the walk.
1239 let mut current = self.arena.parent(proxy);
1240 while let Some(ancestor) = current {
1241 if ancestor == id {
1242 return Some(proxy);
1243 }
1244 if self.arena.get(ancestor)?.access_subtree != AccessSubtreeMode::Inherit {
1245 return None;
1246 }
1247 current = self.arena.parent(ancestor);
1248 }
1249 None
1250 }
1251
1252 /// The composites whose node `id` stands for, innermost first: the order
1253 /// the walker applies their overrides in, so the outermost, which is the
1254 /// one an application attached last, wins.
1255 ///
1256 /// A composite can name another composite as its proxy, which names a
1257 /// field in turn, so the climb follows the chain rather than stopping at
1258 /// the first match.
1259 ///
1260 /// Two composites can also name the same proxy (a `DateEdit` and the
1261 /// `TextInput` inside it both name the field), so an ancestor counts when
1262 /// its proxy is `id` or any composite already found.
1263 pub(crate) fn composites_standing_behind(&self, id: WidgetId) -> Vec<WidgetId> {
1264 let mut found = Vec::new();
1265 let mut current = self.arena.parent(id);
1266 while let Some(ancestor) = current {
1267 if let Some(proxy) = self.live_accessibility_proxy(ancestor)
1268 && (proxy == id || found.contains(&proxy))
1269 {
1270 found.push(ancestor);
1271 }
1272 current = self.arena.parent(ancestor);
1273 }
1274 found
1275 }
1276
1277 /// The composite an assistive `Focus` on `id` gives the keyboard to: the
1278 /// innermost focusable, enabled composite `id` stands for, when `id` is not
1279 /// focusable itself.
1280 ///
1281 /// An editor publishes its text on a body the keyboard never lands on, and
1282 /// that body is the node a screen reader sees, and the one it asks to
1283 /// focus. Parking the keyboard there would pass the keys up to the editor
1284 /// by bubbling but run none of its focus handlers, so no caret, no input
1285 /// method and no focus ring; and asking again while the editor holds focus
1286 /// would take focus away from it.
1287 ///
1288 /// Anything that gives the keyboard to a widget it found through the
1289 /// accessibility tree asks this first: the router does for an assistive
1290 /// `Focus`, and the automation toolkit does before it types.
1291 pub fn focusable_composite_behind(&self, id: WidgetId) -> Option<WidgetId> {
1292 if self
1293 .arena
1294 .get(id)
1295 .is_none_or(|node| self.is_node_focusable(node))
1296 {
1297 return None;
1298 }
1299 self.composites_standing_behind(id)
1300 .into_iter()
1301 .find(|&composite| {
1302 self.arena.is_enabled(composite)
1303 && self
1304 .arena
1305 .get(composite)
1306 .is_some_and(|node| self.is_node_focusable(node))
1307 })
1308 }
1309
1310 /// The `access_disabled` override in force on `id`'s node: its own, unless
1311 /// it handed its node to a proxy, then those of the composites it stands
1312 /// for, the last one set winning as it does for every scalar override.
1313 pub(crate) fn access_disabled_override(
1314 &self,
1315 id: WidgetId,
1316 handed_on: bool,
1317 standing_for: &[WidgetId],
1318 ) -> Option<bool> {
1319 if handed_on {
1320 return None;
1321 }
1322 std::iter::once(id)
1323 .chain(standing_for.iter().copied())
1324 .filter_map(|w| {
1325 self.arena
1326 .get(w)
1327 .and_then(|node| node.access_overrides.as_deref())
1328 .and_then(|ov| ov.disabled)
1329 })
1330 .last()
1331 }
1332
1333 /// The tooltip a composite that hands its node to a proxy should hand on
1334 /// with it: the one it owns, when it owns exactly one, or else one
1335 /// anchored on it. The same claim `tooltip_description_target` grants an
1336 /// owner, without the checks on the node, which are the proxy's to pass.
1337 fn tooltip_claim_for_proxy(
1338 &self,
1339 id: WidgetId,
1340 handled: &std::collections::HashSet<WidgetId>,
1341 ) -> Option<WidgetId> {
1342 let mut claims = self
1343 .tooltips
1344 .iter()
1345 .filter(|t| t.description_owner_id == id && !handled.contains(&t.content_id));
1346 if let (Some(only), None) = (claims.next(), claims.next()) {
1347 return Some(only.content_id);
1348 }
1349 self.tooltips
1350 .iter()
1351 .find(|t| t.anchor_id == id && !handled.contains(&t.content_id))
1352 .map(|t| t.content_id)
1353 }
1354}
1355
1356/// What composites hand down, during one walk, to the descendants that stand
1357/// for them in the accessibility tree ([`Widget::accessibility_proxy`]).
1358///
1359/// The walk visits a composite before its proxy, so the composite leaves its
1360/// share here and the proxy collects it when the walk arrives.
1361#[derive(Default)]
1362pub(super) struct ProxyLedger {
1363 /// For each proxy, the composites it stands for, innermost first.
1364 standing_for: std::collections::HashMap<WidgetId, Vec<WidgetId>>,
1365 /// The tooltip a composite owned, kept for its proxy.
1366 tooltips: std::collections::HashMap<WidgetId, WidgetId>,
1367 /// Each composite's node, and the node of the proxy standing for it.
1368 nodes: std::collections::HashMap<accesskit::NodeId, accesskit::NodeId>,
1369}
1370
1371impl ProxyLedger {
1372 /// The node standing for `nid`, through any chain of composites: `nid`
1373 /// itself when no composite handed it on.
1374 fn stand_in(&self, mut nid: accesskit::NodeId) -> accesskit::NodeId {
1375 // A proxy is a strict descendant, so a chain never loops; the bound is
1376 // there so that cannot be assumed.
1377 for _ in 0..self.nodes.len() {
1378 match self.nodes.get(&nid) {
1379 Some(&next) => nid = next,
1380 None => break,
1381 }
1382 }
1383 nid
1384 }
1385
1386 /// Point every `controls`, `described_by` and `labelled_by` target that
1387 /// names a composite at the node standing for it, through any chain of
1388 /// composites.
1389 fn redirect_relations(&self, nodes: &mut [(accesskit::NodeId, accesskit::Node)]) {
1390 if self.nodes.is_empty() {
1391 return;
1392 }
1393 let redirected = |ids: &[accesskit::NodeId]| {
1394 ids.iter()
1395 .any(|id| self.nodes.contains_key(id))
1396 .then(|| ids.iter().map(|&id| self.stand_in(id)).collect::<Vec<_>>())
1397 };
1398 for (_, node) in nodes.iter_mut() {
1399 if let Some(ids) = redirected(node.controls()) {
1400 node.set_controls(ids);
1401 }
1402 if let Some(ids) = redirected(node.described_by()) {
1403 node.set_described_by(ids);
1404 }
1405 if let Some(ids) = redirected(node.labelled_by()) {
1406 node.set_labelled_by(ids);
1407 }
1408 }
1409 }
1410}
1411
1412/// Whether an AT node is a purely-structural container that should be
1413/// collapsed out of the tree (its children promoted to its parent).
1414///
1415/// True only for a content-free `GenericContainer` / `Unknown` node — the
1416/// empty boxes layout primitives (HStack/VStack/Padding/Expand/…) emit.
1417/// The check is exhaustive by construction: set aside the framework-applied
1418/// children, bounds, and disabled flag, then compare against a fresh
1419/// default node of the same role. Any author- or widget-set property —
1420/// name, value, description, orientation, aria-current, identifier, live
1421/// region, popup, action, relation, hidden flag, … — makes the node differ
1422/// from the default and keeps it, so no semantic property can be missed.
1423/// Callers additionally exempt the Window root, the focused node, and
1424/// relationship targets.
1425fn is_presentational_container(node: &accesskit::Node) -> bool {
1426 use accesskit::Role;
1427 if !matches!(node.role(), Role::GenericContainer | Role::Unknown) {
1428 return false;
1429 }
1430 // Set aside the framework-applied structural bits (children, bounds,
1431 // arena-driven disabled flag), then check the node carries no semantic
1432 // content by comparing against a bare node of the same role.
1433 //
1434 // We compare the *Debug* form, not `==`: AccessKit's `clear_*` leaves
1435 // residue in the private property-value vec (the index is unset but the
1436 // value stays), so `PartialEq` never matches a fresh node. `Node`'s
1437 // Debug renders only logically-set properties, so it reflects true
1438 // content and is exhaustive — any author/widget property keeps the node.
1439 let mut probe = node.clone();
1440 probe.clear_children();
1441 probe.clear_bounds();
1442 probe.clear_disabled();
1443 format!("{probe:?}") == format!("{:?}", accesskit::Node::new(node.role()))
1444}
1445
1446// ─────────────────────────────────────────────────────────────────────
1447// Subtree-merge helpers
1448// ─────────────────────────────────────────────────────────────────────
1449//
1450// These run when a widget's `access_subtree` is `Merge`. The walker
1451// recurses through the descendants, applies each descendant's own
1452// `accessibility() + override apply()` into a temp builder, and absorbs
1453// the resulting label / value / actions into a `MergeAccumulator`.
1454// After the walk finishes the accumulator flushes its accumulated state
1455// onto the parent's builder.
1456//
1457// The accumulator deliberately discards descendant role and numeric
1458// fields (parent's role wins for the merged element) and discards
1459// disabled (parent's state governs the whole merged subtree). A hidden
1460// descendant is not merged at all, and neither is its subtree.
1461// Action lists union with deduplication so two child Buttons each
1462// emitting `Click` don't pollute the merged parent with two copies.
1463
1464/// Walk the descendants of `parent_id` and absorb their label / value /
1465/// actions into `parent_builder`. Per-descendant subtree-mode handling
1466/// lives in [`merge_collect_recursive`].
1467fn merge_descendants_into(
1468 parent_builder: &mut AccessNodeBuilder,
1469 parent_id: WidgetId,
1470 arena: &crate::arena::WidgetArena,
1471) {
1472 let mut acc = MergeAccumulator::default();
1473 for &child in arena.children(parent_id) {
1474 merge_collect_recursive(child, arena, &mut acc);
1475 }
1476 acc.flush_into(parent_builder);
1477}
1478
1479fn merge_collect_recursive(
1480 id: WidgetId,
1481 arena: &crate::arena::WidgetArena,
1482 acc: &mut MergeAccumulator,
1483) {
1484 use crate::widget_builder::AccessSubtreeMode;
1485
1486 if !arena.is_active(id) {
1487 return;
1488 }
1489 let Some(node) = arena.get(id) else {
1490 return;
1491 };
1492
1493 // Build a temp builder for this descendant the same way the walker
1494 // would: widget.accessibility() then override apply(). This means
1495 // a descendant's `.access_label(...)` contributes its resolved
1496 // override string, not its raw widget label.
1497 // A name probe: `absorb` takes the descendant's name, value, actions and
1498 // relations, never its synthetic children — and the runs a text widget
1499 // would emit here would be discarded with `tmp` while the widget's own
1500 // node keeps its copies.
1501 let mut tmp = AccessNodeBuilder::for_name_probe(id);
1502 node.widget.accessibility(&mut tmp);
1503 if let Some(ov) = node.access_overrides.as_deref() {
1504 ov.apply(&mut tmp);
1505 }
1506 // Nested-merge: the descendant itself has access_subtree=Merge.
1507 // Run its own merge into `tmp` BEFORE absorbing — otherwise we'd
1508 // absorb the descendant's empty container state and lose its
1509 // subtree-merged label.
1510 if matches!(node.access_subtree, AccessSubtreeMode::Merge) {
1511 merge_descendants_into(&mut tmp, id, arena);
1512 }
1513 // Skip nodes that opted out of AT entirely: a child marked
1514 // `access_hidden(true)` (or whose widget called `set_hidden()`)
1515 // contributes nothing to the merge, and neither does anything under it.
1516 // The consumer the adapters read through treats a node as hidden when
1517 // any ancestor is, so text below a hidden node is text the widget hid;
1518 // merging it would say it aloud on the merged node.
1519 if tmp.is_hidden() {
1520 return;
1521 }
1522 acc.absorb(&tmp);
1523
1524 match node.access_subtree {
1525 AccessSubtreeMode::Exclude => {
1526 // Prune — don't recurse into descendants of an excluded subtree.
1527 }
1528 AccessSubtreeMode::Merge => {
1529 // Nested Merge: descendant's own subtree was absorbed into
1530 // `tmp` above; don't re-walk its children at this level
1531 // (would double-count). The descendant reads as one
1532 // AT element from the outer merge's perspective.
1533 }
1534 AccessSubtreeMode::Inherit => {
1535 for &grandchild in arena.children(id) {
1536 merge_collect_recursive(grandchild, arena, acc);
1537 }
1538 }
1539 }
1540}
1541
1542/// Per-merge-walk accumulator. Collects descendant state across the
1543/// recursive walk, then `flush_into` writes the unioned values onto
1544/// the parent's builder.
1545///
1546/// Fields that the absorb path can read from `AccessNodeBuilder`
1547/// (label, value, advertised actions) participate in the merge.
1548/// Description and relationship lists (`controls` / `described_by` /
1549/// `labelled_by`) live inside `accesskit::Node` and have no public
1550/// getter on `AccessNodeBuilder`; merging them would require
1551/// reflecting builder mutations into a parallel field, which we
1552/// haven't found a real-world use case for. App authors who need
1553/// description / relationship merge can use the `access_customize`
1554/// escape hatch on the parent.
1555#[derive(Default)]
1556struct MergeAccumulator {
1557 label_parts: Vec<String>,
1558 /// First non-empty value wins.
1559 value: Option<String>,
1560 actions: Vec<accesskit::Action>,
1561}
1562
1563impl MergeAccumulator {
1564 fn absorb(&mut self, src: &AccessNodeBuilder) {
1565 if let Some(name) = src.name()
1566 && !name.is_empty()
1567 {
1568 self.label_parts.push(name.to_string());
1569 }
1570 if let Some(value) = src.value()
1571 && self.value.is_none()
1572 && !value.is_empty()
1573 {
1574 self.value = Some(value.to_string());
1575 }
1576 for &action in src.actions() {
1577 if !self.actions.contains(&action) {
1578 self.actions.push(action);
1579 }
1580 }
1581 }
1582
1583 fn flush_into(self, dst: &mut AccessNodeBuilder) {
1584 // Concatenate new label parts onto whatever the parent's
1585 // builder already carried. Existing parent name kept first.
1586 if !self.label_parts.is_empty() {
1587 let existing = dst.name().map(|s| s.to_string());
1588 let merged = match existing {
1589 Some(e) if !e.is_empty() => {
1590 let mut s = e;
1591 for part in self.label_parts {
1592 s.push(' ');
1593 s.push_str(&part);
1594 }
1595 s
1596 }
1597 _ => self.label_parts.join(" "),
1598 };
1599 dst.set_name(merged);
1600 }
1601 if let Some(v) = self.value {
1602 // Only overwrite parent value if it's currently None — the
1603 // parent's own value (from the inner widget or override
1604 // `access_value`) takes precedence.
1605 if dst.value().is_none() {
1606 dst.set_value(v);
1607 }
1608 }
1609 for action in self.actions {
1610 // Union: skip actions already advertised on the parent
1611 // (avoid duplicate Click/Focus when parent is itself a Button).
1612 if !dst.actions().contains(&action) {
1613 dst.add_action(action);
1614 }
1615 }
1616 }
1617}