diff --git a/src/device/controller.ts b/src/device/controller.ts index 71e52d19..ba94a3bd 100644 --- a/src/device/controller.ts +++ b/src/device/controller.ts @@ -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, @@ -143,6 +144,7 @@ import type { RazerHidClient } from "@openmouse/protocol/drivers/razer/hid"; import type { RazerButtonControl, RazerButtonMapping, + RazerKeyAction, RazerToggleControl, } from "@openmouse/protocol/razer"; import type { RazerViperMiniHidClient } from "@openmouse/protocol/drivers/razer/viper-mini-hid"; @@ -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); @@ -6975,34 +6982,106 @@ 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(CM()?.RazerHidClient); +type ButtonMappingClient = { + setButtonMapping(control: RazerButtonControl, mapping: RazerButtonMapping, layer?: number): Promise; +}; +type ToggleControlClient = Pick; + +function razerClientWith(method: string): Record | null { + const client = razerClient(); + if (!client) return null; + const candidate = client as unknown as Record; + 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, layer?: number): Promise; +}; + +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 { +export function applyRazerButtonMapping( + control: RazerButtonControl, + mapping: RazerButtonMapping, + layer: number = 0, +): void { if (!razerButtonClient()) return; + const base = C().RAZER_BUTTON_CONTROL_LABEL[control]; + const name = layer === 1 ? `${base} (Hypershift)` : base; stageChange({ - key: `razer-button-${control}`, - label: `${C().RAZER_BUTTON_CONTROL_LABEL[control]} → ${mapping}`, - command: `Change ${C().RAZER_BUTTON_CONTROL_LABEL[control]} mapping`, - progress: `Changing ${C().RAZER_BUTTON_CONTROL_LABEL[control]} mapping…`, + key: `razer-button-${control}${layer === 1 ? "-hypershift" : ""}`, + label: `${name} → ${mapping}`, + command: `Change ${name} mapping`, + progress: `Changing ${name} mapping…`, preview: (status) => { - if (status.razerButtonMappings) status.razerButtonMappings[control] = mapping; + const map = layer === 1 ? status.razerHypershiftMappings : status.razerButtonMappings; + if (map) map[control] = mapping; }, apply: async () => { const client = razerButtonClient(); if (!client) throw new Error(st("ctl.gone")); - await client.setButtonMapping(control, mapping); + await client.setButtonMapping(control, mapping, layer); + }, + }); +} + +/** + * 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 ` and physically sends it, confirmed with `wev`. + */ +export function applyRazerKeyMapping( + control: RazerButtonControl, + key: RazerKeyAction, + layer: number = 0, +): void { + if (!razerKeyClient()) return; + const base = C().RAZER_BUTTON_CONTROL_LABEL[control]; + const name = layer === 1 ? `${base} (Hypershift)` : base; + const label = C().razerKeyLabel(key); + stageChange({ + key: `razer-button-${control}${layer === 1 ? "-hypershift" : ""}`, + label: `${name} → ${label}`, + command: `Change ${name} mapping`, + progress: `Changing ${name} mapping…`, + preview: (status) => { + const map = layer === 1 ? status.razerHypershiftMappings : status.razerButtonMappings; + if (map) map[control] = label; + }, + apply: async () => { + const client = razerKeyClient(); + if (!client) throw new Error(st("ctl.gone")); + await client.setKeyboardMapping(control, key, layer); }, }); } 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}`, @@ -7013,7 +7092,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); }, diff --git a/src/device/incott-macros.ts b/src/device/incott-macros.ts index 00489316..7624ec98 100644 --- a/src/device/incott-macros.ts +++ b/src/device/incott-macros.ts @@ -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 @@ -325,20 +326,10 @@ export const INCOTT_MACRO_DEFAULT_ACTION: Readonly([ - ...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([ @@ -347,10 +338,6 @@ const MOUSE_BY_BUTTON = new Map([ [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; } @@ -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], }; diff --git a/src/features/devices/cards/AdvancedCards.tsx b/src/features/devices/cards/AdvancedCards.tsx index 8c9bcd53..ad8573ce 100644 --- a/src/features/devices/cards/AdvancedCards.tsx +++ b/src/features/devices/cards/AdvancedCards.tsx @@ -10,9 +10,9 @@ 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, @@ -20,6 +20,7 @@ import { 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"; @@ -1587,26 +1588,77 @@ 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; - if (!mappings) return null; + const standard = snapshot.status?.razerButtonMappings; + // Written values only: this firmware answers a class `0x02` read with + // whichever layer was written last, so a "read" of Hypershift is the Standard + // value and must not be shown as if it were the layer's contents. + const hypershift = snapshot.status?.razerHypershiftMappings; + const layerWritable = snapshot.status?.razerHypershiftWritable === true; + // Only the models whose firmware was checked for the key encoding offer it — + // the Viper Mini stores `02 02 ` where the older clients have + // no keyboard write at all. + const keyCapable = control.supportsRazerKeyMapping(); + const [layer, setLayer] = useState(0); + const [capturing, setCapturing] = useState<{ control: RazerButtonControl; layer: number } | null>(null); + useEffect(() => { + setCapturing(null); + // A different mouse has its own layers; never carry the switch across. + if (!snapshot.status?.razerHypershiftMappings) setLayer(0); + }, [snapshot.activeDeviceKey, snapshot.status?.razerHypershiftMappings]); + 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.control, { mods, usage }, capturing.layer); + setCapturing(null); + }; + window.addEventListener("keydown", onKeyDown, true); + return () => window.removeEventListener("keydown", onKeyDown, true); + }, [capturing]); + if (!standard) return null; + const mappings = layer === 1 ? (hypershift ?? {}) : standard; 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; + // On Hypershift a control nobody has written to yet is unknown, not absent: + // keep the row so it can be set, and show it as unread. + if (!current && layer === 0) continue; rows.push({ key: `razer-button-${con}`, name: RAZER_BUTTON_CONTROL_LABEL[con], - current, - options: RAZER_BUTTON_MAPPINGS, + current: current ?? "", + 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, }); } - for (const con of RAZER_TOGGLE_CONTROLS) { + for (const con of layer === 1 ? [] : RAZER_TOGGLE_CONTROLS) { const current = mappings[con]; if (!current) continue; const info = RAZER_TOGGLE_CONTROL_INFO[con]; @@ -1632,15 +1684,35 @@ export function RazerButtonCard({ snapshot }: { snapshot: ControlSnapshot }): Re

{t(locale, "adv.mapping")}

+ {layerWritable ? ( + + ) : null}
{rows.map((row) => { const staged = snapshot.pending.keys.includes(row.key); - const known = row.options.includes(row.current); + const known = row.current !== "" && 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({ control: rowControl, layer }); + return; + } if (row.key.startsWith("razer-button-")) { control.applyRazerButtonMapping( row.key.slice("razer-button-".length) as RazerButtonControl, value as RazerButtonMapping, + layer, ); } else { control.applyRazerToggleControl( @@ -1656,15 +1728,27 @@ export function RazerButtonCard({ snapshot }: { snapshot: ControlSnapshot }): Re data-pending-key={row.key} > {displayText(locale, row.name)} - {row.locked ? {displayText(locale, row.current)} : ( + {row.locked ? {displayText(locale, row.current)} : capturing !== null && capturing?.control === rowControl ? ( + + {t(locale, "adv.pressKey")} + + + ) : ( ({ value: option, label: option })), + ...(keyCapable && rowControl + ? [{ value: RAZER_KEY_OPTION, label: t(locale, "adv.keyboardShortcut") }] + : []), ]} - value={row.current} + value={row.current || null} disabled={busy} onChange={applyRazerRow} /> diff --git a/src/i18n/index.ts b/src/i18n/index.ts index 9a70e370..70da3a21 100644 --- a/src/i18n/index.ts +++ b/src/i18n/index.ts @@ -743,6 +743,12 @@ 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.razerLayer": "Button layer", + "adv.razerLayerStandard": "Normal", + "adv.razerLayerHypershift": "Hypershift", + "adv.razerLayerUnknown": "Not read", + "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", diff --git a/src/i18n/locales/ar.ts b/src/i18n/locales/ar.ts index cdfe7869..c7afb265 100644 --- a/src/i18n/locales/ar.ts +++ b/src/i18n/locales/ar.ts @@ -685,6 +685,12 @@ export const ar: Record = { "adv.applyStage": "تطبيق المرحلة", "adv.mapping": "الربط", "adv.razerLocked": "{name} ثابت على الطبقة القياسية ولا يمكن إعادة تعيينه أو تعطيله.", + "adv.razerLayer": "طبقة الأزرار", + "adv.razerLayerStandard": "عادي", + "adv.razerLayerHypershift": "Hypershift", + "adv.razerLayerUnknown": "لم تُقرأ", + "adv.keyboardShortcut": "اختصار لوحة المفاتيح…", + "adv.pressKey": "اضغط مفتاحًا، أو Esc للإلغاء", "adv.multiclick": "مرشح النقر المتعدد", "adv.eggButtonTitle": "النقر المتعدد والربط", "adv.eggSensor": "عناصر التحكم بالمستشعر", diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index f2075a7d..864e96ac 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -686,6 +686,12 @@ export const de: Record = { "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.razerLayer": "Tastenebene", + "adv.razerLayerStandard": "Normal", + "adv.razerLayerHypershift": "Hypershift", + "adv.razerLayerUnknown": "Nicht gelesen", + "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", diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index 34a7e0a3..210ca633 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -686,6 +686,12 @@ export const es: Record = { "adv.applyStage": "Aplicar etapa", "adv.mapping": "Mapeo", "adv.razerLocked": "{name} está fijado en la capa Standard y no se puede reasignar ni desactivar.", + "adv.razerLayer": "Capa de botones", + "adv.razerLayerStandard": "Normal", + "adv.razerLayerHypershift": "Hypershift", + "adv.razerLayerUnknown": "Sin leer", + "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", diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index e801b8a9..65d03e28 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -686,6 +686,12 @@ export const fr: Record = { "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.razerLayer": "Couche de boutons", + "adv.razerLayerStandard": "Normal", + "adv.razerLayerHypershift": "Hypershift", + "adv.razerLayerUnknown": "Non lu", + "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", diff --git a/src/i18n/locales/ja.ts b/src/i18n/locales/ja.ts index 782ad07a..04e9704e 100644 --- a/src/i18n/locales/ja.ts +++ b/src/i18n/locales/ja.ts @@ -686,6 +686,12 @@ export const ja: Record = { "adv.applyStage": "ステージを適用", "adv.mapping": "マッピング", "adv.razerLocked": "{name}はStandardレイヤーに固定されており、再割り当てや無効化はできません。", + "adv.razerLayer": "ボタンレイヤー", + "adv.razerLayerStandard": "通常", + "adv.razerLayerHypershift": "Hypershift", + "adv.razerLayerUnknown": "未読み取り", + "adv.keyboardShortcut": "キーボードショートカット…", + "adv.pressKey": "キーを押してください(Esc でキャンセル)", "adv.multiclick": "マルチクリックフィルター", "adv.eggButtonTitle": "マルチクリックとマッピング", "adv.eggSensor": "センサーコントロール", diff --git a/src/i18n/locales/ko.ts b/src/i18n/locales/ko.ts index 3006db45..4a949531 100644 --- a/src/i18n/locales/ko.ts +++ b/src/i18n/locales/ko.ts @@ -686,6 +686,12 @@ export const ko: Record = { "adv.applyStage": "단계 적용", "adv.mapping": "매핑", "adv.razerLocked": "{name}은(는) Standard 레이어에 고정되어 재할당하거나 비활성화할 수 없습니다.", + "adv.razerLayer": "버튼 레이어", + "adv.razerLayerStandard": "일반", + "adv.razerLayerHypershift": "Hypershift", + "adv.razerLayerUnknown": "읽지 않음", + "adv.keyboardShortcut": "키보드 단축키…", + "adv.pressKey": "키를 누르세요 (Esc로 취소)", "adv.multiclick": "다중 클릭 필터", "adv.eggButtonTitle": "다중 클릭 및 매핑", "adv.eggSensor": "센서 컨트롤", diff --git a/src/i18n/locales/pt.ts b/src/i18n/locales/pt.ts index 62f96c86..345bd638 100644 --- a/src/i18n/locales/pt.ts +++ b/src/i18n/locales/pt.ts @@ -686,6 +686,12 @@ export const pt: Record = { "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.razerLayer": "Camada de botões", + "adv.razerLayerStandard": "Normal", + "adv.razerLayerHypershift": "Hypershift", + "adv.razerLayerUnknown": "Não lido", + "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", diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index fd59167e..09c4e19f 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -685,6 +685,12 @@ export const ru: Record = { "adv.applyStage": "Применить ступень", "adv.mapping": "Назначение", "adv.razerLocked": "{name} закреплена на слое Standard и не переназначается и не отключается.", + "adv.razerLayer": "Слой кнопок", + "adv.razerLayerStandard": "Обычный", + "adv.razerLayerHypershift": "Hypershift", + "adv.razerLayerUnknown": "Не прочитано", + "adv.keyboardShortcut": "Сочетание клавиш…", + "adv.pressKey": "Нажмите клавишу, Esc для отмены", "adv.multiclick": "Фильтр мультикликов", "adv.eggButtonTitle": "Мультиклик и назначение", "adv.eggSensor": "Управление сенсором", diff --git a/src/i18n/locales/tr.ts b/src/i18n/locales/tr.ts index ed437bdb..50223a3c 100644 --- a/src/i18n/locales/tr.ts +++ b/src/i18n/locales/tr.ts @@ -674,6 +674,12 @@ export const tr: Record = { "adv.applyStage": "Kademeyi uygula", "adv.mapping": "Eşleme", "adv.razerLocked": "{name}, Standart katmanda sabittir; yeniden atanamaz veya devre dışı bırakılamaz.", + "adv.razerLayer": "Düğme katmanı", + "adv.razerLayerStandard": "Normal", + "adv.razerLayerHypershift": "Hypershift", + "adv.razerLayerUnknown": "Okunmadı", + "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", diff --git a/src/i18n/locales/vi.ts b/src/i18n/locales/vi.ts index a03e1ec3..43ae7821 100644 --- a/src/i18n/locales/vi.ts +++ b/src/i18n/locales/vi.ts @@ -636,6 +636,12 @@ export const vi: Record = { "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.razerLayer": "Lớp nút", + "adv.razerLayerStandard": "Thường", + "adv.razerLayerHypershift": "Hypershift", + "adv.razerLayerUnknown": "Chưa đọc", + "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", diff --git a/src/i18n/locales/zh.ts b/src/i18n/locales/zh.ts index be9c3860..de8b0958 100644 --- a/src/i18n/locales/zh.ts +++ b/src/i18n/locales/zh.ts @@ -686,6 +686,12 @@ export const zh: Record = { "adv.applyStage": "应用阶段", "adv.mapping": "映射", "adv.razerLocked": "{name} 固定在标准层,无法重新分配或禁用。", + "adv.razerLayer": "按键层", + "adv.razerLayerStandard": "标准", + "adv.razerLayerHypershift": "Hypershift", + "adv.razerLayerUnknown": "未读取", + "adv.keyboardShortcut": "键盘快捷键…", + "adv.pressKey": "按下按键,按 Esc 取消", "adv.multiclick": "多击滤波器", "adv.eggButtonTitle": "多击与映射", "adv.eggSensor": "传感器控制", diff --git a/src/shared/hid-keys.test.ts b/src/shared/hid-keys.test.ts new file mode 100644 index 00000000..a2f04880 --- /dev/null +++ b/src/shared/hid-keys.test.ts @@ -0,0 +1,20 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { RAZER_KEY_MODIFIERS, razerKeyLabel } from "@openmouse/protocol/razer"; +import { hidKeyUsage, keyChordFromLabel } from "./hid-keys.ts"; +import { incottMacroKeyForCode } from "../device/incott-macros.ts"; + +test("a Razer key label turns back into the key it was made from", () => { + const bits = Object.values(RAZER_KEY_MODIFIERS); + for (const key of [{ mods: 0x01, usage: 0x68 }, { mods: 0x0f, usage: 0x04 }, { mods: 0, usage: 0x73 }]) { + assert.deepEqual(keyChordFromLabel(razerKeyLabel(key), razerKeyLabel, bits), key); + } + assert.equal(keyChordFromLabel("Middle Click", razerKeyLabel, bits), null); +}); + +test("F13 to F24 can be captured without joining the Incott key list", () => { + assert.equal(hidKeyUsage("F13"), 0x68); + assert.equal(hidKeyUsage("F24"), 0x73); + assert.equal(incottMacroKeyForCode("F13"), null); + assert.equal(incottMacroKeyForCode("F12"), 0x45); +}); diff --git a/src/shared/hid-keys.ts b/src/shared/hid-keys.ts new file mode 100644 index 00000000..b10f4e4e --- /dev/null +++ b/src/shared/hid-keys.ts @@ -0,0 +1,54 @@ +/** + * Browser `KeyboardEvent.code` -> HID keyboard usage. + * + * One table for every card that lets a user press a key to bind it. Keys outside + * it are left out on purpose: a code with no usage would be written to a device + * as a key it cannot name back. + */ +const KEY_BY_CODE = new Map([ + ...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], +]); + +const EXTENDED_KEY_BY_CODE = new Map( + Array.from({ length: 12 }, (_, i) => [`F${i + 13}`, 0x68 + i] as const), +); + +export function hidKeyUsage(code: string): number | null { + return KEY_BY_CODE.get(code) ?? EXTENDED_KEY_BY_CODE.get(code) ?? null; +} + +/** Every usage the table can produce, for menus that list bindable keys. */ +export const HID_KEY_USAGES: readonly number[] = [...new Set(KEY_BY_CODE.values())]; + +export function keyChordFromLabel( + label: string, + toLabel: (key: { mods: number; usage: number }) => string, + modifierBits: readonly number[], +): { mods: number; usage: number } | null { + for (let set = 0; set < 1 << modifierBits.length; set += 1) { + const mods = modifierBits.reduce((sum, bit, index) => (set & (1 << index) ? sum | bit : sum), 0); + for (let usage = 0; usage < 0x100; usage += 1) { + if (toLabel({ mods, usage }) === label) return { mods, usage }; + } + } + return null; +} + +/** True for a bare modifier press, which a chord recorder waits past. */ +export function isModifierCode(code: string): boolean { + return code === "ShiftLeft" || code === "ShiftRight" + || code === "ControlLeft" || code === "ControlRight" + || code === "AltLeft" || code === "AltRight" + || code === "MetaLeft" || code === "MetaRight"; +}