release / linux-x64 (push) Failing after 59s
ci / linux-x64 (push) Failing after 1m9s
ci / linux-arm64-cross (push) Failing after 4m15s
release / linux-arm64 (push) Successful in 4m36s
release / appimage-startup (push) Skipped
release / publish (push) Skipped
652 lines
27 KiB
JavaScript
652 lines
27 KiB
JavaScript
'use strict';
|
|
|
|
/**
|
|
* Whisper lists, the incoming whisper mode and key binding profiles (local files only), plus the global
|
|
* shortcut helper (`teamspeach-core hotkeys`).
|
|
*
|
|
* The official TeamSpeak 6 client keeps whisper lists and hotkeys as myTeamSpeak "syncable items"
|
|
* (`ApplySyncableItemAction`) and the receive mode as a local JSON blob "whisper"; TeamsPeach has no account,
|
|
* so all three are local files in the profile directory and nothing is synchronised anywhere.
|
|
*
|
|
* List objects keep the official field names (main.js 6.0.0.5163 byte 2368379):
|
|
* { list_uuid, name, type: 1 List | 2 PredefinedGroup, whisper_entry_list: [{ name, uuid, type: 1 Client | 2 Channel }],
|
|
* group_type 0..3, group_target_mode 0..6, target_server_uuid, target_server_name, target_group_id, target_group_name }.
|
|
*
|
|
* Key bindings: see keybind-schema.js (profiles, actions, sources, version 1 → 2 migration).
|
|
*/
|
|
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const { randomUUID } = require('node:crypto');
|
|
const schema = require('./keybind-schema');
|
|
const { spawn } = require('node:child_process');
|
|
|
|
const WHISPER_FILE = 'whisper.json';
|
|
const KEYBINDS_FILE = 'keybinds.json';
|
|
const WHISPER_VERSION = 1;
|
|
const MAX_LISTS = 200;
|
|
const MAX_ENTRIES = 1024;
|
|
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
const CONTROL = /[\u0000-\u001f\u007f]/;
|
|
const LIST_TYPE = { List: 1, PredefinedGroup: 2 };
|
|
const ENTRY_TYPE = { Client: 1, Channel: 2 };
|
|
const RECEIVE_MODES = ['allow_all', 'deny_all'];
|
|
|
|
const fail = (code, message) => ({ ok: false, error: { code, message } });
|
|
const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
const text = (v, min, max) => typeof v === 'string' && v.length >= min && v.length <= max && !CONTROL.test(v);
|
|
const onlyKeys = (v, keys) => Object.keys(v).every((k) => keys.includes(k));
|
|
|
|
// ------------------------------------------------------------------------------------------- persistence
|
|
|
|
/** Writes JSON atomically: a crash leaves either the old or the new file, never a torn one. */
|
|
function writeJson(file, value) {
|
|
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
const tmp = `${file}.tmp`;
|
|
const fd = fs.openSync(tmp, 'w');
|
|
try {
|
|
fs.writeSync(fd, JSON.stringify(value, null, 2));
|
|
fs.fsyncSync(fd);
|
|
} finally {
|
|
fs.closeSync(fd);
|
|
}
|
|
fs.renameSync(tmp, file);
|
|
}
|
|
|
|
/**
|
|
* Reads a versioned store. A missing file is a first run; an unparsable or unknown-shape file is moved aside
|
|
* (`<file>.invalid-<time>`) so it is never silently overwritten; a newer version than this build understands
|
|
* keeps the file untouched and makes the store read-only.
|
|
*/
|
|
function readStore(file, version, now) {
|
|
let raw;
|
|
try {
|
|
raw = fs.readFileSync(file, 'utf8');
|
|
} catch (err) {
|
|
if (err.code === 'ENOENT') return { data: null, readOnly: false, recovered: null };
|
|
throw err;
|
|
}
|
|
let parsed;
|
|
try {
|
|
parsed = JSON.parse(raw);
|
|
} catch {
|
|
return { data: null, readOnly: false, recovered: quarantine(file, now) };
|
|
}
|
|
if (!isObject(parsed) || !Number.isInteger(parsed.version) || parsed.version < 1) {
|
|
return { data: null, readOnly: false, recovered: quarantine(file, now) };
|
|
}
|
|
if (parsed.version > version) return { data: null, readOnly: true, recovered: null };
|
|
return { data: parsed, readOnly: false, recovered: null };
|
|
}
|
|
|
|
function quarantine(file, now) {
|
|
const target = `${file}.invalid-${now()}`;
|
|
fs.renameSync(file, target);
|
|
return target;
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------- validation
|
|
|
|
function validEntry(e) {
|
|
return isObject(e) && onlyKeys(e, ['name', 'uuid', 'type']) && (e.type === ENTRY_TYPE.Client || e.type === ENTRY_TYPE.Channel)
|
|
&& text(e.uuid, 1, 256) && typeof e.name === 'string' && e.name.length <= 8192 && !CONTROL.test(e.name)
|
|
// Official addFromSelection refuses channel paths whose names contain "/" (the path separator).
|
|
&& (e.type === ENTRY_TYPE.Client || e.name.length > 0);
|
|
}
|
|
|
|
/** Returns a normalized list or throws with a message naming the bad field. */
|
|
function normalizeList(list, { assignUuid = false } = {}) {
|
|
if (!isObject(list)) throw new Error('list: expected an object');
|
|
const keys = ['list_uuid', 'name', 'type', 'whisper_entry_list', 'group_type', 'group_target_mode', 'target_server_uuid',
|
|
'target_server_name', 'target_group_id', 'target_group_name'];
|
|
if (!onlyKeys(list, keys)) throw new Error('list: unknown field');
|
|
let uuid = list.list_uuid;
|
|
if (uuid === undefined || uuid === '') {
|
|
if (!assignUuid) throw new Error('list_uuid: required');
|
|
uuid = randomUUID();
|
|
}
|
|
if (typeof uuid !== 'string' || !UUID.test(uuid)) throw new Error('list_uuid: expected a UUID');
|
|
if (!text(list.name, 1, 128) || list.name.trim() !== list.name) throw new Error('name: 1-128 characters without surrounding spaces');
|
|
if (list.type !== LIST_TYPE.List && list.type !== LIST_TYPE.PredefinedGroup) throw new Error('type: unknown whisper list type');
|
|
const entries = list.whisper_entry_list ?? [];
|
|
if (!Array.isArray(entries) || entries.length > MAX_ENTRIES || !entries.every(validEntry)) throw new Error('whisper_entry_list: invalid entry');
|
|
const groupType = list.group_type ?? 0;
|
|
const mode = list.group_target_mode ?? 0;
|
|
if (!Number.isInteger(groupType) || groupType < 0 || groupType > 3) throw new Error('group_type: 0-3');
|
|
if (!Number.isInteger(mode) || mode < 0 || mode > 6) throw new Error('group_target_mode: 0-6');
|
|
const groupId = list.target_group_id ?? '0';
|
|
if (typeof groupId !== 'string' || !/^\d{1,20}$/.test(groupId)) throw new Error('target_group_id: decimal id');
|
|
for (const key of ['target_server_uuid', 'target_server_name', 'target_group_name']) {
|
|
if (list[key] !== undefined && !text(list[key], 0, 256)) throw new Error(`${key}: invalid`);
|
|
}
|
|
// Duplicates by identity (official isClientPresent/isChannelPresent) are collapsed.
|
|
const seen = new Set();
|
|
const unique = [];
|
|
for (const e of entries) {
|
|
const key = e.type === ENTRY_TYPE.Client ? `c:${e.uuid}` : `h:${e.uuid}:${e.name}`;
|
|
if (seen.has(key)) continue;
|
|
seen.add(key);
|
|
unique.push({ name: e.name, uuid: e.uuid, type: e.type });
|
|
}
|
|
return {
|
|
list_uuid: uuid.toLowerCase(),
|
|
name: list.name,
|
|
type: list.type,
|
|
whisper_entry_list: unique,
|
|
group_type: groupType,
|
|
group_target_mode: mode,
|
|
target_server_uuid: list.target_server_uuid ?? '',
|
|
target_server_name: list.target_server_name ?? '',
|
|
target_group_id: groupId,
|
|
target_group_name: list.target_group_name ?? '',
|
|
};
|
|
}
|
|
|
|
class WhisperStore {
|
|
constructor(dir, { now = Date.now } = {}) {
|
|
this.file = path.join(dir, WHISPER_FILE);
|
|
const { data, readOnly, recovered } = readStore(this.file, WHISPER_VERSION, now);
|
|
this.readOnly = readOnly;
|
|
this.recovered = recovered;
|
|
this.receiveMode = 'allow_all'; // official DEFAULT_SETTINGS { receiveMode: AllowAll }
|
|
this.lists = [];
|
|
if (data) this.load(data);
|
|
}
|
|
|
|
load(data) {
|
|
if (RECEIVE_MODES.includes(data.receiveMode)) this.receiveMode = data.receiveMode;
|
|
const lists = Array.isArray(data.lists) ? data.lists.slice(0, MAX_LISTS) : [];
|
|
const seen = new Set();
|
|
for (const raw of lists) {
|
|
try {
|
|
const list = normalizeList(raw);
|
|
if (!seen.has(list.list_uuid)) {
|
|
seen.add(list.list_uuid);
|
|
this.lists.push(list);
|
|
}
|
|
} catch {
|
|
// A single broken list is dropped (official type Invalid is never offered); the rest stay usable.
|
|
this.droppedOnLoad = (this.droppedOnLoad ?? 0) + 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
get() {
|
|
return { receiveMode: this.receiveMode, lists: this.lists.map((l) => ({ ...l, whisper_entry_list: l.whisper_entry_list.map((e) => ({ ...e })) })), readOnly: this.readOnly };
|
|
}
|
|
|
|
persist(next) {
|
|
if (this.readOnly) throw new Error('whisper.json was written by a newer TeamsPeach; not overwriting it');
|
|
writeJson(this.file, { version: WHISPER_VERSION, receiveMode: next.receiveMode, lists: next.lists });
|
|
this.receiveMode = next.receiveMode;
|
|
this.lists = next.lists;
|
|
}
|
|
|
|
saveList(raw) {
|
|
const list = normalizeList(raw, { assignUuid: true });
|
|
const lists = this.lists.slice();
|
|
const at = lists.findIndex((l) => l.list_uuid === list.list_uuid);
|
|
if (at >= 0) lists[at] = list;
|
|
else {
|
|
if (lists.length >= MAX_LISTS) throw new Error(`at most ${MAX_LISTS} whisper lists`);
|
|
lists.push(list);
|
|
}
|
|
this.persist({ receiveMode: this.receiveMode, lists });
|
|
return list;
|
|
}
|
|
|
|
deleteList(listUuid) {
|
|
const lists = this.lists.filter((l) => l.list_uuid !== listUuid);
|
|
if (lists.length === this.lists.length) return false;
|
|
this.persist({ receiveMode: this.receiveMode, lists });
|
|
return true;
|
|
}
|
|
|
|
setReceiveMode(mode) {
|
|
if (!RECEIVE_MODES.includes(mode)) throw new Error('receive mode: allow_all or deny_all');
|
|
this.persist({ receiveMode: mode, lists: this.lists });
|
|
}
|
|
|
|
listIds() {
|
|
return new Set(this.lists.map((l) => l.list_uuid));
|
|
}
|
|
}
|
|
|
|
/**
|
|
* keybinds.json version 2: { version, requireExactMatch, activeProfile, profiles: [{ id, name, bindings }] }.
|
|
* A version 1 file is migrated on load (keybind-schema.loadStore); the original bytes are kept next to it as
|
|
* `keybinds.v1-<time>.json` before the v2 file replaces it, so nothing of the old file is ever lost.
|
|
*/
|
|
class KeybindStore {
|
|
constructor(dir, { now = Date.now, defaultProfileName = 'Default' } = {}) {
|
|
this.file = path.join(dir, KEYBINDS_FILE);
|
|
const { data, readOnly, recovered } = readStore(this.file, schema.KEYBINDS_VERSION, now);
|
|
this.readOnly = readOnly;
|
|
this.recovered = recovered;
|
|
const { state, dropped, migrated } = schema.loadStore(data, { defaultProfileName });
|
|
this.state = state;
|
|
this.droppedOnLoad = dropped;
|
|
this.migratedFrom = null;
|
|
if (migrated && !readOnly) {
|
|
const backup = path.join(dir, `keybinds.v1-${now()}.json`);
|
|
fs.copyFileSync(this.file, backup, fs.constants.COPYFILE_EXCL);
|
|
this.persist(state);
|
|
this.migratedFrom = backup;
|
|
}
|
|
}
|
|
|
|
get() {
|
|
return {
|
|
requireExactMatch: this.state.requireExactMatch,
|
|
activeProfile: this.state.activeProfile,
|
|
profiles: this.state.profiles.map((p) => ({ id: p.id, name: p.name, bindings: p.bindings.map((b) => ({ ...b })) })),
|
|
readOnly: this.readOnly,
|
|
};
|
|
}
|
|
|
|
profile(id) {
|
|
const p = typeof id === 'string' ? this.state.profiles.find((x) => x.id === id.toLowerCase()) : null;
|
|
if (!p) throw new Error('profile: not found');
|
|
return p;
|
|
}
|
|
|
|
/** Bindings of the active profile ("No Profile" → none). */
|
|
activeBindings() {
|
|
return this.state.profiles.find((p) => p.id === this.state.activeProfile)?.bindings ?? [];
|
|
}
|
|
|
|
setExact(value) {
|
|
if (typeof value !== 'boolean') throw new Error('requireExactMatch: expected true/false');
|
|
this.persist({ ...this.state, requireExactMatch: value });
|
|
}
|
|
|
|
/** Official addHotkeyProfile; the first profile becomes the active one (there is no other). */
|
|
addProfile(name) {
|
|
if (this.state.profiles.length >= schema.MAX_PROFILES) throw new Error(`at most ${schema.MAX_PROFILES} profiles`);
|
|
const profile = { id: randomUUID(), name: schema.normalizeProfileName(name), bindings: [] };
|
|
this.persist({ ...this.state, activeProfile: this.state.activeProfile ?? profile.id, profiles: [...this.state.profiles, profile] });
|
|
return profile.id;
|
|
}
|
|
|
|
renameProfile(id, name) {
|
|
const target = this.profile(id);
|
|
const nextName = schema.normalizeProfileName(name);
|
|
this.persist({ ...this.state, profiles: this.state.profiles.map((p) => (p === target ? { ...p, name: nextName } : p)) });
|
|
}
|
|
|
|
/** Official setDefault: the chosen profile becomes the one whose bindings are live. */
|
|
activateProfile(id) {
|
|
const target = this.profile(id);
|
|
if (target.id !== this.state.activeProfile) this.persist({ ...this.state, activeProfile: target.id });
|
|
}
|
|
|
|
/** Official shows delete only for a non-active profile; the active one cannot be deleted. */
|
|
deleteProfile(id) {
|
|
const target = this.profile(id);
|
|
if (target.id === this.state.activeProfile) throw new Error('profile: activate another profile before deleting this one');
|
|
this.persist({ ...this.state, profiles: this.state.profiles.filter((p) => p !== target) });
|
|
}
|
|
|
|
setBindings(id, rawBindings) {
|
|
const target = this.profile(id);
|
|
const bindings = schema.normalizeBindings(rawBindings, target.bindings);
|
|
this.persist({ ...this.state, profiles: this.state.profiles.map((p) => (p === target ? { ...p, bindings } : p)) });
|
|
}
|
|
|
|
/** Official: deleting a whisper list deletes its hotkeys ("…with all associated hotkeys"), in every profile. */
|
|
dropTarget(listUuid) {
|
|
let changed = false;
|
|
const profiles = this.state.profiles.map((p) => {
|
|
const bindings = p.bindings.filter((b) => !(b.action === 'whisper_list' && b.target === listUuid));
|
|
if (bindings.length === p.bindings.length) return p;
|
|
changed = true;
|
|
return { ...p, bindings };
|
|
});
|
|
if (changed) this.persist({ ...this.state, profiles });
|
|
}
|
|
|
|
persist(next) {
|
|
if (this.readOnly) throw new Error('keybinds.json was written by a newer TeamsPeach; not overwriting it');
|
|
writeJson(this.file, { version: schema.KEYBINDS_VERSION, requireExactMatch: next.requireExactMatch, activeProfile: next.activeProfile, profiles: next.profiles });
|
|
this.state = next;
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------- helper
|
|
|
|
const HELPER_BACKENDS = ['windows_registerhotkey', 'xdg_portal_global_shortcuts', 'x11_xgrabkey', 'unavailable'];
|
|
const HELPER_ERRORS = ['in_use', 'unsupported_key', 'invalid', 'portal_denied', 'failed'];
|
|
const MAX_HELPER_LINE = 64 * 1024;
|
|
const MAX_RESTARTS = 3;
|
|
|
|
// Backends that fire only on the exact modifier set; "Require exact key match" off adds modifier variants.
|
|
const EXACT_MODIFIER_BACKENDS = new Set(['windows_registerhotkey', 'x11_xgrabkey']);
|
|
|
|
/**
|
|
* Owns the `teamspeach-core hotkeys` child. It registers only the bindings marked global and reports
|
|
* press/release for those ids; it never sees other keys (see core/src/hotkeys.rs). Disabled in offscreen
|
|
* tests so a test run never registers shortcuts on the user's desktop.
|
|
*
|
|
* With exact matching off, RegisterHotKey/XGrabKey bindings are also registered with extra modifiers
|
|
* (keybind-schema.expandRegistrations); a variant's press/release is reported as its binding. The desktop
|
|
* portal decides matching itself, so it always receives only the bindings' own chords.
|
|
*/
|
|
class HotkeyHelper {
|
|
constructor({ resolveBinary, onEvent, onStatus, enabled, spawnProcess = spawn }) {
|
|
this.resolveBinary = resolveBinary;
|
|
this.onEvent = onEvent;
|
|
this.onStatus = onStatus;
|
|
this.enabled = enabled;
|
|
this.spawnProcess = spawnProcess;
|
|
this.child = null;
|
|
this.seq = 0;
|
|
this.wanted = [];
|
|
this.exact = true;
|
|
this.variantOf = new Map();
|
|
this.heldVariants = new Map(); // binding id → registered ids currently down
|
|
this.restarts = 0;
|
|
const variants = { wanted: 0, registered: 0 };
|
|
this.status = enabled
|
|
? { state: 'idle', backend: null, global: false, release: false, detail: '', results: [], exact: true, variants }
|
|
: { state: 'disabled', backend: null, global: false, release: false, detail: 'test_offscreen', results: [], exact: true, variants };
|
|
}
|
|
|
|
setStatus(patch) {
|
|
this.status = { ...this.status, ...patch };
|
|
this.onStatus(this.status);
|
|
}
|
|
|
|
/**
|
|
* Replaces the registered set with the global physical `bindings`. Starts or stops the helper as needed.
|
|
* `exact` is the profile store's requireExactMatch.
|
|
*/
|
|
bind(bindings, { exact = true } = {}) {
|
|
this.wanted = bindings.filter((b) => b.global).map((b) => ({
|
|
id: b.id, code: b.code, ctrl: b.ctrl, alt: b.alt, shift: b.shift, meta: b.meta, description: b.description ?? b.action,
|
|
}));
|
|
this.exact = exact;
|
|
this.status = { ...this.status, exact };
|
|
if (!this.enabled) return;
|
|
if (this.wanted.length === 0) {
|
|
this.stop();
|
|
this.setStatus({ state: 'idle', results: [], variants: { wanted: 0, registered: 0 } });
|
|
return;
|
|
}
|
|
if (!this.child) this.start();
|
|
else this.sendBind();
|
|
}
|
|
|
|
start() {
|
|
const binary = this.resolveBinary();
|
|
if (!binary) {
|
|
this.setStatus({ state: 'unavailable', backend: 'unavailable', global: false, detail: 'core_binary_missing' });
|
|
return;
|
|
}
|
|
let child;
|
|
try {
|
|
child = this.spawnProcess(binary, ['hotkeys'], { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
|
|
} catch (err) {
|
|
this.setStatus({ state: 'unavailable', backend: 'unavailable', global: false, detail: `spawn_failed: ${err.message}` });
|
|
return;
|
|
}
|
|
this.child = child;
|
|
this.setStatus({ state: 'starting' });
|
|
child.stdin.on('error', () => {});
|
|
child.stderr.resume();
|
|
let pending = '';
|
|
child.stdout.setEncoding('utf8');
|
|
child.stdout.on('data', (chunk) => {
|
|
pending += chunk;
|
|
let end;
|
|
while ((end = pending.indexOf('\n')) >= 0) {
|
|
const line = pending.slice(0, end);
|
|
pending = pending.slice(end + 1);
|
|
if (line.trim()) this.onLine(child, line);
|
|
}
|
|
if (pending.length > MAX_HELPER_LINE) {
|
|
pending = '';
|
|
this.fault(child, 'helper line too long');
|
|
}
|
|
});
|
|
child.on('error', (err) => this.exited(child, `helper error: ${err.message}`));
|
|
child.on('exit', (code) => this.exited(child, `helper exited (${code})`));
|
|
}
|
|
|
|
onLine(child, line) {
|
|
if (child !== this.child) return;
|
|
let msg;
|
|
try {
|
|
msg = JSON.parse(line);
|
|
} catch {
|
|
this.fault(child, 'helper sent invalid JSON');
|
|
return;
|
|
}
|
|
if (!isObject(msg) || typeof msg.event !== 'string') return;
|
|
switch (msg.event) {
|
|
case 'ready':
|
|
if (!HELPER_BACKENDS.includes(msg.backend)) {
|
|
this.fault(child, 'unknown helper backend');
|
|
return;
|
|
}
|
|
this.setStatus({
|
|
state: msg.backend === 'unavailable' ? 'unavailable' : 'ready',
|
|
backend: msg.backend,
|
|
global: msg.global === true && msg.backend !== 'unavailable',
|
|
release: msg.release === true,
|
|
detail: typeof msg.detail === 'string' ? msg.detail.slice(0, 1024) : '',
|
|
});
|
|
if (this.status.global) this.sendBind();
|
|
break;
|
|
case 'bound':
|
|
case 'rebound': {
|
|
if (msg.event === 'bound' && msg.seq !== this.seq) return; // answer to a superseded bind
|
|
const all = Array.isArray(msg.results) ? msg.results.filter((r) => isObject(r) && typeof r.id === 'string' && this.variantOf.has(r.id)) : [];
|
|
const results = all.filter((r) => this.variantOf.get(r.id) === r.id).map((r) => ({
|
|
id: r.id,
|
|
ok: r.ok === true,
|
|
trigger: typeof r.trigger === 'string' ? r.trigger.slice(0, 128) : '',
|
|
error: r.ok === true ? undefined : (HELPER_ERRORS.includes(r.error) ? r.error : 'failed'),
|
|
detail: typeof r.detail === 'string' ? r.detail.slice(0, 512) : '',
|
|
}));
|
|
// Variants another program already owns (in_use) simply do not fire; the binding's own chord decides its status.
|
|
const registered = all.filter((r) => this.variantOf.get(r.id) !== r.id && r.ok === true).length;
|
|
this.restarts = 0;
|
|
this.setStatus({ state: 'ready', results, variants: { ...this.status.variants, registered } });
|
|
break;
|
|
}
|
|
case 'press':
|
|
case 'release': {
|
|
const id = typeof msg.id === 'string' ? this.variantOf.get(msg.id) : undefined;
|
|
if (!id) return;
|
|
const down = this.heldVariants.get(id) ?? new Set();
|
|
if (msg.event === 'press') {
|
|
if (down.has(msg.id)) return;
|
|
down.add(msg.id);
|
|
this.heldVariants.set(id, down);
|
|
if (down.size === 1) this.onEvent({ id, state: 'press', source: 'global' });
|
|
} else {
|
|
if (!down.delete(msg.id)) return;
|
|
if (down.size === 0) {
|
|
this.heldVariants.delete(id);
|
|
this.onEvent({ id, state: 'release', source: 'global' });
|
|
}
|
|
}
|
|
break;
|
|
}
|
|
case 'error':
|
|
this.setStatus({ detail: typeof msg.detail === 'string' ? msg.detail.slice(0, 1024) : 'helper error' });
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
|
|
sendBind() {
|
|
if (!this.child || !this.status.global) return;
|
|
this.releaseAll();
|
|
const expand = !this.exact && EXACT_MODIFIER_BACKENDS.has(this.status.backend);
|
|
const { registrations, variantOf, variants } = schema.expandRegistrations(this.wanted, { exact: !expand });
|
|
this.variantOf = variantOf;
|
|
this.status = { ...this.status, variants: { wanted: variants.wanted, registered: 0 } };
|
|
this.seq = (this.seq + 1) >>> 0;
|
|
this.child.stdin.write(`${JSON.stringify({ cmd: 'bind', seq: this.seq, bindings: registrations })}\n`);
|
|
}
|
|
|
|
/**
|
|
* A held global key must never stay "held" after a rebind, crash or shutdown: whisper or PTT would stick.
|
|
* These releases are `synthetic`: they end held actions but never fire release-triggered actions.
|
|
*/
|
|
releaseAll() {
|
|
for (const id of this.heldVariants.keys()) this.onEvent({ id, state: 'release', source: 'global', synthetic: true });
|
|
this.heldVariants.clear();
|
|
}
|
|
|
|
fault(child, detail) {
|
|
if (child !== this.child) return;
|
|
try { child.kill(); } catch { /* already gone */ }
|
|
this.exited(child, detail);
|
|
}
|
|
|
|
exited(child, detail) {
|
|
if (child !== this.child) return;
|
|
this.child = null;
|
|
this.releaseAll();
|
|
if (this.stopping) return;
|
|
if (this.wanted.length > 0 && this.restarts < MAX_RESTARTS) {
|
|
this.restarts += 1;
|
|
this.setStatus({ state: 'restarting', detail });
|
|
this.start();
|
|
} else {
|
|
this.setStatus({ state: 'unavailable', global: false, detail });
|
|
}
|
|
}
|
|
|
|
stop() {
|
|
const child = this.child;
|
|
if (!child) return;
|
|
this.stopping = true;
|
|
this.releaseAll();
|
|
this.child = null;
|
|
try {
|
|
child.stdin.write(`${JSON.stringify({ cmd: 'shutdown' })}\n`);
|
|
child.stdin.end();
|
|
} catch { /* pipe closed */ }
|
|
const timer = setTimeout(() => { try { child.kill(); } catch { /* gone */ } }, 500);
|
|
timer.unref?.();
|
|
child.once('exit', () => clearTimeout(timer));
|
|
this.stopping = false;
|
|
}
|
|
}
|
|
|
|
// ------------------------------------------------------------------------------------------- IPC
|
|
|
|
/**
|
|
* Registers the renderer API. `getPttCode` supplies the Audio push-to-talk key for conflict checks;
|
|
* `testOffscreen` disables the global helper (bindings then work only while the window is focused, and the
|
|
* status says so). `defaultProfileName` names the profile a version 1 keybinds.json migrates into.
|
|
*/
|
|
function registerWhisperIpc({ ipcMain, trustedSender, getWindow, userDataDir, resolveBinary, testOffscreen, getPttCode, spawnProcess, defaultProfileName }) {
|
|
const whisper = new WhisperStore(userDataDir);
|
|
const keybinds = new KeybindStore(userDataDir, { defaultProfileName });
|
|
const send = (channel, payload) => {
|
|
const contents = getWindow()?.webContents;
|
|
if (contents && !contents.isDestroyed()) contents.send(channel, payload);
|
|
};
|
|
const helper = new HotkeyHelper({
|
|
resolveBinary,
|
|
enabled: !testOffscreen,
|
|
spawnProcess,
|
|
onEvent: (event) => send('keybinds:event', event),
|
|
onStatus: (status) => send('keybinds:status', status),
|
|
});
|
|
const conflictsOf = (bindings) => schema.conflicts(bindings, getPttCode(), whisper.listIds());
|
|
const keybindState = () => {
|
|
const state = keybinds.get();
|
|
return {
|
|
...state,
|
|
profiles: state.profiles.map((p) => ({ ...p, conflicts: conflictsOf(p.bindings) })),
|
|
status: helper.status,
|
|
recovered: keybinds.recovered,
|
|
migratedFrom: keybinds.migratedFrom,
|
|
droppedOnLoad: keybinds.droppedOnLoad,
|
|
};
|
|
};
|
|
/**
|
|
* Only the active profile is live; conflicting rows are never registered. While the renderer records a
|
|
* keyboard chord nothing is registered, so a key already bound globally reaches the recorder instead of
|
|
* firing (RegisterHotKey/XGrabKey would swallow it).
|
|
*/
|
|
let capturing = false;
|
|
const bindAvailable = () => {
|
|
const bindings = capturing ? [] : keybinds.activeBindings();
|
|
const blocked = new Set(conflictsOf(bindings).map((c) => c.id));
|
|
helper.bind(bindings.filter((b) => !blocked.has(b.id)), { exact: keybinds.state.requireExactMatch });
|
|
};
|
|
/** keybinds:capture(on) — the renderer's keyboard recorder started/ended (it also ends on window blur). */
|
|
const setCapturing = (on) => {
|
|
if (typeof on !== 'boolean') throw new Error('capture: expected true/false');
|
|
if (capturing === on) return;
|
|
capturing = on;
|
|
bindAvailable();
|
|
};
|
|
bindAvailable();
|
|
|
|
const guard = (handler) => (event, ...args) => {
|
|
if (!trustedSender(event)) return fail('forbidden', 'forbidden');
|
|
try {
|
|
return handler(...args);
|
|
} catch (err) {
|
|
return fail('bad_request', err.message);
|
|
}
|
|
};
|
|
const keybindChange = (change) => guard((...args) => {
|
|
const extra = change(...args);
|
|
bindAvailable();
|
|
return { ok: true, ...extra, ...keybindState() };
|
|
});
|
|
|
|
ipcMain.handle('whisper:get', guard(() => ({ ok: true, ...whisper.get(), recovered: whisper.recovered })));
|
|
ipcMain.handle('whisper:save-list', guard((list) => {
|
|
const saved = whisper.saveList(list);
|
|
bindAvailable(); // a binding waiting for this list may become usable
|
|
return { ok: true, list: saved };
|
|
}));
|
|
ipcMain.handle('whisper:delete-list', guard((listUuid) => {
|
|
if (typeof listUuid !== 'string' || !UUID.test(listUuid)) throw new Error('list_uuid: expected a UUID');
|
|
const deleted = whisper.deleteList(listUuid.toLowerCase());
|
|
if (deleted) {
|
|
keybinds.dropTarget(listUuid.toLowerCase());
|
|
bindAvailable();
|
|
}
|
|
return { ok: true, deleted, keybinds: keybindState() };
|
|
}));
|
|
ipcMain.handle('whisper:set-receive-mode', guard((mode) => {
|
|
whisper.setReceiveMode(mode);
|
|
return { ok: true, receiveMode: whisper.receiveMode };
|
|
}));
|
|
ipcMain.handle('keybinds:get', guard(() => ({ ok: true, ...keybindState() })));
|
|
ipcMain.handle('keybinds:set', keybindChange((profileId, bindings) => { keybinds.setBindings(profileId, bindings); }));
|
|
ipcMain.handle('keybinds:set-exact', keybindChange((value) => { keybinds.setExact(value); }));
|
|
ipcMain.handle('keybinds:profile-add', keybindChange((name) => ({ profileId: keybinds.addProfile(name) })));
|
|
ipcMain.handle('keybinds:profile-rename', keybindChange((profileId, name) => { keybinds.renameProfile(profileId, name); }));
|
|
ipcMain.handle('keybinds:profile-activate', keybindChange((profileId) => { keybinds.activateProfile(profileId); }));
|
|
ipcMain.handle('keybinds:profile-delete', keybindChange((profileId) => { keybinds.deleteProfile(profileId); }));
|
|
ipcMain.handle('keybinds:capture', guard((on) => { setCapturing(on); return { ok: true }; }));
|
|
|
|
return {
|
|
whisper,
|
|
keybinds,
|
|
helper,
|
|
refreshBindings: bindAvailable,
|
|
dispose: () => helper.stop(),
|
|
};
|
|
}
|
|
|
|
module.exports = {
|
|
registerWhisperIpc,
|
|
WhisperStore,
|
|
KeybindStore,
|
|
HotkeyHelper,
|
|
normalizeList,
|
|
};
|