waydriver 0.2.2

Headless GUI testing for Wayland applications via AT-SPI accessibility APIs and PipeWire screen capture
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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
use atspi::proxy::accessible::AccessibleProxy;
use atspi::proxy::action::ActionProxy;
use atspi::proxy::bus::BusProxy;
use atspi::proxy::collection::CollectionProxy;
use atspi::proxy::component::ComponentProxy;
use atspi::proxy::editable_text::EditableTextProxy;
use atspi::proxy::selection::SelectionProxy;
use atspi::proxy::text::TextProxy;
use atspi::{CoordType, ScrollType, State, StateSet};
use std::collections::HashMap;
use std::fmt::Write as _;
use std::future::Future;
use std::pin::Pin;
use std::time::Duration;
use sxd_document::parser;
use sxd_xpath::{Context, Factory, Value};
use zbus::proxy::CacheProperties;

use crate::error::{Error, Result};

/// Per-method reply timeout applied to every proxy on the a11y bus.
///
/// AT-SPI calls target the *target application's* bridge, so when the
/// app crashes after a Locator has resolved a `(bus, path)` reference,
/// any in-flight call against that bridge waits out the connection's
/// reply timeout. zbus' default (~25s) is a long way to hang
/// `kill_session`, and it dominates [`Locator`](crate::Locator)
/// cancellation latency: `poll_with_retry` checks the cancellation
/// token only at iteration boundaries, so a single stuck call adds the
/// full reply timeout to the kill latency before the next poll
/// observes the cancel.
///
/// 2s is short enough that a worst-case `kill_session` waits at most
/// one in-flight call (the rest short-circuit on the token), and long
/// enough that a momentarily-busy live widget rarely trips it. Calls
/// that *do* time out surface as `MethodError(NoReply)`, which
/// `is_stale_error_name` already classifies as retriable — so the
/// behavior matches the existing "widget went away" path.
///
/// Compositor (mutter RemoteDesktop) and PipeWire connections keep the
/// zbus default: their slow paths (`CreateSession`, ScreenCast
/// negotiation) are bursty by design, and shrinking their timeout
/// would risk false `NoReply`s on a healthy session.
const A11Y_METHOD_TIMEOUT: Duration = Duration::from_secs(2);

/// Screen-relative rectangle for an accessibility element, in logical
/// pixels. All four fields are i32 to match AT-SPI's native types (which
/// permit negative coordinates, e.g. when an element is scrolled off the
/// top of the viewport).
///
/// Produced by [`extents_on`], serialized into the snapshot XML as a
/// `bbox="x,y,width,height"` attribute, and re-parsed into
/// [`ElementInfo::bounds`] by [`evaluate_xpath_detailed`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Rect {
    pub x: i32,
    pub y: i32,
    pub width: i32,
    pub height: i32,
}

impl Rect {
    /// Format as `"x,y,width,height"` — the exact shape stored in the
    /// snapshot's `bbox` attribute.
    pub fn to_bbox_string(&self) -> String {
        format!("{},{},{},{}", self.x, self.y, self.width, self.height)
    }

    /// X coordinate of the right edge (exclusive).
    pub fn right(&self) -> i32 {
        self.x.saturating_add(self.width)
    }

    /// Y coordinate of the bottom edge (exclusive).
    pub fn bottom(&self) -> i32 {
        self.y.saturating_add(self.height)
    }

    /// X coordinate of the center (horizontal midpoint).
    pub fn center_x(&self) -> i32 {
        self.x.saturating_add(self.width / 2)
    }

    /// Y coordinate of the center (vertical midpoint).
    pub fn center_y(&self) -> i32 {
        self.y.saturating_add(self.height / 2)
    }

    /// Whether `self` lies entirely within `outer`. Used by
    /// `scroll_into_view` to decide whether an element is already visible
    /// in its scrollable ancestor — if so, scrolling is a no-op.
    pub fn is_inside(&self, outer: &Rect) -> bool {
        self.x >= outer.x
            && self.y >= outer.y
            && self.right() <= outer.right()
            && self.bottom() <= outer.bottom()
    }

    /// Parse a `"x,y,width,height"` string. Returns `None` on any parse
    /// error so callers can treat malformed bounds as "no bounds here"
    /// rather than failing the whole XPath evaluation.
    pub fn parse_bbox(s: &str) -> Option<Self> {
        let mut parts = s.split(',');
        let x = parts.next()?.parse().ok()?;
        let y = parts.next()?.parse().ok()?;
        let width = parts.next()?.parse().ok()?;
        let height = parts.next()?.parse().ok()?;
        if parts.next().is_some() {
            return None;
        }
        Some(Rect {
            x,
            y,
            width,
            height,
        })
    }
}

// ── Proxy builders ──────────────────────────────────────────────────────────

/// Build an [`AccessibleProxy`] for the given bus name and object path.
pub async fn build_accessible<'a>(
    conn: &'a zbus::Connection,
    bus_name: &str,
    path: &str,
) -> zbus::Result<AccessibleProxy<'a>> {
    AccessibleProxy::builder(conn)
        .destination(bus_name.to_owned())?
        .path(path.to_owned())?
        .cache_properties(CacheProperties::No)
        .build()
        .await
}

async fn build_action<'a>(
    conn: &'a zbus::Connection,
    bus_name: &str,
    path: &str,
) -> zbus::Result<ActionProxy<'a>> {
    ActionProxy::builder(conn)
        .destination(bus_name.to_owned())?
        .path(path.to_owned())?
        .cache_properties(CacheProperties::No)
        .build()
        .await
}

async fn build_editable_text<'a>(
    conn: &'a zbus::Connection,
    bus_name: &str,
    path: &str,
) -> zbus::Result<EditableTextProxy<'a>> {
    EditableTextProxy::builder(conn)
        .destination(bus_name.to_owned())?
        .path(path.to_owned())?
        .cache_properties(CacheProperties::No)
        .build()
        .await
}

async fn build_text<'a>(
    conn: &'a zbus::Connection,
    bus_name: &str,
    path: &str,
) -> zbus::Result<TextProxy<'a>> {
    TextProxy::builder(conn)
        .destination(bus_name.to_owned())?
        .path(path.to_owned())?
        .cache_properties(CacheProperties::No)
        .build()
        .await
}

async fn build_component<'a>(
    conn: &'a zbus::Connection,
    bus_name: &str,
    path: &str,
) -> zbus::Result<ComponentProxy<'a>> {
    ComponentProxy::builder(conn)
        .destination(bus_name.to_owned())?
        .path(path.to_owned())?
        .cache_properties(CacheProperties::No)
        .build()
        .await
}

async fn build_selection<'a>(
    conn: &'a zbus::Connection,
    bus_name: &str,
    path: &str,
) -> zbus::Result<SelectionProxy<'a>> {
    SelectionProxy::builder(conn)
        .destination(bus_name.to_owned())?
        .path(path.to_owned())?
        .cache_properties(CacheProperties::No)
        .build()
        .await
}

#[allow(dead_code)]
async fn build_collection<'a>(
    conn: &'a zbus::Connection,
    bus_name: &str,
    path: &str,
) -> zbus::Result<CollectionProxy<'a>> {
    CollectionProxy::builder(conn)
        .destination(bus_name.to_owned())?
        .path(path.to_owned())?
        .cache_properties(CacheProperties::No)
        .build()
        .await
}

// ── Connection ──────────────────────────────────────────────────────────────

/// Connect to the AT-SPI accessibility bus for a given D-Bus session.
///
/// Returns the raw [`zbus::Connection`] (not [`atspi::connection::AccessibilityConnection`])
/// so we can configure [`A11Y_METHOD_TIMEOUT`] on it via the connection
/// builder — the upstream wrapper offers no public hook for that, and
/// we don't use its registry/event-stream sugar anywhere.
pub async fn connect_a11y(dbus_address: &str) -> Result<zbus::Connection> {
    let session_addr: zbus::address::Address = dbus_address
        .try_into()
        .map_err(|e: zbus::Error| Error::atspi_with("invalid dbus address", e))?;
    let session_conn = zbus::connection::Builder::address(session_addr)?
        .build()
        .await?;

    let bus_proxy = BusProxy::new(&session_conn).await?;
    let a11y_addr_str = bus_proxy.get_address().await?;

    let a11y_addr: zbus::address::Address = a11y_addr_str
        .as_str()
        .try_into()
        .map_err(|e: zbus::Error| Error::atspi_with("invalid a11y bus address", e))?;
    let a11y_conn = zbus::connection::Builder::address(a11y_addr)?
        .method_timeout(A11Y_METHOD_TIMEOUT)
        .build()
        .await
        .map_err(|e| Error::atspi_with("failed to connect to a11y bus", e))?;

    Ok(a11y_conn)
}

/// Get the root accessible node from the AT-SPI registry.
pub async fn get_registry_root(conn: &zbus::Connection) -> Result<AccessibleProxy<'_>> {
    build_accessible(
        conn,
        "org.a11y.atspi.Registry",
        "/org/a11y/atspi/accessible/root",
    )
    .await
    .map_err(|e| Error::atspi_with("failed to get registry root", e))
}

// ── Role normalization ──────────────────────────────────────────────────────

/// Convert a raw AT-SPI role name like `"push button"` or `"menu item"` into
/// a PascalCase XML element name like `"PushButton"` or `"MenuItem"`.
///
/// If the role produces a name that isn't a valid XML element name (empty,
/// starts with a digit, or contains characters outside `[A-Za-z0-9_-]`), we
/// return `None` and the caller falls back to emitting a `<Node role="...">`.
fn role_to_element_name(role: &str) -> Option<String> {
    let mut out = String::with_capacity(role.len());
    for word in role.split_whitespace() {
        let mut chars = word.chars();
        if let Some(first) = chars.next() {
            out.extend(first.to_uppercase());
            for c in chars {
                out.extend(c.to_lowercase());
            }
        }
    }
    if out.is_empty() {
        return None;
    }
    let mut it = out.chars();
    let first = it
        .next()
        .expect("invariant: out.is_empty() returned false above");
    if !(first.is_ascii_alphabetic() || first == '_') {
        return None;
    }
    for c in it {
        if !(c.is_ascii_alphanumeric() || c == '_' || c == '-') {
            return None;
        }
    }
    Some(out)
}

/// Sanitize an AT-SPI attribute key into a valid XML attribute name.
/// Returns `None` if the key would produce an empty or reserved name.
fn sanitize_attr_key(key: &str) -> Option<String> {
    let mut out = String::with_capacity(key.len());
    for c in key.chars() {
        if c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' {
            out.push(c);
        } else {
            out.push('_');
        }
    }
    if out.is_empty() {
        return None;
    }
    let first = out
        .chars()
        .next()
        .expect("invariant: out.is_empty() returned false above");
    if !(first.is_ascii_alphabetic() || first == '_') {
        out.insert(0, '_');
    }
    // Avoid conflicts with attributes the snapshotter emits itself.
    if matches!(out.as_str(), "name" | "role" | "_ref") {
        out.insert(0, '_');
    }
    Some(out)
}

fn xml_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '&' => out.push_str("&amp;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&apos;"),
            // XML 1.0 forbids most control chars; keep TAB/LF/CR, drop the rest.
            '\t' | '\n' | '\r' => out.push(c),
            c if (c as u32) < 0x20 => {}
            c => out.push(c),
        }
    }
    out
}

/// States emitted as boolean XML attributes on each node. Absent = false.
const EMITTED_STATES: &[(State, &str)] = &[
    (State::Showing, "showing"),
    (State::Visible, "visible"),
    (State::Enabled, "enabled"),
    (State::Sensitive, "sensitive"),
    (State::Focused, "focused"),
    (State::Focusable, "focusable"),
    (State::Selected, "selected"),
    (State::Selectable, "selectable"),
    (State::Checked, "checked"),
    (State::Checkable, "checkable"),
    (State::Active, "active"),
    (State::Editable, "editable"),
    (State::Expandable, "expandable"),
    (State::Expanded, "expanded"),
    (State::Collapsed, "collapsed"),
    (State::Pressed, "pressed"),
    (State::Modal, "modal"),
];

// ── Snapshot: live AT-SPI tree → XML document ───────────────────────────────

/// Walk the AT-SPI subtree rooted at `(app_bus_name, app_path)` and emit an
/// XML string representation suitable for XPath evaluation.
///
/// Every element carries a `_ref="<bus>|<path>"` attribute; the XPath
/// evaluator reads this after matching to recover the AT-SPI identity of
/// each matched node.
pub async fn snapshot_tree(
    conn: &zbus::Connection,
    app_bus_name: &str,
    app_path: &str,
) -> Result<String> {
    let app_root = build_accessible(conn, app_bus_name, app_path)
        .await
        .map_err(|e| Error::atspi_with("failed to get app root", e))?;

    let mut output = String::new();
    output.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    snapshot_node(conn, &app_root, app_bus_name, app_path, 0, &mut output).await;
    Ok(output)
}

type SnapshotFuture<'a> = Pin<Box<dyn Future<Output = ()> + Send + 'a>>;

/// Snapshot policy: per-node D-Bus introspection calls
/// (`name`, `get_role_name`, `get_state`, `get_attributes`) that
/// return an error are mapped to their default value so the
/// snapshot of the surrounding tree still succeeds — the invariant
/// is "one poisoned node doesn't abort the snapshot."
///
/// The substituted default is indistinguishable on the wire from a
/// genuinely empty value (a node really *can* have name=""), so
/// this helper logs the swallowed error at `warn` to make flakiness
/// recoverable post-hoc via the trace stream. Modeling the
/// fallibility on the snapshot itself (e.g. a `partial="true"`
/// attribute) would make it observable to consumers but adds churn
/// to every locator that reads metadata; this hybrid keeps the
/// snapshot shape stable while putting the flakiness signal where
/// it's most actionable — the operator's logs, not the test's
/// assertion path.
fn snapshot_default_on_err<T, E>(bus: &str, path: &str, op: &'static str, err: E) -> T
where
    T: Default,
    E: std::fmt::Display,
{
    tracing::warn!(
        %bus, %path, op, error = %err,
        "snapshot: per-node introspection call failed; substituting default"
    );
    T::default()
}

fn snapshot_node<'a>(
    conn: &'a zbus::Connection,
    proxy: &'a AccessibleProxy<'a>,
    bus_name: &'a str,
    path: &'a str,
    depth: usize,
    output: &'a mut String,
) -> SnapshotFuture<'a> {
    Box::pin(async move {
        // role has its own non-Default fallback ("unknown") because
        // an empty role string would change the meaning of the
        // emitted XML element tag (`role_to_element_name` would map
        // it to `<Node>` for a different reason than the
        // genuinely-unmapped role case).
        let raw_role = proxy.get_role_name().await.unwrap_or_else(|e| {
            tracing::warn!(
                %bus_name, %path, error = %e,
                "snapshot: get_role_name failed; substituting \"unknown\""
            );
            "unknown".into()
        });
        let name: String = proxy
            .name()
            .await
            .unwrap_or_else(|e| snapshot_default_on_err(bus_name, path, "name", e));
        let states: StateSet = proxy
            .get_state()
            .await
            .unwrap_or_else(|e| snapshot_default_on_err(bus_name, path, "get_state", e));
        let attrs: HashMap<String, String> = proxy
            .get_attributes()
            .await
            .unwrap_or_else(|e| snapshot_default_on_err(bus_name, path, "get_attributes", e));
        // Fetch window-relative bounds via the Component interface. Any
        // error — element doesn't implement Component, toolkit refused,
        // D-Bus NoReply — maps to "no bounds available" rather than
        // aborting the snapshot. This preserves the invariant that a
        // snapshot always succeeds even when individual nodes misbehave.
        //
        // `Window` over `Screen`: under headless mutter the toolkit
        // routinely reports `(0, 0)` for screen-relative positions (no
        // actual screen to anchor to), which defeats the bounds-based
        // overflow check in `Locator::scroll_into_view` and makes every
        // widget look like it's at the origin. Window-relative coords
        // are stable across headless/headed and give enough signal for
        // layout math.
        let bounds = extents_on(conn, bus_name, path, CoordType::Window)
            .await
            .ok()
            .flatten();

        let element_name = role_to_element_name(&raw_role).unwrap_or_else(|| "Node".to_string());

        let indent = "  ".repeat(depth);
        let _ = write!(output, "{indent}<{element_name}");

        // The raw AT-SPI role is always emitted as an attribute so metadata
        // reads (Locator::role, query responses) can read directly from the
        // snapshot without a second round-trip. The element tag doubles as a
        // convenient XPath node-test but loses fidelity for weird roles that
        // fall back to <Node>; the `role` attribute is the source of truth.
        let _ = write!(output, " role=\"{}\"", xml_escape(&raw_role));
        if !name.is_empty() {
            let _ = write!(output, " name=\"{}\"", xml_escape(&name));
        }
        for (state, attr) in EMITTED_STATES {
            if states.contains(*state) {
                let _ = write!(output, " {attr}=\"true\"");
            }
        }
        if let Some(bb) = bounds {
            let _ = write!(output, " bbox=\"{}\"", bb.to_bbox_string());
        }
        for (key, value) in &attrs {
            if let Some(safe) = sanitize_attr_key(key) {
                let _ = write!(output, " {}=\"{}\"", safe, xml_escape(value));
            }
        }
        let _ = write!(
            output,
            " _ref=\"{}|{}\"",
            xml_escape(bus_name),
            xml_escape(path)
        );

        if depth > 20 {
            output.push_str("/>\n");
            return;
        }

        let children = match proxy.get_children().await {
            Ok(c) if !c.is_empty() => c,
            _ => {
                output.push_str("/>\n");
                return;
            }
        };

        output.push_str(">\n");
        for child_ref in &children {
            let Some(child_bus) = child_ref.name_as_str() else {
                continue;
            };
            let child_path = child_ref.path_as_str();
            let child = match build_accessible(conn, child_bus, child_path).await {
                Ok(c) => c,
                Err(_) => continue,
            };
            snapshot_node(conn, &child, child_bus, child_path, depth + 1, output).await;
        }
        let _ = writeln!(output, "{indent}</{element_name}>");
    })
}

// ── XPath evaluation ────────────────────────────────────────────────────────

/// Snapshot metadata for an element matched by an XPath query.
///
/// Produced by [`evaluate_xpath_detailed`] — reflects the element's state at
/// the time the snapshot was taken, not live.
#[derive(Debug, Clone)]
pub struct ElementInfo {
    /// AT-SPI `(bus_name, object_path)` identity.
    pub ref_: (String, String),
    /// PascalCase role element name as emitted in the snapshot (e.g.
    /// `"PushButton"`). If the raw role wasn't a valid XML name, this is
    /// `"Node"` and the raw role is stored in `role_raw`.
    pub role: String,
    /// Raw AT-SPI role name when the element fell back to `<Node role="…">`.
    pub role_raw: Option<String>,
    /// Accessible name, if set.
    pub name: Option<String>,
    /// Toolkit attributes (excluding the ones waydriver emits itself).
    pub attributes: HashMap<String, String>,
    /// Lowercase names of the AT-SPI states currently set on the element.
    pub states: Vec<String>,
    /// Screen-relative bounds (x, y, width, height) in logical pixels,
    /// as read from `Component::get_extents` at snapshot time. `None` when
    /// the element doesn't implement Component or isn't laid out yet.
    pub bounds: Option<Rect>,
}

const SNAPSHOT_BUILTINS: &[&str] = &["_ref", "name", "role", "bbox"];

fn is_state_attr(key: &str) -> bool {
    EMITTED_STATES.iter().any(|(_, attr)| *attr == key)
}

/// Evaluate an XPath expression against a snapshot produced by
/// [`snapshot_tree`] and return the AT-SPI `(bus, path)` tuples of the
/// matching elements, in document order.
pub fn evaluate_xpath(xml: &str, xpath: &str) -> Result<Vec<(String, String)>> {
    let package =
        parser::parse(xml).map_err(|e| Error::atspi_with("failed to parse snapshot XML", e))?;
    let doc = package.as_document();

    let factory = Factory::new();
    let compiled = factory
        .build(xpath)
        .map_err(|e| Error::InvalidSelector {
            xpath: xpath.to_string(),
            reason: e.to_string(),
        })?
        .ok_or_else(|| Error::InvalidSelector {
            xpath: xpath.to_string(),
            reason: "empty xpath".to_string(),
        })?;

    let ctx = Context::new();
    let value = compiled
        .evaluate(&ctx, doc.root())
        .map_err(|e| Error::InvalidSelector {
            xpath: xpath.to_string(),
            reason: e.to_string(),
        })?;

    let nodeset = match value {
        Value::Nodeset(ns) => ns,
        _ => {
            return Err(Error::InvalidSelector {
                xpath: xpath.to_string(),
                reason: "xpath did not return a node-set".to_string(),
            });
        }
    };

    let mut out = Vec::new();
    for node in nodeset.document_order() {
        let Some(elem) = node.element() else { continue };
        let Some(attr) = elem.attribute_value("_ref") else {
            continue;
        };
        if let Some((bus, path)) = attr.split_once('|') {
            out.push((bus.to_string(), path.to_string()));
        }
    }
    Ok(out)
}

/// Evaluate an XPath expression against a snapshot and return full metadata
/// for each matched element, in document order.
pub fn evaluate_xpath_detailed(xml: &str, xpath: &str) -> Result<Vec<ElementInfo>> {
    let package =
        parser::parse(xml).map_err(|e| Error::atspi_with("failed to parse snapshot XML", e))?;
    let doc = package.as_document();

    let factory = Factory::new();
    let compiled = factory
        .build(xpath)
        .map_err(|e| Error::InvalidSelector {
            xpath: xpath.to_string(),
            reason: e.to_string(),
        })?
        .ok_or_else(|| Error::InvalidSelector {
            xpath: xpath.to_string(),
            reason: "empty xpath".to_string(),
        })?;

    let ctx = Context::new();
    let value = compiled
        .evaluate(&ctx, doc.root())
        .map_err(|e| Error::InvalidSelector {
            xpath: xpath.to_string(),
            reason: e.to_string(),
        })?;

    let nodeset = match value {
        Value::Nodeset(ns) => ns,
        _ => {
            return Err(Error::InvalidSelector {
                xpath: xpath.to_string(),
                reason: "xpath did not return a node-set".to_string(),
            });
        }
    };

    let mut out = Vec::new();
    for node in nodeset.document_order() {
        let Some(elem) = node.element() else { continue };
        let Some(ref_attr) = elem.attribute_value("_ref") else {
            continue;
        };
        let Some((bus, path)) = ref_attr.split_once('|') else {
            continue;
        };

        let role = elem.name().local_part().to_string();
        let role_raw = elem.attribute_value("role").map(|s| s.to_string());
        let name = elem.attribute_value("name").map(|s| s.to_string());
        let bounds = elem.attribute_value("bbox").and_then(Rect::parse_bbox);

        let mut attributes = HashMap::new();
        let mut states = Vec::new();
        for attr in elem.attributes() {
            let key = attr.name().local_part();
            if SNAPSHOT_BUILTINS.contains(&key) {
                continue;
            }
            if is_state_attr(key) {
                if attr.value() == "true" {
                    states.push(key.to_string());
                }
            } else {
                attributes.insert(key.to_string(), attr.value().to_string());
            }
        }

        out.push(ElementInfo {
            ref_: (bus.to_string(), path.to_string()),
            role,
            role_raw,
            name,
            attributes,
            states,
            bounds,
        });
    }
    Ok(out)
}

// ── Actions ─────────────────────────────────────────────────────────────────

fn map_action_err(xpath: &str, bus: &str, path: &str, err: zbus::Error) -> Error {
    if let zbus::Error::MethodError(name, _, _) = &err {
        if is_stale_error_name(name.as_str()) {
            // Log every classify-as-stale so post-hoc analysis can
            // see when the heuristic fires and on which error name.
            // If a future toolkit (Qt6, KWin's a11y bridge) starts
            // surfacing a name that *should* count as stale but
            // doesn't yet, the log will show the gap; conversely a
            // name that gets classified as stale but shouldn't will
            // show up here too.
            tracing::debug!(
                %xpath, %bus, %path, error_name = %name.as_str(),
                "classified D-Bus error as ElementStale"
            );
            return Error::ElementStale {
                xpath: xpath.to_string(),
                bus: bus.to_string(),
                path: path.to_string(),
            };
        }
    }
    Error::atspi_with("dbus", err)
}

/// Classify a D-Bus error-name string as indicating the element is gone.
///
/// Returns true for error names that surface when the target widget
/// was destroyed between resolution and action:
/// - `org.freedesktop.DBus.Error.UnknownObject` — service still
///   alive, object path no longer registered.
/// - `org.freedesktop.DBus.Error.ServiceUnknown` — whole bus name is
///   gone (the app exited).
/// - `…NoReply` — the call timed out waiting for a response, which
///   for AT-SPI means the peer queue has drained because the widget
///   is being torn down.
/// - `…Disconnected` — toolkit-emitted variant (notably surfaced by
///   `org.a11y.atspi.Error.Disconnected` and analogous bridges in
///   Qt's a11y stack) when the underlying object is no longer
///   reachable. Substring-match keeps the classifier
///   toolkit-agnostic; if a new bridge introduces yet another name
///   it lands as a non-stale error and the tracing log in
///   `map_action_err` makes the gap visible without requiring code
///   changes to discover it.
fn is_stale_error_name(name: &str) -> bool {
    name.contains("UnknownObject")
        || name.contains("ServiceUnknown")
        || name.contains("NoReply")
        || name.contains("Disconnected")
}

/// Invoke action index 0 on the element identified by `(bus, path)`.
///
/// NOTE: AT-SPI actions update GTK4's model but don't trigger compositor
/// redraws. Callers driving a test session must follow up with a
/// RemoteDesktop event to force a repaint.
pub async fn do_action_on(
    conn: &zbus::Connection,
    xpath: &str,
    bus: &str,
    path: &str,
) -> Result<()> {
    let action = build_action(conn, bus, path)
        .await
        .map_err(|e| map_action_err(xpath, bus, path, e))?;

    let n_actions: i32 = action.nactions().await.unwrap_or(0);
    tracing::debug!(%xpath, %bus, %path, n_actions, "do_action(0)");

    let success = action
        .do_action(0)
        .await
        .map_err(|e| map_action_err(xpath, bus, path, e))?;

    if !success {
        return Err(Error::atspi(format!(
            "do_action(0) returned false on {bus}{path} — element may not support activation"
        )));
    }
    Ok(())
}

/// Read screen/window-relative bounds for the element identified by
/// `(bus, path)` via the AT-SPI Component interface.
///
/// Returns `Ok(None)` when the element doesn't implement Component, when
/// Component exists but `get_extents` reports a zero-area rect (used by
/// some toolkits to mean "not laid out yet"), or when the D-Bus call
/// fails in a way that shouldn't abort snapshot capture. Hard errors
/// (connection dead) propagate as `Err`.
pub async fn extents_on(
    conn: &zbus::Connection,
    bus: &str,
    path: &str,
    coord_type: CoordType,
) -> zbus::Result<Option<Rect>> {
    let component = build_component(conn, bus, path).await?;
    match component.get_extents(coord_type).await {
        Ok((x, y, width, height)) => {
            if width <= 0 && height <= 0 {
                // GTK returns (0,0,0,0) for widgets that exist in the a11y
                // tree but haven't been realized/mapped yet. Surface that
                // as "no bounds" rather than a nonsense rect.
                Ok(None)
            } else {
                Ok(Some(Rect {
                    x,
                    y,
                    width,
                    height,
                }))
            }
        }
        Err(zbus::Error::MethodError(_, _, _)) => Ok(None),
        Err(e) => Err(e),
    }
}

/// Ask the toolkit to scroll the element identified by `(bus, path)` into
/// view via the AT-SPI `Component::scroll_to` method.
///
/// Returns `Ok(true)` when the widget honored the request, `Ok(false)`
/// when it declined (returned false — usually meaning the widget's
/// toolkit hasn't implemented scroll_to for this role), and
/// `Ok(false)` also when the D-Bus call fails with a MethodError
/// (typically "interface not supported"). Only propagates `Err` for
/// transport-level failures that signal a broken session.
pub async fn scroll_to_on(
    conn: &zbus::Connection,
    bus: &str,
    path: &str,
    scroll_type: ScrollType,
) -> zbus::Result<bool> {
    let component = build_component(conn, bus, path).await?;
    match component.scroll_to(scroll_type).await {
        Ok(ok) => Ok(ok),
        Err(zbus::Error::MethodError(_, _, _)) => Ok(false),
        Err(e) => Err(e),
    }
}

/// Ask the toolkit to scroll the element identified by `(bus, path)` so
/// its position lands at `(x, y)` in the given coordinate frame — the
/// AT-SPI `Component::scroll_to_point` method.
///
/// Same error-mapping contract as [`scroll_to_on`]: any MethodError
/// (the widget doesn't implement it, or rejected the request) becomes
/// `Ok(false)`.
pub async fn scroll_to_point_on(
    conn: &zbus::Connection,
    bus: &str,
    path: &str,
    coord_type: CoordType,
    x: i32,
    y: i32,
) -> zbus::Result<bool> {
    let component = build_component(conn, bus, path).await?;
    match component.scroll_to_point(coord_type, x, y).await {
        Ok(ok) => Ok(ok),
        Err(zbus::Error::MethodError(_, _, _)) => Ok(false),
        Err(e) => Err(e),
    }
}

/// Outcome of an AT-SPI focus request that wants to distinguish "the
/// widget's a11y bridge doesn't expose this" from "the bridge said no
/// to this specific request".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FocusOutcome {
    /// `Component::grab_focus` returned true — the widget reports it
    /// took focus.
    Granted,
    /// `Component::grab_focus` returned false — widget exists, exposes
    /// Component, but rejected the request (typically because it
    /// isn't focusable in its current state).
    Rejected,
    /// The widget's a11y bridge doesn't implement the Component
    /// interface or the `grab_focus` method on it. Common on GTK4
    /// `Entry` / `Text` widgets, where focus has to be driven through
    /// the input layer (Tab navigation, pointer click) instead of
    /// AT-SPI. The keystrokes that follow will land on whatever
    /// currently holds keyboard focus.
    NotSupported,
}

/// Give keyboard focus to the element identified by `(bus, path)` via the
/// AT-SPI Component interface.
///
/// Returns `Err(Error::Atspi(...))` when the element doesn't implement
/// Component or when `grab_focus` returned false (the toolkit rejected the
/// focus request — typically because the element isn't focusable).
pub async fn grab_focus_on(
    conn: &zbus::Connection,
    xpath: &str,
    bus: &str,
    path: &str,
) -> Result<()> {
    let component = build_component(conn, bus, path)
        .await
        .map_err(|e| map_action_err(xpath, bus, path, e))?;
    let ok = component
        .grab_focus()
        .await
        .map_err(|e| map_action_err(xpath, bus, path, e))?;
    if !ok {
        return Err(Error::atspi(format!(
            "grab_focus returned false on {bus}{path} — element not focusable"
        )));
    }
    Ok(())
}

/// Like [`grab_focus_on`] but maps `MethodError` (the Component
/// interface or `grab_focus` method isn't implemented for this widget)
/// to [`FocusOutcome::NotSupported`] instead of an error.
///
/// Used by `Locator::fill_with_opts` so a missing-Component bridge
/// doesn't fail the whole fill — that's the documented GTK4 quirk
/// behind `Entry` and `Text`. Stale-element D-Bus errors still
/// propagate as [`Error::ElementStale`] via [`map_action_err`];
/// transport-level failures still propagate as [`Error::Atspi`].
pub async fn try_grab_focus_on(
    conn: &zbus::Connection,
    xpath: &str,
    bus: &str,
    path: &str,
) -> Result<FocusOutcome> {
    // Building the Component proxy itself doesn't issue a method
    // call — it only verifies the address shape — so a "this widget
    // doesn't support Component" error surfaces on `grab_focus()`.
    let component = build_component(conn, bus, path)
        .await
        .map_err(|e| map_action_err(xpath, bus, path, e))?;
    match component.grab_focus().await {
        Ok(true) => Ok(FocusOutcome::Granted),
        Ok(false) => Ok(FocusOutcome::Rejected),
        Err(zbus::Error::MethodError(name, _, _)) => {
            // Stale-element names (UnknownObject / ServiceUnknown /
            // NoReply / Disconnected) still surface as ElementStale —
            // those mean the target is gone, not that focus isn't
            // supported. Everything else (including
            // `org.freedesktop.DBus.Error.NotSupported` and
            // `UnknownMethod`) maps to NotSupported because the
            // widget exists but doesn't expose this AT-SPI method.
            if is_stale_error_name(name.as_str()) {
                tracing::debug!(
                    %xpath, %bus, %path, error_name = %name.as_str(),
                    "classified D-Bus error as ElementStale during try_grab_focus"
                );
                Err(Error::ElementStale {
                    xpath: xpath.to_string(),
                    bus: bus.to_string(),
                    path: path.to_string(),
                })
            } else {
                Ok(FocusOutcome::NotSupported)
            }
        }
        Err(e) => Err(Error::atspi_with("dbus", e)),
    }
}

/// Replace the editable-text contents of the element identified by `(bus, path)`.
pub async fn set_text_on(
    conn: &zbus::Connection,
    xpath: &str,
    bus: &str,
    path: &str,
    text: &str,
) -> Result<()> {
    let et = build_editable_text(conn, bus, path)
        .await
        .map_err(|e| map_action_err(xpath, bus, path, e))?;
    let ok = et
        .set_text_contents(text)
        .await
        .map_err(|e| map_action_err(xpath, bus, path, e))?;
    if !ok {
        return Err(Error::atspi(format!(
            "set_text_contents returned false on {bus}{path} — element rejected input"
        )));
    }
    Ok(())
}

/// Select the child at `index` on a container that implements the AT-SPI
/// Selection interface — the core primitive behind `Locator::select_option`.
///
/// Maps a `select_child` call that returns `Ok(false)` into an
/// `Error::Atspi` with a diagnostic suggesting the most likely causes
/// (no Selection interface on this element, or the widget rejected the
/// request — e.g. the index is out of range for the model). MethodError
/// from `(bus, path)` going stale between resolution and the call
/// produces `Error::ElementStale` via [`map_action_err`].
pub async fn select_child_on(
    conn: &zbus::Connection,
    xpath: &str,
    bus: &str,
    path: &str,
    index: i32,
) -> Result<()> {
    let sel = build_selection(conn, bus, path)
        .await
        .map_err(|e| map_action_err(xpath, bus, path, e))?;
    let ok = sel
        .select_child(index)
        .await
        .map_err(|e| map_action_err(xpath, bus, path, e))?;
    if !ok {
        return Err(Error::atspi(format!(
            "select_child({index}) returned false on {bus}{path} — element \
             may not implement the Selection interface or the index is out \
             of range"
        )));
    }
    Ok(())
}

/// Read the full text contents of the element identified by `(bus, path)`
/// via the Text interface.
pub async fn read_text_on(
    conn: &zbus::Connection,
    xpath: &str,
    bus: &str,
    path: &str,
) -> Result<String> {
    let t = build_text(conn, bus, path)
        .await
        .map_err(|e| map_action_err(xpath, bus, path, e))?;
    let n = t
        .character_count()
        .await
        .map_err(|e| map_action_err(xpath, bus, path, e))?;
    let s = t
        .get_text(0, n)
        .await
        .map_err(|e| map_action_err(xpath, bus, path, e))?;
    Ok(s)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn role_to_element_name_basic() {
        assert_eq!(
            role_to_element_name("push button").as_deref(),
            Some("PushButton")
        );
        assert_eq!(
            role_to_element_name("menu item").as_deref(),
            Some("MenuItem")
        );
        assert_eq!(role_to_element_name("window").as_deref(), Some("Window"));
        assert_eq!(role_to_element_name("panel").as_deref(), Some("Panel"));
        assert_eq!(
            role_to_element_name("application").as_deref(),
            Some("Application")
        );
    }

    #[test]
    fn role_to_element_name_weird() {
        // Empty → None
        assert_eq!(role_to_element_name(""), None);
        // Role with only whitespace → None
        assert_eq!(role_to_element_name("   "), None);
    }

    #[test]
    fn sanitize_attr_key_clean() {
        assert_eq!(sanitize_attr_key("id").as_deref(), Some("id"));
        assert_eq!(sanitize_attr_key("xml-roles").as_deref(), Some("xml-roles"));
    }

    #[test]
    fn sanitize_attr_key_collides_with_reserved() {
        assert_eq!(sanitize_attr_key("name").as_deref(), Some("_name"));
        assert_eq!(sanitize_attr_key("role").as_deref(), Some("_role"));
        assert_eq!(sanitize_attr_key("_ref").as_deref(), Some("__ref"));
    }

    #[test]
    fn sanitize_attr_key_replaces_bad_chars() {
        assert_eq!(sanitize_attr_key("foo:bar").as_deref(), Some("foo_bar"));
        assert_eq!(sanitize_attr_key("a/b c").as_deref(), Some("a_b_c"));
    }

    #[test]
    fn xml_escape_basic() {
        assert_eq!(xml_escape("<a&b>\"'"), "&lt;a&amp;b&gt;&quot;&apos;");
        assert_eq!(xml_escape("hello"), "hello");
    }

    #[test]
    fn evaluate_xpath_finds_by_name() {
        let xml = r#"<?xml version="1.0"?>
<Application name="calc" _ref="bus|/root">
  <Window name="Calculator" _ref="bus|/w1">
    <PushButton name="7" _ref="bus|/b7"/>
    <PushButton name="+" _ref="bus|/bplus"/>
  </Window>
</Application>"#;
        let hits = evaluate_xpath(xml, "//PushButton[@name='7']").unwrap();
        assert_eq!(hits, vec![("bus".to_string(), "/b7".to_string())]);
    }

    #[test]
    fn evaluate_xpath_multiple_matches() {
        let xml = r#"<?xml version="1.0"?>
<Application _ref="bus|/root">
  <PushButton name="OK" _ref="bus|/b1"/>
  <Dialog _ref="bus|/d1">
    <PushButton name="OK" _ref="bus|/b2"/>
  </Dialog>
</Application>"#;
        let hits = evaluate_xpath(xml, "//PushButton[@name='OK']").unwrap();
        assert_eq!(hits.len(), 2);
        assert_eq!(hits[0].1, "/b1");
        assert_eq!(hits[1].1, "/b2");
    }

    #[test]
    fn evaluate_xpath_scoped_descendant() {
        let xml = r#"<?xml version="1.0"?>
<Application _ref="bus|/root">
  <PushButton name="OK" _ref="bus|/b1"/>
  <Dialog name="Confirm" _ref="bus|/d1">
    <PushButton name="OK" _ref="bus|/b2"/>
  </Dialog>
</Application>"#;
        let hits = evaluate_xpath(xml, "//Dialog[@name='Confirm']//PushButton").unwrap();
        assert_eq!(hits, vec![("bus".to_string(), "/b2".to_string())]);
    }

    #[test]
    fn evaluate_xpath_invalid_syntax() {
        let xml = r#"<?xml version="1.0"?><Application _ref="bus|/root"/>"#;
        let err = evaluate_xpath(xml, "//[").unwrap_err();
        assert!(matches!(err, Error::InvalidSelector { .. }));
    }

    // ── evaluate_xpath_detailed ────────────────────────────────────────────

    #[test]
    fn evaluate_xpath_detailed_extracts_full_metadata() {
        let xml = r#"<?xml version="1.0"?>
<Application _ref="bus|/root">
  <PushButton name="Submit" showing="true" enabled="true" id="btn-submit" _ref="bus|/b1"/>
</Application>"#;
        let hits = evaluate_xpath_detailed(xml, "//PushButton").unwrap();
        assert_eq!(hits.len(), 1);
        let h = &hits[0];
        assert_eq!(h.ref_, ("bus".to_string(), "/b1".to_string()));
        assert_eq!(h.role, "PushButton");
        assert_eq!(h.role_raw, None);
        assert_eq!(h.name.as_deref(), Some("Submit"));
        assert_eq!(
            h.attributes.get("id").map(String::as_str),
            Some("btn-submit")
        );
        assert!(h.states.iter().any(|s| s == "showing"));
        assert!(h.states.iter().any(|s| s == "enabled"));
    }

    #[test]
    fn evaluate_xpath_detailed_separates_states_from_attrs() {
        // `showing` and `enabled` are emitted state attrs; `id` is a toolkit attr;
        // `xml-roles` is a toolkit attr. Ensure they land in the right bucket.
        let xml = r#"<?xml version="1.0"?>
<Application _ref="bus|/root">
  <PushButton name="X" showing="true" enabled="true" id="x" xml-roles="button" _ref="bus|/b"/>
</Application>"#;
        let hits = evaluate_xpath_detailed(xml, "//PushButton").unwrap();
        let h = &hits[0];
        // Exactly the two state attrs should appear in `states`; no toolkit attrs.
        assert!(h.states.iter().any(|s| s == "showing"));
        assert!(h.states.iter().any(|s| s == "enabled"));
        assert!(!h.states.iter().any(|s| s == "id"));
        assert!(!h.states.iter().any(|s| s == "xml-roles"));
        // Exactly the two toolkit attrs should be in `attributes`; no state names.
        assert_eq!(h.attributes.get("id").map(String::as_str), Some("x"));
        assert_eq!(
            h.attributes.get("xml-roles").map(String::as_str),
            Some("button")
        );
        assert!(!h.attributes.contains_key("showing"));
        assert!(!h.attributes.contains_key("enabled"));
    }

    #[test]
    fn evaluate_xpath_detailed_state_false_not_emitted() {
        // The snapshotter only emits state attrs when they're set. A serialized
        // `showing="false"` (shouldn't happen, but test the read side anyway)
        // must NOT land in `states` because the parser only accepts "true".
        let xml = r#"<?xml version="1.0"?>
<Application _ref="bus|/root">
  <PushButton showing="false" _ref="bus|/b"/>
</Application>"#;
        let hits = evaluate_xpath_detailed(xml, "//PushButton").unwrap();
        assert!(hits[0].states.is_empty());
    }

    #[test]
    fn evaluate_xpath_detailed_node_fallback_preserves_raw_role() {
        // When the snapshotter couldn't turn a role into a valid XML name,
        // it emits `<Node role="...">`. The detailed extractor should surface
        // both `role="Node"` and `role_raw=Some("original")`.
        let xml = r#"<?xml version="1.0"?>
<Application _ref="bus|/root">
  <Node role="0weird" name="odd" _ref="bus|/x"/>
</Application>"#;
        let hits = evaluate_xpath_detailed(xml, "//Node").unwrap();
        assert_eq!(hits[0].role, "Node");
        assert_eq!(hits[0].role_raw.as_deref(), Some("0weird"));
        assert_eq!(hits[0].name.as_deref(), Some("odd"));
    }

    #[test]
    fn evaluate_xpath_detailed_absent_name_is_none() {
        let xml = r#"<?xml version="1.0"?>
<Application _ref="bus|/root">
  <Panel _ref="bus|/p"/>
</Application>"#;
        let hits = evaluate_xpath_detailed(xml, "//Panel").unwrap();
        assert_eq!(hits[0].name, None);
    }

    #[test]
    fn evaluate_xpath_detailed_returns_document_order() {
        let xml = r#"<?xml version="1.0"?>
<Application _ref="bus|/root">
  <PushButton name="A" _ref="bus|/a"/>
  <Dialog _ref="bus|/d">
    <PushButton name="B" _ref="bus|/b"/>
  </Dialog>
  <PushButton name="C" _ref="bus|/c"/>
</Application>"#;
        let hits = evaluate_xpath_detailed(xml, "//PushButton").unwrap();
        let names: Vec<&str> = hits.iter().filter_map(|h| h.name.as_deref()).collect();
        assert_eq!(names, vec!["A", "B", "C"]);
    }

    #[test]
    fn evaluate_xpath_detailed_invalid_selector() {
        let xml = r#"<?xml version="1.0"?><Application _ref="bus|/root"/>"#;
        let err = evaluate_xpath_detailed(xml, "//[").unwrap_err();
        assert!(matches!(err, Error::InvalidSelector { .. }));
    }

    // ── Staleness classifier ───────────────────────────────────────────────

    #[test]
    fn is_stale_error_name_recognizes_atspi_error_names() {
        // The three D-Bus error names that surface when a widget is gone.
        assert!(is_stale_error_name(
            "org.freedesktop.DBus.Error.UnknownObject"
        ));
        assert!(is_stale_error_name(
            "org.freedesktop.DBus.Error.ServiceUnknown"
        ));
        assert!(is_stale_error_name("org.freedesktop.DBus.Error.NoReply"));
    }

    #[test]
    fn is_stale_error_name_rejects_unrelated_errors() {
        // Real-world non-stale error names shouldn't produce false positives.
        assert!(!is_stale_error_name(
            "org.freedesktop.DBus.Error.InvalidArgs"
        ));
        assert!(!is_stale_error_name(
            "org.freedesktop.DBus.Error.AccessDenied"
        ));
        assert!(!is_stale_error_name("org.a11y.atspi.Error.SomethingElse"));
        assert!(!is_stale_error_name(""));
    }

    // ── Rect / bbox ────────────────────────────────────────────────────────

    #[test]
    fn rect_bbox_roundtrip() {
        let r = Rect {
            x: 10,
            y: 20,
            width: 100,
            height: 30,
        };
        assert_eq!(r.to_bbox_string(), "10,20,100,30");
        assert_eq!(Rect::parse_bbox("10,20,100,30"), Some(r));
    }

    #[test]
    fn rect_bbox_handles_negative_coords() {
        // Scrolled-off-screen elements report negative offsets.
        let r = Rect::parse_bbox("-50,-10,200,40").unwrap();
        assert_eq!(r.x, -50);
        assert_eq!(r.y, -10);
        assert_eq!(r.width, 200);
        assert_eq!(r.height, 40);
    }

    #[test]
    fn rect_bbox_rejects_malformed() {
        // Missing components — treated as "no bounds" rather than a panic
        // so a malformed snapshot attribute doesn't poison downstream callers.
        assert_eq!(Rect::parse_bbox(""), None);
        assert_eq!(Rect::parse_bbox("10,20,30"), None);
        assert_eq!(Rect::parse_bbox("10,20,30,40,50"), None);
        assert_eq!(Rect::parse_bbox("a,b,c,d"), None);
        assert_eq!(Rect::parse_bbox("10;20;30;40"), None);
    }

    #[test]
    fn evaluate_xpath_detailed_populates_bounds_when_bbox_present() {
        let xml = r#"<?xml version="1.0"?>
<Application name="app" _ref="bus|/app">
  <Button role="button" name="ok" showing="true" bbox="12,34,100,28"
          _ref="bus|/ok"/>
  <Button role="button" name="no-bbox" _ref="bus|/none"/>
</Application>"#;
        let matches = evaluate_xpath_detailed(xml, "//Button").unwrap();
        assert_eq!(matches.len(), 2);
        let ok = &matches[0];
        assert_eq!(ok.name.as_deref(), Some("ok"));
        assert_eq!(
            ok.bounds,
            Some(Rect {
                x: 12,
                y: 34,
                width: 100,
                height: 28,
            })
        );
        let no_bbox = &matches[1];
        assert!(no_bbox.bounds.is_none());
        // bbox attribute should not leak into the generic attributes map
        // (it's in SNAPSHOT_BUILTINS).
        assert!(!ok.attributes.contains_key("bbox"));
    }

    #[test]
    fn rect_is_inside_fully_contained() {
        let outer = Rect {
            x: 0,
            y: 0,
            width: 1024,
            height: 768,
        };
        let inner = Rect {
            x: 100,
            y: 200,
            width: 50,
            height: 20,
        };
        assert!(inner.is_inside(&outer));
    }

    #[test]
    fn rect_is_inside_partial_overlap_left() {
        let outer = Rect {
            x: 10,
            y: 10,
            width: 100,
            height: 100,
        };
        // Starts before outer.x — partially off to the left.
        let straddles = Rect {
            x: 0,
            y: 20,
            width: 30,
            height: 20,
        };
        assert!(!straddles.is_inside(&outer));
    }

    #[test]
    fn rect_is_inside_partial_overlap_bottom() {
        let outer = Rect {
            x: 0,
            y: 0,
            width: 100,
            height: 100,
        };
        // Bottom edge (y=110) extends past outer's bottom (100).
        let straddles = Rect {
            x: 10,
            y: 90,
            width: 50,
            height: 20,
        };
        assert!(!straddles.is_inside(&outer));
    }

    #[test]
    fn rect_is_inside_exact_match() {
        // Edge-touching counts as inside — a widget flush with its
        // viewport's edges is "in view," not partially clipped.
        let r = Rect {
            x: 5,
            y: 5,
            width: 20,
            height: 20,
        };
        assert!(r.is_inside(&r));
    }

    #[test]
    fn rect_is_inside_disjoint() {
        let outer = Rect {
            x: 0,
            y: 0,
            width: 100,
            height: 100,
        };
        let far = Rect {
            x: 500,
            y: 500,
            width: 10,
            height: 10,
        };
        assert!(!far.is_inside(&outer));
    }

    #[test]
    fn rect_geometry_accessors() {
        let r = Rect {
            x: 10,
            y: 20,
            width: 40,
            height: 80,
        };
        assert_eq!(r.right(), 50);
        assert_eq!(r.bottom(), 100);
        assert_eq!(r.center_x(), 30);
        assert_eq!(r.center_y(), 60);
    }

    #[test]
    fn evaluate_xpath_detailed_malformed_bbox_yields_no_bounds() {
        // Parse errors on bbox fall through to `bounds: None` without
        // aborting the whole evaluation — a strict failure here would
        // make one bad node poison the whole snapshot.
        let xml = r#"<?xml version="1.0"?>
<Application _ref="bus|/app">
  <Button role="button" bbox="not-a-rect" _ref="bus|/b"/>
</Application>"#;
        let matches = evaluate_xpath_detailed(xml, "//Button").unwrap();
        assert_eq!(matches.len(), 1);
        assert!(matches[0].bounds.is_none());
    }
}