From c975680b069b8bcf7ba60eb44d0b85ee6f78f77b Mon Sep 17 00:00:00 2001 From: loucass003 Date: Tue, 13 Oct 2026 21:06:57 +0200 Subject: [PATCH] Settings profile ui --- gui/app/public/i18n/en/translation.ftl | 42 +- gui/app/src/App.tsx | 2 + gui/app/src/components/EmptyLayout.tsx | 2 +- gui/app/src/components/ProfileQuickSwitch.tsx | 249 +++++++++ gui/app/src/components/TopBar.tsx | 4 + gui/app/src/components/commons/Drawer.tsx | 87 ++++ gui/app/src/components/commons/Tooltip.tsx | 70 +-- .../src/components/commons/icon/CopyIcon.tsx | 13 + .../components/commons/icon/PencilIcon.tsx | 12 + .../src/components/commons/icon/PlusIcon.tsx | 12 + .../onboarding/OnboardingLayout.tsx | 1 + .../src/components/settings/QuickSearch.tsx | 12 +- .../components/settings/SettingsLayout.tsx | 4 + .../components/settings/SettingsSidebar.tsx | 6 +- .../settings/pages/ProfilesSettings.tsx | 487 ++++++++++++++++++ .../components/settings/settings-pages.tsx | 5 + gui/app/src/hooks/profiles.ts | 98 ++++ .../main/java/dev/slimevr/config/module.kt | 22 +- .../java/dev/slimevr/config/ProfilesTest.kt | 68 +++ .../dev/slimevr/solarxr/SettingsResetTest.kt | 13 +- 20 files changed, 1145 insertions(+), 64 deletions(-) create mode 100644 gui/app/src/components/ProfileQuickSwitch.tsx create mode 100644 gui/app/src/components/commons/Drawer.tsx create mode 100644 gui/app/src/components/commons/icon/CopyIcon.tsx create mode 100644 gui/app/src/components/commons/icon/PencilIcon.tsx create mode 100644 gui/app/src/components/commons/icon/PlusIcon.tsx create mode 100644 gui/app/src/components/settings/pages/ProfilesSettings.tsx create mode 100644 gui/app/src/hooks/profiles.ts diff --git a/gui/app/public/i18n/en/translation.ftl b/gui/app/public/i18n/en/translation.ftl index 8b58cf0a3..4f5b43af9 100644 --- a/gui/app/public/i18n/en/translation.ftl +++ b/gui/app/public/i18n/en/translation.ftl @@ -58,6 +58,11 @@ titlebar-update = Download update titlebar-minimize = Minimize titlebar-maximize = Maximize titlebar-close = Close +titlebar-profiles = Profiles +titlebar-profiles-tooltip = Switch settings and user profiles +titlebar-profiles-settings = Settings +titlebar-profiles-user = User +titlebar-profiles-manage = Manage profiles ## Body parts @@ -431,6 +436,34 @@ mounting_selection_menu-close = Close ## Sidebar settings settings-advanced_section = Advanced settings +settings-sidebar-profiles = Profiles +settings-profiles-settings = Settings profiles +settings-profiles-settings-description = Your setup: trackers, outputs, resets, keybinds and every other setting. Switching applies it right away. +settings-profiles-user = User profiles +settings-profiles-user-description = The person wearing the trackers: height and body proportions. +settings-profiles-new_settings = New profile +settings-profiles-new_user = New profile +settings-profiles-default_name = Profile { $n } +settings-profiles-start_from = Start from +settings-profiles-start_from-defaults = Defaults +settings-profiles-start_from-copy = Copy of { $name } +settings-profiles-name = Profile name +settings-profiles-create = Create +settings-profiles-save = Save +settings-profiles-cancel = Cancel +settings-profiles-rename = Rename +settings-profiles-duplicate = Duplicate +settings-profiles-delete = Delete +settings-profiles-delete-active = Select another profile to delete this one +settings-profiles-delete_action = Delete +settings-profiles-delete_confirm = Delete "{ $name }"? This can't be undone. +settings-profiles-copy_name = { $name } copy +settings-profiles-error-invalid_kind = The profile type is missing. +settings-profiles-error-invalid_name = Names can only contain letters, numbers, spaces, - and _, up to 64 characters. +settings-profiles-error-already_exists = A profile with this name already exists. +settings-profiles-error-not_found = This profile doesn't exist anymore. +settings-profiles-error-is_active = The selected profile can't be deleted. Select another one first. +settings-profiles-error-failed = The server couldn't save the profile files. settings-sidebar-search = Search settings and pages settings-sidebar-search-empty = Nothing matches your search settings-sidebar-search-hint = Type to search every setting and page @@ -963,17 +996,20 @@ settings-utils-advanced-reset-gui = Reset GUI settings settings-utils-advanced-reset-gui-description = Restore the default settings for the interface. settings-utils-advanced-reset-gui-label = Reset GUI settings-utils-advanced-reset-server = Reset tracking settings -settings-utils-advanced-reset-server-description = Restore the default settings for the tracking. +settings-utils-advanced-reset-server-description = Switch back to the default profiles and restore their default tracking settings. settings-utils-advanced-reset-server-label = Reset tracking settings-utils-advanced-reset-all = Reset all settings -settings-utils-advanced-reset-all-description = Restore the default settings for both the interface and tracking. +settings-utils-advanced-reset-all-description = Restore the default settings for the interface, and switch back to the default profiles with their default tracking settings. settings-utils-advanced-reset-all-label = Reset all settings-utils-advanced-reset_warning = Warning: This will reset { $type -> [gui] your GUI [server] your tracking *[all] all your - } settings to the defaults. + } settings to the defaults.{ $type -> + [gui] {""} + *[other] {" "}You will be switched back to the default settings and user profiles. + } Are you sure you want to do this? settings-utils-advanced-reset_warning-reset = Reset settings settings-utils-advanced-reset_warning-cancel = Cancel diff --git a/gui/app/src/App.tsx b/gui/app/src/App.tsx index b6e03029d..69f261d48 100644 --- a/gui/app/src/App.tsx +++ b/gui/app/src/App.tsx @@ -71,6 +71,7 @@ import { ERROR_REPORTING_CONSENT_PATH, } from './components/AppStatusGate'; import { useProvideErrorReporting } from './hooks/error-reporting'; +import { useProvideProfiles } from './hooks/profiles'; export const GH_REPO = 'SlimeVR/SlimeVR-Server'; export const VersionContext = createContext(''); @@ -100,6 +101,7 @@ function ConnectedApp() { function AppRoutes() { const { isMobile } = useBreakpoint('mobile'); useProvideErrorReporting(); + useProvideProfiles(); useProvideSettingsDefaults(); useDiscordPresence(); useControllerNav(); diff --git a/gui/app/src/components/EmptyLayout.tsx b/gui/app/src/components/EmptyLayout.tsx index 142b3a642..c19d83659 100644 --- a/gui/app/src/components/EmptyLayout.tsx +++ b/gui/app/src/components/EmptyLayout.tsx @@ -10,7 +10,7 @@ export function EmptyLayout({ children }: { children: ReactNode }) { data-nav-area="topbar" style={{ gridArea: 't' }} > - +
void; +}) { + const listRef = useRef(null); + + // Long lists open scrolled to the active profile + useEffect(() => { + const list = listRef.current; + if (!open || !list) return; + const active = list.querySelector('[aria-current]'); + if (!active) return; + list.scrollTop = + active.offsetTop - list.clientHeight / 2 + active.offsetHeight / 2; + }, [open]); + + return ( +
+
+ {icon} + +
+
    + {profiles.names.map((name) => { + const active = name === profiles.active; + return ( +
  • + onSelect(name)} + className={classNames( + 'flex w-full items-center gap-2 px-4 py-2 mobile:py-3 hover:bg-background-50', + active && 'bg-background-50/50' + )} + > + + {active && } + + + + {name} + + + +
  • + ); + })} +
+
+ ); +} + +function ProfileMenu({ + profiles, + open, + onClose, +}: { + profiles: Profiles; + open: boolean; + onClose: () => void; +}) { + const { switchProfile } = useProfileOperations(); + + const select = (kind: ProfileKind, active: string, name: string) => { + onClose(); + if (name !== active) switchProfile(kind, name); + }; + + return ( +
+ } + profiles={profiles.settings} + open={open} + onSelect={(name) => + select(ProfileKind.SETTINGS, profiles.settings.active, name) + } + /> + } + profiles={profiles.user} + open={open} + onSelect={(name) => + select(ProfileKind.USER, profiles.user.active, name) + } + /> + + + +
+ ); +} + +export function ProfileQuickSwitch() { + const { l10n } = useLocalization(); + const { isMobile } = useBreakpoint('mobile'); + const profiles = useProfiles(); + const [open, setOpen] = useState(false); + const popoverRef = useRef(null); + const id = `profile-switch-${useId().replace(/:/g, '')}`; + const anchorName = `--${id}`; + + useEffect(() => { + const el = popoverRef.current; + if (!el) return; + el.setAttribute('popover', 'auto'); + const onToggle = (e: Event) => + setOpen((e as ToggleEvent).newState === 'open'); + el.addEventListener('toggle', onToggle); + return () => el.removeEventListener('toggle', onToggle); + }, [profiles !== null, isMobile]); + + if (!profiles) return null; + + const close = () => { + popoverRef.current?.hidePopover(); + setOpen(false); + }; + + return ( + <> +
+ } + > + + +
+ {isMobile ? ( + } + > +
+ +
+
+ ) : ( +
+ +
+ )} + + ); +} diff --git a/gui/app/src/components/TopBar.tsx b/gui/app/src/components/TopBar.tsx index af716dd76..af4d73eb7 100644 --- a/gui/app/src/components/TopBar.tsx +++ b/gui/app/src/components/TopBar.tsx @@ -36,6 +36,7 @@ import { useAtomValue } from 'jotai'; import { connectedIMUTrackersAtom } from '@/store/app-store'; import { useElectron } from '@/hooks/electron'; import { openUrl } from '@/hooks/crossplatform'; +import { ProfileQuickSwitch } from './ProfileQuickSwitch'; // Title bar buttons share one round hit target. const TITLE_BAR_BUTTON_CLASS = @@ -82,10 +83,12 @@ export function VersionTag() { export function TopBar({ progress, actions, + profiles = true, }: { children?: ReactNode; progress?: number; actions?: ReactNode; + profiles?: boolean; }) { const electron = useElectron(); const quickSearch = useQuickSearch(); @@ -219,6 +222,7 @@ export function TopBar({
{actions} + {profiles && } {quickSearch && ( void; + title: ReactNode; + children: ReactNode; +}) { + const ref = useRef(null); + const [shown, setShown] = useState(false); + + const setRef = (node: HTMLDivElement | null) => { + node?.setAttribute('popover', 'manual'); + ref.current = node; + }; + + useLayoutEffect(() => { + const el = ref.current; + if (!el) return; + if (!isOpen) { + setShown(false); + const timeout = setTimeout(() => { + if (el.matches(':popover-open')) el.hidePopover(); + }, SLIDE_MS); + return () => clearTimeout(timeout); + } + if (!el.matches(':popover-open')) el.showPopover(); + el.getBoundingClientRect(); + setShown(true); + }, [isOpen]); + + useEffect(() => { + if (!isOpen) return; + const onKeyDown = (e: KeyboardEvent) => { + if (e.key === 'Escape') onClose(); + }; + window.addEventListener('keydown', onKeyDown); + return () => window.removeEventListener('keydown', onKeyDown); + }, [isOpen, onClose]); + + return ( +
+
+
+
+
+ {title} + + + +
+
+ {children} +
+
+
+
+ ); +} diff --git a/gui/app/src/components/commons/Tooltip.tsx b/gui/app/src/components/commons/Tooltip.tsx index a562c9210..a4086458c 100644 --- a/gui/app/src/components/commons/Tooltip.tsx +++ b/gui/app/src/components/commons/Tooltip.tsx @@ -13,7 +13,7 @@ import { } from 'react'; import { createPortal } from 'react-dom'; import { Typography } from './Typography'; -import { CloseIcon } from './icon/CloseIcon'; +import { Drawer } from './Drawer'; import { focusVisible } from '@/utils/focus-nav'; export type Direction = 'top' | 'left' | 'right' | 'bottom'; @@ -202,10 +202,6 @@ export function FloatingTooltip({ const TOOLTIP_DELAY = 500; -interface DrawerStyle { - bottom: number; -} - export function DrawerTooltip({ children, childRef, @@ -215,10 +211,7 @@ export function DrawerTooltip({ }) { const touchTimestamp = useRef(0); const touchTimeout = useRef(0); - const drawerRef = useRef(null); - const [drawerStyle, setDrawerStyle] = useState( - undefined - ); + const [isOpen, setIsOpen] = useState(false); const touchStart = () => { if (childRef.current && childRef.current.children[0]) { @@ -266,16 +259,13 @@ export function DrawerTooltip({ }; const open = () => { - if (drawerStyle) return; + if (isOpen) return; clearEffect(); - - if (!drawerRef.current) throw new Error('invalid state'); - - setDrawerStyle({ bottom: 0 }); + setIsOpen(true); }; const close = () => { - setDrawerStyle(undefined); + setIsOpen(false); }; useLayoutEffect(() => { @@ -301,45 +291,17 @@ export function DrawerTooltip({ // FIXME: Completely broken not sure why. Will be solved when tooltips on mobile actually work return ( - <> -
close()} - style={{ - opacity: drawerStyle ? 0.5 : 0, - pointerEvents: drawerStyle ? 'all' : 'none', - }} - /> -
-
-
- - Pro tip - - -
-
- {children} -
-
-
- + + Pro tip + + } + > +
{children}
+
); } diff --git a/gui/app/src/components/commons/icon/CopyIcon.tsx b/gui/app/src/components/commons/icon/CopyIcon.tsx new file mode 100644 index 000000000..672cad092 --- /dev/null +++ b/gui/app/src/components/commons/icon/CopyIcon.tsx @@ -0,0 +1,13 @@ +export function CopyIcon({ size = 24 }: { size?: number }) { + return ( + + + + + ); +} diff --git a/gui/app/src/components/commons/icon/PencilIcon.tsx b/gui/app/src/components/commons/icon/PencilIcon.tsx new file mode 100644 index 000000000..7bef9f4a5 --- /dev/null +++ b/gui/app/src/components/commons/icon/PencilIcon.tsx @@ -0,0 +1,12 @@ +export function PencilIcon({ size = 24 }: { size?: number }) { + return ( + + + + ); +} diff --git a/gui/app/src/components/commons/icon/PlusIcon.tsx b/gui/app/src/components/commons/icon/PlusIcon.tsx new file mode 100644 index 000000000..f48e992f6 --- /dev/null +++ b/gui/app/src/components/commons/icon/PlusIcon.tsx @@ -0,0 +1,12 @@ +export function PlusIcon({ size = 24 }: { size?: number }) { + return ( + + + + ); +} diff --git a/gui/app/src/components/onboarding/OnboardingLayout.tsx b/gui/app/src/components/onboarding/OnboardingLayout.tsx index afdca0b9a..f672494a0 100644 --- a/gui/app/src/components/onboarding/OnboardingLayout.tsx +++ b/gui/app/src/components/onboarding/OnboardingLayout.tsx @@ -20,6 +20,7 @@ export function OnboardingLayout({ children }: { children: ReactNode }) { style={{ gridArea: 't' }} > - - + + + + {SHORTCUT_LABEL} diff --git a/gui/app/src/components/settings/SettingsLayout.tsx b/gui/app/src/components/settings/SettingsLayout.tsx index a2305f74d..8df55cc6e 100644 --- a/gui/app/src/components/settings/SettingsLayout.tsx +++ b/gui/app/src/components/settings/SettingsLayout.tsx @@ -32,6 +32,10 @@ export function SettingSelectorMobile() { label: l10n.getString('settings-sidebar-stay_aligned'), url: '/settings/stay-aligned', }, + { + label: l10n.getString('settings-sidebar-profiles'), + url: '/settings/profiles', + }, { label: l10n.getString('settings-sidebar-appearance'), url: '/settings/appearance', diff --git a/gui/app/src/components/settings/SettingsSidebar.tsx b/gui/app/src/components/settings/SettingsSidebar.tsx index 0b0713b04..7aa5a08f1 100644 --- a/gui/app/src/components/settings/SettingsSidebar.tsx +++ b/gui/app/src/components/settings/SettingsSidebar.tsx @@ -23,7 +23,7 @@ export function SettingsSidebar() { const { state: vrcConfigState } = useVRCConfig(); return ( -
+
@@ -41,6 +41,10 @@ export function SettingsSidebar() { to="/settings/stay-aligned" id="settings-sidebar-stay_aligned" /> +
diff --git a/gui/app/src/components/settings/pages/ProfilesSettings.tsx b/gui/app/src/components/settings/pages/ProfilesSettings.tsx new file mode 100644 index 000000000..584e7856f --- /dev/null +++ b/gui/app/src/components/settings/pages/ProfilesSettings.tsx @@ -0,0 +1,487 @@ +import classNames from 'classnames'; +import { KeyboardEvent, ReactNode, useEffect, useRef, useState } from 'react'; +import { useLocalization } from '@fluent/react'; +import { ProfileKind, ProfileOperationStatus } from 'solarxr-protocol'; +import { Button } from '@/components/commons/Button'; +import { Clickable } from '@/components/commons/Clickable'; +import { CheckIcon } from '@/components/commons/icon/CheckIcon'; +import { CopyIcon } from '@/components/commons/icon/CopyIcon'; +import { FolderIcon } from '@/components/commons/icon/FolderIcon'; +import { PencilIcon } from '@/components/commons/icon/PencilIcon'; +import { PlusIcon } from '@/components/commons/icon/PlusIcon'; +import { TrashIcon } from '@/components/commons/icon/TrashIcon'; +import { IconButton } from '@/components/commons/IconButton'; +import { InputInside } from '@/components/commons/Input'; +import { Typography } from '@/components/commons/Typography'; +import { + ProfileNames, + profileErrorId, + useProfileOperations, + useProfiles, +} from '@/hooks/profiles'; +import { + SettingsGroup, + useFocusSetting, +} from '@/components/settings/SettingRow'; +import { + SettingDef, + SettingsGroupDef, + defineSettingsPage, +} from '@/components/settings/settings-definitions'; +import { SettingsPagePaneLayout } from '@/components/settings/SettingsPagePaneLayout'; + +export const profilesSettingsPage = defineSettingsPage({ + path: 'profiles', + title: 'settings-sidebar-profiles', + groups: { + settings: { + title: 'settings-profiles-settings', + description: 'settings-profiles-settings-description', + rows: { create: { title: 'settings-profiles-new_settings' } }, + }, + user: { + title: 'settings-profiles-user', + description: 'settings-profiles-user-description', + rows: { create: { title: 'settings-profiles-new_user' } }, + }, + }, +}); + +type Operations = ReturnType; + +function withoutIsolates(text: string) { + return text.replace(/[\u2066-\u2069]/g, ''); +} + +function ErrorLine({ status }: { status: ProfileOperationStatus | null }) { + if (status === null) return null; + return ( + + ); +} + +function InlineNameEditor({ + initial, + unchangedFrom, + confirmId, + onConfirm, + onCancel, + children, +}: { + initial: string; + unchangedFrom?: string; + confirmId: string; + onConfirm: (name: string) => Promise; + onCancel: () => void; + children?: ReactNode; +}) { + const { l10n } = useLocalization(); + const inputRef = useRef(null); + const [name, setName] = useState(initial); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + useEffect(() => { + inputRef.current?.focus(); + inputRef.current?.select(); + }, []); + + const trimmed = name.trim(); + const canConfirm = !busy && trimmed.length > 0 && trimmed !== unchangedFrom; + + const confirm = async () => { + if (!canConfirm) return; + setBusy(true); + const status = await onConfirm(trimmed); + setBusy(false); + if (status !== ProfileOperationStatus.OK) setError(status); + }; + + const onKeyDown = (e: KeyboardEvent) => { + if (e.key === 'Enter') { + e.preventDefault(); + confirm(); + return; + } + if (e.key === 'Escape') { + e.stopPropagation(); + onCancel(); + } + }; + + return ( +
+
+
+ { + setName(e.currentTarget.value); + setError(null); + }} + /> +
+
+ {children} + +
+ ); +} + +type RowMode = 'idle' | 'rename' | 'duplicate' | 'delete'; + +function ProfileRow({ + kind, + name, + active, + operations, +}: { + kind: ProfileKind; + name: string; + active: boolean; + operations: Operations; +}) { + const { l10n } = useLocalization(); + const [mode, setMode] = useState('idle'); + const [error, setError] = useState(null); + + const finish = (status: ProfileOperationStatus) => { + if (status === ProfileOperationStatus.OK) { + setMode('idle'); + setError(null); + } else { + setError(status); + } + return status; + }; + + return ( +
+ {mode === 'idle' && ( +
+ { + if (!active) operations.switchProfile(kind, name).then(finish); + }} + > + + {active && } + + + {name} + + +
+ setMode('rename')} + > + + + setMode('duplicate')} + > + + + setMode('delete')} + > + + +
+
+ )} + {mode !== 'idle' && ( +
+ {mode === 'rename' && ( + + operations.renameProfile(kind, name, newName).then(finish) + } + onCancel={() => setMode('idle')} + /> + )} + {mode === 'duplicate' && ( + + operations.createProfile(kind, newName, name).then(finish) + } + onCancel={() => setMode('idle')} + /> + )} + {mode === 'delete' && ( +
+ +
+
+
+ )} + {mode === 'delete' && } +
+ )} + {mode === 'idle' && error !== null && ( +
+ +
+ )} +
+ ); +} + +function freeProfileName(template: (n: number) => string, names: string[]) { + const taken = new Set(names.map((name) => name.toLowerCase())); + let n = names.length + 1; + while (taken.has(template(n).toLowerCase())) n++; + return template(n); +} + +function StartFromOption({ + selected, + onClick, + children, +}: { + selected: boolean; + onClick: () => void; + children: ReactNode; +}) { + return ( + + + {selected && ( + + )} + + {children} + + ); +} + +function NewProfileRow({ + kind, + setting, + profiles, + operations, +}: { + kind: ProfileKind; + setting: SettingDef; + profiles: ProfileNames; + operations: Operations; +}) { + const { l10n } = useLocalization(); + const { ref, highlighted } = useFocusSetting(setting.key); + const [creating, setCreating] = useState(false); + const [copyActive, setCopyActive] = useState(false); + + const close = () => { + setCreating(false); + setCopyActive(false); + }; + + return ( +
+ {!creating && ( + setCreating(true)} + className="group flex w-full items-center gap-3 px-3 py-3 xs:px-4 cursor-pointer fill-background-10 transition-colors hover:bg-background-70/30" + > + + + + + + )} + {creating && ( +
+ +
+ + l10n.getString('settings-profiles-default_name', { n }), + profiles.names + ) + )} + confirmId="settings-profiles-create" + onConfirm={async (name) => { + const status = await operations.createProfile( + kind, + name, + copyActive ? profiles.active : '' + ); + if (status === ProfileOperationStatus.OK) close(); + return status; + }} + onCancel={close} + > +
+ +
+ setCopyActive(false)} + > + + + setCopyActive(true)} + > + + +
+
+
+
+
+ )} +
+ ); +} + +function ProfileGroup({ + kind, + group, + profiles, + operations, +}: { + kind: ProfileKind; + group: SettingsGroupDef<'create'>; + profiles: ProfileNames; + operations: Operations; +}) { + return ( + + {profiles.names.map((name) => ( + + ))} + + + ); +} + +export function ProfilesSettings() { + const profiles = useProfiles(); + const operations = useProfileOperations(); + + return ( + } + title={profilesSettingsPage.title} + > + {profiles && ( + <> + + + + )} + + ); +} diff --git a/gui/app/src/components/settings/settings-pages.tsx b/gui/app/src/components/settings/settings-pages.tsx index e0d55bbfd..abd7ef859 100644 --- a/gui/app/src/components/settings/settings-pages.tsx +++ b/gui/app/src/components/settings/settings-pages.tsx @@ -26,6 +26,10 @@ import { HomeScreenSettings } from './pages/HomeScreenSettings'; import { checklistSettingsPage } from './pages/components/TrackingChecklistSettings'; import { ChecklistSettings } from './pages/ChecklistSettings'; import { keybindSettingsPage, KeybindSettings } from './pages/KeybindSettings'; +import { + profilesSettingsPage, + ProfilesSettings, +} from './pages/ProfilesSettings'; import { boneRoutingSettingsPage, BoneRoutingSettings, @@ -58,6 +62,7 @@ export const settingsPages: SettingsPageRoute[] = [ { page: trackersSettingsPage, element: }, { page: resetsSettingsPage, element: }, { page: stayAlignedSettingsPage, element: }, + { page: profilesSettingsPage, element: }, { page: appearanceSettingsPage, element: }, { page: behaviorSettingsPage, element: }, { page: homeSettingsPage, element: }, diff --git a/gui/app/src/hooks/profiles.ts b/gui/app/src/hooks/profiles.ts new file mode 100644 index 000000000..15b0b3d42 --- /dev/null +++ b/gui/app/src/hooks/profiles.ts @@ -0,0 +1,98 @@ +import { useEffect, useRef } from 'react'; +import { atom, useAtomValue, useSetAtom } from 'jotai'; +import { + CreateProfileRequestT, + DeleteProfileRequestT, + ProfileKind, + ProfileListT, + ProfileOperationResponseT, + ProfileOperationStatus, + ProfilesRequestT, + ProfilesResponseT, + RenameProfileRequestT, + RpcMessage, + SwitchProfileRequestT, +} from 'solarxr-protocol'; +import { useWebsocketAPI } from './websocket-api'; + +export type ProfileNames = { + active: string; + names: string[]; +}; + +export type Profiles = { + settings: ProfileNames; + user: ProfileNames; +}; + +export const profilesAtom = atom(null); + +function toProfileNames(list: ProfileListT | null): ProfileNames { + return { + active: list?.active?.toString() ?? '', + names: list?.names.map((name) => name.toString()) ?? [], + }; +} + +export function useProvideProfiles() { + const { useRPCPacket, sendRPCPacket, isConnected } = useWebsocketAPI(); + const setProfiles = useSetAtom(profilesAtom); + + useEffect(() => { + if (!isConnected) return; + sendRPCPacket(RpcMessage.ProfilesRequest, new ProfilesRequestT()); + }, [isConnected]); + + useRPCPacket(RpcMessage.ProfilesResponse, (res: ProfilesResponseT) => + setProfiles({ + settings: toProfileNames(res.settings), + user: toProfileNames(res.user), + }) + ); +} + +export function useProfiles() { + return useAtomValue(profilesAtom); +} + +export function useProfileOperations() { + const { useRPCPacket, sendRPCPacket } = useWebsocketAPI(); + const waiting = useRef<((status: ProfileOperationStatus) => void) | null>(null); + + useRPCPacket( + RpcMessage.ProfileOperationResponse, + (res: ProfileOperationResponseT) => { + waiting.current?.(res.status); + waiting.current = null; + } + ); + + function run(type: RpcMessage, request: Parameters[1]) { + return new Promise((resolve) => { + waiting.current = resolve; + sendRPCPacket(type, request); + }); + } + + return { + switchProfile: (kind: ProfileKind, name: string) => + run(RpcMessage.SwitchProfileRequest, new SwitchProfileRequestT(kind, name)), + createProfile: (kind: ProfileKind, name: string, copyFrom: string) => + run( + RpcMessage.CreateProfileRequest, + new CreateProfileRequestT(kind, name, copyFrom) + ), + renameProfile: (kind: ProfileKind, name: string, newName: string) => + run( + RpcMessage.RenameProfileRequest, + new RenameProfileRequestT(kind, name, newName) + ), + deleteProfile: (kind: ProfileKind, name: string) => + run(RpcMessage.DeleteProfileRequest, new DeleteProfileRequestT(kind, name)), + }; +} + +/** Fluent id of the message for a failed operation. */ +export function profileErrorId(status: ProfileOperationStatus) { + return `settings-profiles-error-${ProfileOperationStatus[status].toLowerCase()}`; +} diff --git a/server/core/src/main/java/dev/slimevr/config/module.kt b/server/core/src/main/java/dev/slimevr/config/module.kt index 728027849..6f8631695 100644 --- a/server/core/src/main/java/dev/slimevr/config/module.kt +++ b/server/core/src/main/java/dev/slimevr/config/module.kt @@ -249,15 +249,35 @@ class AppConfig( ProfileOperationStatus.OK } - fun reset() { + /** + * Switches both kinds back to the default profile and restores its default values. Other profiles are kept. + * A deleted default profile is created again. + */ + suspend fun reset() = profilesLock.withLock { + val defaults = GlobalConfigState() + val settingsName = defaultProfileName(ProfileKind.SETTINGS, defaults.selectedSettingsProfile) + if (settings.context.state.value.name != settingsName) { + globalConfig.context.dispatch(GlobalConfigActions.SetSettingsProfile(settingsName)) + settings.swap(settingsName) + } + val userName = defaultProfileName(ProfileKind.USER, defaults.selectedUserProfile) + if (userConfig.context.state.value.name != userName) { + globalConfig.context.dispatch(GlobalConfigActions.SetUserProfile(userName)) + userConfig.swap(userName) + } settings.context.dispatch(SettingsActions.Update { SettingsConfigState() }) userConfig.context.dispatch(UserConfigActions.Update { UserConfigData() }) val errorReporting = globalConfig.context.state.value.errorReporting globalConfig.context.dispatch( GlobalConfigActions.SetErrorReporting(changeConsent(errorReporting, ErrorReportingConsent.UNDECIDED)), ) + refreshProfiles() } + // A profile named like the default in another case is the same file on case-insensitive filesystems + private suspend fun defaultProfileName(kind: ProfileKind, name: String): String = + listProfiles(kind).firstOrNull { it.equals(name, ignoreCase = true) } ?: name + companion object { suspend fun create(scope: CoroutineScope, storage: ConfigStorage): AppConfig { val globalConfig = GlobalConfig.create(scope, storage) diff --git a/server/core/src/test/java/dev/slimevr/config/ProfilesTest.kt b/server/core/src/test/java/dev/slimevr/config/ProfilesTest.kt index 083eeaf66..8af1fa6c5 100644 --- a/server/core/src/test/java/dev/slimevr/config/ProfilesTest.kt +++ b/server/core/src/test/java/dev/slimevr/config/ProfilesTest.kt @@ -89,6 +89,74 @@ class ProfilesTest { assertTrue(storage.files.getValue("settings/default.json").contains("42.0")) } + @Test + fun `a reset goes back to the default profiles with default values and keeps the others`() = runTest { + val storage = MemoryStorage() + val config = buildConfig(this, storage) + config.settings.context.dispatch(SettingsActions.Update { copy(trackersConfig = trackersConfig.copy(timeoutDelay = 42f)) }) + config.createProfile(ProfileKind.SETTINGS, "gaming", copyFrom = "default") + config.switchProfile(ProfileKind.SETTINGS, "gaming") + config.createProfile(ProfileKind.USER, "other", copyFrom = null) + config.switchProfile(ProfileKind.USER, "other") + runCurrent() + + config.reset() + config.settings.flush() + + assertEquals(ProfileNames("default", listOf("default", "gaming")), config.profiles.value.settings) + assertEquals(ProfileNames("default", listOf("default", "other")), config.profiles.value.user) + assertEquals("default", config.globalConfig.context.state.value.selectedSettingsProfile) + assertEquals("default", config.globalConfig.context.state.value.selectedUserProfile) + assertEquals(TrackersConfig().timeoutDelay, config.settings.context.state.value.data.trackersConfig.timeoutDelay) + assertTrue(!storage.files.getValue("settings/default.json").contains("42.0")) + assertTrue(storage.files.getValue("settings/gaming.json").contains("42.0")) + } + + @Test + fun `a reset recreates the default profile when it was renamed away`() = runTest { + val storage = MemoryStorage() + val config = buildConfig(this, storage) + config.renameProfile(ProfileKind.SETTINGS, "default", "mine") + runCurrent() + + config.reset() + config.settings.flush() + + assertEquals(ProfileNames("default", listOf("default", "mine")), config.profiles.value.settings) + assertTrue("settings/default.json" in storage.files) + } + + @Test + fun `a reset creates the default profile again when it was deleted`() = runTest { + val storage = MemoryStorage() + val config = buildConfig(this, storage) + config.createProfile(ProfileKind.SETTINGS, "other", copyFrom = null) + config.switchProfile(ProfileKind.SETTINGS, "other") + config.deleteProfile(ProfileKind.SETTINGS, "default") + runCurrent() + + config.reset() + + assertEquals(ProfileNames("default", listOf("default", "other")), config.profiles.value.settings) + assertTrue("settings/default.json" in storage.files) + } + + @Test + fun `a reset reuses a default profile named in another case`() = runTest { + val storage = MemoryStorage() + val config = buildConfig(this, storage) + config.createProfile(ProfileKind.SETTINGS, "other", copyFrom = null) + config.switchProfile(ProfileKind.SETTINGS, "other") + config.deleteProfile(ProfileKind.SETTINGS, "default") + assertEquals(ProfileOperationStatus.OK, config.createProfile(ProfileKind.SETTINGS, "Default", copyFrom = null)) + runCurrent() + + config.reset() + + assertEquals(ProfileNames("Default", listOf("Default", "other")), config.profiles.value.settings) + assertEquals("Default", config.globalConfig.context.state.value.selectedSettingsProfile) + } + @Test fun `a hand-edited global config cannot select a profile outside the profile directory`() = runTest { val storage = MemoryStorage() diff --git a/server/core/src/test/java/dev/slimevr/solarxr/SettingsResetTest.kt b/server/core/src/test/java/dev/slimevr/solarxr/SettingsResetTest.kt index ccaad1fdd..1855ed021 100644 --- a/server/core/src/test/java/dev/slimevr/solarxr/SettingsResetTest.kt +++ b/server/core/src/test/java/dev/slimevr/solarxr/SettingsResetTest.kt @@ -2,12 +2,14 @@ package dev.slimevr.solarxr import dev.slimevr.TestAppContext import dev.slimevr.buildTestAppConfig +import dev.slimevr.config.AppConfig import dev.slimevr.config.GlobalConfigActions import dev.slimevr.config.UserConfigActions import dev.slimevr.config.changeConsent import dev.slimevr.context.Context import dev.slimevr.solarxr.rpc.SettingsResetBehaviour import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import solarxr_protocol.rpc.ErrorReportingConsent @@ -15,6 +17,15 @@ import solarxr_protocol.rpc.SettingsResetRequest import kotlin.test.Test import kotlin.test.assertEquals +private fun awaitReset(scope: TestScope, config: AppConfig) { + val deadline = System.nanoTime() + 5_000_000_000L + while (config.globalConfig.context.state.value.errorReporting.consent != ErrorReportingConsent.UNDECIDED && System.nanoTime() < deadline) { + scope.runCurrent() + Thread.sleep(5) + } + scope.runCurrent() +} + @OptIn(ExperimentalCoroutinesApi::class) class SettingsResetTest { @Test @@ -40,7 +51,7 @@ class SettingsResetTest { runCurrent() bridge.rpcDispatcher.emit(SettingsResetRequest()) - runCurrent() + awaitReset(this, config) val errorReporting = config.globalConfig.context.state.value.errorReporting assertEquals(ErrorReportingConsent.UNDECIDED, errorReporting.consent)