xremap 0.15.0

Dynamic key remapp for X and Wayland
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
extern crate evdev;
extern crate nix;

use anyhow::bail;
use derive_where::derive_where;
use evdev::uinput::VirtualDevice;
use evdev::{AttributeSet, BusType, Device, FetchEventsSynced, InputId, KeyCode as Key, RelativeAxisCode};
use log::debug;
use nix::sys::inotify::{AddWatchFlags, InitFlags, Inotify};
use std::collections::HashMap;
use std::error::Error;
#[cfg(feature = "udev")]
use std::fs::metadata;
use std::fs::{self, read_dir};
#[cfg(feature = "udev")]
use std::os::linux::fs::MetadataExt;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::prelude::AsRawFd;
use std::path::{Path, PathBuf};
use std::time::Duration;
use std::{io, process};
#[cfg(feature = "udev")]
use udev::DeviceType;

use crate::util::{evdev_enums_to_string, print_table};

pub static mut DEVICE_NAME: Option<String> = None;

// Credit: https://github.com/mooz/xkeysnail/blob/bf3c93b4fe6efd42893db4e6588e5ef1c4909cfb/xkeysnail/output.py#L10-L32
pub fn output_device(
    bus_type: Option<BusType>,
    enable_wheel: bool,
    vendor: u16,
    product: u16,
) -> Result<VirtualDevice, Box<dyn Error>> {
    let mut keys: AttributeSet<Key> = AttributeSet::new();
    for code in Key::KEY_RESERVED.code()..Key::BTN_TRIGGER_HAPPY40.code() {
        let key = Key::new(code);
        let name = format!("{key:?}");
        if name.starts_with("KEY_") || name.starts_with("BTN_") {
            keys.insert(key);
        }
    }

    let mut relative_axes: AttributeSet<RelativeAxisCode> = AttributeSet::new();
    relative_axes.insert(RelativeAxisCode::REL_X);
    relative_axes.insert(RelativeAxisCode::REL_Y);
    if enable_wheel {
        relative_axes.insert(RelativeAxisCode::REL_HWHEEL);
        relative_axes.insert(RelativeAxisCode::REL_WHEEL);
    }
    relative_axes.insert(RelativeAxisCode::REL_MISC);

    let device = VirtualDevice::builder()?
        // These are taken from https://docs.rs/evdev/0.12.0/src/evdev/uinput.rs.html#183-188
        .input_id(InputId::new(bus_type.unwrap_or(BusType::BUS_USB), vendor, product, 0x111))
        .name(&InputDevice::current_name())
        .with_keys(&keys)?
        .with_relative_axes(&relative_axes)?
        .build()?;
    Ok(device)
}

pub fn device_watcher(watch: bool) -> anyhow::Result<Option<Inotify>> {
    if watch {
        let inotify = Inotify::init(InitFlags::IN_NONBLOCK)?;
        inotify.add_watch("/dev/input", AddWatchFlags::IN_CREATE | AddWatchFlags::IN_ATTRIB)?;
        Ok(Some(inotify))
    } else {
        Ok(None)
    }
}

pub fn get_input_devices(
    device_opts: &[String],
    ignore_opts: &[String],
    mouse: bool,
    watch: bool,
) -> anyhow::Result<HashMap<PathBuf, InputDevice>> {
    let mut devices: Vec<_> = InputDevice::devices()?.collect();
    devices.sort();

    println!("Selecting devices from the following list:");
    println!("{SEPARATOR}");
    devices.iter().for_each(InputDevice::print);
    println!("{SEPARATOR}");

    if device_opts.is_empty() {
        if mouse {
            print!("Selected keyboards and mice automatically since --device options weren't specified");
        } else {
            print!("Selected keyboards automatically since --device options weren't specified");
        }
    } else {
        print!("Selected devices matching {device_opts:?}");
    };
    if ignore_opts.is_empty() {
        println!(":")
    } else {
        println!(", ignoring {ignore_opts:?}:");
    }

    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, mouse) && device.grab()).then_some(device)
        })
        .collect();

    println!("{SEPARATOR}");
    if devices.is_empty() {
        if watch {
            println!("warning: No device was selected, but --watch is waiting for new devices.");
        } else {
            bail!("No device was selected!");
        }
    } else {
        devices.iter().for_each(InputDevice::print);
    }
    println!("{SEPARATOR}");

    Ok(devices.into_iter().map(From::from).collect())
}

#[derive(Debug, Clone)]
pub struct InputDeviceInfo {
    pub name: String,
    pub path: PathBuf,
    pub product: u16,
    pub vendor: u16,
}

impl InputDeviceInfo {
    pub fn matches(&self, filter: &str) -> bool {
        // Check exact matches for explicit selection
        if self.path.as_os_str() == filter || self.name == filter {
            return true;
        }
        // eventXX shorthand for /dev/input/eventXX
        if filter.starts_with("event") && self.path.file_name().expect("every device path has a file name") == filter {
            return true;
        }
        if filter.starts_with("ids:") {
            let args = filter.split(':').collect::<Vec<&str>>();
            if args.len() == 3 {
                let vid = u16::from_str_radix(args[1].trim_start_matches("0x"), 16).unwrap_or(0);
                let pid = u16::from_str_radix(args[2].trim_start_matches("0x"), 16).unwrap_or(0);
                match (vid, pid) {
                    (0, 0) => {}
                    (v, 0) if v == self.vendor => {
                        return true;
                    }
                    (0, p) if p == self.product => {
                        return true;
                    }
                    (v, p) if v == self.vendor && p == self.product => {
                        return true;
                    }
                    (_, _) => {}
                }
            }
        }
        // Allow partial matches for device names
        if self.name.contains(filter) {
            return true;
        }
        // Match udev symlinks to actual physical device path
        if Path::new(filter).is_absolute() {
            if let Ok(resolved_filter) = fs::canonicalize(filter) {
                if self.path == resolved_filter {
                    return true;
                }
            }
        }

        #[cfg(feature = "udev")]
        {
            if filter.starts_with("props:") {
                if let Ok(meta) = metadata(&self.path) {
                    let args = filter.split(':').collect::<Vec<&str>>();
                    if args.len() == 3 {
                        if let Ok(ud) = udev::Device::from_devnum(DeviceType::Character, meta.st_rdev()) {
                            for _ in 0..10 {
                                if ud.is_initialized() {
                                    break;
                                }
                                std::thread::sleep(std::time::Duration::from_millis(10));
                            }
                            let props = ud.properties();
                            for p in props.filter(|p| p.name() == args[1]) {
                                if p.value() == args[2] {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
        }
        false
    }
}

#[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())
        }
    }
}

impl From<InputDevice> for (PathBuf, InputDevice) {
    fn from(device: InputDevice) -> Self {
        (device.path.clone(), device)
    }
}

impl AsRawFd for InputDevice {
    fn as_raw_fd(&self) -> std::os::unix::prelude::RawFd {
        self.device.as_raw_fd()
    }
}

/// Device Wrappers Abstractions
impl InputDevice {
    pub fn wait_for_all_keys_up(&self) -> io::Result<()> {
        for _ in 0..50 {
            let keys = self.device.get_key_state()?;

            if keys.iter().filter(|&key| key != Key::KEY_UNKNOWN).count() == 0 {
                return Ok(());
            }

            std::thread::sleep(Duration::from_millis(100));
        }

        Err(io::Error::new(io::ErrorKind::TimedOut, "Timed out waiting for keys to be released."))
    }

    pub fn grab(&mut self) -> bool {
        let result = self.wait_for_all_keys_up().and_then(|_| self.device.grab());

        match result {
            Ok(_) => true,
            Err(error) => {
                eprintln!(
                    "warning: Failed to grab device '{}' at '{}'. It may have been disconnected, have keys held down, or you may need to grant permissions. Error: {}",
                    self.device_name(),
                    self.path.display(),
                    error
                );
                false
            }
        }
    }

    pub fn ungrab(&mut self) {
        if let Err(error) = self.device.ungrab() {
            println!("Failed to ungrab device '{}' at '{}' due to: {error}", self.device_name(), self.path.display());
        }
    }

    pub fn fetch_events(&mut self) -> io::Result<FetchEventsSynced<'_>> {
        self.device.fetch_events()
    }

    pub fn device_name(&self) -> &str {
        self.device.name().unwrap_or("<Unnamed device>")
    }

    pub fn bus_type(&self) -> BusType {
        self.device.input_id().bus_type()
    }

    pub fn product(&self) -> u16 {
        self.device.input_id().product()
    }

    pub fn vendor(&self) -> u16 {
        self.device.input_id().vendor()
    }

    pub fn to_info(&self) -> InputDeviceInfo {
        InputDeviceInfo {
            name: self.device_name().into(),
            product: self.product(),
            vendor: self.vendor(),
            path: self.path.clone(),
        }
    }
}

impl InputDevice {
    pub fn is_input_device(&self, device_filter: &[String], ignore_filter: &[String], mouse: bool) -> bool {
        if self.device_name() == Self::current_name() {
            return false;
        }
        (if device_filter.is_empty() {
            self.is_keyboard() || (mouse && self.is_mouse())
        } else {
            self.matches_any(device_filter)
        }) && (ignore_filter.is_empty() || !self.matches_any(ignore_filter))
    }

    // 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()
        }))
    }

    #[allow(static_mut_refs)]
    fn current_name() -> &'static str {
        if unsafe { DEVICE_NAME.is_none() } {
            let device_name = if Self::has_device_name("xremap") {
                format!("xremap pid={}", process::id())
            } else {
                "xremap".to_string()
            };
            unsafe {
                DEVICE_NAME = Some(device_name);
            }
        }
        unsafe { DEVICE_NAME.as_ref() }.unwrap()
    }

    fn has_device_name(device_name: &str) -> bool {
        let devices: Vec<_> = match Self::devices() {
            Ok(devices) => devices.collect(),
            Err(_) => return true, // fallback to the safe side
        };
        devices.iter().any(|device| device.device_name().contains(device_name))
    }

    fn matches_any(&self, filter: &[String]) -> bool {
        // Force unmatch its own device
        if self.device_name() == Self::current_name() {
            return false;
        }
        filter.iter().any(|f| self.to_info().matches(f))
    }

    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),
            None => false,
        }
    }

    fn is_mouse(&self) -> bool {
        // Xremap doesn't support absolute device so will break them.
        if self.device.supported_absolute_axes().is_some() {
            debug!("Ignoring absolute device {:18} {}", self.path.display(), self.device_name());
            return false;
        }
        self.device
            .supported_keys()
            .is_some_and(|keys| keys.contains(Key::BTN_LEFT))
    }

    pub fn print(&self) {
        println!("{:18}: {}", self.path.display(), self.device_name())
    }

    pub fn print_details(&self) {
        let properties = evdev_enums_to_string(self.device.properties());
        let events = evdev_enums_to_string(self.device.supported_events());
        let keys = evdev_enums_to_string(self.device.supported_keys().unwrap_or_default());
        let relative = evdev_enums_to_string(self.device.supported_relative_axes().unwrap_or_default());
        let absolute = evdev_enums_to_string(self.device.supported_absolute_axes().unwrap_or_default());
        let leds = evdev_enums_to_string(self.device.supported_leds().unwrap_or_default());
        let switches = evdev_enums_to_string(self.device.supported_switches().unwrap_or_default());

        println!("{}", self.device_name());
        println!("");
        println!("  Path:            {}", self.path.display());
        println!("  Type:            {}", self.bus_type());
        println!(
            "  Vendor/product:  {}:{} (0x{:x}:0x{:x}) ",
            self.vendor(),
            self.product(),
            self.vendor(),
            self.product()
        );
        println!("  Properties:      {}", properties);
        println!("  Events:          {}", events);
        println!("  Keys:            {}", keys);
        println!("  Relative axes:   {}", relative);
        println!("  Absolute axes:   {}", absolute);
        println!("  Leds:            {}", leds);
        println!("  Switches:        {}", switches);
        println!("");
    }
}

/// List info about devices
pub fn print_device_list() -> anyhow::Result<()> {
    let mut devices: Vec<_> = InputDevice::devices()?.collect();
    devices.sort();

    let mut table: Vec<Vec<String>> = vec![];

    table.push(vec![
        "PATH".into(),
        "NAME".into(),
        "IS_KEYBOARD".into(),
        "IS_MOUSE".into(),
        "TYPE".into(),
        "VENDOR".into(),
        "PRODUCT".into(),
    ]);

    for device in devices {
        table.push(vec![
            device.path.display().to_string(),
            device.device_name().to_string(),
            format!("{}", device.is_keyboard()),
            format!("{}", device.is_mouse()),
            device.bus_type().to_string(),
            format!("0x{:x}", device.vendor()),
            format!("0x{:x}", device.product()),
        ]);
    }

    print_table(table);

    Ok(())
}

/// Show device details
pub fn print_device_details() -> anyhow::Result<()> {
    let mut devices: Vec<_> = InputDevice::devices()?.collect();
    devices.sort();

    for device in devices {
        device.print_details();
    }

    Ok(())
}

pub const SEPARATOR: &str = "------------------------------------------------------------------------------";