Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions gpui/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)");
Expand Down
2 changes: 1 addition & 1 deletion gpui/js/entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 [];
});
Expand Down
189 changes: 189 additions & 0 deletions gpui/js/keyboard-logitech.ts
Original file line number Diff line number Diff line change
@@ -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<string, number>();
const liveGameKeys = new Map<string, string>();

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<number, number> | 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<void> {
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)}`);
}
}
}
97 changes: 84 additions & 13 deletions gpui/js/keyboards.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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";
}
Expand Down Expand Up @@ -52,22 +55,62 @@ function driverFor(info: HidInterfaceInfo): DeviceDriver | undefined {
});
}

/** The keyboards plugged in, leaving out anything already listed as a mouse. */
export async function listKeyboards(taken: Set<string>): Promise<KeyboardCandidate[]> {
/** 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<string, { name: string; at: number }>();

/**
* 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<string | undefined> {
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<string>, previous: ReadonlyMap<string, { info: HidInterfaceInfo }>): Promise<KeyboardCandidate[]> {
const via = await invoke<number[]>("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" });
}
return found;
}

/** Opens the board, does one thing with its driver, and closes it again. */
async function withKeyboard<T>(info: HidInterfaceInfo, work: (client: any, brand: string) => Promise<T>): Promise<T> {
return withHidOpenLock(info.key, async () => {
async function withKeyboard<T>(info: KeyboardInterface, work: (client: any, brand: string) => Promise<T>): Promise<T> {
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.");
Expand Down Expand Up @@ -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;
});
}

Expand All @@ -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<unknown> {
export async function writeKeyboard(info: KeyboardInterface, action: string, value: unknown): Promise<unknown> {
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.`);
Expand Down
Loading
Loading