vs-engine-webkit 0.2.20

Browser engine bindings for vibesurfer.
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
//! Linux native input dispatch for the cursor primitives (`vs move-to`,
//! `click-at`, `hover-at`, `drag`).
//!
//! WebKitGTK 6 / GTK 4 deliberately removed public synthetic-event
//! construction (`GdkButtonEvent` and friends are ELF-hidden internal
//! symbols, not in `gdkevents.symbols.in`, so not even unsafe Rust can
//! reach them). The supported paths for injecting trusted input on
//! modern Linux are:
//!
//!  1. **XTest** — X11 protocol extension. `FakeInput` requests go
//!     through the X server and arrive at subscribed clients (our
//!     WebKitGTK WebView's hosting GtkWindow) as real hardware input.
//!     Trusted in JS (`isTrusted = true`). Works under `xvfb` (CI) and
//!     any X11 / Xwayland session.
//!  2. **libei** — Wayland emulated-input protocol. Negotiates a virtual
//!     pointer via the `xdg-desktop-portal` `RemoteDesktop` interface,
//!     then emits events that the compositor delivers as trusted
//!     hardware input. Required for pure-Wayland sessions where the
//!     compositor refuses to launch Xwayland.
//!
//! XTest goes through the pure-Rust `x11rb` crate: no `unsafe`, no
//! `dlopen`/`dlsym`, no libc. libei (Phase B) will route through the
//! similarly-safe `reis` crate. Runtime detection prefers libei under
//! pure Wayland and falls back to XTest otherwise; if neither path is
//! reachable, `cursor_op` returns `ENGINE_UNSUPPORTED` and the wire
//! response carries `! ENGINE_UNSUPPORTED` exactly the same way it did
//! before v0.1.11.
//!
//! Coordinate space: every dispatcher accepts screen-absolute CSS px.
//! The caller (the WebView's hosting `gtk::Window`) maintains the
//! `(window_origin_x, window_origin_y)` translation from the WebView's
//! local rect (top-left at 0,0) into screen coordinates.

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

use x11rb::connection::Connection as _;
use x11rb::protocol::xinput::{self, ConnectionExt as _};
use x11rb::protocol::xproto::{
    AtomEnum, ConfigureWindowAux, ConnectionExt as _, InputFocus, StackMode, Window,
};
use x11rb::protocol::xtest::ConnectionExt as _;
use x11rb::rust_connection::RustConnection;
use x11rb::wrapper::ConnectionExt as _;
use x11rb::CURRENT_TIME;

use crate::engine::{EngineError, EngineResult};

/// A pointer position in screen-absolute CSS pixels.
#[derive(Debug, Clone, Copy)]
pub(crate) struct ScreenPoint {
    pub x: i32,
    pub y: i32,
}

/// Mouse button identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Button {
    Left,
    Middle,
    Right,
}

/// One injected event in a humanized sequence.
#[derive(Debug, Clone, Copy)]
pub(crate) enum InputEvent {
    /// Move the pointer to the given screen position.
    Move(ScreenPoint),
    /// Press a mouse button at the pointer's current position.
    Press(Button),
    /// Release a mouse button at the pointer's current position.
    Release(Button),
    /// Turn the wheel by `(dx, dy)` CSS px at the pointer (positive
    /// `dy` scrolls down). `step` is what one wheel click scrolls on
    /// each axis, for dispatchers that only have clicks.
    Wheel { dx: f64, dy: f64, step: (f64, f64) },
}

/// A pluggable native-input dispatcher.
///
/// Implementors translate `InputEvent`s into platform calls (XTest
/// over `x11rb`, ei_device events over libei, etc.). All methods are
/// fallible because the underlying platform call may fail at runtime
/// (display closed, compositor revoked the session, kernel busy).
pub(crate) trait InputDispatcher: Send + Sync {
    /// Best-effort name for diagnostics / `EngineCapabilities`.
    fn backend_name(&self) -> &'static str;
    /// Dispatch a single event. Implementations may buffer; call
    /// `flush` to guarantee delivery.
    fn dispatch(&self, ev: InputEvent) -> EngineResult<()>;
    /// Force any buffered events to flush to the server / compositor.
    fn flush(&self) -> EngineResult<()>;

    /// Press one character as a real key.
    ///
    /// `settle` pumps the caller's main loop for the given duration.
    /// The dispatcher needs it because making a character typeable can
    /// mean changing the server's keymap, and the toolkit only learns
    /// about that by processing an event — on the same thread this
    /// call is running on. Sleeping here instead would mean the key
    /// arrives before anything can interpret it.
    ///
    /// A dispatcher that cannot reach a keyboard says so, and the wire
    /// reports `ENGINE_UNSUPPORTED` exactly as the whole primitive did
    /// before.
    fn key_down(&self, _ch: char, _settle: &dyn Fn(Duration)) -> EngineResult<()> {
        Err(EngineError::Unsupported {
            engine: "wpe",
            primitive: "type_text",
        })
    }

    /// Release the character most recently pressed by [`Self::key_down`].
    fn key_up(&self, _ch: char) -> EngineResult<()> {
        Err(EngineError::Unsupported {
            engine: "wpe",
            primitive: "type_text",
        })
    }

    /// Release any resources a run of [`Self::type_char`] set up. The
    /// XTest path borrows a keycode from the server's keymap, so this
    /// is where it gives it back; other paths do nothing.
    fn end_typing(&self) -> EngineResult<()> {
        Ok(())
    }

    /// Point the keyboard at whatever the pointer is over, if the
    /// platform routes keys by focus rather than by position. Called
    /// before a run of typing; best-effort, and a failure here is not
    /// worth failing the call over.
    fn focus_pointer_window(&self) {}

    /// Hold (`pressed`) or let go of a modifier key, by X keysym
    /// (Shift_L, Control_L, Alt_L, Super_L), for a click with
    /// modifiers.
    fn modifier(&self, _keysym: u32, _pressed: bool) -> EngineResult<()> {
        Err(EngineError::Unsupported {
            engine: "wpe",
            primitive: "click modifiers",
        })
    }

    /// Put the top-level window titled `title` above the others, where
    /// windows share one screen position and input goes by position.
    /// Best-effort, like focus.
    fn raise_window(&self, _title: &str) {}

    /// The screen's size in pixels, where the platform has one screen
    /// that input addresses by position.
    fn screen_size(&self) -> Option<(i32, i32)> {
        None
    }

    /// Move the top-level window titled `title` to (`x`, `y`) on the
    /// screen. Returns whether it was found.
    fn place_window(&self, _title: &str, _x: i32, _y: i32) -> bool {
        false
    }

    /// Where the top-level window titled `title` sits on the screen now
    /// (its top-left corner), as the display server reports it.
    fn window_origin(&self, _title: &str) -> Option<(i32, i32)> {
        None
    }

    /// The X window id of the top-level window titled `title`, where
    /// the display is X11 (the target of an XDND drop).
    fn x11_window(&self, _title: &str) -> Option<u32> {
        None
    }

    /// Route the input that follows through the pointer and keyboard
    /// that belong to the page named `title` (created on first use), so
    /// pages do not share one pointer position, hover or focus. Where
    /// the platform has one pointer for everything, this does nothing.
    fn use_page_pointer(&self, _title: &str) {}

    /// Remove the pointer and keyboard of a page that closed.
    fn drop_page_pointer(&self, _title: &str) {}

    /// Route the input that follows through the display's core pointer
    /// and keyboard again. Typing uses these: toolkits take keys from
    /// the core keyboard only.
    fn use_core_pointer(&self) {}
}

// =============================================================================
// Runtime detection
// =============================================================================

/// Return the best available input dispatcher for the current session,
/// or `None` if neither libei nor XTest could be reached.
///
/// Detection order:
///   1. If `XDG_SESSION_TYPE=wayland` AND libei portal-session opens:
///      return `Libei`. (Phase B — currently returns `None` from the
///      libei probe; see comment in `LibeiDispatcher::try_new`.)
///   2. Else if `RustConnection::connect` succeeds against the
///      `DISPLAY` env: return `Xtest`.
///   3. Else: `None`.
pub(crate) fn detect() -> Option<Box<dyn InputDispatcher>> {
    if is_wayland_session() {
        if let Some(b) = LibeiDispatcher::try_new() {
            return Some(Box::new(b));
        }
    }
    if let Some(b) = XtestDispatcher::try_new() {
        return Some(Box::new(b));
    }
    None
}

fn is_wayland_session() -> bool {
    std::env::var_os("WAYLAND_DISPLAY").is_some()
        && std::env::var("XDG_SESSION_TYPE").as_deref() == Ok("wayland")
}

/// Cached dispatcher so repeated `cursor_op` calls reuse the X
/// connection / libei session instead of reconnecting each call.
static DISPATCHER: OnceLock<Option<Box<dyn InputDispatcher + 'static>>> = OnceLock::new();

/// Resolve (and cache) the dispatcher. Returns `Err(Unsupported)` if
/// neither backend is available — the caller is the `cursor_op` impl
/// in `wpe.rs`, which propagates the error as `ENGINE_UNSUPPORTED` on
/// the wire.
pub(crate) fn dispatcher() -> EngineResult<&'static (dyn InputDispatcher + 'static)> {
    let cell = DISPATCHER.get_or_init(detect);
    match cell.as_deref() {
        Some(d) => Ok(d),
        None => Err(EngineError::Unsupported {
            engine: "wpe",
            primitive: "cursor_op",
        }),
    }
}

/// Public-side helper used by `wpe.rs::WpeBackend::capabilities()`:
/// returns the backend name (`"xtest"` / `"libei"`) if input dispatch
/// is available, or `None` if it isn't.
#[allow(dead_code)]
pub(crate) fn active_backend_name() -> Option<&'static str> {
    DISPATCHER
        .get_or_init(detect)
        .as_deref()
        .map(InputDispatcher::backend_name)
}

// =============================================================================
// XTest backend (x11rb pure-Rust X11 client)
// =============================================================================

/// XTest event-type codes used in the `FakeInput` request. Mirror of
/// X11 protocol constants — `x11rb` doesn't expose them as named
/// constants under `xtest`, only under `xproto::ButtonPressEvent` /
/// friends, which would require pulling more types just to get u8s.
const XT_MOTION_NOTIFY: u8 = 6;
const XT_BUTTON_PRESS: u8 = 4;
const XT_BUTTON_RELEASE: u8 = 5;
const XT_KEY_PRESS: u8 = 2;
const XT_KEY_RELEASE: u8 = 3;

/// XTest dispatcher. Holds an `x11rb::rust_connection::RustConnection`
/// to the default display plus the root window id (used as the target
/// in `FakeInput` motion requests).
struct XtestDispatcher {
    conn: RustConnection,
    root: Window,
    /// The keycode borrowed from the server's keymap for typing, and
    /// the keysym currently bound to it. See [`XtestDispatcher::bind`].
    scratch: Mutex<Option<ScratchKey>>,
    /// Page windows found by title (see `find_titled`).
    windows: Mutex<std::collections::HashMap<String, Window>>,
    /// `_NET_WM_NAME` and `UTF8_STRING`, interned once.
    name_atoms: (u32, u32),
    /// Whether the server speaks XInput 2.2 (multiple pointers).
    xi2: bool,
    /// Each page's own master pointer, by window title, and the ones
    /// this daemon holds but no page uses (see `page_pointer`).
    pointers: Mutex<PointerPool>,
    /// A window of ours that owns the `VS_PTR_<k>` selections: the
    /// claim on pointer k, released by the server when we exit.
    claim_window: Window,
}

#[derive(Default)]
struct PointerPool {
    assigned: std::collections::HashMap<String, u16>,
    free: Vec<u16>,
}

/// A keycode borrowed from the X server's keymap so arbitrary text
/// can be typed through it.
#[derive(Clone, Copy)]
struct ScratchKey {
    keycode: u8,
    /// What it is bound to right now, so typing "aaa" rebinds once
    /// rather than three times.
    bound: u32,
    /// How many keysyms per keycode this server's keymap uses, needed
    /// to hand the keycode back in the shape it was found.
    per_code: u8,
}

impl XtestDispatcher {
    fn try_new() -> Option<Self> {
        // `connect(None)` reads `$DISPLAY`. The first roots[0] is the
        // default screen — same convention every X11 client uses.
        let (conn, screen_num) = RustConnection::connect(None).ok()?;
        let root = conn.setup().roots.get(screen_num)?.root;
        let atom = |name: &[u8]| -> Option<u32> {
            Some(conn.intern_atom(false, name).ok()?.reply().ok()?.atom)
        };
        let name_atoms = (atom(b"_NET_WM_NAME")?, atom(b"UTF8_STRING")?);
        // XI2 requests need the version handshake first on a client.
        let xi2 = conn
            .xinput_xi_query_version(2, 2)
            .ok()
            .and_then(|c| c.reply().ok())
            .is_some_and(|r| (r.major_version, r.minor_version) >= (2, 2));
        let claim_window = conn.generate_id().ok()?;
        conn.create_window(
            0,
            claim_window,
            root,
            0,
            0,
            1,
            1,
            0,
            x11rb::protocol::xproto::WindowClass::INPUT_ONLY,
            0,
            &x11rb::protocol::xproto::CreateWindowAux::new(),
        )
        .ok()?;
        let me = Self {
            conn,
            root,
            scratch: Mutex::new(None),
            windows: Mutex::default(),
            name_atoms,
            xi2,
            pointers: Mutex::default(),
            claim_window,
        };
        if xi2 {
            me.park_unclaimed_pointers();
        }
        Some(me)
    }

    /// Move every `vs-ptr-<k>` pointer no live daemon claims to the
    /// screen's far corner. A daemon that exited left its pointers
    /// where its pages' input put them, and one resting inside a tile
    /// would hover whichever page goes there next.
    fn park_unclaimed_pointers(&self) {
        let Some(devices) = self
            .conn
            .xinput_xi_query_device(xinput::Device::ALL_MASTER)
            .ok()
            .and_then(|c| c.reply().ok())
        else {
            return;
        };
        for d in devices
            .infos
            .iter()
            .filter(|d| d.type_ == xinput::DeviceType::MASTER_POINTER)
        {
            let Some(k) = std::str::from_utf8(&d.name)
                .ok()
                .and_then(|n| n.strip_prefix("vs-ptr-"))
                .and_then(|n| n.strip_suffix(" pointer"))
            else {
                continue;
            };
            let claimed = self
                .conn
                .intern_atom(false, format!("VS_PTR_{k}").as_bytes())
                .ok()
                .and_then(|c| c.reply().ok())
                .and_then(|a| self.conn.get_selection_owner(a.atom).ok())
                .and_then(|c| c.reply().ok())
                .is_some_and(|r| r.owner != x11rb::NONE);
            if !claimed {
                self.park(d.deviceid);
            }
        }
        self.use_core_pointer();
    }

    /// Move master pointer `id` to the screen's far corner, past every
    /// page window and tile.
    fn park(&self, id: u16) {
        let Some((w, h)) = self.screen_size() else {
            return;
        };
        if let Ok(cookie) = self.conn.xinput_xi_set_client_pointer(x11rb::NONE, id) {
            cookie.ignore_error();
        }
        let _ = self.dispatch(InputEvent::Move(ScreenPoint { x: w - 1, y: h - 1 }));
        let _ = self.conn.sync();
    }

    /// Find a keycode the current keymap leaves empty, so binding it
    /// takes nothing away from the user.
    ///
    /// Typing arbitrary text through XTest means naming a keycode,
    /// and a keycode only means a character because the keymap says
    /// so. Rather than hunt for the keycode that happens to produce
    /// `ß` on this layout — and then work out which modifiers it
    /// needs — we borrow an unused one and bind it to whatever we are
    /// about to type. This is what `xdotool` does for the same
    /// reason. [`Self::end_typing`] gives it back.
    fn find_scratch(&self) -> EngineResult<ScratchKey> {
        let setup = self.conn.setup();
        let (min, max) = (setup.min_keycode, setup.max_keycode);
        let count = max - min + 1;
        let map = self
            .conn
            .get_keyboard_mapping(min, count)
            .map_err(|e| EngineError::Other(format!("GetKeyboardMapping: {e}")))?
            .reply()
            .map_err(|e| EngineError::Other(format!("GetKeyboardMapping reply: {e}")))?;
        let per = map.keysyms_per_keycode as usize;
        if per == 0 {
            return Err(EngineError::Other("empty X keymap".into()));
        }
        // Scan from the top: high keycodes are where layouts leave
        // gaps, and a low free keycode is likelier to be one the
        // session is about to start using.
        for i in (0..usize::from(count)).rev() {
            let syms = &map.keysyms[i * per..(i + 1) * per];
            if syms.iter().all(|&k| k == 0) {
                return Ok(ScratchKey {
                    keycode: min + u8::try_from(i).unwrap_or(0),
                    bound: 0,
                    per_code: map.keysyms_per_keycode,
                });
            }
        }
        Err(EngineError::Other(
            "no free X keycode to type through".into(),
        ))
    }

    /// Bind the scratch keycode to `keysym`, if it is not already.
    fn bind(&self, keysym: u32, settle: &dyn Fn(Duration)) -> EngineResult<u8> {
        let mut guard = self.scratch.lock().unwrap();
        let mut key = match *guard {
            Some(k) => k,
            None => self.find_scratch()?,
        };
        if key.bound != keysym {
            // Every level gets the same keysym, so the character
            // arrives whatever the modifier state happens to be.
            let syms = vec![keysym; usize::from(key.per_code)];
            self.conn
                .change_keyboard_mapping(1, key.keycode, key.per_code, &syms)
                .map_err(|e| EngineError::Other(format!("ChangeKeyboardMapping: {e}")))?
                .check()
                .map_err(|e| EngineError::Other(format!("ChangeKeyboardMapping check: {e}")))?;
            // Clients learn the new mapping from a MappingNotify, and
            // the toolkit only sees that by running its event loop —
            // which is this thread. Pumping rather than sleeping is
            // the difference between the key arriving as the character
            // we just bound and arriving as whatever was there before.
            settle(Duration::from_millis(12));
            key.bound = keysym;
            *guard = Some(key);
        }
        Ok(key.keycode)
    }
}

impl XtestDispatcher {
    /// The keycode the server's keymap already has for `keysym`.
    fn keycode_of(&self, keysym: u32) -> EngineResult<Option<u8>> {
        let setup = self.conn.setup();
        let (min, max) = (setup.min_keycode, setup.max_keycode);
        let map = self
            .conn
            .get_keyboard_mapping(min, max - min + 1)
            .map_err(|e| EngineError::Other(format!("GetKeyboardMapping: {e}")))?
            .reply()
            .map_err(|e| EngineError::Other(format!("GetKeyboardMapping reply: {e}")))?;
        let per = usize::from(map.keysyms_per_keycode.max(1));
        Ok(map
            .keysyms
            .chunks(per)
            .position(|syms| syms.contains(&keysym))
            .and_then(|i| u8::try_from(i).ok())
            .map(|i| min + i))
    }

    /// A wheel turn as clicks of the X11 wheel buttons (4/5 vertical,
    /// 6/7 horizontal): XTest has no smooth-scroll axis, so the turn is
    /// rounded to whole clicks of `step` px, at least one for any
    /// nonzero delta.
    fn wheel_clicks(&self, dx: f64, dy: f64, step: (f64, f64)) -> EngineResult<()> {
        let clicks = |d: f64, step: f64| -> u32 {
            if d == 0.0 {
                0
            } else {
                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                let n = (d.abs() / step.max(1.0)).round() as u32;
                n.max(1)
            }
        };
        let axes = [
            (if dy > 0.0 { 5_u8 } else { 4 }, clicks(dy, step.1)),
            (if dx > 0.0 { 7_u8 } else { 6 }, clicks(dx, step.0)),
        ];
        for (button, n) in axes {
            for _ in 0..n {
                for type_ in [XT_BUTTON_PRESS, XT_BUTTON_RELEASE] {
                    self.conn
                        .xtest_fake_input(type_, button, CURRENT_TIME, self.root, 0, 0, 0)
                        .map_err(|e| EngineError::Other(format!("xtest wheel: {e}")))?
                        .ignore_error();
                }
            }
        }
        Ok(())
    }
}

impl InputDispatcher for XtestDispatcher {
    fn backend_name(&self) -> &'static str {
        "xtest"
    }
    fn dispatch(&self, ev: InputEvent) -> EngineResult<()> {
        let (type_, detail, root_x, root_y) = match ev {
            InputEvent::Move(p) => (XT_MOTION_NOTIFY, 0_u8, clamp_i16(p.x), clamp_i16(p.y)),
            InputEvent::Press(b) => (XT_BUTTON_PRESS, button_code(b), 0, 0),
            InputEvent::Release(b) => (XT_BUTTON_RELEASE, button_code(b), 0, 0),
            InputEvent::Wheel { dx, dy, step } => return self.wheel_clicks(dx, dy, step),
        };
        // FakeInput is fire-and-forget: ignore the void cookie's
        // error reply; any server-side error surfaces on the next
        // request anyway.
        self.conn
            .xtest_fake_input(type_, detail, CURRENT_TIME, self.root, root_x, root_y, 0)
            .map_err(|e| EngineError::Other(format!("xtest_fake_input: {e}")))?
            .ignore_error();
        Ok(())
    }
    fn flush(&self) -> EngineResult<()> {
        self.conn
            .flush()
            .map_err(|e| EngineError::Other(format!("XFlush: {e}")))?;
        // `sync` forces a round-trip so any deferred server error
        // surfaces here rather than on the next `cursor_op`.
        self.conn
            .sync()
            .map_err(|e| EngineError::Other(format!("XSync: {e}")))?;
        Ok(())
    }

    fn modifier(&self, keysym: u32, pressed: bool) -> EngineResult<()> {
        let keycode = match self.keycode_of(keysym)? {
            Some(k) => k,
            None => self.bind(keysym, &|d| std::thread::sleep(d))?,
        };
        let type_ = if pressed {
            XT_KEY_PRESS
        } else {
            XT_KEY_RELEASE
        };
        self.conn
            .xtest_fake_input(type_, keycode, CURRENT_TIME, self.root, 0, 0, 0)
            .map_err(|e| EngineError::Other(format!("xtest modifier: {e}")))?
            .ignore_error();
        Ok(())
    }

    fn key_down(&self, ch: char, settle: &dyn Fn(Duration)) -> EngineResult<()> {
        let keycode = self.bind(keysym_for(ch), settle)?;
        self.conn
            .xtest_fake_input(XT_KEY_PRESS, keycode, CURRENT_TIME, self.root, 0, 0, 0)
            .map_err(|e| EngineError::Other(format!("xtest key press: {e}")))?
            .ignore_error();
        self.flush()
    }

    fn key_up(&self, _ch: char) -> EngineResult<()> {
        // The binding from `key_down` is still in place, so the
        // release names the same keycode.
        let keycode = match *self.scratch.lock().unwrap() {
            Some(k) => k.keycode,
            None => return Ok(()),
        };
        self.conn
            .xtest_fake_input(XT_KEY_RELEASE, keycode, CURRENT_TIME, self.root, 0, 0, 0)
            .map_err(|e| EngineError::Other(format!("xtest key release: {e}")))?
            .ignore_error();
        self.flush()
    }

    fn end_typing(&self) -> EngineResult<()> {
        let mut guard = self.scratch.lock().unwrap();
        let Some(key) = guard.take() else {
            return Ok(());
        };
        // Hand the keycode back empty, the way it was found. Leaving
        // a stray binding behind would change what the user's own
        // keyboard does with that keycode for the rest of the session.
        let syms = vec![0_u32; usize::from(key.per_code)];
        self.conn
            .change_keyboard_mapping(1, key.keycode, key.per_code, &syms)
            .map_err(|e| EngineError::Other(format!("ChangeKeyboardMapping restore: {e}")))?
            .check()
            .map_err(|e| EngineError::Other(format!("ChangeKeyboardMapping restore check: {e}")))?;
        Ok(())
    }

    fn focus_pointer_window(&self) {
        // X routes keys by focus, not by pointer position, and a
        // headless session under xvfb has no window manager to set
        // focus for us. The caller has just clicked to place the
        // caret, so the window under the pointer is the one that
        // should hear the typing. Entirely best-effort: on a session
        // that does have a WM, focus is already where it belongs.
        let Ok(reply) = self.conn.query_pointer(self.root) else {
            return;
        };
        let Ok(reply) = reply.reply() else { return };
        if reply.child == x11rb::NONE {
            return;
        }
        if let Ok(cookie) = self
            .conn
            .set_input_focus(InputFocus::PARENT, reply.child, CURRENT_TIME)
        {
            cookie.ignore_error();
        }
        let _ = self.conn.flush();
    }

    fn raise_window(&self, title: &str) {
        // Without a window manager every host window is a direct child
        // of the root, stacked in the order it was mapped. Find ours by
        // its _NET_WM_NAME (GTK sets it from the title) and restack it.
        let Some(win) = self.find_titled(title) else {
            return;
        };
        let aux = ConfigureWindowAux::new().stack_mode(StackMode::ABOVE);
        if let Ok(cookie) = self.conn.configure_window(win, &aux) {
            cookie.ignore_error();
        }
        let _ = self.conn.sync();
    }

    fn screen_size(&self) -> Option<(i32, i32)> {
        let screen = self.conn.setup().roots.first()?;
        Some((
            i32::from(screen.width_in_pixels),
            i32::from(screen.height_in_pixels),
        ))
    }

    fn place_window(&self, title: &str, x: i32, y: i32) -> bool {
        let Some(win) = self.find_titled(title) else {
            return false;
        };
        let aux = ConfigureWindowAux::new().x(x).y(y);
        if let Ok(cookie) = self.conn.configure_window(win, &aux) {
            cookie.ignore_error();
        }
        self.conn.sync().is_ok()
    }

    fn x11_window(&self, title: &str) -> Option<u32> {
        self.find_titled(title)
    }

    fn window_origin(&self, title: &str) -> Option<(i32, i32)> {
        let win = self.find_titled(title)?;
        let r = self
            .conn
            .translate_coordinates(win, self.root, 0, 0)
            .ok()?
            .reply()
            .ok()?;
        Some((i32::from(r.dst_x), i32::from(r.dst_y)))
    }

    fn use_page_pointer(&self, title: &str) {
        // XTest's core events move the pointer (and type on the
        // keyboard) of the client's ClientPointer, so pointing this
        // connection at the page's own master pair routes everything
        // after it there: its own position, hover state and focus.
        let Some(id) = self.page_pointer(title) else {
            return;
        };
        if let Ok(cookie) = self.conn.xinput_xi_set_client_pointer(x11rb::NONE, id) {
            cookie.ignore_error();
        }
        let _ = self.conn.sync();
    }

    fn use_core_pointer(&self) {
        if !self.xi2 {
            return;
        }
        // Device 2 is always the core ("Virtual core") pointer.
        if let Ok(cookie) = self.conn.xinput_xi_set_client_pointer(x11rb::NONE, 2_u16) {
            cookie.ignore_error();
        }
        let _ = self.conn.sync();
    }

    fn drop_page_pointer(&self, title: &str) {
        // Kept, not removed: removing a master device while GTK runs
        // crashes it. Parked out of the way; the next page this daemon
        // opens takes it.
        let freed = self.pointers.lock().ok().and_then(|mut pool| {
            let id = pool.assigned.remove(title)?;
            pool.free.push(id);
            Some(id)
        });
        if let Some(id) = freed {
            self.park(id);
            self.use_core_pointer();
        }
    }
}

impl XtestDispatcher {
    /// The page's own master pointer: the one it already has, one this
    /// daemon holds free, or a claimed one. Pointer k is named
    /// `vs-ptr-<k>` and claimed by owning the `VS_PTR_<k>` selection;
    /// the server drops the claim when the daemon exits, so a later
    /// daemon reuses the device instead of adding another (devices are
    /// never removed; see `drop_page_pointer`).
    fn page_pointer(&self, title: &str) -> Option<u16> {
        if !self.xi2 {
            return None;
        }
        let mut pool = self.pointers.lock().ok()?;
        if let Some(&id) = pool.assigned.get(title) {
            return Some(id);
        }
        let id = match pool.free.pop() {
            Some(id) => id,
            None => self.claim_pointer()?,
        };
        pool.assigned.insert(title.to_string(), id);
        Some(id)
    }

    /// Claim the first pointer no live daemon holds, making it if it
    /// does not exist yet.
    fn claim_pointer(&self) -> Option<u16> {
        for k in 0..256 {
            let atom = self
                .conn
                .intern_atom(false, format!("VS_PTR_{k}").as_bytes())
                .ok()?
                .reply()
                .ok()?
                .atom;
            let owner = self
                .conn
                .get_selection_owner(atom)
                .ok()?
                .reply()
                .ok()?
                .owner;
            if owner != x11rb::NONE {
                continue;
            }
            self.conn
                .set_selection_owner(self.claim_window, atom, CURRENT_TIME)
                .ok()?;
            // Another daemon may have claimed it in between.
            let owner = self
                .conn
                .get_selection_owner(atom)
                .ok()?
                .reply()
                .ok()?
                .owner;
            if owner != self.claim_window {
                continue;
            }
            let name = format!("vs-ptr-{k}");
            return self.master_named(&name).or_else(|| self.add_master(&name));
        }
        None
    }

    /// The id of the master pointer `<name> pointer`, if it exists.
    fn master_named(&self, name: &str) -> Option<u16> {
        let want = format!("{name} pointer");
        let devices = self
            .conn
            .xinput_xi_query_device(xinput::Device::ALL_MASTER)
            .ok()?
            .reply()
            .ok()?;
        devices
            .infos
            .iter()
            .find(|d| d.type_ == xinput::DeviceType::MASTER_POINTER && d.name == want.as_bytes())
            .map(|d| d.deviceid)
    }

    /// Add a master pointer and keyboard pair named `name`.
    fn add_master(&self, title: &str) -> Option<u16> {
        let name = title.as_bytes().to_vec();
        // Length in 4-byte units: an 8-byte header, then the name
        // padded to a multiple of four.
        let len = u16::try_from((8 + name.len().div_ceil(4) * 4) / 4).ok()?;
        let change = xinput::HierarchyChange {
            len,
            data: xinput::HierarchyChangeData::AddMaster(xinput::HierarchyChangeDataAddMaster {
                send_core: true,
                enable: true,
                name,
            }),
        };
        self.conn
            .xinput_xi_change_hierarchy(&[change])
            .ok()?
            .check()
            .ok()?;
        // The server names the pair "<name> pointer" / "<name> keyboard".
        self.master_named(title)
    }
}

impl XtestDispatcher {
    /// The top-level window titled `title`. Remembered once found: a
    /// lookup walks every top-level window's name, a round trip each.
    fn find_titled(&self, title: &str) -> Option<Window> {
        let cached = self.windows.lock().ok()?.get(title).copied();
        // Still that window: a closed page's id may since name another.
        if let Some(w) = cached.filter(|&w| self.titled_as(w, title)) {
            return Some(w);
        }
        let found = self.scan_titled(title)?;
        if let Ok(mut m) = self.windows.lock() {
            m.insert(title.to_string(), found);
        }
        Some(found)
    }

    fn scan_titled(&self, title: &str) -> Option<Window> {
        let tree = self.conn.query_tree(self.root).ok()?.reply().ok()?;
        tree.children
            .into_iter()
            .rev()
            .find(|&w| self.titled_as(w, title))
    }

    /// Whether window `w` is named `title` (_NET_WM_NAME, which GTK sets
    /// from the title, else WM_NAME).
    fn titled_as(&self, w: Window, title: &str) -> bool {
        let (net_wm_name, utf8) = self.name_atoms;
        let name = |prop, ty| {
            self.conn
                .get_property(false, w, prop, ty, 0, 256)
                .ok()
                .and_then(|c| c.reply().ok())
                .map(|r| r.value)
        };
        name(net_wm_name, utf8)
            .filter(|v| !v.is_empty())
            .or_else(|| name(AtomEnum::WM_NAME.into(), AtomEnum::STRING.into()))
            .is_some_and(|v| v == title.as_bytes())
    }
}

/// The X keysym that produces `ch`.
///
/// Latin-1 is the one range where keysyms and Unicode agree by
/// historical accident, so it passes through. Everything else uses the
/// Unicode escape range the X protocol reserves for exactly this. The
/// few control characters worth typing have named keysyms and no
/// printable form, so they are spelled out.
fn keysym_for(ch: char) -> u32 {
    match ch {
        '\u{8}' => 0xff08,     // BackSpace
        '\t' => 0xff09,        // Tab
        '\n' | '\r' => 0xff0d, // Return
        '\u{1b}' => 0xff1b,    // Escape
        _ => {
            let cp = ch as u32;
            if (0x20..=0x7e).contains(&cp) || (0xa0..=0xff).contains(&cp) {
                cp
            } else {
                0x0100_0000 + cp
            }
        }
    }
}

#[allow(clippy::cast_possible_truncation)]
fn clamp_i16(v: i32) -> i16 {
    v.clamp(i32::from(i16::MIN), i32::from(i16::MAX)) as i16
}

fn button_code(b: Button) -> u8 {
    // X11 button numbering: 1=left, 2=middle, 3=right.
    match b {
        Button::Left => 1,
        Button::Middle => 2,
        Button::Right => 3,
    }
}

// =============================================================================
// libei backend (xdg-desktop-portal RemoteDesktop + ashpd)
// =============================================================================
//
// We don't talk to libei directly — `ashpd`'s `RemoteDesktop` portal
// exposes `notify_pointer_motion_absolute` and `notify_pointer_button`
// as D-Bus methods, which the compositor delivers to focused windows
// as trusted hardware input. This is the recommended path for
// non-interactive applications on modern Wayland sessions (GNOME 41+,
// KDE Plasma 5.27+, sway via wlroots-virtual-pointer).
//
// We park a current-thread tokio runtime on a dedicated thread, run
// the portal session there, and `block_on` for every `dispatch` call.
// The portal session lifecycle (create_session → select_devices →
// start) happens once at process startup; the user sees a one-time
// permission prompt from their compositor. Successive `dispatch`
// calls are cheap D-Bus method calls.

use ashpd::desktop::remote_desktop::{DeviceType, RemoteDesktop};
use ashpd::desktop::{PersistMode, Session};
use enumflags2::BitFlags;
use std::sync::mpsc;

/// libei (xdg-desktop-portal RemoteDesktop) dispatcher.
struct LibeiDispatcher {
    /// Channel into the dedicated portal-session thread. Owned
    /// `tokio` runtime stays on that thread; we don't move it.
    cmd_tx: mpsc::Sender<LibeiCmd>,
}

enum LibeiCmd {
    Motion {
        x: f64,
        y: f64,
        ack: mpsc::Sender<EngineResult<()>>,
    },
    Button {
        code: u32,
        pressed: bool,
        ack: mpsc::Sender<EngineResult<()>>,
    },
    Keysym {
        keysym: i32,
        pressed: bool,
        ack: mpsc::Sender<EngineResult<()>>,
    },
    Axis {
        dx: f64,
        dy: f64,
        ack: mpsc::Sender<EngineResult<()>>,
    },
}

impl LibeiDispatcher {
    fn try_new() -> Option<Self> {
        let (cmd_tx, cmd_rx) = mpsc::channel::<LibeiCmd>();
        let (init_tx, init_rx) = mpsc::sync_channel::<Option<()>>(1);
        std::thread::Builder::new()
            .name("vs-libei".to_string())
            .spawn(move || {
                let Ok(rt) = tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                else {
                    let _ = init_tx.send(None);
                    return;
                };
                rt.block_on(async move {
                    let Ok(proxy) = RemoteDesktop::new().await else {
                        let _ = init_tx.send(None);
                        return;
                    };
                    let Ok(session): Result<Session<'_, RemoteDesktop>, _> =
                        proxy.create_session().await
                    else {
                        let _ = init_tx.send(None);
                        return;
                    };
                    // Ask for a keyboard as well as a pointer. The
                    // portal grants devices per session, so a session
                    // opened for the pointer alone cannot type later.
                    let types: BitFlags<DeviceType> = DeviceType::Pointer | DeviceType::Keyboard;
                    if proxy
                        .select_devices(&session, types, None, PersistMode::DoNot)
                        .await
                        .and_then(|r| r.response())
                        .is_err()
                    {
                        let _ = init_tx.send(None);
                        return;
                    }
                    // `start` triggers the compositor's consent prompt
                    // (one-time, per session) and blocks until the
                    // user approves or denies.
                    if proxy
                        .start(&session, None)
                        .await
                        .and_then(|r| r.response())
                        .is_err()
                    {
                        let _ = init_tx.send(None);
                        return;
                    }
                    let _ = init_tx.send(Some(()));
                    while let Ok(cmd) = cmd_rx.recv() {
                        match cmd {
                            LibeiCmd::Motion { x, y, ack } => {
                                let r = proxy
                                    .notify_pointer_motion_absolute(&session, 0, x, y)
                                    .await
                                    .map_err(|e| EngineError::Other(format!("ei motion: {e}")));
                                let _ = ack.send(r);
                            }
                            LibeiCmd::Keysym {
                                keysym,
                                pressed,
                                ack,
                            } => {
                                let state = if pressed {
                                    ashpd::desktop::remote_desktop::KeyState::Pressed
                                } else {
                                    ashpd::desktop::remote_desktop::KeyState::Released
                                };
                                // The portal takes a keysym directly,
                                // so the compositor does the keymap
                                // work the XTest path has to do by
                                // hand.
                                let r = proxy
                                    .notify_keyboard_keysym(&session, keysym, state)
                                    .await
                                    .map_err(|e| EngineError::Other(format!("ei keysym: {e}")));
                                let _ = ack.send(r);
                            }
                            LibeiCmd::Axis { dx, dy, ack } => {
                                let r = proxy
                                    .notify_pointer_axis(&session, dx, dy, true)
                                    .await
                                    .map_err(|e| EngineError::Other(format!("ei axis: {e}")));
                                let _ = ack.send(r);
                            }
                            LibeiCmd::Button { code, pressed, ack } => {
                                let state = if pressed {
                                    ashpd::desktop::remote_desktop::KeyState::Pressed
                                } else {
                                    ashpd::desktop::remote_desktop::KeyState::Released
                                };
                                #[allow(clippy::cast_possible_wrap)]
                                let r = proxy
                                    .notify_pointer_button(&session, code as i32, state)
                                    .await
                                    .map_err(|e| EngineError::Other(format!("ei button: {e}")));
                                let _ = ack.send(r);
                            }
                        }
                    }
                });
            })
            .ok()?;
        // Block on the portal handshake completing. If the compositor
        // doesn't have a RemoteDesktop portal, or the user denies,
        // the worker thread returns None and we fall through to XTest.
        init_rx.recv().ok().flatten()?;
        Some(Self { cmd_tx })
    }
}

impl InputDispatcher for LibeiDispatcher {
    fn backend_name(&self) -> &'static str {
        "libei"
    }
    fn dispatch(&self, ev: InputEvent) -> EngineResult<()> {
        let (ack_tx, ack_rx) = mpsc::channel();
        let cmd = match ev {
            InputEvent::Move(p) => LibeiCmd::Motion {
                x: f64::from(p.x),
                y: f64::from(p.y),
                ack: ack_tx,
            },
            InputEvent::Press(b) => LibeiCmd::Button {
                code: linux_button_code(b),
                pressed: true,
                ack: ack_tx,
            },
            InputEvent::Release(b) => LibeiCmd::Button {
                code: linux_button_code(b),
                pressed: false,
                ack: ack_tx,
            },
            InputEvent::Wheel { dx, dy, .. } => LibeiCmd::Axis {
                dx,
                dy,
                ack: ack_tx,
            },
        };
        self.cmd_tx
            .send(cmd)
            .map_err(|_| EngineError::Other("libei worker thread gone".into()))?;
        ack_rx
            .recv()
            .map_err(|_| EngineError::Other("libei ack channel closed".into()))?
    }
    fn flush(&self) -> EngineResult<()> {
        Ok(())
    }

    fn key_down(&self, ch: char, _settle: &dyn Fn(Duration)) -> EngineResult<()> {
        self.keysym(ch, true)
    }

    fn key_up(&self, ch: char) -> EngineResult<()> {
        self.keysym(ch, false)
    }

    fn modifier(&self, keysym: u32, pressed: bool) -> EngineResult<()> {
        let (ack_tx, ack_rx) = mpsc::channel();
        #[allow(clippy::cast_possible_wrap)]
        self.cmd_tx
            .send(LibeiCmd::Keysym {
                keysym: keysym as i32,
                pressed,
                ack: ack_tx,
            })
            .map_err(|_| EngineError::Other("libei worker thread gone".into()))?;
        ack_rx
            .recv()
            .map_err(|_| EngineError::Other("libei ack channel closed".into()))?
    }
}

impl LibeiDispatcher {
    fn keysym(&self, ch: char, pressed: bool) -> EngineResult<()> {
        let (ack_tx, ack_rx) = mpsc::channel();
        #[allow(clippy::cast_possible_wrap)]
        let keysym = keysym_for(ch) as i32;
        self.cmd_tx
            .send(LibeiCmd::Keysym {
                keysym,
                pressed,
                ack: ack_tx,
            })
            .map_err(|_| EngineError::Other("libei worker thread gone".into()))?;
        ack_rx
            .recv()
            .map_err(|_| EngineError::Other("libei ack channel closed".into()))?
    }
}

/// Linux input subsystem button codes (`linux/input-event-codes.h`).
/// `BTN_LEFT` = 0x110, `BTN_MIDDLE` = 0x112, `BTN_RIGHT` = 0x111. The
/// RemoteDesktop portal expects these, not the X11 1/2/3 numbering.
fn linux_button_code(b: Button) -> u32 {
    match b {
        Button::Left => 0x110,
        Button::Middle => 0x112,
        Button::Right => 0x111,
    }
}