Compare commits

..
Author SHA1 Message Date
loucass003 e9f13e90a2 Fix lint 2026-04-16 16:12:35 +02:00
loucass003 518cdd3e39 Spotless 2026-04-16 16:05:40 +02:00
HannahPadd 1962c164c7 Keybinds mappings + Linux 2026-04-16 16:03:05 +02:00
42 changed files with 1378 additions and 758 deletions

No files matched your search

+1 -1
View File
@@ -15,7 +15,7 @@
runtimeLibs = pkgs: (with pkgs; [
jdk17
alsa-lib libpulseaudio at-spi2-atk at-spi2-core cairo cups dbus expat
alsa-lib at-spi2-atk at-spi2-core cairo cups dbus expat
gdk-pixbuf glib gtk3 libdrm libgbm libglvnd libnotify
libxkbcommon mesa nspr nss pango systemd vulkan-loader
wayland xorg.libX11 xorg.libXcomposite xorg.libXdamage
+1 -3
View File
@@ -8,9 +8,7 @@ program
'--skip-server-if-running',
'gui will not launch the server if it is already running'
)
.allowUnknownOption()
// Allow passing arguments to Electron.
.allowExcessArguments();
.allowUnknownOption();
if (process.platform === "linux") {
const noUdevOption = new Option('--no-udev', 'disable udev warning');
+15 -43
View File
@@ -16,7 +16,6 @@ import open from 'open';
import trayIcon from '../resources/icons/icon.png?asset';
import appleTrayIcon from '../resources/icons/Square30x30Logo.png?asset';
import { readFile, stat } from 'fs/promises';
import { pathToFileURL } from 'node:url';
import { getPlatform, handleIpc, isPortAvailable } from './utils';
import {
findServerJar,
@@ -27,19 +26,17 @@ import {
getServerDataFolder,
getWindowStateFile,
} from './paths';
import { initStores } from './store';
import { stores } from './store';
import { closeLogger, logger } from './logger';
import { writeFileSync } from 'node:fs';
import { spawn } from 'node:child_process';
import { discordPresence } from './presence';
import { options } from './cli';
import { ServerStatusEvent } from 'electron/preload/interface';
import { mkdir, writeFile } from 'node:fs/promises';
import { mkdir } from 'node:fs/promises';
import { MenuItem } from 'electron/main';
type Stores = Awaited<ReturnType<typeof initStores>>;
let stores: Stores;
// Fixes colors looking washed on linux
// Might affect hdr
if (process.platform === 'linux') {
@@ -58,7 +55,6 @@ protocol.registerSchemesAsPrivileged([
secure: true,
supportFetchAPI: true,
corsEnabled: true,
stream: true,
},
},
]);
@@ -192,6 +188,10 @@ handleIpc(IPC_CHANNELS.GET_FOLDER, (e, folder) => {
}
});
const windowStateFile = await readFile(getWindowStateFile(), {
encoding: 'utf-8',
}).catch(() => null);
const defaultWindowState: {
width: number;
height: number;
@@ -203,15 +203,7 @@ const defaultWindowState: {
x: undefined,
y: undefined,
};
const windowState = await readFile(getWindowStateFile(), {
encoding: 'utf-8',
})
.then(data => JSON.parse(data))
.catch(() => {
logger.error('Failed to load window state, using defaults');
return defaultWindowState;
});
const windowState = windowStateFile ? JSON.parse(windowStateFile) : defaultWindowState;
const MIN_WIDTH = 393;
const MIN_HEIGHT = 667;
@@ -244,7 +236,7 @@ function validateWindowState(state: typeof defaultWindowState) {
const saveWindowState = async () => {
await mkdir(dirname(getWindowStateFile()), { recursive: true });
await writeFile(getWindowStateFile(), JSON.stringify(windowState), { encoding: 'utf-8' });
writeFileSync(getWindowStateFile(), JSON.stringify(windowState));
};
function createWindow() {
@@ -459,36 +451,16 @@ const spawnServer = async () => {
};
};
const createFolders = async () => {
await mkdir(getServerDataFolder(), { recursive: true });
await mkdir(getGuiDataFolder(), { recursive: true });
}
let isQuitting = false;
app.whenReady().then(async () => {
// Register protocol handler for app:// scheme to handle assets with leading slashes
protocol.handle('app', (request) => {
const { pathname } = new URL(request.url);
const filePath = path.normalize(join(__dirname, '../renderer', pathname));
return net.fetch(pathToFileURL(filePath).toString(), { headers: request.headers });
const url = request.url.slice('app://'.length);
const filePath = path.normalize(join(__dirname, '../renderer', url));
return net.fetch('file://' + filePath);
});
try {
await createFolders();
} catch (err) {
logger.error(err, 'Failed to initialize stores');
dialog.showErrorBox(
'SlimeVR',
'Failed to initialize application storage. Please make sure the application has write permissions to its data folder.'
);
app.quit();
return;
}
stores = await initStores();
checkEnvironmentVariables();
const server = await spawnServer();
@@ -507,8 +479,8 @@ app.whenReady().then(async () => {
logger.info('App quitting, saving...');
server?.close();
await server?.waitForExit();
await stores.settings.save();
await stores.cache.save();
stores.settings.save();
stores.cache.save();
discordPresence.destroy();
await saveWindowState();
await closeLogger();
+20 -23
View File
@@ -1,4 +1,4 @@
import { access, mkdir, readFile, writeFile } from "fs/promises";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
import { dirname, join } from "path";
import { logger } from "./logger";
import { getGuiDataFolder } from "./paths";
@@ -10,28 +10,25 @@ export class CustomStore {
private filePath: string;
private debounceMs: number;
private constructor(filePath: string, debounceMs: number = 2000) {
constructor(filePath: string, debounceMs: number = 2000) {
this.filePath = filePath;
this.debounceMs = debounceMs;
this.load();
}
static async create(filePath: string, debounceMs: number = 2000): Promise<CustomStore> {
const store = new CustomStore(filePath, debounceMs);
await store.load();
return store;
}
private async load(): Promise<void> {
private load() {
try {
await access(this.filePath);
const raw = await readFile(this.filePath, 'utf-8');
this.data = JSON.parse(raw);
} catch {
if (existsSync(this.filePath)) {
const raw = readFileSync(this.filePath, 'utf-8');
this.data = JSON.parse(raw);
}
} catch (err) {
logger.error(err, `Failed to load store at ${this.filePath}`);
this.data = {};
logger.warn(`No existing store found at ${this.filePath}, starting with empty store.`);
}
}
/** Set a key and trigger the debounced auto-save */
set(key: string, value: unknown) {
this.data[key] = value;
this.triggerAutoSave();
@@ -57,12 +54,14 @@ export class CustomStore {
}, this.debounceMs);
}
async save(): Promise<boolean> {
save(): boolean {
try {
if (this.saveTimeout) clearTimeout(this.saveTimeout);
await mkdir(dirname(this.filePath), { recursive: true });
await writeFile(this.filePath, JSON.stringify(this.data, null, 2), 'utf-8');
const dir = dirname(this.filePath);
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
writeFileSync(this.filePath, JSON.stringify(this.data, null, 2), 'utf-8');
return true;
} catch (err) {
logger.error(err, 'Save failed', this.filePath);
@@ -71,9 +70,7 @@ export class CustomStore {
}
}
export async function initStores() {
return {
settings: await CustomStore.create(join(getGuiDataFolder(), 'gui-settings.dat'), 1000),
cache: await CustomStore.create(join(getGuiDataFolder(), 'gui-cache.dat'), 100),
};
}
export const stores = {
settings: new CustomStore(join(getGuiDataFolder(), 'gui-settings.dat'), 1000),
cache: new CustomStore(join(getGuiDataFolder(), 'gui-cache.dat'), 100),
};
+1 -1
View File
@@ -68,7 +68,7 @@
"dmg-license": "^1.0.11",
"dotenv": "^16.4.5",
"electron": "^40.3.0",
"electron-builder": "^26.9.0",
"electron-builder": "^26.7.0",
"electron-vite": "^5.0.0",
"@eslint/eslintrc": "^3.3.5",
"@eslint/js": "^9.39.4",
+23
View File
@@ -605,6 +605,29 @@ 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
settings-keybinds = Keybind settings
settings-keybinds_ = ''
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_record-keybind = Click to record
settings-keybinds_now-recording = Recording…
settings-keybinds_reset-button = Reset
settings-keybinds_reset-all-button = Reset all
settings-keybinds-wayland-description = You appear to be using wayland, Please change your shortcuts in your system settings.
settings-keybinds-wayland-open-system-settings-button = Open system settings
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
+2
View File
@@ -56,6 +56,7 @@ import { QuizSlimeSetQuestion } from './components/onboarding/pages/quiz/SlimeSe
import { QuizUsageQuestion } from './components/onboarding/pages/quiz/UsageQuestion';
import { QuizRuntimeQuestion } from './components/onboarding/pages/quiz/RuntimeQuestion';
import { QuizMocapPosQuestion } from './components/onboarding/pages/quiz/MocapPreferencesQuestions';
import { KeybindSettings } from './components/settings/pages/KeybindSettings';
import { ElectronContextC, provideElectron } from './hooks/electron';
import { AppLocalizationProvider } from './i18n/config';
import { openUrl } from './hooks/crossplatform';
@@ -145,6 +146,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,119 @@
import { useState, forwardRef, useRef } from 'react';
import { Typography } from './Typography';
import classNames from 'classnames';
import { useFormContext } from 'react-hook-form';
const excludedKeys = [' ', 'SPACE', 'META'];
const maxKeybindLength = 4;
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 key = e.key.toUpperCase();
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,88 @@
import { Typography } from './Typography';
import './KeybindRow.scss';
import { useEffect, useState } from 'react';
import {
Control,
FieldPath,
FieldValues,
UseFormGetValues,
} 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,
getValue,
openKeybindRecorderModal,
}: {
id?: string;
control: Control<T>;
index: number;
getValue: UseFormGetValues<any>;
openKeybindRecorderModal: (index: number) => void;
}) {
const [binding, setBinding] = useState<string[]>();
const { currentLocales } = useLocaleConfig();
const secondsFormat = new Intl.NumberFormat(currentLocales, {
style: 'unit',
unit: 'second',
unitDisplay: 'narrow',
maximumFractionDigits: 2,
});
const handleOpenModal = () => {
openKeybindRecorderModal(index);
};
useEffect(() => {
setBinding(getValue(`keybinds.${index}.binding`));
});
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>
);
}
+44 -42
View File
@@ -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>
)}
);
}}
/>
);
}
@@ -0,0 +1,13 @@
export function ResetSettingIcon({ size = 24 }: { size?: number }) {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
height={size}
viewBox="0 -960 960 960"
width={size}
fill="#00000"
>
<path d="M520-330v-60h160v60H520Zm60 210v-50h-60v-60h60v-50h60v160h-60Zm100-50v-60h160v60H680Zm40-110v-160h60v50h60v60h-60v50h-60Zm111-280h-83q-26-88-99-144t-169-56q-117 0-198.5 81.5T200-480q0 72 32.5 132t87.5 98v-110h80v240H160v-80h94q-62-50-98-122.5T120-480q0-75 28.5-140.5t77-114q48.5-48.5 114-77T480-840q129 0 226.5 79.5T831-560Z" />
</svg>
);
}
@@ -4,21 +4,19 @@ import { BaseModal } from '@/components/commons/BaseModal';
import { CheckboxInternal } from '@/components/commons/Checkbox';
import { Typography } from '@/components/commons/Typography';
import { useElectron } from '@/hooks/electron';
import { useWebsocketAPI } from '@/hooks/websocket-api';
import { RpcMessage, InstalledInfoResponseT } from 'solarxr-protocol';
import { useConfig } from '@/hooks/config';
import { useLocalization } from '@fluent/react';
import { useAppContext } from '@/hooks/app';
export function UdevRulesModal() {
const { config, setConfig } = useConfig();
const { useRPCPacket, sendRPCPacket } = useWebsocketAPI();
const electron = useElectron();
const [udevContent, setUdevContent] = useState('');
const [isUdevInstalledResponse, setIsUdevInstalledResponse] = useState(true);
const [showUdevWarning, setShowUdevWarning] = useState(false);
const [dontShowThisSession, setDontShowThisSession] = useState(false);
const [dontShowAgain, setDontShowAgain] = useState(false);
const { l10n } = useLocalization();
const { installInfo } = useAppContext();
const handleUdevContent = async () => {
if (electron.isElectron) {
@@ -38,28 +36,14 @@ export function UdevRulesModal() {
if (!config) throw 'Invalid state!';
if (electron.isElectron) {
const isLinux = electron.data().os.type === 'linux';
const udevMissing = !isUdevInstalledResponse;
const udevMissing = !installInfo?.isUdevInstalled;
const notHiddenGlobally = !config.dontShowUdevModal;
const notHiddenThisSession = !dontShowThisSession;
const shouldShow =
isLinux && udevMissing && notHiddenGlobally && notHiddenThisSession;
setShowUdevWarning(shouldShow);
}
}, [config, isUdevInstalledResponse, dontShowThisSession]);
useEffect(() => {
sendRPCPacket(
RpcMessage.InstalledInfoRequest,
new InstalledInfoResponseT()
);
}, []);
useRPCPacket(
RpcMessage.InstalledInfoResponse,
({ isUdevInstalled }: InstalledInfoResponseT) => {
setIsUdevInstalledResponse(isUdevInstalled);
}
);
}, [config, dontShowThisSession]);
const handleModalClose = () => {
if (!config) throw 'Invalid State!';
@@ -72,7 +56,7 @@ export function UdevRulesModal() {
};
return (
<BaseModal isOpen={showUdevWarning} appendClasses={'w-full max-w-2xl'}>
<BaseModal isOpen={showUdevWarning} appendClasses="w-full max-w-2xl">
<div className="flex w-full h-full flex-col gap-4">
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-2">
@@ -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' },
@@ -73,6 +73,13 @@ export function SettingsSidebar() {
scrollTo="gestureControl"
id="settings-sidebar-gesture_control"
/>
{
<SettingsLink
to="/settings/keybinds"
scrollTo="keybinds"
id="settings-sidebar-keybinds"
/>
}
</div>
</div>
<div className="flex flex-col gap-3">
@@ -1,5 +1,5 @@
import { Localized, useLocalization } from '@fluent/react';
import { useEffect, useRef, useState } from 'react';
import { useEffect, useState } from 'react';
import { DefaultValues, useForm } from 'react-hook-form';
import {
ChangeSettingsRequestT,
@@ -180,13 +180,6 @@ export function GeneralSettings() {
const { config } = useConfig();
const { currentLocales } = useLocaleConfig();
const blockHandsWarning = useRef(false);
// If not null, warning will be shown, and showHandsWarning will
// hold which hands should be toggled ([leftHand, rightHand])
const [showHandsWarning, setShowHandsWarning] = useState<
[boolean, boolean] | null
>(null);
const percentageFormat = new Intl.NumberFormat(currentLocales, {
style: 'percent',
maximumFractionDigits: 0,
@@ -207,11 +200,15 @@ export function GeneralSettings() {
});
const {
trackers: { automaticTrackerToggle },
trackers: {
automaticTrackerToggle,
leftHand: steamVrLeftHand,
rightHand: steamVrRightHand,
},
} = watch();
const onSubmit = (values: SettingsForm) => {
const settingsReq = new ChangeSettingsRequestT();
const settings = new ChangeSettingsRequestT();
if (values.trackers) {
const trackers = new SteamVRTrackersSettingT();
@@ -229,29 +226,8 @@ export function GeneralSettings() {
trackers.leftHand = values.trackers.leftHand;
trackers.rightHand = values.trackers.rightHand;
if (
!blockHandsWarning.current &&
!showHandsWarning &&
!settings.steamVrTrackers?.leftHand &&
!settings.steamVrTrackers?.rightHand &&
(trackers.leftHand || trackers.rightHand)
) {
// We have just toggled on one of the hand trackers, show the user a warning
setShowHandsWarning([trackers.leftHand, trackers.rightHand]);
trackers.leftHand = false;
trackers.rightHand = false;
} else if (
blockHandsWarning.current &&
!trackers.leftHand &&
!trackers.rightHand
) {
// Both hand trackers have just been disabled, make sure the warning shows up
// again next time the user toggles one back on
blockHandsWarning.current = false;
}
trackers.automaticTrackerToggle = values.trackers.automaticTrackerToggle;
settingsReq.steamVrTrackers = trackers;
settings.steamVrTrackers = trackers;
}
const modelSettings = new ModelSettingsT();
@@ -296,7 +272,7 @@ export function GeneralSettings() {
modelSettings.legTweaks = legTweaks;
}
settingsReq.modelSettings = modelSettings;
settings.modelSettings = modelSettings;
const tapDetection = new TapDetectionSettingsT();
tapDetection.fullResetDelay = values.tapDetection.fullResetDelay;
@@ -312,30 +288,28 @@ export function GeneralSettings() {
tapDetection.numberTrackersOverThreshold =
values.tapDetection.numberTrackersOverThreshold;
tapDetection.setupMode = false;
settingsReq.tapDetectionSettings = tapDetection;
settings.tapDetectionSettings = tapDetection;
const filtering = new FilteringSettingsT();
filtering.type = values.filtering.type;
filtering.amount = values.filtering.amount;
settingsReq.filtering = filtering;
settings.filtering = filtering;
settingsReq.stayAligned = serializeStayAlignedSettings(values.stayAligned);
settings.stayAligned = serializeStayAlignedSettings(values.stayAligned);
const hidSettings = new HIDSettingsT();
hidSettings.trackersOverHid = values.hidSettings.trackersOverHID;
settingsReq.hidSettings = hidSettings;
settings.hidSettings = hidSettings;
if (values.resetsSettings) {
settingsReq.resetsSettings = loadResetSettings(values.resetsSettings);
settings.resetsSettings = loadResetSettings(values.resetsSettings);
}
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settingsReq);
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settings);
};
useEffect(() => {
const subscription = watch((value, { type }) => {
if (type === 'change') handleSubmit(onSubmit)();
});
const subscription = watch(() => handleSubmit(onSubmit)());
return () => subscription.unsubscribe();
}, []);
@@ -353,11 +327,10 @@ export function GeneralSettings() {
if (settings.steamVrTrackers) {
formData.trackers = settings.steamVrTrackers;
if (
!blockHandsWarning.current &&
(settings.steamVrTrackers.leftHand ||
settings.steamVrTrackers.rightHand)
settings.steamVrTrackers.leftHand ||
settings.steamVrTrackers.rightHand
) {
blockHandsWarning.current = true;
setHandsWarning(false);
}
}
@@ -449,25 +422,37 @@ export function GeneralSettings() {
reset({ ...getValues(), ...formData });
}, [settings]);
// If null, we still haven't shown the hands warning
// if false then initially the hands warning was disabled
const [handsWarning, setHandsWarning] = useState<boolean | null>(null);
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
setSettings(settings);
});
useEffect(() => {
if ((steamVrLeftHand || steamVrRightHand) && handsWarning === null) {
setHandsWarning(true);
} else if (
!(steamVrLeftHand || steamVrRightHand) &&
handsWarning === false
) {
setHandsWarning(null);
}
}, [steamVrLeftHand, steamVrRightHand, handsWarning]);
return (
<SettingsPageLayout>
<HandsWarningModal
isOpen={!!showHandsWarning}
isOpen={!!handsWarning}
onClose={() => {
setValue('trackers.leftHand', false);
setValue('trackers.rightHand', false);
setShowHandsWarning(null);
setHandsWarning(null);
}}
accept={() => {
const [leftHand, rightHand] = showHandsWarning!;
blockHandsWarning.current = true;
setValue('trackers.leftHand', leftHand);
setValue('trackers.rightHand', rightHand);
setShowHandsWarning(null);
setValue('trackers.leftHand', true);
setValue('trackers.rightHand', true);
setHandsWarning(false);
}}
/>
<form className="flex flex-col gap-2 w-full">
@@ -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,269 @@
import { KeybindRecorderModal } from '@/components/commons/KeybindRecorderModal';
import {
SettingsPageLayout,
SettingsPagePaneLayout,
} from '@/components/settings/SettingsPageLayout';
import { WrenchIcon } from '@/components/commons/icon/WrenchIcons';
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,
KeybindT,
OpenUriRequestT,
RpcMessage,
} from 'solarxr-protocol';
import {
FieldPath,
FormProvider,
useFieldArray,
useForm,
} from 'react-hook-form';
import { useAppContext } from '@/hooks/app';
import { useElectron } from '@/hooks/electron';
export type KeybindForm = {
keybinds: {
id: number;
name: string;
binding: string[];
delay: number;
}[];
};
export function KeybindSettings() {
const electron = useElectron();
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 { installInfo } = useAppContext();
const methods = useForm<KeybindForm>({
defaultValues: defaultKeybindsState,
});
const {
control,
handleSubmit,
reset,
setValue,
getValues,
setError,
clearErrors,
resetField,
} = 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.keybindNameId = kb.name;
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.OpenUriRequest, new OpenUriRequestT());
};
useRPCPacket(
RpcMessage.KeybindResponse,
({ keybind, defaultKeybinds }: KeybindResponseT) => {
if (!keybind) return;
const mappedDefaults = defaultKeybinds.map((kb) => ({
id: kb.keybindId,
name: typeof kb.keybindNameId === 'string' ? kb.keybindNameId : '',
binding:
typeof kb.keybindValue === 'string' ? kb.keybindValue.split('+') : [],
delay: kb.keybindDelay,
}));
setDefaultKeybindsState({ keybinds: mappedDefaults });
reset({ keybinds: mappedDefaults });
const mapped = keybind.map((kb) => ({
id: kb.keybindId,
name: typeof kb.keybindNameId === 'string' ? kb.keybindNameId : '',
binding:
typeof kb.keybindValue === 'string' ? kb.keybindValue.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;
if (currentIndex !== null) {
setIsOpen(true);
}
};
const onClose = () => {
if (currentIndex.current != null) {
resetField(`keybinds.${currentIndex.current}.binding`);
}
setIsOpen(false);
};
const createKeybindRows = (): ReactNode => {
return fields.map((field, index) => {
return (
<div className="keybind-row" key={index}>
<KeybindsRow
id={typeof field.name === 'string' ? field.name : ''}
control={control}
index={index}
getValue={getValues}
openKeybindRecorderModal={handleOpenRecorderModal}
/>
</div>
);
});
};
useEffect(() => {
sendRPCPacket(RpcMessage.KeybindRequest, new KeybindRequestT());
}, []);
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>
{!installInfo?.isWayland ? (
<div className="flex flex-col gap-4">
<Typography id="settings-keybinds-wayland-description" />
<div>
<Button
id="settings-keybinds-wayland-open-system-settings-button"
className="flex flex-col"
onClick={handleOpenSystemSettingsButton}
variant="primary"
/>
</div>
</div>
) : (
electron.isElectron &&
electron.data().os.type !== 'windows' && (
<>
<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>
<KeybindRecorderModal
id={
currentIndex.current != null
? fields[currentIndex.current].name
: ''
}
control={control}
name={
(currentIndex.current != null
? `keybinds.${currentIndex.current}.binding`
: '') as FieldPath<KeybindForm>
}
isVisisble={isOpen}
onClose={onClose}
onUnbind={() => {
if (currentIndex.current != null)
setValue(
`keybinds.${currentIndex.current}.binding`,
[]
);
}}
onSubmit={onSubmit}
/>
</FormProvider>
</>
)
)}
</div>
</SettingsPagePaneLayout>
</SettingsPageLayout>
);
}
+23 -2
View File
@@ -5,6 +5,7 @@ import {
ResetResponseT,
RpcMessage,
StartDataFeedT,
InstalledInfoResponseT,
} from 'solarxr-protocol';
import { handleResetSounds } from '@/sounds/sounds';
import { useConfig } from './config';
@@ -18,11 +19,17 @@ import { DEFAULT_LOCALE, LangContext } from '@/i18n/config';
export interface AppContext {
currentFirmwareRelease: FirmwareRelease | null;
installInfo: InstalledInfoResponseT | null;
}
export function useProvideAppContext(): AppContext {
const { useRPCPacket, sendDataFeedPacket, useDataFeedPacket, isConnected } =
useWebsocketAPI();
const {
useRPCPacket,
sendRPCPacket,
sendDataFeedPacket,
useDataFeedPacket,
isConnected,
} = useWebsocketAPI();
const { changeLocales } = useContext(LangContext);
const { config } = useConfig();
const { dataFeedConfig } = useDataFeedConfig();
@@ -34,6 +41,8 @@ export function useProvideAppContext(): AppContext {
const [currentFirmwareRelease, setCurrentFirmwareRelease] =
useState<FirmwareRelease | null>(null);
const [installInfo, setInstallInfo] = useState<InstalledInfoResponseT | null>(null);
useEffect(() => {
if (isConnected) {
const startDataFeed = new StartDataFeedT();
@@ -70,6 +79,17 @@ export function useProvideAppContext(): AppContext {
};
}, [config?.uuid]);
useEffect(() => {
sendRPCPacket(RpcMessage.InstalledInfoRequest, new InstalledInfoResponseT());
}, []);
useRPCPacket(
RpcMessage.InstalledInfoResponse,
({ isUdevInstalled, isWayland }: InstalledInfoResponseT) => {
setInstallInfo(new InstalledInfoResponseT(isUdevInstalled, isWayland));
}
);
useLayoutEffect(() => {
changeLocales([config?.lang || DEFAULT_LOCALE]);
}, []);
@@ -85,6 +105,7 @@ export function useProvideAppContext(): AppContext {
return {
currentFirmwareRelease,
installInfo,
};
}
+4 -1
View File
@@ -105,7 +105,10 @@ function fallbackToDefaults(loadedConfig: any): Config {
// allows to load everything before the first render
export const loadConfig = async () => {
try {
const json = (await store.get<string>('config.json')) ?? '{}';
const json = await store.get<string>('config.json');
if (!json) throw new Error('Config has ceased existing for some reason');
const loadedConfig = fallbackToDefaults(JSON.parse(json));
if (!loadedConfig.uuid) {
+1 -1
View File
@@ -102,7 +102,7 @@ export function useProvideOnboarding() {
});
const onboardingEnded = () => {
if (!settings?.modelSettings || !settings?.vrcOsc) return;
if (!settings?.modelSettings || !settings?.vrcOsc) throw 'settings should be set';
const req = new ChangeSettingsRequestT();
const modelSettings = new ModelSettingsT();
const oscSettings = new VRCOSCSettingsT();
+1
View File
@@ -183,6 +183,7 @@ const config = {
lg: '1300px',
xl: '1600px',
tall: { raw: '(min-height: 860px)' },
'keybinds-small': { raw: 'not (min-width: 1230px)' },
},
extend: {
colors: {
+41 -41
View File
@@ -163,8 +163,8 @@ importers:
specifier: ^40.3.0
version: 40.9.1
electron-builder:
specifier: ^26.9.0
version: 26.9.0(electron-builder-squirrel-windows@26.9.0)
specifier: ^26.7.0
version: 26.8.1(electron-builder-squirrel-windows@26.8.1)
electron-vite:
specifier: ^5.0.0
version: 5.0.0(@swc/[email protected])([email protected](@types/[email protected])([email protected]))
@@ -1798,12 +1798,12 @@ packages:
[email protected]:
resolution: {integrity: sha512-j87o0j6LqPL3QRr8yid6c+Tt5gC7xNfYo6uQIQkorAC6MpeayVMZrEDzKmJJ/Hlv7EnOQpaRm53k6ktDYZyB6w==}
app-builder-lib@26.9.0:
resolution: {integrity: sha512-f/1GhVrDfBH7sSzhAwiXa1rpR/7pB7Av5woUjmt+QYE0QyNvrOAiY05rngtR/PK4/1BzS6/zVoYobIwDAsrtBA==}
app-builder-lib@26.8.1:
resolution: {integrity: sha512-p0Im/Dx5C4tmz8QEE1Yn4MkuPC8PrnlRneMhWJj7BBXQfNTJUshM/bp3lusdEsDbvvfJZpXWnYesgSLvwtM2Zw==}
engines: {node: '>=14.0.0'}
peerDependencies:
dmg-builder: 26.9.0
electron-builder-squirrel-windows: 26.9.0
dmg-builder: 26.8.1
electron-builder-squirrel-windows: 26.8.1
[email protected]:
resolution: {integrity: sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==}
@@ -1975,12 +1975,12 @@ packages:
[email protected]:
resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==}
builder-util-runtime@9.6.0:
resolution: {integrity: sha512-k9V5I18PXLepLZ8jVmPzsH+gVCVZ+9aMVLyCZ0ZLOkT2KSyiBblDCCN8WxDbjOpfLGNHZqqJPBmW0HYeqxlgkQ==}
builder-util-runtime@9.5.1:
resolution: {integrity: sha512-qt41tMfgHTllhResqM5DcnHyDIWNgzHvuY2jDcYP9iaGpkWxTUzV6GQjDeLnlR1/DtdlcsWQbA7sByMpmJFTLQ==}
engines: {node: '>=12.0.0'}
builder-util@26.9.0:
resolution: {integrity: sha512-+eocmbdisnyb40B9nAp/KREfYLXvGagxV50KZv/Zh4aflsr1fdY9Qxs6QG1Jtx1vH5d5NQ3hIcemUi4RSlFK/Q==}
builder-util@26.8.1:
resolution: {integrity: sha512-pm1lTYbGyc90DHgCDO7eo8Rl4EqKLciayNbZqGziqnH9jrlKe8ZANGdityLZU+pJh16dfzjAx2xQq9McuIPEtw==}
[email protected]:
resolution: {integrity: sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q==}
@@ -2346,8 +2346,8 @@ packages:
[email protected]:
resolution: {integrity: sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==}
dmg-builder@26.9.0:
resolution: {integrity: sha512-5uSyg0yY+JRMMGwFjIweaukYkCGcZSZwvH5VPlBHiKkTEP1a1/uV+bs4y+VAxPMgzg67YB4CF1vD4U/2d3chfg==}
dmg-builder@26.8.1:
resolution: {integrity: sha512-glMJgnTreo8CFINujtAhCgN96QAqApDMZ8Vl1r8f0QT8QprvC1UCltV4CcWj20YoIyLZx6IUskaJZ0NV8fokcg==}
[email protected]:
resolution: {integrity: sha512-ZdzmqwKmECOWJpqefloC5OJy1+WZBBse5+MR88z9g9Zn4VY+WYUkAyojmhzJckH5YbbZGcYIuGAkY5/Ys5OM2Q==}
@@ -2386,16 +2386,16 @@ packages:
engines: {node: '>=0.10.0'}
hasBin: true
electron-builder-squirrel-windows@26.9.0:
resolution: {integrity: sha512-Jzsxa3Kjv94ZRZDK7pc8bzu5iglwGsDOBMWTqLpWx2sCEvb3TLW9PMWqOjpDwizqkMBp8GjP6rceLzQYLFIVow==}
electron-builder-squirrel-windows@26.8.1:
resolution: {integrity: sha512-o288fIdgPLHA76eDrFADHPoo7VyGkDCYbLV1GzndaMSAVBoZrGvM9m2IehdcVMzdAZJ2eV9bgyissQXHv5tGzA==}
electron-builder@26.9.0:
resolution: {integrity: sha512-7BEeGz8Xlk7Qvitj70nGAQaq7WQIZ2amsDvsyKSZbxgtL2pM9fm/woZrtn0hoID6Fl7wkn456dK3OmtFNzgiOA==}
electron-builder@26.8.1:
resolution: {integrity: sha512-uWhx1r74NGpCagG0ULs/P9Nqv2nsoo+7eo4fLUOB8L8MdWltq9odW/uuLXMFCDGnPafknYLZgjNX0ZIFRzOQAw==}
engines: {node: '>=14.0.0'}
hasBin: true
electron-publish@26.9.0:
resolution: {integrity: sha512-gsy+U7JfDuD1lPOrCXeECDQoUsWjFah3s1Fv3pqKnjdJuKYDDvGdvC74kLHVG6nl5G0uQ7YN0eftCQ4rUmhvVw==}
electron-publish@26.8.1:
resolution: {integrity: sha512-q+jrSTIh/Cv4eGZa7oVR+grEJo/FoLMYBAnSL5GCtqwUpr1T+VgKB/dn1pnzxIxqD8S/jP1yilT9VrwCqINR4w==}
[email protected]:
resolution: {integrity: sha512-Is+0BBHJ4NrdpAYiperrmp53pLywG/yV/6lIMTAnhxvzj/Cmn5Q/ogSHC6AKe7X+8kPLxxFk0cs5oc/3j/fxIg==}
@@ -6568,7 +6568,7 @@ snapshots:
[email protected]: {}
app-builder-lib@26.9.0(dmg-builder@26.9.0)(electron-builder-squirrel-windows@26.9.0):
app-builder-lib@26.8.1(dmg-builder@26.8.1)(electron-builder-squirrel-windows@26.8.1):
dependencies:
'@develar/schema-utils': 2.6.5
'@electron/asar': 3.4.1
@@ -6581,17 +6581,17 @@ snapshots:
'@malept/flatpak-bundler': 0.4.0
'@types/fs-extra': 9.0.13
async-exit-hook: 2.0.1
builder-util: 26.9.0
builder-util-runtime: 9.6.0
builder-util: 26.8.1
builder-util-runtime: 9.5.1
chromium-pickle-js: 0.2.0
ci-info: 4.3.1
debug: 4.4.3
dmg-builder: 26.9.0(electron-builder-squirrel-windows@26.9.0)
dmg-builder: 26.8.1(electron-builder-squirrel-windows@26.8.1)
dotenv: 16.6.1
dotenv-expand: 11.0.7
ejs: 3.1.10
electron-builder-squirrel-windows: 26.9.0(dmg-builder@26.9.0)
electron-publish: 26.9.0
electron-builder-squirrel-windows: 26.8.1(dmg-builder@26.8.1)
electron-publish: 26.8.1
fs-extra: 10.1.0
hosted-git-info: 4.1.0
isbinaryfile: 5.0.7
@@ -6795,19 +6795,19 @@ snapshots:
base64-js: 1.5.1
ieee754: 1.2.1
builder-util-runtime@9.6.0:
builder-util-runtime@9.5.1:
dependencies:
debug: 4.4.3
sax: 1.6.0
transitivePeerDependencies:
- supports-color
builder-util@26.9.0:
builder-util@26.8.1:
dependencies:
7zip-bin: 5.2.0
'@types/debug': 4.1.13
app-builder-bin: 5.0.0-alpha.12
builder-util-runtime: 9.6.0
builder-util-runtime: 9.5.1
chalk: 4.1.2
cross-spawn: 7.0.6
debug: 4.4.3
@@ -7188,10 +7188,10 @@ snapshots:
[email protected]: {}
dmg-builder@26.9.0(electron-builder-squirrel-windows@26.9.0):
dmg-builder@26.8.1(electron-builder-squirrel-windows@26.8.1):
dependencies:
app-builder-lib: 26.9.0(dmg-builder@26.9.0)(electron-builder-squirrel-windows@26.9.0)
builder-util: 26.9.0
app-builder-lib: 26.8.1(dmg-builder@26.8.1)(electron-builder-squirrel-windows@26.8.1)
builder-util: 26.8.1
fs-extra: 10.1.0
iconv-lite: 0.6.3
js-yaml: 4.1.1
@@ -7238,23 +7238,23 @@ snapshots:
dependencies:
jake: 10.9.4
electron-builder-squirrel-windows@26.9.0(dmg-builder@26.9.0):
electron-builder-squirrel-windows@26.8.1(dmg-builder@26.8.1):
dependencies:
app-builder-lib: 26.9.0(dmg-builder@26.9.0)(electron-builder-squirrel-windows@26.9.0)
builder-util: 26.9.0
app-builder-lib: 26.8.1(dmg-builder@26.8.1)(electron-builder-squirrel-windows@26.8.1)
builder-util: 26.8.1
electron-winstaller: 5.4.0
transitivePeerDependencies:
- dmg-builder
- supports-color
electron-builder@26.9.0(electron-builder-squirrel-windows@26.9.0):
electron-builder@26.8.1(electron-builder-squirrel-windows@26.8.1):
dependencies:
app-builder-lib: 26.9.0(dmg-builder@26.9.0)(electron-builder-squirrel-windows@26.9.0)
builder-util: 26.9.0
builder-util-runtime: 9.6.0
app-builder-lib: 26.8.1(dmg-builder@26.8.1)(electron-builder-squirrel-windows@26.8.1)
builder-util: 26.8.1
builder-util-runtime: 9.5.1
chalk: 4.1.2
ci-info: 4.4.0
dmg-builder: 26.9.0(electron-builder-squirrel-windows@26.9.0)
dmg-builder: 26.8.1(electron-builder-squirrel-windows@26.8.1)
fs-extra: 10.1.0
lazy-val: 1.0.5
simple-update-notifier: 2.0.0
@@ -7263,11 +7263,11 @@ snapshots:
- electron-builder-squirrel-windows
- supports-color
electron-publish@26.9.0:
electron-publish@26.8.1:
dependencies:
'@types/fs-extra': 9.0.13
builder-util: 26.9.0
builder-util-runtime: 9.6.0
builder-util: 26.8.1
builder-util-runtime: 9.5.1
chalk: 4.1.2
form-data: 4.0.5
fs-extra: 10.1.0
@@ -14,6 +14,9 @@ import dev.slimevr.tracking.trackers.Device
import dev.slimevr.tracking.trackers.Tracker
import dev.slimevr.tracking.trackers.TrackerStatus
import dev.slimevr.tracking.trackers.hid.HIDCommon
import dev.slimevr.tracking.trackers.hid.HIDCommon.Companion.HID_TRACKER_PID
import dev.slimevr.tracking.trackers.hid.HIDCommon.Companion.HID_TRACKER_RECEIVER_PID
import dev.slimevr.tracking.trackers.hid.HIDCommon.Companion.HID_TRACKER_RECEIVER_VID
import dev.slimevr.tracking.trackers.hid.HIDCommon.Companion.PACKET_SIZE
import dev.slimevr.tracking.trackers.hid.HIDDevice
import io.eiren.util.logging.LogManager
@@ -91,7 +94,7 @@ class AndroidHIDManager(
}
fun checkConfigureDevice(usbDevice: UsbDevice, requestPermission: Boolean = false) {
if (HIDCommon.matchesAny(usbDevice.vendorId, usbDevice.productId)) {
if (usbDevice.vendorId == HID_TRACKER_RECEIVER_VID && (usbDevice.productId == HID_TRACKER_RECEIVER_PID || usbDevice.productId == HID_TRACKER_PID)) {
if (usbManager.hasPermission(usbDevice)) {
LogManager.info("[TrackerServer] Already have permission for ${usbDevice.deviceName}")
proceedWithDeviceConfiguration(usbDevice)
@@ -201,7 +204,7 @@ class AndroidHIDManager(
private fun deviceEnumerate(requestPermission: Boolean = false) {
val trackersOverHID: Boolean = VRServer.instance.configManager.vrConfig.hidConfig.trackersOverHID
val hidDeviceList: MutableList<UsbDevice> = usbManager.deviceList.values.filter {
HIDCommon.matchesReceiver(it.vendorId, it.productId) || (trackersOverHID && HIDCommon.matchesTracker(it.vendorId, it.productId))
it.vendorId == HID_TRACKER_RECEIVER_VID && (it.productId == HID_TRACKER_RECEIVER_PID || (trackersOverHID && it.productId == HID_TRACKER_PID))
}.toMutableList()
synchronized(devicesByHID) {
// Work on devicesByHid and add/remove as necessary
+2
View File
@@ -83,6 +83,8 @@ dependencies {
implementation("com.mayakapps.kache:kache:2.1.0")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.8.1")
implementation("com.github.HannahPadd:DbusGlobalShortcutsWayland:v0.1.0")
api("com.github.loucass003:EspflashKotlin:v0.11.0")
// Allow the use of reflection
@@ -2,51 +2,49 @@ package dev.slimevr
import com.melloware.jintellitype.HotkeyListener
import com.melloware.jintellitype.JIntellitype
import dev.hannah.portals.PortalManager
import dev.hannah.portals.globalShortcuts.Shortcut
import dev.hannah.portals.globalShortcuts.ShortcutTuple
import dev.slimevr.config.KeybindingsConfig
import dev.slimevr.tracking.trackers.TrackerUtils
import io.eiren.util.OperatingSystem
import io.eiren.util.OperatingSystem.Companion.currentPlatform
import io.eiren.util.ann.AWTThread
import io.eiren.util.logging.LogManager
import solarxr_protocol.rpc.KeybindId
enum class Keybinds(val id: Int, val keybindName: String, val description: String, val keybind: String) {
FULL_RESET(KeybindId.FULL_RESET, "FULL_RESET", "Full Reset", "CTRL+ALT+SHIFT+Y"),
MOUNTING_RESET(KeybindId.MOUNTING_RESET, "MOUNTING_RESET", "Mounting Reset", "CTRL+ALT+SHIFT+I"),
PAUSE_TRACKING(KeybindId.PAUSE_TRACKING, "PAUSE_TRACKING", "Pause Tracking", "CTRL+ALT+SHIFT+O"),
YAW_RESET(KeybindId.YAW_RESET, "YAW_RESET", "Yaw Reset", "CTRL+ALT+SHIFT+U"),
FEET_MOUNTING_RESET(KeybindId.FEET_MOUNTING_RESET, "FEET_MOUNTING_RESET", "Feet Mounting Reset", "CTRL+ALT+SHIFT+P"),
;
override fun toString(): String = keybindName
companion object {
private val byId = Keybinds.entries.associateBy { it.id }
private val byName = Keybinds.entries.associateBy { it.keybindName }
fun getById(value: Int): Keybinds? = byId[value]
fun getByName(name: String): Keybinds? = byName[name]
}
}
class Keybinding @AWTThread constructor(val server: VRServer) : HotkeyListener {
val config: KeybindingsConfig = server.configManager.vrConfig.keybindings
init {
if (currentPlatform != OperatingSystem.WINDOWS) {
LogManager
.info(
"[Keybinding] Currently only supported on Windows. Keybindings will be disabled.",
)
} else {
if (currentPlatform == OperatingSystem.WINDOWS) {
try {
if (JIntellitype.getInstance() != null) {
JIntellitype.getInstance().addHotKeyListener(this)
val fullResetBinding = config.fullResetBinding
JIntellitype.getInstance()
.registerHotKey(FULL_RESET, fullResetBinding)
LogManager.info("[Keybinding] Bound full reset to $fullResetBinding")
val yawResetBinding = config.yawResetBinding
JIntellitype.getInstance()
.registerHotKey(YAW_RESET, yawResetBinding)
LogManager.info("[Keybinding] Bound yaw reset to $yawResetBinding")
val mountingResetBinding = config.mountingResetBinding
JIntellitype.getInstance()
.registerHotKey(MOUNTING_RESET, mountingResetBinding)
LogManager.info("[Keybinding] Bound reset mounting to $mountingResetBinding")
val feetMountingResetBinding = config.feetMountingResetBinding
JIntellitype.getInstance()
.registerHotKey(FEET_MOUNTING_RESET, feetMountingResetBinding)
LogManager.info("[Keybinding] Bound feet reset mounting to $feetMountingResetBinding")
val pauseTrackingBinding = config.pauseTrackingBinding
JIntellitype.getInstance()
.registerHotKey(PAUSE_TRACKING, pauseTrackingBinding)
LogManager.info("[Keybinding] Bound pause tracking to $pauseTrackingBinding")
config.keybinds.forEach { (i, keybind) ->
JIntellitype.getInstance()
.registerHotKey(keybind.id, keybind.binding)
}
}
} catch (e: Throwable) {
LogManager
@@ -55,42 +53,97 @@ class Keybinding @AWTThread constructor(val server: VRServer) : HotkeyListener {
)
}
}
if (currentPlatform == OperatingSystem.LINUX) {
val portalManager = PortalManager(SLIMEVR_IDENTIFIER)
val shortcutsList = Keybinds.entries.map {
ShortcutTuple(it.name, Shortcut(it.description, it.keybind).shortcut)
}.toMutableList()
val globalShortcutsHandler = portalManager.globalShortcutsRequest(shortcutsList)
Runtime.getRuntime().addShutdownHook(
Thread {
println("Closing connection")
globalShortcutsHandler.close()
},
)
val onShortcut: (id: String) -> Unit = { shortcutId ->
val keybind = Keybinds.getByName(shortcutId)
if (keybind != null) {
val delay = config.keybinds[keybind]?.delay?.toLong() ?: 0L
when (keybind) {
Keybinds.FULL_RESET -> {
server.scheduleResetTrackersFull(keybind.keybindName, delay)
}
Keybinds.YAW_RESET -> {
server.scheduleResetTrackersYaw(keybind.keybindName, delay)
}
Keybinds.MOUNTING_RESET -> {
server.scheduleResetTrackersMounting(
keybind.keybindName,
delay,
)
}
Keybinds.FEET_MOUNTING_RESET -> {
server.scheduleResetTrackersMounting(
keybind.keybindName,
delay,
TrackerUtils.feetsBodyParts,
)
}
Keybinds.PAUSE_TRACKING -> {
server.scheduleTogglePauseTracking(
keybind.keybindName,
delay,
)
}
}
}
}
globalShortcutsHandler.onShortcutActivated = onShortcut
}
}
@AWTThread
override fun onHotKey(identifier: Int) {
when (identifier) {
FULL_RESET -> server.scheduleResetTrackersFull(RESET_SOURCE_NAME, config.fullResetDelay)
val keybind = Keybinds.getById(identifier) ?: return
val delay = config.keybinds[keybind]?.delay?.toLong() ?: 0L
when (keybind) {
Keybinds.FULL_RESET -> {
server.scheduleResetTrackersFull(keybind.keybindName, delay)
}
YAW_RESET -> server.scheduleResetTrackersYaw(RESET_SOURCE_NAME, config.yawResetDelay)
Keybinds.YAW_RESET -> {
server.scheduleResetTrackersYaw(keybind.keybindName, delay)
}
MOUNTING_RESET -> server.scheduleResetTrackersMounting(
RESET_SOURCE_NAME,
config.mountingResetDelay,
)
Keybinds.MOUNTING_RESET -> {
server.scheduleResetTrackersMounting(
keybind.keybindName,
delay,
TrackerUtils.feetsBodyParts,
)
}
FEET_MOUNTING_RESET -> server.scheduleResetTrackersMounting(
RESET_SOURCE_NAME,
config.feetMountingResetDelay,
TrackerUtils.feetsBodyParts,
)
Keybinds.FEET_MOUNTING_RESET -> {
server.scheduleResetTrackersMounting(
keybind.keybindName,
delay,
TrackerUtils.feetsBodyParts,
)
}
PAUSE_TRACKING ->
server
.scheduleTogglePauseTracking(
RESET_SOURCE_NAME,
config.pauseTrackingDelay,
)
Keybinds.PAUSE_TRACKING -> {
server.scheduleTogglePauseTracking(
keybind.keybindName,
delay,
)
}
}
}
companion object {
private const val RESET_SOURCE_NAME = "Keybinding"
private const val FULL_RESET = 1
private const val YAW_RESET = 2
private const val MOUNTING_RESET = 3
private const val FEET_MOUNTING_RESET = 4
private const val PAUSE_TRACKING = 5
}
}
@@ -11,6 +11,7 @@ import dev.slimevr.games.vrchat.VRCConfigHandler
import dev.slimevr.games.vrchat.VRCConfigHandlerStub
import dev.slimevr.games.vrchat.VRChatConfigManager
import dev.slimevr.guards.ServerGuards
import dev.slimevr.keybind.KeybindHandler
import dev.slimevr.osc.OSCHandler
import dev.slimevr.osc.OSCRouter
import dev.slimevr.osc.VMCHandler
@@ -128,6 +129,8 @@ class VRServer @JvmOverloads constructor(
val networkProfileChecker: NetworkProfileChecker
val keybindHandler: KeybindHandler
val serverGuards = ServerGuards()
init {
@@ -144,6 +147,7 @@ class VRServer @JvmOverloads constructor(
vrcConfigManager = VRChatConfigManager(this, vrcConfigHandlerProvider(this))
networkProfileChecker = networkProfileProvider(this)
trackingChecklistManager = TrackingChecklistManager(this)
keybindHandler = KeybindHandler(this)
protocolAPI = ProtocolAPI(this)
val computedTrackers = humanPoseManager.computedTrackers
@@ -1,88 +0,0 @@
package dev.slimevr.config;
public class KeybindingsConfig {
private String fullResetBinding = "CTRL+ALT+SHIFT+Y";
private String yawResetBinding = "CTRL+ALT+SHIFT+U";
private String mountingResetBinding = "CTRL+ALT+SHIFT+I";
private String feetMountingResetBinding = "CTRL+ALT+SHIFT+P";
private String pauseTrackingBinding = "CTRL+ALT+SHIFT+O";
private long fullResetDelay = 0L;
private long yawResetDelay = 0L;
private long mountingResetDelay = 0L;
private long feetMountingResetDelay = 0L;
private long pauseTrackingDelay = 0L;
public KeybindingsConfig() {
}
public String getFullResetBinding() {
return fullResetBinding;
}
public String getYawResetBinding() {
return yawResetBinding;
}
public String getMountingResetBinding() {
return mountingResetBinding;
}
public String getFeetMountingResetBinding() {
return feetMountingResetBinding;
}
public String getPauseTrackingBinding() {
return pauseTrackingBinding;
}
public long getFullResetDelay() {
return fullResetDelay;
}
public void setFullResetDelay(long delay) {
fullResetDelay = delay;
}
public long getYawResetDelay() {
return yawResetDelay;
}
public void setYawResetDelay(long delay) {
yawResetDelay = delay;
}
public long getMountingResetDelay() {
return mountingResetDelay;
}
public void setMountingResetDelay(long delay) {
mountingResetDelay = delay;
}
public long getFeetMountingResetDelay() {
return feetMountingResetDelay;
}
public void setFeetMountingResetDelay(long delay) {
feetMountingResetDelay = delay;
}
public long getPauseTrackingDelay() {
return pauseTrackingDelay;
}
public void setPauseTrackingDelay(long delay) {
pauseTrackingDelay = delay;
}
}
@@ -0,0 +1,16 @@
package dev.slimevr.config
import dev.slimevr.Keybinds
data class KeybindData(
var id: Int,
var name: String,
var binding: String,
var delay: Float,
)
class KeybindingsConfig {
val keybinds: MutableMap<Keybinds, KeybindData> = Keybinds.entries
.associateWith { KeybindData(it.id, it.keybindName, it.keybind, 0f) }
.toMutableMap()
}
@@ -0,0 +1,55 @@
package dev.slimevr.keybind
import dev.slimevr.VRServer
import dev.slimevr.config.KeybindingsConfig
import solarxr_protocol.rpc.KeybindT
import java.util.concurrent.CopyOnWriteArrayList
class KeybindHandler(val vrServer: VRServer) {
private val listeners: MutableList<KeybindListener> = CopyOnWriteArrayList()
var keybinds: MutableList<KeybindT> = mutableListOf()
var defaultKeybinds: MutableList<KeybindT> = mutableListOf()
init {
createKeybinds()
}
fun addListener(listener: KeybindListener) {
this.listeners.add(listener)
}
fun removeListener(listener: KeybindListener) {
listeners.removeIf { listener == it }
}
private fun createKeybinds() {
keybinds.clear()
defaultKeybinds.clear()
vrServer.configManager.vrConfig.keybindings.keybinds.forEach { (i, keybind) ->
keybinds.add(
KeybindT().apply {
keybindId = keybind.id
keybindNameId = keybind.name
keybindValue = keybind.binding
keybindDelay = keybind.delay
},
)
}
val binds = KeybindingsConfig().keybinds
binds.forEach { (i, keybind) ->
defaultKeybinds.add(
KeybindT().apply {
keybindId = keybind.id
keybindNameId = keybind.name
keybindValue = keybind.binding
keybindDelay = keybind.delay
},
)
}
}
fun updateKeybinds() {
createKeybinds()
}
}
@@ -0,0 +1,6 @@
package dev.slimevr.keybind
interface KeybindListener {
fun sendKeybind()
fun onKeybindUpdate()
}
@@ -12,6 +12,7 @@ import com.jme3.math.FastMath
import com.jme3.system.NanoTimer
import dev.slimevr.VRServer
import dev.slimevr.config.VRCOSCConfig
import dev.slimevr.protocol.rpc.setup.RPCUtil
import dev.slimevr.tracking.trackers.Device
import dev.slimevr.tracking.trackers.Tracker
import dev.slimevr.tracking.trackers.TrackerPosition
@@ -25,8 +26,6 @@ import io.github.axisangles.ktmath.Vector3
import java.io.IOException
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.NetworkInterface
import kotlin.collections.iterator
private const val OFFSET_SLERP_FACTOR = 0.5f // Guessed from eyeing VRChat
@@ -38,6 +37,8 @@ class VRCOSCHandler(
private val config: VRCOSCConfig,
private val computedTrackers: List<Tracker>,
) : OSCHandler {
private val localIp = RPCUtil.getLocalIp()
private val loopbackIp = InetAddress.getLoopbackAddress().hostAddress
private val vrsystemTrackersAddresses = arrayOf(
"/tracking/vrsystem/head/pose",
"/tracking/vrsystem/leftwrist/pose",
@@ -59,9 +60,9 @@ class VRCOSCHandler(
private var oscPortIn = 0
private var oscPortOut = 0
private var oscIp: InetAddress? = null
private var oscQuerySenderState = false
private var oscQueryPortOut = 0
private var oscQueryIp: InetAddress? = null
private var oscQueryIpMatch = false
private var oscQueryIp: String? = null
private var timeAtLastError: Long = 0
private var receivingPositionOffset = Vector3.NULL
private var postReceivingPositionOffset = Vector3.NULL
@@ -93,15 +94,13 @@ class VRCOSCHandler(
updateOscReceiver(config.portIn, vrsystemTrackersAddresses + oscTrackersAddresses)
updateOscSender(config.portOut, config.address)
if (config.enabled && config.oscqueryEnabled) {
if (vrcOscQueryHandler == null) {
try {
vrcOscQueryHandler = VRCOSCQueryHandler(server, this)
} catch (e: Throwable) {
LogManager.severe("Unable to initialize OSCQuery: $e", e)
}
if (vrcOscQueryHandler == null && config.enabled && config.oscqueryEnabled) {
try {
vrcOscQueryHandler = VRCOSCQueryHandler(this)
} catch (e: Throwable) {
LogManager.severe("Unable to initialize OSCQuery: $e", e)
}
} else {
} else if (vrcOscQueryHandler != null && (!config.enabled || !config.oscqueryEnabled)) {
vrcOscQueryHandler?.close()
vrcOscQueryHandler = null
}
@@ -111,218 +110,122 @@ class VRCOSCHandler(
}
}
fun ipIsLocal(a: InetAddress): Boolean {
if (a.isLoopbackAddress) {
return true
}
for (netInt in NetworkInterface.getNetworkInterfaces()) {
if (netInt.isUp && !netInt.isLoopback && !netInt.isVirtual) {
for (netAddr in netInt.interfaceAddresses) {
if (a == netAddr.address || a.address.contentEquals(netAddr.address.address) || a.hostName == netAddr.address.hostName) {
return true
}
}
}
}
return false
}
fun ipEquals(a: InetAddress?, b: InetAddress?): Boolean = a == b ||
(
a != null &&
b != null &&
(
a.address.contentEquals(b.address) ||
(a.hostName == b.hostName) ||
(ipIsLocal(a) && ipIsLocal(b))
)
)
/**
* Adds an OSC Sender from OSCQuery
*/
fun addOSCQuerySender(oscPortOut: Int, oscIP: String) {
if (!config.enabled) {
closeOscQuerySender()
return
}
try {
// If we already have the best matching client
if (oscQuerySender != null && oscQueryIpMatch) {
return
}
val addr = InetAddress.getByName(oscIP)
val ipMatch = ipEquals(addr, this.oscIp)
// If we already have an OSC sender
if (oscQuerySender != null) {
val portMatch = oscPortOut == this.oscPortOut
// Original IP will be matching because of the check done earlier
val origPortMatch = oscQueryPortOut == this.oscPortOut
// If the IP doesn't match and (the port doesn't match or the original
// port did match), ignore this client
if (!ipMatch && (!portMatch || origPortMatch)) {
return
}
// If this is the same address as what we're already sending to, keep
// using the same OSC sender
if (ipEquals(addr, oscQueryIp)) {
return
}
// So if the IP matches or the port matches and the original one didn't,
// we will select this new address for OSC
}
closeOscQuerySender()
if (ipMatch) {
LogManager.info("[VRCOSCHandler] OSCQuery sender sending to port $oscPortOut at address $oscIP (matches configured address)")
} else {
val addr = InetAddress.getByName(oscIP)
oscQuerySenderState = true
oscQueryIp = oscIP
oscQueryPortOut = oscPortOut
if (oscPortOut != portOut || (oscIP != address.hostName && !(oscIP == localIp && address.hostName == loopbackIp))) {
try {
oscQuerySender = OSCPortOut(InetSocketAddress(addr, oscPortOut))
oscQuerySender?.connect()
LogManager.info("[VRCOSCHandler] OSCQuery sender sending to port $oscPortOut at address $oscIP")
} catch (e: IOException) {
LogManager.severe("[VRCOSCHandler] Error connecting to port $oscPortOut at the address $oscIP: $e")
}
oscQuerySender = OSCPortOut(InetSocketAddress(addr, oscPortOut))
oscQueryIp = addr
oscQueryIpMatch = ipMatch
oscQueryPortOut = oscPortOut
// Avoids additional security checks, but not necessary for UDP, therefore
// isConnected doesn't really indicate that we are actively "connected"
oscQuerySender?.connect()
} catch (e: IOException) {
LogManager.severe("[VRCOSCHandler] Error connecting OSCQuery sender to port $oscPortOut at the address $oscIP: $e")
closeOscQuerySender()
}
}
/**
* Close/remove the OSC sender
* Close/remove the osc query sender
*/
fun closeOscSender() {
try {
oscSender?.close()
oscSender = null
} catch (e: IOException) {
LogManager.severe("[VRCOSCHandler] Error closing the OSC sender: $e")
}
}
/**
* Close/remove the OSCQuery sender
*/
fun closeOscQuerySender() {
try {
oscQuerySender?.close()
oscQuerySender = null
} catch (e: IOException) {
LogManager.severe("[VRCOSCHandler] Error closing the OSCQuery sender: $e")
}
}
/**
* Close/remove the OSC receiver
*/
fun closeOscReceiver() {
try {
oscReceiver?.close()
oscReceiver = null
} catch (e: IOException) {
LogManager.severe("[VRCOSCHandler] Error closing the OSC receiver: $e")
}
}
override fun updateOscReceiver(portIn: Int, oscAddresses: Array<String>) {
if (!config.enabled) {
closeOscReceiver()
return
}
// If already configured and listening, nothing new needs to be configured
if (oscPortIn == portIn && oscReceiver?.isListening == true) return
try {
closeOscReceiver()
// Instantiate the new OSC receiver
LogManager.info("[VRCOSCHandler] Listening to port $portIn")
val newOscReceiver = OSCPortIn(portIn)
oscReceiver = newOscReceiver
oscPortIn = portIn
val listener = OSCMessageListener { event: OSCMessageEvent ->
handleReceivedMessage(event)
fun closeOscQuerySender(newState: Boolean) {
oscQuerySender?.let {
try {
it.close()
oscQuerySender = null
oscQuerySenderState = newState
} catch (e: IOException) {
LogManager.severe("[VRCOSCHandler] Error closing the OSC sender: $e")
}
for (address in oscAddresses) {
newOscReceiver.dispatcher.addListener(
OSCPatternAddressMessageSelector(address),
listener,
)
}
}
override fun updateOscReceiver(portIn: Int, args: Array<String>) {
// Stop listening
val wasListening = oscReceiver != null && oscReceiver!!.isListening
if (wasListening) {
oscReceiver!!.stopListening()
}
if (config.enabled) {
// Instantiates the OSC receiver
try {
oscReceiver = OSCPortIn(portIn)
if (oscPortIn != portIn || !wasListening) {
LogManager.info("[VRCOSCHandler] Listening to port $portIn")
}
oscPortIn = portIn
vrcOscQueryHandler?.updateOSCQuery(portIn.toUShort())
} catch (e: IOException) {
LogManager
.severe(
"[VRCOSCHandler] Error listening to the port $portIn: $e",
)
}
newOscReceiver.startListening()
// Advertise our new receiving port over OSCQuery
vrcOscQueryHandler?.updateOSCQuery(portIn.toUShort())
} catch (e: IOException) {
LogManager.severe("[VRCOSCHandler] Error listening to the port $portIn: $e")
closeOscReceiver()
// Starts listening for VRC or OSCTrackers messages
oscReceiver?.let {
val listener = OSCMessageListener { event: OSCMessageEvent ->
handleReceivedMessage(event)
}
for (address in args) {
it.dispatcher.addListener(
OSCPatternAddressMessageSelector(address),
listener,
)
}
it.startListening()
}
}
}
override fun updateOscSender(portOut: Int, ip: String) {
if (!config.enabled) {
closeOscSender()
return
// Stop sending
val wasConnected = oscSender != null && oscSender!!.isConnected
if (wasConnected) {
try {
oscSender!!.close()
} catch (e: IOException) {
LogManager.severe("[VRCOSCHandler] Error closing the OSC sender: $e")
}
}
try {
// If already configured, nothing new needs to be configured
val addr = InetAddress.getByName(ip)
val resetQuery = if (ipEquals(addr, oscIp) && oscPortOut == portOut) {
// Technically we are fine if `isConnected` is false, but we can just
// assume we're always gonna be connected
if (oscSender?.isConnected == true) {
return
if (config.enabled) {
// Instantiate the OSC sender
try {
val addr = InetAddress.getByName(ip)
oscSender = OSCPortOut(InetSocketAddress(addr, portOut))
if ((oscPortOut != portOut && oscIp != addr) || !wasConnected) {
LogManager.info("[VRCOSCHandler] Sending to port $portOut at address $ip")
}
false
} else {
// If the new IP doesn't match the current OSCQuery IP, close the
// OSCQuery sender after updating the config variables
!ipEquals(addr, oscQueryIp)
oscPortOut = portOut
oscIp = addr
oscSender?.connect()
} catch (e: IOException) {
LogManager
.severe(
"[VRCOSCHandler] Error connecting to port $portOut at the address $ip: $e",
)
return
}
closeOscSender()
LogManager.info("[VRCOSCHandler] Sending to port $portOut at address $ip")
val newOscSender = OSCPortOut(InetSocketAddress(addr, portOut))
oscSender = newOscSender
oscIp = addr
oscPortOut = portOut
// Avoids additional security checks, but not necessary for UDP, therefore
// isConnected doesn't really indicate that we are actively "connected"
newOscSender.connect()
if (resetQuery) {
closeOscQuerySender()
if (oscQueryPortOut == portOut && (oscQueryIp == ip || (oscQueryIp == localIp && ip == loopbackIp))) {
if (oscQuerySender != null) {
// Close the oscQuerySender if it has the same port/ip
closeOscQuerySender(true)
}
} else if (oscQuerySender == null && oscQuerySenderState) {
// Instantiate the oscQuerySender if it could not be instantiated.
addOSCQuerySender(oscQueryPortOut, oscQueryIp!!)
}
} catch (e: IOException) {
LogManager
.severe(
"[VRCOSCHandler] Error connecting to port $portOut at the address $ip: $e",
)
closeOscSender()
return
}
}
private fun handleReceivedMessage(event: OSCMessageEvent) {
// TODO: Track the IP who sent this, we can list them as a send target and
// resolve the VRChat IP/port without scanning OSCQuery
if (vrsystemTrackersAddresses.contains(event.message.address)) {
// Receiving Head and Wrist pose data thanks to OSCQuery
// Create device if it doesn't exist
@@ -504,10 +407,6 @@ class VRCOSCHandler(
}
override fun update() {
if (!config.enabled) {
return
}
// Gets timer from vrServer
if (fpsTimer == null) {
fpsTimer = VRServer.instance.fpsTimer
@@ -521,7 +420,7 @@ class VRCOSCHandler(
val currentTime = System.currentTimeMillis().toFloat()
// Send OSC data
if (oscSender != null || oscQuerySender != null) {
if (oscSender != null && oscSender!!.isConnected) {
// Create new bundle
val bundle = OSCBundle()
@@ -583,12 +482,8 @@ class VRCOSCHandler(
}
try {
// Prioritize OSCQuery since we can't validate oscSender
if (oscQuerySender != null) {
oscQuerySender?.send(bundle)
} else {
oscSender?.send(bundle)
}
oscSender?.send(bundle)
oscQuerySender?.send(bundle)
} catch (e: IOException) {
// Avoid spamming AsynchronousCloseException too many
// times per second
@@ -630,7 +525,7 @@ class VRCOSCHandler(
* Sends the expected HMD rotation upon reset to align the trackers in VRC
*/
fun yawAlign(headRot: Quaternion) {
if (oscSender != null || oscQuerySender != null) {
if (oscSender != null && oscSender!!.isConnected) {
val (_, _, y, _) = headRot.toEulerAngles(EulerOrder.YXZ)
oscArgs.clear()
oscArgs.add(0f)
@@ -641,12 +536,8 @@ class VRCOSCHandler(
oscArgs,
)
try {
// Prioritize OSCQuery since we can't validate oscSender
if (oscQuerySender != null) {
oscQuerySender?.send(oscMessage)
} else {
oscSender?.send(oscMessage)
}
oscSender?.send(oscMessage)
oscQuerySender?.send(oscMessage)
} catch (e: IOException) {
LogManager
.warning("[VRCOSCHandler] Error sending OSC message to VRChat: $e")
@@ -3,7 +3,6 @@ package dev.slimevr.osc
import OSCQueryNode
import OSCQueryServer
import ServiceInfo
import dev.slimevr.VRServer
import dev.slimevr.protocol.rpc.setup.RPCUtil
import io.eiren.util.logging.LogManager
import randomFreePort
@@ -18,7 +17,6 @@ private const val queryPath = "/tracking/vrsystem"
* https://github.com/SlimeVR/oscquery-kt
*/
class VRCOSCQueryHandler(
private val server: VRServer,
private val vrcOscHandler: VRCOSCHandler,
) {
private val oscQueryServer: OSCQueryServer
@@ -73,16 +71,14 @@ class VRCOSCQueryHandler(
val port = info.port
// create a new OSCHandler for this service
server.queueTask {
vrcOscHandler.addOSCQuerySender(port, ip)
}
vrcOscHandler.addOSCQuerySender(port, ip)
}
/**
* Closes the OSCQueryServer and the associated OSC sender.
*/
fun close() {
vrcOscHandler.closeOscQuerySender()
vrcOscHandler.closeOscQuerySender(false)
thread(start = true) {
oscQueryServer.close()
}
@@ -5,7 +5,6 @@ import dev.slimevr.tracking.processor.Bone
import dev.slimevr.tracking.processor.skeleton.HumanSkeleton
import io.github.axisangles.ktmath.EulerOrder
import io.github.axisangles.ktmath.Quaternion
import io.github.axisangles.ktmath.Vector3
import org.apache.commons.lang3.StringUtils
import java.io.BufferedWriter
import java.io.File
@@ -45,91 +44,36 @@ class BVHFileStream : PoseDataStream {
private fun internalNavigateSkeleton(
bone: Bone,
header: (bone: Bone, lastBone: Bone?, invertParentRot: Quaternion, distance: Int, hasBranch: Boolean, invertOffset: Boolean, zeroOffset: Boolean) -> Unit,
header: (bone: Bone, lastBone: Bone?, invertParentRot: Quaternion, distance: Int, hasBranch: Boolean, isParent: Boolean) -> Unit,
footer: (distance: Int) -> Unit,
lastBone: Bone? = null,
invertParentRot: Quaternion = Quaternion.IDENTITY,
distance: Int = 0,
invertOffset: Boolean = false,
zeroOffset: Boolean = false,
isParent: Boolean = false,
) {
val isRoot = lastBone == null
val isInverse = bone === lastBone?.parent
val parent = bone.parent
// If we're visiting the parents or at root, continue to the next parent
val visitParent = (isInverse || isRoot) && parent != null
val visitParent = (isParent || lastBone == null) && parent != null
// We are navigating inversely; this bone's node is at the head rather than
// the tail, so we let our origin child take our children, and we take our
// parent's children in turn
// Root is a special condition where it is both states simultaneously
val invChildren = if (visitParent) {
parent.children
} else {
emptyList()
}
val children = if (!isInverse) {
bone.children
} else {
emptyList()
}
val children = bone.children
val childCount = children.size - (if (isParent) 1 else 0)
val hasBranch = visitParent || children.isNotEmpty()
val hasBranch = visitParent || childCount > 0
header(
bone,
lastBone,
invertParentRot,
distance,
hasBranch,
invertOffset,
zeroOffset,
)
header(bone, lastBone, invertParentRot, distance, hasBranch, isParent)
if (hasBranch) {
// Cache this inverted rotation to reduce computation for each branch
val thisInvertRot = bone.rotationOffset * bone.getGlobalRotation().inv()
val thisInvertRot = bone.getGlobalRotation().inv()
if (visitParent) {
internalNavigateSkeleton(
parent,
header,
footer,
bone,
thisInvertRot,
distance + 1,
invertOffset || isInverse,
false,
)
}
for (child in invChildren) {
// Ignore our own bone (from parent's children)
if (child == bone) continue
internalNavigateSkeleton(
child,
header,
footer,
bone,
thisInvertRot,
distance + 1,
true,
!invertOffset,
)
internalNavigateSkeleton(parent, header, footer, bone, thisInvertRot, distance + 1, true)
}
for (child in children) {
internalNavigateSkeleton(
child,
header,
footer,
bone,
thisInvertRot,
distance + 1,
false,
invertOffset,
)
// If we're a parent, ignore the child
if (isParent && child == lastBone) continue
internalNavigateSkeleton(child, header, footer, bone, thisInvertRot, distance + 1, false)
}
}
@@ -138,17 +82,13 @@ class BVHFileStream : PoseDataStream {
private fun navigateSkeleton(
root: Bone,
header: (bone: Bone, lastBone: Bone?, invertParentRot: Quaternion, distance: Int, hasBranch: Boolean, invertOffset: Boolean, zeroOffset: Boolean) -> Unit,
header: (bone: Bone, lastBone: Bone?, invertParentRot: Quaternion, distance: Int, hasBranch: Boolean, isParent: Boolean) -> Unit,
footer: (distance: Int) -> Unit = {},
// Default true if the root isn't the true root (usually hip)
tailRoot: Boolean = root.parent != null,
) {
// Root is treated as a parent if we want to target the tail as the root node
internalNavigateSkeleton(root, header, footer, invertOffset = tailRoot)
internalNavigateSkeleton(root, header, footer)
}
private fun writeBoneDefHeader(bone: Bone?, lastBone: Bone?, invertParentRot: Quaternion, distance: Int, hasBranch: Boolean, invertOffset: Boolean, zeroOffset: Boolean) {
val isRoot = lastBone == null
private fun writeBoneDefHeader(bone: Bone?, lastBone: Bone?, invertParentRot: Quaternion, distance: Int, hasBranch: Boolean, isParent: Boolean) {
val indentLevel = StringUtils.repeat("\t", distance)
val nextIndentLevel = indentLevel + "\t"
@@ -156,23 +96,24 @@ class BVHFileStream : PoseDataStream {
if (bone == null) {
writer.write("${indentLevel}End Site\n")
} else {
writer.write("${indentLevel}${if (!isRoot) "JOINT" else "ROOT"} ${bone.boneType}\n")
writer
.write("${indentLevel}${if (distance > 0) "JOINT" else "ROOT"} ${bone.boneType}\n")
}
writer.write("$indentLevel{\n")
// "OFFSET": Defines the parent bone's local tail position
// Ignore the root and endpoint offsets
val offset = if (zeroOffset || isRoot) {
Vector3.NULL
if (bone != null && lastBone != null) {
writer.write(
"${nextIndentLevel}OFFSET 0.0 ${(if (isParent) lastBone.length else -lastBone.length) * bvhSettings.offsetScale} 0.0\n",
)
} else {
lastBone.rotationOffset.sandwichUnitY() * ((if (invertOffset) 1 else -1) * lastBone.length * bvhSettings.offsetScale)
writer.write("${nextIndentLevel}OFFSET 0.0 0.0 0.0\n")
}
writer.write("${nextIndentLevel}OFFSET ${offset.x} ${offset.y} ${offset.z}\n")
// Define channels
if (bone != null) {
// Only give position for root
if (!isRoot) {
if (lastBone != null) {
writer.write("${nextIndentLevel}CHANNELS 3 Zrotation Xrotation Yrotation\n")
} else {
writer.write(
@@ -184,15 +125,7 @@ class BVHFileStream : PoseDataStream {
// We use null for convenience and treat it as an end node (no bone)
if (!hasBranch) {
val endDistance = distance + 1
writeBoneDefHeader(
null,
bone,
Quaternion.IDENTITY,
endDistance,
hasBranch = false,
invertOffset = false,
zeroOffset = false,
)
writeBoneDefHeader(null, bone, Quaternion.IDENTITY, endDistance, false, false)
writeBoneDefFooter(endDistance)
}
}
@@ -228,22 +161,10 @@ class BVHFileStream : PoseDataStream {
writer.write("Frame Time: ${streamer.frameInterval}\n")
}
private fun writeBoneRot(bone: Bone, lastBone: Bone?, invertParentRot: Quaternion, distance: Int, hasBranch: Boolean, invertOffset: Boolean, zeroOffset: Boolean) {
val rot = bone.rotationOffset.inv() * invertParentRot * bone.getGlobalRotation()
private fun writeBoneRot(bone: Bone, lastBone: Bone?, invertParentRot: Quaternion, distance: Int, hasBranch: Boolean, isParent: Boolean) {
val rot = invertParentRot * bone.getGlobalRotation()
val angles = rot.toEulerAngles(EulerOrder.ZXY)
// We're the root, so write position
if (lastBone == null) {
val rootPos = if (invertOffset) {
bone.getTailPosition()
} else {
bone.getPosition()
}
// Write root position
val positionScale = bvhSettings.positionScale
writer.write("${rootPos.x * positionScale} ${rootPos.y * positionScale} ${rootPos.z * positionScale}")
}
// Output in order of roll (Z), pitch (X), yaw (Y) (extrinsic)
// Assume spacing is needed at the start (we start with position with no following space)
writer
@@ -253,6 +174,14 @@ class BVHFileStream : PoseDataStream {
@Throws(IOException::class)
override fun writeFrame(skeleton: HumanSkeleton) {
val rootBone = skeleton.getBone(bvhSettings.rootBone)
val rootPos = rootBone.getPosition()
// Write root position
val positionScale = bvhSettings.positionScale
writer
.write("${rootPos.x * positionScale} ${rootPos.y * positionScale} ${rootPos.z * positionScale}")
navigateSkeleton(rootBone, ::writeBoneRot)
writer.newLine()
@@ -11,6 +11,8 @@ import dev.slimevr.protocol.rpc.autobone.RPCAutoBoneHandler
import dev.slimevr.protocol.rpc.firmware.RPCFirmwareUpdateHandler
import dev.slimevr.protocol.rpc.games.vrchat.RPCVRChatHandler
import dev.slimevr.protocol.rpc.installinfo.RPCInstallInfoHandler
import dev.slimevr.protocol.rpc.keybinds.RPCKeybindHandler
import dev.slimevr.protocol.rpc.openuri.RPCOpenUriHandler
import dev.slimevr.protocol.rpc.reset.RPCResetHandler
import dev.slimevr.protocol.rpc.serial.RPCProvisioningHandler
import dev.slimevr.protocol.rpc.serial.RPCSerialHandler
@@ -54,6 +56,14 @@ class RPCHandler(private val api: ProtocolAPI) : ProtocolHandler<RpcMessageHeade
RPCTrackingChecklistHandler(this, api)
RPCUserHeightCalibration(this, api)
RPCInstallInfoHandler(this, api)
RPCOpenUriHandler(this, api)
try {
RPCKeybindHandler(this, api)
} catch (e: Exception) {
e.printStackTrace()
} catch (t: Throwable) {
t.printStackTrace()
}
registerPacketListener(
RpcMessage.AssignTrackerRequest,
@@ -32,12 +32,13 @@ class RPCInstallInfoHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) {
LogManager.warning("Server couldn't verify if udev is installed")
return
}
val response = udevResponse.contains("slime")
val isUdevInstalled = udevResponse.contains("slime")
val isWayland = System.getenv("XDG_SESSION_TYPE").lowercase().contains("wayland")
val fbb = FlatBufferBuilder(1024)
val outbound = this.rpcHandler.createRPCMessage(
fbb,
RpcMessage.InstalledInfoResponse,
createInstalledInfoResponse(fbb, response, false),
createInstalledInfoResponse(fbb, isUdevInstalled, isWayland),
)
fbb.finish(outbound)
conn.send(fbb.dataBuffer())
@@ -0,0 +1,76 @@
package dev.slimevr.protocol.rpc.keybinds
import com.google.flatbuffers.FlatBufferBuilder
import dev.slimevr.Keybinds
import dev.slimevr.config.KeybindData
import dev.slimevr.keybind.KeybindListener
import dev.slimevr.protocol.GenericConnection
import dev.slimevr.protocol.ProtocolAPI
import dev.slimevr.protocol.rpc.RPCHandler
import jdk.internal.joptsimple.internal.Messages.message
import solarxr_protocol.rpc.ChangeKeybindRequest
import solarxr_protocol.rpc.KeybindId
import solarxr_protocol.rpc.KeybindRequest
import solarxr_protocol.rpc.KeybindResponse
import solarxr_protocol.rpc.KeybindResponseT
import solarxr_protocol.rpc.KeybindT
import solarxr_protocol.rpc.RpcMessage
import solarxr_protocol.rpc.RpcMessageHeader
class RPCKeybindHandler(
var rpcHandler: RPCHandler,
var api: ProtocolAPI,
) : KeybindListener {
val keybindingConfig = api.server.configManager.vrConfig.keybindings
init {
this.api.server.keybindHandler.addListener(this)
rpcHandler.registerPacketListener(RpcMessage.KeybindRequest, ::onKeybindRequest)
rpcHandler.registerPacketListener(RpcMessage.ChangeKeybindRequest, ::onChangeKeybindRequest)
}
// TODO: Figure out a way to "refresh" the keybind array here.
private fun buildKeybindResponse(fbb: FlatBufferBuilder): Int = KeybindResponse.pack(
fbb,
KeybindResponseT().apply {
keybind = api.server.keybindHandler.keybinds.toTypedArray()
defaultKeybinds = api.server.keybindHandler.defaultKeybinds.toTypedArray()
},
)
private fun onKeybindRequest(conn: GenericConnection, messageHeader: RpcMessageHeader) {
val fbb = FlatBufferBuilder(32)
val response = buildKeybindResponse(fbb)
val outbound = rpcHandler.createRPCMessage(
fbb,
RpcMessage.KeybindResponse,
response,
)
fbb.finish(outbound)
conn.send(fbb.dataBuffer())
}
private fun onChangeKeybindRequest(conn: GenericConnection, messageHeader: RpcMessageHeader) {
val req = (messageHeader.message(ChangeKeybindRequest()) as ChangeKeybindRequest).unpack()
val keybind = Keybinds.getById(req.keybind.keybindId) ?: return
keybindingConfig.keybinds[keybind] = KeybindData(
req.keybind.keybindId,
req.keybind.keybindNameId,
req.keybind.keybindValue,
req.keybind.keybindDelay,
)
api.server.configManager.saveConfig()
api.server.keybindHandler.updateKeybinds()
}
override fun onKeybindUpdate() {
}
override fun sendKeybind() {
}
}
@@ -0,0 +1,21 @@
package dev.slimevr.protocol.rpc.openuri
import dev.hannah.portals.PortalManager
import dev.slimevr.SLIMEVR_IDENTIFIER
import dev.slimevr.protocol.GenericConnection
import dev.slimevr.protocol.ProtocolAPI
import dev.slimevr.protocol.rpc.RPCHandler
import solarxr_protocol.rpc.RpcMessage
import solarxr_protocol.rpc.RpcMessageHeader
class RPCOpenUriHandler(var rpcHandler: RPCHandler, var api: ProtocolAPI) {
init {
rpcHandler.registerPacketListener(RpcMessage.OpenUriRequest, ::onOpenUriRequest)
}
fun onOpenUriRequest(conn: GenericConnection, messageHeader: RpcMessageHeader?) {
val portalManager = PortalManager(SLIMEVR_IDENTIFIER)
portalManager.openGlobalShortcutsSettings()
}
}
@@ -26,40 +26,13 @@ import kotlin.math.sqrt
class HIDCommon {
companion object {
const val HID_TRACKER_RECEIVER_VID = 0x1209
const val HID_RECEIVER_PID = 0x7690
const val HID_TRACKER_RECEIVER_PID = 0x7690
const val HID_TRACKER_PID = 0x7692
const val GESTURES_INC_VID = 0x4E76
const val GESTURES_INC_PID_D2DX = 0xD2D0
const val GESTURES_INC_PID_D2DX_MASK = 0xFFF0
const val PACKET_SIZE = 16
private val AXES_OFFSET = fromRotationVector(-FastMath.HALF_PI, 0f, 0f)
data class HidProductRule(
val vendorId: Int,
val productId: Int,
val productMask: Int = 0xFFFF,
)
val receiverProductRules = listOf(
HidProductRule(HID_TRACKER_RECEIVER_VID, HID_RECEIVER_PID),
HidProductRule(GESTURES_INC_VID, GESTURES_INC_PID_D2DX, GESTURES_INC_PID_D2DX_MASK),
)
val trackerProductRules = listOf(
HidProductRule(HID_TRACKER_RECEIVER_VID, HID_TRACKER_PID),
)
private fun matchesProductRule(vendorId: Int, productId: Int, rule: HidProductRule): Boolean = vendorId == rule.vendorId && (productId and rule.productMask) == rule.productId
fun allProductRules(): List<HidProductRule> = (receiverProductRules + trackerProductRules)
fun matchesReceiver(vendorId: Int, productId: Int): Boolean = receiverProductRules.any { matchesProductRule(vendorId, productId, it) }
fun matchesTracker(vendorId: Int, productId: Int): Boolean = trackerProductRules.any { matchesProductRule(vendorId, productId, it) }
fun matchesAny(vendorId: Int, productId: Int): Boolean = allProductRules().any { matchesProductRule(vendorId, productId, it) }
fun deviceIdLookup(
hidDevices: MutableList<HIDDevice>,
hidSerialNumber: String?,
+1 -2
View File
@@ -47,7 +47,6 @@ tasks.withType<Javadoc> {
allprojects {
repositories {
// Use jcenter for resolving dependencies.
// You can declare any Maven/Ivy/file repository here.
mavenCentral()
maven(url = "https://jitpack.io")
maven(url = "https://oss.sonatype.org/content/repositories/snapshots")
@@ -74,7 +73,7 @@ tasks.shadowJar {
exclude(dependency("com.fazecast:jSerialComm:.*"))
exclude(dependency("net.java.dev.jna:.*:.*"))
exclude(dependency("com.google.flatbuffers:flatbuffers-java:.*"))
exclude(dependency("com.github.HannahPadd:DbusGlobalShortcutsWayland:v0.1.0"))
exclude(project(":solarxr-protocol"))
}
archiveBaseName.set("slimevr")
@@ -6,6 +6,9 @@ import dev.slimevr.tracking.trackers.Device
import dev.slimevr.tracking.trackers.Tracker
import dev.slimevr.tracking.trackers.TrackerStatus
import dev.slimevr.tracking.trackers.hid.HIDCommon
import dev.slimevr.tracking.trackers.hid.HIDCommon.Companion.HID_TRACKER_PID
import dev.slimevr.tracking.trackers.hid.HIDCommon.Companion.HID_TRACKER_RECEIVER_PID
import dev.slimevr.tracking.trackers.hid.HIDCommon.Companion.HID_TRACKER_RECEIVER_VID
import dev.slimevr.tracking.trackers.hid.HIDCommon.Companion.PACKET_SIZE
import dev.slimevr.tracking.trackers.hid.HIDDevice
import io.eiren.util.logging.LogManager
@@ -55,7 +58,7 @@ class DesktopHIDManager(name: String, private val trackersConsumer: Consumer<Tra
}
private fun checkConfigureDevice(hidDevice: HidDevice) {
if (HIDCommon.matchesAny(hidDevice.vendorId, hidDevice.productId)) {
if (hidDevice.vendorId == HID_TRACKER_RECEIVER_VID && (hidDevice.productId == HID_TRACKER_RECEIVER_PID || hidDevice.productId == HID_TRACKER_PID)) { // TODO: Use list of valid ids
val serial = hidDevice.serialNumber ?: "Unknown HID Device"
if (hidDevice.isClosed) {
if (!hidDevice.open()) {
@@ -210,28 +213,37 @@ class DesktopHIDManager(name: String, private val trackersConsumer: Consumer<Tra
}
private fun deviceEnumerate() {
var rootReceivers: HidDeviceInfoStructure? = null
var rootTrackers: HidDeviceInfoStructure? = null
val trackersOverHID: Boolean = VRServer.instance.configManager.vrConfig.hidConfig.trackersOverHID
try {
rootReceivers = HidApi.enumerateDevices(HID_TRACKER_RECEIVER_VID, HID_TRACKER_RECEIVER_PID) // TODO: Use list of ids
rootTrackers = if (trackersOverHID) {
HidApi.enumerateDevices(HID_TRACKER_RECEIVER_VID, HID_TRACKER_PID)
} else {
null
} // TODO: Use list of ids
} catch (e: Throwable) {
LogManager.severe("[TrackerServer] Couldn't enumerate HID devices", e)
}
var root: HidDeviceInfoStructure? = rootReceivers
if (root == null) {
root = rootTrackers
} else {
var last: HidDeviceInfoStructure = root
while (last.hasNext()) {
last = last.next()
}
last.next = rootTrackers
}
val hidDeviceList: MutableList<HidDevice> = mutableListOf()
for (rule in HIDCommon.allProductRules()) {
var root: HidDeviceInfoStructure? = null
try {
root = HidApi.enumerateDevices(rule.vendorId, if (rule.productMask == 0xFFFF) rule.productId else 0)
} catch (e: Throwable) {
LogManager.severe("[TrackerServer] Couldn't enumerate HID devices using rule ${String.format("%04x:%04x", rule.vendorId, rule.productId)} & ${String.format("0x%04X", rule.productMask)}", e)
}
if (root != null) {
var hidDeviceInfoStructure: HidDeviceInfoStructure? = root
do {
val hidDevice = HidDevice(hidDeviceInfoStructure, null, hidServicesSpecification)
val isReceiver = HIDCommon.matchesReceiver(hidDevice.vendorId, hidDevice.productId)
val isTracker = HIDCommon.matchesTracker(hidDevice.vendorId, hidDevice.productId)
if (isReceiver || (trackersOverHID && isTracker)) {
hidDeviceList.add(hidDevice)
}
hidDeviceInfoStructure = hidDeviceInfoStructure?.next()
} while (hidDeviceInfoStructure != null)
HidApi.freeEnumeration(root)
}
if (root != null) {
var hidDeviceInfoStructure: HidDeviceInfoStructure? = root
do {
hidDeviceList.add(HidDevice(hidDeviceInfoStructure, null, hidServicesSpecification))
hidDeviceInfoStructure = hidDeviceInfoStructure?.next()
} while (hidDeviceInfoStructure != null)
HidApi.freeEnumeration(root)
}
synchronized(devicesByHID) {
// Work on devicesByHid and add/remove as necessary