Skip to main content

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