rusty-keys/src/main.rs

217 lines
6.9 KiB
Rust
Raw Normal View History

2017-09-21 23:27:49 -04:00
extern crate rusty_keys;
2017-09-01 00:24:35 -04:00
extern crate uinput_sys as ffi;
2017-09-08 01:16:34 -04:00
extern crate libc;
extern crate getopts;
2017-11-15 02:39:03 -05:00
extern crate inotify;
2017-09-08 01:16:34 -04:00
2017-11-16 23:21:21 -05:00
use rusty_keys::{KeyMaps, Device, InputDevice, Result};
2017-09-01 00:24:35 -04:00
use ffi::*;
2017-11-16 23:21:21 -05:00
use libc::input_event;
2017-09-08 01:16:34 -04:00
use std::process::{exit, Command};
2017-11-16 23:21:21 -05:00
use std::{env, thread};
use std::sync::mpsc;
use std::sync::mpsc::Sender;
2017-09-08 01:16:34 -04:00
use getopts::Options;
2017-11-15 02:39:03 -05:00
use inotify::{
EventMask,
Inotify,
WatchMask,
};
2017-09-08 01:16:34 -04:00
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
2017-09-19 01:46:36 -04:00
const EV_KEY_U16: u16 = EV_KEY as u16;
2017-09-08 01:16:34 -04:00
#[derive(Debug)]
struct Config {
device_files: Vec<String>,
2017-09-22 00:30:56 -04:00
config_file: String
2017-09-08 01:16:34 -04:00
}
impl Config {
fn new(device_files: Vec<String>, config_file: String) -> Self {
Config { device_files: device_files, config_file: config_file }
2017-09-08 01:16:34 -04:00
}
}
fn main() {
2017-11-16 23:21:21 -05:00
let ret = main_res();
if let Err(e) = ret {
println!("fatal error: {}", e);
}
}
fn main_res() -> Result<()> {
2017-09-08 01:16:34 -04:00
let config = parse_args();
2017-09-22 00:30:56 -04:00
//println!("Config: {:?}", config);
2017-11-15 02:39:03 -05:00
let key_map = KeyMaps::key_map();
2017-11-15 22:59:17 -05:00
//println!("key_map: {:?}", key_map);
let device = rusty_keys::open("/dev/uinput")
.or_else(|_| rusty_keys::open("/dev/input/uinput"))
.or_else(|_| rusty_keys::default())?
.name("rusty-keys")?
.event(key_map.values())?
.create()?;
let mut key_map = KeyMaps::from_cfg(&key_map, &config.config_file);
//println!("keymaps: {:?}", keymaps);
2017-11-16 22:16:13 -05:00
if config.device_files.len() == 1 {
// shortcut, don't bother with threads
let mut input_device = InputDevice::open(&config.device_files[0])?;
input_device.grab()?;
2017-11-16 22:16:13 -05:00
loop {
let event = input_device.read_event()?;
send_event(&mut key_map, event, &device)?
2017-11-15 02:39:03 -05:00
}
} else {
2017-11-16 22:16:13 -05:00
// start up some intra thread communication
let (tx, rx) = mpsc::channel();
if config.device_files.len() > 0 {
// we only want to operate on device files sent in then quit
for device_file in config.device_files.iter() {
let device_file = device_file.clone();
let tx = tx.clone();
thread::spawn(move || {
let ret = spawn_map_thread(tx, &device_file);
if let Err(e) = ret {
println!("mapping for {} ended due to error: {}", device_file, e);
}
});
}
} else {
let tx = tx.clone();
thread::spawn(move || {
// we want to wait forever starting new threads for any new keyboard devices
let mut inotify = Inotify::init().expect("Failed to initialize inotify");
2017-11-15 02:39:03 -05:00
2017-11-16 22:16:13 -05:00
inotify.add_watch("/dev/input/", WatchMask::CREATE).expect("Failed to add inotify watch");
2017-11-15 02:39:03 -05:00
2017-11-16 22:16:13 -05:00
let device_files = get_keyboard_device_filenames();
println!("Detected devices: {:?}", device_files);
for device_file in device_files.iter() {
inotify_spawn_thread(&tx, device_file);
}
2017-11-15 02:39:03 -05:00
2017-11-16 22:16:13 -05:00
let mut buffer = [0u8; 4096];
loop {
let events = inotify.read_events_blocking(&mut buffer);
if let Ok(events) = events {
for event in events {
if !event.mask.contains(EventMask::ISDIR) {
if let Some(device_file) = event.name.and_then(|name|name.to_str()) {
// check if this is an eligible keyboard device
let device_files = get_keyboard_device_filenames();
if !device_files.contains(&device_file.to_string()) {
continue;
}
println!("starting mapping thread for: {}", device_file);
inotify_spawn_thread(&tx, device_file.clone());
}
2017-11-15 02:39:03 -05:00
}
2017-11-15 22:03:52 -05:00
}
2017-11-15 02:39:03 -05:00
}
}
2017-11-16 22:16:13 -05:00
});
}
drop(tx); // drop our last one, so when the threads finish, everything stops
// process all events
for event in rx {
send_event(&mut key_map, event, &device)?
}
2017-09-08 01:16:34 -04:00
}
Ok(())
}
2017-09-08 01:16:34 -04:00
2017-11-16 22:16:13 -05:00
fn send_event(key_map: &mut KeyMaps, mut event: input_event, device: &Device) -> Result<()> {
if event.type_ == EV_KEY_U16 {
key_map.send_event(&mut event, &device)?
} else {
device.write_event(&mut event)?
}
Ok(())
}
fn inotify_spawn_thread(tx: &Sender<input_event>, device_file: &str) {
2017-11-15 22:03:52 -05:00
let mut filename = "/dev/input/".to_string();
filename.push_str(&device_file);
let tx = tx.clone();
2017-11-15 22:03:52 -05:00
thread::spawn(move || {
let ret = spawn_map_thread(tx, &filename);
2017-11-15 22:03:52 -05:00
if let Err(e) = ret {
println!("mapping for {} ended due to error: {}", filename, e);
}
});
}
fn spawn_map_thread(tx: Sender<input_event>, device_file: &str) -> Result<()> {
2017-11-15 02:39:03 -05:00
let mut input_device = InputDevice::open(device_file)?;
input_device.grab()?;
2017-11-15 00:39:00 -05:00
loop {
let event = input_device.read_event()?;
tx.send(event)?
2017-11-15 00:39:00 -05:00
}
}
2017-09-08 01:16:34 -04:00
fn parse_args() -> Config {
fn print_usage(program: &str, opts: Options) {
2017-11-15 01:42:54 -05:00
let brief = format!("Usage: {} [options] [device_files...]", program);
2017-09-08 01:16:34 -04:00
println!("{}", opts.usage(&brief));
}
let args: Vec<_> = env::args().collect();
let mut opts = Options::new();
opts.optflag("h", "help", "prints this help message");
opts.optflag("v", "version", "prints the version");
2017-11-17 00:03:45 -05:00
opts.optopt("c", "config", "specify the keymap config file to use (default: /etc/rusty-keys/keymap.toml)", "FILE");
2017-09-08 01:16:34 -04:00
2017-11-15 01:42:54 -05:00
let matches = opts.parse(&args[1..]);
if matches.is_err() {
print_usage(&args[0], opts);
exit(0);
}
let matches = matches.unwrap();
2017-09-08 01:16:34 -04:00
if matches.opt_present("h") {
print_usage(&args[0], opts);
exit(0);
}
if matches.opt_present("v") {
2017-09-22 00:30:56 -04:00
println!("rusty-keys {}", VERSION);
2017-09-08 01:16:34 -04:00
exit(0);
}
2017-11-15 22:03:52 -05:00
let config_file = matches.opt_str("c").unwrap_or("/etc/rusty-keys/keymap.toml".to_owned());
2017-11-15 01:42:54 -05:00
2017-11-15 02:39:03 -05:00
Config::new(matches.free, config_file)
2017-09-08 01:16:34 -04:00
}
// Detects and returns the name of the keyboard device file. This function uses
// the fact that all device information is shown in /proc/bus/input/devices and
// the keyboard device file should always have an EV of 120013
fn get_keyboard_device_filenames() -> Vec<String> {
let command_str = "grep -E 'Handlers|EV' /proc/bus/input/devices | grep -B1 120013 | grep -Eo event[0-9]+".to_string();
2017-11-15 01:42:54 -05:00
let res = Command::new("sh").arg("-c").arg(command_str).output();
if res.is_err() {
return Vec::new();
}
let res = res.unwrap();
let res_str = std::str::from_utf8(&res.stdout).unwrap_or("");
2017-09-08 01:16:34 -04:00
let mut filenames = Vec::new();
for file in res_str.trim().split('\n') {
2017-11-15 02:39:03 -05:00
filenames.push(file.to_string());
2017-09-08 01:16:34 -04:00
}
filenames
}