Skip to content
214 changes: 204 additions & 10 deletions src/device/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -429,6 +429,8 @@ let lastDiagnosticError: string | null = null;
let reconnectInFlight = false;
let activationInProgress = false;
let activationQueue: Promise<void> = Promise.resolve();
let x11ConnectionReadStarted = false;
let x11SettingsRead: Promise<boolean> | null = null;
let sidebarHidden = false;
let interfaceSettingsOpen = false;
let activeWorkspaceTab: WorkspaceTab = "overview";
Expand Down Expand Up @@ -2876,8 +2878,66 @@ export async function flashPendingChanges(): Promise<FlashResult> {
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<FlashResult> {
async function flashStagedChanges(canWrite?: () => boolean): Promise<FlashResult> {
const owner = getGameProfileOwner();
if (!owner) return "stale";
const batches = pendingChangeBatches();
Expand All @@ -2891,6 +2951,7 @@ async function flashStagedChanges(): Promise<FlashResult> {
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
Expand Down Expand Up @@ -2922,6 +2983,10 @@ async function flashStagedChanges(): Promise<FlashResult> {
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(() => {
Expand All @@ -2933,8 +2998,8 @@ async function flashStagedChanges(): Promise<FlashResult> {
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();
Expand All @@ -2950,6 +3015,11 @@ async function flashStagedChanges(): Promise<FlashResult> {
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()) {
Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -4539,6 +4611,7 @@ function activateClient(target: SupportedClient | KeyboardClient, autoConnect =
} finally {
activationInProgress = false;
}
maybeLoadX11ConnectionSettings();
});
activationQueue = run.then(() => undefined, () => undefined);
return run;
Expand Down Expand Up @@ -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",
Expand All @@ -5026,7 +5099,7 @@ export function applyDpiValue(dpi: number): boolean {
apply: async () => {
await requireClientMethod("setDpi", "DPI").setDpi(dpi);
},
});
}, options);
return true;
}

Expand Down Expand Up @@ -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.
Expand All @@ -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",
Expand All @@ -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 {
Expand Down Expand Up @@ -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<NonNullable<MouseStatus["keychronMouse"]>["dynamicDpi"]>): void {
if (!latestDeviceStatus?.keychronMouse?.dynamicDpi) return;
const next = structuredClone(value);
Expand Down Expand Up @@ -6922,6 +7008,72 @@ export async function refreshKeychronReceiver(): Promise<void> {
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<boolean> {
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<boolean> => {
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<boolean> => {
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);
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -8284,6 +8477,7 @@ async function refreshStatus(): Promise<void> {
} finally {
refreshInProgress = false;
}
maybeLoadX11ConnectionSettings();
}

async function loadPreviewEntries(): Promise<void> {
Expand Down
Loading