wdotool 0.5.1

xdotool-compatible automation for Wayland
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
//! Layer 3 round-trip integration tests: drive `wdotool` against a
//! real headless sway compositor and assert on what events the
//! observer client actually received. This is the layer that catches
//! bugs Layer 2 (mock-backend) can't reach: virtual-keyboard
//! transient-keymap injection, modifier-state divergence between
//! what wdotool thinks is pressed and what the compositor delivers,
//! scroll axis sign, and the focus model on `windowactivate`.
//!
//! Each test starts its own sway session so they're independent.
//! Sway boots in under a second on a warm cache, so per-test
//! isolation is cheap.
//!
//! When `sway` isn't installed the tests skip themselves with a
//! `println!` (visible in `cargo test -- --nocapture`) rather than
//! failing. CI installs sway before running the suite.

#![cfg(target_os = "linux")]

use std::sync::{Mutex, MutexGuard};
use std::time::Duration;

use wdotool_test_harness::{HarnessError, HeadlessSway, Observer, Prime};

/// Process-wide serialization for the round-trip suite. Each test
/// boots its own sway compositor, and running several at once on a
/// CI runner has them fighting for CPU and tripping `wait_for_ready`
/// timeouts. CI passes `--test-threads=1`, but `cargo test --workspace`
/// locally defaults to parallel and was flaking. Holding this mutex
/// across the lifetime of each test makes the suite serial regardless
/// of how it's invoked.
static SUITE_LOCK: Mutex<()> = Mutex::new(());

/// Boot a fresh sway session, spawn the observer inside it, wait for
/// the surface to be ready, and drain prelude noise (modifiers,
/// keyboard_enter, pointer_enter). Returns None when sway isn't
/// installed so the calling test can skip itself. The returned guard
/// keeps `SUITE_LOCK` held for the test's duration.
fn fresh_session() -> Option<(HeadlessSway, Observer, MutexGuard<'static, ()>)> {
    // PoisonError can happen if a previous test panicked; we don't
    // care, the lock is just a cross-test serializer.
    let guard = SUITE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let sway = match HeadlessSway::start() {
        Ok(s) => s,
        Err(HarnessError::SwayUnavailable(_)) => {
            println!(
                "skipping round-trip test: sway is not installed. \
                 install with `pacman -S sway` (Arch) or `apt install sway` (Debian/Ubuntu)."
            );
            return None;
        }
        Err(other) => panic!("sway failed to start: {other}"),
    };
    let observer = sway.spawn_observer().expect("spawn observer");
    // 30s ready timeout: sway boots in well under a second on a
    // dev box, but slow CI runners (no GPU, software rendering,
    // shared with whatever else GitHub Actions is doing) need
    // headroom. The timeout only costs anything when sway is
    // genuinely broken.
    observer
        .wait_for_ready(Duration::from_secs(30))
        .expect("observer reached ready");
    let _ = observer.collect_events(Duration::from_millis(50));
    Some((sway, observer, guard))
}

/// Filter event lines to just the ones with the given prefix, for
/// readable assertions. Returns owned strings so the assertion
/// failure message has full context.
fn lines_starting_with(events: &[String], prefix: &str) -> Vec<String> {
    events
        .iter()
        .filter(|l| l.starts_with(prefix))
        .cloned()
        .collect()
}

/// Linux evdev keycodes for the keys these tests touch. Stable across
/// kernels, OS distributions, and (importantly) sway versions. Used
/// when the observer can't resolve keysym names because the keymap
/// didn't make it through xkbcommon, which has happened on CI.
const KEY_LEFTCTRL: u32 = 29;
const KEY_A: u32 = 30;
const KEY_LEFTSHIFT: u32 = 42;

/// Parse a `key <keycode> <name> <press|release>` line. Returns the
/// keycode, keysym name (which may be `?` if xkb couldn't resolve),
/// and the action.
fn parse_key_line(line: &str) -> Option<(u32, &str, &str)> {
    let mut parts = line.split_whitespace();
    if parts.next()? != "key" {
        return None;
    }
    let kc: u32 = parts.next()?.parse().ok()?;
    let name = parts.next()?;
    let action = parts.next()?;
    Some((kc, name, action))
}

// ============================================================
// Sanity: observer comes up and gets focus inside headless sway.
// ============================================================

#[test]
fn observer_reaches_ready_inside_headless_sway() {
    let Some((_sway, _observer, _guard)) = fresh_session() else {
        return;
    };
}

// ============================================================
// Prime: long-running wdotool that holds virtual devices alive.
// ============================================================

#[test]
fn prime_keeps_seat_capabilities_up_across_calls() {
    // Without prime, every transient `wdotool key a` toggles the seat
    // caps from 0 -> keyboard|pointer -> 0 because each invocation
    // creates and destroys its own virtual devices. With prime
    // running, the caps should stay up through the lifetime of prime.
    // We verify this by counting how many times the cap drops to 0
    // in the observer's stream during multiple wdotool calls.
    let Some((sway, observer, _guard)) = fresh_session() else {
        return;
    };

    let _prime: Prime = sway.spawn_prime().expect("spawn prime");

    // Drain whatever events arrived between observer ready and prime
    // ready (mostly the cap rising to 0x3 and the keymap landing).
    let _ = observer.collect_events(Duration::from_millis(200));

    // Run 3 transient wdotool keypresses. Each adds a temporary
    // virtual_keyboard which raises caps higher (or rather, leaves
    // caps the same since they're already 0x3 from prime), runs the
    // op, then exits. At no point should caps drop to 0x0.
    for _ in 0..3 {
        let out = sway.run_wdotool(&["key", "a"]).expect("run wdotool");
        assert!(out.status.success(), "wdotool failed: {out:?}");
    }
    let events = observer.collect_events(Duration::from_millis(500));
    let cap_drops_to_zero = events.iter().filter(|l| l == &"seat_caps 0x0").count();
    assert_eq!(
        cap_drops_to_zero, 0,
        "seat caps dropped to 0 while prime was running. events: {events:?}"
    );

    // And we should have seen 3 sets of key events (3 a-press, 3 a-release).
    let presses = events
        .iter()
        .filter(|l| l.starts_with("key ") && l.ends_with(" press"))
        .count();
    let releases = events
        .iter()
        .filter(|l| l.starts_with("key ") && l.ends_with(" release"))
        .count();
    assert_eq!(presses, 3, "expected 3 presses, got {presses}: {events:?}");
    assert_eq!(
        releases, 3,
        "expected 3 releases, got {releases}: {events:?}"
    );
}

// ============================================================
// Replay: JSON trace -> backend dispatch -> real compositor.
// ============================================================

#[test]
fn replay_keyboard_trace_round_trips_to_observer() {
    // Hand-write a small trace with keyboard events, replay it
    // against headless sway, and assert each chord arrives at the
    // observer in the right order. Pointer / scroll events from the
    // simulated recorder script are excluded because the
    // sway-headless cursor pipeline doesn't deliver them (see the
    // file header further down). This test specifically pins the
    // JSON -> dispatch -> real-compositor flow, complementing
    // cli_replay.rs's mock-backend coverage of the dispatch contract.
    use std::io::Write as _;
    let Some((sway, observer, _guard)) = fresh_session() else {
        return;
    };

    let dir = tempfile::tempdir().unwrap();
    let trace_path = dir.path().join("trace.json");
    let mut f = std::fs::File::create(&trace_path).unwrap();
    f.write_all(
        br#"[
            {"kind":"key","t_ms":0,"chord":"a"},
            {"kind":"gap","t_ms":1,"ms":10},
            {"kind":"key","t_ms":11,"chord":"ctrl+l"},
            {"kind":"gap","t_ms":12,"ms":10},
            {"kind":"key","t_ms":22,"chord":"Return"}
        ]"#,
    )
    .unwrap();
    drop(f);

    let out = sway
        .run_wdotool(&["replay", trace_path.to_str().unwrap()])
        .expect("run wdotool");
    assert!(out.status.success(), "wdotool replay failed: {out:?}");

    let events = observer.collect_events(Duration::from_millis(400));
    let keys = lines_starting_with(&events, "key ");

    // Expected backend calls per replay's dispatch logic for the
    // chords above:
    //   "a"        -> press(a), release(a)                  [2]
    //   "ctrl+l"   -> press(Ctrl), pr(l), release(Ctrl)     [3 lines, 4 events]
    //   "Return"   -> press(Return), release(Return)        [2]
    // ctrl+l yields a press+release pair around the Ctrl modifier,
    // so the observer sees:
    //   press a, release a,
    //   press Ctrl, press l, release l, release Ctrl,
    //   press Return, release Return
    // Eight key events total; pin the count and the keycode
    // sequence (using evdev keycodes for the same xkb-may-fail
    // robustness as the other keyboard tests in this file).
    const KEY_L: u32 = 38;
    const KEY_RETURN: u32 = 28;
    let parsed: Vec<(u32, &str, &str)> = keys
        .iter()
        .map(|l| parse_key_line(l).unwrap_or_else(|| panic!("parse {l:?}")))
        .collect();
    let expected = [
        (KEY_A, "press"),
        (KEY_A, "release"),
        (KEY_LEFTCTRL, "press"),
        (KEY_L, "press"),
        (KEY_L, "release"),
        (KEY_LEFTCTRL, "release"),
        (KEY_RETURN, "press"),
        (KEY_RETURN, "release"),
    ];
    assert_eq!(
        parsed.len(),
        expected.len(),
        "expected {} key events, got {}: {events:?}",
        expected.len(),
        parsed.len()
    );
    for (i, (exp_kc, exp_act)) in expected.iter().enumerate() {
        assert_eq!(
            parsed[i].0, *exp_kc,
            "keys[{i}] keycode mismatch: {}",
            keys[i]
        );
        assert_eq!(
            parsed[i].2, *exp_act,
            "keys[{i}] action mismatch: {}",
            keys[i]
        );
    }
}

// ============================================================
// Keyboard: key, keydown/keyup, modifier ordering, type.
// ============================================================

#[test]
fn key_a_round_trips_through_wlroots_backend() {
    let Some((sway, observer, _guard)) = fresh_session() else {
        return;
    };
    let out = sway.run_wdotool(&["key", "a"]).expect("run wdotool");
    assert!(out.status.success(), "wdotool failed: {out:?}");

    let events = observer.collect_events(Duration::from_millis(300));
    let keys = lines_starting_with(&events, "key ");
    assert_eq!(keys.len(), 2, "expected exactly press+release: {events:?}");
    let (kc0, _, action0) = parse_key_line(&keys[0]).expect("parse press");
    let (kc1, _, action1) = parse_key_line(&keys[1]).expect("parse release");
    assert_eq!(kc0, KEY_A, "press keycode: {}", keys[0]);
    assert_eq!(action0, "press", "first action: {}", keys[0]);
    assert_eq!(kc1, KEY_A, "release keycode: {}", keys[1]);
    assert_eq!(action1, "release", "second action: {}", keys[1]);
}

#[test]
fn key_ctrl_shift_a_emits_modifiers_in_xdotool_order() {
    let Some((sway, observer, _guard)) = fresh_session() else {
        return;
    };
    let out = sway
        .run_wdotool(&["key", "ctrl+shift+a"])
        .expect("run wdotool");
    assert!(out.status.success(), "wdotool failed: {out:?}");

    let events = observer.collect_events(Duration::from_millis(300));
    let keys = lines_starting_with(&events, "key ");

    // Press(Control_L), Press(Shift_L), Press(a),
    // Release(a), Release(Shift_L), Release(Control_L).
    assert_eq!(keys.len(), 6, "events: {events:?}");
    let parsed: Vec<(u32, &str, &str)> = keys
        .iter()
        .map(|l| parse_key_line(l).unwrap_or_else(|| panic!("parse {l:?}")))
        .collect();
    let expected = [
        (KEY_LEFTCTRL, "press"),
        (KEY_LEFTSHIFT, "press"),
        (KEY_A, "press"),
        (KEY_A, "release"),
        (KEY_LEFTSHIFT, "release"),
        (KEY_LEFTCTRL, "release"),
    ];
    for (i, (exp_kc, exp_act)) in expected.iter().enumerate() {
        assert_eq!(parsed[i].0, *exp_kc, "keys[{i}] keycode: {}", keys[i]);
        assert_eq!(parsed[i].2, *exp_act, "keys[{i}] action: {}", keys[i]);
    }
}

// keydown/keyup don't compose across separate wdotool processes on
// the wlroots backend: each invocation creates and destroys its own
// virtual_keyboard, and sway auto-releases any keys held by a device
// on destruction. Layer 2 covers the dispatch contract; this case
// would only work end-to-end via libei (with a portal session) or a
// future "wdotool session" mode that keeps the device alive across
// commands.
#[ignore = "wlroots backend doesn't preserve held-key state across process invocations"]
#[test]
fn keydown_then_keyup_round_trip_holds_then_releases() {
    // keydown leaves the key held; keyup releases it. A bug where
    // wdotool sends a stray release at process exit (or fails to
    // send the release on keyup) would surface here as either an
    // unexpected release or a missing one.
    let Some((sway, observer, _guard)) = fresh_session() else {
        return;
    };

    let out = sway.run_wdotool(&["keydown", "a"]).expect("run wdotool");
    assert!(out.status.success(), "keydown failed: {out:?}");
    let post_keydown = observer.collect_events(Duration::from_millis(200));
    let keys = lines_starting_with(&post_keydown, "key ");
    assert_eq!(
        keys.len(),
        1,
        "keydown should emit exactly press: {post_keydown:?}"
    );
    assert!(keys[0].contains(" a ") && keys[0].ends_with(" press"));

    let out = sway.run_wdotool(&["keyup", "a"]).expect("run wdotool");
    assert!(out.status.success(), "keyup failed: {out:?}");
    let post_keyup = observer.collect_events(Duration::from_millis(200));
    let keys = lines_starting_with(&post_keyup, "key ");
    assert_eq!(
        keys.len(),
        1,
        "keyup should emit exactly release: {post_keyup:?}"
    );
    assert!(keys[0].contains(" a ") && keys[0].ends_with(" release"));
}

#[test]
fn type_hello_arrives_as_individual_characters() {
    // The wlroots backend types text by injecting a transient keymap
    // that maps the next char to a known keycode, sending press +
    // release, and restoring the original keymap. This test pins that
    // each character arrives as a press-release pair, in order, with
    // a `keymap_changed` event somewhere in the prelude proving the
    // injection happened. The keysym name in each line should match
    // the literal char.
    let Some((sway, observer, _guard)) = fresh_session() else {
        return;
    };
    let out = sway
        .run_wdotool(&["type", "--delay", "0", "hello"])
        .expect("run wdotool");
    assert!(out.status.success(), "wdotool failed: {out:?}");

    let events = observer.collect_events(Duration::from_millis(800));

    // The wlroots backend sends a keymap_received line for each
    // transient keymap upload. Verify at least one happened (proof
    // of the injection mechanism), but don't require keymap_changed
    // since xkbcommon may fail to parse the transient keymap on
    // some sway/xkb versions and skip the "_changed" emit.
    assert!(
        events.iter().any(|l| l.starts_with("keymap_received ")),
        "expected at least one keymap_received during type: {events:?}"
    );

    // Five chars should produce five press events (and five releases).
    // We don't check the keysym name column because the transient
    // keymap may not have parsed cleanly — see above. The critical
    // contract is "five characters got delivered, in order, as
    // press+release pairs".
    let key_lines = lines_starting_with(&events, "key ");
    let presses: Vec<_> = key_lines
        .iter()
        .filter_map(|l| parse_key_line(l))
        .filter(|(_, _, action)| *action == "press")
        .collect();
    let releases: Vec<_> = key_lines
        .iter()
        .filter_map(|l| parse_key_line(l))
        .filter(|(_, _, action)| *action == "release")
        .collect();
    assert_eq!(
        presses.len(),
        5,
        "expected 5 press events for 'hello': {events:?}"
    );
    assert_eq!(
        releases.len(),
        5,
        "expected 5 release events for 'hello': {events:?}"
    );
}

// ============================================================
// Pointer: mousemove (absolute / relative), click, mousedown/up.
//
// Every test in this section is `#[ignore]`d because the headless
// wlroots stack doesn't deliver wl_pointer events to clients in
// response to virtual_pointer.motion_absolute. The original theory
// was a timing race (observer must bind pointer before sway processes
// motion); empirical follow-up showed the pointer client IS bound
// before motion (verified with `wdotool prime` keeping the cap up
// continuously, and confirmed via `keyboard_enter` arriving at the
// observer), but pointer_motion / pointer_enter never fire.
// `swaymsg -t get_seats` reports `capabilities: 0` even when the
// wl_seat protocol shows 0x3 to clients, which says the cursor
// pipeline gates on real input devices, not virtual ones added via
// wlr_virtual_pointer_v1 in headless mode.
//
// Tried three other compositors hoping it was a sway-specific quirk:
// weston (Arch package doesn't ship zwlr_virtual_pointer_v1, so
// wdotool can't even initialize against it), labwc, and river.
// Both labwc and river show the exact same shape as sway: caps up,
// keyboard events work, no pointer events. Strongly suggests the
// gate is in wlroots itself (the shared library all three use),
// not in any compositor's high-level logic.
//
// What would actually un-ignore these: a non-wlroots target
// (mutter / kwin via libei in CI), patching wlroots, or a custom
// test compositor on smithay-rs. None are tractable in the current
// scope. Real-desktop pointer behavior is covered by the pre-release
// manual matrix in `docs/verification/`; Layer 2 pins the
// CLI-to-backend dispatch for every pointer command.
// ============================================================

#[ignore = "sway-headless cursor doesn't fire wl_pointer events for virtual_pointer.motion; see file header"]
#[test]
fn mousemove_absolute_lands_pointer_at_coords() {
    // sway's headless backend creates an output at 1280x720 by default.
    // A surface placed inside that output will receive surface-local
    // coordinates relative to its own origin. With focus_follows_mouse
    // and a single full-screen window, surface origin is at the
    // output origin, so mousemove 100 80 should produce a
    // pointer_motion at approximately (100, 80) surface-local.
    //
    // We test "approximately" because compositors may shift coords by
    // small amounts during cursor handling. A tolerance of a few
    // pixels is fine.
    let Some((sway, observer, _guard)) = fresh_session() else {
        return;
    };
    let out = sway
        .run_wdotool(&["mousemove", "100", "80"])
        .expect("run wdotool");
    assert!(out.status.success(), "wdotool failed: {out:?}");

    let events = observer.collect_events(Duration::from_millis(300));
    let motions = lines_starting_with(&events, "pointer_motion ");
    assert!(
        !motions.is_empty(),
        "expected at least one pointer_motion: {events:?}"
    );
    let last = motions.last().unwrap();
    let mut parts = last.split_whitespace();
    parts.next(); // "pointer_motion"
    let x: f64 = parts.next().unwrap().parse().unwrap();
    let y: f64 = parts.next().unwrap().parse().unwrap();
    assert!(
        (x - 100.0).abs() < 5.0 && (y - 80.0).abs() < 5.0,
        "expected pointer near (100, 80), got ({x}, {y}). All motions: {motions:?}"
    );
}

#[ignore = "sway-headless cursor doesn't fire wl_pointer events for virtual_pointer.motion; see file header"]
#[test]
fn mousemove_relative_emits_motion_delta() {
    // After an absolute move to a known position, a relative move by
    // (dx, dy) should land at (start + dx, start + dy). We use this
    // to verify the relative path actually adds rather than
    // overwrites.
    let Some((sway, observer, _guard)) = fresh_session() else {
        return;
    };

    // Anchor the cursor first.
    sway.run_wdotool(&["mousemove", "200", "150"])
        .expect("run wdotool");
    // Drain motions from the anchor move.
    let _ = observer.collect_events(Duration::from_millis(150));

    // Now relative move by (20, -10).
    let out = sway
        .run_wdotool(&["mousemove", "--relative", "20", "-10"])
        .expect("run wdotool");
    assert!(out.status.success(), "wdotool failed: {out:?}");

    let events = observer.collect_events(Duration::from_millis(300));
    let motions = lines_starting_with(&events, "pointer_motion ");
    assert!(
        !motions.is_empty(),
        "expected at least one pointer_motion: {events:?}"
    );
    let last = motions.last().unwrap();
    let mut parts = last.split_whitespace();
    parts.next();
    let x: f64 = parts.next().unwrap().parse().unwrap();
    let y: f64 = parts.next().unwrap().parse().unwrap();
    assert!(
        (x - 220.0).abs() < 5.0 && (y - 140.0).abs() < 5.0,
        "expected pointer near (220, 140) after relative move, got ({x}, {y})"
    );
}

#[ignore = "sway-headless cursor doesn't fire wl_pointer events for virtual_pointer.motion; see file header"]
#[test]
fn click_1_emits_left_button_press_release() {
    // Linux button code 272 = BTN_LEFT (xdotool's button 1).
    let Some((sway, observer, _guard)) = fresh_session() else {
        return;
    };
    let out = sway.run_wdotool(&["click", "1"]).expect("run wdotool");
    assert!(out.status.success(), "wdotool failed: {out:?}");

    let events = observer.collect_events(Duration::from_millis(300));
    let buttons = lines_starting_with(&events, "pointer_button ");
    assert_eq!(buttons.len(), 2, "expected press+release: {events:?}");
    assert!(
        buttons[0].starts_with("pointer_button 272 ") && buttons[0].ends_with(" press"),
        "press: {}",
        buttons[0]
    );
    assert!(
        buttons[1].starts_with("pointer_button 272 ") && buttons[1].ends_with(" release"),
        "release: {}",
        buttons[1]
    );
}

#[ignore = "sway-headless cursor doesn't fire wl_pointer events for virtual_pointer.motion; see file header"]
#[test]
fn mousedown_then_mouseup_emit_press_then_release() {
    let Some((sway, observer, _guard)) = fresh_session() else {
        return;
    };

    sway.run_wdotool(&["mousedown", "1"]).expect("run wdotool");
    let post_down = observer.collect_events(Duration::from_millis(200));
    let buttons = lines_starting_with(&post_down, "pointer_button ");
    assert_eq!(
        buttons.len(),
        1,
        "mousedown should emit only press: {post_down:?}"
    );
    assert!(
        buttons[0].ends_with(" press"),
        "expected press, got: {}",
        buttons[0]
    );

    sway.run_wdotool(&["mouseup", "1"]).expect("run wdotool");
    let post_up = observer.collect_events(Duration::from_millis(200));
    let buttons = lines_starting_with(&post_up, "pointer_button ");
    assert_eq!(
        buttons.len(),
        1,
        "mouseup should emit only release: {post_up:?}"
    );
    assert!(
        buttons[0].ends_with(" release"),
        "expected release, got: {}",
        buttons[0]
    );
}

// ============================================================
// Scroll: axis label and sign convention.
// ============================================================

#[ignore = "sway-headless cursor doesn't fire wl_pointer events for virtual_pointer.motion; see file header"]
#[test]
fn scroll_positive_dy_emits_vertical_axis_with_positive_value() {
    let Some((sway, observer, _guard)) = fresh_session() else {
        return;
    };
    let out = sway
        .run_wdotool(&["scroll", "0", "3"])
        .expect("run wdotool");
    assert!(out.status.success(), "wdotool failed: {out:?}");

    let events = observer.collect_events(Duration::from_millis(300));
    let axis = events
        .iter()
        .find(|l| l.starts_with("pointer_axis vertical "))
        .unwrap_or_else(|| panic!("no vertical axis event in: {events:?}"));
    let value: f64 = axis.split_whitespace().nth(2).unwrap().parse().unwrap();
    assert!(
        value > 0.0,
        "expected positive vertical scroll, got {value}"
    );
}

#[ignore = "sway-headless cursor doesn't fire wl_pointer events for virtual_pointer.motion; see file header"]
#[test]
fn scroll_negative_dy_emits_vertical_axis_with_negative_value() {
    // Symmetric to the positive case. Catches a sign-flip bug in
    // wlroots' scroll path that wouldn't surface in Layer 2 (which
    // just asserts the value reaches the backend unchanged).
    let Some((sway, observer, _guard)) = fresh_session() else {
        return;
    };
    let out = sway
        .run_wdotool(&["scroll", "0", "-2"])
        .expect("run wdotool");
    assert!(out.status.success(), "wdotool failed: {out:?}");

    let events = observer.collect_events(Duration::from_millis(300));
    let axis = events
        .iter()
        .find(|l| l.starts_with("pointer_axis vertical "))
        .unwrap_or_else(|| panic!("no vertical axis event in: {events:?}"));
    let value: f64 = axis.split_whitespace().nth(2).unwrap().parse().unwrap();
    assert!(
        value < 0.0,
        "expected negative vertical scroll, got {value}"
    );
}

#[ignore = "sway-headless cursor doesn't fire wl_pointer events for virtual_pointer.motion; see file header"]
#[test]
fn scroll_horizontal_axis_routes_to_horizontal_label() {
    let Some((sway, observer, _guard)) = fresh_session() else {
        return;
    };
    let out = sway
        .run_wdotool(&["scroll", "2", "0"])
        .expect("run wdotool");
    assert!(out.status.success(), "wdotool failed: {out:?}");

    let events = observer.collect_events(Duration::from_millis(300));
    assert!(
        events
            .iter()
            .any(|l| l.starts_with("pointer_axis horizontal ")),
        "expected horizontal axis event: {events:?}"
    );
    // No vertical event should fire for a horizontal-only scroll.
    assert!(
        !events
            .iter()
            .any(|l| l.starts_with("pointer_axis vertical ")),
        "unexpected vertical axis event: {events:?}"
    );
}