Debian Codegraph @

src/sync_stream.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 use crate::compat::{input_absinfo, input_event};
2 use crate::constants::*;
3 use crate::device_state::DeviceState;
4 use crate::ff::*;
5 use crate::raw_stream::RawDevice;
6 use crate::{
7 AbsInfo, AttributeSet, AttributeSetRef, AutoRepeat, EventSummary, FFEffect, InputEvent,
8 InputId, KeyCode,
9 };
10
11 use nix::fcntl;
12 use std::fs::File;
13 use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd, RawFd};
14 use std::path::Path;
15 use std::time::SystemTime;
16 use std::{fmt, io};
17
18 /// A physical or virtual device supported by evdev.
19 ///
20 /// Each device corresponds to a path typically found in `/dev/input`, and supports access via
21 /// one or more "types". For example, an optical mouse has buttons that are represented by "keys",
22 /// and reflects changes in its position via "relative axis" reports.
23 ///
24 /// This type specifically is a wrapper over [`RawDevice`],that synchronizes with the kernel's
25 /// state when events are dropped.
26 ///
27 /// If `fetch_events()` isn't called often enough and the kernel drops events from its internal
28 /// buffer, synthetic events will be injected into the iterator returned by `fetch_events()` and
29 /// [`Device::cached_state()`] will be kept up to date when `fetch_events()` is called.
30 #[derive(Debug)]
31 pub struct Device {
32 raw: RawDevice,
33 prev_state: DeviceState,
34 state: DeviceState,
35 block_dropped: bool,
36 }
37
38 impl Device {
39 /// Opens a device, given its system path.
40 ///
41 /// Paths are typically something like `/dev/input/event0`.
42 #[inline(always)]
43 pub fn open(path: impl AsRef<Path>) -> io::Result<Device> {
44 Self::_open(path.as_ref())
45 }
46
47 /// Opens a device, given an already opened file descriptor.
48 #[inline(always)]
49 pub fn from_fd(fd: OwnedFd) -> io::Result<Device> {
50 RawDevice::from_fd(fd).map(Self::from_raw_device)
51 }
52
53 #[inline]
54 fn _open(path: &Path) -> io::Result<Device> {
55 RawDevice::open(path).map(Self::from_raw_device)
56 }
57
58 // TODO: should this be public?
59 pub(crate) fn from_raw_device(raw: RawDevice) -> Device {
60 let state = DeviceState::new(&raw);
61 let prev_state = state.clone();
62
63 Device {
64 raw,
65 prev_state,
66 state,
67 block_dropped: false,
68 }
69 }
70
71 /// Returns the synchronization engine's current understanding (cache) of the device state.
72 ///
73 /// Note that this represents the internal cache of the synchronization engine as of the last
74 /// entry that was pulled out. The advantage to calling this instead of invoking
75 /// [`get_key_state`](RawDevice::get_key_state)
76 /// and the like directly is speed: because reading this cache doesn't require any syscalls it's
77 /// easy to do inside a tight loop. The downside is that if the stream is not being driven quickly,
78 /// this can very quickly get desynchronized from the kernel and provide inaccurate data.
79 pub fn cached_state(&self) -> &DeviceState {
80 &self.state
81 }
82
83 /// Returns the device's name as read from the kernel.
84 pub fn name(&self) -> Option<&str> {
85 self.raw.name()
86 }
87
88 /// Returns the device's physical location, either as set by the caller or as read from the kernel.
89 pub fn physical_path(&self) -> Option<&str> {
90 self.raw.physical_path()
91 }
92
93 /// Returns the user-defined "unique name" of the device, if one has been set.
94 pub fn unique_name(&self) -> Option<&str> {
95 self.raw.unique_name()
96 }
97
98 /// Returns a struct containing bustype, vendor, product, and version identifiers
99 pub fn input_id(&self) -> InputId {
100 self.raw.input_id()
101 }
102
103 /// Returns a struct containing the delay and period for auto repeat
104 pub fn get_auto_repeat(&self) -> Option<AutoRepeat> {
105 self.raw.get_auto_repeat()
106 }
107
108 /// Update the delay and period for autorepeat
109 pub fn update_auto_repeat(&mut self, repeat: &AutoRepeat) -> io::Result<()> {
110 self.raw.update_auto_repeat(repeat)
111 }
112
113 /// Retrieve the scancode for a keycode, if any
114 pub fn get_scancode_by_keycode(&self, keycode: KeyCode) -> io::Result<Vec<u8>> {
115 self.raw.get_scancode_by_keycode(keycode.code() as u32)
116 }
117
118 /// Retrieve the keycode and scancode by index, starting at 0
119 pub fn get_scancode_by_index(&self, index: u16) -> io::Result<(u32, Vec<u8>)> {
120 self.raw.get_scancode_by_index(index)
121 }
122
123 /// Update a scancode. The return value is the previous keycode
124 pub fn update_scancode(&self, keycode: KeyCode, scancode: &[u8]) -> io::Result<KeyCode> {
125 self.raw
126 .update_scancode(keycode.code() as u32, scancode)
127 .map(|keycode| KeyCode::new(keycode as u16))
128 }
129
130 /// Update a scancode by index. The return value is the previous keycode
131 pub fn update_scancode_by_index(
132 &self,
133 index: u16,
134 keycode: KeyCode,
135 scancode: &[u8],
136 ) -> io::Result<u32> {
137 self.raw
138 .update_scancode_by_index(index, keycode.code() as u32, scancode)
139 }
140
141 /// Returns the set of supported "properties" for the device (see `INPUT_PROP_*` in kernel headers)
142 pub fn properties(&self) -> &AttributeSetRef<PropType> {
143 self.raw.properties()
144 }
145
146 /// Returns a tuple of the driver version containing major, minor, rev
147 pub fn driver_version(&self) -> (u8, u8, u8) {
148 self.raw.driver_version()
149 }
150
151 /// Returns a set of the event types supported by this device (KeyType, Switch, etc)
152 ///
153 /// If you're interested in the individual keys or switches supported, it's probably easier
154 /// to just call the appropriate `supported_*` function instead.
155 pub fn supported_events(&self) -> &AttributeSetRef<EventType> {
156 self.raw.supported_events()
157 }
158
159 /// Returns the set of supported keys reported by the device.
160 ///
161 /// For keyboards, this is the set of all possible keycodes the keyboard may emit. Controllers,
162 /// mice, and other peripherals may also report buttons as keys.
163 ///
164 /// # Examples
165 ///
166 /// ```no_run
167 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
168 /// use evdev::{Device, KeyCode};
169 /// let device = Device::open("/dev/input/event0")?;
170 ///
171 /// // Does this device have an ENTER key?
172 /// let supported = device.supported_keys().map_or(false, |keys| keys.contains(KeyCode::KEY_ENTER));
173 /// # Ok(())
174 /// # }
175 /// ```
176 pub fn supported_keys(&self) -> Option<&AttributeSetRef<KeyCode>> {
177 self.raw.supported_keys()
178 }
179
180 /// Returns the set of supported "relative axes" reported by the device.
181 ///
182 /// Standard mice will generally report `REL_X` and `REL_Y` along with wheel if supported.
183 ///
184 /// # Examples
185 ///
186 /// ```no_run
187 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
188 /// use evdev::{Device, RelativeAxisCode};
189 /// let device = Device::open("/dev/input/event0")?;
190 ///
191 /// // Does the device have a scroll wheel?
192 /// let supported = device
193 /// .supported_relative_axes()
194 /// .map_or(false, |axes| axes.contains(RelativeAxisCode::REL_WHEEL));
195 /// # Ok(())
196 /// # }
197 /// ```
198 pub fn supported_relative_axes(&self) -> Option<&AttributeSetRef<RelativeAxisCode>> {
199 self.raw.supported_relative_axes()
200 }
201
202 /// Returns the set of supported "absolute axes" reported by the device.
203 ///
204 /// These are most typically supported by joysticks and touchpads.
205 ///
206 /// # Examples
207 ///
208 /// ```no_run
209 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
210 /// use evdev::{Device, AbsoluteAxisCode};
211 /// let device = Device::open("/dev/input/event0")?;
212 ///
213 /// // Does the device have an absolute X axis?
214 /// let supported = device
215 /// .supported_absolute_axes()
216 /// .map_or(false, |axes| axes.contains(AbsoluteAxisCode::ABS_X));
217 /// # Ok(())
218 /// # }
219 /// ```
220 pub fn supported_absolute_axes(&self) -> Option<&AttributeSetRef<AbsoluteAxisCode>> {
221 self.raw.supported_absolute_axes()
222 }
223
224 /// Returns the set of supported switches reported by the device.
225 ///
226 /// These are typically used for things like software switches on laptop lids (which the
227 /// system reacts to by suspending or locking), or virtual switches to indicate whether a
228 /// headphone jack is plugged in (used to disable external speakers).
229 ///
230 /// # Examples
231 ///
232 /// ```no_run
233 /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
234 /// use evdev::{Device, SwitchCode};
235 /// let device = Device::open("/dev/input/event0")?;
236 ///
237 /// // Does the device report a laptop lid switch?
238 /// let supported = device
239 /// .supported_switches()
240 /// .map_or(false, |axes| axes.contains(SwitchCode::SW_LID));
241 /// # Ok(())
242 /// # }
243 /// ```
244 pub fn supported_switches(&self) -> Option<&AttributeSetRef<SwitchCode>> {
245 self.raw.supported_switches()
246 }
247
248 /// Returns a set of supported LEDs on the device.
249 ///
250 /// Most commonly these are state indicator lights for things like Scroll Lock, but they
251 /// can also be found in cameras and other devices.
252 pub fn supported_leds(&self) -> Option<&AttributeSetRef<LedCode>> {
253 self.raw.supported_leds()
254 }
255
256 /// Returns a set of supported "miscellaneous" capabilities.
257 ///
258 /// Aside from vendor-specific key scancodes, most of these are uncommon.
259 pub fn misc_properties(&self) -> Option<&AttributeSetRef<MiscCode>> {
260 self.raw.misc_properties()
261 }
262
263 /// Returns the set of supported force feedback effects supported by a device.
264 pub fn supported_ff(&self) -> Option<&AttributeSetRef<FFEffectCode>> {
265 self.raw.supported_ff()
266 }
267
268 /// Returns the maximum number of force feedback effects that can be played simultaneously.
269 pub fn max_ff_effects(&self) -> usize {
270 self.raw.max_ff_effects()
271 }
272
273 /// Returns the set of supported simple sounds supported by a device.
274 ///
275 /// You can use these to make really annoying beep sounds come from an internal self-test
276 /// speaker, for instance.
277 pub fn supported_sounds(&self) -> Option<&AttributeSetRef<SoundCode>> {
278 self.raw.supported_sounds()
279 }
280
281 /// Retrieve the current keypress state directly via kernel syscall.
282 pub fn get_key_state(&self) -> io::Result<AttributeSet<KeyCode>> {
283 self.raw.get_key_state()
284 }
285
286 /// Retrieve the current absolute axis state directly via kernel syscall.
287 pub fn get_abs_state(&self) -> io::Result<[input_absinfo; AbsoluteAxisCode::COUNT]> {
288 self.raw.get_abs_state()
289 }
290
291 /// Get the AbsInfo for each supported AbsoluteAxis
292 pub fn get_absinfo(
293 &self,
294 ) -> io::Result<impl Iterator<Item = (AbsoluteAxisCode, AbsInfo)> + '_> {
295 self.raw.get_absinfo()
296 }
297
298 /// Retrieve the current switch state directly via kernel syscall.
299 pub fn get_switch_state(&self) -> io::Result<AttributeSet<SwitchCode>> {
300 self.raw.get_switch_state()
301 }
302
303 /// Retrieve the current LED state directly via kernel syscall.
304 pub fn get_led_state(&self) -> io::Result<AttributeSet<LedCode>> {
305 self.raw.get_led_state()
306 }
307
308 fn sync_state(&mut self, now: SystemTime) -> io::Result<()> {
309 if let Some(ref mut key_vals) = self.state.key_vals {
310 self.raw.update_key_state(key_vals)?;
311 }
312 if let Some(ref mut abs_vals) = self.state.abs_vals {
313 self.raw.update_abs_state(abs_vals)?;
314 }
315 if let Some(ref mut switch_vals) = self.state.switch_vals {
316 self.raw.update_switch_state(switch_vals)?;
317 }
318 if let Some(ref mut led_vals) = self.state.led_vals {
319 self.raw.update_led_state(led_vals)?;
320 }
321 self.state.timestamp = now;
322 Ok(())
323 }
324
325 fn fetch_events_inner(&mut self) -> io::Result<Option<SyncState>> {
326 let block_dropped = std::mem::take(&mut self.block_dropped);
327 let sync = if block_dropped {
328 self.prev_state.clone_from(&self.state);
329 let now = SystemTime::now();
330 self.sync_state(now)?;
331 Some(SyncState::KeyTypes {
332 time: crate::systime_to_timeval(&now),
333 start: KeyCode::new(0),
334 })
335 } else {
336 None
337 };
338
339 self.raw.fill_events()?;
340
341 Ok(sync)
342 }
343
344 /// Fetches and returns events from the kernel ring buffer, doing synchronization on SYN_DROPPED.
345 ///
346 /// By default this will block until events are available. Typically, users will want to call
347 /// this in a tight loop within a thread.
348 /// Will insert "fake" events.
349 pub fn fetch_events(&mut self) -> io::Result<FetchEventsSynced<'_>> {
350 let sync = self.fetch_events_inner()?;
351
352 Ok(FetchEventsSynced {
353 dev: self,
354 range: 0..0,
355 consumed_to: 0,
356 sync,
357 })
358 }
359
360 #[cfg(feature = "tokio")]
361 pub fn into_event_stream(self) -> io::Result<EventStream> {
362 EventStream::new(self)
363 }
364
365 /// Set `O_NONBLOCK` on this device handle.
366 pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
367 let mut flags =
•368 fcntl::OFlag::from_bits_retain(fcntl::fcntl(self, fcntl::F_GETFL)?);
369 flags.set(fcntl::OFlag::O_NONBLOCK, nonblocking);
•370 fcntl::fcntl(self, fcntl::F_SETFL(flags))?;
371 Ok(())
372 }
373
374 /// Grab the device through a kernel syscall.
375 ///
376 /// This prevents other clients (including kernel-internal ones such as rfkill) from receiving
377 /// events from this device.
378 pub fn grab(&mut self) -> io::Result<()> {
379 self.raw.grab()
380 }
381
382 /// Ungrab the device through a kernel syscall.
383 pub fn ungrab(&mut self) -> io::Result<()> {
384 self.raw.ungrab()
385 }
386
387 /// Whether the device is currently grabbed for exclusive use or not.
388 pub fn is_grabbed(&self) -> bool {
389 self.raw.is_grabbed()
390 }
391
392 /// Send an event to the device.
393 ///
394 /// Events that are typically sent to devices are
395 /// [EventType::LED] (turn device LEDs on and off),
396 /// [EventType::SOUND] (play a sound on the device)
397 /// and [EventType::FORCEFEEDBACK] (play force feedback effects on the device, i.e. rumble).
398 pub fn send_events(&mut self, events: &[InputEvent]) -> io::Result<()> {
399 self.raw.send_events(events)
400 }
401
402 /// Uploads a force feedback effect to the device.
403 pub fn upload_ff_effect(&mut self, data: FFEffectData) -> io::Result<FFEffect> {
404 self.raw.upload_ff_effect(data)
405 }
406
407 /// Sets the force feedback gain, i.e. how strong the force feedback effects should be for the
408 /// device. A gain of 0 means no gain, whereas `u16::MAX` is the maximum gain.
409 pub fn set_ff_gain(&mut self, value: u16) -> io::Result<()> {
410 self.raw.set_ff_gain(value)
411 }
412
413 /// Enables or disables autocenter for the force feedback device.
414 pub fn set_ff_autocenter(&mut self, value: u16) -> io::Result<()> {
415 self.raw.set_ff_autocenter(value)
416 }
417 }
418
419 impl Drop for Device {
420 fn drop(&mut self) {
421 if let Err(error) = self.ungrab() {
422 eprintln!("Failed to ungrab device: {error}");
423 }
424 }
425 }
426
427 impl AsFd for Device {
428 fn as_fd(&self) -> BorrowedFd<'_> {
429 self.raw.as_fd()
430 }
431 }
432
433 impl AsRawFd for Device {
434 fn as_raw_fd(&self) -> RawFd {
435 self.raw.as_raw_fd()
436 }
437 }
438
439 impl TryFrom<File> for Device {
440 type Error = io::Error;
441
442 fn try_from(file: File) -> Result<Self, Self::Error> {
443 RawDevice::try_from(file).map(Self::from_raw_device)
444 }
445 }
446
447 /// An iterator over events of a [`Device`], produced by [`Device::fetch_events`].
448 pub struct FetchEventsSynced<'a> {
449 dev: &'a mut Device,
450 /// The current block of the events we're returning to the consumer. If empty
451 /// (i.e. for any x, range == x..x) then we'll find another block on the next `next()` call.
452 range: std::ops::Range<usize>,
453 /// The index into dev.raw.event_buf up to which we'll delete events when dropped.
454 consumed_to: usize,
455 /// Our current synchronization state, i.e. whether we're currently diffing key_vals,
456 /// abs_vals, switch_vals, led_vals, or none of them.
457 sync: Option<SyncState>,
458 }
459
460 enum SyncState {
461 KeyTypes {
462 time: libc::timeval,
463 start: KeyCode,
464 },
465 Absolutes {
466 time: libc::timeval,
467 start: AbsoluteAxisCode,
468 },
469 Switches {
470 time: libc::timeval,
471 start: SwitchCode,
472 },
473 Leds {
474 time: libc::timeval,
475 start: LedCode,
476 },
477 }
478
479 #[inline]
480 fn compensate_events(state: &mut Option<SyncState>, dev: &mut Device) -> Option<InputEvent> {
481 let sync = state.as_mut()?;
482 // this macro checks if there are any differences between the old state and the new for the
483 // specific substate(?) that we're checking and if so returns an input_event with the value set
484 // to the value from the up-to-date state
485 macro_rules! try_compensate {
486 ($time:expr, $start:ident : $typ:ident, $evtype:ident, $sync:ident, $supporteds:ident, $state:ty, $get_state:expr, $get_value:expr) => {
487 if let Some(supported_types) = dev.$supporteds() {
488 let types_to_check = supported_types.slice_iter(*$start);
489 let get_state: fn(&DeviceState) -> $state = $get_state;
490 let vals = get_state(&dev.state);
491 let old_vals = get_state(&dev.prev_state);
492 let get_value: fn($state, $typ) -> _ = $get_value;
493 for typ in types_to_check {
494 let prev = get_value(old_vals, typ);
495 let value = get_value(vals, typ);
496 if prev != value {
497 $start.0 = typ.0 + 1;
498 let ev = InputEvent::from(input_event {
499 time: *$time,
500 type_: EventType::$evtype.0,
501 code: typ.0,
502 value: value as _,
503 });
504 return Some(ev);
505 }
506 }
507 }
508 };
509 }
510 loop {
511 // check keys, then abs axes, then switches, then leds
512 match sync {
513 SyncState::KeyTypes { time, start } => {
514 try_compensate!(
515 time,
516 start: KeyCode,
517 KEY,
518 KeyTypes,
519 supported_keys,
520 &AttributeSetRef<KeyCode>,
521 |st| st.key_vals().unwrap(),
522 |vals, key| vals.contains(key)
523 );
524 *sync = SyncState::Absolutes {
525 time: *time,
526 start: AbsoluteAxisCode(0),
527 };
528 continue;
529 }
530 SyncState::Absolutes { time, start } => {
531 try_compensate!(
532 time,
533 start: AbsoluteAxisCode,
534 ABSOLUTE,
535 Absolutes,
536 supported_absolute_axes,
537 &[input_absinfo],
538 |st| st.abs_vals().unwrap(),
539 |vals, abs| vals[abs.0 as usize].value
540 );
541 *sync = SyncState::Switches {
542 time: *time,
543 start: SwitchCode(0),
544 };
545 continue;
546 }
547 SyncState::Switches { time, start } => {
548 try_compensate!(
549 time,
550 start: SwitchCode,
551 SWITCH,
552 Switches,
553 supported_switches,
554 &AttributeSetRef<SwitchCode>,
555 |st| st.switch_vals().unwrap(),
556 |vals, sw| vals.contains(sw)
557 );
558 *sync = SyncState::Leds {
559 time: *time,
560 start: LedCode(0),
561 };
562 continue;
563 }
564 SyncState::Leds { time, start } => {
565 try_compensate!(
566 time,
567 start: LedCode,
568 LED,
569 Leds,
570 supported_leds,
571 &AttributeSetRef<LedCode>,
572 |st| st.led_vals().unwrap(),
573 |vals, led| vals.contains(led)
574 );
575 let ev = InputEvent::from(input_event {
576 time: *time,
577 type_: EventType::SYNCHRONIZATION.0,
578 code: SynchronizationCode::SYN_REPORT.0,
579 value: 0,
580 });
581 *state = None;
582 return Some(ev);
583 }
584 }
585 }
586 }
587
588 impl Iterator for FetchEventsSynced<'_> {
589 type Item = InputEvent;
590 fn next(&mut self) -> Option<InputEvent> {
591 // first: check if we need to emit compensatory events due to a SYN_DROPPED we found in the
592 // last batch of blocks
593 if let Some(ev) = compensate_events(&mut self.sync, self.dev) {
594 self.dev.prev_state.process_event(ev);
595 return Some(ev);
596 }
597 let state = &mut self.dev.state;
598 let (res, consumed_to) = sync_events(&mut self.range, &self.dev.raw.event_buf, |ev| {
599 state.process_event(ev)
600 });
601 if let Some(end) = consumed_to {
602 self.consumed_to = end
603 }
604 match res {
605 Ok(ev) => Some(InputEvent::from(ev)),
606 Err(requires_sync) => {
607 if requires_sync {
608 self.dev.block_dropped = true;
609 }
610 None
611 }
612 }
613 }
614 }
615
616 impl Drop for FetchEventsSynced<'_> {
617 fn drop(&mut self) {
618 self.dev.raw.event_buf.drain(..self.consumed_to);
619 }
620 }
621
622 /// Err(true) means the device should sync the state with ioctl
623 #[inline]
624 fn sync_events(
625 range: &mut std::ops::Range<usize>,
626 event_buf: &[input_event],
627 mut handle_event: impl FnMut(InputEvent),
628 ) -> (Result<input_event, bool>, Option<usize>) {
629 let mut consumed_to = None;
630 let res = 'outer: loop {
631 if let Some(idx) = range.next() {
632 // we're going through and emitting the events of a block that we checked
633 break Ok(event_buf[idx]);
634 }
635 // find the range of this new block: look for a SYN_REPORT
636 let block_start = range.end;
637 let mut block_dropped = false;
638 for (i, ev) in event_buf.iter().enumerate().skip(block_start) {
639 let ev = InputEvent::from(*ev);
640 match ev.destructure() {
641 EventSummary::Synchronization(_, SynchronizationCode::SYN_DROPPED, _) => {
642 block_dropped = true;
643 }
644 EventSummary::Synchronization(_, SynchronizationCode::SYN_REPORT, _) => {
645 consumed_to = Some(i + 1);
646 if block_dropped {
647 *range = event_buf.len()..event_buf.len();
648 break 'outer Err(true);
649 } else {
650 *range = block_start..i + 1;
651 continue 'outer;
652 }
653 }
654 _ => handle_event(ev),
655 }
656 }
657 break Err(false);
658 };
659 (res, consumed_to)
660 }
661
662 impl fmt::Display for Device {
663 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
664 writeln!(f, "{}:", self.name().unwrap_or("Unnamed device"))?;
665 let (maj, min, pat) = self.driver_version();
666 writeln!(f, " Driver version: {maj}.{min}.{pat}")?;
667 if let Some(ref phys) = self.physical_path() {
668 writeln!(f, " Physical address: {phys:?}")?;
669 }
670 if let Some(ref uniq) = self.unique_name() {
671 writeln!(f, " Unique name: {uniq:?}")?;
672 }
673
674 let id = self.input_id();
675
676 writeln!(f, " Bus: {}", id.bus_type())?;
677 writeln!(f, " Vendor: {:#x}", id.vendor())?;
678 writeln!(f, " Product: {:#x}", id.product())?;
679 writeln!(f, " Version: {:#x}", id.version())?;
680 writeln!(f, " Properties: {:?}", self.properties())?;
681
682 if let (Some(supported_keys), Some(key_vals)) =
683 (self.supported_keys(), self.state.key_vals())
684 {
685 writeln!(f, " KeyTypes supported:")?;
686 for key in supported_keys.iter() {
687 let key_idx = key.code() as usize;
688 writeln!(
689 f,
690 " {:?} ({}index {})",
691 key,
692 if key_vals.contains(key) {
693 "pressed, "
694 } else {
695 ""
696 },
697 key_idx
698 )?;
699 }
700 }
701
702 if let Some(supported_relative) = self.supported_relative_axes() {
703 writeln!(f, " Relative Axes: {supported_relative:?}")?;
704 }
705
706 if let (Some(supported_abs), Some(abs_vals)) =
707 (self.supported_absolute_axes(), &self.state.abs_vals)
708 {
709 writeln!(f, " Absolute Axes:")?;
710 for abs in supported_abs.iter() {
711 writeln!(
712 f,
713 " {:?} ({:?}, index {})",
714 abs, abs_vals[abs.0 as usize], abs.0
715 )?;
716 }
717 }
718
719 if let Some(supported_misc) = self.misc_properties() {
720 writeln!(f, " Miscellaneous capabilities: {supported_misc:?}")?;
721 }
722
723 if let (Some(supported_switch), Some(switch_vals)) =
724 (self.supported_switches(), self.state.switch_vals())
725 {
726 writeln!(f, " Switches:")?;
727 for sw in supported_switch.iter() {
728 writeln!(
729 f,
730 " {:?} ({:?}, index {})",
731 sw,
732 switch_vals.contains(sw),
733 sw.0
734 )?;
735 }
736 }
737
738 if let (Some(supported_led), Some(led_vals)) =
739 (self.supported_leds(), self.state.led_vals())
740 {
741 writeln!(f, " LEDs:")?;
742 for led in supported_led.iter() {
743 writeln!(
744 f,
745 " {:?} ({:?}, index {})",
746 led,
747 led_vals.contains(led),
748 led.0
749 )?;
750 }
751 }
752
753 if let Some(supported_snd) = self.supported_sounds() {
754 write!(f, " Sounds:")?;
755 for snd in supported_snd.iter() {
756 writeln!(f, " {:?} (index {})", snd, snd.0)?;
757 }
758 }
759
760 // if let Some(rep) = self.rep {
761 // writeln!(f, " Repeats: {:?}", rep)?;
762 // }
763
764 let evs = self.supported_events();
765
766 if evs.contains(EventType::FORCEFEEDBACK) {
767 writeln!(f, " Force Feedback supported")?;
768 }
769
770 if evs.contains(EventType::POWER) {
771 writeln!(f, " Power supported")?;
772 }
773
774 if evs.contains(EventType::FORCEFEEDBACKSTATUS) {
775 writeln!(f, " Force Feedback status supported")?;
776 }
777
778 Ok(())
779 }
780 }
781
782 #[cfg(feature = "tokio")]
783 mod tokio_stream {
784 use super::*;
785
786 use std::future::poll_fn;
787 use std::task::{ready, Context, Poll};
788 use tokio::io::unix::AsyncFd;
789
790 /// An asynchronous stream of input events.
791 ///
792 /// This can be used by calling [`stream.next_event().await?`](Self::next_event), or if you
793 /// need to pass it as a stream somewhere, the [`futures::Stream`](Stream) implementation.
794 /// There's also a lower-level [`Self::poll_event`] function if you need to fetch an event from
795 /// inside a `Future::poll` impl.
796 pub struct EventStream {
797 device: AsyncFd<Device>,
798 event_range: std::ops::Range<usize>,
799 consumed_to: usize,
800 sync: Option<SyncState>,
801 }
802 impl Unpin for EventStream {}
803
804 impl EventStream {
805 pub(crate) fn new(device: Device) -> io::Result<Self> {
806 device.set_nonblocking(true)?;
807 let device = AsyncFd::new(device)?;
808 Ok(Self {
809 device,
810 event_range: 0..0,
811 consumed_to: 0,
812 sync: None,
813 })
814 }
815
816 /// Returns a reference to the underlying device
817 pub fn device(&self) -> &Device {
818 self.device.get_ref()
819 }
820
821 /// Returns a mutable reference to the underlying device
822 pub fn device_mut(&mut self) -> &mut Device {
823 self.device.get_mut()
824 }
825
826 /// Try to wait for the next event in this stream. Any errors are likely to be fatal, i.e.
827 /// any calls afterwards will likely error as well.
828 pub async fn next_event(&mut self) -> io::Result<InputEvent> {
829 poll_fn(|cx| self.poll_event(cx)).await
830 }
831
832 /// A lower-level function for directly polling this stream.
833 pub fn poll_event(&mut self, cx: &mut Context<'_>) -> Poll<io::Result<InputEvent>> {
834 'outer: loop {
835 let dev = self.device.get_mut();
836 if let Some(ev) = compensate_events(&mut self.sync, dev) {
837 return Poll::Ready(Ok(ev));
838 }
839 let state = &mut dev.state;
840 let (res, consumed_to) =
841 sync_events(&mut self.event_range, &dev.raw.event_buf, |ev| {
842 state.process_event(ev)
843 });
844 if let Some(end) = consumed_to {
845 self.consumed_to = end
846 }
847 match res {
848 Ok(ev) => return Poll::Ready(Ok(InputEvent::from(ev))),
849 Err(requires_sync) => {
850 if requires_sync {
851 dev.block_dropped = true;
852 }
853 }
854 }
855 dev.raw.event_buf.drain(..self.consumed_to);
856 self.consumed_to = 0;
857
858 loop {
859 let mut guard = ready!(self.device.poll_read_ready_mut(cx))?;
860
861 let res = guard.try_io(|device| device.get_mut().fetch_events_inner());
862 match res {
863 Ok(res) => {
864 self.sync = res?;
865 self.event_range = 0..0;
866 continue 'outer;
867 }
868 Err(_would_block) => continue,
869 }
870 }
871 }
872 }
873 }
874
875 #[cfg(feature = "stream-trait")]
876 impl futures_core::Stream for EventStream {
877 type Item = io::Result<InputEvent>;
878 fn poll_next(
879 self: std::pin::Pin<&mut Self>,
880 cx: &mut Context<'_>,
881 ) -> Poll<Option<Self::Item>> {
882 self.get_mut().poll_event(cx).map(Some)
883 }
884 }
885 }
886 #[cfg(feature = "tokio")]
887 pub use tokio_stream::EventStream;
888
889 #[cfg(test)]
890 mod tests {
891 use super::*;
892
893 fn result_events_iter(
894 events: &[input_event],
895 ) -> impl Iterator<Item = Result<input_event, ()>> + '_ {
896 let mut range = 0..0;
897 std::iter::from_fn(move || {
898 let (res, _) = sync_events(&mut range, events, |_| {});
899 match res {
900 Ok(x) => Some(Ok(x)),
901 Err(true) => Some(Err(())),
902 Err(false) => None,
903 }
904 })
905 }
906
907 fn events_iter(events: &[input_event]) -> impl Iterator<Item = input_event> + '_ {
908 result_events_iter(events).flatten()
909 }
910
911 #[allow(non_upper_case_globals)]
912 const time: libc::timeval = libc::timeval {
913 tv_sec: 0,
914 tv_usec: 0,
915 };
916 const KEY4: input_event = input_event {
917 time,
918 type_: EventType::KEY.0,
919 code: KeyCode::KEY_4.0,
920 value: 1,
921 };
922 const REPORT: input_event = input_event {
923 time,
924 type_: EventType::SYNCHRONIZATION.0,
925 code: SynchronizationCode::SYN_REPORT.0,
926 value: 0,
927 };
928 const DROPPED: input_event = input_event {
929 code: SynchronizationCode::SYN_DROPPED.0,
930 ..REPORT
931 };
932
933 #[test]
934 fn test_sync_impl() {
935 itertools::assert_equal(events_iter(&[]), vec![]);
936 itertools::assert_equal(events_iter(&[KEY4]), vec![]);
937 itertools::assert_equal(events_iter(&[KEY4, REPORT]), vec![KEY4, REPORT]);
938 itertools::assert_equal(events_iter(&[KEY4, REPORT, KEY4]), vec![KEY4, REPORT]);
939 itertools::assert_equal(
940 result_events_iter(&[KEY4, REPORT, KEY4, DROPPED, REPORT]),
941 vec![Ok(KEY4), Ok(REPORT), Err(())],
942 );
943 }
944
945 #[test]
946 fn test_iter_consistency() {
947 // once it sees a SYN_DROPPED, it shouldn't mark the block after it as consumed even if we
948 // keep calling the iterator like an idiot
949 let evs = &[KEY4, REPORT, DROPPED, REPORT, KEY4, REPORT, KEY4];
950 let mut range = 0..0;
951 let mut next = || sync_events(&mut range, evs, |_| {});
952 assert_eq!(next(), (Ok(KEY4), Some(2)));
953 assert_eq!(next(), (Ok(REPORT), None));
954 assert_eq!(next(), (Err(true), Some(4)));
955 assert_eq!(next(), (Err(false), None));
956 assert_eq!(next(), (Err(false), None));
957 assert_eq!(next(), (Err(false), None));
958 }
959 }