-
Notifications
You must be signed in to change notification settings - Fork 124
/
linux.rs
792 lines (734 loc) · 28.7 KB
/
linux.rs
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
//! Contains the input/output code for keyboards on Linux.
#![cfg_attr(feature = "simulated_output", allow(dead_code, unused_imports))]
pub use evdev::BusType;
use evdev::{uinput, Device, EventType, InputEvent, PropType, RelativeAxisType};
use inotify::{Inotify, WatchMask};
use mio::{unix::SourceFd, Events, Interest, Poll, Token};
use nix::ioctl_read_buf;
use rustc_hash::FxHashMap as HashMap;
use signal_hook::{
consts::{SIGINT, SIGTERM, SIGTSTP},
iterator::Signals,
};
use std::convert::TryFrom;
use std::fs;
use std::io;
use std::os::unix::io::AsRawFd;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::thread;
use super::*;
use crate::{kanata::CalculatedMouseMove, oskbd::KeyEvent};
use kanata_parser::cfg::DeviceDetectMode;
use kanata_parser::cfg::UnicodeTermination;
use kanata_parser::custom_action::*;
use kanata_parser::keys::*;
pub struct KbdIn {
devices: HashMap<Token, (Device, String)>,
/// Some(_) if devices are explicitly listed, otherwise None.
missing_device_paths: Option<Vec<String>>,
poll: Poll,
events: Events,
token_counter: usize,
/// stored to prevent dropping
_inotify: Inotify,
include_names: Option<Vec<String>>,
exclude_names: Option<Vec<String>>,
device_detect_mode: DeviceDetectMode,
}
const INOTIFY_TOKEN_VALUE: usize = 0;
const INOTIFY_TOKEN: Token = Token(INOTIFY_TOKEN_VALUE);
pub static WAIT_DEVICE_MS: AtomicU64 = AtomicU64::new(200);
impl KbdIn {
pub fn new(
dev_paths: &[String],
continue_if_no_devices: bool,
include_names: Option<Vec<String>>,
exclude_names: Option<Vec<String>>,
device_detect_mode: DeviceDetectMode,
) -> Result<Self, io::Error> {
let poll = Poll::new()?;
let mut missing_device_paths = None;
let devices = if !dev_paths.is_empty() {
missing_device_paths = Some(vec![]);
devices_from_input_paths(
dev_paths,
missing_device_paths.as_mut().expect("initialized"),
)
} else {
discover_devices(
include_names.as_deref(),
exclude_names.as_deref(),
device_detect_mode,
)
};
if devices.is_empty() {
if continue_if_no_devices {
log::warn!("no keyboard devices found; kanata is waiting");
} else {
return Err(io::Error::new(
io::ErrorKind::NotFound,
"No keyboard devices were found",
));
}
}
let _inotify = watch_devinput().map_err(|e| {
log::error!("failed to watch files: {e:?}");
e
})?;
poll.registry().register(
&mut SourceFd(&_inotify.as_raw_fd()),
INOTIFY_TOKEN,
Interest::READABLE,
)?;
let mut kbdin = Self {
poll,
missing_device_paths,
_inotify,
events: Events::with_capacity(32),
devices: HashMap::default(),
token_counter: INOTIFY_TOKEN_VALUE + 1,
include_names,
exclude_names,
device_detect_mode,
};
for (device, dev_path) in devices.into_iter() {
if let Err(e) = kbdin.register_device(device, dev_path.clone()) {
log::warn!("found device {dev_path} but could not register it {e:?}");
if let Some(ref mut missing) = kbdin.missing_device_paths {
missing.push(dev_path);
}
}
}
Ok(kbdin)
}
fn register_device(&mut self, mut dev: Device, path: String) -> Result<(), io::Error> {
log::info!("registering {path}: {:?}", dev.name().unwrap_or(""));
wait_for_all_keys_unpressed(&dev)?;
// NOTE: This grab-ungrab-grab sequence magically fixes an issue with a Lenovo Yoga
// trackpad not working. No idea why this works.
dev.grab()?;
dev.ungrab()?;
dev.grab()?;
let tok = Token(self.token_counter);
self.token_counter += 1;
let fd = dev.as_raw_fd();
self.poll
.registry()
.register(&mut SourceFd(&fd), tok, Interest::READABLE)?;
self.devices.insert(tok, (dev, path));
Ok(())
}
pub fn read(&mut self) -> Result<Vec<InputEvent>, io::Error> {
let mut input_events = vec![];
loop {
log::trace!("polling");
if let Err(e) = self.poll.poll(&mut self.events, None) {
log::error!("failed poll: {:?}", e);
return Ok(vec![]);
}
let mut do_rediscover = false;
for event in &self.events {
if let Some((device, _)) = self.devices.get_mut(&event.token()) {
if let Err(e) = device
.fetch_events()
.map(|evs| evs.into_iter().for_each(|ev| input_events.push(ev)))
{
// Currently the kind() is uncategorized... not helpful, need to match
// on os error (19)
match e.raw_os_error() {
Some(19) => {
self.poll
.registry()
.deregister(&mut SourceFd(&device.as_raw_fd()))?;
if let Some((_, path)) = self.devices.remove(&event.token()) {
log::warn!("removing kbd device: {path}");
if let Some(ref mut missing) = self.missing_device_paths {
missing.push(path);
}
}
}
_ => {
log::error!("failed fetch events due to {e}, kind: {}", e.kind());
return Err(e);
}
};
}
} else if event.token() == INOTIFY_TOKEN {
do_rediscover = true;
} else {
panic!("encountered unexpected epoll event {event:?}");
}
}
if do_rediscover {
log::info!("watch found file changes, looking for new devices");
self.rediscover_devices()?;
}
if !input_events.is_empty() {
return Ok(input_events);
}
}
}
fn rediscover_devices(&mut self) -> Result<(), io::Error> {
// This function is kinda ugly but the borrow checker doesn't like all this mutation.
let mut paths_registered = vec![];
if let Some(ref mut missing) = self.missing_device_paths {
if missing.is_empty() {
log::info!("no devices are missing, doing nothing");
return Ok(());
}
log::info!("checking for {missing:?}");
let discovered_devices = missing
.iter()
.filter_map(|dev_path| {
for _ in 0..(WAIT_DEVICE_MS.load(Ordering::SeqCst) / 10) {
// try a few times with waits in between; device might not be ready
if let Ok(device) = Device::open(dev_path) {
return Some((device, dev_path.clone()));
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
None
})
.collect::<Vec<(_, _)>>();
for (device, dev_path) in discovered_devices {
if let Err(e) = self.register_device(device, dev_path.clone()) {
log::warn!("found device {dev_path} but could not register it {e:?}");
} else {
paths_registered.push(dev_path);
}
}
}
if let Some(ref mut missing) = self.missing_device_paths {
missing.retain(|path| !paths_registered.contains(path));
} else {
log::info!("sleeping for a moment to let devices become ready");
std::thread::sleep(std::time::Duration::from_millis(
WAIT_DEVICE_MS.load(Ordering::SeqCst),
));
discover_devices(
self.include_names.as_deref(),
self.exclude_names.as_deref(),
self.device_detect_mode,
)
.into_iter()
.try_for_each(|(dev, path)| {
if !self
.devices
.values()
.any(|(_, registered_path)| &path == registered_path)
{
self.register_device(dev, path)
} else {
Ok(())
}
})?;
}
Ok(())
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
enum DeviceType {
Keyboard,
KeyboardMouse,
Mouse,
Other,
}
pub fn is_input_device(device: &Device, detect_mode: DeviceDetectMode) -> bool {
use evdev::Key;
if device.name() == Some("kanata") {
return false;
}
let is_keyboard = device
.supported_keys()
.map_or(false, |keys| keys.contains(Key::KEY_ENTER));
let is_mouse = device
.supported_relative_axes()
.map_or(false, |axes| axes.contains(RelativeAxisType::REL_X));
let device_type = match (is_keyboard, is_mouse) {
(true, true) => DeviceType::KeyboardMouse,
(true, false) => DeviceType::Keyboard,
(false, true) => DeviceType::Mouse,
(false, false) => DeviceType::Other,
};
let device_name = device.name().unwrap_or("unknown device name");
match (detect_mode, device_type) {
(_, DeviceType::Other) => {
log::debug!("Use for input: false. Non-input device: {}", device_name,);
false
}
(DeviceDetectMode::Any, _)
| (DeviceDetectMode::KeyboardMice, DeviceType::Keyboard | DeviceType::KeyboardMouse)
| (DeviceDetectMode::KeyboardOnly, DeviceType::Keyboard) => {
log::debug!(
"Use for input: true. detect type {:?}; device type {:?}, device name: {}",
detect_mode,
device_type,
device_name,
);
true
}
_ => {
log::debug!(
"Use for input: false. detect type {:?}; device type {:?}, device name: {}",
detect_mode,
device_type,
device_name,
);
true
}
}
}
impl TryFrom<InputEvent> for KeyEvent {
type Error = ();
fn try_from(item: InputEvent) -> Result<Self, Self::Error> {
use OsCode::*;
match item.kind() {
evdev::InputEventKind::Key(k) => Ok(Self {
code: OsCode::from_u16(k.0).ok_or(())?,
value: KeyValue::from(item.value()),
}),
evdev::InputEventKind::RelAxis(axis_type) => {
let dist = item.value();
let code: OsCode = match axis_type {
RelativeAxisType::REL_WHEEL | RelativeAxisType::REL_WHEEL_HI_RES => {
if dist > 0 {
MouseWheelUp
} else {
MouseWheelDown
}
}
RelativeAxisType::REL_HWHEEL | RelativeAxisType::REL_HWHEEL_HI_RES => {
if dist > 0 {
MouseWheelRight
} else {
MouseWheelLeft
}
}
_ => return Err(()),
};
Ok(KeyEvent {
code,
value: KeyValue::Tap,
})
}
_ => Err(()),
}
}
}
impl From<KeyEvent> for InputEvent {
fn from(item: KeyEvent) -> Self {
InputEvent::new(EventType::KEY, item.code as u16, item.value as i32)
}
}
use std::cell::Cell;
#[cfg(all(not(feature = "simulated_output"), not(feature = "passthru_ahk")))]
pub struct KbdOut {
device: uinput::VirtualDevice,
accumulated_scroll: u16,
accumulated_hscroll: u16,
raw_buf: Vec<InputEvent>,
pub unicode_termination: Cell<UnicodeTermination>,
pub unicode_u_code: Cell<OsCode>,
}
#[cfg(all(not(feature = "simulated_output"), not(feature = "passthru_ahk")))]
impl KbdOut {
pub fn new(
symlink_path: &Option<String>,
trackpoint: bool,
bus_type: BusType,
) -> Result<Self, io::Error> {
// Support pretty much every feature of a Keyboard or a Mouse in a VirtualDevice so that no event from the original input devices gets lost
// TODO investigate the rare possibility that a device is e.g. a Joystick and a Keyboard or a Mouse at the same time, which could lead to lost events
// For some reason 0..0x300 (max value for a key) doesn't work, the closest that I've got to work is 560
let keys = evdev::AttributeSet::from_iter((0..560).map(evdev::Key));
let relative_axes = evdev::AttributeSet::from_iter([
RelativeAxisType::REL_WHEEL,
RelativeAxisType::REL_HWHEEL,
RelativeAxisType::REL_X,
RelativeAxisType::REL_Y,
RelativeAxisType::REL_Z,
RelativeAxisType::REL_RX,
RelativeAxisType::REL_RY,
RelativeAxisType::REL_RZ,
RelativeAxisType::REL_DIAL,
RelativeAxisType::REL_MISC,
RelativeAxisType::REL_WHEEL_HI_RES,
RelativeAxisType::REL_HWHEEL_HI_RES,
]);
let device = uinput::VirtualDeviceBuilder::new()?
.name("kanata")
// libinput's "disable while typing" feature don't work when bus_type
// is set to BUS_USB, but appears to work when it's set to BUS_I8042.
.input_id(evdev::InputId::new(bus_type, 1, 1, 1))
.with_keys(&keys)?
.with_relative_axes(&relative_axes)?;
let device = if trackpoint {
device.with_properties(&evdev::AttributeSet::from_iter([PropType::POINTING_STICK]))?
} else {
device
};
let mut device = device.build()?;
let devnode = device
.enumerate_dev_nodes_blocking()?
.next() // Expect only one. Using fold or calling next again blocks indefinitely
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "devnode is not found"))??;
log::info!("Created device {:#?}", devnode);
let symlink = if let Some(symlink_path) = symlink_path {
let dest = PathBuf::from(symlink_path);
let symlink = Symlink::new(devnode, dest)?;
Some(symlink)
} else {
None
};
handle_signals(symlink);
Ok(KbdOut {
device,
accumulated_scroll: 0,
accumulated_hscroll: 0,
raw_buf: vec![],
// historically was the only option, so make Enter the default
unicode_termination: Cell::new(UnicodeTermination::Enter),
// historically was the only option, so make KEY_U the default
unicode_u_code: Cell::new(OsCode::KEY_U),
})
}
pub fn update_unicode_termination(&self, t: UnicodeTermination) {
self.unicode_termination.replace(t);
}
pub fn update_unicode_u_code(&self, u: OsCode) {
self.unicode_u_code.replace(u);
}
pub fn write_raw(&mut self, event: InputEvent) -> Result<(), io::Error> {
if event.event_type() == EventType::SYNCHRONIZATION {
// Possible codes are:
//
// SYN_REPORT: probably the only one we'll ever receive, segments atomic reads
// SYN_CONFIG: unused
// SYN_MT_REPORT: same as SYN_REPORT above but for touch devices, which kanata almost
// certainly shouldn't be dealing with.
// SYN_DROPPED: buffer full, events dropped. Not sure what this means or how to handle
// this correctly.
//
// With this knowledge, seems fine to not bother checking.
self.device.emit(&self.raw_buf)?;
self.raw_buf.clear();
} else {
self.raw_buf.push(event);
}
Ok(())
}
pub fn write(&mut self, event: InputEvent) -> Result<(), io::Error> {
if !self.raw_buf.is_empty() {
self.device.emit(&self.raw_buf)?;
self.raw_buf.clear();
}
self.device.emit(&[event])?;
Ok(())
}
pub fn write_many(&mut self, events: &[InputEvent]) -> Result<(), io::Error> {
if !self.raw_buf.is_empty() {
self.device.emit(&self.raw_buf)?;
self.raw_buf.clear();
}
self.device.emit(events)?;
Ok(())
}
pub fn write_key(&mut self, key: OsCode, value: KeyValue) -> Result<(), io::Error> {
let key_ev = KeyEvent::new(key, value);
let input_ev = key_ev.into();
log::debug!("send to uinput: {:?}", input_ev);
self.device.emit(&[input_ev])?;
Ok(())
}
pub fn write_code(&mut self, code: u32, value: KeyValue) -> Result<(), io::Error> {
let event = InputEvent::new(EventType::KEY, code as u16, value as i32);
self.device.emit(&[event])?;
Ok(())
}
pub fn press_key(&mut self, key: OsCode) -> Result<(), io::Error> {
self.write_key(key, KeyValue::Press)
}
pub fn release_key(&mut self, key: OsCode) -> Result<(), io::Error> {
self.write_key(key, KeyValue::Release)
}
/// Send using C-S-u + <unicode hex number> + spc
pub fn send_unicode(&mut self, c: char) -> Result<(), io::Error> {
log::debug!("sending unicode {c}");
let hex = format!("{:x}", c as u32);
self.press_key(OsCode::KEY_LEFTCTRL)?;
self.press_key(OsCode::KEY_LEFTSHIFT)?;
self.press_key(self.unicode_u_code.get())?;
self.release_key(self.unicode_u_code.get())?;
self.release_key(OsCode::KEY_LEFTSHIFT)?;
self.release_key(OsCode::KEY_LEFTCTRL)?;
let mut s = String::new();
for c in hex.chars() {
s.push(c);
let osc = str_to_oscode(&s).expect("valid keycodes for unicode");
s.clear();
self.press_key(osc)?;
self.release_key(osc)?;
}
match self.unicode_termination.get() {
UnicodeTermination::Enter => {
self.press_key(OsCode::KEY_ENTER)?;
self.release_key(OsCode::KEY_ENTER)?;
}
UnicodeTermination::Space => {
self.press_key(OsCode::KEY_SPACE)?;
self.release_key(OsCode::KEY_SPACE)?;
}
UnicodeTermination::SpaceEnter => {
self.press_key(OsCode::KEY_SPACE)?;
self.release_key(OsCode::KEY_SPACE)?;
self.press_key(OsCode::KEY_ENTER)?;
self.release_key(OsCode::KEY_ENTER)?;
}
UnicodeTermination::EnterSpace => {
self.press_key(OsCode::KEY_ENTER)?;
self.release_key(OsCode::KEY_ENTER)?;
self.press_key(OsCode::KEY_SPACE)?;
self.release_key(OsCode::KEY_SPACE)?;
}
}
Ok(())
}
pub fn click_btn(&mut self, btn: Btn) -> Result<(), io::Error> {
self.press_key(btn.into())
}
pub fn release_btn(&mut self, btn: Btn) -> Result<(), io::Error> {
self.release_key(btn.into())
}
pub fn scroll(
&mut self,
direction: MWheelDirection,
hi_res_distance: u16,
) -> Result<(), io::Error> {
log::debug!("scroll: {direction:?} {hi_res_distance:?}");
let mut lo_res_distance = hi_res_distance / HI_RES_SCROLL_UNITS_IN_LO_RES;
let leftover_hi_res_distance = hi_res_distance % HI_RES_SCROLL_UNITS_IN_LO_RES;
match direction {
MWheelDirection::Up | MWheelDirection::Down => {
self.accumulated_scroll += leftover_hi_res_distance;
lo_res_distance += self.accumulated_scroll / HI_RES_SCROLL_UNITS_IN_LO_RES;
self.accumulated_scroll %= HI_RES_SCROLL_UNITS_IN_LO_RES;
}
MWheelDirection::Left | MWheelDirection::Right => {
self.accumulated_hscroll += leftover_hi_res_distance;
lo_res_distance += self.accumulated_hscroll / HI_RES_SCROLL_UNITS_IN_LO_RES;
self.accumulated_hscroll %= HI_RES_SCROLL_UNITS_IN_LO_RES;
}
}
let hi_res_scroll_event = InputEvent::new(
EventType::RELATIVE,
match direction {
MWheelDirection::Up | MWheelDirection::Down => RelativeAxisType::REL_WHEEL_HI_RES.0,
MWheelDirection::Left | MWheelDirection::Right => {
RelativeAxisType::REL_HWHEEL_HI_RES.0
}
},
match direction {
MWheelDirection::Up | MWheelDirection::Right => i32::from(hi_res_distance),
MWheelDirection::Down | MWheelDirection::Left => -i32::from(hi_res_distance),
},
);
if lo_res_distance > 0 {
self.write_many(&[
hi_res_scroll_event,
InputEvent::new(
EventType::RELATIVE,
match direction {
MWheelDirection::Up | MWheelDirection::Down => {
RelativeAxisType::REL_WHEEL.0
}
MWheelDirection::Left | MWheelDirection::Right => {
RelativeAxisType::REL_HWHEEL.0
}
},
match direction {
MWheelDirection::Up | MWheelDirection::Right => i32::from(lo_res_distance),
MWheelDirection::Down | MWheelDirection::Left => {
-i32::from(lo_res_distance)
}
},
),
])
} else {
self.write(hi_res_scroll_event)
}
}
pub fn move_mouse(&mut self, mv: CalculatedMouseMove) -> Result<(), io::Error> {
let (axis, distance) = match mv.direction {
MoveDirection::Up => (RelativeAxisType::REL_Y, -i32::from(mv.distance)),
MoveDirection::Down => (RelativeAxisType::REL_Y, i32::from(mv.distance)),
MoveDirection::Left => (RelativeAxisType::REL_X, -i32::from(mv.distance)),
MoveDirection::Right => (RelativeAxisType::REL_X, i32::from(mv.distance)),
};
self.write(InputEvent::new(EventType::RELATIVE, axis.0, distance))
}
pub fn move_mouse_many(&mut self, moves: &[CalculatedMouseMove]) -> Result<(), io::Error> {
let mut events = vec![];
for mv in moves {
let (axis, distance) = match mv.direction {
MoveDirection::Up => (RelativeAxisType::REL_Y, -i32::from(mv.distance)),
MoveDirection::Down => (RelativeAxisType::REL_Y, i32::from(mv.distance)),
MoveDirection::Left => (RelativeAxisType::REL_X, -i32::from(mv.distance)),
MoveDirection::Right => (RelativeAxisType::REL_X, i32::from(mv.distance)),
};
events.push(InputEvent::new(EventType::RELATIVE, axis.0, distance));
}
self.write_many(&events)
}
pub fn set_mouse(&mut self, _x: u16, _y: u16) -> Result<(), io::Error> {
log::warn!("setmouse does not work in Linux yet. Maybe try out warpd:\n\thttps://github.com/rvaiya/warpd");
Ok(())
}
}
fn devices_from_input_paths(
dev_paths: &[String],
missing_device_paths: &mut Vec<String>,
) -> Vec<(Device, String)> {
dev_paths
.iter()
.map(|dev_path| (dev_path, Device::open(dev_path)))
.filter_map(|(dev_path, open_result)| match open_result {
Ok(d) => Some((d, dev_path.clone())),
Err(e) => {
log::warn!("failed to open device '{dev_path}': {e:?}");
missing_device_paths.push(dev_path.clone());
None
}
})
.collect()
}
fn discover_devices(
include_names: Option<&[String]>,
exclude_names: Option<&[String]>,
device_detect_mode: DeviceDetectMode,
) -> Vec<(Device, String)> {
log::info!("looking for devices in /dev/input");
let devices: Vec<_> = evdev::enumerate()
.map(|(path, device)| {
(
device,
path.to_str()
.expect("non-utf8 path found for device")
.to_owned(),
)
})
.filter(|pd| {
is_input_device(&pd.0, device_detect_mode)
&& match include_names {
None => true,
Some(include_names) => {
let name = pd.0.name().unwrap_or("");
if include_names.iter().any(|include| name == include) {
log::info!("device [{}:{name}] is included", &pd.1);
true
} else {
log::info!("device [{}:{name}] is ignored", &pd.1);
false
}
}
}
&& match exclude_names {
None => true,
Some(exclude_names) => {
let name = pd.0.name().unwrap_or("");
if exclude_names.iter().any(|exclude| name == exclude) {
log::info!("device [{}:{name}] is excluded", &pd.1);
false
} else {
true
}
}
}
})
.collect();
devices
}
fn watch_devinput() -> Result<Inotify, io::Error> {
let inotify = Inotify::init().expect("Failed to initialize inotify");
inotify.watches().add("/dev/input", WatchMask::CREATE)?;
Ok(inotify)
}
#[derive(Clone)]
struct Symlink {
dest: PathBuf,
}
impl Symlink {
fn new(source: PathBuf, dest: PathBuf) -> Result<Self, io::Error> {
if let Ok(metadata) = fs::symlink_metadata(&dest) {
if metadata.file_type().is_symlink() {
fs::remove_file(&dest)?;
} else {
return Err(io::Error::new(
io::ErrorKind::AlreadyExists,
format!(
"Cannot create a symlink at \"{}\": path already exists.",
dest.to_string_lossy()
),
));
}
}
std::os::unix::fs::symlink(&source, &dest)?;
log::info!("Created symlink {:#?} -> {:#?}", dest, source);
Ok(Self { dest })
}
}
fn handle_signals(symlink: Option<Symlink>) {
thread::spawn(|| {
let mut signals = Signals::new([SIGINT, SIGTERM, SIGTSTP]).expect("signals register");
if let Some(signal) = (&mut signals).into_iter().next() {
match signal {
SIGINT | SIGTERM => {
drop(symlink);
signal_hook::low_level::emulate_default_handler(signal)
.expect("run original sighandlers");
unreachable!();
}
SIGTSTP => {
drop(symlink);
log::warn!("got SIGTSTP, exiting instead of pausing so keyboards don't hang");
std::process::exit(SIGTSTP);
}
_ => unreachable!(),
}
}
});
}
// Note for allow: the ioctl_read_buf triggers this clippy lint.
// Note: CI does not yet support this lint, so also allowing unknown lints.
#[allow(unknown_lints)]
#[allow(clippy::manual_slice_size_calculation)]
fn wait_for_all_keys_unpressed(dev: &Device) -> Result<(), io::Error> {
let mut pending_release = false;
const KEY_MAX: usize = OsCode::KEY_MAX as usize;
let mut keystate = [0u8; KEY_MAX / 8 + 1];
loop {
let mut n_pressed_keys = 0;
ioctl_read_buf!(read_keystates, 'E', 0x18, u8);
unsafe { read_keystates(dev.as_raw_fd(), &mut keystate) }
.map_err(|_| io::Error::last_os_error())?;
for i in 0..=KEY_MAX {
if (keystate[i / 8] >> (i % 8)) & 0x1 > 0 {
n_pressed_keys += 1;
}
}
match n_pressed_keys {
0 => break,
_ => pending_release = true,
}
}
if pending_release {
std::thread::sleep(std::time::Duration::from_micros(100));
}
Ok(())
}
impl Drop for Symlink {
fn drop(&mut self) {
let _ = fs::remove_file(&self.dest);
log::info!("Deleted symlink {:#?}", self.dest);
}
}