From e8ef93e8b149b842d55267937c3b8967ca43221c Mon Sep 17 00:00:00 2001
From: Fear2Die
Date: Fri, 27 Nov 2026 17:57:55 +0100
Subject: [PATCH 1/7] Add X11 web controls and read settings before
hardware-test writes
---
src/device/controller.ts | 104 +++++++
src/device/traits.ts | 1 +
src/device/x11-macros.test.ts | 31 ++
src/device/x11-macros.ts | 134 +++++++++
src/features/devices/DeviceHero.tsx | 5 +
src/features/devices/OverviewPage.tsx | 11 +-
src/features/devices/cards/AdvancedCards.tsx | 18 +-
src/features/devices/cards/LightingCard.tsx | 3 +-
src/features/devices/cards/X11MacroCard.tsx | 270 ++++++++++++++++++
.../devices/cards/X11ShortcutCard.tsx | 54 ++++
src/features/devices/cards/availability.ts | 5 +-
src/features/devices/workspace-tabs.ts | 2 +-
.../hardware-test/HardwareTestPage.tsx | 95 +++---
.../hardware-test-report.test.ts | 11 +
.../hardware-test/hardware-test-report.ts | 14 +-
src/i18n/index.ts | 7 +
src/i18n/locales/ar.ts | 7 +
src/i18n/locales/de.ts | 7 +
src/i18n/locales/es.ts | 7 +
src/i18n/locales/fr.ts | 7 +
src/i18n/locales/ja.ts | 7 +
src/i18n/locales/ko.ts | 7 +
src/i18n/locales/pt.ts | 7 +
src/i18n/locales/ru.ts | 7 +
src/i18n/locales/tr.ts | 7 +
src/i18n/locales/vi.ts | 7 +
src/i18n/locales/zh.ts | 7 +
src/styles/areas/library.css | 2 +-
28 files changed, 794 insertions(+), 50 deletions(-)
create mode 100644 src/device/x11-macros.test.ts
create mode 100644 src/device/x11-macros.ts
create mode 100644 src/features/devices/cards/X11MacroCard.tsx
create mode 100644 src/features/devices/cards/X11ShortcutCard.tsx
diff --git a/src/device/controller.ts b/src/device/controller.ts
index 71e52d19..faa639e1 100644
--- a/src/device/controller.ts
+++ b/src/device/controller.ts
@@ -6879,6 +6879,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);
@@ -6915,6 +6928,56 @@ export async function refreshKeychronReceiver(): Promise {
finally { refreshInProgress = false; }
}
+export async function loadX11Settings(): Promise {
+ const client = activeSettingsClient();
+ if (!client || !("readX11Configuration" in client) || !latestDeviceStatus?.ui?.x11ConfigurationAvailable
+ || settingInProgress || activationInProgress || hasPendingChanges() || gameProfileDraft) return false;
+ const device = activeDevice;
+ const label = st("x11.loadSettings");
+ const stillActive = (): boolean => 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;
+ refreshInProgress = true;
+ settingInProgress = true;
+ setReadStatus(label);
+ emit();
+ 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();
+ }
+ };
+ 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;
+ }
+}
+
export function applyKeychronReceiverLighting(value: MouseLighting): void {
if (!latestDeviceStatus?.keychronReceiver) return;
const next = structuredClone(value);
@@ -8059,6 +8122,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
diff --git a/src/device/traits.ts b/src/device/traits.ts
index 7f084500..e5ad4970 100644
--- a/src/device/traits.ts
+++ b/src/device/traits.ts
@@ -160,6 +160,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-macros.test.ts b/src/device/x11-macros.test.ts
new file mode 100644
index 00000000..3ea955d3
--- /dev/null
+++ b/src/device/x11-macros.test.ts
@@ -0,0 +1,31 @@
+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(recordX11MacroEvent(session, 4, false, 2_000), 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..fcc0fa20
--- /dev/null
+++ b/src/device/x11-macros.ts
@@ -0,0 +1,134 @@
+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;
+}
+
+export function startX11MacroRecording(): Recording {
+ return { steps: [], held: new Set(), units: 0, lastAt: null };
+}
+
+/** 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.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..dd2f810a 100644
--- a/src/features/devices/DeviceHero.tsx
+++ b/src/features/devices/DeviceHero.tsx
@@ -74,6 +74,11 @@ 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 8c9bcd53..88392c25 100644
--- a/src/features/devices/cards/AdvancedCards.tsx
+++ b/src/features/devices/cards/AdvancedCards.tsx
@@ -302,6 +302,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 (
@@ -332,6 +333,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}
);
}
@@ -3619,6 +3633,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.
@@ -3663,7 +3679,7 @@ export function ButtonMappingCard({ snapshot }: { snapshot: ControlSnapshot }):
);
-}
\ 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..74287dba 100644
--- a/src/features/hardware-test/hardware-test-report.ts
+++ b/src/features/hardware-test/hardware-test-report.ts
@@ -329,12 +329,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 +345,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 +461,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 9a70e370..c1f5e89c 100644
--- a/src/i18n/index.ts
+++ b/src/i18n/index.ts
@@ -6,6 +6,13 @@ 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.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",
diff --git a/src/i18n/locales/ar.ts b/src/i18n/locales/ar.ts
index cdfe7869..b8c7d69c 100644
--- a/src/i18n/locales/ar.ts
+++ b/src/i18n/locales/ar.ts
@@ -3,6 +3,13 @@ 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.macroStorage": "تعذر تحديث مكتبة وحدات الماكرو في هذا المتصفح.",
+ "x11.loadSettings": "تحميل إعدادات X11",
+ "x11.deepSleep": "السكون العميق",
"receiver.assign": "تعيين إجراء",
"receiver.search": "البحث عن إجراءات",
"receiver.all": "الكل",
diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts
index f2075a7d..bf4cfb44 100644
--- a/src/i18n/locales/de.ts
+++ b/src/i18n/locales/de.ts
@@ -3,6 +3,13 @@ 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.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",
diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts
index 34a7e0a3..8bd6b6bd 100644
--- a/src/i18n/locales/es.ts
+++ b/src/i18n/locales/es.ts
@@ -3,6 +3,13 @@ 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.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",
diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts
index e801b8a9..5ff68371 100644
--- a/src/i18n/locales/fr.ts
+++ b/src/i18n/locales/fr.ts
@@ -3,6 +3,13 @@ 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.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",
diff --git a/src/i18n/locales/ja.ts b/src/i18n/locales/ja.ts
index 782ad07a..a5b90059 100644
--- a/src/i18n/locales/ja.ts
+++ b/src/i18n/locales/ja.ts
@@ -3,6 +3,13 @@ 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.macroStorage": "このブラウザーのマクロライブラリを更新できませんでした。",
+ "x11.loadSettings": "X11 の設定を読み込む",
+ "x11.deepSleep": "ディープスリープ",
"receiver.assign": "操作を割り当て",
"receiver.search": "操作を検索",
"receiver.all": "すべて",
diff --git a/src/i18n/locales/ko.ts b/src/i18n/locales/ko.ts
index 3006db45..52452926 100644
--- a/src/i18n/locales/ko.ts
+++ b/src/i18n/locales/ko.ts
@@ -3,6 +3,13 @@ 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.macroStorage": "이 브라우저의 매크로 라이브러리를 업데이트하지 못했습니다.",
+ "x11.loadSettings": "X11 설정 불러오기",
+ "x11.deepSleep": "깊은 절전",
"receiver.assign": "동작 지정",
"receiver.search": "동작 검색",
"receiver.all": "전체",
diff --git a/src/i18n/locales/pt.ts b/src/i18n/locales/pt.ts
index 62f96c86..20093889 100644
--- a/src/i18n/locales/pt.ts
+++ b/src/i18n/locales/pt.ts
@@ -3,6 +3,13 @@ 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.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",
diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts
index fd59167e..3eea6bb7 100644
--- a/src/i18n/locales/ru.ts
+++ b/src/i18n/locales/ru.ts
@@ -3,6 +3,13 @@ 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.macroStorage": "Не удалось обновить библиотеку макросов в этом браузере.",
+ "x11.loadSettings": "Загрузить настройки X11",
+ "x11.deepSleep": "Глубокий сон",
"receiver.assign": "Назначить действие",
"receiver.search": "Поиск действий",
"receiver.all": "Все",
diff --git a/src/i18n/locales/tr.ts b/src/i18n/locales/tr.ts
index ed437bdb..a07fbe4c 100644
--- a/src/i18n/locales/tr.ts
+++ b/src/i18n/locales/tr.ts
@@ -3,6 +3,13 @@ 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.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ü",
diff --git a/src/i18n/locales/vi.ts b/src/i18n/locales/vi.ts
index a03e1ec3..40ef585f 100644
--- a/src/i18n/locales/vi.ts
+++ b/src/i18n/locales/vi.ts
@@ -3,6 +3,13 @@ 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.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ả",
diff --git a/src/i18n/locales/zh.ts b/src/i18n/locales/zh.ts
index be9c3860..7f8312d9 100644
--- a/src/i18n/locales/zh.ts
+++ b/src/i18n/locales/zh.ts
@@ -3,6 +3,13 @@ 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.macroStorage": "无法更新此浏览器中的宏库。",
+ "x11.loadSettings": "读取 X11 设置",
+ "x11.deepSleep": "深度休眠",
"receiver.assign": "分配操作",
"receiver.search": "搜索操作",
"receiver.all": "全部",
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); }
From 0719e9dbadcf8c8449496564bfb2ec199bcca922 Mon Sep 17 00:00:00 2001
From: Fear2Die
Date: Fri, 4 Dec 2026 13:15:36 +0100
Subject: [PATCH 2/7] Load X11 settings once when the receiver connects
---
src/device/controller.ts | 50 +++++++----
src/device/x11-connection-read.test.ts | 110 +++++++++++++++++++++++++
2 files changed, 146 insertions(+), 14 deletions(-)
create mode 100644 src/device/x11-connection-read.test.ts
diff --git a/src/device/controller.ts b/src/device/controller.ts
index faa639e1..cd1f2e49 100644
--- a/src/device/controller.ts
+++ b/src/device/controller.ts
@@ -427,6 +427,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";
@@ -4031,6 +4033,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. */
@@ -4532,6 +4536,7 @@ function activateClient(target: SupportedClient | KeyboardClient, autoConnect =
} finally {
activationInProgress = false;
}
+ maybeLoadX11ConnectionSettings();
});
activationQueue = run.then(() => undefined, () => undefined);
return run;
@@ -6928,22 +6933,31 @@ export async function refreshKeychronReceiver(): Promise {
finally { refreshInProgress = false; }
}
-export async function loadX11Settings(): Promise {
+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 false;
+ || settingInProgress || activationInProgress || hasPendingChanges() || gameProfileDraft) return Promise.resolve(false);
const device = activeDevice;
const label = st("x11.loadSettings");
- const stillActive = (): boolean => activeSettingsClient() === client && activeDevice === device;
+ 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);
- emit();
try {
const status = await client.readX11Configuration();
if (!stillActive()) return false;
@@ -6965,17 +6979,24 @@ export async function loadX11Settings(): Promise {
emit();
}
};
- 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"));
+ 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;
- });
- } 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 {
@@ -8324,6 +8345,7 @@ async function refreshStatus(): Promise {
} finally {
refreshInProgress = false;
}
+ maybeLoadX11ConnectionSettings();
}
async function loadPreviewEntries(): Promise {
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);
+});
From 662b1d47f16a7fe21681d7bb447553265583e943 Mon Sep 17 00:00:00 2001
From: Fear2Die
Date: Fri, 4 Dec 2026 13:37:05 +0100
Subject: [PATCH 3/7] Localize X11 diagnostics and mark unread button mappings
---
src/features/devices/cards/AdvancedCards.tsx | 2 +-
.../hardware-test/HardwareTestPage.tsx | 20 +++++++++----------
src/i18n/index.ts | 7 +++++++
src/i18n/locales/ar.ts | 7 +++++++
src/i18n/locales/de.ts | 7 +++++++
src/i18n/locales/es.ts | 7 +++++++
src/i18n/locales/fr.ts | 7 +++++++
src/i18n/locales/ja.ts | 7 +++++++
src/i18n/locales/ko.ts | 7 +++++++
src/i18n/locales/pt.ts | 7 +++++++
src/i18n/locales/ru.ts | 7 +++++++
src/i18n/locales/tr.ts | 7 +++++++
src/i18n/locales/vi.ts | 7 +++++++
src/i18n/locales/zh.ts | 7 +++++++
14 files changed, 95 insertions(+), 11 deletions(-)
diff --git a/src/features/devices/cards/AdvancedCards.tsx b/src/features/devices/cards/AdvancedCards.tsx
index 88392c25..ff300b2b 100644
--- a/src/features/devices/cards/AdvancedCards.tsx
+++ b/src/features/devices/cards/AdvancedCards.tsx
@@ -3696,7 +3696,7 @@ export function ButtonMappingCard({ snapshot }: { snapshot: ControlSnapshot }):
{!options.includes(assigned) && (
)}
{isRival650
diff --git a/src/features/hardware-test/HardwareTestPage.tsx b/src/features/hardware-test/HardwareTestPage.tsx
index dc0cc303..7a73b639 100644
--- a/src/features/hardware-test/HardwareTestPage.tsx
+++ b/src/features/hardware-test/HardwareTestPage.tsx
@@ -136,7 +136,7 @@ export function HardwareTestPage({ snapshot }: { snapshot: ControlSnapshot }): R
key: "x11Configuration",
label,
status: x11SettingsRead ? "pass" : "fail",
- detail: x11SettingsRead ? null : "Could not finish reading the X11 settings.",
+ detail: x11SettingsRead ? null : t(locale, "hw.x11ReadFailed"),
};
results.push(check);
updateStage(id, { state: check.status, detail: check.detail });
@@ -264,27 +264,27 @@ export function HardwareTestPage({ snapshot }: { snapshot: ControlSnapshot }): R
}
const live = control.getSnapshot();
if (!sameDevice() || live.settingsPending || live.gameProfileDraft || live.settingInProgress) {
- return { setting: leg.setting, current: leg.current, target: leg.target, status: "skip", detail: "The device or its pending settings changed during the test." };
+ return { setting: leg.setting, current: leg.current, target: leg.target, status: "skip", detail: t(locale, "hw.testSettingsChanged") };
}
if (leg.read() !== leg.currentRaw) {
- return { setting: leg.setting, current: leg.current, target: leg.target, status: "skip", detail: "The original value changed during the test." };
+ return { setting: leg.setting, current: leg.current, target: leg.target, status: "skip", detail: t(locale, "hw.testSettingsChanged") };
}
if (!leg.stageTarget()) {
return { setting: leg.setting, current: leg.current, target: leg.target, status: "fail", detail: "the write was rejected by the driver." };
}
const written = await control.flashPendingChanges().catch(() => "failed" as const);
if (written !== "written") {
- return { setting: leg.setting, current: leg.current, target: leg.target, status: "fail", detail: "The test could not confirm the flash write." };
+ return { setting: leg.setting, current: leg.current, target: leg.target, status: "fail", detail: t(locale, "hw.flashUnconfirmed") };
}
const targetRead = sameDevice() && leg.read() === leg.targetRaw;
const restore = sameDevice() && !control.getSnapshot().settingsPending && leg.stageRestore()
? await control.flashPendingChanges().catch(() => "failed" as const)
: "stale";
if ((restore !== "written" && restore !== "unchanged") || !sameDevice() || leg.read() !== leg.currentRaw) {
- return { setting: leg.setting, current: leg.current, target: leg.target, status: "fail", detail: `Could not confirm the restore to ${leg.current}.` };
+ return { setting: leg.setting, current: leg.current, target: leg.target, status: "fail", detail: tp(locale, "hw.restoreUnconfirmed", { value: leg.current }) };
}
if (!targetRead) {
- return { setting: leg.setting, current: leg.current, target: leg.target, status: "fail", detail: `The test did not read back ${leg.target}. The original value was restored.` };
+ 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}` };
};
@@ -296,9 +296,9 @@ export function HardwareTestPage({ snapshot }: { snapshot: ControlSnapshot }): R
} else {
const live = control.getSnapshot();
if (!sameDevice()) {
- flashResult = flashWriteResult({ skipped: true, skippedReason: "the selected device changed during the test." });
+ flashResult = flashWriteResult({ skipped: true, skippedReason: t(locale, "hw.deviceChanged") });
} else if (needsX11Read && !x11SettingsRead) {
- flashResult = flashWriteResult({ skipped: true, skippedReason: "could not read the original X11 settings." });
+ flashResult = flashWriteResult({ skipped: true, skippedReason: t(locale, "hw.x11ReadFailed") });
} else if (!live.status) {
flashResult = flashWriteResult({ skipped: true, skippedReason: "no live device status — cannot round-trip a write." });
} else if (live.settingsPending || live.gameProfileDraft) {
@@ -313,7 +313,7 @@ export function HardwareTestPage({ snapshot }: { snapshot: ControlSnapshot }): R
} 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 can be written and safely restored." });
+ legs.push({ setting: "DPI", current: `${dpiCurrent.toLocaleString()} DPI`, target: "—", status: "skip", detail: t(locale, "hw.noRestorableTarget") });
} else {
legs.push(await runFlashLeg({
setting: "DPI",
@@ -335,7 +335,7 @@ export function HardwareTestPage({ snapshot }: { snapshot: ControlSnapshot }): R
} else {
const rateTarget = pickFlashPollRateTarget(rateCurrent, live.status.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 can be written and safely restored." });
+ 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",
diff --git a/src/i18n/index.ts b/src/i18n/index.ts
index c1f5e89c..cdaf1a1a 100644
--- a/src/i18n/index.ts
+++ b/src/i18n/index.ts
@@ -323,6 +323,13 @@ 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.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 b8c7d69c..51c3ed71 100644
--- a/src/i18n/locales/ar.ts
+++ b/src/i18n/locales/ar.ts
@@ -266,6 +266,13 @@ export const ar: Record = {
"hw.checking": "جارٍ التحقق من {label}…",
"hw.samplingPrompt": "حرّك الماوس بدوائر صغيرة فوق هذه النافذة — أخذ العينات يستغرق 5 ثوانٍ.",
"hw.flashPrompt": "يُكتب إعداد، ثم يُقرأ من جديد ويُستعاد — قد تتغير سرعة المؤشر للحظات.",
+ "hw.x11ReadFailed": "تعذرت قراءة إعدادات X11.",
+ "hw.deviceChanged": "تغيّر الجهاز المحدد أثناء الاختبار.",
+ "hw.testSettingsChanged": "تغيّر الجهاز أو إعداداته أثناء الاختبار.",
+ "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 bf4cfb44..05fca2f8 100644
--- a/src/i18n/locales/de.ts
+++ b/src/i18n/locales/de.ts
@@ -267,6 +267,13 @@ 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.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 8bd6b6bd..3b564baf 100644
--- a/src/i18n/locales/es.ts
+++ b/src/i18n/locales/es.ts
@@ -267,6 +267,13 @@ 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.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 5ff68371..6e6551cc 100644
--- a/src/i18n/locales/fr.ts
+++ b/src/i18n/locales/fr.ts
@@ -267,6 +267,13 @@ 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.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 a5b90059..e5741e05 100644
--- a/src/i18n/locales/ja.ts
+++ b/src/i18n/locales/ja.ts
@@ -267,6 +267,13 @@ export const ja: Record = {
"hw.checking": "{label} をチェック中…",
"hw.samplingPrompt": "このウィンドウ上でマウスを小さく円を描くように動かしてください(5秒間のサンプリング)。",
"hw.flashPrompt": "設定を書き込み、読み戻し、元に戻します。ポインターの速度が一時的に変わることがあります。",
+ "hw.x11ReadFailed": "X11の設定を読み取れませんでした。",
+ "hw.deviceChanged": "テスト中に選択したデバイスが変わりました。",
+ "hw.testSettingsChanged": "テスト中にデバイスまたはその設定が変わりました。",
+ "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 52452926..a4aa665f 100644
--- a/src/i18n/locales/ko.ts
+++ b/src/i18n/locales/ko.ts
@@ -267,6 +267,13 @@ export const ko: Record = {
"hw.checking": "{label} 확인 중…",
"hw.samplingPrompt": "이 창 위에서 마우스를 작은 원 모양으로 움직이세요 — 5초간 샘플링합니다.",
"hw.flashPrompt": "설정을 쓰고, 다시 읽은 후 복원합니다. 포인터 속도가 잠깐 바뀔 수 있습니다.",
+ "hw.x11ReadFailed": "X11 설정을 읽을 수 없습니다.",
+ "hw.deviceChanged": "테스트 중 선택한 장치가 바뀌었습니다.",
+ "hw.testSettingsChanged": "테스트 중 장치 또는 장치 설정이 바뀌었습니다.",
+ "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 20093889..b1c0efe8 100644
--- a/src/i18n/locales/pt.ts
+++ b/src/i18n/locales/pt.ts
@@ -267,6 +267,13 @@ 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.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 3eea6bb7..cc39e07a 100644
--- a/src/i18n/locales/ru.ts
+++ b/src/i18n/locales/ru.ts
@@ -267,6 +267,13 @@ export const ru: Record = {
"hw.checking": "Проверка: {label}…",
"hw.samplingPrompt": "Двигайте мышь небольшими кругами над этим окном — выборка займёт 5 секунд.",
"hw.flashPrompt": "Настройка записывается, считывается и восстанавливается — скорость указателя может ненадолго измениться.",
+ "hw.x11ReadFailed": "Не удалось прочитать настройки X11.",
+ "hw.deviceChanged": "Во время проверки изменилось выбранное устройство.",
+ "hw.testSettingsChanged": "Во время проверки изменилось устройство или его настройки.",
+ "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 a07fbe4c..9f6edfb4 100644
--- a/src/i18n/locales/tr.ts
+++ b/src/i18n/locales/tr.ts
@@ -266,6 +266,13 @@ 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.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 40ef585f..ce396662 100644
--- a/src/i18n/locales/vi.ts
+++ b/src/i18n/locales/vi.ts
@@ -1227,6 +1227,13 @@ 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.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 7f8312d9..a5bb6dc0 100644
--- a/src/i18n/locales/zh.ts
+++ b/src/i18n/locales/zh.ts
@@ -267,6 +267,13 @@ export const zh: Record = {
"hw.checking": "正在检查 {label}…",
"hw.samplingPrompt": "在此窗口上方小范围画圈移动鼠标——采样 5 秒。",
"hw.flashPrompt": "将写入一项设置、读回后再恢复——指针速度可能短暂变化。",
+ "hw.x11ReadFailed": "无法读取 X11 设置。",
+ "hw.deviceChanged": "测试期间所选设备发生了变化。",
+ "hw.testSettingsChanged": "测试期间设备或其设置发生了变化。",
+ "hw.flashUnconfirmed": "测试无法确认闪存写入成功。",
+ "hw.restoreUnconfirmed": "无法确认已恢复为 {value}。",
+ "hw.flashReadbackMismatch": "无法读回 {value}。原值已恢复。",
+ "hw.noRestorableTarget": "无法写入其他值并安全恢复原值。",
"hw.liveHertz": "{hz} 赫兹 · {samples} 个样本",
"hw.finishTime": "用时 {s} 秒完成",
"hw.identity": "VID / PID",
From 2fdab0bdb9ab574793c06a9d87107c6615e175cb Mon Sep 17 00:00:00 2001
From: Fear2Die
Date: Fri, 4 Dec 2026 13:54:50 +0100
Subject: [PATCH 4/7] Address X11 settings and hardware-test review findings
---
src/device/controller.ts | 49 +++++++++++++--
src/device/profile-write-ownership.test.ts | 39 ++++++++++++
src/device/x11-macros.test.ts | 2 +
src/device/x11-macros.ts | 4 +-
src/features/devices/DeviceHero.tsx | 3 +-
src/features/devices/cards/X11MacroCard.tsx | 15 ++++-
.../hardware-test/HardwareTestPage.tsx | 59 +++++++++----------
src/i18n/index.ts | 1 +
src/i18n/locales/ar.ts | 1 +
src/i18n/locales/de.ts | 1 +
src/i18n/locales/es.ts | 1 +
src/i18n/locales/fr.ts | 1 +
src/i18n/locales/ja.ts | 1 +
src/i18n/locales/ko.ts | 1 +
src/i18n/locales/pt.ts | 1 +
src/i18n/locales/ru.ts | 1 +
src/i18n/locales/tr.ts | 1 +
src/i18n/locales/vi.ts | 1 +
src/i18n/locales/zh.ts | 1 +
src/shared/CardSlot.tsx | 2 +-
20 files changed, 141 insertions(+), 44 deletions(-)
diff --git a/src/device/controller.ts b/src/device/controller.ts
index cd1f2e49..e7102335 100644
--- a/src/device/controller.ts
+++ b/src/device/controller.ts
@@ -2871,6 +2871,43 @@ 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;
+}): Promise<"changed" | "rejected" | "writeUnconfirmed" | "restoreUnconfirmed" | "readbackMismatch" | "restored"> {
+ if (!isGameProfileOwner(owner) || settingInProgress || gameProfileDraft || hasPendingChanges()
+ || latestDeviceStatus?.ui?.settingsReady === false || leg.read(latestDeviceStatus) !== leg.currentRaw) return "changed";
+ leg.stageTarget();
+ const [temporary] = pendingChanges();
+ if (!temporary) return "rejected";
+
+ const written = await flashPendingChanges().catch(() => "failed" as const);
+ const targetRead = leg.read(latestDeviceStatus) === 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) || leg.read(latestDeviceStatus) !== 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 {
const owner = getGameProfileOwner();
@@ -5004,7 +5041,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",
@@ -5024,7 +5061,7 @@ export function applyDpiValue(dpi: number): boolean {
apply: async () => {
await requireClientMethod("setDpi", "DPI").setDpi(dpi);
},
- });
+ }, options);
return true;
}
@@ -6670,7 +6707,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.
@@ -6694,10 +6731,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",
@@ -6711,7 +6748,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 {
diff --git a/src/device/profile-write-ownership.test.ts b/src/device/profile-write-ownership.test.ts
index eca010b9..2e73d53a 100644
--- a/src/device/profile-write-ownership.test.ts
+++ b/src/device/profile-write-ownership.test.ts
@@ -53,6 +53,45 @@ 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 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/x11-macros.test.ts b/src/device/x11-macros.test.ts
index 3ea955d3..59b4b02d 100644
--- a/src/device/x11-macros.test.ts
+++ b/src/device/x11-macros.test.ts
@@ -10,7 +10,9 @@ test("X11 recording fits a long release at capacity and refuses additional press
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);
diff --git a/src/device/x11-macros.ts b/src/device/x11-macros.ts
index fcc0fa20..dba70ff2 100644
--- a/src/device/x11-macros.ts
+++ b/src/device/x11-macros.ts
@@ -73,10 +73,11 @@ interface Recording {
held: Set;
units: number;
lastAt: number | null;
+ shortenedRelease: boolean;
}
export function startX11MacroRecording(): Recording {
- return { steps: [], held: new Set(), units: 0, lastAt: null };
+ return { steps: [], held: new Set(), units: 0, lastAt: null, shortenedRelease: false };
}
/** Reserve one short release for each pressed input, including at capacity. */
@@ -88,6 +89,7 @@ export function recordX11MacroEvent(recording: Recording, usage: number, down: b
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 {
diff --git a/src/features/devices/DeviceHero.tsx b/src/features/devices/DeviceHero.tsx
index dd2f810a..ce8da69f 100644
--- a/src/features/devices/DeviceHero.tsx
+++ b/src/features/devices/DeviceHero.tsx
@@ -76,7 +76,8 @@ export function DeviceHero({
{status?.ui?.x11ConfigurationAvailable ? (
) : null}
{image ? (
diff --git a/src/features/devices/cards/X11MacroCard.tsx b/src/features/devices/cards/X11MacroCard.tsx
index ac36832f..9b89a05f 100644
--- a/src/features/devices/cards/X11MacroCard.tsx
+++ b/src/features/devices/cards/X11MacroCard.tsx
@@ -20,6 +20,7 @@ export function X11MacroCard({ snapshot }: { snapshot: ControlSnapshot }): React
const [button, setButton] = useState("Forward");
const [recording, setRecording] = useState(false);
const [recordedCount, setRecordedCount] = useState(0);
+ const [shortenedRelease, setShortenedRelease] = useState(false);
const [storageFailed, setStorageFailed] = useState(false);
const recorder = useRef | null>(null);
const mapping = snapshot.status?.buttonMappings;
@@ -58,6 +59,7 @@ export function X11MacroCard({ snapshot }: { snapshot: ControlSnapshot }): React
const session = recorder.current;
if (usage !== null && session && recordX11MacroEvent(session, usage, down, performance.now())) {
setRecordedCount(session.steps.length);
+ if (session.shortenedRelease) setShortenedRelease(true);
}
}
function recordKey(event: KeyboardEvent): void {
@@ -103,6 +105,7 @@ export function X11MacroCard({ snapshot }: { snapshot: ControlSnapshot }): React
}
function newDraft(): void {
+ setShortenedRelease(false);
setDraft(newX11Macro(tp(locale, "macro.incottDefaultName", { n: library.length + 1 })));
}
@@ -110,7 +113,9 @@ export function X11MacroCard({ snapshot }: { snapshot: ControlSnapshot }): React
if (!valid) return;
const entry = { ...draft, name, repeats };
const next = saved ? library.map((macro) => macro.id === entry.id ? entry : macro) : [...library, entry];
- setStorageFailed(!writeX11MacroLibrary(next));
+ const stored = writeX11MacroLibrary(next);
+ setStorageFailed(!stored);
+ if (!stored) return;
setLibrary(next);
setDraft(entry);
}
@@ -158,7 +163,10 @@ export function X11MacroCard({ snapshot }: { snapshot: ControlSnapshot }): React
{t(locale, "tab.macro")}