diff --git a/gpui/js/entry.ts b/gpui/js/entry.ts index 0e3bf3c8..6d417f6e 100644 --- a/gpui/js/entry.ts +++ b/gpui/js/entry.ts @@ -10,7 +10,7 @@ import { connectKeyboard, describeKeyboard, listKeyboards, keyboardOp, writeKeyb import { DepthStream, openTravel } from "./depth-stream"; import { napeEditedLayer, readNapeLayer } from "./nape-controls"; import { ALL_STAGE_SUPPORT, driverSetters, stageSupport } from "./dpi-stages"; -import { isMockKey, mockBrand, mockKeyboard, mockKeyboardOp, mockCandidates, mockDepths, mockOnboard, mockOnboardAction, mockStatus } from "./mock"; +import { isMockKey, mockBrand, mockKeyboard, mockKeyboardOp, mockMchoseSections, mockMchoseWrite, mockCandidates, mockDepths, mockOnboard, mockOnboardAction, mockStatus } from "./mock"; import { artBounds, deviceImageCandidates } from "./native-hid/device-images"; import * as logitechWrite from "./native-hid/logitech-actions"; import * as genericWrite from "./native-hid/write"; @@ -112,7 +112,7 @@ const mockWanted = (): string => String((globalThis as any).__mock ?? ""); const { key, action, args } = JSON.parse(argsJson) as { key: string; action: string; args: any }; const candidate = lastList.get(key); if (!candidate) throw new Error(`Unknown interface ${key}; list candidates first.`); - if (isMockKey(key)) return JSON.stringify(mockKeyboardOp(action, args)); + if (isMockKey(key)) return JSON.stringify(mockKeyboardOp(action, args, key)); return JSON.stringify(await keyboardOp(candidate.info, action, args)); }, async connect(key: string): Promise { @@ -121,7 +121,10 @@ const mockWanted = (): string => String((globalThis as any).__mock ?? ""); if (!candidate) throw new Error(`Unknown interface ${key}; list candidates first.`); const mock = isMockKey(key); if ((candidate as any).kind === "keyboard") { - return JSON.stringify(mock ? describeKeyboard(key, "Wuque Studio", mockKeyboard()) : await connectKeyboard(candidate.info)); + if (!mock) return JSON.stringify(await connectKeyboard(candidate.info)); + const mocked = describeKeyboard(key, mockKeyboard(key).brand, mockKeyboard(key)); + if (key === "mock:mchose") mocked.tabs.advanced.unshift(...(mockMchoseSections() as any[])); + return JSON.stringify(mocked); } const device = mock ? { key, brand: mockBrand(key), driver: "Mock", status: mockStatus(key) as any } : await connectToInterface(candidate.info); const caps = mock ? ({ sleepTimeouts: null, lowPowerThresholds: null, debounceMaxMs: null, debounceOptions: null, dpiMax: 26000 } as any) : deviceCapabilities(candidate.info); @@ -279,6 +282,7 @@ const mockWanted = (): string => String((globalThis as any).__mock ?? ""); if (!candidate) throw new Error(`Unknown interface ${key}; list candidates first.`); await travel.stop(key); if ((candidate as any).kind === "keyboard") { + if (key === "mock:mchose") return JSON.stringify(mockMchoseWrite(action, value)); return JSON.stringify(isMockKey(key) ? value : await writeKeyboard(candidate.info, action, value)); } const w = brand === "Logitech" ? logitechWrite : genericWrite; diff --git a/gpui/js/keyboard-mchose-advanced.ts b/gpui/js/keyboard-mchose-advanced.ts new file mode 100644 index 00000000..bcbee4d9 --- /dev/null +++ b/gpui/js/keyboard-mchose-advanced.ts @@ -0,0 +1,411 @@ +// 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); +} diff --git a/gpui/js/keyboard-mchose.ts b/gpui/js/keyboard-mchose.ts new file mode 100644 index 00000000..c94adc1f --- /dev/null +++ b/gpui/js/keyboard-mchose.ts @@ -0,0 +1,539 @@ +// MCHOSE keyboards: the backlight (effect, brightness, speed, direction, colour +// and a colour for every key), each key's actuation and rapid trigger, and the +// keyboard's settings, all for the active profile. Every change is read back by the driver before +// it is reported as made, and settings live on the keyboard at once. +// +// Only the main backlight is edited. A light box (side zone) is carried through +// untouched. Settings are edited in place and live on the keyboard at once. + +import { + MCHOSE_LIGHT_OFF, MCHOSE_MAX_PROFILES, MCHOSE_SPEED_MAX, + MCHOSE_ACTION_TYPE, MCHOSE_MEDIA_NAMES, MCHOSE_MODIFIER, MCHOSE_MOUSE_NAMES, MCHOSE_SPECIAL_NAMES, MCHOSE_SYSTEM_NAMES, MCHOSE_USAGE_NAMES, + mchoseActionFromValue, mchoseActionLabel, mchoseActionValue, mchoseDisplayProfileName, mchoseKeyAction, mchoseLayoutFromDefaults, mchoseMmToSteps, mchoseModel, mchoseProduct, mchoseRapidTriggerStep, mchoseStepsToMm, + type MchoseAction, type MchoseKeyTravel, type MchoseMacro, type MchoseKeyTravelUpdate, type MchoseLighting, type MchoseSettings, +} from "@openmouse/keyboard-protocol/mchose"; +import { + MACRO_MODES, VIRTUAL_MOD_TAP, VIRTUAL_TOGGLE, advancedCategories, describeSlot, formatMacro, calibrationControl, calibrationStatus, freeUnusedSlots, loadProfileFile, saveProfileFile, savedProfileControls, runCalibration, PAIRS, PAIR_OPTIONS, readPairs, setPair, parseMacro, setSlotKey, detachPair, +} from "./keyboard-mchose-advanced"; + +export const MCHOSE_FEATURES = { actuation: true, remap: true, lighting: true }; + +/** + * What an effect's direction switch does, from sampling the live colours of an + * Ace 68 V2 III: the first name is the keyboard's value 0, the second its + * value 1. The spin has no direction that reads clearly from the colours + * alone, so it is only called forward and reverse. + */ +const DIRECTIONS: Record = { + 6: ["Left to right", "Right to left"], + 7: ["Top to bottom", "Bottom to top"], + 8: ["Outward", "Inward"], + 10: ["Forward", "Reverse"], +}; + +/** "Constant on", the effect a board returns to when it is switched on without a remembered one. */ +const DEFAULT_EFFECT = 3; +/** The effect before the backlight was switched off, so switching it on again restores it. */ +const beforeOff = new Map(); + +const byte = (value: unknown): value is number => Number.isInteger(value) && (value as number) >= 0 && (value as number) <= 255; + +async function load(client: any) { + const model = mchoseModel(client.device.productId); + if (!model) throw new Error("This MCHOSE keyboard has no lighting description."); + const { activeProfile } = await client.readBase(); + const lighting: MchoseLighting = await client.readLighting(activeProfile); + return { profile: activeProfile as number, lighting, model, memory: `${client.device.productId}:${activeProfile}` }; +} + +function describe(lighting: MchoseLighting, effects: readonly { value: number; name: string; speed: boolean; direction: boolean; color: boolean }[], memory: string) { + const { main } = lighting; + const on = main.effect !== MCHOSE_LIGHT_OFF; + if (on) beforeOff.set(memory, main.effect); + return { + on, + effect: on ? main.effect : beforeOff.get(memory) ?? DEFAULT_EFFECT, + brightness: main.brightness, + speed: main.speed, + speedMax: MCHOSE_SPEED_MAX, + direction: main.direction, + rainbow: main.rainbow, + rgb: [main.color.r, main.color.g, main.color.b], + effects: effects.map((e) => ({ + value: e.value, + name: e.name, + speed: e.speed, + direction: e.direction, + colour: e.color, + directions: e.direction ? DIRECTIONS[e.value] ?? ["Forward", "Reverse"] : null, + })), + }; +} + +async function readLights(client: any) { + const { lighting, model, memory } = await load(client); + return describe(lighting, model.effects.main, memory); +} + +async function setLights(client: any, wanted: any) { + const { profile, lighting, model, memory } = await load(client); + const known = model.effects.main.some((effect) => effect.value === wanted.effect); + const rgb: unknown[] = Array.isArray(wanted.rgb) ? wanted.rgb : []; + if (!known || typeof wanted.on !== "boolean" || typeof wanted.rainbow !== "boolean" + || !Number.isInteger(wanted.brightness) || wanted.brightness < 0 || wanted.brightness > 100 + || !Number.isInteger(wanted.speed) || wanted.speed < 0 || wanted.speed > MCHOSE_SPEED_MAX + || ![0, 1].includes(wanted.direction) || rgb.length !== 3 || !rgb.every(byte)) { + throw new RangeError("That lighting value is out of range."); + } + const [r, g, b] = rgb as number[]; + const main = { + ...lighting.main, + effect: wanted.on ? wanted.effect : MCHOSE_LIGHT_OFF, + brightness: wanted.brightness, + speed: wanted.speed, + direction: wanted.direction, + rainbow: wanted.rainbow, + color: { r, g, b }, + }; + // The driver writes only what changed and compares the whole config on read-back. + const confirmed: MchoseLighting = await client.setLighting(profile, { ...lighting, main }); + return describe(confirmed, model.effects.main, memory); +} + +/** The effect that shows the per-key colours. */ +const CUSTOM_EFFECT = 0; + + +/** + * Every key with where it sits and its own colour, in the shape the keyboard + * pages draw. `col` is the key's slot in the colour table, which is what a + * colour is written to. + */ +async function readKeyColours(client: any) { + const { profile, model } = await load(client); + // The keyboard's own default keymap places each key, as the vendor app does. + const layout = mchoseLayoutFromDefaults(await client.readDefaultKeymap(0), model.layout); + const colours: { r: number; g: number; b: number }[] = await client.readKeyColors(profile); + return { + layer: 0, + layers: 1, + width: Math.max(...layout.map((key) => key.x + key.width)), + keys: layout.map((key) => { + const c = colours[key.index] ?? { r: 0, g: 0, b: 0 }; + return { row: key.row, col: key.index, x: key.x, y: key.row, w: key.width, label: key.label, colour: [c.r, c.g, c.b] }; + }), + categories: [], + }; +} + +/** Paints keys one colour. The Custom effect is the one that shows them, so it is switched to. */ +async function setKeyColours(client: any, args: any) { + const rgb: unknown[] = Array.isArray(args.rgb) ? args.rgb : []; + const slots: unknown[] = Array.isArray(args.keys) ? args.keys : []; + if (rgb.length !== 3 || !rgb.every(byte) || slots.length === 0 || !slots.every((slot) => Number.isInteger(slot) && (slot as number) >= 0 && (slot as number) < 128)) { + throw new RangeError("Those keys or that colour can't be set."); + } + const { profile, lighting, model, memory } = await load(client); + const [r, g, b] = rgb as number[]; + const written: { r: number; g: number; b: number }[] = await client.setKeyColors( + profile, + (slots as number[]).map((index) => ({ index, color: { r, g, b } })), + ); + let shown = lighting; + if (lighting.main.effect !== CUSTOM_EFFECT) { + shown = await client.setLighting(profile, { ...lighting, main: { ...lighting.main, effect: CUSTOM_EFFECT } }); + } + return { + keys: (slots as number[]).map((col) => ({ col, colour: [written[col].r, written[col].g, written[col].b] })), + lights: describe(shown, model.effects.main, memory), + }; +} + +// --- Actuation and rapid trigger ------------------------------------------- + +/** The numbers the actuation page edits, in millimetres, with the keyboard's limits. */ +const FIELDS = [ + { id: "travel", name: "Actuation point", hint: "How far a key goes down before it registers.", min: 0.1, max: 3.4 }, + { id: "rtPress", name: "Rapid trigger: press", hint: "How far back down it registers again.", min: 0.02, max: 3.4 }, + { id: "rtRelease", name: "Rapid trigger: release", hint: "How far up it lets go.", min: 0.02, max: 3.4 }, + { id: "deadPress", name: "Top dead zone", hint: "Travel at the top that does not count, so a light touch can't register.", min: 0, max: 0.5 }, + { id: "deadRelease", name: "Bottom dead zone", hint: "Travel at the bottom that does not count, so a key held down can't be missed.", min: 0, max: 0.5 }, +] as const; + +/** The key modes, as the vendor's trigger page names them (see MCHOSE_KEY_MODE in the driver). */ +const MODES = [ + { value: 0, label: "Off" }, + { value: 1, label: "Quick trigger" }, + { value: 2, label: "Quick + rapid trigger" }, +] as const; + +/** A key's settings in millimetres, by the names the page uses. */ +function travelMm(record: MchoseKeyTravel) { + const press = mchoseRapidTriggerStep(record.pressPrecision).stepMm; + const release = mchoseRapidTriggerStep(record.releasePrecision).stepMm; + return { + travel: mchoseStepsToMm(record.actuation), + rtPress: mchoseStepsToMm(record.rapidTriggerPress, press), + rtRelease: mchoseStepsToMm(record.rapidTriggerRelease, release), + deadPress: mchoseStepsToMm(record.pressDeadzone), + deadRelease: mchoseStepsToMm(record.releaseDeadzone), + mode: record.keyMode, + }; +} + +/** The layers of a profile, in the order the keyboard stores them. */ +const LAYERS = ["Windows", "Windows Fn", "Mac", "Mac Fn"]; + +/** Functions that are safe to put on a key; the factory reset function is left out on purpose. */ +const SPECIAL_HIDDEN = new Set([0x0800]); + +/** What a key can be set to, grouped as the vendor's key mapping page groups them. */ +function categories() { + const entry = (action: MchoseAction, label: string) => ({ code: mchoseActionValue(action), label }); + const key = (usage: number) => entry(mchoseKeyAction(usage), MCHOSE_USAGE_NAMES[usage]); + const named = (names: Readonly>, make: (code: number) => MchoseAction) => + Object.entries(names).map(([code, label]) => entry(make(Number(code)), label)); + const modifiers: [number, string][] = [ + [MCHOSE_MODIFIER.leftCtrl, "Ctrl"], [MCHOSE_MODIFIER.leftShift, "Shift"], [MCHOSE_MODIFIER.leftAlt, "Alt"], [MCHOSE_MODIFIER.leftWin, "Win"], + [MCHOSE_MODIFIER.rightCtrl, "Right Ctrl"], [MCHOSE_MODIFIER.rightShift, "Right Shift"], [MCHOSE_MODIFIER.rightAlt, "Right Alt"], [MCHOSE_MODIFIER.rightWin, "Right Win"], + ]; + return [ + { name: "Keys", keys: [entry({ type: MCHOSE_ACTION_TYPE.key, code1: 0, code2: 0 }, "Disabled"), ...Object.keys(MCHOSE_USAGE_NAMES).map((usage) => key(Number(usage)))] }, + { name: "Modifiers", keys: modifiers.map(([mask, label]) => entry({ type: MCHOSE_ACTION_TYPE.key, code1: mask, code2: 0 }, label)) }, + { name: "Mouse", keys: [ + ...named(MCHOSE_MOUSE_NAMES, (mask) => ({ type: MCHOSE_ACTION_TYPE.mouse, code1: mask, code2: 0 })), + entry({ type: MCHOSE_ACTION_TYPE.wheel, code1: 0, code2: 1 }, "Wheel up"), + entry({ type: MCHOSE_ACTION_TYPE.wheel, code1: 0, code2: 0xff }, "Wheel down"), + ] }, + { name: "Media", keys: named(MCHOSE_MEDIA_NAMES, (usage) => ({ type: MCHOSE_ACTION_TYPE.media, code1: usage & 0xff, code2: usage >> 8 })) }, + { name: "System", keys: named(MCHOSE_SYSTEM_NAMES, (code) => ({ type: MCHOSE_ACTION_TYPE.system, code1: code, code2: 0 })) }, + { name: "Keyboard", keys: Object.entries(MCHOSE_SPECIAL_NAMES) + .filter(([code]) => !SPECIAL_HIDDEN.has(Number(code))) + .map(([code, label]) => entry({ type: MCHOSE_ACTION_TYPE.special, code1: Number(code) >> 8, code2: Number(code) & 0xff }, label)) }, + ...advancedCategories(), + ]; +} + +/** Every key with where it sits, what it does on `layer`, and its actuation settings. */ +async function readKeys(client: any, layerArg?: unknown) { + const layer = Number.isInteger(layerArg) && (layerArg as number) >= 0 && (layerArg as number) < LAYERS.length ? (layerArg as number) : 0; + const { profile, model } = await load(client); + const layout = mchoseLayoutFromDefaults(await client.readDefaultKeymap(0), model.layout); + const travel: MchoseKeyTravel[] = await client.readKeyTravel(profile); + const now: MchoseAction[] = await client.readKeymap(profile, layer); + const factory: MchoseAction[] = await client.readDefaultKeymap(layer); + const tables = await client.readAdvancedKeys(profile); + const name = (action: MchoseAction) => describeSlot(action, tables) ?? mchoseActionLabel(action) ?? "?"; + return { + layer, + layers: LAYERS.length, + layerNames: LAYERS, + width: Math.max(...layout.map((key) => key.x + key.width)), + // Changes are in the keyboard's profile as soon as they are made. + stored: true, + fields: FIELDS, + modes: MODES, + categories: categories(), + keys: layout.map((key) => ({ + row: key.row, + col: key.index, + x: key.x, + y: key.row, + w: key.width, + code: mchoseActionValue(now[key.index]), + label: name(now[key.index]), + standard: mchoseActionValue(factory[key.index]), + standardLabel: name(factory[key.index]), + actuation: travelMm(travel[key.index]), + })), + }; +} + +/** Puts an action on a key of one layer; the driver reads the layer back. */ +async function setKey(client: any, args: any) { + const { layer, col, code } = args; + if (![layer, col, code].every(Number.isInteger) || layer < 0 || layer >= LAYERS.length || col < 0 || col >= 128 || code < 0 || code > 0xffffff) { + throw new RangeError("That key can't be assigned."); + } + const action = mchoseActionFromValue(code); + if (action.type === VIRTUAL_TOGGLE || action.type === VIRTUAL_MOD_TAP) { + const { profile } = await load(client); + // A mod-tap key keeps doing what it did when it is tapped; a key already using a slot falls back to its factory action. + const now: MchoseAction[] = await client.readKeymap(profile, layer); + const plain = (a: MchoseAction) => a.type !== MCHOSE_ACTION_TYPE.toggle && a.type !== MCHOSE_ACTION_TYPE.modTap && a.type !== MCHOSE_ACTION_TYPE.dks && ![0x92, 0x93, 0x94, 0x95].includes(a.type); + const tap = plain(now[col]) ? now[col] : (await client.readDefaultKeymap(layer))[col]; + await detachPair(client, profile, layer, col, now[col]); + const written = await setSlotKey(client, profile, layer, col, action, tap); + const tables = await client.readAdvancedKeys(profile); + return { row: args.row ?? 0, col, code: mchoseActionValue(written), label: describeSlot(written, tables) ?? mchoseActionLabel(written) ?? "?" }; + } + const known = action.type === MCHOSE_ACTION_TYPE.key || mchoseActionLabel(action) !== null; + if (!known) throw new RangeError("That action is not one this keyboard offers."); + const { profile } = await load(client); + await detachPair(client, profile, layer, col, (await client.readKeymap(profile, layer))[col]); + const written: MchoseAction[] = await client.setKeymap(profile, layer, [{ index: col, action }]); + // A key that used a toggle or mod-tap slot has just left it. + await freeUnusedSlots(client, profile); + return { row: args.row ?? 0, col, code: mchoseActionValue(written[col]), label: mchoseActionLabel(written[col]) ?? "?" }; +} + +/** Changes the given fields on each key, keeping the rest as the keyboard has them. */ +async function setActuation(client: any, args: any) { + const keys: unknown[] = Array.isArray(args.keys) ? args.keys : []; + const patch: Record = args.patch ?? {}; + const known = new Set([...FIELDS.map((f) => f.id), "mode"]); + if (keys.length === 0 || Object.keys(patch).length === 0 || Object.keys(patch).some((name) => !known.has(name) || !Number.isFinite(patch[name])) + || !keys.every((key) => Array.isArray(key) && Number.isInteger(key[1]) && key[1] >= 0 && key[1] < 128)) { + throw new RangeError("Those keys or values can't be set."); + } + for (const field of FIELDS) { + const value = patch[field.id]; + if (value !== undefined && (value < field.min - 1e-9 || value > field.max + 1e-9)) throw new RangeError(`${field.name} must be ${field.min} to ${field.max} mm.`); + } + if (patch.mode !== undefined && !MODES.some((mode) => mode.value === patch.mode)) throw new RangeError("That trigger mode does not exist."); + const { profile } = await load(client); + const before: MchoseKeyTravel[] = await client.readKeyTravel(profile); + for (const [field, precision] of [["rtPress", "pressPrecision"], ["rtRelease", "releasePrecision"]] as const) { + if (patch[field] === undefined) continue; + const most = Math.min(...(keys as [number, number][]).map(([, index]) => { + const step = mchoseRapidTriggerStep(before[index][precision]); + return step.max * step.stepMm; + })); + if (patch[field] > most + 1e-9) throw new RangeError(`Rapid trigger on these keys goes up to ${most} mm.`); + } + const updates: MchoseKeyTravelUpdate[] = (keys as [number, number][]).map(([, index]) => { + const record = before[index]; + const update: MchoseKeyTravelUpdate = { index }; + // Distances are written in the key's own steps; its precision is kept. + if (patch.travel !== undefined) update.actuation = mchoseMmToSteps(patch.travel); + if (patch.rtPress !== undefined) update.rapidTriggerPress = mchoseMmToSteps(patch.rtPress, mchoseRapidTriggerStep(record.pressPrecision).stepMm); + if (patch.rtRelease !== undefined) update.rapidTriggerRelease = mchoseMmToSteps(patch.rtRelease, mchoseRapidTriggerStep(record.releasePrecision).stepMm); + if (patch.deadPress !== undefined) update.pressDeadzone = mchoseMmToSteps(patch.deadPress); + if (patch.deadRelease !== undefined) update.releaseDeadzone = mchoseMmToSteps(patch.deadRelease); + if (patch.mode !== undefined) update.keyMode = patch.mode; + return update; + }); + // The driver checks every value against the vendor's limits and reads the whole table back. + const now: MchoseKeyTravel[] = await client.setKeyTravel(profile, updates); + // An older driver ignores a key mode it does not know and would report success. + if (patch.mode !== undefined && updates.some(({ index }) => now[index].keyMode !== patch.mode)) { + throw new Error("This version of the keyboard library can't set that trigger mode."); + } + return updates.map(({ index }, i) => ({ row: (keys as [number, number][])[i][0], col: index, actuation: travelMm(now[index]) })); +} + +// --- Settings -------------------------------------------------------------- + +const PREFIX = "mchose.kb."; +export const isMchoseKeyboardControl = (action: string) => action.startsWith(`control:${PREFIX}`); + +const toggle = (id: string, label: string, current: boolean, description?: string) => ({ id: PREFIX + id, label, kind: "toggle", current, description }); +const choice = (id: string, label: string, current: number, options: { value: number; label: string }[], description?: string) => + ({ id: PREFIX + id, label, kind: "choice", current, options, description }); + +/** Settings that are one field of the keyboard's settings block. */ +const SETTINGS: Record = { + scan: { field: "scanRateRaw", type: "number", max: 3 }, + debounce: { field: "debounce", type: "boolean" }, + stability: { field: "bottomRapidTrigger", type: "boolean" }, + check: { field: "travelCheck", type: "boolean" }, + berserk: { field: "tachyonMode", type: "boolean" }, + rtsmart: { field: "rtSmart", type: "number", max: 15 }, + lockwin: { field: "lockWin", type: "boolean" }, + lockalttab: { field: "lockAltTab", type: "boolean" }, + lockaltf4: { field: "lockAltF4", type: "boolean" }, + mac: { field: "macMode", type: "boolean" }, + sleep: { field: "sleepEnabled", type: "boolean" }, + sleeptime: { field: "sleepTime", type: "number", max: 255 }, +}; + +/** The name to show: the user's own, or "Profile N" where the vendor app left a code. */ +const profileName = (name: string | null | undefined, index: number): string => + mchoseDisplayProfileName(name ?? null) ?? `Profile ${index + 1}`; + +/** Longest profile name the vendor app accepts. */ +const NAME_LENGTH = 15; + +const text = (id: string, label: string, current: string, description?: string) => ({ id: PREFIX + id, label, kind: "text", current, description }); + +/** Sleep delays offered, in the keyboard's 30-second steps; the current one is always among them. */ +const SLEEP_MINUTES = [1, 2, 5, 10, 30, 60]; + +export async function mchoseSections(client: any) { + const { activeProfile, profileCount, order } = await client.readBase(); + const product = mchoseProduct(client.device.vendorId, client.device.productId); + const [settings, performance, names]: [MchoseSettings, any, (string | null)[]] = await Promise.all([ + client.readSettings(activeProfile), + client.readPerformance(activeProfile), + client.readProfileNames().catch(() => []), + ]); + const macros: MchoseMacro[] = await client.readMacros().catch(() => []); + // Every macro in use, then one empty slot to start the next. + const used = macros.map((m, i) => (m.steps.length > 0 ? i : -1)).filter((i) => i >= 0); + const shown = [...used, ...(used.length < macros.length ? [macros.findIndex((m) => m.steps.length === 0)] : [])].filter((i) => i >= 0); + const macroControls = shown.flatMap((i) => [ + text(`macro.${i}`, `Macro ${i + 1}`, formatMacro(macros[i].steps), i === shown[shown.length - 1] && macros[i].steps.length === 0 + ? "Keys by name: +Ctrl presses, -Ctrl releases, A taps, a number waits that many ms. Example: +Ctrl C -Ctrl 50 Enter. Empty removes the macro." + : "Empty removes the macro."), + choice(`macromode.${i}`, `Macro ${i + 1} plays`, macros[i].mode, MACRO_MODES.some((m) => m.value === macros[i].mode) ? MACRO_MODES : [...MACRO_MODES, { value: macros[i].mode, label: "Custom" }]), + ]); + const pairs = await readPairs(client, activeProfile); + const saved = savedProfileControls(); + const rates = new Set(product?.pollingRatesHz ?? []); + if (performance.pollingHz) rates.add(performance.pollingHz); + const sleeps = new Set([...SLEEP_MINUTES.map((m) => m * 2), settings.sleepTime]); + const others = (order as number[]).slice(0, profileCount) + .filter((slot) => slot !== activeProfile) + .map((slot) => ({ value: slot, label: profileName(names[slot], slot) })); + return [ + { title: "Profile", controls: [ + choice("profile", "Active profile", activeProfile, + (order as number[]).slice(0, profileCount).map((slot) => ({ value: slot, label: profileName(names[slot], slot) })), + "Each profile keeps its own lighting, actuation and settings."), + text("name", "Profile name", profileName(names[activeProfile], activeProfile), `Up to ${NAME_LENGTH} characters.`), + ...(profileCount < MCHOSE_MAX_PROFILES ? [ + text("newprofile", "New profile", "", `Type a name to add a copy of the active profile (up to ${MCHOSE_MAX_PROFILES} on the keyboard).`), + ] : []), + ...(others.length > 0 ? [ + choice("deleteprofile", "Delete profile", -1, [{ value: -1, label: "Choose…" }, ...others], + "Removes another profile from the keyboard. The active profile stays."), + choice("resetprofile", "Reset profile", -1, [{ value: -1, label: "Choose…" }, ...others], + "Sets another profile back to the factory settings. The keyboard restarts."), + ] : []), + ] }, + { title: "Opposing keys", controls: PAIRS.map((pair) => + choice(`pair.${pair.id}`, pair.label, pairs[pair.id], PAIR_OPTIONS, + "SOCD decides what happens when both keys are held; rapid snap releases the first the moment the second goes down.")) }, + ...(saved.length ? [{ title: "Saved profiles", controls: saved }] : []), + { title: "Calibration", controls: [await calibrationControl(client, activeProfile)] }, + { title: "Macros", controls: macroControls }, + { title: "Performance", controls: [ + choice("polling", "Polling rate", performance.pollingHz ?? 0, [...rates].sort((a, b) => a - b).map((hz) => ({ value: hz, label: `${hz} Hz` }))), + choice("scan", "Key scan rate", settings.scanRateRaw, [0, 1, 2, 3].map((n) => ({ value: n, label: `${[1, 2, 4, 8][n]} kHz` })), + "How often the keyboard checks its keys."), + toggle("debounce", "Debounce optimisation", settings.debounce), + toggle("stability", "Stability mode", settings.bottomRapidTrigger), + toggle("check", "Travel self-check", settings.travelCheck), + ] }, + { title: "Rapid trigger", controls: [ + choice("rtsmart", "Smart rapid trigger", settings.rtSmart, + Array.from({ length: 16 }, (_, n) => ({ value: n, label: n === 0 ? "Off" : String(n) }))), + toggle("berserk", "Berserk mode", settings.tachyonMode, "Allows the smallest rapid-trigger distances."), + ] }, + { title: "Locks", controls: [ + toggle("lockwin", "Lock the Windows key", settings.lockWin), + toggle("lockalttab", "Lock Alt+Tab", settings.lockAltTab), + toggle("lockaltf4", "Lock Alt+F4", settings.lockAltF4), + toggle("mac", "Mac layout", settings.macMode, "Uses the Mac layer; turning it on also releases the Windows key lock."), + ] }, + { title: "Power", controls: [ + toggle("sleep", "Sleep when idle", settings.sleepEnabled), + choice("sleeptime", "Sleep after", settings.sleepTime, + [...sleeps].sort((a, b) => a - b).map((steps) => ({ value: steps, label: steps % 2 === 0 ? `${steps / 2} min` : `${steps * 30} s` }))), + ] }, + ]; +} + +/** Writes one setting; the driver reads it back before this returns. */ +export async function writeMchoseKeyboard(client: any, action: string, value: unknown): Promise<"rebooted" | void> { + const id = action.slice(`control:${PREFIX}`.length); + const { activeProfile } = await client.readBase(); + if (id === "profile") { + if (!Number.isInteger(value)) throw new RangeError("Pick a profile."); + await client.setActiveProfile(value); + return; + } + if (id === "name") { + const name = typeof value === "string" ? value.trim() : ""; + if (name === "" || [...name].length > NAME_LENGTH) throw new RangeError(`Use a name of 1 to ${NAME_LENGTH} characters.`); + await client.setProfileName(activeProfile, name); + return; + } + if (id === "newprofile") { + const name = typeof value === "string" ? value.trim() : ""; + if (name === "" || [...name].length > NAME_LENGTH) throw new RangeError(`Use a name of 1 to ${NAME_LENGTH} characters.`); + await client.createProfile(activeProfile, name, false); + return; + } + if (id === "deleteprofile" || id === "resetprofile") { + if (value === -1) return; + if (!Number.isInteger(value)) throw new RangeError("Pick a profile."); + // Only other profiles: the one in use is never touched from here. + if (value === activeProfile) throw new RangeError("The active profile can't be removed or reset here."); + if (id === "deleteprofile") await client.deleteProfile(value); + else await client.factoryReset(value); + return id === "resetprofile" ? "rebooted" : undefined; + } + if (id === "saveprofile") { + await saveProfileFile(client, activeProfile, value); + return; + } + if (id === "loadprofile") { + await loadProfileFile(client, activeProfile, value); + return; + } + if (id === "calibrate") { + if (!Number.isInteger(value)) throw new RangeError("Pick what to do."); + if (value === -1) return; + await runCalibration(client, activeProfile, value as number); + return; + } + const pairId = /^pair\.(.+)$/.exec(id); + if (pairId) { + if (!Number.isInteger(value)) throw new RangeError("Pick how the pair behaves."); + await setPair(client, activeProfile, pairId[1], value as number); + return; + } + const macroId = /^macro(mode)?\.(\d+)$/.exec(id); + if (macroId) { + const index = Number(macroId[2]); + if (index < 0 || index >= 16) throw new RangeError("That macro does not exist."); + const macros: MchoseMacro[] = await client.readMacros(); + if (macroId[1]) { + if (!Number.isInteger(value) || (value as number) < 0 || (value as number) > 255) throw new RangeError("Pick how the macro plays."); + macros[index] = { ...macros[index], mode: value as number }; + } else { + macros[index] = { mode: macros[index].mode, steps: parseMacro(typeof value === "string" ? value : "") }; + } + await client.setMacros(macros); + return; + } + if (id === "polling") { + if (!Number.isInteger(value)) throw new RangeError("Pick a polling rate."); + await client.setPollingRate(activeProfile, value); + return; + } + const setting = SETTINGS[id]; + if (!setting) throw new Error("Unknown MCHOSE keyboard control."); + const valid = setting.type === "boolean" ? typeof value === "boolean" + : Number.isInteger(value) && (value as number) >= 0 && (value as number) <= (setting.max ?? 255); + if (!valid) throw new RangeError("That setting value is out of range."); + const current: MchoseSettings = await client.readSettings(activeProfile); + await client.setSettings(activeProfile, { ...current, [setting.field]: value }); +} + +export async function mchoseOp(client: any, op: string, args: any): Promise { + switch (op) { + case "lighting": + return readLights(client); + case "setLighting": + return setLights(client, args); + case "keys": + return readKeys(client, args?.layer); + case "setKey": + return setKey(client, args); + case "setActuation": + return setActuation(client, args); + // Every change is already on the keyboard. + case "save": + return true; + case "calibrationStatus": + return calibrationStatus(); + case "keyColours": + return readKeyColours(client); + case "setKeyColours": + return setKeyColours(client, args); + default: + throw new Error(`Unknown keyboard operation ${op}`); + } +} diff --git a/gpui/js/keyboards.ts b/gpui/js/keyboards.ts index ca121aba..237cb4c1 100644 --- a/gpui/js/keyboards.ts +++ b/gpui/js/keyboards.ts @@ -9,6 +9,7 @@ import { invoke } from "@tauri-apps/api/core"; import { VIA_USAGE, VIA_USAGE_PAGE } from "@openmouse/keyboard-protocol/via"; import { WUQUE_FEATURES, wuqueOp } from "./keyboard-wuque"; +import { isMchoseKeyboardControl, MCHOSE_FEATURES, mchoseOp, mchoseSections, writeMchoseKeyboard } from "./keyboard-mchose"; import { DEVICE_DRIVERS, type DeviceDriver } from "@openmouse/keyboard-protocol/drivers/registry"; import { SUPPORTED_HID_FILTERS } from "@openmouse/keyboard-protocol/drivers/vendors"; import { listHidInterfaces, TauriHidDevice, type HidInterfaceInfo } from "./native-hid/tauri-hid-device"; @@ -127,7 +128,7 @@ async function withKeyboard(info: KeyboardInterface, work: (client: any, bran ]); } finally { clearTimeout(timer); - await client.close().catch(() => undefined); + if (!client.keepOpen) await client.close().catch(() => undefined); } }); } @@ -171,7 +172,7 @@ export function describeKeyboard(key: string, brand: string, status: any) { status: { ...status, firmware: version ? [version] : status.firmware ?? [], - keyboardFeatures: brand === "Wuque Studio" ? WUQUE_FEATURES : null, + keyboardFeatures: brand === "Wuque Studio" ? WUQUE_FEATURES : brand === "MCHOSE" ? MCHOSE_FEATURES : null, }, controls: null, tabs: { @@ -189,7 +190,7 @@ export async function connectKeyboard(info: KeyboardInterface) { const rates = status.logitech ?? await polling(client); const sections = status.logitech?.onboardMemory ? await logitechKeyboardSections(client, info.key, status.logitech) - : []; + : brand === "MCHOSE" ? await mchoseSections(client) : []; const readout = describeKeyboard(info.key, brand, { ...status, pollingRateHz: rates.pollingRateHz, supportedPollingRates: rates.supportedPollingRates, // These controls are offered only after the hardware returns a profile. @@ -200,11 +201,12 @@ export async function connectKeyboard(info: KeyboardInterface) { }); } -/** Keys, actuation and lighting, where this app can change them. */ +/** Keys, actuation and lighting, where this app can change them (Wuque Studio; MCHOSE lighting). */ export async function keyboardOp(info: HidInterfaceInfo, op: string, args: any): Promise { return withKeyboard(info, async (client, brand) => { - if (brand !== "Wuque Studio") throw new Error("This app can't change that on this keyboard yet."); - return wuqueOp(client, op, args); + if (brand === "Wuque Studio") return wuqueOp(client, op, args); + if (brand === "MCHOSE") return mchoseOp(client, op, args); + throw new Error("This app can't change that on this keyboard yet."); }); } @@ -220,6 +222,15 @@ export async function writeKeyboard(info: KeyboardInterface, action: string, val return { tabs: { ...readout.tabs, advanced: [...sections, ...readout.tabs.advanced] } }; }); } + if (isMchoseKeyboardControl(action)) { + return withKeyboard(info, async (client, brand) => { + if (brand !== "MCHOSE") throw new Error("This control requires an MCHOSE keyboard."); + if (await writeMchoseKeyboard(client, action, value) === "rebooted") return -1; + const status = await client.readStatus(); + const readout = describeKeyboard(info.key, brand, status); + return { tabs: { ...readout.tabs, advanced: [...await mchoseSections(client), ...readout.tabs.advanced] } }; + }); + } if (action !== "pollingRate") throw new Error("This app can't change that on a keyboard yet."); return withKeyboard(info, async (client, brand) => { if (brand === "Logitech") { diff --git a/gpui/js/mock.ts b/gpui/js/mock.ts index 280eb3c0..34cd8724 100644 --- a/gpui/js/mock.ts +++ b/gpui/js/mock.ts @@ -23,15 +23,20 @@ export const mockCandidates = (wanted: string) => [ brands: ["Wuque Studio"], kind: "keyboard", }] : []), + ...(wanted.includes("mchose") ? [{ + info: { key: "mock:mchose", vendorId: 0x3837, productId: 0x3024, productString: "Ace 68 V2-III (mock)", manufacturerString: "MCHOSE", collections: [] }, + brands: ["MCHOSE"], + kind: "keyboard", + }] : []), ...(wanted.includes("x3") ? [{ info: { key: "mock:x3", vendorId: 0x046d, productId: 0xc0a9, productString: "PRO X 3 Superstrike (mock)", manufacturerString: "Logitech", collections: [] }, brands: ["Logitech"], }] : []), ]; -export const mockKeyboard = () => ({ - brand: "Wuque Studio", - name: "Mock keyboard", +export const mockKeyboard = (key = "mock:kb") => ({ + brand: key === "mock:mchose" ? "MCHOSE" : "Wuque Studio", + name: key === "mock:mchose" ? "Ace 68 V2 III" : "Mock keyboard", connectionType: "Wired", firmwareVersion: "1.0.0.0", serial: "KB-0001", @@ -41,8 +46,115 @@ export const mockKeyboard = () => ({ }); +/** The backlight of the fake MCHOSE keyboard; changes are kept for the session. */ +const mockEffect = (value: number, name: string, speed: boolean, colour: boolean, directions: [string, string] | null = null) => + ({ value, name, speed, direction: directions !== null, colour, directions }); +const mockMchoseLights = { + on: true, effect: 6, brightness: 100, speed: 2, speedMax: 4, direction: 0, rainbow: false, rgb: [255, 0, 255], + effects: [ + mockEffect(0, "Custom", false, false), + mockEffect(6, "Horiz Wave", true, true, ["Left to right", "Right to left"]), + mockEffect(7, "Vert Wave", true, true, ["Top to bottom", "Bottom to top"]), + mockEffect(8, "Center Spread", true, true, ["Outward", "Inward"]), + mockEffect(4, "Breath", true, true), + mockEffect(1, "RainbowCycle", true, false), + mockEffect(3, "Constant On", false, true), + ] as unknown[], +}; + +/** The keys of the fake MCHOSE keyboard and their colours. */ +const mockMchoseKeys = [ + { row: 0, col: 26, x: 0, y: 0, w: 1, label: "Esc", standard: 0x100029, standardLabel: "Esc", colour: [0, 0, 0] }, + { row: 0, col: 64, x: 1, y: 0, w: 1, label: "1", standard: 0x10001e, standardLabel: "1", colour: [255, 0, 86] }, + { row: 0, col: 22, x: 2, y: 0, w: 1, label: "2", standard: 0x10001f, standardLabel: "2", colour: [0, 0, 0] }, + { row: 1, col: 66, x: 0, y: 1, w: 1.5, label: "Tab", standard: 0x10002b, standardLabel: "Tab", colour: [0, 0, 0] }, + { row: 1, col: 4, x: 1.5, y: 1, w: 1, label: "Q", standard: 0x100014, standardLabel: "Q", colour: [0, 0, 0] }, + { row: 2, col: 63, x: 0, y: 2, w: 4, label: "Space", standard: 0x10002c, standardLabel: "Space", colour: [0, 0, 0] }, +]; + +/** Codes put on keys of the fake keyboard by layer, and the names of the codes it knows. */ +const mockMchoseCodes: Record> = {}; +const mockMchoseLabels: Record = { 0x100004: "A", 0x100005: "B", 0x100068: "F13", 0x700000: "Macro 1", 0xe10100: "Toggle Ctrl" }; +const mockMchoseLabel = (code: number, col: number) => + mockMchoseLabels[code] ?? mockMchoseKeys.find((k) => k.col === col && k.standard === code)?.standardLabel ?? "?"; +const mockMchoseSettings = new Map(); + +export function mockMchoseWrite(action: string, value: unknown): unknown { + mockMchoseSettings.set(action.replace(/^control:/, ""), value); + return value; +} +const mockMchoseActuation: Record> = Object.fromEntries( + mockMchoseKeys.map((k) => [k.col, { travel: 0.75, rtPress: 0.75, rtRelease: 0.75, deadPress: 0.15, deadRelease: 0.15, mode: 2 }]), +); + +/** Settings sections of the fake MCHOSE keyboard, the way the real adapter lists them. */ +export const mockMchoseSections = () => mockMchoseSectionList().map((section) => ({ + ...section, + controls: section.controls.map((control: any) => mockMchoseSettings.has(control.id) ? { ...control, current: mockMchoseSettings.get(control.id) } : control), +})); + +const mockMchoseSectionList = (): { title: string; controls: any[] }[] => [ + { title: "Profile", controls: [{ id: "mchose.kb.profile", label: "Active profile", kind: "choice", current: 0, + options: [{ value: 0, label: "Profile 1" }, { value: 1, label: "Profile 2" }, { value: 2, label: "Profile 3" }] }, + { id: "mchose.kb.name", label: "Profile name", kind: "text", current: "MAIN", description: "Up to 15 characters." }, + { id: "mchose.kb.deleteprofile", label: "Delete profile", kind: "choice", current: -1, + options: [{ value: -1, label: "Choose…" }, { value: 1, label: "Profile 2" }, { value: 2, label: "Profile 3" }] }, + { id: "mchose.kb.resetprofile", label: "Reset profile", kind: "choice", current: -1, + options: [{ value: -1, label: "Choose…" }, { value: 1, label: "Profile 2" }, { value: 2, label: "Profile 3" }] }] }, + { title: "Opposing keys", controls: [ + { id: "mchose.kb.pair.wasd-ad", label: "A / D", kind: "choice", current: -1, options: [{ value: -1, label: "Off" }, { value: 1, label: "SOCD: first key wins" }, { value: 10, label: "Rapid snap" }] }] }, + { title: "Calibration", controls: [ + { id: "mchose.kb.calibrate", label: "Calibrate keys", kind: "choice", current: -1, options: [{ value: -1, label: "Choose…" }, { value: 0, label: "Start" }] }] }, + { title: "Macros", controls: [ + { id: "mchose.kb.macro.0", label: "Macro 1", kind: "text", current: "", description: "Keys by name: +Ctrl presses, -Ctrl releases, A taps, a number waits that many ms." }, + { id: "mchose.kb.macromode.0", label: "Macro 1 plays", kind: "choice", current: 1, options: [{ value: 1, label: "Play once" }, { value: 0, label: "Repeat while held" }] }] }, + { title: "Performance", controls: [ + { id: "mchose.kb.polling", label: "Polling rate", kind: "choice", current: 8000, options: [1000, 2000, 4000, 8000].map((hz) => ({ value: hz, label: `${hz} Hz` })) }, + { id: "mchose.kb.debounce", label: "Debounce optimisation", kind: "toggle", current: true }, + ] }, + { title: "Locks", controls: [{ id: "mchose.kb.lockwin", label: "Lock the Windows key", kind: "toggle", current: false }] }, +]; + /** A made-up two-row board for the keyboard pages. Nothing is remembered. */ -export const mockKeyboardOp = (op: string, args: any): unknown => { +export const mockKeyboardOp = (op: string, args: any, device = "mock:kb"): unknown => { + if (device === "mock:mchose") { + if (op === "setLighting") Object.assign(mockMchoseLights, args); + if (op === "keys") { + const fields = [ + { id: "travel", name: "Actuation point", hint: "How far a key goes down before it registers.", min: 0.1, max: 3.4 }, + { id: "rtPress", name: "Rapid trigger: press", hint: "How far back down it registers again.", min: 0.02, max: 3.4 }, + { id: "rtRelease", name: "Rapid trigger: release", hint: "How far up it lets go.", min: 0.02, max: 3.4 }, + { id: "deadPress", name: "Top dead zone", hint: "Travel at the top that does not count.", min: 0, max: 0.5 }, + { id: "deadRelease", name: "Bottom dead zone", hint: "Travel at the bottom that does not count.", min: 0, max: 0.5 }, + ]; + const layer = Number.isInteger(args.layer) ? args.layer : 0; + return { + layer, layers: 4, layerNames: ["Windows", "Windows Fn", "Mac", "Mac Fn"], width: 5, stored: true, fields, + categories: [{ name: "Keys", keys: [{ code: 0x100004, label: "A" }, { code: 0x100005, label: "B" }, { code: 0x100068, label: "F13" }] }, + { name: "Macros", keys: [{ code: 0x700000, label: "Macro 1" }] }, { name: "Toggle", keys: [{ code: 0xe10100, label: "Toggle Ctrl" }] }], + modes: [{ value: 0, label: "Off" }, { value: 1, label: "Quick trigger" }, { value: 2, label: "Quick + rapid trigger" }], + keys: mockMchoseKeys.map((k) => ({ ...k, code: mockMchoseCodes[layer]?.[k.col] ?? k.standard, label: mockMchoseLabel(mockMchoseCodes[layer]?.[k.col] ?? k.standard, k.col), actuation: mockMchoseActuation[k.col] })), + }; + } + if (op === "setKey") { + (mockMchoseCodes[args.layer] ??= {})[args.col] = args.code; + return { row: args.row, col: args.col, code: args.code, label: mockMchoseLabel(args.code, args.col) }; + } + if (op === "setActuation") { + return args.keys.map(([row, col]: number[]) => { + mockMchoseActuation[col] = { ...mockMchoseActuation[col], ...args.patch }; + return { row, col, actuation: mockMchoseActuation[col] }; + }); + } + if (op === "keyColours") return { layer: 0, layers: 1, width: 5, categories: [], keys: mockMchoseKeys }; + if (op === "setKeyColours") { + for (const key of mockMchoseKeys) if (args.keys.includes(key.col)) key.colour = args.rgb; + mockMchoseLights.effect = 0; + mockMchoseLights.on = true; + return { keys: args.keys.map((col: number) => ({ col, colour: args.rgb })), lights: mockMchoseLights }; + } + return mockMchoseLights; + } const actuation = { travel: 1.5, rtPress: 0.3, rtRelease: 0.3, deadPress: 0.2, deadRelease: 0.2 }; const key = (row: number, col: number, x: number, w: number, code: number, label: string) => ({ row, col, x, y: row, w, code, label, standard: code, standardLabel: label, actuation }); diff --git a/gpui/js/native-hid/device-images.ts b/gpui/js/native-hid/device-images.ts index d46142a8..aaed7cdc 100644 --- a/gpui/js/native-hid/device-images.ts +++ b/gpui/js/native-hid/device-images.ts @@ -87,6 +87,8 @@ const DEVICE_IMAGES: ReadonlyMap = new Map([ ["3434:0440", "keychron-nape-pro.png"], ["3434:d026", "keychron-nape-pro.png"], ["3434:d029", "keychron-nape-pro.png"], + // MCHOSE Ace 68 V2 III. + ["3837:3024", "mchose-ace68-v2.png"], // Teevolution Terra Pro wired / receiver Compx transports. ["3554:f520", "teevolution-terra-pro.png"], ["3554:f522", "teevolution-terra-pro.png"], @@ -162,6 +164,7 @@ const LOCAL_OVERRIDES: Readonly> = { "attackshark-x11.png": "/devices/attackshark-x11.png", "keychron-nape-pro.png": "/devices/keychron-nape-pro.png", "logitech-mx-master-4.png": "/devices/logitech-mx-master-4.png", + "mchose-ace68-v2.png": "/devices/mchose-ace68-v2.png", "pulsar-pro-dongle.png": "/devices/pulsar-pro-dongle.png", }; diff --git a/gpui/src/app.rs b/gpui/src/app.rs index 841a5aca..f7823545 100644 --- a/gpui/src/app.rs +++ b/gpui/src/app.rs @@ -946,6 +946,8 @@ impl Render for AppView { self.ensure_device_name_editor(window, cx); self.ensure_curve_editor(window, cx); self.ensure_receiver_panel(window, cx); + self.ensure_keyboard_colour(window, cx); + self.ensure_key_paint_picker(window, cx); self.ensure_travel(window, cx); // Kit's Root paints the translucent semantic background once. // Keep the app shell clear so overlapping layers do not compound alpha. diff --git a/gpui/src/app/device_io.rs b/gpui/src/app/device_io.rs index 45de2040..c377d1d6 100644 --- a/gpui/src/app/device_io.rs +++ b/gpui/src/app/device_io.rs @@ -438,7 +438,8 @@ impl AppView { Ok(Ok(applied)) => { // Keyboard profile edits return verified tabs with canonical values. // The typed expression may differ from the value stored by the device. - let confirmed_tabs = id.starts_with("logi.keyboard."); + let confirmed_tabs = id.starts_with("logi.keyboard.") + || (id.starts_with("mchose.kb.") && applied.get("tabs").is_some()); if !confirmed_tabs { expected.push(Expected { action: format!("control:{id}"), value: value.clone() }); } @@ -451,6 +452,17 @@ impl AppView { r.tabs = tabs; } } + if id == "mchose.kb.calibrate" { + v.follow_calibration(key.clone(), cx); + } + if matches!(id.as_str(), "mchose.kb.profile" | "mchose.kb.newprofile" | "mchose.kb.loadprofile") + && v.devices.open.as_deref() == Some(key.as_str()) + { + v.keyboard.forget_device_data(); + if matches!(v.devices.tab, DeviceTab::Actuation | DeviceTab::Keys | DeviceTab::Lighting) { + v.load_keyboard_tab(v.devices.tab, cx); + } + } // A Logitech button: reflect it in the stored profile we hold. if let Some(n) = id.strip_prefix("logi.button.primary.").and_then(|n| n.parse::().ok()) { if let Some(running) = v @@ -487,6 +499,53 @@ impl AppView { .detach(); } + /// While a keyboard calibration runs, refreshes its progress line twice a second. + fn follow_calibration(&mut self, key: String, cx: &mut Context) { + let service = self.hid_service(); + cx.spawn(async move |view, cx| { + let mut failures = 0; + loop { + cx.background_executor().timer(std::time::Duration::from_millis(500)).await; + let present = view + .update(cx, |v: &mut Self, _| { + v.devices.tiles.iter().any(|t| t.key == key && matches!(t.status, TileStatus::Connected(_))) + }) + .unwrap_or(false); + if !present { + break; + } + let control = service.keyboard(&key, "calibrationStatus", serde_json::json!({})).await; + let Some(control) = control.ok().and_then(Result::ok).and_then(|c| serde_json::from_value::(c).ok()) else { + failures += 1; + if failures >= 20 { + break; + } + continue; + }; + failures = 0; + let running = control.options.first().is_some_and(|o| o.label.starts_with("Running")); + let alive = view + .update(cx, |v: &mut Self, cx| { + let Some(tile) = v.devices.tiles.iter_mut().find(|t| t.key == key) else { return false }; + let TileStatus::Connected(r) = &mut tile.status else { return false }; + let Some(slot) = r.tabs.controls_mut().find(|c| c.id == control.id) else { return false }; + // Only while the page still shows a running calibration (a later reload ends this). + if !slot.options.first().is_some_and(|o| o.label.starts_with("Running")) && running { + return false; + } + *slot = control.clone(); + cx.notify(); + true + }) + .unwrap_or(false); + if !alive || !running { + break; + } + } + }) + .detach(); + } + /// The lighting as it would be written now: staged fields over the device's. pub(super) fn effective_lighting(&self, spec: &crate::hid::LightingSpec) -> serde_json::Value { let e = &self.devices.staged.light; diff --git a/gpui/src/app/device_page.rs b/gpui/src/app/device_page.rs index d2c10d11..7b27058c 100644 --- a/gpui/src/app/device_page.rs +++ b/gpui/src/app/device_page.rs @@ -419,7 +419,9 @@ impl AppView { cx, move |this, cx| { this.devices.tab = tab; - if features.actuation && matches!(tab, DeviceTab::Actuation | DeviceTab::Keys | DeviceTab::Lighting) { + if (features.actuation || features.remap || features.lighting) + && matches!(tab, DeviceTab::Actuation | DeviceTab::Keys | DeviceTab::Lighting) + { // Selections mean different things on each of these. this.keyboard.clear_selection(); this.load_keyboard_tab(tab, cx); diff --git a/gpui/src/app/keyboard_panel.rs b/gpui/src/app/keyboard_panel.rs index fc1064b6..fd097acc 100644 --- a/gpui/src/app/keyboard_panel.rs +++ b/gpui/src/app/keyboard_panel.rs @@ -6,8 +6,12 @@ use super::*; use super::widgets::panel; use serde::Deserialize; use serde_json::{json, Value}; +use gpui_kit::component::color_picker::{ColorPicker, ColorPickerEvent, ColorPickerState}; use std::collections::{BTreeMap, BTreeSet}; +/// The colour painted on keys until another is picked. +const WHITE: [u8; 3] = [255, 255, 255]; + /// Height of one row of keys. const KEY_H: f32 = 44.0; @@ -37,6 +41,8 @@ pub(super) struct Key { standard_label: String, /// Millimetres, by the names in `FIELDS`. actuation: Option>, + /// The key's own backlight colour, where the keyboard has one. + colour: Option<[u8; 3]>, } #[derive(Debug, Clone, Deserialize)] @@ -51,6 +57,23 @@ pub(super) struct Category { keys: Vec, } +/// One way a key can trigger (off, quick trigger, ...), where a board has them. +#[derive(Debug, Clone, Deserialize)] +pub(super) struct TriggerMode { + value: u32, + label: String, +} + +/// One actuation setting a board offers, with its range in mm. +#[derive(Debug, Clone, Deserialize)] +pub(super) struct Field { + id: String, + name: String, + hint: String, + min: f64, + max: f64, +} + #[derive(Debug, Clone, Deserialize)] pub(super) struct Board { layer: u8, @@ -58,9 +81,49 @@ pub(super) struct Board { width: f32, keys: Vec, categories: Vec, + /// The settings and ranges this board has; the Wuque Studio ones when empty. + #[serde(default)] + fields: Vec, + /// What the layers are called; "Layer N" where a board does not say. + #[serde(default, rename = "layerNames")] + layer_names: Vec, + /// How a key can trigger; a key's own is the "mode" among its settings. + #[serde(default)] + modes: Vec, + /// Changes are in the keyboard as soon as they are made, so nothing needs saving. + #[serde(default)] + stored: bool, +} + +impl Board { + fn fields(&self) -> Vec { + if !self.fields.is_empty() { + return self.fields.clone(); + } + FIELDS + .iter() + .map(|&(id, name, hint, min, max)| Field { id: id.into(), name: name.into(), hint: hint.into(), min, max }) + .collect() + } } +/// One backlight effect a keyboard offers, with the settings it responds to. #[derive(Debug, Clone, Deserialize)] +pub(super) struct Effect { + value: u32, + name: String, + speed: bool, + colour: bool, + /// What the keyboard's two directions are called, when it has them. + #[serde(default)] + directions: Option<[String; 2]>, +} + +/// The backlight. Wuque Studio boards choose a colour from a palette and name +/// their effects by number; MCHOSE boards list their effects (`effects`) and +/// take any colour (`rgb`). +#[derive(Debug, Clone, Deserialize)] +#[serde(default)] pub(super) struct Lights { on: bool, effect: u32, @@ -68,6 +131,31 @@ pub(super) struct Lights { speed: u32, colour: u32, palette: Vec<[u8; 3]>, + effects: Vec, + #[serde(rename = "speedMax")] + speed_max: u32, + direction: u32, + /// Cycle through colours instead of using `rgb`. + rainbow: bool, + rgb: Option<[u8; 3]>, +} + +impl Default for Lights { + fn default() -> Self { + Lights { + on: true, + effect: 0, + brightness: 0, + speed: 0, + colour: 0, + palette: Vec::new(), + effects: Vec::new(), + speed_max: 100, + direction: 0, + rainbow: false, + rgb: None, + } + } } #[derive(Default)] @@ -77,13 +165,22 @@ pub(super) struct KeyboardPanel { /// Selected keys, by matrix row and column. selected: BTreeSet<(u8, u8)>, /// Actuation values chosen but not yet written. - draft: BTreeMap<&'static str, f64>, + draft: BTreeMap, /// The group of assignable keys on show. category: usize, busy: bool, error: Option, /// Counts openings, so a late answer for another page is dropped. round: u64, + /// The colour picker of a keyboard that takes any colour. + colour: Option<(Entity, Subscription)>, + /// Every key's own colour, for keyboards that colour keys one by one. + colours: Option, + /// The colour the next "paint" puts on keys (white until one is picked), + /// and the picker that chooses it. + paint: Option<[u8; 3]>, + paint_picker: Option<(Entity, Subscription)>, + pending_rgb: Option<[u8; 3]>, } impl KeyboardPanel { @@ -91,6 +188,14 @@ impl KeyboardPanel { *self = KeyboardPanel { round: self.round + 1, ..Default::default() }; } + pub(super) fn forget_device_data(&mut self) { + self.board = None; + self.lights = None; + self.colours = None; + self.colour = None; + self.pending_rgb = None; + } + pub(super) fn clear_selection(&mut self) { self.selected.clear(); self.draft.clear(); @@ -110,6 +215,18 @@ impl KeyboardPanel { } } +/// An 8-bit colour as the picker holds it. +fn rgb_hsla([r, g, b]: [u8; 3]) -> Hsla { + Hsla::from(Rgba { r: f32::from(r) / 255.0, g: f32::from(g) / 255.0, b: f32::from(b) / 255.0, a: 1.0 }) +} + +/// A picked colour in 8-bit channels. +fn hsla_rgb(colour: Hsla) -> [u8; 3] { + let rgb = Rgba::from(colour); + let part = |c: f32| (c.clamp(0.0, 1.0) * 255.0).round() as u8; + [part(rgb.r), part(rgb.g), part(rgb.b)] +} + /// A step from `from`, kept in range and on whole hundredths. fn nudged(from: f64, by: f64, min: f64, max: f64) -> f64 { (((from + by) * 100.0).round() / 100.0).clamp(min, max) @@ -149,6 +266,11 @@ impl AppView { if let Err(error) = result { v.keyboard.error = Some(error); } + if let Some(rgb) = v.keyboard.pending_rgb.take() { + if v.keyboard.lights.as_ref().and_then(|l| l.rgb) != Some(rgb) { + v.send_rgb(rgb, cx); + } + } cx.notify(); }); }) @@ -158,17 +280,71 @@ impl AppView { /// Reads what a tab shows, unless it is already here. pub(super) fn load_keyboard_tab(&mut self, tab: DeviceTab, cx: &mut Context) { if tab == DeviceTab::Lighting { - if self.keyboard.lights.is_none() { - self.keyboard_run("lighting", json!({}), cx, |v, value, _| { - v.keyboard.lights = Some(serde_json::from_value(value).map_err(|e| e.to_string())?); + match &self.keyboard.lights { + None => self.keyboard_run("lighting", json!({}), cx, |v, value, cx| { + let lights: Lights = serde_json::from_value(value).map_err(|e| e.to_string())?; + // A keyboard that lists its effects can also colour keys one by one. + let per_key = !lights.effects.is_empty(); + v.keyboard.lights = Some(lights); + if per_key { + v.load_key_colours(cx); + } Ok(()) - }); + }), + Some(lights) if !lights.effects.is_empty() && self.keyboard.colours.is_none() => self.load_key_colours(cx), + Some(_) => {} } } else if self.keyboard.board.is_none() { self.load_layer(0, cx); } } + fn load_key_colours(&mut self, cx: &mut Context) { + self.keyboard_run("keyColours", json!({}), cx, |v, value, _| { + v.keyboard.colours = Some(serde_json::from_value(value).map_err(|e| e.to_string())?); + Ok(()) + }); + } + + /// Puts the chosen colour on the selected keys (or on every key). + fn paint_keys(&mut self, all: bool, cx: &mut Context) { + let Some(board) = &self.keyboard.colours else { return }; + let slots: Vec = board + .keys + .iter() + .filter(|k| all || self.keyboard.selected.contains(&(k.row, k.col))) + .map(|k| k.col) + .collect(); + if slots.is_empty() { + return; + } + let args = json!({ "keys": slots, "rgb": self.keyboard.paint.unwrap_or(WHITE) }); + self.keyboard_run("setKeyColours", args, cx, |v, value, cx| { + #[derive(Deserialize)] + struct Painted { + col: u8, + colour: [u8; 3], + } + #[derive(Deserialize)] + struct Done { + keys: Vec, + lights: Lights, + } + let done: Done = serde_json::from_value(value).map_err(|e| e.to_string())?; + let count = done.keys.len(); + if let Some(board) = &mut v.keyboard.colours { + for painted in done.keys { + if let Some(key) = board.keys.iter_mut().find(|k| k.col == painted.col) { + key.colour = Some(painted.colour); + } + } + } + v.keyboard.lights = Some(done.lights); + v.show_toast(format!("Coloured {count} {}.", if count == 1 { "key" } else { "keys" }), false, cx); + Ok(()) + }); + } + fn load_layer(&mut self, layer: u8, cx: &mut Context) { self.keyboard_run("keys", json!({ "layer": layer }), cx, |v, value, _| { v.keyboard.board = Some(serde_json::from_value(value).map_err(|e| e.to_string())?); @@ -217,12 +393,17 @@ impl AppView { }); } + fn send_rgb(&mut self, rgb: [u8; 3], cx: &mut Context) { + self.set_lights(|l| l.rgb = Some(rgb), cx); + } + fn set_lights(&mut self, change: impl FnOnce(&mut Lights), cx: &mut Context) { let Some(mut wanted) = self.keyboard.lights.clone() else { return }; change(&mut wanted); let args = json!({ "on": wanted.on, "effect": wanted.effect, "brightness": wanted.brightness, "speed": wanted.speed, "colour": wanted.colour, + "direction": wanted.direction, "rainbow": wanted.rainbow, "rgb": wanted.rgb, }); self.keyboard_run("setLighting", args, cx, |v, value, _| { v.keyboard.lights = Some(serde_json::from_value(value).map_err(|e| e.to_string())?); @@ -282,14 +463,24 @@ impl AppView { .rounded_md() .border_1() .border_color(if selected { accent } else { Hsla { a: 0.0, ..accent } }) - .bg(if selected { Hsla { a: 0.22, ..accent } } else { Hsla { a: 0.07, ..fg } }) + .when(selected && key.colour.is_some(), |face| face.border_2()) + .bg(match key.colour.filter(|c| *c != [0, 0, 0]) { + Some(c) => rgb_hsla(c), + None if selected => Hsla { a: 0.22, ..accent }, + None => Hsla { a: 0.07, ..fg }, + }) .cursor_pointer() - .when(!selected, |face| face.hover(move |face| face.bg(Hsla { a: 0.13, ..fg }))) + .when(!selected && key.colour.is_none(), |face| face.hover(move |face| face.bg(Hsla { a: 0.13, ..fg }))) .child( div() .text_xs() .font_weight(FontWeight::MEDIUM) - .text_color(if marked(key) { accent } else { fg }) + .text_color(match key.colour.filter(|c| *c != [0, 0, 0]) { + // Dark letters on a light key, light letters on a dark one. + Some([r, g, b]) => if u32::from(r) * 299 + u32::from(g) * 587 + u32::from(b) * 114 > 140_000 { gpui::black() } else { gpui::white() }, + None if marked(key) => accent, + None => fg, + }) .child(key.label.clone()), ) .children(caption(key).map(|text| div().text_size(px(9.)).text_color(muted).child(text))) @@ -348,16 +539,17 @@ impl AppView { fn render_actuation(&self, board: &Board, cx: &mut Context) -> Vec
{ let fg = cx.theme().foreground; let muted = cx.theme().muted_foreground; - let pick = |id: &'static str, label: &'static str, codes: Option<&'static [u32]>, cx: &mut Context| { + let pick = |id: &'static str, label: &'static str, names: Option<&'static [&'static str]>, cx: &mut Context| { Button::new(id).compact().ghost().label(label).on_click(cx.listener(move |this, _, _, cx| { - // `None` selects nothing; an empty list, every key. + // `None` selects nothing; an empty list, every key; otherwise the keys + // the board ships with those names. let Some(board) = &this.keyboard.board else { return }; - this.keyboard.selected = match codes { + this.keyboard.selected = match names { None => BTreeSet::new(), - Some(codes) => board + Some(names) => board .keys .iter() - .filter(|k| codes.is_empty() || codes.contains(&k.standard)) + .filter(|k| names.is_empty() || names.contains(&k.standard_label.as_str())) .map(|k| (k.row, k.col)) .collect(), }; @@ -368,8 +560,7 @@ impl AppView { let choose = h_flex() .gap_1() .child(pick("kb-all", "All", Some(&[]), cx)) - // HID codes of W, A, S and D. - .child(pick("kb-wasd", "WASD", Some(&[26, 4, 22, 7]), cx)) + .child(pick("kb-wasd", "WASD", Some(&["W", "A", "S", "D"]), cx)) .child(pick("kb-none", "Clear", None, cx)); let grid = self.key_grid( board, @@ -395,21 +586,55 @@ impl AppView { .child(div().text_xs().text_color(muted).child("Click keys to select them. Each shows its actuation point in mm.")); let count = self.keyboard.selected.len(); + // A board that keeps changes as they are made has nothing to save. + let save = |this: &Self, cx: &mut Context| (!board.stored).then(|| this.save_button("performance", cx)); if count == 0 { - return vec![keys, self.save_button("performance", cx)]; + return std::iter::once(keys).chain(save(self, cx)).collect(); } let mut editor = panel(cx).child(super::device_overview::card_title("Selected keys", cx)); - for (field, name, hint, min, max) in FIELDS { - let draft = self.keyboard.draft.get(field).copied(); - let shown = draft.or_else(|| self.keyboard.shared(field)); + if !board.modes.is_empty() { + let shown = self.keyboard.draft.get("mode").copied().or_else(|| self.keyboard.shared("mode")); + let mut chips = segmented(cx); + for mode in &board.modes { + let value = mode.value; + chips = chips.child(self.chip( + format!("kb-mode-{value}"), + mode.label.clone(), + shown.is_some_and(|m| m as u32 == value), + cx, + move |this, cx| { + this.keyboard.draft.insert("mode".to_string(), f64::from(value)); + cx.notify(); + }, + )); + } + editor = editor.child( + h_flex() + .justify_between() + .items_center() + .gap_4() + .child( + div() + .flex() + .flex_col() + .child(div().text_sm().text_color(fg).child("Trigger")) + .child(div().text_xs().text_color(muted).child("Off keeps one actuation point. The trigger modes move it with the key.")), + ) + .child(chips), + ); + } + for Field { id: field, name, hint, min, max } in board.fields() { + let draft = self.keyboard.draft.get(&field).copied(); + let shown = draft.or_else(|| self.keyboard.shared(&field)); // A mixed selection steps from the first key's value. let from = shown.unwrap_or_else(|| { let first = board.keys.iter().find(|k| self.keyboard.selected.contains(&(k.row, k.col))); - first.and_then(|k| k.actuation.as_ref()?.get(field).copied()).unwrap_or(min) + first.and_then(|k| k.actuation.as_ref()?.get(&field).copied()).unwrap_or(min) }); let step = |label: &'static str, by: f64, cx: &mut Context| { + let field = field.clone(); self.chip(format!("kb-{field}-{label}"), label.to_string(), false, cx, move |this, cx| { - this.keyboard.draft.insert(field, nudged(from, by, min, max)); + this.keyboard.draft.insert(field.clone(), nudged(from, by, min, max)); cx.notify(); }) }; @@ -462,7 +687,7 @@ impl AppView { .on_click(cx.listener(|this, _, _, cx| this.apply_actuation(cx))), ), ); - vec![keys, editor, self.save_button("performance", cx)] + [keys, editor].into_iter().chain(save(self, cx)).collect() } fn render_key_assignments(&self, board: &Board, cx: &mut Context) -> Vec
{ @@ -471,7 +696,7 @@ impl AppView { for layer in 0..board.layers { layers = layers.child(self.chip( format!("kb-layer-{layer}"), - format!("Layer {}", layer + 1), + board.layer_names.get(layer as usize).cloned().unwrap_or_else(|| format!("Layer {}", layer + 1)), board.layer == layer, cx, move |this, cx| this.load_layer(layer, cx), @@ -502,7 +727,8 @@ impl AppView { let picked = (self.keyboard.selected.len() == 1) .then(|| board.keys.iter().find(|k| self.keyboard.selected.contains(&(k.row, k.col)))) .flatten(); - let Some(key) = picked else { return vec![keys, self.save_button("layout", cx)] }; + let save = |this: &Self, cx: &mut Context| (!board.stored).then(|| this.save_button("layout", cx)); + let Some(key) = picked else { return std::iter::once(keys).chain(save(self, cx)).collect() }; let (row, col, standard, now) = (key.row, key.col, key.standard, key.code); let mut groups = segmented(cx); for (i, category) in board.categories.iter().enumerate() { @@ -547,38 +773,222 @@ impl AppView { ) .child(h_flex().child(groups)) .child(choices); - vec![keys, picker, self.save_button("layout", cx)] + [keys, picker].into_iter().chain(save(self, cx)).collect() } - fn render_key_lights(&self, lights: &Lights, cx: &mut Context) -> Div { + /// − value + for one of the backlight's numbers. + fn light_stepper(&self, id: &'static str, now: u32, step: u32, most: u32, set: fn(&mut Lights, u32), cx: &mut Context) -> Div { + let fg = cx.theme().foreground; + let nudge = |label: &'static str, to: u32, cx: &mut Context| { + self.chip(format!("kb-{id}-{label}"), label.to_string(), false, cx, move |this, cx| { + if to != now { + this.set_lights(|l| set(l, to), cx) + } + }) + }; + segmented(cx) + .items_center() + .child(nudge("−", now.saturating_sub(step), cx)) + .child(div().min_w(px(56.)).text_center().text_sm().text_color(fg).child(now.to_string())) + .child(nudge("+", (now + step).min(most), cx)) + } + + /// Makes the colour picker of a keyboard that takes any colour. It needs + /// the window, so this runs before drawing. + pub(super) fn ensure_keyboard_colour(&mut self, window: &mut Window, cx: &mut Context) { + let rgb = match &self.keyboard.lights { + Some(Lights { rgb: Some(rgb), .. }) if self.devices.tab == DeviceTab::Lighting => *rgb, + _ => { + self.keyboard.colour = None; + return; + } + }; + if self.keyboard.colour.is_some() { + return; + } + let start = rgb_hsla(rgb); + let state = cx.new(|cx| ColorPickerState::new(window, cx).default_value(start)); + let changed = cx.subscribe(&state, |this: &mut Self, _, event: &ColorPickerEvent, cx| { + let ColorPickerEvent::Change(Some(colour)) = event else { return }; + let rgb = hsla_rgb(*colour); + if this.keyboard.busy { + this.keyboard.pending_rgb = Some(rgb); + } else if this.keyboard.lights.as_ref().and_then(|l| l.rgb) != Some(rgb) { + this.set_lights(|l| l.rgb = Some(rgb), cx); + } + }); + self.keyboard.colour = Some((state, changed)); + } + + /// The picker for the colour put on single keys, made once per page. + pub(super) fn ensure_key_paint_picker(&mut self, window: &mut Window, cx: &mut Context) { + let wanted = self.devices.tab == DeviceTab::Lighting && self.keyboard.colours.is_some(); + if !wanted { + self.keyboard.paint_picker = None; + return; + } + if self.keyboard.paint_picker.is_some() { + return; + } + let state = cx.new(|cx| ColorPickerState::new(window, cx).default_value(rgb_hsla(self.keyboard.paint.unwrap_or(WHITE)))); + let changed = cx.subscribe(&state, |this: &mut Self, _, event: &ColorPickerEvent, cx| { + if let ColorPickerEvent::Change(Some(colour)) = event { + this.keyboard.paint = Some(hsla_rgb(*colour)); + cx.notify(); + } + }); + self.keyboard.paint_picker = Some((state, changed)); + } + + /// The backlight of a keyboard that lists its effects and takes any colour. + fn render_mchose_lights(&self, lights: &Lights, cx: &mut Context) -> Div { let fg = cx.theme().foreground; let row = |name: &'static str, control: Div| { h_flex().justify_between().items_center().gap_4().child(div().text_sm().text_color(fg).child(name)).child(control) }; + let current = lights.effects.iter().find(|e| e.value == lights.effect); let mut power = segmented(cx); for (label, on) in [("Off", false), ("On", true)] { power = power.child(self.chip(format!("kb-light-{label}"), label.to_string(), lights.on == on, cx, move |this, cx| { this.set_lights(|l| l.on = on, cx) })); } - // − value + for one of the numbers. - let stepper = |id: &'static str, now: u32, step: u32, most: u32, set: fn(&mut Lights, u32), cx: &mut Context| { - let nudge = |label: &'static str, to: u32, cx: &mut Context| { - self.chip(format!("kb-{id}-{label}"), label.to_string(), false, cx, move |this, cx| { - if to != now { - this.set_lights(|l| set(l, to), cx) - } - }) - }; - segmented(cx) - .items_center() - .child(nudge("−", now.saturating_sub(step), cx)) - .child(div().min_w(px(56.)).text_center().text_sm().text_color(fg).child(now.to_string())) - .child(nudge("+", (now + step).min(most), cx)) + let mut effects = segmented(cx); + for effect in &lights.effects { + let value = effect.value; + effects = effects.child(self.chip( + format!("kb-effect-{value}"), + effect.name.clone(), + lights.on && lights.effect == value, + cx, + // Picking an effect also switches the backlight on. + move |this, cx| this.set_lights(|l| (l.effect, l.on) = (value, true), cx), + )); + } + let mut card = panel(cx) + .child(super::device_overview::card_title("Lighting", cx)) + .child(row("Backlight", power)) + .child(super::device_page::divider(cx)) + .child(div().flex().flex_col().gap_2().child(div().text_sm().text_color(fg).child("Effect")).child(effects)) + .child(super::device_page::divider(cx)) + .child(row("Brightness", self.light_stepper("brightness", lights.brightness, 10, 100, |l, v| l.brightness = v, cx))); + if current.is_some_and(|e| e.speed) { + card = card + .child(super::device_page::divider(cx)) + .child(row("Speed", self.light_stepper("speed", lights.speed, 1, lights.speed_max, |l, v| l.speed = v, cx))); + } + if let Some(names) = current.and_then(|e| e.directions.as_ref()) { + let mut directions = segmented(cx); + for (value, name) in names.iter().enumerate() { + directions = directions.child(self.chip( + format!("kb-direction-{value}"), + name.clone(), + lights.direction == value as u32, + cx, + move |this, cx| this.set_lights(|l| l.direction = value as u32, cx), + )); + } + card = card.child(super::device_page::divider(cx)).child(row("Direction", directions)); + } + if current.is_some_and(|e| e.colour) { + let mut mode = segmented(cx); + for (label, rainbow) in [("One colour", false), ("Many colours", true)] { + mode = mode.child(self.chip( + format!("kb-colour-mode-{rainbow}"), + label.to_string(), + lights.rainbow == rainbow, + cx, + move |this, cx| this.set_lights(|l| l.rainbow = rainbow, cx), + )); + } + card = card.child(super::device_page::divider(cx)).child(row("Colour", mode)); + if let (false, Some((state, _))) = (lights.rainbow, &self.keyboard.colour) { + card = card.child(row("Pick the colour", div().child(ColorPicker::new(state)))); + } + } + let note = div() + .text_xs() + .text_color(cx.theme().muted_foreground) + .child("Changes work at once and stay on the keyboard."); + let mut page = div().flex().flex_col().gap_3().child(card).child(note); + if let Some(board) = &self.keyboard.colours { + page = page.child(self.render_key_paint(board, cx)); + } + page + } + + /// Every key drawn in its own colour, to pick keys and colour them. + fn render_key_paint(&self, board: &Board, cx: &mut Context) -> Div { + let muted = cx.theme().muted_foreground; + let chosen = self.keyboard.selected.len(); + let pick = |id: &'static str, label: &'static str, all: bool, cx: &mut Context| { + Button::new(id).compact().ghost().label(label).on_click(cx.listener(move |this, _, _, cx| { + let Some(board) = &this.keyboard.colours else { return }; + this.keyboard.selected = if all { board.keys.iter().map(|k| (k.row, k.col)).collect() } else { BTreeSet::new() }; + cx.notify(); + })) }; - let effect = stepper("effect", lights.effect, 1, 255, |l, v| l.effect = v, cx); - let brightness = stepper("brightness", lights.brightness, 10, 100, |l, v| l.brightness = v, cx); - let speed = stepper("speed", lights.speed, 10, 100, |l, v| l.speed = v, cx); + let grid = self.key_grid( + board, + |_| None, + |_| false, + cx, + |this, row, col, cx| { + if !this.keyboard.selected.remove(&(row, col)) { + this.keyboard.selected.insert((row, col)); + } + cx.notify(); + }, + ); + let mut paint = h_flex().gap_3().items_center().flex_wrap(); + if let Some((state, _)) = &self.keyboard.paint_picker { + paint = paint.child(ColorPicker::new(state)); + } + paint = paint + .child( + Button::new("kb-paint-selected") + .compact() + .label(format!("Colour {chosen} selected")) + .disabled(chosen == 0 || self.keyboard.busy) + .on_click(cx.listener(|this, _, _, cx| this.paint_keys(false, cx))), + ) + .child( + Button::new("kb-paint-all") + .compact() + .label("Colour every key") + .disabled(self.keyboard.busy) + .on_click(cx.listener(|this, _, _, cx| this.paint_keys(true, cx))), + ); + panel(cx) + .child(super::device_overview::card_title("Per-key colours", cx)) + .child( + div() + .text_xs() + .text_color(muted) + .child("Pick keys, choose a colour and colour them. The keyboard shows these with the Custom effect, which is switched on for you."), + ) + .child(h_flex().gap_1().child(pick("kb-colour-all", "All", true, cx)).child(pick("kb-colour-none", "Clear", false, cx))) + .child(grid) + .child(paint) + } + + fn render_key_lights(&self, lights: &Lights, cx: &mut Context) -> Div { + if !lights.effects.is_empty() { + return self.render_mchose_lights(lights, cx); + } + let fg = cx.theme().foreground; + let row = |name: &'static str, control: Div| { + h_flex().justify_between().items_center().gap_4().child(div().text_sm().text_color(fg).child(name)).child(control) + }; + let mut power = segmented(cx); + for (label, on) in [("Off", false), ("On", true)] { + power = power.child(self.chip(format!("kb-light-{label}"), label.to_string(), lights.on == on, cx, move |this, cx| { + this.set_lights(|l| l.on = on, cx) + })); + } + let effect = self.light_stepper("effect", lights.effect, 1, 255, |l, v| l.effect = v, cx); + let brightness = self.light_stepper("brightness", lights.brightness, 10, 100, |l, v| l.brightness = v, cx); + let speed = self.light_stepper("speed", lights.speed, 10, 100, |l, v| l.speed = v, cx); let mut colours = h_flex().gap_2(); for (i, [r, g, b]) in lights.palette.iter().copied().enumerate() { let chosen = lights.colour == i as u32; @@ -611,7 +1021,7 @@ impl AppView { #[cfg(test)] mod tests { - use super::{nudged, Board, Key, KeyboardPanel}; + use super::{hsla_rgb, nudged, rgb_hsla, Board, Key, KeyboardPanel, Lights}; use std::collections::{BTreeMap, BTreeSet}; #[test] @@ -624,10 +1034,57 @@ mod tests { #[test] fn a_selection_shows_a_value_only_when_it_agrees() { let key = |col: u8, travel: f64| Key { col, actuation: Some(BTreeMap::from([("travel".to_string(), travel)])), ..Default::default() }; - let board = Board { layer: 0, layers: 4, width: 15.0, keys: vec![key(0, 1.5), key(1, 1.5), key(2, 0.4)], categories: Vec::new() }; + let board = Board { layer: 0, layers: 4, width: 15.0, keys: vec![key(0, 1.5), key(1, 1.5), key(2, 0.4)], categories: Vec::new(), fields: Vec::new(), modes: Vec::new(), layer_names: Vec::new(), stored: false }; let mut panel = KeyboardPanel { board: Some(board), selected: BTreeSet::from([(0, 0), (0, 1)]), ..Default::default() }; assert_eq!(panel.shared("travel"), Some(1.5)); panel.selected.insert((0, 2)); assert_eq!(panel.shared("travel"), None); } + + #[test] + fn a_wuque_backlight_still_reads_without_the_mchose_fields() { + let lights: Lights = serde_json::from_value(serde_json::json!({ + "on": true, "effect": 3, "brightness": 80, "speed": 40, "colour": 2, "palette": [[255, 0, 0], [0, 255, 0], [0, 0, 255]], + })) + .unwrap(); + assert!(lights.effects.is_empty() && lights.rgb.is_none()); + assert_eq!((lights.effect, lights.colour, lights.palette.len()), (3, 2, 3)); + } + + #[test] + fn an_mchose_backlight_reads_its_effects_and_colour() { + let lights: Lights = serde_json::from_value(serde_json::json!({ + "on": false, "effect": 6, "brightness": 100, "speed": 2, "speedMax": 4, "direction": 1, "rainbow": false, + "rgb": [255, 0, 128], + "effects": [ + { "value": 6, "name": "Horiz Wave", "speed": true, "direction": true, "colour": true, "directions": ["Left to right", "Right to left"] }, + { "value": 3, "name": "Constant On", "speed": false, "direction": false, "colour": true, "directions": null }, + ], + })) + .unwrap(); + assert_eq!((lights.on, lights.speed_max, lights.rgb), (false, 4, Some([255, 0, 128]))); + assert_eq!(lights.effects[0].directions.as_ref().map(|d| d[1].as_str()), Some("Right to left")); + assert!(lights.effects[1].directions.is_none()); + } + + #[test] + fn colours_survive_the_trip_through_the_picker() { + for rgb in [[0, 0, 0], [255, 255, 255], [255, 0, 255], [1, 2, 3], [128, 64, 200]] { + assert_eq!(hsla_rgb(rgb_hsla(rgb)), rgb); + } + } + + #[test] + fn keys_carry_their_own_colour() { + let board: Board = serde_json::from_value(serde_json::json!({ + "layer": 0, "layers": 1, "width": 17.7, "categories": [], + "keys": [ + { "row": 0, "col": 26, "x": 0.3, "y": 0, "w": 1, "label": "Esc", "colour": [0, 255, 0] }, + { "row": 0, "col": 64, "x": 1.4, "y": 0, "w": 1, "label": "1" }, + ], + })) + .unwrap(); + assert_eq!(board.keys[0].colour, Some([0, 255, 0])); + assert_eq!(board.keys[1].colour, None, "a Wuque key has none"); + } } diff --git a/gpui/src/hid.rs b/gpui/src/hid.rs index c254a740..d839f472 100644 --- a/gpui/src/hid.rs +++ b/gpui/src/hid.rs @@ -255,6 +255,7 @@ fn bundled_device_art(filename: &str) -> Option<&'static [u8]> { "attackshark-x11.png" => Some(include_bytes!("../../public/devices/attackshark-x11.png")), "keychron-nape-pro.png" => Some(include_bytes!("../../public/devices/keychron-nape-pro.png")), "logitech-mx-master-4.png" => Some(include_bytes!("../../public/devices/logitech-mx-master-4.png")), + "mchose-ace68-v2.png" => Some(include_bytes!("../../public/devices/mchose-ace68-v2.png")), "pulsar-pro-dongle.png" => Some(include_bytes!("../../public/devices/pulsar-pro-dongle.png")), _ => None, } @@ -873,6 +874,11 @@ fn install_host<'js>( } })?, )?; + // Saved keyboard profiles: small text files in one folder of the app's own settings. + host.set( + "profileFiles", + Function::new(ctx.clone(), |action: String, name: String, text: String| -> String { profile_files(&action, &name, &text) })?, + )?; host.set( "sleep", Function::new( @@ -937,6 +943,64 @@ fn install_host<'js>( ctx.globals().set("__host", host) } +/// Folder holding saved keyboard profiles. +fn profile_dir() -> Option { + dirs::config_dir().map(|dir| dir.join("openmouse").join("keyboard-profiles")) +} + +/// A saved profile's file name: letters, digits, spaces, dashes and underscores only. +fn profile_file_name_ok(name: &str) -> bool { + !name.is_empty() + && name.chars().count() <= 40 + && name.chars().all(|c| c.is_alphanumeric() || c == ' ' || c == '-' || c == '_') + && !name.starts_with(' ') +} + +/// `list`, `save` and `load` for saved keyboard profiles. Answers JSON: `{"ok": ...}` or `{"error": "..."}`. +fn profile_files(action: &str, name: &str, text: &str) -> String { + let fail = |message: &str| serde_json::json!({ "error": message }).to_string(); + let Some(dir) = profile_dir() else { return fail("No settings folder on this computer.") }; + match action { + "list" => { + let mut names: Vec = std::fs::read_dir(&dir) + .map(|entries| { + entries + .flatten() + .filter_map(|entry| entry.file_name().to_str()?.strip_suffix(".json").map(str::to_string)) + .filter(|name| profile_file_name_ok(name)) + .collect() + }) + .unwrap_or_default(); + names.sort(); + serde_json::json!({ "ok": names }).to_string() + } + "save" | "load" if !profile_file_name_ok(name) => fail("Use letters, digits, spaces, - and _ in the name (up to 40)."), + "save" => { + if text.len() > 1_000_000 { + return fail("That profile is too large."); + } + let temp = dir.join(format!("{name}.json.tmp")); + let saved = std::fs::create_dir_all(&dir) + .and_then(|_| std::fs::write(&temp, text)) + .and_then(|_| std::fs::rename(&temp, dir.join(format!("{name}.json")))); + if let Err(error) = saved { + let _ = std::fs::remove_file(&temp); + return fail(&format!("Could not save the profile: {error}")); + } + serde_json::json!({ "ok": true }).to_string() + } + "load" => match std::fs::File::open(dir.join(format!("{name}.json"))).and_then(|file| { + let mut text = String::new(); + std::io::Read::read_to_string(&mut std::io::Read::take(file, 1_000_001), &mut text).map(|_| text) + }) { + Ok(text) if text.len() <= 1_000_000 => serde_json::json!({ "ok": text }).to_string(), + Ok(_) => fail("That profile file is too large."), + Err(error) => fail(&format!("Could not read the profile: {error}")), + }, + _ => fail("Unknown profile file action."), + } +} + fn driver_storage_path() -> Option { dirs::config_dir().map(|dir| dir.join("openmouse").join("driver-storage.json")) } diff --git a/gpui/src/write_safety.rs b/gpui/src/write_safety.rs index c8723cde..6913ee73 100644 --- a/gpui/src/write_safety.rs +++ b/gpui/src/write_safety.rs @@ -64,6 +64,34 @@ pub fn warning(id: &str, label: &str, current: &Value, value: &Value) -> Option< proceed: "Reset", }); } + if id == "mchose.kb.resetprofile" { + return (value.as_i64() != Some(-1)).then_some(Warning { + title: "Reset this profile?", + detail: "Its lighting, actuation and settings go back to the factory ones. The keyboard restarts. This can't be undone.", + proceed: "Reset", + }); + } + if id == "mchose.kb.calibrate" { + return matches!(value.as_i64(), Some(0) | Some(2)).then_some(Warning { + title: "Calibrate the keys?", + detail: "The keyboard forgets its key calibration and relearns it as you press every key twice.", + proceed: "Start", + }); + } + if id == "mchose.kb.loadprofile" { + return (value.as_str().is_some_and(|name| !name.is_empty())).then_some(Warning { + title: "Load this saved profile?", + detail: "The active profile's settings, lighting, keys and actuation are replaced. This can't be undone.", + proceed: "Load", + }); + } + if id == "mchose.kb.deleteprofile" { + return (value.as_i64() != Some(-1)).then_some(Warning { + title: "Delete this profile?", + detail: "It is removed from the keyboard. This can't be undone.", + proceed: "Delete", + }); + } if id.to_ascii_lowercase().contains("reset") { return Some(Warning { title: "Reset this device?", @@ -150,6 +178,13 @@ mod tests { #[test] fn risky_changes_ask_first_and_ordinary_ones_do_not() { let ask = |id, label, current: Value, value: Value| warning(id, label, ¤t, &value).is_some(); + assert!(ask("mchose.kb.deleteprofile", "Delete profile", json!(-1), json!(1))); + assert!(!ask("mchose.kb.deleteprofile", "Delete profile", json!(-1), json!(-1))); + assert!(ask("mchose.kb.resetprofile", "Reset profile", json!(-1), json!(2))); + assert!(ask("mchose.kb.calibrate", "Calibrate keys", json!(-1), json!(0))); + assert!(!ask("mchose.kb.calibrate", "Calibrate keys", json!(-1), json!(1))); + assert!(ask("mchose.kb.loadprofile", "Load saved profile", json!(""), json!("Racing"))); + assert!(!ask("mchose.kb.loadprofile", "Load saved profile", json!(""), json!(""))); assert!(ask("omni.pair", "Pairing", Value::Null, json!(1))); assert!(!ask("omni.pair", "Pairing", Value::Null, json!(0))); assert!(ask("perf.primaryButton", "Primary button", json!("Left"), json!("Right"))); diff --git a/gpui/tests/keyboard.rs b/gpui/tests/keyboard.rs index 69e6eb3c..afdb0006 100644 --- a/gpui/tests/keyboard.rs +++ b/gpui/tests/keyboard.rs @@ -3,9 +3,15 @@ use futures::executor::block_on; use openmouse_gpui::hid::HidService; use serde_json::json; +use std::sync::Mutex; + +/// The mock devices are chosen by an environment variable, which every test +/// here sets for itself, so they take turns. +static MOCK_ENV: Mutex<()> = Mutex::new(()); #[test] fn a_keyboard_is_listed_read_and_changed() { + let _turn = MOCK_ENV.lock().unwrap_or_else(|e| e.into_inner()); // The trailing "!" hides real devices. std::env::set_var("OPENMOUSE_MOCK", "kb!"); let service = HidService::start(); @@ -33,3 +39,68 @@ fn a_keyboard_is_listed_read_and_changed() { let applied = block_on(service.write("mock:kb", &device.brand, "pollingRate", json!(8000))).unwrap().unwrap(); assert_eq!(applied, json!(8000)); } + +#[test] +fn an_mchose_keyboard_offers_lighting_actuation_settings_and_keys() { + let _turn = MOCK_ENV.lock().unwrap_or_else(|e| e.into_inner()); + std::env::set_var("OPENMOUSE_MOCK", "mchose!"); + let service = HidService::start(); + let listed = block_on(service.list_candidates()).unwrap().unwrap(); + assert_eq!(listed.len(), 1, "only the made-up keyboard"); + assert_eq!(listed[0].brands, ["MCHOSE"]); + + let device = block_on(service.connect("mock:mchose")).unwrap().unwrap(); + assert_eq!(device.brand, "MCHOSE"); + let features = &device.status["keyboardFeatures"]; + assert_eq!(features["lighting"], json!(true)); + assert_eq!(features["actuation"], json!(true)); + assert_eq!(features["remap"], json!(true)); + + // The effects it lists and a change to one of them, kept for the next read. + let ask = |op: &str, args| block_on(service.keyboard("mock:mchose", op, args)).unwrap().unwrap(); + let lights = ask("lighting", json!({})); + assert!(lights["effects"].as_array().unwrap().iter().any(|e| e["name"] == json!("Horiz Wave"))); + let wanted = json!({ "on": true, "effect": 7, "brightness": 60, "speed": 3, "direction": 1, "rainbow": true, "rgb": [1, 2, 3] }); + let done = ask("setLighting", wanted); + assert_eq!((&done["effect"], &done["brightness"], &done["rgb"]), (&json!(7), &json!(60), &json!([1, 2, 3]))); + assert_eq!(ask("lighting", json!({}))["direction"], json!(1)); + + // Colouring keys one by one: the keys come with their colours, and painting + // returns the new colours and the effect that shows them. + let board = ask("keyColours", json!({})); + assert_eq!(board["keys"].as_array().unwrap().len(), 6); + let painted = ask("setKeyColours", json!({ "keys": [26, 4], "rgb": [0, 255, 0] })); + assert_eq!(painted["keys"], json!([{ "col": 26, "colour": [0, 255, 0] }, { "col": 4, "colour": [0, 255, 0] }])); + assert_eq!(painted["lights"]["effect"], json!(0), "the Custom effect shows them"); + let board = ask("keyColours", json!({})); + let esc = board["keys"].as_array().unwrap().iter().find(|k| k["label"] == json!("Esc")).unwrap(); + assert_eq!(esc["colour"], json!([0, 255, 0])); + + // Actuation: the board's own fields and ranges, and a change that is kept. + let keys = ask("keys", json!({ "layer": 0 })); + assert_eq!(keys["stored"], json!(true), "nothing to save"); + assert_eq!(keys["fields"][0]["max"], json!(3.4)); + assert_eq!(keys["modes"].as_array().unwrap().len(), 3, "off, quick trigger, quick and rapid"); + let done = ask("setActuation", json!({ "keys": [[0, 26]], "patch": { "mode": 1 } })); + assert_eq!(done[0]["actuation"]["mode"], json!(1)); + let done = ask("setActuation", json!({ "keys": [[0, 26]], "patch": { "travel": 1.2 } })); + assert_eq!(done[0]["actuation"]["travel"], json!(1.2)); + let keys = ask("keys", json!({ "layer": 0 })); + let esc = keys["keys"].as_array().unwrap().iter().find(|k| k["label"] == json!("Esc")).unwrap(); + assert_eq!(esc["actuation"]["travel"], json!(1.2)); + + // Settings come as controls on the Advanced tab. + let advanced: Vec<_> = device.tabs.expect("tabs").advanced.iter().flat_map(|s| &s.controls).map(|c| c.id.clone()).collect(); + assert!(advanced.contains(&"mchose.kb.macro.0".to_string()) && advanced.contains(&"mchose.kb.pair.wasd-ad".to_string())); + assert!(advanced.contains(&"mchose.kb.deleteprofile".to_string()) && advanced.contains(&"mchose.kb.resetprofile".to_string())); + assert!(advanced.contains(&"mchose.kb.polling".to_string()) && advanced.contains(&"mchose.kb.lockwin".to_string())); + + // Key assignments: four named layers, and a key set on one layer only. + let layer1 = ask("keys", json!({ "layer": 1 })); + assert_eq!(layer1["layerNames"][1], json!("Windows Fn")); + let assigned = ask("setKey", json!({ "layer": 1, "row": 0, "col": 26, "code": 0x100068 })); + assert_eq!(assigned["label"], json!("F13")); + let key = |board: &serde_json::Value| board["keys"].as_array().unwrap().iter().find(|k| k["col"] == json!(26)).unwrap()["label"].clone(); + assert_eq!(key(&ask("keys", json!({ "layer": 1 }))), json!("F13")); + assert_eq!(key(&ask("keys", json!({ "layer": 0 }))), json!("Esc"), "the other layer keeps its key"); +} diff --git a/public/devices/mchose-ace68-v2.png b/public/devices/mchose-ace68-v2.png new file mode 100644 index 00000000..9d386494 Binary files /dev/null and b/public/devices/mchose-ace68-v2.png differ