1
//! Platform-neutral accessibility snapshot.
2
//!
3
//! `accesskit` covers Windows (UIA), macOS (`NSAccessibility`) and Unix
4
//! (AT-SPI). It ships NO UIKit backend and NO Android backend, so the iOS and
5
//! Android shells cannot reuse [`crate::managers::a11y::A11yManager::update_tree`]
6
//! — they have to hand UIKit a `UIAccessibilityElement` list and hand Android's
7
//! `AccessibilityNodeProvider` a virtual-view tree, both built from Azul's own
8
//! types.
9
//!
10
//! [`A11ySnapshot`] is that shared intermediate: a flat, index-addressed list of
11
//! everything a screen reader can see, with the label / value / role / bounds /
12
//! supported actions each platform needs, plus the parent-child links UIKit and
13
//! Android both require.
14
//!
15
//! # Why FLAT and index-addressed
16
//!
17
//! Android's `AccessibilityNodeProvider` addresses nodes by a plain `int`
18
//! virtual-view id, and UIKit's container protocol addresses them by
19
//! `NSInteger` index. A snapshot index is the natural id for both, and it round
20
//! trips back to `(DomId, NodeId)` through [`A11ySnapshot::element`] with no
21
//! bit-packing scheme to overflow. (`a11y::decode_a11y_node_id` packs both into
22
//! a `u64`, which is fine for accesskit's `NodeId` and does NOT fit an Android
23
//! `int`.)
24
//!
25
//! Indices are only valid for the snapshot that produced them. Rebuild the
26
//! snapshot on every layout and tell the platform the tree changed — which is
27
//! exactly what both platforms expect after a layout change anyway.
28
//!
29
//! # Node membership
30
//!
31
//! Exactly [`crate::managers::a11y::is_exposed_to_accessibility`], the same
32
//! predicate the accesskit tree uses. If these disagreed, a node would be
33
//! actionable on Linux and invisible on Android for no reason a user could
34
//! understand.
35

            
36
use alloc::{
37
    string::{String, ToString},
38
    vec::Vec,
39
};
40
use std::collections::BTreeMap;
41

            
42
use azul_core::{
43
    dom::{
44
        AccessibilityAction, AccessibilityRole, AccessibilityState, AttributeType, DomId,
45
        DomNodeId, NodeData, NodeId, NodeType,
46
    },
47
    geom::{LogicalPosition, LogicalRect, LogicalSize},
48
};
49

            
50
use crate::{
51
    managers::{a11y::is_exposed_to_accessibility, scroll_state::ScrollManager},
52
    window::DomLayoutResult,
53
};
54

            
55
/// One node as assistive technology sees it.
56
///
57
/// `clippy::struct_excessive_bools` is allowed rather than satisfied. The four
58
/// flags are INDEPENDENT platform a11y states — a node can be focusable and
59
/// editable and disabled at the same time — and each maps 1:1 onto a flag the
60
/// bridges hand to `UIAccessibilityTraits` / `AccessibilityNodeInfo`. Folding
61
/// them into an enum would make illegal what the platforms consider normal, and
62
/// a bitflags newtype would only move the same four bits behind accessors this
63
/// struct exists to expose.
64
#[allow(clippy::struct_excessive_bools)]
65
#[derive(Debug, Clone, PartialEq, Eq)]
66
pub struct A11yElement {
67
    /// The DOM node this element stands for.
68
    pub dom_id: DomId,
69
    /// The DOM node this element stands for.
70
    pub node_id: NodeId,
71
    /// Index of the nearest exposed ancestor in the same snapshot.
72
    /// `None` means "child of the window root".
73
    pub parent: Option<usize>,
74
    /// Indices of the exposed descendants that attach directly to this element.
75
    pub children: Vec<usize>,
76
    /// What a screen reader announces. Empty when the node has no name.
77
    pub label: String,
78
    /// The editable / current value, for inputs and contenteditable nodes.
79
    pub value: Option<String>,
80
    /// Element purpose.
81
    pub role: AccessibilityRole,
82
    /// Absolute bounds in LOGICAL units, padding/border inset, clipped to the
83
    /// window. Logical because the two consumers disagree about pixels: `UIKit`
84
    /// works in points (== logical), Android in physical pixels. Each bridge
85
    /// scales; neither has to un-scale.
86
    pub bounds: LogicalRect,
87
    /// Actions this element accepts. Drives the `UIKit` traits / Android action
88
    /// list, and is what [`A11ySnapshot::supports`] checks before a platform
89
    /// action is forwarded to the engine.
90
    pub actions: Vec<AccessibilityAction>,
91
    /// Can take keyboard focus.
92
    pub focusable: bool,
93
    /// Currently has keyboard focus.
94
    pub focused: bool,
95
    /// Text can be edited in place.
96
    pub editable: bool,
97
    /// `Some(true)` / `Some(false)` for checkable elements, `None` otherwise.
98
    pub checked: Option<bool>,
99
    /// Element is disabled and must not be activated.
100
    pub disabled: bool,
101
}
102

            
103
impl A11yElement {
104
    /// Does this element accept `action`?
105
    #[must_use]
106
    pub fn supports(&self, action: &AccessibilityAction) -> bool {
107
        self.actions.contains(action)
108
    }
109
}
110

            
111
/// A whole window's worth of [`A11yElement`]s, index-addressed.
112
#[derive(Debug, Clone, Default, PartialEq, Eq)]
113
pub struct A11ySnapshot {
114
    /// Window title, i.e. the root container's label.
115
    pub title: String,
116
    /// Every exposed node, in document order.
117
    pub elements: Vec<A11yElement>,
118
    /// Indices of elements with no exposed ancestor (children of the root).
119
    pub roots: Vec<usize>,
120
    /// Window size in logical units, so a bridge can convert without also
121
    /// needing the window state.
122
    pub window_size: LogicalSize,
123
}
124

            
125
impl A11ySnapshot {
126
    /// Build a snapshot from the current layout.
127
    ///
128
    /// Mirrors the three passes of `A11yManager::update_tree` (create, link,
129
    /// attach) so the two surfaces expose the same nodes with the same parents.
130
    #[must_use]
131
    // `too_many_lines` and `cognitive_complexity` are allowed, not satisfied.
132
    // This is a single linear projection: walk every DOM node once and emit one
133
    // flat element per node. The length is the number of a11y attributes a node
134
    // has, not nested control flow, and the obvious split — a helper per
135
    // attribute group — would take eight parameters each and read worse than the
136
    // straight line it replaced.
137
    //
138
    // Worth revisiting when this file gains test coverage: it currently has
139
    // none, which is the real reason not to refactor it blind today. Tracked on
140
    // the deferred-items task.
141
    #[allow(clippy::too_many_lines, clippy::cognitive_complexity)]
142
1
    pub fn build(
143
1
        layout_results: &BTreeMap<DomId, DomLayoutResult>,
144
1
        scroll_manager: &ScrollManager,
145
1
        gpu_state: &crate::managers::gpu_state::GpuStateManager,
146
1
        focused_node: Option<DomNodeId>,
147
1
        title: &str,
148
1
        window_size: LogicalSize,
149
1
    ) -> Self {
150
1
        let mut elements: Vec<A11yElement> = Vec::new();
151
1
        let mut roots: Vec<usize> = Vec::new();
152
        // (dom.inner, node index) -> snapshot index
153
1
        let mut index_of: BTreeMap<(usize, usize), usize> = BTreeMap::new();
154

            
155
1
        let focused = focused_node.and_then(|f| f.node.into_crate_internal().map(|n| (f.dom, n)));
156

            
157
        // ── Pass 1: create an element per exposed node ─────────────────
158
2
        for (dom_id, layout_result) in layout_results {
159
1
            let styled_dom = &layout_result.styled_dom;
160
1
            let node_data_slice = styled_dom.node_data.as_ref();
161
1
            let node_hierarchy = styled_dom.node_hierarchy.as_ref();
162

            
163
3
            for (dom_idx, node_data) in node_data_slice.iter().enumerate() {
164
3
                if !is_exposed_to_accessibility(node_data) {
165
                    continue;
166
3
                }
167
3
                let node_id = NodeId::new(dom_idx);
168

            
169
3
                let bounds = element_bounds(
170
3
                    layout_result,
171
3
                    *dom_id,
172
3
                    node_id,
173
3
                    window_size,
174
3
                    scroll_manager,
175
3
                    gpu_state,
176
                );
177

            
178
                // Child text is the element's name when the node has no
179
                // interactive children — same rule the accesskit builder uses,
180
                // so a group is announced by its text instead of swallowing its
181
                // children.
182
3
                let (child_text, has_non_text_children) =
183
3
                    collect_child_text(node_data_slice, node_hierarchy, dom_idx);
184

            
185
3
                let editable = node_data.is_contenteditable()
186
3
                    || matches!(node_data.node_type, NodeType::TextArea | NodeType::Input);
187

            
188
3
                let mut label = String::new();
189
3
                let mut value: Option<String> = None;
190

            
191
3
                if let Some(info) = node_data.get_accessibility_info() {
192
1
                    if let Some(name) = info.accessibility_name.as_option() {
193
1
                        label = name.as_str().to_string();
194
1
                    }
195
1
                    if let Some(v) = info.accessibility_value.as_option() {
196
                        value = Some(v.as_str().to_string());
197
1
                    }
198
2
                }
199
3
                if let Some(l) = node_data.get_accessible_label() {
200
                    label = l.to_string();
201
3
                }
202
3
                if let Some(v) = node_data.get_accessible_value() {
203
                    value = Some(v.to_string());
204
3
                }
205
3
                if let NodeType::Text(text) = &node_data.node_type {
206
1
                    label = text.as_str().to_string();
207
2
                }
208
3
                if !child_text.is_empty() {
209
1
                    if editable {
210
                        value = Some(child_text);
211
1
                    } else if !has_non_text_children && label.is_empty() {
212
                        label = child_text;
213
1
                    }
214
2
                }
215

            
216
                // A DECLARED role wins; `Unknown` is the default that means
217
                // "not specified" and must not erase the element's own kind.
218
                // Same rule the accesskit tree applies — see
219
                // `crate::managers::a11y::accessibility_role_is_specified`.
220
3
                let role = match node_data.get_accessibility_info() {
221
                    Some(info)
222
1
                        if crate::managers::a11y::accessibility_role_is_specified(&info.role) =>
223
                    {
224
                        info.role
225
                    }
226
3
                    _ => node_type_to_role(&node_data.node_type),
227
                };
228

            
229
3
                let mut checked = None;
230
3
                let mut disabled = false;
231
3
                if let Some(info) = node_data.get_accessibility_info() {
232
1
                    for state in info.states.as_ref() {
233
                        match state {
234
                            AccessibilityState::CheckedTrue => checked = Some(true),
235
                            AccessibilityState::CheckedFalse => checked = Some(false),
236
                            AccessibilityState::Unavailable => disabled = true,
237
                            _ => {}
238
                        }
239
                    }
240
2
                }
241
3
                for attr in node_data.attributes().as_ref() {
242
                    match attr {
243
                        AttributeType::CheckedTrue => checked = Some(true),
244
                        AttributeType::CheckedFalse => checked = Some(false),
245
                        AttributeType::Disabled => disabled = true,
246
                        _ => {}
247
                    }
248
                }
249

            
250
3
                let actions = supported_actions(node_data, scroll_manager, *dom_id, node_id);
251

            
252
3
                index_of.insert((dom_id.inner, dom_idx), elements.len());
253
3
                elements.push(A11yElement {
254
3
                    dom_id: *dom_id,
255
3
                    node_id,
256
3
                    parent: None,
257
3
                    children: Vec::new(),
258
3
                    label,
259
3
                    value,
260
3
                    role,
261
3
                    bounds,
262
3
                    actions,
263
3
                    focusable: node_data.is_focusable(),
264
3
                    focused: focused == Some((*dom_id, node_id)),
265
3
                    editable,
266
3
                    checked,
267
3
                    disabled,
268
3
                });
269
            }
270
        }
271

            
272
        // ── Pass 2: link each element to its nearest exposed ancestor ──
273
        //
274
        // The DOM parent is often NOT exposed (a wrapper div stripped by the
275
        // predicate), so walk up until an exposed ancestor is found — otherwise
276
        // whole subtrees would detach and a screen reader would never reach
277
        // them. Bounded, because a corrupt hierarchy must not hang the UI
278
        // thread that is asking for the tree.
279
2
        for (dom_id, layout_result) in layout_results {
280
1
            let styled_dom = &layout_result.styled_dom;
281
1
            let node_hierarchy = styled_dom.node_hierarchy.as_ref();
282

            
283
3
            for dom_idx in 0..styled_dom.node_data.as_ref().len() {
284
3
                let Some(&self_idx) = index_of.get(&(dom_id.inner, dom_idx)) else {
285
                    continue;
286
                };
287

            
288
3
                let mut current = node_hierarchy[dom_idx].parent_id();
289
3
                let mut parent_idx = None;
290
3
                let mut guard = 0usize;
291
3
                while let Some(parent_node_id) = current {
292
2
                    guard += 1;
293
2
                    if guard > 10_000 {
294
                        break;
295
2
                    }
296
2
                    let p = parent_node_id.index();
297
2
                    if let Some(&idx) = index_of.get(&(dom_id.inner, p)) {
298
2
                        parent_idx = Some(idx);
299
2
                        break;
300
                    }
301
                    if p >= node_hierarchy.len() {
302
                        break;
303
                    }
304
                    current = node_hierarchy[p].parent_id();
305
                }
306

            
307
3
                match parent_idx {
308
2
                    Some(p) => {
309
2
                        elements[self_idx].parent = Some(p);
310
2
                        elements[p].children.push(self_idx);
311
2
                    }
312
1
                    None => roots.push(self_idx),
313
                }
314
            }
315
        }
316

            
317
1
        Self {
318
1
            title: title.to_string(),
319
1
            elements,
320
1
            roots,
321
1
            window_size,
322
1
        }
323
1
    }
324

            
325
    /// Element at `index`, or `None` when the index is stale (the snapshot was
326
    /// rebuilt under the platform's feet). Returning `None` rather than
327
    /// panicking matters: `index` comes straight from `UIKit` / Android, i.e.
328
    /// from another process's idea of what the tree looks like.
329
    #[must_use]
330
    pub fn element(&self, index: usize) -> Option<&A11yElement> {
331
        self.elements.get(index)
332
    }
333

            
334
    /// Snapshot index for a DOM node, if it is exposed.
335
    #[must_use]
336
    pub fn index_of(&self, dom_id: DomId, node_id: NodeId) -> Option<usize> {
337
        self.elements
338
            .iter()
339
            .position(|e| e.dom_id == dom_id && e.node_id == node_id)
340
    }
341

            
342
    /// Index of the currently focused element, if any is exposed.
343
    #[must_use]
344
    pub fn focused(&self) -> Option<usize> {
345
        self.elements.iter().position(|e| e.focused)
346
    }
347

            
348
    #[must_use]
349
    pub const fn is_empty(&self) -> bool {
350
        self.elements.is_empty()
351
    }
352

            
353
    #[must_use]
354
    pub const fn len(&self) -> usize {
355
        self.elements.len()
356
    }
357
}
358

            
359
/// Absolute, padding/border-inset, viewport-clipped bounds in logical units.
360
///
361
/// Same geometry `A11yManager::build_node` computes for accesskit, minus the
362
/// `HiDPI` multiply — see [`A11yElement::bounds`] for why the scale stays with
363
/// the platform. A node with no layout (display:none, never laid out) gets a
364
/// zero rect, which every platform reads as "nothing to highlight".
365
3
fn element_bounds(
366
3
    layout_result: &DomLayoutResult,
367
3
    dom_id: DomId,
368
3
    node_id: NodeId,
369
3
    window_size: LogicalSize,
370
3
    scroll_manager: &ScrollManager,
371
3
    gpu_state: &crate::managers::gpu_state::GpuStateManager,
372
3
) -> LogicalRect {
373
3
    let zero = LogicalRect {
374
3
        origin: LogicalPosition { x: 0.0, y: 0.0 },
375
3
        size: LogicalSize {
376
3
            width: 0.0,
377
3
            height: 0.0,
378
3
        },
379
3
    };
380

            
381
3
    let Some(layout_idx) = layout_result
382
3
        .layout_tree
383
3
        .dom_to_layout
384
3
        .get(&node_id)
385
3
        .and_then(|indices| indices.first())
386
3
        .copied()
387
    else {
388
3
        return zero;
389
    };
390
    let Some(hot) = layout_result.layout_tree.get(layout_idx) else {
391
        return zero;
392
    };
393
    let (Some(pos), Some(size)) = (
394
        layout_result
395
            .calculated_positions
396
            .get(layout_idx.index())
397
            .copied(),
398
        hot.used_size,
399
    ) else {
400
        return zero;
401
    };
402

            
403
    let bp = hot.box_props.unpack();
404
    let pad_left = bp.padding.left + bp.border.left;
405
    let pad_top = bp.padding.top + bp.border.top;
406
    let pad_right = bp.padding.right + bp.border.right;
407
    let pad_bottom = bp.padding.bottom + bp.border.bottom;
408

            
409
    // Static padded rect in local space, THEN mapped to on-screen space
410
    // (ancestor scroll offsets + reference-frame transforms — what the
411
    // renderer actually painted), THEN clamped to the viewport. A screen
412
    // reader must be told where the element IS, not where it was laid out
413
    // before the user scrolled or an animation moved it.
414
    let local = LogicalRect {
415
        origin: LogicalPosition {
416
            x: pos.x + pad_left,
417
            y: pos.y + pad_top,
418
        },
419
        size: LogicalSize {
420
            width: (size.width - pad_left - pad_right).max(0.0),
421
            height: (size.height - pad_top - pad_bottom).max(0.0),
422
        },
423
    };
424
    let on_screen = crate::headless::node_rect_to_screen(
425
        layout_result,
426
        dom_id,
427
        layout_idx.index(),
428
        local,
429
        &|d, n| scroll_manager.get_current_offset(d, n),
430
        &|d, n| {
431
            gpu_state
432
                .caches
433
                .get(&d)
434
                .and_then(|c| c.css_current_transform_values.get(&n))
435
                .copied()
436
        },
437
    );
438

            
439
    let clamp = |v: f32, max: f32| v.max(0.0).min(max);
440
    let x0 = clamp(on_screen.origin.x, window_size.width);
441
    let y0 = clamp(on_screen.origin.y, window_size.height);
442
    let x1 = clamp(on_screen.origin.x + on_screen.size.width, window_size.width);
443
    let y1 = clamp(
444
        on_screen.origin.y + on_screen.size.height,
445
        window_size.height,
446
    );
447

            
448
    if x1 <= x0 || y1 <= y0 {
449
        return zero;
450
    }
451
    LogicalRect {
452
        origin: LogicalPosition { x: x0, y: y0 },
453
        size: LogicalSize {
454
            width: x1 - x0,
455
            height: y1 - y0,
456
        },
457
    }
458
3
}
459

            
460
/// Concatenate direct text children, and report whether any non-text child
461
/// exists (in which case the text must NOT become a group label — the screen
462
/// reader has to be able to navigate into the interactive children).
463
3
fn collect_child_text(
464
3
    node_data: &[NodeData],
465
3
    node_hierarchy: &[azul_core::styled_dom::NodeHierarchyItem],
466
3
    dom_idx: usize,
467
3
) -> (String, bool) {
468
3
    let mut text = String::new();
469
3
    let mut has_non_text = false;
470

            
471
3
    let mut child = node_hierarchy[dom_idx].first_child_id(NodeId::new(dom_idx));
472
3
    let mut guard = 0usize;
473
5
    while let Some(child_id) = child {
474
2
        guard += 1;
475
2
        if guard > 10_000 {
476
            break;
477
2
        }
478
2
        if let Some(child_data) = node_data.get(child_id.index()) {
479
2
            if let NodeType::Text(t) = &child_data.node_type {
480
1
                if !text.is_empty() {
481
                    text.push(' ');
482
1
                }
483
1
                text.push_str(t.as_str());
484
1
            } else {
485
1
                has_non_text = true;
486
1
            }
487
        }
488
2
        if child_id.index() >= node_hierarchy.len() {
489
            break;
490
2
        }
491
2
        child = node_hierarchy[child_id.index()].next_sibling_id();
492
    }
493

            
494
3
    (text, has_non_text)
495
3
}
496

            
497
/// Which actions this node accepts.
498
///
499
/// Mirrors what the accesskit builder advertises: `ScrollIntoView` on
500
/// everything, `Focus` on anything focusable or editable, `Default` on anything
501
/// with activation behaviour, the scroll family on an actually-scrollable
502
/// container, the text family on an editable one, plus whatever the app
503
/// declared in `AccessibilityInfo::supported_actions`.
504
///
505
/// This list is not decoration: [`A11yElement::supports`] is what the iOS and
506
/// Android bridges check before forwarding a platform action, so an element
507
/// cannot be sent an action the engine would silently drop.
508
3
fn supported_actions(
509
3
    node_data: &NodeData,
510
3
    scroll_manager: &ScrollManager,
511
3
    dom_id: DomId,
512
3
    node_id: NodeId,
513
3
) -> Vec<AccessibilityAction> {
514
3
    let mut actions = Vec::new();
515

            
516
3
    actions.push(AccessibilityAction::ScrollIntoView);
517

            
518
3
    if node_data.is_focusable() || node_data.is_contenteditable() {
519
1
        actions.push(AccessibilityAction::Focus);
520
1
        actions.push(AccessibilityAction::Blur);
521
2
    }
522
3
    if node_data.has_activation_behavior() {
523
1
        actions.push(AccessibilityAction::Default);
524
2
    }
525
3
    if node_data.is_contenteditable()
526
3
        || matches!(node_data.node_type, NodeType::TextArea | NodeType::Input)
527
    {
528
        actions.push(AccessibilityAction::SetValue(azul_css::AzString::from("")));
529
        actions.push(AccessibilityAction::ReplaceSelectedText(
530
            azul_css::AzString::from(""),
531
        ));
532
3
    }
533

            
534
3
    if let Some((_offset, max_x, max_y)) = scroll_manager.a11y_scroll_info(dom_id, node_id) {
535
        if max_y > 0.0 {
536
            actions.push(AccessibilityAction::ScrollUp);
537
            actions.push(AccessibilityAction::ScrollDown);
538
        }
539
        if max_x > 0.0 {
540
            actions.push(AccessibilityAction::ScrollLeft);
541
            actions.push(AccessibilityAction::ScrollRight);
542
        }
543
        actions.push(AccessibilityAction::SetScrollOffset(LogicalPosition {
544
            x: 0.0,
545
            y: 0.0,
546
        }));
547
3
    }
548

            
549
3
    if let Some(info) = node_data.get_accessibility_info() {
550
1
        for declared in info.supported_actions.as_ref() {
551
            if !actions.contains(declared) {
552
                actions.push(declared.clone());
553
            }
554
        }
555
2
    }
556

            
557
3
    actions
558
3
}
559

            
560
/// Fallback role for a node with no explicit `AccessibilityInfo`.
561
///
562
/// Deliberately small: only the roles the mobile platforms announce
563
/// differently. Everything else is `Grouping`, which both `UIKit` and Android
564
/// read as "a plain container" — the honest answer for a bare `<div>`, and
565
/// better than claiming a role the node does not have.
566
3
const fn node_type_to_role(node_type: &NodeType) -> AccessibilityRole {
567
3
    match node_type {
568
1
        NodeType::Button => AccessibilityRole::PushButton,
569
        NodeType::A => AccessibilityRole::Link,
570
        NodeType::Text(_)
571
        | NodeType::P
572
        | NodeType::Span
573
        | NodeType::H1
574
        | NodeType::H2
575
        | NodeType::H3
576
        | NodeType::H4
577
        | NodeType::H5
578
1
        | NodeType::H6 => AccessibilityRole::StaticText,
579
        NodeType::Input | NodeType::TextArea => AccessibilityRole::Text,
580
        NodeType::Image(_) => AccessibilityRole::Graphic,
581
        NodeType::Ul | NodeType::Ol => AccessibilityRole::List,
582
        NodeType::Li => AccessibilityRole::ListItem,
583
        NodeType::Table => AccessibilityRole::Table,
584
        NodeType::Td | NodeType::Th => AccessibilityRole::Cell,
585
1
        _ => AccessibilityRole::Grouping,
586
    }
587
3
}