diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 2e346f6b83..b063bfb07f 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -539,6 +539,9 @@ jobs: rustup target add --toolchain 1.90.0 aarch64-unknown-linux-gnu RUSTUP_TOOLCHAIN=1.90.0 bash tools/comet/build.sh + - name: Build the add-on packs + run: bash tools/packs/build.sh app/build/packs + - name: Build id: build env: @@ -642,6 +645,14 @@ jobs: retention-days: 30 compression-level: 0 + - uses: actions/upload-artifact@v4 + with: + name: droiddeck-packs + path: app/build/packs/*.tar.zst + if-no-files-found: error + retention-days: 30 + compression-level: 0 + - name: Report on the pull request if: always() && github.event_name == 'pull_request' continue-on-error: true @@ -744,8 +755,17 @@ jobs: variants: ${{ needs.build.outputs.variants }} secrets: inherit + packs: + needs: build + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + permissions: + contents: read + actions: read + uses: ./.github/workflows/publish-packs.yml + secrets: inherit + announce: - needs: [build, sign] + needs: [build, sign, packs] if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' runs-on: ubuntu-24.04 timeout-minutes: 10 diff --git a/.github/workflows/pr-release-publish.yml b/.github/workflows/pr-release-publish.yml index b55d2a2143..dab96e0154 100644 --- a/.github/workflows/pr-release-publish.yml +++ b/.github/workflows/pr-release-publish.yml @@ -176,6 +176,27 @@ jobs: pattern: droiddeck-pr-signed-* merge-multiple: true path: signed + - name: The add-on packs main has not published + env: + GH_TOKEN: ${{ github.token }} + RUN: ${{ needs.authorize.outputs.run_id }} + run: | + set -euo pipefail + gh run download "$RUN" -R "$GITHUB_REPOSITORY" -n droiddeck-packs -D packs + mkdir -p pr-packs + for file in packs/*.tar.zst; do + name=$(basename "$file" .tar.zst) + sha=$(sha256sum "$file" | cut -d' ' -f1) + tag="pack-$name-${sha:0:16}" + digest=$({ gh api "repos/Droid-Deck/DroidDeck-Components/releases/tags/$tag" 2>/dev/null || echo '{}'; } | + jq -r --arg n "$name.tar.zst" '.assets // [] | .[] | select(.name == $n) | .digest // empty') + if [ "$digest" = "sha256:$sha" ]; then + echo "$name: served from DroidDeck-Components $tag" + else + cp "$file" "pr-packs/$tag.tar.zst" + echo "$name: attached to the PR release as $tag.tar.zst" + fi + done - name: Describe the change env: GH_TOKEN: ${{ github.token }} @@ -233,6 +254,7 @@ jobs: first=true fi echo "first=$first" >> "$GITHUB_OUTPUT" + cp pr-packs/* signed/ 2>/dev/null || true gh release upload "$tag" signed/* -R "$repo" --clobber gh release edit "$tag" -R "$repo" --title "PR #$PR_NUMBER" --notes "$notes" --prerelease keep=$(cd signed && ls | jq -R . | jq -sc .) diff --git a/.github/workflows/publish-packs.yml b/.github/workflows/publish-packs.yml new file mode 100644 index 0000000000..580b1c8188 --- /dev/null +++ b/.github/workflows/publish-packs.yml @@ -0,0 +1,83 @@ +name: Publish add-on packs + +# The add-on packs (tools/packs/build.sh) a Build APK run made, published to DroidDeck-Components under +# content-addressed tags (pack--). The APK from that run pins each pack's +# SHA-256 and downloads it from that tag. A tag is created once and never replaced. +# Only main and release builds publish here; a PR test build attaches the packs main has not published +# to its pr-N release on DroidDeck-CI (pr-release-publish.yml), which is deleted when the PR closes. + +on: + workflow_call: + inputs: + run_id: + description: The Build APK run whose packs to publish; empty for the calling run's own + type: string + default: '' + +permissions: + contents: read + actions: read + +jobs: + publish: + name: publish add-on packs + runs-on: ubuntu-24.04 + timeout-minutes: 15 + concurrency: + group: publish-packs + cancel-in-progress: false + steps: + - name: The packs (this run's build) + if: inputs.run_id == '' + uses: actions/download-artifact@v4 + with: + name: droiddeck-packs + path: packs + + - name: The packs (another Build APK run) + if: inputs.run_id != '' + env: + GH_TOKEN: ${{ github.token }} + RUN: ${{ inputs.run_id }} + run: gh run download "$RUN" -R "$GITHUB_REPOSITORY" -n droiddeck-packs -D packs + + - uses: actions/create-github-app-token@v2 + id: components-token + with: + app-id: ${{ vars.DROIDDECK_CI_APP_ID }} + private-key: ${{ secrets.DROIDDECK_CI_APP_KEY }} + owner: Droid-Deck + repositories: DroidDeck-Components + + - name: Publish + env: + GH_TOKEN: ${{ steps.components-token.outputs.token }} + REPO: Droid-Deck/DroidDeck-Components + BUILD_RUN: ${{ inputs.run_id || github.run_id }} + run: | + set -euo pipefail + published_digest() { + { gh api "repos/$REPO/releases/tags/$1" 2>/dev/null || echo '{}'; } | + jq -r --arg n "$2" '.assets // [] | .[] | select(.name == $n) | .digest // empty' + } + commit=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$BUILD_RUN" --jq .head_sha 2>/dev/null || echo "$GITHUB_SHA") + for name in proot directaudio tracking xbox comet; do + file="packs/$name.tar.zst" + [ -f "$file" ] || { echo "::error::$name.tar.zst is missing from Build APK run $BUILD_RUN"; exit 1; } + sha=$(sha256sum "$file" | cut -d' ' -f1) + tag="pack-$name-${sha:0:16}" + digest=$(published_digest "$tag" "$name.tar.zst") + if [ -z "$digest" ]; then + notes="DroidDeck add-on pack \`$name\`, built by [Build APK run $BUILD_RUN]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$BUILD_RUN) from \`$commit\` with tools/packs/build.sh and published by [run $GITHUB_RUN_ID]($GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID). + + Size: $(stat -c %s "$file") bytes. SHA-256: $sha. APKs built in the same run pin this digest." + gh release create "$tag" -R "$REPO" --title "$tag" --notes "$notes" --latest=false "$file" \ + || echo "::warning::creating $tag failed; checking whether another run published it" + digest=$(published_digest "$tag" "$name.tar.zst") + fi + if [ "$digest" != "sha256:$sha" ]; then + echo "::error::$tag holds ${digest:-nothing} for $name.tar.zst, not sha256:$sha" + exit 1 + fi + echo "- \`$name\`: [$tag]($GITHUB_SERVER_URL/$REPO/releases/tag/$tag) \`$sha\`" >> "$GITHUB_STEP_SUMMARY" + done diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b8fe920602..a151592681 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -63,9 +63,19 @@ jobs: artifact: droiddeck-release secrets: inherit + packs: + needs: find + permissions: + contents: read + actions: read + uses: ./.github/workflows/publish-packs.yml + with: + run_id: ${{ needs.find.outputs.run_id }} + secrets: inherit + publish: name: publish the release - needs: [find, sign] + needs: [find, sign, packs] runs-on: ubuntu-24.04 timeout-minutes: 10 permissions: diff --git a/README.md b/README.md index abb3beb3f2..5ead273034 100644 --- a/README.md +++ b/README.md @@ -47,10 +47,12 @@ Compatibility and performance vary by device; hardware validation is limited. De ## Credits and licence -GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. The registry entries a GOG game's install script (`goggame-.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc//mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve. +GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. The registry entries a GOG game's install script (`goggame-.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc//mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and is already on through Proton. See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve. XR glasses support builds on WinNative's VITURE glasses work. VITURE protocol details were checked against [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) by [@wheaney](https://github.com/wheaney), including the VITURE protocol header it ships, [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) by [@badicsalex](https://github.com/badicsalex) and the [go-macos/iokit VITURE package](https://pkg.go.dev/github.com/go-macos/iokit/viture); the optional VITURE SDK belongs to VITURE and is not included. RayNeo support adapts [@informalTechCode](https://github.com/informalTechCode)'s [RayNeo-Air-Series-3DoF-Scaffold](https://github.com/informalTechCode/RayNeo-Air-Series-3DoF-Scaffold) (Apache-2.0) and references [@verncat](https://github.com/verncat)'s [RayNeo-Air-3S-Pro-OpenVR](https://github.com/verncat/RayNeo-Air-3S-Pro-OpenVR) (MIT) and [Monado](https://gitlab.freedesktop.org/monado/monado) (BSL-1.0); see [docs/third-party/rayneo](docs/third-party/rayneo/README.md). XREAL 1S support references [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) and [xrealOneDeviceKit](https://github.com/wheaney/xrealOneDeviceKit) by @wheaney, [xreal_one_driver](https://github.com/rohitsangwan01/xreal_one_driver) by [@rohitsangwan01](https://github.com/rohitsangwan01) (MIT) and [xr-tools](https://github.com/0xcaff/xr-tools) by [@0xcaff](https://github.com/0xcaff). The REDMAGIC glasses-display findings draw on [@mekhontsev](https://github.com/mekhontsev)'s [MagicDesk investigation](https://github.com/mekhontsev/magicdesk/blob/main/docs/xr-resolution-fix.md) and [@Coding-BR](https://github.com/Coding-BR)'s [decompiled Nubia kernel](https://github.com/Coding-BR/android_kernel_nubia_sm8850_qwjujube). VITURE, RayNeo, XREAL and REDMAGIC are trademarks of their owners; this project is not affiliated with them. Joy-Con VR controllers port the arm model of Google's [Google VR SDK for Unity](https://github.com/googlevr/gvr-unity-sdk) (Apache-2.0), adapt the hand skeleton of Valve's [OpenVR](https://github.com/ValveSoftware/openvr) `handskeletonsimulation` sample (BSD-3-Clause), which follows Moshi Turner's hand simulation in [Monado](https://gitlab.freedesktop.org/monado/monado), and use the Index controller offsets from Monado's `vive_poses.c` (BSL-1.0). Joy-Con behaviour was researched in Linux's [hid-nintendo](https://github.com/torvalds/linux/blob/master/drivers/hid/hid-nintendo.c) driver by Daniel J. Ogorchock, [@dekuNukem](https://github.com/dekuNukem)'s [Nintendo_Switch_Reverse_Engineering](https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering), [SDL](https://github.com/libsdl-org/SDL) and the Android Open Source Project, and checked against [ALVR](https://github.com/alvr-org/ALVR), [OpenComposite](https://gitlab.com/znixian/OpenOVR), [PSMoveSteamVRBridge](https://github.com/HipsterSloth/PSMoveSteamVRBridge), [@F8LEFT](https://github.com/F8LEFT)'s [JoyConVr](https://github.com/F8LEFT/JoyConVr), [@krnelpan1c](https://github.com/krnelpan1c)'s [Daydream-Controller-SteamVR](https://github.com/krnelpan1c/Daydream-Controller-SteamVR), [@yoyobuae](https://github.com/yoyobuae)'s [joyconvr](https://github.com/yoyobuae/joyconvr), [Moonlight](https://github.com/moonlight-stream/moonlight-android) and [Dolphin](https://github.com/dolphin-emu/dolphin); see [docs/third-party/joycon](docs/third-party/joycon/README.md). Nintendo Switch and Joy-Con are trademarks of Nintendo; this project is not affiliated with Nintendo. Camera hand tracking runs Google's [MediaPipe](https://github.com/google-ai-edge/mediapipe) Tasks Vision library with its Pose Landmarker (Lite) model, BlazePose GHUM 3D, and its Hand Landmarker model (all Apache-2.0), on frames from AndroidX [CameraX](https://developer.android.com/jetpack/androidx/releases/camera) (Apache-2.0); MediaPipe's usage reports are switched off. The design was checked against [@F8LEFT](https://github.com/F8LEFT)'s [JoyConVr](https://github.com/F8LEFT/JoyConVr) camera app (MIT), and the short Joy-Con movements follow the accelerometer mode of the [Google VR SDK for Unity](https://github.com/googlevr/gvr-unity-sdk)'s arm model, Eric Foxlin's zero-velocity updates and Frosio, Pedersini and Borghese's accelerometer autocalibration, and the camera and Joy-Con are joined by a Kalman filter (R. E. Kalman, 1960). Bare camera hands take their gestures after [ALVR](https://github.com/alvr-org/ALVR)'s `hand_gestures.rs` (MIT) and Meta Quest's menu pinch, with distances checked on photos from the [HaGRID](https://github.com/hukenovs/hagrid) gesture set (CC BY-SA 4.0, not included), fit the palm with Horn's quaternion method (1987) and smooth it with the 1€ filter (Casiez, Roussel and Vogel, 2012); the white glove model follows Valve's OpenVR render model reference and Index controller poses, is meshed with surface nets (Gibson, 1998; Mikola Lysenko) and blends and shades it with Inigo Quilez's smooth minimum and distance-field ambient occlusion, porting his polygon distance (MIT); see [docs/third-party/handtracking](docs/third-party/handtracking/README.md). + +The Store installs and runs apps with [Flatpak](https://github.com/flatpak/flatpak) (LGPL-2.1). Its sandbox goes through DroidDeck's own bubblewrap shim, which follows how Flatpak hands bwrap its environment. diff --git a/app/build.gradle b/app/build.gradle index c11a7557a2..1a39d2a8e2 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -84,6 +84,23 @@ def commitTime = (gitValue(['show', '-s', '--format=%ct', 'HEAD']) ?: '0').with def desktopKde = rootProject.file('tools/desktop-kde/release.env').readLines() .findAll { it.contains('=') && !it.startsWith('#') } .collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] } +def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLines() + .findAll { it.contains('=') && !it.startsWith('#') } + .collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] } +def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet'].collectEntries { name -> + def pack = file("build/packs/${name}.tar.zst") + if (!pack.isFile()) { + if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs") + return [(name): [sha256: '', size: 0L]] + } + def digest = java.security.MessageDigest.getInstance('SHA-256') + pack.withInputStream { input -> + byte[] buffer = new byte[1 << 20] + int n + while ((n = input.read(buffer)) > 0) digest.update(buffer, 0, n) + } + [(name): [sha256: digest.digest().encodeHex().toString(), size: pack.length()]] +} def desktopRemovalSources = new groovy.json.JsonSlurper().parse(file('src/main/assets/desktop-removal/sources.json')) if (desktopRemovalSources.archives[desktopKde.DESKTOP_KDE_TAG] != desktopKde.DESKTOP_KDE_SHA256) { throw new GradleException('Desktop removal inventories do not match the pinned archive') @@ -119,6 +136,10 @@ android { buildConfigField "String", "DESKTOP_KDE_URL", "\"https://github.com/${desktopKde.DESKTOP_KDE_REPO}/releases/download/${desktopKde.DESKTOP_KDE_TAG}/desktop-kde.tar.zst\"" buildConfigField "String", "DESKTOP_KDE_SHA256", "\"${desktopKde.DESKTOP_KDE_SHA256}\"" buildConfigField "long", "DESKTOP_KDE_SIZE", "${desktopKde.DESKTOP_KDE_SIZE}L" + addonPacks.each { name, pack -> + buildConfigField "String", "PACK_${name.toUpperCase()}_SHA256", "\"${pack.sha256}\"" + buildConfigField "long", "PACK_${name.toUpperCase()}_SIZE", "${pack.size}L" + } ndk { abiFilters 'arm64-v8a' @@ -172,6 +193,11 @@ android { disable 'ExpiredTargetSdkVersion' } + androidResources { + // aapt's default ignore list, plus the trees shipped as add-on packs (tools/packs). + ignoreAssetsPattern '!.svn:!.git:!.ds_store:!*.scc:.*:_*:!CVS:!thumbs.db:!picasa.ini:!*~:droiddeck-xbox:droiddeck-comet:directaudio' + } + packagingOptions { resources { excludes += ['META-INF/versions/9/OSGI-INF/MANIFEST.MF'] @@ -179,6 +205,8 @@ android { jniLibs { useLegacyPackaging = true pickFirsts += ['**/libtermux.so'] + // Shipped in the proot and tracking packs (tools/packs) and run or loaded from there. + excludes += ['**/libproot.so', '**/libproot-loader.so', '**/libopencv_java4.so', '**/libmediapipe_tasks_jni.so'] } } @@ -285,22 +313,8 @@ def buildRustStores = tasks.register('buildRustStores', Exec) { if (!skipRust) android.sourceSets.main.jniLibs.srcDir(rustJniLibsDir) tasks.named('preBuild').configure { dependsOn(buildRustStores) } -def verifyHandModel = tasks.register('verifyHandModel') { - def models = ['hand_landmarker.task': 'fbc2a30080c3c557093b5ddfc334698132eb341044ccee322ccf8bcf3607cde1', - 'hand_landmarker_lite.task': '173c0f47ecee7e935bd4a1e93aa580756b4180c1307c07d709313e82c28672c8'] - .collectEntries { name, hash -> [(file("src/main/assets/models/$name")): hash] } - inputs.files(models.keySet()) - doLast { - models.each { model, expected -> - def actual = java.security.MessageDigest.getInstance('SHA-256').digest(model.bytes).encodeHex().toString() - if (actual != expected) throw new GradleException("Hand Landmarker model checksum mismatch: ${model.name}") - } - } -} -tasks.named('preBuild').configure { dependsOn(verifyHandModel) } - dependencies { - implementation 'org.opencv:opencv:4.13.0' + implementation "org.opencv:opencv:${trackingPack.OPENCV_VERSION}" implementation 'org.khronos.openxr:openxr_loader_for_android:1.1.49' implementation 'com.github.luben:zstd-jni:1.5.7-4@aar' implementation 'org.apache.commons:commons-compress:1.27.1' @@ -320,7 +334,7 @@ dependencies { implementation 'androidx.camera:camera-camera2:1.4.2' implementation 'androidx.camera:camera-lifecycle:1.4.2' implementation 'androidx.webkit:webkit:1.12.1' - implementation('com.google.mediapipe:tasks-vision:1.0.0') { + implementation("com.google.mediapipe:tasks-vision:${trackingPack.MEDIAPIPE_VERSION}") { exclude group: 'com.google.auto.value', module: 'auto-value' } diff --git a/app/src/main/assets/handtracking/hand_landmarker.task b/app/src/main/assets/handtracking/hand_landmarker.task deleted file mode 100644 index 0d53faf378..0000000000 Binary files a/app/src/main/assets/handtracking/hand_landmarker.task and /dev/null differ diff --git a/app/src/main/assets/handtracking/pose_landmarker_lite.task b/app/src/main/assets/handtracking/pose_landmarker_lite.task deleted file mode 100644 index 09576a9301..0000000000 Binary files a/app/src/main/assets/handtracking/pose_landmarker_lite.task and /dev/null differ diff --git a/app/src/main/assets/models/hand_landmarker.task b/app/src/main/assets/models/hand_landmarker.task deleted file mode 100644 index 0d53faf378..0000000000 Binary files a/app/src/main/assets/models/hand_landmarker.task and /dev/null differ diff --git a/app/src/main/cpp/fakeinput_steam.cpp b/app/src/main/cpp/fakeinput_steam.cpp index 486b72076e..ba4b14ec50 100644 --- a/app/src/main/cpp/fakeinput_steam.cpp +++ b/app/src/main/cpp/fakeinput_steam.cpp @@ -21,6 +21,9 @@ #include #include +#ifdef __GLIBC__ +#include +#endif #include #include #include @@ -3577,7 +3580,21 @@ EXPORT int close(int fd) { static constexpr int kMaxRingWaitMs = 2; static constexpr int kLowLatencyRingWaitUs = 250; -EXPORT ssize_t read(int fd, void *buf, size_t count) { +static ssize_t copy_input_events(void *buf, const struct input_event *events, size_t count) { + size_t bytes = count * sizeof(struct input_event); + struct iovec local = {const_cast(events), bytes}; + struct iovec remote = {buf, bytes}; + ssize_t copied = syscall(SYS_process_vm_writev, getpid(), &local, 1, &remote, 1, 0); + if (copied < 0) return -1; + if (copied != static_cast(bytes)) { + errno = EFAULT; + copied -= copied % sizeof(struct input_event); + if (!copied) return -1; + } + return copied; +} + +static ssize_t read_input(int fd, void *buf, size_t count) { if (!watched(fd)) return syscall(SYS_read, fd, buf, count); std::unique_lock guard(controller_mutex()); auto controller = controller_map().find(fd); @@ -3622,42 +3639,44 @@ EXPORT ssize_t read(int fd, void *buf, size_t count) { if (events == 0) break; const uint8_t *ring_events = reinterpret_cast(fake.ring) + FAKE_INPUT_RING_HEADER_SIZE; + std::vector input_events(events); for (size_t i = 0; i < events; ++i) { size_t index = (fake.read_seq + i) % FAKE_INPUT_RING_CAPACITY; RingEvent stored; memcpy(&stored, ring_events + index * FAKE_INPUT_EVENT_SIZE, FAKE_INPUT_EVENT_SIZE); - struct input_event ev = {}; + struct input_event &ev = input_events[i]; ev.time.tv_sec = stored.sec; ev.time.tv_usec = stored.usec; ev.type = stored.type; ev.code = stored.code; ev.value = stored.value; if (ev.type == EV_ABS) ev.code = presented_abs_code(fake, ev.code); - memcpy(static_cast(buf) + i * sizeof(ev), &ev, sizeof(ev)); } __atomic_thread_fence(__ATOMIC_ACQUIRE); if (snap.sequence != __atomic_load_n(&fake.ring->snapshot_seq, __ATOMIC_RELAXED)) continue; - fake.read_seq += events; - return static_cast(events * sizeof(struct input_event)); + ssize_t copied = copy_input_events(buf, input_events.data(), events); + if (copied > 0) fake.read_seq += copied / sizeof(struct input_event); + return copied; } } size_t events = std::min(requested, fake.keyframe_remaining); + struct input_event input_events[kNeutralEventCount] = {}; struct timeval now = {}; gettimeofday(&now, nullptr); for (size_t i = 0; i < events; ++i) { - size_t index = kNeutralEventCount - fake.keyframe_remaining; - struct input_event ev = {}; + size_t index = kNeutralEventCount - fake.keyframe_remaining + i; + struct input_event &ev = input_events[i]; ev.time = now; ev.type = kNeutralEvents[index].type; ev.code = kNeutralEvents[index].code; ev.value = keyframe_value(fake, ev.type, ev.code); if (ev.type == EV_ABS) ev.code = presented_abs_code(fake, ev.code); - memcpy(static_cast(buf) + i * sizeof(ev), &ev, sizeof(ev)); - --fake.keyframe_remaining; } - return static_cast(events * sizeof(struct input_event)); + ssize_t copied = copy_input_events(buf, input_events, events); + if (copied > 0) fake.keyframe_remaining -= copied / sizeof(struct input_event); + return copied; } if (nonblock) { errno = EAGAIN; @@ -3673,6 +3692,52 @@ EXPORT ssize_t read(int fd, void *buf, size_t count) { } } +EXPORT ssize_t read(int fd, void *buf, size_t count) { + return read_input(fd, buf, count); +} + +EXPORT ssize_t readv(int fd, const struct iovec *iov, int iovcnt) { + if (!is_fake_input_fd(fd)) return syscall(SYS_readv, fd, iov, iovcnt); + if (iovcnt < 0 || iovcnt > IOV_MAX) { + errno = EINVAL; + return -1; + } + if (iovcnt && !iov) { + errno = EFAULT; + return -1; + } + std::vector copied_iov(static_cast(iovcnt)); + if (iovcnt) { + size_t bytes = copied_iov.size() * sizeof(struct iovec); + struct iovec local = {copied_iov.data(), bytes}; + struct iovec remote = {const_cast(iov), bytes}; + ssize_t copied = syscall(SYS_process_vm_readv, getpid(), &local, 1, &remote, 1, 0); + if (copied != static_cast(bytes)) { + errno = EFAULT; + return -1; + } + } + iov = copied_iov.data(); + size_t size = 0; + for (int i = 0; i < iovcnt; ++i) { + if (iov[i].iov_len > static_cast(SSIZE_MAX) - size) { + errno = EINVAL; + return -1; + } + size += iov[i].iov_len; + } + + ssize_t total = 0; + for (int i = 0; i < iovcnt; ++i) { + if (!iov[i].iov_len) continue; + ssize_t got = read_input(fd, iov[i].iov_base, iov[i].iov_len); + if (got < 0) return total ? total : -1; + total += got; + if (static_cast(got) != iov[i].iov_len) break; + } + return total; +} + EXPORT ssize_t write(int fd, const void *buf, size_t count) { static auto my_write = reinterpret_cast(dlsym(RTLD_NEXT, "write")); @@ -4103,4 +4168,92 @@ EXPORT int __fxstat64(int version, int fd, struct stat64 *buf) { if (!real) return fstat64(fd, buf); return fake_stat_fd(fd, buf, [version](int f, struct stat64 *b) { return real(version, f, b); }); } + +#if defined(__x86_64__) || defined(__i386__) +using dlsym_fn = void *(*)(void *, const char *); + +static const char *const interposed_names[] = { + "open", "open64", "openat", "openat64", "close", "read", "readv", "write", "writev", "ioctl", + "poll", "ppoll", "select", "stat", "stat64", "fstat", "fstat64", "__xstat", "__xstat64", + "__fxstat", "__fxstat64", "statx", "statfs", "statfs64", "fstatfs", "fstatfs64", "access", + "faccessat", "opendir", "scandir", "inotify_add_watch", +}; + +static dlsym_fn next_dlsym() { + static const dlsym_fn fn = [] { +#ifdef __x86_64__ + const char *base = "GLIBC_2.2.5"; +#else + const char *base = "GLIBC_2.0"; +#endif + for (const char *version : {base, "GLIBC_2.34"}) { + if (auto found = reinterpret_cast(dlvsym(RTLD_NEXT, "dlsym", version))) return found; + } + return dlsym_fn{}; + }(); + return fn; +} + +static void *global_dlsym(void *, const char *name) { return next_dlsym()(RTLD_DEFAULT, name); } + +static void *missing_dlsym(void *, const char *) { return nullptr; } + +static bool interposed(const char *name) { + for (const char *interposed_name : interposed_names) { + if (strcmp(interposed_name, name) == 0) return true; + } + return false; +} + +extern "C" __attribute__((visibility("hidden"), used)) void *fakeinput_dlsym_target(void *handle, const char *name) { + dlsym_fn next = next_dlsym(); + if (!next) return reinterpret_cast(missing_dlsym); + if (handle == RTLD_DEFAULT || handle == RTLD_NEXT || name == nullptr) return reinterpret_cast(next); + static void *const libc = dlopen(LIBC_SO, RTLD_LAZY | RTLD_NOLOAD); + if (handle != libc || !interposed(name)) return reinterpret_cast(next); + return reinterpret_cast(global_dlsym); +} + +#ifdef __x86_64__ +__asm__(".text\n" + ".globl dlsym\n" + ".type dlsym, @function\n" + "dlsym:\n" + ".cfi_startproc\n" + "pushq %rdi\n" + ".cfi_adjust_cfa_offset 8\n" + "pushq %rsi\n" + ".cfi_adjust_cfa_offset 8\n" + "subq $8, %rsp\n" + ".cfi_adjust_cfa_offset 8\n" + "call fakeinput_dlsym_target\n" + "addq $8, %rsp\n" + ".cfi_adjust_cfa_offset -8\n" + "popq %rsi\n" + ".cfi_adjust_cfa_offset -8\n" + "popq %rdi\n" + ".cfi_adjust_cfa_offset -8\n" + "jmp *%rax\n" + ".cfi_endproc\n" + ".size dlsym, .-dlsym\n"); +#else +__asm__(".text\n" + ".globl dlsym\n" + ".type dlsym, @function\n" + "dlsym:\n" + ".cfi_startproc\n" + "subl $12, %esp\n" + ".cfi_adjust_cfa_offset 12\n" + "movl 20(%esp), %eax\n" + "movl %eax, 4(%esp)\n" + "movl 16(%esp), %eax\n" + "movl %eax, (%esp)\n" + "call fakeinput_dlsym_target\n" + "addl $12, %esp\n" + ".cfi_adjust_cfa_offset -12\n" + "jmp *%eax\n" + ".cfi_endproc\n" + ".size dlsym, .-dlsym\n"); +#endif +#endif #endif diff --git a/app/src/main/cpp/sdnative/sdnative.c b/app/src/main/cpp/sdnative/sdnative.c index c7ec580abb..85e0793b10 100644 --- a/app/src/main/cpp/sdnative/sdnative.c +++ b/app/src/main/cpp/sdnative/sdnative.c @@ -1,5 +1,8 @@ +#include #include #include +#include +#include JNIEXPORT void JNICALL Java_com_droiddeck_launcher_input_FakeInputWriter_nativeStoreFence(JNIEnv *env, jclass clazz) { @@ -7,3 +10,10 @@ Java_com_droiddeck_launcher_input_FakeInputWriter_nativeStoreFence(JNIEnv *env, (void)clazz; atomic_thread_fence(memory_order_release); } + +JNIEXPORT jint JNICALL +Java_com_droiddeck_launcher_session_ThreadSignals_tgkill(JNIEnv *env, jclass clazz, jint tgid, jint tid, jint signal) { + (void)env; + (void)clazz; + return syscall(SYS_tgkill, tgid, tid, signal) == 0 ? 0 : errno; +} diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index 8c79ba2f12..68df13b2c1 100644 --- a/app/src/main/java/com/droiddeck/launcher/App.kt +++ b/app/src/main/java/com/droiddeck/launcher/App.kt @@ -30,6 +30,7 @@ class App : Application() { com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this) com.droiddeck.launcher.update.AppUpdates.init(this) com.droiddeck.launcher.core.DownloadSource.init(this) + prefetchAddonPacks() GpuClockPin.clearLeftover(this) com.droiddeck.launcher.glasses.Glasses.init(this) com.droiddeck.launcher.glasses.GlassesMenuMirror.initialize(this) @@ -42,4 +43,21 @@ class App : Application() { com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.itch.ItchBackend) com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend) } + + /** Fetches the packs an existing setup already relies on, so the first use after an update does not wait. */ + private fun prefetchAddonPacks() { + val app = this + Thread({ + runCatching { + if (com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(app).isDirectory) { + com.droiddeck.launcher.core.AddonPack.PROOT.ensure(app) + com.droiddeck.launcher.core.AddonPack.DIRECTAUDIO.ensure(app) + } + if (com.droiddeck.launcher.stores.gog.GogComet.enabled(app)) com.droiddeck.launcher.core.AddonPack.COMET.ensure(app) + if (com.droiddeck.launcher.stores.StoreAccounts.signedInAs(app, com.droiddeck.launcher.stores.Store.XBOX) != null) + com.droiddeck.launcher.core.AddonPack.XBOX.ensure(app) + com.droiddeck.launcher.handtracking.HandTracking.load(app) + }.onFailure { android.util.Log.w("App", "add-on pack prefetch failed", it) } + }, "addon-packs").start() + } } diff --git a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt index 7aab33d1fc..66b43bc347 100644 --- a/app/src/main/java/com/droiddeck/launcher/MainActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/MainActivity.kt @@ -124,6 +124,7 @@ class MainActivity : ComponentActivity() { private var steamController by mutableStateOf(SessionPrefs.CONTROLLER_DECK) private var showComponents by mutableStateOf(false) private var focusComponentsContent by mutableStateOf(true) + private var componentsGameKey by mutableStateOf(null) private var showMapping by mutableStateOf(false) private var saveBusy: String? = null private var onSavePicked: ((File) -> Unit)? = null @@ -860,6 +861,7 @@ class MainActivity : ComponentActivity() { }, onSteamGameArtChanged = { appId -> refreshSteamGameArt(appId) }, onAddedGameRemoved = { folder, appId, name -> removeAddedGame(folder, appId, name) }, + onGameRemoved = { g -> removeGame(g) }, onAddedGamesArt = { on -> SessionPrefs.setAddedGamesArt(this, on); addedGamesArt = on; if (on) refreshAddedGames() }, onSgdbKey = { key -> Thread({ @@ -921,6 +923,7 @@ class MainActivity : ComponentActivity() { }, onProtons = { openProtons() }, onComponents = { focusContent -> openComponents(focusContent) }, + onGameComponents = { game -> openComponents(gameKey = game.profileKey) }, onComponentsTab = { tab -> openComponents(focusContent = true, tab = tab) }, onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(sg) } }, onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(sg) } }, @@ -1433,8 +1436,9 @@ class MainActivity : ComponentActivity() { ) } - private fun openComponents(focusContent: Boolean = true, tab: String? = null) { + private fun openComponents(focusContent: Boolean = true, tab: String? = null, gameKey: String? = null) { focusComponentsContent = focusContent + componentsGameKey = gameKey if (tab != null) components.compComp = tab showPerformance = false showMapping = false @@ -1483,6 +1487,7 @@ class MainActivity : ComponentActivity() { onImport = { pickComponent.launch(InAppFilePicker.buildIntent(this, WCP_EXT, getString(R.string.comp_pick_wcp))) }, onBack = { if (!com.droiddeck.launcher.ui.Hops.back { showComponents = false }) showComponents = false }, games = steamGames, + initialGameKey = componentsGameKey, generalFexPreset = fexPreset, onGeneralFexPreset = { id -> SessionPrefs.setFexPreset(this, id); fexPreset = id }, gpu = drivers.state(), @@ -1716,12 +1721,12 @@ class MainActivity : ComponentActivity() { SessionPrefs.setRunSteamAtStartup(this, on) runSteamAtStartup = on }, - onBootMovie = { id -> SessionPrefs.setBootMovie(this, id); loadBootMovie() }, + onBootMovie = { id -> com.droiddeck.launcher.session.BootMovie.select(this, id); loadBootMovie() }, onBootMovieSound = { on -> SessionPrefs.setBootMovieSound(this, on); bootMovieSound = on }, onImportBootMovie = { pickBootMovie.launch(InAppFilePicker.buildIntent(this, com.droiddeck.launcher.session.BootMovie.PICKER_EXTENSIONS, getString(R.string.boot_movie_pick))) }, - onRemoveBootMovie = { com.droiddeck.launcher.session.BootMovie.removeCustom(this); loadBootMovie() }, + onBootMovieChanged = { loadBootMovie() }, onDeckyInstall = { release -> decky.installDecky(release) }, onDeckyCheck = { decky.refreshDecky() }, onDeckyEnabled = { enabled -> DeckyManager.setSupervisorEnabled(this, enabled); decky.deckySupervisor = enabled }, @@ -1806,6 +1811,30 @@ class MainActivity : ComponentActivity() { }, "steam-art-update").start() } + private fun removeGame(g: Library.SteamGame) { + val folder = g.gameFiles ?: return + when (com.droiddeck.launcher.frontend.GameRemoval.kind(g)) { + com.droiddeck.launcher.frontend.GameRemoval.Kind.LAUNCHER -> Unit + com.droiddeck.launcher.frontend.GameRemoval.Kind.SHORTCUT -> removeAddedGame(folder.path, g.gameId, g.name) + com.droiddeck.launcher.frontend.GameRemoval.Kind.STORE -> { + val installed = com.droiddeck.launcher.frontend.GameRemoval.storeGame(g) + if (installed != null) { + com.droiddeck.launcher.stores.StoresState.uninstall(this, installed) { refreshAddedGames(); refresh() } + return + } + if (g.library == Library.ADDED) { + removeAddedGame(folder.path, g.gameId, g.name) + return + } + val target = com.droiddeck.launcher.frontend.GameRemoval.steamFiles(g) ?: return + Thread({ + com.droiddeck.launcher.frontend.GameRemoval.delete(target) + ui.post { refreshAddedGames(); refresh() } + }, "game-remove").start() + } + } + } + private fun removeAddedGame(folder: String, appId: Long?, name: String) { steamGames = steamGames.filterNot { it.library == Library.ADDED && it.gameFiles?.path == folder } Thread({ com.droiddeck.launcher.frontend.AddedGames.remove(this, java.io.File(folder), appId, name) }, "added-game-remove").start() diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index d3f18ad6ee..eab2ea02bc 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -623,6 +623,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { onDispose { com.droiddeck.launcher.glasses.GlassesMenuMirror.setSessionMenuVisible(this@SessionActivity, false) } } androidx.compose.runtime.LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, pipUi) { updatePointerCapture() } + androidx.compose.runtime.LaunchedEffect(AgentGuest.steamKeyboard) { updateOnScreenControls() } androidx.compose.runtime.LaunchedEffect(picturePosition, SessionState.running, pipUi, cardboard.enabled) { applyGameAlignment() } DroidDeckTheme { if (pipUi) { @@ -635,7 +636,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { } } else { com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) { - CursorOverlay(cursorPos, cursorVisible, resources.displayMetrics.density, + CursorOverlay({ cursorPos }, cursorVisible, resources.displayMetrics.density, cursorImage, cursorHotX, cursorHotY, cursorImageScale) if (hud.text.isNotEmpty()) HudText(hud.text) if (glassesOutputActive && !loading.visible) com.droiddeck.launcher.ui.GlassesPlayingHint(glasses.model) @@ -735,7 +736,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { achievementsInFront = found if (found == null) achievementsOpen = false } - androidx.compose.runtime.LaunchedEffect(pcKeyboardOpen) { if (pcKeyboardOpen) releasePads() } + androidx.compose.runtime.LaunchedEffect(pcKeyboardOpen) { if (pcKeyboardOpen) releasePads(); updateOnScreenControls() } LaunchedEffect(pcKeyboardOpen, drawerOpen, achievementsOpen) { if (pcKeyboardOpen || drawerOpen || achievementsOpen) padMouse.reset() } @@ -834,6 +835,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { SessionPrefs.setSteamController(this@SessionActivity, id) com.droiddeck.launcher.session.SteamDeckPad.showPad(SessionPrefs.padType(id)) com.droiddeck.launcher.input.FakeInputWriter.setPadType(SessionPrefs.padType(id)) + com.droiddeck.launcher.session.InputSysfsComponent.padTypeChanged(SessionPrefs.padType(id)) padType = id }, backActionsInverted = backActionsInverted, @@ -1601,6 +1603,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { intent.getStringExtra(SessionService.EXTRA_STEAM_UI), intent.getStringExtra(SessionService.EXTRA_STEAM_URL), intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS), + shownOnDisplayId, ) } applyFrameGen() @@ -1651,6 +1654,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { override fun onConfigurationChanged(newConfig: android.content.res.Configuration) { super.onConfigurationChanged(newConfig) + if (started) SessionService.setActivityDisplay(this, shownOnDisplayId) cancelTouchGestures() applyFollowOrientation(newConfig) applyUnfoldedControls() @@ -1875,17 +1879,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { var enosys = 0 var fexMissing = false val size = log.length() - java.io.RandomAccessFile(log, "r").use { f -> + val text = java.io.RandomAccessFile(log, "r").use { f -> val start = maxOf(0L, size - 512L * 1024) f.seek(start) val bytes = ByteArray((size - start).toInt()) f.readFully(bytes) - String(bytes, Charsets.ISO_8859_1).lineSequence().forEach { line -> - if (line.contains("Function not implemented")) enosys++ - if (line.contains(FEX_MISSING)) fexMissing = true - } + String(bytes, Charsets.ISO_8859_1) } - if (fexMissing) { + text.lineSequence().forEach { line -> + if (line.contains("Function not implemented")) enosys++ + if (line.contains(FEX_MISSING)) fexMissing = true + } + val steamSetup = com.droiddeck.launcher.session.SteamClientSetupFailure.find(text.lineSequence()) + if (steamSetup != null) { + val message = getString(if (steamSetup.download) R.string.session_end_steam_download else R.string.session_end_steam_setup) + EndHint(listOfNotNull(message, steamSetup.curlError).joinToString("\n")) + } else if (fexMissing) { val what = com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_end_program) EndHint(getString(R.string.session_end_fex_missing, what), evenOnSuccess = true) } else if (enosys >= 8) { @@ -2274,9 +2283,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { return true } + private val shownOnDisplayId: Int get() = + if (Build.VERSION.SDK_INT >= 30) display?.displayId ?: windowManager.defaultDisplay.displayId + else windowManager.defaultDisplay.displayId + private fun refreshSecondScreenDisplays() { if (!::displayManager.isInitialized) return - val primaryId = display?.displayId ?: windowManager.defaultDisplay.displayId + val primaryId = shownOnDisplayId val candidates = SecondScreenDisplays.available(displayManager, primaryId) .filter { glassesScreen == null || it.id != glasses.displayId } val oldIds = secondScreenDisplays.map { it.id }.toSet() @@ -2663,7 +2676,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { ?.let { FileUtils.readString(it)?.trim()?.lowercase() } ?: SessionPrefs.oscMode(this) val controls = onScreenControls ?: return - if (pipUi || unfoldedPanel != null) { + if (pipUi || unfoldedPanel != null || pcKeyboardOpen) { onScreenButtonsVisible = false controls.releaseAll() controls.visibility = View.GONE @@ -2695,25 +2708,29 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { SessionState.mode != SessionService.MODE_DESKTOP } onScreenButtonsVisible = show + val drawn = show && !keyboardCoversPad() if (steam != null) { if (controls.visibility == View.VISIBLE) { controls.releaseAll(); controls.visibility = View.GONE } - if (!show) steam.releaseAll() - steam.visibility = if (show) View.VISIBLE else View.GONE + if (!drawn) steam.releaseAll() + steam.visibility = if (drawn) View.VISIBLE else View.GONE com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = show applyTouchRouting() - Log.i(TAG, "on-screen controls: Steam's touch controller " + if (show) "shown" else "hidden") + Log.i(TAG, "on-screen controls: Steam's touch controller " + if (drawn) "shown" else "hidden") return } - if (show == (controls.visibility == View.VISIBLE)) return - if (!show) controls.releaseAll() - controls.visibility = if (show) View.VISIBLE else View.GONE + if (drawn == (controls.visibility == View.VISIBLE)) return + if (!drawn) controls.releaseAll() + controls.visibility = if (drawn) View.VISIBLE else View.GONE Log.i(TAG, "on-screen controls " + when { - !show -> "hidden" + !drawn -> "hidden" buttonsOnly -> "Steam + QAM" else -> "full pad" }) } + private fun keyboardCoversPad() = + SessionState.mode == SessionService.MODE_STEAM && AgentGuest.steamKeyboard + private fun sendGuestKey(code: Int, down: Boolean) { if (down && pipUi) return if (down) guestKeysDown.add(code) else guestKeysDown.remove(code) @@ -2799,7 +2816,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { refreshSecondScreenDisplays() if (secondScreenMode != SecondScreenMode.NONE && secondScreenPresentation == null) showSecondScreen(secondScreenMode) startedScreens++ - SessionService.setActivityVisible(this, true) + SessionService.setActivityVisible(this, true, shownOnDisplayId) Glasses.rescan() updateGlassesScreen() updateHandCamera() diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt index 2295c407e2..82572ab19f 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentGuest.kt @@ -5,6 +5,7 @@ import android.os.Handler import android.os.Looper import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import android.os.FileObserver import android.util.Log @@ -19,6 +20,8 @@ object AgentGuest { private val main by lazy { Handler(Looper.getMainLooper()) } var focusRevision by mutableIntStateOf(0) private set + var steamKeyboard by mutableStateOf(false) + private set private const val TAG = "AgentGuest" private const val POLL_MS = 50L private val lock = Any() @@ -32,6 +35,7 @@ object AgentGuest { observer?.stopWatching() observer = null lastFocusKey = null + main.post { steamKeyboard = false } val dir = dir(context) dir.deleteRecursively() dir.mkdirs() @@ -43,6 +47,7 @@ object AgentGuest { SessionEvents.record("agent.ready", mapOf("pid" to it.optInt("pid"), "focus" to it.optBoolean("focus"))) } "focus.json" -> readJson(File(dir, path))?.let(::recordFocus) + "keyboard.json" -> readJson(File(dir, path))?.let { recordKeyboard(this, it) } } } }.also { it.startWatching() } @@ -53,9 +58,19 @@ object AgentGuest { synchronized(lock) { observer?.stopWatching() observer = null + main.post { steamKeyboard = false } } } + private fun recordKeyboard(source: FileObserver, snapshot: JSONObject) { + val showing = snapshot.optBoolean("steamKeyboard") + synchronized(lock) { + if (source !== observer) return + main.post { steamKeyboard = showing } + } + SessionEvents.record("keyboard.changed", mapOf("steamKeyboard" to showing, "seq" to snapshot.optInt("seq"))) + } + private fun recordFocus(snapshot: JSONObject) { val fields = linkedMapOf( "focusedApp" to snapshot.opt("focusedApp"), diff --git a/app/src/main/java/com/droiddeck/launcher/core/AddonPack.kt b/app/src/main/java/com/droiddeck/launcher/core/AddonPack.kt new file mode 100644 index 0000000000..db4c06939e --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/core/AddonPack.kt @@ -0,0 +1,137 @@ +package com.droiddeck.launcher.core + +import android.content.Context +import android.util.Log +import com.droiddeck.launcher.BuildConfig +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import java.io.File +import java.io.FileInputStream + +/** + * A pack built by CI alongside this APK (tools/packs). Main and release builds publish it to + * DroidDeck-Components under a content-addressed tag; a PR test build attaches packs that are not there + * yet to its pr-N release on DroidDeck-CI. The APK pins the pack's SHA-256, so only the bytes this build + * was made with install, whichever host serves them. + */ +internal class AddonPack(val name: String, private val sha256: String, val size: Long, private val required: List) { + sealed interface State { + data object Missing : State + data class Downloading(val progress: Float) : State + data object Failed : State + data object Ready : State + } + + private val mutableState = MutableStateFlow(State.Missing) + val state: StateFlow = mutableState.asStateFlow() + private val lock = Any() + + val available: Boolean get() = sha256.isNotEmpty() + private val tag get() = "pack-$name-${sha256.take(16)}" + private val urls get() = listOfNotNull( + "https://github.com/$REPO/releases/download/$tag/$name.tar.zst", + BuildConfig.PR_NUMBER.takeIf { it > 0 }?.let { "https://github.com/$PR_REPO/releases/download/pr-$it/$tag.tar.zst" }, + ) + + private fun root(context: Context) = File(context.filesDir, "addons/$name") + /** App-private and written only after the archive matched the pinned digest. */ + fun dir(context: Context) = File(root(context), sha256) + fun file(context: Context, relative: String) = File(dir(context), relative) + + fun installed(context: Context): Boolean = available && File(dir(context), COMPLETE).isFile + + fun refresh(context: Context): State { + val now = mutableState.value + if (now is State.Downloading) return now + return (if (installed(context)) State.Ready else if (now == State.Failed) State.Failed else State.Missing) + .also { mutableState.value = it } + } + + /** Starts the download in the background unless the pack is already present or on its way. */ + fun ensure(context: Context, onReady: (Context) -> Unit = {}) { + val app = context.applicationContext + synchronized(lock) { + if (installed(app)) { mutableState.value = State.Ready; return } + if (mutableState.value is State.Downloading) return + mutableState.value = State.Downloading(0f) + } + scope.launch { + val ok = runCatching { install(app) }.onFailure { Log.w(TAG, "$name: install failed", it) }.getOrDefault(false) + mutableState.value = if (ok) State.Ready else State.Failed + if (ok) onReady(app) + } + } + + /** Blocks a worker thread until the pack is installed, starting the download if needed. */ + @JvmOverloads + fun await(context: Context, running: () -> Boolean = { true }, onState: (State) -> Unit = {}): Boolean { + if (installed(context)) return true + ensure(context) + while (running()) { + val now = state.value + onState(now) + when (now) { + State.Ready -> return installed(context) + State.Failed -> return false + else -> try { Thread.sleep(250) } catch (e: InterruptedException) { return false } + } + } + return false + } + + private fun install(context: Context): Boolean { + if (!available) { + Log.w(TAG, "$name: this build has no pack") + return false + } + val root = root(context).apply { mkdirs() } + val archive = File(root, "$sha256.tar.zst") + val downloaded = urls.any { url -> + Downloader.downloadFile(url, archive, true, sha256) { p -> mutableState.value = State.Downloading(p.coerceIn(0f, 1f)) } + .also { if (!it) archive.delete() } + } + if (!downloaded) return false + val staging = File(root, "$sha256.partial") + staging.deleteRecursively() + try { + if (!FileInputStream(archive).use { TarZst.extract(it, staging) }) return false + check(required.all { File(staging, it).isFile }) { "$name pack is incomplete" } + File(staging, COMPLETE).writeText(sha256) + val target = dir(context) + target.deleteRecursively() + check(staging.renameTo(target)) { "could not move the $name pack into place" } + } finally { + staging.deleteRecursively() + archive.delete() + } + root.listFiles().orEmpty().filter { it.name != sha256 }.forEach { it.deleteRecursively() } + return true + } + + companion object { + private const val TAG = "AddonPack" + private const val REPO = "Droid-Deck/DroidDeck-Components" + private const val PR_REPO = "Droid-Deck/DroidDeck-CI" + const val COMPLETE = ".complete" + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + + @JvmField + val PROOT = AddonPack("proot", BuildConfig.PACK_PROOT_SHA256, BuildConfig.PACK_PROOT_SIZE, + listOf("libproot.so", "libproot-loader.so")) + @JvmField + val DIRECTAUDIO = AddonPack("directaudio", BuildConfig.PACK_DIRECTAUDIO_SHA256, BuildConfig.PACK_DIRECTAUDIO_SIZE, + listOf("linux-wine11/version.txt", "linux-wine11-systhread/version.txt")) + val TRACKING = AddonPack("tracking", BuildConfig.PACK_TRACKING_SHA256, BuildConfig.PACK_TRACKING_SIZE, listOf( + "hand_landmarker.task", "hand_landmarker_lite.task", "pose_landmarker_lite.task", + "libopencv_java4.so", "libmediapipe_tasks_jni.so")) + val XBOX = AddonPack("xbox", BuildConfig.PACK_XBOX_SHA256, BuildConfig.PACK_XBOX_SIZE, + listOf("version", "xodus-cli", "xodus-service")) + val COMET = AddonPack("comet", BuildConfig.PACK_COMET_SHA256, BuildConfig.PACK_COMET_SIZE, + listOf("version", "comet")) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt index c8341afc26..4672cc651b 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt @@ -29,6 +29,7 @@ object GameEnvironment { fun defaults(preset: String, forceSsbs: Boolean = false): Map = linkedMapOf( "MESA_SHADER_CACHE_DISABLE" to "false", + "DROIDDECK_ANTICHEAT_OFFLINE" to "1", "VKD3D_FEATURE_LEVEL" to "12_2", "VKD3D_SHADER_MODEL" to "6_9", "DOTNET_GCRegionRange" to "800000000", diff --git a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironmentOptions.kt b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironmentOptions.kt index 078ae8165c..3ad45c1fa6 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironmentOptions.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironmentOptions.kt @@ -32,6 +32,7 @@ object GameEnvironmentOptions { Option("MESA_EXTENSION_MAX_YEAR", "", 0, Type.TEXT), Option("MESA_GL_VERSION_OVERRIDE", "", 0, Type.TEXT), Option("PULSE_LATENCY_MSEC", "", 0, Type.NUMBER), + Option("DROIDDECK_ANTICHEAT_OFFLINE", "1", R.string.game_env_anticheat_offline, Type.TOGGLE, listOf("0", "1")), Option("WINE_LARGE_ADDRESS_AWARE", "0", 0, Type.TOGGLE, listOf("0", "1")), Option("WINEDLLOVERRIDES", "", 0, Type.TEXT), Option("GALLIUM_HUD", "simple", 0, Type.MULTIPLE, listOf("simple", "fps", "frametime")), diff --git a/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt b/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt index d2128476ac..a667543a69 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/LogRedactor.kt @@ -146,16 +146,21 @@ object LogRedactor { return out } - fun isText(file: java.io.File): Boolean = try { - file.isFile && file.length() < 64L * 1024 * 1024 && file.inputStream().use { input -> + /** The at-rest rewrite reads a file into memory twice; larger logs are only scrubbed on the way out. */ + const val IN_MEMORY_SCRUB_MAX = 64L * 1024 * 1024 + + fun isBinary(file: java.io.File): Boolean = try { + file.inputStream().use { input -> val buf = ByteArray(4096) val n = input.read(buf) - n <= 0 || (0 until n).none { buf[it].toInt() == 0 } + n > 0 && (0 until n).any { buf[it].toInt() == 0 } } } catch (e: Exception) { - false + true } + fun isText(file: java.io.File): Boolean = file.isFile && file.length() < IN_MEMORY_SCRUB_MAX && !isBinary(file) + const val RULES_VERSION = 3 private val LAN_IPV4 = Regex( @@ -176,8 +181,62 @@ object LogRedactor { } } + private const val SHARE_LINE_MAX = 64 * 1024 + fun scrubForShare(src: java.io.File, out: java.io.Writer) { - src.forEachLine { line -> out.write(redactForShare(line)); out.write("\n") } + src.inputStream().buffered().use { input -> + input.mark(2) + val first = input.read() + val second = input.read() + input.reset() + if ((first == 0xff && second == 0xfe) || (first == 0xfe && second == 0xff)) { + out.write("\n") + return + } + val decoder = Charsets.UTF_8.newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + java.io.InputStreamReader(input, decoder).use { reader -> + val buffer = CharArray(8192) + val line = StringBuilder() + var withheld = false + var afterCr = false + fun emit() { + out.write(if (withheld) "" else redactForShare(line.toString())) + out.write("\n") + line.setLength(0) + withheld = false + } + try { + while (true) { + val size = reader.read(buffer) + if (size < 0) break + for (i in 0 until size) { + val ch = buffer[i] + if (afterCr) { + afterCr = false + if (ch == '\n') continue + } + if (ch == '\r' || ch == '\n') { + emit() + afterCr = ch == '\r' + } else if (!withheld) { + // Splitting a line can separate a credential from its label. + if (ch == '\u0000' || line.length == SHARE_LINE_MAX) { + withheld = true + line.setLength(0) + } else { + line.append(ch) + } + } + } + } + if (withheld || line.isNotEmpty()) emit() + } catch (_: java.nio.charset.CharacterCodingException) { + out.write("\n") + } + } + } } private fun quoted(value: String): String { diff --git a/app/src/main/java/com/droiddeck/launcher/files/AppFilesProvider.kt b/app/src/main/java/com/droiddeck/launcher/files/AppFilesProvider.kt index 0f794ce0dd..9f534b39be 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/AppFilesProvider.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/AppFilesProvider.kt @@ -85,7 +85,7 @@ class AppFilesProvider : DocumentsProvider() { override fun deleteDocument(documentId: String) { val file = fileFor(documentId) - if (file.absolutePath == base.absolutePath) throw FileNotFoundException("the app folder itself is not deleted") + if (file.canonicalPath == baseCanonical) throw FileNotFoundException("the app folder itself is not deleted") try { deleteTree(file.toPath()) } catch (e: IOException) { @@ -154,7 +154,7 @@ class AppFilesProvider : DocumentsProvider() { private fun fileFor(documentId: String): File { val f = File(documentId) - if (!f.isAbsolute || !inside(f)) throw FileNotFoundException("$documentId is outside the app's files") + if (!f.isAbsolute || f.normalize().path != documentId || !inside(f)) throw FileNotFoundException("$documentId is outside the app's files") if (!f.exists()) throw FileNotFoundException("$documentId not found") return f } diff --git a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt index 9fbd251ffa..0843057f75 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt @@ -90,6 +90,7 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.droiddeck.launcher.session.SessionPrefs import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ensureActive import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.io.File @@ -151,8 +152,11 @@ fun FileManagerScreen( var conflictChoice by remember { mutableStateOf(null) } var conflictApplyToAll by remember { mutableStateOf(false) } var operationJob by remember { mutableStateOf(null) } + var cancelledJob by remember { mutableStateOf(null) } var pendingBulkDelete by remember { mutableStateOf>(emptyList()) } var searchQuery by remember { mutableStateOf("") } + val visibleEntries = if (searchQuery.isBlank()) entries + else entries.filter { it.name.contains(searchQuery, ignoreCase = true) } var showSearch by remember { mutableStateOf(false) } var sortBy by remember { mutableStateOf(browsePrefs.getString("fmSortBy", "name") ?: "name") } var sortDesc by remember { mutableStateOf(browsePrefs.getBoolean("fmSortDesc", false)) } @@ -174,16 +178,20 @@ fun FileManagerScreen( var showFavorites by remember { mutableStateOf(false) } var favTick by remember { mutableIntStateOf(0) } + var listingJob by remember { mutableStateOf(null) } + fun loadDirectory(dir: File, resetScroll: Boolean = true) { currentDir = dir if (pickMode) pickPrefs.edit().putString("lastFilePickerDir", dir.absolutePath).apply() - scope.launch { + listingJob?.cancel() + listingJob = scope.launch { val list = withContext(Dispatchers.IO) { dir.listFiles()?.toList() ?.filter { if (pickDirMode) it.isDirectory else !pickMode || it.isDirectory || matchesPickExt(it) } ?.filter { showHidden || !it.name.startsWith(".") } ?.sortedWith(comparatorFor(sortBy, sortDesc)) ?: emptyList() } + if (currentDir != dir) return@launch entries = list if (resetScroll) listState.scrollToItem(0) } @@ -220,7 +228,7 @@ fun FileManagerScreen( fun uniqueDestination(dir: File, name: String): File { var candidate = File(dir, name) - if (!candidate.exists()) return candidate + if (!java.nio.file.Files.exists(candidate.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)) return candidate val dot = name.lastIndexOf('.') val base = if (dot > 0) name.substring(0, dot) else name val ext = if (dot > 0) name.substring(dot) else "" @@ -228,7 +236,7 @@ fun FileManagerScreen( do { candidate = File(dir, "$base ($i)$ext") i++ - } while (candidate.exists()) + } while (java.nio.file.Files.exists(candidate.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)) return candidate } @@ -252,7 +260,7 @@ fun FileManagerScreen( fun performPaste() { val sources = clipboardFiles - if (sources.isEmpty()) return + if (sources.isEmpty() || isOperationRunning || operationJob?.isActive == true || cancelledJob?.isCompleted == false) return val dstDir = currentDir val cut = isCutOperation @@ -261,6 +269,7 @@ fun FileManagerScreen( operationDeterminate = true operationLabel = context.getString(if (cut) R.string.fm_op_moving else R.string.fm_op_copying) isOperationRunning = true + val job = coroutineContext[kotlinx.coroutines.Job] var applyToAll: ConflictChoice? = null var failed = 0 @@ -278,7 +287,7 @@ fun FileManagerScreen( } var dst = File(dstDir, src.name) - if (dst.exists()) { + if (java.nio.file.Files.exists(dst.toPath(), java.nio.file.LinkOption.NOFOLLOW_LINKS)) { val choice = applyToAll ?: askConflict(src)?.also { if (conflictApplyToAll) applyToAll = it } ?: run { skipped++; null } ?: continue @@ -296,6 +305,7 @@ fun FileManagerScreen( } var lastPct = -1 val onProgress = FileOps.ProgressCallback { copied, total -> + job?.ensureActive() val pct = if (total > 0) ((copied * 100) / total).toInt() else 100 if (pct != lastPct) { lastPct = pct @@ -304,8 +314,8 @@ fun FileManagerScreen( } val target = dst val ok = withContext(Dispatchers.IO) { - if (cut) FileOps.moveWithProgress(src, target, onProgress) - else FileOps.copyWithProgress(src, target, onProgress) + if (cut) FileOps.moveWithProgress(src, target, onProgress) { job?.isActive == false } + else FileOps.copyWithProgress(src, target, onProgress) { job?.isActive == false } } if (ok) done++ else failed++ } @@ -791,19 +801,21 @@ fun FileManagerScreen( fontSize = 13.sp, modifier = Modifier.weight(1f), ) + val allVisibleSelected = visibleEntries.isNotEmpty() && visibleEntries.all { it.absolutePath in selectedPaths } + val anyVisibleSelected = visibleEntries.any { it.absolutePath in selectedPaths } val selBarPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp) OutlinedButton( onClick = { - selectedPaths = if (selectedPaths.size == entries.size) emptySet() - else entries.map { it.absolutePath }.toSet() + val shown = visibleEntries.map { it.absolutePath } + selectedPaths = if (allVisibleSelected) selectedPaths - shown.toSet() else selectedPaths + shown }, contentPadding = selBarPadding, - ) { Text(if (selectedPaths.size == entries.size) stringResource(R.string.fm_select_none) else stringResource(R.string.fm_select_all), fontSize = 12.sp) } + ) { Text(if (allVisibleSelected) stringResource(R.string.fm_select_none) else stringResource(R.string.fm_select_all), fontSize = 12.sp) } Spacer(Modifier.width(4.dp)) OutlinedButton( - enabled = selectedPaths.isNotEmpty(), + enabled = anyVisibleSelected, onClick = { - clipboardFiles = entries.filter { it.absolutePath in selectedPaths } + clipboardFiles = visibleEntries.filter { it.absolutePath in selectedPaths } isCutOperation = false selectionMode = false selectedPaths = emptySet() @@ -812,9 +824,9 @@ fun FileManagerScreen( ) { Text(stringResource(R.string.fm_copy), fontSize = 12.sp) } Spacer(Modifier.width(4.dp)) OutlinedButton( - enabled = selectedPaths.isNotEmpty(), + enabled = anyVisibleSelected, onClick = { - clipboardFiles = entries.filter { it.absolutePath in selectedPaths } + clipboardFiles = visibleEntries.filter { it.absolutePath in selectedPaths } isCutOperation = true selectionMode = false selectedPaths = emptySet() @@ -823,8 +835,8 @@ fun FileManagerScreen( ) { Text(stringResource(R.string.fm_cut), fontSize = 12.sp) } Spacer(Modifier.width(4.dp)) OutlinedButton( - enabled = selectedPaths.isNotEmpty(), - onClick = { pendingBulkDelete = entries.filter { it.absolutePath in selectedPaths } }, + enabled = anyVisibleSelected, + onClick = { pendingBulkDelete = visibleEntries.filter { it.absolutePath in selectedPaths } }, contentPadding = selBarPadding, border = BorderStroke(1.dp, MaterialTheme.colorScheme.error), ) { Text(stringResource(R.string.common_delete), color = MaterialTheme.colorScheme.error, fontSize = 12.sp) } @@ -842,7 +854,7 @@ fun FileManagerScreen( modifier = Modifier .fillMaxWidth() .background(MaterialTheme.colorScheme.outline.copy(alpha = 0.1f)) - .clickable { performPaste() } + .clickable(enabled = !isOperationRunning) { performPaste() } .padding(horizontal = 16.dp, vertical = 8.dp), ) { Icon(Icons.Filled.ContentPaste, stringResource(R.string.fm_paste), tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp)) @@ -878,6 +890,7 @@ fun FileManagerScreen( ) if (operationJob != null) { TextButton(onClick = { + cancelledJob = operationJob operationJob?.cancel() operationJob = null isOperationRunning = false @@ -964,8 +977,7 @@ fun FileManagerScreen( .fillMaxSize() .nestedScroll(pullState.nestedScrollConnection), ) { - val shownEntries = if (searchQuery.isBlank()) entries - else entries.filter { it.name.contains(searchQuery, ignoreCase = true) } + val shownEntries = visibleEntries if (showGrid && entries.isNotEmpty()) { LazyVerticalGrid( diff --git a/app/src/main/java/com/droiddeck/launcher/files/FileOps.kt b/app/src/main/java/com/droiddeck/launcher/files/FileOps.kt index 04b83abaa2..29df5ff6d6 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileOps.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileOps.kt @@ -45,23 +45,26 @@ object FileOps { return f.length() } - fun moveWithProgress(src: File, dst: File, progress: ProgressCallback?): Boolean { + fun moveWithProgress(src: File, dst: File, progress: ProgressCallback?, isCancelled: () -> Boolean = { false }): Boolean { if (sameFile(src, dst)) return true + if (isCancelled()) return false if (!dst.exists() && src.renameTo(dst)) { progress?.onProgress(1, 1) return true } - if (!copyWithProgress(src, dst, progress)) return false + if (!copyWithProgress(src, dst, progress, isCancelled)) return false + if (isCancelled()) return false return delete(src) } - fun copyWithProgress(src: File, dst: File, progress: ProgressCallback?): Boolean { + fun copyWithProgress(src: File, dst: File, progress: ProgressCallback?, isCancelled: () -> Boolean = { false }): Boolean { val total = maxOf(totalSize(src), 1L) - return copyWithProgress(src, dst, longArrayOf(0), total, progress) + return copyWithProgress(src, dst, longArrayOf(0), total, progress, isCancelled) } - private fun copyWithProgress(src: File, dst: File, done: LongArray, total: Long, progress: ProgressCallback?): Boolean { - if (isSymlink(src)) return true + private fun copyWithProgress(src: File, dst: File, done: LongArray, total: Long, progress: ProgressCallback?, isCancelled: () -> Boolean): Boolean { + if (isCancelled()) throw java.util.concurrent.CancellationException("Copy cancelled: $src") + if (isSymlink(src)) return copyLink(src, dst) if (sameFile(src, dst)) return true if (src.isDirectory && isWithin(dst, src)) { Log.e(TAG, "Refusing to copy directory into itself: $src -> $dst") @@ -71,7 +74,7 @@ object FileOps { if (!dst.exists() && !dst.mkdirs()) return false var allOk = true src.list()?.forEach { name -> - if (!copyWithProgress(File(src, name), File(dst, name), done, total, progress)) { + if (!copyWithProgress(File(src, name), File(dst, name), done, total, progress, isCancelled)) { Log.e(TAG, "Failed to copy: ${File(src, name)}") allOk = false } @@ -81,13 +84,41 @@ object FileOps { val parent = dst.parentFile if (!src.exists() || (parent != null && !parent.exists() && !parent.mkdirs())) return false val chunk = 4L * 1024 * 1024 + var staging: File? = null + var created = false + var output: java.nio.channels.FileChannel? = null try { + output = try { + java.nio.channels.FileChannel.open(dst.toPath(), java.nio.file.StandardOpenOption.WRITE, java.nio.file.StandardOpenOption.CREATE_NEW) + .also { created = true } + } catch (e: java.nio.file.FileAlreadyExistsException) { + null + } + val target = if (!created && isSymlink(dst)) dst.canonicalFile else dst + var permissions: Set? = null + if (output == null) { + if (isSymlink(target) || target.parentFile?.isDirectory != true) { + throw IOException("Destination symlink target is not a writable directory entry: $dst") + } + if (target.isDirectory) throw IOException("Destination is a directory: $target") + permissions = try { + Files.getPosixFilePermissions(target.toPath()) + } catch (e: java.nio.file.NoSuchFileException) { + null + } catch (e: UnsupportedOperationException) { + null + } + if (target.exists() && !target.canWrite()) throw IOException("Destination is not writable: $target") + val directory = Files.createTempDirectory(checkNotNull(target.absoluteFile.parentFile).toPath(), ".droiddeck-copy-") + staging = directory.toFile() + output = FileOutputStream(File(staging, "file")).channel + } FileInputStream(src).channel.use { input -> - FileOutputStream(dst).channel.use { output -> + checkNotNull(output).use { channel -> val size = input.size() var position = 0L while (position < size) { - val transferred = input.transferTo(position, minOf(chunk, size - position), output) + val transferred = input.transferTo(position, minOf(chunk, size - position), channel) if (transferred <= 0) break position += transferred done[0] += transferred @@ -96,11 +127,54 @@ object FileOps { if (position < size) throw IOException("Incomplete copy: $position/$size bytes") } } + staging?.let { directory -> + val copied = File(directory, "file").toPath() + if (permissions != null && Files.getPosixFilePermissions(copied) != permissions) { + Files.setPosixFilePermissions(copied, permissions) + } + if (isCancelled()) throw java.util.concurrent.CancellationException("Copy cancelled: $src") + Files.move(copied, target.toPath(), java.nio.file.StandardCopyOption.ATOMIC_MOVE) + } return true + } catch (e: java.util.concurrent.CancellationException) { + if (created) dst.delete() + throw e } catch (e: IOException) { Log.e(TAG, "Failed to copy file: $src to $dst", e) - dst.delete() + if (created) dst.delete() return false + } finally { + output?.close() + staging?.let { directory -> + File(directory, "file").delete() + directory.delete() + } + } + } + + private fun copyLink(src: File, dst: File): Boolean { + if (src.absoluteFile == dst.absoluteFile) return true + return try { + val target = Files.readSymbolicLink(src.toPath()) + val parent = dst.parentFile + if (parent != null && !parent.exists() && !parent.mkdirs()) return false + try { + Files.createSymbolicLink(dst.toPath(), target) + } catch (e: java.nio.file.FileAlreadyExistsException) { + val staging = Files.createTempDirectory(checkNotNull(dst.absoluteFile.parentFile).toPath(), ".droiddeck-link-") + val tmp = staging.resolve("link") + try { + Files.createSymbolicLink(tmp, target) + Files.move(tmp, dst.toPath(), java.nio.file.StandardCopyOption.ATOMIC_MOVE) + } finally { + Files.deleteIfExists(tmp) + Files.deleteIfExists(staging) + } + } + true + } catch (e: Exception) { + Log.e(TAG, "Failed to copy link: $src to $dst", e) + false } } diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt index e59c8b723b..5de835f6e1 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/AddedGames.kt @@ -41,10 +41,20 @@ object AddedGames { return SessionPrefs.gameFolderBinds(context).map { (host, guest) -> Root(File(host), guest) } } - private val SKIP = Regex( - "(?i)^(unins.*|setup.*|.*redist.*|vcredist.*|dxsetup.*|dxwebsetup.*|.*crash.*|.*report.*|dotnet.*|directx.*|.*prereq.*" + - "|.*installer.*|.*uninstall.*|.*updater?.*|.*config(ur.*)?|.*settings.*|.*editor.*|.*server.*|.*benchmark.*|.*helper.*|.*eac.*|.*easyanticheat.*|.*battleye.*)\\.exe$", + private val SKIP_PREFIX = Regex("(?i)^(unins|setup|vc_?redist|dxsetup|dxwebsetup|dotnet|directx|easyanticheat|battleye).*") + private val SKIP_PART = Regex("(?i)redist|prereq|installer|uninstall|crashreport|crashhandler|crashpad|crashsender|launchhelper") + private val SKIP_WORDS = setOf( + "eac", "report", "reporter", "editor", "server", "benchmark", "helper", + "update", "updater", "config", "configure", "configurator", "configuration", "settings", ) + private val WORD = Regex("[A-Z]?[a-z]+|[A-Z]+(?![a-z])|[0-9]+") + + internal fun skipExe(name: String): Boolean { + if (!name.endsWith(".exe", ignoreCase = true)) return false + val base = name.dropLast(4) + if (SKIP_PREFIX.matches(base) || SKIP_PART.containsMatchIn(base)) return true + return WORD.findAll(base).any { it.value.lowercase() in SKIP_WORDS } + } const val GUEST_DIR = "/root/Games" @@ -75,7 +85,7 @@ object AddedGames { val key = "${folder.path}|${folder.lastModified()}" val now = System.currentTimeMillis() ranked[key]?.takeIf { now - it.first < RANK_FRESH_MS }?.let { return it.second } - val guessed = GameExePicker.rank(folder) { !SKIP.matches(it.name) } + val guessed = GameExePicker.rank(folder) { !skipExe(it.name) } val declared = declaredExes(folder) val preferred = declared.map { it.path }.toSet() val result = if (declared.isEmpty()) guessed else GameExePicker.Ranking( @@ -128,7 +138,7 @@ object AddedGames { val root = runCatching { folder.canonicalPath + File.separator }.getOrNull() ?: return emptyList() return names.asSequence() .map { File(folder, it.trim().replace('\\', '/').trimStart('/')) } - .filter { it.name.endsWith(".exe", ignoreCase = true) && !SKIP.matches(it.name) && it.isFile } + .filter { it.name.endsWith(".exe", ignoreCase = true) && !skipExe(it.name) && it.isFile } .filter { runCatching { it.canonicalPath.startsWith(root) }.getOrDefault(false) } .distinctBy { it.path } .toList() diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/GameFiles.kt b/app/src/main/java/com/droiddeck/launcher/frontend/GameFiles.kt index 8e0b55def2..63b5f6b4dc 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/GameFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/GameFiles.kt @@ -14,6 +14,7 @@ import java.io.InputStream object GameFiles { const val EXTENSION = "steam" private const val MAX_BYTES = 128 + private const val MAX_NAME_BYTES = 200 private const val INVENTORY = ".droiddeck-sync.json" private const val FORMAT = "droiddeck-game-files-v1" @@ -50,8 +51,15 @@ object GameFiles { fun filename(game: Library.SteamGame, disambiguate: Boolean = false): String { val sanitized = game.name.replace(Regex("[\\p{Cntrl}\\\\/:*?\"<>|]"), "_") .trim().trim('.').ifBlank { "Game" } - val points = sanitized.codePoints().limit(40).toArray() - val title = String(points, 0, points.size) + val points = sanitized.codePoints().toArray() + var end = 0 + var bytes = 0 + while (end < points.size) { + bytes += String(points, end, 1).toByteArray().size + if (bytes > MAX_NAME_BYTES) break + end++ + } + val title = String(points, 0, end).trimEnd { it.isWhitespace() || it == '.' }.ifBlank { "Game" } val suffix = if (disambiguate) " (${game.gameIdString})" else "" return "$title$suffix.$EXTENSION" } diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/GameIdentifier.kt b/app/src/main/java/com/droiddeck/launcher/frontend/GameIdentifier.kt index 4b385d896c..c8faf20e71 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/GameIdentifier.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/GameIdentifier.kt @@ -185,7 +185,7 @@ object GameIdentifier { } private val JUNK_NAME_RE = Regex( - """(?i)^(gse|steam|steam client|goldberg.*|launcher|game|play|start|setup|.* launcher.*|.*launcher redirector|.* redirector|rockstar games launcher.*|epic games launcher|smartsteamemu|coldclient.*|steamemu.*)$""" + """(?i)^(gse|steam|steam client|goldberg.*|launcher|game|play|start|setup|.* launcher.*|.*launcher redirector|.* redirector|rockstar games launcher.*|epic games launcher|smartsteamemu|coldclient.*|steamemu.*|bootstrappackagedgame)$""" ) fun isJunkPeName(name: String): Boolean { diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/GameRemoval.kt b/app/src/main/java/com/droiddeck/launcher/frontend/GameRemoval.kt new file mode 100644 index 0000000000..ab997f0271 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/frontend/GameRemoval.kt @@ -0,0 +1,52 @@ +package com.droiddeck.launcher.frontend + +import com.droiddeck.launcher.stores.InstalledStoreGame +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreGameSidecar +import com.droiddeck.launcher.stores.StoreInstalls +import com.droiddeck.launcher.stores.StoresState +import java.io.File + +object GameRemoval { + enum class Kind { STORE, SHORTCUT, LAUNCHER } + + fun kind(game: Library.SteamGame): Kind = when { + game.library == Library.EPIC_LAUNCHER -> Kind.LAUNCHER + game.library == Library.ADDED && game.source == Library.ADDED -> Kind.SHORTCUT + else -> Kind.STORE + } + + class SteamFiles(val dir: File, val manifest: File, val partial: File?) + + fun steamFiles(game: Library.SteamGame): SteamFiles? { + val dir = game.gameFiles ?: return null + val common = dir.parentFile ?: return null + if (common.name != "common") return null + val steamapps = common.parentFile ?: return null + if (steamapps.name != "steamapps") return null + val manifest = File(steamapps, "appmanifest_${game.appId}.acf") + if (!manifest.isFile) return null + if (!declares(manifest, game.appId)) return null + return SteamFiles(dir, manifest, File(steamapps, "downloading/${game.appId}")) + } + + fun delete(target: SteamFiles): Boolean { + StoreInstalls.deleteTree(target.dir) + if (target.dir.exists()) return false + target.partial?.let { StoreInstalls.deleteTree(it) } + target.manifest.delete() + return !target.manifest.exists() + } + + fun storeGame(game: Library.SteamGame): InstalledStoreGame? { + val folder = game.gameFiles ?: return null + val store = Store.byId(game.source) + val id = game.storeId + if (store != null && id != null) StoresState.installedGame(store, id)?.let { return it } + val sidecar = StoreGameSidecar.read(folder)?.takeIf { it.isInstalled } ?: return null + return InstalledStoreGame(sidecar, folder) + } + + private fun declares(manifest: File, appId: Int): Boolean = + runCatching { manifest.readText() }.getOrNull()?.let { Regex("\"appid\"\\s+\"$appId\"").containsMatchIn(it) } == true +} diff --git a/app/src/main/java/com/droiddeck/launcher/glasses/HandModel.kt b/app/src/main/java/com/droiddeck/launcher/glasses/HandModel.kt index c1bcaaa342..a10f178ae1 100644 --- a/app/src/main/java/com/droiddeck/launcher/glasses/HandModel.kt +++ b/app/src/main/java/com/droiddeck/launcher/glasses/HandModel.kt @@ -1,8 +1,10 @@ package com.droiddeck.launcher.glasses -internal enum class HandModel(val asset: String, val sha256: String) { - FULL("models/hand_landmarker.task", "fbc2a30080c3c557093b5ddfc334698132eb341044ccee322ccf8bcf3607cde1"), - LITE("models/hand_landmarker_lite.task", "173c0f47ecee7e935bd4a1e93aa580756b4180c1307c07d709313e82c28672c8"); +import com.droiddeck.launcher.handtracking.TrackingPack + +internal enum class HandModel(val file: String, val sha256: String) { + FULL(TrackingPack.HAND, "fbc2a30080c3c557093b5ddfc334698132eb341044ccee322ccf8bcf3607cde1"), + LITE(TrackingPack.HAND_LITE, "173c0f47ecee7e935bd4a1e93aa580756b4180c1307c07d709313e82c28672c8"); companion object { val DEFAULT = FULL diff --git a/app/src/main/java/com/droiddeck/launcher/glasses/StereoHandEngine.kt b/app/src/main/java/com/droiddeck/launcher/glasses/StereoHandEngine.kt index 0b086c7c4a..becad63a04 100644 --- a/app/src/main/java/com/droiddeck/launcher/glasses/StereoHandEngine.kt +++ b/app/src/main/java/com/droiddeck/launcher/glasses/StereoHandEngine.kt @@ -1,7 +1,9 @@ package com.droiddeck.launcher.glasses +import com.droiddeck.launcher.core.AddonPack import android.content.Context import com.droiddeck.launcher.R +import com.droiddeck.launcher.handtracking.TrackingPack import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color @@ -11,7 +13,6 @@ import com.google.mediapipe.tasks.core.BaseOptions import com.google.mediapipe.tasks.core.Delegate import com.google.mediapipe.tasks.vision.core.RunningMode import com.google.mediapipe.tasks.vision.handlandmarker.HandLandmarker -import org.opencv.android.OpenCVLoader import org.opencv.android.Utils import org.opencv.core.* import org.opencv.imgproc.Imgproc @@ -170,11 +171,11 @@ internal class StereoHandEngine(private val context: Context, private val token: } finally { calibrationProgress = calibrationProgress.copy(solving = false) } } } private fun detector(selected: HandModel=model, useGpu: Boolean=gpu, maxHands: Int=2): HandLandmarker { - val bytes=context.assets.open(selected.asset).use { it.readBytes() } + val bytes=TrackingPack.file(context,selected.file).readBytes() val hash=MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) } check(hash==selected.sha256) { context.getString(R.string.spatial_model_checksum_error) } return HandLandmarker.createFromOptions(context,HandLandmarker.HandLandmarkerOptions.builder() - .setBaseOptions(BaseOptions.builder().setModelAssetPath(selected.asset) + .setBaseOptions(BaseOptions.builder().setModelAssetBuffer(ByteBuffer.allocateDirect(bytes.size).put(bytes).apply { rewind() }) .setDelegate(if(useGpu) Delegate.GPU else Delegate.CPU).build()) .setRunningMode(RunningMode.VIDEO).setNumHands(maxHands).setMinHandDetectionConfidence(0.6f) .setMinHandPresenceConfidence(0.6f).setMinTrackingConfidence(0.6f).build()) @@ -325,7 +326,11 @@ internal class StereoHandEngine(private val context: Context, private val token: SpatialTracking.session.setHands(generation,SpatialHand(),SpatialHand()) } private fun loop() { - try { check(OpenCVLoader.initLocal()) } catch(e: Throwable) { message=context.getString(R.string.spatial_opencv_error, e.message.orEmpty());return } + val loaded=TrackingPack.awaitNative(context,{ running }) { state -> + if(state is AddonPack.State.Downloading) + message=context.getString(R.string.tracking_pack_downloading,(state.progress*100).toInt()) + } + if(!loaded) { if(running) message=context.getString(R.string.tracking_pack_failed);return } var grayL=Mat();var grayR=Mat();val rgba=Mat() var bmpL: Bitmap?=null;var bmpR: Bitmap?=null var leftGray=ByteArray(0);var rightGray=ByteArray(0) @@ -336,7 +341,7 @@ internal class StereoHandEngine(private val context: Context, private val token: var lastSource=0L;var lastStamp=0L;var captureOn=false;var captureRate=1000;var lastInputSeq=0L var rate=0f try { - check(OpenCVLoader.initLocal()) { context.getString(R.string.spatial_opencv_load_error) } + check(TrackingPack.loadNative(context)) { context.getString(R.string.spatial_opencv_load_error) } joyConFlow=StereoJoyConFlow() while(running) { while(true) { diff --git a/app/src/main/java/com/droiddeck/launcher/handtracking/HandCamera.kt b/app/src/main/java/com/droiddeck/launcher/handtracking/HandCamera.kt index ff2fccb857..eec56c2beb 100644 --- a/app/src/main/java/com/droiddeck/launcher/handtracking/HandCamera.kt +++ b/app/src/main/java/com/droiddeck/launcher/handtracking/HandCamera.kt @@ -39,8 +39,6 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import java.io.File -import java.nio.ByteBuffer -import java.nio.ByteOrder import java.util.concurrent.Executors import kotlin.math.abs @@ -188,9 +186,8 @@ internal class HandCamera( private fun prepare() { if (stopped) return runCatching { - val bytes = context.assets.open(MODEL).use { it.readBytes() } - val model = ByteBuffer.allocateDirect(bytes.size).order(ByteOrder.nativeOrder()).put(bytes) - model.rewind() + check(TrackingPack.loadNative(context)) { "hand tracking download is not installed" } + val model = TrackingPack.model(context, TrackingPack.POSE) val options = PoseLandmarker.PoseLandmarkerOptions.builder() .setBaseOptions(BaseOptions.builder().setModelAssetBuffer(model).setDelegate(Delegate.CPU).build()) .setRunningMode(RunningMode.VIDEO) @@ -305,7 +302,6 @@ internal class HandCamera( companion object { private const val TAG = "HandCamera" - private const val MODEL = "handtracking/pose_landmarker_lite.task" private const val ANALYSIS_WIDTH = 960 private const val ANALYSIS_HEIGHT = 720 private const val MIN_CONFIDENCE = 0.5f diff --git a/app/src/main/java/com/droiddeck/launcher/handtracking/HandModel.kt b/app/src/main/java/com/droiddeck/launcher/handtracking/HandModel.kt index 0f4e754d1e..06aed03632 100644 --- a/app/src/main/java/com/droiddeck/launcher/handtracking/HandModel.kt +++ b/app/src/main/java/com/droiddeck/launcher/handtracking/HandModel.kt @@ -13,8 +13,6 @@ import com.google.mediapipe.tasks.core.BaseOptions import com.google.mediapipe.tasks.core.Delegate import com.google.mediapipe.tasks.vision.core.RunningMode import com.google.mediapipe.tasks.vision.handlandmarker.HandLandmarker -import java.nio.ByteBuffer -import java.nio.ByteOrder import kotlin.math.hypot import kotlin.math.max @@ -134,7 +132,6 @@ internal class HandModel private constructor(private val landmarkers: List = emptySet(), + val downloaded: Boolean = false, ) { val usable: Boolean get() = sides.isNotEmpty() - val ready: Boolean get() = enabled && permitted && usable + val ready: Boolean get() = enabled && permitted && usable && downloaded } private val state = MutableStateFlow(Settings()) @@ -38,8 +40,11 @@ internal object HandTracking { side = prefs.getString(SIDE, null), permitted = permitted(context), sides = if (supported) TrackingCameras.sides(found) else emptySet(), + downloaded = TrackingPack.installed(context), ) state.value = next + if (next.enabled && next.usable && !next.downloaded && TrackingPack.refresh(context) == AddonPack.State.Missing) + TrackingPack.ensure(context) return next } diff --git a/app/src/main/java/com/droiddeck/launcher/handtracking/TrackingPack.kt b/app/src/main/java/com/droiddeck/launcher/handtracking/TrackingPack.kt new file mode 100644 index 0000000000..85a1e38445 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/handtracking/TrackingPack.kt @@ -0,0 +1,56 @@ +package com.droiddeck.launcher.handtracking + +import android.content.Context +import android.util.Log +import com.droiddeck.launcher.core.AddonPack +import java.io.File +import java.io.FileInputStream +import java.nio.ByteBuffer +import java.nio.channels.FileChannel + +/** Hand-tracking models and the OpenCV/MediaPipe native libraries, downloaded on first use. */ +internal object TrackingPack { + const val HAND = "hand_landmarker.task" + const val HAND_LITE = "hand_landmarker_lite.task" + const val POSE = "pose_landmarker_lite.task" + private const val OPENCV = "libopencv_java4.so" + private const val MEDIAPIPE = "libmediapipe_tasks_jni.so" + private const val TAG = "TrackingPack" + + private val pack = AddonPack.TRACKING + val state get() = pack.state + val size get() = pack.size + private val lock = Any() + @Volatile private var nativeLoaded = false + + fun installed(context: Context) = pack.installed(context) + fun refresh(context: Context) = pack.refresh(context) + fun ensure(context: Context) = pack.ensure(context) { HandTracking.load(it) } + + fun file(context: Context, name: String): File = pack.file(context, name) + + fun model(context: Context, name: String): ByteBuffer = + FileInputStream(file(context, name)).use { it.channel.map(FileChannel.MapMode.READ_ONLY, 0, it.channel.size()) } + + /** + * Loads OpenCV and MediaPipe from the pack. MediaPipe's own System.loadLibrary then resolves to the + * already-loaded library by soname, so this must run before any MediaPipe task class initializes. + */ + fun loadNative(context: Context): Boolean { + if (nativeLoaded) return true + synchronized(lock) { + if (nativeLoaded) return true + if (!pack.installed(context)) return false + return runCatching { + System.load(file(context, OPENCV).absolutePath) + System.load(file(context, MEDIAPIPE).absolutePath) + nativeLoaded = true + true + }.onFailure { Log.e(TAG, "native libraries failed to load", it) }.getOrDefault(false) + } + } + + /** Blocks the calling worker thread until the pack is usable, starting the download if needed. */ + fun awaitNative(context: Context, running: () -> Boolean, onState: (AddonPack.State) -> Unit): Boolean = + pack.await(context, running, onState) && loadNative(context) +} diff --git a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java index f25c4d32f0..bdc3ff1739 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java +++ b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java @@ -146,9 +146,15 @@ public final class PadBridge { } } + static boolean isSystemVirtualInputName(String name) { + if (name == null) return false; + String lower = name.trim().toLowerCase(java.util.Locale.ROOT); + return lower.startsWith("uinput-") || lower.startsWith("uinput_"); + } + public static boolean isFromController(InputDevice device) { if (device == null) return false; - if (device.isVirtual()) return false; + if (device.isVirtual() || isSystemVirtualInputName(device.getName())) return false; int sources = device.getSources(); if ((sources & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) return true; if ((sources & InputDevice.SOURCE_JOYSTICK) != InputDevice.SOURCE_JOYSTICK) return false; @@ -165,7 +171,7 @@ public final class PadBridge { public static boolean isControllerKeyEvent(KeyEvent event) { InputDevice device = event.getDevice(); - if (device == null || device.isVirtual()) return false; + if (device == null || device.isVirtual() || isSystemVirtualInputName(device.getName())) return false; if (KeyEvent.isGamepadButton(event.getKeyCode())) { return device.supportsSource(InputDevice.SOURCE_GAMEPAD) || device.supportsSource(InputDevice.SOURCE_JOYSTICK); @@ -190,6 +196,7 @@ public final class PadBridge { public static boolean isControllerMotionEvent(MotionEvent event) { InputDevice device = event.getDevice(); return event.isFromSource(InputDevice.SOURCE_JOYSTICK) && device != null && !device.isVirtual() + && !isSystemVirtualInputName(device.getName()) && (device.supportsSource(InputDevice.SOURCE_GAMEPAD) || device.supportsSource(InputDevice.SOURCE_JOYSTICK)); } @@ -319,16 +326,27 @@ public final class PadBridge { boolean wired = wiredXboxLayout(event); pad.rightX = rightX(event, wired); pad.rightY = rightY(event, wired); - float lt = leftTrigger(event, wired); - float rt = rightTrigger(event, wired); - pad.leftTrigger = lt; - pad.rightTrigger = rt; - float hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X); - float hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y); - pad.up = hatY < -0.5f; - pad.right = hatX > 0.5f; - pad.down = hatY > 0.5f; - pad.left = hatX < -0.5f; + int source = event.getSource(); + float lt = 0f; + float rt = 0f; + if (wired || hasAxis(device, source, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE)) { + lt = leftTrigger(event, wired); + pad.leftTrigger = lt; + } + if (wired || hasAxis(device, source, MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS)) { + rt = rightTrigger(event, wired); + pad.rightTrigger = rt; + } + if (hasAxis(device, source, MotionEvent.AXIS_HAT_X)) { + float hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X); + pad.right = hatX > 0.5f; + pad.left = hatX < -0.5f; + } + if (hasAxis(device, source, MotionEvent.AXIS_HAT_Y)) { + float hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y); + pad.up = hatY < -0.5f; + pad.down = hatY > 0.5f; + } if (Math.max(Math.max(Math.abs(pad.leftX), Math.abs(pad.leftY)), Math.max(Math.abs(pad.rightX), Math.abs(pad.rightY))) > 0.5f || lt > 0.5f || rt > 0.5f || pad.up || pad.right || pad.down || pad.left) { notePlayerInput(); @@ -337,6 +355,12 @@ public final class PadBridge { return true; } + static boolean hasAxis(InputDevice device, int source, int... axes) { + if (device == null) return false; + for (int axis : axes) if (device.getMotionRange(axis, source) != null) return true; + return false; + } + public interface TouchRoute { boolean active(); diff --git a/app/src/main/java/com/droiddeck/launcher/input/SteamTouchBindings.kt b/app/src/main/java/com/droiddeck/launcher/input/SteamTouchBindings.kt index 4d19cb87d6..697b768aa8 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/SteamTouchBindings.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/SteamTouchBindings.kt @@ -16,10 +16,13 @@ object SteamTouchBindings { const val DEFAULT_FOREGROUND = "#232323" const val DEFAULT_BACKGROUND = "#E4E4E4" + fun cleanLabel(raw: String): String = + raw.replace(Regex("""["\\,\p{Cntrl}]"""), " ").replace(Regex("""\s+"""), " ").trim().let { it.take(it.offsetByCodePoints(0, minOf(32, it.codePointCount(0, it.length)))) } + data class Binding(val action: String, val label: String, val icon: String, val foreground: String, val background: String) { fun compose(): String = - if (icon.isEmpty() && foreground.isEmpty() && background.isEmpty()) "$action, $label, " - else "$action, $label, $icon, ${listOf(foreground, background).filter { it.isNotEmpty() }.joinToString(" ")}" + if (icon.isEmpty() && foreground.isEmpty() && background.isEmpty()) "$action, ${cleanLabel(label)}, " + else "$action, ${cleanLabel(label)}, $icon, ${listOf(foreground, background).filter { it.isNotEmpty() }.joinToString(" ")}" val hasIcon get() = icon.isNotEmpty() } diff --git a/app/src/main/java/com/droiddeck/launcher/input/SteamTouchIconPicker.kt b/app/src/main/java/com/droiddeck/launcher/input/SteamTouchIconPicker.kt index 17d665f503..da74416bf0 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/SteamTouchIconPicker.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/SteamTouchIconPicker.kt @@ -84,11 +84,11 @@ class SteamTouchIconPicker( updatePreview(preview) showPanel(host, title, root, listOf( context.getString(R.string.touch_no_icon) to { - onPicked(current.copy(label = label.text.toString().replace(",", " ").trim(), icon = "", foreground = "", background = "")) + onPicked(current.copy(label = SteamTouchBindings.cleanLabel(label.text.toString()), icon = "", foreground = "", background = "")) }, context.getString(R.string.common_cancel) to {}, context.getString(R.string.common_use) to { - onPicked(current.copy(label = label.text.toString().replace(",", " ").trim(), icon = icon, + onPicked(current.copy(label = SteamTouchBindings.cleanLabel(label.text.toString()), icon = icon, foreground = if (icon.isEmpty()) "" else foreground, background = if (icon.isEmpty()) "" else background)) }, )) { loader.shutdown() } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java index 869a6fdf17..11be5bf9b4 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java +++ b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntime.java @@ -1,5 +1,6 @@ package com.droiddeck.launcher.runtime; +import com.droiddeck.launcher.core.AddonPack; import android.content.Context; import android.os.Process; import android.system.ErrnoException; @@ -64,14 +65,12 @@ public final class LinuxRuntime { private static final String HOST_DIR = "opt/android-host"; public static File prootBinary(Context context) { - File packaged = new File(context.getApplicationInfo().nativeLibraryDir, "libproot.so"); - if (packaged.isFile()) return packaged; + if (AddonPack.PROOT.installed(context)) return AddonPack.PROOT.file(context, "libproot.so"); return new File(rootDir(context), HOST_DIR + "/proot"); } public static File prootLoader(Context context) { - File packaged = new File(context.getApplicationInfo().nativeLibraryDir, "libproot-loader.so"); - if (packaged.isFile()) return packaged; + if (AddonPack.PROOT.installed(context)) return AddonPack.PROOT.file(context, "libproot-loader.so"); return new File(rootDir(context), HOST_DIR + "/loader"); } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntimeInstaller.java b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntimeInstaller.java index 8296217cdc..d6f6b00762 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntimeInstaller.java +++ b/app/src/main/java/com/droiddeck/launcher/runtime/LinuxRuntimeInstaller.java @@ -1,5 +1,6 @@ package com.droiddeck.launcher.runtime; +import com.droiddeck.launcher.core.AddonPack; import android.content.Context; import android.util.Log; @@ -261,6 +262,8 @@ public final class LinuxRuntimeInstaller { emptyTrash(LinuxRuntime.rootDir(context).getParentFile()); String downloading = context.getString(R.string.rtinst_downloading); if (listener != null) listener.onProgress(Step.DOWNLOADING, downloading, 0); + if (!AddonPack.PROOT.await(context)) throw new IOException("Cannot download proot"); + if (!AddonPack.DIRECTAUDIO.await(context)) throw new IOException("Cannot download DirectAudio"); boolean ok = Downloader.downloadFile(release.url, archive, true, release.sha256, (fraction) -> { if (listener != null) { listener.onProgress(Step.DOWNLOADING, downloading, diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/ProotFastPath.kt b/app/src/main/java/com/droiddeck/launcher/runtime/ProotFastPath.kt index 08ca036677..94508e3729 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/ProotFastPath.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/ProotFastPath.kt @@ -1,6 +1,7 @@ package com.droiddeck.launcher.runtime import android.content.Context +import com.droiddeck.launcher.core.AddonPack import com.droiddeck.launcher.session.SessionPrefs import java.io.File import java.security.MessageDigest @@ -11,7 +12,7 @@ object ProotFastPath { fun enabled(context: Context): Boolean = SessionPrefs.prootFastPath(context) && !SessionPrefs.prootNoSeccomp(context) && - LinuxRuntime.prootBinary(context).parent == context.applicationInfo.nativeLibraryDir + LinuxRuntime.prootBinary(context).parentFile == AddonPack.PROOT.dir(context) fun key(root: File, binds: List): String? { if (binds.size > MAX_BINDS || binds.any { it.contains('|') } || root.path.contains('|')) return null diff --git a/app/src/main/java/com/droiddeck/launcher/session/BootMovie.kt b/app/src/main/java/com/droiddeck/launcher/session/BootMovie.kt index 3641caec51..8267edd57a 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/BootMovie.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/BootMovie.kt @@ -30,7 +30,7 @@ object BootMovie { internal val AUDIO_CODECS = setOf(MediaFormat.MIMETYPE_AUDIO_OPUS, MediaFormat.MIMETYPE_AUDIO_VORBIS) sealed class Import { - data class Done(val name: String, val audioDropped: Boolean) : Import() + data class Done(val name: String, val audioDropped: Boolean, val id: String = "") : Import() object TooLong : Import() data class Unsupported(val codec: String?) : Import() object Failed : Import() @@ -39,6 +39,21 @@ object BootMovie { private fun dir(context: Context) = File(context.filesDir, "boot-movie") private fun customFile(context: Context) = File(dir(context), "custom.webm") + /** A movie imported before movies were kept in Steam's own folder. */ + internal fun legacyCustomFile(context: Context) = customFile(context) + + /** Unpacks one of DroidDeck's own movies on demand; null for anything else. */ + internal fun assetFile(context: Context, id: String): File? = ASSETS[id]?.let { extractAsset(context, it) } + + /** Picking a movie here makes it Steam's startup movie at the next session, over whatever Steam had picked. */ + fun select(context: Context, id: String) { + SessionPrefs.setBootMovie(context, id) + SessionPrefs.setBootMovieApplyNext(context, true) + BootMovieReport.note(context, "picked $id here; Steam names ${SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context))}") + // Whatever Steam names right now is about to be replaced, so it is not a pick to adopt later. + SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context))?.let { SessionPrefs.setBootMovieSteamSeen(context, it) } + } + fun customName(context: Context): String? = if (customFile(context).isFile) SessionPrefs.bootMovieCustomName(context) ?: "custom.webm" else null @@ -46,21 +61,127 @@ object BootMovie { val chosen = SessionPrefs.bootMovie(context) return when { chosen == CUSTOM && customFile(context).isFile -> CUSTOM + isLibraryId(chosen) && BootMovieLibrary.file(context, chosen) != null -> chosen chosen in ASSETS -> chosen else -> DROIDDECK_30 } } + /** The file the current choice plays from, before any volume or length change. */ + fun currentFile(context: Context): File? = sourceOf(context, choice(context)) + + private fun sourceOf(context: Context, choice: String): File? = when { + choice == CUSTOM -> customFile(context) + isLibraryId(choice) -> BootMovieLibrary.file(context, choice) + else -> ASSETS[choice]?.let { extractAsset(context, it) } + } + + private fun isLibraryId(id: String) = id.startsWith(BootMovieLibrary.PREFIX) || id.startsWith(BootMovieLibrary.STEAM_PREFIX) + fun prepare(context: Context): File? { - val choice = choice(context) - val source = if (choice == CUSTOM) customFile(context) else extractAsset(context, ASSETS.getValue(choice)) ?: return null - if (SessionPrefs.bootMovieSound(context)) return source - val muted = File(source.parentFile, source.nameWithoutExtension + "-muted.webm") - if (muted.isFile && muted.lastModified() >= source.lastModified()) return muted - if (remux(source, muted, audio = false)) return muted - if (BootMovieTranscoder.transcode(source, muted, keepAudio = false) {} != null) return muted - Log.e(TAG, "could not strip audio from ${source.name}; not staging it") - return null + BootMovieLibrary.restore(context) + val source = sourceOf(context, choice(context)) ?: return null + return variant(context, source) + } + + /** The movie as Steam should get it: with the chosen volume and cut off after the chosen number of seconds. */ + private fun variant(context: Context, source: File): File? { + val volume = if (SessionPrefs.bootMovieSound(context)) SessionPrefs.bootMovieVolume(context) else 0 + val seconds = SessionPrefs.bootMovieSeconds(context) + val folder = File(dir(context), "variants") + val plan = if (isOversized(source)) oversizedPlan(volume) else plan(volume, seconds) + if (plan.passthrough) { + prune(folder, null) + return source + } + folder.mkdirs() + val limitUs = if (seconds > 0) seconds * 1_000_000L else Long.MAX_VALUE + val out = File(folder, BootMovieLibrary.variantPrefix(source) + "v$volume-s$seconds.webm") + if (out.isFile && out.length() > 0L && out.lastModified() >= source.lastModified()) { + prune(folder, out.name) + return out + } + val staged = File(folder, out.name + ".staged") + val ok = runCatching { + plan.steps.any { step -> + when (step) { + Step.REMUX_SILENT -> remux(source, staged, audio = false, limitUs) + Step.REMUX_AUDIO -> remux(source, staged, audio = true, limitUs) + Step.TRANSCODE_SILENT -> transcodeSilent(source, staged, limitUs) + Step.TRANSCODE_AUDIO -> BootMovieTranscoder.transcode(source, staged, limitUs = limitUs, gain = volume / 100f) {} != null + Step.REGAIN -> BootMovieTranscoder.regain(source, staged, volume / 100f, limitUs) + } + } + }.getOrDefault(false) + if (ok && staged.renameTo(out)) { + prune(folder, out.name) + return out + } + staged.delete() + Log.e(TAG, "could not prepare ${source.name} (volume $volume, $seconds s)") + return if (plan.sourceOnFailure) source else null + } + + internal enum class Step { REMUX_SILENT, REMUX_AUDIO, TRANSCODE_SILENT, TRANSCODE_AUDIO, REGAIN } + + /** + * How a movie is processed: the steps tried in order until one works, whether the source goes out untouched, and + * whether it still plays as it is when every step fails. + */ + internal class Plan(val passthrough: Boolean, val steps: List, val sourceOnFailure: Boolean) + + internal fun plan(volume: Int, seconds: Int): Plan = when { + volume == 100 && seconds == 0 -> Plan(true, emptyList(), true) + volume == 0 -> Plan(false, listOf(Step.REMUX_SILENT, Step.TRANSCODE_SILENT), false) + // Only a length that could not be applied plays as it is; a volume that could not be applied plays no louder. + volume == 100 -> Plan(false, listOf(Step.REMUX_AUDIO, Step.TRANSCODE_AUDIO), true) + else -> Plan(false, listOf(Step.REGAIN, Step.REMUX_SILENT, Step.TRANSCODE_AUDIO), false) + } + + /** Frames beyond 1920x1080 (4K and the like) have made Steam crash while it starts, so such a movie is always scaled down. */ + internal const val MAX_LONG_SIDE = 1920 + internal const val MAX_SHORT_SIDE = 1080 + + internal fun oversized(width: Int, height: Int) = maxOf(width, height) > MAX_LONG_SIDE || minOf(width, height) > MAX_SHORT_SIDE + + private fun oversized(format: MediaFormat) = + format.containsKey(MediaFormat.KEY_WIDTH) && format.containsKey(MediaFormat.KEY_HEIGHT) && + oversized(format.getInteger(MediaFormat.KEY_WIDTH), format.getInteger(MediaFormat.KEY_HEIGHT)) + + private fun isOversized(source: File): Boolean = probe(source)?.first?.let { oversized(it) } == true + + /** A movie that is too large never goes out as it is: it is converted at the chosen volume, and plays nothing if that fails. */ + internal fun oversizedPlan(volume: Int): Plan = + Plan(false, listOf(if (volume == 0) Step.TRANSCODE_SILENT else Step.TRANSCODE_AUDIO), false) + + private fun transcodeSilent(source: File, target: File, limitUs: Long) = + BootMovieTranscoder.transcode(source, target, keepAudio = false, limitUs = limitUs) {} != null + + /** Keeps at most the one processed copy in use, so trying settings never leaves movies piling up. */ + private fun prune(folder: File, keep: String?) { + folder.listFiles()?.forEach { if (it.name != keep) it.delete() } + } + + /** + * Takes over a startup movie chosen in Steam's own settings: when Steam's config names a movie it did not name before, + * that movie becomes the choice here. Steam already plays it, so nothing is staged over it. True when the choice changed. + */ + fun syncFromSteam(context: Context): Boolean { + val path = SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context)) ?: return false + if (path == SessionPrefs.bootMovieSteamSeen(context)) return false + SessionPrefs.setBootMovieSteamSeen(context, path) + if (path == SessionFiles.BOOT_MOVIE_PATH) return false + val prefix = "/uioverrides/movies/" + // The list names a bought movie from the Steam folder (/config/communityitemscache/...), Steam's config from its config folder. + val id = if (path.startsWith(prefix)) BootMovieLibrary.idOf(path.removePrefix(prefix)) else { + val listed = BootMovieLibrary.list(context).firstOrNull { it.id.startsWith(BootMovieLibrary.STEAM_PREFIX) && it.id.endsWith(path) } + listed?.id ?: BootMovieLibrary.STEAM_PREFIX + path + } + if (BootMovieLibrary.file(context, id) == null) return false + val changed = SessionPrefs.bootMovie(context) != id + BootMovieReport.note(context, "Steam names $path, taken over as $id") + SessionPrefs.setBootMovie(context, id) + return changed } private fun extractAsset(context: Context, name: String): File? { @@ -82,11 +203,15 @@ object BootMovie { } } - fun import(context: Context, file: File, onStart: () -> Unit = {}, onProgress: (Int) -> Unit = {}): Import { + fun import( + context: Context, file: File, onStart: () -> Unit = {}, onProgress: (Int) -> Unit = {}, + title: String? = null, source: String = BootMovieLibrary.SOURCE_IMPORT, repoId: String? = null, + cover: ByteArray? = null, use: Boolean = true, + ): Import { val (format, audio) = probe(file) ?: return Import.Unsupported(null) val video = format.getString(MediaFormat.KEY_MIME) val audioPlayable = audio == null || audio in AUDIO_CODECS - val playable = video in VIDEO_CODECS && file.length() <= MAX_BYTES + val playable = video in VIDEO_CODECS && file.length() <= MAX_BYTES && !oversized(format) val copy = playable && audioPlayable && isWebm(file) val remux = !copy && playable && video in REMUX_CODECS if (!copy && !remux) { @@ -95,11 +220,12 @@ object BootMovie { if (durationUs > MAX_CONVERT_SECONDS * 1_000_000L) return Import.TooLong onStart() } - val target = customFile(context) - val staged = File(dir(context), "custom.webm.staged") + val shown = title?.takeIf { it.isNotBlank() } ?: file.nameWithoutExtension + val library = BootMovieLibrary.libraryDir(context) + val staged = File(library, ".import-${System.nanoTime()}.staged") var audioDropped = remux && !audioPlayable return try { - target.parentFile?.mkdirs() + library.mkdirs() val ok = when { copy -> { file.inputStream().use { input -> staged.outputStream().use { output -> FileUtils.copy(input, output) } } @@ -108,11 +234,10 @@ object BootMovie { remux -> remux(file, staged, audio = true) else -> BootMovieTranscoder.transcode(file, staged, onProgress = onProgress)?.also { audioDropped = it.audioDropped } != null } - if (!ok || !staged.renameTo(target)) return Import.Failed - File(target.parentFile, "custom-muted.webm").delete() - SessionPrefs.setBootMovieCustomName(context, file.name) - SessionPrefs.setBootMovie(context, CUSTOM) - Import.Done(file.name, audioDropped) + if (!ok || !staged.setReadable(true, false)) return Import.Failed + val name = BootMovieLibrary.commit(context, staged, shown, source, repoId, cover) ?: return Import.Failed + if (use) select(context, BootMovieLibrary.idOf(name)) + Import.Done(shown, audioDropped, BootMovieLibrary.idOf(name)) } catch (e: Exception) { Log.w(TAG, "could not import ${file.name}", e) Import.Failed @@ -124,8 +249,9 @@ object BootMovie { fun removeCustom(context: Context) { customFile(context).delete() File(dir(context), "custom-muted.webm").delete() + File(dir(context), "variants").listFiles { f -> f.name.startsWith(BootMovieLibrary.variantPrefix(customFile(context))) }?.forEach { it.delete() } SessionPrefs.setBootMovieCustomName(context, null) - if (SessionPrefs.bootMovie(context) == CUSTOM) SessionPrefs.setBootMovie(context, DROIDDECK_30) + if (SessionPrefs.bootMovie(context) == CUSTOM) select(context, DROIDDECK_30) } private fun isWebm(file: File): Boolean { @@ -156,7 +282,7 @@ object BootMovie { } } - private fun remux(source: File, target: File, audio: Boolean): Boolean { + private fun remux(source: File, target: File, audio: Boolean, limitUs: Long = Long.MAX_VALUE): Boolean { val staged = File(target.parentFile, target.name + ".remux") val extractor = MediaExtractor() var muxer: MediaMuxer? = null @@ -183,7 +309,7 @@ object BootMovie { val info = MediaCodec.BufferInfo() while (true) { val size = extractor.readSampleData(buffer, 0) - if (size < 0) break + if (size < 0 || extractor.sampleTime > limitUs) break val track = tracks[extractor.sampleTrackIndex] if (track != null) { val key = extractor.sampleFlags and MediaExtractor.SAMPLE_FLAG_SYNC != 0 diff --git a/app/src/main/java/com/droiddeck/launcher/session/BootMovieLibrary.kt b/app/src/main/java/com/droiddeck/launcher/session/BootMovieLibrary.kt new file mode 100644 index 0000000000..7c125e8196 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/BootMovieLibrary.kt @@ -0,0 +1,410 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.Bitmap.CompressFormat +import android.media.MediaMetadataRetriever +import android.util.Log +import com.droiddeck.launcher.runtime.LinuxRuntime +import org.json.JSONObject +import java.io.File + +/** + * The boot movies a person can pick from: DroidDeck's own two, a movie imported before this list existed, every `.webm` in + * Steam's custom movies folder (imports, SteamDeckRepo and movies put there by hand; all of them can be removed), Steam's own + * three startup movies and the movies bought in Steam's points shop (neither can be removed). + */ +object BootMovieLibrary { + private const val TAG = "BootMovieLibrary" + const val PREFIX = "file:" + + /** A movie Steam itself keeps outside its custom movies folder, such as one bought in its points shop: `steam:`. */ + const val STEAM_PREFIX = "steam:" + + /** Held while the movie list is read and changed, so two imports at once cannot overwrite each other's entries. */ + private val lock = Any() + + /** Names DroidDeck stages the chosen movie under; they are copies, not movies of their own. */ + internal val STAGED = setOf("bigpicture_startup.webm", "steam_os_startup.webm", "droiddeck-startup.webm") + + const val SOURCE_DROIDDECK = "droiddeck" + const val SOURCE_IMPORT = "import" + const val SOURCE_REPO = "repo" + const val SOURCE_STEAM = "steam" + const val SOURCE_POINTSHOP = "pointshop" + + class Entry(val id: String, val title: String, val source: String, val file: File?, val removable: Boolean) + + internal fun moviesDir(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/config/uioverrides/movies") + + /** + * The folders whose custom movies are listed, found and removed: [moviesDir], where imports are put and managed, then the + * x86-64 client's. The order never depends on which client is running, so a saved choice keeps meaning the same file. + */ + internal fun customMovieDirs(context: Context): List = + listOf(moviesDir(context), File(SessionPrefs.steamRoot(context, "x86_64"), "config/uioverrides/movies")).distinctBy { it.path } + + /** Where imported and installed movies are kept for good; Steam's folder holds a copy, which is put back if it goes missing. */ + internal fun libraryDir(context: Context) = File(context.filesDir, "boot-movie/library") + + private fun metaFile(context: Context) = File(context.filesDir, "boot-movie/movies.json") + + internal fun steamRoot(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam") + + /** The running (else selected) Steam client's config, the one whose startup movie choice is read and recorded. */ + internal fun steamConfig(context: Context) = File(SessionPrefs.activeSteamRoot(context), "config/config.vdf") + + private fun thumbsDir(context: Context) = File(context.filesDir, "boot-movie/thumbs") + + fun idOf(name: String) = PREFIX + name + + /** Every Steam client folder: the usual one and the x86-64 client's. */ + internal fun steamRoots(context: Context): List = listOf( + steamRoot(context), File(LinuxRuntime.rootDir(context), "root/.droiddeck-x64/.local/share/Steam"), + ).filter { it.isDirectory } + + private fun steamFile(context: Context, id: String): File? { + val path = id.removePrefix(STEAM_PREFIX) + if (!path.startsWith("/") || path.contains("..") || path.contains('\\') || !path.endsWith(".webm", ignoreCase = true)) return null + return steamRoots(context).firstNotNullOfOrNull { root -> + listOf("config", "steamui", "").map { File(root, it + path) }.firstOrNull { it.isFile && it.length() > 0L } + } + } + + fun file(context: Context, id: String): File? { + if (id.startsWith(STEAM_PREFIX)) return steamFile(context, id) + if (!id.startsWith(PREFIX)) return null + val name = id.removePrefix(PREFIX) + if (name.isEmpty() || name.contains('/') || name.contains('\\') || name in STAGED) return null + return customMovieDirs(context).map { File(it, name) }.firstOrNull { it.isFile && it.length() > 0L } + } + + private fun isMovie(file: File) = file.isFile && file.length() > 0L && file.name.endsWith(".webm", ignoreCase = true) && + file.name !in STAGED && !file.name.startsWith(".") + + private fun readMeta(context: Context): JSONObject = + runCatching { JSONObject(metaFile(context).readText()) }.getOrDefault(JSONObject()) + + /** Changes the movie list one writer at a time; [change] gets the list and returns whether to save it. */ + private fun editMeta(context: Context, change: (JSONObject) -> Boolean) = synchronized(lock) { + val meta = readMeta(context) + if (change(meta)) { + val file = metaFile(context) + file.parentFile?.mkdirs() + val staged = File(file.parentFile, file.name + ".staged") + runCatching { + staged.writeText(meta.toString()) + if (!staged.renameTo(file)) staged.delete() + }.onFailure { staged.delete(); Log.w(TAG, "could not write the movie list", it) } + } + } + + /** The post a movie was installed from, if it came from SteamDeckRepo. */ + fun repoId(context: Context, name: String): String? = + readMeta(context).optJSONObject(name)?.optString("repo")?.takeIf { it.isNotEmpty() } + + fun installedRepoIds(context: Context): Set { + val meta = readMeta(context) + return meta.keys().asSequence().filter { file(context, idOf(it)) != null } + .mapNotNull { meta.optJSONObject(it)?.optString("repo")?.takeIf { id -> id.isNotEmpty() } }.toSet() + } + + fun nameForRepo(context: Context, repoId: String): String? { + val meta = readMeta(context) + return meta.keys().asSequence().firstOrNull { file(context, idOf(it)) != null && meta.optJSONObject(it)?.optString("repo") == repoId } + } + + fun list(context: Context): List { + val out = ArrayList() + out.add(Entry(BootMovie.DROIDDECK_30, "DroidDeck · 30 fps", SOURCE_DROIDDECK, null, removable = false)) + out.add(Entry(BootMovie.DROIDDECK_60, "DroidDeck · 60 fps", SOURCE_DROIDDECK, null, removable = false)) + BootMovie.customName(context)?.let { out.add(Entry(BootMovie.CUSTOM, it, SOURCE_IMPORT, BootMovie.legacyCustomFile(context), removable = true)) } + restore(context) + val meta = readMeta(context) + val names = HashSet() + customMovieDirs(context).flatMap { dir -> dir.listFiles { f -> isMovie(f) }.orEmpty().toList() } + .filter { names.add(it.name) }.sortedBy { it.name.lowercase() }.forEach { f -> + val info = meta.optJSONObject(f.name) + val source = info?.optString("source")?.takeIf { it.isNotEmpty() } ?: SOURCE_STEAM + val title = info?.optString("title")?.takeIf { it.isNotEmpty() } ?: f.nameWithoutExtension + // Everything in Steam's custom movies folder is the person's own (imported, from SteamDeckRepo or put there by hand). + out.add(Entry(idOf(f.name), title, if (source == SOURCE_STEAM) SOURCE_IMPORT else source, f, removable = true)) + } + val steam = LinkedHashMap() + SessionFiles.startupMoviePath(steamConfig(context))?.takeIf { !it.startsWith(OVERRIDES) }?.let { path -> + steamFile(context, STEAM_PREFIX + path)?.let { steam[STEAM_PREFIX + path] = it } + } + val bought = HashMap() + for (root in steamRoots(context)) { + File(root, "steamui/movies").listFiles { f -> isMovie(f) && f.nameWithoutExtension.lowercase() in NATIVE }.orEmpty() + .sortedBy { it.name.lowercase() }.forEach { steam.putIfAbsent(STEAM_PREFIX + "/movies/" + it.name, it) } + val scan = pointShopMovies(root) + bought.putAll(scan.titles) + for (found in scan.files) steam.putIfAbsent(STEAM_PREFIX + "/" + found.relativeTo(root).invariantSeparatorsPath, found) + } + val seen = HashSet() + for ((id, file) in steam) { + if (file.name in STAGED || !seen.add(file.canonicalPath)) continue + val native = file.nameWithoutExtension.lowercase() in NATIVE + // Steam names a bought movie by an item number and a hash; the points shop's own title is shown when Steam has it. + val title = if (native) NATIVE[file.nameWithoutExtension.lowercase()] ?: file.nameWithoutExtension else bought[file.path] ?: boughtId(file)?.let { "#$it" } ?: file.nameWithoutExtension + out.add(Entry(id, title, if (native) SOURCE_STEAM else SOURCE_POINTSHOP, file, removable = false)) + } + return out + } + + /** The three startup movies Steam ships with; Steam's movies folder holds many more videos that are not startup movies. */ + private val NATIVE = mapOf("deck_startup" to "Deck startup", "oled_startup" to "Oled startup", "startup_machine" to "Machine startup") + + private val skippedFolders = setOf("uioverrides", "steamapps", "librarycache", "httpcache", "logs", "compatdata", "shadercache") + + private val scanLock = Any() + private class Scan(val at: Long, val files: List, val titles: Map) + + private val scans = HashMap() + + /** Forgets the last search for Steam's own movies. */ + internal fun forgetScan() = synchronized(scanLock) { scans.clear() } + + /** + * Movies Steam keeps outside its custom movies folder, such as ones bought in its points shop: every `.webm` below the + * client's config, cache and user folders. The search is repeated at most every 15 seconds for each client folder. + */ + private fun pointShopMovies(root: File): Scan = synchronized(scanLock) { + val now = System.currentTimeMillis() + scans[root.path]?.let { if (now - it.at < 15_000L) return it } + val found = listOf("config", "userdata", "appcache", "steamui").flatMap { top -> + val base = File(root, top) + if (!base.isDirectory) return@flatMap emptyList() + base.walkTopDown().maxDepth(5) + .onEnter { dir -> dir.name !in skippedFolders && !(top == "steamui" && dir.parentFile == base && dir.name == "movies") } + .take(20_000).filter { isMovie(it) }.toList() + }.sortedBy { it.path.lowercase() } + val titles = HashMap() + for (file in found) boughtId(file)?.let { id -> boughtTitle(root, id)?.let { titles[file.path] = it } } + val scan = Scan(now, found, titles) + scans[root.path] = scan + scan + } + + /** The item number in the name Steam gives a bought movie, `_.webm`; null for any other name. */ + private fun boughtId(file: File) = Regex("^(\\d+)_").find(file.nameWithoutExtension)?.groupValues?.get(1) + + /** What the points shop calls a bought movie, from the list of startup movies Steam keeps in each user's local config. */ + private fun boughtTitle(root: File, id: String): String? { + val key = "communityitemid\\\":\\\"$id\\\"" + val title = Regex("item_title\\\\\":\\\\\"([^\\\\\"]*)") + for (user in File(root, "userdata").listFiles { f -> f.isDirectory }.orEmpty()) { + val text = runCatching { File(user, "config/localconfig.vdf").readText() }.getOrNull() ?: continue + val at = text.indexOf(key) + if (at < 0) continue + title.find(text.substring(at, (at + 3000).coerceAtMost(text.length)))?.groupValues?.get(1)?.takeIf { it.isNotBlank() }?.let { return it } + } + return null + } + + private const val OVERRIDES = "/uioverrides/movies/" + + /** Puts back, in Steam's folder, any movie of DroidDeck's that went missing there, such as after the runtime was reset. */ + internal fun restore(context: Context) = synchronized(lock) { + migrateLegacyMeta(context) + val meta = readMeta(context) + val library = libraryDir(context) + meta.keys().asSequence().toList().forEach { name -> + val kept = File(library, name) + if (name.contains('/') || !kept.isFile || kept.length() == 0L) return@forEach + val copy = File(moviesDir(context), name) + if (!copy.isFile || copy.length() != kept.length()) mirror(kept, copy) + } + } + + /** Takes in the movie notes an earlier version kept inside Steam's movies folder, so those movies keep their title and source. */ + private fun migrateLegacyMeta(context: Context) { + val legacy = File(moviesDir(context), ".droiddeck-movies.json") + if (!legacy.isFile) return + val old = runCatching { JSONObject(legacy.readText()) }.getOrNull() ?: return + editMeta(context) { meta -> + var changed = false + old.keys().asSequence().toList().forEach { name -> + val info = old.optJSONObject(name) ?: return@forEach + if (meta.optJSONObject(name) == null && File(moviesDir(context), name).isFile) { meta.put(name, info); changed = true } + } + changed + } + legacy.delete() + } + + /** Copies [kept] to [copy] through a staging name, so Steam never sees half a movie. */ + private fun mirror(kept: File, copy: File): Boolean { + val staged = File(copy.parentFile, copy.name + ".${System.nanoTime()}.staged") + return try { + copy.parentFile?.mkdirs() + kept.inputStream().use { input -> staged.outputStream().use { output -> input.copyTo(output) } } + staged.setReadable(true, false) && staged.renameTo(copy) + } catch (e: Exception) { + Log.w(TAG, "could not copy ${kept.name} into Steam's movies", e) + false + } finally { + staged.delete() + } + } + + fun title(context: Context, id: String): String = list(context).firstOrNull { it.id == id }?.title ?: id + + /** The file a movie id plays from; DroidDeck's own movies live in the app and are unpacked on demand. */ + fun fileOf(context: Context, entry: Entry): File? = entry.file ?: BootMovie.assetFile(context, entry.id) + + /** A free `.webm` name for a movie called [title]; the same title twice gets " (2)", " (3)"… */ + fun freeName(context: Context, title: String): String { + val base = title.replace(Regex("[^\\p{L}\\p{N} ._()\\-]"), "").replace(Regex("\\s+"), " ").trim().trim('.').take(60).ifEmpty { "movie" } + val dirs = customMovieDirs(context) + val library = libraryDir(context) + var name = "$base.webm" + var n = 2 + while (dirs.any { File(it, name).exists() } || File(library, name).exists() || name in STAGED) name = "$base ($n).webm".also { n++ } + return name + } + + /** + * Keeps the finished movie [staged] (a file in [libraryDir]) under a free name, copies it into Steam's folder and notes its + * title, source and cover. Returns the name, or null when it could not be kept. Runs one movie at a time. + */ + internal fun commit(context: Context, staged: File, title: String, source: String, repoId: String? = null, cover: ByteArray? = null): String? = + synchronized(lock) { + val name = freeName(context, title) + val kept = File(libraryDir(context), name) + if (!staged.renameTo(kept)) return null + if (!mirror(kept, File(moviesDir(context), name))) { kept.delete(); return null } + register(context, name, title, source, repoId, cover) + name + } + + /** Notes a movie that was just put into Steam's folder: what to call it, where it came from and its cover. */ + fun register(context: Context, name: String, title: String, source: String, repoId: String? = null, cover: ByteArray? = null) { + editMeta(context) { meta -> + val info = JSONObject().put("title", title).put("source", source) + if (repoId != null) info.put("repo", repoId) + meta.put(name, info) + true + } + if (cover != null) runCatching { + thumbsDir(context).mkdirs() + File(thumbsDir(context), coverName(name)).writeBytes(cover) + } + } + + fun remove(context: Context, id: String): Boolean { + val removed = when { + id == BootMovie.CUSTOM -> { BootMovie.removeCustom(context); true } + else -> { + // Only movies in Steam's custom movies folder are ever deleted; Steam's own and points shop movies are left alone. + if (!id.startsWith(PREFIX)) return false + val name = id.removePrefix(PREFIX) + if (name.isEmpty() || name.contains('/') || name.contains('\\') || name in STAGED) return false + val copies = customMovieDirs(context).map { File(it, name) } + // A name can exist in more than one client's folder; the entry is the first one found (see customMovieDirs), and only that file is deleted. + val target = copies.firstOrNull { it.exists() } + val managed = File(libraryDir(context), name) + if (readMeta(context).optJSONObject(name) == null && target == null && !managed.isFile) return false + synchronized(lock) { + val main = File(moviesDir(context), name) + val another = copies.any { it != target && it.exists() } + val ownsRecord = target == null || target.path == main.path || (!another && !managed.isFile) + var gone = target == null || target.delete() + if (gone && ownsRecord) { + gone = !managed.exists() || managed.delete() + if (gone) { + editMeta(context) { it.remove(name) != null } + File(thumbsDir(context), coverName(name)).delete() + thumbsDir(context).listFiles { f -> f.name.startsWith("frame-" + safe(name) + "-") }?.forEach { it.delete() } + } + } + if (gone) { + val prefixes = listOfNotNull(target, main.takeIf { ownsRecord }).map { variantPrefix(it) } + File(context.filesDir, "boot-movie/variants").listFiles { f -> prefixes.any { f.name.startsWith(it) } }?.forEach { it.delete() } + } + gone + } + } + } + if (removed && SessionPrefs.bootMovie(context) == id) BootMovie.select(context, BootMovie.DROIDDECK_30) + return removed + } + + /** What every processed copy of [source] starts with; the hash of its full path keeps same-named files in different places apart. */ + internal fun variantPrefix(source: File) = safe(source.name) + "." + Integer.toHexString(source.absolutePath.hashCode()) + "-" + + private fun safe(name: String) = name.replace(Regex("[^A-Za-z0-9._-]"), "_") + + private fun coverName(name: String) = "cover-" + safe(name) + + /** How long a movie runs, in whole seconds; 0 when it cannot be read. */ + fun durationSeconds(file: File?): Int { + if (file == null || !file.isFile) return 0 + val retriever = MediaMetadataRetriever() + return try { + retriever.setDataSource(file.path) + val ms = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: 0L + ((ms + 500) / 1000).toInt() + } catch (e: Exception) { + 0 + } finally { + runCatching { retriever.release() } + } + } + + /** The first frame that is not nearly black out of several taken through the movie, else the brightest; a movie may open dark. */ + private fun brightestFrame(retriever: MediaMetadataRetriever, durationMs: Long): Bitmap? { + var best: Bitmap? = null + var bestLuma = -1 + for (fraction in doubleArrayOf(0.33, 0.5, 0.66, 0.2, 0.8, 0.1, 0.9)) { + val frame = runCatching { retriever.getFrameAtTime((durationMs * 1000L * fraction).toLong(), MediaMetadataRetriever.OPTION_CLOSEST) }.getOrNull() ?: continue + val luma = averageLuma(frame) + if (luma >= MIN_COVER_LUMA) return frame + if (luma > bestLuma) { best = frame; bestLuma = luma } + } + return best ?: runCatching { retriever.frameAtTime }.getOrNull() + } + + private fun averageLuma(bitmap: Bitmap): Int { + val small = Bitmap.createScaledBitmap(bitmap, 16, 9, true) + var sum = 0L + for (y in 0 until small.height) for (x in 0 until small.width) { + val c = small.getPixel(x, y) + sum += (((c shr 16) and 0xFF) * 3 + ((c shr 8) and 0xFF) * 6 + (c and 0xFF)) / 10 + } + return (sum / (small.width * small.height)).toInt() + } + + private const val MIN_COVER_LUMA = 24 + + /** A cover for a movie: the picture SteamDeckRepo gave it, or one frame taken from the video and remembered. */ + fun cover(context: Context, entry: Entry): File? { + val file = fileOf(context, entry) ?: return null + val name = if (entry.id.startsWith(PREFIX)) file.name else entry.id + // Points Shop covers once kept a picture that was not always the movie's own; those files are not used. + val given = File(thumbsDir(context), if (entry.source == SOURCE_POINTSHOP) "v2-" + coverName(name) else coverName(name)) + if (given.isFile && given.length() > 0L) return given + val key = "frame-" + safe(name) + "-v2-" + file.length() + "-" + file.lastModified() + ".jpg" + val frame = File(thumbsDir(context), key) + if (frame.isFile && frame.length() > 0L) return frame + val retriever = MediaMetadataRetriever() + return try { + retriever.setDataSource(file.path) + val ms = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull() ?: 0L + val bitmap = brightestFrame(retriever, ms) ?: return null + val width = 480 + val scaled = if (bitmap.width > width) Bitmap.createScaledBitmap(bitmap, width, (bitmap.height * width / bitmap.width).coerceAtLeast(1), true) else bitmap + thumbsDir(context).mkdirs() + thumbsDir(context).listFiles { f -> f.name.startsWith("frame-" + safe(name) + "-") }?.forEach { it.delete() } + val staged = File(thumbsDir(context), "$key.staged") + staged.outputStream().use { scaled.compress(CompressFormat.JPEG, 82, it) } + if (staged.renameTo(frame)) frame else null + } catch (e: Exception) { + Log.w(TAG, "no cover for ${file.name}", e) + null + } finally { + runCatching { retriever.release() } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/BootMovieReport.kt b/app/src/main/java/com/droiddeck/launcher/session/BootMovieReport.kt new file mode 100644 index 0000000000..3a672dcfd9 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/BootMovieReport.kt @@ -0,0 +1,160 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import android.os.Environment +import android.util.Log +import java.io.File +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale + +/** + * What DroidDeck and Steam know about boot movies, in one text file: Steam's startup movie setting, every movie file and + * where it lives, DroidDeck's own state, and a short trace of what each session start did to Steam's config. + */ +object BootMovieReport { + private const val TAG = "BootMovieReport" + private const val MAX_TRACE_LINES = 200 + private const val MAX_HITS = 60 + private val KNOWN_TITLES = listOf("Turret Factory") + private val SKIPPED = setOf("steamapps", "compatdata", "shadercache", "logs") + private val BINARY = setOf("webm", "jpg", "jpeg", "png", "ico", "mp4", "ogg", "mp3", "wav", "ttf", "woff", "woff2", "gif", "webp", "bin", "so", "dll", "exe", "zip", "pak") + private val lock = Any() + + private fun traceFile(context: Context) = File(context.filesDir, "boot-movie/apply.log") + + /** Adds a line to the short trace kept for the report; only the latest lines are kept. */ + fun note(context: Context, line: String) { + synchronized(lock) { + runCatching { + val file = traceFile(context) + file.parentFile?.mkdirs() + val stamp = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date()) + val lines = (if (file.isFile) file.readLines() else emptyList()) + "$stamp $line" + file.writeText(lines.takeLast(MAX_TRACE_LINES).joinToString("\n") + "\n") + } + } + } + + /** Writes the report to Downloads/DroidDeck, or to the app's own folder when that is not possible; null when the report cannot be built or neither folder works. */ + fun write(context: Context): File? { + val text = runCatching { build(context) }.getOrElse { + Log.w(TAG, "could not build the report", it) + return null + } + val folders = listOfNotNull( + File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "DroidDeck"), + context.getExternalFilesDir(null), + ) + for (folder in folders) { + val file = File(folder, "boot-movie-report.txt") + val saved = runCatching { folder.mkdirs(); file.writeText(text); true }.getOrDefault(false) + if (saved) return file + Log.w(TAG, "could not write the report to ${file.path}") + } + return null + } + + private fun describe(file: File) = + "${file.path} ${file.length()} bytes ${SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date(file.lastModified()))}" + + internal fun build(context: Context): String { + val out = StringBuilder() + fun line(text: String = "") { out.append(text).append('\n') } + fun listing(title: String, folder: File) { + line("-- $title: ${folder.path}") + val files = folder.listFiles()?.sortedBy { it.name.lowercase() } + if (files == null) line(" (missing)") else if (files.isEmpty()) line(" (empty)") + else files.forEach { line(" " + describe(it)) } + } + + line("DroidDeck boot movie report, ${Date()}") + line() + line("== DroidDeck state") + line("choice=${BootMovie.choice(context)} saved choice=${SessionPrefs.bootMovie(context)} pending pick=${SessionPrefs.bootMovieApplyNext(context)}") + line("last Steam path seen=${SessionPrefs.bootMovieSteamSeen(context)}") + line("sound=${SessionPrefs.bootMovieSound(context)} volume=${SessionPrefs.bootMovieVolume(context)} seconds=${SessionPrefs.bootMovieSeconds(context)}") + line("session running=${SessionState.running}") + line() + line("== The movie list as shown") + BootMovieLibrary.list(context).forEach { line("${it.id} title=${it.title} source=${it.source} removable=${it.removable} file=${it.file?.path}") } + line() + line("== DroidDeck folders") + listing("library", BootMovieLibrary.libraryDir(context)) + listing("processed copies", File(context.filesDir, "boot-movie/variants")) + val meta = File(context.filesDir, "boot-movie/movies.json") + line("-- movie list file: ${if (meta.isFile) meta.readText().take(8000) else "(missing)"}") + + val roots = BootMovieLibrary.steamRoots(context) + val movieIds = HashSet() + for (root in roots) { + line() + line("== Steam folder ${root.path}") + val config = File(root, "config/config.vdf") + line("config.vdf: ${if (config.isFile) describe(config) else "(missing)"}") + val text = runCatching { config.readText() }.getOrNull() + if (text != null) { + line("-- StartupMovie block:") + (SessionFiles.startupMovieBlock(config) ?: " (none)").lines().forEach { line(" $it") } + line("-- Customization section with the lines before it:") + (SessionFiles.customizationBlock(config) ?: " (none)").lines().forEach { line(" $it") } + line("-- every line of config.vdf that mentions a movie:") + text.lines().filter { it.contains("movie", ignoreCase = true) }.take(40).forEach { line(" ${it.trim()}") } + Regex("\"MovieID\"\\s+\"([^\"]*)\"").find(text)?.groupValues?.get(1)?.takeIf { it.isNotEmpty() && it != "0" }?.let { movieIds.add(it) } + } + listing("custom movies", File(root, "config/uioverrides/movies")) + listing("Steam's own movies", File(root, "steamui/movies")) + listing("config/movies", File(root, "config/movies")) + line("-- every .webm below config, userdata, appcache and steamui:") + var shown = 0 + for (top in listOf("config", "userdata", "appcache", "steamui")) { + val base = File(root, top) + if (!base.isDirectory) continue + for (file in base.walkTopDown().maxDepth(8).onEnter { it.name !in SKIPPED }) { + if (!file.isFile || !file.name.endsWith(".webm", ignoreCase = true)) continue + if (shown++ >= 300) break + line(" " + describe(file)) + Regex("^(\\d+)_[0-9a-fA-F]+").find(file.name)?.groupValues?.get(1)?.let { movieIds.add(it) } + } + } + } + + line() + line("== Where Steam keeps movie names (text found in Steam's files)") + val needles = (KNOWN_TITLES + movieIds).distinct() + line("looking for: ${needles.joinToString(", ")}") + search(roots, needles) { line(" $it") } + + line() + line("== What each session start did to Steam's config (latest last)") + val trace = traceFile(context) + if (trace.isFile) trace.readLines().forEach { line(" $it") } else line(" (nothing yet: start a session after picking a movie)") + return out.toString() + } + + private fun search(roots: List, needles: List, report: (String) -> Unit) { + if (needles.isEmpty()) return + val deadline = System.currentTimeMillis() + 25_000L + var scanned = 0 + var hits = 0 + outer@ for (root in roots) { + for (top in listOf("config", "userdata", "appcache", "steamui")) { + val base = File(root, top) + if (!base.isDirectory) continue + for (file in base.walkTopDown().maxDepth(8).onEnter { it.name !in SKIPPED }) { + if (!file.isFile || file.length() > (2L shl 20) || file.extension.lowercase() in BINARY) continue + if (++scanned > 20_000 || System.currentTimeMillis() > deadline || hits >= MAX_HITS) break@outer + val text = runCatching { String(file.readBytes(), Charsets.ISO_8859_1) }.getOrNull() ?: continue + for (needle in needles) { + val at = text.indexOf(needle) + if (at < 0) continue + hits++ + val around = text.substring((at - 60).coerceAtLeast(0), (at + needle.length + 100).coerceAtMost(text.length)) + report("$needle in ${file.path}: " + around.map { if (it in ' '..'~') it else '.' }.joinToString("")) + } + } + } + } + report("(searched $scanned files, $hits matches)") + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/BootMovieTranscoder.kt b/app/src/main/java/com/droiddeck/launcher/session/BootMovieTranscoder.kt index ff1275d851..92bbbae4e2 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/BootMovieTranscoder.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/BootMovieTranscoder.kt @@ -37,15 +37,77 @@ internal object BootMovieTranscoder { MediaCodecList(MediaCodecList.REGULAR_CODECS).findDecoderForFormat(format) != null }.getOrDefault(false) - fun transcode(source: File, target: File, keepAudio: Boolean = true, onProgress: (Int) -> Unit): Result? { + fun transcode(source: File, target: File, keepAudio: Boolean = true, limitUs: Long = Long.MAX_VALUE, gain: Float = 1f, onProgress: (Int) -> Unit): Result? { val hadAudio = keepAudio && trackFormat(source, "audio/") != null - val audio = if (hadAudio) runCatching { encodeAudio(source) } + val audio = if (hadAudio) runCatching { encodeAudio(source, gain, limitUs) } .onFailure { Log.w(TAG, "could not convert the audio of ${source.name}", it) }.getOrNull() else null - val muxedAudio = runCatching { encodeVideo(source, target, audio, onProgress) } + val muxedAudio = runCatching { encodeVideo(source, target, audio, limitUs, onProgress) } .onFailure { Log.w(TAG, "could not convert ${source.name}", it) }.getOrNull() ?: return null return Result(audioDropped = hadAudio && !muxedAudio) } + /** Copies the video of [source] untouched and gives it its sound again at [gain] of its level, cut to [limitUs]. */ + fun regain(source: File, target: File, gain: Float, limitUs: Long): Boolean { + val audio = runCatching { encodeAudio(source, gain, limitUs) } + .onFailure { Log.w(TAG, "could not change the volume of ${source.name}", it) }.getOrNull() ?: return false + val extractor = MediaExtractor() + var muxer: MediaMuxer? = null + val staged = File(target.parentFile, target.name + ".regain") + return try { + extractor.setDataSource(source.path) + var videoTrack = -1 + var videoFormat: MediaFormat? = null + for (i in 0 until extractor.trackCount) { + val format = extractor.getTrackFormat(i) + val mime = format.getString(MediaFormat.KEY_MIME) ?: continue + if (videoTrack < 0 && (mime == MediaFormat.MIMETYPE_VIDEO_VP8 || mime == MediaFormat.MIMETYPE_VIDEO_VP9)) { + videoTrack = i + videoFormat = format + } + } + if (videoTrack < 0 || videoFormat == null) return false + extractor.selectTrack(videoTrack) + val mux = MediaMuxer(staged.path, MediaMuxer.OutputFormat.MUXER_OUTPUT_WEBM).also { muxer = it } + val outVideo = mux.addTrack(videoFormat) + val outAudio = mux.addTrack(audio.format) + mux.start() + val info = MediaCodec.BufferInfo() + var audioIndex = 0 + fun writeAudioUpTo(timeUs: Long) { + while (audioIndex < audio.samples.size && audio.samples[audioIndex].timeUs <= timeUs) { + val sample = audio.samples[audioIndex++] + info.set(0, sample.data.size, sample.timeUs, 0) + mux.writeSampleData(outAudio, ByteBuffer.wrap(sample.data), info) + } + } + var bufferSize = 8 shl 20 + if (videoFormat.containsKey(MediaFormat.KEY_MAX_INPUT_SIZE)) bufferSize = maxOf(bufferSize, videoFormat.getInteger(MediaFormat.KEY_MAX_INPUT_SIZE)) + val buffer = ByteBuffer.allocate(bufferSize) + while (true) { + val size = extractor.readSampleData(buffer, 0) + if (size < 0 || extractor.sampleTime > limitUs) break + val time = extractor.sampleTime + writeAudioUpTo(time) + val key = extractor.sampleFlags and MediaExtractor.SAMPLE_FLAG_SYNC != 0 + info.set(0, size, time, if (key) MediaCodec.BUFFER_FLAG_KEY_FRAME else 0) + mux.writeSampleData(outVideo, buffer, info) + extractor.advance() + } + writeAudioUpTo(Long.MAX_VALUE) + mux.stop() + mux.release() + muxer = null + staged.renameTo(target) + } catch (e: Exception) { + Log.w(TAG, "could not change the volume of ${source.name}", e) + false + } finally { + runCatching { muxer?.release() } + extractor.release() + staged.delete() + } + } + private fun trackFormat(source: File, prefix: String): Pair? { val extractor = MediaExtractor() return try { @@ -75,6 +137,14 @@ internal object BootMovieTranscoder { return Layout(canvas, ch, (canvas - cw) / 2, 0, cw, ch) } + /** [pcm] made quieter by [gain] and cut to its first [limitUs] microseconds. */ + internal fun scale(pcm: ShortArray, channels: Int, gain: Float, limitUs: Long): ShortArray { + val frames = pcm.size / channels + val kept = if (limitUs == Long.MAX_VALUE) frames else minOf(frames.toLong(), limitUs * OPUS_RATE / 1_000_000L).toInt() + if (gain == 1f && kept == frames) return pcm + return ShortArray(kept * channels) { (pcm[it] * gain).toInt().coerceIn(Short.MIN_VALUE.toInt(), Short.MAX_VALUE.toInt()).toShort() } + } + internal fun resample(pcm: ShortArray, channels: Int, rate: Int): ShortArray { if (rate == OPUS_RATE) return pcm val frames = pcm.size / channels @@ -94,7 +164,10 @@ internal object BootMovieTranscoder { return out } - private fun encodeAudio(source: File): Audio? { + /** Most decoded audio held in memory at once: about six minutes of 48 kHz stereo. */ + private const val MAX_PCM_BYTES = 64 shl 20 + + private fun encodeAudio(source: File, gain: Float = 1f, limitUs: Long = Long.MAX_VALUE): Audio? { val (track, inFormat) = trackFormat(source, "audio/") ?: return null val extractor = MediaExtractor() var decoder: MediaCodec? = null @@ -139,13 +212,16 @@ internal object BootMovieTranscoder { } dec.releaseOutputBuffer(index, false) if (info.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) break + // Past the length that will be kept there is nothing more to decode; without a length, a track too big to hold is dropped. + if (limitUs != Long.MAX_VALUE && info.presentationTimeUs > limitUs) break + if (pcm.size() > MAX_PCM_BYTES) { if (limitUs == Long.MAX_VALUE) return null else break } } } if (channels !in 1..2) return null val raw = pcm.toByteArray() val shorts = ShortArray(raw.size / 2) ByteBuffer.wrap(raw).order(ByteOrder.nativeOrder()).asShortBuffer().get(shorts) - val samples = resample(shorts, channels, rate) + val samples = scale(resample(shorts, channels, rate), channels, gain, limitUs) val format = MediaFormat.createAudioFormat(MediaFormat.MIMETYPE_AUDIO_OPUS, OPUS_RATE, channels) format.setInteger(MediaFormat.KEY_BIT_RATE, 128_000) @@ -201,7 +277,7 @@ internal object BootMovieTranscoder { private fun MediaFormat.intOrNull(key: String): Int? = if (!containsKey(key)) null else runCatching { getInteger(key) }.getOrElse { runCatching { getFloat(key).toInt() }.getOrNull() } - private fun encodeVideo(source: File, target: File, audio: Audio?, onProgress: (Int) -> Unit): Boolean { + private fun encodeVideo(source: File, target: File, audio: Audio?, limitUs: Long, onProgress: (Int) -> Unit): Boolean { val (track, inFormat) = trackFormat(source, "video/") ?: throw IllegalStateException("no video track") val rotation = (inFormat.intOrNull(MediaFormat.KEY_ROTATION) ?: 0).mod(360) val layout = layout(inFormat.getInteger(MediaFormat.KEY_WIDTH), inFormat.getInteger(MediaFormat.KEY_HEIGHT), rotation) @@ -278,7 +354,8 @@ internal object BootMovieTranscoder { val index = dec.dequeueOutputBuffer(decInfo, TIMEOUT_US) if (index >= 0) { val timeUs = decInfo.presentationTimeUs - val keep = decInfo.size > 0 && (lastKept == Long.MIN_VALUE || timeUs - lastKept >= minIntervalUs) + val pastLimit = timeUs > limitUs + val keep = decInfo.size > 0 && !pastLimit && (lastKept == Long.MIN_VALUE || timeUs - lastKept >= minIntervalUs) dec.releaseOutputBuffer(index, keep) if (keep) { if (!frames.awaitFrame()) throw IllegalStateException("decoder frame timed out") @@ -290,9 +367,10 @@ internal object BootMovieTranscoder { if (percent != lastProgress) { lastProgress = percent; onProgress(percent) } } } - if (decInfo.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) { + if (pastLimit || decInfo.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0) { enc.signalEndOfInputStream() decoderDone = true + inputDone = true } } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/InputSysfsComponent.kt b/app/src/main/java/com/droiddeck/launcher/session/InputSysfsComponent.kt new file mode 100644 index 0000000000..03ecd7e8bc --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/InputSysfsComponent.kt @@ -0,0 +1,179 @@ +package com.droiddeck.launcher.session + +import android.os.FileObserver +import android.os.SystemClock +import android.system.Os +import android.util.Log +import com.droiddeck.launcher.core.FileUtils +import com.droiddeck.launcher.core.SessionPart +import com.droiddeck.launcher.input.FakeInputWriter +import java.io.File + +class InputSysfsComponent( + private val nodes: File, + base: File, + private val udevData: File, + private val deckPad: Boolean, + private val steamVirtual: Boolean, +) : SessionPart() { + private val devices = File(base, "devices") + private val classDir = File(base, "class") + private val shown = HashSet() + private var observer: FileObserver? = null + private var running = false + + fun prepare(): Boolean = try { + FileUtils.clear(devices) + FileUtils.clear(classDir) + devices.mkdirs() + classDir.mkdirs() + udevData.mkdirs() + udevData.listFiles()?.forEach { if (isPadRecord(it.name)) it.delete() } + devices.isDirectory && classDir.isDirectory + } catch (e: Exception) { + Log.w(TAG, "pads: could not prepare the input sysfs: $e") + false + } + + fun binds() = listOf(devices.path + ":" + GUEST_DEVICES, classDir.path + ":" + GUEST_CLASS) + + override fun start() { + synchronized(this) { running = true } + active = this + @Suppress("DEPRECATION") + observer = object : FileObserver(nodes.path, CREATE or DELETE or MOVED_TO or MOVED_FROM or CLOSE_WRITE) { + override fun onEvent(event: Int, path: String?) { + if (path != null && NODE_FILE.matches(path)) sync() + } + }.also { it.startWatching() } + sync() + } + + override fun stop() { + observer?.stopWatching() + observer = null + if (active === this) active = null + synchronized(this) { + running = false + for (node in shown.toList()) hide(node) + } + } + + @Synchronized + fun sync() { + if (!running) return + val wanted = (0 until NODE_LIMIT).filter { node -> + File(nodes, "event$node").exists() && if (node >= FIRST_VIRTUAL) File(nodes, ".uinput-event$node.uevent").isFile + else !ringWithdrawn(deckPad, padType) + }.toSet() + for (node in shown - wanted) hide(node) + for (node in wanted - shown) show(node) + } + + private fun show(node: Int) { + val pad = (if (node >= FIRST_VIRTUAL) runCatching { File(nodes, ".uinput-event$node.uevent").readText() }.getOrNull()?.let(::virtualPad) + else ringPad(node, steamVirtual)) ?: return + try { + val input = File(devices, "input$node") + val event = File(input, "event$node") + event.mkdirs() + File(input, "uevent").writeText(pad.uevent()) + File(input, "name").writeText(pad.name + "\n") + File(input, "phys").writeText(pad.phys + "\n") + File(input, "uniq").writeText(pad.uniq + "\n") + File(input, "properties").writeText("0\n") + File(input, "id").mkdirs() + File(input, "id/bustype").writeText("%04x\n".format(pad.bus)) + File(input, "id/vendor").writeText("%04x\n".format(pad.vendor)) + File(input, "id/product").writeText("%04x\n".format(pad.product)) + File(input, "id/version").writeText("%04x\n".format(pad.version)) + File(input, "capabilities").mkdirs() + for (name in CAPABILITIES) File(input, "capabilities/$name").writeText("0\n") + link(File(input, "subsystem"), GUEST_CLASS) + File(event, "uevent").writeText("MAJOR=$MAJOR\nMINOR=${MINOR_BASE + node}\nDEVNAME=input/event$node\n") + File(event, "dev").writeText("$MAJOR:${MINOR_BASE + node}\n") + link(File(event, "subsystem"), GUEST_CLASS) + link(File(event, "device"), "$GUEST_DEVICES/input$node") + val record = udevRecord(SystemClock.elapsedRealtimeNanos() / 1000) + File(udevData, "+input:input$node").writeText(record) + File(udevData, "c$MAJOR:${MINOR_BASE + node}").writeText(record) + link(File(classDir, "input$node"), "$GUEST_DEVICES/input$node") + link(File(classDir, "event$node"), "$GUEST_DEVICES/input$node/event$node") + shown.add(node) + Log.i(TAG, "pads: /dev/input/event$node listed for udev as \"${pad.name}\" (%04x:%04x)".format(pad.vendor, pad.product)) + } catch (e: Exception) { + Log.w(TAG, "pads: could not list /dev/input/event$node for udev: $e") + hide(node) + } + } + + private fun hide(node: Int) { + File(classDir, "event$node").delete() + File(classDir, "input$node").delete() + File(udevData, "c$MAJOR:${MINOR_BASE + node}").delete() + File(udevData, "+input:input$node").delete() + File(devices, "input$node").let { FileUtils.clear(it); it.delete() } + if (shown.remove(node)) Log.i(TAG, "pads: /dev/input/event$node no longer listed for udev") + } + + private fun link(file: File, target: String) { + file.delete() + Os.symlink(target, file.path) + } + + data class Pad( + val bus: Int, + val vendor: Int, + val product: Int, + val version: Int, + val name: String, + val phys: String, + val uniq: String, + ) { + fun uevent(): String = + "PRODUCT=%x/%x/%x/%x\nNAME=\"$name\"\nPHYS=\"$phys\"\nUNIQ=\"$uniq\"\nPROP=0\n".format(bus, vendor, product, version) + } + + companion object { + private const val TAG = "SessionService" + const val GUEST_DEVICES = "/sys/devices/virtual/input" + const val GUEST_CLASS = "/sys/class/input" + private const val MAJOR = 13 + private const val MINOR_BASE = 64 + private const val FIRST_VIRTUAL = 16 + private const val NODE_LIMIT = 64 + private val NODE_FILE = Regex("(\\.uinput-)?event\\d+(\\.uevent)?") + private val CAPABILITIES = listOf("ev", "key", "rel", "abs", "msc", "sw", "led", "snd", "ff") + + @Volatile private var active: InputSysfsComponent? = null + @Volatile private var padType = -1 + + fun padTypeChanged(type: Int) { + padType = type + active?.let { Thread(it::sync, "input-sysfs").start() } + } + + internal fun ringWithdrawn(deckPad: Boolean, type: Int) = deckPad && type != FakeInputWriter.PAD_TYPE_XBOX + + internal fun isPadRecord(name: String) = + Regex("c$MAJOR:(\\d+)").matchEntire(name)?.groupValues?.get(1)?.toInt()?.let { it in MINOR_BASE until MINOR_BASE + NODE_LIMIT } == true || + Regex("\\+input:input(\\d+)").matchEntire(name)?.groupValues?.get(1)?.toInt()?.let { it < NODE_LIMIT } == true + + internal fun udevRecord(initializedUs: Long) = + "I:$initializedUs\nE:ID_INPUT=1\nE:ID_INPUT_JOYSTICK=1\nE:ID_SERIAL=noserial\nG:seat\nG:uaccess\nQ:seat\nQ:uaccess\nV:1\n" + + internal fun ringPad(node: Int, steamVirtual: Boolean) = if (steamVirtual) { + Pad(3, 0x28de, 0x11ff, 0x110, "Microsoft X-Box 360 pad $node", "usb-fakeinput/input$node", "0000000000%02d".format(node)) + } else { + Pad(3, 0x045e, 0x028e, 0x110, "Xbox 360 Controller ($node)", "usb-fakeinput/input$node", "0000000000%02d".format(node)) + } + + internal fun virtualPad(uevent: String): Pad? { + val values = uevent.lines().mapNotNull { line -> + line.indexOf('=').takeIf { it > 0 }?.let { line.substring(0, it) to line.substring(it + 1).trim('"') } + }.toMap() + val id = values["PRODUCT"]?.split('/')?.mapNotNull { it.toIntOrNull(16) }?.takeIf { it.size == 4 } ?: return null + return Pad(id[0], id[1], id[2], id[3], values["NAME"] ?: return null, values["PHYS"].orEmpty(), values["UNIQ"].orEmpty()) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt index e0e8557422..9ec21c2090 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt @@ -118,7 +118,9 @@ object SessionArtifacts { private fun scrubFolder(dir: File, record: Record) { dir.listFiles { f -> f.isFile && !f.name.startsWith(".") && f !in record.files }?.forEach { f -> - if (!LogRedactor.isText(f)) return@forEach + if (LogRedactor.isBinary(f)) return@forEach + // Too large to rewrite in memory: the folder must not be recorded as scrubbed. + if (!LogRedactor.isText(f)) { record.failed = true; return@forEach } val done = scrubFile(dir, f) if (done == null) record.failed = true else record.files[f] = done } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt index a29531cc1f..38b543f936 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -1,10 +1,12 @@ package com.droiddeck.launcher.session +import com.droiddeck.launcher.core.AddonPack import android.content.Context import android.os.Environment import android.util.Log import com.droiddeck.launcher.R import com.droiddeck.launcher.core.FileUtils +import com.droiddeck.launcher.runtime.BwrapSpawner import com.droiddeck.launcher.runtime.DesktopCatalog import com.droiddeck.launcher.runtime.LegacyNames import com.droiddeck.launcher.runtime.LinuxRuntime @@ -15,6 +17,7 @@ object SessionFiles { private const val TAG = "SessionFiles" private const val NO_PAD_SWITCH = "Download/droiddeck-no-pad" const val DIRECTAUDIO_DIR = "usr/local/lib/directaudio" + private const val STAGED_LEDGER = "usr/local/.droiddeck-staged" val DIRECTAUDIO_SETS = arrayOf("linux-wine11", "linux-wine11-systhread") internal val DESKTOP_FILES = arrayOf( @@ -27,7 +30,8 @@ object SessionFiles { "etc/xdg/autostart/droiddeck-clipboard.desktop" to "etc/xdg/autostart/droiddeck-clipboard.desktop", ) - fun stage(context: Context, root: File) { + /** Puts the session's files in place; [startsSession] is true only for the call that starts the Steam session. */ + fun stage(context: Context, root: File, startsSession: Boolean = false) { if (DesktopCatalog.desktopInstalled(root)) try { DesktopCatalog.cleanLegacy(context) } catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) } GameEnvironmentStore.publish(context) @@ -143,15 +147,15 @@ object SessionFiles { "usr/local/bin/gamescope" to "usr/local/bin/gamescope", "usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime", "usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE", - ) + listOf("xodus-cli", "xodus-service", "LICENSE.xodus", "LICENSE.nexus", "LICENSE.LGPL-2.1", "LICENSE.nghttp2", "backend.lock.json", "runtime.lock.json", "version", - "windows/xgameruntime.dll", "windows/winhttp.dll", "windows/windows.web.dll", "windows/twinapi.appcore.dll", "windows/libnghttp2.dll") - .map { "usr/local/lib/droiddeck-xbox/$it" to "usr/local/lib/droiddeck-xbox/$it" } + mangoapp + listOf("comet", "GalaxyCommunication.exe", "update-permissions.exe", "LICENSE", "version").map { "usr/local/lib/droiddeck-comet/$it" to "usr/local/lib/droiddeck-comet/$it" } + msitools.map { it to it } + vr + fexPreloads).filter { (asset, _) -> + ) + mangoapp + msitools.map { it to it } + vr + fexPreloads).filter { (asset, _) -> val dir = asset.substringBeforeLast('/') runCatching { context.assets.list("linuxfs/$dir")?.contains(asset.substringAfterLast('/')) == true }.getOrDefault(false) } val all = (if (DesktopCatalog.desktopInstalled(root)) files + DESKTOP_FILES else files) + optional + val ledger = StageLedger(File(root, STAGED_LEDGER), apkIdentity(context)) for ((asset, relative) in all) { val target = File(root, relative) + if (ledger.current(relative, target)) continue val staged = File(target.parentFile, target.name + ".staged") var installed = false try { @@ -165,7 +169,7 @@ object SessionFiles { } finally { if (!installed) staged.delete() } - if (!installed) Log.e(TAG, "$relative NOT staged") + if (installed) ledger.staged(relative, target) else Log.e(TAG, "$relative NOT staged") } File(root, "usr/local/bin/bannerlator-steam-compat").delete() LegacyNames.migrateRootfs(root) @@ -177,13 +181,17 @@ object SessionFiles { "i386-windows/winedirectaudio.drv", "version.txt", ) - for (set in DIRECTAUDIO_SETS) for (relative in directAudio) { - val target = File(root, "$DIRECTAUDIO_DIR/$set/lib/wine/$relative") + val directAudioPack = AddonPack.DIRECTAUDIO.takeIf { it.installed(context) }?.dir(context) + if (directAudioPack == null) Log.w(TAG, "DirectAudio pack is not installed; drivers not staged") + if (directAudioPack != null) for (set in DIRECTAUDIO_SETS) for (relative in directAudio) { + val key = "$DIRECTAUDIO_DIR/$set/lib/wine/$relative" + val target = File(root, key) + if (ledger.current(key, target)) continue val staged = File(target.parentFile, target.name + ".staged") var installed = false try { target.parentFile?.mkdirs() - context.assets.open("directaudio/$set/$relative").use { input -> + File(directAudioPack, "$set/$relative").inputStream().use { input -> staged.outputStream().use { output -> FileUtils.copy(input, output) } } installed = staged.setReadable(true, false) && staged.renameTo(target) @@ -192,8 +200,9 @@ object SessionFiles { } finally { if (!installed) staged.delete() } - if (!installed) Log.e(TAG, "DirectAudio $set/$relative NOT staged") + if (installed) ledger.staged(key, target) else Log.e(TAG, "DirectAudio $set/$relative NOT staged") } + ledger.save() for (old in arrayOf("aarch64-unix", "aarch64-windows", "i386-windows")) File(root, "$DIRECTAUDIO_DIR/lib/wine/$old").deleteRecursively() val preload = StringBuilder("/usr/local/lib/libblsession.so\n") if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) { @@ -210,20 +219,118 @@ object SessionFiles { if (!FileUtils.writeString(File(etc, "steam-compatibility-label"), context.getString(R.string.steam_compat_label))) { Log.e(TAG, "could not write steam-compatibility-label") } + val droiddeckEtc = File(etc, "droiddeck").apply { mkdirs() } + val stagedSocket = File(droiddeckEtc, "bwrap-socket.staged") + if (!FileUtils.writeString(stagedSocket, BwrapSpawner.socket(context) + "\n") + || !stagedSocket.renameTo(File(droiddeckEtc, "bwrap-socket"))) { + stagedSocket.delete() + Log.e(TAG, "could not write bwrap-socket") + } + BootMovie.syncFromSteam(context) val startupMovie = BootMovie.prepare(context) - // The x86-64 client's config is left alone until its first start creates it. - val steamRoots = listOf(File(root, "root/.local/share/Steam"), File(root, "root/.droiddeck-x64/.local/share/Steam")) - .filterIndexed { i, steam -> i == 0 || File(steam, "config").isDirectory } - for (steam in steamRoots) { - val startupMovieDir = File(steam, "config/uioverrides/movies") - val bigPictureMovieInstalled = startupMovie != null && - stageStartupMovie(startupMovie, startupMovieDir, "bigpicture_startup.webm") - if (startupMovie != null) stageStartupMovie(startupMovie, startupMovieDir, "steam_os_startup.webm") - if (bigPictureMovieInstalled) { - ensureStartupMovieDefault(File(steam, "config/config.vdf")) + val force = SessionPrefs.bootMovieApplyNext(context) + val steamHomes = listOf(File(root, "root/.local/share/Steam")) + + listOf(File(root, "root/.droiddeck-x64/.local/share/Steam")).filter { File(it, "config").isDirectory } + var allDone = true + var allInstalled = true + var seen: String? = null + val activeIsX64 = SessionPrefs.activeSteamClientArch(context) == "x86_64" + for (home in steamHomes) { + val movieDir = File(home, "config/uioverrides/movies") + val config = File(home, "config/config.vdf") + if (startupMovie == null) { + // Nothing to play (a movie whose volume could not be set is never played at another volume), so no earlier copy plays either. + for (name in listOf("bigpicture_startup.webm", "steam_os_startup.webm")) { + File(movieDir, name).delete() + File(movieDir, ".$name.source").delete() + } + } + val bigPictureMovieInstalled = startupMovie != null && stageStartupMovie(startupMovie, movieDir, "bigpicture_startup.webm") + if (startupMovie != null) stageStartupMovie(startupMovie, movieDir, "steam_os_startup.webm") + val before = startupMoviePath(config) + val done = if (bigPictureMovieInstalled) ensureStartupMovieDefault(config, force) else resetMissingStartupMovie(config, force) + BootMovieReport.note( + context, + "stage session=$startsSession pending=$force choice=${SessionPrefs.bootMovie(context)} movie=${startupMovie?.path} " + + "staged=$bigPictureMovieInstalled done=$done steam=${home.path} config: $before -> ${startupMoviePath(config)}", + ) + if (!done) allDone = false + if (!bigPictureMovieInstalled) allInstalled = false + if (done && home.path.contains(".droiddeck-x64") == activeIsX64) seen = if (bigPictureMovieInstalled) BOOT_MOVIE_PATH else "" + } + // A pick made in the app is done once a session started with every Steam client's config having it; guest commands run + // before that, and a Steam that is already running writes its own choice back when it exits. + if (force && allDone && allInstalled && startsSession) SessionPrefs.setBootMovieApplyNext(context, false) + seen?.let { SessionPrefs.setBootMovieSteamSeen(context, it) } + } + + /** + * Points Steam's startup movie back at its own default when it names a movie that is gone: DroidDeck's staged copy that + * could not be prepared, or (when a pick here is waiting) a movie removed from Steam's folder. True when Steam's config + * no longer names a missing movie. + */ + internal fun resetMissingStartupMovie(config: File, force: Boolean): Boolean { + if (!config.isFile) return true + val text = runCatching { config.readText() }.getOrElse { + Log.w(TAG, "could not read Steam config to reset the startup movie", it) + return false + } + val movie = activeStartupMovie(text) ?: return true + val block = text.substring(movie.keyStart, movie.close + 1) + val path = scalar(block, "LocalPath").orEmpty() + if (path.isEmpty()) return true + val missing = File(config.parentFile, "uioverrides/movies/" + path.removePrefix(BOOT_MOVIES_DIR)) + val gone = path.startsWith(BOOT_MOVIES_DIR) && !missing.isFile && (force || path == BOOT_MOVIE_PATH) + if (!gone) return false + val newline = if (text.contains("\r\n")) "\r\n" else "\n" + val updated = setScalar(setScalar(block, "MovieID", "0", newline), "LocalPath", "", newline) + val staged = File(config.parentFile, config.name + ".staged") + return try { + staged.writeText(text.replaceRange(movie.keyStart, movie.close + 1, updated)) + (staged.renameTo(config)).also { if (!it) staged.delete() } + } catch (e: Exception) { + staged.delete() + Log.w(TAG, "could not reset Steam startup movie selection", e) + false + } + } + + private fun apkIdentity(context: Context): String { + val apk = File(context.applicationInfo.sourceDir) + return "${apk.path} ${apk.length()} ${apk.lastModified()}" + } + + private class StageLedger(private val file: File, private val identity: String) { + private val before: Map = FileUtils.readString(file)?.lines() + ?.takeIf { it.firstOrNull() == identity } + ?.drop(1)?.mapNotNull { line -> line.split('\t').takeIf { it.size == 2 }?.let { it[0] to it[1] } }?.toMap() + .orEmpty() + private val after = LinkedHashMap() + + fun current(relative: String, target: File): Boolean { + val mark = mark(target) ?: return false + if (before[relative] != mark) return false + after[relative] = mark + return true + } + + fun staged(relative: String, target: File) { + mark(target)?.let { after[relative] = it } + } + + fun save() { + if (after == before) return + val text = (listOf(identity) + after.map { (relative, mark) -> "$relative\t$mark" }).joinToString("\n") + val staged = File(file.parentFile, file.name + ".staged") + if (!FileUtils.writeString(staged, text) || !staged.renameTo(file)) { + staged.delete() + file.delete() } } + + private fun mark(target: File): String? = + if (target.isFile) "${target.length()} ${target.lastModified()} ${target.canExecute()}" else null } private fun stageStartupMovie(source: File, directory: File, name: String): Boolean { @@ -239,7 +346,11 @@ object SessionFiles { staged.outputStream().use { output -> FileUtils.copy(input, output) } } installed = staged.setReadable(true, false) && staged.renameTo(movie) - if (installed) FileUtils.writeString(stamp, identity) + if (installed) { + FileUtils.writeString(stamp, identity) + // Steam's picker draws its preview from this picture and does not redraw it when the movie changes. + File(directory, name.removeSuffix(".webm") + ".jpg").delete() + } } catch (e: Exception) { Log.w(TAG, "could not stage Steam startup movie $name", e) } finally { @@ -251,43 +362,108 @@ object SessionFiles { private data class VdfBlock(val keyStart: Int, val open: Int, val close: Int) - private fun ensureStartupMovieDefault(config: File) { - val path = "/uioverrides/movies/bigpicture_startup.webm" + internal const val BOOT_MOVIES_DIR = "/uioverrides/movies/" + internal const val BOOT_MOVIE_PATH = "/uioverrides/movies/bigpicture_startup.webm" + + /** + * Steam's startup movie setting is the `StartupMovie` section inside its `Customization` section; the one under the Steam + * settings is where older clients kept it, and DroidDeck still keeps it in step. + */ + private fun customizationMovie(text: String): VdfBlock? { + var from = 0 + while (true) { + val customization = findObject(text, "Customization", from, text.length) ?: return null + findObject(text, "StartupMovie", customization.open + 1, customization.close)?.let { return it } + from = customization.close + 1 + } + } + + /** The older `StartupMovie` section: the first one that is not inside `Customization`. */ + private fun olderMovie(text: String): VdfBlock? { + val inside = customizationMovie(text) + var from = 0 + while (true) { + val movie = findObject(text, "StartupMovie", from, text.length) ?: return null + if (inside == null || movie.keyStart != inside.keyStart) return movie + from = movie.close + 1 + } + } + + /** The section Steam reads: the one under `Customization` when there is one. */ + private fun activeStartupMovie(text: String): VdfBlock? = customizationMovie(text) ?: olderMovie(text) + + /** The movie Steam's config selects, as a path like `/uioverrides/movies/x.webm`; null when none is named. */ + internal fun startupMoviePath(config: File): String? { + val text = runCatching { config.readText() }.getOrNull() ?: return null + val movie = activeStartupMovie(text) ?: return null + return scalar(text.substring(movie.keyStart, movie.close + 1), "LocalPath")?.takeIf { it.isNotEmpty() } + } + + /** Both `StartupMovie` sections of Steam's config as written there, for the report; null when there is none. */ + internal fun startupMovieBlock(config: File): String? { + val text = runCatching { config.readText() }.getOrNull() ?: return null + val parts = listOfNotNull( + customizationMovie(text)?.let { "under Customization:\n" + text.substring(it.keyStart, it.close + 1) }, + olderMovie(text)?.let { "older place:\n" + text.substring(it.keyStart, it.close + 1) }, + ) + return parts.takeIf { it.isNotEmpty() }?.joinToString("\n") + } + + /** The `Customization` section of Steam's config with the lines before it, for the report; null when there is none. */ + internal fun customizationBlock(config: File): String? { + val text = runCatching { config.readText() }.getOrNull() ?: return null + val customization = findObject(text, "Customization", 0, text.length) ?: return null + val before = text.substring(0, customization.keyStart).lines().takeLast(4).joinToString("\n") + return (before + "\n" + text.substring(customization.keyStart, customization.close + 1)).take(4000) + } + + private fun pointAt(text: String, movie: VdfBlock, path: String, newline: String): String { + val block = text.substring(movie.keyStart, movie.close + 1) + return text.replaceRange(movie.keyStart, movie.close + 1, setScalar(setScalar(block, "MovieID", "0", newline), "LocalPath", path, newline)) + } + + /** True when Steam's config selects DroidDeck's staged movie once this returns. */ + internal fun ensureStartupMovieDefault(config: File, force: Boolean = false): Boolean { + val path = BOOT_MOVIE_PATH val legacyPath = "/uioverrides/movies/droiddeck-startup.webm" var text = if (config.isFile) runCatching { config.readText() }.getOrElse { Log.w(TAG, "could not read Steam config for startup movie", it) - return + return false } else "" val newline = if (text.contains("\r\n")) "\r\n" else "\n" - val movie = findObject(text, "StartupMovie", 0, text.length) - if (movie != null) { - val block = text.substring(movie.keyStart, movie.close + 1) + val custom = customizationMovie(text) + val active = custom ?: olderMovie(text) + if (active != null) { + val block = text.substring(active.keyStart, active.close + 1) val selectedId = scalar(block, "MovieID") val selectedPath = scalar(block, "LocalPath") - if (selectedPath == path) { + if (selectedPath == path && custom != null) { Log.i(TAG, "Steam startup movie is set to DroidDeck") - return + return true } val legacyDefault = selectedId == "0" && selectedPath == legacyPath val hasExplicitSelection = (!selectedId.isNullOrEmpty() && selectedId != "0") || !selectedPath.isNullOrEmpty() - if (!legacyDefault && hasExplicitSelection) { + if (!force && !legacyDefault && hasExplicitSelection && selectedPath != path) { Log.i(TAG, "Steam startup movie selection preserved") - return + return false } - val updated = setScalar(block, "MovieID", "0", newline) - .let { setScalar(it, "LocalPath", path, newline) } - text = text.replaceRange(movie.keyStart, movie.close + 1, updated) - } else { + } + // Later sections first, so the positions of earlier ones stay valid. + val targets = listOfNotNull(customizationMovie(text), olderMovie(text)).sortedByDescending { it.keyStart } + for (target in targets) text = pointAt(text, target, path, newline) + if (olderMovie(text) == null) { val steam = findSteamBlock(text) if (steam == null) { - if (text.isNotBlank()) { + if (text.isNotBlank() && customizationMovie(text) == null) { Log.w(TAG, "Steam config has no Steam settings block; startup movie default not set") - return + return false + } + if (text.isBlank()) { + text = "\"InstallConfigStore\"${newline}{${newline}\t\"Software\"${newline}\t{${newline}\t\t\"Valve\"${newline}\t\t{${newline}\t\t\t\"Steam\"${newline}\t\t\t{${newline}" + val section = startupMovieSection("\t\t\t\t", path, newline) + text += section + newline + "\t\t\t}" + newline + "\t\t}" + newline + "\t}" + newline + "}" } - text = "\"InstallConfigStore\"${newline}{${newline}\t\"Software\"${newline}\t{${newline}\t\t\"Valve\"${newline}\t\t{${newline}\t\t\t\"Steam\"${newline}\t\t\t{${newline}" - val section = startupMovieSection("\t\t\t\t", path, newline) - text += section + newline + "\t\t\t}" + newline + "\t\t}" + newline + "\t}" + newline + "}" } else { val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 } val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' } @@ -295,22 +471,35 @@ object SessionFiles { text = text.substring(0, lineStart) + section + newline + indent + text.substring(lineStart) } } + if (customizationMovie(text) == null) text = withCustomization(text, path, newline) val staged = File(config.parentFile, config.name + ".staged") - try { + return try { config.parentFile?.mkdirs() staged.writeText(text) if (!staged.renameTo(config)) { staged.delete() Log.e(TAG, "could not write Steam startup movie selection") + false } else { Log.i(TAG, "Steam startup movie default selected") + true } } catch (e: Exception) { staged.delete() Log.w(TAG, "could not write Steam startup movie selection", e) + false } } + /** Adds the `Customization` section Steam reads, next to the `Software` section, when the config has none. */ + private fun withCustomization(text: String, path: String, newline: String): String { + val root = findObject(text, "InstallConfigStore", 0, text.length) ?: return text + val lineStart = text.lastIndexOf('\n', root.close).let { if (it < 0) 0 else it + 1 } + val indent = text.substring(lineStart, root.close).takeWhile { it == '\t' || it == ' ' } + val section = listOf(indent + "\t\"Customization\"", indent + "\t{", startupMovieSection(indent + "\t\t", path, newline), indent + "\t}").joinToString(newline) + return text.substring(0, lineStart) + section + newline + text.substring(lineStart) + } + private fun findSteamBlock(text: String): VdfBlock? { val install = findObject(text, "InstallConfigStore", 0, text.length) ?: return null val software = findObject(text, "Software", install.open + 1, install.close) ?: return null diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionLogShare.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionLogShare.kt index 80c00cc99a..b44c5c6260 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionLogShare.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionLogShare.kt @@ -66,15 +66,12 @@ object SessionLogShare { return zip } + /** Every entry is scrubbed line by line, whatever its size: a raw copy can carry tokens out of the device. */ private fun addEntry(z: ZipOutputStream, name: String, f: File) { z.putNextEntry(ZipEntry(name)) - if (LogRedactor.isText(f)) { - val w = z.bufferedWriter() - LogRedactor.scrubForShare(f, w) - w.flush() - } else { - f.inputStream().use { it.copyTo(z) } - } + val w = z.bufferedWriter() + LogRedactor.scrubForShare(f, w) + w.flush() z.closeEntry() } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 3cf155ccb7..e7556e97a5 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -118,6 +118,20 @@ object SessionPrefs { prefs(context).edit().putString("storesView", if (view in STORES_VIEWS) view else STORES_VIEWS.first()).apply() } + fun storesTabOrder(context: Context): List = idList(prefs(context).getString("storesTabOrder", null)) + + fun setStoresTabOrder(context: Context, order: List) { + prefs(context).edit().putString("storesTabOrder", order.joinToString(",")).apply() + } + + fun storesTabHidden(context: Context): Set = idList(prefs(context).getString("storesTabHidden", null)).toSet() + + fun setStoresTabHidden(context: Context, hidden: Set) { + prefs(context).edit().putString("storesTabHidden", hidden.joinToString(",")).apply() + } + + private fun idList(raw: String?): List = raw.orEmpty().split(',').map { it.trim() }.filter { it.isNotEmpty() } + val STORES_SORTS = listOf("lastPlayed", "recentlyInstalled", "titleAsc", "titleDesc", "sizeDesc", "sizeAsc", "releaseDateDesc") val STORES_VIEWS = listOf("cards", "capsules", "list") @@ -528,6 +542,17 @@ object SessionPrefs { fun setBootMovie(context: Context, id: String) { prefs(context).edit().putString("bootMovie", id).apply() } fun bootMovieSound(context: Context): Boolean = prefs(context).getBoolean("bootMovieSound", true) fun setBootMovieSound(context: Context, on: Boolean) { prefs(context).edit().putBoolean("bootMovieSound", on).apply() } + fun bootMovieVolume(context: Context): Int = prefs(context).getInt("bootMovieVolume", 100).coerceIn(0, 100) + fun setBootMovieVolume(context: Context, percent: Int) { prefs(context).edit().putInt("bootMovieVolume", percent.coerceIn(0, 100)).apply() } + /** How long the boot movie plays, in seconds; 0 plays all of it. */ + fun bootMovieSeconds(context: Context): Int = prefs(context).getInt("bootMovieSeconds", 0).coerceAtLeast(0) + fun setBootMovieSeconds(context: Context, seconds: Int) { prefs(context).edit().putInt("bootMovieSeconds", seconds.coerceAtLeast(0)).apply() } + /** Set when a movie was picked here, so the next session makes it Steam's startup movie even if Steam had another one. */ + fun bootMovieApplyNext(context: Context): Boolean = prefs(context).getBoolean("bootMovieApplyNext", false) + fun setBootMovieApplyNext(context: Context, on: Boolean) { prefs(context).edit().putBoolean("bootMovieApplyNext", on).apply() } + /** The startup movie path Steam's config held when it was last looked at, so only a change made in Steam is taken over. */ + fun bootMovieSteamSeen(context: Context): String? = prefs(context).getString("bootMovieSteamSeen", null) + fun setBootMovieSteamSeen(context: Context, path: String) { prefs(context).edit().putString("bootMovieSteamSeen", path).apply() } fun bootMovieCustomName(context: Context): String? = prefs(context).getString("bootMovieCustomName", null) fun setBootMovieCustomName(context: Context, name: String?) { prefs(context).edit().apply { if (name == null) remove("bootMovieCustomName") else putString("bootMovieCustomName", name) }.apply() diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt index ff1a7aeeb8..da3e5b5063 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.session +import com.droiddeck.launcher.core.AddonPack import com.droiddeck.launcher.gpu.LinuxVulkanDriver import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager @@ -21,6 +22,8 @@ import android.os.IBinder import android.os.Handler import android.os.Looper import android.os.PowerManager +import android.hardware.display.DisplayManager +import android.view.Display import android.util.Log import com.droiddeck.launcher.R import com.droiddeck.launcher.SessionActivity @@ -56,6 +59,7 @@ class SessionService : Service() { private val components = java.util.concurrent.CopyOnWriteArrayList() private var deckBinds: List = emptyList() + private var inputSysfs: InputSysfsComponent? = null private val stopLock = Any() private var wakeLock: PowerManager.WakeLock? = null private var wifiLock: WifiManager.WifiLock? = null @@ -75,6 +79,7 @@ class SessionService : Service() { private var signInHold = false private val hasVisibleSurface get() = sessionHasVisibleSurface(activityVisible || signInHold, screenOn, xrActivityVisible) private var screenOn = true + private var sessionDisplayId = Display.DEFAULT_DISPLAY private var manualPauseRequested = false private var steamSleepToken: String? = null private var nativeSleepToken: String? = null @@ -94,8 +99,8 @@ class SessionService : Service() { private val screenReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { when (intent?.action) { - Intent.ACTION_SCREEN_OFF -> screenOn = false - Intent.ACTION_SCREEN_ON -> screenOn = true + Intent.ACTION_SCREEN_OFF -> screenOn = readScreenOn(false) + Intent.ACTION_SCREEN_ON -> screenOn = readScreenOn(true) else -> return } if (screenOn) resumeSteamSleepOnReturn() @@ -103,17 +108,49 @@ class SessionService : Service() { updateSuspendPolicy() } } + private var displayListenerRegistered = false + private val displayListener = object : DisplayManager.DisplayListener { + override fun onDisplayAdded(displayId: Int) {} + override fun onDisplayRemoved(displayId: Int) { + if (displayId != sessionDisplayId) return + sessionDisplayId = Display.DEFAULT_DISPLAY + refreshScreenOn() + } + override fun onDisplayChanged(displayId: Int) { + if (displayId == sessionDisplayId && displayId != Display.DEFAULT_DISPLAY) refreshScreenOn() + } + } + + private fun readScreenOn(interactive: Boolean? = null): Boolean { + val id = sessionDisplayId + val state = if (id == Display.DEFAULT_DISPLAY) null + else (getSystemService(Context.DISPLAY_SERVICE) as? DisplayManager)?.getDisplay(id)?.state + return sessionScreenOn(id == Display.DEFAULT_DISPLAY, + interactive ?: (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: true, state) + } + + private fun refreshScreenOn() { + val on = readScreenOn() + if (on == screenOn) return + screenOn = on + if (on) resumeSteamSleepOnReturn() + suspendAttemptFailed = false + updateSuspendPolicy() + } @Volatile private var sessionGen = 0 override fun onCreate() { super.onCreate() - val power = getSystemService(Context.POWER_SERVICE) as? PowerManager - screenOn = power?.isInteractive ?: true + screenOn = readScreenOn() registerReceiver(screenReceiver, IntentFilter().apply { addAction(Intent.ACTION_SCREEN_OFF) addAction(Intent.ACTION_SCREEN_ON) }) screenReceiverRegistered = true + (getSystemService(Context.DISPLAY_SERVICE) as? DisplayManager)?.let { + it.registerDisplayListener(displayListener, Handler(Looper.getMainLooper())) + displayListenerRegistered = true + } } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { @@ -162,12 +199,19 @@ class SessionService : Service() { ACTION_ACTIVITY_VISIBLE -> { if (!SessionState.pipActive) pipTask = false activityVisible = true + sessionDisplayId = intent.getIntExtra(EXTRA_DISPLAY_ID, sessionDisplayId) + screenOn = readScreenOn() suspendDownloadNow = false resumeSteamSleepOnReturn() suspendAttemptFailed = false updateSuspendPolicy() return START_NOT_STICKY } + ACTION_ACTIVITY_DISPLAY -> { + sessionDisplayId = intent.getIntExtra(EXTRA_DISPLAY_ID, sessionDisplayId) + refreshScreenOn() + return START_NOT_STICKY + } ACTION_ACTIVITY_HIDDEN -> { activityVisible = false suspendAttemptFailed = false @@ -231,7 +275,8 @@ class SessionService : Service() { activityVisible = true xrActivityVisible = false signInHold = false - screenOn = (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: true + sessionDisplayId = intent?.getIntExtra(EXTRA_DISPLAY_ID, Display.DEFAULT_DISPLAY) ?: Display.DEFAULT_DISPLAY + screenOn = readScreenOn() manualPauseRequested = false suspendDownloadNow = false steamDownloadMonitor.reset() @@ -294,14 +339,13 @@ class SessionService : Service() { return lines } - private fun tuDebug(linuxDriverId: String): String? { - val override = File(Environment.getExternalStorageDirectory(), TU_DEBUG_SWITCH) - .takeIf { it.isFile }?.let { FileUtils.readString(it)?.trim() } - if (!override.isNullOrEmpty()) return override - if (SessionPrefs.tuSysmem(this)) return "sysmem" - if (linuxDriverId.isEmpty()) return null + private fun tuDebugOverride(): String? = File(Environment.getExternalStorageDirectory(), TU_DEBUG_SWITCH) + .takeIf { it.isFile }?.let { FileUtils.readString(it)?.trim() }?.takeIf { it.isNotEmpty() } + + private fun sysmemDriver(linuxDriverId: String): Boolean { + if (linuxDriverId.isEmpty()) return false val name = LinuxVulkanDriverManager(this).getDriverName(linuxDriverId).lowercase() - return if (name.contains("710-720") || name.contains("710_720")) "sysmem" else null + return name.contains("710-720") || name.contains("710_720") } @@ -320,7 +364,9 @@ class SessionService : Service() { val sessionRoot = LinuxRuntime.sessionRoot(this).apply { mkdirs() } val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() } killStragglers() - SessionFiles.stage(this, root) + for (pack in listOf(AddonPack.PROOT, AddonPack.DIRECTAUDIO)) + if (!pack.await(this, { gen == sessionGen && SessionState.running })) Log.w(TAG, "${pack.name} pack unavailable") + SessionFiles.stage(this, root, startsSession = true) // Earlier sessions' reports still read the Steam logs and VAC marker this session replaces. SessionArtifacts.awaitCollections() SessionArtifacts.finishAbandoned(this) @@ -366,6 +412,7 @@ class SessionService : Service() { val controllersOn = !File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists() SessionState.deckPad = false deckBinds = emptyList() + inputSysfs = null if (controllersOn) { addControllerEnvironment(guest, fakeInputDir, sessionDir) SessionState.padBridge?.syncConnectedControllers() @@ -576,7 +623,9 @@ class SessionService : Service() { ) LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId) ?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) } - tuDebug(linuxDriverId)?.let { guest.add("TU_DEBUG=$it") } + val tuOverride = tuDebugOverride() + val tuDriver = sysmemDriver(linuxDriverId) + (tuOverride ?: "sysmem".takeIf { tuDriver || SessionPrefs.tuSysmem(this) })?.let { guest.add("TU_DEBUG=$it") } com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice()?.let { guest.add("${com.droiddeck.launcher.gpu.TpUbwcHint.ENV}=$it") } if (SessionPrefs.zinkLazy(this)) { guest.add("ZINK_DESCRIPTORS=lazy") @@ -604,8 +653,9 @@ class SessionService : Service() { if (SessionState.mode == MODE_STEAM && SessionPrefs.zramCompression(this) && com.droiddeck.launcher.core.ZramSupport.supported()) guest.add("BL_ZRAM=1") guest.add("BANNER_AUDIO_DIRECT_DECAY=0") - extraEnv().forEach { guest.add(it) } - com.droiddeck.launcher.agent.AgentEnv.beginSession(this).forEach { guest.add(it) } + val extra = extraEnv() + com.droiddeck.launcher.agent.AgentEnv.beginSession(this) + if (extra.none { it.startsWith("TU_DEBUG=") }) guest.add("$GAME_TU_DEBUG=" + (tuOverride ?: if (tuDriver) "sysmem" else "")) + extra.forEach { guest.add(it) } val clientPinned = steamHere && SessionPrefs.clientCpusOverride(this) if (clientPinned) { guest.add("BL_CLIENT_CPUS=" + CpuCores.listOrAll(SessionPrefs.clientCpus(this))) @@ -681,6 +731,7 @@ class SessionService : Service() { val padType = SessionPrefs.steamController(this) guest.add("FAKE_EVDEV_PAD_TYPE=$padType") com.droiddeck.launcher.input.FakeInputWriter.setPadType(SessionPrefs.padType(padType)) + InputSysfsComponent.padTypeChanged(SessionPrefs.padType(padType)) if (wantsTouch) com.droiddeck.launcher.input.SteamTouchDevice.prepare(fakeInputDir)?.let { guest.add("FAKE_TOUCHCTL_RING=" + it.path) } @@ -694,6 +745,9 @@ class SessionService : Service() { if (!SessionState.deckPad) guest.add("SDL_JOYSTICK_HIDAPI=0") guest.add("FAKE_EVDEV_LOG=1") guest.add("FAKE_EVDEV_LOG_FILE=" + File(sessionDir, "pad.log").path) + inputSysfs = InputSysfsComponent(fakeInputDir, File(fakeInputDir.parentFile!!.parentFile!!, "sys/input"), + File(LinuxRuntime.rootDir(this), "run/udev/data"), SessionState.deckPad, !uinput && SessionState.mode == MODE_STEAM) + .takeIf { it.prepare() } SessionState.fakeInputDir = fakeInputDir } @@ -708,6 +762,11 @@ class SessionService : Service() { val binds = ArrayList() if (controllersOn) binds.add(fakeInputDir.path + ":/dev/input") if (controllersOn) binds.addAll(deckBinds) + if (controllersOn) inputSysfs?.let { + it.attach(this) + components.add(it) + binds.addAll(it.binds()) + } val battery = BatteryComponent( File(filesDir, "session/sys/power_supply"), File(LinuxRuntime.rootDir(this), "run/vpower"), @@ -1017,7 +1076,7 @@ class SessionService : Service() { private fun resumeSession(panelVisible: Boolean = true) { if (panelVisible) activityVisible = true - screenOn = (getSystemService(Context.POWER_SERVICE) as? PowerManager)?.isInteractive ?: screenOn + screenOn = readScreenOn() manualPauseRequested = false suspendDownloadNow = false if (steamSleepToken == null && (nativeSleepToken == null || nativeSleepFallback || nativeSleepIdle)) requestSteamWake() @@ -1243,7 +1302,7 @@ class SessionService : Service() { suspendOperationPending = true SessionEvents.record(if (shouldSuspend) "session.suspend_requested" else "session.resume_requested", mapOf( "policy" to suspendPolicy, "activityVisible" to activityVisible, - "screenOn" to screenOn, "steamSleep" to (steamSleepToken != null), + "screenOn" to screenOn, "display" to sessionDisplayId, "steamSleep" to (steamSleepToken != null), "xrActivityVisible" to xrActivityVisible, "nativeSleep" to (nativeSleepToken != null), )) @@ -1507,6 +1566,10 @@ class SessionService : Service() { unregisterReceiver(screenReceiver) screenReceiverRegistered = false } + if (displayListenerRegistered) { + (getSystemService(Context.DISPLAY_SERVICE) as? DisplayManager)?.unregisterDisplayListener(displayListener) + displayListenerRegistered = false + } super.onDestroy() } @@ -1674,6 +1737,7 @@ class SessionService : Service() { private const val TAG = "SessionService" private const val TRACER_NICE = -6 private const val TU_DEBUG_SWITCH = "Download/droiddeck-tu-debug" + private const val GAME_TU_DEBUG = "DROIDDECK_GAME_TU_DEBUG" private const val LEGACY_ENV_SWITCH = "Download/droiddeck-env" private const val ENV_SWITCH_NAME = "droiddeck-env" @@ -1693,6 +1757,8 @@ class SessionService : Service() { private const val ACTION_SUSPEND_POLICY_CHANGED = "com.droiddeck.launcher.SUSPEND_POLICY_CHANGED" private const val ACTION_ACTIVITY_VISIBLE = "com.droiddeck.launcher.ACTIVITY_VISIBLE" private const val ACTION_ACTIVITY_HIDDEN = "com.droiddeck.launcher.ACTIVITY_HIDDEN" + private const val ACTION_ACTIVITY_DISPLAY = "com.droiddeck.launcher.ACTIVITY_DISPLAY" + private const val EXTRA_DISPLAY_ID = "displayId" private const val ACTION_XR_ACTIVITY_VISIBLE = "com.droiddeck.launcher.XR_ACTIVITY_VISIBLE" private const val ACTION_XR_ACTIVITY_HIDDEN = "com.droiddeck.launcher.XR_ACTIVITY_HIDDEN" private const val ACTION_SIGN_IN_HOLD = "com.droiddeck.launcher.SIGN_IN_HOLD" @@ -1729,8 +1795,10 @@ class SessionService : Service() { fun start( context: Context, mode: String = MODE_STEAM, program: String? = null, steamUi: String? = null, steamUrl: String? = null, programArgs: Array? = null, + displayId: Int = Display.DEFAULT_DISPLAY, ) { val intent = Intent(context, SessionService::class.java).putExtra(EXTRA_MODE, mode) + .putExtra(EXTRA_DISPLAY_ID, displayId) if (program != null) intent.putExtra(EXTRA_PROGRAM, program) if (programArgs != null) intent.putExtra(EXTRA_PROGRAM_ARGS, programArgs) if (steamUi != null) intent.putExtra(EXTRA_STEAM_UI, steamUi) @@ -1751,10 +1819,15 @@ class SessionService : Service() { context.startService(Intent(context, SessionService::class.java).setAction(ACTION_PIP_BEGIN)) } - fun setActivityVisible(context: Context, visible: Boolean) { + fun setActivityVisible(context: Context, visible: Boolean, displayId: Int = Display.DEFAULT_DISPLAY) { if (!SessionState.running) return val action = if (visible) ACTION_ACTIVITY_VISIBLE else ACTION_ACTIVITY_HIDDEN - context.startService(Intent(context, SessionService::class.java).setAction(action)) + context.startService(Intent(context, SessionService::class.java).setAction(action).putExtra(EXTRA_DISPLAY_ID, displayId)) + } + + fun setActivityDisplay(context: Context, displayId: Int) { + if (!SessionState.running) return + context.startService(Intent(context, SessionService::class.java).setAction(ACTION_ACTIVITY_DISPLAY).putExtra(EXTRA_DISPLAY_ID, displayId)) } fun setXrActivityVisible(context: Context, visible: Boolean) { diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt index fbe9084083..d694d67862 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt @@ -2,14 +2,22 @@ package com.droiddeck.launcher.session import android.os.Process import java.io.File +import java.io.IOException import java.util.concurrent.ExecutorService import java.util.concurrent.Executors +import java.util.concurrent.RejectedExecutionException internal class SessionSuspendController( private val sessionRoot: () -> Int, private val helperRoots: () -> List, private val suspendAudio: () -> Unit, private val resumeAudio: () -> Unit, + private val procRoot: File = File("/proc"), + private val signal: (Int, Int) -> Unit = Process::sendSignal, + private val threadSignal: (Int, Int, Int) -> Unit = { pid, tid, signal -> ThreadSignals.tgkill(pid, tid, signal) }, + private val sleep: (Long) -> Unit = Thread::sleep, + private val nowMillis: () -> Long = { System.nanoTime() / 1_000_000 }, + private val executor: ExecutorService = Executors.newSingleThreadExecutor(), ) { private enum class Role { SESSION_ROOT, SESSION_CHILD, HELPER_ROOT, HELPER_CHILD } @@ -24,96 +32,95 @@ internal class SessionSuspendController( val parent: Int, val started: Long, val state: Char, + val tracer: Int, ) - private val executor: ExecutorService = Executors.newSingleThreadExecutor() + private data class TaskIdentity(val process: ProcessRecord, val tid: Int, val started: Long) + @Volatile private var closing = false private var frozen = emptyList() fun freeze(completion: (Boolean) -> Unit) { - submit { - if (closing) { - completion(false) - return@submit - } - if (frozen.isNotEmpty()) { - val fullyFrozen = frozen.any { it.role == Role.SESSION_ROOT } && frozen.all(::isStoppedOrGone) - if (!fullyFrozen && restore(frozen)) frozen = emptyList() - completion(fullyFrozen) - return@submit - } - val records = LinkedHashMap, ProcessRecord>() - val root = sessionRoot() - if (root <= 1) { - completion(false) - return@submit - } - runAudio(suspendAudio) - val helpers = helperRoots().filter { it > 1 && it != root }.distinct() - var stablePasses = 0 + submit({ + val records = frozen.associateByTo(LinkedHashMap()) { it.pid to it.started } var complete = false - repeat(10) { pass -> - if (closing) { - restore(records.values.toList()) - runAudio(resumeAudio) - completion(false) - return@submit + var interrupted = false + try { + val root = records.values.firstOrNull { it.role == Role.SESSION_ROOT } + ?: readProcess(sessionRoot())?.takeIf { it.pid > 1 }?.let { + ProcessRecord(it.pid, it.started, Role.SESSION_ROOT) + } ?: throw IOException("Session root is unavailable") + records[root.pid to root.started] = root + runAudio(suspendAudio) + val helpers = helperRoots().filter { it > 1 && it != root.pid }.distinct() + for (helper in helpers) { + if (records.values.any { it.pid == helper && it.role == Role.HELPER_ROOT }) continue + readProcess(helper)?.let { + records[it.pid to it.started] = ProcessRecord(it.pid, it.started, Role.HELPER_ROOT) + } } - val includeRoots = pass >= 2 - addSnapshot(records, root, helpers, includeRoots) - stop(records.values.toList(), includeRoots) - Thread.sleep(if (pass == 0) 70L else 35L) - val rootCaptured = records.values.any { it.role == Role.SESSION_ROOT } - if (rootCaptured && records.isNotEmpty() && records.values.all(::isStoppedOrGone)) { - stablePasses++ - if (stablePasses >= 2) complete = true - } else { - stablePasses = 0 + val deadline = nowMillis() + FREEZE_TIMEOUT_MS + var previous: Map? = null + for (pass in 0 until FREEZE_MAX_PASSES) { + if (closing || nowMillis() >= deadline) break + try { + if (readProcess(root.pid)?.started != root.started) break + addSnapshot(records, root.pid, helpers) + if (readProcess(root.pid)?.started != root.started) break + stop(records.values.toList()) + sleep(if (pass == 0) 70L else 35L) + if (closing || nowMillis() >= deadline) break + val current = stoppedSnapshot(records.values.toList(), root) + if (current != null && current == previous) { + complete = true + break + } + previous = current + } catch (_: IOException) { + previous = null + sleep(35L) + } } - } - if (complete) { + } catch (_: InterruptedException) { + interrupted = true + Thread.interrupted() + } catch (_: Exception) { + } finally { frozen = records.values.toList() - completion(true) - } else { - val restored = restore(records.values.toList()) - runAudio(resumeAudio) - if (!restored) frozen = records.values.toList() - completion(false) + if (!complete) { + if (restoreSafely(frozen)) frozen = emptyList() + runAudio(resumeAudio) + } + if (interrupted) Thread.currentThread().interrupt() } - } + completion(complete) + }, { completion(false) }) } fun resume(completion: (Boolean) -> Unit) { - submit { + submit({ val records = frozen runAudio(resumeAudio) - val resumed = restore(records) + val resumed = restoreSafely(records) if (resumed) frozen = emptyList() completion(resumed) - } + }, { completion(false) }) } fun closeAndResume(completion: () -> Unit) { closing = true - submit { - restore(frozen) - frozen = emptyList() + submit({ + if (restoreSafely(frozen)) frozen = emptyList() completion() executor.shutdown() - } + }, completion) } - private fun submit(task: () -> Unit) { + private fun submit(task: () -> Unit, rejected: () -> Unit) { try { - executor.execute { - try { - task() - } catch (_: InterruptedException) { - Thread.currentThread().interrupt() - } - } - } catch (_: RuntimeException) { - task() + executor.execute(task) + } catch (_: RejectedExecutionException) { + rejected() } } @@ -128,23 +135,25 @@ internal class SessionSuspendController( records: MutableMap, ProcessRecord>, root: Int, helpers: List, - includeRoots: Boolean, ) { val processes = readProcesses() val byPid = processes.associateBy { it.pid } - for (process in descendants(root, processes, byPid)) { - records[process.pid to process.started] = ProcessRecord(process.pid, process.started, Role.SESSION_CHILD) + val rootRecord = records.values.first { it.role == Role.SESSION_ROOT } + if (byPid[root]?.started != rootRecord.started) throw IOException("Session root exited or changed") + val liveHelpers = helpers.filter { pid -> + records.values.any { it.pid == pid && it.role == Role.HELPER_ROOT && it.started == byPid[pid]?.started } } - for (helper in helpers) { + for (process in descendants(root, processes, byPid) + processes.filter { it.tracer == root }) { + records.putIfAbsent(process.pid to process.started, ProcessRecord(process.pid, process.started, Role.SESSION_CHILD)) + } + for (helper in liveHelpers) { for (process in descendants(helper, processes, byPid)) { - records[process.pid to process.started] = ProcessRecord(process.pid, process.started, Role.HELPER_CHILD) + records.putIfAbsent(process.pid to process.started, ProcessRecord(process.pid, process.started, Role.HELPER_CHILD)) } } - if (includeRoots) { - byPid[root]?.let { records[it.pid to it.started] = ProcessRecord(it.pid, it.started, Role.SESSION_ROOT) } - for (helper in helpers) { - byPid[helper]?.let { records[it.pid to it.started] = ProcessRecord(it.pid, it.started, Role.HELPER_ROOT) } - } + byPid[root]?.let { records[it.pid to it.started] = ProcessRecord(it.pid, it.started, Role.SESSION_ROOT) } + for (helper in liveHelpers) { + byPid[helper]?.let { records[it.pid to it.started] = ProcessRecord(it.pid, it.started, Role.HELPER_ROOT) } } } @@ -168,36 +177,84 @@ internal class SessionSuspendController( } private fun readProcesses(): List = - File("/proc").listFiles().orEmpty().mapNotNull { entry -> + (procRoot.listFiles() ?: throw IOException("Cannot enumerate processes")).mapNotNull { entry -> val pid = entry.name.toIntOrNull() ?: return@mapNotNull null - readProcess(pid) + try { readProcess(pid) } catch (_: IOException) { null } } private fun readProcess(pid: Int): ProcessInfo? { - val stat = try { - File("/proc/$pid/stat").readText() - } catch (_: Exception) { - return null - } - val close = stat.lastIndexOf(')') - if (close < 0 || close + 2 >= stat.length) return null - val fields = stat.substring(close + 2).trim().split(Regex("\\s+")) - if (fields.size < 20) return null - return try { - ProcessInfo(pid, fields[1].toInt(), fields[19].toLong(), fields[0].first()) - } catch (_: NumberFormatException) { - null + val base = File(procRoot, pid.toString()) + try { + val fields = readStat(File(base, "stat")) + val tracer = File(base, "status").useLines { lines -> + lines.firstOrNull { it.startsWith("TracerPid:") }?.substringAfter(':')?.trim()?.toIntOrNull() ?: 0 + } + return ProcessInfo(pid, fields[1].toInt(), fields[19].toLong(), fields[0].first(), tracer) + } catch (error: IOException) { + if (procRoot.list()?.contains(pid.toString()) == false) return null + throw error } } - private fun stop(records: List, includeRoots: Boolean) { - val descendants = records.filter { it.role == Role.SESSION_CHILD || it.role == Role.HELPER_CHILD } - val session = records.filter { it.role == Role.SESSION_ROOT } - val helpers = records.filter { it.role == Role.HELPER_ROOT } - for (record in descendants) send(record, SIGSTOP) - if (includeRoots) { - for (record in session) send(record, SIGSTOP) - for (record in helpers) send(record, SIGSTOP) + private fun readStat(file: File): List { + val stat = file.readText() + val close = stat.lastIndexOf(')') + if (close < 0 || close + 2 >= stat.length) throw IOException("Invalid process stat: $file") + val fields = stat.substring(close + 2).trim().split(Regex("\\s+")) + if (fields.size < 20) throw IOException("Incomplete process stat: $file") + return fields + } + + private fun stoppedSnapshot(records: List, root: ProcessRecord): Map? { + // PRoot can leave the leader stopped while native worker threads keep running. + val tasks = LinkedHashMap() + var stopped = true + for (record in records) { + val current = readProcess(record.pid) + if (current == null || current.started != record.started) { + if (record == root) throw IOException("Session root exited or changed") + continue + } + val entries = File(procRoot, "${record.pid}/task").listFiles() + ?: throw IOException("Cannot enumerate threads: ${record.pid}") + if (entries.none { it.name.toIntOrNull() != null }) throw IOException("Empty thread inventory: ${record.pid}") + var liveRoot = false + for (entry in entries) { + val tid = entry.name.toIntOrNull() ?: continue + val fields = readStat(File(entry, "stat")) + val state = fields[0].first() + if (state != 'Z' && state != 'X') liveRoot = true + if (state != 'T' && state != 't' && state != 'Z' && state != 'X') stopped = false + tasks[TaskIdentity(record, tid, fields[19].toLong())] = fields[11].toLong() + fields[12].toLong() + } + if (record == root && !liveRoot) throw IOException("Session root has no live threads") + if (readProcess(record.pid)?.started != record.started) throw IOException("Process changed during inspection") + } + return tasks.takeIf { stopped && it.isNotEmpty() } + } + + // PRoot traces every guest. A stop sent while it runs becomes a group stop that it restarts + // thread by thread; once it is stopped, each thread that takes a SIGSTOP stays parked in its + // signal-delivery stop. So the roots stop first and every guest thread gets its own SIGSTOP. + private fun stop(records: List) { + for (record in records.filter { it.role == Role.SESSION_ROOT }) send(record, SIGSTOP) + for (record in records.filter { it.role == Role.HELPER_ROOT }) send(record, SIGSTOP) + for (record in records.filter { it.role == Role.SESSION_CHILD || it.role == Role.HELPER_CHILD }) { + stopThreads(record) + } + } + + private fun stopThreads(record: ProcessRecord) { + val current = try { readProcess(record.pid) } catch (_: Exception) { return } + if (current == null || current.started != record.started) return + for (entry in File(procRoot, "${record.pid}/task").listFiles().orEmpty()) { + val tid = entry.name.toIntOrNull() ?: continue + val state = try { readStat(File(entry, "stat"))[0].first() } catch (_: IOException) { continue } + if (state == 'T' || state == 't' || state == 'Z' || state == 'X') continue + try { + threadSignal(record.pid, tid, SIGSTOP) + } catch (_: Throwable) { + } } } @@ -213,7 +270,7 @@ internal class SessionSuspendController( for (record in ordered) send(record, SIGCONT) val waiting = ordered.toMutableList() repeat(RESTORE_CHECKS) { check -> - Thread.sleep(25L) + sleep(25L) waiting.removeAll { isRunningOrGone(it) } if (waiting.isEmpty()) return true if (check % 8 == 7) for (record in waiting) send(record, SIGCONT) @@ -221,30 +278,40 @@ internal class SessionSuspendController( return false } + private fun restoreSafely(records: List): Boolean = try { + restore(records) + } catch (_: InterruptedException) { + Thread.currentThread().interrupt() + false + } catch (_: Exception) { + false + } + private fun send(record: ProcessRecord, signal: Int) { - val current = readProcess(record.pid) ?: return - if (current.started != record.started) return + val current = try { readProcess(record.pid) } catch (_: Exception) { return } + if (current == null || current.started != record.started) return try { - Process.sendSignal(record.pid, signal) + this.signal(record.pid, signal) } catch (_: Throwable) { } } - private fun isStoppedOrGone(record: ProcessRecord): Boolean { - val current = readProcess(record.pid) ?: return true - if (current.started != record.started) return true - return current.state == 'T' || current.state == 't' || current.state == 'Z' || current.state == 'X' - } - private fun isRunningOrGone(record: ProcessRecord): Boolean { - val current = readProcess(record.pid) ?: return true - if (current.started != record.started) return true - return current.state != 'T' && current.state != 't' + val current = try { readProcess(record.pid) } catch (_: Exception) { return false } + if (current == null || current.started != record.started) return true + if (current.state == 'T' || current.state == 't') return false + // A traced worker in 't' is usually PRoot handling a system call; 'T' is a job-control stop. + return File(procRoot, "${record.pid}/task").listFiles().orEmpty().none { entry -> + entry.name.toIntOrNull() != null && + try { readStat(File(entry, "stat"))[0].first() == 'T' } catch (_: IOException) { false } + } } private companion object { const val SIGSTOP = 19 const val SIGCONT = 18 const val RESTORE_CHECKS = 80 + const val FREEZE_TIMEOUT_MS = 8_000L + const val FREEZE_MAX_PASSES = 256 } } diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionVisibility.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionVisibility.kt index 33b456ecca..36f3209657 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionVisibility.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionVisibility.kt @@ -1,4 +1,10 @@ package com.droiddeck.launcher.session +import android.view.Display + internal fun sessionHasVisibleSurface(panelVisible: Boolean, screenOn: Boolean, xrVisible: Boolean): Boolean = xrVisible || (panelVisible && screenOn) + +internal fun sessionScreenOn(onDefaultDisplay: Boolean, interactive: Boolean, displayState: Int?): Boolean = + if (onDefaultDisplay || displayState == null || displayState == Display.STATE_UNKNOWN) interactive + else displayState == Display.STATE_ON || displayState == Display.STATE_VR || displayState == Display.STATE_ON_SUSPEND diff --git a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt index f5304ed1ea..78bbc89cd6 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt @@ -21,7 +21,8 @@ object SettingsReset { "noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "guestHostname", "fexPreset", "forceSsbs", "logs", "storageDiagnostics", "upscaler", "upscaleSharpness", "screenEffects", "textureAnisotropy", "textureLodBias", - "steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", + "steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds", + "bootMovieApplyNext", "bootMovieSteamSeen", "questDefaultsV1", ) diff --git a/app/src/main/java/com/droiddeck/launcher/session/SteamClientSetupFailure.kt b/app/src/main/java/com/droiddeck/launcher/session/SteamClientSetupFailure.kt new file mode 100644 index 0000000000..c0a53ca7a2 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/SteamClientSetupFailure.kt @@ -0,0 +1,28 @@ +package com.droiddeck.launcher.session + +class SteamClientSetupFailure(val curlError: String?) { + val download get() = curlError != null + + companion object { + const val MARKER = "== steam: the Steam client could not be set up" + private const val STEP = "checking the Steam client" + private const val X64_STEP = "checking the x86-64 Steam client" + private val CURL_ERROR = Regex("""curl: \(\d+\).*""") + + fun find(lines: Sequence): SteamClientSetupFailure? { + var curlError: String? = null + var found: SteamClientSetupFailure? = null + lines.forEach { line -> + when { + line.contains(STEP) || line.contains(X64_STEP) -> { + curlError = null + found = null + } + line.contains(MARKER) -> found = SteamClientSetupFailure(curlError) + else -> CURL_ERROR.find(line)?.let { curlError = it.value.trim() } + } + } + return found + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/SteamDeckRepo.kt b/app/src/main/java/com/droiddeck/launcher/session/SteamDeckRepo.kt new file mode 100644 index 0000000000..2a940a96f4 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/SteamDeckRepo.kt @@ -0,0 +1,218 @@ +package com.droiddeck.launcher.session + +import android.util.Log +import org.json.JSONObject +import java.io.File +import java.net.HttpURLConnection +import java.net.URL +import java.net.URLEncoder + +/** steamdeckrepo.com's public boot video list, the same one its website and its own manager app read. */ +object SteamDeckRepo { + private const val TAG = "SteamDeckRepo" + const val BASE = "https://steamdeckrepo.com" + + /** The site shows twelve movies a page. */ + const val PAGE_SIZE = 12 + const val MAX_DOWNLOAD_BYTES = 120L shl 20 + private const val MAX_JSON_BYTES = 1 shl 20 + private const val USER_AGENT = "DroidDeck (+https://github.com/Droid-Deck/DroidDeck)" + private const val CACHE_MS = 10 * 60 * 1000L + + enum class Sort(val key: String) { + TRENDING("trending"), DOWNLOADS("downloads-desc"), LIKES("likes-desc"), NEWEST("created_at-desc"), + } + + /** `null` is every device. */ + val DEVICES = listOf("steam_deck", "steam_machine") + + class Post( + val id: String, val title: String, val content: String, val author: String, val thumbnail: String, val video: String, + val seconds: Int, val likes: Int, val downloads: Int, val devices: List, val url: String, + ) + + sealed class Page { + class Ok(val posts: List) : Page() + object Failed : Page() + } + + /** The text of [key], empty when it is missing or JSON null, which `optString` would turn into the word "null". */ + private fun JSONObject.text(key: String): String = if (isNull(key)) "" else optString(key) + + fun parse(json: String): List? { + val array = runCatching { JSONObject(json).optJSONArray("posts") }.getOrNull() ?: return null + val out = ArrayList() + for (i in 0 until array.length()) { + val o = array.optJSONObject(i) ?: continue + val id = o.text("id") + val video = o.text("video") + if (id.isEmpty() || !video.startsWith("https://")) continue + val devices = o.optJSONArray("devices")?.let { d -> (0 until d.length()).map { d.optString(it) } }.orEmpty() + out.add( + Post( + id = id, title = o.text("title").ifBlank { id }, content = o.text("content"), + author = o.optJSONObject("user")?.text("steam_name").orEmpty(), + thumbnail = o.text("thumbnail").takeIf { it.startsWith("https://") }.orEmpty(), video = video, + seconds = o.optInt("video_duration"), likes = o.optInt("likes"), downloads = o.optInt("downloads"), + devices = devices, url = o.text("url"), + ), + ) + } + return out + } + + fun url(sort: Sort, device: String?, search: String, page: Int = 1): String { + val query = StringBuilder("sort=").append(sort.key) + if (device != null) query.append("&device=").append(URLEncoder.encode(device, "UTF-8")) + val term = search.trim() + if (term.isNotEmpty()) query.append("&search=").append(URLEncoder.encode(term, "UTF-8").replace("+", "%20")) + if (page > 1) query.append("&page=").append(page) + return "$BASE/api/posts?$query" + } + + private class Cached(val at: Long, val page: Page.Ok) + private val cache = HashMap() + + fun fetch(sort: Sort, device: String?, search: String, page: Int = 1, now: Long = System.currentTimeMillis()): Page { + val url = url(sort, device, search, page) + synchronized(cache) { cache[url]?.takeIf { now - it.at < CACHE_MS }?.let { return it.page } } + val body = get(url) ?: return Page.Failed + val posts = parse(body) ?: return Page.Failed + val result = Page.Ok(posts.take(PAGE_SIZE)) + synchronized(cache) { cache[url] = Cached(now, result) } + return result + } + + /** + * The number of the last page for a search, found by asking for pages: the site does not say how many there are, but a + * page past the end is empty and the last one is short. Null when the site cannot be reached. + */ + fun lastPage(sort: Sort, device: String?, search: String, cap: Int = 512, count: (Int) -> Int? = { p -> + (fetch(sort, device, search, p) as? Page.Ok)?.posts?.size + }): Int? { + val first = count(1) ?: return null + if (first < PAGE_SIZE) return 1 + var good = 1 + var bad = -1 + var probe = 2 + while (probe <= cap) { + val n = count(probe) ?: return null + if (n == 0) { bad = probe; break } + if (n < PAGE_SIZE) return probe + good = probe + probe *= 2 + } + if (bad < 0) return good + while (bad - good > 1) { + val mid = (good + bad) / 2 + val n = count(mid) ?: return null + if (n == 0) bad = mid else if (n < PAGE_SIZE) return mid else good = mid + } + return good + } + + /** Reads [input] to its end, or null as soon as it holds more than [limit] bytes, so a huge answer is never kept whole. */ + internal fun readLimited(input: java.io.InputStream, limit: Int): ByteArray? { + val out = java.io.ByteArrayOutputStream() + val buffer = ByteArray(16 * 1024) + while (true) { + val n = input.read(buffer) + if (n < 0) break + if (out.size() + n > limit) return null + out.write(buffer, 0, n) + } + return out.toByteArray() + } + + private fun get(url: String): String? { + var connection: HttpURLConnection? = null + return try { + connection = (URL(url).openConnection() as HttpURLConnection).apply { + connectTimeout = 15_000 + readTimeout = 20_000 + setRequestProperty("User-Agent", USER_AGENT) + setRequestProperty("Accept", "application/json") + } + if (connection.responseCode !in 200..299) null else connection.inputStream.use { readLimited(it, MAX_JSON_BYTES)?.toString(Charsets.UTF_8) } + } catch (e: Exception) { + Log.w(TAG, "request failed: ${e.javaClass.simpleName}") + null + } finally { + runCatching { connection?.disconnect() } + } + } + + /** Fetches a small picture such as a cover; null when it cannot be had. */ + fun bytes(url: String, limit: Int = 4 shl 20): ByteArray? { + if (!url.startsWith("https://")) return null + var connection: HttpURLConnection? = null + return try { + connection = (URL(url).openConnection() as HttpURLConnection).apply { + connectTimeout = 15_000 + readTimeout = 20_000 + setRequestProperty("User-Agent", USER_AGENT) + } + if (connection.responseCode !in 200..299 || connection.contentLengthLong > limit) null + else connection.inputStream.use { input -> readLimited(input, limit)?.takeIf { it.isNotEmpty() } } + } catch (e: Exception) { + null + } finally { + runCatching { connection?.disconnect() } + } + } + + /** + * Downloads a movie to [target] through the site's own download address, so the site counts it like a download from + * its website, and falls back to the video's address. True when a file was saved. + */ + fun download(post: Post, target: File, onProgress: (Int) -> Unit = {}): Boolean { + for (url in listOf("$BASE/post/download/${post.id}", post.video)) { + if (save(url, target, onProgress)) return true + } + return false + } + + private fun save(url: String, target: File, onProgress: (Int) -> Unit): Boolean { + var connection: HttpURLConnection? = null + val staged = File(target.parentFile, target.name + ".part") + return try { + target.parentFile?.mkdirs() + connection = (URL(url).openConnection() as HttpURLConnection).apply { + connectTimeout = 15_000 + readTimeout = 30_000 + instanceFollowRedirects = true + setRequestProperty("User-Agent", USER_AGENT) + } + if (connection.responseCode !in 200..299) return false + val type = connection.contentType.orEmpty().lowercase() + if (type.startsWith("text/") || type.contains("json")) return false + val total = connection.contentLengthLong + if (total > MAX_DOWNLOAD_BYTES) return false + var done = 0L + var lastPercent = -1 + connection.inputStream.use { input -> + staged.outputStream().use { output -> + val buffer = ByteArray(64 * 1024) + while (true) { + val n = input.read(buffer) + if (n < 0) break + done += n + if (done > MAX_DOWNLOAD_BYTES) return false + output.write(buffer, 0, n) + if (total > 0) { + val percent = (done * 100 / total).toInt() + if (percent != lastPercent) { lastPercent = percent; onProgress(percent) } + } + } + } + } + done > 0 && (total <= 0 || done == total) && staged.renameTo(target) + } catch (e: Exception) { + Log.w(TAG, "download failed: ${e.javaClass.simpleName}") + false + } finally { + runCatching { connection?.disconnect() } + staged.delete() + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/ThreadSignals.kt b/app/src/main/java/com/droiddeck/launcher/session/ThreadSignals.kt new file mode 100644 index 0000000000..e3323ce951 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/ThreadSignals.kt @@ -0,0 +1,9 @@ +package com.droiddeck.launcher.session + +internal object ThreadSignals { + init { + System.loadLibrary("sdnative") + } + + @JvmStatic external fun tgkill(tgid: Int, tid: Int, signal: Int): Int +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt b/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt index be1b29ed05..bf9d5f6dc9 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/LoginFlows.kt @@ -23,6 +23,14 @@ internal object LoginFlows { override val userAgent: String get() = GogAuth.GALAXY_UA override fun isRedirect(url: String): Boolean = url.startsWith(GogAuth.REDIRECT_PREFIX) + override fun forgetSignIn(done: () -> Unit) { + runCatching { WebCookies.expire(GogAuth.SIGN_IN_URLS, GogAuth.COOKIE_DOMAIN, listOf("/")) { done() } } + .onFailure { + Log.w(TAG, "gog: could not clear the previous web sign-in: ${it.javaClass.simpleName}") + done() + } + } + override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? { val fragment = Uri.parse(url).fragment ?: return activity.getString(com.droiddeck.launcher.R.string.stores_login_error_verification) val frag = Uri.parse("x://x?$fragment") diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt index 2416358432..1b5c6ccdd7 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreLoginActivity.kt @@ -5,6 +5,7 @@ import android.content.res.Configuration import android.graphics.Color import android.net.Uri import android.net.http.SslError +import android.os.Build import android.os.Bundle import android.os.Message import android.util.Log @@ -18,6 +19,7 @@ import android.webkit.WebChromeClient import android.webkit.WebResourceError import android.webkit.WebResourceRequest import android.webkit.WebResourceResponse +import android.webkit.WebSettings import android.webkit.WebView import android.webkit.WebViewClient import android.widget.Button @@ -38,8 +40,12 @@ class StoreLoginActivity : ComponentActivity() { const val EXTRA_STORE = "store" const val EXTRA_CLIENT_URL = "client_url" private const val KEY_STATE = "oauth_state" + private const val KEY_SIGN_IN_CLEARED = "sign_in_cleared" @Volatile internal var floodColor: Int? = null - internal const val CHROME_UA = "Mozilla/5.0 (Linux; Android 14; SM-S918B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.6533.103 Mobile Safari/537.36" + internal fun chromeUserAgent(webView: String?): String = + webView?.replace(Regex(" Build/[^;)]*"), "")?.replace("; wv)", ")")?.replace(" Version/4.0", "") + ?.takeIf { "Chrome/" in it } + ?: "Mozilla/5.0 (Linux; Android ${Build.VERSION.RELEASE}; ${Build.MODEL}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.6533.103 Mobile Safari/537.36" fun generateState(): String { val bytes = ByteArray(24) @@ -54,6 +60,7 @@ class StoreLoginActivity : ComponentActivity() { fun isRedirect(url: String): Boolean fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? val readsPage: Boolean get() = false + fun forgetSignIn(done: () -> Unit) = done() } private var store: Store? = null @@ -74,6 +81,8 @@ class StoreLoginActivity : ComponentActivity() { private var oauthState: String? = null private val captured = AtomicBoolean(false) private var flooded = false + private val chromeUa by lazy { chromeUserAgent(runCatching { WebSettings.getDefaultUserAgent(this) }.getOrNull()) } + private var signInCleared = false private fun dp(value: Int): Int = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, value.toFloat(), resources.displayMetrics).toInt() @@ -109,12 +118,18 @@ class StoreLoginActivity : ComponentActivity() { } } }) - webView.loadUrl(flow!!.startUrl) + val start = flow!!.startUrl + signInCleared = savedInstanceState?.getBoolean(KEY_SIGN_IN_CLEARED) == true + if (signInCleared) webView.loadUrl(start) + else flow!!.forgetSignIn { + signInCleared = true + if (!isDestroyed) webView.loadUrl(start) + } } private fun newFlow(state: String): Flow? { val url = clientUrl - if (url != null) return com.droiddeck.launcher.stores.epic.EpicClient.loginFlow(url) + if (url != null) return com.droiddeck.launcher.stores.epic.EpicClient.loginFlow(url, chromeUa) return store?.let { LoginFlows.forStore(it, state) } } @@ -225,7 +240,7 @@ class StoreLoginActivity : ComponentActivity() { override fun onCreateWindow(view: WebView?, isDialog: Boolean, isUserGesture: Boolean, resultMsg: Message?): Boolean { if (resultMsg == null) return false dismissPopup() - val child = newWebView(CHROME_UA, isPopup = true) + val child = newWebView(chromeUa, isPopup = true) popupWebView = child popupHost.addView(child, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) popupHost.visibility = View.VISIBLE @@ -255,6 +270,8 @@ class StoreLoginActivity : ComponentActivity() { } private inner class Client(private val isPopup: Boolean) : WebViewClient() { + private var mainFrameUrl: String? = null + override fun onPageStarted(view: WebView?, url: String?, favicon: android.graphics.Bitmap?) { Log.d(TAG, "page[popup=$isPopup]: ${StoreLog.redactUrl(url)}") if (url != null && view != null && flow?.isRedirect(url) == true && flow?.readsPage != true) complete(view, url) @@ -277,10 +294,14 @@ class StoreLoginActivity : ComponentActivity() { override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) { handler?.cancel() - showError(getString(R.string.stores_login_error_ssl)) + val url = error?.url + if (url == null || url == view?.url || url == mainFrameUrl) showError(getString(R.string.stores_login_error_ssl)) } - override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean = route(view, request.url) + override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean { + if (request.isForMainFrame) mainFrameUrl = request.url.toString() + return route(view, request.url) + } @Suppress("DEPRECATION") override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean = route(view, Uri.parse(url)) @@ -291,8 +312,8 @@ class StoreLoginActivity : ComponentActivity() { if (f.isRedirect(url) && !f.readsPage) { complete(view, url); return true } if (!isPopup && store == Store.GOG) { if (GogAuth.isGogHost(uri.host) && view.settings.userAgentString != f.userAgent) { view.settings.userAgentString = f.userAgent; return false } - if (GogAuth.isIdentityProviderHost(uri.host) && view.settings.userAgentString != CHROME_UA) { - view.settings.userAgentString = CHROME_UA + if (GogAuth.isIdentityProviderHost(uri.host) && view.settings.userAgentString != chromeUa) { + view.settings.userAgentString = chromeUa CookieManager.getInstance().setAcceptThirdPartyCookies(view, true) view.loadUrl(url) return true @@ -330,6 +351,7 @@ class StoreLoginActivity : ComponentActivity() { override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) oauthState?.let { outState.putString(KEY_STATE, it) } + outState.putBoolean(KEY_SIGN_IN_CLEARED, signInCleared) } override fun onStart() { diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreTabs.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreTabs.kt new file mode 100644 index 0000000000..975626168d --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreTabs.kt @@ -0,0 +1,9 @@ +package com.droiddeck.launcher.stores + +data class StoreTab(val store: Store, val shown: Boolean) + +fun arrangeStoreTabs(order: List, hidden: Set): List { + val known = Store.entries.associateBy { it.id } + val listed = order.mapNotNull { known[it] }.distinct() + return (listed + Store.entries.filterNot { it in listed }).map { StoreTab(it, it.id !in hidden) } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/WebCookies.kt b/app/src/main/java/com/droiddeck/launcher/stores/WebCookies.kt new file mode 100644 index 0000000000..b44a274c50 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/WebCookies.kt @@ -0,0 +1,34 @@ +package com.droiddeck.launcher.stores + +import android.net.Uri +import android.webkit.CookieManager + +internal object WebCookies { + fun expired(header: String?, domain: String, paths: List, host: String? = null): List { + val domains = listOfNotNull(domain, host?.takeIf { it.endsWith(domain) }) + return header.orEmpty().split(';').map { it.substringBefore('=').trim() }.filter { it.isNotEmpty() }.distinct() + .flatMap { name -> + paths.flatMap { path -> + listOf("$name=; Max-Age=0; Path=$path; Secure") + domains.map { "$name=; Max-Age=0; Path=$path; Secure; Domain=$it" } + } + } + } + + fun expire(urls: List, domain: String, paths: List, done: (Int) -> Unit) { + val cookies = CookieManager.getInstance() + val lines = urls.flatMap { url -> expired(cookies.getCookie(url), domain, paths, Uri.parse(url).host).map { url to it } } + if (lines.isEmpty()) { + done(0) + return + } + var left = lines.size + for ((url, line) in lines) { + cookies.setCookie(url, line) { + if (--left == 0) { + cookies.flush() + done(lines.size) + } + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicClient.kt b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicClient.kt index a1bad46229..7f0e86b14b 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicClient.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/epic/EpicClient.kt @@ -21,6 +21,7 @@ import com.droiddeck.launcher.stores.StoreInstallRoot import com.droiddeck.launcher.stores.StoreLog import com.droiddeck.launcher.stores.StoreLoginActivity import com.droiddeck.launcher.stores.StoresState +import com.droiddeck.launcher.stores.WebCookies import com.droiddeck.launcher.stores.download.DownloadEntry import com.droiddeck.launcher.stores.download.DownloadQueue import com.droiddeck.launcher.stores.SteamLiveShortcuts @@ -108,28 +109,15 @@ object EpicClient { fun forgetWebSignIn() { android.os.Handler(android.os.Looper.getMainLooper()).post { runCatching { - val cookies = android.webkit.CookieManager.getInstance() - var cleared = 0 - for (url in COOKIE_URLS) { - val lines = expiredCookies(cookies.getCookie(url), Uri.parse(url).host) - for (line in lines) cookies.setCookie(url, line) - cleared += lines.size + WebCookies.expire(COOKIE_URLS, COOKIE_DOMAIN, COOKIE_PATHS) { cleared -> + Log.i(TAG, "cleared the Epic web sign-in ($cleared cookie lines)") } - cookies.flush() - Log.i(TAG, "cleared the Epic web sign-in ($cleared cookie lines)") }.onFailure { Log.w(TAG, "could not clear the Epic web sign-in: ${it.javaClass.simpleName}") } } } - internal fun expiredCookies(header: String?, host: String? = null): List { - val domains = listOfNotNull(COOKIE_DOMAIN, host?.takeIf { it.endsWith(COOKIE_DOMAIN) }) - return header.orEmpty().split(';').map { it.substringBefore('=').trim() }.filter { it.isNotEmpty() }.distinct() - .flatMap { name -> - COOKIE_PATHS.flatMap { path -> - listOf("$name=; Max-Age=0; Path=$path; Secure") + domains.map { "$name=; Max-Age=0; Path=$path; Secure; Domain=$it" } - } - } - } + internal fun expiredCookies(header: String?, host: String? = null): List = + WebCookies.expired(header, COOKIE_DOMAIN, COOKIE_PATHS, host) fun read(context: Context): Status { val app = context.applicationContext @@ -404,10 +392,10 @@ object EpicClient { } } - internal fun loginFlow(url: String): StoreLoginActivity.Flow? { + internal fun loginFlow(url: String, browserAgent: String): StoreLoginActivity.Flow? { val redirect = redirectOf(url) ?: return null val agent = runCatching { EpicNative.call("auth.config")?.optString("webViewUserAgent") }.getOrNull()?.ifEmpty { null } - return ClientLogin(url, redirect, agent ?: StoreLoginActivity.CHROME_UA) + return ClientLogin(url, redirect, agent ?: browserAgent) } private class ClientLogin( diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogAuth.kt b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogAuth.kt index 2de0880bd1..8e58fab033 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogAuth.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogAuth.kt @@ -20,6 +20,8 @@ object GogAuth { "&redirect_uri=https%3A%2F%2Fembed.gog.com%2Fon_login_success%3Forigin%3Dclient&response_type=token&layout=client2" const val REDIRECT_PREFIX = "https://embed.gog.com/on_login_success" const val GALAXY_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) GOG Galaxy/2.0" + const val COOKIE_DOMAIN = ".gog.com" + val SIGN_IN_URLS = listOf("https://login.gog.com/", "https://auth.gog.com/") fun authUrl(state: String): String = "$AUTH_URL&state=${Uri.encode(state)}" diff --git a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogComet.kt b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogComet.kt index 6241778218..6bc1980f2a 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/gog/GogComet.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/gog/GogComet.kt @@ -6,6 +6,7 @@ import android.util.Log import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue +import com.droiddeck.launcher.core.AddonPack import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.session.SessionEvents import com.droiddeck.launcher.session.SessionPrefs @@ -24,7 +25,8 @@ import java.util.concurrent.TimeUnit object GogComet { private const val TAG = "GogComet" - private const val BIN = "/usr/local/lib/droiddeck-comet/comet" + private const val DIR = "/usr/local/lib/droiddeck-comet" + private const val BIN = "$DIR/comet" private val lock = Any() @Volatile private var process: Process? = null private var pid = -1 @@ -41,7 +43,27 @@ object GogComet { fun setEnabled(context: Context, on: Boolean) { GogPrefs.get(context).edit().putBoolean("achievements", on).apply() + if (on) AddonPack.COMET.ensure(context) + } + private fun stage(context: Context): Boolean { + if (!AddonPack.COMET.installed(context)) { + AddonPack.COMET.ensure(context) + return false + } + val pack = AddonPack.COMET.dir(context) + val root = File(LinuxRuntime.rootDir(context), DIR.removePrefix("/")) + val packaged = File(pack, "version").readText() + if (runCatching { File(root, "version").readText() }.getOrNull() == packaged) return true + root.mkdirs() + pack.listFiles().orEmpty().filter { it.isFile && it.name != "version" && it.name != AddonPack.COMPLETE }.forEach { source -> + val staged = File(root, source.name + ".staged") + source.inputStream().use { input -> staged.outputStream().use { input.copyTo(it) } } + staged.setExecutable(true, false) + check(staged.renameTo(File(root, source.name))) + } + File(root, "version").writeText(packaged) + return true } fun begin() = synchronized(lock) { @@ -113,7 +135,8 @@ object GogComet { return JSONObject().put("ok", true).put("ready", true).put("reason", "ready") } stopLocked() - if (!File(LinuxRuntime.rootDir(context), BIN.removePrefix("/")).isFile) return reply(false, "not-installed") + if (!runCatching { stage(context) }.onFailure { Log.w(TAG, "staging failed", it) }.getOrDefault(false) || + !File(LinuxRuntime.rootDir(context), BIN.removePrefix("/")).isFile) return reply(false, "not-installed") val data = File(context.filesDir, "gog-achievements").apply { mkdirs() } val ready = CountDownLatch(1) val command = LinuxRuntime.command(context, null, null, Environment.getExternalStorageDirectory(), diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxBackend.kt index c8f1d27d14..24d7ff622b 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxBackend.kt @@ -54,8 +54,12 @@ object XboxBackend : StoreBackend { } } if (cached != null && !cached.needsRefresh(force)) return@Thread - val licenses = XboxCatalog.access(Xodus.run(app, listOf("library", "--json", "--market", market)), account, market) - val games = XboxCatalog.products(licenses.keys.toList(), licenses, market).sortedBy { it.title.lowercase() } + val response = Xodus.run(app, listOf("library", "--json", "--market", market)) + val licenses = XboxCatalog.access(response, account, market, report = { StoresState.logLine("Xbox: $it") }) + val products = XboxCatalog.rawProducts(licenses.keys.toList(), market) + val games = products.mapNotNull { XboxCatalog.product(it, licenses) }.sortedBy { it.title.lowercase() } + StoresState.logLine("Xbox: library catalog requested=${licenses.size} returned=${products.size} supported=${games.size} " + + "filtered=${products.size - games.size} backend-skipped=${response.optInt("skippedEntitlements")}") synchronized(this) { if (current != generation || StoreAccounts.signedInAs(app, store) != account) return@Thread access = licenses diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCatalog.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCatalog.kt index 276919ec33..fa7a6b5faa 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCatalog.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCatalog.kt @@ -11,10 +11,25 @@ internal object XboxCatalog { private val productId = Regex("[A-Z0-9]{12}") private val plans = setOf("CFQ7TTC0KGQ8", "CFQ7TTC0KHS0", "CFQ7TTC0P85B", "CFQ7TTC0K5DJ", "CFQ7TTC0K6L8", "CFQ7TTC10QFD") - fun access(json: JSONObject, account: String, market: String, now: Instant = Instant.now()): Map { + fun access(json: JSONObject, account: String, market: String, now: Instant = Instant.now(), report: (String) -> Unit = {}): Map { require(json.getInt("schema") == 1 && json.getString("account") == account && json.getString("market") == market) val age = java.time.Duration.between(timestamp(json.getString("checkedAt")), now).seconds require(age in -60..299) + val memberships: Set? = if (json.has("subscriptions")) { + val subscriptions = json.getJSONArray("subscriptions") + require(subscriptions.length() <= plans.size) + val seen = HashSet() + buildSet { + for (i in 0 until subscriptions.length()) { + val row = subscriptions.getJSONObject(i) + val id = row.getString("productId") + require(id in plans && seen.add(id)) + val status = row.getString("status") + val expiry = timestamp(row.getString("endDate")) + if (status == "Active" && expiry.isAfter(now)) add(id) + } + } + } else null val array = json.getJSONArray("entitlements") require(array.length() <= 10_000) val rows = LinkedHashMap() @@ -30,6 +45,7 @@ internal object XboxCatalog { } fun active(row: JSONObject) = row.getString("status") == "Active" && !row.getBoolean("isTrial") && !row.getBoolean("special") && row.getString("sharingSource") == "None" && timestamp(row.getString("endDate")).isAfter(now) + fun activePlan(id: String) = rows[id]?.let(::active) ?: (id in memberships.orEmpty()) fun kind(id: String, visited: Set = emptySet()): String? { if (id in blocked || id in visited || visited.size >= 16) return null val row = rows[id] ?: return null @@ -37,10 +53,14 @@ internal object XboxCatalog { val parent = row.optString("satisfiedByProductId").takeUnless { it.isBlank() || it == "null" } if (parent == null) return if (id in plans) null else "owned" if (parent in blocked) return null - if (parent in plans) return if (rows[parent]?.let(::active) == true) "gamepass" else null + if (parent in plans) return if (activePlan(parent)) "gamepass" else null return kind(parent, visited + id) } - return rows.keys.mapNotNull { id -> kind(id)?.let { id to it } }.toMap() + val result = rows.keys.mapNotNull { id -> kind(id)?.let { id to it } }.toMap() + val missingPlan = rows.values.count { row -> row.optString("satisfiedByProductId").let { it in plans && !activePlan(it) } } + report("library entitlements=${array.length()} invalid=${array.length() - rows.size} restricted=${rows.values.count { !active(it) }} " + + "unverified-plan=$missingPlan owned=${result.values.count { it == "owned" }} gamepass=${result.values.count { it == "gamepass" }}") + return result } private fun timestamp(value: String): Instant = java.time.OffsetDateTime.parse(value).toInstant() diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/Xodus.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/Xodus.kt index 1029140b30..8eb237d02c 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/Xodus.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/Xodus.kt @@ -2,6 +2,7 @@ package com.droiddeck.launcher.stores.xbox import android.content.Context import android.os.Environment +import com.droiddeck.launcher.core.AddonPack import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.session.SessionPrefs import org.json.JSONObject @@ -42,28 +43,30 @@ internal object Xodus { } } - @Synchronized private fun stage(app: Context) { + @Synchronized private fun stage(app: Context): File { + check(AddonPack.XBOX.await(app)) { "Couldn't download the Xbox components. Check your connection and try again." } + val pack = AddonPack.XBOX.dir(app) val root = File(LinuxRuntime.rootDir(app), DIR.removePrefix("/")) - val packaged = app.assets.open("linuxfs$DIR/version").bufferedReader().use { it.readText() } - if (runCatching { File(root, "version").readText() }.getOrNull() == packaged) return - fun copy(relative: String) { - val entries = app.assets.list("linuxfs$DIR/$relative").orEmpty() - if (entries.isNotEmpty()) { entries.forEach { copy(if (relative.isEmpty()) it else "$relative/$it") }; return } - if (relative == "version") return + val packaged = File(pack, "version").readText() + if (runCatching { File(root, "version").readText() }.getOrNull() == packaged) return pack + fun copy(source: File, relative: String) { + if (source.isDirectory) { source.listFiles().orEmpty().forEach { copy(it, if (relative.isEmpty()) it.name else "$relative/${it.name}") }; return } + if (relative == "version" || relative == AddonPack.COMPLETE) return val file = File(root, relative) file.parentFile?.mkdirs() val staged = File(file.path + ".staged") - app.assets.open("linuxfs$DIR/$relative").use { input -> staged.outputStream().use { input.copyTo(it) } } + source.inputStream().use { input -> staged.outputStream().use { input.copyTo(it) } } staged.setExecutable(true, false) check(staged.renameTo(file)) } - copy("") + copy(pack, "") File(root, "version").writeText(packaged) + return pack } fun start(app: Context, args: List, service: Boolean = false, runtimeDirectory: File? = null, launchDirectory: File? = null, credentialGeneration: String? = null): Child { check(LinuxRuntime.isInstalled(app)) { "Install the Linux runtime before using Xbox." } - stage(app) + val pack = stage(app) val binary = "$DIR/${if (service) "xodus-service" else "xodus-cli"}" check(File(LinuxRuntime.rootDir(app), binary.removePrefix("/")).isFile) { "The Xbox backend is missing. Update the Linux runtime." } val credentials = XboxCredentials(app, credentialGeneration) @@ -83,7 +86,7 @@ internal object Xodus { LinuxRuntime.prootLibraryPath(app).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) } } val digest = java.security.MessageDigest.getInstance("SHA-256") - app.assets.open("linuxfs$binary").use { input -> + File(pack, binary.removePrefix("$DIR/")).inputStream().use { input -> val buffer = ByteArray(65536) while (true) { val n = input.read(buffer); if (n < 0) break; digest.update(buffer, 0, n) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt index bc9618c965..ccd7fd05e3 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AddAppDialog.kt @@ -305,6 +305,7 @@ internal fun AppDialog( modifier: Modifier = Modifier, maxWidth: Dp? = null, width: Dp? = null, fitContent: Boolean = false, back: (() -> Unit)? = null, + scrollable: Boolean = true, content: @Composable ColumnScope.() -> Unit, ) { val pal = LocalPalette.current @@ -342,7 +343,7 @@ internal fun AppDialog( .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) {} .controllerBack(back ?: close) .then(modifier) - .verticalScroll(rememberScrollState()) + .then(if (scrollable) Modifier.verticalScroll(rememberScrollState()) else Modifier) .padding(horizontal = 18.dp, vertical = 16.dp), content = content, ) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BootMovieSection.kt b/app/src/main/java/com/droiddeck/launcher/ui/BootMovieSection.kt new file mode 100644 index 0000000000..3878d274b6 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/BootMovieSection.kt @@ -0,0 +1,695 @@ +package com.droiddeck.launcher.ui + +import android.widget.Toast +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.hoverable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.aspectRatio +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.horizontalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.runtime.mutableStateMapOf +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.contentDescription +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import android.graphics.SurfaceTexture +import android.media.MediaPlayer +import android.net.Uri +import android.view.Surface +import android.view.TextureView +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.lazy.itemsIndexed +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.filled.PlayArrow +import androidx.compose.material.icons.filled.Search +import androidx.compose.material3.Icon +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.input.InputMode +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalInputModeManager +import androidx.compose.ui.viewinterop.AndroidView +import coil.compose.AsyncImage +import com.droiddeck.launcher.R +import com.droiddeck.launcher.session.BootMovie +import com.droiddeck.launcher.session.BootMovieLibrary +import com.droiddeck.launcher.session.BootMovieReport +import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.session.SteamDeckRepo +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File + +private enum class MovieTab { INSTALLED, IMPORT, REPO, SOUND } + +/** Downloads run here rather than in a tab, so switching tabs or closing the settings does not cancel one halfway. */ +private val installScope = CoroutineScope(SupervisorJob() + Dispatchers.Main) + +/** The downloads under way, by post id and percent; kept here so they are still known when the tab or the settings come back. */ +private val installProgress = mutableStateMapOf() + +/** What the movie list looks like right now: every movie and the one Steam will play. */ +private class MovieSnapshot(val entries: List, val selected: String) + +/** The movie list, read again every couple of seconds so a movie picked, added or removed inside Steam shows up here too. */ +@Composable +private fun rememberMovies(refresh: Int, onSelectionChanged: () -> Unit): MovieSnapshot? { + val app = LocalContext.current.applicationContext + var snapshot by remember { mutableStateOf(null) } + val changed by androidx.compose.runtime.rememberUpdatedState(onSelectionChanged) + LaunchedEffect(refresh) { + while (true) { + val before = snapshot?.selected + snapshot = withContext(Dispatchers.IO) { + BootMovie.syncFromSteam(app) + MovieSnapshot(BootMovieLibrary.list(app), BootMovie.choice(app)) + } + if (before != null && before != snapshot?.selected) changed() + delay(2_000) + } + } + return snapshot +} + +@Composable +private fun TabChip(label: String, selected: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) { + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val shape = RoundedCornerShape(8.dp) + Box( + contentAlignment = Alignment.Center, + modifier = modifier.clip(shape) + .background(if (selected) pal.signal.copy(alpha = 0.14f) else Color.White.copy(alpha = 0.03f)) + .border(if (selected) 2.dp else 1.dp, if (selected) pal.signal else pal.line, shape) + .glideBorder(hot, shape, pal.signal) + .hoverable(src) + .clickable(interactionSource = src, indication = androidx.compose.foundation.LocalIndication.current, role = Role.Tab, onClick = onClick) + .controllerConfirm(onClick = onClick) + .semantics { contentDescription = label; this.selected = selected } + .padding(horizontal = 10.dp, vertical = 8.dp), + ) { + Text(label, fontSize = 12.sp, fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Normal, + color = MaterialTheme.colorScheme.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + } +} + +/** The "Boot movie" settings group: Installed movies, Import your own movies, SteamDeckRepo and Sound. */ +@Composable +internal fun BootMovieGroup(s: ModeSettings, a: ModeSettingsActions, host: MenuHost) { + var tab by rememberSaveable { mutableStateOf(MovieTab.INSTALLED) } + SettingsGroup(stringResource(R.string.boot_movie)) { + Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 10.dp)) { + TabChip(stringResource(R.string.boot_movie_tab_installed), tab == MovieTab.INSTALLED, Modifier.weight(1f)) { tab = MovieTab.INSTALLED } + TabChip(stringResource(R.string.boot_movie_tab_import), tab == MovieTab.IMPORT, Modifier.weight(1f)) { tab = MovieTab.IMPORT } + TabChip(stringResource(R.string.boot_movie_tab_repo), tab == MovieTab.REPO, Modifier.weight(1f)) { tab = MovieTab.REPO } + TabChip(stringResource(R.string.boot_movie_tab_sound), tab == MovieTab.SOUND, Modifier.weight(1f)) { tab = MovieTab.SOUND } + } + when (tab) { + MovieTab.INSTALLED -> InstalledTab(a) + MovieTab.IMPORT -> ImportTab(s, a) + MovieTab.REPO -> RepoTab(a) + MovieTab.SOUND -> SoundTab(s, a, host) + } + } +} + +@Composable +private fun InstalledTab(a: ModeSettingsActions) { + var browsing by remember { mutableStateOf(false) } + val snapshot = rememberMovies(0, a.onBootMovieChanged) + val current = snapshot?.let { snap -> snap.entries.firstOrNull { it.id == snap.selected }?.title } + val hint = current ?: stringResource(R.string.common_working) + SettingsRow(stringResource(R.string.boot_movie_installed), hint) { + SecondaryButton(stringResource(R.string.boot_movie_browse), onClick = { browsing = true }) + } + Text( + stringResource(R.string.boot_movie_note), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 14.dp).padding(bottom = 12.dp), + ) + val app = LocalContext.current.applicationContext + val scope = rememberCoroutineScope() + var saving by remember { mutableStateOf(false) } + // The report is for bug reports, so it shows only while Debugging tools is on (read each time this tab opens). + val debugging = remember { com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(app) } + if (debugging) { + SettingsRow(stringResource(R.string.boot_movie_report), stringResource(R.string.boot_movie_report_hint)) { + SecondaryButton(stringResource(R.string.boot_movie_report_save), enabled = !saving, onClick = { + saving = true + scope.launch { + val file = withContext(Dispatchers.IO) { BootMovieReport.write(app) } + saving = false + Toast.makeText( + app, + file?.let { app.getString(R.string.boot_movie_report_saved, it.path) } ?: app.getString(R.string.boot_movie_report_failed), + Toast.LENGTH_LONG, + ).show() + } + }) + } + } + if (browsing) InstalledMoviesDialog(a) { browsing = false } +} + +@Composable +private fun MovieCover(entry: BootMovieLibrary.Entry, modifier: Modifier = Modifier) { + val app = LocalContext.current.applicationContext + val cover by androidx.compose.runtime.produceState(null, entry.id, entry.title) { + value = withContext(Dispatchers.IO) { BootMovieLibrary.cover(app, entry) } + } + Box(modifier.aspectRatio(16f / 9f).clip(RoundedCornerShape(8.dp)).background(Color(0xFF0E1218))) { + cover?.let { AsyncImage(model = it, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize()) } + } +} + +@Composable +private fun movieSourceLabel(source: String): String = stringResource( + when (source) { + BootMovieLibrary.SOURCE_DROIDDECK -> R.string.boot_movie_source_droiddeck + BootMovieLibrary.SOURCE_REPO -> R.string.boot_movie_source_repo + BootMovieLibrary.SOURCE_IMPORT -> R.string.boot_movie_source_import + BootMovieLibrary.SOURCE_POINTSHOP -> R.string.boot_movie_source_pointshop + else -> R.string.boot_movie_source_steam + }, +) + +/** The installed movies as a list with covers; the one Steam plays is highlighted, and the list follows changes made in Steam. */ +@Composable +private fun InstalledMoviesDialog(a: ModeSettingsActions, onDismiss: () -> Unit) { + val app = LocalContext.current.applicationContext + val scope = rememberCoroutineScope() + val shown = rememberShown(onDismiss) + val close = { shown.targetState = false } + var refresh by remember { mutableIntStateOf(0) } + val snapshot = rememberMovies(refresh, a.onBootMovieChanged) + var picked by remember { mutableStateOf(null) } + var removing by remember { mutableStateOf(null) } + var filter by rememberSaveable { mutableStateOf(null) } + val selected = picked ?: snapshot?.selected + LaunchedEffect(snapshot?.selected) { picked = null } + removing?.let { entry -> + RemoveMovieDialog( + entry, + onConfirm = { + removing = null + scope.launch { + withContext(Dispatchers.IO) { BootMovieLibrary.remove(app, entry.id) } + a.onBootMovieChanged() + refresh++ + } + }, + onDismiss = { removing = null }, + ) + } + val firstRow = remember { FocusRequester() } + val inputMode = LocalInputModeManager.current + LaunchedEffect(snapshot != null, filter) { + if (snapshot != null && inputMode.inputMode == InputMode.Keyboard) focusSoon { firstRow } + } + AppDialog(shown, close, "boot-movies", wide = false, scrollable = false) { + val filters = listOf( + null to stringResource(R.string.store_all), + BootMovieLibrary.SOURCE_DROIDDECK to movieSourceLabel(BootMovieLibrary.SOURCE_DROIDDECK), + BootMovieLibrary.SOURCE_STEAM to movieSourceLabel(BootMovieLibrary.SOURCE_STEAM), + BootMovieLibrary.SOURCE_POINTSHOP to movieSourceLabel(BootMovieLibrary.SOURCE_POINTSHOP), + BootMovieLibrary.SOURCE_REPO to movieSourceLabel(BootMovieLibrary.SOURCE_REPO), + BootMovieLibrary.SOURCE_IMPORT to movieSourceLabel(BootMovieLibrary.SOURCE_IMPORT), + ) + var filterOpen by remember { mutableStateOf(false) } + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp), + ) { + Text( + stringResource(R.string.boot_movie_installed), fontSize = 15.sp, color = MaterialTheme.colorScheme.onBackground, + maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f), + ) + Box { + androidx.compose.runtime.CompositionLocalProvider(LocalChipMinWidth provides 100.dp) { + ValueChip(filters.first { it.first == filter }.second, filterOpen) { filterOpen = !filterOpen } + } + AnchoredMenu(filterOpen, onDismiss = { filterOpen = false }, compact = true) { firstItemFocus -> + filters.forEachIndexed { index, (source, label) -> + MenuItem(label, checked = filter == source, focusRequester = if (index == 0) firstItemFocus else null) { + filter = source + filterOpen = false + } + } + } + } + SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = MaterialTheme.colorScheme.error, onClick = close) + } + LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().weight(1f, fill = false)) { + itemsIndexed(snapshot?.entries.orEmpty().filter { filter == null || it.source == filter }, key = { _, entry -> entry.id }) { index, entry -> + ListRow(accent = entry.id == selected, tall = true, focus = if (index == 0) firstRow else null, onClick = { picked = entry.id; a.onBootMovie(entry.id) }) { + MovieCover(entry, Modifier.size(width = 96.dp, height = 54.dp)) + Column(Modifier.weight(1f)) { + Text(entry.title, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground, + maxLines = 2, overflow = TextOverflow.Ellipsis) + Text(movieSourceLabel(entry.source), fontSize = 12.sp, color = if (entry.id == selected) LocalPalette.current.signal else MaterialTheme.colorScheme.onSurfaceVariant) + } + if (entry.removable) SmallIconButton(Icons.Filled.Close, stringResource(R.string.boot_movie_remove), MaterialTheme.colorScheme.error) { + removing = entry + } + } + } + } + } +} + +@Composable +private fun RemoveMovieDialog(entry: BootMovieLibrary.Entry, onConfirm: () -> Unit, onDismiss: () -> Unit) { + androidx.compose.material3.AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.boot_movie_remove_confirm, entry.title)) }, + text = { Text(stringResource(R.string.boot_movie_remove_confirm_body)) }, + confirmButton = { androidx.compose.material3.TextButton(onClick = onConfirm) { Text(stringResource(R.string.boot_movie_remove)) } }, + dismissButton = { androidx.compose.material3.TextButton(onClick = onDismiss) { Text(stringResource(R.string.common_cancel)) } }, + ) +} + +@Composable +private fun ImportTab(s: ModeSettings, a: ModeSettingsActions) { + SettingsRow( + stringResource(R.string.boot_movie_custom), + stringResource(R.string.boot_movie_custom_hint, (BootMovie.MAX_BYTES shr 20).toInt(), BootMovie.MAX_CONVERT_SECONDS), + ) { + SecondaryButton( + when { + s.bootMovieProgress >= 0 -> stringResource(R.string.boot_movie_converting, s.bootMovieProgress) + s.bootMovieImporting -> stringResource(R.string.common_working) + else -> stringResource(R.string.boot_movie_import) + }, + enabled = !s.bootMovieImporting, + progress = s.bootMovieProgress.takeIf { it >= 0 }?.let { it / 100f }, + onClick = a.onImportBootMovie, + ) + } +} + +@Composable +private fun SoundTab(s: ModeSettings, a: ModeSettingsActions, host: MenuHost) { + val app = LocalContext.current.applicationContext + var volume by remember { mutableIntStateOf(SessionPrefs.bootMovieVolume(app)) } + var seconds by remember { mutableIntStateOf(SessionPrefs.bootMovieSeconds(app)) } + val duration by androidx.compose.runtime.produceState(0, s.bootMovie) { + value = withContext(Dispatchers.IO) { BootMovieLibrary.durationSeconds(BootMovie.currentFile(app)) } + } + ToggleRow( + host, "boot-movie-sound", stringResource(R.string.boot_movie_sound), + stringResource(R.string.common_applies_next_session), s.bootMovieSound, onChange = a.onBootMovieSound, + ) + Box(Modifier.padding(horizontal = 6.dp)) { + ValueSlider( + volume, 0..100, 5, s.bootMovieSound, stringResource(R.string.boot_movie_volume), { "$it%" }, + ) { volume = it; SessionPrefs.setBootMovieVolume(app, it) } + } + Box(Modifier.padding(horizontal = 6.dp)) { + val shownSeconds = if (seconds in 1 until duration) seconds else duration + ValueSlider( + shownSeconds, 1..duration.coerceAtLeast(2), 1, duration > 1, stringResource(R.string.boot_movie_length), + { value -> app.getString(R.string.boot_movie_seconds, value) }, + ) { next -> + val stored = if (next >= duration) 0 else next + seconds = stored + SessionPrefs.setBootMovieSeconds(app, stored) + } + } + Text( + stringResource(R.string.boot_movie_length_hint), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 14.dp).padding(bottom = 12.dp), + ) +} + +@Composable +private fun RepoTab(a: ModeSettingsActions) { + val progress = installProgress + val app = LocalContext.current.applicationContext + val scope = rememberCoroutineScope() + var sort by rememberSaveable { mutableStateOf(SteamDeckRepo.Sort.TRENDING) } + var device by rememberSaveable { mutableStateOf(null) } + var query by rememberSaveable { mutableStateOf("") } + var page by rememberSaveable { mutableIntStateOf(1) } + var retry by remember { mutableIntStateOf(0) } + var searching by remember { mutableStateOf(false) } + var jumping by remember { mutableStateOf(false) } + var previewing by remember { mutableStateOf(null) } + var installed by remember { mutableStateOf(setOf()) } + val chosen = rememberMovies(0, a.onBootMovieChanged)?.selected + val inUse by androidx.compose.runtime.produceState(null, chosen) { + value = withContext(Dispatchers.IO) { + chosen?.takeIf { it.startsWith(BootMovieLibrary.PREFIX) }?.let { BootMovieLibrary.repoId(app, it.removePrefix(BootMovieLibrary.PREFIX)) } + } + } + LaunchedEffect(progress.size) { installed = withContext(Dispatchers.IO) { BootMovieLibrary.installedRepoIds(app) } } + val result by androidx.compose.runtime.produceState(null, sort, device, query, page, retry) { + value = null + value = withContext(Dispatchers.IO) { SteamDeckRepo.fetch(sort, device, query, page) } + } + val last by androidx.compose.runtime.produceState(null, sort, device, query, retry) { + value = null + value = withContext(Dispatchers.IO) { SteamDeckRepo.lastPage(sort, device, query) } + } + LaunchedEffect(last) { last?.let { if (page > it) page = it } } + val installPost: (SteamDeckRepo.Post) -> Unit = { post -> + if (progress.isEmpty()) { + progress[post.id] = 0 + installScope.launch { + val outcome = try { + withContext(Dispatchers.IO) { install(app, post) { progress[post.id] = it } } + } catch (e: kotlinx.coroutines.CancellationException) { + throw e + } catch (e: Exception) { + app.getString(R.string.boot_movie_repo_download_failed) + } finally { + progress.remove(post.id) + } + Toast.makeText(app, outcome ?: app.getString(R.string.boot_movie_repo_installed, post.title), Toast.LENGTH_LONG).show() + a.onBootMovieChanged() + } + } + } + val usePost: (SteamDeckRepo.Post) -> Unit = { post -> + scope.launch { + val name = withContext(Dispatchers.IO) { BootMovieLibrary.nameForRepo(app, post.id) } + if (name != null) a.onBootMovie(BootMovieLibrary.idOf(name)) + } + } + Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp).padding(bottom = 12.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) { + Box(Modifier.weight(1f)) { + ListRow(tall = true, onClick = { searching = true }) { + Icon(Icons.Filled.Search, contentDescription = null, tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(18.dp)) + Text( + query.ifEmpty { stringResource(R.string.boot_movie_repo_search) }, fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis, + color = if (query.isEmpty()) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.onBackground, + modifier = Modifier.weight(1f), + ) + } + } + if (query.isNotEmpty()) SecondaryButton(stringResource(R.string.boot_movie_repo_clear), compact = true) { query = ""; page = 1 } + } + Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) { + TabChip(stringResource(R.string.boot_movie_repo_all), device == null) { device = null; page = 1 } + TabChip(stringResource(R.string.boot_movie_repo_deck), device == "steam_deck") { device = "steam_deck"; page = 1 } + TabChip(stringResource(R.string.boot_movie_repo_machine), device == "steam_machine") { device = "steam_machine"; page = 1 } + } + Row(Modifier.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp)) { + SteamDeckRepo.Sort.values().forEach { option -> + TabChip( + stringResource( + when (option) { + SteamDeckRepo.Sort.TRENDING -> R.string.boot_movie_repo_trending + SteamDeckRepo.Sort.DOWNLOADS -> R.string.boot_movie_repo_downloads + SteamDeckRepo.Sort.LIKES -> R.string.boot_movie_repo_likes + SteamDeckRepo.Sort.NEWEST -> R.string.boot_movie_repo_newest + }, + ), + sort == option, + ) { sort = option; page = 1 } + } + } + when (val r = result) { + null -> Text(stringResource(R.string.common_working), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 12.dp)) + is SteamDeckRepo.Page.Failed -> Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Text(stringResource(R.string.boot_movie_repo_failed), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f)) + SecondaryButton(stringResource(R.string.boot_movie_repo_retry), compact = true) { retry++ } + } + is SteamDeckRepo.Page.Ok -> { + if (r.posts.isEmpty()) Text(stringResource(R.string.boot_movie_repo_empty), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 12.dp)) + r.posts.chunked(2).forEach { row -> + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) { + row.forEach { post -> + RepoCard( + post, installed = post.id in installed, inUse = post.id == inUse, percent = progress[post.id], busy = progress.isNotEmpty(), + modifier = Modifier.weight(1f), onPreview = { previewing = post }, onInstall = { installPost(post) }, onUse = { usePost(post) }, + ) + } + if (row.size == 1) Box(Modifier.weight(1f)) + } + } + RepoPager(page, last, hasMore = r.posts.size >= SteamDeckRepo.PAGE_SIZE, onPage = { page = it }, onJump = { jumping = true }) + } + } + } + if (searching) TextEntryDialog( + stringResource(R.string.boot_movie_repo_search), query, number = false, confirm = stringResource(R.string.stores_search_open), + onSubmit = { value -> if (value != query) { query = value; page = 1 } }, onDismiss = { searching = false }, + ) + if (jumping) TextEntryDialog( + stringResource(R.string.boot_movie_repo_go_to_page), page.toString(), number = true, confirm = stringResource(R.string.common_ok), + onSubmit = { value -> value.toIntOrNull()?.let { n -> page = n.coerceIn(1, maxOf(1, last ?: n)) } }, onDismiss = { jumping = false }, + ) + previewing?.let { post -> + PreviewDialog( + post, installed = post.id in installed, inUse = post.id == inUse, percent = progress[post.id], busy = progress.isNotEmpty(), + onInstall = { installPost(post) }, onUse = { usePost(post) }, onDismiss = { previewing = null }, + ) + } +} + +/** Downloads [post] and puts it among the installed movies; returns a message when it failed, null when it worked. */ +private fun install(app: android.content.Context, post: SteamDeckRepo.Post, onProgress: (Int) -> Unit): String? { + val folder = File(app.cacheDir, "boot-movie-download").apply { mkdirs() } + // Leftovers of a download that was cut short are cleared, and every download has a file of its own. + folder.listFiles()?.forEach { if (System.currentTimeMillis() - it.lastModified() > 60 * 60 * 1000L) it.delete() } + val file = File.createTempFile("movie-", ".webm", folder) + return try { + if (!SteamDeckRepo.download(post, file, onProgress)) return app.getString(R.string.boot_movie_repo_download_failed) + val cover = if (post.thumbnail.isNotEmpty()) SteamDeckRepo.bytes(post.thumbnail) else null + when (BootMovie.import(app, file, onProgress = onProgress, title = post.title, source = BootMovieLibrary.SOURCE_REPO, repoId = post.id, cover = cover, use = false)) { + is BootMovie.Import.Done -> null + BootMovie.Import.TooLong -> app.getString(R.string.boot_movie_too_long, BootMovie.MAX_CONVERT_SECONDS) + is BootMovie.Import.Unsupported -> app.getString(R.string.boot_movie_unsupported) + BootMovie.Import.Failed -> app.getString(R.string.boot_movie_import_failed) + } + } finally { + file.delete() + } +} + +@Composable +private fun RepoCard( + post: SteamDeckRepo.Post, installed: Boolean, inUse: Boolean, percent: Int?, busy: Boolean, modifier: Modifier, + onPreview: () -> Unit, onInstall: () -> Unit, onUse: () -> Unit, +) { + val pal = LocalPalette.current + val colors = MaterialTheme.colorScheme + val shape = RoundedCornerShape(10.dp) + val thumbShape = RoundedCornerShape(7.dp) + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val previewLabel = stringResource(R.string.boot_movie_repo_preview) + Column( + verticalArrangement = Arrangement.spacedBy(5.dp), + modifier = modifier.clip(shape) + .background(if (inUse) pal.signal.copy(alpha = 0.14f) else colors.surface.copy(alpha = 0.6f)) + .border(if (inUse) 2.dp else 1.dp, if (inUse) pal.signal else pal.line, shape).padding(6.dp), + ) { + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.fillMaxWidth().aspectRatio(16f / 9f).clip(thumbShape).background(Color(0xFF0E1218)) + .glideBorder(hot, thumbShape, pal.signal) + .hoverable(src).clickable(interactionSource = src, indication = androidx.compose.foundation.LocalIndication.current, role = Role.Button, onClick = onPreview) + .controllerConfirm(onClick = onPreview) + .semantics { contentDescription = previewLabel }, + ) { + if (post.thumbnail.isNotEmpty()) AsyncImage(model = post.thumbnail, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize()) + Box(Modifier.size(40.dp).clip(CircleShape).background(Color.Black.copy(alpha = 0.55f)), contentAlignment = Alignment.Center) { + Icon(Icons.Filled.PlayArrow, contentDescription = null, tint = Color.White, modifier = Modifier.size(26.dp)) + } + } + Text(post.title, fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) + Text(repoInfo(post), fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + RepoAction(installed, inUse, percent, busy, Modifier.fillMaxWidth(), onInstall, onUse) + } +} + +@Composable +private fun repoInfo(post: SteamDeckRepo.Post): String = + listOf(post.author, "♥ ${post.likes}", "⇩ ${post.downloads}", if (post.seconds > 0) stringResource(R.string.boot_movie_seconds, post.seconds) else "") + .filter { it.isNotEmpty() }.joinToString(" · ") + +@Composable +private fun RepoAction(installed: Boolean, inUse: Boolean, percent: Int?, busy: Boolean, modifier: Modifier, onInstall: () -> Unit, onUse: () -> Unit) { + if (inUse) SecondaryButton(stringResource(R.string.boot_movie_in_use), compact = true, modifier = modifier, onClick = {}) + else if (installed) SecondaryButton(stringResource(R.string.boot_movie_repo_use), compact = true, modifier = modifier, onClick = onUse) + else SecondaryButton( + if (percent != null) stringResource(R.string.boot_movie_converting, percent) else stringResource(R.string.boot_movie_repo_install), + enabled = !busy, compact = true, modifier = modifier, onClick = onInstall, + ) +} + +/** A movie from SteamDeckRepo played straight from the site, so it can be checked before it is installed. */ +@Composable +private fun PreviewDialog( + post: SteamDeckRepo.Post, installed: Boolean, inUse: Boolean, percent: Int?, busy: Boolean, + onInstall: () -> Unit, onUse: () -> Unit, onDismiss: () -> Unit, +) { + val shown = rememberShown(onDismiss) + val close = { shown.targetState = false } + val action = remember { FocusRequester() } + val inputMode = LocalInputModeManager.current + LaunchedEffect(Unit) { if (inputMode.inputMode == InputMode.Keyboard) focusSoon { action } } + val maxVideoHeight = (LocalConfiguration.current.screenHeightDp - 200).coerceAtLeast(120).dp + AppDialog(shown, close, "boot-movie-preview", wide = false, maxWidth = 620.dp) { + DialogTitleRow(post.title, close) + Box(Modifier.fillMaxWidth(), contentAlignment = Alignment.Center) { + MoviePreview(post.video, Modifier.heightIn(max = maxVideoHeight).aspectRatio(16f / 9f)) + } + Text(repoInfo(post), fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis) + RepoAction(installed, inUse, percent, busy, Modifier.fillMaxWidth().focusRequester(action), onInstall, onUse) + } +} + +@Composable +private fun MoviePreview(url: String, modifier: Modifier = Modifier) { + val pal = LocalPalette.current + val shape = RoundedCornerShape(10.dp) + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + var state by remember(url) { mutableIntStateOf(0) } + var ratio by remember(url) { mutableFloatStateOf(16f / 9f) } + val player = remember(url) { arrayOfNulls(1) } + DisposableEffect(url) { + onDispose { + runCatching { player[0]?.release() } + player[0] = null + } + } + val toggle = { runCatching { player[0]?.let { if (it.isPlaying) it.pause() else it.start() } }; Unit } + Box( + contentAlignment = Alignment.Center, + modifier = modifier.clip(shape).background(Color.Black) + .glideBorder(hot, shape, pal.signal, pal.line) + .hoverable(src).clickable(interactionSource = src, indication = null, role = Role.Button, onClick = toggle) + .controllerConfirm(onClick = toggle), + ) { + AndroidView( + modifier = Modifier.aspectRatio(ratio), + factory = { viewContext -> + TextureView(viewContext).apply { + surfaceTextureListener = object : TextureView.SurfaceTextureListener { + override fun onSurfaceTextureAvailable(texture: SurfaceTexture, width: Int, height: Int) { + val mp = MediaPlayer() + player[0] = mp + try { + mp.setDataSource(viewContext, Uri.parse(url), mapOf("User-Agent" to "DroidDeck")) + mp.setSurface(Surface(texture)) + mp.isLooping = true + mp.setOnVideoSizeChangedListener { _, w, h -> if (w > 0 && h > 0) ratio = w.toFloat() / h } + mp.setOnPreparedListener { it.start(); state = 1 } + mp.setOnErrorListener { _, _, _ -> state = 2; true } + mp.prepareAsync() + } catch (e: Exception) { + state = 2 + } + } + + override fun onSurfaceTextureSizeChanged(texture: SurfaceTexture, width: Int, height: Int) = Unit + + override fun onSurfaceTextureDestroyed(texture: SurfaceTexture): Boolean { + runCatching { player[0]?.release() } + player[0] = null + return true + } + + override fun onSurfaceTextureUpdated(texture: SurfaceTexture) = Unit + } + } + }, + ) + if (state == 0) Text(stringResource(R.string.common_working), fontSize = 13.sp, color = Color.White.copy(alpha = 0.8f)) + if (state == 2) Text(stringResource(R.string.boot_movie_repo_preview_failed), fontSize = 13.sp, color = Color.White.copy(alpha = 0.8f), modifier = Modifier.padding(12.dp)) + } +} + +/** A dialog with one text box, for a search term or a page number; the Android keyboard comes up with it. */ +@Composable +private fun TextEntryDialog( + title: String, initial: String, number: Boolean, confirm: String, onSubmit: (String) -> Unit, onDismiss: () -> Unit, +) { + val shown = rememberShown(onDismiss) + val close = { shown.targetState = false } + var text by remember { mutableStateOf(initial) } + val submit = { onSubmit(text.trim()); close() } + AppDialog(shown, close, "boot-movie-entry", wide = false, maxWidth = 460.dp) { + DialogTitleRow(title, close) + AdbTextField( + value = text, onValueChange = { text = it }, label = "", keyboardType = if (number) KeyboardType.Number else KeyboardType.Text, + imeAction = ImeAction.Done, placeholder = title, focusOnShow = true, onDone = { submit() }, + ) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) { + SecondaryButton(stringResource(R.string.common_cancel), modifier = Modifier.weight(1f), onClick = close) + SecondaryButton(confirm, modifier = Modifier.weight(1f)) { submit() } + } + } +} + +/** Page buttons around the current page, which opens a box to type another page into; first and last page show their numbers. */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun RepoPager(page: Int, last: Int?, hasMore: Boolean, onPage: (Int) -> Unit, onJump: () -> Unit) { + val reach = last ?: if (hasMore) Int.MAX_VALUE else page + FlowRow( + horizontalArrangement = Arrangement.spacedBy(6.dp, Alignment.CenterHorizontally), + verticalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.fillMaxWidth(), + ) { + SecondaryButton(stringResource(R.string.boot_movie_repo_previous), enabled = page > 1, compact = true) { onPage(page - 1) } + if (page - 3 > 1) SecondaryButton("1", compact = true) { onPage(1) } + for (n in maxOf(1, page - 3) until page) SecondaryButton("$n", compact = true) { onPage(n) } + TabChip("$page", true, Modifier.widthIn(min = 52.dp).heightIn(min = 44.dp), onJump) + for (n in page + 1..minOf(page + 3, reach)) SecondaryButton("$n", compact = true) { onPage(n) } + if (last != null && page + 3 < last) SecondaryButton("$last", compact = true) { onPage(last) } + SecondaryButton(stringResource(R.string.boot_movie_repo_next), enabled = page < reach, compact = true) { onPage(page + 1) } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt index d50a45c4ea..d44f599406 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ComponentsPage.kt @@ -151,6 +151,7 @@ fun ComponentsPage( onImport: () -> Unit, onBack: () -> Unit, games: List = emptyList(), + initialGameKey: String? = null, generalFexPreset: String = "", onGeneralFexPreset: (String) -> Unit = {}, requestInitialFocus: Boolean = true, @@ -169,7 +170,7 @@ fun ComponentsPage( val layer = if (comp in LAYERS) comp else GPU_TAB BackHandler(onBack = onBack) var scopeMenu by remember { mutableStateOf(false) } - var selectedGameKey by remember { mutableStateOf(null) } + var selectedGameKey by remember(initialGameKey) { mutableStateOf(initialGameKey) } var fexMenu by remember { mutableStateOf(false) } var gameProtonMenu by remember { mutableStateOf(false) } var gameProtonId by remember { mutableStateOf(null) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/CursorOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/CursorOverlay.kt index 8f883c24c4..075b7c2ba7 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/CursorOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/CursorOverlay.kt @@ -13,11 +13,12 @@ import androidx.compose.ui.graphics.drawscope.Stroke @Composable fun CursorOverlay( - position: Offset, visible: Boolean, scale: Float, + positionOf: () -> Offset, visible: Boolean, scale: Float, image: ImageBitmap? = null, hotX: Int = 0, hotY: Int = 0, imageScale: Float = 1f, ) { if (!visible) return Canvas(modifier = Modifier.fillMaxSize()) { + val position = positionOf() if (image != null) { val w = (image.width * imageScale).toInt().coerceAtLeast(1) val h = (image.height * imageScale).toInt().coerceAtLeast(1) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt index 6793488780..a6032cd3c5 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt @@ -15,6 +15,7 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.runtime.key import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.Row @@ -30,6 +31,7 @@ import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Delete import androidx.compose.material.icons.outlined.Edit import androidx.compose.ui.semantics.semantics import androidx.compose.foundation.shape.CircleShape @@ -110,7 +112,7 @@ internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, o if (onAdd != null) Rise(0) { GamesHeader(gameCount, s.steamGamesX64, onAdd, Modifier.padding(bottom = 10.dp)) } Rise(0) { Row(verticalAlignment = Alignment.Bottom) { - GameHero(current, Modifier.weight(1f).heightIn(min = if (narrow) 190.dp else 250.dp)) { + GameHero(current, Modifier.weight(1f).heightIn(min = if (narrow) 190.dp else 250.dp), corner = { GameRemoveButton(current, s, a) }) { GameHeroCopy(current, if (narrow) 28.sp else 38.sp) GameActions(current, s, a, onEdit, launch) } @@ -132,7 +134,7 @@ internal fun GamesPage(s: FrontEndState, a: FrontEndActions, selected: String, o modifier = Modifier.weight(1f).fillMaxHeight().verticalScroll(rememberScrollState()) .padding(horizontal = if (narrow) 14.dp else 20.dp, vertical = 16.dp), ) { - GameHero(current, Modifier.fillMaxWidth().heightIn(min = if (narrow) 170.dp else 200.dp)) { + GameHero(current, Modifier.fillMaxWidth().heightIn(min = if (narrow) 170.dp else 200.dp), corner = { GameRemoveButton(current, s, a) }) { GameHeroCopy(current, if (narrow) 24.sp else 32.sp) GameActions(current, s, a, onEdit, launch) } @@ -439,6 +441,47 @@ private fun GamesDialogs(a: FrontEndActions, games: List) { } } +@Composable +private fun GameRemoveButton(g: Library.SteamGame, s: FrontEndState, a: FrontEndActions) { + val kind = com.droiddeck.launcher.frontend.GameRemoval.kind(g) + if (s.shortcutPicker || kind == com.droiddeck.launcher.frontend.GameRemoval.Kind.LAUNCHER) return + if (g.gameFiles?.isDirectory != true) return + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + var asking by remember(g.gameId) { androidx.compose.runtime.mutableStateOf(false) } + val shortcut = kind == com.droiddeck.launcher.frontend.GameRemoval.Kind.SHORTCUT + val label = stringResource(if (shortcut) R.string.edit_remove else R.string.common_uninstall) + val title = if (shortcut) stringResource(R.string.games_remove_title, g.name) else stringResource(R.string.stores_uninstall_title, g.name) + val body = when { + shortcut -> stringResource(R.string.games_remove_body) + g.library == Library.ADDED -> stringResource(R.string.stores_uninstall_body) + else -> stringResource(R.string.games_uninstall_body) + } + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.paneItem("game:remove").downToFirstTile().size(44.dp).clip(Shape12) + .background(if (hot) colors.error.copy(alpha = 0.22f) else Color.Black.copy(alpha = 0.34f)) + .glideBorder(hot, Shape12, colors.error, pal.line2) + .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = androidx.compose.ui.semantics.Role.Button) { asking = true } + .controllerConfirm { asking = true } + .semantics { contentDescription = label }, + ) { + androidx.compose.material3.Icon( + Icons.Outlined.Delete, contentDescription = null, + tint = if (hot) colors.error else Color.White, modifier = Modifier.size(18.dp), + ) + } + if (asking) ConfirmDialog( + title = title, + text = body, + confirm = label, + onConfirm = { a.onGameRemoved(g) }, + onDismiss = { asking = false }, + ) +} + @Composable private fun EditGameButton(onClick: () -> Unit) { val colors = MaterialTheme.colorScheme @@ -570,7 +613,7 @@ private fun libraryLabel(g: Library.SteamGame): String = when { } @Composable -private fun GameHero(g: Library.SteamGame, modifier: Modifier, content: @Composable ColumnScope.() -> Unit) { +private fun GameHero(g: Library.SteamGame, modifier: Modifier, corner: @Composable BoxScope.() -> Unit = {}, content: @Composable ColumnScope.() -> Unit) { val colors = MaterialTheme.colorScheme Box(modifier = modifier.clip(Shape16).background(artBrush(hueOf(g.name)))) { val image = g.hero ?: g.art.takeIf { g.library != Library.EPIC_LAUNCHER } @@ -593,5 +636,6 @@ private fun GameHero(g: Library.SteamGame, modifier: Modifier, content: @Composa modifier = Modifier.align(Alignment.BottomStart).padding(horizontal = 22.dp, vertical = 18.dp), content = content, ) + Box(Modifier.align(Alignment.TopEnd).padding(12.dp), content = corner) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt index 0b9e784e53..6e44aca350 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -165,6 +165,7 @@ class FrontEndActions( val onAddedGamesChanged: (folders: List) -> Unit = {}, val onSteamGameArtChanged: (appId: Int) -> Unit = {}, val onAddedGameRemoved: (folder: String, appId: Long?, name: String) -> Unit = { _, _, _ -> }, + val onGameRemoved: (Library.SteamGame) -> Unit = {}, val onAddedGamesArt: (Boolean) -> Unit = {}, val onSgdbKey: (String) -> Unit = {}, val onStopGameFileSync: () -> Unit = {}, @@ -188,6 +189,7 @@ class FrontEndActions( val onImportLossless: () -> Unit, val onProtons: () -> Unit, val onComponents: (focusContent: Boolean) -> Unit, + val onGameComponents: (Library.SteamGame) -> Unit = { onComponents(true) }, val onComponentsTab: (String) -> Unit = {}, val onSaveImport: (Library.SteamGame) -> Unit = {}, val onSaveExport: (Library.SteamGame, com.droiddeck.launcher.session.GameSaves.Layout) -> Unit = { _, _ -> }, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt index 42eb27d69b..9b65cc8a91 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -523,8 +523,9 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost val back = stringResource(R.string.hop_from_games) SettingCard(stringResource(R.string.setup_card_components), stringResource(R.string.setup_card_components_hint), "card:components", m.hopSource("card:components")) { val at = Hops.sources["card:components"] - if (at == null) a.onComponents(true) - else Hops.go(HopOrigin("games", HOP_SURFACE_GAMES, null, "card:components", at, back, dest = "components", page = "components")) { a.onComponents(true) } + val open = { if (game == null) a.onComponents(true) else a.onGameComponents(game) } + if (at == null) open() + else Hops.go(HopOrigin("games", HOP_SURFACE_GAMES, null, "card:components", at, back, dest = "components", page = "components"), open) } } add { m -> diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt index e0a8ff0b6f..d59e87ce8f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt @@ -185,10 +185,9 @@ internal fun PrimaryButton( .graphicsLayer { alpha = if (LaunchOrigin.flooding === placed) 0f else 1f; scaleX = scale; scaleY = scale; shadowElevation = if (enabled) lift.dp.toPx() else 0f; shape = Shape12; clip = false; ambientShadowColor = pal.signal; spotShadowColor = pal.signal } .clip(Shape12) .background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant))) - .shine(hot, 0.45f) .then(if (enabled) Modifier else Modifier.border(1.dp, pal.line2, Shape12)) - .glideBorder(hot, Shape12, pal.signal) - .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled) { + .then(if (hot) Modifier.border(2.dp, pal.signal, Shape12) else Modifier) + .hoverable(src).clickable(interactionSource = src, indication = null, enabled = enabled) { placed[0]?.takeIf { it.isAttached }?.let { LaunchOrigin.mark(it.boundsInRoot(), placed) } onClick() } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameEnvironmentEditor.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameEnvironmentEditor.kt index 7557eb2495..f8f50a5ebc 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameEnvironmentEditor.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameEnvironmentEditor.kt @@ -143,15 +143,15 @@ internal fun GameEnvironmentEditor(byPad: Boolean, initialScope: String = "", on } } otherId?.let { id -> + val valid = id.isNotEmpty() && GameEnvironment.validScope(id) + val open = { if (valid) { scope = id.toLong().toString(); otherId = null } } Row(verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.spacedBy(10.dp)) { AdbTextField( id, { otherId = it.filter(Char::isDigit) }, stringResource(R.string.game_env_app_id), KeyboardType.Number, ImeAction.Done, modifier = Modifier.weight(1f), compact = true, - onDone = { if (GameEnvironment.validScope(id)) { scope = id.toLong().toString(); otherId = null } }, + onDone = open, ) - SecondaryButton(stringResource(R.string.game_env_open), enabled = id.isNotEmpty() && GameEnvironment.validScope(id)) { - scope = id.toLong().toString(); otherId = null - } + SecondaryButton(stringResource(R.string.game_env_open), enabled = valid, onClick = open) } } if (error) Small(stringResource(R.string.game_env_error), error = true) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/HandCameraUi.kt b/app/src/main/java/com/droiddeck/launcher/ui/HandCameraUi.kt index 86b2aa3924..3aae52a767 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/HandCameraUi.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/HandCameraUi.kt @@ -1,9 +1,11 @@ package com.droiddeck.launcher.ui +import com.droiddeck.launcher.core.AddonPack import android.Manifest import android.content.Intent import android.net.Uri import android.provider.Settings +import android.text.format.Formatter import android.speech.tts.TextToSpeech import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts @@ -70,6 +72,7 @@ import com.droiddeck.launcher.handtracking.Advice import com.droiddeck.launcher.handtracking.BodyPose import com.droiddeck.launcher.handtracking.HandCamera import com.droiddeck.launcher.handtracking.HandTracking +import com.droiddeck.launcher.handtracking.TrackingPack import com.droiddeck.launcher.handtracking.Landmark import com.droiddeck.launcher.handtracking.TrackingCameras import kotlinx.coroutines.delay @@ -186,11 +189,27 @@ internal fun HandCameraRows(host: MenuHost, track: (String) -> Modifier, inSessi }) !s.permitted -> ActionRow(stringResource(R.string.hand_camera_access), stringResource(R.string.hand_camera_access_hint), stringResource(R.string.hand_camera_allow_button), { ask.launch(Manifest.permission.CAMERA) }) + !s.downloaded -> TrackingPackRow() !inSession -> ActionRow(stringResource(R.string.hand_camera_placement), stringResource(R.string.hand_camera_placement_hint), stringResource(R.string.hand_camera_check), { HandTracking.requestCheck() }) } } +@Composable +private fun TrackingPackRow() { + val context = LocalContext.current + val pack by TrackingPack.state.collectAsState() + val size = Formatter.formatShortFileSize(context, TrackingPack.size) + when (val now = pack) { + is AddonPack.State.Downloading -> ActionRow(stringResource(R.string.tracking_pack_title), + stringResource(R.string.tracking_pack_hint, size), stringResource(R.string.tracking_pack_download), {}, progress = now.progress) + AddonPack.State.Failed -> ActionRow(stringResource(R.string.tracking_pack_title), + stringResource(R.string.tracking_pack_failed), stringResource(R.string.tracking_pack_retry), { TrackingPack.ensure(context) }) + else -> ActionRow(stringResource(R.string.tracking_pack_title), + stringResource(R.string.tracking_pack_hint, size), stringResource(R.string.tracking_pack_download), { TrackingPack.ensure(context) }) + } +} + @Composable private fun PlacementCheck(settings: HandTracking.Settings, play: Boolean, onPlay: () -> Unit, onClose: () -> Unit) { val context = LocalContext.current diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt index b0f501cbe9..d90747aca4 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -139,7 +139,7 @@ class ModeSettingsActions( val onBootMovie: (String) -> Unit = {}, val onBootMovieSound: (Boolean) -> Unit = {}, val onImportBootMovie: () -> Unit = {}, - val onRemoveBootMovie: () -> Unit = {}, + val onBootMovieChanged: () -> Unit = {}, val onWifiDiscovery: (Boolean) -> Unit = {}, val onWifiDiscoverySettings: () -> Unit = {}, val onDeckyInstall: (DeckyManager.Release) -> Unit = {}, @@ -467,41 +467,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: onPick = a.onSteamClientArch, ) } - if (s.bootMovie != null) SettingsGroup(stringResource(R.string.boot_movie)) { - ChoiceRow( - host, "boot-movie", stringResource(R.string.boot_movie_video), stringResource(R.string.common_applies_next_session), - buildList { - add(BootMovie.DROIDDECK_30 to stringResource(R.string.boot_movie_droiddeck, 30)) - add(BootMovie.DROIDDECK_60 to stringResource(R.string.boot_movie_droiddeck, 60)) - s.bootMovieCustomName?.let { add(BootMovie.CUSTOM to it) } - }, s.bootMovie, - note = stringResource(R.string.boot_movie_note), onPick = a.onBootMovie, - ) - ToggleRow( - host, "boot-movie-sound", stringResource(R.string.boot_movie_sound), - stringResource(R.string.common_applies_next_session), s.bootMovieSound, onChange = a.onBootMovieSound, - ) - SettingsRow( - stringResource(R.string.boot_movie_custom), - stringResource(R.string.boot_movie_custom_hint, (BootMovie.MAX_BYTES shr 20).toInt(), BootMovie.MAX_CONVERT_SECONDS), - ) { - Row(horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(6.dp)) { - SecondaryButton( - when { - s.bootMovieProgress >= 0 -> stringResource(R.string.boot_movie_converting, s.bootMovieProgress) - s.bootMovieImporting -> stringResource(R.string.common_working) - else -> stringResource(R.string.boot_movie_import) - }, - enabled = !s.bootMovieImporting, - progress = s.bootMovieProgress.takeIf { it >= 0 }?.let { it / 100f }, - onClick = a.onImportBootMovie, - ) - if (s.bootMovieCustomName != null) SecondaryButton( - stringResource(R.string.boot_movie_remove), enabled = !s.bootMovieImporting, onClick = a.onRemoveBootMovie, - ) - } - } - } + if (s.bootMovie != null) BootMovieGroup(s, a, host) if (s.wifiDiscovery != null) SettingsGroup(stringResource(R.string.mode_network)) { val hint = when { s.wifiDiscovery && !s.wifiDiscoveryLocation -> stringResource(R.string.mode_wifi_location_off) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SpatialTrackingActivity.kt b/app/src/main/java/com/droiddeck/launcher/ui/SpatialTrackingActivity.kt index 76539855d9..3b77e09f0f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SpatialTrackingActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SpatialTrackingActivity.kt @@ -29,13 +29,13 @@ import androidx.compose.ui.unit.dp import com.droiddeck.launcher.R import com.droiddeck.launcher.core.AppUiPrefs import com.droiddeck.launcher.glasses.CalibrationDistance +import com.droiddeck.launcher.handtracking.TrackingPack import com.droiddeck.launcher.glasses.Glasses import com.droiddeck.launcher.glasses.SpatialCalibrationProgress import com.droiddeck.launcher.glasses.SpatialTracking import com.droiddeck.launcher.glasses.SpatialTrackingStatus import com.droiddeck.launcher.glasses.StereoCalibrator import kotlinx.coroutines.delay -import org.opencv.android.OpenCVLoader import org.opencv.android.Utils import org.opencv.core.Mat import org.opencv.core.Size @@ -95,7 +95,7 @@ class SpatialTrackingActivity : ComponentActivity() { } override fun onPause() { SpatialTracking.diagnostics(false);super.onPause() } private fun printBoard() { - if(!OpenCVLoader.initLocal()) return + if(!TrackingPack.loadNative(this)) return val c=StereoCalibrator(this);val mat=Mat() c.board.generateImage(Size(1500.0,2100.0),mat,0,1) val bitmap=Bitmap.createBitmap(1500,2100,Bitmap.Config.ARGB_8888) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt index 81a2fee3d5..2c3a0090ef 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt @@ -25,6 +25,7 @@ import androidx.compose.ui.geometry.CornerRadius import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.material.icons.filled.Settings +import androidx.compose.material.icons.filled.SwapHoriz import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.ui.geometry.Size @@ -483,7 +484,7 @@ internal fun DownloadControls(s: FrontEndState, a: FrontEndActions) { } } -internal fun storesSettingsStep(at: Rect, s: androidx.compose.runtime.State, a: FrontEndActions, accent: androidx.compose.ui.graphics.Color): StepAsk = +internal fun storesSettingsStep(at: Rect, s: androidx.compose.runtime.State, a: FrontEndActions, accent: androidx.compose.ui.graphics.Color, onArrange: () -> Unit): StepAsk = StepAsk( anchor = at, side = StepSide.Left, accent = accent, items = 2, maxWidth = 440.dp, handle = { androidx.compose.material3.Icon(androidx.compose.material.icons.Icons.Filled.Settings, null, tint = accent, modifier = Modifier.size(20.dp)) }, @@ -494,6 +495,12 @@ internal fun storesSettingsStep(at: Rect, s: androidx.compose.runtime.State().apply { + addAll(arrangeStoreTabs(SessionPrefs.storesTabOrder(ctx), SessionPrefs.storesTabHidden(ctx))) + } + } + var arranging by remember { mutableStateOf(false) } + val shownStores = tabs.filter { it.shown }.map { it.store } + fun commitTabs() { + SessionPrefs.setStoresTabOrder(ctx, tabs.map { it.store.id }) + SessionPrefs.setStoresTabHidden(ctx, tabs.filterNot { it.shown }.map { it.store.id }.toSet()) + } + fun shiftTab(store: Store, delta: Int) { + val from = tabs.indexOfFirst { it.store == store } + val to = from + delta + if (from < 0 || to !in tabs.indices) return + tabs.add(to, tabs.removeAt(from)) + commitTabs() + } + fun moveTab(store: Store, to: Int) { + val from = tabs.indexOfFirst { it.store == store } + if (from < 0) return + val target = to.coerceIn(0, tabs.lastIndex) + if (target == from) return + tabs.add(target, tabs.removeAt(from)) + commitTabs() + } + fun toggleTab(store: Store) { + val i = tabs.indexOfFirst { it.store == store } + if (i < 0) return + val show = !tabs[i].shown + if (!show && tabs.count { it.shown } <= 1) return + tabs[i] = tabs[i].copy(shown = show) + commitTabs() + } + LaunchedEffect(tabs.map { it.store to it.shown }, chip) { + val picked = Store.byId(chip) ?: return@LaunchedEffect + if (tabs.none { it.store == picked && it.shown }) chip = tabs.firstOrNull { it.shown }?.store?.id ?: chip + } var tab by rememberSaveable { mutableStateOf(if (SessionPrefs.storesOpenTab(ctx) == SessionPrefs.STORES_OPEN_STORE) "store" else "library") } var query by rememberSaveable { mutableStateOf("") } var openGame by rememberSaveable { mutableStateOf(null) } val liveState = androidx.compose.runtime.rememberUpdatedState(s) LaunchedEffect(StoresState.openDownloads) { if (StoresState.openDownloads) { chip = DOWNLOADS; StoresState.openDownloads = false } } val store = Store.byId(chip) + LaunchedEffect(tabs.toList()) { + if (chip != DOWNLOADS && Store.byId(chip) !in shownStores) chip = shownStores.firstOrNull()?.id ?: DOWNLOADS + } val shownTab = tabFor(store, tab) val pane = PaneKey( chip, if (store == null) "" else shownTab, @@ -246,7 +295,8 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier } val pal = LocalPalette.current fun cycleStore(step: Int) { - val ids = Store.entries.map { it.id } + val ids = tabs.filter { it.shown }.map { it.store.id } + if (ids.isEmpty()) return val at = ids.indexOf(chip) pickChip(ids[if (at < 0) (if (step > 0) 0 else ids.size - 1) else (at + step + ids.size) % ids.size]) } @@ -254,6 +304,16 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier if (chip != st.id) pickChip(st.id) else move("first") } BackHandler(enabled = openGame != null) { closeGame() } + BackHandler(enabled = arranging) { arranging = false } + LaunchedEffect(arranging) { + val focus = ff ?: return@LaunchedEffect + if (!arranging || inputMode.inputMode != androidx.compose.ui.input.InputMode.Keyboard) return@LaunchedEffect + repeat(45) { + androidx.compose.runtime.withFrameNanos { } + val req = tabs.firstOrNull()?.let { focus.items["storechip:${it.store.id}"] } ?: return@repeat + if (runCatching { req.requestFocus() }.isSuccess) return@LaunchedEffect + } + } val scroll = rememberScrollState() val detailScroll = rememberScrollState() LaunchedEffect(chip, tab) { scroll.scrollTo(0); grid.scrollToItem(0) } @@ -329,14 +389,32 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier Column( modifier = Modifier.fillMaxSize().padding(horizontal = padH, vertical = if (narrow) 10.dp else 14.dp) .bumpers( - onPrevious = { if (openGame == null) cycleStore(-1) }, - onNext = { if (openGame == null) cycleStore(1) }, + onPrevious = { + val picked = Store.byId(focusedChip) + if (arranging) { if (picked != null) shiftTab(picked, -1) } + else if (openGame == null) cycleStore(-1) + }, + onNext = { + val picked = Store.byId(focusedChip) + if (arranging) { if (picked != null) shiftTab(picked, 1) } + else if (openGame == null) cycleStore(1) + }, ), ) { Box(Modifier.fillMaxWidth().padding(bottom = 8.dp)) { StoreTheme(Store.byId(focusedChip ?: chip)) { - Rise(0) { StoreChips(chip, focusedChip, s.storeDownloadsActive, onStore = { st, _ -> openModes(st) }, onDownloads = { if (chip != DOWNLOADS) pickChip(DOWNLOADS) else move("first") }, - onFocusChip = { focusedChip = it }, onSettings = { at -> if (at != null) StoresMotion.ask(storesSettingsStep(at, liveState, a, pal.signal)) }) } + Rise(0) { + StoreChips( + chip, focusedChip, s.storeDownloadsActive, tabs, arranging, + onStore = { st -> openModes(st) }, + onDownloads = { if (chip != DOWNLOADS) pickChip(DOWNLOADS) else move("first") }, + onFocusChip = { focusedChip = it }, + onArrangeDone = { arranging = false }, + onMoveTab = { st, to -> moveTab(st, to) }, + onToggleTab = { toggleTab(it) }, + onSettings = { at -> if (at != null) StoresMotion.ask(storesSettingsStep(at, liveState, a, pal.signal) { arranging = true }) }, + ) + } } } val fade = with(androidx.compose.ui.platform.LocalDensity.current) { 14.dp.toPx() } @@ -547,55 +625,148 @@ private fun SignInFloodLayer(hostAt: Offset) { } +private class ChipDrag { + var store by mutableStateOf(null) + var from by mutableIntStateOf(-1) + var target by mutableIntStateOf(-1) + var x by mutableFloatStateOf(0f) +} + +@Composable +private fun StoreDot(store: Store, signedIn: Boolean) { + val c = sourceColours(store.id) + Box( + Modifier.size(12.dp) + .onGloballyPositioned { StoresMotion.dots[store] = it.boundsInRoot() } + .pulseRing(StoresMotion.pulses[store] ?: 0, c.dot), + ) { Box(Modifier.matchParentSize().clip(CircleShape).background(c.dot).alpha(if (signedIn) 1f else 0.35f)) } +} + +@Composable +private fun RowScope.ArrangeStoreChip( + tab: StoreTab, index: Int, last: Int, gapPx: Float, drag: ChipDrag, + onFocusChip: (String?) -> Unit, onMoveTab: (Store, Int) -> Unit, onToggleTab: (Store) -> Unit, +) { + val store = tab.store + val box = remember(store) { mutableFloatStateOf(0f) } + val pitch = box.floatValue + gapPx + val held = drag.store == store + val lift by animateFloatAsState(if (held) 1f else 0f, Motion.sp(0.7f, Spring.StiffnessMediumLow), label = "chipLift") + val shift by animateFloatAsState( + when { + drag.store == null || held -> 0f + drag.from < index && drag.target >= index -> -pitch + drag.from > index && drag.target <= index -> pitch + else -> 0f + }, + Motion.sp(0.6f, Spring.StiffnessMediumLow), label = "chipShift", + ) + val pill = remember { RoundedCornerShape(99.dp) } + val signedIn = StoresState.isSignedIn(store) && StoresState.expired[store] != true + fun reset() { + drag.store = null + drag.from = -1 + drag.target = -1 + drag.x = 0f + } + fun commit() { + val from = drag.from + val to = drag.target + reset() + if (from >= 0 && to >= 0 && to != from) onMoveTab(store, to) + } + StoreChip( + label = store.shortLabel, on = false, under = false, key = store.id, mark = sourceColours(store.id).dot, lift = lift, + modifier = Modifier.weight(1f) + .zIndex(if (held) 2f else 0f) + .onSizeChanged { box.floatValue = it.width.toFloat() } + .graphicsLayer { + translationX = if (held) drag.x else shift + shadowElevation = 14.dp.toPx() * lift + shape = pill + clip = false + } + .pointerInput(store, index) { + detectDragGestures( + onDragStart = { + drag.store = store + drag.from = index + drag.target = index + drag.x = 0f + }, + onDragEnd = { commit() }, + onDragCancel = { reset() }, + ) { change, amount -> + change.consume() + val step = box.floatValue + gapPx + if (step <= 0f) return@detectDragGestures + drag.x = (drag.x + amount.x).coerceIn(-drag.from * step, (last - drag.from) * step) + drag.target = (drag.from + (drag.x / step).roundToInt()).coerceIn(0, last) + } + } + .alpha(if (tab.shown) 1f else 0.32f), + lead = { StoreDot(store, signedIn) }, + onFocused = onFocusChip, + ) { onToggleTab(store) } +} + @Composable private fun StoreChips( - selected: String, focused: String?, active: Int, onStore: (Store, Rect?) -> Unit, onDownloads: () -> Unit, onSettings: (Rect?) -> Unit, - onFocusChip: (String?) -> Unit, + selected: String, focused: String?, active: Int, tabs: List, arranging: Boolean, + onStore: (Store) -> Unit, onDownloads: () -> Unit, onSettings: (Rect?) -> Unit, onFocusChip: (String?) -> Unit, + onArrangeDone: () -> Unit, onMoveTab: (Store, Int) -> Unit, onToggleTab: (Store) -> Unit, ) { val pal = LocalPalette.current - val keys = Store.entries.map { it.id } + DOWNLOADS + val keys = tabs.filter { it.shown }.map { it.store.id } + DOWNLOADS val bounds = remember { androidx.compose.runtime.mutableStateMapOf() } val rootBounds = remember { HashMap() } val highlighted = focused ?: selected val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current.inputMode - val fillShown = inputMode != androidx.compose.ui.input.InputMode.Keyboard + val fillShown = inputMode != androidx.compose.ui.input.InputMode.Keyboard && !arranging val tint = androidx.compose.animation.animateColorAsState( Store.byId(highlighted)?.let { sourceColours(it.id).dot } ?: pal.signal, Motion.tw(160), label = "chipTint", ) + val gap = 8.dp + val gapPx = with(androidx.compose.ui.platform.LocalDensity.current) { gap.toPx() } + val drag = remember { ChipDrag() } Box(Modifier.fillMaxWidth()) { - Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { - for (store in Store.entries) { - val signedIn = StoresState.isSignedIn(store) && StoresState.expired[store] != true - StoreChip( - label = store.shortLabel, on = selected == store.id, under = fillShown && highlighted == store.id, key = store.id, mark = sourceColours(store.id).dot, - modifier = Modifier.weight(1f).onGloballyPositioned { bounds[store.id] = it.boundsInParent(); rootBounds[store.id] = it.boundsInRoot() }, - lead = { - val c = sourceColours(store.id) - Box( - Modifier.size(12.dp) - .onGloballyPositioned { StoresMotion.dots[store] = it.boundsInRoot() } - .pulseRing(StoresMotion.pulses[store] ?: 0, c.dot) - .background(c.dot.copy(alpha = if (signedIn) 1f else 0.35f), CircleShape), - ) - }, - description = store.label + if (signedIn || !StoresState.accountsLoaded) "" else " " + stringResource(R.string.stores_chip_signed_out), - onFocused = onFocusChip, - ) { onStore(store, rootBounds[store.id]) } + Row(horizontalArrangement = Arrangement.spacedBy(gap), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { + for (tab in tabs) { + val store = tab.store + if (arranging) { + val index = tabs.indexOfFirst { it.store == store } + key(store) { ArrangeStoreChip(tab, index, tabs.lastIndex, gapPx, drag, onFocusChip, onMoveTab, onToggleTab) } + } else if (tab.shown) { + val signedIn = StoresState.isSignedIn(store) && StoresState.expired[store] != true + key(store) { + StoreChip( + label = store.shortLabel, on = selected == store.id, under = fillShown && highlighted == store.id, key = store.id, mark = sourceColours(store.id).dot, + modifier = Modifier.weight(1f).onGloballyPositioned { bounds[store.id] = it.boundsInParent(); rootBounds[store.id] = it.boundsInRoot() }, + lead = { StoreDot(store, signedIn) }, + description = store.label + if (signedIn || !StoresState.accountsLoaded) "" else " " + stringResource(R.string.stores_chip_signed_out), + onFocused = onFocusChip, + ) { onStore(store) } + } + } } - StoreChip( - label = null, on = selected == DOWNLOADS, under = fillShown && highlighted == DOWNLOADS, key = DOWNLOADS, mark = pal.signal, - modifier = Modifier.onGloballyPositioned { - bounds[DOWNLOADS] = it.boundsInParent() - StoresMotion.downloadsChip = it.boundsInRoot() - }, - lead = { Icon(Icons.Outlined.Download, null, modifier = Modifier.size(18.dp)) }, - trail = if (active > 0) { { CountPill(active) } } else null, - description = stringResource(R.string.stores_tab_downloads), - onFocused = onFocusChip, - ) { onDownloads() } - var cogAt by remember { mutableStateOf(null) } - Box(Modifier.onGloballyPositioned { cogAt = it.boundsInRoot() }) { - IconChip(Icons.Filled.Settings, stringResource(R.string.stores_settings)) { onSettings(cogAt) } + if (arranging) { + IconChip(Icons.Filled.Check, stringResource(R.string.stores_tabs_arrange_done)) { onArrangeDone() } + } else { + StoreChip( + label = null, on = selected == DOWNLOADS, under = fillShown && highlighted == DOWNLOADS, key = DOWNLOADS, mark = pal.signal, + modifier = Modifier.onGloballyPositioned { + bounds[DOWNLOADS] = it.boundsInParent() + StoresMotion.downloadsChip = it.boundsInRoot() + }, + lead = { Icon(Icons.Outlined.Download, null, modifier = Modifier.size(18.dp)) }, + trail = if (active > 0) { { CountPill(active) } } else null, + description = stringResource(R.string.stores_tab_downloads), + onFocused = onFocusChip, + ) { onDownloads() } + var cogAt by remember { mutableStateOf(null) } + Box(Modifier.onGloballyPositioned { cogAt = it.boundsInRoot() }) { + IconChip(Icons.Filled.Settings, stringResource(R.string.stores_settings)) { onSettings(cogAt) } + } } } ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown) @@ -605,7 +776,7 @@ private fun StoreChips( @Composable private fun StoreChip( label: String?, on: Boolean, under: Boolean, key: String, mark: Color, modifier: Modifier, lead: @Composable () -> Unit, - trail: (@Composable () -> Unit)? = null, description: String? = null, + trail: (@Composable () -> Unit)? = null, description: String? = null, lift: Float = 0f, onFocused: (String?) -> Unit = {}, onClick: () -> Unit, ) { val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current @@ -630,10 +801,10 @@ private fun StoreChip( if (f.isFocused && inputMode.inputMode == androidx.compose.ui.input.InputMode.Keyboard) onFocused(key) else if (!f.isFocused) onFocused(null) } - .heightIn(min = 44.dp).graphicsLayer { scaleX = scale; scaleY = scale }.clip(shape) - .background(if (under) Color.Transparent else colors.surface) + .heightIn(min = 44.dp).graphicsLayer { scaleX = scale * (1f + 0.08f * lift); scaleY = scale * (1f + 0.08f * lift) }.clip(shape) + .background(if (under) Color.Transparent else lerp(colors.surface, pal.signal, 0.18f * lift)) .shownBar(on, mark) - .glideBorder(hot, shape, pal.signal, if (under) Color.Transparent else pal.line) + .glideBorder(hot, shape, pal.signal, if (under) Color.Transparent else lerp(pal.line, pal.signal, lift)) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick) .controllerConfirm(onClick = onClick) .then(if (description != null) Modifier.semantics { contentDescription = description } else Modifier) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt b/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt index 86980362f4..e33ebde335 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/Theme.kt @@ -56,7 +56,7 @@ object Themes { ELECTRIC, R.string.theme_electric, R.string.theme_electric_detail, background = Color(0xFF070A10), surface = Color(0xFF0F1522), surfaceVariant = Color(0xFF16203A), line = Color(0xFF1E2A47), line2 = Color(0xFF2A3A5E), onBackground = Color(0xFFEEF3FF), onSurfaceVariant = Color(0xFF8B9AB8), - primary = Color(0xFF2E86FF), primary2 = Color(0xFF136CE0), onPrimary = Color(0xFFFFFFFF), signal = Color(0xFF2E86FF), + primary = Color(0xFF2E86FF), primary2 = Color(0xFF2684FF), onPrimary = Color(0xFF03111F), signal = Color(0xFF2E86FF), good = Color(0xFF4CD37F), ), ) diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 24209cf92b..c8fd949fbe 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -176,6 +176,8 @@ %1$s عبر FEX هذا البرنامج مبني لأجهزة كمبيوتر %1$s ويعمل عبر FEX، الذي لم يتم إعداده بعد. افتح Steam مرة واحدة أثناء تسجيل الدخول: سيجعله DroidDeck يُنزّل FEX وSteam Linux Runtime اللازمة، ثم يُفتح هذا البرنامج. هذا البرنامج + تعذّر تنزيل عميل Steam. قد تكون شبكتك أو VPN تحظر خوادم Steam؛ تحقّق من الاتصال وحاول مرة أخرى. + تعذّر إعداد عميل Steam. تحقّق من الاتصال والمساحة الفارغة، ثم حاول مرة أخرى. %1$s مبني لأجهزة كمبيوتر x86 ويعمل عبر FEX، الذي لم يتم تثبيته بعد. شغّل Steam مرة واحدة أثناء تسجيل الدخول ودعه يُنزّل FEX وSteam Linux Runtime، ثم شغّل هذا البرنامج مجددًا. معرّف تطبيق على Flathub أو صفحته على Flathub. يُعَدّ Flatpak أولًا إن لم يكن مُعدًّا بعد. الملف @@ -546,7 +548,7 @@ لـ Adreno فقط. تقطّع أقل، مع استهلاك أكبر للبطارية والحرارة. إصلاحات الجلسة Turnip: التصيير عبر sysmem - أسرع لـ Steam ولمعظم الألعاب. مطلوب على Adreno 710/720/722. + أسرع لعميل Steam؛ في الألعاب يختار برنامج التشغيل بين العرض المقسّم إلى مربعات والعرض في ذاكرة النظام لكل مرحلة. مطلوب على Adreno 710/720/722. تجاوز مساعد xalia في Steam droiddeck-ntsync (تجريبي) بديل في مساحة المستخدم لبرنامج تشغيل ntsync في Linux، للاختبار. أثناء تفعيله، يستخدمه Proton بدلًا من droiddeck-esync وdroiddeck-fsync. يعمل مع Proton Experimental ARM64 وGE-Proton وproton-cachyos. يُطبَّق في الجلسة التالية. @@ -1062,6 +1064,9 @@ لعبة مُضافة لعبة مخصّصة تخزين الألعاب + يحذف ملفاتها ويزيلها من Steam. + إزالة %1$s؟ + يحذف الاختصار وتبقى ملفات اللعبة. أفضل زوج لهذا GPU، يُحافَظ على تحديثه اختر زوجًا بنفسك جارٍ البحث عن برامج التشغيل… @@ -2008,6 +2013,8 @@ المتاجر إعدادات المتاجر الإعدادات + ترتيب التبويبات + تم (لم يتم تسجيل الدخول) المتجر المكتبة @@ -2234,7 +2241,7 @@ الحجم حفظ العودة إلى الافتراضي - يُرسم فوق خلفية اللعبة كما يفعل Steam. قد يختلف الموضع الدقيق ببضع بكسلات. + قد يختلف هذا الموضع بضع نقاط بكسل. لا توجد لهذه اللعبة شعار بعد. اختر واحدًا من الشعار لتراه هنا. تعذّر حفظ موضع الشعار. حاول مرة أخرى. الخلفية @@ -2815,7 +2822,7 @@ فيديو الإقلاع الفيديو DroidDeck · %1$d إطار/ث - معدل 60 إطارًا/ث أكثر سلاسة لكنه يستهلك المعالج أكثر أثناء بدء Steam. فيديو البدء المختار في إعدادات Steam نفسها له الأولوية. + معدل 60 إطارًا/ث أكثر سلاسة لكنه يستهلك المعالج أكثر أثناء بدء Steam. فيديو مختار في إعدادات Steam نفسها يظهر هنا أيضًا. الصوت فيديو خاص بك MP4 أو MOV أو MKV أو WebM. تُحوَّل الصيغ الأخرى والملفات الأكبر من %1$d ميغابايت إلى WebM بدقة 720p على الجهاز، حتى %2$d ثانية. @@ -2829,6 +2836,51 @@ جارٍ تحويل %1$s لـ Steam. أبقِ DroidDeck مفتوحًا. لا يستطيع هذا الجهاز فك ترميز هذا الفيديو. تعذّر استيراد الفيديو + إزالة %1$s؟ + سيُحذف الفيديو من DroidDeck ومن مجلد فيديوهات Steam. + المثبّتة + استيراد + SteamDeckRepo + الصوت + الفيديوهات المثبّتة + استعراض + DroidDeck + مستورد + SteamDeckRepo + Steam + متجر النقاط + تقرير فيديو الإقلاع + يحفظ ما يعرفه DroidDeck وSteam عن فيديوهات الإقلاع في ملف نصي يمكنك إرفاقه ببلاغ خطأ. + حفظ + تم الحفظ في %1$s + تعذّر حفظ التقرير. + مستوى الصوت + المدة + %1$d ث + عدد الثواني التي يتم تشغيلها من الفيديو. أي جزء أطول من ذلك يُقطع في النهاية. + البحث في SteamDeckRepo + كل الأجهزة + Steam Deck + Steam Machine + الرائجة + الأكثر تنزيلًا + الأكثر إعجابًا + الأحدث + تعذّر الوصول إلى SteamDeckRepo + إعادة المحاولة + لم يُعثر على فيديوهات + تثبيت + استخدام + قيد الاستخدام + تم تثبيت %1$s + تعذّر تنزيل هذا الفيديو + السابق + التالي + الصفحة %1$d + مسح + الانتقال إلى صفحة + معاينة + تعذر تشغيل المعاينة كاميرات Luma Ultra - تجريبية تتبع موضع Joy-Con استخدم كاميرات النظارات الذكية لتحديد موضع وحدات تحكم Joy-Con المقترنة. يتم التحكم في الدوران والأزرار من خلال وحدات تحكم Joy-Con. يتم تقدير الموضع عندما تكون معصميك مخفية. يحل هذا محل وحدات التحكم التي يتم تشغيلها باليدين ويوقف تتبع كاميرا الهاتف مؤقتًا. وجّه وحدات تحكم Joy-Con للأمام عند توصيل مركز التتبع أو إعادة ضبطه. @@ -3002,7 +3054,6 @@ جارٍ انتظار استقرار تتبع الرأس؛ أعد ضبط مركز التتبع إذا طُلب منك ذلك. المراقبة بالكاميرات قديمة جدًا؛ في انتظار زوج جديد تناسب %1$.2f بكسل. قم بقياس المسافة التي حددتها من الكاميرا اليسرى إلى مركز هدف المعايرة، ثم قم بالتحقق من صحتها. - OpenCV غير متاح: %1$s تمت استعادة %1$d من المشاهدات المحفوظة. قم بحساب المعايرة لإعادة المحاولة، أو ابدأ مجموعة جديدة لالتقاط المزيد. ملتقطة %1$d / 24 مشاهدة. حافظ على هدف المعايرة ثابتًا؛ حرك النظارات الذكية للعرض التالي. رُفض الالتقاط: تظهر %1$d / 12 زاوية مطلوبة في كلتا الكاميرتين. أظهر جزءًا أكبر من لوحة المعايرة، وابقَ ثابتًا ثم حاول مرة أخرى. diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 58c46e41fd..a9303902af 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -176,6 +176,8 @@ %1$s con FEX Este programa está hecho para PC %1$s y se ejecuta con FEX, que aún no está listo. Abre Steam una vez con tu sesión iniciada: DroidDeck hará que descargue FEX y el Steam Linux Runtime que necesita, y después se abrirá. Este programa + No se pudo descargar el cliente de Steam. Es posible que tu red o VPN esté bloqueando los servidores de Steam; revisa la conexión e inténtalo de nuevo. + No se pudo configurar el cliente de Steam. Revisa la conexión y el espacio libre, y vuelve a intentarlo. %1$s está hecho para PC x86 y se ejecuta con FEX, que aún no está instalado. Abre Steam una vez con tu sesión iniciada y deja que descargue FEX y el Steam Linux Runtime; después vuelve a iniciarlo. Un ID de app de Flathub o su página en Flathub. Flatpak se configura primero si aún no lo está. Archivo @@ -533,7 +535,7 @@ Solo Adreno. Menos microcortes, más consumo de batería y calor. Correcciones de sesión Turnip: renderizado sysmem - Más rápido para Steam y la mayoría de juegos. Obligatorio en Adreno 710/720/722. + Más rápido para el cliente de Steam; en los juegos, el controlador elige entre renderizado por mosaicos o en memoria del sistema en cada pasada. Obligatorio en Adreno 710/720/722. Omitir el asistente xalia de Steam droiddeck-ntsync (experimental) Un sustituto en espacio de usuario del controlador ntsync de Linux, para pruebas. Mientras está activado, Proton lo usa en lugar de droiddeck-esync y droiddeck-fsync. Funciona con Proton Experimental ARM64, GE-Proton y proton-cachyos. Se aplica en la próxima sesión. @@ -1100,6 +1102,9 @@ Juego agregado Juego personalizado Almacenamiento de juegos + Elimina sus archivos y la quita de Steam. + ¿Quitar %1$s? + Elimina su acceso directo. Los archivos del juego se conservan. El mejor par para esta GPU, siempre actualizado Elige un par manualmente Buscando controladores… @@ -1975,6 +1980,8 @@ Tiendas Ajustes de las tiendas Ajustes + Organizar pestañas + Listo (sin iniciar sesión) Tienda Biblioteca @@ -2185,7 +2192,7 @@ Tamaño Guardar Volver al valor predeterminado - Se dibuja sobre el fondo del juego, igual que en Steam. La posición exacta puede variar unos píxeles. + Este punto exacto puede variar unos pocos píxeles. Este juego aún no tiene logotipo. Elige uno en Logotipo para verlo aquí. No se pudo guardar la posición del logotipo. Inténtalo de nuevo. Fondo @@ -2655,7 +2662,7 @@ Video de arranque Video DroidDeck · %1$d fps - 60 fps se ve más fluido pero usa más CPU mientras Steam se inicia. Un video de inicio elegido en la configuración de Steam tiene prioridad. + 60 fps se ve más fluido pero usa más CPU mientras Steam se inicia. Un video elegido en la configuración de Steam también aparece aquí. Sonido Tu propio video MP4, MOV, MKV o WebM. Otros formatos y archivos de más de %1$d MB se convierten a WebM 720p en el dispositivo, hasta %2$d segundos. @@ -2669,6 +2676,51 @@ Convirtiendo %1$s para Steam. Mantén DroidDeck abierto. Este dispositivo no puede decodificar ese video. No se pudo importar ese video + ¿Quitar %1$s? + Esto elimina el video de DroidDeck y de la carpeta de videos de Steam. + Instalados + Importar + SteamDeckRepo + Sonido + Videos instalados + Explorar + DroidDeck + Importado + SteamDeckRepo + Steam + Tienda de puntos + Informe de películas de arranque + Guarda en un archivo de texto lo que DroidDeck y Steam saben de las películas de arranque, para adjuntarlo a un informe de error. + Guardar + Guardado en %1$s + No se pudo guardar el informe. + Volumen + Duración + %1$d s + Cuántos segundos del video se reproducen. Todo lo que dure más se corta al final. + Buscar en SteamDeckRepo + Todos los dispositivos + Steam Deck + Steam Machine + Tendencias + Más descargados + Más gustados + Más recientes + No se pudo conectar con SteamDeckRepo + Reintentar + No se encontraron videos + Instalar + Usar + En uso + %1$s instalado + No se pudo descargar ese video + Anterior + Siguiente + Página %1$d + Borrar + Ir a la página + Vista previa + No se pudo reproducir la vista previa Clave de API Obtener una clave Clave rechazada @@ -2852,7 +2904,6 @@ Esperando un seguimiento de cabeza estable; restablece el centro de seguimiento si se solicita. La observación con cámara es demasiado antigua; esperando un par nuevo Ajustar %1$.2f px. Mida la distancia seleccionada desde la cámara izquierda hasta el centro del objetivo de calibración y luego valide. - OpenCV no disponible: %1$s %1$d vistas guardadas restauradas. Calcule la calibración para volver a intentarlo o comience un nuevo conjunto para capturar más. Capturado %1$d / 24 vistas. Mantenga fijo el objetivo de calibración; Mueva las gafas inteligentes para la siguiente vista. Captura rechazada: %1$d / 12 esquinas requeridas visibles en ambas cámaras. Muestre más del objetivo de calibración, quédese quieto y vuelva a intentarlo. diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index 910c6a994d..aba51d5590 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -176,6 +176,8 @@ %1$s през FEX Тази програма е компилирана за %1$s компютри и се стартира през FEX, който още не е настроен. Отворете Steam веднъж, докато сте влезли: DroidDeck ще изтегли FEX и необходимата Steam Linux Runtime, след което тя ще се отвори. Тази програма + Клиентът на Steam не можа да бъде изтеглен. Мрежата или VPN връзката ви може да блокира сървърите на Steam; проверете връзката и опитайте отново. + Клиентът на Steam не можа да бъде настроен. Проверете връзката и свободното място, след което опитайте отново. %1$s е компилирана за x86 компютри и се стартира през FEX, който още не е инсталиран. Стартирайте Steam веднъж, докато сте влезли, и го оставете да изтегли FEX и Steam Linux Runtime, след което стартирайте отново. ID на приложение в Flathub или страницата му в Flathub. Flatpak се настройва първо, ако още не е. Файл @@ -538,7 +540,7 @@ Само за Adreno. По-малко засечки, по-голямо използване на батерията и повече топлина. Корекции на сесията Turnip: рендиране sysmem - По-бързо за Steam и повечето игри. Задължително на Adreno 710/720/722. + По-бързо за клиента на Steam; в игрите драйверът избира за всеки проход между рендериране на плочки и в системната памет. Задължително на Adreno 710/720/722. Пропускане на помощника xalia на Steam droiddeck-ntsync (експериментално) Заместител на потребителско ниво за драйвера ntsync на Linux, за тестване. Докато е включен, Proton го използва вместо droiddeck-esync и droiddeck-fsync. Работи с Proton Experimental ARM64, GE-Proton и proton-cachyos. Прилага се от следващата сесия. @@ -1038,6 +1040,9 @@ Добавена игра Персонализирана игра Хранилище за игри + Изтрива файловете ѝ и я премахва от Steam. + Премахване на %1$s? + Изтрива пряката пътека. Файловете на играта остават. Най-добрата двойка за този GPU, поддържана актуална Изберете двойка сами Проверка за драйвери… @@ -1924,6 +1929,8 @@ Магазини Настройки на магазините Настройки + Подреждане на раздели + Готово (не е вписан) Магазин Библиотека @@ -2150,7 +2157,7 @@ Размер Запази Обратно по подразбиране - Рисува се върху фона на играта, както прави Steam. Точната позиция може да се различава с няколко пиксела. + Точното място може да се различава с няколко пиксела. Тази игра още няма лого. Избери такова в Лого, за да го видиш тук. Позицията на логото не можа да се запази. Опитай отново. Фон @@ -2679,7 +2686,7 @@ Начално видео Видео DroidDeck · %1$d кадъра/с - 60 кадъра/с изглежда по-гладко, но натоварва повече процесора, докато Steam се стартира. Начално видео, избрано в настройките на Steam, има предимство. + 60 кадъра/с изглежда по-гладко, но натоварва повече процесора, докато Steam се стартира. Видео, избрано в настройките на Steam, също се показва тук. Звук Собствено видео MP4, MOV, MKV или WebM. Други формати и файлове над %1$d MB се конвертират на устройството до WebM 720p, до %2$d секунди. @@ -2693,6 +2700,51 @@ %1$s се конвертира за Steam. Не затваряйте DroidDeck. Устройството не може да декодира това видео. Видеото не можа да бъде импортирано + Да се премахне ли %1$s? + Това изтрива видеото от DroidDeck и от папката с видеа на Steam. + Инсталирани + Импортиране + SteamDeckRepo + Звук + Инсталирани видеа + Преглед + DroidDeck + Импортирано + SteamDeckRepo + Steam + Магазин за точки + Отчет за стартовите филми + Записва в текстов файл какво знаят DroidDeck и Steam за стартовите филми, за да го прикачите към доклад за грешка. + Запази + Записано в %1$s + Отчетът не можа да бъде записан. + Сила на звука + Продължителност + %1$d с + Колко секунди от филма се възпроизвеждат. Всичко по-дълго се отрязва в края. + Търсене в SteamDeckRepo + Всички устройства + Steam Deck + Steam Machine + Популярни + Най-изтеглени + Най-харесвани + Най-нови + SteamDeckRepo не може да бъде достигнат + Опитайте отново + Не са намерени видеа + Инсталиране + Използване + Използва се + %1$s е инсталирано + Видеото не можа да бъде изтеглено + Назад + Напред + Страница %1$d + Изчисти + Към страница + Преглед + Прегледът не можа да бъде пуснат Luma Ultra камери — Експериментално Проследяване на позицията на Joy-Con Използвайте камерите на интелигентните очила, за да позиционирате сдвоените си контролери Joy-Con. Въртенето и натискането на бутоните идват от контролерите Joy-Con. Позицията се оценява, когато китките ви са скрити. Заменя контролерите, управлявани с голи ръце, и поставя на пауза проследяването с камерата на телефона. Насочете контролерите Joy-Con напред, когато свързвате или нулирате центъра за проследяване. @@ -2866,7 +2918,6 @@ Изчакване на стабилно проследяване на главата; нулиране на центъра за проследяване, ако е поискано. Наблюдението на камерата е твърде старо; в очакване на нов чифт Побиране на %1$.2f пиксела. Измерете избраното разстояние от лявата камера до центъра на целта за калибриране, след което потвърдете. - OpenCV не е наличен: %1$s %1$d запазените изгледи са възстановени. Изчислете калибрирането, за да опитате отново, или започнете нов набор, за да заснемете повече. Заснето %1$d / 24 прегледа. Дръжте целта за калибриране фиксирана; преместете смарт очилата за следващия изглед. Заснемането е отхвърлено: %1$d / 12 задължителни ъгъла, видими и в двете камери. Покажете още от целта за калибриране, задръжте неподвижно и опитайте отново. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 8b13a6ccd3..2bef97b92d 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -176,6 +176,8 @@ %1$s přes FEX Tento program je sestaven pro PC %1$s a běží přes FEX, který ještě není nastaven. Jednou spusťte přihlášený Steam: DroidDeck tím stáhne FEX a Steam Linux Runtime, který potřebuje, a pak se tento program otevře. Tento program + Klienta Steam se nepodařilo stáhnout. Vaše síť nebo VPN možná blokuje servery Steamu; zkontrolujte připojení a zkuste to znovu. + Klienta Steam se nepodařilo nastavit. Zkontrolujte připojení a volné místo a zkuste to znovu. %1$s je sestaven pro PC x86 a běží přes FEX, který ještě není nainstalován. Jednou spusťte přihlášený Steam a nechte ho stáhnout FEX a Steam Linux Runtime, pak to spusťte znovu. ID aplikace Flathub nebo její stránka na Flathub. Flatpak se nejprve nastaví, pokud ještě není. Soubor @@ -542,7 +544,7 @@ Jen Adreno. Méně zadrhávání, více spotřeby baterie a tepla. Opravy relace Turnip: vykreslování sysmem - Rychlejší pro Steam a většinu her. Vyžadováno na Adreno 710/720/722. + Rychlejší pro klienta Steam; ve hrách ovladač pro každý průchod volí dlaždicové vykreslování, nebo vykreslování v systémové paměti. Vyžadováno na Adreno 710/720/722. Vynechat Steamova pomocníka xalia droiddeck-ntsync (experimentální) Uživatelská náhrada linuxového ovladače ntsync, pro testování. Když je zapnuto, Proton ho používá místo droiddeck-esync a droiddeck-fsync. Funguje s Proton Experimental ARM64, GE-Proton a proton-cachyos. Použije se od příští relace. @@ -1050,6 +1052,9 @@ Přidaná hra Vlastní hra Úložiště her + Smaže její soubory a odebere ji ze Steamu. + Odebrat %1$s? + Smaže zástupce. Soubory hry zůstanou. Nejlepší dvojice pro tento GPU, udržovaná aktuální Vyberte dvojici sami Hledání ovladačů… @@ -1966,6 +1971,8 @@ Obchody Nastavení obchodů Nastavení + Uspořádat karty + Hotovo (nepřihlášen) Obchod Knihovna @@ -2192,7 +2199,7 @@ Velikost Uložit Zpět na výchozí - Kreslí se přes pozadí hry, jako to dělá Steam. Přesná poloha se může lišit o pár pixelů. + Přesná poloha se může lišit o několik pixelů. Tato hra zatím nemá logo. Vyber ho v Logo, ať se tady zobrazí. Polohu loga se nepodařilo uložit. Zkus to znovu. Pozadí @@ -2747,7 +2754,7 @@ Úvodní video Video DroidDeck · %1$d fps - 60 fps vypadá plynuleji, ale při spouštění Steamu víc zatěžuje procesor. Úvodní video vybrané přímo v nastavení Steamu má přednost. + 60 fps vypadá plynuleji, ale při spouštění Steamu víc zatěžuje procesor. Video vybrané přímo v nastavení Steamu se zde také zobrazí. Zvuk Vlastní video MP4, MOV, MKV nebo WebM. Jiné formáty a soubory nad %1$d MB se v zařízení převedou na WebM 720p, nejvýše %2$d sekund. @@ -2761,6 +2768,51 @@ Převádí se %1$s pro Steam. Nechte DroidDeck otevřený. Toto zařízení video nedokáže dekódovat. Video se nepodařilo importovat + Odebrat %1$s? + Tím se video smaže z DroidDecku i ze složky videí Steamu. + Nainstalované + Importovat + SteamDeckRepo + Zvuk + Nainstalovaná videa + Procházet + DroidDeck + Importované + SteamDeckRepo + Steam + Obchod s body + Zpráva o úvodních videích + Uloží do textového souboru, co DroidDeck a Steam vědí o úvodních videích, aby šel přiložit k hlášení chyby. + Uložit + Uloženo do %1$s + Zprávu se nepodařilo uložit. + Hlasitost + Délka + %1$d s + Kolik sekund filmu se přehraje. Cokoli delšího se na konci odřízne. + Hledat v SteamDeckRepo + Všechna zařízení + Steam Deck + Steam Machine + Populární + Nejstahovanější + Nejoblíbenější + Nejnovější + SteamDeckRepo se nepodařilo kontaktovat + Zkusit znovu + Nenalezena žádná videa + Nainstalovat + Použít + Používá se + %1$s nainstalováno + Video se nepodařilo stáhnout + Předchozí + Další + Strana %1$d + Vymazat + Přejít na stránku + Náhled + Náhled se nepodařilo přehrát Kamery Luma Ultra — Experimentální Sledování polohy Joy-Conů Použijte kamery chytrých brýlí k umístění spárovaných ovladačů Joy-Con. Otáčení a vstupy tlačítek pocházejí z ovladačů Joy-Con. Poloha se odhaduje, když máte skrytá zápěstí. Nahrazuje ovladače ovládané holýma rukama a pozastavuje sledování fotoaparátem telefonu. Při připojování nebo resetování centra sledování namiřte ovladače Joy-Con dopředu. @@ -2934,7 +2986,6 @@ Čekání na stabilní sledování hlavy; resetování centra sledování je možné, pokud je požadováno. Pozorování kamerou je příliš staré; čekání na nový pár Přizpůsobit %1$.2f pixelům. Změřte vybranou vzdálenost od levé kamery ke středu kalibračního cíle a poté potvrďte. - OpenCV není k dispozici: %1$s Bylo obnoveno %1$d uložených zobrazení. Vypočítejte kalibraci a zkuste to znovu, nebo spusťte novou sadu a zachyťte více. Pořízeno %1$d / 24 zobrazení. Udržujte kalibrační cíl pevný; posuňte chytré brýle pro další pohled. Snímek zamítnut: %1$d / 12 požadovaných rohů viditelných v obou kamerách. Ukažte více z kalibračního cíle, nehýbejte se a zkuste to znovu. diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index e5eebc3dfa..3fe4695cba 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -176,6 +176,8 @@ %1$s via FEX Dette program er bygget til %1$s-pc’er og køres via FEX, som ikke er sat op endnu. Åbn Steam én gang, mens du er logget ind: DroidDeck downloader så FEX og den Steam Linux Runtime, det kræver, hvorefter dette åbner. Dette program + Steam-klienten kunne ikke downloades. Dit netværk eller din VPN blokerer muligvis Steams servere; tjek forbindelsen, og prøv igen. + Steam-klienten kunne ikke konfigureres. Tjek forbindelsen og den ledige lagerplads, og prøv igen. %1$s er bygget til x86-pc’er og køres via FEX, som ikke er installeret endnu. Start Steam én gang, mens du er logget ind, og lad det downloade FEX og Steam Linux Runtime, og start så dette igen. Et Flathub-app-id eller dens Flathub-side. Flatpak sættes op først, hvis det ikke allerede er. Fil @@ -538,7 +540,7 @@ Kun Adreno. Færre hak, mere batteribrug og varme. Sessionsrettelser Turnip: sysmem-rendering - Hurtigere til Steam og de fleste spil. Påkrævet på Adreno 710/720/722. + Hurtigere til Steam-klienten; i spil vælger driveren flise- eller systemhukommelses-rendering for hvert pass. Påkrævet på Adreno 710/720/722. Spring Steams xalia-hjælper over droiddeck-ntsync (eksperimentel) En stand-in til ntsync-driveren i Linux-kernen, i brugerrum, til test. Mens den er til, bruger Proton den i stedet for droiddeck-esync og droiddeck-fsync. Fungerer med Proton Experimental ARM64, GE-Proton og proton-cachyos. Gælder fra næste session. @@ -1038,6 +1040,9 @@ Tilføjet spil Brugerdefineret spil Spillager + Sletter dets filer og fjerner det fra Steam. + Fjern %1$s? + Sletter genvejen. Spillets filer bliver. Det bedste par til denne GPU, holdt opdateret Vælg et par selv Søger efter drivere… @@ -1924,6 +1929,8 @@ Butikker Butiksindstillinger Indstillinger + Arranger faner + Færdig (ikke logget ind) Butik Bibliotek @@ -2150,7 +2157,7 @@ Størrelse Gem Tilbage til standard - Tegnes oven på spillets baggrund, som Steam gør. Den præcise placering kan afvige et par pixels. + Præcis placering kan afvige med nogle få pixel. Dette spil har endnu ikke et logo. Vælg et under Logo for at se det her. Logopladeringen kunne ikke gemmes. Prøv igen. Baggrund @@ -2679,7 +2686,7 @@ Opstartsvideo Video DroidDeck · %1$d fps - 60 fps ser mere flydende ud, men bruger mere CPU, mens Steam starter. En opstartsvideo valgt i Steams egne indstillinger har forrang. + 60 fps ser mere flydende ud, men bruger mere CPU, mens Steam starter. En video valgt i Steams egne indstillinger vises også her. Lyd Din egen video MP4, MOV, MKV eller WebM. Andre formater og filer over %1$d MB konverteres til 720p-WebM på enheden, op til %2$d sekunder. @@ -2693,6 +2700,51 @@ Konverterer %1$s til Steam. Hold DroidDeck åben. Enheden kan ikke afkode videoen. Kunne ikke importere videoen + Fjern %1$s? + Dette sletter videoen fra DroidDeck og fra Steams videomappe. + Installeret + Importér + SteamDeckRepo + Lyd + Installerede videoer + Gennemse + DroidDeck + Importeret + SteamDeckRepo + Steam + Pointbutik + Rapport om startfilm + Gemmer, hvad DroidDeck og Steam ved om startfilm, i en tekstfil, som du kan vedhæfte en fejlrapport. + Gem + Gemt i %1$s + Rapporten kunne ikke gemmes. + Lydstyrke + Længde + %1$d s + Hvor mange sekunder af filmen der afspilles. Alt, hvad der er længere, klippes af til sidst. + Søg i SteamDeckRepo + Alle enheder + Steam Deck + Steam Machine + Populære + Mest downloadet + Mest likede + Nyeste + Kunne ikke få forbindelse til SteamDeckRepo + Prøv igen + Ingen videoer fundet + Installér + Brug + I brug + %1$s installeret + Kunne ikke downloade videoen + Forrige + Næste + Side %1$d + Ryd + Gå til side + Forhåndsvis + Forhåndsvisningen kunne ikke afspilles Luma Ultra-kameraer — Eksperimentel Joy-Con-positionssporing Brug smartglass-kameraerne til at placere dine parrede Joy-Con-controllere. Rotation og knapinput kommer fra Joy-Con-controllerne. Positionen estimeres, når dine håndled er skjulte. Erstatter controllere, der betjenes med bare hænder, og sætter telefonkameraets sporing på pause. Ret Joy-Con-controllerne fremad, når du tilslutter eller nulstiller sporingscentret. @@ -2866,7 +2918,6 @@ Venter på stabil hovedsporing; nulstil sporingscenter, hvis det anmodes om. Kameraobservation er for gammel; venter på et nyt par Tilpas %1$.2f px. Mål din valgte afstand fra venstre kamera til kalibreringsmålets centrum, og valider derefter. - OpenCV utilgængelig: %1$s %1$d gemte visninger gendannet. Beregn kalibrering for at prøve igen, eller start et nyt sæt for at fange mere. Optaget %1$d / 24 visninger. Hold kalibreringsmålet fast; flyt de smarte briller til næste visning. Optagelse afvist: %1$d / 12 påkrævede hjørner synlige i begge kameraer. Vis mere af kalibreringsmålet, hold stille, og prøv derefter igen. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 27564b23d6..9fe1c0e794 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -176,6 +176,8 @@ %1$s über FEX Dieses Programm ist für %1$s-PCs gebaut und läuft über FEX, das noch nicht eingerichtet ist. Öffne Steam einmal, während du angemeldet bist: DroidDeck lässt es FEX und die nötige Steam Linux Runtime herunterladen, danach lässt sich das Programm öffnen. Dieses Programm + Der Steam-Client konnte nicht heruntergeladen werden. Dein Netzwerk oder VPN blockiert möglicherweise die Server von Steam; prüfe die Verbindung und versuche es erneut. + Der Steam-Client konnte nicht eingerichtet werden. Prüfe die Verbindung und den freien Speicher und versuche es erneut. %1$s ist für x86-PCs gebaut und läuft über FEX, das noch nicht installiert ist. Starte Steam einmal, während du angemeldet bist, und lass es FEX und die Steam Linux Runtime herunterladen. Starte es danach erneut. Eine Flathub-App-ID oder ihre Flathub-Seite. Flatpak wird zuerst eingerichtet, falls noch nicht geschehen. Datei @@ -535,7 +537,7 @@ Nur Adreno. Weniger Ruckler, mehr Akkuverbrauch und Wärme. Sitzungskorrekturen Turnip: Sysmem-Rendering - Schneller für Steam und die meisten Spiele. Erforderlich bei Adreno 710/720/722. + Schneller für den Steam-Client; in Spielen wählt der Treiber pro Durchgang zwischen Kachel- und Systemspeicher-Rendering. Erforderlich bei Adreno 710/720/722. Steams xalia-Helfer überspringen droiddeck-ntsync (experimentell) Ein Userspace-Ersatz für den Linux-Treiber ntsync, zum Testen. Solange er aktiv ist, nutzt Proton ihn statt droiddeck-esync und droiddeck-fsync. Funktioniert mit Proton Experimental ARM64, GE-Proton und proton-cachyos. Gilt ab der nächsten Sitzung. @@ -1027,6 +1029,9 @@ Hinzugefügtes Spiel Eigenes Spiel Spielspeicher + Löscht seine Dateien und entfernt es aus Steam. + %1$s entfernen? + Löscht die Verknüpfung. Die Spieldateien bleiben. Das beste Paar für diese GPU, stets aktuell Wähle selbst ein Paar Suche nach Treibern… @@ -1913,6 +1918,8 @@ Stores Store-Einstellungen Einstellungen + Tabs anordnen + Fertig (nicht angemeldet) Store Bibliothek @@ -2136,7 +2143,7 @@ Größe Speichern Auf Standard zurücksetzen - Wird wie bei Steam über dem Spielehintergrund gezeichnet. Die Position kann um einige Pixel abweichen. + Die genaue Position kann um einige Pixel abweichen. Für dieses Spiel gibt es noch kein Logo. Wähle unter Logo eines aus, um es hier zu sehen. Die Logoposition ließ sich nicht speichern. Versuche es erneut. Hintergrund @@ -2679,7 +2686,7 @@ Bootvideo Video DroidDeck · %1$d fps - 60 fps wirkt flüssiger, braucht aber mehr CPU, während Steam startet. Ein in Steam selbst gewähltes Startvideo hat Vorrang. + 60 fps wirkt flüssiger, braucht aber mehr CPU, während Steam startet. Ein in Steam selbst gewähltes Video erscheint hier ebenfalls. Ton Eigenes Video MP4, MOV, MKV oder WebM. Andere Formate und Dateien über %1$d MB werden auf dem Gerät in 720p-WebM umgewandelt, bis %2$d Sekunden. @@ -2693,6 +2700,51 @@ %1$s wird für Steam umgewandelt. DroidDeck geöffnet lassen. Dieses Gerät kann das Video nicht dekodieren. Das Video konnte nicht importiert werden + %1$s entfernen? + Dadurch wird das Video aus DroidDeck und aus dem Videoordner von Steam gelöscht. + Installiert + Importieren + SteamDeckRepo + Ton + Installierte Videos + Durchsuchen + DroidDeck + Importiert + SteamDeckRepo + Steam + Punkteshop + Bericht zu Startfilmen + Speichert in einer Textdatei, was DroidDeck und Steam über Startfilme wissen, zum Anhängen an einen Fehlerbericht. + Speichern + Gespeichert unter %1$s + Der Bericht konnte nicht gespeichert werden. + Lautstärke + Länge + %1$d s + Wie viele Sekunden des Films abgespielt werden. Alles, was länger ist, wird am Ende abgeschnitten. + SteamDeckRepo durchsuchen + Alle Geräte + Steam Deck + Steam Machine + Im Trend + Meistgeladen + Beliebteste + Neueste + SteamDeckRepo ist nicht erreichbar + Erneut versuchen + Keine Videos gefunden + Installieren + Verwenden + In Verwendung + %1$s installiert + Das Video konnte nicht heruntergeladen werden + Zurück + Weiter + Seite %1$d + Leeren + Zur Seite + Vorschau + Die Vorschau konnte nicht abgespielt werden Luma Ultra-Kameras – Experimentell Joy-Con-Positionsverfolgung Positionieren Sie Ihre gekoppelten Joy-Con-Controller mithilfe der Kameras Ihrer Smartbrille. Drehung und Tasteneingaben erfolgen über die Joy-Con-Controller. Die Position wird geschätzt, wenn Ihre Handgelenke verdeckt sind. Ersetzt Controller, die mit bloßen Händen bedient werden, und pausiert die Verfolgung per Smartphone-Kamera. Richten Sie die Joy-Con-Controller nach vorn, wenn Sie die Verbindung herstellen oder das Tracking-Center zurücksetzen. @@ -2866,7 +2918,6 @@ Warten auf stabiles Head-Tracking; Tracking-Zentrum bei Bedarf zurücksetzen. Kamerabeobachtung ist zu alt; warte auf ein neues Paar %1$.2f px anpassen. Messen Sie den ausgewählten Abstand von der linken Kamera zum Zentrum des Kalibrierungsziels und bestätigen Sie ihn anschließend. - OpenCV nicht verfügbar: %1$s %1$d gespeicherte Ansichten wiederhergestellt. Berechnen Sie die Kalibrierung, um es erneut zu versuchen, oder starten Sie einen neuen Satz, um mehr zu erfassen. Aufgenommen %1$d / 24 Aufrufe. Halten Sie das Kalibrierungsziel fest; Bewegen Sie die Datenbrille für die nächste Ansicht. Aufnahme abgelehnt: %1$d / 12 erforderliche Ecken in beiden Kameras sichtbar. Zeigen Sie mehr vom Kalibrierungsziel, halten Sie still und versuchen Sie es dann erneut. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 70790dc77f..14f83431cf 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -176,6 +176,8 @@ %1$s μέσω FEX Αυτό το πρόγραμμα είναι χτισμένο για υπολογιστές %1$s και εκτελείται μέσω FEX, το οποίο δεν έχει ρυθμιστεί ακόμα. Ανοίξτε το Steam μία φορά ενώ είστε συνδεδεμένοι: το DroidDeck κάνει λήψη του FEX και του Steam Linux Runtime που χρειάζεται, και μετά αυτό ανοίγει. Αυτό το πρόγραμμα + Δεν ήταν δυνατή η λήψη του πελάτη Steam. Το δίκτυο ή το VPN σας ίσως αποκλείει τους διακομιστές του Steam· ελέγξτε τη σύνδεση και δοκιμάστε ξανά. + Δεν ήταν δυνατή η ρύθμιση του πελάτη Steam. Ελέγξτε τη σύνδεση και τον ελεύθερο χώρο αποθήκευσης και δοκιμάστε ξανά. Το %1$s είναι χτισμένο για υπολογιστές x86 και εκτελείται μέσω FEX, το οποίο δεν έχει εγκατασταθεί ακόμα. Εκκινήστε το Steam μία φορά ενώ είστε συνδεδεμένοι και αφήστε το να κάνει λήψη του FEX και του Steam Linux Runtime, μετά εκκινήστε αυτό ξανά. Ένα ID εφαρμογής Flathub ή η σελίδα της στο Flathub. Το Flatpak ρυθμίζεται πρώτα, αν δεν έχει ρυθμιστεί ακόμα. Αρχείο @@ -538,7 +540,7 @@ Μόνο Adreno. Λιγότερα κολλήματα, μεγαλύτερη χρήση μπαταρίας και θερμότητα. Διορθώσεις συνεδρίας Turnip: απόδοση sysmem - Ταχύτερο για το Steam και τα περισσότερα παιχνίδια. Απαιτείται σε Adreno 710/720/722. + Ταχύτερο για το πρόγραμμα-πελάτη Steam· στα παιχνίδια ο οδηγός επιλέγει σε κάθε πέρασμα απόδοση με πλακίδια ή στη μνήμη συστήματος. Απαιτείται σε Adreno 710/720/722. Παράβλεψη του βοηθού xalia του Steam droiddeck-ntsync (πειραματικό) Ένα υποκατάστατο σε επίπεδο χρήστη για το πρόγραμμα οδήγησης ntsync του Linux, για δοκιμές. Όσο είναι ενεργό, το Proton το χρησιμοποιεί αντί για το droiddeck-esync και το droiddeck-fsync. Λειτουργεί με Proton Experimental ARM64, GE-Proton και proton-cachyos. Εφαρμόζεται στην επόμενη συνεδρία. @@ -1038,6 +1040,9 @@ Προστέθηκε παιχνίδι Προσαρμοσμένο παιχνίδι Αποθήκευση παιχνιδιών + Διαγράφει τα αρχεία του και το αφαιρεί από το Steam. + Αφαίρεση του %1$s; + Διαγράφει τη συντόμευση. Τα αρχεία του παιχνιδιού παραμένουν. Το καλύτερο ζεύγος για αυτή τη GPU, ενημερωμένο Επιλέξτε ένα ζεύγος εσείς Έλεγχος για προγράμματα οδήγησης… @@ -1924,6 +1929,8 @@ Καταστήματα Ρυθμίσεις καταστημάτων Ρυθμίσεις + Τακτοποίηση καρτελών + Έγινε (μη συνδεδεμένος) Κατάστημα Βιβλιοθήκη @@ -2150,7 +2157,7 @@ Μέγεθος Αποθήκευση Επαναφορά στην προεπιλογή - Σχεδιάζεται πάνω από το φόντο του παιχνιδιού, όπως κάνει το Steam. Η ακριβής θέση μπορεί να διαφέρει μερικά pixel. + Ακριβώς αυτή η θέση μπορεί να διαφέρει κατά μερικά pixel. Αυτό το παιχνίδι δεν έχει λογότυπο ακόμη. Διάλεξε ένα στο Λογότυπο για να το δεις εδώ. Η θέση του λογότυπου δεν αποθηκεύτηκε. Δοκίμασε ξανά. Φόντο @@ -2679,7 +2686,7 @@ Βίντεο εκκίνησης Βίντεο DroidDeck · %1$d fps - Τα 60 fps φαίνονται πιο ομαλά, αλλά επιβαρύνουν περισσότερο τον επεξεργαστή όσο ξεκινά το Steam. Ένα βίντεο εκκίνησης που επιλέχθηκε στις ρυθμίσεις του Steam έχει προτεραιότητα. + Τα 60 fps φαίνονται πιο ομαλά, αλλά επιβαρύνουν περισσότερο τον επεξεργαστή όσο ξεκινά το Steam. Ένα βίντεο που επιλέχθηκε στις ρυθμίσεις του Steam εμφανίζεται κι εδώ. Ήχος Δικό σας βίντεο MP4, MOV, MKV ή WebM. Άλλες μορφές και αρχεία πάνω από %1$d MB μετατρέπονται στη συσκευή σε WebM 720p, έως %2$d δευτερόλεπτα. @@ -2693,6 +2700,51 @@ Μετατροπή του %1$s για το Steam. Αφήστε το DroidDeck ανοιχτό. Η συσκευή δεν μπορεί να αποκωδικοποιήσει αυτό το βίντεο. Δεν ήταν δυνατή η εισαγωγή του βίντεο + Αφαίρεση του %1$s; + Το βίντεο θα διαγραφεί από το DroidDeck και από τον φάκελο βίντεο του Steam. + Εγκατεστημένα + Εισαγωγή + SteamDeckRepo + Ήχος + Εγκατεστημένα βίντεο + Περιήγηση + DroidDeck + Εισαγμένο + SteamDeckRepo + Steam + Κατάστημα πόντων + Αναφορά ταινιών εκκίνησης + Αποθηκεύει σε αρχείο κειμένου ό,τι γνωρίζουν το DroidDeck και το Steam για τις ταινίες εκκίνησης, για να το επισυνάψετε σε αναφορά σφάλματος. + Αποθήκευση + Αποθηκεύτηκε στο %1$s + Δεν ήταν δυνατή η αποθήκευση της αναφοράς. + Ένταση + Διάρκεια + %1$d δευτ. + Πόσα δευτερόλεπτα της ταινίας αναπαράγονται. Ό,τι είναι μεγαλύτερο κόβεται στο τέλος. + Αναζήτηση στο SteamDeckRepo + Όλες οι συσκευές + Steam Deck + Steam Machine + Τάσεις + Περισσότερες λήψεις + Περισσότερα likes + Νεότερα + Δεν ήταν δυνατή η σύνδεση με το SteamDeckRepo + Επανάληψη + Δεν βρέθηκαν βίντεο + Εγκατάσταση + Χρήση + Σε χρήση + Το %1$s εγκαταστάθηκε + Δεν ήταν δυνατή η λήψη αυτού του βίντεο + Προηγούμενη + Επόμενη + Σελίδα %1$d + Εκκαθάριση + Μετάβαση στη σελίδα + Προεπισκόπηση + Η προεπισκόπηση δεν μπόρεσε να αναπαραχθεί Κάμερες Luma Ultra — Πειραματικό Παρακολούθηση θέσης Joy-Con Χρησιμοποιήστε τις κάμερες των έξυπνων γυαλιών για να τοποθετήσετε τα συνδεδεμένα χειριστήρια Joy-Con. Η περιστροφή και οι εντολές κουμπιών προέρχονται από τα χειριστήρια Joy-Con. Η θέση εκτιμάται όταν οι καρποί σας είναι κρυμμένοι. Αντικαθιστά τα χειριστήρια που λειτουργούν με γυμνά χέρια και διακόπτει την παρακολούθηση της κάμερας του τηλεφώνου. Στρέψτε τα χειριστήρια Joy-Con προς τα εμπρός κατά τη σύνδεση ή την επαναφορά του κέντρου παρακολούθησης. @@ -2866,7 +2918,6 @@ Αναμονή για σταθερή παρακολούθηση κεφαλής. Επαναφέρετε το κέντρο παρακολούθησης εάν ζητηθεί Η παρατήρηση με κάμερα είναι πολύ παλιά. περιμένοντας ένα φρέσκο ζευγάρι Προσαρμογή %1$.2f px. Μετρήστε την επιλεγμένη απόσταση από την αριστερή κάμερα μέχρι το κέντρο στόχου βαθμονόμησης και, στη συνέχεια, επικυρώστε. - Το OpenCV δεν είναι διαθέσιμο: %1$s Αποκαταστάθηκαν οι αποθηκευμένες προβολές %1$d. Υπολογίστε τη βαθμονόμηση για να προσπαθήσετε ξανά ή ξεκινήστε ένα νέο σύνολο για να καταγράψετε περισσότερα. Λήψη %1$d / 24 προβολές. Διατηρήστε σταθερό τον στόχο βαθμονόμησης. μετακινήστε τα έξυπνα γυαλιά για την επόμενη προβολή. Η λήψη απορρίφθηκε: %1$d / 12 απαιτούμενες γωνίες ορατές και στις δύο κάμερες. Εμφάνιση μεγαλύτερου μέρους του στόχου βαθμονόμησης, κρατήστε ακίνητο και μετά δοκιμάστε ξανά. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 0d3475efe4..ea6e05fb38 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -176,6 +176,8 @@ %1$s con FEX Este programa está hecho para PC %1$s y se ejecuta con FEX, que aún no está listo. Abre Steam una vez con tu sesión iniciada: DroidDeck hará que descargue FEX y el Steam Linux Runtime que necesita, y después se abrirá. Este programa + No se ha podido descargar el cliente de Steam. Puede que tu red o VPN esté bloqueando los servidores de Steam; comprueba la conexión y vuelve a intentarlo. + No se ha podido configurar el cliente de Steam. Comprueba la conexión y el espacio libre y vuelve a intentarlo. %1$s está hecho para PC x86 y se ejecuta con FEX, que aún no está instalado. Abre Steam una vez con tu sesión iniciada y deja que descargue FEX y el Steam Linux Runtime; después vuelve a iniciarlo. Un ID de app de Flathub o su página en Flathub. Flatpak se configura primero si aún no lo está. Archivo @@ -537,7 +539,7 @@ Solo Adreno. Menos tirones, más consumo de batería y calor. Correcciones de sesión Turnip: renderizado sysmem - Más rápido para Steam y la mayoría de juegos. Obligatorio en Adreno 710/720/722. + Más rápido para el cliente de Steam; en los juegos, el controlador elige entre renderizado por mosaicos o en memoria del sistema en cada pasada. Obligatorio en Adreno 710/720/722. Omitir el asistente xalia de Steam droiddeck-ntsync (experimental) Un sustituto en espacio de usuario del controlador ntsync de Linux, para pruebas. Mientras está activado, Proton lo usa en lugar de droiddeck-esync y droiddeck-fsync. Funciona con Proton Experimental ARM64, GE-Proton y proton-cachyos. Se aplica en la próxima sesión. @@ -1041,6 +1043,9 @@ Juego añadido Juego personalizado Almacenamiento de juegos + Elimina sus archivos y lo quita de Steam. + ¿Quitar %1$s? + Elimina su acceso directo. Los archivos del juego se conservan. El mejor par para esta GPU, siempre actualizado Elige un par manualmente Buscando controladores… @@ -1942,6 +1947,8 @@ Tiendas Ajustes de las tiendas Ajustes + Organizar pestañas + Listo (sin iniciar sesión) Tienda Biblioteca @@ -2165,7 +2172,7 @@ Tamaño Guardar Volver al valor predeterminado - Se dibuja sobre el fondo del juego, igual que en Steam. La posición exacta puede variar unos píxeles. + Este punto exacto puede variar unos pocos píxeles. Este juego aún no tiene logotipo. Elige uno en Logotipo para verlo aquí. No se pudo guardar la posición del logotipo. Inténtalo de nuevo. Fondo @@ -2713,7 +2720,7 @@ Vídeo de arranque Vídeo DroidDeck · %1$d fps - 60 fps se ve más fluido pero usa más CPU mientras Steam se inicia. Un vídeo de inicio elegido en los ajustes de Steam tiene prioridad. + 60 fps se ve más fluido pero usa más CPU mientras Steam se inicia. Un vídeo elegido en los ajustes de Steam también aparece aquí. Sonido Tu propio vídeo MP4, MOV, MKV o WebM. Otros formatos y archivos de más de %1$d MB se convierten a WebM 720p en el dispositivo, hasta %2$d segundos. @@ -2727,6 +2734,51 @@ Convirtiendo %1$s para Steam. Mantén DroidDeck abierto. Este dispositivo no puede decodificar ese vídeo. No se pudo importar ese vídeo + ¿Quitar %1$s? + Esto elimina el vídeo de DroidDeck y de la carpeta de vídeos de Steam. + Instalados + Importar + SteamDeckRepo + Sonido + Vídeos instalados + Explorar + DroidDeck + Importado + SteamDeckRepo + Steam + Tienda de puntos + Informe de películas de arranque + Guarda en un archivo de texto lo que DroidDeck y Steam saben de las películas de arranque, para adjuntarlo a un informe de error. + Guardar + Guardado en %1$s + No se pudo guardar el informe. + Volumen + Duración + %1$d s + Cuántos segundos de la película se reproducen. Lo que dure más se corta al final. + Buscar en SteamDeckRepo + Todos los dispositivos + Steam Deck + Steam Machine + Tendencias + Más descargados + Más valorados + Más recientes + No se pudo acceder a SteamDeckRepo + Reintentar + No se encontraron vídeos + Instalar + Usar + En uso + %1$s instalado + No se pudo descargar ese vídeo + Anterior + Siguiente + Página %1$d + Borrar + Ir a la página + Vista previa + No se pudo reproducir la vista previa Cámaras Luma Ultra — Experimental Seguimiento de posición de los Joy-Con Usa las cámaras de las gafas inteligentes para posicionar tus mandos Joy-Con emparejados. La rotación y las pulsaciones de los botones provienen de los mandos Joy-Con. La posición se estima cuando tus muñecas están ocultas. Reemplaza los mandos operados con las manos desnudas y pausa el seguimiento de la cámara del teléfono. Apunta los mandos Joy-Con hacia adelante al conectar o restablecer el centro de seguimiento. @@ -2900,7 +2952,6 @@ Esperando un seguimiento de cabeza estable; restablece el centro de seguimiento si se solicita. La observación con cámara es demasiado antigua; esperando un par nuevo Ajustar %1$.2f px. Mida la distancia seleccionada desde la cámara izquierda hasta el centro del objetivo de calibración y luego valide. - OpenCV no disponible: %1$s %1$d vistas guardadas restauradas. Calcule la calibración para volver a intentarlo o comience un nuevo conjunto para capturar más. Capturado %1$d / 24 vistas. Mantenga fijo el objetivo de calibración; Mueva las gafas inteligentes para la siguiente vista. Captura rechazada: %1$d / 12 esquinas requeridas visibles en ambas cámaras. Muestre más del objetivo de calibración, quédese quieto y vuelva a intentarlo. diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index c207b4e4c3..680b9c455c 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -176,6 +176,8 @@ %1$s FEXin kautta Tämä ohjelma on tehty %1$s-tietokoneille ja käynnistyy FEXin kautta, jota ei ole vielä määritetty. Avaa Steam kerran kirjautuneena: DroidDeck lataa sen myötä FEXin ja tarvittavan Steam Linux Runtimen, jonka jälkeen tämä avautuu. Tämä ohjelma + Steam-asiakasohjelmaa ei voitu ladata. Verkkosi tai VPN saattaa estää Steamin palvelimet; tarkista yhteys ja yritä uudelleen. + Steam-asiakasohjelmaa ei voitu ottaa käyttöön. Tarkista yhteys ja vapaa tallennustila ja yritä uudelleen. %1$s on tehty x86-tietokoneille ja käynnistyy FEXin kautta, jota ei ole vielä asennettu. Käynnistä Steam kerran kirjautuneena ja anna sen ladata FEX ja Steam Linux Runtime, sitten käynnistä tämä uudelleen. Flathub-sovellustunnus tai sen Flathub-sivu. Flatpak otetaan käyttöön ensin, jos sitä ei ole vielä otettu. Tiedosto @@ -538,7 +540,7 @@ Vain Adreno. Vähemmän nykäyksiä, enemmän akun kulutusta ja lämpöä. Istunnon korjaukset Turnip: sysmem-renderöinti - Nopeampi Steamille ja useimmille peleille. Pakollinen Adreno 710/720/722:lla. + Nopeampi Steam-asiakasohjelmalle; peleissä ajuri valitsee jokaiselle vaiheelle ruuduittaisen tai järjestelmämuistiin tehtävän renderöinnin. Pakollinen Adreno 710/720/722:lla. Ohita Steamin xalia-avustaja droiddeck-ntsync (kokeellinen) Käyttäjätilainen korvike Linuxin ntsync-ajurille, testausta varten. Kun se on päällä, Proton käyttää sitä droiddeck-esyncin ja droiddeck-fsyncin sijaan. Toimii Proton Experimental ARM64:n, GE-Protonin ja proton-cachyosin kanssa. Tulee voimaan seuraavassa istunnossa. @@ -1038,6 +1040,9 @@ Lisätty peli Mukautettu peli Pelien tallennustila + Poistaa sen tiedostot ja poistaa sen Steamista. + Poistetaanko %1$s? + Poistaa pikakuvakkeen. Pelin tiedostot jäävät. Parhaiten tähän GPU:hun sopiva pari, pidetään ajan tasalla Valitse pari itse Tarkistetaan ajureita… @@ -1924,6 +1929,8 @@ Kaupat Kauppojen asetukset Asetukset + Järjestä välilehdet + Valmis (ei kirjautunut) Kauppa Kirjasto @@ -2150,7 +2157,7 @@ Koko Tallenna Takaisin oletukseen - Piirretään pelin taustan päälle, kuten Steam tekee. Tarkka sijainti voi poiketa muutaman pikselin. + Tämä tarkka kohta voi vaihdella muutamalla pikselillä. Tällä pelillä ei ole vielä logoa. Valitse sellainen kohdasta Logo, niin näet sen tässä. Logon sijaintia ei voitu tallentaa. Yritä uudelleen. Tausta @@ -2679,7 +2686,7 @@ Käynnistysvideo Video DroidDeck · %1$d fps - 60 fps näyttää sulavammalta, mutta kuormittaa suoritinta enemmän Steamin käynnistyessä. Steamin omista asetuksista valittu käynnistysvideo on etusijalla. + 60 fps näyttää sulavammalta, mutta kuormittaa suoritinta enemmän Steamin käynnistyessä. Steamin omista asetuksista valittu video näkyy myös täällä. Ääni Oma video MP4, MOV, MKV tai WebM. Muut muodot ja yli %1$d Mt:n tiedostot muunnetaan laitteella 720p-WebM-muotoon, enintään %2$d sekuntia. @@ -2693,6 +2700,51 @@ Muunnetaan %1$s Steamille. Pidä DroidDeck auki. Laite ei pysty purkamaan videota. Videon tuonti epäonnistui + Poistetaanko %1$s? + Tämä poistaa videon DroidDeckistä ja Steamin videokansiosta. + Asennetut + Tuo + SteamDeckRepo + Ääni + Asennetut videot + Selaa + DroidDeck + Tuotu + SteamDeckRepo + Steam + Pisteputiikki + Käynnistyselokuvaraportti + Tallentaa tekstitiedostoon, mitä DroidDeck ja Steam tietävät käynnistyselokuvista, liitettäväksi virheilmoitukseen. + Tallenna + Tallennettu: %1$s + Raportin tallennus epäonnistui. + Äänenvoimakkuus + Pituus + %1$d s + Kuinka monta sekuntia elokuvasta toistetaan. Sitä pidempi osa leikataan pois lopusta. + Hae SteamDeckReposta + Kaikki laitteet + Steam Deck + Steam Machine + Trendaavat + Ladatuimmat + Tykätyimmät + Uusimmat + SteamDeckRepoon ei saatu yhteyttä + Yritä uudelleen + Videoita ei löytynyt + Asenna + Käytä + Käytössä + %1$s asennettu + Videota ei voitu ladata + Edellinen + Seuraava + Sivu %1$d + Tyhjennä + Siirry sivulle + Esikatselu + Esikatselua ei voitu toistaa Luma Ultra -kamerat — Kokeellinen Joy-Con-paikan seuranta Käytä älylasien kameroita pariliitettyjen Joy-Con-ohjainten asemointiin. Kierto- ja painikesyötteet tulevat Joy-Con-ohjaimista. Sijainti arvioidaan, kun ranteesi ovat piilossa. Korvaa paljain käsin käytettävät ohjaimet ja keskeyttää puhelimen kameran seurannan. Osoita Joy-Con-ohjaimet eteenpäin, kun yhdistät tai nollaat seurantakeskuksen. @@ -2866,7 +2918,6 @@ Odotetaan vakaata pään seurantaa; nollaa seurantakeskus pyydettäessä. Kamerahavainto on liian vanha; uutta paria odotellessa Sovita %1$.2f px. Mittaa valitsemasi etäisyys vasemmasta kamerasta kalibrointikohteen keskustaan ​​ja vahvista sitten. - OpenCV ei saatavilla: %1$s %1$d tallennettua näkymää palautettu. Laske kalibrointi yrittääksesi uudelleen tai aloita uusi sarja, jos haluat ottaa lisää. Kuvattu %1$d / 24 katselukertaa. Pidä kalibrointitavoite kiinteänä; siirrä älylaseja seuraavaa näkymää varten. Kuvaus hylätty: %1$d / 12 vaadittua kulmaa näkyvissä molemmissa kameroissa. Näytä lisää kalibrointikohdetta, pidä paikallaan ja yritä sitten uudelleen. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 49d3020809..1072156283 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -176,6 +176,8 @@ %1$s via FEX Ce programme est conçu pour les PC %1$s et s\'exécute via FEX, qui n\'est pas encore configuré. Ouvrez Steam une fois en étant connecté : DroidDeck lui fait télécharger FEX et le Steam Linux Runtime nécessaires, puis ce programme s\'ouvre. Ce programme + Impossible de télécharger le client Steam. Votre réseau ou votre VPN bloque peut-être les serveurs de Steam ; vérifiez la connexion et réessayez. + Impossible de configurer le client Steam. Vérifiez la connexion et l\'espace libre, puis réessayez. %1$s est conçu pour les PC x86 et s\'exécute via FEX, qui n\'est pas encore installé. Lancez Steam une fois en étant connecté et laissez-le télécharger FEX et le Steam Linux Runtime, puis relancez ce programme. ID d\'application Flathub ou sa page Flathub. Si Flatpak n\'est pas encore configuré, il le sera d\'abord. Fichier @@ -537,7 +539,7 @@ Uniquement pour Adreno. Moins de saccades, mais plus de consommation d\'énergie et de chaleur. Correctifs de session Turnip : rendu sysmem - Steam et la plupart des jeux seront plus rapides. Requis pour Adreno 710/720/722. + Le client Steam sera plus rapide ; en jeu, le pilote choisit à chaque passe entre rendu par tuiles et rendu en mémoire système. Requis pour Adreno 710/720/722. Ignorer l\'assistant xalia de Steam droiddeck-ntsync (expérimental) Un substitut en espace utilisateur du pilote Linux ntsync, pour les tests. Lorsqu\'il est activé, Proton l\'utilise à la place de droiddeck-esync et de droiddeck-fsync. Fonctionne avec Proton Experimental ARM64, GE-Proton et proton-cachyos. Prendra effet à la prochaine session. @@ -1041,6 +1043,9 @@ Jeux ajoutés Jeu personnalisé Stockage des jeux + Supprime ses fichiers et le retire de Steam. + Retirer %1$s ? + Supprime son raccourci. Les fichiers du jeu restent. Sélectionne la meilleure combinaison de pilotes pour ce GPU et les maintient à jour Choisir manuellement la combinaison de pilotes Vérification des pilotes… @@ -1942,6 +1947,8 @@ Boutiques Paramètres des boutiques Paramètres + Organiser les onglets + Terminé (non connecté) Boutique Bibliothèque @@ -2165,7 +2172,7 @@ Taille Enregistrer Rétablir par défaut - Dessiné sur l\'arrière-plan du jeu, comme le fait Steam. La position exacte peut varier de quelques pixels. + Cet emplacement exact peut varier de quelques pixels. Ce jeu n\'a pas encore de logo. Choisissez-en un dans Logo pour le voir ici. Impossible d\'enregistrer la position du logo. Réessayez. Arrière-plan @@ -2713,7 +2720,7 @@ Vidéo de démarrage Vidéo DroidDeck · %1$d i/s - 60 i/s est plus fluide mais sollicite davantage le processeur pendant le démarrage de Steam. Une vidéo de démarrage choisie dans les paramètres de Steam est prioritaire. + 60 i/s est plus fluide mais sollicite davantage le processeur pendant le démarrage de Steam. Une vidéo choisie dans les paramètres de Steam apparaît aussi ici. Son Votre propre vidéo MP4, MOV, MKV ou WebM. Les autres formats et les fichiers de plus de %1$d Mo sont convertis en WebM 720p sur l\'appareil, jusqu\'à %2$d secondes. @@ -2727,6 +2734,51 @@ Conversion de %1$s pour Steam. Gardez DroidDeck ouvert. Cet appareil ne peut pas décoder cette vidéo. Impossible d\'importer cette vidéo + Supprimer %1$s ? + Cela supprime la vidéo de DroidDeck et du dossier de vidéos de Steam. + Installées + Importer + SteamDeckRepo + Son + Vidéos installées + Parcourir + DroidDeck + Importée + SteamDeckRepo + Steam + Boutique de points + Rapport sur les vidéos de démarrage + Enregistre dans un fichier texte ce que DroidDeck et Steam savent des vidéos de démarrage, à joindre à un rapport de bogue. + Enregistrer + Enregistré dans %1$s + Impossible d\'enregistrer le rapport. + Volume + Durée + %1$d s + Nombre de secondes du film qui sont lues. Tout ce qui dépasse est coupé à la fin. + Rechercher dans SteamDeckRepo + Tous les appareils + Steam Deck + Steam Machine + Tendances + Les plus téléchargées + Les plus aimées + Les plus récentes + Impossible de joindre SteamDeckRepo + Réessayer + Aucune vidéo trouvée + Installer + Utiliser + Utilisé + %1$s installée + Impossible de télécharger cette vidéo + Précédent + Suivant + Page %1$d + Effacer + Aller à la page + Aperçu + Impossible de lire cet aperçu Caméras Luma Ultra — Expérimental Suivi de la position des Joy-Con Utilisez les caméras des lunettes connectées pour positionner vos manettes Joy-Con appariées. La rotation et les entrées des boutons proviennent des manettes Joy-Con. La position est estimée lorsque vos poignets sont cachés. Remplace les manettes utilisées à mains nues et interrompt le suivi par la caméra du téléphone. Pointez les manettes Joy-Con vers l\'avant lors de la connexion ou de la réinitialisation du centre de suivi. @@ -2900,7 +2952,6 @@ Attente d\'un suivi de tête stable ; réinitialisation du centre de suivi si demandé. L\'observation par caméra est trop ancienne ; en attendant une nouvelle paire Ajuster %1$.2f px. Mesurez la distance sélectionnée entre la caméra gauche et le centre de la cible de calibrage, puis validez. - OpenCV indisponible : %1$s %1$d vues enregistrées restaurées. Calculez l’étalonnage pour réessayer ou démarrez un nouvel ensemble pour en capturer davantage. Capturé %1$d / 24 vues. Gardez la cible d\'étalonnage fixe ; déplacez les lunettes intelligentes pour la vue suivante. Capture rejetée : %1$d / 12 coins requis visibles dans les deux caméras. Affichez davantage la cible d\'étalonnage, restez immobile, puis réessayez. diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index b170099052..2a246077fb 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -176,6 +176,8 @@ FEX के ज़रिए %1$s यह प्रोग्राम %1$s पीसी के लिए बना है और FEX के ज़रिए चलता है, जो अभी सेट नहीं है। साइन इन रहते हुए Steam एक बार खोलें: DroidDeck इससे FEX और ज़रूरी Steam Linux Runtime डाउनलोड करवा लेगा, फिर यह खुल जाएगा। यह प्रोग्राम + Steam क्लाइंट डाउनलोड नहीं हो सका। हो सकता है आपका नेटवर्क या VPN Steam के सर्वर ब्लॉक कर रहा हो; कनेक्शन जांचें और फिर से कोशिश करें। + Steam क्लाइंट सेट अप नहीं हो सका। कनेक्शन और खाली स्टोरेज जांचें, फिर से कोशिश करें। %1$s x86 पीसी के लिए बना है और FEX के ज़रिए चलता है, जो अभी इंस्टॉल नहीं है। साइन इन रहते हुए Steam एक बार शुरू करें और इसे FEX और Steam Linux Runtime डाउनलोड करने दें, फिर इसे फिर से शुरू करें। एक Flathub ऐप ID या उसका Flathub पेज। अगर Flatpak अभी सेट नहीं है, तो पहले वह सेट होगा। फ़ाइल @@ -538,7 +540,7 @@ सिर्फ़ Adreno के लिए। कम हिचकोले, लेकिन ज़्यादा बैटरी खर्च और गर्मी। सेशन फ़िक्स Turnip: sysmem रेंडरिंग - Steam और ज़्यादातर गेम के लिए तेज़। Adreno 710/720/722 पर ज़रूरी। + Steam क्लाइंट के लिए तेज़; गेम में ड्राइवर हर पास के लिए टाइल या सिस्टम मेमोरी रेंडरिंग चुनता है। Adreno 710/720/722 पर ज़रूरी। Steam के xalia हेल्पर को छोड़ें droiddeck-ntsync (एक्सपेरिमेंटल) जांच के लिए Linux ntsync ड्राइवर की यूज़रस्पेस जगह लेने वाली चीज़। चालू रहते हुए, Proton इसे droiddeck-esync और droiddeck-fsync के बदले इस्तेमाल करता है। यह Proton Experimental ARM64, GE-Proton और proton-cachyos के साथ काम करता है। अगले सेशन से लागू होता है। @@ -1038,6 +1040,9 @@ जोड़ा गया गेम कस्टम गेम गेम स्टोरेज + इसकी फ़ाइलें हटाता है और इसे Steam से हटा देता है। + %1$s हटाएं? + इसका शॉर्टकट हटाता है। गेम की फ़ाइलें बनी रहती हैं। इस GPU के लिए सबसे बेहतर जोड़ी, हमेशा नवीनतम खुद एक जोड़ी चुनें ड्राइवर देखे जा रहे हैं… @@ -1924,6 +1929,8 @@ स्टोर स्टोर सेटिंग सेटिंग + टैब व्यवस्थित करें + हो गया (साइन इन नहीं है) स्टोर लाइब्रेरी @@ -2150,7 +2157,7 @@ आकार सहेजें डिफ़ॉल्ट पर लौटाएँ - गेम की पृष्ठभूमि के ऊपर बनता है, जैसे Steam करता है। सटीक स्थिति कुछ पिक्सेल अलग हो सकती है। + यह सटीक जगह कुछ पिक्सल तक अलग हो सकती है। इस गेम का लोगो अभी नहीं है। यहाँ देखने के लिए लोगो में से कोई चुनें। लोगो की स्थिति सहेजी नहीं जा सकी। फिर कोशिश करें। बैकग्राउंड @@ -2679,7 +2686,7 @@ बूट वीडियो वीडियो DroidDeck · %1$d fps - 60 fps ज़्यादा स्मूथ दिखता है, लेकिन Steam शुरू होते समय CPU ज़्यादा इस्तेमाल करता है। Steam की अपनी सेटिंग्स में चुना गया स्टार्टअप वीडियो प्राथमिकता लेता है। + 60 fps ज़्यादा स्मूथ दिखता है, लेकिन Steam शुरू होते समय CPU ज़्यादा इस्तेमाल करता है। Steam की अपनी सेटिंग्स में चुना गया वीडियो यहाँ भी दिखता है। आवाज़ अपना वीडियो MP4, MOV, MKV या WebM. दूसरे फ़ॉर्मैट और %1$d MB से बड़ी फ़ाइलें डिवाइस पर 720p WebM में बदली जाती हैं, %2$d सेकंड तक। @@ -2693,6 +2700,51 @@ %1$s को Steam के लिए बदला जा रहा है। DroidDeck खुला रखें। यह डिवाइस उस वीडियो को डिकोड नहीं कर सकता। वीडियो इंपोर्ट नहीं हो सका + %1$s हटाएं? + इससे वीडियो DroidDeck और Steam के वीडियो फ़ोल्डर से मिट जाएगा। + इंस्टॉल किए गए + इंपोर्ट करें + SteamDeckRepo + आवाज़ + इंस्टॉल किए गए वीडियो + ब्राउज़ करें + DroidDeck + इंपोर्ट किया गया + SteamDeckRepo + Steam + पॉइंट्स शॉप + बूट वीडियो रिपोर्ट + बूट वीडियो के बारे में DroidDeck और Steam की जानकारी एक टेक्स्ट फ़ाइल में सहेजता है, जिसे आप बग रिपोर्ट के साथ जोड़ सकते हैं। + सहेजें + %1$s में सहेजा गया + रिपोर्ट सहेजी नहीं जा सकी। + वॉल्यूम + अवधि + %1$d सेक + वीडियो के कितने सेकंड चलेंगे। इससे लंबा हिस्सा अंत में काट दिया जाता है। + SteamDeckRepo में खोजें + सभी डिवाइस + Steam Deck + Steam Machine + ट्रेंडिंग + सबसे ज़्यादा डाउनलोड किए गए + सबसे ज़्यादा पसंद किए गए + सबसे नए + SteamDeckRepo से कनेक्ट नहीं हो सका + फिर कोशिश करें + कोई वीडियो नहीं मिला + इंस्टॉल करें + इस्तेमाल करें + इस्तेमाल में + %1$s इंस्टॉल हो गया + वह वीडियो डाउनलोड नहीं हो सका + पिछला + अगला + पेज %1$d + साफ़ करें + पेज पर जाएँ + पूर्वावलोकन + यह पूर्वावलोकन चलाया नहीं जा सका Luma Ultra कैमरे — एक्सपेरिमेंटल Joy-Con पोजीशन ट्रैकिंग अपने पेयर्ड Joy-Con कंट्रोलर्स को सही जगह पर लगाने के लिए स्मार्ट ग्लास के कैमरे का इस्तेमाल करें। रोटेशन और बटन इनपुट Joy-Con कंट्रोलर्स से आते हैं। जब आपकी कलाइयां छिपी होती हैं, तो पोजीशन का अंदाज़ा लगाया जाता है। नंगे हाथों से चलने वाले कंट्रोलर्स को बदलता है और फ़ोन-कैमरा ट्रैकिंग को पॉज़ करता है। ट्रैकिंग सेंटर को कनेक्ट या रीसेट करते समय Joy-Con कंट्रोलर्स को आगे की ओर पॉइंट करें। @@ -2866,7 +2918,6 @@ स्थिर हेड ट्रैकिंग की प्रतीक्षा कर रहा है; अनुरोध किए जाने पर ट्रैकिंग सेंटर को रीसेट करें कैमरा अवलोकन बहुत पुराना है; एक नई जोड़ी का इंतजार है फ़िट %1$.2f पीएक्स। बाएं कैमरे से अंशांकन लक्ष्य केंद्र तक अपनी चयनित दूरी को मापें, फिर सत्यापित करें। - OpenCV अनुपलब्ध: %1$s %1$d सहेजे गए दृश्य पुनर्स्थापित किए गए। पुनः प्रयास करने के लिए अंशांकन की गणना करें, या अधिक कैप्चर करने के लिए एक नया सेट प्रारंभ करें। कैप्चर किया गया %1$d / 24 बार देखा गया। अंशांकन लक्ष्य निश्चित रखें; अगले दृश्य के लिए स्मार्ट चश्मा हटाएँ। कैप्चर अस्वीकृत: %1$d / दोनों कैमरों में 12 आवश्यक कोने दिखाई दे रहे हैं। अंशांकन लक्ष्य को और अधिक दिखाएं, स्थिर रखें, फिर पुनः प्रयास करें। diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index a0dd71c18c..ab5bbef494 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -176,6 +176,8 @@ %1$s a FEX-en keresztül Ez a program %1$s PC-khez készült, és a FEX-en keresztül fut, amely még nincs beállítva. Nyissa meg egyszer a Steamet bejelentkezve: a DroidDeck ekkor letölti a FEX-et és a szükséges Steam Linux Runtime-ot, majd ez megnyílik. Ez a program + A Steam-klienst nem sikerült letölteni. Lehet, hogy a hálózat vagy a VPN blokkolja a Steam szervereit; ellenőrizd a kapcsolatot, és próbáld újra. + A Steam-klienst nem sikerült beállítani. Ellenőrizd a kapcsolatot és a szabad tárhelyet, majd próbáld újra. A %1$s x86 PC-khez készült, és a FEX-en keresztül fut, amely még nincs telepítve. Indítsa el egyszer a Steamet bejelentkezve, és hagyja letölteni a FEX-et és a Steam Linux Runtime-ot, majd indítsa el ezt újra. Egy Flathub-alkalmazásazonosító vagy a Flathub-oldala. A Flatpak előbb beállításra kerül, ha még nincs beállítva. Fájl @@ -538,7 +540,7 @@ Csak Adreno. Kevesebb akadás, nagyobb akkumulátorhasználat és hőtermelés. Munkamenet-javítások Turnip: sysmem renderelés - Gyorsabb a Steamhez és a legtöbb játékhoz. Adreno 710/720/722-n szükséges. + Gyorsabb a Steam kliensnek; játékokban a meghajtó menetenként választ a csempés és a rendszermemóriás renderelés között. Adreno 710/720/722-n szükséges. A Steam xalia segítőjének kihagyása droiddeck-ntsync (kísérleti) A Linux ntsync illesztőprogram felhasználói szintű helyettesítője, teszteléshez. Amíg be van kapcsolva, a Proton ezt használja a droiddeck-esync és a droiddeck-fsync helyett. A Proton Experimental ARM64-gyel, a GE-Protonnal és a proton-cachyosszal működik. A következő munkamenettől érvényes. @@ -1038,6 +1040,9 @@ Hozzáadott játék Egyéni játék Játéktárhely + Törli a fájljait, és eltávolítja a Streamből. + %1$s eltávolítása? + Törli a parancsikont. A játék fájljai megmaradnak. A legjobb páros ehhez a GPU-hoz, naprakészen tartva Válasszon párost saját kezűleg Illesztőprogramok keresése… @@ -1924,6 +1929,8 @@ Áruházak Áruházbeállítások Beállítások + Fülek rendezése + Kész (nincs bejelentkezve) Áruház Könyvtár @@ -2150,7 +2157,7 @@ Méret Mentés Vissza az alapértelmezettre - A játék háttere fölött rajzolódik ki, ahogy a Steam is teszi. A pontos pozíció néhány pixellel eltérhet. + Ez a pontos hely néhány képpontnyit eltérhet. Ennek a játéknak még nincs logója. Válassz egyet a Logó alatt, hogy itt lásd. A logó pozícióját nem sikerült menteni. Próbáld újra. Háttér @@ -2679,7 +2686,7 @@ Indítóvideó Videó DroidDeck · %1$d fps - A 60 fps simább, de jobban terheli a processzort a Steam indulása közben. A Steam saját beállításaiban választott indítóvideó elsőbbséget élvez. + A 60 fps simább, de jobban terheli a processzort a Steam indulása közben. A Steam saját beállításaiban választott videó itt is megjelenik. Hang Saját videó MP4, MOV, MKV vagy WebM. Más formátumokat és a %1$d MB-nál nagyobb fájlokat az eszköz 720p WebM-re alakítja, legfeljebb %2$d másodpercig. @@ -2693,6 +2700,51 @@ %1$s átalakítása a Steamhez. Hagyd nyitva a DroidDecket. Ez az eszköz nem tudja dekódolni a videót. Nem sikerült importálni a videót + Eltávolítod: %1$s? + Ezzel törlődik a videó a DroidDeckből és a Steam videómappájából. + Telepítve + Importálás + SteamDeckRepo + Hang + Telepített videók + Tallózás + DroidDeck + Importált + SteamDeckRepo + Steam + Pontbolt + Indítóvideó-jelentés + Szöveges fájlba menti, amit a DroidDeck és a Steam tud az indítóvideókról, hibajelentéshez csatolható. + Mentés + Mentve: %1$s + A jelentést nem sikerült menteni. + Hangerő + Hossz + %1$d mp + A videó hány másodperce játszódik le. Ami ennél hosszabb, azt a végén levágjuk. + Keresés a SteamDeckRepo-ban + Minden eszköz + Steam Deck + Steam Machine + Népszerű + Legtöbbet letöltött + Legkedveltebb + Legújabb + Nem érhető el a SteamDeckRepo + Újra + Nem található videó + Telepítés + Használat + Használatban + %1$s telepítve + Nem sikerült letölteni a videót + Előző + Következő + %1$d. oldal + Törlés + Ugrás az oldalra + Előnézet + Az előnézetet nem sikerült lejátszani Luma Ultra kamerák — Kísérleti Joy-Con pozíciókövetés Használd az okosszemüveg kameráit a párosított Joy-Con kontrollerek pozicionálásához. A forgatás és a gombbemenetek a Joy-Con kontrollerekről származnak. A pozíció akkor becsült, amikor a csuklód rejtve van. Helyettesíti a puszta kézzel működtetett kontrollereket, és szünetelteti a telefonkamera követést. Irányítsd a Joy-Con kontrollereket előre a követőközpont csatlakoztatásakor vagy visszaállításakor. @@ -2864,7 +2916,6 @@ Várakozás stabil fejkövetésre; szükség esetén állítsa vissza a követőközpontot. A kamerás megfigyelés túl régi; friss párra vár Fit %1$.2f px. Mérje meg a kiválasztott távolságot a bal oldali kamera és a kalibrációs célközép között, majd érvényesítse. - Az OpenCV nem érhető el: %1$s %1$d mentett nézet visszaállítva. Számítsa ki a kalibrációt az újrapróbálkozáshoz, vagy indítson új sorozatot, hogy többet rögzítsen. Rögzített %1$d / 24 megtekintés. Tartsa rögzítve a kalibrációs célt; mozgassa az okosszemüveget a következő nézethez. Rögzítés elutasítva: %1$d / 12 szükséges sarok mindkét kamerán látható. Mutasson többet a kalibrációs célból, tartsa mozdulatlanul, majd próbálja újra. diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 61be2c5f11..0bd3c783ff 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -176,6 +176,8 @@ %1$s melalui FEX Program ini dibuat untuk PC %1$s dan berjalan melalui FEX, yang belum disiapkan. Buka Steam sekali saat masuk: DroidDeck akan mengunduh FEX dan Steam Linux Runtime yang diperlukan, lalu ini akan terbuka. Program ini + Tidak dapat mengunduh klien Steam. Jaringan atau VPN Anda mungkin memblokir server Steam; periksa koneksi lalu coba lagi. + Tidak dapat menyiapkan klien Steam. Periksa koneksi dan ruang penyimpanan kosong, lalu coba lagi. %1$s dibuat untuk PC x86 dan berjalan melalui FEX, yang belum terinstal. Mulai Steam sekali saat masuk dan biarkan FEX serta Steam Linux Runtime diunduh, lalu mulai lagi. ID aplikasi Flathub atau halaman Flathub-nya. Flatpak disiapkan dahulu jika belum. File @@ -536,7 +538,7 @@ Hanya Adreno. Lebih sedikit tersendat, lebih banyak penggunaan baterai dan panas. Perbaikan sesi Turnip: rendering sysmem - Lebih cepat untuk Steam dan sebagian besar gim. Diperlukan pada Adreno 710/720/722. + Lebih cepat untuk klien Steam; di gim, driver memilih rendering ubin atau memori sistem untuk setiap pass. Diperlukan pada Adreno 710/720/722. Lewati bantuan xalia milik Steam droiddeck-ntsync (eksperimental) Pengganti userspace untuk driver ntsync Linux, untuk pengujian. Saat aktif, Proton menggunakannya sebagai pengganti droiddeck-esync dan droiddeck-fsync. Berfungsi dengan Proton Experimental ARM64, GE-Proton, dan proton-cachyos. Berlaku pada sesi berikutnya. @@ -1032,6 +1034,9 @@ Gim ditambahkan Gim khusus Penyimpanan gim + Menghapus filenya dan menghapusnya dari Steam. + Hapus %1$s? + Menghapus pintasannya. File game tetap ada. Pasangan terbaik untuk GPU ini, selalu diperbarui Pilih pasangan sendiri Memeriksa driver… @@ -1903,6 +1908,8 @@ Toko Setelan toko Setelan + Atur tab + Selesai (belum masuk) Toko Pustaka @@ -2129,7 +2136,7 @@ Ukuran Simpan Kembalikan ke bawaan - Digambar di atas latar gim, seperti yang dilakukan Steam. Posisi persisnya bisa berbeda beberapa piksel. + Posisi persis ini bisa berbeda beberapa piksel. Gim ini belum punya logo. Pilih salah satu di Logo untuk melihatnya di sini. Posisi logo tidak tersimpan. Coba lagi. Latar belakang @@ -2654,7 +2661,7 @@ Video boot Video DroidDeck · %1$d fps - 60 fps terlihat lebih mulus tetapi memakai lebih banyak CPU saat Steam dimulai. Video startup yang dipilih di pengaturan Steam sendiri lebih diutamakan. + 60 fps terlihat lebih mulus tetapi memakai lebih banyak CPU saat Steam dimulai. Video yang dipilih di pengaturan Steam sendiri juga muncul di sini. Suara Video sendiri MP4, MOV, MKV, atau WebM. Format lain dan file di atas %1$d MB dikonversi ke WebM 720p di perangkat, hingga %2$d detik. @@ -2668,6 +2675,51 @@ Mengonversi %1$s untuk Steam. Biarkan DroidDeck tetap terbuka. Perangkat ini tidak dapat mendekode video itu. Tidak dapat mengimpor video itu + Hapus %1$s? + Ini menghapus video dari DroidDeck dan dari folder video Steam. + Terpasang + Impor + SteamDeckRepo + Suara + Video terpasang + Telusuri + DroidDeck + Diimpor + SteamDeckRepo + Steam + Toko Poin + Laporan film boot + Menyimpan apa yang diketahui DroidDeck dan Steam tentang film boot ke berkas teks yang dapat dilampirkan pada laporan bug. + Simpan + Disimpan di %1$s + Laporan tidak dapat disimpan. + Volume + Durasi + %1$d dtk + Berapa detik film yang diputar. Bagian yang lebih panjang akan dipotong di bagian akhir. + Cari di SteamDeckRepo + Semua perangkat + Steam Deck + Steam Machine + Tren + Paling banyak diunduh + Paling disukai + Terbaru + Tidak dapat terhubung ke SteamDeckRepo + Coba lagi + Video tidak ditemukan + Pasang + Gunakan + Sedang digunakan + %1$s terpasang + Tidak dapat mengunduh video itu + Sebelumnya + Berikutnya + Halaman %1$d + Hapus + Buka halaman + Pratinjau + Pratinjau tidak dapat diputar Kamera Luma Ultra — Eksperimental Pelacakan posisi Joy-Con Gunakan kamera kacamata pintar untuk memposisikan pengontrol Joy-Con yang terpasang. Rotasi dan input tombol berasal dari pengontrol Joy-Con. Posisi diperkirakan saat pergelangan tangan Anda tersembunyi. Menggantikan pengontrol yang dioperasikan dengan tangan kosong dan menghentikan pelacakan kamera ponsel. Arahkan pengontrol Joy-Con ke depan saat menghubungkan atau mengatur ulang pusat pelacakan. @@ -2841,7 +2893,6 @@ Menunggu pelacakan kepala yang stabil; reset pusat pelacakan jika diminta Pengamatan kamera terlalu tua; menunggu pasangan baru Cocok dengan %1$.2f piksel. Ukur jarak yang Anda pilih dari kamera kiri ke pusat target kalibrasi, lalu validasi. - OpenCV tidak tersedia: %1$s %1$d tampilan tersimpan dipulihkan. Hitung kalibrasi untuk mencoba ulang, atau mulai rangkaian baru untuk menangkap lebih banyak. Diambil %1$d / 24 penayangan. Jaga agar target kalibrasi tetap; pindahkan kacamata pintar untuk tampilan selanjutnya. Pengambilan gambar ditolak: %1$d / 12 sudut yang diperlukan terlihat di kedua kamera. Tampilkan lebih banyak target kalibrasi, diamkan, lalu coba lagi. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 98567796a4..a2c2c3c4c5 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -176,6 +176,8 @@ %1$s tramite FEX Questo programma è compilato per PC %1$s e viene eseguito tramite FEX, che non è ancora configurato. Apri Steam una volta dopo aver eseguito l\'accesso: DroidDeck gli farà scaricare FEX e lo Steam Linux Runtime necessario, poi il programma si aprirà. Questo programma + Impossibile scaricare il client Steam. La rete o la VPN potrebbe bloccare i server di Steam; controlla la connessione e riprova. + Impossibile configurare il client Steam. Controlla la connessione e lo spazio libero, poi riprova. %1$s è compilato per PC x86 e viene eseguito tramite FEX, che non è ancora installato. Avvia Steam una volta dopo aver eseguito l\'accesso e lascia che scarichi FEX e lo Steam Linux Runtime, poi riavvia il programma. Un ID app di Flathub o la sua pagina su Flathub. Se manca, Flatpak viene prima configurato. File @@ -537,7 +539,7 @@ Solo Adreno. Meno scatti, più consumo di batteria e più calore. Correzioni della sessione Turnip: rendering sysmem - Più veloce per Steam e la maggior parte dei giochi. Necessario su Adreno 710/720/722. + Più veloce per il client di Steam; nei giochi il driver sceglie per ogni passata tra rendering a tile e in memoria di sistema. Necessario su Adreno 710/720/722. Salta l\'assistente xalia di Steam droiddeck-ntsync (sperimentale) Un sostituto in userspace del driver ntsync di Linux, per i test. Quando è attivo, Proton lo usa al posto di droiddeck-esync e droiddeck-fsync. Funziona con Proton Experimental ARM64, GE-Proton e proton-cachyos. Si applica dalla prossima sessione. @@ -1033,6 +1035,9 @@ Gioco aggiunto Gioco personalizzato Archiviazione dei giochi + Elimina i suoi file e lo rimuove da Steam. + Rimuovere %1$s? + Elimina il suo collegamento. I file del gioco restano. La coppia migliore per questa GPU, mantenuta aggiornata Scegli tu una coppia Ricerca dei driver… @@ -1934,6 +1939,8 @@ Negozi Impostazioni negozi Impostazioni + Disponi schede + Fine (accesso non eseguito) Negozio Libreria @@ -2157,7 +2164,7 @@ Dimensione Salva Ripristina predefinita - Viene disegnato sullo sfondo del gioco, come fa Steam. La posizione esatta può variare di qualche pixel. + Questa posizione esatta può variare di qualche pixel. Questo gioco non ha ancora un logo. Scegline uno in Logo per vederlo qui. Impossibile salvare la posizione del logo. Riprova. Sfondo @@ -2713,7 +2720,7 @@ Video di avvio Video DroidDeck · %1$d fps - 60 fps è più fluido ma usa più CPU durante l\'avvio di Steam. Un video di avvio scelto nelle impostazioni di Steam ha la precedenza. + 60 fps è più fluido ma usa più CPU durante l\'avvio di Steam. Anche un video scelto nelle impostazioni di Steam compare qui. Audio Il tuo video MP4, MOV, MKV o WebM. Altri formati e file oltre %1$d MB vengono convertiti in WebM 720p sul dispositivo, fino a %2$d secondi. @@ -2727,6 +2734,51 @@ Conversione di %1$s per Steam. Tieni aperto DroidDeck. Questo dispositivo non può decodificare il video. Impossibile importare il video + Rimuovere %1$s? + Il video verrà eliminato da DroidDeck e dalla cartella video di Steam. + Installati + Importa + SteamDeckRepo + Audio + Video installati + Sfoglia + DroidDeck + Importato + SteamDeckRepo + Steam + Negozio punti + Rapporto sui filmati di avvio + Salva in un file di testo ciò che DroidDeck e Steam sanno sui filmati di avvio, da allegare a una segnalazione di bug. + Salva + Salvato in %1$s + Impossibile salvare il rapporto. + Volume + Durata + %1$d s + Quanti secondi del filmato vengono riprodotti. Tutto ciò che è più lungo viene tagliato alla fine. + Cerca in SteamDeckRepo + Tutti i dispositivi + Steam Deck + Steam Machine + Di tendenza + Più scaricati + Più apprezzati + Più recenti + Impossibile raggiungere SteamDeckRepo + Riprova + Nessun video trovato + Installa + Usa + In uso + %1$s installato + Impossibile scaricare il video + Precedente + Successivo + Pagina %1$d + Cancella + Vai alla pagina + Anteprima + Impossibile riprodurre l\'anteprima Fotocamere Luma Ultra — Sperimentale Tracciamento della posizione dei Joy-Con Utilizza le fotocamere degli occhiali smart per posizionare i controller Joy-Con associati. La rotazione e gli input dei pulsanti provengono dai controller Joy-Con. La posizione viene stimata quando i polsi sono nascosti. Sostituisce i controller utilizzati a mani nude e mette in pausa il tracciamento tramite la fotocamera del telefono. Punta i controller Joy-Con in avanti quando li connetti o reimposti il ​​centro di tracciamento. @@ -2898,7 +2950,6 @@ In attesa di un tracciamento stabile della testa; ripristina il centro di tracciamento se richiesto. L’osservazione tramite telecamera è troppo vecchia; in attesa di un nuovo paio Adatta %1$.2f px. Misura la distanza selezionata dalla telecamera sinistra al centro del target di calibrazione, quindi convalida. - OpenCV non disponibile: %1$s %1$d visualizzazioni salvate ripristinate. Calcola la calibrazione per riprovare o avvia un nuovo set per acquisirne di più. Acquisito %1$d / 24 visualizzazioni. Mantenere fisso il target di calibrazione; sposta gli occhiali intelligenti per la visualizzazione successiva. Acquisizione rifiutata: %1$d / 12 angoli obbligatori visibili in entrambe le telecamere. Mostra una parte maggiore del target di calibrazione, resta fermo e riprova. diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 9da8b70b67..213144bea4 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -176,6 +176,8 @@ %1$s(FEX経由) このプログラムは%1$s PC向けにビルドされており、FEX経由で実行されますが、FEXはまだセットアップされていません。ログインした状態で一度Steamを開いてください。DroidDeckがFEXと必要なSteam Linux Runtimeをダウンロードした後、このプログラムが開きます。 このプログラム + Steamクライアントをダウンロードできませんでした。ネットワークまたはVPNがSteamのサーバーをブロックしている可能性があります。接続を確認して、もう一度お試しください。 + Steamクライアントをセットアップできませんでした。接続と空き容量を確認して、もう一度お試しください。 %1$sはx86 PC向けにビルドされており、FEX経由で実行されますが、FEXはまだインストールされていません。ログインした状態で一度Steamを起動し、FEXとSteam Linux Runtimeをダウンロードしてから、もう一度起動してください。 FlathubアプリIDまたはそのFlathubページ。Flatpakがまだセットアップされていない場合は、先にセットアップします。 ファイル @@ -536,7 +538,7 @@ Adrenoのみ。スタッターは減りますが、消費電力と発熱が増えます。 セッション修正 Turnip:sysmemレンダリング - Steamとほとんどのゲームが高速になります。Adreno 710/720/722では必須です。 + Steamクライアントが高速になります。ゲームではドライバーがパスごとにタイルレンダリングとシステムメモリレンダリングを選びます。Adreno 710/720/722では必須です。 Steamのxalia補助をスキップ droiddeck-ntsync(実験的) Linuxのntsyncドライバーをユーザー空間で代替するテスト用機能です。オンの間、Protonはdroiddeck-esyncとdroiddeck-fsyncの代わりにこれを使用します。Proton Experimental ARM64、GE-Proton、proton-cachyosで動作します。次回のセッションで有効になります。 @@ -1032,6 +1034,9 @@ 追加されたゲーム カスタムゲーム ゲームストレージ + ファイルを削除し、Steamからも削除します。 + %1$sを削除しますか? + ショートカットを削除します。ゲームファイルは残ります。 このGPUに最適なドライバー構成を選択し、最新の状態に保ちます ドライバー構成を自分で選択する ドライバーを確認中… @@ -1903,6 +1908,8 @@ ストア ストア設定 設定 + タブを整理 + 完了 (未ログイン) ストア ライブラリ @@ -2129,7 +2136,7 @@ サイズ 保存 既定に戻す - ゲームの背景に、Steam と同じ方法で描画されます。位置が数ピクセルずれることがあります。 + この位置は数ピクセルずれることがあります。 このゲームにはまだロゴがありません。ロゴでいずれかを選ぶとここに表示されます。 ロゴの位置を保存できませんでした。もう一度お試しください。 背景 @@ -2654,7 +2661,7 @@ 起動ムービー ムービー DroidDeck · %1$d fps - 60 fps はなめらかですが、Steam の起動中に CPU をより多く使います。Steam 本体の設定で選んだ起動ムービーが優先されます。 + 60 fps はなめらかですが、Steam の起動中に CPU をより多く使います。Steam 本体の設定で選んだムービーもここに表示されます。 サウンド 自分のムービー MP4、MOV、MKV、WebM。その他の形式や %1$d MB を超えるファイルは、端末上で 720p の WebM に変換されます(%2$d 秒まで)。 @@ -2668,6 +2675,51 @@ %1$s を Steam 用に変換しています。DroidDeck を開いたままにしてください。 この端末ではその動画をデコードできません。 ムービーをインポートできませんでした + %1$s を削除しますか? + DroidDeck と Steam のムービーフォルダからムービーが削除されます。 + インストール済み + インポート + SteamDeckRepo + サウンド + インストール済みのムービー + 参照 + DroidDeck + インポート済み + SteamDeckRepo + Steam + ポイントショップ + 起動ムービーのレポート + DroidDeck と Steam が把握している起動ムービーの情報をテキストファイルに保存します。不具合報告に添付できます。 + 保存 + %1$s に保存しました + レポートを保存できませんでした。 + 音量 + 長さ + %1$d 秒 + ムービーを何秒間再生するかを設定します。それより長い部分は最後がカットされます。 + SteamDeckRepo を検索 + すべてのデバイス + Steam Deck + Steam Machine + トレンド + ダウンロード数順 + いいね順 + 新着順 + SteamDeckRepo に接続できませんでした + 再試行 + ムービーが見つかりません + インストール + 使用 + 使用中 + %1$s をインストールしました + ムービーをダウンロードできませんでした + 前へ + 次へ + %1$d ページ + クリア + ページへ移動 + プレビュー + プレビューを再生できませんでした スマートグラス スマートグラスを接続して、ディスプレイと追跡の設定を変更してください。接続を解除しても、保存された設定は保持されます。 VR @@ -2839,7 +2891,6 @@ 安定したヘッドトラッキングを待機中。必要に応じてトラッキングセンターをリセットします。 カメラによる観察は古すぎる。新しいペアを待っています %1$.2f ピクセルにフィットします。左側のカメラからキャリブレーション ターゲットの中心までの選択した距離を測定し、検証します。 - OpenCV は利用できません: %1$s %1$d 個の保存されたビューが復元されました。キャリブレーションを計算して再試行するか、新しいセットを開始してさらにキャプチャします。 %1$d / 24 ビューをキャプチャしました。キャリブレーションターゲットを固定してください。次のビューのためにスマート グラスを移動します。 キャプチャが拒否されました: %1$d / 12 個の必須コーナーが両方のカメラに表示されます。キャリブレーション ターゲットをさらに表示し、静止してからもう一度試してください。 diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 0227531a54..4fc869f78f 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -176,6 +176,8 @@ FEX로 실행되는 %1$s 이 프로그램은 %1$s PC용으로 빌드되어 FEX를 통해 실행되지만, FEX가 아직 설정되지 않았습니다. 로그인한 상태로 Steam을 한 번 열면 DroidDeck이 FEX와 필요한 Steam Linux Runtime을 다운로드한 후 이 프로그램을 엽니다. 이 프로그램 + Steam 클라이언트를 다운로드할 수 없습니다. 네트워크나 VPN이 Steam 서버를 차단하고 있을 수 있습니다. 연결을 확인하고 다시 시도하세요. + Steam 클라이언트를 설정할 수 없습니다. 연결과 남은 저장 공간을 확인한 뒤 다시 시도하세요. %1$s은(는) x86 PC용으로 빌드되어 FEX를 통해 실행되지만, FEX가 아직 설치되지 않았습니다. 로그인한 상태로 Steam을 한 번 시작하여 FEX와 Steam Linux Runtime을 다운로드한 후 다시 시작하세요. Flathub 앱 ID 또는 해당 Flathub 페이지입니다. Flatpak이 아직 설정되지 않은 경우 먼저 설정합니다. 파일 @@ -536,7 +538,7 @@ Adreno에만 해당됩니다. 끊김이 줄어들지만 전력 소모와 발열이 증가합니다. 세션 수정 Turnip: sysmem 렌더링 - Steam과 대부분의 게임이 빨라집니다. Adreno 710/720/722에 필수입니다. + Steam 클라이언트가 빨라집니다. 게임에서는 드라이버가 패스마다 타일 렌더링과 시스템 메모리 렌더링 중 하나를 고릅니다. Adreno 710/720/722에 필수입니다. Steam의 xalia 도우미 건너뛰기 droiddeck-ntsync(실험적) 테스트용으로 Linux ntsync 드라이버를 사용자 공간에서 대신하는 기능입니다. 켜져 있으면 Proton이 droiddeck-esync와 droiddeck-fsync 대신 이 기능을 사용합니다. Proton Experimental ARM64, GE-Proton 및 proton-cachyos에서 작동합니다. 다음 세션에 적용됩니다. @@ -1032,6 +1034,9 @@ 추가된 게임 사용자 정의 게임 게임 저장 공간 + 파일을 삭제하고 Steam에서 제거합니다. + %1$s을(를) 제거할까요? + 바로 가기를 삭제합니다. 게임 파일은 그대로 남습니다. 이 GPU에 가장 적합한 드라이버 조합을 선택하고 최신 상태로 유지합니다 드라이버 조합을 직접 선택 드라이버 확인 중… @@ -1903,6 +1908,8 @@ 스토어 스토어 설정 설정 + 탭 정리 + 완료 (로그인 안 됨) 스토어 라이브러리 @@ -2129,7 +2136,7 @@ 크기 저장 기본값으로 - 게임 배경에 Steam과 같은 방식으로 그려집니다. 위치가 몇 픽셀 어긋날 수 있습니다. + 이 정확한 위치는 몇 픽셀 차이가 날 수 있습니다. 이 게임에는 아직 로고가 없습니다. 로고에서 하나를 고르면 여기에 표시됩니다. 로고 위치를 저장하지 못했습니다. 다시 시도하세요. 배경 @@ -2654,7 +2661,7 @@ 부팅 동영상 동영상 DroidDeck · %1$d fps - 60 fps는 더 부드럽지만 Steam이 시작되는 동안 CPU를 더 사용합니다. Steam 자체 설정에서 고른 시작 동영상이 우선합니다. + 60 fps는 더 부드럽지만 Steam이 시작되는 동안 CPU를 더 사용합니다. Steam 자체 설정에서 고른 동영상도 여기에 표시됩니다. 소리 내 동영상 MP4, MOV, MKV 또는 WebM. 다른 형식과 %1$d MB를 넘는 파일은 기기에서 720p WebM으로 변환됩니다(최대 %2$d초). @@ -2668,6 +2675,51 @@ Steam용으로 %1$s 변환 중입니다. DroidDeck을 열어 두세요. 이 기기에서 해당 동영상을 디코딩할 수 없습니다. 동영상을 가져오지 못했습니다 + %1$s을(를) 삭제할까요? + DroidDeck과 Steam의 동영상 폴더에서 동영상이 삭제됩니다. + 설치됨 + 가져오기 + SteamDeckRepo + 소리 + 설치된 동영상 + 찾아보기 + DroidDeck + 가져옴 + SteamDeckRepo + Steam + 포인트 상점 + 부팅 영상 보고서 + DroidDeck과 Steam이 부팅 영상에 대해 알고 있는 내용을 텍스트 파일로 저장합니다. 버그 보고서에 첨부할 수 있습니다. + 저장 + %1$s에 저장됨 + 보고서를 저장하지 못했습니다. + 볼륨 + 길이 + %1$d초 + 동영상을 몇 초 동안 재생할지 설정합니다. 그보다 긴 부분은 끝에서 잘립니다. + SteamDeckRepo 검색 + 모든 기기 + Steam Deck + Steam Machine + 인기 + 다운로드 많은 순 + 좋아요 많은 순 + 최신순 + SteamDeckRepo에 연결할 수 없습니다 + 다시 시도 + 동영상이 없습니다 + 설치 + 사용 + 사용 중 + %1$s 설치됨 + 동영상을 다운로드하지 못했습니다 + 이전 + 다음 + %1$d페이지 + 지우기 + 페이지로 이동 + 미리보기 + 미리보기를 재생할 수 없습니다 Luma Ultra 카메라 — 실험적 기능 Joy-Con 위치 추적 스마트 안경 카메라를 사용하여 페어링된 Joy-Con 컨트롤러의 위치를 ​​조정합니다. 회전 및 버튼 입력은 Joy-Con 컨트롤러에서 이루어집니다. 손목이 가려진 경우 위치가 추정됩니다. 맨손으로 조작하는 컨트롤러를 대체하며, 휴대폰 카메라 추적이 일시 중지됩니다. 추적 센터를 연결하거나 재설정할 때는 Joy-Con 컨트롤러를 앞쪽으로 향하게 하십시오. @@ -2770,7 +2822,6 @@ 스테레오 또는 모션 검사에 의해 손목 위치가 거부됨 스테레오 포인트가 감지되었지만 손바닥 형상이 일치하지 않습니다. %1$.2f픽셀에 맞춥니다. 왼쪽 카메라에서 보정 대상 중심까지 선택한 거리를 측정한 다음 확인합니다. - OpenCV를 사용할 수 없습니다: %1$s %1$d 저장된 뷰가 복원되었습니다. 다시 시도하려면 보정을 계산하고, 더 많은 것을 캡처하려면 새 세트를 시작하세요. 캡쳐 %1$d / 조회수 24입니다. 교정 대상을 고정된 상태로 유지하십시오. 다음 보기를 위해 스마트 안경을 이동하세요. 캡처 거부됨: %1$d / 두 카메라 모두에 12개의 필수 모서리가 표시됩니다. 보정 대상을 더 많이 표시하고 가만히 있다가 다시 시도하세요. diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index 19c8a6d571..599ff582f9 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -176,6 +176,8 @@ %1$s melalui FEX Program ini dibina untuk PC %1$s dan berjalan melalui FEX, yang belum disediakan lagi. Buka Steam sekali semasa anda log masuk: DroidDeck akan memuat turun FEX dan Steam Linux Runtime yang diperlukan, kemudian ini akan dibuka. Program ini + Tidak dapat memuat turun klien Steam. Rangkaian atau VPN anda mungkin menyekat pelayan Steam; semak sambungan dan cuba lagi. + Tidak dapat menyediakan klien Steam. Semak sambungan dan ruang storan kosong, kemudian cuba lagi. %1$s dibina untuk PC x86 dan berjalan melalui FEX, yang belum dipasang lagi. Mulakan Steam sekali semasa anda log masuk dan biarkan ia memuat turun FEX dan Steam Linux Runtime, kemudian mulakan ini semula. ID apl Flathub atau halaman Flathubnya. Flatpak akan disediakan dahulu jika belum lagi. Fail @@ -536,7 +538,7 @@ Adreno sahaja. Kurang tersekat-sekat, lebih penggunaan bateri dan haba. Pembetulan sesi Turnip: rendering sysmem - Lebih pantas untuk Steam dan kebanyakan permainan. Diperlukan pada Adreno 710/720/722. + Lebih pantas untuk klien Steam; dalam permainan, pemacu memilih pemaparan jubin atau memori sistem bagi setiap laluan. Diperlukan pada Adreno 710/720/722. Langkau pembantu xalia Steam droiddeck-ntsync (eksperimen) Pengganti ruang pengguna untuk pemacu ntsync Linux, untuk pengujian. Semasa ia hidup, Proton menggunakannya sebagai ganti droiddeck-esync dan droiddeck-fsync. Berfungsi dengan Proton Experimental ARM64, GE-Proton dan proton-cachyos. Berkuat kuasa pada sesi seterusnya. @@ -1032,6 +1034,9 @@ Permainan ditambah Permainan tersuai Storan permainan + Memadam failnya dan mengalih keluarnya daripada Steam. + Alih keluar %1$s? + Memadam pintasannya. Fail permainan kekal. Pasangan terbaik untuk GPU ini, dikemas kini sentiasa Pilih pasangan sendiri Menyemak pemacu… @@ -1903,6 +1908,8 @@ Kedai Tetapan kedai Tetapan + Susun tab + Selesai (belum log masuk) Kedai Pustaka @@ -2129,7 +2136,7 @@ Saiz Simpan Kembali kepada lalai - Dilukis di atas latar belakang permainan, seperti yang dibuat oleh Steam. Kedudukan tepatnya mungkin berbeza beberapa piksel. + Kedudukan tepat ini mungkin berbeza beberapa piksel. Permainan ini belum ada logo. Pilih satu di Logo untuk melihatnya di sini. Kedudukan logo tidak dapat disimpan. Cuba lagi. Latar belakang @@ -2654,7 +2661,7 @@ Video but Video DroidDeck · %1$d fps - 60 fps kelihatan lebih lancar tetapi menggunakan lebih banyak CPU semasa Steam bermula. Video permulaan yang dipilih dalam tetapan Steam sendiri diutamakan. + 60 fps kelihatan lebih lancar tetapi menggunakan lebih banyak CPU semasa Steam bermula. Video yang dipilih dalam tetapan Steam sendiri turut dipaparkan di sini. Bunyi Video anda sendiri MP4, MOV, MKV atau WebM. Format lain dan fail melebihi %1$d MB ditukar kepada WebM 720p pada peranti, sehingga %2$d saat. @@ -2668,6 +2675,51 @@ Menukar %1$s untuk Steam. Biarkan DroidDeck terbuka. Peranti ini tidak dapat menyahkod video itu. Tidak dapat mengimport video itu + Alih keluar %1$s? + Ini memadamkan video daripada DroidDeck dan daripada folder video Steam. + Dipasang + Import + SteamDeckRepo + Bunyi + Video dipasang + Layari + DroidDeck + Diimport + SteamDeckRepo + Steam + Kedai Mata + Laporan filem but + Menyimpan apa yang DroidDeck dan Steam ketahui tentang filem but ke dalam fail teks yang boleh dilampirkan pada laporan pepijat. + Simpan + Disimpan di %1$s + Laporan tidak dapat disimpan. + Kelantangan + Tempoh + %1$d s + Berapa saat filem dimainkan. Bahagian yang lebih panjang akan dipotong pada penghujungnya. + Cari SteamDeckRepo + Semua peranti + Steam Deck + Steam Machine + Sohor kini + Paling banyak dimuat turun + Paling disukai + Terbaharu + Tidak dapat menghubungi SteamDeckRepo + Cuba semula + Tiada video ditemui + Pasang + Guna + Sedang digunakan + %1$s dipasang + Tidak dapat memuat turun video itu + Sebelumnya + Seterusnya + Halaman %1$d + Kosongkan + Pergi ke halaman + Pratonton + Pratonton tidak dapat dimainkan Kamera Luma Ultra — Eksperimen Penjejakan kedudukan Joy-Con Gunakan kamera cermin mata pintar untuk meletakkan pengawal Joy-Con yang dipasangkan. Input putaran dan butang datang daripada pengawal Joy-Con. Kedudukan dianggarkan apabila pergelangan tangan anda tersembunyi. Menggantikan pengawal yang dikendalikan dengan tangan kosong dan menjeda penjejakan kamera telefon. Halakan pengawal Joy-Con ke hadapan semasa menyambung atau menetapkan semula pusat penjejakan. @@ -2839,7 +2891,6 @@ Menunggu penjejakan kepala yang stabil; tetapkan semula pusat penjejakan jika diminta Pemerhatian kamera terlalu lama; menunggu pasangan baru Muat %1$.2f px. Ukur jarak pilihan anda dari kamera kiri ke pusat sasaran penentukuran, kemudian sahkan. - OpenCV tidak tersedia: %1$s %1$d paparan yang disimpan dipulihkan. Kira penentukuran untuk mencuba semula, atau mulakan set baharu untuk menangkap lebih banyak lagi. Ditangkap %1$d / 24 paparan. Pastikan sasaran penentukuran tetap; alihkan cermin mata pintar untuk paparan seterusnya. Tangkapan ditolak: %1$d / 12 sudut yang diperlukan kelihatan dalam kedua-dua kamera. Tunjukkan lebih banyak sasaran penentukuran, tahan diam, kemudian cuba lagi. diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index 26f514ce6e..68dcfc185a 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -176,6 +176,8 @@ %1$s via FEX Dette programmet er bygget for %1$s-PC-er og kjører via FEX, som ikke er satt opp ennå. Åpne Steam én gang mens du er innlogget: DroidDeck lar den laste ned FEX og Steam Linux Runtime den trenger, og så åpnes dette. Dette programmet + Kunne ikke laste ned Steam-klienten. Nettverket eller VPN-en din blokkerer kanskje Steams servere; sjekk tilkoblingen og prøv igjen. + Kunne ikke sette opp Steam-klienten. Sjekk tilkoblingen og ledig lagringsplass, og prøv igjen. %1$s er bygget for x86-PC-er og kjører via FEX, som ikke er installert ennå. Start Steam én gang mens du er innlogget, og la den laste ned FEX og Steam Linux Runtime, og start dette på nytt. En Flathub-app-ID eller dens Flathub-side. Flatpak settes opp først hvis det ikke allerede er gjort. Fil @@ -538,7 +540,7 @@ Bare Adreno. Færre hikk, mer batteribruk og varme. Sesjonsfikser Turnip: sysmem-rendering - Raskere for Steam og de fleste spill. Påkrevd på Adreno 710/720/722. + Raskere for Steam-klienten; i spill velger driveren flis- eller systemminnerendering for hvert pass. Påkrevd på Adreno 710/720/722. Hopp over Steams xalia-hjelper droiddeck-ntsync (eksperimentell) En erstatning i brukerrom for Linux-driveren ntsync, for testing. Mens dette er på, bruker Proton den i stedet for droiddeck-esync og droiddeck-fsync. Fungerer med Proton Experimental ARM64, GE-Proton og proton-cachyos. Gjelder fra neste sesjon. @@ -1038,6 +1040,9 @@ Lagt til spill Egendefinert spill Spillagring + Sletter filene og fjerner det fra Steam. + Fjern %1$s? + Sletter snarveien. Spillets filer blir liggende. Det beste paret for denne GPU-en, holdt oppdatert Velg et par selv Ser etter drivere… @@ -1924,6 +1929,8 @@ Butikker Butikkinnstillinger Innstillinger + Ordne faner + Ferdig (ikke innlogget) Butikk Bibliotek @@ -2150,7 +2157,7 @@ Størrelse Lagre Tilbake til standard - Tegnes oppå spillets bakgrunn, slik Steam gjør. Den nøyaktige posisjonen kan avvike noen piksler. + Denne nøyaktige plasseringen kan avvike med noen piksler. Dette spillet har ingen logo ennå. Velg en under Logo for å se den her. Logoposisjonen kunne ikke lagres. Prøv igjen. Bakgrunn @@ -2679,7 +2686,7 @@ Oppstartsvideo Video DroidDeck · %1$d fps - 60 fps ser jevnere ut, men bruker mer CPU mens Steam starter. En oppstartsvideo valgt i Steams egne innstillinger har forrang. + 60 fps ser jevnere ut, men bruker mer CPU mens Steam starter. En video valgt i Steams egne innstillinger vises også her. Lyd Din egen video MP4, MOV, MKV eller WebM. Andre formater og filer over %1$d MB konverteres til 720p-WebM på enheten, opptil %2$d sekunder. @@ -2693,6 +2700,51 @@ Konverterer %1$s for Steam. Hold DroidDeck åpen. Enheten kan ikke dekode videoen. Kunne ikke importere videoen + Fjerne %1$s? + Dette sletter videoen fra DroidDeck og fra Steams videomappe. + Installert + Importer + SteamDeckRepo + Lyd + Installerte videoer + Bla gjennom + DroidDeck + Importert + SteamDeckRepo + Steam + Poengbutikk + Rapport om oppstartsfilmer + Lagrer det DroidDeck og Steam vet om oppstartsfilmer i en tekstfil du kan legge ved en feilrapport. + Lagre + Lagret i %1$s + Rapporten kunne ikke lagres. + Volum + Lengde + %1$d s + Hvor mange sekunder av filmen som spilles av. Alt som er lengre, klippes bort på slutten. + Søk i SteamDeckRepo + Alle enheter + Steam Deck + Steam Machine + Trender + Mest nedlastet + Mest likt + Nyeste + Fikk ikke kontakt med SteamDeckRepo + Prøv igjen + Fant ingen videoer + Installer + Bruk + I bruk + %1$s installert + Kunne ikke laste ned videoen + Forrige + Neste + Side %1$d + Tøm + Gå til side + Forhåndsvis + Forhåndsvisningen kunne ikke spilles av Luma Ultra-kameraer – Eksperimentelt Joy-Con-posisjonssporing Bruk smartbrillenes kameraer til å plassere de parede Joy-Con-kontrollerne. Rotasjon og knappinndata kommer fra Joy-Con-kontrollerne. Posisjonen estimeres når håndleddene dine er skjult. Erstatter kontrollere som betjenes med bare hender og pauser sporing av telefonkamera. Rett Joy-Con-kontrollerne fremover når du kobler til eller tilbakestiller sporingssenteret. @@ -2866,7 +2918,6 @@ Venter på stabil hodesporing; tilbakestill sporingssenteret hvis forespurt. Kameraobservasjon er for gammel; venter på et nytt par Fit %1$.2f px. Mål den valgte avstanden fra venstre kamera til kalibreringsmålsenteret, og valider deretter. - OpenCV utilgjengelig: %1$s %1$d lagrede visninger gjenopprettet. Beregn kalibrering for å prøve på nytt, eller start et nytt sett for å fange mer. Fanget %1$d / 24 visninger. Hold kalibreringsmålet fast; flytt smartbrillene for neste visning. Opptaket avvist: %1$d / 12 nødvendige hjørner synlige i begge kameraene. Vis mer av kalibreringsmålet, hold stille, og prøv på nytt. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 6d38c53953..267afcb69c 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -176,6 +176,8 @@ %1$s via FEX Dit programma is gemaakt voor %1$s-pc’s en draait via FEX, dat nog niet is ingesteld. Open Steam één keer terwijl je bent ingelogd: DroidDeck laat het dan FEX en de benodigde Steam Linux Runtime downloaden. Daarna opent dit. Dit programma + De Steam-client kon niet worden gedownload. Je netwerk of VPN blokkeert mogelijk de servers van Steam; controleer de verbinding en probeer het opnieuw. + De Steam-client kon niet worden ingesteld. Controleer de verbinding en de vrije opslag en probeer het opnieuw. %1$s is gemaakt voor x86-pc’s en draait via FEX, dat nog niet is geïnstalleerd. Start Steam één keer terwijl je bent ingelogd en laat het FEX en de Steam Linux Runtime downloaden. Start dit daarna opnieuw. Een Flathub-app-ID of de Flathub-pagina ervan. Flatpak wordt eerst ingesteld als dat nog niet is gebeurd. Bestand @@ -538,7 +540,7 @@ Alleen Adreno. Minder haperingen, meer batterijverbruik en warmte. Sessiefixes Turnip: sysmem-rendering - Sneller voor Steam en de meeste games. Vereist op Adreno 710/720/722. + Sneller voor de Steam-client; in games kiest het stuurprogramma per pass tussen tegel- en systeemgeheugenrendering. Vereist op Adreno 710/720/722. Sla de xalia-helper van Steam over droiddeck-ntsync (experimenteel) Een userspace-vervanger voor de ntsync-driver van Linux, voor tests. Terwijl dit aan staat, gebruikt Proton dit in plaats van droiddeck-esync en droiddeck-fsync. Werkt met Proton Experimental ARM64, GE-Proton en proton-cachyos. Geldt vanaf de volgende sessie. @@ -1038,6 +1040,9 @@ Toegevoegde game Aangepaste game Opslag voor games + Verwijdert de bestanden en haalt het uit Steam. + %1$s verwijderen? + Verwijdert de snelkoppeling. De gamebestanden blijven staan. Het beste paar voor deze GPU, blijft up-to-date Kies zelf een paar Controleren op drivers… @@ -1924,6 +1929,8 @@ Winkels Instellingen voor winkels Instellingen + Tabbladen rangschikken + Klaar (niet aangemeld) Winkel Bibliotheek @@ -2150,7 +2157,7 @@ Grootte Opslaan Terug naar standaard - Wordt over de achtergrond van de game getekend, zoals Steam doet. De exacte positie kan een paar pixels afwijken. + Deze exacte plek kan een paar pixels verschillen. Deze game heeft nog geen logo. Kies er een bij Logo om het hier te zien. De logopositie kon niet worden opgeslagen. Probeer het opnieuw. Achtergrond @@ -2679,7 +2686,7 @@ Opstartvideo Video DroidDeck · %1$d fps - 60 fps oogt vloeiender maar gebruikt meer CPU terwijl Steam opstart. Een opstartvideo die in Steam zelf is gekozen heeft voorrang. + 60 fps oogt vloeiender maar gebruikt meer CPU terwijl Steam opstart. Een video die in Steam zelf is gekozen verschijnt hier ook. Geluid Eigen video MP4, MOV, MKV of WebM. Andere formaten en bestanden boven %1$d MB worden op het apparaat omgezet naar 720p-WebM, tot %2$d seconden. @@ -2693,6 +2700,51 @@ %1$s wordt omgezet voor Steam. Houd DroidDeck open. Dit apparaat kan deze video niet decoderen. Kan deze video niet importeren + %1$s verwijderen? + Hiermee wordt de video verwijderd uit DroidDeck en uit de videomap van Steam. + Geïnstalleerd + Importeren + SteamDeckRepo + Geluid + Geïnstalleerde video\'s + Bladeren + DroidDeck + Geïmporteerd + SteamDeckRepo + Steam + Puntenwinkel + Rapport over opstartfilms + Slaat op in een tekstbestand wat DroidDeck en Steam weten over opstartfilms, om bij een bugrapport te voegen. + Opslaan + Opgeslagen in %1$s + Het rapport kon niet worden opgeslagen. + Volume + Duur + %1$d s + Hoeveel seconden van de film worden afgespeeld. Alles wat langer is, wordt aan het einde afgekapt. + Zoeken in SteamDeckRepo + Alle apparaten + Steam Deck + Steam Machine + Trending + Meest gedownload + Meest geliked + Nieuwste + Kan SteamDeckRepo niet bereiken + Opnieuw + Geen video\'s gevonden + Installeren + Gebruiken + In gebruik + %1$s geïnstalleerd + Kan die video niet downloaden + Vorige + Volgende + Pagina %1$d + Wissen + Ga naar pagina + Voorbeeld + Het voorbeeld kon niet worden afgespeeld Luma Ultra-camera\'s — Experimenteel Positietracking van Joy-Con-controllers Gebruik de camera\'s van de smartbril om je gekoppelde Joy-Con-controllers te positioneren. Rotatie en knopbediening komen van de Joy-Con-controllers. De positie wordt geschat wanneer je polsen verborgen zijn. Vervangt controllers die met blote handen worden bediend en pauzeert de tracking door de telefooncamera. Richt de Joy-Con-controllers naar voren bij het verbinden of resetten van het trackingcentrum. @@ -2864,7 +2916,6 @@ Wachten op stabiele hoofdtracking; reset het trackingcentrum indien aangevraagd. Cameraobservatie is te oud; wachtend op een nieuw paar Pas %1$.2f px aan. Meet de door u geselecteerde afstand vanaf de linkercamera tot het midden van het kalibratiedoel en valideer vervolgens. - OpenCV niet beschikbaar: %1$s %1$d opgeslagen weergaven hersteld. Bereken de kalibratie om het opnieuw te proberen, of start een nieuwe set om meer vast te leggen. Vastgelegd %1$d / 24 weergaven. Houd het kalibratiedoel vast; verplaats de slimme bril voor de volgende weergave. Opname afgewezen: %1$d / 12 vereiste hoeken zichtbaar in beide camera\'s. Laat meer van het kalibratiedoel zien, blijf stil staan ​​en probeer het opnieuw. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 7886e8f0d3..fc7bb39b1a 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -176,6 +176,8 @@ %1$s przez FEX Ten program jest zbudowany dla komputerów %1$s i działa przez FEX, który nie jest jeszcze skonfigurowany. Otwórz raz Steam po zalogowaniu: DroidDeck pobierze wtedy FEX i potrzebne Steam Linux Runtime, a potem program się otworzy. Ten program + Nie udało się pobrać klienta Steam. Twoja sieć lub VPN może blokować serwery Steam; sprawdź połączenie i spróbuj ponownie. + Nie udało się skonfigurować klienta Steam. Sprawdź połączenie i wolne miejsce, a potem spróbuj ponownie. %1$s jest zbudowany dla komputerów x86 i działa przez FEX, który nie jest jeszcze zainstalowany. Uruchom raz Steam po zalogowaniu i pozwól mu pobrać FEX oraz Steam Linux Runtime, a potem uruchom program ponownie. ID aplikacji z Flathub lub jej strona na Flathub. Jeśli Flatpak nie jest jeszcze skonfigurowany, zostanie skonfigurowany najpierw. Plik @@ -542,7 +544,7 @@ Tylko Adreno. Mniej przycięć, większe zużycie baterii i więcej ciepła. Poprawki sesji Turnip: renderowanie sysmem - Szybsze dla Steam i większości gier. Wymagane na Adreno 710/720/722. + Szybsze dla klienta Steam; w grach sterownik dla każdego przebiegu wybiera renderowanie kafelkowe lub w pamięci systemowej. Wymagane na Adreno 710/720/722. Pomijaj pomocnika xalia w Steam droiddeck-ntsync (eksperymentalne) Zastępnik sterownika Linux ntsync w przestrzeni użytkownika, do testów. Gdy jest włączony, Proton używa go zamiast droiddeck-esync i droiddeck-fsync. Zgodny z Proton Experimental ARM64, GE-Proton i proton-cachyos. Działa od następnej sesji. @@ -1050,6 +1052,9 @@ Dodana gra Własna gra Miejsce na gry + Usuwa jej pliki i usuwa ją ze Steam. + Usunąć %1$s? + Usuwa skrót. Pliki gry pozostają. Najlepsza para dla tego GPU, aktualizowana automatycznie Wybierz parę samodzielnie Sprawdzanie sterowników… @@ -1966,6 +1971,8 @@ Sklepy Ustawienia sklepów Ustawienia + Ułóż karty + Gotowe (niezalogowano) Sklep Biblioteka @@ -2192,7 +2199,7 @@ Rozmiar Zapisz Przywróć domyślne - Logo jest rysowane na tle gry, tak jak robi to Steam. Dokładna pozycja może się różnić o kilka pikseli. + To dokładne miejsce może różnić się o kilka pikseli. Ta gra nie ma jeszcze logo. Wybierz je w Logo, aby zobaczyć je tutaj. Nie udało się zapisać pozycji logo. Spróbuj ponownie. Tło @@ -2747,7 +2754,7 @@ Film startowy Film DroidDeck · %1$d kl./s - 60 kl./s wygląda płynniej, ale bardziej obciąża procesor podczas uruchamiania Steam. Film startowy wybrany w ustawieniach Steam ma pierwszeństwo. + 60 kl./s wygląda płynniej, ale bardziej obciąża procesor podczas uruchamiania Steam. Film wybrany w ustawieniach Steam też jest tu widoczny. Dźwięk Własny film MP4, MOV, MKV lub WebM. Inne formaty i pliki powyżej %1$d MB są konwertowane na urządzeniu do WebM 720p, do %2$d sekund. @@ -2761,6 +2768,51 @@ Konwertowanie %1$s dla Steam. Nie zamykaj DroidDeck. To urządzenie nie może zdekodować tego filmu. Nie udało się zaimportować filmu + Usunąć %1$s? + Film zostanie usunięty z DroidDeck i z folderu filmów Steam. + Zainstalowane + Importuj + SteamDeckRepo + Dźwięk + Zainstalowane filmy + Przeglądaj + DroidDeck + Zaimportowane + SteamDeckRepo + Steam + Sklep za punkty + Raport o filmach startowych + Zapisuje w pliku tekstowym to, co DroidDeck i Steam wiedzą o filmach startowych, do dołączenia do zgłoszenia błędu. + Zapisz + Zapisano w %1$s + Nie udało się zapisać raportu. + Głośność + Długość + %1$d s + Ile sekund filmu jest odtwarzane. Wszystko, co trwa dłużej, jest ucinane na końcu. + Szukaj w SteamDeckRepo + Wszystkie urządzenia + Steam Deck + Steam Machine + Na czasie + Najczęściej pobierane + Najbardziej lubiane + Najnowsze + Nie można połączyć z SteamDeckRepo + Ponów + Nie znaleziono filmów + Zainstaluj + Użyj + W użyciu + Zainstalowano %1$s + Nie udało się pobrać tego filmu + Poprzednia + Następna + Strona %1$d + Wyczyść + Przejdź do strony + Podgląd + Nie udało się odtworzyć podglądu Kamery Luma Ultra — Eksperymentalne Śledzenie pozycji Joy-Conów Użyj kamer w inteligentnych okularach, aby ustawić sparowane kontrolery Joy-Con. Obrót i sterowanie przyciskami pochodzą z kontrolerów Joy-Con. Pozycja jest szacowana, gdy nadgarstki są ukryte. Zastępuje kontrolery obsługiwane gołymi rękami i wstrzymuje śledzenie kamery telefonu. Skieruj kontrolery Joy-Con do przodu podczas podłączania lub resetowania centrum śledzenia. @@ -2931,7 +2983,6 @@ Oczekiwanie na stabilne śledzenie głowy; zresetuj centrum śledzenia, jeśli zostaniesz o to poproszony. Obserwacja kamerą jest zbyt stara; czekam na świeżą parę Dopasuj %1$.2f pikseli. Zmierz wybraną odległość od lewej kamery do środka celu kalibracji, a następnie zatwierdź. - OpenCV niedostępne: %1$s Przywrócono %1$d zapisane widoki. Oblicz kalibrację, aby spróbować ponownie, lub rozpocznij nową serię, aby uchwycić więcej. Zarejestrowane widoki: %1$d / 24. Utrzymuj cel kalibracji nieruchomo; przesuń inteligentne okulary, aby uzyskać następny widok. Przechwytywanie odrzucone: %1$d / 12 wymaganych rogów widocznych w obu kamerach. Pokaż więcej celu kalibracji, przytrzymaj nieruchomo i spróbuj ponownie. diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 35f2b5577c..8c51b09c9e 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -176,6 +176,8 @@ %1$s através do FEX Este programa foi compilado para PCs %1$s e é executado através do FEX, que ainda não está configurado. Abra o Steam uma vez com a sessão iniciada: o DroidDeck transfere o FEX e o Steam Linux Runtime necessários e, depois, este programa abre. Este programa + Não foi possível transferir o cliente Steam. A sua rede ou VPN pode estar a bloquear os servidores da Steam; verifique a ligação e tente novamente. + Não foi possível configurar o cliente Steam. Verifique a ligação e o espaço livre e tente novamente. %1$s foi compilado para PCs x86 e é executado através do FEX, que ainda não está instalado. Abra o Steam uma vez com a sessão iniciada e deixe-o transferir o FEX e o Steam Linux Runtime; depois, volte a iniciá-lo. Um ID de app do Flathub ou a respetiva página no Flathub. O Flatpak é configurado primeiro, se ainda não estiver. Ficheiro @@ -537,7 +539,7 @@ Apenas Adreno. Menos soluços, mais consumo de bateria e mais calor. Correções da sessão Turnip: renderização em sysmem - Mais rápido para o Steam e a maioria dos jogos. Obrigatório no Adreno 710/720/722. + Mais rápido para o cliente Steam; nos jogos, o controlador escolhe em cada passagem entre renderização em mosaico ou na memória do sistema. Obrigatório no Adreno 710/720/722. Ignorar o assistente xalia do Steam droiddeck-ntsync (experimental) Um substituto em espaço de utilizador para o controlador ntsync do Linux, para testes. Enquanto estiver ativado, o Proton utiliza-o em vez do droiddeck-esync e do droiddeck-fsync. Funciona com o Proton Experimental ARM64, o GE-Proton e o proton-cachyos. Aplica-se na próxima sessão. @@ -1033,6 +1035,9 @@ Jogo adicionado Jogo personalizado Armazenamento de jogos + Apaga os ficheiros e remove-o da Steam. + Remover %1$s? + Apaga o atalho. Os ficheiros do jogo mantêm-se. O melhor par para esta GPU, sempre atualizado Escolha um par manualmente A procurar controladores… @@ -1934,6 +1939,8 @@ Lojas Definições das lojas Definições + Organizar separadores + Concluído (sessão não iniciada) Loja Biblioteca @@ -2157,7 +2164,7 @@ Tamanho Guardar Repor predefinição - É desenhado sobre o fundo do jogo, como o Steam faz. A posição exata pode variar alguns píxeis. + Esta posição exata pode variar alguns píxeis. Este jogo ainda não tem logótipo. Escolha um em Logótipo para o ver aqui. Não foi possível guardar a posição do logótipo. Tente novamente. Fundo @@ -2713,7 +2720,7 @@ Vídeo de arranque Vídeo DroidDeck · %1$d fps - 60 fps é mais fluido, mas usa mais CPU enquanto o Steam arranca. Um vídeo de arranque escolhido nas definições do Steam tem prioridade. + 60 fps é mais fluido, mas usa mais CPU enquanto o Steam arranca. Um vídeo escolhido nas definições do Steam também aparece aqui. Som O seu próprio vídeo MP4, MOV, MKV ou WebM. Outros formatos e ficheiros acima de %1$d MB são convertidos para WebM 720p no dispositivo, até %2$d segundos. @@ -2727,6 +2734,51 @@ A converter %1$s para o Steam. Mantenha o DroidDeck aberto. Este dispositivo não consegue descodificar esse vídeo. Não foi possível importar esse vídeo + Remover %1$s? + Isto elimina o vídeo do DroidDeck e da pasta de vídeos do Steam. + Instalados + Importar + SteamDeckRepo + Som + Vídeos instalados + Explorar + DroidDeck + Importado + SteamDeckRepo + Steam + Loja de Pontos + Relatório dos filmes de arranque + Guarda num ficheiro de texto o que o DroidDeck e o Steam sabem sobre os filmes de arranque, para anexar a um relatório de erro. + Guardar + Guardado em %1$s + Não foi possível guardar o relatório. + Volume + Duração + %1$d s + Quantos segundos do filme são reproduzidos. Tudo o que for mais longo é cortado no fim. + Pesquisar no SteamDeckRepo + Todos os dispositivos + Steam Deck + Steam Machine + Em destaque + Mais transferidos + Mais gostados + Mais recentes + Não foi possível aceder ao SteamDeckRepo + Tentar novamente + Nenhum vídeo encontrado + Instalar + Usar + Em utilização + %1$s instalado + Não foi possível transferir esse vídeo + Anterior + Seguinte + Página %1$d + Limpar + Ir para a página + Pré-visualizar + Não foi possível reproduzir a pré-visualização Câmaras Luma Ultra — Experimental Rastreio de posição do Joy-Con Utilize as câmaras dos óculos inteligentes para posicionar os seus comandos Joy-Con emparelhados. A rotação e os comandos dos botões vêm dos comandos Joy-Con. A posição é estimada quando os seus pulsos estão escondidos. Substitui os controlos operados com as mãos nuas e pausa o rastreio da câmara do telefone. Aponte os controlos Joy-Con para a frente ao ligar ou repor o centro de seguimento. @@ -2899,7 +2951,6 @@ Aguarda rastreio de cabeça estável; reponha o centro de rastreio se solicitado. A observação da câmara é muito antiga; à espera de um novo par Ajustar %1$.2f px. Meça a distância selecionada da câmara esquerda até ao centro do alvo de calibração e valide. - OpenCV indisponível: %1$s %1$d visualizações guardadas restauradas. Calcule a calibração para tentar novamente ou inicie um novo conjunto para captar mais. Capturado %1$d/24 visualizações. Mantenha o alvo de calibração fixo; mova os óculos inteligentes para a visualização seguinte. Captura rejeitada: %1$d/12 cantos necessários visíveis em ambas as câmaras. Mostre mais do alvo de calibração, mantenha-se imóvel e tente novamente. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 0672620b8f..7c6f7f9661 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -176,6 +176,8 @@ %1$s pelo FEX Este programa é feito para PCs %1$s e roda pelo FEX, que ainda não está configurado. Abra a Steam uma vez com a sessão iniciada: o DroidDeck faz com que ela baixe o FEX e o Steam Linux Runtime necessários, e então isto abre. Este programa + Não foi possível baixar o cliente Steam. Sua rede ou VPN pode estar bloqueando os servidores da Steam; verifique a conexão e tente novamente. + Não foi possível configurar o cliente Steam. Verifique a conexão e o espaço livre e tente novamente. %1$s é feito para PCs x86 e roda pelo FEX, que ainda não está instalado. Abra a Steam uma vez com a sessão iniciada e deixe-a baixar o FEX e o Steam Linux Runtime; depois, abra isto de novo. Um ID de app do Flathub ou a página dele no Flathub. O Flatpak é configurado antes, se ainda não estiver. Arquivo @@ -537,7 +539,7 @@ Só em Adreno. Menos engasgos, mais gasto de bateria e mais calor. Correções da sessão Turnip: renderização sysmem - Mais rápido para a Steam e a maioria dos jogos. Obrigatório nas Adreno 710/720/722. + Mais rápido para o cliente da Steam; nos jogos, o driver escolhe a cada passagem entre renderização em blocos ou na memória do sistema. Obrigatório nas Adreno 710/720/722. Pular o assistente xalia da Steam droiddeck-ntsync (experimental) Um substituto em espaço de usuário para o driver ntsync do Linux, para testes. Enquanto estiver ativado, o Proton o usa no lugar do droiddeck-esync e do droiddeck-fsync. Funciona com o Proton Experimental ARM64, o GE-Proton e o proton-cachyos. Vale a partir da próxima sessão. @@ -1033,6 +1035,9 @@ Jogo adicionado Jogo personalizado Armazenamento de jogos + Apaga os arquivos e o remove da Steam. + Remover %1$s? + Apaga o atalho. Os arquivos do jogo ficam. O melhor par para esta GPU, sempre atualizado Escolha um par você mesmo Procurando drivers… @@ -1934,6 +1939,8 @@ Lojas Configurações das lojas Configurações + Organizar abas + Concluído (sem login) Loja Biblioteca @@ -2157,7 +2164,7 @@ Tamanho Salvar Voltar ao padrão - É desenhado sobre o plano de fundo do jogo, como a Steam faz. A posição exata pode variar alguns pixels. + Esta posição exata pode variar alguns pixels. Este jogo ainda não tem logo. Escolha um em Logo para vê-lo aqui. Não foi possível salvar a posição do logo. Tente de novo. Fundo @@ -2713,7 +2720,7 @@ Vídeo de inicialização Vídeo DroidDeck · %1$d fps - 60 fps fica mais fluido, mas usa mais CPU enquanto o Steam inicia. Um vídeo de inicialização escolhido nas configurações do Steam tem prioridade. + 60 fps fica mais fluido, mas usa mais CPU enquanto o Steam inicia. Um vídeo escolhido nas configurações do Steam também aparece aqui. Som Seu próprio vídeo MP4, MOV, MKV ou WebM. Outros formatos e arquivos acima de %1$d MB são convertidos para WebM 720p no aparelho, até %2$d segundos. @@ -2727,6 +2734,51 @@ Convertendo %1$s para o Steam. Mantenha o DroidDeck aberto. Este aparelho não consegue decodificar esse vídeo. Não foi possível importar esse vídeo + Remover %1$s? + Isso exclui o vídeo do DroidDeck e da pasta de vídeos do Steam. + Instalados + Importar + SteamDeckRepo + Som + Vídeos instalados + Explorar + DroidDeck + Importado + SteamDeckRepo + Steam + Loja de Pontos + Relatório dos filmes de inicialização + Salva em um arquivo de texto o que o DroidDeck e o Steam sabem sobre os filmes de inicialização, para anexar a um relatório de bug. + Salvar + Salvo em %1$s + Não foi possível salvar o relatório. + Volume + Duração + %1$d s + Quantos segundos do vídeo são reproduzidos. Tudo o que for mais longo é cortado no final. + Pesquisar no SteamDeckRepo + Todos os dispositivos + Steam Deck + Steam Machine + Em alta + Mais baixados + Mais curtidos + Mais recentes + Não foi possível acessar o SteamDeckRepo + Tentar novamente + Nenhum vídeo encontrado + Instalar + Usar + Em uso + %1$s instalado + Não foi possível baixar esse vídeo + Anterior + Próxima + Página %1$d + Limpar + Ir para a página + Pré-visualizar + Não foi possível reproduzir a pré-visualização Câmeras Luma Ultra — Experimental Rastreamento de posição do Joy-Con Use as câmeras dos óculos inteligentes para posicionar seus controles Joy-Con emparelhados. A rotação e os comandos dos botões vêm dos controles Joy-Con. A posição é estimada quando seus pulsos estão escondidos. Substitui os controles operados com as mãos nuas e pausa o rastreamento da câmera do telefone. Aponte os controles Joy-Con para frente ao conectar ou redefinir o centro de rastreamento. @@ -2899,7 +2951,6 @@ Aguardando rastreamento de cabeça estável; redefina o centro de rastreamento se solicitado. A observação da câmera é muito antiga; esperando por um novo par Ajustar %1$.2f px. Meça a distância selecionada da câmera esquerda até o centro do alvo de calibração e valide. - OpenCV indisponível: %1$s %1$d visualizações salvas restauradas. Calcule a calibração para tentar novamente ou inicie um novo conjunto para capturar mais. Capturado %1$d/24 visualizações. Mantenha o alvo de calibração fixo; mova os óculos inteligentes para a próxima visualização. Captura rejeitada: %1$d/12 cantos necessários visíveis em ambas as câmeras. Mostre mais do alvo de calibração, fique imóvel e tente novamente. diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index 329865e8fc..c9e753866f 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -176,6 +176,8 @@ %1$s prin FEX Acest program este compilat pentru PC-uri %1$s și rulează prin FEX, care nu este încă configurat. Deschide Steam o dată, fiind autentificat: DroidDeck îl pune să descarce FEX și Steam Linux Runtime de care are nevoie, apoi acesta se deschide. Acest program + Clientul Steam nu a putut fi descărcat. Rețeaua sau VPN-ul tău poate bloca serverele Steam; verifică conexiunea și încearcă din nou. + Clientul Steam nu a putut fi configurat. Verifică conexiunea și spațiul liber, apoi încearcă din nou. %1$s este compilat pentru PC-uri x86 și rulează prin FEX, care nu este încă instalat. Pornește Steam o dată, fiind autentificat, și lasă-l să descarce FEX și Steam Linux Runtime, apoi pornește din nou acesta. Un ID de aplicație Flathub sau pagina sa Flathub. Flatpak este configurat mai întâi, dacă nu este deja. Fișier @@ -540,7 +542,7 @@ Doar Adreno. Mai puține întreruperi, consum mai mare de baterie și căldură. Remedieri de sesiune Turnip: randare sysmem - Mai rapidă pentru Steam și majoritatea jocurilor. Necesară pe Adreno 710/720/722. + Mai rapidă pentru clientul Steam; în jocuri, driverul alege la fiecare trecere între randarea pe dale și cea în memoria sistemului. Necesară pe Adreno 710/720/722. Omite asistentul xalia al Steam droiddeck-ntsync (experimental) Un substitut la nivel de utilizator pentru driverul Linux ntsync, pentru testare. Cât timp este activ, Proton îl folosește în locul droiddeck-esync și droiddeck-fsync. Funcționează cu Proton Experimental ARM64, GE-Proton și proton-cachyos. Se aplică la sesiunea următoare. @@ -1044,6 +1046,9 @@ Joc adăugat Joc personalizat Stocarea jocurilor + Șterge fișierele sale și îl elimină din Steam. + Elimini %1$s? + Șterge comanda rapidă. Fișierele jocului rămân. Cea mai bună pereche pentru acest GPU, păstrată actualizată Alege o pereche tu însuți Se verifică driverele… @@ -1945,6 +1950,8 @@ Magazine Setările magazinelor Setări + Aranjează filele + Gata (neautentificat) Magazin Bibliotecă @@ -2171,7 +2178,7 @@ Dimensiune Salvează Revino la implicit - Se desenează peste fundalul jocului, ca în Steam. Poziția exactă poate diferi cu câțiva pixeli. + Poziția exactă poate diferi cu câțiva pixeli. Acest joc nu are încă un logo. Alege unul la Logo ca să îl vezi aici. Poziția logo-ului nu a putut fi salvată. Încearcă din nou. Fundal @@ -2713,7 +2720,7 @@ Videoclip de pornire Videoclip DroidDeck · %1$d fps - 60 fps arată mai fluid, dar folosește mai mult procesorul cât pornește Steam. Un videoclip de pornire ales în setările Steam are prioritate. + 60 fps arată mai fluid, dar folosește mai mult procesorul cât pornește Steam. Un videoclip ales în setările Steam apare și aici. Sunet Videoclipul tău MP4, MOV, MKV sau WebM. Alte formate și fișierele de peste %1$d MB sunt convertite pe dispozitiv în WebM 720p, până la %2$d secunde. @@ -2727,6 +2734,51 @@ Se convertește %1$s pentru Steam. Lasă DroidDeck deschis. Acest dispozitiv nu poate decoda videoclipul. Videoclipul nu a putut fi importat + Elimini %1$s? + Videoclipul va fi șters din DroidDeck și din folderul de videoclipuri Steam. + Instalate + Importă + SteamDeckRepo + Sunet + Videoclipuri instalate + Răsfoiește + DroidDeck + Importat + SteamDeckRepo + Steam + Magazin de puncte + Raport despre filmele de pornire + Salvează într-un fișier text ce știu DroidDeck și Steam despre filmele de pornire, pentru a-l atașa la un raport de eroare. + Salvează + Salvat în %1$s + Raportul nu a putut fi salvat. + Volum + Durată + %1$d s + Câte secunde din film se redau. Tot ce este mai lung este tăiat la final. + Caută în SteamDeckRepo + Toate dispozitivele + Steam Deck + Steam Machine + Populare + Cele mai descărcate + Cele mai apreciate + Cele mai noi + Nu s-a putut contacta SteamDeckRepo + Reîncearcă + Nu s-au găsit videoclipuri + Instalează + Folosește + În uz + %1$s instalat + Videoclipul nu a putut fi descărcat + Înapoi + Înainte + Pagina %1$d + Șterge + Mergi la pagina + Previzualizare + Previzualizarea nu a putut fi redată Camere Luma Ultra — Experimentale Urmărirea poziției Joy-Con Folosește camerele ochelarilor inteligenți pentru a poziționa controlerele Joy-Con asociate. Rotirea și comenzile de butoane provin de la controlerele Joy-Con. Poziția este estimată atunci când încheieturile mâinilor sunt ascunse. Înlocuiește controlerele acționate cu mâinile goale și întrerupe urmărirea camerei telefonului. Îndreaptă controlerele Joy-Con înainte atunci când conectezi sau resetezi centrul de urmărire. @@ -2900,7 +2952,6 @@ Se așteaptă o urmărire stabilă a capului; resetează centrul de urmărire dacă este solicitat Observarea camerei este prea veche; așteptând o pereche proaspătă Eroare de calibrare: %1$.2f px. Măsoară distanța selectată de la camera din stânga la centrul țintei de calibrare, apoi validează. - OpenCV indisponibil: %1$s Au fost restaurate %1$d vederi salvate. Calculează calibrarea pentru a reîncerca sau începe un set nou pentru a captura mai multe. Captură %1$d / 24 de vizualizări. Păstrează ținta de calibrare fixă; mută ochelarii inteligenți pentru următoarea vizualizare. Captură respinsă: %1$d / 12 colțuri necesare sunt vizibile în ambele camere. Arată o porțiune mai mare din ținta de calibrare, stai nemișcat, apoi încearcă din nou. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index e25310312c..4af87d354a 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -176,6 +176,8 @@ %1$s через FEX Эта программа собрана для ПК на %1$s и работает через FEX, который еще не настроен. Откройте Steam один раз, войдя в аккаунт: DroidDeck скачает через него FEX и нужную Steam Linux Runtime, после чего программа откроется. Эта программа + Не удалось скачать клиент Steam. Возможно, ваша сеть или VPN блокирует серверы Steam; проверьте подключение и повторите попытку. + Не удалось настроить клиент Steam. Проверьте подключение и свободное место, затем повторите попытку. %1$s — сборка для x86-ПК, которая работает через FEX, а он еще не установлен. Запустите Steam один раз, войдя в аккаунт, и дайте ему скачать FEX и Steam Linux Runtime, затем запустите программу снова. ID приложения Flathub или ссылка на его страницу. Если Flatpak еще не настроен, сначала будет выполнена его настройка. Файл @@ -539,7 +541,7 @@ Только для Adreno. Меньше подтормаживаний, но больше энергопотребления и нагрева. Исправления сессии Turnip: рендеринг sysmem - Steam и большинство игр будут быстрее. Требуется для Adreno 710/720/722. + Клиент Steam будет быстрее; в играх драйвер для каждого прохода выбирает тайловый рендеринг или рендеринг в системной памяти. Требуется для Adreno 710/720/722. Пропустить помощник xalia в Steam droiddeck-ntsync (экспериментально) Замена драйвера ntsync Linux в пространстве пользователя, для тестирования. Пока включено, Proton использует ее вместо droiddeck-esync и droiddeck-fsync. Работает с Proton Experimental ARM64, GE-Proton и proton-cachyos. Вступит в силу в следующей сессии. @@ -1047,6 +1049,9 @@ Добавленная игра Своя игра Хранилище игр + Удаляет файлы игры и убирает ее из Steam. + Убрать %1$s? + Удаляет ярлык. Файлы игры остаются. Лучшая пара для этого GPU, обновляется автоматически Выбрать комбинацию драйверов вручную Проверка драйверов… @@ -1963,6 +1968,8 @@ Магазины Настройки магазинов Настройки + Упорядочить вкладки + Готово (вход не выполнен) Магазин Библиотека @@ -2186,7 +2193,7 @@ Размер Сохранить Вернуть по умолчанию - Рисуется поверх фона игры, как в Steam. Точное положение может отличаться на несколько пикселей. + Точное положение может отличаться на несколько пикселей. У этой игры пока нет логотипа. Выберите его в разделе «Логотип», чтобы увидеть здесь. Не удалось сохранить положение логотипа. Попробуйте ещё раз. Фон @@ -2747,7 +2754,7 @@ Загрузочное видео Видео DroidDeck · %1$d кадр/с - 60 кадр/с выглядит плавнее, но сильнее нагружает процессор при запуске Steam. Видео при запуске, выбранное в настройках самого Steam, имеет приоритет. + 60 кадр/с выглядит плавнее, но сильнее нагружает процессор при запуске Steam. Видео, выбранное в настройках самого Steam, тоже появляется здесь. Звук Своё видео MP4, MOV, MKV или WebM. Другие форматы и файлы больше %1$d МБ преобразуются на устройстве в WebM 720p, до %2$d секунд. @@ -2761,6 +2768,51 @@ %1$s преобразуется для Steam. Не закрывайте DroidDeck. Устройство не может декодировать это видео. Не удалось импортировать видео + Удалить %1$s? + Видео будет удалено из DroidDeck и из папки видео Steam. + Установленные + Импорт + SteamDeckRepo + Звук + Установленные видео + Обзор + DroidDeck + Импортировано + SteamDeckRepo + Steam + Магазин баллов + Отчет о загрузочных роликах + Сохраняет в текстовый файл то, что DroidDeck и Steam знают о загрузочных роликах, чтобы приложить к сообщению об ошибке. + Сохранить + Сохранено: %1$s + Не удалось сохранить отчет. + Громкость + Длительность + %1$d с + Сколько секунд фильма воспроизводится. Всё, что длиннее, обрезается в конце. + Поиск в SteamDeckRepo + Все устройства + Steam Deck + Steam Machine + В тренде + Больше всего загрузок + Больше всего лайков + Новые + Не удалось подключиться к SteamDeckRepo + Повторить + Видео не найдены + Установить + Использовать + Используется + %1$s установлено + Не удалось скачать это видео + Назад + Далее + Страница %1$d + Очистить + Перейти к странице + Просмотр + Не удалось воспроизвести предпросмотр Камеры Luma Ultra — Экспериментальная Отслеживание положения Joy-Con Используйте камеры умных очков для позиционирования сопряженных контроллеров Joy-Con. Вращение и ввод с кнопок осуществляются с помощью контроллеров Joy-Con. Положение оценивается, когда ваши запястья скрыты. Заменяет контроллеры, управляемые голыми руками, и приостанавливает отслеживание камерой телефона. Направьте контроллеры Joy-Con вперед при подключении или сбросе центра отслеживания. @@ -2931,7 +2983,6 @@ Ожидание стабильного отслеживания головы; сбросьте центр отслеживания, если потребуется. Камера наблюдения устарела; жду новую пару По размеру %1$.2f пикселей. Измерьте выбранное расстояние от левой камеры до центра калибровочной цели, а затем подтвердите. - OpenCV недоступен: %1$s %1$d сохраненные просмотры восстановлены. Рассчитайте калибровку, чтобы повторить попытку, или начните новую настройку, чтобы захватить больше. Снято %1$d / 24 просмотра. Держите цель калибровки фиксированной; переместите умные очки для следующего просмотра. Захват отклонен: %1$d / 12 требуемых углов видны в обеих камерах. Покажите больше калибровочной цели, задержитесь и повторите попытку. diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 0cf9b426cf..e740f9cb9b 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -176,6 +176,8 @@ %1$s via FEX Programmet är byggt för %1$s-datorer och körs via FEX, som inte har konfigurerats än. Öppna Steam en gång medan du är inloggad: DroidDeck låter Steam ladda ned FEX och den Steam Linux Runtime som behövs, sedan öppnas detta. Det här programmet + Det gick inte att ladda ned Steam-klienten. Ditt nätverk eller din VPN kanske blockerar Steams servrar; kontrollera anslutningen och försök igen. + Det gick inte att konfigurera Steam-klienten. Kontrollera anslutningen och det lediga lagringsutrymmet och försök igen. %1$s är byggt för x86-datorer och körs via FEX, som inte är installerat än. Starta Steam en gång medan du är inloggad och låt det ladda ned FEX och Steam Linux Runtime. Starta sedan detta igen. Ett app-ID från Flathub eller appens Flathub-sida. Flatpak konfigureras först om det inte redan är gjort. Fil @@ -538,7 +540,7 @@ Bara Adreno. Färre hack, högre batteriförbrukning och mer värme. Sessionsfixar Turnip: sysmem-rendering - Snabbare för Steam och de flesta spel. Krävs på Adreno 710/720/722. + Snabbare för Steam-klienten; i spel väljer drivrutinen kakel- eller systemminnesrendering för varje pass. Krävs på Adreno 710/720/722. Hoppa över Steams xalia-hjälp droiddeck-ntsync (experimentell) En ersättning i användarutrymmet för Linux ntsync-drivrutinen, för testning. Medan det är på använder Proton det i stället för droiddeck-esync och droiddeck-fsync. Fungerar med Proton Experimental ARM64, GE-Proton och proton-cachyos. Gäller från nästa session. @@ -1038,6 +1040,9 @@ Tillagt spel Anpassat spel Spellagring + Tar bort dess filer och tar bort det från Steam. + Ta bort %1$s? + Tar bort genvägen. Spelets filer ligger kvar. Det bästa paret för den här GPU:n, hålls uppdaterat Välj ett par själv Söker efter drivrutiner… @@ -1924,6 +1929,8 @@ Butiker Butiksinställningar Inställningar + Ordna flikar + Klart (inte inloggad) Butik Bibliotek @@ -2150,7 +2157,7 @@ Storlek Spara Tillbaka till standard - Ritas ovanpå spelets bakgrund, som Steam gör. Exakt position kan skilja några pixlar. + Den exakta positionen kan avvika med några pixlar. Det här spelet har ingen logotyp än. Välj en under Logotyp för att se den här. Logotypens position kunde inte sparas. Försök igen. Bakgrund @@ -2679,7 +2686,7 @@ Startvideo Video DroidDeck · %1$d fps - 60 fps ser jämnare ut men använder mer CPU medan Steam startar. En startvideo vald i Steams egna inställningar har företräde. + 60 fps ser jämnare ut men använder mer CPU medan Steam startar. En video vald i Steams egna inställningar visas också här. Ljud Egen video MP4, MOV, MKV eller WebM. Andra format och filer över %1$d MB konverteras till 720p-WebM på enheten, upp till %2$d sekunder. @@ -2693,6 +2700,51 @@ Konverterar %1$s för Steam. Håll DroidDeck öppet. Enheten kan inte avkoda videon. Kunde inte importera videon + Ta bort %1$s? + Videon tas bort från DroidDeck och från Steams videomapp. + Installerade + Importera + SteamDeckRepo + Ljud + Installerade videor + Bläddra + DroidDeck + Importerad + SteamDeckRepo + Steam + Poängbutiken + Rapport om startfilmer + Sparar det DroidDeck och Steam vet om startfilmer i en textfil som du kan bifoga en felrapport. + Spara + Sparad i %1$s + Rapporten kunde inte sparas. + Volym + Längd + %1$d s + Hur många sekunder av filmen som spelas upp. Allt som är längre klipps bort i slutet. + Sök i SteamDeckRepo + Alla enheter + Steam Deck + Steam Machine + Trendar + Mest nedladdade + Mest gillade + Nyast + Kunde inte nå SteamDeckRepo + Försök igen + Inga videor hittades + Installera + Använd + Används + %1$s installerad + Kunde inte ladda ner videon + Föregående + Nästa + Sida %1$d + Rensa + Gå till sida + Förhandsvisa + Förhandsvisningen kunde inte spelas upp Luma Ultra-kameror — Experimentell Joy-Con-positionsspårning Använd smartglasögonens kameror för att placera dina parade Joy-Con-kontroller. Rotation och knappinmatningar kommer från Joy-Con-kontrollerna. Positionen uppskattas när dina handleder är dolda. Ersätter kontroller som manövreras med bara händer och pausar telefonkameran. Rikta Joy-Con-kontrollerna framåt när du ansluter eller återställer spårningscentret. @@ -2865,7 +2917,6 @@ Väntar på stabil huvudspårning; återställ spårningscenter om det begärs. Kameraobservation är för gammal; väntar på ett nytt par Fit %1$.2f px. Mät det valda avståndet från den vänstra kameran till kalibreringsmålets centrum och validera sedan. - OpenCV inte tillgängligt: %1$s %1$d sparade vyer återställda. Beräkna kalibreringen för att försöka igen, eller starta en ny uppsättning för att fånga mer. Fångad %1$d / 24 visningar. Håll kalibreringsmålet fixerat; flytta de smarta glasögonen för nästa vy. Bilden avvisades: %1$d / 12 nödvändiga hörn synliga i båda kamerorna. Visa mer av kalibreringsmålet, håll stilla och försök sedan igen. diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 8bdf43b37d..3a9157bb74 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -176,6 +176,8 @@ %1$s ผ่าน FEX โปรแกรมนี้สร้างมาสำหรับพีซี %1$s และรันผ่าน FEX ซึ่งยังไม่ได้ตั้งค่า เปิด Steam สักครั้งขณะลงชื่อเข้าใช้: DroidDeck จะดาวน์โหลด FEX และ Steam Linux Runtime ที่จำเป็น จากนั้นโปรแกรมนี้จะเปิดขึ้น โปรแกรมนี้ + ดาวน์โหลดไคลเอนต์ Steam ไม่ได้ เครือข่ายหรือ VPN ของคุณอาจบล็อกเซิร์ฟเวอร์ของ Steam ตรวจสอบการเชื่อมต่อแล้วลองอีกครั้ง + ตั้งค่าไคลเอนต์ Steam ไม่ได้ ตรวจสอบการเชื่อมต่อและพื้นที่ว่าง แล้วลองอีกครั้ง %1$s สร้างมาสำหรับพีซี x86 และรันผ่าน FEX ซึ่งยังไม่ได้ติดตั้ง เริ่ม Steam สักครั้งขณะลงชื่อเข้าใช้และให้ดาวน์โหลด FEX และ Steam Linux Runtime จากนั้นเริ่มโปรแกรมนี้อีกครั้ง รหัสแอป Flathub หรือหน้า Flathub ของมัน จะตั้งค่า Flatpak ก่อนหากยังไม่ได้ตั้งค่า ไฟล์ @@ -536,7 +538,7 @@ สำหรับ Adreno เท่านั้น สะดุดน้อยลง แต่ใช้แบตเตอรี่และเกิดความร้อนมากขึ้น การแก้ไขเซสชัน Turnip: การเรนเดอร์ sysmem - เร็วขึ้นสำหรับ Steam และเกมส่วนใหญ่ จำเป็นสำหรับ Adreno 710/720/722 + เร็วขึ้นสำหรับไคลเอนต์ Steam ในเกมไดรเวอร์จะเลือกการเรนเดอร์แบบไทล์หรือในหน่วยความจำระบบในแต่ละพาส จำเป็นสำหรับ Adreno 710/720/722 ข้ามตัวช่วย xalia ของ Steam droiddeck-ntsync (ทดลอง) ตัวแทนในระดับยูสเซอร์สเปซของไดรเวอร์ ntsync ของ Linux สำหรับการทดสอบ เมื่อเปิดใช้ Proton จะใช้สิ่งนี้แทน droiddeck-esync และ droiddeck-fsync ใช้ได้กับ Proton Experimental ARM64, GE-Proton และ proton-cachyos จะมีผลในเซสชันถัดไป @@ -1032,6 +1034,9 @@ เกมที่เพิ่ม เกมกำหนดเอง พื้นที่จัดเก็บเกม + ลบไฟล์และนำออกจาก Steam + ลบ %1$s? + ลบช็อตคัต ไฟล์เกมยังอยู่ คู่ที่ดีที่สุดสำหรับ GPU นี้ อัปเดตให้ล่าสุดเสมอ เลือกคู่ด้วยตัวเอง กำลังตรวจสอบไดรเวอร์… @@ -1903,6 +1908,8 @@ สโตร์ การตั้งค่าสโตร์ การตั้งค่า + จัดเรียงแท็บ + เสร็จสิ้น (ยังไม่ลงชื่อเข้าใช้) สโตร์ ไลบรารี @@ -2129,7 +2136,7 @@ ขนาด บันทึก กลับเป็นค่าเริ่มต้น - วาดทับพื้นหลังของเกมเหมือนที่ Steam ทำ ตำแหน่งจริงอาจต่างไปสองสามพิกเซล + ตำแหน่งที่แน่นอนอาจต่างกันไปไม่กี่พิกเซล เกมนี้ยังไม่มีโลโก้ เลือกในโลโก้เพื่อดูที่นี่ บันทึกตำแหน่งโลโก้ไม่ได้ ลองอีกครั้ง พื้นหลัง @@ -2654,7 +2661,7 @@ วิดีโอบูต วิดีโอ DroidDeck · %1$d fps - 60 fps ลื่นกว่าแต่ใช้ CPU มากขึ้นระหว่างที่ Steam กำลังเริ่ม วิดีโอเริ่มต้นที่เลือกในการตั้งค่าของ Steam เองจะมีลำดับความสำคัญกว่า + 60 fps ลื่นกว่าแต่ใช้ CPU มากขึ้นระหว่างที่ Steam กำลังเริ่ม วิดีโอที่เลือกในการตั้งค่าของ Steam เองจะแสดงที่นี่ด้วย เสียง วิดีโอของคุณเอง MP4, MOV, MKV หรือ WebM รูปแบบอื่นและไฟล์ที่ใหญ่กว่า %1$d MB จะถูกแปลงเป็น WebM 720p บนอุปกรณ์ ความยาวไม่เกิน %2$d วินาที @@ -2668,6 +2675,51 @@ กำลังแปลง %1$s สำหรับ Steam โปรดเปิด DroidDeck ค้างไว้ อุปกรณ์นี้ถอดรหัสวิดีโอนั้นไม่ได้ นำเข้าวิดีโอนี้ไม่ได้ + ลบ %1$s หรือไม่? + วิดีโอจะถูกลบออกจาก DroidDeck และจากโฟลเดอร์วิดีโอของ Steam + ติดตั้งแล้ว + นำเข้า + SteamDeckRepo + เสียง + วิดีโอที่ติดตั้งแล้ว + เรียกดู + DroidDeck + นำเข้าแล้ว + SteamDeckRepo + Steam + ร้านค้าแต้ม + รายงานวิดีโอเปิดเครื่อง + บันทึกสิ่งที่ DroidDeck และ Steam รู้เกี่ยวกับวิดีโอเปิดเครื่องลงในไฟล์ข้อความ เพื่อแนบกับรายงานข้อบกพร่อง + บันทึก + บันทึกไปที่ %1$s แล้ว + ไม่สามารถบันทึกรายงานได้ + ระดับเสียง + ความยาว + %1$d วิ + จำนวนวินาทีของภาพยนตร์ที่จะเล่น ส่วนที่ยาวเกินกว่านั้นจะถูกตัดออกที่ท้าย + ค้นหาใน SteamDeckRepo + ทุกอุปกรณ์ + Steam Deck + Steam Machine + มาแรง + ดาวน์โหลดมากที่สุด + ถูกใจมากที่สุด + ใหม่ล่าสุด + เชื่อมต่อ SteamDeckRepo ไม่ได้ + ลองอีกครั้ง + ไม่พบวิดีโอ + ติดตั้ง + ใช้ + กำลังใช้งาน + ติดตั้ง %1$s แล้ว + ดาวน์โหลดวิดีโอนั้นไม่ได้ + ก่อนหน้า + ถัดไป + หน้า %1$d + ล้าง + ไปที่หน้า + ดูตัวอย่าง + เล่นตัวอย่างไม่ได้ กล้อง Luma Ultra — ทดลอง การติดตามตำแหน่ง Joy-Con ใช้กล้องของแว่นตาอัจฉริยะเพื่อกำหนดตำแหน่งคอนโทรลเลอร์ Joy-Con ที่จับคู่ไว้ การหมุนและการกดปุ่มจะมาจากคอนโทรลเลอร์ Joy-Con ตำแหน่งจะถูกประมาณเมื่อข้อมือของคุณถูกซ่อนอยู่ แทนที่คอนโทรลเลอร์ที่ใช้งานด้วยมือเปล่าและหยุดการติดตามของกล้องโทรศัพท์ชั่วคราว ชี้คอนโทรลเลอร์ Joy-Con ไปข้างหน้าเมื่อเชื่อมต่อหรือรีเซ็ตศูนย์กลางการติดตาม @@ -2841,7 +2893,6 @@ กำลังรอการติดตามศีรษะที่เสถียร รีเซ็ตจุดศูนย์กลางการติดตามหากมีการร้องขอ การสังเกตด้วยกล้องเก่าเกินไป รอคู่ใหม่ครับ พอดี %1$.2f พิกเซล วัดระยะทางที่คุณเลือกจากกล้องด้านซ้ายไปยังศูนย์กลางเป้าหมายการสอบเทียบ จากนั้นตรวจสอบ - OpenCV ไม่พร้อมใช้งาน: %1$s ถ่ายแล้ว %1$d / 24 ครั้ง รักษาเป้าหมายการสอบเทียบให้คงที่ เลื่อนแว่นตาอัจฉริยะเพื่อดูมุมมองถัดไป การจับภาพถูกปฏิเสธ: %1$d / 12 มุมที่ต้องมองเห็นได้ในกล้องทั้งสองตัว แสดงเป้าหมายการสอบเทียบเพิ่มเติม ให้ค้างไว้แล้วลองอีกครั้ง การตรวจสอบระยะทางไม่เสร็จสิ้น: %1$s ลองอีกครั้ง diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index a81213aefb..9e6b9ab15d 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -176,6 +176,8 @@ FEX ile %1$s Bu program %1$s PC\'ler için derlenmiş ve FEX ile çalışır, ancak FEX henüz kurulmadı. Oturum açmışken Steam\'i bir kez açın: DroidDeck, FEX\'i ve gereken Steam Linux Runtime\'ı indirtir, ardından bu program açılır. Bu program + Steam istemcisi indirilemedi. Ağınız veya VPN\'iniz Steam sunucularını engelliyor olabilir; bağlantıyı kontrol edip yeniden deneyin. + Steam istemcisi kurulamadı. Bağlantınızı ve boş depolama alanını kontrol edip yeniden deneyin. %1$s x86 PC\'ler için derlenmiş ve FEX ile çalışır, ancak FEX henüz yüklü değil. Oturum açmışken Steam\'i bir kez başlatıp FEX\'i ve Steam Linux Runtime\'ı indirmesini bekleyin, ardından bunu yeniden başlatın. Bir Flathub uygulama kimliği veya Flathub sayfası. Flatpak henüz kurulu değilse önce o kurulur. Dosya @@ -535,7 +537,7 @@ Yalnızca Adreno. Daha az takılma, daha fazla pil tüketimi ve ısınma. Oturum düzeltmeleri Turnip: sysmem işleme - Steam ve çoğu oyun için daha hızlı. Adreno 710/720/722\'de gereklidir. + Steam istemcisi için daha hızlı; oyunlarda sürücü her geçişte döşeme tabanlı veya sistem belleğinde işlemeyi seçer. Adreno 710/720/722\'de gereklidir. Steam\'in xalia yardımcısını atla droiddeck-ntsync (deneysel) Linux ntsync sürücüsünün test amaçlı, kullanıcı alanında çalışan bir yedeği. Açıkken Proton, droiddeck-esync ve droiddeck-fsync yerine bunu kullanır. Proton Experimental ARM64, GE-Proton ve proton-cachyos ile çalışır. Sonraki oturumda uygulanır. @@ -1027,6 +1029,9 @@ Eklenen oyun Özel oyun Oyun depolama alanı + Dosyalarını siler ve Steam\'den kaldırır. + Kaldır: %1$s? + Kısayolunu siler. Oyun dosyaları kalır. Bu GPU için en iyi çift, güncel tutulur Çifti kendiniz seçin Sürücüler kontrol ediliyor… @@ -1913,6 +1918,8 @@ Mağazalar Mağaza ayarları Ayarlar + Sekmeleri düzenle + Bitti (oturum açılmadı) Mağaza Kütüphane @@ -2136,7 +2143,7 @@ Boyut Kaydet Varsayılana döndür - Steam\'in yaptığı gibi oyunun arka planının üzerine çizilir. Tam konum birkaç piksel değişebilir. + Tam konum birkaç piksel farklı olabilir. Bu oyunun henüz logosu yok. Burada görmek için Logo bölümünden bir tane seçin. Logo konumu kaydedilemedi. Yeniden deneyin. Arka plan @@ -2679,7 +2686,7 @@ Açılış videosu Video DroidDeck · %1$d fps - 60 fps daha akıcı görünür ama Steam açılırken işlemciyi daha çok kullanır. Steam\'in kendi ayarlarında seçilen açılış videosu önceliklidir. + 60 fps daha akıcı görünür ama Steam açılırken işlemciyi daha çok kullanır. Steam\'in kendi ayarlarında seçilen bir video da burada görünür. Ses Kendi videon MP4, MOV, MKV veya WebM. Diğer biçimler ve %1$d MB üzeri dosyalar cihazda 720p WebM\'e dönüştürülür, en fazla %2$d saniye. @@ -2693,6 +2700,51 @@ %1$s Steam için dönüştürülüyor. DroidDeck\'i açık tut. Bu cihaz o videonun kodunu çözemiyor. Video içe aktarılamadı + %1$s kaldırılsın mı? + Video, DroidDeck\'ten ve Steam\'in videolar klasöründen silinir. + Yüklü + İçe aktar + SteamDeckRepo + Ses + Yüklü videolar + Göz at + DroidDeck + İçe aktarılan + SteamDeckRepo + Steam + Puan Mağazası + Açılış videosu raporu + DroidDeck ve Steam’in açılış videoları hakkında bildiklerini, hata raporuna ekleyebileceğiniz bir metin dosyasına kaydeder. + Kaydet + %1$s konumuna kaydedildi + Rapor kaydedilemedi. + Ses düzeyi + Süre + %1$d sn + Videonun kaç saniyesinin oynatılacağı. Daha uzun olan kısım sonunda kesilir. + SteamDeckRepo\'da ara + Tüm cihazlar + Steam Deck + Steam Machine + Trend + En çok indirilen + En çok beğenilen + En yeni + SteamDeckRepo\'ya ulaşılamadı + Tekrar dene + Video bulunamadı + Yükle + Kullan + Kullanımda + %1$s yüklendi + Video indirilemedi + Önceki + Sonraki + Sayfa %1$d + Temizle + Sayfaya git + Önizle + Önizleme oynatılamadı Luma Ultra kameralar — Deneysel Joy-Con konum takibi Eşleştirilmiş Joy-Con kumandalarınızı konumlandırmak için akıllı gözlük kameralarını kullanın. Döndürme ve düğme girişleri Joy-Con kumandalarından gelir. Bilekleriniz gizlendiğinde konum tahmin edilir. Çıplak elle çalıştırılan kumandaların yerini alır ve telefon kamerası izlemesini duraklatır. İzleme merkezini bağlarken veya sıfırlarken Joy-Con kumandalarını ileriye doğru çevirin. @@ -2865,7 +2917,6 @@ Sabit kafa izlemesi bekleniyor; istenirse izleme merkezini sıfırlayın Kamera gözlemi çok eski; yeni bir çift bekliyorum %1$.2f piksele sığdır. Sol kameradan kalibrasyon hedef merkezine kadar seçtiğiniz mesafeyi ölçün ve ardından doğrulayın. - OpenCV kullanılamıyor: %1$s %1$d kayıtlı görünüm geri yüklendi. Yeniden denemek için kalibrasyonu hesaplayın veya daha fazlasını yakalamak için yeni bir set başlatın. Yakalandı %1$d / 24 görüntüleme. Kalibrasyon hedefini sabit tutun; Bir sonraki görünüm için akıllı gözlükleri hareket ettirin. Yakalama reddedildi: %1$d / 12 gerekli köşe her iki kamerada da görünüyor. Kalibrasyon hedefinin daha fazlasını gösterin, sabit durun ve tekrar deneyin. diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 2af43de099..931caa8ade 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -176,6 +176,8 @@ %1$s через FEX Цю програму зібрано для ПК з архітектурою %1$s, і вона працює через FEX, який ще не налаштовано. Один раз відкрийте Steam, увійшовши в обліковий запис: DroidDeck завантажить FEX і потрібний йому Steam Linux Runtime, після чого програма відкриється. Ця програма + Не вдалося завантажити клієнт Steam. Можливо, ваша мережа або VPN блокує сервери Steam; перевірте з’єднання та спробуйте ще раз. + Не вдалося налаштувати клієнт Steam. Перевірте з’єднання та вільне місце, потім спробуйте ще раз. %1$s зібрано для ПК x86; для запуску потрібен FEX, який ще не встановлено. Один раз запустіть Steam, увійшовши в обліковий запис, дайте йому завантажити FEX і Steam Linux Runtime, а потім запустіть це знову. ID додатка Flathub або його сторінка на Flathub. Якщо Flatpak ще не налаштовано, його буде налаштовано спочатку. Файл @@ -542,7 +544,7 @@ Лише Adreno. Менше запинок, вища витрата заряду та нагрів. Виправлення сеансу Turnip: рендеринг через sysmem - Швидше для Steam і більшості ігор. Потрібно для Adreno 710/720/722. + Швидше для клієнта Steam; в іграх драйвер для кожного проходу вибирає тайловий рендеринг або рендеринг у системній пам’яті. Потрібно для Adreno 710/720/722. Пропускати помічник Steam xalia droiddeck-ntsync (експериментально) Програмна заміна драйвера ntsync ядра Linux у просторі користувача, для тестування. Поки це увімкнено, Proton використовує її замість droiddeck-esync і droiddeck-fsync. Працює з Proton Experimental ARM64, GE-Proton і proton-cachyos. Застосовується в наступному сеансі. @@ -1050,6 +1052,9 @@ Додана гра Власна гра Сховище ігор + Видаляє її файли та прибирає її зі Steam. + Видалити %1$s? + Видаляє ярлик. Файли гри залишаються. Найкраща пара для цього GPU, завжди в актуальному стані Виберіть пару самостійно Перевірка драйверів… @@ -1966,6 +1971,8 @@ Магазини Налаштування магазинів Налаштування + Упорядкувати вкладки + Готово (вхід не виконано) Магазин Бібліотека @@ -2192,7 +2199,7 @@ Розмір Зберегти Повернути типове - Малюється поверх тла гри, як це робить Steam. Точна позиція може відрізнятися на кілька пікселів. + Точне розташування може відрізнятися на кілька пікселів. У цієї гри ще немає логотипу. Виберіть його в розділі Логотип, щоб побачити тут. Не вдалося зберегти позицію логотипу. Спробуйте ще раз. Фон @@ -2747,7 +2754,7 @@ Завантажувальне відео Відео DroidDeck · %1$d кадр/с - 60 кадр/с виглядає плавніше, але більше навантажує процесор під час запуску Steam. Відео запуску, вибране в налаштуваннях самого Steam, має пріоритет. + 60 кадр/с виглядає плавніше, але більше навантажує процесор під час запуску Steam. Відео, вибране в налаштуваннях самого Steam, також з\'являється тут. Звук Власне відео MP4, MOV, MKV або WebM. Інші формати й файли понад %1$d МБ перетворюються на пристрої на WebM 720p, до %2$d секунд. @@ -2761,6 +2768,51 @@ %1$s перетворюється для Steam. Не закривайте DroidDeck. Пристрій не може декодувати це відео. Не вдалося імпортувати відео + Видалити %1$s? + Відео буде видалено з DroidDeck і з папки відео Steam. + Встановлені + Імпорт + SteamDeckRepo + Звук + Встановлені відео + Огляд + DroidDeck + Імпортовано + SteamDeckRepo + Steam + Магазин балів + Звіт про завантажувальні ролики + Зберігає в текстовий файл те, що DroidDeck і Steam знають про завантажувальні ролики, щоб додати до повідомлення про помилку. + Зберегти + Збережено: %1$s + Не вдалося зберегти звіт. + Гучність + Тривалість + %1$d с + Скільки секунд фільму відтворюється. Усе, що довше, обрізається в кінці. + Пошук у SteamDeckRepo + Усі пристрої + Steam Deck + Steam Machine + У тренді + Найбільше завантажень + Найбільше вподобань + Нові + Не вдалося підключитися до SteamDeckRepo + Повторити + Відео не знайдено + Встановити + Використати + Використовується + %1$s встановлено + Не вдалося завантажити це відео + Назад + Далі + Сторінка %1$d + Очистити + Перейти на сторінку + Перегляд + Не вдалося відтворити перегляд Камери Luma Ultra — Експериментально Відстеження положення Joy-Con Використовуйте камери розумних окулярів, щоб розташувати парні контролери Joy-Con. Обертання та введення кнопок надходять від контролерів Joy-Con. Положення оцінюється, коли ваші зап\'ястя приховані. Замінює контролери, якими керують голими руками, та призупиняє відстеження камерою телефону. Направте контролери Joy-Con вперед під час підключення або скидання центру відстеження. @@ -2933,7 +2985,6 @@ Очікування стабільного відстеження голови; скиньте центр відстеження, якщо запитується. Камера спостереження занадто стара; в очікуванні свіжої пари Розмістити %1$.2f пікс. Виміряйте вибрану відстань від лівої камери до центру калібрувальної мішені, а потім перевірте. - OpenCV недоступний: %1$s %1$d збережені перегляди відновлено. Обчисліть калібрування, щоб повторити спробу, або почніть новий набір, щоб отримати більше. Знято %1$d / 24 перегляди. Тримайте цілі калібрування фіксованими; перемістіть розумні окуляри для наступного перегляду. Зйомку відхилено: %1$d / 12 необхідних кутів видно в обох камерах. Покажіть більше калібрувальної мішені, затримайтеся та повторіть спробу. diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 70026208ad..d636a67ead 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -176,6 +176,8 @@ %1$s qua FEX Chương trình này được build cho PC %1$s và chạy qua FEX, hiện chưa được thiết lập. Mở Steam một lần khi đã đăng nhập: DroidDeck sẽ tải FEX và Steam Linux Runtime cần thiết, sau đó ứng dụng này sẽ mở. Chương trình này + Không thể tải xuống client Steam. Mạng hoặc VPN của bạn có thể đang chặn máy chủ Steam; hãy kiểm tra kết nối rồi thử lại. + Không thể thiết lập client Steam. Hãy kiểm tra kết nối và dung lượng trống rồi thử lại. %1$s được build cho PC x86 và chạy qua FEX, hiện chưa được cài. Khởi động Steam một lần khi đã đăng nhập và để nó tải FEX cùng Steam Linux Runtime, sau đó khởi động lại ứng dụng này. Một app ID Flathub hoặc trang Flathub của nó. Flatpak sẽ được thiết lập trước nếu chưa có. Tệp @@ -536,7 +538,7 @@ Chỉ dành cho Adreno. Ít giật hơn, dùng nhiều pin và nhiệt hơn. Các bản sửa phiên Turnip: render sysmem - Nhanh hơn cho Steam và hầu hết game. Bắt buộc trên Adreno 710/720/722. + Nhanh hơn cho ứng dụng Steam; trong game, trình điều khiển chọn kết xuất theo ô hoặc trong bộ nhớ hệ thống cho từng lượt. Bắt buộc trên Adreno 710/720/722. Bỏ qua trình trợ giúp xalia của Steam droiddeck-ntsync (thử nghiệm) Một bản thay thế ở không gian người dùng cho driver ntsync của Linux, dùng để thử nghiệm. Khi đang bật, Proton dùng nó thay cho droiddeck-esync và droiddeck-fsync. Hoạt động với Proton Experimental ARM64, GE-Proton và proton-cachyos. Áp dụng từ phiên sau. @@ -1032,6 +1034,9 @@ Game đã thêm Game tùy chỉnh Lưu trữ game + Xóa các tệp của nó và gỡ nó khỏi Steam. + Xóa %1$s? + Xóa shortcut của nó. Các tệp game vẫn còn. Cặp tốt nhất cho GPU này, luôn được cập nhật Tự chọn một cặp Đang kiểm tra driver… @@ -1903,6 +1908,8 @@ Cửa hàng Thiết lập Stores Thiết lập + Sắp xếp thẻ + Xong (chưa đăng nhập) Cửa hàng Thư viện @@ -2129,7 +2136,7 @@ Kích thước Lưu Về mặc định - Được vẽ đè lên nền game như Steam làm. Vị trí chính xác có thể lệch vài pixel. + Vị trí chính xác có thể lệch vài pixel. Game này chưa có logo. Chọn một logo để xem tại đây. Không lưu được vị trí logo. Thử lại. Hình nền @@ -2654,7 +2661,7 @@ Video khởi động Video DroidDeck · %1$d fps - 60 fps mượt hơn nhưng tốn CPU hơn khi Steam đang khởi động. Video khởi động chọn trong cài đặt của chính Steam sẽ được ưu tiên. + 60 fps mượt hơn nhưng tốn CPU hơn khi Steam đang khởi động. Video chọn trong cài đặt của chính Steam cũng hiện ở đây. Âm thanh Video của bạn MP4, MOV, MKV hoặc WebM. Định dạng khác và tệp trên %1$d MB được chuyển sang WebM 720p ngay trên thiết bị, tối đa %2$d giây. @@ -2668,6 +2675,51 @@ Đang chuyển đổi %1$s cho Steam. Hãy để DroidDeck mở. Thiết bị này không giải mã được video đó. Không thể nhập video này + Xóa %1$s? + Thao tác này xóa video khỏi DroidDeck và khỏi thư mục video của Steam. + Đã cài + Nhập + SteamDeckRepo + Âm thanh + Video đã cài + Duyệt + DroidDeck + Đã nhập + SteamDeckRepo + Steam + Cửa hàng điểm + Báo cáo phim khởi động + Lưu những gì DroidDeck và Steam biết về phim khởi động vào một tệp văn bản để đính kèm báo cáo lỗi. + Lưu + Đã lưu vào %1$s + Không thể lưu báo cáo. + Âm lượng + Độ dài + %1$d giây + Số giây của phim sẽ được phát. Phần dài hơn sẽ bị cắt ở cuối. + Tìm trong SteamDeckRepo + Tất cả thiết bị + Steam Deck + Steam Machine + Thịnh hành + Tải nhiều nhất + Thích nhiều nhất + Mới nhất + Không kết nối được SteamDeckRepo + Thử lại + Không tìm thấy video + Cài đặt + Dùng + Đang dùng + Đã cài %1$s + Không thể tải video đó + Trước + Tiếp + Trang %1$d + Xóa + Đến trang + Xem trước + Không thể phát bản xem trước Camera Luma Ultra — Thử nghiệm Theo dõi vị trí Joy-Con Sử dụng camera của kính thông minh để định vị bộ điều khiển Joy-Con đã ghép nối. Xoay và nhập nút đến từ bộ điều khiển Joy-Con. Vị trí được ước tính khi cổ tay của bạn bị che khuất. Thay thế bộ điều khiển được điều khiển bằng tay không và tạm dừng theo dõi bằng camera điện thoại. Hướng bộ điều khiển Joy-Con về phía trước khi kết nối hoặc đặt lại trung tâm theo dõi. @@ -2840,7 +2892,6 @@ Đang chờ theo dõi đầu ổn định; đặt lại trung tâm theo dõi nếu được yêu cầu Camera quan sát quá cũ; đang chờ một cặp mới Vừa vặn %1$.2f px. Đo khoảng cách đã chọn của bạn từ camera bên trái đến trung tâm mục tiêu hiệu chỉnh, sau đó xác thực. - OpenCV không có sẵn: %1$s %1$d lượt xem đã lưu được khôi phục. Tính toán hiệu chuẩn để thử lại hoặc bắt đầu một bộ mới để thu được nhiều dữ liệu hơn. Đã chụp được %1$d / 24 lượt xem. Giữ mục tiêu hiệu chuẩn cố định; di chuyển kính thông minh để xem tiếp theo. Ảnh chụp bị từ chối: %1$d / 12 góc bắt buộc hiển thị ở cả hai máy ảnh. Hiển thị thêm mục tiêu hiệu chỉnh, giữ yên rồi thử lại. diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 7de45e1b82..f513e51a9f 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -176,6 +176,8 @@ %1$s 经由 FEX 此程序面向 %1$s PC 构建,需经由 FEX 运行,而 FEX 尚未配置。请在登录状态下打开一次 Steam:DroidDeck 会让其下载 FEX 及所需的 Steam Linux Runtime,之后即可打开。 此程序 + 无法下载 Steam 客户端。你的网络或 VPN 可能屏蔽了 Steam 的服务器;请检查网络连接后重试。 + 无法设置 Steam 客户端。请检查网络连接和可用存储空间,然后重试。 %1$s 面向 x86 PC 构建,需经由 FEX 运行,而 FEX 尚未安装。请在登录状态下启动一次 Steam,让其下载 FEX 与 Steam Linux Runtime,然后重新启动。 一个 Flathub 应用 ID 或其 Flathub 页面。若尚未配置 Flatpak 会先进行配置。 文件 @@ -536,7 +538,7 @@ 仅限 Adreno。卡顿更少,但更耗电、更发热。 会话修复 Turnip:sysmem 渲染 - 对 Steam 和大多数游戏更快。Adreno 710/720/722 必需。 + Steam 客户端更快;游戏中驱动会为每个渲染通道选择分块渲染或系统内存渲染。Adreno 710/720/722 必需。 跳过 Steam 的 xalia 助手 droiddeck-ntsync(实验性) Linux ntsync 驱动的用户态替代品,供测试使用。开启时,Proton 使用它代替 droiddeck-esync 和 droiddeck-fsync。适用于 Proton Experimental ARM64、GE-Proton 和 proton-cachyos。将在下次会话生效。 @@ -764,7 +766,7 @@ 大小 保存 重置为默认 - 显示在游戏背景上,与 Steam 的绘制方式一致。具体位置可能相差几个像素。 + 确切位置可能相差几个像素。 该游戏还没有标志。在标志中选择一个即可在此查看。 无法保存标志位置。请重试。 搜索 SteamGridDB… @@ -1114,6 +1116,9 @@ 已添加游戏 自定义游戏 游戏存储 + 删除游戏文件并从 Steam 中移除。 + 移除 %1$s? + 删除快捷方式,游戏文件保留。 为此 GPU 挑选的最佳组合,并保持更新 自行挑选驱动组合 正在检查驱动… @@ -1979,6 +1984,8 @@ 游戏商店 游戏商店设置 设置 + 整理标签 + 完成 (未登录) 商店 库 @@ -2654,7 +2661,7 @@ 开机动画 视频 DroidDeck · %1$d fps - 60 fps 更流畅,但 Steam 启动时会占用更多 CPU。在 Steam 自身设置中选择的启动动画优先。 + 60 fps 更流畅,但 Steam 启动时会占用更多 CPU。在 Steam 自身设置中选择的动画也会显示在这里。 声音 自定义视频 MP4、MOV、MKV 或 WebM。其他格式及超过 %1$d MB 的文件会在设备上转换为 720p WebM,最长 %2$d 秒。 @@ -2668,6 +2675,51 @@ 正在为 Steam 转换 %1$s。请保持 DroidDeck 打开。 此设备无法解码该视频。 无法导入该视频 + 移除 %1$s? + 这会从 DroidDeck 和 Steam 的动画文件夹中删除该动画。 + 已安装 + 导入 + SteamDeckRepo + 声音 + 已安装的动画 + 浏览 + DroidDeck + 已导入 + SteamDeckRepo + Steam + 点数商店 + 启动影片报告 + 将 DroidDeck 和 Steam 掌握的启动影片信息保存为文本文件,可附在错误报告中。 + 保存 + 已保存到 %1$s + 无法保存报告。 + 音量 + 时长 + %1$d 秒 + 播放影片的秒数。超出该时长的部分会在结尾被截断。 + 搜索 SteamDeckRepo + 所有设备 + Steam Deck + Steam Machine + 热门 + 下载最多 + 最受欢迎 + 最新 + 无法连接 SteamDeckRepo + 重试 + 未找到动画 + 安装 + 使用 + 使用中 + 已安装 %1$s + 无法下载该动画 + 上一页 + 下一页 + 第 %1$d 页 + 清除 + 转到页面 + 预览 + 无法播放此预览 Luma Ultra 摄像头 — 实验性功能 Joy-Con 位置追踪 使用智能眼镜摄像头定位已配对的 Joy-Con 控制器。旋转和按键输入来自 Joy-Con 控制器。当您的手腕被遮挡时,系统会估算位置。此功能会取代徒手操作的控制器,并暂停手机摄像头追踪。连接或重置追踪中心时,请将 Joy-Con 控制器指向前方。 @@ -2838,7 +2890,6 @@ 正在等待稳定的头部追踪;如果需要,请重置追踪中心。 相机观察太旧;等待一双新的 适合 %1$.2f 像素。测量您选择的从左摄像头到校准目标中心的距离,然后进行验证。 - OpenCV 不可用:%1$s %1$d 已恢复保存的视图。计算校准以重试,或开始新的一组以捕获更多。 已捕获 %1$d / 24 次观看。保持校准目标固定;移动智能眼镜以查看下一个视图。 捕获被拒绝:%1$d / 12 个必需的角在两个摄像头中均可见。显示更多校准目标,保持不动,然后重试。 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index 66207ea8d0..10cc860e71 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -176,6 +176,8 @@ %1$s,透過 FEX 此程式是為 %1$s 電腦而設,需透過 FEX 執行,但 FEX 尚未設定。請在登入狀態下開啟一次 Steam:DroidDeck 會讓它下載 FEX 及所需的 Steam Linux Runtime,之後便會開啟此程式。 此程式 + 無法下載 Steam 用戶端。你的網絡或 VPN 可能封鎖了 Steam 的伺服器;請檢查連線後再試。 + 無法設定 Steam 用戶端。請檢查連線和可用儲存空間,然後再試。 %1$s 是為 x86 電腦而設,需透過 FEX 執行,但 FEX 尚未安裝。請在登入狀態下啟動一次 Steam,讓它下載 FEX 和 Steam Linux Runtime,然後再啟動此程式。 Flathub 應用程式 ID 或其 Flathub 頁面。如尚未設定 Flatpak,會先進行設定。 檔案 @@ -536,7 +538,7 @@ 只限 Adreno。減少卡頓,但更耗電、更發熱。 會話修正 Turnip:sysmem 渲染 - Steam 和大部分遊戲會更快。Adreno 710/720/722 必須開啟。 + Steam 用戶端會更快;遊戲中驅動程式會為每個渲染通道選擇分塊渲染或系統記憶體渲染。Adreno 710/720/722 必須開啟。 略過 Steam 的 xalia 輔助程式 droiddeck-ntsync(實驗性) 在用戶空間代替 Linux ntsync 驅動程式,供測試使用。開啟時,Proton 會使用它而非 droiddeck-esync 和 droiddeck-fsync。適用於 Proton Experimental ARM64、GE-Proton 和 proton-cachyos。下次會話生效。 @@ -1032,6 +1034,9 @@ 已新增的遊戲 自訂遊戲 遊戲儲存位置 + 刪除遊戲檔案並從 Steam 中移除。 + 移除 %1$s? + 刪除捷徑,遊戲檔案保留。 此 GPU 的最佳組合,並會保持最新 自行選擇組合 正在檢查驅動程式… @@ -1903,6 +1908,8 @@ 商店 商店設定 設定 + 整理標籤 + 完成 (未登入) 商店 收藏庫 @@ -2129,7 +2136,7 @@ 大小 儲存 還原預設 - 顯示在遊戲背景上,與 Steam 的繪製方式一致。實際位置可能相差幾個像素。 + 確切位置可能相差幾個像素。 此遊戲尚無標誌。請在標誌中選擇一個,即可在此檢視。 無法儲存標誌位置。請再試一次。 背景 @@ -2654,7 +2661,7 @@ 開機動畫 影片 DroidDeck · %1$d fps - 60 fps 較流暢,但 Steam 啟動時會使用較多 CPU。在 Steam 本身設定中選擇的啟動動畫優先。 + 60 fps 較流暢,但 Steam 啟動時會使用較多 CPU。在 Steam 本身設定中選擇的動畫也會顯示在這裡。 聲音 自訂影片 MP4、MOV、MKV 或 WebM。其他格式及超過 %1$d MB 的檔案會在裝置上轉換為 720p WebM,最長 %2$d 秒。 @@ -2668,6 +2675,51 @@ 正在為 Steam 轉換 %1$s。請保持 DroidDeck 開啟。 此裝置無法解碼該影片。 無法匯入此影片 + 移除 %1$s? + 這會從 DroidDeck 和 Steam 的動畫資料夾中刪除該動畫。 + 已安裝 + 匯入 + SteamDeckRepo + 聲音 + 已安裝的動畫 + 瀏覽 + DroidDeck + 已匯入 + SteamDeckRepo + Steam + 點數商店 + 啟動影片報告 + 將 DroidDeck 和 Steam 掌握的啟動影片資訊儲存為文字檔,可附在錯誤報告中。 + 儲存 + 已儲存到 %1$s + 無法儲存報告。 + 音量 + 長度 + %1$d 秒 + 播放影片的秒數。超出該時長的部分會在結尾被截斷。 + 搜尋 SteamDeckRepo + 所有裝置 + Steam Deck + Steam Machine + 熱門 + 下載最多 + 最受歡迎 + 最新 + 無法連接 SteamDeckRepo + 重試 + 找不到動畫 + 安裝 + 使用 + 使用中 + 已安裝 %1$s + 無法下載該動畫 + 上一頁 + 下一頁 + 第 %1$d 頁 + 清除 + 前往頁面 + 預覽 + 無法播放此預覽 Luma Ultra 相機 — 實驗性功能 Joy-Con 位置追踪 使用智慧眼鏡攝影機定位已配對的 Joy-Con 控制器。旋轉和按鍵輸入來自 Joy-Con 控制器。當您的手腕被遮住時,系統會估算位置。此功能會取代徒手操作的控制器,並暫停手機相機追蹤。連接或重設追蹤中心時,請將 Joy-Con 控制器指向前方。 @@ -2838,7 +2890,6 @@ 正在等待穩定的頭部追蹤;如果需要,請重設追蹤中心。 相機觀察太舊;等待一雙新的 適合 %1$.2f 像素。測量您選擇的從左側攝影機到校準目標中心的距離,然後進行驗證。 - OpenCV 不可用:%1$s %1$d 已恢復已儲存的視圖。計算校準以重試,或開始新的一組以捕獲更多。 已捕獲 %1$d / 24 次觀看。保持校準目標固定;移動智慧眼鏡以查看下一個視圖。 捕捉被拒絕:%1$d / 12 個必需的角落在兩個攝影機中均可見。顯示更多校準目標,保持不動,然後重試。 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index 7fdd8c25b1..e11242c246 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -176,6 +176,8 @@ 透過 FEX 執行 %1$s 此程式是為 %1$s 電腦組建的,需透過 FEX 執行,但 FEX 尚未設定。請在登入狀態下開啟一次 Steam:DroidDeck 會讓它下載 FEX 和所需的 Steam Linux Runtime,之後就能開啟此程式。 此程式 + 無法下載 Steam 用戶端。你的網路或 VPN 可能封鎖了 Steam 的伺服器;請檢查連線後再試一次。 + 無法設定 Steam 用戶端。請檢查連線和可用儲存空間,然後再試一次。 %1$s 是為 x86 電腦組建的,需透過 FEX 執行,但 FEX 尚未安裝。請在登入狀態下啟動一次 Steam,讓它下載 FEX 和 Steam Linux Runtime,然後再重新啟動此程式。 Flathub 應用程式 ID 或其 Flathub 頁面。如果尚未設定 Flatpak,會先進行設定。 檔案 @@ -536,7 +538,7 @@ 僅適用於 Adreno。卡頓更少,但耗電和發熱更多。 工作階段修復 Turnip:sysmem 渲染 - Steam 和大多數遊戲會更快。Adreno 710/720/722 必需。 + Steam 用戶端會更快;遊戲中驅動程式會為每個算繪通道選擇分塊算繪或系統記憶體算繪。Adreno 710/720/722 必需。 跳過 Steam 的 xalia 輔助程式 droiddeck-ntsync(實驗性) 以使用者空間替代 Linux ntsync 驅動程式,供測試使用。開啟時,Proton 會使用它來取代 droiddeck-esync 和 droiddeck-fsync。適用於 Proton Experimental ARM64、GE-Proton 和 proton-cachyos。下次工作階段生效。 @@ -1032,6 +1034,9 @@ 已新增的遊戲 自訂遊戲 遊戲儲存空間 + 刪除遊戲檔案並從 Steam 中移除。 + 要移除 %1$s 嗎? + 刪除捷徑,遊戲檔案保留。 為此 GPU 選擇最佳驅動程式組合,並保持最新 自行選擇驅動程式組合 正在檢查驅動程式… @@ -1903,6 +1908,8 @@ 遊戲商店 遊戲商店設定 設定 + 整理分頁 + 完成 (未登入) 商店 收藏庫 @@ -2129,7 +2136,7 @@ 大小 儲存 還原預設 - 顯示在遊戲背景上,與 Steam 的繪製方式一致。實際位置可能相差幾個像素。 + 確切位置可能相差幾個像素。 此遊戲尚無標誌。請在標誌中選擇一個,即可在此檢視。 無法儲存標誌位置。請再試一次。 背景 @@ -2654,7 +2661,7 @@ 開機動畫 影片 DroidDeck · %1$d fps - 60 fps 較流暢,但 Steam 啟動時會使用較多 CPU。在 Steam 本身設定中選擇的啟動動畫優先。 + 60 fps 較流暢,但 Steam 啟動時會使用較多 CPU。在 Steam 本身設定中選擇的動畫也會顯示在這裡。 聲音 自訂影片 MP4、MOV、MKV 或 WebM。其他格式及超過 %1$d MB 的檔案會在裝置上轉換為 720p WebM,最長 %2$d 秒。 @@ -2668,6 +2675,51 @@ 正在為 Steam 轉換 %1$s。請保持 DroidDeck 開啟。 此裝置無法解碼該影片。 無法匯入此影片 + 移除 %1$s? + 這會從 DroidDeck 和 Steam 的動畫資料夾中刪除該動畫。 + 已安裝 + 匯入 + SteamDeckRepo + 聲音 + 已安裝的動畫 + 瀏覽 + DroidDeck + 已匯入 + SteamDeckRepo + Steam + 點數商店 + 啟動影片報告 + 將 DroidDeck 和 Steam 掌握的啟動影片資訊儲存為文字檔,可附在錯誤報告中。 + 儲存 + 已儲存到 %1$s + 無法儲存報告。 + 音量 + 長度 + %1$d 秒 + 播放影片的秒數。超出該時長的部分會在結尾被截斷。 + 搜尋 SteamDeckRepo + 所有裝置 + Steam Deck + Steam Machine + 熱門 + 下載最多 + 最受歡迎 + 最新 + 無法連線至 SteamDeckRepo + 重試 + 找不到動畫 + 安裝 + 使用 + 使用中 + 已安裝 %1$s + 無法下載該動畫 + 上一頁 + 下一頁 + 第 %1$d 頁 + 清除 + 前往頁面 + 預覽 + 無法播放此預覽 Luma Ultra 相機 — 實驗性功能 Joy-Con 位置追踪 使用智慧眼鏡攝影機定位已配對的 Joy-Con 控制器。旋轉和按鍵輸入來自 Joy-Con 控制器。當您的手腕被遮住時,系統會估算位置。此功能會取代徒手操作的控制器,並暫停手機相機追蹤。連接或重設追蹤中心時,請將 Joy-Con 控制器指向前方。 @@ -2838,7 +2890,6 @@ 正在等待穩定的頭部追蹤;如果需要,請重設追蹤中心。 相機觀察太舊;等待一雙新的 適合 %1$.2f 像素。測量您選擇的從左側攝影機到校準目標中心的距離,然後進行驗證。 - OpenCV 不可用:%1$s %1$d 已恢復已儲存的視圖。計算校準以重試,或開始新的一組以捕獲更多。 已捕獲 %1$d / 24 次觀看。保持校準目標固定;移動智慧眼鏡以查看下一個視圖。 捕捉被拒絕:%1$d / 12 個必需的角落在兩個攝影機中均可見。顯示更多校準目標,保持不動,然後重試。 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ff90ecb9a7..ebef852975 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -90,6 +90,7 @@ Set to 1 to keep this game off droiddeck-fsync; it uses droiddeck-esync where a pack exists, otherwise droiddeck-ntsync. Set to 1 to run this game on droiddeck-fsync, or 0 to put droiddeck-esync first where a pack fits its Proton. Set to 0 to disable Proton’s gamepad-navigation helper for this game. + On by default. Starts an Easy Anti-Cheat game without its anti-cheat when the game supports offline play. Turn off to launch through Easy Anti-Cheat as usual. Online modes that require Easy Anti-Cheat remain unavailable. DXVK overlay for D3D9–11. fps displays frame rate; unset hides it. DXVK settings separated by semicolons. Recent builds use dxvk.maxFrameRate for frame limiting; prefer the session frame limiter for ordinary play. D3D12 frame-rate limit. 0 disables the limit. @@ -180,6 +181,8 @@ %1$s through FEX This program is built for %1$s PCs and runs through FEX, which is not set up yet. Open Steam once while signed in: DroidDeck has it download FEX and the Steam Linux Runtime it needs, then this opens. This program + Couldn\'t download the Steam client. Your network or VPN may be blocking Steam\'s servers; check the connection and try again. + Couldn\'t set up the Steam client. Check your connection and free storage, then try again. %1$s is built for x86 PCs and runs through FEX, which is not installed yet. Start Steam once while signed in and let it download FEX and the Steam Linux Runtime, then start this again. A Flathub app ID or its Flathub page. Flatpak is set up first if it is not yet. File @@ -542,7 +545,7 @@ Adreno only. Fewer hitches, more battery use and heat. Session fixes Turnip: sysmem rendering - Faster for Steam and most games. Required on Adreno 710/720/722. + Faster for the Steam client; in games the driver picks tile or system-memory rendering per pass. Required on Adreno 710/720/722. Skip Steam\'s xalia helper droiddeck-ntsync (experimental) A userspace stand-in for the Linux ntsync driver, for testing. While it is on, Proton uses it instead of droiddeck-esync and droiddeck-fsync. Works with Proton Experimental ARM64, GE-Proton and proton-cachyos. Applies next session. @@ -1069,6 +1072,9 @@ Added game Custom game Games storage + Deletes its files and removes it from Steam. + Remove %1$s? + Deletes its shortcut. The game files stay. The best pair for this GPU, kept up to date Pick a pair yourself Checking for drivers… @@ -1975,6 +1981,8 @@ Stores Stores settings Settings + Arrange tabs + Done (not signed in) Store Library @@ -2212,7 +2220,7 @@ Size Save Reset to default - Shown on the game\'s background, the way Steam draws it. The exact spot can differ by a few pixels. + This exact spot can differ by a few pixels. This game has no logo yet. Choose one under Logo to see it here. Couldn\'t save the logo position. Try again. Background @@ -2539,6 +2547,12 @@ Camera placement Check that the camera can see you before you play. Check + Hand tracking download + Hand tracking needs a one-time %1$s download. + Download + Retry + Downloading hand tracking… %1$d%% + Hand tracking couldn\'t be downloaded. Check your connection and try again. Camera placement Stand the device up 1.5 to 2 metres away at about chest height, with the back camera facing you. Then step into view with your hands out. Stand the device up 1.5 to 2 metres away at about chest height, with the screen facing you. Then step into view with your hands out. @@ -2763,12 +2777,14 @@ Boot movie Movie DroidDeck · %1$d fps - 60 fps looks smoother but uses more CPU while Steam starts. A startup movie picked in Steam\'s own settings takes priority. + 60 fps looks smoother but uses more CPU while Steam starts. A movie picked in Steam\'s own settings shows up here too. Sound Your own movie MP4, MOV, MKV or WebM. Other formats and files over %1$d MB are converted to 720p WebM on the device, up to %2$d seconds. Import Remove + Remove %1$s? + This deletes the movie from DroidDeck and from Steam\'s movies folder. Choose a boot movie %1$s is now the boot movie %1$s is now the boot movie, without sound @@ -2777,6 +2793,49 @@ Converting %1$s for Steam. Keep DroidDeck open. This device cannot decode that video. Could not import that movie + Installed + Import + SteamDeckRepo + Sound + Installed movies + Browse + DroidDeck + Imported + SteamDeckRepo + Steam + Points Shop + Boot movie report + Saves what DroidDeck and Steam know about boot movies to a text file you can attach to a bug report. + Save + Saved to %1$s + Could not save the report. + Volume + Length + %1$d s + How many seconds of the movie play. Anything longer is cut off at the end. + Search SteamDeckRepo + All devices + Steam Deck + Steam Machine + Trending + Most downloaded + Most liked + Newest + Could not reach SteamDeckRepo + Retry + No movies found + Install + Use + In use + %1$s installed + Could not download that movie + Previous + Next + Page %1$d + Clear + Go to page + Preview + This preview could not be played Steady hand aim Aim from your shoulder through your palm. Turn off for wrist-controlled rotation. Spatial setup @@ -2889,7 +2948,6 @@ Waiting for stable head tracking; recenter if requested Camera observation is too old; waiting for a fresh pair Fit %1$.2f px. Measure your selected distance from the left camera to the board center, then validate. - OpenCV unavailable: %1$s %1$d saved views restored. Calculate calibration to retry, or start a new set to capture more. Captured %1$d / 24 views. Keep the board fixed; move the glasses for the next view. Capture rejected: %1$d / 12 required corners visible in both cameras. Show more of the board, hold still, then try again. diff --git a/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt b/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt index 4fe40920d1..281a782246 100644 --- a/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt @@ -7,6 +7,7 @@ class GameEnvironmentTest { @Test fun defaultsIncludeRequestedGraphicsLevelsAndKeepCaching() { val values = GameEnvironment.defaults("") assertEquals("false", values["MESA_SHADER_CACHE_DISABLE"]) + assertEquals("1", values["DROIDDECK_ANTICHEAT_OFFLINE"]) assertEquals("12_2", values["VKD3D_FEATURE_LEVEL"]) assertEquals("6_9", values["VKD3D_SHADER_MODEL"]) } diff --git a/app/src/test/java/com/droiddeck/launcher/core/LogRedactorStreamTest.kt b/app/src/test/java/com/droiddeck/launcher/core/LogRedactorStreamTest.kt new file mode 100644 index 0000000000..38aeaca6a0 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/core/LogRedactorStreamTest.kt @@ -0,0 +1,86 @@ +package com.droiddeck.launcher.core + +import java.io.StringWriter +import java.io.Writer +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class LogRedactorStreamTest { + @get:Rule val tmp = TemporaryFolder() + + @Test fun utf16AndNulDelimitedSecretsAreWithheld() { + val token = "synthetic_private_value" + for (encoding in listOf(Charsets.UTF_16LE, Charsets.UTF_16BE, Charsets.UTF_16)) { + val src = tmp.newFile() + src.writeBytes("sessionid=$token".toByteArray(encoding)) + val out = StringWriter() + LogRedactor.scrubForShare(src, out) + assertFalse(out.toString().replace("\u0000", "").contains(token)) + assertTrue(out.toString().contains("withheld")) + } + } + + @Test fun aNulAfterTheInitialBinaryProbeWithholdsTheWholeLine() { + val src = tmp.newFile() + src.writeText(".".repeat(9000) + "\u0000sessionid=synthetic_private_value") + val out = StringWriter() + LogRedactor.scrubForShare(src, out) + assertFalse(out.toString().contains("synthetic_private_value")) + assertTrue(out.toString().contains("withheld")) + } + + @Test fun aVeryLongLineIsWithheldAndTheFollowingLineIsScrubbed() { + val src = tmp.newFile() + src.bufferedWriter().use { writer -> + writer.write("sessionid=synthetic_private_value ") + repeat(128) { writer.write(".".repeat(64 * 1024)) } + writer.write("\nready=1 token=another_private_value\n") + } + val out = StringWriter() + LogRedactor.scrubForShare(src, out) + assertTrue("oversized line was retained", out.toString().length < 1024) + assertTrue(out.toString().contains("withheld")) + assertTrue(out.toString().contains("ready=1 token=")) + assertFalse(out.toString().contains("private_value")) + } + + @Test fun malformedUtf8WithholdsWithoutReturningTheUnredactedLine() { + val src = tmp.newFile() + src.writeBytes("sessionid=synthetic_private_value ".toByteArray() + byteArrayOf(0xc3.toByte(), 0x28)) + val out = StringWriter() + LogRedactor.scrubForShare(src, out) + assertFalse(out.toString().contains("synthetic_private_value")) + assertTrue(out.toString().contains("withheld")) + } + + @Test fun normalUnicodeAndLineEndingsKeepTheirDiagnosticContent() { + val src = tmp.newFile() + src.writeText("hazır=✓ token=synthetic_private_value\r\n\rstatus=ok\nson") + val out = StringWriter() + LogRedactor.scrubForShare(src, out) + assertEquals("hazır=✓ token=\n\nstatus=ok\nson\n", out.toString()) + } + + @Test fun aLogAboveTheInMemoryLimitIsStillStreamed() { + val src = tmp.newFile() + val block = ("status=ok " + ".".repeat(4090) + "\n").repeat(16) + src.bufferedWriter().use { writer -> + while (src.length() <= LogRedactor.IN_MEMORY_SCRUB_MAX) { + writer.write(block) + writer.flush() + } + } + var chars = 0L + val out = object : Writer() { + override fun write(buffer: CharArray, offset: Int, length: Int) { chars += length } + override fun flush() {} + override fun close() {} + } + LogRedactor.scrubForShare(src, out) + assertEquals(src.length(), chars) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/files/FileOpsCopyTest.kt b/app/src/test/java/com/droiddeck/launcher/files/FileOpsCopyTest.kt new file mode 100644 index 0000000000..ac13ac7814 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/files/FileOpsCopyTest.kt @@ -0,0 +1,172 @@ +package com.droiddeck.launcher.files + +import java.io.File +import java.util.concurrent.CancellationException +import java.nio.file.Files +import java.nio.file.attribute.PosixFilePermissions +import org.junit.Assume.assumeTrue +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +@RunWith(RobolectricTestRunner::class) +class FileOpsCopyTest { + @get:Rule val tmp = TemporaryFolder() + + @Test fun cancellingAnOverwritePreservesTheDestinationAndSource() { + val src = tmp.newFile("source").apply { writeText("replacement") } + val dst = tmp.newFile("dest").apply { writeText("original user data") } + assertThrows(CancellationException::class.java) { + FileOps.copyWithProgress(src, dst, { _, _ -> throw CancellationException("cancel") }) + } + assertTrue("original destination was removed", dst.exists()) + assertEquals("original user data", dst.readText()) + assertEquals("replacement", src.readText()) + assertEquals(setOf("source", "dest"), tmp.root.list()!!.toSet()) + } + + @Test fun cancellingANewCopyLeavesNoPartialDestination() { + val src = tmp.newFile("source").apply { writeText("replacement") } + val dst = File(tmp.root, "dest") + assertThrows(CancellationException::class.java) { + FileOps.copyWithProgress(src, dst, { _, _ -> throw CancellationException("cancel") }) + } + assertFalse(dst.exists()) + assertEquals("replacement", src.readText()) + assertEquals(setOf("source"), tmp.root.list()!!.toSet()) + } + + @Test fun cancellingAMoveFallbackPreservesBothFiles() { + val src = tmp.newFile("source").apply { writeText("replacement") } + val dst = tmp.newFile("dest").apply { writeText("original user data") } + assertThrows(CancellationException::class.java) { + FileOps.moveWithProgress(src, dst, { _, _ -> throw CancellationException("cancel") }) + } + assertTrue("original destination was removed", dst.exists()) + assertEquals("original user data", dst.readText()) + assertEquals("replacement", src.readText()) + } + + @Test fun cancellingStopsATreeOfEmptyFiles() { + val src = tmp.newFolder("source") + for (name in listOf("a", "b", "c")) File(src, name).createNewFile() + val dst = File(tmp.root, "dest") + var checks = 0 + assertThrows(CancellationException::class.java) { + FileOps.copyWithProgress(src, dst, null) { checks++ > 1 } + } + assertEquals(1, dst.list()!!.size) + assertEquals(3, src.list()!!.size) + } + + @Test fun cancellingStopsATreeOfEmptyFolders() { + val src = tmp.newFolder("source") + for (name in listOf("a", "b", "c")) File(src, name).mkdir() + val dst = File(tmp.root, "dest") + var checks = 0 + assertThrows(CancellationException::class.java) { + FileOps.copyWithProgress(src, dst, null) { checks++ > 1 } + } + assertEquals(1, dst.list()!!.size) + } + + @Test fun aCompletedCopyReplacesTheDestination() { + val src = tmp.newFile("source").apply { writeText("replacement") } + val dst = tmp.newFile("dest").apply { writeText("original user data") } + assertTrue(FileOps.copyWithProgress(src, dst, null)) + assertEquals("replacement", dst.readText()) + assertEquals("replacement", src.readText()) + assertEquals(setOf("source", "dest"), tmp.root.list()!!.toSet()) + } + + @Test fun aLongDestinationNameDoesNotOverflowTheStagingName() { + val src = tmp.newFile("source").apply { writeText("replacement") } + val dst = File(tmp.root, "d".repeat(240)) + assertTrue(FileOps.copyWithProgress(src, dst, null)) + assertEquals("replacement", dst.readText()) + } + + @Test fun anOverwritePreservesTheTargetsExecutablePermissions() { + assumeTrue(Files.getFileStore(tmp.root.toPath()).supportsFileAttributeView("posix")) + val src = tmp.newFile("source").apply { writeText("replacement") } + val dst = tmp.newFile("dest").apply { writeText("original") } + val permissions = PosixFilePermissions.fromString("rwxr-x---") + Files.setPosixFilePermissions(dst.toPath(), permissions) + assertTrue(FileOps.copyWithProgress(src, dst, null)) + assertEquals("replacement", dst.readText()) + assertEquals(permissions, Files.getPosixFilePermissions(dst.toPath())) + } + + @Test fun aMoveFallbackPreservesTheTargetsExecutablePermissions() { + assumeTrue(Files.getFileStore(tmp.root.toPath()).supportsFileAttributeView("posix")) + val src = tmp.newFile("source").apply { writeText("replacement") } + val dst = tmp.newFile("dest").apply { writeText("original") } + val permissions = PosixFilePermissions.fromString("rwxr-x---") + Files.setPosixFilePermissions(dst.toPath(), permissions) + assertTrue(FileOps.moveWithProgress(src, dst, null)) + assertFalse(src.exists()) + assertEquals("replacement", dst.readText()) + assertEquals(permissions, Files.getPosixFilePermissions(dst.toPath())) + } + + @Test fun anOverwriteStillRefusesAReadOnlyDestination() { + assumeTrue(Files.getFileStore(tmp.root.toPath()).supportsFileAttributeView("posix")) + val src = tmp.newFile("source").apply { writeText("replacement") } + val dst = tmp.newFile("dest").apply { writeText("original") } + Files.setPosixFilePermissions(dst.toPath(), PosixFilePermissions.fromString("r--r--r--")) + try { + assertFalse(FileOps.copyWithProgress(src, dst, null)) + assertEquals("original", dst.readText()) + assertEquals("replacement", src.readText()) + } finally { + dst.setWritable(true) + } + } + + @Test fun anEmptyFileCanReplaceAnExistingFile() { + val src = tmp.newFile("source") + val dst = tmp.newFile("dest").apply { writeText("original user data") } + var callbacks = 0 + assertTrue(FileOps.copyWithProgress(src, dst, { _, _ -> callbacks++ })) + assertEquals(0, callbacks) + assertEquals(0L, dst.length()) + assertTrue(src.exists()) + } + + @Test fun aFailedPublicationPreservesTheDestinationAndCleansStaging() { + val src = tmp.newFile("source").apply { writeText("replacement") } + val dst = tmp.newFolder("dest") + File(dst, "keep").writeText("original user data") + assertFalse(FileOps.copyWithProgress(src, dst, null)) + assertEquals("original user data", File(dst, "keep").readText()) + assertEquals("replacement", src.readText()) + assertEquals(setOf("source", "dest"), tmp.root.list()!!.toSet()) + } + + @Test fun aSuccessfulMoveFallbackDeletesTheSourceOnlyAfterCopying() { + val src = tmp.newFile("source").apply { writeText("replacement") } + val dst = tmp.newFile("dest").apply { writeText("original user data") } + assertTrue(FileOps.moveWithProgress(src, dst, null)) + assertFalse(src.exists()) + assertEquals("replacement", dst.readText()) + assertEquals(setOf("dest"), tmp.root.list()!!.toSet()) + } + + @Test fun overwritingThroughASymlinkKeepsTheLinkAndUpdatesItsTarget() { + assumeTrue(Files.getFileStore(tmp.root.toPath()).supportsFileAttributeView("posix")) + val src = tmp.newFile("source").apply { writeText("replacement") } + val realTarget = tmp.newFile("real-target").apply { writeText("original user data") } + val link = File(tmp.root, "dest-link") + Files.createSymbolicLink(link.toPath(), realTarget.toPath()) + + assertTrue(FileOps.copyWithProgress(src, link, null)) + assertTrue("destination symlink was replaced instead of written through", Files.isSymbolicLink(link.toPath())) + assertEquals("replacement", realTarget.readText()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/files/FileOpsLinksTest.kt b/app/src/test/java/com/droiddeck/launcher/files/FileOpsLinksTest.kt new file mode 100644 index 0000000000..03ad97a190 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/files/FileOpsLinksTest.kt @@ -0,0 +1,85 @@ +package com.droiddeck.launcher.files + +import java.io.File +import java.nio.file.Files +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Assume.assumeTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner + +@RunWith(RobolectricTestRunner::class) +class FileOpsLinksTest { + @get:Rule val tmp = TemporaryFolder() + + private fun link(at: File, target: String): Boolean = + runCatching { Files.createSymbolicLink(at.toPath(), File(target).toPath()) }.isSuccess + + @Test fun aMovedFolderKeepsItsLinks() { + val src = tmp.newFolder("game") + File(src, "data.bin").writeText("x") + assumeTrue("symlinks unavailable here", link(File(src, "lib.so"), "data.bin")) + val dst = File(tmp.root, "other/game") + File(dst, "keep").mkdirs() + assertTrue(FileOps.moveWithProgress(src, dst, null)) + assertFalse(src.exists()) + assertTrue(Files.isSymbolicLink(File(dst, "lib.so").toPath())) + assertEquals("data.bin", Files.readSymbolicLink(File(dst, "lib.so").toPath()).toString()) + } + + @Test fun aCopiedLinkPointsWhereTheOriginalDoes() { + val src = tmp.newFolder("a") + assumeTrue("symlinks unavailable here", link(File(src, "l"), "/nowhere/target")) + val dst = File(tmp.root, "b") + assertTrue(FileOps.copyWithProgress(src, dst, null)) + assertTrue(Files.isSymbolicLink(File(src, "l").toPath())) + assertTrue(Files.isSymbolicLink(File(dst, "l").toPath())) + } + + @Test fun copyingALinkPreservesAnUnrelatedStagingName() { + val src = File(tmp.root, "source") + assumeTrue("symlinks unavailable here", link(src, "missing-target")) + val dst = File(tmp.root, "dest") + dst.writeText("old destination") + val sibling = File(tmp.root, ".dest.link-tmp") + sibling.writeText("unrelated user data") + + assertTrue(FileOps.copyWithProgress(src, dst, null)) + assertEquals("unrelated user data", sibling.readText()) + assertEquals("missing-target", Files.readSymbolicLink(dst.toPath()).toString()) + assertEquals(setOf("source", "dest", ".dest.link-tmp"), tmp.root.list()!!.toSet()) + } + + @Test fun anUnrelatedStagingDirectoryDoesNotPreventCopyingALink() { + val src = File(tmp.root, "source") + assumeTrue("symlinks unavailable here", link(src, "missing-target")) + val sibling = tmp.newFolder(".dest.link-tmp") + File(sibling, "keep").writeText("unrelated user data") + + assertTrue(FileOps.copyWithProgress(src, File(tmp.root, "dest"), null)) + assertEquals("unrelated user data", File(sibling, "keep").readText()) + } + + @Test fun aLongDestinationNameDoesNotOverflowTheStagingName() { + val src = File(tmp.root, "source") + assumeTrue("symlinks unavailable here", link(src, "missing-target")) + val dst = File(tmp.root, "d".repeat(240)) + assertTrue(FileOps.copyWithProgress(src, dst, null)) + assertEquals("missing-target", Files.readSymbolicLink(dst.toPath()).toString()) + } + + @Test fun aLinkThatCannotReplaceTheDestinationLeavesItAlone() { + val src = tmp.newFolder("c") + assumeTrue("symlinks unavailable here", link(File(src, "l"), "x")) + val dst = File(tmp.root, "d") + File(dst, "l").mkdirs() + File(dst, "l/keep.txt").writeText("kept") + assertFalse(FileOps.copyWithProgress(File(src, "l"), File(dst, "l"), null)) + assertEquals("kept", File(dst, "l/keep.txt").readText()) + assertFalse(File(dst, ".l.link-tmp").exists()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesSkipExeTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesSkipExeTest.kt new file mode 100644 index 0000000000..720b0a6b58 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/frontend/AddedGamesSkipExeTest.kt @@ -0,0 +1,19 @@ +package com.droiddeck.launcher.frontend + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class AddedGamesSkipExeTest { + @Test fun gameTitlesContainingShortSkipWordsAreKept() { + listOf("BeachBuggyRacing.exe", "Reach.exe", "Breach.exe", "Crashday.exe", "CrashBandicoot.exe", + "Observer.exe", "Observer-Win64-Shipping.exe", "Game.exe").forEach { assertFalse(it, AddedGames.skipExe(it)) } + } + + @Test fun installersToolsAndServersAreSkipped() { + listOf("unins000.exe", "setup.exe", "vc_redist.x64.exe", "DXSETUP.exe", "CrashReportClient.exe", + "UnityCrashHandler64.exe", "gamelaunchhelper.exe", "EACLauncher.exe", "DedicatedServer.exe", + "UE4Editor.exe", "valheim_server.exe", "GameConfig.exe", "GameConfigure.exe", "Settings.exe", "Updater.exe", + "EasyAntiCheat_Setup.exe").forEach { assertTrue(it, AddedGames.skipExe(it)) } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/GameFilesTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/GameFilesTest.kt index d37689e295..bcae5c8fec 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/GameFilesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/GameFilesTest.kt @@ -132,6 +132,23 @@ class GameFilesTest { } } + @Test fun longTitlesKeepTheirEndingAndStayApart() { + val folder = tmp.newFolder() + val first = game("32370", "STAR WARS™ Knights of the Old Republic™") + val second = game("208580", "STAR WARS™ Knights of the Old Republic™ II - The Sith Lords™") + assertEquals("STAR WARS™ Knights of the Old Republic™ II - The Sith Lords™.steam", GameFiles.filename(second)) + GameFiles.sync(app, folder, listOf(first, second)) + GameFiles.sync(app, folder, listOf(first, second)) + assertEquals("32370", File(folder, "STAR WARS™ Knights of the Old Republic™.steam").readText()) + assertEquals("208580", File(folder, "STAR WARS™ Knights of the Old Republic™ II - The Sith Lords™.steam").readText()) + assertEquals(2, folder.listFiles()!!.count { it.extension == GameFiles.EXTENSION }) + assertEquals("a".repeat(200) + ".steam", GameFiles.filename(game(name = "a".repeat(300)))) + assertEquals("a".repeat(199) + ".steam", GameFiles.filename(game(name = "a".repeat(199) + " b"))) + assertEquals("Game.steam", GameFiles.filename(game(name = " . "))) + assertEquals("Game.steam", GameFiles.filename(game(name = "Game . ."))) + assertEquals("a".repeat(197) + ".steam", GameFiles.filename(game(name = "a".repeat(197) + " . b"))) + } + @Test fun refusesSymlinksLeavingTheExportFolder() { val folder = tmp.newFolder() val outside = tmp.newFile() diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/GameIdentifierTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/GameIdentifierTest.kt index f7ddc02125..d67170d1e7 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/GameIdentifierTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/GameIdentifierTest.kt @@ -179,7 +179,7 @@ class GameIdentifierTest { @Test fun isJunkPeName_flagsLaunchersNotGames() { - for (junk in listOf("Rockstar Games Launcher Redirector", "GSE", "Steam", "Launcher", "Epic Games Launcher")) { + for (junk in listOf("Rockstar Games Launcher Redirector", "GSE", "Steam", "Launcher", "Epic Games Launcher", "BootstrapPackagedGame")) { assertTrue("expected junk: $junk", GameIdentifier.isJunkPeName(junk)) } for (real in listOf("God of War", "Grand Theft Auto V", "DARK SOULS: REMASTERED", "Hades")) { diff --git a/app/src/test/java/com/droiddeck/launcher/handtracking/HandTrackingTest.kt b/app/src/test/java/com/droiddeck/launcher/handtracking/HandTrackingTest.kt index 3456857d7a..614269942a 100644 --- a/app/src/test/java/com/droiddeck/launcher/handtracking/HandTrackingTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/handtracking/HandTrackingTest.kt @@ -45,11 +45,12 @@ class HandTrackingTest { assertEquals(TrackingCameras.REAR, s.side) } - @Test fun trackingNeedsThePermissionAndACamera() { + @Test fun trackingNeedsThePermissionACameraAndTheTrackingPack() { val context = RuntimeEnvironment.getApplication() - assertFalse(both.copy(enabled = true).ready) - assertTrue(both.copy(enabled = true, permitted = true).ready) - assertFalse(HandTracking.Settings(enabled = true, permitted = true).ready) + assertFalse(both.copy(enabled = true, downloaded = true).ready) + assertFalse(both.copy(enabled = true, permitted = true).ready) + assertTrue(both.copy(enabled = true, permitted = true, downloaded = true).ready) + assertFalse(HandTracking.Settings(enabled = true, permitted = true, downloaded = true).ready) shadowOf(context).grantPermissions(Manifest.permission.CAMERA) HandTracking.refreshPermission(context) assertTrue(HandTracking.settings.value.permitted) diff --git a/app/src/test/java/com/droiddeck/launcher/input/PadBridgeRoutingTest.kt b/app/src/test/java/com/droiddeck/launcher/input/PadBridgeRoutingTest.kt index 8ff62e170e..1d2e1a10e8 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/PadBridgeRoutingTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/PadBridgeRoutingTest.kt @@ -71,6 +71,17 @@ class PadBridgeRoutingTest { InputDevice.KEYBOARD_TYPE_NONE, id = -1) assertTrue(virtual.isVirtual) assertFalse(PadBridge.isFromController(virtual)) + for (uinputName in listOf("uinput-xiaomi", "uinput-fpc", "uinput_nav")) { + val phantom = device( + InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_JOYSTICK, + InputDevice.KEYBOARD_TYPE_NONE, + name = uinputName, + ) + assertFalse(phantom.isVirtual) + assertFalse(PadBridge.isFromController(phantom)) + assertFalse(PadBridge.isControllerKeyEvent(key(phantom, KeyEvent.KEYCODE_BUTTON_A, KeyEvent.ACTION_DOWN))) + } + assertFalse(PadBridge.anyControllerConnected()) } @Test fun keyAndMotionOwnershipDoesNotFollowEverySourceOnTheDevice() { @@ -122,6 +133,21 @@ class PadBridgeRoutingTest { } } + @Test fun onlyAxesTheDeviceReportsReplaceKeyDrivenTriggersAndDpad() { + val js = InputDevice.SOURCE_JOYSTICK + val sticksOnly = device(js or InputDevice.SOURCE_GAMEPAD, InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC, rangeSource = js, axis = MotionEvent.AXIS_X) + val withTrigger = device(js or InputDevice.SOURCE_GAMEPAD, InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC, rangeSource = js, axis = MotionEvent.AXIS_LTRIGGER) + val withHat = device(js or InputDevice.SOURCE_GAMEPAD, InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC, rangeSource = js, axis = MotionEvent.AXIS_HAT_Y) + val triggers = intArrayOf(MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_BRAKE, MotionEvent.AXIS_GAS) + val hat = intArrayOf(MotionEvent.AXIS_HAT_X, MotionEvent.AXIS_HAT_Y) + assertFalse(PadBridge.hasAxis(sticksOnly, js, *triggers)) + assertFalse(PadBridge.hasAxis(sticksOnly, js, *hat)) + assertTrue(PadBridge.hasAxis(withTrigger, js, *triggers)) + assertFalse(PadBridge.hasAxis(withTrigger, js, *hat)) + assertTrue(PadBridge.hasAxis(withHat, js, *hat)) + assertFalse(PadBridge.hasAxis(null, js, *hat)) + } + private fun key(device: InputDevice, code: Int, action: Int, source: Int = InputDevice.SOURCE_KEYBOARD): KeyEvent { val event = KeyEvent(0L, 0L, action, code, 0, 0, device.id, 0, 0, source) assertSame(device, event.device) @@ -131,8 +157,8 @@ class PadBridgeRoutingTest { private var nextId = 10 private fun device(sources: Int, type: Int, keys: IntArray = intArrayOf(KeyEvent.KEYCODE_A, KeyEvent.KEYCODE_DPAD_UP), - rangeSource: Int? = null, axis: Int = MotionEvent.AXIS_X, id: Int = nextId++): InputDevice { - val builder = InputDeviceBuilder.newBuilder().setId(id).setName("routing fixture $id") + rangeSource: Int? = null, axis: Int = MotionEvent.AXIS_X, id: Int = nextId++, name: String = "routing fixture $id"): InputDevice { + val builder = InputDeviceBuilder.newBuilder().setId(id).setName(name) .setDescriptor("routing-$id").setExternal(true).setSources(sources).setKeyboardType(type) .setKeyCharacterMap(KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD)) if (rangeSource != null) builder.addMotionRange(axis, rangeSource, -1f, 1f, 0f, 0f, 0f) diff --git a/app/src/test/java/com/droiddeck/launcher/input/PadPartialAxesTest.kt b/app/src/test/java/com/droiddeck/launcher/input/PadPartialAxesTest.kt new file mode 100644 index 0000000000..a0c5bc986b --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/PadPartialAxesTest.kt @@ -0,0 +1,128 @@ +package com.droiddeck.launcher.input + +import android.hardware.input.InputManager +import android.view.InputDevice +import android.view.KeyEvent +import android.view.MotionEvent +import java.nio.file.Files +import org.junit.After +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.shadows.InputDeviceBuilder + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], manifest = Config.NONE, instrumentedPackages = ["com.droiddeck.launcher.input.FakeInputWriter"], + shadows = [PadBridgeRoutingTest.RegisteredKeyEvent::class, PadBridgeRoutingTest.RegisteredMotionEvent::class, + JoyConPadTest.RecordingWriter::class]) +class PadPartialAxesTest { + private val directory = Files.createTempDirectory("partial-pad").toFile() + private lateinit var bridge: PadBridge + + @Before fun start() { + JoyConPadTest.RecordingWriter.pads.clear() + bridge = PadBridge(directory) + assertTrue(bridge.start()) + } + + @After fun stop() { + bridge.stop() + directory.deleteRecursively() + } + + @Test fun leftTriggerAxisPreservesRightTriggerKey() = trigger(MotionEvent.AXIS_LTRIGGER, false) + @Test fun brakeAxisPreservesRightTriggerKey() = trigger(MotionEvent.AXIS_BRAKE, false) + @Test fun rightTriggerAxisPreservesLeftTriggerKey() = trigger(MotionEvent.AXIS_RTRIGGER, true) + @Test fun gasAxisPreservesLeftTriggerKey() = trigger(MotionEvent.AXIS_GAS, true) + + private fun trigger(axis: Int, leftKey: Boolean) { + val device = device(axis) + key(device, if (leftKey) KeyEvent.KEYCODE_BUTTON_L2 else KeyEvent.KEYCODE_BUTTON_R2) + motion(device, axis to 0.75f) + assertEquals(1f, if (leftKey) pad().leftTrigger else pad().rightTrigger) + assertEquals(0.75f, if (leftKey) pad().rightTrigger else pad().leftTrigger) + motion(device, axis to 0f) + assertEquals(1f, if (leftKey) pad().leftTrigger else pad().rightTrigger) + assertEquals(0f, if (leftKey) pad().rightTrigger else pad().leftTrigger) + } + + @Test fun horizontalHatPreservesVerticalKeys() { + val device = device(MotionEvent.AXIS_HAT_X) + key(device, KeyEvent.KEYCODE_DPAD_UP) + motion(device, MotionEvent.AXIS_HAT_X to 1f) + assertTrue(pad().up) + assertTrue(pad().right) + motion(device, MotionEvent.AXIS_HAT_X to 0f) + assertTrue(pad().up) + assertFalse(pad().right) + } + + @Test fun verticalHatPreservesHorizontalKeys() { + val device = device(MotionEvent.AXIS_HAT_Y) + key(device, KeyEvent.KEYCODE_DPAD_LEFT) + motion(device, MotionEvent.AXIS_HAT_Y to -1f) + assertTrue(pad().left) + assertTrue(pad().up) + motion(device, MotionEvent.AXIS_HAT_Y to 0f) + assertTrue(pad().left) + assertFalse(pad().up) + } + + @Test fun wiredXboxTriggersStillUseTheirSignedZAxes() { + val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ, wired = true) + motion(device, MotionEvent.AXIS_Z to -1f, MotionEvent.AXIS_RZ to 1f, + MotionEvent.AXIS_RX to 0.6f, MotionEvent.AXIS_RY to -0.6f) + assertEquals(0f, pad().leftTrigger) + assertEquals(1f, pad().rightTrigger) + assertEquals(0.6f, pad().rightX) + assertEquals(-0.6f, pad().rightY) + } + + @Test fun sticksWithoutTriggerOrHatAxesPreserveAllDigitalControls() { + val device = device() + key(device, KeyEvent.KEYCODE_BUTTON_L2) + key(device, KeyEvent.KEYCODE_BUTTON_R2) + key(device, KeyEvent.KEYCODE_DPAD_DOWN) + motion(device) + assertEquals(1f, pad().leftTrigger) + assertEquals(1f, pad().rightTrigger) + assertTrue(pad().down) + } + + private fun pad(): PadState = requireNotNull(JoyConPadTest.RecordingWriter.pads[0]) + + private fun key(device: InputDevice, code: Int) { + assertTrue(bridge.onKeyEvent(KeyEvent(0L, 0L, KeyEvent.ACTION_DOWN, code, 0, 0, + device.id, 0, 0, InputDevice.SOURCE_GAMEPAD))) + } + + private fun motion(device: InputDevice, vararg values: Pair) { + val coords = MotionEvent.PointerCoords().apply { + setAxisValue(MotionEvent.AXIS_X, 0.5f) + for ((axis, value) in values) setAxisValue(axis, value) + } + val event = MotionEvent.obtain(0L, 0L, MotionEvent.ACTION_MOVE, 1, + arrayOf(MotionEvent.PointerProperties().apply { id = 0 }), arrayOf(coords), + 0, 0, 1f, 1f, device.id, 0, InputDevice.SOURCE_JOYSTICK, 0) + try { assertTrue(bridge.onMotionEvent(event)) } finally { event.recycle() } + } + + private fun device(vararg axes: Int, wired: Boolean = false): InputDevice { + val builder = InputDeviceBuilder.newBuilder().setId(60).setName("partial pad") + .setDescriptor("partial-pad").setExternal(true) + .setSources(InputDevice.SOURCE_GAMEPAD or InputDevice.SOURCE_JOYSTICK) + .setKeyboardType(InputDevice.KEYBOARD_TYPE_NON_ALPHABETIC) + .setVendorId(if (wired) 0x20d6 else 0).setProductId(if (wired) 0x2063 else 0) + for (axis in axes.toList() + MotionEvent.AXIS_X) { + builder.addMotionRange(axis, InputDevice.SOURCE_JOYSTICK, -1f, 1f, 0f, 0f, 0f) + } + return builder.build().also { + shadowOf(RuntimeEnvironment.getApplication().getSystemService(InputManager::class.java)).addInputDevice(it) + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/SessionKeyboardPadTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SessionKeyboardPadTest.kt new file mode 100644 index 0000000000..7ba52e1683 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/SessionKeyboardPadTest.kt @@ -0,0 +1,118 @@ +package com.droiddeck.launcher.input + +import android.os.Looper +import android.view.View +import androidx.compose.runtime.MutableState +import com.droiddeck.launcher.SessionActivity +import com.droiddeck.launcher.agent.AgentGuest +import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.session.SessionService +import com.droiddeck.launcher.session.SessionState +import java.nio.file.Files +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.Robolectric +import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf +import org.robolectric.annotation.Config +import org.robolectric.util.ReflectionHelpers + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class SessionKeyboardPadTest { + private lateinit var activity: SessionActivity + private lateinit var controls: OnScreenControls + private val directory = Files.createTempDirectory("keyboard-pad").toFile() + + @Before fun setUp() { + activity = Robolectric.buildActivity(SessionActivity::class.java).get() + activity.getSharedPreferences("session", 0).edit().clear().commit() + SessionState.mode = SessionService.MODE_STEAM + controls = OnScreenControls(activity, null).apply { visibility = View.GONE } + ReflectionHelpers.setField(activity, "onScreenControls", controls) + } + + @After fun tearDown() { + steamKeyboard(false) + SteamTouchDevice.release() + directory.deleteRecursively() + SessionState.mode = SessionService.MODE_STEAM + } + + @Test fun padStepsAsideWhileEitherKeyboardIsUpInSteam() { + SessionPrefs.setOscMode(activity, SessionPrefs.OSC_ALWAYS) + update() + assertEquals(View.VISIBLE, controls.visibility) + steamKeyboard(true) + update() + assertEquals(View.GONE, controls.visibility) + steamKeyboard(false) + update() + assertEquals(View.VISIBLE, controls.visibility) + pcKeyboard(true) + update() + assertEquals(View.GONE, controls.visibility) + pcKeyboard(false) + update() + assertEquals(View.VISIBLE, controls.visibility) + } + + @Test fun steamsKeyboardLeavesThePadAloneOutsideSteam() { + SessionState.mode = SessionService.MODE_DESKTOP + SessionPrefs.setOscMode(activity, SessionPrefs.OSC_ALWAYS) + steamKeyboard(true) + update() + assertEquals(View.VISIBLE, controls.visibility) + pcKeyboard(true) + update() + assertEquals(View.GONE, controls.visibility) + } + + @Test fun steamTouchControllerHidesAndHandsTouchBackWhileSteamsKeyboardIsUp() { + SteamTouchDevice.prepare(directory) + val steam = SteamTouchControls(activity, SteamTouchDevice.current!!, {}, {}) + ReflectionHelpers.setField(activity, "steamTouchControls", steam) + ReflectionHelpers.setField(activity, "steamTouchOptions", + SteamTouchConfig.Options(inputMode = SteamTouchConfig.INPUT_CONTROLLER)) + SessionPrefs.setTouchMode(activity, SessionPrefs.TOUCH_DIRECT) + SessionPrefs.setOscMode(activity, SessionPrefs.OSC_STEAM_TOUCH) + update() + assertEquals(View.VISIBLE, steam.visibility) + assertEquals(SessionPrefs.TOUCH_OFF, routedTouchMode()) + steamKeyboard(true) + update() + assertEquals(View.GONE, steam.visibility) + assertTrue(SteamTouchDevice.current!!.plugged) + assertEquals(SessionPrefs.TOUCH_DIRECT, routedTouchMode()) + steamKeyboard(false) + update() + assertEquals(View.VISIBLE, steam.visibility) + assertEquals(SessionPrefs.TOUCH_OFF, routedTouchMode()) + } + + @Test fun endingTheAgentForgetsSteamsKeyboard() { + steamKeyboard(true) + AgentGuest.stop() + shadowOf(Looper.getMainLooper()).idle() + assertFalse(AgentGuest.steamKeyboard) + } + + private fun update() = ReflectionHelpers.callInstanceMethod(activity, "updateOnScreenControls") + + private fun routedTouchMode() = ReflectionHelpers.getField(activity, "routedTouchMode") + + private fun pcKeyboard(open: Boolean) { + ReflectionHelpers.getField>(activity, "pcKeyboardOpen\$delegate").value = open + } + + @Suppress("UNCHECKED_CAST") + private fun steamKeyboard(showing: Boolean) { + val field = AgentGuest::class.java.getDeclaredField("steamKeyboard\$delegate").apply { isAccessible = true } + (field.get(AgentGuest) as MutableState).value = showing + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/SteamTouchBindingsTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SteamTouchBindingsTest.kt index 0ad76cb700..5ce1de6328 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/SteamTouchBindingsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/SteamTouchBindingsTest.kt @@ -115,4 +115,20 @@ class SteamTouchBindingsTest { assertEquals("Jump", SteamTouchBindings.bindingAt(reparsed, ref)!!.label) assertNull(SteamTouchBindings.rewrite(config, SteamTouchBindings.Ref("5", "button_a")) { it }) } + + @Test + fun labelsDropQuotesBackslashesCommasAndControls() { + assertEquals("a b c d e", SteamTouchBindings.cleanLabel("a\"b\\c,d\n e")) + assertEquals(32, SteamTouchBindings.cleanLabel("x".repeat(40)).length) + val b = SteamTouchBindings.Binding("key_press SPACE", "Ju\"mp", "", "", "") + assertEquals("Ju mp", SteamTouchBindings.parse(b.compose()).label) + val comma = SteamTouchBindings.Binding("key_press SPACE", "Jump,Run", "icon", "#FFFFFF", "") + assertEquals(SteamTouchBindings.Binding("key_press SPACE", "Jump Run", "icon", "#FFFFFF", ""), SteamTouchBindings.parse(comma.compose())) + } + + @Test + fun labelsAreCutAtACharacterBoundary() { + val label = SteamTouchBindings.cleanLabel("a".repeat(31) + "🎮" + "b") + assertEquals("a".repeat(31) + "🎮", label) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/BootMovieLibraryTest.kt b/app/src/test/java/com/droiddeck/launcher/session/BootMovieLibraryTest.kt new file mode 100644 index 0000000000..ca68f58678 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/BootMovieLibraryTest.kt @@ -0,0 +1,310 @@ +package com.droiddeck.launcher.session + +import android.content.Context +import org.junit.Assert.* +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config +import java.io.File + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class BootMovieLibraryTest { + private val app get() = RuntimeEnvironment.getApplication() + private val movies get() = BootMovieLibrary.moviesDir(app) + + @Before fun clear() { + app.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() + File(app.filesDir, "boot-movie").deleteRecursively() + movies.deleteRecursively() + BootMovieLibrary.libraryDir(app).deleteRecursively() + File(BootMovieLibrary.steamRoot(app), "steamui").deleteRecursively() + File(BootMovieLibrary.steamRoot(app), "appcache").deleteRecursively() + BootMovieLibrary.forgetScan() + BootMovieLibrary.steamConfig(app).delete() + } + + private fun movie(name: String) = File(movies, name).also { it.parentFile!!.mkdirs(); it.writeText("movie") } + + /** A movie DroidDeck itself imported: kept in the library, copied into Steam's folder and noted in the list. */ + private fun imported(title: String, source: String = BootMovieLibrary.SOURCE_IMPORT, repo: String? = null): String { + val staged = File(BootMovieLibrary.libraryDir(app), ".t-${System.nanoTime()}-${Thread.currentThread().id}.staged").also { it.parentFile!!.mkdirs(); it.writeText("movie") } + return BootMovieLibrary.commit(app, staged, title, source, repo)!! + } + + private fun steamPicksAt(path: String) { + BootMovieLibrary.steamConfig(app).also { it.parentFile!!.mkdirs() }.writeText( + "\"InstallConfigStore\"\n{\n\t\"StartupMovie\"\n\t{\n\t\t\"MovieID\"\t\t\"x\"\n\t\t\"LocalPath\"\t\t\"$path\"\n\t}\n}\n", + ) + } + + private fun steamPicks(name: String) = steamPicksAt("/uioverrides/movies/$name") + + @Test fun theActiveX64ClientsOwnMoviesAreListedAndRemovedToo() { + SessionPrefs.setSteamClientArch(app, "x86_64") + val x64 = File(SessionPrefs.steamRoot(app, "x86_64"), "config/uioverrides/movies") + try { + File(x64, "Mine.webm").also { it.parentFile!!.mkdirs(); it.writeText("movie") } + movie("Main.webm") + val entries = BootMovieLibrary.list(app).filter { it.id.startsWith(BootMovieLibrary.PREFIX) } + assertEquals(listOf("file:Main.webm", "file:Mine.webm"), entries.map { it.id }) + assertTrue(entries.all { it.removable }) + assertEquals("Mine.webm", BootMovieLibrary.file(app, "file:Mine.webm")?.name) + assertEquals("Mine (2).webm", BootMovieLibrary.freeName(app, "Mine")) + assertTrue(BootMovieLibrary.remove(app, "file:Mine.webm")) + assertFalse(File(x64, "Mine.webm").exists()) + } finally { + x64.deleteRecursively() + } + } + + @Test fun removingAMovieKeepsTheSameNamedOneInTheOtherSteamFolder() { + SessionPrefs.setSteamClientArch(app, "x86_64") + val x64 = File(SessionPrefs.steamRoot(app, "x86_64"), "config/uioverrides/movies") + try { + File(x64, "Intro.webm").also { it.parentFile!!.mkdirs(); it.writeText("movie") } + movie("Intro.webm") + assertTrue(BootMovieLibrary.remove(app, "file:Intro.webm")) + assertFalse(File(movies, "Intro.webm").exists()) + assertTrue(File(x64, "Intro.webm").isFile) + assertTrue(BootMovieLibrary.list(app).any { it.id == "file:Intro.webm" }) + assertTrue(BootMovieLibrary.remove(app, "file:Intro.webm")) + assertFalse(File(x64, "Intro.webm").exists()) + } finally { + x64.deleteRecursively() + } + } + + @Test fun aSavedChoiceKeepsMeaningTheSameFileWhicheverClientRuns() { + val x64 = File(SessionPrefs.steamRoot(app, "x86_64"), "config/uioverrides/movies") + try { + File(x64, "Intro.webm").also { it.parentFile!!.mkdirs(); it.writeText("other") } + val main = movie("Intro.webm") + SessionPrefs.setSteamClientArch(app, "x86_64") + assertEquals(main.path, BootMovieLibrary.file(app, "file:Intro.webm")?.path) + SessionPrefs.setSteamClientArch(app, "arm64") + assertEquals(main.path, BootMovieLibrary.file(app, "file:Intro.webm")?.path) + } finally { + x64.deleteRecursively() + } + } + + @Test fun listsTheDroidDeckMoviesAndEveryWebmButNotTheStagedCopies() { + movie("Intro.webm") + movie("bigpicture_startup.webm") + movie("steam_os_startup.webm") + movie("notes.txt") + movie(".hidden.webm") + val ids = BootMovieLibrary.list(app).map { it.id } + assertEquals(listOf(BootMovie.DROIDDECK_30, BootMovie.DROIDDECK_60, "file:Intro.webm"), ids) + } + + @Test fun usesTheTitleItWasRegisteredWithAndFallsBackToTheFileName() { + imported("Fancy", BootMovieLibrary.SOURCE_REPO, "id1"); movie("b.webm") + val list = BootMovieLibrary.list(app).associateBy { it.id } + assertEquals("Fancy", list["file:Fancy.webm"]!!.title) + assertEquals(BootMovieLibrary.SOURCE_REPO, list["file:Fancy.webm"]!!.source) + assertTrue(list["file:Fancy.webm"]!!.removable) + assertTrue(list["file:b.webm"]!!.removable) + assertEquals("b", list["file:b.webm"]!!.title) + assertEquals(BootMovieLibrary.SOURCE_IMPORT, list["file:b.webm"]!!.source) + assertEquals(setOf("id1"), BootMovieLibrary.installedRepoIds(app)) + assertEquals("Fancy.webm", BootMovieLibrary.nameForRepo(app, "id1")) + } + + @Test fun aChosenFileMovieIsKeptAndFallsBackOnceItIsGone() { + val name = imported("Mine") + BootMovie.select(app, "file:$name") + assertEquals("file:$name", BootMovie.choice(app)) + assertTrue(BootMovieLibrary.remove(app, "file:$name")) + assertEquals(BootMovie.DROIDDECK_30, BootMovie.choice(app)) + assertFalse(File(movies, name).exists()) + assertFalse(File(BootMovieLibrary.libraryDir(app), name).exists()) + } + + @Test fun aMovieInSteamsCustomFolderCanBeRemovedEvenWithoutANote() { + movie("by-hand.webm") + assertTrue(BootMovieLibrary.list(app).first { it.id == "file:by-hand.webm" }.removable) + assertTrue(BootMovieLibrary.remove(app, "file:by-hand.webm")) + assertFalse(File(movies, "by-hand.webm").exists()) + } + + @Test fun steamsOwnMoviesAreNeverDeleted() { + val own = File(BootMovieLibrary.steamRoot(app), "steamui/movies/deck_startup.webm").also { it.parentFile!!.mkdirs(); it.writeText("movie") } + val entry = BootMovieLibrary.list(app).first { it.id == "steam:/movies/deck_startup.webm" } + assertFalse(entry.removable) + assertFalse(BootMovieLibrary.remove(app, entry.id)) + assertTrue(own.exists()) + } + + @Test fun anImportSurvivesTheRuntimeBeingReset() { + val name = imported("Keep") + movies.deleteRecursively() + assertTrue(BootMovieLibrary.list(app).any { it.id == "file:$name" }) + assertTrue(File(movies, name).isFile) + } + + @Test fun importsAtTheSameTimeAllLandInTheList() { + val names = java.util.Collections.synchronizedList(ArrayList()) + (1..8).map { n -> Thread { names.add(imported("Movie")) } }.onEach { it.start() }.forEach { it.join() } + assertEquals(8, names.toSet().size) + assertEquals(8, BootMovieLibrary.list(app).count { it.source == BootMovieLibrary.SOURCE_IMPORT }) + } + + @Test fun steamIsPointedBackAtItsDefaultWhenTheStagedMovieIsGone() { + steamPicksAt(SessionFiles.BOOT_MOVIE_PATH) + assertTrue(SessionFiles.resetMissingStartupMovie(BootMovieLibrary.steamConfig(app), false)) + assertNull(SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(app))) + } + + @Test fun aMissingConfigNeedsNoReset() { + assertTrue(SessionFiles.resetMissingStartupMovie(BootMovieLibrary.steamConfig(app), true)) + } + + @Test fun aStagedMovieThatIsThereIsLeftAlone() { + movie("bigpicture_startup.webm") + steamPicksAt(SessionFiles.BOOT_MOVIE_PATH) + assertFalse(SessionFiles.resetMissingStartupMovie(BootMovieLibrary.steamConfig(app), false)) + assertEquals(SessionFiles.BOOT_MOVIE_PATH, SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(app))) + } + + @Test fun aPendingPickResetsASteamMovieThatWasRemoved() { + steamPicksAt("/uioverrides/movies/gone.webm") + assertFalse(SessionFiles.resetMissingStartupMovie(BootMovieLibrary.steamConfig(app), false)) + assertTrue(SessionFiles.resetMissingStartupMovie(BootMovieLibrary.steamConfig(app), true)) + assertNull(SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(app))) + } + + @Test fun onlyTheThreeStartupMoviesOfSteamAreListed() { + listOf("deck_startup", "oled_startup", "startup_machine", "controller_generic_thumbstick_move").forEach { + File(BootMovieLibrary.steamRoot(app), "steamui/movies/$it.webm").also { f -> f.parentFile!!.mkdirs(); f.writeText("movie") } + } + val ids = BootMovieLibrary.list(app).map { it.id }.filter { it.startsWith("steam:") } + assertEquals( + listOf("steam:/movies/deck_startup.webm", "steam:/movies/oled_startup.webm", "steam:/movies/startup_machine.webm"), + ids.sorted(), + ) + } + + @Test fun aMovieBoughtInThePointsShopIsListedAndAdopted() { + val file = File(BootMovieLibrary.steamRoot(app), "appcache/startupmovies/Bought.webm").also { it.parentFile!!.mkdirs(); it.writeText("movie") } + val entry = BootMovieLibrary.list(app).first { it.id == "steam:/appcache/startupmovies/Bought.webm" } + assertFalse(entry.removable) + assertEquals(BootMovieLibrary.SOURCE_POINTSHOP, entry.source) + steamPicksAt("/appcache/startupmovies/Bought.webm") + assertTrue(BootMovie.syncFromSteam(app)) + assertEquals("steam:/appcache/startupmovies/Bought.webm", BootMovie.choice(app)) + assertEquals(file, BootMovie.currentFile(app)) + assertNull(BootMovieLibrary.file(app, "steam:/../x.webm")) + } + + @Test fun aBoughtMovieNamedByIdAndHashIsShownByItsId() { + File(BootMovieLibrary.steamRoot(app), "appcache/startupmovies/39900045022_590371b7f10882d09ac59e5d3691b462c0091a6d.webm") + .also { it.parentFile!!.mkdirs(); it.writeText("movie") } + val entry = BootMovieLibrary.list(app).first { it.source == BootMovieLibrary.SOURCE_POINTSHOP } + assertEquals("#39900045022", entry.title) + } + + @Test fun theReportNamesWhatStageDidAndWhereMoviesAre() { + File(BootMovieLibrary.steamRoot(app), "appcache/startupmovies/1_ab.webm").also { it.parentFile!!.mkdirs(); it.writeText("movie") } + BootMovieReport.note(app, "stage test") + val report = BootMovieReport.build(app) + assertTrue(report.contains("== DroidDeck state")) + assertTrue(report.contains("startupmovies/1_ab.webm")) + assertTrue(report.contains("stage test")) + } + + @Test fun pathTricksAreNotMovies() { + movie("a.webm") + assertNull(BootMovieLibrary.file(app, "file:../a.webm")) + assertNull(BootMovieLibrary.file(app, "file:bigpicture_startup.webm")) + assertFalse(BootMovieLibrary.remove(app, "file:../a.webm")) + } + + @Test fun freeNameNeverReusesAFileOrAStagedName() { + movie("Intro.webm") + assertEquals("Intro (2).webm", BootMovieLibrary.freeName(app, "Intro")) + assertEquals("movie.webm", BootMovieLibrary.freeName(app, "///")) + } + + @Test fun aMovieChosenInsideSteamIsAdoptedOnce() { + movie("a.webm"); movie("b.webm") + BootMovie.select(app, "file:a.webm") + steamPicks("b.webm") + assertTrue(BootMovie.syncFromSteam(app)) + assertEquals("file:b.webm", BootMovie.choice(app)) + // Picking another one here is not undone by the same Steam setting. + BootMovie.select(app, "file:a.webm") + assertFalse(BootMovie.syncFromSteam(app)) + assertEquals("file:a.webm", BootMovie.choice(app)) + // A new pick inside Steam is adopted again. + movie("c.webm") + steamPicks("c.webm") + assertTrue(BootMovie.syncFromSteam(app)) + assertEquals("file:c.webm", BootMovie.choice(app)) + } + + @Test fun aSteamPickIsTakenOverWithoutBeingStagedOverSteamsOwnSetting() { + movie("a.webm") + BootMovie.select(app, "file:a.webm") + SessionPrefs.setBootMovieApplyNext(app, false) + steamPicks("a.webm") + assertFalse(BootMovie.syncFromSteam(app)) + assertEquals("file:a.webm", BootMovie.choice(app)) + assertFalse(SessionPrefs.bootMovieApplyNext(app)) + } + + @Test fun theStagedCopyNamedInSteamsConfigIsNotAPick() { + movie("a.webm") + BootMovie.select(app, "file:a.webm") + steamPicksAt(SessionFiles.BOOT_MOVIE_PATH) + assertFalse(BootMovie.syncFromSteam(app)) + assertEquals("file:a.webm", BootMovie.choice(app)) + } + + @Test fun aBoughtMovieIsShownUnderItsPointsShopTitle() { + File(BootMovieLibrary.steamRoot(app), "config/communityitemscache/startupmovies/39900045022_ab12.webm") + .also { it.parentFile!!.mkdirs(); it.writeText("movie") } + File(BootMovieLibrary.steamRoot(app), "userdata/1/config/localconfig.vdf").also { it.parentFile!!.mkdirs() }.writeText( + "\"GetStartupMovies\"\t\t\"[{\\\"communityitemid\\\":\\\"39900045022\\\",\\\"image_small\\\":\\\"x.png\\\",\\\"name\\\":\\\"Turret Factory\\\",\\\"item_title\\\":\\\"Turret Factory\\\"}]\"\n", + ) + val entry = BootMovieLibrary.list(app).first { it.source == BootMovieLibrary.SOURCE_POINTSHOP } + assertEquals("Turret Factory", entry.title) + } + + @Test fun notesKeptInSteamsMoviesFolderByAnEarlierVersionAreTakenOver() { + movie("Old.webm") + File(movies, ".droiddeck-movies.json").writeText("{\"Old.webm\":{\"title\":\"Old one\",\"source\":\"repo\",\"repo\":\"r1\"}}") + val entry = BootMovieLibrary.list(app).first { it.id == "file:Old.webm" } + assertEquals("Old one", entry.title) + assertEquals(BootMovieLibrary.SOURCE_REPO, entry.source) + assertEquals(setOf("r1"), BootMovieLibrary.installedRepoIds(app)) + assertFalse(File(movies, ".droiddeck-movies.json").exists()) + } + + @Test fun aPickMadeHereBeatsAnOlderSteamPickThatWasNeverSeen() { + movie("a.webm"); movie("b.webm") + steamPicks("b.webm") + BootMovie.select(app, "file:a.webm") + assertFalse(BootMovie.syncFromSteam(app)) + assertEquals("file:a.webm", BootMovie.choice(app)) + } + + @Test fun steamPointingAtAMovieThatIsNotThereChangesNothing() { + steamPicks("gone.webm") + assertFalse(BootMovie.syncFromSteam(app)) + assertEquals(BootMovie.DROIDDECK_30, BootMovie.choice(app)) + } + + @Test fun volumeAndLengthDefaultToTheWholeMovieAtFullVolume() { + assertEquals(100, SessionPrefs.bootMovieVolume(app)) + assertEquals(0, SessionPrefs.bootMovieSeconds(app)) + SessionPrefs.setBootMovieVolume(app, 40) + SessionPrefs.setBootMovieSeconds(app, 3) + assertEquals(40, SessionPrefs.bootMovieVolume(app)) + assertEquals(3, SessionPrefs.bootMovieSeconds(app)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/BootMoviePlanTest.kt b/app/src/test/java/com/droiddeck/launcher/session/BootMoviePlanTest.kt new file mode 100644 index 0000000000..e9341851d7 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/BootMoviePlanTest.kt @@ -0,0 +1,59 @@ +package com.droiddeck.launcher.session + +import com.droiddeck.launcher.session.BootMovie.Step +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class BootMoviePlanTest { + @Test + fun fullVolumeWithoutLimitPassesTheSourceThrough() { + val plan = BootMovie.plan(100, 0) + assertTrue(plan.passthrough) + assertTrue(plan.steps.isEmpty()) + } + + @Test + fun fullVolumeWithLimitKeepsSoundAndFallsBackToTheSource() { + val plan = BootMovie.plan(100, 5) + assertFalse(plan.passthrough) + assertEquals(listOf(Step.REMUX_AUDIO, Step.TRANSCODE_AUDIO), plan.steps) + assertTrue(plan.sourceOnFailure) + } + + @Test + fun silentGoesWithoutSoundAndNeverFallsBackToTheSource() { + val plan = BootMovie.plan(0, 0) + assertEquals(listOf(Step.REMUX_SILENT, Step.TRANSCODE_SILENT), plan.steps) + assertFalse(plan.sourceOnFailure) + } + + @Test + fun partialVolumeDegradesToSilenceNotToFullVolume() { + val plan = BootMovie.plan(40, 0) + assertEquals(listOf(Step.REGAIN, Step.REMUX_SILENT, Step.TRANSCODE_AUDIO), plan.steps) + assertFalse(plan.passthrough) + assertFalse(plan.sourceOnFailure) + } + + @Test + fun framesBeyondFullHdAreOversizedInEitherOrientation() { + assertTrue(BootMovie.oversized(3840, 2160)) + assertTrue(BootMovie.oversized(2160, 3840)) + assertFalse(BootMovie.oversized(1920, 1080)) + assertFalse(BootMovie.oversized(1280, 800)) + assertFalse(BootMovie.oversized(1080, 1920)) + } + + @Test + fun anOversizedMovieIsAlwaysConvertedAndNeverFallsBackToTheSource() { + for (volume in listOf(0, 40, 100)) { + val plan = BootMovie.oversizedPlan(volume) + assertFalse(plan.passthrough) + assertFalse(plan.sourceOnFailure) + } + assertEquals(listOf(Step.TRANSCODE_SILENT), BootMovie.oversizedPlan(0).steps) + assertEquals(listOf(Step.TRANSCODE_AUDIO), BootMovie.oversizedPlan(60).steps) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/BootMovieTranscoderTest.kt b/app/src/test/java/com/droiddeck/launcher/session/BootMovieTranscoderTest.kt new file mode 100644 index 0000000000..bb31c7eaa4 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/BootMovieTranscoderTest.kt @@ -0,0 +1,17 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertSame +import org.junit.Test + +class BootMovieTranscoderTest { + @Test fun scaleQuietsAndCutsTheSoundAtTheSameTime() { + val pcm = ShortArray(48_000 * 2) { 1000 } + assertSame(pcm, BootMovieTranscoder.scale(pcm, 2, 1f, Long.MAX_VALUE)) + val quieter = BootMovieTranscoder.scale(pcm, 2, 0.5f, Long.MAX_VALUE) + assertEquals(pcm.size, quieter.size) + assertEquals(500.toShort(), quieter[0]) + val cut = BootMovieTranscoder.scale(pcm, 2, 1f, 500_000L) + assertEquals(24_000 * 2, cut.size) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/InputSysfsComponentTest.kt b/app/src/test/java/com/droiddeck/launcher/session/InputSysfsComponentTest.kt new file mode 100644 index 0000000000..0cb8e28435 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/InputSysfsComponentTest.kt @@ -0,0 +1,57 @@ +package com.droiddeck.launcher.session + +import com.droiddeck.launcher.input.FakeInputWriter +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class InputSysfsComponentTest { + @Test fun steamInputsVirtualPadKeepsItsIdentity() { + val pad = InputSysfsComponent.virtualPad("PRODUCT=3/28de/11ff/1\nNAME=\"Microsoft X-Box 360 pad 0\"\nPHYS=\"\"\n")!! + assertEquals(listOf(3, 0x28de, 0x11ff, 1), listOf(pad.bus, pad.vendor, pad.product, pad.version)) + assertEquals("Microsoft X-Box 360 pad 0", pad.name) + assertEquals("", pad.phys) + assertTrue(pad.uevent().startsWith("PRODUCT=3/28de/11ff/1\nNAME=\"Microsoft X-Box 360 pad 0\"\n")) + } + + @Test fun anUnreadableDescriptionIsNotListed() { + assertNull(InputSysfsComponent.virtualPad("")) + assertNull(InputSysfsComponent.virtualPad("PRODUCT=3/28de\nNAME=\"pad\"\n")) + assertNull(InputSysfsComponent.virtualPad("PRODUCT=3/28de/11ff/1\n")) + } + + @Test fun ringPadsMatchWhatTheirIoctlsAnswer() { + val xbox = InputSysfsComponent.ringPad(1, steamVirtual = false) + assertEquals("Xbox 360 Controller (1)", xbox.name) + assertEquals(listOf(0x045e, 0x028e, 0x110), listOf(xbox.vendor, xbox.product, xbox.version)) + val steam = InputSysfsComponent.ringPad(0, steamVirtual = true) + assertEquals("Microsoft X-Box 360 pad 0", steam.name) + assertEquals(listOf(0x28de, 0x11ff), listOf(steam.vendor, steam.product)) + } + + @Test fun ringPadsAreHiddenWhereGamesCannotOpenThem() { + assertFalse(InputSysfsComponent.ringWithdrawn(deckPad = false, type = FakeInputWriter.PAD_TYPE_DECK)) + assertFalse(InputSysfsComponent.ringWithdrawn(deckPad = true, type = FakeInputWriter.PAD_TYPE_XBOX)) + assertTrue(InputSysfsComponent.ringWithdrawn(deckPad = true, type = FakeInputWriter.PAD_TYPE_DECK)) + assertTrue(InputSysfsComponent.ringWithdrawn(deckPad = true, type = -1)) + } + + @Test fun onlyThePadsOwnUdevRecordsAreCleared() { + assertTrue(InputSysfsComponent.isPadRecord("c13:64")) + assertTrue(InputSysfsComponent.isPadRecord("c13:80")) + assertTrue(InputSysfsComponent.isPadRecord("+input:input16")) + assertFalse(InputSysfsComponent.isPadRecord("c13:63")) + assertFalse(InputSysfsComponent.isPadRecord("c13:128")) + assertFalse(InputSysfsComponent.isPadRecord("c240:16")) + assertFalse(InputSysfsComponent.isPadRecord("+input:input64")) + } + + @Test fun theUdevRecordMarksAnInitializedJoystick() { + val record = InputSysfsComponent.udevRecord(42).lines() + assertEquals("I:42", record.first()) + assertTrue("E:ID_INPUT_JOYSTICK=1" in record) + assertTrue("E:ID_INPUT=1" in record) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareTest.kt index b91e5bcf67..bc1718bffb 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionLogShareTest.kt @@ -32,6 +32,35 @@ class SessionLogShareTest { "rules $rules\n" + files.joinToString("") { val f = File(folder, it); "${f.length()}\t${f.lastModified()}\t$it\n" }) } + @Test fun aLogPastTheInMemoryCapIsStillScrubbedIntoTheZip() { + val folder = tmp.newFolder("2026-10-18-01-steam") + val line = ("x".repeat(1023) + "\n").toByteArray() + File(folder, "session.log").outputStream().buffered().use { out -> + out.write("$secret\n".toByteArray()) + repeat(65 * 1024) { out.write(line) } + } + assertTrue(File(folder, "session.log").length() >= LogRedactor.IN_MEMORY_SCRUB_MAX) + val out = zip(folder) + assertTrue(out.containsKey("session.log")) + assertFalse(out.getValue("session.log").contains(leaked)) + } + + @Test fun aLogWithANulByteIsScrubbedNotCopiedRaw() { + val folder = tmp.newFolder("2026-10-18-02-steam") + File(folder, "crash.log").writeBytes(byteArrayOf(0) + "$secret\n".toByteArray()) + val out = zip(folder) + assertTrue(out.containsKey("crash.log")) + assertFalse(out.getValue("crash.log").contains(leaked)) + } + + @Test fun utf16SecretsDoNotEscapeInTheSharedZip() { + val folder = tmp.newFolder("2026-10-18-03-steam") + File(folder, "crash.log").writeBytes("sessionid=$leaked".toByteArray(Charsets.UTF_16LE)) + val output = zip(folder).getValue("crash.log") + assertFalse(output.replace("\u0000", "").contains(leaked)) + assertTrue(output.contains("withheld")) + } + @Test fun aRecordedUnchangedFileIsScrubbedAgainOnTheWayIntoTheZip() { val folder = tmp.newFolder("2026-10-06-01-steam") File(folder, "session.log").writeText("$secret\n") diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt new file mode 100644 index 0000000000..61e95da495 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt @@ -0,0 +1,379 @@ +package com.droiddeck.launcher.session + +import java.io.File +import java.util.concurrent.AbstractExecutorService +import java.util.concurrent.RejectedExecutionException +import java.util.concurrent.TimeUnit +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class SessionSuspendControllerTest { + @get:Rule val temporary = TemporaryFolder() + + @Test fun everyWorkerThreadIsStoppedAfterTheRoot() { + for (count in listOf(17, 68)) { + val fixture = fixture(count) + fixture.controller.freeze { assertTrue(it) } + assertTrue(fixture.game.threads.all { it.state == 't' }) + assertTrue(fixture.signals.count { it.pid == GAME && it.signal == STOP } >= count) + assertEquals(ROOT, fixture.signals.first { it.signal == STOP }.pid) + assertTrue(fixture.now < 1000) + assertEquals(1, fixture.audioSuspends) + } + } + + @Test fun cpuMustBeStableAcrossTwoCompleteSnapshots() { + val fixture = fixture(17) + var changes = 0 + fixture.afterSleep = { + if (fixture.game.threads.all { it.state == 't' } && changes < 3) { + fixture.game.threads.last().cpu++ + changes++ + } + } + fixture.controller.freeze { assertTrue(it) } + assertEquals(3, changes) + assertTrue(fixture.signals.count { it.pid == GAME && it.signal == STOP } >= 17) + } + + @Test fun reusedTidAndNewThreadMustJoinTheStableInventory() { + val fixture = fixture(17) + var changed = false + fixture.afterSleep = { + if (!changed && fixture.game.threads.all { it.state == 't' }) { + changed = true + fixture.game.threads.last().apply { started++; state = 'S'; cpu = 0 } + fixture.game.threads += Task(500, 9000, 'S') + } + } + fixture.controller.freeze { assertTrue(it) } + assertTrue(changed) + assertTrue(fixture.game.threads.all { it.state == 't' }) + assertTrue(fixture.signals.count { it.pid == GAME && it.signal == STOP } >= 19) + } + + @Test fun zombieLeaderDoesNotHideRunningWorkers() { + val fixture = fixture(17) + fixture.game.threads.first().state = 'Z' + fixture.sync() + fixture.controller.freeze { assertTrue(it) } + assertEquals('Z', fixture.game.threads.first().state) + assertTrue(fixture.game.threads.drop(1).all { it.state == 't' }) + assertTrue(fixture.signals.count { it.pid == GAME && it.signal == STOP } >= 16) + } + + @Test fun lateReparentedTraceeIsDiscoveredAndResumed() { + val fixture = fixture(17) + val late = Group(600, 1, ROOT, mutableListOf(Task(600, 6000, 'S'))) + fixture.afterSleep = { + if (fixture.root.threads.first().state == 'T' && late !in fixture.groups) fixture.groups += late + } + fixture.controller.freeze { assertTrue(it) } + assertEquals('t', late.threads.first().state) + fixture.controller.resume { assertTrue(it) } + assertEquals('S', late.threads.first().state) + } + + @Test fun descendantHelperKeepsRootStopAndResumeOrdering() { + val fixture = fixture(17) + val helper = Group(700, ROOT, 0, mutableListOf(Task(700, 7000, 'S'))) + fixture.groups += helper + fixture.helpers += helper.pid + fixture.sync() + fixture.controller.freeze { assertTrue(it) } + val stops = fixture.signals.filter { it.signal == STOP } + assertTrue(stops.indexOfFirst { it.pid == ROOT } < stops.indexOfFirst { it.pid == helper.pid }) + val before = fixture.signals.size + fixture.controller.resume { assertTrue(it) } + assertEquals(listOf(ROOT, helper.pid, GAME), fixture.signals.drop(before).take(3).map { it.pid }) + } + + @Test fun retainedHelperDoesNotAdoptAReusedPidOnRefreeze() { + val fixture = fixture(17) + val helper = Group(700, 9000, 0, mutableListOf(Task(700, 7000, 'S'))) + fixture.groups += helper + fixture.helpers += helper.pid + fixture.sync() + fixture.controller.freeze { assertTrue(it) } + fixture.blockGameContinue = true + fixture.controller.resume { assertFalse(it) } + helper.threads.first().apply { started++; state = 'S' } + fixture.sync() + val before = fixture.signals.size + fixture.controller.freeze { assertTrue(it) } + assertFalse(fixture.signals.drop(before).any { it.pid == helper.pid }) + } + + @Test fun timeoutRollsBackAllKnownProcessesAndAudio() { + val fixture = fixture(17) + fixture.neverStop = true + fixture.controller.freeze { assertFalse(it) } + assertTrue(fixture.now <= 8100) + assertEquals(ROOT, fixture.signals.first { it.signal == CONT }.pid) + assertTrue(fixture.game.threads.all { it.state == 'S' }) + assertEquals(1, fixture.audioResumes) + } + + @Test fun missingKnownStatCannotBeMistakenForAnExitedProcess() { + val fixture = fixture(17) + fixture.afterSleep = { + if (fixture.root.threads.first().state == 'T') fixture.missingGameStat = true + } + fixture.controller.freeze { assertFalse(it) } + assertEquals(1, fixture.audioResumes) + fixture.missingGameStat = false + fixture.sync() + fixture.controller.resume { assertTrue(it) } + assertTrue(fixture.game.threads.all { it.state == 'S' }) + } + + @Test fun unavailableOrEmptyThreadInventoryCannotReportSuccess() { + for (empty in listOf(false, true)) { + val fixture = fixture(17) + fixture.emptyGameTasks = empty + fixture.missingGameTasks = !empty + fixture.sync() + fixture.controller.freeze { assertFalse(it) } + assertEquals(1, fixture.audioResumes) + assertTrue(fixture.game.threads.all { it.state == 'S' }) + } + } + + @Test fun disappearingRootFailsAndStillResumesKnownChildren() { + val fixture = fixture(17) + fixture.afterSleep = { + if (fixture.root.threads.first().state == 'T') fixture.rootGone = true + } + fixture.controller.freeze { assertFalse(it) } + assertTrue(fixture.game.threads.all { it.state == 'S' }) + assertEquals(1, fixture.audioResumes) + } + + @Test fun replacementRootIsNeverStoppedOrContinued() { + val fixture = fixture(17) + var atReplacement = -1 + fixture.afterSleep = { + if (atReplacement < 0 && fixture.root.threads.first().state == 'T') { + atReplacement = fixture.signals.size + fixture.root.threads.first().apply { started++; state = 'S' } + } + } + fixture.controller.freeze { assertFalse(it) } + assertTrue(atReplacement > 0) + assertFalse(fixture.signals.drop(atReplacement).any { it.pid == ROOT }) + assertTrue(fixture.game.threads.all { it.state == 'S' }) + } + + @Test fun reusedChildPidIsNotContinuedDuringResume() { + val fixture = fixture(17) + fixture.controller.freeze { assertTrue(it) } + fixture.game.threads.first().apply { started++; state = 'S' } + fixture.game.parent = 1 + fixture.game.tracer = 0 + fixture.sync() + val before = fixture.signals.size + fixture.controller.resume { assertTrue(it) } + assertFalse(fixture.signals.drop(before).any { it.pid == GAME }) + } + + @Test fun closeCancelsFreezeAndRestoresSavedRootAfterServiceClearsIt() { + val executor = QueueExecutor() + val fixture = fixture(68, executor) + var closed = false + var requested = false + fixture.afterSleep = { + if (!requested && fixture.root.threads.first().state == 'T') { + requested = true + fixture.rootPid = -1 + fixture.controller.closeAndResume { closed = true } + } + } + fixture.controller.freeze { assertFalse(it) } + executor.drain() + assertTrue(closed) + assertTrue(executor.isShutdown) + assertTrue(fixture.game.threads.all { it.state == 'S' }) + assertEquals(1, fixture.audioResumes) + } + + @Test fun successfulFreezeIsRecheckedAndAudioIsReassertedAfterFailedResume() { + val fixture = fixture(17) + fixture.controller.freeze { assertTrue(it) } + fixture.blockGameContinue = true + fixture.controller.resume { assertFalse(it) } + assertEquals(1, fixture.audioResumes) + fixture.blockGameContinue = false + fixture.game.threads.last().state = 'S' + fixture.sync() + fixture.controller.freeze { assertTrue(it) } + assertTrue(fixture.game.threads.all { it.state == 't' }) + assertEquals(2, fixture.audioSuspends) + } + + @Test fun failedRollbackCanBeRefrozenAndAudioIsSuspendedAgain() { + val fixture = fixture(17) + fixture.neverStop = true + fixture.blockGameContinue = true + fixture.controller.freeze { assertFalse(it) } + fixture.neverStop = false + fixture.blockGameContinue = false + fixture.controller.freeze { assertTrue(it) } + assertTrue(fixture.game.threads.all { it.state == 't' }) + assertEquals(2, fixture.audioSuspends) + assertEquals(1, fixture.audioResumes) + } + + @Test fun repeatedFreezeResumeKeepsOriginalRootFirstOrdering() { + val fixture = fixture(17) + repeat(2) { + fixture.controller.freeze { assertTrue(it) } + val before = fixture.signals.size + fixture.controller.resume { assertTrue(it) } + assertEquals(ROOT, fixture.signals.drop(before).first().pid) + assertTrue(fixture.game.threads.all { it.state == 'S' }) + } + fixture.controller.freeze { assertTrue(it) } + fixture.rootPid = -1 + var closed = false + fixture.controller.closeAndResume { closed = true } + assertTrue(closed) + assertTrue(fixture.game.threads.all { it.state == 'S' }) + } + + @Test fun rejectedExecutorDoesNotFreezeOnTheCallingThread() { + val executor = QueueExecutor().apply { shutdown() } + val fixture = fixture(17, executor) + fixture.controller.freeze { assertFalse(it) } + assertTrue(fixture.signals.isEmpty()) + assertEquals(0, fixture.audioSuspends) + } + + private fun fixture(count: Int, executor: QueueExecutor = InlineExecutor()) = + Fixture(temporary.newFolder(), count, executor) + + private data class Task(val tid: Int, var started: Long, var state: Char, var cpu: Long = 0) + private data class Group(val pid: Int, var parent: Int, var tracer: Int, val threads: MutableList) + private data class SentSignal(val pid: Int, val signal: Int) + + private class Fixture(val proc: File, count: Int, executor: QueueExecutor) { + val root = Group(ROOT, 9000, 0, mutableListOf(Task(ROOT, 1000, 'S'))) + val game = Group(GAME, ROOT, ROOT, MutableList(count) { Task(GAME + it, 2000L + it, 'S') }) + val groups = mutableListOf(root, game) + val helpers = mutableListOf() + val signals = mutableListOf() + var rootPid = ROOT + var now = 0L + var audioSuspends = 0 + var audioResumes = 0 + var neverStop = false + var blockGameContinue = false + var missingGameStat = false + var missingGameTasks = false + var emptyGameTasks = false + var rootGone = false + var afterSleep: (() -> Unit)? = null + private var continuing = false + val controller = SessionSuspendController( + { rootPid }, { helpers }, { audioSuspends++ }, { audioResumes++ }, + proc, ::signal, ::threadSignal, ::sleep, { now }, executor, + ) + + init { sync() } + + private fun signal(pid: Int, signal: Int) { + signals += SentSignal(pid, signal) + val group = groups.first { it.pid == pid } + if (signal == STOP) { + continuing = false + if (pid == ROOT) group.threads.forEach { it.state = 'T' } + else group.threads.firstOrNull { + it.state !in listOf('T', 't', 'Z', 'X') && !(neverStop && it == game.threads.last()) + }?.state = 't' + } else if (signal == CONT) { + continuing = true + if (!(pid == GAME && blockGameContinue)) group.threads.forEach { if (it.state != 'Z') it.state = 'S' } + } + sync() + } + + private fun threadSignal(pid: Int, tid: Int, signal: Int) { + signals += SentSignal(pid, signal) + val task = groups.first { it.pid == pid }.threads.first { it.tid == tid } + if (signal == STOP && task.state !in listOf('T', 't', 'Z', 'X') && !(neverStop && task == game.threads.last())) { + task.state = 't' + } + sync() + } + + private fun sleep(millis: Long) { + now += millis + if (root.threads.first().state != 'T' && !continuing) game.threads.forEach { + if (it.state != 'Z') { it.state = 'S'; it.cpu++ } + } + afterSleep?.invoke() + sync() + } + + fun sync() { + for (group in groups) { + val dir = File(proc, group.pid.toString()) + if (group == root && rootGone) { dir.deleteRecursively(); continue } + dir.mkdirs() + val stat = File(dir, "stat") + if (group == game && missingGameStat) stat.delete() + else stat.writeText(stat(group, group.threads.first())) + File(dir, "status").writeText("TracerPid: ${group.tracer}\n") + val taskDir = File(dir, "task") + if (group == game && missingGameTasks) { taskDir.deleteRecursively(); continue } + taskDir.mkdirs() + if (group == game && emptyGameTasks) { taskDir.listFiles().orEmpty().forEach { it.deleteRecursively() }; continue } + for (task in group.threads) { + val entry = File(taskDir, task.tid.toString()).apply { mkdirs() } + File(entry, "stat").writeText(stat(group, task)) + } + } + } + + private fun stat(group: Group, task: Task): String { + val fields = MutableList(20) { "0" } + fields[0] = task.state.toString() + fields[1] = group.parent.toString() + fields[11] = task.cpu.toString() + fields[19] = task.started.toString() + return "${task.tid} (fixture (worker)) ${fields.joinToString(" ")}" + } + } + + private open class QueueExecutor : AbstractExecutorService() { + private val queue = ArrayDeque() + private var stopped = false + override fun execute(command: Runnable) { + if (stopped) throw RejectedExecutionException() + queue.add(command) + } + fun drain() { while (queue.isNotEmpty()) queue.removeFirst().run() } + override fun shutdown() { stopped = true } + override fun shutdownNow(): MutableList { + stopped = true + return queue.toMutableList().also { queue.clear() } + } + override fun isShutdown() = stopped + override fun isTerminated() = stopped && queue.isEmpty() + override fun awaitTermination(timeout: Long, unit: TimeUnit) = isTerminated + } + + private class InlineExecutor : QueueExecutor() { + override fun execute(command: Runnable) { super.execute(command); drain() } + } + + private companion object { + const val ROOT = 100 + const val GAME = 200 + const val STOP = 19 + const val CONT = 18 + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionVisibilityTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionVisibilityTest.kt index b35ea287e3..3f34e52234 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionVisibilityTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionVisibilityTest.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.session +import android.view.Display import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test @@ -20,6 +21,34 @@ class SessionVisibilityTest { assertFalse(sessionHasVisibleSurface(false, false, false)) } + @Test fun phoneDisplayFollowsTheInteractiveState() { + assertTrue(sessionScreenOn(true, true, null)) + assertFalse(sessionScreenOn(true, false, null)) + assertFalse(sessionScreenOn(true, false, Display.STATE_ON)) + } + + @Test fun externalDisplayKeepsTheSessionAwakeWhileThePhoneScreenIsOff() { + assertTrue(sessionScreenOn(false, false, Display.STATE_ON)) + assertTrue(sessionScreenOn(false, false, Display.STATE_ON_SUSPEND)) + assertTrue(sessionScreenOn(false, false, Display.STATE_VR)) + } + + @Test fun externalDisplayTurnedOffSuspendsEvenWithThePhoneScreenOn() { + assertFalse(sessionScreenOn(false, true, Display.STATE_OFF)) + assertFalse(sessionScreenOn(false, true, Display.STATE_DOZE)) + assertFalse(sessionScreenOn(false, true, Display.STATE_DOZE_SUSPEND)) + } + + @Test fun missingExternalDisplayFallsBackToThePhone() { + assertTrue(sessionScreenOn(false, true, null)) + assertFalse(sessionScreenOn(false, false, null)) + } + + @Test fun unknownExternalDisplayStateFallsBackToThePhone() { + assertTrue(sessionScreenOn(false, true, Display.STATE_UNKNOWN)) + assertFalse(sessionScreenOn(false, false, Display.STATE_UNKNOWN)) + } + @Test fun losingXrVisibilityReturnsToNormalSuspendRules() { assertTrue(sessionHasVisibleSurface(false, false, true)) assertFalse(sessionHasVisibleSurface(false, false, false)) diff --git a/app/src/test/java/com/droiddeck/launcher/session/StartupMovieConfigTest.kt b/app/src/test/java/com/droiddeck/launcher/session/StartupMovieConfigTest.kt new file mode 100644 index 0000000000..c14fc02310 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/StartupMovieConfigTest.kt @@ -0,0 +1,66 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config +import java.io.File + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class StartupMovieConfigTest { + @get:Rule val folder = TemporaryFolder() + + private val older = "\t\t\t\t\"StartupMovie\"\n\t\t\t\t{\n\t\t\t\t\t\"MovieID\"\t\t\"0\"\n\t\t\t\t\t\"LocalPath\"\t\t\"%s\"\n\t\t\t\t}\n" + private val customization = "\t\"Customization\"\n\t{\n\t\t\"StartupMovie\"\n\t\t{\n\t\t\t\"MovieID\"\t\t\"%s\"\n\t\t\t\"LocalPath\"\t\t\"%s\"\n\t\t}\n\t}\n" + + private fun config(olderPath: String?, id: String?, path: String?): File { + val text = StringBuilder("\"InstallConfigStore\"\n{\n\t\"Software\"\n\t{\n\t\t\"Valve\"\n\t\t{\n\t\t\t\"Steam\"\n\t\t\t{\n") + if (olderPath != null) text.append(older.format(olderPath)) + text.append("\t\t\t}\n\t\t}\n\t}\n") + if (id != null && path != null) text.append(customization.format(id, path)) + text.append("}\n") + return folder.newFile().also { it.writeText(text.toString()) } + } + + @Test fun steamReadsTheMovieUnderCustomizationNotTheOlderOne() { + val file = config(SessionFiles.BOOT_MOVIE_PATH, "39900045022", "/communityitemscache/startupmovies/39900045022_ab.webm") + assertEquals("/communityitemscache/startupmovies/39900045022_ab.webm", SessionFiles.startupMoviePath(file)) + } + + @Test fun aPickIsWrittenWhereSteamReadsItAndTheOlderPlaceIsKeptInStep() { + val file = config("/uioverrides/movies/x.webm", "39900045022", "/communityitemscache/startupmovies/39900045022_ab.webm") + assertTrue(SessionFiles.ensureStartupMovieDefault(file, force = true)) + val text = file.readText() + assertEquals(SessionFiles.BOOT_MOVIE_PATH, SessionFiles.startupMoviePath(file)) + assertFalse(text.contains("39900045022")) + assertEquals(2, Regex("\"LocalPath\"\\s+\"" + Regex.escape(SessionFiles.BOOT_MOVIE_PATH) + "\"").findAll(text).count()) + } + + @Test fun aPickMadeInSteamIsLeftAloneWithoutAPendingPick() { + val file = config(SessionFiles.BOOT_MOVIE_PATH, "0", "/uioverrides/movies/Undertale.webm") + assertFalse(SessionFiles.ensureStartupMovieDefault(file, force = false)) + assertEquals("/uioverrides/movies/Undertale.webm", SessionFiles.startupMoviePath(file)) + } + + @Test fun aConfigWithoutCustomizationGetsOne() { + val file = config(null, null, null) + assertTrue(SessionFiles.ensureStartupMovieDefault(file, force = false)) + val text = file.readText() + assertTrue(text.contains("\"Customization\"")) + assertEquals(SessionFiles.BOOT_MOVIE_PATH, SessionFiles.startupMoviePath(file)) + assertEquals(2, Regex("\"StartupMovie\"").findAll(text).count()) + } + + @Test fun aMissingStagedMovieResetsTheSectionSteamReads() { + val file = config(SessionFiles.BOOT_MOVIE_PATH, "0", SessionFiles.BOOT_MOVIE_PATH) + assertTrue(SessionFiles.resetMissingStartupMovie(file, false)) + assertNull(SessionFiles.startupMoviePath(file)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/SteamClientSetupFailureTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SteamClientSetupFailureTest.kt new file mode 100644 index 0000000000..fd6400c60c --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/SteamClientSetupFailureTest.kt @@ -0,0 +1,72 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class SteamClientSetupFailureTest { + private fun find(vararg lines: String) = SteamClientSetupFailure.find(lines.asSequence()) + + @Test fun aBlockedDownloadCarriesTheLastCurlError() { + val failure = find( + "== STEP 12:35:22 checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)", + "curl: (7) Failed to connect to client-update.steamstatic.com:443 after 3 ms: Could not connect to server", + "curl: (35) Recv failure: Connection reset by peer", + "droiddeck-steam-install: no Steam client CDN answered for steam_client_steamdeck_publicbeta_linuxarm64", + "== steam: the Steam client could not be set up (status 1)", + "[gamescope] [Info] launch: Primary child shut down!", + )!! + assertTrue(failure.download) + assertEquals("curl: (35) Recv failure: Connection reset by peer", failure.curlError) + } + + @Test fun aFailureWithoutCurlErrorIsNotCalledADownloadProblem() { + val failure = find( + "== STEP 12:35:22 checking the Steam client (a first run downloads it)", + "== STEP 12:35:30 downloading Steam: bins_linuxarm64_linuxarm64 (2/17)", + "error: cannot create /root/.local/share/Steam/ubuntu12_32/steam-runtime.tar.xz", + "== steam: the Steam client could not be set up (status 50)", + )!! + assertFalse(failure.download) + assertNull(failure.curlError) + } + + @Test fun aReadyClientIsNoFailure() { + assertNull(find( + "== STEP 12:35:22 checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)", + "curl: (35) Recv failure: Connection reset by peer", + "== STEP 12:35:40 Steam client ready", + )) + } + + @Test fun onlyTheLatestCheckCounts() { + assertNull(find( + "== STEP 10:00:00 checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)", + "curl: (6) Could not resolve host: client-update.steamstatic.com", + "== steam: the Steam client could not be set up (status 1)", + "== STEP 10:05:00 checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)", + "== STEP 10:06:00 Steam client ready", + )) + val failure = find( + "== STEP 10:00:00 checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)", + "curl: (6) Could not resolve host: client-update.steamstatic.com", + "== steam: the Steam client could not be set up (status 1)", + "== STEP 10:05:00 checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)", + "== steam: the Steam client could not be set up (status 9)", + )!! + assertNull(failure.curlError) + } + + @Test fun anArm64SyncErrorIsNotBlamedForTheX64Client() { + val failure = find( + "== STEP 10:00:00 checking the Steam client's arm64 parts (first run downloads them, ~1-2 min)", + "curl: (6) Could not resolve host: client-update.steamstatic.com", + "== STEP 10:00:05 could not update the arm64 client's parts; the x86-64 client keeps its own web helper", + "== STEP 10:00:05 checking the x86-64 Steam client (FEX, experimental; the first run downloads ~2 GB)", + "== steam: the Steam client could not be set up (status 3)", + )!! + assertNull(failure.curlError) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/SteamDeckRepoTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SteamDeckRepoTest.kt new file mode 100644 index 0000000000..4458985f83 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/SteamDeckRepoTest.kt @@ -0,0 +1,92 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class SteamDeckRepoTest { + private val sample = """ + {"posts":[ + {"id":"p1","title":"Cool","content":"c","user":{"steam_name":"Ann"},"thumbnail":"https://x/t.png","video":"https://x/v.webm", + "video_duration":7,"likes":3,"downloads":9,"devices":["steam_deck"],"url":"https://steamdeckrepo.com/post/p1"}, + {"id":"p2","title":"","video":"http://insecure/v.webm"}, + {"id":"","video":"https://x/v.webm"}, + {"id":"p3","video":"https://x/v3.webm","thumbnail":"ftp://bad"} + ],"currentSort":"trending"} + """.trimIndent() + + @Test fun parsesPostsAndSkipsBrokenOnes() { + val posts = SteamDeckRepo.parse(sample)!! + assertEquals(listOf("p1", "p3"), posts.map { it.id }) + val first = posts[0] + assertEquals("Cool", first.title) + assertEquals("Ann", first.author) + assertEquals(7, first.seconds) + assertEquals(listOf("steam_deck"), first.devices) + assertEquals("p3", posts[1].title) + assertEquals("", posts[1].thumbnail) + } + + @Test fun notJsonIsNotAPage() { + assertNull(SteamDeckRepo.parse("")) + assertNull(SteamDeckRepo.parse("{}")) + } + + @Test fun buildsTheSameAddressesAsTheWebsite() { + assertEquals("https://steamdeckrepo.com/api/posts?sort=trending", SteamDeckRepo.url(SteamDeckRepo.Sort.TRENDING, null, "")) + assertEquals( + "https://steamdeckrepo.com/api/posts?sort=downloads-desc&device=steam_machine&search=a%20b%26c&page=3", + SteamDeckRepo.url(SteamDeckRepo.Sort.DOWNLOADS, "steam_machine", " a b&c ", 3), + ) + } + + @Test fun readsAreCutOffAtTheLimit() { + assertEquals(10, SteamDeckRepo.readLimited(ByteArray(10).inputStream(), 10)!!.size) + assertNull(SteamDeckRepo.readLimited(ByteArray(11).inputStream(), 10)) + } + + @Test fun jsonNullsAreEmptyTextNotTheWordNull() { + val posts = SteamDeckRepo.parse( + """{"posts":[{"id":"p9","title":null,"content":null,"user":{"steam_name":null},"thumbnail":null,"video":"https://x/v.webm","url":null}]}""", + )!! + val post = posts.single() + assertEquals("p9", post.title) + assertEquals("", post.content) + assertEquals("", post.author) + assertEquals("", post.thumbnail) + assertEquals("", post.url) + assertTrue(SteamDeckRepo.parse("""{"posts":[{"id":null,"video":"https://x/v.webm"}]}""")!!.isEmpty()) + } + + @Test fun aPageHoldsTwelveMovies() { + assertEquals(12, SteamDeckRepo.PAGE_SIZE) + } + + private fun lastPageOf(pages: Int, tail: Int = SteamDeckRepo.PAGE_SIZE) = SteamDeckRepo.lastPage(SteamDeckRepo.Sort.TRENDING, null, "") { p -> + when { + p < pages -> SteamDeckRepo.PAGE_SIZE + p == pages -> tail + else -> 0 + } + } + + @Test fun theLastPageIsFoundByAskingForPages() { + for (pages in listOf(2, 3, 7, 8, 9, 33, 100, 500)) assertEquals(pages, lastPageOf(pages)) + } + + @Test fun aShortLastPageEndsTheSearchAtOnce() { + assertEquals(1, lastPageOf(1, tail = 5)) + assertEquals(5, lastPageOf(5, tail = 3)) + assertEquals(37, lastPageOf(37, tail = 1)) + } + + @Test fun aSearchWithNothingHasOnePageAndAnUnreachableSiteHasNone() { + assertEquals(1, SteamDeckRepo.lastPage(SteamDeckRepo.Sort.TRENDING, null, "x") { 0 }) + assertNull(SteamDeckRepo.lastPage(SteamDeckRepo.Sort.TRENDING, null, "x") { null }) + assertNull(SteamDeckRepo.lastPage(SteamDeckRepo.Sort.TRENDING, null, "x") { p -> if (p < 4) SteamDeckRepo.PAGE_SIZE else null }) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/StoreLoginUserAgentTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/StoreLoginUserAgentTest.kt new file mode 100644 index 0000000000..bf0c264f2f --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/StoreLoginUserAgentTest.kt @@ -0,0 +1,27 @@ +package com.droiddeck.launcher.stores + +import android.os.Build +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class StoreLoginUserAgentTest { + @Test fun theDevicesWebViewAgentIsSentAsChrome() { + assertEquals( + "Mozilla/5.0 (Linux; Android 16; NP06J) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.7390.122 Mobile Safari/537.36", + StoreLoginActivity.chromeUserAgent( + "Mozilla/5.0 (Linux; Android 16; NP06J Build/BP2A.250605.031.A3; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/141.0.7390.122 Mobile Safari/537.36", + ), + ) + } + + @Test fun noWebViewAgentFallsBackToChromeWithoutAnotherDevicesModel() { + for (agent in listOf(null, "", "Dalvik/2.1.0 (Linux; U; Android 16)")) { + val ua = StoreLoginActivity.chromeUserAgent(agent) + assertTrue(ua, "Chrome/" in ua) + assertFalse(ua, "SM-S918B" in ua) + assertTrue(ua, "Android ${Build.VERSION.RELEASE}; ${Build.MODEL})" in ua) + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/WebCookiesTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/WebCookiesTest.kt new file mode 100644 index 0000000000..ec8c63d100 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/WebCookiesTest.kt @@ -0,0 +1,18 @@ +package com.droiddeck.launcher.stores + +import com.droiddeck.launcher.stores.gog.GogAuth +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class WebCookiesTest { + @Test fun gogLoginCookiesAreExpiredOnTheLoginHostAndTheDomain() { + val lines = WebCookies.expired("galaxy-login-s=a; galaxy-login-tsa=b; galaxy-login-al=c", GogAuth.COOKIE_DOMAIN, listOf("/"), "login.gog.com") + assertEquals(9, lines.size) + assertTrue(lines.contains("galaxy-login-al=; Max-Age=0; Path=/; Secure")) + assertTrue(lines.contains("galaxy-login-al=; Max-Age=0; Path=/; Secure; Domain=.gog.com")) + assertTrue(lines.contains("galaxy-login-al=; Max-Age=0; Path=/; Secure; Domain=login.gog.com")) + assertTrue(lines.none { it.startsWith("galaxy-login-al=c") }) + assertEquals(emptyList(), WebCookies.expired(null, GogAuth.COOKIE_DOMAIN, listOf("/"), "login.gog.com")) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxCatalogTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxCatalogTest.kt index 683696f14f..c5e6927e7a 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxCatalogTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxCatalogTest.kt @@ -19,6 +19,55 @@ class XboxCatalogTest { private fun envelope(vararg rows: JSONObject) = JSONObject().put("schema", 1).put("account", "test@example.test") .put("market", "US").put("checkedAt", now.toString()).put("entitlements", JSONArray(rows.toList())) private fun access(vararg rows: JSONObject) = XboxCatalog.access(envelope(*rows), "test@example.test", "US", now) + private fun membership() = JSONObject().put("productId", plan).put("status", "Active").put("endDate", "2099-01-01T00:00:00Z") + private fun withMembership(json: JSONObject, vararg plans: JSONObject) = json.put("subscriptions", JSONArray(plans.toList())) + + @Test fun separateMembershipRestoresSubscriptionChildrenWithoutInventingOwnership() { + val json = withMembership(envelope(row(game), row(parent, plan)), membership()) + assertEquals(mapOf(game to "owned", parent to "gamepass"), XboxCatalog.access(json, "test@example.test", "US", now)) + assertTrue(XboxCatalog.access(withMembership(envelope(), membership()), "test@example.test", "US", now).isEmpty()) + assertEquals(mapOf(game to "gamepass", parent to "gamepass"), XboxCatalog.access( + withMembership(envelope(row(game, parent), row(parent, plan)), membership()), "test@example.test", "US", now)) + } + + @Test fun separateMembershipPreservesProductRestrictionsAndExistingPlanEvidence() { + for (member in listOf(membership().put("status", "Expired"), membership().put("endDate", now.toString()))) { + assertTrue(XboxCatalog.access(withMembership(envelope(row(game, plan)), member), "test@example.test", "US", now).isEmpty()) + } + assertEquals(mapOf(game to "gamepass"), XboxCatalog.access( + withMembership(envelope(row(game, plan), row(plan))), "test@example.test", "US", now)) + for ((key, value) in listOf("status" to "Expired", "isTrial" to true, "special" to true, + "sharingSource" to "Family", "endDate" to now.toString())) { + for (rows in listOf(arrayOf(row(game, plan).put(key, value)), arrayOf(row(game, plan), row(plan).put(key, value)))) { + assertTrue(XboxCatalog.access(withMembership(envelope(*rows), membership()), "test@example.test", "US", now).isEmpty()) + } + } + } + + @Test fun malformedMembershipFailsTheRefreshInsteadOfBecomingAnEmptySuccessfulLibrary() { + for (json in listOf( + withMembership(envelope(row(game, plan)), membership().put("endDate", "invalid")), + withMembership(envelope(row(game, plan)), membership(), membership()), + withMembership(envelope(row(game, plan)), membership().put("productId", game)), + envelope(row(game, plan)).put("subscriptions", JSONObject.NULL), + )) { + assertThrows(Exception::class.java) { XboxCatalog.access(json, "test@example.test", "US", now) } + } + } + + @Test fun membershipCannotCrossAccountMarketOrFreshnessBoundaries() { + for ((key, value) in listOf("account" to "other@example.test", "market" to "GB", "checkedAt" to "2020-01-01T00:00:00Z")) { + val json = withMembership(envelope(row(game, plan)).put(key, value), membership()) + assertThrows(IllegalArgumentException::class.java) { XboxCatalog.access(json, "test@example.test", "US", now) } + } + } + + @Test fun libraryDiagnosticsContainCountsWithoutAccountOrProductIdentifiers() { + val lines = mutableListOf() + XboxCatalog.access(envelope(row(game), row(parent, plan)), "test@example.test", "US", now, lines::add) + assertEquals(listOf("library entitlements=2 invalid=0 restricted=0 unverified-plan=1 owned=1 gamepass=0"), lines) + assertFalse(lines.single().contains(game) || lines.single().contains(parent) || lines.single().contains("@")) + } @Test fun purchasedAndSubscriptionAccessRemainDistinct() { assertEquals(mapOf(game to "owned", parent to "gamepass"), access(row(game), row(parent, plan), row(plan))) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/ComponentsPageProfileTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/ComponentsPageProfileTest.kt index e01d884da5..501438788e 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/ComponentsPageProfileTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/ComponentsPageProfileTest.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.ui +import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import com.droiddeck.launcher.R @@ -15,9 +16,59 @@ import org.robolectric.annotation.Config @Config(sdk = [28]) class ComponentsPageProfileTest { @get:Rule val compose = createRobolectricComposeRule() + private val gameA = Library.SteamGame(42, "Game A", null, "internal") + private val gameB = Library.SteamGame(43, "Game B", null, "internal") @Test fun gameProfilesCoexistWithTheDefaultComponentStack() { val context = RuntimeEnvironment.getApplication() + show() + val stackHeading = context.getString(R.string.comp_this_proton).uppercase() + compose.onNodeWithText(stackHeading).assertExists() + compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick() + compose.onNodeWithText("Game A").performClick() + compose.onNodeWithText(context.getString(R.string.comp_game_hint)).assertExists() + compose.onNodeWithText(stackHeading).assertDoesNotExist() + + compose.onNodeWithText("Game A").performClick() + compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick() + compose.onNodeWithText(stackHeading).assertExists() + } + + @Test fun opensTheRequestedGameProfileAndAllowsSwitchingToDefault() { + val context = RuntimeEnvironment.getApplication() + show { gameB.profileKey } + compose.onNodeWithText("Game B").assertExists() + compose.onNodeWithText(context.getString(R.string.comp_game_hint)).assertExists() + compose.onNodeWithText(context.getString(R.string.comp_this_proton).uppercase()).assertDoesNotExist() + + compose.onNodeWithText("Game B").performClick() + compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick() + compose.onNodeWithText(context.getString(R.string.comp_this_proton).uppercase()).assertExists() + } + + @Test fun aNewNavigationTargetReplacesThePreviousProfile() { + val context = RuntimeEnvironment.getApplication() + val target = mutableStateOf(gameA.profileKey) + show { target.value } + compose.onNodeWithText("Game A").assertExists() + + compose.runOnIdle { target.value = gameB.profileKey } + compose.onNodeWithText("Game B").assertExists() + compose.onNodeWithText("Game A").assertDoesNotExist() + + compose.runOnIdle { target.value = null } + compose.onNodeWithText(context.getString(R.string.comp_scope_general)).assertExists() + compose.onNodeWithText(context.getString(R.string.comp_this_proton).uppercase()).assertExists() + } + + @Test fun anUnavailableGameFallsBackToTheDefaultProfile() { + val context = RuntimeEnvironment.getApplication() + show { "missing-game" } + compose.onNodeWithText(context.getString(R.string.comp_scope_general)).assertExists() + compose.onNodeWithText(context.getString(R.string.comp_this_proton).uppercase()).assertExists() + } + + private fun show(initialGameKey: () -> String? = { null }) { compose.setContent { DroidDeckTheme { ComponentsPage( @@ -40,20 +91,11 @@ class ComponentsPageProfileTest { onRefresh = {}, onImport = {}, onBack = {}, - games = listOf(Library.SteamGame(42, "Game A", null, "internal")), + games = listOf(gameA, gameB), + initialGameKey = initialGameKey(), requestInitialFocus = false, ) } } - val stackHeading = context.getString(R.string.comp_this_proton).uppercase() - compose.onNodeWithText(stackHeading).assertExists() - compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick() - compose.onNodeWithText("Game A").performClick() - compose.onNodeWithText(context.getString(R.string.comp_game_hint)).assertExists() - compose.onNodeWithText(stackHeading).assertDoesNotExist() - - compose.onNodeWithText("Game A").performClick() - compose.onNodeWithText(context.getString(R.string.comp_scope_general)).performClick() - compose.onNodeWithText(stackHeading).assertExists() } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LaunchSettingsComponentsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LaunchSettingsComponentsTest.kt new file mode 100644 index 0000000000..37544588f3 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/LaunchSettingsComponentsTest.kt @@ -0,0 +1,78 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import com.droiddeck.launcher.R +import com.droiddeck.launcher.frontend.Library +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class LaunchSettingsComponentsTest { + @get:Rule val compose = createRobolectricComposeRule() + private var openedGame: Library.SteamGame? = null + private var defaultOpens = 0 + + @Test fun gameComponentsCardPassesItsGameInsteadOfOpeningDefault() { + val game = Library.SteamGame(42, "Game A", null, "internal") + show(game) + clickComponents() + assertEquals(game, openedGame) + assertEquals(0, defaultOpens) + } + + @Test fun addedGameComponentsCardPreservesItsUnsignedProfileKey() { + val game = Library.SteamGame(-42, "Added game", null, Library.ADDED) + show(game) + clickComponents() + assertEquals(game.profileKey, openedGame?.profileKey) + assertEquals("4294967254", openedGame?.profileKey) + assertEquals(0, defaultOpens) + } + + @Test fun generalComponentsCardStillOpensDefault() { + show(null) + clickComponents() + assertNull(openedGame) + assertEquals(1, defaultOpens) + } + + private fun clickComponents() { + compose.onNodeWithText(RuntimeEnvironment.getApplication().getString(R.string.setup_card_components)).performClick() + compose.waitForIdle() + } + + private fun show(game: Library.SteamGame?) { + compose.setContent { + DroidDeckTheme { + LaunchSettings( + FrontEndState( + installed = null, ready = false, available = null, busy = false, stage = "", percent = -1, + desktopInstalled = false, offlineAccount = null, offline = false, frameGenLabel = "", + romsDir = null, logsEnabled = false, steamGames = listOfNotNull(game), + emulators = emptyList(), running = null, + ), + FrontEndActions( + onPlay = {}, onPlayDesktopUi = {}, onSteamGame = {}, onDesktop = {}, onEmulator = {}, + onRom = {}, onResume = {}, onSteamSettings = {}, onDesktopSettings = {}, + onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onFrameGenPick = {}, + onImportLossless = {}, onProtons = {}, onComponents = { defaultOpens++ }, + onGameComponents = { openedGame = it }, onPerformance = {}, + onRoms = {}, onFiles = {}, onLogs = {}, onOffline = {}, + onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, + onSetPhantomProcessLimit = { _, _ -> }, + ), + rememberMenuHost(), + game, + ) + } + } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/PrimaryButtonContrastTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/PrimaryButtonContrastTest.kt new file mode 100644 index 0000000000..0b7bf29015 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/PrimaryButtonContrastTest.kt @@ -0,0 +1,39 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.luminance +import org.junit.Assert.assertTrue +import org.junit.Test + +class PrimaryButtonContrastTest { + @Test fun electricTextButtonsRemainReadableOnPageAndDialogSurfaces() { + val palette = Themes.byId(Themes.ELECTRIC) + for (background in listOf(palette.background, palette.surface)) { + assertTrue("Electric text button: ${contrast(palette.primary, background)}", + contrast(palette.primary, background) >= 4.5f) + } + } + + @Test fun normalSizedPrimaryTextMeetsContrastAcrossEveryThemeGradient() { + for (palette in Themes.all) { + for (step in 0..100) { + val fraction = step / 100f + val start = palette.primary + val end = palette.primary2 + val background = Color( + start.red + (end.red - start.red) * fraction, + start.green + (end.green - start.green) * fraction, + start.blue + (end.blue - start.blue) * fraction, + ) + val ratio = contrast(palette.onPrimary, background) + assertTrue("${palette.id} gradient $step: $ratio", ratio >= 4.5f) + } + } + } + + private fun contrast(a: Color, b: Color): Float { + val light = maxOf(a.luminance(), b.luminance()) + val dark = minOf(a.luminance(), b.luminance()) + return (light + 0.05f) / (dark + 0.05f) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/PrimaryButtonFocusContrastTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/PrimaryButtonFocusContrastTest.kt new file mode 100644 index 0000000000..51da840cb2 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/PrimaryButtonFocusContrastTest.kt @@ -0,0 +1,46 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.remember +import androidx.compose.ui.platform.LocalView +import androidx.compose.ui.semantics.SemanticsActions +import androidx.compose.ui.test.assertIsFocused +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performSemanticsAction +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.robolectric.RobolectricTestRunner +import org.robolectric.annotation.Config + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28]) +class PrimaryButtonFocusContrastTest { + @get:Rule val compose = createRobolectricComposeRule() + + @Test fun focusedPrimaryButtonDoesNotClaimAColorOverlayAboveItsLabel() { + lateinit var glide: FocusGlide + var clicks = 0 + compose.setContent { + val view = LocalView.current + glide = remember(view) { FocusGlide(view) } + DroidDeckTheme(Themes.ELECTRIC) { + CompositionLocalProvider(LocalFocusGlide provides glide) { + PrimaryButton("Play") { clicks++ } + } + } + } + val button = compose.onNodeWithText("Play") + button.performSemanticsAction(SemanticsActions.RequestFocus) + button.assertIsFocused() + compose.runOnIdle { assertNull(glide.current) } + button.performClick() + compose.runOnIdle { + assertEquals(1, clicks) + assertNull(glide.current) + } + } +} diff --git a/docs/agent-control.md b/docs/agent-control.md index 3407d77bab..98cf552e32 100644 --- a/docs/agent-control.md +++ b/docs/agent-control.md @@ -328,8 +328,8 @@ Neither stabilization nor prediction refreshes camera timestamps or creates gest Each session writes `events.jsonl` beside its other artifacts: the lifecycle (`session.created`, `compositor.started`, `guest.exited`, ...) plus `agent.ready` (the guest agent is up), -`focus.changed` (the focused app, focusable apps or base-layer order changed) and -`agent.launch_requested`. +`focus.changed` (the focused app, focusable apps or base-layer order changed), +`keyboard.changed` (Steam's on-screen keyboard opened or closed) and `agent.launch_requested`. ## UI test tags diff --git a/docs/development/boot-movies.md b/docs/development/boot-movies.md new file mode 100644 index 0000000000..1fa2dd04b3 --- /dev/null +++ b/docs/development/boot-movies.md @@ -0,0 +1,38 @@ +# Boot movies + +Settings → Boot movie has four tabs. + +- **Installed**: "Browse" lists every movie Steam can play: DroidDeck's two, plus every `.webm` in Steam's + `config/uioverrides/movies` folder (imported, installed from SteamDeckRepo, or put there by Steam). The list is re-read + every two seconds, so a movie picked or removed inside Steam shows up, and a movie picked inside Steam becomes the choice. +- **Import**: the same importer as before (copy, remux or on-device transcode to VP8/Opus). The result is written into + Steam's movies folder, so Steam lists it as well. +- **SteamDeckRepo**: browses `https://steamdeckrepo.com/api/posts` (`sort`, `device`, `search`, `page`; 12 posts a page). + Installing downloads the movie through the site's own download address and imports it like any other movie. Tapping a + thumbnail plays the movie from the site (`MediaPlayer` on a `TextureView`) before it is installed. The site does not + say how many pages there are, so the last page is found by asking for pages until one comes back empty or short; the + pager shows the current page (tap it to type another), three pages either side, the first and last page numbers, and + Previous and Next. Search and "go to page" use a small dialog with the app's native text field (`AdbTextField`), + because that field is what brings up the Android keyboard in these screens. +- **Sound**: sound on/off, volume, and how many seconds of the movie play. Anything other than full volume and the whole + movie is built into `files/boot-movie/variants` (audio re-encoded as Opus, video copied) and staged instead. + +Imported and installed movies are kept in `files/boot-movie/library` (with their list, `files/boot-movie/movies.json`) and +copied into Steam's movies folder, so resetting the Linux runtime does not lose them; the copy is put back when it is +missing. The list is changed under one lock, so imports at the same time cannot overwrite each other. Every movie in Steam's custom movies +folder (`config/uioverrides/movies`) can be removed after a confirmation, whether DroidDeck put it there or it was added by +hand or by Steam's own picker. Steam's own three startup movies (`deck_startup`, `oled_startup`, `startup_machine` in +`steamui/movies`) and points shop movies (any other `.webm` below Steam's `config`, `userdata`, `appcache` and `steamui` +folders, plus whatever path `StartupMovie.LocalPath` names) are listed as Steam movies, adopted when picked in Steam, and +never deleted. Bought movies live in `config/communityitemscache/startupmovies/_.webm`; their titles +come from the `GetStartupMovies` list in `userdata//config/localconfig.vdf`. Other videos in `steamui/movies` are not startup movies and are not listed. +Only one processed copy (volume or length change) is kept in `files/boot-movie/variants`; a volume that cannot be applied +plays without sound rather than louder, and plays nothing if that fails too. Covers are cached in `files/boot-movie/thumbs`. Steam reads its startup movie from the `StartupMovie` section inside the `Customization` section of +`config/config.vdf` (`MovieID`, and `LocalPath` relative to `config`; a Points Shop movie has its item number as +`MovieID`). The `StartupMovie` section under `Software/Valve/Steam` is where older clients read it, and DroidDeck writes both. +Selecting a movie here sets `bootMovieApplyNext`, so the next session stages the movie as `bigpicture_startup.webm` and +points both sections at it, over a movie Steam had picked; otherwise a movie picked in Steam is left alone and taken over as +the choice here without being staged over Steam's own setting. Settings > Boot movie > Installed has a report button that +writes what Steam and DroidDeck know to `Download/DroidDeck/boot-movie-report.txt`; it only shows while Debugging tools is on. +A movie larger than 1920x1080 (4K and the like) is never copied or remuxed as it is: import and staging always convert it +(the converter scales to at most 1280x720), because such movies have made Steam crash while it starts. diff --git a/docs/development/game-environment.md b/docs/development/game-environment.md index 2bbf28c786..a6e02b8e27 100644 --- a/docs/development/game-environment.md +++ b/docs/development/game-environment.md @@ -10,7 +10,9 @@ Changes apply on the next game launch, including when Steam is already running. A running game must be restarted. Native Linux games and Steam itself are outside this editor's scope. -The Components page also has a **Configuration** dropdown. **Default profile** owns the +Opening **Components** from a game's launch settings selects that game's profile. +Opening Components from the navigation rail selects **Default profile**. Use the +**Configuration** dropdown to switch profiles explicitly. **Default profile** owns the default Proton and FEX preset. An installed game can inherit those defaults or choose its own Proton and FEX preset. Proton choices are applied through Steam's per-app compatibility mapping, including while Steam is running when its live diff --git a/docs/development/luma-hand-tracking-investigation.md b/docs/development/luma-hand-tracking-investigation.md index 6fa8b32ae8..bbe66e7dda 100644 --- a/docs/development/luma-hand-tracking-investigation.md +++ b/docs/development/luma-hand-tracking-investigation.md @@ -106,7 +106,7 @@ The optional Lite bundle can be rebuilt with `mediapipe==0.10.21` using: python tools/build_hand_lite.py --palm palm_detection_lite.tflite --lite hand_landmark_lite.tflite ``` -Source URLs and hashes are in `app/src/main/assets/models/hand_landmarker_lite.provenance.json`. +Source URLs and hashes are in `tools/packs/tracking/hand_landmarker_lite.provenance.json`. These changes still need live moving-hand, closed-fist, gesture-continuity, and latency validation. Earlier Lite/normalized-input validation passed 52 focused JVM tests, and bundle rebuild and label-archive reproducibility checks passed. Desktop MediaPipe 0.10.21 inference succeeded on color hand fixtures. All six diff --git a/docs/development/luma-spatial-tracking.md b/docs/development/luma-spatial-tracking.md index 26ecaf00fc..b80104fb3e 100644 --- a/docs/development/luma-spatial-tracking.md +++ b/docs/development/luma-spatial-tracking.md @@ -13,7 +13,7 @@ The base enables experimental hand tracking without requiring every user to repe Use the existing optional `droiddeck.vitureSdk` local property with the external VITURE Android SDK 2.4.0. No vendor headers or libraries are checked into the repository. `-PvitureSdkDir=` explicitly builds without the SDK. The ordinary runtime freshness checks remain enabled. Rebuild the ARM64 VR components with `tools/vr/build_windows.py`; its manifest includes `spatialpose_shm.h`. -The hand pipeline pins MediaPipe Tasks Vision 1.0.0, OpenCV 4.13.0, and the model and SHA-256 recorded in `app/src/main/assets/models/hand_landmarker.provenance.json`. Both Gradle and the inference worker verify the model checksum. CPU inference, the full model, concurrent camera inference, scheduled hand discovery, and automatic input-rate adjustment are the defaults, including after app restarts, reconnects, and provider restarts. **Show diagnostics → GPU hand inference** temporarily enables GPU until the next tracking restart; GPU remains experimental because SteamVR restarts and Vulkan device loss were observed during testing. Diagnostics report the selection as `handGpuEnabled` and the initialized detectors as `handInferenceBackend`; `not initialized` means detector startup has not completed. Sustained performance acceptance remains unresolved. +The hand pipeline pins MediaPipe Tasks Vision 1.0.0, OpenCV 4.13.0, and the model and SHA-256 recorded in `tools/packs/tracking/hand_landmarker.provenance.json`. The model, OpenCV and MediaPipe native libraries are downloaded on first use as the tracking pack (`tools/packs`); the pack build and the inference worker verify the model checksum. CPU inference, the full model, concurrent camera inference, scheduled hand discovery, and automatic input-rate adjustment are the defaults, including after app restarts, reconnects, and provider restarts. **Show diagnostics → GPU hand inference** temporarily enables GPU until the next tracking restart; GPU remains experimental because SteamVR restarts and Vulkan device loss were observed during testing. Diagnostics report the selection as `handGpuEnabled` and the initialized detectors as `handInferenceBackend`; `not initialized` means detector startup has not completed. Sustained performance acceptance remains unresolved. Hand input starts by copying 500 permille of stereo callbacks, approximately 12.5 pairs per second at the SDK's documented 25 Hz camera rate. On CPU, automatic adjustment can raise this to 600 or 800 permille (about 15 or 20 Hz) only after eight consecutive valid observations have sufficient processing and freshness headroom. Promotion requires average processing at most 55 ms and observation age at most 110 ms for 15 Hz, then at most 40 ms and 90 ms for 20 Hz. A moving average allows occasional scheduled discovery frames while preserving a sustained processing budget. An average above the selected period reduces the rate; any single processing cost of 80 ms or observation age of 140 ms immediately returns it to 500 permille. Tracking failure and detector resets also return it to 500. This policy requests more input only when processing can accommodate it; it does not guarantee that many completed or valid hand updates. diff --git a/docs/third-party/handtracking/README.md b/docs/third-party/handtracking/README.md index 10107a197f..d6aa30ec7b 100644 --- a/docs/third-party/handtracking/README.md +++ b/docs/third-party/handtracking/README.md @@ -2,13 +2,18 @@ ## Included +None of these files ship in the APK. The app downloads them on first use as one tracking pack +(`tracking.tar.zst`), built in CI by `tools/packs/build.sh` from the pinned sources +below, together with `libopencv_java4.so` and `libmediapipe_tasks_jni.so` taken unchanged from +the OpenCV and MediaPipe Maven AARs. + [MediaPipe](https://github.com/google-ai-edge/mediapipe) Tasks Vision 1.0.0 (`com.google.mediapipe:tasks-vision`, shared with the Luma stereo tracking pipeline; copyright Google LLC and the MediaPipe authors, Apache License 2.0, `LICENSE_MEDIAPIPE` here) finds the player's body in each camera frame. It comes from Maven Central with its dependencies (Guava, Flogger, protobuf-javalite and Google's `datatransport`), all Apache-2.0. -`app/src/main/assets/handtracking/pose_landmarker_lite.task` is MediaPipe's Pose Landmarker (Lite) +`pose_landmarker_lite.task` in the tracking pack (below) is MediaPipe's Pose Landmarker (Lite) model, BlazePose GHUM 3D, unchanged from `https://storage.googleapis.com/mediapipe-models/pose_landmarker/pose_landmarker_lite/float16/1/pose_landmarker_lite.task` (SHA-256 `59929e1d1ee95287735ddd833b19cf4ac46d29bc7afddbbf6753c459690d574a`). Its @@ -16,7 +21,7 @@ model, BlazePose GHUM 3D, unchanged from licenses it under the Apache License 2.0 and lists its limits: one person, up to about 4 metres from the camera, the head in view, and depth that is approximate rather than metric. -`app/src/main/assets/handtracking/hand_landmarker.task` is MediaPipe's Hand Landmarker (full) model +`hand_landmarker.task` in the tracking pack is MediaPipe's Hand Landmarker (full) model bundle, a palm detector and a hand landmark model, unchanged from `https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task` (SHA-256 `fbc2a30080c3c557093b5ddfc334698132eb341044ccee322ccf8bcf3607cde1`). Its @@ -24,14 +29,13 @@ bundle, a palm detector and a hand landmark model, unchanged from licenses it under the Apache License 2.0; it gives 21 landmarks per hand in the picture and in metres, based on the GHUM hand model, and is meant for prominently shown hands. -The Luma stereo pipeline defaults to the Full bundle at -`app/src/main/assets/models/hand_landmarker.task`, with the same checksum as the Full bundle -above. The optional `app/src/main/assets/models/hand_landmarker_lite.task` is built from +The Luma stereo pipeline defaults to the same Full bundle. The optional +`hand_landmarker_lite.task` is built from the official `palm_detection_lite.tflite` and `hand_landmark_lite.tflite` assets at `https://storage.googleapis.com/mediapipe-assets/`. It uses the matching tensor metadata and associated labels from the Full task bundle. These models share the MediaPipe hand tracking model card and Apache License 2.0. Source checksums and the generated bundle checksum are in -`app/src/main/assets/models/hand_landmarker_lite.provenance.json`; `tools/build_hand_lite.py` +`tools/packs/tracking/hand_landmarker_lite.provenance.json`; `tools/build_hand_lite.py` reproduces the bundle with MediaPipe 0.10.21 metadata tooling. [CameraX](https://developer.android.com/jetpack/androidx/releases/camera) 1.4.2 diff --git a/tools/build_hand_lite.py b/tools/build_hand_lite.py index 0b5c91b55c..920b83bfa5 100644 --- a/tools/build_hand_lite.py +++ b/tools/build_hand_lite.py @@ -61,9 +61,9 @@ def build(full, lite, palm, output): if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument('--full', type=Path, default=Path('app/src/main/assets/models/hand_landmarker.task')) + parser.add_argument('--full', type=Path, required=True) parser.add_argument('--lite', type=Path, required=True, help='Pinned hand_landmark_lite.tflite from storage.googleapis.com/mediapipe-assets/') parser.add_argument('--palm', type=Path, required=True, help='Pinned palm_detection_lite.tflite from storage.googleapis.com/mediapipe-assets/') - parser.add_argument('--output', type=Path, default=Path('app/src/main/assets/models/hand_landmarker_lite.task')) + parser.add_argument('--output', type=Path, required=True) args = parser.parse_args() build(args.full, args.lite, args.palm, args.output) diff --git a/tools/build_local.sh b/tools/build_local.sh index e03c49befb..9f6026ab7d 100755 --- a/tools/build_local.sh +++ b/tools/build_local.sh @@ -364,6 +364,7 @@ if ! restore_step comet "${comet_key}" "${comet_out}"; then DROIDDECK_BUILD_IMAGE="${image_name}" bash tools/comet/build-local.sh save_step comet "${comet_key}" "${comet_out}" fi +bash tools/packs/build.sh app/build/packs python3 tools/release/runtime_inputs.py record ./gradlew "${gradle_task}" --console=plain -PndkVersion="${ndk_version}" ${gradle_rust_arg} python3 tools/release/check_session_assets.py "app/build/outputs/apk/${build_variant}/app-${build_variant}.apk" diff --git a/tools/directaudio/sink/module-directaudio-native-sink.c b/tools/directaudio/sink/module-directaudio-native-sink.c index 208dac9ac5..ca3eb01cc5 100644 --- a/tools/directaudio/sink/module-directaudio-native-sink.c +++ b/tools/directaudio/sink/module-directaudio-native-sink.c @@ -126,6 +126,7 @@ struct userdata { unsigned int decay_backoff, cb_count, wd_last_cb; int reopen_running, reopen_redo; int consuming, primed, starved; + int suspended; volatile int dead; /* what the IO thread last logged, so engine changes made on the AAudio thread get a line */ @@ -302,6 +303,7 @@ static void out_error_cb(AAudioStream *aq, void *user, aaudio_result_t error) { struct userdata *u = user; if (aq != __atomic_load_n(&u->aq, __ATOMIC_SEQ_CST)) return; + if (__atomic_load_n(&u->suspended, __ATOMIC_SEQ_CST)) return; /* A disconnected stream (headphones plugged or unplugged, a Bluetooth route coming or going) * can never be restarted: it has to be closed and a new one opened on the current route. */ if (error != AAUDIO_ERROR_DISCONNECTED && @@ -400,6 +402,8 @@ static void *reopen_thread(void *user) { pthread_mutex_lock(&u->lock); old = u->aq; __atomic_store_n(&u->aq, neu, __ATOMIC_SEQ_CST); + if (__atomic_load_n(&u->suspended, __ATOMIC_SEQ_CST)) + AAudioStream_requestStop(neu); pthread_mutex_unlock(&u->lock); } else pa_log("directaudio-native-sink: reopen failed; keeping the old stream"); @@ -575,6 +579,34 @@ static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offse return pa_sink_process_msg(o, code, data, offset, chunk); } +/* A started AAudio stream keeps audioserver's AudioMix wake lock held, so the device never + * suspends while the session sleeps: stop it, and the IO thread's timer, until the sink reopens. */ +static int sink_set_state_in_io_thread_cb(pa_sink *s, pa_sink_state_t new_state, pa_suspend_cause_t new_suspend_cause) { + struct userdata *u = s->userdata; + aaudio_result_t res = AAUDIO_OK; + + if (new_state == PA_SINK_SUSPENDED && !u->suspended) { + pthread_mutex_lock(&u->lock); + __atomic_store_n(&u->suspended, 1, __ATOMIC_SEQ_CST); + if (u->aq) AAudioStream_requestStop(u->aq); + pthread_mutex_unlock(&u->lock); + pa_rtpoll_set_timer_disabled(u->rtpoll); + pa_log("directaudio-native-sink: suspended; output stopped"); + } else if (PA_SINK_IS_OPENED(new_state) && u->suspended) { + pthread_mutex_lock(&u->lock); + __atomic_store_n(&u->suspended, 0, __ATOMIC_SEQ_CST); + u->primed = 0; + __atomic_store_n(&u->last_cb_ns, now_ns(), __ATOMIC_SEQ_CST); + u->wd_last_tick_ns = 0; + if (u->aq) res = AAudioStream_requestStart(u->aq); + pthread_mutex_unlock(&u->lock); + if (res != AAUDIO_OK || !u->aq) request_reopen(u, "resume"); + pa_rtpoll_set_timer_relative(u->rtpoll, 0); + pa_log("directaudio-native-sink: resumed"); + } + return 0; +} + static void thread_func(void *userdata) { struct userdata *u = userdata; @@ -592,8 +624,10 @@ static void thread_func(void *userdata) { /* Half a burst between visits, never blocking on the stream: clients' audio reaches this * thread as messages pa_rtpoll_run handles, and a thread stuck in a write or a wait lets * them run dry (the crackle #338 fixed). */ - service_ring(u); - pa_rtpoll_set_timer_relative(u->rtpoll, PA_MAX(frames_to_usec(u, u->burst) / 2, PA_USEC_PER_MSEC)); + if (!u->suspended) { + service_ring(u); + pa_rtpoll_set_timer_relative(u->rtpoll, PA_MAX(frames_to_usec(u, u->burst) / 2, PA_USEC_PER_MSEC)); + } if ((ret = pa_rtpoll_run(u->rtpoll)) < 0) goto fail; @@ -727,6 +761,7 @@ int pa__init(pa_module *m) { goto fail; } u->sink->parent.process_msg = sink_process_msg; + u->sink->set_state_in_io_thread = sink_set_state_in_io_thread_cb; u->sink->userdata = u; pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq); pa_sink_set_rtpoll(u->sink, u->rtpoll); diff --git a/tools/linuxfs/check-preloads.sh b/tools/linuxfs/check-preloads.sh index 78021c4404..30f94a96a6 100644 --- a/tools/linuxfs/check-preloads.sh +++ b/tools/linuxfs/check-preloads.sh @@ -9,7 +9,7 @@ for bad in libstdc++.so.6 libgcc_s.so.1; do done syms() { "${READELF:-readelf}" -Ws "$1" | awk '$4 == "FUNC" && $5 == "GLOBAL" {sub(/@.*/, "", $8); print $8}'; } FAKE=$(syms "$D/libfakeinput.so") -for sym in open openat ioctl read close poll ppoll select stat fstat access scandir; do +for sym in open openat ioctl read readv close poll ppoll select stat fstat access scandir; do grep -qx "$sym" <<<"$FAKE" || { echo "::error::libfakeinput.so does not export $sym"; exit 1; } done if grep -qxE '__gxx_personality_v0|__cxa_throw|_Unwind_Resume' <<<"$FAKE"; then diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent index 255d3f2555..47d2d62fef 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent @@ -23,6 +23,7 @@ import json import math import re import os +import select import selectors import signal import socket @@ -532,6 +533,111 @@ def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15) ws.close() +KEYBOARD_BINDING = "droiddeckSteamKeyboard" +KEYBOARD_CHECK_SECONDS = 30 +KEYBOARD_JS = r""" +(() => { + const self = window.__droiddeckKeyboard || (window.__droiddeckKeyboard = { watched: new WeakSet(), last: null }); + self.check = () => { + let showing = false; + for (const win of Array.from(globalThis.SteamUIStore?.WindowStore?.SteamUIWindows || [])) { + const value = win?.VirtualKeyboardManager?.IsShowingVirtualKeyboard; + if (!value) continue; + if (!self.watched.has(value) && typeof value.Subscribe === "function") { + self.watched.add(value); + value.Subscribe(() => setTimeout(() => self.check())); + } + if (value.m_currentValue === true) showing = true; + } + if (showing !== self.last) { + self.last = showing; + if (typeof window.__BINDING__ === "function") window.__BINDING__(String(showing)); + } + return showing; + }; + self.timer = self.timer || setInterval(() => self.check(), 500); + return self.check(); +})() +""".replace("__BINDING__", KEYBOARD_BINDING) + + +class KeyboardWatcher(threading.Thread): + def __init__(self, agent_dir): + super().__init__(daemon=True, name="keyboard") + self.agent_dir = agent_dir + self.path = agent_dir / "keyboard.json" + self.showing = None + self.seq = 0 + self.next_id = 0 + self.attached = False + + def report(self, showing): + if showing == self.showing: + return + self.showing = showing + self.seq += 1 + write_json(self.path, {"steamKeyboard": showing, "seq": self.seq}) + + def run(self): + failures, last = 0, None + while True: + try: + self.watch() + except Exception as e: + if self.attached: + log("Steam keyboard: lost the client (%s); reattaching" % e) + failures = 0 + elif str(e) != last: + log("Steam keyboard: waiting for the client (%s)" % e) + self.attached = False + last = str(e) + self.report(False) + failures += 1 + time.sleep(min(2 * failures, 10)) + + def watch(self): + targets = [t for t in cdp_targets(self.agent_dir) + if t.get("title") == "SharedJSContext" and t.get("webSocketDebuggerUrl")] + if not targets: + raise AgentError("NO_TARGET", "No SharedJSContext yet") + ws = WebSocket(targets[0]["webSocketDebuggerUrl"], 5) + try: + self.call(ws, "Runtime.addBinding", {"name": KEYBOARD_BINDING}) + self.report(self.install(ws)) + self.attached = True + while True: + if not ws.buffer and not select.select([ws.s], [], [], KEYBOARD_CHECK_SECONDS)[0]: + self.report(self.install(ws)) + continue + self.event(json.loads(ws.recv())) + finally: + ws.close() + + def install(self, ws): + result = self.call(ws, "Runtime.evaluate", {"expression": KEYBOARD_JS, "returnByValue": True}) + if result.get("exceptionDetails"): + raise AgentError("JS_EXCEPTION", json.dumps(result["exceptionDetails"])[:500]) + return result.get("result", {}).get("value") is True + + def call(self, ws, method, params): + self.next_id += 1 + ws.send(json.dumps({"id": self.next_id, "method": method, "params": params})) + deadline = time.monotonic() + 10 + while time.monotonic() < deadline: + message = json.loads(ws.recv()) + if message.get("id") == self.next_id: + if "error" in message: + raise AgentError("CDP_ERROR", json.dumps(message["error"])) + return message.get("result", {}) + self.event(message) + raise AgentError("TIMEOUT", "No answer to %s from DevTools" % method) + + def event(self, message): + params = message.get("params") or {} + if message.get("method") == "Runtime.bindingCalled" and params.get("name") == KEYBOARD_BINDING: + self.report(params.get("payload") == "true") + + def steam_idle_inhibit(agent_dir, inhibit): expression = """(async want => { const toggle = () => new Promise(done => { @@ -918,6 +1024,8 @@ def serve(agent_dir, focus=True, poll=0.1): can_focus = focus and bool(os.environ.get("DISPLAY")) if can_focus: FocusWatcher(agent_dir / "focus.json").start() + if focus: + KeyboardWatcher(agent_dir).start() write_json(agent_dir / "hello.json", {"pid": os.getpid(), "version": VERSION, "started": int(time.time() * 1000), "displays": displays(), "focus": can_focus}) log("serving %s (focus %s)" % (agent_dir, "on" if can_focus else "off")) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-bwrap b/tools/linuxfs/overlay/usr/local/bin/droiddeck-bwrap index 909056fcd5..2e84a695c2 100644 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-bwrap +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-bwrap @@ -7,7 +7,21 @@ import socket import struct import sys -SOCKET = "\0" + os.environ.get("DROIDDECK_BWRAP_SOCKET", "com.droiddeck.launcher.bwrap") +SOCKET_FILE = "/etc/droiddeck/bwrap-socket" + + +def socket_name(): + name = os.environ.get("DROIDDECK_BWRAP_SOCKET", "") + if not name: + try: + with open(SOCKET_FILE, encoding="utf-8") as f: + name = f.read().strip() + except OSError: + pass + return "\0" + (name or "com.droiddeck.launcher.bwrap") + + +SOCKET = socket_name() VERSION = "bubblewrap 0.11.0 (droiddeck)" NO_ARG = { diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex index aa0db0fd3c..331dcfecc2 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex @@ -674,6 +674,7 @@ def launch(command, env, mode, decide=None): def game_environment(env): try: game_env = runpy.run_path(os.path.join(BIN_DIR, "droiddeck-game-env")) + env = game_env["game_gpu"](env) app = game_env["game_id"](env) or env.get("SteamAppId") or env.get("SteamGameId") if not app: return env diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env index a7fa3a0835..827ad60e85 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env @@ -7,6 +7,7 @@ import subprocess import sys from pathlib import Path +GAME_TU_DEBUG = "DROIDDECK_GAME_TU_DEBUG" SYNC_KEYS = ("BL_SYNC", "BL_SYNC_FALLBACK", "BL_FSYNC_FIRST", "BL_SYNC_MIN_NOFILE", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC") SEED_REDISTS = "/usr/local/bin/droiddeck-seed-redists" PACK_KEYS = ("WINESERVER", "BL_SYNC_PACK", "WINEESYNC", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC") @@ -125,6 +126,35 @@ def skip_red_launcher(command): return command +def offline_without_anticheat(command, env): + """Start the configured game executable when the player opts into launching without EAC.""" + if (env.get("DROIDDECK_ANTICHEAT_OFFLINE") != "1" or len(command) <= 2 + or command[1] != "waitforexitandrun" + or not re.fullmatch(r"start_protected_game(?:_?x64|_?64)?\.exe", + os.path.basename(command[2]), re.IGNORECASE)): + return command + folder = os.path.dirname(command[2]) + try: + with open(os.path.join(folder, "EasyAntiCheat", "settings.json"), encoding="utf-8-sig") as source: + executable = json.load(source).get("executable") + except (OSError, ValueError, AttributeError): + return command + if not isinstance(executable, str) or not executable: + return command + relative = os.path.normpath(executable.replace("\\", "/")) + game = os.path.join(folder, relative) + if os.path.isabs(relative) or relative.startswith("..") or not os.path.isfile(game): + return command + # Resolve symlinks before accepting an executable inside the game directory. + root = os.path.realpath(folder) + if os.path.commonpath((root, os.path.realpath(game))) != root: + return command + if os.path.normcase(os.path.abspath(game)) == os.path.normcase(os.path.abspath(command[2])): + return command + print("droiddeck-game-env: started without Easy Anti-Cheat (offline only)", file=sys.stderr) + return command[:2] + [game] + command[3:] + + def engine_fixes(exe, args): """Environment and extra arguments a game needs because of what it is built with.""" game = Game(exe, args) @@ -153,6 +183,18 @@ def win_components(compat, app_id): return "" +def game_gpu(env): + if GAME_TU_DEBUG not in env: + return env + result = env.copy() + value = result.pop(GAME_TU_DEBUG) + if value: + result["TU_DEBUG"] = value + else: + result.pop("TU_DEBUG", None) + return result + + def apply_config(env, config, app_id, fixes=None): if config.get("version") != 1: raise ValueError("unsupported environment configuration") @@ -283,7 +325,7 @@ def main(): command = sys.argv[1:] if not command: return 2 - env = os.environ.copy() + env = game_gpu(os.environ.copy()) mic_enabled = env.get("BL_MIC_ENABLED") mark_install_scripts(command, env) app_id = game_id(env) @@ -313,6 +355,8 @@ def main(): env = apply_config(env, {"version": 1}, app_id, fixes) except (OSError, ValueError, TypeError, AttributeError): print("droiddeck-game-env: invalid configuration; using inherited environment", file=sys.stderr) + if app_id and len(command) > 1 and command[1] == "waitforexitandrun": + command = offline_without_anticheat(command, env) if mic_enabled == "0": env["BANNER_AUDIO_DIRECT_MIC"] = "0" env = force_ssbs(command, env) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-seed-redists b/tools/linuxfs/overlay/usr/local/bin/droiddeck-seed-redists index a9eaea65c7..a13f6b417f 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-seed-redists +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-seed-redists @@ -188,6 +188,7 @@ present() { awk -F'\t' ' } ' - "$1"; } +regs=() for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/system.reg \ /mnt/droiddeck-sd/steamapps/common/Proton*/files/share/default_pfx*/system.reg \ /root/Games/*/steamapps/common/Proton*/files/share/default_pfx*/system.reg \ @@ -195,8 +196,21 @@ for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/syste "$steam_root"/steamapps/compatdata/*/pfx/system.reg \ /mnt/droiddeck-sd/steamapps/compatdata/*/pfx/system.reg \ /root/Games/*/steamapps/compatdata/*/pfx/system.reg; do - [ -f "$reg" ] || continue + [ -f "$reg" ] && regs+=("$reg") +done +declare -A regid=() +if [ ${#regs[@]} -gt 0 ]; then + while IFS=$'\t' read -r id name; do + regid[$name]=$id + done < <(stat -c $'%i %s %.9Y\t%n' -- "${regs[@]}" 2>/dev/null) +fi + +for reg in "${regs[@]}"; do seeded=${reg%/*}/.droiddeck-redists + checked=${reg%/*}/.droiddeck-redists-checked + id=${regid[$reg]:-} + prev= + [ -f "$checked" ] && read -r prev <"$checked" legacy=${reg%/*}/.bannerlator-redists if [ -f "$legacy" ] && [ ! -f "$seeded" ]; then mv -f "$legacy" "$seeded" @@ -210,12 +224,13 @@ for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/syste if [ -n "${vulkan[$line]:-}" ]; then stale+=("$line"); else kept+=("$line"); fi done if [ ${#stale[@]} -gt 0 ] && unseed "$reg" "${stale[@]}"; then + id= had=() for line in "${kept[@]}"; do had[$line]=1; done printf '%s\n' "${kept[@]}" >"$seeded" echo "== took Vulkan runtime markers out of $reg" fi - if [ ${#had[@]} -gt 0 ]; then + if [ ${#had[@]} -gt 0 ] && { [ -z "$id" ] || [ "$id" != "$prev" ]; }; then declare -A held=() while IFS= read -r line; do [[ $line == *$'\t'* ]] && held[$line]=1; done < <(printf '%s\n' "${!had[@]}" | present "$reg") if [ ${#held[@]} -lt ${#had[@]} ]; then @@ -228,7 +243,11 @@ for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/syste fi missing=() for line in "${want[@]}"; do [ -n "${had[$line]:-}" ] || missing+=("$line"); done - [ ${#missing[@]} -eq 0 ] && continue + if [ ${#missing[@]} -eq 0 ]; then + [ -n "$id" ] && [ "$id" != "$prev" ] && printf '%s\n' "$id" >"$checked" + continue + fi + rm -f "$checked" dated=$(mktemp) || continue touch -r "$reg" "$dated" if printf '%s\n' "$(block_for "${missing[@]}")" >>"$reg"; then diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session index 9b56c76bcf..adfa3ba866 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-session +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-session @@ -4,6 +4,11 @@ export HOME=${HOME:-/root} mode=${1:-desktop} shift || true step() { echo "== STEP $(date -u +%H:%M:%S) $*"; } +steam_setup_failed() { + echo "== steam: the Steam client could not be set up (status $1)" + [ -z "${BL_STEAM_EXIT_FILE:-}" ] || printf '%s\n' "$1" > "$BL_STEAM_EXIT_FILE" + exit "$1" +} if [ -n "${BL_LOG:-}" ] && [ -z "${BL_INSIDE:-}" ]; then mkdir -p "$(dirname "$BL_LOG")" 2>/dev/null if [ "$(stat -c %s "$BL_LOG" 2>/dev/null || echo 0)" -gt 8388608 ]; then @@ -303,6 +308,9 @@ case $mode in taskset -cp "$cores" $$ >/dev/null 2>&1 || true fi python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 || true + if [ -n "${GAMESCOPE_WAYLAND_DISPLAY:-}" ]; then + export WAYLAND_DISPLAY= XDG_SESSION_TYPE=x11 + fi run_program() { local rc=0 child sig forwarded=0 { trap - INT QUIT; exec "$@"; } <&0 & @@ -350,6 +358,12 @@ case $mode in esac ;; steam) + if [ -n "${GAMESCOPE_WAYLAND_DISPLAY:-}" ]; then + export WAYLAND_DISPLAY= XDG_SESSION_TYPE=x11 + fi + export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1 + export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1 + export MOZ_SHM_NO_SEALS=1 steam_x64=0 [ "${BL_STEAM_CLIENT_ARCH:-}" = x86_64 ] && steam_x64=1 steam_cef_gpu=1 @@ -358,10 +372,10 @@ case $mode in # droiddeck-steam-install removes the repair request: read it first so Repair Steam covers both clients. _bl_x64_repair=0 [ -e "$HOME/.bl-steam-repair" ] && _bl_x64_repair=1 - droiddeck-steam-install || exit $? + droiddeck-steam-install || steam_setup_failed $? droiddeck-steam-install --sync steamdeck_publicbeta || step "could not update the arm64 client's parts; the x86-64 client keeps its own web helper" step "checking the x86-64 Steam client (FEX, experimental; the first run downloads ~2 GB)" - BL_X64_REPAIR=$_bl_x64_repair droiddeck-steam-x64 --prepare || exit $? + BL_X64_REPAIR=$_bl_x64_repair droiddeck-steam-x64 --prepare || steam_setup_failed $? step "x86-64 Steam client ready" steam_root=${BL_X64_HOME:-$HOME/.droiddeck-x64}/.local/share/Steam steam_client=(droiddeck-steam-x64 --exec) @@ -371,7 +385,7 @@ case $mode in fi else step "checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)" - droiddeck-steam-install || exit $? + droiddeck-steam-install || steam_setup_failed $? step "Steam client ready" steam_root=$XDG_DATA_HOME/Steam if [ -f "${BL_X64_HOME:-$HOME/.droiddeck-x64}/.local/share/Steam/local.vdf" ]; then diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat index c9c8cb1c2a..7ed1eb71eb 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat @@ -105,7 +105,7 @@ INSTALL_JS = r""" const body = []; uint(1, appid, body); const r = await send("CompatManager.GetCompatTools#1", body); - if (!r.ok) throw new Error("GetCompatTools " + appid + " failed (" + r.eresult + " " + r.error + ")"); + if (!r.ok) throw Object.assign(new Error("GetCompatTools " + appid + " failed (" + r.eresult + " " + r.error + ")"), { eresult: r.eresult }); return { selected: text(r.body, 3), fallback: text(r.body, 4), tools: (r.body[1] || []).map((t) => text(parse(t), 1)) }; }; self.set = async (appid, name) => { @@ -119,7 +119,13 @@ INSTALL_JS = r""" }; self.many = async (apps) => { const out = {}; - for (const app of apps) out[app] = (await self.get(Number(app))).selected; + for (const app of apps) { + try { + out[app] = (await self.get(Number(app))).selected; + } catch (e) { + if (e.eresult !== 128) throw e; + } + } return out; }; window.__droiddeckCompat = self; @@ -555,11 +561,24 @@ class Helper: # "native" from earlier builds also lists dual-platform games nobody chose to run natively. prior_native = state.get("native_choices", ()) native_choices = set(prior_native if isinstance(prior_native, (list, tuple, set)) else ()) + picked = COMPAT["picked_apps"](state) + runnable = {t["name"].lower() for t in live} apps = sorted(set(installed) | set(picks) | set(prior_auto) | native_choices, key=COMPAT["app_order"]) overrides = COMPAT["requested_games"]( COMPAT["game_requests"](), catalog, [t["name"] for t in live]) apps = sorted(set(apps) | set(overrides), key=COMPAT["app_order"]) current = dict(page.compat("many(%s)" % json.dumps(apps)) or {}) + refused = set(apps) - set(current) + refused_native = native_choices & refused + if refused: + apps = [app for app in apps if app not in refused] + installed = [app for app in installed if app not in refused] + picks = [app for app in picks if app not in refused] + prior_auto = {app: tool for app, tool in prior_auto.items() if app not in refused} + if isinstance(state.get("auto"), dict): + state["auto"] = prior_auto + native_choices -= refused + overrides = {app: tool for app, tool in overrides.items() if app not in refused} current["0"] = top["selected"] native = COMPAT["native_targets"](self.steam_root, apps) raw_mapping = COMPAT["read_config_mapping"]( @@ -568,7 +587,7 @@ class Helper: for app in native_choices: current[app] = "" for app in set(native) - native_choices: - if not current.get(app): + if not current.get(app) and app not in picked: current.pop(app, None) else: for app in set(native) | native_choices: @@ -576,7 +595,8 @@ class Helper: # The client shows an explicit native choice as the tool it inherits, and writes config.vdf late. if raw_mapping[app] == "" or current.get(app) not in self.known: current[app] = raw_mapping[app] - elif app in prior_auto or app in native_choices: + elif app in prior_auto or app in native_choices or app in picked and ( + not current.get(app) or COMPAT["unrunnable"](current[app], runnable)): current[app] = "" elif not current.get(app): current.pop(app, None) @@ -590,8 +610,8 @@ class Helper: tool if tool is not None else "Steam native default")) state.update( auto={app: tool for app, tool in auto.items() if tool is not COMPAT["NATIVE_CHOICE"]}, - native_choices=sorted(app for app, tool in auto.items() if tool is COMPAT["NATIVE_CHOICE"]), - tools=catalog, live=True) + native_choices=sorted(refused_native | {app for app, tool in auto.items() if tool is COMPAT["NATIVE_CHOICE"]}), + picked=COMPAT["picked_after"](current, changes), tools=catalog, live=True) state.pop("native", None) if waiting: state["pending"] = wanted diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch b/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch index 48d39813e6..f59c560523 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch @@ -271,6 +271,23 @@ def provision_prefix(compat_data, wait=SERVER_WAIT): return state + (" server-running" if busy else "") +def create_prefix(compat_data, proton, timeout=120): + if not compat_data or not proton or not Path(proton).is_file(): + return "no-proton" + reg = Path(compat_data) / "pfx/user.reg" + if reg.is_file(): + return "present" + try: + Path(compat_data).mkdir(parents=True, exist_ok=True) + subprocess.run([proton, "run", "cmd.exe", "/d", "/c", "exit"], stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout) + except subprocess.TimeoutExpired: + return "timeout" + except OSError: + return "failed" + return "created" if reg.is_file() else "failed" + + CLOUD_TIMEOUT = 15.0 CLOUD_STORES = ("gog", "epic") STORE_GAME = 10 @@ -502,6 +519,10 @@ def main(argv): compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/") prefix_id = os.path.basename(compat_data) if compat_data else "" launch_dir = os.environ.get("BL_LAUNCH_DIR", "") + if launch_dir and cloud_on(sidecar): + made = create_prefix(compat_data, os.environ.get("BL_STORE_PROTON", "")) + if made != "present": + log("cloud %s %s prefix=%s" % (store, game, made)) if store == "gog": prepare_gog(sidecar, compat_data, launch_dir) log("gog registry: " + apply_gog_registry(folder, compat_data, os.environ.get("BL_STORE_PROTON", ""))) diff --git a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility index 67a33b424c..51bf2c287b 100755 --- a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility +++ b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility @@ -1042,6 +1042,16 @@ def plan_mapping(current, installed, runnable, default, auto, native=None, picks return changes, kept +def picked_apps(state): + picked = state.get("picked", ()) + return {app for app in picked if isinstance(app, str)} if isinstance(picked, list) else set() + + +def picked_after(current, changes): + return sorted(({app for app, tool in current.items() if tool} - set(changes) | + {app for app, tool in changes.items() if tool}) - {"0"}, key=app_order) + + def followers(state, current): if "auto" in state: return state["auto"] @@ -1287,6 +1297,8 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non native = native_targets(steam_root, set(apps) | set(picks) | set(managed) | set(native_choices)) if linux_tool != FEX_TOOL: native = {app: linux_tool if tool == FEX_TOOL else tool for app, tool in native.items()} + for app in picked_apps(state) & set(native): + current.setdefault(app, "") changes, auto = plan_mapping( current, apps, names, default, followers(state, current), native, picks, overrides, managed, native_choices) @@ -1297,6 +1309,7 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non write_changed(config_path, text) state["auto"] = {app: tool for app, tool in auto.items() if tool is not NATIVE_CHOICE} state["native_choices"] = sorted(app for app, tool in auto.items() if tool is NATIVE_CHOICE) + state["picked"] = picked_after(current, changes) state.pop("native", None) state["tools"] = catalog state.setdefault("default", default) diff --git a/tools/packs/build.sh b/tools/packs/build.sh new file mode 100755 index 0000000000..d06a4c8fb4 --- /dev/null +++ b/tools/packs/build.sh @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +# Builds the add-on packs the app downloads on first use instead of shipping in the APK: +# proot.tar.zst the patched proot and its loader (built by tools/proot) +# directaudio.tar.zst the Wine DirectAudio drivers (fetched by tools/directaudio/fetch.sh) +# tracking.tar.zst hand-tracking models and the OpenCV/MediaPipe native libraries +# xbox.tar.zst the Xbox backend (built by tools/xbox) for /usr/local/lib/droiddeck-xbox +# comet.tar.zst the GOG Galaxy companion (built by tools/comet) for /usr/local/lib/droiddeck-comet +# Only CI publishes these (.github/workflows/publish-packs.yml); the APK built from the same +# directory pins each pack's SHA-256. +# Usage: tools/packs/build.sh +set -euo pipefail + +here=$(cd "$(dirname "$0")" && pwd) +repo=$(cd "$here/../.." && pwd) +out=${1:?usage: build.sh } +mkdir -p "$out" +out=$(cd "$out" && pwd) +linuxfs="$repo/app/src/main/assets/linuxfs/usr/local/lib" +# shellcheck source=tracking/release.env +source "$here/tracking/release.env" + +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT + +sha256() { if command -v sha256sum >/dev/null; then sha256sum "$1" | cut -d' ' -f1; else shasum -a 256 "$1" | cut -d' ' -f1; fi; } + +fetch() { + local url=$1 expected=$2 dest=$3 + curl -fsSL --retry 4 -o "$dest" "$url" + local actual + actual=$(sha256 "$dest") + if [ "$actual" != "$expected" ]; then + echo "checksum mismatch for $url: $actual" >&2 + exit 1 + fi +} + +pack() { + local name=$1 src=$2 + shift 2 + for required in "$@"; do + [ -f "$src/$required" ] || { echo "$name pack: $src/$required is missing" >&2; exit 1; } + done + python3 -I - "$src" "$work/$name.tar" <<'EOF' +import os, sys, tarfile +src, dest = sys.argv[1], sys.argv[2] +files = [] +for base, dirs, names in os.walk(src): + dirs.sort() + for name in names: + path = os.path.join(base, name) + if os.path.islink(path) or not os.path.isfile(path): + sys.exit(f"{path}: only regular files can be packed") + files.append(os.path.relpath(path, src)) +with tarfile.open(dest, "w", format=tarfile.USTAR_FORMAT) as tar: + for rel in sorted(files): + path = os.path.join(src, rel) + info = tar.gettarinfo(path, arcname=rel) + info.mtime, info.uid, info.gid, info.uname, info.gname = 0, 0, 0, "", "" + info.mode = 0o755 if os.stat(path).st_mode & 0o111 else 0o644 + with open(path, "rb") as f: + tar.addfile(info, f) +EOF + zstd -q -19 -f "$work/$name.tar" -o "$out/$name.tar.zst" + echo "$name $(sha256 "$out/$name.tar.zst") $(wc -c < "$out/$name.tar.zst" | tr -d ' ')" +} + +mkdir "$work/tracking" +fetch "https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task" \ + fbc2a30080c3c557093b5ddfc334698132eb341044ccee322ccf8bcf3607cde1 "$work/tracking/hand_landmarker.task" +fetch "https://storage.googleapis.com/mediapipe-models/pose_landmarker/pose_landmarker_lite/float16/1/pose_landmarker_lite.task" \ + 59929e1d1ee95287735ddd833b19cf4ac46d29bc7afddbbf6753c459690d574a "$work/tracking/pose_landmarker_lite.task" +cp "$here/tracking/hand_landmarker_lite.task" "$work/tracking/" +[ "$(sha256 "$work/tracking/hand_landmarker_lite.task")" = 173c0f47ecee7e935bd4a1e93aa580756b4180c1307c07d709313e82c28672c8 ] || { + echo "checksum mismatch for hand_landmarker_lite.task" >&2; exit 1; } +fetch "https://repo1.maven.org/maven2/org/opencv/opencv/${OPENCV_VERSION}/opencv-${OPENCV_VERSION}.aar" \ + "$OPENCV_AAR_SHA256" "$work/opencv.aar" +fetch "https://dl.google.com/dl/android/maven2/com/google/mediapipe/tasks-core/${MEDIAPIPE_VERSION}/tasks-core-${MEDIAPIPE_VERSION}.aar" \ + "$MEDIAPIPE_AAR_SHA256" "$work/tasks-core.aar" +unzip -q -j "$work/opencv.aar" jni/arm64-v8a/libopencv_java4.so -d "$work/tracking" +unzip -q -j "$work/tasks-core.aar" jni/arm64-v8a/libmediapipe_tasks_jni.so -d "$work/tracking" +chmod 0644 "$work/tracking"/* + +mkdir "$work/proot" +install -m755 "$repo/app/src/main/jniLibs/arm64-v8a/libproot.so" "$repo/app/src/main/jniLibs/arm64-v8a/libproot-loader.so" "$work/proot/" +pack proot "$work/proot" libproot.so libproot-loader.so +pack directaudio "$repo/app/src/main/assets/directaudio" \ + linux-wine11/version.txt linux-wine11-systhread/version.txt +pack tracking "$work/tracking" hand_landmarker.task hand_landmarker_lite.task pose_landmarker_lite.task \ + libopencv_java4.so libmediapipe_tasks_jni.so +pack xbox "$linuxfs/droiddeck-xbox" version xodus-cli xodus-service +pack comet "$linuxfs/droiddeck-comet" version comet diff --git a/app/src/main/assets/models/hand_landmarker.provenance.json b/tools/packs/tracking/hand_landmarker.provenance.json similarity index 100% rename from app/src/main/assets/models/hand_landmarker.provenance.json rename to tools/packs/tracking/hand_landmarker.provenance.json diff --git a/app/src/main/assets/models/hand_landmarker_lite.provenance.json b/tools/packs/tracking/hand_landmarker_lite.provenance.json similarity index 100% rename from app/src/main/assets/models/hand_landmarker_lite.provenance.json rename to tools/packs/tracking/hand_landmarker_lite.provenance.json diff --git a/app/src/main/assets/models/hand_landmarker_lite.task b/tools/packs/tracking/hand_landmarker_lite.task similarity index 100% rename from app/src/main/assets/models/hand_landmarker_lite.task rename to tools/packs/tracking/hand_landmarker_lite.task diff --git a/tools/packs/tracking/release.env b/tools/packs/tracking/release.env new file mode 100644 index 0000000000..73d2589190 --- /dev/null +++ b/tools/packs/tracking/release.env @@ -0,0 +1,4 @@ +OPENCV_VERSION=4.13.0 +OPENCV_AAR_SHA256=a8c9b0929d8d6367bb476320a1f36587db2b57ea18d8f7521ce509514903ca04 +MEDIAPIPE_VERSION=1.0.0 +MEDIAPIPE_AAR_SHA256=609c6fcfe59f58c9739194f65ae5882281c327710e1a616aa7f533a4d9238ca3 diff --git a/tools/proot/PATCHES.md b/tools/proot/PATCHES.md index 43380c33fd..f379b4d7dc 100644 --- a/tools/proot/PATCHES.md +++ b/tools/proot/PATCHES.md @@ -55,6 +55,13 @@ Added for Flatpak: `linkat` fails with `EACCES` and Flatpak could not create its repo (`Creating repo: linkat: Permission denied`). `O_TMPFILE` answers `EOPNOTSUPP`, so libglnx writes a named temporary file and renames it, and a denied link answers `EPERM`, on which ostree's checkout copies instead. +- `0017-android-execstack-denial.patch` - the same policy denies apps executable stacks, so the + `mprotect(PROT_READ | PROT_WRITE | PROT_EXEC | PROT_GROWSDOWN)` with which `ld.so` makes the main + stack executable for an object whose `PT_GNU_STACK` asks for it fails with `EACCES`, and the + program stops before `main` ("cannot enable executable stack as shared object requires: + Permission denied", `libQt5Gui.so.5` in ONLYOFFICE's Flatpak). The filter traces `mprotect` only + for that exact request, and a denied one answers success: the stack stays non-executable, as + Android keeps it anyway, and objects that only carry the flag load. Added by DroidDeck: - `0011-kompat-utsname-only.patch` - `--kernel-release` (the guest's `DroidDeck` hostname) loads diff --git a/tools/proot/fastpath/fastpath.c b/tools/proot/fastpath/fastpath.c index 53741f4a6c..9700a1c618 100644 --- a/tools/proot/fastpath/fastpath.c +++ b/tools/proot/fastpath/fastpath.c @@ -141,6 +141,27 @@ static int traced_by_match(const char *key) { return found; } +static int program_32bit(const char *prog, int scripts) { + char head[256]; + long fd = syscall(SYS_openat, AT_FDCWD, prog, O_RDONLY | O_CLOEXEC); + if (fd < 0) return 1; + long n = syscall(SYS_read, fd, head, sizeof head - 1); + syscall(SYS_close, fd); + if (n < 0) return 1; + head[n] = 0; + if (n >= 2 && head[0] == '#' && head[1] == '!') { + if (scripts <= 0) return 1; + char *p = head + 2; + while (*p == ' ' || *p == '\t') p++; + char *e = p; + while (*e && *e != ' ' && *e != '\t' && *e != '\n' && *e != '\r') e++; + if (e == p || (!*e && n == (long)sizeof head - 1)) return 1; + *e = 0; + return program_32bit(p, scripts - 1); + } + return !(n >= 5 && memcmp(head, "\x7f" "ELF", 4) == 0 && head[4] == 2); +} + static int fex_runs_32bit(void) { if (strcmp(program_invocation_short_name, "FEX") != 0 && strcmp(program_invocation_short_name, "FEXInterpreter") != 0) return 0; @@ -153,12 +174,7 @@ static int fex_runs_32bit(void) { args[n] = 0; const char *prog = args + strlen(args) + 1; if (prog >= args + n || !*prog) return 1; - unsigned char ident[5]; - fd = syscall(SYS_openat, AT_FDCWD, prog, O_RDONLY | O_CLOEXEC); - if (fd < 0) return 1; - n = syscall(SYS_read, fd, ident, sizeof ident); - syscall(SYS_close, fd); - return !(n == 5 && memcmp(ident, "\x7f" "ELF", 4) == 0 && ident[4] == 2); + return program_32bit(prog, 4); } static int in_tracer(struct bind *bd) { diff --git a/tools/proot/patches/0017-android-execstack-denial.patch b/tools/proot/patches/0017-android-execstack-denial.patch new file mode 100644 index 0000000000..2ee6b5fd9c --- /dev/null +++ b/tools/proot/patches/0017-android-execstack-denial.patch @@ -0,0 +1,82 @@ +From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 +From: DroidDeck +Date: Tue, 20 Oct 2026 12:00:00 -0400 +Subject: [PATCH] syscall: work around Android's denial of executable stacks + +SELinux denies apps the execstack permission, so the mprotect with +which ld.so makes the main stack executable for an object whose +PT_GNU_STACK asks for it fails with EACCES, and the program does not +start ("cannot enable executable stack as shared object requires: +Permission denied", libQt5Gui.so.5 in ONLYOFFICE's Flatpak). The +filter traces mprotect only for that exact request, and a denied one +answers success: the stack stays non-executable, as Android keeps it. +--- +diff --git a/src/syscall/exit.c b/src/syscall/exit.c +index e87b7e1..71b36f5 100644 +--- a/src/syscall/exit.c ++++ b/src/syscall/exit.c +@@ -25,6 +25,7 @@ + #include /* SYS_*, */ + #include /* _IOW, */ + #include /* strlen(3), */ ++#include /* PROT_*, */ + + #include "cli/note.h" + #include "syscall/syscall.h" +@@ -552,6 +553,13 @@ void translate_syscall_exit(Tracee *tracee) + if ((int) syscall_result == -EACCES) + poke_reg(tracee, SYSARG_RESULT, -EPERM); + goto end; ++ ++ case PR_mprotect: ++ if ((int) syscall_result == -EACCES ++ && (peek_reg(tracee, ORIGINAL, SYSARG_3) & (PROT_EXEC | PROT_GROWSDOWN)) ++ == (PROT_EXEC | PROT_GROWSDOWN)) ++ poke_reg(tracee, SYSARG_RESULT, 0); ++ goto end; + #endif + + case PR_ioctl: +diff --git a/src/syscall/seccomp.c b/src/syscall/seccomp.c +index d9be7b4..fca220b 100644 +--- a/src/syscall/seccomp.c ++++ b/src/syscall/seccomp.c +@@ -46,6 +46,7 @@ + #include + #include + #include /* assert(3), */ ++#include /* PROT_*, */ + + #include "syscall/seccomp.h" + #include "tracee/tracee.h" +@@ -316,6 +317,10 @@ static size_t trace_length_raw(Sysnum sysnum) + return LENGTH_TRACE_PRLIMIT_STACK; + case PR_ioctl: + return LENGTH_TRACE_IOCTL; ++#ifdef __ANDROID__ ++ case PR_mprotect: ++ return LENGTH_TRACE_SYSCALL_IF_ARG; ++#endif + default: + return LENGTH_TRACE_SYSCALL; + } +@@ -335,6 +340,11 @@ static int add_trace(struct sock_fprog *program, Sysnum sysnum, word_t syscall, + return add_trace_prlimit_stack(program, syscall, flag); + case PR_ioctl: + return add_trace_ioctl_requests(program, syscall, flag); ++#ifdef __ANDROID__ ++ case PR_mprotect: ++ return add_trace_syscall_if_arg(program, syscall, 2, ++ PROT_READ | PROT_WRITE | PROT_EXEC | PROT_GROWSDOWN, flag); ++#endif + default: + return add_trace_syscall(program, syscall, flag); + } +@@ -599,6 +609,7 @@ static FilteredSysnum proot_sysnums[] = { + { PR_lstat64, 0 }, + #ifdef __ANDROID__ + { PR_memfd_create, 0 }, ++ { PR_mprotect, FILTER_SYSEXIT }, + #endif + { PR_mkdir, 0 }, + { PR_mkdirat, 0 }, diff --git a/tools/release/runtime_inputs.py b/tools/release/runtime_inputs.py index fefef3eab7..6b04616ef1 100644 --- a/tools/release/runtime_inputs.py +++ b/tools/release/runtime_inputs.py @@ -12,6 +12,14 @@ from zipfile import ZipFile ROOT = Path(__file__).resolve().parents[2] MANIFEST = Path('app/build/runtime-inputs.json') +PACKS = Path('app/build/packs') +# Runtime trees shipped as add-on packs (tools/packs/build.sh) rather than inside the APK. +PACKED = {'assets/linuxfs/usr/local/lib/droiddeck-xbox/': 'xbox', 'assets/linuxfs/usr/local/lib/droiddeck-comet/': 'comet', + 'assets/directaudio/': 'directaudio'} +PACKED_FILES = {'lib/arm64-v8a/libproot.so': ('proot', 'libproot.so'), + 'lib/arm64-v8a/libproot-loader.so': ('proot', 'libproot-loader.so')} +PACKED_LIBRARIES = ['lib/arm64-v8a/libopencv_java4.so', 'lib/arm64-v8a/libmediapipe_tasks_jni.so'] +PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet'] SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/assets/pulseaudio.tzst', 'tools/linuxfs', 'tools/proot', 'tools/aaudio-sink', 'tools/directaudio', 'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env', @@ -157,10 +165,49 @@ def verify(root=ROOT): return data +def pack_digests(root, name): + path = root / PACKS / (name + '.tar.zst') + if not path.is_file(): + raise ValueError('Missing add-on pack ' + name + '. Run tools/packs/build.sh app/build/packs.') + process = subprocess.Popen(['zstd', '-dc', str(path)], stdout=subprocess.PIPE) + digests = {} + try: + with tarfile.open(fileobj=process.stdout, mode='r|') as archive: + for member in archive: + if member.isfile(): + digests[member.name] = hashlib.sha256(archive.extractfile(member).read()).hexdigest() + finally: + process.stdout.close() + if process.wait(): + raise ValueError('Invalid add-on pack ' + name) + return digests + + def check_apk(apk, root=ROOT): data = verify(root) + packs = {name: pack_digests(root, name) for name in PACK_NAMES} with ZipFile(apk) as package: + names = set(package.namelist()) + for library in PACKED_LIBRARIES: + if library in names: + raise ValueError('APK still carries ' + library + ', which the tracking pack provides') + if library.rsplit('/', 1)[1] not in packs['tracking']: + raise ValueError('Tracking pack missing ' + library) for name, output in data['outputs'].items(): + if name in PACKED_FILES: + pack, rel = PACKED_FILES[name] + if name in names: + raise ValueError('APK still carries ' + name + ', which the ' + pack + ' pack provides') + if packs[pack].get(rel) != output['sha256']: + raise ValueError('Add-on pack ' + pack + ' is missing or has a stale ' + name) + continue + prefix = next((p for p in PACKED if name.startswith(p)), None) + if prefix: + if name in names: + raise ValueError('APK still carries ' + name + ', which the ' + PACKED[prefix] + ' pack provides') + if packs[PACKED[prefix]].get(name[len(prefix):]) != output['sha256']: + raise ValueError('Add-on pack ' + PACKED[prefix] + ' is missing or has a stale ' + name) + continue try: content = package.read(name) except KeyError: diff --git a/tools/tests/test_bwrap_socket.py b/tools/tests/test_bwrap_socket.py new file mode 100644 index 0000000000..7fa782c8ad --- /dev/null +++ b/tools/tests/test_bwrap_socket.py @@ -0,0 +1,36 @@ +import os +import runpy +import shutil +import tempfile +import unittest +from pathlib import Path +from unittest import mock + +BWRAP = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-bwrap" + + +class BwrapSocketTest(unittest.TestCase): + def setUp(self): + self.dir = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.dir, True) + self.shim = runpy.run_path(str(BWRAP)) + self.shim["socket_name"].__globals__["SOCKET_FILE"] = str(self.dir / "bwrap-socket") + + def name(self, env): + with mock.patch.dict(os.environ, env, clear=True): + return self.shim["socket_name"]() + + def test_flatpak_empty_environment_reaches_a_renamed_package(self): + (self.dir / "bwrap-socket").write_text("com.antutu.benchmark.full.bwrap\n") + self.assertEqual("\0com.antutu.benchmark.full.bwrap", self.name({})) + + def test_the_environment_still_wins(self): + (self.dir / "bwrap-socket").write_text("com.antutu.benchmark.full.bwrap\n") + self.assertEqual("\0com.tencent.ig.bwrap", self.name({"DROIDDECK_BWRAP_SOCKET": "com.tencent.ig.bwrap"})) + + def test_without_either_the_standard_package_is_asked(self): + self.assertEqual("\0com.droiddeck.launcher.bwrap", self.name({})) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_droiddeck_agent.py b/tools/tests/test_droiddeck_agent.py index 8997bff978..50b62f2064 100644 --- a/tools/tests/test_droiddeck_agent.py +++ b/tools/tests/test_droiddeck_agent.py @@ -6,6 +6,7 @@ import importlib.util import json import os from pathlib import Path +import shutil import socket import struct import subprocess @@ -77,6 +78,79 @@ class FakeDevTools(threading.Thread): conn.close() +class FakeSteamClient(threading.Thread): + + def __init__(self, showing): + super().__init__(daemon=True) + self.showing = showing + self.server = socket.socket() + self.server.bind(("127.0.0.1", 0)) + self.server.listen(4) + self.port = self.server.getsockname()[1] + self.seen = [] + self.conn = None + self.lock = threading.Lock() + + def run(self): + while True: + try: + conn, _ = self.server.accept() + except OSError: + return + threading.Thread(target=self.serve, args=(conn,), daemon=True).start() + + def send(self, conn, message): + payload = json.dumps(message).encode() + header = bytes([0x81, 126]) + struct.pack(">H", len(payload)) if len(payload) > 125 else bytes([0x81, len(payload)]) + with self.lock: + conn.sendall(header + payload) + + def push(self, payload, name=None): + self.send(self.conn, {"method": "Runtime.bindingCalled", + "params": {"name": name or agent.KEYBOARD_BINDING, "payload": payload}}) + + def drop(self): + self.conn.shutdown(socket.SHUT_RDWR) + self.conn.close() + + def serve(self, conn): + stream = conn.makefile("rb") + head = b"" + while not head.endswith(b"\r\n\r\n"): + head += stream.read(1) + request = head.decode() + if request.startswith("GET /json"): + body = json.dumps([{"title": "Steam Big Picture Mode", "url": "https://steamloopback.host/routes/", + "webSocketDebuggerUrl": "ws://127.0.0.1:%d/devtools/page/2" % self.port}, + {"title": "SharedJSContext", "url": "https://steamloopback.host/", + "webSocketDebuggerUrl": "ws://127.0.0.1:%d/devtools/page/1" % self.port}]).encode() + conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: %d\r\n\r\n" % len(body) + body) + conn.close() + return + key = [l.split(":", 1)[1].strip() for l in request.split("\r\n") if l.lower().startswith("sec-websocket-key")][0] + accept = base64.b64encode(hashlib.sha1((key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode()).digest()).decode() + conn.sendall(("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + "Sec-WebSocket-Accept: %s\r\n\r\n" % accept).encode()) + self.conn = conn + try: + while True: + b0, b1 = stream.read(2) + n = b1 & 0x7F + if n == 126: + n = struct.unpack(">H", stream.read(2))[0] + elif n == 127: + n = struct.unpack(">Q", stream.read(8))[0] + mask = stream.read(4) + data = stream.read(n) + message = json.loads(bytes(b ^ mask[i % 4] for i, b in enumerate(data))) + self.seen.append(message) + self.push("true", name="unrelated") + result = {"result": {"type": "boolean", "value": self.showing}} if message["method"] == "Runtime.evaluate" else {} + self.send(conn, {"id": message["id"], "result": result}) + except (OSError, ValueError): + conn.close() + + class AgentTest(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory() @@ -409,6 +483,144 @@ class AgentTest(unittest.TestCase): self.assertIn(child.pid, agent.game_pids(424242)) +class SteamKeyboardTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.dir = Path(self.temp.name) + + def state(self): + try: + return json.loads((self.dir / "keyboard.json").read_text()) + except (OSError, ValueError): + return None + + def wait_for(self, check): + for _ in range(200): + if check(): + return + time.sleep(0.02) + self.fail("timed out; keyboard.json is %s" % self.state()) + + def test_report_writes_only_changes(self): + watcher = agent.KeyboardWatcher(self.dir) + watcher.report(False) + self.assertEqual({"steamKeyboard": False, "seq": 1}, self.state()) + watcher.report(False) + watcher.report(True) + self.assertEqual({"steamKeyboard": True, "seq": 2}, self.state()) + + def test_follows_the_clients_keyboard_and_rechecks_while_idle(self): + client = FakeSteamClient(False) + client.start() + self.addCleanup(client.server.close) + (self.dir / "cdp-port").write_text(str(client.port)) + watcher = agent.KeyboardWatcher(self.dir) + failure = [] + with patch.object(agent, "KEYBOARD_CHECK_SECONDS", 0.3): + thread = threading.Thread(target=lambda: failure.append(self.capture(watcher.watch)), daemon=True) + thread.start() + self.wait_for(lambda: self.state() == {"steamKeyboard": False, "seq": 1}) + self.assertEqual("Runtime.addBinding", client.seen[0]["method"]) + self.assertEqual(agent.KEYBOARD_BINDING, client.seen[0]["params"]["name"]) + self.assertIn("IsShowingVirtualKeyboard", client.seen[1]["params"]["expression"]) + self.assertIn(agent.KEYBOARD_BINDING, client.seen[1]["params"]["expression"]) + self.assertNotIn("__BINDING__", client.seen[1]["params"]["expression"]) + client.push("true") + self.wait_for(lambda: (self.state() or {}).get("steamKeyboard") is True) + client.push("false") + self.wait_for(lambda: (self.state() or {}).get("steamKeyboard") is False) + client.showing = True + self.wait_for(lambda: (self.state() or {}).get("steamKeyboard") is True) + self.assertGreaterEqual(len([m for m in client.seen if m["method"] == "Runtime.evaluate"]), 2) + client.drop() + thread.join(5) + self.assertFalse(thread.is_alive()) + self.assertIsInstance(failure[0], OSError) + + def test_any_loss_reports_the_keyboard_closed_and_backs_off(self): + watcher = agent.KeyboardWatcher(self.dir) + watcher.report(True) + + def attached_then_lost(): + watcher.attached = True + raise OSError("DevTools closed the connection") + + steps = iter([agent.AgentError("NO_DEVTOOLS", "no port"), agent.AgentError("NO_DEVTOOLS", "no port"), + attached_then_lost, KeyError("SteamUIStore")]) + + def watch(): + step = next(steps, None) + if step is None: + raise SystemExit + if callable(step): + step() + raise step + + with patch.object(watcher, "watch", side_effect=watch), patch.object(agent.time, "sleep") as sleep, \ + patch.object(agent, "log") as log: + with self.assertRaises(SystemExit): + watcher.run() + self.assertEqual({"steamKeyboard": False, "seq": 2}, self.state()) + self.assertEqual([2, 4, 2, 4], [c.args[0] for c in sleep.call_args_list]) + self.assertFalse(watcher.attached) + self.assertEqual(3, log.call_count) + + def test_no_shared_context_yet(self): + with patch.object(agent, "cdp_targets", return_value=[{"title": "Steam", "webSocketDebuggerUrl": "ws://127.0.0.1:1/x"}]): + with self.assertRaises(agent.AgentError) as caught: + agent.KeyboardWatcher(self.dir).watch() + self.assertEqual("NO_TARGET", caught.exception.code) + + @unittest.skipUnless(shutil.which("node"), "node is not installed") + def test_page_script_watches_every_window_with_or_without_subscribe(self): + harness = r""" +const assert = require('assert'); +globalThis.window = globalThis; +const script = require('fs').readFileSync(process.argv[2], 'utf8'); +const calls = []; +window.droiddeckSteamKeyboard = value => calls.push(value); +const tick = ms => new Promise(done => setTimeout(done, ms)); +const value = subscribe => { + const v = { m_currentValue: false, m_callbacks: [] }; + if (subscribe) v.Subscribe = cb => { v.m_callbacks.push(cb); return { Unsubscribe() {} }; }; + v.set = next => { v.m_currentValue = next; for (const cb of v.m_callbacks) cb(next); }; + return v; +}; +(async () => { + assert.strictEqual(eval(script), false); + assert.deepStrictEqual(calls, ['false']); + const main = value(true), overlay = value(false); + globalThis.SteamUIStore = { WindowStore: { SteamUIWindows: [{ VirtualKeyboardManager: { IsShowingVirtualKeyboard: main } }] } }; + assert.strictEqual(eval(script), false); + main.set(true); + await tick(20); + assert.deepStrictEqual(calls, ['false', 'true']); + main.set(false); + await tick(20); + SteamUIStore.WindowStore.SteamUIWindows.push({}, { VirtualKeyboardManager: { IsShowingVirtualKeyboard: overlay } }); + overlay.m_currentValue = true; + await tick(700); + assert.deepStrictEqual(calls, ['false', 'true', 'false', 'true']); + assert.strictEqual(eval(script), true); + assert.strictEqual(main.m_callbacks.length, 1); + clearInterval(window.__droiddeckKeyboard.timer); +})().catch(e => { console.error(e); process.exit(1); }); +""" + (self.dir / "keyboard.js").write_text(agent.KEYBOARD_JS) + (self.dir / "harness.js").write_text(harness) + result = subprocess.run(["node", str(self.dir / "harness.js"), str(self.dir / "keyboard.js")], + capture_output=True, text=True, timeout=20) + self.assertEqual(0, result.returncode, result.stderr) + + @staticmethod + def capture(call): + try: + call() + except Exception as e: + return e + + class VrFocusTest(unittest.TestCase): def test_scene_dashboard_and_external_focus_changes(self): focus = agent.VrSceneFocus() diff --git a/tools/tests/test_fakeinput_ring.py b/tools/tests/test_fakeinput_ring.py index 3c87bd11e2..86afc9939a 100644 --- a/tools/tests/test_fakeinput_ring.py +++ b/tools/tests/test_fakeinput_ring.py @@ -18,24 +18,44 @@ READER = r""" #include #include #include +#include #include -int main(void) +static int vector_count; + +static ssize_t controller_read(int fd, void *buffer, size_t size) { + if (!vector_count) + return read(fd, buffer, size); + struct iovec vectors[3] = { + {buffer, sizeof(struct input_event)}, + {(char *)buffer + sizeof(struct input_event), 0}, + {(char *)buffer + sizeof(struct input_event), size - sizeof(struct input_event)}, + }; + if (vector_count == 1) { + vectors[0].iov_len = size; + return readv(fd, vectors, 1); + } + return readv(fd, vectors, 3); +} + +int main(int argc, char **argv) +{ + vector_count = argc > 1 ? (argv[1][0] == '1' ? 1 : 3) : 0; struct input_event events[64]; int fd = open("/dev/input/event16", O_RDONLY | O_NONBLOCK); if (fd < 0) { perror("open"); return 1; } - while (read(fd, events, sizeof(events)) > 0) + while (controller_read(fd, events, sizeof(events)) > 0) ; puts("ready"); fflush(stdout); char go; if (read(0, &go, 1) != 1) return 1; - ssize_t got = read(fd, events, sizeof(events)); + ssize_t got = controller_read(fd, events, sizeof(events)); for (ssize_t i = 0; i < got / (ssize_t)sizeof(events[0]); i++) printf("%ld.%06ld %u %u %d\n", (long)events[i].time.tv_sec, (long)events[i].time.tv_usec, events[i].type, events[i].code, events[i].value); @@ -65,6 +85,146 @@ int main(void) return 0; } """ +READV_CHECKS = r""" +#include +#include +#include +#include +#include +#include +#include +#include + +int main(void) +{ + struct input_event events[64]; + int fd = open("/dev/input/event16", O_RDONLY | O_NONBLOCK); + if (fd < 0) + return 1; + while (read(fd, events, sizeof(events)) > 0) + ; + struct iovec vector = {events, sizeof(events)}; + if (readv(fd, &vector, 1) != -1 || errno != EAGAIN) + return 2; + if (readv(fd, NULL, 0) != 0) + return 3; + vector.iov_len = 0; + if (readv(fd, &vector, 1) != 0) + return 4; + vector.iov_len = sizeof(struct input_event) - 1; + if (readv(fd, &vector, 1) != -1 || errno != EINVAL) + return 5; + ssize_t (*invoke)(int, const struct iovec *, int) = readv; + if (invoke(fd, NULL, -1) != -1 || errno != EINVAL) + return 6; + if (invoke(fd, NULL, 1025) != -1 || errno != EINVAL) + return 7; + if (invoke(fd, NULL, 1) != -1 || errno != EFAULT) + return 8; + long page = sysconf(_SC_PAGESIZE); + void *area = mmap(NULL, 2 * page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (area == MAP_FAILED) + return 10; + struct iovec *boundary = (struct iovec *)((char *)area + page - sizeof(struct iovec)); + *boundary = vector; + if (mprotect((char *)area + page, page, PROT_NONE)) + return 11; + if (invoke(fd, boundary, 2) != -1 || errno != EFAULT) + return 12; + if (invoke(fd, boundary + 1, 1) != -1 || errno != EFAULT) + return 13; + if (munmap(area, 2 * page)) + return 14; + if (invoke(fd, boundary, 1) != -1 || errno != EFAULT) + return 15; + int pipefd[2]; + char text[5] = {0}; + struct iovec parts[2] = {{text, 1}, {text + 1, 3}}; + if (pipe(pipefd) || write(pipefd[1], "test", 4) != 4 || + readv(pipefd[0], parts, 2) != 4 || strcmp(text, "test")) + return 9; + puts("ok"); + return 0; +} +""" +READV_DESTINATION_CHECKS = r""" +#include +#include +#include +#include +#include +#include +#include + +int main(int argc, char **argv) +{ + struct input_event events[64]; + int fd = open("/dev/input/event16", O_RDONLY | O_NONBLOCK); + if (fd < 0) + return 1; + if (argc > 1) + while (read(fd, events, sizeof(events)) > 0) + ; + puts("ready"); + fflush(stdout); + char go; + if (read(0, &go, 1) != 1) + return 2; + long page = sysconf(_SC_PAGESIZE); + char *area = mmap(NULL, 2 * page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (area == MAP_FAILED || mprotect(area + page, page, PROT_NONE)) + return 3; + struct iovec vector = {area + page, sizeof(struct input_event)}; + if (readv(fd, &vector, 1) != -1 || errno != EFAULT) + return 4; + if (read(fd, vector.iov_base, vector.iov_len) != -1 || errno != EFAULT) + return 5; + if (mprotect(area, page, PROT_READ)) + return 6; + vector.iov_base = area; + if (readv(fd, &vector, 1) != -1 || errno != EFAULT) + return 7; + if (mprotect(area, page, PROT_READ | PROT_WRITE) || munmap(area + page, page)) + return 8; + vector.iov_base = area + page; + if (readv(fd, &vector, 1) != -1 || errno != EFAULT) + return 9; + vector.iov_base = area + page - 1; + if (readv(fd, &vector, 1) != -1 || errno != EFAULT) + return 15; + vector.iov_base = area + page - sizeof(struct input_event); + vector.iov_len = 2 * sizeof(struct input_event); + if (readv(fd, &vector, 1) != sizeof(struct input_event)) + return 10; + struct input_event *first = vector.iov_base; + if (first->type != EV_KEY || first->code != BTN_A) + return 11; + struct iovec parts[2] = {{events, sizeof(struct input_event)}, {NULL, sizeof(struct input_event)}}; + if (readv(fd, parts, 2) != sizeof(struct input_event)) + return 12; + if (events[0].type != (argc > 1 ? EV_ABS : EV_KEY) || events[0].code != (argc > 1 ? ABS_Y : BTN_B)) + return 13; + vector.iov_base = events; + vector.iov_len = sizeof(events); + ssize_t got = readv(fd, &vector, 1); + if (got != (argc > 1 ? 1 : 18) * sizeof(struct input_event) || + events[0].type != (argc > 1 ? EV_SYN : EV_KEY) || events[0].code != (argc > 1 ? SYN_REPORT : BTN_X)) + return 14; + munmap(area, page); + puts("ok"); + return 0; +} +""" +OVERLAY_READ = r""" +#include +#include + +ssize_t read(int fd, void *buffer, size_t size) +{ + struct iovec vector = {buffer, size}; + return readv(fd, &vector, 1); +} +""" def can_build(bits): @@ -82,15 +242,16 @@ class FakeinputRingTest(unittest.TestCase): self.tmp = Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, self.tmp, True) - def ring(self): + def ring(self, virtual=True): hooks = self.tmp / "hooks" hooks.mkdir() - (hooks / "event16").touch() - ring = bytearray(HEADER + CAPACITY * EVENT + DESCRIPTION) + (hooks / ("event16" if virtual else "event0")).touch() + ring = bytearray(HEADER + CAPACITY * EVENT + (DESCRIPTION if virtual else 0)) struct.pack_into("> "%s"\nexec %s "$@"\n' % (log, shutil.which("awk"))) + (shim / "awk").chmod(0o755) + env = dict(os.environ, DROIDDECK_LIBRARIES="", PATH="%s:%s" % (shim, os.environ["PATH"])) + once = self.reg.read_text() + subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True) + self.assertEqual(once, self.reg.read_text()) + self.assertNotIn(str(self.reg), log.read_text() if log.exists() else "") + replaced = self.reg.with_name("system.reg.new") + replaced.write_text("WINE REGISTRY Version 2\n") + os.replace(replaced, self.reg) + subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True) + self.assertEqual(self.reg.read_text().count('"VCRedist2022"=dword:00000001'), 2) + def test_the_prefix_date_is_kept(self): os.utime(self.reg, (1_000_000_000, 1_000_000_000)) self.run_seed() diff --git a/tools/tests/test_session_run_display.py b/tools/tests/test_session_run_display.py new file mode 100644 index 0000000000..430a6a1373 --- /dev/null +++ b/tools/tests/test_session_run_display.py @@ -0,0 +1,67 @@ +import os +import re +import shutil +import subprocess +import tempfile +import unittest +from pathlib import Path + +SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session" + + +def run_case(): + return re.search(r"^ run\)\n.*?^ ;;\n", SESSION.read_text(), re.M | re.S).group(0) + + +def steam_display(): + return re.search(r"^ steam\)\n(.*?)^ steam_x64=0\n", SESSION.read_text(), re.M | re.S).group(1) + + +class SessionRunDisplayTest(unittest.TestCase): + def setUp(self): + self.dir = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.dir, True) + self.target = self.dir / "target.sh" + self.target.write_text("printf '%s\\n' \"${WAYLAND_DISPLAY-unset}\" \"${XDG_SESSION_TYPE-unset}\"" + " > \"$1\"\n") + + def display(self, **env): + base = {k: v for k, v in os.environ.items() + if k not in ("GAMESCOPE_WAYLAND_DISPLAY", "WAYLAND_DISPLAY", "XDG_SESSION_TYPE", + "BL_LAUNCH_DIR")} + seen = self.dir / "seen" + script = ("program_cores() { :; }\nmode=run\ncase $mode in\n" + run_case() + "esac\n" + + "echo unreachable\n") + run = subprocess.run(["bash", "-c", script, "droiddeck-session", str(self.target), str(seen)], + env={**base, **env}, capture_output=True, text=True, timeout=30) + self.assertEqual(0, run.returncode, run.stderr) + self.assertNotIn("unreachable", run.stdout) + return seen.read_text().splitlines() + + def test_programs_under_gamescope_cannot_reach_a_wayland_server(self): + self.assertEqual(["", "x11"], self.display(GAMESCOPE_WAYLAND_DISPLAY="gamescope-0", + WAYLAND_DISPLAY="gamescope-0", XDG_SESSION_TYPE="wayland")) + + def test_without_gamescope_the_display_is_left_alone(self): + self.assertEqual(["wayland-0", "wayland"], self.display(WAYLAND_DISPLAY="wayland-0", XDG_SESSION_TYPE="wayland")) + + def steam_env(self, **env): + base = {k: v for k, v in os.environ.items() + if k not in ("GAMESCOPE_WAYLAND_DISPLAY", "WAYLAND_DISPLAY", "XDG_SESSION_TYPE")} + script = steam_display() + ('printf "%s\\n" "${WAYLAND_DISPLAY-unset}" "${XDG_SESSION_TYPE-unset}"' + ' "${MOZ_SHM_NO_SEALS-unset}" "${MOZ_DISABLE_CONTENT_SANDBOX-unset}"\n') + run = subprocess.run(["bash", "-c", script], env={**base, **env}, capture_output=True, text=True, timeout=30) + self.assertEqual(0, run.returncode, run.stderr) + return run.stdout.splitlines() + + def test_steam_games_under_gamescope_cannot_reach_a_wayland_server(self): + self.assertEqual(["", "x11", "1", "1"], self.steam_env(GAMESCOPE_WAYLAND_DISPLAY="gamescope-0", + WAYLAND_DISPLAY="gamescope-0", XDG_SESSION_TYPE="wayland")) + + def test_steam_without_gamescope_keeps_the_display(self): + self.assertEqual(["wayland-0", "wayland", "1", "1"], + self.steam_env(WAYLAND_DISPLAY="wayland-0", XDG_SESSION_TYPE="wayland")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_steam_client_setup_failure.py b/tools/tests/test_steam_client_setup_failure.py new file mode 100644 index 0000000000..774e14aa4a --- /dev/null +++ b/tools/tests/test_steam_client_setup_failure.py @@ -0,0 +1,82 @@ +import os +from pathlib import Path +import re +import subprocess +import tempfile +import textwrap +import unittest + + +SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session' +SOURCE = SESSION.read_text() +ARM64_BRANCH = SOURCE.index(' else\n step "checking the Steam client (first run') +START = SOURCE.index(' droiddeck-steam-install || steam_setup_failed $?\n', ARM64_BRANCH) +END = SOURCE.index(' step "Steam client ready"\n', START) +HELPER = re.search(r'^steam_setup_failed\(\) \{\n.*?^\}\n', SOURCE, re.M | re.S).group() +INSTALL_BLOCK = HELPER + textwrap.dedent(SOURCE[START:END]) +RUN_GAMESCOPE = re.search(r'^run_gamescope\(\) \(\n.*?^\)\n', SOURCE, re.M | re.S).group() +MARKER = '== steam: the Steam client could not be set up' + + +class SteamClientSetupFailureTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + + def installer(self, status): + script = self.root / 'droiddeck-steam-install' + script.write_text('#!/bin/bash\n' + 'echo "curl: (35) Recv failure: Connection reset by peer" >&2\n' + 'exit ' + str(status) + '\n') + script.chmod(0o755) + + def env(self, **extra): + base = {k: v for k, v in os.environ.items() if k != 'BL_STEAM_EXIT_FILE'} + return dict(base, PATH=str(self.root) + os.pathsep + os.environ['PATH'], + XDG_RUNTIME_DIR=str(self.root), **extra) + + def run_block(self, status, exit_file=None): + self.installer(status) + extra = {'BL_STEAM_EXIT_FILE': str(exit_file)} if exit_file else {} + return subprocess.run(['bash', '-c', INSTALL_BLOCK + 'echo continued\n'], env=self.env(**extra), + capture_output=True, text=True, timeout=10) + + def test_failed_install_reports_its_status_in_the_exit_file(self): + exit_file = self.root / 'exit' + result = self.run_block(1, exit_file) + self.assertEqual(1, result.returncode) + self.assertIn(MARKER + ' (status 1)', result.stdout) + self.assertNotIn('continued', result.stdout) + self.assertEqual('1\n', exit_file.read_text()) + + def test_failed_install_outside_gamescope_still_exits_with_its_status(self): + result = self.run_block(50) + self.assertEqual(50, result.returncode) + self.assertIn(MARKER + ' (status 50)', result.stdout) + + def test_ready_client_continues_without_a_report(self): + exit_file = self.root / 'exit' + result = self.run_block(0, exit_file) + self.assertEqual(0, result.returncode) + self.assertIn('continued', result.stdout) + self.assertNotIn(MARKER, result.stdout) + self.assertFalse(exit_file.exists()) + + def test_failed_install_survives_successful_compositor_shutdown(self): + self.installer(1) + compositor = self.root / 'gamescope' + compositor.write_text('#!/bin/bash\n"$@"\nexit 0\n') + compositor.chmod(0o755) + child = self.root / 'session-child' + child.write_text('#!/bin/bash\n' + INSTALL_BLOCK + 'exit 0\n') + child.chmod(0o755) + result = subprocess.run(['bash', '-c', RUN_GAMESCOPE + '\nrun_gamescope "$@"', 'session', str(child)], + env=self.env(), capture_output=True, text=True, timeout=10) + self.assertEqual(1, result.returncode) + self.assertIn(MARKER, result.stdout) + self.assertEqual(list(self.root.glob('droiddeck-steam-exit.??????')), []) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_steam_compat_live.py b/tools/tests/test_steam_compat_live.py index 90f7e73f8f..3cf27824b4 100644 --- a/tools/tests/test_steam_compat_live.py +++ b/tools/tests/test_steam_compat_live.py @@ -54,6 +54,7 @@ class FakeSocket { state.authed = dec.decode(h[40][0]) === "secret" && dec.decode(body[1][0]) === "secret"; result = state.authed ? 1 : 5; } else if (!state.authed) result = 5; + else if (method === "CompatManager.GetCompatTools#1" && ["16", "128"].includes(String(body[1][0]))) result = Number(body[1][0]); else if (method === "CompatManager.GetCompatTools#1") { const app = String(body[1] ? body[1][0] : 0n); for (const name of state.known) { const t = []; lenField(1, enc.encode(name), t); lenField(2, enc.encode(name + " shown"), t); lenField(1, t, out); } @@ -79,17 +80,19 @@ const install = require("fs").readFileSync(process.argv[4], "utf8"); const before = await c.get(0); await c.set(0, "droiddeck-proton-11-arm64"); await c.set(42, ""); - const after = await c.many(["0", "42", "43"]); + const after = await c.many(["0", "42", "43", "128"]); + const timedOut = await c.many(["0", "16"]).then(() => null, (e) => e.eresult); await new Promise((r) => setTimeout(r, 10)); - console.log(JSON.stringify({ before, after, log: state.log, notify: state.notify, url: state.socket.url })); + console.log(JSON.stringify({ before, after, timedOut, log: state.log, notify: state.notify, url: state.socket.url })); })().catch((e) => { console.error(e.stack || String(e)); process.exit(1); }); """ class FakePage: - def __init__(self, mapping, known): + def __init__(self, mapping, known, refused=()): self.mapping = dict(mapping) self.known = list(known) + self.refused = set(refused) self.sets = [] def compat(self, call): @@ -98,8 +101,10 @@ class FakePage: if name == "get": return {"selected": self.mapping.get(str(args[0]), ""), "fallback": "proton_experimental", "tools": self.known} if name == "many": - return {app: self.mapping.get(app, "") for app in args[0]} + return {app: self.mapping.get(app, "") for app in args[0] if app not in self.refused} if name == "set": + if str(args[0]) in self.refused: + raise RuntimeError("SpecifyCompatTool %s failed (128)" % args[0]) self.mapping[str(args[0])] = args[1] self.sets.append((str(args[0]), args[1])) return True @@ -202,6 +207,7 @@ assert.deepStrictEqual(calls, [['611670', 'custom args', -1, 100], ['2508200', ' self.assertEqual(out["url"], "ws://127.0.0.1:4242/transportsocket/") self.assertEqual(out["before"], {"selected": TOOL, "fallback": "proton_experimental", "tools": [TOOL, TOOL_11, "proton_experimental"]}) self.assertEqual(out["after"], {"0": TOOL_11, "42": "", "43": ""}) + self.assertEqual(out["timedOut"], 16) self.assertEqual(out["log"], ["0=" + TOOL_11, "42="]) self.assertEqual(out["notify"], ["1", "2"]) @@ -264,6 +270,21 @@ class ReconcileTest(unittest.TestCase): self.assertTrue(state["live"]) self.assertEqual(self.helper.installed, ["10", "11"]) + def test_an_app_the_client_refuses_is_dropped_instead_of_failing_the_sync(self): + page = FakePage({"0": TOOL, "10": TOOL, "11": "proton_experimental"}, [TOOL, TOOL_11], refused={"1628350"}) + (self.state / "state.json").write_text(json.dumps({"default": TOOL, "auto": {"10": TOOL, "1628350": TOOL}})) + (self.state / "games.json").write_text(json.dumps({"version": 1, "games": {"1628350": {"valve": True, "dir": "Proton 11.0 (ARM64)"}}})) + state = self.reconcile(page) + self.assertEqual(page.sets, [("11", TOOL)]) + self.assertEqual(state["auto"], {"10": TOOL, "11": TOOL}) + + def test_a_refused_apps_native_choice_is_kept(self): + page = FakePage({"0": TOOL, "10": TOOL, "11": TOOL}, [TOOL, TOOL_11], refused={"20"}) + (self.state / "state.json").write_text(json.dumps({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}, "native_choices": ["20"]})) + state = self.reconcile(page) + self.assertEqual(page.sets, []) + self.assertEqual(state["native_choices"], ["20"]) + def test_app_request_moves_the_default_and_followers(self): page = FakePage({"0": TOOL, "10": TOOL, "11": "GE-Proton11-7"}, [TOOL, TOOL_11]) (self.state / "state.json").write_text(json.dumps({"default": TOOL, "auto": {"10": TOOL}})) @@ -488,6 +509,70 @@ class ReconcileTest(unittest.TestCase): self.assertEqual(page.sets, []) self.assertEqual(state["native_choices"], [app]) + def test_clearing_a_tool_picked_in_steam_keeps_the_native_build(self): + app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}}) + page.known.append(COMPAT["FEX_TOOL"]) + page.mapping[app] = COMPAT["FEX_TOOL"] + config = self.steam / "config/config.vdf" + config.write_text( + '"InstallConfigStore" { "Software" { "Valve" { "Steam" { ' + '"CompatToolMapping" { "0" { "name" "%s" } "%s" { "name" "%s" } } } } } }' % (TOOL, app, COMPAT["FEX_TOOL"])) + state = self.reconcile(page) + self.assertEqual(page.sets, []) + self.assertNotIn(app, state["auto"]) + + page.mapping[app] = "" + state = self.reconcile(page) + self.assertEqual(page.sets, []) + config.write_text( + '"InstallConfigStore" { "Software" { "Valve" { "Steam" { ' + '"CompatToolMapping" { "0" { "name" "%s" } } } } } }' % TOOL) + state = self.reconcile(page) + self.assertEqual(page.sets, []) + self.assertEqual(state["native_choices"], [app]) + + restarted = LIVE["Helper"](str(self.steam), 1) + restarted.page = page + restarted.reconcile() + self.assertEqual(page.sets, []) + + def test_a_new_tool_for_a_picked_game_is_kept_before_the_client_writes_its_config(self): + app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}, "picked": ["892970"]}) + page.mapping[app] = TOOL_11 + with mock.patch.dict(COMPAT, {"native_targets": lambda _root, apps: {app: COMPAT["FEX_TOOL"]} if app in apps else {}}): + state = self.reconcile(page) + self.assertEqual(page.sets, []) + self.assertEqual(page.mapping[app], TOOL_11) + self.assertIn(app, state["picked"]) + + def test_a_cleared_picked_game_showing_a_stale_inherited_tool_stays_native(self): + app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}, "picked": ["892970"]}) + page.mapping[app] = "proton" + state = self.reconcile(page) + self.assertEqual(page.sets, []) + self.assertEqual(state["native_choices"], [app]) + + def test_a_clear_saved_after_the_helper_stopped_is_kept_at_the_next_start(self): + app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}}) + page.known.append(COMPAT["FEX_TOOL"]) + page.mapping[app] = COMPAT["FEX_TOOL"] + config = self.steam / "config/config.vdf" + config.write_text( + '"InstallConfigStore" { "Software" { "Valve" { "Steam" { ' + '"CompatToolMapping" { "0" { "name" "%s" } "%s" { "name" "%s" } } } } } }' % (TOOL, app, COMPAT["FEX_TOOL"])) + state = self.reconcile(page) + self.assertIn(app, state["picked"]) + + config.write_text( + '"InstallConfigStore" { "Software" { "Valve" { "Steam" { ' + '"CompatToolMapping" { "0" { "name" "%s" } } } } } }' % TOOL) + with mock.patch.dict(COMPAT["register_default"].__globals__, {"native_targets": COMPAT["native_targets"]}): + COMPAT["register_default"](str(config), ["10", "11", app], settle=True, directory=str(self.state)) + self.assertNotIn(app, COMPAT["read_config_mapping"](str(config))) + state = json.loads((self.state / "state.json").read_text()) + self.assertEqual(state["native_choices"], [app]) + self.assertNotIn(app, state["picked"]) + def test_unmapped_dual_platform_game_gets_the_default_without_a_readable_config(self): app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL}, "native_choices": ["11"]}) (self.steam / "config/config.vdf").unlink() diff --git a/tools/tests/test_store_launch.py b/tools/tests/test_store_launch.py index 1c4ac4bbac..5da2972ed9 100644 --- a/tools/tests/test_store_launch.py +++ b/tools/tests/test_store_launch.py @@ -226,6 +226,43 @@ class CloudHooks(unittest.TestCase): self.assertEqual(store.CLOUD_TIMEOUT, asked[1][1]) self.assertEqual('cloud-up', asked[2][0]['op']) + def test_a_first_launch_creates_the_prefix_before_the_cloud_download(self): + with tempfile.TemporaryDirectory() as root: + folder = game(root, store_id='epic', ident='fa4240e5') + sidecar = json.loads((folder / store.SIDECAR).read_text()) + sidecar['epic'] = {'eos': False, 'offline': True} + (folder / store.SIDECAR).write_text(json.dumps(sidecar)) + proton = Path(root) / 'proton' + proton.write_text('selected Proton') + compat = Path(root) / 'compatdata/1' + order = [] + + def run(argv, **kwargs): + order.append(argv) + (compat / 'pfx').mkdir(parents=True) + (compat / 'pfx/user.reg').write_text('WINE REGISTRY Version 2\n') + return __import__('subprocess').CompletedProcess(argv, 0) + + env = {'BL_LAUNCH_DIR': root, 'STEAM_COMPAT_DATA_PATH': str(compat), 'BL_STORE_PROTON': str(proton)} + with patch.dict(os.environ, env), patch.object(store.subprocess, 'run', side_effect=run), \ + patch.object(store, 'ask', side_effect=lambda channel, request, timeout=5.0: order.append(request) or {'result': 'ok'}): + self.assertEqual(store.STORE_GAME, store.main([str(folder / store.LAUNCHER)])) + self.assertEqual([str(proton), 'run', 'cmd.exe', '/d', '/c', 'exit'], order[0]) + self.assertEqual({'op': 'cloud-down', 'store': 'epic', 'id': 'fa4240e5'}, order[-1]) + self.assertEqual('present', store.create_prefix(str(compat), str(proton))) + self.assertEqual(2, len(order)) + + def test_a_prefix_that_is_not_made_leaves_the_deferred_download(self): + with tempfile.TemporaryDirectory() as root: + proton = Path(root) / 'proton' + proton.write_text('selected Proton') + with patch.object(store.subprocess, 'run', return_value=__import__('subprocess').CompletedProcess([], 1)): + self.assertEqual('failed', store.create_prefix(root + '/compatdata/1', str(proton))) + with patch.object(store.subprocess, 'run', side_effect=__import__('subprocess').TimeoutExpired('proton', 1)): + self.assertEqual('timeout', store.create_prefix(root + '/compatdata/1', str(proton))) + self.assertEqual('no-proton', store.create_prefix(root + '/compatdata/1', root + '/missing')) + self.assertEqual('no-proton', store.create_prefix('', str(proton))) + def test_cloud_off_or_amazon_runs_proton_as_before(self): with tempfile.TemporaryDirectory() as root: folder = game(root, store_id='gog', ident='1') diff --git a/tools/xbox/README.md b/tools/xbox/README.md index b06825748b..abe39f8c9b 100644 --- a/tools/xbox/README.md +++ b/tools/xbox/README.md @@ -5,7 +5,14 @@ service. It does not install the Nexus desktop launcher or x86 Linux Wine. `backend.lock.json` pins Xodus, the Nexus commit, Rust, and the ordered patch checksums. `runtime.lock.json` pins the Nexus Windows runtime release and each extracted PE DLL. `prepare.py` verifies both source revisions and all Nexus patch -checksums before applying the two local transport/launch patches. +checksums before applying the local transport, launch and library patches. + +`droiddeck-library-subscriptions.patch` queries fresh subscription membership +alongside product entitlements using the same Store session, account and market. +Android can validate a Game Pass child's parent plan when that plan is absent +from the product response. A failed membership query fails the refresh and +preserves the previous library. Empty membership results add no plan evidence; +valid plans already present in the product response retain their existing checks. Build on AArch64 Ubuntu 24.04 with Rust from the lock, a C/C++ compiler, OpenSSL development headers, pkg-config, protoc, CMake, Git, Python 3 and xz: diff --git a/tools/xbox/droiddeck-library-subscriptions.patch b/tools/xbox/droiddeck-library-subscriptions.patch new file mode 100644 index 0000000000..833fab085d --- /dev/null +++ b/tools/xbox/droiddeck-library-subscriptions.patch @@ -0,0 +1,95 @@ +--- a/crates/xodus-cli/src/commands/library.rs ++++ b/crates/xodus-cli/src/commands/library.rs +@@ -96,6 +96,48 @@ + eprintln!("NEXUS_LIBRARY_DIAGNOSTIC_V1 {stage} {status} {count}"); + } + ++const SUBSCRIPTION_PLANS: &[&str] = &[ ++ "CFQ7TTC0KGQ8", "CFQ7TTC0KHS0", "CFQ7TTC0P85B", ++ "CFQ7TTC0K5DJ", "CFQ7TTC0K6L8", "CFQ7TTC10QFD", ++]; ++ ++fn subscription_rows(body: &Value) -> Result, &'static str> { ++ let rows = body["entitlements"].as_object().ok_or("subscriptions-shape")?; ++ if rows.len() > SUBSCRIPTION_PLANS.len() { return Err("subscriptions-count"); } ++ let mut plans = Vec::new(); ++ for (id, row) in rows { ++ if !SUBSCRIPTION_PLANS.contains(&id.as_str()) { return Err("subscriptions-product"); } ++ let status = row["status"].as_str().ok_or("subscriptions-status")?; ++ if status != "Active" { continue; } ++ let expiry = row["endDate"].as_str().filter(|s| s.len() < 50) ++ .filter(|s| chrono::DateTime::parse_from_rfc3339(s).is_ok()).ok_or("subscriptions-expiry")?; ++ plans.push(json!({"productId":id,"status":status,"endDate":expiry})); ++ } ++ Ok(plans) ++} ++ ++async fn subscriptions(client: &reqwest::Client, ticket: &str, market: &str) -> Result, &'static str> { ++ let url = format!("https://beige.xboxservices.com/PCGAFD/entitlements/subscriptions?market={market}&language=en-US&appVersion=0.2.3"); ++ let cv = format!("{}.0", STANDARD_NO_PAD.encode(uuid::Uuid::new_v4().as_bytes())); ++ let mut response = client.post(url) ++ .header("Authorization", ticket).header("X-MS-API-Version", "1.1") ++ .header("Calling-App-Name", "Xodus-Nexus").header("MS-CV", cv) ++ .json(&json!({"productIds":SUBSCRIPTION_PLANS})) ++ .send().await.map_err(|_| "subscriptions-request")?; ++ if !response.status().is_success() { ++ diagnostic("subscriptions-http", response.status().as_u16(), 0); ++ return Err("subscriptions-http"); ++ } ++ if response.content_length().is_some_and(|n| n > 262_144) { return Err("subscriptions-size"); } ++ let mut bytes = Vec::new(); ++ while let Some(chunk) = response.chunk().await.map_err(|_| "subscriptions-read")? { ++ if bytes.len() + chunk.len() > 262_144 { return Err("subscriptions-size"); } ++ bytes.extend_from_slice(&chunk); ++ } ++ let body: Value = serde_json::from_slice(&bytes).map_err(|_| "subscriptions-json")?; ++ subscription_rows(&body) ++} ++ + async fn query(tokens: &TokenManager, market: &str) -> Result { + if market.len() != 2 || !market.bytes().all(|b| b.is_ascii_uppercase()) { + return Err("market"); +@@ -155,6 +197,7 @@ + let page: Value = serde_json::from_slice(&bytes).map_err(|_| "entitlements-json")?; + all.add(&page)?; + if continuation.is_none() { ++ let subscriptions = subscriptions(&client, &ticket, market).await?; + if tokens.get_user().map_err(|_| "account-check")?.username != account { + return Err("account-changed"); + } +@@ -162,7 +205,7 @@ + for (reason, count) in &all.reasons { diagnostic(reason, 0, *count); } + diagnostic(if all.skipped > 0 { "partial" } else { "complete" }, 0, all.skipped); + return Ok(json!({"schema":1,"account":account,"market":market, +- "checkedAt":chrono::Utc::now().to_rfc3339(),"skippedEntitlements":all.skipped, ++ "checkedAt":chrono::Utc::now().to_rfc3339(),"skippedEntitlements":all.skipped,"subscriptions":subscriptions, + "entitlements":all.entries.into_values().collect::>()})); + } + } +@@ -200,6 +243,26 @@ + #[cfg(test)] + mod tests { + use super::*; ++ #[test] ++ fn subscription_membership_is_separate_from_product_entitlements() { ++ let body = json!({"entitlements":{"CFQ7TTC0KGQ8":{ ++ "status":"Active","endDate":"2099-01-01T00:00:00Z","autoRenew":true,"private":"not-output"}}}); ++ assert_eq!(subscription_rows(&body).unwrap(), vec![json!({"productId":"CFQ7TTC0KGQ8", ++ "status":"Active","endDate":"2099-01-01T00:00:00Z"})]); ++ assert!(subscription_rows(&json!({"entitlements":{}})).unwrap().is_empty()); ++ assert!(subscription_rows(&json!({"entitlements":{"CFQ7TTC0KGQ8":{"status":"Expired"}}})).unwrap().is_empty()); ++ } ++ ++ #[test] ++ fn malformed_membership_is_an_error_not_an_empty_subscription_list() { ++ for body in [json!({}), json!({"entitlements":[]}), ++ json!({"entitlements":{"unknown":{"status":"Active"}}}), ++ json!({"entitlements":{"CFQ7TTC0KGQ8":{"status":true}}}), ++ json!({"entitlements":{"CFQ7TTC0KGQ8":{"status":"Active","endDate":"invalid"}}})] { ++ assert!(subscription_rows(&body).is_err()); ++ } ++ } ++ + const A: &str = "9AAAAAAAAAAA"; + const B: &str = "9BBBBBBBBBBB"; + const C: &str = "9CCCCCCCCCCC"; diff --git a/tools/xbox/prepare.py b/tools/xbox/prepare.py index ff7bb15c68..30afc1b019 100755 --- a/tools/xbox/prepare.py +++ b/tools/xbox/prepare.py @@ -9,7 +9,8 @@ import sys recipe = Path(__file__).resolve().parent cache = Path(sys.argv[1]).resolve() lock = json.loads((recipe / 'backend.lock.json').read_text()) -identity = hashlib.sha256((recipe / 'backend.lock.json').read_bytes() + (recipe / 'droiddeck-credentials.patch').read_bytes() + (recipe / 'droiddeck-launch-view.patch').read_bytes()).hexdigest() +local_patches = ['droiddeck-credentials.patch', 'droiddeck-launch-view.patch', 'droiddeck-library-subscriptions.patch'] +identity = hashlib.sha256((recipe / 'backend.lock.json').read_bytes() + b''.join((recipe / name).read_bytes() for name in local_patches)).hexdigest() source = cache / ('source-' + identity[:16]) if not (source / '.prepared').is_file(): if source.exists(): @@ -29,8 +30,8 @@ if not (source / '.prepared').is_file(): file = nexus / 'assets' / patch['file'] assert hashlib.sha256(file.read_bytes()).hexdigest() == patch['sha256'] subprocess.run(['git', '-C', str(source), 'apply', str(file)], check=True) - subprocess.run(['git', '-C', str(source), 'apply', str(recipe / 'droiddeck-credentials.patch')], check=True) - subprocess.run(['git', '-C', str(source), 'apply', str(recipe / 'droiddeck-launch-view.patch')], check=True) + for name in local_patches: + subprocess.run(['git', '-C', str(source), 'apply', str(recipe / name)], check=True) (source / '.prepared').write_text(identity + '\n') assert (source / '.prepared').read_text().strip() == identity print(source)