Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.
fix(linux): incorporate linux-review-fixes for Part 3 input, keymap, and window capture
Jochen Kirstätter824712f16aa3
diff --cc desktop/app/qml/pages/DeckPage.qmlindex 2757d29,2757d29..0567c3b--- a/desktop/app/qml/pages/DeckPage.qml+++ b/desktop/app/qml/pages/DeckPage.qml@@@ -98,9 -98,9 +98,9 @@@ Item{ id: "volume_up", group: qsTr("Audio"), label: qsTr("Volume up") },{ id: "volume_mute", group: qsTr("Audio"), label: qsTr("Mute speaker") },{ id: "mic_mute", group: qsTr("Audio"), label: qsTr("Mute microphone") },-- { id: "show_desktop", group: qsTr("System"), label: qsTr("Show desktop (Win+D)") },++ { id: "show_desktop", group: qsTr("System"), label: Qt.platform.os === "linux" ? qsTr("Show desktop (Super+D)") : qsTr("Show desktop (Win+D)") },{ id: "switch_window", group: qsTr("System"), label: qsTr("Switch window (Alt+Tab)") },-- { id: "screenshot", group: qsTr("System"), label: qsTr("Screenshot (Win+Shift+S)") },++ { id: "screenshot", group: qsTr("System"), label: Qt.platform.os === "linux" ? qsTr("Screenshot") : qsTr("Screenshot (Win+Shift+S)") },{ id: "lock_pc", group: qsTr("System"), label: qsTr("Lock PC") },{ id: "shortcut", group: qsTr("Custom"), label: qsTr("Keyboard shortcut") },{ id: "open_url", group: qsTr("Custom"), label: qsTr("Open website") },@@@ -746,7 -746,7 +746,7 @@@Chip {interactive: trueselected: editorSheet.modWin-- text: qsTr("Win")++ text: Qt.platform.os === "linux" ? qsTr("Super") : qsTr("Win")onClicked: editorSheet.modWin = !editorSheet.modWin}}diff --cc desktop/app/src/linux/input.rsindex 25fd8e4,9396fb0..7462630--- a/desktop/app/src/linux/input.rs+++ b/desktop/app/src/linux/input.rs@@@ -1,888 -1,20 +1,1678 @@@// SPDX-License-Identifier: GPL-3.0-or-later-#![allow(dead_code, unused_variables)]+//! Synthesizes mouse and keyboard input on Linux for a paired phone acting as+//! a touchpad, keyboard, or presentation remote (`docs/protocol/remote.md`),+//! as well as reverse PC mirror touch injection.+//!- //! On X11 / XWayland (`DISPLAY` set), pointer and button events are injected- //! in-process through a persistent `libX11.so.6` + `libXtst.so.6` (`XTest`)- //! display connection so 60 Hz mouse/touch streams do not fork a child process- //! per event. When `libXtst.so.6` is unavailable or running on pure Wayland,- //! falls back to `ydotool` / `wtype` / `xdotool`.++//! Input backends are tried in order of lowest overhead and broadest display-server++//! support:++//! 1. In-process `/dev/uinput` virtual input device (works on both X11 and Wayland).++//! 2. On Wayland: in-process `org.freedesktop.portal.RemoteDesktop` D-Bus session.++//! 3. On X11 / XWayland: in-process `libX11.so.6` + `libXtst.so.6` (`XTest`).++//! 4. Subprocess fallbacks (`ydotool`, `wtype`, `xdotool`), piping text via stdin++//! so typed strings never appear in `/proc/<pid>/cmdline`.-use nectarlink_core::{ButtonAction, KeyMod, MouseButton, SlideAction, TouchAction};+use std::{++ collections::HashMap,+ ffi::{CStr, CString, c_char, c_int, c_uint, c_ulong, c_void},++ io::Write,+ process::{Command, Stdio},+ sync::{Mutex, OnceLock},+};+use nectarlink_core::{ButtonAction, KeyMod, MouseButton, PowerAction, SlideAction, TouchAction};+++// ---- Linux `/dev/uinput` kernel ABI constants ----++const EV_SYN: u16 = 0x00;++const EV_KEY: u16 = 0x01;++const EV_REL: u16 = 0x02;++++const SYN_REPORT: u16 = 0x00;++++const REL_X: u16 = 0x00;++const REL_Y: u16 = 0x01;++const REL_HWHEEL: u16 = 0x06;++const REL_WHEEL: u16 = 0x08;++++const BTN_LEFT: u16 = 0x110;++const BTN_RIGHT: u16 = 0x111;++const BTN_MIDDLE: u16 = 0x112;++++const BUS_USB: u16 = 0x03;++++const UI_DEV_CREATE: c_ulong = 0x5501;++const UI_DEV_DESTROY: c_ulong = 0x5502;++const UI_DEV_SETUP: c_ulong = 0x405c_5503;++const UI_SET_EVBIT: c_ulong = 0x4004_5564;++const UI_SET_KEYBIT: c_ulong = 0x4004_5565;++const UI_SET_RELBIT: c_ulong = 0x4004_5566;++++#[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 InputEvent {++ tv_sec: libc::time_t,++ tv_usec: libc::suseconds_t,++ type_: u16,++ code: u16,++ value: i32,++}++++struct UinputDevice {++ fd: c_int,++}++++impl UinputDevice {++ fn open() -> Option<Self> {++ let paths = [c"/dev/uinput", c"/dev/input/uinput"];++ let mut fd = -1;++ for path in paths {++ // SAFETY: `path` is a valid null-terminated C string.++ let opened =++ unsafe { libc::open(path.as_ptr(), libc::O_WRONLY | libc::O_NONBLOCK | libc::O_CLOEXEC) };++ if opened >= 0 {++ fd = opened;++ break;++ }++ }++ if fd < 0 {++ return None;++ }++++ // SAFETY: `fd` is an open `/dev/uinput` descriptor; ioctl configures supported event bits.++ unsafe {++ if libc::ioctl(fd, UI_SET_EVBIT, c_int::from(EV_SYN)) < 0++ || libc::ioctl(fd, UI_SET_EVBIT, c_int::from(EV_KEY)) < 0++ || libc::ioctl(fd, UI_SET_EVBIT, c_int::from(EV_REL)) < 0++ {++ let _ = libc::close(fd);++ return None;++ }++++ for rel in [REL_X, REL_Y, REL_WHEEL, REL_HWHEEL] {++ if libc::ioctl(fd, UI_SET_RELBIT, c_int::from(rel)) < 0 {++ let _ = libc::close(fd);++ return None;++ }++ }++++ for btn in [BTN_LEFT, BTN_RIGHT, BTN_MIDDLE] {++ if libc::ioctl(fd, UI_SET_KEYBIT, c_int::from(btn)) < 0 {++ let _ = libc::close(fd);++ return None;++ }++ }++++ for key in 1..=248 {++ let _ = libc::ioctl(fd, UI_SET_KEYBIT, key as c_int);++ }++++ let mut setup = UinputSetup {++ id: InputId { bustype: BUS_USB, vendor: 0x1d6b, product: 0x0104, version: 1 },++ name: [0u8; 80],++ ff_effects_max: 0,++ };++ let dev_name = b"NectarLink Virtual Input";++ setup.name[..dev_name.len()].copy_from_slice(dev_name);++++ if libc::ioctl(fd, UI_DEV_SETUP, &setup) < 0 || libc::ioctl(fd, UI_DEV_CREATE) < 0 {++ let _ = libc::close(fd);++ return None;++ }++ }++++ Some(Self { fd })++ }++++ fn emit(&self, type_: u16, code: u16, value: i32) -> bool {++ let ev = InputEvent { tv_sec: 0, tv_usec: 0, type_, code, value };++ let size = std::mem::size_of::<InputEvent>();++ // SAFETY: `ev` is a repr(C) `input_event` struct written atomically to `self.fd`.++ let written = unsafe { libc::write(self.fd, (&raw const ev).cast::<c_void>(), size) };++ written == size as isize++ }++++ fn syn(&self) -> bool {++ self.emit(EV_SYN, SYN_REPORT, 0)++ }++++ fn move_relative(&self, dx: i32, dy: i32) -> bool {++ let mut ok = true;++ if dx != 0 {++ ok &= self.emit(EV_REL, REL_X, dx);++ }++ if dy != 0 {++ ok &= self.emit(EV_REL, REL_Y, dy);++ }++ ok && self.syn()++ }++++ fn button(&self, btn: u16, down: bool) -> bool {++ self.emit(EV_KEY, btn, i32::from(down)) && self.syn()++ }++++ fn scroll(&self, nx: i32, ny: i32) -> bool {++ let mut ok = true;++ if ny != 0 {++ // In evdev, positive REL_WHEEL is scroll up; our `ny > 0` is scroll down.++ ok &= self.emit(EV_REL, REL_WHEEL, -ny);++ }++ if nx != 0 {++ ok &= self.emit(EV_REL, REL_HWHEEL, nx);++ }++ ok && self.syn()++ }++++ fn key_combo(&self, keycode: u16, mods: &[u16]) -> bool {++ let mut ok = true;++ for &m in mods {++ ok &= self.emit(EV_KEY, m, 1);++ }++ ok &= self.emit(EV_KEY, keycode, 1);++ ok &= self.syn();++ ok &= self.emit(EV_KEY, keycode, 0);++ for &m in mods.iter().rev() {++ ok &= self.emit(EV_KEY, m, 0);++ }++ ok && self.syn()++ }++}++++impl Drop for UinputDevice {++ fn drop(&mut self) {++ if self.fd >= 0 {++ // SAFETY: `self.fd` is a valid uinput descriptor owned by `self`.++ unsafe {++ let _ = libc::ioctl(self.fd, UI_DEV_DESTROY);++ let _ = libc::close(self.fd);++ }++ }++ }++}++++fn with_uinput<F: FnOnce(&UinputDevice) -> bool>(f: F) -> bool {++ static UINPUT: OnceLock<Mutex<Option<UinputDevice>>> = OnceLock::new();++ let mutex = UINPUT.get_or_init(|| Mutex::new(UinputDevice::open()));++ let guard = mutex.lock().unwrap_or_else(|e| e.into_inner());++ guard.as_ref().is_some_and(f)++}++++fn evdev_button_code(button: MouseButton) -> u16 {++ match button {++ MouseButton::Left => BTN_LEFT,++ MouseButton::Right => BTN_RIGHT,++ MouseButton::Middle => BTN_MIDDLE,++ }++}++++pub(crate) fn evdev_key_for_mod(m: KeyMod) -> u16 {++ match m {++ KeyMod::Ctrl => 29, // KEY_LEFTCTRL++ KeyMod::Shift => 42, // KEY_LEFTSHIFT++ KeyMod::Alt => 56, // KEY_LEFTALT++ KeyMod::Win => 125, // KEY_LEFTMETA++ }++}++++/// Maps a named X11 keysym (as returned by [`resolve_key`]) to a Linux evdev `KEY_*` code.++/// Letters and digits aren't here: where they are depends on the layout ([`key_code_for_sym`]).++pub(crate) fn evdev_key_for_sym(sym: &str) -> Option<u16> {++ let code = match sym {++ "Escape" => 1,++ "BackSpace" => 14,++ "Tab" => 15,++ "Return" => 28,++ "space" => 57,++ "F1" => 59,++ "F2" => 60,++ "F3" => 61,++ "F4" => 62,++ "F5" => 63,++ "F6" => 64,++ "F7" => 65,++ "F8" => 66,++ "F9" => 67,++ "F10" => 68,++ "F11" => 87,++ "F12" => 88,++ "Print" => 99,++ "Home" => 102,++ "Up" => 103,++ "Prior" => 104,++ "Left" => 105,++ "Right" => 106,++ "End" => 107,++ "Down" => 108,++ "Next" => 109,++ "Insert" => 110,++ "Delete" => 111,++ "XF86AudioMute" => 113,++ "XF86AudioLowerVolume" => 114,++ "XF86AudioRaiseVolume" => 115,++ "XF86AudioNext" => 163,++ "XF86AudioPlay" => 164,++ "XF86AudioPrev" => 165,++ _ => return None,++ };++ Some(code)++}++++/// The modifier keys a [`KeyPress`](super::keymap::KeyPress) needs held.++fn press_mods(press: &super::keymap::KeyPress) -> Vec<u16> {++ let mut mods = Vec::with_capacity(2);++ if press.shift {++ mods.push(evdev_key_for_mod(KeyMod::Shift));++ }++ if press.altgr {++ mods.push(super::keymap::KEY_RIGHTALT);++ }++ mods++}++++/// The evdev key for a shortcut's key name. Named keys (arrows, F-keys,++/// Enter) are in the same place on every layout; a letter isn't (Z is++/// where Y is on a German keyboard), so letters go through the user's++/// layout, and without a known layout there is no key code to send.++fn key_code_for_sym(sym: &str) -> Option<u16> {++ let mut chars = sym.chars();++ match (chars.next(), chars.next()) {++ (Some(ch), None) => {++ super::keymap::current()?.press_for(ch).filter(|p| !p.shift && !p.altgr).map(|p| p.code)++ }++ _ => evdev_key_for_sym(sym),++ }++}++++/// Converts a Unicode character to its X11 keysym (`XK_*` or `0x0100_0000 | codepoint`).++pub(crate) fn char_to_x11_keysym(ch: char) -> u32 {++ match ch {++ '\n' => 0xff0d, // XK_Return++ '\t' => 0xff09, // XK_Tab++ '\u{08}' => 0xff08, // XK_BackSpace++ '\u{1b}' => 0xff1b, // XK_Escape++ ' '..='~' | '\u{a0}'..='\u{ff}' => ch as u32,++ c => 0x0100_0000 | (c as u32),++ }++}++++// ---- Wayland `org.freedesktop.portal.RemoteDesktop` backend ----++struct RemoteDesktopPortal {++ conn: zbus::blocking::Connection,++ session_path: zbus::zvariant::OwnedObjectPath,++}++++impl RemoteDesktopPortal {++ fn connect() -> Option<Self> {++ let conn = zbus::blocking::Connection::session().ok()?;++ if !super::dbus_name_has_owner(&conn, "org.freedesktop.portal.Desktop") {++ return None;++ }++ let rule = zbus::MatchRule::builder()++ .msg_type(zbus::message::Type::Signal)++ .interface("org.freedesktop.portal.Request")++ .and_then(|b| b.member("Response"))++ .map(|b| b.build())++ .ok()?;++ let mut iter = zbus::blocking::MessageIterator::for_match_rule(rule, &conn, None).ok()?;++++ let pid = std::process::id();++ let session_token = format!("nectarlink_rd_sess_{pid}");++ let create_token = format!("nectarlink_rd_create_{pid}");++++ let mut create_opts: HashMap<&str, zbus::zvariant::Value<'_>> = HashMap::new();++ create_opts.insert("handle_token", zbus::zvariant::Value::from(create_token));++ create_opts.insert("session_handle_token", zbus::zvariant::Value::from(session_token));++++ let create_reply = conn++ .call_method(++ Some("org.freedesktop.portal.Desktop"),++ "/org/freedesktop/portal/desktop",++ Some("org.freedesktop.portal.RemoteDesktop"),++ "CreateSession",++ &(&create_opts,),++ )++ .ok()?;++ let create_req_path =++ create_reply.body().deserialize::<zbus::zvariant::OwnedObjectPath>().ok().map(|p| p.to_string());++ let create_results = Self::wait_portal_response(&mut iter, create_req_path.as_deref())?;++ let session_str =++ create_results.get("session_handle").and_then(|v| <&str>::try_from(v).ok())?.to_owned();++ let session_path = zbus::zvariant::OwnedObjectPath::try_from(session_str).ok()?;++++ // SelectDevices: types = 3 (1 = KEYBOARD | 2 = POINTER).++ let select_token = format!("nectarlink_rd_select_{pid}");++ let mut select_opts: HashMap<&str, zbus::zvariant::Value<'_>> = HashMap::new();++ select_opts.insert("handle_token", zbus::zvariant::Value::from(select_token));++ select_opts.insert("types", zbus::zvariant::Value::U32(3));++++ let select_reply = conn++ .call_method(++ Some("org.freedesktop.portal.Desktop"),++ "/org/freedesktop/portal/desktop",++ Some("org.freedesktop.portal.RemoteDesktop"),++ "SelectDevices",++ &(&session_path, &select_opts),++ )++ .ok()?;++ let select_req_path =++ select_reply.body().deserialize::<zbus::zvariant::OwnedObjectPath>().ok().map(|p| p.to_string());++ Self::wait_portal_response(&mut iter, select_req_path.as_deref())?;++++ // Start session.++ let start_token = format!("nectarlink_rd_start_{pid}");++ let mut start_opts: HashMap<&str, zbus::zvariant::Value<'_>> = HashMap::new();++ start_opts.insert("handle_token", zbus::zvariant::Value::from(start_token));++++ let start_reply = conn++ .call_method(++ Some("org.freedesktop.portal.Desktop"),++ "/org/freedesktop/portal/desktop",++ Some("org.freedesktop.portal.RemoteDesktop"),++ "Start",++ &(&session_path, "", &start_opts),++ )++ .ok()?;++ let start_req_path =++ start_reply.body().deserialize::<zbus::zvariant::OwnedObjectPath>().ok().map(|p| p.to_string());++ Self::wait_portal_response(&mut iter, start_req_path.as_deref())?;++++ Some(Self { conn, session_path })++ }++++ fn wait_portal_response(++ iter: &mut zbus::blocking::MessageIterator,++ expected_path: Option<&str>,++ ) -> Option<HashMap<String, zbus::zvariant::OwnedValue>> {++ for msg in iter.take(32) {++ let msg = msg.ok()?;++ if let Some(expected) = expected_path++ && msg.header().path().map(|p| p.as_str()) != Some(expected)++ {++ continue;++ }++ if let Ok((code, results)) =++ msg.body().deserialize::<(u32, HashMap<String, zbus::zvariant::OwnedValue>)>()++ {++ return (code == 0).then_some(results);++ }++ }++ None++ }++++ fn move_relative(&self, dx: f64, dy: f64) -> bool {++ let opts: HashMap<&str, zbus::zvariant::Value<'_>> = HashMap::new();++ self.conn++ .call_method(++ Some("org.freedesktop.portal.Desktop"),++ "/org/freedesktop/portal/desktop",++ Some("org.freedesktop.portal.RemoteDesktop"),++ "NotifyPointerMotion",++ &(&self.session_path, &opts, dx, dy),++ )++ .is_ok()++ }++++ fn move_absolute(&self, x: f64, y: f64) -> bool {++ let opts: HashMap<&str, zbus::zvariant::Value<'_>> = HashMap::new();++ self.conn++ .call_method(++ Some("org.freedesktop.portal.Desktop"),++ "/org/freedesktop/portal/desktop",++ Some("org.freedesktop.portal.RemoteDesktop"),++ "NotifyPointerMotionAbsolute",++ &(&self.session_path, &opts, 0u32, x, y),++ )++ .is_ok()++ }++++ fn button(&self, evdev_btn: i32, down: bool) -> bool {++ let opts: HashMap<&str, zbus::zvariant::Value<'_>> = HashMap::new();++ let state: u32 = u32::from(down);++ self.conn++ .call_method(++ Some("org.freedesktop.portal.Desktop"),++ "/org/freedesktop/portal/desktop",++ Some("org.freedesktop.portal.RemoteDesktop"),++ "NotifyPointerButton",++ &(&self.session_path, &opts, evdev_btn, state),++ )++ .is_ok()++ }++++ fn scroll(&self, nx: i32, ny: i32) -> bool {++ let opts: HashMap<&str, zbus::zvariant::Value<'_>> = HashMap::new();++ let mut ok = true;++ if ny != 0 {++ ok &= self++ .conn++ .call_method(++ Some("org.freedesktop.portal.Desktop"),++ "/org/freedesktop/portal/desktop",++ Some("org.freedesktop.portal.RemoteDesktop"),++ "NotifyPointerAxisDiscrete",++ &(&self.session_path, &opts, 0u32, ny),++ )++ .is_ok();++ }++ if nx != 0 {++ ok &= self++ .conn++ .call_method(++ Some("org.freedesktop.portal.Desktop"),++ "/org/freedesktop/portal/desktop",++ Some("org.freedesktop.portal.RemoteDesktop"),++ "NotifyPointerAxisDiscrete",++ &(&self.session_path, &opts, 1u32, nx),++ )++ .is_ok();++ }++ ok++ }++++ fn keycode(&self, evdev_key: i32, down: bool) -> bool {++ let opts: HashMap<&str, zbus::zvariant::Value<'_>> = HashMap::new();++ let state: u32 = u32::from(down);++ self.conn++ .call_method(++ Some("org.freedesktop.portal.Desktop"),++ "/org/freedesktop/portal/desktop",++ Some("org.freedesktop.portal.RemoteDesktop"),++ "NotifyKeyboardKeycode",++ &(&self.session_path, &opts, evdev_key, state),++ )++ .is_ok()++ }++++ fn keysym(&self, keysym: i32, down: bool) -> bool {++ let opts: HashMap<&str, zbus::zvariant::Value<'_>> = HashMap::new();++ let state: u32 = u32::from(down);++ self.conn++ .call_method(++ Some("org.freedesktop.portal.Desktop"),++ "/org/freedesktop/portal/desktop",++ Some("org.freedesktop.portal.RemoteDesktop"),++ "NotifyKeyboardKeysym",++ &(&self.session_path, &opts, keysym, state),++ )++ .is_ok()++ }++}++++fn with_wayland_portal<F: FnOnce(&RemoteDesktopPortal) -> bool + Send>(f: F) -> bool {++ if !has_wayland_display() {++ return false;++ }++ super::non_tokio(|| {++ static PORTAL: OnceLock<Mutex<Option<RemoteDesktopPortal>>> = OnceLock::new();++ let mutex = PORTAL.get_or_init(|| Mutex::new(RemoteDesktopPortal::connect()));++ let guard = mutex.lock().unwrap_or_else(|e| e.into_inner());++ guard.as_ref().is_some_and(f)++ })++}++++fn has_remote_desktop_portal() -> bool {++ super::non_tokio(|| {++ let Ok(conn) = zbus::blocking::Connection::session() else {++ return false;++ };++ if !super::dbus_name_has_owner(&conn, "org.freedesktop.portal.Desktop") {++ return false;++ }++ let Ok(msg) = conn.call_method(++ Some("org.freedesktop.portal.Desktop"),++ "/org/freedesktop/portal/desktop",++ Some("org.freedesktop.DBus.Properties"),++ "Get",++ &("org.freedesktop.portal.RemoteDesktop", "AvailableDeviceTypes"),++ ) else {++ return false;++ };++ if let Ok(val) = msg.body().deserialize::<zbus::zvariant::OwnedValue>()++ && let Ok(types) = u32::try_from(val)++ {++ return types != 0;++ }++ true++ })++}++++// ---- X11 `libX11.so.6` + `libXtst.so.6` (`XTest`) backend ----+struct X11TestApi {+ _x11_lib: *mut c_void,+ _xtst_lib: *mut c_void,+ open_display: unsafe extern "C" fn(*const c_char) -> *mut c_void,+ flush: unsafe extern "C" fn(*mut c_void) -> c_int,+ string_to_keysym: unsafe extern "C" fn(*const c_char) -> c_ulong,+ keysym_to_keycode: unsafe extern "C" fn(*mut c_void, c_ulong) -> u8,++ keycode_to_keysym: Option<unsafe extern "C" fn(*mut c_void, u8, c_int) -> c_ulong>,+ query_extension:+ unsafe extern "C" fn(*mut c_void, *mut c_int, *mut c_int, *mut c_int, *mut c_int) -> c_int,+ fake_motion: unsafe extern "C" fn(*mut c_void, c_int, c_int, c_int, c_ulong) -> c_int,+ fake_relative_motion: unsafe extern "C" fn(*mut c_void, c_int, c_int, c_ulong) -> c_int,+ fake_button: unsafe extern "C" fn(*mut c_void, c_uint, c_int, c_ulong) -> c_int,+ fake_key: unsafe extern "C" fn(*mut c_void, c_uint, c_int, c_ulong) -> c_int,+}++// SAFETY: Function pointers loaded from libX11.so.6 and libXtst.so.6 are process-wide.+unsafe impl Send for X11TestApi {}+unsafe impl Sync for X11TestApi {}++struct X11Display(*mut c_void);++// SAFETY: Access to the Display pointer is serialized through a Mutex.+unsafe impl Send for X11Display {}++unsafe fn load_sym<T>(handle: *mut c_void, name: &CStr) -> Option<T> {+ let raw = unsafe { libc::dlsym(handle, name.as_ptr()) };+ if raw.is_null() {+ return None;+ }+ Some(unsafe { std::mem::transmute_copy(&raw) })+}++fn x11_test_api() -> Option<&'static X11TestApi> {+ static API: OnceLock<Option<X11TestApi>> = OnceLock::new();+ API.get_or_init(|| unsafe {+ let x11_lib = libc::dlopen(c"libX11.so.6".as_ptr(), libc::RTLD_LAZY | libc::RTLD_LOCAL);+ if x11_lib.is_null() {+ return None;+ }+ let xtst_lib = libc::dlopen(c"libXtst.so.6".as_ptr(), libc::RTLD_LAZY | libc::RTLD_LOCAL);+ if xtst_lib.is_null() {+ let _ = libc::dlclose(x11_lib);+ return None;+ }+ let api = X11TestApi {+ _x11_lib: x11_lib,+ _xtst_lib: xtst_lib,+ open_display: load_sym(x11_lib, c"XOpenDisplay")?,+ flush: load_sym(x11_lib, c"XFlush")?,+ string_to_keysym: load_sym(x11_lib, c"XStringToKeysym")?,+ keysym_to_keycode: load_sym(x11_lib, c"XKeysymToKeycode")?,++ keycode_to_keysym: load_sym(x11_lib, c"XKeycodeToKeysym"),+ query_extension: load_sym(xtst_lib, c"XTestQueryExtension")?,+ fake_motion: load_sym(xtst_lib, c"XTestFakeMotionEvent")?,+ fake_relative_motion: load_sym(xtst_lib, c"XTestFakeRelativeMotionEvent")?,+ fake_button: load_sym(xtst_lib, c"XTestFakeButtonEvent")?,+ fake_key: load_sym(xtst_lib, c"XTestFakeKeyEvent")?,+ };+ Some(api)+ })+ .as_ref()+}++fn with_xtest<F: FnOnce(&X11TestApi, *mut c_void)>(f: F) -> bool {+ if std::env::var_os("DISPLAY").is_none() {+ return false;+ }+ let Some(api) = x11_test_api() else {+ return false;+ };+ static DISPLAY_CONN: OnceLock<Mutex<Option<X11Display>>> = OnceLock::new();+ let mutex = DISPLAY_CONN.get_or_init(|| Mutex::new(None));+ let mut guard = mutex.lock().unwrap_or_else(|e| e.into_inner());+ if guard.is_none() {+ // SAFETY: XOpenDisplay(NULL) connects to $DISPLAY; XTestQueryExtension checks XTEST support.+ let dpy = unsafe { (api.open_display)(std::ptr::null()) };+ if dpy.is_null() {+ return false;+ }+ let mut ev = 0;+ let mut err = 0;+ let mut maj = 0;+ let mut min = 0;+ let ok = unsafe { (api.query_extension)(dpy, &mut ev, &mut err, &mut maj, &mut min) };+ if ok == 0 {+ return false;+ }+ *guard = Some(X11Display(dpy));+ }+ if let Some(X11Display(dpy)) = *guard {+ f(api, dpy);+ // SAFETY: dpy is a valid open X11 Display pointer protected by DISPLAY_CONN mutex.+ unsafe {+ let _ = (api.flush)(dpy);+ }+ true+ } else {+ false+ }+}+++fn uinput_writable() -> bool {++ std::fs::OpenOptions::new().write(true).open("/dev/uinput").is_ok()++ || std::fs::OpenOptions::new().write(true).open("/dev/input/uinput").is_ok()++}+++/// Returns `true` when input synthesis is supported in the current desktop session.pub fn is_available() -> bool {- if has_wayland_display() && (has_executable_in_path("ydotool") || has_executable_in_path("wtype")) {++ if uinput_writable() {+ return true;+ }+ if has_x11_display() && (x11_test_api().is_some() || has_executable_in_path("xdotool")) {+ return true;+ }++ if has_wayland_display()++ && (has_executable_in_path("ydotool")++ || has_executable_in_path("wtype")++ || has_remote_desktop_portal())++ {++ return true;++ }false}-pub fn move_relative(_dx: f32, _dy: f32) {}-pub fn move_absolute(_x: f32, _y: f32) {}-pub fn mirror_touch(_action: TouchAction, _x: f32, _y: f32) {}-pub fn mouse_button(_button: MouseButton, _action: ButtonAction) {}-pub fn release_held_buttons() {}-pub fn scroll(_dx: f32, _dy: f32) {}-pub fn type_text(_text: &str) {}-pub fn press_key(_key: &str, _mods: &[KeyMod]) {}-pub fn slide(_action: SlideAction) {}-pub fn is_user_active_within_ms(_max_idle_ms: u32) -> bool {- false++fn has_executable_in_path(binary: &str) -> bool {+ std::env::var_os("PATH")+ .is_some_and(|paths| std::env::split_paths(&paths).any(|dir| dir.join(binary).is_file()))+}++/// Fractional remainders for sub-pixel pointer motion and sub-notch scrolling,+/// plus which mouse buttons are currently held down by remote input.+#[derive(Default, Debug, Clone, PartialEq)]+struct InputState {+ move_rem_x: f32,+ move_rem_y: f32,+ scroll_rem_x: f32,+ scroll_rem_y: f32,+ held_left: bool,+ held_right: bool,+ held_middle: bool,+}++impl InputState {+ fn accumulate_move(&mut self, dx: f32, dy: f32) -> (i32, i32) {+ let total_x = self.move_rem_x + dx;+ let total_y = self.move_rem_y + dy;+ let ix = total_x.round() as i32;+ let iy = total_y.round() as i32;+ self.move_rem_x = total_x - (ix as f32);+ self.move_rem_y = total_y - (iy as f32);+ (ix, iy)+ }++ fn accumulate_scroll(&mut self, dx: f32, dy: f32) -> (i32, i32) {+ let total_x = self.scroll_rem_x + dx;+ let total_y = self.scroll_rem_y + dy;+ let nx = total_x.round() as i32;+ let ny = total_y.round() as i32;+ self.scroll_rem_x = total_x - (nx as f32);+ self.scroll_rem_y = total_y - (ny as f32);+ (nx, ny)+ }++ fn record_button(&mut self, button: MouseButton, action: ButtonAction) {+ let slot = match button {+ MouseButton::Left => &mut self.held_left,+ MouseButton::Right => &mut self.held_right,+ MouseButton::Middle => &mut self.held_middle,+ };+ *slot = matches!(action, ButtonAction::Down);+ }++ fn take_held_and_reset(&mut self) -> (bool, bool, bool) {+ let held = (self.held_left, self.held_right, self.held_middle);+ self.held_left = false;+ self.held_right = false;+ self.held_middle = false;+ self.move_rem_x = 0.0;+ self.move_rem_y = 0.0;+ self.scroll_rem_x = 0.0;+ self.scroll_rem_y = 0.0;+ held+ }+}++static STATE: Mutex<InputState> = Mutex::new(InputState {+ move_rem_x: 0.0,+ move_rem_y: 0.0,+ scroll_rem_x: 0.0,+ scroll_rem_y: 0.0,+ held_left: false,+ held_right: false,+ held_middle: false,+});++fn has_display_env() -> bool {+ std::env::var_os("DISPLAY").is_some() || std::env::var_os("WAYLAND_DISPLAY").is_some()+}++fn has_wayland_display() -> bool {+ std::env::var_os("WAYLAND_DISPLAY").is_some_and(|v| !v.is_empty())+}++fn has_x11_display() -> bool {+ std::env::var_os("DISPLAY").is_some_and(|v| !v.is_empty())+}++fn run_quiet(program: &str, args: &[&str]) -> bool {+ if !has_display_env() {+ return false;+ }+ Command::new(program)+ .args(args)+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .status()+ .is_ok_and(|s| s.success())+}+++fn run_with_stdin(program: &str, args: &[&str], input: &[u8]) -> bool {++ if !has_display_env() {++ return false;++ }++ let Ok(mut child) = Command::new(program)++ .args(args)++ .stdin(Stdio::piped())++ .stdout(Stdio::null())++ .stderr(Stdio::null())++ .spawn()++ else {++ return false;++ };++ if let Some(mut stdin) = child.stdin.take()++ && stdin.write_all(input).is_err()++ {++ let _ = child.kill();++ let _ = child.wait();++ return false;++ }++ child.wait().is_ok_and(|s| s.success())++}+++fn display_dimensions() -> (i32, i32) {++ let mut sx = 0;++ let mut sy = 0;++ let mut sw = 0;++ let mut sh = 0;++ if crate::bridge::native::ffi::linux_screen_geometry(&mut sx, &mut sy, &mut sw, &mut sh)++ && sw > 0++ && sh > 0++ {++ return (sw, sh);++ }+ if let Some((x, y, w, h)) = super::work_area() {+ let total_w = (x.max(0) + w).max(1);+ let total_h = (y.max(0) + h).max(1);+ if total_w > 0 && total_h > 0 {+ return (total_w, total_h);+ }+ }+ if has_display_env()+ && let Ok(out) = Command::new("xdotool")+ .arg("getdisplaygeometry")+ .stdin(Stdio::null())+ .stderr(Stdio::null())+ .output()+ && out.status.success()+ {+ let text = String::from_utf8_lossy(&out.stdout);+ let mut parts = text.split_whitespace().filter_map(|s| s.parse::<i32>().ok());+ if let (Some(w), Some(h)) = (parts.next(), parts.next())+ && w > 0+ && h > 0+ {+ return (w, h);+ }+ }+ (1920, 1080)+}++fn normalized_to_pixels(x: f32, y: f32, width: i32, height: i32) -> (i32, i32) {+ let max_x = (width - 1).max(1) as f32;+ let max_y = (height - 1).max(1) as f32;+ let px = (x.clamp(0.0, 1.0) * max_x).round() as i32;+ let py = (y.clamp(0.0, 1.0) * max_y).round() as i32;+ (px, py)+}++/// Moves the mouse cursor relatively by `(dx, dy)` pixels, keeping sub-pixel+/// fractions for the next move.+pub fn move_relative(dx: f32, dy: f32) {+ if !dx.is_finite() || !dy.is_finite() {+ return;+ }+ let (ix, iy) = {+ let mut s = STATE.lock().unwrap_or_else(|e| e.into_inner());+ s.accumulate_move(dx, dy)+ };+ if ix == 0 && iy == 0 {+ return;+ }++ if with_uinput(|u| u.move_relative(ix, iy)) {++ return;++ }++ if with_wayland_portal(|p| p.move_relative(f64::from(ix), f64::from(iy))) {++ return;++ }+ let sx = ix.to_string();+ let sy = iy.to_string();+ if has_wayland_display() && run_quiet("ydotool", &["mousemove", "-x", &sx, "-y", &sy]) {+ return;+ }+ if with_xtest(|api, dpy| unsafe {+ let _ = (api.fake_relative_motion)(dpy, ix, iy, 0);+ }) {+ return;+ }+ if !run_quiet("xdotool", &["mousemove_relative", "--", &sx, &sy]) {+ let _ = run_quiet("ydotool", &["mousemove", "-x", &sx, "-y", &sy]);+ }+}++/// Moves the mouse cursor to normalized coordinates `(x, y)` on the primary+/// display (`0.0..=1.0`).+pub fn move_absolute(x: f32, y: f32) {+ if !x.is_finite() || !y.is_finite() {+ return;+ }+ let (w, h) = display_dimensions();+ let (px, py) = normalized_to_pixels(x, y, w, h);++ if with_wayland_portal(|p| p.move_absolute(f64::from(px), f64::from(py))) {++ return;++ }+ let sx = px.to_string();+ let sy = py.to_string();+ if has_wayland_display() && run_quiet("ydotool", &["mousemove", "--absolute", "-x", &sx, "-y", &sy]) {+ return;+ }+ if with_xtest(|api, dpy| unsafe {+ let _ = (api.fake_motion)(dpy, -1, px, py, 0);+ }) {+ return;+ }+ if !run_quiet("xdotool", &["mousemove", "--", &sx, &sy]) {+ let _ = run_quiet("ydotool", &["mousemove", "--absolute", "-x", &sx, "-y", &sy]);+ }+}++/// Injects a normalized touch event (`0.0..=1.0`) from reverse PC mirroring as+/// absolute mouse movement + left button press/release.+pub fn mirror_touch(action: TouchAction, x: f32, y: f32) {+ if !x.is_finite() || !y.is_finite() {+ return;+ }+ let (w, h) = display_dimensions();+ let (px, py) = normalized_to_pixels(x, y, w, h);+ let sx = px.to_string();+ let sy = py.to_string();++ match action {+ TouchAction::Down => {+ if let Ok(mut s) = STATE.lock() {+ s.held_left = true;+ }+ if !has_wayland_display()+ && with_xtest(|api, dpy| unsafe {+ let _ = (api.fake_motion)(dpy, -1, px, py, 0);+ let _ = (api.fake_button)(dpy, 1, 1, 0);+ })+ {+ return;+ }+ if has_wayland_display()+ || !run_quiet("xdotool", &["mousemove", "--", &sx, &sy, "mousedown", "1"])+ {+ move_absolute(x, y);+ mouse_button(MouseButton::Left, ButtonAction::Down);+ }+ }+ TouchAction::Move => {+ move_absolute(x, y);+ }+ TouchAction::Up => {+ if let Ok(mut s) = STATE.lock() {+ s.held_left = false;+ }+ if !has_wayland_display()+ && with_xtest(|api, dpy| unsafe {+ let _ = (api.fake_motion)(dpy, -1, px, py, 0);+ let _ = (api.fake_button)(dpy, 1, 0, 0);+ })+ {+ return;+ }+ if has_wayland_display() || !run_quiet("xdotool", &["mousemove", "--", &sx, &sy, "mouseup", "1"])+ {+ move_absolute(x, y);+ mouse_button(MouseButton::Left, ButtonAction::Up);+ }+ }+ }+}++fn x11_button_num(button: MouseButton) -> c_uint {+ match button {+ MouseButton::Left => 1,+ MouseButton::Middle => 2,+ MouseButton::Right => 3,+ }+}++fn xdotool_button_id(button: MouseButton) -> &'static str {+ match button {+ MouseButton::Left => "1",+ MouseButton::Middle => "2",+ MouseButton::Right => "3",+ }+}++/// Presses, releases or clicks a mouse button.+pub fn mouse_button(button: MouseButton, action: ButtonAction) {+ {+ let mut s = STATE.lock().unwrap_or_else(|e| e.into_inner());+ s.record_button(button, action);+ }++ let evdev_btn = evdev_button_code(button);++ if with_uinput(|u| match action {++ ButtonAction::Click => u.button(evdev_btn, true) && u.button(evdev_btn, false),++ ButtonAction::Down => u.button(evdev_btn, true),++ ButtonAction::Up => u.button(evdev_btn, false),++ }) {++ return;++ }++ if with_wayland_portal(|p| match action {++ ButtonAction::Click => p.button(i32::from(evdev_btn), true) && p.button(i32::from(evdev_btn), false),++ ButtonAction::Down => p.button(i32::from(evdev_btn), true),++ ButtonAction::Up => p.button(i32::from(evdev_btn), false),++ }) {++ return;++ }+ let ydo_code = match (button, action) {+ (MouseButton::Left, ButtonAction::Click) => "0xC0",+ (MouseButton::Left, ButtonAction::Down) => "0x40",+ (MouseButton::Left, ButtonAction::Up) => "0x80",+ (MouseButton::Right, ButtonAction::Click) => "0xC1",+ (MouseButton::Right, ButtonAction::Down) => "0x41",+ (MouseButton::Right, ButtonAction::Up) => "0x81",+ (MouseButton::Middle, ButtonAction::Click) => "0xC2",+ (MouseButton::Middle, ButtonAction::Down) => "0x42",+ (MouseButton::Middle, ButtonAction::Up) => "0x82",+ };+ if has_wayland_display() && run_quiet("ydotool", &["click", ydo_code]) {+ return;+ }+ let btn_num = x11_button_num(button);+ if with_xtest(|api, dpy| unsafe {+ match action {+ ButtonAction::Click => {+ let _ = (api.fake_button)(dpy, btn_num, 1, 0);+ let _ = (api.fake_button)(dpy, btn_num, 0, 0);+ }+ ButtonAction::Down => {+ let _ = (api.fake_button)(dpy, btn_num, 1, 0);+ }+ ButtonAction::Up => {+ let _ = (api.fake_button)(dpy, btn_num, 0, 0);+ }+ }+ }) {+ return;+ }+ let btn = xdotool_button_id(button);+ let subcmd = match action {+ ButtonAction::Click => "click",+ ButtonAction::Down => "mousedown",+ ButtonAction::Up => "mouseup",+ };+ if !run_quiet("xdotool", &[subcmd, btn]) {+ let _ = run_quiet("ydotool", &["click", ydo_code]);+ }+}++/// Releases any mouse buttons still held down by remote input.+pub fn release_held_buttons() {+ let (left, right, middle) = {+ let mut s = STATE.lock().unwrap_or_else(|e| e.into_inner());+ s.take_held_and_reset()+ };+ if !left && !right && !middle {+ return;+ }++ if with_uinput(|u| {++ let mut ok = true;++ if left {++ ok &= u.button(BTN_LEFT, false);++ }++ if middle {++ ok &= u.button(BTN_MIDDLE, false);++ }++ if right {++ ok &= u.button(BTN_RIGHT, false);++ }++ ok++ }) {++ return;++ }++ if with_wayland_portal(|p| {++ let mut ok = true;++ if left {++ ok &= p.button(i32::from(BTN_LEFT), false);++ }++ if middle {++ ok &= p.button(i32::from(BTN_MIDDLE), false);++ }++ if right {++ ok &= p.button(i32::from(BTN_RIGHT), false);++ }++ ok++ }) {++ return;++ }+ if has_wayland_display() {+ let mut handled = true;+ if left {+ handled &= run_quiet("ydotool", &["click", "0x80"]);+ }+ if middle {+ handled &= run_quiet("ydotool", &["click", "0x82"]);+ }+ if right {+ handled &= run_quiet("ydotool", &["click", "0x81"]);+ }+ if handled {+ return;+ }+ }+ if !has_wayland_display()+ && with_xtest(|api, dpy| unsafe {+ if left {+ let _ = (api.fake_button)(dpy, 1, 0, 0);+ }+ if middle {+ let _ = (api.fake_button)(dpy, 2, 0, 0);+ }+ if right {+ let _ = (api.fake_button)(dpy, 3, 0, 0);+ }+ })+ {+ return;+ }+ if left && !run_quiet("xdotool", &["mouseup", "1"]) {+ let _ = run_quiet("ydotool", &["click", "0x80"]);+ }+ if middle && !run_quiet("xdotool", &["mouseup", "2"]) {+ let _ = run_quiet("ydotool", &["click", "0x82"]);+ }+ if right && !run_quiet("xdotool", &["mouseup", "3"]) {+ let _ = run_quiet("ydotool", &["click", "0x81"]);+ }+}++/// Scrolls the mouse wheel smoothly (`dy > 0` scrolls down, `dx > 0` scrolls right).+pub fn scroll(dx: f32, dy: f32) {+ if !dx.is_finite() || !dy.is_finite() {+ return;+ }+ let (nx, ny) = {+ let mut s = STATE.lock().unwrap_or_else(|e| e.into_inner());+ s.accumulate_scroll(dx, dy)+ };+ if nx == 0 && ny == 0 {+ return;+ }++ if with_uinput(|u| u.scroll(nx, ny)) {++ return;++ }++ if with_wayland_portal(|p| p.scroll(nx, ny)) {++ return;++ }+ if has_wayland_display() {+ let mut ydo_ok = true;+ if ny != 0 {+ let wheel_y = (-ny).to_string();+ ydo_ok &= run_quiet("ydotool", &["mousemove", "--wheel", "-x", "0", "-y", &wheel_y]);+ }+ if nx != 0 {+ let wheel_x = nx.to_string();+ ydo_ok &= run_quiet("ydotool", &["mousemove", "--wheel", "-x", &wheel_x, "-y", "0"]);+ }+ if ydo_ok {+ return;+ }+ }+ if with_xtest(|api, dpy| unsafe {+ if ny != 0 {+ let btn: c_uint = if ny > 0 { 5 } else { 4 };+ for _ in 0..ny.unsigned_abs() {+ let _ = (api.fake_button)(dpy, btn, 1, 0);+ let _ = (api.fake_button)(dpy, btn, 0, 0);+ }+ }+ if nx != 0 {+ let btn: c_uint = if nx > 0 { 7 } else { 6 };+ for _ in 0..nx.unsigned_abs() {+ let _ = (api.fake_button)(dpy, btn, 1, 0);+ let _ = (api.fake_button)(dpy, btn, 0, 0);+ }+ }+ }) {+ return;+ }+ if ny != 0 {+ // X11 button 4 = wheel up, button 5 = wheel down.+ let btn = if ny > 0 { "5" } else { "4" };+ let count = ny.unsigned_abs().to_string();+ if !run_quiet("xdotool", &["click", "--repeat", &count, "--delay", "1", btn]) {+ let wheel_y = (-ny).to_string();+ let _ = run_quiet("ydotool", &["mousemove", "--wheel", "-x", "0", "-y", &wheel_y]);+ }+ }+ if nx != 0 {+ // X11 button 6 = wheel left, button 7 = wheel right.+ let btn = if nx > 0 { "7" } else { "6" };+ let count = nx.unsigned_abs().to_string();+ if !run_quiet("xdotool", &["click", "--repeat", &count, "--delay", "1", btn]) {+ let wheel_x = nx.to_string();+ let _ = run_quiet("ydotool", &["mousemove", "--wheel", "-x", &wheel_x, "-y", "0"]);+ }+ }+}+- /// Types arbitrary Unicode text (filtering carriage returns `\r`).++/// Types arbitrary Unicode text (filtering carriage returns `\r`) without++/// exposing the text on any subprocess command line (`ps` / `/proc/<pid>/cmdline`).+pub fn type_text(text: &str) {+ let cleaned: String = text.chars().filter(|&c| c != '\r').collect();+ if cleaned.is_empty() {+ return;+ }- if has_wayland_display() && run_quiet("wtype", &["--", &cleaned]) {++++ // 1. `/dev/uinput`, pressing the keys that type each character on the++ // user's layout. Without a known layout, skip it: a guessed layout++ // types the wrong characters.++ let presses: Option<Vec<super::keymap::KeyPress>> =++ super::keymap::current().and_then(|km| cleaned.chars().map(|ch| km.press_for(ch)).collect());++ if let Some(ref presses) = presses++ && with_uinput(|u| presses.iter().all(|p| u.key_combo(p.code, &press_mods(p))))++ {++ return;++ }++++ // 2. On Wayland, try `org.freedesktop.portal.RemoteDesktop.NotifyKeyboardKeysym`.++ if with_wayland_portal(|p| {++ cleaned.chars().all(|ch| {++ let ks = char_to_x11_keysym(ch) as i32;++ p.keysym(ks, true) && p.keysym(ks, false)++ })++ }) {++ return;++ }++++ // 3. On X11, try in-process XTest key injection when all characters map to keycodes.++ let mut xtest_typed = false;++ let _ = with_xtest(|api, dpy| unsafe {++ let shift_ks = (api.string_to_keysym)(c"Shift_L".as_ptr());++ let shift_kc = c_uint::from((api.keysym_to_keycode)(dpy, shift_ks));++ let mut steps: Vec<(c_uint, bool)> = Vec::with_capacity(cleaned.len());++ for ch in cleaned.chars() {++ let ks = c_ulong::from(char_to_x11_keysym(ch));++ let kc = (api.keysym_to_keycode)(dpy, ks);++ if kc == 0 {++ return;++ }++ let needs_shift = if let Some(kc_to_ks) = api.keycode_to_keysym {++ let unshifted = kc_to_ks(dpy, kc, 0);++ let shifted = kc_to_ks(dpy, kc, 1);++ unshifted != ks && shifted == ks++ } else {++ ch.is_ascii_uppercase()++ || matches!(++ ch,++ '!' | '@'++ | '#'++ | '$'++ | '%'++ | '^'++ | '&'++ | '*'++ | '('++ | ')'++ | '_'++ | '+'++ | '{'++ | '}'++ | '|'++ | ':'++ | '"'++ | '<'++ | '>'++ | '?'++ | '~'++ )++ };++ steps.push((c_uint::from(kc), needs_shift));++ }++ for (kc, shift) in steps {++ if shift && shift_kc != 0 {++ let _ = (api.fake_key)(dpy, shift_kc, 1, 0);++ }++ let _ = (api.fake_key)(dpy, kc, 1, 0);++ let _ = (api.fake_key)(dpy, kc, 0, 0);++ if shift && shift_kc != 0 {++ let _ = (api.fake_key)(dpy, shift_kc, 0, 0);++ }++ }++ xtest_typed = true;++ });++ if xtest_typed {++ return;++ }++++ // 4. Pipe text over stdin (`wtype -` or `xdotool type --file -`) so it is never on argv.++ if has_wayland_display() && run_with_stdin("wtype", &["-"], cleaned.as_bytes()) {+ return;+ }- if !run_quiet("xdotool", &["type", "--clearmodifiers", "--delay", "0", "--", &cleaned]) {- let _ = run_quiet("wtype", &["--", &cleaned]);++ if !run_with_stdin(++ "xdotool",++ &["type", "--clearmodifiers", "--delay", "0", "--file", "-"],++ cleaned.as_bytes(),++ ) {++ let _ = run_with_stdin("wtype", &["-"], cleaned.as_bytes());+ }+}++/// Resolves a protocol key or shortcut name into `(keysym, extra_mods)`.+pub(crate) fn resolve_key(key: &str) -> Option<(String, &'static [KeyMod])> {+ const CTRL: &[KeyMod] = &[KeyMod::Ctrl];+ const WIN: &[KeyMod] = &[KeyMod::Win];+ const NONE: &[KeyMod] = &[];++ let trimmed = key.trim();+ if trimmed.is_empty() {+ return None;+ }+ let lower = trimmed.to_ascii_lowercase();+ let (sym, mods): (&str, &'static [KeyMod]) = match lower.as_str() {+ "copy" => ("c", CTRL),+ "paste" => ("v", CTRL),+ "cut" => ("x", CTRL),+ "undo" => ("z", CTRL),+ "redo" => ("y", CTRL),+ "select_all" => ("a", CTRL),+ "task_view" => ("Tab", WIN),+ "enter" | "return" => ("Return", NONE),+ "backspace" => ("BackSpace", NONE),+ "tab" => ("Tab", NONE),+ "escape" | "esc" => ("Escape", NONE),+ "space" => ("space", NONE),+ "delete" | "del" => ("Delete", NONE),+ "insert" | "ins" => ("Insert", NONE),+ "up" => ("Up", NONE),+ "down" => ("Down", NONE),+ "left" => ("Left", NONE),+ "right" => ("Right", NONE),+ "home" => ("Home", NONE),+ "end" => ("End", NONE),+ "page_up" | "pageup" | "pgup" | "prior" => ("Prior", NONE),+ "page_down" | "pagedown" | "pgdn" | "next" => ("Next", NONE),+ "print" | "printscreen" | "sysrq" => ("Print", NONE),+ "f1" => ("F1", NONE),+ "f2" => ("F2", NONE),+ "f3" => ("F3", NONE),+ "f4" => ("F4", NONE),+ "f5" => ("F5", NONE),+ "f6" => ("F6", NONE),+ "f7" => ("F7", NONE),+ "f8" => ("F8", NONE),+ "f9" => ("F9", NONE),+ "f10" => ("F10", NONE),+ "f11" => ("F11", NONE),+ "f12" => ("F12", NONE),+ "volume_up" | "xf86audioraisevolume" => ("XF86AudioRaiseVolume", NONE),+ "volume_down" | "xf86audiolowervolume" => ("XF86AudioLowerVolume", NONE),+ "volume_mute" | "xf86audiomute" => ("XF86AudioMute", NONE),+ "play_pause" | "xf86audioplay" => ("XF86AudioPlay", NONE),+ "next_track" | "xf86audionext" => ("XF86AudioNext", NONE),+ "prev_track" | "xf86audioprev" => ("XF86AudioPrev", NONE),+ s if s.len() == 1 => {+ let b = s.as_bytes()[0];+ if b.is_ascii_lowercase() || b.is_ascii_digit() {+ return Some((s.to_owned(), NONE));+ }+ return None;+ }+ _ => return None,+ };+ Some((sym.to_owned(), mods))+}++fn mod_name(m: KeyMod) -> &'static str {+ match m {+ KeyMod::Ctrl => "ctrl",+ KeyMod::Alt => "alt",+ KeyMod::Shift => "shift",+ KeyMod::Win => "super",+ }+}++/// Formats an `xdotool key` combo string (e.g. `"ctrl+shift+k"` or `"super+Tab"`)+/// for a protocol key and modifier list.+pub(crate) fn format_xdotool_combo(key: &str, mods: &[KeyMod]) -> Option<String> {+ let (sym, preset_mods) = resolve_key(key)?;+ let mut all_mods: Vec<KeyMod> = Vec::with_capacity(4);+ for &m in preset_mods.iter().chain(mods.iter()) {+ if !all_mods.contains(&m) {+ all_mods.push(m);+ }+ }+ if all_mods.is_empty() {+ return Some(sym);+ }+ let mut parts: Vec<&str> = all_mods.iter().map(|&m| mod_name(m)).collect();+ parts.push(&sym);+ Some(parts.join("+"))+}++fn mod_x11_keysym_name(m: KeyMod) -> &'static CStr {+ match m {+ KeyMod::Ctrl => c"Control_L",+ KeyMod::Alt => c"Alt_L",+ KeyMod::Shift => c"Shift_L",+ KeyMod::Win => c"Super_L",+ }+}++/// Presses a named key or shortcut with optional modifiers.+pub fn press_key(key: &str, mods: &[KeyMod]) {+ if key.eq_ignore_ascii_case("lock") {+ let _ = crate::links::power(PowerAction::Lock);+ return;+ }+ let Some((sym, preset_mods)) = resolve_key(key) else {+ return;+ };+ let mut all_mods: Vec<KeyMod> = Vec::with_capacity(4);+ for &m in preset_mods.iter().chain(mods.iter()) {+ if !all_mods.contains(&m) {+ all_mods.push(m);+ }+ }++++ if let Some(evdev_code) = key_code_for_sym(&sym) {++ let mod_codes: Vec<u16> = all_mods.iter().map(|&m| evdev_key_for_mod(m)).collect();++ if with_uinput(|u| u.key_combo(evdev_code, &mod_codes)) {++ return;++ }++ if with_wayland_portal(|p| {++ let mut ok = true;++ for &mc in &mod_codes {++ ok &= p.keycode(i32::from(mc), true);++ }++ ok &= p.keycode(i32::from(evdev_code), true);++ ok &= p.keycode(i32::from(evdev_code), false);++ for &mc in mod_codes.iter().rev() {++ ok &= p.keycode(i32::from(mc), false);++ }++ ok++ }) {++ return;++ }++ }+++ if has_wayland_display() {+ let mut wtype_args: Vec<String> = Vec::new();+ for &m in &all_mods {+ let wm = match m {+ KeyMod::Ctrl => "ctrl",+ KeyMod::Alt => "alt",+ KeyMod::Shift => "shift",+ KeyMod::Win => "logo",+ };+ wtype_args.push("-M".into());+ wtype_args.push(wm.into());+ }+ wtype_args.push("-k".into());+ wtype_args.push(sym.clone());+ let refs: Vec<&str> = wtype_args.iter().map(String::as_str).collect();+ if run_quiet("wtype", &refs) {+ return;+ }+ }+ if let Ok(c_sym) = CString::new(sym.as_str()) {+ let mut injected = false;+ let _ = with_xtest(|api, dpy| unsafe {+ let ks = (api.string_to_keysym)(c_sym.as_ptr());+ if ks == 0 {+ return;+ }+ let kc = (api.keysym_to_keycode)(dpy, ks);+ if kc == 0 {+ return;+ }+ let mut mod_kcs: Vec<c_uint> = Vec::with_capacity(all_mods.len());+ for &m in &all_mods {+ let mks = (api.string_to_keysym)(mod_x11_keysym_name(m).as_ptr());+ let mkc = (api.keysym_to_keycode)(dpy, mks);+ if mkc != 0 {+ mod_kcs.push(c_uint::from(mkc));+ }+ }+ for &mkc in &mod_kcs {+ let _ = (api.fake_key)(dpy, mkc, 1, 0);+ }+ let _ = (api.fake_key)(dpy, c_uint::from(kc), 1, 0);+ let _ = (api.fake_key)(dpy, c_uint::from(kc), 0, 0);+ for &mkc in mod_kcs.iter().rev() {+ let _ = (api.fake_key)(dpy, mkc, 0, 0);+ }+ injected = true;+ });+ if injected {+ return;+ }+ }+ if let Some(combo) = format_xdotool_combo(key, mods) {+ let _ = run_quiet("xdotool", &["key", "--clearmodifiers", &combo]);+ }+}++/// Executes a presentation slide action.+pub fn slide(action: SlideAction) {+ let key = match action {+ SlideAction::Next => "page_down",+ SlideAction::Previous => "page_up",+ SlideAction::Start => "f5",+ SlideAction::Stop => "escape",+ SlideAction::Black => "b",+ };+ press_key(key, &[]);+}++/// Parses idle milliseconds from `xprintidle` output (`"8801\n"`) or D-Bus+/// `GetIdletime` / `GetSessionIdleTime` output (`"(uint64 8801,)"` or `"(uint32 8,)"`).+pub(crate) fn parse_idle_output_ms(raw: &str, is_seconds: bool) -> Option<u64> {+ let trimmed = raw.trim();+ if trimmed.is_empty() {+ return None;+ }+ if let Ok(val) = trimmed.parse::<u64>() {+ return Some(if is_seconds { val.saturating_mul(1000) } else { val });+ }- // Extract the first integer token from gdbus tuple output like "(uint64 8801,)" or "(uint32 12,)".+ for token in trimmed.split(|c: char| !c.is_ascii_digit()) {+ if !token.is_empty()+ && token != "64"+ && token != "32"+ && let Ok(val) = token.parse::<u64>()+ {+ return Some(if is_seconds { val.saturating_mul(1000) } else { val });+ }+ }+ None+}+- fn query_idle_ms_dbus() -> Option<u64> {- let conn = zbus::blocking::Connection::session().ok()?;- if let Ok(reply) = conn.call_method(- Some("org.gnome.Mutter.IdleMonitor"),- "/org/gnome/Mutter/IdleMonitor/Core",- Some("org.gnome.Mutter.IdleMonitor"),- "GetIdletime",- &(),- ) && let Ok(ms) = reply.body().deserialize::<u64>()++fn query_idle_ms() -> Option<u64> {++ if !has_display_env() {++ return None;++ }++++ // 1. On X11, prefer `xprintidle` first (always returns milliseconds).++ if has_x11_display()++ && let Ok(out) = Command::new("xprintidle").stdin(Stdio::null()).stderr(Stdio::null()).output()++ && out.status.success()++ && let Some(ms) = parse_idle_output_ms(&String::from_utf8_lossy(&out.stdout), false)+ {+ return Some(ms);+ }- if let Ok(reply) = conn.call_method(- Some("org.freedesktop.ScreenSaver"),- "/org/freedesktop/ScreenSaver",- Some("org.freedesktop.ScreenSaver"),- "GetSessionIdleTime",- &(),- ) {- let body = reply.body();- if let Ok(val) = body.deserialize::<u32>() {- return Some(u64::from(val));++++ // 2. Query D-Bus idle monitors in-process via `zbus::blocking::Connection::session()`.++ if let Some(ms) = super::non_tokio(|| {++ let conn = zbus::blocking::Connection::session().ok()?;++ // GNOME Mutter IdleMonitor returns u64 milliseconds.++ if super::dbus_name_has_owner(&conn, "org.gnome.Mutter.IdleMonitor")++ && let Ok(reply) = conn.call_method(++ Some("org.gnome.Mutter.IdleMonitor"),++ "/org/gnome/Mutter/IdleMonitor/Core",++ Some("org.gnome.Mutter.IdleMonitor"),++ "GetIdletime",++ &(),++ )++ {++ let body = reply.body();++ if let Ok(ms) = body.deserialize::<u64>().or_else(|_| body.deserialize::<(u64,)>().map(|(v,)| v))++ {++ return Some(ms);++ }+ }- if let Ok(val) = body.deserialize::<u64>() {- return Some(val);++++ // Freedesktop ScreenSaver (`GetSessionIdleTime` returns u32).++ if super::dbus_name_has_owner(&conn, "org.freedesktop.ScreenSaver") {++ for path in ["/org/freedesktop/ScreenSaver", "/ScreenSaver"] {++ if let Ok(reply) = conn.call_method(++ Some("org.freedesktop.ScreenSaver"),++ path,++ Some("org.freedesktop.ScreenSaver"),++ "GetSessionIdleTime",++ &(),++ ) {++ let body = reply.body();++ if let Ok(val) =++ body.deserialize::<u32>().or_else(|_| body.deserialize::<(u32,)>().map(|(v,)| v))++ {++ return Some(u64::from(val));++ }++ }++ }+ }++ None++ }) {++ return Some(ms);+ }- None- }+- fn query_idle_ms() -> Option<u64> {- if !has_display_env() {- return None;- }- if let Ok(out) = Command::new("xprintidle").stdin(Stdio::null()).stderr(Stdio::null()).output()++ // 3. Fallback to `xprintidle` on Wayland with XWayland if D-Bus idle monitors were unavailable.++ if !has_x11_display()++ && let Ok(out) = Command::new("xprintidle").stdin(Stdio::null()).stderr(Stdio::null()).output()+ && out.status.success()+ && let Some(ms) = parse_idle_output_ms(&String::from_utf8_lossy(&out.stdout), false)+ {+ return Some(ms);+ }- query_idle_ms_dbus()++++ None+}++/// Returns `true` when the user has moved the mouse or pressed a key on this PC+/// within the last `max_idle_ms` milliseconds.+pub fn is_user_active_within_ms(max_idle_ms: u32) -> bool {+ match query_idle_ms() {+ Some(idle_ms) => idle_ms <= u64::from(max_idle_ms),+ None => true,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn resolves_named_keys_and_shortcuts() {+ assert_eq!(resolve_key("enter"), Some(("Return".to_owned(), &[][..])));+ assert_eq!(resolve_key("up"), Some(("Up".to_owned(), &[][..])));+ assert_eq!(resolve_key("copy"), Some(("c".to_owned(), &[KeyMod::Ctrl][..])));+ assert_eq!(resolve_key("paste"), Some(("v".to_owned(), &[KeyMod::Ctrl][..])));+ assert_eq!(resolve_key("task_view"), Some(("Tab".to_owned(), &[KeyMod::Win][..])));+ assert_eq!(resolve_key("a"), Some(("a".to_owned(), &[][..])));+ assert_eq!(resolve_key("A"), Some(("a".to_owned(), &[][..])));+ assert_eq!(resolve_key("5"), Some(("5".to_owned(), &[][..])));+ assert_eq!(resolve_key("f5"), Some(("F5".to_owned(), &[][..])));+ assert_eq!(resolve_key("play_pause"), Some(("XF86AudioPlay".to_owned(), &[][..])));+ assert_eq!(resolve_key("volume_up"), Some(("XF86AudioRaiseVolume".to_owned(), &[][..])));+ assert_eq!(resolve_key("print"), Some(("Print".to_owned(), &[][..])));+ assert!(resolve_key("unknown_key").is_none());+ }+++ #[test]++ fn maps_evdev_keys_and_unicode_keysyms() {++ assert_eq!(evdev_key_for_sym("Return"), Some(28));++ assert_eq!(evdev_key_for_sym("Escape"), Some(1));++ assert_eq!(evdev_key_for_sym("F5"), Some(63));++ assert_eq!(evdev_key_for_sym("XF86AudioPlay"), Some(164));++ assert_eq!(evdev_key_for_mod(KeyMod::Win), 125);++++ assert_eq!(char_to_x11_keysym('a'), 0x61);++ assert_eq!(char_to_x11_keysym('\n'), 0xff0d);++ assert_eq!(char_to_x11_keysym('é'), 0x00e9);++ assert_eq!(char_to_x11_keysym('€'), 0x0100_20ac);++ }+++ #[test]+ fn formats_xdotool_combos_with_preset_and_explicit_modifiers() {+ assert_eq!(format_xdotool_combo("copy", &[]), Some("ctrl+c".to_owned()));+ assert_eq!(+ format_xdotool_combo("k", &[KeyMod::Ctrl, KeyMod::Shift]),+ Some("ctrl+shift+k".to_owned())+ );+ assert_eq!(format_xdotool_combo("tab", &[KeyMod::Alt]), Some("alt+Tab".to_owned()));+ assert_eq!(format_xdotool_combo("d", &[KeyMod::Win]), Some("super+d".to_owned()));+ assert_eq!(format_xdotool_combo("f5", &[]), Some("F5".to_owned()));+ }++ #[test]+ fn accumulates_subpixel_move_and_scroll_remainders() {+ let mut s = InputState::default();+ assert_eq!(s.accumulate_move(0.4, -0.4), (0, 0));+ assert_eq!(s.accumulate_move(0.4, -0.4), (1, -1));+ assert_eq!(s.accumulate_move(0.4, -0.4), (0, 0));++ assert_eq!(s.accumulate_scroll(0.3, 0.3), (0, 0));+ assert_eq!(s.accumulate_scroll(0.3, 0.3), (1, 1));+ }++ #[test]+ fn tracks_held_mouse_buttons_and_resets_on_release() {+ let mut s = InputState::default();+ s.record_button(MouseButton::Left, ButtonAction::Down);+ s.record_button(MouseButton::Right, ButtonAction::Click);+ assert!(s.held_left);+ assert!(!s.held_right);++ let held = s.take_held_and_reset();+ assert_eq!(held, (true, false, false));+ assert!(!s.held_left);+ }++ #[test]+ fn maps_normalized_coordinates_and_parses_idle_output() {+ assert_eq!(normalized_to_pixels(0.0, 0.0, 1920, 1080), (0, 0));+ assert_eq!(normalized_to_pixels(1.0, 1.0, 1920, 1080), (1919, 1079));+ assert_eq!(normalized_to_pixels(0.5, 0.5, 1921, 1081), (960, 540));++ assert_eq!(parse_idle_output_ms("8801\n", false), Some(8801));+ assert_eq!(parse_idle_output_ms("(uint64 4250,)", false), Some(4250));++ assert_eq!(parse_idle_output_ms("(uint32 19,)", true), Some(19_000));+ assert_eq!(parse_idle_output_ms("12", true), Some(12_000));+ }}diff --cc desktop/app/src/linux/keymap.rsindex 0000000,0000000..5fd79b4new file mode 100644--- /dev/null+++ b/desktop/app/src/linux/keymap.rs@@@ -1,0 -1,0 +1,366 @@@++// SPDX-License-Identifier: GPL-3.0-or-later++//! The user's keyboard layout, for typing through `/dev/uinput`.++//!++//! uinput sends physical key codes and the desktop turns them into++//! characters with the user's layout, so typing "z" means pressing the key++//! that is z on that layout (where Y is on a US keyboard, for German). This++//! compiles the configured layout with libxkbcommon, which every Qt app++//! already loads, and finds for each character the key and the modifiers++//! (Shift, AltGr) that produce it.++++use std::{++ collections::HashMap,++ ffi::{CString, c_char, c_int, c_void},++ sync::OnceLock,++};++++/// What the virtual keyboard presses for one character.++#[derive(Debug, Clone, Copy, PartialEq, Eq)]++pub struct KeyPress {++ /// Linux evdev `KEY_*` code.++ pub code: u16,++ pub shift: bool,++ pub altgr: bool,++}++++/// An XKB layout as configured by the desktop: model, layout, variant and options.++#[derive(Debug, Clone, Default, PartialEq, Eq)]++pub struct Layout {++ pub model: String,++ pub layout: String,++ pub variant: String,++ pub options: String,++}++++/// Characters of one layout and the keys that type them.++#[derive(Debug, Default)]++pub struct Keymap {++ by_char: HashMap<char, KeyPress>,++}++++impl Keymap {++ /// The key that types `ch`, if this layout has one.++ pub fn press_for(&self, ch: char) -> Option<KeyPress> {++ match ch {++ '\n' => Some(KeyPress { code: KEY_ENTER, shift: false, altgr: false }),++ '\t' => Some(KeyPress { code: KEY_TAB, shift: false, altgr: false }),++ _ => self.by_char.get(&ch).copied(),++ }++ }++}++++/// The keymap for the desktop's current layout, compiled once. `None` when++/// the layout can't be found or compiled: callers then must not type through++/// uinput, since guessing a layout types the wrong characters.++pub fn current() -> Option<&'static Keymap> {++ static KEYMAP: OnceLock<Option<Keymap>> = OnceLock::new();++ KEYMAP++ .get_or_init(|| {++ let layout = detect_layout()?;++ let keymap = compile(&layout);++ if keymap.is_none() {++ tracing::warn!(layout = %layout.layout, "can't compile the keyboard layout");++ }++ keymap++ })++ .as_ref()++}++++const KEY_TAB: u16 = 15;++const KEY_ENTER: u16 = 28;++/// The right Alt key, which is AltGr (ISO_Level3_Shift) on layouts that have a third level.++pub const KEY_RIGHTALT: u16 = 100;++/// XKB key codes are evdev codes plus 8.++const XKB_EVDEV_OFFSET: u32 = 8;++++/// Keypad keys produce digits and operators too, but depend on Num Lock; the++/// main keys are the ones to press.++fn is_keypad(code: u16) -> bool {++ matches!(code, 55 | 71..=83 | 96 | 98 | 117 | 118 | 121)++}++++// ---- Finding the layout ----++++/// The layout the desktop types with, from (in order) the `XKB_DEFAULT_*`++/// variables, GNOME's input sources, KDE's keyboard settings, and the++/// system's keyboard configuration.++pub fn detect_layout() -> Option<Layout> {++ if let Some(layout) = from_env() {++ return Some(layout);++ }++ if let Some(layout) = std::process::Command::new("gsettings")++ .args(["get", "org.gnome.desktop.input-sources", "sources"])++ .stdin(std::process::Stdio::null())++ .stderr(std::process::Stdio::null())++ .output()++ .ok()++ .filter(|o| o.status.success())++ .and_then(|o| parse_gnome_sources(&String::from_utf8_lossy(&o.stdout)))++ {++ return Some(layout);++ }++ if let Some(layout) = dirs::config_dir()++ .and_then(|d| std::fs::read_to_string(d.join("kxkbrc")).ok())++ .and_then(|text| parse_kxkbrc(&text))++ {++ return Some(layout);++ }++ if let Some(layout) =++ std::fs::read_to_string("/etc/default/keyboard").ok().and_then(|text| parse_default_keyboard(&text))++ {++ return Some(layout);++ }++ std::fs::read_to_string("/etc/X11/xorg.conf.d/00-keyboard.conf")++ .ok()++ .and_then(|text| parse_xorg_keyboard(&text))++}++++fn from_env() -> Option<Layout> {++ let var = |name: &str| std::env::var(name).unwrap_or_default().trim().to_owned();++ let layout = first_of(&var("XKB_DEFAULT_LAYOUT"));++ (!layout.is_empty()).then(|| Layout {++ model: var("XKB_DEFAULT_MODEL"),++ layout,++ variant: first_of(&var("XKB_DEFAULT_VARIANT")),++ options: var("XKB_DEFAULT_OPTIONS"),++ })++}++++/// The first entry of a comma-separated XKB list ("de,us" -> "de").++fn first_of(list: &str) -> String {++ list.split(',').next().unwrap_or_default().trim().to_owned()++}++++/// GNOME: `[('xkb', 'de+nodeadkeys'), ('ibus', 'mozc-jp')]`, first XKB source.++/// An empty list (`@a(ss) []`) means GNOME follows the system layout.++pub(crate) fn parse_gnome_sources(text: &str) -> Option<Layout> {++ let mut rest = text;++ while let Some(start) = rest.find("('") {++ rest = &rest[start + 2..];++ let (kind, after) = rest.split_once("', '")?;++ let (id, after) = after.split_once("')")?;++ rest = after;++ if kind == "xkb" && !id.is_empty() {++ let (layout, variant) = id.split_once('+').unwrap_or((id, ""));++ return Some(Layout { layout: layout.into(), variant: variant.into(), ..Layout::default() });++ }++ }++ None++}++++/// KDE: `~/.config/kxkbrc`, used only when `Use=true` (otherwise KDE keeps the system layout).++pub(crate) fn parse_kxkbrc(text: &str) -> Option<Layout> {++ let mut in_layout = false;++ let mut values = HashMap::new();++ for line in text.lines() {++ let line = line.trim();++ if line.starts_with('[') {++ in_layout = line == "[Layout]";++ } else if in_layout && let Some((key, value)) = line.split_once('=') {++ values.insert(key.trim().to_owned(), value.trim().to_owned());++ }++ }++ if values.get("Use").map(String::as_str) != Some("true") {++ return None;++ }++ let layout = first_of(values.get("LayoutList")?);++ (!layout.is_empty()).then(|| Layout {++ model: values.get("Model").cloned().unwrap_or_default(),++ layout,++ variant: first_of(values.get("VariantList").map(String::as_str).unwrap_or_default()),++ options: values.get("Options").cloned().unwrap_or_default(),++ })++}++++/// Debian and Ubuntu: `/etc/default/keyboard` (`XKBLAYOUT="de"`, ...).++pub(crate) fn parse_default_keyboard(text: &str) -> Option<Layout> {++ let mut values = HashMap::new();++ for line in text.lines() {++ if let Some((key, value)) = line.trim().split_once('=') {++ values.insert(key.trim(), value.trim().trim_matches('"').to_owned());++ }++ }++ let layout = first_of(values.get("XKBLAYOUT")?);++ (!layout.is_empty()).then(|| Layout {++ model: values.get("XKBMODEL").cloned().unwrap_or_default(),++ layout,++ variant: first_of(values.get("XKBVARIANT").map(String::as_str).unwrap_or_default()),++ options: values.get("XKBOPTIONS").cloned().unwrap_or_default(),++ })++}++++/// Fedora, Arch and others: `/etc/X11/xorg.conf.d/00-keyboard.conf`++/// (`Option "XkbLayout" "de"`), as written by `localectl`.++pub(crate) fn parse_xorg_keyboard(text: &str) -> Option<Layout> {++ let mut layout = Layout::default();++ for line in text.lines() {++ let mut parts = line.split('"').map(str::trim).filter(|p| !p.is_empty());++ if parts.next() != Some("Option") {++ continue;++ }++ let (Some(key), Some(value)) = (parts.next(), parts.next()) else { continue };++ match key {++ "XkbModel" => layout.model = value.into(),++ "XkbLayout" => layout.layout = first_of(value),++ "XkbVariant" => layout.variant = first_of(value),++ "XkbOptions" => layout.options = value.into(),++ _ => {}++ }++ }++ (!layout.layout.is_empty()).then_some(layout)++}++++// ---- Compiling it with libxkbcommon ----++++#[repr(C)]++struct RuleNames {++ rules: *const c_char,++ model: *const c_char,++ layout: *const c_char,++ variant: *const c_char,++ options: *const c_char,++}++++type ContextNew = unsafe extern "C" fn(c_int) -> *mut c_void;++type ContextUnref = unsafe extern "C" fn(*mut c_void);++type KeymapNewFromNames = unsafe extern "C" fn(*mut c_void, *const RuleNames, c_int) -> *mut c_void;++type KeymapUnref = unsafe extern "C" fn(*mut c_void);++type KeymapKeycode = unsafe extern "C" fn(*mut c_void) -> u32;++type KeymapNumLevels = unsafe extern "C" fn(*mut c_void, u32, u32) -> u32;++type KeymapSymsByLevel = unsafe extern "C" fn(*mut c_void, u32, u32, u32, *mut *const u32) -> c_int;++type KeysymToUtf32 = unsafe extern "C" fn(u32) -> u32;++++/// Compiles `layout` and maps every character it can type to a key.++pub fn compile(layout: &Layout) -> Option<Keymap> {++ // SAFETY: libxkbcommon is loaded and its functions resolved by name with++ // the signatures from xkbcommon.h; every object created here is released++ // before returning, and `syms` points into the keymap while it is alive.++ unsafe {++ let lib = libc::dlopen(c"libxkbcommon.so.0".as_ptr(), libc::RTLD_LAZY | libc::RTLD_LOCAL);++ if lib.is_null() {++ return None;++ }++ let sym = |name: &std::ffi::CStr| {++ let p = libc::dlsym(lib, name.as_ptr());++ (!p.is_null()).then_some(p)++ };++ let context_new: ContextNew = std::mem::transmute(sym(c"xkb_context_new")?);++ let context_unref: ContextUnref = std::mem::transmute(sym(c"xkb_context_unref")?);++ let keymap_new: KeymapNewFromNames = std::mem::transmute(sym(c"xkb_keymap_new_from_names")?);++ let keymap_unref: KeymapUnref = std::mem::transmute(sym(c"xkb_keymap_unref")?);++ let min_keycode: KeymapKeycode = std::mem::transmute(sym(c"xkb_keymap_min_keycode")?);++ let max_keycode: KeymapKeycode = std::mem::transmute(sym(c"xkb_keymap_max_keycode")?);++ let num_levels: KeymapNumLevels = std::mem::transmute(sym(c"xkb_keymap_num_levels_for_key")?);++ let syms_by_level: KeymapSymsByLevel = std::mem::transmute(sym(c"xkb_keymap_key_get_syms_by_level")?);++ let to_utf32: KeysymToUtf32 = std::mem::transmute(sym(c"xkb_keysym_to_utf32")?);++++ let c = |s: &str| CString::new(s).ok();++ let (model, name, variant, options) =++ (c(&layout.model)?, c(&layout.layout)?, c(&layout.variant)?, c(&layout.options)?);++ let opt = |s: &CString| if s.as_bytes().is_empty() { std::ptr::null() } else { s.as_ptr() };++ let names = RuleNames {++ rules: std::ptr::null(),++ model: opt(&model),++ layout: name.as_ptr(),++ variant: opt(&variant),++ options: opt(&options),++ };++++ let ctx = context_new(0);++ if ctx.is_null() {++ return None;++ }++ let km = keymap_new(ctx, &names, 0);++ if km.is_null() {++ context_unref(ctx);++ return None;++ }++++ let mut by_char = HashMap::new();++ for keycode in min_keycode(km)..=max_keycode(km) {++ let Some(code) = keycode.checked_sub(XKB_EVDEV_OFFSET).and_then(|c| u16::try_from(c).ok()) else {++ continue;++ };++ if is_keypad(code) {++ continue;++ }++ // Levels 0 to 3 of the standard key types: none, Shift, AltGr, Shift+AltGr.++ for level in 0..num_levels(km, keycode, 0).min(4) {++ let mut syms: *const u32 = std::ptr::null();++ let count = syms_by_level(km, keycode, 0, level, &mut syms);++ if count <= 0 || syms.is_null() {++ continue;++ }++ for &keysym in std::slice::from_raw_parts(syms, count as usize) {++ let Some(ch) = char::from_u32(to_utf32(keysym)).filter(|ch| !ch.is_control()) else {++ continue;++ };++ // The lowest level wins: plain before Shift before AltGr.++ by_char.entry(ch).or_insert(KeyPress { code, shift: level % 2 == 1, altgr: level >= 2 });++ }++ }++ }++ keymap_unref(km);++ context_unref(ctx);++ Some(Keymap { by_char })++ }++}++++#[cfg(test)]++mod tests {++ use super::*;++++ #[test]++ fn reads_the_layout_from_each_desktop() {++ let gnome = parse_gnome_sources("[('ibus', 'mozc-jp'), ('xkb', 'de+nodeadkeys'), ('xkb', 'us')]\n");++ assert_eq!(gnome.map(|l| (l.layout, l.variant)), Some(("de".into(), "nodeadkeys".into())));++ assert_eq!(parse_gnome_sources("@a(ss) []\n"), None);++++ let kde = "[Layout]\nDisplayNames=,\nLayoutList=fr,us\nModel=pc105\nUse=true\nVariantList=azerty,\n";++ let kde = parse_kxkbrc(kde).unwrap();++ assert_eq!(++ (kde.layout.as_str(), kde.variant.as_str(), kde.model.as_str()),++ ("fr", "azerty", "pc105")++ );++ assert_eq!(++ parse_kxkbrc("[Layout]\nLayoutList=fr\nUse=false\n"),++ None,++ "Use=false keeps the system layout"++ );++++ let debian = "XKBMODEL=\"pc105\"\nXKBLAYOUT=\"de,us\"\nXKBVARIANT=\"\"\nXKBOPTIONS=\"\"\n";++ assert_eq!(parse_default_keyboard(debian).map(|l| l.layout), Some("de".into()));++++ let xorg = "Section \"InputClass\"\n Identifier \"system-keyboard\"\n Option \"XkbLayout\" \"ch\"\n Option \"XkbVariant\" \"fr\"\nEndSection\n";++ let xorg = parse_xorg_keyboard(xorg).unwrap();++ assert_eq!((xorg.layout.as_str(), xorg.variant.as_str()), ("ch", "fr"));++ }++++ fn layout(name: &str, variant: &str) -> Keymap {++ compile(&Layout { layout: name.into(), variant: variant.into(), ..Layout::default() })++ .expect("libxkbcommon and xkeyboard-config are installed wherever Qt is")++ }++++ #[test]++ fn finds_the_key_for_each_character_on_the_layout() {++ let us = layout("us", "");++ assert_eq!(us.press_for('z'), Some(KeyPress { code: 44, shift: false, altgr: false }));++ assert_eq!(us.press_for('Z'), Some(KeyPress { code: 44, shift: true, altgr: false }));++ assert_eq!(us.press_for('@'), Some(KeyPress { code: 3, shift: true, altgr: false }));++++ // German: Y and Z swap places, @ is AltGr+Q, umlauts have their own keys.++ let de = layout("de", "");++ assert_eq!(de.press_for('z'), Some(KeyPress { code: 21, shift: false, altgr: false }));++ assert_eq!(de.press_for('y'), Some(KeyPress { code: 44, shift: false, altgr: false }));++ assert_eq!(de.press_for('@'), Some(KeyPress { code: 16, shift: false, altgr: true }));++ assert_eq!(de.press_for('ö'), Some(KeyPress { code: 39, shift: false, altgr: false }));++++ // French: A and Q swap, digits need Shift.++ let fr = layout("fr", "");++ assert_eq!(fr.press_for('a'), Some(KeyPress { code: 16, shift: false, altgr: false }));++ assert_eq!(fr.press_for('1'), Some(KeyPress { code: 2, shift: true, altgr: false }));++++ assert_eq!(us.press_for('\n').map(|p| p.code), Some(KEY_ENTER));++ assert_eq!(us.press_for('ö'), None, "a character the layout can't type");++ }++}diff --cc desktop/app/src/linux/mod.rsindex b61829f,9037fe0..760785f--- a/desktop/app/src/linux/mod.rs+++ b/desktop/app/src/linux/mod.rs@@@ -19,6 -19,6 +19,7 @@@ pub mod iconpub mod image;pub mod input;pub mod jumplist;++pub mod keymap;pub mod media_sessions;pub mod mp4;pub mod net;diff --cc desktop/app/src/linux/window_capture.rsindex 1e78310,0000000..d99bddemode 100644,000000..100644--- a/desktop/app/src/linux/window_capture.rs+++ b/desktop/app/src/linux/window_capture.rs@@@ -1,371 -1,0 +1,426 @@@+// SPDX-License-Identifier: GPL-3.0-or-later- //! Capture a single window on Linux via in-process X11 `XGetImage`,++//! Capture a single window on Linux (via in-process X11 `XGetImage`, with `import` fallback),+//! matching the public API of `desktop/app/src/win/window_capture.rs`.+- use std::{- cell::RefCell,- ffi::{CStr, c_char, c_int, c_long, c_uint, c_ulong, c_void},- sync::OnceLock,- };++#![allow(unsafe_code)]+- use super::browser::{HWND, RECT, frame_of};-- pub struct WindowCapture {- hwnd: HWND,- rgba: Vec<u8>,- }-- // SAFETY: WindowCapture only holds a window XID and an owned byte buffer.- unsafe impl Send for WindowCapture {}-- impl WindowCapture {- pub fn new(hwnd: HWND) -> Result<WindowCapture, String> {- if hwnd.0.is_null() {- return Err("invalid window handle".to_owned());- }- Ok(WindowCapture { hwnd, rgba: Vec::new() })- }-- pub fn window(&self) -> HWND {- self.hwnd- }-- /// Capture `self.hwnd`, optionally cropped to `crop` (in screen coordinates),- /// and scale the result into `bgra` (`dst_w` x `dst_h`, tightly packed BGRA).- pub fn capture(&mut self, crop: RECT, dst_w: u32, dst_h: u32, bgra: &mut Vec<u8>) -> bool {- if dst_w == 0 || dst_h == 0 {- return false;- }- let Some(frame) = frame_of(self.hwnd) else {- return false;- };- let win_w = (frame.right - frame.left).max(0) as u32;- let win_h = (frame.bottom - frame.top).max(0) as u32;- if win_w < 32 || win_h < 32 {- return false;- }-- let xid = self.hwnd.0 as usize;- if let Some((src_w, src_h)) = capture_x11_window_bgra(xid, win_w, win_h, &mut self.rgba) {- let (cx0, cy0, cw, ch) = compute_window_crop(frame, crop, src_w, src_h);- scale_bgra(&self.rgba, src_w, src_w * 4, cx0, cy0, cw, ch, dst_w, dst_h, bgra);- return true;- }-- false- }- }++use std::process::Command;+- fn compute_window_crop(frame: RECT, crop: RECT, src_w: u32, src_h: u32) -> (u32, u32, u32, u32) {- let cw = crop.right - crop.left;- let ch = crop.bottom - crop.top;- if cw >= 64 && ch >= 64 {- let x0 = (crop.left - frame.left).clamp(0, src_w as i32) as u32;- let y0 = (crop.top - frame.top).clamp(0, src_h as i32) as u32;- let x1 = (crop.right - frame.left).clamp(x0 as i32, src_w as i32) as u32;- let y1 = (crop.bottom - frame.top).clamp(y0 as i32, src_h as i32) as u32;- if x1 - x0 >= 64 && y1 - y0 >= 64 {- return (x0, y0, x1 - x0, y1 - y0);- }- }- (0, 0, src_w, src_h)- }++use super::browser::{HWND, RECT, frame_of};++#[repr(C)]+struct XWindowAttributes {- x: c_int,- y: c_int,- width: c_int,- height: c_int,- border_width: c_int,- depth: c_int,- visual: *mut c_void,- root: c_ulong,- class: c_int,- bit_gravity: c_int,- win_gravity: c_int,- backing_store: c_int,- backing_planes: c_ulong,- backing_pixel: c_ulong,- save_under: c_int,- colormap: c_ulong,- map_installed: c_int,- map_state: c_int,- all_event_masks: c_long,- your_event_mask: c_long,- do_not_propagate_mask: c_long,- override_redirect: c_int,- screen: *mut c_void,++ x: std::ffi::c_int,++ y: std::ffi::c_int,++ width: std::ffi::c_int,++ height: std::ffi::c_int,++ border_width: std::ffi::c_int,++ depth: std::ffi::c_int,++ visual: *mut std::ffi::c_void,++ root: std::ffi::c_ulong,++ class: std::ffi::c_int,++ bit_gravity: std::ffi::c_int,++ win_gravity: std::ffi::c_int,++ backing_store: std::ffi::c_int,++ backing_planes: std::ffi::c_ulong,++ backing_pixel: std::ffi::c_ulong,++ save_under: std::ffi::c_int,++ colormap: std::ffi::c_ulong,++ map_installed: std::ffi::c_int,++ map_state: std::ffi::c_int,++ all_event_masks: std::ffi::c_long,++ your_event_mask: std::ffi::c_long,++ do_not_propagate_mask: std::ffi::c_long,++ override_redirect: std::ffi::c_int,++ screen: *mut std::ffi::c_void,+}++#[repr(C)]+struct XImageFuncs {- create_image: *mut c_void,- destroy_image: Option<unsafe extern "C" fn(*mut XImage) -> c_int>,- get_pixel: *mut c_void,- put_pixel: *mut c_void,- sub_image: *mut c_void,- add_pixel: *mut c_void,++ create_image: *mut std::ffi::c_void,++ destroy_image: Option<unsafe extern "C" fn(*mut XImage) -> std::ffi::c_int>,++ get_pixel: *mut std::ffi::c_void,++ put_pixel: *mut std::ffi::c_void,++ sub_image: *mut std::ffi::c_void,++ add_pixel: *mut std::ffi::c_void,+}++#[repr(C)]+struct XImage {- width: c_int,- height: c_int,- xoffset: c_int,- format: c_int,++ width: std::ffi::c_int,++ height: std::ffi::c_int,++ xoffset: std::ffi::c_int,++ format: std::ffi::c_int,+ data: *mut u8,- byte_order: c_int,- bitmap_unit: c_int,- bitmap_bit_order: c_int,- bitmap_pad: c_int,- depth: c_int,- bytes_per_line: c_int,- bits_per_pixel: c_int,- red_mask: c_ulong,- green_mask: c_ulong,- blue_mask: c_ulong,- obdata: *mut c_void,++ byte_order: std::ffi::c_int,++ bitmap_unit: std::ffi::c_int,++ bitmap_bit_order: std::ffi::c_int,++ bitmap_pad: std::ffi::c_int,++ depth: std::ffi::c_int,++ bytes_per_line: std::ffi::c_int,++ bits_per_pixel: std::ffi::c_int,++ red_mask: std::ffi::c_ulong,++ green_mask: std::ffi::c_ulong,++ blue_mask: std::ffi::c_ulong,++ obdata: *mut std::ffi::c_void,+ f: XImageFuncs,+}+- struct X11WinCapApi {- open_display: unsafe extern "C" fn(*const c_char) -> *mut c_void,- get_window_attributes: unsafe extern "C" fn(*mut c_void, c_ulong, *mut XWindowAttributes) -> c_int,++type XErrorHandler =++ Option<unsafe extern "C" fn(*mut std::ffi::c_void, *mut std::ffi::c_void) -> std::ffi::c_int>;++++struct X11Api {++ open_display: unsafe extern "C" fn(*const std::ffi::c_char) -> *mut std::ffi::c_void,++ get_window_attributes: unsafe extern "C" fn(++ *mut std::ffi::c_void,++ std::ffi::c_ulong,++ *mut XWindowAttributes,++ ) -> std::ffi::c_int,+ get_image: unsafe extern "C" fn(- *mut c_void,- c_ulong,- c_int,- c_int,- c_uint,- c_uint,- c_ulong,- c_int,++ *mut std::ffi::c_void,++ std::ffi::c_ulong,++ std::ffi::c_int,++ std::ffi::c_int,++ std::ffi::c_uint,++ std::ffi::c_uint,++ std::ffi::c_ulong,++ std::ffi::c_int,+ ) -> *mut XImage,- close_display: unsafe extern "C" fn(*mut c_void) -> c_int,- free: unsafe extern "C" fn(*mut c_void) -> c_int,++ set_error_handler: unsafe extern "C" fn(XErrorHandler) -> XErrorHandler,++ close_display: unsafe extern "C" fn(*mut std::ffi::c_void) -> std::ffi::c_int,++ free: unsafe extern "C" fn(*mut std::ffi::c_void) -> std::ffi::c_int,+}+- unsafe fn dl_sym<T>(handle: *mut c_void, name: &CStr) -> Option<T> {- let raw = unsafe { libc::dlsym(handle, name.as_ptr()) };- if raw.is_null() {- return None;- }- Some(unsafe { std::mem::transmute_copy(&raw) })++unsafe extern "C" fn ignore_x11_error(++ _dpy: *mut std::ffi::c_void,++ _err: *mut std::ffi::c_void,++) -> std::ffi::c_int {++ 0+}+- fn x11_win_cap_api() -> Option<&'static X11WinCapApi> {- static API: OnceLock<Option<X11WinCapApi>> = OnceLock::new();++unsafe fn dl_sym<T: Copy>(lib: *mut std::ffi::c_void, name: &std::ffi::CStr) -> Option<T> {++ let raw = unsafe { libc::dlsym(lib, name.as_ptr()) };++ if raw.is_null() { None } else { Some(unsafe { std::mem::transmute_copy(&raw) }) }++}++++fn x11_api() -> Option<&'static X11Api> {++ static API: std::sync::OnceLock<Option<X11Api>> = std::sync::OnceLock::new();+ API.get_or_init(|| unsafe {++ let candidates = [c"libX11.so.6", c"libX11.so"];+ let mut lib = std::ptr::null_mut();- for name in [c"libX11.so.6", c"libX11.so"] {++ for name in candidates {+ lib = libc::dlopen(name.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL);+ if !lib.is_null() {+ break;+ }+ }+ if lib.is_null() {+ return None;+ }- Some(X11WinCapApi {++ Some(X11Api {+ open_display: dl_sym(lib, c"XOpenDisplay")?,+ get_window_attributes: dl_sym(lib, c"XGetWindowAttributes")?,+ get_image: dl_sym(lib, c"XGetImage")?,++ set_error_handler: dl_sym(lib, c"XSetErrorHandler")?,+ close_display: dl_sym(lib, c"XCloseDisplay")?,+ free: dl_sym(lib, c"XFree")?,+ })+ })+ .as_ref()+}+- struct ThreadDisplay(*mut c_void);++struct ThreadX11Display(*mut std::ffi::c_void);+- impl Drop for ThreadDisplay {++impl Drop for ThreadX11Display {+ fn drop(&mut self) {+ if !self.0.is_null()- && let Some(api) = x11_win_cap_api()++ && let Some(api) = x11_api()+ {+ unsafe {+ let _ = (api.close_display)(self.0);+ }+ }+ }+}+- fn capture_x11_window_bgra(xid: usize, _w: u32, _h: u32, out: &mut Vec<u8>) -> Option<(u32, u32)> {- if std::env::var_os("DISPLAY").is_none() || xid == 0 {- return None;- }++fn with_x11_display<R>(f: impl FnOnce(&X11Api, *mut std::ffi::c_void) -> Option<R>) -> Option<R> {+ std::thread_local! {- static DISPLAY: RefCell<Option<ThreadDisplay>> = const { RefCell::new(None) };++ static DISPLAY: std::cell::RefCell<Option<ThreadX11Display>> = const { std::cell::RefCell::new(None) };+ }- let api = x11_win_cap_api()?;- DISPLAY.with(|cell| unsafe {++ let api = x11_api()?;++ DISPLAY.with(|cell| {+ let mut borrow = cell.borrow_mut();+ if borrow.is_none() {- let dpy = (api.open_display)(std::ptr::null());++ let dpy = unsafe { (api.open_display)(std::ptr::null()) };+ if !dpy.is_null() {- *borrow = Some(ThreadDisplay(dpy));++ *borrow = Some(ThreadX11Display(dpy));+ }+ }+ let dpy = borrow.as_ref()?.0;++ f(api, dpy)++ })++}++++fn has_executable(name: &str) -> bool {++ let Some(path_var) = std::env::var_os("PATH") else {++ return false;++ };++ std::env::split_paths(&path_var).any(|dir| dir.join(name).is_file())++}++++/// Whether single-window capture is supported in the current Linux session.++pub fn is_available() -> bool {++ std::env::var_os("DISPLAY").is_some() && (x11_api().is_some() || has_executable("import"))++}++++pub struct WindowCapture {++ hwnd: HWND,++ rgba: Vec<u8>,++}++++// SAFETY: WindowCapture only holds a window XID and an owned byte buffer.++unsafe impl Send for WindowCapture {}++++impl WindowCapture {++ pub fn new(hwnd: HWND) -> Result<WindowCapture, String> {++ if hwnd.0.is_null() {++ return Err("invalid window handle".to_owned());++ }++ if !is_available() {++ return Err("X11 window capture unavailable".to_owned());++ }++ Ok(WindowCapture { hwnd, rgba: Vec::new() })++ }++++ pub fn window(&self) -> HWND {++ self.hwnd++ }++++ /// Capture `self.hwnd`, optionally cropped to `crop` (in window-relative coordinates),++ /// and scale the result into `bgra` (`dst_w` x `dst_h`, tightly packed BGRA).++ pub fn capture(&mut self, crop: RECT, dst_w: u32, dst_h: u32, bgra: &mut Vec<u8>) -> bool {++ if dst_w == 0 || dst_h == 0 {++ return false;++ }++ let xid = self.hwnd.0 as usize;++ if let Some((src_w, src_h)) = capture_x11_window_bgra(self.hwnd, xid, &mut self.rgba) {++ let (cx0, cy0, cw, ch) = compute_window_crop(crop, src_w, src_h);++ scale_bgra(&self.rgba, src_w, src_w * 4, cx0, cy0, cw, ch, dst_w, dst_h, bgra);++ return true;++ }++++ false++ }++}++++fn compute_window_crop(crop: RECT, src_w: u32, src_h: u32) -> (u32, u32, u32, u32) {++ let cw = crop.right - crop.left;++ let ch = crop.bottom - crop.top;++ if cw >= 64 && ch >= 64 {++ let x0 = crop.left.clamp(0, src_w as i32) as u32;++ let y0 = crop.top.clamp(0, src_h as i32) as u32;++ let x1 = crop.right.clamp(x0 as i32, src_w as i32) as u32;++ let y1 = crop.bottom.clamp(y0 as i32, src_h as i32) as u32;++ if x1 - x0 >= 64 && y1 - y0 >= 64 {++ return (x0, y0, x1 - x0, y1 - y0);++ }++ }++ (0, 0, src_w, src_h)++}++++fn capture_x11_window_in_process(xid: usize, out: &mut Vec<u8>) -> Option<(u32, u32)> {++ with_x11_display(|api, dpy| unsafe {++ let _prev_handler = (api.set_error_handler)(Some(ignore_x11_error));+ let mut attrs: XWindowAttributes = std::mem::zeroed();- // map_state == 2 is IsViewable in X11.- if (api.get_window_attributes)(dpy, xid as c_ulong, &mut attrs) == 0- || attrs.map_state != 2++ if (api.get_window_attributes)(dpy, xid as std::ffi::c_ulong, &mut attrs) == 0+ || attrs.width < 32+ || attrs.height < 32+ {+ return None;+ }+ let src_w = attrs.width as u32;+ let src_h = attrs.height as u32;+ let img = (api.get_image)(+ dpy,- xid as c_ulong,++ xid as std::ffi::c_ulong,+ 0,+ 0,+ src_w,+ src_h,- !0 as c_ulong, // AllPlanes- 2, // ZPixmap++ !0 as std::ffi::c_ulong, // AllPlanes++ 2, // ZPixmap+ );+ if img.is_null() {+ return None;+ }+ if (*img).data.is_null() {+ if let Some(destroy) = (*img).f.destroy_image {+ let _ = destroy(img);+ } else {+ let _ = (api.free)(img.cast());+ }+ return None;+ }- let pitch = (*img).bytes_per_line.max(0) as usize;++++ let bytes_per_line = (*img).bytes_per_line.max(0) as usize;+ let bpp = ((*img).bits_per_pixel.max(24) as usize) / 8;+ let needed = (src_w as usize).checked_mul(src_h as usize)?.checked_mul(4)?;+ out.resize(needed, 0);- let raw_len = pitch.saturating_mul(src_h as usize);- let src_bytes = std::slice::from_raw_parts((*img).data, raw_len);+++ for y in 0..src_h as usize {- let s_row = y * pitch;- let d_row = y * (src_w as usize) * 4;++ let src_row = (*img).data.add(y * bytes_per_line);++ let dst_row_offset = y * (src_w as usize) * 4;+ for x in 0..src_w as usize {- let s_idx = s_row + x * bpp;- let d_idx = d_row + x * 4;- if s_idx + 3 <= src_bytes.len() && d_idx + 4 <= out.len() {- out[d_idx] = src_bytes[s_idx];- out[d_idx + 1] = src_bytes[s_idx + 1];- out[d_idx + 2] = src_bytes[s_idx + 2];- out[d_idx + 3] = 0xFF;- }++ let px = src_row.add(x * bpp);++ let dst_idx = dst_row_offset + x * 4;++ out[dst_idx] = *px;++ out[dst_idx + 1] = *px.add(1);++ out[dst_idx + 2] = *px.add(2);++ out[dst_idx + 3] = 0xFF;+ }+ }+++ if let Some(destroy) = (*img).f.destroy_image {+ let _ = destroy(img);+ } else {++ libc::free((*img).data.cast());+ let _ = (api.free)(img.cast());+ }+++ Some((src_w, src_h))+ })+}+++fn capture_x11_window_bgra(hwnd: HWND, xid: usize, out: &mut Vec<u8>) -> Option<(u32, u32)> {++ if std::env::var_os("DISPLAY").is_none() || xid == 0 {++ return None;++ }++ if let Some(dims) = capture_x11_window_in_process(xid, out) {++ return Some(dims);++ }++ let frame = frame_of(hwnd)?;++ let w = (frame.right - frame.left).max(0) as u32;++ let h = (frame.bottom - frame.top).max(0) as u32;++ if w < 32 || h < 32 {++ return None;++ }++ let expected = (w as usize).checked_mul(h as usize)?.checked_mul(4)?;++ let output = Command::new("import")++ .args(["-silent", "-window", &xid.to_string(), "-depth", "8", "bgra:-"])++ .output()++ .ok()?;++ if !output.status.success() || output.stdout.len() < expected {++ return None;++ }++ out.clear();++ out.extend_from_slice(&output.stdout[..expected]);++ Some((w, h))++}+++/// Area-averaging box filter from a cropped BGRA region `(crop_x, crop_y, crop_w, crop_h)`+/// of `src` into a tightly packed `dst_w` x `dst_h` BGRA buffer.+#[allow(clippy::too_many_arguments)]+pub(crate) fn scale_bgra(+ src: &[u8],+ src_w: u32,+ src_pitch: u32,+ crop_x: u32,+ crop_y: u32,+ crop_w: u32,+ crop_h: u32,+ dst_w: u32,+ dst_h: u32,+ dst: &mut Vec<u8>,+) {+ let dst_len = (dst_w as usize) * (dst_h as usize) * 4;+ dst.resize(dst_len, 0);+ if crop_w == 0 || crop_h == 0 || dst_w == 0 || dst_h == 0 || src_w == 0 {+ return;+ }+ let pitch = src_pitch as usize;++ if crop_w == dst_w && crop_h == dst_h {+ let row_bytes = (dst_w as usize) * 4;+ let x_off = (crop_x as usize) * 4;+ for y in 0..dst_h as usize {+ let s_off = (crop_y as usize + y) * pitch + x_off;+ let d_off = y * row_bytes;+ if s_off + row_bytes <= src.len() {+ dst[d_off..d_off + row_bytes].copy_from_slice(&src[s_off..s_off + row_bytes]);+ }+ }+ return;+ }++ for dy in 0..dst_h {+ let sy0 = crop_y + ((dy as u64 * crop_h as u64) / dst_h as u64) as u32;+ let sy1 = (crop_y + (((dy + 1) as u64 * crop_h as u64) / dst_h as u64) as u32).max(sy0 + 1);+ for dx in 0..dst_w {+ let sx0 = crop_x + ((dx as u64 * crop_w as u64) / dst_w as u64) as u32;+ let sx1 = (crop_x + (((dx + 1) as u64 * crop_w as u64) / dst_w as u64) as u32).max(sx0 + 1);+ let mut b_sum = 0u32;+ let mut g_sum = 0u32;+ let mut r_sum = 0u32;+ let mut count = 0u32;+ for sy in sy0..sy1 {+ let row = (sy as usize) * pitch;+ for sx in sx0..sx1 {+ let idx = row + (sx as usize) * 4;+ if idx + 4 <= src.len() {+ b_sum += src[idx] as u32;+ g_sum += src[idx + 1] as u32;+ r_sum += src[idx + 2] as u32;+ count += 1;+ }+ }+ }+ let out_idx = ((dy * dst_w + dx) as usize) * 4;+ if let (Some(b), Some(g), Some(r)) =+ (b_sum.checked_div(count), g_sum.checked_div(count), r_sum.checked_div(count))+ {+ dst[out_idx] = b as u8;+ dst[out_idx + 1] = g as u8;+ dst[out_idx + 2] = r as u8;+ dst[out_idx + 3] = 0xFF;+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn same_size_is_a_copy() {+ let src = vec![+ 10, 20, 30, 255, 40, 50, 60, 255, //+ 70, 80, 90, 255, 100, 110, 120, 255,+ ];+ let mut dst = Vec::new();+ scale_bgra(&src, 2, 8, 0, 0, 2, 2, 2, 2, &mut dst);+ assert_eq!(dst, src);+ }++ #[test]+ fn halving_averages_and_a_flat_picture_stays_flat() {+ let mut src = Vec::with_capacity(4 * 4 * 4);+ for _ in 0..16 {+ src.extend_from_slice(&[50, 100, 150, 255]);+ }+ let mut dst = Vec::new();+ scale_bgra(&src, 4, 16, 0, 0, 4, 4, 2, 2, &mut dst);+ assert_eq!(dst.len(), 2 * 2 * 4);+ for px in dst.as_chunks::<4>().0 {+ assert_eq!(px, &[50, 100, 150, 255]);+ }+ }++++ #[test]++ fn compute_window_crop_uses_window_relative_coordinates() {++ let crop = RECT { left: 100, top: 80, right: 740, bottom: 440 };++ assert_eq!(compute_window_crop(crop, 1280, 720), (100, 80, 640, 360));++ let tiny = RECT { left: 10, top: 10, right: 30, bottom: 30 };++ assert_eq!(compute_window_crop(tiny, 1280, 720), (0, 0, 1280, 720));++ }+}