xa11y-core 0.14.0

Core types, traits, and selector engine for xa11y cross-platform accessibility
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
//! In-memory mock Provider and test tree for binding tests.
//!
//! Gated behind the `test-support` feature so it only ships when a downstream
//! crate explicitly opts in (bindings' test builds, examples). The tree and
//! Provider impl are shared between `xa11y-python` and `xa11y-js` — neither
//! binding needed a bespoke mock; only their wrapper shapes differ.
//!
//! # Topology
//!
//! ```text
//! application "TestApp" (stable_id="app-root", desc="Test application")
//! └── window "Main Window" (focused, active)
//!     ├── toolbar "Navigation"
//!     │   ├── button "Back" (stable_id="btn-back", desc="Go back")
//!     │   └── button "Forward" (disabled)
//!     └── group "Content"
//!         ├── text_field "Search" (value="hello", editable, desc="Search field")
//!         ├── check_box "Agree" (checked=on)
//!         ├── slider "Volume" (numeric=75, min=0, max=100)
//!         ├── static_text "Status" (value="Loading...", visible=false)
//!         └── list "Items" (expanded=true)
//!             ├── list_item "Item 1" (selected)
//!             └── list_item "Item 2"
//! ```
//!
//! # Shell surfaces
//!
//! Two parentless roots model the OS shell (see [`crate::shell`]). They are
//! reachable only through [`Provider::list_shell_surfaces`] — deliberately not
//! from `list_apps` / `get_children(None)`, so shell UI stays invisible to code
//! that only asks for applications:
//!
//! ```text
//! toolbar "Taskbar" (shell surface: taskbar, pid=MOCK_SHELL_PID)
//! ├── button "Show Hidden Icons" (stable_id="systray-chevron")
//! └── button "Volume" (stable_id="SystemTrayIcon")
//!
//! list "Desktop" (shell surface: desktop, pid=MOCK_SHELL_PID)
//! └── list_item "Trash"
//! ```
//!
//! Call [`build_provider`] to get an `Arc<dyn Provider>`. The provider records
//! actions into an internal log; use [`MockProviderHandle::actions`] to inspect
//! them from tests.

use std::collections::HashMap;
use std::sync::{Arc, Mutex};

use crate::element::{ElementData, Rect, StateSet, Toggled};
use crate::error::{Error, Result};
use crate::event_provider::Subscription;
use crate::provider::Provider;
use crate::role::Role;
use crate::shell::ShellSurfaceKind;

/// Pid the mock reports for its shell-surface roots and their subtrees.
/// Distinct from the test app's 1234 so `ShellSurface::pid` is checkable and
/// so shell nodes can't be confused with app nodes.
pub const MOCK_SHELL_PID: u32 = 4242;

/// Index of the first shell node. Everything from here on belongs to a shell
/// surface rather than to the test application.
const FIRST_SHELL_NODE: usize = 13;

/// The mock's shell surfaces, as `(kind, node index)`. The indices are
/// positions in the element table `build_provider` builds below — the shell
/// roots are the parentless nodes appended after the application subtree.
const SHELL_SURFACES: [(ShellSurfaceKind, usize); 2] = [
    (ShellSurfaceKind::Taskbar, FIRST_SHELL_NODE),
    (ShellSurfaceKind::Desktop, FIRST_SHELL_NODE + 3),
];

/// Tuple describing one row in the mock element table.
///
/// Kept as a type alias so clippy's `type_complexity` lint stays happy.
type MockElementSpec<'a> = (
    Role,
    Option<&'a str>, // name
    Option<&'a str>, // value
    Option<&'a str>, // description
    Option<Rect>,
    Vec<&'a str>, // actions
    StateSet,
    Option<f64>,                                // numeric_value
    Option<f64>,                                // min_value
    Option<f64>,                                // max_value
    Option<&'a str>,                            // stable_id
    Option<HashMap<String, serde_json::Value>>, // raw
);

/// One entry in the mock's action log. `(handle, action_name, optional_argument)`.
pub type ActionLogEntry = (u64, String, Option<String>);

/// Mock provider backing the test tree.
pub struct MockProvider {
    nodes: Vec<MockNode>,
    actions: Mutex<Vec<ActionLogEntry>>,
}

impl MockProvider {
    /// Return a clone of the action log recorded so far.
    pub fn actions(&self) -> Vec<ActionLogEntry> {
        self.actions
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clone()
    }

    /// Clear the action log.
    pub fn clear_actions(&self) {
        self.actions
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .clear();
    }

    fn record(&self, el: &ElementData, action: &str, data: Option<String>) -> Result<()> {
        self.actions
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .push((el.handle, action.to_string(), data));
        Ok(())
    }
}

struct MockNode {
    data: ElementData,
    children: Vec<usize>,
    parent: Option<usize>,
}

impl Provider for MockProvider {
    fn get_children(&self, element: Option<&ElementData>) -> Result<Vec<ElementData>> {
        match element {
            None => {
                if self.nodes.is_empty() {
                    return Ok(vec![]);
                }
                Ok(vec![self.nodes[0].data.clone()])
            }
            Some(el) => {
                let idx = el.handle as usize;
                if idx >= self.nodes.len() {
                    return Ok(vec![]);
                }
                Ok(self.nodes[idx]
                    .children
                    .iter()
                    .map(|&i| self.nodes[i].data.clone())
                    .collect())
            }
        }
    }

    fn get_parent(&self, element: &ElementData) -> Result<Option<ElementData>> {
        let idx = element.handle as usize;
        if idx >= self.nodes.len() {
            return Ok(None);
        }
        Ok(self.nodes[idx].parent.map(|i| self.nodes[i].data.clone()))
    }

    fn list_apps(&self) -> Result<Vec<ElementData>> {
        // The mock tree's root is a single Application node; expose it as
        // the lone "app" so Locator's rootless path enumerates it.
        if self.nodes.is_empty() {
            return Ok(vec![]);
        }
        Ok(vec![self.nodes[0].data.clone()])
    }

    fn focused_app(&self) -> Result<ElementData> {
        // The mock has a single application root; treat it as the foreground
        // app so `App::is_foreground` / `find(|a| a.focused())` have something
        // to resolve against in binding and core tests.
        if self.nodes.is_empty() {
            return Err(Error::selector_not_matched("focused application"));
        }
        Ok(self.nodes[0].data.clone())
    }

    fn list_shell_surfaces(&self) -> Result<Vec<(ShellSurfaceKind, ElementData)>> {
        // Fixed fixture: `SHELL_SURFACES`' indices name nodes `build_provider`
        // always creates, so indexing here cannot be out of range.
        Ok(SHELL_SURFACES
            .iter()
            .map(|(kind, idx)| (*kind, self.nodes[*idx].data.clone()))
            .collect())
    }

    fn press(&self, el: &ElementData) -> Result<()> {
        self.record(el, "press", None)
    }
    fn focus(&self, el: &ElementData) -> Result<()> {
        self.record(el, "focus", None)
    }
    fn blur(&self, el: &ElementData) -> Result<()> {
        self.record(el, "blur", None)
    }
    fn toggle(&self, el: &ElementData) -> Result<()> {
        self.record(el, "toggle", None)
    }
    fn select(&self, el: &ElementData) -> Result<()> {
        self.record(el, "select", None)
    }
    fn expand(&self, el: &ElementData) -> Result<()> {
        self.record(el, "expand", None)
    }
    fn collapse(&self, el: &ElementData) -> Result<()> {
        self.record(el, "collapse", None)
    }
    fn show_menu(&self, el: &ElementData) -> Result<()> {
        self.record(el, "show_menu", None)
    }
    fn increment(&self, el: &ElementData) -> Result<()> {
        self.record(el, "increment", None)
    }
    fn decrement(&self, el: &ElementData) -> Result<()> {
        self.record(el, "decrement", None)
    }
    fn scroll_into_view(&self, el: &ElementData) -> Result<()> {
        self.record(el, "scroll_into_view", None)
    }
    fn set_value(&self, el: &ElementData, value: &str) -> Result<()> {
        self.record(el, "set_value", Some(value.to_string()))
    }
    fn set_numeric_value(&self, el: &ElementData, v: f64) -> Result<()> {
        self.record(el, "set_numeric_value", Some(format!("{v}")))
    }
    fn type_text(&self, el: &ElementData, text: &str) -> Result<()> {
        self.record(el, "type_text", Some(text.to_string()))
    }
    fn set_text_selection(&self, el: &ElementData, start: u32, end: u32) -> Result<()> {
        self.record(el, "set_text_selection", Some(format!("{start}..{end}")))
    }
    fn perform_action(&self, el: &ElementData, action: &str) -> Result<()> {
        self.record(el, action, None)
    }
    fn subscribe(&self, _el: &ElementData) -> Result<Subscription> {
        Err(Error::Platform {
            code: -1,
            message: "MockProvider does not support subscribe".to_string(),
        })
    }
}

/// Build the standard test tree (Python/JS bindings share this).
///
/// Returns an `Arc<MockProvider>` so callers can inspect the action log via
/// [`MockProvider::actions`] while also using it as a `Provider` (via
/// `Arc<dyn Provider>`, supported by the blanket `&T: Provider` impl and
/// `Arc`'s `Deref` coercion).
pub fn build_provider() -> Arc<MockProvider> {
    use serde_json::json;

    let elements: Vec<MockElementSpec> = vec![
        (
            Role::Application,
            Some("TestApp"),
            None,
            Some("Test application"),
            Some(Rect {
                x: 0,
                y: 0,
                width: 1920,
                height: 1080,
            }),
            vec![],
            StateSet::default(),
            None,
            None,
            None,
            Some("app-root"),
            // Example raw metadata — gives the tests a concrete value to
            // assert on via Element.raw.
            Some(HashMap::from([(
                "ax_role".to_string(),
                json!("AXApplication"),
            )])),
        ),
        (
            Role::Window,
            Some("Main Window"),
            None,
            None,
            Some(Rect {
                x: 100,
                y: 50,
                width: 800,
                height: 600,
            }),
            vec![],
            // The mock models the foreground app, so its main window is the
            // active window — mirrors `focused_app` returning the app root.
            StateSet {
                focused: true,
                active: true,
                ..StateSet::default()
            },
            None,
            None,
            None,
            None,
            None,
        ),
        (
            Role::Toolbar,
            Some("Navigation"),
            None,
            None,
            None,
            vec![],
            StateSet::default(),
            None,
            None,
            None,
            None,
            None,
        ),
        (
            Role::Button,
            Some("Back"),
            None,
            Some("Go back"),
            Some(Rect {
                x: 110,
                y: 60,
                width: 50,
                height: 30,
            }),
            vec!["press", "focus"],
            StateSet {
                focusable: true,
                ..StateSet::default()
            },
            None,
            None,
            None,
            Some("btn-back"),
            None,
        ),
        (
            Role::Button,
            Some("Forward"),
            None,
            None,
            Some(Rect {
                x: 170,
                y: 60,
                width: 50,
                height: 30,
            }),
            vec!["press", "focus"],
            StateSet {
                enabled: false,
                focusable: true,
                ..StateSet::default()
            },
            None,
            None,
            None,
            None,
            None,
        ),
        (
            Role::Group,
            Some("Content"),
            None,
            None,
            None,
            vec![],
            StateSet::default(),
            None,
            None,
            None,
            None,
            None,
        ),
        (
            Role::TextField,
            Some("Search"),
            Some("hello"),
            Some("Search field"),
            Some(Rect {
                x: 200,
                y: 120,
                width: 300,
                height: 25,
            }),
            vec!["focus", "set_value", "type_text"],
            StateSet {
                editable: true,
                focusable: true,
                ..StateSet::default()
            },
            None,
            None,
            None,
            None,
            None,
        ),
        (
            Role::CheckBox,
            Some("Agree"),
            None,
            None,
            None,
            vec!["press", "focus"],
            StateSet {
                checked: Some(Toggled::On),
                focusable: true,
                ..StateSet::default()
            },
            None,
            None,
            None,
            None,
            None,
        ),
        (
            Role::Slider,
            Some("Volume"),
            Some("75"),
            None,
            None,
            vec!["increment", "decrement", "set_value", "focus"],
            StateSet {
                focusable: true,
                ..StateSet::default()
            },
            Some(75.0),
            Some(0.0),
            Some(100.0),
            None,
            None,
        ),
        (
            Role::StaticText,
            Some("Status"),
            Some("Loading..."),
            None,
            None,
            vec![],
            StateSet {
                visible: false,
                ..StateSet::default()
            },
            None,
            None,
            None,
            None,
            None,
        ),
        (
            Role::List,
            Some("Items"),
            None,
            None,
            None,
            vec![],
            StateSet {
                expanded: Some(true),
                ..StateSet::default()
            },
            None,
            None,
            None,
            None,
            None,
        ),
        (
            Role::ListItem,
            Some("Item 1"),
            None,
            None,
            None,
            vec!["select", "focus"],
            StateSet {
                selected: true,
                focusable: true,
                ..StateSet::default()
            },
            None,
            None,
            None,
            None,
            None,
        ),
        (
            Role::ListItem,
            Some("Item 2"),
            None,
            None,
            None,
            vec!["select", "focus"],
            StateSet {
                focusable: true,
                ..StateSet::default()
            },
            None,
            None,
            None,
            None,
            None,
        ),
        // ── Shell surfaces (indices 13.., parentless) ─────────────────
        // The taskbar surface: a chevron that opens the tray overflow plus
        // one visible tray icon — the shape the Windows overflow workflow
        // drives.
        (
            Role::Toolbar,
            Some("Taskbar"),
            None,
            None,
            Some(Rect {
                x: 0,
                y: 1040,
                width: 1920,
                height: 40,
            }),
            vec![],
            StateSet::default(),
            None,
            None,
            None,
            Some("Shell_TrayWnd"),
            None,
        ),
        (
            Role::Button,
            Some("Show Hidden Icons"),
            None,
            Some("Open the tray overflow"),
            Some(Rect {
                x: 1700,
                y: 1045,
                width: 30,
                height: 30,
            }),
            vec!["press", "focus"],
            StateSet {
                focusable: true,
                ..StateSet::default()
            },
            None,
            None,
            None,
            Some("systray-chevron"),
            None,
        ),
        (
            Role::Button,
            Some("Volume"),
            None,
            None,
            Some(Rect {
                x: 1740,
                y: 1045,
                width: 30,
                height: 30,
            }),
            vec!["press", "focus"],
            StateSet {
                focusable: true,
                ..StateSet::default()
            },
            None,
            None,
            None,
            Some("SystemTrayIcon"),
            None,
        ),
        // A second surface of a different kind, so kind filtering and the
        // ambiguity refusal have something to discriminate between.
        (
            Role::List,
            Some("Desktop"),
            None,
            None,
            None,
            vec![],
            StateSet::default(),
            None,
            None,
            None,
            Some("Progman"),
            None,
        ),
        (
            Role::ListItem,
            Some("Trash"),
            None,
            None,
            None,
            vec!["select", "focus"],
            StateSet {
                focusable: true,
                ..StateSet::default()
            },
            None,
            None,
            None,
            None,
            None,
        ),
    ];

    // Parent/child topology indexed by position in `elements`.
    let children_map: Vec<Vec<usize>> = vec![
        vec![1],              // 0: application
        vec![2, 5],           // 1: window
        vec![3, 4],           // 2: toolbar
        vec![],               // 3: button Back
        vec![],               // 4: button Forward
        vec![6, 7, 8, 9, 10], // 5: group
        vec![],               // 6: text_field
        vec![],               // 7: check_box
        vec![],               // 8: slider
        vec![],               // 9: static_text
        vec![11, 12],         // 10: list
        vec![],               // 11: list_item 1
        vec![],               // 12: list_item 2
        vec![14, 15],         // 13: taskbar surface root
        vec![],               // 14: button Show Hidden Icons
        vec![],               // 15: button Volume
        vec![17],             // 16: desktop surface root
        vec![],               // 17: list_item Trash
    ];
    let parent_map: Vec<Option<usize>> = vec![
        None,
        Some(0),
        Some(1),
        Some(2),
        Some(2),
        Some(1),
        Some(5),
        Some(5),
        Some(5),
        Some(5),
        Some(5),
        Some(10),
        Some(10),
        // Shell surface roots are top-level in their own right: they have no
        // parent, and nothing in the application subtree points at them.
        None,
        Some(13),
        Some(13),
        None,
        Some(16),
    ];

    let mut nodes = Vec::with_capacity(elements.len());
    for (i, (role, name, value, desc, bounds, actions, states, nv, minv, maxv, sid, raw)) in
        elements.into_iter().enumerate()
    {
        // Shell surfaces are hosted by the mock's shell process, not by the
        // test app, so they carry their own pid.
        let pid = if i >= FIRST_SHELL_NODE {
            MOCK_SHELL_PID
        } else {
            1234
        };
        let data = ElementData {
            role,
            name: name.map(String::from),
            value: value.map(String::from),
            description: desc.map(String::from),
            bounds,
            actions: actions.iter().map(|s| s.to_string()).collect(),
            states,
            numeric_value: nv,
            min_value: minv,
            max_value: maxv,
            stable_id: sid.map(String::from),
            pid: Some(pid),
            raw: raw.unwrap_or_default(),
            handle: i as u64,
        };
        nodes.push(MockNode {
            data,
            children: children_map[i].clone(),
            parent: parent_map[i],
        });
    }

    Arc::new(MockProvider {
        nodes,
        actions: Mutex::new(Vec::new()),
    })
}

/// Build a [`Subscription`] whose underlying sender has already been dropped.
///
/// Used by binding tests to verify that subscriber loops terminate cleanly on
/// disconnect (rather than hanging or silently swallowing the end-of-stream
/// signal).
pub fn disconnected_subscription() -> Subscription {
    use crate::event_provider::{CancelHandle, EventReceiver};

    let (tx, rx) = std::sync::mpsc::channel::<crate::event::Event>();
    drop(tx); // immediate disconnect
    Subscription::new(EventReceiver::new(rx), CancelHandle::noop())
}