diff --git a/gpui/build.rs b/gpui/build.rs index f562257c..75b33e27 100644 --- a/gpui/build.rs +++ b/gpui/build.rs @@ -22,6 +22,7 @@ fn main() { println!("cargo:rerun-if-changed=js/shims"); println!("cargo:rerun-if-changed=js/lib"); println!("cargo:rerun-if-changed=../node_modules/@openmouse/protocol/dist"); + println!("cargo:rerun-if-changed=../node_modules/@openmouse/keyboard-protocol/dist"); if !Path::new("../node_modules/esbuild").exists() { panic!("gpui: run `npm install` in the repo root first (esbuild builds the embedded protocol bundle)"); diff --git a/gpui/js/entry.ts b/gpui/js/entry.ts index ca2e316c..7e86cc9a 100644 --- a/gpui/js/entry.ts +++ b/gpui/js/entry.ts @@ -42,7 +42,7 @@ const mockWanted = (): string => String((globalThis as any).__mock ?? ""); if (!mockWanted().endsWith("!")) { // Mice come first, and a failure to look for keyboards leaves them listed. const mice = new Set(candidates.map((candidate) => candidate.info.key)); - const keyboards = await listKeyboards(mice).catch((error) => { + const keyboards = await listKeyboards(mice, lastList).catch((error) => { console.error("listing keyboards failed:", String(error)); return []; }); diff --git a/gpui/js/keyboard-logitech.ts b/gpui/js/keyboard-logitech.ts new file mode 100644 index 00000000..c6bfeec3 --- /dev/null +++ b/gpui/js/keyboard-logitech.ts @@ -0,0 +1,189 @@ +// Native controls for the G915 X TKL. The shared driver owns the protocol and +// verifies writes. The Desktop view exposes settings using its normal controls. +import type { LogitechKeyboardHidClient } from "@openmouse/keyboard-protocol/drivers/logitech/hid"; +import * as protocol from "@openmouse/keyboard-protocol/logitech"; +import type { + LogitechKeyboardState, LogitechOnboardLightingChange, LogitechOnboardLightingTarget, + LogitechOnboardMemory, LogitechOnboardProfileChanges, LogitechRgbColor, LogitechRgbMode, +} from "@openmouse/keyboard-protocol/logitech"; +import { hidUsage, parseShortcut } from "./keys"; + +const PREFIX = "logi.keyboard."; +const targets = { keys: "Keys", logo: "Logo", idleKeys: "Keys at idle", idleLogo: "Logo at idle" } as const; +const effects = { off: "Off", static: "Static", breathing: "Breathing single", cycle: "Cycling", wave: "Wave", ripple: "Ripple" } as const; +const fields = ["dimAfterSeconds", "offAfterSeconds"] as const; +const selected = new Map(); +const liveGameKeys = new Map(); + +export const isLogitechKeyboardControl = (action: string) => action.startsWith(`control:${PREFIX}`); +const text = (id: string, label: string, current: string, description?: string) => ({ id: PREFIX + id, label, kind: "text", current, description }); +const info = (id: string, label: string, current: string) => ({ id: PREFIX + id, label, kind: "info", current }); +const toggle = (id: string, label: string, current: boolean) => ({ id: PREFIX + id, label, kind: "toggle", current }); +const choice = (id: string, label: string, current: number, options: { value: number; label: string }[]) => + ({ id: PREFIX + id, label, kind: "choice", current, options }); +const timer = (seconds: number | null) => seconds === null ? "Never" : String(seconds); +const hex = (color: LogitechRgbColor) => `#${[color.red, color.green, color.blue].map(v => v.toString(16).padStart(2, "0")).join("")}`; + +function color(value: string): LogitechRgbColor { + if (!/^#[a-f\d]{6}$/i.test(value)) throw new Error("Use a color in #RRGGBB format."); + const rgb = Number.parseInt(value.slice(1), 16); + return { red: rgb >> 16, green: rgb >> 8 & 255, blue: rgb & 255 }; +} + +function parseTimer(value: string): number | null { + if (value.toLowerCase() === "never") return null; + if (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 65534) { + throw new Error("Enter a whole number of seconds from 1 to 65534, or Never."); + } + return Number(value); +} + +function parseEffect(value: string): LogitechOnboardLightingChange | { animationSlot: 0 | 1 } { + const [name, ...args] = value.toLowerCase().split(/\s+/); + if (name === "animation" && args.length === 1 && (args[0] === "8" || args[0] === "9")) { + return { animationSlot: args[0] === "8" ? 0 : 1 }; + } + const mode = effects[name as keyof typeof effects] as LogitechRgbMode | undefined; + if (!Object.hasOwn(effects, name) || !mode) throw new Error("Enter Off, Static, Breathing, Cycle, Wave or Ripple."); + const change: LogitechOnboardLightingChange = { mode }; + if (mode === "Static" || mode === "Breathing single" || mode === "Ripple") change.color = color(args.shift() ?? ""); + if (mode !== "Off" && mode !== "Static" && args.length) { + const period = args.shift()!; + if (!/^\d+$/.test(period)) throw new Error("Enter the period in milliseconds."); + change.periodMs = Number(period); + } + if (args.length) throw new Error("Remove extra values after the effect settings."); + return change; +} + +function showEffect(effect: LogitechOnboardMemory["profiles"][number]["effects"][LogitechOnboardLightingTarget]): string { + if (effect.animationSlot === 0 || effect.animationSlot === 1) return `Animation ${8 + effect.animationSlot}`; + const mode = protocol.logitechRgbMode(effect.effectId); + const label = Object.entries(effects).find(([, wire]) => wire === mode)?.[0]; + return label ? [label, effect.color && hex(effect.color), effect.periodMs].filter(value => value != null).join(" ") : ""; +} + +function disabledKeys(value: string): number[] { + if (value.toLowerCase() === "none") return []; + // Use the driver's physical key map once the package version that exposes it is installed. + const controls = Reflect.get(protocol, "G915_X_TKL_GAME_MODE_KEYS") as ReadonlyMap | undefined; + return value.split(/[\s,]+/).map(name => { + const id = controls?.get(hidUsage(name.length === 1 ? name.toUpperCase() : name)); + if (id === undefined) throw new Error(`The key ${name} is unavailable for Game Mode.`); + return id; + }); +} + +export async function logitechKeyboardSections(client: LogitechKeyboardHidClient, key: string, state: LogitechKeyboardState) { + if (!state.onboardMemory || typeof client.readOnboardMemory !== "function") return []; + const memory = await client.readOnboardMemory(); + const options = memory.profiles.map(profile => ({ value: profile.slot, label: profile.name || `Slot ${profile.slot}` })); + const slot = selected.get(key) ?? memory.activeSlot; + const profile = memory.profiles.find(item => item.slot === slot) ?? memory.profiles[0]; + if (!profile) return []; + const profileId = `profile.${profile.slot}.`; + const controls = [ + text(profileId + "name", "Profile name", profile.name, "Up to 12 characters."), + ...Object.entries(targets).map(([field, label]) => { + const target = field as LogitechOnboardLightingTarget; + const primary = target === "keys" || target === "idleKeys"; + const modes = primary ? "Off, Static #ffffff, Breathing #ffffff 3000, Cycle 3000, Wave 3000" : "Off, Static #ffffff, Breathing #ffffff 3000, Cycle 3000"; + const examples = target === "keys" ? `${modes}, Ripple #ffffff 50, Animation 8 or Animation 9.` : `${modes}.`; + return text(profileId + field, label, showEffect(profile.effects[target]), examples); + }), + text(profileId + fields[0], "Dim after", timer(profile.dimAfterSeconds), "Seconds or Never."), + text(profileId + fields[1], "Turn off after", timer(profile.offAfterSeconds), "Seconds or Never."), + ]; + if (state.gameMode) { + controls.push(text(profileId + "game", "Store Game Mode keys", "", "Type key names separated by commas, such as A, F5. Use None for factory keys only.")); + if (profile.bindings) controls.push(text(profileId + "binding", "Store key assignment", "", "For example F5 = Ctrl+B, or F5 = Original. Fn+F1 toggles key assignments.")); + } + const sections = [ + { title: "Onboard memory", controls: [ + choice("active", "Active profile", memory.enabled ? memory.activeSlot : 0, [{ value: 0, label: "Software mode" }, ...options]), + choice("slot", "Edit profile", profile.slot, options), + ] }, + { title: profile.name || `Profile ${profile.slot}`, controls }, + ]; + if (state.gameMode) sections.push({ title: "Game Mode", controls: [ + info("gameStatus", "Game Mode", state.gameMode.active ? "On" : "Off"), + text("game", "Disable additional keys", liveGameKeys.get(key) ?? "", "Type key names separated by commas, or None for factory keys only."), + ] }); + if (state.lighting?.startup) { + const startup = state.lighting.startup; + sections.push({ title: "Startup lighting", controls: [ + toggle("startup.enabled", "Play startup effect", startup.enabled), + text("startup.primary", "Primary color", hex(startup.primary), "Use #RRGGBB."), + text("startup.secondary", "Secondary color", hex(startup.secondary), "Use #RRGGBB."), + ] }); + } + if (memory.animations?.some(item => item.name)) sections.push({ title: "Stored animations", controls: memory.animations.map(item => + info(`animation.${item.slot}`, `Brightness + ${8 + item.slot}`, item.name || "Empty"), + ) }); + return sections; +} + +export async function writeLogitechKeyboard(client: LogitechKeyboardHidClient, key: string, action: string, value: unknown): Promise { + if (typeof client.readOnboardMemory !== "function") throw new Error("Onboard profiles are unavailable on this connection."); + const id = action.slice(`control:${PREFIX}`.length); + if (id.startsWith("startup.")) { + const startup = (await client.readStatus()).logitech?.lighting?.startup; + if (!startup) throw new Error("This keyboard did not report startup lighting."); + if (id === "startup.enabled" && typeof value === "boolean") { + await client.setStartupLighting({ ...startup, enabled: value }); + } else if ((id === "startup.primary" || id === "startup.secondary") && typeof value === "string") { + await client.setStartupLighting({ ...startup, [id.slice(8)]: color(value.trim()) }); + } else throw new Error("Invalid startup lighting setting."); + return; + } + const memory = await client.readOnboardMemory(); + if (id === "slot" || id === "active") { + if (id === "active" && value === 0) { + await client.leaveOnboardMemory(); + return; + } + const profile = memory.profiles.find(item => item.slot === value); + if (!profile) throw new Error("Unknown onboard profile slot."); + if (id === "active") await client.activateOnboardProfile(profile.slot); + selected.set(key, profile.slot); + return; + } + if (typeof value !== "string") throw new Error("Enter a value for this control."); + const entry = value.trim(); + if (id === "game") { + await client.setGameModeDisabledKeys(disabledKeys(entry)); + liveGameKeys.set(key, entry); + return; + } + const [, slot, field] = /^profile\.(\d+)\.(\w+)$/.exec(id) ?? []; + const profile = memory.profiles.find(item => item.slot === Number(slot)); + if (!profile) throw new Error("Unknown onboard profile slot."); + let changes: LogitechOnboardProfileChanges; + if (field === "name") changes = { name: entry }; + else if (field === fields[0] || field === fields[1]) changes = { [field]: parseTimer(entry) }; + else if (field === "game") changes = { gameModeDisabledKeys: disabledKeys(entry) }; + else if (field === "binding") { + const parts = /^([^=]+)\s*=\s*([^=]+)$/.exec(entry); + if (!parts) throw new Error("Enter an assignment such as F5 = Ctrl+B or F5 = Original."); + const sourceUsage = hidUsage(parts[1].trim()); + const target = parts[2].trim(); + const shortcut = target.toLowerCase() === "original" ? { usage: null, modifiers: 0 } : parseShortcut(target); + changes = { binding: { sourceUsage, targetUsage: shortcut.usage, modifiers: shortcut.modifiers } }; + } else if (Object.hasOwn(targets, field)) { + const effect = parseEffect(entry); + if ("animationSlot" in effect && field !== "keys") throw new Error("Stored animations are available for active keys."); + changes = "animationSlot" in effect ? effect : { lightingByTarget: { [field]: effect } }; + } else throw new Error("Unknown Logitech keyboard control."); + const saved = await client.saveOnboardProfile(profile.slot, profile.revision, changes); + const current = await client.readOnboardMemory(); + if (current.profiles.find(item => item.slot === saved.slot)?.revision !== saved.revision) { + throw new Error("The keyboard did not retain the saved profile."); + } + if (current.enabled && current.activeSlot === profile.slot) { + try { + await client.activateOnboardProfile(profile.slot); + } catch (error) { + throw new Error(`The profile was saved. Select it again to apply the changes: ${String(error)}`); + } + } +} diff --git a/gpui/js/keyboards.ts b/gpui/js/keyboards.ts index b62b97ce..ca121aba 100644 --- a/gpui/js/keyboards.ts +++ b/gpui/js/keyboards.ts @@ -1,6 +1,6 @@ // Keyboards, found and read through `@openmouse/keyboard-protocol`. Every board -// shows what it says about itself; Wuque Studio ones can also be changed (see -// keyboard-wuque.ts). +// shows what it says about itself. Brand-specific editors use the same +// native transport. // // A driver is only offered a board whose report collections it claims: there is // no guessing by vendor, so nothing unknown is ever opened. Any vendor can ship @@ -12,10 +12,13 @@ import { WUQUE_FEATURES, wuqueOp } from "./keyboard-wuque"; 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"; -import { withHidOpenLock } from "./native-hid/hid-open-lock"; +import { isHidBusyError, withHidOpenLock } from "./native-hid/hid-open-lock"; +import { isLogitechKeyboardControl, logitechKeyboardSections, writeLogitechKeyboard } from "./keyboard-logitech"; + +type KeyboardInterface = HidInterfaceInfo & { receiverKey?: string }; export interface KeyboardCandidate { - info: HidInterfaceInfo; + info: KeyboardInterface; brands: string[]; kind: "keyboard"; } @@ -52,13 +55,53 @@ function driverFor(info: HidInterfaceInfo): DeviceDriver | undefined { }); } -/** The keyboards plugged in, leaving out anything already listed as a mouse. */ -export async function listKeyboards(taken: Set): Promise { +/** How long a keyboard found on a shared receiver stays listed before it is asked again. */ +const RECEIVER_KEYBOARD_TTL_MS = 60000; +const receiverKeyboards = new Map(); + +/** + * Names the G915 X TKL paired to a shared receiver. Listing runs on every + * rescan, so a recent answer is reused and a new one reads the identity only. + */ +async function sharedReceiverKeyboard(info: HidInterfaceInfo, listed: string | undefined): Promise { + const known = receiverKeyboards.get(info.key); + if (listed && known && Date.now() - known.at < RECEIVER_KEYBOARD_TTL_MS) return known.name; + try { + const name = await withKeyboard(info, async client => { + // Drivers older than identify() can only answer with a full status read. + const identity = typeof client.identify === "function" + ? await client.identify() + : await client.readStatus().then((status: any) => ({ productId: status.logitech?.productId, name: status.name })); + return identity?.productId === 0x40b6 ? identity.name as string : undefined; + }); + if (name) receiverKeyboards.set(info.key, { name, at: Date.now() }); + else receiverKeyboards.delete(info.key); + return name; + } catch (error) { + // The mouse on the same receiver is being read. Keep what was listed. + if (isHidBusyError(error)) return listed; + receiverKeyboards.delete(info.key); + return undefined; + } +} + +/** Lists keyboards, including the keyboard endpoint of a shared receiver. */ +export async function listKeyboards(taken: Set, previous: ReadonlyMap): Promise { const via = await invoke("hid_vendors_with_usage", { usagePage: VIA_USAGE_PAGE, usage: VIA_USAGE }); const vendors = [...new Set([...filters.flatMap((f) => (f.vendorId === undefined ? [] : [f.vendorId])), ...via])]; const found: KeyboardCandidate[] = []; for (const info of await listHidInterfaces(vendors)) { - if (taken.has(info.key)) continue; + if (taken.has(info.key)) { + if (info.vendorId === 0x046d && info.productId === 0xc547) { + const key = `${info.key}/keyboard`; + const name = await sharedReceiverKeyboard(info, previous.get(key)?.info.productString); + if (name) { + found.push({ info: { ...info, key, receiverKey: info.key, productString: name }, + brands: ["Logitech"], kind: "keyboard" }); + } + } + continue; + } const driver = driverFor(info); if (driver) found.push({ info, brands: [driver.brand], kind: "keyboard" }); } @@ -66,8 +109,8 @@ export async function listKeyboards(taken: Set): Promise(info: HidInterfaceInfo, work: (client: any, brand: string) => Promise): Promise { - return withHidOpenLock(info.key, async () => { +async function withKeyboard(info: KeyboardInterface, work: (client: any, brand: string) => Promise): Promise { + return withHidOpenLock(info.receiverKey ?? info.key, async () => { const driver = driverFor(info); const client = driver?.create(deviceFor(info)) as any; if (!driver || !client) throw new Error("No keyboard driver claims this device."); @@ -140,10 +183,20 @@ export function describeKeyboard(key: string, brand: string, status: any) { }; } -export async function connectKeyboard(info: HidInterfaceInfo) { +export async function connectKeyboard(info: KeyboardInterface) { return withKeyboard(info, async (client, brand) => { const status = await client.readStatus(); - return describeKeyboard(info.key, brand, { ...status, ...(await polling(client)) }); + const rates = status.logitech ?? await polling(client); + const sections = status.logitech?.onboardMemory + ? await logitechKeyboardSections(client, info.key, status.logitech) + : []; + const readout = describeKeyboard(info.key, brand, { + ...status, pollingRateHz: rates.pollingRateHz, supportedPollingRates: rates.supportedPollingRates, + // These controls are offered only after the hardware returns a profile. + ui: sections.length ? { ...status.ui, settingsReady: true, statusNote: undefined } : status.ui, + }); + readout.tabs.advanced.unshift(...sections); + return readout; }); } @@ -156,9 +209,27 @@ export async function keyboardOp(info: HidInterfaceInfo, op: string, args: any): } /** Writes a keyboard setting and resolves to what the board then reports. */ -export async function writeKeyboard(info: HidInterfaceInfo, action: string, value: unknown): Promise { +export async function writeKeyboard(info: KeyboardInterface, action: string, value: unknown): Promise { + if (isLogitechKeyboardControl(action)) { + return withKeyboard(info, async (client, brand) => { + if (brand !== "Logitech") throw new Error("This control requires a Logitech keyboard."); + await writeLogitechKeyboard(client, info.key, action, value); + const status = await client.readStatus(); + const readout = describeKeyboard(info.key, brand, status); + const sections = await logitechKeyboardSections(client, info.key, status.logitech); + return { tabs: { ...readout.tabs, advanced: [...sections, ...readout.tabs.advanced] } }; + }); + } if (action !== "pollingRate") throw new Error("This app can't change that on a keyboard yet."); - return withKeyboard(info, async (client) => { + return withKeyboard(info, async (client, brand) => { + if (brand === "Logitech") { + const { logitech } = await client.readStatus(); + const rate = Number(value); + if (!logitech?.supportedPollingRates.includes(rate)) throw new Error(`This keyboard can't be set to ${value} Hz here.`); + await client.setPollingRate(rate); + if ((await client.readStatus()).logitech?.pollingRateHz !== rate) throw new Error("The keyboard did not confirm the polling rate."); + return rate; + } const name = Object.keys(RATES).find((key) => RATES[key] === Number(value)); if (!name || typeof client.writeReportRate !== "function") { throw new Error(`This keyboard can't be set to ${value} Hz here.`); diff --git a/gpui/src/app/device_io.rs b/gpui/src/app/device_io.rs index e561be77..eb8fc57b 100644 --- a/gpui/src/app/device_io.rs +++ b/gpui/src/app/device_io.rs @@ -386,7 +386,12 @@ impl AppView { let mut expected = Vec::new(); match result { Ok(Ok(applied)) => { - expected.push(Expected { action: format!("control:{id}"), value: value.clone() }); + // 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."); + if !confirmed_tabs { + expected.push(Expected { action: format!("control:{id}"), value: value.clone() }); + } let name = v.control_name(&key, &id); v.saved(&name, cx); // A control that reshapes the page (a switch gaining analog settings) returns the new layout. @@ -409,7 +414,7 @@ impl AppView { } } } - if let Some(tile) = v.devices.tiles.iter_mut().find(|t| t.key == key) { + if let Some(tile) = v.devices.tiles.iter_mut().find(|t| t.key == key).filter(|_| !confirmed_tabs) { if let TileStatus::Connected(r) = &mut tile.status { for section in r.tabs.buttons.iter_mut().chain(r.tabs.advanced.iter_mut()).chain(r.tabs.performance.iter_mut()).chain(r.tabs.receiver.iter_mut()) { for control in &mut section.controls {