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
use anyhow::{Context, Result};
use async_trait::async_trait;
use evdev::{
uinput, AbsInfo, AbsoluteAxisType, AttributeSet, EvdevEnum, InputEventKind, Key, MiscType,
RelativeAxisType,
};
use tracing::{debug, info, trace, warn};
use crate::device::output::{OutputHandler, VIRTUAL_DEVICE_NAME_PREFIX};
use crate::device::util;
use crate::msgs::event;
pub const SCALED_DIM_MIN: i32 = 0;
pub const SCALED_DIM_MAX: i32 = 65535;
pub const SCALED_DIM_RES_X: i32 = 640; // 65536 / 640 = 102.4mm
pub const SCALED_DIM_RES_Y: i32 = 960; // for a 3/2 ratio vs X: 65536 / 960 = 68.3mm
/// Creates virtual uinput devices on the client machine and emits input events locally.
pub struct VirtualUInputDevices {
keyboard_keys: AttributeSet<Key>,
mouse_keys: AttributeSet<Key>,
touchpad_keys: AttributeSet<Key>,
mouse_axes: AttributeSet<RelativeAxisType>,
touchpad_axes: AttributeSet<AbsoluteAxisType>,
keyboard_misc: AttributeSet<MiscType>,
mouse_misc: AttributeSet<MiscType>,
touchpad_misc: AttributeSet<MiscType>,
keyboard_device: uinput::VirtualDevice,
mouse_device: uinput::VirtualDevice,
touchpad_device: uinput::VirtualDevice,
}
impl VirtualUInputDevices {
pub fn new() -> Result<VirtualUInputDevices> {
let pid = std::process::id();
let (keyboard_device, keyboard_keys, keyboard_misc) =
keyboard(pid).context("Failed to create virtual keyboard for simulated output")?;
let (mouse_device, mouse_keys, mouse_misc, mouse_axes) =
mouse(pid).context("Failed to create virtual mouse for simulated output")?;
let (touchpad_device, touchpad_keys, touchpad_misc, touchpad_axes) =
touchpad(pid).context("Failed to create virtual touchpad for simulated output")?;
debug!(
"Event->device routing:
keyboard_keys: {:?}
mouse_keys: {:?}
touchpad_keys: {:?}
mouse_axes: {:?}
touchpad_axes: {:?}
keyboard_misc: {:?}
mouse_misc: {:?}
touchpad_misc: {:?}",
keyboard_keys,
mouse_keys,
touchpad_keys,
mouse_axes,
touchpad_axes,
keyboard_misc,
mouse_misc,
touchpad_misc
);
let ret = VirtualUInputDevices {
keyboard_keys,
mouse_keys,
touchpad_keys,
mouse_axes,
touchpad_axes,
keyboard_misc,
mouse_misc,
touchpad_misc,
keyboard_device,
mouse_device,
touchpad_device,
};
info!("Created virtual uinput devices: keyboard, mouse, touchpad");
Ok(ret)
}
fn route_event(&self, event: evdev::InputEvent) -> Option<EventDest> {
match event.kind() {
InputEventKind::Key(e) => {
if self.keyboard_keys.contains(e) {
Some(EventDest::Keyboard)
} else if self.mouse_keys.contains(e) {
// mouse_keys and touchpad_keys have a lot of BTN_* key overlap
if self.touchpad_keys.contains(e) {
Some(EventDest::MouseOrTouchpad)
} else {
Some(EventDest::Mouse)
}
} else if self.touchpad_keys.contains(e) {
Some(EventDest::Touchpad)
} else {
info!("Dropping key event with unsupported code: {:?}", e);
None
}
}
InputEventKind::RelAxis(e) => {
if self.mouse_axes.contains(e) {
Some(EventDest::Mouse)
} else {
info!("Dropping relaxis event with unsupported code: {:?}", e);
None
}
}
InputEventKind::AbsAxis(e) => {
if self.touchpad_axes.contains(e) {
Some(EventDest::Touchpad)
} else {
info!("Dropping absaxis event with unsupported code: {:?}", e);
None
}
}
InputEventKind::Misc(e) => {
if self.keyboard_misc.contains(e) {
// keyboard_misc and mouse_misc have MSC_SCAN overlap
if self.mouse_misc.contains(e) {
Some(EventDest::KeyboardOrMouse)
} else {
Some(EventDest::Keyboard)
}
} else if self.mouse_misc.contains(e) {
Some(EventDest::Mouse)
} else if self.touchpad_misc.contains(e) {
Some(EventDest::Touchpad)
} else {
info!("Dropping misc event with unsupported code: {:?}", e);
None
}
}
_ => {
info!("Dropping event with unsupported type: {:?}", event);
None
}
}
}
}
#[derive(PartialEq)]
enum EventDest {
Keyboard,
Mouse,
Touchpad,
KeyboardOrMouse,
MouseOrTouchpad,
}
#[async_trait]
impl OutputHandler for VirtualUInputDevices {
async fn write(&mut self, events: Vec<event::InputEvent>) -> Result<()> {
let events = events
.iter()
.filter_map(|event| {
if let Some(e) = &event.inputf64 {
let evdev_event = e.to_evdev(SCALED_DIM_MIN, SCALED_DIM_MAX);
if let Some(dest) = self.route_event(evdev_event) {
Some((evdev_event, dest))
} else {
None
}
} else if let Some(e) = &event.inputi32 {
let evdev_event = e.to_evdev();
if let Some(dest) = self.route_event(evdev_event) {
Some((evdev_event, dest))
} else {
None
}
} else {
warn!("Event missing either an i32 or an f64 value: {}", event);
None
}
})
.collect::<Vec<(evdev::InputEvent, EventDest)>>();
if events.is_empty() {
return Ok(());
}
// Collect stats on how many events apply to each device
// We specifically avoid grouping the events themselves so that ordering is preserved
let mut keyboard_count = 0;
let mut mouse_count = 0;
let mut touchpad_count = 0;
for e in &events {
match e.1 {
EventDest::Keyboard => {
keyboard_count += 1;
}
EventDest::Mouse => {
mouse_count += 1;
}
EventDest::Touchpad => {
touchpad_count += 1;
}
EventDest::KeyboardOrMouse => {
keyboard_count += 1;
mouse_count += 1;
}
EventDest::MouseOrTouchpad => {
mouse_count += 1;
touchpad_count += 1;
}
}
}
// Route the events according to the count stats.
// The events should be single-device in most cases, but we support mixed events too, just in case.
if keyboard_count == events.len() {
// All of the events can be classified as keyboard
let events = events
.iter()
.map(|e| e.0)
.collect::<Vec<evdev::InputEvent>>();
trace!(
"Emitting {} keyboard events: {:?}",
events.len(),
events
.iter()
.map(|e| util::log_event(e))
.collect::<Vec<String>>()
);
self.keyboard_device.emit(&events)?;
} else if mouse_count == events.len() {
// All of the events can be classified as mouse
let events = events
.iter()
.map(|e| e.0)
.collect::<Vec<evdev::InputEvent>>();
trace!(
"Emitting {} mouse events: {:?}",
events.len(),
events
.iter()
.map(|e| util::log_event(e))
.collect::<Vec<String>>()
);
self.mouse_device.emit(&events)?;
} else if touchpad_count == events.len() {
// All of the events can be classified as touchpad
let events = events
.iter()
.map(|e| e.0)
.collect::<Vec<evdev::InputEvent>>();
trace!(
"Emitting {} touchpad events: {:?}",
events.len(),
events
.iter()
.map(|e| util::log_event(e))
.collect::<Vec<String>>()
);
self.touchpad_device.emit(&events)?;
} else {
// Events don't all 'fit' in one device, group by device
let mut keyboard_events = vec![];
let mut mouse_events = vec![];
let mut touchpad_events = vec![];
for event in &events {
match event.1 {
EventDest::Keyboard => {
keyboard_events.push(event.0);
}
EventDest::Mouse => {
mouse_events.push(event.0);
}
EventDest::Touchpad => {
touchpad_events.push(event.0);
}
EventDest::KeyboardOrMouse => {
// Arbitrarily pick whichever device has the most events
// For example, if the batch is a mix of keyboard and touchpad events,
// then this lets us keep the keyboard-or-mouse events with the keyboard.
if keyboard_count >= mouse_count {
keyboard_events.push(event.0);
} else {
mouse_events.push(event.0);
}
}
EventDest::MouseOrTouchpad => {
// Arbitrarily pick whichever device has the most events
// For example, if the batch is a mix of keyboard and touchpad events,
// then this lets us keep the mouse-or-touchpad events with the touchpad.
if mouse_count >= touchpad_count {
mouse_events.push(event.0);
} else {
touchpad_events.push(event.0);
}
}
}
}
trace!(
"Emitting events: keyboard({})={:?} mouse({})={:?} touchpad({})={:?}",
keyboard_events.len(),
keyboard_events
.iter()
.map(|e| util::log_event(e))
.collect::<Vec<String>>(),
mouse_events.len(),
mouse_events
.iter()
.map(|e| util::log_event(e))
.collect::<Vec<String>>(),
touchpad_events.len(),
touchpad_events
.iter()
.map(|e| util::log_event(e))
.collect::<Vec<String>>(),
);
if !keyboard_events.is_empty() {
info!("emit keeb: {:?}", keyboard_events);
self.keyboard_device.emit(&keyboard_events)?;
}
if !mouse_events.is_empty() {
self.mouse_device.emit(&mouse_events)?;
}
if !touchpad_events.is_empty() {
self.touchpad_device.emit(&touchpad_events)?;
}
}
Ok(())
}
}
pub fn keyboard(
pid: u32,
) -> Result<(
uinput::VirtualDevice,
AttributeSet<Key>,
AttributeSet<MiscType>,
)> {
let mut keys = AttributeSet::<Key>::new();
// Report as many keys as possible to emit by the virtual device.
for code in 1..libc::KEY_MAX {
let key = Key::new(code);
// HACK: Include only known KEY_* keys, or else the keyboard will be ignored.
let key_name = format!("{:?}", key);
if key_name.starts_with("KEY_") {
keys.insert(key);
}
}
let device = uinput::VirtualDeviceBuilder::new()?
.name(format!("{} keyboard for pid {}", VIRTUAL_DEVICE_NAME_PREFIX, pid).as_str())
.with_keys(&keys)?
.build()?;
// We don't seem to need to advertise this, but mark it as a possible event so that we aren't dropping it and logging infos about it.
let mut misc = AttributeSet::<MiscType>::new();
misc.insert(MiscType::MSC_SCAN);
Ok((device, keys, misc))
}
pub fn mouse(
pid: u32,
) -> Result<(
uinput::VirtualDevice,
AttributeSet<Key>,
AttributeSet<MiscType>,
AttributeSet<RelativeAxisType>,
)> {
let mut keys = AttributeSet::<Key>::new();
for code in 1..libc::KEY_MAX {
let key = Key::new(code);
// HACK: Include only BTN_* keys, and exclude BTN_TOOL_* or else the mouse is ignored.
let key_name = format!("{:?}", key);
if key_name.starts_with("BTN_") && !key_name.starts_with("BTN_TOOL_") {
keys.insert(key);
}
}
// Claim ALL axes. The mouse will be ignored if it claims keys that aren't relevant to claimed axes.
let mut axes = AttributeSet::<RelativeAxisType>::new();
for code in 0..(libc::REL_CNT as u16) {
axes.insert(RelativeAxisType(code));
}
let device = uinput::VirtualDeviceBuilder::new()?
.name(format!("{} mouse for pid {}", VIRTUAL_DEVICE_NAME_PREFIX, pid).as_str())
.with_keys(&keys)?
.with_relative_axes(&axes)?
.build()?;
// We don't seem to need to advertise this, but mark it as a possible event so that we aren't dropping it and logging infos about it.
let mut misc = AttributeSet::<MiscType>::new();
misc.insert(MiscType::MSC_SCAN);
Ok((device, keys, misc, axes))
}
pub fn touchpad(
pid: u32,
) -> Result<(
uinput::VirtualDevice,
AttributeSet<Key>,
AttributeSet<MiscType>,
AttributeSet<AbsoluteAxisType>,
)> {
let mut props = AttributeSet::<evdev::PropType>::new();
// Doesn't seem to be required, but real touchpads have it:
props.insert(evdev::PropType::BUTTONPAD);
// Required for movement events to be recognized:
props.insert(evdev::PropType::POINTER);
let mut keys = AttributeSet::<Key>::new();
for code in 1..libc::KEY_MAX {
let key = Key::new(code);
// HACK: Limit to only (most) BTN_* keys or else the device won't work.
let key_name = format!("{:?}", key);
if key_name.starts_with("BTN_")
// If one of these keys is present, libinput will classify the device as an ID_INPUT_TABLET,
// rather than as an ID_INPUT_TOUCHPAD. See also: "sudo libinput record /dev/input/eventNN"
&& key_name != "BTN_TOOL_PEN"
&& key_name != "BTN_STYLUS"
&& key_name != "BTN_STYLUS2"
{
keys.insert(key);
}
}
let mut misc = AttributeSet::<MiscType>::new();
misc.insert(MiscType::MSC_TIMESTAMP);
let name = format!(
"{} multi touchpad for pid {}",
VIRTUAL_DEVICE_NAME_PREFIX, pid
);
// These are the valid axes that util::axis_scale_type returns DISCRETE
let mut axis_codes = AttributeSet::<AbsoluteAxisType>::new();
let mut axes = vec![
abs_axis(
AbsoluteAxisType::ABS_MISC,
-1, // min
1048576, // max (arbitrarily big in case some real device uses big values?)
0, // res
&mut axis_codes,
),
abs_axis(
AbsoluteAxisType::ABS_MT_SLOT,
0, // min
32, // max (if this is too big then something panics)
0, // res
&mut axis_codes,
),
abs_axis(
AbsoluteAxisType::ABS_MT_TOOL_TYPE,
0, // min
4095, // max
0, // res
&mut axis_codes,
),
abs_axis(
AbsoluteAxisType::ABS_MT_BLOB_ID,
-1, // min
1048576, // max (arbitrarily big in case some real device uses big IDs)
0, // res
&mut axis_codes,
),
abs_axis(
AbsoluteAxisType::ABS_MT_TRACKING_ID,
-1, // min
1048576, // max (arbitrarily big in case some real device uses big IDs)
0, // res
&mut axis_codes,
),
];
for i in 0..libc::ABS_MAX + 1 {
let axis = AbsoluteAxisType::from_index(i as usize);
match util::axis_scale_type(axis) {
util::AxisScale::X => {
// X axis values: use MAX_X
axes.push(abs_axis(
axis,
SCALED_DIM_MIN,
SCALED_DIM_MAX,
SCALED_DIM_RES_X,
&mut axis_codes,
));
axis_codes.insert(axis);
}
util::AxisScale::Y => {
// Y axis values: use MAX_Y
axes.push(abs_axis(
axis,
SCALED_DIM_MIN,
SCALED_DIM_MAX,
SCALED_DIM_RES_Y,
&mut axis_codes,
));
axis_codes.insert(axis);
}
util::AxisScale::Other => {
axes.push(abs_axis(
axis,
SCALED_DIM_MIN,
SCALED_DIM_MAX,
1,
&mut axis_codes,
));
axis_codes.insert(axis);
}
_ => {}
}
}
let mut device_builder = uinput::VirtualDeviceBuilder::new()?
.name(name.as_str())
.with_properties(&props)?
.with_keys(&keys)?
.with_msc(&misc)?;
for axis in &axes {
device_builder = device_builder.with_absolute_axis(axis)?;
}
let device = device_builder.build()?;
Ok((device, keys, misc, axis_codes))
}
fn abs_axis(
axis: AbsoluteAxisType,
min: i32,
max: i32,
res: i32,
codes: &mut AttributeSet<AbsoluteAxisType>,
) -> evdev::UinputAbsSetup {
codes.insert(axis);
evdev::UinputAbsSetup::new(
axis,
AbsInfo::new(
0, // value
min, // min
max, // max
0, // fuzz
0, // flat
res, // res
),
)
}