diff --git a/src/device/controller.ts b/src/device/controller.ts index a88462dc..3f5e6bdd 100644 --- a/src/device/controller.ts +++ b/src/device/controller.ts @@ -176,7 +176,7 @@ import { VENDOR_ID } from "@openmouse/protocol/drivers/vendors"; import { RAZER_PRODUCTS } from "@openmouse/protocol/razer-devices"; import { parsePreviewMode, previewsEnabled, type FixturePreviewMode, type KeyboardPreviewMode, type PreviewMode } from "./preview/preview-modes"; import { sleepLabel } from "./options"; -import { traitsFor } from "./traits"; +import { traitsFor, verifiedDeviceSettings } from "./traits"; import type { SlxStatus } from "./finalmouse-slx.ts"; import type { AnalogTuning, @@ -429,6 +429,8 @@ let lastDiagnosticError: string | null = null; let reconnectInFlight = false; let activationInProgress = false; let activationQueue: Promise = Promise.resolve(); +let x11ConnectionReadStarted = false; +let x11SettingsRead: Promise | null = null; let sidebarHidden = false; let interfaceSettingsOpen = false; let activeWorkspaceTab: WorkspaceTab = "overview"; @@ -2876,8 +2878,66 @@ export async function flashPendingChanges(): Promise { return flashStagedChanges(); } +/** Restore a hardware test's temporary setting even if the device lost its write acknowledgment. */ +export async function flashHardwareTestSetting(owner: GameProfileOwner | null, leg: { + currentRaw: unknown; + targetRaw: unknown; + stageTarget: () => void; + stageRestore: () => void; + read: (status: MouseStatus | null) => unknown; + isCancelled?: () => boolean; +}): Promise<"cancelled" | "changed" | "writeNotSent" | "writeUnconfirmed" | "restoreUnconfirmed" | "readbackMismatch" | "restored"> { + if (leg.isCancelled?.()) return "cancelled"; + const readVerified = (): unknown => leg.read(verifiedDeviceSettings(latestDeviceStatus)); + const baselineMatches = (): boolean => { + const status = verifiedDeviceSettings(latestDeviceStatus); + return status !== null && status.ui?.settingsReady !== false && leg.read(status) === leg.currentRaw; + }; + if (!isGameProfileOwner(owner) || settingInProgress || gameProfileDraft || hasPendingChanges() + || !baselineMatches()) return "changed"; + leg.stageTarget(); + const [temporary] = pendingChanges(); + if (!temporary) return "writeNotSent"; + + let targetDispatched = false; + const written = await flashStagedChanges(() => { + targetDispatched = !leg.isCancelled?.() && baselineMatches(); + return targetDispatched; + }).catch(() => "failed" as const); + if (!targetDispatched) { + if (isGameProfileOwner(owner) && pendingChanges().includes(temporary)) dropPendingChange(temporary.key); + if (leg.isCancelled?.()) { + if (isGameProfileOwner(owner)) setReadStatus(st("hw.stateStopped")); + return "cancelled"; + } + if (written === "failed") return "writeNotSent"; + if (isGameProfileOwner(owner)) setReadStatus(st("hw.testSettingsChanged")); + return "changed"; + } + const targetRead = readVerified() === leg.targetRaw; + if (!isGameProfileOwner(owner) || settingInProgress) return "restoreUnconfirmed"; + // The failed target may still be staged. Replace only this test's own edit. + const staged = pendingChanges(); + if (gameProfileDraft || staged.some((change) => change !== temporary)) { + if (staged.includes(temporary)) dropPendingChange(temporary.key); + return "restoreUnconfirmed"; + } + leg.stageRestore(); + const [restore] = pendingChanges(); + if (!restore || restore === temporary || restore.key !== temporary.key) { + if (restore === temporary) dropPendingChange(temporary.key); + return "restoreUnconfirmed"; + } + const restored = await flashPendingChanges().catch(() => "failed" as const); + if (restored !== "written" || !isGameProfileOwner(owner) || readVerified() !== leg.currentRaw) { + return "restoreUnconfirmed"; + } + if (written !== "written") return "writeUnconfirmed"; + return targetRead ? "restored" : "readbackMismatch"; +} + /** Writes every staged change. "Apply now" calls it directly to write a game profile draft. */ -async function flashStagedChanges(): Promise { +async function flashStagedChanges(canWrite?: () => boolean): Promise { const owner = getGameProfileOwner(); if (!owner) return "stale"; const batches = pendingChangeBatches(); @@ -2891,6 +2951,7 @@ async function flashStagedChanges(): Promise { pendingBusy = true; emit(); let written = 0; + let skipped = false; let failure: string | null = null; // HID++ replies are matched by feature and function only, so a profile read // still running in the background would take the write's sector reads and @@ -2922,6 +2983,10 @@ async function flashStagedChanges(): Promise { for (const change of group) recordDiagnosticCommand(change.command); }); if (!isGameProfileOwner(owner)) break; + if (canWrite?.() === false) { + skipped = true; + break; + } await writer.apply(); if (!isGameProfileOwner(owner)) break; batch(() => { @@ -2933,8 +2998,8 @@ async function flashStagedChanges(): Promise { recordDiagnosticError(error, st("ctl.unableFlash")); failure = error instanceof Error ? error.message : "Unable to flash the staged changes."; } - await flashPause(FLASH_SETTLE_MS); - const client = isGameProfileOwner(owner) ? activeSettingsClient() : null; + if (written || !skipped) await flashPause(FLASH_SETTLE_MS); + const client = !skipped && isGameProfileOwner(owner) ? activeSettingsClient() : null; const status = client ? await statusAfterWrite(client).catch(() => null) : null; if (status && isGameProfileOwner(owner)) applyStatus(status); endDeviceWrite(); @@ -2950,6 +3015,11 @@ async function flashStagedChanges(): Promise { pushToast("error", st("ctl.flashFailed"), failure); return written > 0 ? "partial" : "failed"; } + if (skipped) { + flashQueued = false; + pendingStatusText = null; + return "unchanged"; + } if (flashQueued) { flashQueued = false; if (hasPendingChanges()) { @@ -4038,6 +4108,8 @@ function clearActiveClients(): void { } gameProfileOwner = null; active = null; + x11ConnectionReadStarted = false; + x11SettingsRead = null; } /** Close and reset the keyboard view so no stale trigger data survives a switch. */ @@ -4539,6 +4611,7 @@ function activateClient(target: SupportedClient | KeyboardClient, autoConnect = } finally { activationInProgress = false; } + maybeLoadX11ConnectionSettings(); }); activationQueue = run.then(() => undefined, () => undefined); return run; @@ -5006,7 +5079,7 @@ export function cancelCustomDpi(dpi?: number): void { emit(); } -export function applyDpiValue(dpi: number): boolean { +export function applyDpiValue(dpi: number, options?: { force?: boolean }): boolean { if (!hasActiveClient() || !dpiOptions.includes(dpi)) return false; stageChange({ key: "dpi", @@ -5026,7 +5099,7 @@ export function applyDpiValue(dpi: number): boolean { apply: async () => { await requireClientMethod("setDpi", "DPI").setDpi(dpi); }, - }); + }, options); return true; } @@ -6672,7 +6745,7 @@ export function setProfileReportRate(link: "wireless" | "wired", hz: number): vo }); } -export function applyPollingRate(rate: number): void { +export function applyPollingRate(rate: number, options?: { force?: boolean }): void { if (!hasActiveClient()) return; // The slider only offers device-advertised rates (or RATE_STEPS_HZ); anything // else arrives from an imported profile key, so reject it before staging. @@ -6696,10 +6769,10 @@ export function applyPollingRate(rate: number): void { await requireClientMethod("setPollingRate", "the polling rate").setPollingRate(rate); } }, - }); + }, options); } -export function applyLiftOffDistance(lod: LiftOffLevel): void { +export function applyLiftOffDistance(lod: LiftOffLevel, options?: { force?: boolean }): void { if (!hasActiveClient()) return; stageChange({ key: "lift-off-distance", @@ -6713,7 +6786,7 @@ export function applyLiftOffDistance(lod: LiftOffLevel): void { apply: async () => { await requireClientMethod("setLiftOffDistance", "the lift-off distance").setLiftOffDistance(lod); }, - }); + }, options); } export function applyLiftOffMode(mode: "single" | "asymmetric"): void { @@ -6886,6 +6959,19 @@ export function toggleSleep(enabled: boolean): void { applyPulsarValue("sleep", enabled ? lastSleepSeconds : WLMOUSE_SLEEP_NEVER); } +export function applyDeepSleep(minutes: number): void { + if (latestDeviceStatus?.deepSleepMinutes == null) return; + const label = `${st("x11.deepSleep")} ${sleepLabel(minutes * 60, interfacePreferences.locale)}`; + stageChange({ + key: "deep-sleep", + label, + command: label, + progress: label, + preview: (status) => { status.deepSleepMinutes = minutes; }, + apply: () => callClientMethod("setDeepSleepTimeout", label, minutes), + }); +} + export function applyKeychronDynamicDpi(value: NonNullable["dynamicDpi"]>): void { if (!latestDeviceStatus?.keychronMouse?.dynamicDpi) return; const next = structuredClone(value); @@ -6922,6 +7008,72 @@ export async function refreshKeychronReceiver(): Promise { finally { refreshInProgress = false; } } +function maybeLoadX11ConnectionSettings(): void { + // A wireless receiver may identify the mouse after the first status read. + if (!x11ConnectionReadStarted && latestDeviceStatus?.ui?.x11AutoReadReady) { + void loadX11Settings(); + } +} + +export function loadX11Settings(): Promise { + if (x11SettingsRead) return x11SettingsRead; + const client = activeSettingsClient(); + if (!client || !("readX11Configuration" in client) || !latestDeviceStatus?.ui?.x11ConfigurationAvailable + || settingInProgress || activationInProgress || hasPendingChanges() || gameProfileDraft) return Promise.resolve(false); + const device = activeDevice; + const label = st("x11.loadSettings"); + const stillActive = (): boolean => x11SettingsRead === result && activeSettingsClient() === client && activeDevice === device; + const load = async (): Promise => { + const deadline = Date.now() + REFRESH_WAIT_TIMEOUT_MS; + while (refreshInProgress && stillActive() && Date.now() <= deadline) await wait(25); + if (!stillActive() || refreshInProgress || settingInProgress || activationInProgress + || hasPendingChanges() || gameProfileDraft) return false; + // Count the read attempt before sending reports, including if it times out. + x11ConnectionReadStarted = true; + refreshInProgress = true; + settingInProgress = true; + setReadStatus(label); + try { + const status = await client.readX11Configuration(); + if (!stillActive()) return false; + applyStatus(status); + return true; + } catch (error) { + if (stillActive()) { + // Earlier reports in a stopped scan can still contain valid settings. + const partial = await client.readStatus().catch(() => null); + if (stillActive()) { + if (partial) applyStatus(partial); + toastForError(label, error); + } + } + return false; + } finally { + refreshInProgress = false; + settingInProgress = false; + emit(); + } + }; + const request = async (): Promise => { + try { + if (!navigator.locks) return await load(); + return await navigator.locks.request("openmouse.x11-settings", { ifAvailable: true }, async (lock) => { + if (lock) return load(); + if (stillActive()) setReadStatus(st("ctl.waitRefresh")); + return false; + }); + } catch (error) { + if (stillActive()) toastForError(label, error); + return false; + } + }; + const result = Promise.resolve().then(request).finally(() => { + if (x11SettingsRead === result) x11SettingsRead = null; + }); + x11SettingsRead = result; + return result; +} + export function applyKeychronReceiverLighting(value: MouseLighting): void { if (!latestDeviceStatus?.keychronReceiver) return; const next = structuredClone(value); @@ -8123,6 +8275,47 @@ export function incottMacroDeviceKey(): string | null { return activeDevice ? receiverKey(activeDevice) : null; } +export function applyX11Macro( + button: string, + name: string, + events: readonly { usage: number; down: boolean; delayMs: number }[], + playback: number, + repeats: number, +): void { + if (!latestDeviceStatus?.ui?.x11MacroBindings || !activeDevice || gameProfileDraft) return; + const device = activeDevice; + const steps = events.map((event) => ({ ...event })); + const label = `${displayText(interfacePreferences.locale, button)} → ${name}`; + stageChange({ + key: `button-${button}`, + label, + command: label, + progress: label, + preview: (status) => { if (status.buttonMappings) status.buttonMappings[button] = "Macro"; }, + apply: async () => { + if (activeDevice !== device) throw new Error(st("ctl.gone")); + await requireClientMethod("assignX11Macro", "the X11 macro").assignX11Macro(button, steps, playback, repeats, name); + }, + }, { force: true }); +} + +export function applyX11Shortcut(button: string, modifiers: number, usage: number, shortcut: string): void { + if (!latestDeviceStatus?.ui?.x11MacroBindings || !activeDevice || gameProfileDraft) return; + const device = activeDevice; + const label = `${button}: ${shortcut}`; + stageChange({ + key: `button-${button}`, + label, + command: label, + progress: label, + preview: (status) => { if (status.buttonMappings) status.buttonMappings[button] = shortcut; }, + apply: async () => { + if (activeDevice !== device) throw new Error(st("ctl.gone")); + await requireClientMethod("setX11KeyboardShortcut", "the X11 keyboard shortcut").setX11KeyboardShortcut(button, modifiers, usage); + }, + }); +} + /** * Incott's 2.4 GHz receiver LED (0 connect & polling rate, 1 battery status, * 2 battery warning). Wireless only — the driver omits the field entirely @@ -8284,6 +8477,7 @@ async function refreshStatus(): Promise { } finally { refreshInProgress = false; } + maybeLoadX11ConnectionSettings(); } async function loadPreviewEntries(): Promise { diff --git a/src/device/profile-write-ownership.test.ts b/src/device/profile-write-ownership.test.ts index eca010b9..d1392efb 100644 --- a/src/device/profile-write-ownership.test.ts +++ b/src/device/profile-write-ownership.test.ts @@ -5,9 +5,14 @@ import vm from "node:vm"; import ts from "typescript"; import * as pending from "./pending-changes.ts"; import * as snapshots from "./game-profile-snapshot.ts"; +import * as traits from "./traits.ts"; function controllerHarness() { pending.clearPendingChanges(); + let now = Date.now(); + class TestDate extends Date { + static now(): number { return now; } + } const timers: (() => void)[] = []; const exports: any = {}; const mocks = new Map(); @@ -15,12 +20,14 @@ function controllerHarness() { export function testSelect(client) { clearActiveClients(); clearPendingChanges(); active = client; activeDevice = client.device; latestDeviceStatus = { name: "Same model", dpi: 800, pollingRateHz: 1000, supportedPollingRates: [500,1000] }; dpiOptions = [800,1200,1600,3200]; } export function testDisconnect() { clearActiveClients(); clearPendingChanges(); activeDevice = null; latestDeviceStatus = null; } export function testReading(value) { refreshInProgress = value; } +export function testReport(patch) { latestDeviceStatus = { ...latestDeviceStatus, ...patch }; } `; const code = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText; const localStorage = { getItem: () => null }; - const context = { exports, structuredClone, __BUILD_CHANNEL__: "stable", __BUILD_ID__: "test", __APP_VERSION__: "test", localStorage, window: { localStorage, setTimeout: (callback: () => void) => { timers.push(callback); return 1; }, clearTimeout() {} }, setTimeout, clearTimeout, console, require: (name: string) => { + const context = { exports, structuredClone, Date: TestDate, __BUILD_CHANNEL__: "stable", __BUILD_ID__: "test", __APP_VERSION__: "test", localStorage, window: { localStorage, setTimeout: (callback: () => void) => { timers.push(callback); return 1; }, clearTimeout() {} }, setTimeout, clearTimeout, console, require: (name: string) => { if (name.endsWith("pending-changes")) return pending; if (name.endsWith("game-profile-snapshot")) return snapshots; + if (name.endsWith("/traits")) return traits; if (name.endsWith("interface-preferences")) return { loadInterfacePreferences: () => ({ locale: "en", reducedMotion: false }) }; if (name.endsWith("i18n/index")) return { t: (_locale: string, key: string) => key, tp: (_locale: string, key: string) => key }; if (!mocks.has(name)) mocks.set(name, new Proxy({}, { get: (target: any, key) => target[key] ??= function () {} })); @@ -30,7 +37,7 @@ export function testReading(value) { refreshInProgress = value; } const a = { device: {}, readStatus: async () => { throw new Error("fake read denied"); } }; const b = { device: {}, readStatus: async () => { throw new Error("fake read denied"); } }; exports.testSelect(a); - return { control: exports, a, b, timers, async drain() { for (let i = 0; i < 30; i++) { timers.splice(0).forEach((callback) => callback()); await Promise.resolve(); } } }; + return { control: exports, a, b, timers, advance(ms: number) { now += ms; }, async drain() { for (let i = 0; i < 30; i++) { timers.splice(0).forEach((callback) => callback()); await Promise.resolve(); } } }; } test("an abandoned profile write never restores A's staged edits into B", async () => { @@ -53,6 +60,125 @@ test("controller owner tokens change across an A/B/A session switch", () => { assert.equal(h.control.isGameProfileOwner(first), false); }); +test("hardware test restores a target accepted before its acknowledgment failed", async () => { + const h = controllerHarness(); + const writes: number[] = []; + Object.assign(h.a, { setDpi: async (dpi: number) => { + writes.push(dpi); + if (dpi === 1600) throw new Error("Acknowledgment timed out after applying DPI"); + } }); + const running = h.control.flashHardwareTestSetting(h.control.getGameProfileOwner(), { + currentRaw: 800, + targetRaw: 1600, + stageTarget: () => h.control.applyDpiValue(1600), + stageRestore: () => h.control.applyDpiValue(800, { force: true }), + read: (status: { dpi: number } | null) => status?.dpi, + }); + await h.drain(); + assert.equal(await running, "writeUnconfirmed"); + assert.deepEqual(writes, [1600, 800]); + assert.deepEqual(pending.pendingChanges(), []); +}); + +test("hardware test skips unverified defaults even when the settings panel is ready", async () => { + const h = controllerHarness(); + h.control.testReport({ ui: { settingsReady: true, valuesVerified: false } }); + const result = await h.control.flashHardwareTestSetting(h.control.getGameProfileOwner(), { + currentRaw: 800, + targetRaw: 1600, + stageTarget: () => assert.fail("the settings are unverified"), + stageRestore: () => assert.fail("nothing was written"), + read: (status: { dpi: number } | null) => status?.dpi, + }); + assert.equal(result, "changed"); + assert.deepEqual(pending.pendingChanges(), []); +}); + +for (const waitingFor of ["a refresh", "the flash pause"]) { + test(`hardware test skips its write when the device baseline changes during ${waitingFor}`, async () => { + const h = controllerHarness(); + Object.assign(h.a, { setDpi: async () => assert.fail("the original DPI changed") }); + h.control.testReading(waitingFor === "a refresh"); + const running = h.control.flashHardwareTestSetting(h.control.getGameProfileOwner(), { + currentRaw: 800, + targetRaw: 1600, + stageTarget: () => h.control.applyDpiValue(1600), + stageRestore: () => assert.fail("nothing was written"), + read: (status: { dpi: number } | null) => status?.dpi, + }); + assert.equal(pending.pendingChangeCount(), 1); + h.control.testReport({ dpi: 1200 }); + h.control.testReading(false); + await h.drain(); + assert.equal(await running, "changed"); + assert.deepEqual(pending.pendingChanges(), []); + }); +} + +test("hardware test reports a refresh timeout before any write was sent", async () => { + const h = controllerHarness(); + const writes: number[] = []; + Object.assign(h.a, { setDpi: async (dpi: number) => { writes.push(dpi); } }); + h.control.testReading(true); + const running = h.control.flashHardwareTestSetting(h.control.getGameProfileOwner(), { + currentRaw: 800, + targetRaw: 1600, + stageTarget: () => h.control.applyDpiValue(1600), + stageRestore: () => h.control.applyDpiValue(800, { force: true }), + read: (status: { dpi: number } | null) => status?.dpi, + }); + h.advance(5001); + await h.drain(); + assert.equal(await running, "writeNotSent"); + assert.deepEqual(writes, []); + assert.deepEqual(pending.pendingChanges(), []); +}); + +for (const cancelAfterDispatch of [false, true]) { + test(`hardware test handles cancellation ${cancelAfterDispatch ? "after" : "before"} write dispatch`, async () => { + const h = controllerHarness(); + let cancelled = false; + const writes: number[] = []; + Object.assign(h.a, { setDpi: async (dpi: number) => { + writes.push(dpi); + h.control.testReport({ dpi }); + cancelled = true; + } }); + const running = h.control.flashHardwareTestSetting(h.control.getGameProfileOwner(), { + currentRaw: 800, + targetRaw: 1600, + stageTarget: () => h.control.applyDpiValue(1600), + stageRestore: () => h.control.applyDpiValue(800, { force: true }), + read: (status: { dpi: number } | null) => status?.dpi, + isCancelled: () => cancelled, + }); + if (!cancelAfterDispatch) cancelled = true; + await h.drain(); + assert.equal(await running, cancelAfterDispatch ? "restored" : "cancelled"); + assert.deepEqual(writes, cancelAfterDispatch ? [1600, 800] : []); + assert.deepEqual(pending.pendingChanges(), []); + }); +} + +test("hardware test leaves another connection's staged settings alone when restoration becomes stale", async () => { + const h = controllerHarness(); + const otherEdit = { key: "other-device-dpi", label: "Other device DPI", command: "DPI", progress: "DPI", apply: async () => {} }; + Object.assign(h.a, { setDpi: async () => { + h.control.testSelect(h.b); + pending.stagePendingChange(otherEdit); + } }); + const running = h.control.flashHardwareTestSetting(h.control.getGameProfileOwner(), { + currentRaw: 800, + targetRaw: 1600, + stageTarget: () => h.control.applyDpiValue(1600), + stageRestore: () => assert.fail("the owner has changed"), + read: (status: { dpi: number } | null) => status?.dpi, + }); + await h.drain(); + assert.equal(await running, "restoreUnconfirmed"); + assert.deepEqual(pending.pendingChanges(), [otherEdit]); +}); + test("controller checks identity again after waiting on a refresh", async () => { const h = controllerHarness(); let writes = 0; diff --git a/src/device/traits.ts b/src/device/traits.ts index 7f084500..5dacd182 100644 --- a/src/device/traits.ts +++ b/src/device/traits.ts @@ -1,5 +1,10 @@ import type { MouseStatus } from "@openmouse/protocol/drivers/mouse-types"; +/** Drivers can expose controls while their status still contains unverified defaults. */ +export function verifiedDeviceSettings(status: MouseStatus | null): MouseStatus | null { + return (status?.ui?.valuesVerified ?? status?.ui?.settingsReady !== false) ? status : null; +} + export interface DriverTraits { advancedSection: boolean; signal: boolean; @@ -160,6 +165,7 @@ export function traitsFor(status: MouseStatus | null): DriverTraits { return { ...traits, advancedSection: traits.advancedSection || egg || ui?.showAdvancedSection === true, + debounce: traits.debounce || (family === "attackshark" && status.debounceMs != null), signal: traits.signal && ui?.hideSignalCard !== true, sleep: traits.sleep && ui?.hideSleepCard !== true, eggControls: egg, diff --git a/src/device/x11-connection-read.test.ts b/src/device/x11-connection-read.test.ts new file mode 100644 index 00000000..28c297b7 --- /dev/null +++ b/src/device/x11-connection-read.test.ts @@ -0,0 +1,110 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import test from "node:test"; +import { setImmediate } from "node:timers/promises"; +import vm from "node:vm"; +import ts from "typescript"; +import * as pending from "./pending-changes.ts"; + +function controllerHarness() { + const exports: any = {}; + const mocks = new Map(); + const source = readFileSync(new URL("./controller.ts", import.meta.url), "utf8") + .replaceAll("import.meta.env", "({ DEV: false })") + ` +export { activateClient, refreshStatus, showDisconnectedState }; +export function testStatus() { return latestDeviceStatus; } +applyStatus = (status) => { latestDeviceStatus = status; }; +refreshSidebar = async () => {}; +startAutomaticRefresh = () => {}; +`; + const code = ts.transpileModule(source, { + compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 }, + }).outputText; + const localStorage = { getItem: () => null, setItem() {} }; + const modules = new Proxy>({}, { + get: (target, key) => key === "then" ? undefined : target[key] ??= function () {}, + }); + vm.runInNewContext(code, { + exports, structuredClone, document: {}, localStorage, + __BUILD_CHANNEL__: "stable", __BUILD_ID__: "test", __APP_VERSION__: "test", + navigator: { locks: { request: async (_name: string, _options: object, read: (lock: object) => unknown) => read({}) } }, + window: { localStorage, setTimeout: () => 1, clearTimeout() {} }, + require(name: string) { + if (name.endsWith("pending-changes")) return pending; + if (name.endsWith("driver-classes")) { + return { driverModules: () => modules, ensureDriverModules: async () => modules }; + } + if (name.endsWith("interface-preferences")) return { loadInterfacePreferences: () => ({ locale: "en" }) }; + if (name.endsWith("i18n/index")) return { t: (_locale: string, key: string) => key, tp: (_locale: string, key: string) => key }; + if (!mocks.has(name)) mocks.set(name, new Proxy({}, { get: (target: any, key) => target[key] ??= function () {} })); + return mocks.get(name); + }, + }); + return exports; +} + +function receiverStatus(ready: boolean, dpi = 0) { + return { name: "Attack Shark X11", dpi, ui: { x11ConfigurationAvailable: true, x11AutoReadReady: ready } }; +} + +test("X11 loads automatically on connect and shares that read with an explicit request", async () => { + const control = controllerHarness(); + let reads = 0; + let dpi = 0; + let finish = () => {}; + const reading = new Promise((resolve) => { finish = resolve; }); + const client = { + device: {}, + getDpiOptions: () => [800], + readStatus: async () => receiverStatus(true, dpi), + async readX11Configuration() { + reads++; + await reading; + dpi = 800; + return receiverStatus(true, dpi); + }, + }; + + await control.activateClient(client); + assert.equal(reads, 1); + const explicitLoad = control.loadX11Settings(); + finish(); + assert.equal(await explicitLoad, true); + assert.equal(control.testStatus().dpi, 800); + await control.refreshStatus(); + await control.refreshStatus(); + assert.equal(reads, 1); + + control.showDisconnectedState(); + await control.activateClient(client); + await setImmediate(); + assert.equal(reads, 2); +}); + +test("X11 waits for receiver activity and leaves a failed connection read available for manual retry", async () => { + const control = controllerHarness(); + let ready = false; + let reads = 0; + const client = { + device: {}, + getDpiOptions: () => [800], + readStatus: async () => receiverStatus(ready), + async readX11Configuration() { + if (++reads === 1) throw new Error("Receiver timed out"); + return receiverStatus(ready, 800); + }, + }; + + await control.activateClient(client); + await setImmediate(); + assert.equal(reads, 0); + ready = true; + await control.refreshStatus(); + await setImmediate(); + assert.equal(reads, 1); + await control.refreshStatus(); + await setImmediate(); + assert.equal(reads, 1); + assert.equal(await control.loadX11Settings(), true); + assert.equal(reads, 2); +}); diff --git a/src/device/x11-macros.test.ts b/src/device/x11-macros.test.ts new file mode 100644 index 00000000..59b4b02d --- /dev/null +++ b/src/device/x11-macros.test.ts @@ -0,0 +1,33 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + X11_MACRO_LIMIT, finishX11MacroRecording, recordX11MacroEvent, startX11MacroRecording, + x11MacroBalanced, x11MacroMouseUsage, x11MacroUnits, +} from "./x11-macros.ts"; + +test("X11 recording fits a long release at capacity and refuses additional presses", () => { + const session = startX11MacroRecording(); + session.units = X11_MACRO_LIMIT - 2; + assert.equal(recordX11MacroEvent(session, 4, true, 0), true); + assert.equal(recordX11MacroEvent(session, 5, true, 10), false); + assert.equal(session.shortenedRelease, false); + assert.equal(recordX11MacroEvent(session, 4, false, 2_000), true); + assert.equal(session.shortenedRelease, true); + const steps = finishX11MacroRecording(session); + assert.equal(x11MacroUnits(steps), 2); + assert.equal(x11MacroBalanced(steps), true); +}); + +test("X11 recording releases held mouse and keyboard inputs when it stops", () => { + const session = startX11MacroRecording(); + const forward = x11MacroMouseUsage(4)!; + recordX11MacroEvent(session, forward, true, 0); + recordX11MacroEvent(session, 4, true, 2_035); + const steps = finishX11MacroRecording(session); + assert.equal(forward, 0xf5); + assert.equal(steps[1].delayMs, 2040); + assert.equal(x11MacroUnits(steps), 5); + assert.deepEqual(steps.slice(2).map(({ usage, down }) => [usage, down]), [[0xf5, false], [4, false]]); + assert.equal(x11MacroBalanced(steps), true); + assert.equal(x11MacroBalanced(steps.slice(1)), false); +}); diff --git a/src/device/x11-macros.ts b/src/device/x11-macros.ts new file mode 100644 index 00000000..dba70ff2 --- /dev/null +++ b/src/device/x11-macros.ts @@ -0,0 +1,136 @@ +import { INCOTT_MACRO_KEY_CHOICES, incottMacroKeyForCode, incottMacroKeyName, newMacroId } from "./incott-macros.ts"; +import { hidKeyForCode } from "../features/profiles/hid-keys.ts"; + +export interface X11MacroStep { + usage: number; + down: boolean; + delayMs: number; +} + +export interface X11Macro { + id: string; + name: string; + playback: number; + repeats: number; + steps: X11MacroStep[]; +} + +const STORE_KEY = "openmouse.x11-macros"; +export const X11_MACRO_LIMIT = 50; +export const X11_DELAY_MIN = 10; +export const X11_DELAY_MAX = 50_000; +const STANDARD_DELAY_MAX = 1270; + +const punctuation = new Map([ + [0x2d, "-"], [0x2e, "="], [0x2f, "["], [0x30, "]"], [0x31, "\\"], + [0x33, ";"], [0x34, "'"], [0x35, "`"], [0x36, ","], [0x37, "."], [0x38, "/"], +]); +const mouseNames = ["Left click", "Right click", "Middle click", "Back", "Forward"]; +export const X11_KEY_CHOICES = [...INCOTT_MACRO_KEY_CHOICES.keyboard, ...punctuation.keys()]; +export const X11_MOUSE_CHOICES = mouseNames.map((_, index) => 0xf1 + index); +const knownUsages = new Set([...X11_KEY_CHOICES, ...X11_MOUSE_CHOICES]); + +export function x11MacroUsageName(usage: number): string { + return mouseNames[usage - 0xf1] ?? punctuation.get(usage) ?? incottMacroKeyName(usage); +} + +export function x11MacroKeyboardUsage(code: string): number | null { + return incottMacroKeyForCode(code) ?? hidKeyForCode(code); +} + +export function x11MacroMouseUsage(button: number): number | null { + return [0xf1, 0xf3, 0xf2, 0xf4, 0xf5][button] ?? null; +} + +export function newX11Macro(name: string): X11Macro { + return { id: newMacroId(), name, playback: 0, repeats: 1, steps: [] }; +} + +export function x11MacroUnits(steps: readonly X11MacroStep[]): number { + return steps.reduce((total, step) => total + (step.delayMs > STANDARD_DELAY_MAX ? 2 : 1), 0); +} + +export function x11MacroBalanced(steps: readonly X11MacroStep[]): boolean { + const held = new Set(); + for (const { usage, down } of steps) { + if (held.has(usage) === down) return false; + if (down) held.add(usage); + else held.delete(usage); + } + return held.size === 0; +} + +export function x11MacroQuantize(delayMs: number): number { + return Math.max(X11_DELAY_MIN, Math.min(X11_DELAY_MAX, Math.round(delayMs / 10) * 10)); +} + +export function isX11MacroDelay(value: number): boolean { + return Number.isInteger(value) && value >= X11_DELAY_MIN && value <= X11_DELAY_MAX && value % 10 === 0; +} + +interface Recording { + steps: X11MacroStep[]; + held: Set; + units: number; + lastAt: number | null; + shortenedRelease: boolean; +} + +export function startX11MacroRecording(): Recording { + return { steps: [], held: new Set(), units: 0, lastAt: null, shortenedRelease: false }; +} + +/** Reserve one short release for each pressed input, including at capacity. */ +export function recordX11MacroEvent(recording: Recording, usage: number, down: boolean, at: number): boolean { + if (recording.held.has(usage) === down) return false; + const delayMs = recording.lastAt === null ? X11_DELAY_MIN : x11MacroQuantize(at - recording.lastAt); + const remainingReleases = recording.held.size + (down ? 1 : -1); + const units = recording.units + (delayMs > STANDARD_DELAY_MAX ? 2 : 1); + if (units + remainingReleases > X11_MACRO_LIMIT) { + // Preserve a release even when its long measured delay would not fit. + if (down) return false; + recording.shortenedRelease = true; + recording.steps.push({ usage, down, delayMs: STANDARD_DELAY_MAX }); + recording.units++; + } else { + recording.steps.push({ usage, down, delayMs }); + recording.units = units; + } + if (down) recording.held.add(usage); + else recording.held.delete(usage); + recording.lastAt = at; + return true; +} + +export function finishX11MacroRecording(recording: Recording): X11MacroStep[] { + return [...recording.steps, ...[...recording.held].map((usage) => ({ usage, down: false, delayMs: X11_DELAY_MIN }))]; +} + +function isStoredMacro(value: unknown): value is X11Macro { + if (typeof value !== "object" || value === null) return false; + const { id, name, playback, repeats, steps } = value as Partial; + return typeof id === "string" && id.length > 0 && typeof name === "string" && name.trim().length > 0 + && typeof playback === "number" && [0, 1, 2].includes(playback) + && typeof repeats === "number" && Number.isInteger(repeats) && repeats >= 1 && repeats <= 255 + && Array.isArray(steps) && steps.length > 0 && steps.length <= X11_MACRO_LIMIT + && steps.every((step) => step && knownUsages.has(step.usage) && typeof step.down === "boolean" && isX11MacroDelay(step.delayMs)) + && x11MacroUnits(steps) <= X11_MACRO_LIMIT && x11MacroBalanced(steps); +} + +export function readX11MacroLibrary(): X11Macro[] { + try { + const value: unknown = JSON.parse(localStorage.getItem(STORE_KEY) ?? "[]"); + return Array.isArray(value) ? value.filter(isStoredMacro) : []; + } catch { + return []; + } +} + +export function writeX11MacroLibrary(macros: readonly X11Macro[]): boolean { + try { + localStorage.setItem(STORE_KEY, JSON.stringify(macros)); + return true; + } catch { + return false; + } +} diff --git a/src/features/devices/DeviceHero.tsx b/src/features/devices/DeviceHero.tsx index 805b5fb8..ce8da69f 100644 --- a/src/features/devices/DeviceHero.tsx +++ b/src/features/devices/DeviceHero.tsx @@ -74,6 +74,12 @@ export function DeviceHero({ ) : null}

+ {status?.ui?.x11ConfigurationAvailable ? ( + + ) : null} {image ? (
import("./cards/X11MacroCard").then(({ X11MacroCard }) => ({ default: X11MacroCard }))); + function on(tab: WorkspaceTab, tabs: readonly WorkspaceTab[]): boolean { return tabs.includes(tab); } @@ -407,6 +410,7 @@ export function Workspace({ show(has.atkButtons, ["buttons"]) ? : null, show(has.buttonMapping && !snapshot.traits.teevolution, ["buttons"]) ? : null, + show(has.x11Macros, ["buttons"]) ? : null, show(has.debounce, ["buttons"]) ? : null, show(has.ksnakeScroll, ["buttons"]) ? : null, @@ -420,6 +424,11 @@ export function Workspace({ show(has.ksnakeMacros, ["macro"]) ? : null, show(has.wallhackMacros, ["macro"]) ? : null, show(has.incottMacros, ["macro"]) ? : null, + show(has.x11Macros, ["macro"]) ? ( + {t(locale, "macro.loading")}

}> + +
+ ) : null, show(has.xiaomiMacros, ["macro"]) ? : null, show(has.leobogMacros, ["macro"]) ? : null, show(has.atkMacros, ["macro"]) ? : null, diff --git a/src/features/devices/cards/AdvancedCards.tsx b/src/features/devices/cards/AdvancedCards.tsx index 9bec4090..3e3c5124 100644 --- a/src/features/devices/cards/AdvancedCards.tsx +++ b/src/features/devices/cards/AdvancedCards.tsx @@ -303,6 +303,7 @@ export function SleepCard({ snapshot }: { snapshot: ControlSnapshot }): ReactNod const staged = snapshot.pending.keys.includes("sleep"); const canDisable = traits.directMode && capabilities?.canDisableSleep === true; const asleep = status.sleepTimeout !== null && status.sleepTimeout !== undefined; + const deepSleep = status.deepSleepMinutes; return (
@@ -333,6 +334,19 @@ export function SleepCard({ snapshot }: { snapshot: ControlSnapshot }): ReactNod onChange={(next) => control.applyPulsarValue("sleep", next)} /> )} + {deepSleep != null ? ( +
+

{t(locale, "x11.deepSleep")}

+ ({ value: i + 1, label: sleepLabel((i + 1) * 60, locale) }))} + value={deepSleep} + disabled={snapshot.settingsPending} + onChange={control.applyDeepSleep} + /> +
+ ) : null}
); } @@ -3675,6 +3689,8 @@ export function ButtonMappingCard({ snapshot }: { snapshot: ControlSnapshot }): : null; const canResetKsnake = isNoirProfile; const mappings = selectedM2NexProfile?.buttonMappings ?? status.buttonMappings; + const x11MappingsUnread = status.ui?.x11ConfigurationAvailable === true + && Object.values(mappings).every((assignment) => assignment === "Unknown"); const pendingButtons = new Set(snapshot.pending.keys); const resettingButtons = pendingButtons.has("ksnake-button-reset"); // Drivers that publish their factory table get the generic restore button. @@ -3719,7 +3735,7 @@ export function ButtonMappingCard({ snapshot }: { snapshot: ControlSnapshot }): { + const selected = library.find((macro) => macro.id === event.currentTarget.value); + if (selected) { + setShortenedRelease(false); + setDraft(selected); + } + }}> + {!saved ? : null} + {library.map((macro) => )} + + + + +
+
+ + {draft.playback === 0 ? ( + + ) : null} +
+
+
+
+
+
+ + +
+
+
+ {draft.steps.length === 0 ?

{t(locale, "kb.mchMacroNoSteps")}

: null} +
+ {draft.steps.map((step, index) => ( +
+ {index + 1} + + + + + + +
+ ))} +
+ {draft.steps.length > 0 ?

{tp(locale, "x11.macroCapacity", { n: units, max: X11_MACRO_LIMIT })}

: null} + {!balanced ?

{t(locale, "x11.macroBalance")}

: null} + {shortenedRelease ?

{t(locale, "x11.macroShortenedRelease")}

: null} + {storageFailed ?

{t(locale, "x11.macroStorage")}

: null} +
+ + + {saved ? : null} +
+ {buttons.length ? ( +
+ + +
+ ) : null} + + ); +} diff --git a/src/features/devices/cards/X11ShortcutCard.tsx b/src/features/devices/cards/X11ShortcutCard.tsx new file mode 100644 index 00000000..e4414c14 --- /dev/null +++ b/src/features/devices/cards/X11ShortcutCard.tsx @@ -0,0 +1,54 @@ +import { useRef, useState, type ReactNode } from "react"; +import { Keyboard } from "lucide-react"; +import { applyX11Shortcut } from "../../../device/controller"; +import { x11MacroKeyboardUsage, x11MacroUsageName } from "../../../device/x11-macros"; +import type { ControlSnapshot } from "../../../device/types"; +import { displayText, t } from "../../../i18n/index"; + +export function X11ShortcutCard({ snapshot }: { snapshot: ControlSnapshot }): ReactNode { + const { locale } = snapshot.preferences; + const mappings = snapshot.status?.buttonMappings; + const buttons = Object.keys(mappings ?? {}).filter((name) => name !== "Left" && mappings?.[name] !== "Unknown"); + const [button, setButton] = useState("Forward"); + const selectedButton = buttons.includes(button) ? button : buttons[0] ?? ""; + const [shortcut, setShortcut] = useState<{ name: string; modifiers: number; usage: number } | null>(null); + const input = useRef(null); + const disabled = !selectedButton || snapshot.settingsPending || snapshot.settingInProgress || snapshot.pending.busy || snapshot.gameProfileDraft; + + return ( +
`button-${name}`).join(" ")}> +
+
+ + +
+ +
+
+ ); +} diff --git a/src/features/devices/cards/availability.ts b/src/features/devices/cards/availability.ts index 40a12732..e0125c94 100644 --- a/src/features/devices/cards/availability.ts +++ b/src/features/devices/cards/availability.ts @@ -56,6 +56,7 @@ export interface CardAvailability { ksnakeMacros: boolean; xiaomiMacros: boolean; leobogMacros: boolean; + x11Macros: boolean; wallhackScanning: boolean; wallhackCurves: boolean; wallhackMacros: boolean; @@ -117,6 +118,7 @@ const NOTHING: CardAvailability = { ksnakeMacros: false, xiaomiMacros: false, leobogMacros: false, + x11Macros: false, wallhackScanning: false, wallhackCurves: false, wallhackMacros: false, @@ -183,7 +185,7 @@ function computeCardAvailability(snapshot: ControlSnapshot): CardAvailability { superstrike: traits.logitech && status.analogButtonTuning?.buttons.length === 2, magnetic: status.magneticButtons?.buttons.length === 2, lighting: Boolean(status.lighting || status.lightingZones?.length), - lightingAdvanced: host && !isNoirKsnake && Boolean(status.lighting || status.lightingZones?.length), + lightingAdvanced: host && ui?.hideAdvancedLighting !== true && !isNoirKsnake && Boolean(status.lighting || status.lightingZones?.length), onboardProfiles: (status.profileCount ?? 0) > 1 && status.activeProfile != null, buttonMapping: Boolean(status.buttonMappings) && Boolean(status.buttonOptions?.length) && !(snapshot.gameProfileDraft && ui?.family === "steelseries-rival650"), @@ -202,6 +204,7 @@ function computeCardAvailability(snapshot: ControlSnapshot): CardAvailability { // The GM3 macro table is write-only, so the editor is always offered; it // starts blank and holds whatever this session uploaded. leobogMacros: ui?.family === "leobog-gm3", + x11Macros: ui?.x11MacroBindings === true, powerMode: host && Boolean(status.powerModes?.length), profiles: traits.logitech && status.deviceMode !== undefined && status.deviceMode !== "Unknown", diff --git a/src/features/devices/workspace-tabs.ts b/src/features/devices/workspace-tabs.ts index 85be2cd7..fb7cf65a 100644 --- a/src/features/devices/workspace-tabs.ts +++ b/src/features/devices/workspace-tabs.ts @@ -18,7 +18,7 @@ export function availableWorkspaceTabs( if (tab === "receiver") return has.keychronReceiver; if (tab === "lighting") return !options.hideLighting && (has.lighting || has.teevolutionDpiLighting); if (tab === "buttons") return hasButtons; - if (tab === "macro") return has.ksnakeMacros || has.wallhackMacros || has.incottMacros || has.xiaomiMacros || has.leobogMacros || has.atkMacros; + if (tab === "macro") return has.ksnakeMacros || has.wallhackMacros || has.incottMacros || has.xiaomiMacros || has.leobogMacros || has.atkMacros || has.x11Macros; if (tab === "profiles") return hasProfiles; return true; }); diff --git a/src/features/hardware-test/HardwareTestPage.tsx b/src/features/hardware-test/HardwareTestPage.tsx index cb84c183..1f34350a 100644 --- a/src/features/hardware-test/HardwareTestPage.tsx +++ b/src/features/hardware-test/HardwareTestPage.tsx @@ -1,8 +1,10 @@ import { displayText } from "../../i18n/index"; import { track } from "../../platform/analytics"; +import type { MouseStatus } from "@openmouse/protocol/drivers/mouse-types"; import { useCallback, useEffect, useRef, useState, type ReactNode } from "react"; import * as control from "../../device/controller"; import type { ControlSnapshot } from "../../device/types"; +import { verifiedDeviceSettings } from "../../device/traits"; import { t, tp } from "../../i18n/index"; import { computeResults, formatHz, rollingLiveHz } from "./polling-stats"; import { brandChecks } from "./hardware-brand-checks"; @@ -11,6 +13,7 @@ import { deviceInfoFromSnapshot, flashWriteResult, formatHexId, + isFlashBaseline, pickFlashDpiTarget, pickFlashLiftOffTarget, pickFlashPollRateTarget, @@ -73,8 +76,7 @@ export function HardwareTestPage({ snapshot }: { snapshot: ControlSnapshot }): R const cancelRef = useRef(false); const stageIdRef = useRef(0); - // Navigating away mid-run must stop the suite: it writes and restores device - // settings, so it cannot keep driving hardware from an unmounted page. + // Leaving the page stops new test writes. An in-flight write can still restore its baseline. useEffect(() => () => { cancelRef.current = true; runningRef.current = false; @@ -110,34 +112,62 @@ export function HardwareTestPage({ snapshot }: { snapshot: ControlSnapshot }): R track("hardware_test_started"); void (async () => { - let info = deviceInfoFromSnapshot(control.getSnapshot()); + const startSnapshot = control.getSnapshot(); + const device = control.getActiveDevice(); + const owner = control.getGameProfileOwner(); + const sameDevice = (): boolean => control.getActiveDevice() === device + && (owner === null || control.isGameProfileOwner(owner)); + const stopReason = (): string | null => { + if (cancelRef.current) return t(locale, "hw.stateStopped"); + return sameDevice() ? null : t(locale, "hw.deviceChanged"); + }; + const needsX11Read = startSnapshot.status?.ui?.x11ConfigurationAvailable === true; + let x11SettingsRead = false; + let info = deviceInfoFromSnapshot(startSnapshot); const results: HardwareTestResult[] = []; let aborted = false; const startedAt = performance.now(); - // Background descriptor lookup (feed the control-interface check detail) - // — no stage of its own, it is not user-visible work. - const interfaces = await hidInterfacesSummary(info.vendorId, info.productId); - if (interfaces) info = { ...info, collectionsSummary: interfaces }; - // "Test started" — the opening beat of the run. const startedStage = addStage({ kind: "start", label: t(locale, "hw.testStarted") }); await sleep(340); updateStage(startedStage, { state: "pass" }); await sleep(140); + if (needsX11Read && !stopReason()) { + const label = t(locale, "x11.loadSettings"); + const id = addStage({ kind: "check", label }); + const loaded = await control.loadX11Settings(); + const stopped = stopReason(); + x11SettingsRead = !stopped && loaded; + if (!stopped) info = deviceInfoFromSnapshot(control.getSnapshot()); + const check: HardwareTestResult = { + key: "x11Configuration", + label, + status: stopped ? "skip" : x11SettingsRead ? "pass" : "fail", + detail: stopped ?? (x11SettingsRead ? null : t(locale, "hw.x11ReadFailed")), + }; + results.push(check); + updateStage(id, { state: check.status, detail: check.detail }); + } + + // Include the control-interface descriptor in the report. + const interfaces = stopReason() ? null : await hidInterfacesSummary(info.vendorId, info.productId); + if (interfaces) info = { ...info, collectionsSummary: interfaces }; + const runCheckStage = async (check: HardwareTestResult): Promise => { - if (cancelRef.current) { + if (stopReason()) { aborted = true; results.push({ ...check, status: "skip" as const, detail: null }); return; } const id = addStage({ kind: "check", label: check.label }); await sleep(300); - if (cancelRef.current) { + const stopped = stopReason(); + if (stopped) { aborted = true; - updateStage(id, { state: "skip", detail: "stopped by user" }); - results.push({ ...check, status: "skip" as const, detail: null }); + updateStage(id, { state: "skip", detail: stopped }); + results.push({ ...check, status: "skip" as const, detail: stopped }); return; } results.push(check); @@ -192,15 +222,16 @@ export function HardwareTestPage({ snapshot }: { snapshot: ControlSnapshot }): R const live = rollingLiveHz(intervals); if (live > 0) setLiveSample({ hz: formatHz(live), samples: intervals.length }); }, 250); - for (let waited = 0; waited < SAMPLE_WINDOW_MS && !cancelRef.current; waited += 100) await sleep(100); + for (let waited = 0; waited < SAMPLE_WINDOW_MS && !stopReason(); waited += 100) await sleep(100); window.clearInterval(progressTimer); window.clearInterval(liveTimer); window.removeEventListener("pointermove", onMove); let samplingResult: HardwareTestResult; - if (cancelRef.current) { + const stopped = stopReason(); + if (stopped) { aborted = true; - samplingResult = { key: "sampling", label: "Polling rate sampling", status: "skip", detail: "stopped by user" }; + samplingResult = { key: "sampling", label: "Polling rate sampling", status: "skip", detail: stopped }; } else { const computed = computeResults(intervals, SAMPLE_WINDOW_MS); samplingResult = pollingSampleResult({ @@ -231,113 +262,109 @@ export function HardwareTestPage({ snapshot }: { snapshot: ControlSnapshot }): R setting: string; current: string; target: string; - note: string; currentRaw: unknown; targetRaw: unknown; - stageTarget: () => boolean; - stageRestore: () => boolean; - read: () => unknown; + stageTarget: () => void; + stageRestore: () => void; + read: (status: MouseStatus | null) => unknown; }): Promise => { await sleep(400); - if (cancelRef.current) { + const stopped = stopReason(); + if (stopped) { aborted = true; - return { setting: leg.setting, current: leg.current, target: leg.target, status: "skip", detail: "stopped by user." }; + return { setting: leg.setting, current: leg.current, target: leg.target, status: "skip", detail: stopped }; } - if (!leg.stageTarget()) { - return { setting: leg.setting, current: leg.current, target: leg.target, status: "fail", detail: "the write was rejected by the driver." }; + const result = await control.flashHardwareTestSetting(owner, { ...leg, isCancelled: () => cancelRef.current }); + if (result === "cancelled") { + aborted = true; + return { setting: leg.setting, current: leg.current, target: leg.target, status: "skip", detail: t(locale, "hw.stateStopped") }; } - let written = false; - try { - await control.flashPendingChanges(); - written = true; - } catch { - written = false; + if (result === "changed") { + return { setting: leg.setting, current: leg.current, target: leg.target, status: "skip", detail: stopReason() ?? t(locale, "hw.testSettingsChanged") }; } - if (!written) { - return { setting: leg.setting, current: leg.current, target: leg.target, status: "fail", detail: "the flash write was not executed." }; + if (result === "writeNotSent") { + return { setting: leg.setting, current: leg.current, target: leg.target, status: "fail", detail: t(locale, "hw.flashNotSent") }; } - if (leg.read() !== leg.targetRaw) { - return { setting: leg.setting, current: leg.current, target: leg.target, status: "fail", detail: `wrote ${leg.target} but read back something else — the write did not stick.` }; + if (result === "writeUnconfirmed") { + return { setting: leg.setting, current: leg.current, target: leg.target, status: "fail", detail: t(locale, "hw.flashUnconfirmed") }; } - try { - leg.stageRestore(); - await control.flashPendingChanges(); - if (leg.read() !== leg.currentRaw) { - return { setting: leg.setting, current: leg.current, target: leg.target, status: "fail", detail: `restore to ${leg.current} failed after reading back ${leg.target} — device settings may have changed.` }; - } - } catch { - return { setting: leg.setting, current: leg.current, target: leg.target, status: "fail", detail: `restore to ${leg.current} failed after reading back ${leg.target} — device settings may have changed.` }; + if (result === "restoreUnconfirmed") { + return { setting: leg.setting, current: leg.current, target: leg.target, status: "fail", detail: tp(locale, "hw.restoreUnconfirmed", { value: leg.current }) }; + } + if (result === "readbackMismatch") { + return { setting: leg.setting, current: leg.current, target: leg.target, status: "fail", detail: tp(locale, "hw.flashReadbackMismatch", { value: leg.target }) }; } return { setting: leg.setting, current: leg.current, target: leg.target, status: "pass", detail: `wrote ${leg.target} → read back → restored ${leg.current}` }; }; let flashResult: HardwareTestResult; - if (cancelRef.current) { + const stopped = stopReason(); + if (stopped) { aborted = true; - flashResult = flashWriteResult({ skipped: true, skippedReason: "stopped by user." }); + flashResult = flashWriteResult({ skipped: true, skippedReason: stopped }); } else { - const legLive = control.getSnapshot(); - const legInfo = deviceInfoFromSnapshot(legLive); - const live = legInfo.present ? legLive : control.getSnapshot(); - if (!live.status) { + const live = control.getSnapshot(); + const liveStatus = live.deviceStatus; + if (needsX11Read && !x11SettingsRead) { + flashResult = flashWriteResult({ skipped: true, skippedReason: t(locale, "hw.x11ReadFailed") }); + } else if (!liveStatus) { flashResult = flashWriteResult({ skipped: true, skippedReason: "no live device status — cannot round-trip a write." }); - } else if (live.settingsPending) { + } else if (live.settingsPending || live.pending.count > 0 || live.gameProfileDraft) { flashResult = flashWriteResult({ skipped: true, skippedReason: "you have staged, unapplied changes — apply or revert them first." }); } else { const legs: FlashSettingRoundTrip[] = []; + const settings = verifiedDeviceSettings(liveStatus); // Setting 1: DPI — round-trip (write → read-back → restore). - const dpiCurrent = live.status.dpi; - if (dpiCurrent === null) { + const dpiCurrent = settings?.dpi ?? null; + if (!isFlashBaseline(dpiCurrent)) { legs.push({ setting: "DPI", current: "—", target: "—", status: "skip", detail: "no DPI value is reported on this device." }); } else { const dpiTarget = pickFlashDpiTarget(dpiCurrent, live.dpiOptions); if (dpiTarget === null) { - legs.push({ setting: "DPI", current: `${dpiCurrent.toLocaleString()} DPI`, target: "—", status: "skip", detail: "no alternate DPI value is writable on this device." }); + legs.push({ setting: "DPI", current: `${dpiCurrent.toLocaleString()} DPI`, target: "—", status: "skip", detail: t(locale, "hw.noRestorableTarget") }); } else { legs.push(await runFlashLeg({ setting: "DPI", current: `${dpiCurrent.toLocaleString()} DPI`, target: `${dpiTarget.toLocaleString()} DPI`, - note: "your pointer speed changes briefly", currentRaw: dpiCurrent, targetRaw: dpiTarget, stageTarget: () => control.applyDpiValue(dpiTarget), - stageRestore: () => control.applyDpiValue(dpiCurrent), - read: () => control.getSnapshot().status?.dpi ?? null, + stageRestore: () => control.applyDpiValue(dpiCurrent, { force: true }), + read: (status) => status?.dpi ?? null, })); } } // Setting 2: Polling rate — round-trip. - const rateCurrent = live.status.pollingRateHz; - if (rateCurrent === null) { + const rateCurrent = settings?.pollingRateHz ?? null; + if (!isFlashBaseline(rateCurrent)) { legs.push({ setting: "Poll rate", current: "—", target: "—", status: "skip", detail: "no polling rate is reported on this device." }); } else { - const rateTarget = pickFlashPollRateTarget(rateCurrent, live.status.supportedPollingRates ?? control.RATE_STEPS_HZ); + const rateTarget = pickFlashPollRateTarget(rateCurrent, liveStatus.supportedPollingRates ?? control.RATE_STEPS_HZ); if (rateTarget === null) { - legs.push({ setting: "Poll rate", current: `${rateCurrent.toLocaleString()} Hz`, target: "—", status: "skip", detail: "no alternate polling rate is writable on this device." }); + legs.push({ setting: "Poll rate", current: `${rateCurrent.toLocaleString()} Hz`, target: "—", status: "skip", detail: t(locale, "hw.noRestorableTarget") }); } else { legs.push(await runFlashLeg({ setting: "Poll rate", current: `${rateCurrent.toLocaleString()} Hz`, target: `${rateTarget.toLocaleString()} Hz`, - note: "the reporting rate changes briefly", currentRaw: rateCurrent, targetRaw: rateTarget, - stageTarget: () => { control.applyPollingRate(rateTarget); return true; }, - stageRestore: () => { control.applyPollingRate(rateCurrent); return true; }, - read: () => control.getSnapshot().status?.pollingRateHz ?? null, + stageTarget: () => control.applyPollingRate(rateTarget), + stageRestore: () => control.applyPollingRate(rateCurrent, { force: true }), + read: (status) => status?.pollingRateHz ?? null, })); } } // Setting 3: Lift-off distance — round-trip. - const lodCurrent = live.status.liftOffDistance; + const lodCurrent = settings?.liftOffDistance ?? null; if (lodCurrent === null) { legs.push({ setting: "Lift-off", current: "—", target: "—", status: "skip", detail: "no lift-off distance is reported on this device." }); } else { - const lodTarget = pickFlashLiftOffTarget(lodCurrent, live.status.supportedLiftOffDistances); + const lodTarget = pickFlashLiftOffTarget(lodCurrent, liveStatus.supportedLiftOffDistances); if (lodTarget === null) { legs.push({ setting: "Lift-off", current: lodCurrent, target: "—", status: "skip", detail: "no alternate lift-off distance is available." }); } else { @@ -345,12 +372,11 @@ export function HardwareTestPage({ snapshot }: { snapshot: ControlSnapshot }): R setting: "Lift-off", current: lodCurrent, target: lodTarget, - note: "the sensor lift height changes briefly", currentRaw: lodCurrent, targetRaw: lodTarget, - stageTarget: () => { control.applyLiftOffDistance(lodTarget); return true; }, - stageRestore: () => { control.applyLiftOffDistance(lodCurrent); return true; }, - read: () => control.getSnapshot().status?.liftOffDistance ?? null, + stageTarget: () => control.applyLiftOffDistance(lodTarget), + stageRestore: () => control.applyLiftOffDistance(lodCurrent, { force: true }), + read: (status) => status?.liftOffDistance ?? null, })); } } @@ -364,7 +390,7 @@ export function HardwareTestPage({ snapshot }: { snapshot: ControlSnapshot }): R } // ── Summary ──────────────────────────────────────────────────────── - const verdict = verdictFor({ results, incomplete: aborted }); + const verdict = verdictFor({ results, incomplete: aborted || stopReason() !== null }); // Crosscheck the device against the supported-devices page (the mirrored // table behind openmouse.app/supported): is it listed, and does this run @@ -760,4 +786,4 @@ export function HardwareTestPage({ snapshot }: { snapshot: ControlSnapshot }): R ); -} \ No newline at end of file +} diff --git a/src/features/hardware-test/hardware-test-report.test.ts b/src/features/hardware-test/hardware-test-report.test.ts index 0916d18d..92bcb475 100644 --- a/src/features/hardware-test/hardware-test-report.test.ts +++ b/src/features/hardware-test/hardware-test-report.test.ts @@ -276,6 +276,17 @@ test("pickFlashLiftOffTarget prefers Medium, falling back to Low", () => { assert.equal(pickFlashLiftOffTarget("Low", ["Low"]), null); }); +test("flash targets require a reported value that can be restored", () => { + for (const baseline of [0, -1, 0.5, Number.NaN, Number.POSITIVE_INFINITY]) { + assert.equal(pickFlashDpiTarget(baseline, [baseline, 800]), null); + assert.equal(pickFlashPollRateTarget(baseline, [baseline, 500]), null); + } + assert.equal(pickFlashDpiTarget(3600, [800, 1600]), null); + assert.equal(pickFlashPollRateTarget(1000, [125, 500]), null); + assert.equal(pickFlashDpiTarget(3600, [800, 3600]), 800); + assert.equal(pickFlashPollRateTarget(1000, [125, 500, 1000]), 500); +}); + test("flashWriteResult scores the round-trip legs — DPI, poll rate, lift-off", () => { const pass = flashWriteResult({ roundTrips: [ diff --git a/src/features/hardware-test/hardware-test-report.ts b/src/features/hardware-test/hardware-test-report.ts index 2d2b6735..c378b6ab 100644 --- a/src/features/hardware-test/hardware-test-report.ts +++ b/src/features/hardware-test/hardware-test-report.ts @@ -1,4 +1,5 @@ import type { ControlSnapshot } from "../../device/types"; +import { verifiedDeviceSettings } from "../../device/traits.ts"; import { formatHz } from "./polling-stats.ts"; import type { SupportedDevicesCrosscheck } from "./supported-devices-crosscheck.ts"; @@ -95,7 +96,7 @@ export function deviceInfoFromSnapshot(snapshot: ControlSnapshot): HardwareDevic // driver whose settings read failed (settingsReady: false) or that has no // read-back (valuesVerified: false) still fills them with defaults, so drop // them here and the read-back checks fail instead of passing on those. - const settings = (status?.ui?.valuesVerified ?? status?.ui?.settingsReady !== false) ? status : null; + const settings = verifiedDeviceSettings(status); return { present: status !== null, brand: status?.brand ?? null, @@ -329,12 +330,12 @@ export function verdictFor(run: { results: HardwareTestResult[]; incomplete: boo * smallest available value. Returns null when there is nothing to write. */ export function pickFlashDpiTarget(current: number | null, options: readonly number[]): number | null { - if (current === null || options.length === 0) return null; + if (!isFlashBaseline(current) || !options.includes(current)) return null; const candidates = [800, 1600, 2400, 3200, current * 2, Math.round(current / 2)]; for (const candidate of candidates) { if (candidate !== current && candidate > 0 && candidate <= MAX_PLAUSIBLE_DPI && options.includes(candidate)) return candidate; } - const alternate = options.find((option) => option !== current); + const alternate = options.find((option) => option !== current && isFlashBaseline(option) && option <= MAX_PLAUSIBLE_DPI); return alternate ?? null; } @@ -345,15 +346,19 @@ export function pickFlashDpiTarget(current: number | null, options: readonly num * value. Returns null when there is nothing to write. */ export function pickFlashPollRateTarget(current: number | null, options: readonly number[]): number | null { - if (current === null || options.length === 0) return null; + if (!isFlashBaseline(current) || !options.includes(current)) return null; const candidates = [current * 2, Math.round(current / 2), 125, 250, 500, 1000, 2000, 4000, 8000]; for (const candidate of candidates) { if (candidate !== current && candidate > 0 && options.includes(candidate)) return candidate; } - const alternate = options.find((option) => option !== current); + const alternate = options.find((option) => option !== current && isFlashBaseline(option)); return alternate ?? null; } +export function isFlashBaseline(value: number | null): value is number { + return value !== null && Number.isInteger(value) && value > 0; +} + /** * Picks the least obtrusive alternate lift-off level the device offers. * Medium is the middle of the physical range, so it is preferred whenever the @@ -457,4 +462,4 @@ export function pollingSampleResult(sample: { status: "skip", detail: `avg ${formatHz(sample.avgHz)} Hz vs reported ${reported} Hz — dropout or rate mismatch detected, so the sample is not counted as a failure.`, }; -} \ No newline at end of file +} diff --git a/src/i18n/index.ts b/src/i18n/index.ts index 3ab9483d..9fd410e4 100644 --- a/src/i18n/index.ts +++ b/src/i18n/index.ts @@ -6,6 +6,14 @@ const en = { "receiver.all": "All", "receiver.mouse": "Mouse buttons", "receiver.shortcuts": "Keyboard shortcuts", + "x11.deepSleep": "Deep sleep", + "x11.macroAssign": "Assign to button", + "x11.macroRecording": "Press keys or mouse buttons. Press Esc to stop.", + "x11.macroCapacity": "{n} of {max} action units used. Delays over 1,270 ms use two.", + "x11.macroBalance": "Each press needs a matching release. Check the order of the steps.", + "x11.macroShortenedRelease": "The recorder shortened a release delay to fit the macro. Review the step timing.", + "x11.macroStorage": "Couldn't update the macro library in this browser.", + "x11.loadSettings": "Load X11 settings", "receiver.media": "Media", "receiver.rates": "DPI and polling", "receiver.lighting": "Lighting and switches", @@ -316,6 +324,14 @@ const en = { "hw.checking": "Checking {label}…", "hw.samplingPrompt": "Move the mouse in small circles over this window — 5 seconds of sampling.", "hw.flashPrompt": "A build setting is written, read back, then restored — your pointer may change briefly.", + "hw.x11ReadFailed": "Could not read the X11 settings.", + "hw.deviceChanged": "The selected device changed during the test.", + "hw.testSettingsChanged": "The device or its settings changed during the test.", + "hw.flashNotSent": "The test failed before sending the flash write.", + "hw.flashUnconfirmed": "The test could not confirm the flash write.", + "hw.restoreUnconfirmed": "Could not confirm the restore to {value}.", + "hw.flashReadbackMismatch": "Could not read back {value}. The original value was restored.", + "hw.noRestorableTarget": "No alternate setting can be written and safely restored.", "hw.liveHertz": "{hz} Hz · {samples} samples", "hw.finishTime": "Finished in {s} s", "hw.identity": "VID / PID", diff --git a/src/i18n/locales/ar.ts b/src/i18n/locales/ar.ts index 932e1a96..bf3f5f33 100644 --- a/src/i18n/locales/ar.ts +++ b/src/i18n/locales/ar.ts @@ -3,6 +3,14 @@ import { WOOTING_UI_STRINGS } from "./wooting-ui.ts"; import { VENDOR_KEYBOARD_UI_STRINGS } from "./vendor-keyboard-ui.ts"; export const ar: Record = { + "x11.macroAssign": "تعيين للزر", + "x11.macroRecording": "اضغط مفاتيح أو أزرار الماوس. اضغط Esc للإيقاف.", + "x11.macroCapacity": "تم استخدام {n} من {max} وحدات إجراء. التأخير الذي يتجاوز 1270 مللي ثانية يستخدم وحدتين.", + "x11.macroBalance": "تحتاج كل ضغطة إلى إفلات مطابق. تحقق من ترتيب الخطوات.", + "x11.macroShortenedRelease": "قصّر المسجّل مدة تأخير إفلات أحد الأزرار لتناسب سعة الماكرو. راجع توقيت الخطوات.", + "x11.macroStorage": "تعذر تحديث مكتبة وحدات الماكرو في هذا المتصفح.", + "x11.loadSettings": "تحميل إعدادات X11", + "x11.deepSleep": "السكون العميق", "receiver.assign": "تعيين إجراء", "receiver.search": "البحث عن إجراءات", "receiver.all": "الكل", @@ -259,6 +267,14 @@ export const ar: Record = { "hw.checking": "جارٍ التحقق من {label}…", "hw.samplingPrompt": "حرّك الماوس بدوائر صغيرة فوق هذه النافذة — أخذ العينات يستغرق 5 ثوانٍ.", "hw.flashPrompt": "يُكتب إعداد، ثم يُقرأ من جديد ويُستعاد — قد تتغير سرعة المؤشر للحظات.", + "hw.x11ReadFailed": "تعذرت قراءة إعدادات X11.", + "hw.deviceChanged": "تغيّر الجهاز المحدد أثناء الاختبار.", + "hw.testSettingsChanged": "تغيّر الجهاز أو إعداداته أثناء الاختبار.", + "hw.flashNotSent": "فشل الاختبار قبل إرسال أمر الكتابة إلى ذاكرة الفلاش.", + "hw.flashUnconfirmed": "تعذر على الاختبار تأكيد الكتابة إلى ذاكرة الفلاش.", + "hw.restoreUnconfirmed": "تعذر تأكيد استعادة القيمة {value}.", + "hw.flashReadbackMismatch": "تعذرت قراءة القيمة {value} مرة أخرى. تمت استعادة القيمة الأصلية.", + "hw.noRestorableTarget": "لا يمكن كتابة إعداد بديل ثم استعادته بأمان.", "hw.liveHertz": "{hz} هرتز · {samples} عينة", "hw.finishTime": "اكتمل خلال {s} ثوانٍ", "hw.identity": "VID / PID", diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index ac6d0eb5..81f2df18 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -3,6 +3,14 @@ import { WOOTING_UI_STRINGS } from "./wooting-ui.ts"; import { VENDOR_KEYBOARD_UI_STRINGS } from "./vendor-keyboard-ui.ts"; export const de: Record = { + "x11.macroAssign": "Taste zuweisen", + "x11.macroRecording": "Drücke Tasten oder Maustasten. Drücke Esc zum Beenden.", + "x11.macroCapacity": "{n} von {max} Aktionseinheiten belegt. Verzögerungen über 1270 ms belegen zwei.", + "x11.macroBalance": "Für jeden Tastendruck muss es ein Loslassen geben. Prüfe die Reihenfolge der Schritte.", + "x11.macroShortenedRelease": "Die Aufzeichnung hat die Verzögerung vor dem Loslassen verkürzt, damit das Makro ins Limit passt. Prüfe das Timing der Schritte.", + "x11.macroStorage": "Die Makrobibliothek konnte in diesem Browser nicht aktualisiert werden.", + "x11.loadSettings": "X11-Einstellungen laden", + "x11.deepSleep": "Tiefschlaf", "receiver.assign": "Aktion zuweisen", "receiver.search": "Aktionen suchen", "receiver.all": "Alle", @@ -260,6 +268,14 @@ export const de: Record = { "hw.checking": "Prüfe {label}…", "hw.samplingPrompt": "Bewegen Sie die Maus in kleinen Kreisen über dieses Fenster — 5 Sekunden Sampling.", "hw.flashPrompt": "Eine Einstellung wird geschrieben, ausgelesen und dann wiederhergestellt — die Zeigergeschwindigkeit kann sich kurz ändern.", + "hw.x11ReadFailed": "Die X11-Einstellungen konnten nicht gelesen werden.", + "hw.deviceChanged": "Das ausgewählte Gerät hat sich während des Tests geändert.", + "hw.testSettingsChanged": "Das Gerät oder seine Einstellungen haben sich während des Tests geändert.", + "hw.flashNotSent": "Der Test ist fehlgeschlagen, bevor er den Schreibbefehl an den Flash-Speicher gesendet hat.", + "hw.flashUnconfirmed": "Der Test konnte den Schreibvorgang im Flash-Speicher nicht bestätigen.", + "hw.restoreUnconfirmed": "Die Wiederherstellung von {value} konnte nicht bestätigt werden.", + "hw.flashReadbackMismatch": "{value} konnte nicht zurückgelesen werden. Der ursprüngliche Wert wurde wiederhergestellt.", + "hw.noRestorableTarget": "Es lässt sich kein anderer Wert schreiben und anschließend sicher zurücksetzen.", "hw.liveHertz": "{hz} Hz · {samples} Samples", "hw.finishTime": "Fertig in {s} s", "hw.identity": "VID / PID", diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index 8defdbc9..983ea869 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -3,6 +3,14 @@ import { WOOTING_UI_STRINGS } from "./wooting-ui.ts"; import { VENDOR_KEYBOARD_UI_STRINGS } from "./vendor-keyboard-ui.ts"; export const es: Record = { + "x11.macroAssign": "Asignar al botón", + "x11.macroRecording": "Pulsa teclas o botones del ratón. Pulsa Esc para detener la grabación.", + "x11.macroCapacity": "Se usan {n} de {max} unidades de acción. Los retardos de más de 1270 ms usan dos.", + "x11.macroBalance": "Cada pulsación debe tener su liberación correspondiente. Revisa el orden de los pasos.", + "x11.macroShortenedRelease": "La grabadora acortó un retraso de liberación para respetar el límite de la macro. Revisa los tiempos de los pasos.", + "x11.macroStorage": "No se pudo actualizar la biblioteca de macros en este navegador.", + "x11.loadSettings": "Cargar ajustes del X11", + "x11.deepSleep": "Suspensión profunda", "receiver.assign": "Asignar una acción", "receiver.search": "Buscar acciones", "receiver.all": "Todo", @@ -260,6 +268,14 @@ export const es: Record = { "hw.checking": "Comprobando {label}…", "hw.samplingPrompt": "Mueve el ratón en círculos pequeños sobre esta ventana — 5 segundos de muestreo.", "hw.flashPrompt": "Se escribe un ajuste, se lee y luego se restaura — el puntero podría cambiar de velocidad brevemente.", + "hw.x11ReadFailed": "No se pudieron leer los ajustes del X11.", + "hw.deviceChanged": "El dispositivo seleccionado cambió durante la prueba.", + "hw.testSettingsChanged": "El dispositivo o sus ajustes cambiaron durante la prueba.", + "hw.flashNotSent": "La prueba falló antes de enviar la orden de escritura a la memoria flash.", + "hw.flashUnconfirmed": "La prueba no pudo confirmar la escritura en la memoria flash.", + "hw.restoreUnconfirmed": "No se pudo confirmar la restauración de {value}.", + "hw.flashReadbackMismatch": "No se pudo volver a leer {value}. Se restauró el valor original.", + "hw.noRestorableTarget": "No se puede escribir un valor alternativo y volver al original de forma segura.", "hw.liveHertz": "{hz} Hz · {samples} muestras", "hw.finishTime": "Finalizado en {s} s", "hw.identity": "VID / PID", diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index 0aa54390..84ff545e 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -3,6 +3,14 @@ import { WOOTING_UI_STRINGS } from "./wooting-ui.ts"; import { VENDOR_KEYBOARD_UI_STRINGS } from "./vendor-keyboard-ui.ts"; export const fr: Record = { + "x11.macroAssign": "Attribuer au bouton", + "x11.macroRecording": "Appuyez sur des touches ou des boutons de souris. Appuyez sur Échap pour arrêter.", + "x11.macroCapacity": "{n} unités d’action utilisées sur {max}. Les délais de plus de 1 270 ms en utilisent deux.", + "x11.macroBalance": "Chaque pression doit avoir un relâchement correspondant. Vérifiez l’ordre des étapes.", + "x11.macroShortenedRelease": "L’enregistreur a raccourci un délai avant relâchement pour respecter la limite de la macro. Vérifiez la durée des étapes.", + "x11.macroStorage": "Impossible de mettre à jour la bibliothèque de macros dans ce navigateur.", + "x11.loadSettings": "Charger les réglages de la X11", + "x11.deepSleep": "Veille profonde", "receiver.assign": "Attribuer une action", "receiver.search": "Rechercher des actions", "receiver.all": "Tout", @@ -260,6 +268,14 @@ export const fr: Record = { "hw.checking": "Vérification de {label}…", "hw.samplingPrompt": "Déplacez la souris en petits cercles au-dessus de cette fenêtre — 5 secondes d'échantillonnage.", "hw.flashPrompt": "Un réglage est écrit, relu puis restauré — le pointeur peut changer de vitesse brièvement.", + "hw.x11ReadFailed": "Impossible de lire les réglages de la X11.", + "hw.deviceChanged": "L’appareil sélectionné a changé pendant le test.", + "hw.testSettingsChanged": "L’appareil ou ses réglages ont changé pendant le test.", + "hw.flashNotSent": "Le test a échoué avant l’envoi de la commande d’écriture en mémoire flash.", + "hw.flashUnconfirmed": "Le test n’a pas pu confirmer l’écriture en mémoire flash.", + "hw.restoreUnconfirmed": "Impossible de confirmer le rétablissement de la valeur {value}.", + "hw.flashReadbackMismatch": "Impossible de relire la valeur {value}. La valeur d’origine a été rétablie.", + "hw.noRestorableTarget": "Aucune autre valeur ne peut être écrite avec un retour sûr à la valeur d’origine.", "hw.liveHertz": "{hz} Hz · {samples} échantillons", "hw.finishTime": "Terminé en {s} s", "hw.identity": "VID / PID", diff --git a/src/i18n/locales/ja.ts b/src/i18n/locales/ja.ts index 099e223a..b0f9370c 100644 --- a/src/i18n/locales/ja.ts +++ b/src/i18n/locales/ja.ts @@ -3,6 +3,14 @@ import { WOOTING_UI_STRINGS } from "./wooting-ui.ts"; import { VENDOR_KEYBOARD_UI_STRINGS } from "./vendor-keyboard-ui.ts"; export const ja: Record = { + "x11.macroAssign": "ボタンに割り当てる", + "x11.macroRecording": "キーやマウスボタンを押します。Esc キーで終了します。", + "x11.macroCapacity": "{max} アクション単位のうち {n} を使用中です。1,270 ms を超える遅延は 2 単位を使います。", + "x11.macroBalance": "押す操作ごとに対応する解放操作が必要です。手順の順序を確認してください。", + "x11.macroShortenedRelease": "マクロの上限に収まるよう、記録時にリリース前の待ち時間を短縮しました。各ステップのタイミングを確認してください。", + "x11.macroStorage": "このブラウザーのマクロライブラリを更新できませんでした。", + "x11.loadSettings": "X11 の設定を読み込む", + "x11.deepSleep": "ディープスリープ", "receiver.assign": "操作を割り当て", "receiver.search": "操作を検索", "receiver.all": "すべて", @@ -260,6 +268,14 @@ export const ja: Record = { "hw.checking": "{label} をチェック中…", "hw.samplingPrompt": "このウィンドウ上でマウスを小さく円を描くように動かしてください(5秒間のサンプリング)。", "hw.flashPrompt": "設定を書き込み、読み戻し、元に戻します。ポインターの速度が一時的に変わることがあります。", + "hw.x11ReadFailed": "X11の設定を読み取れませんでした。", + "hw.deviceChanged": "テスト中に選択したデバイスが変わりました。", + "hw.testSettingsChanged": "テスト中にデバイスまたはその設定が変わりました。", + "hw.flashNotSent": "フラッシュへの書き込み要求を送信する前にテストが失敗しました。", + "hw.flashUnconfirmed": "テストでフラッシュへの書き込みを確認できませんでした。", + "hw.restoreUnconfirmed": "{value}への復元を確認できませんでした。", + "hw.flashReadbackMismatch": "{value}を読み戻せませんでした。元の値に戻しました。", + "hw.noRestorableTarget": "別の値を書き込んでから元の値に安全に戻すことができません。", "hw.liveHertz": "{hz} Hz · {samples} サンプル", "hw.finishTime": "{s} 秒で完了", "hw.identity": "VID / PID", diff --git a/src/i18n/locales/ko.ts b/src/i18n/locales/ko.ts index 7c287b7e..4fb4a282 100644 --- a/src/i18n/locales/ko.ts +++ b/src/i18n/locales/ko.ts @@ -3,6 +3,14 @@ import { WOOTING_UI_STRINGS } from "./wooting-ui.ts"; import { VENDOR_KEYBOARD_UI_STRINGS } from "./vendor-keyboard-ui.ts"; export const ko: Record = { + "x11.macroAssign": "버튼에 할당", + "x11.macroRecording": "키나 마우스 버튼을 누르세요. Esc 키를 누르면 중지됩니다.", + "x11.macroCapacity": "동작 단위 {max}개 중 {n}개 사용 중입니다. 1,270ms를 초과하는 지연은 두 단위를 사용합니다.", + "x11.macroBalance": "누름마다 짝이 맞는 뗌 동작이 필요합니다. 단계 순서를 확인하세요.", + "x11.macroShortenedRelease": "매크로 용량에 맞추기 위해 녹화 중 입력을 놓기 전의 대기 시간이 줄었습니다. 단계별 시간을 확인하세요.", + "x11.macroStorage": "이 브라우저의 매크로 라이브러리를 업데이트하지 못했습니다.", + "x11.loadSettings": "X11 설정 불러오기", + "x11.deepSleep": "깊은 절전", "receiver.assign": "동작 지정", "receiver.search": "동작 검색", "receiver.all": "전체", @@ -260,6 +268,14 @@ export const ko: Record = { "hw.checking": "{label} 확인 중…", "hw.samplingPrompt": "이 창 위에서 마우스를 작은 원 모양으로 움직이세요 — 5초간 샘플링합니다.", "hw.flashPrompt": "설정을 쓰고, 다시 읽은 후 복원합니다. 포인터 속도가 잠깐 바뀔 수 있습니다.", + "hw.x11ReadFailed": "X11 설정을 읽을 수 없습니다.", + "hw.deviceChanged": "테스트 중 선택한 장치가 바뀌었습니다.", + "hw.testSettingsChanged": "테스트 중 장치 또는 장치 설정이 바뀌었습니다.", + "hw.flashNotSent": "플래시 쓰기 명령을 보내기 전에 테스트가 실패했습니다.", + "hw.flashUnconfirmed": "테스트에서 플래시 쓰기를 확인할 수 없습니다.", + "hw.restoreUnconfirmed": "{value}(으)로 복원했는지 확인할 수 없습니다.", + "hw.flashReadbackMismatch": "{value} 값을 다시 읽을 수 없습니다. 원래 값은 복원했습니다.", + "hw.noRestorableTarget": "다른 값을 쓴 뒤 원래 값으로 안전하게 되돌릴 수 없습니다.", "hw.liveHertz": "{hz} Hz · {samples}개 샘플", "hw.finishTime": "{s}초 만에 완료", "hw.identity": "VID / PID", diff --git a/src/i18n/locales/pt.ts b/src/i18n/locales/pt.ts index 538d6e65..8c0005fe 100644 --- a/src/i18n/locales/pt.ts +++ b/src/i18n/locales/pt.ts @@ -3,6 +3,14 @@ import { WOOTING_UI_STRINGS } from "./wooting-ui.ts"; import { VENDOR_KEYBOARD_UI_STRINGS } from "./vendor-keyboard-ui.ts"; export const pt: Record = { + "x11.macroAssign": "Atribuir ao botão", + "x11.macroRecording": "Prima teclas ou botões do rato. Prima Esc para parar.", + "x11.macroCapacity": "{n} de {max} unidades de ação usadas. Atrasos superiores a 1270 ms usam duas.", + "x11.macroBalance": "Cada pressão precisa da libertação correspondente. Verifique a ordem dos passos.", + "x11.macroShortenedRelease": "O gravador encurtou um atraso de liberação para respeitar o limite da macro. Confira o tempo de cada etapa.", + "x11.macroStorage": "Não foi possível atualizar a biblioteca de macros neste navegador.", + "x11.loadSettings": "Carregar definições do X11", + "x11.deepSleep": "Suspensão profunda", "receiver.assign": "Atribuir uma ação", "receiver.search": "Pesquisar ações", "receiver.all": "Todas", @@ -260,6 +268,14 @@ export const pt: Record = { "hw.checking": "Verificando {label}…", "hw.samplingPrompt": "Mova o mouse em círculos pequenos sobre esta janela — 5 segundos de amostragem.", "hw.flashPrompt": "Uma configuração é gravada, relida e restaurada — o ponteiro pode mudar de velocidade por um instante.", + "hw.x11ReadFailed": "Não foi possível ler as configurações do X11.", + "hw.deviceChanged": "O dispositivo selecionado mudou durante o teste.", + "hw.testSettingsChanged": "O dispositivo ou suas configurações mudaram durante o teste.", + "hw.flashNotSent": "O teste falhou antes de enviar o comando de gravação na memória flash.", + "hw.flashUnconfirmed": "O teste não conseguiu confirmar a gravação na memória flash.", + "hw.restoreUnconfirmed": "Não foi possível confirmar a restauração para {value}.", + "hw.flashReadbackMismatch": "Não foi possível reler {value}. O valor original foi restaurado.", + "hw.noRestorableTarget": "Não é possível gravar outro valor e voltar ao original com segurança.", "hw.liveHertz": "{hz} Hz · {samples} amostras", "hw.finishTime": "Concluído em {s} s", "hw.identity": "VID / PID", diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index ecda7d53..0fdfc34f 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -3,6 +3,14 @@ import { WOOTING_UI_STRINGS } from "./wooting-ui.ts"; import { VENDOR_KEYBOARD_UI_STRINGS } from "./vendor-keyboard-ui.ts"; export const ru: Record = { + "x11.macroAssign": "Назначить кнопке", + "x11.macroRecording": "Нажимайте клавиши или кнопки мыши. Нажмите Esc для остановки.", + "x11.macroCapacity": "Использовано {n} из {max} единиц действия. Задержки более 1270 мс занимают две единицы.", + "x11.macroBalance": "Каждому нажатию должно соответствовать отпускание. Проверьте порядок шагов.", + "x11.macroShortenedRelease": "При записи задержка перед отпусканием была сокращена, чтобы уложиться в лимит макроса. Проверьте время шагов.", + "x11.macroStorage": "Не удалось обновить библиотеку макросов в этом браузере.", + "x11.loadSettings": "Загрузить настройки X11", + "x11.deepSleep": "Глубокий сон", "receiver.assign": "Назначить действие", "receiver.search": "Поиск действий", "receiver.all": "Все", @@ -260,6 +268,14 @@ export const ru: Record = { "hw.checking": "Проверка: {label}…", "hw.samplingPrompt": "Двигайте мышь небольшими кругами над этим окном — выборка займёт 5 секунд.", "hw.flashPrompt": "Настройка записывается, считывается и восстанавливается — скорость указателя может ненадолго измениться.", + "hw.x11ReadFailed": "Не удалось прочитать настройки X11.", + "hw.deviceChanged": "Во время проверки изменилось выбранное устройство.", + "hw.testSettingsChanged": "Во время проверки изменилось устройство или его настройки.", + "hw.flashNotSent": "Проверка завершилась ошибкой до отправки команды записи во флеш-память.", + "hw.flashUnconfirmed": "Не удалось подтвердить запись во флеш-память.", + "hw.restoreUnconfirmed": "Не удалось подтвердить восстановление значения {value}.", + "hw.flashReadbackMismatch": "Не удалось повторно прочитать значение {value}. Исходное значение восстановлено.", + "hw.noRestorableTarget": "Невозможно записать другое значение и безопасно вернуть исходное.", "hw.liveHertz": "{hz} Гц · выборок: {samples}", "hw.finishTime": "Завершено за {s} с", "hw.identity": "VID / PID", diff --git a/src/i18n/locales/tr.ts b/src/i18n/locales/tr.ts index 56ebe0c3..c0ad1a62 100644 --- a/src/i18n/locales/tr.ts +++ b/src/i18n/locales/tr.ts @@ -3,6 +3,14 @@ import { WOOTING_UI_STRINGS } from "./wooting-ui.ts"; import { VENDOR_KEYBOARD_UI_STRINGS } from "./vendor-keyboard-ui.ts"; export const tr: Record = { + "x11.macroAssign": "Düğmeye ata", + "x11.macroRecording": "Klavye tuşlarına veya fare düğmelerine basın. Durdurmak için Esc tuşuna basın.", + "x11.macroCapacity": "{max} işlem biriminin {n} tanesi kullanıldı. 1270 ms üzerindeki gecikmeler iki birim kullanır.", + "x11.macroBalance": "Her basışın karşılık gelen bir bırakma adımı olmalıdır. Adımların sırasını kontrol edin.", + "x11.macroShortenedRelease": "Kayıt aracı, makro sınırına sığması için bir bırakma gecikmesini kısalttı. Adımların zamanlamasını kontrol et.", + "x11.macroStorage": "Bu tarayıcıdaki makro kitaplığı güncellenemedi.", + "x11.loadSettings": "X11 ayarlarını yükle", + "x11.deepSleep": "Derin uyku", "receiver.assign": "Bir eylem ata", "receiver.search": "Eylem ara", "receiver.all": "Tümü", @@ -259,6 +267,14 @@ export const tr: Record = { "hw.checking": "{label} kontrol ediliyor…", "hw.samplingPrompt": "Fareyi bu pencere üzerinde küçük daireler çizerek hareket ettirin. Örnekleme 5 saniye sürer.", "hw.flashPrompt": "Bir ayar yazılıp geri okunacak, ardından eski değerine döndürülecek. İşaretçinin davranışı kısa süreliğine değişebilir.", + "hw.x11ReadFailed": "X11 ayarları okunamadı.", + "hw.deviceChanged": "Test sırasında seçili cihaz değişti.", + "hw.testSettingsChanged": "Test sırasında cihaz veya ayarları değişti.", + "hw.flashNotSent": "Test, flash belleğe yazma komutunu göndermeden önce başarısız oldu.", + "hw.flashUnconfirmed": "Test, flash belleğe yazmayı doğrulayamadı.", + "hw.restoreUnconfirmed": "{value} değerine geri dönüldüğü doğrulanamadı.", + "hw.flashReadbackMismatch": "{value} değeri geri okunamadı. İlk değer geri yüklendi.", + "hw.noRestorableTarget": "Başka bir değer yazıp ilk değere güvenle dönmek mümkün değil.", "hw.liveHertz": "{hz} Hz · {samples} örnek", "hw.finishTime": "{s} saniyede tamamlandı", "hw.identity": "VID / PID", diff --git a/src/i18n/locales/vi.ts b/src/i18n/locales/vi.ts index fe032505..aefbe0c0 100644 --- a/src/i18n/locales/vi.ts +++ b/src/i18n/locales/vi.ts @@ -3,6 +3,14 @@ import { WOOTING_UI_STRINGS } from "./wooting-ui.ts"; import { VENDOR_KEYBOARD_UI_STRINGS } from "./vendor-keyboard-ui.ts"; export const vi: Record = { + "x11.macroAssign": "Gán cho nút", + "x11.macroRecording": "Nhấn phím hoặc nút chuột. Nhấn Esc để dừng.", + "x11.macroCapacity": "Đã dùng {n} trên {max} đơn vị thao tác. Độ trễ trên 1270 ms dùng hai đơn vị.", + "x11.macroBalance": "Mỗi lần nhấn phải có thao tác nhả tương ứng. Hãy kiểm tra thứ tự các bước.", + "x11.macroShortenedRelease": "Trình ghi đã rút ngắn độ trễ trước khi nhả phím hoặc nút để vừa giới hạn macro. Hãy xem lại thời gian của các bước.", + "x11.macroStorage": "Không thể cập nhật thư viện macro trong trình duyệt này.", + "x11.loadSettings": "Tải cài đặt X11", + "x11.deepSleep": "Ngủ sâu", "receiver.assign": "Gán thao tác", "receiver.search": "Tìm thao tác", "receiver.all": "Tất cả", @@ -1222,6 +1230,14 @@ export const vi: Record = { "hw.checking": "Đang kiểm tra {label}…", "hw.samplingPrompt": "Di chuyển chuột theo vòng tròn nhỏ trên cửa sổ này — lấy mẫu trong 5 giây.", "hw.flashPrompt": "Một thiết lập được ghi, đọc lại rồi khôi phục — con trỏ có thể thay đổi tốc độ trong giây lát.", + "hw.x11ReadFailed": "Không thể đọc cài đặt X11.", + "hw.deviceChanged": "Thiết bị đã chọn thay đổi trong khi kiểm tra.", + "hw.testSettingsChanged": "Thiết bị hoặc cài đặt của thiết bị thay đổi trong khi kiểm tra.", + "hw.flashNotSent": "Kiểm tra thất bại trước khi gửi lệnh ghi vào bộ nhớ flash.", + "hw.flashUnconfirmed": "Không thể xác nhận thao tác ghi vào bộ nhớ flash.", + "hw.restoreUnconfirmed": "Không thể xác nhận đã khôi phục về giá trị {value}.", + "hw.flashReadbackMismatch": "Không thể đọc lại giá trị {value}. Đã khôi phục giá trị ban đầu.", + "hw.noRestorableTarget": "Không thể ghi giá trị khác rồi khôi phục an toàn về giá trị ban đầu.", "hw.liveHertz": "{hz} Hz · {samples} mẫu", "hw.finishTime": "Hoàn tất trong {s} giây", "hw.identity": "VID / PID", diff --git a/src/i18n/locales/zh.ts b/src/i18n/locales/zh.ts index a74c81c1..5f444e14 100644 --- a/src/i18n/locales/zh.ts +++ b/src/i18n/locales/zh.ts @@ -3,6 +3,14 @@ import { WOOTING_UI_STRINGS } from "./wooting-ui.ts"; import { VENDOR_KEYBOARD_UI_STRINGS } from "./vendor-keyboard-ui.ts"; export const zh: Record = { + "x11.macroAssign": "分配到按键", + "x11.macroRecording": "按下键盘键或鼠标键。按 Esc 停止录制。", + "x11.macroCapacity": "已使用 {n}/{max} 个动作单元。超过 1270 毫秒的延迟会占用两个单元。", + "x11.macroBalance": "每次按下都需要有对应的释放。请检查步骤顺序。", + "x11.macroShortenedRelease": "为满足宏的容量限制,录制时缩短了一次释放前的延迟。请检查步骤的时序。", + "x11.macroStorage": "无法更新此浏览器中的宏库。", + "x11.loadSettings": "读取 X11 设置", + "x11.deepSleep": "深度休眠", "receiver.assign": "分配操作", "receiver.search": "搜索操作", "receiver.all": "全部", @@ -260,6 +268,14 @@ export const zh: Record = { "hw.checking": "正在检查 {label}…", "hw.samplingPrompt": "在此窗口上方小范围画圈移动鼠标——采样 5 秒。", "hw.flashPrompt": "将写入一项设置、读回后再恢复——指针速度可能短暂变化。", + "hw.x11ReadFailed": "无法读取 X11 设置。", + "hw.deviceChanged": "测试期间所选设备发生了变化。", + "hw.testSettingsChanged": "测试期间设备或其设置发生了变化。", + "hw.flashNotSent": "测试在发送闪存写入命令前失败。", + "hw.flashUnconfirmed": "测试无法确认闪存写入成功。", + "hw.restoreUnconfirmed": "无法确认已恢复为 {value}。", + "hw.flashReadbackMismatch": "无法读回 {value}。原值已恢复。", + "hw.noRestorableTarget": "无法写入其他值并安全恢复原值。", "hw.liveHertz": "{hz} 赫兹 · {samples} 个样本", "hw.finishTime": "用时 {s} 秒完成", "hw.identity": "VID / PID", diff --git a/src/shared/CardSlot.tsx b/src/shared/CardSlot.tsx index 6315422a..51ac7d47 100644 --- a/src/shared/CardSlot.tsx +++ b/src/shared/CardSlot.tsx @@ -69,7 +69,7 @@ export function iconForCard(key: string): LucideIcon | null { for (const [pattern, icon] of FEATURE_ICONS) if (pattern.test(key)) return icon; return null; } -const WIDE = new Set(["dpi", "eggpolling", "eggcpi", "eggbuttons", "ksnake-macros", "wallhack-macros", "incott-macros", "lighting-tab", "button-mapping", "keychron-dynamic", "keychron-receiver-buttons"]); +const WIDE = new Set(["dpi", "eggpolling", "eggcpi", "eggbuttons", "ksnake-macros", "wallhack-macros", "incott-macros", "x11-macros", "lighting-tab", "button-mapping", "keychron-dynamic", "keychron-receiver-buttons"]); export function slotCards(cards: readonly ReactNode[]): ReactNode[] { return Children.toArray(cards).map((card) => { diff --git a/src/styles/areas/library.css b/src/styles/areas/library.css index 64ead379..6e5b3add 100644 --- a/src/styles/areas/library.css +++ b/src/styles/areas/library.css @@ -119,7 +119,7 @@ #finalmouse-profiles .profile-rename { margin-top: 8px; } #finalmouse-profiles .profile-rename input { min-width: 0; flex: 1; } -:is(#ksnake-macro-settings, #wallhack-macro-settings, #incott-macro-settings, #xiaomi-macro-settings, #leobog-macro-settings) { grid-column: 1 / -1; gap: 16px; } +:is(#ksnake-macro-settings, #wallhack-macro-settings, #incott-macro-settings, #xiaomi-macro-settings, #leobog-macro-settings, #x11-macro-settings) { grid-column: 1 / -1; gap: 16px; } .ksnake-macro-lead { margin-top: 4px; color: var(--text-3); font-size: var(--fs-meta); font-weight: 400; line-height: 1.5; } .ksnake-macro-notice { padding: 12px; background: var(--well); border-radius: var(--r-sm); color: var(--text-2); font-size: var(--fs-meta); line-height: 1.5; } .ksnake-macro-slot-picker { display: flex; flex-wrap: wrap; align-items: center; gap: 12px 24px; color: var(--text-2); font-size: var(--fs-meta); }