// Toggle keys, mod-tap keys and macros for the MCHOSE keyboards. The key picker offers them as ordinary // entries; the keyboard keeps their details in slot tables, so setting one picks a slot, writes it, and // frees slots no key uses any more. import { MCHOSE_ACTION_TYPE, MCHOSE_ADVANCED_SLOTS, MCHOSE_MACRO_COUNT, MCHOSE_MACRO_MAX_DELAY_MS, MCHOSE_MACRO_MIN_DELAY_MS, MCHOSE_MACRO_MODE, MCHOSE_MODIFIER, MCHOSE_USAGE_NAMES, MCHOSE_LAYER_COUNT, mchoseActionLabel, mchoseActionValue, mchoseKeyAction, type MchoseAction, type MchoseMacroStep, } from "@openmouse/keyboard-protocol/mchose"; /** Entries that stand for a toggle or mod-tap key before a slot is chosen; never stored on the keyboard. */ export const VIRTUAL_TOGGLE = 0xe1; export const VIRTUAL_MOD_TAP = 0xe2; /** Hold time of a mod-tap key, in the keyboard's 10 ms steps. */ const MOD_TAP_HOLD_STEPS = 20; const HOLDS: [number, string][] = [ [MCHOSE_MODIFIER.leftCtrl, "Ctrl"], [MCHOSE_MODIFIER.leftShift, "Shift"], [MCHOSE_MODIFIER.leftAlt, "Alt"], [MCHOSE_MODIFIER.leftWin, "Win"], ]; const TOGGLE_KEYS = [...Array.from({ length: 26 }, (_, i) => 0x04 + i), 0x2c, 0x28, 0x2b, 0x29]; const entry = (type: number, code1: number, code2: number, label: string) => ({ code: mchoseActionValue({ type, code1, code2 }), label }); /** The extra picker categories. */ export function advancedCategories() { return [ { name: "Macros", keys: Array.from({ length: MCHOSE_MACRO_COUNT }, (_, n) => entry(MCHOSE_ACTION_TYPE.macro, n, 0, `Macro ${n + 1}`)) }, { name: "Toggle", keys: [ ...HOLDS.map(([mask, label]) => entry(VIRTUAL_TOGGLE, mask, 0, `Toggle ${label}`)), ...TOGGLE_KEYS.map((usage) => entry(VIRTUAL_TOGGLE, 0, usage, `Toggle ${MCHOSE_USAGE_NAMES[usage]}`)), ] }, { name: "Hold for modifier", keys: HOLDS.map(([mask, label]) => entry(VIRTUAL_MOD_TAP, mask, 0, `Tap: key, hold: ${label}`)) }, ]; } /** The text to show for a key that uses a slot. */ export function describeSlot(action: MchoseAction, tables: { modTap: { tap: MchoseAction; hold: MchoseAction }[]; toggle: MchoseAction[] }): string | null { const name = (a: MchoseAction) => mchoseActionLabel(a) ?? "?"; if (action.type === MCHOSE_ACTION_TYPE.toggle) return `Toggle ${name(tables.toggle[action.code1] ?? { type: 0, code1: 0, code2: 0 })}`; if (action.type === MCHOSE_ACTION_TYPE.modTap) { const slot = tables.modTap[action.code1]; return slot ? `${name(slot.tap)} · hold ${name(slot.hold)}` : "Mod-tap"; } return null; } const same = (a: MchoseAction, b: MchoseAction) => a.type === b.type && a.code1 === b.code1 && a.code2 === b.code2; const empty = (a: MchoseAction) => a.type === 0 && a.code1 === 0 && a.code2 === 0; /** * Sets a toggle or mod-tap key: writes its slot, then the key. Returns the action stored on the key. * `tap` is what a mod-tap key does when tapped (what the key did before). */ export async function setSlotKey(client: any, profile: number, layer: number, col: number, virtual: MchoseAction, tap: MchoseAction): Promise { const tables = await client.readAdvancedKeys(profile); if (virtual.type === VIRTUAL_TOGGLE) { const target = mchoseKeyAction(virtual.code2, virtual.code1); let slot = tables.toggle.findIndex((a: MchoseAction) => same(a, target)); if (slot < 0) { slot = tables.toggle.findIndex(empty); if (slot < 0) throw new RangeError(`All ${MCHOSE_ADVANCED_SLOTS} toggle slots are in use.`); await client.setToggle(profile, slot, target); } const layerNow: MchoseAction[] = await client.setKeymap(profile, layer, [{ index: col, action: { type: MCHOSE_ACTION_TYPE.toggle, code1: slot, code2: 0 } }]); await freeUnusedSlots(client, profile); return layerNow[col]; } // Mod-tap: the tap action keeps working; the hold is the modifier. const hold = mchoseKeyAction(0, virtual.code1); const entryWanted = { tap, hold }; let slot = tables.modTap.findIndex((m: any) => same(m.tap, tap) && same(m.hold, hold)); if (slot < 0) { slot = tables.modTap.findIndex((m: any) => empty(m.tap) && empty(m.hold)); if (slot < 0) throw new RangeError(`All ${MCHOSE_ADVANCED_SLOTS} mod-tap slots are in use.`); await client.setModTap(profile, slot, entryWanted); } const layerNow: MchoseAction[] = await client.setKeymap(profile, layer, [{ index: col, action: { type: MCHOSE_ACTION_TYPE.modTap, code1: slot, code2: MOD_TAP_HOLD_STEPS } }]); await freeUnusedSlots(client, profile); return layerNow[col]; } /** Clears toggle and mod-tap slots that no key on any layer of the profile points at. */ export async function freeUnusedSlots(client: any, profile: number): Promise { const used = { toggle: new Set(), modTap: new Set() }; for (let layer = 0; layer < MCHOSE_LAYER_COUNT; layer += 1) { const keys: MchoseAction[] = await client.readKeymap(profile, layer); for (const a of keys) { if (a.type === MCHOSE_ACTION_TYPE.toggle) used.toggle.add(a.code1); // Snap, SOCD and layer-tap keys share the mod-tap table. if ([0x92, 0x93, 0x94, 0x95].includes(a.type)) used.modTap.add(a.code1); } } const tables = await client.readAdvancedKeys(profile); for (let slot = 0; slot < MCHOSE_ADVANCED_SLOTS; slot += 1) { if (!used.toggle.has(slot) && !empty(tables.toggle[slot])) await client.clearSlot(profile, "toggle", slot); if (!used.modTap.has(slot) && !(empty(tables.modTap[slot].tap) && empty(tables.modTap[slot].hold))) await client.clearSlot(profile, "modTap", slot); } } // --- Macros ---------------------------------------------------------------- const tokenName = (name: string) => name.replace(/\s+/g, ""); const NAME_TO_USAGE = new Map(Object.entries(MCHOSE_USAGE_NAMES).map(([usage, name]) => [tokenName(name).toLowerCase(), Number(usage)])); const MODIFIER_USAGES: Record = { ctrl: 0xe0, shift: 0xe1, alt: 0xe2, win: 0xe3 }; const MOUSE: Record = { lmb: 1, rmb: 2, mmb: 4 }; function codeOf(token: string): { kind: "key" | "mouse"; code: number } { const name = token.toLowerCase(); if (name in MOUSE) return { kind: "mouse", code: MOUSE[name] }; const code = MODIFIER_USAGES[name] ?? NAME_TO_USAGE.get(name); if (code === undefined) throw new RangeError(`Unknown key "${token}" in the macro.`); return { kind: "key", code }; } /** * Macro text: `+A` presses a key, `-A` releases it, `A` taps it, a bare number waits that many milliseconds. * Keys are named as on the key picker (A, Enter, Space, Ctrl, Shift…); `LMB`, `RMB`, `MMB` are mouse buttons. */ export function parseMacro(text: string): MchoseMacroStep[] { const steps: MchoseMacroStep[] = []; for (const token of text.split(/\s+/).filter(Boolean)) { if (/^\d+$/.test(token)) { const ms = Number(token); if (ms < MCHOSE_MACRO_MIN_DELAY_MS || ms > MCHOSE_MACRO_MAX_DELAY_MS) throw new RangeError(`A wait must be ${MCHOSE_MACRO_MIN_DELAY_MS} to ${MCHOSE_MACRO_MAX_DELAY_MS} ms.`); if (steps.length === 0) throw new RangeError("Start the macro with a key, not a wait."); const last = steps[steps.length - 1]; if (last.delayMs + ms > MCHOSE_MACRO_MAX_DELAY_MS) throw new RangeError(`A wait must be ${MCHOSE_MACRO_MIN_DELAY_MS} to ${MCHOSE_MACRO_MAX_DELAY_MS} ms.`); last.delayMs += ms; continue; } const sign = token[0] === "+" || token[0] === "-" ? token[0] : ""; const target = codeOf(sign ? token.slice(1) : token); if (sign === "") { steps.push({ ...target, down: true, delayMs: 0 }, { ...target, down: false, delayMs: 0 }); } else { steps.push({ ...target, down: sign === "+", delayMs: 0 }); } } if (steps.length > 200) throw new RangeError("A macro can have at most 200 steps."); return steps; } const nameOf = (step: MchoseMacroStep): string => { if (step.kind === "mouse") return Object.entries(MOUSE).find(([, bit]) => bit === step.code)?.[0].toUpperCase() ?? `Button${step.code}`; const modifier = Object.entries(MODIFIER_USAGES).find(([, code]) => code === step.code)?.[0]; if (modifier) return modifier[0].toUpperCase() + modifier.slice(1); return tokenName(MCHOSE_USAGE_NAMES[step.code] ?? `Key${step.code}`); }; const tapSafe = (name: string) => !/^\d+$/.test(name) && name[0] !== "+" && name[0] !== "-"; /** The macro as text, folding press-and-release pairs into one tap. */ export function formatMacro(steps: readonly MchoseMacroStep[]): string { const out: string[] = []; for (let i = 0; i < steps.length; i += 1) { const step = steps[i]; const next = steps[i + 1]; const tapped = step.down && step.delayMs === 0 && next && !next.down && next.kind === step.kind && next.code === step.code && tapSafe(nameOf(step)); out.push(tapped ? nameOf(step) : `${step.down ? "+" : "-"}${nameOf(step)}`); const wait = tapped ? next.delayMs : step.delayMs; if (tapped) i += 1; if (wait > 0) out.push(String(wait)); } return out.join(" "); } export const MACRO_MODES = [ { value: MCHOSE_MACRO_MODE.once, label: "Play once" }, { value: MCHOSE_MACRO_MODE.whileHeld, label: "Repeat while held" }, { value: MCHOSE_MACRO_MODE.toggle, label: "Repeat until pressed again" }, ]; // --- Opposing-key pairs ---------------------------------------------------- /** Key pairs offered, by HID usage: each pair can use SOCD or rapid snap. */ export const PAIRS = [ { id: "wasd-ad", label: "A / D", a: 0x04, b: 0x07 }, { id: "wasd-ws", label: "W / S", a: 0x1a, b: 0x16 }, { id: "arrows-lr", label: "Left / Right arrow", a: 0x50, b: 0x4f }, { id: "arrows-ud", label: "Up / Down arrow", a: 0x52, b: 0x51 }, ]; /** Option values: -1 off, 0-3 SOCD rule, 10 rapid snap. */ export const PAIR_OFF = -1; export const PAIR_SNAP = 10; export const PAIR_OPTIONS = [ { value: PAIR_OFF, label: "Off" }, { value: 0, label: "SOCD: last pressed wins" }, { value: 1, label: "SOCD: first key wins" }, { value: 2, label: "SOCD: second key wins" }, { value: 3, label: "SOCD: neither" }, { value: PAIR_SNAP, label: "Rapid snap" }, ]; /** Layers a pair is applied to: the Windows and the Mac base layer. */ const PAIR_LAYERS = [0, 2]; const MIRROR = (rule: number) => (rule === 1 ? 2 : rule === 2 ? 1 : rule); /** Matrix index of the key whose factory action on `layer` is this usage. */ async function colOf(client: any, layer: number, usage: number): Promise { const factory: MchoseAction[] = await client.readDefaultKeymap(layer); const col = factory.findIndex((a) => a.type === MCHOSE_ACTION_TYPE.key && a.code1 === 0 && a.code2 === usage); if (col < 0) throw new RangeError("This keyboard layout has no such key."); return col; } /** The pair settings, as option values, read from the Windows layer. */ export async function readPairs(client: any, profile: number): Promise> { const keymap: MchoseAction[] = await client.readKeymap(profile, PAIR_LAYERS[0]); const travel = await client.readKeyTravel(profile); const out: Record = {}; for (const pair of PAIRS) { const col = await colOf(client, PAIR_LAYERS[0], pair.a); const action = keymap[col]; out[pair.id] = action.type === 0x93 ? PAIR_SNAP : action.type === 0x94 ? travel[col].priority : PAIR_OFF; } return out; } /** Sets a pair on both base layers; the keys' slots are written first and freed afterwards if unused. */ export async function setPair(client: any, profile: number, pairId: string, option: number): Promise { const pair = PAIRS.find((p) => p.id === pairId); if (!pair) throw new RangeError("That key pair does not exist."); if (option !== PAIR_OFF && option !== PAIR_SNAP && !(Number.isInteger(option) && option >= 0 && option <= 3)) throw new RangeError("Pick how the pair behaves."); const plans = new Map(); if (option !== PAIR_OFF) { const tables = await client.readAdvancedKeys(profile); const claimed = new Set(); const slotFor = (keymap: MchoseAction[], col: number): number => { const now = keymap[col]; if ((now.type === 0x93 || now.type === 0x94) && !claimed.has(now.code1)) return now.code1; for (let s = 0; s < MCHOSE_ADVANCED_SLOTS; s += 1) { if (!claimed.has(s) && empty(tables.modTap[s].tap) && empty(tables.modTap[s].hold)) return s; } throw new RangeError("All mod-tap slots are in use."); }; for (const layer of PAIR_LAYERS) { const keymap: MchoseAction[] = await client.readKeymap(profile, layer); const slotA = slotFor(keymap, await colOf(client, layer, pair.a)); claimed.add(slotA); const slotB = slotFor(keymap, await colOf(client, layer, pair.b)); claimed.add(slotB); plans.set(layer, { slotA, slotB }); } } for (const layer of PAIR_LAYERS) { const colA = await colOf(client, layer, pair.a); const colB = await colOf(client, layer, pair.b); const factory: MchoseAction[] = await client.readDefaultKeymap(layer); const plainA = factory[colA]; const plainB = factory[colB]; if (option === PAIR_OFF) { await client.setKeymap(profile, layer, [{ index: colA, action: plainA }, { index: colB, action: plainB }]); continue; } const { slotA, slotB } = plans.get(layer)!; await client.setModTap(profile, slotA, { tap: plainA, hold: plainB }); await client.setModTap(profile, slotB, { tap: plainB, hold: plainA }); const type = option === PAIR_SNAP ? 0x93 : 0x94; await client.setKeymap(profile, layer, [ { index: colA, action: { type, code1: slotA, code2: colB } }, { index: colB, action: { type, code1: slotB, code2: colA } }, ]); } // The rule lives on the keys' travel records, the same for both layers. const colA = await colOf(client, PAIR_LAYERS[0], pair.a); const colB = await colOf(client, PAIR_LAYERS[0], pair.b); const rule = option >= 0 && option <= 3 ? option : 0; await client.setKeyTravel(profile, [{ index: colA, priority: rule }, { index: colB, priority: MIRROR(rule) }]); await freeUnusedSlots(client, profile); } export async function detachPair(client: any, profile: number, layer: number, col: number, action: MchoseAction): Promise { if (action.type !== 0x93 && action.type !== 0x94) return; for (const pair of PAIRS) { if (col === await colOf(client, layer, pair.a) || col === await colOf(client, layer, pair.b)) { await setPair(client, profile, pair.id, PAIR_OFF); return; } } } // --- Calibration ----------------------------------------------------------- /** Progress of a calibration this session started: reports are collected while it runs. */ const calibration: { stop: (() => void) | null; seen: Map; total: number; client: any; profile: number } = { stop: null, seen: new Map(), total: 0, client: null, profile: 0 }; function endCalibrationSession(): void { calibration.stop?.(); calibration.stop = null; const client = calibration.client; calibration.client = null; if (client) { client.keepOpen = false; client.close().catch(() => undefined); } } const sameKeyboard = (a: any, b: any) => a?.device?.vendorId === b?.device?.vendorId && a?.device?.productId === b?.device?.productId; const reportKey = (r: { type: number; code1: number; code2: number }) => `${r.type}:${r.code1}:${r.code2}`; /** The calibration control as it stands now; needs no traffic to the keyboard, so it can be asked often. */ export function calibrationStatus() { const running = calibration.stop !== null; const done = [...calibration.seen.values()].filter((state) => state === "done").length; const waiting = [...calibration.seen.values()].filter((state) => state === "pending").length; return { id: "mchose.kb.calibrate", label: "Calibrate keys", kind: "choice", current: -1, options: [{ value: -1, label: running ? `Running: ${done} of ${calibration.total} keys done${waiting ? `, ${waiting} pressed once` : ""}` : "Choose…" }, ...(running ? [{ value: 1, label: "Finish" }, { value: 2, label: "Start over" }] : [{ value: 0, label: "Start" }])], description: "Start, then press every key all the way down twice (the key lights go blue, then green), then Finish. Don't touch settings while it runs.", }; } export const calibrationControl = async (_client: unknown, _profile: number) => calibrationStatus(); /** Starts, restarts or ends calibration of the active profile. */ export async function runCalibration(client: any, profile: number, step: number): Promise { if (step === 0) { if (calibration.stop) throw new RangeError("A calibration is already running."); try { await client.setDebugMode(profile, true); const factory: MchoseAction[] = await client.readDefaultKeymap(0); calibration.total = factory.filter((a) => a.type !== 0 && !(a.type === MCHOSE_ACTION_TYPE.key && a.code1 === 0 && a.code2 === 0)).length; calibration.seen.clear(); client.keepOpen = true; calibration.client = client; calibration.profile = profile; calibration.stop = client.onKeyReport((r: { type: number; code1: number; code2: number; calibration: string }) => { if (r.calibration !== "none") calibration.seen.set(reportKey(r), r.calibration); }); await client.calibrate("start"); } catch (error) { await client.calibrate("end").catch(() => undefined); await client.setDebugMode(profile, false).catch(() => undefined); endCalibrationSession(); throw error; } } else if (step === 2) { if (!calibration.stop) throw new RangeError("No calibration is running."); if (!sameKeyboard(client, calibration.client)) throw new RangeError("The calibration is running on another keyboard."); calibration.seen.clear(); await calibration.client.calibrate("restart"); } else if (step === 1) { if (!calibration.stop) throw new RangeError("No calibration is running."); if (!sameKeyboard(client, calibration.client)) throw new RangeError("The calibration is running on another keyboard."); const { client: running, profile: started } = calibration; try { await running.calibrate("end"); await running.setDebugMode(started, false); } finally { endCalibrationSession(); } } else { throw new RangeError("Pick what to do."); } } // --- Saved profiles -------------------------------------------------------- type Files = (action: string, name: string, text: string) => string; const files = (): Files | null => (globalThis as any).__host?.profileFiles ?? null; function fileCall(action: string, name = "", text = ""): any { const call = files(); if (!call) throw new Error("Saved profiles are not available here."); const answer = JSON.parse(call(action, name, text)); if (answer.error) throw new Error(answer.error); return answer.ok; } /** The saved profile controls: a name to save the active profile under, and the saved ones to load. */ export function savedProfileControls(): object[] { if (!files()) return []; let names: string[] = []; try { names = fileCall("list"); } catch { /* an unreadable folder just lists nothing */ } return [ { id: "mchose.kb.saveprofile", label: "Save profile as", kind: "text", current: "", description: "Saves the active profile's settings, lighting, keys and actuation to a file; macros and the name are not included. Type a name." }, ...(names.length > 0 ? [{ id: "mchose.kb.loadprofile", label: "Load saved profile", kind: "choice", current: "", options: [{ value: "", label: "Choose…" }, ...names.map((name) => ({ value: name, label: name }))], description: "Replaces the active profile's contents with a saved one.", }] : []), ]; } export async function saveProfileFile(client: any, profile: number, name: unknown): Promise { if (typeof name !== "string" || name.trim() === "") throw new RangeError("Type a name for the saved profile."); const snapshot = await client.exportProfile(profile); fileCall("save", name.trim(), JSON.stringify({ productId: client.device.productId, snapshot })); } export async function loadProfileFile(client: any, profile: number, name: unknown): Promise { if (name === "") return; if (typeof name !== "string") throw new RangeError("Pick a saved profile."); let saved: any; try { saved = JSON.parse(fileCall("load", name)); } catch (error) { throw error instanceof SyntaxError ? new RangeError("That profile file is damaged.") : error; } if (saved?.productId !== client.device.productId) throw new RangeError("That profile was saved from a different keyboard model."); await client.importProfile(profile, saved.snapshot); }