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
use crate::constants::*;
use crate::device_state::DeviceState;
use crate::raw_stream::RawDevice;
use crate::{AttributeSet, AttributeSetRef, AutoRepeat, InputEvent, InputEventKind, InputId, Key};
use std::os::unix::io::{AsRawFd, RawFd};
use std::path::Path;
use std::time::SystemTime;
use std::{fmt, io};
pub struct Device {
raw: RawDevice,
prev_state: DeviceState,
state: DeviceState,
block_dropped: bool,
}
impl Device {
#[inline(always)]
pub fn open(path: impl AsRef<Path>) -> io::Result<Device> {
Self::_open(path.as_ref())
}
#[inline]
fn _open(path: &Path) -> io::Result<Device> {
RawDevice::open(path).map(Self::from_raw_device)
}
pub(crate) fn from_raw_device(raw: RawDevice) -> Device {
let state = DeviceState::new(&raw);
let prev_state = state.clone();
Device {
raw,
prev_state,
state,
block_dropped: false,
}
}
pub fn cached_state(&self) -> &DeviceState {
&self.state
}
pub fn name(&self) -> Option<&str> {
self.raw.name()
}
pub fn physical_path(&self) -> Option<&str> {
self.raw.physical_path()
}
pub fn unique_name(&self) -> Option<&str> {
self.raw.unique_name()
}
pub fn input_id(&self) -> InputId {
self.raw.input_id()
}
pub fn get_auto_repeat(&self) -> Option<AutoRepeat> {
self.raw.get_auto_repeat()
}
pub fn update_auto_repeat(&mut self, repeat: &AutoRepeat) -> io::Result<()> {
self.raw.update_auto_repeat(repeat)
}
pub fn get_scancode_by_keycode(&self, keycode: Key) -> io::Result<Vec<u8>> {
self.raw.get_scancode_by_keycode(keycode.code() as u32)
}
pub fn get_scancode_by_index(&self, index: u16) -> io::Result<(u32, Vec<u8>)> {
self.raw.get_scancode_by_index(index)
}
pub fn update_scancode(&self, keycode: Key, scancode: &[u8]) -> io::Result<Key> {
self.raw
.update_scancode(keycode.code() as u32, scancode)
.map(|keycode| Key::new(keycode as u16))
}
pub fn update_scancode_by_index(
&self,
index: u16,
keycode: Key,
scancode: &[u8],
) -> io::Result<u32> {
self.raw
.update_scancode_by_index(index, keycode.code() as u32, scancode)
}
pub fn properties(&self) -> &AttributeSetRef<PropType> {
self.raw.properties()
}
pub fn driver_version(&self) -> (u8, u8, u8) {
self.raw.driver_version()
}
pub fn supported_events(&self) -> &AttributeSetRef<EventType> {
self.raw.supported_events()
}
pub fn supported_keys(&self) -> Option<&AttributeSetRef<Key>> {
self.raw.supported_keys()
}
pub fn supported_relative_axes(&self) -> Option<&AttributeSetRef<RelativeAxisType>> {
self.raw.supported_relative_axes()
}
pub fn supported_absolute_axes(&self) -> Option<&AttributeSetRef<AbsoluteAxisType>> {
self.raw.supported_absolute_axes()
}
pub fn supported_switches(&self) -> Option<&AttributeSetRef<SwitchType>> {
self.raw.supported_switches()
}
pub fn supported_leds(&self) -> Option<&AttributeSetRef<LedType>> {
self.raw.supported_leds()
}
pub fn misc_properties(&self) -> Option<&AttributeSetRef<MiscType>> {
self.raw.misc_properties()
}
pub fn supported_sounds(&self) -> Option<&AttributeSetRef<SoundType>> {
self.raw.supported_sounds()
}
pub fn get_key_state(&self) -> io::Result<AttributeSet<Key>> {
self.raw.get_key_state()
}
pub fn get_abs_state(&self) -> io::Result<[libc::input_absinfo; AbsoluteAxisType::COUNT]> {
self.raw.get_abs_state()
}
pub fn get_switch_state(&self) -> io::Result<AttributeSet<SwitchType>> {
self.raw.get_switch_state()
}
pub fn get_led_state(&self) -> io::Result<AttributeSet<LedType>> {
self.raw.get_led_state()
}
fn sync_state(&mut self, now: SystemTime) -> io::Result<()> {
if let Some(ref mut key_vals) = self.state.key_vals {
self.raw.update_key_state(key_vals)?;
}
if let Some(ref mut abs_vals) = self.state.abs_vals {
self.raw.update_abs_state(abs_vals)?;
}
if let Some(ref mut switch_vals) = self.state.switch_vals {
self.raw.update_switch_state(switch_vals)?;
}
if let Some(ref mut led_vals) = self.state.led_vals {
self.raw.update_led_state(led_vals)?;
}
self.state.timestamp = now;
Ok(())
}
fn fetch_events_inner(&mut self) -> io::Result<Option<SyncState>> {
let block_dropped = std::mem::take(&mut self.block_dropped);
let sync = if block_dropped {
self.prev_state.clone_from(&self.state);
let now = SystemTime::now();
self.sync_state(now)?;
Some(SyncState::Keys {
time: crate::systime_to_timeval(&now),
start: Key::new(0),
})
} else {
None
};
self.raw.fill_events()?;
Ok(sync)
}
pub fn fetch_events(&mut self) -> io::Result<FetchEventsSynced<'_>> {
let sync = self.fetch_events_inner()?;
Ok(FetchEventsSynced {
dev: self,
range: 0..0,
consumed_to: 0,
sync,
})
}
#[cfg(feature = "tokio")]
pub fn into_event_stream(self) -> io::Result<EventStream> {
EventStream::new(self)
}
pub fn grab(&mut self) -> io::Result<()> {
self.raw.grab()
}
pub fn ungrab(&mut self) -> io::Result<()> {
self.raw.ungrab()
}
}
impl AsRawFd for Device {
fn as_raw_fd(&self) -> RawFd {
self.raw.as_raw_fd()
}
}
pub struct FetchEventsSynced<'a> {
dev: &'a mut Device,
range: std::ops::Range<usize>,
consumed_to: usize,
sync: Option<SyncState>,
}
enum SyncState {
Keys {
time: libc::timeval,
start: Key,
},
Absolutes {
time: libc::timeval,
start: AbsoluteAxisType,
},
Switches {
time: libc::timeval,
start: SwitchType,
},
Leds {
time: libc::timeval,
start: LedType,
},
}
#[inline]
fn compensate_events(state: &mut Option<SyncState>, dev: &mut Device) -> Option<InputEvent> {
let sync = state.as_mut()?;
macro_rules! try_compensate {
($time:expr, $start:ident : $typ:ident, $evtype:ident, $sync:ident, $supporteds:ident, $state:ty, $get_state:expr, $get_value:expr) => {
if let Some(supported_types) = dev.$supporteds() {
let types_to_check = supported_types.slice(*$start);
let get_state: fn(&DeviceState) -> $state = $get_state;
let vals = get_state(&dev.state);
let old_vals = get_state(&dev.prev_state);
let get_value: fn($state, $typ) -> _ = $get_value;
for typ in types_to_check.iter() {
let prev = get_value(old_vals, typ);
let value = get_value(vals, typ);
if prev != value {
$start.0 = typ.0 + 1;
let ev = InputEvent(libc::input_event {
time: *$time,
type_: EventType::$evtype.0,
code: typ.0,
value: value as _,
});
return Some(ev);
}
}
}
};
}
loop {
match sync {
SyncState::Keys { time, start } => {
try_compensate!(
time,
start: Key,
KEY,
Keys,
supported_keys,
&AttributeSetRef<Key>,
|st| st.key_vals().unwrap(),
|vals, key| vals.contains(key)
);
*sync = SyncState::Absolutes {
time: *time,
start: AbsoluteAxisType(0),
};
continue;
}
SyncState::Absolutes { time, start } => {
try_compensate!(
time,
start: AbsoluteAxisType,
ABSOLUTE,
Absolutes,
supported_absolute_axes,
&[libc::input_absinfo],
|st| st.abs_vals().unwrap(),
|vals, abs| vals[abs.0 as usize].value
);
*sync = SyncState::Switches {
time: *time,
start: SwitchType(0),
};
continue;
}
SyncState::Switches { time, start } => {
try_compensate!(
time,
start: SwitchType,
SWITCH,
Switches,
supported_switches,
&AttributeSetRef<SwitchType>,
|st| st.switch_vals().unwrap(),
|vals, sw| vals.contains(sw)
);
*sync = SyncState::Leds {
time: *time,
start: LedType(0),
};
continue;
}
SyncState::Leds { time, start } => {
try_compensate!(
time,
start: LedType,
LED,
Leds,
supported_leds,
&AttributeSetRef<LedType>,
|st| st.led_vals().unwrap(),
|vals, led| vals.contains(led)
);
let ev = InputEvent(libc::input_event {
time: *time,
type_: EventType::SYNCHRONIZATION.0,
code: Synchronization::SYN_REPORT.0,
value: 0,
});
*state = None;
return Some(ev);
}
}
}
}
impl<'a> Iterator for FetchEventsSynced<'a> {
type Item = InputEvent;
fn next(&mut self) -> Option<InputEvent> {
if let Some(ev) = compensate_events(&mut self.sync, &mut self.dev) {
return Some(ev);
}
let state = &mut self.dev.state;
let (res, consumed_to) = sync_events(&mut self.range, &self.dev.raw.event_buf, |ev| {
state.process_event(ev)
});
if let Some(end) = consumed_to {
self.consumed_to = end
}
match res {
Ok(ev) => Some(InputEvent(ev)),
Err(requires_sync) => {
if requires_sync {
self.dev.block_dropped = true;
}
None
}
}
}
}
impl<'a> Drop for FetchEventsSynced<'a> {
fn drop(&mut self) {
self.dev.raw.event_buf.drain(..self.consumed_to);
}
}
#[inline]
fn sync_events(
range: &mut std::ops::Range<usize>,
event_buf: &[libc::input_event],
mut handle_event: impl FnMut(InputEvent),
) -> (Result<libc::input_event, bool>, Option<usize>) {
let mut consumed_to = None;
let res = 'outer: loop {
if let Some(idx) = range.next() {
break Ok(event_buf[idx]);
}
let block_start = range.end;
let mut block_dropped = false;
for (i, ev) in event_buf.iter().enumerate().skip(block_start) {
let ev = InputEvent(*ev);
match ev.kind() {
InputEventKind::Synchronization(Synchronization::SYN_DROPPED) => {
block_dropped = true;
}
InputEventKind::Synchronization(Synchronization::SYN_REPORT) => {
consumed_to = Some(i + 1);
if block_dropped {
*range = event_buf.len()..event_buf.len();
break 'outer Err(true);
} else {
*range = block_start..i + 1;
continue 'outer;
}
}
_ => handle_event(ev),
}
}
break Err(false);
};
(res, consumed_to)
}
impl fmt::Display for Device {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "{}:", self.name().unwrap_or("Unnamed device"))?;
let (maj, min, pat) = self.driver_version();
writeln!(f, " Driver version: {}.{}.{}", maj, min, pat)?;
if let Some(ref phys) = self.physical_path() {
writeln!(f, " Physical address: {:?}", phys)?;
}
if let Some(ref uniq) = self.unique_name() {
writeln!(f, " Unique name: {:?}", uniq)?;
}
let id = self.input_id();
writeln!(f, " Bus: {}", id.bus_type())?;
writeln!(f, " Vendor: {:#x}", id.vendor())?;
writeln!(f, " Product: {:#x}", id.product())?;
writeln!(f, " Version: {:#x}", id.version())?;
writeln!(f, " Properties: {:?}", self.properties())?;
if let (Some(supported_keys), Some(key_vals)) =
(self.supported_keys(), self.state.key_vals())
{
writeln!(f, " Keys supported:")?;
for key in supported_keys.iter() {
let key_idx = key.code() as usize;
writeln!(
f,
" {:?} ({}index {})",
key,
if key_vals.contains(key) {
"pressed, "
} else {
""
},
key_idx
)?;
}
}
if let Some(supported_relative) = self.supported_relative_axes() {
writeln!(f, " Relative Axes: {:?}", supported_relative)?;
}
if let (Some(supported_abs), Some(abs_vals)) =
(self.supported_absolute_axes(), &self.state.abs_vals)
{
writeln!(f, " Absolute Axes:")?;
for abs in supported_abs.iter() {
writeln!(
f,
" {:?} ({:?}, index {})",
abs, abs_vals[abs.0 as usize], abs.0
)?;
}
}
if let Some(supported_misc) = self.misc_properties() {
writeln!(f, " Miscellaneous capabilities: {:?}", supported_misc)?;
}
if let (Some(supported_switch), Some(switch_vals)) =
(self.supported_switches(), self.state.switch_vals())
{
writeln!(f, " Switches:")?;
for sw in supported_switch.iter() {
writeln!(
f,
" {:?} ({:?}, index {})",
sw,
switch_vals.contains(sw),
sw.0
)?;
}
}
if let (Some(supported_led), Some(led_vals)) =
(self.supported_leds(), self.state.led_vals())
{
writeln!(f, " LEDs:")?;
for led in supported_led.iter() {
writeln!(
f,
" {:?} ({:?}, index {})",
led,
led_vals.contains(led),
led.0
)?;
}
}
if let Some(supported_snd) = self.supported_sounds() {
write!(f, " Sounds:")?;
for snd in supported_snd.iter() {
writeln!(f, " {:?} (index {})", snd, snd.0)?;
}
}
let evs = self.supported_events();
if evs.contains(EventType::FORCEFEEDBACK) {
writeln!(f, " Force Feedback supported")?;
}
if evs.contains(EventType::POWER) {
writeln!(f, " Power supported")?;
}
if evs.contains(EventType::FORCEFEEDBACKSTATUS) {
writeln!(f, " Force Feedback status supported")?;
}
Ok(())
}
}
#[cfg(feature = "tokio")]
mod tokio_stream {
use super::*;
use tokio_1 as tokio;
use crate::raw_stream::poll_fn;
use futures_core::{ready, Stream};
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::io::unix::AsyncFd;
pub struct EventStream {
device: AsyncFd<Device>,
event_range: std::ops::Range<usize>,
consumed_to: usize,
sync: Option<SyncState>,
}
impl Unpin for EventStream {}
impl EventStream {
pub(crate) fn new(device: Device) -> io::Result<Self> {
use nix::fcntl;
fcntl::fcntl(device.as_raw_fd(), fcntl::F_SETFL(fcntl::OFlag::O_NONBLOCK))?;
let device = AsyncFd::new(device)?;
Ok(Self {
device,
event_range: 0..0,
consumed_to: 0,
sync: None,
})
}
pub fn device(&self) -> &Device {
self.device.get_ref()
}
pub async fn next_event(&mut self) -> io::Result<InputEvent> {
poll_fn(|cx| self.poll_event(cx)).await
}
pub fn poll_event(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<InputEvent>> {
'outer: loop {
let dev = self.device.get_mut();
if let Some(ev) = compensate_events(&mut self.sync, dev) {
return Poll::Ready(Ok(ev));
}
let state = &mut dev.state;
let (res, consumed_to) =
sync_events(&mut self.event_range, &dev.raw.event_buf, |ev| {
state.process_event(ev)
});
if let Some(end) = consumed_to {
self.consumed_to = end
}
match res {
Ok(ev) => return Poll::Ready(Ok(InputEvent(ev))),
Err(requires_sync) => {
if requires_sync {
dev.block_dropped = true;
}
}
}
dev.raw.event_buf.drain(..self.consumed_to);
self.consumed_to = 0;
loop {
let mut guard = ready!(self.device.poll_read_ready_mut(cx))?;
let res = guard.try_io(|device| device.get_mut().fetch_events_inner());
match res {
Ok(res) => {
self.sync = res?;
self.event_range = 0..0;
continue 'outer;
}
Err(_would_block) => continue,
}
}
}
}
}
impl Stream for EventStream {
type Item = io::Result<InputEvent>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.get_mut().poll_event(cx).map(Some)
}
}
}
#[cfg(feature = "tokio")]
pub use tokio_stream::EventStream;
#[cfg(test)]
mod tests {
use super::*;
fn result_events_iter(
events: &[libc::input_event],
) -> impl Iterator<Item = Result<libc::input_event, ()>> + '_ {
let mut range = 0..0;
std::iter::from_fn(move || {
let (res, _) = sync_events(&mut range, events, |_| {});
match res {
Ok(x) => Some(Ok(x)),
Err(true) => Some(Err(())),
Err(false) => None,
}
})
}
fn events_iter(events: &[libc::input_event]) -> impl Iterator<Item = libc::input_event> + '_ {
result_events_iter(events).flatten()
}
#[allow(non_upper_case_globals)]
const time: libc::timeval = libc::timeval {
tv_sec: 0,
tv_usec: 0,
};
const KEY4: libc::input_event = libc::input_event {
time,
type_: EventType::KEY.0,
code: Key::KEY_4.0,
value: 1,
};
const REPORT: libc::input_event = libc::input_event {
time,
type_: EventType::SYNCHRONIZATION.0,
code: Synchronization::SYN_REPORT.0,
value: 0,
};
const DROPPED: libc::input_event = libc::input_event {
code: Synchronization::SYN_DROPPED.0,
..REPORT
};
#[test]
fn test_sync_impl() {
itertools::assert_equal(events_iter(&[]), vec![]);
itertools::assert_equal(events_iter(&[KEY4]), vec![]);
itertools::assert_equal(events_iter(&[KEY4, REPORT]), vec![KEY4, REPORT]);
itertools::assert_equal(events_iter(&[KEY4, REPORT, KEY4]), vec![KEY4, REPORT]);
itertools::assert_equal(
result_events_iter(&[KEY4, REPORT, KEY4, DROPPED, REPORT]),
vec![Ok(KEY4), Ok(REPORT), Err(())],
);
}
#[test]
fn test_iter_consistency() {
let evs = &[KEY4, REPORT, DROPPED, REPORT, KEY4, REPORT, KEY4];
let mut range = 0..0;
let mut next = || sync_events(&mut range, evs, |_| {});
assert_eq!(next(), (Ok(KEY4), Some(2)));
assert_eq!(next(), (Ok(REPORT), None));
assert_eq!(next(), (Err(true), Some(4)));
assert_eq!(next(), (Err(false), None));
assert_eq!(next(), (Err(false), None));
assert_eq!(next(), (Err(false), None));
}
}