diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index 5c847e25..8803ed51 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -9,7 +9,10 @@ body: attributes: label: Describe the bug description: A clear and concise description of what the bug is. - placeholder: Please describe the bug here... + placeholder: | + Please describe the bug here... + *** Do NOT use AI to generate a bug report *** + Write down what is wrong, attach logs and screenshots when relevant. validations: required: true @@ -22,12 +25,6 @@ body: 2. Click on '...' 3. See error - - type: input - attributes: - label: Expected behavior - description: A clear and concise description of what you expected to happen. - placeholder: Please describe what you expected to happen. - - type: input attributes: label: WiVRn Version @@ -42,20 +39,6 @@ body: description: Describe how WiVRn and OpenComposite/xrizer were installed placeholder: flatpak --user, flatpak, AUR, Gentoo/Guru, built from sources... - - type: textarea - attributes: - label: Server Config - description: | - Provide the content of `config.json` for the server. - Located in `${XDG_CONFIG_HOME-${HOME}/.config}/wivrn/config.json` - or `~/.var/app/io.github.wivrn.wivrn/config/wivrn/config.json` for the flatpak version - placeholder: | - { - "encoders": [ - {"codec": "h264"} - ] - } - - type: textarea attributes: label: Server Logs @@ -64,18 +47,6 @@ body: Add the output of the wivrn-server here. If more than a few lines, prefer file attachment. - - type: dropdown - id: gpu - attributes: - label: What GPU did the bug occur on? - options: - - NVIDIA - - AMD - - Intel - - Other - validations: - required: true - - type: textarea attributes: label: Vulkan Info @@ -107,5 +78,5 @@ body: attributes: label: ADB Logs description: Provide the output of `adb logcat` command. - render: plain + render: text placeholder: Attach the output of adb logcat as a file. diff --git a/.github/workflows/APK-Release.yml b/.github/workflows/APK-Release.yml index c3284951..d7a607ac 100644 --- a/.github/workflows/APK-Release.yml +++ b/.github/workflows/APK-Release.yml @@ -25,16 +25,18 @@ jobs: ref: ${{ github.sha }} fetch-depth: 0 - - name: Prepare Vulkan SDK - uses: humbletim/setup-vulkan-sdk@v1.2.1 + # Gradle distribution and the Android plugin's dependencies. + - uses: actions/cache@v5 with: - vulkan-query-version: 1.3.296.0 - vulkan-components: Glslang, SPIRV-Tools - vulkan-use-cache: true + key: gradle-android-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'build.gradle') }} + path: | + ~/.gradle/caches + ~/.gradle/wrapper + restore-keys: gradle-android- - name: Install dependencies run: | - sudo apt-get update && sudo apt-get install glslang-tools librsvg2-bin gettext npm + sudo apt-get update && sudo apt-get install glslang-tools spirv-tools librsvg2-bin gettext npm wget https://github.com/KhronosGroup/KTX-Software/releases/download/v4.4.0/KTX-Software-4.4.0-Linux-x86_64.deb sudo dpkg --install KTX-Software-4.4.0-Linux-x86_64.deb npm install --global @gltf-transform/cli@4.1.1 diff --git a/.github/workflows/Build.yml b/.github/workflows/Build.yml index da376320..7e561ad1 100644 --- a/.github/workflows/Build.yml +++ b/.github/workflows/Build.yml @@ -30,7 +30,6 @@ jobs: # Perfetto SDK glue don't bitrot (WIVRN_TRACE_MONADO needs percetto, not packaged in CI) - preset: 'server-tracing' packages: libboost-all-dev libsystemd-dev - perfetto: true - preset: 'server-no-systemd' packages: libboost-all-dev - preset: 'server-no-system-boost' @@ -42,7 +41,7 @@ jobs: - name: Apt dependencies uses: awalsh128/cache-apt-pkgs-action@v1.6.1 with: - packages: ccache ${{matrix.config.packages}} ${{ startsWith(matrix.config.preset, 'server') && env.SERVER_DEPS || ''}} + packages: ccache libvulkan-dev glslang-tools spirv-tools libwayland-dev libxrandr-dev ${{matrix.config.packages}} ${{ startsWith(matrix.config.preset, 'server') && env.SERVER_DEPS || ''}} - name: ccache uses: hendrikmuhs/ccache-action@v1.2.23 @@ -69,15 +68,8 @@ jobs: sudo dpkg --install KTX-Software-4.4.2-Linux-x86_64.deb npm install --global @gltf-transform/cli@4.1.1 - - name: Prepare Vulkan SDK - uses: humbletim/setup-vulkan-sdk@v1.2.1 - with: - vulkan-query-version: 1.3.296.0 - vulkan-components: Vulkan-Headers, Vulkan-Loader, Glslang, SPIRV-Reflect, SPIRV-Tools - vulkan-use-cache: true - - name: Fetch Perfetto SDK - if: ${{ matrix.config.perfetto }} + if: ${{ matrix.config.preset == 'server-tracing' }} # The amalgamated SDK is two files; install them where server/CMakeLists.txt looks. env: PERFETTO_TAG: v51.0 @@ -130,7 +122,8 @@ jobs: runs-on: ubuntu-24.04 if: ${{ vars.APK_ONLY == '' }} container: - image: ghcr.io/flathub-infra/flatpak-github-actions:kde-6.9 + # Tag matches runtime-version in the manifest. + image: ghcr.io/flathub-infra/flatpak-github-actions:kde-6.10 options: --privileged steps: @@ -192,13 +185,6 @@ jobs: with: fetch-depth: 0 - - name: Prepare Vulkan SDK - uses: humbletim/setup-vulkan-sdk@v1.2.1 - with: - vulkan-query-version: 1.3.296.0 - vulkan-components: Glslang, SPIRV-Tools - vulkan-use-cache: true - - uses: actions/cache@v5 with: key: cmake-android-${{matrix.buildtype}} @@ -210,9 +196,18 @@ jobs: ${{github.workspace}}/cmake-fetch/*.tgz restore-keys: cmake-android- + # Gradle distribution and the Android plugin's dependencies. + - uses: actions/cache@v5 + with: + key: gradle-android-${{ hashFiles('gradle/wrapper/gradle-wrapper.properties', 'build.gradle') }} + path: | + ~/.gradle/caches + ~/.gradle/wrapper + restore-keys: gradle-android- + - name: Install dependencies run: | - sudo apt-get update && sudo apt-get install glslang-tools librsvg2-bin gettext + sudo apt-get update && sudo apt-get install glslang-tools spirv-tools librsvg2-bin gettext wget https://github.com/KhronosGroup/KTX-Software/releases/download/v4.3.2/KTX-Software-4.3.2-Linux-x86_64.deb sudo dpkg --install KTX-Software-4.3.2-Linux-x86_64.deb npm install --global @gltf-transform/cli diff --git a/.github/workflows/Locales.yml b/.github/workflows/Locales.yml index 772a4db4..2c0878e9 100644 --- a/.github/workflows/Locales.yml +++ b/.github/workflows/Locales.yml @@ -8,15 +8,25 @@ jobs: steps: - uses: actions/checkout@v6 + - name: Apt dependencies + uses: awalsh128/cache-apt-pkgs-action@v1.6.1 + with: + packages: gettext + - name: Install dependencies run: | - sudo apt-get update && sudo apt-get install gettext pip install polib PyGithub - name: Check that .po files are up to date + env: + GH_TOKEN: ${{ github.token }} run: | if [[ "${{github.ref}}" == 'refs/heads/master' ]] ; then tools/check_po.py --manage-issues --github-repository "${{ github.repository }}" --github-token "${{ github.token }}" + elif [[ "${{github.base_ref}}" != "" ]] ; then + FILES=$(gh api repos/${{github.repository}}/pulls/${{github.event.pull_request.number}}/files | jq --raw-output '[.[].filename | select(. | startswith("locale/"))] | join(",")') + echo "Locale files changed by pull request: ${FILES}" + tools/check_po.py --fail-on "${FILES}" else tools/check_po.py fi diff --git a/AndroidManifest.xml b/AndroidManifest.xml index e53a7388..a2441b0c 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -30,6 +30,7 @@ + diff --git a/CMakeLists.txt b/CMakeLists.txt index 8ddb7d23..285d2a74 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -35,7 +35,6 @@ option(WIVRN_USE_SYSTEM_FREETYPE "Use system FreeType" ON) option(WIVRN_USE_SYSTEM_BOOST "Use system Boost headers" ON) option(WIVRN_USE_SYSTEM_OPENXR "Use system OpenXR headers" ON) option(WIVRN_USE_SYSTEM_LIBKTX "Use system KTX-Software library" ON) -option(WIVRN_USE_SYSTEMD "Use libsystemd" ON) option(WIVRN_COMPRESS_GLB "Compress textures in GLB files with gltf-transform" OFF) option(WIVRN_USE_ANDROID_VALIDATION_LAYER "Download the android version of the Vulkan validation layer" OFF) option(WIVRN_USE_ANDROID_BIN_LIBKTX "Download the prebuilt libktx for android" OFF) @@ -49,6 +48,7 @@ option(WIVRN_BUILD_TEST "Build test binaries" OFF) option(WIVRN_WERROR "Treat warnings as errors" OFF) option(WIVRN_OPTIMIZE_SHADERS "Run spirv-opt on compiled shaders" ON) option(WIVRN_DEBUG_SHADERS "Compile shaders with debug information" OFF) +option(WIVRN_ADDRESS_SANITIZER "Use address sanitizer" OFF) if(WIVRN_OPTIMIZE_SHADERS AND WIVRN_DEBUG_SHADERS) message(FATAL_ERROR "WIVRN_OPTIMIZE_SHADERS and WIVRN_DEBUG_SHADERS are incompatible") @@ -123,8 +123,8 @@ endif() if (WIVRN_BUILD_SERVER) find_program(GDBUS_CODEGEN gdbus-codegen REQUIRED) - if (Vulkan_VERSION VERSION_LESS "1.3.261") - message(FATAL_ERROR "Vulkan version must be at least 1.3.261, found ${Vulkan_VERSION}") + if (Vulkan_VERSION VERSION_LESS "1.4.304") + message(FATAL_ERROR "Vulkan version must be at least 1.4.304, found ${Vulkan_VERSION}") endif() if (NOT WIVRN_USE_NVENC AND NOT WIVRN_USE_VAAPI AND NOT WIVRN_USE_X264 AND NOT WIVRN_USE_VULKAN_ENCODE) @@ -136,20 +136,10 @@ if (WIVRN_BUILD_SERVER) pkg_check_modules(LIBDRM REQUIRED IMPORTED_TARGET libdrm) endif() - if (WIVRN_USE_VULKAN_ENCODE) - if (Vulkan_VERSION VERSION_LESS 1.3.283) - message(FATAL_ERROR "Vulkan video encode requires 1.3.283, found ${Vulkan_VERSION}") - endif() - endif() - if (WIVRN_USE_X264) pkg_check_modules(X264 REQUIRED IMPORTED_TARGET x264) endif() - if (WIVRN_USE_SYSTEMD) - pkg_check_modules(SYSTEMD REQUIRED IMPORTED_TARGET libsystemd) - endif() - if (WIVRN_USE_PIPEWIRE) pkg_check_modules(libpipewire REQUIRED IMPORTED_TARGET libpipewire-0.3) endif() @@ -259,17 +249,17 @@ set(KTX_VERSION_FULL "v${KTX_VERSION}") FetchContent_Declare(libktx EXCLUDE_FROM_ALL SYSTEM URL https://github.com/KhronosGroup/KTX-Software/archive/refs/tags/${KTX_VERSION_FULL}.tar.gz URL_HASH SHA256=9412cb45045a503005acd47d98f9e8b47154634a50b4df21e17a1dfa8971d323 ) -FetchContent_Declare(implot EXCLUDE_FROM_ALL SYSTEM URL https://github.com/epezent/implot/archive/3da8bd34299965d3b0ab124df743fe3e076fa222.zip - URL_HASH SHA256=e9b439a94aa6f09fcf12ed9c2cd784efe5e99e96242122aa683e690b29f7a59f) +FetchContent_Declare(implot EXCLUDE_FROM_ALL SYSTEM URL https://github.com/epezent/implot/releases/download/v1.0/implot-v1.0.tar.gz + URL_HASH SHA256=20ca14d5a46f36a650746096c74eba8bea99c9432cd3c877343b96b17a6ae566) file(GLOB IMGUI_PATCHES CONFIGURE_DEPENDS patches/imgui/*) -FetchContent_Declare(imgui EXCLUDE_FROM_ALL SYSTEM URL https://github.com/ocornut/imgui/archive/refs/tags/v1.92.5.tar.gz - URL_HASH SHA256=0eb50fe9aeba1a51f96b5843c7f630a32ed2e9362d693c61b87e4fa870cf826d +FetchContent_Declare(imgui EXCLUDE_FROM_ALL SYSTEM URL https://github.com/ocornut/imgui/archive/refs/tags/v1.92.9.tar.gz + URL_HASH SHA256=af97ed649182c39314320514a672b82008ab462b9293fe23d37b30bfa5d05519 PATCH_COMMAND ${CMAKE_CURRENT_LIST_DIR}/patches/apply.sh ${IMGUI_PATCHES} ) FetchContent_Declare(uni-algo EXCLUDE_FROM_ALL SYSTEM URL https://github.com/uni-algo/uni-algo/archive/v1.2.0.tar.gz URL_HASH SHA256=f2a1539cd8635bc6088d05144a73ecfe7b4d74ee0361fabed6f87f9f19e74ca9) -FetchContent_Declare(entt EXCLUDE_FROM_ALL SYSTEM URL https://github.com/skypjack/entt/archive/refs/tags/v3.16.0.tar.gz - URL_HASH SHA256=7d7b4037b737992342049ffab14f22fa10243e01664f8c3a0657aa247ac52f71) +FetchContent_Declare(entt EXCLUDE_FROM_ALL SYSTEM URL https://github.com/skypjack/entt/archive/refs/tags/v4.0.0.tar.gz + URL_HASH SHA256=32a2ff2c72cb047dfd57306006ef238820b70da7c6ce4e7e8a507ac63365212e) FetchContent_Declare(curl EXCLUDE_FROM_ALL SYSTEM URL https://github.com/curl/curl/releases/download/curl-8_17_0/curl-8.17.0.tar.xz URL_HASH SHA256=955f6e729ad6b3566260e8fef68620e76ba3c31acf0a18524416a185acf77992) FetchContent_Declare(spirv-reflect EXCLUDE_FROM_ALL SYSTEM URL https://github.com/KhronosGroup/SPIRV-Reflect/archive/refs/tags/vulkan-sdk-1.4.328.1.tar.gz @@ -312,6 +302,7 @@ if (WIVRN_BUILD_CLIENT) endif() if (WIVRN_BUILD_SERVER OR WIVRN_BUILD_SERVER_LIBRARY) + find_package(Python3 REQUIRED Interpreter) add_subdirectory(server) if (WIVRN_BUILD_SERVER) @@ -323,9 +314,6 @@ if (WIVRN_BUILD_SERVER OR WIVRN_BUILD_SERVER_LIBRARY) message(STATUS "") message(STATUS "Audio backends:") message(STATUS "\tPipewire : ${WIVRN_USE_PIPEWIRE}") - message(STATUS "") - message(STATUS "Optional features:") - message(STATUS "\tsystemd: ${WIVRN_USE_SYSTEMD}") endif() endif() @@ -355,5 +343,10 @@ foreach(TARGET_NAME wivrn wivrn-server wivrn-dashboard wivrn-common wivrn-dissec target_compile_options(${TARGET_NAME} PRIVATE -Werror) endif() + if (WIVRN_ADDRESS_SANITIZER AND NOT ${TARGET_NAME} STREQUAL wivrn-dissector) + target_compile_options(${TARGET_NAME} PRIVATE -fsanitize=address -fno-omit-frame-pointer) + target_link_options(${TARGET_NAME} PRIVATE -fsanitize=address) + endif() + endif() endforeach() diff --git a/README.md b/README.md index 0de9c77a..f4070337 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,7 @@ We recommend using native packages if available for your distribution: - [Fedora](https://packages.fedoraproject.org/pkgs/wivrn/wivrn/) - [Gentoo Guru](https://gitweb.gentoo.org/repo/proj/guru.git/tree/media-libs/wivrn) - [NixOS](https://search.nixos.org/packages?show=wivrn) +- [Ubuntu PPA](https://launchpad.net/~lvra/+archive/ubuntu/wivrn) For OpenVR and Steam compatibility, you also need a compatibility library such as [xrizer](https://github.com/Supreeeme/xrizer/) or [OpenComposite](https://gitlab.com/znixian/OpenOVR/). @@ -78,7 +79,7 @@ Avahi must be running: systemctl enable --now avahi-daemon ``` -On SteamOS, the Avahi configuration needs to be modified to allow user services such as WiVRn to publish services on the network; see https://github.com/WiVRn/WiVRn/issues/1001#issuecomment-4940906113 for instructions on how to do so. +On SteamOS, the Avahi configuration needs to be modified to allow user services such as WiVRn to publish services on the network; see https://github.com/WiVRn/WiVRn/issues/1001#issuecomment-4940906113 for instructions on how to do so. - If a firewall is installed, open port 5353/UDP for Avahi and ports 9757/UDP+TCP for WiVRn. - For example, if using UFW run `ufw allow 5353/udp` and `ufw allow 9757`. @@ -169,9 +170,10 @@ If the server list is empty in the headset app:
How do I see server logs when using the dashboard? -- Click Troubleshoot > Open server logs, or -- Navigate to `${XDG_STATE_HOME}/wivrn/wivrn-dashboard` (with fallback to `${HOME}/.local/state` for `${XDG_STATE_HOME}`, or -- For flatpak, navigate to `${HOME}/.var/app/io.github.wivrn.wivrn/.local/state/wivrn/wivrn-dashboard`.
+- Click **Troubleshoot > Open server logs** +- Or, navigate to `${XDG_STATE_HOME}/wivrn/wivrn-dashboard` + - In other words, on common setups, the dashboard writes logs to `~/.local/state/wivrn/wivrn-dashboard` + - For WiVRn Flatpak, the dashboard writes logs to `~/.var/app/io.github.wivrn.wivrn/.local/state/wivrn/wivrn-dashboard`
My NVIDIA GPU P-State is limited to P2 instead of reaching the highest P0 while using the NVIDIA NVENC encoder diff --git a/assets/Font Awesome 6 Free-Regular-400.otf b/assets/Font Awesome 6 Free-Regular-400.otf deleted file mode 100644 index 2edf2b2f..00000000 Binary files a/assets/Font Awesome 6 Free-Regular-400.otf and /dev/null differ diff --git a/assets/Font Awesome 6 Free-Solid-900.otf b/assets/Font Awesome 6 Free-Solid-900.otf deleted file mode 100644 index 6bd19b13..00000000 Binary files a/assets/Font Awesome 6 Free-Solid-900.otf and /dev/null differ diff --git a/assets/Font Awesome 7 Brands-Regular-400.otf b/assets/Font Awesome 7 Brands-Regular-400.otf new file mode 100644 index 00000000..addd48ad Binary files /dev/null and b/assets/Font Awesome 7 Brands-Regular-400.otf differ diff --git a/assets/Font Awesome 7 Free-Regular-400.otf b/assets/Font Awesome 7 Free-Regular-400.otf new file mode 100644 index 00000000..2ca9963b Binary files /dev/null and b/assets/Font Awesome 7 Free-Regular-400.otf differ diff --git a/assets/Font Awesome 7 Free-Solid-900.otf b/assets/Font Awesome 7 Free-Solid-900.otf new file mode 100644 index 00000000..af3b5782 Binary files /dev/null and b/assets/Font Awesome 7 Free-Solid-900.otf differ diff --git a/build.gradle b/build.gradle index 6d8b0470..1161658d 100644 --- a/build.gradle +++ b/build.gradle @@ -92,7 +92,7 @@ tasks.register("generatePngs", GeneratePngsTask) { } } - +def use_asan = project.hasProperty('wivrn_address_sanitizer') && wivrn_address_sanitizer == 'ON' android { namespace = "org.meumeu.wivrn" @@ -117,16 +117,20 @@ android { def compressGlb = project.hasProperty('wivrn_compress_glb') ? wivrn_compress_glb : 'OFF' def fetchcontentBaseDir = project.hasProperty('fetchcontent_base_dir') ? ['-DFETCHCONTENT_BASE_DIR=' + fetchcontent_base_dir] : [] + def asan = use_asan ? 'ON': 'OFF' + def stl = use_asan ? 'c++_shared' : "c++_static" + externalNativeBuild { def css = project.hasProperty('wivrn_css') ? project.wivrn_css: "images/wivrn-local.css" cmake { arguments = ['-DANDROID_TOOLCHAIN=clang', - '-DANDROID_STL=c++_static', + '-DANDROID_STL=' + stl, '-DCMAKE_ANDROID_NDK_VERSION=' + ndkVersion, '-DCMAKE_INTERPROCEDURAL_OPTIMIZATION=ON', '-DCMAKE_EXPORT_COMPILE_COMMANDS=ON', '-DCMAKE_ANDROID_ASSETS_DIRECTORIES=' + layout.buildDirectory.dir("assets").get().asFile, + '-DRESOURCES_DIRECTORIES=' + layout.buildDirectory.dir("resources").get().asFile, '-DWIVRN_USE_SYSTEM_BOOST=OFF', '-DWIVRN_USE_SYSTEM_FREETYPE=OFF', '-DWIVRN_USE_ANDROID_BIN_LIBKTX=ON', @@ -139,13 +143,20 @@ android { '-DWIVRN_SHOW_IMGUI_DEMO_WINDOW=' + showImguiDemo, '-DWIVRN_CLIENT_DEBUG_MENU=' + showDebugMenu, '-DWIVRN_CSS=' + css, - '-DWIVRN_COMPRESS_GLB=' + compressGlb] + + '-DWIVRN_COMPRESS_GLB=' + compressGlb, + '-DWIVRN_ADDRESS_SANITIZER=' + asan, + ] + fetchcontentBaseDir resValue "string", "app_name", project.hasProperty('wivrn_app_name') ? project.wivrn_app_name : "WiVRn Local" abiFilters 'arm64-v8a'//, 'x86_64' } } + packaging { + jniLibs { + useLegacyPackaging = use_asan + } + } } signingConfigs { @@ -226,6 +237,7 @@ android { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['client/java'] res.srcDirs = [ 'resources', layout.buildDirectory.dir('generated_resources') ] + resources.srcDirs = [layout.buildDirectory.dir('resources')] assets.srcDirs = ['assets', layout.buildDirectory.dir("assets")] } @@ -243,5 +255,6 @@ android { applicationVariants.all { variant -> // It probably works with merge${variant.name.capitalize()}Assets too tasks["generate${variant.name.capitalize()}Assets"].dependsOn "externalNativeBuild${variant.name.capitalize()}" + tasks["merge${variant.name.capitalize()}Resources"].dependsOn "externalNativeBuild${variant.name.capitalize()}" } } diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 8a497705..53df0645 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -38,6 +38,7 @@ add_library(stb INTERFACE) target_include_directories(stb INTERFACE ${stb_SOURCE_DIR}) if(ANDROID) + file(REMOVE_RECURSE ${RESOURCES_DIRECTORIES}/lib ${ANDROID_LIB_DIRECTORIES}) add_library(wivrn MODULE) find_library(ANDROID_LIBRARY NAMES android REQUIRED) @@ -80,6 +81,23 @@ if(ANDROID) "decoder/android/*.cpp" ) target_sources(wivrn PRIVATE ${PLATFORM_SOURCE}) + + if (WIVRN_ADDRESS_SANITIZER) + file(MAKE_DIRECTORY + ${RESOURCES_DIRECTORIES}/lib/${CMAKE_ANDROID_ARCH_ABI} + ${ANDROID_LIB_DIRECTORIES}/${CMAKE_ANDROID_ARCH_ABI}) + file(GLOB _asan_location + ${ANDROID_NDK}/toolchains/llvm/prebuilt/linux-x86_64/lib/clang/*/lib/linux/libclang_rt.asan-${CMAKE_SYSTEM_PROCESSOR}-android.so + ) + file(COPY + ${_asan_location} + DESTINATION ${ANDROID_LIB_DIRECTORIES}/${CMAKE_ANDROID_ARCH_ABI} + ) + file(COPY_FILE + ${ANDROID_NDK}/wrap.sh/asan.sh + ${RESOURCES_DIRECTORIES}/lib/${CMAKE_ANDROID_ARCH_ABI}/wrap.sh + ) + endif() else() add_executable(wivrn) @@ -106,8 +124,6 @@ endif() # target_compile_definitions(wivrn PRIVATE "XR_USE_TIMESPEC=1") -set_target_properties(wivrn PROPERTIES CXX_VISIBILITY_PRESET hidden) - file(GLOB LOCAL_SOURCE CONFIGURE_DEPENDS "*.cpp" "decoder/*.cpp" @@ -144,6 +160,7 @@ target_link_libraries(wivrn target_compile_definitions(wivrn PRIVATE -DXR_USE_GRAPHICS_API_VULKAN) target_compile_definitions(wivrn PRIVATE -DVMA_STATS_STRING_ENABLED=0) target_compile_definitions(wivrn PRIVATE -DGLM_ENABLE_EXPERIMENTAL) +target_compile_definitions(wivrn PRIVATE IMGUI_DEFINE_MATH_OPERATORS) target_include_directories(wivrn PRIVATE .) @@ -214,9 +231,6 @@ if(WIVRN_USE_ANDROID_VALIDATION_LAYER) file(COPY ${FETCHCONTENT_BASE_DIR}/Vulkan-ValidationLayer/android-binaries-${VVL_VERSION}/${CMAKE_ANDROID_ARCH_ABI} DESTINATION ${ANDROID_LIB_DIRECTORIES}) -else() - # silence "Manually-specified variables were not used by the project" warning - set(_unused ${ANDROID_LIB_DIRECTORIES}) endif() diff --git a/client/android/battery.cpp b/client/android/battery.cpp index c21612df..959ea440 100644 --- a/client/android/battery.cpp +++ b/client/android/battery.cpp @@ -35,7 +35,7 @@ battery_status get_battery_status() return last_status; } -extern "C" __attribute__((visibility("default"))) void Java_org_meumeu_wivrn_BroadcastReceiver_onReceive(JNIEnv * env, jobject instance, jobject ctxt_obj, jobject intent_obj) +extern "C" void Java_org_meumeu_wivrn_BroadcastReceiver_onReceive(JNIEnv * env, jobject instance, jobject ctxt_obj, jobject intent_obj) { jni::jni_thread::setup_thread(env); jni::object<"android/content/Intent"> intent{intent_obj}; diff --git a/client/android/exported_symbols.txt b/client/android/exported_symbols.txt index 42904ba3..f52eaeed 100644 --- a/client/android/exported_symbols.txt +++ b/client/android/exported_symbols.txt @@ -2,10 +2,7 @@ LIBAPP { global: ANativeActivity_onCreate; android_main; - Java_org_meumeu_wivrn_BroadcastReceiver_onReceive; - Java_org_meumeu_wivrn_MainActivity_onRequestPermissionsResult; - Java_org_meumeu_wivrn_MainActivity_onActivityResult; - Java_org_meumeu_wivrn_MainActivity_onNewIntent; + Java_org_meumeu_wivrn*; local: *; }; diff --git a/client/android/intent.cpp b/client/android/intent.cpp index c6f6d848..d884e6d4 100644 --- a/client/android/intent.cpp +++ b/client/android/intent.cpp @@ -59,7 +59,7 @@ jni::object<"android/net/Uri"> intent::get_uri() return obj.call>("getData"); } -extern "C" __attribute__((visibility("default"))) void Java_org_meumeu_wivrn_MainActivity_onActivityResult(JNIEnv * env, jobject instance, int request_code, int result_code, jobject data_obj) +extern "C" void Java_org_meumeu_wivrn_MainActivity_onActivityResult(JNIEnv * env, jobject instance, int request_code, int result_code, jobject data_obj) { auto it = callbacks.find(request_code); if (it == callbacks.end()) diff --git a/client/android/jnipp.h b/client/android/jnipp.h index 4c0ed55d..64680dc3 100644 --- a/client/android/jnipp.h +++ b/client/android/jnipp.h @@ -89,6 +89,7 @@ struct Void struct Int { constexpr static auto static_field = &_JNIEnv::GetStaticIntField; + constexpr static auto obj_field = &_JNIEnv::GetIntField; constexpr static const auto call_method = &_JNIEnv::CallIntMethod; constexpr static const auto call_static_method = &_JNIEnv::CallStaticIntMethod; @@ -277,6 +278,7 @@ struct object } std::unique_ptr, details::deleter> self; + constexpr static auto obj_field = &_JNIEnv::GetObjectField; constexpr static const auto call_method = &_JNIEnv::CallObjectMethod; constexpr static const auto call_static_method = &_JNIEnv::CallStaticObjectMethod; @@ -335,6 +337,14 @@ struct object handles)); } + template + T field(const std::string & name) + { + auto & env = jni_thread::env(); + jfieldID id = env.GetFieldID(klass(), name.c_str(), T::type().c_str()); + return T((env.*T::obj_field)(*this, id)); + } + jobject handle() const { return *this; @@ -374,6 +384,7 @@ struct string : public string_t { using string_t::type; constexpr static auto static_field = &_JNIEnv::GetStaticObjectField; + constexpr static auto obj_field = &_JNIEnv::GetObjectField; operator jstring() { diff --git a/client/android/permissions.cpp b/client/android/permissions.cpp index 9a5725ba..4fe0ddcb 100644 --- a/client/android/permissions.cpp +++ b/client/android/permissions.cpp @@ -93,7 +93,7 @@ void request_permission(const char * permission, std::function callb } } -extern "C" __attribute__((visibility("default"))) void Java_org_meumeu_wivrn_MainActivity_onRequestPermissionsResult( +extern "C" void Java_org_meumeu_wivrn_MainActivity_onRequestPermissionsResult( JNIEnv * env, jobject instance, int requestCode, diff --git a/client/android/usb.cpp b/client/android/usb.cpp new file mode 100644 index 00000000..b83c1108 --- /dev/null +++ b/client/android/usb.cpp @@ -0,0 +1,61 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2026 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "application.h" +#include "jni.h" + +#include +#include + +std::atomic_bool link_properties_changed = false; + +extern "C" void Java_org_meumeu_wivrn_NetworkInfoCallback_onAvailable(JNIEnv * env, jobject instance, jobject network) +{ + spdlog::info("NetworkInfoCallback_onAvailable"); +} +extern "C" void Java_org_meumeu_wivrn_NetworkInfoCallback_onBlockedStatusChanged(JNIEnv * env, jobject instance, jobject network, jboolean blocked) +{ + spdlog::info("NetworkInfoCallback_onBlockedStatusChanged"); +} +extern "C" void Java_org_meumeu_wivrn_NetworkInfoCallback_onCapabilitiesChanged(JNIEnv * env, jobject instance, jobject network, jobject caps) +{ + spdlog::info("NetworkInfoCallback_onCapabitilitiesChanged"); +} +extern "C" void Java_org_meumeu_wivrn_NetworkInfoCallback_onLinkPropertiesChanged(JNIEnv * env, jobject instance, jobject network, jobject jprops) +{ + link_properties_changed = true; +} +extern "C" void Java_org_meumeu_wivrn_NetworkInfoCallback_onLosing(JNIEnv * env, jobject instance, jobject network, jint ms) +{ + spdlog::info("NetworkInfoCallback_onLosing"); +} +extern "C" void Java_org_meumeu_wivrn_NetworkInfoCallback_onLost(JNIEnv * env, jobject instance, jobject network) +{ + spdlog::info("NetworkInfoCallback_onLost"); + link_properties_changed = true; +} +extern "C" void Java_org_meumeu_wivrn_NetworkInfoCallback_onUnavailable(JNIEnv * env, jobject instance) +{ + spdlog::info("NetworkInfoCallback_onUnavailable"); + application::get_config().usb_network = false; +} + +bool usb_link_properties_changed() +{ + return link_properties_changed.exchange(false); +} diff --git a/client/android/usb.h b/client/android/usb.h new file mode 100644 index 00000000..60626ff9 --- /dev/null +++ b/client/android/usb.h @@ -0,0 +1,19 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2026 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +bool usb_link_properties_changed(); diff --git a/client/application.cpp b/client/application.cpp index a3071274..cf46e87f 100644 --- a/client/application.cpp +++ b/client/application.cpp @@ -1404,7 +1404,12 @@ void application::initialize() spaces[size_t(xr::spaces::view)] = xr_session.create_reference_space(XR_REFERENCE_SPACE_TYPE_VIEW); spaces[size_t(xr::spaces::world)] = xr_session.create_reference_space(XR_REFERENCE_SPACE_TYPE_STAGE); - config.emplace(xr_system_id, xr_session); + config.emplace(xr_system_id, xr_session, application::get_config_path() / "client.json"); + default_config.emplace(xr_system_id, xr_session); + +#ifdef __ANDROID__ + set_usb_networking(config->usb_network); +#endif // HTC face tracker fails if created later // we can destroy it right away, it actually stores static handles @@ -1486,7 +1491,7 @@ std::pair application::get_action(std::string_view reque } #ifdef __ANDROID__ -extern "C" __attribute__((visibility("default"))) void Java_org_meumeu_wivrn_MainActivity_onNewIntent(JNIEnv * env, jobject instance, jobject intent_obj) +extern "C" void Java_org_meumeu_wivrn_MainActivity_onNewIntent(JNIEnv * env, jobject instance, jobject intent_obj) { jni::jni_thread::setup_thread(env); jni::object<"android/content/Intent"> intent{intent_obj}; @@ -1676,6 +1681,9 @@ void application::cleanup() #ifdef __ANDROID__ jni::jni_thread::detach(); + app_info.native_app->onAppCmd = nullptr; + app_info.native_app->onInputEvent = nullptr; + app_info.native_app->userData = nullptr; #endif } @@ -1826,6 +1834,38 @@ void application::push_scene(std::shared_ptr s) instance().scene_stack.push_back(std::move(s)); } +#ifdef __ANDROID__ +void application::set_usb_networking(bool enabled) +{ + jni::object<""> act(app_info.native_app->activity->clazz); + auto app = act.call>("getApplication"); + auto ctx = app.call>("getApplicationContext"); + auto system_service = ctx.call>("getSystemService", jni::string("connectivity")); + + auto cb = act.field>("netcb"); + try + { + if (enabled) + { + auto req = jni::new_object<"android/net/NetworkRequest$Builder">() + .call>("removeCapability", jni::Int(12) /*NET_CAPABILITY_INTERNET*/) + .call>("removeCapability", jni::Int(14) /*NET_CAPABILITY_TRUSTED*/) + .call>("addTransportType", jni::Int(8) /*TRANSPORT_USB*/) + .call>("build"); + + // system_service.call("requestNetwork", req, jni::new_object<"org/meumeu/wivrn/NetworkInfoCallback">()); + system_service.call("requestNetwork", req, cb); + } + else + { + system_service.call("unregisterNetworkCallback", cb); + } + } + catch (...) + {} +} +#endif + void application::poll_actions() { std::array action_sets{ diff --git a/client/application.h b/client/application.h index edd7c1e5..f872b557 100644 --- a/client/application.h +++ b/client/application.h @@ -55,7 +55,7 @@ class scene; #ifdef __ANDROID__ -extern "C" __attribute__((visibility("default"))) void Java_org_meumeu_wivrn_MainActivity_onNewIntent(JNIEnv * env, jobject instance, jobject intent_obj); +extern "C" void Java_org_meumeu_wivrn_MainActivity_onNewIntent(JNIEnv * env, jobject instance, jobject intent_obj); #endif struct application_info @@ -77,7 +77,7 @@ class application : public singleton private: #ifdef __ANDROID__ - friend __attribute__((visibility("default"))) void Java_org_meumeu_wivrn_MainActivity_onNewIntent(JNIEnv * env, jobject instance, jobject intent_obj); + friend void Java_org_meumeu_wivrn_MainActivity_onNewIntent(JNIEnv * env, jobject instance, jobject intent_obj); #endif application_info app_info; @@ -156,6 +156,7 @@ private: std::chrono::nanoseconds last_scene_cpu_time; std::optional config; + std::optional default_config; boost::locale::generator gen; boost::locale::gnu_gettext::messages_info messages_info; @@ -311,6 +312,10 @@ public: return *instance().wifi; } +#ifdef __ANDROID__ + void set_usb_networking(bool enabled); +#endif + static void ignore_debug_reports_for(void * object) { #ifndef NDEBUG @@ -330,8 +335,9 @@ public: template static void set_debug_reports_name(const T & object, std::string name) { - // #ifndef NDEBUG - // if (instance().debug_utils_found) + if (not vk_allocator::instance().has_debug_utils) + return; + const vk::DebugUtilsObjectNameInfoEXT name_info{ .objectType = T::objectType, .objectHandle = (uint64_t)(typename T::NativeType)object, @@ -339,10 +345,6 @@ public: }; instance().vk_device.setDebugUtilsObjectNameEXT(name_info); - - // printf("set_debug_reports_name %p, %s\n", object, name.c_str()); - // instance().debug_report_object_name[(uint64_t)object] = std::move(name); - // #endif } static thread_safe & get_queue() @@ -432,6 +434,12 @@ public: return *instance().config; } + static configuration & get_default_config() + { + assert(instance().default_config); + return *instance().default_config; + } + static XrSessionState get_session_state() { return instance().session_state; diff --git a/client/configuration.cpp b/client/configuration.cpp index 99fea686..3d31fa47 100644 --- a/client/configuration.cpp +++ b/client/configuration.cpp @@ -24,7 +24,11 @@ #include "wivrn_packets.h" #include +#include #include +#include +#include +#include #ifdef __ANDROID__ #include "android/permissions.h" @@ -33,6 +37,121 @@ // If no refresh rate is configured, don't select a too high one static const float max_default_rate = 100; +// key <-> member serialization descriptor for scalar settings (see config_fields()). +// The few settings that aren't scalars are handled explicitly in save()/load(). +struct config_field +{ + std::function save; + std::function load; +}; + +namespace +{ +template +inline constexpr bool is_optional_v = false; +template +inline constexpr bool is_optional_v> = true; + +template +struct remove_optional +{ + using type = T; +}; +template +struct remove_optional> +{ + using type = T; +}; + +std::ostream & operator<<(std::ostream & stream, feature f) +{ + return stream << "\"" << magic_enum::enum_name(f) << "\""; +} + +template +void write_value(std::ostream & json, const T & value) +{ + if constexpr (std::is_same_v) + json << std::boolalpha << value; + else if constexpr (std::is_same_v) + json << json_string(value); + else if constexpr (std::is_enum_v) + json << json_string(magic_enum::enum_name(value)); + else if constexpr (std::is_integral_v) + json << (uint64_t)value; + else // floating point + json << value; +} + +template +std::optional read_value(simdjson::simdjson_result val) +{ + if constexpr (std::is_same_v) + { + if (val.is_bool()) + return val.get_bool(); + } + else if constexpr (std::is_same_v) + { + if (val.is_string()) + return std::string(std::string_view(val.get_string().value())); + } + else if constexpr (std::is_enum_v) + { + if (val.is_string()) + { + auto name = val.get_string().value(); + for (const auto & [e, n]: magic_enum::enum_entries()) + if (name == n) + return e; + } + } + else if constexpr (std::is_integral_v) + { + if (val.is_uint64()) + return (T)val.get_uint64(); + if (val.is_int64() and int64_t(val.get_int64()) >= 0) + return (T)val.get_int64(); + } + else // floating point + { + if (val.is_double()) + return (T)val.get_double(); + if (val.is_int64()) + return (T)val.get_int64(); + if (val.is_uint64()) + return (T)val.get_uint64(); + } + return std::nullopt; +} + +// build a field for a plain member: bool / float / integral / std::string / enum, +// optionally wrapped in std::optional (only written when set) +template +config_field scalar(const char * key, T configuration::* member) +{ + return { + .save = [key, member](std::ostream & json, const configuration & c) { + if constexpr (is_optional_v) + { + if (c.*member) + { + json << ",\"" << key << "\":"; + write_value(json, *(c.*member)); + } + } + else + { + json << ",\"" << key << "\":"; + write_value(json, c.*member); + } }, + .load = [key, member](simdjson::dom::element root, configuration & c) { + if (auto v = read_value::type>(root[key])) + c.*member = *v; }, + }; +} +} // namespace + bool configuration::check_feature(feature f) const { { @@ -105,17 +224,22 @@ configuration::configuration(xr::system & system, xr::session & session) features[feature::hand_tracking] = system.hand_tracking_supported(); const auto & rates = session.get_refresh_rates(); + preferred_refresh_rate = rates.empty() ? 0 : rates[0]; for (auto rate: rates) { if (rate >= max_default_rate) break; preferred_refresh_rate = rate; } +} +configuration::configuration(xr::system & system, xr::session & session, const std::filesystem::path & config_path) : + configuration(system, session) +{ try { simdjson::dom::parser parser; - simdjson::dom::element root = parser.load((application::get_config_path() / "client.json").native()); + simdjson::dom::element root = parser.load(config_path.native()); for (simdjson::dom::object i: simdjson::dom::array(root["servers"])) { server_data data{ @@ -134,60 +258,15 @@ configuration::configuration(xr::system & system, xr::session & session) servers.emplace(data.service.txt["cookie"], data); } - if (auto val = root["preferred_refresh_rate"]; val.is_double()) - { - float f = val.get_double(); - if (f == 0 or utils::contains(rates, f)) - preferred_refresh_rate = f; - } + float default_refresh_rate = preferred_refresh_rate; - if (auto val = root["minimum_refresh_rate"]; val.is_double()) - minimum_refresh_rate = val.get_double(); + for (const auto & f: config_fields()) + f.load(root, *this); - if (auto val = root["resolution_scale"]; val.is_double()) - resolution_scale = val.get_double(); - - if (auto val = root["stream_scale"]; val.is_double()) - stream_scale = val.get_double(); - - if (auto val = root["codec"]; val.is_string()) - { - const auto codec_str = val.get_string().value(); - for (const auto & [c, name]: magic_enum::enum_entries()) - { - if (codec_str == name) - { - codec = c; - } - } - } - - if (auto val = root["bit_depth"]; val.is_uint64()) - bit_depth = val.get_uint64(); - - if (auto val = root["bitrate_bps"]; val.is_number()) - bitrate_bps = val.get_uint64(); - - if (auto val = root["enable_stream_gui"]; val.is_bool()) - enable_stream_gui = val.get_bool(); - - if (auto val = root["openxr_post_processing"]; val.is_object()) - parse_openxr_post_processing_options(val.get_object()); - - if (auto val = root["passthrough_enabled"]; val.is_bool()) - passthrough_enabled = val.get_bool(); - - if (auto val = root["mic_unprocessed_audio"]; val.is_bool()) - mic_unprocessed_audio = val.get_bool(); - - if (auto val = root["forward_keyboard"]; val.is_bool()) - forward_keyboard = val.get_bool(); - - if (auto val = root["forward_mouse"]; val.is_bool()) - forward_mouse = val.get_bool(); - - if (auto val = root["forward_gamepad"]; val.is_bool()) - forward_gamepad = val.get_bool(); + // refresh rate must be supported by this headset, otherwise fall back to the default + const auto & rates = session.get_refresh_rates(); + if (preferred_refresh_rate != 0 and not utils::contains(rates, preferred_refresh_rate)) + preferred_refresh_rate = default_refresh_rate; if (auto val = root["body_parts"]; val.is_object()) { @@ -208,44 +287,24 @@ configuration::configuration(xr::system & system, xr::session & session) } } - if (auto val = root["virtual_keyboard_layout"]; val.is_string()) - virtual_keyboard_layout = val.get_string().value(); - - for (const auto & [i, name]: magic_enum::enum_entries()) + // nested object + if (auto val = root["openxr_post_processing"]; val.is_object()) { - if (auto val = root[name]; val.is_bool()) - features[i] = val.get_bool(); + auto obj = val.get_object(); + openxr_post_processing = {}; + if (auto v = obj["super_sampling"]; v.is_int64()) + openxr_post_processing.super_sampling = v.get_int64(); + if (auto v = obj["sharpening"]; v.is_int64()) + openxr_post_processing.sharpening = v.get_int64(); } + // feature flags, keyed by enum name + for (const auto & [f, name]: magic_enum::enum_entries()) + if (auto val = root[name]; val.is_bool()) + features[f] = val.get_bool(); + if (system.passthrough_supported() == xr::passthrough_type::none) passthrough_enabled = false; - - if (auto val = root["override_foveation_enable"]; val.is_bool()) - override_foveation_enable = val.get_bool(); - - if (auto val = root["override_foveation_pitch"]; val.is_double()) - override_foveation_pitch = val.get_double(); - - if (auto val = root["override_foveation_distance"]; val.is_double()) - override_foveation_distance = val.get_double(); - - if (auto val = root["first_run"]; val.is_bool()) - first_run = val.get_bool(); - - if (auto val = root["locale"]; val.is_string()) - locale = val.get_string().value(); - - if (auto val = root["environment_model"]; val.is_string()) - environment_model = (std::string_view)val.get_string(); - - if (auto val = root["high_power_mode"]; val.is_bool()) - high_power_mode = val.get_bool(); - - if (auto val = root["fps_divider"]; val.is_uint64()) - fps_divider = (uint32_t)val.get_uint64(); - - if (auto val = root["extended_config"]; val.is_bool()) - extended_config = val.get_bool(); } catch (std::exception & e) { @@ -253,27 +312,43 @@ configuration::configuration(xr::system & system, xr::session & session) } } -void configuration::parse_openxr_post_processing_options(simdjson::simdjson_result openxr_post_processing_root) +const std::vector & configuration::config_fields() { - openxr_post_processing = {}; - if (auto val = openxr_post_processing_root["super_sampling"]; val.is_int64()) - openxr_post_processing.super_sampling = val.get_int64(); - - if (auto val = openxr_post_processing_root["sharpening"]; val.is_int64()) - openxr_post_processing.sharpening = val.get_int64(); -} - -static std::ostream & operator<<(std::ostream & stream, feature f) -{ - return stream << "\"" << magic_enum::enum_name(f) << "\""; -} - -static std::ostream & write_openxr_post_processing(std::ofstream & stream, const configuration::openxr_post_processing_settings & openxr_post_processing) -{ - stream << "{\"super_sampling\":" << openxr_post_processing.super_sampling; - stream << ",\"sharpening\":" << openxr_post_processing.sharpening; - stream << "}"; - return stream; + static const std::vector fields = { + scalar("resolution_scale", &configuration::resolution_scale), + scalar("bitrate_bps", &configuration::bitrate_bps), + scalar("enable_stream_gui", &configuration::enable_stream_gui), + scalar("app_list_view", &configuration::app_list_view), + scalar("app_icon_size", &configuration::app_icon_size), + scalar("theme_preset", &configuration::theme_preset), + scalar("theme_accent", &configuration::theme_accent), + scalar("theme_rounding", &configuration::theme_rounding), + scalar("theme_card_rounding", &configuration::theme_card_rounding), + scalar("theme_font_scale", &configuration::theme_font_scale), + scalar("theme_background_alpha", &configuration::theme_background_alpha), + scalar("passthrough_enabled", &configuration::passthrough_enabled), + scalar("mic_unprocessed_audio", &configuration::mic_unprocessed_audio), + scalar("forward_keyboard", &configuration::forward_keyboard), + scalar("forward_mouse", &configuration::forward_mouse), + scalar("forward_gamepad", &configuration::forward_gamepad), + scalar("virtual_keyboard_layout", &configuration::virtual_keyboard_layout), + scalar("override_foveation_enable", &configuration::override_foveation_enable), + scalar("override_foveation_pitch", &configuration::override_foveation_pitch), + scalar("override_foveation_distance", &configuration::override_foveation_distance), + scalar("first_run", &configuration::first_run), + scalar("locale", &configuration::locale), + scalar("environment_model", &configuration::environment_model), + scalar("high_power_mode", &configuration::high_power_mode), + scalar("fps_divider", &configuration::fps_divider), + scalar("extended_config", &configuration::extended_config), + scalar("preferred_refresh_rate", &configuration::preferred_refresh_rate), + scalar("minimum_refresh_rate", &configuration::minimum_refresh_rate), + scalar("stream_scale", &configuration::stream_scale), + scalar("codec", &configuration::codec), + scalar("bit_depth", &configuration::bit_depth), + scalar("usb_network", &configuration::usb_network), + }; + return fields; } void configuration::save() @@ -305,51 +380,18 @@ void configuration::save() std::ofstream json(application::get_config_path() / "client.json"); json << "{\"servers\":[" << servers_str << "]"; - json << ",\"preferred_refresh_rate\":" << preferred_refresh_rate; - if (minimum_refresh_rate) - json << ",\"minimum_refresh_rate\":" << *minimum_refresh_rate; - json << ",\"resolution_scale\":" << resolution_scale; - if (stream_scale) - json << ",\"stream_scale\":" << *stream_scale; - if (codec) - json << ",\"codec\":" << json_string(magic_enum::enum_name(*codec)); - json << ",\"bit_depth\":" << (uint64_t)bit_depth; - json << ",\"bitrate_bps\":" << bitrate_bps; - json << ",\"openxr_post_processing\":"; - write_openxr_post_processing(json, openxr_post_processing); - json << ",\"passthrough_enabled\":" << std::boolalpha << passthrough_enabled; - json << ",\"mic_unprocessed_audio\":" << std::boolalpha << mic_unprocessed_audio; - json << ",\"forward_keyboard\":" << std::boolalpha << forward_keyboard; - json << ",\"forward_mouse\":" << std::boolalpha << forward_mouse; - json << ",\"forward_gamepad\":" << std::boolalpha << forward_gamepad; - std::stringstream body_part_ss; - for (const auto & [b, name]: magic_enum::enum_entries()) - { - bool enabled = (body_part_mask & std::to_underlying(b)) != 0; - body_part_ss << "\"" << name << "\":" << std::boolalpha << enabled << ","; - } + for (const auto & f: config_fields()) + f.save(json, *this); - std::string body_parts_str = body_part_ss.str(); - if (!body_parts_str.empty()) - { - body_parts_str.pop_back(); // Remove last comma - json << ",\"body_parts\":{" << body_parts_str << "}"; - } + // nested object + json << ",\"openxr_post_processing\":{\"super_sampling\":" << openxr_post_processing.super_sampling; + json << ",\"sharpening\":" << openxr_post_processing.sharpening << "}"; - json << ",\"enable_stream_gui\":" << std::boolalpha << enable_stream_gui; + // feature flags, keyed by enum name for (auto & [key, value]: features) json << "," << key << ":" << std::boolalpha << value; - json << ",\"virtual_keyboard_layout\":" << json_string(virtual_keyboard_layout); - json << ",\"override_foveation_enable\":" << std::boolalpha << override_foveation_enable; - json << ",\"override_foveation_pitch\":" << override_foveation_pitch; - json << ",\"override_foveation_distance\":" << override_foveation_distance; - json << ",\"first_run\":" << std::boolalpha << first_run; - json << ",\"locale\":" << json_string(locale); - json << ",\"environment_model\":" << json_string(environment_model); - json << ",\"high_power_mode\":" << std::boolalpha << high_power_mode; - json << ",\"fps_divider\":" << fps_divider; - json << ",\"extended_config\":" << std::boolalpha << extended_config; + json << "}"; } @@ -362,6 +404,11 @@ float configuration::get_stream_scale() const { if (stream_scale) return *stream_scale; + return get_default_stream_scale(); +} + +float configuration::get_default_stream_scale() const +{ if (check_feature(feature::eye_gaze)) return 0.3; return 0.5; diff --git a/client/configuration.h b/client/configuration.h index 431d1e94..2d11de7c 100644 --- a/client/configuration.h +++ b/client/configuration.h @@ -22,12 +22,14 @@ #include "wivrn_discover.h" #include "wivrn_packets.h" +#include #include #include #include #include #include #include +#include #include namespace xr @@ -36,6 +38,9 @@ class session; class system; } // namespace xr +// key <-> member serialization descriptor, defined in configuration.cpp +struct config_field; + enum class feature { microphone, @@ -61,7 +66,7 @@ public: std::map servers; float preferred_refresh_rate = 0; std::optional minimum_refresh_rate; - float resolution_scale = 1.0; + float resolution_scale = 1.2; std::optional codec; uint32_t bitrate_bps = 50'000'000; uint8_t bit_depth = 10; @@ -78,6 +83,18 @@ public: bool enable_stream_gui = true; + // application launcher: list vs grid, and grid icon size, 0 small 1 medium 2 large + bool app_list_view = false; + uint32_t app_icon_size = 0; + + // interface theme, defaults match the built-in "Dark" preset and "Blue" accent + std::string theme_preset = "Dark"; + std::string theme_accent = "Blue"; + float theme_rounding = 8; + float theme_card_rounding = 14; + float theme_font_scale = 1.0; + float theme_background_alpha = 0.75; + // XR_FB_composition_layer_settings extension flags struct openxr_post_processing_settings { @@ -97,6 +114,8 @@ public: bool high_power_mode = true; uint32_t fps_divider = 1; + bool usb_network = false; + // Allow unsafe config values bool extended_config = false; @@ -112,16 +131,18 @@ private: std::map features; std::optional stream_scale; - void parse_openxr_post_processing_options(simdjson::simdjson_result root); + // table of scalar settings shared by save()/load(); non-scalar settings are explicit + static const std::vector & config_fields(); public: configuration(xr::system &, xr::session &); - configuration() = default; + configuration(xr::system &, xr::session &, const std::filesystem::path &); void save(); void set_stream_scale(float); float get_stream_scale() const; + float get_default_stream_scale() const; uint32_t max_bitrate(bool extended) const { diff --git a/client/constants.h b/client/constants.h index f35738e0..dd591198 100644 --- a/client/constants.h +++ b/client/constants.h @@ -64,6 +64,13 @@ constexpr float pointer_fading_distance = 40; // Pointer color constexpr uint32_t pointer_color = 0x40ffffff; constexpr uint32_t pointer_color_border = 0xff000000; + +// offset of a popup layer in front of its main GUI panel +constexpr glm::vec3 popup_position = {0, 0, 0.05}; + +// world-space offset of a hover tooltip layer from the hovered item +constexpr glm::vec3 tooltip_distance = {0, 0.004, 0.005}; + } // namespace constants::gui namespace constants::lobby @@ -78,7 +85,6 @@ constexpr auto gui_pitches = std::to_array>({ {90, 78}, }); constexpr float keyboard_pitch = -0.6; -constexpr glm::vec3 popup_position = {0, 0, 0.05}; constexpr glm::vec3 keyboard_position = {0, -0.3, 0.1}; // Position of the near plane @@ -99,10 +105,6 @@ constexpr float initial_gui_distance = 0.5; // Skybox color constexpr XrColor4f sky_color = {0, 0.25, 0.5, 1}; -// Dimming scale/bias when a popup window is shown -constexpr XrColor4f dimming_scale = {0.5, 0.5, 0.5, 1}; -constexpr XrColor4f dimming_bias = {0.25, 0.25, 0.25, 0}; - // Z-indices of composition layers constexpr int zindex_passthrough = -2; constexpr int zindex_lobby = -1; @@ -136,25 +138,3 @@ constexpr float gui_min_layer_distance = 0.5; constexpr float gui_max_layer_distance = 3; } // namespace constants::stream - -namespace constants::style -{ -constexpr ImVec2 window_padding = {20, 20}; -constexpr float window_border_size = 2; -constexpr float window_rounding = 10; - -constexpr ImVec2 tooltip_padding = {5, 5}; -constexpr float tooltip_rounding = 0; -constexpr glm::vec3 tooltip_distance = {0, 0.004, 0.005}; - -constexpr ImVec2 button_size = {220, 80}; -constexpr ImVec2 icon_button_size = {80, 80}; -constexpr float connection_popup_width = 1000; - -constexpr ImVec2 pin_entry_key_size = {90, 70}; -constexpr ImVec2 pin_entry_item_spacing = {10, 10}; -constexpr float pin_entry_popup_width = 3 * pin_entry_key_size.x + 2 * pin_entry_item_spacing.x; - -constexpr ImColor warn(0xf9, 0x73, 0x06); - -} // namespace constants::style diff --git a/client/decoder/android/android_decoder.cpp b/client/decoder/android/android_decoder.cpp index b1ca1616..cdca4a42 100644 --- a/client/decoder/android/android_decoder.cpp +++ b/client/decoder/android/android_decoder.cpp @@ -195,6 +195,8 @@ decoder::decoder( decoder::~decoder() { + if (image_reader) + AImageReader_setImageListener(image_reader.get(), nullptr); if (media_codec) { AMediaCodec_stop(media_codec.get()); diff --git a/client/hmd_traits.cpp b/client/hmd_traits.cpp index d5ac1c0e..cb211987 100644 --- a/client/hmd_traits.cpp +++ b/client/hmd_traits.cpp @@ -190,12 +190,28 @@ void hmd_traits::init() { panel_width_override = 2064; // Quest 3 controller_profile = "meta-quest-touch-plus"; + usb_net = true; } else if (device == "panther") // Quest 3S { panel_width_override = 1832; controller_profile = "meta-quest-touch-plus"; } + + if (auto v = get_property("ro.hzos.build.display_name")) + { + auto digits = utils::split(*v, "."); + try + { + auto major = std::stoi(digits.at(0)); + auto minor = std::stoi(digits.at(1)); + usb_net = major > 2 or (major == 2 and minor >= 6); + } + catch (...) + { + spdlog::warn("Failed to parse Horizon OS version {}", *v); + } + } } else if (model == "Lynx-R1") @@ -269,8 +285,13 @@ void hmd_traits::init() controller_profile = "htc-vive-focus-3"; if (model == "VIVE Focus 3") + { panel_width_override = 2448; + // Reports VK_EXT_debug_utils but does not expose vkSetDebugUtilsObjectNameEXT + vk_debug_ext_allowed = false; + } + if (model == "VIVE Focus Vision") panel_width_override = 2448; diff --git a/client/hmd_traits.h b/client/hmd_traits.h index 685cdd43..7f79d534 100644 --- a/client/hmd_traits.h +++ b/client/hmd_traits.h @@ -55,6 +55,7 @@ public: bool hand_interaction_grip_surface = true; bool pico_face_tracker = false; bool discard_frame = true; // can do xrBeginFrame twice to discard the first one + bool usb_net = false; std::unordered_map override_shader; std::unordered_set blacklisted_extensions; #ifndef NDEBUG diff --git a/client/java/MainActivity.java b/client/java/MainActivity.java index b1b690dc..e02230e4 100644 --- a/client/java/MainActivity.java +++ b/client/java/MainActivity.java @@ -17,6 +17,7 @@ public class MainActivity extends android.app.NativeActivity public native void onActivityResult(int requestCode, int resultCode, android.content.Intent data); private android.content.BroadcastReceiver BatteryInfoReceiver = null; + public android.net.ConnectivityManager.NetworkCallback netcb = null; @Override protected void onCreate(android.os.Bundle savedInstanceState) @@ -24,6 +25,7 @@ public class MainActivity extends android.app.NativeActivity super.onCreate(savedInstanceState); this.BatteryInfoReceiver = new BroadcastReceiver(); + this.netcb = new org.meumeu.wivrn.NetworkInfoCallback(); this.registerReceiver(this.BatteryInfoReceiver, new android.content.IntentFilter(android.content.Intent.ACTION_BATTERY_CHANGED)); } diff --git a/client/java/NetworkInfoCallback.java b/client/java/NetworkInfoCallback.java new file mode 100644 index 00000000..baac3ae7 --- /dev/null +++ b/client/java/NetworkInfoCallback.java @@ -0,0 +1,26 @@ +package org.meumeu.wivrn; + +public class NetworkInfoCallback extends android.net.ConnectivityManager.NetworkCallback +{ + @Override + public native void onAvailable(android.net.Network network); + + @Override + public native void onBlockedStatusChanged(android.net.Network network, boolean blocked); + + @Override + public native void onCapabilitiesChanged(android.net.Network network, android.net.NetworkCapabilities caps); + + @Override + public native void onLinkPropertiesChanged(android.net.Network network, android.net.LinkProperties props); + + @Override + public native void onLosing(android.net.Network network, int maxMsToLive); + + @Override + public native void onLost(android.net.Network network); + + @Override + public native void onUnavailable(); +} + diff --git a/client/libcurl.cpp b/client/libcurl.cpp index 3f1e75cf..8f3c6508 100644 --- a/client/libcurl.cpp +++ b/client/libcurl.cpp @@ -65,7 +65,7 @@ void libcurl::curl_thread_fn() { #ifdef __ANDROID__ // For Android, read all the certificates at start-up, the file names are not - // in the correct format for the current verion of OpenSSL. + // in the correct format for the current version of OpenSSL. // See https://stackoverflow.com/questions/25253823/how-to-make-ssl-peer-verify-work-on-android std::string ca_bundle; for (const std::filesystem::directory_entry & entry: std::filesystem::directory_iterator{"/system/etc/security/cacerts"}) @@ -158,8 +158,10 @@ void libcurl::curl_thread_fn() if (msg->data.result == CURLE_OK) { - xfer.current_state = state::done; - xfer.finish(); + if (xfer.finish()) + xfer.current_state = state::done; + else + xfer.current_state = state::error; } else { @@ -299,17 +301,21 @@ size_t libcurl::transfer_file::write(void * data, size_t size) noexcept return size; } -void libcurl::transfer_file::finish() noexcept +bool libcurl::transfer_file::finish() noexcept { stream.close(); - std::filesystem::rename(temporary_path, final_path); + std::error_code ec{}; + std::filesystem::rename(temporary_path, final_path, ec); + if (ec) + return false; curl_off_t remote_timestamp; if (curl_easy_getinfo(curl, CURLINFO_FILETIME_T, &remote_timestamp) == CURLE_OK) { auto time = std::chrono::file_clock::from_sys(std::chrono::system_clock::from_time_t(remote_timestamp)); - std::filesystem::last_write_time(final_path, time); + std::filesystem::last_write_time(final_path, time, ec); // ignore errors } + return true; } void libcurl::transfer_file::cancel() noexcept @@ -343,8 +349,9 @@ size_t libcurl::transfer_buffer::write(void * data, size_t size) noexcept return size; } -void libcurl::transfer_buffer::finish() noexcept +bool libcurl::transfer_buffer::finish() noexcept { + return true; } void libcurl::transfer_buffer::cancel() noexcept diff --git a/client/libcurl.h b/client/libcurl.h index 0ee3b488..40da074f 100644 --- a/client/libcurl.h +++ b/client/libcurl.h @@ -69,7 +69,7 @@ private: virtual ~transfer(); virtual size_t write(void * data, size_t size) noexcept = 0; - virtual void finish() noexcept = 0; + virtual bool finish() noexcept = 0; virtual void cancel() noexcept = 0; }; @@ -82,7 +82,7 @@ private: std::fstream stream; size_t write(void * data, size_t size) noexcept override; - void finish() noexcept override; + bool finish() noexcept override; void cancel() noexcept override; }; @@ -93,7 +93,7 @@ private: std::string buffer; size_t write(void * data, size_t size) noexcept override; - void finish() noexcept override; + bool finish() noexcept override; void cancel() noexcept override; }; diff --git a/client/main.cpp b/client/main.cpp index f219c8cb..37db0497 100644 --- a/client/main.cpp +++ b/client/main.cpp @@ -89,7 +89,6 @@ void real_main() } #ifdef __ANDROID__ -void android_main(android_app * native_app) __attribute__((visibility("default"))); void android_main(android_app * native_app) { static auto logger = spdlog::android_logger_mt("WiVRn", "WiVRn"); diff --git a/client/render/imgui_impl.cpp b/client/render/imgui_impl.cpp index 31a15ffb..a235f30e 100644 --- a/client/render/imgui_impl.cpp +++ b/client/render/imgui_impl.cpp @@ -16,7 +16,6 @@ * along with this program. If not, see . */ -#define IMGUI_DEFINE_MATH_OPERATORS #include "imgui_impl.h" #include "implot.h" @@ -24,6 +23,7 @@ #include "constants.h" #include "image_loader.h" #include "openxr/openxr.h" +#include "ui_theme.h" #include "utils/mapped_file.h" #include "utils/ranges.h" #include "utils/strings.h" @@ -182,7 +182,7 @@ static float distance_to_window(ImGuiWindow * window, ImVec2 position) static const std::array layout_bindings = { vk::DescriptorSetLayoutBinding{ .binding = 0, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .descriptorType = vk::DescriptorType::eSampledImage, .descriptorCount = 1, .stageFlags = vk::ShaderStageFlagBits::eFragment, }}; @@ -535,11 +535,13 @@ void imgui_context::initialize_fonts() } } - utils::mapped_file font_awesome_regular("assets://Font Awesome 6 Free-Regular-400.otf"); - utils::mapped_file font_awesome_solid("assets://Font Awesome 6 Free-Solid-900.otf"); + assert(font_awesome.empty()); + font_awesome.emplace_back("assets://Font Awesome 7 Free-Regular-400.otf"); + font_awesome.emplace_back("assets://Font Awesome 7 Free-Solid-900.otf"); + font_awesome.emplace_back("assets://Font Awesome 7 Brands-Regular-400.otf"); ImFontConfig config; - config.FontDataOwnedByAtlas = false; + config.FontDataOwnedByAtlas = true; for (auto & font: fonts) { @@ -548,10 +550,11 @@ void imgui_context::initialize_fonts() config.MergeMode = true; } + config.FontDataOwnedByAtlas = false; config.MergeMode = true; config.GlyphMinAdvanceX = 40; // Use if you want to make the icon monospaced - io.Fonts->AddFontFromMemoryTTF(const_cast(font_awesome_regular.data()), font_awesome_regular.size(), constants::gui::font_size_small, &config); - io.Fonts->AddFontFromMemoryTTF(const_cast(font_awesome_solid.data()), font_awesome_solid.size(), constants::gui::font_size_small, &config); + for (auto & fa: font_awesome) + io.Fonts->AddFontFromMemoryTTF(const_cast(fa.data()), fa.size(), constants::gui::font_size_small, &config); } std::vector imgui_context::read_controllers_state(XrTime display_time) @@ -933,6 +936,28 @@ std::vector> imgui_context::end_frame() } } + if (auto modal_popup = ImGui::GetTopMostAndVisiblePopupModal(); modal_popup != nullptr) + { + ImDrawList * draw_list = ImGui::GetForegroundDrawList(); + for (ImGuiWindow * window: context->Windows) + { + if (window == modal_popup or window->ParentWindow != nullptr or not window->Active or window->Hidden or window->IsFallbackWindow) + continue; + + static const auto virtual_keyboard_id = ImHashStr("VirtualKeyboard"); + if (window->ID == virtual_keyboard_id) + continue; + + ImRect window_rect{ + window->Pos.x, + window->Pos.y, + window->Pos.x + window->Size.x, + window->Pos.y + window->Size.y}; + + draw_list->AddRectFilled(window_rect.Min, window_rect.Max, ImGui::ColorConvertFloat4ToU32(wivrn::ui::current().dimming), window->WindowRounding); + } + } + ImGui::Render(); current_command_buffer = (current_command_buffer + 1) % command_buffers.size(); @@ -1147,12 +1172,12 @@ imgui_context::~imgui_context() ImGui::DestroyContext(context); } -ImTextureID imgui_textures::load_texture(const std::string & filename, vk::raii::Sampler && sampler) +ImTextureID imgui_textures::load_texture(const std::string & filename) { - return load_texture(utils::mapped_file{filename}, std::move(sampler), filename); + return load_texture(utils::mapped_file{filename}, filename); } -ImTextureID imgui_textures::load_texture(const std::span & bytes, vk::raii::Sampler && sampler, const std::string & name) +ImTextureID imgui_textures::load_texture(const std::span & bytes, const std::string & name) { bool srgb = true; @@ -1165,7 +1190,6 @@ ImTextureID imgui_textures::load_texture(const std::span & byte std::shared_ptr ds = descriptor_pool.allocate(); vk::DescriptorImageInfo image_info{ - .sampler = *sampler, .imageView = *image->image_view, .imageLayout = vk::ImageLayout::eShaderReadOnlyOptimal, }; @@ -1173,7 +1197,7 @@ ImTextureID imgui_textures::load_texture(const std::span & byte vk::WriteDescriptorSet ds_write{ .dstSet = **ds, .descriptorCount = 1, - .descriptorType = vk::DescriptorType::eCombinedImageSampler, + .descriptorType = vk::DescriptorType::eSampledImage, .pImageInfo = &image_info}; device.updateDescriptorSets(ds_write, nullptr); @@ -1183,7 +1207,6 @@ ImTextureID imgui_textures::load_texture(const std::span & byte textures.emplace( id, texture_data{ - .sampler = std::move(sampler), .image = image, .descriptor_set = std::move(ds), }); @@ -1191,43 +1214,6 @@ ImTextureID imgui_textures::load_texture(const std::span & byte return id; } -ImTextureID imgui_textures::load_texture(const std::span & bytes, const std::string & name) -{ - return load_texture( - bytes, - vk::raii::Sampler{ - device, - vk::SamplerCreateInfo{ - .magFilter = vk::Filter::eLinear, - .minFilter = vk::Filter::eLinear, - .mipmapMode = vk::SamplerMipmapMode::eLinear, - .addressModeU = vk::SamplerAddressMode::eClampToEdge, - .addressModeV = vk::SamplerAddressMode::eClampToEdge, - .addressModeW = vk::SamplerAddressMode::eClampToEdge, - .borderColor = vk::BorderColor::eFloatTransparentBlack, - }, - }, - name); -} - -ImTextureID imgui_textures::load_texture(const std::string & filename) -{ - return load_texture( - filename, - vk::raii::Sampler{ - device, - vk::SamplerCreateInfo{ - .magFilter = vk::Filter::eLinear, - .minFilter = vk::Filter::eLinear, - .mipmapMode = vk::SamplerMipmapMode::eLinear, - .addressModeU = vk::SamplerAddressMode::eClampToEdge, - .addressModeV = vk::SamplerAddressMode::eClampToEdge, - .addressModeW = vk::SamplerAddressMode::eClampToEdge, - .borderColor = vk::BorderColor::eFloatTransparentBlack, - }, - }); -} - void imgui_textures::free_texture(ImTextureID texture) { textures.erase(texture); @@ -1244,11 +1230,6 @@ void imgui_context::set_controllers_enabled(bool value) controllers_enabled = value; } -bool imgui_context::is_modal_popup_shown() const -{ - return ImGui::GetTopMostAndVisiblePopupModal() != nullptr; -} - imgui_context::viewport & imgui_context::layer(ImVec2 position) { for (auto & layer: layers_) @@ -1260,30 +1241,42 @@ imgui_context::viewport & imgui_context::layer(ImVec2 position) return layers_.front(); } -void imgui_context::tooltip(std::string_view text) +void imgui_context::place_layer_relative(size_t layer, size_t base, glm::vec3 offset, glm::quat extra_rotation) +{ + const viewport & b = layers_[base]; + viewport & l = layers_[layer]; + l.orientation = b.orientation * extra_rotation; + l.position = b.position + glm::mat3_cast(b.orientation) * offset; +} + +void imgui_context::tooltip(std::string_view text, std::optional anchor) { // FIXME: this is incorrect if we use the docking branch of imgui ImGuiViewport * viewport = ImGui::GetMainViewport(); - auto & current_layer = layer(ImGui::GetMousePos()); + auto & current_layer = layer(anchor.value_or(ImGui::GetMousePos())); assert(std::ranges::contains(layers_, true, &viewport::tooltip_viewport)); auto & tooltip_layer = *std::ranges::find(layers_, true, &viewport::tooltip_viewport); - // Get the item position before drawing the tooltip (top center) - ImVec2 item_position{ + // anchor above the given display point, or above the last item's rect (top center) + ImVec2 item_position = anchor.value_or(ImVec2{ (ImGui::GetItemRectMin().x + ImGui::GetItemRectMax().x) / 2, ImGui::GetItemRectMin().y, - }; + }); auto pos_backup = viewport->Pos; auto size_backup = viewport->Size; viewport->Pos = ImVec2(tooltip_layer.vp_origin.x, tooltip_layer.vp_origin.y); viewport->Size = ImVec2(tooltip_layer.vp_size.x, tooltip_layer.vp_size.y); - // Draw the tooltip in the tooltip layer + // Draw the tooltip in the tooltip layer, themed // Clamp position to avoid overflowing on the left or the right - ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, constants::style::tooltip_padding); - ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, constants::style::tooltip_rounding); + const wivrn::ui::theme & t = wivrn::ui::current(); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, wivrn::ui::metrics::tooltip_padding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, t.card_rounding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, t.border_size); + ImGui::PushStyleColor(ImGuiCol_PopupBg, t.card); + ImGui::PushStyleColor(ImGuiCol_Border, t.border); auto & style = ImGui::GetStyle(); const ImVec2 text_size = ImGui::CalcTextSize(text.data(), text.data() + text.size(), true); @@ -1293,12 +1286,13 @@ void imgui_context::tooltip(std::string_view text) ImGui::SetNextWindowSizeConstraints({0, 0}, viewport->Size); if (ImGui::BeginTooltip()) { - ImGui::PushStyleColor(ImGuiCol_Text, 0xffffffff); + ImGui::PushStyleColor(ImGuiCol_Text, t.col(t.text)); ImGui::TextUnformatted(text.data(), text.data() + text.size()); ImGui::PopStyleColor(); ImGui::EndTooltip(); } - ImGui::PopStyleVar(2); + ImGui::PopStyleColor(2); + ImGui::PopStyleVar(3); viewport->Pos = pos_backup; viewport->Size = size_backup; @@ -1308,7 +1302,7 @@ void imgui_context::tooltip(std::string_view text) auto M = glm::mat3_cast(tooltip_orientation); float pixel_size = current_layer.size.y / current_layer.vp_size.y; - glm::vec3 tooltip_position_centre = rw_from_vp(item_position) + M * (glm::vec3(0, tooltip_size.y / 2, 0) * pixel_size + constants::style::tooltip_distance); + glm::vec3 tooltip_position_centre = rw_from_vp(item_position) + M * (glm::vec3(0, tooltip_size.y / 2, 0) * pixel_size + constants::gui::tooltip_distance); // Position the tooltip layer tooltip_layer.position = tooltip_position_centre; @@ -1329,9 +1323,15 @@ void ScrollWhenDragging() static int active_id; static ImVec2 cumulated_delta; + // don't drag while a popup is open or just closed: the ray snaps back and synthesises a click + static bool popup_was_open; + const bool popup_open = ImGui::IsPopupOpen(nullptr, ImGuiPopupFlags_AnyPopupId | ImGuiPopupFlags_AnyPopupLevel); + bool HoveredIdAllowOverlap_backup = std::exchange(g.HoveredIdAllowOverlap, true); bool ActiveIdAllowOverlap_backup = std::exchange(g.ActiveIdAllowOverlap, true); - if (active_id == 0 and ImGui::ItemHoverable(window->Rect(), 0, g.CurrentItemFlags) and ImGui::IsMouseClicked(mouse_button, ImGuiInputFlags_None, /*id*/ ImGuiKeyOwner_Any)) + // start only over this window or a child card, and only with no active widget + const bool over = ImGui::IsWindowHovered(ImGuiHoveredFlags_ChildWindows); + if (active_id == 0 and g.ActiveId == 0 and not popup_open and not popup_was_open and over and ImGui::IsMouseClicked(mouse_button, ImGuiInputFlags_None, /*id*/ ImGuiKeyOwner_Any)) { active_id = id; @@ -1357,6 +1357,8 @@ void ScrollWhenDragging() g.HoveredIdAllowOverlap = HoveredIdAllowOverlap_backup; g.ActiveIdAllowOverlap = ActiveIdAllowOverlap_backup; + + popup_was_open = popup_open; } void CenterTextH(const std::string & text) @@ -1397,62 +1399,3 @@ void CenterTextHV(const std::string & text) } ImGui::PopStyleVar(); } - -void InputText(const char * label, std::string & text, const ImVec2 & size, ImGuiInputTextFlags flags) -{ - auto callback = [](ImGuiInputTextCallbackData * data) -> int { - std::string & text = *reinterpret_cast(data->UserData); - - if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) - { - assert(text.data() == data->Buf); - text.resize(data->BufTextLen); - data->Buf = text.data(); - } - - return 0; - }; - - ImGui::InputTextEx(label, nullptr, text.data(), text.size() + 1, size, flags | ImGuiInputTextFlags_CallbackResize, callback, &text); -} - -bool RadioButtonWithoutCheckBox(const std::string & label, bool active, ImVec2 size_arg) -{ - ImGuiWindow * window = ImGui::GetCurrentWindow(); - if (window->SkipItems) - return false; - - ImGuiContext & g = *GImGui; - const ImGuiStyle & style = g.Style; - const ImGuiID id = window->GetID(label.c_str()); - const ImVec2 label_size = ImGui::CalcTextSize(label.c_str(), NULL, true); - - const ImVec2 pos = window->DC.CursorPos; - - ImVec2 size = ImGui::CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f); - - const ImRect bb(pos, pos + size); - ImGui::ItemSize(bb, style.FramePadding.y); - if (!ImGui::ItemAdd(bb, id)) - return false; - - bool hovered, held; - bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held); - - ImGuiCol_ col; - if ((held && hovered) || active) - col = ImGuiCol_ButtonActive; - else if (hovered) - col = ImGuiCol_ButtonHovered; - else - col = ImGuiCol_Button; - - ImGui::RenderNavHighlight(bb, id); - ImGui::RenderFrame(bb.Min, bb.Max, ImGui::GetColorU32(col), true, style.FrameRounding); - - ImVec2 TextAlign{0, 0.5f}; - ImGui::RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label.c_str(), NULL, &label_size, TextAlign, &bb); - - IMGUI_TEST_ENGINE_ITEM_INFO(id, label.c_str(), g.LastItemData.StatusFlags); - return pressed; -} diff --git a/client/render/imgui_impl.h b/client/render/imgui_impl.h index 9ad71e58..420f52da 100644 --- a/client/render/imgui_impl.h +++ b/client/render/imgui_impl.h @@ -21,6 +21,7 @@ #include "image_loader.h" #include "render/growable_descriptor_pool.h" #include "utils/cache.h" +#include "utils/mapped_file.h" #include "utils/thread_safe.h" #include "wivrn_config.h" #include "xr/hand_tracker.h" @@ -30,6 +31,7 @@ #include #include #include +#include #include #include #include @@ -42,7 +44,6 @@ class imgui_textures { struct texture_data { - vk::raii::Sampler sampler; std::shared_ptr image; std::shared_ptr descriptor_set; }; @@ -69,9 +70,7 @@ public: thread_safe & queue, std::shared_ptr image_cache = {}); ~imgui_textures(); - ImTextureID load_texture(const std::string & filename, vk::raii::Sampler && sampler); ImTextureID load_texture(const std::string & filename); - ImTextureID load_texture(const std::span & bytes, vk::raii::Sampler && sampler, const std::string & name = ""); ImTextureID load_texture(const std::span & bytes, const std::string & name = ""); void free_texture(ImTextureID); }; @@ -203,6 +202,7 @@ private: bool show_demo_window = true; #endif + beman::inplace_vector::inplace_vector font_awesome; void initialize_fonts(); std::vector read_controllers_state(XrTime display_time); @@ -226,6 +226,9 @@ public: return layers_; } + // place a satellite layer at base orientation (optionally post-rotated), offset in the base's local frame + void place_layer_relative(size_t layer, size_t base, glm::vec3 offset, glm::quat extra_rotation = glm::quat(1, 0, 0, 0)); + std::vector windows(); viewport & layer(ImVec2 position); @@ -246,12 +249,11 @@ public: void set_current(); - bool is_modal_popup_shown() const; - void vibrate_on_hover(); void set_hovered_item(); void set_controllers_enabled(bool value); - void tooltip(std::string_view text); + // anchor, if set, positions the tooltip above that display point instead of above the last item's rect + void tooltip(std::string_view text, std::optional anchor = std::nullopt); std::array is_aim_interaction() const { return {aim_interaction[0] == 1, aim_interaction[1] == 1}; @@ -263,16 +265,3 @@ void ScrollWhenDragging(); void CenterTextH(const std::string & text); void CenterTextHV(const std::string & text); - -void InputText(const char * label, std::string & text, const ImVec2 & size, ImGuiInputTextFlags flags); - -bool RadioButtonWithoutCheckBox(const std::string & label, bool active, ImVec2 size_arg); - -template -static bool RadioButtonWithoutCheckBox(const std::string & label, T & v, U v_button, ImVec2 size_arg) -{ - const bool pressed = RadioButtonWithoutCheckBox(label, v == v_button, size_arg); - if (pressed) - v = v_button; - return pressed; -} diff --git a/client/render/scene_renderer.cpp b/client/render/scene_renderer.cpp index 5a8ab2e7..17703f46 100644 --- a/client/render/scene_renderer.cpp +++ b/client/render/scene_renderer.cpp @@ -1002,7 +1002,7 @@ void scene_renderer::render( return false; // If blending is disabled (std::get<0> == false), put the closest objects first - // If blending is enabled (std::get<0> == true), put the farthest objeccts first + // If blending is enabled (std::get<0> == true), put the farthest objects first return std::get<0>(a) ^ (std::get<1>(a) > std::get<1>(b)); }); diff --git a/client/render/ui_theme.cpp b/client/render/ui_theme.cpp new file mode 100644 index 00000000..37abbe1c --- /dev/null +++ b/client/render/ui_theme.cpp @@ -0,0 +1,234 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2026 Guillaume Meunier + * Copyright (C) 2026 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "ui_theme.h" +#include "utils/i18n.h" + +namespace wivrn::ui +{ + +static ImVec4 rgb(int r, int g, int b, float a = 1) +{ + return {r / 255.f, g / 255.f, b / 255.f, a}; +} + +static theme dark_default() +{ + theme t; + t.name = "Dark"; + t.localized_name = _C("theme name", "Dark"); + + t.accent = rgb(30, 115, 255); + t.accent_hovered = rgb(64, 140, 255); + t.accent_active = rgb(18, 95, 228); + t.on_accent = rgb(255, 255, 255); + + t.background = rgb(10, 11, 13); + t.card = rgb(22, 24, 29); + t.card_hovered = rgb(28, 30, 36); + t.control = rgb(35, 38, 46); + t.control_hovered = rgb(44, 48, 57); + t.control_active = rgb(52, 57, 68); + + t.text = rgb(244, 245, 248); + t.text_muted = rgb(150, 156, 167); + t.border = rgb(40, 43, 51); + + t.danger = rgb(239, 68, 68); + t.danger_hovered = rgb(248, 96, 96); + t.success = rgb(52, 199, 123); + t.warning = rgb(249, 115, 6); + + t.dimming = rgb(128, 128, 128, 0.5f); + + t.rounding = 8; + t.card_rounding = 14; + t.border_size = 1; + t.font_scale = 1.0; // user multiplier, 100% maps to metrics::font_base + return t; +} + +static theme midnight() +{ + theme t = dark_default(); + t.name = "Midnight"; + t.localized_name = _C("theme name", "Midnight"); + t.background = rgb(6, 8, 16); + t.card = rgb(16, 20, 34); + t.card_hovered = rgb(22, 27, 44); + t.control = rgb(28, 34, 54); + t.control_hovered = rgb(36, 43, 66); + t.control_active = rgb(44, 52, 78); + t.border = rgb(30, 37, 58); + return t; +} + +static theme slate_light() +{ + theme t = dark_default(); + t.name = "Slate"; + t.localized_name = _C("theme name", "Slate"); + t.background = rgb(28, 30, 36); + t.card = rgb(38, 41, 49); + t.card_hovered = rgb(46, 50, 60); + t.control = rgb(54, 59, 70); + t.control_hovered = rgb(64, 70, 83); + t.control_active = rgb(74, 81, 96); + t.text = rgb(236, 238, 242); + t.text_muted = rgb(168, 174, 186); + t.border = rgb(58, 63, 75); + return t; +} + +// True black, ideal for OLED panels +static theme oled() +{ + theme t = dark_default(); + t.name = "OLED"; + t.localized_name = _C("theme name", "OLED"); + t.background = rgb(0, 0, 0); + t.card = rgb(6, 6, 8); + t.card_hovered = rgb(11, 12, 14); + t.control = rgb(22, 24, 28); + t.control_hovered = rgb(30, 32, 38); + t.control_active = rgb(40, 43, 50); + t.border = rgb(26, 28, 33); + return t; +} + +// Neutral dark gray +static theme graphite() +{ + theme t = dark_default(); + t.name = "Graphite"; + t.localized_name = _C("theme name", "Graphite"); + t.background = rgb(20, 21, 23); + t.card = rgb(31, 33, 36); + t.card_hovered = rgb(39, 41, 45); + t.control = rgb(48, 51, 56); + t.control_hovered = rgb(58, 62, 68); + t.control_active = rgb(68, 72, 80); + t.text = rgb(238, 240, 243); + t.text_muted = rgb(160, 164, 172); + t.border = rgb(50, 53, 59); + return t; +} + +// Light surfaces, dark text +static theme light() +{ + theme t = dark_default(); + t.name = "Light"; + t.localized_name = _C("theme name", "Light"); + t.background = rgb(188, 193, 202); + t.card = rgb(252, 252, 253); + t.card_hovered = rgb(242, 243, 246); + t.control = rgb(206, 210, 219); + t.control_hovered = rgb(193, 198, 208); + t.control_active = rgb(178, 184, 196); + t.text = rgb(14, 16, 20); + t.text_muted = rgb(66, 72, 84); + t.border = rgb(176, 182, 194); + t.success = rgb(36, 147, 90); + return t; +} + +std::vector presets() +{ + return {oled(), dark_default(), midnight(), graphite(), slate_light(), light()}; +} + +std::vector accent_swatches() +{ + return { + {"Blue", rgb(30, 115, 255), rgb(64, 140, 255), rgb(18, 95, 228)}, + {"Violet", rgb(132, 72, 255), rgb(152, 98, 255), rgb(112, 52, 232)}, + {"Emerald", rgb(0, 200, 132), rgb(28, 214, 150), rgb(0, 172, 112)}, + {"Amber", rgb(255, 160, 0), rgb(255, 176, 36), rgb(228, 140, 0)}, + {"Rose", rgb(255, 40, 82), rgb(255, 74, 108), rgb(230, 28, 68)}, + {"Cyan", rgb(0, 190, 225), rgb(34, 205, 236), rgb(0, 168, 200)}, + }; +} + +void set_accent(const accent_swatch & swatch) +{ + theme & t = current(); + t.accent = swatch.base; + t.accent_hovered = swatch.hovered; + t.accent_active = swatch.active; +} + +theme & current() +{ + static theme t = dark_default(); + return t; +} + +void set_theme(const theme & t) +{ + current() = t; +} + +float & background_alpha() +{ + static float alpha = 0.75f; // translucent panels by default + return alpha; +} + +void theme::apply() const +{ + ImGuiStyle & style = ImGui::GetStyle(); + + style.FontScaleMain = font_scale; + style.WindowRounding = card_rounding; + style.ChildRounding = card_rounding; + style.PopupRounding = card_rounding; + style.FrameRounding = rounding; + style.GrabRounding = rounding; + style.TabRounding = rounding; + style.FrameBorderSize = border_size; + style.WindowBorderSize = border_size; + + ImVec4 * c = style.Colors; + c[ImGuiCol_Text] = text; + c[ImGuiCol_TextDisabled] = text_muted; + c[ImGuiCol_WindowBg] = background; + c[ImGuiCol_ChildBg] = card; + c[ImGuiCol_PopupBg] = card; + c[ImGuiCol_Border] = border; + c[ImGuiCol_FrameBg] = control; + c[ImGuiCol_FrameBgHovered] = control_hovered; + c[ImGuiCol_FrameBgActive] = control_active; + c[ImGuiCol_Button] = control; + c[ImGuiCol_ButtonHovered] = control_hovered; + c[ImGuiCol_ButtonActive] = accent; + c[ImGuiCol_Header] = control_hovered; + c[ImGuiCol_HeaderHovered] = control_hovered; + c[ImGuiCol_HeaderActive] = accent; + c[ImGuiCol_SliderGrab] = accent; + c[ImGuiCol_SliderGrabActive] = accent_active; + c[ImGuiCol_CheckMark] = accent; + c[ImGuiCol_ScrollbarBg] = {0, 0, 0, 0}; + c[ImGuiCol_ScrollbarGrab] = control; + c[ImGuiCol_ScrollbarGrabHovered] = control_hovered; + c[ImGuiCol_ScrollbarGrabActive] = control_active; + c[ImGuiCol_Separator] = border; +} + +} // namespace wivrn::ui diff --git a/client/render/ui_theme.h b/client/render/ui_theme.h new file mode 100644 index 00000000..349d74cd --- /dev/null +++ b/client/render/ui_theme.h @@ -0,0 +1,173 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2026 Guillaume Meunier + * Copyright (C) 2026 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include +#include +#include + +namespace wivrn::ui +{ + +struct theme +{ + std::string name; + std::string localized_name; + + // Accent + ImVec4 accent; + ImVec4 accent_hovered; + ImVec4 accent_active; + ImVec4 on_accent; // text/icon on an accent fill + + // Surfaces, back to front + ImVec4 background; + ImVec4 card; + ImVec4 card_hovered; + ImVec4 control; // slider rail, secondary button, input + ImVec4 control_hovered; + ImVec4 control_active; + + // Content + ImVec4 text; + ImVec4 text_muted; + ImVec4 border; + + // Semantic + ImVec4 danger; + ImVec4 danger_hovered; + ImVec4 success; + ImVec4 warning; + + // Dimming when a modal popup is visible + ImVec4 dimming; + + // Shape, in pixels + float rounding; // buttons, inputs, sliders + float card_rounding; // cards + float border_size; + + float font_scale; // global text size multiplier + + // packed color with the current global alpha applied, so draw-list widgets dim with BeginDisabled() + ImU32 col(const ImVec4 & c) const + { + ImVec4 v = c; + v.w *= ImGui::GetStyle().Alpha; + return ImGui::ColorConvertFloat4ToU32(v); + } + + // push colors and metrics into the global ImGui style + void apply() const; +}; + +// fixed design tokens shared by the widgets +namespace metrics +{ +constexpr float font_base = 0.765; // user-facing 100% text scale +constexpr float font_title = 1.7; // page header, x base font size +constexpr float font_description = 0.82; // muted secondary text, x base font size + +constexpr ImVec2 button_padding = {26, 14}; +constexpr ImVec2 card_padding = {28, 22}; // regular cards +constexpr ImVec2 list_card_padding = {18, 18}; // cards holding a list of rows + +// shared height of every full-width control so they line up in a setting row, x frame height +constexpr float control_height = 1.65; + +constexpr float toggle_aspect = 1.9; // track width / height +constexpr float toggle_knob_inset = 3; // gap between track edge and knob + +constexpr float slider_grab_width = 14; + +constexpr float segmented_inset = 3; // gap around the active segment + +constexpr float icon_button_glyph = 0.58; // glyph height as a fraction of the button side +constexpr float button_label_glyph = 1.35; // leading icon size in a labeled button, x base text size + +constexpr float combo_row_height = 2.2; // x frame height, big touch rows in the modal +constexpr float combo_chevron = 12; // chevron size in the closed box +constexpr float combo_modal_min_width = 460; // popup never narrower than this +constexpr ImVec2 combo_padding = {16, 0}; // horizontal inner padding of box and rows + +constexpr float list_row_box = 52; // leading icon/thumbnail size in a list row +constexpr float list_row_box_large = 80; // min thumbnail size for full-height list rows +constexpr float list_row_pad = 12; // inner padding of a list row, both axes +constexpr ImVec2 chip_padding = {12, 6}; // inner padding of a chip/badge +constexpr float chip_pill_padding_x = 18; // roomier horizontal padding for top-bar pill chips +constexpr float input_padding_x = 14; // horizontal text padding inside inputs +constexpr float font_modal_title = 1.2; // modal heading, x base font size + +constexpr float label_line_gap = 5; // title to description +constexpr float label_bottom_pad = 6; // breathing room below the description +constexpr float nav_section_gap = 18; // space above a sidebar section header + +constexpr ImVec2 card_item_spacing = {12, 10}; // ItemSpacing pushed around a card section +constexpr float setting_control_width = 480; // width of the control in a setting row + +// application shell: top bar, sidebar, content panel, shared by lobby and in-stream window +constexpr float sidebar_width = 300; +constexpr float top_bar_height = 72; +constexpr float content_margin = 20; // gap around the main content panel + +// application launcher grid +constexpr float app_icon_small = 120; +constexpr float app_icon_medium = 176; +constexpr float app_icon_large = 240; +constexpr float app_tile_margin = 24; // horizontal slack each side of the icon in a tile +constexpr float app_view_toggle_width = 150; // grid/list segmented control +constexpr float app_size_toggle_width = 300; // small/medium/large segmented control +constexpr float app_spinner_radius = 110; // app-starting spinner +constexpr float app_spinner_thickness = 22; + +// modal/popup windows not yet on the card system (first-run, confirm dialogs, loading popup) +constexpr ImVec2 window_padding = {20, 20}; +constexpr float window_rounding = 10; +constexpr float window_border_size = 2; + +constexpr ImVec2 tooltip_padding = {16, 12}; // hover tooltip window padding +constexpr ImVec2 button_size = {220, 80}; // big touch buttons in confirm dialogs + +// PIN entry keypad +constexpr ImVec2 pin_entry_key_size = {90, 70}; +constexpr ImVec2 pin_entry_item_spacing = {10, 10}; +constexpr float pin_entry_popup_width = 3 * pin_entry_key_size.x + 2 * pin_entry_item_spacing.x; +} // namespace metrics + +// theme in effect, call current().apply() after mutating +theme & current(); +void set_theme(const theme & t); + +// panel and card background opacity, 0..1, kept out of the presets so switching palette keeps it +float & background_alpha(); + +std::vector presets(); + +struct accent_swatch +{ + const char * name; + ImVec4 base; + ImVec4 hovered; + ImVec4 active; +}; +std::vector accent_swatches(); +void set_accent(const accent_swatch & swatch); + +} // namespace wivrn::ui diff --git a/client/render/ui_widgets.cpp b/client/render/ui_widgets.cpp new file mode 100644 index 00000000..68398ebc --- /dev/null +++ b/client/render/ui_widgets.cpp @@ -0,0 +1,1453 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2026 Guillaume Meunier + * Copyright (C) 2026 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "ui_widgets.h" + +#include "imgui.h" +#include "imgui_internal.h" +#include "ui_theme.h" + +#include "IconsFontAwesome7.h" + +#include +#include +#include +#include +#include +#include + +// drag-to-scroll helper, defined in imgui_impl.cpp +void ScrollWhenDragging(); + +namespace wivrn::ui +{ + +namespace +{ +std::function hover_haptic_hook; +std::function tooltip_hook; + +// height reserved for the pinned sidebar footer, set by begin_sidebar +float sidebar_footer_height = 0; +} // namespace + +void set_hover_haptic(std::function hook) +{ + hover_haptic_hook = std::move(hook); +} + +void set_tooltip_hook(std::function hook) +{ + tooltip_hook = std::move(hook); +} + +// fire the hover haptic for the last submitted item, hook checks if it is hovered +static void hover_haptic() +{ + if (hover_haptic_hook) + hover_haptic_hook(); +} + +// show a tooltip for the last item, caller ensures it is hovered +static void show_tooltip(const std::string & text) +{ + if (not text.empty() and tooltip_hook) + tooltip_hook(text.c_str()); +} + +void page_header(const std::string & title, const std::string & subtitle) +{ + const theme & t = current(); + + ImGui::PushFont(nullptr, ImGui::GetStyle().FontSizeBase * metrics::font_title); + ImGui::TextUnformatted(title.c_str()); + ImGui::PopFont(); + + if (not subtitle.empty()) + { + ImGui::PushStyleColor(ImGuiCol_Text, t.text_muted); + ImGui::TextUnformatted(subtitle.c_str()); + ImGui::PopStyleColor(); + } + ImGui::Dummy({0, ImGui::GetStyle().ItemSpacing.y}); +} + +// a rounded panel, not a child window, so the page stays one scroll surface, drawn behind +// the content using last frame's height, pair with end_card +namespace +{ +struct card_frame +{ + ImGuiID id; + ImVec2 origin; + float width; + float content_max_x_backup; + float work_max_x_backup; + ImVec2 padding; +}; +std::vector card_stack; +std::unordered_map card_heights; + +bool begin_card_impl(const char * id, ImVec2 padding) +{ + ImGuiWindow * window = ImGui::GetCurrentWindow(); + const theme & t = current(); + const ImGuiID gid = window->GetID(id); + + card_stack.push_back({gid, + window->DC.CursorPos, + ImGui::GetContentRegionAvail().x, + window->ContentRegionRect.Max.x, + window->WorkRect.Max.x, + padding}); + const card_frame & cf = card_stack.back(); + + if (const float h = card_heights[gid]; h > 0) + { + const ImVec2 bb_max = {cf.origin.x + cf.width, cf.origin.y + h}; + ImVec4 card = t.card; + card.w *= background_alpha(); // card fill follows the panel opacity + window->DrawList->AddRectFilled(cf.origin, bb_max, t.col(card), t.card_rounding); + if (t.border_size > 0) + window->DrawList->AddRect(cf.origin, bb_max, t.col(t.border), t.card_rounding, t.border_size); + } + + ImGui::PushID(id); + window->ContentRegionRect.Max.x -= padding.x; + window->WorkRect.Max.x -= padding.x; + ImGui::Indent(padding.x); + ImGui::SetCursorScreenPos({ImGui::GetCursorScreenPos().x, cf.origin.y + padding.y}); + ImGui::BeginGroup(); + return true; +} +} // namespace + +bool begin_card(const char * id, const ImVec2 &) +{ + return begin_card_impl(id, metrics::card_padding); +} + +bool begin_list_card(const char * id) +{ + return begin_card_impl(id, metrics::list_card_padding); +} + +void end_card() +{ + ImGuiWindow * window = ImGui::GetCurrentWindow(); + const card_frame cf = card_stack.back(); + card_stack.pop_back(); + + ImGui::EndGroup(); + ImGui::Unindent(cf.padding.x); + window->ContentRegionRect.Max.x = cf.content_max_x_backup; + window->WorkRect.Max.x = cf.work_max_x_backup; + ImGui::PopID(); + + const float height = ImGui::GetItemRectMax().y + cf.padding.y - cf.origin.y; + card_heights[cf.id] = height; + + // reserve the full card extent so layout and scrolling account for it + ImGui::SetCursorScreenPos(cf.origin); + ImGui::Dummy({cf.width, height}); +} + +void row_separator() +{ + const theme & t = current(); + ImVec4 edge = t.border; + edge.w *= background_alpha(); // match the panel/card opacity + ImGui::PushStyleColor(ImGuiCol_Separator, edge); + ImGui::Separator(); + ImGui::PopStyleColor(); +} + +float setting_label(const std::string & title, const std::string & description, float control_width) +{ + const theme & t = current(); + const ImGuiStyle & style = ImGui::GetStyle(); + + const ImVec2 start = ImGui::GetCursorPos(); + const float avail = ImGui::GetContentRegionAvail().x; + float text_w = avail - control_width - style.ItemSpacing.x; + if (text_w < 1) + text_w = avail; + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {style.ItemSpacing.x, metrics::label_line_gap}); + ImGui::PushTextWrapPos(start.x + text_w); + ImGui::TextUnformatted(title.c_str()); + ImGui::PopTextWrapPos(); + if (not description.empty()) + { + ImGui::PushFont(nullptr, style.FontSizeBase * metrics::font_description); + ImGui::PushStyleColor(ImGuiCol_Text, t.text_muted); + // never wider than half the row, wrap to as many lines as needed + const float desc_w = ImMin(text_w, avail * 0.5f); + ImGui::PushTextWrapPos(start.x + desc_w); + ImGui::TextUnformatted(description.c_str()); + ImGui::PopTextWrapPos(); + ImGui::PopStyleColor(); + ImGui::PopFont(); + } + ImGui::PopStyleVar(); + + // right-aligned control slot, vertically centered against the label block + const float label_h = ImGui::GetCursorPos().y - start.y; + const float ctrl_h = ImGui::GetFrameHeight() * metrics::control_height; + const float ctrl_y = start.y + ImMax(0.f, (label_h - ctrl_h) * 0.5f); + ImGui::SetCursorPos({start.x + avail - control_width, ctrl_y}); + return start.y + label_h; +} + +namespace +{ +struct button_colors +{ + ImVec4 bg, bg_hovered, bg_active, text; +}; + +button_colors colors_for(button_style s, const theme & t) +{ + switch (s) + { + case button_style::primary: + return {t.accent, t.accent_hovered, t.accent_active, t.on_accent}; + case button_style::secondary: + return {t.control, t.control_hovered, t.control_active, t.text}; + case button_style::danger: + return {t.danger, t.danger_hovered, t.danger, t.on_accent}; + case button_style::ghost: + return {{0, 0, 0, 0}, t.control, t.control_active, t.text}; + } + return {}; +} +} // namespace + +std::string icon_label(const char * icon, const std::string & label) +{ + return std::string(icon) + " " + label; +} + +float button_width(const std::string & label) +{ + return ImGui::CalcTextSize(label.c_str()).x + metrics::button_padding.x * 2; +} + +float button_width(const char * icon, const std::string & label) +{ + ImGui::PushFont(nullptr, ImGui::GetFontSize() * metrics::button_label_glyph); + const float icon_w = ImGui::CalcTextSize(icon).x; + ImGui::PopFont(); + const float gap = ImGui::GetFontSize() * 0.4f; + return icon_w + gap + ImGui::CalcTextSize(label.c_str()).x + metrics::button_padding.x * 2; +} + +ImVec2 chip_size(const std::string & label) +{ + const ImVec2 ts = ImGui::CalcTextSize(label.c_str()); + return {ts.x + metrics::chip_padding.x * 2, ts.y + metrics::chip_padding.y * 2}; +} + +float chip_width(const std::string & label, bool dot, float height) +{ + // mirrors the footprint computed in chip() + const ImVec2 ts = ImGui::CalcTextSize(label.c_str()); + const float pad_x = height > 0 ? metrics::chip_pill_padding_x : metrics::chip_padding.x; + const float dot_r = ts.y * 0.26f; + const float dot_gap = dot ? dot_r * 2 + pad_x * 0.55f : 0; + return ts.x + pad_x * 2 + dot_gap; +} + +bool button(const std::string & label, button_style s, const ImVec2 & size) +{ + const theme & t = current(); + + // control height by default, width auto-fits the label + const float h = size.y > 0 ? size.y : ImGui::GetFrameHeight() * metrics::control_height; + + const button_colors c = colors_for(s, t); + ImGui::PushStyleColor(ImGuiCol_Button, c.bg); + ImGui::PushStyleColor(ImGuiCol_ButtonHovered, c.bg_hovered); + ImGui::PushStyleColor(ImGuiCol_ButtonActive, c.bg_active); + ImGui::PushStyleColor(ImGuiCol_Text, c.text); + + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, t.rounding); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, metrics::button_padding); + const bool pressed = ImGui::Button(label.c_str(), {size.x, h}); + ImGui::PopStyleVar(2); + ImGui::PopStyleColor(4); + hover_haptic(); + return pressed; +} + +bool button(const char * icon, const std::string & label, button_style s, const ImVec2 & size) +{ + ImGuiWindow * window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext & g = *GImGui; + const ImGuiStyle & style = g.Style; + const theme & t = current(); + + const float h = size.y > 0 ? size.y : ImGui::GetFrameHeight() * metrics::control_height; + const float glyph_size = ImGui::GetFontSize() * metrics::button_label_glyph; + const float gap = ImGui::GetFontSize() * 0.4f; + + ImGui::PushFont(nullptr, glyph_size); + const float icon_w = ImGui::CalcTextSize(icon).x; + ImGui::PopFont(); + const ImVec2 label_size = ImGui::CalcTextSize(label.c_str()); + const float content_w = icon_w + gap + label_size.x; + const float w = size.x > 0 ? size.x : content_w + metrics::button_padding.x * 2; + + const ImVec2 pos = window->DC.CursorPos; + const ImRect bb(pos, pos + ImVec2{w, h}); + ImGui::ItemSize(bb, style.FramePadding.y); + const ImGuiID id = window->GetID(label.c_str()); + if (not ImGui::ItemAdd(bb, id)) + return false; + + bool hovered, held; + const bool pressed = ImGui::ButtonBehavior(bb, id, &hovered, &held); + hover_haptic(); + + const button_colors c = colors_for(s, t); + ImVec4 bg = c.bg; + if (held) + bg = c.bg_active; + else if (hovered) + bg = c.bg_hovered; + + ImDrawList * draw = window->DrawList; + draw->AddRectFilled(bb.Min, bb.Max, t.col(bg), t.rounding); + + const ImU32 col = t.col(c.text); + const ImVec2 center = bb.GetCenter(); + float x = center.x - content_w * 0.5f; + + // icon centred vertically on its ink box, like icon_button + ImGui::PushFont(nullptr, glyph_size); + unsigned int codepoint = 0; + ImTextCharFromUtf8(&codepoint, icon, nullptr); + const ImFontGlyph * glyph = ImGui::GetFontBaked()->FindGlyph(ImWchar(codepoint)); + if (glyph) + draw->AddText({x, center.y - (glyph->Y0 + glyph->Y1) * 0.5f}, col, icon); + else + draw->AddText({x, center.y - glyph_size * 0.5f}, col, icon); + ImGui::PopFont(); + + x += icon_w + gap; + draw->AddText({x, center.y - label_size.y * 0.5f}, col, label.c_str()); + + return pressed; +} + +bool icon_button(const char * icon, const ImVec2 & size_arg, bool active, const std::string & tooltip) +{ + ImGuiWindow * window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext & g = *GImGui; + const ImGuiStyle & style = g.Style; + const theme & t = current(); + + // square touch target, same height as the sliders and other controls + const float side = ImGui::GetFrameHeight() * metrics::control_height; + const ImVec2 size = size_arg.x > 0 ? size_arg : ImVec2{side, side}; + + const ImVec2 pos = window->DC.CursorPos; + const ImRect bb(pos, pos + size); + ImGui::ItemSize(bb, style.FramePadding.y); + const ImGuiID gid = window->GetID(icon); + if (not ImGui::ItemAdd(bb, gid)) + return false; + + bool hovered, held; + const bool pressed = ImGui::ButtonBehavior(bb, gid, &hovered, &held); + hover_haptic(); + if (hovered) + show_tooltip(tooltip); + + ImVec4 bg = active ? t.accent : t.control; + if (held) + bg = active ? t.accent_active : t.control_active; + else if (hovered) + bg = active ? t.accent_hovered : t.control_hovered; + + ImDrawList * draw = window->DrawList; + draw->AddRectFilled(bb.Min, bb.Max, t.col(bg), t.rounding); + + // centre the glyph on its ink box, not CalcTextSize + const float glyph_size = size.y * metrics::icon_button_glyph; + ImGui::PushFont(nullptr, glyph_size); + const ImU32 col = t.col(active ? t.on_accent : t.text); + const ImVec2 center = bb.GetCenter(); + + unsigned int codepoint = 0; + ImTextCharFromUtf8(&codepoint, icon, nullptr); + const ImFontGlyph * glyph = ImGui::GetFontBaked()->FindGlyph(ImWchar(codepoint)); + if (glyph) + draw->AddText({center.x - (glyph->X0 + glyph->X1) * 0.5f, center.y - (glyph->Y0 + glyph->Y1) * 0.5f}, col, icon); + else + { + const ImVec2 ts = ImGui::CalcTextSize(icon); + draw->AddText({center.x - ts.x * 0.5f, center.y - ts.y * 0.5f}, col, icon); + } + ImGui::PopFont(); + + return pressed; +} + +bool cancel_progress_button(const char * id, float fraction, const ImVec2 & size_arg, const std::string & tooltip) +{ + ImGuiWindow * window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext & g = *GImGui; + const theme & t = current(); + + const float side = ImGui::GetFrameHeight() * metrics::control_height; + const ImVec2 size = size_arg.x > 0 ? size_arg : ImVec2{side, side}; + + const ImVec2 pos = window->DC.CursorPos; + const ImRect bb(pos, pos + size); + ImGui::ItemSize(bb, g.Style.FramePadding.y); + const ImGuiID gid = window->GetID(id); + if (not ImGui::ItemAdd(bb, gid)) + return false; + + bool hovered, held; + const bool pressed = ImGui::ButtonBehavior(bb, gid, &hovered, &held); + hover_haptic(); + if (hovered) + show_tooltip(tooltip); + + ImDrawList * draw = window->DrawList; + const ImVec2 center = bb.GetCenter(); + const float thickness = ImMax(2.f, size.y * 0.09f); + const float radius = ImMin(size.x, size.y) * 0.5f - thickness; + + // faint full ring as the track + draw->PathArcTo(center, radius, 0, 2 * IM_PI, 48); + draw->PathStroke(t.col(t.control), thickness); + + const ImU32 accent = t.col(t.accent); + if (fraction >= 0) + { + // determinate arc, clockwise from the top + const float a0 = -IM_PI * 0.5f; + draw->PathArcTo(center, radius, a0, a0 + ImClamp(fraction, 0.f, 1.f) * 2 * IM_PI, 48); + draw->PathStroke(accent, thickness); + } + else + { + // indeterminate: a rotating quarter arc + const float a0 = float(g.Time) * 3.5f; + draw->PathArcTo(center, radius, a0, a0 + IM_PI * 0.5f, 24); + draw->PathStroke(accent, thickness); + } + + // stop glyph in the centre, brightening on hover to read as a cancel target + const float glyph_size = size.y * metrics::icon_button_glyph * 0.7f; + ImGui::PushFont(nullptr, glyph_size); + const ImU32 col = t.col(hovered or held ? t.text : t.text_muted); + unsigned int codepoint = 0; + ImTextCharFromUtf8(&codepoint, ICON_FA_STOP, nullptr); + const ImFontGlyph * glyph = ImGui::GetFontBaked()->FindGlyph(ImWchar(codepoint)); + if (glyph) + draw->AddText({center.x - (glyph->X0 + glyph->X1) * 0.5f, center.y - (glyph->Y0 + glyph->Y1) * 0.5f}, col, ICON_FA_STOP); + ImGui::PopFont(); + + return pressed; +} + +// Horizontal space a trailing reset slot consumes, gap included +float reset_slot_width() +{ + return ImGui::GetFrameHeight() * metrics::control_height + ImGui::GetStyle().ItemSpacing.x; +} + +// trailing reset button on a value control's row, empty slot when not shown so the right edge stays put +static bool reset_slot(const char * id, bool show) +{ + const float side = ImGui::GetFrameHeight() * metrics::control_height; + ImGui::SameLine(0, ImGui::GetStyle().ItemSpacing.x); + if (not show) + { + ImGui::Dummy({side, side}); + return false; + } + ImGui::PushID(id); + const bool clicked = icon_button(ICON_FA_ARROW_ROTATE_LEFT, {side, side}, false, "Reset to default"); + ImGui::PopID(); + return clicked; +} + +bool toggle(const char * id, bool * v, const bool * default_value) +{ + ImGuiWindow * window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + const theme & t = current(); + const ImGuiStyle & style = ImGui::GetStyle(); + + // match the height of the other controls + const float height = ImGui::GetFrameHeight() * metrics::control_height; + const float width = height * metrics::toggle_aspect; + const float radius = height * 0.5f; + + const ImVec2 pos = window->DC.CursorPos; + const ImRect bb(pos, pos + ImVec2(width, height)); + ImGui::ItemSize(bb, style.FramePadding.y); + const ImGuiID gid = window->GetID(id); + if (not ImGui::ItemAdd(bb, gid)) + return false; + + bool hovered, held; + bool changed = ImGui::ButtonBehavior(bb, gid, &hovered, &held); + hover_haptic(); + if (changed) + *v = not *v; + + ImVec4 track = *v ? t.accent : t.control; + if (hovered) + track = *v ? t.accent_hovered : t.control_hovered; + + ImDrawList * draw = window->DrawList; + draw->AddRectFilled(bb.Min, bb.Max, t.col(track), radius); + const float cx = *v ? (bb.Max.x - radius) : (bb.Min.x + radius); + draw->AddCircleFilled({cx, bb.Min.y + radius}, radius - metrics::toggle_knob_inset, t.col(t.on_accent)); + + if (default_value and reset_slot(id, *v != *default_value)) + { + *v = *default_value; + changed = true; + } + + return changed; +} + +bool slider_int(const char * id, int * v, int v_min, int v_max, const char * format, const ImVec2 & size_arg, const int * default_value) +{ + ImGuiWindow * window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiContext & g = *GImGui; + const ImGuiStyle & style = g.Style; + const theme & t = current(); + const ImGuiID gid = window->GetID(id); + + ImVec2 size = ImGui::CalcItemSize(size_arg, ImGui::CalcItemWidth(), ImGui::GetFrameHeight() * metrics::control_height); + if (default_value) + size.x -= reset_slot_width(); + const ImVec2 pos = window->DC.CursorPos; + const ImRect bb(pos, pos + size); + ImGui::ItemSize(bb, style.FramePadding.y); + if (not ImGui::ItemAdd(bb, gid, &bb)) + return false; + + // activation, mirrors ImGui::SliderScalar + const bool hovered = ImGui::ItemHoverable(bb, gid, g.LastItemData.ItemFlags); + hover_haptic(); + const bool clicked = hovered and ImGui::IsMouseClicked(ImGuiMouseButton_Left, ImGuiInputFlags_None, gid); + if (clicked or g.NavActivateId == gid) + { + if (clicked) + ImGui::SetKeyOwner(ImGuiKey_MouseLeft, gid); + ImGui::SetActiveID(gid, window); + ImGui::SetFocusID(gid, window); + ImGui::FocusWindow(window); + g.ActiveIdUsingNavDirMask |= (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right); + } + + ImRect grab; + const bool changed = ImGui::SliderBehavior(bb, gid, ImGuiDataType_S32, v, &v_min, &v_max, format, ImGuiSliderFlags_None, &grab); + if (changed) + ImGui::MarkItemEdited(gid); + + const float fraction = v_max > v_min ? float(*v - v_min) / float(v_max - v_min) : 0; + const float fill_x = bb.Min.x + (bb.Max.x - bb.Min.x) * fraction; + + ImDrawList * draw = window->DrawList; + draw->AddRectFilled(bb.Min, bb.Max, t.col(t.control), t.rounding); + if (fraction > 0) + { + // round the right corners too once the fill reaches the box edge + const ImDrawFlags fill_flags = fill_x >= bb.Max.x - t.rounding ? ImDrawFlags_RoundCornersAll : ImDrawFlags_RoundCornersLeft; + draw->AddRectFilled(bb.Min, {fill_x, bb.Max.y}, t.col(t.accent_active), t.rounding, fill_flags); + } + // bright grab at the fill edge + const float grab_w = metrics::slider_grab_width; + const float gx = ImClamp(fill_x, bb.Min.x + grab_w * 0.5f, bb.Max.x - grab_w * 0.5f); + draw->AddRectFilled({gx - grab_w * 0.5f, bb.Min.y}, {gx + grab_w * 0.5f, bb.Max.y}, t.col(t.accent), t.rounding); + + char buf[64]; + std::snprintf(buf, sizeof(buf), format, *v); + const ImVec2 ts = ImGui::CalcTextSize(buf); + draw->AddText({bb.Min.x + (size.x - ts.x) * 0.5f, bb.Min.y + (size.y - ts.y) * 0.5f}, t.col(t.text), buf); + + bool reset = false; + if (default_value and reset_slot(id, *v != *default_value)) + { + *v = *default_value; + reset = true; + } + + return changed or reset; +} + +bool segmented(const char * id, const std::vector & options, int * selected, const ImVec2 & size_arg, const int * default_value) +{ + ImGuiWindow * window = ImGui::GetCurrentWindow(); + if (window->SkipItems or options.empty()) + return false; + + ImGuiContext & g = *GImGui; + const ImGuiStyle & style = g.Style; + const theme & t = current(); + + ImVec2 size = ImGui::CalcItemSize(size_arg, ImGui::CalcItemWidth(), ImGui::GetFrameHeight() * metrics::control_height); + if (default_value) + size.x -= reset_slot_width(); + const ImVec2 pos = window->DC.CursorPos; + const ImRect bb(pos, pos + size); + ImGui::ItemSize(bb, style.FramePadding.y); + const ImGuiID gid = window->GetID(id); + if (not ImGui::ItemAdd(bb, gid)) + return false; + + const bool hovered = ImGui::ItemHoverable(bb, gid, g.LastItemData.ItemFlags); + hover_haptic(); + // claim the active id on press so a drag here scrolls nothing (see ScrollWhenDragging) + if (hovered and ImGui::IsMouseClicked(ImGuiMouseButton_Left)) + { + ImGui::SetActiveID(gid, window); + ImGui::FocusWindow(window); + } + if (g.ActiveId == gid and not g.IO.MouseDown[ImGuiMouseButton_Left]) + ImGui::ClearActiveID(); + + ImDrawList * draw = window->DrawList; + draw->AddRectFilled(bb.Min, bb.Max, t.col(t.control), t.rounding); + + const int n = int(options.size()); + const float seg_w = size.x / n; + const float pad = metrics::segmented_inset; + bool changed = false; + + for (int i = 0; i < n; ++i) + { + const ImRect seg({bb.Min.x + seg_w * i, bb.Min.y}, {bb.Min.x + seg_w * (i + 1), bb.Max.y}); + const bool seg_hovered = hovered and seg.Contains(g.IO.MousePos); + if (seg_hovered and ImGui::IsMouseClicked(ImGuiMouseButton_Left)) + { + *selected = i; + changed = true; + } + + const bool active = *selected == i; + if (active) + draw->AddRectFilled(seg.Min + ImVec2(pad, pad), seg.Max - ImVec2(pad, pad), t.col(t.accent), t.rounding); + else if (seg_hovered) + draw->AddRectFilled(seg.Min + ImVec2(pad, pad), seg.Max - ImVec2(pad, pad), t.col(t.control_hovered), t.rounding); + + const char * label = options[i].c_str(); + const ImVec2 ts = ImGui::CalcTextSize(label); + draw->AddText({seg.Min.x + (seg_w - ts.x) * 0.5f, seg.Min.y + (size.y - ts.y) * 0.5f}, t.col(active ? t.on_accent : t.text), label); + } + + if (default_value and reset_slot(id, *selected != *default_value)) + { + *selected = *default_value; + changed = true; + } + + return changed; +} + +namespace +{ +// where combo modals open, in imgui display coords, set each frame by the lobby +ImVec2 popup_center = {0, 0}; +// height of the popup layer, caps tall combo lists so they scroll, 0 = unbounded +float popup_available_height = 0; + +// one selectable option inside the combo modal, tall full-width touch target with an optional description +bool combo_row(const combo_item & item, bool selected, bool checked) +{ + ImGuiWindow * window = ImGui::GetCurrentWindow(); + const theme & t = current(); + + const float row_h = ImGui::GetFrameHeight() * metrics::combo_row_height; + const float row_w = ImGui::GetContentRegionAvail().x; + const ImVec2 pos = window->DC.CursorPos; + const ImRect bb(pos, pos + ImVec2(row_w, row_h)); + ImGui::ItemSize(bb, 0); + const ImGuiID gid = window->GetID(item.name); + if (not ImGui::ItemAdd(bb, gid)) + return false; + + bool hovered, held; + const bool pressed = ImGui::ButtonBehavior(bb, gid, &hovered, &held); + hover_haptic(); + + ImVec4 bg = selected ? t.control_active : t.card; + if (held) + bg = t.control_active; + else if (hovered) + bg = t.control_hovered; + + ImDrawList * draw = window->DrawList; + draw->AddRectFilled(bb.Min, bb.Max, t.col(bg), t.rounding); + if (selected) + draw->AddRectFilled(bb.Min, {bb.Min.x + metrics::combo_padding.x * 0.25f, bb.Max.y}, t.col(t.accent), t.rounding, ImDrawFlags_RoundCornersLeft); + + if (checked) + { + const ImVec2 cs = ImGui::CalcTextSize(ICON_FA_CHECK); + draw->AddText({bb.Max.x - metrics::combo_padding.x - cs.x, bb.Min.y + (row_h - cs.y) * 0.5f}, t.col(t.accent), ICON_FA_CHECK); + } + + const float tx = bb.Min.x + metrics::combo_padding.x; + const ImU32 name_col = t.col(t.text); + const ImVec2 nts = ImGui::CalcTextSize(item.name); + + if (item.description and item.description[0]) + { + const float desc_size = ImGui::GetStyle().FontSizeBase * metrics::font_description; + ImGui::PushFont(nullptr, desc_size); + const ImVec2 dts = ImGui::CalcTextSize(item.description); + const float total = nts.y + metrics::label_line_gap + dts.y; + const float y = bb.Min.y + (row_h - total) * 0.5f; + draw->AddText({tx, y + nts.y + metrics::label_line_gap}, t.col(t.text_muted), item.description); + ImGui::PopFont(); + draw->AddText({tx, y}, name_col, item.name); + } + else + { + draw->AddText({tx, bb.Min.y + (row_h - nts.y) * 0.5f}, name_col, item.name); + } + + return pressed; +} + +bool combo_impl(const char * id, const std::string & title, const char * preview, const std::vector & items, int * selected, std::vector * selected_multi, float width, const int * default_value, const std::vector * default_value_multi, bool close_on_click) +{ + ImGuiWindow * window = ImGui::GetCurrentWindow(); + if (window->SkipItems or items.empty()) + return false; + + const ImGuiStyle & style = ImGui::GetStyle(); + const theme & t = current(); + const ImGuiID gid = window->GetID(id); + + // closed box, same height as the slider so setting rows line up + ImVec2 size = ImGui::CalcItemSize({width, 0}, ImGui::CalcItemWidth(), ImGui::GetFrameHeight() * metrics::control_height); + if (default_value or default_value_multi) + size.x -= reset_slot_width(); + const ImVec2 pos = window->DC.CursorPos; + const ImRect bb(pos, pos + size); + ImGui::ItemSize(bb, style.FramePadding.y); + if (not ImGui::ItemAdd(bb, gid)) + return false; + + bool hovered, held; + const bool clicked = ImGui::ButtonBehavior(bb, gid, &hovered, &held); + hover_haptic(); + + ImVec4 box = t.control; + if (held) + box = t.control_active; + else if (hovered) + box = t.control_hovered; + + ImDrawList * draw = window->DrawList; + draw->AddRectFilled(bb.Min, bb.Max, t.col(box), t.rounding); + if (t.border_size > 0) + draw->AddRect(bb.Min, bb.Max, t.col(t.border), t.rounding, t.border_size); + + const int sel = selected ? ImClamp(*selected, 0, int(items.size()) - 1) : -1; + + // preview, left aligned and clipped to the box + const ImVec2 ts = ImGui::CalcTextSize(preview); + const float pad_x = metrics::combo_padding.x; + draw->PushClipRect(bb.Min, bb.Max, true); + draw->AddText({bb.Min.x + pad_x, bb.Min.y + (size.y - ts.y) * 0.5f}, t.col(t.text), preview); + draw->PopClipRect(); + + // chevron on the right + const float cx = bb.Max.x - pad_x - metrics::combo_chevron * 0.5f; + const float cy = bb.Min.y + size.y * 0.5f; + const float r = metrics::combo_chevron * 0.5f; + draw->AddTriangleFilled({cx - r, cy - r * 0.4f}, {cx + r, cy - r * 0.4f}, {cx, cy + r * 0.6f}, t.col(t.text_muted)); + + char popup_id[64]; + std::snprintf(popup_id, sizeof(popup_id), "##combo_%08X", gid); + if (clicked) + ImGui::OpenPopup(popup_id); + + ImGui::SetNextWindowPos(popup_center, ImGuiCond_Always, {0.5f, 0.5f}); + ImGui::SetNextWindowSize({ImMax(size.x, metrics::combo_modal_min_width), 0}); + + ImGui::PushStyleColor(ImGuiCol_PopupBg, t.card); + ImGui::PushStyleColor(ImGuiCol_Border, t.border); + ImGui::PushStyleColor(ImGuiCol_Text, t.text); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, t.card_rounding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, metrics::card_padding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, t.border_size > 0 ? t.border_size : 1); + + bool changed = false; + if (ImGui::BeginPopupModal(popup_id, nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysAutoResize)) + { + if (not title.empty()) + { + ImGui::PushStyleColor(ImGuiCol_Text, t.text_muted); + ImGui::TextUnformatted(title.c_str()); + ImGui::PopStyleColor(); + ImGui::Dummy({0, style.ItemSpacing.y}); + } + + // cap the list height so a long list scrolls inside the modal instead of clipping + const float row_h = ImGui::GetFrameHeight() * metrics::combo_row_height; + // include the inter-row gaps or a scrollbar shows even when it all fits + float list_h = int(items.size()) * row_h + ImMax(0, int(items.size()) - 1) * style.ItemSpacing.y; + if (popup_available_height > 0) + { + const float title_h = title.empty() ? 0 : ImGui::GetTextLineHeight() + style.ItemSpacing.y; + const float max_list = popup_available_height * 0.9f - 2 * metrics::card_padding.y - title_h; + list_h = ImMin(list_h, ImMax(max_list, row_h)); + } + + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {0, 0}); + ImGui::BeginChild("##list", {0, list_h}); + for (int i = 0; i < int(items.size()); ++i) + { + const bool is_selected = i == sel; + const bool is_selected_multi = selected_multi and i < selected_multi->size() and (*selected_multi)[i]; + if (combo_row(items[i], is_selected, is_selected_multi)) + { + if (selected) + *selected = i; + + if (selected_multi) + { + if (selected_multi->size() <= i) + selected_multi->resize(i + 1); + (*selected_multi)[i] = not(*selected_multi)[i]; + } + + changed = true; + if (close_on_click) + ImGui::CloseCurrentPopup(); + } + if (is_selected and ImGui::IsWindowAppearing()) + ImGui::SetScrollHereY(0.5f); // reveal the current value when opening + } + ImGui::EndChild(); + ImGui::PopStyleVar(); + + // click outside dismisses, AllowWhenBlockedByActiveItem so pressing a row still counts as inside + if (ImGui::IsMouseClicked(ImGuiMouseButton_Left) and not ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) + ImGui::CloseCurrentPopup(); + + ImGui::EndPopup(); + } + + ImGui::PopStyleVar(3); + ImGui::PopStyleColor(3); + + bool show_reset_slot = (selected and default_value and *selected != *default_value) or + (selected_multi and default_value_multi and *selected_multi != *default_value_multi); + + if (reset_slot(id, show_reset_slot)) + { + if (selected and default_value) + *selected = *default_value; + + if (selected_multi and default_value_multi) + *selected_multi = *default_value_multi; + + changed = true; + } + + return changed; +} +} // namespace + +void set_popup_center(const ImVec2 & center, float available_height) +{ + popup_center = center; + popup_available_height = available_height; +} + +bool combo(const char * id, const std::string & title, const std::vector & items, int * selected, float width, const int * default_value) +{ + const int sel = ImClamp(*selected, 0, int(items.size()) - 1); + const char * preview = items[sel].name; + + return combo_impl(id, title, preview, items, selected, nullptr, width, default_value, nullptr, true); +} + +bool combo_multi(const char * id, const std::string & title, const std::string & preview, const std::vector & items, std::vector * selected, float width, const std::vector * default_value) +{ + return combo_impl(id, title, preview.c_str(), items, nullptr, selected, width, nullptr, default_value, false); +} + +void chip(const std::string & label, chip_style style, bool dot, float height) +{ + ImGuiWindow * window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return; + + const theme & t = current(); + + // foreground (text/dot/icon) and the pill fill + ImVec4 fg = t.text; + ImVec4 bg = t.control; + switch (style) + { + case chip_style::neutral: + break; + case chip_style::muted: + fg = t.text_muted; + break; + case chip_style::accent: + fg = t.accent; + bg = {t.accent.x, t.accent.y, t.accent.z, 0.16f}; + break; + case chip_style::success: + fg = t.success; + bg = {t.success.x, t.success.y, t.success.z, 0.16f}; + break; + case chip_style::warning: + fg = t.warning; + bg = {t.warning.x, t.warning.y, t.warning.z, 0.16f}; + break; + case chip_style::danger: + fg = t.danger; + bg = {t.danger.x, t.danger.y, t.danger.z, 0.16f}; + break; + } + + const ImVec2 ts = ImGui::CalcTextSize(label.c_str()); + const ImVec2 pad = metrics::chip_padding; + // tall pill chips (height override) get roomier sides + const float pad_x = height > 0 ? metrics::chip_pill_padding_x : pad.x; + const float dot_r = ts.y * 0.26f; + const float dot_gap = dot ? dot_r * 2 + pad_x * 0.55f : 0; + const ImVec2 size = {ts.x + pad_x * 2 + dot_gap, height > 0 ? height : ts.y + pad.y * 2}; + + const ImVec2 pos = window->DC.CursorPos; + const ImRect bb(pos, pos + size); + ImGui::ItemSize(bb); + if (not ImGui::ItemAdd(bb, 0)) + return; + + ImDrawList * draw = window->DrawList; + draw->AddRectFilled(bb.Min, bb.Max, t.col(bg), size.y * 0.5f); + + float tx = bb.Min.x + pad_x; + if (dot) + { + draw->AddCircleFilled({tx + dot_r, bb.Min.y + size.y * 0.5f}, dot_r, t.col(fg)); + tx += dot_r * 2 + pad_x * 0.55f; + } + draw->AddText({tx, bb.Min.y + (size.y - ts.y) * 0.5f}, t.col(fg), label.c_str()); +} + +void nav_section(const std::string & label) +{ + const theme & t = current(); + const ImGuiStyle & style = ImGui::GetStyle(); + + ImGui::Dummy({0, metrics::nav_section_gap}); // gap above the section + ImGui::Indent(metrics::combo_padding.x); // align with the nav_item icons + ImGui::PushFont(nullptr, style.FontSizeBase * metrics::font_description); + ImGui::PushStyleColor(ImGuiCol_Text, t.text_muted); + ImGui::TextUnformatted(label.c_str()); + ImGui::PopStyleColor(); + ImGui::PopFont(); + ImGui::Unindent(metrics::combo_padding.x); + ImGui::Dummy({0, 4}); +} + +bool nav_item(const char * icon, const std::string & label, bool selected) +{ + ImGuiWindow * window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + const theme & t = current(); + const ImGuiStyle & style = ImGui::GetStyle(); + + const float h = ImGui::GetFrameHeight() * metrics::control_height; + const float w = ImGui::GetContentRegionAvail().x; + const ImVec2 pos = window->DC.CursorPos; + const ImRect bb(pos, pos + ImVec2(w, h)); + ImGui::ItemSize(bb, style.FramePadding.y); + const ImGuiID gid = window->GetID(label.c_str()); + if (not ImGui::ItemAdd(bb, gid)) + return false; + + bool hovered, held; + const bool pressed = ImGui::ButtonBehavior(bb, gid, &hovered, &held); + hover_haptic(); + + ImDrawList * draw = window->DrawList; + const float lum = t.background.x * 0.299f + t.background.y * 0.587f + t.background.z * 0.114f; + if (selected) + { + // accent fill for the active tab + draw->AddRectFilled(bb.Min, bb.Max, t.col(t.accent), t.rounding); + } + else if (hovered) + { + // lighten on dark themes, darken on light ones, the framebuffer blends in linear + // light, so solve for the alpha that yields a constant perceived (gamma-space) step + const float step = lum < 0.5f ? 0.10f : 0.06f; // perceptual lightness delta, stronger on dark + auto to_linear = [](float c) { return c <= 0.04045f ? c / 12.92f : std::pow((c + 0.055f) / 1.055f, 2.4f); }; + const float overlay = lum < 0.5f ? 1.f : 0.f; // lighten vs darken + const float ys = to_linear(lum); + const float yt = to_linear(std::clamp(lum + (overlay - lum) / std::abs(overlay - lum) * step, 0.f, 1.f)); + const float a = (yt - ys) / (overlay - ys); + draw->AddRectFilled(bb.Min, bb.Max, t.col({overlay, overlay, overlay, a}), t.rounding); + } + + const float pad = metrics::combo_padding.x; + const float icon_w = ImGui::GetFontSize() * 1.5f; // icon column + + const ImVec2 its = ImGui::CalcTextSize(icon); + draw->AddText({bb.Min.x + pad + (icon_w - its.x) * 0.5f, bb.Min.y + (h - its.y) * 0.5f}, t.col(selected ? t.on_accent : t.text_muted), icon); + + const ImVec2 ls = ImGui::CalcTextSize(label.c_str()); + draw->AddText({bb.Min.x + pad + icon_w + pad * 0.5f, bb.Min.y + (h - ls.y) * 0.5f}, t.col(selected ? t.on_accent : t.text), label.c_str()); + + return pressed; +} + +static int input_text_resize(ImGuiInputTextCallbackData * data) +{ + if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) + { + std::string & s = *static_cast(data->UserData); + s.resize(data->BufTextLen); + data->Buf = s.data(); + } + return 0; +} + +// common frame styling for the input widgets, paired with pop_input_style +static void push_input_style(float height) +{ + const theme & t = current(); + ImGui::PushStyleColor(ImGuiCol_FrameBg, t.control); + ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, t.control_hovered); + ImGui::PushStyleColor(ImGuiCol_FrameBgActive, t.control_active); + ImGui::PushStyleColor(ImGuiCol_Text, t.text); + ImGui::PushStyleColor(ImGuiCol_TextDisabled, t.text_muted); + ImGui::PushStyleColor(ImGuiCol_Border, t.border); + ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, t.rounding); + ImGui::PushStyleVar(ImGuiStyleVar_FrameBorderSize, t.border_size); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {metrics::input_padding_x, (height - ImGui::GetFontSize()) * 0.5f}); +} + +static void pop_input_style() +{ + ImGui::PopStyleVar(3); + ImGui::PopStyleColor(6); +} + +bool input_text(const char * id, std::string & text, const char * hint, float width) +{ + push_input_style(ImGui::GetFrameHeight() * metrics::control_height); + const bool changed = ImGui::InputTextEx(id, hint, text.data(), int(text.size()) + 1, {width, 0}, ImGuiInputTextFlags_CallbackResize, input_text_resize, &text); + pop_input_style(); + hover_haptic(); + return changed; +} + +bool input_int(const char * id, int * v, int step, int v_min, int v_max, float width) +{ + const ImGuiStyle & style = ImGui::GetStyle(); + const float side = ImGui::GetFrameHeight() * metrics::control_height; + const float gap = style.ItemSpacing.x; + const float total = width > 0 ? width : ImGui::CalcItemWidth(); + const float field_w = total - 2 * (side + gap); + + ImGui::PushID(id); + + push_input_style(side); + ImGui::SetNextItemWidth(field_w); + bool changed = ImGui::InputInt("##field", v, 0, 0, ImGuiInputTextFlags_CharsDecimal); // step 0 hides native buttons + pop_input_style(); + hover_haptic(); + + ImGui::SameLine(0, gap); + if (icon_button(ICON_FA_MINUS, {side, side})) + { + *v -= step; + changed = true; + } + ImGui::SameLine(0, gap); + if (icon_button(ICON_FA_PLUS, {side, side})) + { + *v += step; + changed = true; + } + + if (v_min != v_max) + *v = ImClamp(*v, v_min, v_max); + + ImGui::PopID(); + return changed; +} + +bool begin_modal(const char * id, const std::string & title, float width) +{ + const theme & t = current(); + const ImGuiStyle & style = ImGui::GetStyle(); + + ImGui::SetNextWindowPos(popup_center, ImGuiCond_Always, {0.5f, 0.5f}); + if (width > 0) + ImGui::SetNextWindowSize({width, 0}); + + ImGui::PushStyleColor(ImGuiCol_PopupBg, t.card); + ImGui::PushStyleColor(ImGuiCol_Border, t.border); + ImGui::PushStyleColor(ImGuiCol_Text, t.text); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, t.card_rounding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, metrics::card_padding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, t.border_size > 0 ? t.border_size : 1); + + ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; + if (width <= 0) + flags |= ImGuiWindowFlags_AlwaysAutoResize; + + const bool open = ImGui::BeginPopupModal(id, nullptr, flags); + if (open) + { + if (not title.empty()) + { + ImGui::PushFont(nullptr, style.FontSizeBase * metrics::font_modal_title); + ImGui::TextUnformatted(title.c_str()); + ImGui::PopFont(); + ImGui::Dummy({0, style.ItemSpacing.y}); + } + } + else + { + ImGui::PopStyleVar(3); + ImGui::PopStyleColor(3); + } + return open; +} + +void end_modal() +{ + ImGui::EndPopup(); + ImGui::PopStyleVar(3); + ImGui::PopStyleColor(3); +} + +int confirm_modal(const char * id, const std::string & title, const std::string & message, const std::string & confirm_label, const std::string & cancel_label, bool danger) +{ + int result = 0; + if (begin_modal(id, title, 520)) + { + const theme & t = current(); + ImGui::PushStyleColor(ImGuiCol_Text, t.text_muted); + ImGui::TextWrapped("%s", message.c_str()); + ImGui::PopStyleColor(); + ImGui::Dummy({0, 12}); + + const float gap = ImGui::GetStyle().ItemSpacing.x; + const float cancel_w = ImGui::CalcTextSize(cancel_label.c_str()).x + metrics::button_padding.x * 2; + const float confirm_w = ImGui::CalcTextSize(confirm_label.c_str()).x + metrics::button_padding.x * 2; + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetContentRegionAvail().x - cancel_w - confirm_w - gap); + if (button(cancel_label, button_style::secondary, {cancel_w, 0})) + { + result = -1; + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (button(confirm_label, danger ? button_style::danger : button_style::primary, {confirm_w, 0})) + { + result = 1; + ImGui::CloseCurrentPopup(); + } + end_modal(); + } + return result; +} + +namespace +{ +std::vector list_row_after; // cursor to restore at end_list_row +} + +list_row_result begin_list_row(const char * id, const char * icon, ImTextureID image, const std::string & title, const std::string & subtitle, bool selected, float trailing_width, float height, bool large_thumb, bool interactive) +{ + ImGuiWindow * window = ImGui::GetCurrentWindow(); + const theme & t = current(); + const ImGuiStyle & style = ImGui::GetStyle(); + + // measure title + (possibly multi-line) subtitle so the row can auto-size + const float pad = metrics::list_row_pad; + const float box = large_thumb ? metrics::list_row_box_large : metrics::list_row_box; + const ImVec2 ts = ImGui::CalcTextSize(title.c_str()); + ImVec2 sub_sz{0, 0}; + if (not subtitle.empty()) + { + ImGui::PushFont(nullptr, style.FontSizeBase * metrics::font_description); + sub_sz = ImGui::CalcTextSize(subtitle.c_str()); + ImGui::PopFont(); + } + const float text_h = ts.y + (subtitle.empty() ? 0 : metrics::label_line_gap + sub_sz.y); + const float row_h = height > 0 ? height : ImMax(box, text_h) + 2 * pad; + const ImVec2 p0 = window->DC.CursorPos; + const float avail = ImGui::GetContentRegionAvail().x; + + // non-interactive rows just reserve layout space, no click area and no hover highlight + bool clicked = false; + if (interactive) + { + // the click area excludes the trailing controls so they receive their own clicks + ImGui::SetNextItemAllowOverlap(); + clicked = ImGui::InvisibleButton(id, {ImMax(avail - trailing_width, 1.f), row_h}); + hover_haptic(); + } + else + ImGui::Dummy({avail, row_h}); + const bool hovered = interactive and ImGui::IsItemHovered(); + list_row_after.push_back(window->DC.CursorPos); + + ImDrawList * draw = window->DrawList; + const ImRect bb(p0, p0 + ImVec2(avail, row_h)); + // no tinted background for the selected row, callers mark the active item with a chip + if (hovered) + draw->AddRectFilled(bb.Min, bb.Max, t.col(t.control), t.card_rounding); + + // leading thumbnail or icon box, large_thumb spans the full row height + const float thumb = large_thumb ? row_h - 2 * pad : box; + const ImVec2 box_min = {p0.x + pad, p0.y + (row_h - thumb) * 0.5f}; + const ImVec2 box_max = box_min + ImVec2(thumb, thumb); + if (image) + draw->AddImageRounded(image, box_min, box_max, {0, 0}, {1, 1}, IM_COL32_WHITE, t.rounding); + else + { + draw->AddRectFilled(box_min, box_max, t.col(selected ? t.accent : t.control), t.rounding); + if (icon and icon[0]) + { + const ImVec2 is = ImGui::CalcTextSize(icon); + draw->AddText(box_min + (ImVec2(thumb, thumb) - is) * 0.5f, t.col(selected ? t.on_accent : t.text_muted), icon); + } + } + + // title + subtitle + const float tx = box_max.x + pad; + const float total = subtitle.empty() ? ts.y : ts.y + metrics::label_line_gap + sub_sz.y; + const float ty = p0.y + (row_h - total) * 0.5f; + draw->AddText({tx, ty}, t.col(t.text), title.c_str()); + if (not subtitle.empty()) + { + ImGui::PushFont(nullptr, style.FontSizeBase * metrics::font_description); + draw->AddText({tx, ty + ts.y + metrics::label_line_gap}, t.col(t.text_muted), subtitle.c_str()); + ImGui::PopFont(); + } + + // trailing controls right-align against the inner padding + return {bb.Min, {bb.Max.x - pad, bb.Max.y}, clicked}; +} + +void end_list_row() +{ + ImGui::GetCurrentWindow()->DC.CursorPos = list_row_after.back(); + list_row_after.pop_back(); +} + +int action_menu(const char * id, const char * icon, const std::vector & items) +{ + const theme & t = current(); + + if (icon_button(icon, {}, false)) + ImGui::OpenPopup(id); + + int chosen = -1; + + const float pad = metrics::combo_padding.x; + const float icon_w = ImGui::GetFontSize() * 1.5f; + float content_w = 0; + for (const auto & it: items) + content_w = ImMax(content_w, icon_w + pad + ImGui::CalcTextSize(it.label).x + pad * 2 + ImGui::GetFontSize()); + + // centred modal on the popup layer, like combo() + ImGui::SetNextWindowPos(popup_center, ImGuiCond_Always, {0.5f, 0.5f}); + ImGui::SetNextWindowSize({ImMax(content_w, metrics::combo_modal_min_width), 0}); + + ImGui::PushStyleColor(ImGuiCol_PopupBg, t.card); + ImGui::PushStyleColor(ImGuiCol_Border, t.border); + ImGui::PushStyleColor(ImGuiCol_Text, t.text); + ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, t.card_rounding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, metrics::card_padding); + ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, t.border_size > 0 ? t.border_size : 1); + + if (ImGui::BeginPopupModal(id, nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGuiWindow * window = ImGui::GetCurrentWindow(); + const float row_h = ImGui::GetFrameHeight() * metrics::control_height; + + for (int i = 0; i < int(items.size()); ++i) + { + const action_item & it = items[i]; + ImGui::PushID(i); + const float row_w = ImGui::GetContentRegionAvail().x; + const ImVec2 pos = window->DC.CursorPos; + const ImRect bb(pos, pos + ImVec2(row_w, row_h)); + ImGui::ItemSize(bb, 0); + const ImGuiID gid = window->GetID("##row"); + if (ImGui::ItemAdd(bb, gid)) + { + bool hovered, held; + if (ImGui::ButtonBehavior(bb, gid, &hovered, &held)) + { + chosen = i; + ImGui::CloseCurrentPopup(); + } + hover_haptic(); + + ImDrawList * draw = window->DrawList; + if (hovered) + draw->AddRectFilled(bb.Min, bb.Max, t.col(t.control_hovered), t.rounding); + + const ImU32 fg = t.col(it.danger ? t.danger : t.text); + const ImVec2 its = ImGui::CalcTextSize(it.icon); + draw->AddText({bb.Min.x + pad + (icon_w - its.x) * 0.5f, bb.Min.y + (row_h - its.y) * 0.5f}, fg, it.icon); + const ImVec2 ls = ImGui::CalcTextSize(it.label); + draw->AddText({bb.Min.x + pad + icon_w, bb.Min.y + (row_h - ls.y) * 0.5f}, fg, it.label); + if (it.checked) + { + const ImVec2 cs = ImGui::CalcTextSize(ICON_FA_CHECK); + draw->AddText({bb.Max.x - pad - cs.x, bb.Min.y + (row_h - cs.y) * 0.5f}, t.col(t.accent), ICON_FA_CHECK); + } + } + ImGui::PopID(); + } + + // click outside dismisses, AllowWhenBlockedByActiveItem so pressing a row still counts as inside + if (ImGui::IsMouseClicked(ImGuiMouseButton_Left) and not ImGui::IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem)) + ImGui::CloseCurrentPopup(); + + ImGui::EndPopup(); + } + + ImGui::PopStyleVar(3); + ImGui::PopStyleColor(3); + return chosen; +} + +void top_bar(float height, ImTextureID logo, const std::vector & right_items) +{ + const float side = ImGui::GetFrameHeight() * metrics::control_height; + const float gap = 8; + const float margin = 24; + + // transparent child bg so the alpha-blended window background shows through + ImGui::SetCursorPos({0, 0}); + ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4{0, 0, 0, 0}); + ImGui::BeginChild("TopBar", {ImGui::GetWindowSize().x, height}, 0, ImGuiWindowFlags_NoScrollbar); + { + // logo: WiVRn mascot followed by the wordmark + const float logo_size = 44; + ImGui::SetCursorPos({margin, (height - logo_size) * 0.5f}); + if (logo) + ImGui::Image(logo, {logo_size, logo_size}); + ImGui::SameLine(0, 12); + ImGui::PushFont(nullptr, ImGui::GetStyle().FontSizeBase * 1.3f); + ImGui::SetCursorPosY((height - ImGui::GetFontSize()) * 0.5f); + ImGui::TextUnformatted("WiVRn"); + ImGui::PopFont(); + + // right-aligned cluster + float cluster_w = 0; + for (const auto & it: right_items) + cluster_w += it.width; + if (not right_items.empty()) + cluster_w += gap * (right_items.size() - 1); + + ImGui::SetCursorPos({ImGui::GetWindowSize().x - margin - cluster_w, (height - side) * 0.5f}); + for (size_t i = 0; i < right_items.size(); ++i) + { + ImGui::SetCursorPosY((height - side) * 0.5f); + right_items[i].draw(); + if (i + 1 < right_items.size()) + ImGui::SameLine(0, gap); + } + } + ImGui::EndChild(); + ImGui::PopStyleColor(); +} + +void begin_sidebar(float top_bar_h, float tab_width, int footer_items) +{ + // shares the transparent window background, sections separated by shell_dividers + ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4{0, 0, 0, 0}); + ImGui::SetCursorPos({0, top_bar_h}); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, {16, 16}); + ImGui::BeginChild("Tabs", {tab_width, ImGui::GetWindowSize().y - top_bar_h}, ImGuiChildFlags_AlwaysUseWindowPadding); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {0, 4}); + + // nav list scrolls in a child that fills the rest, footer stays pinned in footer_items rows + const float row_h = ImGui::GetFrameHeight() * metrics::control_height + ImGui::GetStyle().ItemSpacing.y; + sidebar_footer_height = footer_items > 0 ? footer_items * row_h : 0; + ImGui::BeginChild("TabsScroll", {0, ImGui::GetContentRegionAvail().y - sidebar_footer_height}); +} + +void sidebar_footer() +{ + ::ScrollWhenDragging(); // drag to scroll the nav list, like the rest of the GUI + ImGui::EndChild(); // TabsScroll + // pin the footer to the bottom of the sidebar + ImGui::SetCursorPosY(ImGui::GetContentRegionAvail().y + ImGui::GetCursorScreenPos().y - ImGui::GetWindowPos().y - sidebar_footer_height); +} + +void end_sidebar() +{ + ImGui::PopStyleVar(); // ImGuiStyleVar_ItemSpacing + ImGui::EndChild(); // Tabs + ImGui::PopStyleVar(); // ImGuiStyleVar_WindowPadding + ImGui::PopStyleColor(); // ImGuiCol_ChildBg +} + +void shell_dividers(float top_bar_h, float tab_width) +{ + ImVec4 divider_col = current().border; + divider_col.w *= background_alpha(); // follow the panel opacity + const ImU32 divider = ImGui::GetColorU32(divider_col); + const ImVec2 win_pos = ImGui::GetWindowPos(); + const ImVec2 win_size = ImGui::GetWindowSize(); + ImDrawList * dl = ImGui::GetWindowDrawList(); + dl->AddLine({win_pos.x, win_pos.y + top_bar_h}, {win_pos.x + win_size.x, win_pos.y + top_bar_h}, divider); + dl->AddLine({win_pos.x + tab_width, win_pos.y + top_bar_h}, {win_pos.x + tab_width, win_pos.y + win_size.y}, divider); +} + +} // namespace wivrn::ui diff --git a/client/render/ui_widgets.h b/client/render/ui_widgets.h new file mode 100644 index 00000000..1d6d3b70 --- /dev/null +++ b/client/render/ui_widgets.h @@ -0,0 +1,199 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2026 Guillaume Meunier + * Copyright (C) 2026 Patrick Nicolas + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#pragma once + +#include +#include +#include +#include + +// Themed, reusable UI widgets, colors and metrics from wivrn::ui::current() +// Display text takes const std::string &, ids and icon glyphs stay const char * +namespace wivrn::ui +{ + +enum class button_style +{ + primary, // accent fill + secondary, // control fill + danger, // destructive + ghost, // transparent until hovered +}; + +// Page title with an optional muted subtitle +void page_header(const std::string & title, const std::string & subtitle = {}); + +// Rounded panel, pair with end_card +bool begin_card(const char * id, const ImVec2 & size = {0, 0}); +// Tighter padding, for cards holding a list of rows +bool begin_list_card(const char * id); +void end_card(); + +// Full-width divider between rows of a card +void row_separator(); + +// Title and wrapped muted description on the left, control_width reserved on the right +// Returns the window-local y of the label bottom, to keep the row tall enough for a multi-line label +float setting_label(const std::string & title, const std::string & description, float control_width); + +// "