Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

feat(linux): input injection, deck actions, and window capture (Part 3)

Jochen Kirstätter426360fe5132
diff --git a/desktop/app/cpp/native_window.cpp b/desktop/app/cpp/native_window.cpp
index 1731550..6fa3313 100644
--- a/desktop/app/cpp/native_window.cpp
+++ b/desktop/app/cpp/native_window.cpp
@@ -15,9 +15,16 @@
#include <dwmapi.h>
#include <dxgi1_3.h>
#include <windowsx.h>
+#elif defined(__linux__)
+#include <QtGui/QCursor>
+#include <QtGui/QMouseEvent>
+#include <cstring>
+#include <dlfcn.h>
+#endif
namespace {
+#ifdef _WIN32
// Values from the Windows 11 SDK, defined here so older SDK headers work.
constexpr DWORD kUseImmersiveDarkMode = 20; // DWMWA_USE_IMMERSIVE_DARK_MODE
constexpr DWORD kCaptionColor = 35; // DWMWA_CAPTION_COLOR
@@ -49,26 +56,251 @@ void trimD3DResources(QQuickWindow *window)
dxgi3->Release();
}
}
-
-} // namespace
#else
-namespace {
-void trimD3DResources(QQuickWindow * /*window*/) {}
-} // namespace
+void trimD3DResources(QQuickWindow *)
+{
+}
#endif
+#ifdef __linux__
+void activateX11Window(WId winId)
+{
+ if (!winId || qEnvironmentVariableIsEmpty("DISPLAY"))
+ return;
+
+ void *lib = dlopen("libX11.so.6", RTLD_LAZY | RTLD_LOCAL);
+ if (!lib)
+ return;
+
+ using XOpenDisplayFn = void *(*)(const char *);
+ using XCloseDisplayFn = int (*)(void *);
+ using XDefaultRootWindowFn = unsigned long (*)(void *);
+ using XInternAtomFn = unsigned long (*)(void *, const char *, int);
+ using XSendEventFn = int (*)(void *, unsigned long, int, long, void *);
+ using XMapRaisedFn = int (*)(void *, unsigned long);
+ using XSetInputFocusFn = int (*)(void *, unsigned long, int, unsigned long);
+ using XFlushFn = int (*)(void *);
+
+ auto xOpenDisplay = reinterpret_cast<XOpenDisplayFn>(dlsym(lib, "XOpenDisplay"));
+ auto xCloseDisplay = reinterpret_cast<XCloseDisplayFn>(dlsym(lib, "XCloseDisplay"));
+ auto xDefaultRootWindow = reinterpret_cast<XDefaultRootWindowFn>(dlsym(lib, "XDefaultRootWindow"));
+ auto xInternAtom = reinterpret_cast<XInternAtomFn>(dlsym(lib, "XInternAtom"));
+ auto xSendEvent = reinterpret_cast<XSendEventFn>(dlsym(lib, "XSendEvent"));
+ auto xMapRaised = reinterpret_cast<XMapRaisedFn>(dlsym(lib, "XMapRaised"));
+ auto xSetInputFocus = reinterpret_cast<XSetInputFocusFn>(dlsym(lib, "XSetInputFocus"));
+ auto xFlush = reinterpret_cast<XFlushFn>(dlsym(lib, "XFlush"));
+
+ if (xOpenDisplay && xCloseDisplay && xDefaultRootWindow && xInternAtom && xSendEvent && xFlush) {
+ if (void *dpy = xOpenDisplay(nullptr)) {
+ const unsigned long root = xDefaultRootWindow(dpy);
+ const unsigned long window = static_cast<unsigned long>(winId);
+ const unsigned long netActiveWindow = xInternAtom(dpy, "_NET_ACTIVE_WINDOW", 0);
+
+ if (xMapRaised)
+ xMapRaised(dpy, window);
+
+ struct XClientMessageEventCompat {
+ int type;
+ unsigned long serial;
+ int send_event;
+ void *display;
+ unsigned long window;
+ unsigned long message_type;
+ int format;
+ long l[5];
+ long pad[12];
+ } ev {};
+ ev.type = 33; // ClientMessage
+ ev.send_event = 1;
+ ev.display = dpy;
+ ev.window = window;
+ ev.message_type = netActiveWindow;
+ ev.format = 32;
+ ev.l[0] = 2; // Source indication: 2 = pager / direct user action (bypasses WM focus-stealing prevention)
+ ev.l[1] = 0; // CurrentTime
+ ev.l[2] = 0;
+
+ constexpr long kSubstructureRedirectMask = (1L << 20);
+ constexpr long kSubstructureNotifyMask = (1L << 19);
+ xSendEvent(dpy, root, 0, kSubstructureRedirectMask | kSubstructureNotifyMask, &ev);
+
+ if (xSetInputFocus)
+ xSetInputFocus(dpy, window, 1 /* RevertToPointerRoot */, 0 /* CurrentTime */);
+
+ xFlush(dpy);
+ xCloseDisplay(dpy);
+ }
+ }
+ dlclose(lib);
+}
+
+class LinuxWindowEventFilter : public QObject
+{
+public:
+ explicit LinuxWindowEventFilter(NativeWindow *window)
+ : QObject(window)
+ , window_(window)
+ {
+ }
+
+protected:
+ bool eventFilter(QObject *watched, QEvent *event) override
+ {
+ if (watched != window_)
+ return QObject::eventFilter(watched, event);
+
+ switch (event->type()) {
+ case QEvent::MouseMove: {
+ auto *me = static_cast<QMouseEvent *>(event);
+ if (me->buttons() == Qt::NoButton) {
+ const Qt::Edges edges = hitResizeEdges(me->position());
+ updateCursorForEdges(edges);
+ }
+ break;
+ }
+ case QEvent::MouseButtonPress: {
+ auto *me = static_cast<QMouseEvent *>(event);
+ if (me->button() == Qt::LeftButton) {
+ const QPointF pos = me->position();
+ const Qt::Edges edges = hitResizeEdges(pos);
+ if (edges != Qt::Edges()) {
+ window_->startSystemResize(edges);
+ return true;
+ }
+ const qreal titleBarHeight = window_->captionHeight();
+ if (pos.y() < titleBarHeight && !hitInteractiveControl(window_->contentItem(), pos)) {
+ window_->startSystemMove();
+ return true;
+ }
+ }
+ break;
+ }
+ case QEvent::MouseButtonDblClick: {
+ auto *me = static_cast<QMouseEvent *>(event);
+ if (me->button() == Qt::LeftButton) {
+ const QPointF pos = me->position();
+ const Qt::Edges edges = hitResizeEdges(pos);
+ const qreal titleBarHeight = window_->captionHeight();
+ if (edges == Qt::Edges() && pos.y() < titleBarHeight
+ && !hitInteractiveControl(window_->contentItem(), pos)) {
+ window_->toggleMaximized();
+ return true;
+ }
+ }
+ break;
+ }
+ case QEvent::Leave:
+ if (borderCursorActive_) {
+ window_->unsetCursor();
+ borderCursorActive_ = false;
+ }
+ break;
+ default:
+ break;
+ }
+ return QObject::eventFilter(watched, event);
+ }
+
+private:
+ Qt::Edges hitResizeEdges(const QPointF &pos) const
+ {
+ if (!window_ || window_->visibility() == QWindow::Maximized
+ || window_->minimumSize() == window_->maximumSize()) {
+ return {};
+ }
+ if (pos.y() < window_->captionHeight() && hitInteractiveControl(window_->contentItem(), pos)) {
+ return {};
+ }
+ const qreal w = window_->width();
+ const qreal h = window_->height();
+ const qreal b = resizeBorderWidth_;
+ Qt::Edges edges;
+ if (pos.x() < b)
+ edges |= Qt::LeftEdge;
+ else if (pos.x() >= w - b)
+ edges |= Qt::RightEdge;
+ if (pos.y() < b)
+ edges |= Qt::TopEdge;
+ else if (pos.y() >= h - b)
+ edges |= Qt::BottomEdge;
+ return edges;
+ }
+
+ void updateCursorForEdges(Qt::Edges edges)
+ {
+ if (edges == Qt::Edges()) {
+ if (borderCursorActive_) {
+ window_->unsetCursor();
+ borderCursorActive_ = false;
+ }
+ return;
+ }
+ Qt::CursorShape shape = Qt::ArrowCursor;
+ if ((edges == (Qt::TopEdge | Qt::LeftEdge)) || (edges == (Qt::BottomEdge | Qt::RightEdge)))
+ shape = Qt::SizeFDiagCursor;
+ else if ((edges == (Qt::TopEdge | Qt::RightEdge)) || (edges == (Qt::BottomEdge | Qt::LeftEdge)))
+ shape = Qt::SizeBDiagCursor;
+ else if (edges & (Qt::LeftEdge | Qt::RightEdge))
+ shape = Qt::SizeHorCursor;
+ else if (edges & (Qt::TopEdge | Qt::BottomEdge))
+ shape = Qt::SizeVerCursor;
+ window_->setCursor(QCursor(shape));
+ borderCursorActive_ = true;
+ }
+
+ bool hitInteractiveControl(QQuickItem *item, const QPointF &scenePos) const
+ {
+ if (!item || !item->isVisible() || !item->isEnabled() || item->opacity() <= 0.0)
+ return false;
+ const QPointF localPos = item->mapFromScene(scenePos);
+ if (!item->contains(localPos))
+ return false;
+ if (item == window_->maximizeButton() || item->property("_nl_caption_hole").toBool())
+ return true;
+ const auto children = item->childItems();
+ for (int i = children.size() - 1; i >= 0; --i) {
+ if (hitInteractiveControl(children[i], scenePos))
+ return true;
+ }
+ if (item != window_->contentItem()
+ && item->acceptedMouseButtons() != Qt::NoButton) {
+ return true;
+ }
+ return false;
+ }
+
+ NativeWindow *window_ = nullptr;
+ int resizeBorderWidth_ = 6;
+ bool borderCursorActive_ = false;
+};
+#endif
+
+} // namespace
+
NativeWindow::NativeWindow(QWindow *parent)
: QQuickWindow(parent)
{
+ // Qt removes the system title bar and lets content fill the window.
#ifdef _WIN32
- // Qt removes the system title bar and lets content fill the window on Windows.
setFlags(flags() | Qt::ExpandedClientAreaHint);
-#endif
setColor(Qt::transparent);
+#elif defined(__linux__)
+ setFlags(flags() | Qt::FramelessWindowHint);
+ setColor(QColor(0x14, 0x13, 0x11));
+#else
+ setColor(Qt::transparent);
+#endif
// Drop the scene graph and D3D/RHI resources when the window is hidden or
// closed to the tray instead of keeping GPU buffers in private commit.
setPersistentSceneGraph(false);
setPersistentGraphics(false);
+ connect(this, &QWindow::visibilityChanged, this, [this](QWindow::Visibility) {
+ emit windowVisibilityChanged();
+ });
+#ifdef __linux__
+ setProperty("_nl_linux_filter", true);
+ installEventFilter(new LinuxWindowEventFilter(this));
+#endif
}
void NativeWindow::setBackdrop(bool on)
@@ -125,12 +357,16 @@ void NativeWindow::setMaximizeState(bool hovered, bool pressed)
void NativeWindow::addCaptionHole(QQuickItem *item)
{
+ if (item)
+ item->setProperty("_nl_caption_hole", true);
if (item && std::none_of(m_holes.begin(), m_holes.end(), [item](const auto &h) { return h == item; }))
m_holes.emplace_back(item);
}
void NativeWindow::removeCaptionHole(QQuickItem *item)
{
+ if (item)
+ item->setProperty("_nl_caption_hole", false);
m_holes.erase(std::remove_if(m_holes.begin(), m_holes.end(),
[item](const auto &h) { return h.isNull() || h == item; }),
m_holes.end());
@@ -169,14 +405,17 @@ void NativeWindow::bringToFront()
SetForegroundWindow(hwnd);
if (attached)
AttachThreadInput(thisThread, foregroundThread, FALSE);
+#elif defined(__linux__)
+ if (handle())
+ activateX11Window(winId());
#endif
}
void NativeWindow::flash()
{
-#ifdef _WIN32
if (!handle())
return;
+#ifdef _WIN32
FLASHWINFO info { sizeof(FLASHWINFO), hwndOf(this), FLASHW_TRAY | FLASHW_TIMERNOFG, 0, 0 };
FlashWindowEx(&info);
#else
@@ -237,6 +476,14 @@ void NativeWindow::applyFrame()
DwmSetWindowAttribute(hwnd, kSystemBackdropType, &backdrop, sizeof(backdrop));
const COLORREF none = kColorNone;
DwmSetWindowAttribute(hwnd, kCaptionColor, &none, sizeof(none));
+#elif defined(__linux__)
+ setColor(m_darkFrame ? QColor(0x14, 0x13, 0x11) : QColor(0xF8, 0xF6, 0xF2));
+ if (!property("_nl_linux_filter").toBool()) {
+ setProperty("_nl_linux_filter", true);
+ installEventFilter(new LinuxWindowEventFilter(this));
+ }
+#else
+ setColor(m_darkFrame ? QColor(0x14, 0x13, 0x11) : QColor(0xF8, 0xF6, 0xF2));
#endif
}
@@ -348,10 +595,6 @@ bool NativeWindow::nativeEvent(const QByteArray &eventType, void *message, qintp
default:
break;
}
-#else
- Q_UNUSED(eventType);
- Q_UNUSED(message);
- Q_UNUSED(result);
#endif
return QQuickWindow::nativeEvent(eventType, message, result);
}
diff --git a/desktop/app/cpp/native_window.h b/desktop/app/cpp/native_window.h
index ad06b6b..72f6a8a 100644
--- a/desktop/app/cpp/native_window.h
+++ b/desktop/app/cpp/native_window.h
@@ -72,6 +72,7 @@ signals:
void captionHeightChanged();
void maximizeButtonChanged();
void maximizeStateChanged();
+ void windowVisibilityChanged();
void closeRequested();
protected:
diff --git a/desktop/app/i18n/nectarlink_de.ts b/desktop/app/i18n/nectarlink_de.ts
index 5c6ae83..962b83c 100644
--- a/desktop/app/i18n/nectarlink_de.ts
+++ b/desktop/app/i18n/nectarlink_de.ts
@@ -1404,6 +1404,11 @@
</message>
<message>
<location filename="rust_strings.h" line="173" />
+ <source>Enter an application path (/usr/bin/..., .desktop, or .AppImage).</source>
+ <translation>Gib einen Anwendungspfad ein (/usr/bin/…, .desktop oder .AppImage).</translation>
+ </message>
+ <message>
+ <location filename="rust_strings.h" line="174" />
<source>Enter an http:// or https:// web address.</source>
<translation>Gib eine Webadresse mit http:// oder https:// ein.</translation>
</message>
diff --git a/desktop/app/i18n/nectarlink_zh_CN.ts b/desktop/app/i18n/nectarlink_zh_CN.ts
index 5b130ad..f33756c 100644
--- a/desktop/app/i18n/nectarlink_zh_CN.ts
+++ b/desktop/app/i18n/nectarlink_zh_CN.ts
@@ -1404,6 +1404,11 @@
</message>
<message>
<location filename="rust_strings.h" line="173"/>
+ <source>Enter an application path (/usr/bin/..., .desktop, or .AppImage).</source>
+ <translation>请输入应用路径(/usr/bin/...、.desktop 或 .AppImage)。</translation>
+ </message>
+ <message>
+ <location filename="rust_strings.h" line="174"/>
<source>Enter an http:// or https:// web address.</source>
<translation>请输入以 http:// 或 https:// 开头的网址。</translation>
</message>
diff --git a/desktop/app/i18n/rust_strings.h b/desktop/app/i18n/rust_strings.h
index 29ee72c..482f012 100644
--- a/desktop/app/i18n/rust_strings.h
+++ b/desktop/app/i18n/rust_strings.h
@@ -170,6 +170,7 @@ static const char *const nectarlink_rust_strings[] = {
QT_TRANSLATE_NOOP("Deck", "Choose a key for the shortcut."), // desktop/app/src/deck.rs
QT_TRANSLATE_NOOP("Deck", "Choose an application (.exe or .lnk) on this PC."), // desktop/app/src/deck.rs
QT_TRANSLATE_NOOP("Deck", "Enter a command to run on this PC."), // desktop/app/src/deck.rs
+ QT_TRANSLATE_NOOP("Deck", "Enter an application path (/usr/bin/..., .desktop, or .AppImage)."), // desktop/app/src/deck.rs
QT_TRANSLATE_NOOP("Deck", "Enter an http:// or https:// web address."), // desktop/app/src/deck.rs
QT_TRANSLATE_NOOP("Deck", "Enter the text snippet to type."), // desktop/app/src/deck.rs
QT_TRANSLATE_NOOP("Deck", "Invalid action configuration."), // desktop/app/src/deck.rs
diff --git a/desktop/app/qml/components/CaptionButtons.qml b/desktop/app/qml/components/CaptionButtons.qml
index 25f677b..3f6c6fb 100644
--- a/desktop/app/qml/components/CaptionButtons.qml
+++ b/desktop/app/qml/components/CaptionButtons.qml
@@ -12,7 +12,7 @@ Row {
required property NativeWindow window
readonly property bool maximized: window.visibility === Window.Maximized
- visible: Qt.platform.os === "windows"
+ visible: Qt.platform.os !== "osx"
width: visible ? implicitWidth : 0
// As tall as the top bar, like Windows 11's tall title bars, so the glyphs
diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rs
index a150d27..deb88c7 100644
--- a/desktop/app/src/core_host.rs
+++ b/desktop/app/src/core_host.rs
@@ -101,7 +101,7 @@ pub fn start(data_dir: PathBuf, platform: Arc<dyn Platform>) -> std::io::Result<
/// and input injection (`mirror.input`, `input.inject`) only when enabled for at
/// least one paired device (or actively sharing).
pub fn compute_capabilities(
- #[cfg_attr(not(windows), allow(unused_variables))] node: Option<&Node>,
+ #[cfg_attr(not(any(windows, target_os = "linux")), allow(unused_variables))] node: Option<&Node>,
) -> Vec<String> {
let mut caps = vec![
"pc.power".into(),
@@ -113,7 +113,10 @@ pub fn compute_capabilities(
nectarlink_core::TOGGLES_SHOW.into(),
];
#[cfg(any(windows, target_os = "linux"))]
- caps.push(nectarlink_core::PC_WAKE.into());
+ {
+ caps.push(nectarlink_core::PC_WAKE.into());
+ caps.push(nectarlink_core::DECK_ACTIONS.into());
+ }
#[cfg(windows)]
{
caps.push("media.control".into());
@@ -122,7 +125,6 @@ pub fn compute_capabilities(
caps.push(nectarlink_core::STORAGE_WRITE.into());
caps.push(nectarlink_core::MIRROR_VIEW.into());
caps.push(nectarlink_core::MIRROR_LISTEN.into());
- caps.push(nectarlink_core::DECK_ACTIONS.into());
caps.push(nectarlink_core::PC_AUDIO.into());
caps.push(nectarlink_core::RECORDER.into());
caps.push(nectarlink_core::WEBCAM_VIRTUAL.into());
@@ -131,15 +133,16 @@ pub fn compute_capabilities(
}
#[cfg(windows)]
let mut pc_mirror_enabled = crate::pc_mirror::is_active();
- #[cfg(windows)]
+ #[cfg(any(windows, target_os = "linux"))]
let mut remote_input_enabled = false;
- #[cfg(windows)]
+ #[cfg(any(windows, target_os = "linux"))]
if let Some(node) = node
&& let Ok(devices) = node.paired_devices()
{
for d in devices {
if let Ok(toggles) = node.device_toggles(d.id) {
for (name, on) in toggles {
+ #[cfg(windows)]
if on && name == nectarlink_core::PC_MIRROR_TOGGLE {
pc_mirror_enabled = true;
}
@@ -155,7 +158,11 @@ pub fn compute_capabilities(
caps.push(nectarlink_core::MIRROR_CAPTURE.into());
}
#[cfg(windows)]
- if remote_input_enabled {
+ let input_available = true;
+ #[cfg(target_os = "linux")]
+ let input_available = crate::win::input::is_available();
+ #[cfg(any(windows, target_os = "linux"))]
+ if remote_input_enabled && input_available {
caps.push(nectarlink_core::MIRROR_INPUT.into());
caps.push(nectarlink_core::INPUT_INJECT.into());
}
diff --git a/desktop/app/src/deck.rs b/desktop/app/src/deck.rs
index a969caf..42ebaa9 100644
--- a/desktop/app/src/deck.rs
+++ b/desktop/app/src/deck.rs
@@ -321,7 +321,14 @@ fn execute_action(action: &DeckAction) -> Result<(), String> {
Ok(())
}
DeckAction::Screenshot => {
- win::input::press_key("s", &[KeyMod::Win, KeyMod::Shift]);
+ #[cfg(target_os = "linux")]
+ {
+ let _ = win::shell::take_screenshot();
+ }
+ #[cfg(not(target_os = "linux"))]
+ {
+ win::input::press_key("s", &[KeyMod::Win, KeyMod::Shift]);
+ }
Ok(())
}
DeckAction::Shortcut { key, mods } => {
@@ -512,7 +519,13 @@ pub fn build_action(
};
if !action.is_valid() {
return Err(match kind {
- deck_kinds::LAUNCH_APP => tr!("Deck", "Application path must end with .exe or .lnk."),
+ deck_kinds::LAUNCH_APP => {
+ if cfg!(target_os = "linux") {
+ tr!("Deck", "Enter an application path (/usr/bin/..., .desktop, or .AppImage).")
+ } else {
+ tr!("Deck", "Application path must end with .exe or .lnk.")
+ }
+ }
deck_kinds::OPEN_URL => tr!("Deck", "Web address must start with http:// or https://."),
deck_kinds::SHORTCUT => {
tr!("Deck", "Use a single key (a-z, 0-9, f1-f12, enter, tab, space, escape, arrows, etc.).")
@@ -617,6 +630,12 @@ mod tests {
assert_eq!(app, DeckAction::LaunchApp { path: "C:\\Windows\\System32\\calc.exe".into() });
assert!(build_action("launch_app", "C:\\script.bat", false, false, false, false).is_err());
+ let linux_bin = build_action("launch_app", "/usr/bin/firefox", false, false, false, false).unwrap();
+ assert_eq!(linux_bin, DeckAction::LaunchApp { path: "/usr/bin/firefox".into() });
+ let linux_desktop =
+ build_action("launch_app", "org.mozilla.firefox.desktop", false, false, false, false).unwrap();
+ assert_eq!(linux_desktop, DeckAction::LaunchApp { path: "org.mozilla.firefox.desktop".into() });
+
let cmd = build_action("run_command", " echo hello ", false, false, false, false).unwrap();
assert_eq!(cmd, DeckAction::RunCommand { command: "echo hello".into() });
}
diff --git a/desktop/app/src/linux/input.rs b/desktop/app/src/linux/input.rs
index 9396fb0..25fd8e4 100644
--- a/desktop/app/src/linux/input.rs
+++ b/desktop/app/src/linux/input.rs
@@ -1,20 +1,888 @@
// 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`.
-use nectarlink_core::{ButtonAction, KeyMod, MouseButton, SlideAction, TouchAction};
+use std::{
+ ffi::{CStr, CString, c_char, c_int, c_uint, c_ulong, c_void},
+ process::{Command, Stdio},
+ sync::{Mutex, OnceLock},
+};
+use nectarlink_core::{ButtonAction, KeyMod, MouseButton, PowerAction, SlideAction, TouchAction};
+
+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,
+ 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")?,
+ 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
+ }
+}
+
+/// 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")) {
+ return true;
+ }
+ if has_x11_display() && (x11_test_api().is_some() || has_executable_in_path("xdotool")) {
+ 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 display_dimensions() -> (i32, i32) {
+ 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;
+ }
+ 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);
+ 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 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 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 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`).
+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]) {
+ return;
+ }
+ if !run_quiet("xdotool", &["type", "--clearmodifiers", "--delay", "0", "--", &cleaned]) {
+ let _ = run_quiet("wtype", &["--", &cleaned]);
+ }
+}
+
+/// 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 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>()
+ {
+ 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));
+ }
+ if let Ok(val) = body.deserialize::<u64>() {
+ return Some(val);
+ }
+ }
+ 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()
+ && out.status.success()
+ && let Some(ms) = parse_idle_output_ms(&String::from_utf8_lossy(&out.stdout), false)
+ {
+ return Some(ms);
+ }
+ query_idle_ms_dbus()
+}
+
+/// 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 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("12", true), Some(12_000));
+ }
}
diff --git a/desktop/app/src/linux/mod.rs b/desktop/app/src/linux/mod.rs
index f1538cb..b61829f 100644
--- a/desktop/app/src/linux/mod.rs
+++ b/desktop/app/src/linux/mod.rs
@@ -35,6 +35,7 @@ pub mod vmic;
pub mod wallpaper;
pub mod widget;
pub mod wifi;
+pub mod window_capture;
pub mod wol;
use std::{fs, io::Read, process::Command};
diff --git a/desktop/app/src/linux/window_capture.rs b/desktop/app/src/linux/window_capture.rs
new file mode 100644
index 0000000..1e78310
--- /dev/null
+++ b/desktop/app/src/linux/window_capture.rs
@@ -0,0 +1,371 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! Capture a single window on Linux via in-process X11 `XGetImage`,
+//! 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,
+};
+
+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
+ }
+}
+
+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)
+}
+
+#[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,
+}
+
+#[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,
+}
+
+#[repr(C)]
+struct XImage {
+ width: c_int,
+ height: c_int,
+ xoffset: c_int,
+ format: 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,
+ 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,
+ get_image: unsafe extern "C" fn(
+ *mut c_void,
+ c_ulong,
+ c_int,
+ c_int,
+ c_uint,
+ c_uint,
+ c_ulong,
+ 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,
+}
+
+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) })
+}
+
+fn x11_win_cap_api() -> Option<&'static X11WinCapApi> {
+ static API: OnceLock<Option<X11WinCapApi>> = OnceLock::new();
+ API.get_or_init(|| unsafe {
+ let mut lib = std::ptr::null_mut();
+ for name in [c"libX11.so.6", c"libX11.so"] {
+ 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 {
+ open_display: dl_sym(lib, c"XOpenDisplay")?,
+ get_window_attributes: dl_sym(lib, c"XGetWindowAttributes")?,
+ get_image: dl_sym(lib, c"XGetImage")?,
+ close_display: dl_sym(lib, c"XCloseDisplay")?,
+ free: dl_sym(lib, c"XFree")?,
+ })
+ })
+ .as_ref()
+}
+
+struct ThreadDisplay(*mut c_void);
+
+impl Drop for ThreadDisplay {
+ fn drop(&mut self) {
+ if !self.0.is_null()
+ && let Some(api) = x11_win_cap_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;
+ }
+ std::thread_local! {
+ static DISPLAY: RefCell<Option<ThreadDisplay>> = const { RefCell::new(None) };
+ }
+ let api = x11_win_cap_api()?;
+ DISPLAY.with(|cell| unsafe {
+ let mut borrow = cell.borrow_mut();
+ if borrow.is_none() {
+ let dpy = (api.open_display)(std::ptr::null());
+ if !dpy.is_null() {
+ *borrow = Some(ThreadDisplay(dpy));
+ }
+ }
+ let dpy = borrow.as_ref()?.0;
+ 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
+ || 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,
+ 0,
+ 0,
+ src_w,
+ src_h,
+ !0 as 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 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;
+ 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;
+ }
+ }
+ }
+ if let Some(destroy) = (*img).f.destroy_image {
+ let _ = destroy(img);
+ } else {
+ let _ = (api.free)(img.cast());
+ }
+ Some((src_w, src_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]);
+ }
+ }
+}