a7n-platform 0.43.1

Native desktop backends for the Apeirogon software KVM
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
// SPDX-License-Identifier: GPL-3.0-or-later

//! Capture thread: `XInput2` raw events plus keyboard/pointer grabs.

use std::io;
use std::ops::ControlFlow;
use std::thread;
use std::time::{Duration, Instant};

use a7n_proto::v1::{ButtonEvent, InputEvent, KeyEvent, ScrollEvent, ScrollUnit, input_event};
use rustix::event::{PollFd, PollFlags, Timespec, poll};
use rustix::io::Errno;
use tokio::sync::mpsc::error::{TryRecvError, TrySendError};
use tokio::sync::mpsc::{Receiver, Sender};
use x11rb::connection::Connection;
use x11rb::protocol::Event;
use x11rb::protocol::xfixes::{self, ConnectionExt as _};
use x11rb::protocol::xinput::{
    self, ConnectionExt as _, DeviceType, EventMask, KeyEventFlags, XIEventMask,
};
use x11rb::protocol::xproto::{ConnectionExt as _, GrabMode, GrabStatus};
use x11rb::rust_connection::RustConnection;
use x11rb::{CURRENT_TIME, NONE};

use super::buttons::{PointerButton, classify_x_button};
use super::keymap::hid_from_keycode;
use super::{Bounds, Session};
use crate::input::accumulate::MotionAccumulator;
use crate::input::{CaptureControl, Captured, DeadMan, InputError};

/// Longest wait on the X connection before control commands and the dead-man
/// switch are looked at again.
const WAKE_INTERVAL: Duration = Duration::from_millis(50);
/// `XInput2` pseudo device id selecting every master device.
const ALL_MASTER_DEVICES: u16 = 1;
const XI_MAJOR_VERSION: u16 = 2;
const XI_MINOR_VERSION: u16 = 0;
const XFIXES_MAJOR_VERSION: u32 = 4;
const XFIXES_MINOR_VERSION: u32 = 0;
/// Valuator numbers of the pointer's x and y axes.
const AXIS_X: u32 = 0;
const AXIS_Y: u32 = 1;
/// `XInput2` pseudo device id addressing every device, used for hierarchy events.
const ALL_DEVICES: u16 = 0;
/// Xorg names its XTEST slave devices "Virtual core XTEST pointer/keyboard".
const XTEST_DEVICE_NAME: &str = "XTEST";
const THREAD_NAME: &str = "a7n-x11-capture";

pub(super) struct CaptureThread {
    session: Session,
    motion: MotionAccumulator,
    deadman: DeadMan,
    grabbed: bool,
    cursor_hidden: bool,
    /// Slave devices fed by XTEST, i.e. our own injection.
    xtest_sources: Vec<u16>,
}

impl CaptureThread {
    pub(super) fn new(session: Session) -> Result<Self, InputError> {
        session.require_extension(xinput::X11_EXTENSION_NAME)?;
        session.require_extension(xfixes::X11_EXTENSION_NAME)?;
        let version = session
            .conn
            .xinput_xi_query_version(XI_MAJOR_VERSION, XI_MINOR_VERSION)?
            .reply()?;
        if version.major_version < XI_MAJOR_VERSION {
            return Err(InputError::MissingX11Extension("XInput 2.0"));
        }
        session
            .conn
            .xfixes_query_version(XFIXES_MAJOR_VERSION, XFIXES_MINOR_VERSION)?
            .reply()?;
        let hierarchy = EventMask {
            deviceid: ALL_DEVICES,
            mask: vec![XIEventMask::HIERARCHY],
        };
        let mask = EventMask {
            deviceid: ALL_MASTER_DEVICES,
            mask: vec![
                XIEventMask::RAW_MOTION
                    | XIEventMask::RAW_KEY_PRESS
                    | XIEventMask::RAW_KEY_RELEASE
                    | XIEventMask::RAW_BUTTON_PRESS
                    | XIEventMask::RAW_BUTTON_RELEASE,
            ],
        };
        session
            .conn
            .xinput_xi_select_events(session.root, &[mask, hierarchy])?
            .check()?;
        let xtest_sources = query_xtest_sources(&session.conn)?;
        Ok(Self {
            session,
            xtest_sources,
            motion: MotionAccumulator::default(),
            deadman: DeadMan::new(Instant::now()),
            grabbed: false,
            cursor_hidden: false,
        })
    }

    pub(super) fn bounds(&self) -> Bounds {
        self.session.bounds
    }

    pub(super) fn spawn(
        self,
        events: Sender<Captured>,
        control: Receiver<CaptureControl>,
    ) -> Result<(), InputError> {
        thread::Builder::new()
            .name(THREAD_NAME.to_owned())
            .spawn(move || self.run(&events, control))
            .map(drop)
            .map_err(InputError::Thread)
    }

    fn run(mut self, events: &Sender<Captured>, mut control: Receiver<CaptureControl>) {
        while self.step(events, &mut control).is_continue() {}
        // Whatever ended the loop, the local user gets the devices back.
        self.release();
        self.set_cursor_hidden(false);
    }

    fn step(
        &mut self,
        events: &Sender<Captured>,
        control: &mut Receiver<CaptureControl>,
    ) -> ControlFlow<()> {
        self.drain_events(events)?;
        self.drain_control(control)?;
        if (self.grabbed || self.cursor_hidden) && self.deadman.expired(Instant::now()) {
            self.release();
            self.set_cursor_hidden(false);
        }
        self.wait_readable()
    }

    fn drain_events(&mut self, events: &Sender<Captured>) -> ControlFlow<()> {
        loop {
            let event = match self.session.conn.poll_for_event() {
                Ok(Some(event)) => event,
                Ok(None) => return ControlFlow::Continue(()),
                Err(_) => return ControlFlow::Break(()),
            };
            let Ok(captured) = self.translate(&event) else {
                return ControlFlow::Break(());
            };
            if let Some(captured) = captured {
                // Never block here: a stalled daemon must not keep input grabbed,
                // so a full queue drops the event and the dead-man switch
                // still gets its turn. A closed queue means the daemon is gone.
                if let Err(TrySendError::Closed(_)) = events.try_send(captured) {
                    return ControlFlow::Break(());
                }
            }
        }
    }

    fn drain_control(&mut self, control: &mut Receiver<CaptureControl>) -> ControlFlow<()> {
        loop {
            match control.try_recv() {
                Ok(command) => self.apply(command),
                Err(TryRecvError::Empty) => return ControlFlow::Continue(()),
                Err(TryRecvError::Disconnected) => return ControlFlow::Break(()),
            }
        }
    }

    fn apply(&mut self, command: CaptureControl) {
        let now = Instant::now();
        match command {
            CaptureControl::LocalInputs(inputs) => drop(inputs),
            CaptureControl::CursorHidden(hidden) => {
                self.deadman.keepalive(now);
                self.set_cursor_hidden(hidden);
            }
            CaptureControl::Keepalive => self.deadman.keepalive(now),
            CaptureControl::Grab(true) => {
                // A grab request is itself proof that the daemon is alive.
                self.deadman.keepalive(now);
                self.grab();
            }
            CaptureControl::Grab(false) => self.release(),
        }
    }

    fn wait_readable(&self) -> ControlFlow<()> {
        let result = wait_for_input(&self.session.conn);
        match result {
            Ok(()) => ControlFlow::Continue(()),
            Err(_) => ControlFlow::Break(()),
        }
    }

    /// Raw events are not affected by grabs, so capture keeps working while
    /// local applications receive nothing.
    fn grab(&mut self) {
        if self.grabbed {
            return;
        }
        if self.try_grab().is_some() {
            self.grabbed = true;
            return;
        }
        // Never leave the local user half locked out.
        self.release();
        eprintln!("kind=input_grab_failed");
    }

    fn try_grab(&mut self) -> Option<()> {
        let conn = &self.session.conn;
        let root = self.session.root;
        let keyboard = conn
            .grab_keyboard(false, root, CURRENT_TIME, GrabMode::ASYNC, GrabMode::ASYNC)
            .ok()?
            .reply()
            .ok()?;
        (keyboard.status == GrabStatus::SUCCESS).then_some(())?;
        let pointer = conn
            .grab_pointer(
                false,
                root,
                x11rb::protocol::xproto::EventMask::NO_EVENT,
                GrabMode::ASYNC,
                GrabMode::ASYNC,
                NONE,
                NONE,
                CURRENT_TIME,
            )
            .ok()?
            .reply()
            .ok()?;
        (pointer.status == GrabStatus::SUCCESS).then_some(())?;
        conn.flush().ok()
    }

    /// Best effort: if the connection is already gone, the server releases
    /// grabs and the cursor by itself.
    fn release(&mut self) {
        let conn = &self.session.conn;
        let _ = conn.ungrab_keyboard(CURRENT_TIME);
        let _ = conn.ungrab_pointer(CURRENT_TIME);
        let _ = conn.flush();
        self.grabbed = false;
    }

    fn set_cursor_hidden(&mut self, hidden: bool) {
        if self.cursor_hidden == hidden {
            return;
        }
        let conn = &self.session.conn;
        let request = if hidden {
            conn.xfixes_hide_cursor(self.session.root)
        } else {
            conn.xfixes_show_cursor(self.session.root)
        };
        let result = request
            .map_err(InputError::from)
            .and_then(|cookie| cookie.check().map_err(InputError::from));
        match result {
            Ok(()) => self.cursor_hidden = hidden,
            Err(error) => eprintln!("kind=cursor_visibility_failed error={error}"),
        }
    }

    fn translate(&mut self, event: &Event) -> Result<Option<Captured>, x11rb::errors::ReplyError> {
        if let Event::XinputHierarchy(_) = event {
            self.xtest_sources = query_xtest_sources(&self.session.conn)?;
            return Ok(None);
        }
        if is_injected(&self.xtest_sources, source_id(event)) {
            return Ok(None);
        }
        match event {
            Event::XinputRawMotion(raw) => {
                let (dx, dy) = raw_axes(&raw.valuator_mask, &raw.axisvalues_raw);
                let (dx, dy) = self.motion.push(dx, dy);
                if dx == 0 && dy == 0 {
                    return Ok(None);
                }
                let (x, y) = self.session.pointer_position()?;
                Ok(Some(Captured::Pointer { x, y, dx, dy }))
            }
            Event::XinputRawKeyPress(raw) => {
                let repeat = raw.flags.contains(KeyEventFlags::KEY_REPEAT);
                Ok((!repeat).then(|| key(raw.detail, true)).flatten())
            }
            Event::XinputRawKeyRelease(raw) => Ok(key(raw.detail, false)),
            Event::XinputRawButtonPress(raw) => Ok(button(raw.detail, true)),
            Event::XinputRawButtonRelease(raw) => Ok(button(raw.detail, false)),
            _ => Ok(None),
        }
    }
}

/// Our own XTEST injection comes back as raw events; reporting it as local
/// activity would make a driven machine look like it is being used locally.
fn is_injected(xtest_sources: &[u16], source: Option<u16>) -> bool {
    source.is_some_and(|source| xtest_sources.contains(&source))
}

fn source_id(event: &Event) -> Option<u16> {
    match event {
        Event::XinputRawMotion(raw)
        | Event::XinputRawButtonPress(raw)
        | Event::XinputRawButtonRelease(raw) => Some(raw.sourceid),
        Event::XinputRawKeyPress(raw) | Event::XinputRawKeyRelease(raw) => Some(raw.sourceid),
        _ => None,
    }
}

fn query_xtest_sources(conn: &RustConnection) -> Result<Vec<u16>, x11rb::errors::ReplyError> {
    let devices = conn.xinput_xi_query_device(ALL_DEVICES)?.reply()?;
    Ok(devices
        .infos
        .iter()
        .filter(|info| {
            info.type_ == DeviceType::SLAVE_POINTER || info.type_ == DeviceType::SLAVE_KEYBOARD
        })
        .filter(|info| String::from_utf8_lossy(&info.name).contains(XTEST_DEVICE_NAME))
        .map(|info| info.deviceid)
        .collect())
}

fn wait_for_input(conn: &RustConnection) -> io::Result<()> {
    let timeout = Timespec::try_from(WAKE_INTERVAL).map_err(io::Error::other)?;
    let mut fds = [PollFd::new(conn.stream(), PollFlags::IN)];
    match poll(&mut fds, Some(&timeout)) {
        Ok(_) | Err(Errno::INTR) => Ok(()),
        Err(errno) => Err(errno.into()),
    }
}

/// Unaccelerated x and y of a raw event. `values` holds one entry per set bit
/// of `mask`, in valuator order.
fn raw_axes(mask: &[u32], values: &[xinput::Fp3232]) -> (f64, f64) {
    let (mut x, mut y) = (0.0, 0.0);
    let set_bits = mask.iter().enumerate().flat_map(|(word, bits)| {
        (0..u32::BITS)
            .filter(move |bit| bits & (1 << bit) != 0)
            .map(move |bit| word_axis(word, bit))
    });
    for (axis, value) in set_bits.zip(values) {
        let value = f64::from(value.integral) + f64::from(value.frac) / FRAC_SCALE;
        match axis {
            AXIS_X => x = value,
            AXIS_Y => y = value,
            _ => {}
        }
    }
    (x, y)
}

/// A `Fp3232` fraction is in units of 2^-32.
const FRAC_SCALE: f64 = 4_294_967_296.0;

fn word_axis(word: usize, bit: u32) -> u32 {
    u32::try_from(word)
        .unwrap_or(u32::MAX)
        .saturating_mul(u32::BITS)
        + bit
}

fn key(keycode: u32, down: bool) -> Option<Captured> {
    let usage = hid_from_keycode(keycode)?;
    Some(Captured::Input(InputEvent {
        event: Some(input_event::Event::Key(KeyEvent {
            usage,
            down,
            character: String::new(),
        })),
    }))
}

fn button(detail: u32, down: bool) -> Option<Captured> {
    let event = match classify_x_button(detail)? {
        PointerButton::Click(button) => input_event::Event::Button(ButtonEvent {
            button: button.into(),
            down,
        }),
        // A notch is one press; the release carries nothing.
        PointerButton::Scroll { .. } if !down => return None,
        PointerButton::Scroll { dx, dy } => input_event::Event::Scroll(ScrollEvent {
            dx: f32::from(dx),
            dy: f32::from(dy),
            unit: ScrollUnit::Line.into(),
        }),
    };
    Some(Captured::Input(InputEvent { event: Some(event) }))
}

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

    #[test]
    fn is_injected_xtest_source_dropped_real_source_kept() {
        // Arrange
        let xtest_sources = [4, 5];

        // Act
        let verdicts = [Some(4), Some(9), None].map(|source| is_injected(&xtest_sources, source));

        // Assert
        assert_eq!(verdicts, [true, false, false]);
    }
}