uinput input backend and terminal-aware paste

- uinput.rs: kernel virtual keyboard + absolute pointer (Sunshine-style),
  physical evdev keycodes so the compositor's keysym lookup cannot drop
  shifted symbols (#3). Auto on Wayland/portal when /dev/uinput is
  accessible (udev uaccess rule), XTest kept on X11 (it suppresses
  autorepeat for held keys over latency). UU_INPUT_BACKEND=auto|uinput|native.
- Mac viewers send Cmd+V as Ctrl+V (verified: Cmd and Ctrl both arrive as
  VK_LCONTROL). In a focused X11 terminal Ctrl+V becomes Ctrl+Shift+V so it
  pastes instead of quoting the next key; Ctrl+C always interrupts (copy is
  Cmd+Shift+C). UU_TERMINAL_SHORTCUTS=0 disables.

Verified on the 3090 with the official Mac viewer: paste, interrupt,
uinput typing incl. underscores.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
VallierDevandClaude Opus 5.5 committed 2026-10-15 09:49:03 +08:00
1 parent ddbc75bbf6
commit 49edf1d389
4 files changed
+395 -2

No files matched your search

+42
View File
@@ -9,6 +9,8 @@
#include <sys/ipc.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>
#include <strings.h>
#include <X11/extensions/XShm.h>
#include <X11/extensions/XTest.h>
#include <X11/extensions/Xfixes.h>
@@ -190,6 +192,46 @@ int x11_key_event(int keycode, int is_press) {
return 0;
}
/* ---- Terminal-aware paste (Mac viewer Cmd+V arrives as Ctrl+V) ------------------------------
* Linux terminals paste with Ctrl+Shift+V; Ctrl+V quotes the next key (a paste then shows as
* "^[[200~..."). Reports whether the focused window is a terminal emulator. Uses its own
* connection so it never races the capture/input connection. */
static Display *g_probe = NULL;
static int class_is_terminal(const char *value) {
static const char *names[] = { "gnome-terminal", "gnome-terminal-server", "org.gnome.Console", "kgx", "konsole",
"xfce4-terminal", "mate-terminal", "lxterminal", "qterminal", "terminator", "tilix", "xterm", "uxterm",
"urxvt", "rxvt", "alacritty", "kitty", "wezterm", "wezterm-gui", "foot", "st-256color", "terminology",
"guake", "tilda", "deepin-terminal", "ptyxis", "io.elementary.terminal", "cool-retro-term", NULL };
if (!value) return 0;
for (int i = 0; names[i]; i++) if (strcasecmp(value, names[i]) == 0) return 1;
return 0;
}
/* Returns 1 when the focused window belongs to a terminal emulator, else 0. */
int x11_terminal_shortcut_state(void) {
if (!g_probe && !(g_probe = XOpenDisplay(NULL))) return 0;
Window focus = 0; int revert = 0;
XGetInputFocus(g_probe, &focus, &revert);
if (focus == None || focus == PointerRoot) return 0;
Window cur = focus;
for (int depth = 0; depth < 12 && cur; depth++) {
XClassHint hint = {0};
if (XGetClassHint(g_probe, cur, &hint)) {
int terminal = class_is_terminal(hint.res_name) || class_is_terminal(hint.res_class);
if (hint.res_name) XFree(hint.res_name);
if (hint.res_class) XFree(hint.res_class);
return terminal;
}
Window root, parent, *children = NULL; unsigned int n = 0;
if (!XQueryTree(g_probe, cur, &root, &parent, &children, &n)) return 0;
if (children) XFree(children);
if (parent == root) return 0;
cur = parent;
}
return 0;
}
void x11_close() {
if (!g_display) return;
if (g_use_shm) {
+105 -2
View File
@@ -8,7 +8,10 @@ extern "C" {
fn x11_pointer_state(x:*mut libc::c_int,y:*mut libc::c_int,mask:*mut libc::c_uint)->libc::c_int;
fn x11_key_symbol(symbol: libc::c_ulong, is_press: libc::c_int) -> libc::c_int;
fn x11_key_event(keycode: libc::c_int, is_press: libc::c_int) -> libc::c_int;
fn x11_terminal_shortcut_state() -> libc::c_int;
}
#[cfg(not(target_os = "linux"))]
unsafe fn x11_terminal_shortcut_state() -> libc::c_int { 0 }
#[cfg(not(target_os = "linux"))]
unsafe fn x11_mouse_move(_: libc::c_int, _: libc::c_int) -> libc::c_int { 0 }
@@ -33,11 +36,22 @@ struct PendingPointer {
unsafe fn x11_pointer_state(_: *mut libc::c_int,_:*mut libc::c_int,_:*mut libc::c_uint)->libc::c_int {-1}
#[derive(Default)]
struct HeldInput { buttons: std::collections::BTreeSet<i32>, keys: std::collections::BTreeSet<u64> }
pub struct InputInjector { portal_failures: std::sync::atomic::AtomicUsize, portal_outcomes: [std::sync::atomic::AtomicUsize; 3], portal:std::sync::Mutex<Option<std::sync::Arc<crate::portal::PortalSession>>>, backend: crate::desktop_backend::DesktopBackend, pending: std::sync::Mutex<PendingPointer>, held: std::sync::Mutex<HeldInput> }
/// Held modifier VKs (bit 0 Ctrl, 1 Shift, 2 Alt, 3 Win) and keys that got a synthetic Shift.
#[derive(Default)]
struct Shortcuts { modifiers: u8, shifted: std::collections::BTreeSet<i32> }
pub struct InputInjector { shortcuts: std::sync::Mutex<Shortcuts>, uinput: Option<crate::uinput::Devices>, screen: std::sync::Mutex<(u32,u32)>, portal_failures: std::sync::atomic::AtomicUsize, portal_outcomes: [std::sync::atomic::AtomicUsize; 3], portal:std::sync::Mutex<Option<std::sync::Arc<crate::portal::PortalSession>>>, backend: crate::desktop_backend::DesktopBackend, pending: std::sync::Mutex<PendingPointer>, held: std::sync::Mutex<HeldInput> }
impl InputInjector {
pub fn new() -> Self {
Self { portal_failures: std::sync::atomic::AtomicUsize::new(0), portal_outcomes: std::array::from_fn(|_| std::sync::atomic::AtomicUsize::new(0)), portal:std::sync::Mutex::new(None), backend:crate::desktop_backend::detect().unwrap_or(crate::desktop_backend::DesktopBackend::X11), pending: std::sync::Mutex::new(PendingPointer::default()), held:std::sync::Mutex::new(HeldInput::default()) }
let backend = crate::desktop_backend::detect().unwrap_or(crate::desktop_backend::DesktopBackend::X11);
let uinput = if crate::uinput::wanted(backend) {
match crate::uinput::Devices::open() {
Ok(devices) => { log::info!("Input backend: uinput (kernel virtual keyboard/pointer)"); Some(devices) }
Err(e) => { log::warn!("uinput unavailable ({}); using the desktop input path. See README for the udev rule.", e.kind()); None }
}
} else { None };
Self { shortcuts: std::sync::Mutex::new(Shortcuts::default()), uinput, screen: std::sync::Mutex::new((0,0)), portal_failures: std::sync::atomic::AtomicUsize::new(0), portal_outcomes: std::array::from_fn(|_| std::sync::atomic::AtomicUsize::new(0)), portal:std::sync::Mutex::new(None), backend:crate::desktop_backend::detect().unwrap_or(crate::desktop_backend::DesktopBackend::X11), pending: std::sync::Mutex::new(PendingPointer::default()), held:std::sync::Mutex::new(HeldInput::default()) }
}
pub fn bind_portal(&self,session:Option<std::sync::Arc<crate::portal::PortalSession>>) {
@@ -49,6 +63,7 @@ impl InputInjector {
}
pub fn mouse_absolute_normalized(&self, x: f64, y: f64, size: (u32,u32)) {
*self.screen.lock().unwrap() = size;
if let Some(position) = crate::input_mapping::normalized_pointer(x,y,size.0,size.1) {
let mut pending = self.pending.lock().unwrap();
pending.absolute = Some(position);
@@ -117,7 +132,47 @@ impl InputInjector {
}
}
/// Mac viewers send Cmd+V as Ctrl+V (verified: Cmd and Ctrl both arrive as VK_LCONTROL), which in
/// a Linux terminal quotes the next key instead of pasting. In a focused terminal Ctrl+V becomes
/// Ctrl+Shift+V. Ctrl+C is never translated: it must always interrupt, and copy is Cmd+Shift+C
/// (= Ctrl+Shift+C). X11 only; `UU_TERMINAL_SHORTCUTS=0` disables.
fn terminal_shift(&self, key: i32, is_press: bool) -> bool {
let bit = match key { 0x11 | 0xa2 | 0xa3 => 1, 0x10 | 0xa0 | 0xa1 => 2, 0x12 | 0xa4 | 0xa5 => 4, 0x5b | 0x5c => 8, _ => 0 };
let mut shortcuts = self.shortcuts.lock().unwrap();
if bit != 0 {
if is_press { shortcuts.modifiers |= bit } else { shortcuts.modifiers &= !bit }
return false;
}
if !is_press { return shortcuts.shifted.remove(&key); }
if key != 0x56 || shortcuts.modifiers != 1 { return false; }
if std::env::var("UU_TERMINAL_SHORTCUTS").is_ok_and(|v| v == "0") || std::env::var_os("DISPLAY").is_none() { return false; }
let shift = unsafe { x11_terminal_shortcut_state() } & 1 != 0;
if shift {
shortcuts.shifted.insert(key);
static NOTED: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
if NOTED.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 4 {
log::info!("Terminal shortcut: Ctrl+V sent as Ctrl+Shift+V");
}
}
shift
}
pub fn windows_key_event(&self, key: i32, is_press: bool) {
if self.terminal_shift(key, is_press) {
const SHIFT_L: u64 = 0xffe1;
if is_press {
self.inject_key(SHIFT_L, true);
self.key_symbol_event(key, true);
} else {
self.key_symbol_event(key, false);
self.inject_key(SHIFT_L, false);
}
return;
}
self.key_symbol_event(key, is_press);
}
fn key_symbol_event(&self, key: i32, is_press: bool) {
if let Some(symbol) = crate::input_mapping::windows_vk_to_keysym(key) {
let result = self.inject_key(symbol,is_press);
static AUDIT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
@@ -158,19 +213,44 @@ impl InputInjector {
}
}
}
fn uinput_result(result: std::io::Result<()>) -> i32 {
match result {
Ok(()) => 0,
Err(e) => {
static FAILURES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
if FAILURES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 8 { log::warn!("uinput injection failed: {}", e.kind()); }
-1
}
}
}
fn inject_move(&self,x:i32,y:i32,relative:bool)->i32 {
if let Some(uinput)=&self.uinput {
if relative { return Self::uinput_result(uinput.move_relative(x,y)); }
let (w,h)=*self.screen.lock().unwrap();
if w > 1 && h > 1 {
let scale = |v: i32, extent: u32| (i64::from(v) * i64::from(crate::uinput::ABS_MAX) / i64::from(extent - 1)) as i32;
return Self::uinput_result(uinput.move_absolute(scale(x,w),scale(y,h)));
}
}
if let Some(portal)=self.portal.lock().unwrap().as_ref() { return self.portal_result("motion", portal.move_pointer(f64::from(x),f64::from(y),relative)); }
if self.backend==crate::desktop_backend::DesktopBackend::Portal {return self.portal_result("motion", Err("Portal input session is not bound".into()));}
if self.backend==crate::desktop_backend::DesktopBackend::Wayland { crate::wayland::move_pointer(x,y,relative) }
else if relative { unsafe { x11_mouse_relative(x,y) } } else { unsafe { x11_mouse_move(x,y) } }
}
fn inject_button(&self,button:i32,pressed:bool)->i32 {
if let Some(uinput)=&self.uinput {
if let Some((v,h))=crate::uinput::wheel_step(button) { return if pressed { Self::uinput_result(uinput.wheel(v,h)) } else { 0 }; }
if let Some(code)=crate::uinput::button_code(button) { return Self::uinput_result(uinput.button(code,pressed)); }
}
if let Some(portal)=self.portal.lock().unwrap().as_ref() { return self.portal_result("button", portal.button(button,pressed)); }
if self.backend==crate::desktop_backend::DesktopBackend::Portal {return self.portal_result("button", Err("Portal input session is not bound".into()));}
if self.backend==crate::desktop_backend::DesktopBackend::Wayland { crate::wayland::button(button,pressed) }
else { unsafe { x11_mouse_button(button,i32::from(pressed)) } }
}
fn inject_key(&self,symbol:u64,pressed:bool)->i32 {
if let Some(uinput)=&self.uinput {
if let Some(code)=crate::uinput::keysym_to_evdev(symbol) { return Self::uinput_result(uinput.key(code,pressed)); }
}
if let Some(portal)=self.portal.lock().unwrap().as_ref() { return self.portal_result("keyboard", portal.key(symbol,pressed)); }
if self.backend==crate::desktop_backend::DesktopBackend::Portal {return self.portal_result("keyboard", Err("Portal input session is not bound".into()));}
if self.backend==crate::desktop_backend::DesktopBackend::Wayland { crate::wayland::key(symbol,pressed) }
@@ -213,6 +293,29 @@ mod motion_tests {
}
}
#[cfg(test)]
mod shortcut_tests {
use super::*;
#[test]
fn modifiers_are_tracked_and_non_terminal_keys_pass_through() {
let input = InputInjector::new();
assert!(!input.terminal_shift(0x11, true));
assert_eq!(input.shortcuts.lock().unwrap().modifiers, 1);
// No X display in tests: Ctrl+V is not translated.
assert!(!input.terminal_shift(0x56, true));
assert!(!input.terminal_shift(0x56, false));
assert!(!input.terminal_shift(0x11, false));
assert_eq!(input.shortcuts.lock().unwrap().modifiers, 0);
// A translated key keeps its synthetic Shift until its own release.
input.shortcuts.lock().unwrap().shifted.insert(0x56);
assert!(input.terminal_shift(0x56, false));
assert!(!input.terminal_shift(0x56, false));
// Ctrl+C is never translated.
input.terminal_shift(0x11, true);
assert!(!input.terminal_shift(0x43, true));
}
}
#[cfg(test)]
mod scroll_tests {
use super::*;
+1
View File
@@ -14,6 +14,7 @@ mod session_lock;
mod capture;
mod file_trans;
mod input;
mod uinput;
mod input_mapping;
mod port_mapping;
mod power;
+247
View File
@@ -0,0 +1,247 @@
//! Kernel-level virtual keyboard and pointer through /dev/uinput (as Sunshine does).
//!
//! Works the same under X11, every Wayland compositor and the greeter/lock screen, needs no
//! portal permission and sends physical keycodes, so the compositor's keysym → key lookup
//! (which can pick an AltGr level for `minus` and drop `_`, issue #3) is not involved.
//! Access: a udev rule `KERNEL=="uinput", SUBSYSTEM=="misc", OPTIONS+="static_node=uinput",
//! TAG+="uaccess"` grants the logged-in seat user access (see README).
//!
//! Devices: one keyboard + relative mouse, one absolute pointer (ABS_X/ABS_Y 0..=65535 with
//! buttons and wheels, like a QEMU tablet). Mixing relative and absolute axes in one device
//! confuses libinput.
#[cfg(target_os = "linux")]
mod imp {
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
use std::os::unix::io::AsRawFd;
use std::sync::Mutex;
const EV_SYN: u16 = 0x00;
const EV_KEY: u16 = 0x01;
const EV_REL: u16 = 0x02;
const EV_ABS: u16 = 0x03;
const SYN_REPORT: u16 = 0;
const REL_X: u16 = 0x00;
const REL_Y: u16 = 0x01;
const REL_HWHEEL: u16 = 0x06;
const REL_WHEEL: u16 = 0x08;
const ABS_X: u16 = 0x00;
const ABS_Y: u16 = 0x01;
pub const BTN_LEFT: u16 = 0x110;
pub const BTN_RIGHT: u16 = 0x111;
pub const BTN_MIDDLE: u16 = 0x112;
pub const BTN_SIDE: u16 = 0x113;
pub const BTN_EXTRA: u16 = 0x114;
pub const ABS_MAX: i32 = 65535;
const UI_SET_EVBIT: libc::c_ulong = 0x4004_5564;
const UI_SET_KEYBIT: libc::c_ulong = 0x4004_5565;
const UI_SET_RELBIT: libc::c_ulong = 0x4004_5566;
const UI_SET_ABSBIT: libc::c_ulong = 0x4004_5567;
const UI_DEV_CREATE: libc::c_ulong = 0x5501;
const UI_DEV_DESTROY: libc::c_ulong = 0x5502;
const UI_DEV_SETUP: libc::c_ulong = 0x405c_5503;
const UI_ABS_SETUP: libc::c_ulong = 0x401c_5504;
#[repr(C)]
struct InputId { bustype: u16, vendor: u16, product: u16, version: u16 }
#[repr(C)]
struct UinputSetup { id: InputId, name: [u8; 80], ff_effects_max: u32 }
#[repr(C)]
struct AbsInfo { value: i32, minimum: i32, maximum: i32, fuzz: i32, flat: i32, resolution: i32 }
#[repr(C)]
struct UinputAbsSetup { code: u16, _pad: u16, absinfo: AbsInfo }
#[repr(C)]
struct InputEvent { time: libc::timeval, kind: u16, code: u16, value: i32 }
struct Device(File);
impl Drop for Device {
fn drop(&mut self) { unsafe { libc::ioctl(self.0.as_raw_fd(), UI_DEV_DESTROY); } }
}
impl Device {
fn ioctl(&self, request: libc::c_ulong, value: libc::c_ulong) -> std::io::Result<()> {
if unsafe { libc::ioctl(self.0.as_raw_fd(), request, value) } < 0 { Err(std::io::Error::last_os_error()) } else { Ok(()) }
}
fn create(name: &str, product: u16, configure: impl FnOnce(&Device) -> std::io::Result<()>) -> std::io::Result<Self> {
let file = OpenOptions::new().write(true).custom_flags(libc::O_NONBLOCK).open("/dev/uinput")?;
let device = Device(file);
configure(&device)?;
let mut setup = UinputSetup { id: InputId { bustype: 0x06 /* BUS_VIRTUAL */, vendor: 0x1d6b, product, version: 1 }, name: [0; 80], ff_effects_max: 0 };
setup.name[..name.len().min(79)].copy_from_slice(&name.as_bytes()[..name.len().min(79)]);
if unsafe { libc::ioctl(device.0.as_raw_fd(), UI_DEV_SETUP, &setup) } < 0 { return Err(std::io::Error::last_os_error()); }
device.ioctl(UI_DEV_CREATE, 0)?;
Ok(device)
}
fn abs(&self, code: u16) -> std::io::Result<()> {
self.ioctl(UI_SET_ABSBIT, code.into())?;
let setup = UinputAbsSetup { code, _pad: 0, absinfo: AbsInfo { value: 0, minimum: 0, maximum: ABS_MAX, fuzz: 0, flat: 0, resolution: 0 } };
if unsafe { libc::ioctl(self.0.as_raw_fd(), UI_ABS_SETUP, &setup) } < 0 { return Err(std::io::Error::last_os_error()); }
Ok(())
}
fn emit(&mut self, events: &[(u16, u16, i32)]) -> std::io::Result<()> {
let zero = libc::timeval { tv_sec: 0, tv_usec: 0 };
let mut buffer = Vec::with_capacity((events.len() + 1) * std::mem::size_of::<InputEvent>());
for &(kind, code, value) in events.iter().chain(std::iter::once(&(EV_SYN, SYN_REPORT, 0))) {
let event = InputEvent { time: zero, kind, code, value };
let bytes = unsafe { std::slice::from_raw_parts((&event as *const InputEvent).cast::<u8>(), std::mem::size_of::<InputEvent>()) };
buffer.extend_from_slice(bytes);
}
self.0.write_all(&buffer)
}
}
pub struct Devices { keyboard: Mutex<Device>, pointer: Mutex<Device> }
impl Devices {
pub fn open() -> std::io::Result<Self> {
let keyboard = Device::create("uu-remote-linux keyboard", 1, |d| {
d.ioctl(UI_SET_EVBIT, EV_KEY.into())?;
for code in 1..=248u16 { d.ioctl(UI_SET_KEYBIT, code.into())?; }
// Relative motion (games / pointer lock) lives with the keyboard device.
d.ioctl(UI_SET_EVBIT, EV_REL.into())?;
d.ioctl(UI_SET_RELBIT, REL_X.into())?;
d.ioctl(UI_SET_RELBIT, REL_Y.into())?;
for button in [BTN_LEFT, BTN_RIGHT, BTN_MIDDLE] { d.ioctl(UI_SET_KEYBIT, button.into())?; }
Ok(())
})?;
let pointer = Device::create("uu-remote-linux pointer", 2, |d| {
d.ioctl(UI_SET_EVBIT, EV_KEY.into())?;
for button in [BTN_LEFT, BTN_RIGHT, BTN_MIDDLE, BTN_SIDE, BTN_EXTRA] { d.ioctl(UI_SET_KEYBIT, button.into())?; }
d.ioctl(UI_SET_EVBIT, EV_REL.into())?;
d.ioctl(UI_SET_RELBIT, REL_WHEEL.into())?;
d.ioctl(UI_SET_RELBIT, REL_HWHEEL.into())?;
d.ioctl(UI_SET_EVBIT, EV_ABS.into())?;
d.abs(ABS_X)?;
d.abs(ABS_Y)
})?;
Ok(Self { keyboard: Mutex::new(keyboard), pointer: Mutex::new(pointer) })
}
pub fn key(&self, code: u16, pressed: bool) -> std::io::Result<()> {
self.keyboard.lock().unwrap().emit(&[(EV_KEY, code, i32::from(pressed))])
}
pub fn move_absolute(&self, x: i32, y: i32) -> std::io::Result<()> {
self.pointer.lock().unwrap().emit(&[(EV_ABS, ABS_X, x.clamp(0, ABS_MAX)), (EV_ABS, ABS_Y, y.clamp(0, ABS_MAX))])
}
pub fn move_relative(&self, dx: i32, dy: i32) -> std::io::Result<()> {
self.keyboard.lock().unwrap().emit(&[(EV_REL, REL_X, dx), (EV_REL, REL_Y, dy)])
}
pub fn button(&self, code: u16, pressed: bool) -> std::io::Result<()> {
self.pointer.lock().unwrap().emit(&[(EV_KEY, code, i32::from(pressed))])
}
pub fn wheel(&self, vertical: i32, horizontal: i32) -> std::io::Result<()> {
let mut events = Vec::new();
if vertical != 0 { events.push((EV_REL, REL_WHEEL, vertical)); }
if horizontal != 0 { events.push((EV_REL, REL_HWHEEL, horizontal)); }
if events.is_empty() { return Ok(()); }
self.pointer.lock().unwrap().emit(&events)
}
}
}
#[cfg(not(target_os = "linux"))]
mod imp {
pub const BTN_LEFT: u16 = 0x110;
pub const BTN_RIGHT: u16 = 0x111;
pub const BTN_MIDDLE: u16 = 0x112;
pub const BTN_SIDE: u16 = 0x113;
pub const BTN_EXTRA: u16 = 0x114;
pub const ABS_MAX: i32 = 65535;
pub struct Devices;
impl Devices {
pub fn open() -> std::io::Result<Self> { Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "uinput requires Linux")) }
pub fn key(&self, _: u16, _: bool) -> std::io::Result<()> { Ok(()) }
pub fn move_absolute(&self, _: i32, _: i32) -> std::io::Result<()> { Ok(()) }
pub fn move_relative(&self, _: i32, _: i32) -> std::io::Result<()> { Ok(()) }
pub fn button(&self, _: u16, _: bool) -> std::io::Result<()> { Ok(()) }
pub fn wheel(&self, _: i32, _: i32) -> std::io::Result<()> { Ok(()) }
}
}
pub use imp::{Devices, ABS_MAX, BTN_EXTRA, BTN_LEFT, BTN_MIDDLE, BTN_RIGHT, BTN_SIDE};
/// X11 button ordinal (1 left, 2 middle, 3 right, 8/9 side) → evdev button code.
pub fn button_code(x11_button: i32) -> Option<u16> {
match x11_button { 1 => Some(BTN_LEFT), 2 => Some(BTN_MIDDLE), 3 => Some(BTN_RIGHT), 8 => Some(BTN_SIDE), 9 => Some(BTN_EXTRA), _ => None }
}
/// X11 wheel "buttons" 4/5 (vertical) and 6/7 (horizontal) → (REL_WHEEL, REL_HWHEEL) steps.
pub fn wheel_step(x11_button: i32) -> Option<(i32, i32)> {
match x11_button { 4 => Some((1, 0)), 5 => Some((-1, 0)), 6 => Some((0, -1)), 7 => Some((0, 1)), _ => None }
}
/// Base keysym (as produced by input_mapping::windows_vk_to_keysym) → physical evdev keycode
/// at its US-layout position. The compositor then applies the user's own layout, exactly as
/// for a hardware keyboard.
pub fn keysym_to_evdev(keysym: u64) -> Option<u16> {
const LETTERS: [u16; 26] = [30, 48, 46, 32, 18, 33, 34, 35, 23, 36, 37, 38, 50, 49, 24, 25, 16, 19, 31, 20, 22, 47, 17, 45, 21, 44];
const KEYPAD: [u16; 10] = [82, 79, 80, 81, 75, 76, 77, 71, 72, 73];
let code = match keysym {
0x61..=0x7a => LETTERS[(keysym - 0x61) as usize],
0x31..=0x39 => (keysym - 0x31) as u16 + 2, // 1..9
0x30 => 11,
0xffb0..=0xffb9 => KEYPAD[(keysym - 0xffb0) as usize],
0xffbe..=0xffc7 => (keysym - 0xffbe) as u16 + 59, // F1..F10
0xffc8 => 87, 0xffc9 => 88, // F11, F12
0xffca..=0xffd5 => (keysym - 0xffca) as u16 + 183, // F13..F24
0xff0b => 76, // Clear: keypad 5 without NumLock, as on PC keyboards
0xff08 => 14, 0xff09 => 15, 0xff0d => 28, 0xff1b => 1, 0x20 => 57,
0xff13 => 119, 0xffe5 => 58, 0xff7f => 69, 0xff14 => 70, 0xff61 => 99,
0xffe1 => 42, 0xffe2 => 54, 0xffe3 => 29, 0xffe4 => 97, 0xffe9 => 56, 0xffea => 100,
0xffeb => 125, 0xffec => 126, 0xff67 => 127,
0xff55 => 104, 0xff56 => 109, 0xff57 => 107, 0xff50 => 102,
0xff51 => 105, 0xff52 => 103, 0xff53 => 106, 0xff54 => 108,
0xff63 => 110, 0xffff => 111,
0xffaa => 55, 0xffab => 78, 0xffac => 121, 0xffad => 74, 0xffae => 83, 0xffaf => 98, 0xff8d => 96,
0x3b => 39, 0x3d => 13, 0x2c => 51, 0x2d => 12, 0x2e => 52, 0x2f => 53, 0x60 => 41,
0x5b => 26, 0x5c => 43, 0x5d => 27, 0x27 => 40,
0x1008ff12 => 113, 0x1008ff11 => 114, 0x1008ff13 => 115,
0x1008ff17 => 163, 0x1008ff16 => 165, 0x1008ff15 => 166, 0x1008ff14 => 164,
_ => return None,
};
Some(code)
}
/// Input backend policy: `UU_INPUT_BACKEND=uinput` forces uinput, `native` disables it,
/// `auto` (default) uses uinput for Wayland/portal sessions when /dev/uinput is accessible
/// and keeps the verified XTest path on X11.
pub fn wanted(backend: crate::desktop_backend::DesktopBackend) -> bool {
match std::env::var("UU_INPUT_BACKEND").as_deref() {
Ok("uinput") => true,
Ok("native") => false,
_ => backend != crate::desktop_backend::DesktopBackend::X11,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn maps_keysyms_to_physical_us_positions() {
assert_eq!(keysym_to_evdev(0x61), Some(30)); // a
assert_eq!(keysym_to_evdev(0x7a), Some(44)); // z
assert_eq!(keysym_to_evdev(0x30), Some(11)); // 0
assert_eq!(keysym_to_evdev(0x31), Some(2)); // 1
assert_eq!(keysym_to_evdev(0x2d), Some(12)); // minus: Shift+minus gives '_' (#3)
assert_eq!(keysym_to_evdev(0xffe1), Some(42)); // Shift_L
assert_eq!(keysym_to_evdev(0xffc9), Some(88)); // F12
assert_eq!(keysym_to_evdev(0xffb5), Some(76)); // KP_5
assert_eq!(keysym_to_evdev(0x12345), None);
}
#[test]
fn every_mapped_windows_vk_has_a_physical_key() {
let missing: Vec<i32> = (0..=0xff).filter(|vk| {
crate::input_mapping::windows_vk_to_keysym(*vk).is_some_and(|ks| keysym_to_evdev(ks).is_none())
}).collect();
assert!(missing.is_empty(), "VKs without evdev mapping: {missing:x?}");
}
#[test]
fn buttons_and_wheel() {
assert_eq!(button_code(1), Some(BTN_LEFT));
assert_eq!(button_code(3), Some(BTN_RIGHT));
assert_eq!(wheel_step(4), Some((1, 0)));
assert_eq!(wheel_step(7), Some((0, 1)));
assert_eq!(button_code(4), None);
}
}