From 1608c3ea9192f5162fb736e13e21da9bb828b7f1 Mon Sep 17 00:00:00 2001 From: loucass003 Date: Fri, 11 Sep 2026 19:03:04 +0200 Subject: [PATCH] Better keybinds --- gui/app/public/i18n/en/translation.ftl | 7 +- .../components/commons/KeybindRecorder.tsx | 150 +++++++------- .../commons/KeybindRecorderModal.tsx | 7 +- .../src/components/commons/KeybindsRow.tsx | 37 ++-- .../src/components/commons/keybind-keys.ts | 191 ++++++++++++++++++ .../settings/pages/KeybindSettings.tsx | 111 ++++++---- gui/electron/main/index.ts | 9 + gui/electron/preload/index.ts | 2 + gui/shared/src/interface.ts | 1 + gui/shared/src/ipc.ts | 2 + .../src/main/java/dev/slimevr/keybind/keys.kt | 57 ++++++ .../java/dev/slimevr/solarxr/rpc/keybinds.kt | 24 +-- .../java/dev/slimevr/desktop/keybind/gnome.kt | 65 +++++- .../dev/slimevr/desktop/keybind/keybinds.kt | 141 ------------- .../java/dev/slimevr/desktop/keybind/linux.kt | 125 ++++++++++++ .../dev/slimevr/desktop/keybind/windows.kt | 121 +++++++++++ 16 files changed, 758 insertions(+), 292 deletions(-) create mode 100644 gui/app/src/components/commons/keybind-keys.ts create mode 100644 server/core/src/main/java/dev/slimevr/keybind/keys.kt create mode 100644 server/desktop/src/main/java/dev/slimevr/desktop/keybind/linux.kt create mode 100644 server/desktop/src/main/java/dev/slimevr/desktop/keybind/windows.kt diff --git a/gui/app/public/i18n/en/translation.ftl b/gui/app/public/i18n/en/translation.ftl index 9aacfe67e..10904a095 100644 --- a/gui/app/public/i18n/en/translation.ftl +++ b/gui/app/public/i18n/en/translation.ftl @@ -636,6 +636,7 @@ settings-keybinds_pause-tracking = Pause Tracking settings-keybinds_reset-all-button = Reset all settings-keybinds-system-managed-description = Your desktop manages global shortcuts itself, so they have to be changed from your system settings. settings-keybinds-open-system-settings-button = Open system settings +settings-keybinds-system-managed-hint = Set in system settings settings-keybinds-unsupported-description = Global keybinds are not supported on this platform. settings-sidebar-keybinds = Keybinds settings-keybinds-recorder-modal-title = Assign keybind for @@ -649,9 +650,9 @@ settings-keybinds-already-assigned = Already used by { $name } settings-keybinds-click-to-record = Click to record shortcut settings-keybinds-change-shortcut = Click to change shortcut settings-keybinds-reset-single = Reset keybind to default -settings-keybinds-recorder-hint-recording = Hold Ctrl, Alt, or Super, then press a letter or number -settings-keybinds-error-letters-numbers-only = That key can't be used, pick a letter or number -settings-keybinds-error-add-modifier = You can only start a combination with Ctrl, Alt, or Super +settings-keybinds-recorder-hint-recording = Hold the keys you want, then release them +settings-keybinds-error-unsupported-key = That key can't be used in a shortcut +settings-keybinds-error-add-modifier = Hold Ctrl, Alt, or Super with that key ## FK/Tracking settings diff --git a/gui/app/src/components/commons/KeybindRecorder.tsx b/gui/app/src/components/commons/KeybindRecorder.tsx index 4140eb21e..169e4db43 100644 --- a/gui/app/src/components/commons/KeybindRecorder.tsx +++ b/gui/app/src/components/commons/KeybindRecorder.tsx @@ -11,58 +11,26 @@ import { Kbd } from './Kbd'; import classNames from 'classnames'; import { useLocalization } from '@fluent/react'; import './KeybindRow.scss'; - -const MODIFIER_ORDER = ['CTRL', 'ALT', 'SHIFT', 'SUPER']; -const NON_SHIFT_MODIFIERS = ['CTRL', 'ALT', 'SUPER']; -const MODIFIER_KEY_NAMES: Record = { - CONTROL: 'CTRL', - ALT: 'ALT', - SHIFT: 'SHIFT', - META: 'SUPER', - OS: 'SUPER', -}; +import { + MODIFIER_ORDER, + keybindLabel, + modifierNameForKey, + modifiersFromHeld, + resolveKey, +} from './keybind-keys'; const maxKeybindLength = 5; -function orderModifiers(mods: string[]): string[] { - return MODIFIER_ORDER.filter((m) => mods.includes(m)); -} - -export function isValidKeybind(keys: string[]): boolean { - const main = keys.filter((k) => !MODIFIER_ORDER.includes(k)); - if (main.length !== 1 || !/^[A-Z0-9]$/.test(main[0])) return false; - return keys.some((k) => NON_SHIFT_MODIFIERS.includes(k)); -} - -export function keybindKey(keys: string[]): string { - return [...keys].sort().join('+'); -} - -function resolveMainKey(code: string): string | null { - if (code.startsWith('Key')) return code.slice(3); - if (code.startsWith('Digit')) return code.slice(5); - if (code.startsWith('Numpad') && code.length === 7 && /^\d$/.test(code[6])) - return code[6]; - return null; -} - -function modifiersFromEvent(e: React.KeyboardEvent): string[] { - const mods: string[] = []; - if (e.ctrlKey) mods.push('CTRL'); - if (e.altKey) mods.push('ALT'); - if (e.shiftKey) mods.push('SHIFT'); - if (e.metaKey) mods.push('SUPER'); - return orderModifiers(mods); -} - type RecorderState = { - preview: string[] | null; + held: Set; + best: string[] | null; flash: { slot: number; msgId: string } | null; }; type RecorderAction = - | { type: 'preview'; keys: string[] } - | { type: 'clearPreview' } + | { type: 'keydown'; code: string; keys: string[] } + | { type: 'keyup'; code: string } + | { type: 'clear' } | { type: 'flash'; slot: number; msgId: string } | { type: 'clearFlash' }; @@ -71,10 +39,24 @@ function recorderReducer( action: RecorderAction ): RecorderState { switch (action.type) { - case 'preview': - return { preview: action.keys, flash: null }; - case 'clearPreview': - return { ...state, preview: null }; + case 'keydown': { + const held = new Set(state.held); + held.add(action.code); + const hasMain = action.keys.some((k) => !MODIFIER_ORDER.includes(k)); + const bestHasMain = (state.best ?? []).some( + (k) => !MODIFIER_ORDER.includes(k) + ); + const best = + hasMain || !bestHasMain ? action.keys : (state.best ?? action.keys); + return { held, best, flash: null }; + } + case 'keyup': { + const held = new Set(state.held); + held.delete(action.code); + return { ...state, held }; + } + case 'clear': + return { held: new Set(), best: null, flash: null }; case 'flash': return { ...state, flash: { slot: action.slot, msgId: action.msgId } }; case 'clearFlash': @@ -98,16 +80,18 @@ export const KeybindRecorder = forwardRef< ) { const { l10n } = useLocalization(); const [state, dispatch] = useReducer(recorderReducer, { - preview: null, + held: new Set(), + best: null, flash: null, }); const [focused, setFocused] = useState(false); const inputRef = useRef(null); useImperativeHandle(ref, () => inputRef.current!, []); - const showing = state.preview ?? keys; + const recording = state.held.size > 0; + const showing = recording ? (state.best ?? []) : keys; const activeIndex = showing.length; - const slotCount = state.preview + const slotCount = recording ? Math.min(showing.length + 1, maxKeybindLength) : Math.max(showing.length, 1); const displayError = state.flash ? l10n.getString(state.flash.msgId) : error; @@ -124,58 +108,64 @@ export const KeybindRecorder = forwardRef< }, [state.flash]); const handleKeyDown = (e: React.KeyboardEvent) => { - e.preventDefault(); - e.stopPropagation(); + const hasModifier = state.held.size > 0; - if (e.key === 'Escape') { + if (!hasModifier && e.key === 'Escape') { onCloseModal?.(); return; } - if (e.key === 'Backspace' || e.key === 'Delete') { + if (!hasModifier && (e.key === 'Backspace' || e.key === 'Delete')) { onUnbindModal?.(); return; } - if (e.key === 'Enter') { + if (!hasModifier && e.key === 'Enter') { onSubmitModal?.(); return; } - const modifiers = modifiersFromEvent(e); + e.preventDefault(); + e.stopPropagation(); + if (e.repeat) return; - if (MODIFIER_KEY_NAMES[e.key.toUpperCase()]) { - dispatch({ type: 'preview', keys: modifiers }); + const modifierName = modifierNameForKey(e.key); + if (modifierName) { + dispatch({ type: 'keydown', code: e.code, keys: modifiersFromHeld(new Set(state.held).add(e.code)) }); return; } - const mainKey = resolveMainKey(e.code); - if (!mainKey) { + const key = resolveKey(e); + if (!key) { dispatch({ type: 'flash', slot: activeIndex, - msgId: 'settings-keybinds-error-letters-numbers-only', + msgId: 'settings-keybinds-error-unsupported-key', }); return; } - dispatch({ type: 'clearPreview' }); - onKeysChange([...modifiers, mainKey]); + dispatch({ + type: 'keydown', + code: e.code, + keys: [...modifiersFromHeld(state.held), key], + }); }; const handleKeyUp = (e: React.KeyboardEvent) => { - if (state.preview === null) return; - if ( - e.key === 'Escape' || - e.key === 'Enter' || - e.key === 'Backspace' || - e.key === 'Delete' - ) - return; - const modifiers = modifiersFromEvent(e); - dispatch( - modifiers.length > 0 - ? { type: 'preview', keys: modifiers } - : { type: 'clearPreview' } - ); + const wasRecording = state.held.size > 0; + dispatch({ type: 'keyup', code: e.code }); + + if (!wasRecording) return; + const stillHeld = new Set(state.held); + stillHeld.delete(e.code); + if (stillHeld.size === 0 && state.best) { + onKeysChange(state.best); + dispatch({ type: 'clear' }); + } + }; + + const handleBlur = () => { + setFocused(false); + if (state.held.size > 0) dispatch({ type: 'clear' }); }; return ( @@ -196,7 +186,7 @@ export const KeybindRecorder = forwardRef< ref={inputRef} data-nav-raw onFocus={() => setFocused(true)} - onBlur={() => setFocused(false)} + onBlur={handleBlur} onKeyDown={handleKeyDown} onKeyUp={handleKeyUp} /> @@ -218,7 +208,7 @@ export const KeybindRecorder = forwardRef< variant={variant} className="px-4 py-2 min-w-[54px] h-[48px]" > - {key ?? (isActive ? '...' : '')} + {key != null ? keybindLabel(key) : isActive ? '...' : ''} {i < slotCount - 1 && ( diff --git a/gui/app/src/components/commons/KeybindRecorderModal.tsx b/gui/app/src/components/commons/KeybindRecorderModal.tsx index ea48006a8..a1d77c21c 100644 --- a/gui/app/src/components/commons/KeybindRecorderModal.tsx +++ b/gui/app/src/components/commons/KeybindRecorderModal.tsx @@ -6,7 +6,8 @@ import { FieldValues, FieldPath, } from 'react-hook-form'; -import { KeybindRecorder, isValidKeybind, keybindKey } from './KeybindRecorder'; +import { KeybindRecorder } from './KeybindRecorder'; +import { isValidKeybind, keybindKey } from './keybind-keys'; import { Kbd } from './Kbd'; import { Typography } from './Typography'; import { KeyboardIcon } from './icon/KeyboardIcon'; @@ -30,6 +31,7 @@ export function KeybindRecorderModal({ onUnbind, onSubmit, takenBindings, + activatedError, }: { id?: string; control: Control; @@ -40,6 +42,7 @@ export function KeybindRecorderModal({ onSubmit: () => void; onReset?: () => void; takenBindings?: { name: string; binding: string[] }[]; + activatedError?: string | null; }) { const keybindlocalization = 'settings-keybinds_' + id; const { l10n } = useLocalization(); @@ -92,7 +95,7 @@ export function KeybindRecorderModal({ keys={field.value ?? []} onKeysChange={field.onChange} ref={field.ref} - error={fieldState.error?.message} + error={activatedError ?? fieldState.error?.message} onSubmitModal={handleModalSubmit} onUnbindModal={onUnbind} onCloseModal={onClose} diff --git a/gui/app/src/components/commons/KeybindsRow.tsx b/gui/app/src/components/commons/KeybindsRow.tsx index f4ffae90c..4e3c60424 100644 --- a/gui/app/src/components/commons/KeybindsRow.tsx +++ b/gui/app/src/components/commons/KeybindsRow.tsx @@ -5,6 +5,7 @@ import { KeybindForm } from '@/components/settings/pages/KeybindSettings'; import { NumberSelector } from './NumberSelector'; import { useLocaleConfig } from '@/i18n/config'; import { Kbd } from './Kbd'; +import { keybindLabel } from './keybind-keys'; import { RecordIcon } from './icon/RecordIcon'; import { ResetIcon } from './icon/ResetIcon'; import { Tooltip } from './Tooltip'; @@ -25,7 +26,7 @@ function KeyBindKeyList({ keybind }: { keybind: string[] }) { {keybind.map((key, i) => (
- {key} + {keybindLabel(key)} {i < keybind.length - 1 && ( @@ -75,13 +76,15 @@ export function KeybindsRow({ openKeybindRecorderModal, onResetSingle, isModified, + bindingEditable = true, }: { id?: string; control: Control; index: number; - openKeybindRecorderModal: (index: number) => void; + openKeybindRecorderModal?: (index: number) => void; onResetSingle: (index: number) => void; isModified?: boolean; + bindingEditable?: boolean; }) { const binding = useWatch({ @@ -129,17 +132,27 @@ export function KeybindsRow({
- } - preferedDirection="top" - > - openKeybindRecorderModal(index)} + {bindingEditable && openKeybindRecorderModal ? ( + } + preferedDirection="top" > - - - + openKeybindRecorderModal(index)} + > + + + + ) : ( + + )}
diff --git a/gui/app/src/components/commons/keybind-keys.ts b/gui/app/src/components/commons/keybind-keys.ts new file mode 100644 index 000000000..13e2dd611 --- /dev/null +++ b/gui/app/src/components/commons/keybind-keys.ts @@ -0,0 +1,191 @@ +export const MODIFIER_ORDER = ['CTRL', 'ALT', 'SHIFT', 'SUPER']; +const NON_SHIFT_MODIFIERS = ['CTRL', 'ALT', 'SUPER']; +const MODIFIER_KEY_NAMES: Record = { + CONTROL: 'CTRL', + ALT: 'ALT', + SHIFT: 'SHIFT', + META: 'SUPER', + OS: 'SUPER', +}; + +// `KeyboardEvent.code` -> canonical modifier name. The held-key set stores codes (so left/right +// variants of the same modifier don't collide), so lookups against it need this, not +// MODIFIER_KEY_NAMES (which is keyed by the location-less `e.key`). +const MODIFIER_CODE_NAMES: Record = { + ControlLeft: 'CTRL', + ControlRight: 'CTRL', + AltLeft: 'ALT', + AltRight: 'ALT', + ShiftLeft: 'SHIFT', + ShiftRight: 'SHIFT', + MetaLeft: 'SUPER', + MetaRight: 'SUPER', + OSLeft: 'SUPER', + OSRight: 'SUPER', +}; + +// Keys bindable without a modifier: function, media/volume, and standalone system keys. +const MODIFIER_OPTIONAL_KEYS = new Set([ + ...Array.from({ length: 24 }, (_, i) => `F${i + 1}`), + 'MEDIA_PLAY_PAUSE', + 'MEDIA_STOP', + 'MEDIA_NEXT', + 'MEDIA_PREVIOUS', + 'VOLUME_UP', + 'VOLUME_DOWN', + 'VOLUME_MUTE', + 'PRINT_SCREEN', + 'PAUSE', + 'SCROLL_LOCK', +]); + +// `KeyboardEvent.code` -> our canonical key name, kept in sync with +// server/core/.../keybind/keys.kt. Falls back to null (unbindable) for anything else. +const CODE_TO_KEY: Record = { + ArrowUp: 'UP', + ArrowDown: 'DOWN', + ArrowLeft: 'LEFT', + ArrowRight: 'RIGHT', + Home: 'HOME', + End: 'END', + PageUp: 'PAGE_UP', + PageDown: 'PAGE_DOWN', + Insert: 'INSERT', + Delete: 'DELETE', + Space: 'SPACE', + Enter: 'ENTER', + Tab: 'TAB', + Backspace: 'BACKSPACE', + Escape: 'ESCAPE', + NumpadAdd: 'NUMPAD_ADD', + NumpadSubtract: 'NUMPAD_SUBTRACT', + NumpadMultiply: 'NUMPAD_MULTIPLY', + NumpadDivide: 'NUMPAD_DIVIDE', + NumpadDecimal: 'NUMPAD_DECIMAL', + NumpadEnter: 'NUMPAD_ENTER', + Minus: 'MINUS', + Equal: 'EQUAL', + BracketLeft: 'BRACKET_LEFT', + BracketRight: 'BRACKET_RIGHT', + Backslash: 'BACKSLASH', + Semicolon: 'SEMICOLON', + Quote: 'QUOTE', + Backquote: 'BACKQUOTE', + Comma: 'COMMA', + Period: 'PERIOD', + Slash: 'SLASH', + PrintScreen: 'PRINT_SCREEN', + Pause: 'PAUSE', + ScrollLock: 'SCROLL_LOCK', + NumLock: 'NUM_LOCK', + CapsLock: 'CAPS_LOCK', + MediaPlayPause: 'MEDIA_PLAY_PAUSE', + MediaStop: 'MEDIA_STOP', + MediaTrackNext: 'MEDIA_NEXT', + MediaTrackPrevious: 'MEDIA_PREVIOUS', + AudioVolumeUp: 'VOLUME_UP', + AudioVolumeDown: 'VOLUME_DOWN', + AudioVolumeMute: 'VOLUME_MUTE', +}; + +// Canonical key name -> what to render in the Kbd slot. +const KEY_LABELS: Record = { + UP: '↑', + DOWN: '↓', + LEFT: '←', + RIGHT: '→', + PAGE_UP: 'Pg Up', + PAGE_DOWN: 'Pg Dn', + PRINT_SCREEN: 'Prt Scn', + SCROLL_LOCK: 'Scroll Lk', + NUM_LOCK: 'Num Lk', + CAPS_LOCK: 'Caps Lk', + NUMPAD_ADD: 'Num +', + NUMPAD_SUBTRACT: 'Num -', + NUMPAD_MULTIPLY: 'Num *', + NUMPAD_DIVIDE: 'Num /', + NUMPAD_DECIMAL: 'Num .', + NUMPAD_ENTER: 'Num ↵', + MEDIA_PLAY_PAUSE: '⏯', + MEDIA_STOP: '⏹', + MEDIA_NEXT: '⏭', + MEDIA_PREVIOUS: '⏮', + VOLUME_UP: 'Vol +', + VOLUME_DOWN: 'Vol -', + VOLUME_MUTE: 'Vol Mute', + MINUS: '-', + EQUAL: '=', + BRACKET_LEFT: '[', + BRACKET_RIGHT: ']', + BACKSLASH: '\\', + SEMICOLON: ';', + QUOTE: "'", + BACKQUOTE: '`', + COMMA: ',', + PERIOD: '.', + SLASH: '/', + SPACE: 'Space', + ENTER: 'Enter', + TAB: 'Tab', + BACKSPACE: 'Backspace', + ESCAPE: 'Esc', + HOME: 'Home', + END: 'End', + INSERT: 'Ins', + DELETE: 'Del', +}; +Array.from({ length: 10 }, (_, i) => i).forEach((i) => { + KEY_LABELS[`NUMPAD_${i}`] = `Num ${i}`; +}); + +export function keybindLabel(key: string): string { + return KEY_LABELS[key] ?? key; +} + +function orderModifiers(mods: string[]): string[] { + return MODIFIER_ORDER.filter((m) => mods.includes(m)); +} + +export function isValidKeybind(keys: string[]): boolean { + const main = keys.filter((k) => !MODIFIER_ORDER.includes(k)); + if (main.length !== 1) return false; + if (MODIFIER_OPTIONAL_KEYS.has(main[0])) return true; + return keys.some((k) => NON_SHIFT_MODIFIERS.includes(k)); +} + +// Ordered the same way as the server's canonicalKeybind, so the two stay in sync. +export function keybindKey(keys: string[]): string { + const modifiers = orderModifiers(keys.filter((k) => MODIFIER_ORDER.includes(k))); + const main = keys.filter((k) => !MODIFIER_ORDER.includes(k)); + return [...modifiers, ...main].join('+'); +} + +const F_KEY = /^F([1-9]|1\d|2[0-4])$/; + +export function resolveKey(e: React.KeyboardEvent): string | null { + if (MODIFIER_KEY_NAMES[e.key.toUpperCase()]) return null; + if (e.code.startsWith('Key')) return e.code.slice(3); + if (e.code.startsWith('Digit')) return e.code.slice(5); + if (e.code.startsWith('Numpad') && e.code.length === 7 && /^\d$/.test(e.code[6])) + return `NUMPAD_${e.code[6]}`; + // KeyboardEvent.code for function keys is already "F1".."F24", matching our canonical name. + if (F_KEY.test(e.code)) return e.code; + return CODE_TO_KEY[e.code] ?? null; +} + +export function modifierNameForCode(code: string): string | undefined { + return MODIFIER_CODE_NAMES[code]; +} + +export function modifierNameForKey(key: string): string | undefined { + return MODIFIER_KEY_NAMES[key.toUpperCase()]; +} + +export function modifiersFromHeld(held: Set): string[] { + const mods: string[] = []; + for (const code of held) { + const name = MODIFIER_CODE_NAMES[code]; + if (name && !mods.includes(name)) mods.push(name); + } + return orderModifiers(mods); +} diff --git a/gui/app/src/components/settings/pages/KeybindSettings.tsx b/gui/app/src/components/settings/pages/KeybindSettings.tsx index d72e4eae6..1e35c9e7d 100644 --- a/gui/app/src/components/settings/pages/KeybindSettings.tsx +++ b/gui/app/src/components/settings/pages/KeybindSettings.tsx @@ -9,10 +9,13 @@ import { Typography } from '@/components/commons/Typography'; import { useLocalization } from '@fluent/react'; import { Button } from '@/components/commons/Button'; import { KeybindsRow } from '@/components/commons/KeybindsRow'; +import { useElectron } from '@/hooks/electron'; import { useWebsocketAPI } from '@/hooks/websocket-api'; import { ReactNode, useEffect, useMemo, useRef, useState } from 'react'; import { ChangeKeybindRequestT, + KeybindActivatedResponseT, + KeybindId, KeybindRequestT, KeybindResponseT, KeybindSupport, @@ -53,6 +56,7 @@ function areBindingsEqual(a?: string[], b?: string[]): boolean { export function KeybindSettings() { const { l10n } = useLocalization(); + const electron = useElectron(); const { sendRPCPacket, useRPCPacket } = useWebsocketAPI(); const [isOpen, setIsOpen] = useState(false); const [defaultKeybindsState, setDefaultKeybindsState] = useState( @@ -86,26 +90,30 @@ export function KeybindSettings() { // Snapshot of the edited binding, restored if the modal is cancelled const bindingSnapshot = useRef(null); + const [collisionError, setCollisionError] = useState(null); const { fields } = useFieldArray({ control, name: 'keybinds', }); + const submitKeybind = (kb: KeybindForm['keybinds'][number]) => { + const changeKeybindRequest = new ChangeKeybindRequestT(); + const keybind = new KeybindT(); + keybind.keybindId = kb.keybindId; + keybind.keybindValue = kb.binding.join('+'); + keybind.keybindDelay = kb.delay; + changeKeybindRequest.keybind = keybind; + sendRPCPacket(RpcMessage.ChangeKeybindRequest, changeKeybindRequest); + }; + const onSubmit = (data?: KeybindForm) => { const value = data ?? getValues(); + value.keybinds.forEach(submitKeybind); + }; - value.keybinds.forEach((kb) => { - const currentBindingStr = kb.binding.join('+'); - const changeKeybindRequest = new ChangeKeybindRequestT(); - const keybind = new KeybindT(); - keybind.keybindId = kb.keybindId; - keybind.keybindValue = currentBindingStr; - keybind.keybindDelay = kb.delay; - changeKeybindRequest.keybind = keybind; - sendRPCPacket(RpcMessage.ChangeKeybindRequest, changeKeybindRequest); - }); - + const onSubmitIndex = (index: number) => { + submitKeybind(getValues(`keybinds.${index}`)); setIsOpen(false); }; @@ -125,7 +133,7 @@ export function KeybindSettings() { if (defaultKb) { setValue(`keybinds.${index}.binding`, defaultKb.binding); setValue(`keybinds.${index}.delay`, defaultKb.delay); - handleSubmit(onSubmit)(); + submitKeybind(getValues(`keybinds.${index}`)); } }; @@ -155,15 +163,22 @@ export function KeybindSettings() { } ); + const isFirstRender = useRef(true); useEffect(() => { + if (isFirstRender.current) { + isFirstRender.current = false; + return; + } const req = new SetKeybindRecordingRequestT(); req.recording = isOpen; sendRPCPacket(RpcMessage.SetKeybindRecordingRequest, req); + if (electron.isElectron) electron.api.setKeybindRecording(isOpen); }, [isOpen]); const handleOpenRecorderModal = (index: number) => { currentIndex.current = index; bindingSnapshot.current = getValues(`keybinds.${index}.binding`); + setCollisionError(null); setIsOpen(true); }; @@ -175,11 +190,33 @@ export function KeybindSettings() { ); } setIsOpen(false); + setCollisionError(null); clearErrors('keybinds'); }; const editedIndex = currentIndex.current; + useRPCPacket( + RpcMessage.KeybindActivatedResponse, + ({ keybindId }: KeybindActivatedResponseT) => { + if (!isOpen || editedIndex == null || keybindId === KeybindId.NONE) + return; + const editedId = getValues(`keybinds.${editedIndex}.keybindId`); + if (keybindId === editedId) return; + + const clash = getValues('keybinds').find( + (kb) => kb.keybindId === keybindId + ); + if (!clash) return; + + setCollisionError( + l10n.getString('settings-keybinds-already-assigned', { + name: l10n.getString('settings-keybinds_' + clash.name), + }) + ); + } + ); + const takenBindings = editedIndex != null ? getValues('keybinds') @@ -191,7 +228,7 @@ export function KeybindSettings() { })) : []; - const createKeybindRows = (): ReactNode => { + const createKeybindRows = (bindingEditable: boolean): ReactNode => { return fields.map((field, index) => { const currentKb = watch(`keybinds.${index}`); const defaultKb = currentKb @@ -210,9 +247,12 @@ export function KeybindSettings() { id={field.name} control={control} index={index} - openKeybindRecorderModal={handleOpenRecorderModal} + openKeybindRecorderModal={ + bindingEditable ? handleOpenRecorderModal : undefined + } onResetSingle={handleResetSingle} isModified={isModified} + bindingEditable={bindingEditable} /> ); }); @@ -224,8 +264,9 @@ export function KeybindSettings() { useEffect(() => { const subscription = watch((_, { name, type }) => { - if (type === 'change' && name?.endsWith('.delay')) - handleSubmit(onSubmit)(); + if (type !== 'change' || !name?.endsWith('.delay')) return; + const match = name.match(/^keybinds\.(\d+)\.delay$/); + if (match) submitKeybind(getValues(`keybinds.${Number(match[1])}`)); }); return () => subscription.unsubscribe(); }, [watch]); @@ -253,21 +294,22 @@ export function KeybindSettings() {
)} - {support === KeybindSupport.SYSTEM_MANAGED && ( -
- -
-
-
- )} - - {support === KeybindSupport.APP_MANAGED && ( + {(support === KeybindSupport.SYSTEM_MANAGED || + support === KeybindSupport.APP_MANAGED) && ( + {support === KeybindSupport.SYSTEM_MANAGED && ( +
+ +
+
+
+ )} +
@@ -294,7 +336,7 @@ export function KeybindSettings() { - {createKeybindRows()} + {createKeybindRows(support === KeybindSupport.APP_MANAGED)}
@@ -310,7 +352,7 @@ export function KeybindSettings() { /> - {editedIndex != null && ( + {support === KeybindSupport.APP_MANAGED && editedIndex != null && ( { setValue(`keybinds.${editedIndex}.binding`, []); - handleSubmit(onSubmit)(); + onSubmitIndex(editedIndex); }} - onSubmit={() => handleSubmit(onSubmit)()} + onSubmit={() => onSubmitIndex(editedIndex)} onReset={() => handleResetSingle(editedIndex)} takenBindings={takenBindings} + activatedError={collisionError} /> )}
diff --git a/gui/electron/main/index.ts b/gui/electron/main/index.ts index 89c407e4e..41e7cb6e8 100644 --- a/gui/electron/main/index.ts +++ b/gui/electron/main/index.ts @@ -65,6 +65,14 @@ protocol.registerSchemesAsPrivileged([ let mainWindow: BrowserWindow | null = null; +// While the keybind recorder is open, F3/F5/F7/F12/Ctrl+R must reach the renderer as +// ordinary keydowns instead of being eaten by hardenWindow's reload/devtools guards below, +// otherwise those keys can never be captured into a shortcut at all. +let recordingKeybind = false; +handleIpc(IPC_CHANNELS.SET_KEYBIND_RECORDING, (e, recording) => { + recordingKeybind = recording; +}); + handleIpc( IPC_CHANNELS.GH_FETCH, async (_e: unknown, options: T): Promise => { @@ -279,6 +287,7 @@ function hardenWindow(win: BrowserWindow) { const devMode = !!process.env.ELECTRON_RENDERER_URL; win.webContents.on('before-input-event', (event, input) => { if (input.type !== 'keyDown') return; + if (recordingKeybind) return; const key = input.key.toLowerCase(); const mod = input.control || input.meta; diff --git a/gui/electron/preload/index.ts b/gui/electron/preload/index.ts index 6dc650da9..5a933b216 100644 --- a/gui/electron/preload/index.ts +++ b/gui/electron/preload/index.ts @@ -48,4 +48,6 @@ contextBridge.exposeInMainWorld('electronAPI', { setPresence: (options) => ipcRenderer.invoke(IPC_CHANNELS.DISCORD_PRESENCE, options), getInstallDir: () => ipcRenderer.invoke(IPC_CHANNELS.GET_FOLDER, 'exe'), isSteam: () => ipcRenderer.invoke(IPC_CHANNELS.IS_STEAM), + setKeybindRecording: (recording) => + ipcRenderer.invoke(IPC_CHANNELS.SET_KEYBIND_RECORDING, recording), } satisfies IElectronAPI); diff --git a/gui/shared/src/interface.ts b/gui/shared/src/interface.ts index 4250b0ca1..8ea2df866 100644 --- a/gui/shared/src/interface.ts +++ b/gui/shared/src/interface.ts @@ -60,6 +60,7 @@ export interface IElectronAPI { setPresence: (options: DiscordPresence) => void; getInstallDir: () => Promise; isSteam: () => Promise; + setKeybindRecording: (recording: boolean) => void; } declare global { diff --git a/gui/shared/src/ipc.ts b/gui/shared/src/ipc.ts index dc981d4ae..6b3d29a44 100644 --- a/gui/shared/src/ipc.ts +++ b/gui/shared/src/ipc.ts @@ -21,6 +21,7 @@ export const IPC_CHANNELS = { GH_FETCH: 'gh-fetch', DISCORD_PRESENCE: 'discord-presence', IS_STEAM: 'is-steam', + SET_KEYBIND_RECORDING: 'set-keybind-recording', } as const; export interface IpcInvokeMap { @@ -50,4 +51,5 @@ export interface IpcInvokeMap { ) => Promise; [IPC_CHANNELS.DISCORD_PRESENCE]: (options: DiscordPresence) => void; [IPC_CHANNELS.IS_STEAM]: () => boolean; + [IPC_CHANNELS.SET_KEYBIND_RECORDING]: (recording: boolean) => void; } diff --git a/server/core/src/main/java/dev/slimevr/keybind/keys.kt b/server/core/src/main/java/dev/slimevr/keybind/keys.kt new file mode 100644 index 000000000..e614afda9 --- /dev/null +++ b/server/core/src/main/java/dev/slimevr/keybind/keys.kt @@ -0,0 +1,57 @@ +package dev.slimevr.keybind + +val MODIFIER_ORDER = listOf("CTRL", "ALT", "SHIFT", "SUPER") +private val NON_SHIFT_MODIFIERS = setOf("CTRL", "ALT", "SUPER") + +private val LETTERS = ('A'..'Z').map { it.toString() } +private val DIGITS = ('0'..'9').map { it.toString() } +private val FUNCTION_KEYS = (1..24).map { "F$it" } +private val ARROW_KEYS = listOf("UP", "DOWN", "LEFT", "RIGHT") +private val NAV_KEYS = listOf("HOME", "END", "PAGE_UP", "PAGE_DOWN", "INSERT", "DELETE") +private val CONTROL_KEYS = listOf("SPACE", "ENTER", "TAB", "BACKSPACE", "ESCAPE") +private val NUMPAD_KEYS = (0..9).map { "NUMPAD_$it" } + + listOf("NUMPAD_ADD", "NUMPAD_SUBTRACT", "NUMPAD_MULTIPLY", "NUMPAD_DIVIDE", "NUMPAD_DECIMAL", "NUMPAD_ENTER") +private val PUNCTUATION_KEYS = listOf( + "MINUS", "EQUAL", "BRACKET_LEFT", "BRACKET_RIGHT", "BACKSLASH", + "SEMICOLON", "QUOTE", "BACKQUOTE", "COMMA", "PERIOD", "SLASH", +) +private val SYSTEM_KEYS = listOf("PRINT_SCREEN", "PAUSE", "SCROLL_LOCK", "NUM_LOCK", "CAPS_LOCK") +val MEDIA_KEYS = listOf( + "MEDIA_PLAY_PAUSE", + "MEDIA_STOP", + "MEDIA_NEXT", + "MEDIA_PREVIOUS", + "VOLUME_UP", + "VOLUME_DOWN", + "VOLUME_MUTE", +) + +/** Keys meaningfully bindable without a modifier: function, media/volume and standalone system keys. */ +val MODIFIER_OPTIONAL_KEYS: Set = + (FUNCTION_KEYS + MEDIA_KEYS + listOf("PRINT_SCREEN", "PAUSE", "SCROLL_LOCK")).toSet() + +val KEYBIND_MAIN_KEYS: Set = ( + LETTERS + + DIGITS + + FUNCTION_KEYS + + ARROW_KEYS + + NAV_KEYS + + CONTROL_KEYS + + NUMPAD_KEYS + + PUNCTUATION_KEYS + + SYSTEM_KEYS + + MEDIA_KEYS + ).toSet() + +fun canonicalKeybind(binding: String): String { + val parts = binding.split('+').map { it.trim().uppercase() }.filter { it.isNotEmpty() } + return (MODIFIER_ORDER.filter { it in parts } + parts.filterNot { it in MODIFIER_ORDER }).joinToString("+") +} + +fun isValidKeybind(binding: String): Boolean { + val parts = binding.split('+').map { it.trim().uppercase() }.filter { it.isNotEmpty() } + val key = parts.filterNot { it in MODIFIER_ORDER }.singleOrNull() ?: return false + if (key !in KEYBIND_MAIN_KEYS) return false + if (key in MODIFIER_OPTIONAL_KEYS) return true + return parts.any { it in NON_SHIFT_MODIFIERS } +} diff --git a/server/core/src/main/java/dev/slimevr/solarxr/rpc/keybinds.kt b/server/core/src/main/java/dev/slimevr/solarxr/rpc/keybinds.kt index 958a77123..df5adade7 100644 --- a/server/core/src/main/java/dev/slimevr/solarxr/rpc/keybinds.kt +++ b/server/core/src/main/java/dev/slimevr/solarxr/rpc/keybinds.kt @@ -5,7 +5,10 @@ import dev.slimevr.config.Settings import dev.slimevr.config.SettingsActions import dev.slimevr.config.defaultKeybinds import dev.slimevr.keybind.KeybindActions +import dev.slimevr.keybind.KeybindEvent import dev.slimevr.keybind.KeybindManager +import dev.slimevr.keybind.canonicalKeybind +import dev.slimevr.keybind.isValidKeybind import dev.slimevr.solarxr.SolarXRBridge import dev.slimevr.solarxr.SolarXRBridgeBehaviour import kotlinx.coroutines.flow.distinctUntilChanged @@ -15,6 +18,7 @@ import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.onEach import solarxr_protocol.rpc.ChangeKeybindRequest import solarxr_protocol.rpc.Keybind +import solarxr_protocol.rpc.KeybindActivatedResponse import solarxr_protocol.rpc.KeybindId import solarxr_protocol.rpc.KeybindRequest import solarxr_protocol.rpc.KeybindResponse @@ -29,22 +33,6 @@ private fun keybindConfigToProto(config: KeybindConfig): Keybind = Keybind( keybindDelay = config.delay, ) -private val MODIFIER_ORDER = listOf("CTRL", "ALT", "SHIFT", "SUPER") - -private val NON_SHIFT_MODIFIERS = setOf("CTRL", "ALT", "SUPER") - -fun canonicalKeybind(binding: String): String { - val parts = binding.split('+').map { it.trim().uppercase() }.filter { it.isNotEmpty() } - return (MODIFIER_ORDER.filter { it in parts } + parts.filterNot { it in MODIFIER_ORDER }).joinToString("+") -} - -fun isValidKeybind(binding: String): Boolean { - val parts = binding.split('+').map { it.trim().uppercase() }.filter { it.isNotEmpty() } - val key = parts.filterNot { it in MODIFIER_ORDER }.singleOrNull() ?: return false - if (!key.matches(Regex("[A-Z0-9]"))) return false - return parts.any { it in NON_SHIFT_MODIFIERS } -} - class KeybindsBehaviour( private val settings: Settings, private val keybindManager: KeybindManager, @@ -54,6 +42,10 @@ class KeybindsBehaviour( keybindManager.context.dispatch(KeybindActions.SetRecording(req.recording)) }.launchIn(receiver.context.scope) + keybindManager.events.on { event -> + if (keybindManager.recording) receiver.sendRpc(KeybindActivatedResponse(keybindId = event.id)) + }.launchIn(receiver.context.scope) + fun buildResponse(keybinds: List) = KeybindResponse( keybind = keybinds.map { keybindConfigToProto(it) }, defaultKeybinds = defaultKeybinds().map { keybindConfigToProto(it) }, diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/keybind/gnome.kt b/server/desktop/src/main/java/dev/slimevr/desktop/keybind/gnome.kt index 4208cccdc..72d43b87c 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/keybind/gnome.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/keybind/gnome.kt @@ -2,8 +2,8 @@ package dev.slimevr.desktop.keybind import dev.slimevr.config.KeybindConfig import dev.slimevr.desktop.install.executeShellCommand +import dev.slimevr.keybind.canonicalKeybind import dev.slimevr.logging.AppLogger -import dev.slimevr.solarxr.rpc.canonicalKeybind import solarxr_protocol.rpc.KeybindId import java.io.File @@ -16,6 +16,61 @@ private val MODIFIERS = linkedMapOf( "SUPER" to "", ) +// GTK keyval names (gtk_accelerator_name), used both for GNOME's own dconf-stored +// accelerators and as the preferred_trigger the xdg-desktop-portal GlobalShortcuts +// implementation parses with gtk_accelerator_parse. +private val KEY_TO_GTK: Map = buildMap { + ('A'..'Z').forEach { put(it.toString(), it.lowercaseChar().toString()) } + ('0'..'9').forEach { put(it.toString(), it.toString()) } + (1..24).forEach { put("F$it", "F$it") } + put("UP", "Up") + put("DOWN", "Down") + put("LEFT", "Left") + put("RIGHT", "Right") + put("HOME", "Home") + put("END", "End") + put("PAGE_UP", "Page_Up") + put("PAGE_DOWN", "Page_Down") + put("INSERT", "Insert") + put("DELETE", "Delete") + put("SPACE", "space") + put("ENTER", "Return") + put("TAB", "Tab") + put("BACKSPACE", "BackSpace") + put("ESCAPE", "Escape") + (0..9).forEach { put("NUMPAD_$it", "KP_$it") } + put("NUMPAD_ADD", "KP_Add") + put("NUMPAD_SUBTRACT", "KP_Subtract") + put("NUMPAD_MULTIPLY", "KP_Multiply") + put("NUMPAD_DIVIDE", "KP_Divide") + put("NUMPAD_DECIMAL", "KP_Decimal") + put("NUMPAD_ENTER", "KP_Enter") + put("MINUS", "minus") + put("EQUAL", "equal") + put("BRACKET_LEFT", "bracketleft") + put("BRACKET_RIGHT", "bracketright") + put("BACKSLASH", "backslash") + put("SEMICOLON", "semicolon") + put("QUOTE", "apostrophe") + put("BACKQUOTE", "grave") + put("COMMA", "comma") + put("PERIOD", "period") + put("SLASH", "slash") + put("PRINT_SCREEN", "Print") + put("PAUSE", "Pause") + put("SCROLL_LOCK", "Scroll_Lock") + put("NUM_LOCK", "Num_Lock") + put("CAPS_LOCK", "Caps_Lock") + put("MEDIA_PLAY_PAUSE", "AudioPlay") + put("MEDIA_STOP", "AudioStop") + put("MEDIA_NEXT", "AudioNext") + put("MEDIA_PREVIOUS", "AudioPrev") + put("VOLUME_UP", "AudioRaiseVolume") + put("VOLUME_DOWN", "AudioLowerVolume") + put("VOLUME_MUTE", "AudioMute") +} +private val GTK_TO_KEY: Map = KEY_TO_GTK.entries.associate { (k, v) -> v to k } + fun isGnome(): Boolean = System.getenv("XDG_CURRENT_DESKTOP")?.uppercase()?.contains("GNOME") == true fun resolveGnomeAppId(): String? { @@ -35,16 +90,18 @@ fun resolveGnomeAppId(): String? { } /** Converts our `CTRL+ALT+SHIFT+Y` form into GTK's `y` form. */ -private fun toGnomeAccelerator(binding: String): String? { +fun toGnomeAccelerator(binding: String): String? { val parts = binding.split('+').map { it.trim().uppercase() }.filter { it.isNotEmpty() } val key = parts.firstOrNull { it !in MODIFIERS } ?: return null + val gtkKey = KEY_TO_GTK[key] ?: return null val modifiers = parts.filter { it in MODIFIERS }.toSet() - return MODIFIERS.filterKeys { it in modifiers }.values.joinToString("") + key.lowercase() + return MODIFIERS.filterKeys { it in modifiers }.values.joinToString("") + gtkKey } private fun fromGnomeAccelerator(accelerator: String): String? { - val key = accelerator.substringAfterLast('>').uppercase().ifEmpty { return null } + val gtkKey = accelerator.substringAfterLast('>').ifEmpty { return null } + val key = GTK_TO_KEY[gtkKey] ?: return null val modifiers = MODIFIERS.filterValues { it in accelerator }.keys return canonicalKeybind((modifiers + key).joinToString("+")) } diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/keybind/keybinds.kt b/server/desktop/src/main/java/dev/slimevr/desktop/keybind/keybinds.kt index 400c4e42e..96963d22b 100644 --- a/server/desktop/src/main/java/dev/slimevr/desktop/keybind/keybinds.kt +++ b/server/desktop/src/main/java/dev/slimevr/desktop/keybind/keybinds.kt @@ -1,43 +1,16 @@ package dev.slimevr.desktop.keybind -import com.melloware.jintellitype.JIntellitype -import dev.hannah.portals.PortalManager -import dev.hannah.portals.globalShortcuts.GlobalShortcutsHandler -import dev.hannah.portals.globalShortcuts.Shortcut -import dev.hannah.portals.globalShortcuts.ShortcutTuple import dev.slimevr.AppContextProvider import dev.slimevr.CURRENT_PLATFORM import dev.slimevr.Platform -import dev.slimevr.SLIMEVR_IDENTIFIER -import dev.slimevr.config.KeybindConfig -import dev.slimevr.config.SettingsActions -import dev.slimevr.keybind.KeybindEvent import dev.slimevr.logging.AppLogger import kotlinx.coroutines.CoroutineScope -import kotlinx.coroutines.FlowPreview -import kotlinx.coroutines.awaitCancellation -import kotlinx.coroutines.flow.combine -import kotlinx.coroutines.flow.debounce -import kotlinx.coroutines.flow.distinctUntilChanged -import kotlinx.coroutines.flow.distinctUntilChangedBy -import kotlinx.coroutines.flow.drop -import kotlinx.coroutines.flow.filter -import kotlinx.coroutines.flow.launchIn -import kotlinx.coroutines.flow.map -import kotlinx.coroutines.flow.onEach -import kotlinx.coroutines.launch import solarxr_protocol.rpc.KeybindId -private const val BINDING_SETTLE_MS = 300L - fun keybindLabel(id: KeybindId): String = id.name .split('_') .joinToString(" ") { word -> word.lowercase().replaceFirstChar { it.uppercase() } } -private fun toJIntellitypeAccelerator(binding: String): String = binding - .split('+') - .joinToString("+") { if (it == "SUPER") "WIN" else it } - suspend fun createDesktopKeybindManager(appContext: AppContextProvider, scope: CoroutineScope) { when (CURRENT_PLATFORM) { Platform.WINDOWS -> setupWindowsKeybinds(appContext, scope) @@ -45,117 +18,3 @@ suspend fun createDesktopKeybindManager(appContext: AppContextProvider, scope: C else -> AppLogger.keybind.info("Keybinds are not supported on $CURRENT_PLATFORM") } } - -private suspend fun setupWindowsKeybinds(appContext: AppContextProvider, scope: CoroutineScope) { - val instance = try { - JIntellitype.getInstance() - } catch (e: Throwable) { - AppLogger.keybind.error(e, "Failed to initialize JIntellitype, keybinds will be disabled") - return - } - - instance.addHotKeyListener { identifier -> - KeybindId.fromValue(identifier.toUByte())?.let { id -> - scope.launch { appContext.keybindManager.events.emit(KeybindEvent.Fired(id)) } - } - } - - var registered: List = emptyList() - suspend fun apply(keybinds: List) { - registered.forEach { runCatching { instance.unregisterHotKey(it.id.value.toInt()) } } - registered = emptyList() - if (appContext.keybindManager.recording) return - - val active = keybinds.filter { it.binding.isNotEmpty() } - active.forEach { keybind -> - runCatching { instance.registerHotKey(keybind.id.value.toInt(), toJIntellitypeAccelerator(keybind.binding)) } - .onFailure { AppLogger.keybind.warn("Failed to bind ${keybind.id.name} to ${keybind.binding}") } - } - registered = active - } - - apply(appContext.config.settings.context.state.value.data.keybinds) - appContext.keybindManager.events.on { apply(it.keybinds) }.launchIn(scope) - - appContext.keybindManager.context.state - .map { it.recording } - .distinctUntilChanged() - .onEach { apply(appContext.config.settings.context.state.value.data.keybinds) } - .launchIn(scope) -} - -@OptIn(FlowPreview::class) -private suspend fun setupLinuxKeybinds(appContext: AppContextProvider, scope: CoroutineScope) { - val gnomeAppId = if (isGnome()) resolveGnomeAppId() else null - var handler: GlobalShortcutsHandler? = null - - suspend fun adoptGnomeShortcuts(appId: String) { - val stored = readGnomeShortcuts(appId).ifEmpty { return } - appContext.config.settings.context.dispatch( - SettingsActions.Update { - copy(keybinds = keybinds.map { keybind -> stored[keybind.id]?.let { keybind.copy(binding = it) } ?: keybind }) - }, - ) - } - - // Closing a handler disconnects its dbus connection, so every session gets its own manager - suspend fun bind(keybinds: List) { - runCatching { handler?.close() } - handler = null - if (appContext.keybindManager.recording) return - - val shortcuts = keybinds - .filter { it.binding.isNotEmpty() } - .map { keybind -> ShortcutTuple(keybind.id.name, Shortcut(keybindLabel(keybind.id), keybind.binding).shortcut) } - .toMutableList() - if (shortcuts.isEmpty()) return - - handler = runCatching { - PortalManager(SLIMEVR_IDENTIFIER).globalShortcutsRequest(shortcuts).apply { - onShortcutActivated = { shortcutId -> - KeybindId.entries.firstOrNull { it.name == shortcutId }?.let { id -> - scope.launch { appContext.keybindManager.events.emit(KeybindEvent.Fired(id)) } - } - } - } - }.onFailure { - AppLogger.keybind.error(it, "Failed to register global shortcuts, keybinds will not work") - }.getOrNull() - } - if (gnomeAppId != null) { - adoptGnomeShortcuts(gnomeAppId) - } - - bind(appContext.config.settings.context.state.value.data.keybinds) - - appContext.keybindManager.context.state - .map { it.recording } - .distinctUntilChanged() - .filter { it } - .onEach { - runCatching { handler?.close() } - handler = null - } - .launchIn(scope) - - combine( - appContext.keybindManager.context.state.map { it.recording }.distinctUntilChanged(), - appContext.config.settings.context.state.map { it.data.keybinds }.distinctUntilChangedBy { keybinds -> keybinds.map { it.id to it.binding } }, - ) { recording, keybinds -> recording to keybinds } - .drop(1) - .debounce(BINDING_SETTLE_MS) - .filter { (recording, _) -> !recording } - .onEach { (_, keybinds) -> - if (gnomeAppId != null) writeGnomeShortcuts(gnomeAppId, keybinds) - bind(keybinds) - } - .launchIn(scope) - - scope.launch { - try { - awaitCancellation() - } finally { - runCatching { handler?.close() } - } - } -} diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/keybind/linux.kt b/server/desktop/src/main/java/dev/slimevr/desktop/keybind/linux.kt new file mode 100644 index 000000000..0d280ddd3 --- /dev/null +++ b/server/desktop/src/main/java/dev/slimevr/desktop/keybind/linux.kt @@ -0,0 +1,125 @@ +package dev.slimevr.desktop.keybind + +import dev.hannah.portals.PortalManager +import dev.hannah.portals.globalShortcuts.GlobalShortcutsHandler +import dev.hannah.portals.globalShortcuts.Shortcut +import dev.hannah.portals.globalShortcuts.ShortcutTuple +import dev.slimevr.AppContextProvider +import dev.slimevr.SLIMEVR_IDENTIFIER +import dev.slimevr.config.KeybindConfig +import dev.slimevr.config.SettingsActions +import dev.slimevr.keybind.KeybindEvent +import dev.slimevr.logging.AppLogger +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.FlowPreview +import kotlinx.coroutines.awaitCancellation +import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.debounce +import kotlinx.coroutines.flow.distinctUntilChanged +import kotlinx.coroutines.flow.distinctUntilChangedBy +import kotlinx.coroutines.flow.drop +import kotlinx.coroutines.flow.filter +import kotlinx.coroutines.flow.launchIn +import kotlinx.coroutines.flow.map +import kotlinx.coroutines.flow.onEach +import kotlinx.coroutines.launch +import kotlinx.coroutines.runInterruptible +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import kotlinx.coroutines.withTimeout +import solarxr_protocol.rpc.KeybindId + +private const val BINDING_SETTLE_MS = 300L +private const val PORTAL_BIND_TIMEOUT_MS = 5000L + +@OptIn(FlowPreview::class) +suspend fun setupLinuxKeybinds(appContext: AppContextProvider, scope: CoroutineScope) { + val gnomeAppId = if (isGnome()) resolveGnomeAppId() else null + var handler: GlobalShortcutsHandler? = null + val bindMutex = Mutex() + + suspend fun adoptGnomeShortcuts(appId: String) { + val stored = readGnomeShortcuts(appId).ifEmpty { return } + appContext.config.settings.context.dispatch( + SettingsActions.Update { + copy(keybinds = keybinds.map { keybind -> stored[keybind.id]?.let { keybind.copy(binding = it) } ?: keybind }) + }, + ) + } + + // GNOME rejects a second session for the same app_id while one is still open, so the old + // handler always closes before a new one is requested. CreateSession has no timeout of its + // own, so a failed rebind falls back to the last keybinds known to work. + var lastGoodKeybinds: List = emptyList() + + suspend fun attemptBind(keybinds: List): GlobalShortcutsHandler? { + val shortcuts = keybinds + .filter { it.binding.isNotEmpty() } + .map { keybind -> + val trigger = toGnomeAccelerator(keybind.binding) ?: keybind.binding + ShortcutTuple(keybind.id.name, Shortcut(keybindLabel(keybind.id), trigger).shortcut) + } + .toMutableList() + if (shortcuts.isEmpty()) return null + + return runCatching { + withTimeout(PORTAL_BIND_TIMEOUT_MS) { + runInterruptible(Dispatchers.IO) { + PortalManager(SLIMEVR_IDENTIFIER).globalShortcutsRequest(shortcuts) + } + } + }.getOrNull()?.apply { + onShortcutActivated = { shortcutId -> + KeybindId.entries.firstOrNull { it.name == shortcutId }?.let { id -> + scope.launch { appContext.keybindManager.events.emit(KeybindEvent.Fired(id)) } + } + } + } + } + + suspend fun bind(keybinds: List) = bindMutex.withLock { + runCatching { handler?.close() } + handler = null + + if (keybinds.none { it.binding.isNotEmpty() }) { + lastGoodKeybinds = keybinds + return@withLock + } + + handler = attemptBind(keybinds) + if (handler != null) { + lastGoodKeybinds = keybinds + return@withLock + } + + AppLogger.keybind.error("Failed to register global shortcuts for $keybinds, falling back to the last working bindings") + if (keybinds !== lastGoodKeybinds) handler = attemptBind(lastGoodKeybinds) + } + if (gnomeAppId != null) { + adoptGnomeShortcuts(gnomeAppId) + } + + bind(appContext.config.settings.context.state.value.data.keybinds) + + combine( + appContext.keybindManager.context.state.map { it.recording }.distinctUntilChanged(), + appContext.config.settings.context.state.map { it.data.keybinds }.distinctUntilChangedBy { keybinds -> keybinds.map { it.id to it.binding } }, + ) { recording, keybinds -> recording to keybinds } + .drop(1) + .debounce(BINDING_SETTLE_MS) + .filter { (recording, _) -> !recording } + .onEach { (_, keybinds) -> + if (gnomeAppId != null) writeGnomeShortcuts(gnomeAppId, keybinds) + bind(keybinds) + } + .launchIn(scope) + + scope.launch { + try { + awaitCancellation() + } finally { + runCatching { handler?.close() } + } + } +} diff --git a/server/desktop/src/main/java/dev/slimevr/desktop/keybind/windows.kt b/server/desktop/src/main/java/dev/slimevr/desktop/keybind/windows.kt new file mode 100644 index 000000000..599732f66 --- /dev/null +++ b/server/desktop/src/main/java/dev/slimevr/desktop/keybind/windows.kt @@ -0,0 +1,121 @@ +package dev.slimevr.desktop.keybind + +import com.melloware.jintellitype.JIntellitype +import dev.slimevr.AppContextProvider +import dev.slimevr.config.KeybindConfig +import dev.slimevr.keybind.KeybindEvent +import dev.slimevr.keybind.MODIFIER_ORDER +import dev.slimevr.logging.AppLogger +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import solarxr_protocol.rpc.KeybindId + +// Win32 virtual-key codes (winuser.h). RegisterHotKey can't distinguish the numpad Enter +// from the main one, so both map to VK_RETURN. +private val WIN32_VK_CODES: Map = buildMap { + ('A'..'Z').forEach { put(it.toString(), it.code) } + ('0'..'9').forEach { put(it.toString(), it.code) } + (1..24).forEach { put("F$it", 0x70 + (it - 1)) } + put("UP", 0x26) + put("DOWN", 0x28) + put("LEFT", 0x25) + put("RIGHT", 0x27) + put("HOME", 0x24) + put("END", 0x23) + put("PAGE_UP", 0x21) + put("PAGE_DOWN", 0x22) + put("INSERT", 0x2D) + put("DELETE", 0x2E) + put("SPACE", 0x20) + put("ENTER", 0x0D) + put("TAB", 0x09) + put("BACKSPACE", 0x08) + put("ESCAPE", 0x1B) + (0..9).forEach { put("NUMPAD_$it", 0x60 + it) } + put("NUMPAD_MULTIPLY", 0x6A) + put("NUMPAD_ADD", 0x6B) + put("NUMPAD_SUBTRACT", 0x6D) + put("NUMPAD_DECIMAL", 0x6E) + put("NUMPAD_DIVIDE", 0x6F) + put("NUMPAD_ENTER", 0x0D) + put("MINUS", 0xBD) + put("EQUAL", 0xBB) + put("BRACKET_LEFT", 0xDB) + put("BRACKET_RIGHT", 0xDD) + put("BACKSLASH", 0xDC) + put("SEMICOLON", 0xBA) + put("QUOTE", 0xDE) + put("BACKQUOTE", 0xC0) + put("COMMA", 0xBC) + put("PERIOD", 0xBE) + put("SLASH", 0xBF) + put("PRINT_SCREEN", 0x2C) + put("PAUSE", 0x13) + put("SCROLL_LOCK", 0x91) + put("NUM_LOCK", 0x90) + put("CAPS_LOCK", 0x14) + put("MEDIA_PLAY_PAUSE", 0xB3) + put("MEDIA_STOP", 0xB2) + put("MEDIA_NEXT", 0xB0) + put("MEDIA_PREVIOUS", 0xB1) + put("VOLUME_UP", 0xAF) + put("VOLUME_DOWN", 0xAE) + put("VOLUME_MUTE", 0xAD) +} + +private fun win32Modifiers(parts: List): Int { + var mask = 0 + if ("ALT" in parts) mask = mask or JIntellitype.MOD_ALT + if ("CTRL" in parts) mask = mask or JIntellitype.MOD_CONTROL + if ("SHIFT" in parts) mask = mask or JIntellitype.MOD_SHIFT + if ("SUPER" in parts) mask = mask or JIntellitype.MOD_WIN + return mask +} + +/** Returns the (modifier mask, virtual-key code) pair for [RegisterHotKey](https://learn.microsoft.com/windows/win32/api/winuser/nf-winuser-registerhotkey), or null if the key has no Windows mapping. */ +private fun toWindowsHotkey(binding: String): Pair? { + val parts = binding.split('+').map { it.trim().uppercase() }.filter { it.isNotEmpty() } + val key = parts.filterNot { it in MODIFIER_ORDER }.singleOrNull() ?: return null + val vkCode = WIN32_VK_CODES[key] ?: return null + return win32Modifiers(parts) to vkCode +} + +suspend fun setupWindowsKeybinds(appContext: AppContextProvider, scope: CoroutineScope) { + val instance = try { + JIntellitype.getInstance() + } catch (e: Throwable) { + AppLogger.keybind.error(e, "Failed to initialize JIntellitype, keybinds will be disabled") + return + } + + instance.addHotKeyListener { identifier -> + KeybindId.fromValue(identifier.toUByte())?.let { id -> + scope.launch { appContext.keybindManager.events.emit(KeybindEvent.Fired(id)) } + } + } + + val applyMutex = Mutex() + var registered: List = emptyList() + suspend fun apply(keybinds: List) = applyMutex.withLock { + registered.forEach { runCatching { instance.unregisterHotKey(it.id.value.toInt()) } } + registered = emptyList() + + val active = keybinds.filter { it.binding.isNotEmpty() } + active.forEach { keybind -> + val hotkey = toWindowsHotkey(keybind.binding) + if (hotkey == null) { + AppLogger.keybind.warn("No Windows key mapping for ${keybind.id.name} binding ${keybind.binding}") + return@forEach + } + val (mask, vkCode) = hotkey + runCatching { instance.registerHotKey(keybind.id.value.toInt(), mask, vkCode) } + .onFailure { AppLogger.keybind.warn("Failed to bind ${keybind.id.name} to ${keybind.binding}") } + } + registered = active + } + + apply(appContext.config.settings.context.state.value.data.keybinds) + appContext.keybindManager.events.on { apply(it.keybinds) }.launchIn(scope) +}