device watcher improvements

pull/78/head
Roland Fredenhagen 2 years ago
parent aabb1ffcef
commit c23a8cf748
No known key found for this signature in database
GPG Key ID: 094AF99241035EB6

19
Cargo.lock generated

@ -26,6 +26,12 @@ dependencies = [
"memchr",
]
[[package]]
name = "anyhow"
version = "1.0.54"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a99269dff3bc004caa411f38845c20303f1e393ca2bd6581576fa3a7f59577d"
[[package]]
name = "async-io"
version = "1.6.0"
@ -226,6 +232,17 @@ dependencies = [
"syn",
]
[[package]]
name = "derive-where"
version = "1.0.0-rc.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f22a5b69cac4a8cc6efe0930b5a29ab0a0233e5a131af99191cc892c3aaf8829"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "enumflags2"
version = "0.6.4"
@ -1044,8 +1061,10 @@ dependencies = [
name = "xremap"
version = "0.2.5"
dependencies = [
"anyhow",
"clap",
"clap_complete",
"derive-where",
"env_logger",
"evdev",
"indoc",

@ -7,8 +7,10 @@ license = "MIT"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
anyhow = "1.0.53"
clap = { version = "3.0.14", features = ["derive"] }
clap_complete = "3.0.6"
derive-where = "1.0.0-rc.2"
env_logger = "0.9.0"
evdev = "0.11.3"
indoc = "1.0"

@ -14,7 +14,7 @@ extern crate serde_yaml;
use keymap::Keymap;
use modmap::Modmap;
use serde::Deserialize;
use std::{error, fs, path::Path};
use std::{error, fs, path::Path, time::SystemTime};
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
@ -23,10 +23,24 @@ pub struct Config {
pub modmap: Vec<Modmap>,
#[serde(default = "Vec::new")]
pub keymap: Vec<Keymap>,
#[serde(skip)]
pub modify_time: Option<SystemTime>,
}
pub fn load_config(filename: &Path) -> Result<Config, Box<dyn error::Error>> {
let yaml = fs::read_to_string(&filename)?;
let config: Config = serde_yaml::from_str(&yaml)?;
let mut config: Config = serde_yaml::from_str(&yaml)?;
config.modify_time = filename.metadata()?.modified().ok();
Ok(config)
}
// pub fn config_watcher(watch: bool, file: &Path) -> anyhow::Result<Option<Inotify>> {
// if watch {
// let inotify = Inotify::init(InitFlags::IN_NONBLOCK)?;
// inotify.add_watch(file.parent().expect("config file has a parent directory"), AddWatchFlags::IN_CREATE)?;
// inotify.add_watch(file, AddWatchFlags::IN_MODIFY)?;
// Ok(Some(inotify))
// } else {
// Ok(None)
// }
// }

@ -1,14 +1,18 @@
extern crate evdev;
extern crate nix;
use anyhow::bail;
use derive_where::derive_where;
use evdev::uinput::{VirtualDevice, VirtualDeviceBuilder};
use evdev::{AttributeSet, Device, Key, RelativeAxisType};
use evdev::{AttributeSet, Device, FetchEventsSynced, Key, RelativeAxisType};
use nix::sys::inotify::{AddWatchFlags, InitFlags, Inotify};
use std::collections::HashMap;
use std::error::Error;
use std::fs::read_dir;
use std::os::unix::ffi::OsStrExt;
use std::process;
use std::os::unix::prelude::AsRawFd;
use std::path::PathBuf;
use std::{io, process};
static MOUSE_BTNS: [&str; 20] = [
"BTN_MISC",
@ -52,16 +56,16 @@ pub fn output_device() -> Result<VirtualDevice, Box<dyn Error>> {
relative_axes.insert(RelativeAxisType::REL_MISC);
let device = VirtualDeviceBuilder::new()?
.name(&current_device_name())
.name(&InputDevice::current_name())
.with_keys(&keys)?
.with_relative_axes(&relative_axes)?
.build()?;
Ok(device)
}
pub fn device_watcher(watch: bool) -> Result<Option<Inotify>, Box<dyn Error>> {
pub fn device_watcher(watch: bool) -> anyhow::Result<Option<Inotify>> {
if watch {
let inotify = Inotify::init(InitFlags::empty())?;
let inotify = Inotify::init(InitFlags::IN_NONBLOCK)?;
inotify.add_watch("/dev/input", AddWatchFlags::IN_CREATE | AddWatchFlags::IN_ATTRIB)?;
Ok(Some(inotify))
} else {
@ -69,22 +73,17 @@ pub fn device_watcher(watch: bool) -> Result<Option<Inotify>, Box<dyn Error>> {
}
}
pub fn input_devices(
pub fn get_input_devices(
device_opts: &[String],
ignore_opts: &[String],
watch: bool,
) -> Result<Vec<Device>, Box<dyn Error>> {
let mut path_devices = list_devices()?;
let mut paths: Vec<String> = path_devices.keys().cloned().collect();
paths.sort_by(|a, b| device_index(a).partial_cmp(&device_index(b)).unwrap());
) -> anyhow::Result<HashMap<PathBuf, InputDevice>> {
let mut devices: Vec<_> = InputDevice::devices()?.collect();
devices.sort();
println!("Selecting devices from the following list:");
println!("{}", SEPARATOR);
for path in &paths {
if let Some(device) = path_devices.get(path) {
println!("{:18}: {}", path, device_name(device));
}
}
devices.iter().for_each(InputDevice::print);
println!("{}", SEPARATOR);
if device_opts.is_empty() {
@ -97,110 +96,154 @@ pub fn input_devices(
} else {
println!(", ignoring {:?}:", ignore_opts);
}
for path in &paths {
if let Some(device) = path_devices.get(path) {
let matched = if device_opts.is_empty() {
is_keyboard(device)
} else {
match_device(path, device, device_opts)
} && (ignore_opts.is_empty() || !match_device(path, device, ignore_opts));
if !matched {
path_devices.remove(path);
}
}
}
let devices: Vec<_> = devices
.into_iter()
// filter map needed for mutable access
// alternative is `Vec::retain_mut` whenever that gets stabilized
.filter_map(|mut device| {
// filter out any not matching devices and devices that error on grab
(device.is_input_device(device_opts, ignore_opts) && device.grab()).then(|| device)
})
.collect();
println!("{}", SEPARATOR);
if path_devices.is_empty() {
if devices.is_empty() {
if watch {
println!("warning: No device was selected, but --watch is waiting for new devices.");
} else {
return Err("No device was selected!".into());
bail!("No device was selected!");
}
} else {
for (path, device) in path_devices.iter() {
println!("{:18}: {}", path, device_name(device));
}
devices.iter().for_each(InputDevice::print);
}
println!("{}", SEPARATOR);
let mut devices: Vec<Device> = path_devices.into_values().collect();
for device in devices.iter_mut() {
device
.grab()
.map_err(|e| format!("Failed to grab device '{}': {}", device_name(device), e))?;
}
Ok(devices)
Ok(devices.into_iter().map(From::from).collect())
}
// We can't know the device path from evdev::enumerate(). So we re-implement it.
fn list_devices() -> Result<HashMap<String, Device>, Box<dyn Error>> {
let mut path_devices: HashMap<String, Device> = HashMap::new();
if let Ok(dev_input) = read_dir("/dev/input").as_mut() {
for entry in dev_input {
let path = entry?.path();
if let Some(fname) = path.file_name() {
if fname.as_bytes().starts_with(b"event") {
// Allow "Permission denied" when opening the current process's own device.
if let Ok(device) = Device::open(&path) {
if let Ok(path) = path.into_os_string().into_string() {
path_devices.insert(path, device);
}
}
}
}
#[derive_where(PartialEq, PartialOrd, Ord)]
pub struct InputDevice {
path: PathBuf,
#[derive_where(skip)]
device: Device,
}
impl Eq for InputDevice {}
impl TryFrom<PathBuf> for InputDevice {
type Error = io::Error;
fn try_from(path: PathBuf) -> Result<Self, Self::Error> {
let fname = path
.file_name()
.ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?;
if fname.as_bytes().starts_with(b"event") {
Ok(Self {
device: Device::open(&path)?,
path,
})
} else {
Err(io::ErrorKind::InvalidInput.into())
}
}
Ok(path_devices)
}
fn device_name(device: &Device) -> &str {
device.name().unwrap_or("<Unnamed device>")
impl From<InputDevice> for (PathBuf, InputDevice) {
fn from(device: InputDevice) -> Self {
(device.path.clone(), device)
}
}
fn device_index(path: &str) -> i32 {
path.trim_start_matches("/dev/input/event").parse::<i32>().unwrap()
impl AsRawFd for InputDevice {
fn as_raw_fd(&self) -> std::os::unix::prelude::RawFd {
self.device.as_raw_fd()
}
}
fn current_device_name() -> String {
format!("xremap pid={}", process::id())
/// Device Wrappers Abstractions
impl InputDevice {
pub fn grab(&mut self) -> bool {
if let Err(error) = self.device.grab() {
println!("Failed to grab device '{}' at '{}' due to: {error}", self.device_name(), self.path.display());
false
} else {
true
}
}
pub fn fetch_events(&mut self) -> io::Result<FetchEventsSynced> {
self.device.fetch_events()
}
fn device_name(&self) -> &str {
self.device.name().unwrap_or("<Unnamed device>")
}
}
fn match_device(path: &str, device: &Device, device_opts: &[String]) -> bool {
// Force unmatch its own device
if device_name(device) == current_device_name() {
return false;
impl InputDevice {
pub fn is_input_device(&self, device_filter: &[String], ignore_filter: &[String]) -> bool {
(if device_filter.is_empty() {
self.is_keyboard()
} else {
self.matches(device_filter)
}) && (ignore_filter.is_empty() || !self.matches(ignore_filter))
}
for device_opt in device_opts {
// Check exact matches for explicit selection
if path == device_opt || device_name(device) == device_opt {
return true;
}
// eventXX shorthand for /dev/input/eventXX
if device_opt.starts_with("event") && path == format!("/dev/input/{}", device_opt) {
return true;
// We can't know the device path from evdev::enumerate(). So we re-implement it.
fn devices() -> io::Result<impl Iterator<Item = InputDevice>> {
Ok(read_dir("/dev/input")?.filter_map(|entry| {
// Allow "Permission denied" when opening the current process's own device.
InputDevice::try_from(entry.ok()?.path()).ok()
}))
}
fn current_name() -> String {
format!("xremap pid={}", process::id())
}
fn matches(&self, filter: &[String]) -> bool {
// Force unmatch its own device
if self.device_name() == Self::current_name() {
return false;
}
// Allow partial matches for device names
if device_name(device).contains(device_opt) {
return true;
for device_opt in filter {
let device_opt = device_opt.as_str();
// Check exact matches for explicit selection
if self.path.as_os_str() == device_opt || self.device_name() == device_opt {
return true;
}
// eventXX shorthand for /dev/input/eventXX
if device_opt.starts_with("event")
&& self.path.file_name().expect("every device path has a file name") == device_opt
{
return true;
}
// Allow partial matches for device names
if self.device_name().contains(device_opt) {
return true;
}
}
false
}
false
}
fn is_keyboard(device: &Device) -> bool {
// Credit: https://github.com/mooz/xkeysnail/blob/bf3c93b4fe6efd42893db4e6588e5ef1c4909cfb/xkeysnail/input.py#L17-L32
match device.supported_keys() {
Some(keys) => {
keys.contains(Key::KEY_SPACE)
fn is_keyboard(&self) -> bool {
// Credit: https://github.com/mooz/xkeysnail/blob/bf3c93b4fe6efd42893db4e6588e5ef1c4909cfb/xkeysnail/input.py#L17-L32
match self.device.supported_keys() {
Some(keys) => {
keys.contains(Key::KEY_SPACE)
&& keys.contains(Key::KEY_A)
&& keys.contains(Key::KEY_Z)
// BTN_MOUSE
&& !keys.contains(Key::BTN_LEFT)
}
None => false,
}
None => false,
}
pub fn print(&self) {
println!("{:18}: {}", self.path.display(), self.device_name())
}
}
static SEPARATOR: &str = "------------------------------------------------------------------------------";
const SEPARATOR: &str = "------------------------------------------------------------------------------";

@ -1,18 +1,18 @@
use crate::config::Config;
use crate::device::{device_watcher, input_devices, output_device};
use crate::device::{device_watcher, get_input_devices, output_device};
use crate::event_handler::EventHandler;
use anyhow::{anyhow, bail, Context};
use clap::{AppSettings, ArgEnum, IntoApp, Parser};
use clap_complete::Shell;
use evdev::uinput::VirtualDevice;
use evdev::{Device, EventType};
use device::InputDevice;
use evdev::EventType;
use nix::libc::ENODEV;
use nix::sys::inotify::Inotify;
use nix::sys::select::select;
use nix::sys::select::FdSet;
use std::error::Error;
use std::io::stdout;
use std::os::unix::io::AsRawFd;
use std::path::PathBuf;
use std::process::exit;
mod client;
mod config;
@ -66,93 +66,115 @@ enum WatchTargets {
Config,
}
fn main() {
fn main() -> anyhow::Result<()> {
env_logger::init();
let Opts {
device,
ignore,
device: device_filter,
ignore: ignore_filter,
watch,
config,
completions,
} = Opts::parse();
if let Some(shell) = completions {
return clap_complete::generate(shell, &mut Opts::into_app(), "xremap", &mut stdout());
clap_complete::generate(shell, &mut Opts::into_app(), "xremap", &mut stdout());
return Ok(());
}
let config = config.expect("config is set, if not completions");
let config_path = config.expect("config is set, if not completions");
let config = match config::load_config(&config) {
let config = match config::load_config(&config_path) {
Ok(config) => config,
Err(e) => abort(&format!("Failed to load config '{}': {}", config.display(), e)),
Err(e) => bail!("Failed to load config '{}': {}", config_path.display(), e),
};
let watch_devices = watch.contains(&WatchTargets::Device);
// let watch_config = watch.contains(&WatchTargets::Config);
loop {
let output_device = match output_device() {
Ok(output_device) => output_device,
Err(e) => abort(&format!("Failed to prepare an output device: {}", e)),
};
let input_devices = match input_devices(&device, &ignore, watch_devices) {
Ok(input_devices) => input_devices,
Err(e) => abort(&format!("Failed to prepare input devices: {}", e)),
};
if let Err(e) = event_loop(output_device, input_devices, &config, watch_devices) {
if e.to_string().starts_with("No such device") {
println!("Found a removed device. Reselecting devices.");
continue;
}
abort(&format!("Error: {}", e));
}
}
}
fn event_loop(
output_device: VirtualDevice,
mut input_devices: Vec<Device>,
config: &Config,
watch: bool,
) -> Result<(), Box<dyn Error>> {
let watcher = device_watcher(watch)?;
let output_device = match output_device() {
Ok(output_device) => output_device,
Err(e) => bail!("Failed to prepare an output device: {}", e),
};
let mut handler = EventHandler::new(output_device);
let mut input_devices = match get_input_devices(&device_filter, &ignore_filter, watch_devices) {
Ok(input_devices) => input_devices,
Err(e) => bail!("Failed to prepare input devices: {}", e),
};
let device_watcher = device_watcher(watch_devices).context("Setting up device watcher")?;
// let config_watcher = config_watcher(watch_config, &config_path).context("Setting up config watcher")?;
let watchers: Vec<_> = device_watcher
.iter() /*.chain(config_watcher.iter())*/
.collect();
loop {
let readable_fds = select_readable(&input_devices, &watcher)?;
for input_device in &mut input_devices {
if readable_fds.contains(input_device.as_raw_fd()) {
for event in input_device.fetch_events()? {
if event.event_type() == EventType::KEY {
handler.on_event(event, config)?;
} else {
handler.send_event(event)?;
match 'event_loop: loop {
let readable_fds = select_readable(input_devices.values(), &watchers)?;
for input_device in input_devices.values_mut() {
if readable_fds.contains(input_device.as_raw_fd()) {
match input_device.fetch_events().map_err(|e| (e.raw_os_error(), e)) {
Err((Some(ENODEV), _)) => {
println!("Found a removed device. Reselecting devices.");
break 'event_loop Event::ReloadDevices;
}
Err((_, error)) => return Err(error).context("Error fetching input events"),
Ok(events) => {
for event in events {
if event.event_type() == EventType::KEY {
handler
.on_event(event, &config)
.map_err(|e| anyhow!("Failed handling {event:?}:\n {e:?}"))?;
} else {
handler.send_event(event)?;
}
}
}
}
}
}
}
if let Some(inotify) = watcher {
if readable_fds.contains(inotify.as_raw_fd()) {
println!("Detected device changes. Reselecting devices.");
return Ok(());
if let Some(inotify) = device_watcher {
if let Ok(events) = inotify.read_events() {
input_devices.extend(events.into_iter().filter_map(|event| {
event.name.and_then(|name| {
let path = PathBuf::from("/dev/input/").join(name);
let mut device = InputDevice::try_from(path).ok()?;
if device.is_input_device(&device_filter, &ignore_filter) && device.grab() {
device.print();
Some(device.into())
} else {
None
}
})
}))
}
}
} {
Event::ReloadDevices => {
input_devices = match get_input_devices(&device_filter, &ignore_filter, watch_devices) {
Ok(input_devices) => input_devices,
Err(e) => bail!("Failed to prepare input devices: {}", e),
};
} // Event::ReloadConfig => {
// todo!()
// }
}
}
}
fn select_readable(devices: &[Device], watcher: &Option<Inotify>) -> Result<FdSet, Box<dyn Error>> {
enum Event {
// ReloadConfig,
ReloadDevices,
}
fn select_readable<'a>(devices: impl Iterator<Item = &'a InputDevice>, watchers: &[&Inotify]) -> anyhow::Result<FdSet> {
let mut read_fds = FdSet::new();
for device in devices {
read_fds.insert(device.as_raw_fd());
}
if let Some(inotify) = watcher {
for inotify in watchers {
read_fds.insert(inotify.as_raw_fd());
}
select(None, &mut read_fds, None, None, None)?;
Ok(read_fds)
}
fn abort(message: &str) -> ! {
println!("{}", message);
exit(1);
}

Loading…
Cancel
Save