Skip to main content

layout/accessibility/
accessibility_node.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::collections::VecDeque;
6use std::fmt::Debug;
7use std::sync::LazyLock;
8
9use accesskit::{Affine, NodeId, Role};
10use app_units::Au;
11use bitflags::bitflags;
12use euclid::Rect;
13use layout_api::{
14    ARIA_ROLE_TO_ACCESSKIT_ROLE, AccessibilityDamage, BoxAreaType, LayoutElement, LayoutNode,
15    LayoutNodeType, SUPPORTED_ARIA_ROLES,
16};
17use log::trace;
18use num_traits::ToPrimitive;
19use rustc_hash::{FxHashMap, FxHashSet};
20use script::layout_dom::{ServoLayoutElement, ServoLayoutNode};
21use servo_base::print_tree::PrintTree;
22use servo_config::pref;
23use style::dom::{NodeInfo, OpaqueNode};
24use style_traits::CSSPixel;
25use web_atoms::{LocalName, local_name, ns};
26use webrender_api::units::LayoutVector2D;
27
28use super::accessibility_tree::{AccessibilityTree, AccessibilityUpdate, TreeChange};
29use crate::ArcRefCell;
30use crate::accessibility::AccessibilityContext;
31use crate::cell::WeakRefCell;
32use crate::query::{BoxAreaInclusion, process_box_area_request};
33
34/// Convert a rectangle as layout reports it into the one [`accesskit`] wants.
35fn au_rect_to_accesskit_rect(rect: Rect<Au, CSSPixel>) -> accesskit::Rect {
36    accesskit::Rect::new(
37        rect.min_x().to_f64_px(),
38        rect.min_y().to_f64_px(),
39        rect.max_x().to_f64_px(),
40        rect.max_y().to_f64_px(),
41    )
42}
43
44fn scroll_offset_to_affine(layout_vector: LayoutVector2D) -> Affine {
45    Affine::translate((
46        -layout_vector.x.to_f64().unwrap_or(0.),
47        -layout_vector.y.to_f64().unwrap_or(0.),
48    ))
49}
50
51pub(super) struct AccessibilityNode {
52    /// The unique ID for the node. This is used both as a key in [`AccessibilityTree`]'s cache of
53    /// nodes, and as an identifier in [`accesskit`] datastructures: [`accesskit::Node`]s,
54    /// [`accesskit::TreeUpdate`]s and [`accesskit::ActionRequest`]s.
55    id: NodeId,
56    /// The computed [`accesskit::Node`] data. This will be copied and serialized into a
57    /// [`accesskit::TreeUpdate`] whenever it is changed during an update.
58    accesskit_node: accesskit::Node,
59    /// This node's parent, if any.
60    parent_node: Option<WeakRefCell<AccessibilityNode>>,
61    /// All this node's children.
62    child_nodes: Vec<ArcRefCell<AccessibilityNode>>,
63    /// The [`OpaqueNode`] for the DOM node which corresponds to this accessibility node, if any.
64    /// An accessibility node may not correspond to a DOM node if it corresponds to a
65    /// pseudo-element, or in a test.
66    opaque_node: Option<OpaqueNode>,
67    /// This node's scroll offset, if it is a scroll container which has scrolled. This is used to
68    /// translate this node's children.
69    scroll_offset: Option<LayoutVector2D>,
70    /// Any dirty state for the current update.
71    dirty_state: DirtyState,
72}
73
74impl AccessibilityNode {
75    pub(super) fn new(id: NodeId) -> Self {
76        Self::new_with_role(id, Role::Unknown)
77    }
78
79    pub(super) fn new_with_role(id: NodeId, role: Role) -> Self {
80        Self {
81            id,
82            accesskit_node: accesskit::Node::new(role),
83            parent_node: None,
84            child_nodes: vec![],
85            opaque_node: None,
86            scroll_offset: None,
87            dirty_state: DirtyState::empty(),
88        }
89    }
90
91    /// Update this node and its subtree based on damage from the DOM.
92    ///
93    /// - First, if this node has damage from the DOM to be resolved, update the node from the DOM
94    ///   tree, recursively populating any new children.
95    /// - Next, recursively call this method for any children which are dirty, or have dirty
96    ///   descendants.
97    /// - Finally, update any properties on this node which are may have changed due to other
98    ///   changes in the tree.
99    ///
100    /// At the end of this method, both `has_dirty_descendants` and `is_dirty` should be false for
101    /// this node and all its descendants.
102    pub(super) fn update_subtree<'update>(
103        &mut self,
104        ref_self: ArcRefCell<Self>,
105        damage_from_parent: AccessibilityDamage,
106        hidden: bool,
107        context: &AccessibilityContext,
108        tree: &mut AccessibilityTree,
109        update: &mut AccessibilityUpdate<'update>,
110    ) -> LocalAccessibilityDamage {
111        let mut local_damage = LocalAccessibilityDamage::empty();
112
113        let dom_node = update.take_dom_node(&self.id);
114        let damage = update.take_damage(&self.id) | damage_from_parent;
115        let mut children_changed = false;
116
117        if let Some(dom_node) = dom_node {
118            local_damage.insert(self.update_properties_and_children_from_dom_node(
119                &ref_self, &dom_node, damage, tree, update,
120            ));
121            local_damage
122                .insert(self.update_node_from_layout(&dom_node, damage, hidden, context, update));
123
124            if local_damage.contains(LocalAccessibilityDamage::SubtreeChanged) {
125                children_changed = true;
126            }
127
128            self.dirty_state -= DirtyState::HasDamage;
129        }
130
131        let layout_damage = damage & AccessibilityDamage::Layout;
132        if self.dirty_state.descendant_has_damage() || !layout_damage.is_empty() {
133            for child_node in self.children() {
134                let child_node_ref = child_node.clone();
135                let mut child_node = child_node.borrow_mut();
136                let child_local_damage = child_node.update_subtree(
137                    child_node_ref,
138                    layout_damage,
139                    hidden || self.is_hidden(),
140                    context,
141                    tree,
142                    update,
143                );
144                if !child_local_damage.is_empty() {
145                    local_damage.insert(LocalAccessibilityDamage::SubtreeChanged);
146                    if child_local_damage.contains(LocalAccessibilityDamage::VisibilityChanged) {
147                        children_changed = true;
148                    }
149                }
150            }
151        }
152        self.dirty_state -= DirtyState::DescendantHasDamage;
153
154        if children_changed && let Some(scroll_offset) = self.scroll_offset {
155            // If this node may have new, or newly-visible, children, update their scroll offsets.
156            self.set_scroll_offset(scroll_offset, update);
157        }
158
159        local_damage.insert(self.update_node_local(local_damage, update));
160
161        if self.dirty_state.updated() {
162            update.add(self);
163        }
164
165        local_damage
166    }
167
168    /// Update each of this node's ancestors based on changes which have already been applied in the
169    /// tree.
170    pub(super) fn update_ancestors(
171        &self,
172        local_damage: LocalAccessibilityDamage,
173        update: &mut AccessibilityUpdate,
174    ) {
175        if local_damage.is_empty() {
176            return;
177        }
178        for node in self.ancestors() {
179            let mut node = node.borrow_mut();
180            node.update_node_local(LocalAccessibilityDamage::SubtreeChanged, update);
181            node.dirty_state -= DirtyState::DescendantHasDamage;
182            if node.dirty_state.updated() {
183                update.add(&mut node);
184            }
185        }
186    }
187
188    pub(super) fn initialize_from_dom_node(&mut self, dom_node: &ServoLayoutNode) {
189        self.opaque_node = Some(dom_node.opaque());
190        if let Some(dom_element) = dom_node.as_element() {
191            let local_name = dom_element.local_name().to_ascii_lowercase();
192            self.set_html_tag(&local_name);
193        }
194    }
195
196    /// Update the given [`AccessibilityNode`] from its corresponding DOM node and
197    /// [`AccessibilityDamage`].
198    /// If it has new children, those will be created here, but not yet populated.
199    // Any changed nodes will be added to the given [`AccessibilityUpdate`].
200    fn update_properties_and_children_from_dom_node<'update>(
201        &mut self,
202        ref_self: &ArcRefCell<Self>,
203        dom_node: &ServoLayoutNode<'update>,
204        dom_damage: AccessibilityDamage,
205        tree: &mut AccessibilityTree,
206        update: &mut AccessibilityUpdate<'update>,
207    ) -> LocalAccessibilityDamage {
208        let mut local_damage = LocalAccessibilityDamage::empty();
209
210        if !dom_damage.intersects(
211            AccessibilityDamage::Node | AccessibilityDamage::Children | AccessibilityDamage::Layout,
212        ) {
213            return local_damage;
214        }
215
216        // We check for layout damage here because we need to walk the DOM children of nodes with
217        // layout damage in order to be able to recompute their bounds. Text nodes have neither
218        // bounds nor child nodes, so if the only damage is layout, we can early return here.
219        if dom_damage == AccessibilityDamage::Layout && dom_node.is_text_node() {
220            return local_damage;
221        }
222
223        update.counters.nodes_updated_from_dom += 1;
224
225        if dom_damage.intersects(AccessibilityDamage::Node) {
226            local_damage.insert(self.update_properties_from_dom_node(dom_node));
227        }
228
229        if dom_damage.intersects(AccessibilityDamage::Children | AccessibilityDamage::Layout) {
230            // If this node has damage from layout, this ensures that all of its children have
231            // their corresponding DOM nodes in `update`.
232            local_damage
233                .insert(self.update_children_from_dom_node(ref_self, dom_node, tree, update));
234        }
235
236        local_damage
237    }
238
239    /// Update this node's [`Self::children`] from its corresponding DOM node.
240    /// If it has new children, those will be created here, but not yet populated.
241    fn update_children_from_dom_node<'update>(
242        &mut self,
243        ref_self: &ArcRefCell<AccessibilityNode>,
244        dom_node: &ServoLayoutNode<'update>,
245        tree: &mut AccessibilityTree,
246        update: &mut AccessibilityUpdate<'update>,
247    ) -> LocalAccessibilityDamage {
248        let mut remaining_dom_children = dom_node.flat_tree_children().peekable();
249        let mut old_child_ids = self.child_ids().iter().peekable();
250
251        // Iterate over existing children and DOM children while they match. No action is necessary
252        // for these nodes.
253        let mut unchanged_count = 0usize;
254        while let Some(&old_id) = old_child_ids.peek() &&
255            let Some(dom_child) = remaining_dom_children.peek()
256        {
257            if tree.existing_id_for_opaque(dom_child.opaque()) == Some(*old_id) {
258                update.insert_dom_node(*old_id, *dom_child);
259                unchanged_count += 1;
260                old_child_ids.next();
261                remaining_dom_children.next();
262            } else {
263                break;
264            }
265        }
266
267        // If we iterated over all the DOM children without finding any changes, we're done.
268        if old_child_ids.peek().is_none() && remaining_dom_children.peek().is_none() {
269            return LocalAccessibilityDamage::empty();
270        }
271
272        // Remove all child nodes after the first `unchanged_count`.
273        self.child_nodes.truncate(unchanged_count);
274        let mut new_child_ids = Vec::from(self.child_ids());
275        for removed_child_id in new_child_ids.split_off(unchanged_count) {
276            update.set_tree_state_change(removed_child_id, TreeChange::Removed);
277        }
278
279        // Then, (re-)add all the remaining DOM children. Note that this means that some children
280        // may end up being "Moved" even though they haven't changed parents, and may even be in the
281        // same position as previously.
282        let weak_self = ref_self.downgrade();
283        for dom_child in remaining_dom_children {
284            let (child_id, child_ref) = tree.get_or_create_node(&dom_child, update);
285            // TODO(#47162): Since we need to update bounds for all nodes, we need to ensure every
286            // AccessibilityNode has a corresponding DOM node available to be retrieved from the
287            // AccessibilityUpdate. Once we no longer update bounds on all nodes, we won't need to
288            // add all nodes like this.
289            update.insert_dom_node(child_id, dom_child);
290
291            // Update self.child_nodes in place.
292            self.child_nodes.push(child_ref.clone());
293            new_child_ids.push(child_id);
294
295            let mut child = child_ref.borrow_mut();
296            child.parent_node = Some(weak_self.clone());
297
298            if update.is_new(&child_id) {
299                self.dirty_state |= DirtyState::DescendantHasDamage;
300            } else {
301                update.set_tree_state_change(child_id, TreeChange::PendingMove);
302            }
303
304            self.dirty_state
305                .propagate_descendant_has_damage(child.dirty_state);
306        }
307
308        // We can't update the AccessKit node's `children` in place, so we build up the full list
309        // and then set it here.
310        self.accesskit_node.set_children(new_child_ids);
311        self.dirty_state |= DirtyState::Updated;
312
313        LocalAccessibilityDamage::SubtreeChanged
314    }
315
316    /// Update this node's properties from its corresponding DOM node.
317    fn update_properties_from_dom_node(
318        &mut self,
319        dom_node: &ServoLayoutNode,
320    ) -> LocalAccessibilityDamage {
321        let mut local_damage = LocalAccessibilityDamage::empty();
322        local_damage.insert(self.set_role(role_from_dom_node(dom_node)));
323        if dom_node.type_id() == Some(LayoutNodeType::Text) {
324            let text_content = dom_node.text_content();
325            trace!("node text content = {text_content:?}");
326            // FIXME: this should take into account editing selection units (grapheme clusters?)
327            local_damage.insert(self.set_value(&text_content));
328        }
329
330        local_damage
331    }
332
333    /// Update this node's bounds from the current layout geometry.
334    fn update_node_from_layout(
335        &mut self,
336        dom_node: &ServoLayoutNode<'_>,
337        layout_damage: AccessibilityDamage,
338        hidden: bool,
339        context: &AccessibilityContext,
340        update: &mut AccessibilityUpdate,
341    ) -> LocalAccessibilityDamage {
342        let mut local_damage = LocalAccessibilityDamage::empty();
343
344        // Don't update bounds on nodes in hidden subtrees.
345        if hidden || !layout_damage.intersects(AccessibilityDamage::Layout) {
346            return local_damage;
347        }
348
349        if let Some(dom_element) = dom_node.as_element() &&
350            dom_element.style_data().is_some()
351        {
352            let data = dom_element.element_data();
353            let style = data.styles.primary();
354            if style.get_display().is_none() {
355                self.clear_bounds();
356                local_damage.insert(self.set_hidden());
357            } else {
358                local_damage.insert(self.clear_hidden());
359            }
360        }
361
362        if self.is_hidden() {
363            return local_damage;
364        }
365
366        update.counters.nodes_updated_bounds += 1;
367
368        // Border box without transforms. Bounds are in CSS pixels, relative to the document origin;
369        // scroll containers set translations on their child nodes, and the embedder's graft node
370        // carries the transform that composes them into AccessKit's coordinate space (see the
371        // "Coordinates" section of
372        // <https://docs.rs/accesskit/latest/accesskit/struct.Node.html>).
373        // TODO(#47166): This doesn't take any CSS transforms into account.
374        let bounds = process_box_area_request(
375            context.layout_thread,
376            context.stacking_context_tree,
377            *dom_node,
378            BoxAreaType::Border,
379            BoxAreaInclusion::Inlines,
380        )
381        .map(au_rect_to_accesskit_rect);
382
383        // For now only nodes with a box of their own get bounds; anything else, including
384        // `display: none` content, gets its bounds cleared. That leaves two kinds of nodes
385        // without geometry which assistive technology would like to have some:
386        //
387        // TODO(#47164): A text node never has bounds of its own: `LayoutBox::Text` has no
388        // `LayoutBoxBase`, and `Fragment::Text` has no box area, so the query above always returns
389        // `None` for one. Text nodes should get the union of the rectangles of their own
390        // `Fragment::Text` fragments, once `cumulative_box_area_rect()` can handle those.
391        //
392        // TODO(#47163): A `display: contents` element generates no box either. Other
393        // engines (Blink, WebKit, Gecko) compute its bounds as the union of the bounding boxes of
394        // its rendered descendants.
395        match bounds {
396            Some(bounds) => self.set_bounds(bounds),
397            None => self.clear_bounds(),
398        }
399        local_damage
400    }
401
402    /// Update this node's properties based on changes already made to the accessibility tree.
403    /// For example, if there were nodes added or removed in its subtree, its computed text may have
404    /// changed, so that will be recomputed here.
405    /// If any changes are made, add this node to the given [`AccessibilityUpdate`].
406    fn update_node_local(
407        &mut self,
408        local_damage: LocalAccessibilityDamage,
409        update: &mut AccessibilityUpdate,
410    ) -> LocalAccessibilityDamage {
411        let mut new_damage = LocalAccessibilityDamage::empty();
412        if local_damage.is_empty() {
413            return new_damage;
414        }
415        update.counters.nodes_updated_from_tree += 1;
416
417        if local_damage.contains(LocalAccessibilityDamage::SubtreeChanged) ||
418            local_damage.contains(LocalAccessibilityDamage::RoleChanged)
419        {
420            if let Some(text) = self.label_from_descendants() {
421                new_damage.insert(self.set_label(text.as_str()));
422            } else {
423                new_damage.insert(self.clear_label());
424            }
425        }
426
427        new_damage
428    }
429
430    fn label_from_descendants(&self) -> Option<String> {
431        if !NAME_FROM_CONTENTS_ROLES.contains(&self.role()) {
432            return None;
433        }
434        let mut children = VecDeque::from_iter(self.children().cloned());
435        let mut text = String::new();
436        while let Some(child) = children.pop_front() {
437            let child = child.borrow();
438            if child.is_hidden() {
439                continue;
440            }
441            match child.role() {
442                Role::TextRun => {
443                    if let Some(child_text) = child.value() {
444                        text.push_str(child_text);
445                    }
446                },
447                _ => {
448                    for node in child.children().rev() {
449                        children.push_front(node.clone());
450                    }
451                },
452            }
453        }
454        Some(text.trim().to_owned())
455    }
456
457    pub(super) fn print(&self, print_tree: &mut PrintTree, tree: &AccessibilityTree) {
458        let focused = if tree.focused_node_id() == Some(self.id) {
459            "[focused] "
460        } else {
461            ""
462        };
463        let node_string = format!("{focused}{self:?}");
464
465        if self.child_nodes.is_empty() {
466            print_tree.add_item(node_string);
467            return;
468        }
469
470        print_tree.new_level(node_string);
471
472        for child in self.children() {
473            child.borrow().print(print_tree, tree);
474        }
475        print_tree.end_level();
476    }
477
478    pub(super) fn clone_accesskit_node(&self) -> accesskit::Node {
479        self.accesskit_node.clone()
480    }
481
482    pub(super) fn id(&self) -> NodeId {
483        self.id
484    }
485
486    pub(super) fn opaque_node(&self) -> Option<OpaqueNode> {
487        self.opaque_node
488    }
489
490    pub(super) fn dirty_state(&self) -> DirtyState {
491        self.dirty_state
492    }
493
494    pub(super) fn add_dirty_state(&mut self, state: DirtyState) {
495        self.dirty_state |= state;
496    }
497
498    pub(super) fn remove_dirty_state(&mut self, state: DirtyState) {
499        self.dirty_state -= state;
500    }
501
502    pub(super) fn parent(&self) -> Option<ArcRefCell<AccessibilityNode>> {
503        self.parent_node.as_ref().and_then(|weak| weak.upgrade())
504    }
505
506    pub(super) fn children(
507        &self,
508    ) -> impl DoubleEndedIterator<Item = &ArcRefCell<AccessibilityNode>> {
509        self.child_nodes.iter()
510    }
511
512    #[cfg(test)]
513    pub(super) fn set_children_for_testing(
514        &mut self,
515        child_ids: Vec<NodeId>,
516        child_nodes: Vec<ArcRefCell<AccessibilityNode>>,
517    ) {
518        self.accesskit_node.set_children(child_ids);
519        self.child_nodes = child_nodes;
520    }
521
522    pub(super) fn ancestors(&self) -> impl Iterator<Item = ArcRefCell<AccessibilityNode>> {
523        AccessibilityNodeIterator::new(self.parent(), |node| node.parent_node.clone()?.upgrade())
524    }
525
526    pub(super) fn child_ids(&self) -> &[NodeId] {
527        self.accesskit_node.children()
528    }
529
530    pub(super) fn set_scroll_offset(
531        &mut self,
532        offset: LayoutVector2D,
533        update: &mut AccessibilityUpdate,
534    ) {
535        self.scroll_offset = Some(offset);
536        let transform = scroll_offset_to_affine(offset);
537        for child in self.children() {
538            let mut child = child.borrow_mut();
539            if child.is_hidden() {
540                continue;
541            }
542            child.set_transform(transform);
543            if child.dirty_state.updated() {
544                update.add(&mut child);
545            }
546        }
547    }
548
549    pub(super) fn role(&self) -> Role {
550        self.accesskit_node.role()
551    }
552
553    pub(super) fn set_role(&mut self, role: Role) -> LocalAccessibilityDamage {
554        if role == self.accesskit_node.role() {
555            return LocalAccessibilityDamage::empty();
556        }
557        self.accesskit_node.set_role(role);
558        self.dirty_state |= DirtyState::Updated;
559        LocalAccessibilityDamage::RoleChanged
560    }
561
562    fn label(&self) -> Option<&str> {
563        self.accesskit_node.label()
564    }
565
566    fn set_label(&mut self, label: &str) -> LocalAccessibilityDamage {
567        if Some(label) == self.accesskit_node.label() {
568            return LocalAccessibilityDamage::empty();
569        }
570        self.accesskit_node.set_label(label);
571        self.dirty_state |= DirtyState::Updated;
572        LocalAccessibilityDamage::TextChanged
573    }
574
575    fn clear_label(&mut self) -> LocalAccessibilityDamage {
576        if self.accesskit_node.label().is_none() {
577            return LocalAccessibilityDamage::empty();
578        }
579        self.accesskit_node.clear_label();
580        self.dirty_state |= DirtyState::Updated;
581        LocalAccessibilityDamage::TextChanged
582    }
583
584    fn html_tag(&self) -> Option<&str> {
585        self.accesskit_node.html_tag()
586    }
587
588    fn set_html_tag(&mut self, html_tag: &str) {
589        if Some(html_tag) == self.accesskit_node.html_tag() {
590            return;
591        }
592        self.accesskit_node.set_html_tag(html_tag);
593        self.dirty_state |= DirtyState::Updated;
594    }
595
596    fn value(&self) -> Option<&str> {
597        self.accesskit_node.value()
598    }
599
600    fn set_value(&mut self, value: &str) -> LocalAccessibilityDamage {
601        if Some(value) == self.accesskit_node.value() {
602            return LocalAccessibilityDamage::empty();
603        }
604        self.accesskit_node.set_value(value);
605        self.dirty_state |= DirtyState::Updated;
606        LocalAccessibilityDamage::TextChanged
607    }
608
609    fn is_hidden(&self) -> bool {
610        self.accesskit_node.is_hidden()
611    }
612
613    fn set_hidden(&mut self) -> LocalAccessibilityDamage {
614        if self.is_hidden() {
615            return LocalAccessibilityDamage::empty();
616        }
617        self.accesskit_node.set_hidden();
618        self.dirty_state |= DirtyState::Updated;
619        LocalAccessibilityDamage::VisibilityChanged
620    }
621
622    fn clear_hidden(&mut self) -> LocalAccessibilityDamage {
623        if !self.is_hidden() {
624            return LocalAccessibilityDamage::empty();
625        }
626
627        self.accesskit_node.clear_hidden();
628        self.dirty_state |= DirtyState::Updated;
629        LocalAccessibilityDamage::VisibilityChanged
630    }
631
632    fn bounds(&self) -> Option<accesskit::Rect> {
633        self.accesskit_node.bounds()
634    }
635
636    fn set_bounds(&mut self, bounds: accesskit::Rect) {
637        if Some(bounds) == self.accesskit_node.bounds() {
638            return;
639        }
640        self.accesskit_node.set_bounds(bounds);
641        self.dirty_state |= DirtyState::Updated;
642    }
643
644    fn clear_bounds(&mut self) {
645        if self.accesskit_node.bounds().is_none() {
646            return;
647        }
648        self.accesskit_node.clear_bounds();
649        self.dirty_state |= DirtyState::Updated;
650    }
651
652    fn set_transform(&mut self, transform: Affine) {
653        // TODO(#47166): Right now a node will only ever have a single transform from a scroll
654        // container, if any. Once we correctly support CSS transforms, a node may have multiple
655        // transforms, which we'll need to be able to combine.
656        if self.accesskit_node.transform() == Some(&transform) {
657            return;
658        }
659        if transform == Affine::IDENTITY {
660            self.clear_transform();
661            return;
662        }
663        self.accesskit_node.set_transform(transform);
664        self.dirty_state |= DirtyState::Updated;
665    }
666
667    fn clear_transform(&mut self) {
668        if self.accesskit_node.transform().is_none() {
669            return;
670        }
671        self.accesskit_node.clear_transform();
672        self.dirty_state |= DirtyState::Updated;
673    }
674
675    pub(super) fn assert_integrity(&self, expected_parent: Option<WeakRefCell<AccessibilityNode>>) {
676        debug_assert!(pref!(expensive_accessibility_test_assertions_enabled));
677
678        if let Some(actual_parent) = &self.parent_node {
679            let expected = expected_parent.expect("Actual parent but no expected parent");
680            let expected = expected.upgrade().expect("Expected parent was dropped");
681            let actual = actual_parent.upgrade().expect("Actual parent was dropped");
682            assert!(actual.ptr_eq(&expected));
683        } else {
684            assert!(
685                expected_parent.is_none(),
686                "Expected parent but no actual parent"
687            );
688        }
689
690        assert!(
691            self.dirty_state.is_empty(),
692            "{self:?} has dirty state {:?}",
693            self.dirty_state
694        );
695
696        let children_ids: Vec<_> = self.children().map(|child| child.borrow().id).collect();
697        assert_eq!(
698            children_ids,
699            self.child_ids(),
700            "children() IDs didn't match child_ids() for {self:?}"
701        );
702    }
703}
704
705impl Debug for AccessibilityNode {
706    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
707        if self.is_hidden() {
708            write!(f, "[hidden] ")?;
709        }
710        write!(f, "{:?}: {:?}", self.id, self.role())?;
711
712        let write_truncated = |f: &mut std::fmt::Formatter<'_>, value: &str| {
713            let mut truncated = value.to_string();
714            truncated.truncate(30);
715            let ellipsis = if truncated.len() < value.len() {
716                "…"
717            } else {
718                ""
719            };
720            let truncated = truncated.replace("\n", "↵");
721            write!(f, "\"{truncated}{ellipsis}\"")
722        };
723
724        if let Some(value) = self.value() {
725            write!(f, " ")?;
726            write_truncated(f, value)?;
727        }
728        if let Some(html_tag) = self.html_tag() {
729            write!(f, " (html_tag: {html_tag:?})")?;
730        }
731        if let Some(label) = self.label() {
732            write!(f, "\nlabel: ")?;
733            write_truncated(f, label)?;
734        }
735        if let Some(bounds) = self.bounds() {
736            write!(f, "\nbounds: {bounds:?}")?;
737        }
738        if !self.child_ids().is_empty() {
739            write!(f, "\nchildren: {:?}", self.child_ids())?;
740        }
741        Ok(())
742    }
743}
744
745/// <https://w3c.github.io/aria/#host_general_role>
746fn role_from_role_attribute(dom_element: &ServoLayoutElement<'_>) -> Option<Role> {
747    let role_attribute = dom_element.attribute(&ns!(), &local_name!("role"))?;
748    role_attribute
749        .as_tokens()
750        .iter()
751        .filter_map(|role_name_in_attribute| SUPPORTED_ARIA_ROLES.get(role_name_in_attribute))
752        .next()
753        .and_then(|aria_role| ARIA_ROLE_TO_ACCESSKIT_ROLE.get(aria_role))
754        .cloned()
755}
756
757fn role_from_dom_node(dom_node: &ServoLayoutNode<'_>) -> Role {
758    if let Some(dom_element) = dom_node.as_element() {
759        role_from_role_attribute(&dom_element).unwrap_or_else(|| {
760            let local_name = dom_element.local_name().to_ascii_lowercase();
761            *HTML_ELEMENT_ROLE_MAPPINGS
762                .get(&local_name)
763                .unwrap_or(&Role::GenericContainer)
764        })
765    } else if dom_node.type_id() == Some(LayoutNodeType::Text) {
766        Role::TextRun
767    } else {
768        Role::GenericContainer
769    }
770}
771
772struct AccessibilityNodeIterator<I>
773where
774    I: Fn(&AccessibilityNode) -> Option<ArcRefCell<AccessibilityNode>>,
775{
776    next_value: Option<ArcRefCell<AccessibilityNode>>,
777    next_fn: I,
778}
779
780impl<I> AccessibilityNodeIterator<I>
781where
782    I: Fn(&AccessibilityNode) -> Option<ArcRefCell<AccessibilityNode>>,
783{
784    fn new(next_value: Option<ArcRefCell<AccessibilityNode>>, next_fn: I) -> Self {
785        AccessibilityNodeIterator {
786            next_value,
787            next_fn,
788        }
789    }
790}
791
792impl<I> Iterator for AccessibilityNodeIterator<I>
793where
794    I: Fn(&AccessibilityNode) -> Option<ArcRefCell<AccessibilityNode>>,
795{
796    type Item = ArcRefCell<AccessibilityNode>;
797
798    fn next(&mut self) -> Option<Self::Item> {
799        let next_value = self.next_value.take();
800        self.next_value = next_value
801            .as_ref()
802            .and_then(|node| (self.next_fn)(&node.borrow()));
803        next_value
804    }
805}
806
807bitflags! {
808    /// Damage which was caused by changes to the accessibility tree. These changes can cause other
809    /// properties to need to be re-computed based on the updated values, either on the same node or
810    /// on other nodes.
811    #[derive(Clone, Copy, Default, Debug, Eq, PartialEq)]
812    pub(super) struct LocalAccessibilityDamage: u16 {
813        /// This node's children changed, and/or any node in its subtree changed.
814        const SubtreeChanged = 1 << 0;
815        /// This node's computed role changed.
816        const RoleChanged = 1 << 1;
817        /// This node's computed label or text value (for a text node) changed.
818        const TextChanged = 1 << 2;
819        /// This node's visibility changed.
820        const VisibilityChanged = 1 << 3;
821    }
822}
823
824bitflags! {
825    /// Flags tracking an [`AccessibilityNode`]'s dirty state during an update. All flags which are
826    /// set during the update should be unset by the end of the update.
827    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
828    pub(super) struct DirtyState : u16 {
829        /// At least one descendant of this node has unresolved damage from the DOM tree.
830        const DescendantHasDamage = 1 << 0;
831        /// This node has unresolved damage from the DOM tree.
832        const HasDamage = 1 << 1;
833        /// This node's data changed, but it hasn't yet been added to the [`AccessibilityUpdate`].
834        const Updated = 1 << 2;
835    }
836}
837impl DirtyState {
838    pub(super) fn updated(&self) -> bool {
839        self.contains(DirtyState::Updated)
840    }
841
842    pub(super) fn descendant_has_damage(&self) -> bool {
843        self.contains(DirtyState::DescendantHasDamage)
844    }
845
846    pub(super) fn propagate_descendant_has_damage(&mut self, child_dirty_state: DirtyState) {
847        if child_dirty_state.self_or_descendant_has_damage() {
848            self.insert(DirtyState::DescendantHasDamage)
849        }
850    }
851
852    pub(super) fn self_or_descendant_has_damage(&self) -> bool {
853        self.intersects(DirtyState::HasDamage | DirtyState::DescendantHasDamage)
854    }
855}
856
857static HTML_ELEMENT_ROLE_MAPPINGS: LazyLock<FxHashMap<LocalName, Role>> = LazyLock::new(|| {
858    [
859        // FIXME: only a with href!
860        (local_name!("a"), Role::Link),
861        (local_name!("article"), Role::Article),
862        (local_name!("aside"), Role::Complementary),
863        (local_name!("body"), Role::RootWebArea),
864        (local_name!("footer"), Role::ContentInfo),
865        (local_name!("h1"), Role::Heading),
866        (local_name!("h2"), Role::Heading),
867        (local_name!("h3"), Role::Heading),
868        (local_name!("h4"), Role::Heading),
869        (local_name!("h5"), Role::Heading),
870        (local_name!("h6"), Role::Heading),
871        (local_name!("header"), Role::Banner),
872        (local_name!("hr"), Role::Splitter),
873        (local_name!("main"), Role::Main),
874        (local_name!("nav"), Role::Navigation),
875        (local_name!("p"), Role::Paragraph),
876    ]
877    .into_iter()
878    .collect()
879});
880
881/// <https://w3c.github.io/aria/#namefromcontent>
882static NAME_FROM_CONTENTS_ROLES: LazyLock<FxHashSet<Role>> =
883    LazyLock::new(|| [(Role::Heading), (Role::Link)].into_iter().collect());