mirror of
https://github.com/SlimeVR/SlimeVR-Server.git
synced 2026-11-23 18:41:24 -08:00
Compare commits
224
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c1c2133127 | ||
|
|
4a39726fbb | ||
|
|
49dc68886d | ||
|
|
de8757c09f | ||
|
|
b57390e92b | ||
|
|
6cbfb3b34d | ||
|
|
8358ca14a8 | ||
|
|
67fbf0faca | ||
|
|
ce762ba242 | ||
|
|
70eda4f70c | ||
|
|
cdc0e21913 | ||
|
|
6575a11da7 | ||
|
|
9edc747344 | ||
|
|
5e3395afb0 | ||
|
|
cdde0b762f | ||
|
|
71895dec63 | ||
|
|
fc6304d7ee | ||
|
|
563933fa90 | ||
|
|
90956a6a02 | ||
|
|
3a0dc4b922 | ||
|
|
064e22dc1a | ||
|
|
11669d40b8 | ||
|
|
0bbe35b5d1 | ||
|
|
0530cebf92 | ||
|
|
d0b361a821 | ||
|
|
7c6151fbe5 | ||
|
|
c8c57b1511 | ||
|
|
5b45d26c2d | ||
|
|
2b82638961 | ||
|
|
8df1e3dc4c | ||
|
|
a45925bc36 | ||
|
|
22999975ad | ||
|
|
98ccc7c667 | ||
|
|
0723625272 | ||
|
|
4686e915b7 | ||
|
|
d1b1195213 | ||
|
|
f202f96246 | ||
|
|
aa0d2e86a5 | ||
|
|
dc2b47a7dc | ||
|
|
47638cc9d5 | ||
|
|
0757935d60 | ||
|
|
066a73c0c2 | ||
|
|
dd198d2205 | ||
|
|
d7bdeaa48a | ||
|
|
5681c351c5 | ||
|
|
28bedc12f1 | ||
|
|
a69c10d733 | ||
|
|
c0cf2af9be | ||
|
|
71391e7f5a | ||
|
|
33d84f19f1 | ||
|
|
2996858770 | ||
|
|
1e92eafdad | ||
|
|
150c0640cf | ||
|
|
25a066da30 | ||
|
|
8c78f1c371 | ||
|
|
2cf6c0b97c | ||
|
|
710088e513 | ||
|
|
91011120f0 | ||
|
|
837316ba8d | ||
|
|
d9338dc863 | ||
|
|
1763fe9ceb | ||
|
|
f6d662ab71 | ||
|
|
791ae07fe2 | ||
|
|
fe3bee2417 | ||
|
|
431774be16 | ||
|
|
2f5b2eaa94 | ||
|
|
0755413b87 | ||
|
|
cf46ca9f9f | ||
|
|
ba5660be33 | ||
|
|
40bb3d1cbe | ||
|
|
e85bb26537 | ||
|
|
10df44ee2b | ||
|
|
2559cdf9bc | ||
|
|
fe2a7bf442 | ||
|
|
1d554334cc | ||
|
|
a75a1ad195 | ||
|
|
a4aa76aa82 | ||
|
|
c43b44ccc8 | ||
|
|
5f3b1fd0a5 | ||
|
|
facce888a0 | ||
|
|
0c0aac0415 | ||
|
|
1ebd8a4f02 | ||
|
|
95b64883f6 | ||
|
|
861a9fbf12 | ||
|
|
d6e6926d44 | ||
|
|
16d2e0b46b | ||
|
|
83f48a7eba | ||
|
|
24da10715f | ||
|
|
559c076b26 | ||
|
|
67ae02a1b0 | ||
|
|
e1802987ca | ||
|
|
3f7580ac1a | ||
|
|
11783de08b | ||
|
|
256574dc2c | ||
|
|
5a4ba1f73b | ||
|
|
feb3eae3d3 | ||
|
|
bdde772c5c | ||
|
|
c208b7cda2 | ||
|
|
c10d536a6c | ||
|
|
cef72ee9ae | ||
|
|
6dbe872958 | ||
|
|
f390347b56 | ||
|
|
22cb14bb21 | ||
|
|
cc387a6c02 | ||
|
|
412e182079 | ||
|
|
7b80cb926d | ||
|
|
22d1126c66 | ||
|
|
3574130207 | ||
|
|
c5eda4b818 | ||
|
|
cc68e0e750 | ||
|
|
36f2398190 | ||
|
|
ddae53ab42 | ||
|
|
57c39c78b0 | ||
|
|
c71bb3e9c4 | ||
|
|
2f6cb0ab0d | ||
|
|
47a706792b | ||
|
|
7645ff6752 | ||
|
|
a86a6fb2f0 | ||
|
|
945796dade | ||
|
|
f59e5aa869 | ||
|
|
96998a644f | ||
|
|
f2b540d0bd | ||
|
|
d8041833f1 | ||
|
|
b3e61a5482 | ||
|
|
f3de32a7cb | ||
|
|
abc5c7b38c | ||
|
|
0907fe50db | ||
|
|
4b7af0bbed | ||
|
|
6d625d1d25 | ||
|
|
9d3afda739 | ||
|
|
d492061c0a | ||
|
|
e657d97480 | ||
|
|
4446b8d689 | ||
|
|
6c7d6add67 | ||
|
|
3ae788e8af | ||
|
|
7ddb3e74e6 | ||
|
|
6fe10bf71d | ||
|
|
3749b77c75 | ||
|
|
ae4402b5b5 | ||
|
|
170c688db8 | ||
|
|
be34dc981c | ||
|
|
6087178ecf | ||
|
|
04a26ec539 | ||
|
|
3095ce4867 | ||
|
|
b336897bfe | ||
|
|
14e77b6af3 | ||
|
|
cdd47d8b74 | ||
|
|
448f0754ad | ||
|
|
834111c769 | ||
|
|
a21e769d97 | ||
|
|
791a358893 | ||
|
|
428f2ba774 | ||
|
|
951b96d548 | ||
|
|
09724f1fa3 | ||
|
|
3336f6dff1 | ||
|
|
943d51dbdc | ||
|
|
fa3ebf4eb1 | ||
|
|
aa505d041b | ||
|
|
b7cd179cc6 | ||
|
|
1185825b3e | ||
|
|
984c98fd5b | ||
|
|
94e34ca3af | ||
|
|
1775d54bf1 | ||
|
|
4113a091c1 | ||
|
|
acde3a0e34 | ||
|
|
db231f368d | ||
|
|
18c5d0dad6 | ||
|
|
fa46f7d5fb | ||
|
|
7d04273b0e | ||
|
|
a097c26261 | ||
|
|
b17624d87a | ||
|
|
a43ba532e1 | ||
|
|
2d6b250539 | ||
|
|
4bf1e706d3 | ||
|
|
e2fa7c8963 | ||
|
|
6db666840b | ||
|
|
918f28dfc8 | ||
|
|
ac07e65b27 | ||
|
|
902ab1fee1 | ||
|
|
ada2ee3c81 | ||
|
|
c5d8968d58 | ||
|
|
9c7ca73dbc | ||
|
|
6266802a27 | ||
|
|
d1b96a5c6b | ||
|
|
5aaade2915 | ||
|
|
bf3168af2b | ||
|
|
4e69262240 | ||
|
|
ae5a8f4e97 | ||
|
|
a171bc2783 | ||
|
|
242920316b | ||
|
|
2fc64b3e8b | ||
|
|
02ca403e24 | ||
|
|
17e87178fc | ||
|
|
dd6c1e7567 | ||
|
|
0ab80528fe | ||
|
|
e07ef046a6 | ||
|
|
71b74914a3 | ||
|
|
f65f41ad17 | ||
|
|
df4569fe17 | ||
|
|
38743dc8b8 | ||
|
|
9d1e7764e6 | ||
|
|
fa1d2012e1 | ||
|
|
8168e1366a | ||
|
|
ea92fb4c01 | ||
|
|
fc476a1683 | ||
|
|
5946ca1b7a | ||
|
|
6c4fdedcd1 | ||
|
|
1001b7f887 | ||
|
|
86dbdbddf8 | ||
|
|
d46fb013ac | ||
|
|
8ffd00eb47 | ||
|
|
853155600a | ||
|
|
ad9bc911b6 | ||
|
|
2235b8178b | ||
|
|
e37a37bcf9 | ||
|
|
af4665e7c9 | ||
|
|
a42ed79003 | ||
|
|
334be5f7cc | ||
|
|
4c1e4691be | ||
|
|
4fd4997e60 | ||
|
|
6eb63ce9f8 | ||
|
|
01b7b8dbba | ||
|
|
e060bc7cc5 | ||
|
|
d691619b98 |
No files matched your search
@@ -1,9 +1,9 @@
|
||||
if ! has nix_direnv_version || ! nix_direnv_version 2.2.1; then
|
||||
source_url "https://raw.githubusercontent.com/nix-community/nix-direnv/2.2.1/direnvrc" "sha256-zelF0vLbEl5uaqrfIzbgNzJWGmLzCmYAkInj/LNxvKs="
|
||||
if ! has nix_direnv_version || ! nix_direnv_version 3.1.1; then
|
||||
source_url "https://raw.githubusercontent.com/nix-community/nix-direnv/3.1.1/direnvrc" "sha256-p+fzQdrms/hDa7g+soShAybJNo4bN4SIAeSfqNKgD5I="
|
||||
fi
|
||||
|
||||
nix_direnv_watch_file package.json
|
||||
if ! use flake . --impure
|
||||
watch_file package.json
|
||||
if ! use flake .
|
||||
then
|
||||
echo "devenv could not be built. The devenv environment was not loaded. Make the necessary changes to devenv.nix and hit enter to try again." >&2
|
||||
fi
|
||||
@@ -84,23 +84,25 @@ jobs:
|
||||
- name: GUI Lint
|
||||
run: pnpm i && cd gui && pnpm run lint
|
||||
|
||||
java-checks:
|
||||
name: Java Checks
|
||||
server-checks:
|
||||
name: Server Checks
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
submodules: recursive
|
||||
- name: Set up JDK 17
|
||||
- name: Set up JDK 24
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
java-version: '17'
|
||||
java-version: '24'
|
||||
distribution: 'adopt'
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v6
|
||||
- name: Java Spotless Check
|
||||
- name: Server Spotless Check
|
||||
run: ./gradlew spotlessCheck --build-cache
|
||||
- name: Server Detekt Lint
|
||||
run: ./gradlew :server:detekt --build-cache
|
||||
|
||||
|
||||
build-server-jar:
|
||||
@@ -113,10 +115,10 @@ jobs:
|
||||
submodules: recursive
|
||||
- name: Get tags
|
||||
run: git fetch --tags origin --recurse-submodules=no --force
|
||||
- name: Set up JDK 17
|
||||
- name: Set up JDK 24
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
java-version: '17'
|
||||
java-version: '24'
|
||||
distribution: 'adopt'
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v6
|
||||
@@ -260,10 +262,10 @@ jobs:
|
||||
submodules: recursive
|
||||
- name: Get tags
|
||||
run: git fetch --tags origin --recurse-submodules=no --force
|
||||
- name: Set up JDK 17
|
||||
- name: Set up JDK 24
|
||||
uses: actions/setup-java@v5
|
||||
with:
|
||||
java-version: '17'
|
||||
java-version: '24'
|
||||
distribution: 'adopt'
|
||||
- name: Setup Gradle
|
||||
uses: gradle/actions/setup-gradle@v6
|
||||
|
||||
+4
-2
@@ -4,8 +4,10 @@
|
||||
# Syncthing ignore file
|
||||
.stignore
|
||||
|
||||
# Ignore .idea
|
||||
.idea
|
||||
# Ignore .idea, except shared project inspection profiles
|
||||
.idea/*
|
||||
!.idea/inspectionProfiles/
|
||||
!.idea/inspectionProfiles/*.xml
|
||||
|
||||
# Ignore .fleet
|
||||
.fleet
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="27ef4df3-2b89-390d-a9cd-ef29bd86503d" enabled="false" level="WARNING" enabled_by_default="false" />
|
||||
<inspection_tool class="8d635bb8-7d4f-3af3-8d31-6f9164877ab2" enabled="false" level="WARNING" enabled_by_default="false" />
|
||||
<inspection_tool class="ConvertLongToDuration" enabled="false" level="WARNING" enabled_by_default="false" />
|
||||
<inspection_tool class="SSBasedInspection" enabled="true" level="ERROR" enabled_by_default="true">
|
||||
<searchConfiguration name="Use safeLaunch instead of raw launch" uuid="8d635bb8-7d4f-3af3-8d31-6f9164877ab2" description="Use dev.slimevr.util.safeLaunch instead of raw launch to ensure coroutine exceptions are handled properly." suppressId="RAW_LAUNCH_USAGE" problemDescriptor="Use safeLaunch instead of raw launch to ensure coroutine exceptions are handled properly." text="$scope$.launch { $statements$; }" recursive="true" caseInsensitive="false" type="Kotlin" pattern_context="default">
|
||||
<constraint name="__context__" within="" contains="" />
|
||||
<constraint name="scope" within="" contains="" />
|
||||
<constraint name="statements" minCount="0" maxCount="2147483647" within="" contains="" />
|
||||
</searchConfiguration>
|
||||
<searchConfiguration name="Use safeLaunch instead of raw launch" uuid="0e4a6db4-4c7b-3fd4-99ce-2717fa0fd2fb" description="Use dev.slimevr.util.safeLaunch instead of raw launch to ensure coroutine exceptions are handled properly." suppressId="RAW_LAUNCH_USAGE" problemDescriptor="Use safeLaunch instead of raw launch to ensure coroutine exceptions are handled properly." text="launch { $statements$; }" recursive="true" caseInsensitive="false" type="Kotlin" pattern_context="default">
|
||||
<constraint name="__context__" within="" contains="" />
|
||||
<constraint name="statements" minCount="0" maxCount="2147483647" within="" contains="" />
|
||||
</searchConfiguration>
|
||||
<searchConfiguration name="Use safeLaunch instead of raw launch" uuid="27ef4df3-2b89-390d-a9cd-ef29bd86503d" description="Use dev.slimevr.util.safeLaunch instead of raw launch to ensure coroutine exceptions are handled properly." suppressId="RAW_LAUNCH_USAGE" problemDescriptor="Use safeLaunch instead of raw launch to ensure coroutine exceptions are handled properly." text="$scope$.launch($args$) { $statements$; }" recursive="true" caseInsensitive="false" type="Kotlin" pattern_context="default">
|
||||
<constraint name="__context__" within="" contains="" />
|
||||
<constraint name="scope" within="" contains="" />
|
||||
<constraint name="args" maxCount="2147483647" within="" contains="" />
|
||||
<constraint name="statements" minCount="0" maxCount="2147483647" within="" contains="" />
|
||||
</searchConfiguration>
|
||||
<searchConfiguration name="Use safeLaunch instead of raw launch" uuid="ca477c43-2f5b-3907-8b06-02c34dc26930" description="Use dev.slimevr.util.safeLaunch instead of raw launch to ensure coroutine exceptions are handled properly." suppressId="RAW_LAUNCH_USAGE" problemDescriptor="Use safeLaunch instead of raw launch to ensure coroutine exceptions are handled properly." text="launch($args$) { $statements$; }" recursive="true" caseInsensitive="false" type="Kotlin" pattern_context="default">
|
||||
<constraint name="__context__" within="" contains="" />
|
||||
<constraint name="args" maxCount="2147483647" within="" contains="" />
|
||||
<constraint name="statements" minCount="0" maxCount="2147483647" within="" contains="" />
|
||||
</searchConfiguration>
|
||||
</inspection_tool>
|
||||
</profile>
|
||||
</component>
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<settings>
|
||||
<option name="PROJECT_PROFILE" value="Project Default" />
|
||||
<option name="USE_PROJECT_PROFILE" value="true" />
|
||||
<version value="1.0" />
|
||||
</settings>
|
||||
</component>
|
||||
@@ -0,0 +1,64 @@
|
||||
# OpenCode Agent Instructions
|
||||
|
||||
## Environment & Tooling
|
||||
- **Server (Kotlin/Java)**: Use `gradle` (`./gradlew`).
|
||||
- Run: `./gradlew run`
|
||||
- Build: `./gradlew shadowJar`
|
||||
- Format: `./gradlew spotlessApply`
|
||||
- **GUI (Electron/TS)**: Use `pnpm`.
|
||||
- Install: `pnpm i`
|
||||
- Dev: `pnpm gui`
|
||||
- Build: `pnpm package:build`
|
||||
- Format: `pnpm run lint:fix`
|
||||
- **SolarXR Protocol (Submodule)**: Use `bash` and `pnpm`.
|
||||
- Edit: Only `schema/` files.
|
||||
- Generate: `./generate-flatbuffer.sh` (Linux/macOS).
|
||||
- Sync: Run `pnpm i` in root after generation.
|
||||
|
||||
## Architecture: The Reducer/Behaviour Pattern
|
||||
The server uses a reactive reducer pattern for thread safety and observability.
|
||||
|
||||
- **Core Primitives**:
|
||||
- `Context<S, A>`: Holds `StateFlow<S>`, `CoroutineScope`, and `Behaviour`s.
|
||||
- `Behaviour<S, A, C>`:
|
||||
- `reduce(state, action)`: **Pure function**. No side effects.
|
||||
- `observe(receiver)`: **Side effects**. Launch coroutines using `receiver.context.scope`.
|
||||
- **Lifecycle**: `Module.create()` (inert construction) $\rightarrow$ `module.startObserving()` (side-effect activation).
|
||||
- **DI**: Uses `Phase1ContextProvider` $\rightarrow$ `AppContextProvider` hierarchy.
|
||||
- **Communication**: Modules communicate via `dispatch(action)` or by observing another module's `StateFlow`.
|
||||
|
||||
## Design & Coding Preferences
|
||||
- **Function over Class**: Prefer plain functions or `object` over classes for single-purpose logic.
|
||||
- **Function over Extension**: Use plain functions instead of extension functions unless the receiver is the primary subject.
|
||||
- **Action Selection**:
|
||||
- Use `Update` (with a lambda) for internal state changes that require no external reaction.
|
||||
- Use **Named Actions** when multiple behaviours must react to a specific event.
|
||||
- **State Management**: Only include data in `StateFlow` if it is required for observation by other modules.
|
||||
- **Communication**: Decouple modules by using `dispatch` or observing `StateFlow` rather than direct method calls.
|
||||
|
||||
## Agent Workflow
|
||||
- **Phase 1: Discovery**: Use the `Glob` $\rightarrow$ `Grep` $\rightarrow$ `Read` pattern. Never guess file paths or contents.
|
||||
- **Phase 2: Planning**: For complex tasks, use `todowrite` to create a checklist. Present the plan to the user before implementation.
|
||||
- **Phase 3: Implementation**: Use `edit` for existing files; `write` for new files.
|
||||
- **Phase 4: Verification**: Always run the relevant linting or testing tools before marking a task as complete.
|
||||
|
||||
## Common Pitfalls
|
||||
- **Coroutine Leaks**: Never launch coroutines in `observe` using a global scope; **always** use `receiver.context.scope`.
|
||||
- **Direct State Mutation**: Never attempt to mutate state properties directly. Always use `dispatch(action)`.
|
||||
- **Incomplete Cleanup**: Ensure any module owning a `Context` implements a `dispose()` method.
|
||||
|
||||
## Conventions
|
||||
- **Files**: `module.kt` (Class/State/Actions) and `behaviours.kt` (Implementations).
|
||||
- **Actions**: Use `sealed interface`.
|
||||
- **State**: Data classes must use `val` only.
|
||||
- **Cleanup**: We use a direct `dispose()` method on modules instead of a `Disposable` interface.
|
||||
- **Detailed Conventions**: See `server/README.md` for full coding style and architecture details.
|
||||
|
||||
## Testing
|
||||
- **Reducers**: Test by creating a `Context` with specific `Behaviour`s.
|
||||
- **Modules**: Use `TestAppContext` and `buildTest...` helpers from `TestServer.kt`.
|
||||
|
||||
## Verification Protocol
|
||||
- **Linting**: Run `./gradlew spotlessApply` (Server) or `pnpm run lint:fix` (GUI).
|
||||
- **Testing**: Identify and run the relevant test suite (e.g., `./gradlew test` or specific module tests).
|
||||
- **Final Audit**: Perform a final `git diff` check to ensure no unintended changes were made.
|
||||
+7
-4
@@ -22,21 +22,24 @@ Now you can open the codebase in [IDEA](https://www.jetbrains.com/idea/download/
|
||||
|
||||
### Java (server)
|
||||
|
||||
Before contributing to the server, read [server/README.md](server/README.md) for an overview of its architecture and design guidelines.
|
||||
|
||||
The Java code is built with `gradle`, a CLI tool that manages java projects and their
|
||||
dependencies.
|
||||
- You can run the server by running `./gradlew run` in your IDE's terminal.
|
||||
- To compile the code, run `./gradlew shadowJar`. The result will
|
||||
be at `server/build/libs/slimevr.jar` (you can ignore `server.jar`).
|
||||
be at `server/desktop/build/libs/slimevr.jar` (you can ignore `server.jar`).
|
||||
|
||||
(Note: Your IDE may be able to do all of the above for you.)
|
||||
|
||||
### Electron (gui)
|
||||
|
||||
- Activate corepack (included with Node.JS) via `corepack enable` (might require administrator permissions)
|
||||
- Activate corepack (included with Node.js) via `corepack enable`
|
||||
(might require launching Git Bash as administrator on Windows)
|
||||
- Run `pnpm i` in your IDE's terminal to download and install dependencies.
|
||||
- To launch the GUI in dev mode, run `pnpm gui`.
|
||||
- Finally, to compile for production, run `pnpm package:build`. The result
|
||||
will be at `dist/artifacts/` content will change depending of the platform.
|
||||
- Finally, to compile for production, run `pnpm package:build`.
|
||||
The result will be in `gui/dist/artifacts/`. Content will change depending on the platform.
|
||||
|
||||
## Code style
|
||||
|
||||
|
||||
@@ -22,6 +22,8 @@ Latest setup instructions are [in our docs](https://docs.slimevr.dev/server/inde
|
||||
## Building & Contributing
|
||||
For information on building and contributing to the codebase, see [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||
For an overview of the server architecture and design guidelines, see [server/README.md](server/README.md).
|
||||
|
||||
## Translating
|
||||
|
||||
Translation is done via Pontoon at [i18n.slimevr.dev](https://i18n.slimevr.dev/). Please join our [Discord translation forum](https://discord.com/channels/817184208525983775/1050413434249949235) to coordinate.
|
||||
|
||||
@@ -15,6 +15,13 @@
|
||||
|
||||
#include "openvr.h"
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <Windows.h>
|
||||
#else
|
||||
#include <cstdlib>
|
||||
#endif
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
using namespace std::chrono_literals;
|
||||
using namespace solarxr_protocol;
|
||||
|
||||
@@ -95,6 +102,20 @@ static void signal_handler(int signal) {
|
||||
|
||||
int main() {
|
||||
auto &logger = Logger::get();
|
||||
// Steam and SteamVR sets these environment variables on applications that it
|
||||
// spawns, but if an app spawned by Steam then spawns a child that initialises
|
||||
// OpenVR, SteamVR will give the child the appkey of the root application it
|
||||
// is a descendant of, e.g. if SteamVR launches SlimeVR as an overlay,
|
||||
// it will set SteamAppId="3245490" and STEAMVR_APPKEY="steam.overlay.3245490"
|
||||
// which breaks our bindings. We want SteamVR to use a generated appkey if
|
||||
// possible.
|
||||
#ifdef _WIN32
|
||||
SetEnvironmentVariableA("SteamAppId", nullptr);
|
||||
SetEnvironmentVariableA("STEAMVR_APPKEY", nullptr);
|
||||
#else
|
||||
unsetenv("SteamAppId");
|
||||
unsetenv("STEAMVR_APPKEY");
|
||||
#endif
|
||||
|
||||
try {
|
||||
SolarXRConnection conn;
|
||||
@@ -128,14 +149,20 @@ int main() {
|
||||
vr::IVRApplications *app = vr::VRApplications();
|
||||
vr::IVRInput *input = vr::VRInput();
|
||||
|
||||
auto [appManifestPath, actionManifestPath] = VRUtils::initialiseManifest();
|
||||
fs::path actionManifestPath;
|
||||
std::tie(std::ignore, actionManifestPath) = VRUtils::initialiseManifest();
|
||||
|
||||
// We don't want our app key to randomly change if SteamVR decides to honour
|
||||
// application manifests with no binary path. Instead let it generate an
|
||||
// app key based on the executable name (system.generated.[lowercase executable name])
|
||||
#if false
|
||||
if (auto err = app->AddApplicationManifest(appManifestPath.string().data(), true);
|
||||
err != vr::VRApplicationError_None) {
|
||||
logger.error("Failed to add application manifest: {}",
|
||||
app->GetApplicationsErrorNameFromEnum(err));
|
||||
return 1;
|
||||
}
|
||||
#endif
|
||||
|
||||
// SetActionManifestPath may return IPCError if vrserver is busy and takes
|
||||
// too long to reply, so keep invoking until it succeeds
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
plugins {
|
||||
id("org.ajoberstar.grgit")
|
||||
}
|
||||
Generated
+24
-7
@@ -5,11 +5,11 @@
|
||||
"nixpkgs-lib": "nixpkgs-lib"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1777988971,
|
||||
"narHash": "sha256-qIoWPDs+0/8JecyYgE3gpKQxW/4bLW/gp45vow9ioCQ=",
|
||||
"lastModified": 1778716662,
|
||||
"narHash": "sha256-m1Yf0wZ8j1OHjTc2UwHwyQRSnNeSgLJOd7q5Y45hzi4=",
|
||||
"owner": "hercules-ci",
|
||||
"repo": "flake-parts",
|
||||
"rev": "0678d8986be1661af6bb555f3489f2fdfc31f6ff",
|
||||
"rev": "f7c1a2d347e4c52d5fb8d10cb4d94b5884e546fb",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -20,11 +20,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1777954456,
|
||||
"narHash": "sha256-hGdgeU2Nk87RAuZyYjyDjFL6LK7dAZN5RE9+hrDTkDU=",
|
||||
"lastModified": 1781577229,
|
||||
"narHash": "sha256-lrp67w8AulE9Ks53n27I45ADSzbOCn4H+CNW1Ck8B+8=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "549bd84d6279f9852cae6225e372cc67fb91a4c1",
|
||||
"rev": "567a49d1913ce81ac6e9582e3553dd90a955875f",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -34,6 +34,22 @@
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs-jdk24": {
|
||||
"locked": {
|
||||
"lastModified": 1756787288,
|
||||
"narHash": "sha256-rw/PHa1cqiePdBxhF66V7R+WAP8WekQ0mCDG4CFqT8Y=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "d0fc30899600b9b3466ddb260fd83deb486c32f1",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "d0fc30899600b9b3466ddb260fd83deb486c32f1",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"nixpkgs-lib": {
|
||||
"locked": {
|
||||
"lastModified": 1777168982,
|
||||
@@ -52,7 +68,8 @@
|
||||
"root": {
|
||||
"inputs": {
|
||||
"flake-parts": "flake-parts",
|
||||
"nixpkgs": "nixpkgs"
|
||||
"nixpkgs": "nixpkgs",
|
||||
"nixpkgs-jdk24": "nixpkgs-jdk24"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||
# Pinned to a revision that still ships temurin jdk-24
|
||||
nixpkgs-jdk24.url = "github:NixOS/nixpkgs/d0fc30899600b9b3466ddb260fd83deb486c32f1";
|
||||
flake-parts.url = "github:hercules-ci/flake-parts";
|
||||
};
|
||||
|
||||
@@ -10,90 +12,164 @@
|
||||
inputs@{
|
||||
self,
|
||||
nixpkgs,
|
||||
nixpkgs-jdk24,
|
||||
flake-parts,
|
||||
...
|
||||
}:
|
||||
flake-parts.lib.mkFlake { inherit inputs; } {
|
||||
systems = [ "x86_64-linux" ];
|
||||
systems = [
|
||||
"aarch64-linux"
|
||||
"x86_64-linux"
|
||||
];
|
||||
|
||||
perSystem =
|
||||
{ pkgs, ... }:
|
||||
{
|
||||
system,
|
||||
lib,
|
||||
pkgs,
|
||||
...
|
||||
}:
|
||||
let
|
||||
runtimeLibs =
|
||||
pkgs:
|
||||
(with pkgs; [
|
||||
jdk17
|
||||
java = (import nixpkgs-jdk24 { inherit system; }).jdk24;
|
||||
|
||||
alsa-lib
|
||||
libpulseaudio
|
||||
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
|
||||
libX11
|
||||
libXcomposite
|
||||
libXdamage
|
||||
libXext
|
||||
libXfixes
|
||||
libXrandr
|
||||
libxcb
|
||||
libxshmfence
|
||||
libusb1
|
||||
udev
|
||||
libxcrypt-legacy
|
||||
rpm
|
||||
fpm
|
||||
runtimeLibs = [
|
||||
pkgs.alsa-lib
|
||||
pkgs.libpulseaudio
|
||||
pkgs.at-spi2-atk
|
||||
pkgs.at-spi2-core
|
||||
pkgs.cairo
|
||||
pkgs.cups
|
||||
pkgs.dbus
|
||||
pkgs.expat
|
||||
pkgs.gdk-pixbuf
|
||||
pkgs.glib
|
||||
pkgs.gtk3
|
||||
pkgs.libdrm
|
||||
pkgs.libgbm
|
||||
pkgs.libglvnd
|
||||
pkgs.libnotify
|
||||
pkgs.libxkbcommon
|
||||
pkgs.mesa
|
||||
pkgs.nspr
|
||||
pkgs.nss
|
||||
pkgs.pango
|
||||
pkgs.systemd
|
||||
pkgs.vulkan-loader
|
||||
pkgs.wayland
|
||||
pkgs.libX11
|
||||
pkgs.libXcomposite
|
||||
pkgs.libXdamage
|
||||
pkgs.libXext
|
||||
pkgs.libXfixes
|
||||
pkgs.libXrandr
|
||||
pkgs.libxcb
|
||||
pkgs.libxshmfence
|
||||
pkgs.libusb1
|
||||
pkgs.udev
|
||||
pkgs.libxcrypt-legacy
|
||||
];
|
||||
|
||||
wineWow64Packages.stable
|
||||
zlib
|
||||
squashfsTools
|
||||
fakeroot
|
||||
libarchive
|
||||
icu
|
||||
nodejs_22
|
||||
pnpm
|
||||
pkg-config
|
||||
python3
|
||||
gcc
|
||||
gnumake
|
||||
binutils
|
||||
git
|
||||
node-gyp-build
|
||||
]);
|
||||
toolDirectoryName =
|
||||
if pkgs.stdenv.hostPlatform.isDarwin then
|
||||
"darwin"
|
||||
else if pkgs.stdenv.hostPlatform.isLinux then
|
||||
{
|
||||
"armv7l-linux" = "linux-arm32";
|
||||
"aarch64-linux" = "linux-arm64";
|
||||
"i686-linux" = "linux-ia32";
|
||||
"x86_64-linux" = "linux-x64";
|
||||
}
|
||||
."${pkgs.stdenv.hostPlatform.system}"
|
||||
else
|
||||
throw "Unsupported platform";
|
||||
|
||||
slimeShell = pkgs.buildFHSEnv {
|
||||
name = "slimevr-env";
|
||||
targetPkgs = runtimeLibs;
|
||||
profile = ''
|
||||
export JAVA_HOME=${pkgs.jdk17}
|
||||
export PATH="${pkgs.jdk17}/bin:$PATH"
|
||||
# we use fuse2
|
||||
# https://github.com/electron-userland/electron-builder/blob/a6117b3011a105204af8cc2eca02a56976d1ef29/packages/app-builder-lib/src/toolsets/linux.ts#L122
|
||||
runtime = pkgs.stdenvNoCC.mkDerivation {
|
||||
name = "electron-builder-appimage-runtime";
|
||||
src = pkgs.fetchurl {
|
||||
url = "https://github.com/electron-userland/electron-builder-binaries/releases/download/appimage-12.0.1/appimage-12.0.1.7z";
|
||||
hash = "sha256-0S/3648dHsRlLKUjen+9yjOswMdYBFY2/spi3G7LjsQ=";
|
||||
};
|
||||
# https://github.com/NixOS/nixpkgs/blob/7890ba0a99c064446fe2178ef2f8e3abdf6ec42a/pkgs/by-name/lo/losslesscut-bin/build-from-windows.nix#L20
|
||||
nativeBuildInputs = [ pkgs.p7zip ];
|
||||
unpackPhase = ''
|
||||
runHook preUnpack
|
||||
7z x "$src"
|
||||
runHook postUnpack
|
||||
'';
|
||||
installPhase = ''
|
||||
mkdir $out
|
||||
cp -r -t $out/ \
|
||||
lib/ \
|
||||
runtime-*
|
||||
'';
|
||||
};
|
||||
|
||||
# Tell electron-builder to use system tools instead of downloading them
|
||||
export USE_SYSTEM_FPM=true
|
||||
export USE_SYSTEM_MKSQUASHFS=true
|
||||
appImageTools = pkgs.stdenvNoCC.mkDerivation {
|
||||
name = "electron-builder-appimage-tools";
|
||||
dontUnpack = true;
|
||||
|
||||
installPhase = ''
|
||||
mkdir -p "$out/${toolDirectoryName}"
|
||||
ln -s -t $out/${toolDirectoryName} \
|
||||
"${pkgs.desktop-file-utils}/bin/desktop-file-validate" \
|
||||
"${pkgs.squashfsTools}/bin/mksquashfs"
|
||||
ln -s ${runtime}/runtime-* $out/
|
||||
ln -s ${runtime}/lib $out/lib
|
||||
'';
|
||||
runScript = "bash";
|
||||
};
|
||||
in
|
||||
{
|
||||
devShells.default = slimeShell.env;
|
||||
devShells.default = pkgs.mkShell {
|
||||
packages = [
|
||||
# for running the jar
|
||||
java
|
||||
|
||||
# for build
|
||||
pkgs.electron
|
||||
pkgs.rpm
|
||||
pkgs.fpm
|
||||
pkgs.p7zip
|
||||
pkgs.wineWow64Packages.stable
|
||||
pkgs.zlib
|
||||
pkgs.squashfsTools
|
||||
pkgs.desktop-file-utils
|
||||
pkgs.fakeroot
|
||||
pkgs.libarchive
|
||||
pkgs.icu
|
||||
pkgs.nodejs_22
|
||||
pkgs.pnpm
|
||||
pkgs.pkg-config
|
||||
pkgs.python3
|
||||
pkgs.gcc
|
||||
pkgs.gnumake
|
||||
pkgs.binutils
|
||||
pkgs.git
|
||||
pkgs.node-gyp-build
|
||||
];
|
||||
buildInputs = runtimeLibs;
|
||||
|
||||
JAVA_HOME = "${java}/lib/openjdk";
|
||||
USE_SYSTEM_FPM = "true";
|
||||
ELECTRON_BUILDER_7ZIP_PATH = "${pkgs.p7zip}/bin/7za";
|
||||
APPIMAGE_TOOLS_PATH = "${appImageTools}";
|
||||
#ELECTRON_SKIP_BINARY_DOWNLOAD = true;
|
||||
#ELECTRON_DIST = "${pkgs.electron.dist}";
|
||||
#ELECTRON_VERSION = "${pkgs.electron.version}";
|
||||
|
||||
# for electron-vite, so `pnpm gui` works
|
||||
ELECTRON_EXEC_PATH = "${pkgs.electron}/bin/electron";
|
||||
|
||||
shellHook = ''
|
||||
export LD_LIBRARY_PATH="${
|
||||
lib.makeLibraryPath [
|
||||
pkgs.systemd
|
||||
pkgs.hidapi
|
||||
]
|
||||
}:$LD_LIBRARY_PATH"
|
||||
'';
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
+1
-7
@@ -17,10 +17,4 @@ kotlinVersion=2.3.10
|
||||
spotlessVersion=8.2.1
|
||||
shadowJarVersion=9.3.1
|
||||
buildconfigVersion=6.0.7
|
||||
# We should probably stop using grgit, see:
|
||||
# https://andrewoberstar.com/posts/2024-04-02-dont-commit-to-grgit/
|
||||
grgitVersion=5.3.3
|
||||
|
||||
# Fix gradle leaving multiple java processes running that accumulate and use multiple GBs of RAM
|
||||
# This mostly seems to affect it when running from console, and then sending a SIGINT (Ctrl + C)
|
||||
org.gradle.daemon.idletimeout=10000
|
||||
wireVersion=5.3.1
|
||||
Vendored
BIN
Binary file not shown.
+2
-2
@@ -1,7 +1,7 @@
|
||||
distributionBase=GRADLE_USER_HOME
|
||||
distributionPath=wrapper/dists
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.4-bin.zip
|
||||
distributionSha256Sum=f1771298a70f6db5a29daf62378c4e18a17fc33c9ba6b14362e0cdf40610380d
|
||||
distributionSha256Sum=bbaeb2fef8710818cf0e261201dab964c572f92b942812df0c3620d62a529a01
|
||||
distributionUrl=https\://services.gradle.org/distributions/gradle-9.6.0-bin.zip
|
||||
networkTimeout=10000
|
||||
validateDistributionUrl=true
|
||||
zipStoreBase=GRADLE_USER_HOME
|
||||
|
||||
@@ -86,8 +86,7 @@ done
|
||||
# shellcheck disable=SC2034
|
||||
APP_BASE_NAME=${0##*/}
|
||||
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
|
||||
' "$PWD" ) || exit
|
||||
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
|
||||
|
||||
# Use the maximum available, or set MAX_FD != -1 to use that value.
|
||||
MAX_FD=maximum
|
||||
@@ -115,7 +114,7 @@ case "$( uname )" in #(
|
||||
NONSTOP* ) nonstop=true ;;
|
||||
esac
|
||||
|
||||
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
|
||||
CLASSPATH="\\\"\\\""
|
||||
|
||||
|
||||
# Determine the Java command to use to start the JVM.
|
||||
@@ -206,7 +205,7 @@ fi
|
||||
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
|
||||
# Collect all arguments for the java command:
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
|
||||
# and any embedded shellness will be escaped.
|
||||
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
|
||||
# treated as '${Hostname}' itself on the command line.
|
||||
@@ -214,7 +213,7 @@ DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
|
||||
set -- \
|
||||
"-Dorg.gradle.appname=$APP_BASE_NAME" \
|
||||
-classpath "$CLASSPATH" \
|
||||
org.gradle.wrapper.GradleWrapperMain \
|
||||
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
|
||||
"$@"
|
||||
|
||||
# Stop when "xargs" is not available.
|
||||
|
||||
Vendored
+2
-2
@@ -70,11 +70,11 @@ goto fail
|
||||
:execute
|
||||
@rem Setup the command line
|
||||
|
||||
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
|
||||
set CLASSPATH=
|
||||
|
||||
|
||||
@rem Execute Gradle
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
|
||||
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %*
|
||||
|
||||
:end
|
||||
@rem End local scope for the variables with windows NT shell
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export default {
|
||||
'**/*.{ts,tsx}': () => 'tsc -p tsconfig.json --noEmit',
|
||||
'src/**/*.{js,jsx,ts,tsx}': 'eslint --max-warnings=0 --no-warn-ignored --cache --fix',
|
||||
'{electron,src}/**/*.{js,jsx,ts,tsx}': 'eslint --max-warnings=0 --no-warn-ignored --cache --fix',
|
||||
'**/*.{js,jsx,ts,tsx,css,scss,md,json}': 'prettier --write',
|
||||
};
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Option, program } from "commander";
|
||||
import { Option, program } from 'commander';
|
||||
|
||||
program
|
||||
.option('-p, --path <path>', 'set launch path')
|
||||
@@ -12,10 +12,10 @@ program
|
||||
// Allow passing arguments to Electron.
|
||||
.allowExcessArguments();
|
||||
|
||||
if (process.platform === "linux") {
|
||||
if (process.platform === 'linux') {
|
||||
const noUdevOption = new Option('--no-udev', 'disable udev warning');
|
||||
noUdevOption.negate = false;
|
||||
program.addOption(noUdevOption)
|
||||
program.addOption(noUdevOption);
|
||||
}
|
||||
|
||||
program.parse(process.argv);
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
} from './paths';
|
||||
import { initStores } from './store';
|
||||
import { closeLogger, logger } from './logger';
|
||||
|
||||
import { spawn } from 'node:child_process';
|
||||
import { discordPresence } from './presence';
|
||||
import { options } from './cli';
|
||||
@@ -126,14 +127,14 @@ handleIpc(IPC_CHANNELS.LOG, (e, type, ...args) => {
|
||||
});
|
||||
|
||||
handleIpc(IPC_CHANNELS.OPEN_URL, (e, url) => {
|
||||
const allowed_urls = [
|
||||
const allowedUrls = [
|
||||
/^steam:\/\//,
|
||||
/^ms-settings:network$/,
|
||||
/^https:\/\/(?:.+\.)?slimevr\.dev(?:\/.+)?$/,
|
||||
/^https:\/\/github\.com\/SlimeVR(?:\/.+)?$/,
|
||||
/^https:\/\/discord\.gg\/slimevr$/,
|
||||
];
|
||||
if (allowed_urls.find((a) => url.match(a))) open(url);
|
||||
if (allowedUrls.find((a) => url.match(a))) open(url);
|
||||
else logger.error({ url }, 'attempted to open non-whitelisted URL');
|
||||
});
|
||||
|
||||
@@ -370,9 +371,9 @@ function createWindow() {
|
||||
}
|
||||
|
||||
const checkEnvironmentVariables = () => {
|
||||
const to_check = ['_JAVA_OPTIONS', 'JAVA_TOOL_OPTIONS'];
|
||||
const disallowedVars = ['_JAVA_OPTIONS', 'JAVA_TOOL_OPTIONS'];
|
||||
|
||||
const set = to_check.filter((env) => !!process.env[env]);
|
||||
const set = disallowedVars.filter((env) => !!process.env[env]);
|
||||
if (set.length > 0) {
|
||||
dialog.showErrorBox(
|
||||
'SlimeVR',
|
||||
@@ -403,7 +404,7 @@ const spawnServer = async () => {
|
||||
if (!javaBin) {
|
||||
dialog.showErrorBox(
|
||||
'SlimeVR',
|
||||
`Couldn't find a compatible Java version, please download Java 17 or higher`
|
||||
'Unable to find a compatible Java version, please download Java 17 or higher'
|
||||
);
|
||||
app.quit();
|
||||
return;
|
||||
@@ -500,12 +501,6 @@ app.whenReady().then(async () => {
|
||||
|
||||
logger.info('SlimeVR started!');
|
||||
|
||||
process.on('exit', async (code) => {
|
||||
console.log(code);
|
||||
server?.close();
|
||||
await server?.waitForExit();
|
||||
});
|
||||
|
||||
app.on('window-all-closed', () => {
|
||||
app.quit();
|
||||
});
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { access, mkdir, readFile, writeFile } from "fs/promises";
|
||||
import { dirname, join } from "path";
|
||||
import { logger } from "./logger";
|
||||
import { getGuiDataFolder } from "./paths";
|
||||
|
||||
import { access, mkdir, readFile, writeFile } from 'fs/promises';
|
||||
import { dirname, join } from 'path';
|
||||
import { logger } from './logger';
|
||||
import { getGuiDataFolder } from './paths';
|
||||
|
||||
export class CustomStore {
|
||||
private data: Record<string, unknown> = {};
|
||||
@@ -15,7 +14,10 @@ export class CustomStore {
|
||||
this.debounceMs = debounceMs;
|
||||
}
|
||||
|
||||
static async create(filePath: string, debounceMs: number = 2000): Promise<CustomStore> {
|
||||
static async create(
|
||||
filePath: string,
|
||||
debounceMs: number = 2000
|
||||
): Promise<CustomStore> {
|
||||
const store = new CustomStore(filePath, debounceMs);
|
||||
await store.load();
|
||||
return store;
|
||||
@@ -28,7 +30,9 @@ export class CustomStore {
|
||||
this.data = JSON.parse(raw);
|
||||
} catch {
|
||||
this.data = {};
|
||||
logger.warn(`No existing store found at ${this.filePath}, starting with empty store.`);
|
||||
logger.warn(
|
||||
`No existing store found at ${this.filePath}, starting with empty store.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,7 +77,10 @@ export class CustomStore {
|
||||
|
||||
export async function initStores() {
|
||||
return {
|
||||
settings: await CustomStore.create(join(getGuiDataFolder(), 'gui-settings.dat'), 1000),
|
||||
settings: await CustomStore.create(
|
||||
join(getGuiDataFolder(), 'gui-settings.dat'),
|
||||
1000
|
||||
),
|
||||
cache: await CustomStore.create(join(getGuiDataFolder(), 'gui-cache.dat'), 100),
|
||||
};
|
||||
}
|
||||
+18
-19
@@ -1,8 +1,8 @@
|
||||
import os from 'os'
|
||||
import { OSStats } from "../preload/interface";
|
||||
import os from 'os';
|
||||
import { OSStats } from '../preload/interface';
|
||||
import { ipcMain, IpcMainInvokeEvent } from 'electron';
|
||||
import { IpcInvokeMap } from '../shared';
|
||||
import net from 'net'
|
||||
import net from 'net';
|
||||
|
||||
export const getPlatform = (): OSStats['type'] => {
|
||||
switch (os.platform()) {
|
||||
@@ -19,21 +19,21 @@ export const getPlatform = (): OSStats['type'] => {
|
||||
|
||||
export const isPortAvailable = (port: number) => {
|
||||
return new Promise((resolve) => {
|
||||
const s = net.createServer();
|
||||
s.once('error', (err) => {
|
||||
s.close();
|
||||
if ("code" in err && err["code"] == "EADDRINUSE") {
|
||||
resolve(false);
|
||||
} else {
|
||||
resolve(false);
|
||||
}
|
||||
});
|
||||
s.once('listening', () => {
|
||||
resolve(true);
|
||||
s.close();
|
||||
});
|
||||
s.listen(port);
|
||||
const s = net.createServer();
|
||||
s.once('error', (err) => {
|
||||
s.close();
|
||||
if ('code' in err && err['code'] == 'EADDRINUSE') {
|
||||
resolve(false);
|
||||
} else {
|
||||
resolve(false);
|
||||
}
|
||||
});
|
||||
s.once('listening', () => {
|
||||
resolve(true);
|
||||
s.close();
|
||||
});
|
||||
s.listen(port);
|
||||
});
|
||||
};
|
||||
|
||||
export function handleIpc<K extends keyof IpcInvokeMap>(
|
||||
@@ -44,7 +44,6 @@ export function handleIpc<K extends keyof IpcInvokeMap>(
|
||||
) => ReturnType<IpcInvokeMap[K]>
|
||||
) {
|
||||
ipcMain.handle(channel, (event, ...args) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
return handler(event, ...args as any);
|
||||
return handler(event, ...(args as any));
|
||||
});
|
||||
}
|
||||
@@ -41,6 +41,7 @@ SUBSYSTEMS=="usb", ATTRS{idVendor}=="303a", ATTRS{idProduct}=="0002", MODE="0660
|
||||
SUBSYSTEMS=="usb", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", MODE="0660", TAG+="uaccess"
|
||||
|
||||
## SlimeVR
|
||||
# smol slime dongle
|
||||
SUBSYSTEM=="usb", ATTR{idVendor}=="1209", ATTR{idProduct}=="7690", MODE="0660", TAG+="uaccess"
|
||||
KERNEL=="hidraw*", SUBSYSTEM=="hidraw", ATTRS{idVendor}=="1209", ATTRS{idProduct}=="7690", MODE="0660", TAG+="uaccess"
|
||||
# SlimeNRF Receiver & Tracker
|
||||
SUBSYSTEM=="usb|tty", ATTRS{idVendor}=="1209", ATTRS{idProduct}=="7690|7692", MODE="0660", TAG+="uaccess"
|
||||
# same thing but hidraw
|
||||
KERNEL=="hidraw*", SUBSYSTEM=="hidraw", ATTRS{idVendor}=="1209", ATTRS{idProduct}=="7690|7692", MODE="0660", TAG+="uaccess"
|
||||
@@ -39,7 +39,7 @@ export const gui = [
|
||||
...globals.jest,
|
||||
},
|
||||
},
|
||||
files: ['src/**/*.{js,jsx,ts,tsx,json}'],
|
||||
files: ['{electron,src}/**/*.{js,jsx,ts,tsx,json}'],
|
||||
plugins: {
|
||||
'@typescript-eslint': tseslint.plugin,
|
||||
'@stylistic': stylistic,
|
||||
|
||||
+4
-4
@@ -23,9 +23,9 @@
|
||||
"package:build": "pnpm build && pnpm package",
|
||||
"preview": "electron-vite preview --config electron.vite.config.ts",
|
||||
"skipbundler": "vite build",
|
||||
"lint": "tsc --noEmit && eslint --max-warnings=0 \"src/**/*.{js,jsx,ts,tsx,json}\" && prettier --check \"src/**/*.{js,jsx,ts,tsx,css,scss,md,json}\"",
|
||||
"lint:fix": "tsc --noEmit && eslint --fix --max-warnings=0 \"src/**/*.{js,jsx,ts,tsx,json}\" && pnpm run format",
|
||||
"format": "prettier --write \"src/**/*.{js,jsx,ts,tsx,css,scss,md,json}\"",
|
||||
"lint": "tsc --noEmit && eslint --max-warnings=0 \"{electron,src}/**/*.{js,jsx,ts,tsx,json}\" && prettier --check \"{electron,src}/**/*.{js,jsx,ts,tsx,css,scss,md,json}\"",
|
||||
"lint:fix": "tsc --noEmit && eslint --fix --max-warnings=0 \"{electron,src}/**/*.{js,jsx,ts,tsx,json}\" && pnpm run format",
|
||||
"format": "prettier --write \"{electron,src}/**/*.{js,jsx,ts,tsx,css,scss,md,json}\"",
|
||||
"javaversion-build": "cd electron/resources/java-version/ && javac JavaVersion.java && jar cvfe JavaVersion.jar JavaVersion JavaVersion.class",
|
||||
"gen:javaversion": "cd electron/resources/java-version/ && javac JavaVersion.java && jar cvfe JavaVersion.jar JavaVersion JavaVersion.class",
|
||||
"gen:firmware-tool": "openapi-codegen gen firmwareTool"
|
||||
@@ -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.15.0",
|
||||
"electron-vite": "^5.0.0",
|
||||
"@eslint/eslintrc": "^3.3.5",
|
||||
"@eslint/js": "^9.39.4",
|
||||
|
||||
@@ -292,9 +292,6 @@ widget-overlay = Overlay
|
||||
widget-overlay-is_visible_label = Show Overlay in SteamVR
|
||||
widget-overlay-is_mirrored_label = Display Overlay as Mirror
|
||||
|
||||
## Widget: Drift compensation
|
||||
widget-drift_compensation-clear = Clear drift compensation
|
||||
|
||||
## Widget: Clear Mounting calibration
|
||||
widget-clear_mounting = Clear mounting calibration
|
||||
|
||||
@@ -389,9 +386,6 @@ tracker-settings-assignment_section-edit = Edit assignment
|
||||
tracker-settings-mounting_section = Mounting orientation
|
||||
tracker-settings-mounting_section-description = Where is the tracker mounted?
|
||||
tracker-settings-mounting_section-edit = Edit mounting
|
||||
tracker-settings-drift_compensation_section = Allow drift compensation
|
||||
tracker-settings-drift_compensation_section-description = Should this tracker compensate for its drift when drift compensation is enabled?
|
||||
tracker-settings-drift_compensation_section-edit = Allow drift compensation
|
||||
tracker-settings-use_mag = Allow magnetometer on this tracker
|
||||
# Multiline!
|
||||
tracker-settings-use_mag-description =
|
||||
@@ -481,13 +475,12 @@ mounting_selection_menu-close = Close
|
||||
## Sidebar settings
|
||||
settings-sidebar-title = Settings
|
||||
settings-sidebar-general = General
|
||||
settings-sidebar-steamvr = SteamVR
|
||||
settings-sidebar-output = Output
|
||||
settings-sidebar-tracker_mechanics = Tracker mechanics
|
||||
settings-sidebar-stay_aligned = Stay Aligned
|
||||
settings-sidebar-fk_settings = Tracking settings
|
||||
settings-sidebar-gesture_control = Gesture control
|
||||
settings-sidebar-interface = Interface
|
||||
settings-sidebar-osc_router = OSC router
|
||||
settings-sidebar-osc_trackers = VRChat OSC Trackers
|
||||
settings-sidebar-osc_vmc = VMC
|
||||
settings-sidebar-utils = Utilities
|
||||
@@ -501,15 +494,16 @@ settings-sidebar-firmware-tool = DIY Firmware Tool
|
||||
settings-sidebar-vrc_warnings = VRChat Config Warnings
|
||||
settings-sidebar-advanced = Advanced
|
||||
|
||||
## SteamVR settings
|
||||
settings-general-steamvr = SteamVR
|
||||
settings-general-steamvr-subtitle = SteamVR trackers
|
||||
## Output settings
|
||||
# Some keys have steamvr in them as we switched to output but want to keep existing translations
|
||||
settings-general-output = Output
|
||||
settings-general-output_trackers = Output trackers
|
||||
# Not all translation keys support multiline, only the ones that specify it will actually
|
||||
# split it in lines (that also means you can split in lines however you want in those).
|
||||
# The first spaces (not tabs) for indentation will be ignored, just to make the file look nice when writing.
|
||||
# This one is one of this cases that cares about multilines
|
||||
settings-general-steamvr-description =
|
||||
Enable or disable specific SteamVR trackers.
|
||||
settings-general-output_trackers-description =
|
||||
Enable or disable specific trackers to output.
|
||||
Useful for games or apps that only support certain trackers.
|
||||
settings-general-steamvr-trackers-waist = Waist
|
||||
settings-general-steamvr-trackers-chest = Chest
|
||||
@@ -522,10 +516,9 @@ settings-general-steamvr-trackers-right_elbow = Right elbow
|
||||
settings-general-steamvr-trackers-left_hand = Left hand
|
||||
settings-general-steamvr-trackers-right_hand = Right hand
|
||||
settings-general-steamvr-trackers-tracker_toggling = Automatic tracker assignment
|
||||
settings-general-steamvr-trackers-tracker_toggling-description = Automatically handles toggling SteamVR trackers on or off depending on your current tracker assignments.
|
||||
settings-general-output-trackers-tracker_toggling-description = Automatically handles toggling output trackers on or off depending on your current tracker assignments.
|
||||
settings-general-steamvr-trackers-tracker_toggling-label = Automatic tracker assignment
|
||||
settings-general-steamvr-trackers-hands-warning = <b>Warning:</b> Enabling the SteamVR hand trackers will disable inputs from real controllers.
|
||||
This should only be enabled if you are using SlimeVR for hand tracking.
|
||||
settings-general-output-trackers-hands-warning = <b>Warning:</b> Enabling the hand trackers will disable inputs from real controllers in SteamVR.
|
||||
|
||||
Are you sure you want to do this?
|
||||
settings-general-steamvr-trackers-hands-warning-cancel = Cancel
|
||||
@@ -547,25 +540,6 @@ settings-general-tracker_mechanics-filtering-type-prediction = Prediction
|
||||
settings-general-tracker_mechanics-filtering-type-prediction-description = Reduces latency and makes movements more snappy, but may increase jitter.
|
||||
settings-general-tracker_mechanics-filtering-amount = Amount
|
||||
settings-general-tracker_mechanics-yaw-reset-smooth-time = Yaw reset smooth time (0s disables smoothing)
|
||||
settings-general-tracker_mechanics-drift_compensation = Drift compensation
|
||||
# This cares about multilines
|
||||
settings-general-tracker_mechanics-drift_compensation-description =
|
||||
Compensates for IMU yaw drift by applying an inverse rotation.
|
||||
Change the amount of compensation and the number of resets taken into account.
|
||||
This should only be used if you need to reset very often!
|
||||
settings-general-tracker_mechanics-drift_compensation-enabled-label = Drift compensation
|
||||
settings-general-tracker_mechanics-drift_compensation-prediction = Drift compensation prediction
|
||||
# This cares about multilines
|
||||
settings-general-tracker_mechanics-drift_compensation-prediction-description =
|
||||
Predicts yaw drift compensation beyond previously measured range.
|
||||
Enable this if your trackers are continuously spinning on the yaw axis.
|
||||
settings-general-tracker_mechanics-drift_compensation-prediction-label = Drift compensation prediction
|
||||
settings-general-tracker_mechanics-drift_compensation_warning =
|
||||
<b>Warning:</b> Only use drift compensation if you need to reset
|
||||
very often (every ~5-10 minutes).
|
||||
|
||||
Some IMUs prone to frequent resets include:
|
||||
Joy-Cons, owoTrack, and MPUs (without recent firmware).
|
||||
settings-general-tracker_mechanics-drift_compensation_warning-cancel = Cancel
|
||||
settings-general-tracker_mechanics-drift_compensation_warning-done = I understand
|
||||
settings-general-tracker_mechanics-drift_compensation-amount-label = Compensation amount
|
||||
@@ -589,9 +563,8 @@ settings-stay_aligned = Stay Aligned
|
||||
settings-stay_aligned-description = Stay Aligned reduces drift by gradually adjusting your trackers to match your relaxed poses.
|
||||
settings-stay_aligned-setup-label = Setup Stay Aligned
|
||||
settings-stay_aligned-setup-description = You must complete "Setup Stay Aligned" to enable Stay Aligned.
|
||||
settings-stay_aligned-warnings-drift_compensation = ⚠ Please turn off Drift Compensation! Drift Compensation will conflict with Stay Aligned.
|
||||
settings-stay_aligned-enabled-label = Adjust trackers
|
||||
settings-stay_aligned-hide_yaw_correction-label = Hide adjustment (to compare with no Stay Aligned)
|
||||
settings-stay_aligned-hide_yaw_correction-label = Hide adjustment (to compare without Stay Aligned)
|
||||
settings-stay_aligned-general-label = General
|
||||
settings-stay_aligned-relaxed_poses-label = Relaxed Poses
|
||||
settings-stay_aligned-relaxed_poses-description = Stay Aligned uses your relaxed poses to keep the trackers aligned. Use "Setup Stay Aligned" to update these poses.
|
||||
@@ -653,17 +626,10 @@ settings-general-fk_settings-arm_fk-tpose_down = T-pose (down)
|
||||
settings-general-fk_settings-arm_fk-tpose_down-description = Expects your arms to be 90 degrees up to the sides during Full Reset, and down at your sides during Mounting Calibration.
|
||||
settings-general-fk_settings-arm_fk-forward = Forward
|
||||
settings-general-fk_settings-arm_fk-forward-description = Expects your arms to be raised forward at 90 degrees. Useful for VTubing.
|
||||
settings-general-fk_settings-skeleton_settings-toggles = Skeleton toggles
|
||||
settings-general-fk_settings-skeleton_settings-description = Toggle skeleton settings on or off. It is recommended to leave these on.
|
||||
settings-general-fk_settings-skeleton_settings-extended_spine_model = Extended spine model
|
||||
settings-general-fk_settings-skeleton_settings-extended_pelvis_model = Extended pelvis model
|
||||
settings-general-fk_settings-skeleton_settings-extended_knees_model = Extended knee model
|
||||
settings-general-fk_settings-skeleton_settings-ratios = Skeleton ratios
|
||||
settings-general-fk_settings-skeleton_settings-ratios-description = Change the values of skeleton settings. You may need to adjust your proportions after changing these.
|
||||
settings-general-fk_settings-skeleton_settings-impute_waist_from_chest_hip = Impute waist from chest to hip
|
||||
settings-general-fk_settings-skeleton_settings-impute_waist_from_chest_legs = Impute waist from chest to legs
|
||||
settings-general-fk_settings-skeleton_settings-impute_hip_from_chest_legs = Impute hip from chest to legs
|
||||
settings-general-fk_settings-skeleton_settings-impute_hip_from_waist_legs = Impute hip from waist to legs
|
||||
settings-general-fk_settings-skeleton_settings-impute_spine_from_top_down = Impute missing spine trackers from upper to lower
|
||||
settings-general-fk_settings-skeleton_settings-impute_spine_curvature = How much to curve the spine with at least 2 adjacent spine trackers
|
||||
settings-general-fk_settings-skeleton_settings-interp_hip_legs = Average the hip's yaw and roll with the legs'
|
||||
settings-general-fk_settings-skeleton_settings-interp_knee_tracker_ankle = Average the knee trackers' yaw and roll with the ankles'
|
||||
settings-general-fk_settings-skeleton_settings-interp_knee_ankle = Average the knees' yaw and roll with the ankles'
|
||||
@@ -695,7 +661,7 @@ settings-general-gesture_control-fullResetEnabled = Enable tap to full reset
|
||||
settings-general-gesture_control-fullResetDelay = Full reset delay
|
||||
settings-general-gesture_control-fullResetTaps = Taps for full reset
|
||||
settings-general-gesture_control-fullResetTracker = Full Reset Tracker
|
||||
settings-general-gesture_control-mountingResetEnabled = Enable tap to perform mounting calibration
|
||||
settings-general-gesture_control-mountingResetEnabled = Enable tap to mounting reset
|
||||
settings-general-gesture_control-mountingResetDelay = Mounting calibration delay
|
||||
settings-general-gesture_control-mountingResetTaps = Taps for mounting calibration
|
||||
settings-general-gesture_control-mountingResetTracker = Mounting Reset Tracker
|
||||
@@ -790,6 +756,12 @@ settings-serial-factory_reset-warning-cancel = Cancel
|
||||
settings-serial-serial_select = Select a serial port
|
||||
settings-serial-auto_dropdown_item = Auto
|
||||
settings-serial-get_wifi_scan = Get WiFi Scan
|
||||
settings-serial-enter_pairing = Enter Pairing
|
||||
settings-serial-exit_pairing = Exit Pairing
|
||||
settings-serial-calibrate = Calibrate
|
||||
settings-serial-six_side_calibrate = 6-Side Calibrate
|
||||
settings-serial-dfu = Enter DFU
|
||||
settings-serial-meow = Meow!
|
||||
settings-serial-file_type = Plain text
|
||||
settings-serial-save_logs = Save To File
|
||||
settings-serial-send_command = Send
|
||||
@@ -799,30 +771,6 @@ settings-serial-send_command-warning =
|
||||
settings-serial-send_command-warning-ok = I know what I'm doing
|
||||
settings-serial-send_command-warning-cancel = Cancel
|
||||
|
||||
## OSC router settings
|
||||
settings-osc-router = OSC router
|
||||
# This cares about multilines
|
||||
settings-osc-router-description =
|
||||
Forward OSC messages from another program.
|
||||
Useful for using another OSC program with VRChat, for example.
|
||||
settings-osc-router-enable = Enable
|
||||
settings-osc-router-enable-description = Toggle the forwarding of messages.
|
||||
settings-osc-router-enable-label = Enable
|
||||
settings-osc-router-network = Network ports
|
||||
# This cares about multilines
|
||||
settings-osc-router-network-description =
|
||||
Set the ports for listening and sending data.
|
||||
These can be the same as other ports used in the SlimeVR server.
|
||||
settings-osc-router-network-port_in =
|
||||
.label = Port In
|
||||
.placeholder = Port in (default: 9002)
|
||||
settings-osc-router-network-port_out =
|
||||
.label = Port Out
|
||||
.placeholder = Port out (default: 9000)
|
||||
settings-osc-router-network-address = Network address
|
||||
settings-osc-router-network-address-description = Set the address to send out data at.
|
||||
settings-osc-router-network-address-placeholder = IPV4 address
|
||||
|
||||
## OSC VRChat settings
|
||||
settings-osc-vrchat = VRChat OSC Trackers
|
||||
# This cares about multilines
|
||||
@@ -851,13 +799,40 @@ settings-osc-vrchat-network-port_out =
|
||||
settings-osc-vrchat-network-address = Network address
|
||||
settings-osc-vrchat-network-address-description-v1 = Choose which address to send out data to. Can be left untouched for VRChat.
|
||||
settings-osc-vrchat-network-address-placeholder = VRChat ip address
|
||||
settings-osc-vrchat-network-trackers = Trackers
|
||||
settings-osc-vrchat-network-trackers-description = Toggle the sending of specific trackers via OSC.
|
||||
settings-osc-vrchat-network-trackers-chest = Chest
|
||||
settings-osc-vrchat-network-trackers-hip = Hip
|
||||
settings-osc-vrchat-network-trackers-knees = Knees
|
||||
settings-osc-vrchat-network-trackers-feet = Feet
|
||||
settings-osc-vrchat-network-trackers-elbows = Elbows
|
||||
|
||||
## VRChat OSC status
|
||||
settings-osc-vrchat-status-title = Status
|
||||
settings-osc-vrchat-status-disabled = Disabled
|
||||
settings-osc-vrchat-status-input = Input
|
||||
settings-osc-vrchat-status-output = Output
|
||||
settings-osc-vrchat-status-oscquery = OSCQuery
|
||||
settings-osc-vrchat-status-input-idle = Not listening
|
||||
settings-osc-vrchat-status-input-listening = Listening on port {$port}
|
||||
settings-osc-vrchat-status-input-last-data = Last data from VRChat: {$elapsed}
|
||||
settings-osc-vrchat-status-input-no-data = No data received from VRChat yet
|
||||
settings-osc-vrchat-status-output-idle = No target
|
||||
settings-osc-vrchat-status-output-sending = Sending to {$address}:{$port} ({$source})
|
||||
settings-osc-vrchat-status-output-target = Target {$address}:{$port} ({$source})
|
||||
settings-osc-vrchat-status-output-last-frame = Last frame sent: {$elapsed}
|
||||
settings-osc-vrchat-status-output-no-frame = No frame sent yet
|
||||
settings-osc-vrchat-status-source-manual = manual
|
||||
settings-osc-vrchat-status-source-auto = auto-detected
|
||||
settings-osc-vrchat-status-oscquery-disabled = OSCQuery off (manual network mode)
|
||||
settings-osc-vrchat-status-oscquery-advertising = Advertising on port {$port}
|
||||
settings-osc-vrchat-status-oscquery-searching = No VRChat clients found yet
|
||||
settings-osc-vrchat-status-oscquery-discovered-title = Discovered VRChat clients:
|
||||
settings-osc-vrchat-status-oscquery-switch = Switch
|
||||
settings-osc-vrchat-status-network-mode = Network mode
|
||||
settings-osc-vrchat-status-network-mode-description = Automatic mode discovers VRChat through OSCQuery. Manual mode uses the configured address and ports.
|
||||
settings-osc-vrchat-status-network-mode-toggle = Manual network settings
|
||||
settings-osc-vrchat-status-network-manual-description = Configure the local input port and the VRChat OSC target manually.
|
||||
settings-osc-vrchat-status-badge-idle = Idle
|
||||
settings-osc-vrchat-status-badge-listening = Listening
|
||||
settings-osc-vrchat-status-badge-ready = Ready
|
||||
settings-osc-vrchat-status-badge-found = Found
|
||||
settings-osc-vrchat-status-badge-searching = Searching
|
||||
settings-osc-vrchat-status-badge-disabled = Disabled
|
||||
settings-osc-vrchat-status-badge-error = Error
|
||||
|
||||
## VMC OSC settings
|
||||
settings-osc-vmc = Virtual Motion Capture
|
||||
@@ -891,7 +866,7 @@ settings-osc-vmc-mirror_tracking-description = Mirror the tracking horizontally.
|
||||
settings-osc-vmc-mirror_tracking-label = Mirror tracking
|
||||
|
||||
## Common OSC settings
|
||||
settings-osc-common-network-ports_match_error = The OSC Router in and out ports can't be the same!
|
||||
settings-osc-common-network-ports_match_error-v2 = The in and out ports can't be the same!
|
||||
settings-osc-common-network-port_banned_error = The port { $port } can't be used!
|
||||
|
||||
## Advanced settings
|
||||
@@ -1657,12 +1632,20 @@ tracking_checklist-MOUNTING_CALIBRATION = Perform a mounting calibration
|
||||
tracking_checklist-FEET_MOUNTING_CALIBRATION = Perform a feet mounting calibration
|
||||
tracking_checklist-FULL_RESET = Perform a full reset
|
||||
tracking_checklist-FULL_RESET-desc = Some trackers need a reset to be performed.
|
||||
tracking_checklist-STEAMVR_DISCONNECTED = SteamVR not running
|
||||
tracking_checklist-STEAMVR_DISCONNECTED = SteamVR disconnected
|
||||
tracking_checklist-STEAMVR_DISCONNECTED-desc = SteamVR is not running. Are you using it for VR?
|
||||
tracking_checklist-STEAMVR_DISCONNECTED-driver_blocked-desc = The driver has been blocked by SteamVR due to a previous SteamVR crash.
|
||||
tracking_checklist-STEAMVR_DISCONNECTED-driver_disabled-desc = The driver is disabled in SteamVR settings.
|
||||
tracking_checklist-STEAMVR_DISCONNECTED-driver_not_installed-desc = The driver is not installed.
|
||||
tracking_checklist-STEAMVR_DISCONNECTED-open = Launch SteamVR
|
||||
tracking_checklist-STEAMVR_DISCONNECTED-enable = Enable driver
|
||||
tracking_checklist-STEAMVR_HANDS_ENABLED = Hand trackers toggled on
|
||||
tracking_checklist-STEAMVR_HANDS_ENABLED-desc = You have enabled the SteamVR virtual hand trackers. This will cause button inputs to not work in SteamVR and in games.
|
||||
tracking_checklist-STEAMVR_HANDS_ENABLED-go = Disable them
|
||||
tracking_checklist-STANDABLE_INSTALLED = Standable is installed
|
||||
tracking_checklist-STANDABLE_INSTALLED-desc =
|
||||
Standable frequently causes tracking issues when used alongside SlimeVR. Standable should be fully uninstalled in Steam to ensure no issues arise.
|
||||
You must close SteamVR before uninstalling Standable in Steam.
|
||||
tracking_checklist-TRACKERS_REST_CALIBRATION = Calibrate your trackers
|
||||
tracking_checklist-TRACKERS_REST_CALIBRATION-desc = You didn't perform tracker calibration. Please let your trackers (highlighted in yellow) rest on a stable surface for a few seconds.
|
||||
tracking_checklist-TRACKER_ERROR = Trackers with Errors
|
||||
|
||||
@@ -28,7 +28,6 @@ import { SerialDetectionModal } from './components/SerialDetectionModal';
|
||||
import { VRCOSCSettings } from './components/settings/pages/VRCOSCSettings';
|
||||
import { TopBar } from './components/TopBar';
|
||||
import { TrackerSettingsPage } from './components/tracker/TrackerSettings';
|
||||
import { OSCRouterSettings } from './components/settings/pages/OSCRouterSettings';
|
||||
import { VMCSettings } from './components/settings/pages/VMCSettings';
|
||||
import { MountingChoose } from './components/onboarding/pages/mounting/MountingChoose';
|
||||
import { VersionUpdateModal } from './components/VersionUpdateModal';
|
||||
@@ -139,7 +138,6 @@ function Layout() {
|
||||
<Route path="firmware-tool" element={<FirmwareToolSettings />} />
|
||||
<Route path="trackers" element={<GeneralSettings />} />
|
||||
<Route path="serial" element={<Serial />} />
|
||||
<Route path="osc/router" element={<OSCRouterSettings />} />
|
||||
<Route path="osc/vrchat" element={<VRCOSCSettings />} />
|
||||
<Route path="osc/vmc" element={<VMCSettings />} />
|
||||
<Route path="interface" element={<InterfaceSettings />} />
|
||||
|
||||
@@ -34,7 +34,7 @@ export function NavButton({
|
||||
className={classnames(
|
||||
'flex flex-col justify-center xs:gap-4 mobile:gap-2',
|
||||
'mobile:w-[65px] mobile:h-[65px]',
|
||||
'xs:py-3 mobile:py-4 rounded-md mobile:rounded-b-none group select-text',
|
||||
'xs:py-3 mobile:py-4 rounded-md mobile:rounded-b-none group',
|
||||
{
|
||||
'bg-accent-background-50 fill-accent-background-20': doesMatch,
|
||||
'hover:bg-background-70': !doesMatch,
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
NewSerialDeviceResponseT,
|
||||
RpcMessage,
|
||||
SerialDeviceT,
|
||||
SerialDeviceType,
|
||||
} from 'solarxr-protocol';
|
||||
import { useConfig } from '@/hooks/config';
|
||||
import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
@@ -56,7 +57,8 @@ export function SerialDetectionModal() {
|
||||
'/settings/serial',
|
||||
'/onboarding/connect-trackers',
|
||||
'/settings/firmware-tool',
|
||||
].includes(pathname)
|
||||
].includes(pathname) &&
|
||||
device?.type !== SerialDeviceType.HID_RECEIVER
|
||||
) {
|
||||
setOpen(device);
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ function BasicResetButton(options: UseResetOptions & { customName?: string }) {
|
||||
const name = options.customName || resetName;
|
||||
|
||||
const skiReset =
|
||||
options.type === ResetType.Mounting && options.group === 'default';
|
||||
options.type === ResetType.MOUNTING && options.group === 'default';
|
||||
|
||||
return (
|
||||
<Tooltip
|
||||
@@ -175,8 +175,8 @@ export function Toolbar() {
|
||||
<div className="flex-col flex gap-1 md:w-[60%]">
|
||||
<Typography variant="section-title" id="toolbar-drift_reset" />
|
||||
<div className="gap-2 md:h-[72px] h-[62px] w-full grid-cols-2 grid">
|
||||
<BasicResetButton type={ResetType.Full} />
|
||||
<BasicResetButton type={ResetType.Yaw} />
|
||||
<BasicResetButton type={ResetType.FULL} />
|
||||
<BasicResetButton type={ResetType.YAW} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-col flex gap-1 md:flex-grow">
|
||||
@@ -191,18 +191,18 @@ export function Toolbar() {
|
||||
}}
|
||||
>
|
||||
<BasicResetButton
|
||||
type={ResetType.Mounting}
|
||||
type={ResetType.MOUNTING}
|
||||
group={'default'}
|
||||
customName="toolbar-mounting_calibration-default"
|
||||
/>
|
||||
<BasicResetButton
|
||||
type={ResetType.Mounting}
|
||||
type={ResetType.MOUNTING}
|
||||
group={'feet'}
|
||||
customName="toolbar-mounting_calibration-feet"
|
||||
/>
|
||||
{groupVisibility['fingers'] && (
|
||||
<BasicResetButton
|
||||
type={ResetType.Mounting}
|
||||
type={ResetType.MOUNTING}
|
||||
group={'fingers'}
|
||||
customName="toolbar-mounting_calibration-fingers"
|
||||
/>
|
||||
|
||||
@@ -14,13 +14,13 @@ export function InnerSystemFileInput({
|
||||
value,
|
||||
onChange,
|
||||
directory,
|
||||
ref,
|
||||
refCallback: refCallback,
|
||||
}: {
|
||||
label: string;
|
||||
value: string | null;
|
||||
onChange: (...event: any[]) => void;
|
||||
directory: boolean;
|
||||
ref: RefCallBack;
|
||||
refCallback: RefCallBack;
|
||||
}) {
|
||||
const electron = useElectron();
|
||||
|
||||
@@ -38,7 +38,7 @@ export function InnerSystemFileInput({
|
||||
};
|
||||
|
||||
return (
|
||||
<div ref={ref} onClick={handleClick}>
|
||||
<div ref={refCallback} onClick={handleClick}>
|
||||
{value !== null
|
||||
? FileInputContentFile({
|
||||
directory,
|
||||
@@ -77,7 +77,7 @@ export function SystemFileInput<T extends FieldValues = FieldValues>({
|
||||
label={label}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
ref={ref}
|
||||
refCallback={ref}
|
||||
directory={directory}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
export function HorizontalAlignIcon({ size = 22 }) {
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
height={size}
|
||||
viewBox="0 -960 960 960"
|
||||
width={size}
|
||||
fill="#e3e3e3"
|
||||
>
|
||||
<path d="M733.15-312.35 565.5-480l167.65-167.65L796.8-584l-57.73 58.5h160.06v91H739.07L796.8-376l-63.65 63.65ZM434.5-151.87v-656.26h91v656.26h-91ZM226.85-312.35 163.2-376l57.73-58.5H60.87v-91h160.06L163.2-584l63.65-63.65L394.5-480 226.85-312.35Z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
export function MartialArtsIcon({ size = 23 }) {
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
height={size}
|
||||
viewBox="0 -960 960 960"
|
||||
width={size}
|
||||
fill="#e3e3e3"
|
||||
>
|
||||
<path d="m404.07-69-20-364.54-128.68-73.96-12.56 46.02 82.19 142.68-75.22 43.82-101.87-174.54 48.96-174.87 227.13-130.33L314.98-864 376-925.02l189.98 188.74-143.76 82.76 49.43 41.04 328.48-268.48 52.31 61.26-341.2 345.68L491-69h-86.93Zm-212.2-609.09q-34.44 0-59.13-24.69-24.7-24.7-24.7-59.13 0-34.44 24.7-59.01 24.69-24.58 59.13-24.58 34.43 0 59.01 24.58 24.58 24.57 24.58 59.01 0 34.43-24.58 59.13-24.58 24.69-59.01 24.69Z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
export function OutputIcon({ size = 22 }) {
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
height={size}
|
||||
viewBox="0 -960 960 960"
|
||||
width={size}
|
||||
fill="#e3e3e3"
|
||||
>
|
||||
<path d="M202.87-111.87q-37.78 0-64.39-26.61t-26.61-64.39v-554.26q0-37.78 26.61-64.39t64.39-26.61h554.5q37.78 0 64.39 26.61t26.61 64.39v76.41h-91v-76.41h-554.5v554.26h554.5v-76.41h91v76.41q0 37.78-26.61 64.39t-64.39 26.61h-554.5Zm481.2-164.06-63.66-63.66 93.92-94.91H353.78v-91h360.55l-93.92-94.91 63.66-63.66L888.13-480 684.07-275.93Z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
export function TouchDoubleIcon({ size = 22 }) {
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
height={size}
|
||||
viewBox="0 -960 960 960"
|
||||
width={size}
|
||||
fill="#e3e3e3"
|
||||
>
|
||||
<path d="M411.59-71.87q-31.92 0-59.85-13.68-27.93-13.69-47.31-38.78L83.8-405.63l27.13-25.26q22.4-21.72 52.91-25.48 30.51-3.76 56.9 12.44l67.3 40.45V-721.2q0-18.67 12.82-31.48 12.81-12.82 31.5-12.82 18.68 0 31.87 12.82 13.18 12.81 13.18 31.48v475.35l-106.08-64.3L375.8-177.63q6.72 7.96 15.87 12.55 9.15 4.6 19.44 4.6h232.72q31.22 0 53.46-22.23 22.23-22.24 22.23-53.46v-151.87q0-20.11-13.89-34t-34-13.89H457.41v-88.61h214.22q56.7 0 96.6 39.9 39.9 39.9 39.9 96.6v151.87q0 67.91-48.2 116.1-48.19 48.2-116.1 48.2H411.59ZM151.93-616.65q-13.57-22.95-20.88-49.55-7.31-26.6-7.31-54.76 0-86.58 61.03-147.59 61.02-61.02 147.61-61.02 28.16 0 54.12 6.86 25.96 6.86 48.91 20.34 48.92 27.44 77.23 76.23 28.32 48.79 28.32 105.14 0 28.17-7.31 54.78t-20.89 49.57l-76.41-44.31q8-14 12-28.5t4-31.5q0-32-16.5-60t-44.5-44q-13-8-28-12t-31-4q-50 0-85 35t-35 85q0 17 4 31.5t12 28.5l-76.42 44.31Zm343.61 274.02Zm62.98-482.33 44.07-77.41q48.91 27.44 77.23 76.23 28.31 48.79 28.31 105.14 0 28.17-7.31 54.78t-20.89 49.57l-76.41-44.31q8-14 12-28.5t4-31.5q0-32-16.5-60t-44.5-44Z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
File renamed without changes.
@@ -13,6 +13,7 @@ import {
|
||||
NewSerialDeviceResponseT,
|
||||
RpcMessage,
|
||||
SerialDeviceT,
|
||||
SerialDeviceType,
|
||||
SerialDevicesRequestT,
|
||||
SerialDevicesResponseT,
|
||||
TrackerStatus,
|
||||
@@ -77,13 +78,14 @@ function SerialDevicesList({
|
||||
RpcMessage.SerialDevicesResponse,
|
||||
(res: SerialDevicesResponseT) => {
|
||||
setDevices(
|
||||
res.devices.reduce(
|
||||
(curr, device) => ({
|
||||
res.devices.reduce((curr, device) => {
|
||||
if (device?.type != SerialDeviceType.ESP_TRACKER) return curr;
|
||||
|
||||
return {
|
||||
...curr,
|
||||
[device?.port?.toString() ?? 'unknown']: device,
|
||||
}),
|
||||
{}
|
||||
)
|
||||
};
|
||||
}, {})
|
||||
);
|
||||
setLoading(false);
|
||||
}
|
||||
@@ -92,7 +94,7 @@ function SerialDevicesList({
|
||||
useRPCPacket(
|
||||
RpcMessage.NewSerialDeviceResponse,
|
||||
({ device }: NewSerialDeviceResponseT) => {
|
||||
if (device?.port)
|
||||
if (device?.port && device?.type === SerialDeviceType.ESP_TRACKER)
|
||||
setDevices((old) => ({
|
||||
...old,
|
||||
[device?.port?.toString() ?? 'unknown']: device,
|
||||
|
||||
@@ -27,7 +27,7 @@ export function Home() {
|
||||
|
||||
const sendToSettings = (tracker: TrackerDataT) => {
|
||||
navigate(
|
||||
`/tracker/${tracker.trackerId?.trackerNum}/${tracker.trackerId?.deviceId?.id}`
|
||||
`/tracker/${tracker.trackerId}/${tracker.deviceId}`
|
||||
);
|
||||
};
|
||||
|
||||
@@ -86,8 +86,8 @@ export function Home() {
|
||||
warning={
|
||||
!!highlightedTrackers?.trackers.find(
|
||||
(t) =>
|
||||
t?.deviceId?.id === tracker.trackerId?.deviceId?.id &&
|
||||
t?.trackerNum === tracker.trackerId?.trackerNum
|
||||
t?.deviceId?.id === tracker.deviceId &&
|
||||
t?.trackerNum === tracker.trackerId
|
||||
) && highlightedTrackers.step
|
||||
}
|
||||
/>
|
||||
@@ -128,8 +128,8 @@ export function Home() {
|
||||
warning={
|
||||
!!highlightedTrackers?.trackers.find(
|
||||
(t) =>
|
||||
t?.deviceId?.id === tracker.trackerId?.deviceId?.id &&
|
||||
t?.trackerNum === tracker.trackerId?.trackerNum
|
||||
t?.deviceId?.id === tracker.deviceId &&
|
||||
t?.trackerNum === tracker.trackerId
|
||||
) && highlightedTrackers.step
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -15,12 +15,12 @@ import { Tooltip } from '@/components/commons/Tooltip';
|
||||
import { Typography } from '@/components/commons/Typography';
|
||||
|
||||
export function ResetButtonIcon(options: UseResetOptions) {
|
||||
if (options.type === ResetType.Mounting && !options.group)
|
||||
if (options.type === ResetType.MOUNTING && !options.group)
|
||||
options.group = 'default';
|
||||
|
||||
if (options.type === ResetType.Yaw) return <YawResetIcon width={18} />;
|
||||
if (options.type === ResetType.Full) return <FullResetIcon width={18} />;
|
||||
if (options.type === ResetType.Mounting) {
|
||||
if (options.type === ResetType.YAW) return <YawResetIcon width={18} />;
|
||||
if (options.type === ResetType.FULL) return <FullResetIcon width={18} />;
|
||||
if (options.type === ResetType.MOUNTING) {
|
||||
if (options.group === 'default') return <SkiIcon />;
|
||||
if (options.group === 'feet') return <FootIcon />;
|
||||
if (options.group === 'fingers') return <FingersIcon width={16} />;
|
||||
@@ -83,7 +83,7 @@ export function ResetButton({
|
||||
<div className="opacity-0 h-0">
|
||||
{children || <Localized id={name} />}
|
||||
</div>
|
||||
{status !== 'counting' || options.type === ResetType.Yaw
|
||||
{status !== 'counting' || options.type === ResetType.YAW
|
||||
? children || <Localized id={name} />
|
||||
: String(timer)}
|
||||
</div>
|
||||
|
||||
@@ -200,7 +200,7 @@ export const RIGHT_LEG_PARTS = [
|
||||
];
|
||||
|
||||
export const RESET_TYPE_ORDER = [
|
||||
ResetType.Yaw,
|
||||
ResetType.Full,
|
||||
ResetType.Mounting,
|
||||
ResetType.YAW,
|
||||
ResetType.FULL,
|
||||
ResetType.MOUNTING,
|
||||
];
|
||||
@@ -28,7 +28,7 @@ function IncrementButton({
|
||||
<div
|
||||
onClick={onClick}
|
||||
className={classNames(
|
||||
'p-3 rounded-lg xs:w-10 xs:h-10 flex flex-col justify-center items-center cursor-pointer',
|
||||
'no-user-drag p-3 rounded-lg xs:w-10 xs:h-10 flex flex-col justify-center items-center cursor-pointer',
|
||||
'hover:bg-opacity-50 active:bg-accent-background-30',
|
||||
{ 'bg-background-60': bgDark, 'bg-background-40': !bgDark }
|
||||
)}
|
||||
|
||||
@@ -34,7 +34,7 @@ function IncrementButton({
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
'flex rounded-md items-center justify-center flex-row xs:flex-col w-full gap-1 p-3 xs:p-2 xs:w-[75px] xs:h-[75px]',
|
||||
'no-user-drag flex rounded-md items-center justify-center flex-row xs:flex-col w-full gap-1 p-3 xs:p-2 xs:w-[75px] xs:h-[75px]',
|
||||
{
|
||||
'cursor-not-allowed bg-background-80 opacity-50': disabled,
|
||||
'bg-background-50 hover:bg-background-40 cursor-pointer': !disabled,
|
||||
@@ -74,7 +74,7 @@ function UnitSelector({
|
||||
'bg-accent-background-30': active,
|
||||
'hover:bg-background-40 bg-background-40': !active,
|
||||
},
|
||||
'flex items-center justify-center rounded-md outline-background-10 cursor-pointer'
|
||||
'no-user-drag flex items-center justify-center rounded-md outline-background-10 cursor-pointer'
|
||||
)}
|
||||
onClick={onClick}
|
||||
>
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
import { Control, Controller, useForm } from 'react-hook-form';
|
||||
import {
|
||||
ChangeSkeletonConfigRequestT,
|
||||
ChangeSkeletonProportionsRequestT,
|
||||
ResetType,
|
||||
RpcMessage,
|
||||
SkeletonBone,
|
||||
SkeletonConfigRequestT,
|
||||
SkeletonConfigResponseT,
|
||||
SkeletonResetAllRequestT,
|
||||
SkeletonBone, SkeletonProportionsRequestT, SkeletonProportionsResetAllRequestT, SkeletonProportionsResponseT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useOnboarding } from '@/hooks/onboarding';
|
||||
import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
@@ -85,7 +82,7 @@ function IconButton({
|
||||
|
||||
function parseConfigImport(
|
||||
config: SkeletonConfigExport
|
||||
): ChangeSkeletonConfigRequestT[] {
|
||||
): ChangeSkeletonProportionsRequestT[] {
|
||||
if (!config.version) config.version = 1;
|
||||
if (config.version < 1) {
|
||||
// Add config migration stuff here, this one is just an example.
|
||||
@@ -95,7 +92,7 @@ function parseConfigImport(
|
||||
const bone =
|
||||
typeof part.bone === 'string' ? SkeletonBone[part.bone] : part.bone;
|
||||
|
||||
return new ChangeSkeletonConfigRequestT(bone, part.value);
|
||||
return new ChangeSkeletonProportionsRequestT(bone, part.value);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -121,7 +118,7 @@ function ImportExportButtons() {
|
||||
const exporting = useRef(false);
|
||||
|
||||
useRPCPacket(
|
||||
RpcMessage.SkeletonConfigResponse,
|
||||
RpcMessage.SkeletonProportionsResponse,
|
||||
(data: SkeletonConfigExport) => {
|
||||
if (!exporting.current) return;
|
||||
exporting.current = false;
|
||||
@@ -183,11 +180,11 @@ function ImportExportButtons() {
|
||||
}
|
||||
|
||||
parseConfigImport(config).forEach((req) =>
|
||||
sendRPCPacket(RpcMessage.ChangeSkeletonConfigRequest, req)
|
||||
sendRPCPacket(RpcMessage.ChangeSkeletonProportionsRequest, req)
|
||||
);
|
||||
sendRPCPacket(
|
||||
RpcMessage.SkeletonConfigRequest,
|
||||
new SkeletonConfigRequestT()
|
||||
RpcMessage.SkeletonProportionsRequest,
|
||||
new SkeletonProportionsRequestT()
|
||||
);
|
||||
setImportState(ImportStatus.SUCCESS);
|
||||
setTimeout(() => {
|
||||
@@ -219,8 +216,8 @@ function ImportExportButtons() {
|
||||
exporting.current = true;
|
||||
|
||||
sendRPCPacket(
|
||||
RpcMessage.SkeletonConfigRequest,
|
||||
new SkeletonConfigRequestT()
|
||||
RpcMessage.SkeletonProportionsRequest,
|
||||
new SkeletonProportionsRequestT()
|
||||
);
|
||||
}}
|
||||
>
|
||||
@@ -311,16 +308,17 @@ function ButtonsControl({ control }: { control: ManualProportionControls }) {
|
||||
const [showWarning, setShowWarning] = useState(false);
|
||||
const resetAll = () => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.SkeletonResetAllRequest,
|
||||
new SkeletonResetAllRequestT()
|
||||
RpcMessage.SkeletonProportionsResetAllRequest,
|
||||
new SkeletonProportionsResetAllRequestT()
|
||||
);
|
||||
};
|
||||
|
||||
const beneathFloor = useMemo(() => {
|
||||
// TODO I think this needs to be rewritten with rewrite but it also just may be unneeded
|
||||
const hmd = computedTrackers.find(
|
||||
(tracker) =>
|
||||
tracker.tracker.trackerId?.trackerNum === 1 &&
|
||||
tracker.tracker.trackerId.deviceId?.id === undefined
|
||||
tracker.tracker.trackerId === 1 &&
|
||||
tracker.tracker.deviceId === undefined
|
||||
);
|
||||
return !(hmd?.tracker.position && hmd.tracker.position.y >= MIN_HEIGHT);
|
||||
}, [computedTrackers]);
|
||||
@@ -418,8 +416,8 @@ export function ManualProportionsPage() {
|
||||
}, [ratio]);
|
||||
|
||||
useRPCPacket(
|
||||
RpcMessage.SkeletonConfigResponse,
|
||||
(data: SkeletonConfigResponseT) => {
|
||||
RpcMessage.SkeletonProportionsResponse,
|
||||
(data: SkeletonProportionsResponseT) => {
|
||||
if (data.userHeight) setUserHeight(data.userHeight);
|
||||
}
|
||||
);
|
||||
@@ -470,7 +468,7 @@ export function ManualProportionsPage() {
|
||||
<div className="top-4 w-full px-4 absolute flex gap-2 flex-col lg:flex-row md:flex-wrap">
|
||||
<div className="h-14 flex flex-grow items-center">
|
||||
<ResetButton
|
||||
type={ResetType.Full}
|
||||
type={ResetType.FULL}
|
||||
className="w-full h-full bg-background-50 hover:bg-background-40 text-background-10"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -7,14 +7,12 @@ import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
import { useEffect, useState } from 'react';
|
||||
import {
|
||||
CancelUserHeightCalibrationT,
|
||||
ChangeSettingsRequestT,
|
||||
ModelSettingsT,
|
||||
ResetType,
|
||||
RpcMessage,
|
||||
SkeletonConfigRequestT,
|
||||
SkeletonConfigResponseT,
|
||||
SkeletonHeightT,
|
||||
SkeletonResetAllRequestT,
|
||||
SkeletonProportionsRequestT,
|
||||
SkeletonProportionsResetAllRequestT,
|
||||
SkeletonProportionsResponseT,
|
||||
StartUserHeightCalibrationT,
|
||||
UserHeightCalibrationStatus,
|
||||
UserHeightRecordingStatusResponseT,
|
||||
@@ -265,7 +263,7 @@ export function ScaledProportionsPage() {
|
||||
);
|
||||
};
|
||||
|
||||
// Makes it so you dont get spammed by sounds if multiple status complete at once
|
||||
// Makes it so you don't get spammed by sounds if multiple status complete at once
|
||||
useDebouncedEffect(
|
||||
() => {
|
||||
if (!config || !config.feedbackSound) return;
|
||||
@@ -295,8 +293,8 @@ export function ScaledProportionsPage() {
|
||||
);
|
||||
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settingsRequest);
|
||||
sendRPCPacket(
|
||||
RpcMessage.SkeletonResetAllRequest,
|
||||
new SkeletonResetAllRequestT()
|
||||
RpcMessage.SkeletonProportionsResetAllRequest,
|
||||
new SkeletonProportionsResetAllRequestT()
|
||||
);
|
||||
setConfig({ lastUsedProportions: 'scaled' });
|
||||
setLastUsed('manual');
|
||||
@@ -320,8 +318,8 @@ export function ScaledProportionsPage() {
|
||||
);
|
||||
|
||||
useRPCPacket(
|
||||
RpcMessage.SkeletonConfigResponse,
|
||||
(res: SkeletonConfigResponseT) => {
|
||||
RpcMessage.SkeletonProportionsResponse,
|
||||
(res: SkeletonProportionsResponseT) => {
|
||||
setHmdHeight(res.userHeight);
|
||||
}
|
||||
);
|
||||
@@ -336,8 +334,8 @@ export function ScaledProportionsPage() {
|
||||
|
||||
useEffect(() => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.SkeletonConfigRequest,
|
||||
new SkeletonConfigRequestT()
|
||||
RpcMessage.SkeletonProportionsRequest,
|
||||
new SkeletonProportionsRequestT()
|
||||
);
|
||||
|
||||
return () => {
|
||||
@@ -356,8 +354,8 @@ export function ScaledProportionsPage() {
|
||||
if (status && checkNotAuto(status.status)) {
|
||||
setAuto(false);
|
||||
sendRPCPacket(
|
||||
RpcMessage.SkeletonConfigRequest,
|
||||
new SkeletonConfigRequestT()
|
||||
RpcMessage.SkeletonProportionsRequest,
|
||||
new SkeletonProportionsRequestT()
|
||||
); // Re ask the user height so it resets back to the correct value
|
||||
}
|
||||
},
|
||||
@@ -469,7 +467,7 @@ export function ScaledProportionsPage() {
|
||||
state={{ alonePage: state.alonePage }}
|
||||
/>
|
||||
<ResetButton
|
||||
type={ResetType.Full}
|
||||
type={ResetType.FULL}
|
||||
className="bg-background-50 hover:bg-background-40 text-background-10"
|
||||
/>
|
||||
</>
|
||||
|
||||
@@ -69,7 +69,7 @@ export function PreparationStep({
|
||||
>
|
||||
{l10n.getString('onboarding-automatic_mounting-prev_step')}
|
||||
</Button>
|
||||
<ResetButton type={ResetType.Full} onReseted={nextStep} />
|
||||
<ResetButton type={ResetType.FULL} onReseted={nextStep} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -56,7 +56,6 @@ export function ManualMountingPage() {
|
||||
mountingOrientationDegrees
|
||||
);
|
||||
assignreq.trackerId = td.tracker.trackerId;
|
||||
assignreq.allowDriftCompensation = false;
|
||||
|
||||
sendRPCPacket(RpcMessage.AssignTrackerRequest, assignreq);
|
||||
Sentry.metrics.count('manual_mounting_set', 1, {
|
||||
@@ -177,7 +176,6 @@ export function ManualMountingPageStayAligned({
|
||||
mountingOrientationDegrees
|
||||
);
|
||||
assignreq.trackerId = td.tracker.trackerId;
|
||||
assignreq.allowDriftCompensation = false;
|
||||
|
||||
sendRPCPacket(RpcMessage.AssignTrackerRequest, assignreq);
|
||||
Sentry.metrics.count('manual_mounting_set', 1, {
|
||||
|
||||
@@ -58,7 +58,7 @@ export function MountingResetStep({
|
||||
{l10n.getString('onboarding-automatic_mounting-prev_step')}
|
||||
</Button>
|
||||
<ResetButton
|
||||
type={ResetType.Mounting}
|
||||
type={ResetType.MOUNTING}
|
||||
group="default"
|
||||
onReseted={nextStep}
|
||||
/>
|
||||
|
||||
@@ -69,7 +69,7 @@ export function PreparationStep({
|
||||
>
|
||||
{l10n.getString('onboarding-automatic_mounting-prev_step')}
|
||||
</Button>
|
||||
<ResetButton type={ResetType.Full} onReseted={nextStep} />
|
||||
<ResetButton type={ResetType.FULL} onReseted={nextStep} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -5,7 +5,7 @@ import { HumanIcon } from '@/components/commons/icon/HumanIcon';
|
||||
import { HeadsetIcon } from '@/components/commons/icon/HeadsetIcon';
|
||||
import { useState } from 'react';
|
||||
import { SittingIcon } from '@/components/commons/icon/SittingIcon';
|
||||
import { VMCFileUpload } from '@/components/settings/pages/VMCSettings';
|
||||
import { VRMFileUpload } from '@/components/settings/pages/VMCSettings';
|
||||
import { QuizButton } from './SlimeSetQuestion';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
|
||||
@@ -81,7 +81,7 @@ export function QuizMocapPosQuestion() {
|
||||
/>
|
||||
<Typography id="onboarding-quiz-mocap_preferences-vrm_model-desc" />
|
||||
</div>
|
||||
<VMCFileUpload />
|
||||
<VRMFileUpload />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
+2
-2
@@ -29,8 +29,8 @@ function PosePage({
|
||||
return (
|
||||
<div className="flex flex-col py-2">
|
||||
<div className="flex flex-col gap-2">
|
||||
{descriptionKeys.map((descriptionKey) => (
|
||||
<Typography>{l10n.getString(descriptionKey)}</Typography>
|
||||
{descriptionKeys.map((descriptionKey, i) => (
|
||||
<Typography key={i}>{l10n.getString(descriptionKey)}</Typography>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex pt-1 items-center fill-background-50 justify-center px-12">
|
||||
|
||||
@@ -109,32 +109,14 @@ export function TrackersAssignPage() {
|
||||
|
||||
sendRPCPacket(
|
||||
RpcMessage.ChangeSettingsRequest,
|
||||
new ChangeSettingsRequestT(
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
newTapSettings
|
||||
)
|
||||
new ChangeSettingsRequestT(null, null, null, null, null, newTapSettings)
|
||||
);
|
||||
|
||||
return () => {
|
||||
newTapSettings.setupMode = false;
|
||||
sendRPCPacket(
|
||||
RpcMessage.ChangeSettingsRequest,
|
||||
new ChangeSettingsRequestT(
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
null,
|
||||
newTapSettings
|
||||
)
|
||||
new ChangeSettingsRequestT(null, null, null, null, null, newTapSettings)
|
||||
);
|
||||
};
|
||||
}, [tapDetectionSettings]);
|
||||
@@ -220,7 +202,6 @@ export function TrackersAssignPage() {
|
||||
assignreq.bodyPosition = role;
|
||||
assignreq.mountingOrientation = rotation;
|
||||
assignreq.trackerId = trackerId;
|
||||
assignreq.allowDriftCompensation = false;
|
||||
|
||||
sendRPCPacket(RpcMessage.AssignTrackerRequest, assignreq);
|
||||
};
|
||||
|
||||
@@ -2,10 +2,8 @@ import { ReactNode } from 'react';
|
||||
import { ConfigContextC, loadConfig, useConfigProvider } from '@/hooks/config';
|
||||
import { getSentryOrCompute } from '@/utils/sentry';
|
||||
|
||||
const [config, isSteam] = await Promise.all([
|
||||
loadConfig(),
|
||||
window.electronAPI.isSteam(),
|
||||
]);
|
||||
const config = await loadConfig();
|
||||
const isSteam = window.electronAPI ? await window.electronAPI.isSteam() : false;
|
||||
|
||||
if (config?.errorTracking !== undefined) {
|
||||
// load sentry ASAP to catch early errors
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import classNames from 'classnames';
|
||||
import { ReactNode, useEffect, useRef } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { useBreakpoint } from '@/hooks/breakpoint';
|
||||
|
||||
export function SettingsPageLayout({
|
||||
children,
|
||||
@@ -12,7 +11,6 @@ export function SettingsPageLayout({
|
||||
} & React.HTMLAttributes<HTMLDivElement>) {
|
||||
const pageRef = useRef<HTMLDivElement | null>(null);
|
||||
const { state } = useLocation();
|
||||
const { isMobile } = useBreakpoint('mobile');
|
||||
|
||||
useEffect(() => {
|
||||
const typedState: { scrollTo: string } = state;
|
||||
@@ -23,19 +21,10 @@ export function SettingsPageLayout({
|
||||
`#${typedState.scrollTo}`
|
||||
) as HTMLElement | null;
|
||||
if (elem) {
|
||||
// stupid way of doing this, just get the closest overflow-y-auto
|
||||
// usually its just the parentElem
|
||||
const closestScroll = elem.closest(
|
||||
'.overflow-y-auto'
|
||||
) as HTMLElement | null;
|
||||
if (closestScroll) {
|
||||
// The 45 is just enough padding for making the scroll look perfect
|
||||
const topPadding = isMobile ? 80 : 45;
|
||||
closestScroll.scroll({
|
||||
top: elem.offsetTop - topPadding,
|
||||
behavior: 'smooth',
|
||||
});
|
||||
}
|
||||
elem.scrollIntoView({
|
||||
block: 'start',
|
||||
behavior: 'smooth',
|
||||
});
|
||||
}
|
||||
}, [state]);
|
||||
|
||||
@@ -58,7 +47,7 @@ export function SettingsPagePaneLayout({
|
||||
return (
|
||||
<div
|
||||
className={classNames(
|
||||
'bg-background-70 rounded-lg px-4 py-8 flex xs:gap-4 w-full relative',
|
||||
'bg-background-70 rounded-lg px-4 py-8 flex xs:gap-4 w-full relative scroll-mt-12 mobile:scroll-mt-20',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -50,8 +50,8 @@ export function SettingsSidebar() {
|
||||
<div className="flex flex-col gap-2">
|
||||
<SettingsLink
|
||||
to="/settings/trackers"
|
||||
scrollTo="steamvr"
|
||||
id="settings-sidebar-steamvr"
|
||||
scrollTo="output"
|
||||
id="settings-sidebar-output"
|
||||
/>
|
||||
<SettingsLink
|
||||
to="/settings/trackers"
|
||||
@@ -93,6 +93,11 @@ export function SettingsSidebar() {
|
||||
scrollTo="appearance"
|
||||
id="settings-sidebar-appearance"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-3">
|
||||
<Typography variant="section-title" id="settings-sidebar-home" />
|
||||
<div className="flex flex-col gap-2">
|
||||
<SettingsLink
|
||||
to="/settings/interface/home"
|
||||
scrollTo="home"
|
||||
@@ -104,46 +109,41 @@ export function SettingsSidebar() {
|
||||
id="settings-sidebar-checklist"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-3">
|
||||
<Typography variant="section-title">OSC</Typography>
|
||||
<div className="flex flex-col gap-2">
|
||||
<SettingsLink
|
||||
to="/settings/osc/router"
|
||||
scrollTo="router"
|
||||
id="settings-sidebar-osc_router"
|
||||
/>
|
||||
<SettingsLink
|
||||
to="/settings/osc/vrchat"
|
||||
scrollTo="vrchat"
|
||||
id="settings-sidebar-osc_trackers"
|
||||
/>
|
||||
<SettingsLink
|
||||
to="/settings/osc/vmc"
|
||||
scrollTo="vmc"
|
||||
id="settings-sidebar-osc_vmc"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col gap-3">
|
||||
<Typography variant="section-title">OSC</Typography>
|
||||
<div className="flex flex-col gap-2">
|
||||
<SettingsLink
|
||||
to="/settings/osc/vrchat"
|
||||
scrollTo="vrchat"
|
||||
id="settings-sidebar-osc_trackers"
|
||||
/>
|
||||
<SettingsLink
|
||||
to="/settings/osc/vmc"
|
||||
scrollTo="vmc"
|
||||
id="settings-sidebar-osc_vmc"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-3">
|
||||
<Typography variant="section-title" id="settings-sidebar-utils" />
|
||||
<div className="flex flex-col gap-2">
|
||||
<SettingsLink to="/settings/serial" id="settings-sidebar-serial" />
|
||||
</div>
|
||||
<div className="flex flex-col gap-3">
|
||||
<Typography variant="section-title" id="settings-sidebar-utils" />
|
||||
<div className="flex flex-col gap-2">
|
||||
<SettingsLink to="/settings/serial" id="settings-sidebar-serial" />
|
||||
<SettingsLink
|
||||
to="/settings/firmware-tool"
|
||||
id="settings-sidebar-firmware-tool"
|
||||
/>
|
||||
<SettingsLink to="/onboarding/home" id="navbar-onboarding" />
|
||||
{vrcConfigState?.isSupported && (
|
||||
<SettingsLink
|
||||
to="/settings/firmware-tool"
|
||||
id="settings-sidebar-firmware-tool"
|
||||
to="/vrc-warnings"
|
||||
id="settings-sidebar-vrc_warnings"
|
||||
/>
|
||||
<SettingsLink to="/onboarding/home" id="navbar-onboarding" />
|
||||
{vrcConfigState?.isSupported && (
|
||||
<SettingsLink
|
||||
to="/vrc-warnings"
|
||||
id="settings-sidebar-vrc_warnings"
|
||||
/>
|
||||
)}
|
||||
<SettingsLink
|
||||
to="/settings/advanced"
|
||||
id="settings-sidebar-advanced"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<SettingsLink
|
||||
to="/settings/advanced"
|
||||
id="settings-sidebar-advanced"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -10,8 +10,11 @@ import { Button } from '@/components/commons/Button';
|
||||
import { SettingsResetModal } from '@/components/settings/SettingsResetModal';
|
||||
|
||||
import { error } from '@/utils/logging';
|
||||
import { defaultConfig as defaultGUIConfig, useConfig } from '@/hooks/config';
|
||||
import { defaultValues as defaultDevConfig } from '@/components/widgets/DeveloperModeWidget';
|
||||
import {
|
||||
defaultDevSettings,
|
||||
defaultConfig as defaultGUIConfig,
|
||||
useConfig,
|
||||
} from '@/hooks/config';
|
||||
import { RpcMessage, SettingsResetRequestT } from 'solarxr-protocol';
|
||||
import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
import { useElectron } from '@/hooks/electron';
|
||||
@@ -21,7 +24,7 @@ function guiDefaults() {
|
||||
|
||||
const { lang, ...guiDefaults } = defaultGUIConfig;
|
||||
|
||||
guiDefaults.devSettings = defaultDevConfig;
|
||||
guiDefaults.devSettings = defaultDevSettings;
|
||||
|
||||
return guiDefaults;
|
||||
}
|
||||
|
||||
@@ -3,27 +3,19 @@ import { useEffect, useRef, useState } from 'react';
|
||||
import { DefaultValues, useForm } from 'react-hook-form';
|
||||
import {
|
||||
ChangeSettingsRequestT,
|
||||
FilteringSettingsT,
|
||||
FilteringType,
|
||||
LegTweaksSettingsT,
|
||||
ModelRatiosT,
|
||||
ModelSettingsT,
|
||||
ModelTogglesT,
|
||||
RpcMessage,
|
||||
SettingsRequestT,
|
||||
SettingsResponseT,
|
||||
SteamVRTrackersSettingT,
|
||||
TapDetectionSettingsT,
|
||||
HIDSettingsT,
|
||||
VelocitySettingsT,
|
||||
BodyPart,
|
||||
OutputTrackersSettingT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useConfig } from '@/hooks/config';
|
||||
import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
import { useLocaleConfig } from '@/i18n/config';
|
||||
import { CheckBox } from '@/components/commons/Checkbox';
|
||||
import { SteamIcon } from '@/components/commons/icon/SteamIcon';
|
||||
import { WrenchIcon } from '@/components/commons/icon/WrenchIcons';
|
||||
import { WrenchIcon } from '@/components/commons/icon/WrenchIcon';
|
||||
import { NumberSelector } from '@/components/commons/NumberSelector';
|
||||
import { Radio } from '@/components/commons/Radio';
|
||||
import { Typography } from '@/components/commons/Typography';
|
||||
@@ -50,29 +42,16 @@ import { isEqual } from '@react-hookz/deep-equal';
|
||||
import { selectAtom } from 'jotai/utils';
|
||||
import { Dropdown } from '@/components/commons/Dropdown';
|
||||
import { ASSIGNMENT_MODES } from '@/components/onboarding/BodyAssignment';
|
||||
import { OutputIcon } from '@/components/commons/icon/OutputIcon';
|
||||
import { TouchDoubleIcon } from '@/components/commons/icon/TouchDoubleIcon';
|
||||
import { MartialArtsIcon } from '@/components/commons/icon/MartialArtsIcon';
|
||||
|
||||
export type SettingsForm = {
|
||||
trackers: {
|
||||
waist: boolean;
|
||||
chest: boolean;
|
||||
automaticTrackerToggle: boolean;
|
||||
leftFoot: boolean;
|
||||
rightFoot: boolean;
|
||||
leftKnee: boolean;
|
||||
rightKnee: boolean;
|
||||
leftElbow: boolean;
|
||||
rightElbow: boolean;
|
||||
leftHand: boolean;
|
||||
rightHand: boolean;
|
||||
};
|
||||
filtering: {
|
||||
type: number;
|
||||
amount: number;
|
||||
};
|
||||
toggles: {
|
||||
extendedSpine: boolean;
|
||||
extendedPelvis: boolean;
|
||||
extendedKnee: boolean;
|
||||
forceArmsFromHmd: boolean;
|
||||
floorClip: boolean;
|
||||
skatingCorrection: boolean;
|
||||
@@ -84,10 +63,8 @@ export type SettingsForm = {
|
||||
correctConstraints: boolean;
|
||||
};
|
||||
ratios: {
|
||||
imputeWaistFromChestHip: number;
|
||||
imputeWaistFromChestLegs: number;
|
||||
imputeHipFromChestLegs: number;
|
||||
imputeHipFromWaistLegs: number;
|
||||
imputeSpineFromUpperLower: number;
|
||||
imputeSpineCurvature: number;
|
||||
interpHipLegs: number;
|
||||
interpKneeTrackerAnkle: number;
|
||||
interpKneeAnkle: number;
|
||||
@@ -115,29 +92,10 @@ export type SettingsForm = {
|
||||
hidSettings: {
|
||||
trackersOverHID: boolean;
|
||||
};
|
||||
velocitySettings: {
|
||||
sendDerivedVelocity: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
const defaultValues: SettingsForm = {
|
||||
trackers: {
|
||||
waist: false,
|
||||
chest: false,
|
||||
automaticTrackerToggle: true,
|
||||
leftFoot: false,
|
||||
rightFoot: false,
|
||||
leftElbow: false,
|
||||
rightElbow: false,
|
||||
leftHand: false,
|
||||
rightHand: false,
|
||||
leftKnee: false,
|
||||
rightKnee: false,
|
||||
},
|
||||
toggles: {
|
||||
extendedSpine: true,
|
||||
extendedPelvis: true,
|
||||
extendedKnee: true,
|
||||
forceArmsFromHmd: false,
|
||||
floorClip: false,
|
||||
skatingCorrection: false,
|
||||
@@ -149,10 +107,8 @@ const defaultValues: SettingsForm = {
|
||||
correctConstraints: true,
|
||||
},
|
||||
ratios: {
|
||||
imputeWaistFromChestHip: 0.3,
|
||||
imputeWaistFromChestLegs: 0.2,
|
||||
imputeHipFromChestLegs: 0.45,
|
||||
imputeHipFromWaistLegs: 0.4,
|
||||
imputeSpineFromUpperLower: 0.5,
|
||||
imputeSpineCurvature: 0.5,
|
||||
interpHipLegs: 0.25,
|
||||
interpKneeTrackerAnkle: 0.85,
|
||||
interpKneeAnkle: 0.2,
|
||||
@@ -177,7 +133,6 @@ const defaultValues: SettingsForm = {
|
||||
resetsSettings: defaultResetSettings,
|
||||
stayAligned: defaultStayAlignedSettings,
|
||||
hidSettings: { trackersOverHID: false },
|
||||
velocitySettings: { sendDerivedVelocity: false },
|
||||
};
|
||||
|
||||
const settingsAtom = atom(new SettingsResponseT());
|
||||
@@ -201,12 +156,6 @@ export function GeneralSettings() {
|
||||
value: String(value),
|
||||
label: l10n.getString(`body_part-${BodyPart[value]}`),
|
||||
}));
|
||||
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',
|
||||
@@ -227,53 +176,10 @@ export function GeneralSettings() {
|
||||
reValidateMode: 'onChange',
|
||||
});
|
||||
|
||||
const {
|
||||
trackers: { automaticTrackerToggle },
|
||||
} = watch();
|
||||
|
||||
|
||||
const onSubmit = (values: SettingsForm) => {
|
||||
const settingsReq = new ChangeSettingsRequestT();
|
||||
|
||||
if (values.trackers) {
|
||||
const trackers = new SteamVRTrackersSettingT();
|
||||
trackers.waist = values.trackers.waist;
|
||||
trackers.chest = values.trackers.chest;
|
||||
trackers.leftFoot = values.trackers.leftFoot;
|
||||
trackers.rightFoot = values.trackers.rightFoot;
|
||||
|
||||
trackers.leftKnee = values.trackers.leftKnee;
|
||||
trackers.rightKnee = values.trackers.rightKnee;
|
||||
|
||||
trackers.leftElbow = values.trackers.leftElbow;
|
||||
trackers.rightElbow = values.trackers.rightElbow;
|
||||
|
||||
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;
|
||||
}
|
||||
const req = new ChangeSettingsRequestT();
|
||||
|
||||
const modelSettings = new ModelSettingsT();
|
||||
|
||||
@@ -281,9 +187,6 @@ export function GeneralSettings() {
|
||||
const toggles = new ModelTogglesT();
|
||||
toggles.floorClip = values.toggles.floorClip;
|
||||
toggles.skatingCorrection = values.toggles.skatingCorrection;
|
||||
toggles.extendedKnee = values.toggles.extendedKnee;
|
||||
toggles.extendedPelvis = values.toggles.extendedPelvis;
|
||||
toggles.extendedSpine = values.toggles.extendedSpine;
|
||||
toggles.forceArmsFromHmd = values.toggles.forceArmsFromHmd;
|
||||
toggles.toeSnap = values.toggles.toeSnap;
|
||||
toggles.footPlant = values.toggles.footPlant;
|
||||
@@ -296,14 +199,9 @@ export function GeneralSettings() {
|
||||
|
||||
if (values.ratios) {
|
||||
const ratios = new ModelRatiosT();
|
||||
ratios.imputeWaistFromChestHip =
|
||||
values.ratios.imputeWaistFromChestHip || -1;
|
||||
ratios.imputeWaistFromChestLegs =
|
||||
values.ratios.imputeWaistFromChestLegs || -1;
|
||||
ratios.imputeHipFromChestLegs =
|
||||
values.ratios.imputeHipFromChestLegs || -1;
|
||||
ratios.imputeHipFromWaistLegs =
|
||||
values.ratios.imputeHipFromWaistLegs || -1;
|
||||
ratios.imputeSpineFromUpperLower =
|
||||
values.ratios.imputeSpineFromUpperLower || -1;
|
||||
ratios.imputeSpineCurvature = values.ratios.imputeSpineCurvature || -1;
|
||||
ratios.interpHipLegs = values.ratios.interpHipLegs || -1;
|
||||
ratios.interpKneeTrackerAnkle =
|
||||
values.ratios.interpKneeTrackerAnkle || -1;
|
||||
@@ -317,7 +215,7 @@ export function GeneralSettings() {
|
||||
modelSettings.legTweaks = legTweaks;
|
||||
}
|
||||
|
||||
settingsReq.modelSettings = modelSettings;
|
||||
req.modelSettings = modelSettings;
|
||||
|
||||
const tapDetection = new TapDetectionSettingsT();
|
||||
tapDetection.fullResetDelay = values.tapDetection.fullResetDelay;
|
||||
@@ -340,29 +238,29 @@ export function GeneralSettings() {
|
||||
tapDetection.numberTrackersOverThreshold =
|
||||
values.tapDetection.numberTrackersOverThreshold;
|
||||
tapDetection.setupMode = false;
|
||||
settingsReq.tapDetectionSettings = tapDetection;
|
||||
req.tapDetectionSettings = tapDetection;
|
||||
|
||||
const filtering = new FilteringSettingsT();
|
||||
filtering.type = values.filtering.type;
|
||||
filtering.amount = values.filtering.amount;
|
||||
settingsReq.filtering = filtering;
|
||||
req.filtering = filtering;
|
||||
|
||||
settingsReq.stayAligned = serializeStayAlignedSettings(values.stayAligned);
|
||||
req.stayAligned = serializeStayAlignedSettings(values.stayAligned);
|
||||
|
||||
const hidSettings = new HIDSettingsT();
|
||||
hidSettings.trackersOverHid = values.hidSettings.trackersOverHID;
|
||||
settingsReq.hidSettings = hidSettings;
|
||||
req.hidSettings = hidSettings;
|
||||
|
||||
const velocitySettings = new VelocitySettingsT();
|
||||
velocitySettings.sendDerivedVelocity =
|
||||
values.velocitySettings.sendDerivedVelocity;
|
||||
settingsReq.velocitySettings = velocitySettings;
|
||||
req.velocitySettings = velocitySettings;
|
||||
|
||||
if (values.resetsSettings) {
|
||||
settingsReq.resetsSettings = loadResetSettings(values.resetsSettings);
|
||||
req.resetsSettings = loadResetSettings(values.resetsSettings);
|
||||
}
|
||||
|
||||
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settingsReq);
|
||||
sendRPCPacket(RpcMessage.ChangeSettingsRequest, req);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@@ -383,12 +281,12 @@ export function GeneralSettings() {
|
||||
formData.filtering = settings.filtering;
|
||||
}
|
||||
|
||||
if (settings.steamVrTrackers) {
|
||||
formData.trackers = settings.steamVrTrackers;
|
||||
if (settings.outputTrackers) {
|
||||
formData.trackers = settings.outputTrackers;
|
||||
if (
|
||||
!blockHandsWarning.current &&
|
||||
(settings.steamVrTrackers.leftHand ||
|
||||
settings.steamVrTrackers.rightHand)
|
||||
(settings.outputTrackers.trackers.includes(BodyPart.LEFT_HAND) ||
|
||||
settings.outputTrackers.trackers.includes(BodyPart.RIGHT_HAND))
|
||||
) {
|
||||
blockHandsWarning.current = true;
|
||||
}
|
||||
@@ -522,32 +420,22 @@ export function GeneralSettings() {
|
||||
}}
|
||||
/>
|
||||
<form className="flex flex-col gap-2 w-full">
|
||||
<SettingsPagePaneLayout icon={<SteamIcon />} id="steamvr">
|
||||
<SettingsPagePaneLayout icon={<OutputIcon />} id="output">
|
||||
<>
|
||||
<Typography variant="main-title">
|
||||
{l10n.getString('settings-general-steamvr')}
|
||||
{l10n.getString('settings-general-output')}
|
||||
</Typography>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-general-steamvr-subtitle')}
|
||||
</Typography>
|
||||
<div className="flex flex-col py-2">
|
||||
{l10n
|
||||
.getString('settings-general-steamvr-description')
|
||||
.split('\n')
|
||||
.map((line, i) => (
|
||||
<Typography key={i}>{line}</Typography>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col pt-4" />
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString(
|
||||
'settings-general-steamvr-trackers-tracker_toggling'
|
||||
)}
|
||||
</Typography>
|
||||
<div className="flex flex-col pt-2 pb-4">
|
||||
<div className="flex flex-col py-2">
|
||||
{l10n
|
||||
.getString(
|
||||
'settings-general-steamvr-trackers-tracker_toggling-description'
|
||||
'settings-general-output-trackers-tracker_toggling-description'
|
||||
)
|
||||
.split('\n')
|
||||
.map((line, i) => (
|
||||
@@ -564,6 +452,18 @@ export function GeneralSettings() {
|
||||
)}
|
||||
/>
|
||||
<div className="flex flex-col pt-4" />
|
||||
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-general-output_trackers')}
|
||||
</Typography>
|
||||
<div className="flex flex-col py-2">
|
||||
{l10n
|
||||
.getString('settings-general-output_trackers-description')
|
||||
.split('\n')
|
||||
.map((line, i) => (
|
||||
<Typography key={i}>{line}</Typography>
|
||||
))}
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
@@ -664,6 +564,33 @@ export function GeneralSettings() {
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col pt-4" />
|
||||
|
||||
<div className="flex flex-col pt-2 pb-1">
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString(
|
||||
'settings-general-fk_settings-velocity_settings'
|
||||
)}
|
||||
</Typography>
|
||||
<div className="pt-2">
|
||||
<Typography>
|
||||
{l10n.getString(
|
||||
'settings-general-fk_settings-velocity_settings-description'
|
||||
)}
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid sm:grid-cols-1 pb-3">
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="velocitySettings.sendDerivedVelocity"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-velocity_settings-send_derived_velocity'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
</SettingsPagePaneLayout>
|
||||
<StayAlignedSettings values={getValues()} control={control} />
|
||||
@@ -801,7 +728,7 @@ export function GeneralSettings() {
|
||||
/>
|
||||
</>
|
||||
</SettingsPagePaneLayout>
|
||||
<SettingsPagePaneLayout icon={<WrenchIcon />} id="fksettings">
|
||||
<SettingsPagePaneLayout icon={<MartialArtsIcon />} id="fksettings">
|
||||
<>
|
||||
<Typography variant="main-title">
|
||||
{l10n.getString('settings-general-fk_settings')}
|
||||
@@ -974,7 +901,7 @@ export function GeneralSettings() {
|
||||
<div className="grid md:grid-cols-2 flex-col gap-3 pt-2 pb-3">
|
||||
<Radio
|
||||
control={control}
|
||||
name="resetsSettings.armsMountingResetMode"
|
||||
name="resetsSettings.armsResetMode"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-arm_fk-back'
|
||||
)}
|
||||
@@ -985,7 +912,7 @@ export function GeneralSettings() {
|
||||
/>
|
||||
<Radio
|
||||
control={control}
|
||||
name="resetsSettings.armsMountingResetMode"
|
||||
name="resetsSettings.armsResetMode"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-arm_fk-forward'
|
||||
)}
|
||||
@@ -996,7 +923,7 @@ export function GeneralSettings() {
|
||||
/>
|
||||
<Radio
|
||||
control={control}
|
||||
name="resetsSettings.armsMountingResetMode"
|
||||
name="resetsSettings.armsResetMode"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-arm_fk-tpose_up'
|
||||
)}
|
||||
@@ -1007,7 +934,7 @@ export function GeneralSettings() {
|
||||
/>
|
||||
<Radio
|
||||
control={control}
|
||||
name="resetsSettings.armsMountingResetMode"
|
||||
name="resetsSettings.armsResetMode"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-arm_fk-tpose_down'
|
||||
)}
|
||||
@@ -1067,75 +994,8 @@ export function GeneralSettings() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col pt-2 pb-1">
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString(
|
||||
'settings-general-fk_settings-velocity_settings'
|
||||
)}
|
||||
</Typography>
|
||||
<div className="pt-2">
|
||||
<Typography>
|
||||
{l10n.getString(
|
||||
'settings-general-fk_settings-velocity_settings-description'
|
||||
)}
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid sm:grid-cols-1 pb-3">
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="velocitySettings.sendDerivedVelocity"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-velocity_settings-send_derived_velocity'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{config?.debug && (
|
||||
<>
|
||||
<div className="flex flex-col pt-2 pb-3">
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString(
|
||||
'settings-general-fk_settings-skeleton_settings-toggles'
|
||||
)}
|
||||
</Typography>
|
||||
<Typography>
|
||||
{l10n.getString(
|
||||
'settings-general-fk_settings-skeleton_settings-description'
|
||||
)}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid sm:grid-cols-2 gap-3 pb-3">
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="toggles.extendedSpine"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-skeleton_settings-extended_spine_model'
|
||||
)}
|
||||
/>
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="toggles.extendedPelvis"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-skeleton_settings-extended_pelvis_model'
|
||||
)}
|
||||
/>
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="toggles.extendedKnee"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-skeleton_settings-extended_knees_model'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
<div className="flex flex-col pt-2 pb-3 gap-2">
|
||||
<Typography variant="section-title">
|
||||
@@ -1152,9 +1012,9 @@ export function GeneralSettings() {
|
||||
<div className="grid sm:grid-cols-2 gap-3 pb-3">
|
||||
<NumberSelector
|
||||
control={control}
|
||||
name="ratios.imputeWaistFromChestHip"
|
||||
name="ratios.imputeSpineFromUpperLower"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-skeleton_settings-impute_waist_from_chest_hip'
|
||||
'settings-general-fk_settings-skeleton_settings-impute_spine_from_top_down'
|
||||
)}
|
||||
valueLabelFormat={(value) =>
|
||||
percentageFormat.format(value)
|
||||
@@ -1165,35 +1025,9 @@ export function GeneralSettings() {
|
||||
/>
|
||||
<NumberSelector
|
||||
control={control}
|
||||
name="ratios.imputeWaistFromChestLegs"
|
||||
name="ratios.imputeSpineCurvature"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-skeleton_settings-impute_waist_from_chest_legs'
|
||||
)}
|
||||
valueLabelFormat={(value) =>
|
||||
percentageFormat.format(value)
|
||||
}
|
||||
min={0.0}
|
||||
max={1.0}
|
||||
step={0.05}
|
||||
/>
|
||||
<NumberSelector
|
||||
control={control}
|
||||
name="ratios.imputeHipFromChestLegs"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-skeleton_settings-impute_hip_from_chest_legs'
|
||||
)}
|
||||
valueLabelFormat={(value) =>
|
||||
percentageFormat.format(value)
|
||||
}
|
||||
min={0.0}
|
||||
max={1.0}
|
||||
step={0.05}
|
||||
/>
|
||||
<NumberSelector
|
||||
control={control}
|
||||
name="ratios.imputeHipFromWaistLegs"
|
||||
label={l10n.getString(
|
||||
'settings-general-fk_settings-skeleton_settings-impute_hip_from_waist_legs'
|
||||
'settings-general-fk_settings-skeleton_settings-impute_spine_curvature'
|
||||
)}
|
||||
valueLabelFormat={(value) =>
|
||||
percentageFormat.format(value)
|
||||
@@ -1271,7 +1105,7 @@ export function GeneralSettings() {
|
||||
</>
|
||||
</SettingsPagePaneLayout>
|
||||
|
||||
<SettingsPagePaneLayout icon={<WrenchIcon />} id="gestureControl">
|
||||
<SettingsPagePaneLayout icon={<TouchDoubleIcon />} id="gestureControl">
|
||||
<>
|
||||
<Typography variant="main-title">
|
||||
{l10n.getString('settings-general-gesture_control')}
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { Localized, useLocalization } from '@fluent/react';
|
||||
import { useEffect } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { FieldPath, useForm } from 'react-hook-form';
|
||||
import { CheckBox } from '@/components/commons/Checkbox';
|
||||
import { Typography } from '@/components/commons/Typography';
|
||||
import {
|
||||
SettingsPageLayout,
|
||||
SettingsPagePaneLayout,
|
||||
} from '@/components/settings/SettingsPageLayout';
|
||||
import { defaultConfig, useConfig } from '@/hooks/config';
|
||||
import { defaultConfig, DeveloperModeConfig, useConfig } from '@/hooks/config';
|
||||
import { ThemeSelector } from '@/components/commons/ThemeSelector';
|
||||
import { SquaresIcon } from '@/components/commons/icon/SquaresIcon';
|
||||
import { NumberSelector } from '@/components/commons/NumberSelector';
|
||||
@@ -18,7 +18,6 @@ import { Range } from '@/components/commons/Range';
|
||||
import { Dropdown } from '@/components/commons/Dropdown';
|
||||
import { ArrowRightLeftIcon } from '@/components/commons/icon/ArrowIcons';
|
||||
import { SystemFileInput } from '@/components/commons/SystemFileInput';
|
||||
import { DeveloperModeWidget } from '@/components/widgets/DeveloperModeWidget';
|
||||
import { useElectron } from '@/hooks/electron';
|
||||
|
||||
interface InterfaceSettingsForm {
|
||||
@@ -28,7 +27,6 @@ interface InterfaceSettingsForm {
|
||||
fonts: string;
|
||||
};
|
||||
behavior: {
|
||||
devmode: boolean;
|
||||
useTray: boolean;
|
||||
discordPresence: boolean;
|
||||
errorTracking: boolean;
|
||||
@@ -40,6 +38,9 @@ interface InterfaceSettingsForm {
|
||||
feedbackSoundVolume: number;
|
||||
connectedTrackersWarning: boolean;
|
||||
};
|
||||
developer: DeveloperModeConfig & {
|
||||
enabled: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
export function InterfaceSettings() {
|
||||
@@ -65,13 +66,35 @@ export function InterfaceSettings() {
|
||||
defaultConfig.connectedTrackersWarning,
|
||||
},
|
||||
behavior: {
|
||||
devmode: config?.debug ?? defaultConfig.debug,
|
||||
useTray: config?.useTray ?? defaultConfig.useTray ?? false,
|
||||
discordPresence:
|
||||
config?.discordPresence ?? defaultConfig.discordPresence,
|
||||
errorTracking: config?.errorTracking ?? false,
|
||||
bvhDirectory: config?.bvhDirectory ?? defaultConfig.bvhDirectory,
|
||||
},
|
||||
developer: {
|
||||
enabled: config?.debug ?? defaultConfig.debug,
|
||||
highContrast:
|
||||
config?.devSettings?.highContrast ??
|
||||
defaultConfig.devSettings.highContrast,
|
||||
preciseRotation:
|
||||
config?.devSettings?.preciseRotation ??
|
||||
defaultConfig.devSettings.preciseRotation,
|
||||
fastDataFeed:
|
||||
config?.devSettings?.fastDataFeed ??
|
||||
defaultConfig.devSettings.fastDataFeed,
|
||||
filterSlimesAndHMD:
|
||||
config?.devSettings?.filterSlimesAndHMD ??
|
||||
defaultConfig.devSettings.filterSlimesAndHMD,
|
||||
sortByName:
|
||||
config?.devSettings?.sortByName ??
|
||||
defaultConfig.devSettings.sortByName,
|
||||
rawSlimeRotation:
|
||||
config?.devSettings?.rawSlimeRotation ??
|
||||
defaultConfig.devSettings.rawSlimeRotation,
|
||||
moreInfo:
|
||||
config?.devSettings?.moreInfo ?? defaultConfig.devSettings.moreInfo,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -112,9 +135,11 @@ export function InterfaceSettings() {
|
||||
|
||||
useTray: values.behavior.useTray,
|
||||
discordPresence: values.behavior.discordPresence,
|
||||
debug: values.behavior.devmode,
|
||||
errorTracking: values.behavior.errorTracking,
|
||||
bvhDirectory: values.behavior.bvhDirectory,
|
||||
|
||||
debug: values.developer.enabled,
|
||||
devSettings: values.developer,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -128,6 +153,16 @@ export function InterfaceSettings() {
|
||||
return () => subscription.unsubscribe();
|
||||
}, []);
|
||||
|
||||
const devToggles = {
|
||||
highContrast: 'high_contrast',
|
||||
preciseRotation: 'precise_rotation',
|
||||
fastDataFeed: 'fast_data_feed',
|
||||
filterSlimesAndHMD: 'filter_slimes_and_hmd',
|
||||
sortByName: 'sort_by_name',
|
||||
rawSlimeRotation: 'raw_slime_rotation',
|
||||
moreInfo: 'more_info',
|
||||
};
|
||||
|
||||
return (
|
||||
<SettingsPageLayout>
|
||||
<form
|
||||
@@ -299,18 +334,31 @@ export function InterfaceSettings() {
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-2 pb-4 w-full">
|
||||
<div className="">
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
control={control}
|
||||
outlined
|
||||
name="behavior.devmode"
|
||||
label={l10n.getString(
|
||||
'settings-general-interface-dev_mode-label'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
{config?.debug && <DeveloperModeWidget />}
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
control={control}
|
||||
outlined
|
||||
name="developer.enabled"
|
||||
label={l10n.getString(
|
||||
'settings-general-interface-dev_mode-label'
|
||||
)}
|
||||
/>
|
||||
{!!config?.debug && (
|
||||
<div className="grid grid-cols-2 w-full rounded-md gap-2">
|
||||
{Object.entries(devToggles).map(([name, label], i) => (
|
||||
<CheckBox
|
||||
key={i}
|
||||
control={control}
|
||||
variant="toggle"
|
||||
outlined
|
||||
name={
|
||||
`developer.${name}` as FieldPath<InterfaceSettingsForm>
|
||||
}
|
||||
label={l10n.getString(`widget-developer_mode-${label}`)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Typography variant="section-title">
|
||||
|
||||
@@ -6,11 +6,9 @@ import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import {
|
||||
ChangeMagToggleRequestT,
|
||||
DeviceIdT,
|
||||
MagToggleRequestT,
|
||||
MagToggleResponseT,
|
||||
RpcMessage,
|
||||
TrackerIdT,
|
||||
} from 'solarxr-protocol';
|
||||
import { Link } from 'react-router-dom';
|
||||
|
||||
@@ -19,13 +17,11 @@ interface MagnetometerToggleForm {
|
||||
}
|
||||
|
||||
export function MagnetometerToggleSetting({
|
||||
trackerNum,
|
||||
deviceId,
|
||||
trackerId,
|
||||
settingType,
|
||||
id,
|
||||
}: {
|
||||
trackerNum?: number;
|
||||
deviceId?: number;
|
||||
trackerId?: number;
|
||||
settingType: 'general' | 'tracker';
|
||||
id?: string;
|
||||
}) {
|
||||
@@ -45,18 +41,14 @@ export function MagnetometerToggleSetting({
|
||||
if (originalValue.current === values.magToggle) return;
|
||||
setWaitingMag(true);
|
||||
const req = new ChangeMagToggleRequestT();
|
||||
if (trackerNum !== undefined) {
|
||||
const id = new TrackerIdT(
|
||||
deviceId ? new DeviceIdT(deviceId) : undefined,
|
||||
trackerNum
|
||||
);
|
||||
req.trackerId = id;
|
||||
if (trackerId !== undefined) {
|
||||
req.trackerId = trackerId;
|
||||
}
|
||||
|
||||
req.enable = values.magToggle;
|
||||
sendRPCPacket(RpcMessage.ChangeMagToggleRequest, req);
|
||||
},
|
||||
[trackerNum, deviceId]
|
||||
[trackerId]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -66,25 +58,18 @@ export function MagnetometerToggleSetting({
|
||||
|
||||
useEffect(() => {
|
||||
const req = new MagToggleRequestT();
|
||||
if (trackerNum !== undefined) {
|
||||
const id = new TrackerIdT(
|
||||
deviceId ? new DeviceIdT(deviceId) : undefined,
|
||||
trackerNum
|
||||
);
|
||||
req.trackerId = id;
|
||||
if (trackerId !== undefined) {
|
||||
req.trackerId = trackerId;
|
||||
sendRPCPacket(RpcMessage.MagToggleRequest, new MagToggleRequestT());
|
||||
}
|
||||
sendRPCPacket(RpcMessage.MagToggleRequest, req);
|
||||
}, [trackerNum, deviceId]);
|
||||
}, [trackerId]);
|
||||
|
||||
useRPCPacket(RpcMessage.MagToggleResponse, (mag: MagToggleResponseT) => {
|
||||
if (trackerNum !== undefined && mag.trackerId?.trackerNum === undefined) {
|
||||
if (trackerId !== undefined && mag.trackerId === undefined) {
|
||||
setGlobalToggle(mag.enable);
|
||||
}
|
||||
if (
|
||||
mag.trackerId?.trackerNum !== trackerNum ||
|
||||
mag.trackerId?.deviceId?.id !== deviceId
|
||||
) {
|
||||
if (mag.trackerId !== trackerId) {
|
||||
return;
|
||||
}
|
||||
originalValue.current = mag.enable;
|
||||
@@ -94,7 +79,10 @@ export function MagnetometerToggleSetting({
|
||||
|
||||
return settingType === 'general' ? (
|
||||
<>
|
||||
<div className="flex flex-col pt-5 pb-3" id={id}>
|
||||
<div
|
||||
className="flex flex-col pt-5 pb-3 scroll-mt-12 mobile:scroll-mt-20"
|
||||
id={id}
|
||||
>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString(
|
||||
'settings-general-tracker_mechanics-use_mag_on_all_trackers'
|
||||
|
||||
@@ -1,210 +0,0 @@
|
||||
import { Localized, useLocalization } from '@fluent/react';
|
||||
import { useEffect } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import {
|
||||
ChangeSettingsRequestT,
|
||||
OSCRouterSettingsT,
|
||||
OSCSettingsT,
|
||||
RpcMessage,
|
||||
SettingsRequestT,
|
||||
SettingsResponseT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
import { CheckBox } from '@/components/commons/Checkbox';
|
||||
import { RouterIcon } from '@/components/commons/icon/RouterIcon';
|
||||
import { Input } from '@/components/commons/Input';
|
||||
import { Typography } from '@/components/commons/Typography';
|
||||
import {
|
||||
SettingsPageLayout,
|
||||
SettingsPagePaneLayout,
|
||||
} from '@/components/settings/SettingsPageLayout';
|
||||
import { yupResolver } from '@hookform/resolvers/yup';
|
||||
import { object } from 'yup';
|
||||
import {
|
||||
OSCSettings,
|
||||
useOscSettingsValidator,
|
||||
} from '@/hooks/osc-setting-validator';
|
||||
|
||||
interface OSCRouterSettingsForm {
|
||||
router: {
|
||||
oscSettings: OSCSettings;
|
||||
};
|
||||
}
|
||||
|
||||
const defaultValues = {
|
||||
router: {
|
||||
oscSettings: {
|
||||
enabled: false,
|
||||
portIn: 9002,
|
||||
portOut: 9000,
|
||||
address: '127.0.0.1',
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
export function OSCRouterSettings() {
|
||||
const { l10n } = useLocalization();
|
||||
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
|
||||
const { oscValidator } = useOscSettingsValidator();
|
||||
|
||||
const { reset, control, watch, handleSubmit } =
|
||||
useForm<OSCRouterSettingsForm>({
|
||||
defaultValues: defaultValues,
|
||||
reValidateMode: 'onChange',
|
||||
mode: 'onChange',
|
||||
resolver: yupResolver(
|
||||
object({
|
||||
router: object({
|
||||
oscSettings: oscValidator,
|
||||
}),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
const onSubmit = (values: OSCRouterSettingsForm) => {
|
||||
const settings = new ChangeSettingsRequestT();
|
||||
|
||||
if (values.router) {
|
||||
const router = new OSCRouterSettingsT();
|
||||
|
||||
router.oscSettings = Object.assign(
|
||||
new OSCSettingsT(),
|
||||
values.router.oscSettings
|
||||
);
|
||||
|
||||
settings.oscRouter = router;
|
||||
}
|
||||
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settings);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const subscription = watch(() => handleSubmit(onSubmit)());
|
||||
return () => subscription.unsubscribe();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT());
|
||||
}, []);
|
||||
|
||||
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
|
||||
const formData: OSCRouterSettingsForm = defaultValues;
|
||||
if (settings.oscRouter) {
|
||||
if (settings.oscRouter.oscSettings) {
|
||||
formData.router.oscSettings.enabled =
|
||||
settings.oscRouter.oscSettings.enabled;
|
||||
if (settings.oscRouter.oscSettings.portIn)
|
||||
formData.router.oscSettings.portIn =
|
||||
settings.oscRouter.oscSettings.portIn;
|
||||
if (settings.oscRouter.oscSettings.portOut)
|
||||
formData.router.oscSettings.portOut =
|
||||
settings.oscRouter.oscSettings.portOut;
|
||||
if (settings.oscRouter.oscSettings.address)
|
||||
formData.router.oscSettings.address =
|
||||
settings.oscRouter.oscSettings.address.toString();
|
||||
}
|
||||
|
||||
reset(formData);
|
||||
}
|
||||
});
|
||||
|
||||
return (
|
||||
<SettingsPageLayout>
|
||||
<form className="flex flex-col gap-2 w-full">
|
||||
<SettingsPagePaneLayout icon={<RouterIcon />} id="router">
|
||||
<>
|
||||
<Typography variant="main-title">
|
||||
{l10n.getString('settings-osc-router')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pt-2 pb-4">
|
||||
<>
|
||||
{l10n
|
||||
.getString('settings-osc-router-description')
|
||||
.split('\n')
|
||||
.map((line, i) => (
|
||||
<Typography key={i}>{line}</Typography>
|
||||
))}
|
||||
</>
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-router-enable')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n.getString('settings-osc-router-enable-description')}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3 pb-5">
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="router.oscSettings.enabled"
|
||||
label={l10n.getString('settings-osc-router-enable-label')}
|
||||
/>
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-router-network')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<>
|
||||
{l10n
|
||||
.getString('settings-osc-router-network-description')
|
||||
.split('\n')
|
||||
.map((line, i) => (
|
||||
<Typography key={i}>{line}</Typography>
|
||||
))}
|
||||
</>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3 pb-5">
|
||||
<Localized
|
||||
id="settings-osc-router-network-port_in"
|
||||
attrs={{ placeholder: true, label: true }}
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
control={control}
|
||||
name="router.oscSettings.portIn"
|
||||
placeholder="9002"
|
||||
label=""
|
||||
/>
|
||||
</Localized>
|
||||
<Localized
|
||||
id="settings-osc-router-network-port_out"
|
||||
attrs={{ placeholder: true, label: true }}
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
control={control}
|
||||
name="router.oscSettings.portOut"
|
||||
placeholder="9000"
|
||||
label=""
|
||||
/>
|
||||
</Localized>
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-router-network-address')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n.getString(
|
||||
'settings-osc-router-network-address-description'
|
||||
)}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid gap-3 pb-5">
|
||||
<Input
|
||||
type="text"
|
||||
control={control}
|
||||
name="router.oscSettings.address"
|
||||
placeholder={l10n.getString(
|
||||
'settings-osc-router-network-address-placeholder'
|
||||
)}
|
||||
label=""
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
</SettingsPagePaneLayout>
|
||||
</form>
|
||||
</SettingsPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,311 @@
|
||||
import { Localized, useLocalization } from '@fluent/react';
|
||||
import {useEffect, useRef, useState} from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import {
|
||||
BodyPart,
|
||||
ChangeOutputTrackersSettingsRequestT, OutputTrackersSettingsResponseT,
|
||||
RpcMessage, SettingsResponseT, TapDetectionSettingsT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
import { CheckBox } from '@/components/commons/Checkbox';
|
||||
import { FileInput } from '@/components/commons/FileInput';
|
||||
import { OutputTrackersIcon } from '@/components/commons/icon/OutputTrackersIcon';
|
||||
import { Input } from '@/components/commons/Input';
|
||||
import { Typography } from '@/components/commons/Typography';
|
||||
import { magic } from '@/utils/formatting';
|
||||
import {
|
||||
SettingsPageLayout,
|
||||
SettingsPagePaneLayout,
|
||||
} from '@/components/settings/SettingsPageLayout';
|
||||
import { error } from '@/utils/logging';
|
||||
import {
|
||||
OSCPortsAddress,
|
||||
useOscPortsAddressValidator,
|
||||
} from '@/hooks/osc-setting-validator';
|
||||
import { yupResolver } from '@hookform/resolvers/yup';
|
||||
import { boolean, object } from 'yup';
|
||||
import {atom, useAtomValue, useSetAtom} from "jotai";
|
||||
import {selectAtom} from "jotai/utils";
|
||||
import {isEqual} from "@react-hookz/deep-equal";
|
||||
|
||||
interface OutputTrackersSettingsForm {
|
||||
automaticTrackerToggle: boolean;
|
||||
waist: boolean;
|
||||
chest: boolean;
|
||||
leftFoot: boolean;
|
||||
rightFoot: boolean;
|
||||
leftKnee: boolean;
|
||||
rightKnee: boolean;
|
||||
leftElbow: boolean;
|
||||
rightElbow: boolean;
|
||||
leftHand: boolean;
|
||||
rightHand: boolean;
|
||||
sendDerivedVelocity: boolean;
|
||||
}
|
||||
|
||||
const defaultOutputTrackersSettings: OutputTrackersSettingsForm = {
|
||||
automaticTrackerToggle: true,
|
||||
waist: false,
|
||||
chest: false,
|
||||
leftFoot: false,
|
||||
rightFoot: false,
|
||||
leftElbow: false,
|
||||
rightElbow: false,
|
||||
leftHand: false,
|
||||
rightHand: false,
|
||||
leftKnee: false,
|
||||
rightKnee: false,
|
||||
sendDerivedVelocity: false,
|
||||
};
|
||||
|
||||
const settingsAtom = atom(new OutputTrackersSettingsResponseT());
|
||||
const settingsValueAtom = selectAtom(
|
||||
settingsAtom,
|
||||
(settings) => settings,
|
||||
isEqual
|
||||
);
|
||||
|
||||
export function OutputTrackersSettings() {
|
||||
const setSettings = useSetAtom(settingsAtom);
|
||||
const settings = useAtomValue(settingsValueAtom);
|
||||
const { l10n } = useLocalization();
|
||||
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
|
||||
|
||||
const { reset, control, watch, handleSubmit } = useForm<OutputTrackersSettingsForm>({
|
||||
defaultValues: defaultOutputTrackersSettings,
|
||||
reValidateMode: 'onChange',
|
||||
mode: 'onChange',
|
||||
resolver: yupResolver(
|
||||
object({
|
||||
automaticTrackerToggle: boolean().required(),
|
||||
waist: boolean().required(),
|
||||
chest: boolean().required(),
|
||||
leftFoot: boolean().required(),
|
||||
rightFoot: boolean().required(),
|
||||
leftKnee: boolean().required(),
|
||||
rightKnee: boolean().required(),
|
||||
leftElbow: boolean().required(),
|
||||
rightElbow: boolean().required(),
|
||||
leftHand: boolean().required(),
|
||||
rightHand: boolean().required(),
|
||||
sendDerivedVelocity: boolean().required(),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
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 {
|
||||
trackers: { automaticTrackerToggle },
|
||||
} = watch();
|
||||
|
||||
const onSubmit = async (values: OutputTrackersSettingsForm) => {
|
||||
const req = new ChangeOutputTrackersSettingsRequestT();
|
||||
|
||||
// The tracker is at the tail of the bone.
|
||||
// Example, the waist tracker is at the tail of the hip bone so we use the hip BodyPart
|
||||
const enabledBodyParts: [boolean, BodyPart][] = [
|
||||
[values.waist, BodyPart.HIP],
|
||||
[values.chest, BodyPart.CHEST],
|
||||
[values.leftFoot, BodyPart.LEFT_FOOT],
|
||||
[values.rightFoot, BodyPart.RIGHT_FOOT],
|
||||
[values.leftKnee, BodyPart.LEFT_UPPER_LEG],
|
||||
[values.rightKnee, BodyPart.RIGHT_UPPER_LEG],
|
||||
[values.leftElbow, BodyPart.LEFT_UPPER_ARM],
|
||||
[values.rightElbow, BodyPart.RIGHT_UPPER_ARM],
|
||||
[values.leftHand, BodyPart.LEFT_HAND],
|
||||
[values.rightHand, BodyPart.RIGHT_HAND],
|
||||
];
|
||||
req.trackers = enabledBodyParts
|
||||
.filter(([enabled]) => enabled)
|
||||
.map(([, part]) => part);
|
||||
|
||||
// Hand warning
|
||||
if (
|
||||
!blockHandsWarning.current &&
|
||||
!showHandsWarning &&
|
||||
!settings?.trackers.includes(BodyPart.LEFT_HAND) &&
|
||||
!settings?.trackers.includes(BodyPart.RIGHT_HAND) &&
|
||||
(values.leftHand || values.rightHand)
|
||||
) {
|
||||
// We have just toggled on one of the hand trackers, show the user a warning
|
||||
setShowHandsWarning([values.leftHand, values.rightHand]);
|
||||
values.leftHand = false;
|
||||
values.rightHand = false;
|
||||
} else if (
|
||||
blockHandsWarning.current &&
|
||||
!values.leftHand && !values.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;
|
||||
}
|
||||
|
||||
req.automaticTrackerToggle = values.automaticTrackerToggle;
|
||||
req.sendDerivedVelocity = values.sendDerivedVelocity;
|
||||
|
||||
sendRPCPacket(RpcMessage.ChangeOutputTrackersSettingsRequest, req);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const subscription = watch(() => handleSubmit(onSubmit)());
|
||||
return () => subscription.unsubscribe();
|
||||
}, []);
|
||||
|
||||
useRPCPacket(RpcMessage.OutputTrackersSettingsResponse, (settings: OutputTrackersSettingsResponseT) => {
|
||||
const formData: OutputTrackersSettingsForm = defaultOutputTrackersSettings;
|
||||
formData.automaticTrackerToggle = settings.automaticTrackerToggle;
|
||||
formData.sendDerivedVelocity = settings.sendDerivedVelocity;
|
||||
|
||||
reset(formData);
|
||||
});
|
||||
|
||||
return (
|
||||
<SettingsPageLayout>
|
||||
<form className="flex flex-col gap-2 w-full">
|
||||
<SettingsPagePaneLayout icon={<OutputTrackersIcon />} id="vmc">
|
||||
<>
|
||||
<Typography variant="main-title">
|
||||
{l10n.getString('settings-osc-vmc')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pt-2 pb-4">
|
||||
<>
|
||||
{l10n
|
||||
.getString('settings-osc-vmc-description')
|
||||
.split('\n')
|
||||
.map((line, i) => (
|
||||
<Typography key={i}>{line}</Typography>
|
||||
))}
|
||||
</>
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vmc-enable')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n.getString('settings-osc-vmc-enable-description')}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3 pb-5">
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="enabled"
|
||||
label={l10n.getString('settings-osc-vmc-enable-label')}
|
||||
/>
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vmc-network')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<>
|
||||
{l10n
|
||||
.getString('settings-osc-vmc-network-description')
|
||||
.split('\n')
|
||||
.map((line, i) => (
|
||||
<Typography key={i}>{line}</Typography>
|
||||
))}
|
||||
</>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3 pb-5">
|
||||
<Localized
|
||||
id="settings-osc-vmc-network-port_in"
|
||||
attrs={{ placeholder: true, label: true }}
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
control={control}
|
||||
name="portsAddress.portIn"
|
||||
placeholder="9002"
|
||||
label=""
|
||||
/>
|
||||
</Localized>
|
||||
<Localized
|
||||
id="settings-osc-vmc-network-port_out"
|
||||
attrs={{ placeholder: true, label: true }}
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
control={control}
|
||||
name="portsAddress.portOut"
|
||||
placeholder="9000"
|
||||
label=""
|
||||
/>
|
||||
</Localized>
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vmc-network-address')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n.getString('settings-osc-vmc-network-address-description')}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid gap-3 pb-5">
|
||||
<Input
|
||||
type="text"
|
||||
control={control}
|
||||
name="portsAddress.address"
|
||||
placeholder={l10n.getString(
|
||||
'settings-osc-vmc-network-address-placeholder'
|
||||
)}
|
||||
label=""
|
||||
/>
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vmc-vrm')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n.getString('settings-osc-vmc-vrm-description')}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid gap-3 pb-5">
|
||||
<OutputTrackersFileUpload />
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vmc-anchor_hip')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n.getString('settings-osc-vmc-anchor_hip-description')}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3 pb-5">
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="anchorHip"
|
||||
label={l10n.getString('settings-osc-vmc-anchor_hip-label')}
|
||||
/>
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vmc-mirror_tracking')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n.getString('settings-osc-vmc-mirror_tracking-description')}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3 pb-5">
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="mirrorTracking"
|
||||
label={l10n.getString('settings-osc-vmc-mirror_tracking-label')}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
</SettingsPagePaneLayout>
|
||||
</form>
|
||||
</SettingsPageLayout>
|
||||
);
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
SerialUpdateResponseT,
|
||||
SerialTrackerGetWifiScanRequestT,
|
||||
SerialTrackerCustomCommandRequestT,
|
||||
SerialDeviceType,
|
||||
} from 'solarxr-protocol';
|
||||
import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
import { Button } from '@/components/commons/Button';
|
||||
@@ -41,7 +42,10 @@ export function Serial() {
|
||||
const consoleRef = useRef<HTMLDivElement>(null);
|
||||
const [consoleContent, setConsole] = useState('');
|
||||
|
||||
const [isSerialOpen, setSerialOpen] = useState(false);
|
||||
const [openedSerialDevice, setOpenedSerialDevice] = useState<Omit<
|
||||
SerialDeviceT,
|
||||
'pack'
|
||||
> | null>(null);
|
||||
const [serialDevices, setSerialDevices] = useState<
|
||||
Omit<SerialDeviceT, 'pack'>[]
|
||||
>([]);
|
||||
@@ -87,11 +91,19 @@ export function Serial() {
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
sendRPCPacket(RpcMessage.SerialDevicesRequest, new SerialDevicesRequestT());
|
||||
const typedState: { serialPort: string } = state as any;
|
||||
if (typedState?.serialPort) {
|
||||
reset({ port: typedState.serialPort });
|
||||
}
|
||||
|
||||
sendRPCPacket(RpcMessage.SerialDevicesRequest, new SerialDevicesRequestT());
|
||||
const interval = setInterval(() => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.SerialDevicesRequest,
|
||||
new SerialDevicesRequestT()
|
||||
);
|
||||
}, 3000);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -103,11 +115,8 @@ export function Serial() {
|
||||
useRPCPacket(
|
||||
RpcMessage.SerialUpdateResponse,
|
||||
(data: SerialUpdateResponseT) => {
|
||||
if (data.closed) {
|
||||
setSerialOpen(false);
|
||||
} else {
|
||||
setSerialOpen(true);
|
||||
}
|
||||
if (data.device) setOpenedSerialDevice(data.device);
|
||||
else if (data.closed) setOpenedSerialDevice(null);
|
||||
|
||||
if (data.log) {
|
||||
setConsole((console) => console + data.log);
|
||||
@@ -122,6 +131,7 @@ export function Serial() {
|
||||
{
|
||||
name: l10n.getString('settings-serial-auto_dropdown_item'),
|
||||
port: 'Auto',
|
||||
type: SerialDeviceType.ESP_TRACKER,
|
||||
},
|
||||
...(res.devices || []),
|
||||
]);
|
||||
@@ -161,7 +171,7 @@ export function Serial() {
|
||||
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => {
|
||||
if (!isSerialOpen) {
|
||||
if (openedSerialDevice === null) {
|
||||
openSerial(port ?? defaultValues.port);
|
||||
} else {
|
||||
clearInterval(id);
|
||||
@@ -171,7 +181,7 @@ export function Serial() {
|
||||
return () => {
|
||||
clearInterval(id);
|
||||
};
|
||||
}, [isSerialOpen]);
|
||||
}, [openedSerialDevice]);
|
||||
|
||||
const reboot = () => {
|
||||
sendRPCPacket(
|
||||
@@ -179,6 +189,8 @@ export function Serial() {
|
||||
new SerialTrackerRebootRequestT()
|
||||
);
|
||||
};
|
||||
|
||||
// ESP
|
||||
const factoryReset = () => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.SerialTrackerFactoryResetRequest,
|
||||
@@ -209,6 +221,48 @@ export function Serial() {
|
||||
setValue('customCommand', '');
|
||||
};
|
||||
|
||||
// HID
|
||||
const enterPairing = () => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.SerialTrackerCustomCommandRequest,
|
||||
new SerialTrackerCustomCommandRequestT('pair')
|
||||
);
|
||||
};
|
||||
const dfu = () => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.SerialTrackerCustomCommandRequest,
|
||||
new SerialTrackerCustomCommandRequestT('dfu')
|
||||
);
|
||||
};
|
||||
const meow = () => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.SerialTrackerCustomCommandRequest,
|
||||
new SerialTrackerCustomCommandRequestT('meow')
|
||||
);
|
||||
};
|
||||
|
||||
// HID receiver
|
||||
const exitPairing = () => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.SerialTrackerCustomCommandRequest,
|
||||
new SerialTrackerCustomCommandRequestT('exit')
|
||||
);
|
||||
};
|
||||
|
||||
// HID tracker
|
||||
const calibrate = () => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.SerialTrackerCustomCommandRequest,
|
||||
new SerialTrackerCustomCommandRequestT('calibrate')
|
||||
);
|
||||
};
|
||||
const sixSideCalibrate = () => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.SerialTrackerCustomCommandRequest,
|
||||
new SerialTrackerCustomCommandRequestT('6-side')
|
||||
);
|
||||
};
|
||||
|
||||
const consoleContentRef = useRef(consoleContent);
|
||||
useLayoutEffect(() => {
|
||||
consoleContentRef.current = consoleContent;
|
||||
@@ -318,7 +372,7 @@ export function Serial() {
|
||||
>
|
||||
<div className="flex select-text">
|
||||
<pre>
|
||||
{isSerialOpen
|
||||
{openedSerialDevice !== null
|
||||
? consoleContent
|
||||
: l10n.getString('settings-serial-connection_lost')}
|
||||
</pre>
|
||||
@@ -326,70 +380,115 @@ export function Serial() {
|
||||
</div>
|
||||
<div className="border-t-2 pt-2 border-background-60 border-solid gap-2 flex flex-row">
|
||||
<div className="xs:flex flex-grow xs:flex-wrap gap-2 grid grid-cols-2">
|
||||
<Button variant="quaternary" onClick={reboot}>
|
||||
{l10n.getString('settings-serial-reboot')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="quaternary"
|
||||
onClick={() => setTryFactoryReset(true)}
|
||||
>
|
||||
{l10n.getString('settings-serial-factory_reset')}
|
||||
</Button>
|
||||
<Button variant="quaternary" onClick={getWifiScan}>
|
||||
{l10n.getString('settings-serial-get_wifi_scan')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="quaternary"
|
||||
onClick={saveLogToFile}
|
||||
disabled={!isSerialOpen || !consoleContent.trim()}
|
||||
>
|
||||
{l10n.getString('settings-serial-save_logs')}
|
||||
</Button>
|
||||
<div className="ml-auto">
|
||||
<Button
|
||||
variant="quaternary"
|
||||
onClick={pauseScroll}
|
||||
icon={
|
||||
isPaused ? (
|
||||
<PlayIcon width={16} />
|
||||
) : (
|
||||
<PauseIcon width={16} />
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<form
|
||||
className="w-full flex flex-row gap-2 mobile:col-span-2"
|
||||
onSubmit={(e) => {
|
||||
if (!isSerialOpen) {
|
||||
return;
|
||||
}
|
||||
e.preventDefault();
|
||||
if (!acceptedCustomCommandWarning) {
|
||||
setTrySendCustomCommand(true);
|
||||
} else {
|
||||
sendCustomSerialCommand();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex-grow">
|
||||
<Input
|
||||
control={control}
|
||||
name="customCommand"
|
||||
className="flex-grow"
|
||||
placeholder={l10n.getString(
|
||||
'settings-serial-send_command-placeholder'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
variant="quaternary"
|
||||
disabled={!isSerialOpen}
|
||||
type="submit"
|
||||
>
|
||||
{l10n.getString('settings-serial-send_command')}
|
||||
</Button>
|
||||
</form>
|
||||
{openedSerialDevice !== null && (
|
||||
<>
|
||||
<Button variant="quaternary" onClick={reboot}>
|
||||
{l10n.getString('settings-serial-reboot')}
|
||||
</Button>
|
||||
{openedSerialDevice?.type ===
|
||||
SerialDeviceType.ESP_TRACKER && (
|
||||
<>
|
||||
<Button
|
||||
variant="quaternary"
|
||||
onClick={() => setTryFactoryReset(true)}
|
||||
>
|
||||
{l10n.getString('settings-serial-factory_reset')}
|
||||
</Button>
|
||||
<Button variant="quaternary" onClick={getWifiScan}>
|
||||
{l10n.getString('settings-serial-get_wifi_scan')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{openedSerialDevice?.type !==
|
||||
SerialDeviceType.ESP_TRACKER && (
|
||||
<Button variant="quaternary" onClick={enterPairing}>
|
||||
{l10n.getString('settings-serial-enter_pairing')}
|
||||
</Button>
|
||||
)}
|
||||
{openedSerialDevice?.type ===
|
||||
SerialDeviceType.HID_RECEIVER && (
|
||||
<Button variant="quaternary" onClick={exitPairing}>
|
||||
{l10n.getString('settings-serial-exit_pairing')}
|
||||
</Button>
|
||||
)}
|
||||
{openedSerialDevice?.type ===
|
||||
SerialDeviceType.HID_TRACKER && (
|
||||
<>
|
||||
<Button variant="quaternary" onClick={calibrate}>
|
||||
{l10n.getString('settings-serial-calibrate')}
|
||||
</Button>
|
||||
<Button variant="quaternary" onClick={sixSideCalibrate}>
|
||||
{l10n.getString('settings-serial-six_side_calibrate')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{openedSerialDevice?.type !==
|
||||
SerialDeviceType.ESP_TRACKER && (
|
||||
<>
|
||||
<Button variant="quaternary" onClick={dfu}>
|
||||
{l10n.getString('settings-serial-dfu')}
|
||||
</Button>
|
||||
<Button variant="quaternary" onClick={meow}>
|
||||
{l10n.getString('settings-serial-meow')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
<Button
|
||||
variant="quaternary"
|
||||
onClick={saveLogToFile}
|
||||
disabled={
|
||||
openedSerialDevice === null || !consoleContent.trim()
|
||||
}
|
||||
>
|
||||
{l10n.getString('settings-serial-save_logs')}
|
||||
</Button>
|
||||
<div className="ml-auto">
|
||||
<Button
|
||||
variant="quaternary"
|
||||
onClick={pauseScroll}
|
||||
icon={
|
||||
isPaused ? (
|
||||
<PlayIcon width={16} />
|
||||
) : (
|
||||
<PauseIcon width={16} />
|
||||
)
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<form
|
||||
className="w-full flex flex-row gap-2 mobile:col-span-2"
|
||||
onSubmit={(e) => {
|
||||
if (openedSerialDevice === null) {
|
||||
return;
|
||||
}
|
||||
e.preventDefault();
|
||||
if (!acceptedCustomCommandWarning) {
|
||||
setTrySendCustomCommand(true);
|
||||
} else {
|
||||
sendCustomSerialCommand();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="flex-grow">
|
||||
<Input
|
||||
control={control}
|
||||
name="customCommand"
|
||||
className="flex-grow"
|
||||
placeholder={l10n.getString(
|
||||
'settings-serial-send_command-placeholder'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
variant="quaternary"
|
||||
disabled={openedSerialDevice === null}
|
||||
type="submit"
|
||||
>
|
||||
{l10n.getString('settings-serial-send_command')}
|
||||
</Button>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="w-full mobile:col-span-2">
|
||||
<Dropdown
|
||||
|
||||
@@ -2,13 +2,13 @@ import { Localized, useLocalization } from '@fluent/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import {
|
||||
ChangeSettingsRequestT,
|
||||
ChangeVMCOSCSettingsRequestT,
|
||||
ChangeVRMSettingsRequestT,
|
||||
RpcMessage,
|
||||
SettingsRequestT,
|
||||
SettingsResponseT,
|
||||
OSCSettingsT,
|
||||
VMCOSCSettingsT,
|
||||
VRMSettingsT,
|
||||
VMCOSCSettingsRequestT,
|
||||
VMCOSCSettingsResponseT,
|
||||
VRMSettingsRequestT,
|
||||
VRMSettingsResponseT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
import { CheckBox } from '@/components/commons/Checkbox';
|
||||
@@ -23,34 +23,31 @@ import {
|
||||
} from '@/components/settings/SettingsPageLayout';
|
||||
import { error } from '@/utils/logging';
|
||||
import {
|
||||
OSCSettings,
|
||||
useOscSettingsValidator,
|
||||
OSCPortsAddress,
|
||||
useOscPortsAddressValidator,
|
||||
} from '@/hooks/osc-setting-validator';
|
||||
import { yupResolver } from '@hookform/resolvers/yup';
|
||||
import { boolean, object } from 'yup';
|
||||
|
||||
interface VMCSettingsForm {
|
||||
vmc: {
|
||||
oscSettings: OSCSettings;
|
||||
anchorHip: boolean;
|
||||
mirrorTracking: boolean;
|
||||
};
|
||||
enabled: boolean,
|
||||
portsAddress: OSCPortsAddress,
|
||||
anchorHip: boolean;
|
||||
mirrorTracking: boolean;
|
||||
}
|
||||
|
||||
const defaultValues = {
|
||||
vmc: {
|
||||
oscSettings: {
|
||||
enabled: false,
|
||||
portIn: 39540,
|
||||
portOut: 39539,
|
||||
address: '127.0.0.1',
|
||||
},
|
||||
anchorHip: true,
|
||||
mirrorTracking: true,
|
||||
const defaultVMCSettings: VMCSettingsForm = {
|
||||
enabled: false,
|
||||
portsAddress: {
|
||||
portIn: 39540,
|
||||
portOut: 39539,
|
||||
address: '127.0.0.1',
|
||||
},
|
||||
anchorHip: true,
|
||||
mirrorTracking: true,
|
||||
};
|
||||
|
||||
export function VMCFileUpload() {
|
||||
export function VRMFileUpload() {
|
||||
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
|
||||
const { l10n } = useLocalization();
|
||||
const [modelName, setModelName] = useState<string | null>(null);
|
||||
@@ -66,22 +63,20 @@ export function VMCFileUpload() {
|
||||
const vrmJson = watch('vrmJson');
|
||||
|
||||
const updateVRMJson = async () => {
|
||||
const req = new ChangeSettingsRequestT();
|
||||
const vrm = new VRMSettingsT();
|
||||
const req = new ChangeVRMSettingsRequestT();
|
||||
if (vrmJson !== undefined) {
|
||||
if (vrmJson.length > 0) {
|
||||
const file = await parseVRMFile(vrmJson[0]);
|
||||
if (file) {
|
||||
vrm.vrmJson = file.json;
|
||||
req.vrmJson = file.json;
|
||||
setModelName(file.name);
|
||||
}
|
||||
} else {
|
||||
vrm.vrmJson = '';
|
||||
req.vrmJson = '';
|
||||
setModelName(null);
|
||||
}
|
||||
}
|
||||
req.vrm = vrm;
|
||||
sendRPCPacket(RpcMessage.ChangeSettingsRequest, req);
|
||||
sendRPCPacket(RpcMessage.ChangeVRMSettingsRequest, req);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@@ -89,11 +84,12 @@ export function VMCFileUpload() {
|
||||
}, [vrmJson]);
|
||||
|
||||
useEffect(() => {
|
||||
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT());
|
||||
sendRPCPacket(RpcMessage.VMCOSCSettingsRequest, new VMCOSCSettingsRequestT());
|
||||
sendRPCPacket(RpcMessage.VRMSettingsRequest, new VRMSettingsRequestT());
|
||||
}, []);
|
||||
|
||||
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
|
||||
const vrmJson = settings.vrm?.vrmJson?.toString();
|
||||
useRPCPacket(RpcMessage.VRMSettingsResponse, (settings: VRMSettingsResponseT) => {
|
||||
const vrmJson = settings.vrmJson?.toString();
|
||||
if (vrmJson) {
|
||||
let data: any;
|
||||
try {
|
||||
@@ -114,7 +110,7 @@ export function VMCFileUpload() {
|
||||
}}
|
||||
value="help"
|
||||
importedFileName={
|
||||
// if modelname is an empty string, it's an untitled model
|
||||
// if modelName is an empty string, it's an untitled model
|
||||
modelName === ''
|
||||
? l10n.getString('settings-osc-vmc-vrm-untitled_model')
|
||||
: modelName
|
||||
@@ -128,39 +124,33 @@ export function VMCFileUpload() {
|
||||
export function VMCSettings() {
|
||||
const { l10n } = useLocalization();
|
||||
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
|
||||
const { oscValidator } = useOscSettingsValidator();
|
||||
const { oscValidator } = useOscPortsAddressValidator();
|
||||
|
||||
const { reset, control, watch, handleSubmit } = useForm<VMCSettingsForm>({
|
||||
defaultValues,
|
||||
defaultValues: defaultVMCSettings,
|
||||
reValidateMode: 'onChange',
|
||||
mode: 'onChange',
|
||||
resolver: yupResolver(
|
||||
object({
|
||||
vmc: object({
|
||||
oscSettings: oscValidator,
|
||||
anchorHip: boolean().required(),
|
||||
mirrorTracking: boolean().required(),
|
||||
}),
|
||||
enabled: boolean().required(),
|
||||
portsAddress: oscValidator,
|
||||
anchorHip: boolean().required(),
|
||||
mirrorTracking: boolean().required(),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
const onSubmit = async (values: VMCSettingsForm) => {
|
||||
const settings = new ChangeSettingsRequestT();
|
||||
const req = new ChangeVMCOSCSettingsRequestT();
|
||||
|
||||
if (values.vmc) {
|
||||
const vmcOsc = new VMCOSCSettingsT();
|
||||
req.enabled = values.enabled
|
||||
req.portIn = values.portsAddress.portIn
|
||||
req.portOut = values.portsAddress.portOut
|
||||
req.address = values.portsAddress.address
|
||||
req.anchorHip = values.anchorHip;
|
||||
req.mirrorTracking = values.mirrorTracking;
|
||||
|
||||
vmcOsc.oscSettings = Object.assign(
|
||||
new OSCSettingsT(),
|
||||
values.vmc.oscSettings
|
||||
);
|
||||
vmcOsc.anchorHip = values.vmc.anchorHip;
|
||||
vmcOsc.mirrorTracking = values.vmc.mirrorTracking;
|
||||
|
||||
settings.vmcOsc = vmcOsc;
|
||||
}
|
||||
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settings);
|
||||
sendRPCPacket(RpcMessage.ChangeVMCOSCSettingsRequest, req);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@@ -168,27 +158,19 @@ export function VMCSettings() {
|
||||
return () => subscription.unsubscribe();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT());
|
||||
}, []);
|
||||
useRPCPacket(RpcMessage.VMCOSCSettingsResponse, (settings: VMCOSCSettingsResponseT) => {
|
||||
const formData: VMCSettingsForm = defaultVMCSettings;
|
||||
if (settings) {
|
||||
formData.enabled = settings.enabled;
|
||||
if (settings.portIn)
|
||||
formData.portsAddress.portIn = settings.portIn;
|
||||
if (settings.portOut)
|
||||
formData.portsAddress.portOut = settings.portOut;
|
||||
if (settings.address)
|
||||
formData.portsAddress.address = settings.address.toString();
|
||||
|
||||
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
|
||||
const formData: VMCSettingsForm = defaultValues;
|
||||
if (settings.vmcOsc) {
|
||||
if (settings.vmcOsc.oscSettings) {
|
||||
formData.vmc.oscSettings.enabled = settings.vmcOsc.oscSettings.enabled;
|
||||
if (settings.vmcOsc.oscSettings.portIn)
|
||||
formData.vmc.oscSettings.portIn = settings.vmcOsc.oscSettings.portIn;
|
||||
if (settings.vmcOsc.oscSettings.portOut)
|
||||
formData.vmc.oscSettings.portOut =
|
||||
settings.vmcOsc.oscSettings.portOut;
|
||||
if (settings.vmcOsc.oscSettings.address)
|
||||
formData.vmc.oscSettings.address =
|
||||
settings.vmcOsc.oscSettings.address.toString();
|
||||
}
|
||||
|
||||
formData.vmc.anchorHip = settings.vmcOsc.anchorHip;
|
||||
formData.vmc.mirrorTracking = settings.vmcOsc.mirrorTracking;
|
||||
formData.anchorHip = settings.anchorHip;
|
||||
formData.mirrorTracking = settings.mirrorTracking;
|
||||
|
||||
reset(formData);
|
||||
}
|
||||
@@ -225,7 +207,7 @@ export function VMCSettings() {
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="vmc.oscSettings.enabled"
|
||||
name="enabled"
|
||||
label={l10n.getString('settings-osc-vmc-enable-label')}
|
||||
/>
|
||||
</div>
|
||||
@@ -250,7 +232,7 @@ export function VMCSettings() {
|
||||
<Input
|
||||
type="number"
|
||||
control={control}
|
||||
name="vmc.oscSettings.portIn"
|
||||
name="portsAddress.portIn"
|
||||
placeholder="9002"
|
||||
label=""
|
||||
/>
|
||||
@@ -262,7 +244,7 @@ export function VMCSettings() {
|
||||
<Input
|
||||
type="number"
|
||||
control={control}
|
||||
name="vmc.oscSettings.portOut"
|
||||
name="portsAddress.portOut"
|
||||
placeholder="9000"
|
||||
label=""
|
||||
/>
|
||||
@@ -280,7 +262,7 @@ export function VMCSettings() {
|
||||
<Input
|
||||
type="text"
|
||||
control={control}
|
||||
name="vmc.oscSettings.address"
|
||||
name="portsAddress.address"
|
||||
placeholder={l10n.getString(
|
||||
'settings-osc-vmc-network-address-placeholder'
|
||||
)}
|
||||
@@ -296,7 +278,7 @@ export function VMCSettings() {
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid gap-3 pb-5">
|
||||
<VMCFileUpload />
|
||||
<VRMFileUpload />
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vmc-anchor_hip')}
|
||||
@@ -311,7 +293,7 @@ export function VMCSettings() {
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="vmc.anchorHip"
|
||||
name="anchorHip"
|
||||
label={l10n.getString('settings-osc-vmc-anchor_hip-label')}
|
||||
/>
|
||||
</div>
|
||||
@@ -328,7 +310,7 @@ export function VMCSettings() {
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="vmc.mirrorTracking"
|
||||
name="mirrorTracking"
|
||||
label={l10n.getString('settings-osc-vmc-mirror_tracking-label')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -1,115 +1,387 @@
|
||||
import { Localized, useLocalization } from '@fluent/react';
|
||||
import { useEffect } from 'react';
|
||||
import { yupResolver } from '@hookform/resolvers/yup';
|
||||
import classNames from 'classnames';
|
||||
import { ReactNode, useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { boolean, object } from 'yup';
|
||||
import {
|
||||
ChangeSettingsRequestT,
|
||||
OSCSettingsT,
|
||||
OSCTrackersSettingT,
|
||||
ChangeVRCOSCSettingsRequestT,
|
||||
RpcMessage,
|
||||
SettingsRequestT,
|
||||
SettingsResponseT,
|
||||
VRCOSCSettingsT,
|
||||
VRCOSCInputState,
|
||||
VRCOSCNetworkSettingsT,
|
||||
VRCOSCOscQueryState,
|
||||
VRCOSCOutputState,
|
||||
VRCOSCSettingsRequestT,
|
||||
VRCOSCSettingsResponseT,
|
||||
VRCOSCStatusChangeResponseT,
|
||||
VRCOSCStatusRequestT,
|
||||
VRCOSCTargetSource,
|
||||
type VRCOSCDiscoveredTargetT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
import { Button } from '@/components/commons/Button';
|
||||
import { CheckBox } from '@/components/commons/Checkbox';
|
||||
import { VRCIcon } from '@/components/commons/icon/VRCIcon';
|
||||
import { Input } from '@/components/commons/Input';
|
||||
import { Typography } from '@/components/commons/Typography';
|
||||
import { VRCIcon } from '@/components/commons/icon/VRCIcon';
|
||||
import {
|
||||
SettingsPageLayout,
|
||||
SettingsPagePaneLayout,
|
||||
} from '@/components/settings/SettingsPageLayout';
|
||||
import { yupResolver } from '@hookform/resolvers/yup';
|
||||
import { boolean, object } from 'yup';
|
||||
import {
|
||||
OSCSettings,
|
||||
useOscSettingsValidator,
|
||||
} from '@/hooks/osc-setting-validator';
|
||||
import { useWebsocketAPI } from '@/hooks/websocket-api';
|
||||
import {OSCPortsAddress, useOscPortsAddressValidator} from "@/hooks/osc-setting-validator";
|
||||
|
||||
interface VRCOSCSettingsForm {
|
||||
vrchat: {
|
||||
oscSettings: OSCSettings;
|
||||
trackers: {
|
||||
head: boolean;
|
||||
chest: boolean;
|
||||
elbows: boolean;
|
||||
feet: boolean;
|
||||
knees: boolean;
|
||||
hands: boolean;
|
||||
waist: boolean;
|
||||
};
|
||||
oscqueryEnabled: boolean;
|
||||
};
|
||||
enabled: boolean;
|
||||
useManualNetwork: boolean;
|
||||
manualNetwork: OSCPortsAddress
|
||||
}
|
||||
|
||||
const defaultValues = {
|
||||
vrchat: {
|
||||
oscSettings: {
|
||||
enabled: false,
|
||||
portIn: 9001,
|
||||
portOut: 9000,
|
||||
address: '127.0.0.1',
|
||||
},
|
||||
trackers: {
|
||||
head: false,
|
||||
chest: false,
|
||||
elbows: false,
|
||||
feet: false,
|
||||
knees: false,
|
||||
hands: false,
|
||||
waist: false,
|
||||
},
|
||||
oscqueryEnabled: true,
|
||||
const defaultVRCOSCSettings: VRCOSCSettingsForm = {
|
||||
enabled: false,
|
||||
useManualNetwork: false,
|
||||
manualNetwork: {
|
||||
portIn: 9001,
|
||||
portOut: 9000,
|
||||
address: '127.0.0.1',
|
||||
},
|
||||
};
|
||||
|
||||
function asString(value: string | Uint8Array | null | undefined): string {
|
||||
return typeof value === 'string' ? value : '';
|
||||
}
|
||||
|
||||
function formatElapsedTime(timestamp: bigint | null | undefined, now: number) {
|
||||
if (!timestamp) return null;
|
||||
|
||||
const elapsedSeconds = Math.max(
|
||||
0,
|
||||
Math.floor((now - Number(timestamp)) / 1000)
|
||||
);
|
||||
if (elapsedSeconds < 5) return 'just now';
|
||||
if (elapsedSeconds < 60) return `${elapsedSeconds}s ago`;
|
||||
|
||||
const elapsedMinutes = Math.floor(elapsedSeconds / 60);
|
||||
if (elapsedMinutes < 60) return `${elapsedMinutes}m ago`;
|
||||
|
||||
const elapsedHours = Math.floor(elapsedMinutes / 60);
|
||||
return `${elapsedHours}h ago`;
|
||||
}
|
||||
|
||||
type BadgeKind =
|
||||
| 'idle'
|
||||
| 'listening'
|
||||
| 'ready'
|
||||
| 'found'
|
||||
| 'searching'
|
||||
| 'disabled'
|
||||
| 'error';
|
||||
|
||||
const BADGE_LABEL_KEY: Record<BadgeKind, string> = {
|
||||
idle: 'settings-osc-vrchat-status-badge-idle',
|
||||
listening: 'settings-osc-vrchat-status-badge-listening',
|
||||
ready: 'settings-osc-vrchat-status-badge-ready',
|
||||
found: 'settings-osc-vrchat-status-badge-found',
|
||||
searching: 'settings-osc-vrchat-status-badge-searching',
|
||||
disabled: 'settings-osc-vrchat-status-badge-disabled',
|
||||
error: 'settings-osc-vrchat-status-badge-error',
|
||||
};
|
||||
|
||||
const BADGE_CLASSES: Record<BadgeKind, string> = {
|
||||
idle: 'bg-background-50',
|
||||
listening: 'bg-status-success',
|
||||
ready: 'bg-status-success',
|
||||
found: 'bg-status-success',
|
||||
searching: 'bg-status-special',
|
||||
disabled: 'bg-background-50',
|
||||
error: 'bg-status-critical',
|
||||
};
|
||||
|
||||
function StatusBadge({ kind }: { kind: BadgeKind }) {
|
||||
return (
|
||||
<span
|
||||
className={classNames(
|
||||
'rounded-md px-2 py-1 bg-background-70 flex gap-2 items-center'
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={classNames('h-2 w-2 rounded-full', BADGE_CLASSES[kind])}
|
||||
/>
|
||||
<Typography id={BADGE_LABEL_KEY[kind]} bold />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function StatusRow({
|
||||
label,
|
||||
badge,
|
||||
children,
|
||||
}: {
|
||||
label: string;
|
||||
badge: BadgeKind;
|
||||
children?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="flex flex-col gap-1 py-2">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<Typography variant="section-title">{label}</Typography>
|
||||
<StatusBadge kind={badge} />
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function inputBadge(
|
||||
state: VRCOSCInputState,
|
||||
lastReceivedMillis: bigint | null | undefined
|
||||
): BadgeKind {
|
||||
switch (state) {
|
||||
case VRCOSCInputState.LISTENING:
|
||||
return lastReceivedMillis ? 'listening' : 'ready';
|
||||
case VRCOSCInputState.ERROR:
|
||||
return 'error';
|
||||
default:
|
||||
return 'idle';
|
||||
}
|
||||
}
|
||||
|
||||
function outputBadge(state: VRCOSCOutputState): BadgeKind {
|
||||
switch (state) {
|
||||
case VRCOSCOutputState.READY:
|
||||
return 'ready';
|
||||
case VRCOSCOutputState.ERROR:
|
||||
return 'error';
|
||||
default:
|
||||
return 'idle';
|
||||
}
|
||||
}
|
||||
|
||||
function oscQueryBadge(state: VRCOSCOscQueryState): BadgeKind {
|
||||
switch (state) {
|
||||
case VRCOSCOscQueryState.FOUND:
|
||||
return 'found';
|
||||
case VRCOSCOscQueryState.SEARCHING:
|
||||
return 'searching';
|
||||
case VRCOSCOscQueryState.ERROR:
|
||||
return 'error';
|
||||
default:
|
||||
return 'disabled';
|
||||
}
|
||||
}
|
||||
|
||||
function StatusCard({
|
||||
status,
|
||||
now,
|
||||
onSwitchToTarget,
|
||||
}: {
|
||||
status: VRCOSCStatusChangeResponseT;
|
||||
now: number;
|
||||
onSwitchToTarget: (target: VRCOSCDiscoveredTargetT) => void;
|
||||
}) {
|
||||
const { l10n } = useLocalization();
|
||||
|
||||
const inputState = status.inputState ?? VRCOSCInputState.IDLE;
|
||||
const outputState = status.outputState ?? VRCOSCOutputState.IDLE;
|
||||
const oscQueryState = status.oscqueryState ?? VRCOSCOscQueryState.DISABLED;
|
||||
const targetSource = status.targetSource ?? VRCOSCTargetSource.NONE;
|
||||
|
||||
const sourceLabel =
|
||||
targetSource === VRCOSCTargetSource.MANUAL
|
||||
? l10n.getString('settings-osc-vrchat-status-source-manual')
|
||||
: targetSource === VRCOSCTargetSource.DISCOVERED
|
||||
? l10n.getString('settings-osc-vrchat-status-source-auto')
|
||||
: '';
|
||||
|
||||
const lastInputElapsed = formatElapsedTime(
|
||||
status.lastReceivedInputMillis,
|
||||
now
|
||||
);
|
||||
const lastFrameElapsed = formatElapsedTime(status.lastFrameSentMillis, now);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col bg-background-80 px-4 py-2 mb-5 rounded-md divide-y divide-background-60">
|
||||
<StatusRow
|
||||
label={l10n.getString('settings-osc-vrchat-status-input')}
|
||||
badge={inputBadge(inputState, status.lastReceivedInputMillis)}
|
||||
>
|
||||
{inputState === VRCOSCInputState.IDLE ? (
|
||||
<Typography color="secondary">
|
||||
{l10n.getString('settings-osc-vrchat-status-input-idle')}
|
||||
</Typography>
|
||||
) : (
|
||||
<>
|
||||
<Typography color="secondary">
|
||||
{l10n.getString('settings-osc-vrchat-status-input-listening', {
|
||||
port: `${status.inputPort ?? 0}`,
|
||||
})}
|
||||
</Typography>
|
||||
{inputState === VRCOSCInputState.ERROR && status.inputError ? (
|
||||
<Typography color="secondary">
|
||||
{asString(status.inputError)}
|
||||
</Typography>
|
||||
) : lastInputElapsed ? (
|
||||
<Typography color="secondary">
|
||||
{l10n.getString('settings-osc-vrchat-status-input-last-data', {
|
||||
elapsed: lastInputElapsed,
|
||||
})}
|
||||
</Typography>
|
||||
) : (
|
||||
<Typography color="secondary">
|
||||
{l10n.getString('settings-osc-vrchat-status-input-no-data')}
|
||||
</Typography>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</StatusRow>
|
||||
|
||||
<StatusRow
|
||||
label={l10n.getString('settings-osc-vrchat-status-output')}
|
||||
badge={outputBadge(outputState)}
|
||||
>
|
||||
{outputState === VRCOSCOutputState.IDLE ? (
|
||||
<Typography color="secondary">
|
||||
{l10n.getString('settings-osc-vrchat-status-output-idle')}
|
||||
</Typography>
|
||||
) : (
|
||||
<>
|
||||
<Typography color="secondary">
|
||||
{l10n.getString(
|
||||
outputState === VRCOSCOutputState.READY
|
||||
? 'settings-osc-vrchat-status-output-sending'
|
||||
: 'settings-osc-vrchat-status-output-target',
|
||||
{
|
||||
address: asString(status.targetAddress),
|
||||
port: `${status.targetPort ?? 0}`,
|
||||
source: sourceLabel,
|
||||
}
|
||||
)}
|
||||
</Typography>
|
||||
{outputState === VRCOSCOutputState.ERROR && status.outputError ? (
|
||||
<Typography color="secondary">
|
||||
{asString(status.outputError)}
|
||||
</Typography>
|
||||
) : lastFrameElapsed ? (
|
||||
<Typography color="secondary">
|
||||
{l10n.getString(
|
||||
'settings-osc-vrchat-status-output-last-frame',
|
||||
{ elapsed: lastFrameElapsed }
|
||||
)}
|
||||
</Typography>
|
||||
) : (
|
||||
<Typography color="secondary">
|
||||
{l10n.getString('settings-osc-vrchat-status-output-no-frame')}
|
||||
</Typography>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</StatusRow>
|
||||
|
||||
<StatusRow
|
||||
label={l10n.getString('settings-osc-vrchat-status-oscquery')}
|
||||
badge={oscQueryBadge(oscQueryState)}
|
||||
>
|
||||
{oscQueryState === VRCOSCOscQueryState.DISABLED ? (
|
||||
<Typography color="secondary">
|
||||
{l10n.getString('settings-osc-vrchat-status-oscquery-disabled')}
|
||||
</Typography>
|
||||
) : oscQueryState === VRCOSCOscQueryState.ERROR ? (
|
||||
<Typography color="secondary">
|
||||
{asString(status.oscqueryError)}
|
||||
</Typography>
|
||||
) : (
|
||||
<>
|
||||
<Typography color="secondary">
|
||||
{l10n.getString(
|
||||
'settings-osc-vrchat-status-oscquery-advertising',
|
||||
{ port: `${status.oscqueryAdvertisedPort ?? 0}` }
|
||||
)}
|
||||
</Typography>
|
||||
{oscQueryState === VRCOSCOscQueryState.FOUND &&
|
||||
status.discoveredTargets.length > 0 ? (
|
||||
<>
|
||||
<Typography color="secondary">
|
||||
{l10n.getString(
|
||||
'settings-osc-vrchat-status-oscquery-discovered-title'
|
||||
)}
|
||||
</Typography>
|
||||
<ul className="flex flex-col gap-1">
|
||||
{status.discoveredTargets.map((target, index) => (
|
||||
<li
|
||||
key={index}
|
||||
className="flex items-center justify-between gap-2"
|
||||
>
|
||||
<Typography color="secondary">
|
||||
{asString(target.name)} ({asString(target.address)}:
|
||||
{target.portOut})
|
||||
</Typography>
|
||||
{status.discoveredTargets.length > 1 && (
|
||||
<Button
|
||||
variant="tertiary"
|
||||
onClick={() => onSwitchToTarget(target)}
|
||||
>
|
||||
{l10n.getString(
|
||||
'settings-osc-vrchat-status-oscquery-switch'
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
) : (
|
||||
<Typography color="secondary">
|
||||
{l10n.getString(
|
||||
'settings-osc-vrchat-status-oscquery-searching'
|
||||
)}
|
||||
</Typography>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</StatusRow>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function VRCOSCSettings() {
|
||||
const { l10n } = useLocalization();
|
||||
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
|
||||
const { oscValidator } = useOscSettingsValidator();
|
||||
const [status, setStatus] = useState<VRCOSCStatusChangeResponseT | null>(
|
||||
null
|
||||
);
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
|
||||
const { reset, control, watch, handleSubmit } = useForm<VRCOSCSettingsForm>({
|
||||
defaultValues,
|
||||
reValidateMode: 'onChange',
|
||||
mode: 'onChange',
|
||||
resolver: yupResolver(
|
||||
object({
|
||||
vrchat: object({
|
||||
oscSettings: oscValidator,
|
||||
trackers: object({
|
||||
head: boolean().required(),
|
||||
chest: boolean().required(),
|
||||
elbows: boolean().required(),
|
||||
feet: boolean().required(),
|
||||
knees: boolean().required(),
|
||||
hands: boolean().required(),
|
||||
waist: boolean().required(),
|
||||
}),
|
||||
oscqueryEnabled: boolean().required(),
|
||||
}),
|
||||
})
|
||||
),
|
||||
});
|
||||
const { oscValidator } = useOscPortsAddressValidator();
|
||||
const { reset, control, watch, handleSubmit, setValue } =
|
||||
useForm<VRCOSCSettingsForm>({
|
||||
defaultValues: defaultVRCOSCSettings,
|
||||
reValidateMode: 'onChange',
|
||||
mode: 'onChange',
|
||||
resolver: yupResolver(
|
||||
object({
|
||||
enabled: boolean().required(),
|
||||
useManualNetwork: boolean().required(),
|
||||
manualNetwork: oscValidator,
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
const enabled = watch('enabled');
|
||||
const useManualNetwork = watch('useManualNetwork');
|
||||
|
||||
useEffect(() => {
|
||||
const interval = window.setInterval(() => setNow(Date.now()), 1_000);
|
||||
return () => window.clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
const onSubmit = (values: VRCOSCSettingsForm) => {
|
||||
const settings = new ChangeSettingsRequestT();
|
||||
const req = new ChangeVRCOSCSettingsRequestT();
|
||||
|
||||
if (values.vrchat) {
|
||||
const vrcOsc = new VRCOSCSettingsT();
|
||||
req.enabled = values.enabled;
|
||||
req.manualNetwork = values.useManualNetwork
|
||||
? Object.assign(new VRCOSCNetworkSettingsT(), values.manualNetwork)
|
||||
: null;
|
||||
|
||||
vrcOsc.oscSettings = Object.assign(
|
||||
new OSCSettingsT(),
|
||||
values.vrchat.oscSettings
|
||||
);
|
||||
vrcOsc.trackers = Object.assign(
|
||||
new OSCTrackersSettingT(),
|
||||
values.vrchat.trackers
|
||||
);
|
||||
vrcOsc.oscqueryEnabled = values.vrchat.oscqueryEnabled;
|
||||
|
||||
settings.vrcOsc = vrcOsc;
|
||||
}
|
||||
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settings);
|
||||
sendRPCPacket(RpcMessage.ChangeVRCOSCSettingsRequest, req);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@@ -118,34 +390,42 @@ export function VRCOSCSettings() {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT());
|
||||
sendRPCPacket(
|
||||
RpcMessage.VRCOSCSettingsRequest,
|
||||
new VRCOSCSettingsRequestT()
|
||||
);
|
||||
sendRPCPacket(RpcMessage.VRCOSCStatusRequest, new VRCOSCStatusRequestT());
|
||||
}, []);
|
||||
|
||||
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
|
||||
const formData: VRCOSCSettingsForm = defaultValues;
|
||||
if (settings.vrcOsc) {
|
||||
if (settings.vrcOsc.oscSettings) {
|
||||
formData.vrchat.oscSettings.enabled =
|
||||
settings.vrcOsc.oscSettings.enabled;
|
||||
if (settings.vrcOsc.oscSettings.portIn)
|
||||
formData.vrchat.oscSettings.portIn =
|
||||
settings.vrcOsc.oscSettings.portIn;
|
||||
if (settings.vrcOsc.oscSettings.portOut)
|
||||
formData.vrchat.oscSettings.portOut =
|
||||
settings.vrcOsc.oscSettings.portOut;
|
||||
if (settings.vrcOsc.oscSettings.address)
|
||||
formData.vrchat.oscSettings.address =
|
||||
settings.vrcOsc.oscSettings.address.toString();
|
||||
useRPCPacket(
|
||||
RpcMessage.VRCOSCSettingsResponse,
|
||||
(response: VRCOSCSettingsResponseT) => {
|
||||
const formData = defaultVRCOSCSettings;
|
||||
if (response) {
|
||||
formData.enabled = response.enabled;
|
||||
if (response.manualNetwork) {
|
||||
formData.useManualNetwork = true;
|
||||
formData.manualNetwork.portIn = response.manualNetwork.portIn;
|
||||
formData.manualNetwork.portOut =
|
||||
response.manualNetwork.portOut;
|
||||
if (response.manualNetwork.address) {
|
||||
formData.manualNetwork.address = asString(
|
||||
response.manualNetwork.address
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
reset(formData);
|
||||
}
|
||||
|
||||
if (settings.vrcOsc.trackers)
|
||||
formData.vrchat.trackers = settings.vrcOsc.trackers;
|
||||
|
||||
formData.vrchat.oscqueryEnabled = settings.vrcOsc.oscqueryEnabled;
|
||||
|
||||
reset(formData);
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
useRPCPacket(
|
||||
RpcMessage.VRCOSCStatusChangeResponse,
|
||||
(response: VRCOSCStatusChangeResponseT) => {
|
||||
setStatus(response);
|
||||
}
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsPageLayout>
|
||||
@@ -165,6 +445,7 @@ export function VRCOSCSettings() {
|
||||
))}
|
||||
</>
|
||||
</div>
|
||||
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vrchat-enable')}
|
||||
</Typography>
|
||||
@@ -178,22 +459,44 @@ export function VRCOSCSettings() {
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="vrchat.oscSettings.enabled"
|
||||
name="enabled"
|
||||
label={l10n.getString('settings-osc-vrchat-enable-label')}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{enabled && status && (
|
||||
<>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vrchat-status-title')}
|
||||
</Typography>
|
||||
<StatusCard
|
||||
status={status}
|
||||
now={now}
|
||||
onSwitchToTarget={(target) => {
|
||||
setValue('useManualNetwork', true, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
setValue(
|
||||
'manualNetwork.address',
|
||||
asString(target.address),
|
||||
{ shouldDirty: true }
|
||||
);
|
||||
setValue('manualNetwork.portOut', target.portOut, {
|
||||
shouldDirty: true,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vrchat-oscqueryEnabled')}
|
||||
{l10n.getString('settings-osc-vrchat-status-network-mode')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n
|
||||
.getString('settings-osc-vrchat-oscqueryEnabled-description')
|
||||
.split('\n')
|
||||
.map((line, i) => (
|
||||
<Typography key={i}>{line}</Typography>
|
||||
))}
|
||||
{l10n.getString(
|
||||
'settings-osc-vrchat-status-network-mode-description'
|
||||
)}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3 pb-5">
|
||||
@@ -201,125 +504,74 @@ export function VRCOSCSettings() {
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="vrchat.oscqueryEnabled"
|
||||
name="useManualNetwork"
|
||||
label={l10n.getString(
|
||||
'settings-osc-vrchat-oscqueryEnabled-label'
|
||||
'settings-osc-vrchat-status-network-mode-toggle'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vrchat-network')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n.getString('settings-osc-vrchat-network-description-v1')}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3 pb-5">
|
||||
<Localized
|
||||
id="settings-osc-vrchat-network-port_in"
|
||||
attrs={{ placeholder: true, label: true }}
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
control={control}
|
||||
name="vrchat.oscSettings.portIn"
|
||||
placeholder="9001"
|
||||
label=""
|
||||
/>
|
||||
</Localized>
|
||||
<Localized
|
||||
id="settings-osc-vrchat-network-port_out"
|
||||
attrs={{ placeholder: true, label: true }}
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
control={control}
|
||||
name="vrchat.oscSettings.portOut"
|
||||
placeholder="9000"
|
||||
label=""
|
||||
/>
|
||||
</Localized>
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vrchat-network-address')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n.getString(
|
||||
'settings-osc-vrchat-network-address-description-v1'
|
||||
)}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid gap-3 pb-5">
|
||||
<Input
|
||||
type="text"
|
||||
control={control}
|
||||
name="vrchat.oscSettings.address"
|
||||
placeholder={l10n.getString(
|
||||
'settings-osc-vrchat-network-address-placeholder'
|
||||
)}
|
||||
label=""
|
||||
/>
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vrchat-network-trackers')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n.getString(
|
||||
'settings-osc-vrchat-network-trackers-description'
|
||||
)}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3 pb-5">
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="vrchat.trackers.chest"
|
||||
label={l10n.getString(
|
||||
'settings-osc-vrchat-network-trackers-chest'
|
||||
)}
|
||||
/>
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="vrchat.trackers.waist"
|
||||
label={l10n.getString(
|
||||
'settings-osc-vrchat-network-trackers-hip'
|
||||
)}
|
||||
/>
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="vrchat.trackers.knees"
|
||||
label={l10n.getString(
|
||||
'settings-osc-vrchat-network-trackers-knees'
|
||||
)}
|
||||
/>
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="vrchat.trackers.feet"
|
||||
label={l10n.getString(
|
||||
'settings-osc-vrchat-network-trackers-feet'
|
||||
)}
|
||||
/>
|
||||
<CheckBox
|
||||
variant="toggle"
|
||||
outlined
|
||||
control={control}
|
||||
name="vrchat.trackers.elbows"
|
||||
label={l10n.getString(
|
||||
'settings-osc-vrchat-network-trackers-elbows'
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
{useManualNetwork && (
|
||||
<>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vrchat-network')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n.getString(
|
||||
'settings-osc-vrchat-status-network-manual-description'
|
||||
)}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3 pb-5">
|
||||
<Localized
|
||||
id="settings-osc-vrchat-network-port_in"
|
||||
attrs={{ placeholder: true, label: true }}
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
control={control}
|
||||
name="manualNetwork.portIn"
|
||||
placeholder="9001"
|
||||
label=""
|
||||
/>
|
||||
</Localized>
|
||||
<Localized
|
||||
id="settings-osc-vrchat-network-port_out"
|
||||
attrs={{ placeholder: true, label: true }}
|
||||
>
|
||||
<Input
|
||||
type="number"
|
||||
control={control}
|
||||
name="manualNetwork.portOut"
|
||||
placeholder="9000"
|
||||
label=""
|
||||
/>
|
||||
</Localized>
|
||||
</div>
|
||||
<Typography variant="section-title">
|
||||
{l10n.getString('settings-osc-vrchat-network-address')}
|
||||
</Typography>
|
||||
<div className="flex flex-col pb-2">
|
||||
<Typography>
|
||||
{l10n.getString(
|
||||
'settings-osc-vrchat-network-address-description-v1'
|
||||
)}
|
||||
</Typography>
|
||||
</div>
|
||||
<div className="grid gap-3 pb-5">
|
||||
<Input
|
||||
type="text"
|
||||
control={control}
|
||||
name="manualNetwork.address"
|
||||
placeholder={l10n.getString(
|
||||
'settings-osc-vrchat-network-address-placeholder'
|
||||
)}
|
||||
label=""
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
</SettingsPagePaneLayout>
|
||||
</form>
|
||||
|
||||
@@ -9,7 +9,7 @@ import { useLocalization } from '@fluent/react';
|
||||
import { Dispatch, ReactNode, SetStateAction } from 'react';
|
||||
import { StayAlignedRelaxedPose } from 'solarxr-protocol';
|
||||
|
||||
function StaAlignedPoseModal({
|
||||
function StayAlignedPoseModal({
|
||||
open,
|
||||
title,
|
||||
descriptionKeys,
|
||||
@@ -39,8 +39,8 @@ function StaAlignedPoseModal({
|
||||
<Typography variant="main-title">{l10n.getString(title)}</Typography>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
{descriptionKeys.map((descriptionKey) => (
|
||||
<Typography>{l10n.getString(descriptionKey)}</Typography>
|
||||
{descriptionKeys.map((descriptionKey, i) => (
|
||||
<Typography key={i}>{l10n.getString(descriptionKey)}</Typography>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex pt-1 items-center fill-background-50 justify-center px-12">
|
||||
@@ -78,7 +78,7 @@ export const StandingRelaxedPoseModal = ({
|
||||
}: {
|
||||
open: [boolean, Dispatch<SetStateAction<boolean>>];
|
||||
}) => (
|
||||
<StaAlignedPoseModal
|
||||
<StayAlignedPoseModal
|
||||
open={open}
|
||||
title={'onboarding-stay_aligned-relaxed_poses-standing-title'}
|
||||
descriptionKeys={[
|
||||
@@ -92,7 +92,7 @@ export const StandingRelaxedPoseModal = ({
|
||||
width={260}
|
||||
alt="Reset position"
|
||||
/>
|
||||
</StaAlignedPoseModal>
|
||||
</StayAlignedPoseModal>
|
||||
);
|
||||
|
||||
export const SittingRelaxedPoseModal = ({
|
||||
@@ -100,7 +100,7 @@ export const SittingRelaxedPoseModal = ({
|
||||
}: {
|
||||
open: [boolean, Dispatch<SetStateAction<boolean>>];
|
||||
}) => (
|
||||
<StaAlignedPoseModal
|
||||
<StayAlignedPoseModal
|
||||
open={open}
|
||||
title={'onboarding-stay_aligned-relaxed_poses-sitting-title'}
|
||||
descriptionKeys={[
|
||||
@@ -114,7 +114,7 @@ export const SittingRelaxedPoseModal = ({
|
||||
width={260}
|
||||
alt="Reset position"
|
||||
/>
|
||||
</StaAlignedPoseModal>
|
||||
</StayAlignedPoseModal>
|
||||
);
|
||||
|
||||
export const FlatRelaxedPoseModal = ({
|
||||
@@ -122,7 +122,7 @@ export const FlatRelaxedPoseModal = ({
|
||||
}: {
|
||||
open: [boolean, Dispatch<SetStateAction<boolean>>];
|
||||
}) => (
|
||||
<StaAlignedPoseModal
|
||||
<StayAlignedPoseModal
|
||||
open={open}
|
||||
title={'onboarding-stay_aligned-relaxed_poses-flat-title'}
|
||||
descriptionKeys={[
|
||||
@@ -136,5 +136,5 @@ export const FlatRelaxedPoseModal = ({
|
||||
width={560}
|
||||
alt="Reset position"
|
||||
/>
|
||||
</StaAlignedPoseModal>
|
||||
</StayAlignedPoseModal>
|
||||
);
|
||||
@@ -3,7 +3,6 @@ import { StayAlignedSettingsT } from 'solarxr-protocol';
|
||||
import { SettingsForm } from '@/components/settings/pages/GeneralSettings';
|
||||
import { Button } from '@/components/commons/Button';
|
||||
import { CheckBox } from '@/components/commons/Checkbox';
|
||||
import { WrenchIcon } from '@/components/commons/icon/WrenchIcons';
|
||||
import { Typography } from '@/components/commons/Typography';
|
||||
import { SettingsPagePaneLayout } from '@/components/settings/SettingsPageLayout';
|
||||
import { Localized, useLocalization } from '@fluent/react';
|
||||
@@ -17,6 +16,7 @@ import {
|
||||
StandingRelaxedPoseModal,
|
||||
} from './StayAlignedPoseModal';
|
||||
import { useState } from 'react';
|
||||
import { HorizontalAlignIcon } from '@/components/commons/icon/HorizontalAlignIcon';
|
||||
|
||||
export type StayAlignedSettingsForm = {
|
||||
enabled: boolean;
|
||||
@@ -177,7 +177,7 @@ export function StayAlignedSettings({
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsPagePaneLayout icon={<WrenchIcon />} id="stayaligned">
|
||||
<SettingsPagePaneLayout icon={<HorizontalAlignIcon />} id="stayaligned">
|
||||
<Typography variant="main-title">
|
||||
{l10n.getString('settings-stay_aligned')}
|
||||
</Typography>
|
||||
|
||||
@@ -85,7 +85,6 @@ export function TrackerSettingsPage() {
|
||||
);
|
||||
assignreq.bodyPosition = tracker?.tracker.info?.bodyPart || BodyPart.NONE;
|
||||
assignreq.trackerId = tracker?.tracker.trackerId;
|
||||
assignreq.allowDriftCompensation = false;
|
||||
sendRPCPacket(RpcMessage.AssignTrackerRequest, assignreq);
|
||||
setSelectRotation(false);
|
||||
};
|
||||
@@ -96,7 +95,6 @@ export function TrackerSettingsPage() {
|
||||
const assignreq = new AssignTrackerRequestT();
|
||||
assignreq.bodyPosition = role;
|
||||
assignreq.trackerId = tracker?.tracker.trackerId;
|
||||
assignreq.allowDriftCompensation = false;
|
||||
sendRPCPacket(RpcMessage.AssignTrackerRequest, assignreq);
|
||||
setSelectBodypart(false);
|
||||
};
|
||||
@@ -116,7 +114,6 @@ export function TrackerSettingsPage() {
|
||||
|
||||
assignreq.displayName = trackerName ?? null;
|
||||
assignreq.trackerId = tracker?.tracker.trackerId;
|
||||
assignreq.allowDriftCompensation = false;
|
||||
sendRPCPacket(RpcMessage.AssignTrackerRequest, assignreq);
|
||||
};
|
||||
|
||||
@@ -509,8 +506,7 @@ export function TrackerSettingsPage() {
|
||||
MagnetometerStatus.NOT_SUPPORTED && (
|
||||
<MagnetometerToggleSetting
|
||||
settingType="tracker"
|
||||
trackerNum={tracker.tracker.trackerId?.trackerNum}
|
||||
deviceId={tracker.tracker.trackerId?.deviceId?.id}
|
||||
trackerId={tracker.tracker.trackerId}
|
||||
/>
|
||||
)}
|
||||
<div className="flex flex-col gap-2 w-full mt-3 sentry-mask">
|
||||
|
||||
@@ -186,8 +186,8 @@ function Row({
|
||||
const warning =
|
||||
!!highlightedTrackers?.trackers.find(
|
||||
(t) =>
|
||||
t?.deviceId?.id === tracker.trackerId?.deviceId?.id &&
|
||||
t?.trackerNum === tracker.trackerId?.trackerNum
|
||||
t?.deviceId?.id === tracker.deviceId &&
|
||||
t?.trackerNum === tracker.trackerId
|
||||
) && highlightedTrackers.step;
|
||||
|
||||
return (
|
||||
@@ -376,9 +376,9 @@ export function TrackersTable({
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-y-0">
|
||||
{filteredSortedTrackers.map((data) => (
|
||||
{filteredSortedTrackers.map((data, index) => (
|
||||
<Row
|
||||
key={data.tracker.trackerId?.trackerNum}
|
||||
key={index}
|
||||
clickedTracker={clickedTracker}
|
||||
data={data}
|
||||
highlightedTrackers={highlightedTrackers}
|
||||
|
||||
@@ -6,14 +6,13 @@ import {
|
||||
} from '@/hooks/tracking-checklist';
|
||||
import classNames from 'classnames';
|
||||
import {
|
||||
ChangeSettingsRequestT,
|
||||
EnableSteamVRDriverRequestT,
|
||||
ResetType,
|
||||
RpcMessage,
|
||||
SettingsRequestT,
|
||||
SettingsResponseT,
|
||||
SteamVRTrackersSettingT,
|
||||
TrackingChecklistPublicNetworksT,
|
||||
TrackingChecklistSteamVRDisconnectedT,
|
||||
TrackingChecklistStepId,
|
||||
BodyPart, ChangeOutputTrackersSettingsRequestT, OutputTrackersSettingsResponseT, OutputTrackersSettingsRequestT,
|
||||
} from 'solarxr-protocol';
|
||||
import { ReactNode, useEffect, useMemo, useState } from 'react';
|
||||
import { CheckIcon } from '@/components/commons/icon/CheckIcon';
|
||||
@@ -28,8 +27,8 @@ import {
|
||||
ArrowDownIcon,
|
||||
ArrowRightIcon,
|
||||
} from '@/components/commons/icon/ArrowIcons';
|
||||
import { Localized } from '@fluent/react';
|
||||
import { WrenchIcon } from '@/components/commons/icon/WrenchIcons';
|
||||
import { Localized, useLocalization } from '@fluent/react';
|
||||
import { WrenchIcon } from '@/components/commons/icon/WrenchIcon';
|
||||
import { TrackingChecklistModal } from './TrackingChecklistModal';
|
||||
import { NavLink, useNavigate } from 'react-router-dom';
|
||||
import { useBreakpoint } from '@/hooks/breakpoint';
|
||||
@@ -108,39 +107,99 @@ function Step({
|
||||
);
|
||||
}
|
||||
|
||||
function SteamVRDisconnected({
|
||||
step,
|
||||
context,
|
||||
}: {
|
||||
step: TrackingChecklistStep;
|
||||
context: TrackingChecklistContext;
|
||||
}) {
|
||||
const { sendRPCPacket } = useWebsocketAPI();
|
||||
const data = step.extraData as TrackingChecklistSteamVRDisconnectedT | null;
|
||||
|
||||
const enableDriver = () => {
|
||||
sendRPCPacket(
|
||||
RpcMessage.EnableSteamVRDriverRequest,
|
||||
new EnableSteamVRDriverRequestT()
|
||||
);
|
||||
};
|
||||
|
||||
const driverNotInstalled = data?.driverInstalled === false;
|
||||
const driverBlocked = data?.driverBlockedBySafeMode === true;
|
||||
const driverDisabled = data?.driverEnabled === false;
|
||||
|
||||
const showEnableDriverButton = driverBlocked || driverDisabled;
|
||||
|
||||
const getDescriptionId = () => {
|
||||
if (driverBlocked)
|
||||
return 'tracking_checklist-STEAMVR_DISCONNECTED-driver_blocked-desc';
|
||||
if (driverDisabled)
|
||||
return 'tracking_checklist-STEAMVR_DISCONNECTED-driver_disabled-desc';
|
||||
if (driverNotInstalled)
|
||||
return 'tracking_checklist-STEAMVR_DISCONNECTED-driver_not_installed-desc';
|
||||
return 'tracking_checklist-STEAMVR_DISCONNECTED-desc';
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2.5">
|
||||
<Typography id={getDescriptionId()} />
|
||||
<div className="flex justify-between sm:items-center gap-1 flex-col sm:flex-row">
|
||||
{showEnableDriverButton && (
|
||||
<Button
|
||||
id="tracking_checklist-STEAMVR_DISCONNECTED-enable"
|
||||
variant="primary"
|
||||
onClick={enableDriver}
|
||||
/>
|
||||
)}
|
||||
{!showEnableDriverButton && !driverNotInstalled && (
|
||||
<Button
|
||||
id="tracking_checklist-STEAMVR_DISCONNECTED-open"
|
||||
variant="primary"
|
||||
onClick={() => openUrl('steam://run/250820')}
|
||||
/>
|
||||
)}
|
||||
{step.ignorable && (
|
||||
<Button
|
||||
id="tracking_checklist-ignore"
|
||||
variant="secondary"
|
||||
onClick={() => context.toggleSession(step.id)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SteamVRHandsEnabled() {
|
||||
const { sendRPCPacket, useRPCPacket } = useWebsocketAPI();
|
||||
const [steamVrTrackers, setSteamVrTrackers] = useState<Omit<
|
||||
SteamVRTrackersSettingT,
|
||||
ChangeOutputTrackersSettingsRequestT,
|
||||
'pack'
|
||||
> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT());
|
||||
sendRPCPacket(RpcMessage.OutputTrackersSettingsRequest, new OutputTrackersSettingsRequestT());
|
||||
}, []);
|
||||
|
||||
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
|
||||
if (settings.steamVrTrackers) {
|
||||
setSteamVrTrackers(settings.steamVrTrackers);
|
||||
useRPCPacket(RpcMessage.OutputTrackersSettingsResponse, (settings: OutputTrackersSettingsResponseT) => {
|
||||
if (settings.trackers) {
|
||||
setSteamVrTrackers(settings);
|
||||
}
|
||||
});
|
||||
|
||||
const disableHandTrackers = () => {
|
||||
const settings = new ChangeSettingsRequestT();
|
||||
settings.steamVrTrackers = new SteamVRTrackersSettingT(
|
||||
steamVrTrackers?.waist,
|
||||
steamVrTrackers?.chest,
|
||||
steamVrTrackers?.automaticTrackerToggle,
|
||||
steamVrTrackers?.leftFoot,
|
||||
steamVrTrackers?.rightFoot,
|
||||
steamVrTrackers?.leftKnee,
|
||||
steamVrTrackers?.rightKnee,
|
||||
steamVrTrackers?.leftElbow,
|
||||
steamVrTrackers?.rightElbow,
|
||||
false,
|
||||
false
|
||||
);
|
||||
sendRPCPacket(RpcMessage.ChangeSettingsRequest, settings);
|
||||
const req = new ChangeOutputTrackersSettingsRequestT();
|
||||
|
||||
const newTrackers = steamVrTrackers?.trackers.filter(tracker =>
|
||||
tracker != BodyPart.LEFT_HAND && tracker != BodyPart.RIGHT_HAND
|
||||
)
|
||||
if (newTrackers !== undefined) {
|
||||
req.trackers = newTrackers
|
||||
}
|
||||
req.automaticTrackerToggle = steamVrTrackers?.automaticTrackerToggle === true
|
||||
req.sendDerivedVelocity = steamVrTrackers?.sendDerivedVelocity === true
|
||||
|
||||
sendRPCPacket(RpcMessage.ChangeOutputTrackersSettingsRequest, req);
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -157,6 +216,21 @@ function SteamVRHandsEnabled() {
|
||||
);
|
||||
}
|
||||
|
||||
function StandableInstalled() {
|
||||
const { l10n } = useLocalization();
|
||||
|
||||
return (
|
||||
<div className="space-y-2.5">
|
||||
{l10n
|
||||
.getString('tracking_checklist-STANDABLE_INSTALLED-desc')
|
||||
.split('\n')
|
||||
.map((line, i) => (
|
||||
<Typography key={i}>{line}</Typography>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const stepContentLookup: Record<
|
||||
number,
|
||||
(
|
||||
@@ -219,33 +293,13 @@ const stepContentLookup: Record<
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex">
|
||||
<ResetButton type={ResetType.Full} />
|
||||
<ResetButton type={ResetType.FULL} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
[TrackingChecklistStepId.STEAMVR_DISCONNECTED]: (step, { toggleSession }) => {
|
||||
return (
|
||||
<>
|
||||
<div className="space-y-2.5">
|
||||
<Typography id="tracking_checklist-STEAMVR_DISCONNECTED-desc" />
|
||||
<div className="flex justify-between sm:items-center gap-1 flex-col sm:flex-row">
|
||||
<Button
|
||||
id="tracking_checklist-STEAMVR_DISCONNECTED-open"
|
||||
variant="primary"
|
||||
onClick={() => openUrl('steam://run/250820')}
|
||||
/>
|
||||
{step.ignorable && (
|
||||
<Button
|
||||
id="tracking_checklist-ignore"
|
||||
variant="secondary"
|
||||
onClick={() => toggleSession(step.id)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
[TrackingChecklistStepId.STEAMVR_DISCONNECTED]: (step, context) => {
|
||||
return <SteamVRDisconnected step={step} context={context} />;
|
||||
},
|
||||
[TrackingChecklistStepId.TRACKER_ERROR]: () => {
|
||||
return <Typography id="tracking_checklist-TRACKER_ERROR-desc" />;
|
||||
@@ -331,7 +385,7 @@ const stepContentLookup: Record<
|
||||
/>
|
||||
</div>
|
||||
<div className="flex justify-between sm:items-center gap-1 flex-col sm:flex-row">
|
||||
<ResetButton type={ResetType.Mounting} group="default" />
|
||||
<ResetButton type={ResetType.MOUNTING} group="default" />
|
||||
{step.ignorable && (
|
||||
<Button
|
||||
id="tracking_checklist-ignore"
|
||||
@@ -368,7 +422,7 @@ const stepContentLookup: Record<
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-between sm:items-center gap-1 flex-col sm:flex-row">
|
||||
<ResetButton type={ResetType.Mounting} group="feet" />
|
||||
<ResetButton type={ResetType.MOUNTING} group="feet" />
|
||||
{step.ignorable && (
|
||||
<Button
|
||||
id="tracking_checklist-ignore"
|
||||
@@ -410,6 +464,9 @@ const stepContentLookup: Record<
|
||||
[TrackingChecklistStepId.STEAMVR_HANDS_ENABLED]: () => {
|
||||
return <SteamVRHandsEnabled />;
|
||||
},
|
||||
[TrackingChecklistStepId.STANDABLE_INSTALLED]: () => {
|
||||
return <StandableInstalled />;
|
||||
},
|
||||
};
|
||||
|
||||
export function TrackingChecklistMobile() {
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
import { useEffect } from 'react';
|
||||
import { FieldPath, useForm } from 'react-hook-form';
|
||||
import { useConfig } from '@/hooks/config';
|
||||
import { CheckBox } from '@/components/commons/Checkbox';
|
||||
import { useLocalization } from '@fluent/react';
|
||||
|
||||
export interface DeveloperModeWidgetForm {
|
||||
highContrast: boolean;
|
||||
preciseRotation: boolean;
|
||||
fastDataFeed: boolean;
|
||||
filterSlimesAndHMD: boolean;
|
||||
sortByName: boolean;
|
||||
rawSlimeRotation: boolean;
|
||||
moreInfo: boolean;
|
||||
}
|
||||
|
||||
export const defaultValues: DeveloperModeWidgetForm = {
|
||||
highContrast: false,
|
||||
preciseRotation: false,
|
||||
fastDataFeed: false,
|
||||
filterSlimesAndHMD: false,
|
||||
sortByName: false,
|
||||
rawSlimeRotation: false,
|
||||
moreInfo: false,
|
||||
};
|
||||
|
||||
export function DeveloperModeWidget() {
|
||||
const { l10n } = useLocalization();
|
||||
const { config, setConfig } = useConfig();
|
||||
|
||||
const onSubmit = (formData: DeveloperModeWidgetForm) => {
|
||||
setConfig({ devSettings: formData });
|
||||
};
|
||||
|
||||
const { reset, control, handleSubmit, watch } =
|
||||
useForm<DeveloperModeWidgetForm>({
|
||||
defaultValues: defaultValues,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
reset(config?.devSettings || {});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const subscription = watch(() => handleSubmit(onSubmit)());
|
||||
return () => subscription.unsubscribe();
|
||||
}, []);
|
||||
|
||||
const makeToggle = ([name, label]: string[], index: number) => (
|
||||
<CheckBox
|
||||
key={index}
|
||||
control={control}
|
||||
variant="toggle"
|
||||
outlined
|
||||
name={name as FieldPath<DeveloperModeWidgetForm>}
|
||||
label={l10n.getString(`widget-developer_mode-${label}`)}
|
||||
/>
|
||||
);
|
||||
|
||||
const toggles = {
|
||||
highContrast: 'high_contrast',
|
||||
preciseRotation: 'precise_rotation',
|
||||
fastDataFeed: 'fast_data_feed',
|
||||
filterSlimesAndHMD: 'filter_slimes_and_hmd',
|
||||
sortByName: 'sort_by_name',
|
||||
rawSlimeRotation: 'raw_slime_rotation',
|
||||
moreInfo: 'more_info',
|
||||
};
|
||||
|
||||
return (
|
||||
<form className="grid grid-cols-2 w-full rounded-md gap-2">
|
||||
{Object.entries(toggles).map(makeToggle)}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -130,14 +130,18 @@ async function initializeIMUVisualizer(
|
||||
accelArrow.setLength(Math.sqrt(accelLength) * 2);
|
||||
}
|
||||
|
||||
const magVec = new Vector3(mag.x, mag.y, mag.z);
|
||||
const magVec = Vector3FromVec3fT(mag);
|
||||
const magLen = magVec.length();
|
||||
const magMag = Math.sqrt(magLen / 100);
|
||||
if (magLen > 0) {
|
||||
if (magArrow.parent === null) scene.add(magArrow);
|
||||
|
||||
const magDir = magVec.clone().normalize();
|
||||
magArrow.position.copy(magDir.clone().multiplyScalar(-magMag));
|
||||
magArrow.setDirection(magDir);
|
||||
magArrow.setLength(2 * magMag);
|
||||
} else {
|
||||
magArrow.removeFromParent();
|
||||
}
|
||||
};
|
||||
|
||||
@@ -207,9 +211,7 @@ function IMUVisualizerCanvas({
|
||||
}, [model]);
|
||||
|
||||
useEffect(() => {
|
||||
if (contextRef.current) {
|
||||
contextRef.current.update(quat, vec, mag);
|
||||
}
|
||||
contextRef.current?.update(quat, vec, mag);
|
||||
}, [quat, vec, mag]);
|
||||
|
||||
if (error) {
|
||||
@@ -232,10 +234,7 @@ function IMUVisualizerCanvas({
|
||||
export function IMUVisualizerWidget({ tracker }: { tracker: TrackerDataT }) {
|
||||
const { l10n } = useLocalization();
|
||||
const [enabled, setEnabled] = useState(false);
|
||||
const isExtension = useMemo(
|
||||
() => (tracker.trackerId?.trackerNum ?? 0) > 0,
|
||||
[tracker]
|
||||
);
|
||||
const isExtension = false // TODO Do we want to display extensions?
|
||||
|
||||
useEffect(() => {
|
||||
const state = localStorage.getItem('modelPreview');
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
import { useLocalization } from '@fluent/react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { KeyValuesT, MessageT, Payload, Topic } from 'solarxr-protocol';
|
||||
import {
|
||||
OVERLAY_DISPLAY_SETTINGS_TOPIC,
|
||||
PayloadData,
|
||||
usePubSub,
|
||||
} from '@/hooks/pubSub';
|
||||
import { CheckBox } from '@/components/commons/Checkbox';
|
||||
import { Typography } from '@/components/commons/Typography';
|
||||
|
||||
export function OverlayWidget() {
|
||||
const { l10n } = useLocalization();
|
||||
const { publish, subscribe, keyValues } = usePubSub();
|
||||
const [loading, setLoading] = useState(true);
|
||||
const { reset, control, handleSubmit, watch } = useForm<{
|
||||
isVisible: boolean;
|
||||
isMirrored: boolean;
|
||||
}>({
|
||||
defaultValues: {
|
||||
isVisible: false,
|
||||
isMirrored: false,
|
||||
},
|
||||
});
|
||||
|
||||
subscribe(
|
||||
OVERLAY_DISPLAY_SETTINGS_TOPIC,
|
||||
(payload: PayloadData, type: Payload) => {
|
||||
setLoading(false);
|
||||
if (type !== Payload.KeyValues) throw new Error('Invalid payload');
|
||||
const obj = keyValues(payload);
|
||||
reset({
|
||||
isMirrored: obj['is_mirrored'] === 'true',
|
||||
isVisible: obj['is_visible'] === 'true',
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const message = new MessageT();
|
||||
message.topic = OVERLAY_DISPLAY_SETTINGS_TOPIC;
|
||||
message.topicType = Topic.TopicId;
|
||||
message.payloadType = Payload.NONE;
|
||||
publish(message);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const subscription = watch(() => handleSubmit(onSubmit)());
|
||||
return () => subscription.unsubscribe();
|
||||
}, []);
|
||||
|
||||
const onSubmit = (val: { isVisible: boolean; isMirrored: boolean }) => {
|
||||
const message = new MessageT();
|
||||
|
||||
message.topic = OVERLAY_DISPLAY_SETTINGS_TOPIC;
|
||||
message.topicType = Topic.TopicId;
|
||||
|
||||
message.payloadType = Payload.KeyValues;
|
||||
const keyValues = new KeyValuesT();
|
||||
keyValues.keys = ['is_mirrored', 'is_visible'];
|
||||
keyValues.values = [`${val.isMirrored}`, `${val.isVisible}`];
|
||||
message.payload = keyValues;
|
||||
|
||||
publish(message);
|
||||
};
|
||||
|
||||
return !loading ? (
|
||||
<form className="bg-background-60 flex flex-col w-full rounded-md px-2">
|
||||
<div className="mt-2 px-1">
|
||||
<Typography>{l10n.getString('widget-overlay')}</Typography>
|
||||
</div>
|
||||
<CheckBox
|
||||
control={control}
|
||||
name="isVisible"
|
||||
variant="toggle"
|
||||
label={l10n.getString('widget-overlay-is_visible_label')}
|
||||
/>
|
||||
<CheckBox
|
||||
control={control}
|
||||
name="isMirrored"
|
||||
variant="toggle"
|
||||
label={l10n.getString('widget-overlay-is_mirrored_label')}
|
||||
/>
|
||||
</form>
|
||||
) : (
|
||||
<></>
|
||||
);
|
||||
}
|
||||
@@ -16,7 +16,7 @@ import { getSentryOrCompute, updateSentryContext } from '@/utils/sentry';
|
||||
import { fetchCurrentFirmwareRelease, FirmwareRelease } from './firmware-update';
|
||||
import { DEFAULT_LOCALE, LangContext } from '@/i18n/config';
|
||||
|
||||
const isSteam = await window.electronAPI.isSteam();
|
||||
const isSteam = window.electronAPI ? await window.electronAPI.isSteam() : false;
|
||||
|
||||
export interface AppContext {
|
||||
currentFirmwareRelease: FirmwareRelease | null;
|
||||
|
||||
+21
-5
@@ -1,8 +1,4 @@
|
||||
import { createContext, useContext, useState } from 'react';
|
||||
import {
|
||||
defaultValues as defaultDevSettings,
|
||||
DeveloperModeWidgetForm,
|
||||
} from '@/components/widgets/DeveloperModeWidget';
|
||||
import { error } from '@/utils/logging';
|
||||
import { useDebouncedEffect } from './timeout';
|
||||
import { waitUntil } from '@/utils/a11y';
|
||||
@@ -25,13 +21,33 @@ export enum AssignMode {
|
||||
All = 'all',
|
||||
}
|
||||
|
||||
export interface DeveloperModeConfig {
|
||||
highContrast: boolean;
|
||||
preciseRotation: boolean;
|
||||
fastDataFeed: boolean;
|
||||
filterSlimesAndHMD: boolean;
|
||||
sortByName: boolean;
|
||||
rawSlimeRotation: boolean;
|
||||
moreInfo: boolean;
|
||||
}
|
||||
|
||||
export const defaultDevSettings: DeveloperModeConfig = {
|
||||
highContrast: false,
|
||||
preciseRotation: false,
|
||||
fastDataFeed: false,
|
||||
filterSlimesAndHMD: false,
|
||||
sortByName: false,
|
||||
rawSlimeRotation: false,
|
||||
moreInfo: false,
|
||||
};
|
||||
|
||||
export interface Config {
|
||||
uuid: string;
|
||||
debug: boolean;
|
||||
lang: string;
|
||||
doneOnboarding: boolean;
|
||||
watchNewDevices: boolean;
|
||||
devSettings: DeveloperModeWidgetForm;
|
||||
devSettings: DeveloperModeConfig;
|
||||
feedbackSound: boolean;
|
||||
feedbackSoundVolume: number;
|
||||
connectedTrackersWarning: boolean;
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import {
|
||||
SkeletonConfigResponseT,
|
||||
SkeletonBone,
|
||||
RpcMessage,
|
||||
SkeletonConfigRequestT,
|
||||
ChangeSkeletonConfigRequestT,
|
||||
ChangeSkeletonProportionsRequestT,
|
||||
SkeletonProportionsRequestT,
|
||||
SkeletonProportionsResponseT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useWebsocketAPI } from './websocket-api';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
@@ -60,7 +60,7 @@ export function useManualProportions({ type }: { type: 'linear' | 'ratio' }): {
|
||||
const { useRPCPacket, sendRPCPacket } = useWebsocketAPI();
|
||||
const { setConfig } = useConfig();
|
||||
const [skeleton, setSkeleton] = useState<Omit<
|
||||
SkeletonConfigResponseT,
|
||||
SkeletonProportionsResponseT,
|
||||
'pack'
|
||||
> | null>(null);
|
||||
const bodyPartsGrouped: Label[] = useMemo(() => {
|
||||
@@ -121,12 +121,12 @@ export function useManualProportions({ type }: { type: 'linear' | 'ratio' }): {
|
||||
];
|
||||
}, [skeleton, type]);
|
||||
|
||||
useRPCPacket(RpcMessage.SkeletonConfigResponse, (data: SkeletonConfigResponseT) => {
|
||||
useRPCPacket(RpcMessage.SkeletonProportionsResponse, (data: SkeletonProportionsResponseT) => {
|
||||
setSkeleton(data);
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
sendRPCPacket(RpcMessage.SkeletonConfigRequest, new SkeletonConfigRequestT());
|
||||
sendRPCPacket(RpcMessage.SkeletonProportionsRequest, new SkeletonProportionsRequestT());
|
||||
}, []);
|
||||
|
||||
return {
|
||||
@@ -144,8 +144,8 @@ export function useManualProportions({ type }: { type: 'linear' | 'ratio' }): {
|
||||
if (!currentValue) throw 'invalid state - the bone should exists';
|
||||
const currentRatio = currentValue.value / oldGroupTotal;
|
||||
sendRPCPacket(
|
||||
RpcMessage.ChangeSkeletonConfigRequest,
|
||||
new ChangeSkeletonConfigRequestT(part, params.newValue * currentRatio)
|
||||
RpcMessage.ChangeSkeletonProportionsRequest,
|
||||
new ChangeSkeletonProportionsRequestT(part, params.newValue * currentRatio)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -164,8 +164,8 @@ export function useManualProportions({ type }: { type: 'linear' | 'ratio' }): {
|
||||
newValue = 0;
|
||||
|
||||
sendRPCPacket(
|
||||
RpcMessage.ChangeSkeletonConfigRequest,
|
||||
new ChangeSkeletonConfigRequestT(params.bone, newValue)
|
||||
RpcMessage.ChangeSkeletonProportionsRequest,
|
||||
new ChangeSkeletonProportionsRequestT(params.bone, newValue)
|
||||
);
|
||||
|
||||
// Update percent from other bones ratios so the total stays 100%
|
||||
@@ -177,8 +177,8 @@ export function useManualProportions({ type }: { type: 'linear' | 'ratio' }): {
|
||||
const currentValue = skeleton.skeletonParts.find(({ bone }) => bone === part);
|
||||
if (!currentValue) throw 'invalid state - the bone should exists';
|
||||
sendRPCPacket(
|
||||
RpcMessage.ChangeSkeletonConfigRequest,
|
||||
new ChangeSkeletonConfigRequestT(
|
||||
RpcMessage.ChangeSkeletonProportionsRequest,
|
||||
new ChangeSkeletonProportionsRequestT(
|
||||
part,
|
||||
currentValue.value - (diffValue / (group.length - 1)) * signDiff
|
||||
)
|
||||
@@ -188,11 +188,11 @@ export function useManualProportions({ type }: { type: 'linear' | 'ratio' }): {
|
||||
|
||||
if (params.type === 'bone') {
|
||||
sendRPCPacket(
|
||||
RpcMessage.ChangeSkeletonConfigRequest,
|
||||
new ChangeSkeletonConfigRequestT(params.bone, params.newValue)
|
||||
RpcMessage.ChangeSkeletonProportionsRequest,
|
||||
new ChangeSkeletonProportionsRequestT(params.bone, params.newValue)
|
||||
);
|
||||
}
|
||||
sendRPCPacket(RpcMessage.SkeletonConfigRequest, new SkeletonConfigRequestT());
|
||||
sendRPCPacket(RpcMessage.SkeletonProportionsRequest, new SkeletonProportionsRequestT());
|
||||
setConfig({ lastUsedProportions: 'manual' });
|
||||
Sentry.metrics.count('manual_proportions_change', 1, { attributes: params });
|
||||
},
|
||||
|
||||
+13
-12
@@ -11,15 +11,16 @@ import { useLocation } from 'react-router-dom';
|
||||
import { useConfig } from './config';
|
||||
import { useWebsocketAPI } from './websocket-api';
|
||||
import {
|
||||
ChangeResetsSettingsRequestT,
|
||||
ChangeSettingsRequestT,
|
||||
ModelSettingsT,
|
||||
ModelTogglesT,
|
||||
OSCSettingsT,
|
||||
ResetsSettingsT,
|
||||
RpcMessage,
|
||||
SettingsRequestT,
|
||||
SettingsResponseT,
|
||||
SkeletonBone,
|
||||
VRCOSCSettingsRequestT,
|
||||
VRCOSCSettingsT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useManualProportions } from './manual-proportions';
|
||||
@@ -80,6 +81,7 @@ export function useProvideOnboarding() {
|
||||
|
||||
const { state: locatioState } = useLocation();
|
||||
const [settings, setSettings] = useState<SettingsResponseT>();
|
||||
const [vrcOscSettings, setVrcOscSettings] = useState<VRCOSCSettingsT>();
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const { alonePage = false }: { alonePage?: boolean } = (locatioState as any) || {};
|
||||
@@ -90,11 +92,15 @@ export function useProvideOnboarding() {
|
||||
|
||||
useEffect(() => {
|
||||
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsRequestT());
|
||||
sendRPCPacket(RpcMessage.VRCOSCSettingsRequest, new VRCOSCSettingsRequestT());
|
||||
}, []);
|
||||
|
||||
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
|
||||
setSettings(settings);
|
||||
});
|
||||
useRPCPacket(RpcMessage.VRCOSCSettingsResponse, (settings: VRCOSCSettingsT) => {
|
||||
setVrcOscSettings(settings);
|
||||
});
|
||||
|
||||
const { changeBoneValue } = useManualProportions({
|
||||
type: 'linear',
|
||||
@@ -102,10 +108,8 @@ export function useProvideOnboarding() {
|
||||
|
||||
const onboardingEnded = () => {
|
||||
setConfig({ doneOnboarding: true });
|
||||
if (!settings?.modelSettings || !settings?.vrcOsc) return;
|
||||
const req = new ChangeSettingsRequestT();
|
||||
if (!settings?.modelSettings || !vrcOscSettings) return;
|
||||
const modelSettings = new ModelSettingsT();
|
||||
const oscSettings = new VRCOSCSettingsT();
|
||||
|
||||
const mocap = usage === 'mocap' || usage === 'vtubing';
|
||||
|
||||
@@ -114,16 +118,13 @@ export function useProvideOnboarding() {
|
||||
modelSettings.toggles = toggles;
|
||||
req.modelSettings = modelSettings;
|
||||
|
||||
const resets = Object.assign(new ResetsSettingsT(), settings.resetsSettings);
|
||||
resets.resetHmdPitch = mocapPos === 'forehead';
|
||||
req.resetsSettings = resets;
|
||||
const resetsReq = Object.assign(new ChangeResetsSettingsRequestT(), settings.resetsSettings); // TODO
|
||||
resetsReq.resetHmdPitch = mocapPos === 'forehead';
|
||||
sendRPCPacket(RpcMessage.ChangeResetsSettingsRequest, resetsReq);
|
||||
|
||||
const osc = Object.assign(new OSCSettingsT(), settings.vrcOsc.oscSettings);
|
||||
const osc = Object.assign(new VRCOSCSettingsT(), vrcOscSettings);
|
||||
osc.enabled = vrcOsc ?? false;
|
||||
oscSettings.oscSettings = osc;
|
||||
req.vrcOsc = oscSettings;
|
||||
|
||||
sendRPCPacket(RpcMessage.ChangeSettingsRequest, req);
|
||||
sendRPCPacket(RpcMessage.ChangeVRCOSCSettingsRequest, osc);
|
||||
|
||||
if (mocap) {
|
||||
changeBoneValue({ bone: SkeletonBone.HAND_Z, type: 'bone', newValue: 0 });
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import { useLocalization } from '@fluent/react';
|
||||
import { number, object, boolean, string } from 'yup';
|
||||
|
||||
export type OSCSettings = {
|
||||
enabled: boolean;
|
||||
export type OSCPortsAddress = {
|
||||
portIn: number;
|
||||
portOut: number;
|
||||
address: string;
|
||||
};
|
||||
|
||||
export function useOscSettingsValidator() {
|
||||
export function useOscPortsAddressValidator() {
|
||||
const bannedPorts = [6969, 21110];
|
||||
const { l10n } = useLocalization();
|
||||
|
||||
@@ -17,7 +16,7 @@ export function useOscSettingsValidator() {
|
||||
.required()
|
||||
.test(
|
||||
'ports-dont-match',
|
||||
l10n.getString('settings-osc-common-network-ports_match_error'),
|
||||
l10n.getString('settings-osc-common-network-ports_match_error-v2'),
|
||||
(port, context) => context.parent.portIn != context.parent.portOut
|
||||
)
|
||||
.notOneOf(bannedPorts, (context) =>
|
||||
@@ -27,7 +26,6 @@ export function useOscSettingsValidator() {
|
||||
);
|
||||
|
||||
const oscValidator = object({
|
||||
enabled: boolean().required(),
|
||||
portIn: portValidator,
|
||||
portOut: portValidator,
|
||||
address: string()
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import {
|
||||
KeyValuesT,
|
||||
MessageT,
|
||||
PubSubUnion,
|
||||
SubscriptionRequestT,
|
||||
Topic,
|
||||
TopicHandleT,
|
||||
TopicIdT,
|
||||
TopicMappingT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useWebsocketAPI } from './websocket-api';
|
||||
|
||||
export type PayloadData = MessageT['payload'];
|
||||
export type PayloadType = MessageT['payloadType'];
|
||||
|
||||
export function usePubSub() {
|
||||
const { sendPubSubPacket, usePubSubPacket } = useWebsocketAPI();
|
||||
const [handleTopics, setHandleTopics] = useState<{ [key: number]: TopicIdT }>({});
|
||||
|
||||
const subscribe = (
|
||||
topicId: TopicIdT,
|
||||
callback: (data: PayloadData, type: PayloadType) => void
|
||||
): void => {
|
||||
useEffect(() => {
|
||||
const subRequest = new SubscriptionRequestT();
|
||||
subRequest.topicType = Topic.TopicId;
|
||||
subRequest.topic = topicId;
|
||||
sendPubSubPacket(PubSubUnion.SubscriptionRequest, subRequest);
|
||||
}, [sendPubSubPacket, usePubSubPacket]);
|
||||
|
||||
usePubSubPacket(PubSubUnion.Message, (message: MessageT) => {
|
||||
if (message.topicType == Topic.TopicHandle) {
|
||||
const messageHandleId = message.topic as TopicHandleT;
|
||||
if (handleTopics[messageHandleId.id]) {
|
||||
callback(message.payload, message.payloadType);
|
||||
}
|
||||
}
|
||||
if (message.topicType == Topic.TopicId) {
|
||||
const messageTopicId = message.topic as TopicIdT;
|
||||
if (
|
||||
messageTopicId.appName === topicId.appName &&
|
||||
messageTopicId.organization === topicId.organization &&
|
||||
messageTopicId.topic === topicId.topic
|
||||
) {
|
||||
callback(message.payload, message.payloadType);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
usePubSubPacket(PubSubUnion.TopicMapping, (data: TopicMappingT) => {
|
||||
setHandleTopics((handleTopics) => ({
|
||||
...handleTopics,
|
||||
...(data.handle?.id && data.id ? { [data.handle?.id]: data.id } : {}),
|
||||
}));
|
||||
});
|
||||
|
||||
const publish = (message: MessageT) => {
|
||||
sendPubSubPacket(PubSubUnion.Message, message);
|
||||
};
|
||||
|
||||
return {
|
||||
subscribe,
|
||||
publish,
|
||||
keyValues: (payload: PayloadData): Record<string, string> => {
|
||||
const keyValuesPayload = payload as KeyValuesT;
|
||||
return keyValuesPayload.keys.reduce(
|
||||
(curr, _, index) => ({
|
||||
...curr,
|
||||
[keyValuesPayload.keys[index]]: keyValuesPayload.values[index],
|
||||
}),
|
||||
{}
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const topic = ({ appName, organization, topic }: Omit<TopicIdT, 'pack'>) =>
|
||||
Object.assign(new TopicIdT(), { appName, organization, topic });
|
||||
|
||||
export const OVERLAY_DISPLAY_SETTINGS_TOPIC = topic({
|
||||
appName: 'overlay',
|
||||
organization: 'slimevr.dev',
|
||||
topic: 'display_settings',
|
||||
});
|
||||
@@ -1,16 +1,14 @@
|
||||
import {
|
||||
ChangeSettingsRequestT,
|
||||
ResetsSettingsT,
|
||||
ResetsSettingsResponseT,
|
||||
RpcMessage,
|
||||
SettingsResetRequestT,
|
||||
SettingsResponseT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useWebsocketAPI } from './websocket-api';
|
||||
import { useEffect, useState } from 'react';
|
||||
import {useWebsocketAPI} from './websocket-api';
|
||||
import {useEffect, useState} from 'react';
|
||||
|
||||
export interface ResetSettingsForm {
|
||||
resetMountingFeet: boolean;
|
||||
armsMountingResetMode: number;
|
||||
armsResetMode: number;
|
||||
yawResetSmoothTime: number;
|
||||
saveMountingReset: boolean;
|
||||
resetHmdPitch: boolean;
|
||||
@@ -18,16 +16,16 @@ export interface ResetSettingsForm {
|
||||
|
||||
export const defaultResetSettings = {
|
||||
resetMountingFeet: false,
|
||||
armsMountingResetMode: 0,
|
||||
armsResetMode: 0,
|
||||
yawResetSmoothTime: 0.0,
|
||||
saveMountingReset: false,
|
||||
resetHmdPitch: false,
|
||||
};
|
||||
|
||||
export function loadResetSettings(resetSettingsForm: ResetSettingsForm) {
|
||||
const resetsSettings = new ResetsSettingsT();
|
||||
const resetsSettings = new ResetsSettingsResponseT();
|
||||
resetsSettings.resetMountingFeet = resetSettingsForm.resetMountingFeet;
|
||||
resetsSettings.armsMountingResetMode = resetSettingsForm.armsMountingResetMode;
|
||||
resetsSettings.armsResetMode = resetSettingsForm.armsResetMode;
|
||||
resetsSettings.yawResetSmoothTime = resetSettingsForm.yawResetSmoothTime;
|
||||
resetsSettings.saveMountingReset = resetSettingsForm.saveMountingReset;
|
||||
resetsSettings.resetHmdPitch = resetSettingsForm.resetHmdPitch;
|
||||
@@ -40,19 +38,17 @@ export function useResetSettings() {
|
||||
const [settings, setSettings] = useState<ResetSettingsForm>(defaultResetSettings);
|
||||
|
||||
useEffect(() =>
|
||||
sendRPCPacket(RpcMessage.SettingsRequest, new SettingsResetRequestT())
|
||||
sendRPCPacket(RpcMessage.ResetsSettingsRequest, new SettingsResetRequestT())
|
||||
);
|
||||
|
||||
useRPCPacket(RpcMessage.SettingsResponse, (settings: SettingsResponseT) => {
|
||||
if (settings.resetsSettings) setSettings(settings.resetsSettings);
|
||||
useRPCPacket(RpcMessage.ResetsSettingsResponse, (settings: ResetsSettingsResponseT) => {
|
||||
if (settings) setSettings(settings);
|
||||
});
|
||||
|
||||
return {
|
||||
update: (resetSettingsForm: Partial<ResetSettingsForm>) => {
|
||||
const req = new ChangeSettingsRequestT();
|
||||
const res = loadResetSettings({ ...settings, ...resetSettingsForm });
|
||||
req.resetsSettings = res;
|
||||
sendRPCPacket(RpcMessage.ChangeSettingsRequest, req);
|
||||
const req = loadResetSettings({...settings, ...resetSettingsForm});
|
||||
sendRPCPacket(RpcMessage.ChangeResetsSettingsRequest, req);
|
||||
},
|
||||
};
|
||||
}
|
||||
+22
-11
@@ -18,8 +18,8 @@ export type ResetBtnStatus = 'idle' | 'counting' | 'finished';
|
||||
|
||||
export type MountingResetGroup = 'default' | 'feet' | 'fingers';
|
||||
export type UseResetOptions =
|
||||
| { type: ResetType.Full | ResetType.Yaw }
|
||||
| { type: ResetType.Mounting; group: MountingResetGroup };
|
||||
| { type: ResetType.FULL | ResetType.YAW }
|
||||
| { type: ResetType.MOUNTING; group: MountingResetGroup };
|
||||
|
||||
export const BODY_PARTS_GROUPS: Record<MountingResetGroup, BodyPart[]> = {
|
||||
default: [],
|
||||
@@ -32,7 +32,7 @@ export function useReset(
|
||||
onReseted?: () => void,
|
||||
onFailed?: () => void
|
||||
) {
|
||||
if (options.type === ResetType.Mounting && !options.group) options.group = 'default';
|
||||
if (options.type === ResetType.MOUNTING && !options.group) options.group = 'default';
|
||||
|
||||
const serverGuards = useAtomValue(serverGuardsAtom);
|
||||
const { currentLocales } = useLocaleConfig();
|
||||
@@ -48,12 +48,23 @@ export function useReset(
|
||||
const req = new ResetRequestT();
|
||||
req.resetType = options.type;
|
||||
req.bodyParts = parts;
|
||||
switch (options.type) {
|
||||
case ResetType.YAW:
|
||||
req.delay = 0;
|
||||
break;
|
||||
case ResetType.FULL:
|
||||
req.delay = 3;
|
||||
break;
|
||||
case ResetType.MOUNTING:
|
||||
req.delay = 3;
|
||||
break;
|
||||
}
|
||||
sendRPCPacket(RpcMessage.ResetRequest, req);
|
||||
|
||||
Sentry.metrics.count('reset_click', 1, {
|
||||
attributes: {
|
||||
resetType: ResetType[options.type],
|
||||
group: options.type === ResetType.Mounting ? options.group : undefined,
|
||||
group: options.type === ResetType.MOUNTING ? options.group : undefined,
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -91,7 +102,7 @@ export function useReset(
|
||||
({ status, resetType, progress, duration, bodyParts }: ResetResponseT) => {
|
||||
if (
|
||||
resetType !== options.type ||
|
||||
(resetType == ResetType.Mounting &&
|
||||
(resetType == ResetType.MOUNTING &&
|
||||
JSON.stringify(parts) !== JSON.stringify(bodyParts))
|
||||
) {
|
||||
onResetCanceled();
|
||||
@@ -113,11 +124,11 @@ export function useReset(
|
||||
|
||||
const name = useMemo(() => {
|
||||
switch (options.type) {
|
||||
case ResetType.Yaw:
|
||||
case ResetType.YAW:
|
||||
return 'reset-yaw';
|
||||
case ResetType.Full:
|
||||
case ResetType.FULL:
|
||||
return 'reset-full';
|
||||
case ResetType.Mounting:
|
||||
case ResetType.MOUNTING:
|
||||
if (options.group !== 'default') return `reset-mounting-${options.group}`;
|
||||
return 'reset-mounting';
|
||||
default:
|
||||
@@ -127,7 +138,7 @@ export function useReset(
|
||||
|
||||
let disabled = status === 'counting';
|
||||
let error = null;
|
||||
if (options.type === ResetType.Mounting && options.group !== 'default') {
|
||||
if (options.type === ResetType.MOUNTING && options.group !== 'default') {
|
||||
const assignedTrackers = useAtomValue(assignedTrackersAtom);
|
||||
|
||||
if (
|
||||
@@ -140,10 +151,10 @@ export function useReset(
|
||||
disabled = true;
|
||||
error = `reset-error-no_${options.group}_tracker`;
|
||||
}
|
||||
} else if (options.type === ResetType.Mounting && !serverGuards?.canDoMounting) {
|
||||
} else if (options.type === ResetType.MOUNTING && !serverGuards?.canDoMountingReset) {
|
||||
disabled = true;
|
||||
error = 'reset-error-mounting-need_full_reset';
|
||||
} else if (options.type === ResetType.Yaw && !serverGuards?.canDoYawReset) {
|
||||
} else if (options.type === ResetType.YAW && !serverGuards?.canDoYawReset) {
|
||||
disabled = true;
|
||||
error = 'reset-error-yaw-need_full_reset';
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
TrackingChecklistStepVisibility,
|
||||
IgnoreTrackingChecklistStepRequestT,
|
||||
RpcMessage,
|
||||
TrackerIdT,
|
||||
} from 'solarxr-protocol';
|
||||
import { useWebsocketAPI } from './websocket-api';
|
||||
import { createContext, useContext, useEffect, useMemo, useState } from 'react';
|
||||
@@ -47,7 +46,7 @@ export type TrackingChecklistStep = TrackingChecklistStepT & {
|
||||
};
|
||||
export type highlightedTrackers = {
|
||||
step: TrackingChecklistStep;
|
||||
trackers: Array<TrackerIdT>;
|
||||
trackers: Array<number>;
|
||||
};
|
||||
|
||||
const stepVisibility = ({ visibility, status, firstRequired }: TrackingChecklistStep) =>
|
||||
|
||||
@@ -5,8 +5,6 @@ import {
|
||||
DataFeedMessageHeaderT,
|
||||
MessageBundle,
|
||||
MessageBundleT,
|
||||
PubSubHeaderT,
|
||||
PubSubUnion,
|
||||
RpcMessage,
|
||||
RpcMessageHeaderT,
|
||||
} from 'solarxr-protocol';
|
||||
@@ -24,22 +22,17 @@ export interface WebSocketApi {
|
||||
useDataFeedPacket: <T>(type: DataFeedMessage, callback: (packet: T) => void) => void;
|
||||
sendRPCPacket: (type: RpcMessage, data: RPCPacketType) => void;
|
||||
sendDataFeedPacket: (type: DataFeedMessage, data: DataFeedPacketType) => void;
|
||||
usePubSubPacket: <T>(type: PubSubUnion, callback: (packet: T) => void) => void;
|
||||
sendPubSubPacket: (type: PubSubUnion, data: PubSubPacketType) => void;
|
||||
}
|
||||
|
||||
export const WebSocketApiContext = createContext<WebSocketApi>(undefined as never);
|
||||
|
||||
export type RPCPacketType = RpcMessageHeaderT['message'];
|
||||
export type PubSubPacketType = PubSubHeaderT['u'];
|
||||
export type DataFeedPacketType = DataFeedMessageHeaderT['message'];
|
||||
// export type OutboundPacketType = OutboundPacketT['packet'];
|
||||
|
||||
export function useProvideWebsocketApi(): WebSocketApi {
|
||||
const rpcPacketCounterRef = useRef<number>(0);
|
||||
const webSocketRef = useRef<WebSocket | null>(null);
|
||||
const rpclistenerRef = useRef<EventTarget>(new EventTarget());
|
||||
const pubsublistenerRef = useRef<EventTarget>(new EventTarget());
|
||||
const datafeedlistenerRef = useRef<EventTarget>(new EventTarget());
|
||||
const [isFirstConnection, setFirstConnection] = useState(true);
|
||||
const [timedOut, setTimedOut] = useState(false);
|
||||
@@ -91,14 +84,6 @@ export function useProvideWebsocketApi(): WebSocketApi {
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
message.pubSubMsgs.forEach((pubSubHeader) => {
|
||||
pubsublistenerRef.current?.dispatchEvent(
|
||||
new CustomEvent(PubSubUnion[pubSubHeader.uType], {
|
||||
detail: pubSubHeader.u,
|
||||
})
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const sendRPCPacket = (type: RpcMessage, data: RPCPacketType): void => {
|
||||
@@ -138,22 +123,6 @@ export function useProvideWebsocketApi(): WebSocketApi {
|
||||
webSocketRef.current.send(fbb.asUint8Array());
|
||||
};
|
||||
|
||||
const sendPubSubPacket = (type: PubSubUnion, data: PubSubPacketType): void => {
|
||||
if (webSocketRef?.current?.readyState !== WebSocket.OPEN) return;
|
||||
const fbb = new Builder(1);
|
||||
|
||||
const message = new MessageBundleT();
|
||||
|
||||
const pubSubHeader = new PubSubHeaderT();
|
||||
pubSubHeader.uType = type;
|
||||
pubSubHeader.u = data;
|
||||
|
||||
message.pubSubMsgs = [pubSubHeader];
|
||||
fbb.finish(message.pack(fbb));
|
||||
|
||||
webSocketRef.current.send(fbb.asUint8Array());
|
||||
};
|
||||
|
||||
const connect = () => {
|
||||
webSocketRef.current = new WebSocket(`ws://${targetIp}:${targetPort}`);
|
||||
|
||||
@@ -222,20 +191,8 @@ export function useProvideWebsocketApi(): WebSocketApi {
|
||||
};
|
||||
}, [callback, type]);
|
||||
},
|
||||
usePubSubPacket: <T>(type: PubSubUnion, callback: (packet: T) => void) => {
|
||||
useEffect(() => {
|
||||
const onEvent = (event: CustomEventInit) => {
|
||||
callback(event.detail);
|
||||
};
|
||||
pubsublistenerRef.current.addEventListener(PubSubUnion[type], onEvent);
|
||||
return () => {
|
||||
pubsublistenerRef.current.removeEventListener(PubSubUnion[type], onEvent);
|
||||
};
|
||||
}, [callback, type]);
|
||||
},
|
||||
sendRPCPacket,
|
||||
sendDataFeedPacket,
|
||||
sendPubSubPacket,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -426,3 +426,10 @@ div {
|
||||
[data-electron-drag-region='true'] {
|
||||
-webkit-app-region: drag;
|
||||
}
|
||||
|
||||
a,
|
||||
.no-user-drag {
|
||||
-webkit-user-drag: none;
|
||||
-webkit-user-select: none;
|
||||
user-select: none;
|
||||
}
|
||||
@@ -23,7 +23,7 @@ const resetSounds: Record<
|
||||
mew: HTMLAudioElement | null;
|
||||
}
|
||||
> = {
|
||||
[ResetType.Full]: {
|
||||
[ResetType.FULL]: {
|
||||
initial: createAudio('/sounds/full-reset/init-full-reset-with-tail.ogg'),
|
||||
tick: [
|
||||
createAudio('/sounds/full-reset/full-click-1.ogg'),
|
||||
@@ -33,13 +33,13 @@ const resetSounds: Record<
|
||||
end: createAudio('/sounds/full-reset/end-full-reset-with-tail.ogg'),
|
||||
mew,
|
||||
},
|
||||
[ResetType.Yaw]: {
|
||||
[ResetType.YAW]: {
|
||||
initial: null,
|
||||
tick: null,
|
||||
end: createAudio('/sounds/yaw-reset/yaw-reset.ogg'),
|
||||
mew: null,
|
||||
},
|
||||
[ResetType.Mounting]: {
|
||||
[ResetType.MOUNTING]: {
|
||||
initial: createAudio('/sounds/mounting-reset/init-mounting-reset-with-tail.ogg'),
|
||||
tick: [
|
||||
createAudio('/sounds/mounting-reset/mount-click-1.ogg'),
|
||||
|
||||
@@ -99,8 +99,8 @@ export const trackerFromIdAtom = ({
|
||||
({ tracker }) =>
|
||||
trackerNum &&
|
||||
deviceId &&
|
||||
tracker?.trackerId?.trackerNum == trackerNum &&
|
||||
tracker?.trackerId?.deviceId?.id == deviceId
|
||||
tracker?.trackerId == trackerNum &&
|
||||
tracker?.deviceId == deviceId
|
||||
)
|
||||
),
|
||||
(a) => a,
|
||||
|
||||
@@ -68,7 +68,7 @@ export function getSentryOrCompute(enabled = false, uuid: string, isSteam: boole
|
||||
});
|
||||
|
||||
if (!newClient) {
|
||||
error('Couldnt initialize Sentry for error logging');
|
||||
error('Couldn\'t initialize Sentry for error logging');
|
||||
} else {
|
||||
log('Initialized the Sentry client');
|
||||
}
|
||||
@@ -77,15 +77,15 @@ export function getSentryOrCompute(enabled = false, uuid: string, isSteam: boole
|
||||
}
|
||||
|
||||
export function updateSentryContext(devices: DeviceDataT[]) {
|
||||
// We filter out the shit we dont want. We dont need rotation data or ip addresses
|
||||
// We filter out what we don't want (rotations and ip addresses).
|
||||
const trackers = (devices || []).map(({ hardwareInfo, trackers, id }) => ({
|
||||
id: id?.id,
|
||||
id: id,
|
||||
hardwareInfo: { ...hardwareInfo, ipAddress: undefined },
|
||||
trackers: trackers.map(({ info, trackerId }) => ({
|
||||
trackers: trackers.map(({ info, trackerId, deviceId }) => ({
|
||||
info,
|
||||
trackerId: {
|
||||
trackerNum: trackerId?.trackerNum,
|
||||
deviceId: trackerId?.deviceId?.id,
|
||||
trackerNum: trackerId,
|
||||
deviceId: deviceId,
|
||||
},
|
||||
})),
|
||||
}));
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@ import path from 'path';
|
||||
import { visualizer } from 'rollup-plugin-visualizer';
|
||||
import jotaiReactRefresh from 'jotai/babel/plugin-react-refresh';
|
||||
|
||||
const commitHash = execSync('git rev-parse --verify --short HEAD').toString().trim();
|
||||
const commitHash = execSync('git rev-parse --verify --short=8 HEAD').toString().trim();
|
||||
const versionTag = execSync('git --no-pager tag --sort -taggerdate --points-at HEAD')
|
||||
.toString()
|
||||
.split('\n')[0]
|
||||
|
||||
Generated
+253
-472
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,534 @@
|
||||
# SlimeVR Server Architecture
|
||||
|
||||
This document explains how the server is structured, why it's structured that way, and how to extend it correctly.
|
||||
|
||||
---
|
||||
|
||||
## Mental Model
|
||||
|
||||
Every significant part of the server a tracker, a UDP connection, a SolarXR session, a config file is a **module**. Every module is a list of behaviours sharing one context:
|
||||
|
||||

|
||||
|
||||
That's the entire system. Everything else is an application of this pattern.
|
||||
|
||||
---
|
||||
|
||||
## Why This Pattern
|
||||
|
||||
The server handles many concurrent connections, each with independent state that many other components need to observe. A shared mutable object works fine until two coroutines update it at the same time, or you need to know *when* something changed, or you want to add a feature without touching existing code.
|
||||
|
||||
The reducer pattern solves all three:
|
||||
|
||||
- **Thread safety**: `StateFlow.update` is atomic. Concurrent dispatches serialize without locks.
|
||||
- **Observability**: `context.state` is a hot `StateFlow` it always holds the current value and any code can `collect` it and react to changes without being coupled to the producer.
|
||||
- **Extensibility**: adding a feature means adding a `Behaviour` to a list. Nothing else changes.
|
||||
|
||||
The cost is that you cannot mutate state directly. Everything goes through `dispatch`. That constraint is the point.
|
||||
|
||||
---
|
||||
|
||||
## The Context
|
||||
|
||||
`Context<S, A>` (`context/context.kt`) holds the current state as a `StateFlow<S>`, the coroutine scope that defines this module's lifetime, and the behaviour list.
|
||||
|
||||
```kotlin
|
||||
class Context<S, A>(
|
||||
val state: StateFlow<S>,
|
||||
val scope: CoroutineScope,
|
||||
val behaviours: CopyOnWriteArrayList<Behaviour<S, A, *>>,
|
||||
) {
|
||||
fun dispatch(action: A)
|
||||
fun dispatchAll(actions: List<A>)
|
||||
fun <C> observeAll(receiver: C)
|
||||
}
|
||||
```
|
||||
|
||||
`Context.create` takes an initial state and a list of behaviours. On each `dispatch`, it folds every behaviour's `reduce` over the current state in order and publishes the result. Behaviours that don't care about an action return the state unchanged.
|
||||
|
||||
`dispatchAll(actions)` applies a list of actions in one atomic `StateFlow.update`. Use it when you need multiple state changes to be visible as one - intermediate states are never published, so no observer fires between them.
|
||||
|
||||
`observeAll(receiver)` calls `observe(receiver)` on every behaviour in the list. This is how observation is wired after construction - see [Module Lifecycle](#module-lifecycle).
|
||||
|
||||
The `behaviours` list is a `CopyOnWriteArrayList`. This allows adding behaviours after construction, which is needed for modules whose behaviour list depends on runtime context (e.g. `TrackingChecklist` adds step behaviours in `startObserving`).
|
||||
|
||||
---
|
||||
|
||||
## Behaviours
|
||||
|
||||
A behaviour is one feature of a module. It has two methods, both optional:
|
||||
|
||||
```kotlin
|
||||
interface Behaviour<S, A, C> {
|
||||
fun reduce(state: S, action: A): S = state // pure, no side effects
|
||||
fun observe(receiver: C) {} // side effects go here
|
||||
}
|
||||
```
|
||||
|
||||
`reduce` is a pure function - it cannot launch coroutines, call external services, or read from a clock. It just maps `(state, action) → state`.
|
||||
|
||||
`observe` is called once after construction, after the context exists. This is where you launch coroutines, subscribe to flows, register event listeners. All coroutines launched here should use `receiver.context.scope` so they die when the module dies - no manual cleanup, no leaks.
|
||||
|
||||
**Why behaviours instead of methods on the module class?**
|
||||
|
||||
The natural alternative is one class with methods for each feature - ping handling, handshake logic, sensor registration, timeout detection, all in the same file. That works until the class has 20 features and every change has global blast radius. Behaviours make the feature list explicit: you read `create()`, you see exactly what the module does. Adding or removing a feature is one line in that list, touching nothing else.
|
||||
|
||||
**Why `observe` is separate from `reduce`:**
|
||||
|
||||
`reduce` must stay pure so state transitions are testable and predictable. Side effects in `observe` are isolated - a behaviour that logs packets doesn't affect state, a behaviour that saves config doesn't affect packet handling.
|
||||
|
||||
### Scoping Behaviours to Module Lifetime
|
||||
|
||||
Every behaviour's coroutines run inside `receiver.context.scope`. When a UDP connection drops, its scope is cancelled, which cancels every coroutine every behaviour launched for that connection. No teardown code needed anywhere.
|
||||
|
||||
This is why `observe` receives the module (or context) rather than taking a raw `CoroutineScope` parameter - it enforces that behaviours cannot outlive their module.
|
||||
|
||||
### Stateless vs. Stateful Behaviours
|
||||
|
||||
All behaviours are `class`es, instantiated at the call site:
|
||||
|
||||
```kotlin
|
||||
class PacketBehaviour : UDPConnectionBehaviour { ... }
|
||||
|
||||
val behaviours = listOf(PacketBehaviour(), PacketLossBehaviour(), HandshakeBehaviour())
|
||||
```
|
||||
|
||||
Even behaviours with no constructor arguments are `class`es. `object` is banned for behaviours because `observe()` often needs to capture mutable state (timers, counters, flags). An `object` shares that state across every module instance that uses it — a subtle, hard-to-trace bug. Requiring `class` enforces that each module instance gets its own behaviour instance, with its own isolated state. The allocation cost is negligible.
|
||||
|
||||
Behaviours that need external services take them as constructor arguments:
|
||||
|
||||
```kotlin
|
||||
class TrackerConfigBehaviour(
|
||||
private val settings: Settings,
|
||||
private val hardwareId: String,
|
||||
) : TrackerBehaviour { ... }
|
||||
```
|
||||
|
||||
When a behaviour is conditional (depends on a nullable service), use `buildList`:
|
||||
|
||||
```kotlin
|
||||
val behaviours: List<MyBehaviour> = buildList {
|
||||
add(AlwaysPresentBehaviour())
|
||||
optionalService?.let { add(OptionalServiceBehaviour(it)) }
|
||||
}
|
||||
```
|
||||
|
||||
For modules like `SolarXRBridge` where the behaviour list is large and reusable, extract it into a named function on the companion object:
|
||||
|
||||
```kotlin
|
||||
companion object {
|
||||
fun buildBehaviours(appContext: AppContextProvider): List<SolarXRBridgeBehaviour> = buildList {
|
||||
add(DataFeedInitBehaviour(appContext.server, appContext.skeleton))
|
||||
add(FirmwareBehaviour(appContext.server, appContext.firmwareManager))
|
||||
// ...
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This lets tests call `buildBehaviours` with a stub context, or ignore it entirely and construct the module directly with only the behaviours they need.
|
||||
|
||||
### The Receiver Type
|
||||
|
||||
The type parameter `C` controls what `observe` receives. For simple modules where behaviours only need to dispatch or subscribe to state, `C` is the context itself. For modules where behaviours also need to call methods (send bytes, emit events), `C` is the module class:
|
||||
|
||||
```kotlin
|
||||
// behaviours only dispatch/observe state
|
||||
typealias GlobalConfigBehaviour = Behaviour<GlobalConfigState, GlobalConfigActions, GlobalConfigContext>
|
||||
|
||||
// behaviours also call receiver.send(), receiver.packetEvents.on<T>(...)
|
||||
typealias UDPConnectionBehaviour = Behaviour<UDPConnectionState, UDPConnectionActions, UDPConnection>
|
||||
```
|
||||
|
||||
### File Layout
|
||||
|
||||
Behaviours live in a `behaviours.kt` file in the same package as the module, separate from the module class itself:
|
||||
|
||||
```
|
||||
tracker/
|
||||
├── module.kt ← Tracker class, TrackerState, TrackerActions, typealiases
|
||||
├── behaviours.kt ← TrackerBasicBehaviour, TrackerTPSBehaviour, ...
|
||||
└── config.kt ← TrackerConfigBehaviour (its own file - distinct concern)
|
||||
```
|
||||
|
||||
`module.kt` is the standard name for the file containing the module class, state, actions, and typealiases. `behaviours.kt` holds the implementations. For modules with many distinct feature areas, split behaviours by feature instead of one file - `solarxr/` uses this: `datafeed.kt`, `firmware.kt`, `provisioning.kt`, etc. each live alongside `module.kt`.
|
||||
|
||||
---
|
||||
|
||||
## Module Lifecycle
|
||||
|
||||
Every module has a two-step lifecycle: **construction** then **observation wiring**.
|
||||
|
||||
```kotlin
|
||||
// Step 1: create the module (pure construction, no side effects)
|
||||
val manager = FirmwareManager.create(ctx = phase1, scope = scope)
|
||||
|
||||
// Step 2: wire observation (launches coroutines, subscribes to flows)
|
||||
manager.startObserving()
|
||||
```
|
||||
|
||||
`create()` builds the context with its behaviour list and constructs the module. No coroutines are launched, no flows are subscribed. The module is inert.
|
||||
|
||||
`startObserving()` calls `context.observeAll(this)`, which calls `observe(receiver)` on every behaviour. This is where all side effects begin.
|
||||
|
||||
**Why separate construction from observation?**
|
||||
|
||||
Some modules need to exist before all their dependencies are assembled. For example, `TrackingChecklist` is constructed before `AppContext` exists, but its step behaviours depend on `Skeleton` and `VRCConfigManager` which are part of `AppContext`. By deferring observation, the module can be constructed in any order and wired later:
|
||||
|
||||
```kotlin
|
||||
// Constructed early - no AppContext needed yet
|
||||
val trackingChecklist = TrackingChecklist.create(scope = this)
|
||||
|
||||
// AppContext assembled from all modules
|
||||
val appContext = AppContext(server, config, serialServer, skeleton, ..., trackingChecklist)
|
||||
|
||||
// Observation wired now - TrackingChecklist adds its step behaviours using AppContext
|
||||
appContext.startObserving()
|
||||
```
|
||||
|
||||
`AppContext.startObserving()` calls `startObserving()` on every bootstrap module in sequence, and `trackingChecklist.startObserving(appContext)` adds its behaviours to `context.behaviours` before calling `context.observeAll(this)`.
|
||||
|
||||
**Runtime modules** (UDP connections, SolarXR bridges, HID receivers) are created and immediately observed - they have all their dependencies at creation time:
|
||||
|
||||
```kotlin
|
||||
val bridge = SolarXRBridge.create(id = id, appContext = appContext, scope = scope)
|
||||
// startObserving() is called inside create()
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Dependency Injection
|
||||
|
||||
The server uses a typed context hierarchy for dependency injection. Contexts are interfaces - modules declare the minimum phase they need in `create()`, which gives compile-time guarantees that their dependencies exist.
|
||||
|
||||
```
|
||||
Phase1ContextProvider
|
||||
└── AppContextProvider
|
||||
```
|
||||
|
||||
**`Phase1ContextProvider`** - the bootstrap phase. Available before `AppContext` is assembled:
|
||||
|
||||
```kotlin
|
||||
interface Phase1ContextProvider {
|
||||
val server: VRServer
|
||||
val config: AppConfig
|
||||
val serialServer: SerialServer
|
||||
}
|
||||
```
|
||||
|
||||
**`AppContextProvider`** - the full application context. Available after all bootstrap modules are constructed:
|
||||
|
||||
```kotlin
|
||||
interface AppContextProvider : Phase1ContextProvider {
|
||||
val skeleton: Skeleton
|
||||
val firmwareManager: FirmwareManager
|
||||
val vrcConfigManager: VRCConfigManager?
|
||||
val provisioningManager: ProvisioningManager
|
||||
val heightCalibrationManager: HeightCalibrationManager
|
||||
val trackingChecklist: TrackingChecklist
|
||||
fun startObserving()
|
||||
}
|
||||
```
|
||||
|
||||
**The rule:** always use `AppContextProvider` unless the module genuinely cannot be constructed after `AppContext` is assembled. In practice, only bootstrap modules (`FirmwareManager`, `Skeleton`, `ProvisioningManager`, `HeightCalibrationManager`) use `Phase1ContextProvider` in `create()`. Runtime modules like `SolarXRBridge` always receive `AppContextProvider`.
|
||||
|
||||
The concrete classes `Phase1Context` and `AppContext` implement these interfaces. Tests implement the interfaces directly with only the fields they need - see [Testing](#testing).
|
||||
|
||||
---
|
||||
|
||||
## Actions
|
||||
|
||||
Actions are `sealed interface`s. This matters because the compiler enforces exhaustive `when` in reducers - you cannot forget to handle a new action type. Named actions also mean you can grep for all places a specific transition can occur.
|
||||
|
||||
```kotlin
|
||||
sealed interface UDPConnectionActions {
|
||||
data class Handshake(val deviceId: Int) : UDPConnectionActions
|
||||
data class LastPacket(val packetNum: Long?, val time: Long) : UDPConnectionActions
|
||||
data object Disconnected : UDPConnectionActions
|
||||
}
|
||||
```
|
||||
|
||||
The choice between a flexible `Update` action and a named action is about who else needs to react:
|
||||
|
||||
- **`Update`** when only the caller cares about the change. It carries a lambda that transforms state directly. No other behaviour pattern-matches it, so there's no coupling.
|
||||
- **Named action** when other behaviours need to react to this specific event. `Handshake` in `UDPConnectionActions` signals to multiple behaviours that a connection is now established; each one matches it independently.
|
||||
|
||||
```kotlin
|
||||
// Nothing else needs to react - use Update
|
||||
tracker.context.dispatch(TrackerActions.Update { copy(tps = newTps) })
|
||||
|
||||
// Multiple behaviours react to this - use a named action
|
||||
connection.context.dispatch(UDPConnectionActions.Handshake(deviceId = id))
|
||||
```
|
||||
|
||||
If you find yourself dispatching an `Update` that other behaviours start matching against, it's time to promote it to a named action.
|
||||
|
||||
---
|
||||
|
||||
## EventDispatcher
|
||||
|
||||
`EventDispatcher<T>` routes events to typed listeners. Each behaviour registers its own listener in `observe`:
|
||||
|
||||
```kotlin
|
||||
receiver.packetEvents.on<SensorInfo> { packet -> ... } // only SensorInfo
|
||||
receiver.packetEvents.onAny { packet -> ... } // every packet
|
||||
```
|
||||
|
||||
**Why not a central `when` block?**
|
||||
|
||||
A central switch means every new packet type requires editing the dispatch hub. With `EventDispatcher`, each behaviour owns its subscription. Adding a new packet type means adding a class to `packets.kt` and a listener in a behaviour - the routing hub never changes.
|
||||
|
||||
It also means behaviours are self-contained: `SensorInfoBehaviour` is the only place that knows what to do with `SensorInfo`. No shared routing code.
|
||||
|
||||
`EventDispatcher` dispatches by the runtime type of the event by default. When events are wrapped (e.g. `PacketEvent<UDPPacket>` where the actual packet is the inner value), pass a `keyOf` lambda to tell the dispatcher which type to route by - otherwise all events would be bucketed under `PacketEvent` regardless of the inner packet type.
|
||||
|
||||
---
|
||||
|
||||
## Coroutine Scope and Lifetime
|
||||
|
||||
Every module receives a `CoroutineScope` at creation. That scope defines when the module lives and dies:
|
||||
|
||||
- Cancelling the scope cancels all coroutines - all behaviours launched inside it
|
||||
- No `close()`, `stop()`, or `dispose()` methods needed anywhere
|
||||
- A disconnected client, a dropped UDP connection, a closed serial port - all cleaned up by scope cancellation
|
||||
|
||||
Blocking I/O goes on `Dispatchers.IO`. State updates and logic stay on the default dispatcher. Never use `runBlocking` inside an observer - it blocks the coroutine thread pool.
|
||||
|
||||
---
|
||||
|
||||
## State vs. Plain Data
|
||||
|
||||
Not everything needs to be in a `StateFlow`. The rule: **put data in state only if other code needs to react to it changing**.
|
||||
|
||||
- `VRServer.handleCounter` is an `AtomicInt` - nothing reacts to it, so a dispatch round-trip would be waste.
|
||||
- `UDPTrackerServer` has no `Context` at all. Its connection map is a `MutableMap` internal to the server loop. Nothing outside reads it.
|
||||
- Tracker config *is* in state because the SolarXR layer and the config autosave both react to body part assignments changing.
|
||||
|
||||
---
|
||||
|
||||
## Cross-Module Communication
|
||||
|
||||
Modules don't call each other directly. A behaviour in one module subscribes to another module's `StateFlow` and dispatches into its own context (or another module's context) when something relevant changes.
|
||||
|
||||
Two common patterns:
|
||||
|
||||
**React to another module's state:**
|
||||
```kotlin
|
||||
// Inside TrackerConfigBehaviour.observe()
|
||||
// When tracker state changes, persist the relevant fields to Settings
|
||||
receiver.context.state
|
||||
.distinctUntilChangedBy { stateToConfig(it) }
|
||||
.drop(1)
|
||||
.onEach { state ->
|
||||
settings.context.dispatch(SettingsActions.UpdateTracker(hardwareId) { stateToConfig(state) })
|
||||
}
|
||||
.launchIn(receiver.context.scope)
|
||||
```
|
||||
|
||||
**Dispatch into VRServer from a connection:**
|
||||
```kotlin
|
||||
// Inside HandshakeBehaviour.observe() - a UDP connection registers a new device
|
||||
receiver.packetEvents.on<Handshake> { event ->
|
||||
val device = Device.create(...)
|
||||
receiver.serverContext.context.dispatch(VRServerActions.NewDevice(deviceId, device))
|
||||
}
|
||||
```
|
||||
|
||||
The key rule: behaviours own the subscription lifetime via `launchIn(receiver.context.scope)`. When the module dies, the subscription stops - no dangling listeners in foreign modules.
|
||||
|
||||
---
|
||||
|
||||
## IPC and Transport
|
||||
|
||||
The server exposes four connection points:
|
||||
|
||||
| Transport | Client | Protocol |
|
||||
|---|---|---|
|
||||
| Unix socket / named pipe `SlimeVRDriver` | OpenVR driver | Protobuf (Wire) |
|
||||
| Unix socket / named pipe `SlimeVRInput` | External feeder | Protobuf (Wire) |
|
||||
| Unix socket / named pipe `SlimeVRRpc` | SolarXR (IPC path) | FlatBuffers |
|
||||
| WebSocket port 21110 | GUI / third-party (SolarXR) | FlatBuffers |
|
||||
|
||||
**Why separate transport from protocol?**
|
||||
|
||||
Platform files (`linux.kt`, `windows.kt`) own reading frames off a socket and produce a `Flow<ByteArray>` + a `send` function. Protocol handlers (`protocol.kt`, `ipc.kt`) are plain `suspend fun`s that take those two things and know nothing about Unix sockets or named pipes.
|
||||
|
||||
The same `handleSolarXRBridge` function runs on Linux sockets, Windows pipes, and WebSocket. The WebSocket adapter in `ws-server.kt` converts Ktor frames to the same `Flow<ByteArray>` + `send` abstraction. The handler never changes.
|
||||
|
||||
**Why events for IPC message routing?**
|
||||
|
||||
Same reason as UDP packets. The SolarXR protocol has dozens of RPC message types. Behaviours that handle firmware updates, skeleton config, data feeds, etc. each register their own listener on the `rpcDispatcher`. Adding a new RPC handler doesn't touch existing ones.
|
||||
|
||||
### Wire Framing (named sockets)
|
||||
|
||||
All three named sockets use the same framing: a **LE u32 length** prefix (including the 4-byte header itself) followed by the raw payload bytes.
|
||||
|
||||
### UDP Packet Pipeline
|
||||
|
||||
The UDP receive loop runs on `Dispatchers.IO`. It reads a datagram, parses the packet type and payload via `readPacket`, wraps the result in a `PacketEvent`, and pushes it into a `Channel<PacketEvent<UDPPacket>>` per connection.
|
||||
|
||||
A dedicated coroutine per connection drains the channel and calls `EventDispatcher.emit`. Pre-handshake packets are filtered at the channel drain step - a single guard in one place, not spread across every behaviour.
|
||||
|
||||
---
|
||||
|
||||
## Config
|
||||
|
||||
Config is not just file I/O - it is a live state machine. The server supports runtime profile switching, so config data lives in a `StateFlow` like everything else. Code that needs to react to config changes (e.g. tracker body part assignment saving to disk) subscribes to the settings state flow.
|
||||
|
||||
The config system has three layers:
|
||||
|
||||
- **`AppConfig`** - global state: which user profile and settings profile are active
|
||||
- **`UserConfig`** - per-user data (body proportions, etc.)
|
||||
- **`Settings`** - per-profile settings (tracker assignments, port, VRC warnings); persists to disk
|
||||
|
||||
Each is a full module with its own `Context`, behaviours, and JSON autosave. Migrations live in the module's `parseAndMigrate` function - add a `version < N` branch there.
|
||||
|
||||
---
|
||||
|
||||
## Testing
|
||||
|
||||
The module pattern is designed to be testable at each layer independently.
|
||||
|
||||
### Testing reducers
|
||||
|
||||
Create a context directly with the behaviours you want to test. No module class, no scope tricks:
|
||||
|
||||
```kotlin
|
||||
val context = Context.create(
|
||||
initialState = FirmwareManagerState(jobs = mapOf()),
|
||||
scope = this,
|
||||
behaviours = listOf(FirmwareManagerBaseBehaviour()),
|
||||
)
|
||||
context.dispatch(FirmwareManagerActions.UpdateJob(...))
|
||||
assertEquals(FirmwareUpdateStatus.UPLOADING, context.state.value.jobs["COM1"]?.status)
|
||||
```
|
||||
|
||||
### Testing observe behaviour
|
||||
|
||||
Construct the module directly - bypassing `create()` - with only the behaviours relevant to the test. This avoids constructing unrelated dependencies:
|
||||
|
||||
```kotlin
|
||||
val serialServer = buildTestSerialServer(backgroundScope)
|
||||
val context = Context.create(
|
||||
initialState = ProvisioningManager.INITIAL_STATE,
|
||||
scope = backgroundScope,
|
||||
behaviours = listOf(ProvisioningManagerBaseBehaviour()),
|
||||
)
|
||||
val manager = ProvisioningManager(context = context, serialServer = serialServer, scope = backgroundScope)
|
||||
manager.startObserving()
|
||||
|
||||
manager.startProvisioning(buildTestVrServer(backgroundScope), "wifi", "pass", null)
|
||||
```
|
||||
|
||||
For modules that need an `AppContextProvider` (e.g. `SolarXRBridge`), extend `TestAppContext` and override only what the test uses. Every other field defaults to `error("not used in test")`:
|
||||
|
||||
```kotlin
|
||||
val server = buildTestVrServer(backgroundScope)
|
||||
val skeleton = buildTestSkeleton(backgroundScope)
|
||||
val appContext = object : TestAppContext() {
|
||||
override val server = server
|
||||
override val skeleton = skeleton
|
||||
}
|
||||
val context = Context.create(
|
||||
initialState = SolarXRBridgeState(dataFeedConfigs = listOf()),
|
||||
scope = backgroundScope,
|
||||
behaviours = listOf(DataFeedInitBehaviour(server, skeleton)),
|
||||
)
|
||||
val bridge = SolarXRBridge(id = 1, context = context, appContext = appContext,
|
||||
dataFeedDispatcher = EventDispatcher(), rpcDispatcher = EventDispatcher())
|
||||
bridge.startObserving()
|
||||
```
|
||||
|
||||
`TestAppContext` lives in `TestServer.kt`. When a new module is added to `AppContextProvider`, add a default stub there - all existing tests automatically get the default without changes.
|
||||
|
||||
**The pattern:** only initialize what the test exercises. If a behaviour accesses a field that isn't overridden, it throws - that's intentional. It keeps tests focused and stubs minimal.
|
||||
|
||||
### Test helpers (`TestServer.kt`)
|
||||
|
||||
`buildTestVrServer`, `buildTestSerialServer`, `buildTestUserConfig`, and `buildTestSkeleton` are available for constructing real lightweight instances of common dependencies.
|
||||
|
||||
---
|
||||
|
||||
## What Goes Where
|
||||
|
||||
| Location | Purpose |
|
||||
|---|---|
|
||||
| `server/core` | Protocol-agnostic business logic |
|
||||
| `server/desktop` | Platform entry point, IPC wiring, HID, serial flash |
|
||||
| `context/context.kt` | `Context` and `Behaviour` primitives - no domain logic here |
|
||||
| `udp/` | UDP wire protocol: connection state, packets, behaviours, server loop |
|
||||
| `hid/` | HID tracker receiver: registration, rotation, battery, status |
|
||||
| `solarxr/` | `SolarXRBridge` + per-feature behaviour files (one per RPC area) |
|
||||
| `config/` | 3-tier config: `AppConfig`, `UserConfig`, `Settings` |
|
||||
| `firmware/` | OTA and serial flash; independent of UDP tracker protocol |
|
||||
| `trackingchecklist/` | Checklist steps as behaviours observing server/tracker/VRC state |
|
||||
| `skeleton/` | Skeleton solving, proportions, bone geometry |
|
||||
| `vrchat/` | VRChat config monitoring and recommended-value computation |
|
||||
|
||||
---
|
||||
|
||||
## Extending the Server
|
||||
|
||||
### Adding a New Module
|
||||
|
||||
1. **Define state and actions** in `module.kt`:
|
||||
```kotlin
|
||||
data class MyState(val connected: Boolean)
|
||||
|
||||
sealed interface MyActions {
|
||||
data object Connected : MyActions
|
||||
data object Disconnected : MyActions
|
||||
}
|
||||
|
||||
typealias MyContext = Context<MyState, MyActions>
|
||||
typealias MyBehaviour = Behaviour<MyState, MyActions, MyModule>
|
||||
```
|
||||
|
||||
2. **Define the module class** with a `create()` factory and a `startObserving()` method:
|
||||
```kotlin
|
||||
class MyModule(val context: MyContext, val server: VRServer) {
|
||||
fun startObserving() = context.observeAll(this)
|
||||
|
||||
companion object {
|
||||
fun create(ctx: Phase1ContextProvider, scope: CoroutineScope): MyModule {
|
||||
val context = Context.create(
|
||||
initialState = MyState(false),
|
||||
scope = scope,
|
||||
behaviours = listOf(MyCoreBehaviour()),
|
||||
)
|
||||
return MyModule(context, ctx.server)
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
3. **Register in `AppContext`** and call `startObserving()` inside `AppContext.startObserving()`.
|
||||
|
||||
4. **Write behaviours** in `behaviours.kt` (or per-feature files for large modules).
|
||||
|
||||
### Adding a Behaviour to an Existing Module
|
||||
|
||||
Add it to the `behaviours` list in `create()`. The behaviour's `reduce` and `observe` are automatically wired when `startObserving()` is called. Nothing else changes.
|
||||
|
||||
### Adding a New UDP Packet Type
|
||||
|
||||
1. Add the packet class and its `read` function in `udp/packets.kt`
|
||||
2. Add an entry to the `PacketType` enum and a branch in `readPacket()`
|
||||
3. Register a listener in a behaviour's `observe`:
|
||||
```kotlin
|
||||
receiver.packetEvents.on<MyPacket> { event ->
|
||||
receiver.context.dispatch(...)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Style Conventions
|
||||
|
||||
- **Prefer plain functions over classes.** A single-method interface should almost always be a function type (`() -> Unit`, `suspend (ByteArray) -> Unit`). When in doubt, write a function.
|
||||
- **Behaviours are always `class`, never `object`.** Even behaviours with no constructor arguments. `observe()` frequently captures mutable state (timers, counters, flags), and a singleton `object` would share that state across every module instance — a subtle, cross-connection bug. Instantiate every behaviour at the call site: `listOf(PacketBehaviour(), PingBehaviour())`.
|
||||
- **Prefer plain functions over extension functions.** Only use extensions when the receiver type is genuinely the primary subject.
|
||||
- **State data classes are all `val`.** Mutable fields in a state class are a design mistake - use `var` in a plain class if you need local mutability, never in state.
|
||||
- **Use `sealed interface` for actions**, not `sealed class` - no constructor overhead.
|
||||
- **Module creation lives in `companion object { fun create(...) }`.**
|
||||
- **Module observation wiring lives in `startObserving()`**, called via `context.observeAll(this)`.
|
||||
- **Never expose `MutableStateFlow` directly.** Expose `StateFlow` via `context.state`.
|
||||
@@ -12,22 +12,20 @@ import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
|
||||
import java.util.Base64
|
||||
|
||||
plugins {
|
||||
kotlin("android")
|
||||
kotlin("plugin.serialization")
|
||||
id("com.github.gmazzo.buildconfig")
|
||||
|
||||
id("com.android.application") version "8.13.2"
|
||||
id("org.ajoberstar.grgit")
|
||||
id("com.android.application") version "9.2.1"
|
||||
}
|
||||
|
||||
kotlin {
|
||||
jvmToolchain {
|
||||
languageVersion.set(JavaLanguageVersion.of(17))
|
||||
languageVersion.set(JavaLanguageVersion.of(24))
|
||||
}
|
||||
}
|
||||
java {
|
||||
toolchain {
|
||||
languageVersion.set(JavaLanguageVersion.of(17))
|
||||
languageVersion.set(JavaLanguageVersion.of(24))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,7 +81,7 @@ val deleteTempKeyStore = tasks.register<Delete>("deleteTempKeyStore") {
|
||||
|
||||
tasks.withType<KotlinCompile> {
|
||||
compilerOptions {
|
||||
jvmTarget.set(JvmTarget.JVM_17)
|
||||
jvmTarget.set(JvmTarget.JVM_24)
|
||||
freeCompilerArgs.set(listOf("-Xvalue-classes"))
|
||||
}
|
||||
}
|
||||
@@ -101,14 +99,13 @@ tasks.withType<Javadoc> {
|
||||
|
||||
repositories {
|
||||
google()
|
||||
maven(url = "https://jitpack.io")
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(project(":server:core"))
|
||||
|
||||
implementation("commons-cli:commons-cli:1.11.0")
|
||||
implementation("org.apache.commons:commons-lang3:3.20.0")
|
||||
|
||||
// Android stuff
|
||||
implementation("androidx.appcompat:appcompat:1.7.1")
|
||||
implementation("androidx.core:core-ktx:1.17.0")
|
||||
@@ -118,15 +115,21 @@ dependencies {
|
||||
androidTestImplementation("androidx.test.ext:junit:1.3.0")
|
||||
androidTestImplementation("androidx.test.espresso:espresso-core:3.7.0")
|
||||
|
||||
// Serial
|
||||
// Serial + firmware flashing
|
||||
implementation("com.github.mik3y:usb-serial-for-android:3.7.0")
|
||||
implementation("com.github.loucass003:EspflashKotlin:v0.11.0")
|
||||
|
||||
// Logging
|
||||
implementation("io.klogging:klogging:0.11.7")
|
||||
|
||||
// WebSocket server + coroutines
|
||||
val ktorVersion = "3.4.1"
|
||||
implementation("io.ktor:ktor-server-cio:$ktorVersion")
|
||||
implementation("io.ktor:ktor-server-websockets:$ktorVersion")
|
||||
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2")
|
||||
}
|
||||
|
||||
// The android block is where you configure all your Android-specific build options.
|
||||
extra.apply {
|
||||
set("gitVersionCode", grgit.tag.list().size)
|
||||
set("gitVersionName", grgit.describe(mapOf("tags" to true, "always" to true)))
|
||||
}
|
||||
android {
|
||||
// The app's namespace. Used primarily to access app resources.
|
||||
|
||||
@@ -160,12 +163,16 @@ android {
|
||||
|
||||
// adds an offset of the version code as we might do apk releases in the middle of actual
|
||||
// releases if we failed on bundling or stuff
|
||||
val versionCodeOffset = 5
|
||||
// Defines the version number of your app.
|
||||
versionCode = (extra["gitVersionCode"] as? Int)?.plus(versionCodeOffset) ?: 0
|
||||
val versionCodeOffset = 4
|
||||
|
||||
// Defines a user-friendly version name for your app.
|
||||
versionName = extra["gitVersionName"] as? String ?: "v0.0.0"
|
||||
// Defines the version number of your app.
|
||||
versionCode = providers.exec {
|
||||
commandLine("git", "--no-pager", "tag", "-l")
|
||||
}.standardOutput.asText.get().trim().split('\n').size +
|
||||
versionCodeOffset
|
||||
versionName = providers.exec {
|
||||
commandLine("git", "describe", "--tags", "--abbrev=8", "--always")
|
||||
}.standardOutput.asText.get().trim()
|
||||
|
||||
logger.lifecycle("i: Configured for SlimeVR Android version \"$versionName\" ($versionCode).")
|
||||
|
||||
@@ -217,7 +224,7 @@ android {
|
||||
}
|
||||
|
||||
compileOptions {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
sourceCompatibility = JavaVersion.VERSION_24
|
||||
targetCompatibility = JavaVersion.VERSION_24
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,11 @@
|
||||
<uses-feature android:name="android.hardware.usb.host" android:required="false" />
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
|
||||
|
||||
|
||||
@@ -1,15 +1,53 @@
|
||||
package dev.slimevr.android
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.app.*
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.ServiceInfo
|
||||
import android.net.wifi.WifiManager
|
||||
import android.os.Build
|
||||
import android.os.IBinder
|
||||
import android.os.PowerManager
|
||||
import androidx.core.app.NotificationChannelCompat
|
||||
import androidx.core.app.NotificationCompat
|
||||
import androidx.core.app.NotificationManagerCompat
|
||||
import androidx.core.app.ServiceCompat
|
||||
import io.eiren.util.logging.LogManager
|
||||
import dev.slimevr.AppContext
|
||||
import dev.slimevr.FeatureFlags
|
||||
import dev.slimevr.Phase1Context
|
||||
import dev.slimevr.VRServer
|
||||
import dev.slimevr.android.config.AndroidConfigStorage
|
||||
import dev.slimevr.android.hid.createAndroidHIDManager
|
||||
import dev.slimevr.android.ipc.createAndroidSolarXRWebsocketServer
|
||||
import dev.slimevr.android.serial.AndroidFirmwareFlasher
|
||||
import dev.slimevr.android.serial.createAndroidSerialServer
|
||||
import dev.slimevr.android.udp.resolveAndroidUdpAddress
|
||||
import dev.slimevr.android.vrchat.resolveAndroidOscQueryAddress
|
||||
import dev.slimevr.bvh.BVHManager
|
||||
import dev.slimevr.config.AppConfig
|
||||
import dev.slimevr.firmware.FirmwareManager
|
||||
import dev.slimevr.heightcalibration.HeightCalibrationManager
|
||||
import dev.slimevr.networkprofile.NetworkProfileManager
|
||||
import dev.slimevr.provisioning.ProvisioningManager
|
||||
import dev.slimevr.resets.ResetsManager
|
||||
import dev.slimevr.skeleton.Skeleton
|
||||
import dev.slimevr.trackingchecklist.TrackingChecklist
|
||||
import dev.slimevr.udp.UdpServer
|
||||
import dev.slimevr.util.safeLaunch
|
||||
import dev.slimevr.vmc.VMCManager
|
||||
import dev.slimevr.vrcosc.VRCOSCManager
|
||||
import io.klogging.noCoLogger
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.SupervisorJob
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.cancel
|
||||
|
||||
private val logger = noCoLogger("ForegroundService")
|
||||
|
||||
private const val ACTION_STOP = "dev.slimevr.android.STOP_SERVER"
|
||||
const val ACTION_FINISH_APP = "dev.slimevr.android.FINISH_APP"
|
||||
|
||||
/**
|
||||
* ForegroundService helps to keep the SlimeVR Server on Android from being killed.
|
||||
@@ -22,27 +60,37 @@ import io.eiren.util.logging.LogManager
|
||||
* Tested with VRChat on Quest 3 in high population worlds with all avatars on
|
||||
* for over an hour with no shut down of the SlimeVR server. Without this service,
|
||||
* the server would often be shutdown unexpectedly.
|
||||
*
|
||||
* Notes:
|
||||
* Luckily this does not show anything visual over the running app.
|
||||
* The notification only shows in the alert panel and cannot be dismissed.
|
||||
* On Quest there's no way to manually kill the Slime Server, so you have to restart the device.
|
||||
*/
|
||||
class ForegroundService : Service() {
|
||||
private val CHANNEL_ID = "SlimeVrForegroundServiceChannel"
|
||||
private val NOTIFICATION_ID = 100
|
||||
|
||||
private var serviceScope: CoroutineScope? = null
|
||||
private var wakeLock: PowerManager.WakeLock? = null
|
||||
private var multicastLock: WifiManager.MulticastLock? = null
|
||||
private var wifiLock: WifiManager.WifiLock? = null
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
setupAndroidLogging()
|
||||
createNotificationChannel()
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (intent?.action == ACTION_STOP) {
|
||||
ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE)
|
||||
serviceScope?.cancel()
|
||||
serviceScope = null
|
||||
sendBroadcast(Intent(ACTION_FINISH_APP).setPackage(packageName))
|
||||
stopSelf()
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
try {
|
||||
val notification = createNotification()
|
||||
ServiceCompat.startForeground(
|
||||
this,
|
||||
NOTIFICATION_ID, // Cannot be 0
|
||||
NOTIFICATION_ID,
|
||||
notification,
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
|
||||
@@ -54,22 +102,114 @@ class ForegroundService : Service() {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
|
||||
e is ForegroundServiceStartNotAllowedException
|
||||
) {
|
||||
LogManager.severe("Tried to start foreground service when not allowed:", e)
|
||||
logger.error(e, "Tried to start foreground service when not allowed")
|
||||
}
|
||||
// ...
|
||||
}
|
||||
/*
|
||||
* Currently being a foreground process should be enough to keep the server running.
|
||||
* If it turns out to not be enough then the next option would be to return sticky here
|
||||
* which would also require moving server initialization from the MainActivity to here
|
||||
* so the server is restarted when the activity is. You can tell the process is restarted
|
||||
* if the intent variable is null.
|
||||
*/
|
||||
|
||||
if (serviceScope == null) {
|
||||
val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
|
||||
serviceScope = scope
|
||||
scope.safeLaunch { startServer(scope) }
|
||||
}
|
||||
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
serviceScope?.cancel()
|
||||
serviceScope = null
|
||||
wakeLock?.release()
|
||||
wakeLock = null
|
||||
multicastLock?.release()
|
||||
multicastLock = null
|
||||
wifiLock?.release()
|
||||
wifiLock = null
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
private suspend fun startServer(scope: CoroutineScope) {
|
||||
val storage = AndroidConfigStorage(filesDir)
|
||||
val config = AppConfig.create(scope = scope, storage = storage)
|
||||
val server = VRServer.create(scope = scope)
|
||||
val serialServer = createAndroidSerialServer(context = this, scope = scope)
|
||||
|
||||
val phase1 = Phase1Context(server = server, config = config, serialServer = serialServer)
|
||||
|
||||
val firmwareManager = FirmwareManager.create(ctx = phase1, scope = scope, flasher = AndroidFirmwareFlasher)
|
||||
val networkProfileManager = NetworkProfileManager.create(scope = scope, isSupported = false)
|
||||
val skeleton = Skeleton.create(scope = scope, ctx = phase1)
|
||||
val provisioningManager = ProvisioningManager.create(ctx = phase1, scope = scope)
|
||||
val heightCalibrationManager = HeightCalibrationManager.create(ctx = phase1, scope = scope)
|
||||
val trackingChecklist = TrackingChecklist.create(scope = scope)
|
||||
val udpServer = UdpServer.create(scope = scope, addressResolver = ::resolveAndroidUdpAddress)
|
||||
val bvhManager = BVHManager.create(skeleton = skeleton, storage = storage, scope = scope)
|
||||
val vmcManager = VMCManager.create(skeleton = skeleton, ctx = phase1, scope = scope)
|
||||
val vrcOscManager = VRCOSCManager.create(
|
||||
ctx = phase1,
|
||||
scope = scope,
|
||||
oscQueryAddress = resolveAndroidOscQueryAddress(),
|
||||
)
|
||||
val resetsManager = ResetsManager.create(server = server, scope = scope)
|
||||
|
||||
val appContext = AppContext(
|
||||
server = server,
|
||||
config = config,
|
||||
serialServer = serialServer,
|
||||
featureFlags = FeatureFlags(supportsSteamVR = false),
|
||||
skeleton = skeleton,
|
||||
firmwareManager = firmwareManager,
|
||||
vrcConfigManager = null,
|
||||
networkProfileManager = networkProfileManager,
|
||||
provisioningManager = provisioningManager,
|
||||
heightCalibrationManager = heightCalibrationManager,
|
||||
trackingChecklist = trackingChecklist,
|
||||
udpServer = udpServer,
|
||||
bvhManager = bvhManager,
|
||||
vmcManager = vmcManager,
|
||||
vrcOscManager = vrcOscManager,
|
||||
resetsManager = resetsManager,
|
||||
)
|
||||
|
||||
acquireLocks()
|
||||
|
||||
try {
|
||||
appContext.startObserving()
|
||||
|
||||
scope.safeLaunch { createAndroidHIDManager(context = this@ForegroundService, appContext = appContext, scope = this) }
|
||||
scope.safeLaunch { createAndroidSolarXRWebsocketServer(appContext) }
|
||||
|
||||
awaitCancellation()
|
||||
} finally {
|
||||
appContext.dispose()
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressLint("WakelockTimeout")
|
||||
private fun acquireLocks() {
|
||||
val power = getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||
wakeLock = power.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "slimevr:server")
|
||||
.apply { setReferenceCounted(false) }
|
||||
.also { it.acquire() }
|
||||
|
||||
val wifi = getSystemService(Context.WIFI_SERVICE) as WifiManager
|
||||
multicastLock = wifi.createMulticastLock("slimevr-multicast-lock")
|
||||
.apply { setReferenceCounted(true) }
|
||||
.also { it.acquire() }
|
||||
@Suppress("DEPRECATION")
|
||||
wifiLock = wifi.createWifiLock(WifiManager.WIFI_MODE_FULL_HIGH_PERF, "slimevr-wifi-lock")
|
||||
.apply { setReferenceCounted(false) }
|
||||
.also { it.acquire() }
|
||||
}
|
||||
|
||||
private fun stopPendingIntent(): PendingIntent = PendingIntent.getService(
|
||||
this,
|
||||
0,
|
||||
Intent(this, ForegroundService::class.java).apply { action = ACTION_STOP },
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
private fun createNotificationChannel() {
|
||||
val serviceChannel = NotificationChannelCompat.Builder(CHANNEL_ID, NotificationManager.IMPORTANCE_LOW)
|
||||
.setName("SlimeVR Foreground Service Channel")
|
||||
@@ -79,9 +219,20 @@ class ForegroundService : Service() {
|
||||
.createNotificationChannel(serviceChannel)
|
||||
}
|
||||
|
||||
private fun openAppPendingIntent(): PendingIntent = PendingIntent.getActivity(
|
||||
this,
|
||||
0,
|
||||
Intent(this, MainActivity::class.java).apply {
|
||||
flags = Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
|
||||
},
|
||||
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
private fun createNotification(): Notification = NotificationCompat.Builder(this, CHANNEL_ID)
|
||||
.setContentTitle("SlimeVR Server Running")
|
||||
.setContentText("This notification helps keep the server alive")
|
||||
.setSmallIcon(R.drawable.ic_launcher_foreground)
|
||||
.setContentIntent(openAppPendingIntent())
|
||||
.addAction(0, getString(R.string.stop_server), stopPendingIntent())
|
||||
.build()
|
||||
}
|
||||
@@ -2,65 +2,9 @@
|
||||
|
||||
package dev.slimevr.android
|
||||
|
||||
import android.content.Context
|
||||
import android.net.wifi.WifiManager
|
||||
import android.content.Intent
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import dev.slimevr.Keybinding
|
||||
import dev.slimevr.VRServer
|
||||
import dev.slimevr.android.serial.AndroidSerialHandler
|
||||
import dev.slimevr.android.tracking.trackers.hid.AndroidHIDManager
|
||||
import dev.slimevr.config.ConfigManager
|
||||
import dev.slimevr.tracking.trackers.Tracker
|
||||
import io.eiren.util.logging.LogManager
|
||||
import java.io.File
|
||||
import kotlin.concurrent.thread
|
||||
import kotlin.system.exitProcess
|
||||
|
||||
lateinit var vrServer: VRServer
|
||||
private set
|
||||
val vrServerInitialized: Boolean
|
||||
get() = ::vrServer.isInitialized
|
||||
|
||||
fun startVRServer(activity: AppCompatActivity) {
|
||||
thread(start = true, name = "Main VRServer Thread") {
|
||||
try {
|
||||
LogManager.initialize(activity.filesDir)
|
||||
} catch (e1: java.lang.Exception) {
|
||||
e1.printStackTrace()
|
||||
}
|
||||
|
||||
try {
|
||||
val configPath = File(activity.filesDir, "vrconfig.yml").absolutePath
|
||||
val configManager = ConfigManager(configPath)
|
||||
configManager.loadConfig()
|
||||
|
||||
vrServer = VRServer(
|
||||
configManager = configManager,
|
||||
serialHandlerProvider = { _ -> AndroidSerialHandler(activity) },
|
||||
acquireMulticastLock = {
|
||||
val wifi = activity.getSystemService(Context.WIFI_SERVICE) as WifiManager
|
||||
val lock = wifi.createMulticastLock("slimevr-jmdns-multicast-lock")
|
||||
lock.setReferenceCounted(true)
|
||||
lock.acquire()
|
||||
},
|
||||
)
|
||||
vrServer.start()
|
||||
|
||||
// Start service for USB HID trackers
|
||||
val androidHidManager = AndroidHIDManager(
|
||||
"Sensors HID service",
|
||||
{ tracker: Tracker -> vrServer.registerTracker(tracker) },
|
||||
activity,
|
||||
)
|
||||
androidHidManager.start()
|
||||
|
||||
Keybinding(vrServer)
|
||||
vrServer.join()
|
||||
LogManager.closeLogger()
|
||||
exitProcess(0)
|
||||
} catch (e: Throwable) {
|
||||
e.printStackTrace()
|
||||
exitProcess(1)
|
||||
}
|
||||
}
|
||||
activity.startForegroundService(Intent(activity, ForegroundService::class.java))
|
||||
}
|
||||
@@ -1,18 +1,24 @@
|
||||
package dev.slimevr.android
|
||||
|
||||
import android.Manifest
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.util.Log
|
||||
import android.webkit.JavascriptInterface
|
||||
import android.webkit.WebResourceRequest
|
||||
import android.webkit.WebResourceResponse
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebViewClient
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import io.eiren.util.logging.LogManager
|
||||
import androidx.core.content.ContextCompat
|
||||
import java.io.IOException
|
||||
import java.net.URLConnection
|
||||
import java.util.concurrent.locks.ReentrantLock
|
||||
import kotlin.concurrent.withLock
|
||||
|
||||
class AndroidJsObject {
|
||||
@JavascriptInterface
|
||||
@@ -20,36 +26,38 @@ class AndroidJsObject {
|
||||
}
|
||||
|
||||
class MainActivity : AppCompatActivity() {
|
||||
private val requestNotificationPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
|
||||
startVRServer(this)
|
||||
}
|
||||
|
||||
private val finishReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context?, intent: Intent?) = finishAndRemoveTask()
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
setContentView(R.layout.activity_main)
|
||||
|
||||
// Initialize logger (doesn't re-initialize if already run)
|
||||
try {
|
||||
LogManager.initialize(filesDir)
|
||||
} catch (e1: java.lang.Exception) {
|
||||
e1.printStackTrace()
|
||||
ContextCompat.registerReceiver(
|
||||
this,
|
||||
finishReceiver,
|
||||
IntentFilter(ACTION_FINISH_APP),
|
||||
ContextCompat.RECEIVER_NOT_EXPORTED,
|
||||
)
|
||||
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
|
||||
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
requestNotificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||||
} else {
|
||||
startVRServer(this)
|
||||
}
|
||||
|
||||
initLock.withLock {
|
||||
// Start the server if it isn't already running
|
||||
if (!vrServerInitialized) {
|
||||
LogManager.info("[MainActivity] VRServer isn't running yet, starting it...")
|
||||
startVRServer(this)
|
||||
} else {
|
||||
LogManager.info("[MainActivity] VRServer is already running, skipping initialization.")
|
||||
}
|
||||
}
|
||||
|
||||
// Load the web GUI web page
|
||||
LogManager.info("[MainActivity] Initializing GUI WebView...")
|
||||
Log.i(TAG, "Initializing GUI WebView...")
|
||||
val guiWebView = findViewById<WebView>(R.id.guiWebView)
|
||||
|
||||
// ## Configure for web GUI ##
|
||||
// Enable debug mode
|
||||
WebView.setWebContentsDebuggingEnabled(true)
|
||||
|
||||
// Handle path resolution
|
||||
guiWebView.webViewClient = object : WebViewClient() {
|
||||
override fun shouldInterceptRequest(
|
||||
view: WebView,
|
||||
@@ -78,30 +86,26 @@ class MainActivity : AppCompatActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
// Set required features
|
||||
guiWebView.settings.javaScriptEnabled = true
|
||||
guiWebView.settings.domStorageEnabled = true
|
||||
|
||||
// TODO: Let code know it is in android, should be gone when we start using tauri
|
||||
guiWebView.addJavascriptInterface(AndroidJsObject(), "__ANDROID__")
|
||||
|
||||
// Try fixing zoom usability
|
||||
guiWebView.settings.setSupportZoom(true)
|
||||
guiWebView.settings.useWideViewPort = true
|
||||
guiWebView.settings.loadWithOverviewMode = true
|
||||
guiWebView.invokeZoomPicker()
|
||||
|
||||
// Load GUI page
|
||||
guiWebView.loadUrl("https://slimevr.gui/")
|
||||
LogManager.info("[MainActivity] GUI WebView has been initialized and loaded.")
|
||||
Log.i(TAG, "GUI WebView initialized.")
|
||||
}
|
||||
|
||||
// Start a foreground service to notify the user the SlimeVR Server is running
|
||||
// This also helps prevent Android from ejecting the process unexpectedly
|
||||
val serviceIntent = Intent(this, ForegroundService::class.java)
|
||||
startForegroundService(serviceIntent)
|
||||
override fun onDestroy() {
|
||||
unregisterReceiver(finishReceiver)
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
companion object {
|
||||
val initLock = ReentrantLock()
|
||||
private const val TAG = "MainActivity"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package dev.slimevr.android.config
|
||||
|
||||
import dev.slimevr.config.ConfigStorage
|
||||
import dev.slimevr.config.TextFileHandle
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import java.io.File
|
||||
import java.io.RandomAccessFile
|
||||
import java.nio.file.Files
|
||||
import java.nio.file.StandardCopyOption
|
||||
|
||||
class AndroidConfigStorage(private val root: File) : ConfigStorage {
|
||||
override suspend fun read(path: String): String? = withContext(Dispatchers.IO) {
|
||||
val file = resolve(path)
|
||||
if (file.exists()) file.readText() else null
|
||||
}
|
||||
|
||||
override suspend fun write(path: String, content: String) = withContext(Dispatchers.IO) {
|
||||
val file = resolve(path)
|
||||
file.parentFile?.mkdirs()
|
||||
val tmp = File(file.parent, "${file.name}.tmp")
|
||||
tmp.writeText(content)
|
||||
Files.move(tmp.toPath(), file.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING)
|
||||
Unit
|
||||
}
|
||||
|
||||
override suspend fun backup(path: String) = withContext(Dispatchers.IO) {
|
||||
val file = resolve(path)
|
||||
if (!file.exists()) return@withContext
|
||||
val bakTmp = File(file.parent, "${file.name}.bak.tmp")
|
||||
file.copyTo(bakTmp, overwrite = true)
|
||||
Files.move(
|
||||
bakTmp.toPath(),
|
||||
File(file.parent, "${file.name}.bak").toPath(),
|
||||
StandardCopyOption.ATOMIC_MOVE,
|
||||
StandardCopyOption.REPLACE_EXISTING,
|
||||
)
|
||||
}
|
||||
|
||||
override suspend fun exists(path: String): Boolean = withContext(Dispatchers.IO) {
|
||||
resolve(path).exists()
|
||||
}
|
||||
|
||||
override suspend fun ensureDirectory(path: String): Boolean = withContext(Dispatchers.IO) {
|
||||
val directory = resolve(path)
|
||||
directory.isDirectory || directory.mkdirs()
|
||||
}
|
||||
|
||||
override suspend fun openTextFile(path: String): TextFileHandle = withContext(Dispatchers.IO) {
|
||||
val file = resolve(path)
|
||||
file.parentFile?.mkdirs()
|
||||
AndroidRandomAccessTextFileHandle(RandomAccessFile(file, "rw").also { handle -> handle.setLength(0L) })
|
||||
}
|
||||
|
||||
override fun displayPath(path: String): String = resolve(path).absolutePath
|
||||
|
||||
private fun resolve(path: String): File {
|
||||
val requested = File(path)
|
||||
return if (requested.isAbsolute) requested else File(root, path)
|
||||
}
|
||||
}
|
||||
|
||||
private class AndroidRandomAccessTextFileHandle(
|
||||
private val file: RandomAccessFile,
|
||||
) : TextFileHandle {
|
||||
override suspend fun write(text: String) = withContext(Dispatchers.IO) {
|
||||
file.write(text.encodeToByteArray())
|
||||
}
|
||||
|
||||
override suspend fun flush() = withContext(Dispatchers.IO) {
|
||||
file.fd.sync()
|
||||
}
|
||||
|
||||
override suspend fun position(): Long = withContext(Dispatchers.IO) {
|
||||
file.filePointer
|
||||
}
|
||||
|
||||
override suspend fun seek(position: Long) = withContext(Dispatchers.IO) {
|
||||
file.seek(position)
|
||||
}
|
||||
|
||||
override suspend fun close() = withContext(Dispatchers.IO) {
|
||||
file.fd.sync()
|
||||
file.close()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package dev.slimevr.android.hid
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.hardware.usb.UsbConstants
|
||||
import android.hardware.usb.UsbDevice
|
||||
import android.hardware.usb.UsbEndpoint
|
||||
import android.hardware.usb.UsbInterface
|
||||
import android.hardware.usb.UsbManager
|
||||
import androidx.core.content.ContextCompat
|
||||
import dev.slimevr.AppContextProvider
|
||||
import dev.slimevr.AppLogger
|
||||
import dev.slimevr.device.DeviceActions
|
||||
import dev.slimevr.hid.HIDReceiver
|
||||
import dev.slimevr.hid.isCompatibleHidDevice
|
||||
import dev.slimevr.hid.parseHIDPackets
|
||||
import dev.slimevr.util.safeLaunch
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.NonCancellable
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.delay
|
||||
import kotlinx.coroutines.isActive
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
import solarxr_protocol.datatypes.TrackerStatus
|
||||
|
||||
private const val ACTION_USB_HID_PERMISSION = "dev.slimevr.android.USB_HID_PERMISSION"
|
||||
private const val HID_POLL_INTERVAL_MS = 3000L
|
||||
|
||||
private fun findHidInputEndpoint(device: UsbDevice): Pair<UsbInterface, UsbEndpoint>? {
|
||||
for (ifaceIdx in 0 until device.interfaceCount) {
|
||||
val iface = device.getInterface(ifaceIdx)
|
||||
if (iface.interfaceClass != UsbConstants.USB_CLASS_HID) continue
|
||||
for (epIdx in 0 until iface.endpointCount) {
|
||||
val endpoint = iface.getEndpoint(epIdx)
|
||||
if (endpoint.type == UsbConstants.USB_ENDPOINT_XFER_INT &&
|
||||
endpoint.direction == UsbConstants.USB_DIR_IN
|
||||
) {
|
||||
return iface to endpoint
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private data class ActiveReceiver(val job: Job, val receiver: HIDReceiver)
|
||||
|
||||
fun createAndroidHIDManager(context: Context, appContext: AppContextProvider, scope: CoroutineScope) {
|
||||
val usbManager = context.getSystemService(Context.USB_SERVICE) as UsbManager
|
||||
val wakeSignal = Channel<Unit>(Channel.CONFLATED)
|
||||
val permissionRequested = mutableSetOf<String>()
|
||||
val active = mutableMapOf<String, ActiveReceiver>()
|
||||
|
||||
val permissionIntent = PendingIntent.getBroadcast(
|
||||
context,
|
||||
0,
|
||||
Intent(ACTION_USB_HID_PERMISSION).apply { setPackage(context.packageName) },
|
||||
PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
val usbReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(ctx: Context, intent: Intent) {
|
||||
wakeSignal.trySend(Unit)
|
||||
}
|
||||
}
|
||||
|
||||
val intentFilter = IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED).apply {
|
||||
addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
|
||||
addAction(ACTION_USB_HID_PERMISSION)
|
||||
}
|
||||
ContextCompat.registerReceiver(context, usbReceiver, intentFilter, ContextCompat.RECEIVER_NOT_EXPORTED)
|
||||
|
||||
scope.safeLaunch {
|
||||
while (isActive) {
|
||||
val found = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
usbManager.deviceList.values
|
||||
.filter { device -> isCompatibleHidDevice(device.vendorId, device.productId) }
|
||||
.associate { device -> device.deviceName to device }
|
||||
} catch (e: Exception) {
|
||||
AppLogger.hid.error(e, "HID enumeration failed")
|
||||
emptyMap()
|
||||
}
|
||||
}
|
||||
|
||||
for ((deviceName, device) in found) {
|
||||
if (!usbManager.hasPermission(device) && deviceName !in permissionRequested) {
|
||||
AppLogger.hid.info("Requesting USB HID permission for $deviceName")
|
||||
usbManager.requestPermission(device, permissionIntent)
|
||||
permissionRequested.add(deviceName)
|
||||
}
|
||||
}
|
||||
|
||||
val authorized = found.filter { (_, device) -> usbManager.hasPermission(device) }
|
||||
|
||||
val toRemove = (active.keys - authorized.keys) +
|
||||
active.entries.filter { (_, entry) -> !entry.job.isActive }.map { (key, _) -> key }
|
||||
for (deviceName in toRemove) {
|
||||
val entry = active.remove(deviceName) ?: continue
|
||||
entry.job.cancel()
|
||||
entry.job.join()
|
||||
permissionRequested.remove(deviceName)
|
||||
AppLogger.hid.info("HID device removed: $deviceName")
|
||||
}
|
||||
|
||||
for ((deviceName, device) in authorized) {
|
||||
if (deviceName in active) continue
|
||||
permissionRequested.remove(deviceName)
|
||||
|
||||
val hidEndpoint = findHidInputEndpoint(device)
|
||||
if (hidEndpoint == null) {
|
||||
AppLogger.hid.warn("No HID input endpoint found for $deviceName")
|
||||
continue
|
||||
}
|
||||
val (iface, endpoint) = hidEndpoint
|
||||
|
||||
val connection = withContext(Dispatchers.IO) { usbManager.openDevice(device) }
|
||||
if (connection == null) {
|
||||
AppLogger.hid.warn("Failed to open HID device $deviceName")
|
||||
continue
|
||||
}
|
||||
|
||||
connection.claimInterface(iface, true)
|
||||
|
||||
val serial = device.serialNumber ?: deviceName
|
||||
AppLogger.hid.info("HID device detected: $serial")
|
||||
|
||||
val deviceJob = Job(scope.coroutineContext[Job])
|
||||
val deviceScope = CoroutineScope(scope.coroutineContext + deviceJob)
|
||||
|
||||
val receiver = HIDReceiver.create(
|
||||
serialNumber = serial,
|
||||
appContext = appContext,
|
||||
scope = deviceScope,
|
||||
)
|
||||
|
||||
deviceScope.safeLaunch {
|
||||
try {
|
||||
val buffer = ByteArray(64)
|
||||
while (isActive) {
|
||||
val read = withContext(Dispatchers.IO) {
|
||||
try {
|
||||
connection.bulkTransfer(endpoint, buffer, buffer.size, 0)
|
||||
} catch (_: Exception) {
|
||||
-1
|
||||
}
|
||||
}
|
||||
when {
|
||||
read < 0 -> return@safeLaunch
|
||||
read > 0 -> parseHIDPackets(buffer.copyOf(read)).forEach { packet -> receiver.packetEvents.emit(packet) }
|
||||
else -> delay(1)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
withContext(NonCancellable + Dispatchers.IO) {
|
||||
connection.releaseInterface(iface)
|
||||
connection.close()
|
||||
}
|
||||
withContext(NonCancellable) {
|
||||
for (record in receiver.context.state.value.trackers.values) {
|
||||
appContext.server.getDevice(record.deviceId)?.context?.dispatch(
|
||||
DeviceActions.Update { copy(status = TrackerStatus.DISCONNECTED) },
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
deviceJob.complete()
|
||||
|
||||
active[deviceName] = ActiveReceiver(deviceJob, receiver)
|
||||
}
|
||||
|
||||
permissionRequested.retainAll(found.keys)
|
||||
withTimeoutOrNull(HID_POLL_INTERVAL_MS) { wakeSignal.receive() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package dev.slimevr.android.ipc
|
||||
|
||||
import com.google.flatbuffers.FlatBufferBuilder
|
||||
import dev.slimevr.AppContextProvider
|
||||
import dev.slimevr.AppLogger
|
||||
import dev.slimevr.VRServerActions
|
||||
import dev.slimevr.fbscodegen.runtime.JvmFlatBufferReader
|
||||
import dev.slimevr.fbscodegen.runtime.JvmFlatBufferWriter
|
||||
import dev.slimevr.solarxr.SolarXRBridge
|
||||
import dev.slimevr.solarxr.onSolarXRMessage
|
||||
import io.ktor.server.application.install
|
||||
import io.ktor.server.cio.CIO
|
||||
import io.ktor.server.engine.embeddedServer
|
||||
import io.ktor.server.routing.routing
|
||||
import io.ktor.server.websocket.WebSockets
|
||||
import io.ktor.server.websocket.webSocket
|
||||
import io.ktor.util.moveToByteArray
|
||||
import io.ktor.websocket.Frame
|
||||
import kotlinx.coroutines.awaitCancellation
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import kotlinx.coroutines.flow.flow
|
||||
import solarxr_protocol.MessageBundle
|
||||
import java.nio.ByteBuffer
|
||||
|
||||
const val SOLARXR_PORT = 21110
|
||||
|
||||
suspend fun createAndroidSolarXRWebsocketServer(appContext: AppContextProvider) {
|
||||
val engine = embeddedServer(CIO, port = SOLARXR_PORT) {
|
||||
install(WebSockets)
|
||||
|
||||
routing {
|
||||
webSocket {
|
||||
AppLogger.ipc.info("New connection")
|
||||
coroutineScope {
|
||||
val bridge = SolarXRBridge.create(
|
||||
id = appContext.server.nextHandle(),
|
||||
appContext = appContext,
|
||||
scope = this,
|
||||
)
|
||||
|
||||
appContext.server.context.dispatch(VRServerActions.SolarXRConnected(bridge))
|
||||
|
||||
bridge.outbound.on<MessageBundle> { bundle ->
|
||||
val fbb = FlatBufferBuilder(256)
|
||||
fbb.finish(bundle.encode(JvmFlatBufferWriter(fbb)))
|
||||
send(Frame.Binary(fin = true, data = fbb.dataBuffer().moveToByteArray()))
|
||||
}
|
||||
|
||||
try {
|
||||
flow {
|
||||
for (frame in incoming) {
|
||||
when (frame) {
|
||||
is Frame.Binary -> emit(frame.data)
|
||||
is Frame.Close -> AppLogger.ipc.info("Connection closed")
|
||||
else -> {}
|
||||
}
|
||||
}
|
||||
}.collect { bytes ->
|
||||
val reader = JvmFlatBufferReader(ByteBuffer.wrap(bytes))
|
||||
onSolarXRMessage(MessageBundle.decode(reader, reader.getInt(0)), bridge)
|
||||
}
|
||||
} finally {
|
||||
bridge.disconnect()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
engine.start(wait = false)
|
||||
try {
|
||||
awaitCancellation()
|
||||
} finally {
|
||||
engine.stop()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package dev.slimevr.android
|
||||
|
||||
import io.klogging.Level
|
||||
import io.klogging.config.loggingConfiguration
|
||||
import io.klogging.sending.ANDROID
|
||||
|
||||
fun setupAndroidLogging() {
|
||||
loggingConfiguration {
|
||||
sink("android", ANDROID)
|
||||
logging {
|
||||
fromMinLevel(Level.DEBUG) {
|
||||
toSink("android")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,314 +0,0 @@
|
||||
package dev.slimevr.android.serial
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.hardware.usb.UsbManager
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.hoho.android.usbserial.driver.UsbSerialDriver
|
||||
import com.hoho.android.usbserial.driver.UsbSerialPort
|
||||
import com.hoho.android.usbserial.driver.UsbSerialProber
|
||||
import com.hoho.android.usbserial.util.SerialInputOutputManager
|
||||
import dev.slimevr.serial.SerialHandler
|
||||
import dev.slimevr.serial.SerialListener
|
||||
import io.eiren.util.logging.LogManager
|
||||
import java.io.IOException
|
||||
import java.nio.ByteBuffer
|
||||
import java.nio.charset.StandardCharsets
|
||||
import java.util.concurrent.CopyOnWriteArrayList
|
||||
import java.util.stream.Stream
|
||||
import kotlin.streams.asSequence
|
||||
import kotlin.streams.asStream
|
||||
import dev.slimevr.serial.SerialPort as SlimeSerialPort
|
||||
|
||||
class SerialPortWrapper(val port: UsbSerialPort) : SlimeSerialPort() {
|
||||
override val portLocation: String
|
||||
get() = port.device.deviceName
|
||||
override val descriptivePortName: String
|
||||
get() = "${port.device.productName} (${port.device.deviceName})"
|
||||
|
||||
override val vendorId: Int
|
||||
get() = port.device.vendorId
|
||||
|
||||
override val productId: Int
|
||||
get() = port.device.productId
|
||||
}
|
||||
|
||||
class AndroidSerialHandler(val activity: AppCompatActivity) :
|
||||
SerialHandler(),
|
||||
SerialInputOutputManager.Listener {
|
||||
|
||||
private var usbIoManager: SerialInputOutputManager? = null
|
||||
|
||||
private val listeners: MutableList<SerialListener> = CopyOnWriteArrayList()
|
||||
private var lastKnownPorts = setOf<SerialPortWrapper>()
|
||||
private val manager = activity.getSystemService(Context.USB_SERVICE) as UsbManager
|
||||
private var currentPort: SerialPortWrapper? = null
|
||||
private var requestingPermission: String = ""
|
||||
private var readBuffer: StringBuilder = StringBuilder(1024)
|
||||
|
||||
override val isConnected: Boolean
|
||||
get() = currentPort?.port?.isOpen ?: false
|
||||
|
||||
override val knownPorts: Stream<SerialPortWrapper>
|
||||
get() = getPorts()
|
||||
.asSequence()
|
||||
.map { SerialPortWrapper(it.ports[0]) }
|
||||
.filter { isKnownBoard(it) }
|
||||
.asStream()
|
||||
|
||||
val usbReceiver: BroadcastReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(context: Context, intent: Intent) {
|
||||
when (intent.action) {
|
||||
UsbManager.ACTION_USB_DEVICE_ATTACHED, UsbManager.ACTION_USB_DEVICE_DETACHED -> {
|
||||
// Use device from `UsbManager.EXTRA_DEVICE` if this is a problem
|
||||
detectNewPorts()
|
||||
}
|
||||
|
||||
ACTION_USB_PERMISSION -> {
|
||||
// TODO: We can probably receive this event in the server to avoid
|
||||
// polling, but for now we can just ignore it. (Note: This event is
|
||||
// not currently registered, so it will never fire.)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
init {
|
||||
val intentFilter = IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED)
|
||||
intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
|
||||
|
||||
// Listen for USB device attach/detach
|
||||
ContextCompat.registerReceiver(
|
||||
activity,
|
||||
usbReceiver,
|
||||
intentFilter,
|
||||
ContextCompat.RECEIVER_NOT_EXPORTED,
|
||||
)
|
||||
|
||||
// Detect initial serial ports
|
||||
detectNewPorts()
|
||||
}
|
||||
|
||||
private fun getPorts(): List<UsbSerialDriver> = UsbSerialProber.getDefaultProber().findAllDrivers(manager)
|
||||
|
||||
private fun onNewDevice(port: SerialPortWrapper) {
|
||||
// If we missed clearing this on disconnect/close, clear it on discovery
|
||||
if (requestingPermission == port.portLocation) {
|
||||
requestingPermission = ""
|
||||
}
|
||||
|
||||
LogManager.info("[SerialHandler] Device added: ${port.descriptivePortName}")
|
||||
listeners.forEach { it.onNewSerialDevice(port) }
|
||||
}
|
||||
|
||||
private fun onDeviceDel(port: SerialPortWrapper) {
|
||||
// Remove permission request on disconnect so reconnecting re-requests
|
||||
if (requestingPermission == port.portLocation) {
|
||||
requestingPermission = ""
|
||||
}
|
||||
|
||||
// If we're currently using this port, close it
|
||||
currentPort?.portLocation.let { currentPortLocation ->
|
||||
if (currentPortLocation == port.portLocation) {
|
||||
closeSerial()
|
||||
}
|
||||
}
|
||||
|
||||
// If this port is still open for whatever reason, close it
|
||||
if (port.port.isOpen) {
|
||||
port.port.close()
|
||||
}
|
||||
|
||||
LogManager.info("[SerialHandler] Device removed: ${port.descriptivePortName}")
|
||||
listeners.forEach { it.onSerialDeviceDeleted(port) }
|
||||
}
|
||||
|
||||
private fun detectNewPorts() {
|
||||
val addDifferences = knownPorts.asSequence() - lastKnownPorts
|
||||
val delDifferences = lastKnownPorts - knownPorts.asSequence().toSet()
|
||||
lastKnownPorts = knownPorts.asSequence().toSet()
|
||||
addDifferences.forEach { onNewDevice(it) }
|
||||
delDifferences.forEach { onDeviceDel(it) }
|
||||
}
|
||||
|
||||
override fun addListener(channel: SerialListener) {
|
||||
listeners.add(channel)
|
||||
}
|
||||
|
||||
override fun removeListener(channel: SerialListener) {
|
||||
listeners.removeIf { channel === it }
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun openSerial(portLocation: String?, auto: Boolean): Boolean {
|
||||
LogManager.info("[SerialHandler] Trying to open: $portLocation, auto: $auto")
|
||||
lastKnownPorts = knownPorts.asSequence().toSet()
|
||||
val newPort = lastKnownPorts.find {
|
||||
(!auto && it.portLocation == portLocation) || (auto && isKnownBoard(it))
|
||||
}
|
||||
|
||||
if (newPort == null) {
|
||||
LogManager.info(
|
||||
"[SerialHandler] No serial ports found to connect to (${lastKnownPorts.size}) total ports",
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
if (isConnected) {
|
||||
val port = currentPort!!
|
||||
if (newPort != port) {
|
||||
LogManager.info(
|
||||
"[SerialHandler] Closing current serial port " +
|
||||
port.descriptivePortName,
|
||||
)
|
||||
closeSerial()
|
||||
} else {
|
||||
LogManager.info("[SerialHandler] Reusing already open port")
|
||||
listeners.forEach { it.onSerialConnected(port) }
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
LogManager.info(
|
||||
"[SerialHandler] Trying to connect to new serial port " +
|
||||
newPort.descriptivePortName,
|
||||
)
|
||||
|
||||
if (!manager.hasPermission(newPort.port.device)) {
|
||||
val flags = PendingIntent.FLAG_IMMUTABLE
|
||||
val usbPermissionIntent = PendingIntent.getBroadcast(
|
||||
activity,
|
||||
0,
|
||||
Intent(ACTION_USB_PERMISSION),
|
||||
flags,
|
||||
)
|
||||
if (requestingPermission != newPort.portLocation) {
|
||||
LogManager.info("[SerialHandler] Requesting permission for ${newPort.portLocation}")
|
||||
manager.requestPermission(newPort.port.device, usbPermissionIntent)
|
||||
requestingPermission = newPort.portLocation
|
||||
} else {
|
||||
LogManager.info("[SerialHandler] Already requested permission for ${newPort.portLocation}, skipping")
|
||||
}
|
||||
LogManager.warning(
|
||||
"[SerialHandler] Can't open serial port ${newPort.descriptivePortName}, invalid permissions",
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
// If we have permission, we aren't requesting anymore
|
||||
requestingPermission = ""
|
||||
|
||||
val connection = manager.openDevice(newPort.port.device)
|
||||
if (connection == null) {
|
||||
LogManager.warning(
|
||||
"[SerialHandler] Can't open serial port ${newPort.descriptivePortName}, connection failed",
|
||||
)
|
||||
return false
|
||||
}
|
||||
newPort.port.open(connection)
|
||||
newPort.port.setParameters(115200, 8, 1, UsbSerialPort.PARITY_NONE)
|
||||
usbIoManager = SerialInputOutputManager(newPort.port, this).apply {
|
||||
start()
|
||||
}
|
||||
listeners.forEach { it.onSerialConnected(newPort) }
|
||||
currentPort = newPort
|
||||
LogManager.info("[SerialHandler] Serial port ${newPort.descriptivePortName} is open")
|
||||
return true
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
private fun writeSerial(serialText: String, print: Boolean = false) {
|
||||
try {
|
||||
currentPort?.port?.write("${serialText}\n".toByteArray(), 0)
|
||||
if (print) {
|
||||
addLog("-> $serialText\n")
|
||||
}
|
||||
} catch (e: IOException) {
|
||||
addLog("[!] Serial error: ${e.message}\n")
|
||||
LogManager.warning("[SerialHandler] Serial port write error", e)
|
||||
}
|
||||
}
|
||||
|
||||
override fun rebootRequest() {
|
||||
writeSerial("REBOOT")
|
||||
}
|
||||
|
||||
override fun factoryResetRequest() {
|
||||
writeSerial("FRST")
|
||||
}
|
||||
|
||||
override fun infoRequest() {
|
||||
writeSerial("GET INFO")
|
||||
}
|
||||
|
||||
override fun wifiScanRequest() {
|
||||
writeSerial("GET WIFISCAN")
|
||||
}
|
||||
|
||||
override fun customCommandRequest(command: String) {
|
||||
writeSerial(command)
|
||||
}
|
||||
|
||||
override fun closeSerial() {
|
||||
try {
|
||||
if (isConnected) {
|
||||
currentPort?.port?.close()
|
||||
}
|
||||
listeners.forEach { it.onSerialDisconnected() }
|
||||
LogManager.info(
|
||||
"[SerialHandler] Port ${currentPort?.descriptivePortName} closed okay",
|
||||
)
|
||||
usbIoManager?.stop()
|
||||
usbIoManager = null
|
||||
currentPort = null
|
||||
requestingPermission = ""
|
||||
readBuffer.clear()
|
||||
} catch (e: Exception) {
|
||||
LogManager.warning(
|
||||
"[SerialHandler] Error closing port ${currentPort?.descriptivePortName}",
|
||||
e,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
override fun write(buff: ByteArray) {
|
||||
currentPort?.port?.write(buff, 0)
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
override fun setWifi(ssid: String, passwd: String) {
|
||||
writeSerial("SET WIFI \"${ssid}\" \"${passwd}\"")
|
||||
addLog("-> SET WIFI \"$ssid\" \"${passwd.replace(".".toRegex(), "*")}\"\n")
|
||||
}
|
||||
|
||||
override fun getCurrentPort(): SlimeSerialPort? = this.currentPort
|
||||
|
||||
private fun addLog(str: String, server: Boolean = true) {
|
||||
LogManager.info("[Serial] $str")
|
||||
listeners.forEach { it.onSerialLog(str, server) }
|
||||
}
|
||||
|
||||
override fun onNewData(data: ByteArray?) {
|
||||
if (data != null) {
|
||||
// Collect serial in a buffer until newline (or character limit)
|
||||
// This is somewhat of a workaround for Android serial buffer being smaller
|
||||
// than on desktop, so we don't read full lines and it causes parsing issues
|
||||
readBuffer.append(StandardCharsets.UTF_8.decode(ByteBuffer.wrap(data)))
|
||||
|
||||
if (readBuffer.contains('\n') || readBuffer.length >= 1024) {
|
||||
addLog(readBuffer.toString(), false)
|
||||
readBuffer.clear()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onRunError(e: java.lang.Exception?) {}
|
||||
|
||||
companion object {
|
||||
private const val ACTION_USB_PERMISSION = "dev.slimevr.USB_PERMISSION"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package dev.slimevr.android.serial
|
||||
|
||||
import android.hardware.usb.UsbManager
|
||||
import com.hoho.android.usbserial.driver.UsbSerialPort
|
||||
import com.hoho.android.usbserial.driver.UsbSerialProber
|
||||
import dev.llelievr.espflashkotlin.Flasher
|
||||
import dev.llelievr.espflashkotlin.FlasherSerialInterface
|
||||
import dev.llelievr.espflashkotlin.FlashingProgressListener
|
||||
import dev.slimevr.firmware.DownloadedFirmwarePart
|
||||
import dev.slimevr.firmware.FirmwareFlasher
|
||||
import dev.slimevr.serial.FlashingHandler
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
|
||||
class AndroidFlashingHandler(private val usbManager: UsbManager) : FlashingHandler {
|
||||
private var port: UsbSerialPort? = null
|
||||
private var readTimeout: Int = 1000
|
||||
private val pendingBytes = ArrayDeque<Byte>()
|
||||
|
||||
override fun openSerial(portObj: Any) {
|
||||
val portLocation = portObj as? String ?: error("expected port location string")
|
||||
val driver = UsbSerialProber.getDefaultProber()
|
||||
.findAllDrivers(usbManager)
|
||||
.find { driver -> driver.device.deviceName == portLocation }
|
||||
?: error("Unable to find serial port $portLocation")
|
||||
|
||||
val connection = usbManager.openDevice(driver.device)
|
||||
?: error("Unable to open USB device for $portLocation")
|
||||
|
||||
val usbPort = driver.ports[0]
|
||||
usbPort.open(connection)
|
||||
usbPort.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE)
|
||||
this.port = usbPort
|
||||
}
|
||||
|
||||
override fun closeSerial() {
|
||||
port?.close()
|
||||
port = null
|
||||
pendingBytes.clear()
|
||||
}
|
||||
|
||||
override fun write(data: ByteArray) {
|
||||
val p = port ?: error("no port to write")
|
||||
p.write(data, readTimeout)
|
||||
}
|
||||
|
||||
override fun read(length: Int): ByteArray {
|
||||
val p = port ?: error("no port to read")
|
||||
val result = ByteArray(length)
|
||||
var offset = 0
|
||||
|
||||
while (offset < length && pendingBytes.isNotEmpty()) {
|
||||
result[offset++] = pendingBytes.removeFirst()
|
||||
}
|
||||
|
||||
if (offset < length) {
|
||||
val remaining = ByteArray(length - offset)
|
||||
val read = p.read(remaining, readTimeout)
|
||||
remaining.copyInto(result, offset, 0, read)
|
||||
offset += read
|
||||
}
|
||||
|
||||
return result.copyOf(offset)
|
||||
}
|
||||
|
||||
override fun setDTR(value: Boolean) {
|
||||
val p = port ?: error("no port to set DTR")
|
||||
p.setDTR(value)
|
||||
}
|
||||
|
||||
override fun setRTS(value: Boolean) {
|
||||
val p = port ?: error("no port to set RTS")
|
||||
p.setRTS(value)
|
||||
}
|
||||
|
||||
override fun changeBaud(baud: Int) {
|
||||
val p = port ?: error("no port to change baud")
|
||||
p.setParameters(baud, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE)
|
||||
}
|
||||
|
||||
override fun setReadTimeout(timeout: Long) {
|
||||
readTimeout = timeout.toInt().coerceAtLeast(1)
|
||||
}
|
||||
|
||||
override fun availableBytes(): Int {
|
||||
val p = port ?: return 0
|
||||
val peekBuffer = ByteArray(256)
|
||||
val count = try {
|
||||
p.read(peekBuffer, 0)
|
||||
} catch (_: Exception) {
|
||||
0
|
||||
}
|
||||
for (i in 0 until count) pendingBytes.addLast(peekBuffer[i])
|
||||
return pendingBytes.size
|
||||
}
|
||||
|
||||
override fun flushIOBuffers() {
|
||||
val p = port ?: error("no port to flush")
|
||||
pendingBytes.clear()
|
||||
p.purgeHwBuffers(true, true)
|
||||
}
|
||||
}
|
||||
|
||||
object AndroidFirmwareFlasher : FirmwareFlasher {
|
||||
override suspend fun flash(
|
||||
portLocation: String,
|
||||
handler: FlashingHandler,
|
||||
parts: List<DownloadedFirmwarePart>,
|
||||
onProgress: (Int) -> Unit,
|
||||
) {
|
||||
val flasher = Flasher(
|
||||
object : FlasherSerialInterface {
|
||||
override fun openSerial(port: Any) = handler.openSerial(port)
|
||||
override fun closeSerial() = handler.closeSerial()
|
||||
override fun write(data: ByteArray) = handler.write(data)
|
||||
override fun read(length: Int) = handler.read(length)
|
||||
override fun setDTR(value: Boolean) = handler.setDTR(value)
|
||||
override fun setRTS(value: Boolean) = handler.setRTS(value)
|
||||
override fun changeBaud(baud: Int) = handler.changeBaud(baud)
|
||||
override fun setReadTimeout(timeout: Long) = handler.setReadTimeout(timeout)
|
||||
override fun availableBytes() = handler.availableBytes()
|
||||
override fun flushIOBuffers() = handler.flushIOBuffers()
|
||||
},
|
||||
)
|
||||
for (part in parts) {
|
||||
flasher.addBin(part.data, part.offset)
|
||||
}
|
||||
flasher.addProgressListener(
|
||||
object : FlashingProgressListener {
|
||||
override fun progress(progress: Float) {
|
||||
onProgress((progress * 100).toInt())
|
||||
}
|
||||
},
|
||||
)
|
||||
withContext(Dispatchers.IO) { flasher.flash(portLocation) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package dev.slimevr.android.serial
|
||||
|
||||
import android.app.PendingIntent
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.hardware.usb.UsbManager
|
||||
import android.util.Log
|
||||
import androidx.core.content.ContextCompat
|
||||
import com.hoho.android.usbserial.driver.UsbSerialPort
|
||||
import com.hoho.android.usbserial.driver.UsbSerialProber
|
||||
import com.hoho.android.usbserial.util.SerialInputOutputManager
|
||||
import dev.slimevr.AppLogger
|
||||
import dev.slimevr.serial.SerialPortHandle
|
||||
import dev.slimevr.serial.SerialPortInfo
|
||||
import dev.slimevr.serial.SerialServer
|
||||
import dev.slimevr.serial.isKnownSerialBoard
|
||||
import dev.slimevr.util.safeLaunch
|
||||
import kotlinx.coroutines.CoroutineScope
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.channels.Channel
|
||||
import kotlinx.coroutines.withContext
|
||||
import kotlinx.coroutines.withTimeoutOrNull
|
||||
|
||||
private const val TAG = "SerialServer"
|
||||
|
||||
private const val ACTION_USB_SERIAL_PERMISSION = "dev.slimevr.android.USB_SERIAL_PERMISSION"
|
||||
private const val POLL_INTERVAL_MS = 3000L
|
||||
|
||||
private fun openAndroidPort(
|
||||
portLocation: String,
|
||||
usbManager: UsbManager,
|
||||
scope: CoroutineScope,
|
||||
onDataReceived: suspend (String, String) -> Unit,
|
||||
onPortDisconnected: suspend (String) -> Unit,
|
||||
): SerialPortHandle? {
|
||||
val driver = UsbSerialProber.getDefaultProber()
|
||||
.findAllDrivers(usbManager)
|
||||
.find { driver -> driver.device.deviceName == portLocation }
|
||||
?: return null
|
||||
|
||||
if (!usbManager.hasPermission(driver.device)) return null
|
||||
|
||||
val connection = usbManager.openDevice(driver.device) ?: return null
|
||||
val port = driver.ports[0]
|
||||
|
||||
try {
|
||||
port.open(connection)
|
||||
port.setParameters(115200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE)
|
||||
port.dtr = false
|
||||
port.rts = false
|
||||
} catch (e: Exception) {
|
||||
Log.e(TAG, "Failed to open Android serial port $portLocation", e)
|
||||
try {
|
||||
connection.close()
|
||||
} catch (_: Exception) {}
|
||||
return null
|
||||
}
|
||||
|
||||
val readBuffer = StringBuilder(1024)
|
||||
|
||||
val ioManager = SerialInputOutputManager(
|
||||
port,
|
||||
object : SerialInputOutputManager.Listener {
|
||||
override fun onNewData(data: ByteArray) {
|
||||
readBuffer.append(data.toString(Charsets.UTF_8))
|
||||
var newlineIdx = readBuffer.indexOf("\n")
|
||||
while (newlineIdx >= 0) {
|
||||
val line = readBuffer.substring(0, newlineIdx).trimEnd()
|
||||
readBuffer.delete(0, newlineIdx + 1)
|
||||
scope.safeLaunch { onDataReceived(portLocation, line) }
|
||||
newlineIdx = readBuffer.indexOf("\n")
|
||||
}
|
||||
if (readBuffer.length >= 1024) readBuffer.clear()
|
||||
}
|
||||
|
||||
override fun onRunError(e: Exception) {
|
||||
scope.safeLaunch { onPortDisconnected(portLocation) }
|
||||
}
|
||||
},
|
||||
)
|
||||
ioManager.start()
|
||||
|
||||
return SerialPortHandle(
|
||||
portLocation = portLocation,
|
||||
descriptivePortName = "${driver.device.productName ?: portLocation} ($portLocation)",
|
||||
writeCommand = { text -> port.write("$text\n".toByteArray(), 0) },
|
||||
close = {
|
||||
ioManager.stop()
|
||||
try {
|
||||
port.close()
|
||||
} catch (_: Exception) {}
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
private suspend fun runAndroidSerialPoller(
|
||||
context: Context,
|
||||
usbManager: UsbManager,
|
||||
server: SerialServer,
|
||||
wakeSignal: Channel<Unit>,
|
||||
) {
|
||||
val permissionRequested = mutableSetOf<String>()
|
||||
var lastKnown: Set<String> = emptySet()
|
||||
val permissionIntent = PendingIntent.getBroadcast(
|
||||
context,
|
||||
0,
|
||||
Intent(ACTION_USB_SERIAL_PERMISSION).apply { setPackage(context.packageName) },
|
||||
PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
|
||||
)
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
val current = withContext(Dispatchers.IO) {
|
||||
UsbSerialProber.getDefaultProber()
|
||||
.findAllDrivers(usbManager)
|
||||
.filter { driver -> isKnownSerialBoard(driver.device.vendorId, driver.device.productId) }
|
||||
.associateBy { driver -> driver.device.deviceName }
|
||||
}
|
||||
|
||||
for ((deviceName, driver) in current) {
|
||||
if (!usbManager.hasPermission(driver.device) && deviceName !in permissionRequested) {
|
||||
AppLogger.serial.info("Requesting USB serial permission for $deviceName")
|
||||
usbManager.requestPermission(driver.device, permissionIntent)
|
||||
permissionRequested.add(deviceName)
|
||||
}
|
||||
}
|
||||
|
||||
val authorized = current.filter { (_, driver) -> usbManager.hasPermission(driver.device) }
|
||||
|
||||
val added = authorized.keys - lastKnown
|
||||
val removed = lastKnown - authorized.keys
|
||||
|
||||
for (loc in added) {
|
||||
val driver = authorized.getValue(loc)
|
||||
permissionRequested.remove(loc)
|
||||
server.onPortDetected(
|
||||
SerialPortInfo(
|
||||
portLocation = loc,
|
||||
descriptivePortName = "${driver.device.productName ?: loc} ($loc)",
|
||||
vendorId = driver.device.vendorId,
|
||||
productId = driver.device.productId,
|
||||
),
|
||||
)
|
||||
}
|
||||
for (loc in removed) {
|
||||
server.onPortLost(loc)
|
||||
}
|
||||
|
||||
lastKnown = authorized.keys
|
||||
permissionRequested.retainAll(current.keys)
|
||||
} catch (e: Exception) {
|
||||
AppLogger.serial.error(e, "Error polling Android serial ports")
|
||||
}
|
||||
|
||||
withTimeoutOrNull(POLL_INTERVAL_MS) { wakeSignal.receive() }
|
||||
}
|
||||
}
|
||||
|
||||
fun createAndroidSerialServer(context: Context, scope: CoroutineScope): SerialServer {
|
||||
val usbManager = context.getSystemService(Context.USB_SERVICE) as UsbManager
|
||||
val wakeSignal = Channel<Unit>(Channel.CONFLATED)
|
||||
|
||||
val usbReceiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(ctx: Context, intent: Intent) {
|
||||
wakeSignal.trySend(Unit)
|
||||
}
|
||||
}
|
||||
|
||||
val intentFilter = IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED).apply {
|
||||
addAction(UsbManager.ACTION_USB_DEVICE_DETACHED)
|
||||
addAction(ACTION_USB_SERIAL_PERMISSION)
|
||||
}
|
||||
ContextCompat.registerReceiver(context, usbReceiver, intentFilter, ContextCompat.RECEIVER_NOT_EXPORTED)
|
||||
|
||||
val server = SerialServer.create(
|
||||
openPort = { portLocation, onDataReceived, onPortDisconnected ->
|
||||
openAndroidPort(portLocation, usbManager, scope, onDataReceived, onPortDisconnected)
|
||||
},
|
||||
openFlashingPort = { AndroidFlashingHandler(usbManager) },
|
||||
scope = scope,
|
||||
)
|
||||
|
||||
scope.safeLaunch { runAndroidSerialPoller(context, usbManager, server, wakeSignal) }
|
||||
|
||||
return server
|
||||
}
|
||||
Loaded 100 of 529 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user