Skip to main content

gpui/window/
a11y.rs

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