rusty-keys/src/device/device.rs

87 lines
1.8 KiB
Rust
Raw Normal View History

2016-04-24 22:32:24 -04:00
use std::{mem, ptr, slice};
2017-11-16 23:21:21 -05:00
use libc::{timeval, gettimeofday, input_event, c_int};
2016-04-24 22:32:24 -04:00
use nix::unistd;
use ffi::*;
2017-09-01 00:24:35 -04:00
use {Result as Res};
2016-04-24 22:32:24 -04:00
2016-04-25 11:57:45 -04:00
/// The virtual device.
2016-04-24 22:32:24 -04:00
pub struct Device {
fd: c_int,
}
impl Device {
2016-04-25 11:57:45 -04:00
/// Wrap a file descriptor in a `Device`.
2016-04-24 22:32:24 -04:00
pub fn new(fd: c_int) -> Self {
Device {
fd: fd
}
}
2016-04-30 16:54:02 -04:00
#[doc(hidden)]
pub fn write(&self, kind: c_int, code: c_int, value: c_int) -> Res<()> {
2017-09-22 23:57:26 -04:00
let mut event = input_event {
time: timeval { tv_sec: 0, tv_usec: 0 },
type_: kind as u16,
code: code as u16,
value: value as i32,
};
2016-04-24 22:32:24 -04:00
2017-09-22 23:57:26 -04:00
self.write_event(&mut event)
2017-09-08 01:16:34 -04:00
}
#[doc(hidden)]
2017-09-22 23:57:26 -04:00
pub fn write_event(&self, event: &mut input_event) -> Res<()> {
2017-09-08 01:16:34 -04:00
unsafe {
2016-04-24 22:32:24 -04:00
gettimeofday(&mut event.time, ptr::null_mut());
2017-09-22 23:57:26 -04:00
let ptr = event as *const _ as *const u8;
let size = mem::size_of_val(event);
2016-04-24 22:32:24 -04:00
try!(unistd::write(self.fd, slice::from_raw_parts(ptr, size)));
}
Ok(())
}
2016-04-25 11:57:45 -04:00
/// Synchronize the device.
pub fn synchronize(&self) -> Res<()> {
2016-04-24 22:32:24 -04:00
self.write(EV_SYN, SYN_REPORT, 0)
}
2016-05-07 10:38:59 -04:00
/// Send an event.
pub fn send(&self, kind: c_int, code: c_int, value: i32) -> Res<()> {
2017-09-01 00:24:35 -04:00
self.write(kind, code, value)
2016-05-07 10:38:59 -04:00
}
2016-04-25 11:57:45 -04:00
/// Send a press event.
pub fn press(&self, kind: c_int, code: c_int) -> Res<()> {
2017-09-01 00:24:35 -04:00
self.write(kind, code, 1)
2016-04-24 22:32:24 -04:00
}
2016-04-25 11:57:45 -04:00
/// Send a release event.
pub fn release(&self, kind: c_int, code: c_int) -> Res<()> {
2017-09-01 00:24:35 -04:00
self.write(kind, code, 0)
2016-04-24 22:32:24 -04:00
}
2016-04-25 11:57:45 -04:00
/// Send a press and release event.
pub fn click(&self, kind: c_int, code: c_int) -> Res<()> {
2017-09-01 00:24:35 -04:00
try!(self.press(kind, code));
try!(self.release(kind, code));
2016-04-25 11:12:11 -04:00
Ok(())
}
2016-04-25 11:57:45 -04:00
/// Send a relative or absolute positioning event.
pub fn position(&self, kind: c_int, code: c_int, value: i32) -> Res<()> {
2017-09-01 00:24:35 -04:00
self.write(kind, code, value)
2016-04-24 22:32:24 -04:00
}
}
impl Drop for Device {
fn drop(&mut self) {
unsafe {
2017-09-01 00:24:35 -04:00
ui_dev_destroy(self.fd).unwrap();
2016-04-24 22:32:24 -04:00
}
}
}