1use crate::arena::{SmallVec, StrRef};
9use crate::motion::{DrawOp, DrawPayload};
10use crate::solver::{HitRegion, Region};
11
12#[derive(Copy, Clone, PartialEq, Eq, Debug)]
14pub enum A11yRole {
15 Window,
17 Container,
19 Button,
21 TextInput,
23 Slider,
25 ScrollRegion,
27 Text,
29 Image,
31}
32
33#[derive(Copy, Clone, Debug)]
35pub struct A11yNode<'a> {
36 pub id: u32,
38 pub parent_id: Option<u32>,
40 pub role: A11yRole,
42 pub bounds: Region,
44 pub label: Option<StrRef<'a>>,
46 pub value_text: Option<StrRef<'a>>,
48 pub focusable: bool,
50 pub focused: bool,
52 pub disabled: bool,
54 pub checked: Option<bool>,
56 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 #[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 #[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#[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#[derive(Debug)]
136pub struct A11yTreeUpdate<'a, const CAP: usize> {
137 pub root_id: u32,
139 pub focus_id: Option<u32>,
141 pub focus_changed: bool,
143 pub updated_nodes: SmallVec<A11yNode<'a>, CAP>,
145 pub removed_ids: SmallVec<u32, CAP>,
147}
148
149impl<'a, const CAP: usize> A11yTreeUpdate<'a, CAP> {
150 #[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
171fn 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
198pub 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 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
396pub 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#[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
416pub 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
450pub 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}