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): bind GNOME F13-F24 hotkeys to the keysym the keymap gives them (#2622)
void24e845d03bb2
diff --git a/CLAUDE.md b/CLAUDE.mdindex 6c344bd43..d9723e742 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -631,6 +631,7 @@ On GNOME Wayland, Electron's `globalShortcut` API doesn't work due to Wayland's- Electron format: `F8`, `CommandOrControl+Shift+Space`- GNOME format: `F8`, `<Control><Shift>space`- Backtick (`) → `grave` in GNOME keysym format+- F13-F24 bind the keysym the active keymap gives that key (`xkbcomp -xkb $DISPLAY -`, xkb keys `<FK13>`-`<FK24>`), for gsettings and the Hold portal alike: stock xkeyboard-config sends `XF86Launch7` for F16 and has no `F16` keysym, so GNOME can't grab `F16` (#1716). A key with no keysym (`keysym_missing`, e.g. stock F19/F24) or one gsd-media-keys already binds (`keysym_reserved`, e.g. F13 → `XF86Tools` opens Settings) is refused with a message. An unreadable keymap keeps the F-key name### 15. Hyprland Wayland Global Hotkeysdiff --git a/src/helpers/gnomeShortcut.js b/src/helpers/gnomeShortcut.jsindex 7e26c4f62..711883ab5 100644--- a/src/helpers/gnomeShortcut.js+++ b/src/helpers/gnomeShortcut.js@@ -110,6 +110,48 @@ const SHIFTED_PUNCTUATION_TO_GNOME_KEY_MAP = {"/": "question",};+// F13-F24 at the end of a GNOME accelerator ("<Control>F16") or a portal trigger ("CTRL+F16").+const EXTENDED_FUNCTION_KEY = /(?<=^|[>+])F(1[3-9]|2[0-4])$/;+const KEYMAP_QUERY_TIMEOUT_MS = 3000;++// The keysym the active keymap gives an xkb key name ("FK16"), null when the key has none,+// or undefined when the keymap can't be read. xkbcomp ships with XWayland (x11-xkb-utils).+function readKeymapKeysym(keyName) {+ const display = process.env.DISPLAY;+ if (!display) return undefined;+ let keymap;+ try {+ keymap = execFileSync("xkbcomp", ["-xkb", display, "-"], {+ encoding: "utf-8",+ stdio: "pipe",+ timeout: KEYMAP_QUERY_TIMEOUT_MS,+ });+ } catch (err) {+ debugLogger.log("[GnomeShortcut] Could not read the keymap with xkbcomp:", err.message);+ return undefined;+ }+ if (!keymap.includes("xkb_symbols")) return undefined;+ // "key <FK16> { [ XF86Launch7 ] };" or "symbols[Group1]= [ XF86TouchpadOff, ... ]" inside a+ // multi-line entry, never another field's list such as actions[Group1]; a key with no+ // keysym has no entry at all.+ const entry = new RegExp(+ `key <${keyName}>\\s*\\{(?:[^}]*?symbols\\[[^\\]]*\\]\\s*=)?\\s*\\[\\s*([^\\s,\\]]+)`+ ).exec(keymap);+ return entry && entry[1] !== "NoSymbol" ? entry[1] : null;+}++// For comparison: <Primary> and <Ctrl> mean <Control>, modifier order and case don't matter.+function normalizeAccelerator(accelerator) {+ const mods = [];+ const key = accelerator.replace(/<(\w+)>/gi, (_, mod) => {+ const name = mod.toLowerCase();+ mods.push(name === "primary" || name === "ctrl" ? "control" : name);+ return "";+ });+ mods.sort();+ return mods.map((m) => `<${m}>`).join("") + key.toLowerCase();+}+let dbus = null;function getDBus() {@@ -275,15 +317,23 @@ class GnomeShortcutManager {async registerPushToTalk(hotkey, callback) {const preferredTrigger = GnomeShortcutManager.convertToPortalFormat(hotkey);if (!preferredTrigger) return false;+ const tapShortcut = GnomeShortcutManager.convertToGnomeFormat(hotkey);+ const resolved = this.resolveFunctionKey(tapShortcut);+ const { keysym, reason } = resolved;+ if (reason) {+ debugLogger.log(+ `[GnomeShortcut] GNOME can't grab "${tapShortcut}" for Hold with this keymap: ${reason}`+ );+ return reason;+ }await this.unregisterKeybinding("dictation");const registered = await this.globalShortcutsPortal.registerKeybinding(- preferredTrigger,+ keysym ? preferredTrigger.replace(EXTENDED_FUNCTION_KEY, keysym) : preferredTrigger,callback);if (!registered) {- const tapShortcut = GnomeShortcutManager.convertToGnomeFormat(hotkey);- await this.registerKeybinding(tapShortcut, "dictation");+ await this.registerKeybinding(tapShortcut, "dictation", resolved);}return registered;}@@ -299,7 +349,8 @@ class GnomeShortcutManager {return VALID_SHORTCUT_PATTERN.test(shortcut);}- async registerKeybinding(shortcut = "<Alt>r", slotName = "dictation") {+ // resolved: resolveFunctionKey(shortcut) when the caller already has it.+ async registerKeybinding(shortcut = "<Alt>r", slotName = "dictation", resolved) {if (!GnomeShortcutManager.isGnome()) {debugLogger.log("[GnomeShortcut] Not running on GNOME, skipping registration");return false;@@ -312,6 +363,15 @@ class GnomeShortcutManager {return false;}+ const { keysym, reason } = resolved ?? this.resolveFunctionKey(shortcut);+ if (reason) {+ debugLogger.log(+ `[GnomeShortcut] GNOME can't grab "${shortcut}" for slot "${slotName}" with this keymap: ${reason}`+ );+ return reason;+ }+ const binding = keysym ? shortcut.replace(EXTENDED_FUNCTION_KEY, keysym) : shortcut;+const { path: keybindingPath, name: keybindingName } = getSlotConfig(slotName);const SLOT_DBUS_METHOD = {@@ -329,14 +389,14 @@ class GnomeShortcutManager {// Check if another custom shortcut already uses this bindingdebugLogger.log("[GnomeShortcut] Checking for conflicts", {- shortcut,+ shortcut: binding,existingPaths: existing,ownPath: keybindingPath,});- const conflict = this.findConflictingBinding(shortcut, existing, keybindingPath);+ const conflict = this.findConflictingBinding(binding, existing, keybindingPath);if (conflict) {debugLogger.log(- `[GnomeShortcut] Shortcut conflict — "${shortcut}" already used by "${conflict}"`,+ `[GnomeShortcut] Shortcut conflict — "${binding}" already used by "${conflict}"`,{slot: slotName,conflictPath: conflict,@@ -352,7 +412,7 @@ class GnomeShortcutManager {);execFileSync("gsettings",- ["set", `${KEYBINDING_SCHEMA}:${keybindingPath}`, "binding", shortcut],+ ["set", `${KEYBINDING_SCHEMA}:${keybindingPath}`, "binding", binding],{ stdio: "pipe" });execFileSync(@@ -378,7 +438,7 @@ class GnomeShortcutManager {this.registeredSlots.add(slotName);debugLogger.log(- `[GnomeShortcut] Keybinding "${shortcut}" registered for slot "${slotName}" successfully`+ `[GnomeShortcut] Keybinding "${binding}" registered for slot "${slotName}" successfully`);return true;} catch (err) {@@ -441,18 +501,43 @@ class GnomeShortcutManager {}}+ // Stock xkeyboard-config gives the F13-F24 keys XF86 keysyms (F16 sends XF86Launch7) and+ // no F13-F24 keysym at all, and GNOME can only grab a keysym the keymap carries. Returns+ // the keysym to bind instead, the reason GNOME can't grab the key, or {} to keep it.+ resolveFunctionKey(accelerator) {+ const match = EXTENDED_FUNCTION_KEY.exec(accelerator);+ if (!match) return {};+ const keysym = readKeymapKeysym(`FK${match[1]}`);+ if (keysym === undefined || keysym === match[0]) return {};+ if (keysym === null) return { reason: "keysym_missing" };+ if (this.isMediaKeyBinding(accelerator.replace(EXTENDED_FUNCTION_KEY, keysym))) {+ return { reason: "keysym_reserved" };+ }+ return { keysym };+ }++ // gsd-media-keys already grabs the hardware keys GNOME handles itself (XF86Tools opens+ // Settings, XF86AudioMicMute mutes the mic), so a custom shortcut on one never fires.+ isMediaKeyBinding(accelerator) {+ let settings;+ try {+ settings = execFileSync(+ "gsettings",+ ["list-recursively", "org.gnome.settings-daemon.plugins.media-keys"],+ { encoding: "utf-8" }+ );+ } catch (err) {+ debugLogger.log("[GnomeShortcut] Failed to read GNOME media key bindings:", err.message);+ return false;+ }+ const target = normalizeAccelerator(accelerator);+ return [...settings.matchAll(/'([^']*)'/g)].some(+ ([, binding]) => normalizeAccelerator(binding) === target+ );+ }+findConflictingBinding(shortcut, existingPaths, ownPath) {- // Normalize for comparison: <Primary> = <Control>, sort modifiers, case-insensitive- const normalize = (s) => {- const mods = [];- const stripped = s.replace(/<(\w+)>/gi, (_, m) => {- mods.push(m.toLowerCase() === "primary" ? "control" : m.toLowerCase());- return "";- });- mods.sort();- return mods.map((m) => `<${m}>`).join("") + stripped.toLowerCase();- };- const normalizedShortcut = normalize(shortcut);+ const normalizedShortcut = normalizeAccelerator(shortcut);for (const path of existingPaths) {if (path === ownPath) continue;@@ -464,7 +549,7 @@ class GnomeShortcutManager {).trim().replace(/^'|'$/g, "");- if (normalize(binding) === normalizedShortcut) return path;+ if (normalizeAccelerator(binding) === normalizedShortcut) return path;} catch {}}return null;diff --git a/src/helpers/hotkeyManager.js b/src/helpers/hotkeyManager.jsindex 13979427d..62ce31c83 100644--- a/src/helpers/hotkeyManager.js+++ b/src/helpers/hotkeyManager.js@@ -33,6 +33,12 @@ const KDE_FAILURE_REASONS = {"modifier-only": (hotkey) => i18nMain.t("hotkey.errors.osReserved", { hotkey }),};+// Why GNOME can't grab a key the active keymap maps elsewhere (see gnomeShortcut.js)+const GNOME_FAILURE_REASONS = {+ keysym_missing: (hotkey) => i18nMain.t("hotkey.errors.keyNotInKeymap", { hotkey }),+ keysym_reserved: (hotkey) => i18nMain.t("hotkey.errors.keyReservedByGnome", { hotkey }),+};+// Right-side single modifiers are handled by native listeners, not globalShortcutconst RIGHT_SIDE_MODIFIER_PATTERN =/^Right(Control|Ctrl|Alt|Option|Shift|Command|Cmd|Super|Meta|Win)$/i;@@ -266,8 +272,6 @@ class HotkeyManager extends EventEmitter {};}- this.unregisterSlot(slotName);-if (slotName === "meeting") {this.gnomeManager.setMeetingCallback(callback);} else if (slotName === "voiceAgent") {@@ -276,14 +280,16 @@ class HotkeyManager extends EventEmitter {this.gnomeManager.setTranslationCallback(callback);}- const success = await this.gnomeManager.registerKeybinding(gnomeHotkey, slotName);- if (!success) {+ const result = await this.gnomeManager.registerKeybinding(gnomeHotkey, slotName);+ if (result !== true) {debugLogger.log(`[HotkeyManager] GNOME keybinding registration failed for slot "${slotName}" ("${hotkey}")`);return {success: false,- error: i18nMain.t("hotkey.errors.registrationFailed", { hotkey }),+ error:+ GNOME_FAILURE_REASONS[result]?.(hotkey) ||+ i18nMain.t("hotkey.errors.registrationFailed", { hotkey }),};}@@ -572,20 +578,21 @@ class HotkeyManager extends EventEmitter {return true;}- let success = true;+ let result = true;try {if (this.useGnome && this.gnomeManager && hotkey && callback) {- success = await this.registerGnomeDictationHotkey(hotkey, callback, nextMode);+ result = await this.registerGnomeDictationHotkey(hotkey, callback, nextMode);} else if (this.useHyprland && this.hyprlandManager && hotkey) {- success = await this.hyprlandManager.updateKeybinding(hotkey, nextMode === "push");- if (!success) {+ result = await this.hyprlandManager.updateKeybinding(hotkey, nextMode === "push");+ if (!result) {await this.hyprlandManager.updateKeybinding(hotkey, previousMode === "push");}}} catch (err) {debugLogger.warn("[HotkeyManager] Failed to change activation mode:", err.message);- success = false;+ result = false;}+ const success = result === true;if (!success &&@@ -598,7 +605,7 @@ class HotkeyManager extends EventEmitter {) {try {const restored = await this.registerGnomeDictationHotkey(hotkey, callback, "push");- if (!restored) {+ if (restored !== true) {debugLogger.warn("[HotkeyManager] Could not restore GNOME push-to-talk binding");}} catch (err) {@@ -612,7 +619,9 @@ class HotkeyManager extends EventEmitter {if (!success) {if (hotkey) {this.notifyHotkeyFailure(hotkey, {- error: i18nMain.t("hotkey.errors.registrationFailed", { hotkey }),+ error:+ GNOME_FAILURE_REASONS[result]?.(hotkey) ||+ i18nMain.t("hotkey.errors.registrationFailed", { hotkey }),});}return false;@@ -1066,14 +1075,14 @@ class HotkeyManager extends EventEmitter {try {const hotkey = await this.getSavedDictationHotkey();this.nativeRegistrationPending = false;- const success = await this.registerGnomeDictationHotkey(hotkey, callback);- if (success) {+ const result = await this.registerGnomeDictationHotkey(hotkey, callback);+ if (result === true) {this.currentHotkey = hotkey;this.notifyActiveHotkey(hotkey);debugLogger.log(`[HotkeyManager] GNOME hotkey "${hotkey}" registered successfully`);} else {const ok = await this.tryNativeFallbacks(hotkey, "GNOME", (fb) =>- this.registerGnomeDictationHotkey(fb, callback)+ this.registerGnomeDictationHotkey(fb, callback).then((r) => r === true));if (!ok) {this.useGnome = false;@@ -1534,11 +1543,13 @@ class HotkeyManager extends EventEmitter {if (this.useGnome && this.gnomeManager) {debugLogger.log(`[HotkeyManager] Updating GNOME hotkey to "${primary}"`);- const success = await this.registerGnomeDictationHotkey(primary, callback);- if (!success) {+ const result = await this.registerGnomeDictationHotkey(primary, callback);+ if (result !== true) {return {success: false,- message: i18nMain.t("hotkey.errors.updateFailedCheckFormat", { hotkey: primary }),+ message:+ GNOME_FAILURE_REASONS[result]?.(primary) ||+ i18nMain.t("hotkey.errors.updateFailedCheckFormat", { hotkey: primary }),};}this.currentHotkey = primary;diff --git a/src/locales/ar/translation.json b/src/locales/ar/translation.jsonindex 83c893639..c37d85097 100644--- a/src/locales/ar/translation.json+++ b/src/locales/ar/translation.json@@ -4216,6 +4216,8 @@"mouseButtonOnlyMac": "اختصارات أزرار الماوس مدعومة حاليًا على نظام macOS فقط.","alreadyRegistered": "\"{{hotkey}}\" مسجل بالفعل بواسطة تطبيق آخر.","osReserved": "قد يكون \"{{hotkey}}\" محجوزًا بواسطة بيئة سطح المكتب لديك.",+ "keyNotInKeymap": "لا يمكن لـ GNOME استخدام \"{{hotkey}}\" مع تخطيط لوحة المفاتيح الحالي. اختر مفتاحًا آخر.",+ "keyReservedByGnome": "يستخدم GNOME بالفعل \"{{hotkey}}\" لأحد اختصاراته الخاصة. اختر مفتاحًا آخر.","rightModifierNeedsListener": "لا يمكن استخدام \"{{hotkey}}\" على سطح المكتب هذا، إذ تحتاج اختصاراته إلى مفتاح عادي. أضف مفتاحًا، مثل Control+Alt+Space.","holdNeedsReleaseKey": "يحتاج الضغط المستمر للتحدث إلى مفتاح يمكن لـ macOS أن يرصد تحريره: Globe، أو مفتاح جانبي أيمن مثل Option الأيمن، أو اختصار مع مفتاح تعديل. أما النقر فيعمل مع أي مفتاح.","holdNeedsRegularKey": "لاستخدام «استمرار الضغط»، أضف مفتاحًا عاديًا إلى الاختصار، مثل Control+Alt+Space. لا يستطيع سطح المكتب لديك رصد الضغط المستمر على مفاتيح التعديل وحدها.",diff --git a/src/locales/de/translation.json b/src/locales/de/translation.jsonindex 00b99bb8c..96bb823c4 100644--- a/src/locales/de/translation.json+++ b/src/locales/de/translation.json@@ -121,6 +121,8 @@"mouseButtonOnlyMac": "Maustasten-Hotkeys werden derzeit nur auf macOS unterstützt.","alreadyRegistered": "\"{{hotkey}}\" ist bereits von einer anderen Anwendung registriert.","osReserved": "\"{{hotkey}}\" ist möglicherweise von Ihrer Desktop-Umgebung reserviert.",+ "keyNotInKeymap": "GNOME kann „{{hotkey}}“ mit Ihrer Tastaturbelegung nicht verwenden. Wählen Sie eine andere Taste.",+ "keyReservedByGnome": "GNOME verwendet „{{hotkey}}“ bereits für eines seiner eigenen Tastenkürzel. Wählen Sie eine andere Taste.","rightModifierNeedsListener": "„{{hotkey}}“ kann auf diesem Desktop nicht verwendet werden, da seine Tastenkürzel eine normale Taste benötigen. Fügen Sie eine Taste hinzu, z. B. Control+Alt+Space.","holdNeedsReleaseKey": "Halten zum Sprechen braucht eine Taste, deren Loslassen macOS erkennt: Globe, eine rechte Taste wie Rechte Option oder ein Kürzel mit Modifikator. Tippen funktioniert mit jeder Taste.","holdNeedsRegularKey": "Um Halten zu nutzen, fügen Sie dem Kürzel eine normale Taste hinzu, z. B. Control+Alt+Space. Ihr Desktop kann das Halten reiner Modifikatortasten nicht melden.",diff --git a/src/locales/en/translation.json b/src/locales/en/translation.jsonindex 087fec25b..951f66534 100644--- a/src/locales/en/translation.json+++ b/src/locales/en/translation.json@@ -121,6 +121,8 @@"mouseButtonOnlyMac": "Mouse button hotkeys are currently supported on macOS only.","alreadyRegistered": "\"{{hotkey}}\" is already registered by another application.","osReserved": "\"{{hotkey}}\" may be reserved by your desktop environment.",+ "keyNotInKeymap": "GNOME can't use \"{{hotkey}}\" with your keyboard layout. Choose another key.",+ "keyReservedByGnome": "GNOME already uses \"{{hotkey}}\" for one of its own shortcuts. Choose another key.","rightModifierNeedsListener": "\"{{hotkey}}\" can't be used on this desktop, whose shortcuts need a regular key. Add a key, such as Control+Alt+Space.","holdNeedsReleaseKey": "Hold-to-talk needs a key macOS can see you release: Globe, a right-side key like Right Option, or a shortcut with a modifier. Tap works with any key.","holdNeedsRegularKey": "To use Hold, add a regular key to the shortcut, such as Control+Alt+Space. Your desktop can't report holding modifier keys alone.",diff --git a/src/locales/es/translation.json b/src/locales/es/translation.jsonindex 2784544cb..8d1d1c125 100644--- a/src/locales/es/translation.json+++ b/src/locales/es/translation.json@@ -121,6 +121,8 @@"mouseButtonOnlyMac": "Los atajos con botones del ratón solo son compatibles con macOS por ahora.","alreadyRegistered": "\"{{hotkey}}\" ya está registrada por otra aplicación.","osReserved": "\"{{hotkey}}\" puede estar reservada por tu entorno de escritorio.",+ "keyNotInKeymap": "GNOME no puede usar \"{{hotkey}}\" con tu distribución de teclado. Elige otra tecla.",+ "keyReservedByGnome": "GNOME ya usa \"{{hotkey}}\" para uno de sus propios atajos. Elige otra tecla.","rightModifierNeedsListener": "\"{{hotkey}}\" no se puede usar en este escritorio, cuyos atajos necesitan una tecla normal. Añade una tecla, como Control+Alt+Space.","holdNeedsReleaseKey": "Mantener para hablar necesita una tecla cuya liberación macOS pueda detectar: Globo, una tecla derecha como Opción derecha o un atajo con modificador. Pulsar funciona con cualquier tecla.","holdNeedsRegularKey": "Para usar Mantener, añade una tecla normal al atajo, como Control+Alt+Space. Tu escritorio no puede detectar cuándo mantienes pulsadas solo teclas modificadoras.",diff --git a/src/locales/fr/translation.json b/src/locales/fr/translation.jsonindex 8fbe481ca..d5f302fac 100644--- a/src/locales/fr/translation.json+++ b/src/locales/fr/translation.json@@ -121,6 +121,8 @@"mouseButtonOnlyMac": "Les raccourcis avec les boutons de la souris ne sont actuellement pris en charge que sur macOS.","alreadyRegistered": "\"{{hotkey}}\" est déjà enregistré par une autre application.","osReserved": "\"{{hotkey}}\" peut être réservé par votre environnement de bureau.",+ "keyNotInKeymap": "GNOME ne peut pas utiliser « {{hotkey}} » avec votre disposition de clavier. Choisissez une autre touche.",+ "keyReservedByGnome": "GNOME utilise déjà « {{hotkey}} » pour l’un de ses propres raccourcis. Choisissez une autre touche.","rightModifierNeedsListener": "« {{hotkey}} » ne peut pas être utilisé sur ce bureau, dont les raccourcis exigent une touche normale. Ajoutez une touche, par exemple Control+Alt+Space.","holdNeedsReleaseKey": "Maintenir pour parler nécessite une touche dont macOS détecte le relâchement : Globe, une touche droite comme Option droite, ou un raccourci avec modificateur. Appuyer fonctionne avec n’importe quelle touche.","holdNeedsRegularKey": "Pour utiliser le mode Maintenir, ajoutez une touche normale au raccourci, par exemple Control+Alt+Space. Votre bureau ne peut pas signaler le maintien de touches de modification seules.",diff --git a/src/locales/it/translation.json b/src/locales/it/translation.jsonindex 01862e5ce..63ce83044 100644--- a/src/locales/it/translation.json+++ b/src/locales/it/translation.json@@ -121,6 +121,8 @@"mouseButtonOnlyMac": "Le scorciatoie con i tasti del mouse sono attualmente supportate solo su macOS.","alreadyRegistered": "\"{{hotkey}}\" è già registrata da un'altra applicazione.","osReserved": "\"{{hotkey}}\" potrebbe essere riservata dal sistema operativo.",+ "keyNotInKeymap": "GNOME non può usare \"{{hotkey}}\" con il tuo layout di tastiera. Scegli un altro tasto.",+ "keyReservedByGnome": "GNOME usa già \"{{hotkey}}\" per una delle sue scorciatoie. Scegli un altro tasto.","rightModifierNeedsListener": "\"{{hotkey}}\" non può essere usato su questo desktop, le cui scorciatoie richiedono un tasto normale. Aggiungi un tasto, ad esempio Control+Alt+Space.","holdNeedsReleaseKey": "Tieni premuto per parlare richiede un tasto di cui macOS rilevi il rilascio: Globo, un tasto destro come Opzione destra o una scorciatoia con modificatore. Tocca funziona con qualsiasi tasto.","holdNeedsRegularKey": "Per usare Tieni premuto, aggiungi un tasto normale alla scorciatoia, ad esempio Control+Alt+Space. Il desktop non può rilevare la pressione prolungata dei soli tasti modificatori.",diff --git a/src/locales/ja/translation.json b/src/locales/ja/translation.jsonindex 9d7eb89fb..77799c52e 100644--- a/src/locales/ja/translation.json+++ b/src/locales/ja/translation.json@@ -121,6 +121,8 @@"mouseButtonOnlyMac": "マウスボタンのホットキーは現在 macOS でのみサポートされています。","alreadyRegistered": "\"{{hotkey}}\" は別のアプリケーションで既に登録されています。","osReserved": "\"{{hotkey}}\" はデスクトップ環境で予約されている可能性があります。",+ "keyNotInKeymap": "GNOME は現在のキーボードレイアウトでは \"{{hotkey}}\" を使用できません。別のキーを選んでください。",+ "keyReservedByGnome": "GNOME はすでに \"{{hotkey}}\" を独自のショートカットに使用しています。別のキーを選んでください。","rightModifierNeedsListener": "\"{{hotkey}}\" はこのデスクトップでは使用できません。ショートカットには通常のキーが必要です。Control+Alt+Space のようにキーを追加してください。","holdNeedsReleaseKey": "ホールドして話すには、macOS が離したことを検知できるキーが必要です。Globe、右 Option のような右側のキー、または修飾キー付きのショートカットです。タップならどのキーでも使えます。","holdNeedsRegularKey": "ホールドを使うには、Control+Alt+Space のようにショートカットに通常のキーを追加してください。デスクトップは修飾キーだけを押し続けていることを検知できません。",diff --git a/src/locales/pt/translation.json b/src/locales/pt/translation.jsonindex c44b74e31..6cac76ade 100644--- a/src/locales/pt/translation.json+++ b/src/locales/pt/translation.json@@ -121,6 +121,8 @@"mouseButtonOnlyMac": "Atalhos com botões do mouse atualmente são compatíveis apenas no macOS.","alreadyRegistered": "\"{{hotkey}}\" já está registrada por outro aplicativo.","osReserved": "\"{{hotkey}}\" pode estar reservada pelo seu ambiente de desktop.",+ "keyNotInKeymap": "O GNOME não consegue usar \"{{hotkey}}\" com o seu layout de teclado. Escolha outra tecla.",+ "keyReservedByGnome": "O GNOME já usa \"{{hotkey}}\" para um dos seus próprios atalhos. Escolha outra tecla.","rightModifierNeedsListener": "\"{{hotkey}}\" não pode ser usada neste ambiente de trabalho, cujos atalhos precisam de uma tecla normal. Adicione uma tecla, como Control+Alt+Space.","holdNeedsReleaseKey": "Segurar para falar precisa de uma tecla cuja soltura o macOS detecte: Globo, uma tecla direita como Option direita ou um atalho com modificador. Tocar funciona com qualquer tecla.","holdNeedsRegularKey": "Para usar Segurar, adicione uma tecla normal ao atalho, como Control+Alt+Space. O ambiente de desktop não consegue detectar quando você segura apenas teclas modificadoras.",diff --git a/src/locales/ru/translation.json b/src/locales/ru/translation.jsonindex 316c1a7fe..b25c3a85b 100644--- a/src/locales/ru/translation.json+++ b/src/locales/ru/translation.json@@ -121,6 +121,8 @@"mouseButtonOnlyMac": "Горячие клавиши на кнопках мыши в настоящее время поддерживаются только на macOS.","alreadyRegistered": "«{{hotkey}}» уже зарегистрирована другим приложением.","osReserved": "«{{hotkey}}» может быть зарезервирована вашей операционной системой.",+ "keyNotInKeymap": "GNOME не может использовать «{{hotkey}}» с вашей раскладкой клавиатуры. Выберите другую клавишу.",+ "keyReservedByGnome": "GNOME уже использует «{{hotkey}}» для одного из своих сочетаний клавиш. Выберите другую клавишу.","rightModifierNeedsListener": "«{{hotkey}}» нельзя использовать в этой среде рабочего стола: её сочетаниям клавиш нужна обычная клавиша. Добавьте клавишу, например Control+Alt+Space.","holdNeedsReleaseKey": "Для удержания нужна клавиша, отпускание которой macOS может заметить: Globe, правая клавиша вроде правого Option или сочетание с модификатором. Нажатие работает с любой клавишей.","holdNeedsRegularKey": "Чтобы использовать режим «Удержание», добавьте в сочетание обычную клавишу, например Control+Alt+Space. Среда рабочего стола не может сообщить об удержании одних только клавиш-модификаторов.",diff --git a/src/locales/zh-CN/translation.json b/src/locales/zh-CN/translation.jsonindex 11b7971be..f0ea269e6 100644--- a/src/locales/zh-CN/translation.json+++ b/src/locales/zh-CN/translation.json@@ -121,6 +121,8 @@"mouseButtonOnlyMac": "鼠标按键快捷键目前仅在 macOS 上受支持。","alreadyRegistered": "\"{{hotkey}}\" 已被其他应用注册。","osReserved": "\"{{hotkey}}\" 可能被系统保留。",+ "keyNotInKeymap": "GNOME 无法在当前键盘布局下使用 \"{{hotkey}}\"。请选择其他按键。",+ "keyReservedByGnome": "GNOME 已将 \"{{hotkey}}\" 用于自身的快捷键。请选择其他按键。","rightModifierNeedsListener": "\"{{hotkey}}\" 无法在此桌面上使用,其快捷键需要包含一个普通按键。请添加一个按键,例如 Control+Alt+Space。","holdNeedsReleaseKey": "按住说话需要 macOS 能检测到松开的按键:Globe、右侧 Option 之类的右侧按键,或带修饰键的快捷键。点按可用于任何按键。","holdNeedsRegularKey": "要使用按住模式,请在快捷键中添加一个普通按键,例如 Control+Alt+Space。桌面环境无法检测仅按住修饰键的操作。",diff --git a/src/locales/zh-TW/translation.json b/src/locales/zh-TW/translation.jsonindex 980e1cc3c..42e58ed87 100644--- a/src/locales/zh-TW/translation.json+++ b/src/locales/zh-TW/translation.json@@ -121,6 +121,8 @@"mouseButtonOnlyMac": "滑鼠按鍵快捷鍵目前僅在 macOS 上受支援。","alreadyRegistered": "\"{{hotkey}}\" 已被其他應用程式註冊。","osReserved": "\"{{hotkey}}\" 可能被你的作業系統保留。",+ "keyNotInKeymap": "GNOME 無法在目前的鍵盤配置下使用 \"{{hotkey}}\"。請選擇其他按鍵。",+ "keyReservedByGnome": "GNOME 已將 \"{{hotkey}}\" 用於自身的快捷鍵。請選擇其他按鍵。","rightModifierNeedsListener": "\"{{hotkey}}\" 無法在此桌面上使用,其快捷鍵需要包含一個一般按鍵。請加入一個按鍵,例如 Control+Alt+Space。","holdNeedsReleaseKey": "按住說話需要 macOS 能偵測到放開的按鍵:Globe、右側 Option 之類的右側按鍵,或帶修飾鍵的快速鍵。點按可用於任何按鍵。","holdNeedsRegularKey": "要使用按住模式,請在快捷鍵中加入一個一般按鍵,例如 Control+Alt+Space。桌面環境無法偵測僅按住修飾鍵的操作。",diff --git a/test/helpers/gnomeShortcutKeymap.test.js b/test/helpers/gnomeShortcutKeymap.test.jsnew file mode 100644index 000000000..6d3a752dd--- /dev/null+++ b/test/helpers/gnomeShortcutKeymap.test.js@@ -0,0 +1,256 @@+const test = require("node:test");+const assert = require("node:assert/strict");+const childProcess = require("node:child_process");+const Module = require("node:module");++const modulePath = require.resolve("../../src/helpers/gnomeShortcut");+const originalLoad = Module._load;++// `xkbcomp -xkb :0 -` on Ubuntu 26.04's stock keymap (xkb-data 2.46), trimmed to the+// F13-F24 keys: they carry XF86 keysyms, and F19 and F24 have no entry at all.+const STOCK_KEYMAP = [+ 'xkb_symbols "pc+us+inet(evdev)" {',+ " key <FK13> { [ XF86Tools ] };",+ " key <FK14> { [ XF86Launch5 ] };",+ " key <FK15> { [ XF86Launch6 ] };",+ " key <FK16> { [ XF86Launch7 ] };",+ " key <FK17> { [ XF86Launch8 ] };",+ " key <FK18> { [ XF86Launch9 ] };",+ " key <FK20> { [ XF86AudioMicMute ] };",+ " key <FK21> { [ XF86TouchpadToggle ] };",+ " key <FK22> { [ XF86TouchpadOn ] };",+ " key <FK23> {",+ ' type= "PC_SHIFT_SUPER_LEVEL2",',+ " symbols[Group1]= [ XF86TouchpadOff, XF86Assistant ]",+ " };",+ "};",+].join("\n");++// The same keys with the "Use F13-F24 as usual function keys" option (fkeys:basic_13-24).+const FKEYS_KEYMAP = [+ 'xkb_symbols "pc+us+inet(evdev)+fkeys(basic_13-24)" {',+ ...Array.from({ length: 12 }, (_, i) => ` key <FK${13 + i}> { [ F${13 + i} ] };`),+ "};",+].join("\n");++// `gsettings list-recursively` on the same machine, trimmed to the bindings that matter.+const MEDIA_KEYS = [+ "org.gnome.settings-daemon.plugins.media-keys control-center-static ['XF86Tools']",+ "org.gnome.settings-daemon.plugins.media-keys custom-keybindings @as []",+ "org.gnome.settings-daemon.plugins.media-keys mic-mute-static ['XF86AudioMicMute']",+ "org.gnome.settings-daemon.plugins.media-keys screensaver ['<Super>l']",+ "org.gnome.settings-daemon.plugins.media-keys touchpad-off-static ['XF86TouchpadOff']",+ "org.gnome.settings-daemon.plugins.media-keys touchpad-on-static ['XF86TouchpadOn']",+ "org.gnome.settings-daemon.plugins.media-keys touchpad-toggle-static ['XF86TouchpadToggle', '<Ctrl><Super>XF86TouchpadToggle']",+].join("\n");++// customBindings: other custom shortcuts already in gsettings, by path.+function loadManager({ keymap = STOCK_KEYMAP, customBindings = {} } = {}) {+ const calls = [];+ const paths = Object.keys(customBindings);+ const execFileSync = (command, args) => {+ calls.push([command, ...args]);+ if (command === "xkbcomp") {+ if (keymap instanceof Error) throw keymap;+ return keymap;+ }+ if (args[0] === "list-recursively") return MEDIA_KEYS;+ if (args[0] === "get" && args[2] === "custom-keybindings") {+ return paths.length ? `['${paths.join("', '")}']` : "@as []";+ }+ if (args[0] === "get" && args[2] === "binding") {+ return `'${customBindings[args[1].slice(args[1].indexOf(":") + 1)]}'`;+ }+ return "";+ };+ delete require.cache[modulePath];+ Module._load = function loadWithMocks(request, parent, isMain) {+ if (request === "child_process") return { ...childProcess, execFileSync };+ return originalLoad.call(this, request, parent, isMain);+ };+ try {+ const GnomeShortcutManager = require(modulePath);+ return { manager: new GnomeShortcutManager(), calls };+ } finally {+ Module._load = originalLoad;+ }+}++const writtenBinding = (calls) =>+ calls.find(+ ([command, verb, , key]) => command === "gsettings" && verb === "set" && key === "binding"+ )?.[4];+const readKeymap = (calls) => calls.some(([command]) => command === "xkbcomp");++const originalEnv = {+ XDG_CURRENT_DESKTOP: process.env.XDG_CURRENT_DESKTOP,+ DISPLAY: process.env.DISPLAY,+};+test.before(() => {+ process.env.XDG_CURRENT_DESKTOP = "ubuntu:GNOME";+ process.env.DISPLAY = ":0";+});+test.after(() => {+ for (const [name, value] of Object.entries(originalEnv)) {+ if (value === undefined) delete process.env[name];+ else process.env[name] = value;+ }+ delete require.cache[modulePath];+});++test("an F13-F24 key binds the keysym the stock keymap gives it", async () => {+ const { manager, calls } = loadManager();++ assert.equal(await manager.registerKeybinding("F16", "dictation"), true);+ assert.equal(writtenBinding(calls), "XF86Launch7");+});++test("modifiers stay on a remapped F13-F24 key", async () => {+ const { manager, calls } = loadManager();++ assert.equal(await manager.registerKeybinding("<Control><Shift>F15", "meeting"), true);+ assert.equal(writtenBinding(calls), "<Control><Shift>XF86Launch6");+});++test("a keymap that carries F13-F24 keysyms keeps the F-key name", async () => {+ const { manager, calls } = loadManager({ keymap: FKEYS_KEYMAP });++ assert.equal(await manager.registerKeybinding("F16", "dictation"), true);+ assert.equal(writtenBinding(calls), "F16");+});++test("a key with no keysym is refused before anything is written", async () => {+ const { manager, calls } = loadManager();++ assert.equal(await manager.registerKeybinding("F19", "dictation"), "keysym_missing");+ assert.equal(await manager.registerKeybinding("F24", "dictation"), "keysym_missing");+ assert.equal(writtenBinding(calls), undefined);+});++test("a keysym GNOME's media keys already grab is refused", async () => {+ const { manager, calls } = loadManager();++ // F13 sends XF86Tools, which opens Settings; F20 sends XF86AudioMicMute.+ assert.equal(await manager.registerKeybinding("F13", "dictation"), "keysym_reserved");+ assert.equal(await manager.registerKeybinding("F20", "dictation"), "keysym_reserved");+ // F23's multi-line entry sends XF86TouchpadOff first.+ assert.equal(await manager.registerKeybinding("F23", "dictation"), "keysym_reserved");+ // <Ctrl> in a gsd binding is <Control>, so this exact accelerator is taken too.+ assert.equal(+ await manager.registerKeybinding("<Control><Super>F21", "dictation"),+ "keysym_reserved"+ );+ assert.equal(writtenBinding(calls), undefined);+});++test("the same keysym with other modifiers is free", async () => {+ const { manager, calls } = loadManager();++ assert.equal(await manager.registerKeybinding("<Control>F13", "dictation"), true);+ assert.equal(writtenBinding(calls), "<Control>XF86Tools");+});++test("a custom shortcut on the keysym the key sends is a conflict", async () => {+ const other = "/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom0/";+ const { manager, calls } = loadManager({+ customBindings: { [other]: "XF86Launch7" },+ });++ assert.equal(await manager.registerKeybinding("F16", "dictation"), false);+ assert.equal(writtenBinding(calls), undefined);+});++test("a custom shortcut written with <Ctrl> conflicts with <Control>", async () => {+ const other = "/org/gnome/settings-daemon/plugins/media-keys/custom-keybindings/custom0/";+ const { manager, calls } = loadManager({ customBindings: { [other]: "<Ctrl>r" } });++ assert.equal(await manager.registerKeybinding("<Control>r", "dictation"), false);+ assert.equal(writtenBinding(calls), undefined);+});++test("only a key's symbols list is read, never another field's list", async () => {+ const keymap = [+ "xkb_symbols {",+ " key <FK16> {",+ " actions[Group1]= [ SetMods(modifiers=Shift) ],",+ " symbols[Group1]= [ XF86Launch7 ]",+ " };",+ "};",+ ].join("\n");+ const { manager, calls } = loadManager({ keymap });++ assert.equal(await manager.registerKeybinding("F16", "dictation"), true);+ assert.equal(writtenBinding(calls), "XF86Launch7");+});++test("without a DISPLAY the keymap isn't read and the F-key name is kept", async () => {+ process.env.DISPLAY = "";+ try {+ const { manager, calls } = loadManager();++ assert.equal(await manager.registerKeybinding("F16", "dictation"), true);+ assert.equal(writtenBinding(calls), "F16");+ assert.equal(readKeymap(calls), false);+ } finally {+ process.env.DISPLAY = ":0";+ }+});++test("an unreadable keymap keeps the F-key name", async () => {+ for (const keymap of [new Error("spawn xkbcomp ENOENT"), ""]) {+ const { manager, calls } = loadManager({ keymap });++ assert.equal(await manager.registerKeybinding("F16", "dictation"), true);+ assert.equal(writtenBinding(calls), "F16");+ }+});++test("keys outside F13-F24 never read the keymap", async () => {+ const { manager, calls } = loadManager();++ assert.equal(await manager.registerKeybinding("F8", "dictation"), true);+ assert.equal(await manager.registerKeybinding("<Alt>F1", "meeting"), true);+ assert.equal(readKeymap(calls), false);+});++test("Hold hands the portal the keysym", async () => {+ const { manager } = loadManager();+ const triggers = [];+ manager.globalShortcutsPortal = {+ registerKeybinding: async (trigger) => {+ triggers.push(trigger);+ return true;+ },+ unregisterKeybinding: async () => {},+ };++ assert.equal(await manager.registerPushToTalk("Control+F16", () => {}), true);+ assert.deepEqual(triggers, ["CTRL+XF86Launch7"]);+});++test("Hold falling back to Tap binds the keysym and reads the keymap once", async () => {+ const { manager, calls } = loadManager();+ manager.globalShortcutsPortal = {+ registerKeybinding: async () => false,+ unregisterKeybinding: async () => {},+ };++ assert.equal(await manager.registerPushToTalk("F16", () => {}), false);+ assert.equal(writtenBinding(calls), "XF86Launch7");+ assert.equal(calls.filter(([command]) => command === "xkbcomp").length, 1);+});++test("Hold refuses a key GNOME can't grab and keeps the Tap binding", async () => {+ const { manager, calls } = loadManager();+ manager.globalShortcutsPortal = {+ registerKeybinding: async () => assert.fail("the portal is never asked"),+ unregisterKeybinding: async () => {},+ };++ assert.equal(await manager.registerPushToTalk("F19", () => {}), "keysym_missing");+ assert.equal(await manager.registerPushToTalk("F13", () => {}), "keysym_reserved");+ const gsettingsWrites = calls.filter(+ ([command, verb]) => command === "gsettings" && (verb === "set" || verb === "reset")+ );+ assert.deepEqual(gsettingsWrites, []);+});diff --git a/test/helpers/hotkeyGnomeKeymapReasons.test.js b/test/helpers/hotkeyGnomeKeymapReasons.test.jsnew file mode 100644index 000000000..ca3a9b8e9--- /dev/null+++ b/test/helpers/hotkeyGnomeKeymapReasons.test.js@@ -0,0 +1,104 @@+const test = require("node:test");+const assert = require("node:assert/strict");++// GNOME's registration answers true, false, or why GNOME can't grab the key+// (gnomeShortcut.js resolveFunctionKey). A reason is not a success, and the+// user is told the reason instead of a generic failure.+require.cache[require.resolve("electron")] = {+ exports: {+ globalShortcut: { unregisterAll() {} },+ BrowserWindow: class {},+ },+};++const HotkeyManager = require("../../src/helpers/hotkeyManager.js");++const noop = () => {};+const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform");+test.before(() =>+ Object.defineProperty(process, "platform", { value: "linux", configurable: true })+);+test.after(() => Object.defineProperty(process, "platform", originalPlatform));++function gnomeManager(reason) {+ const mgr = new HotkeyManager();+ const failures = [];+ mgr.useGnome = true;+ mgr.gnomeManager = {+ registeredSlots: new Set(),+ supportsPushToTalk: () => true,+ registerKeybinding: async () => reason,+ registerPushToTalk: async () => reason,+ unregisterKeybinding: async () => true,+ unregisterPushToTalk: async () => {},+ setMeetingCallback() {},+ setVoiceAgentCallback() {},+ setTranslationCallback() {},+ };+ mgr.notifyHotkeyFailure = (hotkey, result) => failures.push({ hotkey, ...result });+ return { mgr, failures };+}++test("a dictation hotkey GNOME can't grab is refused with the keymap reason, in Tap and Hold", async () => {+ for (const mode of ["tap", "push"]) {+ const { mgr } = gnomeManager("keysym_missing");+ mgr.activationMode = mode;+ mgr.currentHotkey = "F8";++ const result = await mgr.updateHotkey("F19", noop);++ assert.equal(result.success, false, mode);+ assert.match(result.message, /keyboard layout/);+ assert.match(result.message, /"F19"/);+ assert.equal(mgr.currentHotkey, "F8");+ }+});++test("another slot's hotkey GNOME already uses is refused as reserved and keeps the slot's key", async () => {+ const { mgr } = gnomeManager("keysym_reserved");+ const unregistered = [];+ mgr.gnomeManager.registerKeybinding = async (shortcut) =>+ shortcut === "F9" ? true : "keysym_reserved";+ mgr.gnomeManager.unregisterKeybinding = async (slot) => {+ unregistered.push(slot);+ return true;+ };+ await mgr.registerSlot("meeting", "F9", noop);++ const result = await mgr.registerSlot("meeting", "F13", noop, { atomic: true });++ assert.equal(result.success, false);+ assert.match(result.error, /GNOME already uses/);+ assert.deepEqual(mgr.getSlotHotkeys("meeting"), ["F9"]);+ assert.deepEqual(unregistered, []);+});++test("switching to Hold on a key GNOME can't grab keeps Tap and says why", async () => {+ const { mgr, failures } = gnomeManager("keysym_reserved");+ mgr.activationMode = "tap";+ mgr.currentHotkey = "F13";+ mgr.hotkeyCallback = noop;++ assert.equal(await mgr.setActivationMode("push"), false);+ assert.equal(mgr.activationMode, "tap");+ assert.equal(failures.length, 1);+ assert.match(failures[0].error, /GNOME already uses/);+});++test("switching back to Tap on a key GNOME can't grab keeps Hold and says why", async () => {+ const { mgr, failures } = gnomeManager("keysym_missing");+ const holds = [];+ mgr.gnomeManager.registerPushToTalk = async (hotkey) => {+ holds.push(hotkey);+ return true;+ };+ mgr.activationMode = "push";+ mgr.currentHotkey = "F19";+ mgr.hotkeyCallback = noop;++ assert.equal(await mgr.setActivationMode("tap"), false);+ assert.equal(mgr.activationMode, "push");+ assert.deepEqual(holds, ["F19"]);+ assert.equal(failures.length, 1);+ assert.match(failures[0].error, /keyboard layout/);+});diff --git a/test/helpers/hotkeyStartup.test.js b/test/helpers/hotkeyStartup.test.jsindex ee12c0a64..bf52c008b 100644--- a/test/helpers/hotkeyStartup.test.js+++ b/test/helpers/hotkeyStartup.test.js@@ -215,6 +215,19 @@ for (const backend of ["GNOME", "Hyprland"]) {});}+// gnomeShortcut.js answers with a reason when the keymap leaves GNOME nothing to grab.+test("GNOME startup falls back to F8 when GNOME can't grab the saved key", async () => {+ const f = fixture("GNOME", "F19");+ const register = f.gnome.registerKeybinding;+ f.gnome.registerKeybinding = async (shortcut) =>+ shortcut === "F19" ? "keysym_missing" : register(shortcut);+ await f.manager.initializeHotkey(f.window, () => {});+ f.timers.shift().callback();+ for (let i = 0; i < 5; i++) await tick();+ assert.equal(f.manager.currentHotkey, "F8");+ assert.deepEqual(f.registrations, [{ hotkey: "F8", push: false }]);+});+// Without its evdev listener a Linux session cannot hold through globalShortcut.test("KDE that cannot register falls back to globalShortcut and checks Hold again", async () => {const f = fixture("KDE", "Scrolllock", false);