import { invoke } from "@tauri-apps/api/core"; import { decodeViaMacro, describeViaKeycode, encodeViaMacro, evaluateViaCondition, joinViaMacros, parseViaDefinition, parseViaMacroExpression, parseViaMenus, viaActiveKeys, viaKeycodeFromLayoutName, viaKeycodePicker, viaKeycodeToLayoutName, viaLayoutChoices, viaMacroToExpression, viaNumberToBytes, viaPackLayoutChoices, viaValueToNumber, VIA_MACRO_DELAY_PROTOCOL, type ViaDefinition, type ViaKeycodeGroupId, type ViaMacroAction, type ViaMenuItem, } from "@openmouse/keyboard-protocol/via"; import { hidUsage } from "./keys"; import { MODIFIERS, nameOf, numbered, type MacroStep } from "./macros"; import type { HidInterfaceInfo } from "./native-hid/tauri-hid-device"; export const VIA_FEATURES = { remap: true, noSave: true }; const ENCODER_ROW = 200; const GROUP_NAMES: Record = { letters: "Letters", numbers: "Numbers", symbols: "Symbols", function: "Function keys", navigation: "Navigation", keypad: "Keypad", modifiers: "Modifiers", media: "Media", special: "Special", layers: "Layers", macros: "Macros", lighting: "Lighting", custom: "Custom", }; const definitions = new Map(); export async function viaDefinition(info: HidInterfaceInfo): Promise { const id = `${info.vendorId}:${info.productId}`; if (definitions.has(id)) return definitions.get(id)!; const text = await invoke("via_definition", { vendorId: info.vendorId, productId: info.productId }); let definition: ViaDefinition | null = null; try { definition = text ? parseViaDefinition(JSON.parse(text)) : null; } catch { definition = null; } definitions.set(id, definition); return definition; } async function context(client: any, info: HidInterfaceInfo) { const via = (await client.readStatus()).via; if (!via?.layerCount) throw new Error("The keyboard did not report its VIA layers."); const definition = await viaDefinition(info); if (!definition) throw new Error("VIA has no layout for this keyboard, so its keys can't be shown."); const label = (code: number) => describeViaKeycode(code, via.protocolVersion, definition.customKeycodes).label; const choices = via.layoutOptions == null ? [] : viaLayoutChoices(definition.labels, via.layoutOptions); return { via, definition, label, choices }; } async function readKeys(client: any, info: HidInterfaceInfo, wanted: number) { const { via, definition, label, choices } = await context(client, info); const layer = Math.min(via.layerCount - 1, Math.max(0, wanted)); const keymap: number[][] = await client.readKeymap(definition.matrix, layer + 1); const codes = keymap[layer] ?? []; const active = viaActiveKeys(definition, choices); const keys = active .filter((key) => key.row >= 0) .map((key) => { const code = codes[key.row * definition.matrix.cols + key.col] ?? 0; return { row: key.row, col: key.col, x: key.x, y: key.y, w: key.w, h: key.h, code, label: label(code), standard: code, standardLabel: "" }; }); const encoders = [...new Set(active.filter((key) => key.encoder !== undefined).map((key) => key.encoder!))].sort((a, b) => a - b); const bottom = Math.max(0, ...keys.map((key) => key.y + key.h)); for (const [index, id] of encoders.entries()) { for (const clockwise of [false, true]) { const code = await client.readEncoder(layer, id, clockwise); keys.push({ row: ENCODER_ROW + id, col: clockwise ? 1 : 0, x: index * 2.25 + (clockwise ? 1 : 0), y: bottom + 0.25, w: 1, h: 1, code, label: `${clockwise ? "↻" : "↺"} ${label(code)}`, standard: code, standardLabel: "", }); } } const groups = viaKeycodePicker(via.protocolVersion, via.layerCount, via.macroCount ?? 0, { modules: definition.keycodeModules, custom: definition.customKeycodes, }); return { layer, layers: via.layerCount, width: Math.max(definition.width, encoders.length * 2.25), keys, categories: groups .filter((group) => group.keycodes.length > 0) .map((group) => ({ name: GROUP_NAMES[group.id], keys: group.keycodes.map((code) => ({ code, label: label(code) })) })), }; } async function setKey(client: any, info: HidInterfaceInfo, args: any) { const { layer, row, col, code } = args; const { via, definition, label } = await context(client, info); if (![layer, row, col, code].every(Number.isInteger) || layer < 0 || layer >= via.layerCount || code < 0 || code > 0xffff) { throw new RangeError("That key can't be assigned."); } if (row >= ENCODER_ROW) { const confirmed = await client.setEncoder(layer, row - ENCODER_ROW, col === 1, code); return { row, col, code: confirmed, label: `${col === 1 ? "↻" : "↺"} ${label(confirmed)}` }; } if (row >= definition.matrix.rows || col >= definition.matrix.cols) throw new RangeError("That key is outside the keyboard's matrix."); const confirmed = await client.setKeycode(layer, row, col, code); return { row, col, code: confirmed, label: label(confirmed) }; } export async function viaOp(client: any, info: HidInterfaceInfo, op: string, args: any): Promise { switch (op) { case "keys": return readKeys(client, info, Number(args.layer) || 0); case "setKey": return setKey(client, info, args); case "save": return true; default: throw new Error(`Unknown keyboard operation ${op}`); } } const valueKey = (ids: readonly number[]) => ids.join(":"); const itemLength = (item: ViaMenuItem) => (item.control.type === "color" ? 2 : item.bytes); const wire = (item: ViaMenuItem, protocol: number) => protocol < 11 && item.legacyId !== undefined ? [item.legacyId, ...item.ids.slice(2)] : item.ids; function hsvToHex(hue: number, saturation: number): string { const h = (hue / 255) * 6; const s = saturation / 255; const f = (n: number) => { const k = (n + h) % 6; return Math.round(255 * (1 - s * Math.max(0, Math.min(k, 4 - k, 1)))); }; return `#${[f(5), f(3), f(1)].map((v) => v.toString(16).padStart(2, "0")).join("")}`; } function hexToHsv(hex: string): [number, number] { const m = /^#?([0-9a-f]{6})$/i.exec(hex.trim()); if (!m) throw new RangeError("That is not a colour."); const [r, g, b] = [0, 2, 4].map((i) => parseInt(m[1]!.slice(i, i + 2), 16) / 255) as [number, number, number]; const max = Math.max(r, g, b); const delta = max - Math.min(r, g, b); let hue = 0; if (delta > 0) hue = max === r ? ((g - b) / delta + 6) % 6 : max === g ? (b - r) / delta + 2 : (r - g) / delta + 4; return [Math.round((hue / 6) * 255) % 256, Math.round((max === 0 ? 0 : delta / max) * 255)]; } async function menuState(client: any, info: HidInterfaceInfo) { const { via, definition, label, choices } = await context(client, info); const items = parseViaMenus(definition.menus).flatMap((menu) => menu.sections.flatMap((section) => section.items)); const values = new Map(); for (const item of items) { const key = valueKey(item.ids); if (values.has(key) || item.control.type === "button") continue; values.set(key, await client.readCustomValue(wire(item, via.protocolVersion), itemLength(item)).catch(() => null)); } return { via, definition, label, choices, items, values }; } function itemControl(item: ViaMenuItem, value: number[] | null) { const id = `via.v.${valueKey(item.ids)}`; const control = item.control; const number = value ? viaValueToNumber(value) : null; if (control.type === "range") return { id, label: item.label, kind: "number", min: control.min, max: control.max, step: 1, unit: control.unit, current: number ?? control.min }; if (control.type === "toggle") return { id, label: item.label, kind: "toggle", current: number === null ? false : control.anyOn ? number !== control.off : number === control.on }; if (control.type === "dropdown") return { id, label: item.label, kind: "choice", options: control.options, current: number }; if (control.type === "color") return { id, label: item.label, kind: "color", current: value && value.length >= 2 ? hsvToHex(value[0]!, value[1]!) : "#ffffff" }; return { id, label: item.label, kind: "button", options: [{ label: item.label, value: control.value }], current: control.value }; } const labelTitle = (label: unknown) => (Array.isArray(label) ? String(label[0]) : String(label)); export async function viaSections(client: any, info: HidInterfaceInfo) { const { via, definition, choices, values } = await menuState(client, info); const known = new Map(); for (const item of parseViaMenus(definition.menus).flatMap((menu) => menu.sections.flatMap((section) => section.items))) { const value = values.get(valueKey(item.ids)); if (value) known.set(item.token, viaValueToNumber(value)); } const shown = (expression?: string) => !expression || evaluateViaCondition(expression, (token) => known.get(token)); const lighting: { title: string; controls: unknown[] }[] = []; const sections: { title: string; controls: unknown[] }[] = []; for (const menu of parseViaMenus(definition.menus).filter((m) => shown(m.showIf))) { for (const section of menu.sections) { const controls = section.items.filter((item) => shown(item.showIf)).map((item) => itemControl(item, values.get(valueKey(item.ids)) ?? null)); if (controls.length) lighting.push({ title: section.label && section.label !== menu.label ? `${menu.label}: ${section.label}` : menu.label, controls }); } } if (definition.labels.length) { sections.push({ title: "Layout", controls: definition.labels.map((label, index) => Array.isArray(label) ? { id: `via.layout.${index}`, label: labelTitle(label), kind: "choice", options: label.slice(1).map((name, value) => ({ label: String(name), value })), current: choices[index] ?? 0 } : { id: `via.layout.${index}`, label: labelTitle(label), kind: "toggle", current: (choices[index] ?? 0) === 1 }), }); } sections.push({ title: "Backup", controls: [ { id: "via.file.save", label: "Save layout file", description: "The keymap, macros and knobs as a VIA .layout.json file.", kind: "saveFile", options: [{ label: "Save…", value: `${definition.name.replace(/[^a-zA-Z0-9]/g, "_").toLowerCase() || "keyboard"}.layout.json` }], current: null }, { id: "via.file.load", label: "Load layout file", description: "Replaces the keymap, macros and knobs with a VIA .layout.json file.", kind: "openFile", options: [{ label: "Load…", value: "json" }], current: null }, ], }); return { lighting, advanced: sections }; } async function encoderCount(definition: ViaDefinition, choices: number[]) { return new Set(viaActiveKeys(definition, choices).filter((key) => key.encoder !== undefined).map((key) => key.encoder)).size; } async function layoutFile(client: any, info: HidInterfaceInfo) { const { via, definition, choices } = await context(client, info); const name = (code: number) => viaKeycodeToLayoutName(code, via.protocolVersion); const keymap: number[][] = await client.readKeymap(definition.matrix, via.layerCount); const macros = (via.macroCount ?? 0) > 0 ? await client.readMacros() : null; const count = await encoderCount(definition, choices); const encoders: [string, string][][] = []; for (let id = 0; id < count; id++) { const perLayer: [string, string][] = []; for (let layer = 0; layer < via.layerCount; layer++) { perLayer.push([name(await client.readEncoder(layer, id, false)), name(await client.readEncoder(layer, id, true))]); } encoders.push(perLayer); } return JSON.stringify({ name: definition.name, vendorProductId: info.vendorId * 65536 + info.productId, macros: macros ? macros.macros.map((bytes: number[]) => viaMacroToExpression(decodeViaMacro(bytes, via.protocolVersion), via.protocolVersion)) : [], layers: keymap.map((layer) => layer.map(name)), encoders, }, null, 2); } async function loadLayoutFile(client: any, info: HidInterfaceInfo, text: string) { const { via, definition, choices } = await context(client, info); let file: any; try { file = JSON.parse(text); } catch { throw new Error("That file is not a VIA layout file."); } if (!file || !Array.isArray(file.layers) || file.layers.length === 0) throw new Error("That file is not a VIA layout file."); if (file.vendorProductId !== info.vendorId * 65536 + info.productId) throw new Error("That layout file is for a different keyboard."); const { rows, cols } = definition.matrix; const code = (entry: unknown) => { const found = typeof entry === "string" ? viaKeycodeFromLayoutName(entry, via.protocolVersion) : null; if (found === null) throw new Error(`The layout file has a key this app doesn't know: ${String(entry)}.`); return found; }; const layers = file.layers.slice(0, via.layerCount).map((layer: unknown) => { if (!Array.isArray(layer) || layer.length !== rows * cols) throw new Error("The layout file's layers don't match this keyboard."); return layer.map(code); }); const macros = (via.macroCount ?? 0) > 0 && Array.isArray(file.macros) && file.macros.length > 0 ? await client.readMacros() : null; let encoded: number[][] | null = null; if (macros) { if (file.macros.length !== macros.count) throw new Error("The layout file has a different number of macros."); encoded = file.macros.map((expression: unknown) => encodeViaMacro(parseViaMacroExpression(String(expression), via.protocolVersion), via.protocolVersion)); joinViaMacros(encoded!, macros.bufferSize); } await client.writeKeymap(layers, definition.matrix); if (encoded) await client.writeMacros(encoded); const count = await encoderCount(definition, choices); for (const [id, perLayer] of (Array.isArray(file.encoders) ? file.encoders : []).entries()) { if (id >= count || !Array.isArray(perLayer)) continue; for (const [layer, pair] of perLayer.entries()) { if (layer >= via.layerCount || !Array.isArray(pair)) continue; await client.setEncoder(layer, id, false, code(pair[0])); await client.setEncoder(layer, id, true, code(pair[1])); } } } export async function viaWrite(client: any, info: HidInterfaceInfo, id: string, value: unknown): Promise { if (id === "via.file.save") return layoutFile(client, info); if (id === "via.file.load") { await loadLayoutFile(client, info, String(value)); return null; } const { via, definition, choices, items } = await menuState(client, info); const layout = /^via\.layout\.(\d+)$/.exec(id); if (layout) { const index = Number(layout[1]); const label = definition.labels[index]; if (label === undefined) throw new RangeError("That layout option doesn't exist."); const next = [...choices]; next[index] = typeof value === "boolean" ? Number(value) : Number(value); await client.setLayoutOptions(viaPackLayoutChoices(definition.labels, next)); return null; } const item = items.find((entry) => `via.v.${valueKey(entry.ids)}` === id); if (!item) throw new Error("That setting isn't on this keyboard."); const control = item.control; const address = wire(item, via.protocolVersion); const legacy = address !== item.ids; let bytes: number[]; let verify = true; if (control.type === "color") bytes = hexToHsv(String(value)); else if (control.type === "toggle") bytes = viaNumberToBytes(value ? control.on : control.off, item.bytes); else if (control.type === "button") { bytes = viaNumberToBytes(control.value, item.bytes); verify = false; } else { const number = Number(value); if (!Number.isInteger(number)) throw new RangeError("That value is out of range."); if (control.type === "range" && (number < control.min || number > control.max)) throw new RangeError("That value is out of range."); bytes = viaNumberToBytes(number, item.bytes); } let confirmed: number[] = await client.setCustomValue(address, bytes, verify); if (verify && control.type === "range" && bytes.length === 1 && confirmed[0] !== bytes[0]) { const target = bytes[0]!; const retry = target + (target - confirmed[0]!); if (retry >= 0 && retry <= 0xff) { const second = await client.setCustomValue(address, [retry], true); confirmed = Math.abs(second[0]! - target) <= Math.abs(confirmed[0]! - target) ? second : await client.setCustomValue(address, bytes, true); } } await client.saveCustomChannel(item.ids[0]!, legacy); return null; } export const viaMacroPanel = (count: number) => ({ slots: numbered(count, "Macro"), buttons: [], maxSteps: 128, modifiers: true, mouse: false, readable: true, warning: null, note: "Put a macro on a key from the Macros group on the Keys tab. Saving keeps it on the keyboard.", }); const usageOf = (key: string) => MODIFIERS[key] ?? hidUsage(key); function toSteps(actions: ViaMacroAction[]): MacroStep[] { const steps: MacroStep[] = []; const press = (usage: number, down: boolean) => steps.push({ key: nameOf(usage), down, delay: 0 }); for (const action of actions) { if (action.type === "delay") { if (steps.length) steps[steps.length - 1]!.delay += action.ms; } else if (action.type === "tap") { press(action.keycode, true); press(action.keycode, false); } else if (action.type === "down" || action.type === "up") { press(action.keycode, action.type === "down"); } else { for (const char of action.text) { const upper = char.toUpperCase(); const shifted = /[A-Z]/.test(char); if (char === " ") { press(0x2c, true); press(0x2c, false); continue; } if (!/^[A-Z0-9]$/.test(upper)) throw new Error("This macro types text the app can't show, so it is left as it is."); if (shifted) press(MODIFIERS.Shift!, true); press(hidUsage(upper), true); press(hidUsage(upper), false); if (shifted) press(MODIFIERS.Shift!, false); } } } return steps; } export async function viaMacroOp(client: any, op: string, args: any): Promise { const via = (await client.readStatus()).via; const macros = await client.readMacros(); const slot = Number(args.slot) || 0; if (slot < 0 || slot >= macros.count) throw new RangeError("That macro doesn't exist."); if (op === "read") return toSteps(decodeViaMacro(macros.macros[slot] ?? [], via.protocolVersion)); if (op !== "save") throw new Error(`Unknown macro operation ${op}`); const delays = via.protocolVersion >= VIA_MACRO_DELAY_PROTOCOL; const actions: ViaMacroAction[] = []; for (const step of args.steps as MacroStep[]) { actions.push({ type: step.down ? "down" : "up", keycode: usageOf(step.key) }); if (delays && step.delay > 0) actions.push({ type: "delay", ms: step.delay }); } const next = macros.macros.map((bytes: number[]) => [...bytes]); next[slot] = encodeViaMacro(actions, via.protocolVersion); joinViaMacros(next, macros.bufferSize); await client.writeMacros(next); return true; }