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