Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(linux): populate Wayland clipboard on KDE for native Wayland apps (#2055) (#2098)
Aditya kumar singhe4280ada144f
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8f7b9780c..e07b8b40d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -62,8 +62,8 @@ 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: compositor-aware Wayland paste (Hyprland sendshortcut, wlroots wtype, GNOME/KDE portal keysyms) with native uinput/XTest and system-tool fallbacks. KDE's portal paste sends Shift+Insert to every window but Warp, which binds paste to Ctrl+Shift+V only: KWin resolves keysyms in the active layout only, so a Ctrl+V on a non-Latin layout arrives as Ctrl alone (#2055). The app runs on XWayland, which the compositor won't let read a native Wayland app's clipboard while a Wayland window is focused, so `_saveClipboard` falls back to `wl-paste --type text` when Electron reads nothing; otherwise the restore would wipe the user's clipboard- - Linux: wlroots, Hyprland and niri (xwayland-satellite) hand XWayland's clipboard to a native Wayland app only while an X11 window has focus; KWin, Mutter and COSMIC do it themselves. There (`requiresWlCopy` in `linuxSession.js`; a leftover `SWAYSOCK` or Hyprland signature under another desktop doesn't count) the transcript reaches Wayland apps only through `wl-copy`, so `_pasteText` pastes only when wl-copy wrote both the Wayland clipboard (`_writeClipboardWayland`) and the primary selection that terminals paste on Shift+Insert (`_writePrimarySelection`). `wl-copy --primary` goes through data-control, which still takes a primary selection under niri `disable-primary` (checked on niri 26.04) and Hyprland `middle_click_paste = false` (its data-control code never reads that option). Otherwise it injects nothing and returns `reason: "wl-copy-missing"` (not installed) or `"wl-copy-failed"` (e.g. killed by its 200 ms timeout): the renderer shows the dictation-error pill (Retry writes and pastes the kept text again, never records), a selection edit reports `code: "wl_copy_missing"`/`"wl_copy_failed"`, and the paste-tools card and Settings → Wayland Paste Setup ask for wl-clipboard (#2621). There, a missing `wl-copy` is probed again rather than read from the 30 s command cache, so one installed after a held-back paste counts at once+ - Linux: compositor-aware Wayland paste (Hyprland sendshortcut, wlroots wtype, GNOME/KDE portal keysyms) with native uinput/XTest and system-tool fallbacks. KDE's portal paste sends Shift+Insert to every window but Warp, which binds paste to Ctrl+Shift+V only: KWin resolves keysyms in the active layout only, so a Ctrl+V on a non-Latin layout arrives as Ctrl alone (#2055). The app runs on XWayland, which the compositor won't let read a native Wayland app's clipboard while a Wayland window is focused, so `_saveClipboard` falls back to `wl-paste --type text` when Electron reads nothing; otherwise the restore would wipe the user's clipboard. On KDE it also takes wl-paste's UTF-8 plain text whenever it differs from Electron's, since KWin can leave a stale X11 owner in place after a Wayland app copies, so a rich or image restore first writes the original's text (empty for an image) to Wayland, or the app's own transcript or selection sentinel left there would read as newer. A Wayland-only copy with no plain text (a screenshot copied in Spectacle) isn't saved, so a dictation replaces it with X11's older text+ - Linux: wlroots, Hyprland and niri (xwayland-satellite) hand XWayland's clipboard to a native Wayland app only while an X11 window has focus; Mutter, COSMIC and KWin 6.0.3+ do it themselves (KDE also writes the transcript and primary selection with `wl-copy`, and Settings asks for wl-clipboard there too, since `_saveClipboard` reads the Wayland clipboard there with `wl-paste`). There (`requiresWlCopy` in `linuxSession.js`; a leftover `SWAYSOCK` or Hyprland signature under another desktop doesn't count) the transcript reaches Wayland apps only through `wl-copy`, so `_pasteText` pastes only when wl-copy wrote both the Wayland clipboard (`_writeClipboardWayland`) and the primary selection that terminals paste on Shift+Insert (`_writePrimarySelection`). `wl-copy --primary` goes through data-control, which still takes a primary selection under niri `disable-primary` (checked on niri 26.04) and Hyprland `middle_click_paste = false` (its data-control code never reads that option). Otherwise it injects nothing and returns `reason: "wl-copy-missing"` (not installed) or `"wl-copy-failed"` (e.g. killed by its 200 ms timeout): the renderer shows the dictation-error pill (Retry writes and pastes the kept text again, never records), a selection edit reports `code: "wl_copy_missing"`/`"wl_copy_failed"`, and the paste-tools card and Settings → Wayland Paste Setup ask for wl-clipboard (#2621). There, a missing `wl-copy` is probed again rather than read from the 30 s command cache, so one installed after a held-back paste counts at once- Linux COSMIC: paste reads the focused app from cosmic-comp's `zcosmic_toplevel_info_v1` (`cosmicToplevel.js`, a minimal Wayland wire client, bound at version 1, which still sends app_id and state), never from xdotool, whose XWayland answer goes stale while a native Wayland window has focus. A known terminal is pasted through wtype (Ctrl+Shift+V; Shift+Insert for Konsole); everything else keeps uinput Shift+Insert, since COSMIC gives no PID to spot Electron apps hosting TUIs. Short terminal names (`st`) match whole words only, or every `com.system76.*` app id would read as a terminal- Linux: before any paste or selection-copy chord, `linux-fast-paste --capabilities --await-modifier-release <ms>` waits for physically held modifiers to be released (XKB state on X11, `EVIOCGKEY` on Wayland; `unknown` without `/dev/input` access pastes as before). A chord injected into held keys arrives as a different shortcut, and a virtual device cannot release another device's key (#2113). Still held after 1.5 s → not pasted, `reason: "modifiers-held"`, and the renderer shows the dictation-error pill with the transcript on the clipboard; a selection edit blocked the same way reports `code: "modifiers_held"` and gets the same pill (the assistant caret paste reports the same code, for logs only). `ydotoold`'s virtual keyboard is ignored, since an interrupted chord can leave its modifier down, and an unreadable key state is logged once per session. The wait runs before `pasteLinux` detects the target window, and a selection copy that had to wait looks the target up again, since focus can move while a key is held: a fresh capture then runs the command on its own (`focus_moved`), and a revalidated session declines as `target_changed`. Retry on a modifiers-held pill pastes the kept transcript again rather than recording again (the macOS/Windows push force-stop pill keeps its record-again Retry, since neither platform waits for held keys), ignores clicks while its paste is pending, and never dismisses a newer pill. `useAudioRecording` keeps the pill in processing until the paste attempt settles (the audio manager settles before the paste starts), but never reports that to main, which drops dictation hotkeys while processing; a paste held back after the next dictation started leaves the transcript on the clipboard without a pill. The helper measures its wait on `CLOCK_MONOTONIC`, since the JS watchdog kills it at timeout + 1 s- **database.js**: SQLite operations for transcription historydiff --git a/src/components/SettingsPage.tsx b/src/components/SettingsPage.tsxindex cf2766a43..117135c32 100644--- a/src/components/SettingsPage.tsx+++ b/src/components/SettingsPage.tsx@@ -1384,8 +1384,6 @@ export default function SettingsPage({isWlroots: boolean;isCosmic: boolean;requiresWlCopy: boolean;- hasXclip: boolean;- hasXsel: boolean;isNixOS: boolean;} | null>(null);const [ydotoolGuideKey, setYdotoolGuideKey] = useState<string | null>(null);@@ -3812,35 +3810,12 @@ EOF`,},];- if (ydotoolStatus.isKde) {- checks.push({- 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)",- }),- steps: [- {- title: t("settingsPage.general.waylandPaste.guide.xclip.step1Title", {- defaultValue: "Install xclip",- }),- cmds: [- { cmd: "sudo dnf install xclip # Fedora" },- { cmd: "sudo apt install xclip # Debian/Ubuntu" },- ],- },- ],- });- }-- if (ydotoolStatus.requiresWlCopy) {+ if (ydotoolStatus.requiresWlCopy || ydotoolStatus.isKde) {checks.push({key: "hasWlCopy",label: "wl-copy",ok: ydotoolStatus.hasWlCopy,- required: true,+ required: ydotoolStatus.requiresWlCopy || ydotoolStatus.isKde,desc: t("settingsPage.general.waylandPaste.wlCopyDesc"),steps: [{diff --git a/src/helpers/clipboard.js b/src/helpers/clipboard.jsindex 8ad3a8ecb..aba17dbf8 100644--- a/src/helpers/clipboard.js+++ b/src/helpers/clipboard.js@@ -159,40 +159,6 @@ class ClipboardManager {// True when wl-copy wrote the Wayland clipboard; every other path only reaches// XWayland's._writeClipboardWayland(text, webContents) {- const { isKde } = getLinuxSessionInfo();-- // On KDE with XWayland, write to X11 clipboard directly because- // wl-copy targets the Wayland clipboard which is desynced from X11- if (isKde) {- if (this.commandExists("xclip")) {- try {- const result = spawnSync("xclip", ["-selection", "clipboard"], {- input: text,- timeout: 200,- });- if (result.status === 0) {- clipboard.writeText(text);- return false;- }- } catch {}- }- if (this.commandExists("xsel")) {- try {- const result = spawnSync("xsel", ["--clipboard", "--input"], {- input: text,- timeout: 200,- });- if (result.status === 0) {- clipboard.writeText(text);- return false;- }- } catch {}- }- // Last resort: Electron's clipboard.writeText should work on XWayland- clipboard.writeText(text);- return false;- }-if (this._wlCopyExists()) {try {const result = spawnWlCopy([], text);@@ -218,14 +184,17 @@ class ClipboardManager {// target so we cover Wayland, X11, and XWayland setups. True when wl-copy wrote// the Wayland primary selection._writePrimarySelection(text) {- if (process.platform !== "linux") return false;-- const { isWayland } = getLinuxSessionInfo();+ const { isWayland, isKde } = getLinuxSessionInfo();+ if (process.platform !== "linux" && !isWayland) return false;if (isWayland && this.commandExists("wl-copy")) {try {const result = spawnWlCopy(["--primary"], text);- if (result.status === 0) return true;+ if (result.status === 0) {+ // KDE can leave XWayland's selection out of sync with Wayland's, so write both.+ if (isKde) clipboard.writeText(text, "selection");+ return true;+ }} catch {}}@@ -287,11 +256,11 @@ class ClipboardManager {return null;}- // `--type text` so a copied image never comes back as raw bytes.- _readWaylandClipboardText() {+ // A text type, so a copied image never comes back as raw bytes.+ _readWaylandClipboardText(type = "text") {if (!this._isWayland() || !this.commandExists("wl-paste")) return null;try {- const result = spawnSync("wl-paste", ["--no-newline", "--type", "text"], { timeout: 200 });+ const result = spawnSync("wl-paste", ["--no-newline", "--type", type], { timeout: 200 });if (result.status === 0) return result.stdout.toString();} catch {}return null;@@ -871,6 +840,14 @@ class ClipboardManager {}const keys = Object.keys(data);+ // A Wayland app's copy can leave an older X11 owner in place on KWin,+ // and the KDE restore writes the Wayland clipboard too. Plain text only: `--type text`+ // falls back to the html that Chromium offers with a copied image. A Wayland-only copy+ // with no plain text (a Spectacle screenshot) isn't saved, so it comes back as X11's text.+ if (keys.length > 0 && getLinuxSessionInfo().isKde) {+ const waylandText = this._readWaylandClipboardText("text/plain;charset=utf-8");+ if (waylandText && waylandText !== text) return { type: "text", data: waylandText };+ }if (keys.length === 1 && keys[0] === "image") {return { type: "image", data: data.image };}@@ -887,6 +864,11 @@ class ClipboardManager {_restoreClipboard(original) {if (!original) return;+ // The KDE save trusts Wayland text that differs from X11's, so replace the transcript or+ // sentinel left there. X11 goes last, so KWin 6.0.3+ bridges the rich original to Wayland.+ if (original.type !== "text" && getLinuxSessionInfo().isKde) {+ this._writeClipboardWayland(original.data.text ?? "");+ }if (original.type === "formats") {clipboard.write(original.data);} else if (original.type === "image") {diff --git a/src/helpers/ensureYdotool.js b/src/helpers/ensureYdotool.jsindex 84141924d..45f57091c 100644--- a/src/helpers/ensureYdotool.js+++ b/src/helpers/ensureYdotool.js@@ -205,7 +205,7 @@ function getYdotoolStatus() {hasYdotool,hasYdotoold,hasWtype,- hasWlCopy: requiresWlCopy && commandExists("wl-copy"),+ hasWlCopy: (requiresWlCopy || isKde) && commandExists("wl-copy"),daemonRunning,hasService,hasUinput,diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.jsindex 9a072ab62..340173915 100644--- a/src/helpers/ipcHandlers.js+++ b/src/helpers/ipcHandlers.js@@ -11074,23 +11074,7 @@ 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 } = getLinuxSessionInfo();- let hasXclip = false;- let hasXsel = false;- if (isKde) {- try {- execFileSync("which", ["xclip"], { timeout: 1000 });- hasXclip = true;- } catch {}- try {- execFileSync("which", ["xsel"], { timeout: 1000 });- hasXsel = true;- } catch {}- }- return { ...status, hasXclip, hasXsel };+ return getYdotoolStatus();});ipcMain.handle("get-debug-state", async () => {diff --git a/src/helpers/linuxSession.js b/src/helpers/linuxSession.jsindex f9ea1b9e8..edfb43aec 100644--- a/src/helpers/linuxSession.js+++ b/src/helpers/linuxSession.js@@ -30,9 +30,10 @@ function getLinuxSessionInfo(environment = process.env) {(isNamedWlroots || !!environment.SWAYSOCK || !!environment.HYPRLAND_INSTANCE_SIGNATURE);const isNiri = isWayland && desktopEnv.includes("niri");// wlroots, Hyprland and niri's xwayland-satellite hand an X11 clipboard write to- // Wayland apps only while an X11 window has focus (KWin, Mutter and COSMIC do it- // themselves), so the app's XWayland clipboard reaches a native Wayland app only- // through wl-copy. A stale SWAYSOCK or Hyprland signature alone doesn't count.+ // Wayland apps only while an X11 window has focus (Mutter, COSMIC and KWin 6.0.3++ // do it themselves, and KDE uses wl-copy when installed without requiring it), so+ // the app's XWayland clipboard reaches a native Wayland app only through wl-copy.+ // A stale SWAYSOCK or Hyprland signature alone doesn't count.const requiresWlCopy =isWayland && !isGnome && !isKde && !isCosmic && (isNamedWlroots || isSway || isNiri);diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.jsonindex a3f439a00..ffc5ea713 100644--- a/src/locales/ar/translation.json+++ b/src/locales/ar/translation.json@@ -3750,15 +3750,11 @@"step1Desc": "ابدأ ydotoold وقم بتمكينه ليعمل في كل عملية تسجيل دخول.","step2Title": "التحقق من أنه قيد التشغيل"},- "xclip": {- "step1Title": "تثبيت xclip"- },"wlCopy": {"step1Title": "تثبيت wl-clipboard","step2Title": "التحقق من التثبيت"}},- "xclipDesc": "أداة الحافظة للصق في KDE Wayland (xclip أو xsel)","nixos": {"intro": "أنت تستخدم NixOS. يتطلب اللصق التلقائي الوصول إلى ydotool و /dev/uinput، والذي يمنحه NixOS بشكل تصريحي.","detected": "تم الكشف عنه",diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 1d626a382..09ac080f3 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -2404,15 +2404,11 @@"step1Desc": "Starten Sie ydotoold und aktivieren Sie es für jeden Anmeldevorgang.","step2Title": "Prüfen, ob er läuft"},- "xclip": {- "step1Title": "xclip installieren"- },"wlCopy": {"step1Title": "wl-clipboard installieren","step2Title": "Installation überprüfen"}},- "xclipDesc": "Zwischenablage-Tool für KDE-Wayland-Einfügen (xclip oder xsel)","nixos": {"intro": "Sie verwenden NixOS. Für das automatische Einfügen werden ydotool und Zugriff auf /dev/uinput benötigt, was NixOS deklarativ gewährt.","detected": "Erkannt",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 70455c24f..4e5128801 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -2404,15 +2404,11 @@"step1Desc": "Start ydotoold and enable it so it runs on every login.","step2Title": "Verify it's running"},- "xclip": {- "step1Title": "Install xclip"- },"wlCopy": {"step1Title": "Install wl-clipboard","step2Title": "Verify installation"}},- "xclipDesc": "Clipboard tool for KDE Wayland paste (xclip or xsel)","nixos": {"intro": "You're on NixOS. Auto-paste needs ydotool and /dev/uinput access, which NixOS grants declaratively.","detected": "Detected",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 017cade55..bb02d616a 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -2162,15 +2162,11 @@"step1Desc": "Inicia ydotoold y habilítalo para que se ejecute en cada inicio de sesión.","step2Title": "Verificar que está en ejecución"},- "xclip": {- "step1Title": "Instalar xclip"- },"wlCopy": {"step1Title": "Instalar wl-clipboard","step2Title": "Verificar la instalación"}},- "xclipDesc": "Herramienta de portapapeles para pegado en KDE Wayland (xclip o xsel)","nixos": {"intro": "Estás en NixOS. El pegado automático necesita ydotool y acceso a /dev/uinput, que NixOS concede de forma declarativa.","detected": "Detectado",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 9368ed72c..b540ff070 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -2404,15 +2404,11 @@"step1Desc": "Démarrez ydotoold et activez-le pour qu'il se lance à chaque connexion.","step2Title": "Vérifier qu'il est en cours d'exécution"},- "xclip": {- "step1Title": "Installer xclip"- },"wlCopy": {"step1Title": "Installer wl-clipboard","step2Title": "Vérifier l'installation"}},- "xclipDesc": "Outil de presse-papiers pour le collage KDE Wayland (xclip ou xsel)","nixos": {"intro": "Vous êtes sur NixOS. Le collage automatique nécessite ydotool et l'accès à /dev/uinput, que NixOS accorde de façon déclarative.","detected": "Détecté",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 6e9f2dedd..5c41560b3 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -2110,15 +2110,11 @@"step1Desc": "Avvia ydotoold e abilitalo per l'esecuzione a ogni accesso.","step2Title": "Verifica che sia in esecuzione"},- "xclip": {- "step1Title": "Installa xclip"- },"wlCopy": {"step1Title": "Installa wl-clipboard","step2Title": "Verifica l'installazione"}},- "xclipDesc": "Strumento appunti per incollare in KDE Wayland (xclip o xsel)","nixos": {"intro": "Stai usando NixOS. L'incolla automatico richiede ydotool e l'accesso a /dev/uinput, che NixOS gestisce in modo dichiarativo.","detected": "Rilevato",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex 50c9d5049..2bafec59a 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -2110,15 +2110,11 @@"step1Desc": "ydotoold を起動し、毎回のログイン時に実行されるよう有効化します。","step2Title": "実行中か確認"},- "xclip": {- "step1Title": "xclipをインストール"- },"wlCopy": {"step1Title": "wl-clipboard をインストール","step2Title": "インストールの確認"}},- "xclipDesc": "KDE Waylandの貼り付け用クリップボードツール(xclipまたはxsel)","nixos": {"intro": "NixOSをお使いです。自動貼り付けにはydotoolと/dev/uinputへのアクセスが必要で、NixOSでは宣言的に設定できます。","detected": "検出済み",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex a5b674b00..548badabb 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -2089,15 +2089,11 @@"step1Desc": "Inicie o ydotoold e ative-o para que seja executado em cada início de sessão.","step2Title": "Verificar se está em execução"},- "xclip": {- "step1Title": "Instalar xclip"- },"wlCopy": {"step1Title": "Instalar o wl-clipboard","step2Title": "Verificar a instalação"}},- "xclipDesc": "Ferramenta de área de transferência para colar no KDE Wayland (xclip ou xsel)","nixos": {"intro": "Está no NixOS. A colagem automática requer ydotool e acesso a /dev/uinput, que o NixOS concede de forma declarativa.","detected": "Detetado",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex c17247669..40f6b5740 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -2114,15 +2114,11 @@"step1Desc": "Запустите ydotoold и включите его автозапуск при каждом входе.","step2Title": "Проверить, что он работает"},- "xclip": {- "step1Title": "Установить xclip"- },"wlCopy": {"step1Title": "Установить wl-clipboard","step2Title": "Проверить установку"}},- "xclipDesc": "Инструмент буфера обмена для вставки в KDE Wayland (xclip или xsel)","nixos": {"intro": "Вы используете NixOS. Для автоматической вставки требуются ydotool и доступ к /dev/uinput — NixOS предоставляет это декларативно.","detected": "Обнаружено",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 766e4fa35..16747cee9 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -2110,15 +2110,11 @@"step1Desc": "启动 ydotoold 并设置为每次登录时自动运行。","step2Title": "验证是否正在运行"},- "xclip": {- "step1Title": "安装 xclip"- },"wlCopy": {"step1Title": "安装 wl-clipboard","step2Title": "验证安装"}},- "xclipDesc": "KDE Wayland 粘贴用的剪贴板工具(xclip 或 xsel)","nixos": {"intro": "您正在使用 NixOS。自动粘贴需要 ydotool 和 /dev/uinput 访问权限,NixOS 通过声明式配置来授予这些权限。","detected": "已检测到",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex a58678d70..9784697ab 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -2110,15 +2110,11 @@"step1Desc": "啟動 ydotoold 並設定為每次登入時自動執行。","step2Title": "驗證是否正在執行"},- "xclip": {- "step1Title": "安裝 xclip"- },"wlCopy": {"step1Title": "安裝 wl-clipboard","step2Title": "驗證安裝"}},- "xclipDesc": "KDE Wayland 貼上用的剪貼簿工具(xclip 或 xsel)","nixos": {"intro": "你正在使用 NixOS。自動貼上需要 ydotool 及 /dev/uinput 存取權限,NixOS 以宣告式方式授予這些權限。","detected": "已偵測",diff --git a/src/types/electron.ts b/src/types/electron.tsindex fd4c107aa..277611f55 100644--- a/src/types/electron.ts+++ b/src/types/electron.ts@@ -2349,8 +2349,6 @@ declare global {isWlroots: boolean;isCosmic: boolean;requiresWlCopy: boolean;- hasXclip: boolean;- hasXsel: boolean;}>;// Globe key listener for hotkey capture (macOS only)diff --git a/test/helpers/clipboardRestore.test.js b/test/helpers/clipboardRestore.test.jsindex 734c8b292..f08b004c1 100644--- a/test/helpers/clipboardRestore.test.js+++ b/test/helpers/clipboardRestore.test.js@@ -17,13 +17,14 @@ const fakeClipboard = {readText() {return this.text;},- writeText(text) {+ writeText(text, type) {+ this.writes.push(["writeText", text, type]);+ if (type === "selection") return;this.text = text;this.html = "";this.rtf = "";this.image = null;this.formats = ["text/plain"];- this.writes.push(["writeText", text]);},readHTML() {return this.html;@@ -145,6 +146,13 @@ function createSpawn(calls, exitCodes, { stdout = [] } = {}) {};}+function createSpawnSync(calls) {+ return function mockedSpawnSync(command, args = []) {+ calls.push({ command, args });+ return { status: 0, stdout: Buffer.from("") };+ };+}+async function withWaylandEnvironment(desktop, callback) {const previous = {XDG_SESSION_TYPE: process.env.XDG_SESSION_TYPE,@@ -290,12 +298,142 @@ test("a clipboard XWayland can read is saved without asking wl-paste", async (t)const manager = new Manager();manager.commandExists = (command) => command === "wl-paste";- const snapshot = await withWaylandEnvironment("KDE", () => manager._saveClipboard());+ const snapshot = await withWaylandEnvironment("GNOME", () => manager._saveClipboard());assert.deepEqual(snapshot, { type: "text", data: "readable over X11" });assert.deepEqual(spawnSyncCalls, []);});+// KWin can leave an older X11 owner in place after a Wayland app copies, so+// the X11 clipboard can be older than the Wayland one the KDE restore writes. A current+// X11 owner's text is what wl-paste reads, and an image has no plain text to read, even+// with the html Chromium offers beside it.+const WAYLAND_COPY = "copied in a Wayland app";+const IMAGE_MARKUP = '<img src="https://example.com/a.png">';+for (const { owner, x11, wayland, saved } of [+ {+ owner: "a stale X11 text owner",+ x11: { text: "stale X11 text" },+ wayland: { plain: WAYLAND_COPY },+ saved: { type: "text", data: WAYLAND_COPY },+ },+ {+ owner: "a stale X11 rich-text owner",+ x11: { formats: ["text/html", "text/plain"], text: "stale X11 text", html: "<b>stale</b>" },+ wayland: { plain: WAYLAND_COPY },+ saved: { type: "text", data: WAYLAND_COPY },+ },+ {+ owner: "a stale X11 image owner",+ x11: { formats: ["image/png"], image: nonEmptyImage },+ wayland: { plain: WAYLAND_COPY },+ saved: { type: "text", data: WAYLAND_COPY },+ },+ {+ owner: "a current rich-text owner",+ x11: { formats: ["text/html", "text/plain"], text: "current", html: "<b>current</b>" },+ wayland: { plain: "current" },+ saved: { type: "formats", data: { text: "current", html: "<b>current</b>" } },+ },+ {+ owner: "a current image owner",+ x11: { formats: ["image/png"], image: nonEmptyImage },+ wayland: {},+ saved: { type: "image", data: nonEmptyImage },+ },+ {+ owner: "a Chromium copied image",+ x11: { formats: ["image/png", "text/html"], html: IMAGE_MARKUP, image: nonEmptyImage },+ wayland: { html: IMAGE_MARKUP },+ saved: { type: "formats", data: { html: IMAGE_MARKUP, image: nonEmptyImage } },+ },+]) {+ test(`a KDE clipboard held by ${owner} is saved as ${saved.type}`, async (t) => {+ const platform = Object.getOwnPropertyDescriptor(process, "platform");+ Object.defineProperty(process, "platform", { value: "linux" });+ t.after(() => Object.defineProperty(process, "platform", platform));+ resetClipboard(x11);+ // `--type text` falls back to any text type; an exact type matches only itself.+ const Manager = loadClipboardManager({+ spawnSync: (command, args) => {+ const text = args.at(-1) === "text" ? (wayland.plain ?? wayland.html) : wayland.plain;+ return { status: text === undefined ? 1 : 0, stdout: Buffer.from(text ?? "") };+ },+ });+ const manager = new Manager();+ manager.commandExists = (command) => command === "wl-paste";++ const snapshot = await withWaylandEnvironment("KDE", () => manager._saveClipboard());++ assert.deepEqual(snapshot, saved);+ });+}++// A rich or image restore writes X11 only, so on KWin before 6.0.3 the text the app put on+// Wayland stays there, and the next KDE save would take it for a newer copy.+const RICH_COPY = { formats: ["text/html", "text/plain"], text: "user copy", html: "<b>user</b>" };+for (const { original, x11, when, writeAppText } of [+ {+ original: "rich",+ x11: RICH_COPY,+ when: "a dictation",+ writeAppText: (manager) => manager._writeClipboardWayland("dictated text"),+ },+ {+ original: "rich",+ x11: RICH_COPY,+ when: "a selection capture",+ writeAppText: (manager) => manager._writeClipboardTextAll("__OPENWHISPR_SELECTION_test__"),+ },+ {+ original: "image",+ x11: { formats: ["image/png"], image: nonEmptyImage },+ when: "a dictation",+ writeAppText: (manager) => manager._writeClipboardWayland("dictated text"),+ },+]) {+ test(`a KDE ${original} clipboard restored after ${when} is saved again unchanged`, async (t) => {+ const platform = Object.getOwnPropertyDescriptor(process, "platform");+ Object.defineProperty(process, "platform", { value: "linux" });+ t.after(() => Object.defineProperty(process, "platform", platform));+ resetClipboard(x11);+ let waylandText = x11.text ?? null;+ const Manager = loadClipboardManager({+ spawnSync: (command, args) => {+ if (command === "wl-copy" && !args.includes("--primary")) waylandText = args.at(-1);+ return waylandText === null+ ? { status: 1, stdout: Buffer.from("") }+ : { status: 0, stdout: Buffer.from(waylandText) };+ },+ });+ const manager = new Manager();+ manager.commandExists = (command) => command === "wl-copy" || command === "wl-paste";++ await withWaylandEnvironment("KDE", () => {+ const saved = manager._saveClipboard();+ writeAppText(manager);+ manager._restoreClipboard(saved);++ assert.deepEqual(manager._saveClipboard(), saved);+ });+ });+}++test("a rich or image restore off KDE writes X11 only", async () => {+ const spawnSyncCalls = [];+ const Manager = loadClipboardManager({ spawnSync: createSpawnSync(spawnSyncCalls) });+ const manager = new Manager();+ manager.commandExists = (command) => command === "wl-copy";+ resetClipboard();++ await withWaylandEnvironment("GNOME", () => {+ manager._restoreClipboard({ type: "formats", data: RICH_COPY });+ manager._restoreClipboard({ type: "image", data: nonEmptyImage });+ });++ assert.deepEqual(spawnSyncCalls, []);+});+test("an empty clipboard on X11 is saved without asking wl-paste", async (t) => {const platform = Object.getOwnPropertyDescriptor(process, "platform");Object.defineProperty(process, "platform", { value: "linux" });@@ -1606,3 +1744,68 @@ test("clipboard write failure is never classified as an Accessibility denial", areturn true;});});++test("_writeClipboardWayland on KDE writes wl-copy (Wayland) and Electron's X11 clipboard", async () => {+ const spawnSyncCalls = [];+ const TestClipboardManager = loadClipboardManager({+ spawnSync: createSpawnSync(spawnSyncCalls),+ });+ const manager = new TestClipboardManager();+ manager.commandExists = (cmd) => ["wl-copy", "xclip"].includes(cmd);+ resetClipboard();++ await withWaylandEnvironment("KDE", async () => {+ manager._writeClipboardWayland("dictated KDE text");+ });++ assert.deepEqual(+ spawnSyncCalls.map((call) => [call.command, call.args]),+ [["wl-copy", ["--", "dictated KDE text"]]]+ );+ assert.equal(fakeClipboard.text, "dictated KDE text");+});++test("_writeClipboardWayland on KDE uses renderer fallback when wl-copy is unavailable", async () => {+ const spawnSyncCalls = [];+ const TestClipboardManager = loadClipboardManager({+ spawnSync: createSpawnSync(spawnSyncCalls),+ });+ const manager = new TestClipboardManager();+ manager.commandExists = (cmd) => cmd === "xclip";+ resetClipboard();++ let rendererWritten = null;+ const webContents = {+ isDestroyed: () => false,+ executeJavaScript: async (code) => {+ rendererWritten = code;+ },+ };++ await withWaylandEnvironment("KDE", async () => {+ manager._writeClipboardWayland("dictated KDE text", webContents);+ });++ assert.equal(rendererWritten.includes("dictated KDE text"), true);+ assert.equal(fakeClipboard.text, "dictated KDE text");+});++test("_writePrimarySelection on KDE mirrors wl-copy to Electron's X11 selection", async () => {+ const spawnSyncCalls = [];+ const TestClipboardManager = loadClipboardManager({+ spawnSync: createSpawnSync(spawnSyncCalls),+ });+ const manager = new TestClipboardManager();+ manager.commandExists = (cmd) => ["wl-copy", "xclip"].includes(cmd);+ resetClipboard();++ await withWaylandEnvironment("KDE", async () => {+ manager._writePrimarySelection("selection text");+ });++ assert.deepEqual(+ spawnSyncCalls.map((call) => [call.command, call.args]),+ [["wl-copy", ["--primary", "--", "selection text"]]]+ );+ assert.deepEqual(fakeClipboard.writes, [["writeText", "selection text", "selection"]]);+});