1use 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
116pub(crate) const ROOT_NODE_ID: NodeId = NodeId(0);
118
119pub(crate) type A11yActionListener =
121 Box<dyn FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static>;
122
123pub(crate) struct A11y {
128 force_disabled: bool,
132 pub(crate) active_flag: Arc<AtomicBool>,
137 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 window_title: Option<SharedString>,
156 last_focus_without_node: Option<FocusId>,
159 pub(crate) debug: debug::A11yDebug,
162 #[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 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 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 pub(crate) fn set_focus(&mut self, node_id: NodeId) {
235 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 self.last_focus_without_node = None;
250 self.nodes.set_focus(node_id);
251 } else {
252 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 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 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 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
303pub struct A11ySubtreeBuilder<'a> {
306 parent_id: NodeId,
307 pub(crate) nodes: &'a mut A11yNodeBuilder,
308 pub(crate) fast: crate::fast::a11y::SyntheticParent,
309 #[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 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 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 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 pub(crate) all_nodes: Vec<(NodeId, accesskit::Node)>,
382 pub(crate) seen_ids: FxHashSet<NodeId>,
383 pub(crate) focus: Option<NodeId>,
386 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 #[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 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 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 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 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 pub(crate) fn has_node(&self, id: NodeId) -> bool {
504 id == ROOT_NODE_ID || self.seen_ids.contains(&id)
505 }
506
507 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 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 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 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 fn repair_tree_update(mut update: TreeUpdate) -> TreeUpdate {
602 let node_ids: FxHashSet<NodeId> = update.nodes.iter().map(|(id, _)| *id).collect();
603
604 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 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 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 assert!(builder.focus_is_ancestor_of_current());
697 builder.set_active_descendant(item);
698
699 builder.pop(); builder.pop(); 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 assert!(builder.focus_is_ancestor_of_current());
720 builder.set_active_descendant(item);
721
722 builder.pop(); builder.pop(); builder.pop(); 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 assert!(builder.push(focused_container, test_node()));
739 assert!(builder.push(focused_leaf, test_node()));
740 builder.set_focus(focused_leaf);
741 builder.pop(); builder.pop(); 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(); builder.pop(); 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 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 assert!(!builder.focus_is_ancestor_of_current());
800
801 assert!(builder.push(item, test_node()));
802 assert!(builder.focus_is_ancestor_of_current());
804
805 builder.pop();
806 builder.pop();
807 }
808
809 #[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 #[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 #[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 a11y.set_focus(node);
848 }
849
850 #[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 #[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(); assert!(a11y.nodes.push(second, test_node()));
886 a11y.set_active_descendant(second);
887 a11y.nodes.pop(); a11y.nodes.pop(); }
891
892 #[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(); 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(); a11y.nodes.pop(); let update = a11y.end_frame(Default::default());
913 assert_eq!(update.focus, a);
914 }
915}