Skip to content

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

13.3 KB
Raw Blame
const debugLogger = require("./debugLogger");

let dbus = null;

function getDBus() {
  if (dbus) return dbus;
  try {
    dbus = require("@homebridge/dbus-native");
    return dbus;
  } catch (err) {
    debugLogger.log("[KDEShortcut] Failed to load dbus-native:", err.message);
    return null;
  }
}

// Qt::Key and Qt::KeyboardModifier values for KGlobalAccel
const QT_MODIFIERS = {
  control: 0x04000000,
  ctrl: 0x04000000,
  alt: 0x08000000,
  shift: 0x02000000,
  super: 0x10000000,
  meta: 0x10000000,
  commandorcontrol: 0x04000000,
};

const QT_KEYS = {
  a: 0x41,
  b: 0x42,
  c: 0x43,
  d: 0x44,
  e: 0x45,
  f: 0x46,
  g: 0x47,
  h: 0x48,
  i: 0x49,
  j: 0x4a,
  k: 0x4b,
  l: 0x4c,
  m: 0x4d,
  n: 0x4e,
  o: 0x4f,
  p: 0x50,
  q: 0x51,
  r: 0x52,
  s: 0x53,
  t: 0x54,
  u: 0x55,
  v: 0x56,
  w: 0x57,
  x: 0x58,
  y: 0x59,
  z: 0x5a,
  0: 0x30,
  1: 0x31,
  2: 0x32,
  3: 0x33,
  4: 0x34,
  5: 0x35,
  6: 0x36,
  7: 0x37,
  8: 0x38,
  9: 0x39,
  f1: 0x01000030,
  f2: 0x01000031,
  f3: 0x01000032,
  f4: 0x01000033,
  f5: 0x01000034,
  f6: 0x01000035,
  f7: 0x01000036,
  f8: 0x01000037,
  f9: 0x01000038,
  f10: 0x01000039,
  f11: 0x0100003a,
  f12: 0x0100003b,
  space: 0x20,
  tab: 0x01000001,
  escape: 0x01000000,
  backspace: 0x01000003,
  enter: 0x01000005,
  return: 0x01000004,
  insert: 0x01000006,
  delete: 0x01000007,
  home: 0x01000010,
  end: 0x01000011,
  pageup: 0x01000016,
  pagedown: 0x01000017,
  up: 0x01000013,
  down: 0x01000015,
  left: 0x01000012,
  right: 0x01000014,
  "`": 0x60,
  grave: 0x60,
  // Unshifted punctuation (Qt::Key_*). Same set GNOME maps to X11 keysyms.
  ",": 0x2c,
  ".": 0x2e,
  "/": 0x2f,
  "-": 0x2d,
  "=": 0x3d,
  ";": 0x3b,
  "'": 0x27,
  "\\": 0x5c,
  "[": 0x5b,
  "]": 0x5d,
  plus: 0x2b,
  print: 0x01000009,
  scrolllock: 0x01000026,
  pause: 0x01000008,
};

const COMPONENT_NAME = "openwhispr";

class KDEShortcutManager {
  constructor() {
    this.bus = null;
    this.kglobalaccel = null;
    this.componentProxy = null;
    this.callbacks = new Map();
    this.registeredSlots = new Set();
    // Set by HotkeyManager to debug-log each press and release: (slotName, action).
    this.onHotkeyEvent = null;
  }

  static isKDE() {
    const desktop = (process.env.XDG_CURRENT_DESKTOP || "").toLowerCase();
    return desktop.includes("kde");
  }

  static isWayland() {
    return process.env.XDG_SESSION_TYPE === "wayland";
  }

  static convertToQtKeyCode(electronHotkey) {
    const parts = electronHotkey.split("+");
    let qtKey = 0;

    for (const part of parts) {
      const lower = part.toLowerCase().trim();
      if (QT_MODIFIERS[lower]) {
        qtKey |= QT_MODIFIERS[lower];
      } else {
        const key = QT_KEYS[lower] || QT_KEYS[lower.replace("arrow", "")];
        if (key) {
          qtKey |= key;
        } else {
          debugLogger.log(`[KDEShortcut] Unknown key: "${part}"`);
          return null;
        }
      }
    }

    return qtKey;
  }

  async init() {
    const dbusModule = getDBus();
    if (!dbusModule) return false;

    try {
      this.bus = dbusModule.sessionBus();
      // Without a listener, async socket errors (e.g. a stale
      // DBUS_SESSION_BUS_ADDRESS) crash the process as an unhandled
      // "error" event — sessionBus() returns before connecting.
      this.bus.connection.on("error", (err) => {
        debugLogger.log("[KDEShortcut] D-Bus connection error:", err.message);
      });
      this.kglobalaccel = await new Promise((resolve, reject) => {
        this.bus
          .getService("org.kde.kglobalaccel")
          .getInterface("/kglobalaccel", "org.kde.KGlobalAccel", (err, iface) => {
            if (err) return reject(err);
            resolve(iface);
          });
      });

      debugLogger.log("[KDEShortcut] Connected to KGlobalAccel D-Bus");
      return true;
    } catch (err) {
      debugLogger.log("[KDEShortcut] Failed to connect:", err.message);
      this.bus = null;
      this.kglobalaccel = null;
      return false;
    }
  }

  async _listenForComponent() {
    if (this.componentProxy) return true;

    try {
      const componentPath = `/component/${COMPONENT_NAME}`;
      const iface = await new Promise((resolve, reject) => {
        this.bus
          .getService("org.kde.kglobalaccel")
          .getInterface(componentPath, "org.kde.kglobalaccel.Component", (err, ifc) => {
            if (err) return reject(err);
            resolve(ifc);
          });
      });

      iface.on("globalShortcutPressed", (componentUnique, shortcutUnique, timestamp) => {
        // KGlobalAccel signal sends the actionUnique value as shortcutUnique.
        // Direct callback lookup by slotName should match. Fallback maps
        // actionFriendly names for compatibility.
        const slotName = this._resolveSlotName(shortcutUnique);
        const callback = slotName ? this.callbacks.get(slotName) : null;
        if (callback) {
          this.onHotkeyEvent?.(slotName, "down");
          callback(undefined, "down");
        } else {
          debugLogger.log("[KDEShortcut] No callback found for", {
            shortcutUnique,
            registered: [...this.callbacks.keys()],
          });
        }
      });
      iface.on("globalShortcutReleased", (componentUnique, shortcutUnique) => {
        const slotName = this._resolveSlotName(shortcutUnique);
        if (slotName) this.onHotkeyEvent?.(slotName, "up");
        if (slotName !== "dictation") return;
        this.callbacks.get(slotName)?.(undefined, "up");
      });

      this.componentProxy = iface;
      debugLogger.log("[KDEShortcut] Listening for globalShortcutPressed on", componentPath);
      return true;
    } catch (err) {
      debugLogger.log("[KDEShortcut] Failed to listen on component:", err.message);
      return false;
    }
  }

  _resolveSlotName(shortcutUnique) {
    return this.callbacks.has(shortcutUnique)
      ? shortcutUnique
      : this._findSlotByFriendlyName(shortcutUnique);
  }

  _findSlotByFriendlyName(name) {
    // Map friendly names back to slot names
    const friendlyToSlot = {};
    for (const slotName of this.registeredSlots) {
      friendlyToSlot[`OpenWhispr ${slotName}`] = slotName;
      friendlyToSlot[`OpenWhispr`] = "dictation"; // legacy compat
    }
    return friendlyToSlot[name] || null;
  }

  async registerKeybinding(electronHotkey, slotName = "dictation", callback, isPushToTalk = false) {
    if (!this.kglobalaccel) return false;

    const qtKey = KDEShortcutManager.convertToQtKeyCode(electronHotkey);
    if (qtKey === null) {
      debugLogger.log(`[KDEShortcut] Could not convert "${electronHotkey}" to Qt key code`);
      return false;
    }

    // Modifier-only shortcuts (e.g. Control+Super) don't work on X11.
    // KWin accepts them on Wayland, but emits press and release together after
    // the first modifier is released, so they cannot represent push-to-talk.
    const QT_MODIFIER_MASK = 0xfe000000;
    const isModifierOnly = (qtKey & ~QT_MODIFIER_MASK) === 0;
    const modifierOnlyUnsupported =
      isModifierOnly &&
      (!KDEShortcutManager.isWayland() || (slotName === "dictation" && isPushToTalk));
    if (modifierOnlyUnsupported) {
      debugLogger.log("[KDEShortcut] Modifier-only shortcut not supported in this mode", {
        slot: slotName,
        hotkey: electronHotkey,
        isPushToTalk,
        qtKey: `0x${qtKey.toString(16)}`,
      });
      return "modifier-only";
    }

    // actionId: [componentUnique, actionUnique, componentFriendly, actionFriendly]
    const actionId = [COMPONENT_NAME, slotName, "OpenWhispr", `OpenWhispr ${slotName}`];

    try {
      // Pre-registration conflict check via low-level D-Bus call
      try {
        const dbusModule = getDBus();
        // The invoke callback receives the unwrapped first return value (the
        // aas list of owner actionIds), not a message object with a body.
        const owners = await new Promise((resolve, reject) => {
          this.bus.invoke(
            {
              type: dbusModule.messageType.methodCall,
              destination: "org.kde.kglobalaccel",
              path: "/kglobalaccel",
              interface: "org.kde.KGlobalAccel",
              member: "globalShortcutsByKey",
              signature: "aii",
              body: [[qtKey], 0],
            },
            (err, result) => {
              if (err) return reject(err);
              resolve(result);
            }
          );
        });
        if (Array.isArray(owners) && owners.length > 0) {
          const otherOwners = owners.filter(
            (aid) => Array.isArray(aid) && aid[0] !== COMPONENT_NAME
          );
          if (otherOwners.length > 0) {
            debugLogger.log("[KDEShortcut] Shortcut conflict — key owned by another component", {
              slot: slotName,
              hotkey: electronHotkey,
              owners: otherOwners.map((a) => a[0]),
            });
            return "conflict";
          }
        }
      } catch (checkErr) {
        // globalShortcutsByKey may not exist on older KDE — proceed without check
        debugLogger.log(
          "[KDEShortcut] Could not check for conflicts, proceeding:",
          checkErr.message
        );
      }

      // Clear stale registration, then register with flag 0x02 (SetPresent).
      // Flag 0x02 overwrites any saved binding; flag 0 preserves stale values.
      try {
        await new Promise((resolve, reject) => {
          this.kglobalaccel.unRegister(actionId, (err) => {
            if (err) return reject(err);
            resolve();
          });
        });
      } catch {}
      await new Promise((resolve, reject) => {
        this.kglobalaccel.doRegister(actionId, (err) => {
          if (err) return reject(err);
          resolve();
        });
      });
      const result = await new Promise((resolve, reject) => {
        this.kglobalaccel.setShortcut(actionId, [qtKey], 0x02, (err, res) => {
          if (err) return reject(err);
          resolve(res);
        });
      });

      // Post-registration conflict check: if setShortcut assigned a different key,
      // another component owns it.
      const assignedKey = Array.isArray(result) && result.length > 0 ? result[0] : null;
      if (assignedKey !== null && assignedKey !== qtKey) {
        debugLogger.log("[KDEShortcut] Shortcut conflict — setShortcut assigned different key", {
          slot: slotName,
          requested: `0x${qtKey.toString(16)}`,
          assigned: `0x${assignedKey.toString(16)}`,
        });
        try {
          await new Promise((resolve, reject) => {
            this.kglobalaccel.unRegister(actionId, (err) => {
              if (err) return reject(err);
              resolve();
            });
          });
        } catch {}
        return "conflict";
      }

      if (callback) this.callbacks.set(slotName, callback);
      this.registeredSlots.add(slotName);

      // Start listening for press events on the component
      const listening = await this._listenForComponent();
      if (!listening) {
        debugLogger.log(
          `[KDEShortcut] Keybinding registered but listener failed for "${slotName}", unregistering`
        );
        try {
          await new Promise((resolve, reject) => {
            this.kglobalaccel.unRegister(actionId, (err) => {
              if (err) return reject(err);
              resolve();
            });
          });
        } catch {}
        return false;
      }

      debugLogger.log("[KDEShortcut] Registered", {
        slot: slotName,
        hotkey: electronHotkey,
        qtKey: `0x${qtKey.toString(16)}`,
      });
      return true;
    } catch (err) {
      debugLogger.log(`[KDEShortcut] Registration failed for "${slotName}":`, err.message);
      return false;
    }
  }

  async unregisterKeybinding(slotName = "dictation") {
    if (!this.kglobalaccel) return;

    const actionId = [COMPONENT_NAME, slotName, "OpenWhispr", `OpenWhispr ${slotName}`];

    try {
      await new Promise((resolve, reject) => {
        this.kglobalaccel.unRegister(actionId, (err) => {
          if (err) return reject(err);
          resolve();
        });
      });
      this.callbacks.delete(slotName);
      this.registeredSlots.delete(slotName);
      debugLogger.log("[KDEShortcut] Unregistered", { slot: slotName });
    } catch (err) {
      debugLogger.log(`[KDEShortcut] Unregister failed for "${slotName}":`, err.message);
    }
  }

  async removeRetiredAgentKeybinding() {
    await this.unregisterKeybinding("agent");
  }

  close() {
    // Best-effort cleanup on app shutdown. unRegister calls are async D-Bus
    // calls that may not complete before disconnect, but KGlobalAccel will
    // clean up stale registrations from dead processes anyway.
    const promises = [];
    for (const slotName of this.registeredSlots) {
      const actionId = [COMPONENT_NAME, slotName, "OpenWhispr", `OpenWhispr ${slotName}`];
      try {
        promises.push(
          new Promise((resolve, reject) => {
            this.kglobalaccel?.unRegister(actionId, (err) => {
              if (err) return reject(err);
              resolve();
            });
          })
        );
      } catch {}
    }

    Promise.allSettled(promises).finally(() => {
      if (this.bus) {
        try {
          this.bus.connection.end();
        } catch {}
        this.bus = null;
        this.kglobalaccel = null;
        this.componentProxy = null;
      }
    });

    this.callbacks.clear();
    this.registeredSlots.clear();
  }
}

module.exports = KDEShortcutManager;