// 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, 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, 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"; 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 } 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()); if (!lastStatus.get(key)?.magneticButtons?.liveDepth) 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); 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, key)); 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") { 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); // 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, }); 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"; 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) => { 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)); return value; } if (action === "stages") { await client.setProfileDpiStages(value); return value; } return await client.setOnboardMode(value === "Onboard" ? "Onboard" : "Host"); } 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.`); 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 { const { 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") { 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; 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.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)); } 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}`); } }, };