Skip to main content

velox_engine/
a11y.rs

1//! 无障碍语义树(Accessibility Semantic Tree,兼容 AccessKit / AT-SPI / UI Automation 层次与增量 Diff 模型)。
2//!
3//! 核心特性:
4//! - **100% `#![no_std]` 零堆分配**:从当前帧 `HitRegion` 与 `DrawOp` 自动推导带父子归属的层次无障碍树;
5//! - **跨帧增量更新(AccessKit `TreeUpdate` 1:1 映射)**:通过 [`snapshot_a11y_tree`] 与 [`diff_a11y_snapshot`] /
6//!   [`diff_a11y_trees`] 计算最小变更集(`updated_nodes`、`removed_ids`、`focus_id`),静息帧输出空更新(零屏幕阅读器 IPC 噪声)。
7
8use crate::arena::{SmallVec, StrRef};
9use crate::motion::{DrawOp, DrawPayload};
10use crate::solver::{HitRegion, Region};
11
12/// 无障碍语义角色分类(对应 AccessKit / WAI-ARIA / AT-SPI 核心 Role)。
13#[derive(Copy, Clone, PartialEq, Eq, Debug)]
14pub enum A11yRole {
15    /// 根视口或顶层窗口。
16    Window,
17    /// 通用分组容器。
18    Container,
19    /// 可点击按钮。
20    Button,
21    /// 单行或多行文本输入框。
22    TextInput,
23    /// 可拖拽滑块或数值调节器。
24    Slider,
25    /// 可滚动视口区域。
26    ScrollRegion,
27    /// 静态文本标签。
28    Text,
29    /// 图像或图标。
30    Image,
31}
32
33/// 单个无障碍语义节点快照(带父节点归属与状态属性,兼容 AccessKit `Node` 模型)。
34#[derive(Copy, Clone, Debug)]
35pub struct A11yNode<'a> {
36    /// 节点稳定无障碍 ID(`0` 固定保留为根 `Window`)。
37    pub id: u32,
38    /// 所属父级语义节点 ID(根 `Window` 为 `None`,其余节点均精确指向其最内层容器或根 `Some(0)`)。
39    pub parent_id: Option<u32>,
40    /// 节点语义角色。
41    pub role: A11yRole,
42    /// 屏幕边界矩形。
43    pub bounds: Region,
44    /// 可选的可读文本标签(Accessible Name,如按钮文字或静态文本)。
45    pub label: Option<StrRef<'a>>,
46    /// 可选的控件当前值文本(如 `TextInput` 的编辑内容或 `Slider` 数值)。
47    pub value_text: Option<StrRef<'a>>,
48    /// 是否可接收键盘/旋钮焦点。
49    pub focusable: bool,
50    /// 当前是否处于键盘/旋钮聚焦态。
51    pub focused: bool,
52    /// 节点当前是否处于禁用态。
53    pub disabled: bool,
54    /// 可选勾选/开关状态(`Some(true/false)` 对应复选框/开关/单选态)。
55    pub checked: Option<bool>,
56    /// 若为滚动容器,包含 `(scroll_id, max_scroll, horizontal)`。
57    pub scroll_info: Option<(u32, i16, bool)>,
58}
59
60#[inline]
61fn hash_opt_str(s: Option<StrRef<'_>>) -> u64 {
62    let Some(sr) = s else {
63        return 0;
64    };
65    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
66    for &b in sr.as_str().as_bytes() {
67        h ^= b as u64;
68        h = h.wrapping_mul(0x0100_0000_01b3);
69    }
70    h | 1
71}
72
73impl<'a> A11yNode<'a> {
74    /// 跨生命周期按内容比较两个无障碍节点是否完全一致(忽略底层 `ScratchArena` 指针地址差异)。
75    #[inline]
76    pub fn content_eq(&self, other: &A11yNode<'_>) -> bool {
77        self.id == other.id
78            && self.parent_id == other.parent_id
79            && self.role == other.role
80            && self.bounds == other.bounds
81            && self.label.map(|s| s.as_str()) == other.label.map(|s| s.as_str())
82            && self.value_text.map(|s| s.as_str()) == other.value_text.map(|s| s.as_str())
83            && self.focusable == other.focusable
84            && self.focused == other.focused
85            && self.disabled == other.disabled
86            && self.checked == other.checked
87            && self.scroll_info == other.scroll_info
88    }
89
90    /// 转换为无生命周期依赖的跨帧指纹快照 [`A11yNodeSnapshot`]。
91    #[inline]
92    pub fn to_snapshot(&self) -> A11yNodeSnapshot {
93        A11yNodeSnapshot {
94            id: self.id,
95            parent_id: self.parent_id,
96            role: self.role,
97            bounds: self.bounds,
98            label_hash: hash_opt_str(self.label),
99            value_hash: hash_opt_str(self.value_text),
100            focusable: self.focusable,
101            focused: self.focused,
102            disabled: self.disabled,
103            checked: self.checked,
104            scroll_info: self.scroll_info,
105        }
106    }
107}
108
109impl PartialEq for A11yNode<'_> {
110    #[inline]
111    fn eq(&self, other: &Self) -> bool {
112        self.content_eq(other)
113    }
114}
115
116impl Eq for A11yNode<'_> {}
117
118/// 无生命周期借用的跨帧无障碍节点指纹(`Copy`,可跨越 `ScratchArena::rewind()` 持久化存储以驱动增量 Diff)。
119#[derive(Copy, Clone, PartialEq, Eq, Debug)]
120pub struct A11yNodeSnapshot {
121    pub id: u32,
122    pub parent_id: Option<u32>,
123    pub role: A11yRole,
124    pub bounds: Region,
125    pub label_hash: u64,
126    pub value_hash: u64,
127    pub focusable: bool,
128    pub focused: bool,
129    pub disabled: bool,
130    pub checked: Option<bool>,
131    pub scroll_info: Option<(u32, i16, bool)>,
132}
133
134/// 与 AccessKit `TreeUpdate` 1:1 映射的 `#![no_std]` 零堆增量无障碍树更新补丁。
135#[derive(Debug)]
136pub struct A11yTreeUpdate<'a, const CAP: usize> {
137    /// 根节点 ID(固定为 `0` 对应 [`A11yRole::Window`])。
138    pub root_id: u32,
139    /// 本帧当前拥有焦点的语义节点 ID(`None` 表示焦点停留在窗口根)。
140    pub focus_id: Option<u32>,
141    /// 本帧焦点是否相较上一帧发生转移。
142    pub focus_changed: bool,
143    /// 本帧新增或属性/位置/父关系发生变更的语义节点集合。
144    pub updated_nodes: SmallVec<A11yNode<'a>, CAP>,
145    /// 本帧从语义树中移除的旧节点 ID 列表。
146    pub removed_ids: SmallVec<u32, CAP>,
147}
148
149impl<'a, const CAP: usize> A11yTreeUpdate<'a, CAP> {
150    /// 当节点无任何新增、变更、删除且焦点未变化时返回 `true`(平台桥接层可直接跳过 IPC 推送)。
151    #[inline]
152    pub fn is_empty(&self) -> bool {
153        !self.focus_changed && self.updated_nodes.is_empty() && self.removed_ids.is_empty()
154    }
155}
156
157#[inline]
158fn region_contains(outer: Region, inner: Region) -> bool {
159    !outer.is_empty()
160        && inner.x >= outer.x
161        && inner.y >= outer.y
162        && inner.right() <= outer.right()
163        && inner.bottom() <= outer.bottom()
164}
165
166#[inline]
167fn region_area(r: Region) -> i32 {
168    (r.w.max(0) as i32) * (r.h.max(0) as i32)
169}
170
171/// 在已收集的语义节点中选择包含 `bounds` 的最内层合法父节点 ID(若无更小容器则回退为根窗口 `0`)。
172fn find_best_parent_id(nodes: &[A11yNode<'_>], bounds: Region, self_id: u32, allow_leaf_parents: bool) -> u32 {
173    let mut best_id = 0u32;
174    let mut best_area = i32::MAX;
175    for n in nodes.iter().skip(1) {
176        if n.id == self_id {
177            continue;
178        }
179        let can_be_parent = match n.role {
180            A11yRole::Window | A11yRole::Container | A11yRole::ScrollRegion => true,
181            A11yRole::Button | A11yRole::TextInput | A11yRole::Slider => allow_leaf_parents,
182            A11yRole::Text | A11yRole::Image => false,
183        };
184        if !can_be_parent {
185            continue;
186        }
187        if region_contains(n.bounds, bounds) {
188            let area = region_area(n.bounds);
189            if area <= best_area {
190                best_area = area;
191                best_id = n.id;
192            }
193        }
194    }
195    best_id
196}
197
198/// 从当前帧缓存的 `HitRegion` 与 `DrawOp` 列表构建层次化无障碍语义树节点序列(含 `parent_id` 归属关系)。
199pub fn collect_a11y_nodes<'a, const CAP: usize>(
200    viewport: Region,
201    hits: &[HitRegion<'a>],
202    ops: &[DrawOp<'a>],
203    focused_index: Option<u16>,
204) -> SmallVec<A11yNode<'a>, CAP> {
205    let mut out = SmallVec::new();
206    let _ = out.push(A11yNode {
207        id: 0,
208        parent_id: None,
209        role: A11yRole::Window,
210        bounds: viewport,
211        label: None,
212        value_text: None,
213        focusable: false,
214        focused: false,
215        disabled: false,
216        checked: None,
217        scroll_info: None,
218    });
219
220    for (idx, hit) in hits.iter().enumerate() {
221        let has_key_input = hit
222            .interact
223            .and_then(|i| i.rare)
224            .and_then(|r| r.on_key_input)
225            .is_some();
226        let has_drag = hit
227            .interact
228            .and_then(|i| i.rare)
229            .and_then(|r| r.on_drag)
230            .is_some();
231        let has_click = hit.interact.and_then(|i| i.on_click).is_some();
232
233        let role = if has_key_input {
234            A11yRole::TextInput
235        } else if has_drag {
236            A11yRole::Slider
237        } else if has_click {
238            A11yRole::Button
239        } else if hit.scroll_target.is_some() {
240            A11yRole::ScrollRegion
241        } else {
242            A11yRole::Container
243        };
244
245        // 查找落在该交互区域内的第一段文本作为无障碍标签(Accessible Name)
246        let label = ops.iter().find_map(|op| match op.payload {
247            DrawPayload::TextRun { text, .. }
248                if !op.bounds.intersect(hit.bounds).is_empty() =>
249            {
250                Some(text)
251            }
252            _ => None,
253        });
254        let value_text = if role == A11yRole::TextInput {
255            label
256        } else {
257            None
258        };
259
260        let id = hit.id.unwrap_or((idx as u32) + 1);
261        let parent_id = Some(find_best_parent_id(out.as_slice(), hit.bounds, id, false));
262        let focusable = hit.focus_index.is_some();
263        let focused = hit.focus_index.is_some() && hit.focus_index == focused_index;
264        let scroll_info = hit
265            .scroll_target
266            .map(|(sid, max_s)| (sid, max_s, hit.scroll_horizontal));
267
268        let _ = out.push(A11yNode {
269            id,
270            parent_id,
271            role,
272            bounds: hit.bounds,
273            label,
274            value_text,
275            focusable,
276            focused,
277            disabled: false,
278            checked: None,
279            scroll_info,
280        });
281    }
282
283    for op in ops.iter() {
284        match op.payload {
285            DrawPayload::TextRun { text, .. } => {
286                let parent = find_best_parent_id(out.as_slice(), op.bounds, u32::MAX, true);
287                let ordinal = out
288                    .as_slice()
289                    .iter()
290                    .filter(|n| n.role == A11yRole::Text && n.parent_id == Some(parent))
291                    .count() as u32;
292                let id = op
293                    .id
294                    .unwrap_or_else(|| crate::pod::derive_scoped_id(parent, 0xA117_7E57, ordinal));
295                let _ = out.push(A11yNode {
296                    id,
297                    parent_id: Some(parent),
298                    role: A11yRole::Text,
299                    bounds: op.bounds,
300                    label: Some(text),
301                    value_text: None,
302                    focusable: false,
303                    focused: false,
304                    disabled: false,
305                    checked: None,
306                    scroll_info: None,
307                });
308            }
309            DrawPayload::Sprite(_) => {
310                let parent = find_best_parent_id(out.as_slice(), op.bounds, u32::MAX, true);
311                let ordinal = out
312                    .as_slice()
313                    .iter()
314                    .filter(|n| n.role == A11yRole::Image && n.parent_id == Some(parent))
315                    .count() as u32;
316                let id = op
317                    .id
318                    .unwrap_or_else(|| crate::pod::derive_scoped_id(parent, 0xA117_16A9, ordinal));
319                let _ = out.push(A11yNode {
320                    id,
321                    parent_id: Some(parent),
322                    role: A11yRole::Image,
323                    bounds: op.bounds,
324                    label: None,
325                    value_text: None,
326                    focusable: false,
327                    focused: false,
328                    disabled: false,
329                    checked: None,
330                    scroll_info: None,
331                });
332            }
333            DrawPayload::RichText(rt) => {
334                if let Some(first_span) = rt.spans.first() {
335                    let parent = find_best_parent_id(out.as_slice(), op.bounds, u32::MAX, true);
336                    let ordinal = out
337                        .as_slice()
338                        .iter()
339                        .filter(|n| n.role == A11yRole::Text && n.parent_id == Some(parent))
340                        .count() as u32;
341                    let id = op.id.unwrap_or_else(|| {
342                        crate::pod::derive_scoped_id(parent, 0xA117_7E88, ordinal)
343                    });
344                    let _ = out.push(A11yNode {
345                        id,
346                        parent_id: Some(parent),
347                        role: A11yRole::Text,
348                        bounds: op.bounds,
349                        label: Some(first_span.text),
350                        value_text: None,
351                        focusable: false,
352                        focused: false,
353                        disabled: false,
354                        checked: None,
355                        scroll_info: None,
356                    });
357                }
358            }
359            DrawPayload::DecodedImage(_)
360            | DrawPayload::Vector(_)
361            | DrawPayload::SceneCanvas(_) => {
362                let parent = find_best_parent_id(out.as_slice(), op.bounds, u32::MAX, true);
363                let ordinal = out
364                    .as_slice()
365                    .iter()
366                    .filter(|n| n.role == A11yRole::Image && n.parent_id == Some(parent))
367                    .count() as u32;
368                let id = op
369                    .id
370                    .unwrap_or_else(|| crate::pod::derive_scoped_id(parent, 0xA117_16AA, ordinal));
371                let _ = out.push(A11yNode {
372                    id,
373                    parent_id: Some(parent),
374                    role: A11yRole::Image,
375                    bounds: op.bounds,
376                    label: None,
377                    value_text: None,
378                    focusable: false,
379                    focused: false,
380                    disabled: false,
381                    checked: None,
382                    scroll_info: None,
383                });
384            }
385            DrawPayload::Quad { .. }
386            | DrawPayload::StyledQuad(_)
387            | DrawPayload::PushLayer(_)
388            | DrawPayload::PopLayer
389            | DrawPayload::ExternalTexture(_) => {}
390        }
391    }
392
393    out
394}
395
396/// 将一帧无障碍节点列表压缩为无生命周期借用的 [`A11yNodeSnapshot`] 列表,供跨帧增量 Diff 使用。
397pub fn snapshot_a11y_tree<const CAP: usize>(
398    nodes: &[A11yNode<'_>],
399) -> SmallVec<A11yNodeSnapshot, CAP> {
400    let mut out = SmallVec::new();
401    for n in nodes {
402        let _ = out.push(n.to_snapshot());
403    }
404    out
405}
406
407/// 迭代查询指定 `parent_id` 的全部直接子节点(便于 AccessKit 桥接层填充 `Node::children`)。
408#[inline]
409pub fn children_of<'a, 'b>(
410    nodes: &'b [A11yNode<'a>],
411    parent_id: u32,
412) -> impl Iterator<Item = &'b A11yNode<'a>> {
413    nodes.iter().filter(move |n| n.parent_id == Some(parent_id))
414}
415
416/// 对比上一帧无生命周期快照 `prev` 与当前帧 `curr`,生成最小增量 [`A11yTreeUpdate`]。
417pub fn diff_a11y_snapshot<'a, const CAP: usize>(
418    prev: &[A11yNodeSnapshot],
419    curr: &[A11yNode<'a>],
420) -> A11yTreeUpdate<'a, CAP> {
421    let mut updated_nodes = SmallVec::new();
422    let mut removed_ids = SmallVec::new();
423
424    let prev_focus = prev.iter().find(|n| n.focused).map(|n| n.id);
425    let curr_focus = curr.iter().find(|n| n.focused).map(|n| n.id);
426
427    for c in curr {
428        let snap = c.to_snapshot();
429        let unchanged = prev.iter().any(|p| p.id == snap.id && *p == snap);
430        if !unchanged {
431            let _ = updated_nodes.push(*c);
432        }
433    }
434
435    for p in prev {
436        if !curr.iter().any(|c| c.id == p.id) {
437            let _ = removed_ids.push(p.id);
438        }
439    }
440
441    A11yTreeUpdate {
442        root_id: 0,
443        focus_id: curr_focus,
444        focus_changed: prev_focus != curr_focus,
445        updated_nodes,
446        removed_ids,
447    }
448}
449
450/// 直接对比两帧无障碍节点序列 `prev` 与 `curr`,生成最小增量 [`A11yTreeUpdate`]。
451pub fn diff_a11y_trees<'a, const CAP: usize>(
452    prev: &[A11yNode<'_>],
453    curr: &[A11yNode<'a>],
454) -> A11yTreeUpdate<'a, CAP> {
455    let mut updated_nodes = SmallVec::new();
456    let mut removed_ids = SmallVec::new();
457
458    let prev_focus = prev.iter().find(|n| n.focused).map(|n| n.id);
459    let curr_focus = curr.iter().find(|n| n.focused).map(|n| n.id);
460
461    for c in curr {
462        let unchanged = prev.iter().any(|p| p.id == c.id && c.content_eq(p));
463        if !unchanged {
464            let _ = updated_nodes.push(*c);
465        }
466    }
467
468    for p in prev {
469        if !curr.iter().any(|c| c.id == p.id) {
470            let _ = removed_ids.push(p.id);
471        }
472    }
473
474    A11yTreeUpdate {
475        root_id: 0,
476        focus_id: curr_focus,
477        focus_changed: prev_focus != curr_focus,
478        updated_nodes,
479        removed_ids,
480    }
481}