Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 15 additions & 7 deletions src/device/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import {
retrySharedLightspeedDevice,
SharedLightspeedDevice,
} from "./shared-lightspeed.ts";
import { closestDpiOption } from "./dpi-presets";
import { closestDpiOption, dpiOptionsForStage } from "./dpi-presets";
import {
RIVAL650_FACTORY_MAPPING,
editRival650ButtonDraft,
Expand Down Expand Up @@ -5053,17 +5053,24 @@ export function startCustomDpi(): void {
emit();
}

function activeDpiOptions(): number[] {
const stagedStatus = latestDeviceStatus ? withPendingChanges(latestDeviceStatus) : null;
return dpiOptionsForStage(dpiOptions, stagedStatus, stagedStatus?.activeDpiStage);
}

export function setCustomDpiText(value: string): void {
const digits = value.replace(/\D/g, "");
const max = dpiOptions.length > 0 ? Math.max(...dpiOptions) : null;
const options = activeDpiOptions();
const max = options.length > 0 ? Math.max(...options) : null;
customDpiText = max !== null && digits !== "" && Number(digits) > max ? String(max) : digits;
emit();
}

export function commitCustomDpi(): void {
const dpi = Number(customDpiText.replace(/[^\d]/g, ""));
if (!Number.isInteger(dpi) || !dpiOptions.includes(dpi)) {
const closest = Number.isInteger(dpi) && dpi > 0 ? closestDpiOption(dpiOptions, dpi) : null;
const options = activeDpiOptions();
if (!Number.isInteger(dpi) || !options.includes(dpi)) {
const closest = Number.isInteger(dpi) && dpi > 0 ? closestDpiOption(options, dpi) : null;
setReadStatus(closest === null
? st("ctl.dpiUnsupported")
: st("ctl.closestStep", { dpi: dpi.toLocaleString(), closest: closest.toLocaleString() }));
Expand All @@ -5080,7 +5087,7 @@ export function cancelCustomDpi(dpi?: number): void {
}

export function applyDpiValue(dpi: number, options?: { force?: boolean }): boolean {
if (!hasActiveClient() || !dpiOptions.includes(dpi)) return false;
if (!hasActiveClient() || !activeDpiOptions().includes(dpi)) return false;
stageChange({
key: "dpi",
label: `DPI ${dpi.toLocaleString()}`,
Expand Down Expand Up @@ -5202,8 +5209,9 @@ export function applyDpiStageValue(stage: number, rawDpi: number): void {
const stagedStatus = latestDeviceStatus ? withPendingChanges(latestDeviceStatus) : null;
const stages = stagedStatus?.dpiStages ?? latestDeviceStatus?.dpiStages;
if (!stages || !Number.isInteger(stage) || stage < 0 || stage >= stages.length) return;
const dpi = closestDpiOption(dpiOptions, rawDpi) ?? rawDpi;
if (!dpiOptions.includes(dpi)) {
const options = dpiOptionsForStage(dpiOptions, stagedStatus, stage);
const dpi = closestDpiOption(options, rawDpi) ?? rawDpi;
if (!options.includes(dpi)) {
setReadStatus(st("ctl.dpiNotSupported", { dpi: rawDpi.toLocaleString() }));
emit();
return;
Expand Down
16 changes: 15 additions & 1 deletion src/device/dpi-presets.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import assert from "node:assert/strict";
import test from "node:test";

import { closestDpiOption, dpiPresetValues } from "./dpi-presets.ts";
import { closestDpiOption, dpiOptionsForStage, dpiPresetValues } from "./dpi-presets.ts";

const FINE_GRID = Array.from({ length: 600 }, (_, step) => 50 + step * 50);
/** The G402's real grid, captured from hardware: 252 to 4032 in steps of 84. */
Expand Down Expand Up @@ -50,3 +50,17 @@ test("the closest step is reported for a value the mouse cannot reach", () => {
assert.equal(closestDpiOption(G402_GRID, 100), 252);
assert.equal(closestDpiOption(G402_GRID, 99999), 4032);
});

test("the SC590 Pro's sixth stage uses its own DPI grid", () => {
const options = [100, 200, 4300, 8600, 12000, 20000];
const status = {
dpiStages: [600, 800, 1600, 2400, 3200, 8600],
ui: { dpiStageEditor: {
maxStages: 6, minDpi: 100, maxDpi: 12000, stepDpi: 100,
stageLimits: { 5: { minDpi: 200, maxDpi: 20000, stepDpi: 200 } },
} },
};
assert.deepEqual(dpiOptionsForStage(options, status, 4), [100, 200, 4300, 8600, 12000]);
assert.deepEqual(dpiOptionsForStage(options, status, 5), [200, 8600, 12000, 20000]);
assert.deepEqual(dpiOptionsForStage(options, status), [200, 8600, 12000]);
});
22 changes: 22 additions & 0 deletions src/device/dpi-presets.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { MouseStatus } from "@openmouse/protocol/drivers/mouse-types";

export const COMMON_DPI_PRESETS = [400, 800, 1600, 3200, 6400, 8000] as const;

/**
Expand All @@ -6,6 +8,15 @@ export const COMMON_DPI_PRESETS = [400, 800, 1600, 3200, 6400, 8000] as const;
*/
const DPI_SNAP_TOLERANCE = 0.1;

type DpiStageEditor = NonNullable<NonNullable<MouseStatus["ui"]>["dpiStageEditor"]>;
type DpiStageLimits = Pick<DpiStageEditor, "minDpi" | "maxDpi" | "stepDpi">;

// The stage overrides are optional in protocol packages without SC590 Pro support.
export function dpiStageEditor(status: Pick<MouseStatus, "ui"> | null | undefined):
(DpiStageEditor & { stageLimits?: Readonly<Partial<Record<number, DpiStageLimits>>> }) | undefined {
return status?.ui?.dpiStageEditor;
}

export function closestDpiOption(options: readonly number[], target: number): number | null {
let closest: number | null = null;
for (const option of options) {
Expand All @@ -14,6 +25,17 @@ export function closestDpiOption(options: readonly number[], target: number): nu
return closest;
}

/** With no stage specified, return the values that can be written to every stage. */
export function dpiOptionsForStage(options: number[], status: Pick<MouseStatus, "ui" | "dpiStages"> | null | undefined, stage?: number): number[] {
const editor = dpiStageEditor(status);
if (!editor?.stageLimits) return options;
const limits = stage === undefined
? (status?.dpiStages ?? []).map((_, index) => editor.stageLimits?.[index] ?? editor)
: [editor.stageLimits[stage] ?? editor];
return options.filter((dpi) => limits.every(({ minDpi, maxDpi, stepDpi }) =>
dpi >= minDpi && dpi <= maxDpi && (dpi - minDpi) % stepDpi === 0));
}

/**
* Presets snapped onto the mouse's advertised grid. Mice that list the round
* numbers exactly — most of them — get those values back untouched. Mice with
Expand Down
24 changes: 23 additions & 1 deletion src/device/dpi-stage-writable.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,21 @@ 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 dpiPresets from "./dpi-presets.ts";

function harness() {
pending.clearPendingChanges();
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 function testSelect(client) { clearActiveClients(); clearPendingChanges(); active = client; activeDevice = client.device; latestDeviceStatus = { name: "Fixed stages", dpi: 800, dpiStages: [400, 800, 1600], pollingRateHz: 1000, ui: { dpiStageEditor: { maxStages: 3 } } }; dpiOptions = [400, 800, 1200, 1600, 3200]; }
export function testSelect(client, status, options) { clearActiveClients(); clearPendingChanges(); active = client; activeDevice = client.device; latestDeviceStatus = status ?? { name: "Fixed stages", dpi: 800, dpiStages: [400, 800, 1600], pollingRateHz: 1000, ui: { dpiStageEditor: { maxStages: 3 } } }; dpiOptions = options ?? [400, 800, 1200, 1600, 3200]; }
`;
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: () => 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("dpi-presets")) return dpiPresets;
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 () {} }));
Expand All @@ -40,3 +42,23 @@ test("a mouse that can rewrite a stage still gets the write", () => {
control.applyDpiStageValue(1, 1200);
assert.deepEqual(pending.pendingChanges().map((change) => change.key), ["dpi-stage-1"]);
});

test("DPI values use the range of the pending active stage", () => {
const control = harness();
control.testSelect({ device: {}, async setDpi() {}, async setActiveDpiStage() {} }, {
name: "AULA SC590 Pro",
dpi: 800,
dpiStages: [800, 1600, 2400, 3200, 4000, 8000],
activeDpiStage: 0,
pollingRateHz: 1000,
ui: { dpiStageEditor: {
maxStages: 6, minDpi: 100, maxDpi: 12000, stepDpi: 100,
stageLimits: { 5: { minDpi: 200, maxDpi: 20000, stepDpi: 200 } },
} },
}, [800, 8100, 20000]);
assert.equal(control.applyDpiValue(20000), false);
control.applyActiveDpiStage(5);
assert.equal(control.applyDpiValue(8100), false);
assert.equal(control.applyDpiValue(20000), true);
assert.deepEqual(pending.pendingChanges().map((change) => change.key), ["dpi-active-stage", "dpi"]);
});
2 changes: 2 additions & 0 deletions src/device/profile-write-ownership.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ 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 dpiPresets from "./dpi-presets.ts";
import * as traits from "./traits.ts";

function controllerHarness() {
Expand All @@ -27,6 +28,7 @@ export function testReport(patch) { latestDeviceStatus = { ...latestDeviceStatus
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("dpi-presets")) return dpiPresets;
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 };
Expand Down
66 changes: 54 additions & 12 deletions src/features/devices/cards/DpiCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
import * as control from "../../../device/controller";
import type { ControlSnapshot, LiftOffLevel } from "../../../device/types";
import { isNoirE1Status, isNoirKsnakeStatus, isNoirS1Status, NOIR_DPI_STAGE_COLORS } from "../../../device/noir.ts";
import { closestDpiOption, dpiPresetValues } from "../../../device/dpi-presets";
import { closestDpiOption, dpiOptionsForStage, dpiPresetValues, dpiStageEditor } from "../../../device/dpi-presets";
import { t, tp } from "../../../i18n/index";
import { LiftOffDistance, hasLiftOff } from "./PerformanceCards";

Expand Down Expand Up @@ -43,10 +43,10 @@ function DpiStageEditor({
}): ReactNode {
const status = snapshot.status;
const locale = snapshot.preferences.locale;
const options = snapshot.dpiOptions;
const options = dpiOptionsForStage(snapshot.dpiOptions, status);

const isLogitech = snapshot.profile.slotsAvailable && snapshot.dpiSlotPlan !== null;
const stageEditor = status?.ui?.dpiStageEditor;
const stageEditor = dpiStageEditor(status);
const isStage = Boolean(stageEditor) && Array.isArray(status?.dpiStages) && (status?.dpiStages?.length ?? 0) > 0;
// A driver may publish the stage table without being able to write it (the
// classic Razer driver never sends the unverified `0x04`/`0x06` write), so
Expand Down Expand Up @@ -81,6 +81,8 @@ function DpiStageEditor({

const countCap = isLogitech ? (limits?.maxStages ?? 1) : stageEditor?.maxStages ?? 1;
const rowCap = mode === "generic" ? genericRows : countCap;
const fixedStageCount = mode === "stage" && stageEditor?.countEditable !== true;
const fixedNumericStages = fixedStageCount && !stageAxesEditable;

const initRows = (): StageRow[] => {
if (mode === "logitech" && snapshot.dpiSlotPlan) {
Expand Down Expand Up @@ -137,7 +139,13 @@ function DpiStageEditor({
});
};

const [rows, setRows] = useState<StageRow[]>(initRows);
const [localRows, setRows] = useState<StageRow[]>(initRows);
const editedStages = useRef(new Set<number>());
// Fixed rows keep their hardware index. Only a row with an unfinished edit
// should show a local value; otherwise show what the controller will save.
const rows = fixedNumericStages
? initRows().map((row, index) => editedStages.current.has(index) ? localRows[index] ?? row : row)
: localRows;
const rowsRef = useRef(rows);
rowsRef.current = rows;
const touchedRef = useRef(0);
Expand All @@ -149,7 +157,6 @@ function DpiStageEditor({
};
}, []);

const fixedStageCount = mode === "stage" && stageEditor?.countEditable !== true;
const fillsStageTable = singleFillsStageTable(snapshot);
const singleFillsStages = mode === "generic" && fillsStageTable;

Expand Down Expand Up @@ -191,6 +198,7 @@ function DpiStageEditor({
useEffect(() => {
if (sourceSig === lastSigRef.current) return;
lastSigRef.current = sourceSig;
if (fixedNumericStages) return;
if (Date.now() - touchedRef.current > 1500 || (mode === "logitech" && !timerRef.current)) setRows(initRows());
// initRows is recreated each render on purpose so it always reads fresh snapshot data.
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand All @@ -199,11 +207,20 @@ function DpiStageEditor({
// Switching the editor pill rebuilds the rows from the other mode's source
// (single DPI reads presets, stages read the device stage table).
const lastModeRef = useRef(mode);
const flushRef = useRef<() => void>(() => undefined);
useEffect(() => {
if (mode === lastModeRef.current) return;
lastModeRef.current = mode;
flushRef.current();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High cards/DpiCard.tsx:214

Switching to Single before a fixed-stage edit's debounce expires can leave DPI cycling enabled: for [400, 800, 1600] with stage 0 active, moving stage 0 to 1200 and switching modes produces [1200, 400, 400]. flushRef.current() commits 1200, but the rest of this effect uses the captured, pre-flush status.dpiStages, so applySingleDpi(400) skips stage 0; perform the conversion using the post-flush stage values or on a subsequent render.

🤖 Copy this AI Prompt to have your agent fix this:
In file @src/features/devices/cards/DpiCard.tsx around line 214:

Switching to Single before a fixed-stage edit's debounce expires can leave DPI cycling enabled: for `[400, 800, 1600]` with stage 0 active, moving stage 0 to `1200` and switching modes produces `[1200, 400, 400]`. `flushRef.current()` commits `1200`, but the rest of this effect uses the captured, pre-flush `status.dpiStages`, so `applySingleDpi(400)` skips stage 0; perform the conversion using the post-flush stage values or on a subsequent render.

editedStages.current.clear();
setRows(initRows());
if (singleFillsStages && status?.dpi && stagesDifferFrom(status.dpi)) applySingleDpi(status.dpi);
if (singleFillsStages && status?.dpi) {
const dpi = stageEditor?.stageLimits ? closestDpiOption(options, status.dpi) : status.dpi;
if (dpi !== null && stagesDifferFrom(dpi)) {
setRows((current) => current.map((row) => row.enabled ? { ...row, value: String(dpi) } : row));
applySingleDpi(dpi);
}
}
if (mode === "stage" && fillsStageTable) restoreStagesBeforeSingle();
// initRows is recreated each render on purpose so it always reads fresh snapshot data.
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand All @@ -228,6 +245,17 @@ function DpiStageEditor({
};

const commit = (next: StageRow[]): void => {
if (fixedNumericStages) {
const edited = [...editedStages.current];
editedStages.current.clear();
for (const stage of edited) {
const row = next[stage];
const value = row?.enabled ? parseRow(row.value) : null;
if (value !== null) control.applyDpiStageValue(stage, value);
}
setRows(initRows());
return;
}
if (mode === "logitech") {
// Lift-off lives in the slot plan itself now (edited from the dedicated
// side panel), so a DPI-value commit must not clobber it with the local
Expand Down Expand Up @@ -307,11 +335,14 @@ function DpiStageEditor({
};

const flushEdit = (): void => {
if (!timerRef.current) return;
clearTimeout(timerRef.current);
if (!timerRef.current && editedStages.current.size === 0) return;
if (timerRef.current) clearTimeout(timerRef.current);
timerRef.current = null;
commit(rowsRef.current);
};
useEffect(() => {
flushRef.current = flushEdit;
});

const setEnabled = (index: number, enabled: boolean): void => {
let next = rows.map((row, i) => (i === index ? { ...row, enabled: !row.enabled } : row));
Expand Down Expand Up @@ -355,6 +386,16 @@ function DpiStageEditor({
: row));
setRows(next);
rowsRef.current = next;
if (fixedNumericStages) {
editedStages.current.add(index);
// Finish typed input on blur or Enter so a pause between digits cannot
// save a partial value. Sliders and steppers can still debounce.
if (delay === TYPING_DELAY) {
if (timerRef.current) clearTimeout(timerRef.current);
timerRef.current = null;
return;
}
}
markEdited(next, delay);
};

Expand Down Expand Up @@ -409,14 +450,15 @@ function DpiStageEditor({
setEnabled(index, !rows[index].enabled);
};

const sliderFor = (row: StageRow): { min: number; max: number; step: number; pos: number } => {
const sliderFor = (row: StageRow, index: number): { min: number; max: number; step: number; pos: number } => {
if (mode === "logitech" && limits) {
const value = Math.min(limits.maxDpi, Math.max(limits.minDpi, parseRow(row.value) ?? limits.minDpi));
return { min: limits.minDpi, max: limits.maxDpi, step: limits.stepDpi, pos: value };
}
if (mode === "stage" && stageEditor) {
const value = Math.min(stageEditor.maxDpi, Math.max(stageEditor.minDpi, parseRow(row.value) ?? stageEditor.minDpi));
return { min: stageEditor.minDpi, max: stageEditor.maxDpi, step: stageEditor.stepDpi, pos: value };
const { minDpi, maxDpi, stepDpi } = stageEditor.stageLimits?.[index] ?? stageEditor;
const value = Math.min(maxDpi, Math.max(minDpi, parseRow(row.value) ?? minDpi));
return { min: minDpi, max: maxDpi, step: stepDpi, pos: value };
}
const target = parseRow(row.value) ?? status?.dpi ?? 0;
const pos = options.length > 0 ? closestDpiOption(options, target) ?? 0 : 0;
Expand Down Expand Up @@ -468,7 +510,7 @@ function DpiStageEditor({
) : null}
<div id="dpi-editor-list" className="dpi-editor-list">
{rows.map((row, index) => {
const slider = sliderFor(row);
const slider = sliderFor(row, index);
const isActive = mode === "stage" ? compactIndex(index) === (status?.activeDpiStage ?? 0) : null;
const isStarting = mode === "logitech" && snapshot.dpiSlotPlan
? compactIndex(index) === snapshot.dpiSlotPlan.defaultIndex
Expand Down
4 changes: 3 additions & 1 deletion src/features/hardware-test/HardwareTestPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ 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 { dpiOptionsForStage } from "../../device/dpi-presets";
import type { ControlSnapshot } from "../../device/types";
import { verifiedDeviceSettings } from "../../device/traits";
import { t, tp } from "../../i18n/index";
Expand Down Expand Up @@ -320,7 +321,8 @@ export function HardwareTestPage({ snapshot }: { snapshot: ControlSnapshot }): R
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);
const dpiOptions = dpiOptionsForStage(live.dpiOptions, live.deviceStatus, live.deviceStatus?.activeDpiStage);
const dpiTarget = pickFlashDpiTarget(dpiCurrent, dpiOptions);
if (dpiTarget === null) {
legs.push({ setting: "DPI", current: `${dpiCurrent.toLocaleString()} DPI`, target: "—", status: "skip", detail: t(locale, "hw.noRestorableTarget") });
} else {
Expand Down
5 changes: 5 additions & 0 deletions src/shared/device-images.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,11 @@ test("AULA SC380 Pro resolves its own artwork by name", () => {
assert.equal(isUnknownDevice(null, "AULA SC380"), true);
});

test("AULA SC590 Pro resolves its hosted artwork by name", () => {
assert.equal(deviceImage(null, "AULA SC590 Pro"), "https://img.openmouse.app/aula-sc590-pro.png");
assert.equal(deviceImage(null, "AULA-SC590Pro"), "https://img.openmouse.app/aula-sc590-pro.png");
});

test("SteelSeries Aerox 3 Wireless resolves to its artwork", () => {
assert.equal(deviceImage(null, "SteelSeries Aerox 3 Wireless"), "/devices/steelseries-aerox-3-wireless.png");
assert.equal(deviceImage(null, "Aerox 3 Wireless (wired mode)"), "/devices/steelseries-aerox-3-wireless.png");
Expand Down
Loading