'use strict'; /** * Key binding schema (keybinds.json version 2): profiles, actions, binding sources, conflicts and the * version 1 → 2 migration. Pure: no file system and no Electron, so it is unit-testable. * * Actions follow the official hotkey action enum (main.js 6.0.0 @2287523): every enum entry except * "Unassigned" has an id here. `kind` is when it runs: * hold – down starts, up ends (official up/down pair: Push-To-Talk, Push-To-Mute, the three whispers); * press – runs on down only (official GoLiveCurrentFullscreen: down Activate, up Deactivate = no-op); * trigger – runs once on release (official single-mode actions store only the `up` event). * `group` is the official settings group (get_all @2290500); a group holds at most MAX_PER_GROUP bindings. * * A binding has exactly one source: * physical – { code, ctrl, alt, shift, meta, global }: KeyboardEvent.code plus modifiers; global ones are * registered with the `teamspeach-core hotkeys` helper, local ones work only in the focused window; * remote – { remote: { remoteApp, remoteButton } }: an approved Remote App keyPress button. */ const { randomUUID } = require('node:crypto'); const KEYBINDS_VERSION = 2; const MAX_BINDINGS = 64; // per profile; also the helper's registration limit const MAX_PROFILES = 32; const MAX_PER_GROUP = 6; // official max_hotkeys_for_action (c3V = 6) const PROFILE_NAME_MAX = 64; 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 KEY_CODE = /^[A-Za-z0-9]{1,32}$/; const REMOTE_APP = /^[a-z.]{1,128}$/; // docs/Remote Apps.md: identifier is [a-z.] const MODIFIER_CODES = new Set(['ControlLeft', 'ControlRight', 'AltLeft', 'AltRight', 'ShiftLeft', 'ShiftRight', 'MetaLeft', 'MetaRight', 'OSLeft', 'OSRight']); /** id → { kind, group, official }. Group order below is the settings order. */ const ACTIONS = Object.freeze({ push_to_talk: { kind: 'hold', group: 'push_to_talk', official: 'Push-To-Talk' }, push_to_mute: { kind: 'hold', group: 'push_to_mute', official: 'Push-To-Mute' }, microphone_toggle: { kind: 'trigger', group: 'microphone', official: 'Toggle Microphone Mute' }, microphone_mute: { kind: 'trigger', group: 'microphone', official: 'Microphone Mute' }, microphone_unmute: { kind: 'trigger', group: 'microphone', official: 'Microphone Unmute' }, speaker_toggle: { kind: 'trigger', group: 'speaker', official: 'Toggle Speaker Mute' }, speaker_mute: { kind: 'trigger', group: 'speaker', official: 'Speaker Mute' }, speaker_unmute: { kind: 'trigger', group: 'speaker', official: 'Speaker Unmute' }, away_toggle: { kind: 'trigger', group: 'away', official: 'Toggle Away Status' }, away_online: { kind: 'trigger', group: 'away', official: 'Set Online' }, away_set: { kind: 'trigger', group: 'away', official: 'Set Away' }, away_toggle_message: { kind: 'trigger', group: 'away', official: 'Toggle Away Status with Message' }, reply_whisper: { kind: 'hold', group: 'reply_whisper', official: 'Reply to the last user that whispered you' }, quick_whisper: { kind: 'hold', group: 'quick_whisper', official: 'Whisper to the currently selected items in the servertree' }, whisper_list: { kind: 'hold', group: 'whisper_list', official: 'Whisper to a set list', target: 'whisper_list' }, go_live_current: { kind: 'press', group: 'go_live_current', official: 'Go Live with current Fullscreen App' }, recording_start: { kind: 'trigger', group: 'recording_start', official: 'Start Recording' }, recording_stop: { kind: 'trigger', group: 'recording_stop', official: 'Stop Recording' }, recording_toggle_pause: { kind: 'trigger', group: 'recording_toggle_pause', official: 'Pause or Resume Recording' }, disconnect_current: { kind: 'trigger', group: 'disconnect', official: 'Disconnect from Current Server' }, disconnect_all: { kind: 'trigger', group: 'disconnect', official: 'Disconnect from All Servers' }, talk_power_request: { kind: 'trigger', group: 'talk_power', official: 'Request Talk Power' }, talk_power_grant_next: { kind: 'trigger', group: 'talk_power', official: 'Grant Next User Talk Power' }, }); const fail = (message) => { throw new Error(message); }; const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v); const onlyKeys = (v, keys) => Object.keys(v).every((k) => keys.includes(k)); const text = (v, min, max) => typeof v === 'string' && v.length >= min && v.length <= max && !CONTROL.test(v); function normalizeId(id) { const value = id === undefined || id === '' ? randomUUID() : id; if (typeof value !== 'string' || !UUID.test(value)) fail('id: expected a UUID'); return value.toLowerCase(); } /** * Returns a normalized binding or throws naming the bad field. A whisper_list target may be '' or a list * that no longer exists: like the official resolveTarget the row then asks for a list and does nothing. */ function normalizeBinding(b) { if (!isObject(b) || !onlyKeys(b, ['id', 'action', 'target', 'code', 'ctrl', 'alt', 'shift', 'meta', 'global', 'remote'])) fail('binding: unknown field'); const id = normalizeId(b.id); const spec = ACTIONS[b.action]; if (!spec) fail('action: unknown'); const target = b.target ?? ''; if (spec.target === 'whisper_list') { if (typeof target !== 'string' || (target !== '' && !UUID.test(target))) fail('target: expected a whisper list UUID'); } else if (target !== '') fail('target: only whisper_list has a target'); const base = { id, action: b.action, target: target.toLowerCase() }; if (b.remote !== undefined) { if (['code', 'ctrl', 'alt', 'shift', 'meta', 'global'].some((k) => b[k] !== undefined)) fail('remote: a remote binding has no physical key fields'); const r = b.remote; if (!isObject(r) || !onlyKeys(r, ['remoteApp', 'remoteButton'])) fail('remote: unknown field'); if (typeof r.remoteApp !== 'string' || !REMOTE_APP.test(r.remoteApp)) fail('remote.remoteApp: invalid identifier'); if (!text(r.remoteButton, 1, 128)) fail('remote.remoteButton: 1-128 characters'); return { ...base, remote: { remoteApp: r.remoteApp, remoteButton: r.remoteButton } }; } if (typeof b.code !== 'string' || !KEY_CODE.test(b.code) || MODIFIER_CODES.has(b.code)) fail('code: invalid key'); for (const m of ['ctrl', 'alt', 'shift', 'meta', 'global']) { if (typeof (b[m] ?? false) !== 'boolean') fail(`${m}: expected true/false`); } return { ...base, code: b.code, ctrl: Boolean(b.ctrl), alt: Boolean(b.alt), shift: Boolean(b.shift), meta: Boolean(b.meta), global: b.global !== false }; } function normalizeProfileName(name) { if (typeof name !== 'string') fail('name: expected text'); const trimmed = name.trim(); if (!text(trimmed, 1, PROFILE_NAME_MAX)) fail(`name: 1-${PROFILE_NAME_MAX} characters`); return trimmed; } /** Bindings of one profile; `previous` (same profile before the change) lets migrated groups keep >6 rows. */ function normalizeBindings(raw, previous = []) { if (!Array.isArray(raw) || raw.length > MAX_BINDINGS) fail(`bindings: at most ${MAX_BINDINGS}`); const next = raw.map(normalizeBinding); if (new Set(next.map((b) => b.id)).size !== next.length) fail('bindings: duplicate id'); const count = (list) => list.reduce((m, b) => m.set(ACTIONS[b.action].group, (m.get(ACTIONS[b.action].group) ?? 0) + 1), new Map()); const before = count(previous); for (const [group, n] of count(next)) { if (n > Math.max(MAX_PER_GROUP, before.get(group) ?? 0)) fail(`bindings: at most ${MAX_PER_GROUP} per action`); } return next; } function normalizeProfile(p) { if (!isObject(p) || !onlyKeys(p, ['id', 'name', 'bindings'])) fail('profile: unknown field'); const id = normalizeId(p.id); const name = normalizeProfileName(p.name); const bindings = []; let dropped = 0; for (const raw of Array.isArray(p.bindings) ? p.bindings.slice(0, MAX_BINDINGS) : []) { try { const b = normalizeBinding(raw); if (!bindings.some((x) => x.id === b.id)) bindings.push(b); } catch { dropped += 1; } } return { profile: { id, name, bindings }, dropped }; } /** * Loads a parsed store (version 1 or 2) into the v2 shape. Version 1 `{ bindings }` becomes one active * profile named `defaultProfileName` holding every valid binding unchanged (ids, chords, global flag, * targets); `requireExactMatch` is true because version 1 always matched exactly. A version 1 file without * valid bindings becomes "No Profile" (the official first-run state). Fresh stores default to the official * unchecked toggle (captured settings-keybinds: "Hotkeys will trigger even when other keys are pressed."). */ function loadStore(data, { defaultProfileName = 'Default' } = {}) { const empty = { requireExactMatch: false, activeProfile: null, profiles: [] }; if (!data) return { state: empty, dropped: 0, migrated: false }; if (data.version === 1) { const { profile, dropped } = normalizeProfile({ id: '', name: defaultProfileName, bindings: data.bindings }); if (profile.bindings.length === 0) return { state: { ...empty, requireExactMatch: true }, dropped, migrated: true }; return { state: { requireExactMatch: true, activeProfile: profile.id, profiles: [profile] }, dropped, migrated: true }; } let dropped = 0; const profiles = []; for (const raw of Array.isArray(data.profiles) ? data.profiles.slice(0, MAX_PROFILES) : []) { try { const r = normalizeProfile(raw); dropped += r.dropped; if (!profiles.some((p) => p.id === r.profile.id)) profiles.push(r.profile); } catch { dropped += 1; } } const active = typeof data.activeProfile === 'string' ? data.activeProfile.toLowerCase() : null; return { state: { requireExactMatch: data.requireExactMatch === true, activeProfile: profiles.some((p) => p.id === active) ? active : (profiles[0]?.id ?? null), profiles, }, dropped, migrated: false, }; } const chordKey = (b) => `${b.ctrl ? 'C' : ''}${b.alt ? 'A' : ''}${b.shift ? 'S' : ''}${b.meta ? 'M' : ''}+${b.code}`; const sourceKey = (b) => (b.remote ? `remote:${b.remote.remoteApp}:${b.remote.remoteButton}` : `key:${chordKey(b)}`); /** * Bindings that cannot work as stored: the same chord or remote button twice, a plain chord on the Audio * push-to-talk key (voice.js handles that key itself), or a whisper_list row without an existing list. */ function conflicts(bindings, pttCode, listIds = null) { const out = []; const bySource = new Map(); for (const b of bindings) { const key = sourceKey(b); const other = bySource.get(key); if (other) { out.push({ id: b.id, reason: 'duplicate', with: other.id }); if (!out.some((c) => c.id === other.id && c.reason === 'duplicate')) out.push({ id: other.id, reason: 'duplicate', with: b.id }); } else bySource.set(key, b); if (!b.remote && pttCode && b.action !== 'push_to_talk' && b.code === pttCode && !b.ctrl && !b.alt && !b.shift && !b.meta) out.push({ id: b.id, reason: 'ptt' }); if (listIds && ACTIONS[b.action]?.target === 'whisper_list' && !listIds.has(b.target)) out.push({ id: b.id, reason: 'select_list' }); } return out; } const MODIFIER_BITS = [['ctrl', 1], ['alt', 2], ['shift', 4], ['meta', 8]]; const maskOf = (b) => MODIFIER_BITS.reduce((m, [k, bit]) => (b[k] ? m | bit : m), 0); const popcount = (m) => (m & 1) + ((m >> 1) & 1) + ((m >> 2) & 1) + ((m >> 3) & 1); /** * Registrations for the global helper. Windows RegisterHotKey and X11 XGrabKey only fire on the exact * modifier set, so "Require exact key match" off is realised by also registering the chord with extra * modifiers. Every binding's own chord comes first; extra-modifier variants follow by fewest added * modifiers while the helper limit allows, never taking a chord another binding uses exactly. Variant * ids are `~`; `variantOf` maps each registered id back to its binding id. */ function expandRegistrations(bindings, { exact, limit = MAX_BINDINGS } = {}) { const regs = []; const variantOf = new Map(); const taken = new Set(); for (const b of bindings.slice(0, limit)) { regs.push(b); variantOf.set(b.id, b.id); taken.add(chordKey(b)); } let wanted = 0; if (!exact) { const extras = []; for (let mask = 1; mask < 16; mask += 1) extras.push(mask); extras.sort((a, b) => popcount(a) - popcount(b) || a - b); for (const extra of extras) { for (const b of bindings) { if (maskOf(b) & extra) continue; const variant = { ...b, id: `${b.id}~${extra}` }; for (const [k, bit] of MODIFIER_BITS) if (extra & bit) variant[k] = true; const key = chordKey(variant); if (taken.has(key)) continue; wanted += 1; if (regs.length >= limit) continue; taken.add(key); regs.push(variant); variantOf.set(variant.id, b.id); } } } return { registrations: regs, variantOf, variants: { wanted, registered: regs.length - Math.min(bindings.length, limit) } }; } module.exports = { KEYBINDS_VERSION, MAX_BINDINGS, MAX_PROFILES, MAX_PER_GROUP, ACTIONS, UUID, normalizeBinding, normalizeBindings, normalizeProfileName, loadStore, conflicts, chordKey, expandRegistrations, };