use crate::{device::DeviceWrapper, InputEvent};
use libc::c_int;
use std::io;
use std::os::unix::io::RawFd;
use crate::util::*;
use evdev_sys as raw;
pub struct UInputDevice {
raw: *mut raw::libevdev_uinput,
}
unsafe impl Sync for UInputDevice {}
unsafe impl Send for UInputDevice {}
impl UInputDevice {
fn raw(&self) -> *mut raw::libevdev_uinput {
self.raw
}
pub fn create_from_device<T: DeviceWrapper>(device: &T) -> io::Result<UInputDevice> {
let mut libevdev_uinput = std::ptr::null_mut();
let result = unsafe {
raw::libevdev_uinput_create_from_device(
device.raw(),
raw::LIBEVDEV_UINPUT_OPEN_MANAGED,
&mut libevdev_uinput,
)
};
match result {
0 => Ok(UInputDevice {
raw: libevdev_uinput,
}),
error => Err(io::Error::from_raw_os_error(-error)),
}
}
pub fn devnode(&self) -> Option<&str> {
unsafe { ptr_to_str(raw::libevdev_uinput_get_devnode(self.raw())) }
}
pub fn syspath(&self) -> Option<&str> {
unsafe { ptr_to_str(raw::libevdev_uinput_get_syspath(self.raw())) }
}
pub fn as_fd(&self) -> Option<RawFd> {
match unsafe { raw::libevdev_uinput_get_fd(self.raw()) } {
0 => None,
result => Some(result),
}
}
#[deprecated(
since = "0.5.0",
note = "Prefer `as_fd`. Some function names were changed so they
more closely match their type signature. See issue 42 for discussion
https://github.com/ndesh26/evdev-rs/issues/42"
)]
pub fn fd(&self) -> Option<RawFd> {
self.as_fd()
}
pub fn write_event(&self, event: &InputEvent) -> io::Result<()> {
let (ev_type, ev_code) = event_code_to_int(&event.event_code);
let ev_value = event.value as c_int;
let result = unsafe {
raw::libevdev_uinput_write_event(self.raw(), ev_type, ev_code, ev_value)
};
match result {
0 => Ok(()),
error => Err(io::Error::from_raw_os_error(-error)),
}
}
}
impl Drop for UInputDevice {
fn drop(&mut self) {
unsafe {
raw::libevdev_uinput_destroy(self.raw());
}
}
}
impl std::fmt::Debug for UInputDevice {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.debug_struct("UInputDevice")
.field("devnode", &self.devnode())
.finish()
}
}