rusty_keys/device/
device.rs1use std::{mem, ptr, slice};
2use libc::c_int;
3use libc::{timeval, gettimeofday, input_event};
4use nix::unistd;
5use ffi::*;
6use {Result as Res};
7
8pub struct Device {
10 fd: c_int,
11}
12
13impl Device {
14 pub fn new(fd: c_int) -> Self {
16 Device {
17 fd: fd
18 }
19 }
20
21 #[doc(hidden)]
22 pub fn write(&mut self, kind: c_int, code: c_int, value: c_int) -> Res<()> {
23 let mut event = input_event {
24 time: timeval { tv_sec: 0, tv_usec: 0 },
25 type_: kind as u16,
26 code: code as u16,
27 value: value as i32,
28 };
29
30 self.write_event(&mut event)
31 }
32
33 #[doc(hidden)]
34 pub fn write_event(&self, event: &mut input_event) -> Res<()> {
35 unsafe {
36 gettimeofday(&mut event.time, ptr::null_mut());
37
38 let ptr = event as *const _ as *const u8;
39 let size = mem::size_of_val(event);
40
41 try!(unistd::write(self.fd, slice::from_raw_parts(ptr, size)));
42 }
43
44 Ok(())
45 }
46
47 pub fn synchronize(&mut self) -> Res<()> {
49 self.write(EV_SYN, SYN_REPORT, 0)
50 }
51
52 pub fn send(&mut self, kind: c_int, code: c_int, value: i32) -> Res<()> {
54 self.write(kind, code, value)
55 }
56
57 pub fn press(&mut self, kind: c_int, code: c_int) -> Res<()> {
59 self.write(kind, code, 1)
60 }
61
62 pub fn release(&mut self, kind: c_int, code: c_int) -> Res<()> {
64 self.write(kind, code, 0)
65 }
66
67 pub fn click(&mut self, kind: c_int, code: c_int) -> Res<()> {
69 try!(self.press(kind, code));
70 try!(self.release(kind, code));
71
72 Ok(())
73 }
74
75 pub fn position(&mut self, kind: c_int, code: c_int, value: i32) -> Res<()> {
77 self.write(kind, code, value)
78 }
79}
80
81impl Drop for Device {
82 fn drop(&mut self) {
83 unsafe {
84 ui_dev_destroy(self.fd).unwrap();
85 }
86 }
87}