mirror of
https://github.com/SlimeVR/SlimeVR-Server.git
synced 2026-11-21 09:31:20 -08:00
Keybinds
This commit is contained in:
1 parent
5c4c64e629
commit
9332ff8e02
25 files changed
+1116
-49
No files matched your search
@@ -562,6 +562,27 @@ settings-stay_aligned-debug-label = Debugging
|
||||
settings-stay_aligned-debug-description = Please include your settings when reporting problems about Stay Aligned.
|
||||
settings-stay_aligned-debug-copy-label = Copy settings to clipboard
|
||||
|
||||
## Keybinds Page
|
||||
settings-keybinds = Keybind settings
|
||||
settings-keybinds-description = Change keybinds for various shortcuts
|
||||
keybind_config-keybind_name = Keybind
|
||||
keybind_config-keybind_value = Combination
|
||||
keybind_config-keybind_delay = Delay before trigger (s)
|
||||
settings-keybinds_full-reset = Full Reset
|
||||
settings-keybinds_yaw-reset = Yaw Reset
|
||||
settings-keybinds_mounting-reset = Mounting Reset
|
||||
settings-keybinds_feet-mounting-reset = Feet Mounting Reset
|
||||
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-unsupported-description = Global keybinds are not supported on this platform.
|
||||
settings-sidebar-keybinds = Keybinds
|
||||
settings-keybinds-recorder-modal-title = Assign keybind for
|
||||
settings-keybinds-recorder-modal-reset-button = Reset
|
||||
settings-keybinds-recorder-modal-unbind-button = Unbind
|
||||
settings-keybinds-recorder-modal-done-button = Done
|
||||
|
||||
## FK/Tracking settings
|
||||
settings-general-fk_settings = Tracking Settings
|
||||
|
||||
|
||||
@@ -44,6 +44,7 @@ import { useDiscordPresence } from './hooks/discord-presence';
|
||||
import { withSentryReactRouterV6Routing } from '@sentry/react';
|
||||
import { ScaledProportionsPage } from './components/onboarding/pages/body-proportions/ScaledProportions';
|
||||
import { AdvancedSettings } from './components/settings/pages/AdvancedSettings';
|
||||
import { KeybindSettings } from './components/settings/pages/KeybindSettings';
|
||||
import { FirmwareUpdate } from './components/firmware-update/FirmwareUpdate';
|
||||
import { ConnectionLost } from './components/onboarding/pages/ConnectionLost';
|
||||
import { VRCWarningsPage } from './components/vrc/VRCWarningsPage';
|
||||
@@ -143,6 +144,7 @@ function Layout() {
|
||||
<Route path="interface" element={<InterfaceSettings />} />
|
||||
<Route path="interface/home" element={<HomeScreenSettings />} />
|
||||
<Route path="advanced" element={<AdvancedSettings />} />
|
||||
<Route path="keybinds" element={<KeybindSettings />} />
|
||||
</Route>
|
||||
<Route
|
||||
path="/onboarding"
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { useState, forwardRef, useRef } from 'react';
|
||||
import { Typography } from './Typography';
|
||||
import classNames from 'classnames';
|
||||
import { useFormContext } from 'react-hook-form';
|
||||
|
||||
const excludedKeys = [' ', 'SPACE'];
|
||||
const maxKeybindLength = 4;
|
||||
|
||||
// KeyboardEvent.key spells some keys differently from the combinations the server stores.
|
||||
// The super/windows key comes through as Meta, or as OS on older Firefox.
|
||||
const keyAliases: Record<string, string> = {
|
||||
CONTROL: 'CTRL',
|
||||
META: 'SUPER',
|
||||
OS: 'SUPER',
|
||||
};
|
||||
|
||||
export const KeybindRecorder = forwardRef<
|
||||
HTMLInputElement,
|
||||
{
|
||||
keys: string[];
|
||||
onKeysChange: (v: string[]) => void;
|
||||
error?: string;
|
||||
}
|
||||
>(function KeybindRecorder({ keys, onKeysChange, error }) {
|
||||
const [localKeys, setLocalKeys] = useState<string[]>(keys);
|
||||
const [isRecording, setIsRecording] = useState(false);
|
||||
const [oldKeys, setOldKeys] = useState<string[]>([]);
|
||||
const [invalidSlot, setInvalidSlot] = useState<number | null>(null);
|
||||
const [errorText, setErrorText] = useState<string>('');
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const displayKeys = isRecording ? localKeys : keys;
|
||||
const activeIndex = isRecording ? displayKeys.length : -1;
|
||||
const displayError = errorText || error;
|
||||
|
||||
const { clearErrors } = useFormContext();
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
e.preventDefault();
|
||||
const rawKey = e.key.toUpperCase();
|
||||
const key = keyAliases[rawKey] ?? rawKey;
|
||||
const errorMsg = excludedKeys.includes(key)
|
||||
? `Cannot use ${key}!`
|
||||
: displayKeys.includes(key)
|
||||
? `${key} is a Duplicate Key!`
|
||||
: null;
|
||||
if (errorMsg) {
|
||||
setErrorText(errorMsg);
|
||||
setInvalidSlot(activeIndex);
|
||||
setTimeout(() => {
|
||||
setInvalidSlot(null);
|
||||
}, 350);
|
||||
return;
|
||||
}
|
||||
|
||||
if (displayKeys.length < maxKeybindLength) {
|
||||
const updatedKeys = [...displayKeys, key];
|
||||
setLocalKeys(updatedKeys);
|
||||
onKeysChange(updatedKeys);
|
||||
if (updatedKeys.length == maxKeybindLength) {
|
||||
inputRef.current?.blur();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleOnBlur = () => {
|
||||
setIsRecording(false);
|
||||
if (displayKeys.length < maxKeybindLength - 2 || error) {
|
||||
onKeysChange(oldKeys);
|
||||
setLocalKeys(oldKeys);
|
||||
}
|
||||
};
|
||||
|
||||
const handleOnFocus = () => {
|
||||
clearErrors('keybinds');
|
||||
const initialKeys: string[] = [];
|
||||
setOldKeys(keys);
|
||||
setLocalKeys(initialKeys);
|
||||
onKeysChange(initialKeys);
|
||||
setIsRecording(true);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="w-full justify-center items-center flex flex-col gap-2">
|
||||
<div className="flex gap-2 p-2 items-center rounded-lg relative">
|
||||
<input
|
||||
autoFocus
|
||||
ref={inputRef}
|
||||
className="opacity-0 absolute cursor-pointer w-full"
|
||||
onFocus={handleOnFocus}
|
||||
onBlur={handleOnBlur}
|
||||
onKeyDown={handleKeyDown}
|
||||
/>
|
||||
<div className="flex flex-grow gap-2 justify-center h-full">
|
||||
{Array.from({ length: maxKeybindLength }).map((_, i) => {
|
||||
const key = displayKeys[i];
|
||||
const isActive = isRecording && i === activeIndex;
|
||||
const isInvalid = invalidSlot === i;
|
||||
return (
|
||||
<div key={i} className="flex flex-row">
|
||||
<div
|
||||
className={classNames(
|
||||
'flex p-2 rounded-lg min-w-[50px] min-h-[50px] text-main-title justify-center items-center bg-background-80 mobile:text-sm',
|
||||
{
|
||||
'keyslot-invalid ring-2 ring-status-critical': isInvalid,
|
||||
'keyslot-animate ring-2 ring-accent':
|
||||
isActive && !isInvalid,
|
||||
'ring-accent': !isInvalid && !isInvalid,
|
||||
}
|
||||
)}
|
||||
>
|
||||
{key ?? ''}
|
||||
</div>
|
||||
<div className="flex pl-2 text-main-title justify-center items-center mobile:text-sm">
|
||||
{i < maxKeybindLength - 1 ? '+' : ''}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
{displayError && (
|
||||
<div className="isInvalid keyslot-invalid">
|
||||
<Typography color="text-status-critical">{`${errorText} ${error}`}</Typography>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,93 @@
|
||||
import { BaseModal } from './BaseModal';
|
||||
import {
|
||||
Controller,
|
||||
Control,
|
||||
useFormContext,
|
||||
FieldValues,
|
||||
FieldPath,
|
||||
} from 'react-hook-form';
|
||||
import { KeybindRecorder } from './KeybindRecorder';
|
||||
import { Typography } from './Typography';
|
||||
import { Button } from './Button';
|
||||
import './KeybindRow.scss';
|
||||
import { useLocalization } from '@fluent/react';
|
||||
|
||||
export function KeybindRecorderModal<T extends FieldValues = FieldValues>({
|
||||
id,
|
||||
control,
|
||||
name,
|
||||
isVisisble,
|
||||
onClose,
|
||||
onUnbind,
|
||||
onSubmit,
|
||||
}: {
|
||||
id?: string;
|
||||
control: Control<T>;
|
||||
name: FieldPath<T>;
|
||||
isVisisble: boolean;
|
||||
onClose: () => void;
|
||||
onUnbind: () => void;
|
||||
onSubmit: () => void;
|
||||
}) {
|
||||
const { l10n } = useLocalization();
|
||||
const keybindlocalization = 'settings-keybinds_' + id;
|
||||
const {
|
||||
formState: { errors },
|
||||
resetField,
|
||||
handleSubmit,
|
||||
} = useFormContext();
|
||||
|
||||
return (
|
||||
<BaseModal
|
||||
isOpen={isVisisble}
|
||||
onRequestClose={onClose}
|
||||
appendClasses="w-full max-w-xl"
|
||||
>
|
||||
<div className="flex flex-col gap-3 w-full justify-between h-full">
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-keybinds-recorder-modal-title')}{' '}
|
||||
{l10n.getString(keybindlocalization)}
|
||||
</Typography>
|
||||
<Controller
|
||||
control={control}
|
||||
name={name}
|
||||
render={({ field }) => (
|
||||
<KeybindRecorder
|
||||
keys={field.value ?? []}
|
||||
onKeysChange={field.onChange}
|
||||
ref={field.ref}
|
||||
error={errors.keybinds?.message as string}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<div className="flex flex-row justify-between w-full">
|
||||
<div className="flex flex-row justify-start gap-4">
|
||||
<Button
|
||||
id="settings-keybinds-recorder-modal-reset-button"
|
||||
variant="tertiary"
|
||||
onClick={() => {
|
||||
resetField(name);
|
||||
handleSubmit(onSubmit)();
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
id="settings-keybinds-recorder-modal-unbind-button"
|
||||
variant="tertiary"
|
||||
onClick={() => {
|
||||
onUnbind();
|
||||
handleSubmit(onSubmit)();
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-row justify-end">
|
||||
<Button
|
||||
id="settings-keybinds-recorder-modal-done-button"
|
||||
variant="primary"
|
||||
onClick={handleSubmit(onSubmit)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</BaseModal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
.keybind-row {
|
||||
display: grid;
|
||||
grid-column: 1 / -1;
|
||||
grid-template-columns: subgrid;
|
||||
height: auto;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
@keyframes keyslot {
|
||||
0%,
|
||||
100% {
|
||||
transform: scale(1);
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
50% {
|
||||
transform: scale(1.08);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes shake {
|
||||
0% {
|
||||
transform: translate(1px, 1px) rotate(0deg);
|
||||
}
|
||||
10% {
|
||||
transform: translate(-1px, -2px) rotate(-1deg);
|
||||
}
|
||||
20% {
|
||||
transform: translate(-3px, 0px) rotate(1deg);
|
||||
}
|
||||
30% {
|
||||
transform: translate(3px, 2px) rotate(0deg);
|
||||
}
|
||||
40% {
|
||||
transform: translate(1px, -1px) rotate(1deg);
|
||||
}
|
||||
50% {
|
||||
transform: translate(-1px, 2px) rotate(-1deg);
|
||||
}
|
||||
60% {
|
||||
transform: translate(-3px, 1px) rotate(0deg);
|
||||
}
|
||||
70% {
|
||||
transform: translate(3px, 1px) rotate(-1deg);
|
||||
}
|
||||
80% {
|
||||
transform: translate(-1px, -1px) rotate(1deg);
|
||||
}
|
||||
90% {
|
||||
transform: translate(1px, 2px) rotate(0deg);
|
||||
}
|
||||
100% {
|
||||
transform: translate(1px, -2px) rotate(-1deg);
|
||||
}
|
||||
}
|
||||
|
||||
.keyslot-animate {
|
||||
animation: keyslot 1s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.keyslot-invalid {
|
||||
animation: shake 0.35s ease;
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { Typography } from './Typography';
|
||||
import './KeybindRow.scss';
|
||||
import { Control, FieldPath, FieldValues, useWatch } from 'react-hook-form';
|
||||
import { NumberSelector } from './NumberSelector';
|
||||
import { useLocaleConfig } from '@/i18n/config';
|
||||
|
||||
function KeyBindKeyList({ keybind }: { keybind: string[] }) {
|
||||
if (keybind.length <= 1) {
|
||||
return (
|
||||
<div className="flex h-full text-section-title items-center justifiy-center">
|
||||
Click to edit keybind
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return keybind.map((key, i) => {
|
||||
return (
|
||||
<div key={i} className="flex flex-row">
|
||||
<div className="flex flex-wrap p-2 rounded-lg min-w-[50px] text-standard-bold justify-center items-center bg-background-80 mobile:text-sm">
|
||||
{key ?? ''}
|
||||
</div>
|
||||
<div className="flex justify-center items-center text-section-title mobile:text-sm gap-2 pl-3">
|
||||
{i < keybind.length - 1 ? '+' : ''}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function KeybindsRow<T extends FieldValues = FieldValues>({
|
||||
id,
|
||||
control,
|
||||
index,
|
||||
openKeybindRecorderModal,
|
||||
}: {
|
||||
id?: string;
|
||||
control: Control<T>;
|
||||
index: number;
|
||||
openKeybindRecorderModal: (index: number) => void;
|
||||
}) {
|
||||
const binding = useWatch({
|
||||
control,
|
||||
name: `keybinds.${index}.binding` as FieldPath<T>,
|
||||
}) as string[] | undefined;
|
||||
const { currentLocales } = useLocaleConfig();
|
||||
const secondsFormat = new Intl.NumberFormat(currentLocales, {
|
||||
style: 'unit',
|
||||
unit: 'second',
|
||||
unitDisplay: 'narrow',
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
|
||||
const handleOpenModal = () => {
|
||||
openKeybindRecorderModal(index);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="keybind-row bg-background-60 rounded-xl h-full keybinds-small:flex keybinds-small:flex-col keybinds-small:justify-center keybinds-small:items-center p-2">
|
||||
<label className="text-sm font-medium text-background-10 keybinds-small:flex keybinds-small:py-2 keybinds-small:justify-center keybinds-small:align-middle">
|
||||
<Typography id={`settings-keybinds_${id}`} />
|
||||
</label>
|
||||
<div
|
||||
className="flex gap-2 h-full items-center rounded-lg bg-background-70 hover:bg-background-50 w-full"
|
||||
onClick={handleOpenModal}
|
||||
>
|
||||
<div className="flex flex-grow gap-2 justify-center p-2 h-[50px]">
|
||||
{binding != null && <KeyBindKeyList keybind={binding} />}
|
||||
</div>
|
||||
</div>
|
||||
<NumberSelector
|
||||
control={control}
|
||||
name={`keybinds.${index}.delay` as FieldPath<T>}
|
||||
valueLabelFormat={(value) => secondsFormat.format(value)}
|
||||
min={0}
|
||||
max={10}
|
||||
step={0.2}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -57,60 +57,62 @@ export function NumberSelector<T extends FieldValues = FieldValues>({
|
||||
<Controller
|
||||
control={control}
|
||||
name={name}
|
||||
render={({ field: { onChange, value } }) => (
|
||||
<div className="flex flex-col gap-1 w-full">
|
||||
<Typography bold>{label}</Typography>
|
||||
<div className="flex gap-5 bg-background-60 p-2 rounded-lg">
|
||||
<div className="flex gap-1">
|
||||
{doubleStep !== undefined && (
|
||||
render={({ field: { onChange, value } }) => {
|
||||
return (
|
||||
<div className="flex flex-col gap-1 w-full">
|
||||
{label?.length != 0 ? <Typography bold>{label}</Typography> : <></>}
|
||||
<div className="flex gap-5 bg-background-60 p-2 rounded-lg">
|
||||
<div className="flex gap-1">
|
||||
{doubleStep !== undefined && (
|
||||
<Button
|
||||
variant="tertiary"
|
||||
rounded
|
||||
onClick={() => onChange(doubleStepFn(value, false))}
|
||||
disabled={doubleStepFn(value, false) < min || disabled}
|
||||
>
|
||||
{showButtonWithNumber
|
||||
? decimalFormat.format(-doubleStep)
|
||||
: '--'}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="tertiary"
|
||||
rounded
|
||||
onClick={() => onChange(doubleStepFn(value, false))}
|
||||
disabled={doubleStepFn(value, false) < min || disabled}
|
||||
onClick={() => onChange(stepFn(value, false))}
|
||||
disabled={stepFn(value, false) < min || disabled}
|
||||
>
|
||||
{showButtonWithNumber
|
||||
? decimalFormat.format(-doubleStep)
|
||||
: '--'}
|
||||
-
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="tertiary"
|
||||
rounded
|
||||
onClick={() => onChange(stepFn(value, false))}
|
||||
disabled={stepFn(value, false) < min || disabled}
|
||||
>
|
||||
-
|
||||
</Button>
|
||||
</div>
|
||||
<div className="flex flex-grow justify-center text-center items-center w-10 text-standard">
|
||||
{valueLabelFormat ? valueLabelFormat(value) : value}
|
||||
</div>
|
||||
<div className="flex gap-1">
|
||||
<Button
|
||||
variant="tertiary"
|
||||
rounded
|
||||
onClick={() => onChange(stepFn(value, true))}
|
||||
disabled={stepFn(value, true) > max || disabled}
|
||||
>
|
||||
+
|
||||
</Button>
|
||||
{doubleStep !== undefined && (
|
||||
</div>
|
||||
<div className="flex flex-grow justify-center text-center items-center w-10 text-standard">
|
||||
{valueLabelFormat ? valueLabelFormat(value) : value}
|
||||
</div>
|
||||
<div className="flex gap-1">
|
||||
<Button
|
||||
variant="tertiary"
|
||||
rounded
|
||||
onClick={() => onChange(doubleStepFn(value, true))}
|
||||
disabled={doubleStepFn(value, true) > max || disabled}
|
||||
onClick={() => onChange(stepFn(value, true))}
|
||||
disabled={stepFn(value, true) > max || disabled}
|
||||
>
|
||||
{showButtonWithNumber
|
||||
? decimalFormat.format(doubleStep)
|
||||
: '++'}
|
||||
+
|
||||
</Button>
|
||||
)}
|
||||
{doubleStep !== undefined && (
|
||||
<Button
|
||||
variant="tertiary"
|
||||
rounded
|
||||
onClick={() => onChange(doubleStepFn(value, true))}
|
||||
disabled={doubleStepFn(value, true) > max || disabled}
|
||||
>
|
||||
{showButtonWithNumber
|
||||
? decimalFormat.format(doubleStep)
|
||||
: '++'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -58,6 +58,10 @@ export function SettingSelectorMobile() {
|
||||
label: l10n.getString('settings-sidebar-advanced'),
|
||||
value: { url: '/settings/advanced' },
|
||||
},
|
||||
{
|
||||
label: l10n.getString('settings-sidebar-keybinds'),
|
||||
value: { url: '/settings/keybinds' },
|
||||
},
|
||||
{
|
||||
label: l10n.getString('navbar-onboarding'),
|
||||
value: { url: '/onboarding/home' },
|
||||
|
||||
@@ -144,6 +144,11 @@ export function SettingsSidebar() {
|
||||
to="/settings/advanced"
|
||||
id="settings-sidebar-advanced"
|
||||
/>
|
||||
<SettingsLink
|
||||
to="/settings/keybinds"
|
||||
scrollTo="keybinds"
|
||||
id="settings-sidebar-keybinds"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
.keybind-settings {
|
||||
display: grid;
|
||||
|
||||
grid-template:
|
||||
'n v d ' auto
|
||||
'k k k ' auto
|
||||
'b . . ' auto
|
||||
/ 1fr 1fr 90px;
|
||||
|
||||
grid-template-columns: subgrid;
|
||||
grid-template-rows: subgrid;
|
||||
|
||||
align-items: left;
|
||||
gap: 10px;
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
import { KeybindRecorderModal } from '@/components/commons/KeybindRecorderModal';
|
||||
import {
|
||||
SettingsPageLayout,
|
||||
SettingsPagePaneLayout,
|
||||
} from '@/components/settings/SettingsPageLayout';
|
||||
import { WrenchIcon } from '@/components/commons/icon/WrenchIcon';
|
||||
import { Typography } from '@/components/commons/Typography';
|
||||
import { useLocalization } from '@fluent/react';
|
||||
import './KeybindSettings.scss';
|
||||
import { Button } from '@/components/commons/Button';
|
||||
import { KeybindsRow } from '@/components/commons/KeybindsRow';
|
||||
import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
import { ReactNode, useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
ChangeKeybindRequestT,
|
||||
KeybindRequestT,
|
||||
KeybindResponseT,
|
||||
KeybindSupport,
|
||||
KeybindT,
|
||||
OpenKeybindSettingsRequestT,
|
||||
RpcMessage,
|
||||
} from 'solarxr-protocol';
|
||||
import { FormProvider, useFieldArray, useForm } from 'react-hook-form';
|
||||
|
||||
export type KeybindForm = {
|
||||
keybinds: {
|
||||
id: number;
|
||||
name: string;
|
||||
binding: string[];
|
||||
delay: number;
|
||||
}[];
|
||||
};
|
||||
|
||||
export function KeybindSettings() {
|
||||
const { l10n } = useLocalization();
|
||||
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
|
||||
const [isOpen, setIsOpen] = useState<boolean>(false);
|
||||
const [defaultKeybindsState, setDefaultKeybindsState] = useState<KeybindForm>(
|
||||
{
|
||||
keybinds: [],
|
||||
}
|
||||
);
|
||||
const currentIndex = useRef<number | null>(null);
|
||||
const [support, setSupport] = useState<KeybindSupport>(
|
||||
KeybindSupport.UNSUPPORTED
|
||||
);
|
||||
|
||||
const methods = useForm<KeybindForm>({
|
||||
defaultValues: defaultKeybindsState,
|
||||
});
|
||||
|
||||
const {
|
||||
control,
|
||||
handleSubmit,
|
||||
reset,
|
||||
setValue,
|
||||
getValues,
|
||||
setError,
|
||||
clearErrors,
|
||||
resetField,
|
||||
watch,
|
||||
} = methods;
|
||||
|
||||
const { fields } = useFieldArray({
|
||||
control,
|
||||
name: 'keybinds',
|
||||
});
|
||||
|
||||
const onSubmit = () => {
|
||||
const value = getValues();
|
||||
if (checkDuplicates(value)) {
|
||||
return;
|
||||
}
|
||||
clearErrors('keybinds');
|
||||
|
||||
value.keybinds.forEach((kb) => {
|
||||
const changeKeybindRequest = new ChangeKeybindRequestT();
|
||||
|
||||
const keybind = new KeybindT();
|
||||
keybind.keybindId = kb.id;
|
||||
keybind.keybindValue = kb.binding.join('+');
|
||||
keybind.keybindDelay = kb.delay;
|
||||
|
||||
changeKeybindRequest.keybind = keybind;
|
||||
|
||||
sendRPCPacket(RpcMessage.ChangeKeybindRequest, changeKeybindRequest);
|
||||
setIsOpen(false);
|
||||
});
|
||||
};
|
||||
|
||||
const checkDuplicates = (value: KeybindForm) => {
|
||||
const normalized = value.keybinds
|
||||
.filter((kb) => kb.binding.length > 0)
|
||||
.map((kb) => JSON.stringify([...kb.binding].sort()));
|
||||
|
||||
const unique = new Set(normalized);
|
||||
|
||||
if (unique.size !== normalized.length) {
|
||||
setError('keybinds', {
|
||||
type: 'manual',
|
||||
message: 'Duplicate keybind combinations are not allowed',
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
const handleOpenSystemSettingsButton = () => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.OpenKeybindSettingsRequest,
|
||||
new OpenKeybindSettingsRequestT()
|
||||
);
|
||||
};
|
||||
|
||||
useRPCPacket(
|
||||
RpcMessage.KeybindResponse,
|
||||
({ keybind, defaultKeybinds, support }: KeybindResponseT) => {
|
||||
setSupport(support);
|
||||
if (!keybind) return;
|
||||
|
||||
const mappedDefaults = defaultKeybinds.map((kb) => ({
|
||||
id: kb.keybindId,
|
||||
name: kb.keybindNameId?.toString() ?? '',
|
||||
binding: kb.keybindValue?.toString().split('+') ?? [],
|
||||
delay: kb.keybindDelay,
|
||||
}));
|
||||
|
||||
setDefaultKeybindsState({ keybinds: mappedDefaults });
|
||||
reset({ keybinds: mappedDefaults });
|
||||
|
||||
const mapped = keybind.map((kb) => ({
|
||||
id: kb.keybindId,
|
||||
name: kb.keybindNameId?.toString() ?? '',
|
||||
binding: kb.keybindValue?.toString().split('+') ?? [],
|
||||
delay: kb.keybindDelay,
|
||||
}));
|
||||
|
||||
mapped.forEach((keybind, index) => {
|
||||
setValue(`keybinds.${index}.binding`, keybind.binding);
|
||||
setValue(`keybinds.${index}.delay`, keybind.delay);
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
const handleOpenRecorderModal = (index: number) => {
|
||||
currentIndex.current = index;
|
||||
setIsOpen(true);
|
||||
};
|
||||
|
||||
const onClose = () => {
|
||||
if (currentIndex.current != null) {
|
||||
resetField(`keybinds.${currentIndex.current}.binding`);
|
||||
}
|
||||
setIsOpen(false);
|
||||
};
|
||||
|
||||
// Captured so the modal's callbacks keep the index they were opened with
|
||||
const editedIndex = currentIndex.current;
|
||||
|
||||
const createKeybindRows = (): ReactNode => {
|
||||
return fields.map((field, index) => {
|
||||
return (
|
||||
<div className="keybind-row" key={index}>
|
||||
<KeybindsRow
|
||||
id={field.name}
|
||||
control={control}
|
||||
index={index}
|
||||
openKeybindRecorderModal={handleOpenRecorderModal}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
sendRPCPacket(RpcMessage.KeybindRequest, new KeybindRequestT());
|
||||
}, []);
|
||||
|
||||
// Only the recorder modal submits, so a delay change would otherwise never reach the server
|
||||
useEffect(() => {
|
||||
const subscription = watch((_, { name, type }) => {
|
||||
if (type === 'change' && name?.endsWith('.delay')) onSubmit();
|
||||
});
|
||||
return () => subscription.unsubscribe();
|
||||
}, [watch]);
|
||||
|
||||
return (
|
||||
<SettingsPageLayout>
|
||||
<SettingsPagePaneLayout icon={<WrenchIcon />} id="keybinds">
|
||||
<div className="flex flex-col gap-2">
|
||||
<Typography variant="main-title" id="settings-keybinds" />
|
||||
<div className="flex flex-col pt-2 pb-4">
|
||||
{l10n
|
||||
.getString('settings-keybinds-description')
|
||||
.split('\n')
|
||||
.map((line, i) => (
|
||||
<Typography key={i}>{line}</Typography>
|
||||
))}
|
||||
</div>
|
||||
{support === KeybindSupport.UNSUPPORTED && (
|
||||
<Typography id="settings-keybinds-unsupported-description" />
|
||||
)}
|
||||
{support === KeybindSupport.SYSTEM_MANAGED && (
|
||||
<div className="flex flex-col gap-4">
|
||||
<Typography id="settings-keybinds-system-managed-description" />
|
||||
<div>
|
||||
<Button
|
||||
id="settings-keybinds-open-system-settings-button"
|
||||
className="flex flex-col"
|
||||
onClick={handleOpenSystemSettingsButton}
|
||||
variant="primary"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{support === KeybindSupport.APP_MANAGED && (
|
||||
<>
|
||||
<FormProvider {...methods}>
|
||||
<div className="keybind-settings">
|
||||
<Typography
|
||||
id="keybind_config-keybind_name"
|
||||
variant="section-title"
|
||||
/>
|
||||
<Typography
|
||||
id="keybind_config-keybind_value"
|
||||
variant="section-title"
|
||||
/>
|
||||
<Typography
|
||||
id="keybind_config-keybind_delay"
|
||||
variant="section-title"
|
||||
/>
|
||||
{createKeybindRows()}
|
||||
</div>
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
id="settings-keybinds_reset-all-button"
|
||||
onClick={() => {
|
||||
reset(defaultKeybindsState);
|
||||
handleSubmit(onSubmit)();
|
||||
}}
|
||||
variant="primary"
|
||||
/>
|
||||
</div>
|
||||
{editedIndex != null && (
|
||||
<KeybindRecorderModal
|
||||
id={fields[editedIndex].name}
|
||||
control={control}
|
||||
name={`keybinds.${editedIndex}.binding`}
|
||||
isVisisble={isOpen}
|
||||
onClose={onClose}
|
||||
onUnbind={() =>
|
||||
setValue(`keybinds.${editedIndex}.binding`, [])
|
||||
}
|
||||
onSubmit={onSubmit}
|
||||
/>
|
||||
)}
|
||||
</FormProvider>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</SettingsPagePaneLayout>
|
||||
</SettingsPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -183,6 +183,7 @@ const config = {
|
||||
lg: '1300px',
|
||||
xl: '1600px',
|
||||
tall: { raw: '(min-height: 860px)' },
|
||||
'keybinds-small': { raw: 'not (min-width: 1230px)' },
|
||||
},
|
||||
extend: {
|
||||
colors: {
|
||||
@@ -236,10 +237,10 @@ const config = {
|
||||
},
|
||||
},
|
||||
'timer-tick': {
|
||||
"0%, 40%": {
|
||||
'0%, 40%': {
|
||||
transform: 'scale(1)',
|
||||
},
|
||||
"20%": {
|
||||
'20%': {
|
||||
transform: 'scale(1.3)',
|
||||
},
|
||||
},
|
||||
@@ -294,7 +295,7 @@ const config = {
|
||||
light: `linear-gradient(135deg, ${colors['light-accent'][100]} 50%, ${colors['light-background'][700]} 50% 100%)`,
|
||||
'trans-flag': `linear-gradient(135deg, ${colors['trans-blue'][800]} 40%, ${colors['trans-blue'][700]} 40% 70%, ${colors['trans-blue'][600]} 70% 100%)`,
|
||||
'asexual-flag': `linear-gradient(135deg, ${colors['asexual'][100]} 30%, ${colors['asexual'][200]} 30% 50%, ${colors['asexual'][300]} 50% 70%, ${colors['asexual'][400]} 70% 100%)`,
|
||||
'snep': `linear-gradient(135deg, ${colors['snep'][100]} 40%, ${colors['snep'][200]} 40% 70%, ${colors['snep'][300]} 70% 100%)`,
|
||||
snep: `linear-gradient(135deg, ${colors['snep'][100]} 40%, ${colors['snep'][200]} 40% 70%, ${colors['snep'][300]} 70% 100%)`,
|
||||
},
|
||||
animation: {
|
||||
'spin-ccw': 'spin-ccw 1s linear infinite',
|
||||
|
||||
@@ -16,6 +16,22 @@ import kotlinx.serialization.json.JsonNull
|
||||
import kotlinx.serialization.json.JsonPrimitive
|
||||
import kotlinx.serialization.json.jsonPrimitive
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import solarxr_protocol.rpc.KeybindId
|
||||
|
||||
object KeybindIdSerializer : KSerializer<KeybindId> {
|
||||
override val descriptor = PrimitiveSerialDescriptor("KeybindId", PrimitiveKind.STRING)
|
||||
|
||||
override fun serialize(encoder: Encoder, value: KeybindId) {
|
||||
(encoder as JsonEncoder).encodeJsonElement(JsonPrimitive(value.name))
|
||||
}
|
||||
|
||||
override fun deserialize(decoder: Decoder): KeybindId {
|
||||
val element = (decoder as JsonDecoder).decodeJsonElement()
|
||||
// Falling back to a real keybind would silently turn an unknown entry into a duplicate
|
||||
return KeybindId.entries.firstOrNull { it.name == element.jsonPrimitive.content }
|
||||
?: KeybindId.NONE
|
||||
}
|
||||
}
|
||||
|
||||
object BodyPartSerializer : KSerializer<BodyPart?> {
|
||||
@OptIn(ExperimentalSerializationApi::class)
|
||||
|
||||
@@ -16,6 +16,7 @@ import kotlinx.serialization.json.jsonPrimitive
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import solarxr_protocol.rpc.ArmsResetMode
|
||||
import solarxr_protocol.rpc.FilteringType
|
||||
import solarxr_protocol.rpc.KeybindId
|
||||
|
||||
private const val SETTINGS_CONFIG_VERSION = 2
|
||||
|
||||
@@ -91,6 +92,24 @@ data class ResetsConfig(
|
||||
val lastMountingMethod: MountingMethods = MountingMethods.AUTOMATIC, // TODO
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class KeybindConfig(
|
||||
@Serializable(with = KeybindIdSerializer::class)
|
||||
val id: KeybindId,
|
||||
/** Key combination, keys joined with '+' (e.g. "CTRL+ALT+SHIFT+Y") */
|
||||
val binding: String,
|
||||
/** Delay in seconds before the keybind triggers */
|
||||
val delay: Float = 0f,
|
||||
)
|
||||
|
||||
fun defaultKeybinds(): List<KeybindConfig> = listOf(
|
||||
KeybindConfig(KeybindId.FULL_RESET, "CTRL+ALT+SHIFT+Y"),
|
||||
KeybindConfig(KeybindId.YAW_RESET, "CTRL+ALT+SHIFT+U"),
|
||||
KeybindConfig(KeybindId.MOUNTING_RESET, "CTRL+ALT+SHIFT+I"),
|
||||
KeybindConfig(KeybindId.FEET_MOUNTING_RESET, "CTRL+ALT+SHIFT+P"),
|
||||
KeybindConfig(KeybindId.PAUSE_TRACKING, "CTRL+ALT+SHIFT+O"),
|
||||
)
|
||||
|
||||
// Used in SkeletonConfig
|
||||
@Serializable
|
||||
data class SkeletonTogglesConfig(
|
||||
@@ -170,6 +189,7 @@ data class SettingsConfigState(
|
||||
val skeletonConfig: SkeletonConfig = SkeletonConfig(),
|
||||
val vrcOscConfig: VRCOSCConfig = VRCOSCConfig(),
|
||||
val vmcConfig: VMCConfig = VMCConfig(),
|
||||
val keybinds: List<KeybindConfig> = defaultKeybinds(),
|
||||
)
|
||||
|
||||
private fun migrateSettingsConfig(json: JsonObject): JsonObject {
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
package dev.slimevr
|
||||
|
||||
import solarxr_protocol.rpc.KeybindSupport
|
||||
|
||||
data class FeatureFlags(
|
||||
var steam: Boolean = false,
|
||||
var skipCheckUdev: Boolean = false,
|
||||
var udevRulesInstalled: Boolean? = null,
|
||||
var keybindSupport: KeybindSupport = KeybindSupport.UNSUPPORTED,
|
||||
)
|
||||
@@ -24,6 +24,7 @@ object AppLogger {
|
||||
val oscQuery = logger("OSCQuery")
|
||||
val install = logger("Install")
|
||||
val resets = logger("Resets")
|
||||
val keybind = logger("Keybind")
|
||||
val coroutines = noCoLogger("Coroutines")
|
||||
|
||||
init {
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
package dev.slimevr.solarxr
|
||||
|
||||
import dev.slimevr.config.KeybindConfig
|
||||
import dev.slimevr.config.Settings
|
||||
import dev.slimevr.config.SettingsActions
|
||||
import dev.slimevr.config.defaultKeybinds
|
||||
import solarxr_protocol.rpc.ChangeKeybindRequest
|
||||
import solarxr_protocol.rpc.Keybind
|
||||
import solarxr_protocol.rpc.KeybindId
|
||||
import solarxr_protocol.rpc.KeybindRequest
|
||||
import solarxr_protocol.rpc.KeybindResponse
|
||||
|
||||
private fun keybindNameId(id: KeybindId): String = id.name.lowercase().replace('_', '-')
|
||||
|
||||
private fun keybindConfigToProto(config: KeybindConfig): Keybind = Keybind(
|
||||
keybindId = config.id,
|
||||
keybindNameId = keybindNameId(config.id),
|
||||
keybindValue = config.binding,
|
||||
keybindDelay = config.delay,
|
||||
)
|
||||
|
||||
class KeybindsBehaviour(
|
||||
private val settings: Settings,
|
||||
) : SolarXRBridgeBehaviour {
|
||||
override fun observe(receiver: SolarXRBridge) {
|
||||
receiver.rpcDispatcher.on<KeybindRequest> {
|
||||
val keybinds = settings.context.state.value.data.keybinds
|
||||
receiver.sendRpc(
|
||||
KeybindResponse(
|
||||
keybind = keybinds.map { keybindConfigToProto(it) },
|
||||
defaultKeybinds = defaultKeybinds().map { keybindConfigToProto(it) },
|
||||
support = receiver.appContext.featureFlags.keybindSupport,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
receiver.rpcDispatcher.on<ChangeKeybindRequest> { req ->
|
||||
val keybind = req.keybind ?: return@on
|
||||
val id = keybind.keybindId?.takeUnless { it == KeybindId.NONE } ?: return@on
|
||||
settings.context.dispatch(
|
||||
SettingsActions.Update {
|
||||
copy(
|
||||
keybinds = keybinds.map {
|
||||
if (it.id == id) {
|
||||
it.copy(
|
||||
binding = keybind.keybindValue ?: it.binding,
|
||||
delay = keybind.keybindDelay ?: 0f,
|
||||
)
|
||||
} else {
|
||||
it
|
||||
}
|
||||
},
|
||||
)
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -86,6 +86,7 @@ class SolarXRBridge(
|
||||
add(KnownTrackersBehaviour(appContext.config.settings))
|
||||
add(BvhBehaviour(appContext.bvhManager))
|
||||
add(InstalledInfoBehaviour())
|
||||
add(KeybindsBehaviour(appContext.config.settings))
|
||||
add(SessionCalibrationBehaviour(appContext.resetsManager))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package dev.slimevr.tracker
|
||||
|
||||
import dev.slimevr.AppLogger
|
||||
import dev.slimevr.skeleton.SkeletonActions
|
||||
import dev.slimevr.util.safeLaunch
|
||||
import io.github.axisangles.ktmath.Quaternion
|
||||
@@ -7,7 +8,6 @@ import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||
import kotlinx.coroutines.flow.distinctUntilChangedBy
|
||||
import kotlinx.coroutines.flow.filter
|
||||
import kotlinx.coroutines.flow.flatMapLatest
|
||||
import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.flow.map
|
||||
@@ -196,7 +196,7 @@ class TrackerTPSBehaviour : TrackerBehaviour {
|
||||
receiver.context.dispatch(TrackerActions.Update { copy(tps = tps.toUShort()) })
|
||||
mark = TimeSource.Monotonic.markNow()
|
||||
} catch (e: Exception) {
|
||||
dev.slimevr.AppLogger.coroutines.error(e, "Error in TrackerTPSBehaviour")
|
||||
AppLogger.coroutines.error(e, "Error in TrackerTPSBehaviour")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,6 +88,10 @@ dependencies {
|
||||
implementation("org.hid4java:hid4java:0.8.0")
|
||||
implementation("io.klogging:klogging:0.11.7")
|
||||
|
||||
// Global keybinds: JIntellitype on Windows, dbus xdg-desktop-portal on Linux
|
||||
implementation("com.melloware:jintellitype:1.+")
|
||||
implementation("com.github.HannahPadd:DbusGlobalShortcutsWayland:v0.1.0")
|
||||
|
||||
val ktorVersion = "3.4.1"
|
||||
implementation("io.ktor:ktor-client-core:$ktorVersion")
|
||||
implementation("io.ktor:ktor-client-cio:$ktorVersion")
|
||||
@@ -103,6 +107,8 @@ tasks.shadowJar {
|
||||
exclude(dependency("com.fazecast:jSerialComm:.*"))
|
||||
exclude(dependency("net.java.dev.jna:.*:.*"))
|
||||
exclude(dependency("com.google.flatbuffers:flatbuffers-java:.*"))
|
||||
exclude(dependency("com.melloware:jintellitype:.*"))
|
||||
exclude(dependency("com.github.HannahPadd:DbusGlobalShortcutsWayland:.*"))
|
||||
|
||||
exclude(project(":solarxr-protocol:generated"))
|
||||
}
|
||||
|
||||
@@ -17,6 +17,9 @@ import dev.slimevr.desktop.install.executeShellCommand
|
||||
import dev.slimevr.desktop.install.runInstaller
|
||||
import dev.slimevr.desktop.ipc.createIpcServers
|
||||
import dev.slimevr.desktop.ipc.createSolarXRWebsocketServer
|
||||
import dev.slimevr.desktop.keybind.createDesktopKeybindManager
|
||||
import dev.slimevr.desktop.keybind.isGnome
|
||||
import dev.slimevr.desktop.keybind.resolveGnomeAppId
|
||||
import dev.slimevr.desktop.networkprofile.setupDesktopNetworkProfileChecker
|
||||
import dev.slimevr.desktop.serial.DesktopFirmwareFlasher
|
||||
import dev.slimevr.desktop.serial.createDesktopSerialServer
|
||||
@@ -38,8 +41,12 @@ import dev.slimevr.udp.UdpServer
|
||||
import dev.slimevr.util.safeLaunch
|
||||
import dev.slimevr.vmc.VMCManager
|
||||
import dev.slimevr.vrcosc.VRCOSCManager
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.runBlocking
|
||||
import kotlinx.coroutines.withContext
|
||||
import solarxr_protocol.rpc.KeybindSupport
|
||||
|
||||
fun main(args: Array<String>) = runBlocking<Unit> {
|
||||
contextDebugEnabled = System.getProperty("slimevr.debug.context") == "true" ||
|
||||
@@ -60,6 +67,20 @@ fun main(args: Array<String>) = runBlocking<Unit> {
|
||||
}
|
||||
if (CURRENT_PLATFORM != Platform.LINUX) featureFlags.skipCheckUdev = true
|
||||
|
||||
// Windows registers hotkeys itself, and on GNOME we can rewrite the triggers it stores in dconf.
|
||||
// Other compositors own the bindings, so there the user rebinds from the system settings.
|
||||
featureFlags.keybindSupport = when (CURRENT_PLATFORM) {
|
||||
Platform.WINDOWS -> KeybindSupport.APP_MANAGED
|
||||
|
||||
Platform.LINUX -> if (isGnome() && resolveGnomeAppId() != null) {
|
||||
KeybindSupport.APP_MANAGED
|
||||
} else {
|
||||
KeybindSupport.SYSTEM_MANAGED
|
||||
}
|
||||
|
||||
else -> KeybindSupport.UNSUPPORTED
|
||||
}
|
||||
|
||||
val isInstallDisabled = System.getenv("SLIME_SERVER_DISABLE_INSTALLER")?.toIntOrNull()
|
||||
if (featureFlags.steam && isInstallDisabled != 1) runInstaller()
|
||||
|
||||
@@ -125,16 +146,27 @@ fun main(args: Array<String>) = runBlocking<Unit> {
|
||||
tapDetectionManager = tapDetectionManager,
|
||||
)
|
||||
|
||||
// JVM shutdown hooks fire on SIGINT/SIGTERM but coroutine `finally` blocks do not,
|
||||
// so cancel the root scope on shutdown to let structured concurrency run every cleanup.
|
||||
val rootJob = coroutineContext[Job]!!
|
||||
Runtime.getRuntime().addShutdownHook(
|
||||
Thread {
|
||||
rootJob.cancel()
|
||||
runBlocking { rootJob.join() }
|
||||
},
|
||||
)
|
||||
|
||||
try {
|
||||
appContext.startObserving()
|
||||
|
||||
safeLaunch { createDesktopHIDManager(appContext, this) }
|
||||
safeLaunch { createDesktopKeybindManager(appContext, this) }
|
||||
safeLaunch { createSolarXRWebsocketServer(appContext) }
|
||||
safeLaunch { createIpcServers(appContext) }
|
||||
safeLaunch { setupDesktopNetworkProfileChecker(this, networkProfileManager) }
|
||||
|
||||
awaitCancellation()
|
||||
} finally {
|
||||
appContext.dispose()
|
||||
withContext(NonCancellable) { appContext.dispose() }
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,12 @@
|
||||
package dev.slimevr.desktop.ipc
|
||||
|
||||
import com.google.flatbuffers.FlatBufferBuilder
|
||||
import dev.hannah.portals.PortalManager
|
||||
import dev.slimevr.AppContextProvider
|
||||
import dev.slimevr.AppLogger
|
||||
import dev.slimevr.CURRENT_PLATFORM
|
||||
import dev.slimevr.Platform
|
||||
import dev.slimevr.SLIMEVR_IDENTIFIER
|
||||
import dev.slimevr.VRServerActions
|
||||
import dev.slimevr.desktop.unblockSteamVRDriver
|
||||
import dev.slimevr.fbscodegen.runtime.JvmFlatBufferReader
|
||||
@@ -13,10 +18,13 @@ import dev.slimevr.util.safeLaunch
|
||||
import io.ktor.client.HttpClient
|
||||
import io.ktor.client.engine.cio.CIO
|
||||
import io.ktor.util.moveToByteArray
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.withContext
|
||||
import solarxr_protocol.MessageBundle
|
||||
import solarxr_protocol.rpc.EnableSteamVRDriverRequest
|
||||
import solarxr_protocol.rpc.OpenKeybindSettingsRequest
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
class EnableSteamVRDriverBehaviour : SolarXRBridgeBehaviour {
|
||||
@@ -31,6 +39,21 @@ class EnableSteamVRDriverBehaviour : SolarXRBridgeBehaviour {
|
||||
}
|
||||
}
|
||||
|
||||
class OpenKeybindSettingsBehaviour : SolarXRBridgeBehaviour {
|
||||
override fun observe(receiver: SolarXRBridge) {
|
||||
receiver.rpcDispatcher.on<OpenKeybindSettingsRequest> {
|
||||
if (CURRENT_PLATFORM != Platform.LINUX) return@on
|
||||
receiver.context.scope.safeLaunch {
|
||||
withContext(Dispatchers.IO) {
|
||||
runCatching {
|
||||
PortalManager(SLIMEVR_IDENTIFIER).openGlobalShortcutsSettings()
|
||||
}.onFailure { AppLogger.keybind.error(it, "Failed to open global shortcuts settings") }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun handleSolarXRBridge(
|
||||
appContext: AppContextProvider,
|
||||
messages: Flow<ByteArray>,
|
||||
@@ -43,6 +66,7 @@ suspend fun handleSolarXRBridge(
|
||||
extraBehaviours = { _ ->
|
||||
buildList {
|
||||
add(EnableSteamVRDriverBehaviour())
|
||||
add(OpenKeybindSettingsBehaviour())
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package dev.slimevr.desktop.keybind
|
||||
|
||||
import dev.slimevr.AppLogger
|
||||
import dev.slimevr.config.KeybindConfig
|
||||
import dev.slimevr.desktop.install.executeShellCommand
|
||||
import java.io.File
|
||||
|
||||
private const val GLOBAL_SHORTCUTS_PATH = "/org/gnome/settings-daemon/global-shortcuts"
|
||||
|
||||
private val MODIFIERS = linkedMapOf(
|
||||
"SHIFT" to "<Shift>",
|
||||
"CTRL" to "<Control>",
|
||||
"ALT" to "<Alt>",
|
||||
"SUPER" to "<Super>",
|
||||
)
|
||||
|
||||
fun isGnome(): Boolean = System.getenv("XDG_CURRENT_DESKTOP")?.uppercase()?.contains("GNOME") == true
|
||||
|
||||
fun resolveGnomeAppId(): String? {
|
||||
val cgroup = runCatching { File("/proc/self/cgroup").readText() }.getOrNull() ?: return null
|
||||
|
||||
val scope = cgroup.lineSequence()
|
||||
.map { line -> line.substringAfterLast('/', "") }
|
||||
.firstOrNull { it.startsWith("app-") && it.endsWith(".scope") }
|
||||
?: return null
|
||||
|
||||
// app-<id>-<instance>.scope, where instance is the pid that launched it
|
||||
return scope
|
||||
.removePrefix("app-")
|
||||
.removeSuffix(".scope")
|
||||
.substringBeforeLast('-')
|
||||
.ifEmpty { null }
|
||||
}
|
||||
|
||||
/** Converts our `CTRL+ALT+SHIFT+Y` form into GTK's `<Shift><Control><Alt>y` form. */
|
||||
private 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 modifiers = parts.filter { it in MODIFIERS }.toSet()
|
||||
return MODIFIERS.filterKeys { it in modifiers }.values.joinToString("") + key.lowercase()
|
||||
}
|
||||
|
||||
private fun escapeGVariant(value: String): String = value.replace("\\", "\\\\").replace("'", "\\'")
|
||||
|
||||
private fun buildGnomeShortcutsVariant(keybinds: List<KeybindConfig>): String = keybinds
|
||||
.mapNotNull { keybind ->
|
||||
val accelerator = toGnomeAccelerator(keybind.binding) ?: return@mapNotNull null
|
||||
"('${escapeGVariant(keybind.id.name)}', {'shortcuts': <['${escapeGVariant(accelerator)}']>, " +
|
||||
"'description': <'${escapeGVariant(keybindLabel(keybind.id))}'>})"
|
||||
}
|
||||
.joinToString(", ", prefix = "[", postfix = "]")
|
||||
|
||||
suspend fun gnomeShortcutsExist(appId: String): Boolean {
|
||||
val (exitCode, output) = executeShellCommand("dconf", "read", "$GLOBAL_SHORTCUTS_PATH/$appId/shortcuts") ?: return false
|
||||
return exitCode == 0 && output.isNotBlank()
|
||||
}
|
||||
|
||||
suspend fun writeGnomeShortcuts(appId: String, keybinds: List<KeybindConfig>): Boolean {
|
||||
val bound = keybinds.filter { toGnomeAccelerator(it.binding) != null }
|
||||
if (bound.isEmpty()) return false
|
||||
|
||||
val variant = buildGnomeShortcutsVariant(bound)
|
||||
val (exitCode, output) = executeShellCommand("dconf", "write", "$GLOBAL_SHORTCUTS_PATH/$appId/shortcuts", variant)
|
||||
?: return false
|
||||
|
||||
if (exitCode != 0) {
|
||||
AppLogger.keybind.warn("Failed to write GNOME shortcuts for $appId: ${output.trim()}")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
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.AppLogger
|
||||
import dev.slimevr.CURRENT_PLATFORM
|
||||
import dev.slimevr.Platform
|
||||
import dev.slimevr.SLIMEVR_IDENTIFIER
|
||||
import dev.slimevr.config.KeybindConfig
|
||||
import dev.slimevr.skeleton.SkeletonActions
|
||||
import dev.slimevr.util.safeLaunch
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.flow.Flow
|
||||
import kotlinx.coroutines.flow.distinctUntilChangedBy
|
||||
import kotlinx.coroutines.flow.launchIn
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.onEach
|
||||
import solarxr_protocol.datatypes.BodyPart
|
||||
import solarxr_protocol.rpc.KeybindId
|
||||
import solarxr_protocol.rpc.ResetType
|
||||
|
||||
private const val KEYBIND_SOURCE = "Keybind"
|
||||
|
||||
private val FEET_BODY_PARTS = listOf(BodyPart.LEFT_FOOT, BodyPart.RIGHT_FOOT)
|
||||
|
||||
private fun currentKeybinds(appContext: AppContextProvider): List<KeybindConfig> = appContext.config.settings.context.state.value.data.keybinds
|
||||
|
||||
private fun bindingsFlow(appContext: AppContextProvider): Flow<List<KeybindConfig>> = appContext.config.settings.context.state
|
||||
.map { it.data.keybinds }
|
||||
.distinctUntilChangedBy { keybinds -> keybinds.map { it.id to it.binding } }
|
||||
|
||||
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 }
|
||||
|
||||
private fun triggerKeybind(appContext: AppContextProvider, scope: CoroutineScope, id: KeybindId) {
|
||||
val delaySeconds = currentKeybinds(appContext).find { it.id == id }?.delay ?: 0f
|
||||
scope.safeLaunch {
|
||||
when (id) {
|
||||
KeybindId.FULL_RESET ->
|
||||
appContext.resetsManager.scheduleReset(KEYBIND_SOURCE, ResetType.FULL, delaySeconds)
|
||||
|
||||
KeybindId.YAW_RESET ->
|
||||
appContext.resetsManager.scheduleReset(KEYBIND_SOURCE, ResetType.YAW, delaySeconds)
|
||||
|
||||
KeybindId.MOUNTING_RESET ->
|
||||
appContext.resetsManager.scheduleReset(KEYBIND_SOURCE, ResetType.MOUNTING, delaySeconds)
|
||||
|
||||
KeybindId.FEET_MOUNTING_RESET ->
|
||||
appContext.resetsManager.scheduleReset(KEYBIND_SOURCE, ResetType.MOUNTING, delaySeconds, FEET_BODY_PARTS)
|
||||
|
||||
KeybindId.PAUSE_TRACKING -> {
|
||||
if (delaySeconds > 0f) delay((delaySeconds * 1000).toLong())
|
||||
val skeleton = appContext.skeleton.context
|
||||
skeleton.dispatch(SkeletonActions.PauseTracking(!skeleton.state.value.paused))
|
||||
}
|
||||
|
||||
KeybindId.NONE -> Unit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
suspend fun createDesktopKeybindManager(appContext: AppContextProvider, scope: CoroutineScope) {
|
||||
when (CURRENT_PLATFORM) {
|
||||
Platform.WINDOWS -> setupWindowsKeybinds(appContext, scope)
|
||||
Platform.LINUX -> setupLinuxKeybinds(appContext, scope)
|
||||
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 { triggerKeybind(appContext, scope, it) }
|
||||
}
|
||||
|
||||
var registered: List<KeybindConfig> = emptyList()
|
||||
bindingsFlow(appContext).onEach { keybinds ->
|
||||
registered.forEach { runCatching { instance.unregisterHotKey(it.id.value.toInt()) } }
|
||||
keybinds.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 = keybinds
|
||||
}.launchIn(scope)
|
||||
}
|
||||
|
||||
private suspend fun setupLinuxKeybinds(appContext: AppContextProvider, scope: CoroutineScope) {
|
||||
var handler: GlobalShortcutsHandler? = null
|
||||
|
||||
// Closing a handler disconnects its dbus connection, so every session gets its own manager
|
||||
suspend fun bind(keybinds: List<KeybindConfig>) {
|
||||
runCatching { handler?.close() }
|
||||
val shortcuts = keybinds.map { keybind ->
|
||||
ShortcutTuple(keybind.id.name, Shortcut(keybindLabel(keybind.id), keybind.binding).shortcut)
|
||||
}.toMutableList()
|
||||
|
||||
handler = runCatching {
|
||||
PortalManager(SLIMEVR_IDENTIFIER).globalShortcutsRequest(shortcuts).apply {
|
||||
onShortcutActivated = { shortcutId ->
|
||||
KeybindId.entries.firstOrNull { it.name == shortcutId }?.let { triggerKeybind(appContext, scope, it) }
|
||||
}
|
||||
}
|
||||
}.onFailure {
|
||||
AppLogger.keybind.error(it, "Failed to register global shortcuts, keybinds will not work")
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
val gnomeAppId = if (isGnome()) resolveGnomeAppId() else null
|
||||
if (gnomeAppId == null) {
|
||||
// The compositor owns the triggers and we have no way to change them, so bind once and
|
||||
// leave it alone. The user rebinds from their system settings instead.
|
||||
bind(currentKeybinds(appContext))
|
||||
} else {
|
||||
// GNOME keeps the triggers in dconf and only reads them when a session is created, so a
|
||||
// change means rewriting dconf and starting a new session. Its stored values also win over
|
||||
// the ones we pass, so push the config on startup too or the gui would disagree with what
|
||||
// actually fires. The exception is a first run, where the portal seeds them and prompts.
|
||||
val needsSeeding = !gnomeShortcutsExist(gnomeAppId)
|
||||
|
||||
var isInitialBind = true
|
||||
bindingsFlow(appContext).onEach { keybinds ->
|
||||
if (!(isInitialBind && needsSeeding)) {
|
||||
writeGnomeShortcuts(gnomeAppId, keybinds)
|
||||
}
|
||||
bind(keybinds)
|
||||
isInitialBind = false
|
||||
}.launchIn(scope)
|
||||
}
|
||||
|
||||
scope.safeLaunch {
|
||||
try {
|
||||
awaitCancellation()
|
||||
} finally {
|
||||
runCatching { handler?.close() }
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
Submodule solarxr-protocol updated: 2f00c44f44...c412241496.
Reference in new issue
Block a user