// Entry for the JS bundle embedded in the GPUI app (see build.mjs). Exposes // the same list/connect flow the Tauri app runs (src/native-hid/scan.ts), // bundled unmodified, behind two JSON-in/JSON-out functions for Rust. import "./globals"; import "./wlmouse-apply"; import { macroOp } from "./macros"; import { callClientMethod as genericCall } from "./generic-write"; import { connectKeyboard, describeKeyboard, listKeyboards, keyboardMacroOp, keyboardOp, writeKeyboard } from "./keyboards"; 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 { artBounds, deviceImageCandidates } from "./native-hid/device-images"; import * as logitechWrite from "./native-hid/logitech-actions"; import * as genericWrite from "./native-hid/write"; import { deviceCapabilities, dpiBounds } from "./native-hid/write"; import { DPI_MAX, DPI_MIN, DPI_PRESETS, DPI_STEP, GAMING_SURFACE_MODES } from "./lib/logitech-controls"; import { withLogitechClient } from "./native-hid/logitech-actions"; import { LOGITECH_BUTTON_ACTIONS, factoryDirectoryForFormat } from "@openmouse/protocol/drivers/logitech/onboard-profiles"; import { LOGITECH_COMMANDS, commandFor } from "./lib/logitech-commands"; import { applyGameProfile } from "./lib/game-profiles"; import { describeControls, setPrefs, writeControl, writeLighting } from "./controls"; import { connectToInterface, listCandidateInterfaces, type CandidateInterface } from "./native-hid/scan"; let lastList = new Map(); const lastStatus = new Map(); const lastCaps = new Map(); /** What this app has set on each device, for settings a mouse cannot report. */ const written = new Map>(); const writtenTo = (key: string) => written.get(key) ?? written.set(key, {}).get(key)!; const travel = new DepthStream(async (key, sample) => { const info = lastList.get(key)?.info; if (!info) throw new Error("The mouse isn't connected."); return openTravel(info)(sample); }); const mockWanted = (): string => String((globalThis as any).__mock ?? ""); (globalThis as any).__api = { async listCandidates(): Promise { // A trailing "!" on OPENMOUSE_MOCK (e.g. "ulx!") lists only the fakes. const candidates = mockWanted().endsWith("!") ? [] : await listCandidateInterfaces(); 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, lastList).catch((error) => { console.error("listing keyboards failed:", String(error)); return []; }); candidates.push(...(keyboards as any[])); } candidates.push(...(mockCandidates(mockWanted()) as any[])); lastList = new Map(candidates.map((candidate) => [candidate.info.key, candidate])); return JSON.stringify(candidates); }, async setPrefs(argsJson: string): Promise { setPrefs(JSON.parse(argsJson)); return "{}"; }, /** Artwork for a device: URL plus the box-relative placement `deviceArtStyle` computes in the Tauri app, and ordered slug fallbacks. */ async deviceImage(argsJson: string): Promise { const [key, name] = JSON.parse(argsJson) as [string, string]; const candidates = deviceImageCandidates(key, name); const primary = candidates[0]; const filename = primary.filename; const bounds = artBounds(filename); let art = null; if (bounds) { // Same math as deviceArtStyle() in device-images.ts (target 0.5, cap 50). const linear = Math.sqrt(bounds.w * bounds.h * bounds.aspect); if (linear > 0) { const height = Math.min( (100 * 0.5) / linear, 50 / Math.max(bounds.aspect * bounds.w, 0.01), 50 / Math.max(bounds.h, 0.01), ); art = { height, aspect: bounds.aspect, offsetX: (0.5 - (bounds.x + bounds.w / 2)) * 100, offsetY: (0.5 - (bounds.y + bounds.h / 2)) * 100, }; } } return JSON.stringify({ filename, url: primary.url, art, fallbacks: candidates.slice(1), }); }, /** Magnetic button travel since the last call; keeps the stream alive. */ async buttonDepth(key: string): Promise { if (isMockKey(key)) return JSON.stringify(mockDepths()); const s = lastStatus.get(key); if (!s?.magneticButtons?.liveDepth && !s?.analogButtonTuning?.buttons?.length) return "[]"; return JSON.stringify(await travel.drain(key)); }, async stopButtonDepth(): Promise { await travel.stop(); return "{}"; }, /** Reads or saves one of a mouse's on-board macros. */ async macros(argsJson: string): Promise { 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.`); await travel.stop(key); if (isMockKey(key)) return JSON.stringify(action === "read" ? [] : true); if (candidate.kind === "keyboard") return JSON.stringify(await keyboardMacroOp(candidate.info, action, args)); return JSON.stringify(await macroOp(candidate.info, lastStatus.get(key) ?? {}, action, args)); }, /** Keys, actuation and lighting of a keyboard. */ async keyboard(argsJson: string): Promise { 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)); return JSON.stringify(await keyboardOp(candidate.info, action, args)); }, async connect(key: string): Promise { await travel.stop(key); const candidate = lastList.get(key); 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)); } 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); // Fallback DPI limits and presets per brand, as DevicePerformanceTab.tsx has // them: the device's own limits win (dpiBounds), these cover drivers that // publish none. const razer = device.brand === "Razer"; const attackShark = device.brand === "Attack Shark"; const bounds = dpiBounds(device.status, caps, { min: attackShark ? 50 : razer ? 100 : DPI_MIN, max: attackShark ? 22000 : razer ? 8500 : DPI_MAX, step: attackShark ? 50 : razer ? 100 : DPI_STEP, }); if (!mock && device.brand === "Logitech") { const status = device.status as any; const options: number[] | null = await withLogitechClient(candidate.info, "getDpiOptions", (client: any) => client.getDpiOptions()).catch(() => null); if (options && options.length > 1) { const sorted = [...options].sort((a, b) => a - b); status.dpiOptions = sorted; const gaps = sorted.slice(1).map((v, i) => v - sorted[i]).filter((gap) => gap > 0); Object.assign(bounds, { min: sorted[0], max: sorted[sorted.length - 1], step: Math.min(...gaps), options: sorted }); } if (status.onboardProfileFormat) status.onboardProfileFormat.factory = factoryDirectoryForFormat(status.onboardProfileFormat.id, 255) !== null; } const presets = attackShark ? [400, 800, 1600, 3200, 6400, 12800, 22000] : razer ? [400, 800, 1600, 3200, 6400, 8000] : DPI_PRESETS; // What the stage editor needs to know about this device (see dpi-stages.ts). Object.assign(device.status, { stageSupport: mock ? ALL_STAGE_SUPPORT : stageSupport(candidate.info, device.driver), dpiLimits: bounds, driverName: device.driver, methods: mock ? [] : driverSetters(candidate.info, device.driver), written: writtenTo(key), }); // The Nape layer being edited, which reading the status does not include. const methods: string[] = (device.status as any).methods; if (methods.includes("readLayerKeymap")) { const layer = napeEditedLayer(device.status, writtenTo(key)); (device.status as any).napeKeymap = await readNapeLayer(candidate.info, layer).catch(() => null); } // A Logitech mouse without onboard profiles (MX, office) remaps its buttons // over 0x1B04 instead; reading what each one does is not part of the status. if (!mock && device.brand === "Logitech" && (device.status as any).onboardProfileFormat?.supported !== true) { (device.status as any).logitechButtons = await withLogitechClient(candidate.info, "readButtons", (client: any) => client.readButtons()) .catch(() => null); } lastStatus.set(key, device.status); lastCaps.set(key, caps); return JSON.stringify({ ...device, // `brand` is the registry's label for the driver that answered and what the // app's own gating compares against; a product can carry its own brand (an // Attack Shark R5 Ultra is driven by the Lamzu driver and says so), which is // what a person should be shown. displayBrand: device.status.brand || device.brand, controls: { dpi: bounds, dpiPresets: presets, surfaceModes: GAMING_SURFACE_MODES }, tabs: describeControls(device.brand, device.status, caps), }); }, /** Logitech onboard profiles, read on demand (a full pass is ~80 round trips). */ async onboardProfiles(argsJson: string): Promise { const { key } = JSON.parse(argsJson) as { key: string }; await travel.stop(key); if (isMockKey(key)) return JSON.stringify({ ...mockOnboard(LOGITECH_BUTTON_ACTIONS as string[]), commands: LOGITECH_COMMANDS }); const candidate = lastList.get(key); if (!candidate) throw new Error(`Unknown interface ${key}; list candidates first.`); const profiles: any[] = await withLogitechClient(candidate.info, "readOnboardProfiles", (client: any) => client.readOnboardProfiles()); // `raw` is a Uint8Array kept for maintainers' captures; the page has no use for it. // Each button's `action` becomes the page's command value (a shortcut or media // key reads as one, not as "Custom"). const asCommands = (list: any[] = []) => list.map((a) => ({ ...a, action: commandFor(a.action, a.raw ?? []) })); return JSON.stringify({ profiles: profiles.map(({ raw, ...rest }) => ({ ...rest, buttonAssignments: asCommands(rest.buttonAssignments) })), actions: LOGITECH_BUTTON_ACTIONS, commands: LOGITECH_COMMANDS, }); }, /** Switch the running onboard profile (volatile, no flash write) or Onboard/Host mode. */ async onboardAction(argsJson: string): Promise { const { key, action, value } = JSON.parse(argsJson) as { key: string; action: "useProfile" | "mode" | "stages" | "rename" | "factory" | "enable"; value: any }; await travel.stop(key); if (isMockKey(key)) return JSON.stringify(mockOnboardAction(action, value)); const candidate = lastList.get(key); if (!candidate) throw new Error(`Unknown interface ${key}; list candidates first.`); return JSON.stringify( await withLogitechClient(candidate.info, `onboard ${action}`, async (client: any) => { client.profileFormatId ??= lastStatus.get(key)?.onboardProfileFormat?.id ?? null; try { if (action === "useProfile") { // A stored profile only runs while the mouse is in Onboard mode. await client.setOnboardMode("Onboard"); await client.setCurrentProfile(Number(value)); if (lastStatus.get(key)) lastStatus.get(key).deviceMode = "Onboard"; return value; } if (action === "enable") { await client.setProfileEnabled(Number(value.sector), Boolean(value.enabled)); return value.enabled; } if (action === "rename") { const name = String(value.name ?? "").trim(); if (!name) throw new Error("A profile name can't be empty."); await client.writeActiveProfile({ sector: Number(value.sector), name }); return name; } if (action === "factory") { const profiles = await client.readOnboardProfiles(); if (profiles.length === 0) await client.initializeBlankOnboardProfiles(); else await client.resetAllOnboardProfiles(); if (lastStatus.get(key)) lastStatus.get(key).deviceMode = "Onboard"; return "Onboard"; } if (action === "stages") { const { sector, ...plan } = value; const options: number[] | null = lastStatus.get(key)?.dpiOptions ?? await client.getDpiOptions().catch(() => null); if (options?.length) { const snap = (v: number) => options.reduce((best, o) => (Math.abs(o - v) < Math.abs(best - v) ? o : best)); plan.stages = plan.stages.map((stage: any) => ({ ...stage, x: snap(stage.x), y: snap(stage.y) })); } await client.writeActiveProfile({ sector, dpiStages: plan }); return value; } const mode = await client.setOnboardMode(value === "Onboard" ? "Onboard" : "Host"); if (lastStatus.get(key)) lastStatus.get(key).deviceMode = mode; return mode; } catch (error) { // Log sector/mode + HID++ feature versions so field rejections (e.g. #53) // are diagnosable from a single user log without a custom build. const diag: Record = { action, value, vid: candidate.info.vendorId.toString(16).padStart(4, "0"), pid: candidate.info.productId.toString(16).padStart(4, "0"), deviceIndex: client.deviceIndex, }; if (typeof client.getFeature === "function") { const f8100 = await client.getFeature(0x8100).catch(() => null); const f2201 = await client.getFeature(0x2201).catch(() => null); if (f8100) diag.f8100 = { index: f8100.index, version: f8100.version }; if (f2201) diag.f2201 = { index: f2201.index, version: f2201.version }; } console.warn(`[onboard] ${action} failed: ${error instanceof Error ? error.message : String(error)} diag=${JSON.stringify(diag)}`); throw error; } }), ); }, /** A game profile, applied in one device session (the Tauri app's own applyGameProfile), plus any extra control and lighting overrides. Resolves to the values that were applied. */ async applyProfile(argsJson: string): Promise { const { key, profile } = JSON.parse(argsJson) as { key: string; profile: any }; await travel.stop(key); const candidate = lastList.get(key); if (!candidate) throw new Error(`Unknown interface ${key}; list candidates first.`); if (isMockKey(key)) return "{}"; const applied: Record = {}; const errors: string[] = []; try { await applyGameProfile(candidate.info, profile, (patch) => Object.assign(applied, patch)); } catch (error) { errors.push(error instanceof Error ? error.message : String(error)); } const status = lastStatus.get(key) ?? {}; if (profile.controls && typeof profile.controls === "object") { for (const [id, value] of Object.entries(profile.controls as Record)) { try { await writeControl(candidate.info, status, id, value); } catch (error) { errors.push(`${id}: ${error instanceof Error ? error.message : String(error)}`); } } } if (profile.lighting && typeof profile.lighting === "object") { try { await writeLighting(candidate.info, status, profile.lighting); } catch (error) { errors.push(`Lighting: ${error instanceof Error ? error.message : String(error)}`); } } if (errors.length > 0) throw new Error(errors.join("; ")); return JSON.stringify(applied); }, /** * One live setting. Logitech goes through its receiver-aware module, every * other brand through the generic one - the same split DevicePerformanceTab * makes. Resolves to the value the device actually applied. */ async write(argsJson: string): Promise { let { key, brand, action, value } = JSON.parse(argsJson) as { key: string; brand: string; action: string; value: any; }; const candidate = lastList.get(key); if (!candidate) throw new Error(`Unknown interface ${key}; list candidates first.`); await travel.stop(key); if ((candidate as any).kind === "keyboard") { return JSON.stringify(isMockKey(key) ? value : await writeKeyboard(candidate.info, action, value)); } const w = brand === "Logitech" ? logitechWrite : genericWrite; const info = candidate.info; if (isMockKey(key) && !action.startsWith("control:")) return JSON.stringify(value); // Buttons / Advanced tab controls ("control:") and the Lighting tab. if (action.startsWith("control:")) { const status = lastStatus.get(key) ?? {}; const id = action.slice("control:".length); await writeControl(info, status, id, value); // A few controls decide which others are shown (a Starlight X switch in // TMR mode gains its analog settings, a magnetic button's rapid trigger its // sensitivity); their write returns the new layout. if (id.startsWith("slx.mode") || id === "slx.link" || id === "hits.link" || id === "perf.stageCount" || id.startsWith("logi.remap.") || id.startsWith("mag.") || id.startsWith("x.nape.") || id.startsWith("x.xm.") || id.startsWith("x.fmp.name.") || id === "x.lg.name" || id === "x.lg.restoreButtons" || id.endsWith(".curve") || id.endsWith("/mode")) return JSON.stringify({ tabs: describeControls(brand, status, lastCaps.get(key)) }); return JSON.stringify(value); } if (action === "lighting") { return JSON.stringify(await writeLighting(info, lastStatus.get(key) ?? {}, value)); } const onboard = lastStatus.get(key); const options: number[] | undefined = onboard?.dpiOptions; if (brand === "Logitech" && action === "dpi" && options?.length) { const snap = (v: number, from: unknown) => { const near = options.reduce((best, o) => (Math.abs(o - v) < Math.abs(best - v) ? o : best)); if (typeof from !== "number" || near !== from || v === from) return near; return (v > from ? options.find((o) => o > from) : [...options].reverse().find((o) => o < from)) ?? near; }; value = typeof value === "number" ? snap(value, onboard.dpi) : { ...value, x: snap(value.x, onboard.dpi), y: snap(value.y, onboard.dpiY ?? onboard.dpi) }; onboard.dpi = typeof value === "number" ? value : value.x; if (typeof value !== "number") onboard.dpiY = value.y; } if (brand === "Logitech" && (action === "dpi" || action === "pollingRate" || action === "liftOff") && onboard?.deviceMode === "Onboard" && onboard?.onboardProfileFormat?.writable) { return JSON.stringify(await withLogitechClient(info, `profile ${action}`, async (client: any) => { client.profileFormatId ??= onboard.onboardProfileFormat.id ?? null; const profile = (await client.readOnboardProfiles()).find((p: any) => p.isCurrent); if (!profile) throw new Error("Couldn't find the profile the mouse is running."); if (action === "liftOff") { const lod = ({ Low: 1, Medium: 2, High: 3 } as Record)[value]; if (!lod || !profile.dpiStages.some((stage: any) => stage.lod > 0)) throw new Error("This profile doesn't store a lift-off distance. Switch the mouse to host mode to change it."); const stages = profile.dpiStages.map((stage: any) => ({ ...stage, lod })); await client.writeActiveProfile({ sector: profile.sector, dpiStages: { stages, defaultIndex: Math.min(profile.defaultDpiIndex ?? 0, stages.length - 1) } }); return value; } if (action === "pollingRate") { const wired = onboard.connectionType === "Wired"; if (client.usbTransportId == null) { const firmware = await client.getFeature(0x0003); if (firmware.index) client.usbTransportId = (await client.readIdentity(firmware.index)).transportIds.USB ?? null; } await client.writeActiveProfile({ sector: profile.sector, [wired ? "reportRateWiredHz" : "reportRateWirelessHz"]: value }); } else { const [x, y] = typeof value === "number" ? [value, value] : [value.x, value.y]; const index = Math.min(profile.defaultDpiIndex ?? 0, profile.dpiStages.length - 1); if (index < 0) throw new Error("This profile has no DPI stages."); const stages = profile.dpiStages.map((stage: any, i: number) => (i === index ? { ...stage, x: Math.round(x), y: Math.round(y) } : stage)); await client.writeActiveProfile({ sector: profile.sector, dpiStages: { stages, defaultIndex: index } }); } await client.setCurrentProfile(profile.sector); return typeof value === "number" ? value : Math.round(value.x ?? value); })); } switch (action) { case "dpi": { const has = (method: string) => (lastStatus.get(key)?.methods ?? []).includes(method); // Incott keeps the axes apart only through its own setter. if (typeof value !== "number" && has("setAxisDpi")) { await genericCall(info, "setAxisDpi", Math.round(value.x), Math.round(value.y)); return JSON.stringify(Math.round(value.x)); } // The Instant A825 has no ordinary DPI setter. if (has("setLiveDpi") && !has("setDpi")) { const dpi = Math.round(typeof value === "number" ? value : value.x); await genericCall(info, "setLiveDpi", dpi); return JSON.stringify(dpi); } // A number moves both axes; {x, y} sets them apart (mice that report // separate axes, with X and Y unlinked). return JSON.stringify( typeof value === "number" ? await w.setDpi(info, Math.round(value)) : await w.setDpi(info, Math.round(value.x), Math.round(value.y)), ); } case "pollingRate": return JSON.stringify(await w.setPollingRate(info, value)); case "liftOff": return JSON.stringify(await w.setLiftOffDistance(info, value)); case "surface": return JSON.stringify(await w.setGamingSurfaceMode(info, value)); default: throw new Error(`Unknown action ${action}`); } }, };