Skip to content

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

fix(wayland): auto paste not working on non-QWERTY layouts. (#1525)

Idris Gadi13ae95e62dce
diff --git a/CLAUDE.md b/CLAUDE.md
index 29c729e8b..5417fb360 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -57,7 +57,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: Native XTest binary + compositor-aware fallbacks (xdotool, wtype, ydotool)
+ - Linux: compositor-aware Wayland paste (Hyprland sendshortcut, wlroots wtype, GNOME/KDE portal keysyms) with native uinput/XTest and system-tool fallbacks
- **database.js**: SQLite operations for transcription history
- **debugLogger.js**: Debug logging system with file output
- **devServerManager.js**: Vite dev server integration
@@ -741,8 +741,10 @@ const { t } = useTranslation();
- macOS: Check accessibility permissions (required for AppleScript paste)
- 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
+ - Hyprland Wayland: wtype → sendshortcut → uinput/ydotool
+ - Sway/wlroots Wayland: wtype → uinput/ydotool
+ - GNOME/KDE Wayland: portal keysyms → uinput/ydotool
+ - Physical Wayland fallbacks use Shift+Insert to avoid layout-sensitive KEY_V
- Windows: PowerShell SendKeys (built-in) or nircmd.exe (bundled)
4. **Build Issues**:
@@ -818,8 +820,10 @@ const { t } = useTranslation();
- "Start minimized" is handled app-side by the `startMinimized` setting, not by the desktop entry
- **Clipboard paste tools** (at least one required for auto-paste):
- **X11**: `xdotool` (recommended)
- - **Wayland** (non-GNOME): `wtype` (requires virtual keyboard protocol) or `xdotool` (works via XWayland, recommended for Electron apps)
- - **GNOME Wayland**: `xdotool` for XWayland apps only (native Wayland apps require manual paste)
+ - **Hyprland Wayland**: `wtype`, then `hyprctl` sendshortcut (avoids the sendshortcut stuck-modifier bug when wtype is installed)
+ - **Sway/wlroots Wayland**: `wtype` (requires the virtual keyboard protocol)
+ - **GNOME/KDE Wayland**: RemoteDesktop portal keysyms, then uinput/ydotool
+ - **Wayland physical fallback**: Shift+Insert avoids layout-sensitive KEY_V; `ydotool` requires the `ydotoold` daemon
- Terminal detection: Auto-detects terminal emulators and uses Ctrl+Shift+V
- Fallback: Text copied to clipboard with manual paste instructions
- **GNOME Wayland global hotkeys**:
diff --git a/TROUBLESHOOTING.md b/TROUBLESHOOTING.md
index b45e8eb90..7ddc71952 100644
--- a/TROUBLESHOOTING.md
+++ b/TROUBLESHOOTING.md
@@ -116,11 +116,17 @@
- 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 (`xdotool` recommended, or `wtype` for Sway/Hyprland, or `ydotool` with daemon)
+2. OpenWhispr chooses a compositor-specific paste method:
+ - Hyprland: `wtype`, then `hyprctl dispatch sendshortcut`
+ - Sway and other wlroots compositors: `wtype`
+ - GNOME and KDE Plasma: the RemoteDesktop keyboard portal
+ - `ydotool` is a fallback and requires the `ydotoold` daemon
3. Restart OpenWhispr after installing
OpenWhispr tries clipboard methods in order: `wl-copy` (most reliable) → renderer `navigator.clipboard` → X11 fallback.
+On GNOME and KDE, the first automatic paste can show a remote-interaction permission dialog. Approval is remembered in `~/.cache/openwhispr/portal-paste-token`; revoking permission or invalidating that token makes the prompt return. If automatic paste fails, the transcription remains in the clipboard for manual paste.
+
### Linux System Audio PipeWire Issues
**Symptoms:** Meeting transcription captures the microphone but not other participants, browser audio, or other system audio.
diff --git a/resources/linux-fast-paste.c b/resources/linux-fast-paste.c
index c30c13803..1d317f026 100644
--- a/resources/linux-fast-paste.c
+++ b/resources/linux-fast-paste.c
@@ -45,14 +45,6 @@ typedef enum {
* defeats the 10s watchdog below — so bound every call instead of using the
* default (25s) D-Bus timeout. */
#define PORTAL_CALL_TIMEOUT_MS 3000
-
-/* evdev keycodes for portal mode */
-#define PORTAL_KEY_LEFTCTRL 29
-#define PORTAL_KEY_LEFTSHIFT 42
-#define PORTAL_KEY_C 46
-#define PORTAL_KEY_V 47
-#define PORTAL_KEY_INSERT 110
-
static int portal_exit_code = 0;
typedef struct {
@@ -84,54 +76,62 @@ static guint subscribe_response(PortalData *app, const char *request_path,
callback, app, NULL);
}
-static void portal_emit_key(PortalData *app, gint32 keycode, guint32 pressed,
- const char *label)
+static int portal_emit_keysym(PortalData *app, gint32 keysym, guint32 pressed,
+ const char *label)
{
GError *err = NULL;
GVariant *opts = g_variant_new("a{sv}", NULL);
- g_dbus_connection_call_sync(app->conn, PORTAL_BUS, PORTAL_PATH,
- PORTAL_IFACE, "NotifyKeyboardKeycode",
- g_variant_new("(o@a{sv}iu)", app->session_handle, opts, keycode, pressed),
+ GVariant *result = g_dbus_connection_call_sync(app->conn, PORTAL_BUS, PORTAL_PATH,
+ PORTAL_IFACE, "NotifyKeyboardKeysym",
+ g_variant_new("(o@a{sv}iu)", app->session_handle, opts, keysym, pressed),
NULL, G_DBUS_CALL_FLAGS_NONE, PORTAL_CALL_TIMEOUT_MS, NULL, &err);
- if (err) { fprintf(stderr, "%s: %s\n", label, err->message); g_clear_error(&err); }
+ if (err) {
+ fprintf(stderr, "%s: %s\n", label, err->message);
+ g_clear_error(&err);
+ return 0;
+ }
+ if (result) g_variant_unref(result);
+ return 1;
}
static void portal_send_paste(PortalData *app)
{
+ int ok = 1;
if (app->copy_mode) {
const int use_shift = (app->mode == PASTE_MODE_CTRL_SHIFT_V);
- portal_emit_key(app, PORTAL_KEY_LEFTCTRL, 1, "Ctrl press");
+ ok &= portal_emit_keysym(app, XK_Control_L, 1, "Ctrl press");
if (use_shift)
- portal_emit_key(app, PORTAL_KEY_LEFTSHIFT, 1, "Shift press");
- portal_emit_key(app, PORTAL_KEY_C, 1, "C press");
+ ok &= portal_emit_keysym(app, XK_Shift_L, 1, "Shift press");
+ ok &= portal_emit_keysym(app, XK_c, 1, "C press");
usleep(20000);
- portal_emit_key(app, PORTAL_KEY_C, 0, "C release");
+ ok &= portal_emit_keysym(app, XK_c, 0, "C release");
if (use_shift)
- portal_emit_key(app, PORTAL_KEY_LEFTSHIFT, 0, "Shift release");
- portal_emit_key(app, PORTAL_KEY_LEFTCTRL, 0, "Ctrl release");
+ ok &= portal_emit_keysym(app, XK_Shift_L, 0, "Shift release");
+ ok &= portal_emit_keysym(app, XK_Control_L, 0, "Ctrl release");
} else if (app->mode == PASTE_MODE_SHIFT_INSERT) {
- portal_emit_key(app, PORTAL_KEY_LEFTSHIFT, 1, "Shift press");
+ ok &= portal_emit_keysym(app, XK_Shift_L, 1, "Shift press");
/* let the compositor register the modifier before the key arrives */
usleep(20000);
- portal_emit_key(app, PORTAL_KEY_INSERT, 1, "Insert press");
+ ok &= portal_emit_keysym(app, XK_Insert, 1, "Insert press");
usleep(20000);
- portal_emit_key(app, PORTAL_KEY_INSERT, 0, "Insert release");
- portal_emit_key(app, PORTAL_KEY_LEFTSHIFT, 0, "Shift release");
+ ok &= portal_emit_keysym(app, XK_Insert, 0, "Insert release");
+ ok &= portal_emit_keysym(app, XK_Shift_L, 0, "Shift release");
} else {
const int use_shift = (app->mode == PASTE_MODE_CTRL_SHIFT_V);
- portal_emit_key(app, PORTAL_KEY_LEFTCTRL, 1, "Ctrl press");
+ ok &= portal_emit_keysym(app, XK_Control_L, 1, "Ctrl press");
if (use_shift)
- portal_emit_key(app, PORTAL_KEY_LEFTSHIFT, 1, "Shift press");
+ ok &= portal_emit_keysym(app, XK_Shift_L, 1, "Shift press");
usleep(20000);
- portal_emit_key(app, PORTAL_KEY_V, 1, "V press");
+ ok &= portal_emit_keysym(app, XK_v, 1, "V press");
usleep(20000);
- portal_emit_key(app, PORTAL_KEY_V, 0, "V release");
+ ok &= portal_emit_keysym(app, XK_v, 0, "V release");
if (use_shift)
- portal_emit_key(app, PORTAL_KEY_LEFTSHIFT, 0, "Shift release");
- portal_emit_key(app, PORTAL_KEY_LEFTCTRL, 0, "Ctrl release");
+ ok &= portal_emit_keysym(app, XK_Shift_L, 0, "Shift release");
+ ok &= portal_emit_keysym(app, XK_Control_L, 0, "Ctrl release");
}
+ if (!ok) portal_exit_code = 6;
g_main_loop_quit(app->loop);
}
@@ -824,6 +824,9 @@ int main(int argc, char *argv[]) {
if (capabilities_only) {
printf("paste-v1 selection-copy-v1 target-window-v1");
+#ifdef HAVE_GIO
+ printf(" portal-keysym-v1");
+#endif
#ifdef HAVE_ATSPI
printf(" atspi-selection-v1");
#endif
diff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsx
index c34d0cf7b..e1944960b 100644
--- a/src/components/SettingsPage.tsx
+++ b/src/components/SettingsPage.tsx
@@ -74,6 +74,7 @@ import { useLocalStorage } from "../hooks/useLocalStorage";
import { validateHotkeyForSlot } from "../utils/hotkeyValidation";
import { getPlatform, getCachedPlatform } from "../utils/platform";
import { formatHotkeyLabel } from "../utils/hotkeys";
+import { getLinuxPasteInstallCommands, needsLinuxPasteToolGuidance } from "../utils/linuxPasteTools";
import { ActivationModeSelector } from "./ui/ActivationModeSelector";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select";
import LinuxPttSetupInfo from "./ui/LinuxPttSetupInfo";
@@ -985,22 +986,23 @@ export default function SettingsPage({
}
};
- // ydotool status for Wayland paste diagnostics
+ // Wayland paste tool status for diagnostics.
const [ydotoolStatus, setYdotoolStatus] = useState<{
isLinux: boolean;
isWayland: boolean;
hasYdotool: boolean;
hasYdotoold: boolean;
+ hasWtype: boolean;
daemonRunning: boolean;
hasService: boolean;
hasUinput: boolean;
hasUdevRule: boolean;
hasGroup: boolean;
- allGood: boolean;
- isKde?: boolean;
- hasXclip?: boolean;
- hasXsel?: boolean;
- isNixOS?: boolean;
+ isKde: boolean;
+ isWlroots: boolean;
+ hasXclip: boolean;
+ hasXsel: boolean;
+ isNixOS: boolean;
} | null>(null);
const [ydotoolGuideKey, setYdotoolGuideKey] = useState<string | null>(null);
@@ -2949,7 +2951,7 @@ export default function SettingsPage({
})}
description={t("settingsPage.general.waylandPaste.description", {
defaultValue:
- "Auto-paste on Wayland requires ydotool. Check the status of each component below.",
+ "Auto-paste on Wayland uses ydotool or wtype. wtype is preferred on wlroots compositors.",
})}
/>
{(() => {
@@ -2959,10 +2961,29 @@ export default function SettingsPage({
);
}
const checks = [
+ {
+ key: "hasWtype",
+ label: "wtype",
+ ok: ydotoolStatus.hasWtype,
+ required: ydotoolStatus.isWlroots,
+ desc: t("settingsPage.general.waylandPaste.wtypeDesc"),
+ steps: [
+ {
+ title: t("settingsPage.general.waylandPaste.guide.wtype.step1Title"),
+ desc: t("settingsPage.general.waylandPaste.guide.wtype.step1Desc"),
+ cmds: getLinuxPasteInstallCommands(t, "wtype"),
+ },
+ {
+ title: t("settingsPage.general.waylandPaste.guide.wtype.step2Title"),
+ cmds: [{ cmd: "which wtype" }],
+ },
+ ],
+ },
{
key: "hasYdotool",
label: "ydotool",
ok: ydotoolStatus.hasYdotool,
+ required: !ydotoolStatus.isWlroots,
desc: t("settingsPage.general.waylandPaste.ydotoolDesc", {
defaultValue: "Input automation tool for Wayland",
}),
@@ -2975,12 +2996,7 @@ export default function SettingsPage({
defaultValue:
"Use your distribution's package manager to install ydotool.",
}),
- cmds: [
- { label: "Ubuntu / Pop!_OS / Debian", cmd: "sudo apt install ydotool" },
- { label: "Fedora", cmd: "sudo dnf install ydotool" },
- { label: "Arch Linux", cmd: "sudo pacman -S ydotool" },
- { label: "openSUSE", cmd: "sudo zypper install ydotool" },
- ],
+ cmds: getLinuxPasteInstallCommands(t, "ydotool"),
},
{
title: t("settingsPage.general.waylandPaste.guide.ydotool.step2Title", {
@@ -2997,6 +3013,7 @@ export default function SettingsPage({
key: "hasYdotoold",
label: "ydotoold",
ok: ydotoolStatus.hasYdotoold,
+ required: !ydotoolStatus.isWlroots,
desc: t("settingsPage.general.waylandPaste.ydotooldDesc", {
defaultValue: "Daemon for ydotool (separate package on Ubuntu/Pop!_OS)",
}),
@@ -3024,6 +3041,7 @@ export default function SettingsPage({
key: "hasUinput",
label: "/dev/uinput",
ok: ydotoolStatus.hasUinput,
+ required: !ydotoolStatus.isWlroots,
desc: t("settingsPage.general.waylandPaste.uinputDesc", {
defaultValue: "Kernel input device access",
}),
@@ -3123,6 +3141,7 @@ export default function SettingsPage({
defaultValue: "input group",
}),
ok: ydotoolStatus.hasGroup,
+ required: !ydotoolStatus.isWlroots,
desc: t("settingsPage.general.waylandPaste.inputGroupDesc", {
defaultValue: "User must be in the input group (requires re-login)",
}),
@@ -3150,6 +3169,7 @@ export default function SettingsPage({
defaultValue: "systemd service",
}),
ok: ydotoolStatus.hasService,
+ required: !ydotoolStatus.isWlroots,
desc: t("settingsPage.general.waylandPaste.serviceDesc", {
defaultValue: "User service file for auto-starting ydotoold",
}),
@@ -3205,6 +3225,7 @@ EOF`,
defaultValue: "ydotoold daemon",
}),
ok: ydotoolStatus.daemonRunning,
+ required: !ydotoolStatus.isWlroots,
desc: t("settingsPage.general.waylandPaste.daemonDesc", {
defaultValue: "Background service must be running",
}),
@@ -3247,6 +3268,7 @@ EOF`,
key: "hasXclip",
label: "xclip",
ok: ydotoolStatus.hasXclip || ydotoolStatus.hasXsel || false,
+ required: true,
desc: t("settingsPage.general.waylandPaste.xclipDesc", {
defaultValue: "Clipboard tool for KDE Wayland paste (xclip or xsel)",
}),
@@ -3264,7 +3286,7 @@ EOF`,
});
}
- const allOk = checks.every((c) => c.ok);
+ const allOk = checks.filter((c) => c.required).every((c) => c.ok);
const activeGuide = checks.find((c) => c.key === ydotoolGuideKey);
return (
@@ -3897,7 +3919,7 @@ EOF`,
{platform === "linux" &&
permissionsHook.pasteToolsInfo &&
- !permissionsHook.pasteToolsInfo.available && (
+ needsLinuxPasteToolGuidance(permissionsHook.pasteToolsInfo) && (
<PasteToolsInfo
pasteToolsInfo={permissionsHook.pasteToolsInfo}
isChecking={permissionsHook.isCheckingPasteTools}
diff --git a/src/components/ui/NixOsPasteInfo.tsx b/src/components/ui/NixOsPasteInfo.tsx
index 14d62a3b3..9e8e6185f 100644
--- a/src/components/ui/NixOsPasteInfo.tsx
+++ b/src/components/ui/NixOsPasteInfo.tsx
@@ -4,6 +4,7 @@ import { Copy, CircleCheck, CircleX, RotateCw } from "lucide-react";
interface NixOsPasteInfoProps {
status: {
hasYdotool: boolean;
+ hasWtype: boolean;
hasUinput: boolean;
daemonRunning: boolean;
};
@@ -75,6 +76,7 @@ export default function NixOsPasteInfo({ status, onRecheck }: NixOsPasteInfoProp
})}
:
</span>
+ <StatusPill ok={status.hasWtype} label="wtype" />
<StatusPill ok={status.hasYdotool} label="ydotool" />
<StatusPill ok={status.hasUinput} label="/dev/uinput" />
<StatusPill ok={status.daemonRunning} label="ydotoold" />
diff --git a/src/components/ui/PasteToolsInfo.tsx b/src/components/ui/PasteToolsInfo.tsx
index 6e8c11283..41ccc6253 100644
--- a/src/components/ui/PasteToolsInfo.tsx
+++ b/src/components/ui/PasteToolsInfo.tsx
@@ -3,6 +3,7 @@ import { Check, Terminal, Info } from "lucide-react";
import { Button } from "./button";
import { InfoBox } from "./InfoBox";
import type { PasteToolsResult } from "../../types/electron";
+import { getLinuxPasteInstallCommands, needsLinuxPasteToolGuidance } from "../../utils/linuxPasteTools";
interface PasteToolsInfoProps {
pasteToolsInfo: PasteToolsResult | null;
@@ -59,8 +60,7 @@ export default function PasteToolsInfo({
);
}
- // Linux with tools available
- if (pasteToolsInfo.platform === "linux" && pasteToolsInfo.available) {
+ if (pasteToolsInfo.platform === "linux" && !needsLinuxPasteToolGuidance(pasteToolsInfo)) {
const method = pasteToolsInfo.method || "xdotool";
const methodLabel = method === "xtest" ? "built-in (XTest)" : method;
const methodSuffix =
@@ -91,11 +91,17 @@ export default function PasteToolsInfo({
);
}
- // Linux without tools - show helpful install instructions
- if (pasteToolsInfo.platform === "linux" && !pasteToolsInfo.available) {
+ if (needsLinuxPasteToolGuidance(pasteToolsInfo)) {
const isWayland = pasteToolsInfo.isWayland;
- const recommendedTool = pasteToolsInfo.recommendedInstall;
- const showInstall = !!recommendedTool;
+ const needsWtype = pasteToolsInfo.isWlroots && !pasteToolsInfo.hasWtype;
+ const recommendedTool = needsWtype
+ ? "wtype"
+ : pasteToolsInfo.recommendedInstall === "wtype"
+ ? "wtype"
+ : pasteToolsInfo.recommendedInstall === "xdotool"
+ ? "xdotool"
+ : null;
+ const showInstall = recommendedTool !== null;
return (
<InfoBox variant="warning" className="space-y-3">
@@ -111,42 +117,23 @@ export default function PasteToolsInfo({
{showInstall ? (
<>
<p className="text-sm text-warning dark:text-warning mt-1">
- {t("pasteToolsInfo.installPrefix")}{" "}
- <code className="bg-warning/20 px-1 rounded font-mono">{recommendedTool}</code>:
- </p>
-
- <div className="mt-3 bg-card border border-border p-3 rounded-md font-mono text-xs overflow-x-auto">
- {recommendedTool === "wtype" ? (
- <>
- <div className="text-muted-foreground">
- {t("pasteToolsInfo.installCommands.fedoraRhel")}
- </div>
- <div className="text-foreground">sudo dnf install wtype</div>
- <div className="text-muted-foreground mt-2">
- {t("pasteToolsInfo.installCommands.debianUbuntu")}
- </div>
- <div className="text-foreground">sudo apt install wtype</div>
- <div className="text-muted-foreground mt-2">
- {t("pasteToolsInfo.installCommands.archLinux")}
- </div>
- <div className="text-foreground">sudo pacman -S wtype</div>
- </>
+ {needsWtype ? (
+ t("pasteToolsInfo.wtypeFallbackDescription")
) : (
<>
- <div className="text-muted-foreground">
- {t("pasteToolsInfo.installCommands.debianUbuntuMint")}
- </div>
- <div className="text-foreground">sudo apt install xdotool</div>
- <div className="text-muted-foreground mt-2">
- {t("pasteToolsInfo.installCommands.fedoraRhel")}
- </div>
- <div className="text-foreground">sudo dnf install xdotool</div>
- <div className="text-muted-foreground mt-2">
- {t("pasteToolsInfo.installCommands.archLinux")}
- </div>
- <div className="text-foreground">sudo pacman -S xdotool</div>
+ {t("pasteToolsInfo.installPrefix")} {" "}
+ <code className="bg-warning/20 px-1 rounded font-mono">{recommendedTool}</code>:
</>
)}
+ </p>
+
+ <div className="mt-3 space-y-2 bg-card border border-border p-3 rounded-md font-mono text-xs overflow-x-auto">
+ {getLinuxPasteInstallCommands(t, recommendedTool).map(({ label, cmd }) => (
+ <div key={cmd}>
+ <div className="text-muted-foreground">{label}</div>
+ <div className="text-foreground">{cmd}</div>
+ </div>
+ ))}
</div>
{isWayland && recommendedTool === "wtype" && (
diff --git a/src/components/ui/PermissionsSection.tsx b/src/components/ui/PermissionsSection.tsx
index c9d9e84fd..f31664f01 100644
--- a/src/components/ui/PermissionsSection.tsx
+++ b/src/components/ui/PermissionsSection.tsx
@@ -3,6 +3,7 @@ import { Mic, Shield, Monitor } from "lucide-react";
import PermissionCard from "./PermissionCard";
import MicPermissionWarning from "./MicPermissionWarning";
import PasteToolsInfo from "./PasteToolsInfo";
+import { needsLinuxPasteToolGuidance } from "../../utils/linuxPasteTools";
import type { UsePermissionsReturn } from "../../hooks/usePermissions";
import type { SystemAudioAccessResult } from "../../types/electron";
import { canManageSystemAudioInApp } from "../../utils/systemAudioAccess";
@@ -82,7 +83,7 @@ export default function PermissionsSection({
{platform === "linux" &&
permissions.pasteToolsInfo &&
- !permissions.pasteToolsInfo.available && (
+ needsLinuxPasteToolGuidance(permissions.pasteToolsInfo) && (
<PasteToolsInfo
pasteToolsInfo={permissions.pasteToolsInfo}
isChecking={permissions.isCheckingPasteTools}
diff --git a/src/helpers/clipboard.js b/src/helpers/clipboard.js
index 047911be9..4122293c7 100644
--- a/src/helpers/clipboard.js
+++ b/src/helpers/clipboard.js
@@ -5,6 +5,7 @@ const path = require("path");
const fs = require("fs");
const os = require("os");
const debugLogger = require("./debugLogger");
+const { getLinuxSessionInfo } = require("./linuxSession");
const CACHE_TTL_MS = 30000;
@@ -12,39 +13,6 @@ const CACHE_TTL_MS = 30000;
// only exists to debounce the dialog shown on denial.
const ACCESSIBILITY_CHECK_TTL_MS = 5000;
-const getLinuxDesktopEnv = () =>
- [process.env.XDG_CURRENT_DESKTOP, process.env.XDG_SESSION_DESKTOP, process.env.DESKTOP_SESSION]
- .filter(Boolean)
- .join(":")
- .toLowerCase();
-
-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" ||
- !!process.env.WAYLAND_DISPLAY;
- const xwaylandAvailable = isWayland && !!process.env.DISPLAY;
- const desktopEnv = getLinuxDesktopEnv();
- const isGnome = isWayland && isGnomeDesktop(desktopEnv);
- const isKde = isWayland && isKdeDesktop(desktopEnv);
- const isWlroots = isWayland && isWlrootsCompositor(desktopEnv);
- const isHyprland = isWayland && !!process.env.HYPRLAND_INSTANCE_SIGNATURE;
-
- return { isWayland, xwaylandAvailable, desktopEnv, isGnome, isKde, isWlroots, isHyprland };
-};
-
const PASTE_DELAYS = {
darwin: 120,
win32_fast: 10,
@@ -117,6 +85,10 @@ class ClipboardManager {
this.linuxFastPastePath = null;
this.linuxFastPasteChecked = false;
this.portalDenied = false;
+ this.portalUnavailable = false;
+ this.portalTokenPasteFailed = false;
+ this.portalKeysymChecked = false;
+ this.portalKeysymAvailable = false;
this.portalFailed = false;
this.uinputTimedOut = false;
this.xtestTimedOut = false;
@@ -568,23 +540,19 @@ class ClipboardManager {
proc.on("close", (code) => {
if (timedOut) return reject(new Error("linux-fast-paste --portal timed out"));
clearTimeout(timeoutId);
+ const newToken = stdout.trim();
+ if (newToken) {
+ this._savePortalToken(newToken);
+ }
if (code === 0) {
- const newToken = stdout.trim();
- if (newToken) {
- this._savePortalToken(newToken);
- }
- // Exit 0 without token: dialog was dismissed without approving (e.g. clicked outside).
- // Reject with a recognizable message so the caller can retry.
- if (!restoreToken && !newToken) {
- reject(new Error("portal-dismissed"));
- return;
- }
resolve(newToken || null);
} else if (code === 3) {
// User explicitly clicked "Deny" in the portal dialog.
reject(new Error("portal-denied"));
} else if (code === 5) {
reject(new Error("portal support not compiled in"));
+ } else if (code === 6) {
+ reject(new Error("portal symbolic keyboard input unavailable"));
} else {
reject(
new Error(
@@ -712,6 +680,50 @@ class ClipboardManager {
}
}
+ _runLinuxPasteCommand(command, args, label, { expectedOutput } = {}) {
+ return new Promise((resolve, reject) => {
+ debugLogger.debug("Attempting Linux paste command", { command, args, label }, "clipboard");
+ const proc = spawn(command, args);
+ let stdout = "";
+ let stderr = "";
+ let timedOut = false;
+
+ proc.stdout?.on("data", (data) => {
+ stdout += data.toString();
+ });
+
+ proc.stderr?.on("data", (data) => {
+ stderr += data.toString();
+ });
+
+ const timeoutId = setTimeout(() => {
+ timedOut = true;
+ killProcess(proc, "SIGKILL");
+ reject(new Error(`${label} timed out`));
+ }, 2000);
+
+ proc.on("close", (code) => {
+ if (timedOut) return;
+ clearTimeout(timeoutId);
+ const output = stdout.trim();
+ if (code === 0 && (expectedOutput === undefined || output === expectedOutput)) {
+ resolve();
+ } else {
+ const errorOutput = stderr.trim() || output;
+ reject(
+ new Error(`${label} exited with code ${code}${errorOutput ? `: ${errorOutput}` : ""}`)
+ );
+ }
+ });
+
+ proc.on("error", (error) => {
+ if (timedOut) return;
+ clearTimeout(timeoutId);
+ reject(error);
+ });
+ });
+ }
+
_saveClipboard() {
const formats = clipboard.availableFormats();
const data = {};
@@ -1532,6 +1544,18 @@ class ClipboardManager {
// Shift+Insert on any desktop environment, even when their class is detected.
const useShiftInsert =
detectedIsKonsole || detectedIsElectron || (isWayland && windowSignals.length === 0);
+ const isTerminalTarget =
+ windowSignals.length > 0 && LINUX_TERMINAL_CLASSES.some((term) => signalsMatch(term));
+ const hyprlandShortcut = useShiftInsert
+ ? { modifiers: "SHIFT", key: "Insert" }
+ : isTerminalTarget
+ ? { modifiers: "CTRL SHIFT", key: "V" }
+ : { modifiers: "CTRL", key: "V" };
+ const wtypeArgs = useShiftInsert
+ ? ["-M", "shift", "-k", "Insert", "-m", "shift"]
+ : isTerminalTarget
+ ? ["-M", "ctrl", "-M", "shift", "-k", "v", "-m", "shift", "-m", "ctrl"]
+ : ["-M", "ctrl", "-k", "v", "-m", "ctrl"];
// Konsole on X11 silently drops simulated Ctrl+Shift+V via XTest (a long-standing
// focus/grab quirk), and the native fast-paste binary uses XTest. Route Konsole+X11
@@ -1539,77 +1563,86 @@ class ClipboardManager {
// windowactivate --sync and reliably reaches the target window.
const skipFastPasteForKonsole = detectedIsKonsole && !isWayland;
- if (linuxFastPaste && !skipFastPasteForKonsole) {
- const earlyIsTerminal =
- windowSignals.length > 0
- ? LINUX_TERMINAL_CLASSES.some((term) => signalsMatch(term))
- : false;
- const appendModeFlag = (args) => {
- if (useShiftInsert) args.push("--shift-insert");
- else if (earlyIsTerminal) args.push("--terminal");
- };
+ const appendModeFlag = (args) => {
+ if (useShiftInsert) args.push("--shift-insert");
+ else if (isTerminalTarget) args.push("--terminal");
+ };
- const spawnFastPaste = (args, label) =>
- new Promise((resolve, reject) => {
+ if (isWayland && isWlroots && wtypeExists) {
+ try {
+ await this._runLinuxPasteCommand("wtype", wtypeArgs, "wtype");
+ this.safeLog("✅ Paste successful using wtype");
+ return { method: "wtype", restoreComplete: restoreClipboard() };
+ } catch (error) {
+ debugLogger.warn(
+ "wtype paste failed, falling back",
+ { error: error?.message },
+ "clipboard"
+ );
+ }
+ }
+
+ // sendshortcut resolves keys through the compositor's keymap, so it is
+ // layout-independent — but it has a known stuck-modifier bug (synthetic
+ // modifiers stay latched in XKB: hyprwm/Hyprland#14099, unresolved as of
+ // 0.56). wtype above is equally layout-independent and unaffected, so
+ // sendshortcut is only the zero-dependency fallback. The explicit
+ // "activewindow" target is the community-reported mitigation for #14099.
+ if (isWayland && isHyprland && this.commandExists("hyprctl")) {
+ const currentDispatcher = `hl.dsp.send_shortcut({ mods = "${hyprlandShortcut.modifiers}", key = "${hyprlandShortcut.key}", window = "activewindow" })`;
+ const legacyDispatcher = `${hyprlandShortcut.modifiers}, ${hyprlandShortcut.key}, activewindow`;
+ const dispatchers = [
+ { args: ["dispatch", currentDispatcher], label: "hyprctl send_shortcut" },
+ {
+ args: ["dispatch", "sendshortcut", legacyDispatcher],
+ label: "hyprctl legacy sendshortcut",
+ },
+ ];
+ let lastDispatcherError;
+
+ for (const dispatcher of dispatchers) {
+ try {
+ await this._runLinuxPasteCommand("hyprctl", dispatcher.args, dispatcher.label, {
+ expectedOutput: "ok",
+ });
+ this.safeLog("✅ Paste shortcut dispatched by Hyprland", {
+ dispatcher: dispatcher.label,
+ shortcut: dispatcher.args.at(-1),
+ });
+ return { method: "hyprland-sendshortcut", restoreComplete: restoreClipboard() };
+ } catch (error) {
+ lastDispatcherError = error;
debugLogger.debug(
- `Attempting native linux-fast-paste (${label})`,
- {
- linuxFastPaste,
- args,
- targetWindowId,
- detectedWindowClass,
- detectedWindowComm,
- earlyIsTerminal,
- },
+ "Hyprland dispatcher failed",
+ { dispatcher: dispatcher.label, error: error?.message },
"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()}` : ""}`
- )
- );
- }
- });
+ debugLogger.warn(
+ "Hyprland symbolic paste failed, falling back",
+ { error: lastDispatcherError?.message },
+ "clipboard"
+ );
+ }
- proc.on("error", (error) => {
- if (timedOut) return;
- clearTimeout(timeoutId);
- reject(error);
- });
- });
+ if (linuxFastPaste && !skipFastPasteForKonsole) {
+ const spawnFastPaste = (args, label) =>
+ this._runLinuxPasteCommand(linuxFastPaste, args, `linux-fast-paste ${label}`);
if (isWayland) {
const tryUinputPaste = async () => {
if (this.uinputTimedOut) {
throw new Error("uinput timed out earlier this session, skipping");
}
- const args = ["--uinput"];
- appendModeFlag(args);
+ const args = ["--uinput", "--shift-insert"];
try {
await spawnFastPaste(args, "uinput");
} catch (error) {
// A timeout means uinput hangs in this environment (unlike a fast
// error, which can be transient) — don't re-pay 2s on every paste.
- if (error?.message === "linux-fast-paste timed out") {
+ if (error?.message?.endsWith(" timed out")) {
this.uinputTimedOut = true;
}
throw error;
@@ -1624,88 +1657,75 @@ class ClipboardManager {
};
const tryPortalPaste = async () => {
- const MAX_PORTAL_RETRIES = 3;
- for (let attempt = 0; attempt < MAX_PORTAL_RETRIES; attempt++) {
- try {
- const portalResult = await this._runPortalPaste(linuxFastPaste, {
- shiftInsert: useShiftInsert,
- terminal: earlyIsTerminal,
- });
- this.safeLog("✅ Paste successful using linux-fast-paste --portal (RemoteDesktop)");
- debugLogger.info(
- "Paste successful",
- { tool: "linux-fast-paste", method: "portal", token: !!portalResult },
- "clipboard"
- );
- return { restoreComplete: restoreClipboard() };
- } catch (portalError) {
- if (portalError?.message === "portal-dismissed") {
- debugLogger.warn(
- "Portal dialog dismissed without response, retrying",
- { attempt: attempt + 1, maxRetries: MAX_PORTAL_RETRIES },
- "clipboard"
- );
- continue;
- }
- if (portalError?.message === "portal-denied") {
- this.portalDenied = true;
- debugLogger.warn(
- "User denied portal access, skipping portal for this session",
- {},
- "clipboard"
- );
- } else {
- // Timeout or service error: the session stays broken until app
- // restart, so skip the portal from now on (#1614).
- this.portalFailed = true;
- debugLogger.warn(
- "linux-fast-paste --portal failed, skipping portal for this session",
- { error: portalError?.message },
- "clipboard"
- );
- }
- return false;
+ try {
+ await this._runPortalPaste(linuxFastPaste, {
+ shiftInsert: useShiftInsert,
+ terminal: isTerminalTarget,
+ });
+ this.safeLog("✅ Paste successful using linux-fast-paste --portal (RemoteDesktop)");
+ return { restoreComplete: restoreClipboard() };
+ } catch (portalError) {
+ if (portalError?.message === "portal-denied") {
+ this.portalDenied = true;
+ } else if (
+ portalError?.message === "portal support not compiled in" ||
+ portalError?.message === "portal symbolic keyboard input unavailable"
+ ) {
+ this.portalUnavailable = true;
+ } else {
+ // Timeout or service error: the session stays broken until app
+ // restart, so skip the portal from now on (#1614).
+ this.portalFailed = true;
}
+ debugLogger.warn(
+ "linux-fast-paste --portal failed, falling back",
+ { error: portalError?.message },
+ "clipboard"
+ );
+ return false;
}
- return false;
};
// KDE with XWayland: portal first because clipboard and input are both
- // on X11. uinput causes clipboard desync (X11 clipboard vs Wayland input).
- // GNOME: uinput first because the portal often times out or shows a
- // confusing permission dialog, causing a 10s+ delay (issue #494).
- if (isKde && linuxFastPaste && !this.portalDenied && !this.portalFailed) {
+ // on X11; uinput causes clipboard desync (X11 clipboard vs Wayland input).
+ if (isKde && !this.portalDenied && !this.portalUnavailable && !this.portalFailed) {
+ const portalPaste = await tryPortalPaste();
+ if (portalPaste) return { method: "portal", ...portalPaste };
+ }
+
+ // GNOME: only lead with the portal when a saved token lets it run
+ // silently — a tokenless portal can stall 10s+ on a permission dialog
+ // (issue #494), so first-time pastes try uinput and only fall back to
+ // the portal (and its dialog) when uinput is unavailable.
+ const shouldPreferGnomePortal =
+ isGnome &&
+ !this.portalDenied &&
+ !this.portalUnavailable &&
+ !this.portalFailed &&
+ !this.portalTokenPasteFailed &&
+ !!this._readPortalToken();
+ if (shouldPreferGnomePortal) {
+ const portalPaste = await tryPortalPaste();
+ if (portalPaste) return { method: "portal", ...portalPaste };
+ this.portalTokenPasteFailed = true;
+ }
+
+ try {
+ const uinputPaste = await tryUinputPaste();
+ return { method: "uinput", ...uinputPaste };
+ } catch (uinputError) {
+ debugLogger.warn("uinput paste failed", { error: uinputError?.message }, "clipboard");
+ }
+
+ if (
+ isGnome &&
+ !shouldPreferGnomePortal &&
+ !this.portalDenied &&
+ !this.portalUnavailable &&
+ !this.portalFailed
+ ) {
const portalPaste = await tryPortalPaste();
if (portalPaste) return { method: "portal", ...portalPaste };
- try {
- const uinputPaste = await tryUinputPaste();
- return { method: "uinput", ...uinputPaste };
- } catch (uinputError) {
- debugLogger.warn("uinput paste failed", { error: uinputError?.message }, "clipboard");
- }
- } else if (isGnome && linuxFastPaste) {
- try {
- const uinputPaste = await tryUinputPaste();
- return { method: "uinput", ...uinputPaste };
- } catch (uinputError) {
- debugLogger.warn(
- "uinput paste failed on GNOME, trying portal",
- { error: uinputError?.message },
- "clipboard"
- );
- }
- if (!this.portalDenied && !this.portalFailed) {
- const portalPaste = await tryPortalPaste();
- if (portalPaste) return { method: "portal", ...portalPaste };
- }
- } else {
- // Other compositors (wlroots, etc.): try uinput only
- try {
- const uinputPaste = await tryUinputPaste();
- return { method: "uinput", ...uinputPaste };
- } catch (uinputError) {
- debugLogger.warn("uinput paste failed", { error: uinputError?.message }, "clipboard");
- }
}
// XTest/XWayland fallback: works for XWayland apps on any Wayland compositor
@@ -1727,7 +1747,7 @@ class ClipboardManager {
restoreComplete: restoreClipboard(),
};
} catch (xtestError) {
- if (xtestError?.message === "linux-fast-paste timed out") {
+ if (xtestError?.message?.endsWith(" timed out")) {
this.xtestTimedOut = true;
}
debugLogger.warn(
@@ -1769,20 +1789,15 @@ class ClipboardManager {
}
}
- // Terminals use Ctrl+Shift+V instead of Ctrl+V
- const isTerminal = () => {
- if (windowSignals.length === 0) return false;
- const isTerminalWindow = LINUX_TERMINAL_CLASSES.some((term) => signalsMatch(term));
- if (isTerminalWindow) {
- this.safeLog(`🖥️ Terminal detected: ${windowSignals.join(" | ")}`);
- }
- return isTerminalWindow;
- };
-
- const inTerminal = isTerminal();
- const pasteKeys = useShiftInsert ? "shift+Insert" : inTerminal ? "ctrl+shift+v" : "ctrl+v";
+ if (isTerminalTarget) {
+ this.safeLog(`🖥️ Terminal detected: ${windowSignals.join(" | ")}`);
+ }
+ const pasteKeys = useShiftInsert
+ ? "shift+Insert"
+ : isTerminalTarget
+ ? "ctrl+shift+v"
+ : "ctrl+v";
- const canUseWtype = isWayland && isWlroots;
const canUseYdotool = ydotoolDaemonRunning;
const canUseXdotool = isWayland ? xwaylandAvailable && xdotoolExists : xdotoolExists;
@@ -1797,15 +1812,15 @@ class ClipboardManager {
);
}
- // ydotool 0.1.x (Ubuntu 24.04) uses key names; 1.0.x uses raw keycodes
- // 29 = KEY_LEFTCTRL, 42 = KEY_LEFTSHIFT, 47 = KEY_V, 110 = KEY_INSERT
+ // ydotool 0.1.x (Ubuntu 24.04) uses key names; 1.0.x uses raw keycodes.
+ // Wayland's physical fallback is always Shift+Insert to avoid KEY_V's layout-sensitive position.
const legacyYdotool = this._isYdotoolLegacy();
let ydotoolArgs;
- if (useShiftInsert) {
+ if (isWayland || useShiftInsert) {
ydotoolArgs = legacyYdotool
? ["key", "shift+Insert"]
: ["key", "42:1", "110:1", "110:0", "42:0"];
- } else if (inTerminal) {
+ } else if (isTerminalTarget) {
ydotoolArgs = legacyYdotool
? ["key", "ctrl+shift+v"]
: ["key", "29:1", "42:1", "47:1", "47:0", "42:0", "29:0"];
@@ -1813,30 +1828,18 @@ class ClipboardManager {
ydotoolArgs = legacyYdotool ? ["key", "ctrl+v"] : ["key", "29:1", "47:1", "47:0", "29:0"];
}
- let wtypeArgs;
- if (useShiftInsert) {
- wtypeArgs = ["-M", "shift", "-k", "Insert", "-m", "shift"];
- } else if (inTerminal) {
- wtypeArgs = ["-M", "ctrl", "-M", "shift", "-k", "v", "-m", "shift", "-m", "ctrl"];
- } else {
- wtypeArgs = ["-M", "ctrl", "-k", "v", "-m", "ctrl"];
- }
- const wtypeEntry = canUseWtype ? [{ cmd: "wtype", args: wtypeArgs }] : [];
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: ydotool (uinput) works for all windows; xdotool for XWayland only
- candidates = [...ydotoolEntry, ...xdotoolEntry, ...wtypeEntry];
- }
+ // Compositor-aware priority ordering. X11 and wlroots (where wtype already
+ // ran): xdotool first — native on X11, no daemon needed. GNOME, KDE, or
+ // unknown Wayland: ydotool (uinput) first because it reaches every window,
+ // while xdotool exits 0 even when the focused window is native Wayland and
+ // never receives the keystroke; its Wayland args are layout-safe Shift+Insert.
+ const candidates =
+ !isWayland || isWlroots
+ ? [...xdotoolEntry, ...ydotoolEntry]
+ : [...ydotoolEntry, ...xdotoolEntry];
const available = candidates.filter((c) => this.commandExists(c.cmd));
@@ -1848,7 +1851,7 @@ class ClipboardManager {
targetWindowId,
detectedWindowClass,
detectedWindowComm,
- inTerminal,
+ inTerminal: isTerminalTarget,
useShiftInsert,
pasteKeys,
},
@@ -1963,7 +1966,7 @@ class ClipboardManager {
debugLogger.error("All paste tools failed", { failedAttempts }, "clipboard");
// xdotool type fallback for terminals where Ctrl+Shift+V simulation fails
- if (inTerminal && xdotoolExists && !isWayland) {
+ if (isTerminalTarget && xdotoolExists && !isWayland) {
debugLogger.debug(
"Trying xdotool type fallback for terminal",
{
@@ -2220,12 +2223,28 @@ Would you like to open System Settings now?`;
};
}
- const { isWayland, xwaylandAvailable, isWlroots } = getLinuxSessionInfo();
+ const { isWayland, xwaylandAvailable, isGnome, isKde, isWlroots, isHyprland } =
+ getLinuxSessionInfo();
const linuxFastPaste = this.resolveLinuxFastPasteBinary();
const hasNativeBinary = !!linuxFastPaste;
+ let portalKeysymAvailable = false;
+ if (linuxFastPaste && isWayland && (isGnome || isKde)) {
+ // spawnSync blocks the main process, so probe the binary only once.
+ if (!this.portalKeysymChecked) {
+ this.portalKeysymChecked = true;
+ try {
+ const result = spawnSync(linuxFastPaste, ["--capabilities"], { timeout: 1000 });
+ this.portalKeysymAvailable =
+ result.status === 0 &&
+ result.stdout.toString().split(/\s+/).includes("portal-keysym-v1");
+ } catch {}
+ }
+ portalKeysymAvailable = this.portalKeysymAvailable;
+ }
const tools = [];
- const canUseWtype = isWayland && isWlroots;
+ const hasHyprlandShortcut = isWayland && isHyprland && this.commandExists("hyprctl");
+ const hasWtype = isWayland && isWlroots && this.commandExists("wtype");
const canUseYdotool = this.commandExists("ydotool") && this._isYdotoolDaemonRunning();
const canUseXdotool = !isWayland || xwaylandAvailable;
@@ -2233,13 +2252,14 @@ Would you like to open System Settings now?`;
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 (hasWtype) tools.push("wtype");
+ if (hasHyprlandShortcut) tools.push("hyprland-sendshortcut");
if (canUseXdotool && this.commandExists("xdotool")) tools.push("xdotool");
if (canUseYdotool) tools.push("ydotool");
} else {
+ if (portalKeysymAvailable) tools.push("portal");
if (canUseXdotool && this.commandExists("xdotool")) tools.push("xdotool");
if (canUseYdotool) tools.push("ydotool");
- if (canUseWtype && this.commandExists("wtype")) tools.push("wtype");
}
const hasUinput = this._canAccessUinput();
@@ -2254,25 +2274,34 @@ Would you like to open System Settings now?`;
} else {
recommendedInstall = "xdotool";
}
- } else if (isWayland && hasNativeBinary && !hasUinput && tools.length === 0) {
- recommendedInstall = "usermod -aG input $USER";
+ }
+
+ let method = null;
+ if (!isWayland) {
+ method = nativeBinaryUsable ? "xtest" : tools[0] || null;
+ } else if (hasWtype) {
+ method = "wtype";
+ } else if (hasHyprlandShortcut) {
+ method = "hyprland-sendshortcut";
+ } else if ((isGnome || isKde) && portalKeysymAvailable) {
+ method = "portal";
+ } else if (nativeBinaryUsable) {
+ method = "uinput";
+ } else {
+ method = tools[0] || null;
}
return {
platform: "linux",
available,
- method: nativeBinaryUsable
- ? isWayland && hasUinput
- ? "uinput"
- : "xtest"
- : available
- ? tools[0]
- : null,
- requiresPermission: false,
+ method,
+ requiresPermission: method === "portal",
isWayland,
xwaylandAvailable,
hasNativeBinary,
hasUinput,
+ hasWtype,
+ isWlroots,
tools,
recommendedInstall,
};
diff --git a/src/helpers/ensureYdotool.js b/src/helpers/ensureYdotool.js
index 039ed0821..447398b89 100644
--- a/src/helpers/ensureYdotool.js
+++ b/src/helpers/ensureYdotool.js
@@ -2,6 +2,7 @@ const fs = require("fs");
const os = require("os");
const { spawnSync } = require("child_process");
const { dialog } = require("electron");
+const { getLinuxSessionInfo } = require("./linuxSession");
function getLogger() {
return require("./debugLogger");
@@ -186,27 +187,28 @@ function isNixOS() {
function getYdotoolStatus() {
const hasYdotool = commandExists("ydotool");
const hasYdotoold = commandExists("ydotoold");
+ const hasWtype = commandExists("wtype");
const daemonRunning = isYdotooldRunning();
const hasService = serviceFileExists();
const hasUinput = isUinputAccessible();
const hasUdevRule = udevRuleExists();
const hasGroup = userInInputGroup();
- const isWayland =
- (process.env.XDG_SESSION_TYPE || "").toLowerCase() === "wayland" ||
- !!process.env.WAYLAND_DISPLAY;
+ const { isWayland, isKde, isWlroots } = getLinuxSessionInfo();
return {
isLinux: process.platform === "linux",
isWayland,
+ isKde,
+ isWlroots,
hasYdotool,
hasYdotoold,
+ hasWtype,
daemonRunning,
hasService,
hasUinput,
hasUdevRule,
hasGroup,
isNixOS: isNixOS(),
- allGood: hasYdotool && hasYdotoold && daemonRunning && hasUinput && hasGroup,
};
}
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index cd26a1958..eccfdd78e 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -8601,9 +8601,10 @@ class IPCHandlers {
ipcMain.handle("get-ydotool-status", () => {
const { getYdotoolStatus } = require("./ensureYdotool");
+ const { getLinuxSessionInfo } = require("./linuxSession");
const { execFileSync } = require("child_process");
const status = getYdotoolStatus();
- const isKde = (process.env.XDG_CURRENT_DESKTOP || "").toLowerCase().includes("kde");
+ const { isKde } = getLinuxSessionInfo();
let hasXclip = false;
let hasXsel = false;
if (isKde) {
@@ -8616,7 +8617,7 @@ class IPCHandlers {
hasXsel = true;
} catch {}
}
- return { ...status, isKde, hasXclip, hasXsel };
+ return { ...status, hasXclip, hasXsel };
});
ipcMain.handle("get-debug-state", async () => {
diff --git a/src/helpers/linuxSession.js b/src/helpers/linuxSession.js
new file mode 100644
index 000000000..85bda85e8
--- /dev/null
+++ b/src/helpers/linuxSession.js
@@ -0,0 +1,32 @@
+const WLROOTS_DESKTOPS = ["sway", "hyprland", "wayfire", "river", "dwl", "labwc", "cage"];
+
+function getLinuxSessionInfo() {
+ const isWayland =
+ (process.env.XDG_SESSION_TYPE || "").toLowerCase() === "wayland" ||
+ !!process.env.WAYLAND_DISPLAY;
+ const desktopEnv = [
+ process.env.XDG_CURRENT_DESKTOP,
+ process.env.XDG_SESSION_DESKTOP,
+ process.env.DESKTOP_SESSION,
+ ]
+ .filter(Boolean)
+ .join(":")
+ .toLowerCase();
+ const isWlroots =
+ isWayland &&
+ (WLROOTS_DESKTOPS.some((desktop) => desktopEnv.includes(desktop)) ||
+ !!process.env.SWAYSOCK ||
+ !!process.env.HYPRLAND_INSTANCE_SIGNATURE);
+
+ return {
+ isWayland,
+ xwaylandAvailable: isWayland && !!process.env.DISPLAY,
+ desktopEnv,
+ isGnome: isWayland && desktopEnv.includes("gnome"),
+ isKde: isWayland && desktopEnv.includes("kde"),
+ isWlroots,
+ isHyprland: isWayland && !!process.env.HYPRLAND_INSTANCE_SIGNATURE,
+ };
+}
+
+module.exports = { getLinuxSessionInfo };
diff --git a/src/helpers/selectionManager.js b/src/helpers/selectionManager.js
index 168bbaf44..d7c0e6dcd 100644
--- a/src/helpers/selectionManager.js
+++ b/src/helpers/selectionManager.js
@@ -371,6 +371,7 @@ class SelectionManager {
if (
this.clipboardManager._runPortalPaste &&
!this.clipboardManager.portalDenied &&
+ !this.clipboardManager.portalUnavailable &&
!this.clipboardManager.portalFailed
) {
try {
diff --git a/src/locales/de/translation.json b/src/locales/de/translation.json
index 3a82db7d2..2b8176713 100644
--- a/src/locales/de/translation.json
+++ b/src/locales/de/translation.json
@@ -1116,8 +1116,10 @@
"installCommands": {
"archLinux": "# Arch Linux",
"debianUbuntu": "# Debian / Ubuntu",
+ "debianUbuntuPop": "# Debian / Ubuntu / Pop!_OS",
"debianUbuntuMint": "# Debian / Ubuntu / Mint",
- "fedoraRhel": "# Fedora / RHEL"
+ "fedoraRhel": "# Fedora / RHEL",
+ "openSuse": "# openSUSE Tumbleweed / Leap"
},
"installPrefix": "Für automatisches Einfügen installieren Sie",
"methodReady": "für automatisches Einfügen",
@@ -1133,6 +1135,7 @@
"waylandClipboardTitle": "Zwischenablage-Modus unter Wayland",
"windowsReady": "Windows unterstützt automatisches Einfügen direkt. Keine Einrichtung erforderlich!",
"withoutToolPrefix": "Ohne dieses Tool kopiert OpenWhispr den Text in Ihre Zwischenablage. Sie können ihn dann manuell mit Ctrl+V einfügen.",
+ "wtypeFallbackDescription": "wtype ist die bevorzugte Methode für automatisches Einfügen auf diesem wlroots-Compositor. Eine Alternative ist verfügbar, kann aber weniger zuverlässig sein.",
"xwaylandAppsOnly": "Automatisches Einfügen funktioniert nur für XWayland-Apps"
},
"promptStudio": {
@@ -1911,6 +1914,7 @@
"recheck": "Erneut prüfen",
"copy": "Kopieren",
"ydotoolDesc": "Eingabeautomatisierung für Wayland",
+ "wtypeDesc": "Bevorzugte Eingabeautomatisierung für wlroots-Compositoren",
"ydotooldDesc": "Daemon für ydotool (separates Paket unter Ubuntu/Pop!_OS)",
"uinputDesc": "Zugriff auf das Kernel-Eingabegerät",
"uinputRuleFound": "Regel vorhanden, aber nicht aktiv. Ein Neustart sollte das beheben.",
@@ -1929,6 +1933,11 @@
"step2Title": "Installation überprüfen",
"step2Desc": "Prüfen Sie, ob ydotool in Ihrem PATH verfügbar ist."
},
+ "wtype": {
+ "step1Title": "wtype installieren",
+ "step1Desc": "wtype ist die primäre Methode für automatisches Einfügen unter Hyprland, Sway und anderen wlroots-Compositoren.",
+ "step2Title": "Installation überprüfen"
+ },
"ydotoold": {
"step1Title": "ydotoold installieren",
"step1Desc": "Unter Ubuntu und Pop!_OS ist ydotoold ein separates Paket. Unter Fedora ist es in ydotool enthalten."
diff --git a/src/locales/en/translation.json b/src/locales/en/translation.json
index db600a2a3..01169dbc6 100644
--- a/src/locales/en/translation.json
+++ b/src/locales/en/translation.json
@@ -1116,8 +1116,10 @@
"installCommands": {
"archLinux": "# Arch Linux",
"debianUbuntu": "# Debian / Ubuntu",
+ "debianUbuntuPop": "# Debian / Ubuntu / Pop!_OS",
"debianUbuntuMint": "# Debian / Ubuntu / Mint",
- "fedoraRhel": "# Fedora / RHEL"
+ "fedoraRhel": "# Fedora / RHEL",
+ "openSuse": "# openSUSE Tumbleweed / Leap"
},
"installPrefix": "For automatic text pasting, install",
"methodReady": "for automatic text pasting",
@@ -1133,6 +1135,7 @@
"waylandClipboardTitle": "Clipboard Mode on Wayland",
"windowsReady": "Windows supports automatic pasting out of the box. No setup required!",
"withoutToolPrefix": "Without this tool, OpenWhispr will copy text to your clipboard. You can then paste manually with Ctrl+V.",
+ "wtypeFallbackDescription": "wtype is the preferred auto-paste method for this wlroots compositor. A fallback is available, but may be less reliable.",
"xwaylandAppsOnly": "automatic pasting works for XWayland apps only"
},
"promptStudio": {
@@ -1906,11 +1909,12 @@
},
"waylandPaste": {
"title": "Wayland Paste Setup",
- "description": "Auto-paste on Wayland requires ydotool. Check the status of each component below.",
+ "description": "Auto-paste on Wayland uses ydotool or wtype. wtype is preferred on wlroots compositors.",
"allGoodDesc": "Auto-paste is ready to go.",
"recheck": "Re-check",
"copy": "Copy",
"ydotoolDesc": "Input automation tool for Wayland",
+ "wtypeDesc": "Preferred input automation tool on wlroots compositors",
"ydotooldDesc": "Daemon for ydotool (separate package on Ubuntu/Pop!_OS)",
"uinputDesc": "Kernel input device access",
"uinputRuleFound": "Rule present but not active. A reboot should fix it.",
@@ -1929,6 +1933,11 @@
"step2Title": "Verify installation",
"step2Desc": "Check that ydotool is available in your PATH."
},
+ "wtype": {
+ "step1Title": "Install wtype",
+ "step1Desc": "wtype is the primary auto-paste method on Hyprland, Sway, and other wlroots compositors.",
+ "step2Title": "Verify installation"
+ },
"ydotoold": {
"step1Title": "Install ydotoold",
"step1Desc": "On Ubuntu and Pop!_OS, ydotoold is a separate package. On Fedora, it's included with ydotool."
diff --git a/src/locales/es/translation.json b/src/locales/es/translation.json
index 53539b43c..4d943a96c 100644
--- a/src/locales/es/translation.json
+++ b/src/locales/es/translation.json
@@ -1076,8 +1076,10 @@
"installCommands": {
"archLinux": "# Arch Linux",
"debianUbuntu": "# Debian / Ubuntu",
+ "debianUbuntuPop": "# Debian / Ubuntu / Pop!_OS",
"debianUbuntuMint": "# Debian / Ubuntu / Mint",
- "fedoraRhel": "# Fedora / RHEL"
+ "fedoraRhel": "# Fedora / RHEL",
+ "openSuse": "# openSUSE Tumbleweed / Leap"
},
"installPrefix": "Para pegado automático de texto, instala",
"methodReady": "para pegado automático de texto",
@@ -1093,6 +1095,7 @@
"waylandClipboardTitle": "Modo portapapeles en Wayland",
"windowsReady": "Windows es compatible con el pegado automático de forma nativa. ¡No se requiere configuración!",
"withoutToolPrefix": "Sin esta herramienta, OpenWhispr copiará el texto al portapapeles. Luego puedes pegarlo manualmente con Ctrl+V.",
+ "wtypeFallbackDescription": "wtype es el método de pegado automático preferido para este compositor wlroots. Hay una alternativa disponible, pero puede ser menos fiable.",
"xwaylandAppsOnly": "el pegado automático funciona solo en apps XWayland"
},
"promptStudio": {
@@ -1676,6 +1679,7 @@
"recheck": "Volver a comprobar",
"copy": "Copiar",
"ydotoolDesc": "Herramienta de automatización de entrada para Wayland",
+ "wtypeDesc": "Herramienta de automatización de entrada preferida en compositores wlroots",
"ydotooldDesc": "Daemon de ydotool (paquete separado en Ubuntu/Pop!_OS)",
"uinputDesc": "Acceso al dispositivo de entrada del kernel",
"uinputRuleFound": "Regla presente pero no activa. Un reinicio debería solucionarlo.",
@@ -1694,6 +1698,11 @@
"step2Title": "Verificar la instalación",
"step2Desc": "Comprueba que ydotool esté disponible en tu PATH."
},
+ "wtype": {
+ "step1Title": "Instalar wtype",
+ "step1Desc": "wtype es el método principal de pegado automático en Hyprland, Sway y otros compositores wlroots.",
+ "step2Title": "Verificar la instalación"
+ },
"ydotoold": {
"step1Title": "Instalar ydotoold",
"step1Desc": "En Ubuntu y Pop!_OS, ydotoold es un paquete separado. En Fedora viene incluido con ydotool."
diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.json
index 1561106df..0b73a8dc8 100644
--- a/src/locales/fr/translation.json
+++ b/src/locales/fr/translation.json
@@ -1116,8 +1116,10 @@
"installCommands": {
"archLinux": "# Arch Linux",
"debianUbuntu": "# Debian / Ubuntu",
+ "debianUbuntuPop": "# Debian / Ubuntu / Pop!_OS",
"debianUbuntuMint": "# Debian / Ubuntu / Mint",
- "fedoraRhel": "# Fedora / RHEL"
+ "fedoraRhel": "# Fedora / RHEL",
+ "openSuse": "# openSUSE Tumbleweed / Leap"
},
"installPrefix": "Pour le collage automatique de texte, installez",
"methodReady": "pour le collage automatique de texte",
@@ -1133,6 +1135,7 @@
"waylandClipboardTitle": "Mode presse-papiers sur Wayland",
"windowsReady": "Windows prend en charge le collage automatique nativement. Aucune configuration requise !",
"withoutToolPrefix": "Sans cet outil, OpenWhispr copiera le texte dans le presse-papiers. Vous pourrez ensuite coller manuellement avec Ctrl+V.",
+ "wtypeFallbackDescription": "wtype est la méthode de collage automatique recommandée pour ce compositeur wlroots. Une solution de repli est disponible, mais elle peut être moins fiable.",
"xwaylandAppsOnly": "le collage automatique fonctionne uniquement pour les apps XWayland"
},
"promptStudio": {
@@ -1911,6 +1914,7 @@
"recheck": "Revérifier",
"copy": "Copier",
"ydotoolDesc": "Outil d'automatisation de saisie pour Wayland",
+ "wtypeDesc": "Outil d'automatisation de saisie recommandé sur les compositeurs wlroots",
"ydotooldDesc": "Daemon pour ydotool (paquet séparé sur Ubuntu/Pop!_OS)",
"uinputDesc": "Accès au périphérique d'entrée du noyau",
"uinputRuleFound": "Règle présente mais inactive. Un redémarrage devrait résoudre le problème.",
@@ -1929,6 +1933,11 @@
"step2Title": "Vérifier l'installation",
"step2Desc": "Vérifiez que ydotool est disponible dans votre PATH."
},
+ "wtype": {
+ "step1Title": "Installer wtype",
+ "step1Desc": "wtype est la méthode principale de collage automatique sur Hyprland, Sway et les autres compositeurs wlroots.",
+ "step2Title": "Vérifier l'installation"
+ },
"ydotoold": {
"step1Title": "Installer ydotoold",
"step1Desc": "Sur Ubuntu et Pop!_OS, ydotoold est un paquet séparé. Sur Fedora, il est inclus avec ydotool."
diff --git a/src/locales/it/translation.json b/src/locales/it/translation.json
index 1b47b76b3..5581e3807 100644
--- a/src/locales/it/translation.json
+++ b/src/locales/it/translation.json
@@ -1028,8 +1028,10 @@
"installCommands": {
"archLinux": "# Arch Linux",
"debianUbuntu": "# Debian / Ubuntu",
+ "debianUbuntuPop": "# Debian / Ubuntu / Pop!_OS",
"debianUbuntuMint": "# Debian / Ubuntu / Mint",
- "fedoraRhel": "# Fedora / RHEL"
+ "fedoraRhel": "# Fedora / RHEL",
+ "openSuse": "# openSUSE Tumbleweed / Leap"
},
"installPrefix": "Per l'incollaggio automatico del testo, installa",
"methodReady": "per l'incollaggio automatico del testo",
@@ -1045,6 +1047,7 @@
"waylandClipboardTitle": "Modalità appunti su Wayland",
"windowsReady": "Windows supporta l'incollaggio automatico senza configurazione aggiuntiva!",
"withoutToolPrefix": "Senza questo strumento, OpenWhispr copierà il testo negli appunti. Potrai poi incollare manualmente con Ctrl+V.",
+ "wtypeFallbackDescription": "wtype è il metodo di incollaggio automatico preferito per questo compositor wlroots. È disponibile un'alternativa, ma potrebbe essere meno affidabile.",
"xwaylandAppsOnly": "l'incollaggio automatico funziona solo per le app XWayland"
},
"promptStudio": {
@@ -1628,6 +1631,7 @@
"recheck": "Ricontrolla",
"copy": "Copia",
"ydotoolDesc": "Strumento di automazione input per Wayland",
+ "wtypeDesc": "Strumento di automazione input preferito sui compositor wlroots",
"ydotooldDesc": "Daemon per ydotool (pacchetto separato su Ubuntu/Pop!_OS)",
"uinputDesc": "Accesso al dispositivo di input del kernel",
"uinputRuleFound": "Regola presente ma non attiva. Un riavvio dovrebbe risolvere.",
@@ -1646,6 +1650,11 @@
"step2Title": "Verifica l'installazione",
"step2Desc": "Controlla che ydotool sia disponibile nel tuo PATH."
},
+ "wtype": {
+ "step1Title": "Installa wtype",
+ "step1Desc": "wtype è il metodo principale di incollaggio automatico su Hyprland, Sway e altri compositor wlroots.",
+ "step2Title": "Verifica l'installazione"
+ },
"ydotoold": {
"step1Title": "Installa ydotoold",
"step1Desc": "Su Ubuntu e Pop!_OS, ydotoold è un pacchetto separato. Su Fedora è incluso in ydotool."
diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.json
index 76533aec1..c74cd288e 100644
--- a/src/locales/ja/translation.json
+++ b/src/locales/ja/translation.json
@@ -1028,8 +1028,10 @@
"installCommands": {
"archLinux": "# Arch Linux",
"debianUbuntu": "# Debian / Ubuntu",
+ "debianUbuntuPop": "# Debian / Ubuntu / Pop!_OS",
"debianUbuntuMint": "# Debian / Ubuntu / Mint",
- "fedoraRhel": "# Fedora / RHEL"
+ "fedoraRhel": "# Fedora / RHEL",
+ "openSuse": "# openSUSE Tumbleweed / Leap"
},
"installPrefix": "テキストの自動貼り付けには",
"methodReady": "で自動貼り付け可能",
@@ -1045,6 +1047,7 @@
"waylandClipboardTitle": "Wayland でのクリップボードモード",
"windowsReady": "Windows は自動貼り付けに標準対応しています。設定は不要です!",
"withoutToolPrefix": "このツールがない場合、OpenWhispr はテキストをクリップボードにコピーします。Ctrl+V で手動で貼り付けてください。",
+ "wtypeFallbackDescription": "この wlroots 系コンポジターでは wtype が推奨される自動貼り付け方法です。代替手段も利用できますが、信頼性が低い場合があります。",
"xwaylandAppsOnly": "自動貼り付けは XWayland アプリのみで動作します"
},
"promptStudio": {
@@ -1628,6 +1631,7 @@
"recheck": "再確認",
"copy": "コピー",
"ydotoolDesc": "Wayland 用入力自動化ツール",
+ "wtypeDesc": "wlroots 系コンポジターで推奨される入力自動化ツール",
"ydotooldDesc": "ydotool デーモン(Ubuntu/Pop!_OS では別パッケージ)",
"uinputDesc": "カーネル入力デバイスへのアクセス",
"uinputRuleFound": "ルールは存在しますが未適用です。再起動で解決するはずです。",
@@ -1646,6 +1650,11 @@
"step2Title": "インストールの確認",
"step2Desc": "ydotool が PATH で利用可能か確認してください。"
},
+ "wtype": {
+ "step1Title": "wtype をインストール",
+ "step1Desc": "wtype は Hyprland、Sway などの wlroots 系コンポジターにおける主要な自動貼り付け方法です。",
+ "step2Title": "インストールの確認"
+ },
"ydotoold": {
"step1Title": "ydotoold をインストール",
"step1Desc": "Ubuntu と Pop!_OS では ydotoold は別パッケージです。Fedora では ydotool に含まれています。"
diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.json
index 21c6dc85b..faeffee0b 100644
--- a/src/locales/pt/translation.json
+++ b/src/locales/pt/translation.json
@@ -1007,8 +1007,10 @@
"installCommands": {
"archLinux": "# Arch Linux",
"debianUbuntu": "# Debian / Ubuntu",
+ "debianUbuntuPop": "# Debian / Ubuntu / Pop!_OS",
"debianUbuntuMint": "# Debian / Ubuntu / Mint",
- "fedoraRhel": "# Fedora / RHEL"
+ "fedoraRhel": "# Fedora / RHEL",
+ "openSuse": "# openSUSE Tumbleweed / Leap"
},
"installPrefix": "Para colagem automática de texto, instale",
"methodReady": "para colagem automática de texto",
@@ -1024,6 +1026,7 @@
"waylandClipboardTitle": "Modo área de transferência no Wayland",
"windowsReady": "O Windows suporta colagem automática nativamente. Nenhuma configuração necessária!",
"withoutToolPrefix": "Sem essa ferramenta, o OpenWhispr copiará o texto para a área de transferência. Você poderá colar manualmente com Ctrl+V.",
+ "wtypeFallbackDescription": "O wtype é o método de colagem automática preferido para este compositor wlroots. Há uma alternativa disponível, mas ela pode ser menos confiável.",
"xwaylandAppsOnly": "a colagem automática funciona apenas para apps XWayland"
},
"promptStudio": {
@@ -1607,6 +1610,7 @@
"recheck": "Verificar novamente",
"copy": "Copiar",
"ydotoolDesc": "Ferramenta de automação de entrada para Wayland",
+ "wtypeDesc": "Ferramenta de automação de entrada preferida em compositores wlroots",
"ydotooldDesc": "Daemon do ydotool (pacote separado no Ubuntu/Pop!_OS)",
"uinputDesc": "Acesso ao dispositivo de entrada do kernel",
"uinputRuleFound": "Regra presente mas não ativa. Uma reinicialização deve resolver.",
@@ -1625,6 +1629,11 @@
"step2Title": "Verificar a instalação",
"step2Desc": "Verifique se o ydotool está disponível no seu PATH."
},
+ "wtype": {
+ "step1Title": "Instalar o wtype",
+ "step1Desc": "O wtype é o método principal de colagem automática no Hyprland, Sway e outros compositores wlroots.",
+ "step2Title": "Verificar a instalação"
+ },
"ydotoold": {
"step1Title": "Instalar o ydotoold",
"step1Desc": "No Ubuntu e Pop!_OS, o ydotoold é um pacote separado. No Fedora, está incluído no ydotool."
diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.json
index 95466bb6c..eed035b71 100644
--- a/src/locales/ru/translation.json
+++ b/src/locales/ru/translation.json
@@ -1028,8 +1028,10 @@
"installCommands": {
"archLinux": "# Arch Linux",
"debianUbuntu": "# Debian / Ubuntu",
+ "debianUbuntuPop": "# Debian / Ubuntu / Pop!_OS",
"debianUbuntuMint": "# Debian / Ubuntu / Mint",
- "fedoraRhel": "# Fedora / RHEL"
+ "fedoraRhel": "# Fedora / RHEL",
+ "openSuse": "# openSUSE Tumbleweed / Leap"
},
"installPrefix": "Для автоматической вставки текста установите",
"methodReady": "для автоматической вставки текста",
@@ -1045,6 +1047,7 @@
"waylandClipboardTitle": "Режим буфера обмена в Wayland",
"windowsReady": "Windows поддерживает автоматическую вставку из коробки. Настройка не требуется!",
"withoutToolPrefix": "Без этого инструмента OpenWhispr скопирует текст в буфер обмена. Вы сможете вставить его вручную с помощью Ctrl+V.",
+ "wtypeFallbackDescription": "wtype — предпочтительный способ автоматической вставки для этого композитора wlroots. Доступен резервный вариант, но он может быть менее надёжным.",
"xwaylandAppsOnly": "автоматическая вставка работает только для приложений XWayland"
},
"promptStudio": {
@@ -1632,6 +1635,7 @@
"recheck": "Проверить снова",
"copy": "Копировать",
"ydotoolDesc": "Инструмент автоматизации ввода для Wayland",
+ "wtypeDesc": "Предпочтительный инструмент автоматизации ввода для композиторов wlroots",
"ydotooldDesc": "Демон ydotool (отдельный пакет в Ubuntu/Pop!_OS)",
"uinputDesc": "Доступ к устройству ввода ядра",
"uinputRuleFound": "Правило найдено, но не активно. Перезагрузка должна помочь.",
@@ -1650,6 +1654,11 @@
"step2Title": "Проверить установку",
"step2Desc": "Убедитесь, что ydotool доступен в вашем PATH."
},
+ "wtype": {
+ "step1Title": "Установить wtype",
+ "step1Desc": "wtype — основной способ автоматической вставки в Hyprland, Sway и других композиторах wlroots.",
+ "step2Title": "Проверить установку"
+ },
"ydotoold": {
"step1Title": "Установить ydotoold",
"step1Desc": "В Ubuntu и Pop!_OS ydotoold — отдельный пакет. В Fedora он входит в состав ydotool."
diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.json
index 1141dd3a6..6e6ebd13b 100644
--- a/src/locales/zh-CN/translation.json
+++ b/src/locales/zh-CN/translation.json
@@ -1028,8 +1028,10 @@
"installCommands": {
"archLinux": "# Arch Linux",
"debianUbuntu": "# Debian / Ubuntu",
+ "debianUbuntuPop": "# Debian / Ubuntu / Pop!_OS",
"debianUbuntuMint": "# Debian / Ubuntu / Mint",
- "fedoraRhel": "# Fedora / RHEL"
+ "fedoraRhel": "# Fedora / RHEL",
+ "openSuse": "# openSUSE Tumbleweed / Leap"
},
"installPrefix": "如需自动粘贴文本,请安装",
"methodReady": "用于自动粘贴文本",
@@ -1045,6 +1047,7 @@
"waylandClipboardTitle": "Wayland 上的剪贴板模式",
"windowsReady": "Windows 原生支持自动粘贴,无需额外设置!",
"withoutToolPrefix": "如果不安装此工具,OpenWhispr 会将文本复制到剪贴板,你可以使用 Ctrl+V 手动粘贴。",
+ "wtypeFallbackDescription": "wtype 是此 wlroots 合成器上的首选自动粘贴方式。有备用方案可用,但可能不太可靠。",
"xwaylandAppsOnly": "自动粘贴仅适用于 XWayland 应用"
},
"promptStudio": {
@@ -1628,6 +1631,7 @@
"recheck": "重新检查",
"copy": "复制",
"ydotoolDesc": "Wayland 输入自动化工具",
+ "wtypeDesc": "wlroots 合成器上的首选输入自动化工具",
"ydotooldDesc": "ydotool 守护进程(Ubuntu/Pop!_OS 上为独立包)",
"uinputDesc": "内核输入设备访问",
"uinputRuleFound": "规则已存在但未生效,重启应可解决。",
@@ -1646,6 +1650,11 @@
"step2Title": "验证安装",
"step2Desc": "检查 ydotool 是否在你的 PATH 中可用。"
},
+ "wtype": {
+ "step1Title": "安装 wtype",
+ "step1Desc": "wtype 是 Hyprland、Sway 及其他 wlroots 合成器上的主要自动粘贴方式。",
+ "step2Title": "验证安装"
+ },
"ydotoold": {
"step1Title": "安装 ydotoold",
"step1Desc": "在 Ubuntu 和 Pop!_OS 上,ydotoold 是独立的包。在 Fedora 上它包含在 ydotool 中。"
diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.json
index 854661bd6..2300878e3 100644
--- a/src/locales/zh-TW/translation.json
+++ b/src/locales/zh-TW/translation.json
@@ -1028,8 +1028,10 @@
"installCommands": {
"archLinux": "# Arch Linux",
"debianUbuntu": "# Debian / Ubuntu",
+ "debianUbuntuPop": "# Debian / Ubuntu / Pop!_OS",
"debianUbuntuMint": "# Debian / Ubuntu / Mint",
- "fedoraRhel": "# Fedora / RHEL"
+ "fedoraRhel": "# Fedora / RHEL",
+ "openSuse": "# openSUSE Tumbleweed / Leap"
},
"installPrefix": "如需自動貼上文字,請安裝",
"methodReady": "用於自動貼上文字",
@@ -1045,6 +1047,7 @@
"waylandClipboardTitle": "Wayland 剪貼簿模式",
"windowsReady": "Windows 內建支援自動貼上。不需要額外設定!",
"withoutToolPrefix": "若未安裝此工具,OpenWhispr 會將文字複製到剪貼簿。你可以使用 Ctrl+V 手動貼上。",
+ "wtypeFallbackDescription": "wtype 是此 wlroots 合成器上的首選自動貼上方式。有備用方案可用,但可能較不可靠。",
"xwaylandAppsOnly": "自動貼上僅適用於 XWayland 應用程式"
},
"promptStudio": {
@@ -1628,6 +1631,7 @@
"recheck": "重新檢查",
"copy": "複製",
"ydotoolDesc": "Wayland 輸入自動化工具",
+ "wtypeDesc": "wlroots 合成器上的首選輸入自動化工具",
"ydotooldDesc": "ydotool 常駐程式(Ubuntu/Pop!_OS 上為獨立套件)",
"uinputDesc": "核心輸入裝置存取",
"uinputRuleFound": "規則已存在但未生效,重新開機應可解決。",
@@ -1646,6 +1650,11 @@
"step2Title": "驗證安裝",
"step2Desc": "檢查 ydotool 是否在你的 PATH 中可用。"
},
+ "wtype": {
+ "step1Title": "安裝 wtype",
+ "step1Desc": "wtype 是 Hyprland、Sway 及其他 wlroots 合成器上的主要自動貼上方式。",
+ "step2Title": "驗證安裝"
+ },
"ydotoold": {
"step1Title": "安裝 ydotoold",
"step1Desc": "在 Ubuntu 和 Pop!_OS 上,ydotoold 是獨立的套件。在 Fedora 上它包含在 ydotool 中。"
diff --git a/src/types/electron.ts b/src/types/electron.ts
index 25ac184d7..8f787507f 100644
--- a/src/types/electron.ts
+++ b/src/types/electron.ts
@@ -738,6 +738,8 @@ export interface PasteToolsResult {
terminalAware?: boolean;
hasNativeBinary?: boolean;
hasUinput?: boolean;
+ hasWtype?: boolean;
+ isWlroots?: boolean;
tools?: string[];
recommendedInstall?: string;
}
@@ -1554,13 +1556,17 @@ declare global {
isWayland: boolean;
hasYdotool: boolean;
hasYdotoold: boolean;
+ hasWtype: boolean;
daemonRunning: boolean;
hasService: boolean;
hasUinput: boolean;
hasUdevRule: boolean;
hasGroup: boolean;
isNixOS: boolean;
- allGood: boolean;
+ isKde: boolean;
+ isWlroots: boolean;
+ hasXclip: boolean;
+ hasXsel: boolean;
}>;
// Globe key listener for hotkey capture (macOS only)
diff --git a/src/utils/linuxPasteTools.ts b/src/utils/linuxPasteTools.ts
new file mode 100644
index 000000000..e237041f8
--- /dev/null
+++ b/src/utils/linuxPasteTools.ts
@@ -0,0 +1,44 @@
+type Translate = (key: string) => string;
+
+export type LinuxPasteTool = "wtype" | "ydotool" | "xdotool";
+
+export interface LinuxPasteInstallCommand {
+ label: string;
+ cmd: string;
+}
+
+export function getLinuxPasteInstallCommands(
+ t: Translate,
+ tool: LinuxPasteTool
+): LinuxPasteInstallCommand[] {
+ const commands = [
+ {
+ label: t(
+ tool === "xdotool"
+ ? "pasteToolsInfo.installCommands.debianUbuntuMint"
+ : "pasteToolsInfo.installCommands.debianUbuntuPop"
+ ),
+ cmd: `sudo apt install ${tool}`,
+ },
+ { label: t("pasteToolsInfo.installCommands.fedoraRhel"), cmd: `sudo dnf install ${tool}` },
+ { label: t("pasteToolsInfo.installCommands.archLinux"), cmd: `sudo pacman -S ${tool}` },
+ ];
+
+ return tool === "xdotool"
+ ? commands
+ : [
+ ...commands,
+ {
+ label: t("pasteToolsInfo.installCommands.openSuse"),
+ cmd: `sudo zypper install ${tool}`,
+ },
+ ];
+}
+
+export function needsLinuxPasteToolGuidance(pasteTools: PasteToolsResult) {
+ return (
+ pasteTools.platform === "linux" &&
+ (!pasteTools.available || (pasteTools.isWlroots && !pasteTools.hasWtype))
+ );
+}
+import type { PasteToolsResult } from "../types/electron";
diff --git a/test/helpers/clipboardRestore.test.js b/test/helpers/clipboardRestore.test.js
index 1982b8c6e..c58b65f94 100644
--- a/test/helpers/clipboardRestore.test.js
+++ b/test/helpers/clipboardRestore.test.js
@@ -89,6 +89,15 @@ function loadClipboardManager({ spawn } = {}) {
}
const ClipboardManager = loadClipboardManager();
+const initialExitListeners = new Set(process.listeners("exit"));
+
+test.afterEach(() => {
+ for (const listener of process.listeners("exit")) {
+ if (!initialExitListeners.has(listener)) {
+ process.removeListener("exit", listener);
+ }
+ }
+});
function createSuccessfulSpawn(calls) {
return function successfulSpawn(command, args = []) {
@@ -101,6 +110,46 @@ function createSuccessfulSpawn(calls) {
};
}
+function createSpawn(calls, exitCodes, { stdout = [] } = {}) {
+ return function mockedSpawn(command, args = []) {
+ calls.push({ command, args });
+ const pasteProcess = new EventEmitter();
+ pasteProcess.stderr = new EventEmitter();
+ pasteProcess.stdout = new EventEmitter();
+ const code = exitCodes.shift() ?? 0;
+ const output = stdout.shift();
+ process.nextTick(() => {
+ if (output) pasteProcess.stdout.emit("data", output);
+ pasteProcess.emit("close", code);
+ });
+ return pasteProcess;
+ };
+}
+
+async function withWaylandEnvironment(desktop, callback) {
+ const previous = {
+ XDG_SESSION_TYPE: process.env.XDG_SESSION_TYPE,
+ XDG_CURRENT_DESKTOP: process.env.XDG_CURRENT_DESKTOP,
+ WAYLAND_DISPLAY: process.env.WAYLAND_DISPLAY,
+ HYPRLAND_INSTANCE_SIGNATURE: process.env.HYPRLAND_INSTANCE_SIGNATURE,
+ DISPLAY: process.env.DISPLAY,
+ };
+ process.env.XDG_SESSION_TYPE = "wayland";
+ process.env.XDG_CURRENT_DESKTOP = desktop;
+ process.env.WAYLAND_DISPLAY = "wayland-1";
+ delete process.env.DISPLAY;
+ if (desktop === "Hyprland") process.env.HYPRLAND_INSTANCE_SIGNATURE = "test";
+ else delete process.env.HYPRLAND_INSTANCE_SIGNATURE;
+ try {
+ return await callback();
+ } finally {
+ for (const [key, value] of Object.entries(previous)) {
+ if (value === undefined) delete process.env[key];
+ else process.env[key] = value;
+ }
+ }
+}
+
function resetClipboard({
text = "",
html = "",
@@ -198,6 +247,359 @@ test("pasteText waits for prior clipboard restoration before starting the next p
assert.deepEqual(events, ["start:first", "end:first", "start:second", "end:second"]);
});
+test("Hyprland paste uses the current symbolic shortcut dispatcher", async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSpawn(spawnCalls, [0], { stdout: ["ok\n"] }),
+ });
+ const manager = new TestClipboardManager();
+ manager.commandExists = (command) => command === "hyprctl";
+ manager.resolveLinuxFastPasteBinary = () => null;
+ manager._detectHyprlandWindowClass = () => "kitty";
+
+ await withWaylandEnvironment("Hyprland", () => manager.pasteLinux(null));
+
+ assert.deepEqual(spawnCalls, [
+ {
+ command: "hyprctl",
+ args: [
+ "dispatch",
+ 'hl.dsp.send_shortcut({ mods = "CTRL SHIFT", key = "V", window = "activewindow" })',
+ ],
+ },
+ ]);
+});
+
+test("Hyprland paste falls back to the legacy symbolic shortcut dispatcher", async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSpawn(spawnCalls, [0, 0], {
+ stdout: ["invalid dispatcher\n", "ok\n"],
+ }),
+ });
+ const manager = new TestClipboardManager();
+ manager.commandExists = (command) => command === "hyprctl";
+ manager.resolveLinuxFastPasteBinary = () => null;
+ manager._detectHyprlandWindowClass = () => null;
+
+ await withWaylandEnvironment("Hyprland", () => manager.pasteLinux(null));
+
+ assert.deepEqual(spawnCalls, [
+ {
+ command: "hyprctl",
+ args: [
+ "dispatch",
+ 'hl.dsp.send_shortcut({ mods = "SHIFT", key = "Insert", window = "activewindow" })',
+ ],
+ },
+ { command: "hyprctl", args: ["dispatch", "sendshortcut", "SHIFT, Insert, activewindow"] },
+ ]);
+});
+
+test("Hyprland prefers wtype over sendshortcut when installed", async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSpawn(spawnCalls, [0]),
+ });
+ const manager = new TestClipboardManager();
+ manager.commandExists = (command) => command === "hyprctl" || command === "wtype";
+ manager.resolveLinuxFastPasteBinary = () => null;
+ manager._detectHyprlandWindowClass = () => null;
+
+ await withWaylandEnvironment("Hyprland", () => manager.pasteLinux(null));
+
+ assert.deepEqual(
+ spawnCalls.map((call) => call.command),
+ ["wtype"]
+ );
+});
+
+test("failed wtype on Hyprland continues to sendshortcut", async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSpawn(spawnCalls, [1, 0], { stdout: ["", "ok\n"] }),
+ });
+ const manager = new TestClipboardManager();
+ manager.commandExists = (command) => command === "hyprctl" || command === "wtype";
+ manager.resolveLinuxFastPasteBinary = () => null;
+ manager._detectHyprlandWindowClass = () => null;
+
+ await withWaylandEnvironment("Hyprland", () => manager.pasteLinux(null));
+
+ assert.deepEqual(
+ spawnCalls.map((call) => call.command),
+ ["wtype", "hyprctl"]
+ );
+});
+
+test("wlroots tries wtype before native uinput", async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSuccessfulSpawn(spawnCalls),
+ });
+ const manager = new TestClipboardManager();
+ manager.commandExists = (command) => command === "wtype";
+ manager.resolveLinuxFastPasteBinary = () => "/tmp/linux-fast-paste";
+
+ await withWaylandEnvironment("Sway", () => manager.pasteLinux(null));
+
+ assert.deepEqual(spawnCalls, [
+ { command: "wtype", args: ["-M", "shift", "-k", "Insert", "-m", "shift"] },
+ ]);
+});
+
+test("failed wtype continues to native Shift+Insert uinput", async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSpawn(spawnCalls, [1, 0]),
+ });
+ const manager = new TestClipboardManager();
+ manager.commandExists = (command) => command === "wtype";
+ manager.resolveLinuxFastPasteBinary = () => "/tmp/linux-fast-paste";
+
+ await withWaylandEnvironment("Sway", () => manager.pasteLinux(null));
+
+ assert.deepEqual(
+ spawnCalls.map((call) => call.command),
+ ["wtype", "/tmp/linux-fast-paste"]
+ );
+ assert.deepEqual(spawnCalls[1].args, ["--uinput", "--shift-insert"]);
+});
+
+test("GNOME tries uinput before a tokenless portal", async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSpawn(spawnCalls, [0]),
+ });
+ const manager = new TestClipboardManager();
+ manager.commandExists = () => false;
+ manager.resolveLinuxFastPasteBinary = () => "/tmp/linux-fast-paste";
+ manager._readPortalToken = () => null;
+
+ await withWaylandEnvironment("GNOME", () => manager.pasteLinux(null));
+
+ assert.deepEqual(spawnCalls, [
+ { command: "/tmp/linux-fast-paste", args: ["--uinput", "--shift-insert"] },
+ ]);
+});
+
+test("GNOME falls back to a tokenless portal after uinput fails", async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSpawn(spawnCalls, [1, 0]),
+ });
+ const manager = new TestClipboardManager();
+ manager.commandExists = () => false;
+ manager.resolveLinuxFastPasteBinary = () => "/tmp/linux-fast-paste";
+ manager._readPortalToken = () => null;
+
+ await withWaylandEnvironment("GNOME", () => manager.pasteLinux(null));
+
+ assert.deepEqual(spawnCalls, [
+ { command: "/tmp/linux-fast-paste", args: ["--uinput", "--shift-insert"] },
+ { command: "/tmp/linux-fast-paste", args: ["--portal", "--shift-insert"] },
+ ]);
+});
+
+test("GNOME uses a saved portal token before uinput", async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSpawn(spawnCalls, [0], { stdout: ["rotated-token\n"] }),
+ });
+ const manager = new TestClipboardManager();
+ const savedTokens = [];
+ manager.commandExists = () => false;
+ manager.resolveLinuxFastPasteBinary = () => "/tmp/linux-fast-paste";
+ manager._readPortalToken = () => "restore-token";
+ manager._savePortalToken = (token) => savedTokens.push(token);
+
+ await withWaylandEnvironment("GNOME", () => manager.pasteLinux(null));
+
+ assert.deepEqual(spawnCalls, [
+ {
+ command: "/tmp/linux-fast-paste",
+ args: ["--portal", "--shift-insert", "--restore-token", "restore-token"],
+ },
+ ]);
+ assert.deepEqual(savedTokens, ["rotated-token"]);
+});
+
+test("GNOME stops preferring a saved portal token after it fails", async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSpawn(spawnCalls, [1, 0, 0]),
+ });
+ const manager = new TestClipboardManager();
+ manager.commandExists = () => false;
+ manager.resolveLinuxFastPasteBinary = () => "/tmp/linux-fast-paste";
+ manager._readPortalToken = () => "restore-token";
+
+ await withWaylandEnvironment("GNOME", async () => {
+ await manager.pasteLinux(null);
+ await manager.pasteLinux(null);
+ });
+
+ assert.deepEqual(
+ spawnCalls.map((call) => call.args),
+ [
+ ["--portal", "--shift-insert", "--restore-token", "restore-token"],
+ ["--uinput", "--shift-insert"],
+ ["--uinput", "--shift-insert"],
+ ]
+ );
+});
+
+test("KDE tries portal before uinput", async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSpawn(spawnCalls, [1, 0]),
+ });
+ const manager = new TestClipboardManager();
+ manager.commandExists = () => false;
+ manager.resolveLinuxFastPasteBinary = () => "/tmp/linux-fast-paste";
+ manager._readPortalToken = () => null;
+
+ await withWaylandEnvironment("KDE", () => manager.pasteLinux(null));
+
+ assert.deepEqual(
+ spawnCalls.map((call) => call.args),
+ [
+ ["--portal", "--shift-insert"],
+ ["--uinput", "--shift-insert"],
+ ]
+ );
+});
+
+test("portal exit zero succeeds with or without a restore token", async () => {
+ const calls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSpawn(calls, [0, 0], { stdout: ["", "rotated-token\n"] }),
+ });
+ const manager = new TestClipboardManager();
+ const saved = [];
+ const restoreTokens = [null, "restore-token"];
+ manager._readPortalToken = () => restoreTokens.shift();
+ manager._savePortalToken = (token) => saved.push(token);
+
+ assert.equal(await manager._runPortalPaste("/tmp/linux-fast-paste"), null);
+ assert.equal(await manager._runPortalPaste("/tmp/linux-fast-paste"), "rotated-token");
+ assert.deepEqual(
+ calls.map((call) => call.args),
+ [["--portal"], ["--portal", "--restore-token", "restore-token"]]
+ );
+ assert.deepEqual(saved, ["rotated-token"]);
+});
+
+test("portal symbolic input failure is suppressed for the process", async () => {
+ const manager = new ClipboardManager();
+ const attempts = [];
+ manager.commandExists = () => false;
+ manager.resolveLinuxFastPasteBinary = () => "/tmp/linux-fast-paste";
+ manager._readPortalToken = () => "restore-token";
+ manager._runPortalPaste = async () => {
+ attempts.push("portal");
+ throw new Error("portal symbolic keyboard input unavailable");
+ };
+ manager._runLinuxPasteCommand = async () => attempts.push("uinput");
+
+ await withWaylandEnvironment("GNOME", async () => {
+ await manager.pasteLinux(null);
+ await manager.pasteLinux(null);
+ });
+
+ assert.deepEqual(attempts, ["portal", "uinput", "uinput"]);
+});
+
+test("portal denial is attempted once per process", async () => {
+ const manager = new ClipboardManager();
+ const attempts = [];
+ manager.commandExists = () => false;
+ manager.resolveLinuxFastPasteBinary = () => "/tmp/linux-fast-paste";
+ manager._readPortalToken = () => "restore-token";
+ manager._runPortalPaste = async () => {
+ attempts.push("portal");
+ throw new Error("portal-denied");
+ };
+ manager._runLinuxPasteCommand = async () => attempts.push("uinput");
+
+ await withWaylandEnvironment("GNOME", async () => {
+ await manager.pasteLinux(null);
+ await manager.pasteLinux(null);
+ });
+
+ assert.deepEqual(attempts, ["portal", "uinput", "uinput"]);
+});
+
+test("portal exit six reports unavailable symbolic input", async () => {
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSpawn([], [6]),
+ });
+ const manager = new TestClipboardManager();
+
+ await assert.rejects(
+ manager._runPortalPaste("/tmp/linux-fast-paste"),
+ /portal symbolic keyboard input unavailable/
+ );
+});
+
+test("Wayland ydotool uses raw Shift+Insert keycodes", async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSuccessfulSpawn(spawnCalls),
+ });
+ const manager = new TestClipboardManager();
+ manager.commandExists = (command) => command === "ydotool";
+ manager._isYdotoolDaemonRunning = () => true;
+ manager._isYdotoolLegacy = () => false;
+ manager.resolveLinuxFastPasteBinary = () => null;
+
+ await withWaylandEnvironment("Unknown", () => manager.pasteLinux(null));
+
+ assert.deepEqual(spawnCalls, [
+ { command: "ydotool", args: ["key", "42:1", "110:1", "110:0", "42:0"] },
+ ]);
+});
+
+test("successful Wayland dispatch starts clipboard restoration", async () => {
+ const manager = new ClipboardManager();
+ let restoreCalled = false;
+ manager.commandExists = (command) => command === "hyprctl";
+ manager.resolveLinuxFastPasteBinary = () => null;
+ manager._detectHyprlandWindowClass = () => null;
+ manager._runLinuxPasteCommand = async () => {};
+ manager._restoreClipboardAfterDelay = () => {
+ restoreCalled = true;
+ return Promise.resolve();
+ };
+
+ const result = await withWaylandEnvironment("Hyprland", () =>
+ manager.pasteLinux({ type: "text", data: "previous" }, { expectedClipboardText: "dictated" })
+ );
+ await result.restoreComplete;
+
+ assert.equal(restoreCalled, true);
+});
+
+test("XWayland fallback remains reachable after native Wayland failure", async () => {
+ const spawnCalls = [];
+ const TestClipboardManager = loadClipboardManager({
+ spawn: createSpawn(spawnCalls, [1, 0]),
+ });
+ const manager = new TestClipboardManager();
+ manager.commandExists = () => false;
+ manager.resolveLinuxFastPasteBinary = () => "/tmp/linux-fast-paste";
+
+ await withWaylandEnvironment("Unknown", async () => {
+ process.env.DISPLAY = ":0";
+ await manager.pasteLinux(null);
+ });
+
+ assert.deepEqual(
+ spawnCalls.map((call) => call.args),
+ [["--uinput", "--shift-insert"], ["--shift-insert"]]
+ );
+});
+
test("pasteMacOS restores clipboard after the short macOS delay on successful fast paste", async () => {
const spawnCalls = [];
const TestClipboardManager = loadClipboardManager({