Skip to main content

velox_engine/platform/
a11y_bridge.rs

1//! 原生无障碍协议桥接层(`AccessKitBridge`):将 [`crate::a11y`] 层次语义树与增量 Diff
2//! 1:1 映射为 AccessKit / Windows UIA / macOS NSAccessibility / Linux AT-SPI 兼容更新包,
3//! 并将屏幕阅读器下发的聚焦/点击/滚动/输入动作回灌至 [`VeloxEngine`]。
4
5use std::string::String;
6use std::vec::Vec;
7
8use crate::a11y::{
9    children_of, collect_a11y_nodes, diff_a11y_snapshot, snapshot_a11y_tree, A11yNodeSnapshot,
10    A11yRole,
11};
12use crate::arena::SmallVec;
13use crate::engine::VeloxEngine;
14use crate::pod::{InputEvent, KeyCode};
15use crate::solver::Region;
16
17/// AccessKit 兼容节点更新载荷(无生命周期借用,可直接序列化或喂给 `accesskit::Node`)。
18#[derive(Clone, PartialEq, Eq, Debug)]
19pub struct AccessKitNodeData {
20    pub id: u32,
21    pub role: A11yRole,
22    pub bounds: Region,
23    pub label: Option<String>,
24    pub value: Option<String>,
25    pub focusable: bool,
26    pub focused: bool,
27    pub disabled: bool,
28    pub checked: Option<bool>,
29    pub children: Vec<u32>,
30}
31
32/// 单帧增量无障碍树更新包(对应 `accesskit::TreeUpdate`,静息帧不生成任何 IPC 流量)。
33#[derive(Clone, PartialEq, Eq, Debug, Default)]
34pub struct AccessKitTreeUpdate {
35    pub root_id: u32,
36    pub focus_id: u32,
37    pub updated_nodes: Vec<AccessKitNodeData>,
38    pub removed_ids: Vec<u32>,
39}
40
41impl AccessKitTreeUpdate {
42    #[inline]
43    pub fn is_empty(&self) -> bool {
44        self.updated_nodes.is_empty() && self.removed_ids.is_empty()
45    }
46}
47
48/// 来自操作系统屏幕阅读器 / 辅助技术的逆向操作请求(对应 `accesskit::ActionRequest`)。
49#[derive(Clone, PartialEq, Eq, Debug)]
50pub enum AccessKitActionRequest {
51    Focus { target_id: u32 },
52    Click { target_id: u32 },
53    Scroll { target_id: u32, delta_y: i16 },
54    SetValue { target_id: u32, text: String },
55}
56
57/// 跨帧增量无障碍桥接器(维护上一帧快照基线,实现 0 冗余更新)。
58pub struct AccessKitBridge {
59    prev_snapshot: SmallVec<A11yNodeSnapshot, 256>,
60    last_focus_id: u32,
61    initialized: bool,
62}
63
64impl Default for AccessKitBridge {
65    fn default() -> Self {
66        Self::new()
67    }
68}
69
70impl AccessKitBridge {
71    pub fn new() -> Self {
72        Self {
73            prev_snapshot: SmallVec::new(),
74            last_focus_id: 0,
75            initialized: false,
76        }
77    }
78
79    /// 采集当前 [`VeloxEngine`] 的无障碍树并与上一帧做增量 Diff;若无任何变化返回 `None`。
80    pub fn sync_engine(&mut self, engine: &VeloxEngine) -> Option<AccessKitTreeUpdate> {
81        let nodes = collect_a11y_nodes::<256>(
82            engine.viewport_region(),
83            engine.cached_hit_regions(),
84            engine.cached_draw_ops(),
85            engine.focused_index(),
86        );
87        let cur_snap = snapshot_a11y_tree::<256>(nodes.as_slice());
88        let focus_id = nodes
89            .as_slice()
90            .iter()
91            .find(|n| n.focused)
92            .map(|n| n.id)
93            .unwrap_or(0);
94
95        if !self.initialized {
96            self.initialized = true;
97            self.prev_snapshot = cur_snap;
98            self.last_focus_id = focus_id;
99            let updated_nodes = nodes
100                .as_slice()
101                .iter()
102                .map(|n| AccessKitNodeData {
103                    id: n.id,
104                    role: n.role,
105                    bounds: n.bounds,
106                    label: n.label.map(|s| String::from(s.as_str())),
107                    value: n.value_text.map(|s| String::from(s.as_str())),
108                    focusable: n.focusable,
109                    focused: n.focused,
110                    disabled: n.disabled,
111                    checked: n.checked,
112                    children: children_of(nodes.as_slice(), n.id).map(|c| c.id).collect(),
113                })
114                .collect();
115            return Some(AccessKitTreeUpdate {
116                root_id: 0,
117                focus_id,
118                updated_nodes,
119                removed_ids: Vec::new(),
120            });
121        }
122
123        let diff = diff_a11y_snapshot::<256>(self.prev_snapshot.as_slice(), nodes.as_slice());
124        if diff.is_empty() && focus_id == self.last_focus_id {
125            return None;
126        }
127
128        let updated_nodes: Vec<AccessKitNodeData> = diff
129            .updated_nodes
130            .as_slice()
131            .iter()
132            .map(|n| AccessKitNodeData {
133                id: n.id,
134                role: n.role,
135                bounds: n.bounds,
136                label: n.label.map(|s| String::from(s.as_str())),
137                value: n.value_text.map(|s| String::from(s.as_str())),
138                focusable: n.focusable,
139                focused: n.focused,
140                disabled: n.disabled,
141                checked: n.checked,
142                children: children_of(nodes.as_slice(), n.id).map(|c| c.id).collect(),
143            })
144            .collect();
145        let removed_ids = diff.removed_ids.as_slice().to_vec();
146
147        self.prev_snapshot = cur_snap;
148        self.last_focus_id = focus_id;
149
150        Some(AccessKitTreeUpdate {
151            root_id: 0,
152            focus_id,
153            updated_nodes,
154            removed_ids,
155        })
156    }
157
158    /// 将操作系统屏幕阅读器发出的逆向操作请求翻译并派发给 [`VeloxEngine`]。
159    pub fn apply_action_request(
160        &self,
161        engine: &mut VeloxEngine,
162        req: AccessKitActionRequest,
163    ) -> bool {
164        let nodes = collect_a11y_nodes::<256>(
165            engine.viewport_region(),
166            engine.cached_hit_regions(),
167            engine.cached_draw_ops(),
168            engine.focused_index(),
169        );
170        match req {
171            AccessKitActionRequest::Focus { target_id } => {
172                if let Some(node) = nodes.as_slice().iter().find(|n| n.id == target_id) {
173                    let cx = node.bounds.x.saturating_add(node.bounds.w >> 1);
174                    let cy = node.bounds.y.saturating_add(node.bounds.h >> 1);
175                    return engine.dispatch_pointer_down(cx, cy)
176                        | engine.dispatch_pointer_up(cx, cy);
177                }
178                false
179            }
180            AccessKitActionRequest::Click { target_id } => {
181                if let Some(node) = nodes.as_slice().iter().find(|n| n.id == target_id) {
182                    let cx = node.bounds.x.saturating_add(node.bounds.w >> 1);
183                    let cy = node.bounds.y.saturating_add(node.bounds.h >> 1);
184                    return engine.dispatch_click(cx, cy);
185                }
186                false
187            }
188            AccessKitActionRequest::Scroll { target_id, delta_y } => {
189                if let Some(node) = nodes.as_slice().iter().find(|n| n.id == target_id) {
190                    let cx = node.bounds.x.saturating_add(node.bounds.w >> 1);
191                    let cy = node.bounds.y.saturating_add(node.bounds.h >> 1);
192                    return engine.dispatch_event(InputEvent::Scroll {
193                        x: cx,
194                        y: cy,
195                        delta_y,
196                    });
197                }
198                false
199            }
200            AccessKitActionRequest::SetValue { target_id, text } => {
201                let mut handled = false;
202                if let Some(node) = nodes.as_slice().iter().find(|n| n.id == target_id) {
203                    let cx = node.bounds.x.saturating_add(node.bounds.w >> 1);
204                    let cy = node.bounds.y.saturating_add(node.bounds.h >> 1);
205                    handled |= engine.dispatch_click(cx, cy);
206                    for ch in text.chars() {
207                        handled |= engine.dispatch_key(KeyCode::Char(ch));
208                    }
209                }
210                handled
211            }
212        }
213    }
214}