Skip to content

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

feat(hyprland): support both Lua and legacy configs (#1664)

Idris Gadi47da21d93221
diff --git a/src/helpers/hyprlandShortcut.js b/src/helpers/hyprlandShortcut.js
index e2bacc60e..e5f6ab5b3 100644
--- a/src/helpers/hyprlandShortcut.js
+++ b/src/helpers/hyprlandShortcut.js
@@ -45,19 +45,45 @@ const ELECTRON_TO_HYPRLAND_KEY = {
const VALID_HOTKEY_PATTERN =
/^((CommandOrControl|CmdOrCtrl|Control|Ctrl|Alt|Option|Shift|Super|Meta|Win|Command|Cmd)(\+(CommandOrControl|CmdOrCtrl|Control|Ctrl|Alt|Option|Shift|Super|Meta|Win|Command|Cmd))*(\+)?)?(F([1-9]|1[0-9]|2[0-4])|[A-Za-z0-9]|Space|Escape|Tab|Backspace|Delete|Insert|Home|End|PageUp|PageDown|ArrowUp|ArrowDown|ArrowLeft|ArrowRight|Enter|PrintScreen|ScrollLock|Pause|Backquote|`)?$/i;
-const BINDS_FILENAME = "openwhispr-binds.conf";
-const MANAGED_HEADER_LINES = [
- "# OpenWhispr keybinds (managed automatically)",
- "# If you delete this file, also remove the matching source line from your Hyprland config.",
+const BINDS_FILENAMES = {
+ conf: "openwhispr-binds.conf",
+ lua: "openwhispr-binds.lua",
+};
+const MANAGED_HEADER_TEXT = [
+ "OpenWhispr keybinds (managed automatically)",
+ "If you delete this file, also remove the matching load line from your Hyprland config.",
];
+const MANAGED_HEADER_VARIANTS = new Set([
+ ...MANAGED_HEADER_TEXT,
+ "If you delete this file, also remove the matching source line from your Hyprland config.",
+]);
function isManagedHeaderLine(line) {
- return MANAGED_HEADER_LINES.includes(line.trim());
+ return MANAGED_HEADER_VARIANTS.has(line.trim().replace(/^(#|--)\s*/, ""));
}
-function buildManagedBindsContent(lines = []) {
+function buildManagedBindsContent(lines = [], format = "conf") {
const body = lines.join("\n").trim();
- return MANAGED_HEADER_LINES.join("\n") + "\n" + (body ? body + "\n" : "");
+ const comment = format === "lua" ? "--" : "#";
+ const header = MANAGED_HEADER_TEXT.map((line) => `${comment} ${line}`).join("\n");
+ return header + "\n" + (body ? body + "\n" : "");
+}
+
+function buildLuaBindExpression(luaKeys, dbusCommand) {
+ return `hl.bind(${JSON.stringify(luaKeys)}, hl.dsp.exec_cmd(${JSON.stringify(dbusCommand)}))`;
+}
+
+function runHyprctl(args) {
+ const output = execFileSync("hyprctl", args, {
+ encoding: "utf8",
+ stdio: "pipe",
+ timeout: 5000,
+ });
+ const response = Buffer.isBuffer(output) ? output.toString("utf8").trim() : String(output).trim();
+
+ if (response !== "ok") {
+ throw new Error(response || `hyprctl ${args[0]} returned an empty response`);
+ }
}
function getHyprConfigDir() {
@@ -68,15 +94,52 @@ function getHyprConfigDir() {
return path.join(xdgConfigHome, "hypr");
}
-function getHyprlandConfPath() {
+let cachedHyprlandConfig = null;
+
+function getHyprlandConfig() {
+ if (cachedHyprlandConfig) return cachedHyprlandConfig;
+
if (process.env.HYPRLAND_CONFIG) {
- return path.resolve(process.env.HYPRLAND_CONFIG);
+ const configPath = path.resolve(process.env.HYPRLAND_CONFIG);
+ const format = path.extname(configPath).toLowerCase() === ".lua" ? "lua" : "conf";
+ cachedHyprlandConfig = {
+ path: configPath,
+ format,
+ bindsPath: getBindsFilePath(configPath, format),
+ };
+ return cachedHyprlandConfig;
}
- return path.join(getHyprConfigDir(), "hyprland.conf");
+
+ const configDir = getHyprConfigDir();
+ let format = "conf";
+ try {
+ const systemInfo = execFileSync("hyprctl", ["systeminfo"], {
+ encoding: "utf8",
+ stdio: "pipe",
+ timeout: 3000,
+ });
+ const provider = systemInfo.match(/configProvider:\s*(\S+)/i)?.[1]?.toLowerCase();
+ if (
+ provider === "lua" ||
+ (provider !== "hyprlang" && fs.existsSync(path.join(configDir, "hyprland.lua")))
+ ) {
+ format = "lua";
+ }
+ } catch {
+ if (fs.existsSync(path.join(configDir, "hyprland.lua"))) format = "lua";
+ }
+
+ const configPath = path.join(configDir, `hyprland.${format}`);
+ cachedHyprlandConfig = {
+ path: configPath,
+ format,
+ bindsPath: getBindsFilePath(configPath, format),
+ };
+ return cachedHyprlandConfig;
}
-function getBindsFilePath() {
- return path.join(getHyprConfigDir(), BINDS_FILENAME);
+function getBindsFilePath(configPath, format) {
+ return path.join(path.dirname(configPath), BINDS_FILENAMES[format]);
}
let dbus = null;
@@ -98,6 +161,7 @@ class HyprlandShortcutManager {
this.callback = null;
this.isRegistered = false;
this.currentBinding = null; // Store the current Hyprland bind string for unbinding
+ this.config = null;
}
/**
@@ -258,18 +322,18 @@ class HyprlandShortcutManager {
return {
mods: uniqueMods.join(" "),
key: key,
+ luaKeys: [...uniqueMods, key].filter(Boolean).join(" + ").toUpperCase(),
// Full bind key string for hyprctl keyword bind/unbind
bindKey: uniqueMods.length > 0 ? `${uniqueMods.join(" ")}, ${key}` : `, ${key}`,
};
}
- _writeBindToConfig(bindLine) {
- const bindsFile = getBindsFilePath();
- fs.mkdirSync(path.dirname(bindsFile), { recursive: true });
+ _writeBindToConfig(config, bindLine) {
+ fs.mkdirSync(path.dirname(config.bindsPath), { recursive: true });
let content = "";
try {
- content = fs.readFileSync(bindsFile, "utf-8");
+ content = fs.readFileSync(config.bindsPath, "utf-8");
} catch (err) {
if (err.code !== "ENOENT") throw err;
}
@@ -277,20 +341,19 @@ class HyprlandShortcutManager {
const lines = content.split("\n").filter((line) => {
const trimmed = line.trim();
if (!trimmed || isManagedHeaderLine(trimmed)) return false;
- if (trimmed.startsWith("#")) return true;
+ if (trimmed.startsWith("#") || trimmed.startsWith("--")) return true;
return !trimmed.includes(DBUS_SERVICE_NAME);
});
- const newContent = buildManagedBindsContent([...lines, bindLine]);
+ const newContent = buildManagedBindsContent([...lines, bindLine], config.format);
- fs.writeFileSync(bindsFile, newContent, "utf-8");
+ fs.writeFileSync(config.bindsPath, newContent, "utf-8");
}
- _removeBindFromConfig() {
- const bindsFile = getBindsFilePath();
+ _removeBindFromConfig(config) {
let content = "";
try {
- content = fs.readFileSync(bindsFile, "utf-8");
+ content = fs.readFileSync(config.bindsPath, "utf-8");
} catch (err) {
if (err.code === "ENOENT") return;
throw err;
@@ -299,33 +362,109 @@ class HyprlandShortcutManager {
const lines = content.split("\n").filter((line) => {
const trimmed = line.trim();
if (!trimmed || isManagedHeaderLine(trimmed)) return false;
- if (trimmed.startsWith("#")) return true;
+ if (trimmed.startsWith("#") || trimmed.startsWith("--")) return true;
return !trimmed.includes(DBUS_SERVICE_NAME);
});
- fs.writeFileSync(bindsFile, buildManagedBindsContent(lines), "utf-8");
+ fs.writeFileSync(config.bindsPath, buildManagedBindsContent(lines, config.format), "utf-8");
}
- _ensureSourceInMainConfig() {
- const mainConfig = getHyprlandConfPath();
+ _ensureSourceInMainConfig(config) {
let content;
try {
- content = fs.readFileSync(mainConfig, "utf-8");
+ content = fs.readFileSync(config.path, "utf-8");
} catch (err) {
- if (err.code === "ENOENT") return;
+ if (err.code === "ENOENT") return false;
throw err;
}
- const sourceLine = `source = ./${BINDS_FILENAME}`;
- if (content.includes(`./${BINDS_FILENAME}`)) return;
+ const sourceLine =
+ config.format === "lua"
+ ? `pcall(require, ${JSON.stringify(config.bindsPath)})`
+ : `source = ${config.bindsPath}`;
+ const lines = content.split("\n").filter((line) => {
+ if (!line.includes(BINDS_FILENAMES[config.format])) return true;
+ const trimmed = line.trim();
+ return config.format === "lua"
+ ? !/^(?:dofile|require)\s*\(|^pcall\s*\(\s*require\s*,/.test(trimmed)
+ : !/^source\s*=/.test(trimmed);
+ });
+
+ let insertionIndex = lines.length;
+ while (insertionIndex > 0 && lines[insertionIndex - 1] === "") insertionIndex -= 1;
+ if (config.format === "lua") {
+ let lastStatementIndex = insertionIndex - 1;
+ while (lastStatementIndex >= 0 && lines[lastStatementIndex].trim().startsWith("--")) {
+ lastStatementIndex -= 1;
+ }
+ if (/^return\b/.test((lines[lastStatementIndex] || "").trim())) {
+ insertionIndex = lastStatementIndex;
+ }
+ }
+ lines.splice(insertionIndex, 0, sourceLine);
+
+ const newContent = lines.join("\n");
+ if (newContent === content) return true;
- const separator = content.length > 0 && !content.endsWith("\n") ? "\n" : "";
- fs.appendFileSync(mainConfig, `${separator}${sourceLine}\n`, "utf-8");
- debugLogger.log("[HyprlandShortcut] Added source directive to hyprland.conf");
+ fs.writeFileSync(config.path, newContent, "utf-8");
+ debugLogger.log(`[HyprlandShortcut] Added binding load directive to ${config.path}`);
+ return true;
+ }
+
+ _removeLegacyArtifacts(config) {
+ if (config.format !== "lua") return;
+
+ const configDir = path.dirname(config.path);
+ const legacyConfigPath = path.join(configDir, "hyprland.conf");
+ const legacyBindsPath = path.join(configDir, BINDS_FILENAMES.conf);
+
+ try {
+ const content = fs.readFileSync(legacyConfigPath, "utf-8");
+ const newContent = content
+ .split("\n")
+ .filter((line) => {
+ const trimmed = line.trim();
+ return !(trimmed.includes(BINDS_FILENAMES.conf) && /^source\s*=/.test(trimmed));
+ })
+ .join("\n");
+ if (newContent !== content) fs.writeFileSync(legacyConfigPath, newContent, "utf-8");
+ } catch (err) {
+ if (err.code !== "ENOENT") throw err;
+ }
+
+ try {
+ const content = fs.readFileSync(legacyBindsPath, "utf-8");
+ if (content.includes(MANAGED_HEADER_TEXT[0]) || content.includes(DBUS_SERVICE_NAME)) {
+ fs.unlinkSync(legacyBindsPath);
+ }
+ } catch (err) {
+ if (err.code !== "ENOENT") throw err;
+ }
+ }
+
+ _getConfig() {
+ if (!this.config) this.config = getHyprlandConfig();
+ return this.config;
+ }
+
+ _unbindRuntime(config, binding) {
+ const args =
+ config.format === "lua"
+ ? ["eval", `hl.unbind(${JSON.stringify(binding)})`]
+ : ["keyword", "unbind", binding];
+ runHyprctl(args);
+ }
+
+ _bindRuntime(config, binding, bindValue, dbusCommand) {
+ const args =
+ config.format === "lua"
+ ? ["eval", buildLuaBindExpression(binding, dbusCommand)]
+ : ["keyword", "bind", bindValue];
+ runHyprctl(args);
}
static getHyprlandConfigStatus() {
- const mainConfig = getHyprlandConfPath();
+ const mainConfig = getHyprlandConfig().path;
const status = {
path: mainConfig,
canWrite: false,
@@ -347,11 +486,11 @@ class HyprlandShortcutManager {
}
/**
- * Register a keybinding in Hyprland using hyprctl keyword bind.
+ * Register a keybinding using the runtime API for the active config provider.
* The binding executes a dbus-send command that calls our Toggle() method.
*
- * Also writes the bind to openwhispr-binds.conf (sourced from hyprland.conf)
- * so it survives `hyprctl reload`.
+ * Also writes the bind to a format-specific config file so it survives
+ * `hyprctl reload`.
*/
async registerKeybinding(hotkey) {
if (!HyprlandShortcutManager.isHyprland()) {
@@ -371,39 +510,42 @@ class HyprlandShortcutManager {
}
try {
+ const config = this._getConfig();
+ const runtimeBinding = config.format === "lua" ? converted.luaKeys : converted.bindKey;
+
// First unregister any existing OpenWhispr binding if the hotkey changed.
- if (this.currentBinding && this.currentBinding !== converted.bindKey) {
- await this.unregisterKeybinding();
+ if (this.currentBinding && this.currentBinding !== runtimeBinding) {
+ const unregistered = await this.unregisterKeybinding();
+ if (!unregistered) return false;
}
const dbusCommand = `dbus-send --session --type=method_call --dest=${DBUS_SERVICE_NAME} ${DBUS_OBJECT_PATH} ${DBUS_INTERFACE}.Toggle`;
- // hyprctl keyword bind "MODS, key, exec, command"
+ // Legacy bind payload; Lua builds its expression from the same converted values.
const bindValue = `${converted.bindKey}, exec, ${dbusCommand}`;
try {
- execFileSync("hyprctl", ["keyword", "unbind", converted.bindKey], {
- stdio: "pipe",
- timeout: 5000,
- });
+ this._unbindRuntime(config, runtimeBinding);
} catch (err) {
debugLogger.log(
- `[HyprlandShortcut] Pre-bind unbind for "${converted.bindKey}" failed, continuing:`,
+ `[HyprlandShortcut] Pre-bind unbind for "${runtimeBinding}" failed, continuing:`,
err.message
);
}
- execFileSync("hyprctl", ["keyword", "bind", bindValue], {
- stdio: "pipe",
- timeout: 5000,
- });
+ this._bindRuntime(config, runtimeBinding, bindValue, dbusCommand);
- this.currentBinding = converted.bindKey;
+ this.currentBinding = runtimeBinding;
this.isRegistered = true;
try {
- this._writeBindToConfig(`bind = ${bindValue}`);
- this._ensureSourceInMainConfig();
+ const persistedBind =
+ config.format === "lua"
+ ? buildLuaBindExpression(converted.luaKeys, dbusCommand)
+ : `bind = ${bindValue}`;
+ this._writeBindToConfig(config, persistedBind);
+ const mainConfigFound = this._ensureSourceInMainConfig(config);
+ if (mainConfigFound) this._removeLegacyArtifacts(config);
} catch (err) {
debugLogger.log(
"[HyprlandShortcut] Failed to persist keybinding; runtime bind is still active:",
@@ -412,7 +554,7 @@ class HyprlandShortcutManager {
}
debugLogger.log(
- `[HyprlandShortcut] Keybinding "${hotkey}" (${converted.bindKey}) registered successfully`
+ `[HyprlandShortcut] Keybinding "${hotkey}" (${runtimeBinding}) registered successfully`
);
return true;
} catch (err) {
@@ -439,18 +581,17 @@ class HyprlandShortcutManager {
}
const binding = this.currentBinding;
+ const config = this._getConfig();
try {
- execFileSync("hyprctl", ["keyword", "unbind", binding], {
- stdio: "pipe",
- timeout: 5000,
- });
+ this._unbindRuntime(config, binding);
} catch (err) {
debugLogger.log(`[HyprlandShortcut] Runtime unbind for "${binding}" failed:`, err.message);
+ return false;
}
try {
- this._removeBindFromConfig();
+ this._removeBindFromConfig(config);
} catch (err) {
debugLogger.log("[HyprlandShortcut] Failed to remove persisted keybinding:", err.message);
}
diff --git a/test/helpers/hyprlandShortcut.test.js b/test/helpers/hyprlandShortcut.test.js
new file mode 100644
index 000000000..e66f7c20c
--- /dev/null
+++ b/test/helpers/hyprlandShortcut.test.js
@@ -0,0 +1,360 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const childProcess = require("node:child_process");
+const fs = require("node:fs");
+const Module = require("node:module");
+const os = require("node:os");
+const path = require("node:path");
+
+const modulePath = require.resolve("../../src/helpers/hyprlandShortcut");
+const originalLoad = Module._load;
+const ENV_KEYS = ["HYPRLAND_CONFIG", "HYPRLAND_INSTANCE_SIGNATURE", "XDG_CONFIG_HOME"];
+
+function loadManager(execFileSync) {
+ 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 {
+ return require(modulePath);
+ } finally {
+ Module._load = originalLoad;
+ }
+}
+
+function withTempHyprConfig(fn) {
+ return async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "openwhispr-hyprland-test-"));
+ const saved = Object.fromEntries(ENV_KEYS.map((key) => [key, process.env[key]]));
+ for (const key of ENV_KEYS) delete process.env[key];
+ process.env.XDG_CONFIG_HOME = path.join(root, "config");
+ process.env.HYPRLAND_INSTANCE_SIGNATURE = "test";
+ try {
+ await fn(path.join(process.env.XDG_CONFIG_HOME, "hypr"));
+ } finally {
+ for (const key of ENV_KEYS) {
+ if (saved[key] === undefined) delete process.env[key];
+ else process.env[key] = saved[key];
+ }
+ fs.rmSync(root, { recursive: true, force: true });
+ }
+ };
+}
+
+function successfulHyprctl(provider) {
+ const calls = [];
+ return {
+ calls,
+ execFileSync(command, args) {
+ calls.push({ command, args });
+ if (command === "hyprctl" && args[0] === "systeminfo") {
+ return `State:\n\nconfigProvider: ${provider}\n`;
+ }
+ return "ok\n";
+ },
+ };
+}
+
+const DBUS_COMMAND =
+ "dbus-send --session --type=method_call --dest=com.openwhispr.App /com/openwhispr/App com.openwhispr.App.Toggle";
+
+test(
+ "persists a legacy binding through hyprland.conf",
+ withTempHyprConfig(async (configDir) => {
+ const configPath = path.join(configDir, "hyprland.conf");
+ fs.mkdirSync(configDir, { recursive: true });
+ fs.writeFileSync(configPath, "# legacy config\n");
+ const hyprctl = successfulHyprctl("hyprlang");
+ const HyprlandShortcutManager = loadManager(hyprctl.execFileSync);
+
+ const manager = new HyprlandShortcutManager();
+ assert.equal(await manager.registerKeybinding("Control+Shift+Enter"), true);
+
+ assert.equal(HyprlandShortcutManager.getHyprlandConfigStatus().path, configPath);
+ assert.ok(
+ fs
+ .readFileSync(configPath, "utf8")
+ .includes(`source = ${path.join(configDir, "openwhispr-binds.conf")}\n`)
+ );
+ assert.match(
+ fs.readFileSync(path.join(configDir, "openwhispr-binds.conf"), "utf8"),
+ /bind = CTRL SHIFT, Return, exec, dbus-send/
+ );
+ assert.equal(await manager.unregisterKeybinding(), true);
+ assert.deepEqual(
+ hyprctl.calls.filter(({ args }) => args[0] === "keyword").map(({ args }) => args),
+ [
+ ["keyword", "unbind", "CTRL SHIFT, Return"],
+ ["keyword", "bind", `CTRL SHIFT, Return, exec, ${DBUS_COMMAND}`],
+ ["keyword", "unbind", "CTRL SHIFT, Return"],
+ ]
+ );
+ })
+);
+
+test(
+ "prefers Hyprland's active Lua config when both formats exist",
+ withTempHyprConfig(async (configDir) => {
+ const luaPath = path.join(configDir, "hyprland.lua");
+ fs.mkdirSync(configDir, { recursive: true });
+ fs.writeFileSync(path.join(configDir, "hyprland.conf"), "# legacy config\n");
+ fs.writeFileSync(luaPath, 'require("hypr.bindings")\n');
+ const hyprctl = successfulHyprctl("lua");
+ const HyprlandShortcutManager = loadManager(hyprctl.execFileSync);
+
+ const manager = new HyprlandShortcutManager();
+ assert.equal(hyprctl.calls.filter(({ args }) => args[0] === "systeminfo").length, 0);
+ assert.equal(await manager.registerKeybinding("Control+Shift+Enter"), true);
+ assert.equal(await manager.registerKeybinding("Control+Shift+Enter"), true);
+ assert.equal(hyprctl.calls.filter(({ args }) => args[0] === "systeminfo").length, 1);
+
+ assert.equal(HyprlandShortcutManager.getHyprlandConfigStatus().path, luaPath);
+ assert.match(fs.readFileSync(luaPath, "utf8"), /pcall\(require, .+openwhispr-binds\.lua/);
+ assert.equal(
+ (fs.readFileSync(luaPath, "utf8").match(/openwhispr-binds\.lua/g) || []).length,
+ 1
+ );
+ const binds = fs.readFileSync(path.join(configDir, "openwhispr-binds.lua"), "utf8");
+ assert.match(binds, /^-- OpenWhispr keybinds/m);
+ assert.match(binds, /hl\.bind\("CTRL \+ SHIFT \+ RETURN", hl\.dsp\.exec_cmd\("dbus-send/);
+ assert.doesNotMatch(
+ fs.readFileSync(path.join(configDir, "hyprland.conf"), "utf8"),
+ /openwhispr/
+ );
+ assert.equal(hyprctl.calls.filter(({ args }) => args[0] === "systeminfo").length, 1);
+ })
+);
+
+test(
+ "registers the default modifier-only hotkey through Lua eval",
+ withTempHyprConfig(async (configDir) => {
+ fs.mkdirSync(configDir, { recursive: true });
+ fs.writeFileSync(path.join(configDir, "hyprland.lua"), "-- lua config\n");
+ const hyprctl = successfulHyprctl("lua");
+ const HyprlandShortcutManager = loadManager(hyprctl.execFileSync);
+
+ const manager = new HyprlandShortcutManager();
+ assert.equal(await manager.registerKeybinding("Control+Super"), true);
+
+ const runtimeCalls = hyprctl.calls.filter(({ args }) => args[0] !== "systeminfo");
+ assert.deepEqual(
+ runtimeCalls.map(({ args }) => args),
+ [
+ ["eval", 'hl.unbind("CTRL + SUPER_L")'],
+ ["eval", `hl.bind("CTRL + SUPER_L", hl.dsp.exec_cmd(${JSON.stringify(DBUS_COMMAND)}))`],
+ ]
+ );
+ })
+);
+
+test(
+ "reuses each exact Lua key string when changing and unregistering a hotkey",
+ withTempHyprConfig(async (configDir) => {
+ fs.mkdirSync(configDir, { recursive: true });
+ fs.writeFileSync(path.join(configDir, "hyprland.lua"), "-- lua config\n");
+ const hyprctl = successfulHyprctl("lua");
+ const HyprlandShortcutManager = loadManager(hyprctl.execFileSync);
+ const manager = new HyprlandShortcutManager();
+
+ assert.equal(await manager.registerKeybinding("Control+Shift+Enter"), true);
+ assert.equal(await manager.updateKeybinding("Alt+PageUp"), true);
+ assert.equal(await manager.unregisterKeybinding(), true);
+
+ const evalExpressions = hyprctl.calls
+ .filter(({ args }) => args[0] === "eval")
+ .map(({ args }) => args[1]);
+ assert.deepEqual(evalExpressions, [
+ 'hl.unbind("CTRL + SHIFT + RETURN")',
+ `hl.bind("CTRL + SHIFT + RETURN", hl.dsp.exec_cmd(${JSON.stringify(DBUS_COMMAND)}))`,
+ 'hl.unbind("CTRL + SHIFT + RETURN")',
+ 'hl.unbind("ALT + PAGE_UP")',
+ `hl.bind("ALT + PAGE_UP", hl.dsp.exec_cmd(${JSON.stringify(DBUS_COMMAND)}))`,
+ 'hl.unbind("ALT + PAGE_UP")',
+ ]);
+ })
+);
+
+test(
+ "rejects a Hyprland error reply even when hyprctl exits successfully",
+ withTempHyprConfig(async (configDir) => {
+ fs.mkdirSync(configDir, { recursive: true });
+ fs.writeFileSync(path.join(configDir, "hyprland.lua"), "-- lua config\n");
+ const calls = [];
+ const HyprlandShortcutManager = loadManager((command, args) => {
+ calls.push({ command, args });
+ if (args[0] === "systeminfo") return "configProvider: lua\n";
+ return "keyword can't work with non-legacy parsers. Use eval.\n";
+ });
+
+ const manager = new HyprlandShortcutManager();
+ assert.equal(await manager.registerKeybinding("Control+Shift+Enter"), false);
+ assert.equal(manager.isRegistered, false);
+ assert.equal(manager.currentBinding, null);
+ assert.equal(fs.existsSync(path.join(configDir, "openwhispr-binds.lua")), false);
+ })
+);
+
+test(
+ "keeps a Lua binding registered when runtime unbind fails",
+ withTempHyprConfig(async (configDir) => {
+ fs.mkdirSync(configDir, { recursive: true });
+ fs.writeFileSync(path.join(configDir, "hyprland.lua"), "-- lua config\n");
+ let rejectUnbind = false;
+ const HyprlandShortcutManager = loadManager((command, args) => {
+ if (args[0] === "systeminfo") return "configProvider: lua\n";
+ if (rejectUnbind && args[1] === 'hl.unbind("CTRL + SHIFT + RETURN")') {
+ return "unbind failed\n";
+ }
+ return "ok\n";
+ });
+ const manager = new HyprlandShortcutManager();
+
+ assert.equal(await manager.registerKeybinding("Control+Shift+Enter"), true);
+ rejectUnbind = true;
+
+ assert.equal(await manager.unregisterKeybinding(), false);
+ assert.equal(manager.currentBinding, "CTRL + SHIFT + RETURN");
+ assert.equal(manager.isRegistered, true);
+ })
+);
+
+test(
+ "uses HYPRLAND_CONFIG for a Lua config without spawning systeminfo",
+ withTempHyprConfig(async (configDir) => {
+ const configPath = path.join(configDir, "dotfiles", "custom.lua");
+ fs.mkdirSync(path.dirname(configPath), { recursive: true });
+ fs.writeFileSync(configPath, "-- custom lua config\n");
+ process.env.HYPRLAND_CONFIG = configPath;
+ const hyprctl = successfulHyprctl("hyprlang");
+ const HyprlandShortcutManager = loadManager(hyprctl.execFileSync);
+ const manager = new HyprlandShortcutManager();
+
+ assert.equal(await manager.registerKeybinding("Control+Shift+Enter"), true);
+ assert.equal(HyprlandShortcutManager.getHyprlandConfigStatus().path, configPath);
+ assert.equal(hyprctl.calls.filter(({ args }) => args[0] === "systeminfo").length, 0);
+ assert.match(fs.readFileSync(configPath, "utf8"), /pcall\(require,/);
+ assert.equal(fs.existsSync(path.join(path.dirname(configPath), "openwhispr-binds.lua")), true);
+ })
+);
+
+test(
+ "falls back to an existing Lua config when systeminfo fails",
+ withTempHyprConfig(async (configDir) => {
+ const luaPath = path.join(configDir, "hyprland.lua");
+ fs.mkdirSync(configDir, { recursive: true });
+ fs.writeFileSync(luaPath, "-- lua config\n");
+ const calls = [];
+ const HyprlandShortcutManager = loadManager((command, args) => {
+ calls.push({ command, args });
+ if (args[0] === "systeminfo") throw new Error("hyprctl timed out");
+ return "ok\n";
+ });
+ const manager = new HyprlandShortcutManager();
+
+ assert.equal(calls.length, 0);
+ assert.equal(await manager.registerKeybinding("Control+Shift+Enter"), true);
+ assert.equal(calls.filter(({ args }) => args[0] === "systeminfo").length, 1);
+ assert.equal(calls.filter(({ args }) => args[0] === "eval").length, 2);
+ assert.equal(fs.existsSync(path.join(configDir, "openwhispr-binds.lua")), true);
+ })
+);
+
+test(
+ "falls back to an existing Lua config when systeminfo returns unusable output",
+ withTempHyprConfig(async (configDir) => {
+ fs.mkdirSync(configDir, { recursive: true });
+ fs.writeFileSync(path.join(configDir, "hyprland.lua"), "-- lua config\n");
+ const calls = [];
+ const HyprlandShortcutManager = loadManager((command, args) => {
+ calls.push({ command, args });
+ if (args[0] === "systeminfo") return "Hyprland IPC unavailable\n";
+ return "ok\n";
+ });
+
+ assert.equal(
+ await new HyprlandShortcutManager().registerKeybinding("Control+Shift+Enter"),
+ true
+ );
+ assert.equal(calls.filter(({ args }) => args[0] === "eval").length, 2);
+ assert.equal(calls.filter(({ args }) => args[0] === "keyword").length, 0);
+ })
+);
+
+test(
+ "replaces an old dofile loader before a trailing top-level return",
+ withTempHyprConfig(async (configDir) => {
+ const luaPath = path.join(configDir, "hyprland.lua");
+ const bindsPath = path.join(configDir, "openwhispr-binds.lua");
+ fs.mkdirSync(configDir, { recursive: true });
+ fs.writeFileSync(
+ luaPath,
+ `-- lua config\ndofile("${bindsPath}")\nreturn {}\n-- trailing comment\n`
+ );
+ const hyprctl = successfulHyprctl("lua");
+ const HyprlandShortcutManager = loadManager(hyprctl.execFileSync);
+
+ assert.equal(
+ await new HyprlandShortcutManager().registerKeybinding("Control+Shift+Enter"),
+ true
+ );
+
+ const content = fs.readFileSync(luaPath, "utf8");
+ const protectedLoader = `pcall(require, "${bindsPath}")`;
+ assert.doesNotMatch(content, /dofile\(/);
+ assert.equal((content.match(/openwhispr-binds\.lua/g) || []).length, 1);
+ assert.ok(content.indexOf(protectedLoader) < content.indexOf("return {}"));
+ })
+);
+
+test(
+ "removes the previous header wording when rewriting managed binds",
+ withTempHyprConfig(async (configDir) => {
+ const configPath = path.join(configDir, "hyprland.conf");
+ const bindsPath = path.join(configDir, "openwhispr-binds.conf");
+ fs.mkdirSync(configDir, { recursive: true });
+ fs.writeFileSync(configPath, "# legacy config\n");
+ fs.writeFileSync(
+ bindsPath,
+ "# OpenWhispr keybinds (managed automatically)\n" +
+ "# If you delete this file, also remove the matching source line from your Hyprland config.\n"
+ );
+ const hyprctl = successfulHyprctl("hyprlang");
+ const HyprlandShortcutManager = loadManager(hyprctl.execFileSync);
+
+ assert.equal(
+ await new HyprlandShortcutManager().registerKeybinding("Control+Shift+Enter"),
+ true
+ );
+
+ const content = fs.readFileSync(bindsPath, "utf8");
+ assert.doesNotMatch(content, /matching source line/);
+ assert.equal((content.match(/OpenWhispr keybinds/g) || []).length, 1);
+ })
+);
+
+test(
+ "removes stale managed legacy artifacts after migrating to Lua",
+ withTempHyprConfig(async (configDir) => {
+ const confPath = path.join(configDir, "hyprland.conf");
+ const legacyBindsPath = path.join(configDir, "openwhispr-binds.conf");
+ fs.mkdirSync(configDir, { recursive: true });
+ fs.writeFileSync(path.join(configDir, "hyprland.lua"), "-- lua config\n");
+ fs.writeFileSync(confPath, "# keep this comment\nsource = ./openwhispr-binds.conf\n");
+ fs.writeFileSync(
+ legacyBindsPath,
+ "# OpenWhispr keybinds (managed automatically)\n" +
+ `bind = CTRL SHIFT, Return, exec, ${DBUS_COMMAND}\n`
+ );
+ const hyprctl = successfulHyprctl("lua");
+ const HyprlandShortcutManager = loadManager(hyprctl.execFileSync);
+
+ assert.equal(
+ await new HyprlandShortcutManager().registerKeybinding("Control+Shift+Enter"),
+ true
+ );
+
+ assert.equal(fs.existsSync(legacyBindsPath), false);
+ assert.equal(fs.readFileSync(confPath, "utf8"), "# keep this comment\n");
+ })
+);