diff --git a/native-hid/README.md b/native-hid/README.md index ad38161..d4f1bc6 100644 --- a/native-hid/README.md +++ b/native-hid/README.md @@ -24,20 +24,46 @@ duplicated or reimplemented here. ## How dispatch works -`brands.mjs` maps a `MouseStatus.brand` string (Bridge's saved profile -`device.id` is `":"`, matching what the OpenMouse web app -writes) to that brand's HID vendor id(s) and its candidate driver class(es), -in the same order `mouse-protocol/src/drivers/registry.ts` tries them. - -`apply.mjs` doesn't replicate WebHID's report-descriptor-based -`isSupported()` auto-detection (this adapter reports `collections: []` — -real report-descriptor parsing isn't implemented). Instead, since Bridge -already knows the brand from the saved profile, it opens each HID interface -for that brand's vendor id(s) and tries each candidate class directly: -`client.open()` then `client.readStatus()` — a cheap, read-only call every -`SupportedClient` implements — as a probe. The first class that doesn't -throw is treated as correct, and `setDpi()`/`setPollingRate()` are called on -it. +Drivers are chosen the way the control panel chooses them: by +`@openmouse/protocol`'s own registry (`DEVICE_DRIVERS`, first `supports()` +match wins), so every brand the panel supports is covered, and a new brand +in the protocol package needs no change here. + +The registry's `supports()` checks need what WebHID gives the panel: each +device's collections, parsed from its report descriptors. node-hid cannot +read descriptors, so Bridge does it (`describe_devices` in `src/hid.rs`, the +same grouping and parser as the panel's own Bridge transport) and sends the +described devices with each request: + +1. Once per run, Bridge asks for the registry's `SUPPORTED_HID_FILTERS` + (`{"action": "filters"}`), the filters the panel requests devices with. + Bridge only ever opens a device one of them matches, and only to read its + descriptors, so hardware that shares a mouse maker's chip vendor id (a + motherboard's RGB controller, a touchpad) is never touched. +2. When the devices on the bus change, Bridge asks which brand the registry + files each under (`{"action": "identify", "devices": [...]}`). Those are + the mice it lists. +3. A status or apply request carries the described devices of that brand + (`"devices": [...]`). `registry.mjs` builds the registry's client for each + on a `DescribedDeviceAdapter`, which sends a report down only the + collection whose descriptor declares it, padded to the declared size as + Chrome does (Windows refuses a feature report of any other length), and + reads feature reports at their declared size. `client.open()` then + `client.readStatus()` — a cheap, read-only call every `SupportedClient` + implements — probe it before anything is written. When a profile's brand + is not the one the registry files its mouse under (`"Attack Shark"` saved + for hardware filed as `"Delux"`), Bridge sends `"matchStatusBrand": true` + and every supported device, and the helper keeps the one whose status + reports the brand. + +For a status read, `select-client.mjs` prefers a device whose status includes +a battery, so a receiver's battery-less interfaces never hide the mouse's. +Settings writes take the first device that answers. + +Without `devices` in the request (Node.js could not load the registry, or +Zaunkoenig's acknowledged automation, which identifies its endpoint by +node-hid path), the helper falls back to `brands.mjs`: a brand's vendor ids +and candidate classes, every interface tried in turn. The Attack Shark X11 family is the partial exception. Its settings channel is not visible through WebHID, so `apply.mjs` first checks for VID `0x1d57`, PIDs @@ -48,12 +74,10 @@ fall through to the generic `AttackSharkHidClient` path, which drives the 0x04 six-stage table for model `0x55` (mouse-protocol #174), preserving the stages the request does not touch. -A brand entry can also narrow which interfaces are opened: `productIds` keeps -only its own products on a shared vendor id, and `usagePage` opens only an -interface's collections on that page. The Scyrox entry uses both: CompX's -vendor id `0x3554` carries several brands, and the Scyrox V8's dongle stops -answering on its `0xff02` config collection on Windows while its sibling -vendor collections are open and read. +The Scyrox V8's dongle stops answering on its `0xff02` config collection on +Windows while its sibling vendor collections are open and read, so only that +collection is opened for Scyrox (`ONLY_USAGE_PAGE` in `registry.mjs`, and the +`usagePage` of its `brands.mjs` entry for the fallback). ## Button listener @@ -122,9 +146,9 @@ runtime first and falls back to `node` on `PATH`, so local development read 1,600 DPI and 2,000 Hz, while one on every interface-1 collection got no answer. The full `apply.mjs` path still needs a run on that mouse, and an `@openmouse/protocol` release with the V8 in its Scyrox catalog. -- Other adapter and dispatch paths are structurally tested (module resolution, - exit codes and control flow) and still require validation on their respective - hardware. -- G-Wolves is deliberately left out of `brands.mjs`: it isn't a finished, - exported driver in `mouse-protocol` yet (untracked source, no - `package.json` export, no `registry.ts` entry as of this writing). +- The registry path was hardware-verified on Windows with a Keychron G6 HE + 8K on its TurboLink 8K receiver (battery, DPI and polling read), an Endgame + Gear OP1 8k (DPI and polling read; its `0xa0` config report comes back with + `0x00` in the id slot), and a Wooting 60HE+ (identified and read). +- Other brands are covered by the registry's own `supports()` checks and the + adapter's tests, and still require validation on their hardware. diff --git a/native-hid/src/apply.mjs b/native-hid/src/apply.mjs index fbe9005..d3b2c35 100644 --- a/native-hid/src/apply.mjs +++ b/native-hid/src/apply.mjs @@ -41,6 +41,7 @@ import { BRAND_DRIVERS, brandKey } from "./brands.mjs"; import { applyX11PollingRate, x11DeviceInfos } from "./attack-shark-x11.mjs"; import { candidateDevices, probeVerifiedDevice } from "./hid-device-adapter.mjs"; import { selectClient } from "./select-client.mjs"; +import { identify, knowsBrand, loadRegistry, registryPairs } from "./registry.mjs"; import { devices } from "node-hid"; import { automate } from "./automation.mjs"; @@ -69,15 +70,18 @@ function withTimeout(promise, ms, label) { * the device) on any failure, so the caller can move on to the next * candidate. */ async function probe(device, candidate) { - const module = await import(candidate.module); - const Client = module[candidate.exportName]; - const client = new Client(device); + // Registry candidates come with their client built; brands.mjs ones name a + // class to import. + const client = candidate.client ?? new (await import(candidate.module))[candidate.exportName](device); try { await withTimeout(client.open(), PROBE_TIMEOUT_MS, `${candidate.exportName}.open()`); // Every SupportedClient implements readStatus() (mouse-protocol's // shared client contract) — a cheap, read-only way to confirm this is // really the right class for this interface before writing anything. const status = await withTimeout(client.readStatus(), PROBE_TIMEOUT_MS, `${candidate.exportName}.readStatus()`); + if (candidate.requireBrand !== undefined && brandKey(status?.brand ?? "") !== candidate.requireBrand) { + throw new Error(`reports itself as ${status?.brand ?? "an unknown brand"}`); + } return { client, status }; } catch (error) { await device.close().catch(() => undefined); @@ -87,6 +91,23 @@ async function probe(device, candidate) { async function main() { const input = JSON.parse(await readStdin()); + + // ── Device registry ───────────────────────────────────────────────── + // Bridge asks once for the filters that decide which devices it may open, + // then, whenever the devices on the bus change, which brand the registry + // files each of them under. + if (input.action === "filters") { + const { filters } = await loadRegistry(); + process.stdout.write(JSON.stringify({ filters })); + process.exit(EXIT_APPLIED); + } + if (input.action === "identify") { + const { drivers } = await loadRegistry(); + const described = Array.isArray(input.devices) ? input.devices : []; + process.stdout.write(JSON.stringify({ devices: identify(drivers, described) })); + process.exit(EXIT_APPLIED); + } + const brand = typeof input.brand === "string" ? input.brand : ""; const normalizedBrand = brandKey(brand); const entry = BRAND_DRIVERS[normalizedBrand]; @@ -98,7 +119,11 @@ async function main() { process.stdout.write(JSON.stringify(reply)); process.exit(EXIT_APPLIED); } - if (!entry) { + // With `devices`, Bridge described the bus and the registry picks the + // driver; without them (an older request shape) brands.mjs does. + const registry = Array.isArray(input.devices) ? await loadRegistry() : null; + const knownBrand = registry ? knowsBrand(registry.drivers, brand) || Boolean(entry) : Boolean(entry); + if (!knownBrand && !input.matchStatusBrand) { console.error(`[native-hid] no driver registered for brand "${brand}"`); process.exit(EXIT_NO_DRIVER); } @@ -116,11 +141,17 @@ async function main() { } } - const pairs = entry.vendorIds.flatMap((vendorId) => - candidateDevices(vendorId, entry).flatMap((device) => entry.classes.map((candidate) => ({ device, candidate }))), - ); + const pairs = registry + ? registryPairs(registry.drivers, input.devices, brand, { matchStatusBrand: input.matchStatusBrand === true }) + : entry.vendorIds.flatMap((vendorId) => + candidateDevices(vendorId, entry).flatMap((device) => entry.classes.map((candidate) => ({ device, candidate }))), + ); const { client, status, attempts } = await selectClient(pairs, probe, { preferBattery: input.action === "status" }); + if (!client && !knownBrand) { + console.error(`[native-hid] no device reports itself as ${brand}.`); + process.exit(EXIT_NO_DRIVER); + } if (!client) { console.error( `[native-hid] no ${brand} device answered.` + (attempts.length ? ` Tried:\n ${attempts.join("\n ")}` : " No matching HID interface was found."), diff --git a/native-hid/src/brands.mjs b/native-hid/src/brands.mjs index 56b8f7e..2537980 100644 --- a/native-hid/src/brands.mjs +++ b/native-hid/src/brands.mjs @@ -1,3 +1,8 @@ +// The fallback dispatch table. Bridge normally sends the devices it described +// and the protocol package's own registry picks the driver (registry.mjs); this +// table is used only for a request without them — when the registry could not +// be loaded, and for Zaunkoenig's acknowledged automation (automation.mjs). +// // Maps a MouseStatus `brand` string (mouse-protocol/src/drivers/mouse-types.ts) // to the HID vendor id(s) to enumerate and the candidate driver classes to // try constructing against each interface found, in the same order @@ -5,14 +10,9 @@ // that brand (first-match-wins there; here, first class whose open() + // readStatus() probe succeeds wins — see apply.mjs). // -// Deliberately excluded: -// - "Pulsar": Bridge has a dependency-free native Rust driver for it -// (src/drivers/pulsar.rs) that claims the brand before this helper is ever -// invoked — see src/drivers/mod.rs. -// - G-Wolves: not yet a finished, exported driver in the local mouse-protocol -// checkout (untracked src/g-wolves/, src/drivers/g-wolves/, no package.json -// export or registry.ts entry as of this writing) — add it here once it -// ships upstream. +// "Pulsar" is left out: Bridge has a dependency-free native Rust driver for it +// (src/drivers/pulsar.rs) that claims the brand before this helper is ever +// invoked — see src/drivers/mod.rs. // // Vendor ids are copied from mouse-protocol/src/drivers/vendors.ts and each // driver's own `isSupported()`; class import paths use the package's diff --git a/native-hid/src/hid-device-adapter.mjs b/native-hid/src/hid-device-adapter.mjs index f3dd408..2d82253 100644 --- a/native-hid/src/hid-device-adapter.mjs +++ b/native-hid/src/hid-device-adapter.mjs @@ -291,6 +291,157 @@ export function candidateDevices(vendorId, hints = {}, list = devices) { }); } +/** Whether Bridge parsed the path's descriptor: it declares some report. */ +function declaresReports(path) { + return ["inputReports", "outputReports", "featureReports"].some((kind) => Object.keys(path[kind] ?? {}).length > 0); +} + +/** A collection only the operating system may read: a standard mouse or + * keyboard (see candidateDevices()). */ +function isStandardOnly(path) { + return ( + path.collections.length > 0 && + path.collections.every((collection) => collection.usagePage === 1 && [1, 2, 6].includes(collection.usage)) + ); +} + +/** + * One device as Bridge described it (src/hid.rs, `DescribedDevice`): the + * WebHID view the control panel would get — the same grouping and the + * collections parsed from the report descriptors — plus each collection's + * path and the payload size of every report it declares. + * + * Unlike HidDeviceAdapter it sends a report down only the path whose + * descriptor declares it, padded to the declared size as Chrome's WebHID + * does (Windows refuses a feature report of the wrong length), and reads a + * feature report at its declared size. A path with no declared reports + * (Razer, whose descriptors Bridge does not read) gets HidDeviceAdapter's + * behaviour: any path, a generous read buffer. + */ +export class DescribedDeviceAdapter extends HidDeviceAdapter { + /** + * @param {object} described - one entry of the request's `devices`. + * @param {{ onlyUsagePage?: number, Handle?: typeof HID }} [options] - + * `onlyUsagePage` opens only the paths with a collection on that page, + * for receivers that stop answering while a sibling collection is read + * (Scyrox, see candidateDevices()). + */ + constructor(described, { onlyUsagePage, Handle = HID } = {}) { + const usable = described.paths.filter((path) => !isStandardOnly(path)); + const narrowed = + onlyUsagePage === undefined + ? usable + : usable.filter((path) => path.collections.some((collection) => collection.usagePage === onlyUsagePage)); + const paths = narrowed.length > 0 ? narrowed : usable; + super( + paths.map((path) => ({ + path: path.path, + vendorId: described.vendorId, + productId: described.productId, + product: described.productName, + })), + null, + Handle, + ); + this.vendorId = described.vendorId; + this.productId = described.productId; + this.productName = described.productName ?? ""; + this.collections = described.collections ?? []; + this._paths = paths; + /** Open handles, each with the path it belongs to. */ + this._open = []; + } + + async open() { + if (this.opened) return; + let lastError = null; + for (const path of this._paths) { + try { + const device = new this._Handle(path.path, OPEN_OPTIONS); + // Listening starts node-hid's read loop. On a path that declares + // reports but no input report (the OP1 8k's feature-only 0xff01 + // collection) Windows fails every read, and node-hid gives up on the + // handle, taking the feature reports down with it. + if (!declaresReports(path) || Object.keys(path.inputReports ?? {}).length > 0) { + device.on("data", this._onData); + } + device.on("error", this._onError); + this._open.push({ path, device }); + } catch (error) { + lastError = error; + } + } + if (this._open.length === 0) { + throw lastError ?? new Error("Could not open any HID device path"); + } + this._devices = this._open.map(({ device }) => device); + this.opened = true; + } + + async close() { + await super.close(); + this._open = []; + } + + async sendReport(reportId, data) { + this._send(reportId, data, "outputReports", (device, frame) => device.write(frame)); + } + + async sendFeatureReport(reportId, data) { + this._send(reportId, data, "featureReports", (device, frame) => device.sendFeatureReport(frame)); + } + + async receiveFeatureReport(reportId) { + this._requireOpen(); + const declaring = this._declaring(reportId, "featureReports"); + const targets = declaring.length > 0 ? declaring : this._open; + let lastError; + for (const { path, device } of targets) { + // The declared payload plus the id byte; 91 covers Razer's 90-byte + // reports where nothing is declared (see HidDeviceAdapter). + const length = declaring.length > 0 ? path.featureReports[reportId] + 1 : 91; + try { + const raw = Uint8Array.from(device.getFeatureReport(reportId, length)); + // A declared report's first byte is its id slot, whatever hidapi left + // in it (the OP1 8k's 0xa0 comes back as 0x00 on Windows), as Bridge's + // own transport treats it (`report_payload` in src/hid.rs). + const payload = + declaring.length > 0 || (raw.length > 1 && raw[0] === reportId) ? raw.subarray(1) : raw; + return new DataView(payload.buffer, payload.byteOffset, payload.byteLength); + } catch (error) { + lastError = error; + } + } + throw lastError ?? new Error("No HID interface answered the feature report request."); + } + + /** The open paths whose descriptor declares `reportId` of `kind`. */ + _declaring(reportId, kind) { + return this._open.filter(({ path }) => path[kind]?.[reportId] !== undefined); + } + + /** Sends to the first declaring path that takes the report (any path when + * none declares it), so a command reaches the device once. */ + _send(reportId, data, kind, write) { + this._requireOpen(); + const declaring = this._declaring(reportId, kind); + const targets = declaring.length > 0 ? declaring : this._open; + let lastError; + for (const { path, device } of targets) { + const frame = this._frame(reportId, data); + const declared = path[kind]?.[reportId]; + while (declared !== undefined && frame.length < declared + 1) frame.push(0); + try { + write(device, frame); + return; + } catch (error) { + lastError = error; + } + } + throw lastError ?? new Error("No HID interface accepted the report."); + } +} + export async function probeVerifiedDevice(info, identity, probe, Handle = HID) { const device = new HidDeviceAdapter([info], identity, Handle); try { diff --git a/native-hid/src/registry.mjs b/native-hid/src/registry.mjs new file mode 100644 index 0000000..48ef47c --- /dev/null +++ b/native-hid/src/registry.mjs @@ -0,0 +1,97 @@ +// Chooses drivers the way the control panel does: with @openmouse/protocol's +// own registry (`DEVICE_DRIVERS`, first `supports()` match wins), run against +// the devices Bridge described from their real report descriptors. +// +// Bridge only describes devices matching the registry's SUPPORTED_HID_FILTERS +// (the filters the panel requests devices with), and a driver is only used on +// a device its own `supports()` accepts — the same product-id and descriptor +// checks as in the browser — so nothing outside what OpenMouse itself would +// open is ever written to. +// +// The modules are imported lazily: loading the registry pulls in every driver, +// and apply.mjs must alias `window` before any of them load. + +import { DescribedDeviceAdapter } from "./hid-device-adapter.mjs"; + +/** Receivers that stop answering while a sibling collection is read: only + * the collection on this usage page is opened (see candidateDevices()). */ +const ONLY_USAGE_PAGE = { scyrox: 0xff02 }; + +export async function loadRegistry() { + const [{ DEVICE_DRIVERS }, { SUPPORTED_HID_FILTERS }] = await Promise.all([ + import("@openmouse/protocol/drivers/registry"), + import("@openmouse/protocol/drivers/vendors"), + ]); + return { drivers: DEVICE_DRIVERS, filters: SUPPORTED_HID_FILTERS }; +} + +export function brandKey(brand) { + return String(brand ?? "").trim().toLowerCase(); +} + +/** The registry entry that claims `device`, as `createSupportedClient` picks + * it: the first whose `supports()` accepts the device. */ +export function driverFor(drivers, device) { + return ( + drivers.find((driver) => { + try { + return driver.supports(device); + } catch { + return false; + } + }) ?? null + ); +} + +/** The WebHID-shaped view `supports()` checks: no paths, never opened. */ +function view(described) { + return { + vendorId: described.vendorId, + productId: described.productId, + productName: described.productName ?? "", + collections: described.collections ?? [], + opened: false, + }; +} + +/** The brand the registry files each described device under, or null for + * a device no driver claims. */ +export function identify(drivers, devices) { + return devices.map((described) => ({ + key: described.key, + brand: driverFor(drivers, view(described))?.brand ?? null, + })); +} + +/** + * The (device, client) pairs to try for a `brand` request, in the order + * Bridge listed the devices. Without `matchStatusBrand` only devices the + * registry files under `brand` are used; with it every claimed device is, + * and probe() keeps one whose own status reports `brand`. + */ +export function registryPairs(drivers, devices, brand, { matchStatusBrand = false, Adapter = DescribedDeviceAdapter } = {}) { + const wanted = brandKey(brand); + const pairs = []; + for (const described of devices) { + const driver = driverFor(drivers, view(described)); + if (!driver) continue; + if (!matchStatusBrand && brandKey(driver.brand) !== wanted) continue; + const device = new Adapter(described, { onlyUsagePage: ONLY_USAGE_PAGE[brandKey(driver.brand)] }); + const client = driver.create(device); + pairs.push({ + device, + candidate: { + exportName: client.constructor?.name || driver.brand, + client, + requireBrand: matchStatusBrand ? wanted : undefined, + }, + }); + } + return pairs; +} + +/** Whether the registry has a driver for `brand` at all. */ +export function knowsBrand(drivers, brand) { + const wanted = brandKey(brand); + return drivers.some((driver) => brandKey(driver.brand) === wanted); +} diff --git a/native-hid/src/registry.test.mjs b/native-hid/src/registry.test.mjs new file mode 100644 index 0000000..7b8287d --- /dev/null +++ b/native-hid/src/registry.test.mjs @@ -0,0 +1,195 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { EventEmitter } from "node:events"; + +import { DescribedDeviceAdapter } from "./hid-device-adapter.mjs"; +import { identify, knowsBrand, registryPairs } from "./registry.mjs"; + +/** A node-hid handle that records what is sent through it. */ +function fakeHandles({ failWrites = [] } = {}) { + const log = []; + class Handle extends EventEmitter { + constructor(path) { + super(); + this.path = path; + log.push(["open", path]); + } + write(frame) { + if (failWrites.includes(this.path)) throw new Error("refused"); + log.push(["write", this.path, frame]); + } + sendFeatureReport(frame) { + log.push(["feature", this.path, frame]); + } + getFeatureReport(id, length) { + log.push(["get", this.path, id, length]); + // Windows hands a numbered report back with 0 in the id slot. + return [0, ...Array.from({ length: length - 1 }, (_, index) => index + 1)]; + } + close() { + log.push(["close", this.path]); + } + } + return { Handle, log }; +} + +const collection = (usagePage, usage = 1) => ({ usagePage, usage, children: [], inputReports: [], outputReports: [], featureReports: [] }); + +function described(overrides = {}) { + return { + key: "hid-test", + vendorId: 0x3367, + productId: 0x1964, + productName: "Test Mouse", + collections: [collection(1, 2), collection(0xff01), collection(0xff02)], + paths: [ + { path: "mouse", collections: [collection(1, 2)], inputReports: {}, outputReports: {}, featureReports: {} }, + { path: "config", collections: [collection(0xff01)], inputReports: {}, outputReports: {}, featureReports: { 160: 1040, 161: 63 } }, + { path: "notify", collections: [collection(0xff02)], inputReports: { 9: 15 }, outputReports: { 9: 15 }, featureReports: {} }, + ], + ...overrides, + }; +} + +test("the standard mouse collection is never opened", async () => { + const { Handle, log } = fakeHandles(); + const device = new DescribedDeviceAdapter(described(), { Handle }); + await device.open(); + assert.deepEqual(log.filter(([kind]) => kind === "open").map(([, path]) => path), ["config", "notify"]); +}); + +test("only paths that declare input reports are listened on", async () => { + const { Handle } = fakeHandles(); + const device = new DescribedDeviceAdapter(described(), { Handle }); + await device.open(); + const listening = device._open.filter(({ device: handle }) => handle.listenerCount("data") > 0).map(({ path }) => path.path); + assert.deepEqual(listening, ["notify"]); +}); + +test("a feature report goes only down the path that declares it, padded to its size", async () => { + const { Handle, log } = fakeHandles(); + const device = new DescribedDeviceAdapter(described(), { Handle }); + await device.open(); + await device.sendFeatureReport(0xa1, new Uint8Array([1, 2, 3])); + const sent = log.filter(([kind]) => kind === "feature"); + assert.equal(sent.length, 1); + assert.equal(sent[0][1], "config"); + assert.equal(sent[0][2].length, 64, "the id byte plus the declared 63"); + assert.deepEqual(sent[0][2].slice(0, 4), [0xa1, 1, 2, 3]); +}); + +test("a feature report is read at its declared size and the id slot dropped", async () => { + const { Handle, log } = fakeHandles(); + const device = new DescribedDeviceAdapter(described(), { Handle }); + await device.open(); + const view = await device.receiveFeatureReport(0xa0); + assert.deepEqual(log.find(([kind]) => kind === "get"), ["get", "config", 0xa0, 1041]); + assert.equal(view.byteLength, 1040); + assert.equal(view.getUint8(0), 1, "the payload starts after the id slot, even though it held 0"); +}); + +test("an output report goes to the first declaring path that takes it, once", async () => { + const { Handle, log } = fakeHandles(); + const device = new DescribedDeviceAdapter(described(), { Handle }); + await device.open(); + await device.sendReport(9, new Uint8Array([7])); + const writes = log.filter(([kind]) => kind === "write"); + assert.equal(writes.length, 1); + assert.equal(writes[0][1], "notify"); + assert.equal(writes[0][2].length, 16); +}); + +test("a path without parsed descriptors takes any report, as before", async () => { + const { Handle, log } = fakeHandles(); + const razer = described({ + vendorId: 0x1532, + paths: [{ path: "razer", collections: [collection(0xff00)], inputReports: {}, outputReports: {}, featureReports: {} }], + }); + const device = new DescribedDeviceAdapter(razer, { Handle }); + await device.open(); + await device.sendFeatureReport(0, new Uint8Array([1, 2])); + assert.deepEqual(log.find(([kind]) => kind === "feature")[2], [0, 1, 2], "no padding without a declared size"); + await device.receiveFeatureReport(0); + assert.equal(log.find(([kind]) => kind === "get")[3], 91); + assert.equal(device._open[0].device.listenerCount("data"), 1); +}); + +test("onlyUsagePage narrows the opened paths", async () => { + const { Handle, log } = fakeHandles(); + const device = new DescribedDeviceAdapter(described(), { Handle, onlyUsagePage: 0xff02 }); + await device.open(); + assert.deepEqual(log.filter(([kind]) => kind === "open").map(([, path]) => path), ["notify"]); +}); + +// A stand-in registry: the real one's supports() checks are exercised by +// apply.mjs against hardware; these pin how Bridge uses the answers. +class FakeClient { + constructor(device) { + this.device = device; + } +} +const drivers = [ + { brand: "Endgame Gear", supports: (device) => device.vendorId === 0x3367 && device.collections.some((c) => c.usagePage === 0xff01), create: (device) => new FakeClient(device) }, + { brand: "Keychron", supports: (device) => device.vendorId === 0x3434, create: (device) => new FakeClient(device) }, + { brand: "Broken", supports: () => { throw new Error("bad descriptor"); }, create: () => null }, +]; + +test("identify gives each device the first claiming driver's brand, or null", () => { + const devices = [ + described({ key: "egg" }), + described({ key: "egg-mouse-only", collections: [collection(1, 2)] }), + described({ key: "kc", vendorId: 0x3434 }), + described({ key: "msi", vendorId: 0x1462 }), + ]; + assert.deepEqual(identify(drivers, devices), [ + { key: "egg", brand: "Endgame Gear" }, + { key: "egg-mouse-only", brand: null }, + { key: "kc", brand: "Keychron" }, + { key: "msi", brand: null }, + ]); +}); + +test("a brand request uses only that brand's devices", () => { + const { Handle } = fakeHandles(); + class Adapter extends DescribedDeviceAdapter { + constructor(device, options) { + super(device, { ...options, Handle }); + } + } + const devices = [described({ key: "egg" }), described({ key: "kc", vendorId: 0x3434 })]; + const pairs = registryPairs(drivers, devices, "keychron", { Adapter }); + assert.equal(pairs.length, 1); + assert.equal(pairs[0].device.vendorId, 0x3434); + assert.equal(pairs[0].candidate.exportName, "FakeClient"); + assert.equal(pairs[0].candidate.requireBrand, undefined); +}); + +test("matching on the status brand offers every claimed device", () => { + const { Handle } = fakeHandles(); + class Adapter extends DescribedDeviceAdapter { + constructor(device, options) { + super(device, { ...options, Handle }); + } + } + const devices = [described({ key: "egg" }), described({ key: "kc", vendorId: 0x3434 }), described({ key: "msi", vendorId: 0x1462 })]; + const pairs = registryPairs(drivers, devices, "Attack Shark", { matchStatusBrand: true, Adapter }); + assert.equal(pairs.length, 2); + assert.ok(pairs.every(({ candidate }) => candidate.requireBrand === "attack shark")); +}); + +test("every helper script parses", async () => { + // apply.mjs and the other entry points run main() on import, so no test + // loads them; a syntax error there would otherwise only show in Bridge. + const { readdirSync } = await import("node:fs"); + const { spawnSync } = await import("node:child_process"); + const directory = new URL(".", import.meta.url); + for (const file of readdirSync(directory).filter((name) => name.endsWith(".mjs"))) { + const result = spawnSync(process.execPath, ["--check", new URL(file, directory).pathname.replace(/^\/([A-Za-z]:)/, "$1")]); + assert.equal(result.status, 0, `${file}: ${result.stderr}`); + } +}); + +test("knowsBrand ignores case", () => { + assert.ok(knowsBrand(drivers, "endgame gear")); + assert.ok(!knowsBrand(drivers, "Lamzu")); +}); diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs index de8cd24..90f6671 100644 --- a/src/drivers/mod.rs +++ b/src/drivers/mod.rs @@ -29,6 +29,7 @@ pub mod delux; mod lamzu; mod native_hid; pub mod pulsar; +mod registry; pub use native_hid::{NativeBattery, NativeStatus, spawn_button_listener}; @@ -45,6 +46,9 @@ pub struct DetectedMouse { pub product_id: u16, } +/// Discovery's fallback for when the protocol registry cannot be loaded (see +/// [`detect_mice`]), and the brand prefixes [`brand_in_name`] recognises. +/// /// Brand keys and vendor ids, mirroring the helper's `native-hid/src/brands.mjs` /// (the same drivers the web panel drives, and the same normalization /// `apply.mjs` gives `device.id` prefixes: trim + lowercase). When several @@ -141,13 +145,58 @@ fn discovered_brand(info: &hidapi::DeviceInfo) -> Option<&'static str> { .map(|(brand, _)| *brand) } -/// Every HID interface on the bus whose vendor id belongs to a brand with a -/// Bridge driver, deduplicated to one entry per physical mouse (several -/// interfaces share the same vendor/product/serial). +/// Every mouse on the bus Bridge can drive, one entry per physical mouse. /// -/// Deliberately does not open any device — enumeration only — so it is safe -/// to call while a web panel session or another driver operation runs. +/// Which devices are mice, and their brands, comes from the control panel's +/// own driver registry (see `registry`). A device is opened only the first +/// time it appears, to read its report descriptors, and only if it matches +/// the registry's filters. When the registry cannot be reached (no Node.js), +/// discovery falls back to Bridge's vendor-id table. pub fn detect_mice() -> Vec { + let Some(devices) = registry::devices() else { + return detect_by_vendor(); + }; + let mut mice = mice_from_registry(devices); + // Pulsar has a Rust driver of its own, which reads models the registry + // may not list; those are still found by vendor id. + for mouse in detect_by_vendor() { + if mouse.vendor_id == pulsar::VENDOR_ID + && !mice.iter().any(|known| { + known.vendor_id == mouse.vendor_id && known.product_id == mouse.product_id + }) + { + mice.push(mouse); + } + } + mice +} + +fn mice_from_registry(devices: Vec<(crate::hid::DescribedDevice, String)>) -> Vec { + let mut mice: Vec = Vec::new(); + for (device, brand) in devices { + let tail = identity_tail(&(device.vendor_id, device.product_id, device.serial.as_str())); + let device_id = format!("{brand}:{tail}"); + // Without a serial, Windows lists each interface of a mouse as its + // own device; they are one mouse. + if mice.iter().any(|mouse| mouse.device_id == device_id) { + continue; + } + mice.push(DetectedMouse { + device_id, + name: product_name(&device.product_name, &brand), + vendor_id: device.vendor_id, + product_id: device.product_id, + }); + } + mice +} + +/// Every HID interface on the bus whose vendor id belongs to a brand in +/// [`KNOWN_BRANDS`], deduplicated to one entry per physical mouse (several +/// interfaces share the same vendor/product/serial). +/// +/// Enumeration only, no device is opened. +fn detect_by_vendor() -> Vec { let api = match crate::hid::new_api() { Ok(api) => api, Err(error) => { @@ -286,10 +335,10 @@ pub fn apply_profile(profile: &ApplicationProfile) -> Result { if delux::apply(profile)? { Ok(true) } else { - native_hid::apply(profile) + native_hid::apply(profile, registry::devices_for(&brand).as_ref()) } } - _ => native_hid::apply(profile), + _ => native_hid::apply(profile, registry::devices_for(&brand).as_ref()), } } @@ -344,7 +393,7 @@ pub fn read_status(device_id: &str) -> Result> { { return Ok(Some(status)); } - native_hid::read_status(brand) + native_hid::read_status(brand, registry::devices_for(brand).as_ref()) } /// local Bridge. Native-only devices use this path when WebHID cannot access @@ -353,13 +402,41 @@ pub fn apply_settings(brand: &str, dpi: Option, polling_rate_hz: Option = mice.iter().map(|mouse| mouse.device_id.as_str()).collect(); + assert_eq!(ids, ["Keychron:F5156C34962F36D9", "Endgame Gear:3367:1964"]); + assert_eq!(mice[1].name, "Endgame Gear Mouse"); + } fn profile(device_id: &str) -> ApplicationProfile { ApplicationProfile { diff --git a/src/drivers/native_hid.rs b/src/drivers/native_hid.rs index 2715b34..3599587 100644 --- a/src/drivers/native_hid.rs +++ b/src/drivers/native_hid.rs @@ -24,15 +24,48 @@ use crate::config::ApplicationProfile; /// per-candidate probe timeouts (a few seconds each, for a handful of HID /// interfaces at most). const HELPER_TIMEOUT: Duration = Duration::from_secs(10); -const HELPER_INPUT_LIMIT: usize = 4096; +/// Room for the described devices a request carries (their parsed +/// collections run to a few KiB each). +const HELPER_INPUT_LIMIT: usize = 1024 * 1024; const HELPER_OUTPUT_LIMIT: usize = 64 * 1024; const EXIT_OK: i32 = 0; const EXIT_NO_DRIVER: i32 = 3; +/// The devices a request may use, as Bridge described them (see +/// `drivers::registry`). Without them the helper falls back to its own +/// vendor table. +#[derive(Clone, Debug, Default)] +pub(crate) struct Devices { + pub described: Vec, + /// None of the devices is filed under the requested brand: the helper + /// keeps one whose own status reports the brand. + pub match_status_brand: bool, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct Target<'a> { + #[serde(skip_serializing_if = "Option::is_none")] + devices: Option<&'a [crate::hid::DescribedDevice]>, + #[serde(skip_serializing_if = "std::ops::Not::not")] + match_status_brand: bool, +} + +impl<'a> Target<'a> { + fn of(devices: Option<&'a Devices>) -> Self { + Self { + devices: devices.map(|devices| devices.described.as_slice()), + match_status_brand: devices.is_some_and(|devices| devices.match_status_brand), + } + } +} + #[derive(Serialize)] struct ApplyRequest<'a> { brand: &'a str, + #[serde(flatten)] + target: Target<'a>, #[serde(skip_serializing_if = "Option::is_none")] dpi: Option, #[serde(skip_serializing_if = "Option::is_none", rename = "pollingRateHz")] @@ -48,6 +81,8 @@ struct ApplyRequest<'a> { struct StatusRequest<'a> { brand: &'a str, action: &'static str, + #[serde(flatten)] + target: Target<'a>, } /// The battery fields of `mouse-protocol`'s `MouseStatus`, as `apply.mjs` @@ -107,21 +142,27 @@ fn coerce_dpi(value: Option<&serde_json::Value>) -> Option { /// no driver for this brand (most devices are still driven by the OpenMouse /// web app over WebHID instead), and `Err` when a driver exists but the /// apply itself failed (including the helper or Node.js being unavailable). -pub fn apply(profile: &ApplicationProfile) -> Result { +pub fn apply(profile: &ApplicationProfile, devices: Option<&Devices>) -> Result { let brand = profile.device.id.split(':').next().unwrap_or_default(); apply_settings_with_snapshot( brand, profile.settings.dpi, profile.settings.polling_rate_hz, profile.settings.snapshot.as_ref(), + devices, ) } /// Pushes an explicit settings request from the local HTTP API. This shares /// the exact helper path used by automatic profiles, so native device control /// and profile switching cannot drift into separate protocol implementations. -pub fn apply_settings(brand: &str, dpi: Option, polling_rate_hz: Option) -> Result { - apply_settings_with_snapshot(brand, dpi, polling_rate_hz, None) +pub fn apply_settings( + brand: &str, + dpi: Option, + polling_rate_hz: Option, + devices: Option<&Devices>, +) -> Result { + apply_settings_with_snapshot(brand, dpi, polling_rate_hz, None, devices) } fn apply_settings_with_snapshot( @@ -129,9 +170,11 @@ fn apply_settings_with_snapshot( dpi: Option, polling_rate_hz: Option, settings: Option<&serde_json::Value>, + devices: Option<&Devices>, ) -> Result { let request = ApplyRequest { brand, + target: Target::of(devices), dpi, polling_rate_hz, settings, @@ -142,10 +185,11 @@ fn apply_settings_with_snapshot( /// Reads a `brand` mouse's status via the Node helper. `Ok(None)` means /// the helper has no driver for the brand or the mouse reports no battery /// (a wired mouse); `Err` means a driver exists but no mouse answered. -pub fn read_status(brand: &str) -> Result> { +pub fn read_status(brand: &str, devices: Option<&Devices>) -> Result> { let request = StatusRequest { brand, action: "status", + target: Target::of(devices), }; let Some(stdout) = run_helper(&request)? else { return Ok(None); diff --git a/src/drivers/registry.rs b/src/drivers/registry.rs new file mode 100644 index 0000000..d1df1a8 --- /dev/null +++ b/src/drivers/registry.rs @@ -0,0 +1,245 @@ +//! Which devices on the bus are mice Bridge can drive, and which brand each +//! is, decided by `@openmouse/protocol`'s own driver registry — the same +//! `supports()` checks the control panel runs in the browser — rather than a +//! vendor-id table of Bridge's own. +//! +//! Bridge describes the bus (`hid::describe_devices`: grouped devices with +//! collections parsed from their report descriptors, as WebHID would give the +//! panel) and asks the Node helper once which registry driver claims each. +//! Only devices matching the registry's `SUPPORTED_HID_FILTERS` (the filters +//! the panel requests devices with) are ever opened, so a motherboard RGB +//! controller or a touchpad sharing a mouse maker's chip vendor id is never +//! touched. +//! +//! When the helper cannot be reached (Node.js missing), every function here +//! returns `None` and the callers fall back to the vendor-id table in +//! `drivers/mod.rs`. + +use std::{ + collections::HashMap, + sync::Mutex, + time::{Duration, Instant}, +}; + +use serde::Deserialize; + +use crate::hid::{DescribedDevice, HidFilter}; + +use super::native_hid; + +/// How long a failed helper call is remembered before it is tried again, so +/// a missing Node.js does not cost a process spawn on every 5 s scan. +const RETRY_AFTER: Duration = Duration::from_secs(60); + +/// The registry's device filters, fetched once. +static FILTERS: Mutex>>> = Mutex::new(None); + +/// The brand of each described device, for the set of devices last seen. +static IDENTIFIED: Mutex> = Mutex::new(None); + +enum Cached { + Ready(T), + Failed(Instant), +} + +struct Identified { + /// The device keys and whether each was fully described, sorted: when this + /// changes the devices are identified again. + signature: Vec<(String, bool)>, + outcome: Cached>, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct FiltersReply { + filters: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct IdentifyReply { + devices: Vec, +} + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct IdentifiedDevice { + key: String, + brand: Option, +} + +fn filters() -> Option> { + // Unit tests drive the helper through fakes that know nothing of the + // registry, so they run against the vendor-id table. + if cfg!(test) && std::env::var_os("OPENMOUSE_LIVE_REGISTRY").is_none() { + return None; + } + let mut cached = FILTERS + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + match &*cached { + Some(Cached::Ready(filters)) => return Some(filters.clone()), + Some(Cached::Failed(at)) if at.elapsed() < RETRY_AFTER => return None, + _ => {} + } + let fetched = + native_hid::run_helper(&serde_json::json!({ "action": "filters" })).and_then(|stdout| { + let stdout = stdout.ok_or_else(|| anyhow::anyhow!("the helper has no registry"))?; + Ok(serde_json::from_slice::(&stdout)?.filters) + }); + match fetched { + Ok(filters) => { + *cached = Some(Cached::Ready(filters.clone())); + Some(filters) + } + Err(error) => { + tracing::warn!(%error, "Could not load the device registry; using Bridge's vendor list"); + *cached = Some(Cached::Failed(Instant::now())); + None + } + } +} + +/// Every supported device on the bus with the brand the registry gives it. +pub(super) fn devices() -> Option> { + let filters = filters()?; + let described = crate::hid::describe_devices(&filters) + .map_err(|error| tracing::debug!(%error, "Could not describe HID devices")) + .ok()?; + let brands = identify(&described)?; + Some( + described + .into_iter() + .filter_map(|device| { + let brand = brands.get(&device.key)?.clone(); + Some((device, brand)) + }) + .collect(), + ) +} + +fn identify(devices: &[DescribedDevice]) -> Option> { + let mut signature: Vec<(String, bool)> = devices + .iter() + .map(|device| (device.key.clone(), device.described_fully())) + .collect(); + signature.sort(); + let mut identified = IDENTIFIED + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()); + if let Some(previous) = &*identified + && previous.signature == signature + { + match &previous.outcome { + Cached::Ready(brands) => return Some(brands.clone()), + Cached::Failed(at) if at.elapsed() < RETRY_AFTER => return None, + Cached::Failed(_) => {} + } + } + let outcome = if devices.is_empty() { + Ok(HashMap::new()) + } else { + native_hid::run_helper(&serde_json::json!({ "action": "identify", "devices": devices })) + .and_then(|stdout| { + let stdout = stdout.ok_or_else(|| anyhow::anyhow!("the helper has no registry"))?; + Ok(brands_by_key(serde_json::from_slice(&stdout)?)) + }) + }; + let (cached, result) = match outcome { + Ok(brands) => (Cached::Ready(brands.clone()), Some(brands)), + Err(error) => { + tracing::warn!(%error, "Could not identify HID devices"); + (Cached::Failed(Instant::now()), None) + } + }; + *identified = Some(Identified { + signature, + outcome: cached, + }); + result +} + +fn brands_by_key(reply: IdentifyReply) -> HashMap { + reply + .devices + .into_iter() + .filter_map(|device| Some((device.key, device.brand?))) + .collect() +} + +/// The devices a `brand` request may use: those the registry gives that +/// brand. When none has it — a profile saved under the brand the driver +/// reports (`Attack Shark`) for hardware the registry files under another +/// (`Delux`) — every supported device is offered and the helper keeps the one +/// whose own status reports `brand`. `None` when the registry is unavailable. +pub(super) fn devices_for(brand: &str) -> Option { + let devices = devices()?; + let matching: Vec = devices + .iter() + .filter(|(_, registry_brand)| registry_brand.eq_ignore_ascii_case(brand)) + .map(|(device, _)| device.clone()) + .collect(); + Some(if matching.is_empty() { + native_hid::Devices { + described: devices.into_iter().map(|(device, _)| device).collect(), + match_status_brand: true, + } + } else { + native_hid::Devices { + described: matching, + match_status_brand: false, + } + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Lists the mice plugged in now and reads each, as Bridge's battery poll + /// does: `OPENMOUSE_LIVE_REGISTRY=1 cargo test live_mice -- --ignored --nocapture`. + #[test] + #[ignore = "reads the real HID bus; run by hand"] + fn live_mice() { + assert!( + std::env::var_os("OPENMOUSE_LIVE_REGISTRY").is_some(), + "set OPENMOUSE_LIVE_REGISTRY so the registry is used" + ); + for mouse in super::super::detect_mice() { + let status = super::super::read_status(&mouse.device_id); + println!("{} ({}): {status:?}", mouse.device_id, mouse.name); + } + } + + /// Writes what Bridge would send the helper for the devices plugged in + /// now to the file `OPENMOUSE_DUMP` names, for checking the helper against + /// real hardware: + /// `OPENMOUSE_DUMP=devices.json cargo test dump_live_bus -- --ignored`. + #[test] + #[ignore = "reads the real HID bus; run by hand"] + fn dump_live_bus() { + let stdout = native_hid::run_helper(&serde_json::json!({ "action": "filters" })) + .expect("the helper runs") + .expect("the helper has a registry"); + let filters = serde_json::from_slice::(&stdout) + .unwrap() + .filters; + let devices = crate::hid::describe_devices(&filters).unwrap(); + let path = std::env::var("OPENMOUSE_DUMP").expect("OPENMOUSE_DUMP names the output file"); + std::fs::write(path, serde_json::to_vec_pretty(&devices).unwrap()).unwrap(); + } + + #[test] + fn devices_the_registry_does_not_claim_have_no_brand() { + let reply: IdentifyReply = serde_json::from_str( + r#"{"devices":[{"key":"hid-34340d05a-1","brand":"Keychron"},{"key":"hid-14627c92-2","brand":null}]}"#, + ) + .unwrap(); + let brands = brands_by_key(reply); + assert_eq!( + brands.get("hid-34340d05a-1").map(String::as_str), + Some("Keychron") + ); + assert!(!brands.contains_key("hid-14627c92-2")); + } +} diff --git a/src/hid.rs b/src/hid.rs index a118429..73762a8 100644 --- a/src/hid.rs +++ b/src/hid.rs @@ -1400,31 +1400,8 @@ fn inspect_candidate( let mut collections = Vec::new(); let mut paths = Vec::with_capacity(unique_paths.len()); for path in unique_paths { - let parsed = inspect_descriptors - .then(|| { - api.open_path(&path).ok().and_then(|device| { - let mut descriptor = vec![0; MAX_REPORT_DESCRIPTOR_SIZE]; - let size = device.get_report_descriptor(&mut descriptor).ok()?; - parse_report_descriptor(&descriptor[..size]).ok() - }) - }) - .flatten(); - let layout = if let Some((mut path_collections, path_layout)) = parsed { - collections.append(&mut path_collections); - path_layout - } else { - collections.extend( - infos - .iter() - .filter(|info| info.path() == path.as_c_str()) - .map(|info| CollectionInfo { - usage_page: info.usage_page(), - usage: info.usage(), - ..CollectionInfo::default() - }), - ); - ReportLayout::default() - }; + let (mut path_collections, layout) = inspect_path(api, &path, infos, inspect_descriptors); + collections.append(&mut path_collections); paths.push(CandidatePath { path, layout }); } @@ -1444,6 +1421,230 @@ fn inspect_candidate( }) } +/// The collections and report layout of one path, parsed from its report +/// descriptor. When the descriptor is not read (`read_descriptor` false, as +/// for Razer) or cannot be, each collection the platform enumerated for the +/// path stands in with its usage page and usage only. +fn inspect_path( + api: &HidApi, + path: &CString, + infos: &[hidapi::DeviceInfo], + read_descriptor: bool, +) -> (Vec, ReportLayout) { + let parsed = read_descriptor + .then(|| { + api.open_path(path).ok().and_then(|device| { + let mut descriptor = vec![0; MAX_REPORT_DESCRIPTOR_SIZE]; + let size = device.get_report_descriptor(&mut descriptor).ok()?; + parse_report_descriptor(&descriptor[..size]).ok() + }) + }) + .flatten(); + parsed.unwrap_or_else(|| (enumerated_collections(infos, path), ReportLayout::default())) +} + +fn enumerated_collections(infos: &[hidapi::DeviceInfo], path: &CString) -> Vec { + infos + .iter() + .filter(|info| info.path() == path.as_c_str()) + .map(|info| CollectionInfo { + usage_page: info.usage_page(), + usage: info.usage(), + ..CollectionInfo::default() + }) + .collect() +} + +/// A device filter in the shape OpenMouse passes to +/// `navigator.hid.requestDevice` (`SUPPORTED_HID_FILTERS`): a device matches +/// when its vendor and product match and one of its top-level collections has +/// the usage page and usage, each part only when the filter names it. +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub(crate) struct HidFilter { + pub vendor_id: u16, + pub product_id: Option, + pub usage_page: Option, + pub usage: Option, +} + +impl HidFilter { + fn matches_product(&self, vendor_id: u16, product_id: u16) -> bool { + self.vendor_id == vendor_id && self.product_id.is_none_or(|id| id == product_id) + } + + fn matches_usage(&self, usage_page: u16, usage: u16) -> bool { + self.usage_page.is_none_or(|page| page == usage_page) + && self.usage.is_none_or(|id| id == usage) + } + + fn matches_info(&self, info: &hidapi::DeviceInfo) -> bool { + self.matches_product(info.vendor_id(), info.product_id()) + && self.matches_usage(info.usage_page(), info.usage()) + } + + fn matches_device(&self, device: &DescribedDevice) -> bool { + self.matches_product(device.vendor_id, device.product_id) + && device + .collections + .iter() + .any(|collection| self.matches_usage(collection.usage_page, collection.usage)) + } +} + +/// One device on the bus as the native helper sees it: what WebHID would give +/// the control panel for it (the same grouping and parsed collections as the +/// panel's own Bridge transport), plus the path of each of its collections and +/// the size of every report each declares, so the helper can send a report +/// down the path that declares it, sized the way Windows requires. +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +pub(crate) struct DescribedDevice { + pub key: String, + pub vendor_id: u16, + pub product_id: u16, + pub product_name: String, + collections: Vec, + paths: Vec, + /// For Bridge's own device ids only; the helper never sees serials. + #[serde(skip)] + pub serial: String, + /// False when the device was listed from enumeration alone, during a + /// control panel session, and its descriptors are still to be read. + #[serde(skip)] + complete: bool, +} + +impl DescribedDevice { + pub(crate) fn described_fully(&self) -> bool { + self.complete + } +} + +#[derive(Clone, Debug, Serialize)] +#[serde(rename_all = "camelCase")] +struct DescribedPath { + path: String, + collections: Vec, + /// Payload bytes (report id excluded) of each declared report, by id. + input_reports: std::collections::BTreeMap, + output_reports: std::collections::BTreeMap, + feature_reports: std::collections::BTreeMap, +} + +fn report_bytes(bits: &HashMap) -> std::collections::BTreeMap { + bits.iter() + .map(|(id, bits)| (*id, bits.div_ceil(8))) + .collect() +} + +/// Devices already described, by grouping key. A device is opened to read its +/// descriptors only when it first appears or its paths change, not on every +/// scan. +static DESCRIBED: Mutex, DescribedDevice>>> = Mutex::new(None); + +/// Every device on the bus that one of `filters` matches, described for the +/// native helper. Only matching collections' devices are opened, and only to +/// read their report descriptors; security keys and Logitech receiver child +/// nodes are left out, as the control panel's own listing leaves them out. +/// +/// While the control panel holds a session no device is opened: one that has +/// not been described yet is listed from enumeration alone (usage pages, no +/// reports) and described properly once the session ends. +pub(crate) fn describe_devices(filters: &[HidFilter]) -> Result, String> { + let api = new_api().map_err(|error| error.to_string())?; + let blocked = security_key_paths(&api); + let mut wanted = HashSet::new(); + let mut groups = std::collections::BTreeMap::, Vec>::new(); + for info in api.device_list() { + if blocked.contains(info.path()) || is_receiver_child(info.path()) { + continue; + } + let group = device_group_key(info); + if filters.iter().any(|filter| filter.matches_info(info)) { + wanted.insert(group.clone()); + } + groups.entry(group).or_default().push(info.clone()); + } + groups.retain(|group, _| wanted.contains(group)); + + let mut cache = DESCRIBED.lock().unwrap_or_else(PoisonError::into_inner); + let cache = cache.get_or_insert_with(HashMap::new); + cache.retain(|group, _| groups.contains_key(group)); + let may_open = !client_session_active(); + let mut described = Vec::with_capacity(groups.len()); + for (group, infos) in groups { + let paths: std::collections::BTreeSet = infos + .iter() + .map(|info| info.path().to_string_lossy().into_owned()) + .collect(); + let cached = cache.get(&group).filter(|device| { + device.paths.len() == paths.len() + && device.paths.iter().all(|path| paths.contains(&path.path)) + }); + let device = match cached { + Some(device) => device.clone(), + None => { + let device = describe_group(&api, &group, &infos, may_open); + if may_open { + cache.insert(group, device.clone()); + } + device + } + }; + if filters.iter().any(|filter| filter.matches_device(&device)) { + described.push(device); + } + } + Ok(described) +} + +fn describe_group( + api: &HidApi, + group: &[u8], + infos: &[hidapi::DeviceInfo], + open: bool, +) -> DescribedDevice { + let primary = &infos[0]; + let read_descriptor = open && primary.vendor_id() != RAZER_VENDOR_ID; + let mut seen = HashSet::new(); + let mut collections = Vec::new(); + let mut paths = Vec::new(); + for info in infos { + let path = info.path().to_owned(); + if !seen.insert(path.clone()) { + continue; + } + let (path_collections, layout) = inspect_path(api, &path, infos, read_descriptor); + collections.extend(path_collections.iter().cloned()); + paths.push(DescribedPath { + path: path.to_string_lossy().into_owned(), + collections: path_collections, + input_reports: report_bytes(&layout.input_bits), + output_reports: report_bytes(&layout.output_bits), + feature_reports: report_bytes(&layout.feature_bits), + }); + } + DescribedDevice { + key: stable_device_key(group), + vendor_id: primary.vendor_id(), + product_id: primary.product_id(), + product_name: infos + .iter() + .find_map(|info| info.product_string().filter(|name| !name.is_empty())) + .unwrap_or_default() + .to_owned(), + collections, + paths, + serial: infos + .iter() + .find_map(|info| info.serial_number().filter(|serial| !serial.is_empty())) + .unwrap_or_default() + .to_owned(), + complete: open, + } +} + #[derive(Clone, Default)] struct GlobalState { usage_page: u16, @@ -1799,8 +2000,58 @@ async fn send_json(socket: &mut impl HidSocket, value: &impl Serialize) -> Resul .map_err(|_| "HID socket send deadline exceeded; session disconnected".to_owned())? } +#[cfg(test)] +impl DescribedDevice { + /// A described device with one collection per `(usage_page, usage)`. + pub(crate) fn for_test( + key: &str, + vendor_id: u16, + product_id: u16, + serial: &str, + usages: &[(u16, u16)], + ) -> Self { + Self { + key: key.into(), + vendor_id, + product_id, + product_name: String::new(), + collections: usages + .iter() + .map(|(usage_page, usage)| CollectionInfo { + usage_page: *usage_page, + usage: *usage, + ..CollectionInfo::default() + }) + .collect(), + paths: Vec::new(), + serial: serial.into(), + complete: true, + } + } +} + #[cfg(test)] mod tests { + #[test] + fn a_filter_matches_a_device_by_product_and_any_collection_usage() { + use super::{DescribedDevice, HidFilter}; + let filter = |product_id, usage_page, usage| HidFilter { + vendor_id: 0x3434, + product_id, + usage_page, + usage, + }; + let receiver = + DescribedDevice::for_test("k", 0x3434, 0xd05a, "", &[(0x01, 0x02), (0xffc1, 0x01)]); + assert!(filter(Some(0xd05a), Some(0xffc1), Some(0x01)).matches_device(&receiver)); + assert!(filter(None, Some(0xffc1), None).matches_device(&receiver)); + assert!(filter(None, None, None).matches_device(&receiver)); + assert!(!filter(Some(0xd05b), None, None).matches_device(&receiver)); + assert!(!filter(None, Some(0xff0a), None).matches_device(&receiver)); + // The usage page and usage must be one collection's. + assert!(!filter(None, Some(0xffc1), Some(0x02)).matches_device(&receiver)); + } + #[test] fn device_keys_are_stable_and_never_carry_the_serial() { let receiver = grouped_device_key(0x046d, 0xc54d, b"/dev/hidraw2", Some("375D35803234"));