diff --git a/public/devices/xiaomi-mi-gaming-mouse.png b/public/devices/xiaomi-mi-gaming-mouse.png new file mode 100644 index 00000000..74df4297 Binary files /dev/null and b/public/devices/xiaomi-mi-gaming-mouse.png differ diff --git a/src/device/controller.ts b/src/device/controller.ts index fedcaac1..25e111bf 100644 --- a/src/device/controller.ts +++ b/src/device/controller.ts @@ -98,6 +98,8 @@ import { ensureDriverModules, driverModules, type DriverModules } from "./driver import type { MagneticButtonStatus, MouseLighting, MouseStatus } from "@openmouse/protocol/drivers/mouse-types"; import type { KsnakeMacroProfile } from "@openmouse/protocol/ksnake"; import type { WallhackCurvePoint, WallhackMacroStep } from "@openmouse/protocol/wallhack"; +import type { XiaomiBinding, XiaomiMacroEvent } from "@openmouse/protocol/xiaomi"; +import { XIAOMI_BUTTON_NAMES, XIAOMI_KEY_COMBOS, XIAOMI_MACRO_EVENT_SIZE } from "@openmouse/protocol/xiaomi"; import { cloneM2NexProfile, loadM2NexProfiles, @@ -143,6 +145,7 @@ import type { WLMouseHidClient } from "@openmouse/protocol/drivers/wlmouse/hid"; import type { WLMouseBeastX4kHidClient } from "@openmouse/protocol/drivers/wlmouse/beast-x-4k-hid"; import type { DareuHidClient } from "@openmouse/protocol/drivers/dareu/hid"; import type { IncottHidClient } from "@openmouse/protocol/drivers/incott/hid"; +import type { XiaomiHidClient } from "@openmouse/protocol/drivers/xiaomi/hid"; import type { IncottMacro } from "@openmouse/protocol/incott"; import { BASILISK_V3_PRO_BLUETOOTH, HID_FILTERS } from "./hid-filters"; import { VENDOR_ID } from "@openmouse/protocol/drivers/vendors"; @@ -272,7 +275,7 @@ const needsOpenClasses = (): Array | undefined> => CM()?.MchoseHidClient, CM()?.MchoseDockHidClient, CM()?.MchoseA5ProMaxHidClient, CM()?.MchoseV3HidClient, CM()?.MicrosoftHidClient, CM()?.DareuHidClient, CM()?.IncottHidClient, CM()?.BytechHidClient, CM()?.RapooHidClient, CM()?.FaterHidClient, CM()?.CoolerMasterHidClient, CM()?.RedragonM690ProHidClient, CM()?.AjazzHidClient, - CM()?.HitscanHidClient, + CM()?.HitscanHidClient, CM()?.XiaomiHidClient, ]; const pulsarClasses = (): Array | undefined> => [CM()?.PulsarHidClient, CM()?.PulsarProHidClient, CM()?.PulsarXs1HidClient]; @@ -300,6 +303,7 @@ const keychron4kClient = (): Keychron4kHidClient | null => activeAs(CM()?.Keychr const wlmouse4kClient = (): WLMouseBeastX4kHidClient | null => activeAs(CM()?.WLMouseBeastX4kHidClient); const wallhackMouseClient = (): WallhackMouseHidClient | null => activeAs(CM()?.WallhackMouseHidClient); const incottClient = (): IncottHidClient | null => activeAs(CM()?.IncottHidClient); +const xiaomiMacroClient = (): XiaomiHidClient | null => activeAs(CM()?.XiaomiHidClient); /** Pulsar is the only family with the collection-explorer onboarding path. */ const pulsarClient = (): PulsarClient | null => active !== null ? activeAs(...pulsarClasses()) : null; @@ -329,6 +333,10 @@ let ksnakeMacrosError: string | null = null; let wallhackMacros: (WallhackMacroStep[] | null)[] | null = null; let wallhackMacrosLoading = false; let wallhackMacrosError: string | null = null; +let xiaomiMacros: (XiaomiMacroEvent[] | null)[] | null = null; +let xiaomiBindings: (XiaomiBinding | null)[] | null = null; +let xiaomiMacrosLoading = false; +let xiaomiMacrosError: string | null = null; let wallhackCurves: Record<"classic" | "natural" | "jump" | "custom", WallhackCurvePoint[]> | null = null; let wallhackCurvesLoading = false; let wallhackCurvesError: string | null = null; @@ -588,6 +596,14 @@ const wallhackMacrosCache: SnapshotCloneCache = { + source: undefined, + output: undefined, +}; +const xiaomiBindingsCache: SnapshotCloneCache = { + source: undefined, + output: undefined, +}; const wallhackCurvesCache: SnapshotCloneCache = { source: undefined, output: undefined, @@ -603,6 +619,18 @@ function cloneWallhackMacrosSnapshot( return source?.map((steps) => steps?.map((step) => ({ ...step, event: { ...step.event } })) ?? null) ?? null; } +function cloneXiaomiMacrosSnapshot( + source: typeof xiaomiMacros, +): typeof xiaomiMacros { + return source?.map((events) => events?.map((event) => ({ ...event })) ?? null) ?? null; +} + +function cloneXiaomiBindingsSnapshot( + source: typeof xiaomiBindings, +): typeof xiaomiBindings { + return source?.map((binding) => (binding ? { ...binding } : null)) ?? null; +} + function cloneWallhackCurvesSnapshot( source: typeof wallhackCurves, ): typeof wallhackCurves { @@ -645,6 +673,7 @@ function buildSnapshot(): ControlSnapshot { toasts, devices: sidebarDevices, hasActiveDevice: activeDevice !== null, + activeDeviceKey: activeDeviceKey(), deviceArtwork: deviceArtwork(status), settingInProgress, atkR1SePlusPairingAvailable: isVxeR1SePlusReceiver(activeDevice), @@ -675,6 +704,10 @@ function buildSnapshot(): ControlSnapshot { wallhackMacros: cachedSnapshotClone(wallhackMacrosCache, wallhackMacros, cloneWallhackMacrosSnapshot), wallhackMacrosLoading, wallhackMacrosError, + xiaomiMacros: cachedSnapshotClone(xiaomiMacrosCache, xiaomiMacros, cloneXiaomiMacrosSnapshot), + xiaomiBindings: cachedSnapshotClone(xiaomiBindingsCache, xiaomiBindings, cloneXiaomiBindingsSnapshot), + xiaomiMacrosLoading, + xiaomiMacrosError, wallhackCurves: cachedSnapshotClone(wallhackCurvesCache, wallhackCurves, cloneWallhackCurvesSnapshot), wallhackCurvesLoading, wallhackCurvesError, @@ -1466,6 +1499,136 @@ export function clearWallhackMacroSlot(slot: number): void { }); } +/** Read the eight Xiaomi Mi Gaming Mouse button bindings and macro bodies. */ +export function loadXiaomiMacros(): void { + if (xiaomiMacrosLoading || xiaomiMacros !== null) return; + const client = xiaomiMacroClient(); + if (!client) { + xiaomiMacrosError = st("macro.notReady"); + emit(); + return; + } + xiaomiMacrosLoading = true; + xiaomiMacrosError = null; + emit(); + void (async () => { + try { + const macros: (XiaomiMacroEvent[] | null)[] = []; + const bindings: (XiaomiBinding | null)[] = []; + for (let button = 0; button < 8; button++) { + const binding = await client.readBinding(button); + bindings.push({ ...binding }); + if (binding.mode === XIAOMI_KEY_COMBOS.MACROS_NO_DELAY || binding.mode === XIAOMI_KEY_COMBOS.MACROS_WITH_DELAY) { + macros.push((await client.readMacro(button)).map((event) => ({ ...event }))); + } else { + macros.push(null); + } + } + if (xiaomiMacroClient() !== client) return; + xiaomiMacros = macros; + xiaomiBindings = bindings; + xiaomiMacrosError = null; + } catch (error) { + // A departed client must not write its error into the current device's + // snapshot; the new device's own load will set its state. + if (xiaomiMacroClient() !== client) return; + xiaomiMacrosError = error instanceof Error ? error.message : String(error); + } finally { + if (xiaomiMacroClient() !== client) return; + xiaomiMacrosLoading = false; + emit(); + } + })(); +} + +function setXiaomiBinding(button: number, binding: XiaomiBinding): void { + xiaomiBindings = (xiaomiBindings ?? [null, null, null, null, null, null, null, null]).map( + (entry, index) => (index === button ? { ...binding } : entry), + ); +} + +/** Stage a custom key-combo write for one Xiaomi button (0-7). */ +export function applyXiaomiCustomCombo(button: number, modifiers: number, key: number): void { + const client = xiaomiMacroClient(); + if (!client) { + setReadStatus(st("macro.notReady")); + emit(); + return; + } + stageChange({ + key: `xiaomi-combo-${button}`, + label: `Button ${button + 1} combo`, + command: `Save Xiaomi button ${button + 1} combo`, + progress: `Saving Xiaomi button ${button + 1} combo…`, + apply: async () => { + const live = xiaomiMacroClient(); + if (!live) throw new Error(st("ctl.gone")); + await live.setBinding(button, XIAOMI_KEY_COMBOS.CUSTOM_KEY_COMBO, modifiers, key); + if (xiaomiMacroClient() === live) { + setXiaomiBinding(button, { mode: XIAOMI_KEY_COMBOS.CUSTOM_KEY_COMBO, modifiers, key }); + emit(); + } + }, + }); +} + +/** Stage a macro write for one Xiaomi button (0-7). */ +export function applyXiaomiMacro(button: number, mode: number, events: readonly XiaomiMacroEvent[]): void { + const client = xiaomiMacroClient(); + if (!client) { + setReadStatus(st("macro.notReady")); + emit(); + return; + } + const snapshot = events.map((event) => ({ ...event })); + stageChange({ + key: `xiaomi-macro-${button}`, + label: `Button ${button + 1} macro`, + command: `Save Xiaomi button ${button + 1} macro`, + progress: `Saving Xiaomi button ${button + 1} macro…`, + apply: async () => { + const live = xiaomiMacroClient(); + if (!live) throw new Error(st("ctl.gone")); + await live.setMacro(button, mode, snapshot); + if (xiaomiMacroClient() === live) { + xiaomiMacros = (xiaomiMacros ?? [null, null, null, null, null, null, null, null]).map((entry, index) => + index === button ? snapshot.map((event) => ({ ...event })) : entry, + ); + setXiaomiBinding(button, { mode, macroSize: snapshot.length * XIAOMI_MACRO_EVENT_SIZE }); + emit(); + } + }, + }); +} + +/** Stage clearing the macro bound to one Xiaomi button (0-7). */ +export function clearXiaomiMacro(button: number): void { + const client = xiaomiMacroClient(); + if (!client) { + setReadStatus(st("macro.notReady")); + emit(); + return; + } + stageChange({ + key: `xiaomi-macro-${button}`, + label: `Clear button ${button + 1} macro`, + command: `Clear Xiaomi button ${button + 1} macro`, + progress: `Clearing Xiaomi button ${button + 1} macro…`, + apply: async () => { + const live = xiaomiMacroClient(); + if (!live) throw new Error(st("ctl.gone")); + await live.setMacro(button, XIAOMI_KEY_COMBOS.MACROS_NO_DELAY, []); + if (xiaomiMacroClient() === live) { + xiaomiMacros = (xiaomiMacros ?? [null, null, null, null, null, null, null, null]).map((entry, index) => + index === button ? null : entry, + ); + setXiaomiBinding(button, { mode: XIAOMI_KEY_COMBOS.MACROS_NO_DELAY, macroSize: 0 }); + emit(); + } + }, + }); +} + function readCapabilities(): DeviceCapabilities { const razer = activeAs(CM()?.RazerHidClient); const dm = dmClient(); @@ -3766,6 +3929,9 @@ async function activateClientNow(client: SupportedClient, options: { rememberRec wallhackCurves = null; wallhackCurvesLoading = false; wallhackCurvesError = null; + xiaomiMacros = null; + xiaomiMacrosLoading = false; + xiaomiMacrosError = null; m2nexProfiles = null; activeM2NexProfile = 0; m2nexProfileDirty = false; @@ -4009,6 +4175,9 @@ function showDisconnectedState(): void { wallhackCurves = null; wallhackCurvesLoading = false; wallhackCurvesError = null; + xiaomiMacros = null; + xiaomiMacrosLoading = false; + xiaomiMacrosError = null; m2nexProfiles = null; activeM2NexProfile = 0; m2nexProfileDirty = false; @@ -6797,6 +6966,13 @@ export function applyDeviceButtonMapping(button: string, action: string): void { // remap to anything else supersedes it, and must do so even when stageChange // drops the remap as "already matches", or Apply would still bind Macro. if (action !== "Macro") dropPendingChange(`incott-macro-${button}`); + // A staged Xiaomi combo/macro write is superseded by any preset remap. The + // combo/macro keys use the wire button index, not the display name. + const xiaomiButtonIndex = XIAOMI_BUTTON_NAMES.indexOf(button as (typeof XIAOMI_BUTTON_NAMES)[number]); + if (xiaomiButtonIndex !== -1) { + dropPendingChange(`xiaomi-combo-${xiaomiButtonIndex}`); + dropPendingChange(`xiaomi-macro-${xiaomiButtonIndex}`); + } stageChange({ key: `button-${button}`, label: `${button}: ${action}`, diff --git a/src/device/driver-classes.ts b/src/device/driver-classes.ts index 11d6cac2..5a195874 100644 --- a/src/device/driver-classes.ts +++ b/src/device/driver-classes.ts @@ -76,7 +76,8 @@ export type DriverModules = typeof import("@openmouse/protocol/drivers/endgame/e & typeof import("@openmouse/protocol/drivers/coolermaster/hid") & typeof import("@openmouse/protocol/drivers/ajazz/hid") & typeof import("@openmouse/protocol/drivers/redragon/m690-pro-hid") - & typeof import("@openmouse/protocol/drivers/hitscan/hid"); + & typeof import("@openmouse/protocol/drivers/hitscan/hid") + & typeof import("@openmouse/protocol/drivers/xiaomi/hid"); let loaded: DriverModules | null = null; let loading: Promise | null = null; @@ -143,6 +144,7 @@ export function ensureDriverModules(): Promise { import("@openmouse/protocol/drivers/ajazz/hid"), import("@openmouse/protocol/drivers/redragon/m690-pro-hid"), import("@openmouse/protocol/drivers/hitscan/hid"), + import("@openmouse/protocol/drivers/xiaomi/hid"), ]).then((mods) => (loaded = Object.assign({}, ...mods) as DriverModules)); return loading; } diff --git a/src/device/types.ts b/src/device/types.ts index 481a95e1..3f7c7932 100644 --- a/src/device/types.ts +++ b/src/device/types.ts @@ -5,6 +5,7 @@ import type { KsnakeMacroProfile } from "@openmouse/protocol/ksnake"; import type { KeychronNapeLayerKeymap } from "@openmouse/protocol/keychron"; import type { LogitechReprogrammableControl } from "@openmouse/protocol/logitech"; import type { WallhackCurvePoint, WallhackMacroStep } from "@openmouse/protocol/wallhack"; +import type { XiaomiBinding, XiaomiMacroEvent } from "@openmouse/protocol/xiaomi"; import type { DpiStageCapabilities, DpiStagePlan, OnboardProfile } from "@openmouse/protocol/drivers/logitech/onboard-profiles"; import type { InterfacePreferences } from "../features/settings/interface-preferences"; import type { PreviewMode } from "./preview/preview-modes"; @@ -255,6 +256,8 @@ export interface ControlSnapshot { devices: SidebarDevice[]; hasActiveDevice: boolean; + /** Identity of the active device (vendorId:productId:name), or null. */ + activeDeviceKey: string | null; deviceArtwork: string | null; settingInProgress: boolean; atkR1SePlusPairingAvailable: boolean; @@ -315,6 +318,16 @@ export interface ControlSnapshot { wallhackMacros: (WallhackMacroStep[] | null)[] | null; wallhackMacrosLoading: boolean; wallhackMacrosError: string | null; + /** + * Xiaomi Mi Gaming Mouse per-button macro slots (8), read from the device. + * A slot is null when the button is not bound to a macro mode. Macros are + * saved per button through applyXiaomiMacro. + */ + xiaomiMacros: (XiaomiMacroEvent[] | null)[] | null; + /** Per-button binding state (mode/modifiers/key) for the eight Xiaomi buttons. */ + xiaomiBindings: (XiaomiBinding | null)[] | null; + xiaomiMacrosLoading: boolean; + xiaomiMacrosError: string | null; wallhackCurves: Record<"classic" | "natural" | "jump" | "custom", WallhackCurvePoint[]> | null; wallhackCurvesLoading: boolean; wallhackCurvesError: string | null; diff --git a/src/features/devices/OverviewPage.tsx b/src/features/devices/OverviewPage.tsx index 81b34d0e..ef338819 100644 --- a/src/features/devices/OverviewPage.tsx +++ b/src/features/devices/OverviewPage.tsx @@ -51,6 +51,7 @@ import { ButtonMappingCard, KsnakeMacroCard, WallhackMacroCard, + XiaomiMacroCard, PowerModeCard, OnboardProfileCard, PulsarProCard, @@ -401,6 +402,7 @@ export function Workspace({ show(has.ksnakeMacros, ["macro"]) ? : null, show(has.wallhackMacros, ["macro"]) ? : null, show(has.incottMacros, ["macro"]) ? : null, + show(has.xiaomiMacros, ["macro"]) ? : null, ].filter((node) => node !== null); const advanced = [ diff --git a/src/features/devices/cards/AdvancedCards.tsx b/src/features/devices/cards/AdvancedCards.tsx index afd85a6d..71545a36 100644 --- a/src/features/devices/cards/AdvancedCards.tsx +++ b/src/features/devices/cards/AdvancedCards.tsx @@ -23,6 +23,14 @@ import { import { teevolutionSensorModeUi } from "@openmouse/protocol/teevolution"; import type { KsnakeMacroProfile, KsnakeMacroStep } from "@openmouse/protocol/ksnake"; import type { WallhackMacroStep } from "@openmouse/protocol/wallhack"; +import { + XIAOMI_BUTTON_NAMES, + XIAOMI_KEY_CODES, + XIAOMI_KEY_COMBOS, + XIAOMI_KEY_MODIFIERS, + xiaomiBindingLabel, + type XiaomiMacroEvent, +} from "@openmouse/protocol/xiaomi"; import { isPulsarProProtocol } from "../../../device/traits"; import { isNoirKsnakeStatus } from "../../../device/noir.ts"; import { @@ -2355,6 +2363,502 @@ export function KsnakeMacroCard({ snapshot }: { snapshot: ControlSnapshot }): Re ); } +/** + * Xiaomi Mi Gaming Mouse button bindings: each of the eight bindable buttons + * gets either a custom key combo (modifier mask + HID key) or a macro (a list + * of press/release events, optionally with a per-event delay before it). + */ +const XIAOMI_MODIFIER_BITS: ReadonlyArray<{ bit: number; label: string }> = [ + { bit: XIAOMI_KEY_MODIFIERS.LEFT_CTRL, label: "Ctrl" }, + { bit: XIAOMI_KEY_MODIFIERS.LEFT_SHIFT, label: "Shift" }, + { bit: XIAOMI_KEY_MODIFIERS.LEFT_ALT, label: "Alt" }, + { bit: XIAOMI_KEY_MODIFIERS.LEFT_WIN, label: "Win" }, + { bit: XIAOMI_KEY_MODIFIERS.RIGHT_CTRL, label: "R-Ctrl" }, + { bit: XIAOMI_KEY_MODIFIERS.RIGHT_SHIFT, label: "R-Shift" }, + { bit: XIAOMI_KEY_MODIFIERS.RIGHT_ALT, label: "R-Alt" }, + { bit: XIAOMI_KEY_MODIFIERS.RIGHT_WIN, label: "R-Win" }, +]; + +const XIAOMI_KEY_CODE_BY_EVENT_CODE: Readonly> = { + ...Object.fromEntries("ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("").map((letter, index) => [`Key${letter}`, XIAOMI_KEY_CODES.A + index])), + ...Object.fromEntries(["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"].map((digit, index) => [`Digit${digit}`, XIAOMI_KEY_CODES.ONE + index])), + Enter: XIAOMI_KEY_CODES.ENTER, + Escape: XIAOMI_KEY_CODES.ESCAPE, + Backspace: XIAOMI_KEY_CODES.BACKSPACE, + Tab: XIAOMI_KEY_CODES.TAB, + Space: XIAOMI_KEY_CODES.SPACE, + Minus: XIAOMI_KEY_CODES.SUB, + Equal: XIAOMI_KEY_CODES.EQUAL, + BracketLeft: XIAOMI_KEY_CODES.SQR_BRKT_OPEN, + BracketRight: XIAOMI_KEY_CODES.SQR_BRKT_CLOSE, + Backslash: XIAOMI_KEY_CODES.BACKSLASH, + Semicolon: XIAOMI_KEY_CODES.SEMICOLON, + Quote: XIAOMI_KEY_CODES.APOSTROPHE, + Backquote: XIAOMI_KEY_CODES.BACKTICK, + Comma: XIAOMI_KEY_CODES.COMMA, + Period: XIAOMI_KEY_CODES.DOT, + Slash: XIAOMI_KEY_CODES.SLASH, + CapsLock: XIAOMI_KEY_CODES.CAPS_LOCK, + ...Object.fromEntries(Array.from({ length: 12 }, (_, index) => [`F${index + 1}`, XIAOMI_KEY_CODES.F1 + index])), + PrintScreen: XIAOMI_KEY_CODES.PRINT_SCREEN, + ScrollLock: XIAOMI_KEY_CODES.SCROLL_LOCK, + Pause: XIAOMI_KEY_CODES.PAUSE, + Insert: XIAOMI_KEY_CODES.INSERT, + Home: XIAOMI_KEY_CODES.HOME, + PageUp: XIAOMI_KEY_CODES.PAGE_UP, + Delete: XIAOMI_KEY_CODES.DELETE, + End: XIAOMI_KEY_CODES.END, + PageDown: XIAOMI_KEY_CODES.PAGE_DOWN, + ArrowRight: XIAOMI_KEY_CODES.RIGHT_ARROW, + ArrowLeft: XIAOMI_KEY_CODES.LEFT_ARROW, + ArrowDown: XIAOMI_KEY_CODES.DOWN_ARROW, + ArrowUp: XIAOMI_KEY_CODES.UP_ARROW, + NumLock: XIAOMI_KEY_CODES.NUM_LOCK, + NumpadDivide: XIAOMI_KEY_CODES.NUMPAD_DIV, + NumpadMultiply: XIAOMI_KEY_CODES.NUMPAD_MULT, + NumpadSubtract: XIAOMI_KEY_CODES.NUMPAD_SUB, + NumpadAdd: XIAOMI_KEY_CODES.NUMPAD_ADD, + NumpadEnter: XIAOMI_KEY_CODES.NUMPAD_ENTER, + ...Object.fromEntries(Array.from({ length: 9 }, (_, index) => [`Numpad${index + 1}`, XIAOMI_KEY_CODES.NUMPAD_1 + index])), + Numpad0: XIAOMI_KEY_CODES.NUMPAD_0, + NumpadDecimal: XIAOMI_KEY_CODES.NUMPAD_DOT, + ControlLeft: XIAOMI_KEY_CODES.LEFT_CTRL, + ShiftLeft: XIAOMI_KEY_CODES.LEFT_SHIFT, + AltLeft: XIAOMI_KEY_CODES.LEFT_ALT, + MetaLeft: XIAOMI_KEY_CODES.LEFT_WIN, + OSLeft: XIAOMI_KEY_CODES.LEFT_WIN, + ControlRight: XIAOMI_KEY_CODES.RIGHT_CTRL, + ShiftRight: XIAOMI_KEY_CODES.RIGHT_SHIFT, + AltRight: XIAOMI_KEY_CODES.RIGHT_ALT, + MetaRight: XIAOMI_KEY_CODES.RIGHT_WIN, + OSRight: XIAOMI_KEY_CODES.RIGHT_WIN, +}; + +const XIAOMI_KEY_CODE_NAMES: Readonly> = Object.fromEntries( + Object.entries(XIAOMI_KEY_CODES).map(([name, code]) => [code, name.replace(/_/g, " ")]), +); + +function xiaomiKeyCodeLabel(code: number): string { + return XIAOMI_KEY_CODE_NAMES[code] ?? `0x${code.toString(16)}`; +} + +function xiaomiMacroEventLabel(event: XiaomiMacroEvent): string { + return `${event.state === 0 ? "Press" : "Release"} · ${xiaomiKeyCodeLabel(event.key)}`; +} + +export function XiaomiMacroCard({ snapshot }: { snapshot: ControlSnapshot }): ReactNode { + const status = snapshot.status; + const locale = snapshot.preferences.locale; + const macroCapable = status?.ui?.family === "xiaomi"; + const bindings = snapshot.xiaomiBindings ?? null; + const macros = snapshot.xiaomiMacros ?? null; + + const [button, setButton] = useState(0); + const [mode, setMode] = useState<"combo" | "macro">("combo"); + const [modifiers, setModifiers] = useState(0); + const [key, setKey] = useState(XIAOMI_KEY_CODES.A); + const [timing, setTiming] = useState<"no-delay" | "with-delay">("no-delay"); + const [events, setEvents] = useState([]); + const [isRecording, setIsRecording] = useState(false); + const [recordedEvents, setRecordedEvents] = useState([]); + const recordedEventsRef = useRef([]); + const recordingClockRef = useRef(null); + const recorderFocusRef = useRef(null); + // Tracks the last (device, button, content) triple the sync effect applied, + // so a snapshot rebuild that leaves the selected button's binding/macro + // unchanged does not clobber an in-progress draft. The device key resets + // the sync state when the active device changes, discarding any draft. + const syncedSelectionRef = useRef<{ device: string | null; button: number; signature: string } | null>(null); + const lastDeviceKeyRef = useRef(null); + + const staged = snapshot.pending.keys.includes(`xiaomi-combo-${button}`) + || snapshot.pending.keys.includes(`xiaomi-macro-${button}`); + const disabled = snapshot.settingInProgress || snapshot.pending.busy; + const controlsDisabled = disabled || isRecording; + + // Cancel any in-progress recording when the active device changes, so keys + // pressed during the switch cannot be recorded into the new device's draft. + useEffect(() => { + const deviceKey = snapshot.activeDeviceKey; + if (lastDeviceKeyRef.current === null || lastDeviceKeyRef.current === deviceKey) { + lastDeviceKeyRef.current = deviceKey; + return; + } + lastDeviceKeyRef.current = deviceKey; + setIsRecording(false); + setRecordedEvents([]); + recordedEventsRef.current = []; + recordingClockRef.current = null; + }, [snapshot.activeDeviceKey]); + + // Prepare the editor from the device snapshot whenever the selected button + // changes or a read/apply completes. + useEffect(() => { + if (!bindings || !macros) return; + const binding = bindings[button]; + if (!binding) return; + // The snapshot arrays get new identity on every write (even for other + // buttons), so re-syncing on every rebuild would clobber an in-progress + // draft; only re-sync when the selected button's own content changed. + const signature = JSON.stringify([binding, macros[button] ?? null]); + const deviceKey = snapshot.activeDeviceKey; + const synced = syncedSelectionRef.current; + if (synced && synced.device === deviceKey && synced.button === button && synced.signature === signature) return; + syncedSelectionRef.current = { device: deviceKey, button, signature }; + if (binding.mode === XIAOMI_KEY_COMBOS.MACROS_NO_DELAY || binding.mode === XIAOMI_KEY_COMBOS.MACROS_WITH_DELAY) { + setMode("macro"); + setTiming(binding.mode === XIAOMI_KEY_COMBOS.MACROS_WITH_DELAY ? "with-delay" : "no-delay"); + setEvents((macros[button] ?? []).map((event) => ({ ...event }))); + } else if (binding.mode === XIAOMI_KEY_COMBOS.CUSTOM_KEY_COMBO) { + setMode("combo"); + setModifiers(binding.modifiers ?? 0); + setKey(binding.key ?? XIAOMI_KEY_CODES.A); + setEvents([]); + } else { + setMode("combo"); + setModifiers(0); + setKey(XIAOMI_KEY_CODES.A); + setEvents([]); + } + }, [bindings, macros, button, snapshot.activeDeviceKey]); + + useEffect(() => { + if (macroCapable + && snapshot.xiaomiMacros === null + && !snapshot.xiaomiMacrosLoading + && snapshot.xiaomiMacrosError === null) { + control.loadXiaomiMacros(); + } + }, [macroCapable, snapshot.xiaomiMacros, snapshot.xiaomiMacrosLoading, snapshot.xiaomiMacrosError]); + + const appendRecordedEvent = (event: XiaomiMacroEvent): void => { + const now = performance.now(); + const previous = recordingClockRef.current; + recordingClockRef.current = now; + const delayMs = previous === null + ? 0 + : Math.min(65535, Math.max(0, Math.round(now - previous))); + // Xiaomi stores the delay before each event, so the interval measured + // before the new event belongs to the new event itself. + const next = [...recordedEventsRef.current, { ...event, delayMs }]; + recordedEventsRef.current = next; + setRecordedEvents(next); + }; + + const finishRecording = (): void => { + const next = timing === "no-delay" + ? recordedEventsRef.current.map((event) => ({ ...event, delayMs: 0 })) + : recordedEventsRef.current.map((event) => ({ ...event })); + setIsRecording(false); + setEvents(next); + setRecordedEvents([]); + recordedEventsRef.current = []; + recordingClockRef.current = null; + }; + + const cancelRecording = (): void => { + setIsRecording(false); + setRecordedEvents([]); + recordedEventsRef.current = []; + recordingClockRef.current = null; + }; + + const startRecording = (): void => { + if (disabled || isRecording) return; + recordedEventsRef.current = []; + setRecordedEvents([]); + recordingClockRef.current = performance.now(); + setIsRecording(true); + }; + + useEffect(() => { + if (!isRecording) return undefined; + + // The Record button keeps focus after it is clicked. Keyboard events then + // target that button, and the recorder-control guard (correctly) ignores + // them as UI input. Move focus to a neutral capture surface so the first + // physical key pressed after starting a recording is captured. + recorderFocusRef.current?.focus(); + + const isRecorderControl = (target: EventTarget | null): boolean => ( + target instanceof Element && Boolean(target.closest("[data-macro-recorder-control]")) + ); + + const onKeyDown = (event: KeyboardEvent): void => { + if (isRecorderControl(event.target)) return; + if (event.code === "Escape") { + event.preventDefault(); + event.stopPropagation(); + finishRecording(); + return; + } + if (event.repeat) return; + const code = XIAOMI_KEY_CODE_BY_EVENT_CODE[event.code]; + if (code === undefined) return; + event.preventDefault(); + event.stopPropagation(); + appendRecordedEvent({ key: code, state: 0, delayMs: 0 }); + }; + + const onKeyUp = (event: KeyboardEvent): void => { + if (isRecorderControl(event.target)) return; + const code = XIAOMI_KEY_CODE_BY_EVENT_CODE[event.code]; + if (code === undefined) return; + event.preventDefault(); + event.stopPropagation(); + appendRecordedEvent({ key: code, state: 1, delayMs: 0 }); + }; + + window.addEventListener("keydown", onKeyDown, true); + window.addEventListener("keyup", onKeyUp, true); + return () => { + window.removeEventListener("keydown", onKeyDown, true); + window.removeEventListener("keyup", onKeyUp, true); + }; + }, [isRecording]); + + if (!status || !macroCapable) return null; + + const updateEvent = (index: number, change: Partial): void => { + setEvents((current) => current.map((event, eventIndex) => eventIndex === index ? { ...event, ...change } : event)); + }; + const addEvent = (): void => { + setEvents((current) => [...current, { key: XIAOMI_KEY_CODES.A, state: 0, delayMs: 0 }]); + }; + const removeEvent = (index: number): void => { + setEvents((current) => current.filter((_, eventIndex) => eventIndex !== index)); + }; + const saveMacro = (): void => { + const macroMode = timing === "with-delay" ? XIAOMI_KEY_COMBOS.MACROS_WITH_DELAY : XIAOMI_KEY_COMBOS.MACROS_NO_DELAY; + const next = timing === "no-delay" + ? events.map((event) => ({ ...event, delayMs: 0 })) + : events.map((event) => ({ ...event })); + control.applyXiaomiMacro(button, macroMode, next); + }; + + if (snapshot.xiaomiMacrosLoading) { + return ( +
+

{t(locale, "macro.build")}

+

{t(locale, "macro.xmLoading")}

+
+ ); + } + + if (snapshot.xiaomiMacrosError !== null) { + return ( +
+

{t(locale, "macro.build")}

+

{displayText(locale, snapshot.xiaomiMacrosError)}

+
+
+ ); + } + + if (!bindings || !macros) return null; + + return ( +
+
+
+

{t(locale, "macro.build")}

+

{t(locale, "macro.xmLead")}

+
+
+ + setMode(next)} + /> + {mode === "combo" ? ( +
+

{t(locale, "macro.xmComboHint")}

+
+ {t(locale, "macro.xmModifiers")} + {XIAOMI_MODIFIER_BITS.map(({ bit, label }) => ( + + ))} +
+ +
+ +
+
+ ) : ( + <> +

{t(locale, "macro.xmMacroHint")}

+ setTiming(next)} + /> +
+
+
+
+ {isRecording ? ( +
+ + +
+ ) : ( +
+ + +
+ )} +
+
+ {isRecording ? ( +
+
+ {t(locale, "macro.xmLiveEvents")} + {tp(locale, "macro.xmEvents", { n: recordedEvents.length })} +
+ {recordedEvents.length === 0 ? ( +

{t(locale, "macro.xmRecordingEmpty")}

+ ) : ( +
    + {recordedEvents.map((event, index) => ( +
  1. + {displayText(locale, String(index + 1).padStart(2, "0"))} + {displayText(locale, xiaomiMacroEventLabel(event))} + {displayText(locale, event.delayMs > 0 + ? `+${event.delayMs} ms` + : index === recordedEvents.length - 1 ? "Waiting…" : "Next")} +
  2. + ))} +
+ )} +
+ ) : ( +
+ {events.length === 0 ? ( +
+ {t(locale, "macro.xmNoEvents")} + {t(locale, "macro.xmNoEventsHint")} +
+ ) : null} + {events.map((event, index) => ( +
+ {displayText(locale, String(index + 1).padStart(2, "0"))} + + + + {displayText(locale, xiaomiKeyCodeLabel(event.key))} + +
+ ))} +
+ )} +
+ + +
+ + )} +
+ {t(locale, "macro.xmHelpToggle")} +

{t(locale, "macro.xmHelpBody")}

+
+
+ ); +} + /** * WALLHACK M-001 onboard macros: 4 slots of up to 30 steps, read from the * device and saved per slot. Manual step editor (no live recorder yet): diff --git a/src/features/devices/cards/availability.ts b/src/features/devices/cards/availability.ts index 3a80b0b1..b9213a5a 100644 --- a/src/features/devices/cards/availability.ts +++ b/src/features/devices/cards/availability.ts @@ -49,6 +49,7 @@ export interface CardAvailability { onboardProfiles: boolean; buttonMapping: boolean; ksnakeMacros: boolean; + xiaomiMacros: boolean; wallhackScanning: boolean; wallhackCurves: boolean; wallhackMacros: boolean; @@ -104,6 +105,7 @@ const NOTHING: CardAvailability = { onboardProfiles: false, buttonMapping: false, ksnakeMacros: false, + xiaomiMacros: false, wallhackScanning: false, wallhackCurves: false, wallhackMacros: false, @@ -174,6 +176,9 @@ function computeCardAvailability(snapshot: ControlSnapshot): CardAvailability { // with local slots because this firmware does not expose a reliable macro // read through the browser. ksnakeMacros: ui?.family === "ksnake" || isNoirKsnake, + // The Xiaomi Mi Gaming Mouse exposes per-button custom combos and macros + // through the vendor control interface. + xiaomiMacros: ui?.family === "xiaomi", // WALLHACK M-001 extras. Curves and macros need mouse firmware 57+; the // cards surface the device error when an older board refuses the read. wallhackScanning: ui?.family === "wallhack-mouse" && status.sensorScanningMode != null, diff --git a/src/features/devices/workspace-tabs.test.ts b/src/features/devices/workspace-tabs.test.ts index d279304f..812fd349 100644 --- a/src/features/devices/workspace-tabs.test.ts +++ b/src/features/devices/workspace-tabs.test.ts @@ -89,3 +89,8 @@ test("the macro tab also follows the Incott macro capability", () => { const tabs = availableWorkspaceTabs(true, availability({ incottMacros: true })); assert.deepEqual(tabs, ["overview", "performance", "macro", "advanced"]); }); + +test("the macro tab also follows the Xiaomi macro capability", () => { + const tabs = availableWorkspaceTabs(true, availability({ xiaomiMacros: true })); + assert.deepEqual(tabs, ["overview", "performance", "macro", "advanced"]); +}); diff --git a/src/features/devices/workspace-tabs.ts b/src/features/devices/workspace-tabs.ts index 3bf73144..daa23b07 100644 --- a/src/features/devices/workspace-tabs.ts +++ b/src/features/devices/workspace-tabs.ts @@ -15,7 +15,7 @@ export function availableWorkspaceTabs( return WORKSPACE_TAB_ORDER.filter((tab) => { if (tab === "lighting") return !options.hideLighting && (has.lighting || has.teevolutionDpiLighting); if (tab === "buttons") return hasButtons; - if (tab === "macro") return has.ksnakeMacros || has.wallhackMacros || has.incottMacros; + if (tab === "macro") return has.ksnakeMacros || has.wallhackMacros || has.incottMacros || has.xiaomiMacros; if (tab === "profiles") return hasProfiles; return true; }); diff --git a/src/i18n/index.ts b/src/i18n/index.ts index 2ff16e5b..9ef687fb 100644 --- a/src/i18n/index.ts +++ b/src/i18n/index.ts @@ -1265,6 +1265,37 @@ const en = { "macro.whDelta": "Distance", "macro.whAdd": "Add step", "macro.whMaxSteps": "A slot holds 30 steps.", + "macro.xmLead": "Choose a button, then build a custom key combo or a macro. Saving writes it straight to the mouse.", + "macro.xmLoading": "Reading the eight button bindings…", + "macro.xmButton": "Button", + "macro.xmCombo": "Custom combo", + "macro.xmMacro": "Macro", + "macro.xmTiming": "Timing", + "macro.xmNoDelay": "No delay", + "macro.xmWithDelay": "With delay", + "macro.xmModifiers": "Modifiers", + "macro.xmKey": "Key", + "macro.xmSaveCombo": "Save combo", + "macro.xmClear": "Clear macro", + "macro.xmDelayBefore": "Delay before", + "macro.xmAddEvent": "Add event", + "macro.xmRemoveEvent": "Remove event {n}", + "macro.xmNoEvents": "No events in this macro", + "macro.xmNoEventsHint": "Record input or add an event manually to get started.", + "macro.xmRecord": "Record input", + "macro.xmStop": "Stop recording", + "macro.xmPress": "Press", + "macro.xmRelease": "Release", + "macro.xmEvents": "{n} events", + "macro.xmRecording": "Recording input", + "macro.xmRecorderHint": "Record keyboard input or add an event manually.", + "macro.xmEventsHint": "{n} events · Press Esc to stop", + "macro.xmLiveEvents": "Live event list", + "macro.xmRecordingEmpty": "Press a key to add the first event.", + "macro.xmHelpToggle": "Need help?", + "macro.xmHelpBody": "A custom combo sends a key plus up to eight modifiers when the button is pressed. A macro is a list of press and release events; in with-delay mode each event waits its delay before it fires. Keyboard codes use standard HID usage values.", + "macro.xmComboHint": "The key plus the selected modifiers is sent when the button is pressed.", + "macro.xmMacroHint": "Each event is a key press or release. In with-delay mode the delay before each event is honored.", "m2nex.controls": "M2-NEX profile controls", "m2nex.overline": "PROFILE", "m2nex.label": "M2-NEX", diff --git a/src/i18n/locales/ar.ts b/src/i18n/locales/ar.ts index 4c084ae6..5b5eca24 100644 --- a/src/i18n/locales/ar.ts +++ b/src/i18n/locales/ar.ts @@ -1190,6 +1190,37 @@ export const ar: Record = { "macro.whDelta": "Distance", "macro.whAdd": "Add step", "macro.whMaxSteps": "A slot holds 30 steps.", + "macro.xmLead": "اختر زرًا، ثم أنشئ تركيبة مفاتيح مخصصة أو ماكرو. عند الحفظ يُكتب مباشرة في الفأرة.", + "macro.xmLoading": "جارٍ قراءة ارتباطات الأزرار الثمانية…", + "macro.xmButton": "الزر", + "macro.xmCombo": "تركيبة مخصصة", + "macro.xmMacro": "ماكرو", + "macro.xmTiming": "التوقيت", + "macro.xmNoDelay": "بدون تأخير", + "macro.xmWithDelay": "مع تأخير", + "macro.xmModifiers": "المعدِّلات", + "macro.xmKey": "المفتاح", + "macro.xmSaveCombo": "حفظ التركيبة", + "macro.xmClear": "مسح الماكرو", + "macro.xmDelayBefore": "تأخير قبل", + "macro.xmAddEvent": "إضافة حدث", + "macro.xmRemoveEvent": "إزالة الحدث {n}", + "macro.xmNoEvents": "لا توجد أحداث في هذا الماكرو", + "macro.xmNoEventsHint": "سجّل الإدخال أو أضف حدثًا يدويًا للبدء.", + "macro.xmRecord": "تسجيل الإدخال", + "macro.xmStop": "إيقاف التسجيل", + "macro.xmPress": "اضغط", + "macro.xmRelease": "أفلت", + "macro.xmEvents": "{n} أحداث", + "macro.xmRecording": "جارٍ تسجيل الإدخال", + "macro.xmRecorderHint": "سجّل إدخال لوحة المفاتيح أو أضف حدثًا يدويًا.", + "macro.xmEventsHint": "{n} أحداث · اضغط Esc للإيقاف", + "macro.xmLiveEvents": "قائمة الأحداث المباشرة", + "macro.xmRecordingEmpty": "اضغط مفتاحًا لإضافة الحدث الأول.", + "macro.xmHelpToggle": "تحتاج إلى مساعدة؟", + "macro.xmHelpBody": "ترسل التركيبة المخصصة مفتاحًا مع ما يصل إلى ثمانية معدِّلات عند الضغط على الزر. الماكرو هو قائمة أحداث ضغط وإفلات؛ في وضع التأخير، ينتظر كل حدث تأخيره قبل أن يُطلق. رموز لوحة المفاتيح تستخدم قيم استخدام HID القياسية.", + "macro.xmComboHint": "يُرسل المفتاح مع المعدِّلات المحددة عند الضغط على الزر.", + "macro.xmMacroHint": "كل حدث هو ضغط أو إفلات لمفتاح. في وضع التأخير يُراعى التأخير قبل كل حدث.", "m2nex.macrosUnavailable": "The connected M2-NEX driver does not expose onboard macro access yet.", "m2nex.saveDone": "{name} saved from the current mouse settings.", "m2nex.applyBlocked": "Apply or discard the current changes before applying a profile.", diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index 49457545..a24f4b9c 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -1192,6 +1192,37 @@ export const de: Record = { "macro.whDelta": "Distance", "macro.whAdd": "Add step", "macro.whMaxSteps": "A slot holds 30 steps.", + "macro.xmLead": "Wähle eine Taste aus und erstelle eine eigene Tastenkombination oder ein Makro. Beim Speichern wird es direkt in die Maus geschrieben.", + "macro.xmLoading": "Lese die Zuordnungen der acht Tasten…", + "macro.xmButton": "Taste", + "macro.xmCombo": "Eigene Kombination", + "macro.xmMacro": "Makro", + "macro.xmTiming": "Timing", + "macro.xmNoDelay": "Ohne Verzögerung", + "macro.xmWithDelay": "Mit Verzögerung", + "macro.xmModifiers": "Modifikatoren", + "macro.xmKey": "Taste", + "macro.xmSaveCombo": "Kombination speichern", + "macro.xmClear": "Makro löschen", + "macro.xmDelayBefore": "Verzögerung vor", + "macro.xmAddEvent": "Ereignis hinzufügen", + "macro.xmRemoveEvent": "Ereignis {n} entfernen", + "macro.xmNoEvents": "Keine Ereignisse in diesem Makro", + "macro.xmNoEventsHint": "Nimm Eingaben auf oder füge manuell ein Ereignis hinzu, um zu starten.", + "macro.xmRecord": "Eingabe aufnehmen", + "macro.xmStop": "Aufnahme stoppen", + "macro.xmPress": "Drücken", + "macro.xmRelease": "Loslassen", + "macro.xmEvents": "{n} Ereignisse", + "macro.xmRecording": "Eingabe wird aufgenommen", + "macro.xmRecorderHint": "Nimm Tastatureingaben auf oder füge manuell ein Ereignis hinzu.", + "macro.xmEventsHint": "{n} Ereignisse · Esc drücken zum Stoppen", + "macro.xmLiveEvents": "Live-Ereignisliste", + "macro.xmRecordingEmpty": "Drücke eine Taste, um das erste Ereignis hinzuzufügen.", + "macro.xmHelpToggle": "Benötigst du Hilfe?", + "macro.xmHelpBody": "Eine eigene Kombination sendet beim Drücken der Taste eine Taste plus bis zu acht Modifikatoren. Ein Makro ist eine Liste von Druck- und Loslass-Ereignissen; im Modus mit Verzögerung wartet jedes Ereignis seine Verzögerung, bevor es ausgelöst wird. Tastencodes verwenden Standard-HID-Nutzwerte.", + "macro.xmComboHint": "Die Taste plus die ausgewählten Modifikatoren wird beim Drücken der Taste gesendet.", + "macro.xmMacroHint": "Jedes Ereignis ist ein Tastendruck oder ein Loslassen. Im Modus mit Verzögerung wird die Verzögerung vor jedem Ereignis beachtet.", "m2nex.macrosUnavailable": "The connected M2-NEX driver does not expose onboard macro access yet.", "m2nex.saveDone": "{name} saved from the current mouse settings.", "m2nex.applyBlocked": "Apply or discard the current changes before applying a profile.", diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index 89fcde6c..3509a6b5 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -1192,6 +1192,37 @@ export const es: Record = { "macro.whDelta": "Distance", "macro.whAdd": "Add step", "macro.whMaxSteps": "A slot holds 30 steps.", + "macro.xmLead": "Elige un botón y crea una combinación de teclas personalizada o una macro. Al guardar se escribe directamente en el ratón.", + "macro.xmLoading": "Leyendo las asignaciones de los ocho botones…", + "macro.xmButton": "Botón", + "macro.xmCombo": "Combinación personalizada", + "macro.xmMacro": "Macro", + "macro.xmTiming": "Temporización", + "macro.xmNoDelay": "Sin retraso", + "macro.xmWithDelay": "Con retraso", + "macro.xmModifiers": "Modificadores", + "macro.xmKey": "Tecla", + "macro.xmSaveCombo": "Guardar combinación", + "macro.xmClear": "Borrar macro", + "macro.xmDelayBefore": "Retraso antes de", + "macro.xmAddEvent": "Añadir evento", + "macro.xmRemoveEvent": "Quitar evento {n}", + "macro.xmNoEvents": "No hay eventos en esta macro", + "macro.xmNoEventsHint": "Graba la entrada o añade un evento manualmente para empezar.", + "macro.xmRecord": "Grabar entrada", + "macro.xmStop": "Detener grabación", + "macro.xmPress": "Pulsar", + "macro.xmRelease": "Soltar", + "macro.xmEvents": "{n} eventos", + "macro.xmRecording": "Grabando entrada", + "macro.xmRecorderHint": "Graba la entrada del teclado o añade un evento manualmente.", + "macro.xmEventsHint": "{n} eventos · Pulsa Esc para detener", + "macro.xmLiveEvents": "Lista de eventos en vivo", + "macro.xmRecordingEmpty": "Pulsa una tecla para añadir el primer evento.", + "macro.xmHelpToggle": "¿Necesitas ayuda?", + "macro.xmHelpBody": "Una combinación personalizada envía una tecla más hasta ocho modificadores al pulsar el botón. Una macro es una lista de eventos de pulsación y liberación; en el modo con retraso, cada evento espera su retraso antes de activarse. Los códigos de tecla usan valores de uso HID estándar.", + "macro.xmComboHint": "La tecla más los modificadores seleccionados se envía al pulsar el botón.", + "macro.xmMacroHint": "Cada evento es una pulsación o liberación de tecla. En el modo con retraso se respeta el retraso antes de cada evento.", "m2nex.macrosUnavailable": "The connected M2-NEX driver does not expose onboard macro access yet.", "m2nex.saveDone": "{name} saved from the current mouse settings.", "m2nex.applyBlocked": "Apply or discard the current changes before applying a profile.", diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index 79091c59..70ecb7a5 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -1192,6 +1192,37 @@ export const fr: Record = { "macro.whDelta": "Distance", "macro.whAdd": "Add step", "macro.whMaxSteps": "A slot holds 30 steps.", + "macro.xmLead": "Choisissez un bouton, puis créez une combinaison de touches personnalisée ou une macro. L'enregistrement l'écrit directement dans la souris.", + "macro.xmLoading": "Lecture des affectations des huit boutons…", + "macro.xmButton": "Bouton", + "macro.xmCombo": "Combinaison personnalisée", + "macro.xmMacro": "Macro", + "macro.xmTiming": "Temporisation", + "macro.xmNoDelay": "Sans délai", + "macro.xmWithDelay": "Avec délai", + "macro.xmModifiers": "Modificateurs", + "macro.xmKey": "Touche", + "macro.xmSaveCombo": "Enregistrer la combinaison", + "macro.xmClear": "Effacer la macro", + "macro.xmDelayBefore": "Délai avant", + "macro.xmAddEvent": "Ajouter un événement", + "macro.xmRemoveEvent": "Supprimer l'événement {n}", + "macro.xmNoEvents": "Aucun événement dans cette macro", + "macro.xmNoEventsHint": "Enregistrez une saisie ou ajoutez un événement manuellement pour commencer.", + "macro.xmRecord": "Enregistrer la saisie", + "macro.xmStop": "Arrêter l'enregistrement", + "macro.xmPress": "Appuyer", + "macro.xmRelease": "Relâcher", + "macro.xmEvents": "{n} événements", + "macro.xmRecording": "Enregistrement de la saisie", + "macro.xmRecorderHint": "Enregistrez la saisie clavier ou ajoutez un événement manuellement.", + "macro.xmEventsHint": "{n} événements · Appuyez sur Échap pour arrêter", + "macro.xmLiveEvents": "Liste des événements en direct", + "macro.xmRecordingEmpty": "Appuyez sur une touche pour ajouter le premier événement.", + "macro.xmHelpToggle": "Besoin d'aide ?", + "macro.xmHelpBody": "Une combinaison personnalisée envoie une touche plus jusqu'à huit modificateurs lorsque le bouton est pressé. Une macro est une liste d'événements d'appui et de relâchement ; en mode avec délai, chaque événement attend son délai avant de se déclencher. Les codes clavier utilisent les valeurs d'utilisation HID standard.", + "macro.xmComboHint": "La touche plus les modificateurs sélectionnés est envoyée lorsque le bouton est pressé.", + "macro.xmMacroHint": "Chaque événement est un appui ou un relâchement de touche. En mode avec délai, le délai avant chaque événement est respecté.", "m2nex.macrosUnavailable": "The connected M2-NEX driver does not expose onboard macro access yet.", "m2nex.saveDone": "{name} saved from the current mouse settings.", "m2nex.applyBlocked": "Apply or discard the current changes before applying a profile.", diff --git a/src/i18n/locales/ja.ts b/src/i18n/locales/ja.ts index 3a794cdb..dcc05b43 100644 --- a/src/i18n/locales/ja.ts +++ b/src/i18n/locales/ja.ts @@ -1192,6 +1192,37 @@ export const ja: Record = { "macro.whDelta": "Distance", "macro.whAdd": "Add step", "macro.whMaxSteps": "A slot holds 30 steps.", + "macro.xmLead": "ボタンを選択し、カスタムキーコンボまたはマクロを作成します。保存するとマウスに直接書き込まれます。", + "macro.xmLoading": "8つのボタンの割り当てを読み取っています…", + "macro.xmButton": "ボタン", + "macro.xmCombo": "カスタムコンボ", + "macro.xmMacro": "マクロ", + "macro.xmTiming": "タイミング", + "macro.xmNoDelay": "遅延なし", + "macro.xmWithDelay": "遅延あり", + "macro.xmModifiers": "修飾キー", + "macro.xmKey": "キー", + "macro.xmSaveCombo": "コンボを保存", + "macro.xmClear": "マクロをクリア", + "macro.xmDelayBefore": "前の遅延", + "macro.xmAddEvent": "イベントを追加", + "macro.xmRemoveEvent": "イベント {n} を削除", + "macro.xmNoEvents": "このマクロにイベントがありません", + "macro.xmNoEventsHint": "入力を録画するか、手動でイベントを追加して開始してください。", + "macro.xmRecord": "入力を録画", + "macro.xmStop": "録画を停止", + "macro.xmPress": "押下", + "macro.xmRelease": "離す", + "macro.xmEvents": "{n} 件のイベント", + "macro.xmRecording": "入力を録画中", + "macro.xmRecorderHint": "キーボード入力を録画するか、手動でイベントを追加してください。", + "macro.xmEventsHint": "{n} 件のイベント · Esc で停止", + "macro.xmLiveEvents": "ライブイベント一覧", + "macro.xmRecordingEmpty": "キーを押して最初のイベントを追加してください。", + "macro.xmHelpToggle": "ヘルプが必要ですか?", + "macro.xmHelpBody": "カスタムコンボは、ボタンを押したときにキーと最大8つの修飾キーを送信します。マクロは押下と離すのイベントのリストです。遅延ありモードでは、各イベントが発火する前にその遅延を待ちます。キーコードは標準のHID使用値を使用します。", + "macro.xmComboHint": "ボタンを押したときに、キーと選択した修飾キーが送信されます。", + "macro.xmMacroHint": "各イベントはキーの押下または離すです。遅延ありモードでは、各イベント前の遅延が反映されます。", "m2nex.macrosUnavailable": "The connected M2-NEX driver does not expose onboard macro access yet.", "m2nex.saveDone": "{name} saved from the current mouse settings.", "m2nex.applyBlocked": "Apply or discard the current changes before applying a profile.", diff --git a/src/i18n/locales/ko.ts b/src/i18n/locales/ko.ts index 06656ee6..9f8e4d7f 100644 --- a/src/i18n/locales/ko.ts +++ b/src/i18n/locales/ko.ts @@ -1192,6 +1192,37 @@ export const ko: Record = { "macro.whDelta": "Distance", "macro.whAdd": "Add step", "macro.whMaxSteps": "A slot holds 30 steps.", + "macro.xmLead": "버튼을 선택한 다음 사용자 지정 키 조합 또는 매크로를 만드세요. 저장하면 마우스에 직접 기록됩니다.", + "macro.xmLoading": "8개 버튼 바인딩을 읽는 중…", + "macro.xmButton": "버튼", + "macro.xmCombo": "사용자 지정 조합", + "macro.xmMacro": "매크로", + "macro.xmTiming": "타이밍", + "macro.xmNoDelay": "지연 없음", + "macro.xmWithDelay": "지연 있음", + "macro.xmModifiers": "수정키", + "macro.xmKey": "키", + "macro.xmSaveCombo": "조합 저장", + "macro.xmClear": "매크로 지우기", + "macro.xmDelayBefore": "이전 지연", + "macro.xmAddEvent": "이벤트 추가", + "macro.xmRemoveEvent": "이벤트 {n} 제거", + "macro.xmNoEvents": "이 매크로에 이벤트가 없습니다", + "macro.xmNoEventsHint": "입력을 녹화하거나 수동으로 이벤트를 추가하여 시작하세요.", + "macro.xmRecord": "입력 녹화", + "macro.xmStop": "녹화 중지", + "macro.xmPress": "누름", + "macro.xmRelease": "놓음", + "macro.xmEvents": "이벤트 {n}개", + "macro.xmRecording": "입력 녹화 중", + "macro.xmRecorderHint": "키보드 입력을 녹화하거나 수동으로 이벤트를 추가하세요.", + "macro.xmEventsHint": "이벤트 {n}개 · Esc를 눌러 중지", + "macro.xmLiveEvents": "실시간 이벤트 목록", + "macro.xmRecordingEmpty": "키를 눌러 첫 번째 이벤트를 추가하세요.", + "macro.xmHelpToggle": "도움이 필요하신가요?", + "macro.xmHelpBody": "사용자 지정 조합은 버튼을 누르면 키와 최대 8개의 수정키를 전송합니다. 매크로는 누름과 놓음 이벤트의 목록입니다. 지연 있음 모드에서는 각 이벤트가 발화되기 전에 해당 지연을 기다립니다. 키 코드는 표준 HID 사용 값을 사용합니다.", + "macro.xmComboHint": "버튼을 누르면 키와 선택한 수정키가 전송됩니다.", + "macro.xmMacroHint": "각 이벤트는 키 누름 또는 놓음입니다. 지연 있음 모드에서는 각 이벤트 앞의 지연이 적용됩니다.", "m2nex.macrosUnavailable": "The connected M2-NEX driver does not expose onboard macro access yet.", "m2nex.saveDone": "{name} saved from the current mouse settings.", "m2nex.applyBlocked": "Apply or discard the current changes before applying a profile.", diff --git a/src/i18n/locales/pt.ts b/src/i18n/locales/pt.ts index f37767de..404d3843 100644 --- a/src/i18n/locales/pt.ts +++ b/src/i18n/locales/pt.ts @@ -1192,6 +1192,37 @@ export const pt: Record = { "macro.whDelta": "Distance", "macro.whAdd": "Add step", "macro.whMaxSteps": "A slot holds 30 steps.", + "macro.xmLead": "Escolha um botão e crie uma combinação de teclas personalizada ou uma macro. Ao guardar, é escrito diretamente no rato.", + "macro.xmLoading": "A ler as atribuições dos oito botões…", + "macro.xmButton": "Botão", + "macro.xmCombo": "Combinação personalizada", + "macro.xmMacro": "Macro", + "macro.xmTiming": "Temporização", + "macro.xmNoDelay": "Sem atraso", + "macro.xmWithDelay": "Com atraso", + "macro.xmModifiers": "Modificadores", + "macro.xmKey": "Tecla", + "macro.xmSaveCombo": "Guardar combinação", + "macro.xmClear": "Limpar macro", + "macro.xmDelayBefore": "Atraso antes de", + "macro.xmAddEvent": "Adicionar evento", + "macro.xmRemoveEvent": "Remover evento {n}", + "macro.xmNoEvents": "Sem eventos nesta macro", + "macro.xmNoEventsHint": "Grave a entrada ou adicione um evento manualmente para começar.", + "macro.xmRecord": "Gravar entrada", + "macro.xmStop": "Parar gravação", + "macro.xmPress": "Premir", + "macro.xmRelease": "Largar", + "macro.xmEvents": "{n} eventos", + "macro.xmRecording": "A gravar entrada", + "macro.xmRecorderHint": "Grave a entrada do teclado ou adicione um evento manualmente.", + "macro.xmEventsHint": "{n} eventos · Prima Esc para parar", + "macro.xmLiveEvents": "Lista de eventos em direto", + "macro.xmRecordingEmpty": "Prima uma tecla para adicionar o primeiro evento.", + "macro.xmHelpToggle": "Precisa de ajuda?", + "macro.xmHelpBody": "Uma combinação personalizada envia uma tecla mais até oito modificadores quando o botão é premido. Uma macro é uma lista de eventos de pressão e libertação; no modo com atraso, cada evento aguarda o seu atraso antes de disparar. Os códigos de tecla usam valores de utilização HID padrão.", + "macro.xmComboHint": "A tecla mais os modificadores selecionados é enviada quando o botão é premido.", + "macro.xmMacroHint": "Cada evento é uma pressão ou libertação de tecla. No modo com atraso, o atraso antes de cada evento é respeitado.", "m2nex.macrosUnavailable": "The connected M2-NEX driver does not expose onboard macro access yet.", "m2nex.saveDone": "{name} saved from the current mouse settings.", "m2nex.applyBlocked": "Apply or discard the current changes before applying a profile.", diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index 77928a2e..8cff2a4f 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -1192,6 +1192,37 @@ export const ru: Record = { "macro.whDelta": "Distance", "macro.whAdd": "Add step", "macro.whMaxSteps": "A slot holds 30 steps.", + "macro.xmLead": "Выберите кнопку, затем создайте собственную комбинацию клавиш или макрос. При сохранении данные записываются прямо в мышь.", + "macro.xmLoading": "Чтение назначений восьми кнопок…", + "macro.xmButton": "Кнопка", + "macro.xmCombo": "Собственная комбинация", + "macro.xmMacro": "Макрос", + "macro.xmTiming": "Тайминг", + "macro.xmNoDelay": "Без задержки", + "macro.xmWithDelay": "С задержкой", + "macro.xmModifiers": "Модификаторы", + "macro.xmKey": "Клавиша", + "macro.xmSaveCombo": "Сохранить комбинацию", + "macro.xmClear": "Очистить макрос", + "macro.xmDelayBefore": "Задержка перед", + "macro.xmAddEvent": "Добавить событие", + "macro.xmRemoveEvent": "Удалить событие {n}", + "macro.xmNoEvents": "В этом макросе нет событий", + "macro.xmNoEventsHint": "Запишите ввод или добавьте событие вручную, чтобы начать.", + "macro.xmRecord": "Записать ввод", + "macro.xmStop": "Остановить запись", + "macro.xmPress": "Нажать", + "macro.xmRelease": "Отпустить", + "macro.xmEvents": "{n} событий", + "macro.xmRecording": "Запись ввода", + "macro.xmRecorderHint": "Запишите ввод с клавиатуры или добавьте событие вручную.", + "macro.xmEventsHint": "{n} событий · Нажмите Esc для остановки", + "macro.xmLiveEvents": "Список событий в реальном времени", + "macro.xmRecordingEmpty": "Нажмите клавишу, чтобы добавить первое событие.", + "macro.xmHelpToggle": "Нужна помощь?", + "macro.xmHelpBody": "Собственная комбинация отправляет клавишу и до восьми модификаторов при нажатии кнопки. Макрос — это список событий нажатия и отпускания; в режиме с задержкой каждое событие ожидает свою задержку перед срабатыванием. Коды клавиш используют стандартные значения использования HID.", + "macro.xmComboHint": "При нажатии кнопки отправляется клавиша и выбранные модификаторы.", + "macro.xmMacroHint": "Каждое событие — это нажатие или отпускание клавиши. В режиме с задержкой задержка перед каждым событием учитывается.", "m2nex.macrosUnavailable": "The connected M2-NEX driver does not expose onboard macro access yet.", "m2nex.saveDone": "{name} saved from the current mouse settings.", "m2nex.applyBlocked": "Apply or discard the current changes before applying a profile.", diff --git a/src/i18n/locales/tr.ts b/src/i18n/locales/tr.ts index e8b861d4..1fa7dcc4 100644 --- a/src/i18n/locales/tr.ts +++ b/src/i18n/locales/tr.ts @@ -1186,6 +1186,37 @@ export const tr: Record = { "macro.whDelta": "Mesafe", "macro.whAdd": "Adım ekle", "macro.whMaxSteps": "Bir yuva 30 adım alır.", + "macro.xmLead": "Bir düğme seçin, ardından özel tuş kombinasyonu veya makro oluşturun. Kaydetme doğrudan fareye yazar.", + "macro.xmLoading": "Sekiz düğmenin atamaları okunuyor…", + "macro.xmButton": "Düğme", + "macro.xmCombo": "Özel kombinasyon", + "macro.xmMacro": "Makro", + "macro.xmTiming": "Zamanlama", + "macro.xmNoDelay": "Gecikmesiz", + "macro.xmWithDelay": "Gecikmeli", + "macro.xmModifiers": "Değiştiriciler", + "macro.xmKey": "Tuş", + "macro.xmSaveCombo": "Kombinasyonu kaydet", + "macro.xmClear": "Makroyu temizle", + "macro.xmDelayBefore": "Önceki gecikme", + "macro.xmAddEvent": "Olay ekle", + "macro.xmRemoveEvent": "{n} olayını kaldır", + "macro.xmNoEvents": "Bu makroda olay yok", + "macro.xmNoEventsHint": "Başlamak için girdi kaydedin veya bir olayı manuel ekleyin.", + "macro.xmRecord": "Girdi kaydet", + "macro.xmStop": "Kaydı durdur", + "macro.xmPress": "Bas", + "macro.xmRelease": "Bırak", + "macro.xmEvents": "{n} olay", + "macro.xmRecording": "Girdi kaydediliyor", + "macro.xmRecorderHint": "Klavye girdisini kaydedin veya bir olayı manuel ekleyin.", + "macro.xmEventsHint": "{n} olay · Durdurmak için Esc", + "macro.xmLiveEvents": "Canlı olay listesi", + "macro.xmRecordingEmpty": "İlk olayı eklemek için bir tuşa basın.", + "macro.xmHelpToggle": "Yardıma mı ihtiyacınız var?", + "macro.xmHelpBody": "Özel kombinasyon, düğmeye basıldığında bir tuşu ve en fazla sekiz değiştiriciyi gönderir. Makro, basma ve bırakma olaylarının listesidir; gecikmeli modda her olay tetiklenmeden önce gecikmesini bekler. Klavye kodları standart HID kullanım değerlerini kullanır.", + "macro.xmComboHint": "Tuş ve seçili değiştiriciler, düğmeye basıldığında gönderilir.", + "macro.xmMacroHint": "Her olay bir tuş basması veya bırakmasıdır. Gecikmeli modda her olayın önceki gecikmesi uygulanır.", "m2nex.controls": "M2-NEX profil kontrolleri", "m2nex.overline": "PROFİL", "m2nex.label": "M2-NEX", diff --git a/src/i18n/locales/vi.ts b/src/i18n/locales/vi.ts index 750784d9..440a1da4 100644 --- a/src/i18n/locales/vi.ts +++ b/src/i18n/locales/vi.ts @@ -1197,6 +1197,37 @@ export const vi: Record = { "macro.whDelta": "Distance", "macro.whAdd": "Add step", "macro.whMaxSteps": "A slot holds 30 steps.", + "macro.xmLead": "Chọn một nút, sau đó tạo tổ hợp phím tùy chỉnh hoặc macro. Khi lưu, nó được ghi trực tiếp vào chuột.", + "macro.xmLoading": "Đang đọc gán của tám nút…", + "macro.xmButton": "Nút", + "macro.xmCombo": "Tổ hợp tùy chỉnh", + "macro.xmMacro": "Macro", + "macro.xmTiming": "Thời điểm", + "macro.xmNoDelay": "Không trễ", + "macro.xmWithDelay": "Có trễ", + "macro.xmModifiers": "Phím sửa", + "macro.xmKey": "Phím", + "macro.xmSaveCombo": "Lưu tổ hợp", + "macro.xmClear": "Xóa macro", + "macro.xmDelayBefore": "Trễ trước", + "macro.xmAddEvent": "Thêm sự kiện", + "macro.xmRemoveEvent": "Xóa sự kiện {n}", + "macro.xmNoEvents": "Không có sự kiện trong macro này", + "macro.xmNoEventsHint": "Ghi âm đầu vào hoặc thêm sự kiện thủ công để bắt đầu.", + "macro.xmRecord": "Ghi âm đầu vào", + "macro.xmStop": "Dừng ghi âm", + "macro.xmPress": "Nhấn", + "macro.xmRelease": "Thả", + "macro.xmEvents": "{n} sự kiện", + "macro.xmRecording": "Đang ghi âm đầu vào", + "macro.xmRecorderHint": "Ghi âm đầu vào bàn phím hoặc thêm sự kiện thủ công.", + "macro.xmEventsHint": "{n} sự kiện · Nhấn Esc để dừng", + "macro.xmLiveEvents": "Danh sách sự kiện trực tiếp", + "macro.xmRecordingEmpty": "Nhấn một phím để thêm sự kiện đầu tiên.", + "macro.xmHelpToggle": "Cần trợ giúp?", + "macro.xmHelpBody": "Tổ hợp tùy chỉnh gửi một phím cùng tối đa tám phím sửa khi nút được nhấn. Macro là danh sách các sự kiện nhấn và thả; ở chế độ có trễ, mỗi sự kiện chờ thời gian trễ của nó trước khi kích hoạt. Mã phím sử dụng giá trị sử dụng HID tiêu chuẩn.", + "macro.xmComboHint": "Phím cùng các phím sửa được chọn sẽ được gửi khi nút được nhấn.", + "macro.xmMacroHint": "Mỗi sự kiện là một lần nhấn hoặc thả phím. Ở chế độ có trễ, thời gian trễ trước mỗi sự kiện được tuân theo.", "m2nex.macrosUnavailable": "The connected M2-NEX driver does not expose onboard macro access yet.", "m2nex.saveDone": "{name} saved from the current mouse settings.", "m2nex.applyBlocked": "Apply or discard the current changes before applying a profile.", diff --git a/src/i18n/locales/zh.ts b/src/i18n/locales/zh.ts index c2642929..15ab5770 100644 --- a/src/i18n/locales/zh.ts +++ b/src/i18n/locales/zh.ts @@ -1192,6 +1192,37 @@ export const zh: Record = { "macro.whDelta": "Distance", "macro.whAdd": "Add step", "macro.whMaxSteps": "A slot holds 30 steps.", + "macro.xmLead": "选择一个按键,然后创建自定义按键组合或宏。保存时会直接写入鼠标。", + "macro.xmLoading": "正在读取八个按键的绑定…", + "macro.xmButton": "按键", + "macro.xmCombo": "自定义组合", + "macro.xmMacro": "宏", + "macro.xmTiming": "时序", + "macro.xmNoDelay": "无延迟", + "macro.xmWithDelay": "带延迟", + "macro.xmModifiers": "修饰键", + "macro.xmKey": "按键", + "macro.xmSaveCombo": "保存组合", + "macro.xmClear": "清除宏", + "macro.xmDelayBefore": "前置延迟", + "macro.xmAddEvent": "添加事件", + "macro.xmRemoveEvent": "删除事件 {n}", + "macro.xmNoEvents": "此宏中没有事件", + "macro.xmNoEventsHint": "录制输入或手动添加事件以开始。", + "macro.xmRecord": "录制输入", + "macro.xmStop": "停止录制", + "macro.xmPress": "按下", + "macro.xmRelease": "释放", + "macro.xmEvents": "{n} 个事件", + "macro.xmRecording": "正在录制输入", + "macro.xmRecorderHint": "录制键盘输入或手动添加事件。", + "macro.xmEventsHint": "{n} 个事件 · 按 Esc 停止", + "macro.xmLiveEvents": "实时事件列表", + "macro.xmRecordingEmpty": "按一个键以添加第一个事件。", + "macro.xmHelpToggle": "需要帮助?", + "macro.xmHelpBody": "自定义组合在按下按键时发送一个按键加最多八个修饰键。宏是按下和释放事件的列表;在带延迟模式下,每个事件在触发前会等待其延迟。键盘代码使用标准 HID 用法值。", + "macro.xmComboHint": "按下按键时,会发送该按键加所选的修饰键。", + "macro.xmMacroHint": "每个事件是一次按键按下或释放。在带延迟模式下,每个事件前的延迟会被遵守。", "m2nex.macrosUnavailable": "The connected M2-NEX driver does not expose onboard macro access yet.", "m2nex.saveDone": "{name} saved from the current mouse settings.", "m2nex.applyBlocked": "Apply or discard the current changes before applying a profile.", diff --git a/src/shared/device-images.test.ts b/src/shared/device-images.test.ts index f3a4efd8..33a84848 100644 --- a/src/shared/device-images.test.ts +++ b/src/shared/device-images.test.ts @@ -90,6 +90,14 @@ test("ATK ZERO resolves by name", () => { assert.equal(deviceImage(null, "ATK ZERO"), CDN + "atk-zero.png"); }); +test("Xiaomi Mi Gaming Mouse resolves by name (wired and wireless PIDs)", () => { + // TEMPORARY: served from the repo override (see LOCAL_OVERRIDES in + // device-images.ts) until the render is uploaded to R2. + assert.equal(deviceImage(null, "Mi Gaming Mouse"), "/devices/xiaomi-mi-gaming-mouse.png"); + assert.equal(deviceImage(dev(0x2717, 0x5009), "Mi Gaming Mouse"), "/devices/xiaomi-mi-gaming-mouse.png"); + assert.equal(deviceImage(dev(0x2717, 0x500b), "Mi Gaming Mouse"), "/devices/xiaomi-mi-gaming-mouse.png"); +}); + test("Dareu A950 PRO Mg resolves by name", () => { assert.equal(deviceImage(null, "Dareu A950 PRO Mg"), CDN + "dareu-a950-pro-mg.png"); }); diff --git a/src/shared/device-images.ts b/src/shared/device-images.ts index 4c7bd8b9..b2a16720 100644 --- a/src/shared/device-images.ts +++ b/src/shared/device-images.ts @@ -187,6 +187,9 @@ function computeDeviceImageFilename(displayName: string): string { if (/\bm1\s*[-_]?\s*nex\b/i.test(displayName)) return "noir-m1-nex.png"; if (/\bnoir\s*e1\b/i.test(displayName)) return "noir-e1.png"; if (/fantech/i.test(displayName)) return "unknown-device.png"; + // The driver reports the model as "Mi Gaming Mouse" for both the wired + // (0x5009) and wireless (0x500b) PIDs, so one name rule covers both. + if (/mi\s*gaming\s*mouse/i.test(displayName)) return "xiaomi-mi-gaming-mouse.png"; return "unknown-device.png"; } @@ -218,6 +221,9 @@ const LOCAL_OVERRIDES: Readonly> = { // The keyboard placeholder: a black keyboard silhouette with a question mark, // the keyboard twin of unknown-device.png. Served locally until it is in the bucket. "unknown-keyboard.png": "/devices/unknown-keyboard.png", + // Rendered from the reference app's animation frames (black background + // removed); served locally until the R2 upload happens. + "xiaomi-mi-gaming-mouse.png": "/devices/xiaomi-mi-gaming-mouse.png", }; export type DeviceImageKind = "mouse" | "keyboard"; diff --git a/src/styles/areas/library.css b/src/styles/areas/library.css index 520b81a8..fb3a8b85 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) { grid-column: 1 / -1; gap: 16px; } +:is(#ksnake-macro-settings, #wallhack-macro-settings, #incott-macro-settings, #xiaomi-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); } @@ -171,6 +171,21 @@ .ksnake-macro-delete { display: grid; place-items: center; width: 32px; height: 32px; border-radius: var(--r-sm); color: var(--text-3); } .ksnake-macro-delete:hover:not(:disabled) { color: var(--bad); background: var(--glint); } .ksnake-macro-delete:disabled { opacity: .4; } +/* Xiaomi macros reuse the K-snake recorder and step rows; only the combo + editor (modifier grid + key picker) and the action row are their own. */ +.xiaomi-macro-combo { display: grid; gap: 12px; } +.xiaomi-macro-modifiers { display: flex; flex-wrap: wrap; gap: 8px 16px; margin: 0; padding: 12px; border: 1px solid var(--line-1); border-radius: var(--r-md); } +.xiaomi-macro-modifiers legend { padding-inline: 6px; color: var(--text-3); font-size: var(--fs-meta); } +.xiaomi-macro-modifier { display: inline-flex; align-items: center; gap: 6px; color: var(--text-2); font-size: var(--fs-meta); } +.xiaomi-macro-key-picker { display: grid; gap: 8px; min-width: 0; color: var(--text-3); font-size: var(--fs-meta); } +.xiaomi-macro-key-picker select { min-width: min(240px, 100%); max-width: 100%; } +.xiaomi-macro-actions { flex-wrap: wrap; justify-content: flex-start; gap: 8px; padding-top: 12px; border-top: 1px solid var(--line-1); } +.xiaomi-macro-actions > button { display: inline-flex; align-items: center; justify-content: center; gap: 7px; min-height: 32px; height: auto; padding: 7px 12px; border-radius: var(--r-sm); background: var(--btn); box-shadow: var(--btn-shadow); color: var(--text-1); font-size: 12px; font-weight: 600; } +.xiaomi-macro-actions > button:hover:not(:disabled) { background: var(--btn-hover); } +.xiaomi-macro-actions > button:disabled { opacity: .45; cursor: default; } +.xiaomi-macro-actions > .xiaomi-macro-save { background: var(--accent); box-shadow: var(--primary-shadow); color: var(--on-accent); } +.xiaomi-macro-actions > .xiaomi-macro-save:hover:not(:disabled) { background: color-mix(in srgb, var(--accent) 90%, var(--text-1)); } +.xiaomi-macro-step { grid-template-columns: 28px minmax(100px, 1fr) minmax(100px, 1fr) 76px minmax(80px, 1fr) 32px; } /* Incott macros reuse the K-snake recorder and rows; only the library, the button grid and a wrapping step row are their own. */ .incott-macro-library > label { flex: 1 1 200px; }