Skip to content

Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.

feat: native XTest paste binary for Linux with compositor-aware fallbacks (#262)

Gabriel Steine565753ca54f
diff --git a/.github/workflows/build-and-notarize.yml b/.github/workflows/build-and-notarize.yml
index ec305c5e7..8e53064ae 100644
--- a/.github/workflows/build-and-notarize.yml
+++ b/.github/workflows/build-and-notarize.yml
@@ -58,10 +58,10 @@ jobs:
key: linux-electron-${{ hashFiles('**/package-lock.json') }}
restore-keys: linux-electron-
- - name: Install Linux packaging dependencies
+ - name: Install Linux build and packaging dependencies
run: |
sudo apt-get update
- sudo apt-get install -y rpm
+ sudo apt-get install -y rpm libx11-dev libxtst-dev
- name: Build Application
run: npm run build:linux -- --publish never
diff --git a/.gitignore b/.gitignore
index ae7a38f09..80e6d0cb3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -310,3 +310,4 @@ skills/
ehthumbs.db
Thumbs.db
.macos-globe-listener.hash
+.linux-fast-paste.hash
diff --git a/CLAUDE.md b/CLAUDE.md
index ec9c25184..a45d1c44c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -51,7 +51,7 @@ OpenWhispr is an Electron-based desktop dictation application that uses whisper.
- **clipboard.js**: Cross-platform clipboard operations
- macOS: AppleScript-based paste with accessibility permission check
- Windows: PowerShell SendKeys with nircmd.exe fallback
- - Linux: Multi-tool support (wtype, ydotool, xdotool) for X11/Wayland compatibility
+ - Linux: Native XTest binary + compositor-aware fallbacks (xdotool, wtype, ydotool)
- **database.js**: SQLite operations for transcription history
- **debugLogger.js**: Debug logging system with file output
- **devServerManager.js**: Vite dev server integration
@@ -435,10 +435,10 @@ On GNOME Wayland, Electron's `globalShortcut` API doesn't work due to Wayland's
3. **Clipboard Not Working**:
- macOS: Check accessibility permissions (required for AppleScript paste)
- - Linux X11: Install `xdotool` for paste simulation
- - Linux Wayland: Install `wtype` or `ydotool` (requires `ydotoold` daemon)
- - GNOME Wayland: Use `xdotool` for XWayland apps only
- - Other Wayland compositors: `wtype` (if compositor supports virtual keyboard) or `ydotool`
+ - Linux: Native `linux-fast-paste` binary (XTest) is tried first, works for X11 and XWayland apps
+ - X11: xdotool fallback if native binary unavailable
+ - GNOME/KDE Wayland: xdotool (XWayland apps) → ydotool (requires ydotoold daemon)
+ - wlroots Wayland (Sway, Hyprland): wtype → xdotool → ydotool
- Windows: PowerShell SendKeys (built-in) or nircmd.exe (bundled)
4. **Build Issues**:
diff --git a/TROUBLESHOOTING.md b/TROUBLESHOOTING.md
index a9d93e979..d54855ad1 100644
--- a/TROUBLESHOOTING.md
+++ b/TROUBLESHOOTING.md
@@ -94,7 +94,7 @@
- Debian/Ubuntu: `sudo apt install wl-clipboard`
- Fedora/RHEL: `sudo dnf install wl-clipboard`
- Arch: `sudo pacman -S wl-clipboard`
-2. Ensure a paste tool is installed (`wtype`, `ydotool`, or `xdotool`)
+2. Ensure a paste tool is installed (`xdotool` recommended, or `wtype` for Sway/Hyprland, or `ydotool` with daemon)
3. Restart OpenWhispr after installing
OpenWhispr tries clipboard methods in order: `wl-copy` (most reliable) → renderer `navigator.clipboard` → X11 fallback.
diff --git a/electron-builder.json b/electron-builder.json
index e2acdaf56..c762020d7 100644
--- a/electron-builder.json
+++ b/electron-builder.json
@@ -87,6 +87,7 @@
"src/assets/**/*",
"resources/bin/macos-globe-listener",
"resources/bin/macos-fast-paste",
+ "resources/bin/linux-fast-paste",
{
"from": "resources/bin/",
"to": "bin/",
@@ -156,9 +157,9 @@
"deb": {
"afterRemove": "resources/linux/after-remove.sh",
"fpm": [
- "--deb-recommends",
+ "--deb-suggests",
"xdotool",
- "--deb-recommends",
+ "--deb-suggests",
"wtype",
"--deb-recommends",
"wl-clipboard"
@@ -167,9 +168,9 @@
"rpm": {
"fpm": [
"--rpm-tag",
- "Recommends: xdotool",
+ "Suggests: xdotool",
"--rpm-tag",
- "Recommends: wtype",
+ "Suggests: wtype",
"--rpm-tag",
"Recommends: wl-clipboard"
]
diff --git a/package.json b/package.json
index b57ef1648..7e86dbb4a 100644
--- a/package.json
+++ b/package.json
@@ -8,7 +8,8 @@
"compile:globe": "node scripts/build-globe-listener.js",
"compile:fast-paste": "node scripts/build-macos-fast-paste.js",
"compile:winkeys": "node scripts/build-windows-key-listener.js",
- "compile:native": "npm run compile:globe && npm run compile:fast-paste && npm run compile:winkeys",
+ "compile:linux-paste": "node scripts/build-linux-fast-paste.js",
+ "compile:native": "npm run compile:globe && npm run compile:fast-paste && npm run compile:winkeys && npm run compile:linux-paste",
"prestart": "npm run compile:native",
"start": "electron .",
"predev": "npm run compile:native",
diff --git a/resources/linux-fast-paste.c b/resources/linux-fast-paste.c
new file mode 100644
index 000000000..23ef77a50
--- /dev/null
+++ b/resources/linux-fast-paste.c
@@ -0,0 +1,234 @@
+#define _GNU_SOURCE
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <strings.h>
+#include <X11/Xlib.h>
+#include <X11/Xatom.h>
+#include <X11/Xutil.h>
+#include <X11/extensions/XTest.h>
+#include <X11/keysym.h>
+#include <unistd.h>
+
+#ifdef HAVE_UINPUT
+#include <linux/uinput.h>
+#include <linux/input.h>
+#include <fcntl.h>
+#include <errno.h>
+#endif
+
+static const char *terminal_classes[] = {
+ "konsole", "gnome-terminal", "terminal", "kitty", "alacritty",
+ "terminator", "xterm", "urxvt", "rxvt", "tilix", "terminology",
+ "wezterm", "foot", "st", "yakuake", "ghostty", "guake", "tilda",
+ "hyper", "tabby", "sakura", "warp", NULL
+};
+
+static int is_terminal(const char *wm_class) {
+ if (!wm_class) return 0;
+ for (int i = 0; terminal_classes[i]; i++) {
+ if (strcasestr(wm_class, terminal_classes[i]))
+ return 1;
+ }
+ return 0;
+}
+
+static Window get_active_window(Display *dpy) {
+ Atom prop = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", True);
+ if (prop != None) {
+ Atom actual_type;
+ int actual_format;
+ unsigned long nitems, bytes_after;
+ unsigned char *data = NULL;
+
+ if (XGetWindowProperty(dpy, DefaultRootWindow(dpy), prop, 0, 1, False,
+ XA_WINDOW, &actual_type, &actual_format,
+ &nitems, &bytes_after, &data) == Success && data) {
+ Window win = nitems > 0 ? *(Window *)data : None;
+ XFree(data);
+ if (win != None) return win;
+ }
+ }
+
+ Window focused;
+ int revert;
+ XGetInputFocus(dpy, &focused, &revert);
+ return focused;
+}
+
+/* Send _NET_ACTIVE_WINDOW client message then fall back to XSetInputFocus */
+static void activate_window(Display *dpy, Window win) {
+ Atom net_active = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False);
+ XEvent ev;
+ memset(&ev, 0, sizeof(ev));
+ ev.xclient.type = ClientMessage;
+ ev.xclient.window = win;
+ ev.xclient.message_type = net_active;
+ ev.xclient.format = 32;
+ ev.xclient.data.l[0] = 2; /* source: pager / direct call */
+ ev.xclient.data.l[1] = CurrentTime;
+ ev.xclient.data.l[2] = 0;
+
+ XSendEvent(dpy, DefaultRootWindow(dpy), False,
+ SubstructureNotifyMask | SubstructureRedirectMask, &ev);
+ XFlush(dpy);
+
+ /* Give the WM time to process the activation request */
+ usleep(50000);
+
+ /* Fallback: also set X input focus directly */
+ XSetInputFocus(dpy, win, RevertToParent, CurrentTime);
+ XFlush(dpy);
+ usleep(20000);
+}
+
+#ifdef HAVE_UINPUT
+static void emit(int fd, int type, int code, int val) {
+ struct input_event ie;
+ memset(&ie, 0, sizeof(ie));
+ ie.type = type;
+ ie.code = code;
+ ie.value = val;
+ if (write(fd, &ie, sizeof(ie)) < 0) {
+ /* best-effort: logged by caller via exit code */
+ }
+}
+
+static int paste_via_uinput(int use_shift) {
+ int fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK);
+ if (fd < 0) {
+ fprintf(stderr, "Cannot open /dev/uinput: %s\n", strerror(errno));
+ return 3;
+ }
+
+ if (ioctl(fd, UI_SET_EVBIT, EV_KEY) < 0 ||
+ ioctl(fd, UI_SET_KEYBIT, KEY_LEFTCTRL) < 0 ||
+ ioctl(fd, UI_SET_KEYBIT, KEY_LEFTSHIFT) < 0 ||
+ ioctl(fd, UI_SET_KEYBIT, KEY_V) < 0) {
+ close(fd);
+ return 4;
+ }
+
+ struct uinput_setup usetup;
+ memset(&usetup, 0, sizeof(usetup));
+ usetup.id.bustype = BUS_USB;
+ usetup.id.vendor = 0x1234;
+ usetup.id.product = 0x5678;
+ snprintf(usetup.name, UINPUT_MAX_NAME_SIZE, "openwhispr-paste");
+
+ if (ioctl(fd, UI_DEV_SETUP, &usetup) < 0 ||
+ ioctl(fd, UI_DEV_CREATE) < 0) {
+ close(fd);
+ return 4;
+ }
+
+ /* Let the kernel register the virtual device */
+ usleep(50000);
+
+ emit(fd, EV_KEY, KEY_LEFTCTRL, 1);
+ emit(fd, EV_SYN, SYN_REPORT, 0);
+
+ if (use_shift) {
+ emit(fd, EV_KEY, KEY_LEFTSHIFT, 1);
+ emit(fd, EV_SYN, SYN_REPORT, 0);
+ }
+
+ usleep(8000);
+
+ emit(fd, EV_KEY, KEY_V, 1);
+ emit(fd, EV_SYN, SYN_REPORT, 0);
+ usleep(8000);
+
+ emit(fd, EV_KEY, KEY_V, 0);
+ emit(fd, EV_SYN, SYN_REPORT, 0);
+
+ usleep(8000);
+
+ if (use_shift) {
+ emit(fd, EV_KEY, KEY_LEFTSHIFT, 0);
+ emit(fd, EV_SYN, SYN_REPORT, 0);
+ }
+
+ emit(fd, EV_KEY, KEY_LEFTCTRL, 0);
+ emit(fd, EV_SYN, SYN_REPORT, 0);
+
+ usleep(20000);
+
+ ioctl(fd, UI_DEV_DESTROY);
+ close(fd);
+ return 0;
+}
+#endif
+
+int main(int argc, char *argv[]) {
+ int force_terminal = 0;
+ int use_uinput = 0;
+ Window target_window = None;
+
+ for (int i = 1; i < argc; i++) {
+ if (strcmp(argv[i], "--terminal") == 0) {
+ force_terminal = 1;
+ } else if (strcmp(argv[i], "--uinput") == 0) {
+ use_uinput = 1;
+ } else if (strcmp(argv[i], "--window") == 0 && i + 1 < argc) {
+ target_window = (Window)strtoul(argv[++i], NULL, 0);
+ }
+ }
+
+ if (use_uinput) {
+#ifdef HAVE_UINPUT
+ return paste_via_uinput(force_terminal);
+#else
+ fprintf(stderr, "uinput support not compiled in\n");
+ return 3;
+#endif
+ }
+
+ Display *dpy = XOpenDisplay(NULL);
+ if (!dpy) return 1;
+
+ int event_base, error_base, major, minor;
+ if (!XTestQueryExtension(dpy, &event_base, &error_base, &major, &minor)) {
+ XCloseDisplay(dpy);
+ return 2;
+ }
+
+ if (target_window != None) {
+ activate_window(dpy, target_window);
+ }
+
+ Window win = (target_window != None) ? target_window : get_active_window(dpy);
+
+ int use_shift = force_terminal;
+ if (!use_shift && win != None) {
+ XClassHint hint;
+ if (XGetClassHint(dpy, win, &hint)) {
+ use_shift = is_terminal(hint.res_class) || is_terminal(hint.res_name);
+ XFree(hint.res_name);
+ XFree(hint.res_class);
+ }
+ }
+
+ KeyCode ctrl = XKeysymToKeycode(dpy, XK_Control_L);
+ KeyCode shift = XKeysymToKeycode(dpy, XK_Shift_L);
+ KeyCode v = XKeysymToKeycode(dpy, XK_v);
+
+ XTestFakeKeyEvent(dpy, ctrl, True, CurrentTime);
+ if (use_shift)
+ XTestFakeKeyEvent(dpy, shift, True, CurrentTime);
+ usleep(8000);
+
+ XTestFakeKeyEvent(dpy, v, True, CurrentTime);
+ usleep(8000);
+ XTestFakeKeyEvent(dpy, v, False, CurrentTime);
+
+ usleep(8000);
+ if (use_shift)
+ XTestFakeKeyEvent(dpy, shift, False, CurrentTime);
+ XTestFakeKeyEvent(dpy, ctrl, False, CurrentTime);
+
+ XFlush(dpy);
+ usleep(20000);
+ XCloseDisplay(dpy);
+ return 0;
+}
diff --git a/scripts/build-linux-fast-paste.js b/scripts/build-linux-fast-paste.js
new file mode 100755
index 000000000..f9c3d49e9
--- /dev/null
+++ b/scripts/build-linux-fast-paste.js
@@ -0,0 +1,141 @@
+#!/usr/bin/env node
+
+const { spawnSync } = require("child_process");
+const crypto = require("crypto");
+const fs = require("fs");
+const path = require("path");
+
+const isLinux = process.platform === "linux";
+if (!isLinux) {
+ process.exit(0);
+}
+
+const projectRoot = path.resolve(__dirname, "..");
+const cSource = path.join(projectRoot, "resources", "linux-fast-paste.c");
+const outputDir = path.join(projectRoot, "resources", "bin");
+const outputBinary = path.join(outputDir, "linux-fast-paste");
+const hashFile = path.join(outputDir, ".linux-fast-paste.hash");
+
+function log(message) {
+ console.log(`[linux-fast-paste] ${message}`);
+}
+
+function ensureDir(dirPath) {
+ if (!fs.existsSync(dirPath)) {
+ fs.mkdirSync(dirPath, { recursive: true });
+ }
+}
+
+if (!fs.existsSync(cSource)) {
+ console.error(`[linux-fast-paste] C source not found at ${cSource}`);
+ process.exit(1);
+}
+
+ensureDir(outputDir);
+
+let needsBuild = true;
+if (fs.existsSync(outputBinary)) {
+ try {
+ const binaryStat = fs.statSync(outputBinary);
+ const sourceStat = fs.statSync(cSource);
+ if (binaryStat.mtimeMs >= sourceStat.mtimeMs) {
+ needsBuild = false;
+ }
+ } catch {
+ needsBuild = true;
+ }
+}
+
+function hasUinputHeaders() {
+ for (const compiler of ["gcc", "cc"]) {
+ try {
+ const result = spawnSync(compiler, ["-E", "-x", "c", "-"], {
+ input: "#include <linux/uinput.h>\n",
+ stdio: ["pipe", "pipe", "pipe"],
+ env: process.env,
+ });
+ if (result.status === 0) return true;
+ } catch {}
+ }
+ return false;
+}
+
+const uinputAvailable = hasUinputHeaders();
+
+function computeBuildHash() {
+ const sourceContent = fs.readFileSync(cSource, "utf8");
+ const flags = uinputAvailable ? "uinput" : "nouinput";
+ return crypto.createHash("sha256").update(sourceContent + flags).digest("hex");
+}
+
+if (!needsBuild && fs.existsSync(outputBinary)) {
+ try {
+ const currentHash = computeBuildHash();
+
+ if (fs.existsSync(hashFile)) {
+ const savedHash = fs.readFileSync(hashFile, "utf8").trim();
+ if (savedHash !== currentHash) {
+ log("Source or build flags changed, rebuild needed");
+ needsBuild = true;
+ }
+ } else {
+ fs.writeFileSync(hashFile, currentHash);
+ }
+ } catch (err) {
+ log(`Hash check failed: ${err.message}, forcing rebuild`);
+ needsBuild = true;
+ }
+}
+
+if (!needsBuild) {
+ process.exit(0);
+}
+
+function attemptCompile(command, args) {
+ log(`Compiling with ${[command, ...args].join(" ")}`);
+ return spawnSync(command, args, {
+ stdio: "inherit",
+ env: process.env,
+ });
+}
+
+const compileArgs = [
+ "-O2",
+ cSource,
+ "-o",
+ outputBinary,
+ "-lX11",
+ "-lXtst",
+];
+
+if (uinputAvailable) {
+ log("uinput headers found, enabling uinput support");
+ compileArgs.push("-DHAVE_UINPUT");
+} else {
+ log("uinput headers not found, building without uinput support");
+}
+
+let result = attemptCompile("gcc", compileArgs);
+
+if (result.status !== 0) {
+ result = attemptCompile("cc", compileArgs);
+}
+
+if (result.status !== 0) {
+ console.warn("[linux-fast-paste] Failed to compile Linux fast-paste binary. Install libx11-dev and libxtst-dev to enable native paste. Falling back to system tools.");
+ process.exit(0);
+}
+
+try {
+ fs.chmodSync(outputBinary, 0o755);
+} catch (error) {
+ console.warn(`[linux-fast-paste] Unable to set executable permissions: ${error.message}`);
+}
+
+try {
+ fs.writeFileSync(hashFile, computeBuildHash());
+} catch (err) {
+ log(`Warning: Could not save source hash: ${err.message}`);
+}
+
+log("Successfully built Linux fast-paste binary.");
diff --git a/src/components/ui/PasteToolsInfo.tsx b/src/components/ui/PasteToolsInfo.tsx
index a0596f4cc..6e8c11283 100644
--- a/src/components/ui/PasteToolsInfo.tsx
+++ b/src/components/ui/PasteToolsInfo.tsx
@@ -62,6 +62,7 @@ export default function PasteToolsInfo({
// Linux with tools available
if (pasteToolsInfo.platform === "linux" && pasteToolsInfo.available) {
const method = pasteToolsInfo.method || "xdotool";
+ const methodLabel = method === "xtest" ? "built-in (XTest)" : method;
const methodSuffix =
pasteToolsInfo.isWayland && method === "xdotool"
? t("pasteToolsInfo.xwaylandAppsOnly")
@@ -78,7 +79,7 @@ export default function PasteToolsInfo({
</h3>
<p className="text-sm text-success dark:text-success">
{t("pasteToolsInfo.usingMethodPrefix")}{" "}
- <code className="bg-success/20 px-1 rounded">{method}</code> {methodSuffix}
+ <code className="bg-success/20 px-1 rounded">{methodLabel}</code> {methodSuffix}
</p>
</div>
</div>
@@ -93,7 +94,6 @@ export default function PasteToolsInfo({
// Linux without tools - show helpful install instructions
if (pasteToolsInfo.platform === "linux" && !pasteToolsInfo.available) {
const isWayland = pasteToolsInfo.isWayland;
- const xwaylandAvailable = pasteToolsInfo.xwaylandAvailable;
const recommendedTool = pasteToolsInfo.recommendedInstall;
const showInstall = !!recommendedTool;
@@ -149,13 +149,13 @@ export default function PasteToolsInfo({
)}
</div>
- {isWayland && recommendedTool === "wtype" && xwaylandAvailable && (
+ {isWayland && recommendedTool === "wtype" && (
<p className="text-sm text-warning dark:text-warning mt-3">
{t("pasteToolsInfo.noteXwaylandAlso")}
</p>
)}
- {isWayland && recommendedTool !== "wtype" && (
+ {isWayland && recommendedTool === "xdotool" && (
<p className="text-sm text-warning dark:text-warning mt-3">
{t("pasteToolsInfo.noteXwaylandOnly")}
</p>
diff --git a/src/helpers/clipboard.js b/src/helpers/clipboard.js
index 8d62b022c..499913619 100644
--- a/src/helpers/clipboard.js
+++ b/src/helpers/clipboard.js
@@ -20,6 +20,17 @@ const getLinuxDesktopEnv = () =>
const isGnomeDesktop = (desktopEnv) => desktopEnv.includes("gnome");
+const isKdeDesktop = (desktopEnv) => desktopEnv.includes("kde");
+
+const isWlrootsCompositor = (desktopEnv) => {
+ const wlrootsDesktops = ["sway", "hyprland", "wayfire", "river", "dwl", "labwc", "cage"];
+ return (
+ wlrootsDesktops.some((wm) => desktopEnv.includes(wm)) ||
+ !!process.env.SWAYSOCK ||
+ !!process.env.HYPRLAND_INSTANCE_SIGNATURE
+ );
+};
+
const getLinuxSessionInfo = () => {
const isWayland =
(process.env.XDG_SESSION_TYPE || "").toLowerCase() === "wayland" ||
@@ -27,11 +38,12 @@ const getLinuxSessionInfo = () => {
const xwaylandAvailable = isWayland && !!process.env.DISPLAY;
const desktopEnv = getLinuxDesktopEnv();
const isGnome = isWayland && isGnomeDesktop(desktopEnv);
+ const isKde = isWayland && isKdeDesktop(desktopEnv);
+ const isWlroots = isWayland && isWlrootsCompositor(desktopEnv);
- return { isWayland, xwaylandAvailable, desktopEnv, isGnome };
+ return { isWayland, xwaylandAvailable, desktopEnv, isGnome, isKde, isWlroots };
};
-// ms before simulating keystroke
const PASTE_DELAYS = {
darwin: 120,
win32_nircmd: 30,
@@ -39,7 +51,6 @@ const PASTE_DELAYS = {
linux: 50,
};
-// ms after paste completes before restoring clipboard
const RESTORE_DELAYS = {
darwin: 450,
win32_nircmd: 80,
@@ -63,6 +74,8 @@ class ClipboardManager {
this.nircmdChecked = false;
this.fastPastePath = null;
this.fastPasteChecked = false;
+ this.linuxFastPastePath = null;
+ this.linuxFastPasteChecked = false;
}
_isWayland() {
@@ -113,9 +126,7 @@ class ClipboardManager {
this.nircmdPath = nircmdPath;
return nircmdPath;
}
- } catch (error) {
- // Continue checking other paths
- }
+ } catch (error) {}
}
this.safeLog("⚠️ nircmd.exe not found, will use PowerShell fallback");
@@ -133,35 +144,29 @@ class ClipboardManager {
};
}
- resolveFastPasteBinary() {
- if (this.fastPasteChecked) {
- return this.fastPastePath;
+ _resolveNativeBinary(binaryName, platform, cacheKeyChecked, cacheKeyPath) {
+ if (this[cacheKeyChecked]) {
+ return this[cacheKeyPath];
}
- this.fastPasteChecked = true;
+ this[cacheKeyChecked] = true;
- if (process.platform !== "darwin") {
+ if (process.platform !== platform) {
return null;
}
const candidates = new Set([
- path.join(__dirname, "..", "..", "resources", "bin", "macos-fast-paste"),
- path.join(__dirname, "..", "..", "resources", "macos-fast-paste"),
+ path.join(__dirname, "..", "..", "resources", "bin", binaryName),
+ path.join(__dirname, "..", "..", "resources", binaryName),
]);
if (process.resourcesPath) {
[
- path.join(process.resourcesPath, "macos-fast-paste"),
- path.join(process.resourcesPath, "bin", "macos-fast-paste"),
- path.join(process.resourcesPath, "resources", "macos-fast-paste"),
- path.join(process.resourcesPath, "resources", "bin", "macos-fast-paste"),
- path.join(process.resourcesPath, "app.asar.unpacked", "resources", "macos-fast-paste"),
- path.join(
- process.resourcesPath,
- "app.asar.unpacked",
- "resources",
- "bin",
- "macos-fast-paste"
- ),
+ path.join(process.resourcesPath, binaryName),
+ path.join(process.resourcesPath, "bin", binaryName),
+ path.join(process.resourcesPath, "resources", binaryName),
+ path.join(process.resourcesPath, "resources", "bin", binaryName),
+ path.join(process.resourcesPath, "app.asar.unpacked", "resources", binaryName),
+ path.join(process.resourcesPath, "app.asar.unpacked", "resources", "bin", binaryName),
].forEach((candidate) => candidates.add(candidate));
}
@@ -174,7 +179,7 @@ class ClipboardManager {
} catch {
fs.chmodSync(candidate, 0o755);
}
- this.fastPastePath = candidate;
+ this[cacheKeyPath] = candidate;
return candidate;
}
} catch {
@@ -185,6 +190,60 @@ class ClipboardManager {
return null;
}
+ resolveFastPasteBinary() {
+ return this._resolveNativeBinary(
+ "macos-fast-paste",
+ "darwin",
+ "fastPasteChecked",
+ "fastPastePath"
+ );
+ }
+
+ resolveLinuxFastPasteBinary() {
+ return this._resolveNativeBinary(
+ "linux-fast-paste",
+ "linux",
+ "linuxFastPasteChecked",
+ "linuxFastPastePath"
+ );
+ }
+
+ _isYdotoolDaemonRunning() {
+ const uid = process.getuid?.();
+ const socketPaths = [
+ process.env.YDOTOOL_SOCKET,
+ uid != null ? `/run/user/${uid}/.ydotool_socket` : null,
+ "/tmp/.ydotool_socket",
+ ].filter(Boolean);
+
+ for (const socketPath of socketPaths) {
+ try {
+ if (fs.statSync(socketPath)) return true;
+ } catch {}
+ }
+
+ try {
+ return spawnSync("pidof", ["ydotoold"], { timeout: 1000 }).status === 0;
+ } catch {
+ return false;
+ }
+ }
+
+ _canAccessUinput() {
+ if (process.platform !== "linux") return false;
+ const now = Date.now();
+ if (this._uinputCache && now < this._uinputCache.expiresAt) {
+ return this._uinputCache.accessible;
+ }
+ let accessible = false;
+ try {
+ fs.accessSync("/dev/uinput", fs.constants.W_OK);
+ accessible = true;
+ } catch {}
+ this._uinputCache = { accessible, expiresAt: now + 30000 };
+ return accessible;
+ }
+
safeLog(...args) {
if (process.env.NODE_ENV === "development") {
try {
@@ -262,7 +321,7 @@ class ClipboardManager {
method = nircmdPath ? "nircmd" : "powershell";
await this.pasteWindows(originalClipboard);
} else {
- method = "linux-tools";
+ method = this.resolveLinuxFastPasteBinary() ? "linux-xtest" : "linux-tools";
await this.pasteLinux(originalClipboard, options);
}
@@ -574,11 +633,13 @@ class ClipboardManager {
}
async pasteLinux(originalClipboard, options = {}) {
- const { isWayland, xwaylandAvailable, isGnome } = getLinuxSessionInfo();
+ const { isWayland, xwaylandAvailable, isGnome, isKde, isWlroots } = getLinuxSessionInfo();
const webContents = options.webContents;
const xdotoolExists = this.commandExists("xdotool");
const wtypeExists = this.commandExists("wtype");
const ydotoolExists = this.commandExists("ydotool");
+ const ydotoolDaemonRunning = ydotoolExists && this._isYdotoolDaemonRunning();
+ const linuxFastPaste = this.resolveLinuxFastPasteBinary();
debugLogger.debug(
"Linux paste environment",
@@ -586,9 +647,14 @@ class ClipboardManager {
isWayland,
xwaylandAvailable,
isGnome,
+ isKde,
+ isWlroots,
+ linuxFastPaste: !!linuxFastPaste,
+ canAccessUinput: this._canAccessUinput(),
xdotoolExists,
wtypeExists,
ydotoolExists,
+ ydotoolDaemonRunning,
display: process.env.DISPLAY,
waylandDisplay: process.env.WAYLAND_DISPLAY,
xdgSessionType: process.env.XDG_SESSION_TYPE,
@@ -597,64 +663,190 @@ class ClipboardManager {
"clipboard"
);
- // Capture target window before our window takes focus
- const getXdotoolActiveWindow = () => {
- if (!xdotoolExists || (isWayland && !xwaylandAvailable)) {
- return null;
- }
+ const restoreClipboard = () => {
+ setTimeout(() => {
+ if (isWayland) {
+ this._writeClipboardWayland(originalClipboard, webContents);
+ } else {
+ clipboard.writeText(originalClipboard);
+ }
+ }, RESTORE_DELAYS.linux);
+ };
+
+ const terminalClasses = [
+ "konsole",
+ "gnome-terminal",
+ "terminal",
+ "kitty",
+ "alacritty",
+ "terminator",
+ "xterm",
+ "urxvt",
+ "rxvt",
+ "tilix",
+ "terminology",
+ "wezterm",
+ "foot",
+ "st",
+ "yakuake",
+ "ghostty",
+ "guake",
+ "tilda",
+ "hyper",
+ "tabby",
+ "sakura",
+ "warp",
+ ];
+
+ // Pre-detect the target window BEFORE our window takes focus or blurs,
+ // so the fast-paste binary and fallback tools know where to send keystrokes.
+ const preDetectTargetWindow = () => {
+ if (!xdotoolExists || (isWayland && !xwaylandAvailable)) return null;
try {
const result = spawnSync("xdotool", ["getactivewindow"]);
- if (result.status !== 0) {
- return null;
- }
- return result.stdout.toString().trim() || null;
+ return result.status === 0 ? result.stdout.toString().trim() || null : null;
} catch {
return null;
}
};
- const getXdotoolWindowClass = (windowId) => {
- if (!xdotoolExists || (isWayland && !xwaylandAvailable)) {
- return null;
- }
+ const preDetectWindowClass = (windowId) => {
+ if (!xdotoolExists || (isWayland && !xwaylandAvailable)) return null;
try {
const args = windowId
? ["getwindowclassname", windowId]
: ["getactivewindow", "getwindowclassname"];
const result = spawnSync("xdotool", args);
- if (result.status !== 0) {
- return null;
- }
- const className = result.stdout.toString().toLowerCase().trim();
- return className || null;
+ return result.status === 0 ? result.stdout.toString().toLowerCase().trim() || null : null;
} catch {
return null;
}
};
- const targetWindowId = getXdotoolActiveWindow();
- const xdotoolWindowClass = getXdotoolWindowClass(targetWindowId);
+ const targetWindowId = preDetectTargetWindow();
+ const xdotoolWindowClass = preDetectWindowClass(targetWindowId);
+
+ if (linuxFastPaste) {
+ const earlyIsTerminal = xdotoolWindowClass
+ ? terminalClasses.some((t) => xdotoolWindowClass.includes(t))
+ : false;
+
+ const spawnFastPaste = (args, label) =>
+ new Promise((resolve, reject) => {
+ debugLogger.debug(
+ `Attempting native linux-fast-paste (${label})`,
+ { linuxFastPaste, args, targetWindowId, xdotoolWindowClass, earlyIsTerminal },
+ "clipboard"
+ );
+ const proc = spawn(linuxFastPaste, args);
+ let stderr = "";
+
+ proc.stderr?.on("data", (data) => {
+ stderr += data.toString();
+ });
+
+ let timedOut = false;
+ const timeoutId = setTimeout(() => {
+ timedOut = true;
+ killProcess(proc, "SIGKILL");
+ }, 2000);
+
+ proc.on("close", (code) => {
+ if (timedOut) return reject(new Error("linux-fast-paste timed out"));
+ clearTimeout(timeoutId);
+ if (code === 0) {
+ resolve();
+ } else {
+ reject(
+ new Error(
+ `linux-fast-paste exited with code ${code}${stderr ? `: ${stderr.trim()}` : ""}`
+ )
+ );
+ }
+ });
+
+ proc.on("error", (error) => {
+ if (timedOut) return;
+ clearTimeout(timeoutId);
+ reject(error);
+ });
+ });
+
+ if (isWayland) {
+ const uinputArgs = ["--uinput"];
+ if (earlyIsTerminal) uinputArgs.push("--terminal");
+
+ try {
+ await spawnFastPaste(uinputArgs, "uinput");
+ this.safeLog("✅ Paste successful using native linux-fast-paste (uinput)");
+ debugLogger.info(
+ "Paste successful",
+ { tool: "linux-fast-paste", method: "uinput" },
+ "clipboard"
+ );
+ restoreClipboard();
+ return;
+ } catch (uinputError) {
+ debugLogger.warn("uinput paste failed", { error: uinputError?.message }, "clipboard");
+
+ if (xwaylandAvailable) {
+ const xtestArgs = [];
+ if (targetWindowId) xtestArgs.push("--window", targetWindowId);
+ if (earlyIsTerminal) xtestArgs.push("--terminal");
+
+ try {
+ await spawnFastPaste(xtestArgs, "XTest/XWayland fallback");
+ this.safeLog("✅ Paste successful using native linux-fast-paste (XTest/XWayland)");
+ debugLogger.info(
+ "Paste successful",
+ { tool: "linux-fast-paste", method: "xtest-xwayland" },
+ "clipboard"
+ );
+ restoreClipboard();
+ return;
+ } catch (xtestError) {
+ debugLogger.warn(
+ "XTest/XWayland fallback also failed",
+ { error: xtestError?.message },
+ "clipboard"
+ );
+ }
+ }
+
+ this.safeLog(
+ `⚠️ Native linux-fast-paste failed: ${uinputError?.message || uinputError}, falling back to system tools`
+ );
+ }
+ } else {
+ const xtestArgs = [];
+ if (targetWindowId) xtestArgs.push("--window", targetWindowId);
+ if (earlyIsTerminal) xtestArgs.push("--terminal");
+
+ try {
+ await spawnFastPaste(xtestArgs, "XTest");
+ this.safeLog("✅ Paste successful using native linux-fast-paste (XTest)");
+ debugLogger.info(
+ "Paste successful",
+ { tool: "linux-fast-paste", method: "xtest" },
+ "clipboard"
+ );
+ restoreClipboard();
+ return;
+ } catch (error) {
+ this.safeLog(
+ `⚠️ Native linux-fast-paste failed: ${error?.message || error}, falling back to system tools`
+ );
+ debugLogger.warn(
+ "Native linux-fast-paste failed, falling back",
+ { error: error?.message },
+ "clipboard"
+ );
+ }
+ }
+ }
// Terminals use Ctrl+Shift+V instead of Ctrl+V
const isTerminal = () => {
- const terminalClasses = [
- "konsole",
- "gnome-terminal",
- "terminal",
- "kitty",
- "alacritty",
- "terminator",
- "xterm",
- "urxvt",
- "rxvt",
- "tilix",
- "terminology",
- "wezterm",
- "foot",
- "st",
- "yakuake",
- ];
-
if (xdotoolWindowClass) {
const isTerminalWindow = terminalClasses.some((term) => xdotoolWindowClass.includes(term));
if (isTerminalWindow) {
@@ -679,17 +871,15 @@ class ClipboardManager {
}
}
}
- } catch {
- // Detection failed, assume non-terminal
- }
+ } catch {}
return false;
};
const inTerminal = isTerminal();
const pasteKeys = inTerminal ? "ctrl+shift+v" : "ctrl+v";
- const canUseWtype = isWayland && !isGnome;
- const canUseYdotool = isWayland;
+ const canUseWtype = isWayland && isWlroots;
+ const canUseYdotool = ydotoolDaemonRunning;
const canUseXdotool = isWayland ? xwaylandAvailable && xdotoolExists : xdotoolExists;
// windowactivate ensures the target window (not ours) receives the keystroke
@@ -703,25 +893,34 @@ class ClipboardManager {
);
}
- // ydotool key codes: 29=Ctrl, 42=Shift, 47=V; :1=press, :0=release
- const ydotoolArgs = inTerminal
- ? ["key", "29:1", "42:1", "47:1", "47:0", "42:0", "29:0"]
- : ["key", "29:1", "47:1", "47:0", "29:0"];
-
- const candidates = [
- ...(canUseWtype
- ? [
- inTerminal
- ? {
- cmd: "wtype",
- args: ["-M", "ctrl", "-M", "shift", "-k", "v", "-m", "shift", "-m", "ctrl"],
- }
- : { cmd: "wtype", args: ["-M", "ctrl", "-k", "v", "-m", "ctrl"] },
- ]
- : []),
- ...(canUseXdotool ? [{ cmd: "xdotool", args: xdotoolArgs }] : []),
- ...(canUseYdotool ? [{ cmd: "ydotool", args: ydotoolArgs }] : []),
- ];
+ // Use key names for ydotool 0.1.x compat (Ubuntu ships 0.1.8)
+ const ydotoolArgs = inTerminal ? ["key", "ctrl+shift+v"] : ["key", "ctrl+v"];
+
+ const wtypeEntry = canUseWtype
+ ? [
+ inTerminal
+ ? {
+ cmd: "wtype",
+ args: ["-M", "ctrl", "-M", "shift", "-k", "v", "-m", "shift", "-m", "ctrl"],
+ }
+ : { cmd: "wtype", args: ["-M", "ctrl", "-k", "v", "-m", "ctrl"] },
+ ]
+ : [];
+ const xdotoolEntry = canUseXdotool ? [{ cmd: "xdotool", args: xdotoolArgs }] : [];
+ const ydotoolEntry = canUseYdotool ? [{ cmd: "ydotool", args: ydotoolArgs }] : [];
+
+ // Compositor-aware priority ordering
+ let candidates;
+ if (!isWayland) {
+ // X11: xdotool is native and needs no daemon; ydotool as fallback
+ candidates = [...xdotoolEntry, ...ydotoolEntry];
+ } else if (isWlroots) {
+ // wlroots (Sway, Hyprland, etc.): wtype is native; then xdotool for XWayland; ydotool last
+ candidates = [...wtypeEntry, ...xdotoolEntry, ...ydotoolEntry];
+ } else {
+ // GNOME, KDE, or unknown Wayland: xdotool for XWayland apps first; ydotool fallback; wtype last resort
+ candidates = [...xdotoolEntry, ...ydotoolEntry, ...wtypeEntry];
+ }
const available = candidates.filter((c) => this.commandExists(c.cmd));
@@ -786,13 +985,7 @@ class ClipboardManager {
if (code === 0) {
debugLogger.debug("Paste successful", { cmd: tool.cmd }, "clipboard");
- setTimeout(() => {
- if (isWayland) {
- this._writeClipboardWayland(originalClipboard, webContents);
- } else {
- clipboard.writeText(originalClipboard);
- }
- }, RESTORE_DELAYS.linux);
+ restoreClipboard();
resolve();
} else {
debugLogger.error(
@@ -837,7 +1030,7 @@ class ClipboardManager {
await pasteWith(tool);
this.safeLog(`✅ Paste successful using ${tool.cmd}`);
debugLogger.info("Paste successful", { tool: tool.cmd }, "clipboard");
- return; // Success!
+ return;
} catch (error) {
const failureInfo = {
tool: tool.cmd,
@@ -847,7 +1040,6 @@ class ClipboardManager {
failedAttempts.push(failureInfo);
this.safeLog(`⚠️ Paste with ${tool.cmd} failed:`, error?.message || error);
debugLogger.warn("Paste tool failed, trying next", failureInfo, "clipboard");
- // Continue to next tool
}
}
@@ -864,7 +1056,7 @@ class ClipboardManager {
"clipboard"
);
this.safeLog("🔄 Trying xdotool type fallback for terminal...");
- const textToType = clipboard.readText(); // Read what we put in clipboard
+ const textToType = clipboard.readText();
const typeArgs = targetWindowId
? ["windowactivate", "--sync", targetWindowId, "type", "--clearmodifiers", "--", textToType]
: ["type", "--clearmodifiers", "--", textToType];
@@ -893,43 +1085,39 @@ class ClipboardManager {
let errorMsg;
if (isWayland) {
- if (isGnome) {
- if (!xwaylandAvailable) {
+ if (isGnome || isKde) {
+ if (!xwaylandAvailable && !ydotoolDaemonRunning) {
errorMsg =
- "Clipboard copied, but GNOME Wayland blocks automatic pasting. Please paste manually with Ctrl+V.";
- } else if (!xdotoolExists) {
+ "Clipboard copied, but automatic pasting on Wayland requires xdotool (with XWayland) or ydotool (with ydotoold daemon running). Please paste manually with Ctrl+V.";
+ } else if (!xdotoolExists && !ydotoolDaemonRunning) {
errorMsg =
- "Clipboard copied, but automatic pasting on GNOME Wayland requires xdotool for XWayland apps. Please install xdotool or paste manually with Ctrl+V.";
- } else if (!xdotoolWindowClass) {
- errorMsg =
- "Clipboard copied, but the active app isn't running under XWayland. Please paste manually with Ctrl+V.";
+ "Clipboard copied, but automatic pasting requires xdotool (recommended) or ydotool. Please install xdotool or paste manually with Ctrl+V.";
} else {
errorMsg =
- "Clipboard copied, but paste simulation failed via XWayland. Please paste manually with Ctrl+V.";
+ "Clipboard copied, but paste simulation failed. Please paste manually with Ctrl+V.";
}
- } else if (!wtypeExists && !xdotoolExists) {
- if (!xwaylandAvailable) {
+ } else if (isWlroots) {
+ if (!wtypeExists && !xdotoolExists && !ydotoolDaemonRunning) {
errorMsg =
- "Clipboard copied, but automatic pasting on Wayland requires wtype or xdotool. Please install one or paste manually with Ctrl+V.";
+ "Clipboard copied, but automatic pasting requires wtype (recommended for your compositor) or xdotool. Please install one or paste manually with Ctrl+V.";
} else {
errorMsg =
- "Clipboard copied, but automatic pasting on Wayland requires xdotool (recommended for Electron/XWayland apps) or wtype. Please install one or paste manually with Ctrl+V.";
+ "Clipboard copied, but paste simulation failed. Please paste manually with Ctrl+V.";
}
} else {
- const xdotoolNote =
- xwaylandAvailable && !xdotoolExists
- ? " Consider installing xdotool, which works well with Electron apps running under XWayland."
- : "";
errorMsg =
- "Clipboard copied, but paste simulation failed on Wayland. Your compositor may not support the virtual keyboard protocol." +
- xdotoolNote +
- " Alternatively, paste manually with Ctrl+V.";
+ "Clipboard copied, but paste simulation failed on Wayland. Please install xdotool or paste manually with Ctrl+V.";
}
} else {
errorMsg =
"Clipboard copied, but paste simulation failed on X11. Please install xdotool or paste manually with Ctrl+V.";
}
+ if (ydotoolExists && !ydotoolDaemonRunning) {
+ errorMsg +=
+ "\n\nNote: ydotool is installed but the ydotoold daemon is not running. Start it with: sudo systemctl enable --now ydotool";
+ }
+
const err = new Error(errorMsg + failureSummary);
err.code = "PASTE_SIMULATION_FAILED";
err.failedAttempts = failedAttempts;
@@ -940,6 +1128,8 @@ class ClipboardManager {
failedAttempts,
isWayland,
isGnome,
+ isKde,
+ isWlroots,
},
"clipboard"
);
@@ -1087,6 +1277,10 @@ Would you like to open System Settings now?`;
}
preWarmAccessibility() {
+ if (process.platform === "linux") {
+ this.resolveLinuxFastPasteBinary();
+ return;
+ }
if (process.platform !== "darwin") return;
this.checkAccessibilityPermissions().catch(() => {});
this.resolveFastPasteBinary();
@@ -1129,41 +1323,59 @@ Would you like to open System Settings now?`;
};
}
- const { isWayland, xwaylandAvailable, isGnome } = getLinuxSessionInfo();
+ const { isWayland, xwaylandAvailable, isGnome, isKde, isWlroots } = getLinuxSessionInfo();
+ const linuxFastPaste = this.resolveLinuxFastPasteBinary();
+ const hasNativeBinary = !!linuxFastPaste;
+
const tools = [];
- const canUseWtype = isWayland && !isGnome;
- const canUseYdotool = isWayland;
+ const canUseWtype = isWayland && isWlroots;
+ const canUseYdotool = this.commandExists("ydotool") && this._isYdotoolDaemonRunning();
const canUseXdotool = !isWayland || xwaylandAvailable;
- if (canUseWtype && this.commandExists("wtype")) {
- tools.push("wtype");
- }
- if (canUseXdotool && this.commandExists("xdotool")) {
- tools.push("xdotool");
- }
- if (canUseYdotool && this.commandExists("ydotool")) {
- tools.push("ydotool");
+ if (!isWayland) {
+ if (canUseXdotool && this.commandExists("xdotool")) tools.push("xdotool");
+ if (canUseYdotool) tools.push("ydotool");
+ } else if (isWlroots) {
+ if (canUseWtype && this.commandExists("wtype")) tools.push("wtype");
+ if (canUseXdotool && this.commandExists("xdotool")) tools.push("xdotool");
+ if (canUseYdotool) tools.push("ydotool");
+ } else {
+ if (canUseXdotool && this.commandExists("xdotool")) tools.push("xdotool");
+ if (canUseYdotool) tools.push("ydotool");
+ if (canUseWtype && this.commandExists("wtype")) tools.push("wtype");
}
- const available = tools.length > 0;
+ const hasUinput = this._canAccessUinput();
+ const nativeBinaryUsable = hasNativeBinary && (!isWayland || hasUinput || xwaylandAvailable);
+ const available = nativeBinaryUsable || tools.length > 0;
let recommendedInstall;
- if (!available) {
+ if (!nativeBinaryUsable && tools.length === 0) {
if (!isWayland) {
recommendedInstall = "xdotool";
- } else if (isGnome) {
- recommendedInstall = xwaylandAvailable ? "xdotool" : undefined;
+ } else if (isWlroots) {
+ recommendedInstall = "wtype";
} else {
- recommendedInstall = xwaylandAvailable ? "xdotool" : "wtype or xdotool";
+ recommendedInstall = "xdotool";
}
+ } else if (isWayland && hasNativeBinary && !hasUinput && tools.length === 0) {
+ recommendedInstall = "usermod -aG input $USER";
}
return {
platform: "linux",
available,
- method: available ? tools[0] : null,
+ method: nativeBinaryUsable
+ ? isWayland && hasUinput
+ ? "uinput"
+ : "xtest"
+ : available
+ ? tools[0]
+ : null,
requiresPermission: false,
isWayland,
xwaylandAvailable,
+ hasNativeBinary,
+ hasUinput,
tools,
recommendedInstall,
};
diff --git a/src/types/electron.ts b/src/types/electron.ts
index d566baa2b..7008b4c6f 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -162,6 +162,8 @@ export interface PasteToolsResult {
requiresPermission: boolean;
isWayland?: boolean;
xwaylandAvailable?: boolean;
+ hasNativeBinary?: boolean;
+ hasUinput?: boolean;
tools?: string[];
recommendedInstall?: string;
}