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
80 changes: 72 additions & 8 deletions src/device/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { cachedBatterySamples, estimateBatteryTime, estimateFromRatedLife, HISTO
import { bridgeEmptyResultMessage, isBridgeHidActive } from "../features/bridge/bridge-hid";
import { applyBridgeNativeSettings } from "../features/bridge/bridge";
import { pollingRateText } from "../shared/polling-rate";
import { keyChordFromLabel } from "../shared/hid-keys";
import {
clientSupportScore,
createKeyboardClient,
Expand Down Expand Up @@ -143,6 +144,7 @@ import type { RazerHidClient } from "@openmouse/protocol/drivers/razer/hid";
import type {
RazerButtonControl,
RazerButtonMapping,
RazerKeyAction,
Comment thread
onyxhq-dev marked this conversation as resolved.
Resolved
RazerToggleControl,
} from "@openmouse/protocol/razer";
import type { RazerViperMiniHidClient } from "@openmouse/protocol/drivers/razer/viper-mini-hid";
Expand Down Expand Up @@ -2411,7 +2413,12 @@ export function applyGameProfileSnapshot(snapshot: GameProfileSnapshot): void {

for (const [button, action] of Object.entries(s.buttonMappings ?? {})) applyDeviceButtonMapping(button, action);
for (const [control, mapping] of Object.entries(s.razerButtonMappings ?? {})) {
applyRazerButtonMapping(control as RazerButtonControl, mapping as RazerButtonMapping);
if ((C().RAZER_BUTTON_MAPPINGS as readonly string[]).includes(mapping)) {
applyRazerButtonMapping(control as RazerButtonControl, mapping as RazerButtonMapping);
continue;
}
const key = keyChordFromLabel(mapping, C().razerKeyLabel, Object.values(C().RAZER_KEY_MODIFIERS));
if (key) applyRazerKeyMapping(control as RazerButtonControl, key);
}

if (s.finalmouseDongleLedMode != null) applyFinalmouseSetting("dongleLed", s.finalmouseDongleLedMode);
Expand Down Expand Up @@ -6975,12 +6982,44 @@ export function applyLowPowerThreshold(percent: number): void {
}

/**
* Only the base `RazerHidClient` carries the class `0x02` button commands —
* the Viper Mini, Viper and Cobra siblings claim their own single product ids
* and have never been checked against it.
* Any Razer client that carries the class `0x02` button commands.
*
* Checked by capability, not by class: the base `RazerHidClient` was the only
* driver with them for a long time, but the Viper Mini's own client now
* implements `setButtonMapping` too. A class check silently dropped it, so the
* Buttons card rendered from `razerButtonMappings` while every dropdown in it
* staged nothing — the row looked editable and did nothing.
*/
function razerButtonClient(): RazerHidClient | null {
return activeAs<RazerHidClient>(CM()?.RazerHidClient);
type ButtonMappingClient = Pick<RazerHidClient, "setButtonMapping">;
type ToggleControlClient = Pick<RazerHidClient, "setToggleControl">;

function razerClientWith(method: string): Record<string, unknown> | null {
const client = razerClient();
if (!client) return null;
const candidate = client as unknown as Record<string, unknown>;
return typeof candidate[method] === "function" ? candidate : null;
}

function razerButtonClient(): ButtonMappingClient | null {
return razerClientWith("setButtonMapping") as ButtonMappingClient | null;
}

function razerToggleClient(): ToggleControlClient | null {
return razerClientWith("setToggleControl") as ToggleControlClient | null;
}

/** The Viper Mini's client carries the keyboard-mapping write; others do not. */
type KeyboardMappingClient = {
setKeyboardMapping(control: RazerButtonControl, key: RazerKeyAction): Promise<string>;
};

function razerKeyClient(): KeyboardMappingClient | null {
return razerClientWith("setKeyboardMapping") as KeyboardMappingClient | null;
}

/** Whether the connected Razer client can write a keyboard key to a button. */
export function supportsRazerKeyMapping(): boolean {
return razerKeyClient() !== null;
}

export function applyRazerButtonMapping(control: RazerButtonControl, mapping: RazerButtonMapping): void {
Expand All @@ -7001,8 +7040,33 @@ export function applyRazerButtonMapping(control: RazerButtonControl, mapping: Ra
});
}

/**
* Assigns a keyboard key to a Razer control. Only models whose firmware has
* been checked for the encoding get here: the Viper Mini stores
* `02 02 <mods> <usage>` and physically sends it, confirmed with `wev`.
*/
export function applyRazerKeyMapping(control: RazerButtonControl, key: RazerKeyAction): void {
if (!razerKeyClient()) return;
const name = C().RAZER_BUTTON_CONTROL_LABEL[control];
const label = C().razerKeyLabel(key);
stageChange({
key: `razer-button-${control}`,
label: `${name} → ${label}`,
command: `Change ${name} mapping`,
progress: `Changing ${name} mapping…`,
preview: (status) => {
if (status.razerButtonMappings) status.razerButtonMappings[control] = label;
},
apply: async () => {
const client = razerKeyClient();
if (!client) throw new Error(st("ctl.gone"));
await client.setKeyboardMapping(control, key);
},
});
}

export function applyRazerToggleControl(control: RazerToggleControl, label: string): void {
if (!razerButtonClient()) return;
if (!razerToggleClient()) return;
const name = C().RAZER_TOGGLE_CONTROL_INFO[control].label;
stageChange({
key: `razer-toggle-${control}`,
Expand All @@ -7013,7 +7077,7 @@ export function applyRazerToggleControl(control: RazerToggleControl, label: stri
if (status.razerButtonMappings) status.razerButtonMappings[control] = label;
},
apply: async () => {
const client = razerButtonClient();
const client = razerToggleClient();
if (!client) throw new Error(st("ctl.gone"));
await client.setToggleControl(control, label);
},
Expand Down
25 changes: 6 additions & 19 deletions src/device/incott-macros.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
type IncottMacroLoop,
type IncottMacroStep,
} from "@openmouse/protocol/incott";
import { HID_KEY_USAGES, hidKeyUsage } from "../shared/hid-keys.ts";

/**
* Local store for Incott macros: a library of named macros, plus which button
Expand Down Expand Up @@ -325,20 +326,10 @@ export const INCOTT_MACRO_DEFAULT_ACTION: Readonly<Record<IncottButtonName, stri
* key table names. A key outside it would upload as a code the editor cannot
* show, so the recorder ignores it instead.
*/
const KEY_BY_CODE = new Map<string, number>([
...Array.from({ length: 26 }, (_, i) => [`Key${String.fromCharCode(65 + i)}`, 0x04 + i] as const),
...Array.from({ length: 9 }, (_, i) => [`Digit${i + 1}`, 0x1e + i] as const),
["Digit0", 0x27],
...Array.from({ length: 12 }, (_, i) => [`F${i + 1}`, 0x3a + i] as const),
["Enter", 0x28], ["Escape", 0x29], ["Backspace", 0x2a], ["Tab", 0x2b], ["Space", 0x2c],
["Insert", 0x49], ["Delete", 0x4c], ["Home", 0x4a], ["End", 0x4d],
["PageUp", 0x4b], ["PageDown", 0x4e],
["ArrowUp", 0x52], ["ArrowDown", 0x51], ["ArrowLeft", 0x50], ["ArrowRight", 0x4f],
["CapsLock", 0x39], ["NumLock", 0x53], ["ScrollLock", 0x47],
["PrintScreen", 0x46], ["Pause", 0x48], ["ContextMenu", 0x65],
["ControlLeft", 0xe0], ["ShiftLeft", 0xe1], ["AltLeft", 0xe2], ["MetaLeft", 0xe3],
["ControlRight", 0xe4], ["ShiftRight", 0xe5], ["AltRight", 0xe6], ["MetaRight", 0xe7],
]);
export function incottMacroKeyForCode(code: string): number | null {
const usage = hidKeyUsage(code);
return usage !== null && HID_KEY_USAGES.includes(usage) ? usage : null;
}

/** `MouseEvent.button` -> macro key. Only the three buttons the table has. */
const MOUSE_BY_BUTTON = new Map<number, number>([
Expand All @@ -347,10 +338,6 @@ const MOUSE_BY_BUTTON = new Map<number, number>([
[2, INCOTT_MACRO_MOUSE_KEYS.right],
]);

export function incottMacroKeyForCode(code: string): number | null {
return KEY_BY_CODE.get(code) ?? null;
}

export function incottMacroKeyForMouseButton(button: number): number | null {
return MOUSE_BY_BUTTON.get(button) ?? null;
}
Expand All @@ -362,5 +349,5 @@ export function incottMacroKeyName(key: number): string {
/** Every key a step can be set to: mouse buttons first, then the keyboard. */
export const INCOTT_MACRO_KEY_CHOICES: Readonly<{ mouse: readonly number[]; keyboard: readonly number[] }> = {
mouse: [INCOTT_MACRO_MOUSE_KEYS.left, INCOTT_MACRO_MOUSE_KEYS.right, INCOTT_MACRO_MOUSE_KEYS.middle],
keyboard: [...KEY_BY_CODE.values()],
keyboard: [...HID_KEY_USAGES],
};
64 changes: 60 additions & 4 deletions src/features/devices/cards/AdvancedCards.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,17 @@ import {
type EggSpdtMode,
} from "@openmouse/protocol/drivers/endgame/egg-op1-hid";
import {
RAZER_BUTTON_CONTROLS,
RAZER_BUTTON_CONTROL_LABEL,
RAZER_BUTTON_MAPPINGS,
RAZER_KEY_MODIFIERS,
RAZER_LOCKED_BUTTON_CONTROL,
RAZER_TOGGLE_CONTROLS,
RAZER_TOGGLE_CONTROL_INFO,
type RazerButtonControl,
type RazerButtonMapping,
type RazerToggleControl,
} from "@openmouse/protocol/razer";
import { hidKeyUsage, isModifierCode } from "../../../shared/hid-keys";
import { teevolutionSensorModeUi } from "@openmouse/protocol/teevolution";
import type { KsnakeMacroProfile, KsnakeMacroStep } from "@openmouse/protocol/ksnake";
import type { WallhackMacroStep } from "@openmouse/protocol/wallhack";
Expand Down Expand Up @@ -1587,20 +1588,58 @@ export function EggCpiCard({ snapshot }: { snapshot: ControlSnapshot }): ReactNo
* Laid out with `button-remap-list`/`button-remap-row` to match
* `MxMasterButtonsCard`, the other remap card in this same tab.
*/

/** OptionMenu sentinel: picking this starts a key capture instead of a mapping. */
const RAZER_KEY_OPTION = "__razer_key__";

export function RazerButtonCard({ snapshot }: { snapshot: ControlSnapshot }): ReactNode {
const locale = snapshot.preferences.locale;
const mappings = snapshot.status?.razerButtonMappings;
// Only the models whose firmware was checked for the key encoding offer it —
// the Viper Mini stores `02 02 <mods> <usage>` where the older clients have
// no keyboard write at all.
const keyCapable = control.supportsRazerKeyMapping();
const [capturing, setCapturing] = useState<RazerButtonControl | null>(null);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
useEffect(() => setCapturing(null), [snapshot.activeDeviceKey]);
useEffect(() => {
if (!capturing) return undefined;
const onKeyDown = (event: KeyboardEvent): void => {
// A bare modifier is the start of a chord, not the key itself.
if (isModifierCode(event.code)) return;
event.preventDefault();
event.stopPropagation();
if (event.code === "Escape") {
setCapturing(null);
return;
}
if (event.repeat) return;
const usage = hidKeyUsage(event.code);
if (usage === null) return;
const mods = (event.ctrlKey ? RAZER_KEY_MODIFIERS.ctrl ?? 0 : 0)
| (event.shiftKey ? RAZER_KEY_MODIFIERS.shift ?? 0 : 0)
| (event.altKey ? RAZER_KEY_MODIFIERS.alt ?? 0 : 0)
| (event.metaKey ? RAZER_KEY_MODIFIERS.meta ?? 0 : 0);
control.applyRazerKeyMapping(capturing, { mods, usage });
setCapturing(null);
};
window.addEventListener("keydown", onKeyDown, true);
return () => window.removeEventListener("keydown", onKeyDown, true);
}, [capturing]);
if (!mappings) return null;
const busy = snapshot.settingInProgress;
const rows: Array<{ key: string; name: string; current: string; options: readonly string[]; locked: boolean }> = [];
for (const con of RAZER_BUTTON_CONTROLS) {
// The wheel press and the bottom button are model-specific: only a model
// whose firmware answers for them contributes a row.
const order: RazerButtonControl[] = ["leftClick", "scrollClick", "rightClick", "mouse4", "mouse5", "dpiButton"];
const options = (snapshot.status?.razerButtonOptions ?? RAZER_BUTTON_MAPPINGS) as readonly string[];
for (const con of order) {
const current = mappings[con];
if (!current) continue;
rows.push({
key: `razer-button-${con}`,
name: RAZER_BUTTON_CONTROL_LABEL[con],
current,
options: RAZER_BUTTON_MAPPINGS,
options,
// Left Click is fixed on the Standard layer — Synapse enforces the same
// restriction, and the driver throws rather than send it.
locked: con === RAZER_LOCKED_BUTTON_CONTROL,
Expand Down Expand Up @@ -1636,7 +1675,14 @@ export function RazerButtonCard({ snapshot }: { snapshot: ControlSnapshot }): Re
{rows.map((row) => {
const staged = snapshot.pending.keys.includes(row.key);
const known = row.options.includes(row.current);
const rowControl = row.key.startsWith("razer-button-")
? row.key.slice("razer-button-".length) as RazerButtonControl
: null;
const applyRazerRow = (value: string): void => {
if (value === RAZER_KEY_OPTION && rowControl) {
setCapturing(rowControl);
return;
}
if (row.key.startsWith("razer-button-")) {
control.applyRazerButtonMapping(
row.key.slice("razer-button-".length) as RazerButtonControl,
Expand All @@ -1656,13 +1702,23 @@ export function RazerButtonCard({ snapshot }: { snapshot: ControlSnapshot }): Re
data-pending-key={row.key}
>
<span>{displayText(locale, row.name)}</span>
{row.locked ? <output>{displayText(locale, row.current)}</output> : (
{row.locked ? <output>{displayText(locale, row.current)}</output> : capturing !== null && capturing === rowControl ? (
<span className="button-remap-capture">
<small className="setting-note">{t(locale, "adv.pressKey")}</small>
<button type="button" className="ghost" onClick={() => setCapturing(null)}>
{t(locale, "common.cancel")}
</button>
</span>
) : (
<OptionMenu
id={row.key}
ariaLabel={displayText(locale, row.name)}
options={[
...(known ? [] : [{ value: row.current, label: row.current, disabled: true }]),
...row.options.map((option) => ({ value: option, label: option })),
...(keyCapable && rowControl
? [{ value: RAZER_KEY_OPTION, label: t(locale, "adv.keyboardShortcut") }]
: []),
]}
value={row.current}
disabled={busy}
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -743,6 +743,8 @@ const en = {
"adv.applyStage": "Apply stage",
"adv.mapping": "Mapping",
"adv.razerLocked": "{name} is fixed on the Standard layer and cannot be reassigned or disabled.",
"adv.keyboardShortcut": "Keyboard shortcut…",
"adv.pressKey": "Press a key, or Esc to cancel",
"adv.multiclick": "Multiclick filter",
"adv.eggButtonTitle": "Multiclick and mapping",
"adv.eggSensor": "Sensor controls",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/ar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -685,6 +685,8 @@ export const ar: Record<I18nKey, string> = {
"adv.applyStage": "تطبيق المرحلة",
"adv.mapping": "الربط",
"adv.razerLocked": "{name} ثابت على الطبقة القياسية ولا يمكن إعادة تعيينه أو تعطيله.",
"adv.keyboardShortcut": "اختصار لوحة المفاتيح…",
"adv.pressKey": "اضغط مفتاحًا، أو Esc للإلغاء",
"adv.multiclick": "مرشح النقر المتعدد",
"adv.eggButtonTitle": "النقر المتعدد والربط",
"adv.eggSensor": "عناصر التحكم بالمستشعر",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -686,6 +686,8 @@ export const de: Record<I18nKey, string> = {
"adv.applyStage": "Stufe anwenden",
"adv.mapping": "Belegung",
"adv.razerLocked": "{name} ist auf der Standard-Ebene fixiert und kann nicht neu zugewiesen oder deaktiviert werden.",
"adv.keyboardShortcut": "Tastenkürzel…",
"adv.pressKey": "Taste drücken, Esc zum Abbrechen",
"adv.multiclick": "Mehrfachklick-Filter",
"adv.eggButtonTitle": "Mehrfachklick und Belegung",
"adv.eggSensor": "Sensor-Steuerung",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -686,6 +686,8 @@ export const es: Record<I18nKey, string> = {
"adv.applyStage": "Aplicar etapa",
"adv.mapping": "Mapeo",
"adv.razerLocked": "{name} está fijado en la capa Standard y no se puede reasignar ni desactivar.",
"adv.keyboardShortcut": "Atajo de teclado…",
"adv.pressKey": "Pulsa una tecla, Esc para cancelar",
"adv.multiclick": "Filtro de multiclic",
"adv.eggButtonTitle": "Multiclic y mapeo",
"adv.eggSensor": "Controles del sensor",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -686,6 +686,8 @@ export const fr: Record<I18nKey, string> = {
"adv.applyStage": "Appliquer l'étape",
"adv.mapping": "Mappage",
"adv.razerLocked": "{name} est fixé sur la couche Standard et ne peut pas être réaffecté ou désactivé.",
"adv.keyboardShortcut": "Raccourci clavier…",
"adv.pressKey": "Appuyez sur une touche, Échap pour annuler",
"adv.multiclick": "Filtre multiclic",
"adv.eggButtonTitle": "Multiclic et mappage",
"adv.eggSensor": "Contrôles du capteur",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -686,6 +686,8 @@ export const ja: Record<I18nKey, string> = {
"adv.applyStage": "ステージを適用",
"adv.mapping": "マッピング",
"adv.razerLocked": "{name}はStandardレイヤーに固定されており、再割り当てや無効化はできません。",
"adv.keyboardShortcut": "キーボードショートカット…",
"adv.pressKey": "キーを押してください(Esc でキャンセル)",
"adv.multiclick": "マルチクリックフィルター",
"adv.eggButtonTitle": "マルチクリックとマッピング",
"adv.eggSensor": "センサーコントロール",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/ko.ts
Original file line number Diff line number Diff line change
Expand Up @@ -686,6 +686,8 @@ export const ko: Record<I18nKey, string> = {
"adv.applyStage": "단계 적용",
"adv.mapping": "매핑",
"adv.razerLocked": "{name}은(는) Standard 레이어에 고정되어 재할당하거나 비활성화할 수 없습니다.",
"adv.keyboardShortcut": "키보드 단축키…",
"adv.pressKey": "키를 누르세요 (Esc로 취소)",
"adv.multiclick": "다중 클릭 필터",
"adv.eggButtonTitle": "다중 클릭 및 매핑",
"adv.eggSensor": "센서 컨트롤",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/pt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -686,6 +686,8 @@ export const pt: Record<I18nKey, string> = {
"adv.applyStage": "Aplicar estágio",
"adv.mapping": "Mapeamento",
"adv.razerLocked": "{name} é fixo na camada Standard e não pode ser reatribuído nem desativado.",
"adv.keyboardShortcut": "Atalho de teclado…",
"adv.pressKey": "Pressione uma tecla, Esc para cancelar",
"adv.multiclick": "Filtro multiclique",
"adv.eggButtonTitle": "Multiclique e mapeamento",
"adv.eggSensor": "Controles do sensor",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/ru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -685,6 +685,8 @@ export const ru: Record<I18nKey, string> = {
"adv.applyStage": "Применить ступень",
"adv.mapping": "Назначение",
"adv.razerLocked": "{name} закреплена на слое Standard и не переназначается и не отключается.",
"adv.keyboardShortcut": "Сочетание клавиш…",
"adv.pressKey": "Нажмите клавишу, Esc для отмены",
"adv.multiclick": "Фильтр мультикликов",
"adv.eggButtonTitle": "Мультиклик и назначение",
"adv.eggSensor": "Управление сенсором",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/tr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -674,6 +674,8 @@ export const tr: Record<I18nKey, string> = {
"adv.applyStage": "Kademeyi uygula",
"adv.mapping": "Eşleme",
"adv.razerLocked": "{name}, Standart katmanda sabittir; yeniden atanamaz veya devre dışı bırakılamaz.",
"adv.keyboardShortcut": "Klavye kısayolu…",
"adv.pressKey": "Bir tuşa basın, iptal için Esc",
"adv.multiclick": "Çoklu tıklama filtresi",
"adv.eggButtonTitle": "Çoklu tıklama ve eşleme",
"adv.eggSensor": "Sensör denetimleri",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/locales/vi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -636,6 +636,8 @@ export const vi: Record<I18nKey, string> = {
"adv.applyStage": "Áp dụng stage",
"adv.mapping": "Gán nút",
"adv.razerLocked": "{name} được cố định trên layer Standard và không thể gán lại hoặc tắt.",
"adv.keyboardShortcut": "Phím tắt…",
"adv.pressKey": "Nhấn một phím, Esc để huỷ",
"adv.multiclick": "Bộ lọc multiclick",
"adv.eggButtonTitle": "Multiclick và gán nút",
"adv.eggSensor": "Điều khiển cảm biến",
Expand Down
Loading