Skip to main content

gpui/window/
a11y.rs

1//! Accessibility support, provided by [AccessKit][accesskit].
2//!
3//! There are user-facing guide-level docs [here](crate::_accessibility).
4//!
5//! ## Architecture
6//!
7//! ```text
8//!                              ┌────────────────────────────────┐   ┌─────────────────────┐
9//!                           ┌─▶│ AccessKit Adapter (MacOS)      │◀─▶│ MacOS System APIs   │
10//!                           │  └────────────────────────────────┘   └─────────────────────┘
11//!                           │
12//! ┌──────┐   ┌───────────┐  │  ┌────────────────────────────────┐   ┌─────────────────────┐
13//! │ GPUI │◀─▶│ AccessKit │◀─┼─▶│ AccessKit Adapter (Windows)    │◀─▶│ Windows System APIs │
14//! └──────┘   └───────────┘  │  └────────────────────────────────┘   └─────────────────────┘
15//!                           │
16//!                           │  ┌────────────────────────────────┐   ┌─────────────────────┐
17//!                           └─▶│ AccessKit Adapter (Linux)      │◀─▶│ dbus                │
18//!                              └────────────────────────────────┘   └─────────────────────┘
19//! ```
20//!
21//! In order for GPUI apps to be usable for people using assistive technology,
22//! we must do a few things:
23//! - Inform the system when the UI changes meaningfully. This includes:
24//!   - Reporting new/removed/changed UI elements
25//!   - *Not* reporting irrelevant UI changes, e.g. an invisible `div()` being
26//!     added.
27//!   - Reporting the appearance and capabilities of each UI element. For example:
28//!     - What does this piece of text say?
29//!     - How far along is this progress bar?
30//!     - Can this node be focused?
31//!     - Can this node have a value directly assigned? (e.g. a slider)
32//! - Allowing the system to interact with the UI by dispatching actions to
33//!   nodes. Note that AccessKit has its own [`Action`] type, which is not the
34//!   [`crate::Action`] trait.
35//! - Activate and deactivate accessibility features when requested by the
36//!   system.
37//!
38//! Activating and deactivating at the right time is trivial, so I won't go into
39//! detail here. The other two are almost orthogonal in implementation.
40//!
41//! The state for both lives in the [`A11y`] struct in this module.
42//!
43//! ### Reporting UI changes
44//!
45//! Every frame, we build a [`TreeUpdate`] and send it to the platform-specific
46//! adapter. A [`TreeUpdate`] is a representation of a subset of the UI tree.
47//! When the adapter receives the update, it diffs it against the previous
48//! update, and calls platform-specific APIs to inform screen readers about the
49//! changes. Nodes may have been created, destroyed, or updated.
50//!
51//! Each node has an ID, and this ID *should* be stable across frames. If a
52//! node's ID changes, then, from AccessKit's point of view, it is a different
53//! node.
54//!
55//! We derive the node ID from the [`GlobalElementId`] in
56//! [`GlobalElementId::accesskit_node_id`]. Nodes without [`GlobalElementId`]s
57//! cannot produce an AccessKit [`NodeId`], and so are not included in the
58//! accessibility tree. We try to warn when using accessibility APIs on
59//! [`div()`] without setting an ID.
60//!
61//! This all happens in [`Drawable::prepaint`]. The [`A11y`] struct maintains a
62//! stack of nodes during prepainting, which we can use to calculate the
63//! [`NodeId`]s, and record parent-child relationships. Once all [`Element`]s in
64//! a frame have been prepainted, we send the resulting [`TreeUpdate`] object to
65//! the adapter and the screen reader can announce the changes.
66//!
67//! #### Synthetic children
68//!
69//! Additionally, some nodes can register "synthetic children" using
70//! [`Element::a11y_synthetic_children`]. Normally, one accesskit node is pushed
71//! for every [`Element`] with a role and id. However, sometimes a single
72//! element may want to produce many accesskit nodes. These extra nodes are
73//! referred to as "synthetic children" of the element providing a non-default
74//! [`Element::a11y_synthetic_children`] implementation.
75//!
76//! The user is provided a builder-style API using [`A11ySubtreeBuilder`], which
77//! allows them to create push nodes that are children of the current node, as
78//! well as modify the current node itself.
79//!
80//! GPUI calls this callback *after* prepainting (and just before popping the
81//! corresponding element), since this step may need prepaint information to be
82//! available. In the future, we may want to add prepaint information more
83//! generally to [`Element::write_a11y_info`], but for now that's not necessary.
84//!
85//! ### Responding to actions
86//!
87//! On adapter creation, we provide a callback to the adapter, which can be used
88//! to dispatch actions. This callback forwards to [`A11y::action_listeners`], a
89//! mapping from [`NodeId`]s to action handlers (basically just `Box<dyn
90//! Fn()>`).
91//!
92//! This is populated in:
93//! - [`Window::on_a11y_action`], which is called by:
94//! - [`Interactivity::paint`], which is called by:
95//! - [`StatefulInteractiveElement::on_a11y_action`], which is a public-facing API
96//!
97//! These are cleared at the start of a frame, and re-populated during painting.
98//!
99//! [`NodeId`]: accesskit::NodeId
100
101use crate::*;
102
103pub(crate) mod debug;
104
105use crate::{App, Bounds, FocusId, Pixels, SharedString, Window};
106use accesskit::{Action, NodeId, TreeUpdate};
107use collections::{FxHashMap, FxHashSet};
108use smallvec::SmallVec;
109use std::hash::{Hash, Hasher};
110use std::sync::{
111    Arc,
112    atomic::{AtomicBool, Ordering},
113};
114
115/// The fixed AccessKit node ID used for the root of every window's a11y tree.
116pub(crate) const ROOT_NODE_ID: NodeId = NodeId(0);
117
118/// A listener for an accessibility action on a specific node.
119pub(crate) type A11yActionListener =
120    Box<dyn FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static>;
121
122/// Per-window accessibility state.
123///
124/// Manages the AccessKit tree that is built each frame and the mappings
125/// needed to dispatch incoming action requests back to the right elements.
126pub(crate) struct A11y {
127    /// Whether accessibility has been [forcibly disabled] for this window.
128    ///
129    /// [forcibly disabled]: crate::Application::new_inaccessible
130    force_disabled: bool,
131    /// Whether a11y features have been requested by the system.
132    ///
133    /// Updated by AccessKit using callbacks provided to the adapter. Can change
134    /// halfway through a frame.
135    active_flag: Arc<AtomicBool>,
136    /// Whether a11y features are active for *this specific frame*.
137    ///
138    /// At the start of each frame, we load [`Self::active_flag`] (using
139    /// [`Self::sync_active_flag`]) and use this to determine whether we
140    /// should construct a [`TreeUpdate`] for this frame. It's important that
141    /// this value is stable within a frame, because the builder API exposed by
142    /// this type maintains a stack of nodes and each must be pushed and popped
143    /// exactly once.
144    ///
145    /// At the end of the frame, we re-call [`Self::sync_active_flag`] to
146    /// determine whether we should actually send the finished [`TreeUpdate`].
147    active_this_frame: bool,
148    pub(crate) nodes: A11yNodeBuilder,
149    pub(crate) focus_ids: FxHashMap<NodeId, FocusId>,
150    pub(crate) node_bounds: FxHashMap<NodeId, Bounds<Pixels>>,
151    pub(crate) action_listeners: FxHashMap<NodeId, Vec<(Action, A11yActionListener)>>,
152    /// The window's title, used to label the root node so assistive
153    /// technology can tell windows apart.
154    window_title: Option<SharedString>,
155    /// The focus id we most recently reported as having no accessibility node,
156    /// used to log at most once per focus change rather than every frame.
157    last_focus_without_node: Option<FocusId>,
158    /// Retains the last tree update (and, in debug builds, per-node provenance)
159    /// so it can be dumped via [`crate::Window::debug_a11y_tree_json`].
160    debug: debug::A11yDebug,
161    /// Maps a view's [`EntityId`] to its `Render` type name
162    #[cfg(debug_assertions)]
163    pub(crate) view_type_names: FxHashMap<EntityId, &'static str>,
164}
165
166impl A11y {
167    pub(crate) fn new(
168        active_flag: Arc<AtomicBool>,
169        force_disabled: bool,
170        window_title: Option<SharedString>,
171    ) -> Self {
172        Self {
173            force_disabled,
174            active_flag,
175            active_this_frame: false,
176            nodes: A11yNodeBuilder::new(),
177            focus_ids: FxHashMap::default(),
178            node_bounds: FxHashMap::default(),
179            action_listeners: FxHashMap::default(),
180            window_title,
181            last_focus_without_node: None,
182            debug: debug::A11yDebug::default(),
183            #[cfg(debug_assertions)]
184            view_type_names: FxHashMap::default(),
185        }
186    }
187
188    /// Logs (once per focus change) that the focused element is not exposed to
189    /// assistive technology because it has no accessibility node. When this
190    /// happens, screen readers fall back to announcing the whole window instead
191    /// of the focused element. The fix is to give the element both an
192    /// `.id(...)` and a `.role(...)`.
193    pub(crate) fn note_focus_without_node(&mut self, focus_id: FocusId, reason: &str) {
194        if self.last_focus_without_node != Some(focus_id) {
195            self.last_focus_without_node = Some(focus_id);
196            log::info!(
197                "a11y: focused element ({focus_id:?}) has no accessibility node \
198                 ({reason}); assistive technology will announce the whole window \
199                 instead. Give it both an `.id(...)` and a `.role(...)` to expose it."
200            );
201        }
202    }
203
204    pub(crate) fn set_window_title(&mut self, title: impl Into<SharedString>) {
205        self.window_title = Some(title.into());
206    }
207
208    /// Ensures that [`Self::is_active`] returns up to date information.
209    ///
210    /// See the docs for [`Self::active_flag`] and [`Self::active_this_frame`]
211    /// for more commentary.
212    pub(crate) fn sync_active_flag(&mut self) {
213        self.active_this_frame = self.is_enabled() && self.active_flag.load(Ordering::SeqCst);
214    }
215
216    pub(crate) fn is_enabled(&self) -> bool {
217        !self.force_disabled
218    }
219
220    pub(crate) fn is_active(&self) -> bool {
221        self.active_this_frame
222    }
223
224    pub(crate) fn set_focusable(&mut self, node_id: NodeId, focus_id: FocusId) {
225        self.focus_ids.insert(node_id, focus_id);
226    }
227
228    /// Report `node_id` as the currently-focused node, if it is present in the
229    /// tree.
230    ///
231    /// Must only be called once per frame.
232    pub(crate) fn set_focus(&mut self, node_id: NodeId) {
233        // A focused node must have been registered as focusable this frame.
234        if !self.focus_ids.contains_key(&node_id) {
235            if cfg!(debug_assertions) {
236                panic!("set_focus called for a node that was not registered with set_focusable");
237            } else {
238                log::warn!(
239                    "a11y: set_focus called for a node that was not registered with \
240                     set_focusable ({node_id:?})"
241                );
242            }
243        }
244        if self.nodes.has_node(node_id) {
245            // The focused element is properly exposed; reset the dedup so a
246            // later focus on a node-less element logs again.
247            self.last_focus_without_node = None;
248            self.nodes.set_focus(node_id);
249        } else {
250            // The element registered a focus handle and an id, but never got a
251            // node because it has no role.
252            if let Some(focus_id) = self.focus_ids.get(&node_id).copied() {
253                self.note_focus_without_node(focus_id, "it has an id but no role");
254            }
255        }
256    }
257
258    pub(crate) fn set_active_descendant(&mut self, node_id: NodeId) {
259        // The active descendant must be a descendant of the focused container,
260        // not the focused node itself.
261        if self.nodes.node_is_focused(node_id) {
262            if cfg!(debug_assertions) {
263                panic!("set_active_descendant called on the focused node");
264            } else {
265                log::warn!("a11y: set_active_descendant called on the focused node ({node_id:?})");
266            }
267            return;
268        }
269        if self.nodes.has_node(node_id) && self.nodes.focus_is_ancestor_of_current() {
270            self.nodes.set_active_descendant(node_id);
271        }
272    }
273
274    /// Clear per-frame state and push the root node to start a new frame.
275    pub(crate) fn begin_frame(&mut self) {
276        self.focus_ids.clear();
277        self.node_bounds.clear();
278        self.action_listeners.clear();
279        self.nodes.begin_frame(self.window_title.as_ref());
280    }
281
282    /// Finalize the tree and produce a [`TreeUpdate`] for the platform adapter.
283    pub(crate) fn end_frame(&mut self, frame: debug::FrameDebugInfo) -> TreeUpdate {
284        let update = self.nodes.finalize();
285        self.debug.capture(
286            &update,
287            self.nodes.focus,
288            self.nodes.active_descendant,
289            self.window_title.as_ref(),
290            frame,
291        );
292        #[cfg(debug_assertions)]
293        self.debug.capture_node_info(&self.nodes.node_info);
294        update
295    }
296
297    pub(crate) fn debug_tree_json(&self) -> Option<String> {
298        self.debug.to_json()
299    }
300}
301
302/// Builder API for synthetic children. See the docs for
303/// [`Element::a11y_synthetic_children`].
304pub struct A11ySubtreeBuilder<'a> {
305    parent_id: NodeId,
306    nodes: &'a mut A11yNodeBuilder,
307    /// Provenance of the real element whose `a11y_synthetic_children` is
308    /// running.
309    #[cfg(debug_assertions)]
310    creator: debug::NodeCreator,
311}
312
313impl<'a> A11ySubtreeBuilder<'a> {
314    pub(crate) fn new(parent_id: NodeId, nodes: &'a mut A11yNodeBuilder) -> Self {
315        Self {
316            parent_id,
317            nodes,
318            #[cfg(debug_assertions)]
319            creator: debug::NodeCreator::default(),
320        }
321    }
322
323    #[cfg(debug_assertions)]
324    pub(crate) fn with_creator(mut self, creator: debug::NodeCreator) -> Self {
325        self.creator = creator;
326        self
327    }
328
329    /// Derive a [`NodeId`] for a synthetic child.
330    ///
331    /// The generated ID is based on the hash of `key`, as well as the parent's
332    /// ID. This means that `key`s must be unique within the same
333    /// [`Element::a11y_synthetic_children`] call, but may be duplicated across
334    /// different calls.
335    pub fn synthetic_node_id(&self, key: impl Hash) -> NodeId {
336        let mut hasher = std::hash::DefaultHasher::default();
337        self.parent_id.0.hash(&mut hasher);
338        key.hash(&mut hasher);
339        NodeId(hasher.finish())
340    }
341
342    /// Append a synthetic leaf node as a child of this element's node.
343    ///
344    /// Returns `false` if a node with this id is already present in the tree,
345    /// in which case the node is discarded.
346    pub fn push_child(&mut self, id: NodeId, node: accesskit::Node) -> bool {
347        let pushed = self.nodes.push_leaf(id, node);
348        #[cfg(debug_assertions)]
349        if pushed {
350            self.nodes.record_node_info(
351                id,
352                debug::NodeDebugInfo {
353                    synthetic: true,
354                    view: self.creator.view,
355                    element_id: self.creator.element_id.clone(),
356                    source_location: self.creator.source_location,
357                },
358            );
359        }
360        pushed
361    }
362
363    /// A mutable reference to the parent node.
364    pub fn parent_node(&mut self) -> &mut accesskit::Node {
365        self.nodes
366            .current_node_mut()
367            .expect("A11ySubtreeBuilder exists only while its element's node is on the stack")
368    }
369}
370
371pub(crate) struct A11yNodeBuilder {
372    ids_stack: SmallVec<[NodeId; 16]>,
373    nodes_stack: SmallVec<[accesskit::Node; 16]>,
374    /// This is the exact type required by accesskit, so we can't just make it a
375    /// `HashMap<NodeId, Node>` to remove the need for `seen_ids`
376    all_nodes: Vec<(NodeId, accesskit::Node)>,
377    seen_ids: FxHashSet<NodeId>,
378    /// The node that GPUI considers focused. Note that this may be different to
379    /// what is reported to accesskit - see [`Self::active_descendant`]
380    focus: Option<NodeId>,
381    /// If a node calls `.aria_active_descendant()`, AND an ancestor is focused,
382    /// override it as the focused node. This supports the "active descendant"
383    /// pattern, which allows a focused container to act as if a descendant is
384    /// focused.
385    active_descendant: Option<NodeId>,
386    /// vue-native fork: `(parent, child)` pairs from deferred draws (see
387    /// [`Self::begin_adopted`]), linked in [`Self::finalize`].
388    adoptions: Vec<(NodeId, NodeId)>,
389    #[cfg(debug_assertions)]
390    node_info: FxHashMap<NodeId, debug::NodeDebugInfo>,
391}
392
393impl A11yNodeBuilder {
394    fn new() -> Self {
395        Self {
396            ids_stack: SmallVec::new(),
397            nodes_stack: SmallVec::new(),
398            all_nodes: Vec::new(),
399            seen_ids: FxHashSet::default(),
400            focus: None,
401            active_descendant: None,
402            adoptions: Vec::new(),
403            #[cfg(debug_assertions)]
404            node_info: FxHashMap::default(),
405        }
406    }
407
408    /// Records provenance for a node already pushed this frame. Debug builds only.
409    #[cfg(debug_assertions)]
410    pub(crate) fn record_node_info(&mut self, id: NodeId, info: debug::NodeDebugInfo) {
411        self.node_info.insert(id, info);
412    }
413
414    #[must_use]
415    fn can_push(&mut self, id: NodeId) -> bool {
416        debug_assert!(!self.ids_stack.is_empty(), "node pushed before push_root");
417
418        if !self.seen_ids.insert(id) {
419            debug_assert!(
420                false,
421                "Duplicate a11y node id: {id:?}. In a release build, this node would be silently discarded from the a11y tree."
422            );
423            return false;
424        }
425
426        true
427    }
428
429    /// Push a new node onto the stack. It becomes a child of the current
430    /// top-of-stack node.
431    ///
432    /// Returns `true` if the node was successfully pushed.
433    pub(crate) fn push(&mut self, id: NodeId, node: accesskit::Node) -> bool {
434        if !self.can_push(id) {
435            return false;
436        }
437
438        if let Some(parent) = self.nodes_stack.last_mut() {
439            parent.push_child(id);
440        }
441        self.ids_stack.push(id);
442        self.nodes_stack.push(node);
443        true
444    }
445
446    /// Add a leaf node as a child of the current top-of-stack node, without
447    /// pushing it onto the stack. Semantically equivalent to a [`Self::push`]
448    /// followed by a [`Self::pop`].
449    ///
450    /// Returns `true` if the node was successfully pushed.
451    pub(crate) fn push_leaf(&mut self, id: NodeId, node: accesskit::Node) -> bool {
452        if !self.can_push(id) {
453            return false;
454        }
455
456        if let Some(parent) = self.nodes_stack.last_mut() {
457            parent.push_child(id);
458        }
459        self.all_nodes.push((id, node));
460        true
461    }
462
463    pub(crate) fn current_node_mut(&mut self) -> Option<&mut accesskit::Node> {
464        self.nodes_stack.last_mut()
465    }
466
467    /// vue-native fork: the node on top of the stack, which a node pushed now
468    /// would become a child of. `Window::defer_draw` records it.
469    pub(crate) fn current_id(&self) -> NodeId {
470        self.ids_stack.last().copied().unwrap_or(ROOT_NODE_ID)
471    }
472
473    /// vue-native fork: starts prepainting a deferred draw that was deferred
474    /// while `parent` was on top of the stack.
475    ///
476    /// A deferred draw is prepainted after the whole tree, when only the root
477    /// is left on the stack, so its nodes used to hang off the window root: a
478    /// dialog's absolutely positioned Close button was the dialog's sibling.
479    /// `parent` was finalized long ago, so a stand-in carrying its id collects
480    /// the children here, and [`Self::finalize`] links them to it.
481    pub(crate) fn begin_adopted(&mut self, parent: NodeId) {
482        self.ids_stack.push(parent);
483        self.nodes_stack
484            .push(accesskit::Node::new(accesskit::Role::GenericContainer));
485    }
486
487    /// vue-native fork: ends what [`Self::begin_adopted`] began.
488    pub(crate) fn end_adopted(&mut self) {
489        if let (Some(parent), Some(stand_in)) = (self.ids_stack.pop(), self.nodes_stack.pop()) {
490            self.adoptions
491                .extend(stand_in.children().iter().map(|&child| (parent, child)));
492        }
493    }
494
495    /// vue-native fork: gives every adopted child to its parent, after the
496    /// parent's own children. A parent that is not in the tree after all
497    /// leaves the child on the root, where it would have been anyway.
498    fn link_adoptions(&mut self) {
499        if self.adoptions.is_empty() {
500            return;
501        }
502        let index: FxHashMap<NodeId, usize> = self
503            .all_nodes
504            .iter()
505            .enumerate()
506            .map(|(ix, (id, _))| (*id, ix))
507            .collect();
508        for (parent, child) in std::mem::take(&mut self.adoptions) {
509            let ix = index
510                .get(&parent)
511                .or_else(|| index.get(&ROOT_NODE_ID))
512                .copied();
513            if let Some(ix) = ix {
514                self.all_nodes[ix].1.push_child(child);
515            }
516        }
517    }
518
519    /// Pop the current node off the stack and finalize it into the all_nodes
520    /// list.
521    pub(crate) fn pop(&mut self) {
522        debug_assert!(self.ids_stack.len() > 1, "pop would remove the root node");
523
524        if let (Some(id), Some(node)) = (self.ids_stack.pop(), self.nodes_stack.pop()) {
525            self.all_nodes.push((id, node));
526        }
527    }
528
529    /// Push the root node to start a new frame.
530    fn begin_frame(&mut self, window_title: Option<&SharedString>) {
531        self.all_nodes.clear();
532        self.ids_stack.clear();
533        self.nodes_stack.clear();
534        self.seen_ids.clear();
535        self.adoptions.clear();
536        #[cfg(debug_assertions)]
537        self.node_info.clear();
538        let mut root_node = accesskit::Node::new(accesskit::Role::Window);
539        if let Some(title) = window_title {
540            root_node.set_label(title.to_string());
541        }
542
543        self.ids_stack.push(ROOT_NODE_ID);
544        self.nodes_stack.push(root_node);
545        self.focus = None;
546        self.active_descendant = None;
547    }
548
549    /// Returns whether a node with the given ID has been pushed in this frame.
550    pub(crate) fn has_node(&self, id: NodeId) -> bool {
551        id == ROOT_NODE_ID || self.seen_ids.contains(&id)
552    }
553
554    /// Returns whether `id` is the node currently reported as focused.
555    pub(crate) fn node_is_focused(&self, id: NodeId) -> bool {
556        self.focus == Some(id)
557    }
558
559    pub(crate) fn focus_is_ancestor_of_current(&self) -> bool {
560        let Some(focus) = self.focus else {
561            return false;
562        };
563
564        // The current node is on top of the stack; everything below it is an
565        // ancestor.
566        let ancestor_count = self.ids_stack.len().saturating_sub(1);
567        self.ids_stack[..ancestor_count].contains(&focus)
568    }
569
570    pub(crate) fn set_active_descendant(&mut self, id: NodeId) {
571        if self
572            .active_descendant
573            .is_some_and(|existing| existing != id)
574        {
575            if cfg!(debug_assertions) {
576                panic!("active descendant claimed by multiple nodes in one frame");
577            } else {
578                log::warn!(
579                    "a11y: multiple nodes claimed the active descendant this frame; \
580                     using last-wins ({id:?})"
581                );
582            }
583        }
584        self.active_descendant = Some(id);
585    }
586
587    pub(crate) fn set_focus(&mut self, id: NodeId) {
588        if self.focus.is_some() {
589            if cfg!(debug_assertions) {
590                panic!("set_focus called more than once in a single frame");
591            } else {
592                log::warn!(
593                    "a11y: set_focus called more than once in a single frame; \
594                     using last-wins ({id:?})"
595                );
596            }
597        }
598        self.focus = Some(id);
599    }
600
601    fn finalize(&mut self) -> TreeUpdate {
602        // Stack should contain only the root node
603        debug_assert_eq!(self.ids_stack.len(), 1);
604        debug_assert_eq!(self.ids_stack[0], ROOT_NODE_ID);
605
606        if self.ids_stack.len() != 1 {
607            log::error!(
608                "a11y: Stack imbalance at end of frame: expected 1 (root), got {}. \
609                 Some elements may have pushed without popping.",
610                self.ids_stack.len()
611            );
612        }
613
614        // Pop remaining nodes (should just be the root).
615        while !self.ids_stack.is_empty() {
616            if let (Some(id), Some(node)) = (self.ids_stack.pop(), self.nodes_stack.pop()) {
617                self.all_nodes.push((id, node));
618            }
619        }
620        self.link_adoptions();
621
622        let focus = match self.active_descendant {
623            Some(id) if self.has_node(id) => id,
624            Some(id) => {
625                if cfg!(debug_assertions) {
626                    panic!("active_descendant set to {id:?}, which is not in the tree");
627                } else {
628                    log::warn!("active_descendant set to {id:?}, which is not in the tree");
629                    self.focus.unwrap_or(ROOT_NODE_ID)
630                }
631            }
632
633            _ => self.focus.unwrap_or(ROOT_NODE_ID),
634        };
635
636        let nodes = std::mem::take(&mut self.all_nodes);
637        let update = TreeUpdate {
638            nodes,
639            tree: Some(accesskit::Tree::new(ROOT_NODE_ID)),
640            tree_id: accesskit::TreeId::ROOT,
641            focus,
642        };
643
644        Self::repair_tree_update(update)
645    }
646
647    /// Accesskit panics on invalid [`TreeUpdate`]s. This function defensively
648    /// checks invariants that accesskit panics on, and tries to fix them.
649    fn repair_tree_update(mut update: TreeUpdate) -> TreeUpdate {
650        let node_ids: FxHashSet<NodeId> = update.nodes.iter().map(|(id, _)| *id).collect();
651
652        // Focus must point to a node in the tree.
653        if !node_ids.contains(&update.focus) {
654            log::error!(
655                "a11y: Focused node {:?} is not in the tree ({} nodes). \
656                 Falling back to root. This is a bug in the a11y tree builder.",
657                update.focus,
658                update.nodes.len()
659            );
660            update.focus = ROOT_NODE_ID;
661        }
662
663        // Every child reference must point to a node in the update.
664        for (id, node) in &mut update.nodes {
665            let has_invalid_child = node
666                .children()
667                .iter()
668                .any(|child_id| !node_ids.contains(child_id));
669            if has_invalid_child {
670                let children = node.children();
671                let invalid_count = children
672                    .iter()
673                    .filter(|child_id| !node_ids.contains(child_id))
674                    .count();
675                log::error!(
676                    "a11y: Node {:?} references {} children not present in the tree. \
677                     Stripping invalid child references.",
678                    id,
679                    invalid_count
680                );
681                let valid: Vec<NodeId> = children
682                    .iter()
683                    .copied()
684                    .filter(|child_id| node_ids.contains(child_id))
685                    .collect();
686                node.set_children(valid);
687            }
688        }
689
690        update
691    }
692}
693
694#[cfg(test)]
695mod tests {
696    // Import specific items rather than glob-importing `super`, which would pull
697    // in gpui's own `test` attribute macro and shadow the standard one.
698    use super::{A11y, A11yNodeBuilder, ROOT_NODE_ID};
699    use crate::FocusId;
700    use accesskit::{NodeId, Role};
701    use std::sync::{Arc, atomic::AtomicBool};
702
703    fn test_node() -> accesskit::Node {
704        accesskit::Node::new(Role::GenericContainer)
705    }
706
707    fn new_builder() -> A11yNodeBuilder {
708        let mut builder = A11yNodeBuilder::new();
709        builder.begin_frame(None);
710        builder
711    }
712
713    fn new_a11y() -> A11y {
714        let mut a11y = A11y::new(Arc::new(AtomicBool::new(true)), false, None);
715        a11y.begin_frame();
716        a11y
717    }
718
719    #[test]
720    fn accessibility_enabled_is_independent_of_activation() {
721        for force_disabled in [false, true] {
722            for active in [false, true] {
723                let mut a11y = A11y::new(Arc::new(AtomicBool::new(active)), force_disabled, None);
724                a11y.sync_active_flag();
725
726                assert_eq!(a11y.is_enabled(), !force_disabled);
727                assert_eq!(a11y.is_active(), !force_disabled && active);
728            }
729        }
730    }
731
732    #[test]
733    fn active_descendant_honored_when_container_focused() {
734        let mut builder = new_builder();
735        let container = NodeId(1);
736        let item = NodeId(2);
737
738        assert!(builder.push(container, test_node()));
739        builder.set_focus(container);
740        assert!(builder.push(item, test_node()));
741
742        // The item is on top of the stack; the focused container is its
743        // ancestor, so the claim is honored.
744        assert!(builder.focus_is_ancestor_of_current());
745        builder.set_active_descendant(item);
746
747        builder.pop(); // item
748        builder.pop(); // container
749        let update = builder.finalize();
750        assert_eq!(update.focus, item);
751    }
752
753    #[test]
754    fn active_descendant_honored_for_deep_descendant() {
755        let mut builder = new_builder();
756        let container = NodeId(1);
757        let group = NodeId(2);
758        let item = NodeId(3);
759
760        assert!(builder.push(container, test_node()));
761        builder.set_focus(container);
762        assert!(builder.push(group, test_node()));
763        assert!(builder.push(item, test_node()));
764
765        // The item is a grandchild of the focused container; depth doesn't
766        // matter, the focused ancestor is still on the stack.
767        assert!(builder.focus_is_ancestor_of_current());
768        builder.set_active_descendant(item);
769
770        builder.pop(); // item
771        builder.pop(); // group
772        builder.pop(); // container
773        let update = builder.finalize();
774        assert_eq!(update.focus, item);
775    }
776
777    #[test]
778    fn active_descendant_ignored_when_focus_in_other_subtree() {
779        let mut builder = new_builder();
780        let focused_container = NodeId(1);
781        let focused_leaf = NodeId(2);
782        let other_container = NodeId(3);
783        let other_item = NodeId(4);
784
785        // First subtree holds real focus.
786        assert!(builder.push(focused_container, test_node()));
787        assert!(builder.push(focused_leaf, test_node()));
788        builder.set_focus(focused_leaf);
789        builder.pop(); // focused_leaf
790        builder.pop(); // focused_container
791
792        // Second subtree: its item would claim the active descendant, but the
793        // focus is not on any of its ancestors, so the gate rejects it.
794        assert!(builder.push(other_container, test_node()));
795        assert!(builder.push(other_item, test_node()));
796        assert!(!builder.focus_is_ancestor_of_current());
797        builder.pop(); // other_item
798        builder.pop(); // other_container
799
800        let update = builder.finalize();
801        assert_eq!(update.focus, focused_leaf);
802    }
803
804    #[test]
805    fn active_descendant_ignored_when_nothing_focused() {
806        let mut builder = new_builder();
807        let container = NodeId(1);
808        let item = NodeId(2);
809
810        assert!(builder.push(container, test_node()));
811        assert!(builder.push(item, test_node()));
812
813        // Nothing is focused (focus defaults to the root window node), so the
814        // gate rejects the claim.
815        assert!(!builder.focus_is_ancestor_of_current());
816        builder.pop();
817        builder.pop();
818
819        let update = builder.finalize();
820        assert_eq!(update.focus, ROOT_NODE_ID);
821    }
822
823    #[test]
824    fn regular_focus_used_when_no_active_descendant() {
825        let mut builder = new_builder();
826        let focused = NodeId(1);
827
828        assert!(builder.push(focused, test_node()));
829        builder.set_focus(focused);
830        builder.pop();
831
832        let update = builder.finalize();
833        assert_eq!(update.focus, focused);
834    }
835
836    #[test]
837    fn focus_is_ancestor_excludes_self_and_non_ancestors() {
838        let mut builder = new_builder();
839        let container = NodeId(1);
840        let item = NodeId(2);
841
842        assert!(builder.push(container, test_node()));
843        builder.set_focus(container);
844
845        // With the focused container itself on top, it is not its own (strict)
846        // ancestor, so the gate is false.
847        assert!(!builder.focus_is_ancestor_of_current());
848
849        assert!(builder.push(item, test_node()));
850        // Now the focused container is a strict ancestor of the item on top.
851        assert!(builder.focus_is_ancestor_of_current());
852
853        builder.pop();
854        builder.pop();
855    }
856
857    // The double-claim guard panics only in debug builds; in release it falls
858    // back to last-wins with a warning.
859    #[test]
860    #[cfg_attr(
861        debug_assertions,
862        should_panic(expected = "active descendant claimed by multiple nodes")
863    )]
864    fn multiple_active_descendant_claims_panic_in_debug() {
865        let mut builder = new_builder();
866        builder.set_active_descendant(NodeId(1));
867        builder.set_active_descendant(NodeId(2));
868    }
869
870    // Setting focus twice in one frame means two elements both claimed window
871    // focus; that panics in debug and falls back to last-wins in release.
872    #[test]
873    #[cfg_attr(
874        debug_assertions,
875        should_panic(expected = "set_focus called more than once")
876    )]
877    fn setting_focus_twice_panics_in_debug() {
878        let mut builder = new_builder();
879        builder.set_focus(NodeId(1));
880        builder.set_focus(NodeId(2));
881    }
882
883    // Focusing a node that was never registered as focusable is a bug: panic in
884    // debug, warn in release.
885    #[test]
886    #[cfg_attr(
887        debug_assertions,
888        should_panic(expected = "was not registered with set_focusable")
889    )]
890    fn set_focus_without_set_focusable() {
891        let mut a11y = new_a11y();
892        let node = NodeId(1);
893        assert!(a11y.nodes.push(node, test_node()));
894        // set_focusable was never called for `node`.
895        a11y.set_focus(node);
896    }
897
898    // The focused node cannot also be its own active descendant: panic in
899    // debug, warn in release.
900    #[test]
901    #[cfg_attr(debug_assertions, should_panic(expected = "on the focused node"))]
902    fn set_active_descendant_on_focused_node() {
903        let mut a11y = new_a11y();
904        let node = NodeId(1);
905        assert!(a11y.nodes.push(node, test_node()));
906        a11y.set_focusable(node, FocusId::default());
907        a11y.set_focus(node);
908        a11y.set_active_descendant(node);
909    }
910
911    // Two sibling children of a focused container both claim the active
912    // descendant (both pass the focus gate). The second claim is a bug: panic
913    // in debug, last-wins + warn in release.
914    #[test]
915    #[cfg_attr(
916        debug_assertions,
917        should_panic(expected = "active descendant claimed by multiple nodes")
918    )]
919    fn two_siblings_claiming_active_descendant() {
920        let mut a11y = new_a11y();
921        let container = NodeId(1);
922        let first = NodeId(2);
923        let second = NodeId(3);
924
925        assert!(a11y.nodes.push(container, test_node()));
926        a11y.set_focusable(container, FocusId::default());
927        a11y.set_focus(container);
928
929        assert!(a11y.nodes.push(first, test_node()));
930        a11y.set_active_descendant(first);
931        a11y.nodes.pop(); // first
932
933        assert!(a11y.nodes.push(second, test_node()));
934        a11y.set_active_descendant(second);
935        a11y.nodes.pop(); // second
936
937        a11y.nodes.pop(); // container
938    }
939
940    // Node A is focused; node C (a child of the unfocused node B) claims the
941    // active descendant. The final tree must still report A as focused.
942    #[test]
943    fn active_descendant_in_unfocused_subtree_keeps_real_focus() {
944        let mut a11y = new_a11y();
945        let a = NodeId(1);
946        let b = NodeId(2);
947        let c = NodeId(3);
948
949        assert!(a11y.nodes.push(a, test_node()));
950        a11y.set_focusable(a, FocusId::default());
951        a11y.set_focus(a);
952        a11y.nodes.pop(); // a
953
954        assert!(a11y.nodes.push(b, test_node()));
955        assert!(a11y.nodes.push(c, test_node()));
956        a11y.set_active_descendant(c);
957        a11y.nodes.pop(); // c
958        a11y.nodes.pop(); // b
959
960        let update = a11y.end_frame(Default::default());
961        assert_eq!(update.focus, a);
962    }
963}
964
965/// vue-native fork: a deferred draw's nodes go under the node it was deferred
966/// from (`A11yNodeBuilder::begin_adopted`).
967#[cfg(test)]
968mod vn_adoption_tests {
969    use super::{A11yNodeBuilder, ROOT_NODE_ID};
970    use accesskit::{NodeId, Role};
971
972    fn node() -> accesskit::Node {
973        accesskit::Node::new(Role::GenericContainer)
974    }
975
976    fn children_of(update: &accesskit::TreeUpdate, id: NodeId) -> Vec<NodeId> {
977        update
978            .nodes
979            .iter()
980            .find(|(n, _)| *n == id)
981            .map(|(_, node)| node.children().to_vec())
982            .unwrap_or_default()
983    }
984
985    #[test]
986    fn a_deferred_node_is_a_child_of_the_node_it_was_deferred_from() {
987        let (dialog, title, close, icon) = (NodeId(1), NodeId(2), NodeId(3), NodeId(4));
988        let mut b = A11yNodeBuilder::new();
989        b.begin_frame(None);
990
991        // The dialog and its in-flow child; the Close button is deferred while
992        // the dialog is on top of the stack.
993        assert!(b.push(dialog, node()));
994        assert!(b.push_leaf(title, node()));
995        let deferred_from = b.current_id();
996        b.pop();
997        assert_eq!(deferred_from, dialog);
998
999        // Prepainted after the whole tree, with only the root on the stack.
1000        b.begin_adopted(deferred_from);
1001        assert!(b.push(close, node()));
1002        assert!(b.push_leaf(icon, node()));
1003        b.pop();
1004        b.end_adopted();
1005
1006        let update = b.finalize();
1007        assert_eq!(children_of(&update, dialog), vec![title, close]);
1008        assert_eq!(children_of(&update, close), vec![icon]);
1009        assert_eq!(children_of(&update, ROOT_NODE_ID), vec![dialog], "not on the root");
1010        let dialogs = update.nodes.iter().filter(|(id, _)| *id == dialog).count();
1011        assert_eq!(dialogs, 1, "the stand-in is not a node of its own");
1012    }
1013}