diff --git a/.github/trusted-test-builds.txt b/.github/trusted-test-builds.txt index fa4cff1104..4f94e6c268 100644 --- a/.github/trusted-test-builds.txt +++ b/.github/trusted-test-builds.txt @@ -1,5 +1,6 @@ ASEbrahim FX192 +FryMcNugget K11MCH1 KeegantheVeganat0r kingokksa diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 52c70b7d8f..08cb6341be 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -195,17 +195,17 @@ jobs: app/src/main/assets/linuxfs !app/src/main/assets/linuxfs/usr/local/lib/droiddeck-comet !app/src/main/assets/linuxfs/usr/local/lib/droiddeck-xbox - !app/src/main/assets/linuxfs/i386/libblsession.so + !app/src/main/assets/linuxfs/i386/libddsession.so !app/src/main/assets/linuxfs/i386/libfakeinput.so !app/src/main/assets/linuxfs/i386/libfaultreport.so - !app/src/main/assets/linuxfs/libblaudit.so - !app/src/main/assets/linuxfs/libblfastpath.so + !app/src/main/assets/linuxfs/libddaudit.so + !app/src/main/assets/linuxfs/libddfastpath.so !app/src/main/assets/linuxfs/libddnatv-hook.so - !app/src/main/assets/linuxfs/libblsession.so + !app/src/main/assets/linuxfs/libddsession.so !app/src/main/assets/linuxfs/libfakeinput.so !app/src/main/assets/linuxfs/libssbs.so !app/src/main/assets/linuxfs/usr/local/bin/droiddeck-clipboard - !app/src/main/assets/linuxfs/x86_64/libblsession.so + !app/src/main/assets/linuxfs/x86_64/libddsession.so !app/src/main/assets/linuxfs/x86_64/libfakeinput.so !app/src/main/assets/linuxfs/x86_64/libfaultreport.so !app/src/main/assets/linuxfs/x86_64/libvulkan-thunk.so @@ -291,7 +291,7 @@ jobs: - name: Build the non-Adreno test additions (Mali bridge client, Venus GL probe, Xclipse layer) run: | set -euo pipefail - bash tools/ci/install-ubuntu-packages.sh gcc-aarch64-linux-gnu libvulkan-dev + bash tools/ci/install-ubuntu-packages.sh gcc-aarch64-linux-gnu libc6-dev-arm64-cross libvulkan-dev D=app/src/main/assets/linuxfs mkdir -p "$D/usr/local/bin" "$D/usr/local/lib/droiddeck-xclipse" aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -Wextra -Wno-unused-parameter -fvisibility=hidden -pthread \ @@ -765,7 +765,6 @@ jobs: if: ${{ github.event_name != 'pull_request' || !github.event.pull_request.draft }} runs-on: ubuntu-24.04 timeout-minutes: 15 - continue-on-error: true permissions: contents: read actions: read @@ -811,7 +810,6 @@ jobs: stores-host-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.rust.outputs.rustc }}- - name: Store engines host unit tests timeout-minutes: 10 - continue-on-error: true run: | set -o pipefail cd app/src/main/rust/stores @@ -900,7 +898,7 @@ jobs: checks: name: Compile and test APK - needs: [build, python-tests] + needs: [build, python-tests, store-tests] if: ${{ !cancelled() && (github.event_name != 'pull_request' || !github.event.pull_request.draft) }} runs-on: ubuntu-24.04 timeout-minutes: 5 @@ -909,7 +907,8 @@ jobs: env: BUILD_RESULT: ${{ needs.build.result }} PYTHON_RESULT: ${{ needs.python-tests.result }} - run: test "$BUILD_RESULT" = success && test "$PYTHON_RESULT" = success + STORE_RESULT: ${{ needs.store-tests.result }} + run: test "$BUILD_RESULT" = success && test "$PYTHON_RESULT" = success && test "$STORE_RESULT" = success sign: needs: [build, checks] diff --git a/README.md b/README.md index a62414073d..7154309b06 100644 --- a/README.md +++ b/README.md @@ -47,7 +47,7 @@ Help, Preview builds and device reports are on [Discord](https://discord.gg/JRGA ## Build -Needs Docker, Java 17, the Android SDK and NDK, Rust via rustup, GitHub CLI, Python 3 and `zstd`. +Needs Docker, Java 17, the Android SDK and NDK, Rust via rustup, Go, a host C compiler, the x86_64 and i686 MinGW-w64 compilers (i686 with DWARF-2 exceptions, as Debian and Ubuntu ship it; SJLJ builds such as Homebrew's cannot link Rust's `i686-pc-windows-gnu`), GitHub CLI, Python 3 and `zstd`. On x86_64 Linux, Docker also needs an arm64 binfmt handler (`docker run --privileged --rm tonistiigi/binfmt --install arm64`). ```bash tools/build_local.sh @@ -70,13 +70,13 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V - Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05. - mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). -- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT). FEX's code disk cache was checked in its source. +- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. - x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence. - x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes. - `WriteProcessMemory` hooks fall back to `/proc//mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11. - Windows programs on noexec storage get executable copies of their image pages, following [@yujikaido](https://github.com/yujikaido)'s finding in [droiddeck-rp4pro](https://github.com/yujikaido/droiddeck-rp4pro) that Wine's own processes need the noexec shim. -- Wine write watches use userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later). libblsession supplies the arm64 syscall number and answers `PAGEMAP_SCAN` from `/proc/self/pagemap`. -- libblsession runs Wine's arm64 `SIGUSR2` context handler (`dlls/ntdll/unix/signal_arm64.c`, LGPL-2.1-or-later) in place on a frame laid out like [Linux](https://github.com/torvalds/linux)'s `arch/arm64/kernel/signal.c`, and serves `fill_vm_counters` in `dlls/ntdll/unix/process.c` the kernel's own `/proc//status`. +- Wine write watches use userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later). libddsession supplies the arm64 syscall number and answers `PAGEMAP_SCAN` from `/proc/self/pagemap`. +- libddsession runs Wine's arm64 `SIGUSR2` context handler (`dlls/ntdll/unix/signal_arm64.c`, LGPL-2.1-or-later) in place on a frame laid out like [Linux](https://github.com/torvalds/linux)'s `arch/arm64/kernel/signal.c`, and serves `fill_vm_counters` in `dlls/ntdll/unix/process.c` the kernel's own `/proc//status`. - droiddeck-ntsync follows the [Linux](https://github.com/torvalds/linux) ntsync semantics in `Documentation/userspace-api/ntsync.rst` (GPL-2.0). - The proot fast path orders bindings like [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later). - DiRT 3 and DiRT Showdown keep their telemetry socket the way RoccoC's DiRTTelemetryErrorFix (MIT) does, based on the fix by Carsten Gottschling. @@ -97,6 +97,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V - Battle.net is by [@kayakyakr](https://github.com/kayakyakr). It runs Blizzard's own client in Proton (downloaded from Blizzard, not included) and shows key art from the [Battle.net Shop](https://shop.battle.net). Without Steam, its games see the pad as an Xbox 360 controller via `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`. - The EA store follows the EA app's protocols as documented by [ArmchairDevelopers](https://github.com/ArmchairDevelopers)' [Maxima](https://github.com/ArmchairDevelopers/Maxima) (GPL-3.0): sign-in, the GraphQL queries (included verbatim, since EA matches them by hash), build archives, online activation licences and the LSX game endpoint. The code is DroidDeck's own. - Battle.net installs drive Blizzard's Agent the way [@barncastle](https://github.com/barncastle)'s [Battle.Net-Installer](https://github.com/barncastle/Battle.Net-Installer) does, with requests from [wowdev.wiki](https://wowdev.wiki/Agent). Read without taking code: [@mubaraknumann](https://github.com/mubaraknumann)'s [unifideck](https://github.com/mubaraknumann/unifideck), [@djmittens](https://github.com/djmittens)'s [neo-mittens](https://github.com/djmittens/neo-mittens) `bnetswitch`, [@BCD1210](https://github.com/BCD1210)'s [soju](https://github.com/BCD1210/soju) and [Lutris](https://github.com/lutris/lutris)'s `product.db` reader. +- The Rockstar launcher service looks for launcher pipe names in the executables beside the game, since [CitizenFX](https://github.com/citizenfx/fivem)'s `ros-patches-five` shows GTA V opening `GTAVLauncher_Pipe` and [@pingod](https://github.com/pingod)'s [rdr2-linux-launcher](https://github.com/pingod/rdr2-linux-launcher) notes that Rockstar's protected executables resolve such strings only at run time. Read without taking code. - World of Warcraft addon imports replace an addon's folder from a temporary copy, as [WowUp](https://github.com/WowUp/WowUp) does, and read flavour folders the way [WoWDeck](https://github.com/sigboe/wowdeck) does. No code from either is used. - The World of Warcraft addon Download window searches [WoWInterface](https://www.wowinterface.com) through its MMOUI API. [CurseForge](https://www.curseforge.com/wow) opens in the user's browser, with no API and no key. - The Xbox store runs [@domsvoboda](https://github.com/domsvoboda)'s [nexus-backend](https://github.com/domsvoboda/nexus-backend) 0.2.15 (GPL-3.0, a fork of [Xodus](https://github.com/xodus-gaming/xodus)), and Xbox games load the Windows modules of his [nexus-runtime](https://github.com/domsvoboda/nexus-runtime) (LGPL-2.1-or-later), including the C++ [nexus-xgameruntime](https://github.com/domsvoboda/nexus-xgameruntime) and `wintypes.dll`. Content licensing sends delegation-compact device tickets in the licensing wire form, as nexus-backend's Store license path (commit `27c335e`) does. Minecraft's GameInput setup was checked against [@Wyze3306](https://github.com/Wyze3306)'s [BedrockOnLinux](https://github.com/Wyze3306/BedrockOnLinux) (MIT). diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 54fe09ca7c..aff5658bbe 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -4,6 +4,9 @@ + + + @@ -150,6 +153,7 @@ + @@ -298,6 +302,15 @@ android:resizeableActivity="true" android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density" /> + (dlsym(RTLD_DEFAULT, "bl_udevmon_inject")); + static auto inject = reinterpret_cast(dlsym(RTLD_DEFAULT, "dd_udevmon_inject")); return inject ? inject(action, devpath, subsystem, devname, major, minor) : -1; } diff --git a/app/src/main/cpp/shaders/smaa.frag b/app/src/main/cpp/shaders/smaa.frag index e6095db9ad..55160fdcff 100644 --- a/app/src/main/cpp/shaders/smaa.frag +++ b/app/src/main/cpp/shaders/smaa.frag @@ -85,17 +85,16 @@ void main() { float crossingPattern = smoothstep(threshold, threshold * 2.5, crossingContrast); float areaWeight = 0.38 * crossingPattern * clamp(span / 4.0, 0.0, 1.0); float diagonalContrast = max(abs(nw - se), abs(ne - sw)); - float cornerFactor = 1.0 - 0.18 * smoothstep(threshold, threshold * 3.0, diagonalContrast); + float cornerFactor = 1.0 - 0.35 * smoothstep(threshold, threshold * 3.0, diagonalContrast); float baseWeight = areaWeight * endpointArea * edgeConfidence * cornerFactor; - float diagonalStrength = abs(abs(nw - se) - abs(ne - sw)); + float diagonalStrength = min(vertical, horizontal); float diagonalPattern = smoothstep(threshold, threshold * 2.5, diagonalStrength); - float diagonalFallback = 0.16 * diagonalPattern * edgeConfidence * cornerFactor; + float diagonalContinuity = smoothstep(1.0, 3.0, span); + float diagonalFallback = 0.16 * diagonalPattern * edgeConfidence + * cornerFactor * diagonalContinuity * crossingPattern; - float weight = clamp( - baseWeight <= 0.0001 ? diagonalFallback : baseWeight, - 0.0, 0.42 - ); + float weight = clamp(max(baseWeight, diagonalFallback), 0.0, 0.42); vec3 across = texture(InputTexture, uv + normal * px).rgb; outColor = vec4(mix(center.rgb, across, weight), center.a); } diff --git a/app/src/main/cpp/shaders/smaa_frag.h b/app/src/main/cpp/shaders/smaa_frag.h index ea8bb4d56a..1467b4efc0 100644 --- a/app/src/main/cpp/shaders/smaa_frag.h +++ b/app/src/main/cpp/shaders/smaa_frag.h @@ -2,7 +2,7 @@ #include static const uint32_t smaa_code[] = { - 0x07230203u, 0x00010000u, 0x0008000bu, 0x00000254u, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu, + 0x07230203u, 0x00010000u, 0x0008000bu, 0x00000251u, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u, 0x0007000fu, 0x00000004u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00000072u, 0x000000f6u, 0x00030010u, 0x00000004u, 0x00000007u, 0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du, @@ -53,391 +53,391 @@ static const uint32_t smaa_code[] = { 0x00000200u, 0x67616964u, 0x6c616e6fu, 0x746e6f43u, 0x74736172u, 0x00000000u, 0x00060005u, 0x0000020au, 0x6e726f63u, 0x61467265u, 0x726f7463u, 0x00000000u, 0x00050005u, 0x00000214u, 0x65736162u, 0x67696557u, 0x00007468u, 0x00070005u, 0x0000021cu, 0x67616964u, 0x6c616e6fu, 0x65727453u, 0x6874676eu, 0x00000000u, - 0x00060005u, 0x00000227u, 0x67616964u, 0x6c616e6fu, 0x74746150u, 0x006e7265u, 0x00070005u, 0x0000022du, - 0x67616964u, 0x6c616e6fu, 0x6c6c6146u, 0x6b636162u, 0x00000000u, 0x00040005u, 0x00000235u, 0x67696577u, - 0x00007468u, 0x00040005u, 0x0000023eu, 0x6f726361u, 0x00007373u, 0x00040047u, 0x00000025u, 0x00000021u, - 0x00000000u, 0x00040047u, 0x00000025u, 0x00000022u, 0x00000000u, 0x00030047u, 0x00000064u, 0x00000002u, - 0x00050048u, 0x00000064u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00050048u, 0x00000064u, 0x00000001u, - 0x00000023u, 0x00000010u, 0x00050048u, 0x00000064u, 0x00000002u, 0x00000023u, 0x00000018u, 0x00050048u, - 0x00000064u, 0x00000003u, 0x00000023u, 0x0000001cu, 0x00040047u, 0x00000072u, 0x0000001eu, 0x00000000u, - 0x00040047u, 0x000000f6u, 0x0000001eu, 0x00000000u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, - 0x00000002u, 0x00030016u, 0x00000006u, 0x00000020u, 0x00040017u, 0x00000007u, 0x00000006u, 0x00000003u, - 0x00040020u, 0x00000008u, 0x00000007u, 0x00000007u, 0x00040021u, 0x00000009u, 0x00000006u, 0x00000008u, - 0x00040017u, 0x0000000du, 0x00000006u, 0x00000002u, 0x00040020u, 0x0000000eu, 0x00000007u, 0x0000000du, - 0x00050021u, 0x0000000fu, 0x00000006u, 0x0000000eu, 0x0000000eu, 0x0004002bu, 0x00000006u, 0x00000019u, - 0x3e59b3d0u, 0x0004002bu, 0x00000006u, 0x0000001au, 0x3f371759u, 0x0004002bu, 0x00000006u, 0x0000001bu, - 0x3d93dd98u, 0x0006002cu, 0x00000007u, 0x0000001cu, 0x00000019u, 0x0000001au, 0x0000001bu, 0x00040020u, - 0x00000020u, 0x00000007u, 0x00000006u, 0x00090019u, 0x00000022u, 0x00000006u, 0x00000001u, 0x00000000u, - 0x00000000u, 0x00000000u, 0x00000001u, 0x00000000u, 0x0003001bu, 0x00000023u, 0x00000022u, 0x00040020u, - 0x00000024u, 0x00000000u, 0x00000023u, 0x0004003bu, 0x00000024u, 0x00000025u, 0x00000000u, 0x00040015u, - 0x00000028u, 0x00000020u, 0x00000000u, 0x0004002bu, 0x00000028u, 0x00000029u, 0x00000000u, 0x0004002bu, - 0x00000006u, 0x0000002cu, 0x00000000u, 0x00040017u, 0x0000002fu, 0x00000006u, 0x00000004u, 0x0004002bu, - 0x00000028u, 0x00000048u, 0x00000001u, 0x0004002bu, 0x00000006u, 0x00000063u, 0x3f800000u, 0x0006001eu, - 0x00000064u, 0x0000002fu, 0x0000000du, 0x00000006u, 0x00000006u, 0x00040020u, 0x00000065u, 0x00000009u, - 0x00000064u, 0x0004003bu, 0x00000065u, 0x00000066u, 0x00000009u, 0x00040015u, 0x00000067u, 0x00000020u, - 0x00000001u, 0x0004002bu, 0x00000067u, 0x00000068u, 0x00000001u, 0x00040020u, 0x00000069u, 0x00000009u, - 0x0000000du, 0x0005002cu, 0x0000000du, 0x0000006cu, 0x00000063u, 0x00000063u, 0x00040020u, 0x00000071u, - 0x00000001u, 0x0000000du, 0x0004003bu, 0x00000071u, 0x00000072u, 0x00000001u, 0x0004002bu, 0x00000006u, - 0x00000075u, 0x3f000000u, 0x00040020u, 0x0000007bu, 0x00000007u, 0x0000002fu, 0x0004002bu, 0x00000006u, - 0x000000deu, 0x3d3851ecu, 0x0004002bu, 0x00000006u, 0x000000e0u, 0x3da3d70au, 0x00020014u, 0x000000f1u, - 0x00040020u, 0x000000f5u, 0x00000003u, 0x0000002fu, 0x0004003bu, 0x000000f5u, 0x000000f6u, 0x00000003u, - 0x00040020u, 0x000000f9u, 0x00000007u, 0x000000f1u, 0x0004002bu, 0x00000006u, 0x00000113u, 0xbf800000u, - 0x00040020u, 0x0000011fu, 0x00000007u, 0x00000067u, 0x0004002bu, 0x00000067u, 0x00000127u, 0x00000006u, - 0x0004002bu, 0x00000006u, 0x00000161u, 0x3f266666u, 0x0004002bu, 0x00000006u, 0x00000182u, 0x40200000u, - 0x0004002bu, 0x00000006u, 0x000001cau, 0x3d6147aeu, 0x0004002bu, 0x00000006u, 0x000001f8u, 0x3ec28f5cu, - 0x0004002bu, 0x00000006u, 0x000001fcu, 0x40800000u, 0x0004002bu, 0x00000006u, 0x0000020bu, 0x3e3851ecu, - 0x0004002bu, 0x00000006u, 0x0000020eu, 0x40400000u, 0x0004002bu, 0x00000006u, 0x0000022eu, 0x3e23d70au, - 0x0004002bu, 0x00000006u, 0x00000237u, 0x38d1b717u, 0x0004002bu, 0x00000006u, 0x0000023cu, 0x3ed70a3du, - 0x0004002bu, 0x00000028u, 0x0000024du, 0x00000003u, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, - 0x00000003u, 0x000200f8u, 0x00000005u, 0x0004003bu, 0x0000000eu, 0x00000062u, 0x00000007u, 0x0004003bu, - 0x0000000eu, 0x00000070u, 0x00000007u, 0x0004003bu, 0x0000007bu, 0x0000007cu, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x00000080u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x00000081u, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x00000085u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x0000008du, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x00000090u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x00000098u, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x0000009bu, 0x00000007u, 0x0004003bu, 0x00000008u, 0x000000a3u, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x000000a6u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x000000aeu, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x000000b1u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000b6u, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x000000bbu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000c0u, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x000000c5u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000cfu, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x000000d9u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000ddu, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x000000e3u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000e7u, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x000000ebu, 0x00000007u, 0x0004003bu, 0x000000f9u, 0x000000fau, 0x00000007u, 0x0004003bu, - 0x0000000eu, 0x000000feu, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x00000100u, 0x00000007u, 0x0004003bu, - 0x0000000eu, 0x0000010bu, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x0000010du, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x0000011du, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000011eu, 0x00000007u, 0x0004003bu, - 0x0000011fu, 0x00000120u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x00000129u, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x0000012eu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000130u, 0x00000007u, 0x0004003bu, - 0x0000000eu, 0x00000136u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x00000137u, 0x00000007u, 0x0004003bu, - 0x0000000eu, 0x0000013eu, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x0000013fu, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x00000143u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000145u, 0x00000007u, 0x0004003bu, - 0x0000000eu, 0x0000014bu, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x0000014cu, 0x00000007u, 0x0004003bu, - 0x0000000eu, 0x00000153u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x00000154u, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x0000017bu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000017fu, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x00000186u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x00000192u, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x00000195u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x000001a0u, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x000001a3u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x000001aeu, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x000001b1u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x000001bbu, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x000001beu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001c7u, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x000001ceu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001d0u, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x000001ddu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001dfu, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x000001ecu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001f1u, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x000001f7u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000200u, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x0000020au, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000214u, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x0000021cu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000227u, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x0000022du, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000235u, 0x00000007u, 0x0004003bu, - 0x00000008u, 0x0000023eu, 0x00000007u, 0x00050041u, 0x00000069u, 0x0000006au, 0x00000066u, 0x00000068u, - 0x0004003du, 0x0000000du, 0x0000006bu, 0x0000006au, 0x0007000cu, 0x0000000du, 0x0000006du, 0x00000001u, - 0x00000028u, 0x0000006bu, 0x0000006cu, 0x00050050u, 0x0000000du, 0x0000006eu, 0x00000063u, 0x00000063u, - 0x00050088u, 0x0000000du, 0x0000006fu, 0x0000006eu, 0x0000006du, 0x0003003eu, 0x00000062u, 0x0000006fu, - 0x0004003du, 0x0000000du, 0x00000073u, 0x00000072u, 0x0004003du, 0x0000000du, 0x00000074u, 0x00000062u, - 0x0005008eu, 0x0000000du, 0x00000076u, 0x00000074u, 0x00000075u, 0x0004003du, 0x0000000du, 0x00000077u, - 0x00000062u, 0x0005008eu, 0x0000000du, 0x00000078u, 0x00000077u, 0x00000075u, 0x00050083u, 0x0000000du, - 0x00000079u, 0x0000006cu, 0x00000078u, 0x0008000cu, 0x0000000du, 0x0000007au, 0x00000001u, 0x0000002bu, - 0x00000073u, 0x00000076u, 0x00000079u, 0x0003003eu, 0x00000070u, 0x0000007au, 0x0004003du, 0x00000023u, - 0x0000007du, 0x00000025u, 0x0004003du, 0x0000000du, 0x0000007eu, 0x00000070u, 0x00050057u, 0x0000002fu, - 0x0000007fu, 0x0000007du, 0x0000007eu, 0x0003003eu, 0x0000007cu, 0x0000007fu, 0x0004003du, 0x0000002fu, - 0x00000082u, 0x0000007cu, 0x0008004fu, 0x00000007u, 0x00000083u, 0x00000082u, 0x00000082u, 0x00000000u, - 0x00000001u, 0x00000002u, 0x0003003eu, 0x00000081u, 0x00000083u, 0x00050039u, 0x00000006u, 0x00000084u, - 0x0000000bu, 0x00000081u, 0x0003003eu, 0x00000080u, 0x00000084u, 0x0004003du, 0x00000023u, 0x00000086u, - 0x00000025u, 0x0004003du, 0x0000000du, 0x00000087u, 0x00000070u, 0x00050041u, 0x00000020u, 0x00000088u, - 0x00000062u, 0x00000029u, 0x0004003du, 0x00000006u, 0x00000089u, 0x00000088u, 0x00050050u, 0x0000000du, - 0x0000008au, 0x00000089u, 0x0000002cu, 0x00050083u, 0x0000000du, 0x0000008bu, 0x00000087u, 0x0000008au, - 0x00050057u, 0x0000002fu, 0x0000008cu, 0x00000086u, 0x0000008bu, 0x0008004fu, 0x00000007u, 0x0000008eu, - 0x0000008cu, 0x0000008cu, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x0000008du, 0x0000008eu, - 0x00050039u, 0x00000006u, 0x0000008fu, 0x0000000bu, 0x0000008du, 0x0003003eu, 0x00000085u, 0x0000008fu, - 0x0004003du, 0x00000023u, 0x00000091u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000092u, 0x00000070u, - 0x00050041u, 0x00000020u, 0x00000093u, 0x00000062u, 0x00000029u, 0x0004003du, 0x00000006u, 0x00000094u, - 0x00000093u, 0x00050050u, 0x0000000du, 0x00000095u, 0x00000094u, 0x0000002cu, 0x00050081u, 0x0000000du, - 0x00000096u, 0x00000092u, 0x00000095u, 0x00050057u, 0x0000002fu, 0x00000097u, 0x00000091u, 0x00000096u, - 0x0008004fu, 0x00000007u, 0x00000099u, 0x00000097u, 0x00000097u, 0x00000000u, 0x00000001u, 0x00000002u, - 0x0003003eu, 0x00000098u, 0x00000099u, 0x00050039u, 0x00000006u, 0x0000009au, 0x0000000bu, 0x00000098u, - 0x0003003eu, 0x00000090u, 0x0000009au, 0x0004003du, 0x00000023u, 0x0000009cu, 0x00000025u, 0x0004003du, - 0x0000000du, 0x0000009du, 0x00000070u, 0x00050041u, 0x00000020u, 0x0000009eu, 0x00000062u, 0x00000048u, - 0x0004003du, 0x00000006u, 0x0000009fu, 0x0000009eu, 0x00050050u, 0x0000000du, 0x000000a0u, 0x0000002cu, - 0x0000009fu, 0x00050083u, 0x0000000du, 0x000000a1u, 0x0000009du, 0x000000a0u, 0x00050057u, 0x0000002fu, - 0x000000a2u, 0x0000009cu, 0x000000a1u, 0x0008004fu, 0x00000007u, 0x000000a4u, 0x000000a2u, 0x000000a2u, - 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x000000a3u, 0x000000a4u, 0x00050039u, 0x00000006u, - 0x000000a5u, 0x0000000bu, 0x000000a3u, 0x0003003eu, 0x0000009bu, 0x000000a5u, 0x0004003du, 0x00000023u, - 0x000000a7u, 0x00000025u, 0x0004003du, 0x0000000du, 0x000000a8u, 0x00000070u, 0x00050041u, 0x00000020u, - 0x000000a9u, 0x00000062u, 0x00000048u, 0x0004003du, 0x00000006u, 0x000000aau, 0x000000a9u, 0x00050050u, - 0x0000000du, 0x000000abu, 0x0000002cu, 0x000000aau, 0x00050081u, 0x0000000du, 0x000000acu, 0x000000a8u, - 0x000000abu, 0x00050057u, 0x0000002fu, 0x000000adu, 0x000000a7u, 0x000000acu, 0x0008004fu, 0x00000007u, - 0x000000afu, 0x000000adu, 0x000000adu, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x000000aeu, - 0x000000afu, 0x00050039u, 0x00000006u, 0x000000b0u, 0x0000000bu, 0x000000aeu, 0x0003003eu, 0x000000a6u, - 0x000000b0u, 0x0004003du, 0x00000006u, 0x000000b2u, 0x00000080u, 0x0004003du, 0x00000006u, 0x000000b3u, - 0x00000085u, 0x00050083u, 0x00000006u, 0x000000b4u, 0x000000b2u, 0x000000b3u, 0x0006000cu, 0x00000006u, - 0x000000b5u, 0x00000001u, 0x00000004u, 0x000000b4u, 0x0003003eu, 0x000000b1u, 0x000000b5u, 0x0004003du, - 0x00000006u, 0x000000b7u, 0x00000080u, 0x0004003du, 0x00000006u, 0x000000b8u, 0x00000090u, 0x00050083u, - 0x00000006u, 0x000000b9u, 0x000000b7u, 0x000000b8u, 0x0006000cu, 0x00000006u, 0x000000bau, 0x00000001u, - 0x00000004u, 0x000000b9u, 0x0003003eu, 0x000000b6u, 0x000000bau, 0x0004003du, 0x00000006u, 0x000000bcu, - 0x00000080u, 0x0004003du, 0x00000006u, 0x000000bdu, 0x0000009bu, 0x00050083u, 0x00000006u, 0x000000beu, - 0x000000bcu, 0x000000bdu, 0x0006000cu, 0x00000006u, 0x000000bfu, 0x00000001u, 0x00000004u, 0x000000beu, - 0x0003003eu, 0x000000bbu, 0x000000bfu, 0x0004003du, 0x00000006u, 0x000000c1u, 0x00000080u, 0x0004003du, - 0x00000006u, 0x000000c2u, 0x000000a6u, 0x00050083u, 0x00000006u, 0x000000c3u, 0x000000c1u, 0x000000c2u, - 0x0006000cu, 0x00000006u, 0x000000c4u, 0x00000001u, 0x00000004u, 0x000000c3u, 0x0003003eu, 0x000000c0u, - 0x000000c4u, 0x0004003du, 0x00000006u, 0x000000c6u, 0x00000080u, 0x0004003du, 0x00000006u, 0x000000c7u, - 0x00000085u, 0x0004003du, 0x00000006u, 0x000000c8u, 0x00000090u, 0x0007000cu, 0x00000006u, 0x000000c9u, - 0x00000001u, 0x00000025u, 0x000000c7u, 0x000000c8u, 0x0004003du, 0x00000006u, 0x000000cau, 0x0000009bu, - 0x0004003du, 0x00000006u, 0x000000cbu, 0x000000a6u, 0x0007000cu, 0x00000006u, 0x000000ccu, 0x00000001u, - 0x00000025u, 0x000000cau, 0x000000cbu, 0x0007000cu, 0x00000006u, 0x000000cdu, 0x00000001u, 0x00000025u, - 0x000000c9u, 0x000000ccu, 0x0007000cu, 0x00000006u, 0x000000ceu, 0x00000001u, 0x00000025u, 0x000000c6u, - 0x000000cdu, 0x0003003eu, 0x000000c5u, 0x000000ceu, 0x0004003du, 0x00000006u, 0x000000d0u, 0x00000080u, - 0x0004003du, 0x00000006u, 0x000000d1u, 0x00000085u, 0x0004003du, 0x00000006u, 0x000000d2u, 0x00000090u, - 0x0007000cu, 0x00000006u, 0x000000d3u, 0x00000001u, 0x00000028u, 0x000000d1u, 0x000000d2u, 0x0004003du, - 0x00000006u, 0x000000d4u, 0x0000009bu, 0x0004003du, 0x00000006u, 0x000000d5u, 0x000000a6u, 0x0007000cu, - 0x00000006u, 0x000000d6u, 0x00000001u, 0x00000028u, 0x000000d4u, 0x000000d5u, 0x0007000cu, 0x00000006u, - 0x000000d7u, 0x00000001u, 0x00000028u, 0x000000d3u, 0x000000d6u, 0x0007000cu, 0x00000006u, 0x000000d8u, - 0x00000001u, 0x00000028u, 0x000000d0u, 0x000000d7u, 0x0003003eu, 0x000000cfu, 0x000000d8u, 0x0004003du, - 0x00000006u, 0x000000dau, 0x000000cfu, 0x0004003du, 0x00000006u, 0x000000dbu, 0x000000c5u, 0x00050083u, - 0x00000006u, 0x000000dcu, 0x000000dau, 0x000000dbu, 0x0003003eu, 0x000000d9u, 0x000000dcu, 0x0004003du, - 0x00000006u, 0x000000dfu, 0x000000d9u, 0x00050085u, 0x00000006u, 0x000000e1u, 0x000000dfu, 0x000000e0u, - 0x0007000cu, 0x00000006u, 0x000000e2u, 0x00000001u, 0x00000028u, 0x000000deu, 0x000000e1u, 0x0003003eu, - 0x000000ddu, 0x000000e2u, 0x0004003du, 0x00000006u, 0x000000e4u, 0x000000b1u, 0x0004003du, 0x00000006u, - 0x000000e5u, 0x000000b6u, 0x0007000cu, 0x00000006u, 0x000000e6u, 0x00000001u, 0x00000028u, 0x000000e4u, - 0x000000e5u, 0x0003003eu, 0x000000e3u, 0x000000e6u, 0x0004003du, 0x00000006u, 0x000000e8u, 0x000000bbu, - 0x0004003du, 0x00000006u, 0x000000e9u, 0x000000c0u, 0x0007000cu, 0x00000006u, 0x000000eau, 0x00000001u, - 0x00000028u, 0x000000e8u, 0x000000e9u, 0x0003003eu, 0x000000e7u, 0x000000eau, 0x0004003du, 0x00000006u, - 0x000000ecu, 0x000000e3u, 0x0004003du, 0x00000006u, 0x000000edu, 0x000000e7u, 0x0007000cu, 0x00000006u, - 0x000000eeu, 0x00000001u, 0x00000028u, 0x000000ecu, 0x000000edu, 0x0003003eu, 0x000000ebu, 0x000000eeu, - 0x0004003du, 0x00000006u, 0x000000efu, 0x000000ebu, 0x0004003du, 0x00000006u, 0x000000f0u, 0x000000ddu, - 0x000500bcu, 0x000000f1u, 0x000000f2u, 0x000000efu, 0x000000f0u, 0x000300f7u, 0x000000f4u, 0x00000000u, - 0x000400fau, 0x000000f2u, 0x000000f3u, 0x000000f4u, 0x000200f8u, 0x000000f3u, 0x0004003du, 0x0000002fu, - 0x000000f7u, 0x0000007cu, 0x0003003eu, 0x000000f6u, 0x000000f7u, 0x000100fdu, 0x000200f8u, 0x000000f4u, - 0x0004003du, 0x00000006u, 0x000000fbu, 0x000000e3u, 0x0004003du, 0x00000006u, 0x000000fcu, 0x000000e7u, - 0x000500beu, 0x000000f1u, 0x000000fdu, 0x000000fbu, 0x000000fcu, 0x0003003eu, 0x000000fau, 0x000000fdu, - 0x0004003du, 0x000000f1u, 0x000000ffu, 0x000000fau, 0x000300f7u, 0x00000102u, 0x00000000u, 0x000400fau, - 0x000000ffu, 0x00000101u, 0x00000106u, 0x000200f8u, 0x00000101u, 0x00050041u, 0x00000020u, 0x00000103u, - 0x00000062u, 0x00000048u, 0x0004003du, 0x00000006u, 0x00000104u, 0x00000103u, 0x00050050u, 0x0000000du, - 0x00000105u, 0x0000002cu, 0x00000104u, 0x0003003eu, 0x00000100u, 0x00000105u, 0x000200f9u, 0x00000102u, - 0x000200f8u, 0x00000106u, 0x00050041u, 0x00000020u, 0x00000107u, 0x00000062u, 0x00000029u, 0x0004003du, - 0x00000006u, 0x00000108u, 0x00000107u, 0x00050050u, 0x0000000du, 0x00000109u, 0x00000108u, 0x0000002cu, - 0x0003003eu, 0x00000100u, 0x00000109u, 0x000200f9u, 0x00000102u, 0x000200f8u, 0x00000102u, 0x0004003du, - 0x0000000du, 0x0000010au, 0x00000100u, 0x0003003eu, 0x000000feu, 0x0000010au, 0x0004003du, 0x000000f1u, - 0x0000010cu, 0x000000fau, 0x000300f7u, 0x0000010fu, 0x00000000u, 0x000400fau, 0x0000010cu, 0x0000010eu, - 0x00000116u, 0x000200f8u, 0x0000010eu, 0x0004003du, 0x00000006u, 0x00000110u, 0x000000b1u, 0x0004003du, - 0x00000006u, 0x00000111u, 0x000000b6u, 0x000500beu, 0x000000f1u, 0x00000112u, 0x00000110u, 0x00000111u, - 0x000600a9u, 0x00000006u, 0x00000114u, 0x00000112u, 0x00000113u, 0x00000063u, 0x00050050u, 0x0000000du, - 0x00000115u, 0x00000114u, 0x0000002cu, 0x0003003eu, 0x0000010du, 0x00000115u, 0x000200f9u, 0x0000010fu, - 0x000200f8u, 0x00000116u, 0x0004003du, 0x00000006u, 0x00000117u, 0x000000bbu, 0x0004003du, 0x00000006u, - 0x00000118u, 0x000000c0u, 0x000500beu, 0x000000f1u, 0x00000119u, 0x00000117u, 0x00000118u, 0x000600a9u, - 0x00000006u, 0x0000011au, 0x00000119u, 0x00000113u, 0x00000063u, 0x00050050u, 0x0000000du, 0x0000011bu, - 0x0000002cu, 0x0000011au, 0x0003003eu, 0x0000010du, 0x0000011bu, 0x000200f9u, 0x0000010fu, 0x000200f8u, - 0x0000010fu, 0x0004003du, 0x0000000du, 0x0000011cu, 0x0000010du, 0x0003003eu, 0x0000010bu, 0x0000011cu, - 0x0003003eu, 0x0000011du, 0x0000002cu, 0x0003003eu, 0x0000011eu, 0x0000002cu, 0x0003003eu, 0x00000120u, - 0x00000068u, 0x000200f9u, 0x00000121u, 0x000200f8u, 0x00000121u, 0x000400f6u, 0x00000123u, 0x00000124u, - 0x00000000u, 0x000200f9u, 0x00000125u, 0x000200f8u, 0x00000125u, 0x0004003du, 0x00000067u, 0x00000126u, - 0x00000120u, 0x000500b3u, 0x000000f1u, 0x00000128u, 0x00000126u, 0x00000127u, 0x000400fau, 0x00000128u, - 0x00000122u, 0x00000123u, 0x000200f8u, 0x00000122u, 0x0004003du, 0x0000000du, 0x0000012au, 0x000000feu, - 0x0004003du, 0x00000067u, 0x0000012bu, 0x00000120u, 0x0004006fu, 0x00000006u, 0x0000012cu, 0x0000012bu, - 0x0005008eu, 0x0000000du, 0x0000012du, 0x0000012au, 0x0000012cu, 0x0003003eu, 0x00000129u, 0x0000012du, - 0x0004003du, 0x000000f1u, 0x0000012fu, 0x000000fau, 0x000300f7u, 0x00000132u, 0x00000000u, 0x000400fau, - 0x0000012fu, 0x00000131u, 0x0000013au, 0x000200f8u, 0x00000131u, 0x0004003du, 0x0000000du, 0x00000133u, - 0x00000070u, 0x0004003du, 0x0000000du, 0x00000134u, 0x00000129u, 0x00050083u, 0x0000000du, 0x00000135u, - 0x00000133u, 0x00000134u, 0x0003003eu, 0x00000136u, 0x00000135u, 0x0004003du, 0x0000000du, 0x00000138u, - 0x00000062u, 0x0003003eu, 0x00000137u, 0x00000138u, 0x00060039u, 0x00000006u, 0x00000139u, 0x00000012u, - 0x00000136u, 0x00000137u, 0x0003003eu, 0x00000130u, 0x00000139u, 0x000200f9u, 0x00000132u, 0x000200f8u, - 0x0000013au, 0x0004003du, 0x0000000du, 0x0000013bu, 0x00000070u, 0x0004003du, 0x0000000du, 0x0000013cu, - 0x00000129u, 0x00050083u, 0x0000000du, 0x0000013du, 0x0000013bu, 0x0000013cu, 0x0003003eu, 0x0000013eu, - 0x0000013du, 0x0004003du, 0x0000000du, 0x00000140u, 0x00000062u, 0x0003003eu, 0x0000013fu, 0x00000140u, - 0x00060039u, 0x00000006u, 0x00000141u, 0x00000016u, 0x0000013eu, 0x0000013fu, 0x0003003eu, 0x00000130u, - 0x00000141u, 0x000200f9u, 0x00000132u, 0x000200f8u, 0x00000132u, 0x0004003du, 0x00000006u, 0x00000142u, - 0x00000130u, 0x0003003eu, 0x0000012eu, 0x00000142u, 0x0004003du, 0x000000f1u, 0x00000144u, 0x000000fau, - 0x000300f7u, 0x00000147u, 0x00000000u, 0x000400fau, 0x00000144u, 0x00000146u, 0x0000014fu, 0x000200f8u, - 0x00000146u, 0x0004003du, 0x0000000du, 0x00000148u, 0x00000070u, 0x0004003du, 0x0000000du, 0x00000149u, - 0x00000129u, 0x00050081u, 0x0000000du, 0x0000014au, 0x00000148u, 0x00000149u, 0x0003003eu, 0x0000014bu, - 0x0000014au, 0x0004003du, 0x0000000du, 0x0000014du, 0x00000062u, 0x0003003eu, 0x0000014cu, 0x0000014du, - 0x00060039u, 0x00000006u, 0x0000014eu, 0x00000012u, 0x0000014bu, 0x0000014cu, 0x0003003eu, 0x00000145u, - 0x0000014eu, 0x000200f9u, 0x00000147u, 0x000200f8u, 0x0000014fu, 0x0004003du, 0x0000000du, 0x00000150u, - 0x00000070u, 0x0004003du, 0x0000000du, 0x00000151u, 0x00000129u, 0x00050081u, 0x0000000du, 0x00000152u, - 0x00000150u, 0x00000151u, 0x0003003eu, 0x00000153u, 0x00000152u, 0x0004003du, 0x0000000du, 0x00000155u, - 0x00000062u, 0x0003003eu, 0x00000154u, 0x00000155u, 0x00060039u, 0x00000006u, 0x00000156u, 0x00000016u, - 0x00000153u, 0x00000154u, 0x0003003eu, 0x00000145u, 0x00000156u, 0x000200f9u, 0x00000147u, 0x000200f8u, - 0x00000147u, 0x0004003du, 0x00000006u, 0x00000157u, 0x00000145u, 0x0003003eu, 0x00000143u, 0x00000157u, - 0x0004003du, 0x00000006u, 0x00000158u, 0x0000011du, 0x0004003du, 0x00000067u, 0x00000159u, 0x00000120u, - 0x00050082u, 0x00000067u, 0x0000015au, 0x00000159u, 0x00000068u, 0x0004006fu, 0x00000006u, 0x0000015bu, - 0x0000015au, 0x000500b4u, 0x000000f1u, 0x0000015cu, 0x00000158u, 0x0000015bu, 0x000300f7u, 0x0000015eu, - 0x00000000u, 0x000400fau, 0x0000015cu, 0x0000015du, 0x0000015eu, 0x000200f8u, 0x0000015du, 0x0004003du, - 0x00000006u, 0x0000015fu, 0x0000012eu, 0x0004003du, 0x00000006u, 0x00000160u, 0x000000ddu, 0x00050085u, - 0x00000006u, 0x00000162u, 0x00000160u, 0x00000161u, 0x000500bau, 0x000000f1u, 0x00000163u, 0x0000015fu, - 0x00000162u, 0x000200f9u, 0x0000015eu, 0x000200f8u, 0x0000015eu, 0x000700f5u, 0x000000f1u, 0x00000164u, - 0x0000015cu, 0x00000147u, 0x00000163u, 0x0000015du, 0x000300f7u, 0x00000166u, 0x00000000u, 0x000400fau, - 0x00000164u, 0x00000165u, 0x00000166u, 0x000200f8u, 0x00000165u, 0x0004003du, 0x00000067u, 0x00000167u, - 0x00000120u, 0x0004006fu, 0x00000006u, 0x00000168u, 0x00000167u, 0x0003003eu, 0x0000011du, 0x00000168u, - 0x000200f9u, 0x00000166u, 0x000200f8u, 0x00000166u, 0x0004003du, 0x00000006u, 0x00000169u, 0x0000011eu, - 0x0004003du, 0x00000067u, 0x0000016au, 0x00000120u, 0x00050082u, 0x00000067u, 0x0000016bu, 0x0000016au, - 0x00000068u, 0x0004006fu, 0x00000006u, 0x0000016cu, 0x0000016bu, 0x000500b4u, 0x000000f1u, 0x0000016du, - 0x00000169u, 0x0000016cu, 0x000300f7u, 0x0000016fu, 0x00000000u, 0x000400fau, 0x0000016du, 0x0000016eu, - 0x0000016fu, 0x000200f8u, 0x0000016eu, 0x0004003du, 0x00000006u, 0x00000170u, 0x00000143u, 0x0004003du, - 0x00000006u, 0x00000171u, 0x000000ddu, 0x00050085u, 0x00000006u, 0x00000172u, 0x00000171u, 0x00000161u, - 0x000500bau, 0x000000f1u, 0x00000173u, 0x00000170u, 0x00000172u, 0x000200f9u, 0x0000016fu, 0x000200f8u, - 0x0000016fu, 0x000700f5u, 0x000000f1u, 0x00000174u, 0x0000016du, 0x00000166u, 0x00000173u, 0x0000016eu, - 0x000300f7u, 0x00000176u, 0x00000000u, 0x000400fau, 0x00000174u, 0x00000175u, 0x00000176u, 0x000200f8u, - 0x00000175u, 0x0004003du, 0x00000067u, 0x00000177u, 0x00000120u, 0x0004006fu, 0x00000006u, 0x00000178u, - 0x00000177u, 0x0003003eu, 0x0000011eu, 0x00000178u, 0x000200f9u, 0x00000176u, 0x000200f8u, 0x00000176u, - 0x000200f9u, 0x00000124u, 0x000200f8u, 0x00000124u, 0x0004003du, 0x00000067u, 0x00000179u, 0x00000120u, - 0x00050080u, 0x00000067u, 0x0000017au, 0x00000179u, 0x00000068u, 0x0003003eu, 0x00000120u, 0x0000017au, - 0x000200f9u, 0x00000121u, 0x000200f8u, 0x00000123u, 0x0004003du, 0x00000006u, 0x0000017cu, 0x0000011du, - 0x0004003du, 0x00000006u, 0x0000017du, 0x0000011eu, 0x00050081u, 0x00000006u, 0x0000017eu, 0x0000017cu, - 0x0000017du, 0x0003003eu, 0x0000017bu, 0x0000017eu, 0x0004003du, 0x00000006u, 0x00000180u, 0x000000ddu, - 0x0004003du, 0x00000006u, 0x00000181u, 0x000000ddu, 0x00050085u, 0x00000006u, 0x00000183u, 0x00000181u, - 0x00000182u, 0x0004003du, 0x00000006u, 0x00000184u, 0x000000ebu, 0x0008000cu, 0x00000006u, 0x00000185u, - 0x00000001u, 0x00000031u, 0x00000180u, 0x00000183u, 0x00000184u, 0x0003003eu, 0x0000017fu, 0x00000185u, - 0x0004003du, 0x00000023u, 0x00000187u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000188u, 0x00000070u, - 0x00050041u, 0x00000020u, 0x00000189u, 0x00000062u, 0x00000029u, 0x0004003du, 0x00000006u, 0x0000018au, - 0x00000189u, 0x0004007fu, 0x00000006u, 0x0000018bu, 0x0000018au, 0x00050041u, 0x00000020u, 0x0000018cu, - 0x00000062u, 0x00000048u, 0x0004003du, 0x00000006u, 0x0000018du, 0x0000018cu, 0x0004007fu, 0x00000006u, - 0x0000018eu, 0x0000018du, 0x00050050u, 0x0000000du, 0x0000018fu, 0x0000018bu, 0x0000018eu, 0x00050081u, - 0x0000000du, 0x00000190u, 0x00000188u, 0x0000018fu, 0x00050057u, 0x0000002fu, 0x00000191u, 0x00000187u, - 0x00000190u, 0x0008004fu, 0x00000007u, 0x00000193u, 0x00000191u, 0x00000191u, 0x00000000u, 0x00000001u, - 0x00000002u, 0x0003003eu, 0x00000192u, 0x00000193u, 0x00050039u, 0x00000006u, 0x00000194u, 0x0000000bu, - 0x00000192u, 0x0003003eu, 0x00000186u, 0x00000194u, 0x0004003du, 0x00000023u, 0x00000196u, 0x00000025u, - 0x0004003du, 0x0000000du, 0x00000197u, 0x00000070u, 0x00050041u, 0x00000020u, 0x00000198u, 0x00000062u, - 0x00000029u, 0x0004003du, 0x00000006u, 0x00000199u, 0x00000198u, 0x00050041u, 0x00000020u, 0x0000019au, - 0x00000062u, 0x00000048u, 0x0004003du, 0x00000006u, 0x0000019bu, 0x0000019au, 0x0004007fu, 0x00000006u, - 0x0000019cu, 0x0000019bu, 0x00050050u, 0x0000000du, 0x0000019du, 0x00000199u, 0x0000019cu, 0x00050081u, - 0x0000000du, 0x0000019eu, 0x00000197u, 0x0000019du, 0x00050057u, 0x0000002fu, 0x0000019fu, 0x00000196u, - 0x0000019eu, 0x0008004fu, 0x00000007u, 0x000001a1u, 0x0000019fu, 0x0000019fu, 0x00000000u, 0x00000001u, - 0x00000002u, 0x0003003eu, 0x000001a0u, 0x000001a1u, 0x00050039u, 0x00000006u, 0x000001a2u, 0x0000000bu, - 0x000001a0u, 0x0003003eu, 0x00000195u, 0x000001a2u, 0x0004003du, 0x00000023u, 0x000001a4u, 0x00000025u, - 0x0004003du, 0x0000000du, 0x000001a5u, 0x00000070u, 0x00050041u, 0x00000020u, 0x000001a6u, 0x00000062u, - 0x00000029u, 0x0004003du, 0x00000006u, 0x000001a7u, 0x000001a6u, 0x0004007fu, 0x00000006u, 0x000001a8u, - 0x000001a7u, 0x00050041u, 0x00000020u, 0x000001a9u, 0x00000062u, 0x00000048u, 0x0004003du, 0x00000006u, - 0x000001aau, 0x000001a9u, 0x00050050u, 0x0000000du, 0x000001abu, 0x000001a8u, 0x000001aau, 0x00050081u, - 0x0000000du, 0x000001acu, 0x000001a5u, 0x000001abu, 0x00050057u, 0x0000002fu, 0x000001adu, 0x000001a4u, - 0x000001acu, 0x0008004fu, 0x00000007u, 0x000001afu, 0x000001adu, 0x000001adu, 0x00000000u, 0x00000001u, - 0x00000002u, 0x0003003eu, 0x000001aeu, 0x000001afu, 0x00050039u, 0x00000006u, 0x000001b0u, 0x0000000bu, - 0x000001aeu, 0x0003003eu, 0x000001a3u, 0x000001b0u, 0x0004003du, 0x00000023u, 0x000001b2u, 0x00000025u, - 0x0004003du, 0x0000000du, 0x000001b3u, 0x00000070u, 0x00050041u, 0x00000020u, 0x000001b4u, 0x00000062u, - 0x00000029u, 0x0004003du, 0x00000006u, 0x000001b5u, 0x000001b4u, 0x00050041u, 0x00000020u, 0x000001b6u, - 0x00000062u, 0x00000048u, 0x0004003du, 0x00000006u, 0x000001b7u, 0x000001b6u, 0x00050050u, 0x0000000du, - 0x000001b8u, 0x000001b5u, 0x000001b7u, 0x00050081u, 0x0000000du, 0x000001b9u, 0x000001b3u, 0x000001b8u, - 0x00050057u, 0x0000002fu, 0x000001bau, 0x000001b2u, 0x000001b9u, 0x0008004fu, 0x00000007u, 0x000001bcu, - 0x000001bau, 0x000001bau, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x000001bbu, 0x000001bcu, - 0x00050039u, 0x00000006u, 0x000001bdu, 0x0000000bu, 0x000001bbu, 0x0003003eu, 0x000001b1u, 0x000001bdu, - 0x0004003du, 0x00000006u, 0x000001bfu, 0x0000011du, 0x0004003du, 0x00000006u, 0x000001c0u, 0x0000011eu, - 0x00050083u, 0x00000006u, 0x000001c1u, 0x000001bfu, 0x000001c0u, 0x0006000cu, 0x00000006u, 0x000001c2u, - 0x00000001u, 0x00000004u, 0x000001c1u, 0x0004003du, 0x00000006u, 0x000001c3u, 0x0000017bu, 0x0007000cu, - 0x00000006u, 0x000001c4u, 0x00000001u, 0x00000028u, 0x000001c3u, 0x00000063u, 0x00050088u, 0x00000006u, - 0x000001c5u, 0x000001c2u, 0x000001c4u, 0x0008000cu, 0x00000006u, 0x000001c6u, 0x00000001u, 0x0000002bu, - 0x000001c5u, 0x0000002cu, 0x00000063u, 0x0003003eu, 0x000001beu, 0x000001c6u, 0x0004003du, 0x00000006u, - 0x000001c8u, 0x000001beu, 0x0004003du, 0x00000006u, 0x000001c9u, 0x0000017bu, 0x00050085u, 0x00000006u, - 0x000001cbu, 0x000001c9u, 0x000001cau, 0x00050081u, 0x00000006u, 0x000001ccu, 0x00000063u, 0x000001cbu, - 0x00050088u, 0x00000006u, 0x000001cdu, 0x000001c8u, 0x000001ccu, 0x0003003eu, 0x000001c7u, 0x000001cdu, - 0x0004003du, 0x000000f1u, 0x000001cfu, 0x000000fau, 0x000300f7u, 0x000001d2u, 0x00000000u, 0x000400fau, - 0x000001cfu, 0x000001d1u, 0x000001d7u, 0x000200f8u, 0x000001d1u, 0x0004003du, 0x00000006u, 0x000001d3u, - 0x00000186u, 0x0004003du, 0x00000006u, 0x000001d4u, 0x00000195u, 0x00050083u, 0x00000006u, 0x000001d5u, - 0x000001d3u, 0x000001d4u, 0x0006000cu, 0x00000006u, 0x000001d6u, 0x00000001u, 0x00000004u, 0x000001d5u, - 0x0003003eu, 0x000001d0u, 0x000001d6u, 0x000200f9u, 0x000001d2u, 0x000200f8u, 0x000001d7u, 0x0004003du, - 0x00000006u, 0x000001d8u, 0x00000186u, 0x0004003du, 0x00000006u, 0x000001d9u, 0x000001a3u, 0x00050083u, - 0x00000006u, 0x000001dau, 0x000001d8u, 0x000001d9u, 0x0006000cu, 0x00000006u, 0x000001dbu, 0x00000001u, - 0x00000004u, 0x000001dau, 0x0003003eu, 0x000001d0u, 0x000001dbu, 0x000200f9u, 0x000001d2u, 0x000200f8u, - 0x000001d2u, 0x0004003du, 0x00000006u, 0x000001dcu, 0x000001d0u, 0x0003003eu, 0x000001ceu, 0x000001dcu, - 0x0004003du, 0x000000f1u, 0x000001deu, 0x000000fau, 0x000300f7u, 0x000001e1u, 0x00000000u, 0x000400fau, - 0x000001deu, 0x000001e0u, 0x000001e6u, 0x000200f8u, 0x000001e0u, 0x0004003du, 0x00000006u, 0x000001e2u, - 0x000001a3u, 0x0004003du, 0x00000006u, 0x000001e3u, 0x000001b1u, 0x00050083u, 0x00000006u, 0x000001e4u, - 0x000001e2u, 0x000001e3u, 0x0006000cu, 0x00000006u, 0x000001e5u, 0x00000001u, 0x00000004u, 0x000001e4u, - 0x0003003eu, 0x000001dfu, 0x000001e5u, 0x000200f9u, 0x000001e1u, 0x000200f8u, 0x000001e6u, 0x0004003du, - 0x00000006u, 0x000001e7u, 0x00000195u, 0x0004003du, 0x00000006u, 0x000001e8u, 0x000001b1u, 0x00050083u, - 0x00000006u, 0x000001e9u, 0x000001e7u, 0x000001e8u, 0x0006000cu, 0x00000006u, 0x000001eau, 0x00000001u, - 0x00000004u, 0x000001e9u, 0x0003003eu, 0x000001dfu, 0x000001eau, 0x000200f9u, 0x000001e1u, 0x000200f8u, - 0x000001e1u, 0x0004003du, 0x00000006u, 0x000001ebu, 0x000001dfu, 0x0003003eu, 0x000001ddu, 0x000001ebu, - 0x0004003du, 0x00000006u, 0x000001edu, 0x000001ceu, 0x0004003du, 0x00000006u, 0x000001eeu, 0x000001ddu, - 0x00050083u, 0x00000006u, 0x000001efu, 0x000001edu, 0x000001eeu, 0x0006000cu, 0x00000006u, 0x000001f0u, - 0x00000001u, 0x00000004u, 0x000001efu, 0x0003003eu, 0x000001ecu, 0x000001f0u, 0x0004003du, 0x00000006u, - 0x000001f2u, 0x000000ddu, 0x0004003du, 0x00000006u, 0x000001f3u, 0x000000ddu, 0x00050085u, 0x00000006u, - 0x000001f4u, 0x000001f3u, 0x00000182u, 0x0004003du, 0x00000006u, 0x000001f5u, 0x000001ecu, 0x0008000cu, - 0x00000006u, 0x000001f6u, 0x00000001u, 0x00000031u, 0x000001f2u, 0x000001f4u, 0x000001f5u, 0x0003003eu, - 0x000001f1u, 0x000001f6u, 0x0004003du, 0x00000006u, 0x000001f9u, 0x000001f1u, 0x00050085u, 0x00000006u, - 0x000001fau, 0x000001f8u, 0x000001f9u, 0x0004003du, 0x00000006u, 0x000001fbu, 0x0000017bu, 0x00050088u, - 0x00000006u, 0x000001fdu, 0x000001fbu, 0x000001fcu, 0x0008000cu, 0x00000006u, 0x000001feu, 0x00000001u, - 0x0000002bu, 0x000001fdu, 0x0000002cu, 0x00000063u, 0x00050085u, 0x00000006u, 0x000001ffu, 0x000001fau, - 0x000001feu, 0x0003003eu, 0x000001f7u, 0x000001ffu, 0x0004003du, 0x00000006u, 0x00000201u, 0x00000186u, - 0x0004003du, 0x00000006u, 0x00000202u, 0x000001b1u, 0x00050083u, 0x00000006u, 0x00000203u, 0x00000201u, - 0x00000202u, 0x0006000cu, 0x00000006u, 0x00000204u, 0x00000001u, 0x00000004u, 0x00000203u, 0x0004003du, - 0x00000006u, 0x00000205u, 0x00000195u, 0x0004003du, 0x00000006u, 0x00000206u, 0x000001a3u, 0x00050083u, - 0x00000006u, 0x00000207u, 0x00000205u, 0x00000206u, 0x0006000cu, 0x00000006u, 0x00000208u, 0x00000001u, - 0x00000004u, 0x00000207u, 0x0007000cu, 0x00000006u, 0x00000209u, 0x00000001u, 0x00000028u, 0x00000204u, - 0x00000208u, 0x0003003eu, 0x00000200u, 0x00000209u, 0x0004003du, 0x00000006u, 0x0000020cu, 0x000000ddu, - 0x0004003du, 0x00000006u, 0x0000020du, 0x000000ddu, 0x00050085u, 0x00000006u, 0x0000020fu, 0x0000020du, - 0x0000020eu, 0x0004003du, 0x00000006u, 0x00000210u, 0x00000200u, 0x0008000cu, 0x00000006u, 0x00000211u, - 0x00000001u, 0x00000031u, 0x0000020cu, 0x0000020fu, 0x00000210u, 0x00050085u, 0x00000006u, 0x00000212u, - 0x0000020bu, 0x00000211u, 0x00050083u, 0x00000006u, 0x00000213u, 0x00000063u, 0x00000212u, 0x0003003eu, - 0x0000020au, 0x00000213u, 0x0004003du, 0x00000006u, 0x00000215u, 0x000001f7u, 0x0004003du, 0x00000006u, - 0x00000216u, 0x000001c7u, 0x00050085u, 0x00000006u, 0x00000217u, 0x00000215u, 0x00000216u, 0x0004003du, - 0x00000006u, 0x00000218u, 0x0000017fu, 0x00050085u, 0x00000006u, 0x00000219u, 0x00000217u, 0x00000218u, - 0x0004003du, 0x00000006u, 0x0000021au, 0x0000020au, 0x00050085u, 0x00000006u, 0x0000021bu, 0x00000219u, - 0x0000021au, 0x0003003eu, 0x00000214u, 0x0000021bu, 0x0004003du, 0x00000006u, 0x0000021du, 0x00000186u, - 0x0004003du, 0x00000006u, 0x0000021eu, 0x000001b1u, 0x00050083u, 0x00000006u, 0x0000021fu, 0x0000021du, - 0x0000021eu, 0x0006000cu, 0x00000006u, 0x00000220u, 0x00000001u, 0x00000004u, 0x0000021fu, 0x0004003du, - 0x00000006u, 0x00000221u, 0x00000195u, 0x0004003du, 0x00000006u, 0x00000222u, 0x000001a3u, 0x00050083u, - 0x00000006u, 0x00000223u, 0x00000221u, 0x00000222u, 0x0006000cu, 0x00000006u, 0x00000224u, 0x00000001u, - 0x00000004u, 0x00000223u, 0x00050083u, 0x00000006u, 0x00000225u, 0x00000220u, 0x00000224u, 0x0006000cu, - 0x00000006u, 0x00000226u, 0x00000001u, 0x00000004u, 0x00000225u, 0x0003003eu, 0x0000021cu, 0x00000226u, - 0x0004003du, 0x00000006u, 0x00000228u, 0x000000ddu, 0x0004003du, 0x00000006u, 0x00000229u, 0x000000ddu, - 0x00050085u, 0x00000006u, 0x0000022au, 0x00000229u, 0x00000182u, 0x0004003du, 0x00000006u, 0x0000022bu, - 0x0000021cu, 0x0008000cu, 0x00000006u, 0x0000022cu, 0x00000001u, 0x00000031u, 0x00000228u, 0x0000022au, - 0x0000022bu, 0x0003003eu, 0x00000227u, 0x0000022cu, 0x0004003du, 0x00000006u, 0x0000022fu, 0x00000227u, - 0x00050085u, 0x00000006u, 0x00000230u, 0x0000022eu, 0x0000022fu, 0x0004003du, 0x00000006u, 0x00000231u, - 0x0000017fu, 0x00050085u, 0x00000006u, 0x00000232u, 0x00000230u, 0x00000231u, 0x0004003du, 0x00000006u, - 0x00000233u, 0x0000020au, 0x00050085u, 0x00000006u, 0x00000234u, 0x00000232u, 0x00000233u, 0x0003003eu, - 0x0000022du, 0x00000234u, 0x0004003du, 0x00000006u, 0x00000236u, 0x00000214u, 0x000500bcu, 0x000000f1u, - 0x00000238u, 0x00000236u, 0x00000237u, 0x0004003du, 0x00000006u, 0x00000239u, 0x0000022du, 0x0004003du, - 0x00000006u, 0x0000023au, 0x00000214u, 0x000600a9u, 0x00000006u, 0x0000023bu, 0x00000238u, 0x00000239u, - 0x0000023au, 0x0008000cu, 0x00000006u, 0x0000023du, 0x00000001u, 0x0000002bu, 0x0000023bu, 0x0000002cu, - 0x0000023cu, 0x0003003eu, 0x00000235u, 0x0000023du, 0x0004003du, 0x00000023u, 0x0000023fu, 0x00000025u, - 0x0004003du, 0x0000000du, 0x00000240u, 0x00000070u, 0x0004003du, 0x0000000du, 0x00000241u, 0x0000010bu, - 0x0004003du, 0x0000000du, 0x00000242u, 0x00000062u, 0x00050085u, 0x0000000du, 0x00000243u, 0x00000241u, - 0x00000242u, 0x00050081u, 0x0000000du, 0x00000244u, 0x00000240u, 0x00000243u, 0x00050057u, 0x0000002fu, - 0x00000245u, 0x0000023fu, 0x00000244u, 0x0008004fu, 0x00000007u, 0x00000246u, 0x00000245u, 0x00000245u, - 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x0000023eu, 0x00000246u, 0x0004003du, 0x0000002fu, - 0x00000247u, 0x0000007cu, 0x0008004fu, 0x00000007u, 0x00000248u, 0x00000247u, 0x00000247u, 0x00000000u, - 0x00000001u, 0x00000002u, 0x0004003du, 0x00000007u, 0x00000249u, 0x0000023eu, 0x0004003du, 0x00000006u, - 0x0000024au, 0x00000235u, 0x00060050u, 0x00000007u, 0x0000024bu, 0x0000024au, 0x0000024au, 0x0000024au, - 0x0008000cu, 0x00000007u, 0x0000024cu, 0x00000001u, 0x0000002eu, 0x00000248u, 0x00000249u, 0x0000024bu, - 0x00050041u, 0x00000020u, 0x0000024eu, 0x0000007cu, 0x0000024du, 0x0004003du, 0x00000006u, 0x0000024fu, - 0x0000024eu, 0x00050051u, 0x00000006u, 0x00000250u, 0x0000024cu, 0x00000000u, 0x00050051u, 0x00000006u, - 0x00000251u, 0x0000024cu, 0x00000001u, 0x00050051u, 0x00000006u, 0x00000252u, 0x0000024cu, 0x00000002u, - 0x00070050u, 0x0000002fu, 0x00000253u, 0x00000250u, 0x00000251u, 0x00000252u, 0x0000024fu, 0x0003003eu, - 0x000000f6u, 0x00000253u, 0x000100fdu, 0x00010038u, 0x00050036u, 0x00000006u, 0x0000000bu, 0x00000000u, - 0x00000009u, 0x00030037u, 0x00000008u, 0x0000000au, 0x000200f8u, 0x0000000cu, 0x0004003du, 0x00000007u, - 0x00000018u, 0x0000000au, 0x00050094u, 0x00000006u, 0x0000001du, 0x00000018u, 0x0000001cu, 0x000200feu, - 0x0000001du, 0x00010038u, 0x00050036u, 0x00000006u, 0x00000012u, 0x00000000u, 0x0000000fu, 0x00030037u, - 0x0000000eu, 0x00000010u, 0x00030037u, 0x0000000eu, 0x00000011u, 0x000200f8u, 0x00000013u, 0x0004003bu, - 0x00000020u, 0x00000021u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x00000031u, 0x00000007u, 0x0004003bu, - 0x00000020u, 0x00000034u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x0000003cu, 0x00000007u, 0x0004003du, - 0x00000023u, 0x00000026u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000027u, 0x00000010u, 0x00050041u, - 0x00000020u, 0x0000002au, 0x00000011u, 0x00000029u, 0x0004003du, 0x00000006u, 0x0000002bu, 0x0000002au, - 0x00050050u, 0x0000000du, 0x0000002du, 0x0000002bu, 0x0000002cu, 0x00050083u, 0x0000000du, 0x0000002eu, - 0x00000027u, 0x0000002du, 0x00050057u, 0x0000002fu, 0x00000030u, 0x00000026u, 0x0000002eu, 0x0008004fu, - 0x00000007u, 0x00000032u, 0x00000030u, 0x00000030u, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, - 0x00000031u, 0x00000032u, 0x00050039u, 0x00000006u, 0x00000033u, 0x0000000bu, 0x00000031u, 0x0003003eu, - 0x00000021u, 0x00000033u, 0x0004003du, 0x00000023u, 0x00000035u, 0x00000025u, 0x0004003du, 0x0000000du, - 0x00000036u, 0x00000010u, 0x00050041u, 0x00000020u, 0x00000037u, 0x00000011u, 0x00000029u, 0x0004003du, - 0x00000006u, 0x00000038u, 0x00000037u, 0x00050050u, 0x0000000du, 0x00000039u, 0x00000038u, 0x0000002cu, - 0x00050081u, 0x0000000du, 0x0000003au, 0x00000036u, 0x00000039u, 0x00050057u, 0x0000002fu, 0x0000003bu, - 0x00000035u, 0x0000003au, 0x0008004fu, 0x00000007u, 0x0000003du, 0x0000003bu, 0x0000003bu, 0x00000000u, - 0x00000001u, 0x00000002u, 0x0003003eu, 0x0000003cu, 0x0000003du, 0x00050039u, 0x00000006u, 0x0000003eu, - 0x0000000bu, 0x0000003cu, 0x0003003eu, 0x00000034u, 0x0000003eu, 0x0004003du, 0x00000006u, 0x0000003fu, - 0x00000021u, 0x0004003du, 0x00000006u, 0x00000040u, 0x00000034u, 0x00050083u, 0x00000006u, 0x00000041u, - 0x0000003fu, 0x00000040u, 0x0006000cu, 0x00000006u, 0x00000042u, 0x00000001u, 0x00000004u, 0x00000041u, - 0x000200feu, 0x00000042u, 0x00010038u, 0x00050036u, 0x00000006u, 0x00000016u, 0x00000000u, 0x0000000fu, - 0x00030037u, 0x0000000eu, 0x00000014u, 0x00030037u, 0x0000000eu, 0x00000015u, 0x000200f8u, 0x00000017u, - 0x0004003bu, 0x00000020u, 0x00000045u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x0000004eu, 0x00000007u, - 0x0004003bu, 0x00000020u, 0x00000051u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x00000059u, 0x00000007u, - 0x0004003du, 0x00000023u, 0x00000046u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000047u, 0x00000014u, - 0x00050041u, 0x00000020u, 0x00000049u, 0x00000015u, 0x00000048u, 0x0004003du, 0x00000006u, 0x0000004au, - 0x00000049u, 0x00050050u, 0x0000000du, 0x0000004bu, 0x0000002cu, 0x0000004au, 0x00050083u, 0x0000000du, - 0x0000004cu, 0x00000047u, 0x0000004bu, 0x00050057u, 0x0000002fu, 0x0000004du, 0x00000046u, 0x0000004cu, - 0x0008004fu, 0x00000007u, 0x0000004fu, 0x0000004du, 0x0000004du, 0x00000000u, 0x00000001u, 0x00000002u, - 0x0003003eu, 0x0000004eu, 0x0000004fu, 0x00050039u, 0x00000006u, 0x00000050u, 0x0000000bu, 0x0000004eu, - 0x0003003eu, 0x00000045u, 0x00000050u, 0x0004003du, 0x00000023u, 0x00000052u, 0x00000025u, 0x0004003du, - 0x0000000du, 0x00000053u, 0x00000014u, 0x00050041u, 0x00000020u, 0x00000054u, 0x00000015u, 0x00000048u, - 0x0004003du, 0x00000006u, 0x00000055u, 0x00000054u, 0x00050050u, 0x0000000du, 0x00000056u, 0x0000002cu, - 0x00000055u, 0x00050081u, 0x0000000du, 0x00000057u, 0x00000053u, 0x00000056u, 0x00050057u, 0x0000002fu, - 0x00000058u, 0x00000052u, 0x00000057u, 0x0008004fu, 0x00000007u, 0x0000005au, 0x00000058u, 0x00000058u, - 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x00000059u, 0x0000005au, 0x00050039u, 0x00000006u, - 0x0000005bu, 0x0000000bu, 0x00000059u, 0x0003003eu, 0x00000051u, 0x0000005bu, 0x0004003du, 0x00000006u, - 0x0000005cu, 0x00000045u, 0x0004003du, 0x00000006u, 0x0000005du, 0x00000051u, 0x00050083u, 0x00000006u, - 0x0000005eu, 0x0000005cu, 0x0000005du, 0x0006000cu, 0x00000006u, 0x0000005fu, 0x00000001u, 0x00000004u, - 0x0000005eu, 0x000200feu, 0x0000005fu, 0x00010038u, + 0x00060005u, 0x00000220u, 0x67616964u, 0x6c616e6fu, 0x74746150u, 0x006e7265u, 0x00070005u, 0x00000226u, + 0x67616964u, 0x6c616e6fu, 0x746e6f43u, 0x69756e69u, 0x00007974u, 0x00070005u, 0x00000229u, 0x67616964u, + 0x6c616e6fu, 0x6c6c6146u, 0x6b636162u, 0x00000000u, 0x00040005u, 0x00000235u, 0x67696577u, 0x00007468u, + 0x00040005u, 0x0000023bu, 0x6f726361u, 0x00007373u, 0x00040047u, 0x00000025u, 0x00000021u, 0x00000000u, + 0x00040047u, 0x00000025u, 0x00000022u, 0x00000000u, 0x00030047u, 0x00000064u, 0x00000002u, 0x00050048u, + 0x00000064u, 0x00000000u, 0x00000023u, 0x00000000u, 0x00050048u, 0x00000064u, 0x00000001u, 0x00000023u, + 0x00000010u, 0x00050048u, 0x00000064u, 0x00000002u, 0x00000023u, 0x00000018u, 0x00050048u, 0x00000064u, + 0x00000003u, 0x00000023u, 0x0000001cu, 0x00040047u, 0x00000072u, 0x0000001eu, 0x00000000u, 0x00040047u, + 0x000000f6u, 0x0000001eu, 0x00000000u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, + 0x00030016u, 0x00000006u, 0x00000020u, 0x00040017u, 0x00000007u, 0x00000006u, 0x00000003u, 0x00040020u, + 0x00000008u, 0x00000007u, 0x00000007u, 0x00040021u, 0x00000009u, 0x00000006u, 0x00000008u, 0x00040017u, + 0x0000000du, 0x00000006u, 0x00000002u, 0x00040020u, 0x0000000eu, 0x00000007u, 0x0000000du, 0x00050021u, + 0x0000000fu, 0x00000006u, 0x0000000eu, 0x0000000eu, 0x0004002bu, 0x00000006u, 0x00000019u, 0x3e59b3d0u, + 0x0004002bu, 0x00000006u, 0x0000001au, 0x3f371759u, 0x0004002bu, 0x00000006u, 0x0000001bu, 0x3d93dd98u, + 0x0006002cu, 0x00000007u, 0x0000001cu, 0x00000019u, 0x0000001au, 0x0000001bu, 0x00040020u, 0x00000020u, + 0x00000007u, 0x00000006u, 0x00090019u, 0x00000022u, 0x00000006u, 0x00000001u, 0x00000000u, 0x00000000u, + 0x00000000u, 0x00000001u, 0x00000000u, 0x0003001bu, 0x00000023u, 0x00000022u, 0x00040020u, 0x00000024u, + 0x00000000u, 0x00000023u, 0x0004003bu, 0x00000024u, 0x00000025u, 0x00000000u, 0x00040015u, 0x00000028u, + 0x00000020u, 0x00000000u, 0x0004002bu, 0x00000028u, 0x00000029u, 0x00000000u, 0x0004002bu, 0x00000006u, + 0x0000002cu, 0x00000000u, 0x00040017u, 0x0000002fu, 0x00000006u, 0x00000004u, 0x0004002bu, 0x00000028u, + 0x00000048u, 0x00000001u, 0x0004002bu, 0x00000006u, 0x00000063u, 0x3f800000u, 0x0006001eu, 0x00000064u, + 0x0000002fu, 0x0000000du, 0x00000006u, 0x00000006u, 0x00040020u, 0x00000065u, 0x00000009u, 0x00000064u, + 0x0004003bu, 0x00000065u, 0x00000066u, 0x00000009u, 0x00040015u, 0x00000067u, 0x00000020u, 0x00000001u, + 0x0004002bu, 0x00000067u, 0x00000068u, 0x00000001u, 0x00040020u, 0x00000069u, 0x00000009u, 0x0000000du, + 0x0005002cu, 0x0000000du, 0x0000006cu, 0x00000063u, 0x00000063u, 0x00040020u, 0x00000071u, 0x00000001u, + 0x0000000du, 0x0004003bu, 0x00000071u, 0x00000072u, 0x00000001u, 0x0004002bu, 0x00000006u, 0x00000075u, + 0x3f000000u, 0x00040020u, 0x0000007bu, 0x00000007u, 0x0000002fu, 0x0004002bu, 0x00000006u, 0x000000deu, + 0x3d3851ecu, 0x0004002bu, 0x00000006u, 0x000000e0u, 0x3da3d70au, 0x00020014u, 0x000000f1u, 0x00040020u, + 0x000000f5u, 0x00000003u, 0x0000002fu, 0x0004003bu, 0x000000f5u, 0x000000f6u, 0x00000003u, 0x00040020u, + 0x000000f9u, 0x00000007u, 0x000000f1u, 0x0004002bu, 0x00000006u, 0x00000113u, 0xbf800000u, 0x00040020u, + 0x0000011fu, 0x00000007u, 0x00000067u, 0x0004002bu, 0x00000067u, 0x00000127u, 0x00000006u, 0x0004002bu, + 0x00000006u, 0x00000161u, 0x3f266666u, 0x0004002bu, 0x00000006u, 0x00000182u, 0x40200000u, 0x0004002bu, + 0x00000006u, 0x000001cau, 0x3d6147aeu, 0x0004002bu, 0x00000006u, 0x000001f8u, 0x3ec28f5cu, 0x0004002bu, + 0x00000006u, 0x000001fcu, 0x40800000u, 0x0004002bu, 0x00000006u, 0x0000020bu, 0x3eb33333u, 0x0004002bu, + 0x00000006u, 0x0000020eu, 0x40400000u, 0x0004002bu, 0x00000006u, 0x0000022au, 0x3e23d70au, 0x0004002bu, + 0x00000006u, 0x00000239u, 0x3ed70a3du, 0x0004002bu, 0x00000028u, 0x0000024au, 0x00000003u, 0x00050036u, + 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x0004003bu, 0x0000000eu, + 0x00000062u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x00000070u, 0x00000007u, 0x0004003bu, 0x0000007bu, + 0x0000007cu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000080u, 0x00000007u, 0x0004003bu, 0x00000008u, + 0x00000081u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000085u, 0x00000007u, 0x0004003bu, 0x00000008u, + 0x0000008du, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000090u, 0x00000007u, 0x0004003bu, 0x00000008u, + 0x00000098u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000009bu, 0x00000007u, 0x0004003bu, 0x00000008u, + 0x000000a3u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000a6u, 0x00000007u, 0x0004003bu, 0x00000008u, + 0x000000aeu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000b1u, 0x00000007u, 0x0004003bu, 0x00000020u, + 0x000000b6u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000bbu, 0x00000007u, 0x0004003bu, 0x00000020u, + 0x000000c0u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000c5u, 0x00000007u, 0x0004003bu, 0x00000020u, + 0x000000cfu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000d9u, 0x00000007u, 0x0004003bu, 0x00000020u, + 0x000000ddu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000e3u, 0x00000007u, 0x0004003bu, 0x00000020u, + 0x000000e7u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000000ebu, 0x00000007u, 0x0004003bu, 0x000000f9u, + 0x000000fau, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x000000feu, 0x00000007u, 0x0004003bu, 0x0000000eu, + 0x00000100u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x0000010bu, 0x00000007u, 0x0004003bu, 0x0000000eu, + 0x0000010du, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000011du, 0x00000007u, 0x0004003bu, 0x00000020u, + 0x0000011eu, 0x00000007u, 0x0004003bu, 0x0000011fu, 0x00000120u, 0x00000007u, 0x0004003bu, 0x0000000eu, + 0x00000129u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000012eu, 0x00000007u, 0x0004003bu, 0x00000020u, + 0x00000130u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x00000136u, 0x00000007u, 0x0004003bu, 0x0000000eu, + 0x00000137u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x0000013eu, 0x00000007u, 0x0004003bu, 0x0000000eu, + 0x0000013fu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000143u, 0x00000007u, 0x0004003bu, 0x00000020u, + 0x00000145u, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x0000014bu, 0x00000007u, 0x0004003bu, 0x0000000eu, + 0x0000014cu, 0x00000007u, 0x0004003bu, 0x0000000eu, 0x00000153u, 0x00000007u, 0x0004003bu, 0x0000000eu, + 0x00000154u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000017bu, 0x00000007u, 0x0004003bu, 0x00000020u, + 0x0000017fu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000186u, 0x00000007u, 0x0004003bu, 0x00000008u, + 0x00000192u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000195u, 0x00000007u, 0x0004003bu, 0x00000008u, + 0x000001a0u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001a3u, 0x00000007u, 0x0004003bu, 0x00000008u, + 0x000001aeu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001b1u, 0x00000007u, 0x0004003bu, 0x00000008u, + 0x000001bbu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001beu, 0x00000007u, 0x0004003bu, 0x00000020u, + 0x000001c7u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001ceu, 0x00000007u, 0x0004003bu, 0x00000020u, + 0x000001d0u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001ddu, 0x00000007u, 0x0004003bu, 0x00000020u, + 0x000001dfu, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001ecu, 0x00000007u, 0x0004003bu, 0x00000020u, + 0x000001f1u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x000001f7u, 0x00000007u, 0x0004003bu, 0x00000020u, + 0x00000200u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000020au, 0x00000007u, 0x0004003bu, 0x00000020u, + 0x00000214u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x0000021cu, 0x00000007u, 0x0004003bu, 0x00000020u, + 0x00000220u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000226u, 0x00000007u, 0x0004003bu, 0x00000020u, + 0x00000229u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000235u, 0x00000007u, 0x0004003bu, 0x00000008u, + 0x0000023bu, 0x00000007u, 0x00050041u, 0x00000069u, 0x0000006au, 0x00000066u, 0x00000068u, 0x0004003du, + 0x0000000du, 0x0000006bu, 0x0000006au, 0x0007000cu, 0x0000000du, 0x0000006du, 0x00000001u, 0x00000028u, + 0x0000006bu, 0x0000006cu, 0x00050050u, 0x0000000du, 0x0000006eu, 0x00000063u, 0x00000063u, 0x00050088u, + 0x0000000du, 0x0000006fu, 0x0000006eu, 0x0000006du, 0x0003003eu, 0x00000062u, 0x0000006fu, 0x0004003du, + 0x0000000du, 0x00000073u, 0x00000072u, 0x0004003du, 0x0000000du, 0x00000074u, 0x00000062u, 0x0005008eu, + 0x0000000du, 0x00000076u, 0x00000074u, 0x00000075u, 0x0004003du, 0x0000000du, 0x00000077u, 0x00000062u, + 0x0005008eu, 0x0000000du, 0x00000078u, 0x00000077u, 0x00000075u, 0x00050083u, 0x0000000du, 0x00000079u, + 0x0000006cu, 0x00000078u, 0x0008000cu, 0x0000000du, 0x0000007au, 0x00000001u, 0x0000002bu, 0x00000073u, + 0x00000076u, 0x00000079u, 0x0003003eu, 0x00000070u, 0x0000007au, 0x0004003du, 0x00000023u, 0x0000007du, + 0x00000025u, 0x0004003du, 0x0000000du, 0x0000007eu, 0x00000070u, 0x00050057u, 0x0000002fu, 0x0000007fu, + 0x0000007du, 0x0000007eu, 0x0003003eu, 0x0000007cu, 0x0000007fu, 0x0004003du, 0x0000002fu, 0x00000082u, + 0x0000007cu, 0x0008004fu, 0x00000007u, 0x00000083u, 0x00000082u, 0x00000082u, 0x00000000u, 0x00000001u, + 0x00000002u, 0x0003003eu, 0x00000081u, 0x00000083u, 0x00050039u, 0x00000006u, 0x00000084u, 0x0000000bu, + 0x00000081u, 0x0003003eu, 0x00000080u, 0x00000084u, 0x0004003du, 0x00000023u, 0x00000086u, 0x00000025u, + 0x0004003du, 0x0000000du, 0x00000087u, 0x00000070u, 0x00050041u, 0x00000020u, 0x00000088u, 0x00000062u, + 0x00000029u, 0x0004003du, 0x00000006u, 0x00000089u, 0x00000088u, 0x00050050u, 0x0000000du, 0x0000008au, + 0x00000089u, 0x0000002cu, 0x00050083u, 0x0000000du, 0x0000008bu, 0x00000087u, 0x0000008au, 0x00050057u, + 0x0000002fu, 0x0000008cu, 0x00000086u, 0x0000008bu, 0x0008004fu, 0x00000007u, 0x0000008eu, 0x0000008cu, + 0x0000008cu, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x0000008du, 0x0000008eu, 0x00050039u, + 0x00000006u, 0x0000008fu, 0x0000000bu, 0x0000008du, 0x0003003eu, 0x00000085u, 0x0000008fu, 0x0004003du, + 0x00000023u, 0x00000091u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000092u, 0x00000070u, 0x00050041u, + 0x00000020u, 0x00000093u, 0x00000062u, 0x00000029u, 0x0004003du, 0x00000006u, 0x00000094u, 0x00000093u, + 0x00050050u, 0x0000000du, 0x00000095u, 0x00000094u, 0x0000002cu, 0x00050081u, 0x0000000du, 0x00000096u, + 0x00000092u, 0x00000095u, 0x00050057u, 0x0000002fu, 0x00000097u, 0x00000091u, 0x00000096u, 0x0008004fu, + 0x00000007u, 0x00000099u, 0x00000097u, 0x00000097u, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, + 0x00000098u, 0x00000099u, 0x00050039u, 0x00000006u, 0x0000009au, 0x0000000bu, 0x00000098u, 0x0003003eu, + 0x00000090u, 0x0000009au, 0x0004003du, 0x00000023u, 0x0000009cu, 0x00000025u, 0x0004003du, 0x0000000du, + 0x0000009du, 0x00000070u, 0x00050041u, 0x00000020u, 0x0000009eu, 0x00000062u, 0x00000048u, 0x0004003du, + 0x00000006u, 0x0000009fu, 0x0000009eu, 0x00050050u, 0x0000000du, 0x000000a0u, 0x0000002cu, 0x0000009fu, + 0x00050083u, 0x0000000du, 0x000000a1u, 0x0000009du, 0x000000a0u, 0x00050057u, 0x0000002fu, 0x000000a2u, + 0x0000009cu, 0x000000a1u, 0x0008004fu, 0x00000007u, 0x000000a4u, 0x000000a2u, 0x000000a2u, 0x00000000u, + 0x00000001u, 0x00000002u, 0x0003003eu, 0x000000a3u, 0x000000a4u, 0x00050039u, 0x00000006u, 0x000000a5u, + 0x0000000bu, 0x000000a3u, 0x0003003eu, 0x0000009bu, 0x000000a5u, 0x0004003du, 0x00000023u, 0x000000a7u, + 0x00000025u, 0x0004003du, 0x0000000du, 0x000000a8u, 0x00000070u, 0x00050041u, 0x00000020u, 0x000000a9u, + 0x00000062u, 0x00000048u, 0x0004003du, 0x00000006u, 0x000000aau, 0x000000a9u, 0x00050050u, 0x0000000du, + 0x000000abu, 0x0000002cu, 0x000000aau, 0x00050081u, 0x0000000du, 0x000000acu, 0x000000a8u, 0x000000abu, + 0x00050057u, 0x0000002fu, 0x000000adu, 0x000000a7u, 0x000000acu, 0x0008004fu, 0x00000007u, 0x000000afu, + 0x000000adu, 0x000000adu, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x000000aeu, 0x000000afu, + 0x00050039u, 0x00000006u, 0x000000b0u, 0x0000000bu, 0x000000aeu, 0x0003003eu, 0x000000a6u, 0x000000b0u, + 0x0004003du, 0x00000006u, 0x000000b2u, 0x00000080u, 0x0004003du, 0x00000006u, 0x000000b3u, 0x00000085u, + 0x00050083u, 0x00000006u, 0x000000b4u, 0x000000b2u, 0x000000b3u, 0x0006000cu, 0x00000006u, 0x000000b5u, + 0x00000001u, 0x00000004u, 0x000000b4u, 0x0003003eu, 0x000000b1u, 0x000000b5u, 0x0004003du, 0x00000006u, + 0x000000b7u, 0x00000080u, 0x0004003du, 0x00000006u, 0x000000b8u, 0x00000090u, 0x00050083u, 0x00000006u, + 0x000000b9u, 0x000000b7u, 0x000000b8u, 0x0006000cu, 0x00000006u, 0x000000bau, 0x00000001u, 0x00000004u, + 0x000000b9u, 0x0003003eu, 0x000000b6u, 0x000000bau, 0x0004003du, 0x00000006u, 0x000000bcu, 0x00000080u, + 0x0004003du, 0x00000006u, 0x000000bdu, 0x0000009bu, 0x00050083u, 0x00000006u, 0x000000beu, 0x000000bcu, + 0x000000bdu, 0x0006000cu, 0x00000006u, 0x000000bfu, 0x00000001u, 0x00000004u, 0x000000beu, 0x0003003eu, + 0x000000bbu, 0x000000bfu, 0x0004003du, 0x00000006u, 0x000000c1u, 0x00000080u, 0x0004003du, 0x00000006u, + 0x000000c2u, 0x000000a6u, 0x00050083u, 0x00000006u, 0x000000c3u, 0x000000c1u, 0x000000c2u, 0x0006000cu, + 0x00000006u, 0x000000c4u, 0x00000001u, 0x00000004u, 0x000000c3u, 0x0003003eu, 0x000000c0u, 0x000000c4u, + 0x0004003du, 0x00000006u, 0x000000c6u, 0x00000080u, 0x0004003du, 0x00000006u, 0x000000c7u, 0x00000085u, + 0x0004003du, 0x00000006u, 0x000000c8u, 0x00000090u, 0x0007000cu, 0x00000006u, 0x000000c9u, 0x00000001u, + 0x00000025u, 0x000000c7u, 0x000000c8u, 0x0004003du, 0x00000006u, 0x000000cau, 0x0000009bu, 0x0004003du, + 0x00000006u, 0x000000cbu, 0x000000a6u, 0x0007000cu, 0x00000006u, 0x000000ccu, 0x00000001u, 0x00000025u, + 0x000000cau, 0x000000cbu, 0x0007000cu, 0x00000006u, 0x000000cdu, 0x00000001u, 0x00000025u, 0x000000c9u, + 0x000000ccu, 0x0007000cu, 0x00000006u, 0x000000ceu, 0x00000001u, 0x00000025u, 0x000000c6u, 0x000000cdu, + 0x0003003eu, 0x000000c5u, 0x000000ceu, 0x0004003du, 0x00000006u, 0x000000d0u, 0x00000080u, 0x0004003du, + 0x00000006u, 0x000000d1u, 0x00000085u, 0x0004003du, 0x00000006u, 0x000000d2u, 0x00000090u, 0x0007000cu, + 0x00000006u, 0x000000d3u, 0x00000001u, 0x00000028u, 0x000000d1u, 0x000000d2u, 0x0004003du, 0x00000006u, + 0x000000d4u, 0x0000009bu, 0x0004003du, 0x00000006u, 0x000000d5u, 0x000000a6u, 0x0007000cu, 0x00000006u, + 0x000000d6u, 0x00000001u, 0x00000028u, 0x000000d4u, 0x000000d5u, 0x0007000cu, 0x00000006u, 0x000000d7u, + 0x00000001u, 0x00000028u, 0x000000d3u, 0x000000d6u, 0x0007000cu, 0x00000006u, 0x000000d8u, 0x00000001u, + 0x00000028u, 0x000000d0u, 0x000000d7u, 0x0003003eu, 0x000000cfu, 0x000000d8u, 0x0004003du, 0x00000006u, + 0x000000dau, 0x000000cfu, 0x0004003du, 0x00000006u, 0x000000dbu, 0x000000c5u, 0x00050083u, 0x00000006u, + 0x000000dcu, 0x000000dau, 0x000000dbu, 0x0003003eu, 0x000000d9u, 0x000000dcu, 0x0004003du, 0x00000006u, + 0x000000dfu, 0x000000d9u, 0x00050085u, 0x00000006u, 0x000000e1u, 0x000000dfu, 0x000000e0u, 0x0007000cu, + 0x00000006u, 0x000000e2u, 0x00000001u, 0x00000028u, 0x000000deu, 0x000000e1u, 0x0003003eu, 0x000000ddu, + 0x000000e2u, 0x0004003du, 0x00000006u, 0x000000e4u, 0x000000b1u, 0x0004003du, 0x00000006u, 0x000000e5u, + 0x000000b6u, 0x0007000cu, 0x00000006u, 0x000000e6u, 0x00000001u, 0x00000028u, 0x000000e4u, 0x000000e5u, + 0x0003003eu, 0x000000e3u, 0x000000e6u, 0x0004003du, 0x00000006u, 0x000000e8u, 0x000000bbu, 0x0004003du, + 0x00000006u, 0x000000e9u, 0x000000c0u, 0x0007000cu, 0x00000006u, 0x000000eau, 0x00000001u, 0x00000028u, + 0x000000e8u, 0x000000e9u, 0x0003003eu, 0x000000e7u, 0x000000eau, 0x0004003du, 0x00000006u, 0x000000ecu, + 0x000000e3u, 0x0004003du, 0x00000006u, 0x000000edu, 0x000000e7u, 0x0007000cu, 0x00000006u, 0x000000eeu, + 0x00000001u, 0x00000028u, 0x000000ecu, 0x000000edu, 0x0003003eu, 0x000000ebu, 0x000000eeu, 0x0004003du, + 0x00000006u, 0x000000efu, 0x000000ebu, 0x0004003du, 0x00000006u, 0x000000f0u, 0x000000ddu, 0x000500bcu, + 0x000000f1u, 0x000000f2u, 0x000000efu, 0x000000f0u, 0x000300f7u, 0x000000f4u, 0x00000000u, 0x000400fau, + 0x000000f2u, 0x000000f3u, 0x000000f4u, 0x000200f8u, 0x000000f3u, 0x0004003du, 0x0000002fu, 0x000000f7u, + 0x0000007cu, 0x0003003eu, 0x000000f6u, 0x000000f7u, 0x000100fdu, 0x000200f8u, 0x000000f4u, 0x0004003du, + 0x00000006u, 0x000000fbu, 0x000000e3u, 0x0004003du, 0x00000006u, 0x000000fcu, 0x000000e7u, 0x000500beu, + 0x000000f1u, 0x000000fdu, 0x000000fbu, 0x000000fcu, 0x0003003eu, 0x000000fau, 0x000000fdu, 0x0004003du, + 0x000000f1u, 0x000000ffu, 0x000000fau, 0x000300f7u, 0x00000102u, 0x00000000u, 0x000400fau, 0x000000ffu, + 0x00000101u, 0x00000106u, 0x000200f8u, 0x00000101u, 0x00050041u, 0x00000020u, 0x00000103u, 0x00000062u, + 0x00000048u, 0x0004003du, 0x00000006u, 0x00000104u, 0x00000103u, 0x00050050u, 0x0000000du, 0x00000105u, + 0x0000002cu, 0x00000104u, 0x0003003eu, 0x00000100u, 0x00000105u, 0x000200f9u, 0x00000102u, 0x000200f8u, + 0x00000106u, 0x00050041u, 0x00000020u, 0x00000107u, 0x00000062u, 0x00000029u, 0x0004003du, 0x00000006u, + 0x00000108u, 0x00000107u, 0x00050050u, 0x0000000du, 0x00000109u, 0x00000108u, 0x0000002cu, 0x0003003eu, + 0x00000100u, 0x00000109u, 0x000200f9u, 0x00000102u, 0x000200f8u, 0x00000102u, 0x0004003du, 0x0000000du, + 0x0000010au, 0x00000100u, 0x0003003eu, 0x000000feu, 0x0000010au, 0x0004003du, 0x000000f1u, 0x0000010cu, + 0x000000fau, 0x000300f7u, 0x0000010fu, 0x00000000u, 0x000400fau, 0x0000010cu, 0x0000010eu, 0x00000116u, + 0x000200f8u, 0x0000010eu, 0x0004003du, 0x00000006u, 0x00000110u, 0x000000b1u, 0x0004003du, 0x00000006u, + 0x00000111u, 0x000000b6u, 0x000500beu, 0x000000f1u, 0x00000112u, 0x00000110u, 0x00000111u, 0x000600a9u, + 0x00000006u, 0x00000114u, 0x00000112u, 0x00000113u, 0x00000063u, 0x00050050u, 0x0000000du, 0x00000115u, + 0x00000114u, 0x0000002cu, 0x0003003eu, 0x0000010du, 0x00000115u, 0x000200f9u, 0x0000010fu, 0x000200f8u, + 0x00000116u, 0x0004003du, 0x00000006u, 0x00000117u, 0x000000bbu, 0x0004003du, 0x00000006u, 0x00000118u, + 0x000000c0u, 0x000500beu, 0x000000f1u, 0x00000119u, 0x00000117u, 0x00000118u, 0x000600a9u, 0x00000006u, + 0x0000011au, 0x00000119u, 0x00000113u, 0x00000063u, 0x00050050u, 0x0000000du, 0x0000011bu, 0x0000002cu, + 0x0000011au, 0x0003003eu, 0x0000010du, 0x0000011bu, 0x000200f9u, 0x0000010fu, 0x000200f8u, 0x0000010fu, + 0x0004003du, 0x0000000du, 0x0000011cu, 0x0000010du, 0x0003003eu, 0x0000010bu, 0x0000011cu, 0x0003003eu, + 0x0000011du, 0x0000002cu, 0x0003003eu, 0x0000011eu, 0x0000002cu, 0x0003003eu, 0x00000120u, 0x00000068u, + 0x000200f9u, 0x00000121u, 0x000200f8u, 0x00000121u, 0x000400f6u, 0x00000123u, 0x00000124u, 0x00000000u, + 0x000200f9u, 0x00000125u, 0x000200f8u, 0x00000125u, 0x0004003du, 0x00000067u, 0x00000126u, 0x00000120u, + 0x000500b3u, 0x000000f1u, 0x00000128u, 0x00000126u, 0x00000127u, 0x000400fau, 0x00000128u, 0x00000122u, + 0x00000123u, 0x000200f8u, 0x00000122u, 0x0004003du, 0x0000000du, 0x0000012au, 0x000000feu, 0x0004003du, + 0x00000067u, 0x0000012bu, 0x00000120u, 0x0004006fu, 0x00000006u, 0x0000012cu, 0x0000012bu, 0x0005008eu, + 0x0000000du, 0x0000012du, 0x0000012au, 0x0000012cu, 0x0003003eu, 0x00000129u, 0x0000012du, 0x0004003du, + 0x000000f1u, 0x0000012fu, 0x000000fau, 0x000300f7u, 0x00000132u, 0x00000000u, 0x000400fau, 0x0000012fu, + 0x00000131u, 0x0000013au, 0x000200f8u, 0x00000131u, 0x0004003du, 0x0000000du, 0x00000133u, 0x00000070u, + 0x0004003du, 0x0000000du, 0x00000134u, 0x00000129u, 0x00050083u, 0x0000000du, 0x00000135u, 0x00000133u, + 0x00000134u, 0x0003003eu, 0x00000136u, 0x00000135u, 0x0004003du, 0x0000000du, 0x00000138u, 0x00000062u, + 0x0003003eu, 0x00000137u, 0x00000138u, 0x00060039u, 0x00000006u, 0x00000139u, 0x00000012u, 0x00000136u, + 0x00000137u, 0x0003003eu, 0x00000130u, 0x00000139u, 0x000200f9u, 0x00000132u, 0x000200f8u, 0x0000013au, + 0x0004003du, 0x0000000du, 0x0000013bu, 0x00000070u, 0x0004003du, 0x0000000du, 0x0000013cu, 0x00000129u, + 0x00050083u, 0x0000000du, 0x0000013du, 0x0000013bu, 0x0000013cu, 0x0003003eu, 0x0000013eu, 0x0000013du, + 0x0004003du, 0x0000000du, 0x00000140u, 0x00000062u, 0x0003003eu, 0x0000013fu, 0x00000140u, 0x00060039u, + 0x00000006u, 0x00000141u, 0x00000016u, 0x0000013eu, 0x0000013fu, 0x0003003eu, 0x00000130u, 0x00000141u, + 0x000200f9u, 0x00000132u, 0x000200f8u, 0x00000132u, 0x0004003du, 0x00000006u, 0x00000142u, 0x00000130u, + 0x0003003eu, 0x0000012eu, 0x00000142u, 0x0004003du, 0x000000f1u, 0x00000144u, 0x000000fau, 0x000300f7u, + 0x00000147u, 0x00000000u, 0x000400fau, 0x00000144u, 0x00000146u, 0x0000014fu, 0x000200f8u, 0x00000146u, + 0x0004003du, 0x0000000du, 0x00000148u, 0x00000070u, 0x0004003du, 0x0000000du, 0x00000149u, 0x00000129u, + 0x00050081u, 0x0000000du, 0x0000014au, 0x00000148u, 0x00000149u, 0x0003003eu, 0x0000014bu, 0x0000014au, + 0x0004003du, 0x0000000du, 0x0000014du, 0x00000062u, 0x0003003eu, 0x0000014cu, 0x0000014du, 0x00060039u, + 0x00000006u, 0x0000014eu, 0x00000012u, 0x0000014bu, 0x0000014cu, 0x0003003eu, 0x00000145u, 0x0000014eu, + 0x000200f9u, 0x00000147u, 0x000200f8u, 0x0000014fu, 0x0004003du, 0x0000000du, 0x00000150u, 0x00000070u, + 0x0004003du, 0x0000000du, 0x00000151u, 0x00000129u, 0x00050081u, 0x0000000du, 0x00000152u, 0x00000150u, + 0x00000151u, 0x0003003eu, 0x00000153u, 0x00000152u, 0x0004003du, 0x0000000du, 0x00000155u, 0x00000062u, + 0x0003003eu, 0x00000154u, 0x00000155u, 0x00060039u, 0x00000006u, 0x00000156u, 0x00000016u, 0x00000153u, + 0x00000154u, 0x0003003eu, 0x00000145u, 0x00000156u, 0x000200f9u, 0x00000147u, 0x000200f8u, 0x00000147u, + 0x0004003du, 0x00000006u, 0x00000157u, 0x00000145u, 0x0003003eu, 0x00000143u, 0x00000157u, 0x0004003du, + 0x00000006u, 0x00000158u, 0x0000011du, 0x0004003du, 0x00000067u, 0x00000159u, 0x00000120u, 0x00050082u, + 0x00000067u, 0x0000015au, 0x00000159u, 0x00000068u, 0x0004006fu, 0x00000006u, 0x0000015bu, 0x0000015au, + 0x000500b4u, 0x000000f1u, 0x0000015cu, 0x00000158u, 0x0000015bu, 0x000300f7u, 0x0000015eu, 0x00000000u, + 0x000400fau, 0x0000015cu, 0x0000015du, 0x0000015eu, 0x000200f8u, 0x0000015du, 0x0004003du, 0x00000006u, + 0x0000015fu, 0x0000012eu, 0x0004003du, 0x00000006u, 0x00000160u, 0x000000ddu, 0x00050085u, 0x00000006u, + 0x00000162u, 0x00000160u, 0x00000161u, 0x000500bau, 0x000000f1u, 0x00000163u, 0x0000015fu, 0x00000162u, + 0x000200f9u, 0x0000015eu, 0x000200f8u, 0x0000015eu, 0x000700f5u, 0x000000f1u, 0x00000164u, 0x0000015cu, + 0x00000147u, 0x00000163u, 0x0000015du, 0x000300f7u, 0x00000166u, 0x00000000u, 0x000400fau, 0x00000164u, + 0x00000165u, 0x00000166u, 0x000200f8u, 0x00000165u, 0x0004003du, 0x00000067u, 0x00000167u, 0x00000120u, + 0x0004006fu, 0x00000006u, 0x00000168u, 0x00000167u, 0x0003003eu, 0x0000011du, 0x00000168u, 0x000200f9u, + 0x00000166u, 0x000200f8u, 0x00000166u, 0x0004003du, 0x00000006u, 0x00000169u, 0x0000011eu, 0x0004003du, + 0x00000067u, 0x0000016au, 0x00000120u, 0x00050082u, 0x00000067u, 0x0000016bu, 0x0000016au, 0x00000068u, + 0x0004006fu, 0x00000006u, 0x0000016cu, 0x0000016bu, 0x000500b4u, 0x000000f1u, 0x0000016du, 0x00000169u, + 0x0000016cu, 0x000300f7u, 0x0000016fu, 0x00000000u, 0x000400fau, 0x0000016du, 0x0000016eu, 0x0000016fu, + 0x000200f8u, 0x0000016eu, 0x0004003du, 0x00000006u, 0x00000170u, 0x00000143u, 0x0004003du, 0x00000006u, + 0x00000171u, 0x000000ddu, 0x00050085u, 0x00000006u, 0x00000172u, 0x00000171u, 0x00000161u, 0x000500bau, + 0x000000f1u, 0x00000173u, 0x00000170u, 0x00000172u, 0x000200f9u, 0x0000016fu, 0x000200f8u, 0x0000016fu, + 0x000700f5u, 0x000000f1u, 0x00000174u, 0x0000016du, 0x00000166u, 0x00000173u, 0x0000016eu, 0x000300f7u, + 0x00000176u, 0x00000000u, 0x000400fau, 0x00000174u, 0x00000175u, 0x00000176u, 0x000200f8u, 0x00000175u, + 0x0004003du, 0x00000067u, 0x00000177u, 0x00000120u, 0x0004006fu, 0x00000006u, 0x00000178u, 0x00000177u, + 0x0003003eu, 0x0000011eu, 0x00000178u, 0x000200f9u, 0x00000176u, 0x000200f8u, 0x00000176u, 0x000200f9u, + 0x00000124u, 0x000200f8u, 0x00000124u, 0x0004003du, 0x00000067u, 0x00000179u, 0x00000120u, 0x00050080u, + 0x00000067u, 0x0000017au, 0x00000179u, 0x00000068u, 0x0003003eu, 0x00000120u, 0x0000017au, 0x000200f9u, + 0x00000121u, 0x000200f8u, 0x00000123u, 0x0004003du, 0x00000006u, 0x0000017cu, 0x0000011du, 0x0004003du, + 0x00000006u, 0x0000017du, 0x0000011eu, 0x00050081u, 0x00000006u, 0x0000017eu, 0x0000017cu, 0x0000017du, + 0x0003003eu, 0x0000017bu, 0x0000017eu, 0x0004003du, 0x00000006u, 0x00000180u, 0x000000ddu, 0x0004003du, + 0x00000006u, 0x00000181u, 0x000000ddu, 0x00050085u, 0x00000006u, 0x00000183u, 0x00000181u, 0x00000182u, + 0x0004003du, 0x00000006u, 0x00000184u, 0x000000ebu, 0x0008000cu, 0x00000006u, 0x00000185u, 0x00000001u, + 0x00000031u, 0x00000180u, 0x00000183u, 0x00000184u, 0x0003003eu, 0x0000017fu, 0x00000185u, 0x0004003du, + 0x00000023u, 0x00000187u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000188u, 0x00000070u, 0x00050041u, + 0x00000020u, 0x00000189u, 0x00000062u, 0x00000029u, 0x0004003du, 0x00000006u, 0x0000018au, 0x00000189u, + 0x0004007fu, 0x00000006u, 0x0000018bu, 0x0000018au, 0x00050041u, 0x00000020u, 0x0000018cu, 0x00000062u, + 0x00000048u, 0x0004003du, 0x00000006u, 0x0000018du, 0x0000018cu, 0x0004007fu, 0x00000006u, 0x0000018eu, + 0x0000018du, 0x00050050u, 0x0000000du, 0x0000018fu, 0x0000018bu, 0x0000018eu, 0x00050081u, 0x0000000du, + 0x00000190u, 0x00000188u, 0x0000018fu, 0x00050057u, 0x0000002fu, 0x00000191u, 0x00000187u, 0x00000190u, + 0x0008004fu, 0x00000007u, 0x00000193u, 0x00000191u, 0x00000191u, 0x00000000u, 0x00000001u, 0x00000002u, + 0x0003003eu, 0x00000192u, 0x00000193u, 0x00050039u, 0x00000006u, 0x00000194u, 0x0000000bu, 0x00000192u, + 0x0003003eu, 0x00000186u, 0x00000194u, 0x0004003du, 0x00000023u, 0x00000196u, 0x00000025u, 0x0004003du, + 0x0000000du, 0x00000197u, 0x00000070u, 0x00050041u, 0x00000020u, 0x00000198u, 0x00000062u, 0x00000029u, + 0x0004003du, 0x00000006u, 0x00000199u, 0x00000198u, 0x00050041u, 0x00000020u, 0x0000019au, 0x00000062u, + 0x00000048u, 0x0004003du, 0x00000006u, 0x0000019bu, 0x0000019au, 0x0004007fu, 0x00000006u, 0x0000019cu, + 0x0000019bu, 0x00050050u, 0x0000000du, 0x0000019du, 0x00000199u, 0x0000019cu, 0x00050081u, 0x0000000du, + 0x0000019eu, 0x00000197u, 0x0000019du, 0x00050057u, 0x0000002fu, 0x0000019fu, 0x00000196u, 0x0000019eu, + 0x0008004fu, 0x00000007u, 0x000001a1u, 0x0000019fu, 0x0000019fu, 0x00000000u, 0x00000001u, 0x00000002u, + 0x0003003eu, 0x000001a0u, 0x000001a1u, 0x00050039u, 0x00000006u, 0x000001a2u, 0x0000000bu, 0x000001a0u, + 0x0003003eu, 0x00000195u, 0x000001a2u, 0x0004003du, 0x00000023u, 0x000001a4u, 0x00000025u, 0x0004003du, + 0x0000000du, 0x000001a5u, 0x00000070u, 0x00050041u, 0x00000020u, 0x000001a6u, 0x00000062u, 0x00000029u, + 0x0004003du, 0x00000006u, 0x000001a7u, 0x000001a6u, 0x0004007fu, 0x00000006u, 0x000001a8u, 0x000001a7u, + 0x00050041u, 0x00000020u, 0x000001a9u, 0x00000062u, 0x00000048u, 0x0004003du, 0x00000006u, 0x000001aau, + 0x000001a9u, 0x00050050u, 0x0000000du, 0x000001abu, 0x000001a8u, 0x000001aau, 0x00050081u, 0x0000000du, + 0x000001acu, 0x000001a5u, 0x000001abu, 0x00050057u, 0x0000002fu, 0x000001adu, 0x000001a4u, 0x000001acu, + 0x0008004fu, 0x00000007u, 0x000001afu, 0x000001adu, 0x000001adu, 0x00000000u, 0x00000001u, 0x00000002u, + 0x0003003eu, 0x000001aeu, 0x000001afu, 0x00050039u, 0x00000006u, 0x000001b0u, 0x0000000bu, 0x000001aeu, + 0x0003003eu, 0x000001a3u, 0x000001b0u, 0x0004003du, 0x00000023u, 0x000001b2u, 0x00000025u, 0x0004003du, + 0x0000000du, 0x000001b3u, 0x00000070u, 0x00050041u, 0x00000020u, 0x000001b4u, 0x00000062u, 0x00000029u, + 0x0004003du, 0x00000006u, 0x000001b5u, 0x000001b4u, 0x00050041u, 0x00000020u, 0x000001b6u, 0x00000062u, + 0x00000048u, 0x0004003du, 0x00000006u, 0x000001b7u, 0x000001b6u, 0x00050050u, 0x0000000du, 0x000001b8u, + 0x000001b5u, 0x000001b7u, 0x00050081u, 0x0000000du, 0x000001b9u, 0x000001b3u, 0x000001b8u, 0x00050057u, + 0x0000002fu, 0x000001bau, 0x000001b2u, 0x000001b9u, 0x0008004fu, 0x00000007u, 0x000001bcu, 0x000001bau, + 0x000001bau, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x000001bbu, 0x000001bcu, 0x00050039u, + 0x00000006u, 0x000001bdu, 0x0000000bu, 0x000001bbu, 0x0003003eu, 0x000001b1u, 0x000001bdu, 0x0004003du, + 0x00000006u, 0x000001bfu, 0x0000011du, 0x0004003du, 0x00000006u, 0x000001c0u, 0x0000011eu, 0x00050083u, + 0x00000006u, 0x000001c1u, 0x000001bfu, 0x000001c0u, 0x0006000cu, 0x00000006u, 0x000001c2u, 0x00000001u, + 0x00000004u, 0x000001c1u, 0x0004003du, 0x00000006u, 0x000001c3u, 0x0000017bu, 0x0007000cu, 0x00000006u, + 0x000001c4u, 0x00000001u, 0x00000028u, 0x000001c3u, 0x00000063u, 0x00050088u, 0x00000006u, 0x000001c5u, + 0x000001c2u, 0x000001c4u, 0x0008000cu, 0x00000006u, 0x000001c6u, 0x00000001u, 0x0000002bu, 0x000001c5u, + 0x0000002cu, 0x00000063u, 0x0003003eu, 0x000001beu, 0x000001c6u, 0x0004003du, 0x00000006u, 0x000001c8u, + 0x000001beu, 0x0004003du, 0x00000006u, 0x000001c9u, 0x0000017bu, 0x00050085u, 0x00000006u, 0x000001cbu, + 0x000001c9u, 0x000001cau, 0x00050081u, 0x00000006u, 0x000001ccu, 0x00000063u, 0x000001cbu, 0x00050088u, + 0x00000006u, 0x000001cdu, 0x000001c8u, 0x000001ccu, 0x0003003eu, 0x000001c7u, 0x000001cdu, 0x0004003du, + 0x000000f1u, 0x000001cfu, 0x000000fau, 0x000300f7u, 0x000001d2u, 0x00000000u, 0x000400fau, 0x000001cfu, + 0x000001d1u, 0x000001d7u, 0x000200f8u, 0x000001d1u, 0x0004003du, 0x00000006u, 0x000001d3u, 0x00000186u, + 0x0004003du, 0x00000006u, 0x000001d4u, 0x00000195u, 0x00050083u, 0x00000006u, 0x000001d5u, 0x000001d3u, + 0x000001d4u, 0x0006000cu, 0x00000006u, 0x000001d6u, 0x00000001u, 0x00000004u, 0x000001d5u, 0x0003003eu, + 0x000001d0u, 0x000001d6u, 0x000200f9u, 0x000001d2u, 0x000200f8u, 0x000001d7u, 0x0004003du, 0x00000006u, + 0x000001d8u, 0x00000186u, 0x0004003du, 0x00000006u, 0x000001d9u, 0x000001a3u, 0x00050083u, 0x00000006u, + 0x000001dau, 0x000001d8u, 0x000001d9u, 0x0006000cu, 0x00000006u, 0x000001dbu, 0x00000001u, 0x00000004u, + 0x000001dau, 0x0003003eu, 0x000001d0u, 0x000001dbu, 0x000200f9u, 0x000001d2u, 0x000200f8u, 0x000001d2u, + 0x0004003du, 0x00000006u, 0x000001dcu, 0x000001d0u, 0x0003003eu, 0x000001ceu, 0x000001dcu, 0x0004003du, + 0x000000f1u, 0x000001deu, 0x000000fau, 0x000300f7u, 0x000001e1u, 0x00000000u, 0x000400fau, 0x000001deu, + 0x000001e0u, 0x000001e6u, 0x000200f8u, 0x000001e0u, 0x0004003du, 0x00000006u, 0x000001e2u, 0x000001a3u, + 0x0004003du, 0x00000006u, 0x000001e3u, 0x000001b1u, 0x00050083u, 0x00000006u, 0x000001e4u, 0x000001e2u, + 0x000001e3u, 0x0006000cu, 0x00000006u, 0x000001e5u, 0x00000001u, 0x00000004u, 0x000001e4u, 0x0003003eu, + 0x000001dfu, 0x000001e5u, 0x000200f9u, 0x000001e1u, 0x000200f8u, 0x000001e6u, 0x0004003du, 0x00000006u, + 0x000001e7u, 0x00000195u, 0x0004003du, 0x00000006u, 0x000001e8u, 0x000001b1u, 0x00050083u, 0x00000006u, + 0x000001e9u, 0x000001e7u, 0x000001e8u, 0x0006000cu, 0x00000006u, 0x000001eau, 0x00000001u, 0x00000004u, + 0x000001e9u, 0x0003003eu, 0x000001dfu, 0x000001eau, 0x000200f9u, 0x000001e1u, 0x000200f8u, 0x000001e1u, + 0x0004003du, 0x00000006u, 0x000001ebu, 0x000001dfu, 0x0003003eu, 0x000001ddu, 0x000001ebu, 0x0004003du, + 0x00000006u, 0x000001edu, 0x000001ceu, 0x0004003du, 0x00000006u, 0x000001eeu, 0x000001ddu, 0x00050083u, + 0x00000006u, 0x000001efu, 0x000001edu, 0x000001eeu, 0x0006000cu, 0x00000006u, 0x000001f0u, 0x00000001u, + 0x00000004u, 0x000001efu, 0x0003003eu, 0x000001ecu, 0x000001f0u, 0x0004003du, 0x00000006u, 0x000001f2u, + 0x000000ddu, 0x0004003du, 0x00000006u, 0x000001f3u, 0x000000ddu, 0x00050085u, 0x00000006u, 0x000001f4u, + 0x000001f3u, 0x00000182u, 0x0004003du, 0x00000006u, 0x000001f5u, 0x000001ecu, 0x0008000cu, 0x00000006u, + 0x000001f6u, 0x00000001u, 0x00000031u, 0x000001f2u, 0x000001f4u, 0x000001f5u, 0x0003003eu, 0x000001f1u, + 0x000001f6u, 0x0004003du, 0x00000006u, 0x000001f9u, 0x000001f1u, 0x00050085u, 0x00000006u, 0x000001fau, + 0x000001f8u, 0x000001f9u, 0x0004003du, 0x00000006u, 0x000001fbu, 0x0000017bu, 0x00050088u, 0x00000006u, + 0x000001fdu, 0x000001fbu, 0x000001fcu, 0x0008000cu, 0x00000006u, 0x000001feu, 0x00000001u, 0x0000002bu, + 0x000001fdu, 0x0000002cu, 0x00000063u, 0x00050085u, 0x00000006u, 0x000001ffu, 0x000001fau, 0x000001feu, + 0x0003003eu, 0x000001f7u, 0x000001ffu, 0x0004003du, 0x00000006u, 0x00000201u, 0x00000186u, 0x0004003du, + 0x00000006u, 0x00000202u, 0x000001b1u, 0x00050083u, 0x00000006u, 0x00000203u, 0x00000201u, 0x00000202u, + 0x0006000cu, 0x00000006u, 0x00000204u, 0x00000001u, 0x00000004u, 0x00000203u, 0x0004003du, 0x00000006u, + 0x00000205u, 0x00000195u, 0x0004003du, 0x00000006u, 0x00000206u, 0x000001a3u, 0x00050083u, 0x00000006u, + 0x00000207u, 0x00000205u, 0x00000206u, 0x0006000cu, 0x00000006u, 0x00000208u, 0x00000001u, 0x00000004u, + 0x00000207u, 0x0007000cu, 0x00000006u, 0x00000209u, 0x00000001u, 0x00000028u, 0x00000204u, 0x00000208u, + 0x0003003eu, 0x00000200u, 0x00000209u, 0x0004003du, 0x00000006u, 0x0000020cu, 0x000000ddu, 0x0004003du, + 0x00000006u, 0x0000020du, 0x000000ddu, 0x00050085u, 0x00000006u, 0x0000020fu, 0x0000020du, 0x0000020eu, + 0x0004003du, 0x00000006u, 0x00000210u, 0x00000200u, 0x0008000cu, 0x00000006u, 0x00000211u, 0x00000001u, + 0x00000031u, 0x0000020cu, 0x0000020fu, 0x00000210u, 0x00050085u, 0x00000006u, 0x00000212u, 0x0000020bu, + 0x00000211u, 0x00050083u, 0x00000006u, 0x00000213u, 0x00000063u, 0x00000212u, 0x0003003eu, 0x0000020au, + 0x00000213u, 0x0004003du, 0x00000006u, 0x00000215u, 0x000001f7u, 0x0004003du, 0x00000006u, 0x00000216u, + 0x000001c7u, 0x00050085u, 0x00000006u, 0x00000217u, 0x00000215u, 0x00000216u, 0x0004003du, 0x00000006u, + 0x00000218u, 0x0000017fu, 0x00050085u, 0x00000006u, 0x00000219u, 0x00000217u, 0x00000218u, 0x0004003du, + 0x00000006u, 0x0000021au, 0x0000020au, 0x00050085u, 0x00000006u, 0x0000021bu, 0x00000219u, 0x0000021au, + 0x0003003eu, 0x00000214u, 0x0000021bu, 0x0004003du, 0x00000006u, 0x0000021du, 0x000000e3u, 0x0004003du, + 0x00000006u, 0x0000021eu, 0x000000e7u, 0x0007000cu, 0x00000006u, 0x0000021fu, 0x00000001u, 0x00000025u, + 0x0000021du, 0x0000021eu, 0x0003003eu, 0x0000021cu, 0x0000021fu, 0x0004003du, 0x00000006u, 0x00000221u, + 0x000000ddu, 0x0004003du, 0x00000006u, 0x00000222u, 0x000000ddu, 0x00050085u, 0x00000006u, 0x00000223u, + 0x00000222u, 0x00000182u, 0x0004003du, 0x00000006u, 0x00000224u, 0x0000021cu, 0x0008000cu, 0x00000006u, + 0x00000225u, 0x00000001u, 0x00000031u, 0x00000221u, 0x00000223u, 0x00000224u, 0x0003003eu, 0x00000220u, + 0x00000225u, 0x0004003du, 0x00000006u, 0x00000227u, 0x0000017bu, 0x0008000cu, 0x00000006u, 0x00000228u, + 0x00000001u, 0x00000031u, 0x00000063u, 0x0000020eu, 0x00000227u, 0x0003003eu, 0x00000226u, 0x00000228u, + 0x0004003du, 0x00000006u, 0x0000022bu, 0x00000220u, 0x00050085u, 0x00000006u, 0x0000022cu, 0x0000022au, + 0x0000022bu, 0x0004003du, 0x00000006u, 0x0000022du, 0x0000017fu, 0x00050085u, 0x00000006u, 0x0000022eu, + 0x0000022cu, 0x0000022du, 0x0004003du, 0x00000006u, 0x0000022fu, 0x0000020au, 0x00050085u, 0x00000006u, + 0x00000230u, 0x0000022eu, 0x0000022fu, 0x0004003du, 0x00000006u, 0x00000231u, 0x00000226u, 0x00050085u, + 0x00000006u, 0x00000232u, 0x00000230u, 0x00000231u, 0x0004003du, 0x00000006u, 0x00000233u, 0x000001f1u, + 0x00050085u, 0x00000006u, 0x00000234u, 0x00000232u, 0x00000233u, 0x0003003eu, 0x00000229u, 0x00000234u, + 0x0004003du, 0x00000006u, 0x00000236u, 0x00000214u, 0x0004003du, 0x00000006u, 0x00000237u, 0x00000229u, + 0x0007000cu, 0x00000006u, 0x00000238u, 0x00000001u, 0x00000028u, 0x00000236u, 0x00000237u, 0x0008000cu, + 0x00000006u, 0x0000023au, 0x00000001u, 0x0000002bu, 0x00000238u, 0x0000002cu, 0x00000239u, 0x0003003eu, + 0x00000235u, 0x0000023au, 0x0004003du, 0x00000023u, 0x0000023cu, 0x00000025u, 0x0004003du, 0x0000000du, + 0x0000023du, 0x00000070u, 0x0004003du, 0x0000000du, 0x0000023eu, 0x0000010bu, 0x0004003du, 0x0000000du, + 0x0000023fu, 0x00000062u, 0x00050085u, 0x0000000du, 0x00000240u, 0x0000023eu, 0x0000023fu, 0x00050081u, + 0x0000000du, 0x00000241u, 0x0000023du, 0x00000240u, 0x00050057u, 0x0000002fu, 0x00000242u, 0x0000023cu, + 0x00000241u, 0x0008004fu, 0x00000007u, 0x00000243u, 0x00000242u, 0x00000242u, 0x00000000u, 0x00000001u, + 0x00000002u, 0x0003003eu, 0x0000023bu, 0x00000243u, 0x0004003du, 0x0000002fu, 0x00000244u, 0x0000007cu, + 0x0008004fu, 0x00000007u, 0x00000245u, 0x00000244u, 0x00000244u, 0x00000000u, 0x00000001u, 0x00000002u, + 0x0004003du, 0x00000007u, 0x00000246u, 0x0000023bu, 0x0004003du, 0x00000006u, 0x00000247u, 0x00000235u, + 0x00060050u, 0x00000007u, 0x00000248u, 0x00000247u, 0x00000247u, 0x00000247u, 0x0008000cu, 0x00000007u, + 0x00000249u, 0x00000001u, 0x0000002eu, 0x00000245u, 0x00000246u, 0x00000248u, 0x00050041u, 0x00000020u, + 0x0000024bu, 0x0000007cu, 0x0000024au, 0x0004003du, 0x00000006u, 0x0000024cu, 0x0000024bu, 0x00050051u, + 0x00000006u, 0x0000024du, 0x00000249u, 0x00000000u, 0x00050051u, 0x00000006u, 0x0000024eu, 0x00000249u, + 0x00000001u, 0x00050051u, 0x00000006u, 0x0000024fu, 0x00000249u, 0x00000002u, 0x00070050u, 0x0000002fu, + 0x00000250u, 0x0000024du, 0x0000024eu, 0x0000024fu, 0x0000024cu, 0x0003003eu, 0x000000f6u, 0x00000250u, + 0x000100fdu, 0x00010038u, 0x00050036u, 0x00000006u, 0x0000000bu, 0x00000000u, 0x00000009u, 0x00030037u, + 0x00000008u, 0x0000000au, 0x000200f8u, 0x0000000cu, 0x0004003du, 0x00000007u, 0x00000018u, 0x0000000au, + 0x00050094u, 0x00000006u, 0x0000001du, 0x00000018u, 0x0000001cu, 0x000200feu, 0x0000001du, 0x00010038u, + 0x00050036u, 0x00000006u, 0x00000012u, 0x00000000u, 0x0000000fu, 0x00030037u, 0x0000000eu, 0x00000010u, + 0x00030037u, 0x0000000eu, 0x00000011u, 0x000200f8u, 0x00000013u, 0x0004003bu, 0x00000020u, 0x00000021u, + 0x00000007u, 0x0004003bu, 0x00000008u, 0x00000031u, 0x00000007u, 0x0004003bu, 0x00000020u, 0x00000034u, + 0x00000007u, 0x0004003bu, 0x00000008u, 0x0000003cu, 0x00000007u, 0x0004003du, 0x00000023u, 0x00000026u, + 0x00000025u, 0x0004003du, 0x0000000du, 0x00000027u, 0x00000010u, 0x00050041u, 0x00000020u, 0x0000002au, + 0x00000011u, 0x00000029u, 0x0004003du, 0x00000006u, 0x0000002bu, 0x0000002au, 0x00050050u, 0x0000000du, + 0x0000002du, 0x0000002bu, 0x0000002cu, 0x00050083u, 0x0000000du, 0x0000002eu, 0x00000027u, 0x0000002du, + 0x00050057u, 0x0000002fu, 0x00000030u, 0x00000026u, 0x0000002eu, 0x0008004fu, 0x00000007u, 0x00000032u, + 0x00000030u, 0x00000030u, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x00000031u, 0x00000032u, + 0x00050039u, 0x00000006u, 0x00000033u, 0x0000000bu, 0x00000031u, 0x0003003eu, 0x00000021u, 0x00000033u, + 0x0004003du, 0x00000023u, 0x00000035u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000036u, 0x00000010u, + 0x00050041u, 0x00000020u, 0x00000037u, 0x00000011u, 0x00000029u, 0x0004003du, 0x00000006u, 0x00000038u, + 0x00000037u, 0x00050050u, 0x0000000du, 0x00000039u, 0x00000038u, 0x0000002cu, 0x00050081u, 0x0000000du, + 0x0000003au, 0x00000036u, 0x00000039u, 0x00050057u, 0x0000002fu, 0x0000003bu, 0x00000035u, 0x0000003au, + 0x0008004fu, 0x00000007u, 0x0000003du, 0x0000003bu, 0x0000003bu, 0x00000000u, 0x00000001u, 0x00000002u, + 0x0003003eu, 0x0000003cu, 0x0000003du, 0x00050039u, 0x00000006u, 0x0000003eu, 0x0000000bu, 0x0000003cu, + 0x0003003eu, 0x00000034u, 0x0000003eu, 0x0004003du, 0x00000006u, 0x0000003fu, 0x00000021u, 0x0004003du, + 0x00000006u, 0x00000040u, 0x00000034u, 0x00050083u, 0x00000006u, 0x00000041u, 0x0000003fu, 0x00000040u, + 0x0006000cu, 0x00000006u, 0x00000042u, 0x00000001u, 0x00000004u, 0x00000041u, 0x000200feu, 0x00000042u, + 0x00010038u, 0x00050036u, 0x00000006u, 0x00000016u, 0x00000000u, 0x0000000fu, 0x00030037u, 0x0000000eu, + 0x00000014u, 0x00030037u, 0x0000000eu, 0x00000015u, 0x000200f8u, 0x00000017u, 0x0004003bu, 0x00000020u, + 0x00000045u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x0000004eu, 0x00000007u, 0x0004003bu, 0x00000020u, + 0x00000051u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x00000059u, 0x00000007u, 0x0004003du, 0x00000023u, + 0x00000046u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000047u, 0x00000014u, 0x00050041u, 0x00000020u, + 0x00000049u, 0x00000015u, 0x00000048u, 0x0004003du, 0x00000006u, 0x0000004au, 0x00000049u, 0x00050050u, + 0x0000000du, 0x0000004bu, 0x0000002cu, 0x0000004au, 0x00050083u, 0x0000000du, 0x0000004cu, 0x00000047u, + 0x0000004bu, 0x00050057u, 0x0000002fu, 0x0000004du, 0x00000046u, 0x0000004cu, 0x0008004fu, 0x00000007u, + 0x0000004fu, 0x0000004du, 0x0000004du, 0x00000000u, 0x00000001u, 0x00000002u, 0x0003003eu, 0x0000004eu, + 0x0000004fu, 0x00050039u, 0x00000006u, 0x00000050u, 0x0000000bu, 0x0000004eu, 0x0003003eu, 0x00000045u, + 0x00000050u, 0x0004003du, 0x00000023u, 0x00000052u, 0x00000025u, 0x0004003du, 0x0000000du, 0x00000053u, + 0x00000014u, 0x00050041u, 0x00000020u, 0x00000054u, 0x00000015u, 0x00000048u, 0x0004003du, 0x00000006u, + 0x00000055u, 0x00000054u, 0x00050050u, 0x0000000du, 0x00000056u, 0x0000002cu, 0x00000055u, 0x00050081u, + 0x0000000du, 0x00000057u, 0x00000053u, 0x00000056u, 0x00050057u, 0x0000002fu, 0x00000058u, 0x00000052u, + 0x00000057u, 0x0008004fu, 0x00000007u, 0x0000005au, 0x00000058u, 0x00000058u, 0x00000000u, 0x00000001u, + 0x00000002u, 0x0003003eu, 0x00000059u, 0x0000005au, 0x00050039u, 0x00000006u, 0x0000005bu, 0x0000000bu, + 0x00000059u, 0x0003003eu, 0x00000051u, 0x0000005bu, 0x0004003du, 0x00000006u, 0x0000005cu, 0x00000045u, + 0x0004003du, 0x00000006u, 0x0000005du, 0x00000051u, 0x00050083u, 0x00000006u, 0x0000005eu, 0x0000005cu, + 0x0000005du, 0x0006000cu, 0x00000006u, 0x0000005fu, 0x00000001u, 0x00000004u, 0x0000005eu, 0x000200feu, + 0x0000005fu, 0x00010038u, }; diff --git a/app/src/main/cpp/waylandcomp/CMakeLists.txt b/app/src/main/cpp/waylandcomp/CMakeLists.txt index c7aa1b0eb4..13e9e1b3e0 100644 --- a/app/src/main/cpp/waylandcomp/CMakeLists.txt +++ b/app/src/main/cpp/waylandcomp/CMakeLists.txt @@ -26,7 +26,7 @@ add_library(droiddeckwayland SHARED generated/linux-dmabuf-v1-protocol.c generated/wayland-android-protocol.c generated/viewporter-protocol.c - generated/banner-desktop-v1-protocol.c + generated/droiddeck-desktop-v1-protocol.c generated/presentation-time-protocol.c generated/pointer-constraints-unstable-v1-protocol.c generated/relative-pointer-unstable-v1-protocol.c diff --git a/app/src/main/cpp/waylandcomp/generated/banner-desktop-v1-protocol.c b/app/src/main/cpp/waylandcomp/generated/droiddeck-desktop-v1-protocol.c similarity index 76% rename from app/src/main/cpp/waylandcomp/generated/banner-desktop-v1-protocol.c rename to app/src/main/cpp/waylandcomp/generated/droiddeck-desktop-v1-protocol.c index ae0a87daa1..c96d2aa689 100644 --- a/app/src/main/cpp/waylandcomp/generated/banner-desktop-v1-protocol.c +++ b/app/src/main/cpp/waylandcomp/generated/droiddeck-desktop-v1-protocol.c @@ -38,7 +38,7 @@ extern const struct wl_interface wl_surface_interface; -static const struct wl_interface *banner_desktop_v1_types[] = { +static const struct wl_interface *droiddeck_desktop_v1_types[] = { NULL, &wl_surface_interface, &wl_surface_interface, @@ -47,16 +47,16 @@ static const struct wl_interface *banner_desktop_v1_types[] = { NULL, }; -static const struct wl_message banner_desktop_v1_requests[] = { - { "destroy", "", banner_desktop_v1_types + 0 }, - { "set_desktop", "o", banner_desktop_v1_types + 1 }, - { "set_window", "ouii", banner_desktop_v1_types + 2 }, - { "set_zorder", "a", banner_desktop_v1_types + 0 }, +static const struct wl_message droiddeck_desktop_v1_requests[] = { + { "destroy", "", droiddeck_desktop_v1_types + 0 }, + { "set_desktop", "o", droiddeck_desktop_v1_types + 1 }, + { "set_window", "ouii", droiddeck_desktop_v1_types + 2 }, + { "set_zorder", "a", droiddeck_desktop_v1_types + 0 }, }; -WL_PRIVATE const struct wl_interface banner_desktop_v1_interface = { - "banner_desktop_v1", 1, - 4, banner_desktop_v1_requests, +WL_PRIVATE const struct wl_interface droiddeck_desktop_v1_interface = { + "droiddeck_desktop_v1", 1, + 4, droiddeck_desktop_v1_requests, 0, NULL, }; diff --git a/app/src/main/cpp/waylandcomp/generated/banner-desktop-v1-server-protocol.h b/app/src/main/cpp/waylandcomp/generated/droiddeck-desktop-v1-server-protocol.h similarity index 76% rename from app/src/main/cpp/waylandcomp/generated/banner-desktop-v1-server-protocol.h rename to app/src/main/cpp/waylandcomp/generated/droiddeck-desktop-v1-server-protocol.h index 78f65e7fbb..37e704f3bf 100644 --- a/app/src/main/cpp/waylandcomp/generated/banner-desktop-v1-server-protocol.h +++ b/app/src/main/cpp/waylandcomp/generated/droiddeck-desktop-v1-server-protocol.h @@ -1,6 +1,6 @@ -#ifndef BANNER_DESKTOP_V1_SERVER_PROTOCOL_H -#define BANNER_DESKTOP_V1_SERVER_PROTOCOL_H +#ifndef DROIDDECK_DESKTOP_V1_SERVER_PROTOCOL_H +#define DROIDDECK_DESKTOP_V1_SERVER_PROTOCOL_H #include #include @@ -14,7 +14,7 @@ struct wl_client; struct wl_resource; /* - * @section page_copyright_banner_desktop_v1 Copyright + * @section page_copyright_droiddeck_desktop_v1 Copyright * * Copyright 2026 The412Banner * @@ -42,15 +42,15 @@ struct wl_resource; -struct banner_desktop_v1; +struct droiddeck_desktop_v1; struct wl_surface; -#ifndef BANNER_DESKTOP_V1_INTERFACE -#define BANNER_DESKTOP_V1_INTERFACE -extern const struct wl_interface banner_desktop_v1_interface; +#ifndef DROIDDECK_DESKTOP_V1_INTERFACE +#define DROIDDECK_DESKTOP_V1_INTERFACE +extern const struct wl_interface droiddeck_desktop_v1_interface; #endif -struct banner_desktop_v1_interface { +struct droiddeck_desktop_v1_interface { void (*destroy)(struct wl_client *client, struct wl_resource *resource); void (*set_desktop)(struct wl_client *client, @@ -68,10 +68,10 @@ struct banner_desktop_v1_interface { }; -#define BANNER_DESKTOP_V1_DESTROY_SINCE_VERSION 1 -#define BANNER_DESKTOP_V1_SET_DESKTOP_SINCE_VERSION 1 -#define BANNER_DESKTOP_V1_SET_WINDOW_SINCE_VERSION 1 -#define BANNER_DESKTOP_V1_SET_ZORDER_SINCE_VERSION 1 +#define DROIDDECK_DESKTOP_V1_DESTROY_SINCE_VERSION 1 +#define DROIDDECK_DESKTOP_V1_SET_DESKTOP_SINCE_VERSION 1 +#define DROIDDECK_DESKTOP_V1_SET_WINDOW_SINCE_VERSION 1 +#define DROIDDECK_DESKTOP_V1_SET_ZORDER_SINCE_VERSION 1 #ifdef __cplusplus } diff --git a/app/src/main/cpp/waylandcomp/protocols/banner-desktop-v1.xml b/app/src/main/cpp/waylandcomp/protocols/droiddeck-desktop-v1.xml similarity index 96% rename from app/src/main/cpp/waylandcomp/protocols/banner-desktop-v1.xml rename to app/src/main/cpp/waylandcomp/protocols/droiddeck-desktop-v1.xml index 7c62b2a2e2..45ba5572a1 100644 --- a/app/src/main/cpp/waylandcomp/protocols/banner-desktop-v1.xml +++ b/app/src/main/cpp/waylandcomp/protocols/droiddeck-desktop-v1.xml @@ -1,5 +1,5 @@ - + Copyright 2026 The412Banner @@ -23,7 +23,7 @@ DEALINGS IN THE SOFTWARE. - + Each Wine process is a separate Wayland client, so a Windows virtual desktop can't be built from subsurfaces. Instead the process that owns diff --git a/app/src/main/cpp/waylandcomp/src/compositor.c b/app/src/main/cpp/waylandcomp/src/compositor.c index 94ec75d26e..f78f0d3f86 100644 --- a/app/src/main/cpp/waylandcomp/src/compositor.c +++ b/app/src/main/cpp/waylandcomp/src/compositor.c @@ -24,7 +24,7 @@ #include "sc_layer.h" #include "ahb_swapchain.h" #include "viewporter-server-protocol.h" -#include "banner-desktop-v1-server-protocol.h" +#include "droiddeck-desktop-v1-server-protocol.h" #include "presentation-time-server-protocol.h" #include "pointer-constraints-unstable-v1-server-protocol.h" #include "relative-pointer-unstable-v1-server-protocol.h" @@ -79,7 +79,7 @@ static void open_session_log(void) { localtime_r(&now, &tm); strftime(stamp, sizeof(stamp), "%Y-%m-%d_%H-%M-%S", &tm); - const char *given = getenv("BL_WAYLAND_LOG"); + const char *given = getenv("DD_WAYLAND_LOG"); if (given && *given) { snprintf(path, sizeof(path), "%s", given); } else { @@ -256,6 +256,7 @@ struct surface { struct wl_list child_link; int sub_x, sub_y, sub_pending_x, sub_pending_y, sub_pending; int below_parent; + int sub_desync; int fullscreen; int toplevel_committed; @@ -332,6 +333,7 @@ struct pending_release { struct wl_resource *buffer; struct wl_listener destroy; struct surface *surface; + struct surface *held_by; int64_t at_ns; int64_t since_ns; struct wl_list link; @@ -434,10 +436,54 @@ static void pending_release_free(struct pending_release *pr) { free(pr); } +static void release_due_buffers(void); +static void arm_release_timer(void); + static void pending_releases_forget_surface(struct surface *s) { struct pending_release *pr; - wl_list_for_each(pr, &g_pending_releases, link) + int unheld = 0; + wl_list_for_each(pr, &g_pending_releases, link) { if (pr->surface == s) pr->surface = NULL; + if (pr->held_by == s) { pr->held_by = NULL; unheld = 1; } + } + if (unheld) { release_due_buffers(); arm_release_timer(); } +} + +static void pending_releases_cancel(struct wl_resource *buffer) { + struct pending_release *pr, *tmp; + wl_list_for_each_safe(pr, tmp, &g_pending_releases, link) + if (pr->buffer == buffer) pending_release_free(pr); +} + +static void pending_releases_apply(struct surface *holder) { + struct pending_release *pr; + int unheld = 0; + wl_list_for_each(pr, &g_pending_releases, link) + if (pr->held_by == holder) { pr->held_by = NULL; unheld = 1; } + if (unheld) { release_due_buffers(); arm_release_timer(); } +} + +static struct surface *sync_holder(struct surface *s) { + struct surface *holder = NULL; + for (int depth = 0; s && s->role == ROLE_SUBSURFACE && s->parent && depth < 8; depth++) { + if (!s->sub_desync) holder = s->parent; + s = s->parent; + } + return holder; +} + +static void pending_releases_rehold(struct surface *changed) { + struct pending_release *pr; + int unheld = 0; + wl_list_for_each(pr, &g_pending_releases, link) { + if (!pr->held_by || !pr->surface) continue; + struct surface *s = pr->surface; + for (int depth = 0; s && s != changed && depth < 8; depth++) s = s->parent; + if (s != changed) continue; + pr->held_by = sync_holder(pr->surface); + if (!pr->held_by) unheld = 1; + } + if (unheld) { release_due_buffers(); arm_release_timer(); } } static void on_pending_release_buffer_destroyed(struct wl_listener *l, void *data) { @@ -450,20 +496,18 @@ static void arm_release_timer(void) { int64_t earliest = 0; if (g_release_timer_fd < 0) return; wl_list_for_each(pr, &g_pending_releases, link) - if (!buffer_release_blocked(pr->buffer) && (!earliest || pr->at_ns < earliest)) + if (!pr->held_by && !buffer_release_blocked(pr->buffer) && (!earliest || pr->at_ns < earliest)) earliest = pr->at_ns; struct itimerspec its = {0}; if (earliest) { its.it_value.tv_sec = earliest / 1000000000LL; its.it_value.tv_nsec = earliest % 1000000000LL; } timerfd_settime(g_release_timer_fd, TFD_TIMER_ABSTIME, &its, NULL); } -static int on_release_timer(int fd, uint32_t mask, void *data) { +static void release_due_buffers(void) { struct pending_release *pr, *tmp; - uint64_t expirations; int64_t now = now_ns() + 300000; - if (read(fd, &expirations, sizeof(expirations)) < 0 && errno != EAGAIN) return 0; wl_list_for_each_safe(pr, tmp, &g_pending_releases, link) { - if (pr->at_ns <= now && !buffer_release_blocked(pr->buffer)) { + if (!pr->held_by && pr->at_ns <= now && !buffer_release_blocked(pr->buffer)) { /* Attached again since (to its surface or another): that surface releases it later. */ if (buffer_shown_elsewhere(pr->buffer, NULL)) { pending_release_free(pr); @@ -474,28 +518,39 @@ static int on_release_timer(int fd, uint32_t mask, void *data) { pending_release_free(pr); } } +} + +static int on_release_timer(int fd, uint32_t mask, void *data) { + uint64_t expirations; + if (read(fd, &expirations, sizeof(expirations)) < 0 && errno != EAGAIN) return 0; + release_due_buffers(); wl_display_flush_clients(g_display); arm_release_timer(); return 0; } -static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_t since_ns) { +static void release_buffer(struct surface *s, struct wl_resource *buffer, int64_t since_ns, struct surface *holder) { /* No allocation or immediate-release fallback is allowed for a quarantined * DMA-BUF. Existing queued releases stay held; their timer is disarmed. */ if (buffer_release_blocked(buffer)) return; const int limit = g_fps_limit; const int64_t interval = limit > 0 ? 1000000000LL / limit : g_refresh_ns; - if (g_release_unpaced || interval <= 0 || g_release_timer_fd < 0) { send_buffer_release(buffer); perf_note_release(since_ns); return; } + const int paced = !g_release_unpaced && interval > 0 && g_release_timer_fd >= 0; + if (!paced && !holder) { send_buffer_release(buffer); perf_note_release(since_ns); return; } int64_t now = now_ns(); - int64_t at = s->next_release_ns + interval; - int64_t latest = now + interval * (int64_t)(s->releases_pending + 1); - if (at < now) at = now; - if (at > latest) at = latest; - s->next_release_ns = at; + int64_t at = now; + if (paced) { + int64_t latest = now + interval * (int64_t)(s->releases_pending + 1); + at = s->next_release_ns + interval; + if (at < now) at = now; + if (at > latest) at = latest; + s->next_release_ns = at; + } struct pending_release *pr = calloc(1, sizeof(*pr)); if (!pr) { send_buffer_release(buffer); perf_note_release(since_ns); return; } pr->buffer = buffer; pr->surface = s; + pr->held_by = holder; pr->at_ns = at; pr->since_ns = since_ns; pr->destroy.notify = on_pending_release_buffer_destroyed; @@ -721,7 +776,7 @@ static void drop_dmabuf(struct surface *s, int paced) { wl_list_remove(&s->dmabuf_destroy.link); if (buffer_shown_elsewhere(s->dmabuf, s)) { } else if (!ahb_swapchain_defer_release(s->dmabuf_buf, s->dmabuf, s, paced)) { - if (paced) release_buffer(s, s->dmabuf, now_ns()); + if (paced) release_buffer(s, s->dmabuf, now_ns(), sync_holder(s)); else send_buffer_release(s->dmabuf); } s->dmabuf = NULL; @@ -887,6 +942,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re s->last_dmabuf = buffer; pace_note_buffer(buffer); drop_dmabuf(s, 1); + pending_releases_cancel(buffer); s->dmabuf = buffer; s->dmabuf_buf = b; b->refs++; @@ -977,7 +1033,7 @@ void droiddeck_dmabuf_ref(struct dmabuf_buffer *b) { b->refs++; } void droiddeck_dmabuf_unref(struct dmabuf_buffer *b) { dmabuf_buffer_unref(b); } void droiddeck_release_buffer(struct surface *s, struct wl_resource *buffer, int paced, int64_t since_ns) { if (buffer_release_blocked(buffer)) return; - if (paced && s) release_buffer(s, buffer, since_ns); + if (paced && s) release_buffer(s, buffer, since_ns, NULL); else { send_buffer_release(buffer); perf_note_release(since_ns); } } void droiddeck_surface_describe(const struct surface *s, char *out, size_t size) { describe(s, out, size); } @@ -1265,6 +1321,7 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) { s->pending_attach = 0; surface_drop_idle(s); + buf_trace_attach(buffer); if (s->role == ROLE_CURSOR) { if (!buffer) { cursor_publish_hidden(); @@ -1275,7 +1332,6 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) { } else if (s->role == ROLE_NONE) { if (buffer) surface_hold_idle(s, buffer); } else if (db) { - buf_trace_attach(buffer); take_dmabuf(s, db, buffer); } else if (shm) { drop_dmabuf(s, 1); @@ -1289,6 +1345,7 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) { if (buffer) send_buffer_release(buffer); } } + pending_releases_apply(s); wl_list_for_each(child, &s->children, child_link) { if (child->sub_pending) { @@ -1486,8 +1543,14 @@ static void subsurface_place_below(struct wl_client *c, struct wl_resource *r, struct wl_resource *sibling) { restack_child(wl_resource_get_user_data(r), wl_resource_get_user_data(sibling), 0); } -static void subsurface_set_sync(struct wl_client *c, struct wl_resource *r) {} -static void subsurface_set_desync(struct wl_client *c, struct wl_resource *r) {} +static void subsurface_set_sync(struct wl_client *c, struct wl_resource *r) { + struct surface *s = wl_resource_get_user_data(r); + if (s) s->sub_desync = 0; +} +static void subsurface_set_desync(struct wl_client *c, struct wl_resource *r) { + struct surface *s = wl_resource_get_user_data(r); + if (s) { s->sub_desync = 1; pending_releases_rehold(s); } +} static const struct wl_subsurface_interface subsurface_impl = { .destroy = subsurface_destroy, .set_position = subsurface_set_position, @@ -1521,6 +1584,7 @@ static void subcompositor_get_subsurface(struct wl_client *c, struct wl_resource s->subsurface = sub; s->parent = p; s->below_parent = 0; + s->sub_desync = 0; s->sub_x = s->sub_y = 0; wl_list_insert(p->children.prev, &s->child_link); } @@ -1796,14 +1860,14 @@ static void desktop_set_zorder(struct wl_client *c, struct wl_resource *r, struc apply_zorder(); schedule_render(); } -static const struct banner_desktop_v1_interface desktop_impl = { +static const struct droiddeck_desktop_v1_interface desktop_impl = { .destroy = desktop_destroy_req, .set_desktop = desktop_set_desktop, .set_window = desktop_set_window, .set_zorder = desktop_set_zorder, }; static void bind_desktop(struct wl_client *c, void *data, uint32_t ver, uint32_t id) { - struct wl_resource *r = wl_resource_create(c, &banner_desktop_v1_interface, ver, id); + struct wl_resource *r = wl_resource_create(c, &droiddeck_desktop_v1_interface, ver, id); wl_resource_set_implementation(r, &desktop_impl, NULL, NULL); } @@ -4083,7 +4147,7 @@ int droiddeck_wayland_run(void) { wl_global_create(display, &zwp_linux_dmabuf_v1_interface, 4, NULL, bind_dmabuf); droiddeck_android_wlegl_init(display); wl_global_create(display, &wl_seat_interface, 9, NULL, bind_seat); - wl_global_create(display, &banner_desktop_v1_interface, 1, NULL, bind_desktop); + wl_global_create(display, &droiddeck_desktop_v1_interface, 1, NULL, bind_desktop); wl_global_create(display, &wp_presentation_interface, 2, NULL, bind_presentation); wl_global_create(display, &zwp_pointer_constraints_v1_interface, 1, NULL, bind_pointer_constraints); wl_global_create(display, &zwp_relative_pointer_manager_v1_interface, 1, NULL, bind_relative_pointer_manager); diff --git a/app/src/main/cpp/waylandcomp/src/effects_chain.c b/app/src/main/cpp/waylandcomp/src/effects_chain.c index 141a536229..385a46b322 100644 --- a/app/src/main/cpp/waylandcomp/src/effects_chain.c +++ b/app/src/main/cpp/waylandcomp/src/effects_chain.c @@ -155,6 +155,10 @@ int vkp_effects_upscaling(void) { return spatial_mode(g_cur.scaling) && g_cur.scaling != 6; } +int vkp_effects_sharpening(void) { + return vkp_effects_upscaling() || cas_active(&g_cur); +} + int vkp_effects_postprocessing(void) { vkp_effects_sync(); return effect_count(&g_cur) > 0; diff --git a/app/src/main/cpp/waylandcomp/src/effects_chain.h b/app/src/main/cpp/waylandcomp/src/effects_chain.h index 25f00225fc..bb1ca5ae1f 100644 --- a/app/src/main/cpp/waylandcomp/src/effects_chain.h +++ b/app/src/main/cpp/waylandcomp/src/effects_chain.h @@ -11,6 +11,7 @@ int vkp_effects_sync(void); int vkp_effects_active(void); int vkp_effects_upscaling(void); +int vkp_effects_sharpening(void); int vkp_effects_postprocessing(void); VkFilter vkp_effects_blit_filter(void); diff --git a/app/src/main/cpp/waylandcomp/src/vk_present.c b/app/src/main/cpp/waylandcomp/src/vk_present.c index 8c595d1711..53ddadaeb0 100644 --- a/app/src/main/cpp/waylandcomp/src/vk_present.c +++ b/app/src/main/cpp/waylandcomp/src/vk_present.c @@ -2179,7 +2179,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i VkImageLayout result_layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; if (fx) { int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f); - if (fg) { mapped_w = scene_w; mapped_h = scene_h; } + if (fg && !vkp_effects_sharpening()) { mapped_w = scene_w; mapped_h = scene_h; } vkp_effects_set_formats(scene_fmt, scene_fmt); result = vkp_effects_run(cmd, scene_img, input_w, input_h, mapped_w, mapped_h, &rw, &rh); effects_overlay_draws(cmd, result, rw, rh, scene_w, scene_h, diff --git a/app/src/main/java/com/droiddeck/launcher/App.kt b/app/src/main/java/com/droiddeck/launcher/App.kt index 3cedb3f171..1a45ab8512 100644 --- a/app/src/main/java/com/droiddeck/launcher/App.kt +++ b/app/src/main/java/com/droiddeck/launcher/App.kt @@ -43,15 +43,17 @@ class App : Application() { if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic" || process == "$packageName:shortcuts_sync" || process == "$packageName:bottom_desktop") return CrashHandler.install(this) + com.droiddeck.launcher.input.ShortcutsRelay.Holder.install(this) com.droiddeck.launcher.agent.AgentHost.refresh(this) - com.droiddeck.launcher.agent.AgentTab.load(this) com.droiddeck.launcher.ui.NavTabs.load(this) + com.droiddeck.launcher.ui.DeveloperTools.load(this) com.droiddeck.launcher.ui.AgentPet.install(this) if (com.droiddeck.launcher.agent.AgentTab.visible) com.droiddeck.launcher.lab.LabNotice.openOnInstall = "agent" com.droiddeck.launcher.lab.LabNotice.started(this) com.droiddeck.launcher.session.QuestExperimental.initialize(this) com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this) com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this) + com.droiddeck.launcher.session.SessionPrefs.settleStoresTabOrder(this, com.droiddeck.launcher.stores.Store.entries.map { it.id }) com.droiddeck.launcher.update.AppUpdates.init(this) com.droiddeck.launcher.update.UpdateWatch.sync(this, com.droiddeck.launcher.update.AppUpdates.follow(this, null)) com.droiddeck.launcher.core.DownloadSource.init(this) diff --git a/app/src/main/java/com/droiddeck/launcher/DriverMenus.kt b/app/src/main/java/com/droiddeck/launcher/DriverMenus.kt index 689279742f..925884b3c3 100644 --- a/app/src/main/java/com/droiddeck/launcher/DriverMenus.kt +++ b/app/src/main/java/com/droiddeck/launcher/DriverMenus.kt @@ -319,7 +319,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl refreshDrivers() return } - if (gpu.family.mali && DriverPairs.recommendedKey(gpu, emptyList()) == null && + if (gpu.family.mali && !DriverPairs.autoEligible(gpu) && com.droiddeck.launcher.gpu.VulkanInfo.cachedOrNull() == null) { releaseChecking = true autoStatus = activity.getString(R.string.drivers_checking_latest) @@ -335,14 +335,14 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl }, "gpu-name").start() return } - Log.i(TAG, "auto: ${gpu.name} (${gpu.family}) -> " + (DriverPairs.recommendedKey(gpu, emptyList()) ?: "no pair")) - if (gpu.family.mali && DriverPairs.recommendedKey(gpu, emptyList()) == null) { + Log.i(TAG, "auto: ${gpu.name} (${gpu.family}) eligible=${DriverPairs.autoEligible(gpu)}") + if (gpu.family.mali && !DriverPairs.autoEligible(gpu)) { // No PanVK build covers this Mali (e.g. the G1 series, arch v14): the phone's own driver. autoStatus = useMaliFallback(null) refreshDrivers() return } - if (DriverPairs.recommendedKey(gpu, emptyList()) == null) { + if (!DriverPairs.autoEligible(gpu)) { autoStatus = activity.getString(R.string.drivers_none_to_set, gpu.supportText(activity, com.droiddeck.launcher.core.DeviceSupport.vkBridge(activity)).lowercase()) return } @@ -372,7 +372,11 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl } gpu.family == GpuInfo.Family.POWERVR && (pair == null || !pair.complete) -> { // RADV is not published right now: the Xclipse falls back to the system route. - SessionPrefs.ensurePowerVrAutoDrivers(activity) + if (gpu.name.contains("Xclipse", ignoreCase = true) && DriverPairs.xclipseNeedsUpstream(gpu.name)) { + if (!SessionState.running) SessionPrefs.ensurePowerVrAutoDrivers(activity, powerVr = true, autoOwnedOnly = true) + } else { + SessionPrefs.ensurePowerVrAutoDrivers(activity) + } autoStatus = activity.getString(R.string.drivers_powervr_builtin) refreshDrivers() } diff --git a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt index bdb334a9e7..a8f165bc42 100644 --- a/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/FrontEndActivity.kt @@ -208,8 +208,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private var animationsEnabled by mutableStateOf(true) private var lowStorageWarning by mutableStateOf(true) private var launcherIcon by mutableStateOf(LauncherIcon.DARK) - private var gameStoresEnabled by mutableStateOf(true) - private var soundtracksEnabled by mutableStateOf(true) private var soundtracksIngame by mutableStateOf(false) private var soundtracks by mutableStateOf>(emptyList()) private var soundtracksLoaded by mutableStateOf(false) @@ -911,6 +909,16 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet private fun readGameIntent(request: Intent) { request.getStringExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV)?.let { navRequest = it; request.removeExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV) } + request.data?.takeIf { it.scheme == "droiddeck" && it.host == "settings" }?.let { uri -> + val section = uri.pathSegments.firstOrNull() + navRequest = if (section in setOf("storage", "sync", "downloads")) section + else "settings:" + (com.droiddeck.launcher.ui.SettingsSection.of(section) ?: com.droiddeck.launcher.ui.SettingsSection.OVERVIEW).key + request.data = null + gameLinkReading = false + pendingGameLink = null + syncDualPanel() + return + } if (navRequest == com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_APPS) { homeAppSelected = HomeApp.isHomeScreenEnabled(this) && HomeApp.isDefault(this) if (!homeAppSelected) navRequest = null @@ -927,7 +935,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet val soundtrackId = com.droiddeck.launcher.frontend.SoundtrackShortcuts.read(request) if (soundtrackId != null) { soundtrackLaunch = true - navRequest = if (SessionPrefs.soundtracksEnabled(this)) "sound:$soundtrackId" else "app:$soundtrackId" + navRequest = if ("soundtracks" !in com.droiddeck.launcher.ui.NavTabs.hidden) "sound:$soundtrackId" else "app:$soundtrackId" request.data = null request.action = Intent.ACTION_MAIN return @@ -955,13 +963,36 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } } - private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}): Boolean { + private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}, onSettled: () -> Unit = {}) { + val request = gameLaunchRequest.incrementAndGet() if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this) if (pkgStage != null) { onHandled() android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show() - return false + return } + val files = game.gameFiles + if (game.source != com.droiddeck.launcher.stores.Store.XBOX.id || files == null) { + if (startGame(game, returnHome, onHandled)) onSettled() + return + } + Thread({ + val refused = com.droiddeck.launcher.stores.xbox.XboxManifest.needsAppModel(files) + ui.post { + when { + request != gameLaunchRequest.get() || isFinishing || isDestroyed -> onHandled() + refused -> { + onHandled() + android.widget.Toast.makeText(this, getString(R.string.game_needs_app_model, game.name), android.widget.Toast.LENGTH_LONG).show() + onSettled() + } + startGame(game, returnHome, onHandled) -> onSettled() + } + } + }, "xbox-app-model").start() + } + + private fun startGame(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit): Boolean { if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled) onHandled() if (SessionState.running) { @@ -1176,19 +1207,19 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet if (!isDestroyed && lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) syncDualPanel() }, LINK_PANEL_MS) val game = games.firstOrNull { it.gameIdString == id } - if (game == null) { + val link = intent + fun consume() { + if (intent !== link || pendingGameLink != id) return pendingGameLink = null - intent.data = null - intent.action = Intent.ACTION_MAIN - intent.removeExtra(GameLaunchIntent.EXTRA_APP_ID) + link.data = null + link.action = Intent.ACTION_MAIN + link.removeExtra(GameLaunchIntent.EXTRA_APP_ID) + } + if (game == null) { + consume() syncDualPanel() android.widget.Toast.makeText(this, R.string.game_link_missing, android.widget.Toast.LENGTH_LONG).show() - } else if (launchGame(game, returnHome = true)) { - pendingGameLink = null - intent.data = null - intent.action = Intent.ACTION_MAIN - intent.removeExtra(GameLaunchIntent.EXTRA_APP_ID) - } + } else launchGame(game, returnHome = true, onSettled = ::consume) } private fun chooseGameShortcut(game: Library.SteamGame) { @@ -1235,8 +1266,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet lowStorageWarning = SessionPrefs.lowStorageWarning(this) LauncherIcon.repair(this, intent?.component) launcherIcon = LauncherIcon.current(this) - gameStoresEnabled = SessionPrefs.gameStoresEnabled(this) - soundtracksEnabled = SessionPrefs.soundtracksEnabled(this) soundtracksIngame = SessionPrefs.soundtracksIngame(this) gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this) storesShowMature = SessionPrefs.storesShowMature(this) @@ -1249,6 +1278,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet androidx.compose.runtime.LaunchedEffect(prootPack) { if (prootPack == com.droiddeck.launcher.core.AddonPack.State.Ready && installed == null) refresh() } + val appsTabShown = "android-apps" !in com.droiddeck.launcher.ui.NavTabs.hidden + androidx.compose.runtime.LaunchedEffect(appsTabShown) { if (appsTabShown && androidApps.isEmpty()) refreshAndroidApps() } DroidDeckTheme(theme, appScale = appScale) { com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize().exposeTestTags()) { if (decky.deckyPendingZip != null) com.droiddeck.launcher.ui.DeckyZipWarningDialog( @@ -1332,8 +1363,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet animationsEnabled = animationsEnabled, lowStorageWarning = lowStorageWarning, launcherIcon = launcherIcon, - gameStoresEnabled = gameStoresEnabled, - soundtracksEnabled = soundtracksEnabled, + soundtracksEnabled = "soundtracks" !in com.droiddeck.launcher.ui.NavTabs.hidden, soundtracksIngame = soundtracksIngame, soundtracks = soundtracks, soundtracksLoaded = soundtracksLoaded, @@ -1483,7 +1513,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet 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) } }, + onSaveImport = { sg -> importSaves(sg.name) { GameSaves.game(this@FrontEndActivity, sg) } }, onAddonImport = { sg, target -> importAddons(sg.name, target) }, onAddonDelete = { target, name -> saveAction(getString(R.string.main_addons_deleting, name)) { @@ -1491,8 +1521,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet getString(R.string.main_addons_deleted, name) } }, - onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(sg) } }, + onSaveExport = { sg, layout -> exportSaves(sg.name, layout) { GameSaves.game(this@FrontEndActivity, sg) } }, onPerformance = { refreshCores(); showComponents = false; showMapping = false; showPerformance = true }, + performancePanel = { PerformanceHost(embedded = true) }, onRoms = { showRoms = true }, onFiles = { startActivity(Intent(this, com.droiddeck.launcher.files.FileManagerActivity::class.java)) }, onBrowseFiles = { dir -> @@ -1608,8 +1639,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet offline = OfflineMode.enabled(this) }, onPageBack = { showPerformance = false; showComponents = false; showMapping = false }, - onGameStoresEnabled = { on -> SessionPrefs.setGameStoresEnabled(this, on); gameStoresEnabled = on }, - onSoundtracksEnabled = { on -> SessionPrefs.setSoundtracksEnabled(this, on); soundtracksEnabled = on }, onSoundtracksIngame = { on -> SessionPrefs.setSoundtracksIngame(this, on) soundtracksIngame = on @@ -1908,6 +1937,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) setIntent(intent) + gameLaunchRequest.incrementAndGet() if (intent.action == SteamIntegration.ACTION_SETUP) { gameLinkReading = false pendingGameLink = null @@ -2200,13 +2230,13 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } private fun refreshAndroidApps() { - if (!homeAppSelected) { + if (!homeAppSelected && "android-apps" in com.droiddeck.launcher.ui.NavTabs.hidden) { ++androidAppsListing androidApps = emptyList() return } val seq = ++androidAppsListing - HomePins.refresh(this) + if (homeAppSelected) HomePins.refresh(this) Thread({ val apps = runCatching { HomeApp.launchableApps(this) }.getOrDefault(emptyList()) ui.post { if (seq == androidAppsListing) androidApps = apps } @@ -2704,7 +2734,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet } @Composable - private fun PerformanceHost() { + private fun PerformanceHost(embedded: Boolean = false) { + if (embedded) androidx.compose.runtime.LaunchedEffect(Unit) { refreshCores() } PerformancePage( cores = CpuCores.all.map { c -> CoreRow(c, "cpu$c" + (CpuCores.maxGhz(c)?.let { String.format(java.util.Locale.US, " · %.1f GHz", it) } ?: "")) }, clientOverride = clientOverride, clientCores = clientCores, gameCores = gameCores, paceCores = paceCores, @@ -2750,6 +2781,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet SessionPrefs.setGameCpus(this, CpuCores.format(gameCores)) }, onDismiss = { showPerformance = false }, + embedded = embedded, ) } @@ -3093,6 +3125,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet installed = LinuxRuntimeInstaller.installedVersion(this) ready = LinuxRuntime.isInstalled(this) vkBridge = SessionPrefs.vkBridge(this) + venus = SessionPrefs.venus(this) + venusHostVulkan = com.droiddeck.launcher.session.VenusComponent.hostVulkanTooOld(this) vkBridgeSafe = SessionPrefs.vkBridgeSafe(this) bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this) removalPending = LinuxRuntimeInstaller.hasRemovalPending(this) @@ -3299,7 +3333,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet com.droiddeck.launcher.core.AppLanguage.setChosen(this, com.droiddeck.launcher.core.AppLanguage.SYSTEM) if (!ok) android.widget.Toast.makeText(this, R.string.setup_reset_settings_partial, android.widget.Toast.LENGTH_LONG).show() com.droiddeck.launcher.ui.Motion.refresh(this) - com.droiddeck.launcher.agent.AgentTab.load(this) + com.droiddeck.launcher.ui.DeveloperTools.load(this) com.droiddeck.launcher.ui.NavTabs.load(this) if (!switchLauncherIcon(LauncherIcon.DARK)) recreate() } diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index f8e0fb414b..52e9eeccee 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -191,6 +191,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var unfoldedPanel by mutableStateOf(null) private var unfoldedColumn: android.widget.LinearLayout? = null private var unfoldedDeckSurface: com.droiddeck.launcher.ui.InputSurfaceView? = null + private var swappedInputSurface: com.droiddeck.launcher.ui.InputSurfaceView? = null private var unfoldedDeckPanel by mutableStateOf(null) private var deckPanelLayouts: Map = emptyMap() private lateinit var sessionRoot: FrameLayout @@ -200,6 +201,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde @Volatile private var inputUsesLocalActions = false private var inputUsesPointer = false private var inputProfile = InputProfile.defaults(InputProfile.GAME) + private var stockInputProfile = InputProfile.defaults(InputProfile.GAME) private val inputMotion = InputMotion { inputRouter } private val heldKeys = HeldInput { code, down -> WaylandCompositor.nativeSendKey(code, if (down) 1 else 0) } private val heldButtons = HeldInput(::sendSceneButton) @@ -486,7 +488,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } drawerLayerOpen = false drawerPinned = false - if (value) drawerDocked = dockDrawer() && openDockedMenu() + if (value) { + releaseHeldKeys() + drawerDocked = dockDrawer() && openDockedMenu() + } drawerOpenState = value if (!value && drawerDocked) closeDockedMenu() } @@ -500,6 +505,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var drawerGameProfileId by mutableStateOf(null) private var drawerGameProfileSelectionMade = false private var fpsLimit by mutableStateOf(SessionState.fpsLimit) + private var cornerTap by mutableStateOf(false) + private fun fpsLimitKey(): String? = if (SessionState.running) SessionPrefs.fpsLimitKey(SessionState.mode, SessionState.gameId) + else SessionPrefs.fpsLimitKey(intent.getStringExtra(SessionService.EXTRA_MODE), intent.getStringExtra(SessionService.EXTRA_GAME_ID)) private var blackFrameInsertion by mutableStateOf(false) private fun noSteamSession(): Boolean = (SessionState.mode == SessionService.MODE_RUN && @@ -539,6 +547,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var lastMouseY = Float.NaN private var padType by mutableStateOf(SessionPrefs.CONTROLLER_DECK) private var pcKeyboardOpen by mutableStateOf(false) + private var fieldKeyboardOnPrimary = false + private var pendingFieldKeyboard = false + private var fieldKeyboardImeShown = false private var achievementsInFront by mutableStateOf(null) private var achievementsOpen by mutableStateOf(false) private var hudOn by mutableStateOf(true) @@ -656,11 +667,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun onDisplayAdded(displayId: Int) { notifyActivityDisplayStateChanged(displayId) refreshSecondScreenDisplays() + updateBottomGame() } override fun onDisplayRemoved(displayId: Int) { if (refreshActivityDisplayId() && started) { SessionService.setActivityDisplay(this@SessionActivity, sessionActivityDisplayId) } + updateBottomGame() refreshSecondScreenDisplays() } override fun onDisplayChanged(displayId: Int) { @@ -788,9 +801,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde com.droiddeck.launcher.gpu.SteamVrHealth.begin(this, SessionState.sessionId) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) if (!SessionState.running) { - SessionState.fpsLimit = 0 - fpsLimit = 0 + SessionState.fpsLimit = SessionPrefs.savedFpsLimit(this, fpsLimitKey()) } + fpsLimit = SessionState.fpsLimit + cornerTap = SessionPrefs.drawerCornerTap(this) applyOutputPacing() if (!SessionState.running) { SessionState.followScreen = followChoice() @@ -814,7 +828,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde pointerCaptureRefused = false if (usbMouse.active) updatePointerCapture() } else { - releaseHeldGuestInput() + releaseHeldInputOnCaptureLoss() uiHandler.postDelayed(::updatePointerCapture, 250) } } @@ -872,10 +886,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde root.addView(controls) } keyboard = KeyboardHost(this).also { host -> - host.onImeChanged = { updateDesktopKeyboardButton() } + host.onImeChanged = ::onPrimaryImeChanged root.addView(host) } - desktopKeyboardButton = com.droiddeck.launcher.input.DesktopKeyboardButton(this) { keyboard?.show() } + desktopKeyboardButton = com.droiddeck.launcher.input.DesktopKeyboardButton(this) { showPrimaryKeyboard() } .also { root.addView(it) } touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener) directTouchHold = DirectTouchHold(PointerGestures.slop(this), pointerListener, directTouchSink) @@ -893,6 +907,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde drawnRect()?.let { forwardTouch(event, it) } } override fun rightClick(x: Float, y: Float) { + if (!screenTapsClick) return pointerListener.onLongPress() pointerListener.onButton(PointerGestures.BTN_RIGHT, true, x, y) surfaceView.postDelayed({ pointerListener.onButton(PointerGestures.BTN_RIGHT, false, x, y) }, 50L) @@ -1090,6 +1105,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (AgentGuest.keyboardDismissals != keyboardDismissalsSeen[0]) { keyboardDismissalsSeen[0] = AgentGuest.keyboardDismissals secondScreenPresentation?.closeFieldKeyboard() + dismissFieldKeyboard() } } androidx.compose.runtime.LaunchedEffect(picturePosition, integerScaling, SessionState.running, pipUi, cardboard.enabled) { applyGameAlignment() } @@ -1130,6 +1146,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde drawerPage = com.droiddeck.launcher.ui.SessionDrawerPage.GLASSES drawerOpen = true } + if (!drawerOpen && !pcKeyboardOpen && !loading.visible) { + com.droiddeck.launcher.ui.DrawerEntryHint(SessionState.mode == SessionService.MODE_STEAM, backActionsInverted) { drawerOpen = true } + if (cornerTap) com.droiddeck.launcher.ui.DrawerCornerTap { drawerOpen = true } + } if (loading.visible) LoadingOverlay( loading.step, loading.percent, loading.elapsed, loading.hint, loading.ended, topic = loading.topic, readable = loading.readable, @@ -1312,7 +1332,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } if (pcKeyboardOpen) com.droiddeck.launcher.ui.PcKeyboard( sendKey = { code, down -> if (CompositorHost.isStarted) sendGuestKey(code, down, 32) }, - onAndroidKeyboard = { pcKeyboardOpen = false; keyboard?.toggle() }, + onAndroidKeyboard = { pcKeyboardOpen = false; togglePrimaryKeyboard() }, onClose = { pcKeyboardOpen = false }, ) if (!drawerDocked) SessionMenu( @@ -1436,6 +1456,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde secondScreenNone = !bottomOutputActive && !dockDrawer(), gameOnBottom = bottomOutputActive, gameSwapAvailable = bottomSwapAvailable, + gameSwapBuiltIn = !::displayManager.isInitialized || displayManager.getDisplay(selectedSecondScreenDisplay) + ?.let(com.droiddeck.launcher.input.DualScreen::builtIn) ?: true, onGameOnBottom = { on -> drawerOpen = false; putGameOnBottom(on) }, dashboardAvailable = bottomPages().isNotEmpty(), desktopAvailable = com.droiddeck.launcher.session.BottomDesktop.available(), @@ -1598,8 +1620,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde onFpsLimit = { fps -> SessionState.fpsLimit = fps fpsLimit = fps + SessionPrefs.saveFpsLimit(this@SessionActivity, fpsLimitKey(), fps) applyOutputPacing() }, + cornerTap = cornerTap, + onCornerTap = { on -> SessionPrefs.setDrawerCornerTap(this@SessionActivity, on); cornerTap = on }, blackFrameInsertion = blackFrameInsertion, blackFrameInsertionAvailable = blackFrameInsertion || blackFrameInsertionAvailable(), onBlackFrameInsertion = { on -> @@ -1629,7 +1654,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde pickLossless.launch(InAppFilePicker.buildIntent( this@SessionActivity, listOf("dll"), getString(R.string.lsfg_pick_title))) }, - onKeyboard = { drawerOpen = false; pcKeyboardOpen = false; keyboard?.toggle() }, + onKeyboard = { drawerOpen = false; pcKeyboardOpen = false; togglePrimaryKeyboard() }, onHardwareKeyboard = ::togglePcKeyboard, wowChatShown = com.droiddeck.launcher.ui.WowChat.isWow(AgentGuest.gameProgram), wowChat = wowChat.remembered, @@ -1860,7 +1885,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val all = com.droiddeck.launcher.input.VrControllers.Emulate.entries com.droiddeck.launcher.input.VrControllers.setEmulate(this, all[(pads.emulate.ordinal + 1) % all.size]) }) else null, - onKeyboard = { keyboard?.toggle() }, + onKeyboard = { togglePrimaryKeyboard() }, onSessionMenu = { drawerOpen = true }, onStopSteamVr = if (vr) ({ steamVrAction("stop") }) else null, brightness = glasses.brightness, @@ -1901,12 +1926,44 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun togglePcKeyboard() { drawerOpen = false - keyboard?.hide() + hidePrimaryKeyboard() onScreenControls?.releaseAll() bottomInputControls?.releaseAll() pcKeyboardOpen = !pcKeyboardOpen } + private fun showPrimaryKeyboard() { + pendingFieldKeyboard = false + fieldKeyboardOnPrimary = false + keyboard?.show() + } + + private fun togglePrimaryKeyboard() { + pendingFieldKeyboard = false + fieldKeyboardOnPrimary = false + keyboard?.toggle() + } + + private fun hidePrimaryKeyboard() { + pendingFieldKeyboard = false + fieldKeyboardOnPrimary = false + keyboard?.hide() + } + + private fun onPrimaryImeChanged(visible: Boolean) { + if (visible) fieldKeyboardImeShown = true + else if (fieldKeyboardImeShown) { + fieldKeyboardImeShown = false + fieldKeyboardOnPrimary = false + } + updateDesktopKeyboardButton() + } + + private fun dismissFieldKeyboard() { + pendingFieldKeyboard = false + if (fieldKeyboardOnPrimary) hidePrimaryKeyboard() + } + private fun updateControllerPrefs(change: () -> Unit) { change() controllerSettings = ControllerPrefs.read(this) @@ -2691,7 +2748,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val waylandLog = File(SessionPaths.beginOrCurrent(this), "wayland.log") WaylandCompositor.setSessionLogFile(waylandLog) try { - android.system.Os.setenv("BL_WAYLAND_LOG", waylandLog.path, true) + android.system.Os.setenv("DD_WAYLAND_LOG", waylandLog.path, true) } catch (e: Exception) { Log.w(TAG, "could not point the compositor's log at $waylandLog", e) } @@ -3139,6 +3196,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun onSessionEnded(status: Int) { ended = true + uiHandler.removeCallbacks(guardWhenRunning) + com.droiddeck.launcher.session.KeepTopActivity.release() ++steamVrRequestGeneration if (isInPictureInPictureMode) { runOnUiThread { finish() } @@ -3245,8 +3304,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } } - private fun prootFailureHint(): EndHint? { - if (SessionState.failureCode != "PROOT_MISSING") return null + private fun startFailureHint(): EndHint? { + val code = SessionState.failureCode ?: return null + if (code == "GUEST_EXIT") return null val message = SessionState.failureMessage ?: return null return EndHint(message) } @@ -3256,7 +3316,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun sessionExitHint(status: Int): EndHint? = if (status == 0) presentationFaultHint() - else runtimeDamageHint() ?: sessionEndHint(SessionState.logFile) ?: prootFailureHint() + else runtimeDamageHint() ?: sessionEndHint(SessionState.logFile) ?: startFailureHint() private fun sessionEndHint(log: File?): EndHint? { presentationFaultHint()?.let { return it } @@ -3657,7 +3717,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val target = com.droiddeck.launcher.input.DualScreen.sessionDisplay(this, displayManager, shownOnDisplayId) ?: return false return try { val presentation = secondScreenPresentation ?: secondScreenPresentation(target).also { - selectedSecondScreenDisplay = target.displayId secondScreenPresentation = it } if (!presentation.isShowing) presentation.show() @@ -4016,16 +4075,23 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val candidates = SecondScreenDisplays.available(displayManager, primaryId) .filter { glassesScreen == null || it.id != glasses.displayId } val oldIds = secondScreenDisplays.map { it.id }.toSet() + val oldSelectedDisplay = selectedSecondScreenDisplay secondScreenDisplays = candidates reconcileDock(primaryId) - bottomSwapAvailable = bottomGame != null || bottomGameDisplay() != null val newIds = candidates.map { it.id }.toSet() if (secondScreenMode != SecondScreenMode.NONE && oldIds.isNotEmpty() && selectedSecondScreenDisplay !in newIds) { + bottomSwapAvailable = bottomGame != null closeSecondScreen(reset = true) SessionState.secondScreenAutoOpened = false return } - if (selectedSecondScreenDisplay !in newIds) selectedSecondScreenDisplay = candidates.firstOrNull()?.id ?: -1 + selectedSecondScreenDisplay = SecondScreenDisplays.selection(selectedSecondScreenDisplay, candidates.map { it.id }, gameOnBottom) { + SessionState.secondScreenDisplay = it + } + if (selectedSecondScreenDisplay != oldSelectedDisplay) { + updateBottomGame() + } + bottomSwapAvailable = bottomGame != null || bottomGameDisplay() != null if (secondScreenMode != SecondScreenMode.NONE && candidates.isEmpty()) { closeSecondScreen(reset = true) SessionState.secondScreenAutoOpened = false @@ -4047,12 +4113,22 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun openDualScreenControls() { if (SessionState.secondScreenAutoOpened || secondScreenMode != SecondScreenMode.NONE || pipUi) return + if (gameOnBottom && selectedSecondScreenDisplay >= 0 && secondScreenDisplays.none { it.id == selectedSecondScreenDisplay }) return if (!SessionPrefs.dualScreenSessionControls(this)) return val target = com.droiddeck.launcher.input.DualScreen.sessionDisplay(this, displayManager, shownOnDisplayId) ?: return if (secondScreenDisplays.none { it.id == target.displayId }) return + val gameDisplay = bottomGame?.display?.displayId + ?: if (SessionState.gameOnBottom) bottomGameDisplay()?.displayId else null SessionState.secondScreenAutoOpened = true - selectedSecondScreenDisplay = target.displayId - selectSecondScreenMode(openingPanel()) + if (gameDisplay != null && gameDisplay != target.displayId && secondScreenDisplays.any { it.id == gameDisplay }) { + panelMode(openingPanel()) + } else { + val selectionChanged = selectedSecondScreenDisplay != target.displayId + selectedSecondScreenDisplay = target.displayId + SessionState.secondScreenDisplay = target.displayId + if (selectionChanged) updateBottomGame() + selectSecondScreenMode(openingPanel()) + } automaticPanel = secondScreenMode != SecondScreenMode.NONE dualControlsProvisional = ::loading.isInitialized && loading.visible } @@ -4078,6 +4154,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (secondScreenDisplays.none { it.id == displayId }) return selectedSecondScreenDisplay = displayId SessionState.secondScreenDisplay = displayId + updateBottomGame() if (secondScreenMode != SecondScreenMode.NONE) showSecondScreen(secondScreenMode) } @@ -4096,6 +4173,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde return } if (selectedSecondScreenDisplay !in secondScreenDisplays.map { it.id }) { + if (gameOnBottom && selectedSecondScreenDisplay >= 0) { + panelMode(mode) + return + } selectedSecondScreenDisplay = secondScreenDisplays.first().id } showSecondScreen(mode) @@ -4174,7 +4255,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde ) } }, - onSwap = if (bottomSwapAvailable && com.droiddeck.launcher.input.DualScreen.builtIn(target)) ({ putGameOnBottom(true) }) else null, + onSwap = if (bottomSwapAvailable) ({ putGameOnBottom(true) }) else null, onDeckPanel = ::selectDeckPanel, dashboard = if (bottomPages().isEmpty()) null else ({ DroidDeckTheme { @@ -4278,6 +4359,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde val library = com.droiddeck.launcher.input.InputLibraries.read(this) val desktop = loadingMode() == SessionService.MODE_DESKTOP inputProfile = library.compileActive(desktop, secondScreenMode.panel(this)) + stockInputProfile = library.compileStock(desktop, secondScreenMode.panel(this)) primaryInputLayout = library.activeLayout(desktop, InputRole.PRIMARY) adaptiveSticks = primaryInputLayout?.adaptiveSticks quickButtons = primaryInputLayout?.takeIf { it.editable }?.let { l -> l.quickButtons.associateWith { it !in l.style.hidden } }.orEmpty() @@ -4417,6 +4499,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (!started) return null if (secondScreenPresentation?.showsKeyboard != true && dockDrawer()) { val target = com.droiddeck.launcher.input.DualScreen.sessionDisplay(this, displayManager, shownOnDisplayId) ?: return null + if (gameOnBottom && selectedSecondScreenDisplay != target.displayId) return null if (drawerOpen || drawerPinned) drawerOpen = false typingReturnMode = secondScreenMode selectedSecondScreenDisplay = target.displayId @@ -4426,16 +4509,37 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun openBottomKeyboard() { - val presentation = bottomKeyboardPresentation() ?: return + val presentation = bottomKeyboardPresentation() + if (presentation == null) { + if (keyboardBelongsOnPrimary()) { + pendingFieldKeyboard = true + retryFieldKeyboard(hasWindowFocus()) + } + return + } + pendingFieldKeyboard = false + if (fieldKeyboardOnPrimary) hidePrimaryKeyboard() presentation.requestKeyboard(forField = true) com.droiddeck.launcher.ui.SessionTyping.focusDisplay(this, presentation.display.displayId) } + private fun keyboardBelongsOnPrimary() = SecondScreenDisplays.keyboardOnPrimary(gameOnBottom, selectedSecondScreenDisplay, + secondScreenDisplays.map { it.id }, taken = com.droiddeck.launcher.input.DualScreen::taken) + + private fun retryFieldKeyboard(hasFocus: Boolean) { + if (!pendingFieldKeyboard || !hasFocus || !resumed || pipUi) return + pendingFieldKeyboard = false + if (!keyboardBelongsOnPrimary()) return + fieldKeyboardOnPrimary = true + fieldKeyboardImeShown = keyboard?.hideMeansDismissal == true + keyboard?.show() + } + private fun onGameTextField(focused: Boolean) { if (!focused || !com.droiddeck.launcher.ui.WowChat.isWow(AgentGuest.gameProgram)) wowChat.chatClosed() else if (resumed && !pipUi && !pcKeyboardOpen && resources.configuration.hardKeyboardHidden != android.content.res.Configuration.HARDKEYBOARDHIDDEN_NO) { - keyboard?.takeIf { it.shown }?.hide() + hidePrimaryKeyboard() wowChat.chatOpened() } } @@ -4522,9 +4626,13 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun updateKeyboardRoute() { - AgentGuest.routeKeyboard(this, SessionState.mode == SessionService.MODE_STEAM && - (secondScreenPresentation?.showsKeyboard == true || dockDrawer()) && - SessionPrefs.androidTextFieldKeyboard(this)) + AgentGuest.routeKeyboard(this, SecondScreenDisplays.routeKeyboard( + SessionState.mode == SessionService.MODE_STEAM, + SessionPrefs.androidTextFieldKeyboard(this), + secondScreenPresentation?.showsKeyboard == true, + dockDrawer(), + SecondScreenDisplays.keyboardOnPrimary(gameOnBottom, selectedSecondScreenDisplay, + secondScreenDisplays.map { it.id }, resumed && !pipUi, com.droiddeck.launcher.input.DualScreen::taken))) } private fun dropDockedDrawer() { @@ -4735,6 +4843,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private var lockedSwipeY = 0f private var dismissTouch = false private var sessionTouchDown = false + private var screenTapsClick = true + + private fun onScreenMouseButtonShown(): Boolean = listOfNotNull( + onScreenControls?.inputSurface, bottomInputControls?.inputSurface, unfoldedPanel?.inputSurface, unfoldedDeckSurface, + secondScreenPresentation?.controlsView, swappedInputSurface, + ).any { it.isShown && inputProfile.showsMouseButton(it.inputRole, it.shownElements, stockInputProfile) } override fun onTouchEvent(event: MotionEvent): Boolean { val pen = PenStream.penIndex(event) @@ -4767,6 +4881,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } val snapshot = fingerTouchSnapshot(uiBlocking) val route = com.droiddeck.launcher.input.TouchRouter.decide(snapshot) + if (event.actionMasked == MotionEvent.ACTION_DOWN) { + screenTapsClick = !onScreenMouseButtonShown() + if (::touchpad.isInitialized) touchpad.clicks = screenTapsClick + if (::scrollTouch.isInitialized) scrollTouch.clicks = screenTapsClick + } if (route != touchRoute) { Log.i(TAG, "touch route $touchRoute -> $route (mode=$routedTouchMode steamUi=${SessionState.steamUi} scrollLayer=$scrollTouchGesture)") touchRoute = route @@ -4916,6 +5035,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL) ignoreGameTouch = false return true } + // With an on-screen mouse button the press comes from the button, so the pointer has to be there before + // the two-finger gesture buffer holds the touch-down. + if (SessionState.mode == SessionService.MODE_DESKTOP && !screenTapsClick && !pointerLocked && + event.actionMasked == MotionEvent.ACTION_DOWN) movePointer(event.x, event.y) if (SessionState.mode == SessionService.MODE_DESKTOP && twoFingerGestures.onTouch(event)) return true return forwardTouch(event, rect) } @@ -4950,7 +5073,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } } } - directTouchHold.onTouch(event) + if (screenTapsClick) directTouchHold.onTouch(event) + else if (!pointerLocked && (event.actionMasked == MotionEvent.ACTION_DOWN || event.actionMasked == MotionEvent.ACTION_MOVE)) + movePointer(event.x, event.y) return true } @@ -4997,10 +5122,14 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun relativeMouseAttached(): Boolean = !isInMultiWindowMode && !glassesOutputActive && mouseAttached() + private fun sessionOwnsInput() = + resumed && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !inputSettingsOpen && + !pipUi && !bottomOutputActive && !touchEditorOpen && !wowChatOnTop + private fun updatePointerCapture() { if (!::surfaceView.isInitialized) return val view = window.decorView - val want = (pointerLocked || relativeMouseAttached()) && resumed && hasWindowFocus() && !drawerOpen && !pcKeyboardOpen && !achievementsOpen && !inputSettingsOpen && !pipUi && !bottomOutputActive && !touchEditorOpen && !wowChatOnTop && mouseAttached() + val want = (pointerLocked || relativeMouseAttached()) && sessionOwnsInput() && hasWindowFocus() && mouseAttached() releaseDesktopMouseGrab() updateUsbMouse(want) if (want == view.hasPointerCapture()) return @@ -5323,14 +5452,26 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun keyboardCoversPad() = SessionState.mode == SessionService.MODE_STEAM && AgentGuest.steamKeyboard - private fun releaseHeldGuestInput() { + private fun releaseHeldInputOnCaptureLoss() { + if (sessionOwnsInput()) releaseHeldPointerInput() else releaseHeldGuestInput() + } + + private fun releaseHeldPointerInput() { mouseBackInput.cancel() cancelPen(releaseKey = true) heldButtons.release(1 or 2 or 8 or 16) + } + + private fun releaseHeldKeys() { guestKeysDown.toList().forEach { sendGuestKey(it, false) } heldKeys.release(8 or 16 or 32) } + private fun releaseHeldGuestInput() { + releaseHeldPointerInput() + releaseHeldKeys() + } + private fun sendGuestKey(key: Int, down: Boolean, owner: Int = 1) { if (down && pipUi) return val code = if (key == KEY_RIGHTCTRL && SessionState.mode == SessionService.MODE_DESKTOP) KEY_LEFTCTRL else key @@ -5406,6 +5547,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde private fun showPipUi(show: Boolean) { pipUi = show + updateKeyboardRoute() + if (!show) retryFieldKeyboard(hasWindowFocus()) if (show) { if (::hud.isInitialized) hud.setHidden(true) drawerOpen = false @@ -5425,7 +5568,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde guestKeysDown.toList().forEach { sendGuestKey(it, false) } heldKeys.clear() heldButtons.clear() - keyboard?.hide() + hidePrimaryKeyboard() sessionClipboard.stop() padMotion?.stop() cursorVisible = false @@ -5466,7 +5609,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) { - if (::pip.isInitialized && (requestCode >= 0 || intent.component?.packageName == packageName || + if (::pip.isInitialized && intent.component?.className != com.droiddeck.launcher.session.KeepTopActivity::class.java.name && + (requestCode >= 0 || intent.component?.packageName == packageName || intent.action in setOf(Intent.ACTION_CHOOSER, Intent.ACTION_SEND, Intent.ACTION_OPEN_DOCUMENT, Intent.ACTION_GET_CONTENT, "android.settings.PICTURE_IN_PICTURE_SETTINGS"))) pip.background() super.startActivityForResult(intent, requestCode, options) @@ -5498,6 +5642,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } override fun onStop() { + if (lightPause.stopped()) departureCleanup() if (runtimeRemovalBlocked) { super.onStop(); return } started = false if (::hud.isInitialized) hud.setBackgrounded(true) @@ -5541,6 +5686,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde override fun onResume() { super.onResume() + uiHandler.removeCallbacks(lightPauseCheck) + when (lightPause.resumed(com.droiddeck.launcher.session.KeepTopActivity.bounces)) { + com.droiddeck.launcher.session.LightPause.Resume.LIGHT -> return + com.droiddeck.launcher.session.LightPause.Resume.CLEANUP_FIRST -> departureCleanup() + com.droiddeck.launcher.session.LightPause.Resume.NORMAL -> Unit + } drawerGameInventoryRevision++ com.droiddeck.launcher.input.SystemKeyCapture.attach(this, { hasWindowFocus() && !appUiOwnsPointer() && CompositorHost.isStarted }) { event -> com.droiddeck.launcher.input.GuestKeys.send(event) { code, down -> sendGuestKey(code, down, 8) } @@ -5568,6 +5719,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde onScreenControls?.reload() controllerSettings = ControllerPrefs.read(this) resumed = true + updateKeyboardRoute() + retryFieldKeyboard(hasWindowFocus()) updateDesktopKeyboardButton() com.droiddeck.launcher.input.HomeButtonShortcuts.attach(this, enabled = { @@ -5604,10 +5757,63 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde SessionPrefs.sessionPrefs(this).registerOnSharedPreferenceChangeListener(cardboardPrefListener) } + private var memoryPressureAt = 0L + private var focusBounce = false + private val lightPause = com.droiddeck.launcher.session.LightPause() + private val lightPauseCheck = Runnable { if (lightPause.timedOut()) departureCleanup() } + private var topResumed = false + private val guardWhenRunning = object : Runnable { + override fun run() { + if (!topResumed || isFinishing) return + if (SessionState.running) guardOtherDisplays() else uiHandler.postDelayed(this, 2_000) + } + } + + // RUNNING_LOW and RUNNING_CRITICAL are not delivered from API 34, so the guard also goes up + // as soon as a running session is on top. + override fun onTrimMemory(level: Int) { + super.onTrimMemory(level) + if (!com.droiddeck.launcher.session.TopUnderPressure.isPressure(level)) return + memoryPressureAt = android.os.SystemClock.elapsedRealtime() + guardOtherDisplays() + } + + override fun onTopResumedActivityChanged(isTopResumedActivity: Boolean) { + super.onTopResumedActivityChanged(isTopResumedActivity) + topResumed = isTopResumedActivity + uiHandler.removeCallbacks(guardWhenRunning) + if (isTopResumedActivity) uiHandler.post(guardWhenRunning) + else if (com.droiddeck.launcher.session.TopUnderPressure.shouldReclaim( + android.os.SystemClock.elapsedRealtime(), memoryPressureAt, SessionState.running, isFinishing)) guardOtherDisplays() + } + + private fun guardOtherDisplays() { + if (!SessionState.running || isFinishing) return + val wasResumed = lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED) + val bounced = com.droiddeck.launcher.session.KeepTopActivity.guardOtherDisplays(this, display?.displayId ?: android.view.Display.DEFAULT_DISPLAY) + if (com.droiddeck.launcher.session.KeepTopActivity.hasPendingStarts()) { + uiHandler.removeCallbacks(guardWhenRunning) + uiHandler.postDelayed(guardWhenRunning, com.droiddeck.launcher.session.KeepTopActivity.RETRY_MS) + } + if (!bounced) return + if (!wasResumed) return + focusBounce = true + uiHandler.postDelayed({ focusBounce = false }, 500) + } + override fun onPause() { + if (focusBounce) { + focusBounce = false + lightPause.paused(com.droiddeck.launcher.session.KeepTopActivity.bounces) + uiHandler.postDelayed(lightPauseCheck, 200) + } else departureCleanup() + super.onPause() + } + + private fun departureCleanup() { com.droiddeck.launcher.input.SystemKeyCapture.detach(this) com.droiddeck.launcher.input.HomeButtonShortcuts.detach(this) - if (runtimeRemovalBlocked) { super.onPause(); return } + if (runtimeRemovalBlocked) return physicalShortcuts.clear() backQamInput.cancel() mouseBackInput.cancel() @@ -5641,14 +5847,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde if (::scrollTouch.isInitialized) scrollTouch.cancel() if (::padMouse.isInitialized) padMouse.reset() resumed = false + updateKeyboardRoute() updatePointerCapture() updatePadMotion() - keyboard?.takeIf { it.shown }?.hide() + val pendingKeyboard = pendingFieldKeyboard + hidePrimaryKeyboard() + pendingFieldKeyboard = pendingKeyboard SessionPrefs.sessionPrefs(this).unregisterOnSharedPreferenceChangeListener(cardboardPrefListener) SessionPrefs.sessionPrefs(this).unregisterOnSharedPreferenceChangeListener(screenEffectsProfilePrefListener) ControllerPrefs.prefs(this).unregisterOnSharedPreferenceChangeListener(shortcutPrefListener) updateHeadTracker() - super.onPause() } private fun steamVrAction(action: String) { @@ -5889,9 +6097,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } private fun bottomGameDisplay(): Display? { - if (!::displayManager.isInitialized) return null - return com.droiddeck.launcher.input.DualScreen.sessionDisplay(this, displayManager, shownOnDisplayId) - ?.takeIf { it.isValid && com.droiddeck.launcher.input.DualScreen.builtIn(it) } + if (!::displayManager.isInitialized || SessionPrefs.dualScreenSessionMode(this) == com.droiddeck.launcher.input.DualScreen.MODE_OFF) return null + return com.droiddeck.launcher.input.DualScreen.selectedSessionDisplay( + this, displayManager, shownOnDisplayId, selectedSecondScreenDisplay, + ) } private fun putGameOnBottom(on: Boolean) { @@ -6017,7 +6226,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde tabs = tabs, ) val keyboardExtra = com.droiddeck.launcher.ui.BarExtra(getString(R.string.second_show_keyboard), icon = R.drawable.ic_bottom_keyboard) { - keyboard?.toggle() + togglePrimaryKeyboard() } val profileLayout = secondaryInputLayout androidx.compose.foundation.layout.Box( @@ -6045,8 +6254,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde androidx.compose.runtime.key(profileLayout) { androidx.compose.ui.viewinterop.AndroidView( factory = { context -> com.droiddeck.launcher.ui.InputSurfaceView(context, padBridge, profileLayout?.elements.orEmpty(), - surfaceStyle = profileLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()) }, + surfaceStyle = profileLayout?.style ?: com.droiddeck.launcher.input.InputSurfaceStyle()).also { swappedInputSurface = it } }, modifier = Modifier.fillMaxWidth().weight(1f), + onRelease = { if (swappedInputSurface === it) swappedInputSurface = null }, ) } } @@ -6213,6 +6423,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde releaseHeldGuestInput() } if (hasFocus && !pipUi) { + retryFieldKeyboard(true) goFullscreen() refreshClipboard() } @@ -6257,6 +6468,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde } override fun onDestroy() { + uiHandler.removeCallbacks(guardWhenRunning) + com.droiddeck.launcher.session.KeepTopActivity.release() synchronized(frameGenGlobalLock) { frameGenActivityActive = false frameGenRequests.incrementAndGet() diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentEnv.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentEnv.kt index 05d5d4e77b..b1b4406520 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentEnv.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentEnv.kt @@ -58,7 +58,8 @@ object AgentEnv { fun override(context: Context, name: String): JSONObject = synchronized(lock) { AgentAccess.requireCommands(context) if (NAME.matchEntire(name) == null || name in setOf(".", "..")) throw AgentException("INVALID_NAME", "Override names are letters, digits, '.', '_' and '-'") - if (name == "libblfastpath.so" && (SessionState.running || SessionState.guestPid > 0 || SessionState.phase == SessionPhase.STOPPING)) { + if (name == LEGACY_FAST_PATH) throw AgentException("INVALID_NAME", "The fast-path library is now $FAST_PATH") + if (name == "libddfastpath.so" && (SessionState.running || SessionState.guestPid > 0 || SessionState.phase == SessionPhase.STOPPING)) { throw AgentException("SESSION_ACTIVE", "Stop the session before installing a fast-path library") } val source = File(inbox(context), name) @@ -73,7 +74,7 @@ object AgentEnv { staged.delete() throw AgentException("OVERRIDE_FAILED", "Could not stage the override") } - if (name == "libblfastpath.so" && !arm64SharedLibrary(staged)) { + if (name == "libddfastpath.so" && !arm64SharedLibrary(staged)) { staged.delete() throw AgentException("INVALID_LIBRARY", "The fast path must be a 64-bit little-endian ARM64 ELF shared library") } @@ -86,7 +87,7 @@ object AgentEnv { state.put("pendingOverrides", JSONArray(merge(strings(state.optJSONArray("pendingOverrides")), listOf(name)))) save(context, state) state.put("installed", "$GUEST_BIN/$name") - if (name == "libblfastpath.so") { + if (name == "libddfastpath.so") { val digest = MessageDigest.getInstance("SHA-256") target.inputStream().use { input -> val buffer = ByteArray(65536) @@ -103,10 +104,10 @@ object AgentEnv { fun fastPathLibrary(context: Context): String = synchronized(lock) { if (!AgentAccess.commandsAllowed(context)) return@synchronized ProotFastPath.LIBRARY - if ("libblfastpath.so" !in strings(load(context).optJSONArray("activeOverrides"))) return@synchronized ProotFastPath.LIBRARY - val file = File(bin(context), "libblfastpath.so") + if ("libddfastpath.so" !in strings(load(context).optJSONArray("activeOverrides"))) return@synchronized ProotFastPath.LIBRARY + val file = File(bin(context), "libddfastpath.so") if (!file.isFile || Files.isSymbolicLink(file.toPath())) return@synchronized ProotFastPath.LIBRARY - "$GUEST_BIN/libblfastpath.so" + "$GUEST_BIN/libddfastpath.so" } private fun arm64SharedLibrary(file: File): Boolean = file.inputStream().use { input -> @@ -129,13 +130,18 @@ object AgentEnv { } val state = load(context) val active = strings(state.optJSONArray("pending")) - val overrides = strings(state.optJSONArray("pendingOverrides")) + val queued = strings(state.optJSONArray("pendingOverrides")) + val legacy = File(bin(context), LEGACY_FAST_PATH) + val stranded = FAST_PATH in queued && legacy.isFile && !File(bin(context), FAST_PATH).exists() && + !legacy.renameTo(File(bin(context), FAST_PATH)) + if (stranded) Log.w(TAG, "could not rename the queued $LEGACY_FAST_PATH; it stays queued for the next session") + val overrides = if (stranded) queued - FAST_PATH else queued bin(context).listFiles() - ?.filter { it.name !in overrides }?.forEach { it.delete() } + ?.filter { it.name !in overrides && !(stranded && it.name == LEGACY_FAST_PATH) }?.forEach { it.delete() } val lines = strings(state.optJSONArray("persistent")) + active - val withPath = if (overrides.none { it != "libblfastpath.so" }) lines else lines + "PATH=$GUEST_BIN:${pathOf(lines)}" + val withPath = if (overrides.none { it != "libddfastpath.so" }) lines else lines + "PATH=$GUEST_BIN:${pathOf(lines)}" state.put("active", JSONArray(active)).put("pending", JSONArray()) - state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray()) + state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray(if (stranded) listOf(FAST_PATH) else emptyList())) save(context, state) if (withPath.isNotEmpty()) Log.i(TAG, "agent environment keys for this session: ${withPath.map { it.substringBefore('=') }}") withPath @@ -158,6 +164,9 @@ object AgentEnv { save(context, state) } + private const val FAST_PATH = "libddfastpath.so" + private const val LEGACY_FAST_PATH = "libblfastpath.so" + private fun pathOf(lines: List) = lines.lastOrNull { it.startsWith("PATH=") }?.substringAfter('=')?.takeIf { it.isNotBlank() } ?: LinuxRuntime.GUEST_PATH @@ -186,6 +195,9 @@ object AgentEnv { for (key in listOf("pending", "active", "persistent", "pendingOverrides", "activeOverrides")) { if (!state.has(key)) state.put(key, JSONArray()) } + for (key in listOf("pendingOverrides", "activeOverrides")) { + state.put(key, JSONArray(strings(state.optJSONArray(key)).map { if (it == LEGACY_FAST_PATH) FAST_PATH else it }.distinct())) + } return state } diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentHarness.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentHarness.kt index 669a1c5503..9ae46f143c 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentHarness.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentHarness.kt @@ -1,11 +1,13 @@ package com.droiddeck.launcher.agent +import androidx.annotation.StringRes import androidx.annotation.VisibleForTesting +import com.droiddeck.launcher.R import org.json.JSONArray import org.json.JSONObject import java.io.File -/** One coding agent CLI in the Linux userland, run one process per turn (or kept open, see [input]). */ +/** One coding agent CLI in the Linux userland, run as a process that takes its turns over stdin (see [AgentProtocol]). */ interface AgentHarness { val id: String val name: String @@ -20,32 +22,35 @@ interface AgentHarness { /** A guest command that signs in through $BROWSER. */ val signIn: List /** - * Where the user makes an API key, for a CLI whose own sign-in is a terminal prompt: [signIn] - * then only opens this page, and the key is pasted into DroidDeck and saved by [saveKey]. + * APIs the CLI reaches with a key pasted into DroidDeck, for a CLI whose own sign-in is a terminal + * prompt; empty when it signs in through [signIn]. */ - val keyPage: String? get() = null - /** Whether a key from [keyPage] is saved under [rootfs]. */ - fun hasKey(rootfs: File): Boolean = false - fun saveKey(rootfs: File, key: String) {} + val providers: List get() = emptyList() + /** Ids of the [providers] with a key saved under [rootfs]. */ + fun keys(rootfs: File): Set = emptySet() + /** + * Saves [key] for [provider]. A [Provider.custom] one also takes the [endpoint] it is served from, and + * [get] fetches a URL from the userland, with the key as a bearer token when it is not null. + */ + fun saveKey(rootfs: File, provider: Provider, key: String, endpoint: String? = null, get: (String, String?) -> String = { url, _ -> error("Cannot reach $url") }) {} + fun removeKey(rootfs: File, provider: Provider) {} /** Whether the CLI has models that need no account; [useFree] then counts as signed in. */ val free: Boolean get() = false fun useFree(rootfs: File) {} + /** Usage reports the conversation's whole cost rather than the turn's. */ + val sessionCost: Boolean get() = false /** Whether [Options.plan] means anything to this CLI. */ val plans: Boolean /** Reasoning effort levels the CLI accepts, lowest first; empty when it has none. */ val efforts: List /** Models to offer besides the CLI's default; [rootfs] is where the CLI's own files can be read. */ fun models(rootfs: File): List - /** The guest command for one turn; [conversation] is null for the first one. */ + /** How the CLI may run its tools, the one that asks before each action first and the default. */ + val permissions: List + /** The guest command of the process that runs the conversation's turns; [conversation] is null for a new one. */ fun turn(message: String, conversation: String?, options: Options): List - /** - * The line that hands [message] to a [turn] process over stdin, or null when the message is already in the - * command. A process that takes its messages this way stays open between turns, so work it started in the - * background can wake it, as it does in the CLI's own terminal. - */ - fun input(message: String): String? = null - /** One line of the CLI's output, or null when it carries nothing to show. */ - fun parse(line: String): AgentEvent? + /** A new reader for one [turn] process; it keeps what that process has said so far. */ + fun protocol(): AgentProtocol /** The folder, under the userland's root, where the CLI loads user skills (`/SKILL.md`). */ val skills: String /** The CLI's global instructions file under the userland's root, where DroidDeck keeps its rules in a marked block. */ @@ -57,14 +62,45 @@ interface AgentHarness { data class Model(val id: String, val label: String) - data class Options(val model: String? = null, val plan: Boolean = false, val brief: String? = null, val effort: String? = null) + /** An API reached with a key; [keyPage] is where the key is made, and a [custom] one is any OpenAI-compatible server. */ + data class Provider(val id: String, val name: String, val keyPage: String? = null, val custom: Boolean = false) + + /** A permission mode; [id] is DroidDeck's own name for it, which each CLI maps to its flags. */ + data class Permission(val id: String, @StringRes val label: Int, @StringRes val hint: Int) + + data class Options( + val model: String? = null, val plan: Boolean = false, val brief: String? = null, val effort: String? = null, + val permission: String = ASK, val workdir: String = "/root", + ) companion object { + const val ASK = "ask" + const val EDITS = "edits" + const val AUTO = "auto" + const val DONT_ASK = "dontask" + const val FULL = "full" + val all: List = listOf(ClaudeCode, Codex, OpenCode) fun byId(id: String?): AgentHarness = all.firstOrNull { it.id == id } ?: ClaudeCode } } +/** What goes to one CLI process's stdin, and what its output lines mean. */ +interface AgentProtocol { + /** + * The lines that start a turn of [message]; [started] is true for a process that has just been started. The + * process stays open between turns, so work it started in the background can wake it. + */ + fun input(message: String, conversation: String?, options: AgentHarness.Options, started: Boolean): List + /** One line of the process's output, or null when it carries nothing to show. */ + fun parse(line: String): AgentEvent? + /** The line that answers [approval]. */ + fun answer(approval: AgentHost.Approval, allow: Boolean): String +} + +/** The message a CLI tells its model when the user denies a tool call. */ +internal const val DENIED = "The user denied this tool call." + /** What one line of output carries: whole entries, or text still being written. */ data class AgentEvent( val conversation: String? = null, @@ -81,6 +117,12 @@ data class AgentEvent( val background: Boolean = false, /** The error a background turn ended with, if it failed. */ val backgroundError: String? = null, + /** Lines to write to the process's stdin right away, the next step of a request it has answered. */ + val reply: List = emptyList(), + /** A tool call that waits for the user to allow it. */ + val approval: AgentHost.Approval? = null, + /** The id of an approval the CLI no longer waits for. */ + val resolved: String? = null, ) /** Claude Code: `claude -p` with stream-json input and output, resumed by session id. */ @@ -122,22 +164,54 @@ object ClaudeCode : AgentHarness { AgentHarness.Model("opus", "Opus"), AgentHarness.Model("sonnet", "Sonnet"), AgentHarness.Model("haiku", "Haiku"), ) - // DroidDeck runs the agent unattended on the user's own device; permission prompts have no one to answer them. + override val permissions = listOf( + AgentHarness.Permission(AgentHarness.ASK, R.string.agent_permission_ask, R.string.agent_permission_ask_hint), + AgentHarness.Permission(AgentHarness.EDITS, R.string.agent_permission_edits, R.string.agent_permission_edits_hint), + AgentHarness.Permission(AgentHarness.AUTO, R.string.agent_permission_auto, R.string.agent_permission_auto_hint), + AgentHarness.Permission(AgentHarness.DONT_ASK, R.string.agent_permission_dont_ask, R.string.agent_permission_dont_ask_hint), + AgentHarness.Permission(AgentHarness.FULL, R.string.agent_permission_full, R.string.agent_permission_full_hint), + ) + + private val MODES = mapOf( + AgentHarness.ASK to "manual", AgentHarness.EDITS to "acceptEdits", AgentHarness.AUTO to "auto", + AgentHarness.DONT_ASK to "dontAsk", AgentHarness.FULL to "bypassPermissions", + ) + + /** + * Prompts reach DroidDeck as can_use_tool requests on stdout (the SDK's stdio prompt tool). Plan mode keeps + * answering none, so a turn that would leave plan mode ends on its plan. + */ override fun turn(message: String, conversation: String?, options: AgentHarness.Options) = buildList { addAll(listOf(binary, "-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose", "--include-partial-messages")) - addAll(listOf("--permission-mode", if (options.plan) "plan" else "bypassPermissions")) + val mode = if (options.plan) "plan" else MODES[options.permission] ?: "manual" + addAll(listOf("--permission-mode", mode)) + if (mode != "plan" && mode != "bypassPermissions") add("--permission-prompt-tool=stdio") options.model?.let { addAll(listOf("--model", it)) } options.effort?.let { addAll(listOf("--effort", it)) } options.brief?.let { addAll(listOf("--append-system-prompt", it)) } if (conversation != null) addAll(listOf("--resume", conversation)) } - override fun input(message: String): String? = JSONObject() + fun input(message: String): String = JSONObject() .put("type", "user") .put("message", JSONObject().put("role", "user").put("content", JSONArray().put(JSONObject().put("type", "text").put("text", message)))) .toString() - override fun parse(line: String): AgentEvent? { + override fun protocol(): AgentProtocol = object : AgentProtocol { + override fun input(message: String, conversation: String?, options: AgentHarness.Options, started: Boolean) = listOf(this@ClaudeCode.input(message)) + override fun parse(line: String) = this@ClaudeCode.parse(line) + override fun answer(approval: AgentHost.Approval, allow: Boolean) = this@ClaudeCode.answer(approval, allow) + } + + @VisibleForTesting + internal fun answer(approval: AgentHost.Approval, allow: Boolean): String { + val decision = if (allow) JSONObject().put("behavior", "allow").put("updatedInput", runCatching { JSONObject(approval.payload) }.getOrDefault(JSONObject())) + else JSONObject().put("behavior", "deny").put("message", DENIED) + return JSONObject().put("type", "control_response") + .put("response", JSONObject().put("subtype", "success").put("request_id", approval.id).put("response", decision)).toString() + } + + fun parse(line: String): AgentEvent? { val o = runCatching { JSONObject(line) }.getOrNull() ?: return null val conversation = o.optString("session_id").takeIf { it.isNotEmpty() } // A subagent's messages carry the call that started it; only its tool calls are shown, under that call. @@ -184,6 +258,13 @@ object ClaudeCode : AgentHarness { AgentEvent(conversation, results) } "rate_limit_event" -> AgentEvent(conversation, limits = limits(o.optJSONObject("rate_limit_info"))) + "control_request" -> { + val request = o.optJSONObject("request")?.takeIf { it.optString("subtype") == "can_use_tool" } ?: return null + val tool = request.optString("tool_name") + val input = request.optJSONObject("input") ?: JSONObject() + AgentEvent(approval = AgentHost.Approval(o.optString("request_id"), tool, detail(input), fullInput(tool, input), input.toString())) + } + "control_cancel_request" -> AgentEvent(resolved = o.optString("request_id")) // The CLI starts turns of its own for background tasks (a resumed session first answers the ones the last // run left behind). Such a result is not the end of the user's turn; the host decides what it ends. "result" -> { @@ -266,7 +347,7 @@ object ClaudeCode : AgentHarness { }.joinToString("\n") } -/** OpenAI Codex: `codex exec --json`, resumed by thread id. */ +/** OpenAI Codex: `codex app-server`, its JSON-RPC protocol over stdio, resumed by thread id. */ object Codex : AgentHarness { override val id = "codex" override val name = "Codex" @@ -292,6 +373,13 @@ object Codex : AgentHarness { override val plans = false override val efforts = listOf("low", "medium", "high") + // Codex's sandbox needs Landlock and seccomp, which proot does not provide, so commands run unsandboxed + // and "untrusted" is what makes Codex ask before each one that is not known to be safe. + override val permissions = listOf( + AgentHarness.Permission(AgentHarness.ASK, R.string.agent_permission_ask, R.string.agent_permission_ask_hint), + AgentHarness.Permission(AgentHarness.FULL, R.string.agent_permission_full, R.string.agent_permission_full_hint), + ) + /** Codex keeps the models its account can use in `~/.codex/models_cache.json` once it has run. */ override fun models(rootfs: File): List = runCatching { val o = JSONObject(File(rootfs, "root/.codex/models_cache.json").readText()) @@ -304,106 +392,230 @@ object Codex : AgentHarness { } }.getOrDefault(emptyList()) - // Codex's own sandbox needs Landlock and seccomp, which proot does not provide. - override fun turn(message: String, conversation: String?, options: AgentHarness.Options) = buildList { - addAll(listOf(binary, "exec")) - if (conversation != null) addAll(listOf("resume", conversation)) - addAll(listOf("--json", "--dangerously-bypass-approvals-and-sandbox", "--skip-git-repo-check")) - options.model?.let { addAll(listOf("-m", it)) } - options.effort?.let { addAll(listOf("-c", "model_reasoning_effort=\"$it\"")) } - // codex exec has no system prompt option, so a new conversation starts with the brief. - add(if (conversation == null && options.brief != null) "${options.brief}\n\n$message" else message) - } + override fun turn(message: String, conversation: String?, options: AgentHarness.Options) = withoutStderr("codex", listOf(binary, "app-server")) - override fun parse(line: String): AgentEvent? { - val o = runCatching { JSONObject(line) }.getOrNull() ?: return null - val item = o.optJSONObject("item") - val id = item?.optString("id").orEmpty() - val entries = when (o.optString("type")) { - "thread.started" -> return AgentEvent(o.optString("thread_id").takeIf { it.isNotEmpty() }) - "item.started" -> when (item?.optString("type")) { - "command_execution" -> shellCommand(item.optString("command")).let { listOf(AgentHost.Entry.Used(id, "Shell", firstLine(it), it)) } - "mcp_tool_call" -> listOf(AgentHost.Entry.Used(id, item.optString("tool").ifEmpty { "Tool" }, item.optString("server"), item.optJSONObject("arguments")?.toString(2).orEmpty())) - "web_search" -> listOf(AgentHost.Entry.Used(id, "Search", item.optString("query"), item.optString("query"))) - else -> emptyList() - } - "item.updated" -> when (item?.optString("type")) { - "todo_list" -> listOf(todoEntry(id, item)) - else -> emptyList() - } - "item.completed" -> when (item?.optString("type")) { - "agent_message" -> item.optString("text").trim().takeIf { it.isNotEmpty() }?.let { listOf(AgentHost.Entry.Said(it)) }.orEmpty() - "reasoning" -> item.optString("text").trim().takeIf { it.isNotEmpty() }?.let { listOf(AgentHost.Entry.Thought(it)) }.orEmpty() - "command_execution" -> listOf(AgentHost.Entry.Result(id, item.optString("aggregated_output"), - item.has("exit_code") && !item.isNull("exit_code") && item.optInt("exit_code") != 0)) - "mcp_tool_call" -> listOf(AgentHost.Entry.Result(id, item.optJSONObject("result")?.toString(2) ?: item.optJSONObject("error")?.optString("message").orEmpty(), - item.optString("status") == "failed")) - "web_search" -> listOf(AgentHost.Entry.Result(id, "", false)) - "file_change" -> listOf( - AgentHost.Entry.Used(id, "Edit", changedFiles(item), changedFiles(item).replace(", ", "\n")), - AgentHost.Entry.Result(id, item.optString("status"), item.optString("status") == "failed"), - ) - "todo_list" -> listOf(todoEntry(id, item)) - "error" -> listOf(AgentHost.Entry.Said("⚠ " + item.optString("message"))) - else -> emptyList() - } - "turn.completed" -> return AgentEvent( - entries = listOf(AgentHost.Entry.Finished(null)), - usage = o.optJSONObject("usage")?.let { AgentHost.Usage(0, 0.0, it.optLong("input_tokens") + it.optLong("cached_input_tokens"), it.optLong("output_tokens")) }, + override fun protocol(): AgentProtocol = Protocol() + + @VisibleForTesting + internal class Protocol : AgentProtocol { + private var next = 1 + private var thread: String? = null + /** The initialize request, the thread/start or thread/resume sent once it succeeds, and the turn that waits for its thread. */ + private var initializing = -1 + private var initialized = false + private var open: String? = null + private var opening = -1 + private var waiting: JSONObject? = null + private var starting = -1 + private var turnId = "" + /** Each file change's paths and diffs, from its start; an approval for it names only the item. */ + private val changes = mutableMapOf() + private var input = 0L + private var output = 0L + + override fun input(message: String, conversation: String?, options: AgentHarness.Options, started: Boolean): List { + val turn = JSONObject() + .put("input", JSONArray().put(JSONObject().put("type", "text").put("text", message).put("text_elements", JSONArray()))) + options.model?.let { turn.put("model", it) } + options.effort?.let { turn.put("effort", it) } + val known = thread + if (!started && known != null) return listOf(startTurn(turn.put("threadId", known))) + val params = JSONObject() + .put("approvalPolicy", if (options.permission == AgentHarness.FULL) "never" else "untrusted") + .put("sandbox", "danger-full-access") + options.model?.let { params.put("model", it) } + options.brief?.let { params.put("developerInstructions", it) } + if (conversation != null) params.put("threadId", conversation) + waiting = turn + opening = next++ + val request = JSONObject().put("id", opening).put("method", if (conversation != null) "thread/resume" else "thread/start").put("params", params).toString() + // Codex refuses a second initialize on one connection, so a thread that failed to open is asked for again alone. + if (initialized) return listOf(request) + open = request + initializing = next++ + return listOf( + JSONObject().put("id", initializing).put("method", "initialize") + .put("params", JSONObject().put("clientInfo", JSONObject().put("name", "droiddeck").put("title", "DroidDeck").put("version", "1")) + .put("capabilities", JSONObject.NULL)).toString(), ) - "turn.failed" -> listOf(AgentHost.Entry.Finished(o.optJSONObject("error")?.optString("message") ?: "turn failed")) - // codex reports a dropped stream it is retrying as an error event, and the turn goes on. - "error" -> o.optString("message").let { message -> - if (message.startsWith("Reconnecting...")) emptyList() else listOf(AgentHost.Entry.Finished(message.ifEmpty { "error" })) - } - else -> emptyList() } - return if (entries.isEmpty()) null else AgentEvent(entries = entries) + + private fun startTurn(params: JSONObject): String { + starting = next++ + return JSONObject().put("id", starting).put("method", "turn/start").put("params", params).toString() + } + + override fun answer(approval: AgentHost.Approval, allow: Boolean): String = + JSONObject(approval.payload).put("result", JSONObject().put("decision", if (allow) "accept" else "decline")).toString() + + override fun parse(line: String): AgentEvent? { + val o = runCatching { JSONObject(line) }.getOrNull() ?: return null + val method = o.optString("method") + if (method.isEmpty()) return response(o) + val params = o.optJSONObject("params") ?: JSONObject() + if (o.has("id")) return request(o.get("id"), method, params) + return notification(method, params) + } + + private fun response(o: JSONObject): AgentEvent? { + val id = o.optInt("id", -1) + val error = o.optJSONObject("error")?.optString("message")?.ifEmpty { "error" } + return when (id) { + initializing -> { + if (error != null) return AgentEvent(entries = listOf(AgentHost.Entry.Finished(error))) + initialized = true + val request = open ?: return null + open = null + AgentEvent(reply = listOf(JSONObject().put("method", "initialized").toString(), request)) + } + opening -> { + if (error != null) return AgentEvent(entries = listOf(AgentHost.Entry.Finished(error))) + val started = o.optJSONObject("result")?.optJSONObject("thread")?.optString("id")?.takeIf { it.isNotEmpty() } ?: return null + thread = started + val turn = waiting ?: return AgentEvent(started) + waiting = null + AgentEvent(started, reply = listOf(startTurn(turn.put("threadId", started)))) + } + starting -> error?.let { AgentEvent(entries = listOf(AgentHost.Entry.Finished(it))) } + else -> null + } + } + + private fun request(id: Any, method: String, params: JSONObject): AgentEvent { + val payload = JSONObject().put("id", id).toString() + return when (method) { + "item/commandExecution/requestApproval" -> { + val command = shellCommand(params.optString("command")) + val reason = params.optString("reason").takeIf { it.isNotEmpty() && it != "null" } + AgentEvent(approval = AgentHost.Approval(id.toString(), "Shell", firstLine(command), listOfNotNull(command, reason).joinToString("\n\n"), payload)) + } + "item/fileChange/requestApproval" -> { + val list = changes[params.optString("itemId")] ?: JSONArray() + val files = (0 until list.length()).mapNotNull { list.optJSONObject(it) } + AgentEvent(approval = AgentHost.Approval( + id.toString(), "Edit", files.joinToString(", ") { it.optString("path") }.take(400), + files.joinToString("\n\n") { it.optString("path") + "\n" + patchLines(it.optString("diff"), it.optJSONObject("kind")?.optString("type").orEmpty()) }, payload, + )) + } + // Everything else asks for something DroidDeck has no screen for; refusing keeps the turn going. + else -> AgentEvent(reply = listOf(JSONObject(payload) + .put("error", JSONObject().put("code", -32601).put("message", "DroidDeck cannot answer $method")).toString())) + } + } + + private fun notification(method: String, params: JSONObject): AgentEvent? { + val item = params.optJSONObject("item") + val id = item?.optString("id").orEmpty() + val entries: List = when (method) { + "thread/started" -> return params.optJSONObject("thread")?.optString("id")?.takeIf { it.isNotEmpty() }?.let { AgentEvent(it) } + "turn/started" -> { + turnId = params.optJSONObject("turn")?.optString("id").orEmpty() + input = 0 + output = 0 + return null + } + "item/agentMessage/delta" -> return AgentEvent(text = params.optString("delta")) + "item/reasoning/summaryTextDelta", "item/reasoning/textDelta" -> return AgentEvent(thinking = params.optString("delta")) + "item/started" -> when (item?.optString("type")) { + "commandExecution" -> shellCommand(item.optString("command")).let { listOf(AgentHost.Entry.Used(id, "Shell", firstLine(it), it)) } + "mcpToolCall" -> listOf(AgentHost.Entry.Used(id, item.optString("tool").ifEmpty { "Tool" }, item.optString("server"), item.opt("arguments")?.let(::pretty).orEmpty())) + "webSearch" -> listOf(AgentHost.Entry.Used(id, "Search", item.optString("query"), item.optString("query"))) + "fileChange" -> { + val list = item.optJSONArray("changes") ?: JSONArray() + changes[id] = list + fileEntries(id, list) + } + else -> emptyList() + } + "item/completed" -> when (item?.optString("type")) { + "agentMessage" -> item.optString("text").trim().takeIf { it.isNotEmpty() }?.let { listOf(AgentHost.Entry.Said(it)) }.orEmpty() + "reasoning" -> { + val parts = (strings(item.optJSONArray("summary")) + strings(item.optJSONArray("content"))).joinToString("\n\n").trim() + if (parts.isEmpty()) emptyList() else listOf(AgentHost.Entry.Thought(parts)) + } + "commandExecution" -> { + val status = item.optString("status") + val exit = if (item.isNull("exitCode")) 0 else item.optInt("exitCode") + val out = item.optString("aggregatedOutput").takeUnless { item.isNull("aggregatedOutput") }.orEmpty() + listOf(AgentHost.Entry.Result(id, if (status == "declined") out.ifEmpty { DENIED } else out, status != "completed" || exit != 0)) + } + "mcpToolCall" -> listOf(AgentHost.Entry.Result(id, + item.optJSONObject("result")?.let(::pretty) ?: item.optJSONObject("error")?.optString("message").orEmpty(), item.optString("status") == "failed")) + "webSearch" -> listOf(AgentHost.Entry.Result(id, "", false)) + "fileChange" -> { + val list = item.optJSONArray("changes") ?: changes[id] ?: JSONArray() + changes.remove(id) + val failed = item.optString("status") != "completed" + (0 until list.length()).map { AgentHost.Entry.Result("$id#$it", if (failed) item.optString("status") else "", failed) } + } + else -> emptyList() + } + "turn/plan/updated" -> listOf(plan(params.optJSONArray("plan"))) + "thread/tokenUsage/updated" -> { + val usage = params.optJSONObject("tokenUsage") ?: return null + val last = usage.optJSONObject("last") + input += last?.optLong("inputTokens") ?: 0 + output += last?.optLong("outputTokens") ?: 0 + return AgentEvent( + context = last?.optLong("totalTokens")?.takeIf { it > 0 }, + window = usage.optLong("modelContextWindow").takeIf { it > 0 }, + ) + } + "account/rateLimits/updated" -> return rateLimits(params.optJSONObject("rateLimits"))?.let { AgentEvent(limits = it) } + "serverRequest/resolved" -> return AgentEvent(resolved = params.opt("requestId")?.toString()) + "turn/completed" -> { + val turn = params.optJSONObject("turn") ?: JSONObject() + val error = when (turn.optString("status")) { + "failed" -> turn.optJSONObject("error")?.optString("message")?.ifEmpty { null } ?: "turn failed" + else -> null + } + return AgentEvent( + entries = listOf(AgentHost.Entry.Finished(error)), + usage = AgentHost.Usage(if (turn.isNull("durationMs")) 0 else turn.optLong("durationMs"), 0.0, input, output), + ) + } + else -> emptyList() + } + return if (entries.isEmpty()) null else AgentEvent(entries = entries) + } + + private fun plan(steps: JSONArray?): AgentHost.Entry.Used { + val text = (0 until (steps?.length() ?: 0)).mapNotNull { i -> + val step = steps?.optJSONObject(i) ?: return@mapNotNull null + val mark = when (step.optString("status")) { "completed" -> "[x]"; "inProgress" -> "[~]"; else -> "[ ]" } + "$mark ${step.optString("step")}" + }.joinToString("\n") + return AgentHost.Entry.Used("$turnId-todo", "TodoWrite", "", text, output = "") + } } - private const val TOKEN_COUNT = "\"payload\":{\"type\":\"token_count\"" - - /** Codex prints no limits with --json; its session log, named after the thread, has a token_count event each step. */ - override fun usage(rootfs: File, conversation: String?): AgentEvent? { - conversation ?: return null - val log = File(rootfs, "root/.codex/sessions").walkBottomUp().filter { it.isFile && it.name.endsWith("-$conversation.jsonl") } - .maxByOrNull { it.lastModified() } ?: return null - val last = runCatching { log.readLines().lastOrNull { it.contains(TOKEN_COUNT) } }.getOrNull() ?: return null - return tokenCount(last) + /** One Edit per changed file: its path, then the diff as lines led by ' ', '-' or '+'. */ + private fun fileEntries(id: String, changes: JSONArray) = (0 until changes.length()).mapNotNull { i -> + val change = changes.optJSONObject(i) ?: return@mapNotNull null + val path = change.optString("path") + AgentHost.Entry.Used("$id#$i", "Edit", path, path + "\n" + patchLines(change.optString("diff"), change.optJSONObject("kind")?.optString("type").orEmpty())) } @VisibleForTesting - internal fun tokenCount(line: String): AgentEvent? { - val payload = runCatching { JSONObject(line).optJSONObject("payload") }.getOrNull()?.takeIf { it.optString("type") == "token_count" } ?: return null - val info = payload.optJSONObject("info") - val rates = payload.optJSONObject("rate_limits") - val limits = listOf("primary", "secondary").mapNotNull { key -> - val w = rates?.optJSONObject(key) ?: return@mapNotNull null - AgentHost.Limit(w.optInt("window_minutes"), w.optDouble("used_percent", 0.0).toInt(), w.optLong("resets_at")) - } - return AgentEvent( - context = info?.optJSONObject("last_token_usage")?.optLong("total_tokens")?.takeIf { it > 0 }, - window = info?.optLong("model_context_window")?.takeIf { it > 0 }, - limits = limits.takeIf { it.isNotEmpty() }, - ) + internal fun rateLimits(snapshot: JSONObject?): List? { + snapshot ?: return null + return listOf("primary", "secondary").mapNotNull { key -> + val w = snapshot.optJSONObject(key) ?: return@mapNotNull null + AgentHost.Limit(w.optInt("windowDurationMins"), w.optDouble("usedPercent", 0.0).toInt(), w.optLong("resetsAt")) + }.takeIf { it.isNotEmpty() } } - private fun todoEntry(id: String, item: JSONObject): AgentHost.Entry.Used { - val items = item.optJSONArray("items") ?: JSONArray() - val text = (0 until items.length()).mapNotNull { i -> - val todo = items.optJSONObject(i) ?: return@mapNotNull null - "${if (todo.optBoolean("completed")) "[x]" else "[ ]"} ${todo.optString("text")}" - }.joinToString("\n") - return AgentHost.Entry.Used("$id-todo", "TodoWrite", "", text, output = "") - } + private fun strings(list: JSONArray?) = (0 until (list?.length() ?: 0)).mapNotNull { list?.optString(it)?.takeIf { s -> s.isNotBlank() } } - private fun changedFiles(item: JSONObject): String { - val changes = item.optJSONArray("changes") ?: return "" - return (0 until changes.length()).mapNotNull { changes.optJSONObject(it)?.optString("path") }.joinToString(", ").take(400) + private fun pretty(value: Any): String = when (value) { + is JSONObject -> value.toString(2) + is JSONArray -> value.toString(2) + JSONObject.NULL -> "" + else -> value.toString() } } -/** OpenCode: `opencode run --format json`, resumed by session id. */ +/** OpenCode: `opencode acp`, the Agent Client Protocol over stdio, resumed by session id. */ object OpenCode : AgentHarness { override val id = "opencode" override val name = "OpenCode" @@ -412,31 +624,117 @@ object OpenCode : AgentHarness { override val instructions = "root/.config/opencode/AGENTS.md" override val install = "curl -fsSL https://opencode.ai/install | bash -s -- --no-modify-path" private const val AUTH = "root/.local/share/opencode/auth.json" + private const val CONFIG = "root/.config/opencode/opencode.json" private const val FREE = "root/.config/opencode/.droiddeck-free" private const val MODELS = "root/.cache/droiddeck/opencode-models" + /** The provider id DroidDeck gives a server the user names, in opencode's config and auth. */ + private const val CUSTOM = "droiddeck" // `opencode models` lists only what the saved keys reach, so the check that runs it keeps the model list current. override val signedIn = listOf("sh", "-c", "mkdir -p /${MODELS.substringBeforeLast('/')}; $binary models --verbose > /$MODELS.$$ 2>/dev/null && mv -f /$MODELS.$$ /$MODELS; rm -f /$MODELS.$$; " + - "grep -q '\"type\"' /$AUTH 2>/dev/null || [ -e /$FREE ]") - override val keyPage = "https://opencode.ai/auth" - override val signIn = listOf("/root/.local/bin/android-open", keyPage) + "grep -q '\"type\"' /$AUTH 2>/dev/null || [ -e /$FREE ] || grep -q '\"$CUSTOM\"' /$CONFIG 2>/dev/null") + // Ids are opencode's own (models.dev), so a saved key is what `opencode auth login` would save for that provider. + override val providers = listOf( + AgentHarness.Provider("opencode", "OpenCode Zen", "https://opencode.ai/auth"), + AgentHarness.Provider("ollama-cloud", "Ollama Cloud", "https://ollama.com/settings/keys"), + AgentHarness.Provider("openrouter", "OpenRouter", "https://openrouter.ai/settings/keys"), + AgentHarness.Provider("openai", "OpenAI", "https://platform.openai.com/api-keys"), + AgentHarness.Provider("anthropic", "Anthropic", "https://console.anthropic.com/settings/keys"), + AgentHarness.Provider("google", "Gemini", "https://aistudio.google.com/apikey"), + AgentHarness.Provider(CUSTOM, "Other server", custom = true), + ) + override val signIn = listOf("/root/.local/bin/android-open", providers.first().keyPage!!) override val free = true override val plans = true override val efforts = listOf("low", "medium", "high") - override fun hasKey(rootfs: File) = runCatching { JSONObject(File(rootfs, AUTH).readText()).has("opencode") }.getOrDefault(false) + override fun keys(rootfs: File): Set { + val auth = runCatching { JSONObject(File(rootfs, AUTH).readText()) }.getOrNull() + val custom = runCatching { JSONObject(File(rootfs, CONFIG).readText()).optJSONObject("provider")?.has(CUSTOM) }.getOrNull() == true + return providers.filter { auth?.has(it.id) == true || (it.custom && custom) }.map { it.id }.toSet() + } - /** The key opencode's own `auth login` would save for OpenCode Zen. */ - override fun saveKey(rootfs: File, key: String) { - val file = File(rootfs, AUTH) - // An auth.json that cannot be read holds other providers' sign-ins too, so it is never replaced. - val auth = if (file.exists()) JSONObject(file.readText()) else JSONObject() - auth.put("opencode", JSONObject().put("type", "api").put("key", key.trim())) + /** + * Saves the key as opencode's own `auth login` would. A custom server also gets a provider in + * opencode's config with the models its `/models` lists, since opencode does not list them itself. + */ + override fun saveKey(rootfs: File, provider: AgentHarness.Provider, key: String, endpoint: String?, get: (String, String?) -> String) { + val token = key.trim().takeIf { it.isNotEmpty() } + // Both files are read before either is written, so one that cannot be read changes nothing. + val authFile = File(rootfs, AUTH) + val auth = readJson(authFile) + if (token != null) auth.put(provider.id, JSONObject().put("type", "api").put("key", token)) else auth.remove(provider.id) + if (!provider.custom) return writeJson(authFile, auth, private = true) + val base = endpoint(endpoint ?: "") + val configFile = File(rootfs, CONFIG) + val before = configFile.takeIf { it.exists() }?.readText() + val config = readJson(configFile) + val models = modelIds(get("$base/models", token)) + check(models.isNotEmpty()) { "No models at $base" } + if (!config.has("\$schema")) config.put("\$schema", "https://opencode.ai/config.json") + val all = config.optJSONObject("provider") ?: JSONObject().also { config.put("provider", it) } + all.put(CUSTOM, JSONObject() + .put("npm", "@ai-sdk/openai-compatible") + .put("name", runCatching { java.net.URI(base).host }.getOrNull() ?: provider.name) + .put("options", JSONObject().put("baseURL", base)) + .put("models", JSONObject().apply { models.forEach { put(it, JSONObject().put("name", it)) } })) + writeJson(configFile, config) + try { + writeJson(authFile, auth, private = true) + } catch (e: Exception) { + val undone = runCatching { + if (before != null) writeFile(configFile, before) else java.nio.file.Files.deleteIfExists(configFile.toPath()) + } + // First, since the setup row shows two lines of the message. + undone.exceptionOrNull()?.let { throw IllegalStateException("The server config could not be put back (${it.message}): ${e.message}", e) } + throw e + } + } + + override fun removeKey(rootfs: File, provider: AgentHarness.Provider) { + if (File(rootfs, AUTH).exists()) editJson(File(rootfs, AUTH), private = true) { it.remove(provider.id) } + if (provider.custom && File(rootfs, CONFIG).exists()) editJson(File(rootfs, CONFIG)) { it.optJSONObject("provider")?.remove(CUSTOM) } + } + + /** A server address as typed, made into the OpenAI-compatible base URL opencode calls. */ + @VisibleForTesting + internal fun endpoint(typed: String): String { + val url = typed.trim().trimEnd('/').let { if ("://" in it) it else "http://$it" } + require(url.substringAfter("://").isNotEmpty()) { "No server address" } + return if (url.substringAfter("://").contains('/')) url else "$url/v1" + } + + @VisibleForTesting + internal fun modelIds(body: String): List { + // The userland can print its own warnings ahead of the response. + val json = body.substring(body.indexOf('{').coerceAtLeast(0), body.lastIndexOf('}') + 1) + val data = runCatching { JSONObject(json).optJSONArray("data") }.getOrNull() ?: return emptyList() + return (0 until data.length()).mapNotNull { data.optJSONObject(it)?.optString("id")?.takeIf { id -> id.isNotEmpty() } }.distinct() + } + + // A file that cannot be read holds the user's other providers too, so it is never replaced. + private fun readJson(file: File) = if (file.exists()) JSONObject(file.readText()) else JSONObject() + + private fun editJson(file: File, private: Boolean = false, edit: (JSONObject) -> Unit) = + writeJson(file, readJson(file).also(edit), private) + + /** Writes beside [file] and moves it into place, so a write that stops partway leaves the old file. */ + private fun writeJson(file: File, json: JSONObject, private: Boolean = false) = writeFile(file, json.toString(2) + "\n", private) + + private fun writeFile(file: File, text: String, private: Boolean = false) { file.parentFile?.mkdirs() - file.writeText(auth.toString(2) + "\n") - file.setReadable(false, false) - file.setReadable(true, true) + val temp = File(file.parentFile, ".${file.name}.tmp") + try { + temp.writeText(text) + if (private) { + temp.setReadable(false, false) + temp.setReadable(true, true) + } + java.nio.file.Files.move(temp.toPath(), file.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING, java.nio.file.StandardCopyOption.ATOMIC_MOVE) + } finally { + temp.delete() + } } override fun useFree(rootfs: File) { @@ -473,7 +771,8 @@ object OpenCode : AgentHarness { runCatching { JSONObject(json.toString()) }.getOrNull()?.takeIf { it.optString("status") != "deprecated" }?.let { o -> val provider = o.optString("providerID") val label = o.optString("name").ifEmpty { current } - models += AgentHarness.Model(current, if (provider.isEmpty() || provider == "opencode") label else "$label · $provider") + val source = if (provider == "opencode" || provider == CUSTOM) "" else providers.firstOrNull { it.id == provider }?.name ?: provider + models += AgentHarness.Model(current, if (source.isEmpty()) label else "$label · $source") o.optJSONObject("limit")?.optLong("context")?.takeIf { it > 0 }?.let { windows[current] = it } } id = null @@ -484,86 +783,234 @@ object OpenCode : AgentHarness { private val MODEL_ID = Regex("""^[\w.-]+/\S+$""") - private class Spent(var cost: Double = 0.0, var input: Long = 0, var output: Long = 0) - private val spent = Spent() - @Volatile private var model: String? = null + override val permissions = listOf( + AgentHarness.Permission(AgentHarness.ASK, R.string.agent_permission_ask, R.string.agent_permission_ask_hint), + AgentHarness.Permission(AgentHarness.EDITS, R.string.agent_permission_edits, R.string.agent_permission_edits_hint), + AgentHarness.Permission(AgentHarness.FULL, R.string.agent_permission_full, R.string.agent_permission_full_hint), + ) - override fun turn(message: String, conversation: String?, options: AgentHarness.Options): List { - synchronized(spent) { spent.cost = 0.0; spent.input = 0; spent.output = 0 } - model = options.model - // DroidDeck runs the agent unattended; --auto approves all the agent does not deny itself, and plan mode denies edits. - return buildList { - addAll(listOf(binary, "run", "--format", "json", "--auto", "--thinking")) - if (conversation != null) addAll(listOf("-s", conversation)) - if (options.plan) addAll(listOf("--agent", "plan")) - options.model?.let { addAll(listOf("-m", it)) } - options.effort?.let { addAll(listOf("--variant", it)) } - add("--") - // opencode run has no system prompt option, so a new conversation starts with the brief. - add(if (conversation == null && options.brief != null) "${options.brief}\n\n$message" else message) + /** + * Rules merged over the user's opencode config. OpenCode applies the last rule that matches in key order, so the + * asking modes name each permission rather than "*", which could land after a rule of the user's and override it. + */ + @VisibleForTesting + internal fun rules(permission: String): JSONObject { + val asks = listOf("bash", "webfetch", "websearch", "codesearch") + return when (permission) { + AgentHarness.FULL -> JSONObject().put("*", "allow") + AgentHarness.EDITS -> JSONObject().put("edit", "allow").apply { asks.forEach { put(it, "ask") } } + else -> JSONObject().put("edit", "ask").apply { asks.forEach { put(it, "ask") } } } } - override fun usage(rootfs: File, conversation: String?): AgentEvent? { - val id = model ?: return null - return listed(rootfs)?.windows?.get(id)?.let { AgentEvent(window = it) } - } + override fun turn(message: String, conversation: String?, options: AgentHarness.Options) = + withoutStderr("opencode", listOf("/usr/bin/env", "OPENCODE_PERMISSION=${rules(options.permission)}", binary, "acp")) - override fun parse(line: String): AgentEvent? { - val o = runCatching { JSONObject(line) }.getOrNull() ?: return null - val conversation = o.optString("sessionID").takeIf { it.isNotEmpty() } - val part = o.optJSONObject("part") - return when (o.optString("type")) { - "text" -> AgentEvent(conversation, text(part) { AgentHost.Entry.Said(it) }) - "reasoning" -> AgentEvent(conversation, text(part) { AgentHost.Entry.Thought(it) }) - "tool_use" -> AgentEvent(conversation, part?.let { tool(it) }.orEmpty()) - "step_finish" -> { - val tokens = part?.optJSONObject("tokens") - val cache = tokens?.optJSONObject("cache") - val total = synchronized(spent) { - spent.cost += part?.optDouble("cost", 0.0) ?: 0.0 - spent.input += (tokens?.optLong("input") ?: 0) + (cache?.optLong("read") ?: 0) + (cache?.optLong("write") ?: 0) - spent.output += (tokens?.optLong("output") ?: 0) + (tokens?.optLong("reasoning") ?: 0) - AgentHost.Usage(0, spent.cost, spent.input, spent.output) + /** The conversation's cost so far; DroidDeck takes the turn's share from what its chat has recorded. */ + override val sessionCost = true + + override fun protocol(): AgentProtocol = Protocol() + + /** `opencode acp`: the Agent Client Protocol, JSON-RPC over stdio. */ + @VisibleForTesting + internal class Protocol : AgentProtocol { + private enum class Stage { INIT, SESSION, CONFIG, PROMPT, IDLE } + + private var next = 1 + private var stage = Stage.IDLE + private var pending = -1 + private var session: String? = null + private var resume: String? = null + private var cwd = "/root" + /** Requests for the session still to send, each once the one before it has been answered. */ + private val queue = ArrayDeque<(String) -> JSONObject>() + private val said = StringBuilder() + private val thought = StringBuilder() + /** Each tool call's name, which only its first update carries, and its latest entry. */ + private val names = mutableMapOf() + private val used = mutableMapOf() + private var cost = 0.0 + private var started = 0L + + override fun input(message: String, conversation: String?, options: AgentHarness.Options, started: Boolean): List { + val text = if (conversation == null && options.brief != null) "${options.brief}\n\n$message" else message + val prompt = { id: String -> + JSONObject().put("sessionId", id).put("prompt", JSONArray().put(JSONObject().put("type", "text").put("text", text))) + } + queue.clear() + val known = session + if (!started && known != null && configured) return listOf(send(Stage.PROMPT, "session/prompt", prompt(known))) + fun option(config: String, value: String) = { id: String -> JSONObject().put("sessionId", id).put("configId", config).put("value", value) } + options.model?.let { queue += option("model", it) } + options.effort?.let { queue += option("effort", it) } + queue += option("mode", if (options.plan) "plan" else "build") + queue += prompt + // A session whose options were refused sets them all again before its next prompt. + if (!started && known != null) return listOf(advance(known)) + resume = conversation + cwd = options.workdir + return listOf(send(Stage.INIT, "initialize", JSONObject().put("protocolVersion", 1).put("clientCapabilities", JSONObject()))) + } + + private fun send(stage: Stage, method: String, params: JSONObject): String { + this.stage = stage + pending = next++ + if (stage == Stage.PROMPT) started = System.currentTimeMillis() + return JSONObject().put("jsonrpc", "2.0").put("id", pending).put("method", method).put("params", params).toString() + } + + /** The next queued request: the prompt once nothing else is left. */ + private fun advance(id: String): String { + val make = queue.removeFirst() + val params = make(id) + configuring = params.optString("configId") + configured = queue.isEmpty() + return if (queue.isEmpty()) send(Stage.PROMPT, "session/prompt", params) else send(Stage.CONFIG, "session/set_config_option", params) + } + + /** The config option the pending set_config_option sets. */ + private var configuring = "" + /** The session's model, effort and mode were all set, so a later prompt can go straight to it. */ + private var configured = false + + override fun answer(approval: AgentHost.Approval, allow: Boolean): String = JSONObject(approval.payload).put("jsonrpc", "2.0") + .put("result", JSONObject().put("outcome", JSONObject().put("outcome", "selected").put("optionId", if (allow) "once" else "reject"))).toString() + + override fun parse(line: String): AgentEvent? { + val o = runCatching { JSONObject(line) }.getOrNull() ?: return null + val method = o.optString("method") + val params = o.optJSONObject("params") ?: JSONObject() + return when { + method.isEmpty() -> response(o) + o.has("id") -> request(o.get("id"), method, params) + method == "session/update" -> update(params.optJSONObject("update") ?: return null) + else -> null + } + } + + private fun response(o: JSONObject): AgentEvent? { + if (o.optInt("id", -1) != pending) return null + val error = o.optJSONObject("error")?.let { it.optJSONObject("data")?.optString("message")?.ifEmpty { null } ?: it.optString("message").ifEmpty { "error" } } + val result = o.optJSONObject("result") ?: JSONObject() + return when (stage) { + Stage.INIT -> error?.let(::failed) ?: AgentEvent(reply = listOf( + resume?.let { send(Stage.SESSION, "session/resume", JSONObject().put("sessionId", it).put("cwd", cwd).put("mcpServers", JSONArray())) } + ?: send(Stage.SESSION, "session/new", JSONObject().put("cwd", cwd).put("mcpServers", JSONArray())), + )) + Stage.SESSION -> { + if (error != null) return failed(error) + val id = result.optString("sessionId").ifEmpty { resume.orEmpty() }.takeIf { it.isNotEmpty() } ?: return failed("no session") + session = id + AgentEvent(id, reply = listOf(advance(id))) } - val context = tokens?.optLong("total")?.takeIf { it > 0 } - // A step that ends to run tools is followed by another; any other reason ends the turn. - if (part?.optString("reason") == "tool-calls") AgentEvent(conversation, context = context) - else AgentEvent(conversation, listOf(AgentHost.Entry.Finished(null)), context = context, usage = total) + // A model without effort levels refuses one and the turn goes on with its default; a refused + // mode would run a plan turn as a build one, so it ends the turn instead. + Stage.CONFIG -> if (error != null && configuring == "mode") failed(error) else AgentEvent(reply = listOf(advance(session ?: return null))) + Stage.PROMPT -> { + stage = Stage.IDLE + val usage = result.optJSONObject("usage") + val reason = result.optString("stopReason") + AgentEvent( + session, + flush() + AgentHost.Entry.Finished(error ?: if (reason == "refusal") "refused" else null), + usage = AgentHost.Usage( + System.currentTimeMillis() - started, cost, + (usage?.optLong("inputTokens") ?: 0) + (usage?.optLong("cachedReadTokens") ?: 0), + (usage?.optLong("outputTokens") ?: 0) + (usage?.optLong("thoughtTokens") ?: 0), + ), + ) + } + Stage.IDLE -> null } - "error" -> { - val error = o.optJSONObject("error") - val message = error?.optJSONObject("data")?.optString("message")?.takeIf { it.isNotEmpty() } - ?: error?.optString("message")?.takeIf { it.isNotEmpty() } ?: error?.optString("name")?.takeIf { it.isNotEmpty() } ?: "error" - AgentEvent(conversation, listOf(AgentHost.Entry.Finished(message))) + } + + private fun failed(error: String): AgentEvent { + stage = Stage.IDLE + configured = false + return AgentEvent(session, flush() + AgentHost.Entry.Finished(error)) + } + + private fun request(id: Any, method: String, params: JSONObject): AgentEvent { + val payload = JSONObject().put("id", id).toString() + if (method != "session/request_permission") { + // File writes and terminals stay with OpenCode, which does them itself when the client declines. + return AgentEvent(reply = listOf(JSONObject(payload).put("jsonrpc", "2.0") + .put("error", JSONObject().put("code", -32601).put("message", "DroidDeck cannot answer $method")).toString())) } - else -> conversation?.let { AgentEvent(it) } + val call = params.optJSONObject("toolCall") ?: JSONObject() + val raw = call.optJSONObject("rawInput") ?: JSONObject() + val name = names[call.optString("toolCallId")] ?: call.optString("kind") + val kind = call.optString("kind") + val approval = when { + kind == "execute" -> AgentHost.Approval(id.toString(), "Bash", firstLine(raw.optString("command")), raw.optString("command"), payload) + // OpenCode asks for a folder outside the workspace on its own, before the tool's own ask. + raw.has("parentDir") -> AgentHost.Approval( + id.toString(), "External directory", raw.optString("parentDir"), + listOf(raw.optString("parentDir"), raw.optString("command")).filter { it.isNotEmpty() }.joinToString("\n\n"), payload, + ) + raw.has("diff") -> { + val path = raw.optString("filepath") + AgentHost.Approval(id.toString(), "Edit", path, path + "\n" + patchLines(raw.optString("diff"), ""), payload) + } + else -> AgentHost.Approval(id.toString(), toolName(name), call.optString("title"), raw.toString(2), payload) + } + return AgentEvent(session, flush(), approval = approval) + } + + private fun update(u: JSONObject): AgentEvent? = when (u.optString("sessionUpdate")) { + "agent_message_chunk" -> chunk(u)?.let { said.append(it); AgentEvent(session, text = it) } + "agent_thought_chunk" -> chunk(u)?.let { thought.append(it); AgentEvent(session, thinking = it) } + "tool_call", "tool_call_update" -> AgentEvent(session, flush() + tool(u)) + "usage_update" -> { + u.optJSONObject("cost")?.optDouble("amount")?.takeIf { !it.isNaN() }?.let { cost = it } + AgentEvent(session, context = u.optLong("used").takeIf { it > 0 }, window = u.optLong("size").takeIf { it > 0 }) + } + else -> null + } + + private fun chunk(u: JSONObject) = u.optJSONObject("content")?.takeIf { it.optString("type") == "text" }?.optString("text")?.takeIf { it.isNotEmpty() } + + /** What was written since the last entry, as whole entries. */ + private fun flush(): List = buildList { + thought.toString().trim().takeIf { it.isNotEmpty() }?.let { add(AgentHost.Entry.Thought(it)) } + said.toString().trim().takeIf { it.isNotEmpty() }?.let { add(AgentHost.Entry.Said(it)) } + thought.clear() + said.clear() + } + + private fun tool(u: JSONObject): List { + val id = u.optString("toolCallId") + if (u.optString("sessionUpdate") == "tool_call") names[id] = u.optString("title") + val input = u.optJSONObject("rawInput")?.takeIf { it.length() > 0 } + val entry = if (input != null || used[id] == null) tool(id, names[id].orEmpty(), input ?: JSONObject()) else used.getValue(id) + used[id] = entry + val raw = u.optJSONObject("rawOutput") + return when (u.optString("status")) { + "completed" -> { + val exit = raw?.optJSONObject("metadata")?.opt("exit") + listOf(entry, AgentHost.Entry.Result(id, raw?.optString("output")?.ifEmpty { null } ?: content(u), exit is Number && exit.toInt() != 0)) + } + "failed" -> listOf(entry, AgentHost.Entry.Result(id, raw?.optString("error")?.ifEmpty { null } ?: content(u), true)) + else -> listOf(entry) + } + } + + private fun content(u: JSONObject): String { + val list = u.optJSONArray("content") ?: return "" + return (0 until list.length()).mapNotNull { list.optJSONObject(it)?.optJSONObject("content")?.optString("text") }.joinToString("\n") } } - private fun text(part: JSONObject?, entry: (String) -> AgentHost.Entry) = - part?.optString("text")?.trim()?.takeIf { it.isNotEmpty() }?.let { listOf(entry(it)) }.orEmpty() + private fun toolName(name: String) = name.replaceFirstChar { it.uppercase() }.ifEmpty { "Tool" } - private fun tool(part: JSONObject): List { - val id = part.optString("callID").ifEmpty { part.optString("id") } - val state = part.optJSONObject("state") ?: JSONObject() - val input = state.optJSONObject("input") ?: JSONObject() + private fun tool(id: String, name: String, input: JSONObject): AgentHost.Entry.Used { val path = input.optString("filePath") - val (name, detail, full) = when (val tool = part.optString("tool")) { - "bash" -> Triple("Bash", firstLine(input.optString("command")), input.optString("command")) - "edit" -> Triple("Edit", path, path + "\n" + lineDiff(input.optString("oldString"), input.optString("newString"))) - "write" -> Triple("Write", path, path + "\n" + lineDiff("", input.optString("content"))) - "todowrite" -> Triple("TodoWrite", "", todos(input.optJSONArray("todos"))) - else -> Triple(tool.replaceFirstChar { it.uppercase() }.ifEmpty { "Tool" }, detail(input), input.toString(2)) - } - val used = AgentHost.Entry.Used(id, name, detail, full) - return when (state.optString("status")) { - "completed" -> { - val exit = state.optJSONObject("metadata")?.opt("exit") - listOf(used, AgentHost.Entry.Result(id, state.optString("output"), exit is Number && exit.toInt() != 0)) - } - "error" -> listOf(used, AgentHost.Entry.Result(id, state.optString("error"), true)) - else -> listOf(used) + return when (name) { + "bash" -> AgentHost.Entry.Used(id, "Bash", firstLine(input.optString("command")), input.optString("command")) + "edit" -> AgentHost.Entry.Used(id, "Edit", path, path + "\n" + lineDiff(input.optString("oldString"), input.optString("newString"))) + "write" -> AgentHost.Entry.Used(id, "Write", path, path + "\n" + lineDiff("", input.optString("content"))) + "todowrite" -> AgentHost.Entry.Used(id, "TodoWrite", "", todos(input.optJSONArray("todos"))) + else -> AgentHost.Entry.Used(id, toolName(name), detail(input), if (input.length() == 0) "" else input.toString(2)) } } @@ -584,6 +1031,13 @@ object OpenCode : AgentHarness { @VisibleForTesting internal fun firstLine(text: String) = text.lineSequence().first().take(160) +/** + * [command] with its stderr in a log of its own under /root/.cache/droiddeck. The agent's stdout and stderr share one + * pipe, and a log line written in the middle of a long JSON line would make that line unreadable. + */ +internal fun withoutStderr(log: String, command: List) = + listOf("/bin/sh", "-c", "mkdir -p /root/.cache/droiddeck; exec \"\$@\" 2>/root/.cache/droiddeck/$log.log", "sh") + command + private const val DIFF_CONTEXT = 2 /** @@ -606,6 +1060,18 @@ internal fun lineDiff(old: String, new: String): String { }.joinToString("\n") } +/** A unified diff's hunks without their headers; an added or deleted file's diff is its whole content. */ +@VisibleForTesting +internal fun patchLines(diff: String, kind: String): String { + val lines = diff.removeSuffix("\n").lines() + when (kind) { + "add" -> return lines.joinToString("\n") { "+$it" } + "delete" -> return lines.joinToString("\n") { "-$it" } + } + val start = lines.indexOfFirst { it.startsWith("@@") } + return (if (start < 0) lines else lines.drop(start)).filter { it.isNotEmpty() && !it.startsWith("@@") && !it.startsWith("\\") }.joinToString("\n") +} + private val SHELL_WRAPPER = Regex("^/bin/(?:ba)?sh -l?c '(.*)'$", RegexOption.DOT_MATCHES_ALL) /** Codex runs each command as `/bin/bash -lc ''`; the command is what the user wants to read. */ diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt index de00d5ce73..80667afef0 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentHost.kt @@ -21,8 +21,8 @@ import java.nio.file.Files /** * The launcher's agent: a coding agent CLI ([AgentHarness]) from the Linux userland, run headless - * outside any game or desktop session: one process per turn, or for a CLI that takes its messages over - * stdin one process kept open between turns, so background work can start a turn of its own. Conversations are kept on disk + * outside any game or desktop session as one process that takes its messages over stdin and stays open + * between turns, so background work can start a turn of its own. Conversations are kept on disk * ([AgentChats]), so a restart (a Lab build, a crash) continues the same one. */ object AgentHost { @@ -56,6 +56,9 @@ object AgentHost { /** A message typed while the agent was working, sent when the turn ends. */ data class Queued(val text: String, val files: List) + /** A tool call the CLI waits on the user to allow; [payload] is what its protocol needs to answer. */ + data class Approval(val id: String, val tool: String, val detail: String, val input: String, val payload: String = "") + enum class State { MISSING, IDLE, WORKING } private const val TAG = "AgentHost" @@ -94,6 +97,12 @@ object AgentHost { private set var plan by mutableStateOf(false) private set + /** The chosen [AgentHarness.Permission] of [harness]; asking first until the user picks another. */ + var permission by mutableStateOf(AgentHarness.ASK) + private set + /** Tool calls of the running turn that wait for the user, oldest first. */ + val approvals = mutableStateListOf() + private var approvalNoticed = false var chat by mutableStateOf(null) private set /** A reply finished since the conversation was last on screen. */ @@ -123,7 +132,9 @@ object AgentHost { var lab by mutableStateOf(null) private set - private class Turn(val process: Process, val pid: Int, val stdin: java.io.OutputStream? = null) { + private class Turn(val process: Process, val pid: Int, val protocol: AgentProtocol, val stdin: java.io.OutputStream) { + fun write(lines: List) = synchronized(this) { stdin.apply { lines.forEach { write((it + "\n").toByteArray()) }; flush() } } + var writingGeneration: Int? = null var exitStatus: Int? = null var costs: AgentCostTracker? = null @@ -171,6 +182,8 @@ object AgentHost { model = prefs(app).getString(modelKey(harness), null) effort = prefs(app).getString(effortKey(harness), null)?.takeIf { it in harness.efforts } plan = prefs(app).getBoolean(PLAN_KEY, false) + permission = prefs(app).getString(permissionKey(harness), null)?.takeIf { id -> harness.permissions.any { it.id == id } } + ?: harness.permissions.first().id limits = decodeLimits(prefs(app).getString(limitsKey(harness), null)) available = LinuxRuntime.hasRootfs(app) installed = harness.files.all { guestFileExists(app, it) } @@ -273,6 +286,42 @@ object AgentHost { prefs(context).edit().putBoolean(PLAN_KEY, on).apply() } + /** Kept per CLI, for every conversation; the CLI process restarts with it on the next message. */ + fun choosePermission(context: Context, id: String) { + if (harness.permissions.none { it.id == id }) return + permission = id + prefs(context).edit().putString(permissionKey(harness), id).apply() + } + + /** Lets the CLI run [approval]'s tool call, or tells it the user said no. */ + fun answer(context: Context, approval: Approval, allow: Boolean) { + if (!approvals.remove(approval)) return + val running = turn ?: session ?: return + val line = running.protocol.answer(approval, allow) + val app = context.applicationContext + val current = harness + Thread({ runCatching { running.write(listOf(line)) }.onFailure { lost(app, running, current, it) } }, "agent-approval").start() + approvalsChanged(app) + } + + /** The approval notice goes once nothing waits on the user any more. */ + private fun approvalsChanged(app: Context) { + if (approvals.isNotEmpty() || !approvalNoticed) return + approvalNoticed = false + AgentNotice.clear(app) + } + + /** + * A line the CLI waits for could not be written, so it would wait forever: its process ends, which ends + * the turn, and the chat says why. A request that may have reached it is not sent again. + */ + private fun lost(app: Context, from: Turn, current: AgentHarness, error: Throwable) { + Log.w(TAG, "could not write to ${current.name}", error) + main.post { if (turn === from || session === from) record(app, Entry.Notice("Could not write to ${current.name}: ${error.message ?: error.javaClass.simpleName}")) } + AgentProcesses.killTree(from.pid) + from.process.destroy() + } + fun models(context: Context) = harness.models(LinuxRuntime.rootDir(context.applicationContext)) /** Sends [text] now, or after the current turn when the agent is working. */ @@ -303,19 +352,20 @@ object AgentHost { val current = harness val prompt = AgentAttachments.prompt(message, attached) turnPlanned = plan && current.plans - val options = AgentHarness.Options(model, turnPlanned, BRIEF, effort) - val command = current.turn(prompt, conversation, options) - val line = current.input(prompt) - val key = "${current.id}|$id|$model|$turnPlanned|$effort" + val options = AgentHarness.Options(model, turnPlanned, BRIEF, effort, permission, workspace(app)) + val key = "${current.id}|$id|$model|$turnPlanned|$effort|$permission" + val resumed = conversation background = false + approvals.clear() + approvalsChanged(app) val kept = session - if (kept != null && line != null && sessionKey == key && kept.process.isAlive) { + if (kept != null && sessionKey == key && kept.process.isAlive) { main.removeCallbacks(reap) turn = kept kept.writingGeneration = gen kept.clearingCosts = prompt == "/clear" Thread({ - val written = runCatching { synchronized(kept) { kept.stdin?.apply { write((line + "\n").toByteArray()); flush() } != null } }.getOrDefault(false) + val written = runCatching { kept.write(kept.protocol.input(prompt, resumed, options, started = false)) }.isSuccess // The process died between turns: the same message goes to a new one, which resumes the conversation. main.post { if (kept.writingGeneration == gen) kept.writingGeneration = null @@ -323,7 +373,7 @@ object AgentHost { if (!written) { dropSession() turn = null - spawn(app, gen, current, current.turn(prompt, conversation, options), line, key) + spawn(app, gen, current, prompt, resumed, options, key) } else kept.exitStatus?.let { processExited(app, kept, current, it) } } } @@ -331,12 +381,14 @@ object AgentHost { return } dropSession() - spawn(app, gen, current, command, line, key) + spawn(app, gen, current, prompt, resumed, options, key) } - private fun spawn(app: Context, gen: Int, current: AgentHarness, command: List, line: String?, key: String) { - val workdir = workspace(app) - var threadConversation = conversation + private fun spawn(app: Context, gen: Int, current: AgentHarness, prompt: String, resumed: String?, options: AgentHarness.Options, key: String) { + val workdir = options.workdir + val command = current.turn(prompt, resumed, options) + val protocol = current.protocol() + var threadConversation = resumed Thread({ runCatching { current.prepare(LinuxRuntime.rootDir(app)) } runCatching { AgentSetup.installHelpers(app) } @@ -349,17 +401,18 @@ object AgentHost { main.post { if (generation == gen) finish(app, e.message ?: "could not start") } return@Thread } - val started = Turn(child, AgentProcesses.pidOf(child), if (line != null) child.outputStream else null).apply { - if (current === ClaudeCode && line != null) costs = AgentCostTracker() + val started = Turn(child, AgentProcesses.pidOf(child), protocol, child.outputStream).apply { + if (current === ClaudeCode) costs = AgentCostTracker() } OrphanReaper.keep(started.pid) main.post { if (generation == gen && state == State.WORKING && turn == null) { turn = started - if (line != null) { session = started; sessionKey = key } + session = started + sessionKey = key } else AgentProcesses.killTree(started.pid) } - if (line != null) runCatching { child.outputStream.apply { write((line + "\n").toByteArray()); flush() } } else child.outputStream.close() + runCatching { started.write(protocol.input(prompt, resumed, options, started = true)) }.onFailure { lost(app, started, current, it) } val raw = runCatching { val log = File(app.filesDir, TURN_LOG).apply { parentFile?.mkdirs() } log.renameTo(File(app.filesDir, "$TURN_LOG.1")) @@ -368,7 +421,8 @@ object AgentHost { runCatching { child.inputStream.bufferedReader().forEachLine { output -> runCatching { raw?.apply { write(output); newLine(); flush() } } - val parsed = current.parse(output) ?: return@forEachLine + val parsed = protocol.parse(output) ?: return@forEachLine + if (parsed.reply.isNotEmpty()) runCatching { started.write(parsed.reply) }.onFailure { lost(app, started, current, it) } parsed.conversation?.let { threadConversation = it } val done = parsed.entries.any { it is Entry.Finished } val event = if (!done) parsed else runCatching { current.usage(LinuxRuntime.rootDir(app), threadConversation) }.getOrNull() @@ -410,7 +464,7 @@ object AgentHost { if (background && state == State.WORKING) finish(app, event.backgroundError, usage = event.usage?.let { from.costs?.perTurn(it) ?: it }) return } - val content = event.text != null || event.thinking != null || event.entries.any { it !is Entry.Finished } + val content = event.text != null || event.thinking != null || event.approval != null || event.entries.any { it !is Entry.Finished } if (content && state == State.IDLE && session === from) { main.removeCallbacks(reap) background = true @@ -428,10 +482,17 @@ object AgentHost { from.clearingCosts = false } val applied = if (finished != null && state == State.WORKING && event.usage != null) - event.copy(usage = from.costs?.perTurn(event.usage) ?: event.usage) else event + event.copy(usage = turnCost(from.costs?.perTurn(event.usage) ?: event.usage)) else event apply(app, applied) } + /** A CLI that reports the conversation's whole cost spent what this chat has not recorded yet. */ + private fun turnCost(usage: Usage): Usage { + if (!harness.sessionCost) return usage + val recorded = entries.sumOf { (it as? Entry.Finished)?.usage?.costUsd ?: 0.0 } + return usage.copy(costUsd = (usage.costUsd - recorded).coerceAtLeast(0.0)) + } + /** Ends the CLI process kept between turns, and with it whatever it still runs in the background. */ private fun dropSession() { main.removeCallbacks(reap) @@ -529,6 +590,15 @@ object AgentHost { } event.text?.let { live += it } event.thinking?.let { liveThinking += it } + event.resolved?.let { id -> + approvals.removeAll { it.id == id } + approvalsChanged(app) + } + event.approval?.takeIf { a -> state == State.WORKING && approvals.none { it.id == a.id } }?.let { + approvals += it + approvalNoticed = true + AgentNotice.post(app, AgentNotice.Kind.APPROVAL, listOf(it.tool, it.detail).filter { s -> s.isNotEmpty() }.joinToString(": ")) + } event.context?.let { context = it } event.window?.let { window = it } event.limits?.let { reported -> @@ -549,6 +619,8 @@ object AgentHost { private fun finish(app: Context, error: String?, stopped: Boolean = false, usage: Usage? = null) { if (state != State.WORKING) return turn = null + approvals.clear() + approvalsChanged(app) val answeredTask = background background = false main.removeCallbacks(reap) @@ -762,6 +834,7 @@ object AgentHost { private const val LINGER_MS = 20 * 60_000L private fun modelKey(harness: AgentHarness) = "model_${harness.id}" + private fun permissionKey(harness: AgentHarness) = "permission_${harness.id}" private fun limitsKey(harness: AgentHarness) = "limits_${harness.id}" @VisibleForTesting diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentNotice.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentNotice.kt index edba77a0c8..22203ace48 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentNotice.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentNotice.kt @@ -16,10 +16,10 @@ internal object AgentNotice { private const val CHANNEL_ID = "agent_done" private const val NOTIFICATION_ID = 4108 - enum class Kind { DONE, FAILED, QUESTION } + enum class Kind { DONE, FAILED, QUESTION, APPROVAL } fun post(context: Context, kind: Kind, text: String) { - if (onScreen(context)) return + if (onScreen(context, kind)) return val manager = context.getSystemService(NotificationManager::class.java) ?: return manager.createNotificationChannel(NotificationChannel(CHANNEL_ID, context.getString(R.string.agent_done_channel), NotificationManager.IMPORTANCE_DEFAULT)) val open = PendingIntent.getActivity(context, 2, @@ -31,6 +31,7 @@ internal object AgentNotice { Kind.DONE -> R.string.agent_done Kind.FAILED -> R.string.agent_done_failed Kind.QUESTION -> R.string.agent_done_question + Kind.APPROVAL -> R.string.agent_done_approval }) runCatching { manager.notify(NOTIFICATION_ID, Notification.Builder(context, CHANNEL_ID) @@ -49,9 +50,9 @@ internal object AgentNotice { context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID) } - /** The chat in a DroidDeck window in front, or the pet, which shows the reply in its own bubble. */ - private fun onScreen(context: Context): Boolean { - if (AgentPet.floating) return true + /** The chat in a DroidDeck window in front, or the pet, which shows the reply in its own bubble but has no way to answer an approval. */ + private fun onScreen(context: Context, kind: Kind): Boolean { + if (AgentPet.floating && kind != Kind.APPROVAL) return true val state = ActivityManager.RunningAppProcessInfo().also { ActivityManager.getMyMemoryState(it) } return AgentPet.agentOnScreen > 0 && state.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND } diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt index a4107fa287..e917e36605 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentSetup.kt @@ -27,25 +27,52 @@ object AgentSetup { val detail = mutableStateMapOf() var runtimeInstalled by mutableStateOf(true) private set - /** The harness has a key from its [AgentHarness.keyPage] saved; signed in without one means its free models. */ - var keySaved by mutableStateOf(false) + /** Ids of the harness's [AgentHarness.providers] with a key saved; signed in without one means its free models. */ + var keys by mutableStateOf(emptySet()) private set + /** The provider and custom server picked in the key field, kept while a save is checked. */ + var provider by mutableStateOf(null) + var server by mutableStateOf("") /** Saves a pasted key for a harness that signs in with one, then checks the sign-in again. */ - fun saveKey(context: Context, key: String) = signInLocally(context) { harness, root -> harness.saveKey(root, key) } + fun saveKey(context: Context, provider: AgentHarness.Provider, key: String, endpoint: String? = null) = signInLocally(context) { harness, root -> + harness.saveKey(root, provider, key, endpoint) { url, token -> fetch(context.applicationContext, url, token) } + } + + fun removeKey(context: Context, provider: AgentHarness.Provider) = signInLocally(context) { harness, root -> harness.removeKey(root, provider) } + + /** A GET from the userland, which reaches the LAN servers the app's own cleartext policy does not. */ + private fun fetch(app: Context, url: String, token: String?): String { + // The key goes in on stdin, so it is never in a command line. + val process = AgentHost.guest(app, listOf("curl", "-fsSL", "--max-time", "20", "-H", "@-", url), connectAdb = false).start() + process.outputStream.bufferedWriter().use { if (token != null) it.write("Authorization: Bearer $token\n") } + val output = process.inputStream.bufferedReader().readText() + check(process.waitFor(30, TimeUnit.SECONDS) && process.exitValue() == 0) { output.trim().lines().lastOrNull()?.takeIf { it.isNotEmpty() } ?: "Cannot reach $url" } + return output + } fun useFree(context: Context) = signInLocally(context) { harness, root -> harness.useFree(root) } + private val signInLock = Any() + private fun signInLocally(context: Context, write: (AgentHarness, File) -> Unit) { val app = context.applicationContext val harness = AgentHost.harness set(Step.SIGN_IN, Status.WORKING) Thread({ - val result = runCatching { write(harness, LinuxRuntime.rootDir(app)) } + // Each write reads the files the one before it left, including across a save's model request. + val result = synchronized(signInLock) { runCatching { write(harness, LinuxRuntime.rootDir(app)) } } main.post { - status[Step.SIGN_IN] = Status.UNKNOWN - result.exceptionOrNull()?.let { detail[Step.SIGN_IN] = it.message ?: "failed" } - check(app) + // A failure stays on the row with the key field open, since the next check would clear it. + val error = result.exceptionOrNull() + if (error != null) { + status[Step.SIGN_IN] = Status.FAILED + detail[Step.SIGN_IN] = error.message ?: "failed" + } else { + status[Step.SIGN_IN] = Status.UNKNOWN + detail.remove(Step.SIGN_IN) + check(app) + } } }, "agent-sign-in").start() } @@ -75,7 +102,7 @@ object AgentSetup { if (!runtimeInstalled) return AgentHost.refresh(app) val harness = AgentHost.harness - keySaved = harness.hasKey(LinuxRuntime.rootDir(app)) + keys = harness.keys(LinuxRuntime.rootDir(app)) val probes = mutableListOf>>() for (step in Step.entries) if (status[step] != Status.WORKING) { when (step) { @@ -102,10 +129,15 @@ object AgentSetup { fun runsAsRoot(step: Step) = step == Step.INSTALL /** Runs [step]'s action. [CONNECTION] is the app's own pairing flow, so the caller opens it. */ - fun run(context: Context, step: Step) { + fun run(context: Context, step: Step) = run(context, step, null) + + /** Opens the page where a provider's key is made, as the sign-in of a harness that takes pasted keys. */ + fun openKeyPage(context: Context, page: String) = run(context, Step.SIGN_IN, listOf("/root/.local/bin/android-open", page)) + + private fun run(context: Context, step: Step, override: List?) { val app = context.applicationContext val harness = AgentHost.harness - val command = when (step) { + val command = override ?: when (step) { Step.CONNECTION -> return Step.INSTALL -> { listOf("sh", "-c", "set -e; export DEBIAN_FRONTEND=noninteractive; " + diff --git a/app/src/main/java/com/droiddeck/launcher/agent/AgentTab.kt b/app/src/main/java/com/droiddeck/launcher/agent/AgentTab.kt index b779288f3e..7f7ee12ab4 100644 --- a/app/src/main/java/com/droiddeck/launcher/agent/AgentTab.kt +++ b/app/src/main/java/com/droiddeck/launcher/agent/AgentTab.kt @@ -1,23 +1,9 @@ package com.droiddeck.launcher.agent -import android.content.Context -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.setValue -import com.droiddeck.launcher.session.SessionPrefs +import com.droiddeck.launcher.ui.NavTabs object AgentTab { - var shown by mutableStateOf(false) - private set + val shown: Boolean get() = "agent" !in NavTabs.hidden val visible: Boolean get() = shown && AgentHost.available - - fun load(context: Context) { - shown = SessionPrefs.agentTab(context) - } - - fun set(context: Context, show: Boolean) { - shown = show - SessionPrefs.setAgentTab(context, show) - } } diff --git a/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java b/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java index 6aa7d13456..53a0a6aacf 100644 --- a/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java +++ b/app/src/main/java/com/droiddeck/launcher/audio/PulseAudioComponent.java @@ -16,8 +16,10 @@ import java.nio.file.Files; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.concurrent.TimeUnit; +import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.IntConsumer; import java.util.function.IntSupplier; +import java.util.function.Supplier; public class PulseAudioComponent extends SessionPart { private static final String TAG = "PulseAudio"; @@ -38,6 +40,7 @@ public class PulseAudioComponent extends SessionPart { private long generation; private long launches; private final IntConsumer terminate; + final ReentrantReadWriteLock commands = new ReentrantReadWriteLock(); HostLifecycle(IntConsumer terminate) { this.terminate = terminate; @@ -54,11 +57,27 @@ public class PulseAudioComponent extends SessionPart { pid = -1; } - synchronized boolean launch(long expected, IntSupplier launch) { - if (expected != generation) return false; - launches++; - pid = launch.getAsInt(); - return true; + boolean launch(long expected, IntSupplier launch) { + commands.writeLock().lock(); + try { + synchronized (this) { + if (expected != generation) return false; + launches++; + pid = launch.getAsInt(); + return true; + } + } finally { + commands.writeLock().unlock(); + } + } + + T command(long token, Supplier command) { + commands.readLock().lock(); + try { + return live(token) ? command.get() : null; + } finally { + commands.readLock().unlock(); + } } synchronized boolean current(long expected) { @@ -218,13 +237,13 @@ public class PulseAudioComponent extends SessionPart { String loadedAs = null; for (int attempt = 1; attempt <= 5 && loadedAs == null && host.live(token); attempt++) { try { Thread.sleep(2000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); return; } - if (pactlFor(token, "load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", "performance_mode=1", - "adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls) != null - && pactlFor(token, "set-default-sink", "DirectAudio") != null) { + if (pactlOk(token, "load-module", "module-directaudio-native-sink", "sink_name=DirectAudio", "performance_mode=1", + "adaptive=1", "decay=0", "limiter=1", "watchdog=1", "volume=1.0", "control_dir=" + deviceControls) + && pactlOk(token, "set-default-sink", "DirectAudio")) { loadedAs = "DirectAudio on attempt " + attempt; - } else if (pactlFor(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink", - "performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) != null - && pactlFor(token, "set-default-sink", "AAudioSink") != null) { + } else if (pactlOk(token, "load-module", "module-aaudio-sink", "sink_name=AAudioSink", + "performance_mode=" + (attempt == 1 ? "1" : "0"), "adaptive=1", "volume=1.0", "control_dir=" + deviceControls) + && pactlOk(token, "set-default-sink", "AAudioSink")) { loadedAs = "the plain AAudio sink (AAudioSink) on attempt " + attempt; } } @@ -248,14 +267,24 @@ public class PulseAudioComponent extends SessionPart { } private String pactlFor(long token, String... args) { - return host.live(token) ? pactl(args) : null; + return host.command(token, () -> pactl(true, args)); } - /** Runs pactl against this daemon; its stdout, or null when it failed or timed out. */ - private String pactl(String... args) { + private boolean pactlOk(long token, String... args) { + return host.command(token, () -> pactl(false, args)) != null; + } + + private static void reap(java.lang.Process process) throws InterruptedException { + process.destroyForcibly(); + process.waitFor(2, TimeUnit.SECONDS); + } + + /** Runs pactl against this daemon; its stdout when captured (empty otherwise), or null when it failed or timed out. */ + private String pactl(boolean capture, String... args) { File pactl = new File(workingDir, "pactl"); if (!pactl.isFile() || host.pid <= 1) return null; java.lang.Process process = null; + File output = null; try { File modules = new File(workingDir, "modules/arm64"); ArrayList cmd = new ArrayList<>(); @@ -268,29 +297,33 @@ public class PulseAudioComponent extends SessionPart { builder.environment().put("HOME", workingDir.getAbsolutePath()); builder.environment().put("TMPDIR", workingDir.getAbsolutePath()); builder.environment().put("PULSE_SERVER", "unix:" + socket().getAbsolutePath()); - process = builder.start(); - String output; - try (InputStream in = process.getInputStream(); - java.io.ByteArrayOutputStream outStream = new java.io.ByteArrayOutputStream()) { - byte[] buf = new byte[4096]; - int n; - while ((n = in.read(buf)) != -1) { - outStream.write(buf, 0, n); - } - output = outStream.toString(java.nio.charset.StandardCharsets.UTF_8.name()); + if (capture) { + output = File.createTempFile("pactl", ".out", workingDir); + builder.redirectOutput(output); + } else { + builder.redirectOutput(new File("/dev/null")); } + process = builder.start(); if (!process.waitFor(5, TimeUnit.SECONDS)) { - process.destroyForcibly(); + reap(process); return null; } - return process.exitValue() == 0 ? output : null; + if (process.exitValue() != 0) return null; + return capture ? new String(Files.readAllBytes(output.toPath()), java.nio.charset.StandardCharsets.UTF_8) : ""; } catch (InterruptedException e) { Thread.currentThread().interrupt(); return null; } catch (Throwable t) { return null; } finally { - if (process != null && process.isAlive()) process.destroyForcibly(); + if (process != null && process.isAlive()) { + try { + reap(process); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } + if (output != null) output.delete(); } } 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 53f152a60b..55e7e61284 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironment.kt @@ -23,6 +23,7 @@ object GameEnvironment { ) fun validName(name: String) = namePattern.matches(name) + fun currentName(name: String) = if (name.startsWith("BL_")) "DD_" + name.removePrefix("BL_") else name fun supported(name: String) = name !in unused && !name.startsWith("BOX64_") && !name.startsWith("BOX86_") fun validValue(value: String) = '\u0000' !in value && value.length <= 8192 fun validScope(scope: String) = scope.isEmpty() || (Regex("[1-9][0-9]*").matches(scope) && scope.toLongOrNull()?.let { it in 1..4294967295L } == true) @@ -97,14 +98,14 @@ object GameEnvironment { val syncBackends = listOf(SessionPrefs.SYNC_NTSYNC, SessionPrefs.SYNC_FSYNC, SessionPrefs.SYNC_ESYNC, SessionPrefs.SYNC_WINESERVER) - val syncKeys = listOf("BL_SYNC", "BL_FSYNC_FIRST", "BL_SYNC_FALLBACK", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC") + val syncKeys = listOf("DD_SYNC", "DD_FSYNC_FIRST", "DD_SYNC_FALLBACK", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC") fun syncEnvironment(backend: String): Map { require(backend in syncBackends) { "unknown sync $backend" } return buildMap { - put("BL_SYNC", if (backend == SessionPrefs.SYNC_NTSYNC) "1" else "0") - put("BL_FSYNC_FIRST", if (backend == SessionPrefs.SYNC_FSYNC) "1" else "0") - put("BL_SYNC_FALLBACK", if (backend == SessionPrefs.SYNC_WINESERVER) "0" else "1") + put("DD_SYNC", if (backend == SessionPrefs.SYNC_NTSYNC) "1" else "0") + put("DD_FSYNC_FIRST", if (backend == SessionPrefs.SYNC_FSYNC) "1" else "0") + put("DD_SYNC_FALLBACK", if (backend == SessionPrefs.SYNC_WINESERVER) "0" else "1") if (backend == SessionPrefs.SYNC_FSYNC) put("PROTON_NO_ESYNC", "1") } } 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 5958c5e99b..ab7fed7c27 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/GameEnvironmentOptions.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/GameEnvironmentOptions.kt @@ -20,7 +20,7 @@ object GameEnvironmentOptions { Option("PROTON_NO_NTSYNC", "1", R.string.game_env_no_ntsync, Type.TOGGLE, listOf("0", "1")), Option("PROTON_NO_ESYNC", "1", R.string.game_env_no_esync, Type.TOGGLE, listOf("0", "1")), Option("PROTON_NO_FSYNC", "1", R.string.game_env_no_fsync, Type.TOGGLE, listOf("0", "1")), - Option("BL_FSYNC_FIRST", "1", R.string.game_env_fsync_first, Type.TOGGLE, listOf("0", "1")), + Option("DD_FSYNC_FIRST", "1", R.string.game_env_fsync_first, Type.TOGGLE, listOf("0", "1")), Option("DXVK_HUD", "fps", R.string.game_env_hud, Type.MULTIPLE, listOf("scale=0.5", "scale=0.7", "opacity=0.5", "opacity=0.7", "devinfo", "fps", "frametimes", "submissions", "drawcalls", "pipelines", "descriptors", "memory", "gpuload", "version", "api", "cs", "compiler", "samplers")), Option("DXVK_CONFIG", "dxvk.maxFrameRate = 60", R.string.game_env_dxvk_config, Type.TEXT), Option("VKD3D_FRAME_RATE", "60", R.string.game_env_vkd3d_limit, Type.NUMBER), diff --git a/app/src/main/java/com/droiddeck/launcher/core/SessionLogCapture.kt b/app/src/main/java/com/droiddeck/launcher/core/SessionLogCapture.kt index 89ec374d6d..650a6b8d4d 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/SessionLogCapture.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/SessionLogCapture.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.core +import android.content.Context import android.os.Process import android.util.Log import java.io.BufferedWriter @@ -113,7 +114,17 @@ object SessionLogCapture { } } - fun dumpMemoryPressure(target: File) { + internal const val LMKD_COMMAND = "logcat -d -b main,events -v threadtime -s lowmemorykiller:D killinfo:I" + + " | grep -v -E 'pgskip|zoneinfo_parse|polling check|thrashing:' | tail -n 120" + + private fun lowMemoryKiller(context: Context?): String = when { + context == null -> "(not captured)\n" + !WirelessAdbFix.hasSavedPairing(context) -> "(not captured: pair DroidDeck with Wireless debugging in Settings > Diagnostics)\n" + else -> runCatching { WirelessAdbFix.shell(context, LMKD_COMMAND) } + .fold({ it.ifBlank { "(no lmkd lines in the log)\n" } }, { "(not captured: ${it.message})\n" }) + } + + fun dumpMemoryPressure(target: File, context: Context? = null) { var temporary: File? = null try { val staged = File.createTempFile(target.name, ".part", target.parentFile).also { temporary = it } @@ -150,7 +161,8 @@ object SessionLogCapture { body.isNotEmpty() -> body else -> "(no readable events were returned)\n" } + - "\n/proc/pressure/memory:\n$pressure\n/proc/meminfo:\n$meminfo\n/sys/class/kgsl/kgsl/page_alloc:\n$gpu" + "\n/proc/pressure/memory:\n$pressure\n/proc/meminfo:\n$meminfo\n/sys/class/kgsl/kgsl/page_alloc:\n$gpu" + + "\nAndroid's low memory killer (lmkd), read over Wireless debugging:\n${lowMemoryKiller(context)}" ) Files.move( staged.toPath(), target.toPath(), diff --git a/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt b/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt index 84f87cca13..cd10300f4f 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/SteamIntegration.kt @@ -37,7 +37,7 @@ object SteamIntegration { locationOn = WifiDiscovery.locationEnabled(context), brightness = Settings.System.canWrite(context), home = HomeApp.isDefault(context), - shortcuts = shortcutsEnabled(context), + shortcuts = shortcutsEnabled(context) && shortcutsCurrent(context), shortcutsRestricted = restrictedSettings(context), suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false), ) @@ -61,6 +61,10 @@ object SteamIntegration { return enabled.split(':').any { ComponentName.unflattenFromString(it.trim()) == shortcutsComponent } } + @Suppress("DEPRECATION") + fun shortcutsCurrent(context: Context): Boolean = + runCatching { context.packageManager.getPackageInfo(Relay.PACKAGE, 0).versionCode }.getOrDefault(0) >= Relay.VERSION + fun shortcutsListed(context: Context): Boolean = context.getSystemService(android.view.accessibility.AccessibilityManager::class.java) ?.installedAccessibilityServiceList.orEmpty() diff --git a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt index 784b39d748..5c8b32f7ba 100644 --- a/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt +++ b/app/src/main/java/com/droiddeck/launcher/core/WirelessAdbFix.kt @@ -235,6 +235,17 @@ object WirelessAdbFix { fun hasSavedPairing(context: Context): Boolean = savedConnection(context.applicationContext) != null + fun savedPairingIsLocal(context: Context): Boolean = savedConnection(context.applicationContext)?.host + ?.let { host -> + // Unlike isLocalAddress, an address that cannot be matched to this device's own counts as remote. + runCatching { + val address = InetAddress.getByName(host) + address.isLoopbackAddress || NetworkInterface.getNetworkInterfaces().toList().any { network -> + network.inetAddresses.toList().any { it.address.contentEquals(address.address) } + } + }.getOrDefault(false) + } == true + fun clearCachedApps(context: Context) { shell(context, "am kill-all") } 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 9f534b39be..affd27293d 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/AppFilesProvider.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/AppFilesProvider.kt @@ -13,6 +13,7 @@ import android.provider.DocumentsContract.Root import android.provider.DocumentsProvider import android.webkit.MimeTypeMap import com.droiddeck.launcher.R +import com.droiddeck.launcher.session.SessionPrefs import java.io.File import java.io.FileNotFoundException import java.io.IOException @@ -26,11 +27,21 @@ import java.nio.file.attribute.BasicFileAttributes class AppFilesProvider : DocumentsProvider() { private lateinit var base: File private lateinit var baseCanonical: String + private lateinit var privatePaths: List override fun attachInfo(context: Context, info: ProviderInfo) { super.attachInfo(context, info) base = context.dataDir baseCanonical = base.canonicalPath + // The wireless ADB pairing identity, preferences, store logins and Steam's saved login stay app-only. + privatePaths = listOf( + context.noBackupFilesDir, + File(base, "shared_prefs"), + context.getDatabasePath("x").parentFile!!, + File(context.filesDir, "stores"), + File(SessionPrefs.steamRoot(context, "arm64"), "config"), + File(SessionPrefs.steamRoot(context, "x86_64"), "config"), + ).flatMap { listOf(it.absoluteFile.normalize().path, runCatching { it.canonicalPath }.getOrDefault(it.path)) }.distinct() } override fun onCreate() = true @@ -74,6 +85,7 @@ class AppFilesProvider : DocumentsProvider() { var file = File(parent, name) var n = 2 while (file.exists()) file = File(parent, "$name (${n++})") + if (isPrivate(file)) throw FileNotFoundException("could not create ${file.path}") val made = try { if (mimeType == Document.MIME_TYPE_DIR) file.mkdir() else file.createNewFile() } catch (e: IOException) { @@ -85,7 +97,7 @@ class AppFilesProvider : DocumentsProvider() { override fun deleteDocument(documentId: String) { val file = fileFor(documentId) - if (file.canonicalPath == baseCanonical) throw FileNotFoundException("the app folder itself is not deleted") + if (file.canonicalPath == baseCanonical || holdsPrivate(file)) throw FileNotFoundException("$documentId holds the app's private files") try { deleteTree(file.toPath()) } catch (e: IOException) { @@ -116,17 +128,19 @@ class AppFilesProvider : DocumentsProvider() { override fun renameDocument(documentId: String, displayName: String): String { val file = fileFor(documentId) + if (holdsPrivate(file)) throw FileNotFoundException("$documentId holds the app's private files") val target = File(file.parentFile, displayName.substringAfterLast('/')) - if (target.exists() || !file.renameTo(target)) throw FileNotFoundException("could not rename $documentId") + if (target.exists() || isPrivate(target) || !file.renameTo(target)) throw FileNotFoundException("could not rename $documentId") return target.absolutePath } override fun moveDocument(sourceDocumentId: String, sourceParentDocumentId: String, targetParentDocumentId: String): String { val source = fileFor(sourceDocumentId) + if (holdsPrivate(source)) throw FileNotFoundException("$sourceDocumentId holds the app's private files") val targetParent = fileFor(targetParentDocumentId) if (!targetParent.isDirectory) throw FileNotFoundException("$targetParentDocumentId is not a folder") val target = File(targetParent, source.name) - if (target.exists() || !source.renameTo(target)) throw FileNotFoundException("could not move $sourceDocumentId") + if (target.exists() || isPrivate(target) || !source.renameTo(target)) throw FileNotFoundException("could not move $sourceDocumentId") return target.absolutePath } @@ -163,7 +177,19 @@ class AppFilesProvider : DocumentsProvider() { val abs = f.absoluteFile.normalize().path if (abs != base.absolutePath && !abs.startsWith(base.absolutePath + "/")) return false val real = runCatching { f.canonicalPath }.getOrNull() ?: return false - return real == baseCanonical || real.startsWith("$baseCanonical/") + if (real != baseCanonical && !real.startsWith("$baseCanonical/")) return false + return !isPrivate(f) + } + + private fun isPrivate(f: File): Boolean { + val real = runCatching { f.canonicalPath }.getOrNull() ?: return true + val paths = listOf(f.absoluteFile.normalize().path, real) + return privatePaths.any { p -> paths.any { it == p || it.startsWith("$p/") } } + } + + private fun holdsPrivate(f: File): Boolean { + val paths = listOfNotNull(f.absoluteFile.normalize().path, runCatching { f.canonicalPath }.getOrNull()) + return privatePaths.any { p -> paths.any { p.startsWith("$it/") } } } private fun addRow(result: MatrixCursor, file: File) { @@ -173,7 +199,7 @@ class AppFilesProvider : DocumentsProvider() { } else if (file.canWrite()) { flags = flags or Document.FLAG_SUPPORTS_WRITE } - if (file.absolutePath != base.absolutePath && file.parentFile?.canWrite() == true) { + if (file.absolutePath != base.absolutePath && file.parentFile?.canWrite() == true && !holdsPrivate(file)) { flags = flags or Document.FLAG_SUPPORTS_DELETE or Document.FLAG_SUPPORTS_RENAME or Document.FLAG_SUPPORTS_MOVE or Document.FLAG_SUPPORTS_REMOVE } 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 4da772b1e8..9945083226 100644 --- a/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/files/FileManagerScreen.kt @@ -40,12 +40,10 @@ import androidx.compose.material.icons.filled.ContentPaste import androidx.compose.material.icons.filled.CreateNewFolder import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Folder -import androidx.compose.material.icons.filled.GridView import androidx.compose.material.icons.filled.SdStorage import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Sort import androidx.compose.material.icons.filled.Star -import androidx.compose.material.icons.filled.ViewList import androidx.compose.material.icons.filled.StarBorder import androidx.compose.material.icons.filled.Storage import androidx.compose.material.icons.filled.Smartphone @@ -727,11 +725,15 @@ fun FileManagerScreen( modifier = Modifier .fillMaxWidth() .background(MaterialTheme.colorScheme.surfaceContainer) - .then(if (compactToolbar) Modifier.horizontalScroll(rememberScrollState()) else Modifier) .padding(horizontal = 8.dp, vertical = 6.dp), ) { - IconButton(onClick = { requestNavigation(FileManagerNavigation.UP) }, enabled = canGoUp && !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) { - Icon(Icons.Filled.ArrowBack, stringResource(R.string.fm_back), tint = MaterialTheme.colorScheme.primary) + val upEnabled = canGoUp && !cancellingNavigation + IconButton(onClick = { requestNavigation(FileManagerNavigation.UP) }, enabled = upEnabled, modifier = Modifier.focusGlide(CircleShape)) { + Icon( + Icons.Filled.ArrowBack, + stringResource(R.string.fm_back), + tint = if (upEnabled) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f), + ) } val currentDriveLabel = stringResource(describeLocation(currentDir).driveLabel) @@ -794,113 +796,119 @@ fun FileManagerScreen( Spacer(Modifier.width(4.dp)) - if (showFavorites) { - Text( - text = stringResource(R.string.fm_favorites), - color = MaterialTheme.colorScheme.primary, - fontSize = 13.sp, - fontWeight = FontWeight.SemiBold, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f), - ) - } else if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) { - if (!compactToolbar) Spacer(Modifier.weight(1f)) - } else { - Text( - text = currentDir.name.ifBlank { currentDir.absolutePath }, - color = MaterialTheme.colorScheme.onSurface, - fontSize = 14.sp, - fontWeight = FontWeight.SemiBold, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f), - ) - } - - if (launchDir != null) { - IconButton(onClick = { requestNavigation(FileManagerNavigation.RETURN_TO_START) }, enabled = !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) { - Icon(Icons.AutoMirrored.Filled.KeyboardReturn, stringResource(R.string.fm_return_to_start), tint = MaterialTheme.colorScheme.primary) - } - if (LocalConfiguration.current.screenWidthDp >= 700) Spacer(Modifier.width(56.dp)) - } - - if (!showFavorites) { - if (!pickMode) { - OutlinedButton( - onClick = { showNewFolderDialog = true }, - border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)), - contentPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp), - modifier = Modifier.height(32.dp).focusGlide(CircleShape), - ) { - Icon(Icons.Filled.CreateNewFolder, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp)) - Spacer(Modifier.width(5.dp)) - Text(stringResource(R.string.fm_new_folder), color = MaterialTheme.colorScheme.onBackground, fontSize = 12.sp) - } - } - IconButton(onClick = { - gridView = !gridView - browsePrefs.edit().putBoolean("fmGridView", gridView).apply() - }, modifier = Modifier.focusGlide(CircleShape)) { - Icon( - if (gridView) Icons.Filled.ViewList else Icons.Filled.GridView, - if (gridView) stringResource(R.string.fm_list_view) else stringResource(R.string.fm_grid_view), - tint = MaterialTheme.colorScheme.onSurfaceVariant, + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .weight(1f) + .then(if (compactToolbar) Modifier.horizontalScroll(rememberScrollState()) else Modifier), + ) { + if (showFavorites) { + Text( + text = stringResource(R.string.fm_favorites), + color = MaterialTheme.colorScheme.primary, + fontSize = 13.sp, + fontWeight = FontWeight.SemiBold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f), + ) + } else if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) { + if (!compactToolbar) Spacer(Modifier.weight(1f)) + } else { + Text( + text = currentDir.name.ifBlank { currentDir.absolutePath }, + color = MaterialTheme.colorScheme.onSurface, + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = if (compactToolbar) Modifier.widthIn(max = 140.dp) else Modifier.weight(1f), ) } - IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }, modifier = Modifier.focusGlide(CircleShape)) { - Icon(Icons.Filled.Search, stringResource(R.string.fm_search), tint = MaterialTheme.colorScheme.onSurfaceVariant) - } - Box { - IconButton(onClick = { showSortMenu = true }, modifier = Modifier.focusGlide(CircleShape)) { - Icon(Icons.Filled.Sort, stringResource(R.string.fm_sort), tint = MaterialTheme.colorScheme.onSurfaceVariant) - } - DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) { - listOf("name" to stringResource(R.string.fm_sort_name), "date" to stringResource(R.string.fm_sort_date), "size" to stringResource(R.string.fm_prop_size)) - .forEach { (key, label) -> - DropdownMenuItem( - text = { - Text(if (sortBy == key) "$label ${if (sortDesc) "↓" else "↑"}" else label) - }, - onClick = { - if (sortBy == key) sortDesc = !sortDesc else { sortBy = key; sortDesc = false } - browsePrefs.edit().putString("fmSortBy", sortBy) - .putBoolean("fmSortDesc", sortDesc).apply() - showSortMenu = false - loadDirectory(currentDir, resetScroll = false) - }, - modifier = Modifier.focusGlide(), - ) - } - HorizontalDivider(color = MaterialTheme.colorScheme.outline) - DropdownMenuItem( - text = { Text(if (compactRows) stringResource(R.string.fm_rows_comfortable) else stringResource(R.string.fm_rows_compact)) }, - onClick = { - compactRows = !compactRows - browsePrefs.edit().putBoolean("fmCompactRows", compactRows).apply() - showSortMenu = false - }, - modifier = Modifier.focusGlide(), - ) - DropdownMenuItem( - text = { Text(if (showHidden) stringResource(R.string.fm_hide_hidden) else stringResource(R.string.fm_show_hidden)) }, - onClick = { - showHidden = !showHidden - browsePrefs.edit().putBoolean("fmShowHidden", showHidden).apply() - showSortMenu = false - loadDirectory(currentDir, resetScroll = false) - }, - modifier = Modifier.focusGlide(), - ) - } - } - } - IconButton(onClick = { showFavorites = !showFavorites }, modifier = Modifier.focusGlide(CircleShape)) { - if (showFavorites) { - Icon(Icons.Filled.Star, stringResource(R.string.fm_hide_favorites), tint = MaterialTheme.colorScheme.primary) - } else { - Icon(Icons.Filled.StarBorder, stringResource(R.string.fm_show_favorites), tint = MaterialTheme.colorScheme.onSurfaceVariant) + if (launchDir != null) { + IconButton(onClick = { requestNavigation(FileManagerNavigation.RETURN_TO_START) }, enabled = !cancellingNavigation, modifier = Modifier.focusGlide(CircleShape)) { + Icon(Icons.AutoMirrored.Filled.KeyboardReturn, stringResource(R.string.fm_return_to_start), tint = MaterialTheme.colorScheme.primary) + } + if (LocalConfiguration.current.screenWidthDp >= 700) Spacer(Modifier.width(56.dp)) + } + + if (!showFavorites) { + if (!pickMode) { + OutlinedButton( + onClick = { showNewFolderDialog = true }, + border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)), + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp), + modifier = Modifier.height(32.dp).focusGlide(CircleShape), + ) { + Icon(Icons.Filled.CreateNewFolder, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp)) + Spacer(Modifier.width(5.dp)) + Text(stringResource(R.string.fm_new_folder), color = MaterialTheme.colorScheme.onBackground, fontSize = 12.sp) + } + } + IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }, modifier = Modifier.focusGlide(CircleShape)) { + Icon(Icons.Filled.Search, stringResource(R.string.fm_search), tint = MaterialTheme.colorScheme.onSurfaceVariant) + } + Box { + IconButton(onClick = { showSortMenu = true }, modifier = Modifier.focusGlide(CircleShape)) { + Icon(Icons.Filled.Sort, stringResource(R.string.fm_sort), tint = MaterialTheme.colorScheme.onSurfaceVariant) + } + DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) { + listOf("name" to stringResource(R.string.fm_sort_name), "date" to stringResource(R.string.fm_sort_date), "size" to stringResource(R.string.fm_prop_size)) + .forEach { (key, label) -> + DropdownMenuItem( + text = { + Text(if (sortBy == key) "$label ${if (sortDesc) "↓" else "↑"}" else label) + }, + onClick = { + if (sortBy == key) sortDesc = !sortDesc else { sortBy = key; sortDesc = false } + browsePrefs.edit().putString("fmSortBy", sortBy) + .putBoolean("fmSortDesc", sortDesc).apply() + showSortMenu = false + loadDirectory(currentDir, resetScroll = false) + }, + modifier = Modifier.focusGlide(), + ) + } + HorizontalDivider(color = MaterialTheme.colorScheme.outline) + DropdownMenuItem( + text = { Text(if (gridView) stringResource(R.string.fm_list_view) else stringResource(R.string.fm_grid_view)) }, + onClick = { + gridView = !gridView + browsePrefs.edit().putBoolean("fmGridView", gridView).apply() + showSortMenu = false + }, + modifier = Modifier.focusGlide(), + ) + DropdownMenuItem( + text = { Text(if (compactRows) stringResource(R.string.fm_rows_comfortable) else stringResource(R.string.fm_rows_compact)) }, + onClick = { + compactRows = !compactRows + browsePrefs.edit().putBoolean("fmCompactRows", compactRows).apply() + showSortMenu = false + }, + modifier = Modifier.focusGlide(), + ) + DropdownMenuItem( + text = { Text(if (showHidden) stringResource(R.string.fm_hide_hidden) else stringResource(R.string.fm_show_hidden)) }, + onClick = { + showHidden = !showHidden + browsePrefs.edit().putBoolean("fmShowHidden", showHidden).apply() + showSortMenu = false + loadDirectory(currentDir, resetScroll = false) + }, + modifier = Modifier.focusGlide(), + ) + } + } + } + + IconButton(onClick = { showFavorites = !showFavorites }, modifier = Modifier.focusGlide(CircleShape)) { + if (showFavorites) { + Icon(Icons.Filled.Star, stringResource(R.string.fm_hide_favorites), tint = MaterialTheme.colorScheme.primary) + } else { + Icon(Icons.Filled.StarBorder, stringResource(R.string.fm_show_favorites), tint = MaterialTheme.colorScheme.onSurfaceVariant) + } } } if (!pickMode && onExit != null) { diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt b/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt index 8acbbe18b0..26c9c99813 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/Library.kt @@ -222,16 +222,7 @@ object Library { internal fun concealedSteamApps(root: File): Set { val config = AddedGames.accountConfig(root) ?: return emptySet() - val hidden = runCatching { - val entries = org.json.JSONArray(File(config, "cloudstorage/cloud-storage-namespace-1.json").readText()) - val entry = (0 until entries.length()).map { entries.getJSONArray(it) } - .firstOrNull { it.optString(0) == "user-collections.hidden" }?.optJSONObject(1) - if (entry == null || entry.optBoolean("is_deleted")) emptySet() else { - val collection = org.json.JSONObject(entry.optString("value")) - fun ids(key: String) = collection.optJSONArray(key)?.let { a -> (0 until a.length()).map { a.optLong(it) } }.orEmpty() - ids("added").toSet() - ids("removed").toSet() - } - }.getOrDefault(emptySet()) + val hidden = SteamHidden.read(root) val private = runCatching { PRIVATE_APPS.find(File(config, "localconfig.vdf").readText())?.groupValues?.get(1) ?.split(',')?.mapNotNull { it.trim().toLongOrNull() }?.toSet() @@ -302,6 +293,7 @@ object Library { g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, ADDED, g.gameId, hero = art.hero ?: art.header, lastPlayed = maxOf(lastPlayed, recordedPlay(context, g.gameId)), gameFiles = g.folder, protonPrefix = if (g.source == com.droiddeck.launcher.stores.Store.BATTLENET.id) File(com.droiddeck.launcher.runtime.BattleNet.prefix(context), "pfx").takeIf { it.isDirectory } + else if (g.source == com.droiddeck.launcher.stores.Store.UBISOFT.id) File(com.droiddeck.launcher.stores.ubisoft.UbisoftConnect.prefix(context), "pfx").takeIf { it.isDirectory } else protonPrefix(context, g.steamAppId?.toLong() ?: g.appId, libraries = roots), icon = art.icon?.takeIf { it.extension.lowercase() != "ico" }, source = g.source, storeId = g.storeId, diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackCollections.kt b/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackCollections.kt index d680ae0709..9eebd911bc 100644 --- a/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackCollections.kt +++ b/app/src/main/java/com/droiddeck/launcher/frontend/SoundtrackCollections.kt @@ -177,9 +177,10 @@ object SoundtrackCollections { source = Library.SOURCE_COLLECTION, soundtrack = true, ) - fun games(context: Context, favoritesLabel: String): List { + fun games(context: Context, favoritesLabel: String, skipEmptyFavorites: Boolean = false): List { val s = snapshot - return listOf(game(context, FAVORITES_ID, favoritesLabel, s.favorites)) + s.collections.map { game(context, it.id, it.name, it.tracks) } + val favorites = if (skipEmptyFavorites && s.favorites.isEmpty()) emptyList() else listOf(game(context, FAVORITES_ID, favoritesLabel, s.favorites)) + return favorites + s.collections.map { game(context, it.id, it.name, it.tracks) } } fun album(context: Context, id: Int): Soundtrack.Album { diff --git a/app/src/main/java/com/droiddeck/launcher/frontend/SteamHidden.kt b/app/src/main/java/com/droiddeck/launcher/frontend/SteamHidden.kt new file mode 100644 index 0000000000..71ab7de95c --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/frontend/SteamHidden.kt @@ -0,0 +1,78 @@ +package com.droiddeck.launcher.frontend + +import org.json.JSONArray +import org.json.JSONObject +import java.io.File + +internal object SteamHidden { + private const val KEY = "user-collections.hidden" + + private fun file(root: File): File? = AddedGames.accountConfig(root)?.let { File(it, "cloudstorage/cloud-storage-namespace-1.json") } + + class Saved(val hidden: Set, val queued: Boolean) + + private fun id(member: Any?): Long? = when (member) { + is Int -> member.toLong() + is Long -> member + is String -> member.toLongOrNull() + else -> null + } + + private fun ids(collection: JSONObject, key: String, strict: Boolean): List { + if (!collection.has(key)) return emptyList() + val array = collection.optJSONArray(key) ?: throw IllegalStateException(key) + return (0 until array.length()).mapNotNull { index -> + id(array.get(index)) ?: if (strict) throw IllegalStateException(key) else null + } + } + + fun read(root: File): Set = readOrNull(root).orEmpty() + + fun readOrNull(root: File): Set? = runCatching { + val entries = JSONArray(file(root)?.readText() ?: return null) + val slot = (0 until entries.length()).map { entries.getJSONArray(it) }.firstOrNull { it.optString(0) == KEY } + val entry = slot?.optJSONObject(1) + if (slot != null && entry == null) return null + if (entry == null || entry.optBoolean("is_deleted")) emptySet() else { + val collection = JSONObject(entry.optString("value")) + ids(collection, "added", false).toSet() - ids(collection, "removed", false).toSet() + } + }.getOrNull() + + fun write(root: File, appId: Long, hidden: Boolean, now: Long = System.currentTimeMillis() / 1000): Saved? = runCatching { + val target = file(root) ?: return null + val entries = JSONArray(target.readText()) + val slot = (0 until entries.length()).firstOrNull { entries.getJSONArray(it).optString(0) == KEY } + val entry = if (slot == null) JSONObject().put("key", KEY) else entries.getJSONArray(slot).optJSONObject(1) ?: return null + val live = !entry.optBoolean("is_deleted") + val collection = if (live && entry.has("value")) JSONObject(entry.optString("value")) else JSONObject().put("id", "hidden") + val added = ids(collection, "added", true).filter { it != appId } + val removed = ids(collection, "removed", true).filter { it != appId } + collection.put("added", JSONArray(if (hidden) added + appId else added)) + collection.put("removed", JSONArray(if (hidden) removed else removed + appId)) + entry.put("value", collection.toString()) + entry.put("timestamp", now) + entry.put("is_deleted", false) + entry.opt("version")?.toString()?.toLongOrNull()?.let { entry.put("version", (it + 1).toString()) } + if (slot == null) entries.put(JSONArray().put(KEY).put(entry)) + val temp = File(target.parentFile, target.name + ".tmp") + temp.writeText(entries.toString()) + if (!temp.renameTo(target)) { + temp.delete() + return null + } + Saved(ids(collection, "added", true).toSet() - ids(collection, "removed", true).toSet(), markModified(File(target.parentFile, "cloud-storage-namespace-1.modified.json"))) + }.getOrNull() + + private fun markModified(file: File): Boolean { + val pending = if (file.exists()) runCatching { JSONArray(file.readText()) }.getOrNull() ?: return false else JSONArray() + if ((0 until pending.length()).any { pending.optString(it) == KEY }) return true + val temp = File(file.parentFile, file.name + ".tmp") + val saved = runCatching { + temp.writeText(pending.put(KEY).toString()) + temp.renameTo(file) + }.getOrDefault(false) + if (!saved) temp.delete() + return saved + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/DriverPairs.kt b/app/src/main/java/com/droiddeck/launcher/gpu/DriverPairs.kt index ce7572bba4..fc40dc7143 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/DriverPairs.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/DriverPairs.kt @@ -18,6 +18,7 @@ object DriverPairs { /** RADV-Xclipse rebased on JimVulkan's upstream: a manual choice, never Auto. */ const val NAD_RADV_XCLIPSE_UPSTREAM = "nad:radv-xclipse-upstream" private val XCLIPSE_MODEL = Regex("""(?i)xclipse\s*(\d{3})\b""") + private val SUPPORTED_XCLIPSE_MODELS = setOf("530", "920", "940") const val NAD_MALI_JM = "nad:panvk-mali-jm" const val NAD_MALI_G710 = "nad:panvk-mali-g710" const val NAD_MALI_G615 = "nad:panvk-mali-g615" @@ -112,9 +113,12 @@ object DriverPairs { } } - /** 950 and 960 panic on the older build; a name without a model number is treated the same way. */ - private fun xclipseNeedsUpstream(name: String): Boolean = - XCLIPSE_MODEL.find(name)?.groupValues?.get(1).let { it == null || it == "950" || it == "960" } + internal fun xclipseNeedsUpstream(name: String): Boolean = + XCLIPSE_MODEL.find(name)?.groupValues?.get(1) !in SUPPORTED_XCLIPSE_MODELS + + fun autoEligible(gpu: GpuInfo, sdk: Int = android.os.Build.VERSION.SDK_INT): Boolean = + recommendedKey(gpu, emptyList(), sdk = sdk) != null || + (gpu.family == Family.POWERVR && gpu.name.contains("Xclipse", ignoreCase = true)) fun recommendedKey( gpu: GpuInfo, pairs: List, @@ -125,6 +129,7 @@ object DriverPairs { Family.POWERVR -> return when { !gpu.name.contains("Xclipse", ignoreCase = true) -> null xclipseNeedsUpstream(gpu.name) && pairs.any { it.key == NAD_RADV_XCLIPSE_UPSTREAM } -> NAD_RADV_XCLIPSE_UPSTREAM + xclipseNeedsUpstream(gpu.name) -> null else -> NAD_RADV_XCLIPSE } Family.MALI_OTHER, Family.NOT_ADRENO -> return null diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt b/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt index 7645d3326a..77cbdf55cf 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt +++ b/app/src/main/java/com/droiddeck/launcher/gpu/GpuInfo.kt @@ -118,9 +118,7 @@ data class GpuInfo( val samsung = Build.MANUFACTURER.equals("samsung", ignoreCase = true) return GpuInfo( name = when { - family == Family.POWERVR -> SystemVulkanDriver.gpuName().let { gpu -> - VulkanInfo.cachedOrNull()?.get("device")?.takeIf { it.contains(gpu, ignoreCase = true) } ?: gpu - } + family == Family.POWERVR -> systemDriverName(SystemVulkanDriver.gpuName(), VulkanInfo.cachedOrNull()) mali != null && mali.isNotEmpty() -> mali !adreno -> Build.HARDWARE.ifBlank { UNNAMED } model > 0 -> "Adreno $model" @@ -134,6 +132,9 @@ data class GpuInfo( ) } + fun systemDriverName(gpu: String, vulkan: Map?): String = + vulkan?.get("device")?.takeIf { it.contains(gpu, ignoreCase = true) } ?: gpu + internal fun verifiedOn(model: Int, device: String): Boolean = model == 722 && device.equals("Retroid Pocket Duo", ignoreCase = true) diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriver.java b/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriver.java index 25dd68b4d9..13adf1f129 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriver.java +++ b/app/src/main/java/com/droiddeck/launcher/gpu/LinuxVulkanDriver.java @@ -12,7 +12,7 @@ import java.util.function.Supplier; public final class LinuxVulkanDriver { private static final String TAG = "LinuxVulkanDriver"; - public static final String ENV = "BL_VK_DRIVER"; + public static final String ENV = "DD_VK_DRIVER"; public static final String HELP_TEXT = "The driver the Steam client, the games it launches and the desktop's programs render on, " diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/SystemVulkanDriver.java b/app/src/main/java/com/droiddeck/launcher/gpu/SystemVulkanDriver.java index 1106ac9602..77f735e094 100644 --- a/app/src/main/java/com/droiddeck/launcher/gpu/SystemVulkanDriver.java +++ b/app/src/main/java/com/droiddeck/launcher/gpu/SystemVulkanDriver.java @@ -256,12 +256,12 @@ public final class SystemVulkanDriver { if (xclipse) environment.add("DROIDDECK_HYBRIS_DXVK=dxvk-2.6.2"); // The Android driver has a render node, but no KMS primary node. SDL presents // through the wrapper's Wayland Vulkan swapchain instead of a KMS-style path. - environment.add("BL_GAMESCOPE_BACKEND=sdl"); + environment.add("DD_GAMESCOPE_BACKEND=sdl"); // The Android pvr kernel accepts Vulkan DMA-BUF imports but rejects PRIME GEM handles. - environment.add("BL_POWERVR_DRM_HANDLES=1"); - environment.add("BL_POWERVR_RENDER_NODE=" + node); + environment.add("DD_POWERVR_DRM_HANDLES=1"); + environment.add("DD_POWERVR_RENDER_NODE=" + node); // Inner Gamescope/Xwayland lacks the bridge's Android-buffer WSI protocols. - environment.add("BL_STEAM_GL_PRESENT=1"); + environment.add("DD_STEAM_GL_PRESENT=1"); // Only actual Proton game launches use the bundled DXVK and X11 WSI layer. environment.add("DROIDDECK_POWERVR_RUNTIME=" + directory.getPath()); } diff --git a/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt b/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt index db5f74e4cf..3c996a03f0 100644 --- a/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt +++ b/app/src/main/java/com/droiddeck/launcher/hud/GameFrames.kt @@ -275,7 +275,7 @@ internal class GameFrameFeed( private const val INFO_NS = 500_000_000L private const val SHIFT_NS = 1_000_000_000L private const val SHIFT_RECHECK_NS = 100_000_000L - private const val CLOCK_CONTROL_PATH = "tmp/.bl-clock" + private const val CLOCK_CONTROL_PATH = "tmp/.dd-clock" fun forRoot(root: File) = GameFrameFeed(File(root, HudFrames.PATH), clockControl = File(root, CLOCK_CONTROL_PATH)) diff --git a/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt b/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt index 848fc65701..1d8bf5d682 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/DualScreen.kt @@ -82,6 +82,12 @@ object DualScreen { fun sessionDisplay(context: Context, displayManager: DisplayManager, primaryDisplayId: Int): Display? = display(context, displayManager, primaryDisplayId, SessionPrefs.dualScreenSessionMode(context)) + fun selectedSessionDisplay(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, selectedDisplayId: Int): Display? = + displayManager.getDisplay(selectedDisplayId)?.takeIf { + SessionPrefs.dualScreenSessionMode(context) != MODE_OFF && it.isValid && it.displayId != primaryDisplayId && + (it.flags and Display.FLAG_PRESENTATION) != 0 && !taken(it.displayId) + } + fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, mode: String = SessionPrefs.dualScreenMode(context)): Display? = when (mode) { MODE_OFF -> null diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt b/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt index bcc641ebaa..5f0b082c8c 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputLibraries.kt @@ -138,16 +138,16 @@ object InputLibraries { update(context) { library -> library.layouts.firstOrNull { it.id == layoutId && it.editable }?.let { library.withLayout(it.withQuickButton(button, shown)) } ?: library } }.isSuccess - fun defaultPositions(context: Context, library: InputLibrary, layout: SavedInputLayout): List? { + fun defaultPositions(context: Context, library: InputLibrary, layout: SavedInputLayout): Pair, Float>? { val origin = layout.origin ?: layout.id - InputStockLayouts.layouts().firstOrNull { it.id == origin }?.let { return it.elements } + InputStockLayouts.layouts().firstOrNull { it.id == origin }?.let { return it.elements to it.aspect } if (origin == OVERLAY || origin.startsWith("migrated.layout.")) { val (surfaceContext, metrics) = primaryDisplay(context) val size = if (origin == OVERLAY) listOf(metrics.widthPixels, metrics.heightPixels) else origin.removePrefix("migrated.layout.").split('x').mapNotNull { it.toIntOrNull() } - return size.takeIf { it.size == 2 && it.all { side -> side > 0 } }?.let { LegacyGamepadLayout(surfaceContext, it[0], it[1]).elements() } + return size.takeIf { it.size == 2 && it.all { side -> side > 0 } }?.let { LegacyGamepadLayout(surfaceContext, it[0], it[1]).elements() to it[0].toFloat() / it[1] } } - return library.layouts.firstOrNull { it.id == origin && it.id != layout.id }?.elements + return library.layouts.firstOrNull { it.id == origin && it.id != layout.id }?.let { it.elements to it.aspect } } @Suppress("DEPRECATION") diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt b/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt index cc6313dc30..0e5ed4261f 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputLibrary.kt @@ -97,6 +97,16 @@ data class InputLibrary( fun compileActive(isDesktop: Boolean, panel: String? = null): InputProfile = compileParts(activeId(isDesktop), InputRole.entries.associateWith { preset(if (it == InputRole.SECONDARY) panelPart(isDesktop, panel).bindings else activePart(isDesktop, it).bindings) }) + fun compileStock(isDesktop: Boolean, panel: String? = null): InputProfile { + val defaults = InputProfile.defaults(profile(activeId(isDesktop)).base) + val stock = InputStockLayouts.presets(InputStockLayouts.layouts()) + return compileParts(defaults.id, InputRole.entries.associateWith { role -> + val part = if (role == InputRole.SECONDARY) panelPart(isDesktop, panel) else activePart(isDesktop, role) + val origin = layouts.firstOrNull { it.id == part.layout }?.origin ?: part.layout + stock.firstOrNull { it.id == part.bindings || (origin != null && it.layoutId == origin) } + ?: SavedInputBindings(part.bindings, "", role == InputRole.PHYSICAL, part.layout, defaults.bindings[role].orEmpty()) + }) + } fun saveSelection(isDesktop: Boolean, name: String, id: String = newInputId()): InputLibrary { val current = profile(activeId(isDesktop)) diff --git a/app/src/main/java/com/droiddeck/launcher/input/InputProfile.kt b/app/src/main/java/com/droiddeck/launcher/input/InputProfile.kt index 2375cf34e8..a122766271 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/InputProfile.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/InputProfile.kt @@ -53,6 +53,16 @@ data class InputProfile( fun elementClickAction(role: InputRole, element: InputSurfaceElement): InputAction = clicks[role]?.get(element.id) ?: defaultElementClick(element, elementAction(role, element.id, element.control)) { action(role, it) } + fun showsMouseButton(role: InputRole, shown: List, stock: InputProfile): Boolean = shown.any { element -> + val action = elementAction(role, element.id, element.control).takeIf { + elements[role]?.get(element.id) != stock.elements[role]?.get(element.id) || it != stock.elementAction(role, element.id, element.control) + } + val click = elementClickAction(role, element).takeIf { + clicks[role]?.get(element.id) != stock.clicks[role]?.get(element.id) || it != stock.elementClickAction(role, element) + } + listOfNotNull(action, click).any { it is InputAction.MouseButton && it.validFor(element.control) } + } + companion object { const val GAME = "game" const val DESKTOP = "desktop" diff --git a/app/src/main/java/com/droiddeck/launcher/input/KeyboardHost.kt b/app/src/main/java/com/droiddeck/launcher/input/KeyboardHost.kt index 6656b7697f..5372be6db5 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/KeyboardHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/KeyboardHost.kt @@ -26,6 +26,8 @@ class KeyboardHost( var imeShowing = false private set var onImeChanged: ((Boolean) -> Unit)? = null + val hideMeansDismissal: Boolean + get() = Build.VERSION.SDK_INT < Build.VERSION_CODES.R || (shown && imeShowing) init { isFocusable = false diff --git a/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt index e281a2b741..2a36489e85 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/LegacyGamepadLayout.kt @@ -176,7 +176,7 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid } - fun elements(): List { + fun elements(previousStickGeometry: Boolean = false): List { fit = fitScale() controls.forEach { it.radius = scaled(it.radiusDp) } placeAuto(width.toFloat(), height.toFloat()) @@ -189,7 +189,7 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid }.map { c -> InputSurfaceElement(requireNotNull(InputControl.fromId(c.id)), (c.cx - c.halfW) / width, (c.cy - c.halfH) / height, 2 * c.halfW / width, 2 * c.halfH / height, floating = settings.adaptiveSticks, hideWhenIdle = c.stick >= 0 && settings.adaptiveSticks, - buttonShape = if (c.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE).let(::widenStick).bounded() + buttonShape = if (c.id in shoulderIds) InputButtonShape.PILL else InputButtonShape.CIRCLE).let { if (previousStickGeometry) widenStickPreviously(it) else widenStick(it) }.bounded() }.toMutableList() if (settings.keyboardButton) result += keyboard() return result @@ -315,7 +315,7 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid return e.copy(x = (cx - radius) / width, y = (cy - radius) / height, width = 2 * radius / width, height = 2 * radius / height) } - private fun widenStick(e: InputSurfaceElement): InputSurfaceElement { + private fun widenStickPreviously(e: InputSurfaceElement): InputSurfaceElement { val extra = e.width * (STICK_REACH - 1f) return when (e.control) { InputControl.LS -> (e.x - extra).coerceAtLeast(0f).let { x -> e.copy(x = x, width = e.x + e.width - x) } @@ -323,6 +323,16 @@ internal class LegacyGamepadLayout(private val context: Context, private val wid else -> e } } + + private fun widenStick(e: InputSurfaceElement): InputSurfaceElement { + val extra = e.width * (STICK_REACH - 1f) + val width = e.width + extra + return when (e.control) { + InputControl.LS -> e.copy(x = (e.x - extra).coerceIn(0f, (1f - width).coerceAtLeast(0f)), width = width) + InputControl.RS -> e.copy(x = e.x.coerceIn(0f, (1f - width).coerceAtLeast(0f)), width = width) + else -> e + } + } private companion object { const val MIN_FACE_MM = 9.5f const val FULL_SIZE_HEIGHT_MM = 85f diff --git a/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt b/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt index 4923221fa0..ee3a6560ae 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenControls.kt @@ -32,6 +32,7 @@ class OnScreenControls(context: Context, pad: PadBridge?, val dock: OnScreenLayo var isPinnedOnly = false private set val hasPinned get() = layout?.elements?.any { it.alwaysShown } == true + val inputSurface: com.droiddeck.launcher.ui.InputSurfaceView get() = surface var onTouchMiss: ((MotionEvent) -> Unit)? get() = surface.onTouchMiss set(value) { surface.onTouchMiss = value } diff --git a/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt b/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt index 3935c1a565..9fbb01c7ad 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/OnScreenLayout.kt @@ -5,6 +5,7 @@ import android.graphics.Rect import kotlin.math.abs import kotlin.math.max import kotlin.math.min +import kotlin.math.roundToInt object OnScreenLayout { data class Dock(val portrait: Boolean, val grips: Boolean, val left: InputControl = InputControl.LS, val right: InputControl = InputControl.RS) { @@ -41,6 +42,14 @@ object OnScreenLayout { return stored.mapNotNull { byId[it.id] } + placed.filter { p -> stored.none { it.id == p.id } } } + fun editorElements(context: Context, layout: SavedInputLayout, width: Int, height: Int, edited: Boolean = false): List = + elements(context, if (edited && width > 0 && height > 0) layout.copy(aspect = width.toFloat() / height) else layout, width, height, Rect()) + + fun editorFrame(layout: SavedInputLayout, displayed: List): List { + val byId = displayed.associateBy { it.id } + return layout.elements.map { byId[it.id] ?: it } + } + fun fit(elements: List, referenceWidth: Float, referenceHeight: Float, width: Int, height: Int, safe: Rect): List { val w = width.toFloat() val h = height.toFloat() @@ -77,8 +86,11 @@ object OnScreenLayout { if (gamepad.any { it.id.startsWith("legacy:") }) { val named = layout.id.removePrefix("migrated.layout.").takeIf { it != layout.id }?.split('x')?.mapNotNull { it.toIntOrNull() } ?.takeIf { it.size == 2 && it.all { size -> size > 0 } }?.let { it[0] to it[1] } - for ((w, h) in listOfNotNull(named, width to height, long to short, short to long).distinct()) { - if (matches(gamepad, LegacyGamepadLayout(display, w, h, scale = layout.scale).elements())) return (w.toFloat() to h.toFloat()) to true + val aspectSize = layout.aspect.takeIf { layout.id == InputLibraries.OVERLAY && it > 0f } + ?.let { (it * height).roundToInt().coerceAtLeast(1) to height } + for ((w, h) in listOfNotNull(named, width to height, aspectSize, long to short, short to long).distinct()) { + val generator = LegacyGamepadLayout(display, w, h, scale = layout.scale) + if (matches(gamepad, generator.elements()) || matches(gamepad, generator.elements(previousStickGeometry = true))) return (w.toFloat() to h.toFloat()) to true } } val aspect = layout.aspect.takeIf { it > 0f } ?: (long.toFloat() / short) 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 c75602585c..666a9d1ceb 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java +++ b/app/src/main/java/com/droiddeck/launcher/input/PadBridge.java @@ -12,6 +12,8 @@ import com.droiddeck.launcher.session.SessionState; import java.io.File; import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; import java.util.concurrent.atomic.AtomicIntegerArray; public final class PadBridge { @@ -56,6 +58,7 @@ public final class PadBridge { private final FakeInputWriter[] playerWriters = new FakeInputWriter[SLOTS]; private final PadState[] playerStates = new PadState[SLOTS]; private final float[][] rawSticks = new float[SLOTS][4]; + private final Map rightStickLayouts = new HashMap<>(); private final boolean[][] keyTriggers = new boolean[SLOTS][2]; private final int[] retainedSticks = new int[SLOTS]; private final PadState effectiveState = new PadState(); @@ -240,6 +243,7 @@ public final class PadBridge { clearBackQamWrites(); releaseBackPaddles(); activeControllerId = NO_CONTROLLER; + rightStickLayouts.clear(); for (int slot = 0; slot < SLOTS; slot++) { owners[slot] = NO_CONTROLLER; partners[slot] = NO_CONTROLLER; @@ -525,20 +529,23 @@ public final class PadBridge { float lx = event.getAxisValue(MotionEvent.AXIS_X); float ly = event.getAxisValue(MotionEvent.AXIS_Y); boolean wired = wiredXboxLayout(device, event.getSource()); - float rx = event.getAxisValue(wired ? MotionEvent.AXIS_RX : MotionEvent.AXIS_Z); - float ry = event.getAxisValue(wired ? MotionEvent.AXIS_RY : MotionEvent.AXIS_RZ); + boolean rxRyStick = rightStickUsesRxRy(event, device, rightStickLayouts); + float rx = event.getAxisValue(rxRyStick ? MotionEvent.AXIS_RX : MotionEvent.AXIS_Z); + float ry = event.getAxisValue(rxRyStick ? MotionEvent.AXIS_RY : MotionEvent.AXIS_RZ); retainStick(slot, JoyCon.LEFT, lx, ly); retainStick(slot, JoyCon.RIGHT, rx, ry); projectSticks(slot); int source = event.getSource(); float lt = 0f; float rt = 0f; - if (wired || hasAxis(device, source, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE)) { - lt = axisTrigger(leftTrigger(event, wired), keyTriggers[slot], 0); + boolean signedLeft = signedZTriggers(event, device, wired, rxRyStick, true); + boolean signedRight = signedZTriggers(event, device, wired, rxRyStick, false); + if (signedLeft || hasAxis(device, source, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE)) { + lt = axisTrigger(triggerValue(event, device, wired, rxRyStick, true), keyTriggers[slot], 0); pad.leftTrigger = lt; } - if (wired || hasAxis(device, source, MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS)) { - rt = axisTrigger(rightTrigger(event, wired), keyTriggers[slot], 1); + if (signedRight || hasAxis(device, source, MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS)) { + rt = axisTrigger(triggerValue(event, device, wired, rxRyStick, false), keyTriggers[slot], 1); pad.rightTrigger = rt; } if (hasAxis(device, source, MotionEvent.AXIS_HAT_X)) { @@ -596,6 +603,92 @@ public final class PadBridge { return false; } + static boolean rightStickUsesRxRy(MotionEvent event, InputDevice device, Map layouts) { + int source = event.getSource(); + if (wiredXboxLayout(device, source)) return true; + boolean hasRxRy = hasAxis(device, source, MotionEvent.AXIS_RX) + && hasAxis(device, source, MotionEvent.AXIS_RY); + boolean hasZRz = hasAxis(device, source, MotionEvent.AXIS_Z) + && hasAxis(device, source, MotionEvent.AXIS_RZ); + if (!hasRxRy) return false; + if (!hasZRz) return true; + Boolean cached = layouts.get(event.getDeviceId()); + if (cached != null) return cached; + boolean rxRyEvidence = atMinimum(device, source, event, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ) + && nearCentre(device, source, event, MotionEvent.AXIS_RX, MotionEvent.AXIS_RY); + boolean zRzEvidence = atMinimum(device, source, event, MotionEvent.AXIS_RX, MotionEvent.AXIS_RY) + && nearCentre(device, source, event, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ); + if (rxRyEvidence == zRzEvidence) return false; + boolean useRxRy = rxRyEvidence; + layouts.put(event.getDeviceId(), useRxRy); + return useRxRy; + } + + static boolean signedZTriggers(MotionEvent event, InputDevice device, boolean wired, boolean rxRyStick, boolean left) { + if (wired) return true; + if (!rxRyStick) return false; + int source = event.getSource(); + int signedAxis = left ? MotionEvent.AXIS_Z : MotionEvent.AXIS_RZ; + int dedicatedAxis = left ? MotionEvent.AXIS_LTRIGGER : MotionEvent.AXIS_RTRIGGER; + int alternateAxis = left ? MotionEvent.AXIS_BRAKE : MotionEvent.AXIS_GAS; + return hasAxis(device, source, signedAxis) + && !hasAxis(device, source, dedicatedAxis, alternateAxis); + } + + static float triggerValue(MotionEvent event, InputDevice device, boolean wired, boolean rxRyStick, boolean left) { + if (signedZTriggers(event, device, wired, rxRyStick, left)) { + int axis = left ? MotionEvent.AXIS_Z : MotionEvent.AXIS_RZ; + float value = event.getAxisValue(axis); + if (!wired && device != null) { + InputDevice.MotionRange range = device.getMotionRange(axis, event.getSource()); + if (range != null && range.getMax() > range.getMin()) { + return Math.max(0f, Math.min(1f, + (value - range.getMin()) / (range.getMax() - range.getMin()))); + } + } + return Math.max(0f, Math.min(1f, (value + 1f) / 2f)); + } + int source = event.getSource(); + int axis = left ? MotionEvent.AXIS_LTRIGGER : MotionEvent.AXIS_RTRIGGER; + int alternate = left ? MotionEvent.AXIS_BRAKE : MotionEvent.AXIS_GAS; + if (device == null) { + float value = event.getAxisValue(axis); + return value != 0f ? value : event.getAxisValue(alternate); + } + if (hasAxis(device, source, axis)) { + float value = event.getAxisValue(axis); + return value != 0f ? value : event.getAxisValue(alternate); + } + if (hasAxis(device, source, alternate)) return event.getAxisValue(alternate); + return 0f; + } + + private static float restDistance(InputDevice device, int source, MotionEvent event, int xAxis, int yAxis) { + return (restDistance(device.getMotionRange(xAxis, source), event.getAxisValue(xAxis)) + + restDistance(device.getMotionRange(yAxis, source), event.getAxisValue(yAxis))) / 2f; + } + + private static float restDistance(InputDevice.MotionRange range, float value) { + float span = range.getMax() - range.getMin(); + if (span <= 0f) return 1f; + return Math.abs(value - (range.getMin() + range.getMax()) / 2f) / span; + } + + private static boolean atMinimum(InputDevice device, int source, MotionEvent event, int xAxis, int yAxis) { + return atMinimum(device.getMotionRange(xAxis, source), event.getAxisValue(xAxis)) + && atMinimum(device.getMotionRange(yAxis, source), event.getAxisValue(yAxis)); + } + + private static boolean atMinimum(InputDevice.MotionRange range, float value) { + float span = range.getMax() - range.getMin(); + return value - range.getMin() <= span * 0.02f; + } + + private static boolean nearCentre(InputDevice device, int source, MotionEvent event, int xAxis, int yAxis) { + return restDistance(device.getMotionRange(xAxis, source), event.getAxisValue(xAxis)) <= 0.1f + && restDistance(device.getMotionRange(yAxis, source), event.getAxisValue(yAxis)) <= 0.1f; + } + public interface TouchRoute { boolean active(); @@ -1182,16 +1275,4 @@ public final class PadBridge { && device.getMotionRange(MotionEvent.AXIS_RZ, source) != null; } - public static float leftTrigger(MotionEvent event, boolean wired) { - if (wired) return Math.max(0f, Math.min(1f, (event.getAxisValue(MotionEvent.AXIS_Z) + 1f) / 2f)); - float value = event.getAxisValue(MotionEvent.AXIS_LTRIGGER); - return value != 0f ? value : event.getAxisValue(MotionEvent.AXIS_BRAKE); - } - - public static float rightTrigger(MotionEvent event, boolean wired) { - if (wired) return Math.max(0f, Math.min(1f, (event.getAxisValue(MotionEvent.AXIS_RZ) + 1f) / 2f)); - float value = event.getAxisValue(MotionEvent.AXIS_RTRIGGER); - return value != 0f ? value : event.getAxisValue(MotionEvent.AXIS_GAS); - } - } diff --git a/app/src/main/java/com/droiddeck/launcher/input/PadMouse.kt b/app/src/main/java/com/droiddeck/launcher/input/PadMouse.kt index 2d71451ccf..dccba8a1b6 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/PadMouse.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/PadMouse.kt @@ -42,6 +42,7 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S private val total = Sticks() private val triggerAxes = HashMap() private val wiredLayout = HashMap() + private val rightStickLayouts = HashMap() private val down = HashMap>() private val sent = HashMap() private val held = LinkedHashMap() @@ -87,14 +88,21 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S fun onMotion(event: MotionEvent): Boolean { if (event.actionMasked != MotionEvent.ACTION_MOVE) return true val sticks = physical.getOrPut(event.deviceId) { Sticks() } - val wired = wiredLayout.getOrPut(event.deviceId) { PadBridge.wiredXboxLayout(event) } + val device = event.device + val wired = wiredLayout.getOrPut(event.deviceId) { PadBridge.wiredXboxLayout(device, event.source) } + val rxRyStick = PadBridge.rightStickUsesRxRy(event, device, rightStickLayouts) sticks.leftX = event.getAxisValue(MotionEvent.AXIS_X) sticks.leftY = event.getAxisValue(MotionEvent.AXIS_Y) - sticks.rightX = scrollAxis(event, if (wired) MotionEvent.AXIS_RX else MotionEvent.AXIS_Z) - sticks.rightY = scrollAxis(event, if (wired) MotionEvent.AXIS_RY else MotionEvent.AXIS_RZ) - if (hasTriggerAxes(event)) { - sticks.leftTrigger = PadBridge.leftTrigger(event, wired) - sticks.rightTrigger = PadBridge.rightTrigger(event, wired) + sticks.rightX = scrollAxis(event, if (rxRyStick) MotionEvent.AXIS_RX else MotionEvent.AXIS_Z) + sticks.rightY = scrollAxis(event, if (rxRyStick) MotionEvent.AXIS_RY else MotionEvent.AXIS_RZ) + val signedLeft = PadBridge.signedZTriggers(event, device, wired, rxRyStick, true) + val signedRight = PadBridge.signedZTriggers(event, device, wired, rxRyStick, false) + val analogTriggers = hasTriggerAxes(event) + if (analogTriggers || signedLeft) { + sticks.leftTrigger = PadBridge.triggerValue(event, device, wired, rxRyStick, true) + } + if (analogTriggers || signedRight) { + sticks.rightTrigger = PadBridge.triggerValue(event, device, wired, rxRyStick, false) } val hatX = event.getAxisValue(MotionEvent.AXIS_HAT_X) val hatY = event.getAxisValue(MotionEvent.AXIS_HAT_Y) @@ -129,6 +137,7 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S physical.clear() triggerAxes.clear() wiredLayout.clear() + rightStickLayouts.clear() touch.clear() down.clear() sent.clear() @@ -207,6 +216,7 @@ class PadMouse(private val listener: Listener, private val clock: () -> Long = S private fun hasTriggerAxes(event: android.view.InputEvent): Boolean = triggerAxes.getOrPut(event.deviceId) { val device = event.device ?: return@getOrPut true device.getMotionRange(MotionEvent.AXIS_LTRIGGER) != null || device.getMotionRange(MotionEvent.AXIS_BRAKE) != null || + device.getMotionRange(MotionEvent.AXIS_RTRIGGER) != null || device.getMotionRange(MotionEvent.AXIS_GAS) != null || (event is MotionEvent && wiredLayout.getOrPut(event.deviceId) { PadBridge.wiredXboxLayout(event) }) } diff --git a/app/src/main/java/com/droiddeck/launcher/input/ScrollTouchGestures.kt b/app/src/main/java/com/droiddeck/launcher/input/ScrollTouchGestures.kt index 4f1ebc9bdd..06da1bae21 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/ScrollTouchGestures.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/ScrollTouchGestures.kt @@ -42,6 +42,7 @@ class ScrollTouchGestures( private var flingY = 0f private var flingAt = 0L private var flinging = false + var clicks = true private val longPress = Runnable { held = true @@ -86,7 +87,7 @@ class ScrollTouchGestures( lastY = startY tracker = VelocityTracker.obtain().also { it.addMovement(event) } listener.onMove(startX, startY) - handler.postDelayed(longPress, TouchTiming.HOLD_MS) + if (clicks) handler.postDelayed(longPress, TouchTiming.HOLD_MS) } MotionEvent.ACTION_MOVE -> { val index = event.findPointerIndex(pointerId).takeIf { it >= 0 } ?: return true @@ -153,6 +154,7 @@ class ScrollTouchGestures( private fun click(button: Int) { releaseClick() + if (!clicks) return listener.onButton(button, true) clicked = button handler.postDelayed(clickUp, TouchTiming.CLICK_MS) diff --git a/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt b/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt index 2d0006925f..590ef4fc08 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/SecondScreenMode.kt @@ -40,6 +40,18 @@ enum class SecondScreenMode(val id: String, @StringRes val label: Int, val bindi data class SecondScreenDisplay(val id: Int, val label: String) object SecondScreenDisplays { + fun selection(selected: Int, available: List, gameRequested: Boolean): Int = + if (selected in available || gameRequested && selected >= 0) selected else available.firstOrNull() ?: -1 + + fun selection(selected: Int, available: List, gameRequested: Boolean, save: (Int) -> Unit): Int = + selection(selected, available, gameRequested).also { if (it != selected) save(it) } + + fun keyboardOnPrimary(gameRequested: Boolean, selected: Int, available: List, visible: Boolean = true, taken: (Int) -> Boolean): Boolean = + visible && gameRequested && selected >= 0 && (selected !in available || taken(selected)) + + fun routeKeyboard(steam: Boolean, enabled: Boolean, panel: Boolean, dock: Boolean, primaryFallback: Boolean): Boolean = + steam && enabled && (panel || dock || primaryFallback) + fun available(displayManager: DisplayManager, primaryDisplayId: Int = Display.DEFAULT_DISPLAY): List = displayManager.getDisplays(DisplayManager.DISPLAY_CATEGORY_PRESENTATION) .asSequence() diff --git a/app/src/main/java/com/droiddeck/launcher/input/ShortcutsRelay.kt b/app/src/main/java/com/droiddeck/launcher/input/ShortcutsRelay.kt index 6c24a7a472..a39a84adf1 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/ShortcutsRelay.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/ShortcutsRelay.kt @@ -178,4 +178,56 @@ class ShortcutsRelay : Service(), InputManager.InputDeviceListener { private companion object { const val KEY_TIMEOUT_MS = 200L } + + // Frontends such as Cocoon treat a running player process as an open game, so the relay runs only while a screen is started. + object Holder : android.app.Application.ActivityLifecycleCallbacks, android.content.ServiceConnection { + private const val RELEASE_MS = 1_000L + private val handler = Handler(Looper.getMainLooper()) + private var app: android.app.Application? = null + private var started = 0 + private var bound = false + private val release = Runnable { unbind() } + + fun install(application: android.app.Application) { + app?.unregisterActivityLifecycleCallbacks(this) + handler.removeCallbacks(release) + started = 0 + bound = false + app = application + application.registerActivityLifecycleCallbacks(this) + } + + override fun onActivityStarted(activity: android.app.Activity) { + started++ + handler.removeCallbacks(release) + if (!bound) bind() + } + + override fun onActivityStopped(activity: android.app.Activity) { + started = (started - 1).coerceAtLeast(0) + if (started == 0) handler.postDelayed(release, RELEASE_MS) + } + + private fun bind() { + val context = app ?: return + if (runCatching { context.packageManager.getPackageInfo(Relay.PACKAGE, 0) }.isFailure) return + bound = runCatching { + context.bindService(Intent(context, ShortcutsRelay::class.java), this, Context.BIND_AUTO_CREATE) + }.getOrDefault(false) + } + + private fun unbind() { + if (!bound) return + bound = false + runCatching { app?.unbindService(this) } + } + + override fun onServiceConnected(name: android.content.ComponentName?, service: IBinder?) = Unit + override fun onServiceDisconnected(name: android.content.ComponentName?) = Unit + override fun onActivityCreated(activity: android.app.Activity, savedInstanceState: android.os.Bundle?) = Unit + override fun onActivityResumed(activity: android.app.Activity) = Unit + override fun onActivityPaused(activity: android.app.Activity) = Unit + override fun onActivitySaveInstanceState(activity: android.app.Activity, outState: android.os.Bundle) = Unit + override fun onActivityDestroyed(activity: android.app.Activity) = Unit + } } diff --git a/app/src/main/java/com/droiddeck/launcher/input/TouchpadGestures.kt b/app/src/main/java/com/droiddeck/launcher/input/TouchpadGestures.kt index ed4e87732b..659b99c0ce 100644 --- a/app/src/main/java/com/droiddeck/launcher/input/TouchpadGestures.kt +++ b/app/src/main/java/com/droiddeck/launcher/input/TouchpadGestures.kt @@ -17,6 +17,11 @@ class TouchpadGestures( var bounds: android.graphics.RectF = android.graphics.RectF(0f, 0f, 1f, 1f) var sensitivity = 1.15f var desktop = false + var clicks = true + set(value) { + if (field != value) lastTapAt = 0L + field = value + } private val handler = Handler(Looper.getMainLooper()) private var lastX = 0f @@ -50,12 +55,17 @@ class TouchpadGestures( held = true dragging = true listener.onLongPress() - listener.onButton(PointerGestures.BTN_LEFT, true, x, y) + press(PointerGestures.BTN_LEFT) } private val clickUp = Runnable { releaseClick() } + private fun press(button: Int) { + if (clicks) listener.onButton(button, true, x, y) + } + private fun click(button: Int) { releaseClick() + if (!clicks) return listener.onButton(button, true, x, y) clicked = button handler.postDelayed(clickUp, TouchTiming.CLICK_MS) @@ -108,12 +118,12 @@ class TouchpadGestures( travelled = 0f; held = false; twoFingers = false; scrolled = false; secondWasTap = false fingers = 1; pinching = false anchorId = event.getPointerId(0); moverId = -1; holdDrag = false; scrollLocked = false - if (event.eventTime - lastTapAt < TouchTiming.DOUBLE_TAP_MS) { + if (clicks && event.eventTime - lastTapAt < TouchTiming.DOUBLE_TAP_MS) { dragging = true - listener.onButton(PointerGestures.BTN_LEFT, true, x, y) + press(PointerGestures.BTN_LEFT) } else { dragging = false - handler.postDelayed(longPress, TouchTiming.HOLD_MS) + if (clicks) handler.postDelayed(longPress, TouchTiming.HOLD_MS) } return true } @@ -153,7 +163,7 @@ class TouchpadGestures( secondWasTap = false if (!dragging) { dragging = true - listener.onButton(PointerGestures.BTN_LEFT, true, x, y) + press(PointerGestures.BTN_LEFT) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt b/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt index 1eed2f3842..ca408e3b36 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/BwrapSpawner.kt @@ -218,12 +218,15 @@ object BwrapSpawner { private fun runtimeLib(rootfs: String, name: String): File? = LIB_DIRS.map { File(rootfs, "$it/$name") }.firstOrNull { it.exists() } - private fun gpu(rootfs: String, root: File, env: MutableMap): List? { + internal fun gpu( + rootfs: String, root: File, env: MutableMap, + kgslAvailable: Boolean = File("/dev/kgsl-3d0").exists(), + ): List? { env["VKBRIDGE_SOCKET"]?.let { sock -> if (File(sock).exists()) return bridgeGpu(rootfs, root, env, sock) } val driver = runtimeLib(rootfs, "libvulkan_freedreno.so") - if (driver == null || !File("/dev/kgsl-3d0").exists()) return null + if (driver == null || !kgslAvailable) return null if (env.containsKey("VK_ICD_FILENAMES") || env.containsKey("VK_DRIVER_FILES")) return null - if (env["BL_DESKTOP"] == "1" && env["GAMESCOPE_WAYLAND_DISPLAY"] == null) return null + if (env["LIBGL_ALWAYS_SOFTWARE"] == "1" && env["GAMESCOPE_WAYLAND_DISPLAY"] == null) return null val binds = arrayListOf(Bind(driver.canonicalPath, "$GPU_DIR/libvulkan_freedreno.so")) for (name in GPU_LIBS) { val f = runtimeLib(rootfs, name) ?: continue diff --git a/app/src/main/java/com/droiddeck/launcher/runtime/LegacyNames.kt b/app/src/main/java/com/droiddeck/launcher/runtime/LegacyNames.kt index 3febbfd1fa..3f4589ae13 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/LegacyNames.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/LegacyNames.kt @@ -21,6 +21,10 @@ object LegacyNames { "etc/bannerlator-network.json" to "etc/droiddeck-network.json", "etc/bannerlator-wifi-scan-request" to "etc/droiddeck-wifi-scan-request", ) + private val RETIRED_FILES = listOf("libblsession.so", "libblfastpath.so", "libblaudit.so").map { "usr/local/lib/$it" } + + listOf("x86_64", "i386").map { "usr/local/lib/droiddeck-fex/$it/libblsession.so" } + private const val LEGACY_MARKER = ".bl-" + private val QUEUED_MARKERS = setOf(".bl-proton-extra", ".bl-steam-urls") private val MENU_REWRITES = listOf( Triple("usr/local/share/applications", "/usr/local/bin/bannerlator-", "/usr/local/bin/droiddeck-"), Triple("usr/share/applications", "Exec=env APPIMAGE_EXTRACT_AND_RUN=1 /opt/appimages/", @@ -38,6 +42,20 @@ object LegacyNames { fun migrateRootfs(root: File) { migrateEtc(root) for ((old, new) in MOVED_FILES) move(File(root, old), File(root, new)) + for (path in RETIRED_FILES) File(root, path).delete() + File(root, "root").listFiles { f -> f.name.startsWith(LEGACY_MARKER) }?.forEach { + val target = File(it.parentFile, ".dd-" + it.name.removePrefix(LEGACY_MARKER)) + if (it.name in QUEUED_MARKERS && it.isFile && !isLink(it) && target.isFile && !isLink(target)) { + val queued = it.readText() + if (queued.isNotBlank()) { + val separator = if (target.length() > 0 && !target.readText().endsWith("\n")) "\n" else "" + target.appendText(separator + if (queued.endsWith("\n")) queued else queued + "\n") + } + FileUtils.delete(it) + } else { + move(it, target) + } + } linkScripts(root) rewriteMenuEntries(root) } 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 11265bd8ae..27ef86f086 100644 --- a/app/src/main/java/com/droiddeck/launcher/runtime/ProotFastPath.kt +++ b/app/src/main/java/com/droiddeck/launcher/runtime/ProotFastPath.kt @@ -9,7 +9,7 @@ import java.security.MessageDigest object ProotFastPath { private const val TAG = "ProotFastPath" - const val LIBRARY = "/usr/local/lib/libblfastpath.so" + const val LIBRARY = "/usr/local/lib/libddfastpath.so" const val MAX_BINDS = 256 fun allows(preference: Boolean, noSeccomp: Boolean, source: String, nativeUserland: Boolean = false): Boolean = diff --git a/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt b/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt index 32225c3f95..5300b24720 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/BottomDesktop.kt @@ -315,11 +315,11 @@ object BottomDesktop { main.post { if (generation == guestGeneration) watchIme(imeDir) } val binds = LinuxRuntime.binds(context, current.sessionRoot, runtime, Environment.getExternalStorageDirectory(), current.binds) val guest = ArrayList(current.guest).apply { - add("BL_WIDTH=$width") - add("BL_HEIGHT=$height") - add("BL_DEBUG_DIR=" + dir.path) - add("BL_TOP_SESSION=" + SessionState.mode) - add("BL_IME_DIR=" + imeDir.path) + add("DD_WIDTH=$width") + add("DD_HEIGHT=$height") + add("DD_DEBUG_DIR=" + dir.path) + add("DD_TOP_SESSION=" + SessionState.mode) + add("DD_IME_DIR=" + imeDir.path) add(SCRIPT) } val command = if (current.nativeUserland) { diff --git a/app/src/main/java/com/droiddeck/launcher/session/EsyncPacks.kt b/app/src/main/java/com/droiddeck/launcher/session/EsyncPacks.kt index 60044ccb84..a6d281701e 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/EsyncPacks.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/EsyncPacks.kt @@ -440,7 +440,7 @@ object EsyncPacks { fun enabled(context: Context): Boolean = SessionPrefs.syncFallback(context) || try { GameEnvironmentStore.read(context).let { config -> - (listOf(config.shared) + config.games.values).any { it["BL_SYNC_FALLBACK"] == "1" } + (listOf(config.shared) + config.games.values).any { it["DD_SYNC_FALLBACK"] == "1" } } } catch (t: Throwable) { false diff --git a/app/src/main/java/com/droiddeck/launcher/session/FexCatalog.kt b/app/src/main/java/com/droiddeck/launcher/session/FexCatalog.kt index d3471283e8..40fc1d323c 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/FexCatalog.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/FexCatalog.kt @@ -57,8 +57,8 @@ object FexCatalog { } fun environment(build: Build, sources: List = DownloadSource.candidates(build.url)): List = listOf( - "BL_FEX_TAG=${build.tag}", - "BL_FEX_SHA256=${build.sha256}", - "BL_FEX_URLS=" + sources.joinToString(" "), + "DD_FEX_TAG=${build.tag}", + "DD_FEX_SHA256=${build.sha256}", + "DD_FEX_URLS=" + sources.joinToString(" "), ) } diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt b/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt index 81dc109d67..d4bdce833e 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt @@ -2,6 +2,7 @@ package com.droiddeck.launcher.session import android.content.Context import android.util.AtomicFile +import android.util.Log import com.droiddeck.launcher.core.GameEnvironment import com.droiddeck.launcher.core.TextureFiltering import com.droiddeck.launcher.runtime.LinuxRuntime @@ -9,6 +10,7 @@ import org.json.JSONObject import java.io.File object GameEnvironmentStore { + private const val TAG = "GameEnvironmentStore" private const val SETTINGS = "game-environment.json" private const val GUEST_FILE = "root/.config/droiddeck/game-environment.json" const val DXVK_CONFIG = "dxvkConfig" @@ -19,7 +21,16 @@ object GameEnvironmentStore { fun read(context: Context): GameEnvironment.Config { val file = AtomicFile(File(context.filesDir, SETTINGS)) val bytes = try { file.readFully() } catch (_: java.io.FileNotFoundException) { return GameEnvironment.Config() } - return decode(JSONObject(bytes.toString(Charsets.UTF_8))) + return try { + decode(JSONObject(bytes.toString(Charsets.UTF_8))) + } catch (error: Exception) { + if (error !is org.json.JSONException && error !is IllegalArgumentException) throw error + val aside = File(context.filesDir, "$SETTINGS.unreadable") + Log.w(TAG, "game environment settings are unreadable, set aside as ${aside.name}", error) + aside.delete() + file.baseFile.renameTo(aside) + GameEnvironment.Config() + } } fun decode(json: JSONObject): GameEnvironment.Config { @@ -29,7 +40,8 @@ object GameEnvironmentStore { require(GameEnvironment.validName(name)) val entry = value.get(name) require(entry == JSONObject.NULL || entry is String && GameEnvironment.validValue(entry)) - put(name, if (entry == JSONObject.NULL) null else entry as String) + val current = GameEnvironment.currentName(name) + if (current == name || !value.has(current)) put(current, if (entry == JSONObject.NULL) null else entry as String) } } val games = json.optJSONObject("games") @@ -52,10 +64,9 @@ object GameEnvironmentStore { @Synchronized fun save(context: Context, config: GameEnvironment.Config) { - val json = encode(config) - decode(json) - write(File(context.filesDir, SETTINGS), json.toString()) - publish(context, config) + val normalized = decode(encode(config)) + write(File(context.filesDir, SETTINGS), encode(normalized).toString()) + publish(context, normalized) } @Synchronized diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameSaves.kt b/app/src/main/java/com/droiddeck/launcher/session/GameSaves.kt index 3a31da0113..a1491ff85a 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/GameSaves.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/GameSaves.kt @@ -25,7 +25,7 @@ object GameSaves { fun label(context: Context): String = context.getString(R.string.saves_layout_zip, app) } - data class Game(val game: Library.SteamGame, val prefix: File?, val saves: List) { + data class Game(val game: Library.SteamGame, val prefix: File?, val saves: List, val root: String? = null) { val launched get() = prefix?.let { File(it, "drive_c").isDirectory } == true } @@ -36,7 +36,28 @@ object GameSaves { fun savesDir(): File = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "DroidDeck/Saves") private fun backupsDir(): File = File(savesDir(), "backups") - fun game(game: Library.SteamGame): Game = Game(game, game.protonPrefix, game.protonPrefix?.let { locate(it, game) } ?: emptyList()) + fun game(context: Context, game: Library.SteamGame): Game { + val root = if (ubisoft(game)) ubisoftRoot(context, game) else null + val saves = game.protonPrefix?.let { prefix -> if (ubisoft(game)) root?.let { ubisoftSaves(prefix, it) }.orEmpty() else locate(prefix, game) }.orEmpty() + return Game(game, game.protonPrefix, saves, root) + } + + fun saves(context: Context, prefix: File, game: Library.SteamGame): List = + if (ubisoft(game)) ubisoftRoot(context, game)?.let { ubisoftSaves(prefix, it) }.orEmpty() else locate(prefix, game) + + private fun ubisoftRoot(context: Context, game: Library.SteamGame): String? { + val product = game.gameFiles?.let { com.droiddeck.launcher.stores.StoreGameSidecar.read(it) }?.extra?.get("productId")?.toLongOrNull() ?: return null + val user = com.droiddeck.launcher.stores.ubisoft.UbisoftAuth.load(context)?.userId + if (user.isNullOrEmpty() || user.contains('/') || user.contains("..")) return null + return "Saved Games/Ubisoft/$user/$product" + } + + private fun ubisoft(game: Library.SteamGame) = game.source == com.droiddeck.launcher.stores.Store.UBISOFT.id + + private fun ubisoftSaves(prefix: File, rel: String): List { + val files = File(profile(prefix), rel).walkTopDown().filter { it.isFile }.toList() + return if (files.isEmpty()) emptyList() else listOf(SaveDir(rel, files.size, files.sumOf { it.length() })) + } private val SAVE_ROOTS = listOf("Documents/My Games", "Saved Games", "AppData/Roaming", "Documents", "AppData/Local", "AppData/LocalLow") @@ -109,9 +130,11 @@ object GameSaves { fun export(context: Context, game: Game, layout: Layout, dir: File): Pair { val prefix = game.prefix ?: error(context.getString(R.string.saves_not_launched, game.game.name)) + val roots = game.saves.map { it.relPath } + if (roots.isEmpty() && ubisoft(game.game)) error(context.getString(R.string.saves_none_found, game.game.name)) dir.mkdirs() val out = File(dir, "${safe(game.game.name)}_${stamp()}.zip") - val count = zipProfile(profile(prefix), game.saves.map { it.relPath }.ifEmpty { null }, layout, out) + val count = zipProfile(profile(prefix), roots.ifEmpty { null }, layout, out) if (count == 0) { out.delete(); error(context.getString(R.string.saves_none_found, game.game.name)) } return out to count } @@ -142,12 +165,21 @@ object GameSaves { if (!driveC.isDirectory) error(context.getString(R.string.saves_not_launched, game.game.name)) if (!looksLikeSaveZip(zip)) error(context.getString(R.string.saves_not_save_zip, zip.name)) + val scoped = if (ubisoft(game.game)) game.root ?: error(context.getString(R.string.saves_none_found, game.game.name)) else null + if (scoped != null) { + val base = File(profile(prefix), scoped).canonicalFile + val eligible = ZipInputStream(BufferedInputStream(zip.inputStream())).use { zis -> + generateSequence { zis.nextEntry }.any { e -> !e.isDirectory && remap(e.name)?.let { File(driveC, it).canonicalFile.path.startsWith(base.path + File.separator) } == true } + } + if (!eligible) error(context.getString(R.string.saves_not_save_zip, zip.name)) + } backupsDir().mkdirs() - val backup = File(backupsDir(), "${safe(game.game.name)}_${stamp()}.zip") - val backedUp = zipProfile(profile(prefix), null, Layout.GAMEHUB, backup) + val backup = File(backupsDir(), "${safe(game.game.name)}_${stamp()}_${System.currentTimeMillis()}.zip") + val backedUp = if (scoped != null && File(profile(prefix), scoped).walkTopDown().none { it.isFile }) 0 + else zipProfile(profile(prefix), scoped?.let(::listOf), Layout.GAMEHUB, backup) if (backedUp == 0) backup.delete() - val base = driveC.canonicalFile + val base = (if (scoped != null) File(profile(prefix), scoped) else driveC).canonicalFile var written = 0 ZipInputStream(BufferedInputStream(zip.inputStream())).use { zis -> var e = zis.nextEntry diff --git a/app/src/main/java/com/droiddeck/launcher/session/GraphicsReport.kt b/app/src/main/java/com/droiddeck/launcher/session/GraphicsReport.kt index 8caa1e6f8e..c84d8353d3 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/GraphicsReport.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/GraphicsReport.kt @@ -34,8 +34,8 @@ object GraphicsReport { /** The guest keys the report repeats: everything that decides which Vulkan driver loads. */ private val ENV_PREFIXES = listOf( - "VK_", "BL_VK", "BL_DRM", "BL_VKBRIDGE", "VKBRIDGE", "MESA_", "GALLIUM_", "ZINK", "TU_", "PANVK", - "DROIDDECK_POWERVR", "DROIDDECK_HYBRIS", "BL_GAME_LOGS", "LIBGL_", "GAMESCOPE_DISABLE", "XWAYLAND", + "VK_", "DD_VK", "DD_DRM", "DD_VKBRIDGE", "VKBRIDGE", "MESA_", "GALLIUM_", "ZINK", "TU_", "PANVK", + "DROIDDECK_POWERVR", "DROIDDECK_HYBRIS", "DD_GAME_LOGS", "LIBGL_", "GAMESCOPE_DISABLE", "XWAYLAND", ) /** Per-game graphics logs and the guest's Vulkan summary: on for a non-Adreno GPU, or by Setup's switch. */ diff --git a/app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt b/app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt new file mode 100644 index 0000000000..849c0aafcc --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/KeepTopActivity.kt @@ -0,0 +1,91 @@ +package com.droiddeck.launcher.session + +import android.app.Activity +import android.app.ActivityOptions +import android.content.Context +import android.content.Intent +import android.hardware.display.DisplayManager +import android.os.Bundle +import android.os.SystemClock +import android.util.Log +import android.view.Display +import android.view.WindowManager + +// While a session runs, sits invisibly on top of every other display until it ends, so +// that display's home launcher is not its top activity. lmkd kills the launcher first; restarted as a +// top activity it takes focus from the session, which then drops to adj 50 and is killed next. +class KeepTopActivity : Activity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + @Suppress("DEPRECATION") overridePendingTransition(0, 0) + if (intent.getBooleanExtra(EXTRA_BOUNCE, false)) { + bounces++ + finish() + return + } + if (intent.getIntExtra(EXTRA_GENERATION, -1) != generation) { + finishAndRemoveTask() + return + } + window.addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE) + val id = display?.displayId ?: Display.INVALID_DISPLAY + starting.remove(id) + guards[id]?.takeIf { it !== this && !it.isFinishing }?.finishAndRemoveTask() + guards[id] = this + } + + override fun onDestroy() { + guards.values.remove(this) + super.onDestroy() + } + + companion object { + private const val TAG = "KeepTop" + private const val EXTRA_BOUNCE = "bounce" + private const val EXTRA_GENERATION = "generation" + private var generation = 0 + var bounces = 0 + private set + private val guards = HashMap() + private const val START_TIMEOUT_MS = 2_000L + private val starting = HashMap() + + fun guardOtherDisplays(context: Context, sessionDisplay: Int): Boolean { + val displays = context.getSystemService(DisplayManager::class.java)?.displays ?: return false + var started = false + for (display in displays) { + val id = display.displayId + if (id == sessionDisplay || display.state != Display.STATE_ON || guards[id]?.isFinishing == false || + starting[id]?.let { SystemClock.elapsedRealtime() - it < START_TIMEOUT_MS } == true) continue + runCatching { + launch(context, id, bounce = false) + starting[id] = SystemClock.elapsedRealtime() + started = true + Log.i(TAG, "guarding display $id from a home launcher restart") + }.onFailure { Log.w(TAG, "could not guard display $id", it) } + } + if (!started) return false + return runCatching { launch(context, sessionDisplay, bounce = true) } + .onFailure { Log.w(TAG, "could not return focus to display $sessionDisplay", it) }.isSuccess + } + + fun hasPendingStarts() = starting.isNotEmpty() + + const val RETRY_MS = START_TIMEOUT_MS + 250 + + fun release() { + generation++ + guards.values.toList().forEach { it.finishAndRemoveTask() } + guards.clear() + starting.clear() + } + + private fun launch(context: Context, displayId: Int, bounce: Boolean) { + val intent = Intent(context, KeepTopActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION) + .putExtra(EXTRA_BOUNCE, bounce) + .putExtra(EXTRA_GENERATION, generation) + context.startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle()) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/LightPause.kt b/app/src/main/java/com/droiddeck/launcher/session/LightPause.kt new file mode 100644 index 0000000000..6ac1eabf9f --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/LightPause.kt @@ -0,0 +1,32 @@ +package com.droiddeck.launcher.session + +// Tracks a pause that skipped the session's departure cleanup for the keep-top focus bounce. +internal class LightPause { + private var pending = false + private var bouncesAtPause = 0 + + fun paused(bounces: Int) { + pending = true + bouncesAtPause = bounces + } + + // The bounce resumes the session within tens of milliseconds; still paused at the timeout means + // something else holds the pause. + fun timedOut(): Boolean = take() + + fun stopped(): Boolean = take() + + fun resumed(bounces: Int): Resume { + if (!pending) return Resume.NORMAL + pending = false + return if (bounces != bouncesAtPause) Resume.LIGHT else Resume.CLEANUP_FIRST + } + + private fun take(): Boolean { + val was = pending + pending = false + return was + } + + enum class Resume { NORMAL, LIGHT, CLEANUP_FIRST } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt index e75c10d118..aaaac49a8e 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/ProtonExtras.kt @@ -45,7 +45,7 @@ object ProtonExtras { fun offered(context: Context): List = tools.filter { it.id != BIONIC || NativeGuest.enabled(context) } private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root") - private fun requests(context: Context) = File(home(context), ".bl-proton-extra") + private fun requests(context: Context) = File(home(context), ".dd-proton-extra") private fun toolsDir(context: Context) = File(home(context), ".local/share/Steam/compatibilitytools.d") private fun releasesFile(context: Context) = File(context.filesDir, "proton-extras.json") private fun latestFile(context: Context) = File(context.filesDir, "proton-latest.json") diff --git a/app/src/main/java/com/droiddeck/launcher/session/QuestExperimental.kt b/app/src/main/java/com/droiddeck/launcher/session/QuestExperimental.kt index dc992c5bfc..3fe95fc815 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/QuestExperimental.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/QuestExperimental.kt @@ -68,7 +68,7 @@ object QuestExperimental { appendLine("driverMode=${SessionPrefs.gpuDriverMode(context)}") appendLine("androidDriver=${SessionPrefs.androidDriver(context)}") appendLine("steamSurfaceControlWorkaround=${SessionPrefs.hdr(context, "steam")}") - appendLine("GPUOBJ fallback installed in Android driver and ARM64 libblsession") + appendLine("GPUOBJ fallback installed in Android driver and ARM64 libddsession") appendLine("Experimental Quest 2/3/3S compatibility; 2D panel application") } Log.i(TAG, report) 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 3ac0ef8ab6..2b4744574f 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionArtifacts.kt @@ -544,6 +544,7 @@ object SessionArtifacts { "session died of a crash, the entry is in there unless the device rebooted.\n" + (if (newest) exitReasons(context) else "") ) + restartNote(File(dir, "device.txt").lastModified(), bootedAt())?.let { recoveryNote.appendText(it) } if (newest && lastExitForMemory(context)) killedForMemory = true } if (recoveryPreviouslyAttempted && !runtimeCaptured.exists() && @@ -597,7 +598,7 @@ object SessionArtifacts { } val memoryLog = File(dir, "memory-pressure.log") if (newest && !memoryLog.exists()) { - SessionLogCapture.dumpMemoryPressure(memoryLog) + SessionLogCapture.dumpMemoryPressure(memoryLog, context) } if (stopWhenSessionStarts && SessionState.running) { record.failed = true @@ -686,5 +687,21 @@ object SessionArtifacts { return gone.size } + private fun bootedAt(): Long = System.currentTimeMillis() - android.os.SystemClock.elapsedRealtime() + + internal fun restartNote(sessionStartedAt: Long, bootedAt: Long): String? { + if (sessionStartedAt <= 0L) return null + val stamp = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US) + return if (bootedAt > sessionStartedAt + BOOT_CLOCK_SLACK_MS) { + "The device itself probably restarted after this session began (estimated boot ${stamp.format(Date(bootedAt))}, from the clock and uptime, so a clock change can fake it):\n" + + "if so, the whole system went down and crash.log is the new boot's buffer and says nothing about the session.\n" + } else { + "The device does not appear to have restarted since this session began (estimated boot ${stamp.format(Date(bootedAt))}, from the clock and uptime):\n" + + "only this app's processes ended, so crash.log and the exit records cover the end.\n" + } + } + + private const val BOOT_CLOCK_SLACK_MS = 60_000L + private fun now(): String = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).format(Date()) } 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 7b3e520907..9501915fe5 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionFiles.kt @@ -109,11 +109,11 @@ object SessionFiles { "usr/local/bin/droiddeck-steam-compat" to "usr/local/bin/droiddeck-steam-compat", "usr/local/bin/droiddeck-steam-taskset" to "usr/local/libexec/droiddeck-steam/taskset", "usr/local/bin/droiddeck-fex" to "usr/local/bin/droiddeck-fex", - "libblsession.so" to "usr/local/lib/libblsession.so", + "libddsession.so" to "usr/local/lib/libddsession.so", "libfakeinput.so" to "usr/local/lib/libfakeinput.so", - "libblfastpath.so" to "usr/local/lib/libblfastpath.so", + "libddfastpath.so" to "usr/local/lib/libddfastpath.so", "libddnatv-hook.so" to "usr/lib/libddnatv-hook.so", - "libblaudit.so" to "usr/local/lib/libblaudit.so", + "libddaudit.so" to "usr/local/lib/libddaudit.so", "libssbs.so" to "usr/local/lib/libssbs.so", "usr/local/bin/droiddeck-session" to "usr/local/bin/droiddeck-session", "usr/local/bin/droiddeck-fonts" to "usr/local/bin/droiddeck-fonts", @@ -238,7 +238,7 @@ object SessionFiles { "usr/local/lib/droiddeck-gpuload/VK_LAYER_DROIDDECK_vram_cap.json" to "usr/share/vulkan/implicit_layer.d/droiddeck_vram_cap.json", ) val fexPreloads = listOf("x86_64", "i386").flatMap { arch -> - listOf("libblsession.so", "libfakeinput.so", "libfaultreport.so").map { "$arch/$it" to "usr/local/lib/droiddeck-fex/$arch/$it" } + listOf("libddsession.so", "libfakeinput.so", "libfaultreport.so").map { "$arch/$it" to "usr/local/lib/droiddeck-fex/$arch/$it" } } + listOf("libvulkan-thunk.so", "libwebkitinput.so").map { "x86_64/$it" to "usr/local/lib/droiddeck-fex/x86_64/$it" } // The Mali compatibility layer (tools/venus/layer, David Cimo): an implicit Vulkan layer that // fills in the features DXVK requires and Mali lacks. Idle outside Wine and on GPUs that have them. @@ -315,7 +315,7 @@ object SessionFiles { for (pack in SERVICE_PACKS.keys) stageStoreService(context, root, pack, ledger) 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") + val preload = StringBuilder("/usr/local/lib/libddsession.so\n") if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) { preload.append("/usr/local/lib/libfakeinput.so\n") } 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 f6e563815d..ed23e31bc3 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -203,18 +203,6 @@ object SessionPrefs { prefs(context).edit().putBoolean("androidTextFieldKeyboard", on).apply() } - fun gameStoresEnabled(context: Context): Boolean = prefs(context).getBoolean("gameStoresEnabled", true) - - fun setGameStoresEnabled(context: Context, on: Boolean) { - prefs(context).edit().putBoolean("gameStoresEnabled", on).apply() - } - - fun soundtracksEnabled(context: Context): Boolean = prefs(context).getBoolean("soundtracksEnabled", true) - - fun setSoundtracksEnabled(context: Context, on: Boolean) { - prefs(context).edit().putBoolean("soundtracksEnabled", on).apply() - } - fun soundtracksIngame(context: Context): Boolean = prefs(context).getBoolean("soundtracksIngame", false) fun setSoundtracksIngame(context: Context, on: Boolean) { @@ -267,16 +255,55 @@ object SessionPrefs { prefs(context).edit().putBoolean("libraryShowSize", show).apply() } + fun libraryShowHidden(context: Context): Boolean = prefs(context).getBoolean("libraryShowHidden", false) + + fun setLibraryShowHidden(context: Context, show: Boolean) { + prefs(context).edit().putBoolean("libraryShowHidden", show).apply() + } + + fun libraryHidden(context: Context): Set = prefs(context).getStringSet("libraryHidden", null)?.toSet().orEmpty() + + fun setLibraryHidden(context: Context, keys: Set) { + prefs(context).edit().putStringSet("libraryHidden", keys.toSet()).apply() + } + fun railLabels(context: Context): Boolean = prefs(context).getBoolean("railLabels", false) fun setRailLabels(context: Context, show: Boolean) { prefs(context).edit().putBoolean("railLabels", show).apply() } - fun agentTab(context: Context): Boolean = prefs(context).getBoolean("agentTab", false) + fun developerTools(context: Context): Boolean = + prefs(context).getBoolean("developerTools", com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(context)) - fun setAgentTab(context: Context, show: Boolean) { - prefs(context).edit().putBoolean("agentTab", show).apply() + fun setDeveloperTools(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("developerTools", on).apply() + } + + fun fpsLimitKey(mode: String?, game: String?): String? = when (mode) { + SessionService.MODE_RUN -> game?.trim()?.takeIf(com.droiddeck.launcher.frontend.GameLaunchLink::validId)?.let { "fpsLimit.game.$it" } + SessionService.MODE_DESKTOP -> "fpsLimit.desktop" + else -> null + } + + fun savedFpsLimit(context: Context, key: String?): Int = key?.let { prefs(context).getInt(it, 0) } ?: 0 + + fun saveFpsLimit(context: Context, key: String?, fps: Int) { + key ?: return + prefs(context).edit().apply { if (fps > 0) putInt(key, fps) else remove(key) }.apply() + } + + fun drawerCornerTap(context: Context): Boolean = + prefs(context).getBoolean("drawerCornerTap", android.os.Build.MANUFACTURER.equals("Oculus", true) || android.os.Build.MANUFACTURER.equals("Meta", true)) + + fun setDrawerCornerTap(context: Context, on: Boolean) { + prefs(context).edit().putBoolean("drawerCornerTap", on).apply() + } + + fun drawerHintShown(context: Context): Int = prefs(context).getInt("drawerHintShown", 0) + + fun countDrawerHint(context: Context) { + prefs(context).edit().putInt("drawerHintShown", drawerHintShown(context) + 1).apply() } fun libraryShowUninstalled(context: Context): Boolean = prefs(context).getBoolean("libraryShowUninstalled", false) @@ -291,8 +318,36 @@ object SessionPrefs { prefs(context).edit().putStringSet("libraryFavorites", keys.toSet()).apply() } + fun storesTabOrderCustomized(context: Context): Boolean = + prefs(context).getBoolean("storesTabOrderCustomized", false) + + fun setStoresTabOrderCustomized(context: Context, customized: Boolean) { + prefs(context).edit().putBoolean("storesTabOrderCustomized", customized).apply() + } + fun storesTabOrder(context: Context): List = idList(prefs(context).getString("storesTabOrder", null)) + /** An order nobody arranged stays unsaved, so it keeps following the default. */ + fun saveStoresTabs(context: Context, order: List, hidden: Set, arranged: Boolean) { + if (arranged) setStoresTabOrderCustomized(context, true) + if (storesTabOrderCustomized(context)) setStoresTabOrder(context, order) + setStoresTabHidden(context, hidden) + } + + private val LEGACY_STORES_TAB_ORDER = listOf("gog", "epic", "amazon", "xbox", "itch", "gamejolt", "battlenet", "ubisoft", "ea", "rockstar") + + /** + * Forgets an order the user never arranged, so the Stores tabs and Library pills follow whatever the default is now. + * Earlier versions saved the default of their day, which is why a saved order alone does not mean the user chose it. + */ + fun settleStoresTabOrder(context: Context, defaults: List) { + if (storesTabOrderCustomized(context)) return + val saved = storesTabOrder(context) + if (saved.isEmpty()) return + if (saved == LEGACY_STORES_TAB_ORDER || saved == defaults) prefs(context).edit().remove("storesTabOrder").apply() + else setStoresTabOrderCustomized(context, true) + } + fun setStoresTabOrder(context: Context, order: List) { prefs(context).edit().putString("storesTabOrder", order.joinToString(",")).apply() } @@ -309,13 +364,35 @@ object SessionPrefs { prefs(context).edit().putString("navTabOrder", order.joinToString(",")).apply() } - fun navTabShelved(context: Context): Set = idList(prefs(context).getString("navTabShelved", "soundtracks,agent")).toSet() + fun navTabShelved(context: Context): Set? = prefs(context).getString("navTabShelved", null)?.let { idList(it).toSet() } fun setNavTabShelved(context: Context, keys: Set) { prefs(context).edit().putString("navTabShelved", keys.joinToString(",")).apply() } - fun navTabHidden(context: Context): Set = idList(prefs(context).getString("navTabHidden", null)).toSet() + fun navTabHidden(context: Context): Set? = prefs(context).getString("navTabHidden", null)?.let { idList(it).toSet() } + + fun navTabLayoutVersion(context: Context): Int = prefs(context).getInt("navTabLayout", 0) + + class LegacyTabSwitches(val touched: Boolean, val stores: Boolean, val soundtracks: Boolean, val agent: Boolean) + + fun legacyTabSwitches(context: Context): LegacyTabSwitches { + val p = prefs(context) + val keys = listOf("navTabOrder", "navTabShelved", "navTabHidden", "gameStoresEnabled", "soundtracksEnabled", "agentTab") + return LegacyTabSwitches( + touched = keys.any { p.contains(it) }, + stores = p.getBoolean("gameStoresEnabled", true), + soundtracks = p.getBoolean("soundtracksEnabled", true), + agent = p.getBoolean("agentTab", false) && p.getBoolean("developerTools", true), + ) + } + + fun finishTabSwitchMigration(context: Context, version: Int) { + val p = prefs(context) + val e = p.edit() + if (!p.contains("developerTools") && p.getBoolean("agentTab", false)) e.putBoolean("developerTools", true) + e.remove("gameStoresEnabled").remove("soundtracksEnabled").remove("agentTab").putInt("navTabLayout", version).apply() + } fun setNavTabHidden(context: Context, keys: Set) { prefs(context).edit().putString("navTabHidden", keys.joinToString(",")).apply() @@ -620,14 +697,42 @@ object SessionPrefs { } @JvmStatic - fun ensurePowerVrAutoDrivers(context: Context) { - if (com.droiddeck.launcher.core.DeviceSupport.openDriverActive(context)) return - ensurePowerVrAutoDrivers(context, SystemVulkanDriver.isPowerVr()) + fun ensurePowerVrAutoDrivers(context: Context) = reconcilePowerVrAutoDrivers( + context, SystemVulkanDriver.isPowerVr(), SystemVulkanDriver.isXclipse(), + com.droiddeck.launcher.gpu.VulkanInfo::cachedOrNull, + ) + + fun ensurePowerVrAutoDriversAfterGpuQuery(context: Context) = reconcilePowerVrAutoDrivers( + context, SystemVulkanDriver.isPowerVr(), SystemVulkanDriver.isXclipse(), + com.droiddeck.launcher.gpu.VulkanInfo::query, + ) + + internal fun reconcilePowerVrAutoDrivers( + context: Context, powerVr: Boolean, xclipse: Boolean, vulkan: () -> Map?, + ) { + val device = if (xclipse) vulkan() ?: return else null + val unsupported = unsupportedXclipse(xclipse) { + com.droiddeck.launcher.gpu.GpuInfo.systemDriverName(SystemVulkanDriver.gpuName(), device) + } + val activeKey = com.droiddeck.launcher.gpu.DriverBundle.active(context) + ?.id + ?.let(com.droiddeck.launcher.gpu.DriverPairs::nonAdreno) + val upstreamBundle = activeKey == com.droiddeck.launcher.gpu.DriverPairs.NAD_RADV_XCLIPSE_UPSTREAM || + (activeKey != null && activeKey.startsWith("${com.droiddeck.launcher.gpu.DriverPairs.NAD_RADV_XCLIPSE_UPSTREAM}-")) + if (com.droiddeck.launcher.core.DeviceSupport.openDriverActive(context) && (!unsupported || upstreamBundle)) return + ensurePowerVrAutoDrivers(context, powerVr, unsupported) } - internal fun ensurePowerVrAutoDrivers(context: Context, powerVr: Boolean) { + internal fun unsupportedXclipse(xclipse: Boolean, gpuName: () -> String): Boolean = + xclipse && com.droiddeck.launcher.gpu.DriverPairs.xclipseNeedsUpstream(gpuName()) + + internal fun ensurePowerVrAutoDrivers(context: Context, powerVr: Boolean, autoOwnedOnly: Boolean = false) { if (!powerVr || gpuDriverMode(context) != GPU_DRIVERS_AUTO) return - prefs(context).edit().putString("linuxDriver", "").putString("androidDriver", TurnipDriver.AUTO).apply() + val owned = gpuAutoInstalled(context) + val edit = prefs(context).edit() + if (!autoOwnedOnly || linuxDriver(context) in owned) edit.putString("linuxDriver", "") + if (!autoOwnedOnly || androidDriver(context) in owned) edit.putString("androidDriver", TurnipDriver.AUTO) + edit.apply() } fun gpuAutoInstalled(context: Context): Set = @@ -661,7 +766,7 @@ object SessionPrefs { } private fun shaderPrecacheApplied(context: Context) = - java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.bl-shader-precache-applied") + java.io.File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(context), "root/.dd-shader-precache-applied") fun pendingShaderPrecache(context: Context): Boolean? { val prefs = prefs(context) @@ -1379,6 +1484,8 @@ object SessionPrefs { (id and 0xFFFFFFFFL) to key.removePrefix("addedAppId:") }.toMap() + fun storeGameFolder(context: Context, key: String): String? = prefs(context).getString("storeFolder:$key", null) + fun followStoreGame(context: Context, key: String, folderPath: String, gone: (String) -> Boolean) = synchronized(addedGameLock) { val p = prefs(context) val previous = p.getString("storeFolder:$key", null) @@ -1493,7 +1600,7 @@ object SessionPrefs { } val upscalerChoices = listOf( - 0 to "Linear", 2 to "Nearest", 4 to "AMD FSR 1", 3 to "Snapdragon GSR", + 2 to "Nearest", 0 to "Linear", 4 to "AMD FSR 1", 3 to "Snapdragon GSR", 8 to "Snapdragon GSR (quality)", 7 to "NVIDIA NIS", 6 to "Sharpen only", ) @@ -1508,12 +1615,12 @@ object SessionPrefs { fun canonicalUpscaler(mode: Int): Int = when (mode) { 1 -> 0 5 -> 4 - else -> mode.takeIf { m -> upscalerChoices.any { it.first == m } } ?: 0 + else -> mode.takeIf { m -> upscalerChoices.any { it.first == m } } ?: 2 } fun upscalerHasSharpness(mode: Int): Boolean = canonicalUpscaler(mode) in 3..8 - fun upscaler(context: Context): Int = canonicalUpscaler(prefs(context).getInt("upscaler", 0)) + fun upscaler(context: Context): Int = canonicalUpscaler(prefs(context).getInt("upscaler", 2)) fun setUpscaler(context: Context, mode: Int) { prefs(context).edit().putInt("upscaler", canonicalUpscaler(mode)).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 a0d73a28db..d5dd4fa0ac 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionService.kt @@ -411,6 +411,7 @@ class SessionService : Service() { ?.takeIf(GameLaunchLink::validId) ?: steamUrlGameId SessionState.gameId = resolvedGameId + SessionState.fpsLimit = SessionPrefs.savedFpsLimit(this, SessionPrefs.fpsLimitKey(SessionState.mode, resolvedGameId)) SessionPrefs.setActiveScreenEffectsProfile( this, SessionPrefs.screenEffectsProfileId(SessionState.mode, resolvedGameId, SessionState.program), @@ -496,7 +497,7 @@ class SessionService : Service() { private fun runSession(gen: Int) { - SessionPrefs.ensurePowerVrAutoDrivers(this) + SessionPrefs.ensurePowerVrAutoDriversAfterGpuQuery(this) if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) { com.droiddeck.launcher.gpu.VulkanInfo.query()["api"]?.let { SessionPrefs.setHostVulkanApi(this, it) } if (SessionPrefs.venus(this)) VenusComponent.hostVulkanTooOld(this)?.let { @@ -565,10 +566,19 @@ class SessionService : Service() { SessionFiles.stage(this, root, startsSession = true) } catch (error: Exception) { Log.e(TAG, "Could not prepare the session graphics runtime", error) + failSession(gen, "GRAPHICS_RUNTIME_FAILED", getString(R.string.session_graphics_runtime_failed), -1) stopSession(-1, gen) return } + if (!stillStarting()) { + Log.i(TAG, "session stopped while its files were staging") + return + } SessionArtifacts.awaitCollections() + if (!stillStarting()) { + Log.i(TAG, "session stopped while earlier session logs were being collected") + return + } SessionArtifacts.finishAbandoned(this, beforeGuestStart = true) VacDiagnostics.arm(this) com.droiddeck.launcher.agent.AgentGuest.reset(this) @@ -580,7 +590,9 @@ class SessionService : Service() { SessionEvents.step("game-environment") { GameEnvironmentStore.publish(this) } } catch (e: Exception) { Log.e(TAG, "could not publish the game environment", e) + failSession(gen, "GAME_ENVIRONMENT_FAILED", getString(R.string.session_game_environment_failed), -1) stopSession(-1, gen) + abandonStart(gen, sessionDir) return } val sessionLog = File(sessionDir, "session.log") @@ -609,9 +621,10 @@ class SessionService : Service() { Log.e(TAG, "Could not resolve the selected Linux Vulkan driver", e) failSession(gen, "VULKAN_DRIVER_UNAVAILABLE", e.message ?: "Selected Linux Vulkan driver is unavailable", -1) stopSession(-1, gen) + abandonStart(gen, sessionDir) return } - if (steamHere) guest.add("BL_EPIC_APP_ID=" + com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId) + if (steamHere) guest.add("DD_EPIC_APP_ID=" + com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId) val fastPathAt = guest.size val pulse = SessionEvents.step("audio") { startAudio(guest, sessionDir, directAudioPack) } @@ -623,36 +636,36 @@ class SessionService : Service() { val encoder = VideoEncodeBridge(File(filesDir, "venc/venc.sock")) encoder.attach(this) components.add(encoder) - guest.add("BL_VENC_SOCKET=" + encoder.socket.absolutePath) + guest.add("DD_VENC_SOCKET=" + encoder.socket.absolutePath) } com.droiddeck.launcher.gpu.ClockLogComponent(File(sessionDir, "clocks.log")).let { it.attach(this) components.add(it) } - guest.add("BL_WIDTH=" + size.first) - guest.add("BL_HEIGHT=" + size.second) + guest.add("DD_WIDTH=" + size.first) + guest.add("DD_HEIGHT=" + size.second) if (noSteamGame()) runCatching { val scope = NoSteamLaunch.scopeOf(SessionState.program, SessionState.programArgs) { NoSteamLaunch.battleNetTitleScope(this, it) } NoSteamLaunch.resolution(GameEnvironmentStore.read(this), scope, size) }.onFailure { Log.w(TAG, "game resolution", it) }.getOrNull()?.let { (w, h) -> - guest.add("BL_GAME_WIDTH=$w") - guest.add("BL_GAME_HEIGHT=$h") + guest.add("DD_GAME_WIDTH=$w") + guest.add("DD_GAME_HEIGHT=$h") Log.i(TAG, "game resolution: ${w}x$h on a ${size.first}x${size.second} output") } if (SessionState.followScreen || size.first < size.second || SessionPrefs.orientation(this) == android.content.pm.ActivityInfo.SCREEN_ORIENTATION_USER) - guest.add("BL_FOLLOW_OUTPUT=1") + guest.add("DD_FOLLOW_OUTPUT=1") if (SessionState.hdr) { - guest.add("BL_HDR=1") + guest.add("DD_HDR=1") guest.add("DXVK_HDR=1") Log.i(TAG, "hdr: gamescope --hdr-enabled, DXVK_HDR=1") } guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=100") guest.add("WINE_OFFSCREEN_CHECK_MS=100") - guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz)) - guest.add("BL_LOG=" + sessionLog.path) - guest.add("BL_DEBUG_DIR=" + sessionDir.path) + guest.add("DD_REFRESH=" + Math.round(SessionState.refreshHz)) + guest.add("DD_LOG=" + sessionLog.path) + guest.add("DD_DEBUG_DIR=" + sessionDir.path) if (EnhancedDiagnostics.isActive(this, sessionDir)) guest.add("DROIDDECK_ENHANCED_DIAGNOSTICS=1") val fakeInputDir = File(sessionRoot, "dev/input").apply { mkdirs() } @@ -665,7 +678,7 @@ class SessionService : Service() { SessionEvents.step("controller-sync") { SessionState.padBridge?.syncConnectedControllers() } } val noSteamGame = noSteamGame() - if (noSteamGame) guest.add("BL_PIN_CORES=0") + if (noSteamGame) guest.add("DD_PIN_CORES=0") if ((steamHere || SessionState.program == NoSteamLaunch.EPIC) && com.droiddeck.launcher.stores.epic.EpicClient.read(this).installed) { runCatching { SessionEvents.step("epic-library") { com.droiddeck.launcher.stores.epic.EpicClientLibrary.sync(this) } } .onFailure { Log.w(TAG, "Epic library sync failed", it) } @@ -675,17 +688,19 @@ class SessionService : Service() { if (steamHere || noSteamGame) { val added = SessionEvents.step("added-games-scan") { com.droiddeck.launcher.frontend.AddedGames.scan(this) } val listing = SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) } - guest.add("BL_ADDED_GAMES=" + listing.path) - if (OfflineMode.enabled(this)) guest.add("BL_STEAM_OFFLINE=1") - if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("BL_LOSSLESS_OWNED=1") + guest.add("DD_ADDED_GAMES=" + listing.path) + if (OfflineMode.enabled(this)) guest.add("DD_STEAM_OFFLINE=1") + if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("DD_LOSSLESS_OWNED=1") if (added.isNotEmpty()) Log.i(TAG, "added games: " + added.joinToString { "${it.name} (${it.exe.name})" }) } + guest.add("DD_LAUNCH_DIR=" + sessionRoot.path) + // Proton builds up to 11.12 report X11 text fields under this name. guest.add("BL_LAUNCH_DIR=" + sessionRoot.path) - GameStorage.effective(this)?.let { guest.add("BL_LIBRARY_LABEL=" + it.label.replace('"', ' ')) } - if (SessionState.mode == MODE_STEAM && SessionState.steamUi == "desktop") guest.add("BL_STEAM_UI=desktop") + GameStorage.effective(this)?.let { guest.add("DD_LIBRARY_LABEL=" + it.label.replace('"', ' ')) } + if (SessionState.mode == MODE_STEAM && SessionState.steamUi == "desktop") guest.add("DD_STEAM_UI=desktop") // Detailed graphics logs: per-game logs and the guest's Vulkan summary (a GPU that is not // an Adreno, or Setup's switch), and graphics-report.txt for every session. - if (GraphicsReport.detailed(this)) guest.add("BL_GAME_LOGS=1") + if (GraphicsReport.detailed(this)) guest.add("DD_GAME_LOGS=1") SessionEvents.step("graphics-report") { GraphicsReport.begin(this, sessionDir, guest) } val shellGuest = ArrayList(guest).apply { add("SHELL=/bin/bash") @@ -707,6 +722,7 @@ class SessionService : Service() { if (program.isNullOrEmpty()) { Log.e(TAG, "run mode without a program") stopSession(65, gen) + abandonStart(gen, sessionDir) return } guest.add(program) @@ -802,15 +818,25 @@ class SessionService : Service() { components.add(deviceControls) if (gen != sessionGen || !SessionState.running) { Log.i(TAG, "session stopped while it was starting; not launching it") - if (gen == sessionGen) components.clear() + abandonStart(gen, sessionDir) return } + val started = ArrayList() try { - components.forEach { it.start() } + for (part in components.toList()) { + if (!stillStarting()) { + Log.i(TAG, "session stopped while its components were starting; stopping the ${started.size} already started") + abandonStart(gen, sessionDir, started) + return + } + started.add(part) + part.start() + } } catch (e: Exception) { Log.e(TAG, "Could not start the session components", e) failSession(gen, "COMPONENT_START_FAILED", e.message ?: "Session component could not be started", -1) stopSession(-1, gen) + abandonStart(gen, sessionDir, started) return } @@ -837,9 +863,8 @@ class SessionService : Service() { launchWatcher = null syncWatcher?.stopWatching() syncWatcher = null - components.reversed().forEach { runCatching { it.stop() } } - components.clear() } + abandonStart(gen, sessionDir, started) if (pid > 1) Thread({ teardown(pid) }, "session-teardown").start() return } @@ -851,6 +876,7 @@ class SessionService : Service() { SessionEvents.record("guest.start_failed", mapOf("pid" to pid)) failSession(gen, "GUEST_START_FAILED", "The guest process could not be started", pid) stopSession(-1, gen) + abandonStart(gen, sessionDir, started) return } if (gen == sessionGen && SessionState.running) { @@ -872,8 +898,8 @@ class SessionService : Service() { if (!pulse.setSinkSuspended(false)) Log.w(TAG, "could not resume audio sink") if (!pulse.setMicSuspended(false)) Log.w(TAG, "could not resume microphone source") }, - zramControl = File(filesDir, "${LinuxRuntime.DIR}/tmp/.bl-zram"), - clockControl = File(filesDir, "${LinuxRuntime.DIR}/tmp/.bl-clock"), + zramControl = File(filesDir, "${LinuxRuntime.DIR}/tmp/.dd-zram"), + clockControl = File(filesDir, "${LinuxRuntime.DIR}/tmp/.dd-clock"), mapClockControl = { WaylandCompositor.nativeSetClockControl(it.path) }, pagedOut = { processes, unacknowledged, residentKb, swapKb, swapBeforeKb, millis -> Log.i(TAG, "paged out $processes processes ($unacknowledged unacknowledged) in $millis ms: " + @@ -905,6 +931,30 @@ class SessionService : Service() { } } + private fun abandonStart(gen: Int, sessionDir: File, started: List = emptyList()) { + val (ended, endedArch) = synchronized(stopLock) { + if (gen != sessionGen || SessionState.running) return + components.clear() + GpuClockPin.stop(this) + GameThreadHints.stop() + com.droiddeck.launcher.stores.StoreLaunchRequests.stop() + MemoryLog.stop() + val ended = synchronized(SessionPaths) { + if (SessionPaths.current() == sessionDir) SessionPaths.take() else null + } + if (ended != null) SessionArtifacts.collectionStarted(ended) + ended to SessionState.steamClientArch + } + started.asReversed().forEach { + try { + it.stop() + } catch (e: Exception) { + Log.w(TAG, "stopping ${it.javaClass.simpleName}", e) + } + } + if (ended != null) Thread({ collectSessionArtifacts(ended, endedArch) }, "session-collect").start() + } + private fun openSessionFolder(): File { val sessionDir = SessionPaths.beginOrCurrent(this) val sessionLog = File(sessionDir, "session.log") @@ -942,16 +992,16 @@ class SessionService : Service() { } else { guest.add("LANG=C.UTF-8") } - guest.add("BL_STEAM_LANGUAGE=" + SteamLanguage.forLocale( + guest.add("DD_STEAM_LANGUAGE=" + SteamLanguage.forLocale( com.droiddeck.launcher.core.AppLanguage.effective(this), com.droiddeck.launcher.core.AppLanguage.system(this).country, )) guest.add("TZ=" + java.util.TimeZone.getDefault().id) - if (SessionState.mode == MODE_STEAM) SessionPrefs.pendingShaderPrecache(this)?.let { guest.add("BL_SHADER_PRECACHE=" + if (it) "1" else "0") } + if (SessionState.mode == MODE_STEAM) SessionPrefs.pendingShaderPrecache(this)?.let { guest.add("DD_SHADER_PRECACHE=" + if (it) "1" else "0") } guest.add("XDG_RUNTIME_DIR=" + LinuxRuntime.GUEST_RUNTIME_DIR) guest.add("XDG_SESSION_TYPE=wayland") guest.add("WAYLAND_DISPLAY=wayland-0") - guest.add("BL_ANDROID_CLIPBOARD=" + File(filesDir, "session/android-clipboard").path) + guest.add("DD_ANDROID_CLIPBOARD=" + File(filesDir, "session/android-clipboard").path) guest.add("GAMESCOPE_FORCE_GENERAL_QUEUE=1") guest.add("MESA_LOADER_DRIVER_OVERRIDE=zink") guest.add("GALLIUM_DRIVER=zink") @@ -983,7 +1033,7 @@ class SessionService : Service() { guest.add("XWAYLAND_NO_GLAMOR=1") Log.w(TAG, "xwayland: the last session's Xwayland crashed; glamor off for this one (XWAYLAND_NO_GLAMOR=1)") } - if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) guest.add("BL_RAISE_NOFILE=1") + if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) guest.add("DD_RAISE_NOFILE=1") if (!com.droiddeck.launcher.core.DeviceSupport.adreno()) { val kernel = System.getProperty("os.version").orEmpty() val old = kernelBefore(kernel, 6, 6) @@ -997,11 +1047,11 @@ class SessionService : Service() { if (SessionPrefs.steamGpuCompositing(this)) { Log.i(TAG, "steam: GPU web compositing (Setup's \"Steam interface: GPU drawing\")") } else { - guest.add("BL_STEAM_SOFT_COMPOSITING=1") + guest.add("DD_STEAM_SOFT_COMPOSITING=1") Log.i(TAG, "steam: software web compositing for the open driver pair (GPU raster kept)") } - guest.add("BL_OPEN_DRIVER=1") - LinuxRuntime.gpuStandIn(this)?.takeIf { it == LinuxRuntime.MALI_DEVICE }?.let { guest.add("BL_DRM_STANDIN=$it") } + guest.add("DD_OPEN_DRIVER=1") + LinuxRuntime.gpuStandIn(this)?.takeIf { it == LinuxRuntime.MALI_DEVICE }?.let { guest.add("DD_DRM_STANDIN=$it") } } val tuOverride = tuDebugOverride() val tuDriver = sysmemDriver(linuxDriverId) @@ -1015,10 +1065,10 @@ class SessionService : Service() { guest.add("MESA_DISK_CACHE_DATABASE=1") guest.addAll(GpuStatsComponent.guestEnv(LinuxRuntime.rootDir(this))) guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216") - if (SessionState.mode == MODE_STEAM) guest.add("BL_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0")) + if (SessionState.mode == MODE_STEAM) guest.add("DD_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0")) SessionState.steamClientArch = if (steamHere) SessionPrefs.steamClientArch(this) else null SessionState.steamClientArch?.let { arch -> - guest.add("BL_STEAM_CLIENT_ARCH=$arch") + guest.add("DD_STEAM_CLIENT_ARCH=$arch") SessionPaths.current()?.let { SessionArtifacts.recordClient(it, arch) SessionArtifacts.markSteamLogs(it, File(SessionPrefs.steamRoot(this, arch), "logs")) @@ -1026,23 +1076,23 @@ class SessionService : Service() { } FexCatalog.cached(this)?.let { guest.addAll(FexCatalog.environment(it)) } if (SessionState.mode == MODE_STEAM) { - guest.add("BL_GAMESCOPE_STRETCH_16X9=" + (if (SessionPrefs.stretch16x9(this)) "1" else "0")) + guest.add("DD_GAMESCOPE_STRETCH_16X9=" + (if (SessionPrefs.stretch16x9(this)) "1" else "0")) } if (SessionPrefs.noXalia(this)) guest.add("PROTON_USE_XALIA=0") - guest.add("BL_SYNC=" + (if (SessionPrefs.fastSync(this)) "1" else "0")) - guest.add("BL_SYNC_FALLBACK=" + (if (SessionPrefs.syncFallback(this)) "1" else "0")) - guest.add("BL_FSYNC_FIRST=" + (if (SessionPrefs.fsyncFirst(this)) "1" else "0")) - guest.add("BL_PACE_CORES=" + (if (SessionPrefs.paceCores(this)) "1" else "0")) - guest.add("BL_GAMESCOPE_REALTIME=" + (if (SessionPrefs.gamescopeRealtime(this)) "1" else "0")) - if (SessionPrefs.cursorComposite(this)) guest.add("BL_CURSOR_COMPOSITE=1") + guest.add("DD_SYNC=" + (if (SessionPrefs.fastSync(this)) "1" else "0")) + guest.add("DD_SYNC_FALLBACK=" + (if (SessionPrefs.syncFallback(this)) "1" else "0")) + guest.add("DD_FSYNC_FIRST=" + (if (SessionPrefs.fsyncFirst(this)) "1" else "0")) + guest.add("DD_PACE_CORES=" + (if (SessionPrefs.paceCores(this)) "1" else "0")) + guest.add("DD_GAMESCOPE_REALTIME=" + (if (SessionPrefs.gamescopeRealtime(this)) "1" else "0")) + if (SessionPrefs.cursorComposite(this)) guest.add("DD_CURSOR_COMPOSITE=1") relativeMouseForSession().takeIf { it != 0 }?.let { guest.add("gamescope_relative_mouse=$it") } if (com.droiddeck.launcher.core.ZramSupport.supported()) { - guest.add("BL_ZRAM=1") - if (steamHere) SessionPrefs.ramCapMb(this).takeIf { it > 0 }?.let { guest.add("BL_RAM_CAP_MB=$it") } - if (!SessionPrefs.zramClient(this)) guest.add("BL_ZRAM_CLIENT=0") - if (!SessionPrefs.zramIdle(this)) guest.add("BL_ZRAM_IDLE=0") + guest.add("DD_ZRAM=1") + if (steamHere) SessionPrefs.ramCapMb(this).takeIf { it > 0 }?.let { guest.add("DD_RAM_CAP_MB=$it") } + if (!SessionPrefs.zramClient(this)) guest.add("DD_ZRAM_CLIENT=0") + if (!SessionPrefs.zramIdle(this)) guest.add("DD_ZRAM_IDLE=0") } - SessionPrefs.vramCapMb(this).takeIf { it > 0 }?.let { guest.add("BL_VRAM_MB=$it") } + SessionPrefs.vramCapMb(this).takeIf { it > 0 }?.let { guest.add("DD_VRAM_MB=$it") } guest.add("AUDIO_DIRECT_DECAY=0") val extra = extraEnv() + agentEnvironment guest.addAll(TurnipEnvironment.gameEnvironment(tuOverride, tuDriver, SessionPrefs.tuSysmem(this), extra)) @@ -1051,10 +1101,10 @@ class SessionService : Service() { com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice(this)?.let { guest.add("${com.droiddeck.launcher.gpu.TpUbwcHint.ENV}=$it") } val clientPinned = steamHere && SessionPrefs.clientCpusOverride(this) if (clientPinned) { - guest.add("BL_CLIENT_CPUS=" + CpuCores.listOrAll(SessionPrefs.clientCpus(this))) + guest.add("DD_CLIENT_CPUS=" + CpuCores.listOrAll(SessionPrefs.clientCpus(this))) } CpuCores.gameLaunchList(SessionPrefs.gameCpus(this), clientPinned) - .takeIf { it.isNotEmpty() }?.let { guest.add("BL_GAME_CPUS=$it") } + .takeIf { it.isNotEmpty() }?.let { guest.add("DD_GAME_CPUS=$it") } } private fun startVkBridge(guest: MutableList, sessionDir: File) { @@ -1063,16 +1113,16 @@ class SessionService : Service() { val bridge = com.droiddeck.launcher.gpu.VkBridgeComponent(socket, File(sessionDir, "vkbridge-server.log")) bridge.attach(this) components.add(bridge) - guest.add("BL_VKBRIDGE=1") - if (SessionPrefs.steamGpuCompositing(this)) guest.add("BL_STEAM_GPU_COMPOSITING=1") + guest.add("DD_VKBRIDGE=1") + if (SessionPrefs.steamGpuCompositing(this)) guest.add("DD_STEAM_GPU_COMPOSITING=1") SessionPrefs.linuxDriver(this).takeIf { it.isNotEmpty() } ?.let { runCatching { LinuxVulkanDriver.resolveIcdPath(this, it) }.getOrNull() } - ?.let { guest.add("BL_VKBRIDGE_FALLBACK_ICD=$it") } + ?.let { guest.add("DD_VKBRIDGE_FALLBACK_ICD=$it") } guest.add("VKBRIDGE_SOCKET=" + socket.path) guest.add("VKBRIDGE_CLIENT_LOG=" + File(sessionDir, "vkbridge-client.log").path) guest.add("VKBRIDGE_MODE=" + SessionPrefs.vkBridgeMode(this)) LinuxRuntime.gpuStandIn(this)?.let { node -> - guest.add("BL_DRM_STANDIN=$node") + guest.add("DD_DRM_STANDIN=$node") LinuxRuntime.deviceNumbers(node)?.let { guest.add("VKBRIDGE_DRM_RENDER=$it") } } Log.i(TAG, "vkbridge: on (${com.droiddeck.launcher.core.DeviceSupport.gpuName(this)}, ${SessionPrefs.vkBridgeMode(this)} mode), socket $socket") @@ -1086,7 +1136,7 @@ class SessionService : Service() { SessionPrefs.directAudio(this) val wantsMic = SessionPrefs.micEnabled(this) && checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED - guest.add("BL_MIC_ENABLED=" + if (wantsMic) "1" else "0") + guest.add("DD_MIC_ENABLED=" + if (wantsMic) "1" else "0") guest.add("AUDIO_DIRECT_MIC=" + if (wantsMic) "1" else "0") val audioDir = File(filesDir, "directaudio").apply { mkdirs() } val relaySocket = File(audioDir, "relay.sock") @@ -1114,7 +1164,7 @@ class SessionService : Service() { components.add(relay) } if (wantsDirectAudio) { - guest.add("BL_DIRECTAUDIO=/" + SessionFiles.DIRECTAUDIO_DIR) + guest.add("DD_DIRECTAUDIO=/" + SessionFiles.DIRECTAUDIO_DIR) guest.add("AUDIO_DIRECT_RELAY=" + relaySocket.absolutePath) val lowLatency = com.droiddeck.launcher.audio.DirectAudioTiming.lowLatencyOutput() val timing = com.droiddeck.launcher.audio.DirectAudioTiming.environment(lowLatency) @@ -1270,9 +1320,9 @@ class SessionService : Service() { ) if (device != null) { val envAt = guest.indexOf(LinuxRuntime.SESSION_SCRIPT).takeIf { it >= 0 } ?: guest.size - guest.add(envAt, "BL_STORAGE_DIAGNOSTICS=1") - guest.add(envAt + 1, "BL_STORAGE_DEVICE=$device") - guest.add(envAt + 2, "BL_STORAGE_LOG=${File(sessionDir, "storage.log").absolutePath}") + guest.add(envAt, "DD_STORAGE_DIAGNOSTICS=1") + guest.add(envAt + 1, "DD_STORAGE_DEVICE=$device") + guest.add(envAt + 2, "DD_STORAGE_LOG=${File(sessionDir, "storage.log").absolutePath}") } else { Log.w(TAG, "storage diagnostics: selected library could not be identified; metadata snapshot only") } @@ -1417,7 +1467,7 @@ class SessionService : Service() { val listing = File(filesDir, "session/steam-libraries-x64.json").apply { parentFile?.mkdirs() } listing.writeText(x64Libraries.toString()) val envAt = guest.indexOf(LinuxRuntime.SESSION_SCRIPT).takeIf { it >= 0 } ?: guest.size - guest.add(envAt, "BL_X64_STEAM_LIBRARIES=" + listing.path) + guest.add(envAt, "DD_X64_STEAM_LIBRARIES=" + listing.path) } catch (e: Exception) { Log.w(TAG, "x86-64 steam library: the list could not be written; internal storage alone this session", e) } @@ -1427,10 +1477,32 @@ class SessionService : Service() { for ((path, label) in libraries) json.put(org.json.JSONObject().put("path", path).put("label", label.replace('"', ' ').replace('\\', ' '))) listing.writeText(json.toString()) val envAt = guest.indexOf(LinuxRuntime.SESSION_SCRIPT).takeIf { it >= 0 } ?: guest.size - guest.add(envAt, "BL_STEAM_LIBRARIES=" + listing.path) + guest.add(envAt, "DD_STEAM_LIBRARIES=" + listing.path) } catch (e: Exception) { Log.w(TAG, "steam library: the list could not be written; the card alone this session", e) } + if (SessionState.mode == MODE_DESKTOP) { + try { + val listing = File(filesDir, "session/desktop-volumes.json").apply { parentFile?.mkdirs() } + val volumes = org.json.JSONArray() + var room = if (ProotFastPath.enabled(this)) { + ProotFastPath.MAX_BINDS - LinuxRuntime.binds(this, sessionRoot, runtimeDir, Environment.getExternalStorageDirectory(), binds).size + } else Int.MAX_VALUE + for (root in com.droiddeck.launcher.files.StorageRoots.list(this)) { + if (!root.removable || !root.readable) continue + val path = root.dir.absolutePath + if (':' in path || '|' in path || room <= 0) continue + binds.add(path) + room-- + volumes.put(org.json.JSONObject().put("path", path).put("label", root.label)) + } + listing.writeText(volumes.toString()) + val envAt = guest.indexOf(LinuxRuntime.SESSION_SCRIPT).takeIf { it >= 0 } ?: guest.size + guest.add(envAt, "DD_DESKTOP_VOLUMES=" + listing.path) + } catch (e: Exception) { + Log.w(TAG, "desktop volumes: the list could not be written", e) + } + } return binds } @@ -2328,7 +2400,8 @@ class SessionService : Service() { override fun onTaskRemoved(rootIntent: Intent?) { if (rootIntent?.component?.className in setOf( com.droiddeck.launcher.ui.DualScreenActivity::class.java.name, - com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name)) return + com.droiddeck.launcher.ui.SessionTypingActivity::class.java.name, + KeepTopActivity::class.java.name)) return if (pipTask || xrActivityVisible) { Log.i(TAG, "panel task dismissed - retaining the session under its active surface policy") activityVisible = false 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 ad7360d8ee..221a1e78c5 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionSuspendController.kt @@ -286,7 +286,7 @@ internal class SessionSuspendController( } val targets = records.values.filter { record -> try { - File(procRoot, "${record.pid}/maps").useLines { lines -> lines.any { it.endsWith("/libblsession.so") } } + File(procRoot, "${record.pid}/maps").useLines { lines -> lines.any { it.endsWith("/libddsession.so") } } } catch (_: IOException) { false } 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 0cd971422a..0a08067990 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SettingsReset.kt @@ -14,11 +14,11 @@ object SettingsReset { internal val SESSION_KEYS = setOf( "orientation", "launcherFullscreen", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt", "dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard", - "gameStoresEnabled", "soundtracksEnabled", "soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature", + "soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature", "storesInstallLanguage", "hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController", "gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController", - "stretch16x9", "picturePosition", "integerScaling", "railLabels", "agentTab", "navTabOrder", "navTabShelved", "navTabHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys", + "stretch16x9", "picturePosition", "integerScaling", "railLabels", "developerTools", "navTabOrder", "navTabShelved", "navTabHidden", "pcKeyboardSize", "pcKeyboardOpacity", "pcKeyboardHiddenKeys", "gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop", "tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "paceCores", "ramCapMb", "vramCapMb", "zramClient", "zramIdle", "directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus", diff --git a/app/src/main/java/com/droiddeck/launcher/session/SteamDownloadMonitor.kt b/app/src/main/java/com/droiddeck/launcher/session/SteamDownloadMonitor.kt index ccc8693c33..133514d643 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SteamDownloadMonitor.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SteamDownloadMonitor.kt @@ -115,7 +115,7 @@ internal class SteamDownloadMonitor { val steam = File(home, ".local/share/Steam") val stamped = File(steam, "package/droiddeck-installed").isFile || File(steam, "package/bannerlator-installed").isFile - return !(stamped && File(steam, "steamrtarm64/steam").isFile) || File(home, ".bl-steam-repair").exists() + return !(stamped && File(steam, "steamrtarm64/steam").isFile) || File(home, ".dd-steam-repair").exists() } internal fun manifests(runtimeRoot: File, mounts: Map): List { diff --git a/app/src/main/java/com/droiddeck/launcher/session/SteamGameProcess.kt b/app/src/main/java/com/droiddeck/launcher/session/SteamGameProcess.kt index 13a88ee493..7a00553f3b 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SteamGameProcess.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SteamGameProcess.kt @@ -40,8 +40,9 @@ object SteamGameProcess { val appId = args.getOrNull(i + 1) ?.takeIf { it.startsWith("AppId=") } ?.removePrefix("AppId=") + val launchOptions = args.drop(i + 2).takeWhile { it != "--" } - if (appId == expectedAppId) return true + if (appId == expectedAppId && "Install=1" !in launchOptions) return true } if (args[i] == "-applaunch" && diff --git a/app/src/main/java/com/droiddeck/launcher/session/SteamRepair.kt b/app/src/main/java/com/droiddeck/launcher/session/SteamRepair.kt index 9cd25d6856..e6d22749ed 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SteamRepair.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SteamRepair.kt @@ -6,7 +6,7 @@ import java.io.File object SteamRepair { private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root") - private fun request(context: Context) = File(home(context), ".bl-steam-repair") + private fun request(context: Context) = File(home(context), ".dd-steam-repair") private fun unconfirmed(context: Context) = File(home(context), ".local/share/Steam/package/droiddeck-unconfirmed") private fun x64Unconfirmed(context: Context) = File(home(context), ".droiddeck-x64/.local/share/Steam/package/droiddeck-unconfirmed") diff --git a/app/src/main/java/com/droiddeck/launcher/session/TopUnderPressure.kt b/app/src/main/java/com/droiddeck/launcher/session/TopUnderPressure.kt new file mode 100644 index 0000000000..3c7a55adea --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/TopUnderPressure.kt @@ -0,0 +1,13 @@ +package com.droiddeck.launcher.session + +import android.content.ComponentCallbacks2 + +internal object TopUnderPressure { + const val WINDOW_MS = 5_000L + + fun isPressure(level: Int) = + level == ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL || level == ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW + + fun shouldReclaim(nowMs: Long, pressureAtMs: Long, sessionRunning: Boolean, finishing: Boolean) = + sessionRunning && !finishing && pressureAtMs > 0 && nowMs - pressureAtMs in 0..WINDOW_MS +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/VenusComponent.kt b/app/src/main/java/com/droiddeck/launcher/session/VenusComponent.kt index a1856a6a9c..a9ab0f58d6 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/VenusComponent.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/VenusComponent.kt @@ -102,7 +102,7 @@ class VenusComponent(private val logFile: File?) : SessionPart() { // (Steam's GL, Xwayland's glamor) requires robustness2's nullDescriptor, which the // layer stands in for. The session script checks it and falls back to llvmpipe. "DROIDDECK_MALI_COMPAT=1", - "BL_VENUS=1", + "DD_VENUS=1", // gamescope's composite layout without immutable YCbCr samplers from the start // (patch 0930): a Mali-G615 refused every composite pipeline with them, and testing // that through Venus took the render server down. diff --git a/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt b/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt index 45b1be5429..c2fd9890d5 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/CloudSaves.kt @@ -5,11 +5,20 @@ import android.content.SharedPreferences import android.util.Log import com.droiddeck.launcher.frontend.AddedGames import com.droiddeck.launcher.frontend.Library +import com.droiddeck.launcher.stores.ea.EaAuth +import com.droiddeck.launcher.stores.ea.EaCloud +import com.droiddeck.launcher.stores.ea.EaLibrary +import com.droiddeck.launcher.stores.ea.EaPrefs +import com.droiddeck.launcher.stores.ea.EaSaveRules import com.droiddeck.launcher.stores.epic.EpicApiClient import com.droiddeck.launcher.stores.epic.EpicCredentialStore import com.droiddeck.launcher.stores.epic.EpicPrefs import com.droiddeck.launcher.stores.gog.GogAuth import com.droiddeck.launcher.stores.gog.GogPrefs +import com.droiddeck.launcher.stores.ubisoft.UbisoftAuth +import com.droiddeck.launcher.stores.ubisoft.UbisoftCloud +import com.droiddeck.launcher.stores.ubisoft.UbisoftCloudTransport +import com.droiddeck.launcher.stores.ubisoft.UbisoftConnect import java.io.File import java.net.HttpURLConnection import java.net.URL @@ -32,19 +41,27 @@ object CloudSaves { if (detail.isNotEmpty()) " detail=\"$detail\"" else "" } - class Status(val supported: Boolean, val folder: File?, val lastSync: Long, val reason: String, val conflicts: List = emptyList()) + class Status(val supported: Boolean, val folder: File?, val lastSync: Long, val reason: String, val conflicts: List = emptyList(), val signedIn: Boolean = true) - private fun game(context: Context, store: Store, id: String): Pair? = - StoreInstallRoot.gameFolders(context).firstNotNullOfOrNull { f -> - StoreGameSidecar.read(f)?.takeIf { it.store == store && it.id == id && it.isInstalled }?.let { f to it } - } + private fun game(context: Context, store: Store, id: String): Pair? { + fun match(f: File) = StoreGameSidecar.read(f)?.takeIf { it.store == store && it.id == id && it.isInstalled }?.let { f to it } + return StoreInstallRoot.gameFolders(context).firstNotNullOfOrNull(::match) + ?: if (store != Store.UBISOFT) null + else com.droiddeck.launcher.session.SessionPrefs.storeGameFolder(context, "${store.id}:$id")?.let { match(File(it)) } + } + + fun supports(store: Store?): Boolean = store == Store.GOG || store == Store.EPIC || store == Store.EA || store == Store.UBISOFT fun prefix(context: Context, folder: File): File? { val appId = AddedGames.scan(context).firstOrNull { it.folder.absolutePath == folder.absolutePath }?.appId ?: return null return Library.protonPrefix(context, appId and 0xFFFFFFFFL) } - private fun prefs(context: Context, store: Store) = if (store == Store.GOG) GogPrefs.get(context) else EpicPrefs.get(context) + private fun prefs(context: Context, store: Store) = when (store) { + Store.GOG -> GogPrefs.get(context) + Store.EA -> EaPrefs.get(context) + else -> EpicPrefs.get(context) + } fun lastSync(context: Context, store: Store, id: String): Long = prefs(context, store).getLong("cloud_sync_$id", 0L) @@ -52,6 +69,7 @@ object CloudSaves { private const val TEMPLATE_NONE = "none" + private const val UBISOFT_TEMPLATE = "ubisoft" internal const val TEMPLATE_NONE_TTL_MS = 24 * 60 * 60 * 1000L internal fun noneTemplateIsCurrent(storedAtMs: Long, nowMs: Long) = @@ -64,6 +82,10 @@ object CloudSaves { fun template(context: Context, store: Store, id: String, folder: File, sidecar: StoreGameSidecar): String? { val p = prefs(context, store) + if (store == Store.EA) eaRules(context, id)?.let { fresh -> + if (fresh.isEmpty()) rememberNoCloud(p, id) else p.edit().putString("cloud_template_$id", fresh).remove("cloud_template_at_$id").apply() + return fresh + } var retryNone = false if (p.contains("cloud_template_$id")) { val cached = p.getString("cloud_template_$id", "") ?: "" @@ -89,7 +111,9 @@ object CloudSaves { val item = sidecar.extra["catalogItemId"].orEmpty() if (ns.isEmpty() || item.isEmpty()) "" else EpicApiClient.getCustomAttribute(token, ns, item, "CloudSaveFolder") } - Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT, Store.ROCKSTAR -> "" + Store.UBISOFT -> UBISOFT_TEMPLATE + Store.EA -> eaRules(context, id) ?: return null + Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.ROCKSTAR -> "" } ?: return null p.edit() .putString("cloud_template_$id", fetched.ifEmpty { TEMPLATE_NONE }) @@ -146,18 +170,25 @@ object CloudSaves { val (folder, sidecar) = game(context, store, id) ?: return null to "not-installed" val template = template(context, store, id, folder, sidecar) ?: return null to "store-unreachable" if (template.isEmpty()) return null to "no-cloud-saves" + if (store == Store.UBISOFT) { + val user = UbisoftAuth.load(context)?.userId?.takeIf { it.isNotEmpty() } ?: return null to "not-signed-in" + val product = sidecar.extra["productId"]?.toLongOrNull() ?: return null to "unresolved" + return File(UbisoftConnect.prefix(context), "pfx/drive_c/users/steamuser/Saved Games/Ubisoft/$user/$product") to "ok" + } val pfx = prefix(context, folder) ?: return null to "no-prefix" val dir = when (store) { Store.GOG -> CloudSavePaths.gog(template, pfx, folder) Store.EPIC -> CloudSavePaths.epic(template, pfx, folder, EpicCredentialStore.load(context)?.accountId.orEmpty(), id) - Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT, Store.ROCKSTAR -> null + Store.EA -> if (sidecar.extra["masterTitleId"].isNullOrEmpty()) null + else EaSaveRules.parse(template)?.base()?.let(EaSaveRules::template)?.let { CloudSavePaths.gog(it, pfx, folder) } + Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR -> null } return dir to (if (dir == null) "unresolved" else "ok") } fun status(context: Context, store: Store, id: String): Status { val (dir, reason) = saveFolder(context, store, id) - return Status(reason != "no-cloud-saves" && reason != "not-installed", dir, lastSync(context, store, id), reason, conflicts(context, store, id)) + return Status(reason != "no-cloud-saves" && reason != "not-installed", dir, lastSync(context, store, id), reason, conflicts(context, store, id, dir), signedIn(context, store)) } @@ -175,7 +206,33 @@ object CloudSaves { val account = EpicCredentialStore.load(context)?.accountId.orEmpty() if (token == null || account.isEmpty()) null else EpicCloud(account, id, token) } - Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.EA, Store.UBISOFT, Store.ROCKSTAR -> null + Store.UBISOFT -> { + val session = UbisoftAuth.current(context) + val product = StoreGameSidecar.read(folder)?.extra?.get("productId")?.toLongOrNull() + if (session == null || product == null) null else UbisoftCloudTransport(UbisoftCloud(session, product), session.userId) + } + Store.EA -> { + val sidecar = StoreGameSidecar.read(folder) + val rules = sidecar?.let { template(context, store, id, folder, it) }?.let(EaSaveRules::parse) + val base = rules?.base() + val token = EaAuth.accessToken(context) + val uid = EaAuth.load(context)?.userId.orEmpty() + val master = sidecar?.extra?.get("masterTitleId").orEmpty() + if (rules == null || base == null || token == null || uid.isEmpty() || master.isEmpty()) null + else EaCloud(token, uid, EaCloud.keys(master, sidecar?.extra?.get("multiplayerId").orEmpty()), base, rules, saveFolder(context, store, id).first) + } + Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.ROCKSTAR -> null + } + + private fun signedIn(context: Context, store: Store): Boolean = when (store) { + Store.EA -> EaAuth.signedIn(context) + else -> true + } + + private fun eaRules(context: Context, id: String): String? { + val games = EaLibrary.cached(context) + if (games.isEmpty()) return null + return games.firstOrNull { it.offerId == id }?.cloudSaves.orEmpty() } private fun gogScopedToken(context: Context, id: String, clientId: String): String? { @@ -184,11 +241,15 @@ object CloudSaves { } - private fun baseline(context: Context, store: Store, id: String): Map? = - CloudPlan.fromJson(prefs(context, store).getString("cloud_baseline_$id", null)) + /** Ubisoft saves belong to an account and product, so their sync state is kept per save folder. */ + internal fun scope(store: Store, id: String, dir: File): String = + if (store == Store.UBISOFT) "$id:${dir.parentFile?.name.orEmpty()}:${dir.name}" else id - private fun saveBaseline(context: Context, store: Store, id: String, b: Map) = - prefs(context, store).edit().putString("cloud_baseline_$id", CloudPlan.toJson(b)).apply() + internal fun baseline(context: Context, store: Store, key: String): Map? = + CloudPlan.fromJson(prefs(context, store).getString("cloud_baseline_$key", null)) + + private fun saveBaseline(context: Context, store: Store, key: String, b: Map) = + prefs(context, store).edit().putString("cloud_baseline_$key", CloudPlan.toJson(b)).apply() internal class Migration(val baseline: Map, val moved: Int, val cleaned: Int, val failed: Int) @@ -260,30 +321,45 @@ object CloudSaves { if (result == null || result.failed == 0) p.edit().putInt("cloud_layout_$id", CLOUD_LAYOUT).apply() } - fun conflicts(context: Context, store: Store, id: String): List = - prefs(context, store).getString("cloud_conflicts_$id", "").orEmpty().split('\n').filter { it.isNotEmpty() } + fun conflicts(context: Context, store: Store, id: String, dir: File? = null): List = + if (store == Store.UBISOFT && dir == null) emptyList() else savedConflicts(context, store, dir?.let { scope(store, id, it) } ?: id) - private fun saveConflicts(context: Context, store: Store, id: String, names: Collection) = - prefs(context, store).edit().putString("cloud_conflicts_$id", names.joinToString("\n")).apply() + private fun savedConflicts(context: Context, store: Store, key: String): List = + prefs(context, store).getString("cloud_conflicts_$key", "").orEmpty().split('\n').filter { it.isNotEmpty() } - fun download(context: Context, store: Store, id: String, force: Boolean = false): Result = - sync(context, store, id, "down") { dir, cloud -> downWith(context, store, id, dir, cloud, force) } + private fun saveConflicts(context: Context, store: Store, key: String, names: Collection) = + prefs(context, store).edit().putString("cloud_conflicts_$key", names.joinToString("\n")).apply() + + private fun alike(cloud: CloudTransport, conflicts: List, local: Map, remote: Map): List = + if (cloud.contentDigests) emptyList() + else conflicts.filter { name -> + val r = remote[name] ?: return@filter false + val l = local[name] ?: return@filter false + runCatching { md5(cloud.get(r).first) }.getOrNull()?.equals(l.md5, ignoreCase = true) == true + } + + private fun settled(plan: CloudPlan.Plan, alike: List): CloudPlan.Plan = + if (alike.isEmpty()) plan else CloudPlan.Plan(plan.transfer, plan.conflicts - alike.toSet(), plan.same + alike, plan.refused) + + fun download(context: Context, store: Store, id: String, force: Boolean = false, claim: () -> Boolean = { true }): Result = + sync(context, store, id, "down") { dir, cloud -> downWith(context, store, id, dir, cloud, force, claim) } fun upload(context: Context, store: Store, id: String, force: Boolean = false): Result = sync(context, store, id, "up") { dir, cloud -> upWith(context, store, id, dir, cloud, force) } - fun downloadOrDefer(context: Context, store: Store, id: String): Result = - downloadOrDefer(context, store, id, Executor { Thread(it, "cloud-deferred").start() }) + fun downloadOrDefer(context: Context, store: Store, id: String, claim: () -> Boolean): Result = + downloadOrDefer(context, store, id, Executor { Thread(it, "cloud-deferred").start() }, claim) - internal fun downloadOrDefer(context: Context, store: Store, id: String, executor: Executor): Result { + internal fun downloadOrDefer(context: Context, store: Store, id: String, executor: Executor, claim: () -> Boolean = { true }): Result { val app = context.applicationContext val g = game(app, store, id) ?: return done(store, id, "down", Result("skipped", 0, 0, "not-installed")) if (!g.second.cloud) return done(store, id, "down", Result("skipped", 0, 0, "off")) - if (prefix(app, g.first)?.let { CloudSavePaths.profile(it).isDirectory } == true) return download(app, store, id) + val ready = { (if (store == Store.UBISOFT) File(UbisoftConnect.prefix(app), "pfx") else prefix(app, g.first))?.let { CloudSavePaths.profile(it).isDirectory } == true } + if (ready()) return download(app, store, id, claim = claim) executor.execute { val end = System.currentTimeMillis() + PREFIX_WAIT_MS while (System.currentTimeMillis() < end) { - if (prefix(app, g.first)?.let { CloudSavePaths.profile(it).isDirectory } == true) { download(app, store, id); return@execute } + if (ready()) { download(app, store, id); return@execute } Thread.sleep(2000) } done(store, id, "down", Result("skipped", 0, 0, "no-prefix")) @@ -304,8 +380,12 @@ object CloudSaves { if (dir != null && store == Store.GOG) migrateGogNested(context, id, g.first, dir) val cloud = if (dir != null) transport(context, store, id, g.first) else null when { + cloud is UbisoftCloudTransport && dir?.parentFile?.name != cloud.user -> Result("skipped", 0, 0, "account-changed") dir == null -> Result("skipped", 0, 0, reason) + cloud == null && store == Store.EA && signedIn(context, store) -> Result("failed", 0, 0, "sign-in-unreachable") cloud == null -> Result("skipped", 0, 0, "not-signed-in") + cloud is EaCloud && cloud.localDir?.canonicalPath != dir.canonicalPath -> Result("skipped", 0, 0, "rules-changed") + cloud is EaCloud && caseCollision(localFiles(dir).keys, cloud::wants) -> Result("failed", 0, 0, "case-collision") else -> body(dir, cloud).also { if (it.result == "ok") markSynced(context, store, id) } } } @@ -319,15 +399,32 @@ object CloudSaves { return done(store, id, way, result) } + internal fun caseCollision(names: Collection, wants: (String) -> Boolean): Boolean = + names.filter(wants).groupBy { it.lowercase() }.any { it.value.size > 1 } + private fun done(store: Store, id: String, way: String, r: Result): Result { Log.i(TAG, "cloud ${store.id} $id $way ${r.line}") StoresState.logLine("cloud ${store.id} $id $way ${r.line}") return r } - private fun localFiles(dir: File): Map = - if (!dir.isDirectory) emptyMap() - else dir.walkTopDown().filter { it.isFile }.associateBy { it.relativeTo(dir).path.replace(File.separatorChar, '/') } + private fun localFiles(dir: File): Map { + if (!dir.isDirectory) return emptyMap() + val root = runCatching { dir.toPath().toRealPath() }.getOrNull() ?: return emptyMap() + val found = LinkedHashMap() + fun walk(d: File, prefix: String, ancestry: Set) { + for (child in d.listFiles().orEmpty()) { + val real = runCatching { child.toPath().toRealPath() }.getOrNull() ?: continue + if (!real.startsWith(root)) continue + val name = prefix + child.name + if (child.isDirectory) { + if (real !in ancestry) walk(child, "$name/", ancestry + real) + } else if (child.isFile) found[name] = child + } + } + walk(dir, "", setOf(root)) + return found + } internal fun md5(f: File): String = md5(f.readBytes()) @@ -341,46 +438,85 @@ object CloudSaves { return files.associateBy { it.name } } - internal fun downWith(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport, force: Boolean): Result { - val files = localFiles(dir) + internal fun downWith(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport, force: Boolean, claim: () -> Boolean = { true }): Result { + val files = localFiles(dir).filterKeys(cloud::wants) val remote = remote(cloud) { it in files } val local = files.mapValues { CloudPlan.Local(md5(it.value)) } - val base = baseline(context, store, id) - val plan = CloudPlan.down(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base) - val take = if (force) plan.transfer + plan.conflicts else plan.transfer - if (take.isNotEmpty() && files.isNotEmpty()) backup(context, store, id, dir, "local") + val key = scope(store, id, dir) + val base = baseline(context, store, key) + val planned = CloudPlan.down(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base) + val alike = alike(cloud, planned.conflicts, local, remote) + val plan = settled(planned, alike) + val saved = savedConflicts(context, store, key).filter { it in remote && it !in alike && it !in plan.same } + val take = if (force) (plan.transfer + plan.conflicts + saved).distinct() else plan.transfer val next = HashMap(base.orEmpty()) var bytes = 0L + val written = HashSet() + val changed = ArrayList() + val blocked = ArrayList() + val fetched = LinkedHashMap>>() for (name in take) { val f = remote[name] ?: continue - val (data, modified) = cloud.get(f) + if (!File(dir, name).canonicalPath.startsWith(dir.canonicalPath + File.separator)) { blocked += name; continue } + fetched[name] = f to cloud.get(f) + } + if (fetched.isNotEmpty() && !claim()) return Result("skipped", 0, 0, "launch-moved-on") + val replaced = fetched.keys.mapNotNull { name -> files[name] ?: File(dir, name).takeIf { it.isFile } } + if (!backupReplaced(context, store, id, dir, replaced)) return Result("failed", 0, 0, "backup-failed") + for ((name, got) in fetched) { + val (f, content) = got + val (data, modified) = content val dest = File(dir, name) - if (!dest.canonicalPath.startsWith(dir.canonicalPath + File.separator)) continue + if ((if (dest.isFile) md5(dest) else null) != local[name]?.md5) { changed += name; continue } dest.parentFile?.mkdirs() dest.writeBytes(data) if (modified > 0) dest.setLastModified(modified) bytes += data.size + written += name next[name] = CloudPlan.Entry(md5(data), f.md5, if (modified > 0) modified else f.modifiedMs) } for (name in plan.same) remote[name]?.let { r -> next[name] = CloudPlan.Entry(local.getValue(name).md5, r.md5, r.modifiedMs) } - saveBaseline(context, store, id, next) - val left = if (force) emptyList() else plan.conflicts - saveConflicts(context, store, id, left) - return Result("ok", take.size, bytes, if (take.isEmpty()) "up-to-date" else "downloaded", left.size) + saveBaseline(context, store, key, next) + val left = (if (force) take.filter { it !in written } else plan.conflicts + saved.filter { it !in written } + changed) + .filter { it !in blocked }.distinct() + saveConflicts(context, store, key, left) + val reason = when { + take.isEmpty() -> "up-to-date" + changed.isNotEmpty() -> "changed-locally" + blocked.isNotEmpty() -> "blocked-path" + else -> "downloaded" + } + val detail = listOfNotNull( + changed.takeIf { it.isNotEmpty() }?.joinToString(prefix = "changed locally: "), + blocked.takeIf { it.isNotEmpty() }?.joinToString(prefix = "outside the save folder: "), + ).joinToString("; ") + return Result(if (written.size < take.size) "partial" else "ok", written.size, bytes, reason, left.size, detail) } internal fun upWith(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport, force: Boolean): Result { - val base = baseline(context, store, id) ?: return Result("skipped", 0, 0, "no-baseline") - val files = localFiles(dir) + val key = scope(store, id, dir) + val base = baseline(context, store, key) ?: return Result("skipped", 0, 0, "no-baseline") + val files = localFiles(dir).filterKeys(cloud::wants).let { all -> if (cloud is UbisoftCloudTransport) all.filterValues(::markUbisoftSave) else all } if (files.isEmpty()) return Result("skipped", 0, 0, "nothing-local") val remote = remote(cloud) { it in files } val local = files.mapValues { CloudPlan.Local(md5(it.value)) } - val plan = CloudPlan.up(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base) - val send = CloudPlan.upSend(plan, force, cloud is GogCloud, files.keys) + val planned = CloudPlan.up(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base) + val alike = alike(cloud, planned.conflicts, local, remote) + val plan = settled(planned, alike) + val saved = savedConflicts(context, store, key).filter { it !in alike && it !in plan.same } + var send = CloudPlan.upSend(plan, force, cloud is GogCloud, files.keys) val next = HashMap(base) for (name in plan.same) remote[name]?.let { r -> next[name] = CloudPlan.Entry(local.getValue(name).md5, r.md5, r.modifiedMs) } + var drifted = emptyList() + var raced = emptyList() + if (send.isNotEmpty()) { + val copies = backupCloud(context, store, id, cloud, send.mapNotNull { remote[it] }) + if (cloud is UbisoftCloudTransport && !force) { + drifted = send.filter { name -> val synced = base[name]?.localMd5; synced != null && copies[name]?.let { it != synced } == true } + send = send - drifted.toSet() + } + } if (send.isNotEmpty()) { - backupCloud(context, store, id, cloud, send.mapNotNull { remote[it] }) val stamped = HashMap() val sentMd5 = HashMap() if (cloud is GogCloud) { @@ -394,19 +530,40 @@ object CloudSaves { } else { val data = send.associateWith { files.getValue(it).readBytes() } for ((name, bytes) in data) sentMd5[name] = md5(bytes) - stamped += cloud.put(data, send.associateWith { files.getValue(it).lastModified() }) + stamped += try { + cloud.put(data, send.associateWith { files.getValue(it).lastModified() }) + } catch (e: CloudChanged) { + raced = e.unsent + e.sent + } catch (e: Exception) { + val kept = send.mapNotNull { name -> cloud.committed(name)?.let { name to it } } + if (kept.isNotEmpty()) { + for ((name, r) in kept) next[name] = CloudPlan.Entry(sentMd5.getValue(name), r.md5, r.modifiedMs) + saveBaseline(context, store, key, next) + saveConflicts(context, store, key, saved - kept.map { it.first }.toSet()) + } + throw e + } + send = send.filter { it in stamped } for ((name, t) in stamped) if (t > 0) files[name]?.setLastModified(t) } - val after = remote(cloud) { it in send } + val after = if (send.all { cloud.committed(it) != null }) emptyMap() else remote(cloud) { it in send && cloud.committed(it) == null } for (name in send) { - val r = after[name] + val r = cloud.committed(name) ?: after[name] next[name] = CloudPlan.Entry(sentMd5.getValue(name), r?.md5, r?.modifiedMs ?: stamped[name] ?: -1L) } } - saveBaseline(context, store, id, next) - val left = if (force) emptyList() else plan.conflicts - saveConflicts(context, store, id, left) - return Result("ok", send.size, send.sumOf { files.getValue(it).length() }, if (send.isEmpty()) "up-to-date" else "uploaded", left.size) + saveBaseline(context, store, key, next) + val left = (if (force) (plan.conflicts + saved).filter { it !in send } + raced + else plan.conflicts + drifted + raced + saved.filter { it !in send && it in files }).distinct() + saveConflicts(context, store, key, left) + val reason = when { + raced.isNotEmpty() -> "changed-in-cloud" + send.isEmpty() -> "up-to-date" + else -> "uploaded" + } + return Result(if (raced.isEmpty()) "ok" else "partial", send.size, send.sumOf { files.getValue(it).length() }, reason, left.size, + if (raced.isEmpty()) "" else raced.joinToString(prefix = "changed in the cloud: ")) } @@ -441,23 +598,59 @@ object CloudSaves { private fun backupRoot(context: Context, store: Store, id: String) = File(context.filesDir, "stores/cloud-backups/${store.id}-${id.replace(Regex("[^A-Za-z0-9._-]"), "_")}") - private fun backup(context: Context, store: Store, id: String, dir: File, kind: String) { - val root = backupRoot(context, store, id) - runCatching { dir.copyRecursively(File(root, "$kind-${System.currentTimeMillis()}"), overwrite = true) } - prune(root, kind) + private fun markUbisoftSave(file: File): Boolean { + val head = ByteArray(40) + var filled = 0 + file.inputStream().use { input -> + while (filled < head.size) { + val n = input.read(head, filled, head.size - filled) + if (n < 0) break + filled += n + } + } + if (filled < head.size) return false + if (UbisoftCloud.mark(head) != null) return true + if (head.copyOfRange(8, 40).any { it != 0.toByte() }) return false + java.io.RandomAccessFile(file, "rw").use { it.seek(8); it.write(UbisoftCloud.freshMark().toByteArray(Charsets.ISO_8859_1)) } + return true } - private fun backupCloud(context: Context, store: Store, id: String, cloud: CloudTransport, files: List) { - if (files.isEmpty()) return + private fun backupCloud(context: Context, store: Store, id: String, cloud: CloudTransport, files: List): Map { + if (files.isEmpty()) return emptyMap() val root = backupRoot(context, store, id) val target = File(root, "cloud-${System.currentTimeMillis()}") + val copies = HashMap() for (f in files) { val dest = File(target, f.name) if (!dest.canonicalPath.startsWith(target.canonicalPath + File.separator)) continue dest.parentFile?.mkdirs() - dest.writeBytes(cloud.get(f).first) + val data = cloud.get(f).first + dest.writeBytes(data) + copies[f.name] = md5(data) } prune(root, "cloud") + return copies + } + + private fun backupReplaced(context: Context, store: Store, id: String, dir: File, replaced: List): Boolean { + if (replaced.isEmpty()) return true + val base = runCatching { dir.canonicalPath + File.separator }.getOrNull() ?: return false + val root = backupRoot(context, store, id) + val stamp = "${System.currentTimeMillis()}-${java.util.UUID.randomUUID().toString().take(8)}" + val staging = File(root, "staging-$stamp") + val copied = runCatching { + for (f in replaced) { + check(f.canonicalPath.startsWith(base)) + f.copyTo(File(staging, f.relativeTo(dir).path), overwrite = true) + } + check(staging.renameTo(File(root, "local-$stamp"))) + }.isSuccess + if (!copied) { + staging.deleteRecursively() + return false + } + prune(root, "local") + return true } private fun prune(root: File, kind: String) { diff --git a/app/src/main/java/com/droiddeck/launcher/stores/CloudTransport.kt b/app/src/main/java/com/droiddeck/launcher/stores/CloudTransport.kt index 2971bb61ca..9e0ad99196 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/CloudTransport.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/CloudTransport.kt @@ -27,6 +27,10 @@ class CloudFile(val name: String, var modifiedMs: Long, var md5: String? = null, class CloudPut(val modifiedMs: Long, val md5: String?) interface CloudTransport { + /** False when [CloudFile.md5] is a version the service assigns rather than a digest of the content. */ + val contentDigests: Boolean get() = true + fun committed(name: String): CloudFile? = null + fun wants(name: String): Boolean = true fun list(): List fun details(file: CloudFile) {} fun get(file: CloudFile): Pair @@ -182,6 +186,8 @@ internal fun isoDate(s: String?): Long { class NoCloudSaves : Exception("no cloud saves") +class CloudChanged(val sent: Map, val unsent: List) : Exception("cloud saves changed since they were read") + internal fun splitGogName(name: String): Pair { val slash = name.indexOf('/') return if (slash <= 0 || slash == name.length - 1) null to name diff --git a/app/src/main/java/com/droiddeck/launcher/stores/Store.kt b/app/src/main/java/com/droiddeck/launcher/stores/Store.kt index b48530fbea..67b439943d 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/Store.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/Store.kt @@ -1,16 +1,16 @@ package com.droiddeck.launcher.stores enum class Store(val id: String, val label: String, val shortLabel: String) { - GOG("gog", "GOG", "GOG"), EPIC("epic", "Epic Games", "Epic"), - AMAZON("amazon", "Amazon Games", "Amazon"), - XBOX("xbox", "Xbox", "Xbox"), - ITCH("itch", "Itch.io", "Itch.io"), - GAMEJOLT("gamejolt", "Game Jolt", "Game Jolt"), - BATTLENET("battlenet", "Battle.net", "Battle.net"), - UBISOFT("ubisoft", "Ubisoft Connect", "Ubisoft"), EA("ea", "EA", "EA"), - ROCKSTAR("rockstar", "Rockstar Games", "Rockstar"); + XBOX("xbox", "Xbox", "Xbox"), + GOG("gog", "GOG", "GOG"), + ROCKSTAR("rockstar", "Rockstar Games", "Rockstar"), + ITCH("itch", "Itch.io", "Itch.io"), + UBISOFT("ubisoft", "Ubisoft Connect", "Ubisoft"), + AMAZON("amazon", "Amazon Games", "Amazon"), + BATTLENET("battlenet", "Battle.net", "Battle.net"), + GAMEJOLT("gamejolt", "Game Jolt", "Game Jolt"); val folder: String get() = if (this == ITCH) "itch" else shortLabel diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunchRequests.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunchRequests.kt index c4af9891d0..cc231dfcb8 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunchRequests.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreLaunchRequests.kt @@ -46,11 +46,18 @@ object StoreLaunchRequests { } private fun answer(app: Context, file: File) { + val resp = File(dir(app), "resp").apply { mkdirs() } + val rid = file.name.removeSuffix(".json") + val taken = File(resp, "$rid.taken") + val writing = File(resp, "$rid.writing") + if (!file.renameTo(taken)) return val request = try { - JSONObject(file.readText()).also { file.delete() } + JSONObject(taken.readText()) } catch (e: Exception) { + taken.delete() return } + val claim = { taken.renameTo(writing) } val reply = when (request.optString("op")) { "xbox-released" -> { com.droiddeck.launcher.stores.xbox.XboxRuntime.released(request.optString("lease")) @@ -58,7 +65,10 @@ object StoreLaunchRequests { } "xbox-renew" -> JSONObject().put("ok", com.droiddeck.launcher.stores.xbox.XboxRuntime.renew(app, request.optString("id"), request.optString("lease"))) "xbox-prepare" -> runCatching { com.droiddeck.launcher.stores.xbox.XboxRuntime.prepare(app, request.getString("id")) } - .getOrElse { JSONObject().put("ok", false).put("reason", "Xbox account service is unavailable. Sign in again and retry.") } + .getOrElse { + StoresState.logLine("Xbox: launch prepare failed (${it.javaClass.simpleName}: ${it.message})") + JSONObject().put("ok", false).put("reason", reasonFor(it)) + } "ea-prepare" -> runCatching { lastLaunched = Store.EA to request.optString("id"); com.droiddeck.launcher.stores.ea.EaLaunch.prepare(app, request) } .getOrElse { JSONObject().put("ok", false).put("reason", "error-" + it.javaClass.simpleName) } "ea-exited" -> { @@ -105,7 +115,7 @@ object StoreLaunchRequests { else { lastLaunched = store to id CloudSaves.markDirty(app, store, id) - CloudSaves.downloadOrDefer(app, store, id).let { JSONObject().put("ok", it.ok).put("result", it.result).put("files", it.files).put("reason", it.reason) } + CloudSaves.downloadOrDefer(app, store, id, claim).let { JSONObject().put("ok", it.ok).put("result", it.result).put("files", it.files).put("reason", it.reason) } } } "cloud-up" -> { @@ -164,12 +174,31 @@ object StoreLaunchRequests { else -> JSONObject().put("ok", false).put("reason", "unknown-op") } try { - val resp = File(dir(app), "resp").apply { mkdirs() } val tmp = File(resp, file.name + ".tmp") tmp.writeText(reply.toString()) tmp.renameTo(File(resp, file.name)) } catch (e: Exception) { Log.w(TAG, "could not answer ${file.name}: ${e.message}") + } finally { + taken.delete() + writing.delete() } } + + /// What the guest prints when a launch is refused. + /// + /// The message is the only thing that separates a stale sign-in from a title + /// that is not installed, so it is kept, minus anything that could carry a + /// device path or a token: segments lookng like a path are dropped and the + /// rest is folded to plain text. + internal fun reasonFor(error: Throwable): String { + val text = error.message.orEmpty() + .split(' ') + .filterNot { it.contains('/') || it.startsWith("http") } + .joinToString(" ") + .filter { it.isLetterOrDigit() || it in " .,:;_-()'" } + .trim() + .take(160) + return if (text.isEmpty()) "Xbox account service is unavailable. Sign in again and retry." else text + } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreLibraryCache.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreLibraryCache.kt new file mode 100644 index 0000000000..9adeff3f16 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreLibraryCache.kt @@ -0,0 +1,70 @@ +package com.droiddeck.launcher.stores + +import android.content.Context +import java.io.File +import org.json.JSONArray +import org.json.JSONObject + +internal object StoreLibraryCache { + private fun file(context: Context, store: Store) = File(context.filesDir, "store-library/${store.id}.json") + + fun load(context: Context, store: Store): List? { + val f = file(context, store) + if (!f.isFile) return null + return runCatching { decode(store, f.readText()) }.getOrNull() + } + + private val locks = Store.entries.associateWith { Any() } + + fun save(context: Context, store: Store, items: List, current: () -> Boolean) = synchronized(locks.getValue(store)) { + if (!current()) return@synchronized + val f = file(context, store) + runCatching { + f.parentFile?.mkdirs() + val tmp = File(f.parentFile, f.name + ".tmp") + tmp.writeText(encode(items)) + if (!tmp.renameTo(f)) { f.delete(); tmp.renameTo(f) } + } + } + + fun clear(context: Context, store: Store) = synchronized(locks.getValue(store)) { + file(context, store).delete() + } + + internal fun encode(items: List): String { + val out = JSONArray() + items.forEach { i -> + out.put(JSONObject() + .put("id", i.id).put("title", i.title) + .put("image", i.imageUrl ?: "").put("tall", i.tallImageUrl ?: "").put("logo", i.logoUrl ?: "") + .put("tags", i.tags).put("free", i.isFree).put("hasPrice", i.hasPrice) + .put("finalPrice", i.finalPrice).put("originalPrice", i.originalPrice).put("discount", i.discountPercent) + .put("url", i.storeUrl).put("developer", i.developer).put("publisher", i.publisher) + .put("releaseDate", i.releaseDate).put("description", i.description) + .put("owned", i.owned).put("size", i.sizeBytes).put("extra", JSONObject(i.extra)) + .put("mature", i.mature).put("subscription", i.subscription).put("includedWith", i.includedWith)) + } + return out.toString() + } + + internal fun decode(store: Store, text: String): List { + val raw = JSONArray(text) + return (0 until raw.length()).mapNotNull { n -> + val o = raw.optJSONObject(n) ?: return@mapNotNull null + val extra = o.optJSONObject("extra") + val map = HashMap() + extra?.keys()?.forEach { k -> map[k] = extra.optString(k) } + CatalogItem( + store = store, id = o.optString("id"), title = o.optString("title"), + imageUrl = o.optString("image").ifBlank { null }, tallImageUrl = o.optString("tall").ifBlank { null }, + logoUrl = o.optString("logo").ifBlank { null }, + tags = o.optString("tags"), isFree = o.optBoolean("free"), hasPrice = o.optBoolean("hasPrice"), + finalPrice = o.optString("finalPrice"), originalPrice = o.optString("originalPrice"), discountPercent = o.optInt("discount"), + storeUrl = o.optString("url"), developer = o.optString("developer"), publisher = o.optString("publisher"), + releaseDate = o.optString("releaseDate"), description = o.optString("description"), + owned = o.optBoolean("owned"), sizeBytes = o.optLong("size"), extra = map, + mature = o.optBoolean("mature"), subscription = o.optBoolean("subscription"), includedWith = o.optString("includedWith"), + ) + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoreSizes.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoreSizes.kt index 21969dfbe7..8a47c06806 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoreSizes.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoreSizes.kt @@ -27,13 +27,20 @@ object StoreSizes { fun size(item: CatalogItem): Long = known[item.key] ?: item.sizeBytes + private val NO_REMOTE_SIZE = setOf(Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR) + private val settled = mutableStateMapOf() + + // A size that can still arrive this session: not known yet, the store can report one, and no lookup came back empty. + fun coming(item: CatalogItem): Boolean = + item.accessible && item.sizeBytes <= 0 && item.store !in NO_REMOTE_SIZE && !known.containsKey(item.key) && settled[item.key] != true + private val caches = ConcurrentHashMap() private fun cache(context: Context, store: Store) = caches.getOrPut(store) { SizeCache.forStore(context.applicationContext.filesDir, store) } fun request(context: Context, item: CatalogItem) { if (!item.accessible || item.sizeBytes > 0 || item.store == Store.GOG || known.containsKey(item.key)) return - resolve(context, item).thenAccept { bytes -> - if (bytes != null) StoresState.post { known[item.key] = bytes } + resolve(context, item).whenComplete { bytes, _ -> + StoresState.post { if (bytes != null && bytes > 0) known[item.key] = bytes else settled[item.key] = true } } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt index 46de6eaab0..8cd6ea13a2 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/StoresState.kt @@ -202,6 +202,7 @@ object StoresState { backend?.signOut(app) if (store == Store.GOG) com.droiddeck.launcher.stores.gog.GogComet.replaceAccount { StoreAccounts.clear(app, store) } else if (store != Store.XBOX || backend == null) StoreAccounts.clear(app, store) + StoreLibraryCache.clear(app, store) if (store == Store.GAMEJOLT) { com.droiddeck.launcher.stores.gamejolt.GameJoltCollections.clear() com.droiddeck.launcher.stores.gamejolt.GameJoltUpdates.clear(app) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaAuth.kt b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaAuth.kt index 67fb8e655e..a600c905bc 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaAuth.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaAuth.kt @@ -17,7 +17,7 @@ object EaAuth { const val CLIENT_ID = "JUNO_PC_CLIENT" private const val CLIENT_SECRET = "4mRLtYMb6vq9qglomWEaT4ChxsXWcyqbQpuBNfMPOYOiDmYYQmjuaBsF2Zp0RyVeWkfqhE9TuGgAw7te" const val AUTH_URL = "https://accounts.ea.com/connect/auth" - private const val TOKEN_URL = "https://accounts.ea.com/connect/token" + internal var tokenUrl = "https://accounts.ea.com/connect/token" const val REDIRECT = "qrc:///html/login_successful.html" private const val REFRESH_MARGIN_MS = 5 * 60 * 1000L private val refreshLock = Any() @@ -41,8 +41,11 @@ object EaAuth { val personaId: String, val displayName: String, val eaId: String, + val rejected: Boolean = false, ) + private class Rejected(message: String) : IllegalStateException(message) + class Pending(val url: String, val verifier: String) internal fun fromJson(o: JSONObject): Account? { @@ -55,6 +58,7 @@ object EaAuth { personaId = o.optString("persona_id"), displayName = o.optString("display_name"), eaId = o.optString("ea_id"), + rejected = o.optBoolean("refresh_rejected"), ) } @@ -122,14 +126,15 @@ object EaAuth { private fun tokenCall(values: List>): JSONObject { val reply = EaHttp.request( - TOKEN_URL, "POST", + tokenUrl, "POST", mapOf("Content-Type" to "application/x-www-form-urlencoded"), EaHttp.form(values + listOf("client_id" to CLIENT_ID, "client_secret" to CLIENT_SECRET)).toByteArray(), follow = false, ) val json = runCatching { JSONObject(reply.text) }.getOrNull() if (!reply.ok || json == null || json.optString("access_token").isEmpty()) { - throw IllegalStateException("EA token request failed (${reply.status}): ${json?.optString("error_description")?.ifEmpty { json.optString("error") } ?: ""}") + val message = "EA token request failed (${reply.status}): ${json?.optString("error_description")?.ifEmpty { json.optString("error") } ?: ""}" + throw if (json?.optString("error") == "invalid_grant") Rejected(message) else IllegalStateException(message) } return json } @@ -162,6 +167,7 @@ object EaAuth { tokenCall(listOf("grant_type" to "refresh_token", "refresh_token" to a.refreshToken)) } catch (e: Exception) { Log.w(TAG, "refresh: ${e.message}") + if (e is Rejected) markRejected(context, a.refreshToken) return null } val access = token.getString("access_token") @@ -176,11 +182,24 @@ object EaAuth { val record = StoreAccounts.read(app, Store.EA) ?: return false record.put("access_token", access).put("expires_at", System.currentTimeMillis() + expiresIn * 1000) refresh.takeIf { it.isNotEmpty() }?.let { record.put("refresh_token", it) } + record.remove("refresh_rejected") player?.let { record.put("user_id", it.userId).put("persona_id", it.personaId).put("display_name", it.displayName).put("ea_id", it.eaId) } StoreAccounts.write(app, Store.EA, record) true } + private fun markRejected(context: Context, refresh: String) = synchronized(refreshLock) { + val app = context.applicationContext + val record = StoreAccounts.read(app, Store.EA) ?: return@synchronized + if (record.optString("refresh_token") != refresh) return@synchronized + StoreAccounts.write(app, Store.EA, record.put("refresh_rejected", true)) + } + + fun signedIn(context: Context): Boolean { + val a = load(context) ?: return false + return a.userId.isNotEmpty() && !(a.rejected && a.expiresAt <= System.currentTimeMillis()) + } + fun accessToken(context: Context): String? { val current = load(context) ?: return null if (fresh(current)) return current.accessToken diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaCloud.kt b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaCloud.kt new file mode 100644 index 0000000000..6c5242474e --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaCloud.kt @@ -0,0 +1,265 @@ +package com.droiddeck.launcher.stores.ea + +import android.util.Base64 +import android.util.Xml +import com.droiddeck.launcher.stores.CloudFile +import com.droiddeck.launcher.stores.CloudTransport +import java.io.File +import java.io.StringReader +import java.security.MessageDigest +import java.time.Instant +import org.xmlpull.v1.XmlPullParser + +internal class EaCloud( + private val token: String, + private val uid: String, + private val keys: List, + private val base: String, + private val rules: EaSaveRules, + val localDir: File? = null, +) : CloudTransport { + class Entry(val size: Long, val href: String, val md5: String, val created: String, val modified: String, val localName: String) + + class Manifest(val lineage: String, val files: List, val snapshots: List) + + private class Signed(val url: String, val headers: Map) + + private class Request(val verb: String, val resource: String, val md5: String? = null, val type: String? = null) + + private var key: String? = null + private var found = false + private var listed: Map? = null + private val committed = HashMap() + + override fun wants(name: String): Boolean = rules.matches(base + name) + + override fun committed(name: String): CloudFile? = committed[name] + + override fun list(): List { + val manifest = pick() + val files = manifest?.files.orEmpty().mapNotNull { e -> + val path = EaSaveRules.normalize(e.localName) + if (!path.startsWith(base, ignoreCase = true) || !rules.matches(path)) return@mapNotNull null + val md5 = hex(e.md5) ?: error("EA listed ${path.substring(base.length)} without a valid checksum") + CloudFile(localName(path.substring(base.length)), parseTime(e.modified), md5, readLink = e.href) + } + val twins = files.groupBy { it.name.lowercase() }.values.firstOrNull { it.size > 1 } + check(twins == null) { "EA lists more than one save named ${twins!!.first().name} in different cases" } + listed = files.associate { it.name.lowercase() to it.md5 } + return files + } + + private fun localName(name: String): String { + var dir = localDir ?: return name + val parts = name.split('/') + val out = ArrayList() + for (part in parts) { + val match = dir.listFiles()?.filter { it.name.equals(part, ignoreCase = true) }.orEmpty() + check(match.size <= 1) { "The save folder holds more than one file named $part in different cases" } + val pick = match.singleOrNull() + if (pick == null) return (out + parts.drop(out.size)).joinToString("/") + out += pick.name + dir = pick + } + return out.joinToString("/") + } + + override fun get(file: CloudFile): Pair { + val href = file.readLink ?: error("EA has no data for ${file.name}") + return locked("read", key ?: keys.first()) { lock, _ -> + val signed = authorize(lock, listOf(Request("GET", href))).single() + val reply = EaHttp.request(signed.url, headers = signed.headers) + check(reply.ok) { "EA cloud save download answered ${reply.status}" } + val want = file.md5 ?: error("EA listed ${file.name} without a valid checksum") + check(hex(b64(md5(reply.body))) == want) { "EA cloud save ${file.name} failed its checksum" } + reply.body to file.modifiedMs + } + } + + override fun put(files: Map, modifiedMs: Map): Map { + if (key == null) pick() + check(found || keys.size == 1) { "EA has no cloud save record for this game yet; play it once in the EA app" } + val target = key ?: keys.first() + val seen = listed + return locked("write", target) { lock, body -> + val locked = manifestUrl(body)?.let { fetchManifest(it) } + check(locked != null || !found) { "EA's cloud save record disappeared" } + val current = locked ?: Manifest("{00000000-0000-0000-0000-000000000000}", emptyList(), emptyList()) + if (seen != null) for (name in files.keys) { + val entry = current.files.firstOrNull { EaSaveRules.normalize(it.localName).equals(base + name, ignoreCase = true) } + val now = entry?.let { hex(it.md5) ?: error("EA lists $name without a valid checksum") } + check(now == seen[name.lowercase()]) { "EA's cloud saves changed since they were read" } + } + val now = System.currentTimeMillis() + val added = files.map { (name, data) -> + val sum = md5(data) + val stamp = stamp(modifiedMs[name]?.takeIf { it > 0 } ?: now) + val old = current.files.firstOrNull { EaSaveRules.normalize(it.localName).equals(base + name, ignoreCase = true) } + Entry(data.size.toLong(), "content/${data.size}-${hexOf(sum)}", b64(sum), old?.created ?: stamp, stamp, base + name) to data + } + val names = added.map { it.first.localName.lowercase() }.toSet() + val next = Manifest(current.lineage, current.files.filter { EaSaveRules.normalize(it.localName).lowercase() !in names } + added.map { it.first }, current.snapshots) + val xml = write(next).toByteArray() + val xmlMd5 = b64(md5(xml)) + val requests = added.map { Request("PUT", it.first.href, it.first.md5, "application/octet-stream") } + Request("PUT", "manifest.xml", xmlMd5, "text/xml") + val signed = authorize(lock, requests) + for ((i, pair) in added.withIndex()) upload(signed[i], pair.second) + upload(signed.last(), xml) + found = true + for ((entry, _) in added) { + val name = entry.localName.substring(base.length) + committed[name] = CloudFile(name, parseTime(entry.modified), hex(entry.md5), readLink = entry.href) + } + listed = null + files.mapValues { (name, _) -> modifiedMs[name]?.takeIf { it > 0 } ?: now } + } + } + + private fun pick(): Manifest? { + for (candidate in keys) { + val manifest = locked("read", candidate, missing = { null }) { _, body -> manifestUrl(body)?.let { fetchManifest(it) } } + if (manifest != null) { + key = candidate + found = true + return manifest + } + } + key = keys.first() + found = false + return null + } + + private fun upload(signed: Signed, data: ByteArray) { + val reply = EaHttp.request(signed.url, "PUT", signed.headers, data) + check(reply.ok) { "EA cloud save upload answered ${reply.status}" } + } + + private fun fetchManifest(url: String): Manifest? { + val reply = EaHttp.request(url) + if (reply.status == 404) return null + check(reply.ok) { "EA cloud save manifest answered ${reply.status}" } + return parse(reply.text) + } + + private fun locked(kind: String, key: String, missing: (() -> T)? = null, body: (String, String) -> T): T { + val reply = EaHttp.request("$HOST/lock/$kind/$uid/$key", "POST", mapOf(AUTH to token, "Content-Type" to "application/xml"), ByteArray(0)) + if (reply.status == 404 && missing != null) return missing() + check(reply.ok) { "EA cloud saves answered ${reply.status}" } + val lock = reply.header(LOCK) ?: error("EA did not grant a cloud save lock") + try { + return body(lock, reply.text) + } finally { + runCatching { EaHttp.request("$HOST/lock/delete/$uid", "DELETE", mapOf(AUTH to token, LOCK to lock)) } + } + } + + private fun authorize(lock: String, requests: List): List { + val body = buildString { + append("") + for ((i, r) in requests.withIndex()) { + append("").append(r.verb).append("").append(escape(r.resource)).append("") + r.md5?.let { append("").append(it).append("") } + r.type?.let { append("").append(it).append("") } + append("") + } + append("") + } + val reply = EaHttp.request("$HOST/lock/authorize/$uid", "PUT", mapOf(AUTH to token, LOCK to lock, "Content-Type" to "application/xml"), body.toByteArray()) + check(reply.ok) { "EA cloud saves refused the transfer (${reply.status})" } + return signedRequests(reply.text, requests.size) + } + + companion object { + private const val HOST = "https://cloudsync.juno.ea.com" + private const val AUTH = "X-Origin-AuthToken" + private const val LOCK = "X-Origin-Sync-Lock" + private val REQUEST = Regex("]*\\bid=\"(\\d+)\"[^>]*>(.*?)", RegexOption.DOT_MATCHES_ALL) + private val HEADER = Regex("]*)/?>") + + fun keys(masterTitleId: String, multiplayerId: String): List = + if (multiplayerId.isNotEmpty()) listOf("${masterTitleId}_$multiplayerId") else listOf(masterTitleId, "${masterTitleId}_$masterTitleId") + + fun manifestUrl(lockBody: String): String? = Regex("([^<]+)").find(lockBody)?.groupValues?.get(1)?.let(::unescape) + + fun parse(xml: String): Manifest { + val p = Xml.newPullParser().apply { setInput(StringReader(xml)) } + var root: String? = null + var lineage: String? = null + var depth = 0 + var closed = false + val files = ArrayList() + val snapshots = ArrayList() + var file: Array? = null + var local: Entry? = null + runCatching { + while (p.next() != XmlPullParser.END_DOCUMENT) when (p.eventType) { + XmlPullParser.START_TAG -> { + depth++ + val at = { name: String -> p.getAttributeValue(null, name).orEmpty() } + when { + root == null -> { root = p.name; lineage = p.getAttributeValue(null, "lineage") } + depth == 2 && p.name == "file" -> { file = arrayOf(at("size"), at("href"), at("md5")); local = null } + depth == 3 && p.name == "localName" && file != null -> { + val f = file!! + val created = at("created") + val modified = at("lastModified") + local = Entry(f[0].toLongOrNull() ?: 0, f[1], f[2], created, modified, p.nextText()) + depth-- + } + depth == 2 && p.name == "snapshot" -> { snapshots += p.nextText(); depth-- } + } + } + XmlPullParser.END_TAG -> { + if (depth == 2 && p.name == "file") { local?.let(files::add); file = null } + depth-- + if (depth == 0) closed = true + } + } + }.onFailure { error("EA sent an incomplete cloud save manifest") } + check(root == "manifest" && depth == 0 && closed) { "EA sent an incomplete cloud save manifest" } + return Manifest(lineage ?: "{00000000-0000-0000-0000-000000000000}", files, snapshots) + } + + fun write(m: Manifest): String = buildString { + append("\n") + for (f in m.files) { + append(" \n") + append(" ") + append(escape(f.localName)).append("\n \n") + } + for (s in m.snapshots) append(" ").append(escape(s)).append("\n") + append("\n") + } + + private fun signedRequests(xml: String, count: Int): List { + val byId = REQUEST.findAll(xml).associate { m -> + val inner = m.groupValues[2] + val url = Regex("([^<]+)").find(inner)?.groupValues?.get(1)?.let(::unescape) ?: error("EA sent no transfer URL") + val headers = HEADER.findAll(inner).mapNotNull { h -> + val k = attr(h.groupValues[1], "key") ?: return@mapNotNull null + k to (attr(h.groupValues[1], "value") ?: "") + }.toMap() + m.groupValues[1].toInt() to Signed(url, headers) + } + return (0 until count).map { byId[it] ?: error("EA signed ${byId.size} of $count cloud save transfers") } + } + + fun stamp(ms: Long): String = Instant.ofEpochMilli(ms / 1000 * 1000).toString() + "Z" + + fun parseTime(s: String): Long = runCatching { Instant.parse(s.trimEnd('Z') + "Z").toEpochMilli() }.getOrDefault(-1L) + + private fun attr(attrs: String, name: String): String? = Regex("\\b$name=\"([^\"]*)\"").find(attrs)?.groupValues?.get(1)?.let(::unescape) + + private fun md5(data: ByteArray) = MessageDigest.getInstance("MD5").digest(data) + + private fun b64(sum: ByteArray) = Base64.encodeToString(sum, Base64.NO_WRAP) + + private fun hexOf(sum: ByteArray) = sum.joinToString("") { "%02x".format(it) } + + fun hex(b64: String): String? = runCatching { hexOf(Base64.decode(b64, Base64.DEFAULT)) }.getOrNull()?.takeIf { it.length == 32 } + + private fun escape(s: String) = s.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """) + + private fun unescape(s: String) = EaSaveRules.unescape(s) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ea/EaSaveRules.kt b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaSaveRules.kt new file mode 100644 index 0000000000..b103473eb8 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/ea/EaSaveRules.kt @@ -0,0 +1,84 @@ +package com.droiddeck.launcher.stores.ea + +internal class EaSaveRules(private val rules: List>) { + val includes get() = rules.filter { it.first }.map { it.second } + val excludes get() = rules.filterNot { it.first }.map { it.second } + + fun base(): String? { + val dirs = includes.filterNot(::bare).map { pattern -> + val wild = pattern.indexOfFirst { it == '*' || it == '?' } + val fixed = if (wild < 0) pattern else pattern.substring(0, wild) + if (fixed.endsWith('/')) fixed else fixed.substringBeforeLast('/', "") + "/" + } + val parts = dirs.map { it.trimEnd('/').split('/') } + if (parts.isEmpty()) return null + val common = ArrayList() + for (i in parts.minOf { it.size }.let { 0 until it }) { + val seg = parts[0][i] + if (parts.all { it[i].equals(seg, ignoreCase = true) }) common += seg else break + } + if (common.isEmpty() || !VARIABLE.matches(common[0])) return null + return common.joinToString("/") + "/" + } + + fun matches(path: String): Boolean { + val p = normalize(path) + val inside = base()?.let { p.startsWith(it, ignoreCase = true) } ?: false + return rules.firstOrNull { (_, pattern) -> if (bare(pattern)) inside && hit(pattern, p.substringAfterLast('/')) else hit(pattern, p) }?.first ?: false + } + + private fun bare(pattern: String) = !pattern.startsWith('%') && '/' !in pattern + + private fun hit(pattern: String, path: String): Boolean = when { + pattern.endsWith('/') -> path.startsWith(pattern, ignoreCase = true) + pattern.any { it == '*' || it == '?' } -> glob(pattern).matches(path) + else -> path.equals(pattern, ignoreCase = true) + } + + private fun glob(pattern: String): Regex = Regex( + pattern.split('*').joinToString("[^/]*") { part -> part.split('?').joinToString("[^/]") { Regex.escape(it) } }, + RegexOption.IGNORE_CASE, + ) + + companion object { + private val VARIABLE = Regex("%[A-Za-z]+%") + private val RULE = Regex("<(include|exclude)\\b([^>]*)>([^<]*)", RegexOption.IGNORE_CASE) + private val ORDER = Regex("\\border\\s*=\\s*[\"']?(\\d+)") + private val TOKENS = mapOf( + "documents" to "%DOCUMENTS%", "savedgames" to "%SAVED_GAMES%", "appdata" to "%APPDATA%", + "localappdata" to "%LOCALAPPDATA%", "programdata" to "%PROGRAMDATA%", "userprofile" to "%USERPROFILE%", + "locallowappdata" to "%APPLICATION_DATA_LOCAL_LOW%", "installdir" to "%INSTALL%", + ) + + private val COMMENT = Regex("", RegexOption.DOT_MATCHES_ALL) + private val ENTITY = Regex("&(#x[0-9a-fA-F]+|#[0-9]+|lt|gt|quot|apos|amp);") + + fun normalize(path: String) = path.replace('\\', '/') + + fun parse(xml: String): EaSaveRules? { + val rules = RULE.findAll(COMMENT.replace(xml, "")).mapIndexed { index, rule -> + val order = ORDER.find(rule.groupValues[2])?.groupValues?.get(1)?.toIntOrNull() ?: index + Triple(order, rule.groupValues[1].equals("include", true), normalize(unescape(rule.groupValues[3]).trim())) + }.filter { it.third.isNotEmpty() }.sortedBy { it.first }.map { it.second to it.third }.toList() + if (rules.none { it.first }) return null + return EaSaveRules(rules) + } + + fun template(base: String): String? { + val variable = VARIABLE.find(base)?.takeIf { it.range.first == 0 } ?: return null + val token = TOKENS[variable.value.trim('%').lowercase()] ?: return null + return token + base.substring(variable.value.length) + } + + fun unescape(s: String): String = ENTITY.replace(s) { m -> + when (val e = m.groupValues[1]) { + "lt" -> "<" + "gt" -> ">" + "quot" -> "\"" + "apos" -> "'" + "amp" -> "&" + else -> runCatching { String(Character.toChars(if (e.startsWith("#x")) e.substring(2).toInt(16) else e.substring(1).toInt())) }.getOrDefault(m.value) + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarBackend.kt index f816ed8ef1..1d0584ac9d 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/rockstar/RockstarBackend.kt @@ -14,6 +14,7 @@ import com.droiddeck.launcher.stores.StoreFront import com.droiddeck.launcher.stores.StoreInstallRoot import com.droiddeck.launcher.stores.StoreLoginActivity import com.droiddeck.launcher.stores.StoreShelves +import com.droiddeck.launcher.stores.StoreLibraryCache import com.droiddeck.launcher.stores.StoresState import com.droiddeck.launcher.stores.WebCookies import com.droiddeck.launcher.stores.download.DownloadEntry @@ -163,7 +164,16 @@ object RockstarLibrary { post(gen) { StoresState.status.remove(Store.ROCKSTAR); StoresState.problems[Store.ROCKSTAR] = app.getString(R.string.stores_sync_sign_in) } return } - if (StoresState.library[Store.ROCKSTAR].isNullOrEmpty()) post(gen) { StoresState.status[Store.ROCKSTAR] = app.getString(R.string.stores_sync_game_list) } + val cached = StoreLibraryCache.load(app, Store.ROCKSTAR) + post(gen) { + if (StoresState.library[Store.ROCKSTAR] == null) { + if (cached != null) { + StoresState.library[Store.ROCKSTAR] = cached + StoresState.shelves[Store.ROCKSTAR]?.let { StoresState.shelves[Store.ROCKSTAR] = StoreFront.markOwned(it, cached, RockstarCatalog::sameGame) } + } + else StoresState.status[Store.ROCKSTAR] = app.getString(R.string.stores_sync_game_list) + } + } val account = RockstarApps.fetch(t.ticket) { StoresState.logLine(it) } val games = games(account) owned(account).filter { o -> games.none { it.id == o.id } }.takeIf { it.isNotEmpty() }?.let { elsewhere -> @@ -175,6 +185,7 @@ object RockstarLibrary { StoresState.library[Store.ROCKSTAR] = games StoresState.shelves[Store.ROCKSTAR]?.let { StoresState.shelves[Store.ROCKSTAR] = StoreFront.markOwned(it, games, RockstarCatalog::sameGame) } } + StoreLibraryCache.save(app, Store.ROCKSTAR, games) { generation.get() == gen } StoresState.logLine("Rockstar: ${games.size} owned games") } catch (e: Exception) { StoresState.logLine("Rockstar: library sync failed: ${e.javaClass.simpleName} ${e.message.orEmpty().take(300)}") diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftActivation.kt b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftActivation.kt index d11fde4210..06075ca15d 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftActivation.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftActivation.kt @@ -15,23 +15,44 @@ object UbisoftActivation { private const val POLL_MS = 250L private const val IDLE_MS = 60_000L private val watching = HashMap() + private val owners = HashMap() + + private const val INVALIDATE = "denuvo-invalidate" fun bridge(context: Context, product: Long) = File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/ubisoft/bridge-$product") /** Starts answering the product's activations; stale requests are cleared before this returns. */ - fun watch(app: Context, product: Long) { + fun watch(app: Context, product: Long, owner: String?) { val dir = bridge(app, product) synchronized(watching) { val running = watching.containsKey(product) watching[product] = System.currentTimeMillis() + if (owner.isNullOrEmpty()) owners.remove(product) else owners[product] = owner if (running) return dir.mkdirs() - dir.listFiles()?.forEach { it.delete() } + dir.listFiles()?.forEach { if (it.name != INVALIDATE) it.delete() } } Thread({ var idleSince = 0L while (true) { - runCatching { dir.listFiles { f -> f.name.startsWith("denuvo-") && f.name.endsWith(".req") }?.forEach { answer(app, product, it) } } + runCatching { + val marker = File(dir, INVALIDATE) + val (owner, requests) = synchronized(watching) { + owners[product] to dir.listFiles { f -> f.name.startsWith("denuvo-") && f.name.endsWith(".req") }.orEmpty() + } + if (marker.exists()) { + val named = runCatching { marker.readText().trim() }.getOrNull()?.takeIf { it.isNotEmpty() } + val issuer = named ?: owner + if (invalidate(app, product, issuer)) marker.delete() + else if (named == null && issuer != null) runCatching { + val part = File(dir, "$INVALIDATE.part") + part.writeText(issuer) + check(part.renameTo(marker)) + } + } + val pending = marker.exists() + requests.forEach { answer(app, product, it, owner, pending) } + } .onFailure { StoresState.logLine("Ubisoft: activation for $product: ${it.javaClass.simpleName}") } val now = System.currentTimeMillis() if (SessionState.running) idleSince = 0L @@ -44,18 +65,31 @@ object UbisoftActivation { }, "ubisoft-activation-$product").start() } - private fun answer(app: Context, product: Long, request: File) { + private fun answer(app: Context, product: Long, request: File, owner: String?, pending: Boolean) { val challenge = runCatching { request.readBytes() }.getOrNull() ?: return request.delete() - val reply = File(request.parentFile, request.name.removeSuffix(".req") + ".rsp") - val token = activate(app, product, challenge) + val reply = File(request.parentFile, request.name.removeSuffix(".req").removeSuffix(".cache") + ".rsp") + val token = activate(app, product, challenge, owner, cached = request.name.endsWith(".cache.req") && !pending) val part = File(reply.path + ".part") part.writeBytes(token ?: ByteArray(0)) part.renameTo(reply) } - private fun activate(app: Context, product: Long, challenge: ByteArray): ByteArray? { + private fun invalidate(app: Context, product: Long, owner: String?): Boolean { + val user = owner ?: return false + val gone = TokenCache(cacheDir(app)).drop(user, product) + if (gone) StoresState.logLine("Ubisoft: activation for $product: kept game token dropped") + return gone + } + + private fun activate(app: Context, product: Long, challenge: ByteArray, owner: String?, cached: Boolean): ByteArray? { val s = UbisoftAuth.current(app) ?: return null.also { StoresState.logLine("Ubisoft: activation for $product: signed out") } + if (owner == null || s.userId != owner) return null.also { StoresState.logLine("Ubisoft: activation for $product: the signed-in account changed") } + val cache = TokenCache(cacheDir(app)) + if (cached) cache.get(s.userId, product)?.let { + StoresState.logLine("Ubisoft: activation for $product: kept ${it.size} B game token") + return it + } val answer = UbisoftNative.call("denuvo", JSONObject().put("ticket", s.ticket).put("sessionId", s.sessionId) .put("productId", product).put("challenge", hex(challenge))) answer?.optString("error")?.takeIf { it.isNotEmpty() }?.let { @@ -64,9 +98,28 @@ object UbisoftActivation { } val token = answer?.optString("token")?.takeIf { it.isNotEmpty() }?.let(::unhex) StoresState.logLine("Ubisoft: activation for $product: ${token?.size ?: 0} B game token") + if (token != null && !cache.put(s.userId, product, token)) StoresState.logLine("Ubisoft: activation for $product: game token not kept") return token } + private fun cacheDir(app: Context) = File(app.filesDir, "ubisoft/denuvo") + + internal class TokenCache(private val dir: File) { + private fun file(user: String, product: Long) = File(dir, "${user.filter { it.isLetterOrDigit() || it == '-' }}-$product.token") + + fun get(user: String, product: Long): ByteArray? = runCatching { file(user, product).readBytes() }.getOrNull()?.takeIf { it.isNotEmpty() } + + fun put(user: String, product: Long, token: ByteArray): Boolean = runCatching { + dir.mkdirs() + val target = file(user, product) + val part = File(target.path + ".part") + part.writeBytes(token) + check(part.renameTo(target)) + }.isSuccess + + fun drop(user: String, product: Long): Boolean = file(user, product).let { it.delete() || !it.exists() } + } + internal fun hex(b: ByteArray): String = b.joinToString("") { "%02x".format(it) } internal fun unhex(s: String): ByteArray? = diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftBackend.kt b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftBackend.kt index 5d1a8c31bc..ba3053ef7c 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftBackend.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftBackend.kt @@ -15,6 +15,7 @@ import com.droiddeck.launcher.stores.StoreInstallRoot import com.droiddeck.launcher.stores.download.DownloadEntry import com.droiddeck.launcher.stores.download.DownloadQueue import com.droiddeck.launcher.stores.StoreLoginActivity +import com.droiddeck.launcher.stores.StoreLibraryCache import com.droiddeck.launcher.stores.StoresState import com.droiddeck.launcher.stores.WebCookies import org.json.JSONObject @@ -206,7 +207,16 @@ object UbisoftLibrary { post(gen) { StoresState.status.remove(Store.UBISOFT); StoresState.problems[Store.UBISOFT] = app.getString(R.string.stores_sync_sign_in) } return } - if (StoresState.library[Store.UBISOFT].isNullOrEmpty()) post(gen) { StoresState.status[Store.UBISOFT] = app.getString(R.string.stores_sync_game_list) } + val cached = StoreLibraryCache.load(app, Store.UBISOFT) + post(gen) { + if (StoresState.library[Store.UBISOFT] == null) { + if (cached != null) { + StoresState.library[Store.UBISOFT] = cached + StoresState.shelves[Store.UBISOFT]?.let { StoresState.shelves[Store.UBISOFT] = StoreFront.markOwned(it, cached, UbisoftStore::sameGame) } + } + else StoresState.status[Store.UBISOFT] = app.getString(R.string.stores_sync_game_list) + } + } val all = ArrayList() var offset = 0 while (true) { @@ -241,6 +251,7 @@ object UbisoftLibrary { StoresState.library[Store.UBISOFT] = games StoresState.shelves[Store.UBISOFT]?.let { StoresState.shelves[Store.UBISOFT] = StoreFront.markOwned(it, games, UbisoftStore::sameGame) } } + StoreLibraryCache.save(app, Store.UBISOFT, games) { generation.get() == gen } StoresState.logLine("Ubisoft: ${games.size} owned games") } catch (e: Exception) { StoresState.logLine("Ubisoft: library sync failed: ${e.javaClass.simpleName} ${e.message.orEmpty().take(200)}") diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftCloud.kt b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftCloud.kt new file mode 100644 index 0000000000..26001da37a --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftCloud.kt @@ -0,0 +1,220 @@ +package com.droiddeck.launcher.stores.ubisoft + +import android.os.Build +import android.util.Base64 +import com.droiddeck.launcher.stores.CloudChanged +import com.droiddeck.launcher.stores.CloudFile +import com.droiddeck.launcher.stores.CloudTransport +import org.json.JSONArray +import org.json.JSONObject +import java.io.ByteArrayOutputStream +import java.net.HttpURLConnection +import java.net.URL +import java.security.MessageDigest +import java.time.Instant +import java.util.zip.Deflater +import java.util.zip.Inflater + +internal interface UbisoftSlots { + fun entity(): UbisoftCloud.Entity? + fun upload(slot: String, data: ByteArray) + fun update(entity: UbisoftCloud.Entity, slots: JSONArray) + fun download(slot: String): ByteArray? +} + +internal class UbisoftCloud(private val session: UbisoftAuth.Session, val product: Long) : UbisoftSlots { + class Slot(val id: Int, val filename: String, val hash: String, val size: Long, val modifiedMs: Long) + + class Entity(val json: JSONObject) { + val id: String get() = json.optString("entityId") + val revision: Int get() = json.optInt("revision") + val slots: List get() { + val list = json.optJSONObject("obj")?.optJSONArray("slots") ?: JSONArray() + return (0 until list.length()).mapNotNull { list.optJSONObject(it) }.map { + Slot(it.optInt("id"), it.optString("filename"), it.optString("hash"), it.optLong("size"), UbisoftAuth.parseTime(it.optString("lastModified"))) + } + } + } + + private val authorization get() = "ubi_v1 t=${session.ticket}" + + override fun entity(): Entity? { + val url = "https://public-ubiservices.ubi.com/v1/profiles/${session.profileId}/entities?name=${entityName(product)}" + val reply = UbisoftAuth.request(url, authorization = authorization, sessionId = session.sessionId) + check(reply.ok) { "Ubisoft cloud saves answered ${reply.status}" } + val list = JSONObject(reply.body).optJSONArray("entities") ?: return null + return (0 until list.length()).mapNotNull { list.optJSONObject(it) }.firstOrNull { it.optString("name") == entityName(product) }?.let(::Entity) + } + + override fun upload(slot: String, data: ByteArray) { + val packed = deflate(data) + val md5 = Base64.encodeToString(MessageDigest.getInstance("MD5").digest(packed), Base64.NO_WRAP) + val signed = signed("put", JSONArray().put(JSONObject().put("name", slot).put("size", packed.size).put("md5", md5))).single() + val c = URL(signed.getString("url")).openConnection() as HttpURLConnection + c.connectTimeout = 15_000 + c.readTimeout = 60_000 + c.requestMethod = "PUT" + c.doOutput = true + c.setFixedLengthStreamingMode(packed.size) + c.setRequestProperty("Content-MD5", md5) + try { + c.outputStream.use { it.write(packed) } + check(c.responseCode in 200..299) { "Ubisoft cloud save upload answered ${c.responseCode}" } + } finally { + c.disconnect() + } + } + + override fun update(entity: Entity, slots: JSONArray) { + val obj = JSONObject(entity.json.optJSONObject("obj")?.toString() ?: "{}") + .put("slots", slots).put("timestamp", (System.currentTimeMillis() / 1000).toString()).put("pc_name", Build.MODEL ?: "Android") + val body = JSONObject().put("revision", entity.revision).put("name", entity.json.optString("name")).put("type", "cloudSave") + .put("spaceId", entity.json.optString("spaceId")).put("tags", entity.json.optJSONArray("tags") ?: JSONArray()).put("obj", obj) + val reply = UbisoftAuth.request("https://public-ubiservices.ubi.com/v1/profiles/entities/${entity.id}", "PUT", + authorization, session.sessionId, body.toString()) + check(reply.ok) { "Ubisoft cloud save record answered ${reply.status}" } + } + + override fun download(slot: String): ByteArray? { + val signed = signed("get", JSONArray().put(JSONObject().put("name", slot))).single() + val c = URL(signed.getString("url")).openConnection() as HttpURLConnection + c.connectTimeout = 15_000 + c.readTimeout = 60_000 + return try { + when (c.responseCode) { + 404 -> null + in 200..299 -> c.inputStream.use(::inflate) + else -> error("Ubisoft cloud save download answered ${c.responseCode}") + } + } finally { + c.disconnect() + } + } + + private fun signed(method: String, items: JSONArray): List { + val answer = UbisoftNative.call("cloud-urls", JSONObject().put("ticket", session.ticket).put("sessionId", session.sessionId) + .put("productId", product).put("method", method).put("items", items)) ?: error("Ubisoft cloud saves are unavailable") + answer.optString("error").takeIf { it.isNotEmpty() }?.let { error(it) } + val requests = answer.getJSONArray("requests") + return (0 until requests.length()).map { requests.getJSONObject(it) } + } + + companion object { + private const val MAX_SAVE = 256L * 1024 * 1024 + + fun entityName(product: Long) = "upcCloudSaveUplayId_$product" + + private val MARK = Regex("[0-9a-f]{32}") + + internal fun freshMark(): String = java.util.UUID.randomUUID().toString().replace("-", "") + + internal fun mark(save: ByteArray): String? = + if (save.size < 40) null else String(save, 8, 32, Charsets.ISO_8859_1).takeIf { MARK.matches(it) } + + internal fun deflate(data: ByteArray): ByteArray { + val deflater = Deflater(Deflater.BEST_COMPRESSION) + deflater.setInput(data) + deflater.finish() + val out = ByteArrayOutputStream(data.size / 2 + 64) + val buffer = ByteArray(64 * 1024) + try { + while (!deflater.finished()) out.write(buffer, 0, deflater.deflate(buffer)) + } finally { + deflater.end() + } + return out.toByteArray() + } + + internal fun inflate(data: ByteArray): ByteArray = inflate(data.inputStream()) + + internal fun inflate(input: java.io.InputStream): ByteArray { + val inflater = Inflater() + val out = ByteArrayOutputStream(64 * 1024) + val buffer = ByteArray(64 * 1024) + val chunk = ByteArray(64 * 1024) + try { + while (!inflater.finished()) { + if (inflater.needsInput()) { + val read = input.read(chunk) + if (read < 0) error("Ubisoft cloud save is truncated") + inflater.setInput(chunk, 0, read) + continue + } + if (inflater.needsDictionary()) error("Ubisoft cloud save is truncated") + val n = inflater.inflate(buffer) + check(out.size().toLong() + n <= MAX_SAVE) { "Ubisoft cloud save is too large" } + out.write(buffer, 0, n) + } + } finally { + inflater.end() + } + return out.toByteArray() + } + + internal fun version(slot: Slot): String = "${slot.size}:${slot.modifiedMs}:${slot.hash}" + } +} + +internal class UbisoftCloudTransport(private val cloud: UbisoftSlots, val user: String) : CloudTransport { + private var listed: UbisoftCloud.Entity? = null + private val committed = HashMap() + + override val contentDigests: Boolean get() = false + + override fun committed(name: String): CloudFile? = committed[name] + + override fun wants(name: String): Boolean = name.endsWith(SUFFIX) && !name.contains('/') + + override fun list(): List { + val entity = cloud.entity() + listed = entity + return entity?.slots.orEmpty().map { CloudFile(it.filename + SUFFIX, it.modifiedMs, UbisoftCloud.version(it)) } + } + + override fun get(file: CloudFile): Pair { + val data = cloud.download(file.name.removeSuffix(SUFFIX)) ?: error("Ubisoft has no data for ${file.name}") + return data to file.modifiedMs + } + + override fun put(files: Map, modifiedMs: Map): Map { + var expected = listed ?: cloud.entity() ?: error("Ubisoft has no cloud save record for this game yet; play it once in Ubisoft Connect") + val marks = files.mapValues { (name, data) -> + check(name.endsWith(SUFFIX) && !name.contains('/')) { "$name is not a Ubisoft save slot" } + UbisoftCloud.mark(data) ?: error("$name has no save identifier for Ubisoft Connect") + } + val sent = LinkedHashMap() + try { + for ((name, data) in files) { + val slot = name.removeSuffix(SUFFIX) + val live = cloud.entity() ?: error("Ubisoft's cloud save record disappeared") + if (live.revision != expected.revision) throw CloudChanged(sent, files.keys.filter { it !in sent }) + val now = System.currentTimeMillis() + cloud.upload(slot, data) + val slots = JSONArray(live.json.optJSONObject("obj")?.optJSONArray("slots")?.toString() ?: "[]") + val entry = (0 until slots.length()).map { slots.getJSONObject(it) }.firstOrNull { it.optString("filename") == slot } + ?: JSONObject().put("filename", slot).also { if (slot.toIntOrNull() != null) it.put("id", slot.toInt()); slots.put(it) } + entry.put("hash", marks.getValue(name)).put("size", data.size).put("lastModified", Instant.ofEpochMilli(now).toString()) + cloud.update(live, slots) + val after = cloud.entity() + val mine = after?.let { committedSlot(live, it, slot, marks.getValue(name), data.size.toLong()) } + ?: throw CloudChanged(sent, files.keys.filter { it !in sent }) + sent[name] = now + committed[name] = CloudFile(name, mine.modifiedMs, UbisoftCloud.version(mine)) + expected = after + } + } finally { + listed = null + } + return sent + } + + companion object { + const val SUFFIX = ".save" + + internal fun committedSlot(before: UbisoftCloud.Entity, after: UbisoftCloud.Entity, filename: String, hash: String, size: Long): UbisoftCloud.Slot? { + fun others(e: UbisoftCloud.Entity) = e.slots.filter { it.filename != filename }.associate { it.filename to UbisoftCloud.version(it) } + if (others(before) != others(after)) return null + return after.slots.firstOrNull { it.filename == filename && it.hash == hash && it.size == size } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftLaunch.kt b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftLaunch.kt index 279d3b3e43..4f284f77b4 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftLaunch.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/ubisoft/UbisoftLaunch.kt @@ -58,7 +58,7 @@ object UbisoftLaunch { } } ?: cached setup?.let { StoresState.logLine("Ubisoft: setup for $product: ${it.toString().take(1500)}") } - UbisoftActivation.watch(app, product) + UbisoftActivation.watch(app, product, s.userId) return JSONObject().put("ok", true) .put("productId", product) .put("ticket", native.optString("ticket")) 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 d678a2f410..32597faeb7 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 @@ -112,11 +112,21 @@ object XboxBackend : StoreBackend { fun selectPackage(context: Context, choice: org.json.JSONObject) { val pending = packageChoice ?: return packageChoice = null - val item = pending.item.copy(extra = pending.item.extra + ("contentId" to choice.getString("contentId"))) + val item = pending.item.chosen(choice) com.droiddeck.launcher.stores.download.SavedQueue.remember(context, item, pending.root) enqueue(context.applicationContext, item, pending.root) } + /** + * The picker can offer a package in a different container format than the + * catalogue listed, and the installer dispatches on that format, so the + * choice decides it and the catalogue value only fills a missing one. + */ + private fun CatalogItem.chosen(choice: org.json.JSONObject): CatalogItem { + val format = choice.optString("packageFormat").takeIf { it.isNotBlank() } ?: extra["format"].orEmpty() + return copy(extra = extra + mapOf("contentId" to choice.getString("contentId"), "format" to format)) + } + override fun install(context: Context, item: CatalogItem, root: File) { val app = context.applicationContext if (!item.extra["baseId"].isNullOrBlank()) { XboxContent.install(app, item); return } @@ -128,7 +138,7 @@ object XboxBackend : StoreBackend { val choices = XboxCatalog.objects(plan.getJSONArray("choices")).filter { it.optBoolean("supported") && it.optString("kind") == "Game" } check(choices.isNotEmpty()) { "This offer has no supported PC package." } if (plan.getString("status") == "ready" && choices.size == 1) { - val selected = item.copy(extra = item.extra + ("contentId" to choices.single().getString("contentId"))) + val selected = item.chosen(choices.single()) com.droiddeck.launcher.stores.download.SavedQueue.remember(app, selected, root) enqueue(app, selected, root) } else StoresState.post { packageChoice = PackageChoice(item, root, choices) } 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 6f50a03039..cd3982ebdd 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 @@ -18,6 +18,14 @@ internal object XboxCatalog { "CFQ7TTC10QFD" to "Xbox Game Pass (Starter Edition)", ) + /** + * The formats the installer can put on disk, so the catalogue never lists a + * title it cannot install. `MSIXVC` streams in place; an EAppx container is a + * legacy package that takes `legacy-install` instead. + */ + internal fun installableFormat(format: String): Boolean = + format.equals("MSIXVC", true) || format.equals("EAPPX", true) || format.equals("EAPPXBUNDLE", true) + 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 @@ -102,11 +110,15 @@ internal object XboxCatalog { if (!productId.matches(id) || json.optString("ProductType") != "Game") return null val localized = objects(json.optJSONArray("LocalizedProperties")).firstOrNull() ?: return null val title = localized.optString("ProductTitle").takeIf { it.isNotBlank() } ?: return null - val packages = objects(json.optJSONArray("DisplaySkuAvailabilities")).flatMap { - objects(it.optJSONObject("Sku")?.optJSONObject("Properties")?.optJSONArray("Packages")) - } + val packages = objects(json.optJSONArray("DisplaySkuAvailabilities")) + .mapNotNull { it.optJSONObject("Sku")?.optJSONObject("Properties") } + .filter { it.opt("IsTrial") != true && it.opt("IsPreOrder") != true } + .flatMap { objects(it.optJSONArray("Packages")) } val pc = packages.filter { pkg -> objects(pkg.optJSONArray("PlatformDependencies")).any { it.optString("PlatformName") == "Windows.Desktop" } } - val installable = pc.any { it.optString("PackageFormat").equals("MSIXVC", true) } + val installable = pc.any { installableFormat(it.optString("PackageFormat")) } + // The installer needs the format, not just the fact that one exists: a + // legacy container takes a different subcommand from a streamed package. + val format = pc.firstOrNull { installableFormat(it.optString("PackageFormat")) }?.optString("PackageFormat").orEmpty() val streams = cloud?.streams(id, access[id].orEmpty()) == true if (!installable && !streams) return null val images = objects(localized.optJSONArray("Images")) @@ -129,7 +141,8 @@ internal object XboxCatalog { publisher = localized.optString("PublisherName"), developer = localized.optString("DeveloperName"), description = localized.optString("ProductDescription"), sizeBytes = if (installable) pc.maxOfOrNull { it.optLong("MaxDownloadSizeInBytes") } ?: 0L else 0L, - extra = mapOf("market" to Xodus.market(), "access" to kind.orEmpty(), "pc" to flag(installable), "cloud" to flag(streams)), + extra = mapOf("market" to Xodus.market(), "access" to kind.orEmpty(), "pc" to flag(installable), + "cloud" to flag(streams), "format" to format), ) } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxContent.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxContent.kt index 1594dee927..be9731cdb7 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxContent.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxContent.kt @@ -40,7 +40,8 @@ internal object XboxContent { val item = CatalogItem(Store.XBOX, id, localized?.optString("ProductTitle")?.ifBlank { id } ?: id, imageUrl = base.sidecar.cover, owned = access == "owned", subscription = access == "gamepass", sizeBytes = pkg.optLong("MaxDownloadSizeInBytes"), - extra = mapOf("baseId" to base.sidecar.id, "contentId" to cid, "market" to market, "family" to pkg.getString("PackageFamilyName"))) + extra = mapOf("baseId" to base.sidecar.id, "contentId" to cid, "market" to market, + "family" to pkg.getString("PackageFamilyName"), "format" to pkg.optString("PackageFormat"))) Offer(item, File(base.folder, ".xbox-content/$id/.droiddeck-content.json").isFile) } StoresState.post { plan = Plan(base, offers) } @@ -51,7 +52,7 @@ internal object XboxContent { private fun packages(product: JSONObject?): List = XboxCatalog.objects(product?.optJSONArray("DisplaySkuAvailabilities")) .filter { it.optJSONObject("Sku")?.optJSONObject("Properties")?.optBoolean("IsTrial", true) == false } .flatMap { XboxCatalog.objects(it.optJSONObject("Sku")?.optJSONObject("Properties")?.optJSONArray("Packages")) } - .filter { pkg -> pkg.optString("PackageFormat") == "MSIXVC" && + .filter { pkg -> XboxCatalog.installableFormat(pkg.optString("PackageFormat")) && XboxCatalog.objects(pkg.optJSONArray("PlatformDependencies")).any { it.optString("PlatformName") == "Windows.Desktop" } } private val parents = java.util.concurrent.ConcurrentHashMap() diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCredentials.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCredentials.kt index 59403dac0f..0daee79ccd 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCredentials.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxCredentials.kt @@ -249,10 +249,17 @@ internal class XboxCredentials(private val app: Context, expectedGeneration: Str block(current) } fun invalidate(app: Context, revoked: () -> Unit = {}) = storage(app) { - java.io.File(StoreAccounts.dir(app, Store.XBOX), "generation").writeText(UUID.randomUUID().toString()) - StoreAccounts.clear(app, Store.XBOX) - revoked() + try { + java.io.File(StoreAccounts.dir(app, Store.XBOX), "generation").writeText(UUID.randomUUID().toString()) + val device = StoreAccounts.read(app, Store.XBOX)?.optJSONObject("slots")?.opt(DEVICE_SLOT) + val kept = device != null && runCatching { StoreAccounts.write(app, Store.XBOX, deviceOnly(device)) }.isSuccess + if (!kept) StoreAccounts.clear(app, Store.XBOX) + } finally { + revoked() + } } + internal const val DEVICE_SLOT = "dev_license" + internal fun deviceOnly(device: Any): JSONObject = JSONObject().put("slots", JSONObject().put(DEVICE_SLOT, device)) fun storage(app: Context, block: () -> T): T = synchronized(lock) { java.io.RandomAccessFile(java.io.File(StoreAccounts.dir(app, Store.XBOX), "account.lock"), "rw").use { file -> file.channel.lock().use { block() } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxInstaller.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxInstaller.kt index 3d02e4db57..85ea9fad69 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxInstaller.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxInstaller.kt @@ -15,6 +15,10 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog private val paused = CountDownLatch(1) @Volatile private var child: Xodus.Child? = null @Volatile private var delete = false + /** A legacy container has no pause protocol: the downloader is killed instead. */ + private val legacy = item.extra["format"]?.lowercase() in setOf("eappx", "eappxbundle") + /** Release builds hide logcat from adb, so the tail is reported in the failure itself. */ + private val errors = java.util.concurrent.ConcurrentLinkedQueue() override fun run(handle: DownloadQueue.JobHandle): String? { if (cancelled.get()) return null @@ -41,13 +45,21 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog val source = if (content) selected else item.id val guestFolder = StoreInstallRoot.guestPathForXodus(app, folder) val selection = if (content) emptyList() else listOf("--selected-content-id", selected) - Xodus.start(app, listOf("streaming", source, guestFolder, "--market", market, - "--progress-json", "--control-stdin") + selection).use { process -> + // Streaming rejects a legacy container outright, so dispatch on the + // format the catalogue recorded rather than fail after a download. + val command = if (legacy) "legacy-install" else "streaming" + Xodus.start(app, if (legacy) { + listOf(command, source, guestFolder, "--market", market, "--progress-json", "--store-id", item.id) + selection + } else { + listOf(command, source, guestFolder, "--market", market, "--progress-json", "--control-stdin") + selection + }).use { process -> child = process val rejected = AtomicBoolean(false) val rejectedLine = Regex(Xodus.SIGN_IN_REJECTED) val diagnostics = Xodus.diagnostics(process) { line -> StoresState.logLine("Xbox: $line") + errors.add(line) + while (errors.size > MAX_ERROR_LINES) errors.poll() if (line.matches(rejectedLine)) rejected.set(true) } if (cancelled.get()) process.process.destroy() @@ -60,7 +72,16 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog when (progress.getString("phase")) { "complete" -> complete = true "downloading", "download", "transfer" -> handle.progress(progress.getLong("completedBytes"), progress.optLong("totalBytes")) - "finalizing", "installing" -> handle.stage(DownloadStage.INSTALL) + // Unpacking reports files, not bytes: the frontend hands + // over one container and the backend counts what it has + // written, which is the only measure that moves while a + // single multi-gigabyte member is decrypted. + "installing" -> { + handle.stage(DownloadStage.INSTALL) + val total = progress.optLong("totalBytes") + if (total > 0L) handle.stageProgress(progress.getLong("completedBytes"), total) + } + "finalizing" -> handle.stage(DownloadStage.INSTALL) else -> handle.stage(DownloadStage.MANIFEST) } } @@ -69,7 +90,14 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog diagnostics.join(2000) if (cancelled.get()) return null check(!rejected.get()) { app.getString(com.droiddeck.launcher.R.string.stores_xbox_sign_in_again) } - check(process.process.exitValue() == 0 && complete) { "Xbox download did not complete. Resume to retry with fresh licenses." } + val exit = process.process.exitValue() + if (exit != 0 || !complete) { + val tail = errors.toList().takeLast(MAX_ERROR_LINES) + report(command, source, market, exit, tail) + licenseRefusal(tail)?.let { error(app.getString(it)) } + error("Xbox download did not complete. Resume to retry with fresh licenses." + + tail.takeLast(3).joinToString("") { "\n$it" }) + } } if (content) { XboxContent.complete(app, item, folder) @@ -87,6 +115,21 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog } } + /** Writes the backend's words beside the app, where adb can read them. */ + private fun report(command: String, source: String, market: String, exit: Int, tail: List) { + val text = buildString { + appendLine("command: $command $source --market $market") + appendLine("legacy: $legacy") + appendLine("exit: $exit") + appendLine("--- stderr (last ${tail.size} lines) ---") + tail.forEach { appendLine(it) } + } + runCatching { + app.getExternalFilesDir(null)?.let { File(it, "xbox-install.log").writeText(text) } + } + StoresState.logLine("Xbox install failed (exit $exit): ${tail.lastOrNull().orEmpty()}") + } + override fun cancel(deleteFiles: Boolean) { cancelled.set(true) delete = deleteFiles @@ -98,14 +141,25 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog } Thread({ runCatching { - process.send(JSONObject().put("schema", 1).put("command", "pause")) - paused.await(3, TimeUnit.SECONDS) + if (!legacy) { + process.send(JSONObject().put("schema", 1).put("command", "pause")) + paused.await(3, TimeUnit.SECONDS) + } + process.close() } - process.close() }, "xbox-download-stop").start() } companion object { + private const val MAX_ERROR_LINES = 40 + const val DEVICES_URL = "https://account.microsoft.com/devices/content" + private const val LICENSE_DIAGNOSTIC = "NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 " + internal fun licenseRefusal(tail: List): Int? = when (tail.lastOrNull { it.startsWith(LICENSE_DIAGNOSTIC) } + ?.removePrefix(LICENSE_DIAGNOSTIC)?.substringBefore(' ')) { + "content-device-limit" -> com.droiddeck.launcher.R.string.stores_xbox_device_group_full + "content-device-name" -> com.droiddeck.launcher.R.string.stores_xbox_license_refused + else -> null + } internal fun executable(folder: File): String = XboxManifest.executable(folder) } } diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxLaunchViews.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxLaunchViews.kt index 9316ab27ef..c18bb9bb2e 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxLaunchViews.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxLaunchViews.kt @@ -18,7 +18,8 @@ internal class XboxLaunchViews { parent.listFiles()?.filter { it.name.startsWith("launch-") }?.forEach(::remove) recovered.add(parent.path) } - return Files.createTempDirectory(parent.toPath(), "launch-").toFile() + // The guest binds the files directory by the path Android reports, not its canonical one. + return File(files, "xbox-runtime/views/" + Files.createTempDirectory(parent.toPath(), "launch-").fileName) } companion object { diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxLibraryCache.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxLibraryCache.kt index 5de1abcac8..074e1e9025 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxLibraryCache.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxLibraryCache.kt @@ -29,7 +29,10 @@ internal object XboxLibraryCache { .put("image", game.imageUrl).put("poster", game.tallImageUrl).put("description", game.description) .put("developer", game.developer).put("publisher", game.publisher).put("size", game.sizeBytes) .put("access", if (game.subscription) "gamepass" else if (game.owned) "owned" else "none") - .put("pc", game.xboxPc).put("cloud", game.xboxCloud).put("cloudId", game.extra["cloudId"].orEmpty())) + .put("pc", game.xboxPc).put("cloud", game.xboxCloud).put("cloudId", game.extra["cloudId"].orEmpty()) + // The installer picks its subcommand from this; without it a + // cached legacy game would fall back to streaming. + .put("format", game.extra["format"].orEmpty())) }).toString() internal fun decode(text: String?, account: String, market: String, now: Long = System.currentTimeMillis()): Snapshot? = runCatching { @@ -46,13 +49,18 @@ internal object XboxLibraryCache { val title = row.getString("title") val access = row.getString("access") val cloudId = row.optString("cloudId").takeIf { it.matches(Regex("[A-Z0-9]{12}")) }.orEmpty() + val format = row.optString("format").takeIf { XboxCatalog.installableFormat(it) }.orEmpty() require(id.matches(Regex("[A-Z0-9]{12}")) && title.isNotBlank() && access in setOf("owned", "gamepass")) + // A title with no legacy format keeps the plain shape a cache written + // before formats existed has, so a restart round-trips unchanged. + val extra = linkedMapOf("market" to market, "access" to access, + "pc" to XboxCatalog.flag(row.getBoolean("pc")), "cloud" to XboxCatalog.flag(row.getBoolean("cloud")), "cloudId" to cloudId) + if (format.isNotEmpty()) extra["format"] = format CatalogItem(Store.XBOX, id, title, row.optString("image").takeIf { it.isNotEmpty() }, tallImageUrl = row.optString("poster").takeIf { it.isNotEmpty() }, description = row.optString("description"), developer = row.optString("developer"), publisher = row.optString("publisher"), sizeBytes = row.optLong("size"), owned = access == "owned", subscription = access == "gamepass", - storeUrl = "https://www.xbox.com/games/store/$id", extra = mapOf("market" to market, "access" to access, - "pc" to XboxCatalog.flag(row.getBoolean("pc")), "cloud" to XboxCatalog.flag(row.getBoolean("cloud")), "cloudId" to cloudId)) + storeUrl = "https://www.xbox.com/games/store/$id", extra = extra) } require(games.map { it.id }.distinct().size == games.size) Snapshot(games, savedAt) diff --git a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt index d738193ed7..d966dea1e8 100644 --- a/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt +++ b/app/src/main/java/com/droiddeck/launcher/stores/xbox/XboxManifest.kt @@ -5,12 +5,25 @@ import org.xmlpull.v1.XmlPullParser internal object XboxManifest { data class Info(val storeId: String, val name: String, val publisher: String, val version: String, - val dependency: String, val related: List, val executables: List) + val dependency: String, val related: List, val executables: List, val entryPoint: String, + val runtimeBehavior: String = "") + + /** A GameCore title describes itself with the config; a legacy package does not. */ + private const val GAME_CONFIG = "MicrosoftGame.config" + private const val APPX_MANIFEST = "AppxManifest.xml" + private const val FULL_TRUST = "Windows.FullTrustApplication" + private const val APP_MODEL = "windowsApp" + private val directBehaviors = setOf("packagedClassicApp", "win32App") fun read(folder: File): Info { - val manifests = folder.listFiles().orEmpty().filter { it.name.equals("MicrosoftGame.config", true) && it.isFile } - require(manifests.size == 1) { "Missing or ambiguous MicrosoftGame.config." } - val manifest = manifests.single() + // Both manifests are read the same way: an identity, an executable path and, + // for a Store package, related content. + val files = folder.listFiles().orEmpty() + val config = files.filter { it.name.equals(GAME_CONFIG, true) && it.isFile } + val legacy = files.filter { it.name.equals(APPX_MANIFEST, true) && it.isFile } + require(config.size + legacy.size == 1) { "Missing or ambiguous game manifest." } + val manifest = (config + legacy).single() + val rootTag = if (config.isEmpty()) "Package" else "Game" require(manifest.length() <= 1_048_576) val parser = android.util.Xml.newPullParser().apply { setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, false) } val identities = ArrayList>() @@ -18,7 +31,11 @@ internal object XboxManifest { val dependencies = ArrayList() val related = ArrayList() val entries = ArrayList() + val entryPoints = ArrayList() + val behaviors = ArrayList() fun attribute(name: String) = parser.getAttributeValue(null, name).orEmpty() + fun localAttribute(name: String) = (0 until parser.attributeCount) + .firstOrNull { parser.getAttributeName(it).substringAfterLast(':') == name }?.let(parser::getAttributeValue).orEmpty() var root = false var elements = 0 manifest.inputStream().use { input -> @@ -29,16 +46,22 @@ internal object XboxManifest { XmlPullParser.DOCDECL -> error("Xbox game manifests cannot contain a DTD.") XmlPullParser.START_TAG -> { require(++elements <= 10_000 && parser.depth <= 64) { "Xbox game manifest is too complex." } - if (parser.depth == 1) { require(!root && parser.name == "Game"); root = true } + if (parser.depth == 1) { require(!root && parser.name == rootTag); root = true } when (parser.name) { "Identity" -> identities.add(listOf(attribute("Name"), attribute("Publisher"), attribute("Version"))) "StoreId" -> storeIds.add(parser.nextText().trim()) "MainPackageDependency" -> dependencies.add(attribute("Name")) "RelatedProduct" -> related.add(parser.nextText().trim()) - "Executable" -> { - val path = attribute("Name").replace('\\', '/') + // Both carry the launch path: an attribute on the config's + // Executable, or on the AppxManifest's Application. + "Executable", "Application" -> { + val path = attribute("Name").ifEmpty { attribute("Executable") }.replace('\\', '/') if (path.endsWith(".exe", true) && attribute("TargetDeviceFamily") in listOf("", "PC", "Windows.Desktop") && !attribute("IsDevOnly").equals("true", true)) entries.add(path) + if (parser.name == "Application") { + attribute("EntryPoint").takeIf { it.isNotEmpty() }?.let(entryPoints::add) + localAttribute("RuntimeBehavior").takeIf { it.isNotEmpty() }?.let(behaviors::add) + } } } } @@ -48,9 +71,25 @@ internal object XboxManifest { require(root && identities.size <= 1 && storeIds.size <= 1 && dependencies.size <= 1) { "Invalid Xbox game manifest." } val ids = related.distinct() require(ids.size <= 128 && ids.all { it.matches(Regex("[A-Z0-9]{12}")) }) + val entry = entryPoints.distinct() + val behavior = behaviors.distinct() + require(entry.size <= 1 && behavior.size <= 1) { "Invalid Xbox game manifest." } val identity = identities.singleOrNull() return Info(storeIds.singleOrNull().orEmpty(), identity?.get(0).orEmpty(), identity?.get(1).orEmpty(), identity?.get(2).orEmpty(), - dependencies.singleOrNull().orEmpty(), ids, entries) + dependencies.singleOrNull().orEmpty(), ids, entries, entry.singleOrNull().orEmpty(), behavior.singleOrNull().orEmpty()) + } + + /** + * A full trust package starts its executable directly. Anything else is activated + * through the Windows app model, which this runtime has no host for, so starting + * the executable would only crash. + */ + fun needsAppModel(folder: File): Boolean { + val info = runCatching { read(folder) }.getOrNull() ?: return false + val behavior = info.runtimeBehavior + if (behavior.equals(APP_MODEL, true)) return true + if (directBehaviors.any { it.equals(behavior, true) }) return false + return info.entryPoint.isNotEmpty() && !info.entryPoint.equals(FULL_TRUST, true) } fun executable(folder: File): String { @@ -63,8 +102,29 @@ internal object XboxManifest { file = matches.single() } require(file.canonicalPath.startsWith(folder.canonicalPath + File.separator)) - if (file.isFile) return file.relativeTo(folder).invariantSeparatorsPath + if (file.isFile) return forwarded(folder, file) ?: file.relativeTo(folder).invariantSeparatorsPath } error("The Xbox package has no supported PC launch executable.") } + + private fun forwarded(folder: File, launcher: File): String? = try { + val arguments = File(launcher.parentFile, launcher.nameWithoutExtension + "LaunchArguments.txt") + if (!arguments.isFile || arguments.length() > 65_536) null + else arguments.readLines().firstNotNullOfOrNull { line -> + line.trim().takeIf { it.startsWith("exe=", ignoreCase = true) }?.substring(4)?.trim() + }?.takeIf { it.isNotEmpty() && !it.contains(':') }?.let { target -> located(folder.canonicalFile, launcher.parentFile.canonicalFile, target) } + } catch (_: java.io.IOException) { + null + } + + private fun located(root: File, start: File, target: String): String? { + var file = start + for (part in target.split('/', '\\').filter { it.isNotEmpty() && it != "." }) { + file = if (part == "..") file.parentFile ?: return null + else file.listFiles().orEmpty().filter { it.name.equals(part, true) }.singleOrNull() ?: return null + } + val resolved = file.canonicalFile + if (!resolved.isFile || !resolved.path.startsWith(root.path + File.separator) || !resolved.extension.equals("exe", true)) return null + return resolved.relativeTo(root).invariantSeparatorsPath + } } 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 f27794d1b5..39866fceea 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 @@ -155,10 +155,12 @@ internal object Xodus { const val SIGN_IN_REJECTED = "Microsoft content licensing rejected sign-in \\(HTTP 401\\)\\. Sign in again in Settings\\." + internal val reportable = Regex("NEXUS_CREDENTIAL_ERROR_V1 [a-z-]{1,48}|NEXUS_LIBRARY_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{1,3} [0-9]{1,6}|NEXUS_SESSION_DIAGNOSTIC_V1 [a-z-]{1,64}|Account library unavailable \\([a-z-]{1,64}\\); credentials and installed games are unchanged\\.|Account library timed out; installed games are unchanged\\.|Xbox profile is temporarily unavailable \\([a-z-]{1,48}\\); stored account is unchanged\\.|Xbox profile request timed out; stored account is unchanged\\.|NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{1,3}|NEXUS_LEGACY_INSTALL_DIAGNOSTIC_V1 [a-z0-9-]{1,48}( [0-9]{1,6})?|NEXUS_LEGACY_INSTALL_DETAIL_V1 [A-Za-z0-9 .,;-]{1,220}|NEXUS_EXTRACT_DIAGNOSTIC_V1 [a-z-]{1,48}|NEXUS_EXTRACT_DETAIL_V1 [A-Za-z0-9 ._?-]{1,220}|$SIGN_IN_REJECTED") + fun diagnostics(child: Child, report: (String) -> Unit = { com.droiddeck.launcher.stores.StoresState.logLine("Xbox: $it") }): Thread = Thread({ runCatching { child.process.errorStream.bufferedReader().useLines { lines -> lines.forEach { line -> - if (line.matches(Regex("NEXUS_CREDENTIAL_ERROR_V1 [a-z-]{1,48}|NEXUS_LIBRARY_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{1,3} [0-9]{1,6}|NEXUS_SESSION_DIAGNOSTIC_V1 [a-z-]{1,64}|Account library unavailable \\([a-z-]{1,64}\\); credentials and installed games are unchanged\\.|Account library timed out; installed games are unchanged\\.|Xbox profile is temporarily unavailable \\([a-z-]{1,48}\\); stored account is unchanged\\.|Xbox profile request timed out; stored account is unchanged\\.|NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 [a-z-]{1,48} [0-9]{3}|$SIGN_IN_REJECTED"))) + if (line.matches(reportable)) report(line) } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt index ae1826bbde..01a486b574 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPage.kt @@ -19,15 +19,18 @@ import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.awaitEachGesture import androidx.compose.foundation.gestures.awaitFirstDown +import androidx.compose.foundation.gestures.waitForUpOrCancellation import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.ime import androidx.compose.foundation.layout.imePadding import androidx.compose.foundation.layout.padding @@ -37,6 +40,7 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardActions @@ -50,11 +54,12 @@ import androidx.compose.material.icons.outlined.Mic import androidx.compose.material.icons.outlined.Add import androidx.compose.material.icons.outlined.ArrowDownward import androidx.compose.material.icons.outlined.AttachFile -import androidx.compose.material.icons.outlined.AutoAwesome +import androidx.compose.material.icons.outlined.Terminal import androidx.compose.material.icons.outlined.Build import androidx.compose.material.icons.outlined.Close import androidx.compose.material.icons.outlined.ExpandMore import androidx.compose.material.icons.outlined.History +import androidx.compose.material.icons.outlined.Lock import androidx.compose.material.icons.outlined.Memory import androidx.compose.material.icons.outlined.MoreHoriz import androidx.compose.material.icons.outlined.Pets @@ -95,6 +100,7 @@ import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.input.nestedscroll.NestedScrollConnection import androidx.compose.ui.input.nestedscroll.NestedScrollSource import androidx.compose.ui.input.nestedscroll.nestedScroll +import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.pointer.PointerEventPass import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.onGloballyPositioned @@ -124,7 +130,7 @@ import kotlinx.coroutines.launch internal enum class AgentPanel { NONE, MODEL, USAGE, HISTORY, PROCESSES, TOOLS } /** Slash commands the app handles itself; others go to the CLI, which has its own. */ -private val LOCAL_COMMANDS = listOf("/new", "/model", "/plan", "/history", "/processes", "/stop") +private val LOCAL_COMMANDS = listOf("/new", "/model", "/permissions", "/plan", "/history", "/processes", "/stop") private val CLI_COMMANDS = listOf("/compact", "/cost", "/review", "/init") /** @@ -203,7 +209,7 @@ private fun AgentPageContent( var setup by rememberSaveable { mutableStateOf(false) } val draft = rememberSaveable { mutableStateOf("") } if (setup || AgentHost.state == AgentHost.State.MISSING || !(AgentSetup.ready || AgentSetup.completed(context))) { - AgentSetupView(modifier, onDone = { setup = false }) + AgentSetupView(modifier, firstControl = inputModifier, onDone = { setup = false }) return } var panel by rememberSaveable { mutableStateOf(AgentPanel.NONE) } @@ -229,6 +235,10 @@ private fun AgentPageContent( // The keyboard leaves too little height for a panel and the editor together, so typing closes the panel. val keyboardOpen = WindowInsets.ime.getBottom(LocalDensity.current) > 0 LaunchedEffect(keyboardOpen) { if (keyboardOpen && (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE)) panel = AgentPanel.NONE } + // History, processes and tools take the whole page, which would hide an approval the turn is waiting on. + LaunchedEffect(AgentHost.approvals.size, panel) { + if (AgentHost.approvals.isNotEmpty() && (panel == AgentPanel.HISTORY || panel == AgentPanel.PROCESSES || panel == AgentPanel.TOOLS)) panel = AgentPanel.NONE + } Column( modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e -> val k = e.nativeKeyEvent @@ -275,7 +285,8 @@ private fun AgentPageContent( readingBack = false scope.launch { list.scrollToItem(maxOf(0, list.layoutInfo.totalItemsCount - 1), Int.MAX_VALUE / 2) } } - val hidden = !composer.focused && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty() + val hidden = !composer.focused && !composer.hasUnconsumedFocusRequest() && readingBack && AgentHost.entries.isNotEmpty() && + AgentHost.approvals.isEmpty() var listHeight by remember { mutableIntStateOf(0) } Box( Modifier.weight(1f).fillMaxWidth().clipToBounds().nestedScroll(dragBack).onGloballyPositioned { @@ -292,7 +303,8 @@ private fun AgentPageContent( awaitEachGesture { awaitFirstDown(requireUnconsumed = false, pass = PointerEventPass.Initial) if (panel == AgentPanel.MODEL || panel == AgentPanel.USAGE) panel = AgentPanel.NONE - if (composer.focused) focusManager.clearFocus() + // Forced: the unforced path walks the focus chain and throws ("ActiveParent with no focused child") when a tap lands while focus is moving. + if (composer.focused) focusManager.clearFocus(force = true) } }, list, following = !readingBack, onRevise = { composer.open() }, onSent = toLatest, @@ -304,7 +316,7 @@ private fun AgentPageContent( } } androidx.compose.animation.AnimatedVisibility(!hidden, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) { - AgentComposer(composer, draft, visible, inlineControls, onPanel = { panel = it }, onSent = toLatest) + AgentComposer(composer, draft, visible && started, inlineControls, onPanel = { panel = it }, onSent = toLatest) } } } @@ -349,7 +361,7 @@ private fun AgentTopBar(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstC } } -/** The harness, model, effort and plan mode, opening the model picker; [compact] names only the model. */ +/** The harness, model, effort, a permission mode other than asking first and plan mode, opening the model picker; [compact] names only the model. */ @Composable private fun ModelChip(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstControl: Modifier, modifier: Modifier = Modifier, compact: Boolean = false) { val context = LocalContext.current @@ -360,8 +372,12 @@ private fun ModelChip(panel: AgentPanel, onPanel: (AgentPanel) -> Unit, firstCon modifier = modifier.then(if (compact) Modifier.widthIn(max = 120.dp) else Modifier).height(36.dp).clip(Shape12).then(firstControl) .clickable { onPanel(AgentPanel.MODEL) }.padding(horizontal = 8.dp).testTag("agent-model"), ) { - val parts = if (compact) listOf(model) - else listOfNotNull(AgentHost.harness.name, model, AgentHost.effort, stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans }) + val mode = AgentHost.harness.permissions.drop(1).firstOrNull { it.id == AgentHost.permission }?.let { stringResource(it.label) } + val parts = if (compact) listOfNotNull(mode ?: model) + else listOfNotNull( + AgentHost.harness.name, model, AgentHost.effort, mode, + stringResource(R.string.agent_plan_short).takeIf { AgentHost.plan && AgentHost.harness.plans }, + ) Text(parts.joinToString(" · "), fontSize = 13.sp, color = if (panel == AgentPanel.MODEL) pal.primary else pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false)) Icon(Icons.Outlined.ExpandMore, null, tint = pal.onSurfaceVariant, modifier = Modifier.size(16.dp)) @@ -451,7 +467,7 @@ private fun AgentConversation(modifier: Modifier, list: LazyListState, following } if (AgentHost.entries.isEmpty() && !working) { Column(modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) { - Icon(Icons.Outlined.AutoAwesome, null, tint = pal.primary, modifier = Modifier.size(40.dp)) + Icon(Icons.Outlined.Terminal, null, tint = pal.primary, modifier = Modifier.size(40.dp)) Text(stringResource(R.string.agent_empty), fontSize = 15.sp, color = pal.onSurfaceVariant, textAlign = TextAlign.Center, modifier = Modifier.widthIn(max = 460.dp).padding(top = 12.dp)) } @@ -518,6 +534,39 @@ internal fun clock(seconds: Long): String { } } +/** The oldest tool call that waits for the user; tapping its input shows all of it. */ +@Composable +private fun AgentApprovalCard(approval: AgentHost.Approval, more: Int) { + val context = LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + var open by remember(approval.id) { mutableStateOf(false) } + Column( + Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape14).background(colors.surface).border(1.dp, AttentionAmber, Shape14) + .padding(horizontal = 14.dp, vertical = 10.dp).testTag("agent-approval"), + ) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Column(Modifier.weight(1f)) { + Text(stringResource(R.string.agent_approval_title, approval.tool), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground) + if (more > 0) Text(stringResource(R.string.agent_approval_more, more), fontSize = 12.5.sp, color = pal.onSurfaceVariant) + } + SecondaryButton(stringResource(R.string.agent_approval_deny), compact = true, modifier = Modifier.testTag("agent-approval-deny")) { + AgentHost.answer(context, approval, allow = false) + } + PrimaryButton(stringResource(R.string.agent_approval_allow), compact = true, modifier = Modifier.testTag("agent-approval-allow")) { + AgentHost.answer(context, approval, allow = true) + } + } + val body = approval.input.ifBlank { approval.detail } + val shown = Modifier.fillMaxWidth().padding(top = 6.dp) + .then(if (open) Modifier.heightIn(max = 280.dp).verticalScroll(rememberScrollState()) else Modifier).clickable { open = !open } + if (body.isNotBlank()) Text( + body, fontSize = 12.sp, fontFamily = FontFamily.Monospace, color = pal.onSurfaceVariant, + maxLines = if (open) Int.MAX_VALUE else 4, overflow = TextOverflow.Ellipsis, modifier = shown, + ) + } +} + @Composable private fun AgentLabCard() { val context = LocalContext.current @@ -670,7 +719,7 @@ private fun AgentComposer( val text = draft.trim() when (text.substringBefore(' ')) { "/new" -> AgentHost.forget(context) - "/model" -> onPanel(AgentPanel.MODEL) + "/model", "/permissions" -> onPanel(AgentPanel.MODEL) "/plan" -> AgentHost.choosePlan(context, !AgentHost.plan) "/history" -> onPanel(AgentPanel.HISTORY) "/processes" -> onPanel(AgentPanel.PROCESSES) @@ -687,6 +736,7 @@ private fun AgentComposer( val keyboardOpen = WindowInsets.ime.getBottom(LocalDensity.current) > 0 Column(Modifier.fillMaxWidth().padding(bottom = if (keyboardOpen) 4.dp else 8.dp)) { if (labOpen) AgentLabCard() + AgentHost.approvals.firstOrNull()?.let { AgentApprovalCard(it, AgentHost.approvals.size - 1) } if (hasActivity()) Row( horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()), @@ -703,9 +753,23 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState voice.finish(send) + voice.finishing -> Unit + else -> send() + } + } val working = AgentHost.state == AgentHost.State.WORKING if (draft.startsWith("/") && !draft.contains(' ')) { val matches = (LOCAL_COMMANDS + CLI_COMMANDS).filter { it.startsWith(draft) && it != draft } @@ -725,23 +789,35 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState Unit = { modifier -> Box(modifier.padding(start = 8.dp, top = 10.dp, bottom = 10.dp)) { if (draft.isEmpty()) Text( - stringResource(if (working) R.string.agent_hint_working else R.string.agent_hint), fontSize = 16.sp, + stringResource( + when { + voice.listening && !voice.locked -> R.string.agent_voice_hold + voice.listening -> R.string.agent_voice_listening + working -> R.string.agent_hint_working + else -> R.string.agent_hint + }, + ), + fontSize = 16.sp, color = pal.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, ) BasicTextField( - draft, { draft = it }, + draft, { + draft = it + if (voice.listening) voice.stop() + }, Modifier.fillMaxWidth().focusRequester(field).onFocusChanged { focused = it.isFocused composer.focused = it.isFocused @@ -750,50 +826,132 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState Unit = { if (working) RoundButton(Icons.Outlined.Stop, stringResource(R.string.agent_stop), pal.error.copy(alpha = 0.22f), colors.error, "agent-stop") { AgentHost.stop(context) } val canSend = draft.isNotBlank() || AgentAttachments.pending.isNotEmpty() // An empty message has nothing to send, so the button there dictates one instead. - if ((!canSend || voice.listening) && voiceAvailable) VoiceButton(voice) { voice.start(draft) } - else RoundButton( + if ((!canSend || voice.listening) && !voice.finishing) VoiceButton(voice, onStart = { voice.start(draft) }, onSend = send, onSetup = { voiceSetup = true }) + if (voice.finishing || (voice.listening && voice.locked) || (canSend && !voice.listening)) RoundButton( Icons.AutoMirrored.Outlined.Send, stringResource(if (working) R.string.agent_queue else R.string.agent_send), - if (canSend) pal.primary else pal.surfaceVariant, if (canSend) pal.onPrimary else pal.onSurfaceVariant, "agent-send", enabled = canSend, - ) { - voice.stop() - send() + pal.primary, pal.onPrimary, "agent-send", enabled = !voice.finishing, + ) { sendNow() } + } + if (stacked) Column { + text(Modifier.fillMaxWidth()) + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { + if (attach) AttachButton() + if (AgentAttachments.gameFrame != null) GameFrameButton() + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp)) { if (controls != null && !focused) controls() } + actions() } + } else Row(verticalAlignment = Alignment.Bottom) { + if (attach) AttachButton() + if (AgentAttachments.gameFrame != null) GameFrameButton() + text(Modifier.weight(1f)) + if (controls != null && !focused) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(42.dp)) { controls() } + actions() } } } +/** + * Held, it listens until let go and then sends; slid up, it keeps listening hands-free; slid left, it puts the text back. + * A tap or a controller press also listens hands-free. + */ @Composable -private fun VoiceButton(voice: AgentVoice, onStart: () -> Unit) { +private fun VoiceButton(voice: AgentVoice, onStart: () -> Unit, onSend: () -> Unit, onSetup: () -> Unit) { val context = LocalContext.current val pal = LocalPalette.current - val ask = if (LocalActivityResultRegistryOwner.current != null) rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> - if (granted) onStart() else android.widget.Toast.makeText(context, R.string.agent_voice_denied, android.widget.Toast.LENGTH_SHORT).show() - } else null - RoundButton( - if (voice.listening) Icons.Outlined.MicOff else Icons.Outlined.Mic, stringResource(if (voice.listening) R.string.agent_voice_stop else R.string.agent_voice), - if (voice.listening) pal.primary else pal.surfaceVariant, if (voice.listening) pal.onPrimary else pal.onBackground, "agent-voice", - ) { + val start by rememberUpdatedState(onStart) + val send by rememberUpdatedState(onSend) + val setup by rememberUpdatedState(onSetup) + val handsFree = { + start() + if (voice.listening) voice.locked = true + } + val toggle = { when { voice.listening -> voice.finish() - context.checkSelfPermission(android.Manifest.permission.RECORD_AUDIO) == android.content.pm.PackageManager.PERMISSION_GRANTED -> onStart() - ask != null -> ask.launch(android.Manifest.permission.RECORD_AUDIO) - else -> android.widget.Toast.makeText(context, R.string.agent_voice_denied, android.widget.Toast.LENGTH_SHORT).show() + !voiceReady(context) -> setup() + else -> handsFree() } } + val density = LocalDensity.current + val lockPx = with(density) { 56.dp.toPx() } + val cancelPx = with(density) { 72.dp.toPx() } + var drag by remember { mutableStateOf(Offset.Zero) } + val holding = voice.listening && !voice.locked + val icon = when { + voice.locked -> Icons.Outlined.MicOff + holding && -drag.x > cancelPx / 2 && -drag.x > -drag.y -> Icons.Outlined.Close + holding && -drag.y > lockPx / 2 -> Icons.Outlined.Lock + else -> Icons.Outlined.Mic + } + val scale = if (holding) 1.12f + 0.12f * voice.level else 1f + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.padding(start = 6.dp).size(42.dp).graphicsLayer { + scaleX = scale + scaleY = scale + }.clip(CircleShape).background(if (voice.listening) pal.primary else pal.surfaceVariant) + .pointerInput(voice) { + awaitEachGesture { + val down = awaitFirstDown(pass = PointerEventPass.Initial) + down.consume() + if (voice.listening || !voiceReady(context)) { + waitForUpOrCancellation(PointerEventPass.Initial)?.let { + it.consume() + toggle() + } + return@awaitEachGesture + } + start() + var resolved = !voice.listening + try { + while (!resolved) { + val change = awaitPointerEvent(PointerEventPass.Initial).changes.firstOrNull { it.id == down.id } ?: break + // Compose ends a cancelled touch stream with a lift that arrives already consumed; that is not a release. + if (!change.pressed && change.isConsumed) break + change.consume() + drag = change.position - down.position + when { + !voice.listening -> resolved = true + drag.y < -lockPx -> { + voice.locked = true + resolved = true + } + drag.x < -cancelPx -> { + voice.cancel() + resolved = true + } + !change.pressed -> { + val tap = change.uptimeMillis - down.uptimeMillis < viewConfiguration.longPressTimeoutMillis / 2 && + drag.getDistance() < viewConfiguration.touchSlop + if (tap) voice.locked = true else voice.finish(send) + resolved = true + } + } + } + } finally { + drag = Offset.Zero + if (!resolved && voice.listening && !voice.locked) voice.finish() + } + } + } + .clickable(onClick = toggle).testTag("agent-voice"), + ) { + Icon( + icon, stringResource(if (voice.listening) R.string.agent_voice_stop else R.string.agent_voice), + tint = if (voice.listening) pal.onPrimary else pal.onBackground, modifier = Modifier.size(21.dp), + ) + } } /** Attaches what the running game shows, taken from its own surface so nothing drawn over it is in the picture. */ diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentPanels.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentPanels.kt index 3fc46e09b1..a462fca130 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentPanels.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentPanels.kt @@ -50,6 +50,11 @@ import androidx.compose.material3.Icon import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.ime +import androidx.compose.foundation.relocation.bringIntoViewRequester +import androidx.compose.ui.text.input.KeyboardType import androidx.compose.runtime.rememberCoroutineScope import kotlinx.coroutines.launch import com.droiddeck.launcher.agent.AgentTools @@ -62,7 +67,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.withContext -/** The model, reasoning effort and plan mode for the next turns; a conversation keeps going with whatever is chosen. */ +/** The model, reasoning effort, permissions and plan mode for the next turns; a conversation keeps going with whatever is chosen. */ @Composable internal fun AgentModelPicker() { val context = LocalContext.current @@ -87,6 +92,20 @@ internal fun AgentModelPicker() { } } } + val modes = AgentHost.harness.permissions + if (modes.size > 1) Column(verticalArrangement = Arrangement.spacedBy(6.dp)) { + Text(stringResource(R.string.agent_permissions), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground, modifier = Modifier.padding(horizontal = 2.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.horizontalScroll(rememberScrollState())) { + for (mode in modes) { + val label = stringResource(mode.label) + if (mode.id == AgentHost.permission) PrimaryButton(label, compact = true, modifier = Modifier.testTag("agent-permission")) {} + else SecondaryButton(label, compact = true, modifier = Modifier.testTag("agent-permission")) { AgentHost.choosePermission(context, mode.id) } + } + } + modes.firstOrNull { it.id == AgentHost.permission }?.let { + Text(stringResource(it.hint), fontSize = 12.5.sp, color = pal.onSurfaceVariant, modifier = Modifier.padding(horizontal = 2.dp)) + } + } if (AgentHost.harness.plans) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp)) { Column(Modifier.weight(1f)) { Text(stringResource(R.string.agent_plan), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground) @@ -416,14 +435,23 @@ private fun ToolsRow(title: String, detail: String, action: @Composable () -> Un } @Composable +@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) internal fun ToolsField(value: String, onValue: (String) -> Unit, hint: String, tag: String) { - val colors = MaterialTheme.colorScheme - val pal = LocalPalette.current - Box(Modifier.fillMaxWidth().clip(Shape12).background(pal.surfaceVariant).padding(horizontal = 12.dp, vertical = 10.dp)) { - if (value.isEmpty()) Text(hint, fontSize = 14.sp, color = pal.onSurfaceVariant, maxLines = 1) - BasicTextField( - value, onValue, singleLine = true, textStyle = TextStyle(fontSize = 14.sp, fontFamily = FontFamily.Monospace, color = colors.onSurface), - cursorBrush = SolidColor(pal.primary), modifier = Modifier.fillMaxWidth().testTag(tag), - ) - } + // The launcher's pane focus group sends a Compose text field's focus back to the last tile it remembers, + // so these fields use the EditText the rest of the launcher types into. + val view = remember { androidx.compose.foundation.relocation.BringIntoViewRequester() } + var focused by remember { mutableStateOf(false) } + val window = androidx.compose.ui.platform.LocalView.current + // An EditText's focus does not scroll its Compose parent, so the field follows the keyboard as it opens. + val keyboard = WindowInsets.ime.getBottom(androidx.compose.ui.platform.LocalDensity.current) + LaunchedEffect(focused, keyboard) { if (focused) view.bringIntoView() } + AdbTextField( + value = value, onValueChange = onValue, label = hint, keyboardType = KeyboardType.Text, imeAction = ImeAction.Done, + modifier = Modifier.bringIntoViewRequester(view).testTag(tag), placeholder = hint, compact = true, showLabel = false, + onFocusChange = { focused = it }, + onDone = { + (window.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager) + ?.hideSoftInputFromWindow(window.windowToken, 0) + }, + ) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentSetupView.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentSetupView.kt index 653e8eedb6..3f7293b748 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentSetupView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentSetupView.kt @@ -4,6 +4,8 @@ import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ExperimentalLayoutApi +import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding @@ -46,7 +48,7 @@ import com.droiddeck.launcher.agent.AgentSetup.Step import com.droiddeck.launcher.core.WirelessAdbPairingService @Composable -internal fun AgentSetupView(modifier: Modifier, onDone: () -> Unit = {}) { +internal fun AgentSetupView(modifier: Modifier, firstControl: Modifier = Modifier, onDone: () -> Unit = {}) { val context = LocalContext.current val colors = MaterialTheme.colorScheme val pal = LocalPalette.current @@ -76,7 +78,7 @@ internal fun AgentSetupView(modifier: Modifier, onDone: () -> Unit = {}) { Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) { for (harness in AgentHarness.all) { val chosen = harness == AgentHost.harness - if (chosen) PrimaryButton(harness.name, compact = true) {} else SecondaryButton(harness.name, enabled = !AgentSetup.busy, compact = true) { AgentHost.choose(context, harness) } + if (chosen) PrimaryButton(harness.name, compact = true, modifier = firstControl) {} else SecondaryButton(harness.name, enabled = !AgentSetup.busy, compact = true) { AgentHost.choose(context, harness) } } } val steps = Step.entries @@ -97,21 +99,21 @@ internal fun AgentSetupView(modifier: Modifier, onDone: () -> Unit = {}) { steps.forEachIndexed { index, step -> val status = AgentSetup.status[step] ?: Status.UNKNOWN val harness = AgentHost.harness - // A harness that signs in with a pasted key: the sign-in opens its key page and this field takes the key. - val keyed = step == Step.SIGN_IN && harness.keyPage != null + // A harness that signs in with pasted keys: this row picks the provider and takes its key. + val keyed = step == Step.SIGN_IN && harness.providers.isNotEmpty() var keyOpen by rememberSaveable(harness.id) { mutableStateOf(false) } val (title, hint) = labels(step, harness.name, keyed) val lab = AgentHost.lab?.takeIf { it.prepare && it.running } val detail = when { step == Step.PREPARE && lab != null -> stringResource(R.string.agent_prepare_progress, lab.permille / 10, clock(lab.etaSeconds.toLong().coerceAtLeast(0))) - keyed && status == Status.DONE && !AgentSetup.keySaved -> stringResource(R.string.agent_step_free_models) + keyed && status == Status.DONE && AgentSetup.detail[step] == null -> + harness.providers.filter { it.id in AgentSetup.keys }.joinToString(" · ") { it.name }.ifEmpty { stringResource(R.string.agent_step_free_models) } else -> AgentSetup.detail[step] ?: hint } // Shown while the sign-in is pending, so it is still there after a trip to the browser for the key. val pending = (status == Status.TODO || status == Status.FAILED) && AgentSetup.status[Step.INSTALL] == Status.DONE val showKey = keyed && (keyOpen || pending) && status != Status.WORKING - var key by remember(harness.id) { mutableStateOf("") } CheckRow( when (status) { Status.DONE -> CheckState.OK @@ -122,33 +124,17 @@ internal fun AgentSetupView(modifier: Modifier, onDone: () -> Unit = {}) { ) { val blocked = (step in setOf(Step.SIGN_IN, Step.GITHUB, Step.BUILD_TOOLS) && AgentSetup.status[Step.INSTALL] != Status.DONE) || (step == Step.PREPARE && AgentSetup.status[Step.BUILD_TOOLS] != Status.DONE) - val openKey = { - keyOpen = true - AgentSetup.run(context, step) - } - if ((status == Status.TODO || status == Status.FAILED) && !blocked) { + if (keyed) { + if (pending && harness.free) SecondaryButton(stringResource(R.string.agent_action_free), compact = true) { AgentSetup.useFree(context) } + else if (status == Status.DONE) SecondaryButton(stringResource(if (keyOpen) R.string.common_hide else R.string.agent_action_add_key), compact = true) { keyOpen = !keyOpen } + } else if ((status == Status.TODO || status == Status.FAILED) && !blocked) { val label = stringResource(if (status == Status.FAILED) R.string.agent_setup_retry else action(step)) - val run = { if (step == Step.CONNECTION) pair(context) else if (keyed) openKey() else AgentSetup.run(context, step) } - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - if (keyed && harness.free) SecondaryButton(stringResource(R.string.agent_action_free), compact = true) { AgentSetup.useFree(context) } - if (step.required) PrimaryButton(label, compact = true, onClick = run) else SecondaryButton(label, compact = true, onClick = run) - } - } else if (keyed && status == Status.DONE && !AgentSetup.keySaved && !keyOpen) { - SecondaryButton(stringResource(R.string.agent_action_add_key), compact = true, onClick = openKey) + val run = { if (step == Step.CONNECTION) pair(context) else AgentSetup.run(context, step) } + if (step.required) PrimaryButton(label, compact = true, onClick = run) else SecondaryButton(label, compact = true, onClick = run) } } if (showKey) { - Row( - verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), - modifier = Modifier.fillMaxWidth().padding(start = 56.dp, end = 14.dp, bottom = 10.dp), - ) { - Box(Modifier.weight(1f)) { ToolsField(key, { key = it.trim() }, stringResource(R.string.agent_key_hint), "agent-key") } - PrimaryButton(stringResource(R.string.agent_key_save), enabled = key.isNotBlank(), compact = true) { - keyOpen = false - AgentSetup.saveKey(context, key) - key = "" - } - } + KeyPanel(harness) { keyOpen = false } if (index < steps.lastIndex) Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line)) } } @@ -167,6 +153,47 @@ internal fun AgentSetupView(modifier: Modifier, onDone: () -> Unit = {}) { } } +/** Picks one of [harness]'s providers and saves its key, or a custom server's address. */ +@OptIn(ExperimentalLayoutApi::class) +@Composable +private fun KeyPanel(harness: AgentHarness, onSaved: () -> Unit) { + val context = LocalContext.current + val provider = harness.providers.firstOrNull { it.id == AgentSetup.provider } ?: harness.providers.first() + var key by remember(harness.id, provider.id) { mutableStateOf("") } + val saved = provider.id in AgentSetup.keys + Column( + verticalArrangement = Arrangement.spacedBy(10.dp), + modifier = Modifier.fillMaxWidth().padding(start = 56.dp, end = 14.dp, bottom = 12.dp), + ) { + FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + for (option in harness.providers) { + val name = if (option.id in AgentSetup.keys) "${option.name} ✓" else option.name + if (option == provider) PrimaryButton(name, compact = true) {} else SecondaryButton(name, compact = true) { AgentSetup.provider = option.id } + } + } + if (provider.custom) ToolsField(AgentSetup.server, { AgentSetup.server = it.trim() }, stringResource(R.string.agent_key_server_hint), "agent-key-server") + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Box(Modifier.weight(1f)) { + ToolsField( + key, { key = it.trim() }, + if (provider.custom) stringResource(R.string.agent_key_optional_hint) else stringResource(R.string.agent_key_hint, provider.name), + "agent-key", + ) + } + provider.keyPage?.let { page -> SecondaryButton(stringResource(R.string.agent_key_get), compact = true) { AgentSetup.openKeyPage(context, page) } } + if (saved) SecondaryButton(stringResource(R.string.agent_storage_remove), compact = true) { AgentSetup.removeKey(context, provider) } + PrimaryButton( + stringResource(R.string.agent_key_save), compact = true, + enabled = if (provider.custom) AgentSetup.server.isNotBlank() else key.isNotBlank(), + ) { + AgentSetup.saveKey(context, provider, key, AgentSetup.server.takeIf { provider.custom }) + key = "" + onSaved() + } + } + } +} + @Composable private fun StorageCard() { val context = LocalContext.current diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentVoice.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentVoice.kt index a6d78e599e..95ce56e58e 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AgentVoice.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentVoice.kt @@ -1,44 +1,93 @@ package com.droiddeck.launcher.ui +import android.content.ComponentName import android.content.Context import android.content.Intent +import android.content.ServiceConnection +import android.os.Build +import android.os.IBinder import android.os.Bundle +import android.os.Handler +import android.os.Looper import android.speech.RecognitionListener +import android.speech.RecognitionService import android.speech.RecognizerIntent import android.speech.SpeechRecognizer import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue -/** Dictation into the Agent editor: what is heard so far follows the text already typed, until the user edits the draft. */ +/** + * Dictation into the Agent editor: what is heard so far follows the text already typed, until the user edits the draft. + * Listening carries on across pauses until [finish], which can send once the last words are written. + */ internal class AgentVoice(private val context: Context, private val draft: () -> String, private val onText: (String) -> Unit) { var listening by mutableStateOf(false) private set + /** Whether listening goes on without the button held. */ + var locked by mutableStateOf(false) + /** How loud the speech is, from 0 to 1. */ + var level by mutableFloatStateOf(0f) + private set + /** Set when the speech service could not open the microphone, which a fresh install of Speech Services by Google cannot until allowed. */ + var serviceMicBlocked by mutableStateOf(false) private var recognizer: SpeechRecognizer? = null + private var typed = "" private var base = "" private var written = "" + /** Set between [finish] and the final result, while a send may still be waiting on the last words. */ + var finishing by mutableStateOf(false) + private set + private var then: (() -> Unit)? = null + private val main = Handler(Looper.getMainLooper()) fun start(typed: String) { stop() - val speech = runCatching { SpeechRecognizer.createSpeechRecognizer(context) }.getOrNull() ?: return + val service = component(context) + val speech = runCatching { SpeechRecognizer.createSpeechRecognizer(context, service) }.getOrNull() ?: return recognizer = speech - base = typed.trimEnd().let { if (it.isEmpty()) it else "$it " } + if (service != null && !isDefault(context)) lend(service) + this.typed = typed + base = continued(typed) written = typed + finishing = false + listening = true speech.setRecognitionListener(object : RecognitionListener { - override fun onReadyForSpeech(params: Bundle?) { listening = true } + override fun onReadyForSpeech(params: Bundle?) {} override fun onBeginningOfSpeech() {} - override fun onRmsChanged(rmsdB: Float) {} + override fun onRmsChanged(rmsdB: Float) { if (recognizer === speech) level = ((rmsdB + 2f) / 12f).coerceIn(0f, 1f) } override fun onBufferReceived(buffer: ByteArray?) {} - override fun onEndOfSpeech() {} - override fun onError(error: Int) { if (recognizer === speech) stop() } + override fun onEndOfSpeech() { level = 0f } + override fun onError(error: Int) { + if (recognizer !== speech) return + // The recognizer gives up on a pause; the user is still talking until they let go or stop. + if (!finishing && (error == SpeechRecognizer.ERROR_NO_MATCH || error == SpeechRecognizer.ERROR_SPEECH_TIMEOUT)) { + base = continued(written) + relisten(speech) + } else { + done() + if (error == SpeechRecognizer.ERROR_AUDIO || error == SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS) serviceMicBlocked = true + } + } override fun onResults(results: Bundle?) { if (recognizer !== speech) return heard(results) - stop() + if (recognizer !== speech) return + if (finishing) done() else { + base = continued(written) + relisten(speech) + } } override fun onPartialResults(partialResults: Bundle?) { if (recognizer === speech) heard(partialResults) } override fun onEvent(eventType: Int, params: Bundle?) {} }) + listen(speech) + } + + private fun continued(text: String) = text.trimEnd().let { if (it.isEmpty()) it else "$it " } + + private fun listen(speech: SpeechRecognizer) { val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH) .putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM) .putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true) @@ -46,22 +95,71 @@ internal class AgentVoice(private val context: Context, private val draft: () -> runCatching { speech.startListening(intent) }.onFailure { stop() } } + private fun relisten(speech: SpeechRecognizer) { + main.post { if (recognizer === speech && !finishing) listen(speech) } + } + private fun heard(results: Bundle?) { val spoken = results?.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION)?.firstOrNull()?.takeIf { it.isNotBlank() } ?: return - if (draft() != written) return stop() + if (draft() != written) return if (finishing) done() else stop() written = base + spoken onText(written) } - /** Ends listening but keeps the recognizer until its final result arrives. */ - fun finish() { + /** Ends listening but keeps the recognizer until its final result arrives, then runs [then]. */ + fun finish(then: (() -> Unit)? = null) { val speech = recognizer ?: return + finishing = true + this.then = then listening = false - runCatching { speech.stopListening() }.onFailure { stop() } + locked = false + level = 0f + runCatching { speech.stopListening() }.onFailure { done() } + // Some recognizers never answer a stop with nothing heard. + main.postDelayed({ if (recognizer === speech) done() }, FINAL_RESULT_TIMEOUT_MS) + } + + private fun done() { + val next = then + stop() + next?.invoke() + } + + /** Stops listening, but a send already waiting on the last words goes ahead with what was heard. */ + fun settle() { + if (finishing) done() else stop() + } + + /** Stops and puts back the text typed before listening began. */ + fun cancel() { + val restore = draft() == written + stop() + if (restore) onText(typed) + } + + private var lent: ServiceConnection? = null + + // Android passes the microphone only to the default speech service on its own; any other one records silence unless + // the app in front binds it with its own capabilities for as long as it listens. + private fun lend(service: ComponentName) { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return + val connection = object : ServiceConnection { + override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {} + override fun onServiceDisconnected(name: ComponentName?) {} + } + val intent = Intent(RecognitionService.SERVICE_INTERFACE).setComponent(service) + if (runCatching { context.bindService(intent, connection, Context.BIND_AUTO_CREATE or Context.BIND_INCLUDE_CAPABILITIES) }.getOrDefault(false)) lent = connection + else runCatching { context.unbindService(connection) } } fun stop() { + lent?.let { runCatching { context.unbindService(it) } } + lent = null + then = null + finishing = false listening = false + locked = false + level = 0f val speech = recognizer ?: return recognizer = null runCatching { speech.cancel() } @@ -69,6 +167,38 @@ internal class AgentVoice(private val context: Context, private val draft: () -> } companion object { + private const val FINAL_RESULT_TIMEOUT_MS = 3000L + fun available(context: Context) = SpeechRecognizer.isRecognitionAvailable(context) + + /** The package that turns speech into text, if one is installed. */ + fun service(context: Context): String? = component(context)?.packageName + + const val DEFAULT_SETTING = "voice_recognition_service" + + private fun chosen(context: Context) = android.provider.Settings.Secure.getString(context.contentResolver, DEFAULT_SETTING) + ?.takeIf { it.isNotBlank() }?.let(ComponentName::unflattenFromString) + + private fun installed(context: Context) = context.packageManager.queryIntentServices(Intent(RecognitionService.SERVICE_INTERFACE), 0) + .map { ComponentName(it.serviceInfo.packageName, it.serviceInfo.name) } + + // Installing a speech service does not always make it the system's choice, and without one Android refuses to listen. + fun component(context: Context): ComponentName? { + val chosen = chosen(context) + val installed = installed(context) + return installed.firstOrNull { it == chosen } ?: installed.firstOrNull() + } + + /** + * Whether the installed service is the system's chosen one. Android only passes DroidDeck's right to the microphone on to that one; + * any other service hears silence once DroidDeck is in front. + */ + fun isDefault(context: Context): Boolean { + val chosen = chosen(context) ?: return false + return chosen in installed(context) + } + + fun serviceHears(context: Context, service: String) = + context.packageManager.checkPermission(android.Manifest.permission.RECORD_AUDIO, service) == android.content.pm.PackageManager.PERMISSION_GRANTED } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AgentVoiceSetup.kt b/app/src/main/java/com/droiddeck/launcher/ui/AgentVoiceSetup.kt new file mode 100644 index 0000000000..66be2e4ccf --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/AgentVoiceSetup.kt @@ -0,0 +1,160 @@ +package com.droiddeck.launcher.ui + +import android.Manifest +import android.app.Activity +import android.content.Context +import android.content.ContextWrapper +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.provider.Settings +import androidx.activity.compose.LocalActivityResultRegistryOwner +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Close +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +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.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalLifecycleOwner +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import com.droiddeck.launcher.R +import com.droiddeck.launcher.core.WirelessAdbFix + +private const val SPEECH_SERVICES = "com.google.android.tts" + +/** Whether the mic can turn speech into text: a speech service is installed, and it and DroidDeck may both use the microphone. */ +internal fun voiceReady(context: Context): Boolean { + val service = AgentVoice.service(context) ?: return false + return appHears(context) && AgentVoice.serviceHears(context, service) +} + +/** Runs [command] over the saved Wireless debugging pairing off the main thread, then [done] on it with whether it worked. */ +private fun adb(context: Context, command: String, done: (Boolean) -> Unit) { + val app = context.applicationContext + Thread({ + // The pairing can be with another device, where the grant would land instead of here. + val ok = runCatching { WirelessAdbFix.savedPairingIsLocal(app) }.getOrDefault(false) && runCatching { WirelessAdbFix.shell(app, command) }.isSuccess + android.os.Handler(android.os.Looper.getMainLooper()).post { done(ok) } + }, "agent-voice-setup").start() +} + +private fun appHears(context: Context) = context.checkSelfPermission(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED + +/** Opens [intent] over DroidDeck when it can, so Back comes straight back to the setup. */ +private fun open(context: Context, intent: Intent): Boolean { + var base = context + while (base !is Activity && base is ContextWrapper) base = base.baseContext + return runCatching { + if (base is Activity) base.startActivity(intent) else context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + }.isSuccess +} + +private fun openAppInfo(context: Context, pkg: String) { + open(context, Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", pkg, null))) +} + +private fun openStore(context: Context) { + if (!open(context, Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$SPEECH_SERVICES")))) { + open(context, Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=$SPEECH_SERVICES"))) + } +} + +/** What talking to the agent still needs, each step one button away, checked again whenever DroidDeck comes back. */ +@Composable +internal fun AgentVoiceSetup(onReady: () -> Unit, onClose: () -> Unit) { + val context = LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + var checks by remember { mutableIntStateOf(0) } + val owner = LocalLifecycleOwner.current + DisposableEffect(owner) { + val observer = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_RESUME) checks++ } + owner.lifecycle.addObserver(observer) + onDispose { owner.lifecycle.removeObserver(observer) } + } + val service = remember(checks) { AgentVoice.service(context) } + val appMic = remember(checks) { appHears(context) } + val serviceMic = remember(checks, service) { service != null && AgentVoice.serviceHears(context, service) } + val paired = remember(checks) { WirelessAdbFix.hasSavedPairing(context) } + var working by remember { mutableStateOf(false) } + val shown = remember { booleanArrayOf(true) } + DisposableEffect(Unit) { onDispose { shown[0] = false } } + // A saved pairing does not mean Wireless debugging is on now, so a refusal falls back to doing it by hand. + val viaAdb: (String, () -> Unit) -> Unit = { command, byHand -> + working = true + adb(context, command) { ok -> + working = false + checks++ + if (!ok && shown[0]) byHand() + } + } + LaunchedEffect(service, appMic, serviceMic) { if (service != null && appMic && serviceMic) onReady() } + val ask = if (LocalActivityResultRegistryOwner.current != null) rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> + // Android stops asking after the user refuses twice; the switch is then only in App info. + if (granted) checks++ else openAppInfo(context, context.packageName) + } else null + Column( + Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14).testTag("agent-voice-setup"), + ) { + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.padding(start = 14.dp, end = 6.dp, top = 6.dp)) { + Text( + stringResource(R.string.agent_voice_setup), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, + modifier = Modifier.weight(1f), + ) + Box(contentAlignment = Alignment.Center, modifier = Modifier.size(36.dp).clip(CircleShape).clickable(onClick = onClose)) { + Icon(Icons.Outlined.Close, stringResource(R.string.agent_voice_setup_close), tint = pal.onSurfaceVariant, modifier = Modifier.size(18.dp)) + } + } + CheckRow( + if (service != null) CheckState.OK else CheckState.WARN, stringResource(R.string.agent_voice_setup_service), + if (service == null) stringResource(R.string.agent_voice_setup_service_detail) else null, + action = if (service == null) ({ SecondaryButton(stringResource(R.string.setup_install), compact = true) { openStore(context) } }) else null, + ) + CheckRow( + if (appMic) CheckState.OK else CheckState.WARN, stringResource(R.string.agent_voice_setup_app_mic), null, + action = if (!appMic) ({ + SecondaryButton(stringResource(R.string.libraries_access_allow), compact = true) { + if (ask != null) ask.launch(Manifest.permission.RECORD_AUDIO) else openAppInfo(context, context.packageName) + } + }) else null, + ) + CheckRow( + if (serviceMic) CheckState.OK else CheckState.WARN, stringResource(R.string.agent_voice_setup_service_mic), + if (service != null && !serviceMic && !paired) stringResource(R.string.agent_voice_setup_service_mic_detail) else null, divider = false, + action = if (service != null && !serviceMic) ({ + SecondaryButton(stringResource(R.string.libraries_access_allow), enabled = !working, compact = true) { + if (paired) viaAdb("pm grant $service ${Manifest.permission.RECORD_AUDIO}") { openAppInfo(context, service) } else openAppInfo(context, service) + } + }) else null, + ) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt index 4303dde0fe..8904f2c2d4 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/AndroidAppsPage.kt @@ -848,13 +848,28 @@ private fun FolderSheet( renaming = false } val firstApp = remember { FocusRequester() } + val title = remember { FocusRequester() } + var toTitle by remember { mutableStateOf(false) } + var titleFocused by remember { mutableStateOf(false) } + val sheetView = androidx.compose.ui.platform.LocalView.current + val leaveName = { + if (renaming) { + (ctx.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager) + ?.hideSoftInputFromWindow(sheetView.windowToken, 0) + toTitle = true + commit() + } + } val inputMode = LocalInputModeManager.current.inputMode val ff = LocalFrontFocus.current val grid = rememberLazyGridState() var closing by remember { mutableStateOf(false) } var inside by remember { mutableStateOf(false) } LaunchedEffect(renaming, inputMode) { - if (!renaming && !closing && inputMode == InputMode.Keyboard && apps.isNotEmpty()) { + if (!renaming && !closing && toTitle) { + focusWithinFrames({ titleFocused || closing }) { title } + toTitle = false + } else if (!renaming && !closing && inputMode == InputMode.Keyboard && apps.isNotEmpty()) { grid.scrollToItem(0) androidx.compose.runtime.withFrameNanos { } // After touch, focus starts outside the page and the first request is turned to the page's own entry, behind the sheet. Ask until it is in here. @@ -885,6 +900,12 @@ private fun FolderSheet( .clip(Shape16).background(pal.surfaceVariant.copy(alpha = 0.97f)) .glideBorder(false, Shape16, pal.signal, pal.signal.copy(alpha = 0.22f)) .pointerInput(Unit) { awaitEachGesture { awaitFirstDown(requireUnconsumed = false).consume() } } + .onPreviewKeyEvent { event -> + val k = event.nativeKeyEvent + if (!renaming || k.keyCode != KeyEvent.KEYCODE_BUTTON_B) return@onPreviewKeyEvent false + if (k.action == KeyEvent.ACTION_DOWN && k.repeatCount == 0) leaveName() + true + } .controllerBack(close) .onFocusChanged { inside = it.hasFocus } .focusProperties { @@ -901,7 +922,7 @@ private fun FolderSheet( AdbTextField( value = name, onValueChange = { name = it.take(40) }, label = stringResource(R.string.apps_folder_name), keyboardType = KeyboardType.Text, imeAction = ImeAction.Done, compact = true, showLabel = false, - placeholder = folder.name, focusOnShow = true, onDone = { commit() }, + placeholder = folder.name, focusOnShow = true, onDone = { commit() }, onBack = leaveName, ) } else { val src = remember { MutableInteractionSource() } @@ -914,6 +935,8 @@ private fun FolderSheet( modifier = Modifier.clip(Shape12) .background(if (hot) pal.signal.copy(alpha = 0.12f) else colors.onBackground.copy(alpha = 0.07f)) .glideBorder(hot, Shape12, pal.signal) + .focusRequester(title) + .onFocusChanged { titleFocused = it.isFocused } .hoverable(src) .clickable(interactionSource = src, indication = LocalIndication.current, onClickLabel = stringResource(R.string.apps_folder_rename), role = Role.Button, onClick = rename) .controllerConfirm(onClick = rename) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/CardDetailHost.kt b/app/src/main/java/com/droiddeck/launcher/ui/CardDetailHost.kt index 2a50f3c35b..29410a2725 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/CardDetailHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/CardDetailHost.kt @@ -26,6 +26,7 @@ import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.luminance import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.onGloballyPositioned @@ -76,6 +77,7 @@ internal fun CardDetailHost( var leaving by remember { mutableStateOf(false) } var from by remember { mutableStateOf(null) } var art by remember { mutableStateOf(null) } + var hero by remember { mutableStateOf(null) } var viewportAt by remember { mutableStateOf(Offset.Zero) } var viewportH by remember { mutableStateOf(0) } LaunchedEffect(open) { @@ -83,6 +85,7 @@ internal fun CardDetailHost( val mark = StoresMotion.takeCard(open) from = mark?.let { Origin(it.bounds.translate(-viewportAt), it.corner) } art = mark?.art + hero = mark?.hero StoresMotion.heroLands = mark != null leaving = false shown = open @@ -152,7 +155,12 @@ internal fun CardDetailHost( }, ) } - PageFlood(origin, leaving, painter, onto = { StoresMotion.heroAt }, ontoCorner = 16.dp) { body() } + val light = androidx.compose.material3.MaterialTheme.colorScheme.background.luminance() > 0.5f + val heroPainter = hero?.takeIf { it != art }?.let { url -> + coil.compose.rememberAsyncImagePainter(remember(url) { coil.request.ImageRequest.Builder(ctx).data(url).size(1280, 720).placeholderMemoryCacheKey(url).build() }) + } ?: painter + val look = HeroLook(rememberArtBrightness(hero ?: art), light, androidx.compose.material3.MaterialTheme.colorScheme.background) + PageFlood(origin, leaving, painter, onto = { StoresMotion.heroAt }, ontoCorner = 0.dp, ontoLook = look, ontoArt = heroPainter) { body() } } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ColorPickerDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ColorPickerDialog.kt index d8b3c61a27..e9ff41cbe9 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ColorPickerDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ColorPickerDialog.kt @@ -10,13 +10,17 @@ 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.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable +import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf @@ -31,12 +35,14 @@ import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.semantics.contentDescription import androidx.compose.ui.semantics.semantics import androidx.compose.ui.semantics.Role import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.droiddeck.launcher.R import kotlin.math.atan2 @@ -77,33 +83,63 @@ internal fun ColorPickerDialog(title: String, initial: Int, onDismiss: () -> Uni hue = h.coerceIn(0f, 360f); sat = s.coerceIn(0f, 1f); value = v.coerceIn(0f, 1f) hexText = ThemeColors.hex(ThemeColors.fromHsv(hue, sat, value)) } - AppDialog(shown, close, "colorPicker", wide = false, maxWidth = 460.dp, scrollState = scroll) { + val screen = LocalConfiguration.current + val beside = screen.screenWidthDp > screen.screenHeightDp && screen.screenWidthDp >= 600 + val wheelSize = if (beside) (screen.screenHeightDp - 176).coerceIn(160, 216).dp else 168.dp + val short = beside && wheelSize < 216.dp + AppDialog(shown, close, "colorPicker", wide = false, maxWidth = if (beside) 680.dp else 460.dp, scrollState = scroll) { DialogTitleRow(title, close) - Row(horizontalArrangement = Arrangement.spacedBy(14.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { - ColorWheel(hue, sat, value) { h, s -> picked(h = h, s = s) } - Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { - Swatch(Color(initial)) - Swatch(Color(current)) - } + val wheel: @Composable () -> Unit = { ColorWheel(hue, sat, value, wheelSize) { h, s -> picked(h = h, s = s) } } + val track = if (short) 24.dp else 40.dp + val sliders: @Composable () -> Unit = { + ValueSlider(hue.toInt(), 0..360, step = 5, enabled = true, label = stringResource(R.string.theme_color_hue), format = { "$it°" }, + modifier = Modifier.focusRequester(first), track = track) { picked(h = it.toFloat()) } + ValueSlider((sat * 100).toInt(), 0..100, step = 2, enabled = true, label = stringResource(R.string.theme_color_saturation), format = { "$it%" }, + track = track) { picked(s = it / 100f) } + ValueSlider((value * 100).toInt(), 0..100, step = 2, enabled = true, label = stringResource(R.string.theme_color_brightness), format = { "$it%" }, + track = track) { picked(v = it / 100f) } } - ValueSlider(hue.toInt(), 0..360, step = 5, enabled = true, label = stringResource(R.string.theme_color_hue), format = { "$it°" }, - modifier = Modifier.focusRequester(first)) { picked(h = it.toFloat()) } - ValueSlider((sat * 100).toInt(), 0..100, step = 2, enabled = true, label = stringResource(R.string.theme_color_saturation), format = { "$it%" }) { picked(s = it / 100f) } - ValueSlider((value * 100).toInt(), 0..100, step = 2, enabled = true, label = stringResource(R.string.theme_color_brightness), format = { "$it%" }) { picked(v = it / 100f) } - AdbTextField( - value = hexText, - onValueChange = { text -> - hexText = text - ThemeColors.parseHex(text)?.let { argb -> ThemeColors.toHsv(argb).let { hsv -> hue = hsv.h; sat = hsv.s; value = hsv.v } } - }, - label = "", keyboardType = KeyboardType.Ascii, imeAction = ImeAction.Done, placeholder = stringResource(R.string.theme_color_hex), - onFocusChange = { typingHex = it }, - onDone = { ThemeColors.parseHex(hexText)?.let { onApply(it); close() } }, - ) - Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) { - SecondaryButton(stringResource(R.string.common_cancel), modifier = Modifier.weight(1f), onClick = close) - PrimaryButton(stringResource(R.string.common_ok), enabled = ThemeColors.parseHex(hexText) != null, modifier = Modifier.weight(1f)) { - ThemeColors.parseHex(hexText)?.let { onApply(it); close() } + val hex: @Composable (Modifier) -> Unit = { modifier -> + AdbTextField( + value = hexText, + onValueChange = { text -> + hexText = text + ThemeColors.parseHex(text)?.let { argb -> ThemeColors.toHsv(argb).let { hsv -> hue = hsv.h; sat = hsv.s; value = hsv.v } } + }, + label = "", keyboardType = KeyboardType.Ascii, imeAction = ImeAction.Done, placeholder = stringResource(R.string.theme_color_hex), + showLabel = false, compact = beside, modifier = modifier, + onFocusChange = { typingHex = it }, + onDone = { ThemeColors.parseHex(hexText)?.let { onApply(it); close() } }, + ) + } + val ok = { ThemeColors.parseHex(hexText)?.let { onApply(it); close() }; Unit } + val valid = ThemeColors.parseHex(hexText) != null + if (beside) { + Row(horizontalArrangement = Arrangement.spacedBy(20.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { + wheel() + Column(verticalArrangement = Arrangement.spacedBy(if (short) 2.dp else 8.dp), modifier = Modifier.weight(1f)) { + CompositionLocalProvider(LocalCompactSettings provides true) { sliders() } + } + } + Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { + BeforeAfter(Color(initial), Color(current), Modifier.size(96.dp, 44.dp)) + hex(Modifier.weight(1f)) + SecondaryButton(stringResource(R.string.common_cancel), modifier = Modifier.width(128.dp), onClick = close) + PrimaryButton(stringResource(R.string.common_ok), enabled = valid, modifier = Modifier.width(128.dp), fill = true, onClick = ok) + } + } else { + Row(horizontalArrangement = Arrangement.spacedBy(14.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { + wheel() + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Swatch(Color(initial)) + Swatch(Color(current)) + } + } + sliders() + hex(Modifier) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) { + SecondaryButton(stringResource(R.string.common_cancel), modifier = Modifier.weight(1f), onClick = close) + PrimaryButton(stringResource(R.string.common_ok), enabled = valid, modifier = Modifier.weight(1f), fill = true, onClick = ok) } } } @@ -116,9 +152,17 @@ private fun Swatch(color: Color) { } @Composable -private fun ColorWheel(hue: Float, sat: Float, value: Float, onPick: (hue: Float, sat: Float) -> Unit) { +private fun BeforeAfter(before: Color, after: Color, modifier: Modifier) { + val shape = RoundedCornerShape(10.dp) + Row(modifier.clip(shape).border(1.dp, LocalPalette.current.line2, shape)) { + Box(Modifier.weight(1f).fillMaxHeight().background(before)) + Box(Modifier.weight(1f).fillMaxHeight().background(after)) + } +} + +@Composable +private fun ColorWheel(hue: Float, sat: Float, value: Float, size: Dp, onPick: (hue: Float, sat: Float) -> Unit) { val rim = MaterialTheme.colorScheme.onBackground - val size = 168.dp fun at(offset: Offset, side: Float) { val center = side / 2f val dx = offset.x - center diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DesktopPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/DesktopPage.kt index 28768454c3..9d3a84e7a5 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DesktopPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DesktopPage.kt @@ -156,7 +156,10 @@ internal fun DesktopPage(s: FrontEndState, a: FrontEndActions, modifier: Modifie }, rows = { tab -> if (tab == SheetTab.FILES) DesktopFiles(s, a) - else a.modeSheet(mode, tab, SheetExtras()) + else a.modeSheet(mode, tab, SheetExtras( + performance = { PerformanceLink(a, "desktop", SheetTab.SESSION) }, + drivers = { summary -> DriversLink(a, summary, "desktop", stringResource(R.string.hop_from_play)) }, + )) }, ) if (adding && !s.busy) AddAppDialog(s.ready, onDismiss = { adding = false }) { request, label -> UserAppsState.add(ctx, request, label) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DownloadsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/DownloadsPage.kt new file mode 100644 index 0000000000..b32ad6b87f --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/DownloadsPage.kt @@ -0,0 +1,70 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.expandVertically +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.shrinkVertically +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Settings +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.positionInRoot +import androidx.compose.ui.layout.boundsInRoot +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.R + +internal object DownloadsNav { + var showSettings = false +} + +@Composable +internal fun DownloadsPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier) { + val pal = LocalPalette.current + val live = androidx.compose.runtime.rememberUpdatedState(s) + var gearAt by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf(null) } + val openSettings = { gearAt?.let { StoresMotion.ask(downloadsSettingsStep(it, live, a, pal.signal)) } } + androidx.compose.runtime.LaunchedEffect(gearAt != null) { + if (gearAt != null && DownloadsNav.showSettings) { DownloadsNav.showSettings = false; openSettings() } + } + var hostAt by androidx.compose.runtime.remember { androidx.compose.runtime.mutableStateOf(androidx.compose.ui.geometry.Offset.Zero) } + androidx.compose.runtime.DisposableEffect(Unit) { val page = Any(); StoresMotion.hosting(page); onDispose { StoresMotion.release(page) } } + androidx.activity.compose.BackHandler(enabled = StoresMotion.stepOpen) { StoresMotion.fold() } + androidx.compose.foundation.layout.Box(androidx.compose.ui.Modifier.fillMaxSize().onGloballyPositioned { hostAt = it.positionInRoot() }) { + Column(modifier.verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) { + PageHeader(stringResource(R.string.stores_tab_downloads)) { + Spacer(Modifier.weight(1f)) + androidx.compose.foundation.layout.Box(Modifier.onGloballyPositioned { gearAt = it.boundsInRoot() }) { + SmallIconButton(Icons.Filled.Settings, stringResource(R.string.downloads_settings), tint = MaterialTheme.colorScheme.onSurfaceVariant) { + openSettings() + } + } + } + StoresDownloadsPane(s, a) + } + StoresMotion.step?.let { ask -> + androidx.compose.runtime.key(ask) { + StepOut( + open = StoresMotion.stepOpen, pill = ask.anchor.translate(-hostAt), preferredSide = ask.side, accent = ask.accent, + onDismiss = { StoresMotion.fold() }, onClosed = { StoresMotion.closed(ask) }, + pillCorner = ask.pillCorner, maxWidth = ask.maxWidth, items = ask.items, handle = ask.handle, content = ask.content, + ) + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DrawerEntryHint.kt b/app/src/main/java/com/droiddeck/launcher/ui/DrawerEntryHint.kt new file mode 100644 index 0000000000..59c87675e9 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/DrawerEntryHint.kt @@ -0,0 +1,101 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.slideInHorizontally +import androidx.compose.animation.slideOutHorizontally +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.WindowInsets +import androidx.compose.foundation.layout.displayCutout +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.layout.windowInsetsPadding +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.KeyboardArrowLeft +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +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.input.pointer.pointerInput +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.R +import com.droiddeck.launcher.session.SessionPrefs +import kotlinx.coroutines.delay + +private const val HINT_SESSIONS = 3 +private const val HINT_MS = 6_000L +private var hintedSession: Any? = null + +@Composable +internal fun DrawerEntryHint(steam: Boolean, inverted: Boolean, onOpen: () -> Unit) { + val context = LocalContext.current + var shown by remember { mutableStateOf(false) } + LaunchedEffect(Unit) { + val session = com.droiddeck.launcher.session.SessionState.sessionId + if (hintedSession == session || SessionPrefs.drawerHintShown(context) >= HINT_SESSIONS) return@LaunchedEffect + hintedSession = session + SessionPrefs.countDrawerHint(context) + shown = true + delay(HINT_MS) + shown = false + } + Box(Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.displayCutout), contentAlignment = Alignment.CenterEnd) { + AnimatedVisibility(shown, enter = slideInHorizontally { it } + fadeIn(), exit = slideOutHorizontally { it } + fadeOut()) { + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier + .clip(RoundedCornerShape(topStart = 14.dp, bottomStart = 14.dp)) + .background(Color(0xE6101216)) + .clickable(role = Role.Button, onClickLabel = stringResource(R.string.drawer_handle)) { shown = false; onOpen() } + .padding(start = 10.dp, end = 14.dp, top = 10.dp, bottom = 10.dp) + .widthIn(max = 260.dp) + .testTag("drawer-hint"), + ) { + Icon(Icons.AutoMirrored.Filled.KeyboardArrowLeft, null, tint = Color.White, modifier = Modifier.size(20.dp)) + val bound = remember { + com.droiddeck.launcher.input.PhysicalShortcuts.read(context) + .filter { it.action == com.droiddeck.launcher.input.PhysicalShortcuts.Action.DROIDDECK } + .map { it.button.label }.distinct().joinToString(" / ") + } + Text( + if (bound.isNotEmpty()) stringResource(R.string.drawer_hint_button, bound) + else stringResource(if (!steam) R.string.drawer_hint else if (inverted) R.string.drawer_hint_steam_inverted else R.string.drawer_hint_steam), + fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = Color.White, + ) + } + } + } +} + +@Composable +internal fun DrawerCornerTap(onOpen: () -> Unit) { + Box(Modifier.fillMaxSize().windowInsetsPadding(WindowInsets.displayCutout), contentAlignment = Alignment.TopEnd) { + Box( + Modifier.size(64.dp).testTag("drawer-corner") + .pointerInput(Unit) { detectTapGestures(onDoubleTap = { onOpen() }) }, + ) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DropSheet.kt b/app/src/main/java/com/droiddeck/launcher/ui/DropSheet.kt index 317d9b0ce4..c0b4ac7a8a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DropSheet.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DropSheet.kt @@ -465,7 +465,7 @@ internal fun BoxWithConstraintsScope.DropSheet( var handleSize by remember { mutableStateOf(androidx.compose.ui.unit.IntSize.Zero) } val lipH = 32.dp + state.pull.value.dp val drop = { if (!state.open && enabled) state.open = true } - val settingsLabel = stringResource(R.string.drawer_page_settings) + val settingsLabel = stringResource(R.string.sheet_lip) Box( contentAlignment = Alignment.BottomCenter, modifier = Modifier diff --git a/app/src/main/java/com/droiddeck/launcher/ui/DualScreenPanel.kt b/app/src/main/java/com/droiddeck/launcher/ui/DualScreenPanel.kt index df4e4a8d1b..3ea7950600 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/DualScreenPanel.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/DualScreenPanel.kt @@ -1,5 +1,7 @@ package com.droiddeck.launcher.ui +import androidx.compose.material.icons.automirrored.outlined.ArrowBack +import androidx.compose.material.icons.Icons import android.app.ActivityOptions import android.content.Context import android.content.Intent @@ -363,7 +365,8 @@ internal fun DualPanelContent(model: DualPanelModel) { private fun PanelTile(key: String, current: Boolean, badge: Boolean, count: Int, modifier: Modifier, onClick: () -> Unit) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current - val (label, icon) = railLabelIcon(key) + val (label, base) = railLabelIcon(key) + val icon = if (key == NavTabs.MORE && MoreTabs.inside) Icons.AutoMirrored.Outlined.ArrowBack else base val shape = RoundedCornerShape(18.dp) Box( modifier.fillMaxSize().clip(shape) @@ -373,7 +376,7 @@ private fun PanelTile(key: String, current: Boolean, badge: Boolean, count: Int, contentAlignment = Alignment.Center, ) { Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) { - Icon(icon, contentDescription = null, tint = if (current) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(34.dp)) + androidx.compose.animation.Crossfade(icon, animationSpec = Motion.tw(220), label = "panelIcon") { Icon(it, contentDescription = null, tint = if (current) pal.signal else colors.onSurfaceVariant, modifier = Modifier.size(34.dp)) } Text(stringResource(label), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = if (current) pal.signal else colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(horizontal = 6.dp)) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt index 610cd61138..191956c170 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndContent.kt @@ -251,6 +251,18 @@ private fun Content( } return } + if (selected == "downloads") { + DownloadsPage(s, a, modifier.padding(horizontal = padH).padding(top = padV)) + return + } + if (selected == "storage") { + StorageTabPage(s, a, modifier.padding(horizontal = padH).padding(top = padV)) + return + } + if (selected == "sync") { + SyncTabPage(s, modifier.padding(horizontal = padH).padding(top = padV)) + return + } if (selected == "updates") { UpdatesPage(s, a, modifier.padding(horizontal = padH).padding(top = padV)) return @@ -276,14 +288,17 @@ private fun Content( return } if (selected == NavTabs.MORE) { - MorePage(s, a, onSelect, modifier.padding(horizontal = padH).padding(top = padV)) + Box(modifier) { + MorePage(s, a, onSelect, Modifier.padding(horizontal = padH).padding(top = padV)) + EditTabsSheet(s, a) + } return } if (selected == "agent") { AgentPage(modifier.padding(horizontal = padH).padding(top = padV)) return } - if (selected == "android-apps" && s.isHomeApp) { + if (selected == "android-apps") { AndroidAppsPage(s, a, modifier, onAndroidAppClick) return } 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 45ef20fe8d..ab0a80940b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndGames.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.ui +import androidx.compose.material.icons.outlined.Sync import androidx.compose.ui.platform.testTag import com.droiddeck.launcher.R import androidx.compose.ui.res.stringResource @@ -41,11 +42,12 @@ import androidx.compose.runtime.getValue @Composable -internal fun GameFileFolderActions(s: FrontEndState, a: FrontEndActions) { +internal fun GameFileFolderActions(s: FrontEndState, a: FrontEndActions, labeled: Boolean = false) { if (s.shortcutPicker) return var open by remember { androidx.compose.runtime.mutableStateOf(false) } Box { - SecondaryButton(stringResource(R.string.game_frontend_files), compact = true) { open = !open } + if (labeled) SecondaryButton(stringResource(R.string.game_frontend_files), compact = true) { open = !open } + else HeaderIconButton(stringResource(R.string.game_frontend_files), androidx.compose.material.icons.Icons.Outlined.Sync, "frontend-files", Modifier.downToFirstTile()) { open = !open } AnchoredMenu(open, onDismiss = { open = false }, title = s.gameSyncFolder ?: stringResource(R.string.game_frontend_files)) { first -> MenuItem(stringResource(R.string.game_file_sync), checked = false, focusRequester = first) { open = false; a.onSyncGameFiles() @@ -80,6 +82,12 @@ internal fun cloudMessage(context: android.content.Context, r: com.droiddeck.lau r.files == 0 -> context.getString(R.string.cloud_up_to_date) else -> context.getString(R.string.cloud_done, r.files) } + "partial" -> when { + r.conflicts > 0 && r.detail.isNotEmpty() -> context.getString(R.string.cloud_conflict_files_detail, r.conflicts, r.detail) + r.conflicts > 0 -> context.getString(R.string.cloud_conflict_files, r.conflicts) + r.detail.isNotEmpty() -> context.getString(R.string.cloud_partial, r.detail) + else -> context.getString(R.string.cloud_not_synced) + } "skipped" -> context.getString(when (r.reason) { "not-signed-in" -> R.string.cloud_signed_out "no-cloud-saves" -> R.string.cloud_none diff --git a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt index a4bd236398..c35f3d10df 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndRail.kt @@ -47,11 +47,15 @@ import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Apps +import androidx.compose.material.icons.outlined.Download +import androidx.compose.material.icons.outlined.SdStorage +import androidx.compose.material.icons.outlined.Sync import androidx.compose.material.icons.outlined.Terminal import androidx.compose.material.icons.outlined.DesktopWindows import androidx.compose.material.icons.outlined.Layers import androidx.compose.material.icons.outlined.LocalMall import androidx.compose.material.icons.outlined.MoreHoriz +import androidx.compose.material.icons.automirrored.outlined.ArrowBack import androidx.compose.material.icons.outlined.SportsEsports import androidx.compose.material.icons.outlined.Storefront import androidx.compose.material.icons.outlined.SystemUpdate @@ -195,28 +199,32 @@ internal fun railLabelIcon(key: String): Pair = when (key) { "games" -> R.string.rail_games to Icons.Outlined.VideoLibrary "soundtracks" -> R.string.rail_music to SoundtrackIcon "stores" -> R.string.rail_stores to Icons.Outlined.LocalMall + "downloads" -> R.string.stores_tab_downloads to Icons.Outlined.Download "desktop" -> R.string.rail_desktop to Icons.Outlined.DesktopWindows "components" -> R.string.rail_components to Icons.Outlined.Layers "agent" -> R.string.rail_agent to Icons.Outlined.Terminal "android-apps" -> R.string.rail_apps to Icons.Outlined.Apps "setup" -> R.string.rail_setup to Icons.Outlined.Tune + "storage" -> R.string.rail_storage to Icons.Outlined.SdStorage + "sync" -> R.string.rail_sync to Icons.Outlined.Sync NavTabs.MORE -> R.string.rail_more to Icons.Outlined.MoreHoriz else -> R.string.rail_updates to Icons.Outlined.SystemUpdate } internal fun setupNeedsAttention(s: FrontEndState): Boolean = !s.ready || (s.available != null && s.available != s.installed) || - PhantomProcessLimit.blocksSteam(s.phantomProcessStatus) || com.droiddeck.launcher.sync.Syncthing.needsAttention + PhantomProcessLimit.blocksSteam(s.phantomProcessStatus) internal fun railBadge(s: FrontEndState, key: String, setupNeedsAttention: Boolean = setupNeedsAttention(s)): Boolean = when (key) { "setup" -> setupNeedsAttention + "sync" -> com.droiddeck.launcher.sync.Syncthing.needsAttention "updates" -> s.updates.hasUpdate NavTabs.MORE -> NavTabs.more(s).any { it != NavTabs.MORE && railBadge(s, it, setupNeedsAttention) } else -> false } internal fun railCount(s: FrontEndState, key: String): Int = when (key) { - "stores" -> s.storeDownloadsActive - NavTabs.MORE -> if ("stores" in NavTabs.more(s)) s.storeDownloadsActive else 0 + "downloads" -> s.storeDownloadsActive + NavTabs.MORE -> if ("downloads" in NavTabs.more(s)) s.storeDownloadsActive else 0 else -> 0 } @@ -226,13 +234,16 @@ private fun NavigationItems( place: (String) -> Modifier, onSelect: (String) -> Unit, onFocusSelect: (String) -> Unit, ) { val setupNeedsAttention = setupNeedsAttention(s) + val downloadsAt = if ("downloads" in NavTabs.more(s)) NavTabs.MORE else "downloads" for (key in navigationKeys(s)) { - val (label, icon) = railLabelIcon(key) + val (label, base) = railLabelIcon(key) + val icon = if (key == NavTabs.MORE && MoreTabs.inside) Icons.AutoMirrored.Outlined.ArrowBack else base key(key) { RailItem(stringResource(label), icon, key, shown == key, compact, iconOnly, height, width, badge = railBadge(s, key, setupNeedsAttention), count = railCount(s, key), - place = place, onFocus = { onFocusSelect(key) }) { onSelect(key) } + place = { k -> if (k == downloadsAt) place(k).onGloballyPositioned { StoresMotion.downloadsChip = it.boundsInRoot() } else place(k) }, + onFocus = { onFocusSelect(key) }) { onSelect(key) } } } } @@ -288,9 +299,9 @@ private fun RailItem( .selectable(selected = current, interactionSource = src, indication = LocalIndication.current, role = Role.Tab, onClick = onClick) .then(if (iconOnly) Modifier.semantics { contentDescription = label } else Modifier), ) { - if (iconOnly) Icon(icon, contentDescription = null, tint = fg, modifier = Modifier.size(22.dp)) + if (iconOnly) androidx.compose.animation.Crossfade(icon, animationSpec = Motion.tw(220), label = "railIcon") { Icon(it, contentDescription = null, tint = fg, modifier = Modifier.size(22.dp)) } else Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(3.dp)) { - Icon(icon, contentDescription = null, tint = fg, modifier = Modifier.size(if (height < 56.dp) 20.dp else 22.dp)) + androidx.compose.animation.Crossfade(icon, animationSpec = Motion.tw(220), label = "railIcon") { Icon(it, contentDescription = null, tint = fg, modifier = Modifier.size(if (height < 56.dp) 20.dp else 22.dp)) } FitText(label, maxSize = 12.sp, modifier = Modifier.padding(horizontal = 4.dp), fontWeight = FontWeight.SemiBold, color = fg) } if (badge) Box( 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 369f78edff..ef414c4eb0 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndScreen.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.ui +import androidx.compose.ui.input.pointer.pointerInput import java.io.File import androidx.compose.ui.res.stringResource import com.droiddeck.launcher.R @@ -180,7 +181,6 @@ class FrontEndState( val animationsEnabled: Boolean = true, val lowStorageWarning: Boolean = true, val launcherIcon: String = com.droiddeck.launcher.LauncherIcon.DARK, - val gameStoresEnabled: Boolean = true, val soundtracksEnabled: Boolean = true, val soundtracksIngame: Boolean = false, val soundtracks: List = emptyList(), @@ -246,6 +246,7 @@ class FrontEndActions( val onAddonDelete: (com.droiddeck.launcher.runtime.WowAddons.Target, String) -> Unit = { _, _ -> }, val onSaveExport: (Library.SteamGame, com.droiddeck.launcher.session.GameSaves.Layout) -> Unit = { _, _ -> }, val onPerformance: () -> Unit, + val performancePanel: @Composable () -> Unit = {}, val onRoms: () -> Unit, val onFiles: () -> Unit, val onBrowseFiles: (File) -> Unit = {}, @@ -288,8 +289,6 @@ class FrontEndActions( val onDownloadMirror: (String) -> Unit = {}, val onDownloadPrefix: (String) -> Unit = {}, val onDownloadProxy: (String) -> Unit = {}, - val onGameStoresEnabled: (Boolean) -> Unit = {}, - val onSoundtracksEnabled: (Boolean) -> Unit = {}, val onSoundtracksIngame: (Boolean) -> Unit = {}, val onSoundtrackAdded: (java.io.File) -> Unit = {}, val onSoundtracksChanged: () -> Unit = {}, @@ -455,16 +454,26 @@ fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () - val frontFocus = remember { FrontFocus() } val textInput = androidx.compose.ui.platform.LocalTextInputService.current val bottomTextInput = remember(textInput) { textInput?.let { androidx.compose.ui.text.input.TextInputService(BottomScreenTextInput(it)) } } - androidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxSize()) { + androidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxSize().pointerInput(Unit) { + awaitPointerEventScope { + while (true) { + val e = awaitPointerEvent(androidx.compose.ui.input.pointer.PointerEventPass.Initial) + e.changes.firstOrNull { it.pressed && !it.previousPressed }?.let { StoresMotion.touched(it.position) } + } + } + }) { CompositionLocalProvider( LocalFrontFocus provides frontFocus, LocalNarrowPane provides (maxWidth < NarrowPaneWidth), androidx.compose.ui.platform.LocalTextInputService provides (if (s.dualScreen) bottomTextInput else textInput), LocalBottomTyping provides s.dualScreen, ) { FrontEndScreenBody(s, a, page, frontFocus) } + DownloadFlights() } } +private val SETTINGS_NAV = SettingsSection.entries.map { "settings:${it.key}" }.toSet() + "settings" + @OptIn(ExperimentalComposeUiApi::class) @Composable private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)?, frontFocus: FrontFocus) { @@ -475,11 +484,12 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com LaunchedEffect(s.navigate) { val target = s.navigate ?: return@LaunchedEffect when (target) { - "stores:downloads" -> { com.droiddeck.launcher.stores.StoresState.openDownloads = true; selected = "stores" } + "stores:downloads" -> selected = "downloads" "components" -> a.onComponents(true) "setup:launcher" -> { SetupTabs.openLauncher = true; selected = "setup" } com.droiddeck.launcher.sync.SyncthingService.NAV -> com.droiddeck.launcher.sync.Syncthing.requestOpen() "setup:integration" -> { SetupTabs.openOverview = true; selected = "setup" } + in SETTINGS_NAV -> { SetupTabs.openSection = SettingsSection.of(target.removePrefix("settings:")) ?: SettingsSection.OVERVIEW; selected = "setup" } com.droiddeck.launcher.core.AppUiPrefs.HOME_PAGE_APPS -> { // Home lands on the apps page itself, so a page open over the rail (Components, Performance) closes first. if (s.pageKey != null) a.onPageBack() @@ -581,7 +591,6 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com BackHandler(enabled = !processSettingsPageVisible && backToMore) { selected = NavTabs.MORE } - LaunchedEffect(s.isHomeApp) { if (!s.isHomeApp && selected == "android-apps") selected = "steam" } LaunchedEffect(s.soundtracksEnabled) { if (!s.soundtracksEnabled && (selected == "soundtracks" || selected.startsWith("sound:"))) selected = "games" } @@ -595,7 +604,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com val openTab = when { Hops.origin != null && s.pageKey == Hops.origin?.page -> Hops.origin!!.dest - s.pageKey == "performance" -> "steam" + s.pageKey == "performance" -> "setup" s.pageKey == "controller-mapping" -> "setup" selected.startsWith("app:") -> "games" selected.startsWith("sound:") -> "soundtracks" @@ -603,6 +612,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com else -> s.pageKey ?: selected } val railSelection = if (openTab in NavTabs.more(s)) NavTabs.MORE else openTab + androidx.compose.runtime.SideEffect { MoreTabs.inside = railSelection == NavTabs.MORE && openTab != NavTabs.MORE } val railSelectionNow = androidx.compose.runtime.rememberUpdatedState(railSelection) var railPicks by remember { mutableStateOf(0) } val showRailPage: (String, Boolean) -> Unit = { key, focusContent -> @@ -616,10 +626,29 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com } } LaunchedEffect(com.droiddeck.launcher.storage.StorageState.openRequests) { - if (com.droiddeck.launcher.storage.StorageState.openPending) showRailPage("setup", true) + if (com.droiddeck.launcher.storage.StorageState.openPending) { + com.droiddeck.launcher.storage.StorageState.openPending = false + showRailPage("storage", true) + } } LaunchedEffect(com.droiddeck.launcher.sync.Syncthing.openRequests) { - if (com.droiddeck.launcher.sync.Syncthing.openPending) showRailPage("setup", true) + if (com.droiddeck.launcher.sync.Syncthing.openPending) { + com.droiddeck.launcher.sync.Syncthing.openPending = false + showRailPage("sync", true) + } + } + LaunchedEffect(com.droiddeck.launcher.stores.StoresState.openDownloads) { + if (com.droiddeck.launcher.stores.StoresState.openDownloads) { + com.droiddeck.launcher.stores.StoresState.openDownloads = false + showRailPage("downloads", true) + } + } + LaunchedEffect(RailRequest.key) { + RailRequest.key?.let { showRailPage(it, true) } + RailRequest.key = null + } + LaunchedEffect(SetupTabs.openSection) { + if (SetupTabs.openSection != null && (railSelection != "setup" || s.pageKey != null)) showRailPage("setup", true) } val onRailFocus: (String) -> Unit = { key -> if (key != railSelection) showRailPage(key, false) @@ -725,11 +754,11 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com onRailSelect(key) }, a) CompositionLocalProvider(LocalShowSection provides { key -> selected = key }) { - val agentKeyboardOpen = railSelection == "agent" && WindowInsets.ime.getBottom(androidx.compose.ui.platform.LocalDensity.current) > 0 + val agentKeyboardOpen = openTab == "agent" && WindowInsets.ime.getBottom(androidx.compose.ui.platform.LocalDensity.current) > 0 LauncherLayout( bottomNavigation && !s.dualScreen, pal.line, Modifier.fillMaxSize().onGloballyPositioned { screenAt = it.positionInRoot() } - .then(if (railSelection == "agent") Modifier.imePadding() else Modifier) + .then(if (openTab == "agent") Modifier.imePadding() else Modifier) .then(if (s.dualScreen) Modifier.onKeyEvent { event -> val step = dualPageStep(event.nativeKeyEvent) ?: return@onKeyEvent false if (event.type == KeyEventType.KeyDown && !processSettingsPageVisible) { 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 cb5d228a7a..9f457566bb 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndSetup.kt @@ -86,16 +86,19 @@ import com.droiddeck.launcher.R internal enum class CheckState { OK, WARN, BUSY } -private const val STORAGE_TAB = 3 -private const val LAUNCHER_TAB = 2 +private val OVERVIEW_TAB = SettingsSection.OVERVIEW.ordinal +private val PERFORMANCE_TAB = SettingsSection.PERFORMANCE.ordinal +private val CONTROLLER_TAB = SettingsSection.CONTROLLER.ordinal +private val GLASSES_TAB = SettingsSection.GLASSES.ordinal +private val LAUNCHER_TAB = SettingsSection.LAUNCHER.ordinal +private val DEVELOPER_TAB = SettingsSection.DEVELOPER.ordinal internal object SetupTabs { var openLauncher = false var focusTabs = false var openOverview = false + var openSection by mutableStateOf(null) } -private const val GLASSES_TAB = 6 -private const val SYNC_TAB = 4 @Composable internal fun CheckRow(state: CheckState, title: String, detail: String?, divider: Boolean = true, action: (@Composable () -> Unit)? = null) { @@ -193,40 +196,28 @@ internal fun SetupPanel( onDismiss = { editDownloadProxy = false }, onSave = { a.onDownloadProxy(it); editDownloadProxy = false }, ) - val tabs = listOf(stringResource(R.string.setup_tab_overview), stringResource(R.string.setup_tab_controller), stringResource(R.string.setup_tab_launcher), stringResource(R.string.setup_tab_storage), stringResource(R.string.setup_tab_sync), stringResource(R.string.setup_tab_diagnostics), stringResource(R.string.setup_tab_glasses)) - var tab by rememberSaveable { mutableStateOf(if (SetupTabs.openLauncher) LAUNCHER_TAB else 0) } + val tabs = SettingsSection.entries.map { stringResource(it.title) } + var tab by rememberSaveable { mutableStateOf(SetupTabs.openSection?.ordinal ?: if (SetupTabs.openLauncher) LAUNCHER_TAB else OVERVIEW_TAB) } + var query by rememberSaveable { mutableStateOf("") } + var searching by rememberSaveable { mutableStateOf(false) } var logsRefresh by remember { mutableStateOf(0) } var deleteSessionLogs by remember { mutableStateOf(null) } SetupTabs.openLauncher = false - if (SetupTabs.openOverview) { tab = 0; SetupTabs.openOverview = false } + if (SetupTabs.openOverview) { tab = OVERVIEW_TAB; SetupTabs.openOverview = false } + LaunchedEffect(SetupTabs.openSection) { + SetupTabs.openSection?.let { tab = it.ordinal; searching = false; query = "" } + SetupTabs.openSection = null + } val chipFocus = remember { List(tabs.size) { FocusRequester() } } var tabTurned by remember { mutableStateOf(false) } - val pick: (Int) -> Unit = { i -> tab = i; tabTurned = true; if (i == 5) logsRefresh++ } + val pick: (Int) -> Unit = { i -> tab = i; tabTurned = true; searching = false; query = ""; if (i == DEVELOPER_TAB) logsRefresh++ } val inputModeManager = LocalInputModeManager.current - LaunchedEffect(com.droiddeck.launcher.storage.StorageState.openRequests) { - if (com.droiddeck.launcher.storage.StorageState.openPending) { - com.droiddeck.launcher.storage.StorageState.openPending = false - tab = STORAGE_TAB - } - } LaunchedEffect(Unit) { while (true) { kotlinx.coroutines.delay(2_000) a.onRefreshPhantomStatus() } } - LaunchedEffect(com.droiddeck.launcher.sync.Syncthing.openRequests) { - if (com.droiddeck.launcher.sync.Syncthing.openPending) { - com.droiddeck.launcher.sync.Syncthing.openPending = false - tab = SYNC_TAB - } - } - var syncAdvanced by rememberSaveable { mutableStateOf(false) } - if (syncAdvanced) { - androidx.activity.compose.BackHandler { syncAdvanced = false } - SyncAdvancedPage(host) { syncAdvanced = false } - return - } LaunchedEffect(tab) { if (tabTurned && inputModeManager.inputMode == InputMode.Keyboard) { androidx.compose.runtime.withFrameNanos { } @@ -245,11 +236,17 @@ internal fun SetupPanel( ), ) { PageHeader(stringResource(R.string.setup_title)) { - Box(Modifier.weight(1f)) { SheetChips(tabs, tab, chipFocus, onPick = pick) } + SettingsPillSearch( + Modifier.weight(1f), searching, query, { query = it }, + onOpen = { searching = true }, onClose = { searching = false; query = "" }, + ) { SheetChips(tabs, tab, chipFocus, onPick = pick) } } - Column(modifier = Modifier.weight(1f).fillMaxWidth().then(if (tab == 1) Modifier else Modifier.verticalScroll(rememberScrollState())).padding(bottom = if (tab == 1) 0.dp else 24.dp)) { - when (tab) { - 0 -> { + val listing = searching && query.isNotBlank() + val fixed = tab == CONTROLLER_TAB && !listing + Column(modifier = Modifier.weight(1f).fillMaxWidth().then(if (fixed) Modifier else Modifier.verticalScroll(rememberScrollState())).padding(bottom = if (fixed) 0.dp else 24.dp)) { + if (listing) SettingsSearchResults(query) { section -> pick(section.ordinal) } + else when (tab) { + OVERVIEW_TAB -> { // Setup's "Safe mode" row, under the GPU row while the bridge is on and can be used here. val bridgeModeRow = !s.adreno && s.vkBridge && com.droiddeck.launcher.core.DeviceSupport.bridgeUsable() val gpuCheck: @Composable (Boolean) -> Unit = { divider -> @@ -413,12 +410,16 @@ internal fun SetupPanel( SettingsGroup(stringResource(R.string.setup_runtime)) { runtimeCheck(false) } SteamIntegrationGroup(s.integration, s.integrationFocus, a.onIntegration, a.onIntegrationAppInfo, a.onIntegrationLocation) } - 1 -> { + PERFORMANCE_TAB -> { + a.performancePanel() + MemoryGroup(s, a, host, onPairWirelessDebugging) + } + CONTROLLER_TAB -> { val controller = s.controller - if (controller != null && a.controller != null) InputSettingsPage(onBack = { pick(0) }, embedded = true) + if (controller != null && a.controller != null) InputSettingsPage(onBack = { pick(OVERVIEW_TAB) }, embedded = true) if (s.controller == null || a.controller == null) Note(stringResource(R.string.setup_controller_unavailable)) } - 2 -> { + LAUNCHER_TAB -> { val look: @Composable () -> Unit = { SettingsGroup(stringResource(R.string.setup_group_look)) { SettingsRow(stringResource(R.string.setup_theme), stringResource(R.string.setup_theme_hint)) { @@ -461,7 +462,6 @@ internal fun SetupPanel( LanguageRow(host, s.language, a.onLanguage) if (s.soundtracksEnabled) ToggleRow(host, "soundtracks-ingame", stringResource(R.string.setup_soundtracks_ingame), stringResource(R.string.setup_soundtracks_ingame_hint), s.soundtracksIngame, onChange = a.onSoundtracksIngame) } - TabsSettingsGroup(host, s, a) } val device: @Composable () -> Unit = { SettingsGroup(stringResource(R.string.setup_group_device)) { @@ -588,12 +588,16 @@ internal fun SetupPanel( } else Column { look(); device(); art(); download() } } } - STORAGE_TAB -> StoragePanel(s, a) - SYNC_TAB -> SyncPanel(host, runtimeOk) { syncAdvanced = true } - 5 -> { - SettingsGroup(stringResource(R.string.setup_tab_diagnostics)) { + DEVELOPER_TAB -> { + val devContext = LocalContext.current + SettingsGroup(stringResource(R.string.dev_tools_title)) { + ToggleRow(host, "developer-tools", stringResource(R.string.dev_tools_title), stringResource(R.string.dev_tools_hint), DeveloperTools.on) { + DeveloperTools.set(devContext, it) + } + } + SettingsGroup(stringResource(R.string.dev_group_logs)) { ToggleRow(host, "logs", stringResource(R.string.setup_logs), stringResource(R.string.setup_logs_hint), s.logsEnabled) { a.onLogs() } - ToggleRow( + if (DeveloperTools.on) ToggleRow( host, "enhanced-diagnostics", stringResource(R.string.setup_enhanced_diagnostics), stringResource(R.string.setup_enhanced_diagnostics_hint), s.enhancedDiagnosticsArmed, ) { a.onEnhancedDiagnostics() } @@ -603,9 +607,9 @@ internal fun SetupPanel( s.gameDebugLogsEnabled, enabled = s.logsEnabled, ) { a.onGameDebugLogs() } - ToggleRow(host, "vacdiag", stringResource(R.string.setup_vac_diag), stringResource(R.string.setup_vac_diag_hint), s.vacDiagnostics) { a.onVacDiagnostics() } - ToggleRow(host, "agent-commands", stringResource(R.string.setup_agent_commands), null, s.agentCommands) { a.onAgentCommands() } - if (com.droiddeck.launcher.agent.AgentHost.available) { + if (DeveloperTools.on) ToggleRow(host, "vacdiag", stringResource(R.string.setup_vac_diag), stringResource(R.string.setup_vac_diag_hint), s.vacDiagnostics) { a.onVacDiagnostics() } + if (DeveloperTools.on) ToggleRow(host, "agent-commands", stringResource(R.string.setup_agent_commands), null, s.agentCommands) { a.onAgentCommands() } + if (DeveloperTools.on && com.droiddeck.launcher.agent.AgentHost.available) { val agentContext = androidx.compose.ui.platform.LocalContext.current ToggleRow(host, "agent-pet", stringResource(R.string.setup_agent_pet), stringResource(R.string.setup_agent_pet_hint), AgentPet.enabled) { AgentPet.set(agentContext, it) @@ -615,8 +619,8 @@ internal fun SetupPanel( stringResource(R.string.setup_agent_pet_allow), onClick = { AgentPet.requestFloating(agentContext) }, ) } - ToggleRow(host, "graphics-logs", stringResource(R.string.setup_graphics_logs), stringResource(R.string.setup_graphics_logs_hint), s.graphicsLogs) { a.onGraphicsLogs() } - if (!s.adreno && com.droiddeck.launcher.session.SessionPrefs.steamGpuCompositingAllowed()) ToggleRow(host, "steam-gpu-drawing", stringResource(R.string.setup_steam_gpu_drawing), stringResource(R.string.setup_steam_gpu_drawing_hint), s.steamGpuDrawing) { a.onSteamGpuDrawing() } + if (DeveloperTools.on) ToggleRow(host, "graphics-logs", stringResource(R.string.setup_graphics_logs), stringResource(R.string.setup_graphics_logs_hint), s.graphicsLogs) { a.onGraphicsLogs() } + if (DeveloperTools.on && !s.adreno && com.droiddeck.launcher.session.SessionPrefs.steamGpuCompositingAllowed()) ToggleRow(host, "steam-gpu-drawing", stringResource(R.string.setup_steam_gpu_drawing), stringResource(R.string.setup_steam_gpu_drawing_hint), s.steamGpuDrawing) { a.onSteamGpuDrawing() } ActionRow(stringResource(R.string.setup_latest_logs), stringResource(R.string.drawer_logs_hint), stringResource(R.string.drawer_share_logs), a.onShareLogs, progress = com.droiddeck.launcher.session.SessionLogShare.progress) androidx.compose.material3.HorizontalDivider() @@ -661,38 +665,6 @@ internal fun SetupPanel( ActionRow(stringResource(R.string.setup_reset_settings), stringResource(R.string.setup_reset_settings_hint), stringResource(R.string.setup_reset_settings_button), a.onResetSettings) } - SettingsGroup(stringResource(R.string.setup_group_memory)) { - ToggleRow( - host, "clear-cached-apps", stringResource(R.string.setup_clear_cached), - stringResource(if (s.adbPaired) R.string.setup_clear_cached_hint else R.string.setup_clear_cached_unpaired), - s.clearCachedApps, enabled = s.adbPaired || s.clearCachedApps, - ) { a.onClearCachedApps(it) } - ChoiceRow( - host, "background-app-limit", stringResource(R.string.setup_bg_limit), - stringResource(if (s.adbPaired) R.string.setup_bg_limit_hint else R.string.setup_clear_cached_unpaired), - listOf( - com.droiddeck.launcher.core.BackgroundAppLimit.OFF to stringResource(R.string.game_env_off), - 4 to stringResource(R.string.setup_bg_limit_4), - 1 to stringResource(R.string.setup_bg_limit_1), - 0 to stringResource(R.string.setup_bg_limit_0), - ), - s.backgroundAppLimit, enabled = s.adbPaired || s.backgroundAppLimit != com.droiddeck.launcher.core.BackgroundAppLimit.OFF, - onPick = a.onBackgroundAppLimit, - ) - ChoiceRow( - host, "memory-hud", stringResource(R.string.setup_memory_hud), stringResource(R.string.setup_memory_hud_hint), - listOf( - com.droiddeck.launcher.session.SessionPrefs.MEMORY_HUD_OFF to stringResource(R.string.game_env_off), - com.droiddeck.launcher.session.SessionPrefs.MEMORY_HUD_SIMPLE to stringResource(R.string.setup_memory_hud_simple), - com.droiddeck.launcher.session.SessionPrefs.MEMORY_HUD_ADVANCED to stringResource(R.string.setup_memory_hud_advanced), - ), - s.memoryHud, onPick = a.onMemoryHud, - ) - if (!s.adbPaired) ActionRow( - stringResource(R.string.setup_adb_pair), stringResource(R.string.setup_adb_pair_hint), - stringResource(R.string.setup_adb_pair_button), onPairWirelessDebugging, - ) - } } GLASSES_TAB -> GlassesSetupPanel() } @@ -715,6 +687,42 @@ internal fun SetupPanel( } } +@Composable +private fun MemoryGroup(s: FrontEndState, a: FrontEndActions, host: MenuHost, onPairWirelessDebugging: () -> Unit) { + SettingsGroup(stringResource(R.string.setup_group_background_apps)) { + ToggleRow( + host, "clear-cached-apps", stringResource(R.string.setup_clear_cached), + stringResource(if (s.adbPaired) R.string.setup_clear_cached_hint else R.string.setup_clear_cached_unpaired), + s.clearCachedApps, enabled = s.adbPaired || s.clearCachedApps, + ) { a.onClearCachedApps(it) } + ChoiceRow( + host, "background-app-limit", stringResource(R.string.setup_bg_limit), + stringResource(if (s.adbPaired) R.string.setup_bg_limit_hint else R.string.setup_clear_cached_unpaired), + listOf( + com.droiddeck.launcher.core.BackgroundAppLimit.OFF to stringResource(R.string.game_env_off), + 4 to stringResource(R.string.setup_bg_limit_4), + 1 to stringResource(R.string.setup_bg_limit_1), + 0 to stringResource(R.string.setup_bg_limit_0), + ), + s.backgroundAppLimit, enabled = s.adbPaired || s.backgroundAppLimit != com.droiddeck.launcher.core.BackgroundAppLimit.OFF, + onPick = a.onBackgroundAppLimit, + ) + ChoiceRow( + host, "memory-hud", stringResource(R.string.setup_memory_hud), stringResource(R.string.setup_memory_hud_hint), + listOf( + com.droiddeck.launcher.session.SessionPrefs.MEMORY_HUD_OFF to stringResource(R.string.game_env_off), + com.droiddeck.launcher.session.SessionPrefs.MEMORY_HUD_SIMPLE to stringResource(R.string.setup_memory_hud_simple), + com.droiddeck.launcher.session.SessionPrefs.MEMORY_HUD_ADVANCED to stringResource(R.string.setup_memory_hud_advanced), + ), + s.memoryHud, onPick = a.onMemoryHud, + ) + if (!s.adbPaired) ActionRow( + stringResource(R.string.setup_adb_pair), stringResource(R.string.setup_adb_pair_hint), + stringResource(R.string.setup_adb_pair_button), onPairWirelessDebugging, + ) + } +} + @Composable internal fun ReadinessCard( passing: Int, total: Int, line: String, open: Boolean, onDetails: () -> Unit, title: String? = null, ready: Boolean = passing == total, 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 f12ad81ddb..6d360d7357 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/FrontEndWidgets.kt @@ -54,6 +54,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.draw.clip +import androidx.compose.ui.draw.drawBehind import androidx.compose.ui.draw.rotate import androidx.compose.ui.graphics.Brush import androidx.compose.ui.focus.focusProperties @@ -112,7 +113,8 @@ internal fun Actions(content: @Composable () -> Unit) = FlowRow( ) { content() } @Composable -internal fun ActionChip(t: String, ok: Boolean) = Box(contentAlignment = Alignment.Center, modifier = Modifier.heightIn(min = 44.dp)) { Chip(t, ok) } +internal fun ActionChip(t: String, ok: Boolean, fraction: Float? = null, key: Any? = null) = + Box(contentAlignment = Alignment.Center, modifier = Modifier.heightIn(min = 44.dp)) { Chip(t, ok, fraction, key) } internal val Shape16 = RoundedCornerShape(16.dp) @@ -139,13 +141,32 @@ internal fun BackLink(label: String, compact: Boolean = false, onClick: () -> Un } @Composable -internal fun Chip(t: String, ok: Boolean) { +internal fun Chip(t: String, ok: Boolean, fraction: Float? = null, key: Any? = null) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current - Text( - t, fontSize = 12.sp, color = if (ok) pal.good else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, - modifier = Modifier.clip(RoundedCornerShape(99.dp)).background(colors.surfaceVariant).border(1.dp, if (ok) pal.good.copy(alpha = 0.3f) else pal.line, RoundedCornerShape(99.dp)).padding(horizontal = 9.dp, vertical = 4.dp), - ) + val shape = RoundedCornerShape(99.dp) + val ink = if (ok) pal.good else colors.onSurfaceVariant + Box(Modifier.clip(shape).background(colors.surfaceVariant).border(1.dp, if (ok) pal.good.copy(alpha = 0.3f) else pal.line, shape)) { + if (fraction != null) ChipFill(fraction, key, pal.signal.copy(alpha = 0.3f)) + Text( + t, fontSize = 12.sp, color = ink, maxLines = 1, overflow = TextOverflow.Ellipsis, + modifier = Modifier.padding(horizontal = 9.dp, vertical = 4.dp), + ) + } +} + +@Composable +internal fun androidx.compose.foundation.layout.BoxScope.ChipFill(fraction: Float, key: Any?, color: Color) { + androidx.compose.runtime.key(key) { + val target = fraction.coerceIn(0f, 1f) + val shown = remember { Animatable(target) } + LaunchedEffect(target) { shown.animateTo(target, androidx.compose.animation.core.tween(250, easing = androidx.compose.animation.core.LinearEasing)) } + Box( + Modifier.matchParentSize().drawBehind { + drawRect(color, size = androidx.compose.ui.geometry.Size(size.width * shown.value, size.height)) + }, + ) + } } @Composable diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt index a1fe8dc9a4..edd95faab4 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameDetail.kt @@ -1,5 +1,7 @@ package com.droiddeck.launcher.ui +import android.widget.Toast +import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.LocalIndication import androidx.compose.ui.semantics.Role import androidx.compose.runtime.CompositionLocalProvider @@ -216,7 +218,6 @@ internal fun GameDetail( } val art: Any? = game?.hero ?: item?.imageUrl ?: installed?.sidecar?.hero ?: installed?.sidecar?.cover val artModel: Any? = if (art is String) cardArtRequest(art, item?.tallImageUrl) else art - val inSteam = !s.shortcutPicker && source != Library.SOURCE_STEAM && (game != null || installed != null) && !(game?.library == Library.XBOX_CLOUD && installed == null) val inset = LocalDetailInset.current GameBackdrop(artModel, art ?: game?.art, hueOf(title), fadeTop = inset.top < 8.dp, onArtPlaced = { StoresMotion.heroAt = it }) { Column(Modifier.fillMaxWidth().padding(horizontal = inset.horizontal).padding(top = inset.top).onFocusChanged { inPage = it.hasFocus }.bumpers(onPrevious = { cycle(-1) }, onNext = { cycle(1) })) { @@ -236,8 +237,9 @@ internal fun GameDetail( } val header: @Composable () -> Unit = { Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { - GameStatusLine(source, game, item, installed, download?.location ?: failed?.location, inSteam) + Spacer(Modifier.height(if (narrow) 8.dp else 20.dp)) GameTitle(title, game?.logo ?: item?.logoUrl, if (narrow) 30.sp else 40.sp) + GameStatusLine(source, game, item, installed, download?.location ?: failed?.location) if (!failed?.error.isNullOrBlank()) Text( failed!!.error!!, fontSize = 13.sp, lineHeight = 17.sp, fontWeight = FontWeight.Medium, color = MaterialTheme.colorScheme.error, maxLines = 3, overflow = TextOverflow.Ellipsis, @@ -256,7 +258,7 @@ internal fun GameDetail( stringResource(R.string.game_tab_achievements_count, stringResource(R.string.achievements_title), achievementState.done, list.size) } ?: stringResource(R.string.achievements_title) GameTab.LAUNCH -> stringResource(R.string.game_tab_launch) - GameTab.SAVES -> stringResource(if (Store.byId(source).let { it == Store.GOG || it == Store.EPIC }) R.string.game_tab_saves_cloud else R.string.games_saves) + GameTab.SAVES -> stringResource(if (CloudSaves.supports(Store.byId(source))) R.string.game_tab_saves_cloud else R.string.games_saves) GameTab.ADDONS -> stringResource(R.string.game_tab_addons) GameTab.INSTALL -> stringResource(R.string.game_tab_install) } @@ -296,16 +298,16 @@ internal fun SourceBadge(source: String) { } @Composable -private fun GameStatusLine(source: String, game: Library.SteamGame?, item: CatalogItem?, installed: InstalledStoreGame?, downloadAt: String?, inSteam: Boolean) { +private fun GameStatusLine(source: String, game: Library.SteamGame?, item: CatalogItem?, installed: InstalledStoreGame?, downloadAt: String?) { val ctx = LocalContext.current val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val folder = installed?.folder ?: game?.gameFiles val passName = item?.includedWith.orEmpty() val state = when { - installed != null -> listOf(stringResource(R.string.stores_eyebrow_installed), StoreInstallRoot.labelFor(ctx, installed.folder)) + installed != null -> listOf(StoreInstallRoot.labelFor(ctx, installed.folder)) game?.library == Library.XBOX_CLOUD -> listOf(libraryLabel(game)) - game != null -> listOf(stringResource(R.string.stores_eyebrow_installed), libraryLabel(game)) + game != null -> listOf(libraryLabel(game)) !downloadAt.isNullOrBlank() -> listOf(stringResource(R.string.stores_eyebrow_library), downloadAt) item?.owned == true -> listOf(stringResource(R.string.stores_eyebrow_library)) item?.subscription == true -> listOf(passName.ifBlank { stringResource(R.string.stores_game_pass) }) @@ -314,19 +316,26 @@ private fun GameStatusLine(source: String, game: Library.SteamGame?, item: Catal else -> listOf(stringResource(R.string.stores_eyebrow_store)) } val size = if (folder != null && (installed != null || game != null)) diskSize(installed, folder) else catalogSize(item).takeIf { it > 0 } - val line = (state + listOfNotNull(size?.let { formatBytes(it) })).filter { it.isNotBlank() }.joinToString(" · ").replaceFirstChar { it.uppercase() } - val muted = colors.onBackground.copy(alpha = 0.78f) - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { + val where = state.filter { it.isNotBlank() }.joinToString(" · ").replaceFirstChar { it.uppercase() } + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.horizontalScroll(androidx.compose.foundation.rememberScrollState()), + ) { SourceBadge(source) - Text(line, fontSize = 12.sp, color = muted, maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f, fill = false)) - if (inSteam) { - Text("·", fontSize = 12.sp, color = muted.copy(alpha = 0.5f)) - Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(5.dp)) { - Icon(Icons.Outlined.VideogameAsset, contentDescription = null, tint = muted, modifier = Modifier.size(15.dp)) - Text(stringResource(R.string.stores_in_steam_label), fontSize = 12.sp, color = muted, maxLines = 1) - Icon(Icons.Filled.Check, contentDescription = null, tint = pal.good, modifier = Modifier.size(14.dp)) - } - } + if (where.isNotBlank()) StatusChip(where) + if (size != null) StatusChip(formatBytes(size)) + } +} + +@Composable +private fun StatusChip(text: String, icon: androidx.compose.ui.graphics.vector.ImageVector? = null, tint: Color? = null) { + val colors = MaterialTheme.colorScheme + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.glass(CircleShape, 0.06f).padding(horizontal = 10.dp, vertical = 4.dp), + ) { + if (icon != null) Icon(icon, contentDescription = null, tint = tint ?: colors.onBackground.copy(alpha = 0.85f), modifier = Modifier.size(13.dp)) + Text(text, fontSize = 11.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground.copy(alpha = 0.9f), maxLines = 1) } } @@ -384,7 +393,7 @@ private fun GameTitle(title: String, logo: Any?, titleSize: TextUnit) { if (logo != null && !failed) AsyncImage( model = logo, contentDescription = title, contentScale = ContentScale.Fit, alignment = Alignment.CenterStart, onError = { failed = true }, - modifier = Modifier.padding(vertical = 4.dp).height((titleSize.value * 1.5f).dp).widthIn(max = (titleSize.value * 7f).dp).clip(RoundedCornerShape(10.dp)).testTag("game-logo"), + modifier = Modifier.padding(vertical = 4.dp).height((titleSize.value * 2.3f).dp).widthIn(max = (titleSize.value * 10f).dp).clip(RoundedCornerShape(10.dp)).testTag("game-logo"), ) else Text( title, fontSize = titleSize, lineHeight = titleSize * 1.12f, fontWeight = FontWeight.Black, color = MaterialTheme.colorScheme.onBackground, maxLines = 2, overflow = TextOverflow.Ellipsis, @@ -449,7 +458,7 @@ internal fun GameActions( if (installed != null && id != null) { LaunchedEffect(id) { BattleNetInstall.checkUpdate(ctx, installed) } if (download != null) { - ActionChip(downloadLabel(download), ok = false) + ActionChip(downloadLabel(download), ok = false, fraction = download.stageFraction.takeIf { it >= 0f }, key = download.stage) if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause)) { DownloadQueue.pause(download.key) } else SecondaryButton(stringResource(R.string.stores_dl_resume)) { DownloadQueue.resume(ctx, download.key) } } else if (BattleNetInstall.updates[id] == true) { @@ -458,10 +467,13 @@ internal fun GameActions( } SecondaryButton(stringResource(R.string.bnet_open)) { a.onBattleNet() } } - if (game != null && !compactMenu) EditArtButton(game) + if (game != null && !compactMenu) { + HideButton(hideKey(game), game) + EditArtButton(game) + } } download != null -> { - ActionChip(downloadLabel(download), ok = false) + ActionChip(downloadLabel(download), ok = false, fraction = download.stageFraction.takeIf { it >= 0f }, key = download.stage) if (download.state != DownloadState.PAUSED) SecondaryButton(stringResource(R.string.stores_dl_pause), modifier = leadOn) { DownloadQueue.pause(download.key) } else PrimaryButton(stringResource(R.string.stores_dl_resume), main = true, modifier = leadOn) { DownloadQueue.resume(ctx, download.key) } ConfirmButton(stringResource(R.string.stores_dl_cancel), stringResource(R.string.stores_dl_cancel_confirm)) { DownloadQueue.cancel(ctx, download.key) } @@ -518,6 +530,8 @@ internal fun GameActions( } item != null -> PrimaryButton(buyLabel(item), main = true, modifier = leadOn) { openStoreUrl(ctx, item) } } + val entryKey = game?.let(::hideKey) ?: storeKey + if (!s.shortcutPicker && entryKey != null && (game == null || cloud)) HideButton(entryKey, game) if (cloud && (download != null || failed != null)) { XboxStreamButton(game.storeId.orEmpty(), game.name) XboxLibraryButton(game.storeId.orEmpty(), item) @@ -610,6 +624,17 @@ internal fun rememberEditArt(g: Library.SteamGame): (() -> Unit)? { } } +internal fun hideKey(g: Library.SteamGame): String = g.storeId?.let { "${g.source}:$it" } ?: GameRef.key(g) + +@Composable +internal fun HideButton(key: String, g: Library.SteamGame?) { + val ctx = LocalContext.current + rememberHiddenSync() + val hidden = LibraryHidden.isHidden(key, g) + val failed = stringResource(R.string.game_hide_failed) + SecondaryButton(stringResource(if (hidden) R.string.game_unhide else R.string.common_hide), compact = true) { if (!LibraryHidden.set(ctx, key, g, !hidden)) Toast.makeText(ctx, failed, Toast.LENGTH_LONG).show() } +} + @Composable internal fun EditArtButton(g: Library.SteamGame) { val open = rememberEditArt(g) ?: return @@ -620,6 +645,10 @@ internal fun EditArtButton(g: Library.SteamGame) { private fun GameMoreMenu(g: Library.SteamGame, a: FrontEndActions) { var open by remember(g.gameId) { mutableStateOf(false) } val edit = rememberEditArt(g) + val ctx = LocalContext.current + rememberHiddenSync() + val hidden = LibraryHidden.isHidden(hideKey(g), g) + val failed = stringResource(R.string.game_hide_failed) Box { SecondaryButton(stringResource(R.string.game_more)) { open = !open } AnchoredMenu(open, onDismiss = { open = false }, title = stringResource(R.string.game_more), compact = true) { first -> @@ -630,6 +659,8 @@ private fun GameMoreMenu(g: Library.SteamGame, a: FrontEndActions) { MenuItem(stringResource(R.string.game_shortcut_add), checked = false, focusRequester = take()) { open = false; a.onGameShortcut(g) } MenuItem(stringResource(R.string.game_file_export), checked = false) { open = false; a.onExportGameFile(g) } MenuItem(stringResource(R.string.game_link_copy), checked = false) { open = false; a.onCopyGameLink(g) } + val hideKey = hideKey(g) + MenuItem(stringResource(if (hidden) R.string.game_unhide else R.string.common_hide), checked = false) { open = false; if (!LibraryHidden.set(ctx, hideKey, g, !hidden)) Toast.makeText(ctx, failed, Toast.LENGTH_LONG).show() } edit?.let { run -> MenuItem(stringResource(R.string.game_edit_art), checked = false) { open = false; run() } } } } @@ -861,8 +892,10 @@ private fun ShortcutFields(game: Library.SteamGame, folder: File) { @Composable private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) { - val saves by produceState?>(null, g.gameId) { - value = withContext(Dispatchers.IO) { runCatching { GameSaves.locate(prefix, g) }.getOrDefault(emptyList()) } + val context = LocalContext.current.applicationContext + var synced by remember(g.gameId) { mutableStateOf(0) } + val saves by produceState?>(null, g.gameId, synced) { + value = withContext(Dispatchers.IO) { runCatching { GameSaves.saves(context, prefix, g) }.getOrDefault(emptyList()) } } val found = saves val summary = when { @@ -880,9 +913,9 @@ private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) { } Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) { Text(summary, fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(bottom = 6.dp).readable().padding(4.dp)) - if (Store.byId(g.source).let { it == Store.GOG || it == Store.EPIC }) { + if (CloudSaves.supports(Store.byId(g.source))) { SectionLabel(stringResource(R.string.store_cloud_saves)) - CloudRows(g) + CloudRows(g) { synced++ } SectionLabel(stringResource(R.string.games_saves)) } MenuItem(stringResource(R.string.games_import_saves), checked = false) { a.onSaveImport(g) } @@ -938,14 +971,16 @@ private fun AddonRow(name: String, target: WowAddons.Target, a: FrontEndActions) } @Composable -private fun CloudRows(g: Library.SteamGame) { - val store = Store.byId(g.source)?.takeIf { it != Store.AMAZON && it != Store.EA } ?: return +private fun CloudRows(g: Library.SteamGame, onSynced: () -> Unit = {}) { + val store = Store.byId(g.source)?.takeIf { it != Store.AMAZON } ?: return val id = g.storeId ?: return val context = LocalContext.current.applicationContext var busy by remember(g.gameId) { mutableStateOf(null) } var tick by remember(g.gameId) { mutableStateOf(0) } + var refreshing by remember(g.gameId) { mutableStateOf(false) } val status by produceState(null, g.gameId, tick) { value = withContext(Dispatchers.IO) { runCatching { CloudSaves.status(context, store, id) }.getOrNull() } + refreshing = false } val folder = g.gameFiles var enabled by remember(g.gameId) { mutableStateOf(folder?.let { StoreGameSidecar.read(it)?.cloud } ?: true) } @@ -957,7 +992,7 @@ private fun CloudRows(g: Library.SteamGame) { busy = if (up) "up" else "down" Thread({ val r = if (up) CloudSaves.upload(context, store, id, force) else CloudSaves.download(context, store, id, force) - StoresState.post { busy = null; tick++; android.widget.Toast.makeText(context, cloudMessage(context, r), android.widget.Toast.LENGTH_SHORT).show() } + StoresState.post { refreshing = true; busy = null; tick++; onSynced(); android.widget.Toast.makeText(context, cloudMessage(context, r), android.widget.Toast.LENGTH_SHORT).show() } }, "cloud-manual").start() } MenuItem(stringResource(R.string.store_cloud_saves), checked = enabled && supported, enabled = supported, @@ -969,11 +1004,13 @@ private fun CloudRows(g: Library.SteamGame) { StoresState.post { enabled = written?.cloud ?: enabled } }, "cloud-switch").start() } - val ready = st != null && supported && enabled && busy == null + val ready = st != null && supported && enabled && busy == null && !refreshing && st.folder != null && st.signedIn val pending = stringResource(R.string.cloud_pending) val summary = when { st == null || busy != null -> pending !supported -> stringResource(R.string.cloud_none) + !st.signedIn || st.reason == "not-signed-in" -> stringResource(R.string.cloud_signed_out) + st.folder == null -> stringResource(R.string.cloud_not_synced) conflict -> stringResource(R.string.cloud_conflict_files, st.conflicts.size) st.lastSync > 0 -> stringResource(R.string.cloud_last_sync, android.text.format.DateUtils.getRelativeTimeSpanString(st.lastSync).toString()) else -> stringResource(R.string.cloud_never) @@ -1055,6 +1092,15 @@ internal fun diskSize(installed: InstalledStoreGame?, folder: File): Long? { internal object FolderSizes { val known = androidx.compose.runtime.mutableStateMapOf() private val asked = java.util.Collections.synchronizedSet(HashSet()) + private var saved: android.content.SharedPreferences? = null + + // The last walk of each folder shows at once after a restart; a fresh walk still replaces it. + fun load(context: android.content.Context) { + if (saved != null) return + val p = context.applicationContext.getSharedPreferences("folder_sizes", android.content.Context.MODE_PRIVATE) + saved = p + p.all.forEach { (path, bytes) -> if (bytes is Long && path !in known) known[path] = bytes } + } fun request(folder: File) { if (!asked.add(folder.path)) return @@ -1069,7 +1115,10 @@ internal object FolderSizes { override fun visitFileFailed(file: java.nio.file.Path, exc: java.io.IOException): java.nio.file.FileVisitResult = java.nio.file.FileVisitResult.CONTINUE }) }.isSuccess - if (walked) StoresState.post { known[folder.path] = total } else asked.remove(folder.path) + if (walked) { + saved?.edit()?.putLong(folder.path, total)?.apply() + StoresState.post { known[folder.path] = total } + } else asked.remove(folder.path) }, "folder-size").start() } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GameGlass.kt b/app/src/main/java/com/droiddeck/launcher/ui/GameGlass.kt index e5fd8845bd..39c6b07768 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GameGlass.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GameGlass.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.ui +import androidx.compose.animation.core.animateFloat import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Box @@ -117,7 +118,7 @@ private fun ambientRequest(ctx: android.content.Context, model: Any?): ImageRequ private const val AmbientPixels = 6 @Composable -private fun rememberArtBrightness(model: Any?): Float { +internal fun rememberArtBrightness(model: Any?): Float { val ctx = LocalContext.current val data = (model as? ImageRequest)?.data ?: model val brightness by produceState(0.3f, data) { @@ -170,6 +171,10 @@ internal fun GameBackdrop( }, ) { DisposableEffect(art == null) { onDispose { if (art == null) onArtPlaced(null) } } + if (art == null) androidx.compose.runtime.SideEffect { + StoresMotion.heroFadeTop = fadeTop + StoresMotion.heroDrift = { 0f } + } Box( Modifier.matchParentSize() .graphicsLayer { compositingStrategy = CompositingStrategy.Offscreen } @@ -189,8 +194,9 @@ internal fun GameBackdrop( private fun ArtLayer(model: Any?, sample: Any?, fadeTop: Boolean, blur: androidx.compose.ui.unit.Dp, onPlaced: (androidx.compose.ui.geometry.Rect?) -> Unit) { val colors = MaterialTheme.colorScheme val light = colors.background.luminance() > 0.5f - val pale = ((rememberArtBrightness(sample) - 0.28f) / 0.5f).coerceIn(0f, 1f) - val dim = if (light) 1f else 1f - 0.4f * pale + val look = HeroLook(rememberArtBrightness(sample), light, colors.background) + val dim = look.dim + val pale = look.pale val artFilter = remember(dim) { ColorFilter.colorMatrix(ColorMatrix(floatArrayOf(dim, 0f, 0f, 0f, 0f, 0f, dim, 0f, 0f, 0f, 0f, 0f, dim, 0f, 0f, 0f, 0f, 0f, 1f, 0f))) } BoxWithConstraints(Modifier.fillMaxWidth()) { val height = (maxWidth * 0.4f).coerceIn(ArtMin, ArtMax) @@ -206,24 +212,37 @@ private fun ArtLayer(model: Any?, sample: Any?, fadeTop: Boolean, blur: androidx if (fadeTop) drawRect(Brush.verticalGradient(0f to Color.Transparent, (24.dp.toPx() / size.height) to Color.Black), blendMode = BlendMode.DstIn) }, ) { + // A slow push-in and drift, centred where the crop leans, that starts from rest so a card flight lands on the same frame. + val drift = if (Motion.scale == 0f) null else androidx.compose.animation.core.rememberInfiniteTransition(label = "heroDrift").animateFloat( + 0f, 1f, + androidx.compose.animation.core.infiniteRepeatable( + androidx.compose.animation.core.tween(18_000, easing = androidx.compose.animation.core.EaseInOutSine), + androidx.compose.animation.core.RepeatMode.Reverse, + ), + label = "heroDriftT", + ) + androidx.compose.runtime.SideEffect { + StoresMotion.heroFadeTop = fadeTop + StoresMotion.heroDrift = { drift?.value ?: 0f } + } AsyncImage( model = model, contentDescription = null, contentScale = ContentScale.Crop, alignment = BiasAlignment(0.45f, -0.35f), colorFilter = artFilter, - modifier = Modifier.matchParentSize().then(if (blur > 0.dp) Modifier.blur(blur) else Modifier), + modifier = Modifier.matchParentSize() + .graphicsLayer { + val t = drift?.value ?: 0f + val zoom = HeroDrift.zoom(t) + scaleX = zoom + scaleY = zoom + translationX = size.width * HeroDrift.DX * t + translationY = size.height * HeroDrift.DY * t + transformOrigin = androidx.compose.ui.graphics.TransformOrigin(HeroDrift.PX, HeroDrift.PY) + } + .then(if (blur > 0.dp) Modifier.blur(blur) else Modifier), ) Box( - Modifier.matchParentSize().drawBehind { - drawRect(colors.background.copy(alpha = if (light) 0.1f else 0.12f + 0.3f * pale)) - drawRect( - Brush.radialGradient( - 0f to colors.background.copy(alpha = if (light) 0.5f else 0.66f), - 0.55f to colors.background.copy(alpha = if (light) 0.2f else 0.3f), - 1f to Color.Transparent, - center = Offset(size.width * 0.22f, size.height * 0.55f), radius = size.width * 0.55f, - ), - ) - }, + Modifier.matchParentSize().drawBehind { with(look) { shade(size, 1f) } }, ) } } @@ -265,3 +284,29 @@ internal fun Modifier.glass(shape: Shape, lift: Float = 0f): Modifier { } .border(1.dp, rim, shape) } + +internal class HeroLook(brightness: Float, val light: Boolean, val background: Color) { + val pale = ((brightness - 0.28f) / 0.5f).coerceIn(0f, 1f) + val dim = if (light) 1f else 1f - 0.4f * pale + + fun androidx.compose.ui.graphics.drawscope.DrawScope.shade(size: androidx.compose.ui.geometry.Size, strength: Float) { + drawRect(background.copy(alpha = (if (light) 0.1f else 0.12f + 0.3f * pale) * strength), size = size) + drawRect( + Brush.radialGradient( + 0f to background.copy(alpha = (if (light) 0.5f else 0.66f) * strength), + 0.55f to background.copy(alpha = (if (light) 0.2f else 0.3f) * strength), + 1f to Color.Transparent, + center = Offset(size.width * 0.22f, size.height * 0.55f), radius = size.width * 0.55f, + ), + size = size, + ) + } +} + +internal object HeroDrift { + const val PX = 0.72f + const val PY = 0.33f + const val DX = -0.04f + const val DY = 0.03f + fun zoom(t: Float) = 1f + 0.16f * t +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/GogMaintenanceUi.kt b/app/src/main/java/com/droiddeck/launcher/ui/GogMaintenanceUi.kt index 57f6923396..165905ac51 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/GogMaintenanceUi.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/GogMaintenanceUi.kt @@ -68,7 +68,7 @@ internal fun GogMaintenanceActions(game: InstalledStoreGame) { } } if (active) { - ActionChip(downloadLabel(download!!), ok = false) + ActionChip(downloadLabel(download!!), ok = false, fraction = download!!.stageFraction.takeIf { it >= 0f }, key = download!!.stage) if (download.interruptible) { SecondaryButton(stringResource(if (download.state == DownloadState.PAUSED) R.string.stores_dl_resume else R.string.stores_dl_pause)) { if (download.state == DownloadState.PAUSED) DownloadQueue.resume(ctx, key) else DownloadQueue.pause(key) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt index ddf5838be8..5b94225115 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceDialog.kt @@ -1,6 +1,7 @@ package com.droiddeck.launcher.ui import android.app.Presentation +import android.graphics.Rect import android.hardware.display.DisplayManager import android.os.Bundle import android.os.Handler @@ -37,6 +38,7 @@ import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize +import kotlin.math.abs import kotlin.math.roundToInt import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.LocalContext @@ -59,7 +61,7 @@ import com.droiddeck.launcher.input.* import com.droiddeck.launcher.session.SessionState private data class SurfaceSnapshot(val elements: List, val actions: Map, - val clicks: Map, val scale: Float) + val clicks: Map, val scale: Float, val aspect: Float) private class GamepadScaler(private val context: android.content.Context, private val width: Int, private val height: Int) { private fun generator(scale: Float) = LegacyGamepadLayout(context, width, height, scale = scale) @@ -69,7 +71,8 @@ private class GamepadScaler(private val context: android.content.Context, privat } private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputBindings, val defaults: List? = null, - private val gamepad: GamepadScaler? = null, snap: Boolean = true) { + private val defaultsFrame: Float = 0f, private var gamepad: GamepadScaler? = null, snap: Boolean = true) { + val hasGamepad get() = gamepad != null var elements by mutableStateOf(layout.elements) var actions by mutableStateOf(preset.elements) var clicks by mutableStateOf(preset.clicks) @@ -83,27 +86,40 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB var clickProperties by mutableStateOf(false) var history by mutableStateOf>(emptyList()) var layoutScale by mutableFloatStateOf(layout.scale) + var aspect by mutableFloatStateOf(layout.aspect) private var scaleBase by mutableStateOf, List, Float>?>(null) private var scaleValue by mutableIntStateOf(100) - private val rescales get() = gamepad != null && elements.any { it.id in gamepad.ids } + private val rescales get() = gamepad?.let { pad -> elements.any { it.id in pad.ids } } == true val scale get() = when { scaleBase?.second == elements -> scaleValue rescales -> (layoutScale * 100).roundToInt() else -> 100 } - val positioned get() = (if (rescales) gamepad!!.reset(elements) else defaults?.let { elements.withPositionsOf(it) }) + val positioned get() = (if (rescales) gamepad!!.reset(elements) else defaults?.let { elements.withPositionsOf(refit(it, defaultsFrame)) }) ?.takeIf { it != elements || rescales && layoutScale != 1f } + + private fun refit(placed: List, from: Float): List { + if (from <= 0f || aspect <= 0f || abs(from / aspect - 1f) < .01f) return placed + return OnScreenLayout.fit(placed, from, 1f, (aspect * 1000).roundToInt().coerceAtLeast(1), 1000, Rect()) + } val element get() = elements.firstOrNull { it.id == selected } - val dirty get() = elements != layout.elements || actions != preset.elements || clicks != preset.clicks || layoutScale != layout.scale - fun checkpoint() { history = (history + SurfaceSnapshot(elements, actions, clicks, layoutScale)).takeLast(40) } - fun undo() { history.lastOrNull()?.let { elements = it.elements; actions = it.actions; clicks = it.clicks; layoutScale = it.scale; history = history.dropLast(1) } } + val dirty get() = elements != layout.elements || actions != preset.elements || clicks != preset.clicks || layoutScale != layout.scale || aspect != layout.aspect + fun checkpoint() { history = (history + SurfaceSnapshot(elements, actions, clicks, layoutScale, aspect)).takeLast(40) } + fun undo() { history.lastOrNull()?.let { elements = it.elements; actions = it.actions; clicks = it.clicks; layoutScale = it.scale; aspect = it.aspect; history = history.dropLast(1) } } + fun beginEdit(displayed: List, aspect: Float, scaler: GamepadScaler? = gamepad) { + checkpoint() + elements = OnScreenLayout.editorFrame(layout.copy(elements = elements), displayed) + this.aspect = aspect + scaler?.let { gamepad = it } + } fun scaleAll(percent: Int) { val base = scaleBase?.takeIf { it.second == elements } ?: Triple(elements, elements, if (rescales) layoutScale else 0f).also { checkpoint() } val factor = percent / 100f - elements = if (base.third > 0f && gamepad != null) { + val pad = gamepad + elements = if (base.third > 0f && pad != null) { layoutScale = factor - val others = base.first.filterNot { it.id in gamepad.ids }.scaled(factor / base.third).associateBy { it.id } - gamepad.rescale(base.first, base.third, factor).map { others[it.id] ?: it } + val others = base.first.filterNot { it.id in pad.ids }.scaled(factor / base.third).associateBy { it.id } + pad.rescale(base.first, base.third, factor).map { others[it.id] ?: it } } else base.first.scaled(factor) scaleValue = percent; scaleBase = Triple(base.first, elements, base.third) } @@ -112,10 +128,6 @@ private class SurfaceDraft(val layout: SavedInputLayout, val preset: SavedInputB fun clickAction(e: InputSurfaceElement) = preset.copy(elements = actions, clicks = clicks).clickAction(e) } -@Suppress("DEPRECATION") -private fun displayAspect(display: Display): Float? = android.util.DisplayMetrics().also(display::getRealMetrics) - .takeIf { it.widthPixels > 0 && it.heightPixels > 0 }?.let { (it.widthPixels.toFloat() / it.heightPixels).coerceIn(.05f, 20f) } - @Composable fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> Unit, role: InputRole = InputRole.SECONDARY, layoutId: String? = null, bindingsId: String? = null) { @@ -132,7 +144,8 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> val (w, h) = OnScreenLayout.generatedSize(context, savedLayout, metrics.widthPixels, metrics.heightPixels) ?: (metrics.widthPixels to metrics.heightPixels) GamepadScaler(display, w, h) } - SurfaceDraft(savedLayout, savedBindings, InputLibraries.defaultPositions(context, library, savedLayout), gamepad, ControllerPrefs.snap(context)) + val defaults = InputLibraries.defaultPositions(context, library, savedLayout) + SurfaceDraft(savedLayout, savedBindings, defaults?.first, defaults?.second ?: 0f, gamepad, ControllerPrefs.snap(context)) } val manager = remember { context.getSystemService(DisplayManager::class.java) } var revision by remember { mutableIntStateOf(0) } @@ -153,7 +166,7 @@ fun InputSurfaceDialog(profile: String, onDismiss: () -> Unit, onChanged: () -> InputLibraries.update(context) { latest -> val l = latest.layouts.first { it.id == savedLayout.id } val p = latest.preset(savedBindings.id) - latest.withLayout(l.copy(elements = draft.elements, aspect = target?.let(::displayAspect) ?: l.aspect, scale = draft.layoutScale)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } }, + latest.withLayout(l.copy(elements = draft.elements, aspect = draft.aspect, scale = draft.layoutScale)).withPreset(p.copy(elements = draft.actions.filterKeys { id -> draft.elements.any { it.id == id } }, clicks = draft.clicks.filterKeys { id -> draft.elements.any { it.id == id && it.hasClick } })) } }.onSuccess { onChanged(); onDismiss() }.onFailure { failure = it.message ?: context.getString(R.string.input_save_failed) } @@ -253,10 +266,10 @@ private fun SurfaceCanvas(draft: SurfaceDraft, transparent: Boolean = false) { AndroidView(factory = { InputSurfaceEditorView(it) }, modifier = Modifier.fillMaxSize().testTag("input-layout-canvas"), update = { view -> view.setBackgroundColor(if (transparent) android.graphics.Color.TRANSPARENT else android.graphics.Color.rgb(10, 11, 13)) - view.style = draft.layout.style.copy(hidden = emptySet()); view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap + view.style = draft.layout.style.copy(hidden = emptySet()); view.sourceLayout = draft.layout; view.aspect = draft.aspect; view.elements = draft.elements; view.selected = draft.selected; view.snap = draft.snap view.isEnabled = !draft.properties && !draft.adding view.onSelect = { if (!draft.properties) draft.selected = it } - view.onBeginEdit = draft::checkpoint + view.onBeginEdit = { e, w, h -> draft.beginEdit(e, w.toFloat() / h, if (draft.hasGamepad) GamepadScaler(view.context, w, h) else null) } view.onChange = { e -> if (!draft.properties) draft.elements = draft.elements.map { if (it.id == e.id) e else it } } }) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt index d03eaa6e9f..1e21a245de 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceEditorView.kt @@ -9,6 +9,8 @@ import android.view.HapticFeedbackConstants import android.view.MotionEvent import android.view.ViewConfiguration import android.widget.FrameLayout +import com.droiddeck.launcher.input.OnScreenLayout +import com.droiddeck.launcher.input.SavedInputLayout import com.droiddeck.launcher.input.InputSurfaceElement import com.droiddeck.launcher.input.InputSurfaceStyle import com.droiddeck.launcher.input.snapSurfaceElement @@ -16,7 +18,11 @@ import kotlin.math.abs internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { var elements: List = emptyList() - set(value) { field = value; preview.updateCustomLayout(value); invalidate() } + set(value) { field = value; refreshElements(); invalidate() } + var aspect = 1f + set(value) { field = value; refreshElements(); invalidate() } + var sourceLayout: SavedInputLayout? = null + set(value) { field = value; refreshElements(); invalidate() } var style = InputSurfaceStyle() set(value) { field = value; preview.updateStyle(value) } var snap = true @@ -26,7 +32,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { var selected: String? = null set(value) { field = value; invalidate() } var onSelect: (String?) -> Unit = {} - var onBeginEdit: () -> Unit = {} + var onBeginEdit: (List, Int, Int) -> Unit = { _, _, _ -> } var onChange: (InputSurfaceElement) -> Unit = {} private val preview = InputSurfaceView(context) private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.rgb(26, 159, 255); strokeWidth = 2 * resources.displayMetrics.density } @@ -37,17 +43,31 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { private var corner = 0 private var dragging = false + private var visibleElements: List = emptyList() + init { setBackgroundColor(Color.rgb(10, 11, 13)) addView(preview, LayoutParams(-1, -1)) } + private fun refreshElements() { + visibleElements = sourceLayout?.let { layout -> + OnScreenLayout.editorElements(context, layout.copy(elements = elements, aspect = aspect), width, height) + } ?: elements + preview.updateCustomLayout(visibleElements) + } + + override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { + super.onSizeChanged(w, h, oldw, oldh) + refreshElements() + } + override fun dispatchDraw(canvas: Canvas) { super.dispatchDraw(canvas) paint.style = Paint.Style.STROKE guideX?.let { canvas.drawLine(width * it, 0f, width * it, height.toFloat(), paint) } guideY?.let { canvas.drawLine(0f, height * it, width.toFloat(), height * it, paint) } - val e = elements.firstOrNull { it.id == selected } ?: return + val e = visibleElements.firstOrNull { it.id == selected } ?: return val l = width * e.x; val t = height * e.y; val r = l + width * e.width; val b = t + height * e.height paint.style = Paint.Style.STROKE; canvas.drawRect(l, t, r, b, paint) paint.style = Paint.Style.FILL @@ -65,7 +85,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { MotionEvent.ACTION_DOWN -> { clearGuides() downX = event.x; downY = event.y; dragging = false; corner = 0 - val current = elements.firstOrNull { it.id == selected } + val current = visibleElements.firstOrNull { it.id == selected } if (current != null) { val left = width * current.x; val top = height * current.y val right = left + width * current.width; val bottom = top + height * current.height @@ -73,7 +93,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { val vertical = if (abs(downY - top) < radius) 4 else if (abs(downY - bottom) < radius) 8 else 0 if (horizontal != 0 && vertical != 0) corner = horizontal or vertical } - original = if (corner != 0) current else elements.asReversed().firstOrNull { + original = if (corner != 0) current else visibleElements.asReversed().firstOrNull { downX / width in it.x..(it.x + it.width) && downY / height in it.y..(it.y + it.height) } selected = original?.id; onSelect(selected) @@ -81,7 +101,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { MotionEvent.ACTION_MOVE -> { val e = original ?: return true if (!dragging && abs(event.x - downX) + abs(event.y - downY) > ViewConfiguration.get(context).scaledTouchSlop) { - dragging = true; onBeginEdit() + dragging = true; onBeginEdit(visibleElements, width, height) } if (!dragging) return true val dx = (event.x - downX) / width; val dy = (event.y - downY) / height @@ -93,7 +113,7 @@ internal class InputSurfaceEditorView(context: Context) : FrameLayout(context) { val bottom = if (corner and 8 != 0) (e.y + e.height + dy).coerceIn(top + .03f, 1f) else e.y + e.height e.copy(x = left, y = top, width = right - left, height = bottom - top).bounded() } - val aligned = if (snap) snapSurfaceElement(next, elements.filter { it.id != e.id }, 9 * resources.displayMetrics.density / width, + val aligned = if (snap) snapSurfaceElement(next, visibleElements.filter { it.id != e.id }, 9 * resources.displayMetrics.density / width, 9 * resources.displayMetrics.density / height, corner) else null if (aligned != null && (aligned.x != null && aligned.x != guideX || aligned.y != null && aligned.y != guideY)) performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK) guideX = aligned?.x; guideY = aligned?.y diff --git a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt index f121a9a73a..0058224c01 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/InputSurfaceView.kt @@ -48,7 +48,7 @@ class InputSurfaceView( context: Context, private val pad: PadBridge? = null, private var customLayout: List = emptyList(), - private val inputRole: InputRole = InputRole.SECONDARY, + val inputRole: InputRole = InputRole.SECONDARY, private var surfaceStyle: InputSurfaceStyle = InputSurfaceStyle(), private val haptics: Boolean = inputRole != InputRole.PRIMARY, ) : FrameLayout(context) { @@ -59,6 +59,7 @@ class InputSurfaceView( private var requestedLayout = customLayout init { customLayout = surfaceStyle.shown(customLayout); addView(content, LayoutParams(-1, -1)); renderCustom(pad) } + val shownElements: List get() = customLayout var onTouchMiss: ((MotionEvent) -> Unit)? = null private var forwardedPointers = 0 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LibraryAccounts.kt b/app/src/main/java/com/droiddeck/launcher/ui/LibraryAccounts.kt new file mode 100644 index 0000000000..2b10c7902e --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/LibraryAccounts.kt @@ -0,0 +1,171 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.LocalIndication +import androidx.compose.foundation.background +import androidx.compose.foundation.basicMarquee +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.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material3.Icon +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.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.layout.LayoutCoordinates +import androidx.compose.ui.layout.boundsInRoot +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.R +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoresState + +@Composable +internal fun StoreAccountsButton() { + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val placed = remember { arrayOfNulls(1) } + var itchKey by remember { mutableStateOf(false) } + val home = { placed[0]?.takeIf { it.isAttached }?.boundsInRoot() } + if (itchKey) ItchKeyDialog { itchKey = false } + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val label = stringResource(R.string.library_accounts) + val open = { + placed[0]?.takeIf { it.isAttached }?.boundsInRoot()?.let { at -> + Steps.ask(StepAsk( + anchor = at, side = StepSide.Left, accent = pal.signal, items = storesWithSignIn().size + 1, pillCorner = 20.dp, maxWidth = 380.dp, + handle = { Icon(Icons.Filled.Add, null, tint = pal.signal, modifier = Modifier.size(20.dp)) }, + ) { + StoreAccountsStep(onSignIn = { store, row -> + Steps.fold() + when { + store == Store.ITCH -> itchKey = true + row == null || Motion.scale == 0f || StoresMotion.signIn != null -> StoresState.signIn(ctx, store) + else -> { + val accent = storePalette(pal, store).signal + StoresMotion.signIn = SignInFlood(store, row, accent, sourceColours(store.id).dot, home = home()) + } + } + }) + }) + } + Unit + } + Box(Modifier.onGloballyPositioned { placed[0] = it }) { + Box( + contentAlignment = Alignment.Center, + modifier = Modifier.paneItem("libchip:accounts").testTag("library-accounts").size(40.dp).clip(CircleShape) + .background(colors.surface) + .glideBorder(hot, CircleShape, pal.signal, pal.line) + .hoverable(src) + .clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClickLabel = label, onClick = open) + .controllerConfirm(onClick = open), + ) { Icon(Icons.Filled.Add, label, tint = if (hot) colors.onBackground else colors.onSurfaceVariant, modifier = Modifier.size(20.dp)) } + } +} + +private fun storesWithSignIn(): List = Store.entries.filter { StoresState.backend(it) != null } + +@Composable +private fun StepOutScope.StoreAccountsStep(onSignIn: (Store, androidx.compose.ui.geometry.Rect?) -> Unit) { + val ctx = LocalContext.current + val colors = MaterialTheme.colorScheme + var leaving by remember { mutableStateOf(null) } + LaunchedEffect(leaving) { if (leaving != null) focusSoon { first } } + val out = leaving + if (out == null) { + StepTitle(stringResource(R.string.library_accounts)) + Column(Modifier.fillMaxWidth().heightIn(max = (maxHeight - 72.dp).coerceAtLeast(120.dp)).verticalScroll(rememberScrollState())) { + storesWithSignIn().forEachIndexed { i, store -> + val name = StoresState.accounts[store] + val at = remember { arrayOfNulls(1) } + StoreTheme(store) { + AccountRow( + store, name, + modifier = Modifier.stepItem(1 + i).then(if (i == 0) Modifier.focusRequester(first) else Modifier) + .onGloballyPositioned { at[0] = it }, + enabled = open, + ) { if (name != null) leaving = store else onSignIn(store, at[0]?.takeIf { it.isAttached }?.boundsInRoot()) } + } + } + } + } else { + StepTitle(stringResource(R.string.stores_signout_title, out.label)) + Text(stringResource(R.string.stores_signout_note), fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.stepItem(1).padding(start = 4.dp, bottom = 12.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), modifier = Modifier.fillMaxWidth().stepItem(2)) { + StepChoice(stringResource(R.string.stores_signout_stay), enabled = open, modifier = Modifier.focusRequester(first)) { leaving = null } + StepChoice(stringResource(R.string.stores_signout_go), danger = true, enabled = open) { + Steps.fold() + StoresState.signOut(ctx, out) + } + } + } +} + +@OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) +@Composable +private fun AccountRow(store: Store, account: String?, modifier: Modifier, enabled: Boolean, onClick: () -> Unit) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = rememberHot(src) + val shape = RoundedCornerShape(20.dp) + val signedIn = account != null + val accent = pal.signal + Row( + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), + modifier = modifier.fillMaxWidth().heightIn(min = 44.dp).clip(shape) + .background(if (hot) accent.copy(alpha = 0.16f) else Color.Transparent) + .glideBorder(hot, shape, accent, Color.Transparent) + .hoverable(src) + .clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, role = Role.Button, onClick = onClick) + .controllerConfirm(enabled = enabled, onClick = onClick) + .testTag("account-${store.id}") + .padding(horizontal = 16.dp), + ) { + Box(Modifier.size(10.dp).background(sourceColours(store.id).dot.copy(alpha = if (signedIn) 1f else 0.45f), CircleShape)) + Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) { + Text(store.label, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, softWrap = false) + if (account != null) Text( + account, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, softWrap = false, + modifier = Modifier.weight(1f, fill = false).basicMarquee(iterations = Int.MAX_VALUE, initialDelayMillis = 1_200), + ) + } + Text( + stringResource(if (signedIn) R.string.library_account_sign_out else R.string.library_account_sign_in), + fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = if (signedIn) (if (hot) colors.error else colors.onSurfaceVariant) else if (hot) accent else colors.onBackground, maxLines = 1, + ) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LibraryFavorites.kt b/app/src/main/java/com/droiddeck/launcher/ui/LibraryFavorites.kt index 2aab3b4b9f..2756bc2812 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LibraryFavorites.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LibraryFavorites.kt @@ -28,8 +28,12 @@ internal object LibraryFavorites { internal fun toggled(keys: Set, key: String): Set = if (key in keys) keys - key else keys + key -internal fun inLibrarySource(source: String, entry: LibraryEntry, favorites: Set): Boolean = when (source) { - LIBRARY_ALL -> true - LIBRARY_FAVORITES -> entry.favoriteKey in favorites - else -> entry.source == source +internal fun inLibrarySource(source: String, entry: LibraryEntry, favorites: Set, hidden: (LibraryEntry) -> Boolean = { false }): Boolean { + val concealed = hidden(entry) + return when (source) { + LIBRARY_HIDDEN -> concealed + LIBRARY_ALL -> !concealed + LIBRARY_FAVORITES -> !concealed && entry.favoriteKey in favorites + else -> !concealed && entry.source == source + } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LibraryHidden.kt b/app/src/main/java/com/droiddeck/launcher/ui/LibraryHidden.kt new file mode 100644 index 0000000000..a0fb74ef6f --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/LibraryHidden.kt @@ -0,0 +1,78 @@ +package com.droiddeck.launcher.ui + +import android.content.Context +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.remember +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalLifecycleOwner +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.setValue +import com.droiddeck.launcher.frontend.AddedGames +import com.droiddeck.launcher.frontend.Library +import com.droiddeck.launcher.frontend.SteamHidden +import com.droiddeck.launcher.session.SessionPrefs + +internal const val LIBRARY_HIDDEN = "hidden" + +internal object LibraryHidden { + var keys by mutableStateOf>(emptySet()) + private set + var account by mutableStateOf(null) + private set + var steam by mutableStateOf>(emptySet()) + private set + + fun load(context: Context) { + keys = SessionPrefs.libraryHidden(context) + refreshSteam(context) + } + + fun refreshSteam(context: Context) { + val root = SessionPrefs.activeSteamRoot(context) + adopt(root) + SteamHidden.readOrNull(root)?.let { steam = it } + } + + private fun adopt(root: java.io.File) { + val resolved = AddedGames.accountConfig(root) + if (resolved != account) { + account = resolved + steam = emptySet() + } + } + + fun steamId(game: Library.SteamGame?): Long? = game?.takeIf { Library.fromSteamClient(it) }?.appId?.toLong() + + fun isHidden(key: String, game: Library.SteamGame?): Boolean = key in keys || steamId(game)?.let { it in steam } == true + + fun isHidden(entry: LibraryEntry): Boolean = isHidden(entry.favoriteKey, entry.game) + + fun set(context: Context, key: String, game: Library.SteamGame?, hidden: Boolean): Boolean { + val id = steamId(game) + val root = SessionPrefs.activeSteamRoot(context) + val written = id?.let { SteamHidden.write(root, it, hidden) } + if (id != null) { + adopt(root) + steam = written?.hidden ?: SteamHidden.readOrNull(root) ?: steam + } + keys = if (hidden && (id == null || written == null)) keys + key else keys - key + SessionPrefs.setLibraryHidden(context, keys) + return id == null || written?.queued == true + } +} + +@Composable +internal fun rememberHiddenSync() { + val ctx = LocalContext.current + remember { LibraryHidden.load(ctx) } + val lifecycle = LocalLifecycleOwner.current.lifecycle + DisposableEffect(lifecycle) { + val observer = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_RESUME) LibraryHidden.refreshSteam(ctx) } + lifecycle.addObserver(observer) + onDispose { lifecycle.removeObserver(observer) } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt index d4210f326b..272f42840c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LibraryPage.kt @@ -163,11 +163,17 @@ internal fun collectionEntries(all: List, items: List internal fun installedFirst(entries: List): List = entries.partition { it.installed }.let { (on, off) -> on + off } internal const val LIBRARY_ALL = "all" -internal fun librarySources(entries: List, order: List, always: Set = emptySet(), favorites: Set = emptySet()): List = - (listOf(LIBRARY_FAVORITES, Library.SOURCE_STEAM) + arrangeStoreTabs(order, emptySet()).map { it.store.id } + Library.ADDED + Library.SOURCE_COLLECTION) +internal fun librarySources( + entries: List, order: List, always: Set = emptySet(), favorites: Set = emptySet(), + hidden: (LibraryEntry) -> Boolean = { false }, showHidden: Boolean = false, +): List = + (listOf(LIBRARY_FAVORITES, Library.SOURCE_STEAM) + arrangeStoreTabs(order, emptySet()).map { it.store.id } + Library.ADDED + Library.SOURCE_COLLECTION + LIBRARY_HIDDEN) .filter { source -> - if (source == LIBRARY_FAVORITES) entries.any { it.favoriteKey in favorites } - else source in always || entries.any { it.source == source } + when (source) { + LIBRARY_HIDDEN -> showHidden + LIBRARY_FAVORITES -> entries.any { it.favoriteKey in favorites && !hidden(it) } + else -> source in always || entries.any { it.source == source && !hidden(it) } + } } internal object LibraryDisplay { @@ -178,11 +184,14 @@ internal object LibraryDisplay { private set var size by mutableStateOf(true) private set + var hidden by mutableStateOf(false) + private set fun load(context: android.content.Context) { level = SessionPrefs.libraryCardLevel(context).coerceIn(0, scales.lastIndex) title = SessionPrefs.libraryShowTitle(context) size = SessionPrefs.libraryShowSize(context) + hidden = SessionPrefs.libraryShowHidden(context) } fun step(context: android.content.Context, by: Int) { @@ -199,6 +208,11 @@ internal object LibraryDisplay { size = !size SessionPrefs.setLibraryShowSize(context, size) } + + fun toggleHidden(context: android.content.Context) { + hidden = !hidden + SessionPrefs.setLibraryShowHidden(context, hidden) + } } internal object LibraryView { @@ -226,10 +240,13 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current LaunchedEffect(Unit) { StoresState.refresh(ctx) } remember { LibraryDisplay.load(ctx) } + remember { FolderSizes.load(ctx) } remember { LibraryFavorites.load(ctx) } + rememberHiddenSync() val soundMode = selected == "soundtracks" || selected.startsWith("sound:") val favorites = if (soundMode) emptySet() else LibraryFavorites.keys - val stores = s.gameStoresEnabled && !s.shortcutPicker && !soundMode + val concealed: (LibraryEntry) -> Boolean = { !soundMode && LibraryHidden.isHidden(it) } + val stores = !s.shortcutPicker && !soundMode val signedIn = Store.entries.filter { StoresState.isSignedIn(it) } LaunchedEffect(stores, signedIn) { if (stores) signedIn.forEach { StoresState.loadLibrary(ctx, it) } } val owned = if (stores) signedIn.associateWith { StoresState.library[it].orEmpty() } else emptyMap() @@ -241,7 +258,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, val favoritesLabel = stringResource(R.string.soundtracks_favorites) val all = remember(soundMode, s.steamGames, s.soundtracks, s.soundtracksEnabled, cloudRows, owned, installedStore, savedSnapshot, favoritesLabel) { if (soundMode) s.soundtracks.map { LibraryEntry("sound:${it.appId}", it.source, it.name, it, null, true) } + - (if (s.soundtracks.isEmpty() && savedSnapshot.favorites.isEmpty() && savedSnapshot.collections.isEmpty()) emptyList() else SoundtrackCollections.games(ctx, favoritesLabel)) + (if (s.soundtracks.isEmpty() && savedSnapshot.favorites.isEmpty() && savedSnapshot.collections.isEmpty()) emptyList() else SoundtrackCollections.games(ctx, favoritesLabel, skipEmptyFavorites = true)) .map { LibraryEntry("sound:${it.appId}", it.source, it.name, it, null, true) } else libraryEntries(s.steamGames + cloudRows + if (s.soundtracksEnabled) emptyList() else s.soundtracks.filter { it.library != Library.ADDED }, owned, installedStore) } @@ -265,8 +282,8 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, val gameJoltSignedIn = owned.containsKey(Store.GAMEJOLT) val sources = librarySources( all, SessionPrefs.storesTabOrder(ctx), - listOfNotNull(Store.ITCH.id.takeIf { itchSignedIn && !soundMode }, Store.GAMEJOLT.id.takeIf { gameJoltSignedIn && !soundMode }, Library.SOURCE_COLLECTION.takeIf { soundMode }).toSet(), - favorites, + listOfNotNull(Store.ITCH.id.takeIf { itchSignedIn && !soundMode }, Store.GAMEJOLT.id.takeIf { gameJoltSignedIn && !soundMode }).toSet(), + favorites, concealed, LibraryDisplay.hidden && !soundMode, ) val source = LibraryView.source.takeIf { it == LIBRARY_ALL || it in sources } ?: LIBRARY_ALL val q = LibraryView.query.trim().lowercase() @@ -289,7 +306,7 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, val collectionItems = collectionId?.let { if (source == Store.GAMEJOLT.id) GameJoltCollections.gamesOf(it) else ItchCollections.gamesOf(it) } val pool = if (collectionId == null) all else collectionEntries(all, collectionItems.orEmpty(), Store.byId(source) ?: Store.ITCH) val matching = pool.filter { - inLibrarySource(source, it, favorites) && (q.isEmpty() || it.title.lowercase().contains(q)) && keepsXbox(xboxFilter, it) + inLibrarySource(source, it, favorites, concealed) && (q.isEmpty() || it.title.lowercase().contains(q)) && keepsXbox(xboxFilter, it) } val listUninstalled = if (collectionId == null) showUninstalled else collectionShows?.takeIf { it.first == collectionId }?.second ?: true val trackHits by produceState>(emptyList(), soundMode, q, source, s.soundtracks) { @@ -316,8 +333,8 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, } } var savedDialog by remember { mutableStateOf(false) } - val candidates = if (listUninstalled) matching else matching.filter { it.installed } - val hiddenUninstalled = if (listUninstalled) 0 else matching.count { !it.installed } + val candidates = if (listUninstalled || source == LIBRARY_HIDDEN) matching else matching.filter { it.installed } + val hiddenUninstalled = if (listUninstalled || source == LIBRARY_HIDDEN) 0 else matching.count { !it.installed } val sort = s.storesSort val sizeSort = sort == "sizeAsc" || sort == "sizeDesc" val installedAt = StoresState.installed.associate { it.key to it.sidecar.installedAt } @@ -345,7 +362,13 @@ internal fun LibraryPage(s: FrontEndState, a: FrontEndActions, selected: String, } var sizesWaited by remember(sizeSort) { mutableStateOf(false) } LaunchedEffect(sizeSort) { if (sizeSort) { kotlinx.coroutines.delay(8_000); sizesWaited = true } } - val sizesPending = sizeSort && !sizesWaited && candidates.any { sizeOf(it) == null } + fun sizeComing(e: LibraryEntry): Boolean = when { + e.storeKey != null && e.storeKey in installedStore -> true + e.game?.gameFiles != null -> true + e.item != null -> StoreSizes.coming(e.item) + else -> false + } + val sizesPending = sizeSort && !sizesWaited && candidates.any { sizeOf(it) == null && sizeComing(it) } val sorted = sortGames( candidates, sort, title = { it.title }, releaseDate = { it.item?.releaseDate.orEmpty() }, lastPlayed = { e -> entryTime(e.game?.lastPlayed, e.storeKey?.let { lastPlayed[it] }) }, @@ -467,7 +490,10 @@ private fun LibraryEmpty(s: FrontEndState, a: FrontEndActions, modifier: Modifie Rise(0) { PageHeader(stringResource(R.string.rail_games)) { if (s.steamGamesX64) ClientTag() - if (!s.shortcutPicker) AddGameButton { GamesDialogState.adding = true } + if (!s.shortcutPicker) { + AddGameButton { GamesDialogState.adding = true } + StoreAccountsButton() + } } } Rise(1) { Note(stringResource(if (s.shortcutPicker && s.shortcutLibraryScanning) R.string.game_shortcut_scanning else R.string.games_empty)) } @@ -476,7 +502,7 @@ private fun LibraryEmpty(s: FrontEndState, a: FrontEndActions, modifier: Modifie PrimaryButton(stringResource(R.string.games_play_steam), enabled = !s.busy, main = true, icon = Icons.Filled.PlayArrow, modifier = Modifier.padding(top = 12.dp).testTag("play-steam"), onClick = a.onPlay) } } - Box(Modifier.padding(top = 12.dp)) { GameFileFolderActions(s, a) } + Box(Modifier.padding(top = 12.dp)) { GameFileFolderActions(s, a, labeled = true) } } } @@ -529,7 +555,7 @@ private fun LibraryGrid( } val picker = s.shortcutPicker && e.game != null val choose = if (picker) ({ a.onSteamGame(e.game!!) }) else null - if (listMode) LibraryRow(e, first, navigation, choose, onOpen) else LibraryTile(e, capsules, first, navigation, choose, onOpen, showSource = source == LIBRARY_ALL || source == LIBRARY_FAVORITES) + if (listMode) LibraryRow(e, first, navigation, choose, onOpen) else LibraryTile(e, capsules, first, navigation, choose, onOpen, showSource = source == LIBRARY_ALL || source == LIBRARY_FAVORITES || source == LIBRARY_HIDDEN) } LazyVerticalGrid( columns = if (listMode) GridCells.Fixed(1) else GridCells.Adaptive(tileWidth), state = grid, @@ -545,7 +571,7 @@ private fun LibraryGrid( Rise(0) { LibraryHeader(s, a, total, searchCleared, source == Store.XBOX.id, showUninstalled, onShowUninstalled, collections = Store.byId(source)?.takeIf { it == Store.ITCH || it == Store.GAMEJOLT }, soundMode = soundMode, onAddSoundtrack = onAddSoundtrack, onCollections = onCollections) } } item(key = "filters", span = { GridItemSpan(maxLineSpan) }) { - Rise(1) { LibraryFilters(sources, source, onSource) } + Rise(1) { LibraryFilters(sources, source, onSource, accounts = !soundMode && !s.shortcutPicker) } } for ((store, line) in syncing) item(key = "sync-${store.id}", span = { GridItemSpan(maxLineSpan) }) { Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.fillMaxWidth()) { @@ -655,7 +681,7 @@ private fun LibraryHeader( } }, ) { - if (soundMode) HeaderIconButton(stringResource(R.string.soundtracks_saved), Icons.Filled.BookmarkBorder, "collections", onCollections) + if (soundMode) HeaderIconButton(stringResource(R.string.soundtracks_saved), Icons.Filled.BookmarkBorder, "collections", onClick = onCollections) DisplayButton() if (!soundMode && (showUninstalled != null || xbox)) LibraryFilterButton(showUninstalled, onShowUninstalled, xbox) if (collections != null) CollectionsButton(collections) @@ -668,18 +694,20 @@ private fun LibraryHeader( } @Composable -private fun LibraryFilters(sources: List, source: String, onSource: (String) -> Unit) { - if (sources.size < 2) return +private fun LibraryFilters(sources: List, source: String, onSource: (String) -> Unit, accounts: Boolean) { + val chips = sources.size >= 2 || sources.singleOrNull() == LIBRARY_HIDDEN + if (!chips && !accounts) return Row( horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(top = 4.dp, bottom = 2.dp).horizontalScroll(rememberScrollState()), ) { - SourceFilterChip(LIBRARY_ALL, stringResource(R.string.stores_tab_all), source == LIBRARY_ALL, dot = null) { onSource(LIBRARY_ALL) } - for (src in sources) { + if (chips) SourceFilterChip(LIBRARY_ALL, stringResource(R.string.stores_tab_all), source == LIBRARY_ALL, dot = null) { onSource(LIBRARY_ALL) } + if (chips) for (src in sources) { val store = Store.byId(src) val dot = when { store != null -> sourceColours(src).dot.copy(alpha = if (StoresState.isSignedIn(store) && StoresState.expired[store] != true) 1f else 0.35f) src == LIBRARY_FAVORITES -> FavoritesColours.dot + src == LIBRARY_HIDDEN -> Color(0xFF9AA0A6) src == Library.SOURCE_STEAM || src == Library.ADDED || src == Library.SOURCE_COLLECTION -> sourceColours(src).dot else -> null } @@ -688,11 +716,13 @@ private fun LibraryFilters(sources: List, source: String, onSource: (Str when (src) { Library.ADDED -> stringResource(R.string.library_filter_added) LIBRARY_FAVORITES -> stringResource(R.string.soundtracks_favorites) + LIBRARY_HIDDEN -> stringResource(R.string.apps_filter_hidden) else -> store?.shortLabel ?: sourceLabel(src) }, source == src, dot, ) { onSource(src) } } + if (accounts) StoreAccountsButton() } } @@ -739,7 +769,9 @@ private fun LibraryTile(e: LibraryEntry, capsule: Boolean, first: Boolean, navig RequestSize(e) val open = { val art = if (capsule) tall else wide - placed[0]?.takeIf { it.isAttached }?.let { StoresMotion.markCard(CardMark(e.key, it.boundsInRoot(), corner, (art as? java.io.File)?.path ?: art as? String)) } + placed[0]?.takeIf { it.isAttached }?.let { + StoresMotion.markCard(CardMark(e.key, it.boundsInRoot(), corner, (art as? java.io.File)?.path ?: art as? String, (wide as? java.io.File)?.path ?: wide as? String)) + } onOpen(e.key) } Column( @@ -802,7 +834,9 @@ internal fun ArtCard( }, ) badge?.invoke(this) - if (chip != null) Box(Modifier.align(Alignment.TopEnd).padding(6.dp)) { StateChip(chip, ChipTone.BUSY, small = true) } + if (chip != null) Box(Modifier.align(Alignment.TopEnd).padding(6.dp)) { + StateChip(chip, ChipTone.BUSY, small = true, fraction = download?.stageFraction?.takeIf { it >= 0f }, key = download?.stage) + } val showName = LibraryDisplay.title || hot val showDetail = LibraryDisplay.size || hot if (showName || showDetail) Column( @@ -914,14 +948,14 @@ private fun LibraryRow(e: LibraryEntry, first: Boolean, navigation: Modifier, ch } @Composable -internal fun HeaderIconButton(description: String, icon: androidx.compose.ui.graphics.vector.ImageVector, key: String, onClick: () -> Unit) { +internal fun HeaderIconButton(description: String, icon: androidx.compose.ui.graphics.vector.ImageVector, key: String, modifier: Modifier = Modifier, onClick: () -> Unit) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val src = remember { MutableInteractionSource() } val hot = rememberHot(src) Box( contentAlignment = Alignment.Center, - modifier = Modifier.paneItem("btn:$key").size(32.dp).clip(CircleShape).background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent) + modifier = modifier.paneItem("btn:$key").size(32.dp).clip(CircleShape).background(if (hot) pal.signal.copy(alpha = 0.14f) else Color.Transparent) .glideBorder(hot, CircleShape, pal.signal) .hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, role = Role.Button, onClick = onClick) .controllerConfirm(onClick = onClick) @@ -1045,7 +1079,7 @@ internal fun DisplayButton() { HeaderIconButton(title, Icons.Filled.Visibility, "display") { val from = at ?: return@HeaderIconButton Steps.ask(StepAsk( - anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = 4, + anchor = from, side = StepSide.Left, accent = pal.signal, pillCorner = 8.dp, items = 5, handle = { Icon(Icons.Filled.Visibility, null, tint = pal.signal, modifier = Modifier.size(18.dp)) }, ) { StepTitle(title) @@ -1068,6 +1102,10 @@ internal fun DisplayButton() { stringResource(R.string.library_display_size), selected = LibraryDisplay.size, enabled = open, modifier = Modifier.fillMaxWidth().stepItem(3), ) { LibraryDisplay.toggleSize(ctx) } + StepChoice( + stringResource(R.string.apps_filter_hidden), selected = LibraryDisplay.hidden, enabled = open, + modifier = Modifier.fillMaxWidth().stepItem(4), + ) { LibraryDisplay.toggleHidden(ctx) } } }) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt index 3b89f47d2e..88b32cf5de 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/LiftSheet.kt @@ -322,7 +322,7 @@ internal fun LiftHero( val touchOnly = inputMode.inputMode == InputMode.Touch val lipFocus = remember { FocusRequester() } - val settingsLabel = stringResource(R.string.drawer_page_settings) + val settingsLabel = stringResource(R.string.sheet_lip) var lipFocused by remember { mutableStateOf(false) } val lipWanted = !open && (!shown || lipBack) && (playFocused || playHovered || touchOnly || lipFocused) && drop?.let { it.open || it.shown } != true LaunchedEffect(lipWanted) { @@ -666,7 +666,7 @@ internal fun Handle(height: Dp, above: Boolean = false) { .drawBorderSidesAndFoot(pal.line, 12.dp, flip = above) .padding(start = 14.dp, end = 10.dp), ) { - Text(stringResource(R.string.drawer_page_settings), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant, maxLines = 1) + Text(stringResource(R.string.sheet_lip), fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant, maxLines = 1) Icon( if (above) Icons.Filled.KeyboardArrowDown else Icons.Filled.KeyboardArrowUp, null, tint = colors.onSurfaceVariant, modifier = Modifier.size(16.dp).graphicsLayer { translationY = if (still) 0f else (if (above) 3.dp else -3.dp).toPx() * lift }, 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 21520b3860..1cc0393388 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -213,6 +213,14 @@ class SheetExtras( fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: SheetExtras = SheetExtras()) { val steam = s.mode == SessionService.MODE_STEAM val host = rememberMenuHost() + Text( + stringResource(when (s.mode) { + SessionService.MODE_STEAM -> R.string.sheet_scope_steam + SessionService.MODE_DESKTOP -> R.string.sheet_scope_desktop + else -> R.string.sheet_scope_other + }), + fontSize = 12.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(start = 4.dp, top = 2.dp, bottom = 4.dp), + ) if (tab == SheetTab.DISPLAY) { val context = LocalContext.current val portraitWindow = SessionPrefs.portrait(context) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/MorePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/MorePage.kt index b4d6952413..a2dad0a54c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/MorePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/MorePage.kt @@ -28,6 +28,7 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.platform.testTag +import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.text.font.FontWeight @@ -43,10 +44,9 @@ internal fun MorePage(s: FrontEndState, a: FrontEndActions, onSelect: (String) - Column(modifier.verticalScroll(rememberScrollState())) { PageHeader(stringResource(R.string.rail_more)) { Spacer(Modifier.weight(1f)) - SecondaryButton(stringResource(R.string.more_edit_tabs), compact = true) { - SetupTabs.openLauncher = true - SetupTabs.focusTabs = true - onSelect("setup") + SecondaryButton(stringResource(R.string.more_edit_tabs), compact = true, + modifier = Modifier.focusRequester(MoreTabs.button).testTag("more-edit-tabs")) { + MoreTabs.editing = true } } BoxWithConstraints(Modifier.fillMaxWidth()) { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt b/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt index 17f1478201..f7f4319d29 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/NavTabs.kt @@ -5,15 +5,33 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import com.droiddeck.launcher.agent.AgentHost -import com.droiddeck.launcher.agent.AgentTab import com.droiddeck.launcher.session.SessionPrefs internal enum class TabPlace { BAR, MORE, HIDDEN } +internal object DeveloperTools { + var on by mutableStateOf(false) + private set + + fun load(context: Context) { + on = SessionPrefs.developerTools(context) + } + + fun set(context: Context, enabled: Boolean) { + on = enabled + SessionPrefs.setDeveloperTools(context, enabled) + } +} + internal object NavTabs { const val MORE = "more" - val FEATURES = setOf("stores", "soundtracks", "agent") - val ALL = listOf("steam", "games", "soundtracks", "stores", "desktop", "agent", "components", "android-apps", "setup", "updates") + val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "android-apps", "agent") + val DEFAULT_SHELVED = setOf("stores", "soundtracks", "components", "storage", "sync", "android-apps", "agent") + val DEFAULT_HIDDEN = setOf("android-apps", "agent") + private val SHELVED_WHEN_NEW = setOf("storage", "sync", "android-apps", "agent") + private val OLD_ORDER = listOf("steam", "games", "soundtracks", "stores", "downloads", "desktop", "agent", "components", "android-apps", "storage", "sync", "setup", "updates") + private val OLD_SHELVED = setOf("soundtracks", "agent", "storage", "sync") + private const val LAYOUT_VERSION = 2 var order by mutableStateOf(ALL) private set @@ -23,9 +41,41 @@ internal object NavTabs { private set fun load(context: Context) { - order = arrange(SessionPrefs.navTabOrder(context)) - shelved = SessionPrefs.navTabShelved(context).intersect(ALL.toSet()) - hidden = SessionPrefs.navTabHidden(context).intersect(ALL.toSet()) - FEATURES - "setup" + migrate(context) + val saved = SessionPrefs.navTabOrder(context) + order = arrange(saved) + shelved = (SessionPrefs.navTabShelved(context) ?: DEFAULT_SHELVED).intersect(ALL.toSet()) + + if (saved.isEmpty()) emptySet() else SHELVED_WHEN_NEW - saved.toSet() + hidden = (SessionPrefs.navTabHidden(context) ?: DEFAULT_HIDDEN).intersect(ALL.toSet()) - "setup" + } + + fun reset(context: Context) { + order = ALL + shelved = DEFAULT_SHELVED + hidden = DEFAULT_HIDDEN + SessionPrefs.setNavTabOrder(context, order) + SessionPrefs.setNavTabShelved(context, shelved) + SessionPrefs.setNavTabHidden(context, hidden) + } + + fun isDefault(): Boolean = order == ALL && shelved == DEFAULT_SHELVED && hidden == DEFAULT_HIDDEN + + // Before layout 2, switches for game stores, soundtracks and the agent tab, and the home-screen requirement for Apps, + // decided which tabs existed. A layout someone had already touched keeps showing what it showed then. + private fun migrate(context: Context) { + if (SessionPrefs.navTabLayoutVersion(context) >= LAYOUT_VERSION) return + val legacy = SessionPrefs.legacyTabSwitches(context) + if (legacy.touched) { + if (SessionPrefs.navTabOrder(context).isEmpty()) SessionPrefs.setNavTabOrder(context, OLD_ORDER) + if (SessionPrefs.navTabShelved(context) == null) SessionPrefs.setNavTabShelved(context, OLD_SHELVED) + val hide = (SessionPrefs.navTabHidden(context) ?: emptySet()).toMutableSet() + if (!legacy.stores) hide += setOf("stores", "downloads") + if (!legacy.soundtracks) hide += "soundtracks" + if (!legacy.agent) hide += "agent" + if (!com.droiddeck.launcher.HomeApp.isHomeScreenEnabled(context) || !com.droiddeck.launcher.HomeApp.isDefault(context)) hide += "android-apps" + SessionPrefs.setNavTabHidden(context, hide) + } + SessionPrefs.finishTabSwitchMigration(context, LAYOUT_VERSION) } fun arrange(saved: List): List { @@ -40,7 +90,6 @@ internal object NavTabs { } fun available(s: FrontEndState, key: String): Boolean = when (key) { - "android-apps" -> s.isHomeApp "agent" -> AgentHost.available else -> true } @@ -48,18 +97,11 @@ internal object NavTabs { fun hideable(key: String) = key != "setup" fun place(s: FrontEndState, key: String): TabPlace = when { - featureOff(s, key) || key in hidden -> TabPlace.HIDDEN + key in hidden -> TabPlace.HIDDEN key in shelved -> TabPlace.MORE else -> TabPlace.BAR } - private fun featureOff(s: FrontEndState, key: String) = when (key) { - "stores" -> !s.gameStoresEnabled - "soundtracks" -> !s.soundtracksEnabled - "agent" -> !AgentTab.shown - else -> false - } - fun listed(s: FrontEndState) = order.filter { available(s, it) } fun more(s: FrontEndState) = listed(s).filter { place(s, it) == TabPlace.MORE } @@ -70,7 +112,7 @@ internal object NavTabs { } fun setHidden(context: Context, key: String, hide: Boolean) { - hidden = if (hide && hideable(key) && key !in FEATURES) hidden + key else hidden - key + hidden = if (hide && hideable(key)) hidden + key else hidden - key SessionPrefs.setNavTabHidden(context, hidden) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PageFlood.kt b/app/src/main/java/com/droiddeck/launcher/ui/PageFlood.kt index e0e95343d7..12834b1edf 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PageFlood.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PageFlood.kt @@ -1,5 +1,6 @@ package com.droiddeck.launcher.ui +import androidx.compose.ui.graphics.drawscope.withTransform import android.os.SystemClock import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.spring @@ -84,6 +85,8 @@ internal fun PageFlood( sinks: Boolean = false, onto: (() -> Rect?)? = null, ontoCorner: androidx.compose.ui.unit.Dp = 0.dp, + ontoLook: HeroLook? = null, + ontoArt: Painter? = null, content: @Composable () -> Unit, ) { val pal = LocalPalette.current @@ -108,12 +111,16 @@ internal fun PageFlood( kotlinx.coroutines.withTimeoutOrNull(300) { snapshotFlow { get() }.first { it != null } } }?.translate(-at)?.takeIf { it.height > 1f && it.overlaps(Rect(Offset.Zero, size)) } if (target != null) { + // A tile with no picture yet would cover the card with a blank box, so wait briefly for the art. + if (!leaving) kotlinx.coroutines.withTimeoutOrNull(250) { + snapshotFlow { art.ready() && (ontoArt == null || ontoArt.ready()) }.first { it } + } coroutineScope { if (!leaving) { val runs = edges.map { launch { it.animateTo(1f, Motion.sp(0.85f, 320f)) } } - snapshotFlow { edges.all { it.value >= 0.9f } }.first { it } - launch { shown.animateTo(1f, Motion.tw(240)) } - launch { delay(Motion.ms(140).toLong()); tile.animateTo(0f, Motion.tw(220)) } + snapshotFlow { edges.all { it.value >= 0.985f } }.first { it } + launch { shown.animateTo(1f, Motion.tw(220)) } + launch { delay(Motion.ms(120).toLong()); tile.animateTo(0f, Motion.tw(200)) } runs.forEach { it.join() } } else { launch { shown.animateTo(0f, Motion.tw(160)) } @@ -164,15 +171,16 @@ internal fun PageFlood( val rise = if (onto != null) 0f else 1f Box(Modifier.fillMaxSize().graphicsLayer { alpha = shown.value; translationY = (1f - shown.value) * 14.dp.toPx() * rise }) { content() } val onCorner = with(density) { ontoCorner.toPx() } - Canvas(Modifier.fillMaxSize()) { - if (tile.value > 0.01f) drawTile(from, edges.map { it.value }, pal.surface, pal.line2, tile.value, art, target, onCorner) + Canvas(Modifier.fillMaxSize().graphicsLayer { compositingStrategy = androidx.compose.ui.graphics.CompositingStrategy.Offscreen }) { + val live = target?.let { landed -> onto?.invoke()?.translate(-at)?.takeIf { it.height > 1f } ?: landed } + if (tile.value > 0.01f && (live == null || art.ready())) drawTile(from, edges.map { it.value }, pal.surface, pal.line2, tile.value, art, live, onCorner, ontoLook, ontoArt) } } } private fun DrawScope.drawTile( from: Origin, v: List, fill: Color, line: Color, alpha: Float, art: Painter? = null, - to: Rect? = null, toCorner: Float = 0f, + to: Rect? = null, toCorner: Float = 0f, look: HeroLook? = null, toArt: Painter? = null, ) { val (l, t, r, b) = v val mean = v.sumOf { it.coerceIn(0f, 1f).toDouble() }.toFloat() / 4f @@ -194,8 +202,12 @@ private fun DrawScope.drawTile( val h = (bottom - top).coerceAtLeast(0f) val corner = if (to != null) lerp(from.corner, toCorner, mean).coerceAtMost(minOf(w, h) / 2f) else lerp(from.corner * (1f - mean), minOf(w, h) * 0.42f, sin(PI * mean).toFloat().coerceAtLeast(0f)) - drawRoundRect(fill, Offset(left, top), Size(w, h), CornerRadius(corner), alpha = alpha) val pic = art?.intrinsicSize?.takeIf { it.isSpecified && it.width > 0f && it.height > 0f } + if (to != null && art != null && pic != null && w > 0f && h > 0f) { + drawHeroTile(art, toArt ?: art, left, top, w, h, corner, mean, alpha, fill, look, StoresMotion.heroDrift() * mean, StoresMotion.heroFadeTop) + return + } + drawRoundRect(fill, Offset(left, top), Size(w, h), CornerRadius(corner), alpha = alpha) if (art != null && pic != null && w > 0f && h > 0f) { val k = maxOf(w / pic.width, h / pic.height) val dw = pic.width * k @@ -207,3 +219,53 @@ private fun DrawScope.drawTile( val edge = (1f - mean * 3f).coerceIn(0f, 1f) if (edge > 0f) drawRoundRect(line, Offset(left, top), Size(w, h), CornerRadius(corner), alpha = alpha * edge, style = Stroke(1.dp.toPx())) } + +// Morphs the card's fitted art into the detail hero as GameBackdrop's ArtLayer draws it: cropped toward the upper right, +// dimmed, faded in from the left and out at the bottom, so the hand-off to the real hero has nothing to jump. +private fun DrawScope.drawHeroTile( + card: Painter, hero: Painter, left: Float, top: Float, w: Float, h: Float, corner: Float, t: Float, alpha: Float, fill: Color, look: HeroLook?, + drift: Float, fadeTop: Boolean, +) { + val shape = Path().apply { addRoundRect(RoundRect(left, top, left + w, top + h, CornerRadius(corner))) } + drawContext.canvas.saveLayer(Rect(left, top, left + w, top + h), androidx.compose.ui.graphics.Paint()) + clipPath(shape) { + drawRect(fill, Offset(left, top), Size(w, h), alpha = alpha * (1f - t)) + val swap = if (hero === card) 1f else if (!hero.ready()) 0f else ((t - 0.15f) / 0.6f).coerceIn(0f, 1f) + if (hero !== card) drawCropped(card, left, top, w, h, 0f, 0f, alpha * (1f - swap)) + withTransform({ + translate(w * HeroDrift.DX * drift, h * HeroDrift.DY * drift) + scale(HeroDrift.zoom(drift), HeroDrift.zoom(drift), Offset(left + w * HeroDrift.PX, top + h * HeroDrift.PY)) + clipRect(left, top, left + w, top + h) + }) { drawCropped(hero, left, top, w, h, lerp(0f, 0.45f, t), lerp(0f, -0.35f, t), alpha * swap) } + if (look != null) { + if (look.dim < 1f) drawRect(Color.Black, Offset(left, top), Size(w, h), alpha = alpha * (1f - look.dim) * t) + translate(left, top) { with(look) { shade(Size(w, h), t * alpha) } } + } + val keep = Color.Black + val gone = Color.Black.copy(alpha = 1f - t) + drawRect( + androidx.compose.ui.graphics.Brush.horizontalGradient(0.08f to gone, 0.55f to keep, startX = left, endX = left + w), + Offset(left, top), Size(w, h), blendMode = androidx.compose.ui.graphics.BlendMode.DstIn, + ) + drawRect( + androidx.compose.ui.graphics.Brush.verticalGradient(0.55f to keep, 1f to gone, startY = top, endY = top + h), + Offset(left, top), Size(w, h), blendMode = androidx.compose.ui.graphics.BlendMode.DstIn, + ) + if (fadeTop && h > 0f) drawRect( + androidx.compose.ui.graphics.Brush.verticalGradient(0f to gone, (24.dp.toPx() / h).coerceAtMost(1f) to keep, startY = top, endY = top + h), + Offset(left, top), Size(w, h), blendMode = androidx.compose.ui.graphics.BlendMode.DstIn, + ) + } + drawContext.canvas.restore() +} + +private fun DrawScope.drawCropped(art: Painter, left: Float, top: Float, w: Float, h: Float, bx: Float, by: Float, alpha: Float) { + if (alpha <= 0.001f) return + val pic = art.intrinsicSize.takeIf { it.isSpecified && it.width > 0f && it.height > 0f } ?: return + val k = maxOf(w / pic.width, h / pic.height) + val dw = pic.width * k + val dh = pic.height * k + translate(left + (w - dw) / 2f * (1f + bx), top + (h - dh) / 2f * (1f + by)) { with(art) { draw(Size(dw, dh), alpha = alpha) } } +} + +private fun Painter?.ready(): Boolean = this == null || intrinsicSize.let { it.isSpecified && it.width > 0f && it.height > 0f } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt index e55590dba3..df22a743f1 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PerformanceDialog.kt @@ -83,15 +83,12 @@ fun PerformancePage( onClientCore: (Int, Boolean) -> Unit, onGameCore: (Int, Boolean) -> Unit, onDismiss: () -> Unit, + embedded: Boolean = false, ) { val host = rememberMenuHost() val colors = MaterialTheme.colorScheme val coreItems = cores.map { it.core to it.label } - SettingsPage( - host, title = stringResource(R.string.perf_title), - lede = stringResource(R.string.perf_lede), - onBack = onDismiss, - ) { + val body: @Composable () -> Unit = { SettingsGroup(stringResource(R.string.perf_client_cores_group)) { ToggleRow( host, "override", stringResource(R.string.perf_override), @@ -252,4 +249,12 @@ fun PerformancePage( } } } + if (embedded) Column { + Text(stringResource(R.string.perf_lede), fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp, vertical = 6.dp)) + body() + } else SettingsPage( + host, title = stringResource(R.string.perf_title), + lede = stringResource(R.string.perf_lede), + onBack = onDismiss, + ) { body() } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt index 60b4223f0a..7f633fcf4f 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/PhantomProcessGatePage.kt @@ -41,6 +41,7 @@ import com.droiddeck.launcher.core.PhantomProcessLimit import com.droiddeck.launcher.core.PhantomProcessStatus import com.droiddeck.launcher.core.WirelessAdbPairingService import com.droiddeck.launcher.core.WirelessAdbPairingService.Stage +import com.droiddeck.launcher.session.QuestExperimental @Composable fun PhantomProcessGatePage( @@ -63,6 +64,7 @@ fun PhantomProcessGatePage( } } val hasToggle = PhantomProcessLimit.hasDeveloperToggle() + val sideQuest = QuestExperimental.isSupported() BoxWithConstraints(Modifier.fillMaxWidth()) { val compact = maxWidth < 620.dp && maxHeight < 500.dp @@ -78,12 +80,13 @@ fun PhantomProcessGatePage( BoxWithConstraints(Modifier.fillMaxWidth()) { val wide = maxWidth >= 620.dp val fix: @Composable ColumnScope.() -> Unit = { - FixGroup(hasToggle, stage, environment, compact, applyingSavedPairing, onOpenDeveloperOptions, onFixWithWirelessDebugging, + if (sideQuest) SideQuestGroup(compact, onCopyCommand) + else FixGroup(hasToggle, stage, environment, compact, applyingSavedPairing, onOpenDeveloperOptions, onFixWithWirelessDebugging, onOpenNotificationSettings, onCancel = { WirelessAdbPairingService.cancel(context) }) } val side: @Composable ColumnScope.() -> Unit = { StatusGroup(status, compact) - OtherWays(hasToggle, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging, onEnterAddressManually, onCopyCommand) + if (!sideQuest) OtherWays(hasToggle, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging, onEnterAddressManually, onCopyCommand) } if (wide) { Row(horizontalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth()) { @@ -246,16 +249,35 @@ private fun OtherWays( Body(stringResource(R.string.gate_manual_hint)) SecondaryButton(stringResource(R.string.gate_enter_manually), compact = true, onClick = onEnterAddressManually) Body(stringResource(R.string.gate_from_computer)) - Text( - PhantomProcessLimit.adbCommand(), - style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace, fontSize = 11.sp), - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) + AdbCommand() SecondaryButton(stringResource(R.string.gate_copy_command), compact = true, onClick = onCopyCommand) } } } +@Composable +private fun SideQuestGroup(compact: Boolean, onCopyCommand: () -> Unit) { + SettingsGroup(stringResource(R.string.gate_sidequest), compact = compact) { + Column( + modifier = Modifier.fillMaxWidth().padding(if (compact) 10.dp else 14.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + Body(stringResource(R.string.gate_sidequest_steps)) + AdbCommand() + PrimaryButton(stringResource(R.string.gate_copy_command), compact = compact, onClick = onCopyCommand) + } + } +} + +@Composable +private fun AdbCommand() { + Text( + PhantomProcessLimit.adbCommand(), + style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace, fontSize = 11.sp), + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) +} + @Composable private fun Body(text: String, modifier: Modifier = Modifier, error: Boolean = false, warn: Boolean = false) { Text( diff --git a/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt b/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt new file mode 100644 index 0000000000..debc0f86b4 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/RailSettingsPages.kt @@ -0,0 +1,166 @@ +package com.droiddeck.launcher.ui + +import androidx.activity.compose.BackHandler +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.slideInHorizontally +import androidx.compose.animation.slideOutHorizontally +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.interaction.MutableInteractionSource +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusProperties +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.foundation.focusGroup +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.boundsInRoot +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.droiddeck.launcher.R + +internal object MoreTabs { + var editing by mutableStateOf(false) + var inside by mutableStateOf(false) + val button = FocusRequester() +} + +@Composable +internal fun StorageTabPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier) { + Column(modifier.verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) { + PageHeader(stringResource(R.string.rail_storage)) + StoragePanel(s, a) + } +} + +@Composable +internal fun SyncTabPage(s: FrontEndState, modifier: Modifier) { + val host = rememberMenuHost() + var advanced by rememberSaveable { mutableStateOf(false) } + if (advanced) { + BackHandler { advanced = false } + Box(modifier) { SyncAdvancedPage(host) { advanced = false } } + return + } + Column(modifier.verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) { + PageHeader(stringResource(R.string.rail_sync)) + SyncPanel(host, s.ready && !s.busy && !s.removalPending) { advanced = true } + } +} + +@Composable +private fun ResetTabsRow() { + val ctx = androidx.compose.ui.platform.LocalContext.current + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val title = stringResource(R.string.tabs_reset_title) + val body = stringResource(R.string.tabs_reset_body) + val keep = stringResource(R.string.common_cancel) + val reset = stringResource(R.string.tabs_reset) + var at by remember { mutableStateOf(null) } + Box(Modifier.padding(top = 12.dp)) { SettingsRow(stringResource(R.string.tabs_reset_title), stringResource(R.string.tabs_reset_hint)) { + Box(Modifier.onGloballyPositioned { at = it.boundsInRoot() }) { + SecondaryButton(reset, modifier = Modifier.testTag("tabs-reset")) { + val from = at ?: run { NavTabs.reset(ctx); return@SecondaryButton } + Steps.ask(StepAsk( + anchor = from, side = StepSide.Left, accent = pal.signal, items = 3, pillCorner = 20.dp, maxWidth = 360.dp, + handle = { androidx.compose.material3.Text(reset, fontSize = 13.sp, color = pal.signal) }, + ) { + StepTitle(title) + androidx.compose.material3.Text(body, fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.stepItem(1).padding(start = 4.dp, bottom = 12.dp)) + androidx.compose.foundation.layout.Row(horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(8.dp, Alignment.End), modifier = Modifier.stepItem(2)) { + StepChoice(keep, enabled = open, modifier = Modifier.focusRequester(first)) { Steps.fold() } + StepChoice(reset, enabled = open) { Steps.fold(); NavTabs.reset(ctx) } + } + }) + } + } + } } +} + +@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class) +@Composable +internal fun EditTabsSheet(s: FrontEndState, a: FrontEndActions) { + val pal = LocalPalette.current + BackHandler(enabled = MoreTabs.editing) { MoreTabs.editing = false } + androidx.compose.runtime.DisposableEffect(Unit) { onDispose { MoreTabs.editing = false } } + var wasOpen by remember { mutableStateOf(false) } + val closeInput = androidx.compose.ui.platform.LocalInputModeManager.current + LaunchedEffect(MoreTabs.editing) { + if (MoreTabs.editing) wasOpen = true + else if (wasOpen && closeInput.inputMode == androidx.compose.ui.input.InputMode.Keyboard) focusSoon { MoreTabs.button } + } + Box(Modifier.fillMaxSize()) { + AnimatedVisibility(MoreTabs.editing, enter = fadeIn(), exit = fadeOut()) { + Box( + Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.45f)) + .focusProperties { canFocus = false } + .clickable(interactionSource = remember { MutableInteractionSource() }, indication = null) { MoreTabs.editing = false }, + ) + } + BoxWithConstraints(Modifier.fillMaxSize(), contentAlignment = Alignment.CenterEnd) { + val width = minOf(560.dp, maxWidth * 0.92f) + AnimatedVisibility(MoreTabs.editing, enter = slideInHorizontally { it } + fadeIn(), exit = slideOutHorizontally { it } + fadeOut()) { + val inside = remember { FocusRequester() } + var holds by remember { mutableStateOf(false) } + val openInput = androidx.compose.ui.platform.LocalInputModeManager.current + // The launcher only takes focus in controller mode, so opening by touch switches to it like startup does. + LaunchedEffect(Unit) { + repeat(60) { + androidx.compose.runtime.withFrameNanos { } + if (holds || !MoreTabs.editing) return@LaunchedEffect + if (openInput.inputMode != androidx.compose.ui.input.InputMode.Keyboard) openInput.requestInputMode(androidx.compose.ui.input.InputMode.Keyboard) + runCatching { inside.requestFocus() } + } + } + Column( + Modifier.width(width).fillMaxHeight() + .onFocusChanged { holds = it.hasFocus } + .focusRequester(inside) + .focusProperties { exit = { if (MoreTabs.editing) FocusRequester.Cancel else FocusRequester.Default } } + .focusGroup() + .background(MaterialTheme.colorScheme.background) + .border(1.dp, pal.line).padding(horizontal = 18.dp, vertical = 16.dp).testTag("edit-tabs-sheet"), + ) { + PageHeader(stringResource(R.string.more_edit_tabs)) { + Spacer(Modifier.weight(1f)) + SmallIconButton(Icons.Filled.Close, stringResource(R.string.common_close), tint = MaterialTheme.colorScheme.onSurfaceVariant) { + MoreTabs.editing = false + } + } + Column(Modifier.weight(1f).verticalScroll(rememberScrollState())) { + TabsSettingsGroup(rememberMenuHost(), s, a) + if (!NavTabs.isDefault()) ResetTabsRow() + } + } + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt index 578c936ad6..62f3c61f6c 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SecondScreenPresentation.kt @@ -63,7 +63,8 @@ class SecondScreenPresentation( private var imeSeen = false private var fieldKeyboard = false private var terminalPanel: SessionTerminalPanel? = null - private var controlsView: InputSurfaceView? = null + var controlsView: InputSurfaceView? = null + private set private var created = false init { diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt index cb438903b7..d65852ece2 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionDrawerPage.kt @@ -14,7 +14,7 @@ internal enum class SessionDrawerPage(val firstControl: String) { } internal fun sessionDrawerPages( - hasSecondScreen: Boolean, hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentHost.installed && com.droiddeck.launcher.agent.AgentTab.shown, + hasSecondScreen: Boolean, hasGlasses: Boolean = false, hasAgent: Boolean = com.droiddeck.launcher.agent.AgentTab.shown, ): List = SessionDrawerPage.entries.filter { (hasSecondScreen || it != SessionDrawerPage.SECOND_SCREEN) && (hasGlasses || it != SessionDrawerPage.GLASSES) && diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionLoading.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionLoading.kt index 85a1462949..888ab39678 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionLoading.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionLoading.kt @@ -77,6 +77,7 @@ import androidx.compose.ui.text.PlatformTextStyle import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.LineHeightStyle import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.platform.testTag @Composable @@ -223,6 +224,9 @@ fun LoadingOverlay( modifier = Modifier.align(Alignment.BottomCenter).padding(start = 120.dp, end = 120.dp, bottom = 28.dp), ) if (!ended && onCancel != null) CancelHint(onCancel, Modifier.align(Alignment.BottomEnd).padding(end = 16.dp, bottom = 16.dp)) + if (!ended && onShareLogs != null) androidx.compose.material3.TextButton( + onClick = onShareLogs, modifier = Modifier.align(Alignment.BottomStart).padding(start = 16.dp, bottom = 12.dp).testTag("loading-report"), + ) { Text(stringResource(R.string.report_problem), fontSize = 13.sp, color = colors.onSurfaceVariant) } if (flood != null) FloodGather(flood, ball, onFlooded) } } @@ -242,7 +246,7 @@ private fun EndedActions(onRetry: (() -> Unit)?, onRepair: (() -> Unit)?, onShar if (onRepair != null) SecondaryButton(stringResource(R.string.store_try_again), modifier = claim(), onClick = onRetry) else PrimaryButton(stringResource(R.string.store_try_again), modifier = claim(), onClick = onRetry) } - if (onShareLogs != null) SecondaryButton(stringResource(R.string.drawer_share_logs), modifier = claim(), + if (onShareLogs != null) SecondaryButton(stringResource(R.string.report_problem), modifier = claim(), progress = com.droiddeck.launcher.session.SessionLogShare.progress, onClick = onShareLogs) if (onClose != null) SecondaryButton(stringResource(R.string.mode_back), modifier = claim(), onClick = onClose) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 8d671466e2..6100bc9ed2 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -43,7 +43,6 @@ import androidx.compose.material.icons.outlined.PowerSettingsNew import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.material.icons.outlined.DesktopWindows import androidx.compose.material.icons.outlined.Layers -import androidx.compose.material.icons.outlined.AutoAwesome import androidx.compose.material.icons.outlined.ScreenShare import androidx.compose.material.icons.outlined.Pause import androidx.compose.material.icons.outlined.PictureInPictureAlt @@ -186,7 +185,7 @@ private val SessionDrawerPage.icon get() = when (this) { SessionDrawerPage.VR -> VrHeadsetIcon SessionDrawerPage.EFFECTS -> Icons.Outlined.AutoFixHigh SessionDrawerPage.GAMES -> Icons.Outlined.Layers - SessionDrawerPage.AGENT -> Icons.Outlined.AutoAwesome + SessionDrawerPage.AGENT -> Icons.Outlined.Terminal SessionDrawerPage.SESSION -> Icons.Outlined.Settings } @@ -262,6 +261,7 @@ class DrawerActions( val secondScreenNone: Boolean = true, val gameOnBottom: Boolean = false, val gameSwapAvailable: Boolean = false, + val gameSwapBuiltIn: Boolean = true, val onGameOnBottom: (Boolean) -> Unit = {}, val dashboardAvailable: Boolean = false, val desktopAvailable: Boolean = false, @@ -277,6 +277,8 @@ class DrawerActions( val onFrameGenReset: () -> Unit = {}, val fpsLimit: Int = 0, val onFpsLimit: (Int) -> Unit = {}, + val cornerTap: Boolean = false, + val onCornerTap: (Boolean) -> Unit = {}, val blackFrameInsertion: Boolean = false, val blackFrameInsertionAvailable: Boolean = false, val onBlackFrameInsertion: (Boolean) -> Unit = {}, @@ -618,6 +620,14 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont format = { if (it <= SessionPrefs.FPS_LIMIT_OFF) offLabel else it.toString() }, modifier = focus.track(page, "fps-limit"), onChange = { a.onFpsLimit(if (it <= SessionPrefs.FPS_LIMIT_OFF) 0 else it) }) + if (a.steam && !a.direct && a.onQam != null) SettingsRow( + stringResource(R.string.drawer_frame_limit), stringResource(R.string.drawer_frame_limit_steam_hint), + ) { + DrawerOutlineButton(stringResource(R.string.drawer_open_steam_qam), modifier = focus.track(page, "fps-limit-steam")) { + host.open = null + a.onQam?.invoke() + } + } } SettingsGroup(stringResource(R.string.display_image_scaling)) { if (a.steam) SettingsRow(stringResource(R.string.display_integer_scaling), null) { @@ -728,6 +738,9 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont SessionPrefs.BACK_DOUBLE_TAP_MS_OPTIONS.map { it to stringResource(R.string.back_tap_ms, it) }, a.backDoubleTapMs, chipModifier = focus.track(page, "back-double-tap"), onPick = a.onBackDoubleTapMs) PhysicalShortcutRows(modifierFor = { focus.track(page, "physical-shortcut-${it.name}") }) + ToggleRow(host, "corner-tap", stringResource(R.string.drawer_corner_tap), + stringResource(R.string.drawer_corner_tap_hint), a.cornerTap, + chipModifier = focus.track(page, "corner-tap"), onChange = a.onCornerTap) } SettingsGroup(stringResource(R.string.drawer_latency)) { ToggleRow(host, "low-latency", stringResource(R.string.drawer_low_latency), @@ -820,6 +833,15 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont } SessionDrawerPage.AGENT -> Unit SessionDrawerPage.SESSION -> { + SettingsGroup(stringResource(R.string.drawer_support)) { + SettingsRow(stringResource(R.string.report_problem), stringResource(R.string.report_problem_hint)) { + DrawerOutlineButton(stringResource(R.string.drawer_share_logs), modifier = focus.track(page, "share-logs"), + progress = com.droiddeck.launcher.session.SessionLogShare.progress) { + host.open = null + a.onShareLogs() + } + } + } if (a.isHomeApp) SettingsGroup(stringResource(R.string.drawer_android_apps)) { SettingsRow(stringResource(R.string.drawer_launch_app), null) { DrawerOutlineButton(if (androidAppsExpanded) stringResource(R.string.common_hide) else stringResource(R.string.common_show), modifier = focus.track(page, "apps")) { @@ -874,15 +896,6 @@ internal fun SessionDrawer(open: Boolean, requestedPage: SessionDrawerPage, cont onChange = a.onSteamDownloadsInBackground, ) } - SettingsGroup(stringResource(R.string.drawer_support)) { - SettingsRow(stringResource(R.string.drawer_logs), stringResource(R.string.drawer_logs_hint)) { - DrawerOutlineButton(stringResource(R.string.drawer_share_logs), modifier = focus.track(page, "share-logs"), - progress = com.droiddeck.launcher.session.SessionLogShare.progress) { - host.open = null - a.onShareLogs() - } - } - } if (a.pipSupported) SettingsGroup(stringResource(R.string.pip_title)) { ToggleRow(host, "pip-auto", stringResource(R.string.pip_auto), null, a.pipAutoEnter, onChange = a.onPipAutoEnter) @@ -1303,7 +1316,8 @@ private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String) } if (a.gameSwapAvailable || a.gameOnBottom) SettingsGroup(stringResource(R.string.swap_game_screen_group)) { ChoiceRow(host, "game-screen", stringResource(R.string.swap_game_screen), null, - listOf(false to stringResource(R.string.swap_game_screen_top), true to stringResource(R.string.swap_game_screen_bottom)), + if (a.gameSwapBuiltIn) listOf(false to stringResource(R.string.swap_game_screen_top), true to stringResource(R.string.swap_game_screen_bottom)) + else listOf(false to stringResource(R.string.main_primary), true to stringResource(R.string.main_secondary)), a.gameOnBottom, chipModifier = track("game-screen"), onPick = a.onGameOnBottom) } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt new file mode 100644 index 0000000000..37de5eba31 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsIndex.kt @@ -0,0 +1,153 @@ +package com.droiddeck.launcher.ui + +import android.content.Context +import androidx.annotation.StringRes +import androidx.compose.runtime.getValue +import androidx.compose.runtime.setValue +import com.droiddeck.launcher.R + +internal enum class SettingsSection(val key: String, @StringRes val title: Int) { + OVERVIEW("overview", R.string.setup_tab_overview), + PERFORMANCE("performance", R.string.setup_tab_performance), + CONTROLLER("controller", R.string.setup_tab_controller), + GLASSES("glasses", R.string.setup_tab_glasses), + LAUNCHER("launcher", R.string.setup_tab_launcher), + DEVELOPER("developer", R.string.setup_tab_diagnostics); + + companion object { + fun of(key: String?): SettingsSection? = entries.firstOrNull { it.key == key } + } +} + +internal object RailRequest { + var key by androidx.compose.runtime.mutableStateOf(null) +} + +internal enum class SettingsPlace(@StringRes val title: Int) { + SETTINGS(R.string.settings_place_settings), + TAB(R.string.settings_place_tab), + DRAWER(R.string.settings_place_drawer), + SHEET(R.string.settings_place_sheet), + STEAM_QAM(R.string.settings_place_steam_qam), +} + +internal class SettingsEntry( + val place: SettingsPlace, + @StringRes val title: Int, + @StringRes val group: Int? = null, + val section: SettingsSection? = null, + val words: List = emptyList(), + val developer: Boolean = false, + val tab: String? = null, +) { + val within: Int? get() = section?.title ?: tab?.let { railLabelIcon(it).first } ?: group + + fun path(context: Context): List = + listOfNotNull(context.getString(place.title), within?.let(context::getString), context.getString(title)) + + fun matches(context: Context, query: String): Boolean { + val q = query.trim().lowercase() + if (q.isEmpty()) return false + val text = (path(context) + words).joinToString(" ").lowercase() + return q.split(Regex("\\s+")).all { it in text } + } +} + +internal object SettingsIndex { + private fun s(section: SettingsSection, @StringRes title: Int, vararg words: String) = + SettingsEntry(SettingsPlace.SETTINGS, title, section = section, words = words.toList()) + + private fun d(@StringRes group: Int, @StringRes title: Int, vararg words: String) = + SettingsEntry(SettingsPlace.DRAWER, title, group = group, words = words.toList()) + + private fun sh(@StringRes group: Int, @StringRes title: Int, vararg words: String) = + SettingsEntry(SettingsPlace.SHEET, title, group = group, words = words.toList()) + + val entries: List = listOf( + s(SettingsSection.OVERVIEW, R.string.setup_runtime, "ubuntu", "linux", "repair", "update"), + s(SettingsSection.OVERVIEW, R.string.setup_limit, "phantom", "process", "killed", "background"), + s(SettingsSection.OVERVIEW, R.string.setup_account, "steam", "login", "sign in"), + + s(SettingsSection.PERFORMANCE, R.string.perf_override, "steam client cores", "cpu"), + s(SettingsSection.PERFORMANCE, R.string.perf_game_cores, "cpu", "pin", "cores", "affinity"), + s(SettingsSection.PERFORMANCE, R.string.perf_pace_cores, "cpu"), + s(SettingsSection.PERFORMANCE, R.string.perf_glthread, "opengl", "gl"), + s(SettingsSection.PERFORMANCE, R.string.perf_zink), + s(SettingsSection.PERFORMANCE, R.string.perf_noglerror), + s(SettingsSection.PERFORMANCE, R.string.perf_gsrealtime, "gamescope"), + s(SettingsSection.PERFORMANCE, R.string.perf_gpuclock, "gpu", "clock", "max"), + s(SettingsSection.PERFORMANCE, R.string.perf_ram_cap, "ram", "memory"), + s(SettingsSection.PERFORMANCE, R.string.perf_vram_cap, "vram", "memory"), + s(SettingsSection.PERFORMANCE, R.string.perf_zram_idle, "zram", "swap", "memory"), + s(SettingsSection.PERFORMANCE, R.string.perf_zram_client, "zram", "swap", "memory"), + s(SettingsSection.PERFORMANCE, R.string.setup_clear_cached, "memory", "ram", "crash", "sleep", "killed"), + s(SettingsSection.PERFORMANCE, R.string.setup_bg_limit, "memory", "ram", "background apps"), + s(SettingsSection.PERFORMANCE, R.string.setup_memory_hud, "memory", "ram", "overlay"), + s(SettingsSection.PERFORMANCE, R.string.perf_sysmem), + s(SettingsSection.PERFORMANCE, R.string.perf_xalia), + s(SettingsSection.PERFORMANCE, R.string.perf_esync, "esync", "sync", "wine"), + s(SettingsSection.PERFORMANCE, R.string.perf_fsync, "fsync", "sync", "wine"), + s(SettingsSection.PERFORMANCE, R.string.perf_fastsync, "ntsync", "sync", "wine"), + s(SettingsSection.PERFORMANCE, R.string.perf_seccomp, "proot"), + s(SettingsSection.PERFORMANCE, R.string.perf_fastpath, "proot"), + s(SettingsSection.PERFORMANCE, R.string.perf_native_userland, "proot"), + s(SettingsSection.PERFORMANCE, R.string.perf_cursor_composite, "mouse", "cursor"), + s(SettingsSection.PERFORMANCE, R.string.perf_hostname, "name"), + + s(SettingsSection.CONTROLLER, R.string.setup_tab_controller, "gamepad", "buttons", "mapping", "profile", "remap"), + SettingsEntry(SettingsPlace.TAB, R.string.rail_storage, tab = "storage", words = listOf("sd card", "space", "uninstall", "disk")), + SettingsEntry(SettingsPlace.TAB, R.string.rail_sync, tab = "sync", words = listOf("syncthing", "saves")), + s(SettingsSection.GLASSES, R.string.setup_tab_glasses, "xreal", "viture", "vr", "ar"), + + s(SettingsSection.LAUNCHER, R.string.setup_theme, "color", "dark"), + s(SettingsSection.LAUNCHER, R.string.setup_app_scale, "size", "zoom"), + s(SettingsSection.LAUNCHER, R.string.setup_launcher_icon), + s(SettingsSection.LAUNCHER, R.string.setup_animations), + s(SettingsSection.LAUNCHER, R.string.setup_rail_labels, "sidebar"), + s(SettingsSection.LAUNCHER, R.string.setup_language, "translate"), + SettingsEntry(SettingsPlace.TAB, R.string.setup_stores_speed, tab = "downloads", words = listOf("download", "speed", "bandwidth", "slow")), + SettingsEntry(SettingsPlace.TAB, R.string.stores_parallel, tab = "downloads", words = listOf("download", "parallel", "queue", "at once")), + SettingsEntry(SettingsPlace.TAB, R.string.setup_group_tabs, tab = NavTabs.MORE, words = listOf("tabs", "hide", "reorder", "agent", "stores", "edit tabs")), + s(SettingsSection.LAUNCHER, R.string.setup_home, "home screen", "launcher"), + s(SettingsSection.LAUNCHER, R.string.setup_launcher_orientation, "rotate", "portrait"), + s(SettingsSection.LAUNCHER, R.string.setup_session_orientation, "rotate", "portrait"), + s(SettingsSection.LAUNCHER, R.string.setup_fullscreen), + s(SettingsSection.LAUNCHER, R.string.setup_dual_screen_launcher, "thor", "second screen", "bottom screen"), + s(SettingsSection.LAUNCHER, R.string.setup_low_storage_warning), + s(SettingsSection.LAUNCHER, R.string.mode_sgdb_key, "artwork", "steamgriddb"), + s(SettingsSection.LAUNCHER, R.string.setup_download_source, "mirror", "china"), + s(SettingsSection.LAUNCHER, R.string.setup_download_proxy), + + s(SettingsSection.DEVELOPER, R.string.setup_latest_logs, "logs", "log", "bug", "report", "crash", "zip"), + s(SettingsSection.DEVELOPER, R.string.setup_logs, "logs"), + s(SettingsSection.DEVELOPER, R.string.setup_game_debug_logs, "logs", "wine", "proton"), + SettingsEntry(SettingsPlace.SETTINGS, R.string.setup_enhanced_diagnostics, section = SettingsSection.DEVELOPER, words = listOf("logs"), developer = true), + s(SettingsSection.DEVELOPER, R.string.setup_reset_settings, "default"), + s(SettingsSection.DEVELOPER, R.string.dev_tools_title, "agent", "ai", "claude", "codex"), + SettingsEntry(SettingsPlace.SETTINGS, R.string.setup_graphics_logs, section = SettingsSection.DEVELOPER, words = listOf("logs", "gpu"), developer = true), + + d(R.string.drawer_page_display, R.string.drawer_frame_limit, "fps", "cap", "limit", "non-steam", "desktop"), + d(R.string.drawer_page_display, R.string.frame_gen_title, "lsfg", "lossless", "fps"), + d(R.string.drawer_page_display, R.string.display_filter, "upscale", "fsr", "sharpness"), + d(R.string.drawer_hud, R.string.drawer_hud, "fps", "counter", "overlay", "performance"), + d(R.string.drawer_page_controller, R.string.input_touchscreen, "touch", "mouse", "direct", "touchpad", "click"), + d(R.string.drawer_page_controller, R.string.mode_osc, "on-screen", "controls", "touch controls", "buttons"), + d(R.string.drawer_page_controller, R.string.osc_steam_layout, "touch layout", "edit layout", "on-screen"), + d(R.string.drawer_page_controller, R.string.drawer_pc_keyboard, "keyboard", "typing"), + d(R.string.mode_session, R.string.report_problem, "logs", "log", "bug", "crash", "share", "zip"), + d(R.string.mode_session, R.string.mode_suspend, "sleep", "background", "native", "resume"), + + SettingsEntry(SettingsPlace.STEAM_QAM, R.string.drawer_frame_limit, R.string.perf_title, words = listOf("fps", "cap", "limit", "steam games")), + SettingsEntry(SettingsPlace.STEAM_QAM, R.string.perf_title, words = listOf("performance overlay", "fps", "counter", "tdp")), + + sh(R.string.drawer_page_display, R.string.display_session, "resolution", "scaling", "hdr", "refresh"), + sh(R.string.drawer_page_display, R.string.sheet_graphics_drivers, "turnip", "driver", "gpu", "adreno", "mali"), + sh(R.string.mode_tab_steam, R.string.setup_offline, "offline", "steam"), + sh(R.string.mode_audio, R.string.mode_mic, "microphone", "voice"), + sh(R.string.mode_session, R.string.mode_suspend, "sleep", "background"), + sh(R.string.stores_tab_library, R.string.stores_tab_library, "second library", "sd card", "steam library"), + ) + + fun search(context: Context, query: String): List = + entries.filter { (!it.developer || DeveloperTools.on) && it.matches(context, query) } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt new file mode 100644 index 0000000000..f2adebd9bf --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsSearch.kt @@ -0,0 +1,120 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.ui.unit.lerp +import androidx.compose.ui.graphics.graphicsLayer +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.focus.focusProperties +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.runtime.setValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.getValue +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.layout.BoxWithConstraints +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.focusGroup +import androidx.compose.animation.core.animateFloatAsState +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Close +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.runtime.remember +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.R +import androidx.compose.ui.input.pointer.PointerEventPass +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.semantics.clearAndSetSemantics + +// Grows out of the search button over the section pills, with the same spring as the other page searches. +@OptIn(androidx.compose.ui.ExperimentalComposeUiApi::class) +@Composable +internal fun SettingsPillSearch( + modifier: Modifier, searching: Boolean, query: String, onQuery: (String) -> Unit, + onOpen: () -> Unit, onClose: () -> Unit, pills: @Composable () -> Unit, +) { + val colors = MaterialTheme.colorScheme + val open by animateFloatAsState(if (searching) 1f else 0f, Motion.sp(0.75f, 420f), label = "settingsSearch") + val icon = remember { FocusRequester() } + var toIcon by remember { mutableStateOf(false) } + var focusOnOpen by remember { mutableStateOf(false) } + val close = { toIcon = true; focusOnOpen = false; onClose() } + BackHandler(enabled = searching) { close() } + LaunchedEffect(toIcon, searching, open <= 0.01f) { + if (searching) toIcon = false + else if (toIcon && open <= 0.01f) { focusSoon { icon }; toIcon = false } + } + BoxWithConstraints(modifier, contentAlignment = Alignment.CenterEnd) { + val full = maxWidth + Box( + Modifier.fillMaxWidth().padding(end = 52.dp) + .graphicsLayer { alpha = 1f - open; translationX = -24.dp.toPx() * open } + .focusProperties { enter = { if (searching) FocusRequester.Cancel else FocusRequester.Default } } + .focusGroup() + .then(if (searching) Modifier.clearAndSetSemantics {} else Modifier) + .then(if (searching) Modifier.pointerInput(Unit) { + awaitPointerEventScope { while (true) awaitPointerEvent(PointerEventPass.Initial).changes.forEach { it.consume() } } + } else Modifier), + ) { pills() } + if (searching || open > 0.01f) { + val w = lerp(44.dp, (full - 40.dp).coerceIn(44.dp, 640.dp), open) + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp)) { + Box(Modifier.width(w).graphicsLayer { alpha = (open * 1.6f).coerceAtMost(1f) }) { + AdbTextField( + value = query, onValueChange = onQuery, label = "", keyboardType = KeyboardType.Text, imeAction = ImeAction.Search, + placeholder = stringResource(R.string.settings_search), compact = true, showLabel = false, focusOnShow = focusOnOpen, + clearFocus = !searching, + onFocusChange = { focused -> if (!focused && query.isEmpty() && searching) { focusOnOpen = false; onClose() } }, + ) + } + SmallIconButton(Icons.Filled.Close, stringResource(R.string.settings_search_clear), tint = colors.onSurfaceVariant) { close() } + } + } else { + Box(Modifier.focusRequester(icon)) { SearchIcon(stringResource(R.string.settings_search)) { focusOnOpen = true; onOpen() } } + } + } +} + +@Composable +internal fun SettingsSearchResults(query: String, onOpen: (SettingsSection) -> Unit) { + val ctx = LocalContext.current + val found = remember(query) { SettingsIndex.search(ctx, query) } + if (found.isEmpty()) { + Note(stringResource(R.string.settings_search_none, query.trim())) + return + } + Column { + found.groupBy { it.place }.forEach { (place, entries) -> + SettingsGroup(stringResource(place.title)) { + entries.forEach { entry -> + val within = entry.within?.let { stringResource(it) } + val title = stringResource(entry.title) + val section = entry.section + val tab = entry.tab + if (section != null) { + ActionRow(title, within, stringResource(R.string.store_open), onClick = { onOpen(section) }) + } else if (tab != null) { + ActionRow(title, within, stringResource(R.string.store_open), onClick = { + if (tab == NavTabs.MORE) MoreTabs.editing = true + if (tab == "downloads") DownloadsNav.showSettings = true + RailRequest.key = tab + }) + } else { + SettingsRow(title, entry.path(ctx).dropLast(1).joinToString(" › ")) {} + } + } + } + } + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt index b5595a52b7..5ebcc3c051 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt @@ -108,6 +108,7 @@ import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalInputModeManager import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntRect import androidx.compose.ui.unit.IntSize @@ -605,7 +606,7 @@ fun SliderRow( @Composable fun ValueSlider( value: Int, range: IntRange, step: Int, enabled: Boolean, label: String?, format: (Int) -> String, - modifier: Modifier = Modifier, onChange: (Int) -> Unit, + modifier: Modifier = Modifier, track: Dp = 40.dp, onChange: (Int) -> Unit, ) { val compact = LocalCompactSettings.current val colors = MaterialTheme.colorScheme @@ -628,7 +629,7 @@ fun ValueSlider( } } Column( - modifier = modifier.fillMaxWidth().heightIn(min = if (compact) 64.dp else 72.dp) + modifier = modifier.fillMaxWidth().heightIn(min = track + if (compact) 24.dp else 32.dp) .clip(shape).background(if (hot) pal.signal.copy(alpha = 0.12f) else Color.Transparent) .glideBorder(hot, shape, pal.signal) .alpha(if (enabled) 1f else 0.5f) @@ -663,7 +664,7 @@ fun ValueSlider( Text(text, fontSize = if (compact) 12.sp else 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1) } Canvas( - Modifier.fillMaxWidth().height(40.dp).onSizeChanged { trackPx = it.width } + Modifier.fillMaxWidth().height(track).onSizeChanged { trackPx = it.width } .pointerInput(enabled, range, step, thumbInset) { if (enabled) detectTapGestures { fromX(it.x) } } .pointerInput(enabled, range, step, thumbInset) { if (enabled) detectHorizontalDragGestures { change, _ -> fromX(change.position.x); change.consume() } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SheetRows.kt b/app/src/main/java/com/droiddeck/launcher/ui/SheetRows.kt index 2b2ecf9048..181a837065 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SheetRows.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SheetRows.kt @@ -23,7 +23,7 @@ internal fun FrameGenGroup(s: FrontEndState, a: FrontEndActions) { internal fun PerformanceLink(a: FrontEndActions, rail: String, tab: String) { val id = "sheet:performance" val title = stringResource(R.string.setup_tool_performance) - SettingsGroup(title) { + SettingsGroup(stringResource(R.string.sheet_all_settings_hint)) { LinkRow(title, stringResource(R.string.setup_tool_performance_hint), stringResource(R.string.store_open), id, arrow = "›") { Hops.sources[id]?.let { at -> PageOrigin.mark(Origin(at, 12f * Hops.density)) @@ -31,6 +31,9 @@ internal fun PerformanceLink(a: FrontEndActions, rail: String, tab: String) { } a.onPerformance() } + LinkRow(stringResource(R.string.sheet_all_settings), stringResource(R.string.setup_title), stringResource(R.string.store_open), "sheet:all-settings", arrow = "›") { + SetupTabs.openSection = SettingsSection.OVERVIEW + } } } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt index b24c0f2cf1..7f2d0cb0c1 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SteamHome.kt @@ -83,12 +83,21 @@ private const val DRIFT_STEP_NS = 15_000_000L internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier) { val ctx = androidx.compose.ui.platform.LocalContext.current LaunchedEffect(Unit) { com.droiddeck.launcher.frontend.SteamFeatured.load(ctx) } - val featured = com.droiddeck.launcher.frontend.SteamFeatured.games + rememberHiddenSync() + val featuredAll = com.droiddeck.launcher.frontend.SteamFeatured.games val signedIn = s.offlineAccount != null - val owned by produceState(emptyList>(), signedIn) { - value = if (!signedIn) emptyList() else withContext(Dispatchers.IO) { runCatching { Library.steamLibraryArt(ctx).shuffled() }.getOrDefault(emptyList()) } + val account = LibraryHidden.account + val scanned by produceState>>>(account to emptyList(), signedIn, LibraryHidden.steam, account) { + val art = if (!signedIn) emptyList() else withContext(Dispatchers.IO) { runCatching { Library.steamLibraryArt(ctx).shuffled() }.getOrDefault(emptyList()) } + value = account to art } - val games = remember(s.steamGames) { s.steamGames.sortedWith(compareByDescending { it.lastPlayed }.thenBy { it.gameId }) } + val ownedAll = if (scanned.first == account) scanned.second else emptyList() + val concealed = remember(s.steamGames, LibraryHidden.keys, LibraryHidden.steam) { + LibraryHidden.steam + s.steamGames.filter { LibraryHidden.isHidden(hideKey(it), it) }.map { it.appId.toLong() } + } + val owned = remember(ownedAll, concealed) { ownedAll.filter { it.first.toLong() !in concealed } } + val featured = remember(featuredAll, concealed) { featuredAll.filter { it.appId.toLong() !in concealed } } + val games = remember(s.steamGames, LibraryHidden.keys, LibraryHidden.steam) { s.steamGames.filterNot { LibraryHidden.isHidden(hideKey(it), it) }.sortedWith(compareByDescending { it.lastPlayed }.thenBy { it.gameId }) } val narrow = LocalNarrowPane.current var words by remember { mutableStateOf(null) } val mode = com.droiddeck.launcher.session.SessionService.MODE_STEAM @@ -145,6 +154,8 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier) words = { val runtimeStatus: @Composable () -> Unit = { if (s.busy || (s.available != null && s.available != s.installed)) RuntimeChip(s) + else if (setupNeedsAttention(s)) SecondaryButton(stringResource(R.string.play_needs_you), compact = true, + modifier = Modifier.testTag("play-needs-you")) { SetupTabs.openSection = SettingsSection.OVERVIEW } else if (s.integration.suggested && signedIn && !com.droiddeck.launcher.core.PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)) IntegrationSuggestion(s.integration, { a.onSteamIntegration(null) }, a.onDismissIntegration) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt index 1333172d7a..7856fdcfea 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoragePage.kt @@ -39,6 +39,7 @@ import androidx.compose.foundation.relocation.bringIntoViewRequester import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Check import androidx.compose.material.icons.filled.ChevronRight +import androidx.compose.material.icons.outlined.Delete import androidx.compose.material.icons.outlined.Extension import androidx.compose.material.icons.outlined.Folder import androidx.compose.material.icons.outlined.Layers @@ -907,19 +908,31 @@ private fun SelectBox(on: Boolean, enabled: Boolean, onToggle: () -> Unit) { @Composable private fun ConfirmDialog(title: String, body: String, confirm: String, danger: Boolean = true, onConfirm: () -> Unit, onDismiss: () -> Unit) { - val colors = MaterialTheme.colorScheme - val pal = LocalPalette.current - AlertDialog( - onDismissRequest = onDismiss, - title = { Text(title) }, - text = { Text(body, fontSize = 14.sp) }, - confirmButton = { FocusText(confirm, if (danger) colors.error else pal.signal) { onDismiss(); onConfirm() } }, - dismissButton = { - val cancel = remember { FocusRequester() } - LaunchedEffect(Unit) { runCatching { cancel.requestFocus() } } - FocusText(stringResource(R.string.common_cancel), colors.onBackground, modifier = Modifier.focusRequester(cancel), onClick = onDismiss) - }, - ) + val accent = if (danger) MaterialTheme.colorScheme.error else LocalPalette.current.signal + val cancel = stringResource(R.string.common_cancel) + val glide = LocalFocusGlide.current + val view = androidx.compose.ui.platform.LocalView.current + val confirmNow = androidx.compose.runtime.rememberUpdatedState(onConfirm) + val dismissNow = androidx.compose.runtime.rememberUpdatedState(onDismiss) + androidx.compose.runtime.DisposableEffect(Unit) { + val at = focusAnchor(glide, androidx.compose.ui.geometry.Offset.Zero) + ?: androidx.compose.ui.geometry.Rect(androidx.compose.ui.geometry.Offset(view.rootView.width / 2f, view.rootView.height / 2f), 1f) + var confirmed = false + val ask = StepAsk( + anchor = at, side = StepSide.Left, accent = accent, items = 3, pillCorner = 12.dp, maxWidth = 360.dp, + onDismiss = { dismissNow.value(); if (confirmed) confirmNow.value() }, + handle = { Icon(if (danger) Icons.Outlined.Delete else Icons.Filled.Check, null, tint = accent, modifier = Modifier.size(18.dp)) }, + ) { + StepTitle(title) + Text(body, fontSize = 13.sp, lineHeight = 18.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.stepItem(1).padding(start = 4.dp, bottom = 12.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), modifier = Modifier.fillMaxWidth().stepItem(2)) { + StepChoice(cancel, enabled = open, modifier = Modifier.focusRequester(first)) { Steps.fold() } + StepChoice(confirm, danger = danger, enabled = open) { confirmed = true; Steps.fold() } + } + } + Steps.ask(ask) + onDispose { if (Steps.step === ask) Steps.drop() } + } } private class DataTarget(val key: String, val label: String, val prefixes: List>, val shaders: List>) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoreChips.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoreChips.kt index 3921df7f32..a822548739 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoreChips.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoreChips.kt @@ -1,6 +1,7 @@ package com.droiddeck.launcher.ui import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme @@ -73,7 +74,7 @@ internal fun SourceChip(source: String, small: Boolean = false, modifier: Modifi } @Composable -internal fun StateChip(text: String, tone: ChipTone, small: Boolean = false) { +internal fun StateChip(text: String, tone: ChipTone, small: Boolean = false, fraction: Float? = null, key: Any? = null) { val pal = LocalPalette.current val (fill, ink) = when (tone) { ChipTone.OK -> Color(0xFF16321F) to pal.good @@ -82,10 +83,14 @@ internal fun StateChip(text: String, tone: ChipTone, small: Boolean = false) { ChipTone.DEAL -> Color(0xFF1E3A1A) to Color(0xFF9BE27A) ChipTone.PLAIN -> MaterialTheme.colorScheme.surfaceVariant to MaterialTheme.colorScheme.onSurfaceVariant } - Text( - text, fontSize = if (small) 9.sp else 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.3.sp, color = ink, maxLines = 1, - modifier = Modifier.clip(RoundedCornerShape(6.dp)).background(fill).padding(horizontal = if (small) 5.dp else 8.dp, vertical = if (small) 1.dp else 2.dp), - ) + val shape = RoundedCornerShape(6.dp) + Box(Modifier.clip(shape).background(fill)) { + if (fraction != null) ChipFill(fraction, key, ink.copy(alpha = 0.26f)) + Text( + text, fontSize = if (small) 9.sp else 11.sp, fontWeight = FontWeight.Bold, letterSpacing = 0.3.sp, color = ink, maxLines = 1, + modifier = Modifier.padding(horizontal = if (small) 5.dp else 8.dp, vertical = if (small) 1.dp else 2.dp), + ) + } } internal enum class ChipTone { OK, BUSY, WARN, DEAL, PLAIN } 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 0b1000e6e3..59ae4df3b8 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresDownloads.kt @@ -61,6 +61,7 @@ import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.OpenInNew import androidx.compose.material.icons.filled.PlayArrow import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text @@ -371,6 +372,11 @@ private fun DownloadCard(d: DownloadEntry, s: FrontEndState, a: FrontEndActions) CancelAction { DownloadQueue.cancel(ctx, d.key) } } DownloadState.FAILED -> { + if (d.store == Store.XBOX && d.error == stringResource(R.string.stores_xbox_device_group_full)) { + RoundAction(Icons.AutoMirrored.Filled.OpenInNew, stringResource(R.string.stores_xbox_manage_devices)) { + runCatching { ctx.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(com.droiddeck.launcher.stores.xbox.XboxInstaller.DEVICES_URL)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)) } + } + } RoundAction(Icons.Filled.Refresh, stringResource(R.string.stores_dl_resume), primary = true) { DownloadQueue.retry(ctx, d.key) } CancelAction { DownloadQueue.clear(ctx, d.key) } } @@ -535,7 +541,6 @@ internal fun storesSettingsStep(at: Rect, s: androidx.compose.runtime.State, a: FrontEndActions, accent: androidx.compose.ui.graphics.Color): 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)) }, + ) { + StepTitle(stringResource(R.string.downloads_settings)) + Column(Modifier.stepItem(1).fillMaxWidth().focusRequester(first).focusGroup().padding(horizontal = 14.dp, vertical = 11.dp)) { DownloadControls(s.value, a) } + } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresMotion.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresMotion.kt index 3d5ba671ca..66fcc94965 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresMotion.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresMotion.kt @@ -1,5 +1,8 @@ package com.droiddeck.launcher.ui +import androidx.compose.foundation.layout.Box +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.positionInRoot import android.os.SystemClock import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.EnterTransition @@ -67,6 +70,13 @@ internal object StoresMotion { var downloadsChip by mutableStateOf(null) + private var touch: Offset? = null + private var touchAt = 0L + + fun touched(at: Offset) { touch = at; touchAt = SystemClock.uptimeMillis() } + + fun recentTouch(): Offset? = touch.takeIf { SystemClock.uptimeMillis() - touchAt < 4_000 } + var landed by mutableIntStateOf(0) val flights = mutableStateListOf() @@ -87,6 +97,16 @@ internal object StoresMotion { stepOpen = true } + private var host: Any? = null + + fun hosting(page: Any) { host = page } + + fun release(page: Any) { + if (host !== page) return + host = null + drop() + } + fun drop() { step?.let { step = null; it.onDismiss() } stepOpen = false @@ -109,6 +129,8 @@ internal object StoresMotion { val dots = HashMap() var heroAt by mutableStateOf(null) + var heroFadeTop = false + var heroDrift: () -> Float = { 0f } var heroLands by mutableStateOf(false) @@ -123,7 +145,7 @@ internal object StoresMotion { fun takeCard(key: String): CardMark? = card?.takeIf { it.key == key && SystemClock.uptimeMillis() - cardAt < 1_000 }.also { card = null } } -internal class CardMark(val key: String, val bounds: Rect, val corner: Float, val art: String?) +internal class CardMark(val key: String, val bounds: Rect, val corner: Float, val art: String?, val hero: String? = art) internal class StepAsk( val anchor: Rect, @@ -137,7 +159,7 @@ internal class StepAsk( val content: @Composable StepOutScope.() -> Unit, ) -internal class SignInFlood(val store: Store, val from: Rect, val start: Color, val color: Color) { +internal class SignInFlood(val store: Store, val from: Rect, val start: Color, val color: Color, val home: Rect? = null) { var away by mutableStateOf(false) var drainTo by mutableStateOf(null) } @@ -301,3 +323,31 @@ internal fun AnimatedRows( } } } + +@Composable +internal fun DownloadFlights() { + val glide = LocalFocusGlide.current + var origin by remember { mutableStateOf(Offset.Zero) } + val active = com.droiddeck.launcher.stores.StoresState.downloads.filter { it.isActive }.map { it.key }.toSet() + val seen = remember { mutableSetOf().also { it.addAll(active) } } + LaunchedEffect(active) { + val fresh = active - seen + seen.clear(); seen.addAll(active) + if (fresh.isEmpty()) return@LaunchedEffect + val from = StoresMotion.takeInstall() ?: focusAnchor(glide, origin) + if (from != null) StoresMotion.fly(from) else StoresMotion.landed++ + } + Box(Modifier.fillMaxSize().onGloballyPositioned { origin = it.positionInRoot() }) { + FlightLayer(origin) + SignInFloodLayer(origin) + } +} + +internal fun focusAnchor(glide: FocusGlide?, origin: Offset): Rect? { + val ring = glide?.let { g -> + val src = g.current ?: return@let null + val host = g.host?.takeIf { it.isAttached } ?: return@let null + g.boundsOf(src)?.translate(host.positionInRoot()) + } + return ring ?: StoresMotion.recentTouch()?.let { Rect(it + origin - Offset(24f, 24f), androidx.compose.ui.geometry.Size(48f, 48f)) } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt index e5005a018e..440541dda4 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/StoresPage.kt @@ -143,7 +143,6 @@ import com.droiddeck.launcher.stores.formatBytes import androidx.compose.runtime.setValue -private const val DOWNLOADS = "downloads" private data class PaneKey(val chip: String, val signedIn: Boolean, val accountsLoaded: Boolean) @@ -156,22 +155,22 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier val padH = if (narrow) 14.dp else 22.dp val tabs = remember { androidx.compose.runtime.mutableStateListOf().apply { + SessionPrefs.settleStoresTabOrder(ctx, Store.entries.map { it.id }) addAll(arrangeStoreTabs(SessionPrefs.storesTabOrder(ctx), SessionPrefs.storesTabHidden(ctx))) } } var chip by rememberSaveable { mutableStateOf(tabs.firstOrNull { it.shown }?.store?.id ?: Store.GOG.id) } 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 commitTabs(markCustomized: Boolean = false) { + SessionPrefs.saveStoresTabs(ctx, tabs.map { it.store.id }, tabs.filterNot { it.shown }.map { it.store.id }.toSet(), markCustomized) } 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() + commitTabs(markCustomized = true) } fun moveTab(store: Store, to: Int) { val from = tabs.indexOfFirst { it.store == store } @@ -179,7 +178,7 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier val target = to.coerceIn(0, tabs.lastIndex) if (target == from) return tabs.add(target, tabs.removeAt(from)) - commitTabs() + commitTabs(markCustomized = true) } fun toggleTab(store: Store) { val i = tabs.indexOfFirst { it.store == store } @@ -196,10 +195,9 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier 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 + if (Store.byId(chip) !in shownStores) chip = shownStores.firstOrNull()?.id ?: chip } val pane = PaneKey( chip, @@ -333,9 +331,8 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier StoreTheme(Store.byId(focusedChip ?: chip)) { Rise(0) { StoreChips( - chip, focusedChip, s.storeDownloadsActive, tabs, arranging, + chip, focusedChip, 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) }, @@ -378,7 +375,6 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier .focusGroup(), ) { when { - k.chip == DOWNLOADS -> Column(Modifier.fillMaxWidth().verticalScroll(scroll).padding(top = 4.dp, bottom = 16.dp)) { StoresDownloadsPane(s, a) } st == null -> {} !k.accountsLoaded -> Box(Modifier.fillMaxWidth().padding(top = 16.dp)) { androidx.compose.material3.LinearProgressIndicator(Modifier.fillMaxWidth().height(3.dp)) @@ -393,7 +389,6 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier }, ) { key -> GameDetail(key, s, a, heroFocus, backLabel, hopRail = null, onBack = { closeGame() }, inStore = true) } } - FlightLayer(hostAt) StoresMotion.step?.let { ask -> key(ask) { StepOut( @@ -403,16 +398,8 @@ internal fun StoresPage(s: FrontEndState, a: FrontEndActions, modifier: Modifier ) } } - SignInFloodLayer(hostAt) - } - androidx.compose.runtime.DisposableEffect(Unit) { onDispose { StoresMotion.drop() } } - val activeKeys = StoresState.downloads.filter { it.isActive }.map { it.key }.toSet() - val seenActive = remember { mutableSetOf().also { it.addAll(activeKeys) } } - LaunchedEffect(activeKeys) { - val fresh = activeKeys - seenActive - seenActive.clear(); seenActive.addAll(activeKeys) - if (fresh.isNotEmpty()) StoresMotion.takeInstall()?.let { StoresMotion.fly(it) } } + androidx.compose.runtime.DisposableEffect(Unit) { val page = Any(); StoresMotion.hosting(page); onDispose { StoresMotion.release(page) } } } @Composable @@ -470,14 +457,14 @@ internal fun InstallWhere(item: CatalogItem) { } @Composable -private fun SignInFloodLayer(hostAt: Offset) { +internal fun SignInFloodLayer(hostAt: Offset) { val f = StoresMotion.signIn ?: return val ctx = LocalContext.current val lifecycle = androidx.compose.ui.platform.LocalLifecycleOwner.current.lifecycle val density = androidx.compose.ui.platform.LocalDensity.current key(f) { var paused by remember { mutableStateOf(false) } - fun back() { if (f.drainTo == null) f.drainTo = if (StoresState.isSignedIn(f.store)) StoresMotion.dots[f.store] ?: f.from else f.from } + fun back() { if (f.drainTo == null) f.drainTo = f.home ?: if (StoresState.isSignedIn(f.store)) StoresMotion.dots[f.store] ?: f.from else f.from } androidx.compose.runtime.DisposableEffect(lifecycle) { val obs = androidx.lifecycle.LifecycleEventObserver { _, e -> if (e == androidx.lifecycle.Lifecycle.Event.ON_PAUSE && f.away) paused = true @@ -594,12 +581,12 @@ private fun RowScope.ArrangeStoreChip( @OptIn(androidx.compose.foundation.ExperimentalFoundationApi::class) @Composable private fun StoreChips( - selected: String, focused: String?, active: Int, tabs: List, arranging: Boolean, - onStore: (Store) -> Unit, onDownloads: () -> Unit, onSettings: (Rect?) -> Unit, onFocusChip: (String?) -> Unit, + selected: String, focused: String?, tabs: List, arranging: Boolean, + onStore: (Store) -> Unit, onSettings: (Rect?) -> Unit, onFocusChip: (String?) -> Unit, onArrangeDone: () -> Unit, onMoveTab: (Store, Int) -> Unit, onToggleTab: (Store) -> Unit, ) { val pal = LocalPalette.current - val keys = tabs.filter { it.shown }.map { it.store.id } + DOWNLOADS + val keys = tabs.filter { it.shown }.map { it.store.id } val bounds = remember { androidx.compose.runtime.mutableStateMapOf() } val highlighted = focused ?: selected val inputMode = androidx.compose.ui.platform.LocalInputModeManager.current.inputMode @@ -638,25 +625,11 @@ private fun StoreChips( } } } - ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown && highlighted != DOWNLOADS) + ChipGlide(keys.indexOf(highlighted), bounds[highlighted], tint, visible = fillShown) } if (arranging) { IconChip(Icons.Filled.Check, stringResource(R.string.stores_tabs_arrange_done)) { onArrangeDone() } } else { - Box { - 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() } - ChipGlide(keys.indexOf(DOWNLOADS), bounds[DOWNLOADS], tint, visible = fillShown && highlighted == DOWNLOADS) - } var cogAt by remember { mutableStateOf(null) } Box(Modifier.onGloballyPositioned { cogAt = it.boundsInRoot() }) { IconChip(Icons.Filled.Settings, stringResource(R.string.stores_settings)) { onSettings(cogAt) } @@ -1304,7 +1277,7 @@ private fun GameCard( val placed = remember { arrayOfNulls(1) } val corner = with(androidx.compose.ui.platform.LocalDensity.current) { 10.dp.toPx() } val open = { - placed[0]?.takeIf { it.isAttached }?.let { StoresMotion.markCard(CardMark(item.key, it.boundsInRoot(), corner, item.imageUrl ?: item.tallImageUrl)) } + placed[0]?.takeIf { it.isAttached }?.let { StoresMotion.markCard(CardMark(item.key, it.boundsInRoot(), corner, item.imageUrl ?: item.tallImageUrl, item.imageUrl ?: item.tallImageUrl)) } onOpen(item.key) } val screen = with(androidx.compose.ui.platform.LocalDensity.current) { androidx.compose.ui.platform.LocalConfiguration.current.screenHeightDp.dp.toPx() } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt b/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt index 475c400b16..6d4605785a 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/TabsSettings.kt @@ -55,7 +55,6 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.zIndex import com.droiddeck.launcher.R -import com.droiddeck.launcher.agent.AgentTab import kotlin.math.roundToInt private const val MORE_LINE = "|more|" @@ -93,11 +92,6 @@ internal fun TabsSettingsGroup(host: MenuHost, s: FrontEndState, a: FrontEndActi NavTabs.rearrange(ctx, state, next.subList(0, split), next.subList(split + 1, next.size)) } fun setShown(key: String, show: Boolean) { - when (key) { - "stores" -> if (show != s.gameStoresEnabled) a.onGameStoresEnabled(show) - "soundtracks" -> if (show != s.soundtracksEnabled) a.onSoundtracksEnabled(show) - "agent" -> if (show != AgentTab.shown) AgentTab.set(ctx, show) - } NavTabs.setHidden(ctx, key, !show) } diff --git a/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt index a685e414f3..ebcfcb1ea7 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/WirelessAdbFixPage.kt @@ -365,8 +365,10 @@ internal fun AdbTextField( onDone: (() -> Unit)? = null, focusOnShow: Boolean = false, showLabel: Boolean = true, + onBack: (() -> Unit)? = null, ) { val context = LocalContext.current + val onBackLatest = rememberUpdatedState(onBack) val focusAsked = remember { booleanArrayOf(false) } val palette = LocalPalette.current val onValueChangeLatest = rememberUpdatedState(onValueChange) @@ -384,7 +386,8 @@ internal fun AdbTextField( fun typeOnBottom(editText: EditText): Boolean { if (!bottomTypingLatest.value || !DualScreenPanel.attached) return false val text = editText.text.toString() - val request = TypingRequest( + lateinit var request: TypingRequest + request = TypingRequest( TextFieldValue(text, TextRange(editText.selectionStart.coerceIn(0, text.length), editText.selectionEnd.coerceIn(0, text.length))), ImeOptions(singleLine = true, keyboardType = keyboardType, imeAction = imeAction), { next -> @@ -392,7 +395,7 @@ internal fun AdbTextField( editText.setSelection(next.selection.start.coerceIn(0, next.text.length), next.selection.end.coerceIn(0, next.text.length)) }, { action -> editText.onEditorAction(imeActionFlag(action)) }, - { editText.post { editText.clearFocus() } }, + { editText.post { if (typingRequest[0] === request) onBackLatest.value?.invoke() ?: editText.clearFocus() } }, ) typingRequest[0] = request DualScreenPanel.startTyping(request) @@ -450,6 +453,20 @@ internal fun AdbTextField( onDoneLatest.value?.invoke() true } + // Search and Go are terminal: leaving them unhandled + // keeps focus in the field, so the keyboard would stay + // up over the results it was used to find. + imeAction in setOf(ImeAction.Search, ImeAction.Go) && + (actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_GO || isEnter) -> { + onDoneLatest.value?.invoke() + post { + clearFocus() + (context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) + as? android.view.inputmethod.InputMethodManager) + ?.hideSoftInputFromWindow(windowToken, 0) + } + true + } else -> false } } @@ -463,6 +480,7 @@ internal fun AdbTextField( ?.isVisible(androidx.core.view.WindowInsetsCompat.Type.ime()) == true if (hidingKeyboard) (view.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager) ?.hideSoftInputFromWindow(view.windowToken, 0) + onBackLatest.value?.let { hidingKeyboard = true; it() } } hidingKeyboard } diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/BottomDesktopCompositorService.kt b/app/src/main/java/com/droiddeck/launcher/wayland/BottomDesktopCompositorService.kt index 26faded94c..d1c64b4b39 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/BottomDesktopCompositorService.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/BottomDesktopCompositorService.kt @@ -70,7 +70,7 @@ class BottomDesktopCompositorService : Service() { FileUtils.copyAsset(this, "wayland/keymap.xkb", File(runtimeDir, "keymap.xkb")) data.getString(KEY_LOG)?.let { path -> WaylandCompositor.setSessionLogFile(File(path)) - runCatching { android.system.Os.setenv("BL_WAYLAND_LOG", path, true) } + runCatching { android.system.Os.setenv("DD_WAYLAND_LOG", path, true) } .onFailure { Log.w(TAG, "could not point the compositor's log at $path", it) } } WaylandCompositor.setFirstFrameListener { reply(MSG_FIRST_FRAME) } diff --git a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt index ad4878b2ef..4ad4263161 100644 --- a/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt +++ b/app/src/main/java/com/droiddeck/launcher/wayland/CompositorHost.kt @@ -50,7 +50,7 @@ object CompositorHost { refreshHz: Float, fpsLimit: Int, ): Boolean { - WaylandCompositor.nativeSetClockControl(java.io.File(context.filesDir, "${com.droiddeck.launcher.runtime.LinuxRuntime.DIR}/tmp/.bl-clock").path) + WaylandCompositor.nativeSetClockControl(java.io.File(context.filesDir, "${com.droiddeck.launcher.runtime.LinuxRuntime.DIR}/tmp/.dd-clock").path) ownVsyncThread = SessionPrefs.vsyncThread(context) WaylandCompositor.nativeSetRenderOnCommit(SessionPrefs.renderOnCommit(context)) blackFrameInsertion = SessionPrefs.blackFrameInsertion(context) diff --git a/app/src/main/java/org/webrtc/DroidDeckLowLatencyDecoderFactory.java b/app/src/main/java/org/webrtc/DroidDeckLowLatencyDecoderFactory.java index c26b295e84..b0277f2fd8 100644 --- a/app/src/main/java/org/webrtc/DroidDeckLowLatencyDecoderFactory.java +++ b/app/src/main/java/org/webrtc/DroidDeckLowLatencyDecoderFactory.java @@ -84,7 +84,7 @@ public class DroidDeckLowLatencyDecoderFactory implements VideoDecoderFactory { private Surface standInSurface() { if (standIn == null) { - standInThread = new HandlerThread("bl-decoder-standin"); + standInThread = new HandlerThread("dd-decoder-standin"); standInThread.start(); standIn = ImageReader.newInstance(Math.max(width, 16), Math.max(height, 16), ImageFormat.PRIVATE, 3); standIn.setOnImageAvailableListener(reader -> { diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index bdb5ae8e31..e92f6f47e2 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -203,6 +203,8 @@ هذا البرنامج مبني لأجهزة كمبيوتر %1$s ويعمل عبر FEX، الذي لم يتم إعداده بعد. افتح Steam مرة واحدة أثناء تسجيل الدخول: سيجعله DroidDeck يُنزّل FEX وSteam Linux Runtime اللازمة، ثم يُفتح هذا البرنامج. تعذّر تنزيل proot الخاص بـ DroidDeck. تحقّق من الاتصال وحاول مرة أخرى. لم تبدأ الجلسة لأن proot الاحتياطي أبطأ من أن يصلح للعب. تعذّر تنزيل بيئة رسومات PowerVR. تحقق من الاتصال وحاول مرة أخرى. + تعذّر تجهيز بيئة الرسومات، لذا لم تبدأ الجلسة. + تعذّر إعداد بيئة اللعبة، لذا لم تبدأ الجلسة. تعذّر تنزيل DirectAudio، لذا يستخدم صوت الألعاب المسار الأبطأ في هذه الجلسة. هذا البرنامج لم تتمكن الجلسة من الرسم على الشاشة: %1$s. تعرض هذه الشاشة السبب بدلًا من شاشة سوداء؛ والتفاصيل في سجلات الجلسة. @@ -1346,6 +1348,7 @@ إدخال العنوان يدويًا من جهاز كمبيوتر يحتوي على ADB: نسخ الأمر + وصّل النظارة بالكمبيوتر وافتح SideQuest. اختر “Run ADB Command” ثم “Custom Command”، واكتب الأمر الظاهر أدناه، ثم اختر “Run Command”. اختر الشاشة التي ستُفتَح فيها إعدادات Android. الشاشة الرئيسية تم الإقران. جارٍ البحث عن منفذ تصحيح الأخطاء اللاسلكي… @@ -1604,6 +1607,8 @@ تعذّر على Android فتح نافذة ضمن النافذة. المزيد تعديل الصور + إزالة من المخفية + تعذّرت المزامنة مع Steam. أغلق Steam وحاول مرة أخرى. في Steam اختصار إضافة إلى الشاشة الرئيسية 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 84618fdd14..c754689975 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -203,6 +203,8 @@ 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á. No se pudo descargar el proot de DroidDeck. Revisa la conexión e inténtalo de nuevo. La sesión no se inició porque el proot alternativo es demasiado lento para jugar. No se pudo descargar el entorno gráfico de PowerVR. Revisa la conexión e inténtalo de nuevo. + No se pudo preparar el entorno gráfico, así que la sesión no se inició. + No se pudo configurar el entorno del juego, así que la sesión no se inició. No se pudo descargar DirectAudio, así que el audio de los juegos usa la ruta más lenta en esta sesión. Este programa La sesión no pudo dibujar en la pantalla: %1$s. En lugar de una pantalla negra, esta pantalla muestra el motivo; los registros de la sesión tienen los detalles. @@ -1352,6 +1354,7 @@ Ingresar dirección manualmente Desde una computadora con ADB: Copiar comando + Conecta el visor a una computadora y abre SideQuest. Elige “Run ADB Command” y luego “Custom Command”, escribe el comando que aparece abajo y selecciona “Run Command”. Elige en qué pantalla abrir los Ajustes de Android. Pantalla principal Vinculado. Buscando el puerto de la Depuración inalámbrica… @@ -1650,6 +1653,8 @@ Android no pudo abrir imagen en imagen. Más Editar imágenes + Quitar de ocultas + No se pudo sincronizar con Steam. Cierra Steam e inténtalo de nuevo. En Steam Acceso directo Agregar a la pantalla de inicio diff --git a/app/src/main/res/values-bg/strings.xml b/app/src/main/res/values-bg/strings.xml index be5c06043a..e5c8de89cb 100644 --- a/app/src/main/res/values-bg/strings.xml +++ b/app/src/main/res/values-bg/strings.xml @@ -203,6 +203,8 @@ Тази програма е компилирана за %1$s компютри и се стартира през FEX, който още не е настроен. Отворете Steam веднъж, докато сте влезли: DroidDeck ще изтегли FEX и необходимата Steam Linux Runtime, след което тя ще се отвори. proot на DroidDeck не можа да бъде изтеглен. Проверете връзката и опитайте пак. Сесията не беше стартирана, защото резервният proot е твърде бавен за игра. Графичната среда за PowerVR не можа да бъде изтеглена. Проверете връзката и опитайте отново. + Графичната среда не можа да бъде подготвена, затова сесията не беше стартирана. + Средата на играта не можа да бъде настроена, затова сесията не беше стартирана. DirectAudio не можа да бъде изтеглен, затова звукът на игрите използва по-бавния път в тази сесия. Тази програма Сесията не успя да изобрази съдържание на екрана: %1$s. Вместо черен екран тук е показана причината; подробностите са в дневниците на сесията. @@ -1318,6 +1320,7 @@ Ръчно въвеждане на адреса От компютър с ADB: Копиране на командата + Свържете шлема с компютър и отворете SideQuest. Изберете „Run ADB Command“, после „Custom Command“, въведете командата, показана по-долу, и изберете „Run Command“. Изберете на кой екран да се отворят настройките на Android. Основен екран Сдвоено. Търсене на порта за безжично отстраняване на грешки… @@ -1572,6 +1575,8 @@ Android не можа да отвори картина в картината. Още Редактиране на изображенията + Премахване от скритите + Синхронизирането със Steam не успя. Затворете Steam и опитайте отново. В Steam Пряк път Добавяне към началния екран diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index a5bfeabd6e..370a0eea68 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -203,6 +203,8 @@ 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. Proot od DroidDeck se nepodařilo stáhnout. Zkontrolujte připojení a zkuste to znovu. Relace nebyla spuštěna, protože záložní proot je na hraní příliš pomalý. Grafické prostředí PowerVR se nepodařilo stáhnout. Zkontrolujte připojení a zkuste to znovu. + Grafické prostředí se nepodařilo připravit, a proto relace nebyla spuštěna. + Herní prostředí se nepodařilo nastavit, a proto relace nebyla spuštěna. DirectAudio se nepodařilo stáhnout, takže zvuk her v této relaci používá pomalejší cestu. Tento program Relaci se nepodařilo vykreslit na obrazovku: %1$s. Místo černé obrazovky je zde důvod; podrobnosti jsou v protokolech relace. @@ -1332,6 +1334,7 @@ Zadat adresu ručně Z počítače s ADB: Kopírovat příkaz + Připojte headset k počítači a otevřete SideQuest. Zvolte „Run ADB Command“, pak „Custom Command“, opište příkaz zobrazený níže a vyberte „Run Command“. Vyberte, na kterém displeji se má otevřít Nastavení Androidu. Hlavní obrazovka Spárováno. Hledání portu Bezdrátového ladění… @@ -1588,6 +1591,8 @@ Android nemohl otevřít obraz v obraze. Další Upravit grafiku + Odebrat ze skrytých + Synchronizace se Steamem se nezdařila. Zavřete Steam a zkuste to znovu. Ve Steamu Zkratka Přidat na domovskou obrazovku diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 0f6dc3fc44..ea39e14dea 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -203,6 +203,8 @@ 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. DroidDecks proot kunne ikke downloades. Tjek forbindelsen, og prøv igen. Sessionen blev ikke startet, fordi reserve-proot er for langsom at spille på. PowerVR-grafikmiljøet kunne ikke hentes. Tjek forbindelsen, og prøv igen. + Grafikmiljøet kunne ikke klargøres, så sessionen blev ikke startet. + Spilmiljøet kunne ikke sættes op, så sessionen blev ikke startet. DirectAudio kunne ikke downloades, så spillyd bruger den langsommere vej i denne session. Dette program Sessionen kunne ikke tegne på skærmen: %1$s. Denne skærm viser hvorfor i stedet for en sort skærm; sessionens logfiler indeholder detaljerne. @@ -1318,6 +1320,7 @@ Indtast adresse manuelt Fra en computer med ADB: Kopier kommando + Slut headsettet til en computer, og åbn SideQuest. Vælg “Run ADB Command” og derefter “Custom Command”, skriv kommandoen vist nedenfor, og vælg “Run Command”. Vælg, hvilken skærm Android-indstillinger skal åbnes på. Hovedskærm Parret. Finder porten for Trådløs fejlretning… @@ -1572,6 +1575,8 @@ Android kunne ikke åbne billede i billede. Mere Rediger grafik + Fjern fra skjulte + Kunne ikke synkronisere med Steam. Luk Steam og prøv igen. I Steam Genvej Tilføj til hjemmeskærm diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index e708522cc8..e8b4ccd022 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -203,6 +203,8 @@ 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. DroidDecks proot konnte nicht heruntergeladen werden. Prüfe die Verbindung und versuch es erneut. Die Sitzung wurde nicht gestartet, da das Ersatz-proot zum Spielen zu langsam ist. Die PowerVR-Grafikumgebung konnte nicht heruntergeladen werden. Prüfe die Verbindung und versuch es erneut. + Die Grafikumgebung konnte nicht vorbereitet werden, daher wurde die Sitzung nicht gestartet. + Die Spielumgebung konnte nicht eingerichtet werden, daher wurde die Sitzung nicht gestartet. DirectAudio konnte nicht heruntergeladen werden, daher nutzt der Spielton in dieser Sitzung den langsameren Weg. Dieses Programm Die Sitzung konnte nicht auf den Bildschirm zeichnen: %1$s. Auf diesem Bildschirm sehen Sie den Grund statt eines schwarzen Bildschirms; die Details finden Sie in den Sitzungsprotokollen. @@ -1310,6 +1312,7 @@ Adresse manuell eingeben Von einem Computer mit ADB: Befehl kopieren + Verbinde das Headset mit einem Computer und öffne SideQuest. Wähle „Run ADB Command“, dann „Custom Command“, tippe den unten gezeigten Befehl ein und wähle „Run Command“. Wähle, auf welchem Display die Android-Einstellungen geöffnet werden. Hauptbildschirm Gekoppelt. Suche den Port für Debugging über WLAN… @@ -1564,6 +1567,8 @@ Android konnte Bild im Bild nicht öffnen. Mehr Grafiken bearbeiten + Nicht mehr ausblenden + Synchronisierung mit Steam fehlgeschlagen. Schließe Steam und versuche es erneut. In Steam Verknüpfung Zum Startbildschirm hinzufügen diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index ab2c52fa52..42baf8965a 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -203,6 +203,8 @@ Αυτό το πρόγραμμα είναι χτισμένο για υπολογιστές %1$s και εκτελείται μέσω FEX, το οποίο δεν έχει ρυθμιστεί ακόμα. Ανοίξτε το Steam μία φορά ενώ είστε συνδεδεμένοι: το DroidDeck κάνει λήψη του FEX και του Steam Linux Runtime που χρειάζεται, και μετά αυτό ανοίγει. Δεν ήταν δυνατή η λήψη του proot του DroidDeck. Ελέγξτε τη σύνδεση και δοκιμάστε ξανά. Η συνεδρία δεν ξεκίνησε, επειδή το εναλλακτικό proot είναι πολύ αργό για παιχνίδι. Δεν ήταν δυνατή η λήψη του γραφικού περιβάλλοντος PowerVR. Ελέγξτε τη σύνδεση και δοκιμάστε ξανά. + Δεν ήταν δυνατή η προετοιμασία του γραφικού περιβάλλοντος, οπότε η συνεδρία δεν ξεκίνησε. + Δεν ήταν δυνατή η ρύθμιση του περιβάλλοντος του παιχνιδιού, οπότε η συνεδρία δεν ξεκίνησε. Δεν ήταν δυνατή η λήψη του DirectAudio, οπότε ο ήχος των παιχνιδιών χρησιμοποιεί την πιο αργή διαδρομή σε αυτή τη συνεδρία. Αυτό το πρόγραμμα Η συνεδρία δεν μπόρεσε να σχεδιάσει στην οθόνη: %1$s. Αυτή η οθόνη δείχνει τον λόγο αντί να είναι μαύρη· οι λεπτομέρειες βρίσκονται στα αρχεία καταγραφής της συνεδρίας. @@ -1318,6 +1320,7 @@ Μη αυτόματη εισαγωγή διεύθυνσης Από υπολογιστή με ADB: Αντιγραφή εντολής + Συνδέστε το headset σε υπολογιστή και ανοίξτε το SideQuest. Επιλέξτε «Run ADB Command», μετά «Custom Command», πληκτρολογήστε την εντολή που εμφανίζεται παρακάτω και επιλέξτε «Run Command». Επιλέξτε σε ποια οθόνη θα ανοίξουν οι Ρυθμίσεις Android. Κύρια οθόνη Έγινε σύζευξη. Αναζήτηση θύρας Ασύρματου εντοπισμού σφαλμάτων… @@ -1572,6 +1575,8 @@ Το Android δεν μπόρεσε να ανοίξει τη λειτουργία εικόνας εντός εικόνας. Περισσότερα Επεξεργασία εικαστικών + Κατάργηση από τις κρυφές + Αποτυχία συγχρονισμού με το Steam. Κλείστε το Steam και δοκιμάστε ξανά. Στο Steam Συντόμευση Προσθήκη στην αρχική οθόνη diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 9855649a1b..38ada10bda 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -203,6 +203,8 @@ 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á. No se ha podido descargar el proot de DroidDeck. Comprueba la conexión y vuelve a intentarlo. La sesión no se ha iniciado porque el proot alternativo es demasiado lento para jugar. No se pudo descargar el entorno gráfico de PowerVR. Comprueba la conexión e inténtalo de nuevo. + No se pudo preparar el entorno gráfico, así que la sesión no se inició. + No se pudo configurar el entorno del juego, así que la sesión no se inició. No se ha podido descargar DirectAudio, así que el audio de los juegos usa la ruta más lenta en esta sesión. Este programa La sesión no pudo dibujar en la pantalla: %1$s. En lugar de mostrarse una pantalla negra, esta pantalla explica el motivo; los registros de la sesión contienen los detalles. @@ -1325,6 +1327,7 @@ Introducir dirección manualmente Desde un ordenador con ADB: Copiar comando + Conecta el visor a un ordenador y abre SideQuest. Elige «Run ADB Command» y luego «Custom Command», escribe el comando que aparece abajo y selecciona «Run Command». Elige en qué pantalla abrir los Ajustes de Android. Pantalla principal Vinculado. Buscando el puerto de la Depuración inalámbrica… @@ -1580,6 +1583,8 @@ Android no pudo abrir imagen en imagen. Más Editar imágenes + Quitar de ocultas + No se pudo sincronizar con Steam. Cierra Steam e inténtalo de nuevo. En Steam Acceso directo Añadir a la pantalla de inicio diff --git a/app/src/main/res/values-fi/strings.xml b/app/src/main/res/values-fi/strings.xml index a3f72f20f8..b912a7cf0b 100644 --- a/app/src/main/res/values-fi/strings.xml +++ b/app/src/main/res/values-fi/strings.xml @@ -203,6 +203,8 @@ 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. DroidDeckin proota ei voitu ladata. Tarkista yhteys ja yritä uudelleen. Istuntoa ei käynnistetty, koska varaproot on liian hidas pelaamiseen. PowerVR-grafiikkaympäristöä ei voitu ladata. Tarkista yhteys ja yritä uudelleen. + Grafiikkaympäristöä ei voitu valmistella, joten istuntoa ei käynnistetty. + Peliympäristöä ei voitu määrittää, joten istuntoa ei käynnistetty. DirectAudiota ei voitu ladata, joten pelin ääni käyttää tässä istunnossa hitaampaa reittiä. Tämä ohjelma Istunto ei pystynyt piirtämään näytölle: %1$s. Mustan ruudun sijaan tämä näyttö kertoo syyn. Tarkemmat tiedot ovat istuntolokeissa. @@ -1318,6 +1320,7 @@ Syötä osoite manuaalisesti Tietokoneelta ADB:llä: Kopioi komento + Liitä lasit tietokoneeseen ja avaa SideQuest. Valitse ”Run ADB Command” ja sitten ”Custom Command”, kirjoita alla näkyvä komento ja valitse ”Run Command”. Valitse, millä näytöllä Android-asetukset avataan. Päänäyttö Pariutui. Etsitään Langattoman virheenkorjauksen porttia… @@ -1572,6 +1575,8 @@ Android ei pystynyt avaamaan kuva kuvassa -tilaa. Lisää Muokkaa kuvitusta + Poista piilotetuista + Synkronointi Steamin kanssa epäonnistui. Sulje Steam ja yritä uudelleen. Steamissa Pikakuvake Lisää aloitusnäytölle diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 22c0ea0e10..c889818314 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -203,6 +203,8 @@ 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. Impossible de télécharger le proot de DroidDeck. Vérifiez la connexion et réessayez. La session n\'a pas été démarrée, car le proot de secours est trop lent pour jouer. L\'environnement graphique PowerVR n\'a pas pu être téléchargé. Vérifiez la connexion et réessayez. + L\'environnement graphique n\'a pas pu être préparé, la session n\'a donc pas été lancée. + L\'environnement de jeu n\'a pas pu être configuré, la session n\'a donc pas été lancée. Impossible de télécharger DirectAudio ; l\'audio des jeux utilise le chemin plus lent pour cette session. Ce programme La session n\'a pas pu dessiner à l\'écran : %1$s. Cet écran affiche la raison au lieu d\'un écran noir ; les journaux de la session contiennent les détails. @@ -1324,6 +1326,7 @@ Saisir l\'adresse manuellement Utiliser ADB depuis un ordinateur : Copier la commande + Branchez le casque à un ordinateur et ouvrez SideQuest. Choisissez « Run ADB Command », puis « Custom Command », saisissez la commande affichée ci-dessous et sélectionnez « Run Command ». Choisissez l\'écran sur lequel ouvrir les paramètres Android. Écran principal Appairé. Recherche du port de débogage sans fil… @@ -1579,6 +1582,8 @@ Android ne peut pas ouvrir le mode PiP. Plus Modifier les illustrations + Ne plus masquer + Synchronisation avec Steam impossible. Fermez Steam et réessayez. Dans Steam Raccourci Ajouter à l\'écran d\'accueil diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xml index 8903487ab8..d26bbc324c 100644 --- a/app/src/main/res/values-hi/strings.xml +++ b/app/src/main/res/values-hi/strings.xml @@ -203,6 +203,8 @@ यह प्रोग्राम %1$s पीसी के लिए बना है और FEX के ज़रिए चलता है, जो अभी सेट नहीं है। साइन इन रहते हुए Steam एक बार खोलें: DroidDeck इससे FEX और ज़रूरी Steam Linux Runtime डाउनलोड करवा लेगा, फिर यह खुल जाएगा। DroidDeck का proot डाउनलोड नहीं हो सका। कनेक्शन जांचें और फिर कोशिश करें। सेशन शुरू नहीं किया गया, क्योंकि बैकअप proot खेलने के लिए बहुत धीमा है। PowerVR ग्राफ़िक्स एनवायरमेंट डाउनलोड नहीं हो सका। कनेक्शन जाँचें और फिर कोशिश करें। + ग्राफ़िक्स एनवायरमेंट तैयार नहीं हो सका, इसलिए सेशन शुरू नहीं हुआ। + गेम एनवायरमेंट सेट अप नहीं हो सका, इसलिए सेशन शुरू नहीं हुआ। DirectAudio डाउनलोड नहीं हो सका, इसलिए इस सेशन में गेम ऑडियो धीमा पाथ इस्तेमाल करता है। यह प्रोग्राम सत्र स्क्रीन पर ड्रॉ नहीं कर सका: %1$s। काली स्क्रीन के बजाय यह स्क्रीन कारण दिखाती है; पूरा विवरण सत्र लॉग में है। @@ -1318,6 +1320,7 @@ एड्रेस खुद डालें ADB वाले कंप्यूटर से: कमांड कॉपी करें + हेडसेट को कंप्यूटर से जोड़ें और SideQuest खोलें। “Run ADB Command”, फिर “Custom Command” चुनें, नीचे दिखाया गया कमांड टाइप करें और “Run Command” चुनें। Android Settings किस डिस्प्ले पर खोलना है चुनें। मुख्य स्क्रीन पेयर हो गया। वायरलेस डीबगिंग का पोर्ट खोजा जा रहा है… @@ -1572,6 +1575,8 @@ Android पिक्चर इन पिक्चर नहीं खोल सका। और आर्ट एडिट करें + छिपे हुए से हटाएं + Steam के साथ सिंक नहीं हो सका। Steam बंद करके फिर कोशिश करें। Steam में शॉर्टकट होम स्क्रीन पर जोड़ें diff --git a/app/src/main/res/values-hu/strings.xml b/app/src/main/res/values-hu/strings.xml index 482fc2a420..6563b39d2d 100644 --- a/app/src/main/res/values-hu/strings.xml +++ b/app/src/main/res/values-hu/strings.xml @@ -203,6 +203,8 @@ 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. A DroidDeck proot nem tölthető le. Ellenőrizze a kapcsolatot, és próbálja újra. A munkamenet nem indult el, mert a tartalék proot túl lassú a játékhoz. A PowerVR grafikus környezetet nem sikerült letölteni. Ellenőrizd a kapcsolatot, és próbáld újra. + A grafikus környezetet nem sikerült előkészíteni, ezért a munkamenet nem indult el. + A játékkörnyezetet nem sikerült beállítani, ezért a munkamenet nem indult el. A DirectAudio nem tölthető le, ezért a játékhang ebben a munkamenetben a lassabb útvonalat használja. Ez a program A munkamenet nem tudta megjeleníteni a képet a képernyőn: %1$s. Fekete képernyő helyett ez a képernyő mutatja az okot; a részletek a munkamenet naplóiban találhatók. @@ -1318,6 +1320,7 @@ Cím kézi megadása Egy ADB-vel rendelkező számítógépről: Parancs másolása + Csatlakoztasd a headsetet egy számítógéphez, és nyisd meg a SideQuestet. Válaszd a „Run ADB Command”, majd a „Custom Command” lehetőséget, írd be az alább látható parancsot, és válaszd a „Run Command” gombot. Válassza ki, melyik kijelzőn nyíljon meg az Android Beállítások. Fő képernyő Párosítva. A vezeték nélküli hibakeresés portjának keresése… @@ -1572,6 +1575,8 @@ Az Android nem tudta megnyitni a kép a képben módot. Továbbiak Illusztrációk szerkesztése + Eltávolítás a rejtettek közül + Nem sikerült szinkronizálni a Steammel. Zárd be a Steamet, és próbáld újra. A Steamben Parancsikon Hozzáadás a kezdőképernyőhöz diff --git a/app/src/main/res/values-in/strings.xml b/app/src/main/res/values-in/strings.xml index 3a7ec22277..1cc8c8a9c1 100644 --- a/app/src/main/res/values-in/strings.xml +++ b/app/src/main/res/values-in/strings.xml @@ -203,6 +203,8 @@ 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. proot DroidDeck tidak dapat diunduh. Periksa koneksi lalu coba lagi. Sesi tidak dimulai karena proot cadangan terlalu lambat untuk bermain. Lingkungan grafis PowerVR tidak dapat diunduh. Periksa koneksi dan coba lagi. + Lingkungan grafis tidak dapat disiapkan, jadi sesi tidak dimulai. + Lingkungan game tidak dapat disiapkan, jadi sesi tidak dimulai. DirectAudio tidak dapat diunduh, jadi audio gim menggunakan jalur yang lebih lambat di sesi ini. Program ini Sesi gagal menampilkan gambar ke layar: %1$s. Layar ini menunjukkan alasannya, bukan layar hitam; rinciannya ada di log sesi. @@ -1312,6 +1314,7 @@ Masukkan alamat secara manual Dari komputer dengan ADB: Salin perintah + Hubungkan headset ke komputer dan buka SideQuest. Pilih “Run ADB Command”, lalu “Custom Command”, ketik perintah yang ditampilkan di bawah, dan pilih “Run Command”. Pilih tampilan tempat membuka Setelan Android. Layar utama Berhasil dipasangkan. Mencari port Debugging nirkabel… @@ -1565,6 +1568,8 @@ Android tidak dapat membuka gambar dalam gambar. Lainnya Edit gambar + Hapus dari tersembunyi + Gagal menyinkronkan dengan Steam. Tutup Steam lalu coba lagi. Di Steam Pintasan Tambahkan ke layar utama diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 3fcd62bebe..296ea93f8d 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -203,6 +203,8 @@ 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à. Impossibile scaricare il proot di DroidDeck. Controlla la connessione e riprova. La sessione non è stata avviata perché il proot di riserva è troppo lento per giocare. Non è stato possibile scaricare l\'ambiente grafico PowerVR. Controlla la connessione e riprova. + Non è stato possibile preparare l\'ambiente grafico, quindi la sessione non è stata avviata. + Non è stato possibile configurare l\'ambiente di gioco, quindi la sessione non è stata avviata. Impossibile scaricare DirectAudio, quindi l\'audio dei giochi usa il percorso più lento in questa sessione. Questo programma La sessione non è riuscita a disegnare sullo schermo: %1$s. Questa schermata mostra il motivo al posto di una schermata nera; i log della sessione contengono i dettagli. @@ -1316,6 +1318,7 @@ Inserisci l\'indirizzo manualmente Da un computer con ADB: Copia comando + Collega il visore a un computer e apri SideQuest. Scegli “Run ADB Command”, poi “Custom Command”, digita il comando mostrato sotto e seleziona “Run Command”. Scegli su quale schermo aprire le Impostazioni di Android. Schermo principale Accoppiato. Ricerca della porta del Debug wireless… @@ -1571,6 +1574,8 @@ Android non è riuscito ad aprire il picture in picture. Altro Modifica grafica + Rimuovi dai nascosti + Impossibile sincronizzare con Steam. Chiudi Steam e riprova. In Steam Scorciatoia Aggiungi alla schermata Home diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 92dce25b1e..3a616a8570 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -203,6 +203,8 @@ このプログラムは%1$s PC向けにビルドされており、FEX経由で実行されますが、FEXはまだセットアップされていません。ログインした状態で一度Steamを開いてください。DroidDeckがFEXと必要なSteam Linux Runtimeをダウンロードした後、このプログラムが開きます。 DroidDeckのprootをダウンロードできませんでした。接続を確認して、もう一度お試しください。代替のprootではプレイするには遅すぎるため、セッションは開始されませんでした。 PowerVRのグラフィックス環境をダウンロードできませんでした。接続を確認して、もう一度お試しください。 + グラフィックス環境を準備できなかったため、セッションを開始しませんでした。 + ゲーム環境を設定できなかったため、セッションを開始しませんでした。 DirectAudioをダウンロードできなかったため、このセッションではゲーム音声に低速な経路を使用します。 このプログラム セッションが画面に描画できませんでした: %1$s。黒い画面の代わりに、この画面で理由を表示しています。詳細はセッションログにあります。 @@ -1312,6 +1314,7 @@ 手動でアドレスを入力 PCでADBを使用: コマンドをコピー + ヘッドセットをパソコンにつないで SideQuest を開きます。「Run ADB Command」→「Custom Command」を選び、下に表示されたコマンドを入力して「Run Command」を選びます。 Android設定をどの画面で開くか選択してください。 メイン画面 ペアリング済み。ワイヤレスデバッグのポートを検索中… @@ -1565,6 +1568,8 @@ Androidがピクチャーインピクチャーを開けませんでした。 その他 アートを編集 + 非表示を解除 + Steamと同期できませんでした。Steamを終了してもう一度お試しください。 Steamに追加済み ショートカット ホーム画面に追加 diff --git a/app/src/main/res/values-ko/strings.xml b/app/src/main/res/values-ko/strings.xml index 2a5e900ad3..78182d217a 100644 --- a/app/src/main/res/values-ko/strings.xml +++ b/app/src/main/res/values-ko/strings.xml @@ -203,6 +203,8 @@ 이 프로그램은 %1$s PC용으로 빌드되어 FEX를 통해 실행되지만, FEX가 아직 설정되지 않았습니다. 로그인한 상태로 Steam을 한 번 열면 DroidDeck이 FEX와 필요한 Steam Linux Runtime을 다운로드한 후 이 프로그램을 엽니다. DroidDeck의 proot를 다운로드할 수 없습니다. 연결을 확인하고 다시 시도하세요. 대체 proot는 플레이하기에 너무 느리므로 세션을 시작하지 않았습니다. PowerVR 그래픽 환경을 다운로드하지 못했습니다. 연결을 확인하고 다시 시도하세요. + 그래픽 환경을 준비하지 못해 세션을 시작하지 않았습니다. + 게임 환경을 설정하지 못해 세션을 시작하지 않았습니다. DirectAudio를 다운로드할 수 없어 이번 세션에서는 게임 오디오가 더 느린 경로를 사용합니다. 이 프로그램 세션이 화면을 그리지 못했습니다: %1$s. 검은 화면 대신 이 화면에 이유를 표시합니다. 자세한 내용은 세션 로그에 있습니다. @@ -1312,6 +1314,7 @@ 수동으로 주소 입력 PC에서 ADB 사용: 명령 복사 + 헤드셋을 컴퓨터에 연결하고 SideQuest를 엽니다. “Run ADB Command”, “Custom Command”를 차례로 선택하고 아래에 표시된 명령을 입력한 뒤 “Run Command”를 선택하세요. Android 설정을 어느 화면에서 열지 선택하세요. 메인 화면 페어링됨. 무선 디버깅 포트를 찾는 중… @@ -1565,6 +1568,8 @@ Android에서 PIP를 열 수 없습니다. 더보기 아트 편집 + 숨김 해제 + Steam과 동기화하지 못했습니다. Steam을 종료한 후 다시 시도하세요. Steam에 있음 바로 가기 홈 화면에 추가 diff --git a/app/src/main/res/values-ms/strings.xml b/app/src/main/res/values-ms/strings.xml index dad7152e60..8ac9fe26ef 100644 --- a/app/src/main/res/values-ms/strings.xml +++ b/app/src/main/res/values-ms/strings.xml @@ -203,6 +203,8 @@ 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. proot DroidDeck tidak dapat dimuat turun. Semak sambungan dan cuba lagi. Sesi tidak dimulakan kerana proot sandaran terlalu perlahan untuk bermain. Persekitaran grafik PowerVR tidak dapat dimuat turun. Semak sambungan dan cuba lagi. + Persekitaran grafik tidak dapat disediakan, jadi sesi tidak dimulakan. + Persekitaran permainan tidak dapat disediakan, jadi sesi tidak dimulakan. DirectAudio tidak dapat dimuat turun, jadi audio permainan menggunakan laluan yang lebih perlahan untuk sesi ini. Program ini Sesi gagal melukis pada skrin: %1$s. Skrin ini menunjukkan sebabnya, bukannya skrin hitam; butiran ada dalam log sesi. @@ -1312,6 +1314,7 @@ Masukkan alamat secara manual Daripada komputer dengan ADB: Salin arahan + Sambungkan set kepala ke komputer dan buka SideQuest. Pilih “Run ADB Command”, kemudian “Custom Command”, taip perintah yang dipaparkan di bawah dan pilih “Run Command”. Pilih paparan mana untuk membuka Tetapan Android. Skrin utama Digandingkan. Mencari port Debugging Wayarles… @@ -1565,6 +1568,8 @@ Android tidak dapat membuka gambar dalam gambar. Lagi Sunting seni + Alih keluar daripada tersembunyi + Tidak dapat menyegerak dengan Steam. Tutup Steam dan cuba lagi. Dalam Steam Pintasan Tambah ke skrin utama diff --git a/app/src/main/res/values-nb/strings.xml b/app/src/main/res/values-nb/strings.xml index ac63235e69..dc2dc6ec18 100644 --- a/app/src/main/res/values-nb/strings.xml +++ b/app/src/main/res/values-nb/strings.xml @@ -203,6 +203,8 @@ 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. Kunne ikke laste ned DroidDecks proot. Sjekk tilkoblingen og prøv igjen. Sesjonen ble ikke startet, fordi reserve-proot er for treg til å spille på. PowerVR-grafikkmiljøet kunne ikke lastes ned. Sjekk tilkoblingen og prøv igjen. + Grafikkmiljøet kunne ikke klargjøres, så økten ble ikke startet. + Spillmiljøet kunne ikke settes opp, så økten ble ikke startet. Kunne ikke laste ned DirectAudio, så spillyd bruker den tregere veien i denne sesjonen. Dette programmet Økten kunne ikke tegne på skjermen: %1$s. Denne skjermen viser hvorfor i stedet for en svart skjerm; detaljene finnes i loggene for økten. @@ -1318,6 +1320,7 @@ Skriv inn adresse manuelt Fra en datamaskin med ADB: Kopier kommando + Koble headsettet til en datamaskin og åpne SideQuest. Velg «Run ADB Command», deretter «Custom Command», skriv inn kommandoen vist nedenfor og velg «Run Command». Velg hvilken skjerm Android-innstillinger skal åpnes på. Hovedskjerm Koblet sammen. Finner porten for trådløs feilsøking… @@ -1572,6 +1575,8 @@ Android kunne ikke åpne bilde-i-bilde. Mer Rediger grafikk + Fjern fra skjulte + Kunne ikke synkronisere med Steam. Lukk Steam og prøv igjen. I Steam Snarvei Legg til på hjem-skjermen diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 92815ade36..1ae36c1cad 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -203,6 +203,8 @@ 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. De proot van DroidDeck kon niet worden gedownload. Controleer de verbinding en probeer het opnieuw. De sessie is niet gestart, omdat de reserve-proot te traag is om op te spelen. De PowerVR-grafische omgeving kon niet worden gedownload. Controleer de verbinding en probeer het opnieuw. + De grafische omgeving kon niet worden voorbereid, dus de sessie is niet gestart. + De spelomgeving kon niet worden ingesteld, dus de sessie is niet gestart. DirectAudio kon niet worden gedownload, dus gamegeluid gebruikt deze sessie de tragere route. Dit programma De sessie kon niet op het scherm tekenen: %1$s. Dit scherm laat zien waarom, in plaats van een zwart scherm; de details staan in de sessielogboeken. @@ -1318,6 +1320,7 @@ Adres handmatig invoeren Vanaf een computer met ADB: Opdracht kopiëren + Sluit de headset aan op een computer en open SideQuest. Kies ‘Run ADB Command’ en dan ‘Custom Command’, typ de hieronder getoonde opdracht en selecteer ‘Run Command’. Kies op welk scherm Android-instellingen wordt geopend. Hoofdscherm Gekoppeld. Poort van Draadloos debuggen zoeken… @@ -1572,6 +1575,8 @@ Android kon scherm-in-scherm niet openen. Meer Afbeeldingen bewerken + Niet meer verbergen + Synchroniseren met Steam is mislukt. Sluit Steam en probeer het opnieuw. In Steam Snelkoppeling Toevoegen aan startscherm diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 3a57ee94a6..dd47a73b5d 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -203,6 +203,8 @@ 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. Nie udało się pobrać proot DroidDeck. Sprawdź połączenie i spróbuj ponownie. Sesja nie została uruchomiona, bo zapasowy proot jest zbyt wolny do grania. Nie udało się pobrać środowiska graficznego PowerVR. Sprawdź połączenie i spróbuj ponownie. + Nie udało się przygotować środowiska graficznego, więc sesja nie została uruchomiona. + Nie udało się skonfigurować środowiska gry, więc sesja nie została uruchomiona. Nie udało się pobrać DirectAudio, więc w tej sesji dźwięk gier używa wolniejszej ścieżki. Ten program Sesja nie mogła wyświetlić obrazu na ekranie: %1$s. Ten ekran pokazuje przyczynę zamiast czarnego obrazu; szczegóły znajdują się w logach sesji. @@ -1332,6 +1334,7 @@ Wpisz adres ręcznie Z komputera z ADB: Kopiuj polecenie + Podłącz gogle do komputera i otwórz SideQuest. Wybierz „Run ADB Command”, potem „Custom Command”, wpisz polecenie widoczne poniżej i wybierz „Run Command”. Wybierz, na którym ekranie otworzyć Ustawienia Androida. Ekran główny Sparowano. Wyszukiwanie portu debugowania bezprzewodowego… @@ -1588,6 +1591,8 @@ Android nie mógł otworzyć obrazu w obrazie. Więcej Edytuj grafiki + Usuń z ukrytych + Nie udało się zsynchronizować ze Steamem. Zamknij Steama i spróbuj ponownie. W Steam Skrót Dodaj do ekranu głównego diff --git a/app/src/main/res/values-pt-rPT/strings.xml b/app/src/main/res/values-pt-rPT/strings.xml index 5b37d1f37d..fdb7974b59 100644 --- a/app/src/main/res/values-pt-rPT/strings.xml +++ b/app/src/main/res/values-pt-rPT/strings.xml @@ -203,6 +203,8 @@ 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. Não foi possível transferir o proot do DroidDeck. Verifique a ligação e tente novamente. A sessão não foi iniciada, porque o proot alternativo é demasiado lento para jogar. Não foi possível transferir o ambiente gráfico PowerVR. Verifique a ligação e tente novamente. + Não foi possível preparar o ambiente gráfico, pelo que a sessão não foi iniciada. + Não foi possível configurar o ambiente do jogo, pelo que a sessão não foi iniciada. Não foi possível transferir o DirectAudio, por isso o áudio dos jogos utiliza o caminho mais lento nesta sessão. Este programa A sessão não conseguiu desenhar no ecrã: %1$s. Este ecrã mostra o motivo em vez de um ecrã preto; os registos da sessão têm os detalhes. @@ -1316,6 +1318,7 @@ Introduzir endereço manualmente A partir de um computador com ADB: Copiar comando + Ligue os óculos a um computador e abra o SideQuest. Escolha “Run ADB Command”, depois “Custom Command”, escreva o comando apresentado abaixo e selecione “Run Command”. Escolha em que ecrã abrir as Definições do Android. Ecrã principal Sincronizado. A procurar a porta da Depuração sem fios… @@ -1571,6 +1574,8 @@ O Android não conseguiu abrir o ecrã no ecrã. Mais Editar imagens + Remover dos ocultos + Não foi possível sincronizar com o Steam. Feche o Steam e tente novamente. No Steam Atalho Adicionar ao ecrã principal diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 09dbde1188..d29261a8a7 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -203,6 +203,8 @@ 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. Não foi possível baixar o proot do DroidDeck. Verifique a conexão e tente novamente. A sessão não foi iniciada, porque o proot alternativo é lento demais para jogar. Não foi possível baixar o ambiente gráfico PowerVR. Verifique a conexão e tente novamente. + Não foi possível preparar o ambiente gráfico, então a sessão não foi iniciada. + Não foi possível configurar o ambiente do jogo, então a sessão não foi iniciada. Não foi possível baixar o DirectAudio, então o áudio dos jogos usa o caminho mais lento nesta sessão. Este programa A sessão não conseguiu desenhar na tela: %1$s. Esta tela mostra o motivo no lugar de uma tela preta; os logs da sessão trazem os detalhes. @@ -1324,6 +1326,7 @@ Digitar endereço manualmente De um computador com ADB: Copiar comando + Conecte o headset a um computador e abra o SideQuest. Escolha “Run ADB Command”, depois “Custom Command”, digite o comando mostrado abaixo e selecione “Run Command”. Escolha em qual tela abrir as Configurações do Android. Tela principal Pareado. Procurando a porta da Depuração por Wi-Fi… @@ -1579,6 +1582,8 @@ O Android não conseguiu abrir o picture-in-picture. Mais Editar artes + Remover dos ocultos + Não foi possível sincronizar com o Steam. Feche o Steam e tente novamente. Na Steam Atalho Adicionar à tela inicial diff --git a/app/src/main/res/values-ro/input_library.xml b/app/src/main/res/values-ro/input_library.xml index e277e65abf..5a3648d509 100644 --- a/app/src/main/res/values-ro/input_library.xml +++ b/app/src/main/res/values-ro/input_library.xml @@ -29,7 +29,7 @@ Cruce Trăgaci Gata - Anulează + Anulează ultima acțiune + Adaugă Trage pentru a muta. Trage de un colț pentru a redimensiona. Atinge Proprietăți pentru a atribui o acțiune. Editare pe ecranul secundar diff --git a/app/src/main/res/values-ro/strings.xml b/app/src/main/res/values-ro/strings.xml index c8c259c6d8..fff6f62692 100644 --- a/app/src/main/res/values-ro/strings.xml +++ b/app/src/main/res/values-ro/strings.xml @@ -203,6 +203,8 @@ 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. Proot-ul DroidDeck nu a putut fi descărcat. Verifică conexiunea și încearcă din nou. Sesiunea nu a fost pornită, deoarece proot-ul de rezervă este prea lent pentru jocuri. Mediul grafic PowerVR nu a putut fi descărcat. Verifică conexiunea și încearcă din nou. + Mediul grafic nu a putut fi pregătit, așa că sesiunea nu a pornit. + Mediul jocului nu a putut fi configurat, așa că sesiunea nu a pornit. DirectAudio nu a putut fi descărcat, așa că sunetul jocurilor folosește calea mai lentă în această sesiune. Acest program Sesiunea nu a putut reda pe ecran: %1$s. Acest ecran arată motivul în locul unui ecran negru; detaliile sunt în jurnalele sesiunii. @@ -1325,6 +1327,7 @@ Introdu adresa manual De pe un computer cu ADB: Copiază comanda + Conectează căștile la un computer și deschide SideQuest. Alege „Run ADB Command”, apoi „Custom Command”, scrie comanda afișată mai jos și selectează „Run Command”. Alege pe care afișaj se deschid Setările Android. Ecranul principal Asociat. Se caută portul de Depanare wireless… @@ -1580,6 +1583,8 @@ Android nu a putut deschide imaginea în imagine. Mai multe Editează grafica + Elimină din ascunse + Nu s-a putut sincroniza cu Steam. Închide Steam și încearcă din nou. În Steam Comandă rapidă Adaugă pe ecranul principal diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index d708e3980e..c1e27d2a5a 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -203,6 +203,8 @@ Эта программа собрана для ПК на %1$s и работает через FEX, который еще не настроен. Откройте Steam один раз, войдя в аккаунт: DroidDeck скачает через него FEX и нужную Steam Linux Runtime, после чего программа откроется. Не удалось скачать proot DroidDeck. Проверьте подключение и повторите попытку. Сессия не запущена, так как резервный proot слишком медленный для игры. Не удалось скачать графическую среду PowerVR. Проверьте подключение и повторите попытку. + Не удалось подготовить графическую среду, поэтому сеанс не запущен. + Не удалось настроить игровую среду, поэтому сеанс не запущен. Не удалось скачать DirectAudio, поэтому в этой сессии звук игр идёт по более медленному пути. Эта программа Сеансу не удалось вывести изображение на экран: %1$s. Вместо чёрного экрана здесь показана причина; подробности в журналах сеанса. @@ -1332,6 +1334,7 @@ Ввести адрес вручную С компьютера через ADB: Копировать команду + Подключите шлем к компьютеру и откройте SideQuest. Выберите «Run ADB Command», затем «Custom Command», введите команду, показанную ниже, и нажмите «Run Command». Выберите экран для открытия настроек Android. Главный экран Сопряжено. Поиск порта отладки по Wi-Fi… @@ -1588,6 +1591,8 @@ Android не может открыть PiP. Ещё Изменить обложку + Убрать из скрытых + Не удалось синхронизировать со Steam. Закройте Steam и повторите попытку. В Steam Ярлык Добавить на главный экран diff --git a/app/src/main/res/values-sv/strings.xml b/app/src/main/res/values-sv/strings.xml index 3afaf1ca1a..f2732a0c90 100644 --- a/app/src/main/res/values-sv/strings.xml +++ b/app/src/main/res/values-sv/strings.xml @@ -203,6 +203,8 @@ 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 gick inte att ladda ned DroidDecks proot. Kontrollera anslutningen och försök igen. Sessionen startades inte eftersom reserv-proot är för långsam att spela på. PowerVR-grafikmiljön kunde inte laddas ned. Kontrollera anslutningen och försök igen. + Grafikmiljön kunde inte förberedas, så sessionen startades inte. + Spelmiljön kunde inte konfigureras, så sessionen startades inte. Det gick inte att ladda ned DirectAudio, så spelljudet använder den långsammare vägen den här sessionen. Det här programmet Sessionen kunde inte rita på skärmen: %1$s. Den här skärmen visar orsaken i stället för att vara svart; detaljerna finns i sessionsloggarna. @@ -1318,6 +1320,7 @@ Ange adress manuellt Från en dator med ADB: Kopiera kommando + Anslut headsetet till en dator och öppna SideQuest. Välj ”Run ADB Command” och sedan ”Custom Command”, skriv in kommandot som visas nedan och välj ”Run Command”. Välj vilken skärm Android-inställningar ska öppnas på. Huvudskärm Ihopkopplad. Letar efter porten för Trådlös felsökning… @@ -1572,6 +1575,8 @@ Android kunde inte öppna bild-i-bild. Mer Redigera grafik + Ta bort från dolda + Kunde inte synkronisera med Steam. Stäng Steam och försök igen. I Steam Genväg Lägg till på hemskärmen diff --git a/app/src/main/res/values-th/strings.xml b/app/src/main/res/values-th/strings.xml index 0935269c42..89147a62cf 100644 --- a/app/src/main/res/values-th/strings.xml +++ b/app/src/main/res/values-th/strings.xml @@ -203,6 +203,8 @@ โปรแกรมนี้สร้างมาสำหรับพีซี %1$s และรันผ่าน FEX ซึ่งยังไม่ได้ตั้งค่า เปิด Steam สักครั้งขณะลงชื่อเข้าใช้: DroidDeck จะดาวน์โหลด FEX และ Steam Linux Runtime ที่จำเป็น จากนั้นโปรแกรมนี้จะเปิดขึ้น ดาวน์โหลด proot ของ DroidDeck ไม่ได้ ตรวจสอบการเชื่อมต่อแล้วลองใหม่ เซสชันไม่ได้เริ่มเพราะ proot สำรองช้าเกินกว่าจะเล่นได้ ดาวน์โหลดสภาพแวดล้อมกราฟิก PowerVR ไม่สำเร็จ ตรวจสอบการเชื่อมต่อแล้วลองอีกครั้ง + เตรียมสภาพแวดล้อมกราฟิกไม่สำเร็จ จึงไม่ได้เริ่มเซสชัน + ตั้งค่าสภาพแวดล้อมของเกมไม่สำเร็จ จึงไม่ได้เริ่มเซสชัน ดาวน์โหลด DirectAudio ไม่ได้ เสียงเกมในเซสชันนี้จึงใช้เส้นทางที่ช้ากว่า โปรแกรมนี้ เซสชันไม่สามารถแสดงผลบนหน้าจอได้: %1$s หน้าจอนี้แสดงสาเหตุแทนที่จะเป็นหน้าจอสีดำ รายละเอียดอยู่ในบันทึกของเซสชัน @@ -1312,6 +1314,7 @@ กรอกที่อยู่ด้วยตัวเอง จากคอมพิวเตอร์ที่มี ADB: คัดลอกคำสั่ง + เชื่อมต่อแว่นกับคอมพิวเตอร์แล้วเปิด SideQuest เลือก “Run ADB Command” จากนั้น “Custom Command” พิมพ์คำสั่งที่แสดงด้านล่างแล้วเลือก “Run Command” เลือกหน้าจอที่จะเปิดการตั้งค่า Android หน้าจอหลัก จับคู่แล้ว กำลังค้นหาพอร์ตของ Wireless debugging… @@ -1565,6 +1568,8 @@ Android ไม่สามารถเปิดภาพซ้อนภาพได้ เพิ่มเติม แก้ไขภาพปก + นำออกจากที่ซ่อนไว้ + ซิงค์กับ Steam ไม่สำเร็จ ปิด Steam แล้วลองอีกครั้ง ใน Steam ช็อตคัต เพิ่มไปยังหน้าจอหลัก diff --git a/app/src/main/res/values-tr/strings.xml b/app/src/main/res/values-tr/strings.xml index fd890e2b3e..84ccc32c35 100644 --- a/app/src/main/res/values-tr/strings.xml +++ b/app/src/main/res/values-tr/strings.xml @@ -203,6 +203,8 @@ 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. DroidDeck\'in proot\'u indirilemedi. Bağlantıyı kontrol edip tekrar deneyin. Yedek proot oynamak için fazla yavaş olduğundan oturum başlatılmadı. PowerVR grafik ortamı indirilemedi. Bağlantıyı kontrol edip tekrar deneyin. + Grafik ortamı hazırlanamadı, bu yüzden oturum başlatılmadı. + Oyun ortamı ayarlanamadı, bu yüzden oturum başlatılmadı. DirectAudio indirilemedi, bu yüzden oyun sesi bu oturumda daha yavaş yolu kullanıyor. Bu program Oturum ekrana görüntü çizemedi: %1$s. Bu ekran, siyah bir ekran yerine nedenini gösteriyor; ayrıntılar oturum günlüklerinde. @@ -1310,6 +1312,7 @@ Adresi elle girin ADB\'li bir bilgisayardan: Komutu kopyala + Başlığı bir bilgisayara bağlayın ve SideQuest’i açın. “Run ADB Command”, ardından “Custom Command” seçin, aşağıda gösterilen komutu yazın ve “Run Command” seçin. Android Ayarları\'nın hangi ekranda açılacağını seçin. Ana ekran Eşleşti. Kablosuz hata ayıklama bağlantı noktası bulunuyor… @@ -1564,6 +1567,8 @@ Android, pencere içinde pencereyi açamadı. Diğer Görseli düzenle + Gizlilikten çıkar + Steam ile senkronize edilemedi. Steam\'i kapatıp tekrar deneyin. Steam\'de Kısayol Ana ekrana ekle diff --git a/app/src/main/res/values-uk/input_library.xml b/app/src/main/res/values-uk/input_library.xml index c00c0b1a39..f2504dde51 100644 --- a/app/src/main/res/values-uk/input_library.xml +++ b/app/src/main/res/values-uk/input_library.xml @@ -29,7 +29,7 @@ Хрестовина Тригер Готово - Скасувати + Скасувати дію + Додати Перетягніть, щоб перемістити. Потягніть за кут, щоб змінити розмір. Торкніться «Властивості», щоб призначити дію. Редагування на другому екрані diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 09d8f3720e..17d3a83830 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -203,6 +203,8 @@ Цю програму зібрано для ПК з архітектурою %1$s, і вона працює через FEX, який ще не налаштовано. Один раз відкрийте Steam, увійшовши в обліковий запис: DroidDeck завантажить FEX і потрібний йому Steam Linux Runtime, після чого програма відкриється. Не вдалося завантажити proot DroidDeck. Перевірте зʼєднання та спробуйте ще раз. Сеанс не запущено, бо резервний proot занадто повільний для гри. Не вдалося завантажити графічне середовище PowerVR. Перевірте підключення й повторіть спробу. + Не вдалося підготувати графічне середовище, тому сеанс не запущено. + Не вдалося налаштувати ігрове середовище, тому сеанс не запущено. Не вдалося завантажити DirectAudio, тому в цьому сеансі звук ігор іде повільнішим шляхом. Ця програма Сеанс не зміг вивести зображення на екран: %1$s. Замість чорного екрана тут показано причину; подробиці — у журналах сеансу. @@ -1332,6 +1334,7 @@ Ввести адресу вручну З комп’ютера з ADB: Копіювати команду + Підключіть шолом до комп’ютера й відкрийте SideQuest. Виберіть «Run ADB Command», потім «Custom Command», введіть команду, показану нижче, і виберіть «Run Command». Виберіть, на якому екрані відкрити налаштування Android. Головний екран Поєднано. Пошук порту бездротового налагодження… @@ -1588,6 +1591,8 @@ Android не вдалося відкрити режим «Картинка в картинці». Більше Змінити обкладинку + Прибрати з прихованих + Не вдалося синхронізувати зі Steam. Закрийте Steam і спробуйте ще раз. У Steam Ярлик Додати на головний екран diff --git a/app/src/main/res/values-vi/strings.xml b/app/src/main/res/values-vi/strings.xml index 4ca053aa28..34ec1d90bc 100644 --- a/app/src/main/res/values-vi/strings.xml +++ b/app/src/main/res/values-vi/strings.xml @@ -203,6 +203,8 @@ 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ở. Không thể tải proot của DroidDeck. Hãy kiểm tra kết nối rồi thử lại. Phiên chưa được khởi động vì proot dự phòng quá chậm để chơi. Không thể tải môi trường đồ họa PowerVR. Hãy kiểm tra kết nối rồi thử lại. + Không thể chuẩn bị môi trường đồ họa nên phiên chưa được khởi động. + Không thể thiết lập môi trường trò chơi nên phiên chưa được khởi động. Không thể tải DirectAudio, nên âm thanh game dùng đường chậm hơn trong phiên này. Chương trình này Phiên không thể vẽ lên màn hình: %1$s. Màn hình này cho biết lý do thay vì màn hình đen; chi tiết nằm trong nhật ký phiên. @@ -1312,6 +1314,7 @@ Nhập địa chỉ thủ công Từ một máy tính có ADB: Sao chép lệnh + Kết nối kính với máy tính và mở SideQuest. Chọn “Run ADB Command”, rồi “Custom Command”, nhập lệnh hiển thị bên dưới và chọn “Run Command”. Chọn màn hình để mở Android Settings. Màn hình chính Đã ghép nối. Đang tìm cổng Gỡ lỗi qua mạng không dây… @@ -1565,6 +1568,8 @@ Android không thể mở hình trong hình. Thêm Sửa ảnh bìa + Bỏ ẩn + Không thể đồng bộ với Steam. Hãy đóng Steam rồi thử lại. Trong Steam Shortcut Thêm vào màn hình chính diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml index 97f5b03c51..aa10c5ccf6 100644 --- a/app/src/main/res/values-zh-rCN/strings.xml +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -203,6 +203,8 @@ 此程序面向 %1$s PC 构建,需经由 FEX 运行,而 FEX 尚未配置。请在登录状态下打开一次 Steam:DroidDeck 会让其下载 FEX 及所需的 Steam Linux Runtime,之后即可打开。 无法下载 DroidDeck 的 proot。请检查网络连接后重试。由于备用 proot 太慢无法流畅游玩,会话未启动。 无法下载 PowerVR 图形环境。请检查网络连接后重试。 + 无法准备图形环境,因此未启动会话。 + 无法设置游戏环境,因此未启动会话。 无法下载 DirectAudio,本次会话的游戏音频将使用较慢的路径。 此程序 会话无法向屏幕绘制画面:%1$s。此界面显示原因而非黑屏;详情见会话日志。 @@ -1395,6 +1397,7 @@ 手动输入地址 通过装有 ADB 的电脑: 复制命令 + 将头显连接到电脑并打开 SideQuest。依次选择“Run ADB Command”和“Custom Command”,输入下方显示的命令,然后选择“Run Command”。 选择在哪个屏幕上打开 Android 设置。 主屏幕 已配对。正在查找无线调试端口… @@ -1648,6 +1651,8 @@ Android 无法打开画中画。 更多 编辑封面 + 取消隐藏 + 无法与 Steam 同步。请关闭 Steam 后重试。 已在 Steam 中 快捷方式 添加到主屏幕 diff --git a/app/src/main/res/values-zh-rHK/strings.xml b/app/src/main/res/values-zh-rHK/strings.xml index ada736fa81..d86325fe04 100644 --- a/app/src/main/res/values-zh-rHK/strings.xml +++ b/app/src/main/res/values-zh-rHK/strings.xml @@ -203,6 +203,8 @@ 此程式是為 %1$s 電腦而設,需透過 FEX 執行,但 FEX 尚未設定。請在登入狀態下開啟一次 Steam:DroidDeck 會讓它下載 FEX 及所需的 Steam Linux Runtime,之後便會開啟此程式。 無法下載 DroidDeck 的 proot。請檢查連線後再試一次。會話未啟動,因為備用 proot 太慢,無法用來玩遊戲。 無法下載 PowerVR 圖形環境。請檢查網絡連線後再試。 + 無法準備圖形環境,因此未有啟動工作階段。 + 無法設定遊戲環境,因此未有啟動工作階段。 無法下載 DirectAudio,因此本次會話的遊戲音訊會使用較慢的路徑。 此程式 工作階段無法把畫面繪製到螢幕:%1$s。這個畫面會顯示原因,而不是黑畫面;詳情載於工作階段記錄。 @@ -1311,6 +1313,7 @@ 手動輸入位址 在已安裝 ADB 的電腦上: 複製指令 + 將頭戴裝置連接到電腦並開啟 SideQuest。依次選擇「Run ADB Command」和「Custom Command」,輸入下方顯示的指令,然後選擇「Run Command」。 選擇要在哪個螢幕開啟 Android 設定。 主螢幕 已配對,正在尋找無線偵錯連接埠… @@ -1564,6 +1567,8 @@ Android 無法開啟畫中畫。 更多 編輯圖片 + 取消隱藏 + 無法與 Steam 同步。請關閉 Steam 後再試。 在 Steam 中 捷徑 加至主畫面 diff --git a/app/src/main/res/values-zh-rTW/strings.xml b/app/src/main/res/values-zh-rTW/strings.xml index e32b9a76e6..cb8df3aec8 100644 --- a/app/src/main/res/values-zh-rTW/strings.xml +++ b/app/src/main/res/values-zh-rTW/strings.xml @@ -203,6 +203,8 @@ 此程式是為 %1$s 電腦組建的,需透過 FEX 執行,但 FEX 尚未設定。請在登入狀態下開啟一次 Steam:DroidDeck 會讓它下載 FEX 和所需的 Steam Linux Runtime,之後就能開啟此程式。 無法下載 DroidDeck 的 proot。請檢查連線後再試一次。工作階段未啟動,因為備用 proot 太慢,無法用來玩遊戲。 無法下載 PowerVR 圖形環境。請檢查網路連線後再試。 + 無法準備圖形環境,因此未啟動工作階段。 + 無法設定遊戲環境,因此未啟動工作階段。 無法下載 DirectAudio,因此本次工作階段的遊戲音訊會使用較慢的路徑。 此程式 工作階段無法在螢幕上繪製畫面:%1$s。此畫面會顯示原因,而不是黑畫面;詳細資訊請見工作階段記錄。 @@ -1311,6 +1313,7 @@ 手動輸入位址 使用電腦上的 ADB: 複製指令 + 將頭戴裝置連接到電腦並開啟 SideQuest。依序選擇「Run ADB Command」和「Custom Command」,輸入下方顯示的指令,然後選擇「Run Command」。 選擇在哪個螢幕上開啟 Android 設定。 主螢幕 已配對。正在尋找無線偵錯連接埠… @@ -1564,6 +1567,8 @@ Android 無法開啟子母畫面。 更多 編輯圖片 + 取消隱藏 + 無法與 Steam 同步。請關閉 Steam 後再試。 在 Steam 中 捷徑 新增至主螢幕 diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 742061bba2..e697c0bb00 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -231,6 +231,8 @@ 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. DroidDeck\'s proot could not be downloaded. Check the connection and try again. The session was not started, because the fallback proot is too slow to play on. The PowerVR graphics runtime could not be downloaded. Check the connection and try again. + The graphics runtime could not be prepared, so the session was not started. + The game environment could not be set up, so the session was not started. DirectAudio could not be downloaded, so game audio uses the slower path this session. This program The session could not draw to the screen: %1$s. This screen shows why instead of a black one; the session logs have the details. @@ -702,7 +704,7 @@ Its files are removed. It\'s in use, so the default takes over. Display Frame limit - Caps this game. The display switches to a refresh rate the cap divides evenly when it has one; other caps can look uneven. Steam games use Steam\'s Frame Limit in the Quick Access menu. + Remembered for this game, or for Desktop. The display switches to a refresh rate the cap divides evenly; other caps can look uneven. Black frame insertion Sharper motion: a black refresh follows every frame. Needs 100 Hz or more; the game runs at half the refresh rate and looks dimmer. Off while frame generation is on. Effects @@ -926,7 +928,7 @@ Controller Session Launcher - Setup + Settings ● All set %1$d of %2$d ready System check @@ -1238,6 +1240,15 @@ Add Dictate Stop dictating + Slide up to lock · left to cancel + Listening… + Set up talking to the agent + Close + Speech service + Speech Services by Google turns your voice into text + Microphone for DroidDeck + Microphone for the speech service + Permissions › Microphone › Allow DroidDeck needs the microphone to dictate Attach what the game shows Could not capture the game @@ -1245,6 +1256,7 @@ Agent finished Agent stopped with an error Agent has a question + Agent is waiting for your OK %d step %d steps @@ -1322,6 +1334,21 @@ Plan first Plan Proposes a plan without changing anything + Permissions + Ask first + Asks before edits and commands that need your OK + Accept edits + Edits files freely, asks before commands + Auto + A safety check decides, blocking risky actions + Don\'t ask + Denies anything your settings don\'t allow + Full access + Runs everything without asking + Allow %1$s? + Allow + Deny + +%1$d more Conversations No conversations yet Just now @@ -1372,10 +1399,13 @@ Sign in Free models Add key - Paste your API key from opencode.ai/auth + Paste your %1$s key + API key, if the server needs one + Server address, like 192.168.1.20:11434 + Get key Save - Free models, or a Zen key from opencode.ai/auth - Free models · add a Zen key for the rest + Free models, or a key from your provider + Free models · add a key for more PR #%1$d Not built for this copy of DroidDeck Updated %1$s @@ -1428,6 +1458,8 @@ Enter address manually From a computer with ADB: Copy command + SideQuest + Connect the headset to a computer and open SideQuest. Choose “Run ADB Command”, then “Custom Command”, type the command shown below and select “Run Command”. Choose which display to open Android Settings on. Main screen Paired. Finding the Wireless debugging port… @@ -1674,7 +1706,7 @@ Store Components Apps - Setup + Settings Updates More Edit tabs @@ -1743,6 +1775,8 @@ Android could not open picture in picture. More Edit art + Remove hidden + Couldn\'t sync with Steam. Close Steam and try again. In Steam Shortcut Add to home screen @@ -1755,6 +1789,7 @@ This game is no longer in your DroidDeck library. Stop the current session before launching a Steam game. Could not send the game to Steam. Try launching it again. + %1$s is a UWP app. This runtime has no Windows app-model host to start it. Retry removal Removing Removal incomplete @@ -2863,6 +2898,8 @@ Already up to date Sign in to the store to sync saves Saves were not synced + Some saves were not synced · %1$s + Cloud conflict · %1$d files · %2$s installed in your library store @@ -2976,6 +3013,9 @@ Close Try again Finishing sign-in… + This Microsoft account is at its device limit. Remove an old device under Manage devices, then resume. + Manage devices + Microsoft does not license any available version of this game to this device. Microsoft rejected the Xbox sign-in. Sign out of Xbox in Stores, sign in again, then resume. The sign-in page could not be loaded: %1$s This provider refuses to sign in from an embedded page. Sign in with your store password instead. @@ -4217,4 +4257,46 @@ %1$d of %2$d Press back once more to exit Integer + Performance + Android memory + Search settings + No setting matches \"%1$s\" + Clear search + Settings + In-game menu + Steam or Desktop options (swipe up) + Steam quick menu (•••) + Logs + Tabs + Storage + Syncthing + Download settings + Developer tools + Agent, graphics logs and other tools for testing DroidDeck + Options + Steam defaults · used each time Steam starts + Desktop defaults · used each time Desktop starts + Defaults · used each time this mode starts + All settings + Applies to every mode + Set in Steam + Steam games use the Frame Limit in Steam\'s quick menu › Performance + Open + Report a problem + Shares this session\'s logs for a bug report + Back opens this menu · Back twice opens Steam\'s menu + Back opens this menu + %1$s opens this menu + Back twice opens this menu · Back once opens Steam\'s menu + Corner tap opens this menu + Double-tap the top-right corner, for devices without a Back button + Open the session menu + Settings need you + Store accounts + Sign in + Sign out + Reset + Reset tabs + Steam, Desktop, Library, Downloads, Settings and Updates on the bar, the rest under More. + Your tab order and what sits under More or is hidden go back to the defaults. diff --git a/app/src/main/rust/stores/src/ubisoft/ffi.rs b/app/src/main/rust/stores/src/ubisoft/ffi.rs index 30df1ccd4f..9cfbb97801 100644 --- a/app/src/main/rust/stores/src/ubisoft/ffi.rs +++ b/app/src/main/rust/stores/src/ubisoft/ffi.rs @@ -75,6 +75,33 @@ fn denuvo(ticket: &str, session: &str, product: u32, challenge: &str) -> Result< }) } +fn cloud_urls(request: &serde_json::Value) -> Result { + let s = |k: &str| request.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string(); + let product = request.get("productId").and_then(|v| v.as_u64()).unwrap_or(0) as u32; + let method = match s("method").as_str() { + "put" => super::service::CLOUD_PUT, + "get" => super::service::CLOUD_GET, + other => return Err(format!("unknown cloud save method {other}")), + }; + let items: Vec = request.get("items").and_then(|v| v.as_array()).ok_or("no items")?.iter().map(|i| super::service::CloudItem { + name: i.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string(), + size: i.get("size").and_then(|v| v.as_u64()).unwrap_or(0), + md5_base64: i.get("md5").and_then(|v| v.as_str()).unwrap_or("").to_string(), + }).collect(); + if items.is_empty() || items.iter().any(|i| i.name.is_empty()) { + return Err("cloud save items need names".into()); + } + let (ticket, session) = (s("ticket"), s("sessionId")); + let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().map_err(|e| e.to_string())?; + rt.block_on(async { + let mut d = super::demux::Demux::connect(&ticket).await?; + let (mut ownership, _) = super::service::Ownership::open(&mut d, &ticket, &session).await?; + let token = ownership.token(&mut d, product).await?; + let signed = super::service::cloudsave_urls(&mut d, &token, product, method, &items).await?; + Ok(json!({ "requests": signed.iter().map(|r| json!({ "url": r.url, "header": r.header })).collect::>() })) + }) +} + fn call(op: &str, request: &str) -> String { let parsed: serde_json::Value = serde_json::from_str(request).unwrap_or(serde_json::Value::Null); let s = |k: &str| parsed.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string(); @@ -86,6 +113,7 @@ fn call(op: &str, request: &str) -> String { .and_then(|r| install::chunks(&r)) .map(|m| json!({ "chunks": install::chunks_json(&m.chunks), "setup": install::setup_json(&m) })) .unwrap_or_else(|e| json!({ "error": e })), + "cloud-urls" => cloud_urls(&parsed).unwrap_or_else(|e| json!({ "error": e })), "launch" => launch(&s("ticket"), &s("sessionId"), parsed.get("productId").and_then(|v| v.as_u64()).unwrap_or(0) as u32) .unwrap_or_else(|e| json!({ "error": e })), _ => json!({ "error": format!("unknown operation {op}") }), diff --git a/app/src/main/rust/stores/src/ubisoft/service.rs b/app/src/main/rust/stores/src/ubisoft/service.rs index bfdddc29a9..de8e724d09 100644 --- a/app/src/main/rust/stores/src/ubisoft/service.rs +++ b/app/src/main/rust/stores/src/ubisoft/service.rs @@ -204,3 +204,48 @@ pub async fn denuvo_token(d: &mut Demux, ownership_token: &str, challenge: &[u8] let t = pb::fields(pb::sub(&rsp, 3).ok_or("no game token answer")?)?; pb::sub(&t, 1).filter(|b| !b.is_empty()).map(<[u8]>::to_vec).ok_or_else(|| "Ubisoft sent an empty game token".into()) } + +pub struct CloudItem { + pub name: String, + pub size: u64, + pub md5_base64: String, +} + +pub struct SignedRequest { + pub header: String, + pub url: String, +} + +pub const CLOUD_PUT: u64 = 1; +pub const CLOUD_GET: u64 = 2; + +pub async fn cloudsave_urls(d: &mut Demux, ownership_token: &str, product_id: u32, method: u64, items: &[CloudItem]) -> Result, String> { + let conn = d.open("cloudsave_service").await?; + let mut req = Msg::new().text(1, ownership_token).uint(2, product_id as u64).uint(3, method); + for item in items { + let mut entry = Msg::new().text(1, &item.name); + if method == CLOUD_PUT { + entry = entry.msg(2, Msg::new().uint(1, item.size).text(2, &item.md5_base64)); + } + req = req.msg(4, entry); + } + let raw = d.call(conn, Msg::new().msg(1, Msg::new().uint(1, 1).msg(2, req))).await?; + let rsp = pb::fields(pb::sub(&pb::fields(&raw)?, 1).ok_or("no cloud save answer")?)?; + let urls = pb::fields(pb::sub(&rsp, 2).ok_or("no cloud save URLs")?)?; + let status = pb::num(&urls, 1).unwrap_or(0); + if status != 1 { + return Err(format!("Ubisoft's cloud save service refused the request (status {status})")); + } + let mut out = Vec::new(); + for r in pb::subs(&urls, 2) { + let r = pb::fields(r)?; + out.push(SignedRequest { + header: pb::string(&r, 1).unwrap_or_default(), + url: pb::string(&r, 2).ok_or("cloud save URL missing")?, + }); + } + if out.len() != items.len() { + return Err(format!("Ubisoft signed {} of {} cloud save requests", out.len(), items.len())); + } + Ok(out) +} diff --git a/app/src/test/java/com/droiddeck/launcher/DriverMenusAutoTest.kt b/app/src/test/java/com/droiddeck/launcher/DriverMenusAutoTest.kt index 923c1f41fd..98feec59bc 100644 --- a/app/src/test/java/com/droiddeck/launcher/DriverMenusAutoTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/DriverMenusAutoTest.kt @@ -8,6 +8,10 @@ import com.droiddeck.launcher.session.QuestExperimental import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.gpu.TpUbwcHint import com.droiddeck.launcher.gpu.TurnipDriver +import com.droiddeck.launcher.gpu.TurnipReleases +import com.droiddeck.launcher.gpu.VulkanInfo +import com.droiddeck.launcher.gpu.SystemVulkanDriver +import com.droiddeck.launcher.wayland.CompositorHost import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertNull @@ -20,12 +24,26 @@ import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config import org.robolectric.shadows.ShadowBuild +import org.robolectric.shadows.ShadowLooper +import org.robolectric.annotation.Implementation +import org.robolectric.annotation.Implements import org.robolectric.util.ReflectionHelpers @RunWith(RobolectricTestRunner::class) -@Config(sdk = [28], manifest = Config.NONE) +@Config(sdk = [28], manifest = Config.NONE, shadows = [DriverMenusAutoTest.XclipseDriver::class]) class DriverMenusAutoTest { + @Implements(SystemVulkanDriver::class) + class XclipseDriver { + companion object { + var enabled = false + @JvmStatic @Implementation fun isPowerVr() = enabled + @JvmStatic @Implementation fun isXclipse() = enabled + @JvmStatic @Implementation fun gpuName() = if (enabled) "Xclipse" else "PowerVR" + } + } + @Before fun reset() { + XclipseDriver.enabled = false ReflectionHelpers.setStaticField(TpUbwcHint::class.java, "resolved", false) ReflectionHelpers.setStaticField(TpUbwcHint::class.java, "cached", null) ReflectionHelpers.setStaticField(TpUbwcHint::class.java, "activeMode", null) @@ -35,6 +53,42 @@ class DriverMenusAutoTest { ShadowBuild.setDevice("eureka") } + @Test fun unsupportedXclipseFallsBackThroughAutoAndFlagsDisplayRestart() { + XclipseDriver.enabled = true + ShadowBuild.setModel("Generic phone") + ShadowBuild.setDevice("generic") + ReflectionHelpers.setStaticField(VulkanInfo::class.java, "cached", mapOf("device" to "Xclipse 540")) + val originalFetch = TurnipReleases.fetch + TurnipReleases.fetch = { _, _, _ -> "[]" } + val activity = Robolectric.buildActivity(Activity::class.java).setup().get() + SessionPrefs.setGpuDriverMode(activity, SessionPrefs.GPU_DRIVERS_AUTO) + SessionPrefs.setAndroidDriver(activity, "old-display") + SessionPrefs.setLinuxDriver(activity, "old-linux") + SessionPrefs.setGpuAutoInstalled(activity, setOf("old-display", "old-linux")) + ReflectionHelpers.setStaticField(CompositorHost::class.java, "started", true) + CompositorHost.displayChoice = "old-display" + try { + val menus = DriverMenus(activity, Handler(Looper.getMainLooper())) + menus.ensureAuto(force = true) + val deadline = System.currentTimeMillis() + 10000 + while (menus.releaseChecking && System.currentTimeMillis() < deadline) { + Thread.sleep(10) + ShadowLooper.idleMainLooper() + } + assertFalse(menus.releaseChecking) + assertEquals(activity.getString(R.string.drivers_powervr_builtin), menus.autoStatus) + assertEquals(TurnipDriver.AUTO, SessionPrefs.androidDriver(activity)) + assertEquals("", SessionPrefs.linuxDriver(activity)) + assertTrue(menus.restartPending) + } finally { + TurnipReleases.fetch = originalFetch + ReflectionHelpers.setStaticField(VulkanInfo::class.java, "cached", null) + ReflectionHelpers.setStaticField(CompositorHost::class.java, "started", false) + CompositorHost.displayChoice = null + XclipseDriver.enabled = false + } + } + @Test fun pickingTheAutoDisplayHandsBothHalvesToAuto() { val activity = Robolectric.buildActivity(Activity::class.java).setup().get() SessionPrefs.setGpuDriverMode(activity, SessionPrefs.GPU_DRIVERS_MIX) diff --git a/app/src/test/java/com/droiddeck/launcher/agent/AgentHostTest.kt b/app/src/test/java/com/droiddeck/launcher/agent/AgentHostTest.kt index 30cb71009e..e51a0d2fca 100644 --- a/app/src/test/java/com/droiddeck/launcher/agent/AgentHostTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/agent/AgentHostTest.kt @@ -84,10 +84,10 @@ class AgentHostTest { val command = ClaudeCode.turn("hello there", null, AgentHarness.Options()) assertEquals("stream-json", command[command.indexOf("--input-format") + 1]) assertFalse("hello there" in command) - val line = org.json.JSONObject(ClaudeCode.input("hello there")!!) + val line = org.json.JSONObject(ClaudeCode.input("hello there")) assertEquals("user", line.getString("type")) assertEquals("hello there", line.getJSONObject("message").getJSONArray("content").getJSONObject(0).getString("text")) - assertNull(Codex.input("hi")) + assertEquals(listOf(ClaudeCode.input("hi")), ClaudeCode.protocol().input("hi", "abc", AgentHarness.Options(), started = false)) } @Test fun aTaskNotificationResultIsMarkedBackgroundAndCarriesItsUsage() { @@ -126,13 +126,35 @@ class AgentHostTest { assertTrue(used("Monitor", """{"command":"tail -f log"}""").background) } - @Test fun claudeTurnsBypassPermissionsOrPlanAndTakeAModel() { + @Test fun claudeTurnsAskFirstByDefaultAndTakeAModel() { val first = ClaudeCode.turn("hi", null, AgentHarness.Options()) - assertTrue("bypassPermissions" in first && "--resume" !in first && "--model" !in first && "--include-partial-messages" in first) + assertEquals("manual", first[first.indexOf("--permission-mode") + 1]) + assertTrue("--permission-prompt-tool=stdio" in first && "--resume" !in first && "--model" !in first && "--include-partial-messages" in first) val next = ClaudeCode.turn("hi", "abc", AgentHarness.Options(model = "opus", plan = true)) assertEquals("abc", next[next.indexOf("--resume") + 1]) assertEquals("opus", next[next.indexOf("--model") + 1]) assertEquals("plan", next[next.indexOf("--permission-mode") + 1]) + assertFalse("--permission-prompt-tool=stdio" in next) + fun mode(permission: String) = ClaudeCode.turn("hi", null, AgentHarness.Options(permission = permission)).let { it[it.indexOf("--permission-mode") + 1] } + assertEquals(listOf("manual", "acceptEdits", "auto", "dontAsk", "bypassPermissions"), ClaudeCode.permissions.map { mode(it.id) }) + assertFalse("--permission-prompt-tool=stdio" in ClaudeCode.turn("hi", null, AgentHarness.Options(permission = AgentHarness.FULL))) + } + + @Test fun claudePermissionPromptsBecomeApprovalsAnsweredOnStdin() { + val event = ClaudeCode.parse("""{"type":"control_request","request_id":"r1","request":{"subtype":"can_use_tool","tool_name":"Bash","input":{"command":"rm -rf build"},"tool_use_id":"t1"}}""")!! + val approval = event.approval!! + assertEquals(AgentHost.Approval("r1", "Bash", "rm -rf build", "rm -rf build", """{"command":"rm -rf build"}"""), approval) + val allow = org.json.JSONObject(ClaudeCode.answer(approval, allow = true)) + assertEquals("control_response", allow.getString("type")) + val response = allow.getJSONObject("response") + assertEquals("r1", response.getString("request_id")) + assertEquals("allow", response.getJSONObject("response").getString("behavior")) + assertEquals("rm -rf build", response.getJSONObject("response").getJSONObject("updatedInput").getString("command")) + val deny = org.json.JSONObject(ClaudeCode.answer(approval, allow = false)).getJSONObject("response").getJSONObject("response") + assertEquals("deny", deny.getString("behavior")) + assertTrue(deny.getString("message").isNotEmpty()) + assertEquals("r1", ClaudeCode.parse("""{"type":"control_cancel_request","request_id":"r1"}""")!!.resolved) + assertNull(ClaudeCode.parse("""{"type":"control_request","request_id":"r2","request":{"subtype":"hook_callback"}}""")) } @Test fun claudeShowsWholeEditsAndTodos() { @@ -142,28 +164,99 @@ class AgentHostTest { """{"todos":[{"content":"read","status":"completed"},{"content":"fix","status":"in_progress"},{"content":"test","status":"pending"}]}"""))) } - @Test fun codexEventsBecomeEntries() { - assertEquals("t1", Codex.parse("""{"type":"thread.started","thread_id":"t1"}""")!!.conversation) - assertEquals(listOf(Entry.Used("i1", "Shell", "uname -m", "uname -m")), - Codex.parse("""{"type":"item.started","item":{"id":"i1","type":"command_execution","command":"uname -m","status":"in_progress"}}""")!!.entries) - assertEquals(listOf(Entry.Result("i1", "aarch64\n", false)), - Codex.parse("""{"type":"item.completed","item":{"id":"i1","type":"command_execution","command":"uname -m","aggregated_output":"aarch64\n","exit_code":0}}""")!!.entries) - assertEquals(listOf(Entry.Said("It is aarch64.")), - Codex.parse("""{"type":"item.completed","item":{"id":"i2","type":"agent_message","text":"It is aarch64."}}""")!!.entries) - assertEquals(Entry.Used("i3", "Edit", "a.kt, b.kt", "a.kt\nb.kt"), - Codex.parse("""{"type":"item.completed","item":{"id":"i3","type":"file_change","status":"completed","changes":[{"path":"a.kt"},{"path":"b.kt"}]}}""")!!.entries.first()) - assertEquals(listOf(Entry.Finished(null)), Codex.parse("""{"type":"turn.completed","usage":{}}""")!!.entries) - assertEquals(listOf(Entry.Finished("quota")), Codex.parse("""{"type":"turn.failed","error":{"message":"quota"}}""")!!.entries) - assertNull(Codex.parse("""{"type":"error","message":"Reconnecting... 1/5 (stream disconnected before completion)"}""")) - assertEquals(listOf(Entry.Finished("unauthorized")), Codex.parse("""{"type":"error","message":"unauthorized"}""")!!.entries) - assertNull(Codex.parse("""{"type":"item.started","item":{"type":"reasoning"}}""")) + private fun json(line: String) = org.json.JSONObject(line) + + @Test fun codexOpensAThreadThenStartsTheTurn() { + val command = Codex.turn("hi", null, AgentHarness.Options()) + assertEquals(listOf("/root/.local/bin/codex", "app-server"), command.takeLast(2)) + assertTrue(command[2].endsWith("2>/root/.cache/droiddeck/codex.log")) + val p = Codex.Protocol() + val init = json(p.input("hi", null, AgentHarness.Options(model = "gpt", effort = "high", brief = "brief"), started = true).single()) + assertEquals("initialize", init.getString("method")) + val lines = p.parse("""{"id":${init.getInt("id")},"result":{"userAgent":"codex"}}""")!!.reply + assertEquals(listOf("initialized", "thread/start"), lines.map { json(it).getString("method") }) + val start = json(lines[1]) + val params = start.getJSONObject("params") + assertEquals("untrusted", params.getString("approvalPolicy")) + assertEquals("danger-full-access", params.getString("sandbox")) + assertEquals("brief", params.getString("developerInstructions")) + val opened = p.parse("""{"id":${start.getInt("id")},"result":{"thread":{"id":"t1"},"approvalPolicy":"untrusted"}}""")!! + assertEquals("t1", opened.conversation) + val turn = json(opened.reply.single()) + assertEquals("turn/start", turn.getString("method")) + assertEquals("t1", turn.getJSONObject("params").getString("threadId")) + assertEquals("hi", turn.getJSONObject("params").getJSONArray("input").getJSONObject(0).getString("text")) + assertEquals("high", turn.getJSONObject("params").getString("effort")) + val next = json(p.input("again", "t1", AgentHarness.Options(), started = false).single()) + assertEquals("turn/start", next.getString("method")) + assertEquals("t1", next.getJSONObject("params").getString("threadId")) + fun opening(q: Codex.Protocol, conversation: String?, options: AgentHarness.Options): org.json.JSONObject { + val id = json(q.input("hi", conversation, options, started = true).single()).getInt("id") + return json(q.parse("""{"id":$id,"result":{}}""")!!.reply.last()) + } + val resumed = opening(Codex.Protocol(), "t9", AgentHarness.Options(permission = AgentHarness.FULL)) + assertEquals("thread/resume", resumed.getString("method")) + assertEquals("t9", resumed.getJSONObject("params").getString("threadId")) + assertEquals("never", resumed.getJSONObject("params").getString("approvalPolicy")) + assertEquals(listOf(Entry.Finished("no such thread")), Codex.Protocol().let { q -> + val id = opening(q, "gone", AgentHarness.Options()).getInt("id") + q.parse("""{"id":$id,"error":{"code":-32600,"message":"no such thread"}}""")!!.entries + }) + // A thread that failed to open is asked for again on the same connection without a second initialize. + Codex.Protocol().let { q -> + val id = opening(q, "gone", AgentHarness.Options()).getInt("id") + q.parse("""{"id":$id,"error":{"code":-32600,"message":"no such thread"}}""") + assertEquals(listOf("thread/resume"), q.input("again", "gone", AgentHarness.Options(), started = false).map { json(it).getString("method") }) + } + assertEquals(listOf(Entry.Finished("not signed in")), Codex.Protocol().let { q -> + val id = json(q.input("hi", null, AgentHarness.Options(), started = true).single()).getInt("id") + q.parse("""{"id":$id,"error":{"code":-32600,"message":"not signed in"}}""")!!.entries + }) } - @Test fun codexTurnsSkipItsSandboxResumeAndTakeAModel() { - assertEquals(listOf("/root/.local/bin/codex", "exec", "--json", "--dangerously-bypass-approvals-and-sandbox", "--skip-git-repo-check", "hi"), - Codex.turn("hi", null, AgentHarness.Options())) - assertEquals(listOf("/root/.local/bin/codex", "exec", "resume", "t1", "--json", "--dangerously-bypass-approvals-and-sandbox", "--skip-git-repo-check", "-m", "gpt", "hi"), - Codex.turn("hi", "t1", AgentHarness.Options(model = "gpt"))) + @Test fun codexItemsBecomeEntries() { + val p = Codex.Protocol() + assertEquals(listOf(Entry.Used("e1", "Shell", "touch x", "touch x")), p.parse( + """{"method":"item/started","params":{"item":{"type":"commandExecution","id":"e1","command":"/bin/bash -lc 'touch x'","status":"inProgress","aggregatedOutput":null,"exitCode":null}}}""")!!.entries) + assertEquals(listOf(Entry.Result("e1", "", false)), p.parse( + """{"method":"item/completed","params":{"item":{"type":"commandExecution","id":"e1","command":"/bin/bash -lc 'touch x'","status":"completed","aggregatedOutput":null,"exitCode":0}}}""")!!.entries) + assertTrue((p.parse("""{"method":"item/completed","params":{"item":{"type":"commandExecution","id":"e2","command":"false","status":"declined","aggregatedOutput":null,"exitCode":null}}}""")!!.entries.single() as Entry.Result).failed) + assertEquals(listOf(Entry.Said("done")), p.parse("""{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"m1","text":"done","phase":"final_answer"}}}""")!!.entries) + assertEquals("Do", p.parse("""{"method":"item/agentMessage/delta","params":{"itemId":"m1","delta":"Do"}}""")!!.text) + assertEquals(listOf(Entry.Used("f1#0", "Edit", "/w/note.txt", "/w/note.txt\n+hi")), p.parse( + """{"method":"item/started","params":{"item":{"type":"fileChange","id":"f1","changes":[{"path":"/w/note.txt","kind":{"type":"add"},"diff":"hi\n"}],"status":"inProgress"}}}""")!!.entries) + assertEquals(listOf(Entry.Result("f1#0", "", false)), p.parse( + """{"method":"item/completed","params":{"item":{"type":"fileChange","id":"f1","changes":[{"path":"/w/note.txt","kind":{"type":"add"},"diff":"hi\n"}],"status":"completed"}}}""")!!.entries) + p.parse("""{"method":"turn/started","params":{"turn":{"id":"u1"}}}""") + assertEquals("[x] read\n[~] fix\n[ ] test", (p.parse("""{"method":"turn/plan/updated","params":{"plan":[{"step":"read","status":"completed"},{"step":"fix","status":"inProgress"},{"step":"test","status":"pending"}]}}""")!!.entries.single() as Entry.Used).input) + val usage = p.parse("""{"method":"thread/tokenUsage/updated","params":{"tokenUsage":{"total":{"totalTokens":32017},"last":{"totalTokens":16055,"inputTokens":16019,"outputTokens":36},"modelContextWindow":258400}}}""")!! + assertEquals(16_055L, usage.context) + assertEquals(258_400L, usage.window) + assertEquals(listOf(AgentHost.Limit(10_080, 84, 1795123687)), p.parse( + """{"method":"account/rateLimits/updated","params":{"rateLimits":{"limitId":"codex","primary":{"usedPercent":84,"windowDurationMins":10080,"resetsAt":1795123687},"secondary":null}}}""")!!.limits) + val end = p.parse("""{"method":"turn/completed","params":{"turn":{"id":"u1","status":"completed","error":null,"durationMs":4200}}}""")!! + assertEquals(listOf(Entry.Finished(null)), end.entries) + assertEquals(AgentHost.Usage(4200, 0.0, 16_019, 36), end.usage) + assertEquals(listOf(Entry.Finished("quota")), p.parse("""{"method":"turn/completed","params":{"turn":{"id":"u2","status":"failed","error":{"message":"quota"},"durationMs":null}}}""")!!.entries) + assertNull(p.parse("""{"method":"error","params":{"error":{"message":"Reconnecting..."},"willRetry":true}}""")) + assertNull(p.parse("not json")) + } + + @Test fun codexApprovalRequestsWaitForTheUser() { + val p = Codex.Protocol() + val command = p.parse("""{"method":"item/commandExecution/requestApproval","id":0,"params":{"kind":"command","itemId":"e1","command":"/bin/bash -lc 'touch x'","cwd":"/w"}}""")!!.approval!! + assertEquals(AgentHost.Approval("0", "Shell", "touch x", "touch x", """{"id":0}"""), command) + assertEquals("""{"id":0,"result":{"decision":"accept"}}""", p.answer(command, allow = true)) + assertEquals("decline", json(p.answer(command, allow = false)).getJSONObject("result").getString("decision")) + p.parse("""{"method":"item/started","params":{"item":{"type":"fileChange","id":"f1","changes":[{"path":"/w/a.kt","kind":{"type":"update"},"diff":"@@ -1 +1 @@\n-old\n+new\n"}],"status":"inProgress"}}}""") + val edit = p.parse("""{"method":"item/fileChange/requestApproval","id":1,"params":{"itemId":"f1","reason":null}}""")!!.approval!! + assertEquals("Edit", edit.tool) + assertEquals("/w/a.kt", edit.detail) + assertEquals("/w/a.kt\n-old\n+new", edit.input) + val refused = json(p.parse("""{"method":"item/tool/requestUserInput","id":2,"params":{}}""")!!.reply.single()) + assertEquals(2, refused.getInt("id")) + assertTrue(refused.has("error")) + assertEquals("1", p.parse("""{"method":"serverRequest/resolved","params":{"requestId":1}}""")!!.resolved) } @Test fun aToolIdUsedAgainInALaterTurnIsANewCall() { @@ -289,28 +382,6 @@ class AgentHostTest { assertEquals(1_000_000L, result.window) } - @Test fun codexTokenCountsCarryContextAndLimits() { - val event = Codex.tokenCount("""{"timestamp":"t","type":"event_msg","payload":{"type":"token_count","info":{"total_token_usage":{"total_tokens":90000},"last_token_usage":{"total_tokens":41000},"model_context_window":272000},"rate_limits":{"primary":{"used_percent":12.5,"window_minutes":300,"resets_at":1794435600},"secondary":{"used_percent":40.0,"window_minutes":10080,"resets_at":1794592800}}}}""")!! - assertEquals(41_000L, event.context) - assertEquals(272_000L, event.window) - assertEquals(listOf(AgentHost.Limit(300, 12, 1794435600), AgentHost.Limit(10_080, 40, 1794592800)), event.limits) - assertNull(Codex.tokenCount("""{"type":"event_msg","payload":{"type":"agent_message"}}""")) - } - - @Test fun codexUsageComesFromTheThreadsSessionLog() { - val root = Files.createTempDirectory("rootfs").toFile() - val log = File(root, "root/.codex/sessions/2026/11/12/rollout-2026-11-12T10-00-00-thread1.jsonl").apply { parentFile!!.mkdirs() } - log.writeText( - """{"type":"event_msg","payload":{"type":"token_count","info":{"last_token_usage":{"total_tokens":15692},"model_context_window":258400},"rate_limits":{"primary":{"used_percent":86.0,"window_minutes":10080,"resets_at":1794716485},"secondary":null}}}""" + "\n" + - """{"type":"response_item","payload":{"type":"additional_tools","tools":[{"description":"reports token_count as it goes"}]}}""" + "\n", - ) - val event = Codex.usage(root, "thread1")!! - assertEquals(15_692L, event.context) - assertEquals(258_400L, event.window) - assertEquals(listOf(AgentHost.Limit(10_080, 86, 1794716485)), event.limits) - assertNull(Codex.usage(root, "other")) - } - @Test fun limitsRoundTripThroughPrefs() { val limits = listOf(AgentHost.Limit(300, 7, 1794435600), AgentHost.Limit(10_080, 85, 1794592800)) assertEquals(limits, AgentHost.decodeLimits(AgentHost.encodeLimits(limits))) diff --git a/app/src/test/java/com/droiddeck/launcher/agent/AgentSecurityTest.kt b/app/src/test/java/com/droiddeck/launcher/agent/AgentSecurityTest.kt index 7fe76acc98..98e2722386 100644 --- a/app/src/test/java/com/droiddeck/launcher/agent/AgentSecurityTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/agent/AgentSecurityTest.kt @@ -209,7 +209,7 @@ class AgentSecurityTest { @Test fun fastPathLibraryIsValidatedAndSelectedForOneSession() { AgentAccess.setCommandsEnabled(context, true) - val source = File(AgentEnv.inbox(context).apply { mkdirs() }, "libblfastpath.so") + val source = File(AgentEnv.inbox(context).apply { mkdirs() }, "libddfastpath.so") source.writeText("wrong architecture") refused("INVALID_LIBRARY") { AgentEnv.override(context, source.name) } val header = ByteArray(64) @@ -227,11 +227,43 @@ class AgentSecurityTest { assertEquals(64, response.getString("sha256").length) assertEquals(ProotFastPath.LIBRARY, AgentEnv.fastPathLibrary(context)) AgentEnv.beginSession(context) - assertEquals("/opt/droiddeck-agent/bin/libblfastpath.so", AgentEnv.fastPathLibrary(context)) + assertEquals("/opt/droiddeck-agent/bin/libddfastpath.so", AgentEnv.fastPathLibrary(context)) AgentEnv.endSession(context) assertEquals(ProotFastPath.LIBRARY, AgentEnv.fastPathLibrary(context)) } + @Test fun aFastPathOverrideQueuedUnderTheOldNameStillApplies() { + AgentAccess.setCommandsEnabled(context, true) + File(AgentEnv.inbox(context).apply { mkdirs() }, "libblfastpath.so").writeText("old") + refused("INVALID_NAME") { AgentEnv.override(context, "libblfastpath.so") } + val bin = File(LinuxRuntime.rootDir(context), "opt/droiddeck-agent/bin").apply { mkdirs() } + File(bin, "libblfastpath.so").writeText("queued") + File(context.filesDir, "agent-env.json").writeText("""{"pendingOverrides":["libblfastpath.so"]}""") + AgentEnv.beginSession(context) + assertEquals("/opt/droiddeck-agent/bin/libddfastpath.so", AgentEnv.fastPathLibrary(context)) + assertEquals("queued", File(bin, "libddfastpath.so").readText()) + assertFalse(File(bin, "libblfastpath.so").exists()) + AgentEnv.endSession(context) + } + + @Test fun aQueuedOldNameOverrideThatCannotBeRenamedWaits() { + AgentAccess.setCommandsEnabled(context, true) + val bin = File(LinuxRuntime.rootDir(context), "opt/droiddeck-agent/bin").apply { mkdirs() } + File(bin, "libblfastpath.so").writeText("queued") + File(context.filesDir, "agent-env.json").writeText("""{"pendingOverrides":["libblfastpath.so"]}""") + bin.setWritable(false) + try { + org.junit.Assume.assumeFalse(bin.canWrite()) + AgentEnv.beginSession(context) + assertEquals(ProotFastPath.LIBRARY, AgentEnv.fastPathLibrary(context)) + assertTrue(File(bin, "libblfastpath.so").isFile) + val state = JSONObject(File(context.filesDir, "agent-env.json").readText()) + assertEquals("libddfastpath.so", state.getJSONArray("pendingOverrides").getString(0)) + } finally { + bin.setWritable(true) + } + } + @Test fun environmentValuesAreNotLogged() { AgentAccess.setCommandsEnabled(context, true) AgentEnv.set(context, listOf("CUSTOM=synthetic-private-value"), false) diff --git a/app/src/test/java/com/droiddeck/launcher/agent/OpenCodeTest.kt b/app/src/test/java/com/droiddeck/launcher/agent/OpenCodeTest.kt index f34e2ad07c..24ce085ec0 100644 --- a/app/src/test/java/com/droiddeck/launcher/agent/OpenCodeTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/agent/OpenCodeTest.kt @@ -18,61 +18,133 @@ import java.nio.file.Files class OpenCodeTest { private val session = "ses_1" - private fun event(type: String, part: String) = """{"type":"$type","timestamp":1,"sessionID":"$session","part":$part}""" + private fun json(line: String) = JSONObject(line) + private fun update(u: String) = """{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"$session","update":$u}}""" - @Test fun turnsResumeByIdAndCarryModelPlanAndVariant() { - assertEquals(listOf(OpenCode.binary, "run", "--format", "json", "--auto", "--thinking", "--", "brief\n\nhi"), - OpenCode.turn("hi", null, AgentHarness.Options(brief = "brief"))) - assertEquals(listOf(OpenCode.binary, "run", "--format", "json", "--auto", "--thinking", "-s", "ses_1", "--agent", "plan", - "-m", "opencode/big-pickle", "--variant", "high", "--", "-hi"), - OpenCode.turn("-hi", "ses_1", AgentHarness.Options(model = "opencode/big-pickle", plan = true, brief = "brief", effort = "high"))) + /** Drives a new process through initialize and session/new to the prompt, returning it and the prompt's id. */ + private fun opened(options: AgentHarness.Options = AgentHarness.Options()): Pair { + val p = OpenCode.Protocol() + var line = p.input("hi", null, options, started = true).single() + var result = "{}" + while (true) { + val request = json(line) + if (request.getString("method") == "session/prompt") return p to request.getInt("id") + if (request.getString("method") == "session/new") result = """{"sessionId":"$session"}""" + line = p.parse("""{"jsonrpc":"2.0","id":${request.getInt("id")},"result":$result}""")!!.reply.single() + } } - @Test fun textReasoningAndStepsBecomeEntries() { - OpenCode.turn("hi", null, AgentHarness.Options()) - assertEquals(session, OpenCode.parse(event("step_start", """{"type":"step-start"}"""))!!.conversation) - assertEquals(listOf(Entry.Said("x86_64")), OpenCode.parse(event("text", """{"type":"text","text":" x86_64\n"}"""))!!.entries) - assertEquals(listOf(Entry.Thought("why")), OpenCode.parse(event("reasoning", """{"type":"reasoning","text":"why"}"""))!!.entries) - val step = OpenCode.parse(event("step_finish", """{"reason":"tool-calls","tokens":{"total":7894,"input":6013,"output":89,"reasoning":0,"cache":{"write":0,"read":1792}},"cost":0.01}"""))!! - assertEquals(emptyList(), step.entries) - assertEquals(7894L, step.context) - val end = OpenCode.parse(event("step_finish", """{"reason":"stop","tokens":{"total":7927,"input":241,"output":6,"reasoning":2,"cache":{"write":0,"read":7680}},"cost":0.02}"""))!! - assertEquals(listOf(Entry.Finished(null)), end.entries) - assertEquals(AgentHost.Usage(0, 0.03, 6013L + 1792 + 241 + 7680, 89L + 6 + 2), end.usage!!.copy(costUsd = Math.round(end.usage!!.costUsd * 100) / 100.0)) + @Test fun turnsServeAcpUnderTheChosenRules() { + val command = OpenCode.turn("hi", null, AgentHarness.Options()).dropWhile { it != "/usr/bin/env" } + assertEquals(listOf("/usr/bin/env", OpenCode.binary, "acp"), listOf(command[0]) + command.drop(2)) + val ask = json(command[1].removePrefix("OPENCODE_PERMISSION=")) + assertEquals("ask", ask.getString("edit")) + assertEquals("ask", ask.getString("bash")) + assertFalse(ask.has("*")) + assertEquals("allow", OpenCode.rules(AgentHarness.EDITS).getString("edit")) + assertEquals("ask", OpenCode.rules(AgentHarness.EDITS).getString("bash")) + assertEquals("""{"*":"allow"}""", OpenCode.rules(AgentHarness.FULL).toString()) } - @Test fun eachTurnCountsOnlyItsOwnSteps() { - OpenCode.turn("one", null, AgentHarness.Options()) - OpenCode.parse(event("step_finish", """{"reason":"stop","tokens":{"input":100,"output":10,"cache":{}},"cost":1}""")) - OpenCode.turn("two", session, AgentHarness.Options()) - val end = OpenCode.parse(event("step_finish", """{"reason":"stop","tokens":{"input":5,"output":1,"cache":{}},"cost":0}"""))!! - assertEquals(AgentHost.Usage(0, 0.0, 5, 1), end.usage) + @Test fun aNewProcessOpensItsSessionAndSetsModelModeAndEffortBeforeThePrompt() { + val p = OpenCode.Protocol() + val init = json(p.input("hi", null, AgentHarness.Options(model = "opencode/big-pickle", effort = "high", brief = "brief", workdir = "/root/DroidDeck"), started = true).single()) + assertEquals("initialize", init.getString("method")) + val new = json(p.parse("""{"jsonrpc":"2.0","id":${init.getInt("id")},"result":{"protocolVersion":1}}""")!!.reply.single()) + assertEquals("session/new", new.getString("method")) + assertEquals("/root/DroidDeck", new.getJSONObject("params").getString("cwd")) + val created = p.parse("""{"jsonrpc":"2.0","id":${new.getInt("id")},"result":{"sessionId":"$session","configOptions":[]}}""")!! + assertEquals(session, created.conversation) + val sent = mutableListOf() + var line = created.reply.single() + while (true) { + val request = json(line) + sent += request + if (request.getString("method") == "session/prompt") break + // A refused effort, one the model does not have, does not stop the turn. + val refused = request.getJSONObject("params").getString("configId") == "effort" + val answer = if (refused) """"error":{"code":-32602,"message":"no"}""" else """"result":{}""" + line = p.parse("""{"jsonrpc":"2.0","id":${request.getInt("id")},$answer}""")!!.reply.single() + } + assertEquals(listOf("model" to "opencode/big-pickle", "effort" to "high", "mode" to "build"), + sent.dropLast(1).map { it.getJSONObject("params").let { o -> o.getString("configId") to o.getString("value") } }) + assertEquals("brief\n\nhi", sent.last().getJSONObject("params").getJSONArray("prompt").getJSONObject(0).getString("text")) + val again = json(p.input("two", session, AgentHarness.Options(brief = "brief"), started = false).single()) + assertEquals("session/prompt", again.getString("method")) + assertEquals("two", again.getJSONObject("params").getJSONArray("prompt").getJSONObject(0).getString("text")) } - @Test fun toolsBecomeCallsWithTheirResults() { - val bash = OpenCode.parse(event("tool_use", """{"type":"tool","tool":"bash","callID":"c1","state":{"status":"completed","input":{"command":"uname -m"},"output":"aarch64\n","metadata":{"exit":0}}}"""))!! - assertEquals(listOf(Entry.Used("c1", "Bash", "uname -m", "uname -m"), Entry.Result("c1", "aarch64\n", false)), bash.entries) - val failed = OpenCode.parse(event("tool_use", """{"type":"tool","tool":"bash","callID":"c2","state":{"status":"completed","input":{"command":"false"},"output":"(no output)","metadata":{"exit":1}}}"""))!! - assertTrue((failed.entries[1] as Entry.Result).failed) - val edit = OpenCode.parse(event("tool_use", """{"type":"tool","tool":"edit","callID":"c3","state":{"status":"completed","input":{"filePath":"/w/a.txt","oldString":"hi","newString":"bye"},"output":"Edit applied successfully."}}"""))!! - assertEquals(Entry.Used("c3", "Edit", "/w/a.txt", "/w/a.txt\n-hi\n+bye"), edit.entries[0]) - val write = OpenCode.parse(event("tool_use", """{"type":"tool","tool":"write","callID":"c4","state":{"status":"completed","input":{"filePath":"/w/b.txt","content":"one\n"},"output":"Wrote file successfully."}}"""))!! - assertEquals("/w/b.txt\n+one", (write.entries[0] as Entry.Used).input) - val todo = OpenCode.parse(event("tool_use", """{"type":"tool","tool":"todowrite","callID":"c5","state":{"status":"completed","input":{"todos":[{"content":"A","status":"completed"},{"content":"B","status":"in_progress"},{"content":"C","status":"pending"}]},"output":"[]"}}"""))!! - assertEquals("[x] A\n[~] B\n[ ] C", (todo.entries[0] as Entry.Used).input) - val read = OpenCode.parse(event("tool_use", """{"type":"tool","tool":"read","callID":"c6","state":{"status":"error","input":{"filePath":"/nope"},"error":"File not found"}}"""))!! - assertEquals("Read", (read.entries[0] as Entry.Used).tool) - assertEquals("/nope", (read.entries[0] as Entry.Used).detail) - assertEquals(Entry.Result("c6", "File not found", true), read.entries[1]) - val running = OpenCode.parse(event("tool_use", """{"type":"tool","tool":"bash","callID":"c7","state":{"status":"running","input":{"command":"sleep 9"}}}"""))!! - assertEquals(listOf(Entry.Used("c7", "Bash", "sleep 9", "sleep 9")), running.entries) + @Test fun aResumedSessionPlansWhenAsked() { + val p = OpenCode.Protocol() + val init = json(p.input("hi", "ses_9", AgentHarness.Options(plan = true), started = true).single()) + val resume = json(p.parse("""{"jsonrpc":"2.0","id":${init.getInt("id")},"result":{}}""")!!.reply.single()) + assertEquals("session/resume", resume.getString("method")) + assertEquals("ses_9", resume.getJSONObject("params").getString("sessionId")) + val resumed = p.parse("""{"jsonrpc":"2.0","id":${resume.getInt("id")},"result":{"configOptions":[]}}""")!! + assertEquals("ses_9", resumed.conversation) + val mode = json(resumed.reply.single()) + assertEquals("plan", mode.getJSONObject("params").getString("value")) + assertEquals(listOf(Entry.Finished("Invalid mode")), p.parse("""{"jsonrpc":"2.0","id":${mode.getInt("id")},"error":{"code":-32602,"message":"Invalid mode"}}""")!!.entries) + // The next message on the same process asks for the mode again rather than prompting in whatever mode the session has. + val retry = json(p.input("again", "ses_9", AgentHarness.Options(plan = true), started = false).single()) + assertEquals("session/set_config_option", retry.getString("method")) + assertEquals("plan", retry.getJSONObject("params").getString("value")) + val prompt = json(p.parse("""{"jsonrpc":"2.0","id":${retry.getInt("id")},"result":{}}""")!!.reply.single()) + assertEquals("session/prompt", prompt.getString("method")) + p.parse("""{"jsonrpc":"2.0","id":${prompt.getInt("id")},"result":{"stopReason":"end_turn"}}""") + assertEquals("session/prompt", json(p.input("third", "ses_9", AgentHarness.Options(plan = true), started = false).single()).getString("method")) + val gone = OpenCode.Protocol() + val id = json(gone.input("hi", "ses_x", AgentHarness.Options(), started = true).single()).getInt("id") + val resumeId = json(gone.parse("""{"jsonrpc":"2.0","id":$id,"result":{}}""")!!.reply.single()).getInt("id") + assertEquals(listOf(Entry.Finished("Session not found")), gone.parse("""{"jsonrpc":"2.0","id":$resumeId,"error":{"code":-32603,"message":"Internal error","data":{"message":"Session not found"}}}""")!!.entries) } - @Test fun errorsEndTheTurn() { - assertEquals(listOf(Entry.Finished("Invalid credential")), OpenCode.parse( - """{"type":"error","sessionID":"ses_1","error":{"name":"APIError","data":{"message":"Invalid credential","statusCode":401}}}""")!!.entries) - assertEquals(listOf(Entry.Finished("UnknownError")), OpenCode.parse("""{"type":"error","error":{"name":"UnknownError"}}""")!!.entries) - assertNull(OpenCode.parse("not json")) + @Test fun chunksAndToolCallsBecomeEntries() { + val (p, prompt) = opened() + assertEquals("We need", p.parse(update("""{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"We need"}}"""))!!.thinking) + val pending = p.parse(update("""{"sessionUpdate":"tool_call","toolCallId":"c1","title":"bash","kind":"execute","status":"pending","locations":[],"rawInput":{"cwd":"/work"}}"""))!! + assertEquals(listOf(Entry.Thought("We need"), Entry.Used("c1", "Bash", "", "")), pending.entries) + assertEquals(listOf(Entry.Used("c1", "Bash", "touch /work/probe.txt", "touch /work/probe.txt")), p.parse(update( + """{"sessionUpdate":"tool_call_update","toolCallId":"c1","status":"in_progress","kind":"execute","title":"touch /work/probe.txt","rawInput":{"command":"touch /work/probe.txt","cwd":"/work"}}"""))!!.entries) + assertEquals(listOf(Entry.Used("c1", "Bash", "touch /work/probe.txt", "touch /work/probe.txt"), Entry.Result("c1", "(no output)", false)), p.parse(update( + """{"sessionUpdate":"tool_call_update","toolCallId":"c1","status":"completed","title":"touch /work/probe.txt","content":[{"type":"content","content":{"type":"text","text":"(no output)"}}],"rawOutput":{"output":"(no output)","metadata":{"exit":0}}}"""))!!.entries) + p.parse(update("""{"sessionUpdate":"tool_call","toolCallId":"c2","title":"write","kind":"edit","status":"pending","rawInput":{}}""")) + assertEquals(Entry.Used("c2", "Write", "/work/note.txt", "/work/note.txt\n+hi"), p.parse(update( + """{"sessionUpdate":"tool_call_update","toolCallId":"c2","status":"in_progress","kind":"edit","title":"write","rawInput":{"content":"hi","filePath":"/work/note.txt"}}"""))!!.entries.single()) + assertEquals(Entry.Result("c2", "The user rejected permission to use this specific tool call.", true), p.parse(update( + """{"sessionUpdate":"tool_call_update","toolCallId":"c2","status":"failed","rawOutput":{"error":"The user rejected permission to use this specific tool call."}}"""))!!.entries[1]) + assertEquals("done", p.parse(update("""{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"done"}}"""))!!.text) + val usage = p.parse(update("""{"sessionUpdate":"usage_update","used":7760,"size":200000,"cost":{"amount":0.25,"currency":"USD"}}"""))!! + assertEquals(7760L, usage.context) + assertEquals(200_000L, usage.window) + val end = p.parse("""{"jsonrpc":"2.0","id":$prompt,"result":{"stopReason":"end_turn","usage":{"inputTokens":592,"outputTokens":3,"totalTokens":7763,"cachedReadTokens":7168}}}""")!! + assertEquals(listOf(Entry.Said("done"), Entry.Finished(null)), end.entries) + assertEquals(0.25, end.usage!!.costUsd, 0.0) + assertEquals(592L + 7168, end.usage!!.inputTokens) + assertTrue(OpenCode.sessionCost) + } + + @Test fun permissionRequestsWaitForTheUser() { + val (p, prompt) = opened() + p.parse(update("""{"sessionUpdate":"tool_call","toolCallId":"c1","title":"bash","kind":"execute","status":"pending","rawInput":{}}""")) + val bash = p.parse("""{"jsonrpc":"2.0","id":0,"method":"session/request_permission","params":{"sessionId":"$session","toolCall":{"toolCallId":"c1","title":"touch /w/x","kind":"execute","status":"pending","rawInput":{"command":"touch /w/x"}},"options":[{"optionId":"once","kind":"allow_once","name":"Allow once"},{"optionId":"reject","kind":"reject_once","name":"Reject"}]}}""")!!.approval!! + assertEquals(AgentHost.Approval("0", "Bash", "touch /w/x", "touch /w/x", """{"id":0}"""), bash) + val outside = p.parse("""{"jsonrpc":"2.0","id":5,"method":"session/request_permission","params":{"sessionId":"$session","toolCall":{"toolCallId":"c1","title":"touch /root/x","kind":"other","rawInput":{"command":"touch /root/x","parentDir":"/root"}}}}""")!!.approval!! + assertEquals("External directory", outside.tool) + assertEquals("/root", outside.detail) + val allow = json(p.answer(bash, allow = true)) + assertEquals(0, allow.getInt("id")) + assertEquals("once", allow.getJSONObject("result").getJSONObject("outcome").getString("optionId")) + assertEquals("reject", json(p.answer(bash, allow = false)).getJSONObject("result").getJSONObject("outcome").getString("optionId")) + val edit = p.parse("""{"jsonrpc":"2.0","id":1,"method":"session/request_permission","params":{"sessionId":"$session","toolCall":{"toolCallId":"c2","title":"/w/a.txt","kind":"edit","rawInput":{"filepath":"/w/a.txt","diff":"Index: /w/a.txt\n===\n--- /w/a.txt\n+++ /w/a.txt\n@@ -1,1 +1,1 @@\n-old\n+new\n"}}}}""")!!.approval!! + assertEquals("Edit", edit.tool) + assertEquals("/w/a.txt\n-old\n+new", edit.input) + val write = json(p.parse("""{"jsonrpc":"2.0","id":2,"method":"fs/write_text_file","params":{"sessionId":"$session","path":"/w/a.txt","content":"new"}}""")!!.reply.single()) + assertEquals(2, write.getInt("id")) + assertTrue(write.has("error")) + assertEquals(listOf(Entry.Finished("Invalid credential")), p.parse( + """{"jsonrpc":"2.0","id":$prompt,"error":{"code":-32603,"message":"Internal error","data":{"message":"Invalid credential"}}}""")!!.entries) + assertNull(p.parse("not json")) } @Test fun verboseModelListingGivesLabelsAndWindows() { @@ -108,30 +180,33 @@ class OpenCodeTest { assertEquals(mapOf("opencode/big-pickle" to 200000L, "opencode-go/kimi-k3" to 262144L), windows) } - @Test fun modelsAndWindowComeFromTheCachedListing() { + @Test fun modelsComeFromTheCachedListing() { val root = Files.createTempDirectory("rootfs").toFile() assertEquals(emptyList(), OpenCode.models(root)) File(root, "root/.cache/droiddeck/opencode-models").apply { parentFile!!.mkdirs() } .writeText("opencode/big-pickle\n{\n \"providerID\": \"opencode\",\n \"name\": \"Big Pickle\",\n \"limit\": {\"context\": 200000}\n}\n") assertEquals(listOf(AgentHarness.Model("opencode/big-pickle", "Big Pickle")), OpenCode.models(root)) - OpenCode.turn("hi", null, AgentHarness.Options(model = "opencode/big-pickle")) - assertEquals(200000L, OpenCode.usage(root, session)!!.window) - OpenCode.turn("hi", null, AgentHarness.Options()) - assertNull(OpenCode.usage(root, session)) } + private fun provider(id: String) = OpenCode.providers.first { it.id == id } + @Test fun aSavedKeyKeepsOtherProvidersAndFreeIsItsOwnMark() { val root = Files.createTempDirectory("rootfs").toFile() - assertFalse(OpenCode.hasKey(root)) + assertEquals(emptySet(), OpenCode.keys(root)) val auth = File(root, "root/.local/share/opencode/auth.json").apply { parentFile!!.mkdirs() } - auth.writeText("""{"openai":{"type":"oauth","refresh":"r"}}""") - assertFalse(OpenCode.hasKey(root)) - OpenCode.saveKey(root, " sk-zen \n") + auth.writeText("""{"openai-codex":{"type":"oauth","refresh":"r"}}""") + assertEquals(emptySet(), OpenCode.keys(root)) + OpenCode.saveKey(root, provider("opencode"), " sk-zen \n") + OpenCode.saveKey(root, provider("ollama-cloud"), "ol-key") val saved = JSONObject(auth.readText()) - assertEquals("r", saved.getJSONObject("openai").getString("refresh")) + assertEquals("r", saved.getJSONObject("openai-codex").getString("refresh")) assertEquals("sk-zen", saved.getJSONObject("opencode").getString("key")) - assertEquals("api", saved.getJSONObject("opencode").getString("type")) - assertTrue(OpenCode.hasKey(root)) + assertEquals("api", saved.getJSONObject("ollama-cloud").getString("type")) + assertEquals("ol-key", saved.getJSONObject("ollama-cloud").getString("key")) + assertEquals(setOf("opencode", "ollama-cloud"), OpenCode.keys(root)) + OpenCode.removeKey(root, provider("opencode")) + assertEquals(setOf("ollama-cloud"), OpenCode.keys(root)) + assertTrue(JSONObject(auth.readText()).has("openai-codex")) OpenCode.useFree(root) assertTrue(File(root, "root/.config/opencode/.droiddeck-free").exists()) } @@ -140,15 +215,96 @@ class OpenCodeTest { val root = Files.createTempDirectory("rootfs").toFile() val auth = File(root, "root/.local/share/opencode/auth.json").apply { parentFile!!.mkdirs() } auth.writeText("{not json") - assertTrue(runCatching { OpenCode.saveKey(root, "sk-zen") }.isFailure) + assertTrue(runCatching { OpenCode.saveKey(root, provider("opencode"), "sk-zen") }.isFailure) assertEquals("{not json", auth.readText()) - assertFalse(OpenCode.hasKey(root)) + assertEquals(emptySet(), OpenCode.keys(root)) + val config = File(root, "root/.config/opencode/opencode.json").apply { parentFile!!.mkdirs() } + config.writeText("""{"provider":{"droiddeck":{"options":{"baseURL":"http://a/v1"}}}}""") + assertTrue(runCatching { OpenCode.saveKey(root, provider("droiddeck"), "k", "b:1") { _, _ -> """{"data":[{"id":"m"}]}""" } }.isFailure) + assertEquals("""{"provider":{"droiddeck":{"options":{"baseURL":"http://a/v1"}}}}""", config.readText()) + assertEquals(setOf("droiddeck"), OpenCode.keys(root)) } - @Test fun signInIsTheKeyOrTheFreeMark() { + @Test fun aCustomServerBecomesAProviderWithTheModelsItLists() { + val root = Files.createTempDirectory("rootfs").toFile() + val config = File(root, "root/.config/opencode/opencode.json").apply { parentFile!!.mkdirs() } + config.writeText("""{"theme":"tokyonight","provider":{"mine":{"npm":"x"}}}""") + val asked = mutableListOf>() + OpenCode.saveKey(root, provider("droiddeck"), "", "192.168.1.20:11434/") { url, key -> + asked += url to key + """{"object":"list","data":[{"id":"qwen3:8b"},{"id":"gpt-oss:20b"},{"id":"qwen3:8b"}]}""" + } + assertEquals(listOf("http://192.168.1.20:11434/v1/models" to null), asked) + val saved = JSONObject(config.readText()) + assertEquals("tokyonight", saved.getString("theme")) + assertTrue(saved.getJSONObject("provider").has("mine")) + val custom = saved.getJSONObject("provider").getJSONObject("droiddeck") + assertEquals("@ai-sdk/openai-compatible", custom.getString("npm")) + assertEquals("192.168.1.20", custom.getString("name")) + assertEquals("http://192.168.1.20:11434/v1", custom.getJSONObject("options").getString("baseURL")) + assertEquals(setOf("qwen3:8b", "gpt-oss:20b"), custom.getJSONObject("models").keys().asSequence().toSet()) + assertEquals(setOf("droiddeck"), OpenCode.keys(root)) + assertFalse(JSONObject(File(root, "root/.local/share/opencode/auth.json").readText()).has("droiddeck")) + + OpenCode.saveKey(root, provider("droiddeck"), "sk-lan", "https://llm.example/api/v1") { url, key -> asked += url to key; """{"data":[{"id":"m"}]}""" } + assertEquals("https://llm.example/api/v1/models" to "sk-lan", asked.last()) + assertEquals("sk-lan", JSONObject(File(root, "root/.local/share/opencode/auth.json").readText()).getJSONObject("droiddeck").getString("key")) + + OpenCode.removeKey(root, provider("droiddeck")) + assertEquals(emptySet(), OpenCode.keys(root)) + assertTrue(JSONObject(config.readText()).getJSONObject("provider").has("mine")) + } + + @Test fun modelIdsSkipWhatTheUserlandPrintsFirst() { + assertEquals(listOf("m"), OpenCode.modelIds("proot warning: can't sanitize binding \"/proc/self/fd/1\"\n{\"data\":[{\"id\":\"m\"}]}\n")) + assertEquals(emptyList(), OpenCode.modelIds("curl: (7) Failed to connect")) + } + + @Test fun aFailedKeyWritePutsTheServerConfigBack() { + val root = Files.createTempDirectory("rootfs").toFile() + val config = File(root, "root/.config/opencode/opencode.json").apply { parentFile!!.mkdirs() } + val previous = """{"provider":{"droiddeck":{"options":{"baseURL":"http://a/v1"}}}}""" + config.writeText(previous) + // A folder where the key file's temporary copy goes makes that write fail after the config is written. + File(root, "root/.local/share/opencode/.auth.json.tmp").mkdirs() + assertTrue(runCatching { OpenCode.saveKey(root, provider("droiddeck"), "k", "b:1") { _, _ -> """{"data":[{"id":"m"}]}""" } }.isFailure) + assertEquals(previous, config.readText()) + assertFalse(File(root, "root/.config/opencode/.opencode.json.tmp").exists()) + + config.delete() + File(root, "root/.local/share/opencode/.auth.json.tmp").mkdirs() + assertTrue(runCatching { OpenCode.saveKey(root, provider("droiddeck"), "k", "b:1") { _, _ -> """{"data":[{"id":"m"}]}""" } }.isFailure) + assertFalse(config.exists()) + } + + @Test fun aServerWithoutModelsIsNotSaved() { + val root = Files.createTempDirectory("rootfs").toFile() + val error = runCatching { OpenCode.saveKey(root, provider("droiddeck"), "", "localhost:1234") { _, _ -> """{"data":[]}""" } }.exceptionOrNull() + assertEquals("No models at http://localhost:1234/v1", error?.message) + assertFalse(File(root, "root/.config/opencode/opencode.json").exists()) + } + + @Test fun providerModelsAreLabelledWithTheProvider() { + val (models, _) = OpenCode.listModels(""" + ollama-cloud/gpt-oss:120b + { + "providerID": "ollama-cloud", + "name": "gpt-oss:120b" + } + droiddeck/qwen3:8b + { + "providerID": "droiddeck", + "name": "qwen3:8b" + } + """.trimIndent()) + assertEquals(listOf(AgentHarness.Model("ollama-cloud/gpt-oss:120b", "gpt-oss:120b · Ollama Cloud"), AgentHarness.Model("droiddeck/qwen3:8b", "qwen3:8b")), models) + } + + @Test fun signInIsAKeyTheFreeMarkOrACustomServer() { val probe = OpenCode.signedIn.last() assertTrue(probe.contains("/root/.local/share/opencode/auth.json")) assertTrue(probe.contains("[ -e /root/.config/opencode/.droiddeck-free ]")) + assertTrue(probe.contains("grep -q '\"droiddeck\"' /root/.config/opencode/opencode.json")) assertTrue(probe.contains("models --verbose > /root/.cache/droiddeck/opencode-models.$$")) assertEquals(listOf("/root/.local/bin/android-open", "https://opencode.ai/auth"), OpenCode.signIn) } diff --git a/app/src/test/java/com/droiddeck/launcher/audio/PulseAudioComponentTest.kt b/app/src/test/java/com/droiddeck/launcher/audio/PulseAudioComponentTest.kt index d06cc52d03..63c1003b4f 100644 --- a/app/src/test/java/com/droiddeck/launcher/audio/PulseAudioComponentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/audio/PulseAudioComponentTest.kt @@ -68,6 +68,80 @@ class PulseAudioComponentTest { assertFalse(host.live(host.token())) } + @Test + fun aRestartWaitsForAnInFlightSinkGuardCommand() { + val killed = mutableListOf() + val host = PulseAudioComponent.HostLifecycle { killed.add(it) } + val generation = host.begin() + host.launch(generation) { 31463 } + val first = host.token() + val checked = CountDownLatch(1) + val resume = CountDownLatch(1) + val pool = Executors.newFixedThreadPool(2) + try { + val command = pool.submit { + host.command(first) { + checked.countDown() + resume.await() + "old host" + } + } + assertTrue(checked.await(5, TimeUnit.SECONDS)) + assertTrue(pool.submit { host.exited(generation) }.get(5, TimeUnit.SECONDS)) + val launched = CountDownLatch(1) + val restart = pool.submit { + host.launch(generation) { + launched.countDown() + 31464 + } + } + val deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5) + while (!host.commands.hasQueuedThreads() && !restart.isDone && System.nanoTime() < deadline) Thread.yield() + assertTrue(host.commands.hasQueuedThreads()) + assertEquals(1L, launched.count) + assertFalse(restart.isDone) + resume.countDown() + assertEquals("old host", command.get(5, TimeUnit.SECONDS)) + assertTrue(restart.get(5, TimeUnit.SECONDS)) + assertEquals(31464, host.pid) + assertEquals(null, host.command(first) { error("stale guard reached the replacement host") }) + assertEquals("new host", host.command(host.token()) { "new host" }) + assertTrue(killed.isEmpty()) + } finally { + resume.countDown() + pool.shutdownNow() + } + } + + @Test + fun stopIsNotHeldUpByAnInFlightSinkGuardCommand() { + val killed = mutableListOf() + val host = PulseAudioComponent.HostLifecycle { killed.add(it) } + host.launch(host.begin()) { 31463 } + val token = host.token() + val checked = CountDownLatch(1) + val resume = CountDownLatch(1) + val pool = Executors.newFixedThreadPool(2) + try { + val command = pool.submit { + host.command(token) { + checked.countDown() + resume.await() + "done" + } + } + assertTrue(checked.await(5, TimeUnit.SECONDS)) + pool.submit { host.stop() }.get(5, TimeUnit.SECONDS) + assertEquals(listOf(31463), killed) + assertFalse(host.live(token)) + resume.countDown() + assertEquals("done", command.get(5, TimeUnit.SECONDS)) + } finally { + resume.countDown() + pool.shutdownNow() + } + } + @Test fun failedLaunchDoesNotRestartOrTerminateAnInvalidPid() { val host = PulseAudioComponent.HostLifecycle { error("invalid pid terminated") } 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 cd9d785d8c..219ecad5a1 100644 --- a/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/core/GameEnvironmentTest.kt @@ -134,12 +134,12 @@ class GameEnvironmentTest { assertEquals("1", chosen.games["42"]!!["FEX_TSOENABLED"]) } val ntsync = GameEnvironment.withGameSync(base, "42", "ntsync").games["42"]!! - assertEquals(listOf("1", "0", "1"), listOf(ntsync["BL_SYNC"], ntsync["BL_FSYNC_FIRST"], ntsync["BL_SYNC_FALLBACK"])) + assertEquals(listOf("1", "0", "1"), listOf(ntsync["DD_SYNC"], ntsync["DD_FSYNC_FIRST"], ntsync["DD_SYNC_FALLBACK"])) assertFalse(ntsync.containsKey("PROTON_NO_ESYNC")) val fsync = GameEnvironment.withGameSync(base, "42", "fsync").games["42"]!! - assertEquals(listOf("0", "1", "1", "1"), listOf(fsync["BL_SYNC"], fsync["BL_FSYNC_FIRST"], fsync["BL_SYNC_FALLBACK"], fsync["PROTON_NO_ESYNC"])) + assertEquals(listOf("0", "1", "1", "1"), listOf(fsync["DD_SYNC"], fsync["DD_FSYNC_FIRST"], fsync["DD_SYNC_FALLBACK"], fsync["PROTON_NO_ESYNC"])) val wineserver = GameEnvironment.withGameSync(base, "42", "wineserver").games["42"]!! - assertEquals(listOf("0", "0", "0"), listOf(wineserver["BL_SYNC"], wineserver["BL_FSYNC_FIRST"], wineserver["BL_SYNC_FALLBACK"])) + assertEquals(listOf("0", "0", "0"), listOf(wineserver["DD_SYNC"], wineserver["DD_FSYNC_FIRST"], wineserver["DD_SYNC_FALLBACK"])) val inherited = GameEnvironment.withGameSync(base, "42", null) assertNull(GameEnvironment.gameSync(inherited, "42")) assertEquals(mapOf("FEX_TSOENABLED" to "1"), inherited.games["42"]) diff --git a/app/src/test/java/com/droiddeck/launcher/files/AppFilesProviderTest.kt b/app/src/test/java/com/droiddeck/launcher/files/AppFilesProviderTest.kt new file mode 100644 index 0000000000..6a413cc81a --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/files/AppFilesProviderTest.kt @@ -0,0 +1,105 @@ +package com.droiddeck.launcher.files + +import android.Manifest +import android.content.pm.ProviderInfo +import android.database.Cursor +import android.provider.DocumentsContract.Document +import com.droiddeck.launcher.session.SessionPrefs +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertThrows +import org.junit.Assert.assertTrue +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 +import java.io.FileNotFoundException + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class AppFilesProviderTest { + private val app get() = RuntimeEnvironment.getApplication() + private lateinit var provider: AppFilesProvider + private lateinit var base: File + + @Before fun setUp() { + base = app.dataDir + provider = AppFilesProvider() + provider.attachInfo(app, ProviderInfo().apply { + authority = "${app.packageName}.documents" + exported = true + grantUriPermissions = true + readPermission = Manifest.permission.MANAGE_DOCUMENTS + writePermission = Manifest.permission.MANAGE_DOCUMENTS + }) + } + + private fun file(path: String, text: String = "x") = File(base, path).apply { parentFile!!.mkdirs(); writeText(text) } + + private fun children(dir: File): List { + val c: Cursor = provider.queryChildDocuments(dir.absolutePath, null, null as String?) + try { + val names = mutableListOf() + while (c.moveToNext()) names += c.getString(c.getColumnIndexOrThrow(Document.COLUMN_DISPLAY_NAME)) + return names + } finally { + c.close() + } + } + + @Test fun listingHidesPrivateFolders() { + file("no_backup/adbkey") + file("shared_prefs/settings.xml") + file("databases/app.db") + file("files/stores/epic/auth.json") + file("files/saves/slot1.sav") + val steam = SessionPrefs.steamRoot(app, "arm64") + File(steam, "config/loginusers.vdf").apply { parentFile!!.mkdirs(); writeText("x") } + File(steam, "steamapps/game.txt").apply { parentFile!!.mkdirs(); writeText("x") } + + val root = children(base) + assertFalse(root.contains("no_backup")) + assertFalse(root.contains("shared_prefs")) + assertFalse(root.contains("databases")) + assertTrue(root.contains("files")) + val files = children(File(base, "files")) + assertFalse(files.contains("stores")) + assertTrue(files.contains("saves")) + val steamChildren = children(steam) + assertFalse(steamChildren.contains("config")) + assertTrue(steamChildren.contains("steamapps")) + } + + @Test fun privateFilesDoNotOpen() { + val key = file("no_backup/adbkey") + val prefs = file("shared_prefs/settings.xml") + val login = File(SessionPrefs.steamRoot(app, "x86_64"), "config/loginusers.vdf").apply { parentFile!!.mkdirs(); writeText("x") } + listOf(key, prefs, login).forEach { f -> + assertThrows(FileNotFoundException::class.java) { provider.openDocument(f.absolutePath, "r", null) } + assertThrows(FileNotFoundException::class.java) { provider.queryDocument(f.absolutePath, null) } + assertThrows(FileNotFoundException::class.java) { provider.deleteDocument(f.absolutePath) } + } + assertTrue(key.exists()) + } + + @Test fun ordinaryFileStillOpens() { + val save = file("files/saves/slot1.sav", "progress") + provider.openDocument(save.absolutePath, "r", null).use { pfd -> + assertEquals("progress", android.os.ParcelFileDescriptor.AutoCloseInputStream(pfd).bufferedReader().readText()) + } + } + + @Test fun privateFoldersCannotBeCreatedOrCarriedOut() { + File(base, "databases").deleteRecursively() + assertThrows(FileNotFoundException::class.java) { provider.createDocument(base.absolutePath, Document.MIME_TYPE_DIR, "databases") } + assertFalse(File(base, "databases").exists()) + file("files/stores/epic/auth.json") + val files = File(base, "files") + assertThrows(FileNotFoundException::class.java) { provider.renameDocument(files.absolutePath, "elsewhere") } + assertThrows(FileNotFoundException::class.java) { provider.deleteDocument(files.absolutePath) } + assertTrue(File(files, "stores/epic/auth.json").exists()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/ModeSettingsLoadingTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/ModeSettingsLoadingTest.kt index d9c0dd8f38..4f1be7eac0 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/ModeSettingsLoadingTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/ModeSettingsLoadingTest.kt @@ -35,7 +35,7 @@ class ModeSettingsLoadingTest { @Test fun desktopDoesNotConsumeSteamsAppliedShaderChoice() { val activity = Robolectric.buildActivity(FrontEndActivity::class.java).get() SessionPrefs.setShaderPrecache(activity, false) - val applied = File(LinuxRuntime.rootDir(activity), "root/.bl-shader-precache-applied") + val applied = File(LinuxRuntime.rootDir(activity), "root/.dd-shader-precache-applied") applied.parentFile!!.mkdirs() applied.writeText("0") load(activity, SessionService.MODE_DESKTOP) diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/SoundtrackCollectionsTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/SoundtrackCollectionsTest.kt index 6aa9bb1640..3d85fc18ff 100644 --- a/app/src/test/java/com/droiddeck/launcher/frontend/SoundtrackCollectionsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/frontend/SoundtrackCollectionsTest.kt @@ -40,4 +40,15 @@ class SoundtrackCollectionsTest { val list = listOf(Collection(2_000_000_005, "x", emptyList())) assertEquals(2_000_000_006, SoundtrackCollections.nextId(list)) } + + @Test fun emptyFavoritesCanBeLeftOutOfTheLibraryList() { + val context = androidx.test.core.app.ApplicationProvider.getApplicationContext() + SoundtrackCollections.load(context) + val custom = SoundtrackCollections.create(context, "Chill", emptyList())!! + val favorites = SoundtrackCollections.FAVORITES_ID + assertEquals(listOf(custom), SoundtrackCollections.games(context, "Favorites", skipEmptyFavorites = true).map { it.appId }) + assertEquals(listOf(favorites, custom), SoundtrackCollections.games(context, "Favorites").map { it.appId }) + SoundtrackCollections.add(context, favorites, listOf(ref("a"))) + assertEquals(listOf(favorites, custom), SoundtrackCollections.games(context, "Favorites", skipEmptyFavorites = true).map { it.appId }) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/frontend/SteamHiddenTest.kt b/app/src/test/java/com/droiddeck/launcher/frontend/SteamHiddenTest.kt new file mode 100644 index 0000000000..bca99f5188 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/frontend/SteamHiddenTest.kt @@ -0,0 +1,101 @@ +package com.droiddeck.launcher.frontend + +import java.io.File +import org.json.JSONArray +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +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 + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33]) +class SteamHiddenTest { + @get:Rule val tmp = TemporaryFolder() + + private fun steamRoot(): File = tmp.newFolder("Steam").also { root -> + File(root, "config").mkdirs() + File(root, "config/loginusers.vdf").writeText( + "\"users\"\n{\n\t\"76561198352563669\"\n\t{\n\t\t\"AccountName\"\t\t\"a\"\n\t\t\"MostRecent\"\t\t\"1\"\n\t}\n}\n") + } + + private fun store(root: File, json: String?): File { + val dir = File(root, "userdata/392297941/config/cloudstorage").apply { mkdirs() } + return File(dir, "cloud-storage-namespace-1.json").also { f -> json?.let { f.writeText(it) } } + } + + private fun hiddenEntry(file: File): JSONObject { + val entries = JSONArray(file.readText()) + return (0 until entries.length()).map { entries.getJSONArray(it) }.first { it.getString(0) == "user-collections.hidden" }.getJSONObject(1) + } + + @Test fun hidingAddsTheGameAndKeepsOtherEntries() { + val root = steamRoot() + val file = store(root, """[["user-collections.favorite",{"key":"user-collections.favorite","value":"{}"}],["user-collections.hidden",{"key":"user-collections.hidden","timestamp":5,"version":"7","value":"{\"id\":\"hidden\",\"name\":\"Hidden\",\"added\":[10],\"removed\":[]}"}]]""") + assertNotNull(SteamHidden.write(root, 440, true, now = 99)) + assertEquals(setOf(10L, 440L), SteamHidden.read(root)) + val entry = hiddenEntry(file) + assertEquals(99L, entry.getLong("timestamp")) + assertEquals("8", entry.getString("version")) + assertEquals("Hidden", JSONObject(entry.getString("value")).getString("name")) + assertEquals(2, JSONArray(file.readText()).length()) + } + + @Test fun unhidingTakesTheGameOutAgain() { + val root = steamRoot() + store(root, """[["user-collections.hidden",{"key":"user-collections.hidden","value":"{\"id\":\"hidden\",\"added\":[10,440],\"removed\":[]}"}]]""") + assertNotNull(SteamHidden.write(root, 440, false)) + assertEquals(setOf(10L), SteamHidden.read(root)) + } + + @Test fun aMissingCollectionIsCreatedWhenHiding() { + val root = steamRoot() + val file = store(root, "[]") + assertNotNull(SteamHidden.write(root, 2931908220L, true)) + assertEquals(setOf(2931908220L), SteamHidden.read(root)) + assertFalse(hiddenEntry(file).getBoolean("is_deleted")) + } + + @Test fun aDeletedCollectionIsRevivedWhenHiding() { + val root = steamRoot() + store(root, """[["user-collections.hidden",{"key":"user-collections.hidden","is_deleted":true}]]""") + assertEquals(emptySet(), SteamHidden.read(root)) + assertNotNull(SteamHidden.write(root, 7, true)) + assertEquals(setOf(7L), SteamHidden.read(root)) + } + + @Test fun withoutASteamStoreNothingIsWritten() { + val root = steamRoot() + assertNull(SteamHidden.write(root, 1, true)) + assertEquals(emptySet(), SteamHidden.read(root)) + } + + @Test fun theCollectionIsMarkedAsPendingUploadOnce() { + val root = steamRoot() + val file = store(root, "[]") + SteamHidden.write(root, 1, true) + SteamHidden.write(root, 2, true) + assertEquals("""["user-collections.hidden"]""", File(file.parentFile, "cloud-storage-namespace-1.modified.json").readText()) + } + + @Test fun aMalformedMemberIsRejectedAndTheFileIsLeftAlone() { + val root = steamRoot() + val json = """[["user-collections.hidden",{"key":"user-collections.hidden","value":"{\"id\":\"hidden\",\"added\":[\"x\"],\"removed\":[]}"}]]""" + val file = store(root, json) + assertEquals(emptySet(), SteamHidden.readOrNull(root)) + assertNull(SteamHidden.write(root, 1, true)) + assertEquals(json, file.readText()) + } + + @Test fun numericStringsAreReadAndBadMembersAreSkipped() { + val root = steamRoot() + store(root, """[["user-collections.hidden",{"key":"user-collections.hidden","value":"{\"id\":\"hidden\",\"added\":[\"440\",\"x\",4.5,730],\"removed\":[]}"}]]""") + assertEquals(setOf(440L, 730L), SteamHidden.read(root)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/gpu/DriverPairsTest.kt b/app/src/test/java/com/droiddeck/launcher/gpu/DriverPairsTest.kt index b234260030..ac77658543 100644 --- a/app/src/test/java/com/droiddeck/launcher/gpu/DriverPairsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/gpu/DriverPairsTest.kt @@ -217,13 +217,43 @@ class DriverPairsTest { assertFalse(upstream.suits(GpuInfo("PowerVR", 0, Family.POWERVR, "", false))) assertEquals("RADV upstream · Samsung Xclipse", upstream.name) assertEquals(DriverPairs.NAD_RADV_XCLIPSE, DriverPairs.recommendedKey(xclipse, pairs)) - for (name in listOf("Samsung Xclipse 530", "Samsung Xclipse 540", "Samsung Xclipse 920")) + assertEquals(DriverPairs.NAD_RADV_XCLIPSE, DriverPairs.recommendedKey(GpuInfo("Samsung Xclipse 920", 0, Family.POWERVR, "", false), pairs)) + for (name in listOf("Samsung Xclipse 530")) assertEquals(DriverPairs.NAD_RADV_XCLIPSE, DriverPairs.recommendedKey(GpuInfo(name, 0, Family.POWERVR, "", false), pairs)) + for (name in listOf("Samsung Xclipse 540", "Samsung Xclipse 950", "Samsung Xclipse 960", "Xclipse")) + assertEquals(DriverPairs.NAD_RADV_XCLIPSE_UPSTREAM, DriverPairs.recommendedKey(GpuInfo(name, 0, Family.POWERVR, "", false), pairs)) assertTrue(DriverPairs.isNonAdreno("RADV-Xclipse-upstream")) - for (name in listOf("Samsung Xclipse 950", "Samsung Xclipse 960", "Xclipse")) { - val newer = GpuInfo(name, 0, Family.POWERVR, "", false) - assertEquals(DriverPairs.NAD_RADV_XCLIPSE_UPSTREAM, DriverPairs.recommendedKey(newer, pairs)) - assertEquals(DriverPairs.NAD_RADV_XCLIPSE, DriverPairs.recommendedKey(newer, pairs.filter { it.key != DriverPairs.NAD_RADV_XCLIPSE_UPSTREAM })) + for (name in listOf("Samsung Xclipse 540", "Samsung Xclipse 950", "Samsung Xclipse 960", "Xclipse")) + assertNull(DriverPairs.recommendedKey(GpuInfo(name, 0, Family.POWERVR, "", false), pairs.filter { it.key != DriverPairs.NAD_RADV_XCLIPSE_UPSTREAM })) + } + + @Test + fun autoEligibilityDoesNotDependOnPublishedXclipsePairs() { + fun mali(name: String) = GpuInfo(name, 0, GpuInfo.familyOf(false, 0, mali = name), "", false) + val xclipse540 = GpuInfo("Samsung Xclipse 540", 0, Family.POWERVR, "", false) + val xclipse920 = GpuInfo("Samsung Xclipse 920", 0, Family.POWERVR, "", false) + val upstream = TurnipReleases.Asset("Non-Adreno", "r1", "RADV-Xclipse-upstream.zip", "https://example/upstream", 9_000_000, + false, "label", "0".repeat(64), DriverPairs.nonAdreno("RADV-Xclipse-upstream"), bundle = true) + val pairs = DriverPairs.from(TurnipReleases.Check(listOf(upstream), emptyList(), emptyList(), 0L)) + assertTrue(DriverPairs.autoEligible(xclipse540)) + assertNull(DriverPairs.recommendedKey(xclipse540, emptyList())) + assertEquals(DriverPairs.NAD_RADV_XCLIPSE_UPSTREAM, DriverPairs.recommendedKey(xclipse540, pairs)) + assertTrue(DriverPairs.autoEligible(xclipse920)) + assertEquals(DriverPairs.NAD_RADV_XCLIPSE, DriverPairs.recommendedKey(xclipse920, emptyList())) + assertTrue(DriverPairs.autoEligible(gpu(740))) + assertTrue(DriverPairs.autoEligible(mali("Mali-G57"))) + assertFalse(DriverPairs.autoEligible(mali("Mali-G1-Ultra"))) + assertFalse(DriverPairs.autoEligible(GpuInfo("PowerVR", 0, Family.POWERVR, "", false))) + } + + @Test + fun autoEligibilityMatchesRecommendedKeyForAdrenoAndMali() { + fun mali(name: String) = GpuInfo(name, 0, GpuInfo.familyOf(false, 0, mali = name), "", false) + for (gpu in listOf(gpu(710), gpu(740), mali("Mali-G57"), mali("Mali-G925-Immortalis MC12"))) { + assertEquals( + DriverPairs.recommendedKey(gpu, emptyList(), sdk = 34) != null, + DriverPairs.autoEligible(gpu, sdk = 34), + ) } } diff --git a/app/src/test/java/com/droiddeck/launcher/hud/FrameStatsTest.kt b/app/src/test/java/com/droiddeck/launcher/hud/FrameStatsTest.kt index 20e83499e8..4f029316f2 100644 --- a/app/src/test/java/com/droiddeck/launcher/hud/FrameStatsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/hud/FrameStatsTest.kt @@ -82,7 +82,7 @@ class FrameStatsTest { } @Test fun guestFrameTimesMoveByThePausedSessionsClockShift() { - val control = java.io.File.createTempFile("bl-clock", null) + val control = java.io.File.createTempFile("dd-clock", null) try { control.writeBytes(java.nio.ByteBuffer.allocate(8).order(java.nio.ByteOrder.LITTLE_ENDIAN).putLong(62_283_930_706L).array()) val feed = GameFrameFeed(java.io.File("/nonexistent/droiddeck-hud/frames"), clockControl = control) diff --git a/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt b/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt index c510dc72f3..7409d4558b 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/DualScreenTest.kt @@ -29,6 +29,26 @@ class DualScreenTest { assertFalse(DualScreen.isBuiltIn(5, "AYN Thor")) } + @Test @Config(sdk = [34]) fun selectedInternalAndExternalDisplaysCanBeUsed() { + withDisplay(INTERNAL, "Bottom screen") { internal -> + assertEquals(internal.displayId, DualScreen.selectedSessionDisplay(context, displays, Display.DEFAULT_DISPLAY, internal.displayId)?.displayId) + } + withDisplay(EXTERNAL, "HDMI Screen") { external -> + assertEquals(external.displayId, DualScreen.selectedSessionDisplay(context, displays, Display.DEFAULT_DISPLAY, external.displayId)?.displayId) + SessionPrefs.setDualScreenSessionMode(context, DualScreen.MODE_OFF) + assertNull(DualScreen.selectedSessionDisplay(context, displays, Display.DEFAULT_DISPLAY, external.displayId)) + SessionPrefs.setDualScreenSessionMode(context, DualScreen.MODE_AUTO) + } + } + + @Test @Config(sdk = [34]) fun missingOrRemovedSelectedDisplaysCannotBeUsed() { + assertNull(DualScreen.selectedSessionDisplay(context, displays, Display.DEFAULT_DISPLAY, Display.INVALID_DISPLAY)) + val id = ShadowDisplayManager.addDisplay("w640dp-h480dp", EXTERNAL) + shadowOf(displays.getDisplay(id)).setFlags(Display.FLAG_PRESENTATION) + ShadowDisplayManager.removeDisplay(id) + assertNull(DualScreen.selectedSessionDisplay(context, displays, Display.DEFAULT_DISPLAY, id)) + } + @Test fun knownModelsCountWhenTheTypeIsHidden() { assertTrue(DualScreen.isBuiltIn(null, "Retroid Pocket Duo")) assertTrue(DualScreen.isBuiltIn(null, " AYN Thor ")) diff --git a/app/src/test/java/com/droiddeck/launcher/input/InputLayoutToolsTest.kt b/app/src/test/java/com/droiddeck/launcher/input/InputLayoutToolsTest.kt index 44ad82b904..cdaa68a779 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/InputLayoutToolsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/InputLayoutToolsTest.kt @@ -50,7 +50,7 @@ class InputLayoutToolsTest { assertEquals(InputLibraries.DECK, independent.layout(InputProfile.GAME, InputRole.SECONDARY)!!.origin) val stock = InputStockLayouts.layouts().first { it.id == InputLibraries.DECK }.elements val dragged = mine.copy(elements = mine.elements.map { it.copy(x = 0f, y = 0f) }) - assertEquals(stock, InputLibraries.defaultPositions(context, copied, dragged)) + assertEquals(stock to InputStockLayouts.layouts().first { it.id == InputLibraries.DECK }.aspect, InputLibraries.defaultPositions(context, copied, dragged)) assertEquals(mine.elements, dragged.elements.withPositionsOf(stock)) assertEquals(copied, InputLibraries.decode(InputLibraries.encode(copied))) } @@ -58,7 +58,7 @@ class InputLayoutToolsTest { @Test fun builtInGamepadDefaultsComeFromTheGamepadGenerator() { val library = InputLibraries.read(context) val gamepad = library.layouts.first { it.id == InputLibraries.OVERLAY } - val defaults = InputLibraries.defaultPositions(context, library, gamepad)!! + val defaults = InputLibraries.defaultPositions(context, library, gamepad)!!.first assertEquals(gamepad.elements.map { it.id }.toSet(), defaults.map { it.id }.toSet()) assertNull(InputLibraries.defaultPositions(context, library, SavedInputLayout("new", "New"))) } @@ -162,6 +162,23 @@ class InputLayoutToolsTest { assertEquals(label, emptyList>(), overlapping(elements, width, height)) } + private fun assertStickView(elements: List, width: Int, height: Int, label: String) { + for (control in listOf(InputControl.LS, InputControl.RS)) { + val stick = elements.first { it.control == control } + assertTrue("$label ${stick.id} keeps its widened travel width", stick.width * width >= stick.height * height * 1.25f - 1f) + assertTrue("$label ${stick.id} stays on screen", stick.x >= 0f && stick.x + stick.width <= 1.0001f) + } + } + + @Test fun sticksKeepTheirFullViewAtSurfaceEdges() { + for ((width, height) in listOf(2608 to 1200, 1920 to 1080, 1280 to 960)) { + ControllerPrefs.setLayout(context, width, height, mapOf("ls" to (0f to .5f), "rs" to (1f to .5f))) + val elements = LegacyGamepadLayout(context, width, height).elements() + assertStickView(elements, width, height, "$width x $height") + ControllerPrefs.resetLayout(context, width, height) + } + } + @Test @Config(qualifiers = "w833dp-h468dp-land-369dpi") fun buttonSizeKeepsTheGamepadShapeAtHandheldDensity() { for ((w, h) in listOf(1920 to 1080, 1920 to 1200)) { @@ -191,4 +208,10 @@ class InputLayoutToolsTest { } } } + + @Test @Config(qualifiers = "w745dp-h343dp-land-420dpi") + fun wideHighDensityGamepadKeepsItsShape() { + val elements = LegacyGamepadLayout(context, 2608, 1200).elements() + assertGamepadShape(elements, 2608, 1200, "2608 x 1200") + } } diff --git a/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt b/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt index 4bfa52f518..9c81655b0a 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/InputLibraryTest.kt @@ -592,4 +592,45 @@ class InputLibraryTest { assertEquals(old.preset(InputStockLayouts.TRACKPAD), upgraded.preset(InputStockLayouts.TRACKPAD)) assertEquals(InputStockLayouts.layouts().single { it.id == InputLibraries.DECK }.elements, upgraded.layouts.single { it.id == InputLibraries.DECK }.elements) } + + @Test fun stockSecondScreenPanelsKeepTapsClicking() { + val library = InputLibraries.read(context) + for (desktop in listOf(false, true)) for (panel in listOf(null, InputStockLayouts.TRACKPAD) + DeckPanel.entries.map { it.bindings }) { + val shown = library.panelLayout(desktop, panel)!!.elements + assertTrue(shown.isNotEmpty()) + assertFalse(library.compileActive(desktop, panel).showsMouseButton(InputRole.SECONDARY, shown, library.compileStock(desktop, panel))) + } + } + + @Test fun userBoundSecondScreenMouseButtonIsDetected() { + val stock = InputLibraries.read(context) + val grips = DeckPanel.GRIPS.bindings + val button = stock.panelLayout(false, grips)!!.elements.first { it.control.dimensions == 1 } + val bound = stock.withPreset(stock.preset(grips).copy(elements = mapOf(button.id to InputAction.MouseButton(272)))) + for (desktop in listOf(false, true)) { + assertTrue(bound.compileActive(desktop, grips).showsMouseButton(InputRole.SECONDARY, listOf(button), bound.compileStock(desktop, grips))) + assertFalse(bound.compileActive(desktop, grips).showsMouseButton(InputRole.PRIMARY, listOf(button), bound.compileStock(desktop, grips))) + } + val pad = stock.panelLayout(true, InputStockLayouts.TRACKPAD)!!.elements.single() + val rebound = stock.withPreset(stock.preset(InputStockLayouts.TRACKPAD).let { it.copy(clicks = it.clicks + (pad.id to InputAction.MouseButton(273))) }) + assertTrue(rebound.compileActive(true).showsMouseButton(InputRole.SECONDARY, listOf(pad), rebound.compileStock(true))) + } + + @Test fun copiedStockPanelsKeepTapsClickingUntilAMouseButtonIsAdded() { + val stock = InputLibraries.read(context) + for (desktop in listOf(false, true)) { + val source = stock.panelLayout(desktop, null)!! + val copied = stock.useLayout(stock.activeId(desktop), InputRole.SECONDARY, source.id, shared = false) + val layout = copied.activeLayout(desktop, InputRole.SECONDARY)!! + assertNotEquals(source.id, layout.id) + assertEquals(source.id, layout.origin) + assertFalse(copied.compileActive(desktop).showsMouseButton(InputRole.SECONDARY, layout.elements, copied.compileStock(desktop))) + val added = InputSurfaceElement(InputControl.A, .4f, .4f, .1f, .1f, id = "custom:added") + val grown = copied.withLayout(layout.copy(elements = layout.elements + added)) + val bindings = grown.activePart(desktop, InputRole.SECONDARY).bindings + val bound = grown.withPreset(grown.preset(bindings).let { it.copy(elements = it.elements + (added.id to InputAction.MouseButton(272))) }) + assertTrue(bound.compileActive(desktop).showsMouseButton(InputRole.SECONDARY, layout.elements + added, bound.compileStock(desktop))) + assertFalse(bound.compileActive(desktop).showsMouseButton(InputRole.SECONDARY, layout.elements, bound.compileStock(desktop))) + } + } } diff --git a/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt index 0a95382937..cfe027586a 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/OnScreenLayoutTest.kt @@ -49,6 +49,83 @@ class OnScreenLayoutTest { } } + @Test @Config(qualifiers = "w745dp-h343dp-land-420dpi") + fun aBuiltInGamepadSavedAtTheDisplaySizeRegeneratesForTheMeasuredSurface() { + val saved = gamepad().copy(elements = LegacyGamepadLayout(context, 2608, 1200).elements(), aspect = 2608f / 1200) + val placed = OnScreenLayout.elements(context, saved, 2048, 1200, Rect()) + assertEquals(LegacyGamepadLayout(context, 2048, 1200).regenerate(saved.elements), placed) + } + + @Test @Config(qualifiers = "w745dp-h343dp-land-420dpi") + fun previouslyGeneratedEdgeSticksRegenerateWithoutOverridingCustomGeometry() { + val w = 2608 + val h = 1200 + ControllerPrefs.setLayout(context, w, h, mapOf("ls" to (0f to .5f), "rs" to (1f to .5f))) + val generator = LegacyGamepadLayout(context, w, h) + val old = generator.elements(previousStickGeometry = true) + val current = generator.elements() + assertTrue(old.filter { it.control == InputControl.LS || it.control == InputControl.RS }.zip(current.filter { it.control == InputControl.LS || it.control == InputControl.RS }).any { (a, b) -> kotlin.math.abs(a.width - b.width) > .01f }) + val saved = gamepad().copy(elements = old, aspect = w.toFloat() / h) + assertEquals(LegacyGamepadLayout(context, 2048, h).regenerate(old), OnScreenLayout.elements(context, saved, 2048, h, Rect())) + val custom = saved.copy(elements = old.map { if (it.id == "legacy:a") it.copy(x = .4f) else it }) + assertEquals(OnScreenLayout.fit(custom.elements, custom.aspect, 1f, 2048, h, Rect()), OnScreenLayout.elements(context, custom, 2048, h, Rect())) + } + + @Test fun savingTheEditorFrameKeepsEveryControlWhereTheEditorShowsIt() { + val w = 2608 + val h = 1200 + val layout = SavedInputLayout("custom", "Custom", listOf( + InputSurfaceElement(InputControl.A, .1f, .2f, .1f, .2f, "custom:a"), + InputSurfaceElement(InputControl.B, .7f, .6f, .1f, .2f, "custom:b")), aspect = 16f / 9f) + val displayed = OnScreenLayout.editorElements(context, layout, w, h, edited = true) + val moved = displayed.map { if (it.id == "custom:a") it.copy(x = .4f) else it } + val frame = OnScreenLayout.editorFrame(layout, moved + InputSurfaceElement(InputControl.X, .5f, .5f, .1f, .1f, "builtin:keyboard")) + assertEquals(layout.elements.map { it.id }, frame.map { it.id }) + val saved = layout.copy(elements = frame, aspect = w.toFloat() / h) + val game = OnScreenLayout.elements(context, saved, w, h, Rect()) + val editor = OnScreenLayout.editorElements(context, saved, w, h, edited = true) + for (shown in moved) { + assertArrayEquals(px(shown, w, h), px(game.first { it.id == shown.id }, w, h), .001f) + assertArrayEquals(px(shown, w, h), px(editor.first { it.id == shown.id }, w, h), .001f) + } + } + + @Test fun editorAndGameUseTheSamePixelRectsOnWideAndStandardScreens() { + val layout = gamepad() + for ((w, h) in listOf(2000 to 900, 1600 to 900)) { + val game = OnScreenLayout.elements(context, layout, w, h, Rect()) + val editor = OnScreenLayout.editorElements(context, layout, w, h) + assertEquals(game.map { it.id }, editor.map { it.id }) + game.zip(editor).forEach { (gameElement, editorElement) -> + assertArrayEquals(px(gameElement, w, h), px(editorElement, w, h), .001f) + } + } + } + + @Test fun editedGeneratedAndCustomLayoutsKeepTheirPixelRectsAcrossRefreshes() { + for ((w, h) in listOf(2000 to 900, 1600 to 900)) { + val generated = gamepad() + val generatedEdit = generated.elements.map { if (it.id == "legacy:a") it.copy(x = .3f, y = .4f, width = .12f, height = .12f) else it } + val generatedSaved = generated.copy(elements = generatedEdit, aspect = w.toFloat() / h) + val generatedPixels = px(OnScreenLayout.elements(context, generatedSaved, w, h, Rect()).first { it.id == "legacy:a" }, w, h) + val generatedRefresh = px(OnScreenLayout.editorElements(context, generatedSaved, w, h, edited = true).first { it.id == "legacy:a" }, w, h) + assertArrayEquals(generatedPixels, generatedRefresh, .001f) + + val custom = SavedInputLayout("custom", "Custom", listOf(InputSurfaceElement(InputControl.A, .3f, .4f, .12f, .12f)), aspect = w.toFloat() / h) + val customRefresh = OnScreenLayout.editorElements(context, custom, w, h, edited = true) + assertArrayEquals(px(customRefresh.single(), w, h), px(OnScreenLayout.editorElements(context, custom.copy(elements = customRefresh), w, h, edited = true).single(), w, h), .001f) + } + } + + @Test fun resetPositionsRestoresGeneratedGeometryAfterAnEdit() { + for ((w, h) in listOf(2000 to 900, 1600 to 900)) { + val original = gamepad() + val moved = original.copy(elements = original.elements.map { if (it.id == "legacy:a") it.copy(x = .3f) else it }, aspect = w.toFloat() / h) + val reset = LegacyGamepadLayout(context, w, h).regenerate(moved.elements) + assertEquals(LegacyGamepadLayout(context, w, h).regenerate(original.elements), OnScreenLayout.elements(context, moved.copy(elements = reset), w, h, Rect())) + } + } + @Test fun regenerationKeepsTheUsersButtonStylesAndRemovedButtons() { val layout = gamepad().let { g -> g.copy(elements = g.elements.filterNot { it.id == "legacy:y" }.map { if (it.id == "legacy:a") it.copy(opacity = .4f, icon = 0, name = "Jump") else it }) } val placed = OnScreenLayout.elements(context, layout, 2000, 1000, Rect()) diff --git a/app/src/test/java/com/droiddeck/launcher/input/OnScreenMouseButtonTest.kt b/app/src/test/java/com/droiddeck/launcher/input/OnScreenMouseButtonTest.kt new file mode 100644 index 0000000000..aebe881c8a --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/OnScreenMouseButtonTest.kt @@ -0,0 +1,71 @@ +package com.droiddeck.launcher.input + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class OnScreenMouseButtonTest { + private val button = InputSurfaceElement(InputControl.A, .8f, .6f, .1f, .1f, id = "custom:left") + private val stick = InputSurfaceElement(InputControl.LS, .1f, .6f, .2f, .3f, id = "custom:stick") + private val legacyA = InputSurfaceElement(InputControl.A, .8f, .6f, .1f, .1f) + private val game = InputProfile.defaults(InputProfile.GAME) + private val desktop = InputProfile.defaults(InputProfile.DESKTOP) + private val overlay = InputControl.entries.map { InputSurfaceElement(it, .1f, .1f, .1f, .1f) } + + private fun profile(vararg elements: Pair, clicks: Map = emptyMap(), base: InputProfile = game) = + base.copy(elements = mapOf(InputRole.PRIMARY to elements.toMap()), clicks = mapOf(InputRole.PRIMARY to clicks)) + + @Test fun shownButtonBoundToAMouseButtonIsDetected() { + listOf(272, 273, 274).forEach { code -> + assertTrue(profile(button.id to InputAction.MouseButton(code)).showsMouseButton(InputRole.PRIMARY, listOf(stick, button), game)) + } + } + + @Test fun stickClickBoundToAMouseButtonIsDetected() { + val profile = profile(stick.id to InputAction.Native(), clicks = mapOf(stick.id to InputAction.MouseButton(272))) + assertTrue(profile.showsMouseButton(InputRole.PRIMARY, listOf(stick), game)) + } + + @Test fun legacyButtonUsesItsRoleBinding() { + val profile = game.withBinding(InputRole.PRIMARY, InputControl.A, InputAction.MouseButton(272)) + assertTrue(profile.showsMouseButton(InputRole.PRIMARY, listOf(legacyA), game)) + assertFalse(profile.showsMouseButton(InputRole.SECONDARY, listOf(legacyA), game)) + } + + @Test fun stockDesktopOverlayKeepsTapsClicking() { + assertFalse(desktop.showsMouseButton(InputRole.PRIMARY, overlay, desktop)) + } + + @Test fun userBoundMouseButtonInDesktopIsDetected() { + val rebound = desktop.withBinding(InputRole.PRIMARY, InputControl.X, InputAction.MouseButton(272)) + assertTrue(rebound.showsMouseButton(InputRole.PRIMARY, overlay, desktop)) + val stickClick = desktop.withBinding(InputRole.PRIMARY, InputControl.L3, InputAction.MouseButton(274)) + assertTrue(stickClick.showsMouseButton(InputRole.PRIMARY, overlay, desktop)) + assertTrue(profile(button.id to InputAction.MouseButton(272), base = desktop).showsMouseButton(InputRole.PRIMARY, overlay + button, desktop)) + } + + @Test fun desktopBindingsOnAGameBaseProfileAreUserPicked() { + val copied = desktop.copy(id = "custom") + assertTrue(copied.showsMouseButton(InputRole.PRIMARY, overlay, game)) + } + + @Test fun layoutWithoutAMouseButtonKeepsTapsClicking() { + val profile = profile(button.id to InputAction.Keys(listOf(57)), stick.id to InputAction.Pointer()) + assertFalse(profile.showsMouseButton(InputRole.PRIMARY, listOf(stick, button), game)) + assertFalse(game.showsMouseButton(InputRole.PRIMARY, listOf(legacyA, stick) + overlay, game)) + } + + @Test fun hiddenMouseButtonDoesNotCount() { + assertFalse(profile(button.id to InputAction.MouseButton(272)).showsMouseButton(InputRole.PRIMARY, listOf(stick), game)) + assertFalse(profile(button.id to InputAction.MouseButton(272)).showsMouseButton(InputRole.PRIMARY, emptyList(), game)) + } + + @Test fun physicalMouseBindingsDoNotCount() { + val profile = game.withBinding(InputRole.PHYSICAL, InputControl.A, InputAction.MouseButton(272)) + assertFalse(profile.showsMouseButton(InputRole.PRIMARY, listOf(legacyA), game)) + } + + @Test fun invalidMouseCodeDoesNotCount() { + assertFalse(profile(button.id to InputAction.MouseButton(1)).showsMouseButton(InputRole.PRIMARY, listOf(button), game)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/PadPartialAxesTest.kt b/app/src/test/java/com/droiddeck/launcher/input/PadPartialAxesTest.kt index ae46c9d5e3..b79e813a9e 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/PadPartialAxesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/PadPartialAxesTest.kt @@ -83,6 +83,117 @@ class PadPartialAxesTest { assertEquals(-0.6f, pad().rightY) } + @Test fun onlyRxRyAxesProvideTheRightStick() { + val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY) + motion(device, MotionEvent.AXIS_RX to 0.6f, MotionEvent.AXIS_RY to -0.6f) + assertEquals(0.6f, pad().rightX) + assertEquals(-0.6f, pad().rightY) + } + + @Test fun rxRyStickWithoutZRzKeepsTriggersReleased() { + val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY) + motion(device, MotionEvent.AXIS_RX to 0f, MotionEvent.AXIS_RY to 0f) + assertEquals(0f, pad().leftTrigger) + assertEquals(0f, pad().rightTrigger) + } + + @Test fun rxRyStickReadsDedicatedTriggerAxes() { + val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_RTRIGGER) + motion(device, MotionEvent.AXIS_RX to 0.6f, MotionEvent.AXIS_RY to 0f, + MotionEvent.AXIS_LTRIGGER to 0.4f, MotionEvent.AXIS_RTRIGGER to 0f) + assertEquals(0.6f, pad().rightX) + assertEquals(0.4f, pad().leftTrigger) + assertEquals(0f, pad().rightTrigger) + } + + @Test fun leftTriggerFallsBackToBrakeWhenDedicatedAxisIsZero() { + val device = device(MotionEvent.AXIS_LTRIGGER, MotionEvent.AXIS_BRAKE) + motion(device, MotionEvent.AXIS_LTRIGGER to 0f, MotionEvent.AXIS_BRAKE to 0.7f) + assertEquals(0.7f, pad().leftTrigger) + } + + @Test fun rightTriggerFallsBackToGasWhenDedicatedAxisIsZero() { + val device = device(MotionEvent.AXIS_RTRIGGER, MotionEvent.AXIS_GAS) + motion(device, MotionEvent.AXIS_RTRIGGER to 0f, MotionEvent.AXIS_GAS to 0.8f) + assertEquals(0.8f, pad().rightTrigger) + } + + @Test fun onlyZRzAxesProvideTheRightStick() { + val device = device(MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ) + motion(device, MotionEvent.AXIS_Z to 0.6f, MotionEvent.AXIS_RZ to -0.6f) + assertEquals(0.6f, pad().rightX) + assertEquals(-0.6f, pad().rightY) + } + + @Test fun bothPairsUseThePairAtRestNearCentreAsTheStick() { + val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ) + motion(device, MotionEvent.AXIS_RX to -1f, MotionEvent.AXIS_RY to -1f, + MotionEvent.AXIS_Z to 0f, MotionEvent.AXIS_RZ to 0f) + assertEquals(0f, pad().rightX) + assertEquals(0f, pad().rightY) + motion(device, MotionEvent.AXIS_RX to 0.2f, MotionEvent.AXIS_RY to -0.3f, + MotionEvent.AXIS_Z to 0.7f, MotionEvent.AXIS_RZ to -0.8f) + assertEquals(0.7f, pad().rightX) + assertEquals(-0.8f, pad().rightY) + } + + @Test fun bothPairsUseRxRyAsStickWhenZRzRestAtMinimum() { + val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ) + motion(device, MotionEvent.AXIS_RX to 0f, MotionEvent.AXIS_RY to 0f, + MotionEvent.AXIS_Z to -1f, MotionEvent.AXIS_RZ to -1f) + assertEquals(0f, pad().rightX) + assertEquals(0f, pad().rightY) + assertEquals(0f, pad().leftTrigger) + assertEquals(0f, pad().rightTrigger) + motion(device, MotionEvent.AXIS_RX to 0.6f, MotionEvent.AXIS_RY to -0.6f, + MotionEvent.AXIS_Z to 1f, MotionEvent.AXIS_RZ to 1f) + assertEquals(0.6f, pad().rightX) + assertEquals(-0.6f, pad().rightY) + assertEquals(1f, pad().leftTrigger) + assertEquals(1f, pad().rightTrigger) + } + + @Test fun nonWiredZeroToOneSignedZTriggersNormalizeFromTheirRange() { + val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ, + zeroToOneAxes = setOf(MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ)) + motion(device, MotionEvent.AXIS_RX to 0f, MotionEvent.AXIS_RY to 0f, + MotionEvent.AXIS_Z to 0f, MotionEvent.AXIS_RZ to 0f) + assertEquals(0f, pad().leftTrigger) + assertEquals(0f, pad().rightTrigger) + motion(device, MotionEvent.AXIS_RX to 0.6f, MotionEvent.AXIS_RY to -0.6f, + MotionEvent.AXIS_Z to 1f, MotionEvent.AXIS_RZ to 1f) + assertEquals(1f, pad().leftTrigger) + assertEquals(1f, pad().rightTrigger) + } + + @Test fun movingFirstEventDoesNotLockTheWrongStickPair() { + val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_Z, MotionEvent.AXIS_RZ) + motion(device, MotionEvent.AXIS_RX to 1f, MotionEvent.AXIS_RY to 0f, + MotionEvent.AXIS_Z to 0f, MotionEvent.AXIS_RZ to 0f) + assertEquals(0f, pad().rightX) + assertEquals(0f, pad().rightY) + motion(device, MotionEvent.AXIS_RX to 0f, MotionEvent.AXIS_RY to 0f, + MotionEvent.AXIS_Z to -1f, MotionEvent.AXIS_RZ to -1f) + motion(device, MotionEvent.AXIS_RX to 0.6f, MotionEvent.AXIS_RY to -0.6f, + MotionEvent.AXIS_Z to -1f, MotionEvent.AXIS_RZ to -1f) + assertEquals(0.6f, pad().rightX) + assertEquals(-0.6f, pad().rightY) + } + + @Test fun dedicatedRightTriggerWinsOverSignedRightTrigger() { + val device = device(MotionEvent.AXIS_RX, MotionEvent.AXIS_RY, MotionEvent.AXIS_Z, + MotionEvent.AXIS_RZ, MotionEvent.AXIS_RTRIGGER) + motion(device, MotionEvent.AXIS_RX to 0f, MotionEvent.AXIS_RY to 0f, + MotionEvent.AXIS_Z to -1f, MotionEvent.AXIS_RZ to -1f) + motion(device, MotionEvent.AXIS_RX to 0.6f, MotionEvent.AXIS_RY to -0.6f, + MotionEvent.AXIS_Z to -1f, MotionEvent.AXIS_RZ to -1f, + MotionEvent.AXIS_RTRIGGER to 0.7f) + assertEquals(0f, pad().leftTrigger) + assertEquals(0.7f, pad().rightTrigger) + assertEquals(0.6f, pad().rightX) + assertEquals(-0.6f, pad().rightY) + } + @Test fun sticksWithoutTriggerOrHatAxesPreserveAllDigitalControls() { val device = device() key(device, KeyEvent.KEYCODE_BUTTON_L2) @@ -208,14 +319,15 @@ class PadPartialAxesTest { try { assertTrue(bridge.onMotionEvent(event)) } finally { event.recycle() } } - private fun device(vararg axes: Int, wired: Boolean = false): InputDevice { + private fun device(vararg axes: Int, wired: Boolean = false, zeroToOneAxes: Set = emptySet()): 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) + val min = if (axis in zeroToOneAxes) 0f else -1f + builder.addMotionRange(axis, InputDevice.SOURCE_JOYSTICK, min, 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/ScrollTouchGesturesTest.kt b/app/src/test/java/com/droiddeck/launcher/input/ScrollTouchGesturesTest.kt index 60436eaabd..ea2d50c5fb 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/ScrollTouchGesturesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/ScrollTouchGesturesTest.kt @@ -131,6 +131,50 @@ class ScrollTouchGesturesTest { assertEquals(listOf("move 400,300"), events) } + @Test fun tapsAndHoldsDoNotClickWhileClicksAreOff() { + gestures.clicks = false + touch(MotionEvent.ACTION_DOWN, 400f, 300f) + advance(80) + touch(MotionEvent.ACTION_UP, 400f, 300f) + advance(100) + touch(MotionEvent.ACTION_DOWN, 400f, 300f) + advance(600) + touch(MotionEvent.ACTION_UP, 402f, 301f) + advance(100) + assertEquals(listOf("move 400,300", "move 400,300"), events) + } + + @Test fun holdThenMoveScrollsWhileClicksAreOff() { + gestures.clicks = false + touch(MotionEvent.ACTION_DOWN, 400f, 800f) + advance(600) + touch(MotionEvent.ACTION_MOVE, 402f, 500f) + advance(200) + touch(MotionEvent.ACTION_UP, 402f, 500f) + advance(100) + assertEquals(300f, scrolledY, 0.01f) + assertEquals(listOf("move 400,800"), events) + } + + @Test fun turningClicksOffReleasesAClickInFlight() { + touch(MotionEvent.ACTION_DOWN, 400f, 300f) + advance(80) + touch(MotionEvent.ACTION_UP, 400f, 300f) + gestures.clicks = false + touch(MotionEvent.ACTION_DOWN, 400f, 300f) + advance(80) + touch(MotionEvent.ACTION_UP, 400f, 300f) + advance(100) + assertEquals(listOf("move 400,300", "left down", "left up", "move 400,300"), events) + events.clear() + gestures.clicks = true + touch(MotionEvent.ACTION_DOWN, 400f, 300f) + advance(80) + touch(MotionEvent.ACTION_UP, 400f, 300f) + advance(100) + assertEquals(listOf("move 400,300", "left down", "left up"), events) + } + @Test fun aSecondFingerDoesNotJumpTheScroll() { touch(MotionEvent.ACTION_DOWN, 400f, 900f) advance(100) diff --git a/app/src/test/java/com/droiddeck/launcher/input/SecondScreenModeTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SecondScreenModeTest.kt index 9956f1aa6d..566a091c42 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/SecondScreenModeTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/SecondScreenModeTest.kt @@ -1,9 +1,58 @@ package com.droiddeck.launcher.input import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue import org.junit.Test class SecondScreenModeTest { + @Test fun fallbackSelectionSurvivesRecreationAndRequestedDisplaySurvivesDisconnect() { + var saved = 2 + SecondScreenDisplays.selection(saved, listOf(3), false) { saved = it } + assertEquals(3, saved) + assertEquals(3, SecondScreenDisplays.selection(saved, listOf(3), true)) + SecondScreenDisplays.selection(saved, listOf(2), true) { saved = it } + assertEquals(3, saved) + } + + @Test fun keyboardFallsBackOnlyForADisconnectedRequestedDisplay() { + val taken: (Int) -> Boolean = { it == 2 } + val free: (Int) -> Boolean = { false } + assertTrue(SecondScreenDisplays.keyboardOnPrimary(true, 2, listOf(3), taken = free)) + assertTrue(SecondScreenDisplays.keyboardOnPrimary(true, 2, listOf(2, 3), taken = taken)) + assertFalse(SecondScreenDisplays.keyboardOnPrimary(true, 2, listOf(2, 3), taken = free)) + assertFalse(SecondScreenDisplays.keyboardOnPrimary(false, 2, listOf(3), taken = taken)) + assertFalse(SecondScreenDisplays.keyboardOnPrimary(true, -1, listOf(3), taken = taken)) + } + + @Test fun primaryFallbackRequiresVisibleActivity() { + for (available in listOf(emptyList(), listOf(2))) { + assertTrue(SecondScreenDisplays.keyboardOnPrimary(true, 2, available, true) { true }) + assertFalse(SecondScreenDisplays.keyboardOnPrimary(true, 2, available, false) { true }) + } + } + + @Test fun keyboardRouteIncludesOccupiedDisplayFallbackOnlyWhenEnabled() { + val fallback = SecondScreenDisplays.keyboardOnPrimary(true, 2, listOf(2)) { it == 2 } + assertTrue(fallback) + assertTrue(SecondScreenDisplays.routeKeyboard(true, true, false, false, fallback)) + assertFalse(SecondScreenDisplays.routeKeyboard(true, false, false, false, fallback)) + assertFalse(SecondScreenDisplays.routeKeyboard(false, true, false, false, fallback)) + assertFalse(SecondScreenDisplays.routeKeyboard(true, true, false, false, false)) + assertTrue(SecondScreenDisplays.routeKeyboard(true, true, true, false, false)) + assertTrue(SecondScreenDisplays.routeKeyboard(true, true, false, true, false)) + } + + @Test fun selectedGameDisplayIsNotReplacedWhenItDisconnects() { + assertEquals(2, SecondScreenDisplays.selection(2, listOf(3), true)) + assertEquals(2, SecondScreenDisplays.selection(2, emptyList(), true)) + assertEquals(2, SecondScreenDisplays.selection(2, listOf(3, 2), true)) + assertEquals(3, SecondScreenDisplays.selection(3, listOf(3), true)) + assertEquals(3, SecondScreenDisplays.selection(2, listOf(3), false)) + assertEquals(3, SecondScreenDisplays.selection(-1, listOf(3), true)) + assertEquals(-1, SecondScreenDisplays.selection(-1, emptyList(), false)) + } + @Test fun withNothingRememberedDeckPadsGetControlsAndOthersTheDashboard() { assertEquals(SecondScreenMode.DECK_CONTROLS, SecondScreenMode.opening(null, deckPad = true, dashboard = true)) assertEquals(SecondScreenMode.DASHBOARD, SecondScreenMode.opening(null, deckPad = false, dashboard = true)) diff --git a/app/src/test/java/com/droiddeck/launcher/input/SessionFieldKeyboardTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SessionFieldKeyboardTest.kt new file mode 100644 index 0000000000..483c61f562 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/input/SessionFieldKeyboardTest.kt @@ -0,0 +1,169 @@ +package com.droiddeck.launcher.input + +import android.view.KeyEvent +import android.view.WindowInsets +import com.droiddeck.launcher.SessionActivity +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.annotation.Config +import org.robolectric.util.ReflectionHelpers + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [28], manifest = Config.NONE) +class SessionFieldKeyboardTest { + private lateinit var activity: SessionActivity + private lateinit var keyboard: KeyboardHost + + @Before fun setUp() { + activity = Robolectric.buildActivity(SessionActivity::class.java).get() + keyboard = KeyboardHost(activity) + ReflectionHelpers.setField(activity, "keyboard", keyboard) + keyboard.onImeChanged = { visible -> + ReflectionHelpers.callInstanceMethod(activity, "onPrimaryImeChanged", + ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, visible)) + } + } + + @Test fun guestDismissalClosesOnlyTheGuestOwnedKeyboard() { + openFieldKeyboard() + call("dismissFieldKeyboard") + assertFalse(keyboard.shown) + call("showPrimaryKeyboard") + call("dismissFieldKeyboard") + assertTrue(keyboard.shown) + } + + @Test fun pauseHideThenManualReopenSurvivesGuestDismissal() { + openFieldKeyboard() + call("hidePrimaryKeyboard") + assertFalse(keyboard.shown) + call("showPrimaryKeyboard") + call("dismissFieldKeyboard") + assertTrue(keyboard.shown) + openFieldKeyboard() + call("dismissFieldKeyboard") + assertFalse(keyboard.shown) + } + + @Test fun manualToggleAndPcKeyboardRelinquishGuestOwnership() { + openFieldKeyboard() + call("togglePrimaryKeyboard") + call("togglePrimaryKeyboard") + call("dismissFieldKeyboard") + assertTrue(keyboard.shown) + openFieldKeyboard() + call("togglePcKeyboard") + call("showPrimaryKeyboard") + call("dismissFieldKeyboard") + assertTrue(keyboard.shown) + } + + @Test fun pendingGuestRequestWaitsForFocusAndCanBeDismissed() { + ReflectionHelpers.callInstanceMethod(activity, "setGameOnBottom", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, true)) + ReflectionHelpers.callInstanceMethod(activity, "setSelectedSecondScreenDisplay", ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, 2)) + ReflectionHelpers.callInstanceMethod(activity, "setResumed", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, true)) + call("openBottomKeyboard") + ReflectionHelpers.callInstanceMethod(activity, "retryFieldKeyboard", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, false)) + assertFalse(keyboard.shown) + call("dismissFieldKeyboard") + ReflectionHelpers.callInstanceMethod(activity, "retryFieldKeyboard", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, true)) + assertFalse(keyboard.shown) + call("openBottomKeyboard") + ReflectionHelpers.callInstanceMethod(activity, "retryFieldKeyboard", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, true)) + assertTrue(keyboard.shown) + call("dismissFieldKeyboard") + assertFalse(keyboard.shown) + } + + @Config(sdk = [33]) + @Test fun staleHiddenEventFromEarlierHideKeepsNewGuestOwnership() { + call("showPrimaryKeyboard") + ime(true) + call("hidePrimaryKeyboard") + requestFieldKeyboard() + ime(false) + assertTrue(owned()) + ime(true) + call("dismissFieldKeyboard") + assertFalse(keyboard.shown) + } + + @Config(sdk = [33]) + @Test fun hiddenEventAfterGuestKeyboardShowsClearsOwnership() { + requestFieldKeyboard() + ime(true) + ime(false) + assertFalse(owned()) + call("showPrimaryKeyboard") + call("dismissFieldKeyboard") + assertTrue(keyboard.shown) + } + + @Config(sdk = [33]) + @Test fun guestRequestWhileKeyboardAlreadyVisibleClearsOnRealDismissal() { + call("showPrimaryKeyboard") + ime(true) + requestFieldKeyboard() + assertTrue(owned()) + ime(false) + assertFalse(owned()) + } + + @Test fun backDismissalWithoutImeInsetsClearsOwnership() { + requestFieldKeyboard() + assertTrue(owned()) + val t = System.currentTimeMillis() + keyboard.onKeyPreIme(KeyEvent.KEYCODE_BACK, KeyEvent(t, t, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK, 0)) + assertFalse(keyboard.shown) + assertFalse(owned()) + } + + @Test fun focusReturnSkipsPrimaryKeyboardWhenDestinationNoLongerPrimary() { + setFlag("setGameOnBottom", true) + selectDisplay(2) + setFlag("setResumed", true) + call("openBottomKeyboard") + retry(false) + setFlag("setGameOnBottom", false) + retry(true) + assertFalse(keyboard.shown) + assertFalse(owned()) + assertFalse(ReflectionHelpers.getField(activity, "pendingFieldKeyboard")) + } + + private fun requestFieldKeyboard() { + setFlag("setGameOnBottom", true) + selectDisplay(2) + setFlag("setResumed", true) + call("openBottomKeyboard") + retry(true) + assertTrue(keyboard.shown) + } + + private fun ime(visible: Boolean) { + keyboard.dispatchApplyWindowInsets(WindowInsets.Builder().setVisible(WindowInsets.Type.ime(), visible).build()) + } + + private fun owned() = ReflectionHelpers.getField(activity, "fieldKeyboardOnPrimary") + + private fun selectDisplay(id: Int) = ReflectionHelpers.callInstanceMethod(activity, "setSelectedSecondScreenDisplay", + ReflectionHelpers.ClassParameter.from(Int::class.javaPrimitiveType, id)) + + private fun retry(focus: Boolean) = ReflectionHelpers.callInstanceMethod(activity, "retryFieldKeyboard", + ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, focus)) + + private fun setFlag(name: String, value: Boolean) = ReflectionHelpers.callInstanceMethod(activity, name, + ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, value)) + + private fun openFieldKeyboard() { + ReflectionHelpers.setField(activity, "fieldKeyboardOnPrimary", true) + keyboard.show() + } + + private fun call(name: String) = ReflectionHelpers.callInstanceMethod(activity, name) +} diff --git a/app/src/test/java/com/droiddeck/launcher/input/SessionInputPointerTest.kt b/app/src/test/java/com/droiddeck/launcher/input/SessionInputPointerTest.kt index 835eca2e9b..879c18233c 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/SessionInputPointerTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/SessionInputPointerTest.kt @@ -186,6 +186,42 @@ class SessionInputPointerTest { assertEquals(29 to 0, CompositorShadow.keys.last()) } + @Test fun losingPointerCaptureReleasesMouseButtonsButKeepsKeyboardKeysHeld() { + ReflectionHelpers.getField>(activity, "resumed\$delegate").value = true + val keys = ReflectionHelpers.getField(activity, "heldKeys") + val buttons = ReflectionHelpers.getField(activity, "heldButtons") + output.key(17, true) + keys.set(8, 30, true) + buttons.set(2, 272, true) + CompositorShadow.keys.clear() + CompositorShadow.events.clear() + ReflectionHelpers.callInstanceMethod(activity, "releaseHeldInputOnCaptureLoss") + assertTrue(CompositorShadow.keys.none { it.second == 0 }) + assertTrue(CompositorShadow.events.contains(Triple(3, 272, 0))) + output.key(17, false) + assertEquals(17 to 0, CompositorShadow.keys.last()) + } + + @Test fun losingPointerCaptureToAnotherInputSurfaceReleasesKeyboardKeys() { + ReflectionHelpers.getField>(activity, "resumed\$delegate").value = true + for (state in listOf("drawerOpenState", "wowChatOnTop")) { + val open: androidx.compose.runtime.MutableState = ReflectionHelpers.getField(activity, state + "\$delegate") + open.value = true + ReflectionHelpers.getField(activity, "heldKeys").set(16, 17, true) + CompositorShadow.keys.clear() + ReflectionHelpers.callInstanceMethod(activity, "releaseHeldInputOnCaptureLoss") + assertEquals(state, 17 to 0, CompositorShadow.keys.last()) + open.value = false + } + } + + @Test fun openingTheSessionMenuReleasesHeldKeyboardKeys() { + ReflectionHelpers.getField(activity, "heldKeys").set(16, 17, true) + CompositorShadow.keys.clear() + ReflectionHelpers.callInstanceMethod(activity, "setDrawerOpen", ReflectionHelpers.ClassParameter.from(Boolean::class.javaPrimitiveType, true)) + assertEquals(17 to 0, CompositorShadow.keys.last()) + } + @Test fun horizontalWheelUsesTheSameDirectionInBothMouseBackends() { output.scrollHorizontal(2) assertEquals(listOf(Triple(11, 0, 240)), CompositorShadow.events) diff --git a/app/src/test/java/com/droiddeck/launcher/input/ShortcutsRelayTest.kt b/app/src/test/java/com/droiddeck/launcher/input/ShortcutsRelayTest.kt index 2a8d99cd81..283951b5e0 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/ShortcutsRelayTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/ShortcutsRelayTest.kt @@ -32,9 +32,10 @@ class ShortcutsRelayTest { private fun choose(value: String?) = Settings.Secure.putString(context.contentResolver, Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES, value) - private fun installCompanion() { + @Suppress("DEPRECATION") + private fun installCompanion(version: Int = Relay.VERSION) { val app = ApplicationInfo().apply { packageName = Relay.PACKAGE; uid = companionUid } - shadowOf(context.packageManager).installPackage(PackageInfo().apply { packageName = Relay.PACKAGE; applicationInfo = app }) + shadowOf(context.packageManager).installPackage(PackageInfo().apply { packageName = Relay.PACKAGE; applicationInfo = app; versionCode = version }) shadowOf(context.packageManager).setPackagesForUid(companionUid, Relay.PACKAGE) } @@ -84,6 +85,26 @@ class ShortcutsRelayTest { assertEquals(0, config(binder, companionUid)) } + @Test fun anOldCompanionIsOfferedAsAnUpdate() { + installCompanion(version = 1) + choose("${Relay.PACKAGE}/${Relay.SERVICE}") + assertTrue(SteamIntegration.shortcutsEnabled(context)) + assertFalse(SteamIntegration.read(context).shortcuts) + installCompanion() + assertTrue(SteamIntegration.read(context).shortcuts) + } + + @Test fun droidDeckHoldsTheRelayOnlyWhileAScreenIsStarted() { + installCompanion() + ShortcutsRelay.Holder.install(context) + val activity = Robolectric.buildActivity(android.app.Activity::class.java).create() + activity.start() + assertEquals(1, shadowOf(context).boundServiceConnections.size) + activity.stop() + shadowOf(android.os.Looper.getMainLooper()).idleFor(java.time.Duration.ofSeconds(2)) + assertEquals(0, shadowOf(context).boundServiceConnections.size) + } + @Test fun windowSnapshotsSurviveTheTrip() { val sent = mapOf(2 to listOf(Relay.Window(7, 1, 3, Rect(0, 0, 1080, 1240), "guest.app"), Relay.Window(8, 2, 1, Rect(1, 2, 3, 4), null))) val got = Relay.decode(Relay.encode(sent)) diff --git a/app/src/test/java/com/droiddeck/launcher/input/TouchpadGesturesTest.kt b/app/src/test/java/com/droiddeck/launcher/input/TouchpadGesturesTest.kt index 2b84e3ae4d..c967ce02fd 100644 --- a/app/src/test/java/com/droiddeck/launcher/input/TouchpadGesturesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/input/TouchpadGesturesTest.kt @@ -262,6 +262,75 @@ class TouchpadGesturesTest { assertFalse(events.contains("left down")) } + @Test fun tapsDoNotClickWhileClicksAreOff() { + touchpad.clicks = false + tap() + advance(20) + tap() + advance(TouchTiming.HOLD_MS + 100) + touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f)) + advance(TouchTiming.HOLD_MS + 100) + touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 300f)) + advance(200) + assertFalse(events.any { it.endsWith(" down") }) + } + + @Test fun twoFingerTapDoesNotClickWhileClicksAreOff() { + touchpad.clicks = false + touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f)) + advance(10) + touch(MotionEvent.ACTION_POINTER_DOWN, 1, 1 to (400f to 300f), 2 to (600f to 310f)) + advance(60) + touch(MotionEvent.ACTION_POINTER_UP, 1, 1 to (400f to 300f), 2 to (600f to 310f)) + advance(10) + touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 300f)) + advance(200) + assertFalse(events.any { it.endsWith(" down") }) + } + + @Test fun pointerStillMovesWhileClicksAreOff() { + touchpad.clicks = false + touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f)) + advance(10) + touch(MotionEvent.ACTION_MOVE, 0, 1 to (440f to 300f)) + advance(10) + touch(MotionEvent.ACTION_UP, 0, 1 to (440f to 300f)) + assertTrue(events.contains("move")) + assertTrue(touchpad.x > 960f) + assertFalse(events.any { it.endsWith(" down") }) + } + + @Test fun tapsClickAgainOnceClicksAreBackOn() { + touchpad.clicks = false + tap() + advance(400) + touchpad.clicks = true + tap() + advance(200) + assertEquals(listOf("left down", "left up"), events) + } + + @Test fun aTapWhileClicksWereOffDoesNotStartADragOnceTheyAreBackOn() { + touchpad.clicks = false + tap() + advance(20) + touchpad.clicks = true + touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f)) + assertEquals(emptyList(), events) + advance(80) + touch(MotionEvent.ACTION_UP, 0, 1 to (400f to 300f)) + advance(200) + assertEquals(listOf("left down", "left up"), events) + } + + @Test fun doubleTapStillDragsWhileClicksStayOn() { + tap() + advance(20) + touchpad.clicks = true + touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f)) + assertEquals(listOf("left down", "left up", "left down"), events) + } + private fun tap() { touch(MotionEvent.ACTION_DOWN, 0, 1 to (400f to 300f)) advance(80) diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt index 23db657ed5..cf78bed84f 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/BwrapSpawnerTest.kt @@ -60,10 +60,10 @@ class BwrapSpawnerTest { val env = mutableMapOf( "DDNATV_ROOT" to rootfs, "DDNATV_BINDS" to "/dev:/dev", "HOME" to "/root", "SPA_PLUGIN_DIR" to "/usr/local/lib/droiddeck-pipewire/lib/spa-0.2", - "LD_PRELOAD" to "/run/droiddeck-preload/libblsession.so:$rootfs/usr/local/lib/libblsession.so:$rootfs/usr/lib/libddnatv-hook.so", + "LD_PRELOAD" to "/run/droiddeck-preload/libddsession.so:$rootfs/usr/local/lib/libddsession.so:$rootfs/usr/lib/libddnatv-hook.so", ) BwrapSpawner.withoutRootfsSettings(env, rootfs) - assertEquals(mapOf("HOME" to "/root", "LD_PRELOAD" to "/run/droiddeck-preload/libblsession.so"), env) + assertEquals(mapOf("HOME" to "/root", "LD_PRELOAD" to "/run/droiddeck-preload/libddsession.so"), env) val onlySession = mutableMapOf("LD_PRELOAD" to "$rootfs/usr/lib/libddnatv-hook.so") BwrapSpawner.withoutRootfsSettings(onlySession, rootfs) assertTrue(onlySession.isEmpty()) @@ -112,6 +112,40 @@ class BwrapSpawnerPlanTest { .put("cwd", "/app") .put("ops", JSONArray().apply { ops.forEach { put(it) } }) + @Test fun desktopSandboxesGetTheRuntimeGpuWithoutReplacingExplicitChoices() { + val lib = File(runtime, "usr/lib/aarch64-linux-gnu/libvulkan_freedreno.so") + lib.parentFile!!.mkdirs() + lib.writeText("") + val root = File(dir, "root").apply { mkdirs() } + for (session in listOf(emptyMap(), mapOf("DD_DESKTOP" to "1"), + mapOf("DD_DESKTOP" to "1", "GALLIUM_DRIVER" to "zink", "MESA_LOADER_DRIVER_OVERRIDE" to "zink"))) { + val env = session.toMutableMap() + val binds = BwrapSpawner.gpu(runtime.path, root, env, true)!! + assertTrue(binds.any { it.host == lib.canonicalPath && it.guest == "/run/droiddeck-gpu/libvulkan_freedreno.so" }) + assertEquals("/run/droiddeck-gpu/freedreno_icd.json", env["VK_DRIVER_FILES"]) + assertEquals("zink", env["GALLIUM_DRIVER"]) + assertEquals(session["DD_DESKTOP"], env["DD_DESKTOP"]) + } + for (choice in listOf(mapOf("VK_DRIVER_FILES" to "/custom/icd.json"), + mapOf("VK_ICD_FILENAMES" to ""), mapOf("LIBGL_ALWAYS_SOFTWARE" to "1"))) { + val env = (choice + ("DD_DESKTOP" to "1")).toMutableMap() + val original = env.toMap() + assertEquals(null, BwrapSpawner.gpu(runtime.path, root, env, true)) + assertEquals(original, env) + } + val env = mutableMapOf("DD_DESKTOP" to "1", "GALLIUM_DRIVER" to "llvmpipe") + assertTrue(BwrapSpawner.gpu(runtime.path, root, env, true)!!.isNotEmpty()) + assertEquals("llvmpipe", env["GALLIUM_DRIVER"]) + val gamescope = mutableMapOf("DD_DESKTOP" to "1", "LIBGL_ALWAYS_SOFTWARE" to "1", "GAMESCOPE_WAYLAND_DISPLAY" to "gamescope-0") + assertTrue(BwrapSpawner.gpu(runtime.path, root, gamescope, true)!!.isNotEmpty()) + val unavailable = mutableMapOf("DD_DESKTOP" to "1") + assertEquals(null, BwrapSpawner.gpu(runtime.path, root, unavailable, false)) + assertEquals(mapOf("DD_DESKTOP" to "1"), unavailable) + assertTrue(lib.delete()) + assertEquals(null, BwrapSpawner.gpu(runtime.path, root, unavailable, true)) + assertEquals(mapOf("DD_DESKTOP" to "1"), unavailable) + } + @Test fun buildsTheTreeFlatpakAsksFor() { val context = RuntimeEnvironment.getApplication() val info = Base64.encodeToString("[Application]\nname=org.example.Game\n".toByteArray(), Base64.NO_WRAP) @@ -147,8 +181,8 @@ class BwrapSpawnerPlanTest { @Test fun fexSandboxesStartThroughTheEnvTheyBringAndSkipArmPreloads() { val context = RuntimeEnvironment.getApplication() val rootfs = LinuxRuntime.rootDir(context) - val lib = File(rootfs, "usr/local/lib/libblsession.so").apply { parentFile?.mkdirs(); writeText("") } - val preload = File(rootfs, "etc/ld.so.preload").apply { parentFile?.mkdirs(); writeText("/usr/local/lib/libblsession.so\n") } + val lib = File(rootfs, "usr/local/lib/libddsession.so").apply { parentFile?.mkdirs(); writeText("") } + val preload = File(rootfs, "etc/ld.so.preload").apply { parentFile?.mkdirs(); writeText("/usr/local/lib/libddsession.so\n") } try { val plan = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp")) .put("envTool", "/run/droiddeck-fex/bin/env"), dir) @@ -163,12 +197,12 @@ class BwrapSpawnerPlanTest { @Test fun sandboxedAppsSeeTheSessionsNetworkLink() { val context = RuntimeEnvironment.getApplication() val rootfs = LinuxRuntime.rootDir(context) - val lib = File(rootfs, "usr/local/lib/libblsession.so").apply { parentFile?.mkdirs(); writeText("") } - val preload = File(rootfs, "etc/ld.so.preload").apply { parentFile?.mkdirs(); writeText("/usr/local/lib/libblsession.so\n") } + val lib = File(rootfs, "usr/local/lib/libddsession.so").apply { parentFile?.mkdirs(); writeText("") } + val preload = File(rootfs, "etc/ld.so.preload").apply { parentFile?.mkdirs(); writeText("/usr/local/lib/libddsession.so\n") } val link = File(rootfs, "etc/droiddeck-net").apply { writeText("if wlan0 2 1500\n") } try { val plan = BwrapSpawner.plan(context, request(op("t" to "dir", "dest" to "/tmp")), dir) - assertEquals("/run/droiddeck-preload/libblsession.so", plan.env["LD_PRELOAD"]) + assertEquals("/run/droiddeck-preload/libddsession.so", plan.env["LD_PRELOAD"]) assertEquals(link.path, plan.binds.single { it.guest == "/etc/droiddeck-net" }.host) } finally { listOf(lib, preload, link).forEach { it.delete() } diff --git a/app/src/test/java/com/droiddeck/launcher/runtime/LegacyNamesTest.kt b/app/src/test/java/com/droiddeck/launcher/runtime/LegacyNamesTest.kt index a921259b16..027ed9359b 100644 --- a/app/src/test/java/com/droiddeck/launcher/runtime/LegacyNamesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/runtime/LegacyNamesTest.kt @@ -93,4 +93,41 @@ class LegacyNamesTest { assertEquals("Exec=env APPIMAGE_EXTRACT_AND_RUN=1 /opt/appimages/other.AppImage\n", File(root, "usr/share/applications/other.desktop").readText()) } + + @Test fun homeMarkersKeepTheirStateAndRetiredLibrariesGo() { + write("root/.bl-lossless-asked", "1") + write("root/.bl-compat-pending", "550\n") + write("root/.dd-seed-beat", "new") + write("root/.bl-seed-beat", "old") + write("usr/local/lib/libblsession.so", "old") + write("usr/local/lib/droiddeck-fex/x86_64/libblsession.so", "old") + write("usr/local/lib/libddsession.so", "new") + LegacyNames.migrateRootfs(root) + assertEquals("1", File(root, "root/.dd-lossless-asked").readText()) + assertEquals("550\n", File(root, "root/.dd-compat-pending").readText()) + assertEquals("new", File(root, "root/.dd-seed-beat").readText()) + assertFalse(File(root, "root/.bl-lossless-asked").exists()) + assertFalse(File(root, "root/.bl-seed-beat").exists()) + assertFalse(File(root, "usr/local/lib/libblsession.so").exists()) + assertFalse(File(root, "usr/local/lib/droiddeck-fex/x86_64/libblsession.so").exists()) + assertEquals("new", File(root, "usr/local/lib/libddsession.so").readText()) + } + + @Test fun queuedRequestsUnderBothNamesAreAllKept() { + write("root/.bl-proton-extra", "ge") + write("root/.dd-proton-extra", "em\n") + LegacyNames.migrateRootfs(root) + assertEquals("em\nge\n", File(root, "root/.dd-proton-extra").readText()) + assertFalse(File(root, "root/.bl-proton-extra").exists()) + } + + @Test fun queuedRequestsStaySeparateWhenTheNewQueueIsUnterminated() { + write("root/.bl-proton-extra", "ge\n") + write("root/.dd-proton-extra", "cachyos") + write("root/.bl-steam-urls", "steam://run/440") + write("root/.dd-steam-urls", "steam://run/570") + LegacyNames.migrateRootfs(root) + assertEquals("cachyos\nge\n", File(root, "root/.dd-proton-extra").readText()) + assertEquals("steam://run/570\nsteam://run/440\n", File(root, "root/.dd-steam-urls").readText()) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/EsyncPacksTest.kt b/app/src/test/java/com/droiddeck/launcher/session/EsyncPacksTest.kt index 7d44b10873..06e9073b3c 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/EsyncPacksTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/EsyncPacksTest.kt @@ -679,11 +679,11 @@ class EsyncPacksTest { val root = temp.newFolder("rootfs") EsyncPacks.store(root).mkdirs() assertEquals(0, EsyncPacks.fetchWanted(context, root)) - GameEnvironmentStore.save(context, GameEnvironment.Config(games = mapOf("42" to mapOf("BL_SYNC_FALLBACK" to "1")))) + GameEnvironmentStore.save(context, GameEnvironment.Config(games = mapOf("42" to mapOf("DD_SYNC_FALLBACK" to "1")))) assertTrue(EsyncPacks.enabled(context)) - GameEnvironmentStore.save(context, GameEnvironment.Config(shared = mapOf("BL_SYNC_FALLBACK" to "1"))) + GameEnvironmentStore.save(context, GameEnvironment.Config(shared = mapOf("DD_SYNC_FALLBACK" to "1"))) assertTrue(EsyncPacks.enabled(context)) - GameEnvironmentStore.save(context, GameEnvironment.Config(games = mapOf("42" to mapOf("BL_SYNC_FALLBACK" to "0")))) + GameEnvironmentStore.save(context, GameEnvironment.Config(games = mapOf("42" to mapOf("DD_SYNC_FALLBACK" to "0")))) assertFalse(EsyncPacks.enabled(context)) SessionPrefs.setSyncFallback(context, true) assertTrue(EsyncPacks.enabled(context)) diff --git a/app/src/test/java/com/droiddeck/launcher/session/FexCatalogTest.kt b/app/src/test/java/com/droiddeck/launcher/session/FexCatalogTest.kt index 3f4fa2f75d..8d01ba52eb 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/FexCatalogTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/FexCatalogTest.kt @@ -41,6 +41,6 @@ class FexCatalogTest { @Test fun theSessionGetsTheBuildAndEverySource() { val env = FexCatalog.environment(FexCatalog.Build("fex-2610-r5", url, sha), listOf(url, "https://ghfast.top/$url")) - assertEquals(listOf("BL_FEX_TAG=fex-2610-r5", "BL_FEX_SHA256=$sha", "BL_FEX_URLS=$url https://ghfast.top/$url"), env) + assertEquals(listOf("DD_FEX_TAG=fex-2610-r5", "DD_FEX_SHA256=$sha", "DD_FEX_URLS=$url https://ghfast.top/$url"), env) } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/GameEnvironmentStoreTest.kt b/app/src/test/java/com/droiddeck/launcher/session/GameEnvironmentStoreTest.kt index da16928da6..273d91d1d9 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/GameEnvironmentStoreTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/GameEnvironmentStoreTest.kt @@ -315,4 +315,27 @@ class GameEnvironmentStoreTest { GameEnvironmentStore.save(context, config) assertEquals(config, GameEnvironmentStore.read(context)) } + + @Test fun savedSettingsFromBeforeTheRenameKeepTheirValues() { + val json = JSONObject("""{"version":1,"shared":{"BL_SYNC":"1","DXVK_HUD":"fps"}, + "games":{"440":{"BL_FSYNC_FIRST":"1","BL_SYNC_FALLBACK":"0","DD_SYNC_FALLBACK":"1"}}}""") + val config = GameEnvironmentStore.decode(json) + assertEquals(mapOf("DD_SYNC" to "1", "DXVK_HUD" to "fps"), config.shared) + assertEquals(mapOf("DD_FSYNC_FIRST" to "1", "DD_SYNC_FALLBACK" to "1"), config.games["440"]) + } + + @Test fun unreadableSettingsAreSetAsideAndSessionsStillStart() { + val settings = File(context.filesDir, "game-environment.json") + val aside = File(context.filesDir, "game-environment.json.unreadable") + aside.delete() + for (broken in listOf("", """{"version":1,"shared":{"bad name":"1"}}""")) { + settings.writeText(broken) + assertEquals(GameEnvironment.Config(), GameEnvironmentStore.read(context)) + assertFalse(settings.exists()) + assertEquals(broken, aside.readText()) + } + GameEnvironmentStore.publish(context) + assertEquals(1, JSONObject(guest.readText()).getInt("version")) + aside.delete() + } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/LightPauseTest.kt b/app/src/test/java/com/droiddeck/launcher/session/LightPauseTest.kt new file mode 100644 index 0000000000..8e14b74147 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/LightPauseTest.kt @@ -0,0 +1,56 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class LightPauseTest { + @Test + fun theBounceAloneResumesLight() { + val pause = LightPause() + pause.paused(bounces = 3) + assertEquals(LightPause.Resume.LIGHT, pause.resumed(bounces = 4)) + assertFalse(pause.timedOut()) + } + + @Test + fun anUnrelatedPauseWithoutABounceCleansUpAtTheTimeout() { + val pause = LightPause() + pause.paused(bounces = 3) + assertTrue(pause.timedOut()) + assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 3)) + } + + @Test + fun aBounceWhileAnotherActivityHoldsThePauseStillCleansUpAtTheTimeout() { + val pause = LightPause() + pause.paused(bounces = 3) + assertTrue(pause.timedOut()) + assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 4)) + } + + @Test + fun aResumeBeforeTheTimeoutWithoutABounceCleansUpFirst() { + val pause = LightPause() + pause.paused(bounces = 3) + assertEquals(LightPause.Resume.CLEANUP_FIRST, pause.resumed(bounces = 3)) + assertFalse(pause.timedOut()) + } + + @Test + fun aStopAfterALightPauseCleansUpOnce() { + val pause = LightPause() + pause.paused(bounces = 3) + assertTrue(pause.stopped()) + assertFalse(pause.timedOut()) + assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 4)) + } + + @Test + fun aNormalPauseIsUntouched() { + val pause = LightPause() + assertFalse(pause.stopped()) + assertEquals(LightPause.Resume.NORMAL, pause.resumed(bounces = 0)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/PowerVrAutoDriversTest.kt b/app/src/test/java/com/droiddeck/launcher/session/PowerVrAutoDriversTest.kt index fe2f6a8125..804d96e88f 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/PowerVrAutoDriversTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/PowerVrAutoDriversTest.kt @@ -1,26 +1,94 @@ package com.droiddeck.launcher.session import android.content.Context -import org.robolectric.RuntimeEnvironment +import android.net.Uri +import com.droiddeck.launcher.DriverMenusAutoTest +import com.droiddeck.launcher.core.DeviceSupport +import com.droiddeck.launcher.gpu.DriverBundle +import com.droiddeck.launcher.gpu.GpuInfo +import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager import com.droiddeck.launcher.gpu.TurnipDriver +import org.json.JSONObject +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.RobolectricTestRunner +import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config +import java.io.File +import java.util.zip.ZipEntry +import java.util.zip.ZipOutputStream @RunWith(RobolectricTestRunner::class) -@Config(sdk = [28], manifest = Config.NONE) +@Config(sdk = [28], manifest = Config.NONE, shadows = [DriverMenusAutoTest.XclipseDriver::class]) class PowerVrAutoDriversTest { private val context: Context = RuntimeEnvironment.getApplication() @Before fun reset() { + DriverMenusAutoTest.XclipseDriver.enabled = false + clearBundles() context.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() SessionPrefs.setLinuxDriver(context, "imported-linux") SessionPrefs.setAndroidDriver(context, "imported-display") } + @After fun cleanupBundles() { + clearBundles() + } + + private fun clearBundles() { + File(context.filesDir, "graphics_driver").deleteRecursively() + File(context.filesDir, LinuxVulkanDriverManager.DIR_NAME).deleteRecursively() + context.getSharedPreferences("driver_bundles", Context.MODE_PRIVATE).edit().clear().commit() + } + + private fun installAndSelectNonAdrenoBundle( + tag: String = "RADV-Xclipse", + packageName: String = "RADV-Xclipse", + ): DriverBundle.Bundle { + fun library(libc: String) = ByteArray(64).also { + byteArrayOf(0x7f, 'E'.code.toByte(), 'L'.code.toByte(), 'F'.code.toByte(), 2, 1).copyInto(it) + it[18] = 0xB7.toByte() + } + libc.toByteArray() + ByteArray(1) + + val manifest = JSONObject() + .put("package", packageName) + .put("version", "0.1.0") + .put("tag", tag) + .put( + "drivers", + JSONObject() + .put("android", JSONObject().put("path", "android")) + .put("linux", JSONObject().put("path", "linux")), + ) + val entries = mapOf( + "android/meta.json" to JSONObject().put("name", "radv v0.1.0").put("libraryName", "libvulkan_radeon.so").toString().toByteArray(), + "android/libvulkan_radeon.so" to library("libc.so"), + "linux/meta.json" to JSONObject().put("name", "radv v0.1.0").put("driverVersion", "radv-test").toString().toByteArray(), + "linux/libvulkan_radeon.so" to library("libc.so.6"), + "manifest.json" to manifest.toString().toByteArray(), + ) + val file = File.createTempFile("radv-bundle", ".zip", context.cacheDir) + return try { + ZipOutputStream(file.outputStream()).use { z -> + for ((name, data) in entries) { + z.putNextEntry(ZipEntry(name)) + z.write(data) + z.closeEntry() + } + } + val bundle = DriverBundle.install(context, Uri.fromFile(file)) + DriverBundle.select(context, bundle) + bundle + } finally { + file.delete() + } + } + @Test fun autoRepairsStaleAdrenoSelectionsOnPowerVr() { SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO) SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true) @@ -28,17 +96,172 @@ class PowerVrAutoDriversTest { assertEquals(TurnipDriver.AUTO, SessionPrefs.androidDriver(context)) } - @Test fun explicitManualChoicesRemainOnPowerVr() { - SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_MANUAL) - SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true) + @Test fun nonXclipsePowerVrKeepsManualPair() { + SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO) + SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true, autoOwnedOnly = true) assertEquals("imported-linux", SessionPrefs.linuxDriver(context)) assertEquals("imported-display", SessionPrefs.androidDriver(context)) } + @Test fun unsupportedXclipseClearsAnAutoOwnedOldPair() { + SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO) + SessionPrefs.setLinuxDriver(context, "old-linux") + SessionPrefs.setAndroidDriver(context, "old-display") + SessionPrefs.setGpuAutoInstalled(context, setOf("old-display", "old-linux")) + SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true, autoOwnedOnly = true) + assertEquals("", SessionPrefs.linuxDriver(context)) + assertEquals(TurnipDriver.AUTO, SessionPrefs.androidDriver(context)) + } + + @Test fun unsupportedXclipseKeepsAManualPair() { + SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_MANUAL) + SessionPrefs.setLinuxDriver(context, "old-linux") + SessionPrefs.setAndroidDriver(context, "old-display") + SessionPrefs.setGpuAutoInstalled(context, setOf("old-display", "old-linux")) + SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true, autoOwnedOnly = true) + assertEquals("old-linux", SessionPrefs.linuxDriver(context)) + assertEquals("old-display", SessionPrefs.androidDriver(context)) + } + + @Test fun autoClearsOwnedDisplayButKeepsManualLinux() { + SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO) + SessionPrefs.setGpuAutoInstalled(context, setOf("imported-display")) + SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true, autoOwnedOnly = true) + assertEquals(TurnipDriver.AUTO, SessionPrefs.androidDriver(context)) + assertEquals("imported-linux", SessionPrefs.linuxDriver(context)) + } + + @Test fun autoClearsOwnedLinuxButKeepsManualDisplay() { + SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO) + SessionPrefs.setGpuAutoInstalled(context, setOf("imported-linux")) + SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true, autoOwnedOnly = true) + assertEquals("imported-display", SessionPrefs.androidDriver(context)) + assertEquals("", SessionPrefs.linuxDriver(context)) + } + @Test fun adrenoAutoChoicesRemain() { SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO) SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = false) assertEquals("imported-linux", SessionPrefs.linuxDriver(context)) assertEquals("imported-display", SessionPrefs.androidDriver(context)) } + + @Test fun sessionStartKeepsStandaloneDriverOnUnsupportedXclipse() { + SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO) + SessionPrefs.setAndroidDriver(context, "standalone-display") + SessionPrefs.setGpuAutoInstalled(context, setOf("imported-linux")) + val ownedOnly = SessionPrefs.unsupportedXclipse(true) { "Samsung Xclipse 540" } + SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true, autoOwnedOnly = ownedOnly) + assertEquals("standalone-display", SessionPrefs.androidDriver(context)) + assertEquals("", SessionPrefs.linuxDriver(context)) + } + + @Test fun sessionStartOwnershipRuleIgnoresOtherGpus() { + assertEquals(false, SessionPrefs.unsupportedXclipse(false) { "Samsung Xclipse 540" }) + assertEquals(false, SessionPrefs.unsupportedXclipse(true) { "Samsung Xclipse 920" }) + } + + @Test fun sessionStartNamesTheXclipseFromVulkanBeforeTheOwnershipRule() { + val queried = mapOf("device" to "Samsung Xclipse 920") + assertEquals("Xclipse", GpuInfo.systemDriverName("Xclipse", null)) + assertEquals("Samsung Xclipse 920", GpuInfo.systemDriverName("Xclipse", queried)) + assertEquals("PowerVR", GpuInfo.systemDriverName("PowerVR", queried)) + SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO) + SessionPrefs.setGpuAutoInstalled(context, setOf("imported-linux")) + val ownedOnly = SessionPrefs.unsupportedXclipse(true) { GpuInfo.systemDriverName("Xclipse", queried) } + SessionPrefs.ensurePowerVrAutoDrivers(context, powerVr = true, autoOwnedOnly = ownedOnly) + assertEquals("", SessionPrefs.linuxDriver(context)) + assertEquals(TurnipDriver.AUTO, SessionPrefs.androidDriver(context)) + } + + @Test fun sessionStartLeavesTheGpuUnqueriedOffXclipse() { + var asked = false + assertEquals(false, SessionPrefs.unsupportedXclipse(false) { asked = true; "Xclipse" }) + assertEquals(false, asked) + } + + @Test fun cachedOnlySessionStartLeavesPrefsWhenTheXclipseIsUnnamed() { + SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO) + SessionPrefs.setGpuAutoInstalled(context, setOf("imported-display", "imported-linux")) + var reads = 0 + SessionPrefs.reconcilePowerVrAutoDrivers(context, powerVr = true, xclipse = true) { reads++; null } + assertEquals(1, reads) + assertEquals("imported-linux", SessionPrefs.linuxDriver(context)) + assertEquals("imported-display", SessionPrefs.androidDriver(context)) + } + + @Test fun sessionStartWithANamedXclipseClearsOnlyAutoOwnedSelections() { + DriverMenusAutoTest.XclipseDriver.enabled = true + SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO) + SessionPrefs.setGpuAutoInstalled(context, setOf("imported-linux")) + SessionPrefs.reconcilePowerVrAutoDrivers(context, powerVr = true, xclipse = true) { + mapOf("device" to "Samsung Xclipse 540") + } + assertEquals("", SessionPrefs.linuxDriver(context)) + assertEquals("imported-display", SessionPrefs.androidDriver(context)) + } + + @Test fun sessionStartUnsupportedXclipseResetsAutoOwnedEvenWithBothOpenDriversSelected() { + DriverMenusAutoTest.XclipseDriver.enabled = true + val bundle = installAndSelectNonAdrenoBundle() + assertTrue(DeviceSupport.openDriverActive(context)) + SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO) + SessionPrefs.setGpuAutoInstalled(context, setOf(bundle.androidId, bundle.linuxId)) + SessionPrefs.reconcilePowerVrAutoDrivers(context, powerVr = true, xclipse = true) { + mapOf("device" to "Samsung Xclipse 540") + } + assertFalse(DeviceSupport.openDriverActive(context)) + assertEquals("", SessionPrefs.linuxDriver(context)) + assertEquals(TurnipDriver.AUTO, SessionPrefs.androidDriver(context)) + } + + @Test fun sessionStartUnsupportedXclipseKeepsAutoOwnedUpstreamBundle() { + DriverMenusAutoTest.XclipseDriver.enabled = true + val bundle = installAndSelectNonAdrenoBundle( + tag = "RADV-Xclipse-upstream", + packageName = "RADV-Xclipse-upstream", + ) + assertTrue(DeviceSupport.openDriverActive(context)) + SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO) + SessionPrefs.setGpuAutoInstalled(context, setOf(bundle.androidId, bundle.linuxId)) + SessionPrefs.reconcilePowerVrAutoDrivers(context, powerVr = true, xclipse = true) { + mapOf("device" to "Samsung Xclipse 540") + } + assertTrue(DeviceSupport.openDriverActive(context)) + assertEquals(bundle.linuxId, SessionPrefs.linuxDriver(context)) + assertEquals(bundle.androidId, SessionPrefs.androidDriver(context)) + } + + @Test fun sessionStartSupportedXclipseKeepsActiveOpenDriverBundle() { + DriverMenusAutoTest.XclipseDriver.enabled = true + val bundle = installAndSelectNonAdrenoBundle() + assertTrue(DeviceSupport.openDriverActive(context)) + SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO) + SessionPrefs.setGpuAutoInstalled(context, setOf(bundle.androidId, bundle.linuxId)) + SessionPrefs.reconcilePowerVrAutoDrivers(context, powerVr = true, xclipse = true) { + mapOf("device" to "Samsung Xclipse 920") + } + assertTrue(DeviceSupport.openDriverActive(context)) + assertEquals(bundle.linuxId, SessionPrefs.linuxDriver(context)) + assertEquals(bundle.androidId, SessionPrefs.androidDriver(context)) + } + + @Test fun sessionStartWithASupportedXclipseClearsUnownedSelections() { + DriverMenusAutoTest.XclipseDriver.enabled = true + SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO) + SessionPrefs.reconcilePowerVrAutoDrivers(context, powerVr = true, xclipse = true) { + mapOf("device" to "Samsung Xclipse 920") + } + assertEquals("", SessionPrefs.linuxDriver(context)) + assertEquals(TurnipDriver.AUTO, SessionPrefs.androidDriver(context)) + } + + @Test fun sessionStartReadsNoVulkanNameOffXclipse() { + SessionPrefs.setGpuDriverMode(context, SessionPrefs.GPU_DRIVERS_AUTO) + SessionPrefs.reconcilePowerVrAutoDrivers(context, powerVr = true, xclipse = false) { + throw AssertionError("queried") + } + assertEquals("", SessionPrefs.linuxDriver(context)) + assertEquals(TurnipDriver.AUTO, SessionPrefs.androidDriver(context)) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt index 7f3eec4092..1835b6b85d 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionDisplayTest.kt @@ -178,7 +178,7 @@ class SessionDisplayTest { @Test fun removedFilterAliasesRetainTheirEquivalentBehavior() { assertEquals(0, SessionPrefs.canonicalUpscaler(1)) assertEquals(4, SessionPrefs.canonicalUpscaler(5)) - assertEquals(0, SessionPrefs.canonicalUpscaler(99)) + assertEquals(2, SessionPrefs.canonicalUpscaler(99)) assertFalse(SessionPrefs.upscalerHasSharpness(0)) assertFalse(SessionPrefs.upscalerHasSharpness(1)) assertFalse(SessionPrefs.upscalerHasSharpness(2)) diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionEndHintTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionEndHintTest.kt index 4bc4aef334..56a8ad1ce5 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionEndHintTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionEndHintTest.kt @@ -34,14 +34,20 @@ class SessionEndHintTest { private var previousArchitecture: String? = null private var previousLog: File? = null private var previousDirectory: File? = null + private var previousFailureCode: String? = null + private var previousFailureMessage: String? = null @Before fun setUp() { previousArchitecture = SessionState.steamClientArch previousLog = SessionState.logFile previousDirectory = SessionState.logDirectory + previousFailureCode = SessionState.failureCode + previousFailureMessage = SessionState.failureMessage SessionState.logFile = null SessionState.logDirectory = null + SessionState.failureCode = null + SessionState.failureMessage = null DetectedGpu.family = GpuInfo.Family.NOT_ADRENO DetectedGpu.name = "test GPU" activity = Robolectric.buildActivity(SessionActivity::class.java).get() @@ -53,6 +59,8 @@ class SessionEndHintTest { SessionState.steamClientArch = previousArchitecture SessionState.logFile = previousLog SessionState.logDirectory = previousDirectory + SessionState.failureCode = previousFailureCode + SessionState.failureMessage = previousFailureMessage DetectedGpu.family = GpuInfo.Family.NOT_ADRENO DetectedGpu.name = "test GPU" } @@ -122,6 +130,22 @@ class SessionEndHintTest { assertNull(exitHint(0)) } + @Test + fun startFailureShowsTheRecordedMessage() { + SessionState.failureCode = "POWERVR_MISSING" + SessionState.failureMessage = "x" + val hint = exitHint(-1) + assertNotNull(hint) + assertEquals("x", ReflectionHelpers.getField(hint, "text")) + } + + @Test + fun guestExitMessageIsNotShownAsAStartFailure() { + SessionState.failureCode = "GUEST_EXIT" + SessionState.failureMessage = "Session guest exited with status 1" + assertNull(exitHint(1)) + } + @Test fun missingEmptyAndUnrelatedLogsHaveNoHint() { assertNull(hint(null)) diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionRestartNoteTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionRestartNoteTest.kt new file mode 100644 index 0000000000..230afe7db9 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionRestartNoteTest.kt @@ -0,0 +1,30 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test + +class SessionRestartNoteTest { + private val started = 1_731_100_000_000L + + @Test fun aBootAfterTheSessionBeganIsReportedAsARestart() { + val note = SessionArtifacts.restartNote(started, started + 20 * 60_000L) + assertNotNull(note) + assertTrue(note!!.startsWith("The device itself probably restarted")) + } + + @Test fun aBootBeforeTheSessionBeganMeansOnlyTheAppEnded() { + val note = SessionArtifacts.restartNote(started, started - 3 * 3_600_000L) + assertTrue(note!!.startsWith("The device does not appear to have restarted")) + } + + @Test fun clockCorrectionsWithinAMinuteAreNotARestart() { + val note = SessionArtifacts.restartNote(started, started + 30_000L) + assertTrue(note!!.startsWith("The device does not appear to have restarted")) + } + + @Test fun aFolderWithoutAStartTimeSaysNothing() { + assertNull(SessionArtifacts.restartNote(0L, started)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionScalingPrefsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionScalingPrefsTest.kt index de082c7fe9..3d0e420001 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionScalingPrefsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionScalingPrefsTest.kt @@ -85,4 +85,23 @@ class SessionScalingPrefsTest { SessionPrefs.setUpscaler(context, 1) assertEquals(0, prefs.getInt("upscaler", -1)) } + + private fun fpsContext(): Context = RuntimeEnvironment.getApplication().also { + it.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() + } + + @Test fun aFrameLimitStaysWithTheGameOrDesktopItWasSetIn() { + val ctx = fpsContext() + val game = SessionPrefs.fpsLimitKey(SessionService.MODE_RUN, "123") + val desktop = SessionPrefs.fpsLimitKey(SessionService.MODE_DESKTOP, null) + SessionPrefs.saveFpsLimit(ctx, game, 45) + SessionPrefs.saveFpsLimit(ctx, desktop, 30) + assertEquals(45, SessionPrefs.savedFpsLimit(ctx, game)) + assertEquals(30, SessionPrefs.savedFpsLimit(ctx, desktop)) + assertEquals(0, SessionPrefs.savedFpsLimit(ctx, SessionPrefs.fpsLimitKey(SessionService.MODE_RUN, "456"))) + assertEquals(null, SessionPrefs.fpsLimitKey(SessionService.MODE_STEAM, "123")) + assertEquals(null, SessionPrefs.fpsLimitKey(SessionService.MODE_RUN, "not-a-game")) + SessionPrefs.saveFpsLimit(ctx, game, 0) + assertEquals(0, SessionPrefs.savedFpsLimit(ctx, game)) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt index 44aa6c73cd..7d2087f6fc 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SessionSuspendControllerTest.kt @@ -39,7 +39,7 @@ class SessionSuspendControllerTest { assertEquals(listOf(Triple(1, 1_000_000L, 3_000_000L)), fixture.pagedOut) assertEquals(0, fixture.unacknowledged) assertTrue(fixture.game.threads.all { it.state == 't' }) - assertFalse(File(fixture.control.parentFile, ".bl-zram.ack.$GAME").exists()) + assertFalse(File(fixture.control.parentFile, ".dd-zram.ack.$GAME").exists()) } @Test fun unchangedSwapIsNotTakenForAFinishedPageOut() { @@ -478,8 +478,8 @@ class SessionSuspendControllerTest { var emptyGameTasks = false var rootGone = false var afterSleep: (() -> Unit)? = null - val control = File(tmp, ".bl-zram") - val clock = File(tmp, ".bl-clock") + val control = File(tmp, ".dd-zram") + val clock = File(tmp, ".dd-clock") var clockAtContinue: Long? = null var clockAtMapping: Long? = null val pagedOut = mutableListOf>() @@ -582,7 +582,7 @@ class SessionSuspendControllerTest { "TracerPid: ${group.tracer}\n" + if (group == game) "VmRSS:\t$gameResidentKb kB\nVmSwap:\t$gameSwapKb kB\n" else "", ) - if (group == game) File(dir, "maps").writeText("7f00000000-7f00001000 r-xp 00000000 fe:05 42 /usr/local/lib/libblsession.so\n") + if (group == game) File(dir, "maps").writeText("7f00000000-7f00001000 r-xp 00000000 fe:05 42 /usr/local/lib/libddsession.so\n") val taskDir = File(dir, "task") if (group == game && missingGameTasks) { taskDir.deleteRecursively(); continue } taskDir.mkdirs() diff --git a/app/src/test/java/com/droiddeck/launcher/session/SteamDownloadMonitorTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SteamDownloadMonitorTest.kt index 52920aefca..99bbba886f 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SteamDownloadMonitorTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SteamDownloadMonitorTest.kt @@ -250,7 +250,7 @@ class SteamDownloadMonitorTest { File(steam, "package").mkdirs() File(steam, "package/bannerlator-installed").writeText("1\n") assertFalse(SteamDownloadMonitor.clientInstallPending(root)) - File(root, "root/.bl-steam-repair").writeText("1\n") + File(root, "root/.dd-steam-repair").writeText("1\n") assertTrue(SteamDownloadMonitor.clientInstallPending(root)) } finally { root.deleteRecursively() diff --git a/app/src/test/java/com/droiddeck/launcher/session/SteamGameProcessTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SteamGameProcessTest.kt index fc1a1bb276..ae9b31d80c 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SteamGameProcessTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SteamGameProcessTest.kt @@ -30,6 +30,22 @@ class SteamGameProcessTest { assertFalse(SteamGameProcess.matches(cmdline("python3", "/proton", "waitforexitandrun", "game.exe"), "976310")) } + @Test fun steamsInstallScriptStepIsNotTheGame() { + val wrapper = arrayOf("/root/.local/share/Steam/linuxarm64/steam-launch-wrapper", "--oom-score-adjust", "900", "--") + val reaper = "/root/.local/share/Steam/steamrtarm64/reaper" + val proton = "/root/.local/share/Steam/compatibilitytools.d/DroidDeck-Proton 11-12.8/droiddeck-proton-wrap" + val evaluator = arrayOf(reaper, "SteamLaunch", "AppId=351710", "Install=1", "--", + proton, "run", "/root/.local/share/Steam/legacycompat/iscriptevaluator.exe", "legacycompat\\evaluatorscript_351710.vdf") + val game = arrayOf(reaper, "SteamLaunch", "AppId=351710", "--", + proton, "waitforexitandrun", "/root/.local/share/Steam/steamapps/common/Neptunia Rebirth2/NeptuniaReBirth2.exe") + + assertFalse(SteamGameProcess.matches(cmdline(*evaluator), "351710")) + assertFalse(SteamGameProcess.matches(cmdline(*wrapper, *evaluator), "351710")) + assertTrue(SteamGameProcess.matches(cmdline(*game), "351710")) + assertTrue(SteamGameProcess.matches(cmdline(*wrapper, *game), "351710")) + assertTrue(SteamGameProcess.matches(cmdline(reaper, "SteamLaunch", "AppId=351710", "--", "game", "Install=1"), "351710")) + } + @Test fun shortcutCGameIdsMatchTheir32BitSteamAppId() { val cgameId = ((976310L shl 32) or 0x02000000L).toString() @@ -67,5 +83,9 @@ class SteamGameProcessTest { process("200", "reaper", "SteamLaunch", "AppId=976310", "--", "proton", "waitforexitandrun", "MK11.exe") assertTrue(SteamGameProcess.running("976310", proc)) assertFalse(SteamGameProcess.running("123", proc)) + process("300", "reaper", "SteamLaunch", "AppId=351710", "Install=1", "--", "proton", "run", "iscriptevaluator.exe") + assertFalse(SteamGameProcess.running("351710", proc)) + process("301", "reaper", "SteamLaunch", "AppId=351710", "--", "proton", "waitforexitandrun", "game.exe") + assertTrue(SteamGameProcess.running("351710", proc)) } } diff --git a/app/src/test/java/com/droiddeck/launcher/session/SteamLibrariesTest.kt b/app/src/test/java/com/droiddeck/launcher/session/SteamLibrariesTest.kt index 5317e5ca33..cef09d10a5 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/SteamLibrariesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/SteamLibrariesTest.kt @@ -4,6 +4,7 @@ import com.droiddeck.launcher.frontend.AddedGames import com.droiddeck.launcher.frontend.Library import java.io.File import org.junit.Assert.* +import org.junit.Assume.assumeFalse import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder @@ -145,6 +146,7 @@ class SteamLibrariesTest { } @Test fun rawAndStorageMountViewsOverlapButDistinctFoldersDoNot() { + assumeFalse(java.nio.file.Files.isSymbolicLink(File("/mnt").toPath())) val raw = SteamLibraries.canonical(File("/mnt/media_rw/ABCD-1234/Games")) val storage = SteamLibraries.canonical(File("/storage/ABCD-1234/Games")) assertEquals(storage, raw) diff --git a/app/src/test/java/com/droiddeck/launcher/session/StoresTabOrderTest.kt b/app/src/test/java/com/droiddeck/launcher/session/StoresTabOrderTest.kt new file mode 100644 index 0000000000..fb1fb71a5d --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/StoresTabOrderTest.kt @@ -0,0 +1,56 @@ +package com.droiddeck.launcher.session + +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.arrangeStoreTabs +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +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 = [33]) +class StoresTabOrderTest { + private val app get() = RuntimeEnvironment.getApplication() + private val defaults = Store.entries.map { it.id } + private fun shown() = arrangeStoreTabs(SessionPrefs.storesTabOrder(app), emptySet()).map { it.store.id } + + @Test + fun anOldDefaultOrderMovesToTheCurrentOne() { + SessionPrefs.setStoresTabOrder(app, listOf("gog", "epic", "amazon", "xbox", "itch", "gamejolt", "battlenet", "ubisoft", "ea", "rockstar")) + SessionPrefs.settleStoresTabOrder(app, defaults) + assertEquals(defaults, shown()) + assertFalse(SessionPrefs.storesTabOrderCustomized(app)) + } + + @Test + fun aSavedCurrentDefaultIsNotMistakenForTheUsersOwn() { + SessionPrefs.setStoresTabOrder(app, defaults) + repeat(2) { SessionPrefs.settleStoresTabOrder(app, defaults) } + assertFalse(SessionPrefs.storesTabOrderCustomized(app)) + assertTrue(SessionPrefs.storesTabOrder(app).isEmpty()) + } + + @Test + fun anArrangedOrderIsKept() { + val mine = defaults.reversed() + SessionPrefs.setStoresTabOrder(app, mine) + SessionPrefs.settleStoresTabOrder(app, defaults) + assertTrue(SessionPrefs.storesTabOrderCustomized(app)) + assertEquals(mine, shown()) + } + + @Test + fun hidingAStoreLeavesTheOrderFollowingTheDefault() { + SessionPrefs.saveStoresTabs(app, defaults, setOf("itch"), arranged = false) + assertTrue(SessionPrefs.storesTabOrder(app).isEmpty()) + val later = defaults.reversed() + SessionPrefs.settleStoresTabOrder(app, later) + assertFalse(SessionPrefs.storesTabOrderCustomized(app)) + assertTrue(SessionPrefs.storesTabOrder(app).isEmpty()) + assertEquals(setOf("itch"), SessionPrefs.storesTabHidden(app)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/TopUnderPressureTest.kt b/app/src/test/java/com/droiddeck/launcher/session/TopUnderPressureTest.kt new file mode 100644 index 0000000000..ac0ec06843 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/TopUnderPressureTest.kt @@ -0,0 +1,25 @@ +package com.droiddeck.launcher.session + +import android.content.ComponentCallbacks2 +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class TopUnderPressureTest { + @Test + fun onlyRunningLevelsCountAsPressure() { + assertTrue(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL)) + assertTrue(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW)) + assertFalse(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE)) + assertFalse(TopUnderPressure.isPressure(ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN)) + } + + @Test + fun reclaimsOnlyDuringASessionShortlyAfterPressure() { + assertTrue(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = true, finishing = false)) + assertFalse(TopUnderPressure.shouldReclaim(20_000, 9_500, sessionRunning = true, finishing = false)) + assertFalse(TopUnderPressure.shouldReclaim(10_000, 0, sessionRunning = true, finishing = false)) + assertFalse(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = false, finishing = false)) + assertFalse(TopUnderPressure.shouldReclaim(10_000, 9_500, sessionRunning = true, finishing = true)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/CloudSavesTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/CloudSavesTest.kt index 9f1dcd2b0d..f3944a8034 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/CloudSavesTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/CloudSavesTest.kt @@ -1,5 +1,8 @@ package com.droiddeck.launcher.stores +import com.droiddeck.launcher.stores.ubisoft.MemorySlots +import com.droiddeck.launcher.stores.ubisoft.UbisoftCloud +import com.droiddeck.launcher.stores.ubisoft.UbisoftCloudTransport import java.io.File import java.util.concurrent.Executor import org.junit.Assert.assertArrayEquals @@ -20,10 +23,18 @@ class CloudSavesTest { private class Memory : CloudTransport { val files = HashMap>() val puts = ArrayList() + var onGet: (CloudFile) -> Unit = {} + var raceAfter = Int.MAX_VALUE override fun list() = files.map { (k, v) -> CloudFile(k, v.second, CloudSaves.md5(v.first)) } - override fun get(file: CloudFile) = files.getValue(file.name) - override fun put(files: Map, modifiedMs: Map): Map = - files.mapValues { (k, v) -> puts += k; this.files[k] = v to 99_000L; 99_000L } + override fun get(file: CloudFile) = files.getValue(file.name).also { onGet(file) } + override fun put(files: Map, modifiedMs: Map): Map { + val sent = LinkedHashMap() + for ((k, v) in files) { + if (sent.size >= raceAfter) throw CloudChanged(sent, files.keys.filter { it !in sent }) + puts += k; this.files[k] = v to 99_000L; sent[k] = 99_000L + } + return sent + } } private fun dir() = File(app.filesDir, "saves-${System.nanoTime()}").apply { mkdirs() } @@ -50,6 +61,72 @@ class CloudSavesTest { assertEquals("v1", File(kept, "slot0.sav").readText()) } + @Test fun aFolderAliasNeverHidesTheRealSaveFromARestore() { + val game = id; val dir = dir() + File(dir, "SaveData").mkdirs(); File(dir, "SaveData/slot.sav").writeText("local") + val link = runCatching { java.nio.file.Files.createSymbolicLink(File(dir, "Cache").toPath(), File(dir, "SaveData").toPath()) } + org.junit.Assume.assumeTrue(link.isSuccess) + val memory = Memory().apply { files["SaveData/slot.sav"] = "cloud".toByteArray() to 1000L } + val cloud = object : CloudTransport by memory { + override fun wants(name: String) = name.startsWith("SaveData/") + } + CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = true) + assertEquals("cloud", File(dir, "SaveData/slot.sav").readText()) + val kept = File(app.filesDir, "stores/cloud-backups/gog-$game").listFiles { f -> f.name.startsWith("local-") }!!.single() + assertEquals("local", File(kept, "SaveData/slot.sav").readText()) + } + + @Test fun aSaveReachedOnlyThroughAFolderAliasStillGoesUp() { + val game = id; val dir = dir() + File(dir, "Actual").mkdirs(); File(dir, "Actual/slot.sav").writeText("played") + val link = runCatching { java.nio.file.Files.createSymbolicLink(File(dir, "SaveData").toPath(), File(dir, "Actual").toPath()) } + org.junit.Assume.assumeTrue(link.isSuccess) + java.nio.file.Files.createSymbolicLink(File(dir, "Actual/loop").toPath(), dir.toPath()) + val memory = Memory() + val cloud = object : CloudTransport by memory { + override fun wants(name: String) = name.startsWith("SaveData/") + } + CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false) + val r = CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = false) + assertEquals("uploaded", r.reason) + assertEquals(listOf("SaveData/slot.sav"), memory.puts) + assertEquals("played", String(memory.files.getValue("SaveData/slot.sav").first)) + } + + @Test fun onlySelectedSavesCanCollideByCase() { + val names = listOf("Logs/A.txt", "Logs/a.txt", "SaveGame/1") + assertFalse(CloudSaves.caseCollision(names) { !it.startsWith("Logs/") }) + assertTrue(CloudSaves.caseCollision(names) { true }) + assertTrue(CloudSaves.caseCollision(listOf("SaveGame/1", "savegame/1")) { it.lowercase().startsWith("savegame/") }) + } + + @Test fun aSavedConflictWhoseSidesNowMatchIsCleared() { + val game = id; val dir = dir() + val cloud = Memory().apply { files["slot0.sav"] = "v1".toByteArray() to 1000L } + CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false) + cloud.files["slot0.sav"] = "v2".toByteArray() to 50_000L + File(dir, "slot0.sav").writeText("v2") + com.droiddeck.launcher.stores.gog.GogPrefs.get(app).edit().putString("cloud_conflicts_$game", "slot0.sav").apply() + assertEquals("up-to-date", CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false).reason) + assertTrue(CloudSaves.conflicts(app, Store.GOG, game).isEmpty()) + com.droiddeck.launcher.stores.gog.GogPrefs.get(app).edit().putString("cloud_conflicts_$game", "slot0.sav").apply() + CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = false) + assertTrue(CloudSaves.conflicts(app, Store.GOG, game).isEmpty()) + } + + @Test fun aDownloadTheLaunchStoppedWaitingForWritesNothing() { + val game = id; val dir = dir() + File(dir, "slot0.sav").writeText("local") + val cloud = Memory().apply { files["slot0.sav"] = "v1".toByteArray() to 1000L } + val r = CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = true, claim = { false }) + assertEquals("skipped", r.result); assertEquals("launch-moved-on", r.reason) + assertEquals("local", File(dir, "slot0.sav").readText()) + assertFalse(File(app.filesDir, "stores/cloud-backups/gog-$game").exists()) + var claimed = 0 + assertEquals("ok", CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = true, claim = { claimed++; true }).result) + assertEquals(1, claimed); assertEquals("v1", File(dir, "slot0.sav").readText()) + } + @Test fun aFileChangedOnBothSidesIsLeftForTheUser() { val game = id; val dir = dir() val cloud = Memory().apply { files["slot0.sav"] = "v1".toByteArray() to 1000L } @@ -65,6 +142,134 @@ class CloudSavesTest { assertTrue(CloudSaves.conflicts(app, Store.GOG, game).isEmpty()) } + @Test fun aSlotTheGameRewritesDuringADownloadIsKeptAndNamedAsAConflict() { + val game = id; val dir = dir() + val cloud = Memory().apply { files["slot0.sav"] = "v1".toByteArray() to 1000L } + CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false) + cloud.files["slot0.sav"] = "cloud v2".toByteArray() to 50_000L + cloud.onGet = { File(dir, "slot0.sav").writeText("game wrote") } + val r = CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false) + assertEquals("partial", r.result); assertEquals("changed-locally", r.reason); assertEquals(1, r.conflicts) + assertTrue(r.detail.contains("slot0.sav")) + assertEquals("game wrote", File(dir, "slot0.sav").readText()) + assertEquals(listOf("slot0.sav"), CloudSaves.conflicts(app, Store.GOG, game)) + } + + @Test fun aCloudNameOutsideTheSaveFolderIsBlockedNotAConflict() { + val game = id; val dir = dir() + val cloud = Memory().apply { files["../escape.sav"] = "x".toByteArray() to 1000L } + val r = CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false) + assertEquals("partial", r.result); assertEquals("blocked-path", r.reason); assertEquals(0, r.conflicts) + assertTrue(r.detail.contains("../escape.sav")) + assertFalse(File(dir.parentFile, "escape.sav").exists()) + assertTrue(CloudSaves.conflicts(app, Store.GOG, game).isEmpty()) + } + + @Test fun anUploadStoppedByANewerCloudWriteKeepsTheRestAsConflicts() { + val game = id; val dir = dir() + val cloud = Memory().apply { files["a.sav"] = "a1".toByteArray() to 1000L; files["b.sav"] = "b1".toByteArray() to 1000L } + CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false) + File(dir, "a.sav").writeText("a2"); File(dir, "b.sav").writeText("b2") + cloud.raceAfter = 1 + val r = CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = false) + assertEquals("partial", r.result); assertEquals("changed-in-cloud", r.reason); assertEquals(1, r.files) + val unsent = listOf("a.sav", "b.sav").single { it !in cloud.puts } + assertEquals(listOf(unsent), CloudSaves.conflicts(app, Store.GOG, game)) + } + + @Test fun aForcedUploadKeepsConflictsForSlotsItDidNotSend() { + val game = id; val dir = dir() + val cloud = Memory().apply { files["slot0.sav"] = "v1".toByteArray() to 1000L; files["slot1.sav"] = "w1".toByteArray() to 1000L } + CloudSaves.downWith(app, Store.GOG, game, dir, cloud, force = false) + File(dir, "slot0.sav").writeText("local v2"); File(dir, "slot1.sav").delete() + cloud.files["slot0.sav"] = "cloud v2".toByteArray() to 50_000L + com.droiddeck.launcher.stores.gog.GogPrefs.get(app).edit().putString("cloud_conflicts_$game", "slot0.sav\nslot1.sav").apply() + CloudSaves.upWith(app, Store.GOG, game, dir, cloud, force = true) + assertEquals("local v2", String(cloud.files.getValue("slot0.sav").first)) + assertEquals(listOf("slot1.sav"), CloudSaves.conflicts(app, Store.GOG, game)) + } + + private fun ubisoftDir(user: String, root: File = File(app.filesDir, "ubi-${System.nanoTime()}")) = File(root, "$user/77").apply { mkdirs() } + + @Test fun aSlotBothSidesSavedAlikeIsNotAConflictWhenTheCloudNamesOnlyAVersion() { + val game = id; val dir = ubisoftDir("u1") + val slots = MemorySlots().apply { store("1", MemorySlots.save("a1")) } + assertEquals("ok", CloudSaves.downWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false).result) + File(dir, "1.save").writeBytes(MemorySlots.save("a2")) + slots.store("1", MemorySlots.save("a2")) + val down = CloudSaves.downWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false) + assertEquals(0, down.conflicts) + assertTrue(CloudSaves.conflicts(app, Store.UBISOFT, game, dir).isEmpty()) + val up = CloudSaves.upWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false) + assertEquals("up-to-date", up.reason); assertEquals(0, up.conflicts) + File(dir, "1.save").writeBytes(MemorySlots.save("a3 local")) + slots.store("1", MemorySlots.save("a3 cloud")) + assertEquals(1, CloudSaves.downWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false).conflicts) + } + + @Test fun aNewUbisoftSaveWithAnEmptyIdentifierIsStampedAndUploaded() { + val game = id; val dir = ubisoftDir("u1") + val slots = MemorySlots().apply { store("1", MemorySlots.save("a1")) } + CloudSaves.downWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false) + File(dir, "2.save").writeBytes("UBISAVE0".toByteArray() + ByteArray(32) + "fresh slot".toByteArray()) + File(dir, "3.save").writeBytes("UBISAVE0".toByteArray() + "not-an-identifier-but-not-empty!".toByteArray()) + val up = CloudSaves.upWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false) + assertEquals("uploaded", up.reason) + val stamped = UbisoftCloud.mark(File(dir, "2.save").readBytes()) + assertTrue(stamped != null) + assertEquals("fresh slot", String(File(dir, "2.save").readBytes().copyOfRange(40, 50))) + assertEquals(stamped, UbisoftCloud.mark(slots.data.getValue("2"))) + assertFalse("3" in slots.data) + assertEquals("not-an-identifier-but-not-empty!", String(File(dir, "3.save").readBytes().copyOfRange(8, 40))) + } + + @Test fun aSlotCommittedBeforeALaterOneFailsReachesTheBaseline() { + val game = id; val dir = ubisoftDir("u1") + val slots = MemorySlots().apply { store("1", MemorySlots.save("a1")); store("2", MemorySlots.save("b1")) } + CloudSaves.downWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false) + File(dir, "1.save").writeBytes(MemorySlots.save("a2")); File(dir, "2.save").writeBytes(MemorySlots.save("b2")) + slots.uploadsLeft = 1 + assertTrue(runCatching { CloudSaves.upWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false) } + .exceptionOrNull() is java.io.IOException) + val base = CloudSaves.baseline(app, Store.UBISOFT, CloudSaves.scope(Store.UBISOFT, game, dir))!! + val sent = listOf("1", "2").single { slots.data.getValue(it).contentEquals(MemorySlots.save(if (it == "1") "a2" else "b2")) } + val kept = if (sent == "1") "2" else "1" + assertEquals(CloudSaves.md5(File(dir, "$sent.save")), base.getValue("$sent.save").localMd5) + assertEquals(CloudSaves.md5(MemorySlots.save(if (kept == "1") "a1" else "b1")), base.getValue("$kept.save").localMd5) + slots.uploadsLeft = Int.MAX_VALUE + val r = CloudSaves.upWith(app, Store.UBISOFT, game, dir, UbisoftCloudTransport(slots, "u1"), force = false) + assertEquals("ok", r.result); assertEquals(1, r.files); assertEquals(0, r.conflicts) + } + + @Test fun ubisoftConflictsBelongToTheAccountAndProductThatHadThem() { + val game = id; val root = File(app.filesDir, "ubi-${System.nanoTime()}") + val a = ubisoftDir("uA", root); val b = ubisoftDir("uB", root) + val cloudB = Memory().apply { files["slot0.save"] = "b1".toByteArray() to 1000L } + CloudSaves.downWith(app, Store.UBISOFT, game, b, cloudB, force = false) + File(b, "slot0.save").writeText("b local") + val cloudA = Memory().apply { files["slot0.save"] = "a1".toByteArray() to 1000L } + CloudSaves.downWith(app, Store.UBISOFT, game, a, cloudA, force = false) + File(a, "slot0.save").writeText("a local") + cloudA.files["slot0.save"] = "a2".toByteArray() to 50_000L + assertEquals(1, CloudSaves.downWith(app, Store.UBISOFT, game, a, cloudA, force = false).conflicts) + assertEquals(listOf("slot0.save"), CloudSaves.conflicts(app, Store.UBISOFT, game, a)) + assertTrue(CloudSaves.conflicts(app, Store.UBISOFT, game, b).isEmpty()) + CloudSaves.downWith(app, Store.UBISOFT, game, b, cloudB, force = true) + assertEquals("b local", File(b, "slot0.save").readText()) + com.droiddeck.launcher.stores.epic.EpicPrefs.get(app).edit().putString("cloud_conflicts_$game", "slot0.save").apply() + assertTrue(CloudSaves.conflicts(app, Store.UBISOFT, game, ubisoftDir("uC", root)).isEmpty()) + assertTrue(CloudSaves.conflicts(app, Store.UBISOFT, game).isEmpty()) + } + + @Test fun aUbisoftGameAddedFromAnotherFolderIsFoundForCloudSaves() { + val game = id + val folder = File(app.filesDir, "Elsewhere/Anno-$game").apply { mkdirs() } + File(folder, "Anno.exe").writeText("MZ") + StoreGameSidecar(Store.UBISOFT, game, "Anno", "Anno.exe", extra = mapOf("productId" to "77")).write(folder) + com.droiddeck.launcher.session.SessionPrefs.followStoreGame(app, "ubisoft:$game", folder.path) { true } + assertEquals("not-signed-in", CloudSaves.status(app, Store.UBISOFT, game).reason) + } + @Test fun aDirtyMarkStaysUntilAnUploadGoesThroughOrIsSkippedForGood() { val gameId = "1207664643" val folder = File(StoreInstallRoot.storeDir(StoreInstallRoot.internalRoot(app), Store.GOG), "ELDERBORN-mark").apply { mkdirs() } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/StoreCacheTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/StoreCacheTest.kt index c01e4202f6..4366866c6b 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/StoreCacheTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/StoreCacheTest.kt @@ -42,4 +42,20 @@ class StoreCacheTest { val fresh = listOf(a) assertSame(fresh, mergeItems(null, fresh)) } + + @Test fun aSavedStoreLibraryRoundTripsWithItsStoreAndExtras() { + val games = listOf( + CatalogItem( + Store.UBISOFT, "4553", "Far Cry 3 Blood Dragon", "https://img/wide.jpg", tallImageUrl = "https://img/tall.jpg", + logoUrl = "https://img/logo.png", owned = true, sizeBytes = 2_000_000L, extra = mapOf("productId" to "205", "spaceId" to "abc"), + subscription = true, includedWith = "Ubisoft+", + ), + CatalogItem(Store.UBISOFT, "1", "No art", null), + ) + assertEquals(games, StoreLibraryCache.decode(Store.UBISOFT, StoreLibraryCache.encode(games))) + } + + @Test fun aSavedEmptyStoreLibraryStaysEmptyRatherThanUnknown() { + assertEquals(emptyList(), StoreLibraryCache.decode(Store.ROCKSTAR, StoreLibraryCache.encode(emptyList()))) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/ea/EaTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/ea/EaTest.kt index b9deb11a11..2a3ed5ce63 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/ea/EaTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/ea/EaTest.kt @@ -1,6 +1,7 @@ package com.droiddeck.launcher.stores.ea import com.droiddeck.launcher.stores.CatalogItem +import com.droiddeck.launcher.stores.CloudSaves import com.droiddeck.launcher.stores.Store import com.droiddeck.launcher.stores.StoreGameSidecar import com.droiddeck.launcher.stores.StoreLaunch @@ -413,4 +414,190 @@ class EaTest { assertTrue(!EaAuth.storeRefreshed(app, "late", 3600, "r3")) assertNull(EaAuth.load(app)) } + + private fun tokenServer(status: String, error: String = "invalid_grant"): java.net.ServerSocket { + val server = java.net.ServerSocket(0) + Thread { + runCatching { + server.accept().use { socket -> + val input = socket.getInputStream() + val head = StringBuilder() + while (!head.endsWith("\r\n\r\n")) head.append(input.read().takeIf { it >= 0 }?.toChar() ?: break) + val length = Regex("(?i)content-length: *(\\d+)").find(head)?.groupValues?.get(1)?.toInt() ?: 0 + repeat(length) { input.read() } + val body = """{"error":"$error"}""".toByteArray() + socket.getOutputStream().apply { + write("HTTP/1.1 $status\r\nContent-Type: application/json\r\nContent-Length: ${body.size}\r\nConnection: close\r\n\r\n".toByteArray()) + write(body) + flush() + } + } + } + }.apply { isDaemon = true; start() } + return server + } + + @Test fun aRejectedRefreshAsksForSignInWhileAnUnreachableOneKeepsTheSessionForARetry() { + val app = org.robolectric.RuntimeEnvironment.getApplication() + val real = EaAuth.tokenUrl + try { + com.droiddeck.launcher.stores.StoreAccounts.write(app, Store.EA, + JSONObject().put("access_token", "old").put("refresh_token", "r").put("expires_at", 1L).put("user_id", "1")) + EaAuth.tokenUrl = "http://127.0.0.1:1/" + assertNull(EaAuth.accessToken(app)) + assertTrue(CloudSaves.status(app, Store.EA, "x").signedIn) + tokenServer("503 Service Unavailable", "temporarily_unavailable").use { server -> + EaAuth.tokenUrl = "http://127.0.0.1:${server.localPort}/" + assertNull(EaAuth.accessToken(app)) + } + assertTrue(CloudSaves.status(app, Store.EA, "x").signedIn) + tokenServer("400 Bad Request", "invalid_client").use { server -> + EaAuth.tokenUrl = "http://127.0.0.1:${server.localPort}/" + assertNull(EaAuth.accessToken(app)) + } + assertTrue(CloudSaves.status(app, Store.EA, "x").signedIn) + tokenServer("400 Bad Request").use { server -> + EaAuth.tokenUrl = "http://127.0.0.1:${server.localPort}/" + assertNull(EaAuth.accessToken(app)) + } + assertFalse(CloudSaves.status(app, Store.EA, "x").signedIn) + assertTrue(EaAuth.storeRefreshed(app, "new", 3600, "r2")) + assertTrue(CloudSaves.status(app, Store.EA, "x").signedIn) + } finally { + EaAuth.tokenUrl = real + EaAuth.signOut(app) + } + } + + private val heat = """ +%Documents%/Need for Speed Heat/SaveGame/savegame/ +%Documents%/Need for Speed Heat/SaveGame/wraps/ +%Documents%/Need for Speed Heat/settings/PROFILEOPTIONS +""" + + @Test fun rulesFindTheFolderTheyShareAndPickOnlyTheirFiles() { + val rules = EaSaveRules.parse(heat)!! + assertEquals("%Documents%/Need for Speed Heat/", rules.base()) + assertEquals("%DOCUMENTS%/Need for Speed Heat/", EaSaveRules.template(rules.base()!!)) + assertTrue(rules.matches("%Documents%/Need for Speed Heat/SaveGame/savegame/1")) + assertTrue(rules.matches("%documents%\\need for speed heat\\settings\\PROFILEOPTIONS")) + assertFalse(rules.matches("%Documents%/Need for Speed Heat/settings/PROFILEOPTIONS.bak")) + assertFalse(rules.matches("%Documents%/Need for Speed Heat/Logs/crash.txt")) + } + + @Test fun globsStayInsideTheirFolderAndExcludesWin() { + val bf = EaSaveRules.parse("""%Documents%/Battlefield 6/settings/*.xml + %Documents%/Battlefield 6/settings/*.sav""")!! + assertEquals("%Documents%/Battlefield 6/settings/", bf.base()) + assertTrue(bf.matches("%Documents%/Battlefield 6/settings/a.sav")) + assertFalse(bf.matches("%Documents%/Battlefield 6/settings/sub/a.sav")) + val le = EaSaveRules.parse(""" + %Documents%/BioWare/Mass Effect Legendary Edition/Config/ + %Documents%/BioWare/Mass Effect Legendary Edition/""")!! + assertTrue(le.matches("%Documents%/BioWare/Mass Effect Legendary Edition/Save/ME1/x.pcsav")) + assertFalse(le.matches("%Documents%/BioWare/Mass Effect Legendary Edition/Config/GamerSettings.ini")) + assertNull(EaSaveRules.parse("")) + assertNull(EaSaveRules.parse("""C:/Games/x/""")!!.base()) + } + + @Test fun rulesApplyInTheirOrderAndTheFirstMatchDecides() { + val rules = EaSaveRules.parse(""" +%Documents%/Game/Config/ +%Documents%/Game/Config/keys.ini +%Documents%/Game/""")!! + assertTrue(rules.matches("%Documents%/Game/Config/keys.ini")) + assertFalse(rules.matches("%Documents%/Game/Config/video.ini")) + assertTrue(rules.matches("%Documents%/Game/Save/1.sav")) + } + + @Test fun aBarePatternMatchesFileNamesInsideTheSaveFolder() { + val dig = EaSaveRules.parse(""" +%Documents%/My Games/SteamWorld Dig/controls.cfg +%Documents%/My Games/SteamWorld Dig/settings.xml +*.xml +%Documents%/My Games/SteamWorld Dig/profile.dat""")!! + assertEquals("%Documents%/My Games/SteamWorld Dig/", dig.base()) + assertTrue(dig.matches("%Documents%/My Games/SteamWorld Dig/profile1.xml")) + assertFalse(dig.matches("%Documents%/My Games/SteamWorld Dig/settings.xml")) + assertFalse(dig.matches("%Documents%/Other Game/profile1.xml")) + val witness = EaSaveRules.parse("""%AppData%/The Witness/**.png""")!! + assertEquals("%AppData%/The Witness/", witness.base()) + assertTrue(witness.matches("%AppData%/The Witness/shot.png")) + } + + @Test fun localLowAndInstallFoldersResolveToTheirTemplates() { + val fe = EaSaveRules.parse("""%LocalLowAppData%/Zoink Games/Fe/SystemSettings.sav +%LocalLowAppData%/Zoink Games/Fe/Save1.sav""")!! + assertEquals("%APPLICATION_DATA_LOCAL_LOW%/Zoink Games/Fe/", EaSaveRules.template(fe.base()!!)) + val castle = EaSaveRules.parse("""%InstallDir%/x86/Lost_Castle_Data/lc_game_data +%InstallDir%/x64/Lost_Castle_Data/lc_game_data""")!! + assertEquals("%INSTALL%/", EaSaveRules.template(castle.base()!!)) + assertTrue(castle.matches("%InstallDir%/x64/Lost_Castle_Data/lc_game_data")) + assertFalse(castle.matches("%InstallDir%/x64/Lost_Castle_Data/other")) + } + + @Test fun aManifestWithSingleQuotedAttributesKeepsEveryField() { + val m = EaCloud.parse(""" + %Documents%/A & B/1 + s1""") + val f = m.files.single() + assertEquals(12L, f.size); assertEquals("content/12-ab", f.href); assertEquals("q+w==", f.md5) + assertEquals("2022-10-17T23:51:04ZZ", f.created); assertEquals("2022-10-18T00:00:00ZZ", f.modified) + assertEquals("%Documents%/A & B/1", f.localName) + assertEquals("{1}", m.lineage); assertEquals(listOf("s1"), m.snapshots) + assertTrue(runCatching { EaCloud.parse("") }.isFailure) + } + + @Test fun aManifestKeepsItsFilesSnapshotsAndEaTimestampsThroughAWrite() { + val xml = """ + + %Documents%/Need for Speed Heat/SaveGame/savegame/1 + + 80cmnqT/rIKQRmciINSVhQ== +""" + val m = EaCloud.parse(xml) + assertEquals(1, m.files.size) + assertEquals("c7996be80a6e38d1f8ef28866b114f8b", EaCloud.hex(m.files[0].md5)) + assertEquals(1666050664000L, EaCloud.parseTime(m.files[0].modified)) + assertEquals("2022-10-17T23:51:04ZZ", EaCloud.stamp(1666050664123L)) + val again = EaCloud.parse(EaCloud.write(m)) + assertEquals(m.files.single().localName, again.files.single().localName) + assertEquals(m.files.single().href, again.files.single().href) + assertEquals(m.files.single().created, again.files.single().created) + assertEquals(m.files.single().modified, again.files.single().modified) + assertEquals(m.files.single().size, again.files.single().size) + assertEquals(m.files.single().md5, again.files.single().md5) + assertEquals(listOf("80cmnqT/rIKQRmciINSVhQ=="), again.snapshots) + assertEquals(m.lineage, again.lineage) + } + + @Test fun commentedRulesAreIgnoredAndNamesKeepTheirSpaces() { + val rules = EaSaveRules.parse(""" + + %Documents%/Game/ """)!! + assertEquals(listOf("%Documents%/Game/"), rules.includes) + assertTrue(rules.excludes.isEmpty()) + assertTrue(rules.matches("%Documents%/Game/Config/a.ini")) + assertEquals("%Documents%/Game/slot.sav ", EaSaveRules.normalize("%Documents%\\Game\\slot.sav ")) + } + + @Test fun aTruncatedManifestIsRefused() { + val cut = runCatching { EaCloud.parse("""""") } + assertTrue(cut.isFailure) + val open = runCatching { EaCloud.parse("""%Documents%/a""") } + assertTrue(open.isFailure) + } + + @Test fun snapshotEntitiesAreDecodedOnceAndWrittenBackTheSame() { + val m = EaCloud.parse("""abc+def""") + assertEquals(listOf("abc+def"), m.snapshots) + assertEquals(listOf("abc+def"), EaCloud.parse(EaCloud.write(m)).snapshots) + } + + @Test fun cloudKeysFollowTheMultiplayerId() { + assertEquals(listOf("195133_195133"), EaCloud.keys("195133", "195133")) + assertEquals(listOf("52209", "52209_52209"), EaCloud.keys("52209", "")) + assertEquals("https://x/y?a=1&b=2", EaCloud.manifestUrl("https://x/y?a=1&b=2")) + assertTrue(CloudSaves.supports(Store.EA)) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/MemorySlots.kt b/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/MemorySlots.kt new file mode 100644 index 0000000000..e32909ee71 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/MemorySlots.kt @@ -0,0 +1,43 @@ +package com.droiddeck.launcher.stores.ubisoft + +import com.droiddeck.launcher.stores.CloudSaves +import org.json.JSONArray +import org.json.JSONObject +import java.time.Instant + +internal class MemorySlots : UbisoftSlots { + private var record = JSONObject().put("entityId", "e1").put("name", UbisoftCloud.entityName(77L)).put("revision", 1) + .put("obj", JSONObject().put("slots", JSONArray())) + private var clock = 1_700_000_000_000L + val data = HashMap() + var uploadsLeft = Int.MAX_VALUE + var afterUpdate: (JSONArray) -> Unit = {} + + override fun entity() = UbisoftCloud.Entity(JSONObject(record.toString())) + + override fun upload(slot: String, data: ByteArray) { + if (uploadsLeft-- <= 0) throw java.io.IOException("upload failed") + this.data[slot] = data + } + + override fun update(entity: UbisoftCloud.Entity, slots: JSONArray) { + afterUpdate(slots) + record = JSONObject(record.toString()).put("revision", record.getInt("revision") + 1).put("obj", JSONObject().put("slots", slots)) + } + + override fun download(slot: String) = data[slot] + + fun store(slot: String, bytes: ByteArray) { + data[slot] = bytes + val slots = JSONArray(record.getJSONObject("obj").getJSONArray("slots").toString()) + val entry = (0 until slots.length()).map { slots.getJSONObject(it) }.firstOrNull { it.optString("filename") == slot } + ?: JSONObject().put("filename", slot).put("id", slot.toInt()).also { slots.put(it) } + clock += 60_000L + entry.put("hash", UbisoftCloud.mark(bytes)).put("size", bytes.size).put("lastModified", Instant.ofEpochMilli(clock).toString()) + record = JSONObject(record.toString()).put("revision", record.getInt("revision") + 1).put("obj", JSONObject().put("slots", slots)) + } + + companion object { + fun save(tag: String): ByteArray = ("UBISAVE0" + CloudSaves.md5(tag.toByteArray()) + tag).toByteArray() + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/UbisoftTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/UbisoftTest.kt index aecf4ca779..b0aea68660 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/UbisoftTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/ubisoft/UbisoftTest.kt @@ -5,6 +5,7 @@ import com.droiddeck.launcher.stores.Store import com.droiddeck.launcher.stores.StoreGameSidecar import com.droiddeck.launcher.stores.StoreLaunch import org.json.JSONArray +import java.io.File import org.json.JSONObject import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals @@ -98,4 +99,74 @@ class UbisoftTest { assertArrayEquals(bytes, UbisoftActivation.unhex("00017fff802a")) assertNull(UbisoftActivation.unhex("abc")) } + + @Test fun aSaveNamesItsUbisoftIdentifierInItsHeader() { + val mark = "4ef5bf634b40daa577aaeaa52c2283a9" + val save = byteArrayOf(0x24, 2, 0, 0, 0, 0, 0, 0) + mark.toByteArray() + ByteArray(64) { it.toByte() } + assertEquals(mark, UbisoftCloud.mark(save)) + assertNull(UbisoftCloud.mark(ByteArray(8) + ByteArray(32) + ByteArray(16))) + assertNull(UbisoftCloud.mark(ByteArray(39))) + } + + @Test fun cloudSaveBodiesSurviveTheZlibHop() { + val save = ByteArray(200_000) { (it % 251).toByte() } + assertArrayEquals(save, UbisoftCloud.inflate(UbisoftCloud.deflate(save))) + assertEquals(0x78, UbisoftCloud.deflate(save)[0].toInt()) + val packed = UbisoftCloud.deflate(save) + val cut = runCatching { UbisoftCloud.inflate(packed.copyOf(packed.size / 2)) } + assertTrue(cut.isFailure) + } + + @Test fun aSlotVersionChangesWithItsSizeTimeOrIdentifier() { + val a = UbisoftCloud.Slot(1, "1", "4ef5bf634b40daa577aaeaa52c2283a9", 2414, 1_689_224_156_000) + assertEquals("2414:1689224156000:4ef5bf634b40daa577aaeaa52c2283a9", UbisoftCloud.version(a)) + assertTrue(UbisoftCloud.version(a) != UbisoftCloud.version(UbisoftCloud.Slot(1, "1", a.hash, 2414, a.modifiedMs + 1))) + } + + @Test fun aSlotCommitCountsOnlyWhenNoOtherSlotMovedAndOursLanded() { + fun entity(revision: Int, vararg slots: Triple) = UbisoftCloud.Entity(JSONObject().put("revision", revision) + .put("obj", JSONObject().put("slots", JSONArray().apply { + for ((name, hash, size) in slots) put(JSONObject().put("filename", name).put("hash", hash).put("size", size).put("lastModified", "2026-01-01T00:00:00Z")) + }))) + val a = "4ef5bf634b40daa577aaeaa52c2283a9"; val b = "0123456789abcdef0123456789abcdef"; val c = "fedcba9876543210fedcba9876543210" + val before = entity(4, Triple("1", a, 10), Triple("2", b, 20)) + assertEquals(c, UbisoftCloudTransport.committedSlot(before, entity(5, Triple("1", c, 11), Triple("2", b, 20)), "1", c, 11)?.hash) + assertNull(UbisoftCloudTransport.committedSlot(before, entity(6, Triple("1", c, 11), Triple("2", a, 21)), "1", c, 11)) + assertNull(UbisoftCloudTransport.committedSlot(before, entity(6, Triple("1", b, 30), Triple("2", b, 20)), "1", c, 11)) + assertNull(UbisoftCloudTransport.committedSlot(before, entity(6, Triple("1", c, 11)), "1", c, 11)) + } + + @Test fun aSlotTheCloudRewritesBeforeItIsVerifiedStaysUnsent() { + val slots = MemorySlots().apply { store("1", MemorySlots.save("a1")) } + val transport = UbisoftCloudTransport(slots, "u1") + transport.list() + slots.afterUpdate = { list -> list.getJSONObject(0).put("hash", UbisoftCloud.mark(MemorySlots.save("other device"))) } + val changed = runCatching { transport.put(mapOf("1.save" to MemorySlots.save("a2"))) }.exceptionOrNull() as com.droiddeck.launcher.stores.CloudChanged + assertTrue(changed.sent.isEmpty()) + assertEquals(listOf("1.save"), changed.unsent) + assertNull(transport.committed("1.save")) + } + + @Test fun ubisoftCloudSavesAreSupported() { + assertTrue(com.droiddeck.launcher.stores.CloudSaves.supports(Store.UBISOFT)) + assertTrue(!com.droiddeck.launcher.stores.CloudSaves.supports(Store.AMAZON)) + } + + @Test fun keptGameTokensBelongToOneAccountAndProductUntilDropped() { + val root = kotlin.io.path.createTempDirectory().toFile() + val dir = File(root, "cache") + val cache = UbisoftActivation.TokenCache(dir) + assertNull(cache.get("u-1", 109)) + assertTrue(cache.put("u-1", 109, byteArrayOf(1, 2, 3))) + assertArrayEquals(byteArrayOf(1, 2, 3), cache.get("u-1", 109)) + assertNull(cache.get("u-1", 82)) + assertNull(cache.get("u-2", 109)) + assertTrue(cache.put("../u-1", 82, byteArrayOf(4))) + assertEquals(listOf("cache"), root.list()!!.toList()) + assertTrue(dir.listFiles()!!.all { it.parentFile == dir }) + assertTrue(cache.drop("u-1", 109)) + assertNull(cache.get("u-1", 109)) + assertTrue(cache.drop("u-1", 109)) + root.deleteRecursively() + } } 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 a59450e341..c2106a9bf9 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 @@ -184,6 +184,23 @@ class XboxCatalogTest { assertFalse(XboxCatalog.product(product(game, "Windows.Desktop"), mapOf(game to "gamepass"), null)!!.xboxCloud) } + @Test fun trialAndPreorderSkusDoNotMakeAGamePcInstallable() { + fun sku(format: String, vararg flags: String) = JSONObject().put("Sku", JSONObject().put("Properties", JSONObject().apply { + flags.forEach { put(it, true) } + put("Packages", JSONArray().put(JSONObject().put("PackageFormat", format).put("MaxDownloadSizeInBytes", 7L) + .put("PlatformDependencies", JSONArray().put(JSONObject().put("PlatformName", "Windows.Desktop"))))) + })) + fun offer(vararg skus: JSONObject) = JSONObject().put("ProductId", game).put("ProductType", "Game") + .put("LocalizedProperties", JSONArray().put(JSONObject().put("ProductTitle", "A Game"))) + .put("DisplaySkuAvailabilities", JSONArray(skus.toList())) + assertNull(XboxCatalog.product(offer(sku("EAPPX", "IsTrial")), mapOf(game to "owned"))) + assertNull(XboxCatalog.product(offer(sku("MSIXVC", "IsPreOrder")), mapOf(game to "owned"))) + val streamed = XboxCatalog.product(offer(sku("EAPPX", "IsTrial")), mapOf(game to "gamepass"), XboxCloudCatalog(setOf(game), emptySet()))!! + assertFalse(streamed.xboxPc); assertTrue(streamed.xboxCloud); assertEquals("", streamed.extra["format"]); assertEquals(0L, streamed.sizeBytes) + val retail = XboxCatalog.product(offer(sku("MSIXVC", "IsTrial"), sku("EAPPX")), mapOf(game to "owned"))!! + assertTrue(retail.xboxPc); assertEquals("EAPPX", retail.extra["format"]); assertEquals(7L, retail.sizeBytes) + } + @Test fun aCloudOnlyEditionFoldsIntoThePcCardWithTheSameTitle() { val cloud = XboxCloudCatalog(gamePass = setOf(parent), all = emptySet()) val pc = XboxCatalog.product(product(game, "Windows.Desktop"), mapOf(game to "gamepass"), cloud)!! diff --git a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxDeviceKeptTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxDeviceKeptTest.kt new file mode 100644 index 0000000000..b2227ae288 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxDeviceKeptTest.kt @@ -0,0 +1,67 @@ +package com.droiddeck.launcher.stores.xbox + +import com.droiddeck.launcher.stores.CredentialCipher +import com.droiddeck.launcher.stores.Store +import com.droiddeck.launcher.stores.StoreAccounts +import org.json.JSONArray +import org.json.JSONObject +import org.junit.After +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +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.security.SecureRandom +import javax.crypto.spec.SecretKeySpec + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [33], application = android.app.Application::class) +class XboxDeviceKeptTest { + private val app get() = RuntimeEnvironment.getApplication() + private val key = SecretKeySpec(ByteArray(32).also { SecureRandom().nextBytes(it) }, "AES") + + @Before fun setUp() { StoreAccounts.keys = CredentialCipher.KeyProvider { key }; StoreAccounts.keystoreFailed = false } + @After fun tearDown() { + StoreAccounts.clear(app, Store.XBOX) + StoreAccounts.keys = CredentialCipher.Keystore; StoreAccounts.keystoreFailed = false + } + + @Test fun signingOutKeepsOnlyTheRegisteredDevice() { + val device = JSONArray(listOf(1, 2, 3)) + StoreAccounts.write(app, Store.XBOX, JSONObject().put("username", "player") + .put("slots", JSONObject().put(XboxCredentials.DEVICE_SLOT, device).put("user-tokens", JSONArray(listOf(9))))) + XboxCredentials.invalidate(app) + val record = StoreAccounts.read(app, Store.XBOX)!! + assertNull(StoreAccounts.signedInAs(app, Store.XBOX)) + val slots = record.getJSONObject("slots") + assertEquals(listOf(XboxCredentials.DEVICE_SLOT), slots.keys().asSequence().toList()) + assertEquals(device.toString(), slots.getJSONArray(XboxCredentials.DEVICE_SLOT).toString()) + } + + @Test fun aFailedDeviceRewriteStillSignsOutAndRevokes() { + var sealing = true + StoreAccounts.keys = object : CredentialCipher.KeyProvider { + override fun key() = if (sealing) key else throw java.security.KeyStoreException("sealing refused") + override fun existing() = key + } + StoreAccounts.write(app, Store.XBOX, JSONObject().put("username", "player") + .put("slots", JSONObject().put(XboxCredentials.DEVICE_SLOT, JSONArray(listOf(1))))) + sealing = false + var revoked = false + XboxCredentials.invalidate(app) { revoked = true } + assertTrue(revoked) + assertTrue(StoreAccounts.keystoreFailed) + assertNull(StoreAccounts.read(app, Store.XBOX)) + assertNull(StoreAccounts.signedInAs(app, Store.XBOX)) + } + + @Test fun signingOutWithoutADeviceLeavesNoRecord() { + StoreAccounts.write(app, Store.XBOX, JSONObject().put("username", "player").put("slots", JSONObject())) + XboxCredentials.invalidate(app) + assertNull(StoreAccounts.read(app, Store.XBOX)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxInstallerRefusalTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxInstallerRefusalTest.kt new file mode 100644 index 0000000000..0e717f0c17 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxInstallerRefusalTest.kt @@ -0,0 +1,22 @@ +package com.droiddeck.launcher.stores.xbox + +import com.droiddeck.launcher.R +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class XboxInstallerRefusalTest { + private val refused = "NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-device-name 400" + private val full = "NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-device-limit 200" + private val granted = "NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-parsed 200" + + @Test fun theLastLicensingAnswerDecidesTheMessage() { + assertEquals(R.string.stores_xbox_license_refused, XboxInstaller.licenseRefusal(listOf(refused, "NEXUS_LEGACY_INSTALL_DIAGNOSTIC_V1 license-failed"))) + assertEquals(R.string.stores_xbox_device_group_full, XboxInstaller.licenseRefusal(listOf(full))) + } + + @Test fun aRefusalAnOlderBuildRecoveredFromIsNotReported() { + assertNull(XboxInstaller.licenseRefusal(listOf(refused, "NEXUS_LEGACY_INSTALL_DETAIL_V1 newest build has no license for this device, trying an older build", granted, "NEXUS_TRANSFER_DIAGNOSTIC_V1 transfer-short 0"))) + assertNull(XboxInstaller.licenseRefusal(listOf("NEXUS_TRANSFER_DIAGNOSTIC_V1 transfer-short 0"))) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxLaunchViewsTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxLaunchViewsTest.kt index f14d294c01..145cb45e66 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxLaunchViewsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxLaunchViewsTest.kt @@ -50,4 +50,15 @@ class XboxLaunchViewsTest { assertEquals("preserve", evidence.readText()) } finally { root.deleteRecursively() } } + + @Test fun viewsKeepTheFilesPathTheGuestBinds() { + val root = Files.createTempDirectory("xbox-view-alias").toFile() + try { + val real = root.resolve("data/data/app/files").apply { mkdirs() } + val alias = root.resolve("user0").also { Files.createSymbolicLink(it.toPath(), real.parentFile!!.toPath()) }.resolve("files") + val view = XboxLaunchViews().create(alias) + assertEquals(alias.resolve("xbox-runtime/views").path, view.parentFile!!.path) + assertTrue(real.resolve("xbox-runtime/views").resolve(view.name).isDirectory) + } finally { root.deleteRecursively() } + } } diff --git a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxManifestTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxManifestTest.kt index 99ab0a0eb6..d23072471a 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxManifestTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XboxManifestTest.kt @@ -16,6 +16,46 @@ class XboxManifestTest { java.io.File(root, "MicrosoftGame.Config").writeText("") assertEquals("Bin/Game.exe", XboxInstaller.executable(root)) } + @Test fun aLauncherMenuIsSkippedForTheProgramItNames() { + val root = temporary.newFolder() + java.io.File(root, "EmuMenu").mkdir() + java.io.File(root, "EmuMenu/EmuMenu.exe").writeText("menu") + java.io.File(root, "Emu.exe").writeText("emulator") + java.io.File(root, "MicrosoftGame.config").writeText("") + java.io.File(root, "EmuMenu/EmuMenuLaunchArguments.txt").writeText("exe=..\\Emu.exe\r\ntitlename=Game\r\n") + assertEquals("Emu.exe", XboxInstaller.executable(root)) + java.io.File(root, "EmuMenu/EmuMenuLaunchArguments.txt").writeText("exe=..\\..\\outside.exe\r\n") + assertEquals("EmuMenu/EmuMenu.exe", XboxInstaller.executable(root)) + java.io.File(root, "EmuMenu/EmuMenuLaunchArguments.txt").writeText("titlename=Game\r\n") + assertEquals("EmuMenu/EmuMenu.exe", XboxInstaller.executable(root)) + java.io.File(root, "EmuMenu/EmuMenuLaunchArguments.txt").writeText("exe=..\\EMU.EXE\r\n") + assertEquals("Emu.exe", XboxInstaller.executable(root)) + java.io.File(root, "emu.exe").writeText("other") + if (root.listFiles().orEmpty().count { it.name.equals("emu.exe", true) } == 2) + assertEquals("EmuMenu/EmuMenu.exe", XboxInstaller.executable(root)) + } + @Test fun anUnreadableForwardingFileFallsBackToTheDeclaredProgram() { + val root = temporary.newFolder() + java.io.File(root, "EmuMenu").mkdir() + java.io.File(root, "EmuMenu/EmuMenu.exe").writeText("menu") + java.io.File(root, "Emu.exe").writeText("emulator") + java.io.File(root, "MicrosoftGame.config").writeText("") + val arguments = java.io.File(root, "EmuMenu/EmuMenuLaunchArguments.txt").apply { writeText("exe=..\\Emu.exe\r\n") } + org.junit.Assume.assumeTrue(arguments.setReadable(false, false) && !arguments.canRead()) + try { assertEquals("EmuMenu/EmuMenu.exe", XboxInstaller.executable(root)) } finally { arguments.setReadable(true, false) } + } + @Test fun aForwardedProgramStaysRelativeWhenTheFolderIsReachedThroughALink() { + val real = temporary.newFolder() + java.io.File(real, "EmuMenu").mkdir() + java.io.File(real, "EmuMenu/EmuMenu.exe").writeText("menu") + java.io.File(real, "Emu.exe").writeText("emulator") + java.io.File(real, "MicrosoftGame.config").writeText("") + java.io.File(real, "EmuMenu/EmuMenuLaunchArguments.txt").writeText("exe=..\\Emu.exe\r\n") + val link = java.io.File(temporary.root, "linked") + val linked = runCatching { java.nio.file.Files.createSymbolicLink(link.toPath(), real.toPath()) }.isSuccess + org.junit.Assume.assumeTrue(linked) + assertEquals("Emu.exe", XboxInstaller.executable(link)) + } @Test fun rejectsTraversalAndExternalEntities() { for (xml in listOf("", "]>&external;", @@ -47,6 +87,75 @@ class XboxManifestTest { assertEquals(listOf("Retail.exe"), info.executables) assertEquals("Retail.exe", XboxManifest.executable(root)) } + @Test fun legacyPackageManifestNamesItsExecutableTheSameWay() { + // A legacy EAppx package carries AppxManifest.xml and has no config; the + // launcher must still find the identity and the launch path, or an install + // that completed cannot be registered or started. + val root = temporary.newFolder() + java.io.File(root, "ForzaHorizon4.exe").writeText("encrypted") + java.io.File(root, "AppxManifest.xml").writeText(""" + + + + """) + val info = XboxManifest.read(root) + assertEquals("Microsoft.SunriseBaseGame", info.name) + assertEquals("2023.1122.1704.2", info.version) + assertEquals(listOf("ForzaHorizon4.exe"), info.executables) + assertEquals("Windows.FullTrustApplication", info.entryPoint) + assertEquals("ForzaHorizon4.exe", XboxManifest.executable(root)) + assertFalse(XboxManifest.needsAppModel(root)) + } + @Test fun uwpEntryPointNeedsAnAppModelHost() { + // Forza Horizon 4's Store build declares Forza.App, so its executable is a view + // provider rather than a program: starting it directly only crashes. + val root = temporary.newFolder() + java.io.File(root, "ForzaHorizon4.exe").writeText("encrypted") + java.io.File(root, "AppxManifest.xml").writeText(""" + + + """) + assertEquals("Forza.App", XboxManifest.read(root).entryPoint) + assertTrue(XboxManifest.needsAppModel(root)) + } + private fun legacy(application: String): java.io.File { + val root = temporary.newFolder() + java.io.File(root, "Game.exe").writeText("encrypted") + java.io.File(root, "AppxManifest.xml").writeText(""" + + + $application""") + return root + } + @Test fun windowsAppRuntimeBehaviorNeedsAnAppModelWithoutAnEntryPoint() { + val root = legacy("""""") + assertEquals("windowsApp", XboxManifest.read(root).runtimeBehavior) + assertEquals("", XboxManifest.read(root).entryPoint) + assertTrue(XboxManifest.needsAppModel(root)) + } + @Test fun classicRuntimeBehaviorsStartTheExecutableDirectly() { + for (behavior in listOf("packagedClassicApp", "win32App")) { + val root = legacy("""""") + assertEquals(behavior, XboxManifest.read(root).runtimeBehavior) + assertFalse(behavior, XboxManifest.needsAppModel(root)) + val declared = legacy("""""") + assertFalse(behavior, XboxManifest.needsAppModel(declared)) + } + } + @Test fun anEntryPointStillDecidesWithoutARuntimeBehavior() { + assertTrue(XboxManifest.needsAppModel(legacy(""""""))) + assertFalse(XboxManifest.needsAppModel(legacy(""""""))) + } + @Test fun aTitleWithoutALegacyManifestNeverNeedsAnAppModel() { + val root = temporary.newFolder() + java.io.File(root, "Game.exe").writeText("encrypted") + java.io.File(root, "MicrosoftGame.config").writeText("") + assertEquals("", XboxManifest.read(root).entryPoint) + assertFalse(XboxManifest.needsAppModel(root)) + assertFalse(XboxManifest.needsAppModel(temporary.newFolder())) + } @Test fun signInBridgeRejectsUntrustedAndNonHttpsOrigins() { assertTrue(XboxLoginActivity.trusted("https://login.live.com/ppsecure/InlineLogin.srf")) for (url in listOf("http://login.live.com/", "https://login.live.com.evil.test/", "https://evil.test@login.live.com/", "https://login.live.com:8443/")) diff --git a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XodusDiagnosticsTest.kt b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XodusDiagnosticsTest.kt index c2d723f7b6..3e2310be5c 100644 --- a/app/src/test/java/com/droiddeck/launcher/stores/xbox/XodusDiagnosticsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/stores/xbox/XodusDiagnosticsTest.kt @@ -1,6 +1,8 @@ package com.droiddeck.launcher.stores.xbox +import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Test @@ -16,4 +18,12 @@ class XodusDiagnosticsTest { assertFalse("Microsoft content licensing rejected sign-in (HTTP 403). Sign in again in Settings.".matches(rejected)) assertFalse("NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-http 401".matches(rejected)) } + + @Test fun aLicensingTimeoutAfterARefusalReachesTheTailAndIsReported() { + val stderr = listOf("NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-device-name 400", "NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-timeout 0") + val tail = stderr.filter { it.matches(Xodus.reportable) } + assertEquals(stderr, tail) + assertNull(XboxInstaller.licenseRefusal(tail)) + assertFalse("NEXUS_CONTENT_LICENSE_DIAGNOSTIC_V1 content-timeout 1000".matches(Xodus.reportable)) + } } diff --git a/app/src/test/java/com/droiddeck/launcher/ui/CloudMessageTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/CloudMessageTest.kt index 2bf7360edf..0ada7eba29 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/CloudMessageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/CloudMessageTest.kt @@ -3,6 +3,7 @@ package com.droiddeck.launcher.ui import com.droiddeck.launcher.R import com.droiddeck.launcher.stores.CloudSaves import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @@ -25,6 +26,15 @@ class CloudMessageTest { assertEquals(ctx.getString(R.string.cloud_not_synced), msg("failed", 0, 0, "SocketTimeoutException")) } + @Test fun aPartialSyncNamesTheSlotsItLeft() { + fun partial(conflicts: Int, detail: String) = cloudMessage(ctx, CloudSaves.Result("partial", 0, 0L, "blocked-path", conflicts, detail)) + assertEquals(ctx.getString(R.string.cloud_partial, "outside the save folder: ../x.save"), partial(0, "outside the save folder: ../x.save")) + assertEquals(ctx.getString(R.string.cloud_conflict_files_detail, 2, "changed locally: 1.save, 2.save"), partial(2, "changed locally: 1.save, 2.save")) + assertTrue(partial(1, "changed locally: 1.save").contains("1.save")) + assertEquals(ctx.getString(R.string.cloud_conflict_files, 1), partial(1, "")) + assertEquals(ctx.getString(R.string.cloud_not_synced), partial(0, "")) + } + @Test fun okResultsSayWhatHappened() { assertEquals(ctx.getString(R.string.cloud_up_to_date), msg("ok", 0, 0, "up-to-date")) assertEquals(ctx.getString(R.string.cloud_done, 3), msg("ok", 3, 0, "uploaded")) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/ColorPickerLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/ColorPickerLayoutTest.kt new file mode 100644 index 0000000000..41c43ad81c --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/ColorPickerLayoutTest.kt @@ -0,0 +1,54 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.ui.test.getUnclippedBoundsInRoot +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.unit.dp +import com.droiddeck.launcher.R +import org.junit.Assert.assertTrue +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 +import org.robolectric.annotation.GraphicsMode + +@RunWith(RobolectricTestRunner::class) +@Config(sdk = [34], qualifiers = "w832dp-h468dp-land-369dpi") +@GraphicsMode(GraphicsMode.Mode.NATIVE) +class ColorPickerLayoutTest { + @get:Rule val compose = createRobolectricComposeRule() + + private fun show() { + compose.setContent { + DroidDeckTheme(theme = Themes.GRAPHITE) { ColorPickerDialog("Highlight color", 0xFFE53935.toInt(), onDismiss = {}) {} } + } + compose.mainClock.advanceTimeBy(1_000) + } + + private fun ok() = compose.onNodeWithText(RuntimeEnvironment.getApplication().getString(R.string.common_ok)).getUnclippedBoundsInRoot() + + private fun assertOkOnScreen() { + val height = RuntimeEnvironment.getApplication().resources.configuration.screenHeightDp.dp + val ok = ok() + assertTrue("OK ends at ${ok.bottom} on a $height screen", ok.bottom <= height - 28.dp) + assertTrue("OK starts at ${ok.top}", ok.top >= 0.dp) + } + + @Test fun onALandscapeHandheldThePickerEndsWellAboveTheScreenEdge() { + show() + val ok = ok() + val title = compose.onNodeWithText("Highlight color").getUnclippedBoundsInRoot() + assertTrue("OK ends at ${ok.bottom}, title ${title.top}", ok.bottom <= 468.dp - 40.dp) + assertTrue("title starts at ${title.top}", title.top >= 40.dp) + } + + @Test @Config(qualifiers = "w740dp-h360dp-land-420dpi") + fun onAShortLandscapePhoneOkIsOnScreen() { show(); assertOkOnScreen() } + + @Test @Config(qualifiers = "w800dp-h384dp-land") + fun onAShortWideScreenOkIsOnScreen() { show(); assertOkOnScreen() } + + @Test @Config(qualifiers = "w411dp-h891dp-port-420dpi") + fun inPortraitOkIsOnScreen() { show(); assertOkOnScreen() } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt new file mode 100644 index 0000000000..192e70d5e1 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/InputSurfaceEditorViewTest.kt @@ -0,0 +1,76 @@ +package com.droiddeck.launcher.ui + +import android.view.MotionEvent +import com.droiddeck.launcher.input.InputControl +import com.droiddeck.launcher.input.InputSurfaceElement +import com.droiddeck.launcher.input.OnScreenLayout +import com.droiddeck.launcher.input.SavedInputLayout +import org.junit.Assert.assertEquals +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 = [34], manifest = Config.NONE) +class InputSurfaceEditorViewTest { + private val context get() = RuntimeEnvironment.getApplication() + private val layout = SavedInputLayout("custom", "Custom", listOf(InputSurfaceElement(InputControl.A, .1f, .2f, .2f, .2f)), aspect = 2f) + + private fun view() = InputSurfaceEditorView(context).apply { + layout(0, 0, 1000, 1000) + sourceLayout = layout + aspect = layout.aspect + elements = layout.elements + snap = false + } + + private fun center() = OnScreenLayout.editorElements(context, layout, 1000, 1000).first().let { (it.x + it.width / 2) * 1000 to (it.y + it.height / 2) * 1000 } + @Suppress("UNCHECKED_CAST") + private fun InputSurfaceEditorView.rendered() = javaClass.getDeclaredField("visibleElements").also { it.isAccessible = true }.get(this) as List + + private fun InputSurfaceEditorView.touch(action: Int, x: Float, y: Float) { + MotionEvent.obtain(0, 10, action, x, y, 0).also { onTouchEvent(it); it.recycle() } + } + + @Test fun editingStartsInTheDisplayedFrame() { + val view = view() + var started: Pair, Float>? = null + view.onBeginEdit = { elements, w, h -> started = elements to w.toFloat() / h } + val (x, y) = center() + view.touch(MotionEvent.ACTION_DOWN, x, y) + view.touch(MotionEvent.ACTION_MOVE, x + 100f, y + 50f) + val (elements, aspect) = requireNotNull(started) + assertEquals(1f, aspect, .0001f) + assertEquals(OnScreenLayout.editorElements(context, layout, 1000, 1000), elements) + } + + @Test fun undoRestoresTheSavedFrameForHitTesting() { + val view = view() + var selection: String? = null + view.onSelect = { selection = it } + view.elements = layout.elements.map { it.copy(x = .5f) } + view.elements = layout.elements + val (x, y) = center() + view.touch(MotionEvent.ACTION_DOWN, x, y) + assertEquals("legacy:a", selection) + } + + @Test fun editorFramePreservesAddedAndRemovedDraftElements() { + val added = layout.elements + InputSurfaceElement(InputControl.B, .6f, .2f, .2f, .2f, id = "added") + val removed = layout.copy(elements = emptyList()) + assertEquals(added, OnScreenLayout.editorFrame(layout.copy(elements = added), added)) + assertEquals(emptyList(), OnScreenLayout.editorFrame(removed, emptyList())) + } + + @Test fun savedAspectRemainsStableForRenamesAndResizes() { + val view = view() + val renamed = layout.elements.map { it.copy(name = "Renamed") } + view.elements = renamed + view.aspect = 2f + assertEquals(OnScreenLayout.editorElements(context, layout.copy(elements = renamed, aspect = 2f), 1000, 1000), view.rendered()) + view.layout(0, 0, 800, 1000) + assertEquals(OnScreenLayout.editorElements(context, layout.copy(elements = renamed, aspect = 2f), 800, 1000), view.rendered()) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/LibraryHiddenTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/LibraryHiddenTest.kt new file mode 100644 index 0000000000..ac5835c2a5 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/LibraryHiddenTest.kt @@ -0,0 +1,42 @@ +package com.droiddeck.launcher.ui + +import com.droiddeck.launcher.frontend.Library +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class LibraryHiddenTest { + private fun steam(id: Int, name: String) = LibraryEntry("app:$id", Library.SOURCE_STEAM, name, Library.SteamGame(id, name, null, "Steam library"), null, true) + + private val tf2 = steam(440, "Team Fortress 2") + private val cs = steam(10, "Counter-Strike") + private val hiddenSet = setOf(tf2.favoriteKey) + private val hidden: (LibraryEntry) -> Boolean = { it.favoriteKey in hiddenSet } + + @Test fun hiddenGamesLeaveAllAndTheirStoreTab() { + assertFalse(inLibrarySource(LIBRARY_ALL, tf2, emptySet(), hidden)) + assertFalse(inLibrarySource(Library.SOURCE_STEAM, tf2, emptySet(), hidden)) + assertTrue(inLibrarySource(LIBRARY_ALL, cs, emptySet(), hidden)) + assertTrue(inLibrarySource(Library.SOURCE_STEAM, cs, emptySet(), hidden)) + } + + @Test fun hiddenGamesLeaveFavorites() { + assertFalse(inLibrarySource(LIBRARY_FAVORITES, tf2, setOf(tf2.favoriteKey), hidden)) + } + + @Test fun theHiddenSourceHoldsOnlyHiddenGames() { + assertTrue(inLibrarySource(LIBRARY_HIDDEN, tf2, emptySet(), hidden)) + assertFalse(inLibrarySource(LIBRARY_HIDDEN, cs, emptySet(), hidden)) + } + + @Test fun theHiddenTabIsLastAndOnlyWhenEnabled() { + val entries = listOf(tf2, cs) + assertEquals(listOf(Library.SOURCE_STEAM), librarySources(entries, emptyList(), hidden = hidden)) + assertEquals(listOf(Library.SOURCE_STEAM, LIBRARY_HIDDEN), librarySources(entries, emptyList(), hidden = hidden, showHidden = true)) + } + + @Test fun aStoreTabWithOnlyHiddenGamesDisappears() { + assertEquals(emptyList(), librarySources(listOf(tf2), emptyList(), hidden = hidden)) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt index f824f20d2c..1736382512 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/NavTabsTest.kt @@ -37,29 +37,60 @@ class NavTabsTest { @Before @After fun reset() { ctx.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear().commit() NavTabs.load(ctx) - com.droiddeck.launcher.agent.AgentTab.load(ctx) } - @Test fun musicStartsInMore() { - assertEquals(listOf("steam", "games", "stores", "desktop", "components", "setup", "updates", NavTabs.MORE), navigationKeys(state())) - assertEquals(listOf("soundtracks"), NavTabs.more(state())) - assertEquals(setOf("soundtracks", "agent"), NavTabs.shelved) + @Test fun aFreshInstallShowsTheDefaultBarMoreAndHiddenTabs() { + assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", NavTabs.MORE), navigationKeys(state())) + assertEquals(listOf("stores", "soundtracks", "components", "storage", "sync"), NavTabs.more(state())) + assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "android-apps")) + assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "agent")) assertFalse(com.droiddeck.launcher.agent.AgentTab.shown) + assertTrue(NavTabs.isDefault()) } @Test fun showingMusicOnceKeepsItShownAfterReload() { place("soundtracks", TabPlace.BAR) NavTabs.load(ctx) - assertEquals(listOf("steam", "games", "soundtracks", "stores", "desktop", "components", "setup", "updates"), navigationKeys(state())) + assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", "soundtracks", NavTabs.MORE), navigationKeys(state())) } @Test fun shelvedTabsLeaveTheBarAndAddMoreAtTheEnd() { - place("stores", TabPlace.MORE) - place("components", TabPlace.MORE) + place("desktop", TabPlace.MORE) val s = state() - assertEquals(listOf("components", "soundtracks", "stores"), NavTabs.more(s)) + assertEquals(listOf("desktop", "stores", "soundtracks", "components", "storage", "sync"), NavTabs.more(s)) assertEquals(NavTabs.MORE, navigationKeys(s).last()) - assertFalse("stores" in navigationKeys(s)) + assertFalse("desktop" in navigationKeys(s)) + } + + @Test fun appsAndTheDevHarnessCanBeShownWithoutHomeScreenOrDeveloperTools() { + place("android-apps", TabPlace.MORE) + assertTrue("android-apps" in NavTabs.more(state())) + place("agent", TabPlace.BAR) + assertTrue(com.droiddeck.launcher.agent.AgentTab.shown) + } + + @Test fun resettingPutsBackTheDefaultLayout() { + place("stores", TabPlace.BAR) + place("updates", TabPlace.HIDDEN) + moveTab("downloads", -1) + assertFalse(NavTabs.isDefault()) + NavTabs.reset(ctx) + NavTabs.load(ctx) + assertTrue(NavTabs.isDefault()) + assertEquals(listOf("steam", "desktop", "games", "downloads", "setup", "updates", NavTabs.MORE), navigationKeys(state())) + } + + @Test fun anOldLayoutKeepsWhatItsSwitchesShowed() { + ctx.getSharedPreferences("session", Context.MODE_PRIVATE).edit().clear() + .putBoolean("gameStoresEnabled", false).putBoolean("soundtracksEnabled", false).commit() + NavTabs.load(ctx) + val s = state() + assertEquals(listOf("steam", "games", "desktop", "components", "setup", "updates", NavTabs.MORE), navigationKeys(s)) + assertEquals(listOf("storage", "sync"), NavTabs.more(s)) + listOf("stores", "downloads", "soundtracks", "android-apps", "agent").forEach { assertEquals(it, TabPlace.HIDDEN, NavTabs.place(s, it)) } + val prefs = ctx.getSharedPreferences("session", Context.MODE_PRIVATE) + assertFalse(prefs.contains("gameStoresEnabled")) + assertFalse(prefs.contains("soundtracksEnabled")) } @Test fun hiddenTabsAreNowhereAndSetupCannotBeHidden() { @@ -71,38 +102,54 @@ class NavTabsTest { assertTrue("setup" in navigationKeys(s)) } - @Test fun disabledStoresFeatureReadsAsHidden() { - assertEquals(TabPlace.HIDDEN, NavTabs.place(state(storesOn = false), "stores")) + @Test fun storesAndMusicHideLikeAnyOtherTab() { + place("stores", TabPlace.HIDDEN) + place("soundtracks", TabPlace.HIDDEN) + assertEquals(TabPlace.HIDDEN, NavTabs.place(state(), "stores")) + assertEquals(TabPlace.MORE, NavTabs.place(state(), "components")) + assertEquals(TabPlace.BAR, NavTabs.place(state(), "downloads")) + assertEquals(listOf("components", "storage", "sync"), NavTabs.more(state())) } @Test fun movingSwapsWithTheNextVisibleTabAndPersists() { - place("soundtracks", TabPlace.BAR) - moveTab("stores", -1) - assertEquals(listOf("steam", "games", "stores", "soundtracks"), navigationKeys(state()).take(4)) + moveTab("games", -1) + assertEquals(listOf("steam", "games", "desktop", "downloads"), navigationKeys(state()).take(4)) NavTabs.load(ctx) - assertEquals(listOf("steam", "games", "stores", "soundtracks"), navigationKeys(state()).take(4)) + assertEquals(listOf("steam", "games", "desktop", "downloads"), navigationKeys(state()).take(4)) } @Test fun tabsMissingFromASavedOrderSlotInAfterTheirDefaultNeighbour() { - assertEquals(listOf("updates", "steam", "games", "soundtracks", "stores", "desktop", "agent", "components", "android-apps", "setup"), + assertEquals(listOf("updates", "stores", "soundtracks", "components", "storage", "sync", "android-apps", "agent", "steam", "desktop", "games", "downloads", "setup"), NavTabs.arrange(listOf("updates", "steam"))) - assertEquals(listOf("games", "soundtracks", "steam", "setup", "stores", "desktop", "agent", "components", "android-apps", "updates"), + assertEquals(listOf("games", "downloads", "steam", "setup", "stores", "soundtracks", "desktop", "components", "storage", "sync", "android-apps", "agent", "updates"), NavTabs.arrange(listOf("games", "steam", "setup", "stores", "desktop", "components", "android-apps", "updates", "bogus"))) } + @Test fun storageAndSyncJoinMoreForUsersWithASavedLayout() { + ctx.getSharedPreferences("session", Context.MODE_PRIVATE).edit() + .putString("navTabOrder", "steam,games,soundtracks,stores,desktop,agent,components,android-apps,setup,updates") + .putString("navTabShelved", "soundtracks").commit() + NavTabs.load(ctx) + assertEquals(listOf("soundtracks", "storage", "sync"), NavTabs.more(state())) + place("sync", TabPlace.BAR) + NavTabs.load(ctx) + assertTrue("sync" in navigationKeys(state())) + } + @Test fun moreCarriesTheDownloadCountAndBadgesOfShelvedTabs() { - place("stores", TabPlace.MORE) + place("downloads", TabPlace.MORE) place("setup", TabPlace.MORE) val s = state(downloads = 3, setupReady = false) assertEquals(3, railCount(s, NavTabs.MORE)) assertTrue(railBadge(s, NavTabs.MORE)) - place("stores", TabPlace.BAR) + place("downloads", TabPlace.BAR) assertEquals(0, railCount(s, NavTabs.MORE)) - assertEquals(3, railCount(s, "stores")) + assertEquals(3, railCount(s, "downloads")) + assertEquals(0, railCount(s, "stores")) } - @Test fun sideRailShowsTheDownloadCountOnMoreWhenStoresIsShelved() { - place("stores", TabPlace.MORE) + @Test fun sideRailShowsTheDownloadCountOnMoreWhenDownloadsIsShelved() { + place("downloads", TabPlace.MORE) val s = state(downloads = 2) compose.setContent { DroidDeckTheme { @@ -111,13 +158,13 @@ class NavTabsTest { } } } - compose.onNodeWithTag("rail-stores").assertDoesNotExist() + compose.onNodeWithTag("rail-downloads").assertDoesNotExist() compose.onNode(hasTestTag("rail-more")).assertIsDisplayed() compose.onNode(hasText("2") and hasParentTag("rail-more"), useUnmergedTree = true).assertIsDisplayed() } @Test fun morePageListsShelvedTabsWithTheirCount() { - place("stores", TabPlace.MORE) + place("downloads", TabPlace.MORE) place("components", TabPlace.MORE) val s = state(downloads = 4) compose.setContent { @@ -127,9 +174,9 @@ class NavTabsTest { } } } - compose.onNodeWithTag("more-stores").assertIsDisplayed() + compose.onNodeWithTag("more-downloads").assertIsDisplayed() compose.onNodeWithTag("more-components").assertIsDisplayed() - compose.onNode(hasText("4") and hasParentTag("more-stores"), useUnmergedTree = true).assertIsDisplayed() + compose.onNode(hasText("4") and hasParentTag("more-downloads"), useUnmergedTree = true).assertIsDisplayed() } @Test fun backFromAShelvedTabReturnsToMore() { @@ -159,7 +206,7 @@ class NavTabsTest { compose.setContent { DroidDeckTheme { FrontEndScreen(state(), actions(), page = null) } } compose.mainClock.advanceTimeBy(2_000) compose.onNode(hasText(ctx.getString(com.droiddeck.launcher.R.string.content_page_gone))).assertDoesNotExist() - compose.onNode(hasTestTag("rail-games") and androidx.compose.ui.test.isSelected()).assertExists() + compose.onNode(hasTestTag("rail-desktop") and androidx.compose.ui.test.isSelected()).assertExists() } @Test fun setupListMovesATabAcrossTheMoreLineWithTheControllerAndHidesWithItsSwitch() { @@ -203,11 +250,11 @@ class NavTabsTest { private fun hasParentTag(tag: String) = androidx.compose.ui.test.hasAnyAncestor(hasTestTag(tag)) - private fun state(storesOn: Boolean = true, downloads: Int = 0, setupReady: Boolean = true) = FrontEndState( + private fun state(downloads: Int = 0, setupReady: Boolean = true) = FrontEndState( installed = "r9", ready = setupReady, available = null, busy = false, stage = "", percent = -1, desktopInstalled = true, offlineAccount = null, offline = false, frameGenLabel = "", romsDir = null, logsEnabled = false, steamGames = emptyList(), emulators = emptyList(), running = null, - gameStoresEnabled = storesOn, storeDownloadsActive = downloads, + storeDownloadsActive = downloads, ) private fun actions() = FrontEndActions( diff --git a/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt index 25ba697759..1f6a4b7073 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/PortraitLayoutTest.kt @@ -75,6 +75,11 @@ class PortraitLayoutTest { } @Test fun narrowBottomBarScrollsToEveryDestinationWithAppsAndResumeVisible() { + val ctx = androidx.test.core.app.ApplicationProvider.getApplicationContext() + NavTabs.reset(ctx) + NavTabs.setHidden(ctx, "android-apps", false) + val all = NavTabs.listed(stateWithAppsAndSession).filter { NavTabs.place(stateWithAppsAndSession, it) != TabPlace.HIDDEN } + NavTabs.rearrange(ctx, stateWithAppsAndSession, all, emptyList()) val selected = mutableStateOf("steam") compose.setContent { DroidDeckTheme { @@ -82,7 +87,7 @@ class PortraitLayoutTest { } } compose.mainClock.advanceTimeBy(1_000) - for (key in listOf("games", "stores", "desktop", "components", "android-apps", "setup", "updates", "steam")) { + for (key in all.drop(1) + all.first()) { compose.onNodeWithTag("rail-$key").performScrollTo() compose.mainClock.advanceTimeBy(1_000) compose.onNodeWithTag("rail-$key").assertIsDisplayed().performClick() @@ -91,6 +96,7 @@ class PortraitLayoutTest { compose.onNodeWithTag("rail-$key").assertIsSelected().assertHeightIsAtLeast(48.dp).assertWidthIsAtLeast(48.dp) } compose.onNodeWithContentDescription("Resume Steam").assertIsDisplayed() + NavTabs.reset(ctx) } @Test fun bottomBarFollowsSidebarLabelsSetting() { diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt index 15888d289f..58b8ba055b 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/SessionDrawerPageTest.kt @@ -5,7 +5,7 @@ import org.junit.Test class SessionDrawerPageTest { @Test fun singleScreenNavigationStartsWithControllerAndSkipsSecondScreen() { - val pages = sessionDrawerPages(false) + val pages = sessionDrawerPages(false, hasAgent = false) assertEquals(SessionDrawerPage.CONTROLLER, pages.first()) assertFalse(SessionDrawerPage.SECOND_SCREEN in pages) assertEquals(SessionDrawerPage.DISPLAY, pages.step(SessionDrawerPage.CONTROLLER, 1)) @@ -14,11 +14,11 @@ class SessionDrawerPageTest { } @Test fun connectedSecondaryDisplayAddsItsPageAfterControllerAndPreservesOtherPages() { - val connected = sessionDrawerPages(true) + val connected = sessionDrawerPages(true, hasAgent = false) assertEquals(SessionDrawerPage.SECOND_SCREEN, connected.step(SessionDrawerPage.CONTROLLER, 1)) assertEquals(SessionDrawerPage.DISPLAY, connected.step(SessionDrawerPage.SECOND_SCREEN, 1)) - assertEquals(sessionDrawerPages(false), connected.filter { it != SessionDrawerPage.SECOND_SCREEN }) - for (pages in listOf(connected, sessionDrawerPages(false))) { + assertEquals(sessionDrawerPages(false, hasAgent = false), connected.filter { it != SessionDrawerPage.SECOND_SCREEN }) + for (pages in listOf(connected, sessionDrawerPages(false, hasAgent = false))) { assertEquals(SessionDrawerPage.HUD, pages.step(SessionDrawerPage.DISPLAY, 1)) assertEquals(SessionDrawerPage.EFFECTS, pages.step(SessionDrawerPage.HUD, 1)) assertEquals(SessionDrawerPage.VR, pages.step(SessionDrawerPage.EFFECTS, 1)) @@ -27,7 +27,7 @@ class SessionDrawerPageTest { } } - @Test fun theAgentPageComesBeforeSessionOnlyWhenTheAgentIsInstalled() { + @Test fun theAgentPageComesBeforeSessionOnlyWhenTheTabIsShown() { val with = sessionDrawerPages(false, hasAgent = true) assertEquals(SessionDrawerPage.AGENT, with.step(SessionDrawerPage.GAMES, 1)) assertEquals(SessionDrawerPage.SESSION, with.step(SessionDrawerPage.AGENT, 1)) diff --git a/app/src/test/java/com/droiddeck/launcher/ui/SettingsMapTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/SettingsMapTest.kt new file mode 100644 index 0000000000..2bfc25c309 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/ui/SettingsMapTest.kt @@ -0,0 +1,69 @@ +package com.droiddeck.launcher.ui + +import com.droiddeck.launcher.R +import java.io.File +import javax.xml.parsers.DocumentBuilderFactory +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Test + +class SettingsMapTest { + private val strings: Map by lazy { + File("src/main/res/values").listFiles { f -> f.extension == "xml" }.orEmpty().flatMap { file -> + val doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file) + val nodes = doc.getElementsByTagName("string") + (0 until nodes.length).map { i -> + val n = nodes.item(i) + n.attributes.getNamedItem("name").nodeValue to n.textContent.replace("\\'", "'").replace("\\\"", "\"") + } + }.toMap() + } + + private val names: Map by lazy { + R.string::class.java.fields.associate { it.getInt(null) to it.name } + } + + private fun text(id: Int): String = strings.getValue(names.getValue(id)) + + private fun render(): String = buildString { + appendLine("# Where settings live") + appendLine() + appendLine("Generated from `SettingsIndex.kt` by `SettingsMapTest`. Run `UPDATE_SETTINGS_MAP=1 ./gradlew :app:testDebugUnitTest --tests '*SettingsMapTest*'` after changing the index.") + appendLine() + appendLine("Links of the form `droiddeck://settings/
` open a Settings section directly.") + appendLine() + SettingsIndex.entries.groupBy { it.place }.forEach { (place, entries) -> + appendLine("## ${text(place.title)}") + appendLine() + appendLine("| Setting | Where | Also matches |") + appendLine("| --- | --- | --- |") + entries.forEach { e -> + val where = listOfNotNull(text(place.title), e.within?.let(::text)).joinToString(" › ") + + (e.section?.let { " (`droiddeck://settings/${it.key}`)" } ?: "") + appendLine("| ${text(e.title)} | $where | ${e.words.joinToString(", ")} |") + } + appendLine() + } + } + + @Test + fun everyIndexedStringExists() { + SettingsIndex.entries.forEach { e -> + listOfNotNull(e.title, e.within).forEach { id -> assertTrue("missing string $id", names[id] in strings) } + } + SettingsSection.entries.forEach { assertTrue(names[it.title] in strings) } + } + + @Test + fun docsMatchIndex() { + val doc = File("../docs/settings-map.md") + val now = render() + if (System.getenv("UPDATE_SETTINGS_MAP") == "1") doc.writeText(now) + assertEquals("docs/settings-map.md is stale; regenerate it", now, doc.readText().replace("\r\n", "\n")) + } + + @Test + fun sectionKeysRoundTrip() { + SettingsSection.entries.forEach { assertEquals(it, SettingsSection.of(it.key)) } + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt b/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt index 4f914f0b55..1f214aba0c 100644 --- a/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/ui/StoreRestorationTest.kt @@ -64,7 +64,7 @@ class StoreRestorationTest { } compose.mainClock.advanceTimeBy(100) compose.onNodeWithText(ctx.getString(R.string.stores_xbox_content_title)).assertExists() - compose.onNodeWithText("Missing or ambiguous MicrosoftGame.config.").assertExists() + compose.onNodeWithText("Missing or ambiguous game manifest.").assertExists() compose.onNodeWithText(ctx.getString(android.R.string.ok)).performClick() compose.runOnIdle { assertNull(XboxContent.plan) } } diff --git a/docs/agent-control.md b/docs/agent-control.md index 171f0960c7..ed9fbcf1e3 100644 --- a/docs/agent-control.md +++ b/docs/agent-control.md @@ -151,7 +151,7 @@ tools/droiddeckctl env set DXVK_HUD=fps tools/droiddeckctl env list tools/droiddeckctl env clear [next|persistent|all] tools/droiddeckctl override gamescope ./gamescope -tools/droiddeckctl override libblfastpath.so ./libblfastpath.so +tools/droiddeckctl override libddfastpath.so ./libddfastpath.so tools/droiddeckctl proot-profile enable --slow-us 1000 tools/droiddeckctl proot-profile disable tools/droiddeckctl proot-profile report ./session.log --sort wall @@ -436,7 +436,7 @@ through first, since the launcher window carries the game's app id too: `proot-profile enable` queues handler profiling for the next session using the existing debugging consent gate. Counters and bounded slow samples appear in `session.log`; `proot-profile report` ranks a saved local log without ADB. This measures PRoot handler work, not full syscall latency. -`override libblfastpath.so FILE` selects a glibc ARM64 shared library in the next session's preload +`override libddfastpath.so FILE` selects a glibc ARM64 shared library in the next session's preload list, reports its SHA-256, and refuses installation until the current session stops. It lasts for one session; the next session stages the bundled library again. See [the profiling workflow](development/proot-performance.md#finding-the-next-fast-path) for timing diff --git a/docs/development/arm64-steam-client.md b/docs/development/arm64-steam-client.md index bb9120017b..9fd6ed8177 100644 --- a/docs/development/arm64-steam-client.md +++ b/docs/development/arm64-steam-client.md @@ -10,7 +10,7 @@ publishes it on the Steam Deck client channels. `droiddeck-steam-install` instal Valve also publishes `steam_client_steamdeck_stable_linuxarm64`. - `droiddeck-steam-install --channel` prints the channel in use. The session passes that value as `-clientbeta` and writes it to `package/beta`. The two must match, or the client loops on rc 42. -- Setting: `BL_STEAM_CHANNEL`, otherwise `~/.config/droiddeck/steam-channel`, set to `beta` or +- Setting: `DD_STEAM_CHANNEL`, otherwise `~/.config/droiddeck/steam-channel`, set to `beta` or `stable`. A set channel never changes on its own. - With no setting, the client falls back to `steamdeck_stable` automatically. It stays on stable (`package/droiddeck-channel`) until a setting says otherwise. The fallback happens: diff --git a/docs/development/low-memory.md b/docs/development/low-memory.md index 770fc80d11..434aa22679 100644 --- a/docs/development/low-memory.md +++ b/docs/development/low-memory.md @@ -1,6 +1,6 @@ # Low-memory reclaim and userspace compression -The Steam session monitor uses the existing `libblsession.so` page-out request to reclaim +The Steam session monitor uses the existing `libddsession.so` page-out request to reclaim private anonymous launcher memory. The default remains a request 20 seconds after game focus, with five minutes between requests. With client compression enabled, low system headroom can also trigger a request while a game is loading, before its first focused window. @@ -20,6 +20,12 @@ retry delay, up to five minutes. After game exit, speculative launcher readback until the session is under any explicit RAM cap, pressure has subsided, and available RAM can cover twice the launcher's swap while leaving the headroom reserve. Normal demand paging continues while readback is deferred; Steam does not have to wait for the monitor to recover. +The same readback runs while the game is still running once the client has been in front of it +for five seconds (a game stuck on a black screen and left through Steam, or a long stay in the +Steam menu), under the same memory checks and only without an explicit RAM cap. Missing or +unreadable focus data never counts as the client in front. Demand paging +alone left the Steam library and menus blank for about half a minute in that case. The +client is compressed again 20 seconds after the game is back in front. Missing memory counters disable automatic pressure reclaim and speculative readback. Missing PSI alone still permits the `MemAvailable` fallback. No root settings, swap sizes, compression algorithms, Android process priorities or game-specific settings are changed. @@ -52,26 +58,29 @@ percentage: Android's `lmkd` killed a session on a 7.5 GiB device with kill. A world load added 1 GiB of GPU memory in about ten seconds, and compressing 1.4 GiB took 2.6 seconds, so the request has to leave room for both. -Performance > Compress idle game memory turns this off (`BL_ZRAM_IDLE=0`); launcher compression +Performance > Compress idle game memory turns this off (`DD_ZRAM_IDLE=0`); launcher compression and the RAM cap are unaffected. The session request runs when real headroom falls below a quarter of RAM (bounded to 768–2560 MiB), or below one and a half times that with at least 1% `some` or `full avg10` memory stall. Real headroom subtracts positive growth in KGSL allocation, `Unevictable`, and -`Shmem` from `MemAvailable`; a rapid fall also qualifies near twice the headroom. The monitor +`Shmem` from `MemAvailable`; a rapid fall also qualifies below twice the headroom or two fifths of RAM, whichever is larger (a 15 GB Thor Max was killed with 5.3 GB still available while memory fell about 400 MB per tick). The monitor may first request page-out of idle Steam and hidden launchers, subject to the Performance setting and client reclaim limits. When both qualify, both requests are sent before waiting for either to complete, so a slow launcher acknowledgement does not delay the game request. Until the client request finishes, its anonymous RSS remains reserved from the session's swap budget. Completion and backoff are measured against the processes that received each request, even if a later scan finds different processes. The session request targets processes that loaded -`libblsession.so`: the game, Wine and its services, and excludes Steam and hidden launchers. +`libddsession.so`: the game, Wine and its services, and excludes Steam and hidden launchers. Requests are at least 30 seconds apart and need the same swap reserve as launcher requests. When the session has read back more than half of what the previous request compressed, that memory is in use: the request is skipped and the wait doubles, -up to five minutes. A request whose memory stayed compressed resets it to 30 seconds. Below half -the headroom the wait is ignored and only the 30-second spacing applies. The state resets when -the game exits. +up to five minutes. A completed request must also raise `MemAvailable` by at least one +sixteenth of the tier headroom, with a 16 MiB minimum; otherwise the same wait doubles because +the pass did not provide meaningful system headroom. A request whose memory stayed compressed or +whose available memory recovers resets the wait to 30 seconds. Below half the headroom the wait +is ignored and only the 30-second spacing applies, so critical pressure can still trigger a +request. The state resets when the game exits. Measured on a Retroid Pocket Duo (7.5 GiB, kernel 6.6, 6 GiB lzo-rle zram plus a 4 GiB swap file) entering the world in World of Warcraft: Forever, one run each: diff --git a/docs/development/mali-venus.md b/docs/development/mali-venus.md index fa72294e42..caf0d2db70 100644 --- a/docs/development/mali-venus.md +++ b/docs/development/mali-venus.md @@ -164,7 +164,7 @@ App (Kotlin/C): - Gives a zero row pitch a packed 64-byte row (gamescope's 1x1 root buffer). - `gpu/GpuInfo.kt`, `FrontEndActivity.kt`, `core/DeviceReport.kt`: wording, plus a "Venus" line in `device.txt`. - `session/SessionFiles.kt`: stages the Mali compatibility layer when the APK carries it. -- `tools/linuxfs/preload/venus.c` (new, part of `libblsession`): unsets `LIBGL_KOPPER_DISABLE` when `VN_DEBUG` has `vtest`. +- `tools/linuxfs/preload/venus.c` (new, part of `libddsession`): unsets `LIBGL_KOPPER_DISABLE` when `VN_DEBUG` has `vtest`. - Steam's `steamwebhelper.sh` sets it unconditionally. - Without kopper and without DRI3, Zink gets no GL context, and the Steam UI crash-loops. - Steam restores that script when it verifies its install, so it cannot be edited. diff --git a/docs/development/proot-performance.md b/docs/development/proot-performance.md index 634b7bc63a..254106016a 100644 --- a/docs/development/proot-performance.md +++ b/docs/development/proot-performance.md @@ -47,7 +47,7 @@ waits; it does not establish a full-install PRoot overhead percentage. ``` SessionService ─HostProcess─▶ libproot.so (ONE tracer process, nice -6 after 2 s) └─ /usr/bin/env -i … droiddeck-session steam - └─ gamescope ─▶ droiddeck-session (BL_INSIDE) ─▶ steamrtarm64/steam (+ steamwebhelper/CEF tree) + └─ gamescope ─▶ droiddeck-session (DD_INSIDE) ─▶ steamrtarm64/steam (+ steamwebhelper/CEF tree) └─ reaper ─▶ droiddeck-game-env ─▶ droiddeck-proton ─▶ Valve ARM64 Proton (python) └─ wine (arm64ec, FEX loaded in-process as a DLL) ─▶ wineserver, game.exe, … ``` @@ -56,7 +56,7 @@ SessionService ─HostProcess─▶ libproot.so (ONE tracer process, nice -6 aft - The options are `--kill-on-exit`, `--kernel-release=…` (kompat, for the hostname), `-i uid:uid` (fake_id0, for Xwayland's `setgid`/`setuid`), and about 25 binds: `/dev`, `/proc`, `/sys`, fake `/proc` and `/sys` files, the GPU node, `/dev/shm`, storage and the game libraries. -- `/etc/ld.so.preload` loads `libblsession.so` (the `tools/linuxfs/preload/*.c` shims) into every +- `/etc/ld.so.preload` loads `libddsession.so` (the `tools/linuxfs/preload/*.c` shims) into every guest process. - The Flatpak sandboxes (`BwrapSpawner`) already run in **separate** proot instances, started from the Android side. @@ -187,9 +187,9 @@ Checked against bionic `android16-release`: |---|---|---| | `rseq`, `set_robust_list` | **blocked** | glibc, at the start of every thread, while all signals are blocked | | `faccessat2` | **blocked** | glibc's `faccessat()`, which tries it on **every** call before falling back, so 2 round trips (`access()` calls the plain `faccessat` syscall directly) | -| `fchmodat2`, `openat2` | **blocked** | newer glibc, Flatpak/libglnx, FEX's rootfs lookups (`libblsession.so` turns `openat2` into `openat`, resolving `RESOLVE_IN_ROOT` paths component by component inside the root) | +| `fchmodat2`, `openat2` | **blocked** | newer glibc, Flatpak/libglnx, FEX's rootfs lookups (`libddsession.so` turns `openat2` into `openat`, resolving `RESOLVE_IN_ROOT` paths component by component inside the root) | | `setuid`, `setgid` and the rest of the family | **blocked** | Xwayland (hence `-i`) | -| `futex_waitv`, `io_uring_*`, `landlock_*` | **blocked** | Proton's fsync (droiddeck-fsync answers `futex_waitv` in `libblsession.so`), some engines | +| `futex_waitv`, `io_uring_*`, `landlock_*` | **blocked** | Proton's fsync (droiddeck-fsync answers `futex_waitv` in `libddsession.so`), some engines | | `clone3` | blocked before Android 15 | glibc `pthread_create` | | `close_range` | blocked on Android 12 | | | `statx`, `process_vm_readv`/`writev`, `memfd_create`, `pidfd_*`, `seccomp` | allowed | | @@ -300,7 +300,7 @@ it needs `patches/0014`, enabled with `PROOT_FASTPATH=1`. library file itself at the fixed address instead, as proot's loader does for every program. - Nothing claims `0xffff00000` first. - The stub's syscalls pass Android's filter. They should: all are allowed. -- **Integrate into `libblsession.so`** rather than a second preload. `opens.c` and `pathcache.c` +- **Integrate into `libddsession.so`** rather than a second preload. `opens.c` and `pathcache.c` already define `open` and `access`, so their "real" call should become the fast path. That also removes the second library's load cost, about 0.2–0.4 ms per exec that is still unexplained (see the exec row above). @@ -375,19 +375,19 @@ Build a **glibc ARM64** library using the same toolchain as the shipped fast pat docker run --rm --platform linux/amd64 --user "$(id -u):$(id -g)" \ -v "$PWD:/src" -w /src droiddeck-local-cross:24.04-v3 \ aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ - -o /src/libblfastpath.so tools/proot/fastpath/fastpath.c -ldl + -o /src/libddfastpath.so tools/proot/fastpath/fastpath.c -ldl tools/droiddeckctl stop -tools/droiddeckctl override libblfastpath.so ./libblfastpath.so +tools/droiddeckctl override libddfastpath.so ./libddfastpath.so tools/droiddeckctl proot-profile enable tools/droiddeckctl start steam --wait ``` -The existing override bridge now recognizes `libblfastpath.so`: it checks ELF class, endianness, +The existing override bridge now recognizes `libddfastpath.so`: it checks ELF class, endianness, type, and machine, reports SHA-256, and selects that file in `/etc/ld.so.preload` for one session. It rejects installation while a session is active. This is an architecture check, not validation of libc compatibility or the library's behavior. The fast path still requires its normal enabled -setting and the patched PRoot pack. Its basename stays `libblfastpath.so`, so `libblsession`'s FEX +setting and the patched PRoot pack. Its basename stays `libddfastpath.so`, so `libddsession`'s FEX routing finds it. Guest-command restaging retains the active selection. After stopping, the next session stages the bundled preload again; `env clear all` cancels queued overrides. diff --git a/docs/development/proroot-analysis.md b/docs/development/proroot-analysis.md index 7d4139c35a..8136f96e20 100644 --- a/docs/development/proroot-analysis.md +++ b/docs/development/proroot-analysis.md @@ -63,7 +63,7 @@ handles the same constraint with `libproot-loader.so`. ## Compared with DroidDeck -| | DroidDeck (proot + 0001–0018 + `libblfastpath.so`) | proroot | +| | DroidDeck (proot + 0001–0018 + `libddfastpath.so`) | proroot | |---|---|---| | exec, `PT_INTERP`, `/proc/self/exe` | proot's loader under ptrace, 0.4–0.8 ms per exec | Its own loaders, with no tracer; also needs its own ld.so with a glibc offset table | | path calls through libc wrappers | fast path, about 0.6–1.9 µs | runtime hooks | @@ -82,7 +82,7 @@ DroidDeck is as a fast path *in front of* proot. ## What is worth taking -1. **Patch glibc's svc sites from `libblfastpath.so`'s constructor.** This is the largest gain +1. **Patch glibc's svc sites from `libddfastpath.so`'s constructor.** This is the largest gain and the cheapest way to do option 6 in [proot-performance](proot-performance.md) ("a proot-aware glibc") without rebuilding glibc. - For `libc.so.6` (and `ld-linux-aarch64.so.1` for runtime `dlopen`), rewrite each `svc #0` @@ -136,7 +136,7 @@ netlink and SysV shm (`netif.c` and `sysv.c` already cover these); and the long- `tools/proot/fastpath/svc-patch.h`, included by `fastpath.c`, implements the first slice of item 1. It runs automatically in fresh processes using the replacement -`libblfastpath.so` when the ordinary fast-path configuration and tracer-key check +`libddfastpath.so` when the ordinary fast-path configuration and tracer-key check succeed. Set `PROOT_FP_PATCH_SVC=0` to disable it for troubleshooting or comparisons; `PROOT_FP_PATCH_SVC=1` also explicitly enables it. It skips processes that already have multiple threads, and declines SVE/SME hardware because the relay preserves the base ARM64 register state. diff --git a/docs/development/steam-display-scaling.md b/docs/development/steam-display-scaling.md index 496995ad05..a5c5a674f0 100644 --- a/docs/development/steam-display-scaling.md +++ b/docs/development/steam-display-scaling.md @@ -13,7 +13,7 @@ very high-resolution panels and on foldables? ## How the session is sized today (main @ c636eea3) - `droiddeck-session` starts gamescope with `-W/-H` (output) = `-w/-h` (nested, what games and the - client see) = `BL_WIDTH x BL_HEIGHT`, the per-mode "Resolution" setting. The default is + client see) = `DD_WIDTH x DD_HEIGHT`, the per-mode "Resolution" setting. The default is `1280x720` (`SessionDisplay.DEFAULT_RESOLUTION`). One Xwayland server holds both the Steam client and the games. - The Android compositor (`waylandcomp`) draws gamescope's output into a panel-sized swapchain @@ -68,7 +68,7 @@ fullscreen off, with a spike build of `feat/steam-native-output`. Each run sets Steam UI idle: GPU 0%, gamescope 27 dma-bufs, Xwayland 39. Everything renders at 1920x1080. -### Run 2: client height cap (`BL_STEAM_MAX_HEIGHT=720`) +### Run 2: client height cap (`DD_STEAM_MAX_HEIGHT=720`) - Log: `== steam: the client's height capped at 720 (was unset)`. The client never wrote its own value during the run, so a one-time set would hold. @@ -173,15 +173,15 @@ restored): the session starts at `size=1280x720` and the device report shows `72 ### How runs 2 to 6 were driven -Two temporary session-script hooks, not kept on this branch: `BL_STEAM_MAX_HEIGHT=N` wrote -`GAMESCOPE_STEAM_MAX_HEIGHT` on the root window, and `BL_GAME_XWAYLAND_MODE=WxH` wrote +Two temporary session-script hooks, not kept on this branch: `DD_STEAM_MAX_HEIGHT=N` wrote +`GAMESCOPE_STEAM_MAX_HEIGHT` on the root window, and `DD_GAME_XWAYLAND_MODE=WxH` wrote `GAMESCOPE_XWAYLAND_MODE_CONTROL = 1,W,H,0` five seconds after `GAMESCOPE_FOCUSED_APP` showed a game. `--xwayland-count 2` and `STEAM_MULTIPLE_XWAYLANDS=1` went through `Download/droiddeck-env`. ## Two Xwayland servers by default (`feat/steam-dual-xwayland`) Steam sessions now start gamescope with `--xwayland-count 2` and `STEAM_MULTIPLE_XWAYLANDS=1`. -`BL_XWAYLAND_COUNT=1` in `Android/data/com.droiddeck.launcher/files/droiddeck-env` goes back to one. The session script's +`DD_XWAYLAND_COUNT=1` in `Android/data/com.droiddeck.launcher/files/droiddeck-env` goes back to one. The session script's root-window requests that are meant for the game (the drawer's live Force fullscreen, `GAMESCOPE_FORCE_WINDOWS_FULLSCREEN`, and the resume watcher's `GAMESCOPE_RESTORE_FOCUS_WINDOW`) go to both displays, `$DISPLAY` and `STEAM_GAME_DISPLAY_0`. gamescope reads both per server, so @@ -221,8 +221,8 @@ With games on their own Xwayland server, FlatOut 2 no longer shrinks under the Q reason "Force game windows fullscreen" existed. What it still did was make any game whose Game Resolution differs from what it draws fight it (runs 4 and 5). The switch is gone from Steam settings (Games) and the session drawer (Display), along with its preference, the -`BL_GAMESCOPE_FORCE_FULLSCREEN` flag, the `~/.droiddeck-fill` live watcher and the device report -line. `BL_GAMESCOPE_ARGS=--force-windows-fullscreen` in `Android/data/com.droiddeck.launcher/files/droiddeck-env` still passes the +`DD_GAMESCOPE_FORCE_FULLSCREEN` flag, the `~/.droiddeck-fill` live watcher and the device report +line. `DD_GAMESCOPE_ARGS=--force-windows-fullscreen` in `Android/data/com.droiddeck.launcher/files/droiddeck-env` still passes the flag for an experiment. Device check (Thor): Alan Wake's American Nightmare with its 1280x720 Game Resolution runs on `:1` diff --git a/docs/development/steam-game-imports.md b/docs/development/steam-game-imports.md index 2e4a0cc3e7..52d69934fc 100644 --- a/docs/development/steam-game-imports.md +++ b/docs/development/steam-game-imports.md @@ -64,6 +64,17 @@ inherit those routes. Managed shortcuts are replaced; user-created shortcuts and unreadable shortcut files are preserved. Both routes use the existing ARM64 Proton registration. +## Adopting shared library folders + +At every session start, `droiddeck-steam-library` looks through `steamapps/common` of each +added library for non-empty folders no manifest names. A folder whose name is the +`config.installdir` of exactly one playable app in `appcache/appinfo.vdf` (the `game` +type wins over a demo; tools, DLC and ambiguous names are skipped) gets an +`appmanifest_.acf` with `Universe=1`, `StateFlags=4` and no build, so Steam verifies +the existing files and downloads only what differs. Existing manifests are never +rewritten, an app installed in another library is skipped, and only the added library is +written to. Ownership is not read before the client runs; Steam enforces the license. + ## Launcher artwork The installed Steam game scan lists each game's `appcache/librarycache/` diff --git a/docs/development/steam-touch-controls.md b/docs/development/steam-touch-controls.md index 9cb6bc1bbd..72cea31ce3 100644 --- a/docs/development/steam-touch-controls.md +++ b/docs/development/steam-touch-controls.md @@ -38,7 +38,7 @@ SteamTouchConfig (Steam's configs) ←─── output reports ←── Ste - **Plugging.** The device is plugged in only while Steam's controls are shown: always in a Steam session with that choice, since a handheld's built-in pad would keep Auto off for good. Unplugging ends the device's report stream (the client lets the controller go); either way libfakeinput - sends a udev event through `udevmon.c`'s stand-in monitor (`bl_udevmon_inject`), since the + sends a udev event through `udevmon.c`'s stand-in monitor (`dd_udevmon_inject`), since the sandbox gives the client no kernel uevents and its HID discovery would never look again. ## Layouts diff --git a/docs/development/stores.md b/docs/development/stores.md index e8ff8fcbd0..9776ac8c4c 100644 --- a/docs/development/stores.md +++ b/docs/development/stores.md @@ -270,7 +270,7 @@ A game's web links reach Android: `droiddeck-store-launch` sets the prefix's `HKCU\Software\Wine\WineBrowser` `Browsers` to `/usr/local/bin/droiddeck-open-url`, which is also `xdg-open` first on the game's PATH, and hands http(s) addresses to the app, which opens them in Android's browser. EOS uses this when a sign-in needs a one-time step ("corrective action"): it -falls back to a browser, the user approves on the phone, and the game signs in. `BL_DEBUG_BROWSER=1` +falls back to a browser, the user approves on the phone, and the game signs in. `DD_DEBUG_BROWSER=1` in droiddeck-env adds `WINEDEBUG=+shell,+winebrowser`. Epic's EOS overlay is not provisioned (with it games exited while loading); an `OverlayPath` an earlier build wrote is removed at launch. The parked overlay work is on the branch `park/epic-eos-overlay`. diff --git a/docs/development/thor-sd-storage-investigation.md b/docs/development/thor-sd-storage-investigation.md index e2cee625a5..e4315616eb 100644 --- a/docs/development/thor-sd-storage-investigation.md +++ b/docs/development/thor-sd-storage-investigation.md @@ -426,7 +426,7 @@ path. still fall back. Same workloads on the Thor, stock library against the new one (session started with -`droiddeckctl override libblfastpath.so`, PRoot profiler on): +`droiddeckctl override libddfastpath.so`, PRoot profiler on): | Workload | Stock | New | |---|---|---| diff --git a/docs/development/x86-64-steam-client.md b/docs/development/x86-64-steam-client.md index cf25613687..7679a0a6c8 100644 --- a/docs/development/x86-64-steam-client.md +++ b/docs/development/x86-64-steam-client.md @@ -2,7 +2,7 @@ Valve's x86-64 Linux Steam client, run unchanged under FEX beside the default arm64 client. It is opt-in: Steam settings, **Steam client: x86-64** (`steamClientArch`, passed to the -session as `BL_STEAM_CLIENT_ARCH=x86_64`, applies from the next session), or the desktop menu entry +session as `DD_STEAM_CLIENT_ARCH=x86_64`, applies from the next session), or the desktop menu entry **Steam x86-64 (FEX, experimental)**. The Library lists the active client's games and tags its header "x86-64" while that client's list is shown. This page records why each workaround exists and what was seen on devices. The timeline is in `docs/progress-log.md`. @@ -11,7 +11,7 @@ on devices. The timeline is in `docs/progress-log.md`. VAC-secured servers ("Connection Blocked ... VAC secured server") and no client log mentions VAC. VAC modules are x86 code. Under FEX the x86-64 client has a module it can run, as SteamLite does in Wine. -**Layout.** Everything lives in its own home, `$X64_HOME` (`BL_X64_HOME`, default `~/.droiddeck-x64`): +**Layout.** Everything lives in its own home, `$X64_HOME` (`DD_X64_HOME`, default `~/.droiddeck-x64`): its own `~/.steam` links, config, libraries, x86 rootfs and log (`steam-x64.log`). Shared with the arm64 client: the sign-in, and its `config/uioverrides` (Steam's startup movie overrides), which the x86 client links. One client runs at a time, since both use the same account; the standalone launcher shuts the @@ -76,7 +76,7 @@ arm64 client down first. - **Tracer.** proot is a tracer, so tier0 believes a debugger is attached and breaks into it with int3 on the first failed assertion: the web helper died of SIGTRAP a second after every start. `preload/tracer.c` exempts web helpers on purpose (Chromium traps on a status fd that is not - procfs); with `BL_WEBHELPER_HIDE_TRACER=1` only opens called from `libtier0_s.so` get the copy + procfs); with `DD_WEBHELPER_HIDE_TRACER=1` only opens called from `libtier0_s.so` get the copy without the tracer. - **FEXServer owns the rootfs.** A FEX process takes its rootfs from FEXServer, and a server started earlier without `FEX_ROOTFS` (any FEX run in the guest) serves none: every x86 library lookup fell @@ -86,7 +86,7 @@ arm64 client down first. never got a browser up. FEX looks in the rootfs first, so an empty `rootfs/dev/dri` hides the node. - **Scout runtime.** Valve ships it as `ubuntu12_32/steam-runtime.tar.xz` and `steam.sh` unpacks it. Since `steam.sh` is not used, `--prepare` unpacks it when its checksum changes. -- **Repair.** Repair Steam (`BL_X64_REPAIR=1`), or two starts in a row that never showed the client +- **Repair.** Repair Steam (`DD_X64_REPAIR=1`), or two starts in a row that never showed the client (`package/droiddeck-unconfirmed`; the app clears the count once the client is on screen), removes the install stamp so the client is reinstalled. Counts from before this was tracked are dropped rather than taken as failed starts. `droiddeck-steam-install` removes the repair request when it is @@ -100,10 +100,10 @@ arm64 client down first. - **FEX settings.** The app's PERFORMANCE_TSO preset (`core/FexPreset.kt`, WinNative's default). FEX's own defaults keep half-barrier TSO and full-precision x87, which cost every x86 program time. Values already in the environment win. -- **Fast path.** libblfastpath, preloaded into every guest process and so into FEX, broke FEX's 32-bit +- **Fast path.** libddfastpath, preloaded into every guest process and so into FEX, broke FEX's 32-bit mode (SIGILL at start). It stands down when FEX is about to run a 32-bit program; 64-bit programs - keep it. `BL_X64_FP_OFF=1` turns it off for everything. -- **Diagnostics.** `BL_FEX` runs another FEX build (a `DEBUG_STRACE` one, say). `BL_FEXSERVER_LOG` + keep it. `DD_X64_FP_OFF=1` turns it off for everything. +- **Diagnostics.** `DD_FEX` runs another FEX build (a `DEBUG_STRACE` one, say). `DD_FEXSERVER_LOG` starts a FEXServer in the foreground logging there; every FEX process that logs to "server" (`FEX_OUTPUTLOG` or an AppConfig) then has its lines tagged with its pid (file logs overwrite each other). @@ -113,18 +113,18 @@ arm64 client down first. The client's web helper draws its whole UI. There are two: - **The arm64 client's helper** (`droiddeck-x64-arm-webhelper`), used when both clients are the same - Steam build (unless `BL_X64_X86_WEBHELPER=1`). FEX hands the arm64 program to the CPU, so it runs + Steam build (unless `DD_X64_X86_WEBHELPER=1`). FEX hands the arm64 program to the CPU, so it runs natively with the session's preloads (KGSL poll fix, fast path) and the arm64 session's GPU settings. It talks to the client over IPC, and a helper of another build never comes up: the client restarted it every 10 s (device: 1790721607 against 1790904859). The session therefore updates the arm64 client's parts on the same channel first (`droiddeck-steam-install --sync steamdeck_publicbeta`). With this helper the client itself gets the GPU: it shows every Big Picture frame the helper draws, and in software (llvmpipe under FEX) that held the UI at about 20 fps - (`BL_X64_CLIENT_SOFTWARE=1` keeps it in software). Device: 144 fps menus. + (`DD_X64_CLIENT_SOFTWARE=1` keeps it in software). Device: 144 fps menus. - **The client's own x86 helper on the GPU** (`droiddeck-x64-webhelper`), otherwise: ANGLE's GL backend through FEX's GL thunk to zink and Turnip. On ANGLE's Vulkan backend the x86 compositor thread was the bottleneck (16 fps against 60). Never `--in-process-gpu`, the preload's default: a - GPU crash there took the whole helper down (102 restarts). `BL_X64_CEF_GPU=0` keeps it in software. + GPU crash there took the whole helper down (102 restarts). `DD_X64_CEF_GPU=0` keeps it in software. Its GPU process loads libpci, which exits when `/sys/bus/pci/devices` lists a device whose files the app may not read (a RedMagic's PCIe root ports): every GPU process exited with status 1 in about 50 ms, software ones too, until Chromium gave up ("GPU process isn't usable") and the menus stayed @@ -132,7 +132,7 @@ The client's web helper draws its whole UI. There are two: 0 GPU process exits, ANGLE on zink and Turnip. The session shim (`preload/net.c`) turns `steamrt64/steamwebhelper.sh`'s exec of `./steamwebhelper` -into `BL_X64_ARM_WEBHELPER`. Nothing in the client's folder is edited: the client checksums its files +into `DD_X64_ARM_WEBHELPER`. Nothing in the client's folder is edited: the client checksums its files as it starts and reinstalled itself over an edited launcher (2-3 minutes) on every start. Quick Access Menu and flicker, x86 helper: @@ -149,7 +149,7 @@ Quick Access Menu and flicker, x86 helper: `LIBGL_KOPPER_DISABLE=true` none did in 60 opens, at 60 fps instead of about 140 (Xwayland's per-window timing for child windows). No flashes was chosen over frame rate. -Software path (no host thunks, or `BL_X64_SOFTWARE=1`): x86 Mesa has no driver for this GPU, so +Software path (no host thunks, or `DD_X64_SOFTWARE=1`): x86 Mesa has no driver for this GPU, so llvmpipe for GL (the client's own window needs GLX) and the rootfs's own Vulkan ICDs (lavapipe). GLX first failed because the desktop exports zink over the arm64 Turnip ICD; those variables are cleared. `LIBGL_DRI3_DISABLE=1`: over DRI3 the X server hands out the GPU node and Mesa's software path then @@ -187,7 +187,7 @@ alone would then read as an installed client. 0008). FEX opened every rootfs path with `openat2(RESOLVE_IN_ROOT)` and fell through to the arm64 guest on anything but EXDEV; x86 bash could not find libtinfo. Since r4 the fallback resolves the path inside the rootfs itself (absolute symlinks restart at the rootfs, as `RESOLVE_IN_ROOT` does); - before, they resolved against the arm64 guest. `libblsession.so` (`preload/robust.c`) answers + before, they resolved against the arm64 guest. `libddsession.so` (`preload/robust.c`) answers `openat2` first in practice and does the same walk for `RESOLVE_IN_ROOT` callers, so Valve's FEX-Emu on the arm64 client gets it too. Each path component is then its own system call. - `0002-thunkgen-newer-clang`: the container's newer clang has no `FileManager::clearStatCache()`, @@ -214,7 +214,7 @@ alone would then read as an installed client. - **Where the app gets it.** The app downloads FEX from Droid-Deck/DroidDeck-Components, where nothing is uploaded by hand. The app follows its `fex.json`: it reads it from Components' `main` (directly, at most every ten minutes) and keeps the last copy, and every session passes - that build to `droiddeck-fex-update` (`BL_FEX_TAG`, `BL_FEX_SHA256`, `BL_FEX_URLS` with the download + that build to `droiddeck-fex-update` (`DD_FEX_TAG`, `DD_FEX_SHA256`, `DD_FEX_URLS` with the download source's mirrors). The script installs a build only after its archive matches the sha256 and every program in it loads (`ld-linux --list`); the files it replaces are kept aside until the installed copy loads too and put back otherwise, and the tag is written last. Otherwise it keeps the installed one while that still loads, @@ -246,7 +246,7 @@ alone would then read as an installed client. - **Mapping** (`x64_map_direct`): every game the client's appinfo cache shows with a Linux build (type game, oslist with linux; runtime from `config/app_mappings`: SteamLinuxRuntime_sniper or _soldier, none means scout), installed or not, so Steam downloads the Linux depots. A title on a tool chosen in - Properties keeps it, except `BL_X64_DIRECT_APPS` (Left 4 Dead 2, 550, by default), which is always + Properties keeps it, except `DD_X64_DIRECT_APPS` (Left 4 Dead 2, 550, by default), which is always taken back. `direct-auto.json` lists what was mapped. One pass over the mapping: a 2000-title fixture went from 16.5 s to 0.2 s with the same output. - A game whose Windows build is installed (it ran on a Proton before) stays a Windows game on the @@ -270,7 +270,7 @@ alone would then read as an installed client. in its container. - **GPU.** Games get FEX's host thunks and the session's GPU settings (Turnip, Zink), saved by the launcher as `game-gpu.env` and rewritten whenever it runs; `game-gpu.local` is the user's, never - rewritten, and is read after it. `BL_X64_GAME_SOFTWARE=1` keeps a game in software, with + rewritten, and is read after it. `DD_X64_GAME_SOFTWARE=1` keeps a game in software, with `mesa_glthread=false` (GL threading is no help with software GL under FEX). - Source games (`hl2.sh`, `hl2_linux`, `srcds`) get `-condebug` for the VAC diagnostics. - **Controllers.** `libfakeinput` is built for x86-64 and preloaded in the rootfs; Big Picture works @@ -316,7 +316,7 @@ alone would then read as an installed client. written only while no client runs. Shader pre-caching stays each client's own: the x86 client may fetch a shared game's shader cache into its own folder (Valheim, 1.8 GB). - **SD card.** The x86 client's card library is a folder inside the arm64 one (`/mnt/droiddeck-sd/x86-64`, - `GameStorage.X64_CARD_DIR`, passed as `BL_X64_STEAM_LIBRARIES`), so the install dialog offers Internal + `GameStorage.X64_CARD_DIR`, passed as `DD_X64_STEAM_LIBRARIES`), so the install dialog offers Internal Storage and SD card. compatdata, shadercache and runtime tools stay private, as in the arm64 card library. FEX runs x86 programs from the noexec exFAT card. The folder appears with the client's first session on the card and its `steamapps` with the first library write. Desktop sessions prepare it as @@ -378,7 +378,7 @@ alone would then read as an installed client. it. It keeps the game display Steam chose: the saved `DISPLAY=:0` hid the game window and made DiRT Showdown exit after about 7 s. Proton takes its Steam client parts from the client's install folder, and the x86 client's are x86, so `STEAM_COMPAT_CLIENT_INSTALL_PATH` points at the arm64 root - and `BL_X64_STEAM_ROOT` keeps the x86 one for install-script lookups. + and `DD_X64_STEAM_ROOT` keeps the x86 one for install-script lookups. - **Game overlay.** The x86 client preloads its own x86 overlay; the arm64 one takes its place. The overlay marks the game's windows with the Steam app ID, and without it gamescope never shows them (FlatOut ran and played sound behind Steam's launch screen, "steam app id: 0"). The agent also tags @@ -425,7 +425,7 @@ alone would then read as an installed client. to secure servers."). That console reaches a file only with `-condebug`: `//console.log`, or `/game//console.log` for Source 2. At session start the app writes `~/.droiddeck-vac-diagnostics` (start time, client, each console.log's length, since `-condebug` - appends). The launch wrapper (`bl_vacdiag`) then adds `-condebug` to Source titles (found by + appends). The launch wrapper (`dd_vacdiag`) then adds `-condebug` to Source titles (found by `gameinfo.txt` or `gameinfo.gi`), flags `-insecure` in launch options and notes each launch. At the end the session copies what each console.log gained into `vac/`, scrubbed, and writes `vac.txt`: the game's secure/insecure lines, VAC lines in the client's logs, and which client files are present. A @@ -440,7 +440,7 @@ alone would then read as an installed client. ## Session integration, restarts and mapping -- With `BL_STEAM_CLIENT_ARCH=x86_64`, `droiddeck-session` updates the arm64 client's parts +- With `DD_STEAM_CLIENT_ARCH=x86_64`, `droiddeck-session` updates the arm64 client's parts (`droiddeck-steam-install`, then `--sync steamdeck_publicbeta`), runs `droiddeck-steam-x64 --prepare` and starts the client with `droiddeck-steam-x64 --exec`. Steps only for the arm64 client (library registration, the ARM64 Proton fetch, the live compat helper) are skipped; added games, @@ -450,7 +450,7 @@ alone would then read as an installed client. failed at ../src/pulse/operation.c:136 pa_operation_get_state()", the runtime's PulseAudio 13). `preload/pulseguard.c` (x86 builds only; the arm64 client does not hit it) answers a missing operation as cancelled and ignores its unref and cancel. The session passes `-steamdeck -steamos3` unless - `BL_X64_DECK=0`. Switch to Desktop is expected to need no change (an x86 shell under FEX runs + `DD_X64_DECK=0`. Switch to Desktop is expected to need no change (an x86 shell under FEX runs `steamos-session-select`); the full switch has not been tested on a device. - **Process names.** Under FEX a process's argv[0] is FEX and the program is its first argument. The session's game detection, CPU pinning and the zRAM watcher read that argument. Steam pins itself and @@ -459,13 +459,13 @@ alone would then read as an installed client. `steam-compatibility --x64 --live` and `droiddeck-steam-x64 --map-direct --live`, every 15 s and only in the session's first hour (720 beats of 5 s). A title installed after that is mapped when the client exits and takes effect from the next session. Steam reads a - mapping changed while it runs only at its next start, so changed titles go to `.bl-compat-pending`. + mapping changed while it runs only at its next start, so changed titles go to `.dd-compat-pending`. Once they have installed (`StateFlags` 4 in the client's root or its card folder) and no game runs, the client is restarted once per title, at most 3 times a session. - **After exit.** Added games, `steam-compatibility --x64` and `--map-direct` run again: the client wrote its mapping from memory as it exited, over what the live passes set. - The Lossless Scaling ownership probe and the Steam import watcher reach the x86 client through the - arm64 client's `steamclient.so` (`BL_STEAMCLIENT`); the watcher restarts the client with + arm64 client's `steamclient.so` (`DD_STEAMCLIENT`); the watcher restarts the client with `droiddeck-steam-x64 --exec -shutdown`. - Steam logs and the Steam language come from the x86 client's home. On the desktop, `steam` and `steamdeck-steam` start the selected client, and the desktop game entries list its libraries. diff --git a/docs/development/xbox-store.md b/docs/development/xbox-store.md index bc4aecf661..7133e5c078 100644 --- a/docs/development/xbox-store.md +++ b/docs/development/xbox-store.md @@ -1,7 +1,8 @@ # Xbox / PC Game Pass on Thor -This integrates PC Microsoft Store MSIXVC packages, -not Xbox console emulation or UWP/APPX packages. +This integrates PC Microsoft Store packages, both streamed MSIXVC packages and the legacy +EAppx containers older desktop titles still ship as. It is not Xbox console emulation and +does not run UWP titles in a packaged-app host. ## Testing on Thor @@ -69,14 +70,96 @@ not Xbox console emulation or UWP/APPX packages. cleanup must preserve installed game files reached through view symlinks. 10. Sign out from Xbox. Installed files should remain, account library data should clear, and Play/download licensing should require sign-in again. +11. Install a legacy title that ships an EAppx bundle, such as Forza Horizon 4 + (`9PNQKHFLD2WQ`). The download shows as a percentage rather than a streamed + install, Stop kills it rather than pausing, and a finished install registers + the executable named by `AppxManifest.xml`. Expect tens of gigabytes: check + free space first, since the preflight needs the download plus two copies of + the largest container. Do not uninstall DroidDeck or clear application data to troubleshoot this build. The signed APK is installed in place to retain existing Steam and store data. +## Legacy EAppx packages + +A title that predates MSIXVC ships as an EAppx bundle: an archive of Appx packages, encrypted, +with an `AppxManifest.xml` per package instead of `MicrosoftGame.config`. `streaming` rejects the +format, so the installer reads the format the catalogue recorded and runs `xodus-cli +legacy-install` instead. `MSIXVC`, `EAPPX` and `EAPPXBUNDLE` are the only formats listed for a +`Windows.Desktop` package; the format is carried into the install record so a later update or +resume dispatches the same way. + +The verb resolves, licenses, downloads, extracts, then hoists the manifest to the game root: + +- **Resolution.** The Xbox content service is asked first. Some legacy bundles it answers with no + files at all; Windows Update (`fe3cr.delivery.mp.microsoft.com`, SOAP `GetCookie`, + `SyncUpdates`, `GetExtendedUpdateInfo2`) is asked next through the title's `WuCategoryId` and + returns the full bundle with a time-signed CDN URL. That endpoint is a public Windows Update + service and needs no Xbox credential, but it presents a certificate chained to Microsoft's ECC + Product Root CA 2018, which Android's CA bundle does not carry, so `wu-root.pem` is pinned for + those requests only. A WU result is reduced to its `.eappx`/`.eappxbundle` files: the plain + `.appx` framework packages delivered beside it (VCLibs) and the differential `.cab` metadata are + not containers this path can unpack. +- **Licensing.** The existing `license` verb runs before the first byte is fetched and must return + content keys; no keys means no install. +- **Space.** Free space is checked up front against the download plus two copies of the largest + container, because a bundle is expanded in place. Each container is removed as soon as it is + unpacked, so the peak is the archive plus its contents rather than both plus the earlier + archives. A container a stopped attempt finished is counted as reclaimable, since the retry + truncates it before writing. +- **Pause and resume.** A legacy download has no control channel: Stop kills the downloader, and + the next attempt starts an unfinished container again from byte zero, while a container that + completed is kept and reused. Nothing is checkpointed inside a container. +- **Frameworks.** An installed package gets its `PackageDependency` frameworks from the package + graph; an unpacked folder has none, so the loader fails with `0xc0000135` on + `VCRUNTIME140_APP.dll` and friends. The verb fetches each declared framework from its Windows + Update category and copies its libraries beside the title, which is where the loader looks. A + category lists one package per architecture under identifier-only names, so each is unpacked + until one declares `ProcessorArchitecture="x64"`; taking the first one puts 32-bit DLLs into a + 64-bit folder and every load fails with `0xc000007b`. Only the libraries that copy put there + are withdrawn when a framework is replaced, so a title's own DLL of the same name survives. +- **Updates.** Installing over a folder that already holds a manifest lifts the new package over + the old files; on a first install an existing target is an error rather than a merge. +- **Failure detail.** A release build hides logcat from adb, so a failed install writes the + backend's stderr tail to `files/xbox-install.log` beside the app and repeats the last lines in + the failure message. + ## Evidence and limits Verified during development: +- The catalogue lists a legacy title beside the MSIXVC ones, and its detail page + offers Install with the recorded format. +- Resolution of a real legacy PC bundle on Thor without any Xbox token: Forza + Horizon 4 (`9PNQKHFLD2WQ`) through Windows Update as + `Microsoft.SunriseBaseGame_2023.1122.1704.2_neutral_~_8wekyb3d8bbwe.eappxbundle`, + 85,219,173,025 bytes, with a signed CDN URL. The Xbox content service returns + no files for that product, which is why the WU route exists. +- `AppxManifest.xml` identity and executable extraction, and its rejection rules, + are unit-tested against a manifest of that shape. +- An install of that bundle completed on Thor. The 85,219,173,025-byte container + produced 79.3 GB at the game root with `AppxManifest.xml` and the package DLLs + directly beneath it, which the launcher reports as installed. +- Unpacking that bundle ran at about 40 MB/s on one thread and about 200 MB/s + across four, measured as growth of the destination folder. The container is + deleted once its members are on disk, so the peak footprint is one package at + a time rather than the archive plus everything under it. The install bubble + advances through this stage: each file's declared length is counted as it is + written, and a bundle member is one file, so the folder's growth covers it. +- A launch of this title through Xodus/ARM64 Proton reaches the loader with every declared + framework in place, then fails inside Wine: its manifest names `EntryPoint="Forza.App"`, a UWP + application that expects the app model to activate a view, which Wine has no host for. The + Play action reads that entry point from `AppxManifest.xml` and refuses the launch with a + message, and a launch that does reach the runtime reports `uwp-entry-point` rather than dying + silently. A package naming `Windows.FullTrustApplication` starts as an ordinary Win32 + executable instead. +- Activation itself is not the missing piece. A DLL registered under + `HKLM\Software\Microsoft\WindowsRuntime\ActivatableClassId\Windows.ApplicationModel.Core.CoreApplication` + is loaded by `combase.dll`, and its `DllGetActivationFactory` is called for that class. Such a + title still stops earlier: `GetCurrentPackageFullName` and `GetCurrentPackageFamilyName` are + Wine stubs, so a package has no identity, and an activation factory alone cannot supply the + `IFrameworkViewSource`/`CoreWindow` host the view asks for. + - Native AArch64 CLI execution on Thor's existing Linux runtime. - Abstract-socket credential transport with a synthetic account on Thor; this does not establish a real Microsoft sign-in. diff --git a/docs/progress-log.md b/docs/progress-log.md index 30b558b86b..462affde2a 100644 --- a/docs/progress-log.md +++ b/docs/progress-log.md @@ -58,7 +58,7 @@ the timeline, then lessons and backlog. Companion to the README (what the app *d `mirror-release.yml`, checked against a new `fex.json` catalog there (Components PR #2), and `droiddeck-steam-x64` downloads it from there instead of The412Banner/DroidDeck. - **FEX fex-2610-r4** (PR #71 review): without openat2 (proot) FEX opened rootfs paths with absolute - symlinks resolved against the arm64 guest, and `libblsession.so` converted every openat2 the same way + symlinks resolved against the arm64 guest, and `libddsession.so` converted every openat2 the same way before FEX saw ENOSYS. `preload/robust.c` now resolves `RESOLVE_IN_ROOT` paths component by component inside the root (59 cases; 100,000-path differential fuzz; new `test_openat2_preload.py`), and patch 0001 does the same in FEX. Patch 0003 marks only the host mappings that overlap a failed MAP_32BIT @@ -313,7 +313,7 @@ stay as they were (`afa479ee`). - **Merged main (94 commits).** Main dropped the Steam channel and Deck-mode settings (#546): only the client choice (`steamClientArch`), `activeSteamRoot` and VAC diagnostics remain. Main's web-helper - arguments (#566, `bl_webhelper_argv`) are composed with the x86 client's arm64 web-helper redirect in + arguments (#566, `dd_webhelper_argv`) are composed with the x86 client's arm64 web-helper redirect in `preload/net.c`. Main's single background loop (#575) now carries the x86 hooks: the client's own compat pass (`--x64 --live`), `steamrt64` in the pinning and stale-tmp patterns, Lossless probe off for x86, and the once-per-title restart after a new mapping. The text-strings merge had dropped three of @@ -483,7 +483,7 @@ cache is saved as the round goes, so a sync the user closes the app on still lea paths (`SessionPrefs.gameFolderBinds`), so the listing and every Steam shortcut are unchanged; `addedGamesDirs` is cleared. Log: `games: migrated → N games`. - **Libraries:** `GameStorage.gamesFolderLibraries` returns only a Games folder Steam installed - into (an appmanifest in its `steamapps/`); the others drop out of `BL_STEAM_LIBRARIES` and the + into (an appmanifest in its `steamapps/`); the others drop out of `DD_STEAM_LIBRARIES` and the runtime's `droiddeck-steam-library` forgets the `/root/Games/...` entries it had registered. The user's two folders have `steamapps/` without manifests (checked on the device), so both go. - **Tests:** `GamesFolderMigrationTest` (exe / appid / name / removal kept, guest paths unchanged, @@ -510,7 +510,7 @@ What it took, in order (each step was the next failure on device): could not find libtinfo. `tools/fex/patches/0001-openat2-enosys-fallback.patch`. - **FEXServer owns the rootfs** - a server started before `FEX_ROOTFS` (any earlier FEX run) answers every client with no rootfs. The launcher stops it first. -- **32-bit x86 died with SIGILL** - libblfastpath (the proot fast path, preloaded into every guest +- **32-bit x86 died with SIGILL** - libddfastpath (the proot fast path, preloaded into every guest process, FEX itself included) breaks FEX's 32-bit mode. `PROOT_FP_OFF=1` for FEX. - **"Steam now requires user namespaces"** - steam-runtime-check-requirements' bwrap probe; the arm64 client has no such probe. The SteamRT3 client (`steamrt64/steam`) is started directly, the @@ -518,7 +518,7 @@ What it took, in order (each step was the next failure on device): runtime linked file by file and only the probe replaced. - **tier0 assertion "Function not implemented"** - semget: Android has no System V IPC. Traced with a `-DDEBUG_STRACE` FEX (build-fex.yml `cxxflags` input, artifact only). The session shim - (`preload/*.c`) is now also built natively as `libblsession-x86_64.so`, staged, and preloaded + (`preload/*.c`) is now also built natively as `libddsession-x86_64.so`, staged, and preloaded through the rootfs's own `/etc/ld.so.preload`. - **re-exec into pressure-vessel after self-update** - `STEAM_STEAMRT_RECURSION_GUARD=1`. - **libgtk-x11-2.0 missing / soname links / old glibc shadowing** - Valve's steamrt3c platform @@ -526,10 +526,10 @@ What it took, in order (each step was the next failure on device): and only libraries the rootfs lacks (LD_LIBRARY_PATH beats system folders whatever its order). - **GLX failed** - the desktop exports zink over the arm64 Turnip ICD; cleared, llvmpipe used. - **web helper died of SIGTRAP a second after start** - found with pid-tagged traces (FEX AppConfig - `OutputLog=server` + a foreground FEXServer, `BL_FEXSERVER_LOG`; file logs overwrite each other): + `OutputLog=server` + a foreground FEXServer, `DD_FEXSERVER_LOG`; file logs overwrite each other): every web helper read `/proc/self/status` from libtier0_s.so, saw proot as a tracer, and tier0 broke into the "debugger" with int3. `preload/tracer.c` exempts the web helper on purpose (Chromium traps - on a status fd that is not procfs); with `BL_WEBHELPER_HIDE_TRACER=1` only opens called from + on a status fd that is not procfs); with `DD_WEBHELPER_HIDE_TRACER=1` only opens called from libtier0_s.so get the copy. - `SessionFiles` stages `bannerlator-steam-x64` and the x86-64 shim (they were missing from the list). @@ -545,7 +545,7 @@ Later the same day (device-proven unless noted): - From an audit of `bannerlator-session`: stale lock cleanup, branch sync before every start, core re-pinning, path cache and `perms.c` for `steamrt64`, the app's FEX preset (PERFORMANCE_TSO). - **Play button (built, not yet device-tested)**: Steam settings > Client > "Steam client: ARM64 / - x86-64 (FEX, experimental)" (`BL_STEAM_CLIENT_ARCH`). The session then starts the x86 client via + x86-64 (FEX, experimental)" (`DD_STEAM_CLIENT_ARCH`). The session then starts the x86 client via `bannerlator-steam-x64 --prepare/--exec` and gives it everything it gives the arm64 one; steps only for the arm64 client (ARM64 Proton, mapping, seeding, Decky, steamclient.so probes) are skipped. @@ -908,7 +908,7 @@ without it and Setup says "Stores engine not built"). launch, so it is removed (user decision): no overlay switch, no download, no `OverlayPath`; a launch removes a pointer an earlier build wrote, and the app deletes an earlier 656 MB download once. The work is parked on `park/epic-eos-overlay` (at `bf81104`). Kept: the browser hand-off, - the Epic card (sign-in, offline, Resolve Epic sign-in) and `BL_DEBUG_BROWSER`. + the Epic card (sign-in, offline, Resolve Epic sign-in) and `DD_DEBUG_BROWSER`. - **A game launched from the Games tab with no session running sat at "Launching"** (device, 2026-10-09-04-steam, and 2026-10-08-05 before it). The session put `steam://rungameid/` on the client's command line; the client took it seconds before its interface was up (focus went to @@ -931,9 +931,9 @@ without it and Setup says "Stores engine not built"). browser in the prefix (`"Browsers"="/usr/local/bin/droiddeck-open-url,xdg-open"`, an absolute path that does not depend on Wine's PATH), linked as `xdg-open` first on the game's PATH, and reading the session channel from `/tmp/droiddeck-browser/launch-dir` when Wine does not pass - `BL_LAUNCH_DIR` on. Whether EOS calls ShellExecute at all in its browser flow (rather than handing + `DD_LAUNCH_DIR` on. Whether EOS calls ShellExecute at all in its browser flow (rather than handing a verification URI and code to the game to show) is what the next run's `droiddeck xdg-open:` line, - or `BL_DEBUG_BROWSER=1` in droiddeck-env (`WINEDEBUG=+shell,+winebrowser`), will show. + or `DD_DEBUG_BROWSER=1` in droiddeck-env (`WINEDEBUG=+shell,+winebrowser`), will show. - **Resolve Epic sign-in** (the Epic card): opens Epic's account page behind its sign-in in Android's browser, where a pending corrective action (privacy policy, EULA) is presented. - **Epic overlay off by default** (device A/B, Metalstorm: overlay pointer set → exits while diff --git a/docs/settings-map.md b/docs/settings-map.md new file mode 100644 index 0000000000..b9b42d5639 --- /dev/null +++ b/docs/settings-map.md @@ -0,0 +1,106 @@ +# Where settings live + +Generated from `SettingsIndex.kt` by `SettingsMapTest`. Run `UPDATE_SETTINGS_MAP=1 ./gradlew :app:testDebugUnitTest --tests '*SettingsMapTest*'` after changing the index. + +Links of the form `droiddeck://settings/
` open a Settings section directly. + +## Settings + +| Setting | Where | Also matches | +| --- | --- | --- | +| Linux runtime | Settings › Overview (`droiddeck://settings/overview`) | ubuntu, linux, repair, update | +| Child-process limit | Settings › Overview (`droiddeck://settings/overview`) | phantom, process, killed, background | +| Steam account | Settings › Overview (`droiddeck://settings/overview`) | steam, login, sign in | +| Override Steam's core choice | Settings › Performance (`droiddeck://settings/performance`) | steam client cores, cpu | +| Game cores | Settings › Performance (`droiddeck://settings/performance`) | cpu, pin, cores, affinity | +| Save power on steady games | Settings › Performance (`droiddeck://settings/performance`) | cpu | +| Threaded GL | Settings › Performance (`droiddeck://settings/performance`) | opengl, gl | +| Zink: lazy descriptors | Settings › Performance (`droiddeck://settings/performance`) | | +| Skip GL error checks | Settings › Performance (`droiddeck://settings/performance`) | | +| gamescope: realtime GPU queue | Settings › Performance (`droiddeck://settings/performance`) | gamescope | +| Hold the GPU at its top clock | Settings › Performance (`droiddeck://settings/performance`) | gpu, clock, max | +| RAM cap | Settings › Performance (`droiddeck://settings/performance`) | ram, memory | +| VRAM cap | Settings › Performance (`droiddeck://settings/performance`) | vram, memory | +| Compress idle game memory | Settings › Performance (`droiddeck://settings/performance`) | zram, swap, memory | +| Compress Steam while a game runs | Settings › Performance (`droiddeck://settings/performance`) | zram, swap, memory | +| Clear cached apps before a session | Settings › Performance (`droiddeck://settings/performance`) | memory, ram, crash, sleep, killed | +| Background apps during a session | Settings › Performance (`droiddeck://settings/performance`) | memory, ram, background apps | +| Memory readout | Settings › Performance (`droiddeck://settings/performance`) | memory, ram, overlay | +| Turnip: sysmem rendering | Settings › Performance (`droiddeck://settings/performance`) | | +| Skip Steam's xalia helper | Settings › Performance (`droiddeck://settings/performance`) | | +| droiddeck-esync | Settings › Performance (`droiddeck://settings/performance`) | esync, sync, wine | +| droiddeck-fsync first | Settings › Performance (`droiddeck://settings/performance`) | fsync, sync, wine | +| droiddeck-ntsync | Settings › Performance (`droiddeck://settings/performance`) | ntsync, sync, wine | +| Run proot without seccomp | Settings › Performance (`droiddeck://settings/performance`) | proot | +| proot fast path | Settings › Performance (`droiddeck://settings/performance`) | proot | +| Run without proot (experimental) | Settings › Performance (`droiddeck://settings/performance`) | proot | +| Draw the cursor inside gamescope | Settings › Performance (`droiddeck://settings/performance`) | mouse, cursor | +| Host name | Settings › Performance (`droiddeck://settings/performance`) | name | +| Controller | Settings › Controller (`droiddeck://settings/controller`) | gamepad, buttons, mapping, profile, remap | +| Smart glasses | Settings › Smart glasses (`droiddeck://settings/glasses`) | xreal, viture, vr, ar | +| Theme | Settings › Launcher (`droiddeck://settings/launcher`) | color, dark | +| App scale | Settings › Launcher (`droiddeck://settings/launcher`) | size, zoom | +| App icon | Settings › Launcher (`droiddeck://settings/launcher`) | | +| Animations | Settings › Launcher (`droiddeck://settings/launcher`) | | +| Sidebar labels | Settings › Launcher (`droiddeck://settings/launcher`) | sidebar | +| Language | Settings › Launcher (`droiddeck://settings/launcher`) | translate | +| Use as Home screen | Settings › Launcher (`droiddeck://settings/launcher`) | home screen, launcher | +| Launcher orientation | Settings › Launcher (`droiddeck://settings/launcher`) | rotate, portrait | +| Session orientation | Settings › Launcher (`droiddeck://settings/launcher`) | rotate, portrait | +| Fullscreen | Settings › Launcher (`droiddeck://settings/launcher`) | | +| Dual screen launcher | Settings › Launcher (`droiddeck://settings/launcher`) | thor, second screen, bottom screen | +| Warn when storage is low | Settings › Launcher (`droiddeck://settings/launcher`) | | +| SteamGridDB API key | Settings › Launcher (`droiddeck://settings/launcher`) | artwork, steamgriddb | +| Source | Settings › Launcher (`droiddeck://settings/launcher`) | mirror, china | +| HTTP proxy | Settings › Launcher (`droiddeck://settings/launcher`) | | +| Latest session logs | Settings › Developer (`droiddeck://settings/developer`) | logs, log, bug, report, crash, zip | +| Session logs | Settings › Developer (`droiddeck://settings/developer`) | logs | +| Game debug logs | Settings › Developer (`droiddeck://settings/developer`) | logs, wine, proton | +| Enhanced diagnostics for next session | Settings › Developer (`droiddeck://settings/developer`) | logs | +| Reset all settings | Settings › Developer (`droiddeck://settings/developer`) | default | +| Developer tools | Settings › Developer (`droiddeck://settings/developer`) | agent, ai, claude, codex | +| Detailed graphics logs | Settings › Developer (`droiddeck://settings/developer`) | logs, gpu | + +## Tabs + +| Setting | Where | Also matches | +| --- | --- | --- | +| Storage | Tabs › Storage | sd card, space, uninstall, disk | +| Syncthing | Tabs › Syncthing | syncthing, saves | +| Download speed tier | Tabs › Downloads | download, speed, bandwidth, slow | +| Downloads at a time | Tabs › Downloads | download, parallel, queue, at once | +| Tabs | Tabs › More | tabs, hide, reorder, agent, stores, edit tabs | + +## In-game menu + +| Setting | Where | Also matches | +| --- | --- | --- | +| Frame limit | In-game menu › Display | fps, cap, limit, non-steam, desktop | +| Frame generation | In-game menu › Display | lsfg, lossless, fps | +| Scaling filter | In-game menu › Display | upscale, fsr, sharpness | +| Performance HUD | In-game menu › Performance HUD | fps, counter, overlay, performance | +| Touchscreen | In-game menu › Controller | touch, mouse, direct, touchpad, click | +| On-screen controls | In-game menu › Controller | on-screen, controls, touch controls, buttons | +| Steam touch layout | In-game menu › Controller | touch layout, edit layout, on-screen | +| PC keyboard | In-game menu › Controller | keyboard, typing | +| Report a problem | In-game menu › Session | logs, log, bug, crash, share, zip | +| Background behavior | In-game menu › Session | sleep, background, native, resume | + +## Steam quick menu (•••) + +| Setting | Where | Also matches | +| --- | --- | --- | +| Frame limit | Steam quick menu (•••) › Performance | fps, cap, limit, steam games | +| Performance | Steam quick menu (•••) | performance overlay, fps, counter, tdp | + +## Steam or Desktop options (swipe up) + +| Setting | Where | Also matches | +| --- | --- | --- | +| Session display | Steam or Desktop options (swipe up) › Display | resolution, scaling, hdr, refresh | +| Graphics drivers | Steam or Desktop options (swipe up) › Display | turnip, driver, gpu, adreno, mali | +| Offline mode | Steam or Desktop options (swipe up) › Steam | offline, steam | +| Microphone | Steam or Desktop options (swipe up) › Audio | microphone, voice | +| Background behavior | Steam or Desktop options (swipe up) › Session | sleep, background | +| Library | Steam or Desktop options (swipe up) › Library | second library, sd card, steam library | + diff --git a/docs/testing/steam-in-kde.md b/docs/testing/steam-in-kde.md index 306e9a20dc..caa1e6a8f9 100644 --- a/docs/testing/steam-in-kde.md +++ b/docs/testing/steam-in-kde.md @@ -2,7 +2,7 @@ The [Discord report](https://discord.com/channels/1552707793247539220/1552707794430459916/1558974992753098874) describes Steam replacing KDE with a gamescope session. The launcher unconditionally wrote `steam-launch`, which tells the Android app to end KDE and start Steam under gamescope. Other desktop applications have a separate GPU wrapper; this change addresses Steam's desktop client. -Desktop Steam now runs the existing session supervisor with `BL_INSIDE=1` on KDE's inherited Xwayland display and authentication. CEF uses software rendering because KDE's QPainter compositor accepts shared-memory buffers. Big Picture continues to request the explicit gaming session. A lock keeps repeated menu clicks from starting another supervisor while Steam is starting or updating; subsequent clicks wait for Steam's live IPC pipe and then forward the Steam URL to the existing client. This also prevents a second click during cold startup from launching a client without software CEF. KDE retains its own agent and clipboard helpers when Steam starts and exits. +Desktop Steam now runs the existing session supervisor with `DD_INSIDE=1` on KDE's inherited Xwayland display and authentication. CEF uses software rendering because KDE's QPainter compositor accepts shared-memory buffers. Big Picture continues to request the explicit gaming session. A lock keeps repeated menu clicks from starting another supervisor while Steam is starting or updating; subsequent clicks wait for Steam's live IPC pipe and then forward the Steam URL to the existing client. This also prevents a second click during cold startup from launching a client without software CEF. KDE retains its own agent and clipboard helpers when Steam starts and exits. Validation on AYN Thor uses the full wireless ADB serial `adb-d234a848-fv2FDl (2)._adb-tls-connect._tcp`. Live script testing displayed the authenticated library, restored the main window from maximized to windowed, opened Settings as a separate window, and forwarded a second launch to Downloads. KDE's panel remained visible, no gamescope process started, and no session handoff file was written. Quitting Steam returned to the running Plasma desktop with its agent still available. An explicit Big Picture launch then switched to a Steam session and reached READY with Steam focused. diff --git a/shortcuts/build.gradle b/shortcuts/build.gradle index b9e37dd89d..62f6a84201 100644 --- a/shortcuts/build.gradle +++ b/shortcuts/build.gradle @@ -9,9 +9,9 @@ android { defaultConfig { applicationId 'com.droiddeck.shortcuts' minSdkVersion 26 - targetSdkVersion 28 - versionCode 1 - versionName '1' + targetSdkVersion 34 + versionCode 3 + versionName '3' } sourceSets.main.java.srcDir('src/protocol/java') diff --git a/shortcuts/src/main/AndroidManifest.xml b/shortcuts/src/main/AndroidManifest.xml index 2409846f7b..bdeaa1c3b1 100644 --- a/shortcuts/src/main/AndroidManifest.xml +++ b/shortcuts/src/main/AndroidManifest.xml @@ -1,6 +1,12 @@ + + + + + + = 33) registerReceiver(packages, filter, Context.RECEIVER_NOT_EXPORTED); + else registerReceiver(packages, filter); receiving = true; bindAll(); } @@ -88,7 +89,8 @@ public class ShortcutsService extends AccessibilityService { if (linked) continue; Link link = new Link(component); try { - if (bindService(new Intent(Relay.ACTION).setComponent(component), link, Context.BIND_AUTO_CREATE)) links.add(link); + // No BIND_AUTO_CREATE: frontends read a running player as an open game, so the relay app decides when it runs. + if (bindService(new Intent(Relay.ACTION).setComponent(component), link, 0)) links.add(link); else unbindService(link); } catch (RuntimeException ignored) { } diff --git a/shortcuts/src/protocol/java/com/droiddeck/shortcuts/Relay.java b/shortcuts/src/protocol/java/com/droiddeck/shortcuts/Relay.java index 77f354d055..bc8b03b9b4 100644 --- a/shortcuts/src/protocol/java/com/droiddeck/shortcuts/Relay.java +++ b/shortcuts/src/protocol/java/com/droiddeck/shortcuts/Relay.java @@ -13,6 +13,7 @@ public final class Relay { public static final String SERVICE = PACKAGE + ".ShortcutsService"; public static final String ACTION = "com.droiddeck.shortcuts.RELAY"; public static final String DESCRIPTOR = "com.droiddeck.shortcuts.Relay"; + public static final int VERSION = 3; public static final int CONFIG = 1; public static final int KEY = 2; diff --git a/tools/build_local.sh b/tools/build_local.sh index fa49414b15..6f8d004ffa 100755 --- a/tools/build_local.sh +++ b/tools/build_local.sh @@ -128,15 +128,15 @@ docker run --rm --platform "${docker_platform}" \ -o "$d/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl aarch64-linux-gnu-strip --strip-unneeded "$d/libfakeinput.so" aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ - -o "$d/libblsession.so" tools/linuxfs/preload/*.c -ldl - aarch64-linux-gnu-strip --strip-unneeded "$d/libblsession.so" + -o "$d/libddsession.so" tools/linuxfs/preload/*.c -ldl + aarch64-linux-gnu-strip --strip-unneeded "$d/libddsession.so" aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ - -o "$d/libblfastpath.so" tools/proot/fastpath/fastpath.c -ldl - aarch64-linux-gnu-strip --strip-unneeded "$d/libblfastpath.so" + -o "$d/libddfastpath.so" tools/proot/fastpath/fastpath.c -ldl + aarch64-linux-gnu-strip --strip-unneeded "$d/libddfastpath.so" bash tools/nativeguest/build.sh "$d/libddnatv-hook.so" aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -nostdlib -ffreestanding -fno-stack-protector \ - -fno-tree-loop-distribute-patterns -Wl,-z,defs -o "$d/libblaudit.so" tools/proot/fastpath/audit.c - aarch64-linux-gnu-strip --strip-unneeded "$d/libblaudit.so" + -fno-tree-loop-distribute-patterns -Wl,-z,defs -o "$d/libddaudit.so" tools/proot/fastpath/audit.c + aarch64-linux-gnu-strip --strip-unneeded "$d/libddaudit.so" aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ -o "$d/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl aarch64-linux-gnu-strip --strip-unneeded "$d/libssbs.so" diff --git a/tools/components/build-arm64-preloads.sh b/tools/components/build-arm64-preloads.sh index e06aa2afc1..7b4cc7d03c 100644 --- a/tools/components/build-arm64-preloads.sh +++ b/tools/components/build-arm64-preloads.sh @@ -7,15 +7,15 @@ aarch64-linux-gnu-g++ -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compa -o "$D/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl aarch64-linux-gnu-strip --strip-unneeded "$D/libfakeinput.so" aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ - -o "$D/libblsession.so" tools/linuxfs/preload/*.c -ldl -aarch64-linux-gnu-strip --strip-unneeded "$D/libblsession.so" + -o "$D/libddsession.so" tools/linuxfs/preload/*.c -ldl +aarch64-linux-gnu-strip --strip-unneeded "$D/libddsession.so" aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ - -o "$D/libblfastpath.so" tools/proot/fastpath/fastpath.c -ldl -aarch64-linux-gnu-strip --strip-unneeded "$D/libblfastpath.so" + -o "$D/libddfastpath.so" tools/proot/fastpath/fastpath.c -ldl +aarch64-linux-gnu-strip --strip-unneeded "$D/libddfastpath.so" bash tools/nativeguest/build.sh "$D/libddnatv-hook.so" aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -nostdlib -ffreestanding -fno-stack-protector \ - -fno-tree-loop-distribute-patterns -Wl,-z,defs -o "$D/libblaudit.so" tools/proot/fastpath/audit.c -aarch64-linux-gnu-strip --strip-unneeded "$D/libblaudit.so" + -fno-tree-loop-distribute-patterns -Wl,-z,defs -o "$D/libddaudit.so" tools/proot/fastpath/audit.c +aarch64-linux-gnu-strip --strip-unneeded "$D/libddaudit.so" aarch64-linux-gnu-gcc -shared -fPIC -O2 -Wall -pthread \ -o "$D/libssbs.so" tools/linuxfs/ssbs/ssbs_adapter.c -ldl aarch64-linux-gnu-strip --strip-unneeded "$D/libssbs.so" diff --git a/tools/components/preloads.lock.json b/tools/components/preloads.lock.json index 45beb41529..37e2319dad 100644 --- a/tools/components/preloads.lock.json +++ b/tools/components/preloads.lock.json @@ -1,121 +1,168 @@ { - "archive_sha256": "cb6487a94f25a3068fd07958174eb5b5e14f709655ff4ef0a8cdbd99138513b2", - "arm64_recipe": "1c92a1b0669277de3e78e9f292634affb5b5a19d5ea49d3ad8610c1dc638c2fb", + "archive_sha256": "2d1f53c795615e7066a47ad26c791397d830bb8b028e9c89f9f809eaeebd3fae", + "arm64_recipe": "d89e4bbf9533840a44d77c52a392cdce242822b1e80293ea4de26d2f06a09698", "groups": { "arm64": { - "@runner": "84f825635599f81ed33f62c5fc4c73f66044d1468b060d65f83855eb9c8bfe77", + "@runner": "37a91043149e9747985b419002d87ff4df41ec6def4169e0ef16711d7261dbf2", "app/src/main/cpp/adrenotools/src/hook/kgsl.h": "396c56761034a4ed783543ee3312c6ec64d63b2a1cf7eecf1939c23251f25adf", - "app/src/main/cpp/fakeinput_steam.cpp": "3d11e859ca58a42a9da92a3fc589d404df790e151f7e18ea6114645750e70ef5", - "app/src/main/cpp/venc/venc_proto.h": "2242ddbc8981d14a33bac70264bb3e7f701fd1c3ebb988e17bbb2b19b6b808f7", + "app/src/main/cpp/fakeinput_steam.cpp": "e1377f9d7cd8539a9a327e2851b04c8e05e931f8b5ee554fa4f36d4b17f96718", + "app/src/main/cpp/venc/venc_proto.h": "57636af2644b36ea101cd09de42c423e864a612160561239ceda77ce888d5370", "tools/linuxfs/clipboard/clipboard.c": "96291c2bbc040c83caabf059ab3e95a9ed90d6a768c759d7cb4c0b64706bddfa", - "tools/linuxfs/preload/binfmt.c": "0933cc49cb53f0aa1206e2eae516d38dc3337e74174be07e10619c42aa56792b", - "tools/linuxfs/preload/dircache.c": "8e7f19ea4a1198783d53a3f357326c6177da157b0cc7e0d22e1670963e1c26e7", - "tools/linuxfs/preload/drm.c": "e0eabab0d8ed9e841918e827bf87168efa7f2dfb8404169e9bed3ab5eda2836c", - "tools/linuxfs/preload/fsync.c": "795c114c2a05d3f250d07145d04c5658091699da3b96290da36348ccadfb0c09", - "tools/linuxfs/preload/inputudev.c": "2648248d3d235a582eb8459709e0a85de537c03ac10c5040fbfb50d9846c68eb", - "tools/linuxfs/preload/kgslid.c": "88a7875fd5289930204d155d92ac9d15492cd06db16ed87aa9c95af37f3e7089", - "tools/linuxfs/preload/kgslpoll.c": "f0d853d919a52487c04cbda5fb3fa22269da54b7f4ee2f7dd3b5bd9909418670", - "tools/linuxfs/preload/links.c": "b7bbcf9112393b152f358fe6f8dc9a1955f0c8532e1eddf016a971415cd13c64", - "tools/linuxfs/preload/lock.c": "f71b3fd40e6a2b74908d3cdc601e8748699ae9c7a89b542d2445b999015ffd66", - "tools/linuxfs/preload/net.c": "335853c8ea0e9a8ebbc5a5500dc4bded9c34c4310a6ab8aa46b07d5ce1c2b55e", - "tools/linuxfs/preload/netif.c": "cc26d50b8d4639d8dd4697811bbf85c9d9f31761f9504a4af42473de3cb22b3c", - "tools/linuxfs/preload/noexec.c": "1855aeaeda3d506329bd9af1107580c74d1f56787c411b2e01c0a8a9d4059c7b", - "tools/linuxfs/preload/ntsync.c": "0614c48af0c062bfcb4c30141efe1b792b340767a67d2fe92ee9877d2ba16e0d", - "tools/linuxfs/preload/opens.c": "92ae4aea16aa457a898dedf4a70eb332d80d3b1e77f3a60bace7715a4317399e", - "tools/linuxfs/preload/pathcache.c": "eb0d4b5238fe6c8891e805d90bd837e466754100c978fad2d0ff717116b9b8a3", - "tools/linuxfs/preload/perms.c": "f600619c4ca130f69001ed7ad7bd74a3dc215b14c61479c45bb770f916d244b9", - "tools/linuxfs/preload/pulseguard.c": "57674ea40283e53a27bc78362de1ba41ee972d172ea38b1f818b1d6eed0abe65", + "tools/linuxfs/preload/binfmt.c": "45e820cdd75f2bd42710d98a4d5fee7398b667c9793ee94d8b8b7c4f29f4380c", + "tools/linuxfs/preload/clockpause.c": "5c8cbe1303e3b5fce97b000a952ab15691c0b56dc874e4a963f0e7888ce3f2c7", + "tools/linuxfs/preload/descriptor.c": "673b1cd0a5cd287a572e67aa60c2c36d1bc90ccac4f73ad0a783d4d2e2e5df07", + "tools/linuxfs/preload/dircache.c": "09d3dee98e49ef85b8e8112acb6a2b3d8b980eac80f07b3c82785e567f0606a6", + "tools/linuxfs/preload/drm.c": "9c9b9deab902276ee23a08a98730b2c6adbf7ea6d61e1e73d2a2e7c7016b1335", + "tools/linuxfs/preload/fsync.c": "f2f5fd3197d536d9396dd3d69837f6a2b0b4ff9aaffdb6f55b200408aaf5793d", + "tools/linuxfs/preload/inputudev.c": "76d7f720cd9531d8d38c2977956bf764b0db6055cb56aa35493476a244d9a22e", + "tools/linuxfs/preload/kgslid.c": "1a9639606ece49c5aff74baa5b9ef0921ec5dbc321d19d3f59184e4456f324a4", + "tools/linuxfs/preload/kgslpoll.c": "d03c09e0c82f76716dcc1f3ca77e718c60929bedf221ea5dae8ab43f5ab3e3f3", + "tools/linuxfs/preload/links.c": "c5761d450e070de912fbc9c71562d3fbf54775b484ea0fa57ded2e0c0771f7cf", + "tools/linuxfs/preload/lock.c": "1fcfefe28ef49ccd73f13b69ceb576492101cd1ddb88f08e0c73646ddeb327f2", + "tools/linuxfs/preload/net.c": "0645013df15656573d484bf6f8e6d8657beb228c779ae1143c0874e12559bf3e", + "tools/linuxfs/preload/netif.c": "cf6568ce8ffea44f24a8443160d86e4efddcdb964c908532935cbc4c4570ca91", + "tools/linuxfs/preload/noexec.c": "12f5245a893f9044558270cb03cfb7020546bfe3e90a9264b33d3f818dd30433", + "tools/linuxfs/preload/ntsync.c": "acffede0324fc89ac91f8181c2df23e6f39459a4db678a44ce9e65e0f282418c", + "tools/linuxfs/preload/oomadj.c": "d84d552a24ec3467e7ba5cf92a384521dfbcf1fc9a97e899b7b18d20bf1b45d5", + "tools/linuxfs/preload/opens.c": "2ba8f056ae0f2ab87a3d58ca0926b09af67deb1e24048506117bc26601e249c6", + "tools/linuxfs/preload/owner.c": "746d0a1834d0e19f7d9adfad72a6080a1104610f98c1d61e14d2c3a91a9eb04d", + "tools/linuxfs/preload/pathcache.c": "7d8287736f8f1988738d233c002ff6e00127c98034fcd35c2bb63a84c04b85a3", + "tools/linuxfs/preload/perms.c": "5ffa0ce5ff8269fc567dc5581bec380dcf2c90b9fb178c8dbae747e61430608f", + "tools/linuxfs/preload/pulseguard.c": "a91a0d5c745ea32ad52d57010a8b3cf7171bc4a3d2f73b870c64a6a62b233b56", "tools/linuxfs/preload/quest_kgsl.c": "59d9b8416be6a1c680f1d1e4c2427d2cbb7b415344261adb357d9d211ec95cfe", - "tools/linuxfs/preload/robust.c": "9eb6c0ed50e0f48a8cfb86bd92587f471354bdf2531b9177f4b3ab83bdfed39a", - "tools/linuxfs/preload/rptouch.c": "0e3f8bf2f9a41324361f38fa4da8d2d47593c9555f0cabf8228767397846c7c3", - "tools/linuxfs/preload/space.c": "118389bcc89dfa2b4230b80915e21d2d4331c4cff1f5a58265f85e6ecb5c29d2", - "tools/linuxfs/preload/storage.c": "08a8b46c3588f3160bb8608489768010ec36d5ccdb2b25a431ec9d6fcd413a6e", - "tools/linuxfs/preload/sysv.c": "49774ee5e2e39b84dcfadf63abdc741b3df236cb11783744a1280adee36965e8", + "tools/linuxfs/preload/robust.c": "02cd25316912c79897e2c5a1ed44b059b815d36bc62ba8d4691f718eeae92947", + "tools/linuxfs/preload/rptouch.c": "fc6db7e4b9432a7361e805a9a2dd134f9f3ec4ffba7927ab4b2c7b6bd2a22644", + "tools/linuxfs/preload/space.c": "9258ec8a8f8d87f2629b753d1838a09000110d936103284a04134b8cbed024d3", + "tools/linuxfs/preload/storage.c": "5c0dc4e5901e8cc32cdf241e38e3d5dcd3dae8b8ca94579f633754c8eadd617b", + "tools/linuxfs/preload/subreaper.c": "6f3830c0368a768bd0d367fa94345e6e4725875acc9662cf3690f1c5f28bf71c", + "tools/linuxfs/preload/sysv.c": "893dfad1db964eb1f79af94978b4af8b87279b85c30a4d589b5844cded476ed3", "tools/linuxfs/preload/tracefs.c": "be3f8a2f032b56e6e08a931e77a9386aea4bb93421a482271e06386ec0c469b6", - "tools/linuxfs/preload/tracer.c": "f34e5377c891b0a8d00489245d66f96bc352df4cd90f47a951dcadae980af4c1", - "tools/linuxfs/preload/udevmon.c": "2045dfb883cfb6e2016c359a3dc3af17f3b8f383f6dd0d5dfee407ef0d344852", - "tools/linuxfs/preload/usr2.c": "6ae704380b45a9b3a74c4fe2b3ce4482470dae59ced26cf0aee64f4b4dcc11f9", - "tools/linuxfs/preload/venc.c": "24c3c46fe49d28adfc8c977e52c9cc407f534b26f56d94b3425b8bb01803dba8", + "tools/linuxfs/preload/tracer.c": "4b5481ea91a475bb6ac16a7ba63e371f0a850a17adac5399302a610c0a57ec0a", + "tools/linuxfs/preload/udevmon.c": "4d5f07f2521af702b3f2adda3c93a39873f87c0946de007bca8b1fe6699596fa", + "tools/linuxfs/preload/usr2.c": "4b4044da1ddf07d12bafeb893c257679e26a5ea2f58e6cc0d715f27b931e7b1e", + "tools/linuxfs/preload/vdec.c": "a7b2d0754067493cde1929846f7b2c9692c4dde96ee273a92c81ac65470fac50", + "tools/linuxfs/preload/venc.c": "7fda60f013736d98dab734a9344e0f1d527dc3d976a71f5ccd4a0bc17d9f346f", + "tools/linuxfs/preload/venus.c": "d4af5c3532d4c7d9891b75cd5a137252e791beafe319b9fd976be123f7b80403", "tools/linuxfs/preload/vmwrite.c": "1a3ea2ec4354e0716c17f7db537b19ab82bcd524f2aece2fa5dec89b076a2188", - "tools/linuxfs/preload/webhelper.c": "a8213a7a96b407459c83fb93365cfe58fd05964e7bb262b8061c1c0792a6aac8", - "tools/linuxfs/preload/writewatch.c": "61e395d1caa184d329dead0e36c4e92cb1069b1154ac36581f37406c1c242240", - "tools/linuxfs/preload/xmode.c": "9a09995bf52d40b07f16828bcc545b59b8fb1ba60d9cb09f14f7f31dba1e65a6", - "tools/linuxfs/preload/zram.c": "12bcf07459728d4a7ede6fa0fea8deb330f7c5d0f0dd61e610e81b9efecd4262", + "tools/linuxfs/preload/webhelper.c": "bec759f908fb7c52238a7b72d3888aac6187aaec2378c190749ab8a5f7f1d81a", + "tools/linuxfs/preload/writewatch.c": "285ed7e627dc9349dd3ae45e8c1ffeaf4c56970b9eac5046754e348b4587dd6b", + "tools/linuxfs/preload/xmode.c": "3b6e36b29795544fdc0299822049b1890a7612578051d2a8982485c263dcf259", + "tools/linuxfs/preload/zram.c": "60b8c9fbd96adcc2026e48c651948d592f06017ff679e4775b1752be26525a2e", "tools/linuxfs/ssbs/ssbs_adapter.c": "9e4e0fe637f7b8f91f12d8151f02e8d31bcb4294be2b2c62d3cd3ce76f200306", + "tools/nativeguest/LICENSE": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", + "tools/nativeguest/app-seccomp-dump.c": "b5bfb92de5d64fa286b5a1cf3f4f71687817fc093cf698c65ffb2a5c575ce809", + "tools/nativeguest/build-gosys.sh": "34877be3fdbf7cf74f1dc19fbe708d428b135e65caf92a8ad0cbc7772ad699c7", + "tools/nativeguest/build.sh": "5aad4e82e293a2b47f461434dd6b024360d3b4356dadabc28b2fcc08220103be", + "tools/nativeguest/ddnatv-hook.c": "65451173bedbc332668f25b6589ca54d0a4c2d7edfaeb48f69ce00632b5d968b", + "tools/nativeguest/gosys/gosys.c": "a7808741af5fcaede7260f743b482612a7b2a818e207514bab667d06ca82f4d4", + "tools/nativeguest/gosys/gosys.ld": "dd4de106e3f9429a9373f8ed512537ed5b4927efc368ce3b8364776be435fb80", + "tools/nativeguest/gosys/gosys_abi.h": "8c246268e0645a7148bc2ad9f0c1d6147e0a3bc0c7625956be9afc018c58ada0", + "tools/nativeguest/hook/env.c": "ed84ca5c1f9704eba140263123f0b1876d1e2daee7b92d444f06edab3246f327", + "tools/nativeguest/hook/exec.c": "69111bf9a9ebaf56f59825c99fa16078f53ba708e8816e2c9bd02aff909149f5", + "tools/nativeguest/hook/exec_probe.c": "539ba604469d0a7fcc1677709bc56386ac92de4ba07fe80fda10f4cd85bf6d1a", + "tools/nativeguest/hook/fileops.c": "10bde17100bc2d7ed44f8921b16472309bb108b6f77371aaa3036d0737867706", + "tools/nativeguest/hook/files.c": "be6affd0bdf55e4759b5ba5edbbd280b47bae74013d790c0132474e8aca9abeb", + "tools/nativeguest/hook/go_programs.c": "418340c66a1d9fd5b492fff8b22d929ca3b4ef672ba73968c0d0ca5a4e9f3937", + "tools/nativeguest/hook/hardlinks.c": "eae44472aaefb9c24854610acfe16b221081a8bdc39bc63f8c957292ddced6ed", + "tools/nativeguest/hook/identity.c": "89f1632f00b141c568e8dbc0226039d3f6d9bd0752ff337e343cac2cb3a60705", + "tools/nativeguest/hook/net.c": "ec62f2bf9bb1eb15b7947d577a6cdde67dcce21bdaf217fd74c00ceb78e4f471", + "tools/nativeguest/hook/paths.c": "7d3098f944c6c13621eb4295df3ecb06350fc61381e4b92070764d66d8c85354", + "tools/nativeguest/hook/posix_shm.c": "0bb3782c538723051d51d147d35a9f5b37872b2a6ffa49d3059264539533d0f7", + "tools/nativeguest/hook/privileged.c": "d1acc6faca83f9b7a1a4d5a07fe19d73d139f8f9f3ec6215347c6ec7088f1819", + "tools/nativeguest/hook/setup.c": "2a3baa4ecc9fe39ff96e920a5e49e8b94fe432c63cc3fecd8badf40003a67ffc", + "tools/nativeguest/hook/signals.c": "b9e3646c3376150d64afff81a1e3f40a7ef5662de6b2b01d15f1bb8f2c5ecdf9", + "tools/nativeguest/hook/sockets.c": "6e221ca047351e67b2a0a4611d9782b60f7f309309b83a46406cf371becc2f40", + "tools/nativeguest/hook/static_programs.c": "f53db68d18240d1bbf92cf7ecabfb207861bbf563785516be3325bc9c511e629", + "tools/nativeguest/hook/syscalls.c": "1e6e7e44e2a49ac768aaf55661748a4ce703c06bab6dbe1ce25c5de80f416053", + "tools/nativeguest/hook/sysv_shm.c": "1ef54c48aa25d827494502c913423612f270767a6343435fbc5868ad927b5ed1", + "tools/nativeguest/seccomp-sim.c": "261d8ef8364f05a45acc43767eab22057357f056558b69835a0198d5bae3d9b8", "tools/proot/fastpath/audit.c": "bfe347a2ddaceef40a78d7d590e4e679724ee4c82f3f1f1e3c7017a18ad536d4", - "tools/proot/fastpath/fastpath.c": "4cd07b25ba14f6faa6bac5091ae323ded6b646dbb34b9e5a92ea6385e4d37cb5", - "tools/quest/kgsl_compat.c": "111afffda7a6df2469610f6c342ae086b1a97a559c586efc4a28015b86efd6bd", + "tools/proot/fastpath/fastpath.c": "8fe165886b0462b912507636592462599f4657b4c2c56723968b8f95981dd05e", + "tools/proot/fastpath/svc-cache.h": "bf0b4669ff3d5b72354cc0fdb62d1c2637b545db2096d782a1f713ae9cfbdc89", + "tools/proot/fastpath/svc-dispatch.h": "18dbd595a181ac9d7c0e2eb9ef4321cd9e3ea24e7506beac71cd9e9923d327e5", + "tools/proot/fastpath/svc-patch.h": "9c1d05485a4f79e71b4a49e73e6d2fa37473de20db93acdc7fbfe04c6156fb96", + "tools/proot/fastpath/svc-publish.h": "1c4491e8b22d15319619c1d61707f614fa2b152afd5d02ad197c3da9a2f26e62", + "tools/proot/fastpath/svc-stack.h": "2545db824775ea4673e0272cf7c16f64c87e92db4853f6874cf2c3451cba474b", + "tools/quest/kgsl_compat.c": "92cf5b3da0b3704c20d9e1307bb5abc0530717b9a2e2fd7c8db876a85dc333a1", "tools/quest/kgsl_compat.h": "2e9e0eb647530a35277954b7e61a22ee958067fe46056a608fb32f40f273f1bf" }, "x86": { - "@runner": "84f825635599f81ed33f62c5fc4c73f66044d1468b060d65f83855eb9c8bfe77", + "@runner": "37a91043149e9747985b419002d87ff4df41ec6def4169e0ef16711d7261dbf2", "app/src/main/cpp/adrenotools/src/hook/kgsl.h": "396c56761034a4ed783543ee3312c6ec64d63b2a1cf7eecf1939c23251f25adf", - "app/src/main/cpp/fakeinput_steam.cpp": "3d11e859ca58a42a9da92a3fc589d404df790e151f7e18ea6114645750e70ef5", - "app/src/main/cpp/venc/venc_proto.h": "2242ddbc8981d14a33bac70264bb3e7f701fd1c3ebb988e17bbb2b19b6b808f7", - "tools/linuxfs/build-x86-preloads.sh": "d0820252809881db89db5a17427e74b9aa4964aae70623cb7f4b474e90c7a23b", + "app/src/main/cpp/fakeinput_steam.cpp": "e1377f9d7cd8539a9a327e2851b04c8e05e931f8b5ee554fa4f36d4b17f96718", + "app/src/main/cpp/venc/venc_proto.h": "57636af2644b36ea101cd09de42c423e864a612160561239ceda77ce888d5370", + "tools/linuxfs/build-x86-preloads.sh": "cf283b41c9a39b61bb628035a405cc8d33bd8085056ea482f80253a3ddd6ab8b", "tools/linuxfs/debian-image.env": "1c79dea4314c784042a5c59208765c8401771098f293185d61a157d89edf6e52", "tools/linuxfs/fex/faultreport.c": "573bf780f32f7256dc2fbf40fe850d67e67c354509fdedcac3ff7f1a261daac3", - "tools/linuxfs/fex/vulkanpin.c": "f2693ac2be8d15f7881115e61b1c6b3fe4aeec8f603584c6fce5b0f046563d51", - "tools/linuxfs/fex/webkitinput.c": "693ffd6c8c8c97e87156444ad2255c84dbf22cd0053d135fb8d9be094b5534d1", - "tools/linuxfs/preload/binfmt.c": "0933cc49cb53f0aa1206e2eae516d38dc3337e74174be07e10619c42aa56792b", - "tools/linuxfs/preload/dircache.c": "8e7f19ea4a1198783d53a3f357326c6177da157b0cc7e0d22e1670963e1c26e7", - "tools/linuxfs/preload/drm.c": "e0eabab0d8ed9e841918e827bf87168efa7f2dfb8404169e9bed3ab5eda2836c", - "tools/linuxfs/preload/fsync.c": "795c114c2a05d3f250d07145d04c5658091699da3b96290da36348ccadfb0c09", - "tools/linuxfs/preload/inputudev.c": "2648248d3d235a582eb8459709e0a85de537c03ac10c5040fbfb50d9846c68eb", - "tools/linuxfs/preload/kgslid.c": "88a7875fd5289930204d155d92ac9d15492cd06db16ed87aa9c95af37f3e7089", - "tools/linuxfs/preload/kgslpoll.c": "f0d853d919a52487c04cbda5fb3fa22269da54b7f4ee2f7dd3b5bd9909418670", - "tools/linuxfs/preload/links.c": "b7bbcf9112393b152f358fe6f8dc9a1955f0c8532e1eddf016a971415cd13c64", - "tools/linuxfs/preload/lock.c": "f71b3fd40e6a2b74908d3cdc601e8748699ae9c7a89b542d2445b999015ffd66", - "tools/linuxfs/preload/net.c": "335853c8ea0e9a8ebbc5a5500dc4bded9c34c4310a6ab8aa46b07d5ce1c2b55e", - "tools/linuxfs/preload/netif.c": "cc26d50b8d4639d8dd4697811bbf85c9d9f31761f9504a4af42473de3cb22b3c", - "tools/linuxfs/preload/noexec.c": "1855aeaeda3d506329bd9af1107580c74d1f56787c411b2e01c0a8a9d4059c7b", - "tools/linuxfs/preload/ntsync.c": "0614c48af0c062bfcb4c30141efe1b792b340767a67d2fe92ee9877d2ba16e0d", - "tools/linuxfs/preload/opens.c": "92ae4aea16aa457a898dedf4a70eb332d80d3b1e77f3a60bace7715a4317399e", - "tools/linuxfs/preload/pathcache.c": "eb0d4b5238fe6c8891e805d90bd837e466754100c978fad2d0ff717116b9b8a3", - "tools/linuxfs/preload/perms.c": "f600619c4ca130f69001ed7ad7bd74a3dc215b14c61479c45bb770f916d244b9", - "tools/linuxfs/preload/pulseguard.c": "57674ea40283e53a27bc78362de1ba41ee972d172ea38b1f818b1d6eed0abe65", + "tools/linuxfs/fex/vulkanpin.c": "c530e265486fd106705fac906848871c9bce6acef2718a9c2d5dbb5bd7650227", + "tools/linuxfs/fex/webkitinput.c": "5356a003aa30686218f403ad4ea67f792ac84dc434f289032292f234908d5c48", + "tools/linuxfs/preload/binfmt.c": "45e820cdd75f2bd42710d98a4d5fee7398b667c9793ee94d8b8b7c4f29f4380c", + "tools/linuxfs/preload/clockpause.c": "5c8cbe1303e3b5fce97b000a952ab15691c0b56dc874e4a963f0e7888ce3f2c7", + "tools/linuxfs/preload/descriptor.c": "673b1cd0a5cd287a572e67aa60c2c36d1bc90ccac4f73ad0a783d4d2e2e5df07", + "tools/linuxfs/preload/dircache.c": "09d3dee98e49ef85b8e8112acb6a2b3d8b980eac80f07b3c82785e567f0606a6", + "tools/linuxfs/preload/drm.c": "9c9b9deab902276ee23a08a98730b2c6adbf7ea6d61e1e73d2a2e7c7016b1335", + "tools/linuxfs/preload/fsync.c": "f2f5fd3197d536d9396dd3d69837f6a2b0b4ff9aaffdb6f55b200408aaf5793d", + "tools/linuxfs/preload/inputudev.c": "76d7f720cd9531d8d38c2977956bf764b0db6055cb56aa35493476a244d9a22e", + "tools/linuxfs/preload/kgslid.c": "1a9639606ece49c5aff74baa5b9ef0921ec5dbc321d19d3f59184e4456f324a4", + "tools/linuxfs/preload/kgslpoll.c": "d03c09e0c82f76716dcc1f3ca77e718c60929bedf221ea5dae8ab43f5ab3e3f3", + "tools/linuxfs/preload/links.c": "c5761d450e070de912fbc9c71562d3fbf54775b484ea0fa57ded2e0c0771f7cf", + "tools/linuxfs/preload/lock.c": "1fcfefe28ef49ccd73f13b69ceb576492101cd1ddb88f08e0c73646ddeb327f2", + "tools/linuxfs/preload/net.c": "0645013df15656573d484bf6f8e6d8657beb228c779ae1143c0874e12559bf3e", + "tools/linuxfs/preload/netif.c": "cf6568ce8ffea44f24a8443160d86e4efddcdb964c908532935cbc4c4570ca91", + "tools/linuxfs/preload/noexec.c": "12f5245a893f9044558270cb03cfb7020546bfe3e90a9264b33d3f818dd30433", + "tools/linuxfs/preload/ntsync.c": "acffede0324fc89ac91f8181c2df23e6f39459a4db678a44ce9e65e0f282418c", + "tools/linuxfs/preload/oomadj.c": "d84d552a24ec3467e7ba5cf92a384521dfbcf1fc9a97e899b7b18d20bf1b45d5", + "tools/linuxfs/preload/opens.c": "2ba8f056ae0f2ab87a3d58ca0926b09af67deb1e24048506117bc26601e249c6", + "tools/linuxfs/preload/owner.c": "746d0a1834d0e19f7d9adfad72a6080a1104610f98c1d61e14d2c3a91a9eb04d", + "tools/linuxfs/preload/pathcache.c": "7d8287736f8f1988738d233c002ff6e00127c98034fcd35c2bb63a84c04b85a3", + "tools/linuxfs/preload/perms.c": "5ffa0ce5ff8269fc567dc5581bec380dcf2c90b9fb178c8dbae747e61430608f", + "tools/linuxfs/preload/pulseguard.c": "a91a0d5c745ea32ad52d57010a8b3cf7171bc4a3d2f73b870c64a6a62b233b56", "tools/linuxfs/preload/quest_kgsl.c": "59d9b8416be6a1c680f1d1e4c2427d2cbb7b415344261adb357d9d211ec95cfe", - "tools/linuxfs/preload/robust.c": "9eb6c0ed50e0f48a8cfb86bd92587f471354bdf2531b9177f4b3ab83bdfed39a", - "tools/linuxfs/preload/rptouch.c": "0e3f8bf2f9a41324361f38fa4da8d2d47593c9555f0cabf8228767397846c7c3", - "tools/linuxfs/preload/space.c": "118389bcc89dfa2b4230b80915e21d2d4331c4cff1f5a58265f85e6ecb5c29d2", - "tools/linuxfs/preload/storage.c": "08a8b46c3588f3160bb8608489768010ec36d5ccdb2b25a431ec9d6fcd413a6e", - "tools/linuxfs/preload/sysv.c": "49774ee5e2e39b84dcfadf63abdc741b3df236cb11783744a1280adee36965e8", + "tools/linuxfs/preload/robust.c": "02cd25316912c79897e2c5a1ed44b059b815d36bc62ba8d4691f718eeae92947", + "tools/linuxfs/preload/rptouch.c": "fc6db7e4b9432a7361e805a9a2dd134f9f3ec4ffba7927ab4b2c7b6bd2a22644", + "tools/linuxfs/preload/space.c": "9258ec8a8f8d87f2629b753d1838a09000110d936103284a04134b8cbed024d3", + "tools/linuxfs/preload/storage.c": "5c0dc4e5901e8cc32cdf241e38e3d5dcd3dae8b8ca94579f633754c8eadd617b", + "tools/linuxfs/preload/subreaper.c": "6f3830c0368a768bd0d367fa94345e6e4725875acc9662cf3690f1c5f28bf71c", + "tools/linuxfs/preload/sysv.c": "893dfad1db964eb1f79af94978b4af8b87279b85c30a4d589b5844cded476ed3", "tools/linuxfs/preload/tracefs.c": "be3f8a2f032b56e6e08a931e77a9386aea4bb93421a482271e06386ec0c469b6", - "tools/linuxfs/preload/tracer.c": "f34e5377c891b0a8d00489245d66f96bc352df4cd90f47a951dcadae980af4c1", - "tools/linuxfs/preload/udevmon.c": "2045dfb883cfb6e2016c359a3dc3af17f3b8f383f6dd0d5dfee407ef0d344852", - "tools/linuxfs/preload/usr2.c": "6ae704380b45a9b3a74c4fe2b3ce4482470dae59ced26cf0aee64f4b4dcc11f9", - "tools/linuxfs/preload/venc.c": "24c3c46fe49d28adfc8c977e52c9cc407f534b26f56d94b3425b8bb01803dba8", + "tools/linuxfs/preload/tracer.c": "4b5481ea91a475bb6ac16a7ba63e371f0a850a17adac5399302a610c0a57ec0a", + "tools/linuxfs/preload/udevmon.c": "4d5f07f2521af702b3f2adda3c93a39873f87c0946de007bca8b1fe6699596fa", + "tools/linuxfs/preload/usr2.c": "4b4044da1ddf07d12bafeb893c257679e26a5ea2f58e6cc0d715f27b931e7b1e", + "tools/linuxfs/preload/vdec.c": "a7b2d0754067493cde1929846f7b2c9692c4dde96ee273a92c81ac65470fac50", + "tools/linuxfs/preload/venc.c": "7fda60f013736d98dab734a9344e0f1d527dc3d976a71f5ccd4a0bc17d9f346f", + "tools/linuxfs/preload/venus.c": "d4af5c3532d4c7d9891b75cd5a137252e791beafe319b9fd976be123f7b80403", "tools/linuxfs/preload/vmwrite.c": "1a3ea2ec4354e0716c17f7db537b19ab82bcd524f2aece2fa5dec89b076a2188", - "tools/linuxfs/preload/webhelper.c": "a8213a7a96b407459c83fb93365cfe58fd05964e7bb262b8061c1c0792a6aac8", - "tools/linuxfs/preload/writewatch.c": "61e395d1caa184d329dead0e36c4e92cb1069b1154ac36581f37406c1c242240", - "tools/linuxfs/preload/xmode.c": "9a09995bf52d40b07f16828bcc545b59b8fb1ba60d9cb09f14f7f31dba1e65a6", - "tools/linuxfs/preload/zram.c": "12bcf07459728d4a7ede6fa0fea8deb330f7c5d0f0dd61e610e81b9efecd4262", - "tools/quest/kgsl_compat.c": "111afffda7a6df2469610f6c342ae086b1a97a559c586efc4a28015b86efd6bd", + "tools/linuxfs/preload/webhelper.c": "bec759f908fb7c52238a7b72d3888aac6187aaec2378c190749ab8a5f7f1d81a", + "tools/linuxfs/preload/writewatch.c": "285ed7e627dc9349dd3ae45e8c1ffeaf4c56970b9eac5046754e348b4587dd6b", + "tools/linuxfs/preload/xmode.c": "3b6e36b29795544fdc0299822049b1890a7612578051d2a8982485c263dcf259", + "tools/linuxfs/preload/zram.c": "60b8c9fbd96adcc2026e48c651948d592f06017ff679e4775b1752be26525a2e", + "tools/quest/kgsl_compat.c": "92cf5b3da0b3704c20d9e1307bb5abc0530717b9a2e2fd7c8db876a85dc333a1", "tools/quest/kgsl_compat.h": "2e9e0eb647530a35277954b7e61a22ee958067fe46056a608fb32f40f273f1bf" } }, "origin": { - "artifact": 12520502054, - "artifact_sha256": "b7e800a1884a516ec52b050b7f904f9881427bca4579f660b909fd18f15e49ff", - "commit": "b76f13f7acc0af0cc00369dde61fb88e40529e6d", - "run": 39992155294, - "url": "https://github.com/Droid-Deck/DroidDeck/actions/runs/39992155294" + "artifact": 14400591108, + "artifact_sha256": "974023be39cb1b7a168efb38369d1adfe2a51f0e1d7b9b535b50c8692a24f870", + "commit": "c8b291b9dbdeae137236a56ad66f08b1f3370a8a", + "run": 44240744255, + "url": "https://github.com/Droid-Deck/DroidDeck/actions/runs/44240744255" }, "outputs": { - "i386/libblsession.so": "5343cdb704217ddc81ee593e67d5987363dc7b5ac78bd4bd36000219e5063268", - "i386/libfakeinput.so": "188d88dfb13b6e2f2df948e7b8b4d9ec604770f55d1ea5b6b9e21ad56a74ce5e", + "i386/libddsession.so": "da5562f924faf98144b569ee3ed113be7dcee59deef24abc84be56fd4ba9ccd3", + "i386/libfakeinput.so": "99f6328a3a380672680969a54cd2e9996edf25c287fa5a00e2db54264da8d898", "i386/libfaultreport.so": "95f9ef60f04a13ee60cfbd4d2d2efb60a7063b722e646c78c9dc27162292877b", - "libblaudit.so": "6c6abe89baf5d7309babee0c3372a4b00c2b689e2a63de38c5e9a660626509b5", - "libblfastpath.so": "0e1f151b5c1c5ea9dd380ad58d09f8fe7ba3ae037d0991cb3eef6899e9d5ec83", - "libblsession.so": "29d4b5ea46dba941107e02c0ee544244b137a339cada43bff65c350f2ef2755a", - "libfakeinput.so": "5f6dc3aea05de2dc1fbe0bbfac2ce4d11e3d47f761c6b06c8badb15fe1904392", + "libddaudit.so": "6c6abe89baf5d7309babee0c3372a4b00c2b689e2a63de38c5e9a660626509b5", + "libddfastpath.so": "9cdf153a8f9d4e150123dd5bac8ff678a0b84c1318e036c1d928b542821103b6", + "libddnatv-hook.so": "8ed3de674273734ae239408a315ab7813e1e5bb606ed126b9e45eec0e84fe399", + "libddsession.so": "da6c3a919bd6f48f5abfdab383c45be71fb20b684c6defec4fbbbb450b8e2d59", + "libfakeinput.so": "46b671065c0a811fc10d46dcf8dc4b58fce110079c8d919d2e1072c3b02eca02", "libssbs.so": "c288ed0da26c2481aff270d1cdafe1205061c4a300c2c46ae1b53c6e0c94f44b", "usr/local/bin/droiddeck-clipboard": "ec50e8f67fdf76372927189b0fdb670f9b70fd3484f2fe3e833bc8f9fdc44205", - "x86_64/libblsession.so": "61d19f06aebab6a789f8c99f687af9903376bfc853e46b70c48a2ce5e497accc", - "x86_64/libfakeinput.so": "8663dd2086bf8ae53069a480dd9ae4619109d32f0947a29e2ce38f07a21ae2e6", + "x86_64/libddsession.so": "1438bc246fb0fec985ef71fccbe4acdc067b1ae4b97befdc8f01fdd79c99b151", + "x86_64/libfakeinput.so": "74ef688919a0f757d2c022b7a18d64e7c4819301e79e0aa8572d8e0ef8318e49", "x86_64/libfaultreport.so": "bb0dc9165d0d764473e552508650edd586df16d620fc5b16b8b1c5740a28ce22", "x86_64/libvulkan-thunk.so": "74f01b652d7e8179561a096a552328b68da640cc4bad3981edd38e6afbf90243", - "x86_64/libwebkitinput.so": "9b07380a7b017397b9c56bb7bb1161e046b0c6a647fc413888904606b0def6d0" + "x86_64/libwebkitinput.so": "d0ba6886642595132d1ec9abb8d9f4cc7e1bc4c750b4a5d53d2f089334a6b4e3" }, "toolchain": { "arm64": "Ubuntu 24.04 GCC cross compiler; exact build commands pinned by arm64_recipe", diff --git a/tools/components/recipes.json b/tools/components/recipes.json index 92fcc548a4..79562333d4 100644 --- a/tools/components/recipes.json +++ b/tools/components/recipes.json @@ -29,6 +29,7 @@ "ndk": true, "packages": [ "gcc-aarch64-linux-gnu", + "libc6-dev-arm64-cross", "g++-aarch64-linux-gnu", "libvulkan1", "mesa-vulkan-drivers" @@ -62,10 +63,10 @@ ], "outputs": [ "app/src/main/assets/linuxfs/x86_64/libfakeinput.so", - "app/src/main/assets/linuxfs/x86_64/libblsession.so", + "app/src/main/assets/linuxfs/x86_64/libddsession.so", "app/src/main/assets/linuxfs/x86_64/libfaultreport.so", "app/src/main/assets/linuxfs/i386/libfakeinput.so", - "app/src/main/assets/linuxfs/i386/libblsession.so", + "app/src/main/assets/linuxfs/i386/libddsession.so", "app/src/main/assets/linuxfs/i386/libfaultreport.so", "app/src/main/assets/linuxfs/x86_64/libwebkitinput.so", "app/src/main/assets/linuxfs/x86_64/libvulkan-thunk.so" @@ -83,10 +84,10 @@ ], "snapshot_outputs": [ "x86_64/libfakeinput.so", - "x86_64/libblsession.so", + "x86_64/libddsession.so", "x86_64/libfaultreport.so", "i386/libfakeinput.so", - "i386/libblsession.so", + "i386/libddsession.so", "i386/libfaultreport.so", "x86_64/libwebkitinput.so", "x86_64/libvulkan-thunk.so" @@ -155,7 +156,8 @@ "app/src/main/assets/linuxfs/usr/local/lib/droiddeck-comet/version" ], "packages": [ - "gcc-aarch64-linux-gnu" + "gcc-aarch64-linux-gnu", + "libc6-dev-arm64-cross" ] }, "arm64-preloads": { @@ -169,15 +171,16 @@ ], "outputs": [ "app/src/main/assets/linuxfs/libfakeinput.so", - "app/src/main/assets/linuxfs/libblsession.so", - "app/src/main/assets/linuxfs/libblfastpath.so", - "app/src/main/assets/linuxfs/libblaudit.so", + "app/src/main/assets/linuxfs/libddsession.so", + "app/src/main/assets/linuxfs/libddfastpath.so", + "app/src/main/assets/linuxfs/libddaudit.so", "app/src/main/assets/linuxfs/libssbs.so", "app/src/main/assets/linuxfs/usr/local/bin/droiddeck-clipboard", "app/src/main/assets/linuxfs/libddnatv-hook.so" ], "packages": [ "gcc-aarch64-linux-gnu", + "libc6-dev-arm64-cross", "g++-aarch64-linux-gnu" ], "source_inputs": [ @@ -194,9 +197,9 @@ ], "snapshot_outputs": [ "libfakeinput.so", - "libblsession.so", - "libblfastpath.so", - "libblaudit.so", + "libddsession.so", + "libddfastpath.so", + "libddaudit.so", "libssbs.so", "usr/local/bin/droiddeck-clipboard", "libddnatv-hook.so" @@ -245,7 +248,8 @@ "app/src/main/assets/linuxfs/usr/local/bin/droiddeck-vkbridge-smoke" ], "packages": [ - "gcc-aarch64-linux-gnu" + "gcc-aarch64-linux-gnu", + "libc6-dev-arm64-cross" ] }, "dirt-ws2": { diff --git a/tools/droiddeckctl b/tools/droiddeckctl index 2ade313d41..15675a1797 100755 --- a/tools/droiddeckctl +++ b/tools/droiddeckctl @@ -1355,7 +1355,7 @@ def build_parser() -> argparse.ArgumentParser: env_clear = env_ops.add_parser("clear") env_clear.add_argument("scope", nargs="?", choices=["next", "persistent", "all"], default="next") - override = commands.add_parser("override", help="override a program or libblfastpath.so for the next session (debugging tools)") + override = commands.add_parser("override", help="override a program or libddfastpath.so for the next session (debugging tools)") override.add_argument("name", help="the program name, e.g. gamescope") override.add_argument("path", help="the local file to push") diff --git a/tools/fex/patches/0005-gl-thunk-forward-x-errors.patch b/tools/fex/patches/0005-gl-thunk-forward-x-errors.patch new file mode 100644 index 0000000000..c4641ab213 --- /dev/null +++ b/tools/fex/patches/0005-gl-thunk-forward-x-errors.patch @@ -0,0 +1,170 @@ +diff --git a/ThunkLibs/include/common/X11Manager.h b/ThunkLibs/include/common/X11Manager.h +index a0b1f9e..3843a5f 100644 +--- a/ThunkLibs/include/common/X11Manager.h ++++ b/ThunkLibs/include/common/X11Manager.h +@@ -24,7 +24,7 @@ using guest_size_t = size_t; + * guest display/connection. + */ + struct X11Manager { +- std::mutex mutex; ++ std::recursive_mutex mutex; + + // Maps guest connection to intermediary host connection + std::unordered_map connections; +@@ -68,18 +68,25 @@ struct X11Manager { + return it->second; + } + ++ _XDisplay* FindGuestDisplay(const _XDisplay* from) { ++ std::unique_lock lock(mutex); ++ for (auto& [guest, host] : displays) { ++ if (host == from) { ++ return guest; ++ } ++ } ++ return nullptr; ++ } ++ + guest_layout<_XDisplay*> HostToGuestDisplay(const _XDisplay* from) { + if (from == nullptr) { + return {.data = 0}; + } + +- std::unique_lock lock(mutex); +- for (auto& [guest, host] : displays) { +- if (host == from) { +- guest_layout<_XDisplay*> ret; +- ret.data = reinterpret_cast(guest); +- return ret; +- } ++ if (auto guest = FindGuestDisplay(from)) { ++ guest_layout<_XDisplay*> ret; ++ ret.data = reinterpret_cast(guest); ++ return ret; + } + + fprintf(stderr, "ERROR: Could not map host display %p back to guest\n", from); +@@ -106,6 +113,21 @@ struct X11Manager { + return func(Name); + } + ++ static XErrorHandler HostXSetErrorHandler(XErrorHandler Handler) { ++ static auto func = reinterpret_cast(dlsym(GetLibX11(), "XSetErrorHandler")); ++ return func(Handler); ++ } ++ ++ static void HostXLockDisplay(Display* a) { ++ static auto func = reinterpret_cast(dlsym(GetLibX11(), "XLockDisplay")); ++ func(a); ++ } ++ ++ static void HostXUnlockDisplay(Display* a) { ++ static auto func = reinterpret_cast(dlsym(GetLibX11(), "XUnlockDisplay")); ++ func(a); ++ } ++ + static XVisualInfo* HostXGetVisualInfo(Display* a, long b, XVisualInfo* c, int* d) { + static auto func = reinterpret_cast(dlsym(GetLibX11(), "XGetVisualInfo")); + return func(a, b, c, d); +@@ -114,6 +136,7 @@ struct X11Manager { + // NOTE: Struct pointers are replaced by void* to avoid involving data layout conversion here. + int (*GuestXSync)(void*, int) = nullptr; + void* (*GuestXGetVisualInfo)(void*, guest_long, void*, int*) = nullptr; ++ int (*GuestXErrorForward)(void*, guest_long, int, int, int) = nullptr; + + // XDisplayString internally just reads data from _XDisplay's internal struct definition. + // This breaks when data layout is different, so allow reading from a guest context instead. +diff --git a/ThunkLibs/libGL/libGL_Guest.cpp b/ThunkLibs/libGL/libGL_Guest.cpp +index b0eea5b..01eb801 100644 +--- a/ThunkLibs/libGL/libGL_Guest.cpp ++++ b/ThunkLibs/libGL/libGL_Guest.cpp +@@ -28,6 +28,8 @@ $end_info$ + + #include "thunkgen_guest_libGL.inl" + ++#include ++ + typedef void voidFunc(); + + // Maps OpenGL API function names to the address of a guest function which is +@@ -79,11 +81,26 @@ static void* malloc_wrapper(size_t size) { + return malloc(size); + } + ++static int ForwardXError(Display* display, long resourceid, int error_code, int request_code, int minor_code) { ++ xError error {}; ++ error.type = X_Error; ++ error.errorCode = error_code; ++ error.resourceID = resourceid; ++ error.majorCode = request_code; ++ error.minorCode = minor_code; ++ LockDisplay(display); ++ error.sequenceNumber = display->request; ++ int result = _XError(display, &error); ++ UnlockDisplay(display); ++ return result; ++} ++ + static void OnInit() { + fexfn_pack_GL_SetGuestMalloc((uintptr_t)malloc_wrapper, (uintptr_t)CallbackUnpack::Unpack); + fexfn_pack_GL_SetGuestXSync((uintptr_t)XSync, (uintptr_t)CallbackUnpack::Unpack); + fexfn_pack_GL_SetGuestXGetVisualInfo((uintptr_t)XGetVisualInfo, (uintptr_t)CallbackUnpack::Unpack); + fexfn_pack_GL_SetGuestXDisplayString((uintptr_t)XDisplayString, (uintptr_t)CallbackUnpack::Unpack); ++ fexfn_pack_GL_SetGuestXErrorForward((uintptr_t)ForwardXError, (uintptr_t)CallbackUnpack::Unpack); + } + + // libGL.so must pull in libX11.so as a dependency. Referencing some libX11 +diff --git a/ThunkLibs/libGL/libGL_Host.cpp b/ThunkLibs/libGL/libGL_Host.cpp +index dd3cec4..84efe41 100644 +--- a/ThunkLibs/libGL/libGL_Host.cpp ++++ b/ThunkLibs/libGL/libGL_Host.cpp +@@ -66,6 +66,28 @@ static void fexfn_impl_libGL_GL_SetGuestXDisplayString(uintptr_t GuestTarget, ui + MakeHostTrampolineForGuestFunctionAt(GuestTarget, GuestUnpacker, &x11_manager.GuestXDisplayString); + } + ++static XErrorHandler HostPreviousXErrorHandler = nullptr; ++ ++static int HostXErrorHandler(Display* HostDisplay, XErrorEvent* Event) { ++ auto GuestDisplay = x11_manager.FindGuestDisplay(HostDisplay); ++ if (!GuestDisplay || !x11_manager.GuestXErrorForward) { ++ return HostPreviousXErrorHandler ? HostPreviousXErrorHandler(HostDisplay, Event) : 0; ++ } ++ x11_manager.HostXUnlockDisplay(HostDisplay); ++ int Result = x11_manager.GuestXErrorForward(GuestDisplay, static_cast(Event->resourceid), Event->error_code, ++ Event->request_code, Event->minor_code); ++ x11_manager.HostXLockDisplay(HostDisplay); ++ return Result; ++} ++ ++static void fexfn_impl_libGL_GL_SetGuestXErrorForward(uintptr_t GuestTarget, uintptr_t GuestUnpacker) { ++ MakeHostTrampolineForGuestFunctionAt(GuestTarget, GuestUnpacker, &x11_manager.GuestXErrorForward); ++ auto Previous = x11_manager.HostXSetErrorHandler(HostXErrorHandler); ++ if (Previous != HostXErrorHandler) { ++ HostPreviousXErrorHandler = Previous; ++ } ++} ++ + #include "thunkgen_host_libGL.inl" + + auto fexfn_impl_libGL_glXGetProcAddress(const GLubyte* name) -> void (*)() { +diff --git a/ThunkLibs/libGL/libGL_interface.cpp b/ThunkLibs/libGL/libGL_interface.cpp +index 04a2d2b..b769cda 100644 +--- a/ThunkLibs/libGL/libGL_interface.cpp ++++ b/ThunkLibs/libGL/libGL_interface.cpp +@@ -26,6 +26,7 @@ void GL_SetGuestMalloc(uintptr_t, uintptr_t); + void GL_SetGuestXSync(uintptr_t, uintptr_t); + void GL_SetGuestXGetVisualInfo(uintptr_t, uintptr_t); + void GL_SetGuestXDisplayString(uintptr_t, uintptr_t); ++void GL_SetGuestXErrorForward(uintptr_t, uintptr_t); + template<> + struct fex_gen_config : fexgen::custom_guest_entrypoint, fexgen::custom_host_impl {}; + template<> +@@ -34,6 +35,8 @@ template<> + struct fex_gen_config : fexgen::custom_guest_entrypoint, fexgen::custom_host_impl {}; + template<> + struct fex_gen_config : fexgen::custom_guest_entrypoint, fexgen::custom_host_impl {}; ++template<> ++struct fex_gen_config : fexgen::custom_guest_entrypoint, fexgen::custom_host_impl {}; + + template + struct fex_gen_type {}; diff --git a/tools/linuxfs/build-x86-preloads.sh b/tools/linuxfs/build-x86-preloads.sh index 0e0abffcde..a9c32a18d6 100755 --- a/tools/linuxfs/build-x86-preloads.sh +++ b/tools/linuxfs/build-x86-preloads.sh @@ -8,12 +8,12 @@ for arch in x86_64 i386; do esac mkdir -p "$out/$arch" gcc $bits -shared -fPIC -O2 -Wall -pthread \ - -o "$out/$arch/libblsession.so" tools/linuxfs/preload/*.c -ldl + -o "$out/$arch/libddsession.so" tools/linuxfs/preload/*.c -ldl g++ $bits -shared -fPIC -O2 -Wall -Wno-attributes -Wno-nonnull-compare \ -pthread -std=c++17 -static-libstdc++ -static-libgcc -Wl,--exclude-libs,ALL \ -o "$out/$arch/libfakeinput.so" app/src/main/cpp/fakeinput_steam.cpp -ldl - strip --strip-unneeded "$out/$arch/libblsession.so" "$out/$arch/libfakeinput.so" - for lib in "$out/$arch/libblsession.so" "$out/$arch/libfakeinput.so"; do + strip --strip-unneeded "$out/$arch/libddsession.so" "$out/$arch/libfakeinput.so" + for lib in "$out/$arch/libddsession.so" "$out/$arch/libfakeinput.so"; do newest=$(objdump -T "$lib" | grep -o 'GLIBC_2\.[0-9]*' | sort -u -t. -k2,2n | tail -1) minor=${newest#GLIBC_2.} if [ "$minor" -gt 31 ]; then diff --git a/tools/linuxfs/check-preloads.sh b/tools/linuxfs/check-preloads.sh index a21d785ca8..0f801f87a0 100644 --- a/tools/linuxfs/check-preloads.sh +++ b/tools/linuxfs/check-preloads.sh @@ -15,12 +15,12 @@ done if grep -qxE '__gxx_personality_v0|__cxa_throw|_Unwind_Resume' <<<"$FAKE"; then echo "::error::libfakeinput.so exports the C++ runtime"; exit 1 fi -SESSION=$(syms "$D/libblsession.so") +SESSION=$(syms "$D/libddsession.so") for sym in socket bind getsockname setsockopt statfs statvfs syscall shm_open shm_unlink mmap mmap64 munmap mprotect drmPrimeFDToHandle drmCloseBufferHandle; do - grep -qx "$sym" <<<"$SESSION" || { echo "::error::libblsession.so does not export $sym"; exit 1; } + grep -qx "$sym" <<<"$SESSION" || { echo "::error::libddsession.so does not export $sym"; exit 1; } done if grep -qx drmIoctl <<<"$SESSION"; then - echo "::error::libblsession.so exports drmIoctl"; exit 1 + echo "::error::libddsession.so exports drmIoctl"; exit 1 fi SSBS=$(syms "$D/libssbs.so") for sym in sigaction signal bsd_signal sysv_signal; do diff --git a/tools/linuxfs/desktop/droiddeck-desktop b/tools/linuxfs/desktop/droiddeck-desktop index 53da7ebaad..d063bab657 100644 --- a/tools/linuxfs/desktop/droiddeck-desktop +++ b/tools/linuxfs/desktop/droiddeck-desktop @@ -19,15 +19,15 @@ done 2>/dev/null export DROIDDECK_NESTED_SCALE=1 export DROIDDECK_GLTHREAD=${mesa_glthread:-} unset MESA_LOADER_DRIVER_OVERRIDE LIBGL_KOPPER_DRI2 mesa_glthread -if [ -n "${BL_DEBUG_DIR:-}" ]; then - mkdir -p "$BL_DEBUG_DIR" 2>/dev/null || true - exec >>"$BL_DEBUG_DIR/desktop.log" 2>&1 - echo "== droiddeck-desktop $(date -u '+%Y-%m-%d %H:%M:%S UTC') ${BL_WIDTH:-1280}x${BL_HEIGHT:-720}" +if [ -n "${DD_DEBUG_DIR:-}" ]; then + mkdir -p "$DD_DEBUG_DIR" 2>/dev/null || true + exec >>"$DD_DEBUG_DIR/desktop.log" 2>&1 + echo "== droiddeck-desktop $(date -u '+%Y-%m-%d %H:%M:%S UTC') ${DD_WIDTH:-1280}x${DD_HEIGHT:-720}" fi find "$XDG_RUNTIME_DIR" -mindepth 1 -maxdepth 1 ! -name 'wayland-0*' ! -name 'keymap.xkb' -exec rm -rf {} + 2>/dev/null chmod 700 "$XDG_RUNTIME_DIR" 2>/dev/null mkdir -p /tmp/.X11-unix /tmp/.ICE-unix && chmod 1777 /tmp/.X11-unix /tmp/.ICE-unix 2>/dev/null -export BL_DESKTOP=1 +export DD_DESKTOP=1 ln -sf /usr/local/bin/droiddeck-steam-launch /usr/local/bin/steamdeck-steam 2>/dev/null ln -sf /usr/local/bin/droiddeck-steam-shim /usr/local/bin/steam 2>/dev/null python3 /usr/local/bin/droiddeck-desktop-games 2>&1 | sed 's/^/[games] /' @@ -125,9 +125,8 @@ if [ "$(cat /usr/share/droiddeck/kwin-compositor 2>/dev/null)" = opengl ]; then chmod 755 /run/droiddeck/kwin/kwin_wayland export PATH=/run/droiddeck/kwin:$PATH fi -if /usr/local/bin/droiddeck-pipewire start; then - eval "$(/usr/local/bin/droiddeck-pipewire env)" -else +# Plasma uses the rootfs libpipewire; the bundle's module and plugin paths leave it without a shell. +if ! /usr/local/bin/droiddeck-pipewire start; then echo "== pipewire: not running; screen capture has no picture" fi echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY" @@ -135,7 +134,7 @@ dbus-run-session -- startplasma-wayland rc=$? /usr/local/bin/droiddeck-pipewire stop echo "== droiddeck-desktop: Plasma ended ($rc)" -if [ "$rc" -eq 0 ] && [ -z "${BL_BOTTOM_DESKTOP:-}" ]; then +if [ "$rc" -eq 0 ] && [ -z "${DD_BOTTOM_DESKTOP:-}" ]; then /usr/local/bin/droiddeck-steam-launch bigpicture sleep 30 fi diff --git a/tools/linuxfs/desktop/droiddeck-desktop-gpu b/tools/linuxfs/desktop/droiddeck-desktop-gpu index 061d646208..a0173f7b6d 100644 --- a/tools/linuxfs/desktop/droiddeck-desktop-gpu +++ b/tools/linuxfs/desktop/droiddeck-desktop-gpu @@ -15,7 +15,7 @@ CHROMIUM_FLAGS = " --no-sandbox --ozone-platform=x11" def enabled(): - return os.environ.get("BL_DESKTOP_GPU", "on").strip().lower() not in ("off", "0", "no", "false") + return os.environ.get("DD_DESKTOP_GPU", "on").strip().lower() not in ("off", "0", "no", "false") def main_group(text): diff --git a/tools/linuxfs/desktop/droiddeck-gpu b/tools/linuxfs/desktop/droiddeck-gpu index da4bf7e41c..380caa4d63 100644 --- a/tools/linuxfs/desktop/droiddeck-gpu +++ b/tools/linuxfs/desktop/droiddeck-gpu @@ -1,30 +1,30 @@ #!/bin/bash set -u [ $# -gt 0 ] || { echo "usage: droiddeck-gpu [args...]" >&2; exit 64; } -if [ -n "${BL_DEBUG_DIR:-}" ]; then - exec >>"$BL_DEBUG_DIR/desktop.log" 2>&1 +if [ -n "${DD_DEBUG_DIR:-}" ]; then + exec >>"$DD_DEBUG_DIR/desktop.log" 2>&1 fi -width=${BL_WIDTH:-1280} -height=${BL_HEIGHT:-720} -backend=${BL_GAMESCOPE_BACKEND:-wayland} +width=${DD_WIDTH:-1280} +height=${DD_HEIGHT:-720} +backend=${DD_GAMESCOPE_BACKEND:-wayland} case "$backend" in wayland|sdl) ;; *) echo "== unsupported gamescope backend: $backend" >&2; exit 64 ;; esac window=0 -if [ "$backend" = wayland ] && [ "${BL_DESKTOP_GPU_WINDOW:-1}" != 0 ] && [ -n "${WAYLAND_DISPLAY:-}" ] && [ "$WAYLAND_DISPLAY" != wayland-0 ]; then +if [ "$backend" = wayland ] && [ "${DD_DESKTOP_GPU_WINDOW:-1}" != 0 ] && [ -n "${WAYLAND_DISPLAY:-}" ] && [ "$WAYLAND_DISPLAY" != wayland-0 ]; then window=1 parent=$WAYLAND_DISPLAY args=(--backend sdl --expose-wayland --follow-game-window-mode -W "$width" -H "$height" -w "$width" -h "$height") else args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$width" -h "$height") fi -if [ "${BL_FPS:-0}" -gt 0 ]; then - args+=(-r "$BL_FPS") -elif [ "${BL_REFRESH:-0}" -gt 0 ]; then - args+=(-r "$BL_REFRESH") +if [ "${DD_FPS:-0}" -gt 0 ]; then + args+=(-r "$DD_FPS") +elif [ "${DD_REFRESH:-0}" -gt 0 ]; then + args+=(-r "$DD_REFRESH") fi -[ "${BL_HDR:-0}" = 1 ] && args+=(--hdr-enabled) +[ "${DD_HDR:-0}" = 1 ] && args+=(--hdr-enabled) if [ "$window" = 1 ]; then echo "== droiddeck-gpu $(date -u +%H:%M:%S): $* (gamescope ${width}x${height} in a window on $parent)" else @@ -38,7 +38,7 @@ wsi=",${MESA_VK_WSI_DEBUG:-}," while [[ $wsi == *,sw,* ]]; do wsi=${wsi//,sw,/,}; done wsi=${wsi#,}; wsi=${wsi%,} if [ -n "$wsi" ]; then export MESA_VK_WSI_DEBUG=$wsi; else unset MESA_VK_WSI_DEBUG; fi -export BL_DESKTOP_GPU_CHILD=1 +export DD_DESKTOP_GPU_CHILD=1 export MESA_LOADER_DRIVER_OVERRIDE=zink GALLIUM_DRIVER=zink LIBGL_KOPPER_DRI2=true [ -n "${DROIDDECK_GLTHREAD:-}" ] && export mesa_glthread=$DROIDDECK_GLTHREAD export APPIMAGE_EXTRACT_AND_RUN=1 @@ -51,7 +51,7 @@ if ! command -v gamescopereaper >/dev/null 2>&1; then done fi if [ "$window" = 1 ]; then - export BL_GPU_CHILD_WSI=${MESA_VK_WSI_DEBUG:-} + export DD_GPU_CHILD_WSI=${MESA_VK_WSI_DEBUG:-} SDL_VIDEODRIVER=wayland MESA_VK_WSI_DEBUG=sw gamescope "${args[@]}" -- /usr/local/bin/droiddeck-gpu-window "$@" else gamescope "${args[@]}" -- env SDL_VIDEODRIVER=x11 /usr/local/bin/droiddeck-gpu-window "$@" diff --git a/tools/linuxfs/desktop/kwin_wayland_wrapper b/tools/linuxfs/desktop/kwin_wayland_wrapper index a34e7455a0..81753d2a58 100755 --- a/tools/linuxfs/desktop/kwin_wayland_wrapper +++ b/tools/linuxfs/desktop/kwin_wayland_wrapper @@ -1,5 +1,5 @@ #!/bin/bash -if [ "${BL_DESKTOP:-}" = 1 ]; then - set -- --wayland-display wayland-0 --socket wayland-1 --width "${BL_WIDTH:-1280}" --height "${BL_HEIGHT:-720}" --no-lockscreen "$@" +if [ "${DD_DESKTOP:-}" = 1 ]; then + set -- --wayland-display wayland-0 --socket wayland-1 --width "${DD_WIDTH:-1280}" --height "${DD_HEIGHT:-720}" --no-lockscreen "$@" fi exec /usr/bin/kwin_wayland_wrapper "$@" diff --git a/tools/linuxfs/overlay/usr/bin/steamos-session-select b/tools/linuxfs/overlay/usr/bin/steamos-session-select index eaac87341b..35f9bebbaf 100644 --- a/tools/linuxfs/overlay/usr/bin/steamos-session-select +++ b/tools/linuxfs/overlay/usr/bin/steamos-session-select @@ -3,9 +3,9 @@ echo "steamos-session-select: $*" >&2 case "${1:-}" in ""|gamescope) exit 0 ;; esac -dir=${BL_LAUNCH_DIR:-} +dir=${DD_LAUNCH_DIR:-} if [ -z "$dir" ] || [ ! -d "$dir" ]; then - echo "steamos-session-select: not inside a DroidDeck session (BL_LAUNCH_DIR unset)" >&2 + echo "steamos-session-select: not inside a DroidDeck session (DD_LAUNCH_DIR unset)" >&2 exit 1 fi printf 'session=desktop\nui=desktop\nurl=\n' > "$dir/steam-launch.tmp" && mv -f "$dir/steam-launch.tmp" "$dir/steam-launch" diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent index 5ae8031e68..114e608e33 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-agent @@ -283,7 +283,7 @@ def sandboxed_apps(proc=Path("/proc")): def window_steam_app(win, flatpaks, proc=Path("/proc")): match = STEAM_APP_CLASS.match(win.get("class") or "") if match: - return match.group(1) if os.environ.get("BL_STEAM_CLIENT_ARCH") == "x86_64" else None + return match.group(1) if os.environ.get("DD_STEAM_CLIENT_ARCH") == "x86_64" else None pid = win.get("pid") if pid: if under_reaper(pid, proc): @@ -391,18 +391,26 @@ class FocusWatcher(threading.Thread): x.close() except (OSError, AgentError) as e: log("focus snapshot failed: %s" % e) + self.publish({}) time.sleep(2) continue if tag_game_windows(snap): self.changed.set() continue - body = {k: v for k, v in snap.items() if k != "t"} - if body == self.last: - continue - self.last = body - self.seq += 1 - snap["seq"] = self.seq - write_json(self.path, snap) + self.publish(snap) + + def publish(self, snap): + body = {k: v for k, v in snap.items() if k != "t"} + if body == self.last: + return + try: + write_json(self.path, dict(snap, seq=self.seq + 1)) + except OSError as e: + log("focus publication failed: %s" % e) + self.changed.set() + return + self.seq += 1 + self.last = body def listen(self): while True: @@ -521,7 +529,7 @@ def cdp_port(agent_dir): try: port = (agent_dir / "cdp-port").read_text().strip() except OSError: - port = os.environ.get("BL_CDP_PORT", "") + port = os.environ.get("DD_CDP_PORT", "") if not port.isdigit(): raise AgentError("NO_DEVTOOLS", "The Steam client's DevTools port is not known (no Steam client in this session yet)") return int(port) @@ -1210,9 +1218,9 @@ def serve(agent_dir, focus=True, poll=0.1): def main(argv): - base = os.environ.get("BL_LAUNCH_DIR") + base = os.environ.get("DD_LAUNCH_DIR") if not base: - print("BL_LAUNCH_DIR is not set", file=sys.stderr) + print("DD_LAUNCH_DIR is not set", file=sys.stderr) return 2 if argv and argv[0] == "--wait-steam-shortcut-overview": if len(argv) not in (2, 3): diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet index 1e76859e04..066f9c572e 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-battlenet @@ -321,6 +321,15 @@ def install_path(root, library): return letter.upper() + ":\\" + path[len(target):].strip("/").replace("/", "\\") +def keeps_open(root): + try: + with open(os.path.join(drive_c(root), *CONFIG), encoding="utf-8-sig") as f: + client = json.load(f).get("Client") + except (OSError, ValueError, AttributeError): + return False + return isinstance(client, dict) and LAUNCH_BEHAVIOR[0] in client and client[LAUNCH_BEHAVIOR[0]] != LAUNCH_BEHAVIOR[1] + + def write_config(root, library=None): path = os.path.join(drive_c(root), *CONFIG) key, value = LAUNCH_BEHAVIOR @@ -338,7 +347,7 @@ def write_config(root, library=None): return None client = config["Client"] changes = [] - if client.get(key) != value: + if key not in client: client[key] = value changes.append("launch") if client.get("HardwareAcceleration") != "false": @@ -467,7 +476,7 @@ def still_pages(root): def desktop_size(): - width, height = os.environ.get("BL_WIDTH", ""), os.environ.get("BL_HEIGHT", "") + width, height = os.environ.get("DD_WIDTH", ""), os.environ.get("DD_HEIGHT", "") if width.isdigit() and height.isdigit() and 0 < int(width) <= 7680 and 0 < int(height) <= 4320: return int(width), int(height) return 1280, 720 @@ -875,6 +884,9 @@ class Tidy: self.game_since = self.game_since if self.game_since is not None else now if own and not self.closed_for_game and now - self.game_since >= self.settle: self.closed_for_game, self.agent_seen, self.agent_lost = True, False, None + if keeps_open(steam_root()): + say("Battle.net is set to stay open as a game launches: left open") + return False if any(is_client(argv) for _, argv in own) and any(shares_sign_in(argv) for argv in games): say("Battle.net stayed open beside a game signing in with its token: left open") return False @@ -900,18 +912,18 @@ class Tidy: def desktop_gpu(): - if os.environ.get("BL_DESKTOP") != "1" or os.environ.get("BL_DESKTOP_GPU_CHILD"): + if os.environ.get("DD_DESKTOP") != "1" or os.environ.get("DD_DESKTOP_GPU_CHILD"): return None - if os.environ.get("BL_DESKTOP_GPU", "on").strip().lower() in ("off", "0", "no", "false"): + if os.environ.get("DD_DESKTOP_GPU", "on").strip().lower() in ("off", "0", "no", "false"): return None gpu = os.path.join(BIN, "droiddeck-gpu") return gpu if os.access(gpu, os.X_OK) else None def proton_options(): - if os.environ.get("BL_DESKTOP") == "1" and not os.environ.get("BL_DESKTOP_GPU_CHILD"): + if os.environ.get("DD_DESKTOP") == "1" and not os.environ.get("DD_DESKTOP_GPU_CHILD"): return ["--window"] - width, height = os.environ.get("BL_WIDTH", ""), os.environ.get("BL_HEIGHT", "") + width, height = os.environ.get("DD_WIDTH", ""), os.environ.get("DD_HEIGHT", "") options = ["--desktop", "%sx%s" % (width, height)] if width.isdigit() and height.isdigit() else [] game = os.environ.get("SteamGameId", "") return options + (["--game-id", game] if game.isdigit() and game != "0" else []) @@ -942,7 +954,7 @@ def queued_requests(launch_dir): def serve_requests(pfx, processes=None, launch_dir=None): - launch_dir = launch_dir or os.environ.get("BL_LAUNCH_DIR") + launch_dir = launch_dir or os.environ.get("DD_LAUNCH_DIR") names = queued_requests(launch_dir) if launch_dir else [] if not names or not agent_up(wine_processes(pfx) if processes is None else processes): return False @@ -1136,7 +1148,7 @@ def stop_leftovers(pfx): def open_client(root, reinstall=False): pfx = os.path.join(prefix(root), "pfx") write_menu() - answer = ask_fex(os.environ.get("BL_LAUNCH_DIR")) + answer = ask_fex(os.environ.get("DD_LAUNCH_DIR")) say("FEX: %s" % (answer or "no answer from the app; Components' choice stays")) if running(pfx): say("Battle.net is already running in its prefix; waiting for it to close") @@ -1226,7 +1238,7 @@ def launch(root, code): try: own = None if lock is not None and not running(pfx): - answer = ask_fex(os.environ.get("BL_LAUNCH_DIR")) + answer = ask_fex(os.environ.get("DD_LAUNCH_DIR")) say("FEX: %s" % (answer or "no answer from the app; Components' choice stays")) verb = None if stop_leftovers(pfx) else "run" configure(root, LIBRARY) @@ -1560,7 +1572,7 @@ def main(argv): if gpu: say("the desktop starts Battle.net on the GPU") os.execv(gpu, [gpu, os.path.abspath(sys.argv[0])] + list(sys.argv[1:])) - os.environ["BL_BATTLENET"] = "1" + os.environ["DD_BATTLENET"] = "1" if launching: say("launch %s" % argv[1]) return launch(root, argv[1]) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-bottom-desktop b/tools/linuxfs/overlay/usr/local/bin/droiddeck-bottom-desktop index 2c19c23bed..768ce16942 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-bottom-desktop +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-bottom-desktop @@ -2,16 +2,16 @@ # KDE Plasma on a dual-screen handheld's bottom screen, next to the session on the top one. set -u export HOME=${HOME:-/root} -if [ -n "${BL_DEBUG_DIR:-}" ]; then - mkdir -p "$BL_DEBUG_DIR" 2>/dev/null || true - exec >>"$BL_DEBUG_DIR/bottom-desktop.log" 2>&1 +if [ -n "${DD_DEBUG_DIR:-}" ]; then + mkdir -p "$DD_DEBUG_DIR" 2>/dev/null || true + exec >>"$DD_DEBUG_DIR/bottom-desktop.log" 2>&1 fi -echo "== droiddeck-bottom-desktop $(date -u '+%Y-%m-%d %H:%M:%S UTC') ${BL_WIDTH:-?}x${BL_HEIGHT:-?} beside a ${BL_TOP_SESSION:-?} session" +echo "== droiddeck-bottom-desktop $(date -u '+%Y-%m-%d %H:%M:%S UTC') ${DD_WIDTH:-?}x${DD_HEIGHT:-?} beside a ${DD_TOP_SESSION:-?} session" [ -x /usr/local/bin/droiddeck-desktop ] || { echo "== the desktop package is not installed"; exit 66; } # Launch requests would reach the top session's watcher and could replace it. -unset BL_LAUNCH_DIR BL_LOG -export BL_BOTTOM_DESKTOP=1 +unset DD_LAUNCH_DIR BL_LAUNCH_DIR DD_LOG +export DD_BOTTOM_DESKTOP=1 for _ in $(seq 1 100); do wayland-info >/dev/null 2>&1 && break diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-bookmarks b/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-bookmarks index 5cbf57b4aa..e91b7090ff 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-bookmarks +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-bookmarks @@ -23,7 +23,7 @@ ET.register_namespace("bookmark", ICON_NS) def steam_libraries(home, data): steam = data / "Steam" libraries = {steam: "Internal Storage"} - listing = os.environ.get("BL_STEAM_LIBRARIES") + listing = os.environ.get("DD_STEAM_LIBRARIES") selected = None if listing: try: @@ -46,15 +46,15 @@ def steam_libraries(home, data): managed = path == LIBRARY or path.is_relative_to(home / "Games") or path.is_relative_to(ADDED) if selected is not None and managed and path not in selected: continue - if path == LIBRARY and selected is None and not os.environ.get("BL_LIBRARY_LABEL"): + if path == LIBRARY and selected is None and not os.environ.get("DD_LIBRARY_LABEL"): continue label = entry.get("label") label = re.sub(r'\\(["\\])', r'\1', label) if isinstance(label, str) else "" libraries[path] = label or path.name if selected is not None: libraries.update(selected) - elif os.environ.get("BL_LIBRARY_LABEL"): - libraries[LIBRARY] = os.environ["BL_LIBRARY_LABEL"] + elif os.environ.get("DD_LIBRARY_LABEL"): + libraries[LIBRARY] = os.environ["DD_LIBRARY_LABEL"] libraries[steam] = "Internal Storage" return {path.as_uri(): "Steam (" + (" ".join(label.split()) or path.name) + ")" for path, label in libraries.items() if path.is_absolute() and (path / "steamapps").is_dir()} @@ -67,7 +67,25 @@ def place_uri(uri): return uri -def update_places(path, libraries): +def removable_volumes(): + listing = os.environ.get("DD_DESKTOP_VOLUMES") + if not listing: + return {} + volumes = {} + for entry in json.loads(Path(listing).read_text()): + path = Path(entry["path"]) + if not path.is_absolute(): + continue + try: + with os.scandir(path): + pass + except OSError: + continue + volumes[path.as_uri()] = " ".join(str(entry["label"]).split()) or path.name + return volumes + + +def update_places(path, libraries, mark=MARK, icon_name="steam", id_prefix="droiddeck-steam-"): if path.is_file(): parser = ET.XMLParser(target=ET.TreeBuilder(insert_comments=True, insert_pis=True)) root = ET.fromstring(path.read_bytes(), parser=parser) @@ -80,10 +98,10 @@ def update_places(path, libraries): before = ET.tostring(root) seen = set() personal = {place_uri(b.get("href")) for b in root.findall("bookmark") - if b.find("info/metadata[@owner='" + KDE_OWNER + "']/" + MARK) is None} + if b.find("info/metadata[@owner='" + KDE_OWNER + "']/" + mark) is None} for bookmark in root.findall("bookmark"): metadata = bookmark.find("info/metadata[@owner='" + KDE_OWNER + "']") - if metadata is None or metadata.find(MARK) is None: + if metadata is None or metadata.find(mark) is None: continue uri = place_uri(bookmark.get("href")) if uri not in libraries or uri in seen or uri in personal: @@ -101,10 +119,10 @@ def update_places(path, libraries): ET.SubElement(bookmark, "title").text = label info = ET.SubElement(bookmark, "info") icon = ET.SubElement(info, "metadata", {"owner": "http://freedesktop.org"}) - ET.SubElement(icon, "{" + ICON_NS + "}icon", {"name": "steam"}) + ET.SubElement(icon, "{" + ICON_NS + "}icon", {"name": icon_name}) metadata = ET.SubElement(info, "metadata", {"owner": KDE_OWNER}) - ET.SubElement(metadata, "ID").text = "droiddeck-steam-" + hashlib.sha256(uri.encode()).hexdigest()[:16] - ET.SubElement(metadata, MARK).text = "true" + ET.SubElement(metadata, "ID").text = id_prefix + hashlib.sha256(uri.encode()).hexdigest()[:16] + ET.SubElement(metadata, mark).text = "true" ET.SubElement(metadata, "isSystemItem").text = "false" if ET.tostring(root) != before: atomic_write(path, ET.tostring(root, encoding="unicode", xml_declaration=True)) @@ -150,11 +168,13 @@ def atomic_write(path, content): def main(): home = Path.home() config = Path(os.environ.get("XDG_CONFIG_HOME") or home / ".config") - label = os.environ.get("BL_LIBRARY_LABEL") + label = os.environ.get("DD_LIBRARY_LABEL") available = bool(label) and (LIBRARY / "steamapps").is_dir() update_bookmark(bookmarks_file(home, config), label if available else None) data = Path(os.environ.get("XDG_DATA_HOME") or home / ".local/share") - update_places(data / "user-places.xbel", steam_libraries(home, data)) + places = data / "user-places.xbel" + update_places(places, steam_libraries(home, data)) + update_places(places, removable_volumes(), "DroidDeckRemovableVolume", "drive-removable-media", "droiddeck-volume-") if __name__ == "__main__": diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-clipboard b/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-clipboard index ccb7768c62..014f305350 100644 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-clipboard +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-clipboard @@ -1,6 +1,6 @@ #!/bin/bash -[ -n "${BL_ANDROID_CLIPBOARD:-}" ] && [ -n "${DISPLAY:-}" ] || exit 0 -/usr/local/bin/droiddeck-clipboard "$BL_ANDROID_CLIPBOARD" & +[ -n "${DD_ANDROID_CLIPBOARD:-}" ] && [ -n "${DISPLAY:-}" ] || exit 0 +/usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD" & child=$! trap 'kill "$child" 2>/dev/null' EXIT trap 'exit 0' TERM INT diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-games b/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-games index f49a90dd70..15fbee0d39 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-games +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-desktop-games @@ -4,8 +4,8 @@ import re import sys HOME = os.environ.get("HOME", "/root") -X64 = os.environ.get("BL_STEAM_CLIENT_ARCH") == "x86_64" -CLIENT_HOME = (os.environ.get("BL_X64_HOME") or os.path.join(HOME, ".droiddeck-x64")) if X64 else HOME +X64 = os.environ.get("DD_STEAM_CLIENT_ARCH") == "x86_64" +CLIENT_HOME = (os.environ.get("DD_X64_HOME") or os.path.join(HOME, ".droiddeck-x64")) if X64 else HOME STEAM_ROOT = sys.argv[1] if len(sys.argv) > 1 else os.path.join(CLIENT_HOME, ".local/share/Steam") LIBRARIES = ((STEAM_ROOT, "Steam Games"), ("/mnt/droiddeck-sd/x86-64" if X64 else "/mnt/droiddeck-sd", "SD Games")) NOT_GAMES = {228980, 1070560, 1161040, 1391110, 1493710, 1628350, 1826330, 3127680, 4183110, 4185400, 4427310, 4628740} diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-epic b/tools/linuxfs/overlay/usr/local/bin/droiddeck-epic index d0ad7010c2..9f77cb5ff8 100644 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-epic +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-epic @@ -112,7 +112,7 @@ HIDDEN_ENV = { "DROIDDECK_EPIC_HIDDEN": "1", "EGL_DISABLE_STORE_PREWARM": "1", } -KEPT_ENV = ("HOME", "USER", "LOGNAME", "LANG", "LANGUAGE", "LC_ALL", "LC_MESSAGES", "TZ", "XDG_RUNTIME_DIR", "BL_LAUNCH_DIR") +KEPT_ENV = ("HOME", "USER", "LOGNAME", "LANG", "LANGUAGE", "LC_ALL", "LC_MESSAGES", "TZ", "XDG_RUNTIME_DIR", "DD_LAUNCH_DIR", "BL_LAUNCH_DIR") LAUNCH_VERBS = ("waitforexitandrun", "run", "runinprefix") EPIC_ARGS = ("-auth_", "-epic") CMD_SPECIAL = "&|<>^" @@ -720,7 +720,7 @@ def clear_playing(): def launch_dir(): - found = os.environ.get("BL_LAUNCH_DIR", "") + found = os.environ.get("DD_LAUNCH_DIR", "") if not found: try: with open(LAUNCH_DIR_FILE, encoding="utf-8") as f: @@ -1234,25 +1234,7 @@ def wait_for(check, timeout, step=0.1): def capped_log(path): - os.makedirs(os.path.dirname(path), exist_ok=True) - handle = open(path, "wb") - read, write = os.pipe() - - def pump(): - written = 0 - with os.fdopen(read, "rb") as source: - while True: - chunk = source.read1(65536) if hasattr(source, "read1") else source.read(65536) - if not chunk: - break - if written < LOG_CAP: - handle.write(chunk[:LOG_CAP - written]) - handle.flush() - written += len(chunk) - handle.close() - - threading.Thread(target=pump, daemon=True).start() - return write + return GAME_DEBUG["capped_log"](path, LOG_CAP)[0] class Session: diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-esync b/tools/linuxfs/overlay/usr/local/bin/droiddeck-esync index d4cb5267ad..a817894ef1 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-esync +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-esync @@ -39,7 +39,7 @@ MIN_NOFILE = 8192 LOG_LINES = 200 LIVE_FILE = "prefixes.json" LIVE_ROWS = 200 -LIVE_KEYS = ("WINESERVER", "BL_SYNC_PACK", "WINEESYNC", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "BL_SYNC", "BL_FSYNC", "WINEFSYNC") +LIVE_KEYS = ("WINESERVER", "DD_SYNC_PACK", "WINEESYNC", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "DD_SYNC", "DD_FSYNC", "WINEFSYNC") CACHE_ROWS = 512 TEMP_AGE = 3600 GC_GRACE = 600 @@ -637,7 +637,7 @@ def app_id(env): def minimum_nofile(env): try: - return int(env.get("BL_SYNC_MIN_NOFILE") or MIN_NOFILE) + return int(env.get("DD_SYNC_MIN_NOFILE") or MIN_NOFILE) except ValueError: return MIN_NOFILE @@ -650,8 +650,8 @@ def log_launch(root, command, env, tool, pack_id): try: soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) line = tsv([[int(time.time()), app_id(env) or "-", command[1] if len(command) > 1 else "-", tool, pack_id or "-", - env.get("WINEESYNC") or "-", env.get("BL_SYNC") or "-", "%s/%s" % (limit(soft), limit(hard)), - env.get("BL_FSYNC") or "-"]]) + env.get("WINEESYNC") or "-", env.get("DD_SYNC") or "-", "%s/%s" % (limit(soft), limit(hard)), + env.get("DD_FSYNC") or "-"]]) def append(text): lines = [entry for entry in text.split("\n") if entry] @@ -704,7 +704,7 @@ def select(command, env): if not prefix or last == "0" or last.startswith("0-"): return result if truthy(env.get("PROTON_NO_NTSYNC")): - env["BL_SYNC"] = "0" + env["DD_SYNC"] = "0" result = (list(command), dict(env)) root = store_root(env) if root is None: @@ -796,7 +796,7 @@ def keep_live(root, command, env, tool): return None if not os.path.isfile(kept_command) or not server_running(prefix): return None - kept_pack = row["env"].get("BL_SYNC_PACK") + kept_pack = row["env"].get("DD_SYNC_PACK", row["env"].get("BL_SYNC_PACK")) if isinstance(kept_pack, str) and kept_pack and command[1:2] == ["waitforexitandrun"]: try: cache = HashCache(root) @@ -808,25 +808,28 @@ def keep_live(root, command, env, tool): pack = {"id": kept_pack} if pack is None or pack["id"] != kept_pack: return None + kept = {("DD_" + name[3:] if name.startswith("BL_") else name): value + for name, value in row["env"].items() if name.startswith("BL_")} + kept.update((name, value) for name, value in row["env"].items() if not name.startswith("BL_")) command, env = list(command), dict(env) command[0] = kept_command for name in LIVE_KEYS: - value = row["env"].get(name) + value = kept.get(name) if isinstance(value, str): env[name] = value else: env.pop(name, None) say("droiddeck-esync: Wine is still running in this prefix; keeping its sync choice (%s)" % describe(env)) - log_launch(root, command, env, tool, env.get("BL_SYNC_PACK")) + log_launch(root, command, env, tool, env.get("DD_SYNC_PACK")) return command, env def describe(env): - if env.get("BL_SYNC") == "1": + if env.get("DD_SYNC") == "1": return "droiddeck-ntsync" - if env.get("BL_FSYNC") == "1": + if env.get("DD_FSYNC") == "1": return "droiddeck-fsync" - if env.get("BL_SYNC_PACK") and truthy(env.get("WINEESYNC")): + if env.get("DD_SYNC_PACK") and truthy(env.get("WINEESYNC")): return "droiddeck-esync" if all(truthy(env.get(name)) for name in WINESERVER_ONLY): return "wineserver" @@ -835,13 +838,13 @@ def describe(env): def fsync_ready(env, measured): listed = "PROTON_NO_FSYNC" not in env and app_id(env) in NOSYNC_APPS - return measured["fsync"] and env.get("BL_SYNC") != "1" and not truthy(env.get("PROTON_NO_FSYNC")) and not listed + return measured["fsync"] and env.get("DD_SYNC") != "1" and not truthy(env.get("PROTON_NO_FSYNC")) and not listed def with_fsync(root, command, env, tool, reason): command, env = list(command), dict(env) - env["BL_FSYNC"] = "1" - env["BL_SYNC"] = "0" + env["DD_FSYNC"] = "1" + env["DD_SYNC"] = "0" env["WINEFSYNC"] = "1" say("droiddeck-fsync: %s; stock binaries with Proton's fsync" % reason) log_launch(root, command, env, tool, None) @@ -855,10 +858,10 @@ def stand_in(root, command, env, tool, reason, measured=None): if truthy(env.get("PROTON_NO_NTSYNC")): say("droiddeck-esync: %s; stock binaries" % reason) elif measured is not None and not measured["ntsync"]: - env["BL_SYNC"] = "0" + env["DD_SYNC"] = "0" say("droiddeck-esync: %s; stock binaries (this Wine has no ntsync)" % reason) else: - env["BL_SYNC"] = "1" + env["DD_SYNC"] = "1" say("droiddeck-esync: %s; stock binaries with droiddeck-ntsync" % reason) log_launch(root, command, env, tool, None) return command, env @@ -880,17 +883,17 @@ def wineserver_only(env): if truthy(env["PROTON_NO_FSYNC"]): env["WINEFSYNC"] = "0" if truthy(env["PROTON_NO_NTSYNC"]): - env["BL_SYNC"] = "0" + env["DD_SYNC"] = "0" return env def choose(root, command, env, tool, stock): name = os.path.basename(tool.rstrip("/")) or tool - wants_fsync = env.get("BL_FSYNC_FIRST") == "1" - if "BL_FSYNC" in env: - env["BL_FSYNC"] = "0" - stock = (stock[0], dict(stock[1], BL_FSYNC="0")) - if env.get("BL_SYNC_FALLBACK") != "1" and not wants_fsync and env.get("BL_SYNC") != "1": + wants_fsync = env.get("DD_FSYNC_FIRST") == "1" + if "DD_FSYNC" in env: + env["DD_FSYNC"] = "0" + stock = (stock[0], dict(stock[1], DD_FSYNC="0")) + if env.get("DD_SYNC_FALLBACK") != "1" and not wants_fsync and env.get("DD_SYNC") != "1": stock = (stock[0], wineserver_only(stock[1])) say("droiddeck-esync: off; wineserver sync only") log_launch(root, stock[0], stock[1], tool, None) @@ -898,14 +901,14 @@ def choose(root, command, env, tool, stock): cache = HashCache(root) try: measured = measure(tool, cache) - if env.get("BL_SYNC") == "1" and not measured["ntsync"]: - env["BL_SYNC"] = "0" - stock = (stock[0], dict(stock[1], BL_SYNC="0")) + if env.get("DD_SYNC") == "1" and not measured["ntsync"]: + env["DD_SYNC"] = "0" + stock = (stock[0], dict(stock[1], DD_SYNC="0")) wants_fsync = True say("droiddeck-ntsync: %s has no ntsync; trying droiddeck-fsync" % name) if wants_fsync and fsync_ready(env, measured): return with_fsync(root, command, env, tool, "chosen for %s" % name) - if env.get("BL_SYNC_FALLBACK") != "1": + if env.get("DD_SYNC_FALLBACK") != "1": say("droiddeck-esync: off") log_launch(root, command, env, tool, None) return stock @@ -936,16 +939,16 @@ def choose(root, command, env, tool, stock): env["WINEESYNC"] = "0" env["PROTON_NO_ESYNC"] = "1" if not truthy(env.get("PROTON_NO_NTSYNC")) and measured["ntsync"]: - env["BL_SYNC"] = "1" + env["DD_SYNC"] = "1" elif not env.get("WINEESYNC"): env["WINEESYNC"] = "1" if truthy(env["WINEESYNC"]) and "PROTON_NO_FSYNC" not in env: env["PROTON_NO_FSYNC"] = "1" env["WINESERVER"] = os.path.join(dist, WINESERVER) - env["BL_SYNC_PACK"] = pack["id"] + env["DD_SYNC_PACK"] = pack["id"] command[0] = os.path.join(dist, os.path.basename(command[0])) say("droiddeck-esync: pack %s for %s (%s, %s match); droiddeck-ntsync %s, droiddeck-esync %s, fds %s/%s" - % (pack["id"], name, measured["version_line"], match_kind(pack, measured), "on" if env.get("BL_SYNC") == "1" else "off", + % (pack["id"], name, measured["version_line"], match_kind(pack, measured), "on" if env.get("DD_SYNC") == "1" else "off", "on" if truthy(env["WINEESYNC"]) else "off", limit(soft), limit(hard))) log_launch(root, command, env, tool, pack["id"]) return command, env @@ -1005,7 +1008,7 @@ def update_wanted(root, fresh, scanned, packs, cache): def reconcile_store(root, steam_root, env): cache = HashCache(root) packs = load_packs(root) - enabled = env.get("BL_SYNC_FALLBACK") == "1" + enabled = env.get("DD_SYNC_FALLBACK") == "1" rows = [] fresh = {} scanned = set() diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex index af04761346..e8edb67d5e 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex @@ -38,7 +38,7 @@ RUNTIMES = {SNIPER_APPID: ("sniper_platform_", "Steam Linux Runtime 3.0 (sniper" SLR4_APPID: ("steamrt4_platform_", "Steam Linux Runtime 4.0 (steamrt4")} MARKER = ".droiddeck-fex" LAYOUT = 1 -ROOTFS_LAYOUT = 4 +ROOTFS_LAYOUT = 10 BLOB_DIRS = re.compile(r"^(?:\.ref|[0-9a-f]{2})$") ROOTFS_LIBRARY_DIRS = ("lib", "lib64") ARCH_DIRS = ("x86_64-linux-gnu", "i386-linux-gnu") @@ -49,10 +49,18 @@ PROVIDED = frozenset(( "libnss_compat.so.2", "libnss_dns.so.2", "libnss_files.so.2", "libnss_hesiod.so.2", "libthread_db.so.1", "libmemusage.so", "libpcprofile.so", "libc_malloc_debug.so.0", "gconv", "libstdc++.so.6", "libgcc_s.so.1", "libssl.so.3", "libcrypto.so.3", + "libfreetype.so.6", "libpng16.so.16", "libbrotlidec.so.1", "libbrotlicommon.so.1", "libbz2.so.1.0", "libz.so.1", + "libwayland-client.so.0", "libwayland-egl.so.1", "libwayland-server.so.0", "libffi.so.8", + "libgbm.so.1", "libdrm.so.2", "libexpat.so.1", )) +PROVIDED_NEEDS = { + "libwayland-client.so.0": ("libffi.so.8",), + "libwayland-server.so.0": ("libffi.so.8",), + "libgbm.so.1": ("libdrm.so.2", "libexpat.so.1"), +} GLIBC_BUILD = re.compile(r"^(?:ld|lib[A-Za-z_]+)-2\.[0-9]+\.so$|^libSegFault\.so$") GUEST_LIBDIRS = (("x86_64", "lib/x86_64-linux-gnu"), ("i386", "lib/i386-linux-gnu")) -PRELOAD_NAMES = ("libblsession.so", "libfakeinput.so") +PRELOAD_NAMES = ("libddsession.so", "libfakeinput.so") FAULT_REPORT = "libfaultreport.so" VULKAN_PIN = "libvulkan-thunk.so" VULKAN_PIN_DIR = "lib/x86_64-linux-gnu/droiddeck/vulkan" @@ -174,7 +182,7 @@ def own_fex_loads(): def update_own_fex(): - wanted = os.environ.get("BL_FEX_TAG") + wanted = os.environ.get("DD_FEX_TAG") if not wanted: return if (read_text(OWN_FEX_TAG) or "").strip() == wanted and own_fex_loads(): @@ -343,10 +351,14 @@ def stays_in_libraries(root, target, link): def mirror(source, provider, name, target, root): - if provider and name in PROVIDED and os.path.lexists(os.path.join(provider, name)): + usable_provider = provider and all(os.path.exists(os.path.join(provider, needed)) + for needed in (name,) + PROVIDED_NEEDS.get(name, ())) + if name in PROVIDED and usable_provider: clone(os.path.join(provider, name), os.path.join(target, name)) return path = os.path.join(source, name) + if not os.path.lexists(path): + return link = os.readlink(path) if os.path.islink(path) else None if link and GLIBC_BUILD.match(os.path.basename(link)): if name not in INTERPRETERS: @@ -365,6 +377,16 @@ def build_rootfs(base, provider): rootfs = os.path.join(STATE, "rootfs") stamp = "%d\n%s\n%s%s\n%s" % (ROOTFS_LAYOUT, os.path.realpath(base), read_text(os.path.join(base_files, MARKER)) or "", os.path.realpath(provider), read_text(os.path.join(provider_files, MARKER)) or "") + for top in ("lib", "lib64"): + for arch in ARCH_DIRS: + for name in sorted(PROVIDED): + path = os.path.join(provider_files, top, arch, name) + try: + info = os.stat(path) + stamp += "\n%s %s %d %d %d %d" % (path, os.path.realpath(path), info.st_ino, info.st_size, + info.st_mtime_ns, info.st_ctime_ns) + except OSError: + stamp += "\n%s missing" % path if read_text(os.path.join(rootfs, MARKER)) == stamp: return False for entry in os.listdir(STATE): @@ -384,7 +406,7 @@ def build_rootfs(base, provider): if entry in ARCH_DIRS and os.path.isdir(path) and not os.path.islink(path): provided = os.path.join(provider_files, top, entry) os.makedirs(os.path.join(tmp, top, entry)) - for name in set(os.listdir(path)) | {name for name in PROVIDED if os.path.lexists(os.path.join(provided, name))}: + for name in set(os.listdir(path)) | {name for name in PROVIDED if os.path.exists(os.path.join(provided, name))}: mirror(path, provided, name, os.path.join(tmp, top, entry), tmp) else: mirror(source, None, entry, os.path.join(tmp, top), tmp) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update index d88a4a97e9..5e663308d1 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-fex-update @@ -55,11 +55,11 @@ fex_ready() { local have ok= have=$(cat /usr/local/share/fex-emu/.droiddeck-tag 2>/dev/null || true) [ -x /usr/local/bin/FEX ] && fex_loads / && ok=1 - if [ -n "${BL_FEX_TAG:-}" ]; then - if [ -n "$ok" ] && [ "$have" = "$BL_FEX_TAG" ]; then FEX_NOW=$have FEX_FROM=catalog; return 0; fi - step "downloading FEX ($BL_FEX_TAG)" - if fex_install "$BL_FEX_TAG" "${BL_FEX_SHA256:-}" "${BL_FEX_URLS:-}"; then FEX_NOW=$BL_FEX_TAG FEX_FROM=catalog; return 0; fi - if [ -n "$ok" ]; then FEX_NOW=$have FEX_FROM="kept; $BL_FEX_TAG did not install"; return 0; fi + if [ -n "${DD_FEX_TAG:-}" ]; then + if [ -n "$ok" ] && [ "$have" = "$DD_FEX_TAG" ]; then FEX_NOW=$have FEX_FROM=catalog; return 0; fi + step "downloading FEX ($DD_FEX_TAG)" + if fex_install "$DD_FEX_TAG" "${DD_FEX_SHA256:-}" "${DD_FEX_URLS:-}"; then FEX_NOW=$DD_FEX_TAG FEX_FROM=catalog; return 0; fi + if [ -n "$ok" ]; then FEX_NOW=$have FEX_FROM="kept; $DD_FEX_TAG did not install"; return 0; fi fi if [ -n "$ok" ] && [ "$have" = "$FEX_TAG" ]; then FEX_NOW=$have FEX_FROM=built-in; return 0; fi step "downloading FEX ($FEX_TAG)" diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-flatpak-run b/tools/linuxfs/overlay/usr/local/bin/droiddeck-flatpak-run index b8210c3550..38088653d9 100644 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-flatpak-run +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-flatpak-run @@ -7,7 +7,7 @@ case ":${XDG_DATA_DIRS:-}:" in *) export XDG_DATA_DIRS=$HOME/.local/share/flatpak/exports/share:${XDG_DATA_DIRS:-/usr/local/share:/usr/share} ;; esac socket=() -if [ -n "${BL_INSIDE:-}" ] || [ -n "${GAMESCOPE_WAYLAND_DISPLAY:-}" ]; then +if [ -n "${DD_INSIDE:-}" ] || [ -n "${GAMESCOPE_WAYLAND_DISPLAY:-}" ]; then unset WAYLAND_DISPLAY export XDG_SESSION_TYPE=x11 socket=(--nosocket=wayland --socket=x11) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-debug b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-debug index df2e704402..9cf741bf87 100644 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-debug +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-debug @@ -1,8 +1,11 @@ #!/usr/bin/python3 +import contextlib import json import os import re import sys +import tempfile +import threading from pathlib import Path GAME_DEBUG_CHANNELS = ( @@ -44,7 +47,7 @@ def load_config(): def session_debug_dir(env): - return env.get("BL_DEBUG_DIR", "") + return env.get("DD_DEBUG_DIR", "") def apply_game_debug_logs(env, config=None, debug_dir=None): @@ -69,3 +72,74 @@ def apply_game_debug_logs(env, config=None, debug_dir=None): "WINEDEBUG": game_debug_channels(env.get("WINEDEBUG"), env.get("PROTON_LOG")), }) return result + + +def capped_log(path, limit, mirror=False): + os.makedirs(os.path.dirname(path), exist_ok=True) + handle = open(path, "wb") + try: + read, write = os.pipe() + except OSError: + handle.close() + raise + + def pump(): + remaining = limit + mirror_ok = mirror + with os.fdopen(read, "rb") as source, handle: + while True: + chunk = source.read1(65536) + if not chunk: + break + saved = chunk[:remaining] + remaining -= len(saved) + if saved: + try: + handle.write(saved) + handle.flush() + except (OSError, ValueError): + remaining = 0 + if mirror_ok: + try: + sys.stderr.write(chunk.decode("utf-8", "replace")) + sys.stderr.flush() + except (OSError, ValueError): + mirror_ok = False + + thread = threading.Thread(target=pump, daemon=True) + thread.start() + return write, thread + + +@contextlib.contextmanager +def desktop_program_logs(env): + program = env.get("DROIDDECK_DESKTOP_PROGRAM") + if program: + env = dict(env) + env.pop("DROIDDECK_DESKTOP_PROGRAM", None) + if not program or env.get("PROTON_LOG", "0") not in ("", "0"): + yield env, None + return + folder = session_debug_dir(env) + try: + if not os.path.isabs(folder) or not os.path.isdir(folder): + raise OSError("session log directory unavailable") + fd, path = tempfile.mkstemp(prefix="desktop-program-", suffix=".log", dir=folder) + os.close(fd) + output, thread = capped_log(path, 1024 * 1024, mirror=True) + except OSError as error: + print("droiddeck-game-env: desktop diagnostics unavailable (%s)" % error, file=sys.stderr) + yield env, None + return + try: + if env.get("WINEDEBUG", "-all") in ("", "-all"): + env["WINEDEBUG"] = "-all,err+all,+mscoree,+loaddll" + try: + print("droiddeck-game-env: desktop program %s; first 1048576 diagnostic bytes: %s" % (program, path), + file=sys.stderr, flush=True) + except OSError: + pass + yield env, output + finally: + os.close(output) + thread.join(timeout=1) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env index 0ba853a6ef..c0685ed7d6 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-game-env @@ -2,6 +2,7 @@ import hashlib import json import os +import platform import re import runpy import signal @@ -14,9 +15,9 @@ GAME_PREFIX = "DROIDDECK_GAME_" GAME_SPLIT_KEYS = ("TU_DEBUG", "MESA_NO_ERROR") CHROMIUM_FILES = {"chrome-sandbox", "chrome_100_percent.pak", "v8_context_snapshot.bin"} D3D9_DEFAULT_MEMORY_MB = 4096 -SYNC_KEYS = ("BL_SYNC", "BL_SYNC_FALLBACK", "BL_FSYNC_FIRST", "BL_SYNC_MIN_NOFILE", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC") +SYNC_KEYS = ("DD_SYNC", "DD_SYNC_FALLBACK", "DD_FSYNC_FIRST", "DD_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") +PACK_KEYS = ("WINESERVER", "DD_SYNC_PACK", "WINEESYNC", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC") GAME_DEBUG = runpy.run_path(str(Path(__file__).with_name("droiddeck-game-debug"))) game_debug_channels = GAME_DEBUG["game_debug_channels"] apply_game_debug_logs = GAME_DEBUG["apply_game_debug_logs"] @@ -85,9 +86,10 @@ def game_files(exe): class Game: - def __init__(self, exe, args): + def __init__(self, exe, args, app_id=""): self.exe = exe self.args = args + self.app_id = app_id self.stem = os.path.splitext(os.path.basename(exe))[0].lower() self.files = game_files(exe) @@ -157,6 +159,12 @@ def ff7_rebirth_feature_level(game): return {"VKD3D_FEATURE_LEVEL": "12_2"}, [], "Final Fantasy VII Rebirth: D3D12 feature level 12_2 (the device-reported level fails its DX12 check)" +@fix +def kcd2_feature_level(game): + if game.app_id == "1771300": + return {"VKD3D_FEATURE_LEVEL": "12_2", "VKD3D_SHADER_MODEL": "6_9"}, [], "Kingdom Come: Deliverance II: D3D12 feature level 12_2 and shader model 6_9 (the detected level fails its startup check, and 12_0 alone stalls on the splash screen)" + + @fix def arkham_city_x87(game): if "batmanac.exe" in game.files: @@ -366,8 +374,8 @@ def offline_without_anticheat(command, env): return command[:2] + [game] + command[3:] -def engine_fixes(exe, args): - game = Game(exe, args) +def engine_fixes(exe, args, app_id=""): + game = Game(exe, args, app_id) env, extra, notes = {}, [], [] for check in FIXES: found = check(game) @@ -452,8 +460,18 @@ def game_gpu(env, keep=False): return result +def split_game_gpu(entries): + result = dict(entries) + for key in GAME_SPLIT_KEYS: + if GAME_PREFIX + key in result: + value = result.pop(GAME_PREFIX + key) + if key not in entries: + result[key] = None if value == "" else value + return result + + def vram_cap(env): - value = env.get("BL_VRAM_MB", "") + value = env.get("DD_VRAM_MB", "") if not re.fullmatch(r"[1-9][0-9]{0,6}", value): return env result = env.copy() @@ -551,7 +569,7 @@ def cpu_topology(env, command=()): if env["WINE_CPU_TOPOLOGY"]: env["PROTON_CPU_TOPOLOGY"] = env["WINE_CPU_TOPOLOGY"] return - picked = bool(env.get("DROIDDECK_GAME_CORES", "").strip() or env.get("BL_GAME_CPUS", "").strip()) + picked = bool(env.get("DROIDDECK_GAME_CORES", "").strip() or env.get("DD_GAME_CPUS", "").strip()) fastest = env.get("DROIDDECK_FASTEST_CORES", "").strip() != "0" and game_id(env) is not None if not (picked or fastest): return @@ -595,12 +613,12 @@ def apply_config(env, config, app_id, fixes=None): if config.get("version") != 1: raise ValueError("unsupported environment configuration") result = env.copy() - entries = dict(config.get("shared", {})) + entries = split_game_gpu(config.get("shared", {})) for name, value in (fixes or {}).items(): if name == "WINEDLLOVERRIDES" and entries.get(name, env.get(name)): value = entries.get(name, env.get(name)) + ";" + value entries[name] = value - game = config.get("games", {}).get(app_id, {}) + game = split_game_gpu(config.get("games", {}).get(app_id, {})) fix = (fixes or {}).get("WINEDLLOVERRIDES") if fix and isinstance(game.get("WINEDLLOVERRIDES"), str): own = game["WINEDLLOVERRIDES"] @@ -632,7 +650,7 @@ def apply_config(env, config, app_id, fixes=None): # An open driver pair (PanVK, RADV) on a GPU that is not an Adreno: vkd3d-proton reports the # driver's own feature level and shader model. The app-wide 12_2 / 6_9 over-promised what PanVK # has, and an Unreal DX12 game took paths that crashed. A game's own setting still wins. - if env.get("BL_OPEN_DRIVER") == "1": + if env.get("DD_OPEN_DRIVER") == "1": game = config.get("games", {}).get(app_id, {}) or {} for name in ("VKD3D_FEATURE_LEVEL", "VKD3D_SHADER_MODEL"): if name not in game and name in result: @@ -667,7 +685,7 @@ def render_path_defaults(command, env): def bridge_feature_level(env): - if env.get("BL_VKBRIDGE") != "1" or env.get("VKD3D_FEATURE_LEVEL") not in ("12_1", "12_2"): + if env.get("DD_VKBRIDGE") != "1" or env.get("VKD3D_FEATURE_LEVEL") not in ("12_1", "12_2"): return None was = env["VKD3D_FEATURE_LEVEL"] env["VKD3D_FEATURE_LEVEL"] = "12_0" @@ -748,11 +766,31 @@ EVALUATOR_SCRIPT = re.compile(r"(?:^|[\\/])evaluatorscript_[0-9]+\.vdf$", re.IGN def mark_install_scripts(command, env): if not any(arg.lower().replace("\\", "/").endswith("iscriptevaluator.exe") for arg in command): return [] - root = env.get("BL_X64_STEAM_ROOT") or env.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or str(Path.home() / ".local/share/Steam") + root = env.get("DD_X64_STEAM_ROOT") or env.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or str(Path.home() / ".local/share/Steam") scripts = [str(Path(root) / arg.replace("\\", "/")) for arg in command if EVALUATOR_SCRIPT.search(arg)] scripts = [path for path in scripts if os.path.isfile(path)] if not scripts: return [] + data = env.get("STEAM_COMPAT_DATA_PATH") + tool = os.path.dirname(command[0]) + new_prefix = data and not os.path.isfile(os.path.join(data, "pfx", "system.reg")) + template = "default_pfx" + if env.get("PROTON_USE_ARM64", "1") == "1" and platform.machine() == "aarch64" and os.path.isdir(os.path.join(tool, "files/bin-arm64")): + template = "default_pfx_arm64" + if new_prefix and not os.path.isfile(os.path.join(tool, "files/share", template, "system.reg")): + try: + subprocess.run([command[0], "run", "cmd.exe", "/c", "exit", "0"], env=env, + stdout=sys.stderr, stderr=sys.stderr, timeout=120, check=False) + except (OSError, subprocess.SubprocessError) as error: + print("droiddeck-game-env: prefix initialization failed (%s)" % error, file=sys.stderr) + try: + wineserver = next((path for path in (os.path.join(tool, "files", name, "wineserver") for name in ("bin-arm64", "bin")) + if os.access(path, os.X_OK)), os.path.join(tool, "files/bin-arm64/wineserver")) + subprocess.run([wineserver, "-w"], env=dict(env, WINEPREFIX=os.path.join(data, "pfx")), + stdout=sys.stderr, stderr=sys.stderr, timeout=120, check=True) + except (OSError, subprocess.SubprocessError) as error: + print("droiddeck-game-env: wineserver wait failed (%s)" % error, file=sys.stderr) + return scripts try: subprocess.run([SEED_REDISTS, root], env=dict(env, DROIDDECK_SEED_SCRIPTS="\n".join(scripts)), stdout=sys.stderr, timeout=60, check=False) @@ -1011,7 +1049,7 @@ def repair_foreign_system_dlls(prefix, proton, env=None): machine = pe_machine(path) if machine is None or PE["machine_compatible"](path, machines, machine, builtins): continue - link = path.parent / (name + ".bl-new") + link = path.parent / (name + ".dd-new") backup = path.parent / (name + FOREIGN_SUFFIX) if backups: backup = path.parent / (name + FOREIGN_SUFFIX + ".%d" % (backups[-1][0] + 1)) @@ -1188,11 +1226,22 @@ def diagnostic_game_exit(app_id, raw_code, source=None, wrapper_status=None): def start(launch, launch_env, digest, after=None, diagnostic_app_id=None): + with GAME_DEBUG["desktop_program_logs"](launch_env) as (env, output): + code = start_process(launch, env, digest, after, diagnostic_app_id, output) + if output is not None: + try: + print("droiddeck-game-env: desktop program exited with status %d" % code, file=sys.stderr, flush=True) + except OSError: + pass + return code + + +def start_process(launch, launch_env, digest, after=None, diagnostic_app_id=None, output=None): if len(launch) > 1 and launch[1] == "waitforexitandrun": ubisoft_composition_off(launch[0], launch_env) launch, launch_env = system_graphics_launch(launch, launch_env) - if after or diagnostic_app_id is not None: - process = subprocess.Popen(launch, env=launch_env) + if after or diagnostic_app_id is not None or output is not None: + process = subprocess.Popen(launch, env=launch_env, stderr=output) if diagnostic_app_id is not None: diagnostic_game_event("game_start", diagnostic_app_id) try: @@ -1269,14 +1318,14 @@ def system_graphics_launch(command, env): def game_logs(command, env, app_id, now=None): """Detailed graphics logs for one game launch, in the session's log folder: Proton's own log, DXVK's and vkd3d-proton's, and the Vulkan driver's startup messages. The app turns this on - (BL_GAME_LOGS=1) on a GPU that is not an Adreno, or with Setup's "Detailed graphics logs".""" - if env.get("BL_GAME_LOGS") != "1" or not env.get("BL_DEBUG_DIR") or len(command) < 3 \ + (DD_GAME_LOGS=1) on a GPU that is not an Adreno, or with Setup's "Detailed graphics logs".""" + if env.get("DD_GAME_LOGS") != "1" or not env.get("DD_DEBUG_DIR") or len(command) < 3 \ or command[1] != "waitforexitandrun": return env import time stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime(now)) name = app_id or re.sub(r"[^A-Za-z0-9._-]+", "_", Path(command[2]).stem)[:40] or "game" - parent = Path(env["BL_DEBUG_DIR"]) / "games" + parent = Path(env["DD_DEBUG_DIR"]) / "games" try: parent.mkdir(parents=True, exist_ok=True) folder = Path(tempfile.mkdtemp(prefix=stamp + "-", suffix="-" + name, dir=parent)) @@ -1302,7 +1351,7 @@ def game_logs(command, env, app_id, now=None): "proton: %s" % command[0], "started: %s" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(now)), ] + ["%s=%s" % (key, env[key]) for key in sorted(env) - if key.startswith(("VK_", "BL_VK", "BL_DRM", "BL_OPEN", "MESA_", "PANVK", "DXVK_", "VKD3D", "ZINK", "TU_", "DROIDDECK_VKD3D"))]) + "\n") + if key.startswith(("VK_", "DD_VK", "DD_DRM", "DD_OPEN", "MESA_", "PANVK", "DXVK_", "VKD3D", "ZINK", "TU_", "DROIDDECK_VKD3D"))]) + "\n") except OSError: pass # Whether the game's sound reaches PulseAudio: the streams 20 s and 60 s in, without waiting. @@ -1327,7 +1376,7 @@ def main(): if not command: return 2 env = game_gpu(os.environ.copy()) - mic_enabled = env.get("BL_MIC_ENABLED") + mic_enabled = env.get("DD_MIC_ENABLED") debug_dir = session_debug_dir(env) prefix_path = env.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/") app_id = game_id(env) @@ -1369,7 +1418,7 @@ def main(): if fixed: print("droiddeck-game-env: replaced foreign-architecture system DLLs with this Proton's own: %s" % ", ".join(fixed), file=sys.stderr) - scripts = mark_install_scripts(command, env) + scripts = mark_install_scripts(command, effective_env) if scripts and install_scripts_done(scripts, env): print("droiddeck-game-env: install scripts already run in this prefix; evaluator skipped", file=sys.stderr) return 0 @@ -1394,7 +1443,7 @@ def main(): death_stranding_allocator(app_id, command[2]) ubisoft_overlay_off(env) project_zomboid_jvm(command) - fixes, extra, notes = engine_fixes(command[2], command[3:]) if len(command) > 2 else ({}, [], []) + fixes, extra, notes = engine_fixes(command[2], command[3:], app_id) if len(command) > 2 else ({}, [], []) if not gl_default: fixes.pop("vblank_mode", None) for note in notes: diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-gog-maintenance b/tools/linuxfs/overlay/usr/local/bin/droiddeck-gog-maintenance index 1fc6e0f37e..ec2aa51854 100644 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-gog-maintenance +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-gog-maintenance @@ -99,11 +99,11 @@ def desktop_environment(base, proc=Path("/proc")): if command != b"/usr/bin/plasmashell": continue values = dict(os.fsdecode(item).split("=", 1) for item in (entry / "environ").read_bytes().split(b"\0") if b"=" in item) - if values.get("BL_DESKTOP") != "1" or values.get("XDG_RUNTIME_DIR") != env.get("XDG_RUNTIME_DIR"): + if values.get("DD_DESKTOP") != "1" or values.get("XDG_RUNTIME_DIR") != env.get("XDG_RUNTIME_DIR"): continue if not values.get("DISPLAY") or values.get("WAYLAND_DISPLAY") == env.get("WAYLAND_DISPLAY"): continue - for key in ("DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS", "BL_DESKTOP"): + for key in ("DISPLAY", "WAYLAND_DISPLAY", "XAUTHORITY", "DBUS_SESSION_BUS_ADDRESS", "DD_DESKTOP"): if key in values: env[key] = values[key] return env @@ -130,10 +130,10 @@ def runner(folder, appid, game, graphical=False): raise ValueError("No Proton tool is installed for this game") tool, command = available[name] base = desktop_environment(os.environ) if graphical else dict(os.environ) - env = run["environment"](base, target, tool, root, window=base.get("BL_DESKTOP") == "1") + env = run["environment"](base, target, tool, root, window=base.get("DD_DESKTOP") == "1") env["DROIDDECK_GOG_MAINTENANCE"] = "1" env["FEX_X87REDUCEDPRECISION"] = "0" - env.pop("BL_STORE_EXIT", None) + env.pop("DD_STORE_EXIT", None) return str(Path(tool) / command), env, target.compatdata diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-gpu-window b/tools/linuxfs/overlay/usr/local/bin/droiddeck-gpu-window index 5fc4e20a02..9616ea3248 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-gpu-window +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-gpu-window @@ -44,8 +44,8 @@ def advertise_compositing(): if __name__ == '__main__': if len(sys.argv) < 2: raise SystemExit('usage: droiddeck-gpu-window [args...]') - if 'BL_GPU_CHILD_WSI' in os.environ: - wsi = os.environ.pop('BL_GPU_CHILD_WSI') + if 'DD_GPU_CHILD_WSI' in os.environ: + wsi = os.environ.pop('DD_GPU_CHILD_WSI') if wsi: os.environ['MESA_VK_WSI_DEBUG'] = wsi else: diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-ime b/tools/linuxfs/overlay/usr/local/bin/droiddeck-ime index 4f110cfbc6..d6fd4cd3bc 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-ime +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-ime @@ -84,8 +84,8 @@ def connect(): def main(): - launch = os.environ.get("BL_LAUNCH_DIR", "") - report = Report(os.environ.get("BL_IME_DIR") or (os.path.join(launch, "agent") if launch else "")) + launch = os.environ.get("DD_LAUNCH_DIR", "") + report = Report(os.environ.get("DD_IME_DIR") or (os.path.join(launch, "agent") if launch else "")) conn = Connection(connect()) conn.send(DISPLAY_ID, 1, struct.pack("/dev/null || true - echo "== open files: soft/hard $bl_nofile_was -> soft $(ulimit -Sn)" - [ -n "${BL_DEBUG_DIR:-}" ] && echo "soft/hard $bl_nofile_was -> soft $(ulimit -Sn) (session tree)" > "$BL_DEBUG_DIR/limits.txt" 2>/dev/null - unset bl_nofile_was + echo "== open files: soft/hard $dd_nofile_was -> soft $(ulimit -Sn)" + [ -n "${DD_DEBUG_DIR:-}" ] && echo "soft/hard $dd_nofile_was -> soft $(ulimit -Sn) (session tree)" > "$DD_DEBUG_DIR/limits.txt" 2>/dev/null + unset dd_nofile_was fi export HOME=${HOME:-/root} mode=${1:-desktop} @@ -16,32 +16,32 @@ shift || true step() { echo "== STEP $(date -u +%H:%M:%S.%3N) $*"; } 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" + [ -z "${DD_STEAM_EXIT_FILE:-}" ] || printf '%s\n' "$1" > "$DD_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 - mv -f "$BL_LOG" "$BL_LOG.1" +if [ -n "${DD_LOG:-}" ] && [ -z "${DD_INSIDE:-}" ]; then + mkdir -p "$(dirname "$DD_LOG")" 2>/dev/null + if [ "$(stat -c %s "$DD_LOG" 2>/dev/null || echo 0)" -gt 8388608 ]; then + mv -f "$DD_LOG" "$DD_LOG.1" fi dd=$(command -v gnudd || echo dd) - exec > >({ "$dd" of="$BL_LOG" oflag=append conv=notrunc iflag=count_bytes count="${BL_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1 + exec > >({ "$dd" of="$DD_LOG" oflag=append conv=notrunc iflag=count_bytes count="${DD_LOG_CAP:-268435456}" bs=65536 status=none; cat >/dev/null; }) 2>&1 echo "== droiddeck-session $(date) mode=$mode $*" - echo "== uid=$(id -u) size=${BL_WIDTH:-?}x${BL_HEIGHT:-?} icd=${VK_ICD_FILENAMES:-none}" + echo "== uid=$(id -u) size=${DD_WIDTH:-?}x${DD_HEIGHT:-?} icd=${VK_ICD_FILENAMES:-none}" echo "== gamescope: $(gamescope --version 2>&1 | head -1) at $(command -v gamescope)" echo "== rootfs: $(cat /.version 2>/dev/null || echo unversioned)" fi start_diagnostic_inventory() { [ "${DROIDDECK_ENHANCED_DIAGNOSTICS:-0}" = 1 ] || return 0 - [ -z "${BL_INSIDE:-}" ] || return 0 + [ -z "${DD_INSIDE:-}" ] || return 0 if ! command -v droiddeck-diagnostic-inventory >/dev/null 2>&1; then printf '%s\n' 'DROIDDECK_PROCESS_TRACE {"schema":1,"event":"provider","status":"unavailable"}' return 0 fi droiddeck-diagnostic-inventory --watch --root-pid "$$" & - _bl_diagnostic_inventory=$! - trap 'kill "$_bl_diagnostic_inventory" 2>/dev/null || true; wait "$_bl_diagnostic_inventory" 2>/dev/null || true' EXIT + _dd_diagnostic_inventory=$! + trap 'kill "$_dd_diagnostic_inventory" 2>/dev/null || true; wait "$_dd_diagnostic_inventory" 2>/dev/null || true' EXIT } start_diagnostic_inventory @@ -104,7 +104,7 @@ prepare_locale() { printf '%s\n' "$want" > "$stamp" echo "== locale archive built for $want" } -[ -z "${BL_INSIDE:-}" ] && prepare_locale +[ -z "${DD_INSIDE:-}" ] && prepare_locale clear_stale_tmp() { local running names=() n @@ -129,26 +129,26 @@ clear_stale_tmp() { [ "$n" -gt 0 ] && echo "== /tmp: cleared $n entries earlier sessions left" return 0 } -[ -z "${BL_INSIDE:-}" ] && clear_stale_tmp -if [ -z "${BL_INSIDE:-}" ]; then - if [ "${BL_ZRAM:-0}" = 1 ]; then printf 0 > /tmp/.bl-zram; else rm -f /tmp/.bl-zram; fi - dd if=/dev/zero of=/tmp/.bl-clock bs=8 count=1 conv=notrunc status=none +[ -z "${DD_INSIDE:-}" ] && clear_stale_tmp +if [ -z "${DD_INSIDE:-}" ]; then + if [ "${DD_ZRAM:-0}" = 1 ]; then printf 0 > /tmp/.dd-zram; else rm -f /tmp/.dd-zram; fi + dd if=/dev/zero of=/tmp/.dd-clock bs=8 count=1 conv=notrunc status=none fi steam_devtools() { - _bl_cdp=() + _dd_cdp=() if [ -f "$steam_root/.cef-enable-remote-debugging" ]; then if timeout 5 python3 -c 'import socket, sys s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(("127.0.0.1", int(sys.argv[1])))' "$1" 2>/dev/null; then - BL_CDP_PORT=$1 + DD_CDP_PORT=$1 return 0 fi echo "== steam: port $1 is held by another app; Decky cannot load this session and Steam's devtools use another port" fi - BL_CDP_PORT=$((20000 + RANDOM % 30000)) - _bl_cdp=(-cef-enable-debugging -devtools-port "$BL_CDP_PORT") + DD_CDP_PORT=$((20000 + RANDOM % 30000)) + _dd_cdp=(-cef-enable-debugging -devtools-port "$DD_CDP_PORT") } steam_update_stuck() { @@ -170,7 +170,7 @@ run_gamescope() ( local status_file child_status compositor_status status_file=$(mktemp "${XDG_RUNTIME_DIR:-/tmp}/droiddeck-steam-exit.XXXXXX") || exit 73 trap 'rm -f "$status_file"' EXIT - BL_STEAM_EXIT_FILE="$status_file" gamescope "$@" + DD_STEAM_EXIT_FILE="$status_file" gamescope "$@" compositor_status=$? if read -r child_status < "$status_file" && [[ $child_status =~ ^[0-9]{1,3}$ ]] \ && [ "$child_status" -le 255 ]; then @@ -185,47 +185,47 @@ run_gamescope() ( ) collect_steam_logs() { - [ -n "${BL_DEBUG_DIR:-}" ] || return 0 + [ -n "${DD_DEBUG_DIR:-}" ] || return 0 local sync_store=$HOME/.local/share/droiddeck-esync sync_file - if [ -d "$sync_store" ] && mkdir -p "$BL_DEBUG_DIR/droiddeck-esync" 2>/dev/null; then + if [ -d "$sync_store" ] && mkdir -p "$DD_DEBUG_DIR/droiddeck-esync" 2>/dev/null; then for sync_file in launches.log tools.tsv wanted.tsv prefixes.json; do - [ -f "$sync_store/$sync_file" ] && cp "$sync_store/$sync_file" "$BL_DEBUG_DIR/droiddeck-esync/" 2>/dev/null + [ -f "$sync_store/$sync_file" ] && cp "$sync_store/$sync_file" "$DD_DEBUG_DIR/droiddeck-esync/" 2>/dev/null done fi local fex_state=$HOME/.local/share/droiddeck-fex - if [ -d "$fex_state" ] && mkdir -p "$BL_DEBUG_DIR/droiddeck-fex" 2>/dev/null; then - cp "$fex_state/status.json" "$fex_state/config/Config.json" "$BL_DEBUG_DIR/droiddeck-fex/" 2>/dev/null + if [ -d "$fex_state" ] && mkdir -p "$DD_DEBUG_DIR/droiddeck-fex" 2>/dev/null; then + cp "$fex_state/status.json" "$fex_state/config/Config.json" "$DD_DEBUG_DIR/droiddeck-fex/" 2>/dev/null fi } -trap 'bl_stopping=1; collect_steam_logs 2>/dev/null || true' TERM INT HUP -if [ -n "${BL_VK_DRIVER:-}" ]; then - bl_icd_lib=$(sed -n 's/.*"library_path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$BL_VK_DRIVER" 2>/dev/null | head -1) - bl_icd_lib=$(printf '%s' "$bl_icd_lib" | sed 's|\\/|/|g') - case $bl_icd_lib in +trap 'dd_stopping=1; collect_steam_logs 2>/dev/null || true' TERM INT HUP +if [ -n "${DD_VK_DRIVER:-}" ]; then + dd_icd_lib=$(sed -n 's/.*"library_path"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$DD_VK_DRIVER" 2>/dev/null | head -1) + dd_icd_lib=$(printf '%s' "$dd_icd_lib" | sed 's|\\/|/|g') + case $dd_icd_lib in /*) ;; - ?*) bl_icd_lib="$(dirname "$BL_VK_DRIVER")/$bl_icd_lib" ;; + ?*) dd_icd_lib="$(dirname "$DD_VK_DRIVER")/$dd_icd_lib" ;; esac - if [ -r "$BL_VK_DRIVER" ] && [ -n "$bl_icd_lib" ] && [ -r "$bl_icd_lib" ]; then - export VK_DRIVER_FILES="$BL_VK_DRIVER" - export VK_ICD_FILENAMES="$BL_VK_DRIVER" - echo "== vulkan driver: imported $bl_icd_lib (via $BL_VK_DRIVER)" + if [ -r "$DD_VK_DRIVER" ] && [ -n "$dd_icd_lib" ] && [ -r "$dd_icd_lib" ]; then + export VK_DRIVER_FILES="$DD_VK_DRIVER" + export VK_ICD_FILENAMES="$DD_VK_DRIVER" + echo "== vulkan driver: imported $dd_icd_lib (via $DD_VK_DRIVER)" else - echo "== vulkan driver: IGNORING $BL_VK_DRIVER (manifest or ${bl_icd_lib:-library} unreadable); using the runtime's own" + echo "== vulkan driver: IGNORING $DD_VK_DRIVER (manifest or ${dd_icd_lib:-library} unreadable); using the runtime's own" fi - unset bl_icd_lib + unset dd_icd_lib fi -bl_webhelper_layout() { - if [ -n "${BL_VKBRIDGE_WEBHELPER_ARGS:-}" ]; then - printf '%s\n' "$BL_VKBRIDGE_WEBHELPER_ARGS" - elif [ -z "${BL_VKBRIDGE_CEF_ANGLE:-}" ]; then +dd_webhelper_layout() { + if [ -n "${DD_VKBRIDGE_WEBHELPER_ARGS:-}" ]; then + printf '%s\n' "$DD_VKBRIDGE_WEBHELPER_ARGS" + elif [ -z "${DD_VKBRIDGE_CEF_ANGLE:-}" ]; then echo stock - elif [ "$BL_VKBRIDGE_CEF_ANGLE" = vulkan ] && [ "${BL_VKBRIDGE_CEF_VULKAN:-1}" != 0 ]; then + elif [ "$DD_VKBRIDGE_CEF_ANGLE" = vulkan ] && [ "${DD_VKBRIDGE_CEF_VULKAN:-1}" != 0 ]; then echo "--use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan" else - echo "--use-gl=angle --use-angle=$BL_VKBRIDGE_CEF_ANGLE" + echo "--use-gl=angle --use-angle=$DD_VKBRIDGE_CEF_ANGLE" fi } -bl_now_ms() { +dd_now_ms() { if [ -n "${EPOCHREALTIME:-}" ]; then local t=${EPOCHREALTIME/[.,]/} echo $((10#$t / 1000)) @@ -240,15 +240,15 @@ vkbridge_wait_socket() { echo "== vkbridge: server socket ready (waited 0 ms)" return 0 fi - start=$(bl_now_ms) + start=$(dd_now_ms) while :; do - now=$(bl_now_ms) + now=$(dd_now_ms) waited=$((now - start)) if [ -S "$sock" ]; then echo "== vkbridge: server socket ready (waited $waited ms; the server listens after its startup probe)" return 0 fi - if [ -n "${bl_stopping:-}" ]; then + if [ -n "${dd_stopping:-}" ]; then echo "== vkbridge: no server socket after $waited ms; the session is stopping" return 1 fi @@ -259,63 +259,66 @@ vkbridge_wait_socket() { sleep 0.05 done } -if [ "${BL_VKBRIDGE:-0}" = 1 ]; then - bl_vkb_icd=/usr/local/share/vkbridge/droidbridge_icd.json - [ -z "${BL_INSIDE:-}" ] && vkbridge_wait_socket "${VKBRIDGE_SOCKET:-}" "${BL_VKBRIDGE_WAIT_MS:-10000}" - bl_vkb_missing= - [ -r "$bl_vkb_icd" ] || bl_vkb_missing="$bl_vkb_missing icd" - [ -r /usr/local/lib/vkbridge/libvulkan_droidbridge.so ] || bl_vkb_missing="$bl_vkb_missing library" - [ -S "${VKBRIDGE_SOCKET:-}" ] || bl_vkb_missing="$bl_vkb_missing socket" - if [ -z "$bl_vkb_missing" ]; then - export VK_DRIVER_FILES=$bl_vkb_icd VK_ICD_FILENAMES=$bl_vkb_icd +if [ "${DD_VKBRIDGE:-0}" = 1 ]; then + dd_vkb_icd=/usr/local/share/vkbridge/droidbridge_icd.json + [ -z "${DD_INSIDE:-}" ] && vkbridge_wait_socket "${VKBRIDGE_SOCKET:-}" "${DD_VKBRIDGE_WAIT_MS:-10000}" + dd_vkb_missing= + [ -r "$dd_vkb_icd" ] || dd_vkb_missing="$dd_vkb_missing icd" + [ -r /usr/local/lib/vkbridge/libvulkan_droidbridge.so ] || dd_vkb_missing="$dd_vkb_missing library" + [ -S "${VKBRIDGE_SOCKET:-}" ] || dd_vkb_missing="$dd_vkb_missing socket" + if [ -z "$dd_vkb_missing" ]; then + export VK_DRIVER_FILES=$dd_vkb_icd VK_ICD_FILENAMES=$dd_vkb_icd export VKBRIDGE_SOCKET VKBRIDGE_CLIENT_LOG if [ -r /root/.vkbridge-env ]; then while IFS='=' read -r _k _v; do - case "$_k" in VKBRIDGE_*|BL_VKBRIDGE_*) export "$_k=$_v" ;; esac + case "$_k" in VKBRIDGE_*|DD_VKBRIDGE_*) export "$_k=$_v" ;; esac done < /root/.vkbridge-env - [ -z "${BL_INSIDE:-}" ] && echo "== vkbridge: development settings from /root/.vkbridge-env: $(cut -d= -f1 /root/.vkbridge-env | tr '\n' ' ')" + while IFS='=' read -r _k _v; do + case "$_k" in BL_VKBRIDGE_*) grep -q "^DD_${_k#BL_}=" /root/.vkbridge-env || export "DD_${_k#BL_}=$_v" ;; esac + done < /root/.vkbridge-env + [ -z "${DD_INSIDE:-}" ] && echo "== vkbridge: development settings from /root/.vkbridge-env: $(cut -d= -f1 /root/.vkbridge-env | tr '\n' ' ')" fi export VKD3D_FEATURE_LEVEL=${VKD3D_FEATURE_LEVEL:-12_0} unset TU_DEBUG - if [ -z "${BL_INSIDE:-}" ]; then + if [ -z "${DD_INSIDE:-}" ]; then step "vkbridge self-test" - bl_vkb_smoke=$(timeout 60 /usr/local/bin/droiddeck-vkbridge-smoke 2>&1) - printf '%s\n' "$bl_vkb_smoke" | sed 's/^/== vkbridge: /' - bl_vkb_why= - if printf '%s\n' "$bl_vkb_smoke" | grep -qE '^FAIL memory sharing'; then - bl_vkb_why=memory - elif printf '%s\n' "$bl_vkb_smoke" | grep -qE '^FAIL (image clear|draw)'; then - bl_vkb_why=draw + dd_vkb_smoke=$(timeout 60 /usr/local/bin/droiddeck-vkbridge-smoke 2>&1) + printf '%s\n' "$dd_vkb_smoke" | sed 's/^/== vkbridge: /' + dd_vkb_why= + if printf '%s\n' "$dd_vkb_smoke" | grep -qE '^FAIL memory sharing'; then + dd_vkb_why=memory + elif printf '%s\n' "$dd_vkb_smoke" | grep -qE '^FAIL (image clear|draw)'; then + dd_vkb_why=draw fi - if [ -n "$bl_vkb_why" ] && [ -r "${BL_VKBRIDGE_FALLBACK_ICD:-}" ]; then - export VK_DRIVER_FILES=$BL_VKBRIDGE_FALLBACK_ICD VK_ICD_FILENAMES=$BL_VKBRIDGE_FALLBACK_ICD BL_VKBRIDGE=0 - export BL_OPEN_DRIVER=1 BL_DRM_STANDIN=/dev/mali0 - [ "${BL_STEAM_GPU_COMPOSITING:-0}" = 1 ] || export BL_STEAM_SOFT_COMPOSITING=1 - if [ "$bl_vkb_why" = memory ]; then - echo "== vkbridge: memory sharing = none (no method passed the server's self-test); this session uses the PanVK pair instead ($BL_VKBRIDGE_FALLBACK_ICD)" + if [ -n "$dd_vkb_why" ] && [ -r "${DD_VKBRIDGE_FALLBACK_ICD:-}" ]; then + export VK_DRIVER_FILES=$DD_VKBRIDGE_FALLBACK_ICD VK_ICD_FILENAMES=$DD_VKBRIDGE_FALLBACK_ICD DD_VKBRIDGE=0 + export DD_OPEN_DRIVER=1 DD_DRM_STANDIN=/dev/mali0 + [ "${DD_STEAM_GPU_COMPOSITING:-0}" = 1 ] || export DD_STEAM_SOFT_COMPOSITING=1 + if [ "$dd_vkb_why" = memory ]; then + echo "== vkbridge: memory sharing = none (no method passed the server's self-test); this session uses the PanVK pair instead ($DD_VKBRIDGE_FALLBACK_ICD)" else - echo "== vkbridge: self-test failed images or draws; this session uses the PanVK pair instead ($BL_VKBRIDGE_FALLBACK_ICD)" + echo "== vkbridge: self-test failed images or draws; this session uses the PanVK pair instead ($DD_VKBRIDGE_FALLBACK_ICD)" fi - [ -n "${BL_DEBUG_DIR:-}" ] && printf '%s\n%s\n' "$BL_VKBRIDGE_FALLBACK_ICD" "$bl_vkb_why" > "$BL_DEBUG_DIR/vkbridge-fallback" 2>/dev/null - elif [ -n "$bl_vkb_why" ]; then - echo "== vkbridge: self-test failed ($bl_vkb_why) and no PanVK pair is installed to fall back on; expect a black screen or a lost device - set a Mali driver pair in Setup" + [ -n "${DD_DEBUG_DIR:-}" ] && printf '%s\n%s\n' "$DD_VKBRIDGE_FALLBACK_ICD" "$dd_vkb_why" > "$DD_DEBUG_DIR/vkbridge-fallback" 2>/dev/null + elif [ -n "$dd_vkb_why" ]; then + echo "== vkbridge: self-test failed ($dd_vkb_why) and no PanVK pair is installed to fall back on; expect a black screen or a lost device - set a Mali driver pair in Setup" fi - unset bl_vkb_why - unset bl_vkb_smoke + unset dd_vkb_why + unset dd_vkb_smoke if command -v vulkaninfo >/dev/null 2>&1; then timeout 30 vulkaninfo --summary 2>&1 | sed -n '/^Devices:/,$p' | head -40 | sed 's/^/== vulkaninfo: /' fi fi - [ "${BL_VKBRIDGE:-0}" = 1 ] && echo "== vulkan driver: Mali bridge ($bl_vkb_icd, server at $VKBRIDGE_SOCKET)" + [ "${DD_VKBRIDGE:-0}" = 1 ] && echo "== vulkan driver: Mali bridge ($dd_vkb_icd, server at $VKBRIDGE_SOCKET)" else - echo "== vulkan driver: Mali bridge requested but NOT usable (icd $bl_vkb_icd, socket ${VKBRIDGE_SOCKET:-unset}; missing:$bl_vkb_missing)" - [ -n "${BL_INSIDE:-}" ] || exit 69 + echo "== vulkan driver: Mali bridge requested but NOT usable (icd $dd_vkb_icd, socket ${VKBRIDGE_SOCKET:-unset}; missing:$dd_vkb_missing)" + [ -n "${DD_INSIDE:-}" ] || exit 69 fi - unset bl_vkb_icd bl_vkb_missing + unset dd_vkb_icd dd_vkb_missing fi -if [ "${BL_VENUS:-0}" = 1 ] && [ -z "${BL_INSIDE:-}" ] && command -v vulkaninfo >/dev/null 2>&1; then - if bl_vn_info=$(timeout 30 vulkaninfo 2>/dev/null); then - case $(printf '%s\n' "$bl_vn_info" | grep -m1 'nullDescriptor') in +if [ "${DD_VENUS:-0}" = 1 ] && [ -z "${DD_INSIDE:-}" ] && command -v vulkaninfo >/dev/null 2>&1; then + if dd_vn_info=$(timeout 30 vulkaninfo 2>/dev/null); then + case $(printf '%s\n' "$dd_vn_info" | grep -m1 'nullDescriptor') in *true*) echo "== venus: nullDescriptor present (Zink keeps the GPU)" ;; *) export GALLIUM_DRIVER=llvmpipe LIBGL_ALWAYS_SOFTWARE=1 @@ -326,21 +329,21 @@ if [ "${BL_VENUS:-0}" = 1 ] && [ -z "${BL_INSIDE:-}" ] && command -v vulkaninfo else echo "== venus: vulkaninfo failed or timed out; GL left on Zink" fi - unset bl_vn_info + unset dd_vn_info fi -if [ "${BL_GAME_LOGS:-0}" = 1 ] && [ -z "${BL_INSIDE:-}" ] && [ -n "${BL_DEBUG_DIR:-}" ]; then +if [ "${DD_GAME_LOGS:-0}" = 1 ] && [ -z "${DD_INSIDE:-}" ] && [ -n "${DD_DEBUG_DIR:-}" ]; then ( { - echo "== VK_DRIVER_FILES=${VK_DRIVER_FILES:-} VK_ICD_FILENAMES=${VK_ICD_FILENAMES:-} BL_DRM_STANDIN=${BL_DRM_STANDIN:-}" + echo "== VK_DRIVER_FILES=${VK_DRIVER_FILES:-} VK_ICD_FILENAMES=${VK_ICD_FILENAMES:-} DD_DRM_STANDIN=${DD_DRM_STANDIN:-}" if command -v vulkaninfo >/dev/null 2>&1; then timeout 10 vulkaninfo --summary echo "== vulkaninfo exit: $?" - if timeout 20 vulkaninfo > "$BL_DEBUG_DIR/vulkan-full.txt" 2>&1; then + if timeout 20 vulkaninfo > "$DD_DEBUG_DIR/vulkan-full.txt" 2>&1; then echo "== device extensions (full list in vulkan-full.txt):" - sed -n '/^Device Extensions:/,/^$/p' "$BL_DEBUG_DIR/vulkan-full.txt" | grep -o 'VK_[A-Za-z0-9_]*' | sort -u | tr '\n' ' ' | fold -s -w 200 + sed -n '/^Device Extensions:/,/^$/p' "$DD_DEBUG_DIR/vulkan-full.txt" | grep -o 'VK_[A-Za-z0-9_]*' | sort -u | tr '\n' ' ' | fold -s -w 200 echo echo "== key features:" - grep -E '^[[:space:]]+(robustBufferAccess2?|robustImageAccess2?|nullDescriptor|logicOp|fillModeNonSolid|shaderClipDistance|shaderCullDistance|dualSrcBlend|geometryShader|scalarBlockLayout|timelineSemaphore|dynamicRendering|synchronization2|maintenance4|maintenance5|maintenance6|shaderDrawParameters|descriptorIndexing|bufferDeviceAddress|vulkanMemoryModel|hostQueryReset|imagelessFramebuffer|samplerYcbcrConversion|shaderInt64|shaderFloat64|shaderInt16|shaderFloat16|storageBuffer16BitAccess|extendedDynamicState[23]?|vertexInputDynamicState|customBorderColors|customBorderColorWithoutFormat|depthClipEnable|multiViewport|textureCompressionBC|indexTypeUint8|rectangularLines|bresenhamLines|transformFeedback|geometryStreams|graphicsPipelineLibrary|pushDescriptor|primitiveTopologyListRestart|dynamicRenderingLocalRead|shaderDemoteToHelperInvocation|subgroupSizeControl|computeFullSubgroups|inlineUniformBlock|pipelineCreationCacheControl) = ' "$BL_DEBUG_DIR/vulkan-full.txt" | sed 's/^[[:space:]]*/ /' | sort -u + grep -E '^[[:space:]]+(robustBufferAccess2?|robustImageAccess2?|nullDescriptor|logicOp|fillModeNonSolid|shaderClipDistance|shaderCullDistance|dualSrcBlend|geometryShader|scalarBlockLayout|timelineSemaphore|dynamicRendering|synchronization2|maintenance4|maintenance5|maintenance6|shaderDrawParameters|descriptorIndexing|bufferDeviceAddress|vulkanMemoryModel|hostQueryReset|imagelessFramebuffer|samplerYcbcrConversion|shaderInt64|shaderFloat64|shaderInt16|shaderFloat16|storageBuffer16BitAccess|extendedDynamicState[23]?|vertexInputDynamicState|customBorderColors|customBorderColorWithoutFormat|depthClipEnable|multiViewport|textureCompressionBC|indexTypeUint8|rectangularLines|bresenhamLines|transformFeedback|geometryStreams|graphicsPipelineLibrary|pushDescriptor|primitiveTopologyListRestart|dynamicRenderingLocalRead|shaderDemoteToHelperInvocation|subgroupSizeControl|computeFullSubgroups|inlineUniformBlock|pipelineCreationCacheControl) = ' "$DD_DEBUG_DIR/vulkan-full.txt" | sed 's/^[[:space:]]*/ /' | sort -u else echo "== full vulkaninfo failed or timed out (exit $?)" fi @@ -348,19 +351,19 @@ if [ "${BL_GAME_LOGS:-0}" = 1 ] && [ -z "${BL_INSIDE:-}" ] && [ -n "${BL_DEBUG_D echo "== vulkaninfo is not in this runtime; GPU nodes:" ls -l /dev/kgsl-3d0 /dev/mali0 /dev/dri 2>&1 fi - } > "$BL_DEBUG_DIR/vulkan-summary.txt" 2>&1 + } > "$DD_DEBUG_DIR/vulkan-summary.txt" 2>&1 ) & fi -export GAMESCOPE_FORCE_VULKAN_REALTIME=${BL_GAMESCOPE_REALTIME:-0} +export GAMESCOPE_FORCE_VULKAN_REALTIME=${DD_GAMESCOPE_REALTIME:-0} start_agent() { - [ -n "${BL_LAUNCH_DIR:-}" ] && [ -x /usr/local/bin/droiddeck-agent ] || return 0 - mkdir -p "$BL_LAUNCH_DIR/agent" + [ -n "${DD_LAUNCH_DIR:-}" ] && [ -x /usr/local/bin/droiddeck-agent ] || return 0 + mkdir -p "$DD_LAUNCH_DIR/agent" /usr/local/bin/droiddeck-agent "$@" 2>&1 & } nap() { - [ -n "${bl_nap_fd:-}" ] || exec {bl_nap_fd}<> <(:) - read -r -t "$1" -u "$bl_nap_fd" _ 2>/dev/null || : + [ -n "${dd_nap_fd:-}" ] || exec {dd_nap_fd}<> <(:) + read -r -t "$1" -u "$dd_nap_fd" _ 2>/dev/null || : } # Which program a driver error came from: Mesa's lines ("radv/amdgpu: The CS has been rejected", # "ZINK: vkQueueWaitIdle failed") carry no process name. For the first three minutes of an open @@ -368,7 +371,7 @@ nap() { # line count at that moment, so an error's line number in session.log points at what had just # started. Pure bash over /proc (no execs: see nap). watch_processes() { - local out=$BL_DEBUG_DIR/processes.txt log=$BL_DEBUG_DIR/session.log i p pid comm lines + local out=$DD_DEBUG_DIR/processes.txt log=$DD_DEBUG_DIR/session.log i p pid comm lines local -a argv new local -A seen=() echo "# seconds session.log-lines pid name command line" > "$out" 2>/dev/null || return 0 @@ -391,7 +394,7 @@ watch_processes() { nap 0.5 done } -if [ "${BL_OPEN_DRIVER:-0}" = 1 ] && [ -z "${BL_INSIDE:-}" ] && [ -n "${BL_DEBUG_DIR:-}" ]; then +if [ "${DD_OPEN_DRIVER:-0}" = 1 ] && [ -z "${DD_INSIDE:-}" ] && [ -n "${DD_DEBUG_DIR:-}" ]; then watch_processes & fi export XDG_DATA_HOME=${XDG_DATA_HOME:-$HOME/.local/share} @@ -424,9 +427,9 @@ client_single_core_matches() { } program_cores() { - [ "${BL_PIN_CORES:-1}" = 0 ] && return 0 + [ "${DD_PIN_CORES:-1}" = 0 ] && return 0 command -v taskset >/dev/null 2>&1 || return 0 - if [ -n "${BL_GAME_CPUS:-}" ]; then echo "$BL_GAME_CPUS"; return 0; fi + if [ -n "${DD_GAME_CPUS:-}" ]; then echo "$DD_GAME_CPUS"; return 0; fi [ "$mode" = run ] && return 0 local f n max min= list= for f in /sys/devices/system/cpu/cpu[0-9]*/cpufreq/cpuinfo_max_freq; do @@ -442,7 +445,7 @@ program_cores() { echo "$list" } -if [ -z "${BL_INSIDE:-}" ]; then +if [ -z "${DD_INSIDE:-}" ]; then /usr/local/bin/droiddeck-fonts 2>&1 | sed 's/^/[fonts] /' device_fonts=/usr/local/share/fonts/android if [ -d "$device_fonts" ] && [ -d /etc/fonts/conf.d ] && command -v fc-cache >/dev/null 2>&1; then @@ -493,13 +496,13 @@ if [ -z "${BL_INSIDE:-}" ]; then fi exec /usr/local/bin/droiddeck-desktop fi - width=${BL_WIDTH:-1280} - height=${BL_HEIGHT:-720} + width=${DD_WIDTH:-1280} + height=${DD_HEIGHT:-720} nested=$width nested_h=$height - if [ "${BL_FOLLOW_OUTPUT:-0}" = 1 ]; then + if [ "${DD_FOLLOW_OUTPUT:-0}" = 1 ]; then echo "== gamescope: the output follows the screen (${width}x${height} to start)" - elif [ "$mode" = steam ] && [ "${BL_GAMESCOPE_STRETCH_16X9:-0}" = 1 ]; then + elif [ "$mode" = steam ] && [ "${DD_GAMESCOPE_STRETCH_16X9:-0}" = 1 ]; then wide=$(( (height * 16 + 4) / 9 / 2 * 2 )) tall=$(( (width * 9 + 8) / 16 / 2 * 2 )) if [ "$wide" -gt "$width" ]; then @@ -511,47 +514,47 @@ if [ -z "${BL_INSIDE:-}" ]; then echo "== gamescope: games at ${nested}x${nested_h} stretched to the ${width}x${height} output" fi fi - if [ "$mode" = run ] && [ "${BL_GAME_WIDTH:-0}" -gt 0 ] && [ "${BL_GAME_HEIGHT:-0}" -gt 0 ]; then - nested=$BL_GAME_WIDTH - nested_h=$BL_GAME_HEIGHT + if [ "$mode" = run ] && [ "${DD_GAME_WIDTH:-0}" -gt 0 ] && [ "${DD_GAME_HEIGHT:-0}" -gt 0 ]; then + nested=$DD_GAME_WIDTH + nested_h=$DD_GAME_HEIGHT game_size=1 echo "== gamescope: the game runs at ${nested}x${nested_h}, scaled to the ${width}x${height} output with its proportions kept" fi - backend=${BL_GAMESCOPE_BACKEND:-wayland} + backend=${DD_GAMESCOPE_BACKEND:-wayland} case "$backend" in wayland) ;; sdl) export SDL_VIDEODRIVER=wayland ;; *) echo "== unsupported gamescope backend: $backend"; exit 64 ;; esac - if [ "$mode" = steam ] && [ "${BL_CURSOR_COMPOSITE:-0}" = 1 ]; then + if [ "$mode" = steam ] && [ "${DD_CURSOR_COMPOSITE:-0}" = 1 ]; then export gamescope_cursor_composite=2 fi # Through the Mali bridge, Steam's UI flickered while gamescope handed its layers to the phone's # compositor as separate planes, for a reason not yet found; one composited image does not # (Mali-G76 MC4: 145 footer flips in 6 s at rest, 0 composited). - if [ "$mode" = steam ] && [ "${BL_VKBRIDGE:-0}" = 1 ] && [ -z "${gamescope_composite_force:-}" ]; then + if [ "$mode" = steam ] && [ "${DD_VKBRIDGE:-0}" = 1 ] && [ -z "${gamescope_composite_force:-}" ]; then export gamescope_composite_force=1 echo "== gamescope: composites every frame (Mali bridge: the Steam UI flickers on separate planes)" fi args=(--backend "$backend" --expose-wayland -f -W "$width" -H "$height" -w "$nested" -h "$nested_h") if [ "${game_size:-0}" != 1 ] && { [ "$nested" != "$width" ] || [ "$nested_h" != "$height" ]; }; then args+=(-S stretch) - export BL_STRETCHED=1 + export DD_STRETCHED=1 fi - if [ "${BL_REFRESH:-0}" -gt 0 ]; then - args+=(-r "$BL_REFRESH") + if [ "${DD_REFRESH:-0}" -gt 0 ]; then + args+=(-r "$DD_REFRESH") export GAMESCOPE_NESTED_REFRESH_FOLLOWS_HOST=1 fi - [ "$mode" = steam ] && [ "${BL_STEAM_UI:-}" != desktop ] && args+=(-e) - if [ "$mode" = steam ] && [ "${BL_XWAYLAND_COUNT:-2}" -gt 1 ]; then - args+=(--xwayland-count "${BL_XWAYLAND_COUNT:-2}") + [ "$mode" = steam ] && [ "${DD_STEAM_UI:-}" != desktop ] && args+=(-e) + if [ "$mode" = steam ] && [ "${DD_XWAYLAND_COUNT:-2}" -gt 1 ]; then + args+=(--xwayland-count "${DD_XWAYLAND_COUNT:-2}") export STEAM_MULTIPLE_XWAYLANDS=1 fi [ "$mode" = steam ] && args+=(--default-touch-mode 4) - [ "${BL_HDR:-0}" = 1 ] && args+=(--hdr-enabled) - [ -n "${BL_GAMESCOPE_ARGS:-}" ] && read -r -a _bl_extra <<<"$BL_GAMESCOPE_ARGS" && args+=("${_bl_extra[@]}") - if [ "$mode" = steam ] && [ "${BL_MANGOAPP:-1}" = 1 ] \ - && [ "${BL_STEAM_UI:-}" != desktop ] && command -v mangoapp >/dev/null 2>&1; then + [ "${DD_HDR:-0}" = 1 ] && args+=(--hdr-enabled) + [ -n "${DD_GAMESCOPE_ARGS:-}" ] && read -r -a _dd_extra <<<"$DD_GAMESCOPE_ARGS" && args+=("${_dd_extra[@]}") + if [ "$mode" = steam ] && [ "${DD_MANGOAPP:-1}" = 1 ] \ + && [ "${DD_STEAM_UI:-}" != desktop ] && command -v mangoapp >/dev/null 2>&1; then MANGOHUD_CONFIGFILE=/tmp/droiddeck-mangohud.conf echo no_display > "$MANGOHUD_CONFIGFILE" export MANGOHUD_CONFIGFILE STEAM_USE_MANGOAPP=1 STEAM_MANGOAPP_PRESETS_SUPPORTED=1 STEAM_MANGOAPP_HORIZONTAL_SUPPORTED=1 @@ -559,7 +562,7 @@ if [ -z "${BL_INSIDE:-}" ]; then echo "== gamescope: mangoapp on ($(command -v mangoapp), config $MANGOHUD_CONFIGFILE)" fi mkdir -p /run/droiddeck-hud && export DROIDDECK_HUD_FRAMES=/run/droiddeck-hud/frames - export BL_INSIDE=1 + export DD_INSIDE=1 rm -f "${XDG_RUNTIME_DIR:-/tmp}"/gamescope-limiter-* export GAMESCOPE_LIMITER_FILE="${XDG_RUNTIME_DIR:-/tmp}/droiddeck-gamescope-limiter" rm -f "$GAMESCOPE_LIMITER_FILE" @@ -570,21 +573,21 @@ if [ -z "${BL_INSIDE:-}" ]; then echo "== pipewire: not running; Remote Play and game recording have no picture" fi run_gamescope "${args[@]}" -- "$0" "$mode" "$@" - _bl_status=$? + _dd_status=$? /usr/local/bin/droiddeck-pipewire stop - exit $_bl_status + exit $_dd_status fi exec gamescope "${args[@]}" -- "$0" "$mode" "$@" fi -bl_displays() { +dd_displays() { printf '%s\n' "$DISPLAY" [ -n "${STEAM_GAME_DISPLAY_0:-}" ] && [ "$STEAM_GAME_DISPLAY_0" != "$DISPLAY" ] && printf '%s\n' "$STEAM_GAME_DISPLAY_0" return 0 } -bl_xprop_set_all() { +dd_xprop_set_all() { local d ok=1 - for d in $(bl_displays); do + for d in $(dd_displays); do DISPLAY=$d xprop -root -f "$1" 32c -set "$1" "$2" 2>/dev/null || ok=0 done [ "$ok" = 1 ] @@ -609,11 +612,11 @@ reap_orphans() { done } -if [ "${BL_DESKTOP:-}" != 1 ] && [ -n "${BL_ANDROID_CLIPBOARD:-}" ] && [ -x /usr/local/bin/droiddeck-clipboard ]; then - /usr/local/bin/droiddeck-clipboard "$BL_ANDROID_CLIPBOARD" & +if [ "${DD_DESKTOP:-}" != 1 ] && [ -n "${DD_ANDROID_CLIPBOARD:-}" ] && [ -x /usr/local/bin/droiddeck-clipboard ]; then + /usr/local/bin/droiddeck-clipboard "$DD_ANDROID_CLIPBOARD" & fi -[ "${BL_DESKTOP:-}" = 1 ] || start_agent +[ "${DD_DESKTOP:-}" = 1 ] || start_agent case $mode in desktop) @@ -644,8 +647,8 @@ case $mode in wait "$child" || rc=$? [ "$forwarded" = 1 ] || break done - if [ -n "${BL_LAUNCH_DIR:-}" ]; then - printf '%s\n' "$rc" > "$BL_LAUNCH_DIR/run-status.tmp" && mv -f "$BL_LAUNCH_DIR/run-status.tmp" "$BL_LAUNCH_DIR/run-status" + if [ -n "${DD_LAUNCH_DIR:-}" ]; then + printf '%s\n' "$rc" > "$DD_LAUNCH_DIR/run-status.tmp" && mv -f "$DD_LAUNCH_DIR/run-status.tmp" "$DD_LAUNCH_DIR/run-status" fi exit "$rc" } @@ -679,20 +682,20 @@ case $mode in 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 + [ "${DD_STEAM_CLIENT_ARCH:-}" = x86_64 ] && steam_x64=1 steam_cef_gpu=1 if [ "$steam_x64" = 1 ]; then step "checking the Steam client's arm64 parts (first run downloads them, ~1-2 min)" - _bl_x64_repair=0 - [ -e "$HOME/.bl-steam-repair" ] && _bl_x64_repair=1 + _dd_x64_repair=0 + [ -e "$HOME/.dd-steam-repair" ] && _dd_x64_repair=1 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 || steam_setup_failed $? + DD_X64_REPAIR=$_dd_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_root=${DD_X64_HOME:-$HOME/.droiddeck-x64}/.local/share/Steam steam_client=(droiddeck-steam-x64 --exec) - if [ "${BL_X64_X86_WEBHELPER:-0}" = 1 ] && + if [ "${DD_X64_X86_WEBHELPER:-0}" = 1 ] && ! droiddeck-steam-x64 --webhelper-gpu; then steam_cef_gpu=0 fi @@ -701,68 +704,68 @@ case $mode in 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 + if [ -f "${DD_X64_HOME:-$HOME/.droiddeck-x64}/.local/share/Steam/local.vdf" ]; then droiddeck-steam-x64 --sync-login || true droiddeck-steam-x64 --share || true fi steam_client=("$steam_root/steamrtarm64/steam") - _bl_srt_shim=$HOME/.droiddeck-steamrt-shim - if droiddeck-steamrt-shim "$steam_root/steamrtarm64" "$_bl_srt_shim"; then - echo "== steam: Valve containerized the arm64 Steam client (it carries a Steam Runtime container); starting it through $_bl_srt_shim" - steam_client=(env STEAM_RUNTIME_STEAMRT="$_bl_srt_shim" PATH="$_bl_srt_shim/bin:$PATH" "${steam_client[@]}") + _dd_srt_shim=$HOME/.droiddeck-steamrt-shim + if droiddeck-steamrt-shim "$steam_root/steamrtarm64" "$_dd_srt_shim"; then + echo "== steam: Valve containerized the arm64 Steam client (it carries a Steam Runtime container); starting it through $_dd_srt_shim" + steam_client=(env STEAM_RUNTIME_STEAMRT="$_dd_srt_shim" PATH="$_dd_srt_shim/bin:$PATH" "${steam_client[@]}") fi fi - _bl_proton_root=$steam_root + _dd_proton_root=$steam_root if [ "$steam_x64" = 1 ]; then - _bl_proton_root=$XDG_DATA_HOME/Steam - if ! ls -d "$_bl_proton_root"/compatibilitytools.d/GE-Proton*-aarch64 >/dev/null 2>&1 && - ! grep -q '^ge' "$HOME/.bl-proton-extra" 2>/dev/null; then - echo ge >> "$HOME/.bl-proton-extra" + _dd_proton_root=$XDG_DATA_HOME/Steam + if ! ls -d "$_dd_proton_root"/compatibilitytools.d/GE-Proton*-aarch64 >/dev/null 2>&1 && + ! grep -q '^ge' "$HOME/.dd-proton-extra" 2>/dev/null; then + echo ge >> "$HOME/.dd-proton-extra" fi fi - if [ -s "$HOME/.bl-proton-extra" ]; then - _bl_left=$HOME/.bl-proton-extra.left - : > "$_bl_left" - _bl_got_proton=0 - while read -r _bl_extra || [ -n "$_bl_extra" ]; do - case ${_bl_extra# } in ""|"#"*) continue ;; esac - step "installing Proton '$_bl_extra' (large download, several minutes)" - if droiddeck-proton-extra "$_bl_proton_root" $_bl_extra; then - _bl_got_proton=1 - step "installed Proton '$_bl_extra'" + if [ -s "$HOME/.dd-proton-extra" ]; then + _dd_left=$HOME/.dd-proton-extra.left + : > "$_dd_left" + _dd_got_proton=0 + while read -r _dd_extra || [ -n "$_dd_extra" ]; do + case ${_dd_extra# } in ""|"#"*) continue ;; esac + step "installing Proton '$_dd_extra' (large download, several minutes)" + if droiddeck-proton-extra "$_dd_proton_root" $_dd_extra; then + _dd_got_proton=1 + step "installed Proton '$_dd_extra'" else - step "Proton '$_bl_extra' failed; will retry next session" - echo "$_bl_extra" >> "$_bl_left" + step "Proton '$_dd_extra' failed; will retry next session" + echo "$_dd_extra" >> "$_dd_left" fi - done < "$HOME/.bl-proton-extra" - mv -f "$_bl_left" "$HOME/.bl-proton-extra" - if [ "$steam_x64" = 1 ] && [ "$_bl_got_proton" = 1 ]; then + done < "$HOME/.dd-proton-extra" + mv -f "$_dd_left" "$HOME/.dd-proton-extra" + if [ "$steam_x64" = 1 ] && [ "$_dd_got_proton" = 1 ]; then droiddeck-steam-x64 --prepare || true fi fi - if [ -s "$HOME/.bl-steam-urls" ]; then - while read -r _bl_url || [ -n "$_bl_url" ]; do - case ${_bl_url# } in steam://*) ;; *) continue ;; esac - step "asking the client for $_bl_url" - set -- "$@" "$_bl_url" - done < "$HOME/.bl-steam-urls" - rm -f "$HOME/.bl-steam-urls" + if [ -s "$HOME/.dd-steam-urls" ]; then + while read -r _dd_url || [ -n "$_dd_url" ]; do + case ${_dd_url# } in steam://*) ;; *) continue ;; esac + step "asking the client for $_dd_url" + set -- "$@" "$_dd_url" + done < "$HOME/.dd-steam-urls" + rm -f "$HOME/.dd-steam-urls" fi - if [ -n "${BL_CLIENT_CPUS:-}" ]; then - step "client cores: $BL_CLIENT_CPUS" + if [ -n "${DD_CLIENT_CPUS:-}" ]; then + step "client cores: $DD_CLIENT_CPUS" fi - if [ "${BL_ZRAM:-0}" = 1 ]; then + if [ "${DD_ZRAM:-0}" = 1 ]; then step "zRAM compression: on" - [ "${BL_ZRAM_CLIENT:-1}" = 1 ] || step "zRAM: Steam, the hidden Epic Games Launcher and Battle.net are not compressed while games run (turned off in Performance)" - _bl_ram_cap=0 - case ${BL_RAM_CAP_MB:-} in + [ "${DD_ZRAM_CLIENT:-1}" = 1 ] || step "zRAM: Steam, the hidden Epic Games Launcher and Battle.net are not compressed while games run (turned off in Performance)" + _dd_ram_cap=0 + case ${DD_RAM_CAP_MB:-} in ''|0) ;; - *[!0-9]*|0*|???????*) step "RAM cap: ignored invalid value '$BL_RAM_CAP_MB'" ;; - *) _bl_ram_cap=$((BL_RAM_CAP_MB * 1024)); step "RAM cap: ${BL_RAM_CAP_MB} MB" ;; + *[!0-9]*|0*|???????*) step "RAM cap: ignored invalid value '$DD_RAM_CAP_MB'" ;; + *) _dd_ram_cap=$((DD_RAM_CAP_MB * 1024)); step "RAM cap: ${DD_RAM_CAP_MB} MB" ;; esac ( - bl_zram_scan() { - _bl_game=0 _bl_pids=() _bl_others=() _bl_apps= + dd_zram_scan() { + _dd_game=0 _dd_pids=() _dd_others=() _dd_apps= local _d _c _args _name _a _id _fex _lower _bnet=() _bnet_game=0 for _d in /proc/[0-9]*; do [ "${_d##*/}" != "$BASHPID" ] || continue @@ -780,21 +783,21 @@ case $mode in AppId=769) ;; AppId=[0-9]*) _id=${_a#AppId=} - case $_id in *[!0-9]*) ;; *) _bl_game=1; _bl_apps="$_bl_apps $_id" ;; esac + case $_id in *[!0-9]*) ;; *) _dd_game=1; _dd_apps="$_dd_apps $_id" ;; esac ;; esac done ;; - steam|steamwebhelper) _bl_pids+=("${_d##*/}") ;; + steam|steamwebhelper) _dd_pids+=("${_d##*/}") ;; *) _lower=${_name,,} if [ "$_fex" = 1 ] && grep -qz '^DROIDDECK_EPIC_HIDDEN=1$' "$_d/environ" 2>/dev/null; then - _bl_pids+=("${_d##*/}") + _dd_pids+=("${_d##*/}") elif [[ $_lower == [a-z]:[\\/]'program files (x86)'[\\/]battle.net[\\/]* || $_lower == [a-z]:[\\/]programdata[\\/]battle.net[\\/]* ]]; then _bnet+=("${_d##*/}") else - _bl_others+=("${_d##*/}") + _dd_others+=("${_d##*/}") if [[ $_lower == [a-z]:[\\/]* ]]; then case ${_lower##*[\\/]} in agent.exe|conhost.exe|explorer.exe|lsass.exe|plugplay.exe|rpcss.exe|services.exe|start.exe|\ @@ -811,12 +814,12 @@ case $mode in esac done if [ "$_bnet_game" = 1 ]; then - _bl_pids+=("${_bnet[@]}") + _dd_pids+=("${_bnet[@]}") else - _bl_others+=("${_bnet[@]}") + _dd_others+=("${_bnet[@]}") fi } - bl_zram_usage() { + dd_zram_usage() { local _p _k _v _u _resident _anonymous _rss=0 _anon=0 _swap=0 for _p in "$@"; do _resident=0 _anonymous=-1 @@ -831,25 +834,25 @@ case $mode in [ "$_anonymous" -ge 0 ] || _anonymous=$_resident _rss=$((_rss + _resident)) _anon=$((_anon + _anonymous)) done - _bl_rss=$_rss _bl_anon=$_anon - _bl_swap=$_swap + _dd_rss=$_rss _dd_anon=$_anon + _dd_swap=$_swap echo "$# processes, resident $((_rss / 1024)) MB, in zram $((_swap / 1024)) MB" } - bl_memory_read() { + dd_memory_read() { local _k _v _u _kind _fields _avg _whole _frac _gpu_bytes _growth _saved_growth _saved_fall - _saved_growth=${_bl_preserved_growth:-0} _saved_fall=${_bl_preserved_fall:-0} - _bl_preserved_growth=0 _bl_preserved_fall=0 - _bl_mem_total=0 _bl_available=-1 _bl_swap_total=0 _bl_swap_free=-1 - _bl_psi_some=0 _bl_psi_full=0 _bl_gpu=0 _bl_unevictable=0 _bl_shmem=0 + _saved_growth=${_dd_preserved_growth:-0} _saved_fall=${_dd_preserved_fall:-0} + _dd_preserved_growth=0 _dd_preserved_fall=0 + _dd_mem_total=0 _dd_available=-1 _dd_swap_total=0 _dd_swap_free=-1 + _dd_psi_some=0 _dd_psi_full=0 _dd_gpu=0 _dd_unevictable=0 _dd_shmem=0 while read -r _k _v _u; do case $_v in ''|*[!0-9]*) continue ;; esac case $_k in - MemTotal:) _bl_mem_total=$_v ;; - MemAvailable:) _bl_available=$_v ;; - SwapTotal:) _bl_swap_total=$_v ;; - SwapFree:) _bl_swap_free=$_v ;; - Unevictable:) _bl_unevictable=$_v ;; - Shmem:) _bl_shmem=$_v ;; + MemTotal:) _dd_mem_total=$_v ;; + MemAvailable:) _dd_available=$_v ;; + SwapTotal:) _dd_swap_total=$_v ;; + SwapFree:) _dd_swap_free=$_v ;; + Unevictable:) _dd_unevictable=$_v ;; + Shmem:) _dd_shmem=$_v ;; esac done 2>/dev/null < /proc/meminfo if [ -r /proc/pressure/memory ]; then @@ -862,329 +865,366 @@ case $mode in _frac=${_frac:0:2} case $_whole$_frac in ''|*[!0-9]*) continue ;; esac if [ "$_kind" = some ]; then - _bl_psi_some=$((10#$_whole * 100 + 10#$_frac)) + _dd_psi_some=$((10#$_whole * 100 + 10#$_frac)) else - _bl_psi_full=$((10#$_whole * 100 + 10#$_frac)) + _dd_psi_full=$((10#$_whole * 100 + 10#$_frac)) fi done 2>/dev/null < /proc/pressure/memory fi if [ -r /sys/class/kgsl/kgsl/page_alloc ]; then read -r _gpu_bytes _u < /sys/class/kgsl/kgsl/page_alloc case $_gpu_bytes in ''|*[!0-9]*) _gpu_bytes=0 ;; esac - _bl_gpu=$((_gpu_bytes / 1024)) + _dd_gpu=$((_gpu_bytes / 1024)) fi - _bl_psi=$_bl_psi_some - [ "$_bl_psi_full" -gt "$_bl_psi" ] && _bl_psi=$_bl_psi_full - if [ "${_bl_sample_at:-}" = "" ]; then - _bl_growth=0 _bl_fall=0 - _bl_sample_at=$SECONDS _bl_sample_available=$_bl_available _bl_sample_gpu=$_bl_gpu - _bl_sample_unevictable=$_bl_unevictable _bl_sample_shmem=$_bl_shmem - elif [ "$SECONDS" -gt "$_bl_sample_at" ]; then - _bl_growth=0 _bl_fall=0 - _growth=$((_bl_gpu - _bl_sample_gpu)); [ "$_growth" -gt 0 ] && _bl_growth=$((_bl_growth + _growth)) - _growth=$((_bl_unevictable - _bl_sample_unevictable)); [ "$_growth" -gt 0 ] && _bl_growth=$((_bl_growth + _growth)) - _growth=$((_bl_shmem - _bl_sample_shmem)); [ "$_growth" -gt 0 ] && _bl_growth=$((_bl_growth + _growth)) - _bl_fall=$((_bl_sample_available - _bl_available)) - [ "$_saved_growth" -gt "$_bl_growth" ] && _bl_growth=$_saved_growth - [ "$_saved_fall" -gt "$_bl_fall" ] && _bl_fall=$_saved_fall - _bl_sample_at=$SECONDS _bl_sample_available=$_bl_available _bl_sample_gpu=$_bl_gpu - _bl_sample_unevictable=$_bl_unevictable _bl_sample_shmem=$_bl_shmem + _dd_psi=$_dd_psi_some + [ "$_dd_psi_full" -gt "$_dd_psi" ] && _dd_psi=$_dd_psi_full + if [ "${_dd_sample_at:-}" = "" ]; then + _dd_growth=0 _dd_fall=0 + _dd_sample_at=$SECONDS _dd_sample_available=$_dd_available _dd_sample_gpu=$_dd_gpu + _dd_sample_unevictable=$_dd_unevictable _dd_sample_shmem=$_dd_shmem + elif [ "$SECONDS" -gt "$_dd_sample_at" ]; then + _dd_growth=0 _dd_fall=0 + _growth=$((_dd_gpu - _dd_sample_gpu)); [ "$_growth" -gt 0 ] && _dd_growth=$((_dd_growth + _growth)) + _growth=$((_dd_unevictable - _dd_sample_unevictable)); [ "$_growth" -gt 0 ] && _dd_growth=$((_dd_growth + _growth)) + _growth=$((_dd_shmem - _dd_sample_shmem)); [ "$_growth" -gt 0 ] && _dd_growth=$((_dd_growth + _growth)) + _dd_fall=$((_dd_sample_available - _dd_available)) + [ "$_saved_growth" -gt "$_dd_growth" ] && _dd_growth=$_saved_growth + [ "$_saved_fall" -gt "$_dd_fall" ] && _dd_fall=$_saved_fall + if [ $((SECONDS - _dd_sample_at)) -ge 5 ]; then + _dd_sample_at=$SECONDS _dd_sample_available=$_dd_available _dd_sample_gpu=$_dd_gpu + _dd_sample_unevictable=$_dd_unevictable _dd_sample_shmem=$_dd_shmem + fi fi - _bl_real_available=$_bl_available - [ "$_bl_real_available" -ge 0 ] && _bl_real_available=$((_bl_real_available - _bl_growth)) - _bl_headroom=$((_bl_mem_total / 5)) - [ "$_bl_headroom" -ge $((512 * 1024)) ] || _bl_headroom=$((512 * 1024)) - [ "$_bl_headroom" -le $((1536 * 1024)) ] || _bl_headroom=$((1536 * 1024)) - _bl_tier_headroom=$((_bl_mem_total / 4)) - [ "$_bl_tier_headroom" -ge $((768 * 1024)) ] || _bl_tier_headroom=$((768 * 1024)) - [ "$_bl_tier_headroom" -le $((2560 * 1024)) ] || _bl_tier_headroom=$((2560 * 1024)) - _bl_swap_reserve=$((_bl_swap_total / 5)) - [ "$_bl_swap_reserve" -ge $((256 * 1024)) ] || _bl_swap_reserve=$((256 * 1024)) + _dd_real_available=$_dd_available + [ "$_dd_real_available" -ge 0 ] && _dd_real_available=$((_dd_real_available - _dd_growth)) + _dd_headroom=$((_dd_mem_total / 5)) + [ "$_dd_headroom" -ge $((512 * 1024)) ] || _dd_headroom=$((512 * 1024)) + [ "$_dd_headroom" -le $((1536 * 1024)) ] || _dd_headroom=$((1536 * 1024)) + _dd_tier_headroom=$((_dd_mem_total / 4)) + [ "$_dd_tier_headroom" -ge $((768 * 1024)) ] || _dd_tier_headroom=$((768 * 1024)) + [ "$_dd_tier_headroom" -le $((2560 * 1024)) ] || _dd_tier_headroom=$((2560 * 1024)) + _dd_fall_headroom=$((_dd_tier_headroom * 2)) + [ "$_dd_fall_headroom" -ge $((_dd_mem_total * 2 / 5)) ] || _dd_fall_headroom=$((_dd_mem_total * 2 / 5)) + _dd_swap_reserve=$((_dd_swap_total / 5)) + [ "$_dd_swap_reserve" -ge $((256 * 1024)) ] || _dd_swap_reserve=$((256 * 1024)) } - bl_memory_tight() { - [ "$_bl_mem_total" -gt 0 ] && [ "$_bl_available" -ge 0 ] && - { [ "$_bl_real_available" -lt "$_bl_headroom" ] || - { [ "$_bl_psi" -ge 100 ] && [ "$_bl_real_available" -lt $((_bl_mem_total / 3)) ]; } || - { [ "$_bl_fall" -ge $((256 * 1024)) ] && [ "$_bl_real_available" -lt $((_bl_headroom * 2)) ]; }; } + dd_memory_tight() { + [ "$_dd_mem_total" -gt 0 ] && [ "$_dd_available" -ge 0 ] && + { [ "$_dd_real_available" -lt "$_dd_headroom" ] || + { [ "$_dd_psi" -ge 100 ] && [ "$_dd_real_available" -lt $((_dd_mem_total / 3)) ]; } || + { [ "$_dd_fall" -ge $((256 * 1024)) ] && [ "$_dd_real_available" -lt $((_dd_headroom * 2)) ]; }; } } - bl_client_can_pageout() { - bl_memory_read - bl_zram_usage "${_bl_pids[@]}" > /dev/null - [ "$_bl_mem_total" -gt 0 ] && bl_zram_has_room + dd_client_can_pageout() { + dd_memory_read + dd_zram_usage "${_dd_pids[@]}" > /dev/null + [ "$_dd_mem_total" -gt 0 ] && dd_zram_has_room } - bl_zram_has_room() { - [ "$_bl_swap_total" -gt 0 ] && - [ $((_bl_swap_free - _bl_anon - ${_bl_client_reserve:-0})) -ge "$_bl_swap_reserve" ] + dd_zram_has_room() { + [ "$_dd_swap_total" -gt 0 ] && + [ $((_dd_swap_free - _dd_anon - ${_dd_client_reserve:-0})) -ge "$_dd_swap_reserve" ] } - bl_client_can_readback() { - bl_memory_read - bl_zram_usage "${_bl_pids[@]}" > /dev/null - [ "$_bl_mem_total" -gt 0 ] && ! bl_memory_tight && ! bl_memory_critical && - [ "$_bl_real_available" -ge $((_bl_swap * 2)) ] && - [ $((_bl_real_available - _bl_swap)) -ge "$_bl_headroom" ] + dd_client_can_readback() { + dd_memory_read + dd_zram_usage "${_dd_pids[@]}" > /dev/null + [ "$_dd_mem_total" -gt 0 ] && ! dd_memory_tight && ! dd_memory_critical && + [ "$_dd_real_available" -ge $((_dd_swap * 2)) ] && + [ $((_dd_real_available - _dd_swap)) -ge "$_dd_headroom" ] } - bl_client_pressure() { - [ "${BL_ZRAM_CLIENT:-1}" = 1 ] && [ "$_bl_game" = 1 ] && - [ "${#_bl_pids[@]}" -gt 0 ] && { bl_memory_tight || bl_memory_critical; } || return 0 - [ "$_bl_pressure_at" -lt 0 ] || - [ $((SECONDS - _bl_pressure_at)) -ge "$_bl_pressure_backoff" ] || return 0 - [ "$_bl_packed" -lt 0 ] || [ $((SECONDS - _bl_packed)) -ge 30 ] || return 0 - _bl_pressure_at=$SECONDS - if ! bl_client_can_pageout; then - step "zRAM: pressure reclaim skipped, swap headroom too small ($((_bl_swap_free / 1024)) MB free)" + dd_client_pressure() { + [ "${DD_ZRAM_CLIENT:-1}" = 1 ] && [ "$_dd_game" = 1 ] && + [ "${#_dd_pids[@]}" -gt 0 ] && { dd_memory_tight || dd_memory_critical; } || return 0 + [ "$_dd_pressure_at" -lt 0 ] || + [ $((SECONDS - _dd_pressure_at)) -ge "$_dd_pressure_backoff" ] || return 0 + [ "$_dd_packed" -lt 0 ] || [ $((SECONDS - _dd_packed)) -ge 30 ] || return 0 + _dd_pressure_at=$SECONDS + if ! dd_client_can_pageout; then + step "zRAM: pressure reclaim skipped, swap headroom too small ($((_dd_swap_free / 1024)) MB free)" return 0 fi - [ "$_bl_rss" -ge $((128 * 1024)) ] || return 0 - _bl_pressure_before=$_bl_rss + [ "$_dd_rss" -ge $((128 * 1024)) ] || return 0 + _dd_pressure_before=$_dd_rss if [ "${1:-}" = defer ]; then - _bl_client_reserve=$_bl_anon - _bl_client_pending=1 + _dd_client_reserve=$_dd_anon + _dd_client_pending=1 fi - bl_zram_send 1 "memory pressure, compressing the client (available $((_bl_available / 1024)) MB, swap free $((_bl_swap_free / 1024)) MB)" client "${1:-}" - _bl_packed=$SECONDS + dd_zram_send 1 "memory pressure, compressing the client (available $((_dd_available / 1024)) MB, swap free $((_dd_swap_free / 1024)) MB)" client "${1:-}" + _dd_packed=$SECONDS if [ "${1:-}" = defer ]; then - _bl_client_targets=("${_bl_zram_targets[@]}") + _dd_client_targets=("${_dd_zram_targets[@]}") else - bl_client_pressure_result + dd_client_pressure_result fi } - bl_client_pressure_finish() { - [ "${_bl_client_pending:-0}" = 1 ] || return 0 - bl_zram_finish 1 "${_bl_client_targets[@]}" - bl_client_pressure_result "${_bl_client_targets[@]}" - _bl_client_pending=0 _bl_client_reserve=0 _bl_client_targets=() + dd_client_pressure_finish() { + [ "${_dd_client_pending:-0}" = 1 ] || return 0 + dd_zram_finish 1 "${_dd_client_targets[@]}" + dd_client_pressure_result "${_dd_client_targets[@]}" + _dd_client_pending=0 _dd_client_reserve=0 _dd_client_targets=() } - bl_client_pressure_result() { - [ "${_bl_pageout_complete:-0}" = 1 ] || return 0 - if [ "$#" -gt 0 ]; then bl_zram_usage "$@" > /dev/null; else bl_zram_usage "${_bl_pids[@]}" > /dev/null; fi - if [ $((_bl_pressure_before - _bl_rss)) -lt $((16 * 1024)) ]; then - _bl_pressure_backoff=$((_bl_pressure_backoff * 2 > 300 ? 300 : _bl_pressure_backoff * 2)) + dd_client_pressure_result() { + [ "${_dd_pageout_complete:-0}" = 1 ] || return 0 + if [ "$#" -gt 0 ]; then dd_zram_usage "$@" > /dev/null; else dd_zram_usage "${_dd_pids[@]}" > /dev/null; fi + if [ $((_dd_pressure_before - _dd_rss)) -lt $((16 * 1024)) ]; then + _dd_pressure_backoff=$((_dd_pressure_backoff * 2 > 300 ? 300 : _dd_pressure_backoff * 2)) else - _bl_pressure_backoff=30 + _dd_pressure_backoff=30 fi } - bl_memory_critical() { - [ "$_bl_mem_total" -gt 0 ] && [ "$_bl_available" -ge 0 ] && - { [ "$_bl_real_available" -lt "$_bl_tier_headroom" ] || - { [ "$_bl_psi" -ge 100 ] && [ "$_bl_real_available" -lt $((_bl_tier_headroom * 3 / 2)) ]; } || - { [ "$_bl_fall" -ge $((256 * 1024)) ] && [ "$_bl_real_available" -lt $((_bl_tier_headroom * 2)) ]; }; } + dd_memory_critical() { + [ "$_dd_mem_total" -gt 0 ] && [ "$_dd_available" -ge 0 ] && + { [ "$_dd_real_available" -lt "$_dd_tier_headroom" ] || + { [ "$_dd_psi" -ge 100 ] && [ "$_dd_real_available" -lt $((_dd_tier_headroom * 3 / 2)) ]; } || + { [ "$_dd_fall" -ge $((256 * 1024)) ] && [ "$_dd_real_available" -lt "$_dd_fall_headroom" ]; }; } } - bl_session_pressure() { - bl_memory_read - [ "$_bl_game" = 1 ] && bl_memory_critical || return 0 - [ "${BL_ZRAM_IDLE:-1}" = 1 ] && bl_game_focused 0 || return 0 - local _wait=$_bl_tier_backoff _before _pids _targets - [ "$_bl_available" -ge $((_bl_headroom / 2)) ] || [ "$_bl_tier_pushed" -lt 0 ] || _wait=30 - [ "$_bl_tier_at" -lt 0 ] || [ $((SECONDS - _bl_tier_at)) -ge "$_wait" ] || return 0 - if [ "$_bl_tier_at" -ge 0 ] && [ "$_bl_tier_pushed" -gt 0 ]; then - bl_tier_readback - if [ "$_bl_tier_back" -le $((_bl_tier_pushed / 2)) ]; then - _bl_tier_backoff=30 + dd_session_pressure() { + dd_memory_read + dd_memory_critical || _dd_tier_backoff=30 _dd_tier_nogain=0 + [ "$_dd_game" = 1 ] && dd_memory_critical || return 0 + [ "${DD_ZRAM_IDLE:-1}" = 1 ] && dd_game_focused 0 || return 0 + local _wait=$_dd_tier_backoff _before _available_before _pids _targets _gain _min_gain + [ "$_dd_available" -ge $((_dd_headroom / 2)) ] || [ "$_dd_tier_pushed" -lt 0 ] || _wait=30 + [ "$_dd_tier_at" -lt 0 ] || [ $((SECONDS - _dd_tier_at)) -ge "$_wait" ] || return 0 + if [ "$_dd_tier_at" -ge 0 ] && [ "$_dd_tier_pushed" -gt 0 ]; then + dd_tier_readback + if [ "$_dd_tier_back" -le $((_dd_tier_pushed / 2)) ]; then + [ "${_dd_tier_nogain:-0}" = 1 ] || _dd_tier_backoff=30 else - _bl_tier_backoff=$((_bl_tier_backoff * 2 > 300 ? 300 : _bl_tier_backoff * 2)) - _bl_tier_at=$SECONDS _bl_tier_pushed=-1 - step "zRAM: the game read back most of its last page-out, next try in ${_bl_tier_backoff} s" + _dd_tier_backoff=$((_dd_tier_backoff * 2 > 300 ? 300 : _dd_tier_backoff * 2)) + _dd_tier_at=$SECONDS _dd_tier_pushed=-1 + step "zRAM: the game read back most of its last page-out, next try in ${_dd_tier_backoff} s" return 0 fi fi - _bl_tier_at=$SECONDS _bl_tier_pushed=0 - bl_zram_pick session - bl_zram_usage "${_pids[@]}" > /dev/null - [ "$_bl_rss" -ge $((256 * 1024)) ] || return 0 - if ! bl_zram_has_room; then - step "zRAM: low-memory page-out skipped, swap headroom too small ($((_bl_swap_free / 1024)) MB free)" + _dd_tier_at=$SECONDS _dd_tier_pushed=0 + dd_zram_pick session + dd_zram_usage "${_pids[@]}" > /dev/null + [ "$_dd_rss" -ge $((256 * 1024)) ] || return 0 + if ! dd_zram_has_room; then + step "zRAM: low-memory page-out skipped, swap headroom too small ($((_dd_swap_free / 1024)) MB free)" return 0 fi - _targets=("${_pids[@]}") _before=$_bl_swap - bl_zram_send 1 "low memory (available $((_bl_real_available / 1024)) MB), compressing idle game memory" session - bl_zram_usage "${_targets[@]}" > /dev/null - _bl_tier_pushed=$((_bl_swap - _before)) - bl_tier_note "${_targets[@]}" + _targets=("${_pids[@]}") _before=$_dd_swap _available_before=$_dd_available + dd_zram_send 1 "low memory (available $((_dd_real_available / 1024)) MB), compressing idle game memory" session + dd_zram_usage "${_targets[@]}" > /dev/null + _dd_tier_pushed=$((_dd_swap - _before)) + dd_tier_note "${_targets[@]}" + if [ "${_dd_pageout_complete:-0}" = 1 ]; then + dd_memory_read + _gain=$((_dd_available - _available_before)) + _min_gain=$((_dd_tier_headroom / 16)) + [ "$_min_gain" -ge $((16 * 1024)) ] || _min_gain=$((16 * 1024)) + if [ "$_gain" -lt "$_min_gain" ]; then + _dd_tier_backoff=$((_dd_tier_backoff * 2 > 300 ? 300 : _dd_tier_backoff * 2)) + _dd_tier_at=$SECONDS _dd_tier_nogain=1 + step "zRAM: low-memory page-out gained only $((_gain / 1024)) MB available, next try in ${_dd_tier_backoff} s" + else + _dd_tier_nogain=0 + fi + fi } - bl_proc_start() { + dd_proc_start() { local _s= - _bl_start= + _dd_start= read -r _s 2>/dev/null < "/proc/$1/stat" || return 1 _s=${_s##*) } set -- $_s [ "$1" != Z ] && [ "$#" -ge 20 ] || return 1 - _bl_start=${20} + _dd_start=${20} } - bl_tier_note() { + dd_tier_note() { local _p - _bl_tier_targets=() _bl_tier_swaps=() _bl_tier_starts=() + _dd_tier_targets=() _dd_tier_swaps=() _dd_tier_starts=() for _p in "$@"; do - bl_proc_start "$_p" || continue - bl_zram_usage "$_p" > /dev/null - _bl_tier_targets+=("$_p") _bl_tier_swaps+=("$_bl_swap") _bl_tier_starts+=("$_bl_start") + dd_proc_start "$_p" || continue + dd_zram_usage "$_p" > /dev/null + _dd_tier_targets+=("$_p") _dd_tier_swaps+=("$_dd_swap") _dd_tier_starts+=("$_dd_start") done } - bl_tier_readback() { + dd_tier_readback() { local _i _back=0 - for _i in "${!_bl_tier_targets[@]}"; do - bl_proc_start "${_bl_tier_targets[$_i]}" && [ "$_bl_start" = "${_bl_tier_starts[$_i]}" ] || continue - bl_zram_usage "${_bl_tier_targets[$_i]}" > /dev/null - [ "${_bl_tier_swaps[$_i]}" -le "$_bl_swap" ] || _back=$((_back + _bl_tier_swaps[_i] - _bl_swap)) + for _i in "${!_dd_tier_targets[@]}"; do + dd_proc_start "${_dd_tier_targets[$_i]}" && [ "$_dd_start" = "${_dd_tier_starts[$_i]}" ] || continue + dd_zram_usage "${_dd_tier_targets[$_i]}" > /dev/null + [ "${_dd_tier_swaps[$_i]}" -le "$_dd_swap" ] || _back=$((_back + _dd_tier_swaps[_i] - _dd_swap)) done - _bl_tier_back=$_back + _dd_tier_back=$_back } - bl_watch_nap() { + dd_watch_nap() { local _i - if [ "$_bl_game" = 1 ] && [ "$_bl_available" -ge 0 ] && [ "$_bl_real_available" -lt $((_bl_tier_headroom * 2)) ]; then + if [ "$_dd_game" = 1 ] && [ "$_dd_available" -ge 0 ] && [ "$_dd_real_available" -lt "$_dd_fall_headroom" ]; then for _i in 1 2 3 4 5; do nap 1 - bl_memory_read - bl_memory_critical && return 0 + dd_memory_read + dd_memory_critical && return 0 done else nap 5 fi return 0 } - bl_session_others() { + dd_session_others() { local _p - _bl_session=() - for _p in "${_bl_others[@]}"; do - grep -q -m1 '/libblsession\.so$' "/proc/$_p/maps" 2>/dev/null && _bl_session+=("$_p") + _dd_session=() + for _p in "${_dd_others[@]}"; do + grep -q -m1 '/libddsession\.so$' "/proc/$_p/maps" 2>/dev/null && _dd_session+=("$_p") done } - bl_zram_pick() { + dd_zram_pick() { if [ "$1" = game ]; then - bl_session_others - _pids=("${_bl_session[@]}") - [ "${BL_ZRAM_CLIENT:-1}" != 1 ] || _pids+=("${_bl_pids[@]}") + dd_session_others + _pids=("${_dd_session[@]}") + [ "${DD_ZRAM_CLIENT:-1}" != 1 ] || _pids+=("${_dd_pids[@]}") elif [ "$1" = session ]; then - bl_session_others - _pids=("${_bl_session[@]}") + dd_session_others + _pids=("${_dd_session[@]}") else - _pids=("${_bl_pids[@]}") + _pids=("${_dd_pids[@]}") fi } - bl_zram_wait() { + dd_zram_wait() { local _p _left _start=$SECONDS while [ $((SECONDS - _start)) -lt 12 ]; do _left=0 for _p in "$@"; do - [ -s "/tmp/.bl-zram.ack.$_p" ] && continue + [ -s "/tmp/.dd-zram.ack.$_p" ] && continue [ -d "/proc/$_p" ] || continue - [ $((SECONDS - _start)) -ge 2 ] && [ ! -e "/tmp/.bl-zram.ack.$_p" ] && continue + [ $((SECONDS - _start)) -ge 2 ] && [ ! -e "/tmp/.dd-zram.ack.$_p" ] && continue _left=1 done [ "$_left" = 1 ] || break nap 0.2 done - _bl_pageout_complete=1 + _dd_pageout_complete=1 for _p in "$@"; do - if [ -d "/proc/$_p" ] && [ ! -s "/tmp/.bl-zram.ack.$_p" ]; then _bl_pageout_complete=0; fi - rm -f "/tmp/.bl-zram.ack.$_p" + if [ -d "/proc/$_p" ] && [ ! -s "/tmp/.dd-zram.ack.$_p" ]; then _dd_pageout_complete=0; fi + rm -f "/tmp/.dd-zram.ack.$_p" done } - bl_zram_send() { + dd_zram_send() { local _mode=$1 _what=$2 _which=$3 _pids _p - bl_zram_pick "$_which" - step "zRAM: $_what ($(bl_zram_usage "${_pids[@]}"))" - for _p in "${_pids[@]}"; do rm -f "/tmp/.bl-zram.ack.$_p"; done - printf '%s' "$_mode" > /tmp/.bl-zram + dd_zram_pick "$_which" + step "zRAM: $_what ($(dd_zram_usage "${_pids[@]}"))" + for _p in "${_pids[@]}"; do rm -f "/tmp/.dd-zram.ack.$_p"; done + printf '%s' "$_mode" > /tmp/.dd-zram [ "${#_pids[@]}" = 0 ] || kill -URG "${_pids[@]}" 2>/dev/null - _bl_zram_targets=("${_pids[@]}") + _dd_zram_targets=("${_pids[@]}") [ "${4:-}" != defer ] || return 0 - bl_zram_finish "$_mode" "${_pids[@]}" + dd_zram_finish "$_mode" "${_pids[@]}" } - bl_zram_finish() { + dd_zram_finish() { local _mode=$1 shift - if [ "$_mode" = 1 ]; then bl_zram_wait "$@"; else nap 5; fi - bl_zram_scan - step "zRAM: done ($(bl_zram_usage "$@"))" + if [ "$_mode" = 1 ]; then dd_zram_wait "$@"; else nap 5; fi + dd_zram_scan + step "zRAM: done ($(dd_zram_usage "$@"))" } - bl_game_focused() { - if [ "${BL_DESKTOP:-}" = 1 ] || [ -z "${BL_LAUNCH_DIR:-}" ]; then + dd_game_focused() { + if [ "${DD_DESKTOP:-}" = 1 ] || [ -z "${DD_LAUNCH_DIR:-}" ]; then return 0 fi local id id=$(sed -n 's/.*"focusedApp"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' \ - "$BL_LAUNCH_DIR/agent/focus.json" 2>/dev/null | head -1) - [ -n "$id" ] || return "${1:-1}" - case " ${_bl_apps-} " in + "$DD_LAUNCH_DIR/agent/focus.json" 2>/dev/null | head -1) + [ -n "$id" ] || return "${1:-2}" + case " ${_dd_apps-} " in *" $id "*) return 0 ;; esac return 1 } - bl_over_cap() { - [ "$_bl_ram_cap" -gt 0 ] || return 1 - _bl_measured=$SECONDS - bl_session_others - bl_zram_usage "${_bl_pids[@]}" "${_bl_session[@]}" > /dev/null - [ "$_bl_rss" -gt "$_bl_ram_cap" ] + dd_over_cap() { + [ "$_dd_ram_cap" -gt 0 ] || return 1 + _dd_measured=$SECONDS + dd_session_others + dd_zram_usage "${_dd_pids[@]}" "${_dd_session[@]}" > /dev/null + [ "$_dd_rss" -gt "$_dd_ram_cap" ] } - bl_cap_due() { - [ "$_bl_ram_cap" -gt 0 ] && { [ "$_bl_measured" -lt 0 ] || [ $((SECONDS - _bl_measured)) -ge 30 ]; } + dd_cap_due() { + [ "$_dd_ram_cap" -gt 0 ] && { [ "$_dd_measured" -lt 0 ] || [ $((SECONDS - _dd_measured)) -ge 30 ]; } } - _bl_since=-1 _bl_since_apps= _bl_packed=-1 _bl_measured=-1 _bl_unpack=0 _bl_capped=-1 _bl_backoff=30 - _bl_pressure_at=-1 _bl_pressure_backoff=30 _bl_tier_at=-1 _bl_tier_backoff=30 _bl_tier_pushed=0 _bl_tier_back=0 _bl_tier_targets=() _bl_tier_swaps=() _bl_tier_starts=() - _bl_client_pending=0 _bl_client_reserve=0 _bl_client_targets=() - _bl_sample_at= _bl_sample_available=0 _bl_sample_gpu=0 _bl_sample_unevictable=0 _bl_sample_shmem=0 + _dd_since=-1 _dd_since_apps= _dd_packed=-1 _dd_measured=-1 _dd_unpack=0 _dd_capped=-1 _dd_backoff=30 + _dd_pressure_at=-1 _dd_pressure_backoff=30 _dd_tier_at=-1 _dd_tier_backoff=30 _dd_tier_nogain=0 _dd_tier_pushed=0 _dd_tier_back=0 _dd_tier_targets=() _dd_tier_swaps=() _dd_tier_starts=() + _dd_client_pending=0 _dd_client_reserve=0 _dd_client_targets=() _dd_away= + _dd_sample_at= _dd_sample_available=0 _dd_sample_gpu=0 _dd_sample_unevictable=0 _dd_sample_shmem=0 while kill -0 $$ 2>/dev/null; do - bl_zram_scan - bl_memory_read - if bl_cap_due; then - if bl_over_cap; then - if [ "$_bl_capped" -lt 0 ] || [ $((SECONDS - _bl_capped)) -ge "$_bl_backoff" ]; then - bl_zram_usage "${_bl_pids[@]}" > /dev/null - if [ "$_bl_rss" -ge $((512 * 1024)) ]; then - bl_zram_send 1 "over the ${BL_RAM_CAP_MB} MB RAM cap, compressing the client" client - [ "$_bl_game" = 1 ] && _bl_packed=$SECONDS + dd_zram_scan + dd_memory_read + if dd_cap_due; then + if dd_over_cap; then + if [ "$_dd_capped" -lt 0 ] || [ $((SECONDS - _dd_capped)) -ge "$_dd_backoff" ]; then + dd_zram_usage "${_dd_pids[@]}" > /dev/null + if [ "$_dd_rss" -ge $((512 * 1024)) ]; then + dd_zram_send 1 "over the ${DD_RAM_CAP_MB} MB RAM cap, compressing the client" client + [ "$_dd_game" = 1 ] && _dd_packed=$SECONDS else - step "RAM cap: over, client already small ($((_bl_rss / 1024)) MB resident), skipping it" + step "RAM cap: over, client already small ($((_dd_rss / 1024)) MB resident), skipping it" fi - bl_over_cap && bl_zram_send 1 "still over the RAM cap, compressing the rest of the session" session - if bl_over_cap; then - _bl_backoff=$((_bl_backoff * 2 > 600 ? 600 : _bl_backoff * 2)) - step "RAM cap: still over after paging out, next try in ${_bl_backoff} s" + dd_over_cap && dd_zram_send 1 "still over the RAM cap, compressing the rest of the session" session + if dd_over_cap; then + _dd_backoff=$((_dd_backoff * 2 > 600 ? 600 : _dd_backoff * 2)) + step "RAM cap: still over after paging out, next try in ${_dd_backoff} s" else - _bl_backoff=30 + _dd_backoff=30 fi - _bl_capped=$SECONDS + _dd_capped=$SECONDS fi else - _bl_backoff=30 + _dd_backoff=30 fi fi - _bl_preserved_growth=$_bl_growth _bl_preserved_fall=$_bl_fall - bl_client_pressure defer - _bl_preserved_growth=$_bl_growth _bl_preserved_fall=$_bl_fall - bl_session_pressure - bl_client_pressure_finish - if [ "$_bl_game" = 1 ] && bl_game_focused; then - if [ "$_bl_since" -lt 0 ] || [ "$_bl_since_apps" != "$_bl_apps" ]; then - _bl_since=$SECONDS _bl_since_apps=$_bl_apps + _dd_preserved_growth=$_dd_growth _dd_preserved_fall=$_dd_fall + dd_client_pressure defer + _dd_preserved_growth=$_dd_growth _dd_preserved_fall=$_dd_fall + dd_session_pressure + dd_client_pressure_finish + _dd_focus=1 + [ "$_dd_game" = 1 ] && { dd_game_focused && _dd_focus=0 || _dd_focus=$?; } + if [ "$_dd_game" = 1 ] && [ "$_dd_focus" = 0 ]; then + _dd_away= + if [ "$_dd_since" -lt 0 ] || [ "$_dd_since_apps" != "$_dd_apps" ]; then + _dd_since=$SECONDS _dd_since_apps=$_dd_apps fi - if [ "${BL_ZRAM_CLIENT:-1}" = 1 ] && [ $((SECONDS - _bl_since)) -ge 20 ] && [ "${#_bl_pids[@]}" -gt 0 ] && - { [ "$_bl_packed" -lt 0 ] || [ $((SECONDS - _bl_packed)) -ge 300 ]; } && bl_client_can_pageout; then - bl_zram_send 1 "compressing the client" client - _bl_packed=$SECONDS + if [ "${DD_ZRAM_CLIENT:-1}" = 1 ] && [ $((SECONDS - _dd_since)) -ge 20 ] && [ "${#_dd_pids[@]}" -gt 0 ] && + { [ "$_dd_packed" -lt 0 ] || [ $((SECONDS - _dd_packed)) -ge 300 ]; } && dd_client_can_pageout; then + dd_zram_send 1 "compressing the client" client + _dd_packed=$SECONDS fi - elif [ "$_bl_game" != 1 ]; then - if [ "$_bl_packed" -ge 0 ]; then - _bl_unpack=1 + elif [ "$_dd_game" != 1 ]; then + _dd_away= + if [ "$_dd_packed" -ge 0 ]; then + _dd_unpack=1 fi - _bl_since=-1 _bl_packed=-1 _bl_tier_at=-1 _bl_tier_backoff=30 _bl_tier_pushed=0 _bl_tier_targets=() _bl_tier_swaps=() _bl_tier_starts=() + _dd_since=-1 _dd_packed=-1 _dd_tier_at=-1 _dd_tier_backoff=30 _dd_tier_nogain=0 _dd_tier_pushed=0 _dd_tier_targets=() _dd_tier_swaps=() _dd_tier_starts=() else - _bl_since=-1 + _dd_since=-1 + if [ "$_dd_focus" = 1 ]; then + [ -n "${_dd_away-}" ] || _dd_away=$SECONDS + else + _dd_away= + fi + if [ "$_dd_packed" -ge 0 ]; then + _dd_unpack=1 + fi fi - if [ "$_bl_unpack" = 1 ] && [ "$_bl_game" = 0 ] && ! bl_over_cap && bl_client_can_readback; then - bl_zram_send 0 "memory recovered, reading the client back" client - _bl_unpack=0 + if [ "$_dd_unpack" = 1 ] && + { [ "$_dd_game" = 0 ] || { [ "${_dd_ram_cap:-0}" = 0 ] && [ -n "${_dd_away-}" ] && [ $((SECONDS - _dd_away)) -ge 5 ]; }; } && + ! dd_over_cap && dd_client_can_readback; then + if [ "$_dd_game" = 0 ]; then + dd_zram_send 0 "memory recovered, reading the client back" client + else + dd_zram_send 0 "the client is in front of the game, reading it back" client + _dd_packed=-1 + fi + _dd_unpack=0 fi - bl_watch_nap + dd_watch_nap done ) & fi - if [ "${BL_LAUNCHER_CORES:-1}" != 0 ] && [ -n "${BL_LAUNCH_DIR:-}" ] && [ -z "${BL_DESKTOP:-}" ] \ - && [ "${BL_STEAM_UI:-}" != desktop ] && [ -x /usr/local/bin/droiddeck-launcher-cores ]; then - /usr/local/bin/droiddeck-launcher-cores "$BL_LAUNCH_DIR/agent/focus.json" 2>&1 & + if [ "${DD_LAUNCHER_CORES:-1}" != 0 ] && [ -n "${DD_LAUNCH_DIR:-}" ] && [ -z "${DD_DESKTOP:-}" ] \ + && [ "${DD_STEAM_UI:-}" != desktop ] && [ -x /usr/local/bin/droiddeck-launcher-cores ]; then + /usr/local/bin/droiddeck-launcher-cores "$DD_LAUNCH_DIR/agent/focus.json" 2>&1 & fi - if [ "${BL_PACE_CORES:-1}" != 0 ] && [ -n "${DROIDDECK_HUD_FRAMES:-}" ] && [ -z "${BL_DESKTOP:-}" ] \ + if [ "${DD_PACE_CORES:-1}" != 0 ] && [ -n "${DROIDDECK_HUD_FRAMES:-}" ] && [ -z "${DD_DESKTOP:-}" ] \ && [ -x /usr/local/bin/droiddeck-pace-cores ]; then /usr/local/bin/droiddeck-pace-cores "$DROIDDECK_HUD_FRAMES" 2>&1 & fi @@ -1194,46 +1234,46 @@ case $mode in droiddeck-steam-library "$steam_root" || true step "setting up the ARM64 Proton compatibility tool" steam-compatibility "$steam_root" || true - if [ -z "${BL_DESKTOP:-}" ] && [ "${BL_STEAM_UI:-}" != desktop ]; then - droiddeck-steam-ui-scale "$steam_root" "${BL_WIDTH:-1280}" "${BL_HEIGHT:-720}" || true + if [ -z "${DD_DESKTOP:-}" ] && [ "${DD_STEAM_UI:-}" != desktop ]; then + droiddeck-steam-ui-scale "$steam_root" "${DD_WIDTH:-1280}" "${DD_HEIGHT:-720}" || true fi - if [ -n "${BL_ADDED_GAMES:-}" ]; then + if [ -n "${DD_ADDED_GAMES:-}" ]; then step "adding the app's own games to the client's library" - droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true + droiddeck-steam-shortcuts "$steam_root" "$DD_ADDED_GAMES" || true fi DROIDDECK_SEED_LATER=1 droiddeck-seed-redists "$steam_root" || true else - _bl_x64_tool=$(droiddeck-steam-x64 --default-tool) - if [ -n "$_bl_x64_tool" ]; then - if [ -n "${BL_ADDED_GAMES:-}" ]; then + _dd_x64_tool=$(droiddeck-steam-x64 --default-tool) + if [ -n "$_dd_x64_tool" ]; then + if [ -n "${DD_ADDED_GAMES:-}" ]; then step "adding the app's own games to the x86-64 client's library" - BL_COMPAT_TOOL=$_bl_x64_tool droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true + DD_COMPAT_TOOL=$_dd_x64_tool droiddeck-steam-shortcuts "$steam_root" "$DD_ADDED_GAMES" || true fi - step "pointing the x86-64 client's Windows titles at $_bl_x64_tool" - BL_COMPAT_TOOL=$_bl_x64_tool steam-compatibility "$steam_root" --x64 || true + step "pointing the x86-64 client's Windows titles at $_dd_x64_tool" + DD_COMPAT_TOOL=$_dd_x64_tool steam-compatibility "$steam_root" --x64 || true fi - if [ -z "${BL_DESKTOP:-}" ] && [ "${BL_STEAM_UI:-}" != desktop ]; then - droiddeck-steam-ui-scale "$steam_root" "${BL_WIDTH:-1280}" "${BL_HEIGHT:-720}" || true + if [ -z "${DD_DESKTOP:-}" ] && [ "${DD_STEAM_UI:-}" != desktop ]; then + droiddeck-steam-ui-scale "$steam_root" "${DD_WIDTH:-1280}" "${DD_HEIGHT:-720}" || true fi DROIDDECK_SEED_LATER=1 droiddeck-seed-redists "$steam_root" || true fi - if [ -n "${BL_SHADER_PRECACHE:-}" ]; then - droiddeck-steam-shaders "$BL_SHADER_PRECACHE" "$XDG_DATA_HOME/Steam" \ - "${BL_X64_HOME:-$HOME/.droiddeck-x64}/.local/share/Steam" && - echo "$BL_SHADER_PRECACHE" > "$HOME/.bl-shader-precache-applied" || true + if [ -n "${DD_SHADER_PRECACHE:-}" ]; then + droiddeck-steam-shaders "$DD_SHADER_PRECACHE" "$XDG_DATA_HOME/Steam" \ + "${DD_X64_HOME:-$HOME/.droiddeck-x64}/.local/share/Steam" && + echo "$DD_SHADER_PRECACHE" > "$HOME/.dd-shader-precache-applied" || true fi if [ "$steam_x64" = 0 ] && [ ! -f "$steam_root/steamapps/appmanifest_4427310.acf" ]; then step "asking the client to fetch the ARM64 Proton" set -- "$@" steam://install/4427310 ( - _bl_acf="$steam_root/steamapps/appmanifest_4427310.acf" + _dd_acf="$steam_root/steamapps/appmanifest_4427310.acf" for _ in $(seq 1 360); do sleep 10 - if grep -q '"StateFlags"[[:space:]]*"4"' "$_bl_acf" 2>/dev/null; then + if grep -q '"StateFlags"[[:space:]]*"4"' "$_dd_acf" 2>/dev/null; then sleep 10 steam-compatibility "$steam_root" >/dev/null 2>&1 || true step "compatibility layer installed: restarting the Steam client once" - : > "$HOME/.bl-restart-once" + : > "$HOME/.dd-restart-once" "${steam_client[@]}" -shutdown >/dev/null 2>&1 || true exit 0 fi @@ -1241,23 +1281,23 @@ case $mode in ) & if ! grep -q '"RememberPassword"[[:space:]]*"1"' "$steam_root/config/loginusers.vdf" 2>/dev/null; then ( - _bl_acf="$steam_root/steamapps/appmanifest_4427310.acf" - _bl_conn="$steam_root/logs/connection_log.txt" - _bl_cons="$steam_root/logs/console_log.txt" - _bl_from=$(stat -c %s "$_bl_conn" 2>/dev/null || echo 0) - _bl_cfrom=$(stat -c %s "$_bl_cons" 2>/dev/null || echo 0) + _dd_acf="$steam_root/steamapps/appmanifest_4427310.acf" + _dd_conn="$steam_root/logs/connection_log.txt" + _dd_cons="$steam_root/logs/console_log.txt" + _dd_from=$(stat -c %s "$_dd_conn" 2>/dev/null || echo 0) + _dd_cfrom=$(stat -c %s "$_dd_cons" 2>/dev/null || echo 0) for _ in $(seq 1 180); do sleep 10 - [ -f "$_bl_acf" ] && exit 0 - if tail -c +$((_bl_from + 1)) "$_bl_conn" 2>/dev/null | grep -q "RecvMsgClientLogOnResponse() : processing complete"; then + [ -f "$_dd_acf" ] && exit 0 + if tail -c +$((_dd_from + 1)) "$_dd_conn" 2>/dev/null | grep -q "RecvMsgClientLogOnResponse() : processing complete"; then for _ in $(seq 1 45); do - tail -c +$((_bl_cfrom + 1)) "$_bl_cons" 2>/dev/null | grep -q "Waiting for compat in post-logon took" && break + tail -c +$((_dd_cfrom + 1)) "$_dd_cons" 2>/dev/null | grep -q "Waiting for compat in post-logon took" && break sleep 2 done - for _bl_try in 1 2 3; do + for _dd_try in 1 2 3; do sleep 10 - [ -f "$_bl_acf" ] && exit 0 - step "signed in: asking the client again for the ARM64 Proton (try $_bl_try of 3)" + [ -f "$_dd_acf" ] && exit 0 + step "signed in: asking the client again for the ARM64 Proton (try $_dd_try of 3)" "${steam_client[@]}" steam://install/4427310 >/dev/null 2>&1 || true sleep 50 done @@ -1267,10 +1307,10 @@ case $mode in ) & fi fi - [ -z "${BL_DESKTOP:-}" ] && ( + [ -z "${DD_DESKTOP:-}" ] && ( stretch=0 restore=0 - [ "${BL_STRETCHED:-0}" = 1 ] && stretch=1 - [ "${BL_RESTORE_ON_RESUME:-1}" = 1 ] && restore=1 + [ "${DD_STRETCHED:-0}" = 1 ] && stretch=1 + [ "${DD_RESTORE_ON_RESUME:-1}" = 1 ] && restore=1 atoms=(STEAM_TOUCH_CLICK_MODE GAMESCOPE_FOCUSED_APP) [ "$stretch" = 1 ] && atoms+=(GAMESCOPE_NEW_SCALING_SCALER) prop_value() { @@ -1297,12 +1337,12 @@ case $mode in filter\ *) filter=${v#filter } ;; esac done < <(sed -n 's/.*\] Client version:.*/client/p; s/.*\] Set scaling mode: \([0-9]*\).*/mode \1/p; s/.*\] Set scaling filter: \([0-9]*\).*/filter \1/p' "$log") - case $mode in [1-5]) bl_xprop_set_all GAMESCOPE_NEW_SCALING_SCALER $((mode - 1)) \ + case $mode in [1-5]) dd_xprop_set_all GAMESCOPE_NEW_SCALING_SCALER $((mode - 1)) \ && echo "== scaling: applied the client's saved scaling mode $mode" ;; esac case $filter in 1) v=0 ;; 2) v=1 ;; 3) v=2 ;; *) v= ;; esac - [ -n "$v" ] && bl_xprop_set_all GAMESCOPE_NEW_SCALING_FILTER "$v" \ + [ -n "$v" ] && dd_xprop_set_all GAMESCOPE_NEW_SCALING_FILTER "$v" \ && echo "== scaling: applied the client's saved scaling filter $filter" return 0 } @@ -1320,8 +1360,8 @@ case $mode in if [ "$pv" != "$app" ]; then app=$pv echo "== focused app: $app (touch mode ${tmode:-unset}) at $(date +%T)" - if [ -n "${BL_LAUNCH_DIR:-}" ]; then - printf '%s\n' "$app" > "$BL_LAUNCH_DIR/steam-focused-app.tmp" && mv -f "$BL_LAUNCH_DIR/steam-focused-app.tmp" "$BL_LAUNCH_DIR/steam-focused-app" + if [ -n "${DD_LAUNCH_DIR:-}" ]; then + printf '%s\n' "$app" > "$DD_LAUNCH_DIR/steam-focused-app.tmp" && mv -f "$DD_LAUNCH_DIR/steam-focused-app.tmp" "$DD_LAUNCH_DIR/steam-focused-app" fi fi case $pv in ''|0|769|*[!0-9]*) ;; *) restore_steam_scaling ;; esac @@ -1329,7 +1369,7 @@ case $mode in case $pv in ''|*[!0-9]*) prev=; continue ;; esac if [ "$prev" = 769 ] && [ "$pv" != 769 ]; then nap 1 - bl_xprop_set_all GAMESCOPE_RESTORE_FOCUS_WINDOW 1 \ + dd_xprop_set_all GAMESCOPE_RESTORE_FOCUS_WINDOW 1 \ && echo "== resume: asked gamescope to restore the game window (app $pv)" fi prev=$pv @@ -1345,33 +1385,33 @@ case $mode in ) & steam_hold_launch() { local game=$1 shortcut= waited=0 status=0 - _bl_focused() { xprop -root GAMESCOPE_FOCUSED_APP 2>/dev/null | sed -n 's/.*= *//p'; } - _bl_starting() { pgrep -f "reaper SteamLaunch AppId=$(((game >> 32) & 0xffffffff))( |$)" >/dev/null 2>&1; } - _bl_hand_off() { - printf '%s\n' "$game" > "$BL_LAUNCH_DIR/steam-game.tmp" && mv -f "$BL_LAUNCH_DIR/steam-game.tmp" "$BL_LAUNCH_DIR/steam-game" + _dd_focused() { xprop -root GAMESCOPE_FOCUSED_APP 2>/dev/null | sed -n 's/.*= *//p'; } + _dd_starting() { pgrep -f "reaper SteamLaunch AppId=$(((game >> 32) & 0xffffffff))( |$)" >/dev/null 2>&1; } + _dd_hand_off() { + printf '%s\n' "$game" > "$DD_LAUNCH_DIR/steam-game.tmp" && mv -f "$DD_LAUNCH_DIR/steam-game.tmp" "$DD_LAUNCH_DIR/steam-game" } - _bl_end=$((SECONDS + 120)) - until [ "$(_bl_focused)" = 769 ] || [ "$SECONDS" -ge "$_bl_end" ]; do + _dd_end=$((SECONDS + 120)) + until [ "$(_dd_focused)" = 769 ] || [ "$SECONDS" -ge "$_dd_end" ]; do sleep 1 done [ "${#game}" -gt 10 ] && shortcut=1 - _bl_ready_end=$((SECONDS + 30)) - while [ "$waited" -lt 30 ] && [ "$((_bl_ready_end - SECONDS))" -gt 0 ]; do - timeout "$((_bl_ready_end - SECONDS))" /usr/local/bin/droiddeck-agent --steam-ready >/dev/null 2>&1 && break - [ "$((_bl_ready_end - SECONDS))" -gt 1 ] || break + _dd_ready_end=$((SECONDS + 30)) + while [ "$waited" -lt 30 ] && [ "$((_dd_ready_end - SECONDS))" -gt 0 ]; do + timeout "$((_dd_ready_end - SECONDS))" /usr/local/bin/droiddeck-agent --steam-ready >/dev/null 2>&1 && break + [ "$((_dd_ready_end - SECONDS))" -gt 1 ] || break sleep 1 waited=$((waited + 1)) done waited=0 echo "== steam: interface up; launching the requested game $game" - _bl_hand_off + _dd_hand_off [ -n "$shortcut" ] || return 0 - while [ "$(_bl_focused)" = 769 ] && [ "$waited" -lt 20 ]; do + while [ "$(_dd_focused)" = 769 ] && [ "$waited" -lt 20 ]; do sleep 1 waited=$((waited + 1)) done - [ "$(_bl_focused)" = 769 ] || return 0 - if _bl_starting; then + [ "$(_dd_focused)" = 769 ] || return 0 + if _dd_starting; then echo "== steam: the requested game is already starting; not launching again" return 0 fi @@ -1379,53 +1419,53 @@ case $mode in /usr/local/bin/droiddeck-agent --wait-steam-shortcut-overview "$game" 45 || status=$? if [ "$status" -eq 3 ]; then echo "== steam: not a shortcut CGameID; not launching again" - elif _bl_starting; then + elif _dd_starting; then echo "== steam: the requested game started while waiting; not launching again" - elif [ "$(_bl_focused)" = 769 ]; then + elif [ "$(_dd_focused)" = 769 ]; then echo "== steam: clearing the pending launch interstitial for $game (overview status $status)" /usr/local/bin/droiddeck-agent --steam-clear-pending-interstitial "$(((game >> 32) & 0xffffffff))" >/dev/null 2>&1 && return 0 echo "== steam: launching the requested game again $game" - _bl_hand_off + _dd_hand_off else echo "== steam: the game took focus while waiting; not launching again" fi } - if [ -n "${BL_LAUNCH_DIR:-}" ] && [ -z "${BL_DESKTOP:-}" ]; then - _bl_held= - _bl_uninstall= - _bl_rest=() - for _bl_arg in "$@"; do - case $_bl_arg in - steam://rungameid/*) _bl_held=${_bl_arg#steam://rungameid/} ;; - steam://uninstall/*) _bl_uninstall=${_bl_arg#steam://uninstall/} ;; - *) _bl_rest+=("$_bl_arg") ;; + if [ -n "${DD_LAUNCH_DIR:-}" ] && [ -z "${DD_DESKTOP:-}" ]; then + _dd_held= + _dd_uninstall= + _dd_rest=() + for _dd_arg in "$@"; do + case $_dd_arg in + steam://rungameid/*) _dd_held=${_dd_arg#steam://rungameid/} ;; + steam://uninstall/*) _dd_uninstall=${_dd_arg#steam://uninstall/} ;; + *) _dd_rest+=("$_dd_arg") ;; esac done - if [ -n "$_bl_uninstall" ]; then - set -- "${_bl_rest[@]}" + if [ -n "$_dd_uninstall" ]; then + set -- "${_dd_rest[@]}" ( - _bl_end=$((SECONDS + 120)) - until [ "$(xprop -root GAMESCOPE_FOCUSED_APP 2>/dev/null | sed -n 's/.*= *//p')" = 769 ] || [ "$SECONDS" -ge "$_bl_end" ]; do + _dd_end=$((SECONDS + 120)) + until [ "$(xprop -root GAMESCOPE_FOCUSED_APP 2>/dev/null | sed -n 's/.*= *//p')" = 769 ] || [ "$SECONDS" -ge "$_dd_end" ]; do sleep 1 done sleep 4 - echo "== steam: interface up; asking to uninstall $_bl_uninstall" - printf '%s\n' "$_bl_uninstall" > "$BL_LAUNCH_DIR/steam-uninstall.tmp" && mv -f "$BL_LAUNCH_DIR/steam-uninstall.tmp" "$BL_LAUNCH_DIR/steam-uninstall" + echo "== steam: interface up; asking to uninstall $_dd_uninstall" + printf '%s\n' "$_dd_uninstall" > "$DD_LAUNCH_DIR/steam-uninstall.tmp" && mv -f "$DD_LAUNCH_DIR/steam-uninstall.tmp" "$DD_LAUNCH_DIR/steam-uninstall" ) & fi - if [ -n "$_bl_held" ]; then - set -- "${_bl_rest[@]}" - steam_hold_launch "$_bl_held" & + if [ -n "$_dd_held" ]; then + set -- "${_dd_rest[@]}" + steam_hold_launch "$_dd_held" & fi fi - if [ -s "$HOME/.bl-autolaunch" ]; then - _bl_app=$(cat "$HOME/.bl-autolaunch") - case $_bl_app in - steam://*) _bl_url=$_bl_app ;; - *) _bl_url=steam://rungameid/$_bl_app ;; + if [ -s "$HOME/.dd-autolaunch" ]; then + _dd_app=$(cat "$HOME/.dd-autolaunch") + case $_dd_app in + steam://*) _dd_url=$_dd_app ;; + *) _dd_url=steam://rungameid/$_dd_app ;; esac - echo "== autolaunch $_bl_url" - set -- "$@" "$_bl_url" + echo "== autolaunch $_dd_url" + set -- "$@" "$_dd_url" fi if command -v dbus-daemon >/dev/null 2>&1 && command -v droiddeck-netmanager >/dev/null 2>&1; then write_system_bus_config @@ -1437,15 +1477,15 @@ case $mode in done if [ -S /run/dbus/system_bus_socket ]; then echo "== network: system bus up, NetworkManager stand-in running" - rm -f "$BL_LAUNCH_DIR/steam-sleep-ready" + rm -f "$DD_LAUNCH_DIR/steam-sleep-ready" droiddeck-login1 --with-netmanager & login_manager=$! for ((_i = 0; _i < 50; _i++)); do - [ -f "$BL_LAUNCH_DIR/steam-sleep-ready" ] && break + [ -f "$DD_LAUNCH_DIR/steam-sleep-ready" ] && break kill -0 "$login_manager" 2>/dev/null || break nap 0.1 done - if [ ! -f "$BL_LAUNCH_DIR/steam-sleep-ready" ]; then + if [ ! -f "$DD_LAUNCH_DIR/steam-sleep-ready" ]; then echo "== sleep: login1 did not start; refusing a client that cannot resume" exit 69 fi @@ -1461,43 +1501,43 @@ case $mode in # Without a session bus libdbus autolaunches one under the game; it never exits and Steam's # reaper waits on it, so the launch or exit never finishes. if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ]; then - _bl_bus=${XDG_RUNTIME_DIR:-/run/droiddeck}/bus - rm -f "$_bl_bus" - dbus-daemon --session --address="unix:path=$_bl_bus" --nofork --nopidfile & + _dd_bus=${XDG_RUNTIME_DIR:-/run/droiddeck}/bus + rm -f "$_dd_bus" + dbus-daemon --session --address="unix:path=$_dd_bus" --nofork --nopidfile & for _ in $(seq 1 50); do - [ -S "$_bl_bus" ] && break + [ -S "$_dd_bus" ] && break nap 0.1 done - if [ -S "$_bl_bus" ]; then - export DBUS_SESSION_BUS_ADDRESS="unix:path=$_bl_bus" - echo "== session bus up at $_bl_bus" + if [ -S "$_dd_bus" ]; then + export DBUS_SESSION_BUS_ADDRESS="unix:path=$_dd_bus" + echo "== session bus up at $_dd_bus" else echo "== session bus did not come up; programs may start their own" fi fi - _bl_compat_env=(env -u LD_LIBRARY_PATH -u STEAM_RUNTIME -u STEAM_STEAMRT_RECURSION_GUARD) - [ "${LD_LIBRARY_PATH+x}" ] && _bl_compat_env+=("LD_LIBRARY_PATH=$LD_LIBRARY_PATH") - [ "${STEAM_RUNTIME+x}" ] && _bl_compat_env+=("STEAM_RUNTIME=$STEAM_RUNTIME") - [ "${STEAM_STEAMRT_RECURSION_GUARD+x}" ] && _bl_compat_env+=("STEAM_STEAMRT_RECURSION_GUARD=$STEAM_STEAMRT_RECURSION_GUARD") + _dd_compat_env=(env -u LD_LIBRARY_PATH -u STEAM_RUNTIME -u STEAM_STEAMRT_RECURSION_GUARD) + [ "${LD_LIBRARY_PATH+x}" ] && _dd_compat_env+=("LD_LIBRARY_PATH=$LD_LIBRARY_PATH") + [ "${STEAM_RUNTIME+x}" ] && _dd_compat_env+=("STEAM_RUNTIME=$STEAM_RUNTIME") + [ "${STEAM_STEAMRT_RECURSION_GUARD+x}" ] && _dd_compat_env+=("STEAM_STEAMRT_RECURSION_GUARD=$STEAM_STEAMRT_RECURSION_GUARD") export STEAM_RUNTIME=1 export STEAM_STEAMRT_RECURSION_GUARD=1 export LD_LIBRARY_PATH=$steam_root/steamrtarm64:$steam_root/steamrtarm64/panorama${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} export SDL_VIDEO_X11_DGAMOUSE=0 - bl_steam_path=$PATH - bl_steam_angle=vulkan - bl_steam_presentation=() - if [ "${BL_STEAM_GL_PRESENT:-}" = 1 ]; then - bl_steam_path="/usr/local/libexec/droiddeck-steam:$PATH" + dd_steam_path=$PATH + dd_steam_angle=vulkan + dd_steam_presentation=() + if [ "${DD_STEAM_GL_PRESENT:-}" = 1 ]; then + dd_steam_path="/usr/local/libexec/droiddeck-steam:$PATH" export DISABLE_GAMESCOPE_WSI=1 LIBGL_KOPPER_DISABLE=true - bl_steam_angle=gl - bl_steam_presentation=(-cef-disable-gpu-compositing) + dd_steam_angle=gl + dd_steam_presentation=(-cef-disable-gpu-compositing) echo "== steam: system PowerVR uses OpenGL/DRI3 through Zink with software CEF compositing" - elif [ "${BL_STEAM_SOFT_COMPOSITING:-}" = 1 ]; then - bl_steam_presentation=(-cef-disable-gpu-compositing) + elif [ "${DD_STEAM_SOFT_COMPOSITING:-}" = 1 ]; then + dd_steam_presentation=(-cef-disable-gpu-compositing) echo "== steam: open driver pair - software CEF compositing, GPU raster" fi - _bl_cef=(-cef-force-gpu "${bl_steam_presentation[@]}" -cef-use-gl=angle "-cef-use-angle=$bl_steam_angle") + _dd_cef=(-cef-force-gpu "${dd_steam_presentation[@]}" -cef-use-gl=angle "-cef-use-angle=$dd_steam_angle") decky_loader=$HOME/homebrew/services/PluginLoader if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ -x "$decky_loader" ]; then decky_arch=$(cat "$HOME/homebrew/services/.droiddeck-decky-arch" 2>/dev/null || echo unknown) @@ -1534,64 +1574,64 @@ case $mode in fi fi steam_devtools 8080 - export BL_CDP_PORT - if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ "${decky_arch:-}" = x86_64 ] && [ ${#_bl_cdp[@]} = 0 ]; then - echo "== steam: devtools port $BL_CDP_PORT left open for the x86_64 Decky loader" + export DD_CDP_PORT + if [ -f "$HOME/.droiddeck-decky-enabled" ] && [ "${decky_arch:-}" = x86_64 ] && [ ${#_dd_cdp[@]} = 0 ]; then + echo "== steam: devtools port $DD_CDP_PORT left open for the x86_64 Decky loader" else - export BL_CDP_GUARD=$BL_CDP_PORT - echo "== steam: devtools port $BL_CDP_PORT, guest processes only" + export DD_CDP_GUARD=$DD_CDP_PORT + echo "== steam: devtools port $DD_CDP_PORT, guest processes only" fi - [ -n "${BL_LAUNCH_DIR:-}" ] && mkdir -p "$BL_LAUNCH_DIR/agent" && echo "$BL_CDP_PORT" > "$BL_LAUNCH_DIR/agent/cdp-port" + [ -n "${DD_LAUNCH_DIR:-}" ] && mkdir -p "$DD_LAUNCH_DIR/agent" && echo "$DD_CDP_PORT" > "$DD_LAUNCH_DIR/agent/cdp-port" if [ "$steam_x64" = 1 ]; then { droiddeck-steam-compat --files-only "$steam_root" 2>&1 & } else - { "${_bl_compat_env[@]}" droiddeck-steam-compat "$steam_root" 2>&1 & } + { "${_dd_compat_env[@]}" droiddeck-steam-compat "$steam_root" 2>&1 & } fi - _bl_ui=(-gamepadui) - [ "${BL_STEAM_UI:-}" = desktop ] && _bl_ui=() - # bl_steam_angle / bl_steam_presentation (set above) default to the Adreno values (vulkan, - # none); only the system-PowerVR path (BL_STEAM_GL_PRESENT=1) changes them. - _bl_cef=(-cef-force-gpu "${bl_steam_presentation[@]}" -cef-use-gl=angle "-cef-use-angle=${bl_steam_angle:-vulkan}") - [ "${steam_cef_gpu:-1}" = 1 ] || _bl_cef=(-cef-disable-gpu) - if [ "${BL_DESKTOP:-}" = 1 ] && [ "${BL_STEAM_UI:-}" = desktop ]; then - _bl_cef=(-cef-disable-gpu) - _bl_ui=(-nobigpicture) + _dd_ui=(-gamepadui) + [ "${DD_STEAM_UI:-}" = desktop ] && _dd_ui=() + # dd_steam_angle / dd_steam_presentation (set above) default to the Adreno values (vulkan, + # none); only the system-PowerVR path (DD_STEAM_GL_PRESENT=1) changes them. + _dd_cef=(-cef-force-gpu "${dd_steam_presentation[@]}" -cef-use-gl=angle "-cef-use-angle=${dd_steam_angle:-vulkan}") + [ "${steam_cef_gpu:-1}" = 1 ] || _dd_cef=(-cef-disable-gpu) + if [ "${DD_DESKTOP:-}" = 1 ] && [ "${DD_STEAM_UI:-}" = desktop ]; then + _dd_cef=(-cef-disable-gpu) + _dd_ui=(-nobigpicture) fi - if [ "${BL_VKBRIDGE:-0}" = 1 ]; then + if [ "${DD_VKBRIDGE:-0}" = 1 ]; then # On the GPU the Steam UI held about 400 MB through the bridge (Mali-G76 MC4, 3 GB of RAM); with # a game loading beside it, Android's low-memory killer took the whole session down. - if [ -z "${BL_VKBRIDGE_CEF_GPU:-}" ]; then - _bl_mem_kb=$(awk '/^MemTotal:/ {print $2}' /proc/meminfo 2>/dev/null) - if [ "${_bl_mem_kb:-0}" -gt 0 ] && [ "$_bl_mem_kb" -lt 4194304 ]; then - BL_VKBRIDGE_CEF_GPU=0 - echo "== steam: $((_bl_mem_kb / 1024)) MB of RAM: the browser UI draws in software to leave games the memory" + if [ -z "${DD_VKBRIDGE_CEF_GPU:-}" ]; then + _dd_mem_kb=$(awk '/^MemTotal:/ {print $2}' /proc/meminfo 2>/dev/null) + if [ "${_dd_mem_kb:-0}" -gt 0 ] && [ "$_dd_mem_kb" -lt 4194304 ]; then + DD_VKBRIDGE_CEF_GPU=0 + echo "== steam: $((_dd_mem_kb / 1024)) MB of RAM: the browser UI draws in software to leave games the memory" fi fi - if [ "${BL_VKBRIDGE_CEF_GPU:-1}" = 0 ]; then - _bl_cef=(-cef-disable-gpu -cef-disable-gpu-compositing) + if [ "${DD_VKBRIDGE_CEF_GPU:-1}" = 0 ]; then + _dd_cef=(-cef-disable-gpu -cef-disable-gpu-compositing) echo "== steam: browser UI in software (Mali bridge)" - elif [ "${_bl_cef[0]}" = -cef-force-gpu ]; then + elif [ "${_dd_cef[0]}" = -cef-force-gpu ]; then # With Steam's own web helper layout the Deck UI's footer and overlays flicker on the bridge # (Mali-G78 MP14). ANGLE on Vulkan without Chromium's Vulkan compositing draws them steadily. - : "${BL_VKBRIDGE_CEF_ANGLE=vulkan}" "${BL_VKBRIDGE_CEF_VULKAN=0}" - _bl_cef=(-cef-force-gpu -cef-use-gl=angle -cef-use-angle="${BL_VKBRIDGE_CEF_ANGLE:-vulkan}") + : "${DD_VKBRIDGE_CEF_ANGLE=vulkan}" "${DD_VKBRIDGE_CEF_VULKAN=0}" + _dd_cef=(-cef-force-gpu -cef-use-gl=angle -cef-use-angle="${DD_VKBRIDGE_CEF_ANGLE:-vulkan}") fi - [ "${BL_VKBRIDGE_CEF_LOG:-0}" = 1 ] && _bl_cef+=(-cef-enable-logging=stderr -cef-v=1) - [ -n "${BL_VKBRIDGE_CEF_EXTRA:-}" ] && read -r -a _bl_cef_extra <<<"$BL_VKBRIDGE_CEF_EXTRA" && _bl_cef+=("${_bl_cef_extra[@]}") - BL_WEBHELPER_ARGS=$(bl_webhelper_layout) - export BL_WEBHELPER_ARGS - echo "== steam: web helper process layout: $BL_WEBHELPER_ARGS (Mali bridge)" + [ "${DD_VKBRIDGE_CEF_LOG:-0}" = 1 ] && _dd_cef+=(-cef-enable-logging=stderr -cef-v=1) + [ -n "${DD_VKBRIDGE_CEF_EXTRA:-}" ] && read -r -a _dd_cef_extra <<<"$DD_VKBRIDGE_CEF_EXTRA" && _dd_cef+=("${_dd_cef_extra[@]}") + DD_WEBHELPER_ARGS=$(dd_webhelper_layout) + export DD_WEBHELPER_ARGS + echo "== steam: web helper process layout: $DD_WEBHELPER_ARGS (Mali bridge)" fi - if [ "${BL_STEAM_UI:-}" != desktop ]; then - if [ "$steam_x64" = 0 ] || [ "${BL_X64_DECK:-1}" != 0 ]; then - _bl_ui+=(-steamdeck -steamos3) + if [ "${DD_STEAM_UI:-}" != desktop ]; then + if [ "$steam_x64" = 0 ] || [ "${DD_X64_DECK:-1}" != 0 ]; then + _dd_ui+=(-steamdeck -steamos3) export STEAM_GAMESCOPE_NIS_SUPPORTED=1 export STEAM_GAMESCOPE_FANCY_SCALING_SUPPORT=1 echo "== steam: Deck mode on (-steamdeck -steamos3)" fi fi - export STEAMOS_STEAM_SHUTDOWN_SENTINEL="$HOME/.bl-steam-shutdown" - export STEAMOS_STEAM_REBOOT_SENTINEL="$HOME/.bl-steam-reboot" + export STEAMOS_STEAM_SHUTDOWN_SENTINEL="$HOME/.dd-steam-shutdown" + export STEAMOS_STEAM_REBOOT_SENTINEL="$HOME/.dd-steam-reboot" if ! pgrep -f 'steamwebhelper|steamrtarm64/steam|steamrt64/steam' >/dev/null 2>&1; then _stale="" for _f in "$steam_root/.crash" "$steam_root/steam.pid" \ @@ -1606,28 +1646,28 @@ case $mode in if [ "$steam_x64" = 0 ]; then steam_channel=$(droiddeck-steam-install --channel 2>/dev/null || echo steamdeck_publicbeta) fi - _bl_lang=() - [ -n "${BL_STEAM_LANGUAGE:-}" ] && _bl_lang=(-language "$BL_STEAM_LANGUAGE") + _dd_lang=() + [ -n "${DD_STEAM_LANGUAGE:-}" ] && _dd_lang=(-language "$DD_STEAM_LANGUAGE") steam_beta=$steam_root/package/beta - if [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then + if [ -n "${DD_ADDED_GAMES:-}" ] && [ -f "$DD_ADDED_GAMES" ]; then if [ "$steam_x64" = 0 ]; then - droiddeck-steam-games watch "$steam_root" "$BL_ADDED_GAMES" & + droiddeck-steam-games watch "$steam_root" "$DD_ADDED_GAMES" & else - BL_STEAMCLIENT=$XDG_DATA_HOME/Steam/steamrtarm64/steamclient.so \ - BL_STEAM_SHUTDOWN="droiddeck-steam-x64 --exec -shutdown" \ - droiddeck-steam-games watch "$steam_root" "$BL_ADDED_GAMES" & + DD_STEAMCLIENT=$XDG_DATA_HOME/Steam/steamrtarm64/steamclient.so \ + DD_STEAM_SHUTDOWN="droiddeck-steam-x64 --exec -shutdown" \ + droiddeck-steam-games watch "$steam_root" "$DD_ADDED_GAMES" & fi games_watcher=$! fi - echo "== steam args: ${_bl_ui[*]} ${_bl_cdp[*]} ${_bl_lang[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-ozone-platform=x11 ${_bl_cef[*]} $*$([ "$steam_x64" = 1 ] && echo ' (x86-64 client under FEX)')" + echo "== steam args: ${_dd_ui[*]} ${_dd_cdp[*]} ${_dd_lang[*]} -clientbeta $steam_channel -no-cef-sandbox -cef-ozone-platform=x11 ${_dd_cef[*]} $*$([ "$steam_x64" = 1 ] && echo ' (x86-64 client under FEX)')" steam_updates=0 steam_installs=0 steam_update_stamp=$(stat -c '%n %Y %s' "$steam_root"/package/*.installed 2>/dev/null) - rm -f "$HOME/.bl-stop-requested" "$STEAMOS_STEAM_SHUTDOWN_SENTINEL" "$STEAMOS_STEAM_REBOOT_SENTINEL" + rm -f "$HOME/.dd-stop-requested" "$STEAMOS_STEAM_SHUTDOWN_SENTINEL" "$STEAMOS_STEAM_REBOOT_SENTINEL" steam_other_game_running() { local line value n open - open=$(cat "$BL_LAUNCH_DIR/epic-open" 2>/dev/null) - case $open in ?|*[!0-9]*) open=${BL_EPIC_APP_ID:-$open} ;; esac + open=$(cat "$DD_LAUNCH_DIR/epic-open" 2>/dev/null) + case $open in ?|*[!0-9]*) open=${DD_EPIC_APP_ID:-$open} ;; esac line=$(xprop -root GAMESCOPE_FOCUSABLE_APPS 2>/dev/null) || return 1 case $line in *=*) value=${line#*= } ;; *) return 1 ;; esac for n in ${value//,/ }; do @@ -1636,19 +1676,19 @@ case $mode in return 1 } steam_restart_for() { - if [ "$(cat "$HOME/.bl-restarted-for" 2>/dev/null)" = "$1" ]; then + if [ "$(cat "$HOME/.dd-restarted-for" 2>/dev/null)" = "$1" ]; then echo "== steam: $2, but Steam was already restarted for it; launching it anyway" return 1 fi - printf '%s\n' "$1" > "$HOME/.bl-restarted-for" + printf '%s\n' "$1" > "$HOME/.dd-restarted-for" echo "== steam: $2; restarting Steam to launch it" - printf '%s\n' "$1" > "$HOME/.bl-restart-game" + printf '%s\n' "$1" > "$HOME/.dd-restart-game" "${steam_client[@]:-$steam_root/steamrtarm64/steam}" -shutdown >/dev/null 2>&1 } steam_launch_game() { local state=0 tries /usr/local/bin/droiddeck-agent --steam-shortcut-state "$1" 6 >/dev/null 2>&1 || state=$? - [ "$state" -eq 0 ] && rm -f "$HOME/.bl-restarted-for" + [ "$state" -eq 0 ] && rm -f "$HOME/.dd-restarted-for" if [ "$state" -eq 4 ]; then if steam_other_game_running; then echo "== steam: the client lost shortcut $1, but a game is running; launching it anyway" @@ -1676,27 +1716,27 @@ case $mode in ran=$(pgrep -a -f 'SteamLaunch AppId=[0-9]' 2>/dev/null | sed -n 's/.* SteamLaunch AppId=\([0-9]*\).*/\1/p') if [ -n "$ran" ]; then for n in $ran; do - [ "$n" -ge 2147483648 ] && _bl_ran[$n]=1 + [ "$n" -ge 2147483648 ] && _dd_ran[$n]=1 done - _bl_exited= + _dd_exited= return fi - [ "${#_bl_ran[@]}" -gt 0 ] || return 0 - if [ -z "$_bl_exited" ]; then - _bl_exited=1 + [ "${#_dd_ran[@]}" -gt 0 ] || return 0 + if [ -z "$_dd_exited" ]; then + _dd_exited=1 return fi - _bl_exited= - for n in "${!_bl_ran[@]}"; do + _dd_exited= + for n in "${!_dd_ran[@]}"; do state=0 /usr/local/bin/droiddeck-agent --steam-shortcut-state "$(printf '%u' $(((n << 32) | 0x02000000)))" 3 >/dev/null 2>&1 || state=$? [ "$state" -eq 4 ] && lost="$lost $n" done - _bl_ran=() + _dd_ran=() [ -n "$lost" ] || return 0 pgrep -f 'SteamLaunch AppId=[0-9]' >/dev/null 2>&1 && return 0 echo "== steam: the client dropped shortcut(s)$lost when they exited; restarting Steam so it lists them again" - : > "$HOME/.bl-restart-lost" + : > "$HOME/.dd-restart-lost" "${steam_client[@]:-$steam_root/steamrtarm64/steam}" -shutdown >/dev/null 2>&1 } steam_bring_forward() { @@ -1723,8 +1763,8 @@ case $mode in done } requests= - if [ -n "${BL_LAUNCH_DIR:-}" ] && [ -d "$BL_LAUNCH_DIR" ]; then - rm -f "$BL_LAUNCH_DIR/steam-stop" "$BL_LAUNCH_DIR/steam-game" "$BL_LAUNCH_DIR/steam-game.tmp" + if [ -n "${DD_LAUNCH_DIR:-}" ] && [ -d "$DD_LAUNCH_DIR" ]; then + rm -f "$DD_LAUNCH_DIR/steam-stop" "$DD_LAUNCH_DIR/steam-game" "$DD_LAUNCH_DIR/steam-game.tmp" requests=1 fi ( @@ -1734,14 +1774,14 @@ case $mode in lossless_job= lossless_left=0 lossless_owned=$HOME/.config/droiddeck/lossless-owned - lossless_asked=$HOME/.bl-lossless-asked + lossless_asked=$HOME/.dd-lossless-asked rm -f "$lossless_asked" - [ "${BL_LOSSLESS_OWNED:-0}" != 1 ] && lossless_left=60 - declare -A _bl_pinned=() - declare -A _bl_ran=() - _bl_exited= - compat_stamp=$HOME/.bl-compat-beat - seed_stamp=$HOME/.bl-seed-beat + [ "${DD_LOSSLESS_OWNED:-0}" != 1 ] && lossless_left=60 + declare -A _dd_pinned=() + declare -A _dd_ran=() + _dd_exited= + compat_stamp=$HOME/.dd-compat-beat + seed_stamp=$HOME/.dd-seed-beat rm -f "$compat_stamp" "$seed_stamp" changed_since() { local d @@ -1770,8 +1810,8 @@ case $mode in done return 1 } - compat_pending=$HOME/.bl-compat-pending - compat_restarted=$HOME/.bl-compat-restarted + compat_pending=$HOME/.dd-compat-pending + compat_restarted=$HOME/.dd-compat-restarted rm -f "$compat_pending" : > "$compat_restarted" compat_restarts=0 @@ -1792,16 +1832,16 @@ case $mode in } while :; do if [ -n "$requests" ]; then - if [ -e "$BL_LAUNCH_DIR/steam-stop" ]; then - rm -f "$BL_LAUNCH_DIR/steam-stop" - : > "$HOME/.bl-stop-requested" + if [ -e "$DD_LAUNCH_DIR/steam-stop" ]; then + rm -f "$DD_LAUNCH_DIR/steam-stop" + : > "$HOME/.dd-stop-requested" echo "== steam: the app asked for a clean exit" "${steam_client[@]}" -shutdown >/dev/null 2>&1 || true exit 0 fi - if [ -f "$BL_LAUNCH_DIR/steam-uninstall" ]; then - uninstall_id=$(cat "$BL_LAUNCH_DIR/steam-uninstall" 2>/dev/null) - rm -f "$BL_LAUNCH_DIR/steam-uninstall" + if [ -f "$DD_LAUNCH_DIR/steam-uninstall" ]; then + uninstall_id=$(cat "$DD_LAUNCH_DIR/steam-uninstall" 2>/dev/null) + rm -f "$DD_LAUNCH_DIR/steam-uninstall" case $uninstall_id in ''|0*|*[!0-9]*|???????????*) echo "== steam: ignored invalid uninstall request" ;; *) @@ -1810,9 +1850,9 @@ case $mode in ;; esac fi - if [ -f "$BL_LAUNCH_DIR/steam-game" ]; then - game_id=$(cat "$BL_LAUNCH_DIR/steam-game" 2>/dev/null) - rm -f "$BL_LAUNCH_DIR/steam-game" + if [ -f "$DD_LAUNCH_DIR/steam-game" ]; then + game_id=$(cat "$DD_LAUNCH_DIR/steam-game" 2>/dev/null) + rm -f "$DD_LAUNCH_DIR/steam-game" case $game_id in ''|0*|*[!0-9]*) echo "== steam: ignored invalid game launch request" ;; *) @@ -1837,16 +1877,16 @@ case $mode in [ "$((tick % 10))" -eq 0 ] || continue beat=$((beat + 1)) steam_check_exits - if [ "$beat" -le 720 ] && [ -n "${BL_CLIENT_CPUS:-}" ]; then + if [ "$beat" -le 720 ] && [ -n "${DD_CLIENT_CPUS:-}" ]; then for _d in /proc/[0-9]*; do { IFS= read -r -d '' _c && { IFS= read -r -d '' _c1 || _c1=; }; } < "$_d/cmdline" 2>/dev/null || continue case $_c in FEX|*/FEX|FEXInterpreter|*/FEXInterpreter) _c=$_c1 ;; esac case $_c in *steamwebhelper*|*steamrtarm64/steam|*steamrt64/steam|*gamescope*) ;; *) continue ;; esac _t=("$_d"/task/*) _p=${_d#/proc/} - [ "${_bl_pinned[$_p]:-}" = "${#_t[@]}" ] && client_single_core_matches "$BL_CLIENT_CPUS" "${_t[@]}" && continue - taskset -a -cp "$BL_CLIENT_CPUS" "$_p" >/dev/null 2>&1 || true - _bl_pinned[$_p]=${#_t[@]} + [ "${_dd_pinned[$_p]:-}" = "${#_t[@]}" ] && client_single_core_matches "$DD_CLIENT_CPUS" "${_t[@]}" && continue + taskset -a -cp "$DD_CLIENT_CPUS" "$_p" >/dev/null 2>&1 || true + _dd_pinned[$_p]=${#_t[@]} done fi if [ "$beat" -le 720 ] && [ "$((beat % 3))" -eq 0 ] && { [ -z "$library_job" ] || ! kill -0 "$library_job" 2>/dev/null; }; then @@ -1861,8 +1901,8 @@ case $mode in [ -z "$seed" ] || droiddeck-seed-redists "$steam_root" >/dev/null 2>&1 || true if [ -n "$compat" ]; then if [ "$steam_x64" = 1 ]; then - [ -z "${_bl_x64_tool:-}" ] || - BL_COMPAT_TOOL=$_bl_x64_tool steam-compatibility "$steam_root" --x64 --live >/dev/null 2>&1 || true + [ -z "${_dd_x64_tool:-}" ] || + DD_COMPAT_TOOL=$_dd_x64_tool steam-compatibility "$steam_root" --x64 --live >/dev/null 2>&1 || true droiddeck-steam-x64 --map-direct --live >/dev/null 2>&1 || true else steam-compatibility "$steam_root" >/dev/null 2>&1 || true @@ -1873,17 +1913,17 @@ case $mode in fi fi if [ "$((beat % 3))" -eq 0 ] && [ -s "$compat_pending" ] && [ "$compat_restarts" -lt 3 ] && compat_settled; then - _bl_new=$(sort -u "$compat_pending" | grep -vxF -f "$compat_restarted" || true) + _dd_new=$(sort -u "$compat_pending" | grep -vxF -f "$compat_restarted" || true) rm -f "$compat_pending" - if [ -n "$_bl_new" ]; then + if [ -n "$_dd_new" ]; then compat_restarts=$((compat_restarts + 1)) - printf '%s\n' $_bl_new >> "$compat_restarted" + printf '%s\n' $_dd_new >> "$compat_restarted" if [ "$steam_x64" = 1 ]; then - step "newly installed title(s) $(echo $_bl_new) set to an ARM64 Proton (Windows builds) or DroidDeck direct (Linux builds): restarting the Steam client once so it takes effect" + step "newly installed title(s) $(echo $_dd_new) set to an ARM64 Proton (Windows builds) or DroidDeck direct (Linux builds): restarting the Steam client once so it takes effect" else - step "newly installed title(s) $(echo $_bl_new) set to the ARM64 Proton: restarting the Steam client once so it takes effect" + step "newly installed title(s) $(echo $_dd_new) set to the ARM64 Proton: restarting the Steam client once so it takes effect" fi - : > "$HOME/.bl-restart-once" + : > "$HOME/.dd-restart-once" "${steam_client[@]}" -shutdown >/dev/null 2>&1 || true fi fi @@ -1893,7 +1933,7 @@ case $mode in lossless_left=0 elif ! pgrep -x wineserver >/dev/null 2>&1; then ( - if [ "$steam_x64" = 1 ]; then export BL_STEAMCLIENT=$XDG_DATA_HOME/Steam/steamrtarm64/steamclient.so; fi + if [ "$steam_x64" = 1 ]; then export DD_STEAMCLIENT=$XDG_DATA_HOME/Steam/steamrtarm64/steamclient.so; fi answer=$(droiddeck-steam-games probe "$steam_root" 993090 2>/dev/null) || exit 0 case $answer in *'"993090": true'*) mkdir -p "${lossless_owned%/*}" && : > "$lossless_owned" && echo "== Lossless Scaling: owned" ;; @@ -1907,65 +1947,65 @@ case $mode in done ) & stop_watcher=$! - if [ "${BL_VENUS:-0}" = 1 ] && [ -x /usr/local/bin/droiddeck-glprobe ] && [ "${GALLIUM_DRIVER:-}" = zink ]; then + if [ "${DD_VENUS:-0}" = 1 ] && [ -x /usr/local/bin/droiddeck-glprobe ] && [ "${GALLIUM_DRIVER:-}" = zink ]; then LIBGL_DEBUG=verbose MESA_LOG_LEVEL=debug timeout 20 /usr/local/bin/droiddeck-glprobe 2>&1 | grep -v drirc | head -60 | sed 's/^/== glprobe: /' if [ "${PIPESTATUS[0]}" = 1 ]; then VK_LOADER_DEBUG=error,warn timeout 20 /usr/local/bin/droiddeck-glprobe 2>&1 | grep -v drirc | head -40 | sed 's/^/== glprobe (loader): /' DROIDDECK_MALI_COMPAT_TRACE=1 MESA_DEBUG=1 MESA_LOG_LEVEL=debug LIBGL_DEBUG=verbose ZINK_DEBUG=mem VN_DEBUG=init,result,log_ctx_info \ - timeout 30 /usr/local/bin/droiddeck-glprobe > "${BL_DEBUG_DIR:-/tmp}/glprobe-trace.txt" 2>&1 - grep -v drirc "${BL_DEBUG_DIR:-/tmp}/glprobe-trace.txt" | head -120 | sed 's/^/== glprobe (trace): /' - echo "== glprobe (trace): last pre-device query before Zink gave up: $(grep 'droiddeck-mali-compat: trace:' "${BL_DEBUG_DIR:-/tmp}/glprobe-trace.txt" | grep -v 'trace: extensions:' | tail -1)" + timeout 30 /usr/local/bin/droiddeck-glprobe > "${DD_DEBUG_DIR:-/tmp}/glprobe-trace.txt" 2>&1 + grep -v drirc "${DD_DEBUG_DIR:-/tmp}/glprobe-trace.txt" | head -120 | sed 's/^/== glprobe (trace): /' + echo "== glprobe (trace): last pre-device query before Zink gave up: $(grep 'droiddeck-mali-compat: trace:' "${DD_DEBUG_DIR:-/tmp}/glprobe-trace.txt" | grep -v 'trace: extensions:' | tail -1)" command -v vulkaninfo >/dev/null 2>&1 && DROIDDECK_MALI_COMPAT_TRACE=1 timeout 20 vulkaninfo --summary 2>&1 | head -40 | sed 's/^/== glprobe (vulkaninfo): /' - bl_gl_ok= - for bl_variant in "ZINK_DEBUG=" "ZINK_DEBUG= ZINK_DESCRIPTORS=auto" "ZINK_DEBUG= LIBGL_KOPPER_DISABLE=true" "ZINK_DEBUG= DROIDDECK_MALI_COMPAT=0"; do - if env $bl_variant timeout 20 /usr/local/bin/droiddeck-glprobe 2>&1 | grep -v drirc | head -20 | sed "s/^/== glprobe ($bl_variant): /"; [ "${PIPESTATUS[0]}" = 0 ]; then - bl_gl_ok=$bl_variant + dd_gl_ok= + for dd_variant in "ZINK_DEBUG=" "ZINK_DEBUG= ZINK_DESCRIPTORS=auto" "ZINK_DEBUG= LIBGL_KOPPER_DISABLE=true" "ZINK_DEBUG= DROIDDECK_MALI_COMPAT=0"; do + if env $dd_variant timeout 20 /usr/local/bin/droiddeck-glprobe 2>&1 | grep -v drirc | head -20 | sed "s/^/== glprobe ($dd_variant): /"; [ "${PIPESTATUS[0]}" = 0 ]; then + dd_gl_ok=$dd_variant break fi done - if [ -n "$bl_gl_ok" ] && [ "$bl_gl_ok" != "ZINK_DEBUG= DROIDDECK_MALI_COMPAT=0" ]; then - for bl_kv in $bl_gl_ok; do - case $bl_kv in *=) unset "${bl_kv%=}" ;; *) export "$bl_kv" ;; esac + if [ -n "$dd_gl_ok" ] && [ "$dd_gl_ok" != "ZINK_DEBUG= DROIDDECK_MALI_COMPAT=0" ]; then + for dd_kv in $dd_gl_ok; do + case $dd_kv in *=) unset "${dd_kv%=}" ;; *) export "$dd_kv" ;; esac done - echo "== venus: GL through Zink starts with: $bl_gl_ok (the Steam client gets that)" + echo "== venus: GL through Zink starts with: $dd_gl_ok (the Steam client gets that)" else - [ -n "$bl_gl_ok" ] && echo "== venus: Zink starts only without the Mali compatibility layer (then without nullDescriptor); not used" + [ -n "$dd_gl_ok" ] && echo "== venus: Zink starts only without the Mali compatibility layer (then without nullDescriptor); not used" export GALLIUM_DRIVER=llvmpipe LIBGL_ALWAYS_SOFTWARE=1 unset MESA_LOADER_DRIVER_OVERRIDE LIBGL_KOPPER_DRI2 echo "== venus: GL through Zink did not start (see glprobe above); the Steam client's GL uses llvmpipe (software)" fi - unset bl_gl_ok bl_variant bl_kv + unset dd_gl_ok dd_variant dd_kv fi fi - rm -f "$HOME/.bl-restart-game" "$HOME/.bl-restarted-for" + rm -f "$HOME/.dd-restart-game" "$HOME/.dd-restarted-for" while :; do - rm -f "$HOME/.bl-restart-once" "$HOME/.bl-restart-lost" + rm -f "$HOME/.dd-restart-once" "$HOME/.dd-restart-lost" if [ -f "$steam_beta" ] && [ "$(cat "$steam_beta" 2>/dev/null)" != "$steam_channel" ]; then echo "== steam: client branch on disk was '$(cat "$steam_beta" 2>/dev/null)', set to '$steam_channel' to match -clientbeta" echo "$steam_channel" > "$steam_beta" fi - if [ -z "${_bl_counted:-}" ] && [ -z "${BL_DESKTOP:-}" ]; then + if [ -z "${_dd_counted:-}" ] && [ -z "${DD_DESKTOP:-}" ]; then echo start >> "$steam_root/package/droiddeck-unconfirmed" - _bl_counted=1 + _dd_counted=1 fi - if [ -n "${BL_STEAM_LANGUAGE:-}" ]; then + if [ -n "${DD_STEAM_LANGUAGE:-}" ]; then if [ "$steam_x64" = 1 ]; then - droiddeck-steam-language "${BL_X64_HOME:-$HOME/.droiddeck-x64}" "$BL_STEAM_LANGUAGE" || true + droiddeck-steam-language "${DD_X64_HOME:-$HOME/.droiddeck-x64}" "$DD_STEAM_LANGUAGE" || true else - droiddeck-steam-language "$HOME" "$BL_STEAM_LANGUAGE" || true + droiddeck-steam-language "$HOME" "$DD_STEAM_LANGUAGE" || true fi fi - step "starting the Steam client${BL_STEAM_UI:+ ($BL_STEAM_UI UI)}" + step "starting the Steam client${DD_STEAM_UI:+ ($DD_STEAM_UI UI)}" desktop_ui_pid= - if [ "${BL_STEAM_UI:-}" = desktop ]; then + if [ "${DD_STEAM_UI:-}" = desktop ]; then /usr/local/bin/droiddeck-steam-desktop-ui & desktop_ui_pid=$! fi steam_started=$SECONDS - PATH="$bl_steam_path" \ - BL_STEAM_WEBHELPER="$steam_root/steamrtarm64/steamwebhelper" \ - "${steam_client[@]}" "${_bl_ui[@]}" "${_bl_cdp[@]}" "${_bl_lang[@]}" -clientbeta "$steam_channel" \ - -no-cef-sandbox -cef-ozone-platform=x11 "${_bl_cef[@]}" "$@" + PATH="$dd_steam_path" \ + DD_STEAM_WEBHELPER="$steam_root/steamrtarm64/steamwebhelper" \ + "${steam_client[@]}" "${_dd_ui[@]}" "${_dd_cdp[@]}" "${_dd_lang[@]}" -clientbeta "$steam_channel" \ + -no-cef-sandbox -cef-ozone-platform=x11 "${_dd_cef[@]}" "$@" rc=$? steam_ran=$((SECONDS - steam_started)) if [ -n "$desktop_ui_pid" ]; then @@ -1980,20 +2020,20 @@ case $mode in if [ -f "$HOME/.config/droiddeck/fex-wanted" ] && [ -x /usr/local/bin/droiddeck-fex ]; then /usr/local/bin/droiddeck-fex status >/dev/null 2>&1 || true fi - if [ -n "${BL_ADDED_GAMES:-}" ] && [ -f "$BL_ADDED_GAMES" ]; then + if [ -n "${DD_ADDED_GAMES:-}" ] && [ -f "$DD_ADDED_GAMES" ]; then if [ "$steam_x64" = 0 ]; then - droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true - elif [ -n "${_bl_x64_tool:-}" ]; then - BL_COMPAT_TOOL=$_bl_x64_tool droiddeck-steam-shortcuts "$steam_root" "$BL_ADDED_GAMES" || true + droiddeck-steam-shortcuts "$steam_root" "$DD_ADDED_GAMES" || true + elif [ -n "${_dd_x64_tool:-}" ]; then + DD_COMPAT_TOOL=$_dd_x64_tool droiddeck-steam-shortcuts "$steam_root" "$DD_ADDED_GAMES" || true fi fi if [ "$steam_x64" = 1 ]; then - [ -z "${_bl_x64_tool:-}" ] || - BL_COMPAT_TOOL=$_bl_x64_tool steam-compatibility "$steam_root" --x64 >/dev/null 2>&1 || true + [ -z "${_dd_x64_tool:-}" ] || + DD_COMPAT_TOOL=$_dd_x64_tool steam-compatibility "$steam_root" --x64 >/dev/null 2>&1 || true droiddeck-steam-x64 --map-direct || true fi - if [ -f "$HOME/.bl-stop-requested" ]; then - rm -f "$HOME/.bl-stop-requested" "$HOME/.bl-restart-once" + if [ -f "$HOME/.dd-stop-requested" ]; then + rm -f "$HOME/.dd-stop-requested" "$HOME/.dd-restart-once" break fi if [ -e "$STEAMOS_STEAM_SHUTDOWN_SENTINEL" ]; then @@ -2008,32 +2048,32 @@ case $mode in set -- continue fi - if [ -s "$HOME/.bl-restart-game" ]; then - _bl_again=$(cat "$HOME/.bl-restart-game" 2>/dev/null) - rm -f "$HOME/.bl-restart-game" - case $_bl_again in + if [ -s "$HOME/.dd-restart-game" ]; then + _dd_again=$(cat "$HOME/.dd-restart-game" 2>/dev/null) + rm -f "$HOME/.dd-restart-game" + case $_dd_again in ''|0*|*[!0-9]*) ;; *) - echo "== steam: starting the client again to launch $_bl_again" + echo "== steam: starting the client again to launch $_dd_again" set -- - steam_hold_launch "$_bl_again" & + steam_hold_launch "$_dd_again" & continue ;; esac fi - if [ -f "$HOME/.bl-restart-lost" ]; then - rm -f "$HOME/.bl-restart-lost" + if [ -f "$HOME/.dd-restart-lost" ]; then + rm -f "$HOME/.dd-restart-lost" echo "== steam: starting the client again so it lists every shortcut" set -- continue fi - if [ -f "$HOME/.bl-restart-once" ]; then + if [ -f "$HOME/.dd-restart-once" ]; then echo "== steam: restarting once so the new compatibility layer is in the client's lists" set -- continue fi - if [ "$steam_x64" = 1 ] && [ "$rc" -eq 132 ] && [ -z "${_bl_x64_sigill:-}" ]; then - _bl_x64_sigill=1 + if [ "$steam_x64" = 1 ] && [ "$rc" -eq 132 ] && [ -z "${_dd_x64_sigill:-}" ]; then + _dd_x64_sigill=1 echo "== steam: the x86-64 client stopped on an illegal instruction after it updated itself; starting it again once" set -- continue @@ -2053,14 +2093,14 @@ case $mode in kill "$games_watcher" 2>/dev/null || true wait "$games_watcher" 2>/dev/null || true fi - if [ -n "${BL_DESKTOP:-}" ]; then + if [ -n "${DD_DESKTOP:-}" ]; then if [ -n "${decky_supervisor:-}" ]; then kill "$decky_supervisor" 2>/dev/null || true wait "$decky_supervisor" 2>/dev/null || true echo "== Decky: session supervisor stopped" fi - _bl_jobs=$(jobs -p) - [ -n "$_bl_jobs" ] && kill $_bl_jobs 2>/dev/null + _dd_jobs=$(jobs -p) + [ -n "$_dd_jobs" ] && kill $_dd_jobs 2>/dev/null echo "== steam: the client on the desktop has exited" else if [ -n "${decky_supervisor:-}" ]; then @@ -2068,12 +2108,12 @@ case $mode in wait "$decky_supervisor" 2>/dev/null || true echo "== Decky: session supervisor stopped" fi - _bl_jobs=$(jobs -p) - [ -n "$_bl_jobs" ] && kill $_bl_jobs 2>/dev/null + _dd_jobs=$(jobs -p) + [ -n "$_dd_jobs" ] && kill $_dd_jobs 2>/dev/null reap_orphans fi - if [ -n "${BL_STEAM_EXIT_FILE:-}" ]; then - printf '%s\n' "$rc" > "$BL_STEAM_EXIT_FILE" + if [ -n "${DD_STEAM_EXIT_FILE:-}" ]; then + printf '%s\n' "$rc" > "$DD_STEAM_EXIT_FILE" fi exit "$rc" ;; diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat index e96ce1c553..b39682bc29 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-compat @@ -1315,7 +1315,7 @@ def main(): files_only = sys.argv[1:2] == ["--files-only"] steam_root = sys.argv[2 if files_only else 1] try: - port = int(os.environ.get("BL_CDP_PORT", "")) + port = int(os.environ.get("DD_CDP_PORT", "")) except ValueError: say("no devtools port for this session; the client's mapping is kept through config.vdf") return 0 @@ -1339,7 +1339,7 @@ def main(): watcher = Watcher([COMPAT["state_path"]("request.json"), COMPAT["state_path"]("games.json"), os.path.join(steam_root, "appcache", "appinfo.vdf")] + [os.path.join(lib, "steamapps", "libraryfolders.vdf") for lib in (steam_root, COMPAT["LIBRARY"] + "-sd")]) - steamos = os.environ.get("BL_STEAMDECK") == "1" and os.environ.get("BL_STEAM_UI") != "desktop" + steamos = os.environ.get("DD_STEAMDECK") == "1" and os.environ.get("DD_STEAM_UI") != "desktop" helper = Helper(steam_root, port, steamos) failures = 0 last = None diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-desktop-ui b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-desktop-ui index 88d60dde6a..37fefbafaa 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-desktop-ui +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-desktop-ui @@ -21,9 +21,9 @@ def select_desktop(evaluate, timeout=90): if __name__ == '__main__': - base = os.environ.get('BL_LAUNCH_DIR') + base = os.environ.get('DD_LAUNCH_DIR') if not base: - raise SystemExit('BL_LAUNCH_DIR is not set') + raise SystemExit('DD_LAUNCH_DIR is not set') agent = runpy.run_path('/usr/local/bin/droiddeck-agent') selected = select_desktop(lambda expression: agent['cdp_eval']( Path(base) / 'agent', expression, timeout=2)) diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games index ac8213d41e..c618cadf35 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-games @@ -1,9 +1,11 @@ #!/usr/bin/env python3 import ctypes as C +import functools import json import os from pathlib import Path import re +import runpy import shlex import subprocess import sys @@ -132,7 +134,7 @@ def method(obj, slot, result, *args): def probe(steam_root, ids): - library = C.CDLL(os.environ.get("BL_STEAMCLIENT") or str(Path(steam_root) / "steamrtarm64/steamclient.so")) + library = C.CDLL(os.environ.get("DD_STEAMCLIENT") or str(Path(steam_root) / "steamrtarm64/steamclient.so")) library.CreateInterface.argtypes = [C.c_char_p, C.c_void_p] library.CreateInterface.restype = C.c_void_p client = library.CreateInterface(b"SteamClient020", None) @@ -182,8 +184,8 @@ def downloads_idle(steam_root): def request_restart(steam_root): - Path(os.environ.get("HOME", "/root"), ".bl-restart-once").touch() - command = shlex.split(os.environ.get("BL_STEAM_SHUTDOWN", "")) or [str(Path(steam_root) / "steamrtarm64/steam"), "-shutdown"] + Path(os.environ.get("HOME", "/root"), ".dd-restart-once").touch() + command = shlex.split(os.environ.get("DD_STEAM_SHUTDOWN", "")) or [str(Path(steam_root) / "steamrtarm64/steam"), "-shutdown"] subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30) @@ -229,7 +231,7 @@ def remember_tried(steam_root, account, appids): def watch(steam_root, listing): games = [game for game in read_json(listing, []) if not store_game(game) and not game.get("native")] - if os.environ.get("BL_STEAM_OFFLINE") == "1" or not games: + if os.environ.get("DD_STEAM_OFFLINE") == "1" or not games: return candidates, sources = {}, {} next_lookup = 0 @@ -257,7 +259,7 @@ def watch(steam_root, listing): elif candidates and (key != probed or now >= next_probe): probed, next_probe = key, now + 300 try: - probe_env = dict(os.environ, HOME=os.environ["BL_STEAM_IPC_HOME"]) if os.environ.get("BL_STEAM_IPC_HOME") else None + probe_env = dict(os.environ, HOME=os.environ["DD_STEAM_IPC_HOME"]) if os.environ.get("DD_STEAM_IPC_HOME") else None result = subprocess.run([sys.executable, __file__, "probe", steam_root, *map(str, sorted(set(candidates.values())))], capture_output=True, text=True, timeout=15, env=probe_env) @@ -445,18 +447,22 @@ def park(steamapps): print(f"droiddeck-steam-games: {appid} is not here this session; its install is set aside until it is") +@functools.lru_cache(maxsize=1) +def compatibility(): + return runpy.run_path(os.path.join(os.path.dirname(os.path.abspath(__file__)), "steam-compatibility")) + + def seed_install(steam_root, game, appid): steamapps = Path(steam_root) / "steamapps" common = steamapps / "common" name = f"DroidDeck-{appid}" target = common / name source = Path(game["folder"]) - title = game["name"].replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ").replace("\r", " ") - minimal = ('"AppState"\n{\n' + f' "appid" "{appid}"\n "Universe" "1"\n "name" "{title}"\n' - + f' "StateFlags" "4"\n "installdir" "{name}"\n' + '}\n') + manifest_text = compatibility()["manifest_text"] + minimal = manifest_text(appid, game["name"], name) legacy = minimal.replace(' "Universe" "1"\n', '') # Steam checks every file of an import with no build before updating it, from scratch each time it is interrupted. - bare = minimal[:-2] + ' "AutoUpdateBehavior" "1"\n}\n' + bare = manifest_text(appid, game["name"], name, True) build = installed_build(source, appid, name) if build is None: content = bare diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install index f3098fd3ea..c58790f87a 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-install @@ -6,7 +6,7 @@ stable_channel=steamdeck_stable steam_root=${XDG_DATA_HOME:-$HOME/.local/share}/Steam channel_state=$steam_root/package/droiddeck-channel pinned=1 -wanted=${BL_STEAM_CHANNEL:-$(cat "$HOME/.config/droiddeck/steam-channel" 2>/dev/null || true)} +wanted=${DD_STEAM_CHANNEL:-$(cat "$HOME/.config/droiddeck/steam-channel" 2>/dev/null || true)} case $wanted in stable|"$stable_channel") steam_channel=$stable_channel ;; beta|"$beta_channel") steam_channel=$beta_channel ;; @@ -24,7 +24,7 @@ manifest=steam_client_${steam_channel}_linuxarm64 stamp=$steam_root/package/droiddeck-installed legacy_stamp=$steam_root/package/bannerlator-installed unconfirmed=$steam_root/package/droiddeck-unconfirmed -repair_request=$HOME/.bl-steam-repair +repair_request=$HOME/.dd-steam-repair parts=$steam_root/package/droiddeck-download if [ -f "$legacy_stamp" ] && [ ! -f "$stamp" ]; then mv -f "$legacy_stamp" "$stamp" || true @@ -85,7 +85,7 @@ size_of() { echo $((n)) } limits=(--connect-timeout 30 --speed-limit 4096 --speed-time 60) -read -r -a delays <<< "${BL_STEAM_RETRY_DELAYS:-5 10 20 30 30}" +read -r -a delays <<< "${DD_STEAM_RETRY_DELAYS:-5 10 20 30 30}" step() { echo "== STEP $(date -u +%H:%M:%S) $*"; } progress() { diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-launch b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-launch index 346b32d7f2..62b7eb15d3 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-launch +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-launch @@ -11,13 +11,13 @@ case $target in *) url=steam://rungameid/$target ;; esac -if [ "$ui" = desktop ] && [ "${BL_DESKTOP:-}" = 1 ]; then +if [ "$ui" = desktop ] && [ "${DD_DESKTOP:-}" = 1 ]; then case ",${MESA_VK_WSI_DEBUG:-}," in *,sw,*) ;; *) export MESA_VK_WSI_DEBUG=${MESA_VK_WSI_DEBUG:+$MESA_VK_WSI_DEBUG,}sw ;; esac - if [ "${BL_STEAM_CLIENT_ARCH:-}" = x86_64 ]; then - client_home=${BL_X64_HOME:-${HOME:-/root}/.droiddeck-x64} + if [ "${DD_STEAM_CLIENT_ARCH:-}" = x86_64 ]; then + client_home=${DD_X64_HOME:-${HOME:-/root}/.droiddeck-x64} client=(/usr/local/bin/droiddeck-steam-x64 --exec) else steam_root=${XDG_DATA_HOME:-${HOME:-/root}/.local/share}/Steam @@ -25,7 +25,7 @@ if [ "$ui" = desktop ] && [ "${BL_DESKTOP:-}" = 1 ]; then client_home=$HOME client=("$steam_root/steamrtarm64/steam") fi - if [ "${BL_BOTTOM_DESKTOP:-}" = 1 ]; then + if [ "${DD_BOTTOM_DESKTOP:-}" = 1 ]; then pid=$(cat "$client_home/.steam/steam.pid" 2>/dev/null || true) if [ -p "$client_home/.steam/steam.pipe" ] && [[ "$pid" =~ ^[0-9]+$ ]] && kill -0 "$pid" 2>/dev/null; then # The top screen's client takes the request, so games open there. @@ -48,13 +48,13 @@ if [ "$ui" = desktop ] && [ "${BL_DESKTOP:-}" = 1 ]; then exit 69 fi [ "$url" = steam://exit ] && exit 0 - export BL_INSIDE=1 BL_STEAM_UI=desktop + export DD_INSIDE=1 DD_STEAM_UI=desktop exec /usr/local/bin/droiddeck-session steam "${url:-steam://open/library}" fi -dir=${BL_LAUNCH_DIR:-} +dir=${DD_LAUNCH_DIR:-} if [ -z "$dir" ] || [ ! -d "$dir" ]; then - echo "droiddeck-steam-launch: not inside a DroidDeck session (BL_LAUNCH_DIR unset)" >&2 + echo "droiddeck-steam-launch: not inside a DroidDeck session (DD_LAUNCH_DIR unset)" >&2 exit 69 fi printf 'ui=%s\nurl=%s\n' "$ui" "$url" > "$dir/steam-launch.tmp" && mv -f "$dir/steam-launch.tmp" "$dir/steam-launch" diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-library b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-library index 5577e1aad7..cac12173dc 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-library +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-library @@ -2,9 +2,11 @@ import json import os import re +import runpy import sys -LIBRARIES = (("/mnt/droiddeck-sd", os.environ.get("BL_LIBRARY_LABEL", "SD Card")),) +BIN_DIR = os.path.dirname(os.path.abspath(__file__)) +LIBRARIES = (("/mnt/droiddeck-sd", os.environ.get("DD_LIBRARY_LABEL", "SD Card")),) MAIN_LABEL = "Internal Storage" @@ -50,6 +52,77 @@ def register(steam_root, library, label): return len(apps) +def installdirs(libraries): + found = set() + for library in libraries: + steamapps = os.path.join(library, "steamapps") + try: + names = os.listdir(steamapps) + except OSError: + continue + for name in names: + if not re.fullmatch(r"appmanifest_\d+\.acf", name): + continue + try: + with open(os.path.join(steamapps, name), encoding="utf-8", errors="replace") as f: + m = re.search(r'"installdir"\s+"([^"]*)"', f.read(), re.I) + except OSError: + continue + if m: + found.add(m.group(1)) + return found + + +def populated(path): + try: + with os.scandir(path) as entries: + return next(entries, None) is not None + except OSError: + return False + + +def adoptable(library, known): + common = os.path.join(library, "steamapps", "common") + try: + names = sorted(os.listdir(common)) + except OSError: + return [] + return [n for n in names if n not in known and not n.startswith(".") + and os.path.isdir(os.path.join(common, n)) and populated(os.path.join(common, n))] + + +def adopt(steam_root, library): + compat = runpy.run_path(os.path.join(BIN_DIR, "steam-compatibility")) + known = compat["libraries"](steam_root) + folders = adoptable(library, installdirs(known + [library])) + if not folders: + return 0 + entries = compat["appinfo_entries"](os.path.join(steam_root, "appcache", "appinfo.vdf")) + by_dir = {} + for app, info in entries.items(): + if app not in compat["NOT_GAMES"] and info["type"] in compat["PLAYABLE_TYPES"] and info["installdir"]: + by_dir.setdefault(info["installdir"], []).append((app, info)) + steamapps = os.path.join(library, "steamapps") + adopted = 0 + for folder in folders: + matches = by_dir.get(folder, []) + games = [m for m in matches if m[1]["type"] == "game"] or matches + if len(games) != 1: + continue + app, info = games[0] + if any(os.path.isfile(os.path.join(root, "steamapps", "appmanifest_%s.acf" % app)) + for root in known + [library]): + continue + try: + with open(os.path.join(steamapps, "appmanifest_%s.acf" % app), "x", encoding="utf-8") as f: + f.write(compat["manifest_text"](app, info["name"] or folder, folder, True)) + except OSError: + continue + adopted += 1 + print("droiddeck-steam-library: adopted %s as app %s in %s" % (folder, app, library)) + return adopted + + RETIRED = ("/mnt/bannerlator",) RENAMED = (("/mnt/bannerlator-sd", "/mnt/droiddeck-sd"),) @@ -146,7 +219,7 @@ ADDED_DIR = "/mnt/droiddeck-lib/" def wanted(): - listing = os.environ.get("BL_STEAM_LIBRARIES") + listing = os.environ.get("DD_STEAM_LIBRARIES") if not listing: return None try: @@ -176,6 +249,7 @@ def main(): managed = libraries is not None for library, label in libraries if managed else LIBRARIES: if os.path.isdir(os.path.join(library, "steamapps")): + adopt(steam_root, library) register(steam_root, library, label) relabel(steam_root, library, label) else: diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shim b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shim index 6ba870b14e..da8e2c48c4 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shim +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shim @@ -1,6 +1,6 @@ #!/bin/bash set -u -if [ "${BL_DESKTOP:-}" = 1 ]; then +if [ "${DD_DESKTOP:-}" = 1 ]; then url= ui=desktop for arg in "$@"; do @@ -12,5 +12,5 @@ if [ "${BL_DESKTOP:-}" = 1 ]; then done exec /usr/local/bin/droiddeck-steam-launch "$ui" ${url:+"$url"} fi -[ "${BL_STEAM_CLIENT_ARCH:-}" = x86_64 ] && exec /usr/local/bin/droiddeck-steam-x64 --exec "$@" +[ "${DD_STEAM_CLIENT_ARCH:-}" = x86_64 ] && exec /usr/local/bin/droiddeck-steam-x64 --exec "$@" exec "${HOME:-/root}/.local/share/Steam/steamrtarm64/steam" "$@" diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shortcuts b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shortcuts index 5e37501b35..4cb3301d41 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shortcuts +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-shortcuts @@ -345,7 +345,7 @@ def main(): cfg = os.path.join(steam_root, "config", "config.vdf") if os.path.isfile(cfg) and (ours or routes): tools = os.path.join(steam_root, "compatibilitytools.d") - x64_tool = os.environ.get("BL_COMPAT_TOOL") + x64_tool = os.environ.get("DD_COMPAT_TOOL") own = {} if x64_tool: protect = {compat.first_key(os.path.join(tools, e, "compatibilitytool.vdf"), ["compatibilitytools", "compat_tools"]) or e: e diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-taskset b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-taskset index 8973fc7f51..163183fc81 100644 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-taskset +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-taskset @@ -4,7 +4,7 @@ # before starting the browser when Android denies sched_setaffinity. set -u if [ "$#" -ge 2 ] && [[ "$1" =~ ^(0[xX])?[0-9a-fA-F]+$ ]] && - [ -n "${BL_STEAM_WEBHELPER:-}" ] && [ "$2" -ef "$BL_STEAM_WEBHELPER" ]; then + [ -n "${DD_STEAM_WEBHELPER:-}" ] && [ "$2" -ef "$DD_STEAM_WEBHELPER" ]; then mask=$1 shift # Pin this wrapper before exec; never retry a helper that has already run. diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 index 0aeb0e594c..2c77626a1c 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-steam-x64 @@ -7,7 +7,7 @@ X64_CHANNEL=steamdeck_publicbeta MANIFEST=steam_client_${X64_CHANNEL}_steamrt64 REAL_HOME=${HOME:-/root} -X64_HOME=${BL_X64_HOME:-$REAL_HOME/.droiddeck-x64} +X64_HOME=${DD_X64_HOME:-$REAL_HOME/.droiddeck-x64} ROOTFS=$X64_HOME/rootfs STEAM_X64=$X64_HOME/.local/share/Steam ARM_STEAM=${XDG_DATA_HOME:-$REAL_HOME/.local/share}/Steam @@ -88,7 +88,7 @@ x64_map_direct() { done python3 - "$mode" "$STEAM_X64/config/config.vdf" "$STEAM_X64/appcache/appinfo.vdf" "$X64_HOME/direct-auto.json" \ "$X64_HOME/direct-sniper" "$libraries" "$(x64_default_tool)" \ - "$REAL_HOME/.bl-compat-pending" ${BL_X64_DIRECT_APPS:-550} \ + "$REAL_HOME/.dd-compat-pending" ${DD_X64_DIRECT_APPS:-550} \ <<'PY' || { [ "$mode" = live ] || step "could not map titles to DroidDeck direct"; } # Steam does not swap an installed build when the tool changes: a title installed for Windows stays on Proton. import json, os, re, struct, sys @@ -356,7 +356,7 @@ if [ ! -f "$ROOTFS/.droiddeck-complete" ]; then fi echo "== x86-64 rootfs: $(sed -n 's|.*/download/\([^/]*\)/.*|\1|p' <<<"$ROOTFS_URL") (sha256 ${ROOTFS_SHA256:0:12})" >&2 : > "$ROOTFS/etc/ld.so.preload" -for lib in libblsession libfakeinput; do +for lib in libddsession libfakeinput; do have=0 arches="x86_64 i386"; [ "$lib" = libfakeinput ] && arches=x86_64 rm -f "$ROOTFS/usr/local/lib/i386-linux-gnu/libfakeinput.so" @@ -371,11 +371,11 @@ for lib in libblsession libfakeinput; do elif [ "$have" = 1 ]; then echo "/usr/local/\$LIB/$lib.so" >> "$ROOTFS/etc/ld.so.preload" else step "warning: no x86 build of $lib (/usr/local/lib/droiddeck-fex/x86_64/$lib.so)"; fi done -rm -f "$ROOTFS/usr/local/lib/libblsession-x86_64.so" "$ROOTFS/usr/local/lib/libfakeinput-x86_64.so" +rm -f "$ROOTFS/usr/local/lib/libddsession-x86_64.so" "$ROOTFS/usr/local/lib/libfakeinput-x86_64.so" unconfirmed=$STEAM_X64/package/droiddeck-unconfirmed if [ -d "${unconfirmed%/*}" ] && ! grep -qx tracked "$unconfirmed" 2>/dev/null; then echo tracked > "$unconfirmed"; fi x64_repair= -if [ "${BL_X64_REPAIR:-0}" = 1 ]; then +if [ "${DD_X64_REPAIR:-0}" = 1 ]; then x64_repair=requested elif [ -f "$unconfirmed" ] && ! grep -qx repaired "$unconfirmed" && [ "$(grep -cx start "$unconfirmed")" -ge 2 ]; then x64_repair="the client was started $(grep -cx start "$unconfirmed") times without showing anything" @@ -502,7 +502,7 @@ marker=$(cat "${0%/*}/vac-marker" 2>/dev/null) case "$*" in *hl2.sh*|*hl2_linux*|*srcds*) [ -n "$marker" ] && [ -f "$marker" ] && set -- "$@" -condebug ;; esac # game-gpu.env is rewritten whenever the launcher runs; game-gpu.local is the user's and is read after it. gpu=$HOME/game-gpu.env -if [ -f "$gpu" ] && [ "${BL_X64_GAME_SOFTWARE:-0}" != 1 ]; then +if [ -f "$gpu" ] && [ "${DD_X64_GAME_SOFTWARE:-0}" != 1 ]; then . "$gpu" [ -f "$HOME/game-gpu.local" ] && . "$HOME/game-gpu.local" else @@ -580,9 +580,9 @@ VDF x64_sync_login if ! pgrep -f 'steamrt64/steam( |$)' >/dev/null 2>&1; then listing_ok=0 - if BL_X64_SHARED=$X64_HOME/shared/arm64 python3 - "$STEAM_X64" "${BL_X64_STEAM_LIBRARIES:-}" "$STEAM_X64/config/libraryfolders.vdf" "$STEAM_X64/steamapps/libraryfolders.vdf" <<'PY'; then + if DD_X64_SHARED=$X64_HOME/shared/arm64 python3 - "$STEAM_X64" "${DD_X64_STEAM_LIBRARIES:-}" "$STEAM_X64/config/libraryfolders.vdf" "$STEAM_X64/steamapps/libraryfolders.vdf" <<'PY'; then import json, os, re, sys -keep = {os.path.realpath(sys.argv[1]), os.path.realpath(os.environ["BL_X64_SHARED"])} +keep = {os.path.realpath(sys.argv[1]), os.path.realpath(os.environ["DD_X64_SHARED"])} # Without the session's list nothing is known about the card: leave the folders as they are. if not sys.argv[2]: sys.exit(3) @@ -622,7 +622,7 @@ PY step "could not check the x86-64 client's library folders" fi if [ "$listing_ok" = 1 ]; then - BL_STEAM_LIBRARIES=$BL_X64_STEAM_LIBRARIES droiddeck-steam-library "$STEAM_X64" || + DD_STEAM_LIBRARIES=$DD_X64_STEAM_LIBRARIES droiddeck-steam-library "$STEAM_X64" || step "could not add the card to the x86-64 client's library folders" fi fi @@ -706,11 +706,11 @@ PY } x64_gpu() { - [ "${BL_X64_SOFTWARE:-0}" != 1 ] && [ -d /usr/local/share/fex-emu/GuestThunks ] && [ -d /usr/local/lib/fex-emu/HostThunks ] + [ "${DD_X64_SOFTWARE:-0}" != 1 ] && [ -d /usr/local/share/fex-emu/GuestThunks ] && [ -d /usr/local/lib/fex-emu/HostThunks ] } x64_webhelper_gpu() { - x64_gpu && [ "${BL_X64_CLIENT_SOFTWARE:-0}" != 1 ] && [ "${BL_X64_CEF_GPU:-1}" != 0 ] + x64_gpu && [ "${DD_X64_CLIENT_SOFTWARE:-0}" != 1 ] && [ "${DD_X64_CEF_GPU:-1}" != 0 ] } x64_env() { @@ -729,7 +729,7 @@ if x64_gpu; then done } > "$X64_HOME/game-gpu.env" fi -if x64_gpu && [ "${BL_X64_CLIENT_SOFTWARE:-0}" != 1 ]; then +if x64_gpu && [ "${DD_X64_CLIENT_SOFTWARE:-0}" != 1 ]; then export FEX_THUNKCONFIG=$X64_HOME/thunks.json unset LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE else @@ -737,7 +737,7 @@ unset FEX_THUNKCONFIG $gpu_vars export LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe export LIBGL_DRI3_DISABLE=1 fi -[ "${BL_X64_FP_OFF:-0}" = 1 ] && export PROOT_FP_OFF=1 +[ "${DD_X64_FP_OFF:-0}" = 1 ] && export PROOT_FP_OFF=1 export FEX_TSOENABLED=${FEX_TSOENABLED:-1} FEX_VECTORTSOENABLED=${FEX_VECTORTSOENABLED:-0} \ FEX_MEMCPYSETTSOENABLED=${FEX_MEMCPYSETTSOENABLED:-0} FEX_HALFBARRIERTSOENABLED=${FEX_HALFBARRIERTSOENABLED:-0} \ FEX_X87REDUCEDPRECISION=${FEX_X87REDUCEDPRECISION:-1} FEX_MULTIBLOCK=${FEX_MULTIBLOCK:-1} @@ -750,7 +750,7 @@ export STEAM_RUNTIME=1 [ -d "$X64_HOME/steamrt-shim/bin" ] && export PATH=$X64_HOME/steamrt-shim/bin:$PATH export LD_LIBRARY_PATH=$STEAM_X64/steamrt64:$STEAM_X64/steamrt64/panorama:$X64_HOME/steamrt-libs export STEAM_STEAMRT_RECURSION_GUARD=1 -export BL_WEBHELPER_HIDE_TRACER=1 +export DD_WEBHELPER_HIDE_TRACER=1 } x64_manifest_version() { @@ -760,7 +760,7 @@ x64_manifest_version() { } x64_gpu_probe() { - local fex=${BL_FEX:-/usr/local/bin/FEX} + local fex=${DD_FEX:-/usr/local/bin/FEX} echo "== x86-64 GPU probe (x86 glxinfo and vulkaninfo through FEX):" ( unset LD_LIBRARY_PATH @@ -795,23 +795,23 @@ x64_arm_webhelper_cpu_supported() { x64_exec() { x64_env cd "$STEAM_X64" - if [ "${BL_X64_X86_WEBHELPER:-0}" != 1 ] && [ -x /usr/local/bin/droiddeck-x64-arm-webhelper ] && + if [ "${DD_X64_X86_WEBHELPER:-0}" != 1 ] && [ -x /usr/local/bin/droiddeck-x64-arm-webhelper ] && [ -x "$ARM_STEAM/steamrtarm64/steamwebhelper" ] && x64_arm_webhelper_cpu_supported; then local chan x86_build arm_build chan=$(cat "$STEAM_X64/package/beta" 2>/dev/null || echo "$X64_CHANNEL") x86_build=$(awk -F'"' '$2 == "version" { print $4; exit }' "$STEAM_X64/package/steam_client_${chan}_steamrt64.manifest" 2>/dev/null || true) arm_build=$(awk -F'"' '$2 == "version" { print $4; exit }' "$ARM_STEAM/package/steam_client_${chan}_linuxarm64.manifest" 2>/dev/null || true) if [ -n "$x86_build" ] && [ "$x86_build" = "$arm_build" ]; then - export BL_X64_ARM_WEBHELPER=/usr/local/bin/droiddeck-x64-arm-webhelper + export DD_X64_ARM_WEBHELPER=/usr/local/bin/droiddeck-x64-arm-webhelper else echo "== x86-64 client build ${x86_build:-?}, arm64 web helper's ${arm_build:-?}: keeping the x86 web helper" >&2 fi fi - if [ -z "${BL_X64_ARM_WEBHELPER:-}" ] && x64_webhelper_gpu; then - export BL_WEBHELPER_ARGS="--ignore-gpu-blocklist --use-gl=angle --use-angle=gl --ozone-platform=x11" - [ -x /usr/local/bin/droiddeck-x64-webhelper ] && export BL_X64_ARM_WEBHELPER=/usr/local/bin/droiddeck-x64-webhelper - elif [ -z "${BL_X64_ARM_WEBHELPER:-}" ]; then - export BL_WEBHELPER_ARGS=stock + if [ -z "${DD_X64_ARM_WEBHELPER:-}" ] && x64_webhelper_gpu; then + export DD_WEBHELPER_ARGS="--ignore-gpu-blocklist --use-gl=angle --use-angle=gl --ozone-platform=x11" + [ -x /usr/local/bin/droiddeck-x64-webhelper ] && export DD_X64_ARM_WEBHELPER=/usr/local/bin/droiddeck-x64-webhelper + elif [ -z "${DD_X64_ARM_WEBHELPER:-}" ]; then + export DD_WEBHELPER_ARGS=stock local a args=() soft=0 for a in "$@"; do case $a in @@ -827,7 +827,7 @@ x64_exec() { grep --line-buffered -oE 'Downloading update \([0-9,]+ of [0-9,]+ KB\)|^[[:space:]]*(\[[^]]+\][[:space:]]*)*(Extracting package|Installing update)\.\.\.[[:space:]]*$' | sed -u 's/,//g' >&2 ) & echo "== x86-64 client: steamrt64 $(x64_manifest_version steamrt64) (the client may update itself)" >&2 x64_webhelper_gpu && { x64_gpu_watch >&2 & } - exec "${BL_FEX:-/usr/local/bin/FEX}" "$STEAM_X64/steamrt64/steam" "$@" + exec "${DD_FEX:-/usr/local/bin/FEX}" "$STEAM_X64/steamrt64/steam" "$@" } x64_share() { @@ -969,8 +969,8 @@ if pgrep -f 'steamrtarm64/steam( |$)' >/dev/null 2>&1; then fi x64_prepare step "FEX, rootfs and client ready" -if [ -n "${BL_FEXSERVER_LOG:-}" ]; then - FEX_ROOTFS=$ROOTFS "$(dirname "${BL_FEX:-/usr/local/bin/FEX}")/FEXServer" -f -p 600 >"$BL_FEXSERVER_LOG" 2>&1 & +if [ -n "${DD_FEXSERVER_LOG:-}" ]; then + FEX_ROOTFS=$ROOTFS "$(dirname "${DD_FEX:-/usr/local/bin/FEX}")/FEXServer" -f -p 600 >"$DD_FEXSERVER_LOG" 2>&1 & sleep 1 fi x64_bus= x64_nm= x64_pin= @@ -1017,11 +1017,11 @@ if ! pgrep -f 'steamrt64/steam( |$)' >/dev/null 2>&1; then { [ -e "$f" ] || [ -L "$f" ]; } && rm -f "$f" done fi -if [ -n "${BL_CLIENT_CPUS:-}" ] && command -v taskset >/dev/null 2>&1; then +if [ -n "${DD_CLIENT_CPUS:-}" ] && command -v taskset >/dev/null 2>&1; then ( while sleep 5; do for pid in $(ps -A -o PID,ARGS | awk '($2 ~ /^(.*\/)?FEX(Interpreter)?$/) && ($3 ~ /steamrt64\/steam$/ || $3 ~ /steamwebhelper$/) {print $1} $2 ~ /steamrtarm64\/steamwebhelper$/ {print $1}'); do - taskset -a -p -c "$BL_CLIENT_CPUS" "$pid" >/dev/null 2>&1 + taskset -a -p -c "$DD_CLIENT_CPUS" "$pid" >/dev/null 2>&1 done done ) & @@ -1031,7 +1031,7 @@ for attempt in 1 2 3 4 5; do echo "$X64_CHANNEL" > "$STEAM_X64/package/beta" step "starting the x86-64 SteamRT3 client under FEX (attempt $attempt): $*" rc=0 - if [ "${BL_X64_X86_WEBHELPER:-0}" != 1 ] || x64_webhelper_gpu; then cef=(-cef-force-gpu -cef-ozone-platform=x11 -cef-use-gl=angle -cef-use-angle=vulkan); else cef=(-cef-disable-gpu); fi + if [ "${DD_X64_X86_WEBHELPER:-0}" != 1 ] || x64_webhelper_gpu; then cef=(-cef-force-gpu -cef-ozone-platform=x11 -cef-use-gl=angle -cef-use-angle=vulkan); else cef=(-cef-disable-gpu); fi ( x64_exec -clientbeta "$X64_CHANNEL" -no-cef-sandbox "${cef[@]}" "$@" ) >>"$LOG" 2>&1 || rc=$? step "client exited rc=$rc" [ "$rc" = 42 ] || break diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch b/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch index d4cb905f4c..5031cb93dc 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-store-launch @@ -7,6 +7,7 @@ import os import re import shlex import shutil +import stat import sys import time import subprocess @@ -115,7 +116,7 @@ def through_client(folder, sidecar, timeout=CLIENT_TIMEOUT): return str(answer.get("reason") or "failed") -def ask(channel, request, timeout=TIMEOUT): +def ask(channel, request, timeout=TIMEOUT, claim=False): req_dir, resp_dir = channel / "req", channel / "resp" req_dir.mkdir(parents=True, exist_ok=True) resp_dir.mkdir(parents=True, exist_ok=True) @@ -124,19 +125,33 @@ def ask(channel, request, timeout=TIMEOUT): tmp.write_text(json.dumps(request)) os.rename(tmp, req_dir / (rid + ".json")) answer = resp_dir / (rid + ".json") - deadline = time.monotonic() + timeout - while time.monotonic() < deadline: + + def wait(seconds): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + try: + value = json.loads(answer.read_text()) + answer.unlink() + return value + except (OSError, ValueError): + time.sleep(0.05) + return None + + value = wait(timeout) + if value is not None: + return value + for pending in (req_dir / (rid + ".json"), resp_dir / (rid + ".taken")): + abandoned = pending.with_name(rid + ".abandoned") try: - value = json.loads(answer.read_text()) - answer.unlink() - return value - except (OSError, ValueError): - time.sleep(0.05) - try: - (req_dir / (rid + ".json")).unlink() - except OSError: - pass - return None + os.rename(pending, abandoned) + except OSError: + continue + try: + abandoned.unlink() + except OSError: + pass + return None + return wait(CLAIMED_TIMEOUT) if claim else None def windows_path(unix): @@ -192,7 +207,7 @@ def server_socket(pfx): st = os.stat(pfx) except OSError: return None - base = os.environ.get("BL_WINE_SERVER_BASE") or "/tmp/.wine-%d" % os.getuid() + base = os.environ.get("DD_WINE_SERVER_BASE") or "/tmp/.wine-%d" % os.getuid() return Path(base) / ("server-%x-%x" % (st.st_dev, st.st_ino)) / "socket" @@ -254,7 +269,8 @@ def create_prefix(compat_data, proton, timeout=120): CLOUD_TIMEOUT = 15.0 -CLOUD_STORES = ("gog", "epic") +CLAIMED_TIMEOUT = 120.0 +CLOUD_STORES = ("gog", "epic", "ea", "ubisoft") STORE_GAME = 10 RAN = 11 RAN_FAILED = 12 @@ -264,7 +280,7 @@ BATTLENET_LAUNCH = re.compile(r'(?i)^--exec=\s*"?launch\s+([A-Za-z0-9_]{1,16})"? def battlenet(argv, env=os.environ): - if env.get("BL_BATTLENET"): + if env.get("DD_BATTLENET"): return None exe, code = False, None for raw in argv: @@ -285,12 +301,14 @@ def cloud_on(sidecar): def exited(argv, code=0): found = find_store_game(argv) - launch_dir = os.environ.get("BL_LAUNCH_DIR", "") + launch_dir = os.environ.get("DD_LAUNCH_DIR", "") if found is not None and launch_dir and str(found[1].get("store")) == "rockstar": ask(Path(launch_dir) / "stores", {"op": "rockstar-exited", "store": "rockstar", "id": str(found[1].get("id"))}, timeout=1.0) compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH") if compat_data: (Path(compat_data) / "pfx" / ROCKSTAR_FOLDER / "launch.json").unlink(missing_ok=True) + for line in rockstar_launcher_log(compat_data): + log("rockstar launcher: " + line) return 0 if found is not None and str(found[1].get("store")) == "epic" and os.environ.get(EPIC_HANDLED) != "1" \ and os.access(EPIC_CLIENT, os.X_OK): @@ -301,11 +319,14 @@ def exited(argv, code=0): if found is not None and launch_dir and str(found[1].get("store")) == "ea": ask(Path(launch_dir) / "stores", {"op": "ea-exited", "store": "ea", "id": str(found[1].get("id"))}, timeout=1.0) log("ea %s exited" % found[1].get("id")) - return 0 if found is None or not launch_dir or not cloud_on(found[1]): return 0 store, game = str(found[1].get("store")), str(found[1].get("id")) - ask(Path(launch_dir) / "stores", {"op": "cloud-up", "store": store, "id": game}, timeout=1.0) + try: + ask(Path(launch_dir) / "stores", {"op": "cloud-up", "store": store, "id": game}, timeout=1.0) + except OSError as error: + log("cloud %s %s up not requested (%s)" % (store, game, type(error).__name__)) + return 0 log("cloud %s %s up requested" % (store, game)) return 0 @@ -320,6 +341,29 @@ ROCKSTAR_TITLES = {"gta3": "Grand Theft Auto III", "gtavc": "Grand Theft Auto: V "gta4": "Grand Theft Auto IV", "lanoire": "LANoireMTL"} +def rockstar_launcher_log(compat_data, limit=65536): + pfx = Path(compat_data) / "pfx" + target = pfx / ROCKSTAR_FOLDER + if not target.resolve().is_relative_to(pfx.resolve()): + return [] + path = target / "launcher.log" + try: + descriptor = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + except OSError: + return [] + try: + if not stat.S_ISREG(os.fstat(descriptor).st_mode): + return [] + with os.fdopen(descriptor, "rb", closefd=False) as source: + data = source.read(limit) + path.unlink(missing_ok=True) + except OSError: + return [] + finally: + os.close(descriptor) + return [line.strip() for line in data.decode("utf-8", "replace").splitlines() if line.strip()] + + def rockstar_sdk(folder, sidecar): if str(sidecar.get("id")) in ("gta4", "lanoire"): return True @@ -464,6 +508,7 @@ def prepare_rockstar(folder, sidecar, compat_data, launch_dir, proton="", ask_ap return "invalid-service-path" config = target / "launch.json" config.unlink(missing_ok=True) + (target / "launcher.log").unlink(missing_ok=True) legacy = str(sidecar.get("id")) in ROCKSTAR_TITLES sdk = rockstar_sdk(folder, sidecar) title = ROCKSTAR_TITLES.get(str(sidecar.get("id"))) @@ -798,7 +843,7 @@ def provision_galaxy(compat_data, proton, timeout=90): ':existing', 'echo ready>"%s"' % answer, 'exit /b 0'] bat.write_bytes(("\r\n".join(lines) + "\r\n").encode()) env = os.environ.copy() - env["BL_COMET_BOOTSTRAP"] = "1" + env["DD_COMET_BOOTSTRAP"] = "1" run = subprocess.run([proton, "run", "cmd.exe", "/d", "/c", windows_path(str(bat))], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout) if run.returncode or not result.is_file() or result.read_text().strip() != "ready": @@ -819,7 +864,7 @@ def prepare_gog(sidecar, compat_data, launch_dir): if not isinstance(answer, dict) or not answer.get("ready"): log("gog achievements: " + (str(answer.get("reason", "unavailable")) if isinstance(answer, dict) else "timeout")) return False - state = provision_galaxy(compat_data, os.environ.get("BL_STORE_PROTON", "")) + state = provision_galaxy(compat_data, os.environ.get("DD_STORE_PROTON", "")) log("gog achievements prefix: " + state) return state == "ready" @@ -1405,7 +1450,7 @@ def write_licenses(compat_data, licenses): def prepare_ea(folder, sidecar, compat_data, launch_dir): game = str(sidecar.get("id")) - proton = os.environ.get("BL_STORE_PROTON", "") + proton = os.environ.get("DD_STORE_PROTON", "") made = create_prefix(compat_data, proton) ready = made in ("present", "created") or (compat_data and (Path(compat_data) / "pfx/user.reg").is_file()) stub = install_origin_stub(compat_data) if ready else "no-prefix" @@ -1573,22 +1618,22 @@ def main(argv): return RAN_FAILED 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", "")) + launch_dir = os.environ.get("DD_LAUNCH_DIR", "") + if launch_dir and cloud_on(sidecar) and store != "ea": + made = create_prefix(compat_data, os.environ.get("DD_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", ""))) - log("gog support data: " + gog_support_data(folder, compat_data, os.environ.get("BL_STORE_PROTON", ""))) + log("gog registry: " + apply_gog_registry(folder, compat_data, os.environ.get("DD_STORE_PROTON", ""))) + log("gog support data: " + gog_support_data(folder, compat_data, os.environ.get("DD_STORE_PROTON", ""))) if store == "rockstar": if game not in ROCKSTAR_TITLES and not rockstar_sdk(folder, sidecar): if compat_data: (Path(compat_data) / "pfx" / ROCKSTAR_FOLDER / "launch.json").unlink(missing_ok=True) return STORE_GAME try: - state = prepare_rockstar(folder, sidecar, compat_data, launch_dir, os.environ.get("BL_STORE_PROTON", "")) + state = prepare_rockstar(folder, sidecar, compat_data, launch_dir, os.environ.get("DD_STORE_PROTON", "")) except (OSError, ValueError, subprocess.TimeoutExpired): state = "preparation-failed" log("rockstar %s: %s" % (game, state)) @@ -1597,7 +1642,7 @@ def main(argv): return STORE_GAME if state == "ready" else RAN_FAILED if store == "ubisoft": try: - log("ubisoft %s: %s" % (game, prepare_ubisoft(folder, sidecar, compat_data, launch_dir, os.environ.get("BL_STORE_PROTON", "")))) + log("ubisoft %s: %s" % (game, prepare_ubisoft(folder, sidecar, compat_data, launch_dir, os.environ.get("DD_STORE_PROTON", "")))) except OSError as e: try: (folder / UBISOFT_LAUNCH).unlink() @@ -1643,13 +1688,16 @@ def main(argv): log("epic prefix=%s %s" % (prefix_id or "?", provision_prefix(compat_data))) if store == "ea": prepare_ea(folder, sidecar, compat_data, launch_dir) - return STORE_GAME if not cloud_on(sidecar): if store in CLOUD_STORES: log("cloud %s %s down result=skipped reason=off" % (store, game)) - return 0 + return STORE_GAME if store == "ea" else 0 if launch_dir: - answer = ask(Path(launch_dir) / "stores", {"op": "cloud-down", "store": store, "id": game}, timeout=CLOUD_TIMEOUT) + try: + answer = ask(Path(launch_dir) / "stores", {"op": "cloud-down", "store": store, "id": game}, timeout=CLOUD_TIMEOUT, claim=True) + except OSError as error: + log("cloud %s %s down result=failed reason=%s" % (store, game, type(error).__name__)) + return STORE_GAME if answer is None: log("cloud %s %s down result=timeout" % (store, game)) else: diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-x64-arm-proton b/tools/linuxfs/overlay/usr/local/bin/droiddeck-x64-arm-proton index 1f82a06915..5098f84654 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-x64-arm-proton +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-x64-arm-proton @@ -9,7 +9,7 @@ for v in $(compgen -e); do case $v in FEX_*) unset "$v" ;; esac done unset LD_LIBRARY_PATH LD_PRELOAD STEAM_RUNTIME_STEAMRT STEAM_STEAMRT_RECURSION_GUARD \ - LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE GALLIUM_DRIVER BL_WEBHELPER_HIDE_TRACER PROOT_FP_OFF + LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE GALLIUM_DRIVER DD_WEBHELPER_HIDE_TRACER PROOT_FP_OFF game_display=${DISPLAY:-} if [ -f "$x64_home/arm-session.env" ]; then @@ -18,7 +18,7 @@ else export HOME=/root fi [ -z "$game_display" ] || export DISPLAY=$game_display -export BL_X64_STEAM_ROOT=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-} +export DD_X64_STEAM_ROOT=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-} export STEAM_COMPAT_CLIENT_INSTALL_PATH=$HOME/.local/share/Steam arm_overlay=$STEAM_COMPAT_CLIENT_INSTALL_PATH/steamrtarm64/gameoverlayrenderer.so if [ "$overlay" = 1 ] && [ -f "$arm_overlay" ]; then diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-x64-arm-webhelper b/tools/linuxfs/overlay/usr/local/bin/droiddeck-x64-arm-webhelper index bd89a4ddb1..d60d35c876 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-x64-arm-webhelper +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-x64-arm-webhelper @@ -5,7 +5,7 @@ arm=/root/.local/share/Steam/steamrtarm64 for v in $(compgen -e); do case $v in FEX_*) unset "$v" ;; esac done -unset LD_PRELOAD LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE BL_WEBHELPER_HIDE_TRACER BL_X64_ARM_WEBHELPER +unset LD_PRELOAD LIBGL_ALWAYS_SOFTWARE LIBGL_DRI3_DISABLE DD_WEBHELPER_HIDE_TRACER DD_X64_ARM_WEBHELPER if [ -f "$x64_home/arm-session.env" ]; then eval "$(grep -E '^declare -x (VK_ICD_FILENAMES|VK_DRIVER_FILES|GALLIUM_DRIVER|MESA_LOADER_DRIVER_OVERRIDE|LIBGL_KOPPER_DRI2|TU_DEBUG|ZINK_DEBUG|ZINK_DESCRIPTORS|MESA_NO_ERROR|MESA_DISK_CACHE_DATABASE)=' "$x64_home/arm-session.env")" fi diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-x64-webhelper b/tools/linuxfs/overlay/usr/local/bin/droiddeck-x64-webhelper index 8c830ab9b1..62915bf645 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-x64-webhelper +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-x64-webhelper @@ -1,6 +1,6 @@ #!/bin/bash -unset BL_X64_ARM_WEBHELPER -export BL_WEBHELPER_ARGS=stock DISABLE_GAMESCOPE_WSI=1 vk_xwayland_wait_ready=true LIBGL_KOPPER_DISABLE=true +unset DD_X64_ARM_WEBHELPER +export DD_WEBHELPER_ARGS=stock DISABLE_GAMESCOPE_WSI=1 vk_xwayland_wait_ready=true LIBGL_KOPPER_DISABLE=true if [ -x ./steamwebhelper ]; then exec ./steamwebhelper "$@" fi diff --git a/tools/linuxfs/overlay/usr/local/bin/droiddeck-xbox b/tools/linuxfs/overlay/usr/local/bin/droiddeck-xbox index 6e27070bcd..143aa07c27 100755 --- a/tools/linuxfs/overlay/usr/local/bin/droiddeck-xbox +++ b/tools/linuxfs/overlay/usr/local/bin/droiddeck-xbox @@ -1,4 +1,5 @@ #!/usr/bin/python3 +import hashlib import hmac import json import os @@ -11,6 +12,7 @@ import subprocess import sys import tempfile import threading +import xml.etree.ElementTree as ElementTree BIN = Path(__file__).resolve().parent RUNTIME = Path('/usr/local/lib/droiddeck-xbox') @@ -137,6 +139,117 @@ def register_classes(proton, prefix, env): print('droiddeck-xbox: Windows Runtime class registration failed; launching without it', file=sys.stderr) +def game_config(exe): + path = Path(exe) + if not path.is_absolute(): + return None + for folder in list(path.parents)[:4]: + config = folder / 'MicrosoftGame.config' + if config.is_file(): + return config + return None + + +def windows_arguments(text): + arguments, current, quoted, started, at = [], [], False, False, 0 + while at < len(text): + char = text[at] + if char == '\\': + run = len(text) - at - len(text[at:].lstrip('\\')) + at += run + if at < len(text) and text[at] == '"': + current.append('\\' * (run // 2)) + if run % 2: + current.append('"') + at += 1 + else: + current.append('\\' * run) + started = True + continue + if char == '"': + if quoted and text[at + 1:at + 2] == '"': + current.append('"') + at += 2 + continue + quoted = not quoted + started = True + elif char in ' \t' and not quoted: + if started: + arguments.append(''.join(current)) + current, started = [], False + else: + current.append(char) + started = True + at += 1 + if started: + arguments.append(''.join(current)) + return arguments + + +def install_actions(config): + try: + root = ElementTree.fromstring(config.read_bytes()) + except (OSError, ElementTree.ParseError): + return [] + actions = [] + for registration in root.iter(): + if registration.tag.rsplit('}', 1)[-1] != 'CustomInstallActions': + continue + folder = next((node.text or '' for node in registration if node.tag.rsplit('}', 1)[-1] == 'Folder'), '') + for node in registration.iter(): + if node.tag.rsplit('}', 1)[-1] != 'InstallAction': + continue + name, file = node.get('Name', ''), node.get('File', '') + parts = [part for part in (folder.strip() + '\\' + file).replace('/', '\\').split('\\') if part] + if not name or not file or any(part in ('.', '..') or ':' in part for part in parts): + continue + target = config.parent.joinpath(*parts) + try: + inside = target.resolve().is_relative_to(config.parent.resolve()) + except OSError: + inside = False + if inside and target.is_file() and target.suffix.lower() in ('.msi', '.exe'): + actions.append((name, target, windows_arguments(node.get('Arguments', '')))) + return actions + + +def run_install_actions(proton, prefix, exe, env): + config = game_config(exe) + if config is None: + return + done = prefix / 'drive_c' / 'ProgramData' / 'DroidDeck' / 'install-actions' + for name, target, arguments in install_actions(config): + try: + content = hashlib.sha256() + with target.open('rb') as source: + for block in iter(lambda: source.read(1 << 20), b''): + content.update(block) + identity = hashlib.sha256(name.encode('utf-8') + b'\0' + content.digest()).hexdigest()[:24] + marker = done / ('%s-%s' % (''.join(c for c in name if c.isalnum() or c in '-_')[:64], identity)) + if marker.exists(): + continue + except OSError as error: + print('droiddeck-xbox: install action %s could not be read (%s); launching without it' % (name, error), file=sys.stderr) + continue + windows = 'Z:' + str(target).replace('/', '\\') + if target.suffix.lower() == '.msi': + command = [proton, 'run', 'msiexec', '/i', windows, *arguments] + else: + command = [proton, 'run', windows, *arguments] + try: + code = subprocess.run(command, stdout=sys.stderr, env=env, timeout=600).returncode + except (OSError, subprocess.TimeoutExpired): + code = None + if code != 0: + print('droiddeck-xbox: install action %s did not finish; launching without it' % name, file=sys.stderr) + continue + try: + done.mkdir(parents=True, exist_ok=True) + marker.touch() + except OSError as error: + print('droiddeck-xbox: install action %s finished but could not be recorded (%s)' % (name, error), file=sys.stderr) + + def view_drive(prefix, exe): path = Path(exe) view = next((parent for parent in path.parents if parent.name.startswith('droiddeck-xbox-')), None) @@ -184,6 +297,7 @@ def wine(argv, source_env=None): target.unlink() shutil.copyfile(RUNTIME / 'windows' / name, target) register_classes(command[0], prefix, env) + run_install_actions(command[0], prefix, argv[0], env) overrides = ';'.join(name[:-4] + '=n' for name in DLLS if name != 'libnghttp2.dll') env['WINEDLLOVERRIDES'] = overrides + ';' + env.get('WINEDLLOVERRIDES', '') exe, drive = view_drive(prefix, argv[0]) @@ -385,12 +499,12 @@ def launch(command, env): for name in DLLS: if not (RUNTIME / 'windows' / name).is_file(): raise RuntimeError('Xbox Windows runtime is missing; update the Linux runtime') - launch_dir = env.get('BL_LAUNCH_DIR') + launch_dir = env.get('DD_LAUNCH_DIR') if not launch_dir: raise RuntimeError('No Xbox account channel; start the game from DroidDeck') reply = store['ask'](Path(launch_dir) / 'stores', {'op': 'xbox-prepare', 'id': sidecar['id']}, timeout=190) if not reply or not reply.get('ok'): - raise RuntimeError('Xbox account service is unavailable; sign in again and retry') + raise RuntimeError((reply or {}).get('reason') or 'Xbox account service is unavailable; sign in again and retry') stopped = threading.Event() close = lambda: None try: @@ -404,7 +518,7 @@ def launch(command, env): context.chmod(0o600) owned_env = dict(env, DROIDDECK_XBOX_ACTIVE='1', DROIDDECK_XBOX_COMMAND_FILE=str(context), XODUS_SOCKET=reply['socket'], XODUS_BRIDGE_PORT=str(port), XODUS_BRIDGE_KEY=key, - XODUS_LOG='off', RUST_LOG='off', XODUS_SAVE_SYNC='auto' if sidecar.get('cloud', True) else 'off') + XODUS_LOG='off', RUST_LOG='off', XODUS_SAVE_SYNC='auto' if sidecar.get('cloud', True) else 'none') for name in ('DROIDDECK_XBOX_CREDENTIAL_SOCKET', 'DROIDDECK_XBOX_CREDENTIAL_PORT', 'DROIDDECK_XBOX_CREDENTIAL_KEY'): owned_env.pop(name, None) if reply.get('playfab'): diff --git a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility index 06811d0366..911bd8d822 100755 --- a/tools/linuxfs/overlay/usr/local/bin/steam-compatibility +++ b/tools/linuxfs/overlay/usr/local/bin/steam-compatibility @@ -59,72 +59,73 @@ TOOL_MANIFEST_VDF = """"manifest" """ % LAUNCHER -BL_STORE_SETUP = """ -bl_store_launch() { +DD_STORE_SETUP = """ +dd_store_launch() { [ "${verb:-}" = waitforexitandrun ] || return 0 if [ -x /usr/local/bin/droiddeck-open-url ]; then mkdir -p /tmp/droiddeck-browser ln -sfn /usr/local/bin/droiddeck-open-url /tmp/droiddeck-browser/xdg-open - [ -n "${BL_LAUNCH_DIR:-}" ] && printf '%s -' "$BL_LAUNCH_DIR" > /tmp/droiddeck-browser/launch-dir + [ -n "${DD_LAUNCH_DIR:-}" ] && printf '%s +' "$DD_LAUNCH_DIR" > /tmp/droiddeck-browser/launch-dir PATH="/tmp/droiddeck-browser:$PATH"; export PATH fi - if [ "${BL_DEBUG_BROWSER:-}" = 1 ]; then + if [ "${DD_DEBUG_BROWSER:-}" = 1 ]; then WINEDEBUG="${WINEDEBUG:+$WINEDEBUG,}+shell,+winebrowser"; export WINEDEBUG fi [ -x /usr/local/bin/droiddeck-store-launch ] || return 0 /usr/local/bin/droiddeck-store-launch "$@" rc=$? - [ $rc -eq 10 ] && BL_STORE_EXIT=1 + [ $rc -eq 10 ] && DD_STORE_EXIT=1 [ $rc -eq 11 ] && exit 0 [ $rc -eq 12 ] && exit 1 return 0 } -bl_run() { +dd_run() { if [ -x /usr/local/bin/droiddeck-steamvr-flat ] && /usr/local/bin/droiddeck-steamvr-flat "${verb:-}"; then set -- /usr/local/bin/droiddeck-steamvr-game "$@" fi - if [ -n "${BL_STORE_EXIT:-}" ]; then + if [ -n "${DD_STORE_EXIT:-}" ]; then + trap : INT TERM HUP "$@" rc=$? - /usr/local/bin/droiddeck-store-launch --exited --code "$rc" "${BL_STORE_ARGS[@]}" || true + /usr/local/bin/droiddeck-store-launch --exited --code "$rc" "${DD_STORE_ARGS[@]}" || true exit $rc fi exec "$@" } """ -BL_DESKTOP_GPU_SETUP = """ -bl_desktop_gpu() { +DD_DESKTOP_GPU_SETUP = """ +dd_desktop_gpu() { local name saved gpu=/usr/local/bin/droiddeck-gpu local names=(LD_PRELOAD LD_LIBRARY_PATH ENABLE_VK_LAYER_VALVE_steam_overlay_1 ENABLE_VK_LAYER_VALVE_steam_fossilize_1) - if [ -n "${BL_DESKTOP_GPU_CHILD:-}" ]; then + if [ -n "${DD_DESKTOP_GPU_CHILD:-}" ]; then for name in "${names[@]}"; do - saved=BL_GPU_SAVED_$name + saved=DD_GPU_SAVED_$name [ -n "${!saved+x}" ] || continue export "$name=${!saved}" unset "$saved" done return 0 fi - [ "${BL_DESKTOP:-}" = 1 ] && [ "${verb:-}" = waitforexitandrun ] && [ -x "$gpu" ] || return 0 - local choice=${BL_DESKTOP_GPU:-on} + [ "${DD_DESKTOP:-}" = 1 ] && [ "${verb:-}" = waitforexitandrun ] && [ -x "$gpu" ] || return 0 + local choice=${DD_DESKTOP_GPU:-on} case "${choice,,}" in off | 0 | no | false) return 0 ;; esac case " $* " in *iscriptevaluator*) return 0 ;; esac local clear=() for name in "${names[@]}"; do [ -n "${!name+x}" ] || continue - export "BL_GPU_SAVED_$name=${!name}" + export "DD_GPU_SAVED_$name=${!name}" clear+=(-u "$name") done echo "droiddeck-gpu: the desktop starts this game on the GPU" >&2 exec env "${clear[@]}" "$gpu" "$0" "$verb" "$@" } -bl_desktop_gpu "$@" +dd_desktop_gpu "$@" """ -BL_COMPONENTS_SETUP = """ -bl_components() { +DD_COMPONENTS_SETUP = """ +dd_components() { base=$1 cm_dir="${HOME:-/root}/.local/share/droiddeck-components" cm_list="$cm_dir/desired.tsv" @@ -209,7 +210,7 @@ bl_components() { continue fi mkdir -p "$(dirname "$f")" - cp -f "$src" "$f.bl-new" && mv -f "$f.bl-new" "$f" || continue + cp -f "$src" "$f.dd-new" && mv -f "$f.dd-new" "$f" || continue case "$rel" in *.so) chmod 755 "$f" ;; *) chmod 644 "$f" ;; esac cm_fixed=$((cm_fixed + 1)) done @@ -221,17 +222,17 @@ bl_components() { } """ -BL_GAME_CPUS_SETUP = """ -bl_game_cpus() { - [ -n "${BL_GAME_CPUS:-}" ] || return 0 +DD_GAME_CPUS_SETUP = """ +dd_game_cpus() { + [ -n "${DD_GAME_CPUS:-}" ] || return 0 command -v taskset >/dev/null 2>&1 || return 0 - BL_TASKSET="taskset -c $BL_GAME_CPUS" - echo "droiddeck-proton: game cores $BL_GAME_CPUS" >&2 + DD_TASKSET="taskset -c $DD_GAME_CPUS" + echo "droiddeck-proton: game cores $DD_GAME_CPUS" >&2 } """ -BL_LIBPATH_SETUP = """ -bl_libpath() { +DD_LIBPATH_SETUP = """ +dd_libpath() { export PROTON_USE_PIPEWIRE=${PROTON_USE_PIPEWIRE:-0} [ -n "${LD_LIBRARY_PATH:-}" ] || return 0 local kept= dir old_ifs=$IFS @@ -247,9 +248,9 @@ bl_libpath() { } """ -BL_IDTECH3_SETUP = """ -bl_idtech3() { - BL_EXTRA_ARGS=() +DD_IDTECH3_SETUP = """ +dd_idtech3() { + DD_EXTRA_ARGS=() case "${SteamAppId:-${STEAM_COMPAT_APP_ID:-}}" in 2200|2350|9010|6020) ;; *) return 0 ;; @@ -259,15 +260,15 @@ bl_idtech3() { echo "droiddeck-proton: Quake-engine title; its launch options set the video mode, left as they are" >&2 return 0 ;; esac - w=${BL_WIDTH:-1280} - h=${BL_HEIGHT:-720} - BL_EXTRA_ARGS=(+set r_fullscreen 0 +set r_mode -1 +set r_customwidth "$w" +set r_customheight "$h") + w=${DD_WIDTH:-1280} + h=${DD_HEIGHT:-720} + DD_EXTRA_ARGS=(+set r_fullscreen 0 +set r_mode -1 +set r_customwidth "$w" +set r_customheight "$h") echo "droiddeck-proton: Quake-engine title: windowed at ${w}x${h}" >&2 } """ -BL_VACDIAG_SETUP = """ -bl_vacdiag() { +DD_VACDIAG_SETUP = """ +dd_vacdiag() { [ -f /root/.droiddeck-vac-diagnostics ] || return 0 [ "${verb:-}" = waitforexitandrun ] || return 0 local exe= a dir added=no app=${SteamAppId:-${STEAM_COMPAT_APP_ID:-0}} @@ -278,7 +279,7 @@ bl_vacdiag() { if ls "$dir"/*/gameinfo.txt >/dev/null 2>&1 || ls "$dir"/../../*/gameinfo.gi >/dev/null 2>&1; then case " $* " in *" -condebug "*) echo "droiddeck-proton: vac-diag: app $app already has -condebug" >&2 ;; - *) BL_EXTRA_ARGS+=(-condebug); added=yes + *) DD_EXTRA_ARGS+=(-condebug); added=yes echo "droiddeck-proton: vac-diag: app $app is a Source title; launched with -condebug" >&2 ;; esac else @@ -292,7 +293,7 @@ bl_vacdiag() { } """ -BL_DRIVER_QUERY_SKIP = """ +DD_DRIVER_QUERY_SKIP = """ case "$verb:${1##*/}:${STEAM_COMPAT_DATA_PATH%/}" in run:d3ddriverquery64.exe:*/compatdata/0 | run:d3ddriverquery.exe:*/compatdata/0) echo "droiddeck-proton: Steam's D3D driver query is not run (it fails here and would start Wine in compatdata/0)" >&2 @@ -300,23 +301,23 @@ case "$verb:${1##*/}:${STEAM_COMPAT_DATA_PATH%/}" in esac """ -BL_DIRECTAUDIO_SETUP = """ -bl_is_steam_installscript_target() { +DD_DIRECTAUDIO_SETUP = """ +dd_is_steam_installscript_target() { local target=${1:-} local steam_root=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-${XDG_DATA_HOME:-$HOME/.local/share}/Steam} local helper="$steam_root/legacycompat/iscriptevaluator.exe" [ -f "$helper" ] && [[ -n "$target" && "$target" -ef "$helper" ]] } -bl_directaudio() { +dd_directaudio() { case "${verb:-}" in run|waitforexitandrun|runinprefix) ;; *) return 0 ;; esac base=$1 - [ -n "${BL_DIRECTAUDIO:-}" ] || return 0 - [ -d "$BL_DIRECTAUDIO" ] || return 0 - if bl_is_steam_installscript_target "${2:-}"; then + [ -n "${DD_DIRECTAUDIO:-}" ] || return 0 + [ -d "$DD_DIRECTAUDIO" ] || return 0 + if dd_is_steam_installscript_target "${2:-}"; then echo "droiddeck-proton: DirectAudio skipped for Steam's install-script evaluator" >&2 return 0 fi @@ -340,7 +341,7 @@ bl_directaudio() { return 0 fi if grep -aq PsCreateSystemThread "$winepulse"; then set=linux-wine11-systhread; else set=linux-wine11; fi - da="$BL_DIRECTAUDIO/$set" + da="$DD_DIRECTAUDIO/$set" if [ ! -d "$da/lib/wine" ]; then echo "droiddeck-proton: DirectAudio left off - no driver set for the $set interface is staged" >&2 return 0 @@ -361,16 +362,16 @@ bl_directaudio() { dir="$pfx/drive_c/windows/${pair%%:*}" src="$da/lib/wine/${pair#*:}/winedirectaudio.drv" if [ -d "$dir" ] && [ -f "$src" ] && [ "$(readlink "$dir/winedirectaudio.drv" 2>/dev/null)" != "$src" ]; then - ln -sfn "$src" "$dir/winedirectaudio.drv.bl-new" && mv -f "$dir/winedirectaudio.drv.bl-new" "$dir/winedirectaudio.drv" + ln -sfn "$src" "$dir/winedirectaudio.drv.dd-new" && mv -f "$dir/winedirectaudio.drv.dd-new" "$dir/winedirectaudio.drv" fi done key='[Software\\\\Wine\\\\Drivers]' if [ "$(readlink "$pfx/drive_c/windows/system32/winedirectaudio.drv" 2>/dev/null)" != "$da/lib/wine/aarch64-windows/winedirectaudio.drv" ]; then echo "droiddeck-proton: DirectAudio could not be placed in the prefix; Proton's own audio stays" >&2 - elif ! BL_KEY="$key" awk 'index($0, "[") == 1 { inside = index($0, ENVIRON["BL_KEY"] " ") == 1 } inside && index($0, "\\"Audio\\"=") == 1 { last = $0 } END { exit last != "\\"Audio\\"=\\"directaudio,pulse\\"" }' "$reg" 2>/dev/null; then + elif ! DD_KEY="$key" awk 'index($0, "[") == 1 { inside = index($0, ENVIRON["DD_KEY"] " ") == 1 } inside && index($0, "\\"Audio\\"=") == 1 { last = $0 } END { exit last != "\\"Audio\\"=\\"directaudio,pulse\\"" }' "$reg" 2>/dev/null; then printf '\\n%s %s\\n"Audio"="directaudio,pulse"\\n' "$key" "$(date +%s)" >> "$reg" echo "droiddeck-proton: DirectAudio selected in the prefix" >&2 - srv="${BL_WINE_SERVER_BASE:-/tmp/.wine-$(id -u)}/server-$(printf '%x-%x' $(stat -c '%d %i' "$pfx" 2>/dev/null || echo 0 0))/socket" + srv="${DD_WINE_SERVER_BASE:-/tmp/.wine-$(id -u)}/server-$(printf '%x-%x' $(stat -c '%d %i' "$pfx" 2>/dev/null || echo 0 0))/socket" if [ -S "$srv" ]; then echo "droiddeck-proton: a wineserver is already running for this prefix; DirectAudio may only engage on the next launch" >&2 fi @@ -385,7 +386,7 @@ bl_directaudio() { LAUNCHER_SH = """#!/bin/bash verb=$1; shift steam_root=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-${XDG_DATA_HOME:-$HOME/.local/share}/Steam} -for fake in /usr/local/lib/libfakeinput.so /usr/local/lib/libblsession.so; do +for fake in /usr/local/lib/libfakeinput.so /usr/local/lib/libddsession.so; do if [ -f "$fake" ]; then case ":${LD_PRELOAD:-}:" in *":$fake:"*) ;; @@ -393,7 +394,7 @@ for fake in /usr/local/lib/libfakeinput.so /usr/local/lib/libblsession.so; do esac fi done -audit=/usr/local/lib/libblaudit.so +audit=/usr/local/lib/libddaudit.so if [ -n "${PROOT_FP_KEY:-}" ] && [ -f "$audit" ]; then case ":${LD_AUDIT:-}:" in *":$audit:"*) ;; @@ -418,16 +419,16 @@ for name in %s; do [ -n "$depot" ] && break done if [ -n "$depot" ]; then - bl_components "$depot" - bl_directaudio "$depot" "$@" - bl_game_cpus - bl_idtech3 "$@" - bl_vacdiag "$@" - bl_libpath - BL_STORE_PROTON="$depot/proton"; export BL_STORE_PROTON - bl_store_launch "$@" - BL_STORE_ARGS=("$@") - bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env "$depot/proton" "$verb" "$@" "${BL_EXTRA_ARGS[@]}" + dd_components "$depot" + dd_directaudio "$depot" "$@" + dd_game_cpus + dd_idtech3 "$@" + dd_vacdiag "$@" + dd_libpath + DD_STORE_PROTON="$depot/proton"; export DD_STORE_PROTON + dd_store_launch "$@" + DD_STORE_ARGS=("$@") + dd_run ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env "$depot/proton" "$verb" "$@" "${DD_EXTRA_ARGS[@]}" fi echo "droiddeck-proton: no ARM64 Proton depot yet - the client downloads one as this tool's dependency; retry the launch once it has" >&2 exit 1 @@ -437,8 +438,8 @@ LAUNCHER_TEMPLATE = LAUNCHER_SH def launcher_sh(sources=SOURCES): return (LAUNCHER_TEMPLATE % " ".join('"%s"' % n for n in sources)).replace( - "verb=$1; shift", "verb=$1; shift\n" + BL_DRIVER_QUERY_SKIP + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP + BL_IDTECH3_SETUP - + BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1) + "verb=$1; shift", "verb=$1; shift\n" + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP + DD_IDTECH3_SETUP + + DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1) LAUNCHER_SH = launcher_sh() @@ -458,7 +459,7 @@ EXTRA_MANIFEST_VDF = """"manifest" EXTRA_WRAPPER_SH = """#!/bin/bash verb=$1; shift here=$(dirname "$0") -for fake in /usr/local/lib/libfakeinput.so /usr/local/lib/libblsession.so; do +for fake in /usr/local/lib/libfakeinput.so /usr/local/lib/libddsession.so; do if [ -f "$fake" ]; then case ":${LD_PRELOAD:-}:" in *":$fake:"*) ;; @@ -466,31 +467,31 @@ for fake in /usr/local/lib/libfakeinput.so /usr/local/lib/libblsession.so; do esac fi done -audit=/usr/local/lib/libblaudit.so +audit=/usr/local/lib/libddaudit.so if [ -n "${PROOT_FP_KEY:-}" ] && [ -f "$audit" ]; then case ":${LD_AUDIT:-}:" in *":$audit:"*) ;; *) LD_AUDIT="$audit${LD_AUDIT:+:$LD_AUDIT}"; export LD_AUDIT ;; esac fi -bl_components "$here" -bl_directaudio "$here" "$@" -bl_game_cpus -bl_idtech3 "$@" -bl_vacdiag "$@" -bl_libpath -BL_STORE_PROTON="$here/%s"; export BL_STORE_PROTON -bl_store_launch "$@" -BL_STORE_ARGS=("$@") -bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env "$BL_STORE_PROTON" "$verb" "$@" "${BL_EXTRA_ARGS[@]}" +dd_components "$here" +dd_directaudio "$here" "$@" +dd_game_cpus +dd_idtech3 "$@" +dd_vacdiag "$@" +dd_libpath +DD_STORE_PROTON="$here/%s"; export DD_STORE_PROTON +dd_store_launch "$@" +DD_STORE_ARGS=("$@") +dd_run ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env "$DD_STORE_PROTON" "$verb" "$@" "${DD_EXTRA_ARGS[@]}" """ def extra_wrapper_sh(entry_point): return (EXTRA_WRAPPER_SH % entry_point).replace( 'here=$(dirname "$0")', - 'here=$(dirname "$0")\n' + BL_DRIVER_QUERY_SKIP + BL_DESKTOP_GPU_SETUP + BL_DIRECTAUDIO_SETUP + BL_GAME_CPUS_SETUP - + BL_IDTECH3_SETUP + BL_VACDIAG_SETUP + BL_COMPONENTS_SETUP + BL_LIBPATH_SETUP + BL_STORE_SETUP, 1) + 'here=$(dirname "$0")\n' + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP + + DD_IDTECH3_SETUP + DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1) EXTRA_COMPAT_TOOL_VDF = """"compatibilitytools" @@ -535,12 +536,12 @@ verb=$1; shift case $verb in getcompatpath | getnativepath) printf '%s\\n' "$1"; exit 0 ;; esac -""" + BL_DESKTOP_GPU_SETUP + BL_GAME_CPUS_SETUP + """ -bl_game_cpus +""" + DD_DESKTOP_GPU_SETUP + DD_GAME_CPUS_SETUP + """ +dd_game_cpus if [ -x /usr/local/bin/droiddeck-steamvr-flat ] && /usr/local/bin/droiddeck-steamvr-flat "$verb"; then - exec /usr/local/bin/droiddeck-steamvr-game ${BL_TASKSET:-} /usr/local/bin/droiddeck-fex steam "$verb" "$@" + exec /usr/local/bin/droiddeck-steamvr-game ${DD_TASKSET:-} /usr/local/bin/droiddeck-fex steam "$verb" "$@" fi -exec ${BL_TASKSET:-} /usr/local/bin/droiddeck-fex steam "$verb" "$@" +exec ${DD_TASKSET:-} /usr/local/bin/droiddeck-fex steam "$verb" "$@" """ @@ -895,7 +896,10 @@ def appinfo_entries(path, wanted=None): deck = common.get("steam_deck_compatibility") configuration = deck.get("configuration") if isinstance(deck, dict) else None recommended = configuration.get("recommended_runtime", "") if isinstance(configuration, dict) else "" + config = info.get("config") if isinstance(info.get("config"), dict) else {} entry = { + "name": str(common.get("name", "")), + "installdir": str(config.get("installdir", "")), "oslist": {part.strip().lower() for part in str(common.get("oslist", "")).split(",") if part.strip()}, "osarch": str(common.get("osarch", "")).lower(), "type": str(common.get("type", "")).lower(), @@ -962,6 +966,13 @@ def native_targets(steam_root, apps): return targets +def manifest_text(appid, name, installdir, bare=False): + title = name.replace("\\", "\\\\").replace('"', '\\"').replace("\n", " ").replace("\r", " ") + text = ('"AppState"\n{\n' + f' "appid" "{appid}"\n "Universe" "1"\n "name" "{title}"\n' + + f' "StateFlags" "4"\n "installdir" "{installdir}"\n' + '}\n') + return text[:-2] + ' "AutoUpdateBehavior" "1"\n}\n' if bare else text + + def app_manifest(steam_root, app): for library in libraries(steam_root): try: @@ -1693,7 +1704,7 @@ def x64_repoint(steam_root, tool, live=False): write_changed(config, text) print("steam-compatibility: x86-64 client's Proton entries point at %s" % tool) if moved and live: - with open(os.path.join(os.path.expanduser("~"), ".bl-compat-pending"), "a") as f: + with open(os.path.join(os.path.expanduser("~"), ".dd-compat-pending"), "a") as f: f.write("".join("%s\n" % a for a in moved)) print("steam-compatibility: repointed while the client runs: %s" % " ".join(moved)) return moved @@ -1702,7 +1713,7 @@ def x64_repoint(steam_root, tool, live=False): def main(): steam_root = sys.argv[1] if "--x64" in sys.argv[2:]: - x64_repoint(steam_root, os.environ.get("BL_COMPAT_TOOL"), "--live" in sys.argv[2:]) + x64_repoint(steam_root, os.environ.get("DD_COMPAT_TOOL"), "--live" in sys.argv[2:]) return tools = os.path.join(steam_root, "compatibilitytools.d") os.makedirs(tools, exist_ok=True) diff --git a/tools/linuxfs/preload/binfmt.c b/tools/linuxfs/preload/binfmt.c index dbe2977265..94cecdeb86 100644 --- a/tools/linuxfs/preload/binfmt.c +++ b/tools/linuxfs/preload/binfmt.c @@ -19,7 +19,7 @@ typedef int (*spawn_fn)(pid_t *, const char *, const posix_spawn_file_actions_t *, const posix_spawnattr_t *, char *const[], char *const[]); __attribute__((visibility("hidden"))) -char *const *bl_webhelper_argv(const char *path, char *const argv[], char *const envp[]); +char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]); #if defined(__aarch64__) || defined(BINFMT_TEST) @@ -29,7 +29,7 @@ static int flag(const char *name) { } static int handing_off(void) { - return flag("BL_DESKTOP") || flag("BL_BINFMT"); + return flag("DD_DESKTOP") || flag("DD_BINFMT"); } static int foreign(const char *path, int error) { @@ -105,36 +105,36 @@ static int spawn_handler(pid_t *pid, const char *path, const posix_spawn_file_ac return real(pid, BINFMT_HANDLER, fa, attr, args, envp); } -__attribute__((visibility("hidden"))) void bl_binfmt_before(const char *path, char *const argv[], char *const envp[]) { +__attribute__((visibility("hidden"))) void dd_binfmt_before(const char *path, char *const argv[], char *const envp[]) { if (handing_off() && foreign(path, ENOEXEC)) hand_off(path, argv, envp); } -__attribute__((visibility("hidden"))) int bl_binfmt_retry(const char *path, char *const argv[], char *const envp[], int error) { +__attribute__((visibility("hidden"))) int dd_binfmt_retry(const char *path, char *const argv[], char *const envp[], int error) { if (wanted(path, error)) hand_off(path, argv, envp); errno = error; return -1; } -__attribute__((visibility("hidden"))) void bl_binfmt_before_search(const char *file, char *const argv[], char *const envp[]) { +__attribute__((visibility("hidden"))) void dd_binfmt_before_search(const char *file, char *const argv[], char *const envp[]) { char path[PATH_MAX]; - if (handing_off() && lookup(file, path, sizeof path)) bl_binfmt_before(path, argv, envp); + if (handing_off() && lookup(file, path, sizeof path)) dd_binfmt_before(path, argv, envp); } -__attribute__((visibility("hidden"))) int bl_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error) { +__attribute__((visibility("hidden"))) int dd_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error) { char path[PATH_MAX]; - if (handing_off() && lookup(file, path, sizeof path)) return bl_binfmt_retry(path, argv, envp, error); + if (handing_off() && lookup(file, path, sizeof path)) return dd_binfmt_retry(path, argv, envp, error); errno = error; return -1; } -__attribute__((visibility("hidden"))) int bl_binfmt_runnable(const char *path, int mode) { +__attribute__((visibility("hidden"))) int dd_binfmt_runnable(const char *path, int mode) { if (mode != X_OK || !handing_off()) return 0; int runs = foreign(path, EACCES) != 0; errno = EACCES; return runs; } -__attribute__((visibility("hidden"))) int bl_binfmt_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa, +__attribute__((visibility("hidden"))) int dd_binfmt_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa, const posix_spawnattr_t *attr, char *const argv[], char *const envp[], spawn_fn real) { if (handing_off() && foreign(path, ENOEXEC)) return spawn_handler(pid, path, fa, attr, argv, envp, real); @@ -145,54 +145,54 @@ __attribute__((visibility("hidden"))) int bl_binfmt_spawn(pid_t *pid, const char int execvpe(const char *file, char *const argv[], char *const envp[]) { char resolved[PATH_MAX]; const char *path = lookup(file, resolved, sizeof resolved) ? resolved : file; - char *const *adjusted = bl_webhelper_argv(path, argv, envp); + char *const *adjusted = dd_webhelper_argv(path, argv, envp); static int (*real)(const char *, char *const[], char *const[]); if (!real) real = (int (*)(const char *, char *const[], char *const[]))dlsym(RTLD_NEXT, "execvpe"); - bl_binfmt_before_search(file, (char *const *)adjusted, envp); + dd_binfmt_before_search(file, (char *const *)adjusted, envp); real(file, (char *const *)adjusted, envp); - return bl_binfmt_after_search(file, (char *const *)adjusted, envp, errno); + return dd_binfmt_after_search(file, (char *const *)adjusted, envp, errno); } int posix_spawnp(pid_t *pid, const char *file, const posix_spawn_file_actions_t *fa, const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) { char path[PATH_MAX]; int found = lookup(file, path, sizeof path); - char *const *adjusted = bl_webhelper_argv(found ? path : file, argv, envp); + char *const *adjusted = dd_webhelper_argv(found ? path : file, argv, envp); static spawn_fn real, spawn; if (!real) real = (spawn_fn)dlsym(RTLD_NEXT, "posix_spawnp"); if (!spawn) spawn = (spawn_fn)dlsym(RTLD_NEXT, "posix_spawn"); if (!handing_off() || !found) return real(pid, file, fa, attr, (char *const *)adjusted, envp); - return bl_binfmt_spawn(pid, path, fa, attr, (char *const *)adjusted, envp, spawn); + return dd_binfmt_spawn(pid, path, fa, attr, (char *const *)adjusted, envp, spawn); } #else -__attribute__((visibility("hidden"))) int bl_binfmt_runnable(const char *path, int mode) { +__attribute__((visibility("hidden"))) int dd_binfmt_runnable(const char *path, int mode) { (void)path, (void)mode; return 0; } -__attribute__((visibility("hidden"))) void bl_binfmt_before(const char *path, char *const argv[], char *const envp[]) { +__attribute__((visibility("hidden"))) void dd_binfmt_before(const char *path, char *const argv[], char *const envp[]) { (void)path, (void)argv, (void)envp; } -__attribute__((visibility("hidden"))) int bl_binfmt_retry(const char *path, char *const argv[], char *const envp[], int error) { +__attribute__((visibility("hidden"))) int dd_binfmt_retry(const char *path, char *const argv[], char *const envp[], int error) { (void)path, (void)argv, (void)envp; errno = error; return -1; } -__attribute__((visibility("hidden"))) void bl_binfmt_before_search(const char *file, char *const argv[], char *const envp[]) { +__attribute__((visibility("hidden"))) void dd_binfmt_before_search(const char *file, char *const argv[], char *const envp[]) { (void)file, (void)argv, (void)envp; } -__attribute__((visibility("hidden"))) int bl_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error) { +__attribute__((visibility("hidden"))) int dd_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error) { (void)file, (void)argv, (void)envp; errno = error; return -1; } -__attribute__((visibility("hidden"))) int bl_binfmt_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa, +__attribute__((visibility("hidden"))) int dd_binfmt_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa, const posix_spawnattr_t *attr, char *const argv[], char *const envp[], spawn_fn real) { return real(pid, path, fa, attr, argv, envp); diff --git a/tools/linuxfs/preload/clockpause.c b/tools/linuxfs/preload/clockpause.c index eed7a401d7..8fe0b7ce77 100644 --- a/tools/linuxfs/preload/clockpause.c +++ b/tools/linuxfs/preload/clockpause.c @@ -14,10 +14,10 @@ #include #include -#if defined(__aarch64__) || defined(BL_CLOCK_ANY_ARCH) +#if defined(__aarch64__) || defined(DD_CLOCK_ANY_ARCH) #ifndef CP_CTL -#define CP_CTL "/tmp/.bl-clock" +#define CP_CTL "/tmp/.dd-clock" #endif #ifndef FUTEX_LOCK_PI2 #define FUTEX_LOCK_PI2 13 @@ -255,7 +255,7 @@ int timerfd_settime(int fd, int flags, const struct itimerspec *value, struct it return cp_tfd_settime(fd, flags, cp_timer(fd, flags, value, &moved), old); } -__attribute__((visibility("hidden"))) int bl_clock_syscall(long number, const long *args, long (*real)(long, ...), long *ret) { +__attribute__((visibility("hidden"))) int dd_clock_syscall(long number, const long *args, long (*real)(long, ...), long *ret) { struct timespec moved; struct itimerspec timer; int64_t shift; @@ -302,7 +302,7 @@ __attribute__((visibility("hidden"))) int bl_clock_syscall(long number, const lo #else -__attribute__((visibility("hidden"))) int bl_clock_syscall(long number, const long *args, long (*real)(long, ...), long *ret) { +__attribute__((visibility("hidden"))) int dd_clock_syscall(long number, const long *args, long (*real)(long, ...), long *ret) { (void)number; (void)args; (void)real; diff --git a/tools/linuxfs/preload/descriptor.c b/tools/linuxfs/preload/descriptor.c index 681dce999e..686030988c 100644 --- a/tools/linuxfs/preload/descriptor.c +++ b/tools/linuxfs/preload/descriptor.c @@ -14,12 +14,12 @@ #define STORE "/.droiddeck-descriptors" #define ENTRY_MAX (PATH_MAX * 2) -int bl_is_wineserver(void) __attribute__((visibility("hidden"))); +int dd_is_wineserver(void) __attribute__((visibility("hidden"))); static int store_seen; static int kept(const char *name) { - return name != NULL && strcmp(name, DESCRIPTOR) == 0 && bl_is_wineserver(); + return name != NULL && strcmp(name, DESCRIPTOR) == 0 && dd_is_wineserver(); } static int store_root(char *out, size_t size) { @@ -226,7 +226,7 @@ int fremovexattr(int fd, const char *name) { static int tracked(const char *path, char *out, size_t size) { int saved = errno, found; - found = bl_is_wineserver() && store_exists() && resolved(path, out, size) == 0; + found = dd_is_wineserver() && store_exists() && resolved(path, out, size) == 0; errno = saved; return found; } @@ -259,7 +259,7 @@ static void follow(const char *from, const char *to) { } __attribute__((visibility("hidden"))) -int bl_descriptor_unlink(const char *path, int (*real)(const char *)) { +int dd_descriptor_unlink(const char *path, int (*real)(const char *)) { char target[PATH_MAX]; int known = tracked(path, target, sizeof(target)), result = real(path); @@ -268,7 +268,7 @@ int bl_descriptor_unlink(const char *path, int (*real)(const char *)) { } __attribute__((visibility("hidden"))) -int bl_descriptor_rmdir(const char *path, int (*real)(const char *)) { +int dd_descriptor_rmdir(const char *path, int (*real)(const char *)) { char target[PATH_MAX]; int known = tracked(path, target, sizeof(target)), result = real(path); @@ -277,12 +277,12 @@ int bl_descriptor_rmdir(const char *path, int (*real)(const char *)) { } __attribute__((visibility("hidden"))) -int bl_descriptor_remove(const char *path, int (*real)(const char *)) { - return bl_descriptor_rmdir(path, real); +int dd_descriptor_remove(const char *path, int (*real)(const char *)) { + return dd_descriptor_rmdir(path, real); } __attribute__((visibility("hidden"))) -int bl_descriptor_rename(const char *from, const char *to, int (*real)(const char *, const char *)) { +int dd_descriptor_rename(const char *from, const char *to, int (*real)(const char *, const char *)) { char old[PATH_MAX], new[PATH_MAX]; int known = tracked(from, old, sizeof(old)), result = real(from, to); diff --git a/tools/linuxfs/preload/dircache.c b/tools/linuxfs/preload/dircache.c index a94717bd78..e322c6cde3 100644 --- a/tools/linuxfs/preload/dircache.c +++ b/tools/linuxfs/preload/dircache.c @@ -112,7 +112,7 @@ static void after_fork(void) { static int enabled(void) { static int cached = -1; if (cached < 0) { - const char *off = getenv("BL_NO_DIR_CACHE"); + const char *off = getenv("DD_NO_DIR_CACHE"); cached = strcmp(program_invocation_short_name, "steam") == 0 && (strstr(program_invocation_name, "steamrtarm64") != NULL || strstr(program_invocation_name, "steamrt64") != NULL) && !(off && strcmp(off, "1") == 0); @@ -816,9 +816,9 @@ static void end(struct expect *x, int nx) { give(&lock); } -int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode, +int dd_dircache_create(int dirfd, const char *path, int flags, mode_t mode, int (*real)(int, const char *, int, mode_t)) __attribute__((visibility("hidden"))); -int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode, +int dd_dircache_create(int dirfd, const char *path, int flags, mode_t mode, int (*real)(int, const char *, int, mode_t)) { struct side s; if (!(flags & O_CREAT) || (dirfd != AT_FDCWD && (path == NULL || path[0] != '/')) || !watching(path) || !split(path, &s)) @@ -860,17 +860,17 @@ int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode, } ONE_PATH(mkdir, ADDED, IN_CREATE, next_mkdir(path, mode), mode_t mode) -int bl_descriptor_unlink(const char *path, int (*real)(const char *)) __attribute__((visibility("hidden"))); -int bl_descriptor_rmdir(const char *path, int (*real)(const char *)) __attribute__((visibility("hidden"))); -int bl_descriptor_remove(const char *path, int (*real)(const char *)) __attribute__((visibility("hidden"))); -int bl_descriptor_rename(const char *from, const char *to, int (*real)(const char *, const char *)) +int dd_descriptor_unlink(const char *path, int (*real)(const char *)) __attribute__((visibility("hidden"))); +int dd_descriptor_rmdir(const char *path, int (*real)(const char *)) __attribute__((visibility("hidden"))); +int dd_descriptor_remove(const char *path, int (*real)(const char *)) __attribute__((visibility("hidden"))); +int dd_descriptor_rename(const char *from, const char *to, int (*real)(const char *, const char *)) __attribute__((visibility("hidden"))); -static int moved(const char *from, const char *to) { return bl_descriptor_rename(from, to, next_rename); } +static int moved(const char *from, const char *to) { return dd_descriptor_rename(from, to, next_rename); } -ONE_PATH(rmdir, REMOVED, IN_DELETE, bl_descriptor_rmdir(path, next_rmdir)) -ONE_PATH(unlink, REMOVED, IN_DELETE, bl_descriptor_unlink(path, next_unlink)) -ONE_PATH(remove, REMOVED, IN_DELETE, bl_descriptor_remove(path, next_remove)) +ONE_PATH(rmdir, REMOVED, IN_DELETE, dd_descriptor_rmdir(path, next_rmdir)) +ONE_PATH(unlink, REMOVED, IN_DELETE, dd_descriptor_unlink(path, next_unlink)) +ONE_PATH(remove, REMOVED, IN_DELETE, dd_descriptor_remove(path, next_remove)) #define TWO_PATHS(name, gone, event, call) \ int name(const char *from, const char *to) { \ @@ -900,8 +900,8 @@ ONE_PATH(remove, REMOVED, IN_DELETE, bl_descriptor_remove(path, next_remove)) return r; \ } -int bl_link_lock(const char *oldpath, const char *newpath, int result) __attribute__((visibility("hidden"))); -static int link_or_lock(const char *from, const char *to) { return bl_link_lock(from, to, next_link(from, to)); } +int dd_link_lock(const char *oldpath, const char *newpath, int result) __attribute__((visibility("hidden"))); +static int link_or_lock(const char *from, const char *to) { return dd_link_lock(from, to, next_link(from, to)); } TWO_PATHS(rename, 1, IN_MOVED_TO, moved) TWO_PATHS(link, 0, IN_CREATE, link_or_lock) @@ -938,8 +938,8 @@ static int listed_absent(const char *dir, const char *name, long long now) { return 0; } -int bl_dircache_absent(const char *path) __attribute__((visibility("hidden"))); -int bl_dircache_absent(const char *path) { +int dd_dircache_absent(const char *path) __attribute__((visibility("hidden"))); +int dd_dircache_absent(const char *path) { struct side s; if (!watching(path) || !split(path, &s)) return 0; for (const char *c = s.name; *c; c++) @@ -957,15 +957,15 @@ int bl_dircache_absent(const char *path) { #else -int bl_dircache_absent(const char *path) __attribute__((visibility("hidden"))); -int bl_dircache_absent(const char *path) { +int dd_dircache_absent(const char *path) __attribute__((visibility("hidden"))); +int dd_dircache_absent(const char *path) { (void)path; return 0; } -int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode, +int dd_dircache_create(int dirfd, const char *path, int flags, mode_t mode, int (*real)(int, const char *, int, mode_t)) __attribute__((visibility("hidden"))); -int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode, +int dd_dircache_create(int dirfd, const char *path, int flags, mode_t mode, int (*real)(int, const char *, int, mode_t)) { return real(dirfd, path, flags, mode); } diff --git a/tools/linuxfs/preload/drm.c b/tools/linuxfs/preload/drm.c index 9c40a39294..4a47a3cd76 100644 --- a/tools/linuxfs/preload/drm.c +++ b/tools/linuxfs/preload/drm.c @@ -43,7 +43,7 @@ static int is_kgsl(int fd) { struct stat st; pthread_mutex_lock(&lock); if (kgsl_state == 0) { - const char *standin = getenv("BL_DRM_STANDIN"); + const char *standin = getenv("DD_DRM_STANDIN"); kgsl_state = stat("/dev/kgsl-3d0", &st) == 0 || (standin && *standin && stat(standin, &st) == 0) ? 1 : -1; if (kgsl_state > 0) kgsl_dev = st.st_rdev; } @@ -52,7 +52,7 @@ static int is_kgsl(int fd) { } /* Keep the opt-in separate from GPU detection: manual ICDs must retain native DRM behavior. */ -struct bl_drm_version { +struct dd_drm_version { int major, minor, patch; size_t name_len; char *name; @@ -61,21 +61,21 @@ struct bl_drm_version { size_t desc_len; char *desc; }; -#define BL_DRM_VERSION _IOWR('d', 0x00, struct bl_drm_version) +#define DD_DRM_VERSION _IOWR('d', 0x00, struct dd_drm_version) static int is_powervr(int fd) { - const char *enabled = getenv("BL_POWERVR_DRM_HANDLES"); + const char *enabled = getenv("DD_POWERVR_DRM_HANDLES"); if (!enabled || strcmp(enabled, "1")) return 0; - const char *path = getenv("BL_POWERVR_RENDER_NODE"); + const char *path = getenv("DD_POWERVR_RENDER_NODE"); if (!path || !*path) return 0; struct stat node, candidate; if (stat(path, &node) || fstat(fd, &candidate) || !S_ISCHR(candidate.st_mode) || !S_ISCHR(node.st_mode) || candidate.st_rdev != node.st_rdev) return 0; char name[16] = {0}; - struct bl_drm_version version = {.name_len = sizeof(name) - 1, .name = name}; + struct dd_drm_version version = {.name_len = sizeof(name) - 1, .name = name}; /* Bypass the preload's ioctl dispatcher to avoid recursively entering this hook. */ - return syscall(SYS_ioctl, fd, BL_DRM_VERSION, &version) == 0 && + return syscall(SYS_ioctl, fd, DD_DRM_VERSION, &version) == 0 && version.name_len == 3 && !memcmp(name, "pvr", 3); } @@ -118,7 +118,7 @@ static int same_file_description(int a, int b) { } #endif if (ret < 0) { - const char *standin = getenv("BL_DRM_STANDIN"); + const char *standin = getenv("DD_DRM_STANDIN"); ret = standin && *standin ? same_by_flock(a, b) : 0; } errno = saved_errno; @@ -324,7 +324,7 @@ int drmCloseBufferHandle(int fd, uint32_t handle) { return fn ? fn(fd, handle) : -ENOSYS; } -__attribute__((visibility("hidden"))) int bl_drm_gem_close(int fd, unsigned long request, void *arg, int *rc) { +__attribute__((visibility("hidden"))) int dd_drm_gem_close(int fd, unsigned long request, void *arg, int *rc) { if (request != GEM_CLOSE || !arg) { return 0; } diff --git a/tools/linuxfs/preload/fsync.c b/tools/linuxfs/preload/fsync.c index 7a4529aa94..da60e28f1d 100644 --- a/tools/linuxfs/preload/fsync.c +++ b/tools/linuxfs/preload/fsync.c @@ -98,11 +98,11 @@ static int (*fs_real_shm_unlink)(const char *); static void *(*fs_real_mmap)(void *, size_t, int, int, int, off_t); static void *(*fs_real_mmap64)(void *, size_t, int, int, int, off64_t); static int (*fs_real_munmap)(void *, size_t); -__attribute__((visibility("hidden"))) int bl_noexec_retry(int prot, int flags, int fd); +__attribute__((visibility("hidden"))) int dd_noexec_retry(int prot, int flags, int fd); static int fs_on(void) { if (fs_state < 0) { - const char *e = getenv("BL_FSYNC"); + const char *e = getenv("DD_FSYNC"); fs_state = e && e[0] == '1'; } return fs_state; @@ -511,14 +511,14 @@ static long fs_wake(uint32_t key, int n) { return woken; } -void bl_fsync_fds_closed(unsigned int first, unsigned int last) __attribute__((visibility("hidden"))); -void bl_fsync_fds_closed(unsigned int first, unsigned int last) { +void dd_fsync_fds_closed(unsigned int first, unsigned int last) __attribute__((visibility("hidden"))); +void dd_fsync_fds_closed(unsigned int first, unsigned int last) { int fd = __atomic_load_n(&fs_fd, __ATOMIC_ACQUIRE); if (fd >= 0 && (unsigned int)fd >= first && (unsigned int)fd <= last) __atomic_store_n(&fs_fd, -1, __ATOMIC_RELEASE); } -int bl_fsync_syscall(long number, const long *args, long *ret) __attribute__((visibility("hidden"))); -int bl_fsync_syscall(long number, const long *args, long *ret) { +int dd_fsync_syscall(long number, const long *args, long *ret) __attribute__((visibility("hidden"))); +int dd_fsync_syscall(long number, const long *args, long *ret) { if (number == SYS_futex_waitv) { if (!fs_on()) return 0; if (!args[0] && !args[1]) { @@ -617,15 +617,15 @@ int shm_unlink(const char *name) { return r; } -int bl_venc_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off, +int dd_venc_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off, void *(*real)(void *, size_t, int, int, int, off_t), void **out) __attribute__((weak, visibility("hidden"))); void *mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off) { void *p; if (!fs_real_mmap) fs_real_mmap = (void *(*)(void *, size_t, int, int, int, off_t))dlsym(RTLD_NEXT, "mmap"); - if (bl_venc_mmap && bl_venc_mmap(addr, len, prot, flags, fd, off, fs_real_mmap, &p)) return p; + if (dd_venc_mmap && dd_venc_mmap(addr, len, prot, flags, fd, off, fs_real_mmap, &p)) return p; p = fs_real_mmap(addr, len, prot, flags, fd, off); - if (p == MAP_FAILED && bl_noexec_retry(prot, flags, fd)) p = fs_real_mmap(addr, len, prot & ~PROT_EXEC, flags, fd, off); + if (p == MAP_FAILED && dd_noexec_retry(prot, flags, fd)) p = fs_real_mmap(addr, len, prot & ~PROT_EXEC, flags, fd, off); if (p != MAP_FAILED && __builtin_expect(fs_fd >= 0, 0)) fs_track(p, len, flags, fd, off); return p; } @@ -633,10 +633,10 @@ void *mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off) { void *mmap64(void *addr, size_t len, int prot, int flags, int fd, off64_t off) { void *p; if (!fs_real_mmap64) fs_real_mmap64 = (void *(*)(void *, size_t, int, int, int, off64_t))dlsym(RTLD_NEXT, "mmap64"); - if (bl_venc_mmap && bl_venc_mmap(addr, len, prot, flags, fd, off, (void *(*)(void *, size_t, int, int, int, off_t))fs_real_mmap64, &p)) + if (dd_venc_mmap && dd_venc_mmap(addr, len, prot, flags, fd, off, (void *(*)(void *, size_t, int, int, int, off_t))fs_real_mmap64, &p)) return p; p = fs_real_mmap64(addr, len, prot, flags, fd, off); - if (p == MAP_FAILED && bl_noexec_retry(prot, flags, fd)) p = fs_real_mmap64(addr, len, prot & ~PROT_EXEC, flags, fd, off); + if (p == MAP_FAILED && dd_noexec_retry(prot, flags, fd)) p = fs_real_mmap64(addr, len, prot & ~PROT_EXEC, flags, fd, off); if (p != MAP_FAILED && __builtin_expect(fs_fd >= 0, 0)) fs_track(p, len, flags, fd, off); return p; } diff --git a/tools/linuxfs/preload/inputudev.c b/tools/linuxfs/preload/inputudev.c index eb78ce1efb..d33a0adaac 100644 --- a/tools/linuxfs/preload/inputudev.c +++ b/tools/linuxfs/preload/inputudev.c @@ -168,7 +168,7 @@ static struct pad *pad_for_syslink(const char *path) { static void *next_symbol(const char *name) { return dlsym(RTLD_NEXT, name); } -char *bl_cached_realpath(const char *path, char *resolved, char *(*real)(const char *, char *)) +char *dd_cached_realpath(const char *path, char *resolved, char *(*real)(const char *, char *)) __attribute__((visibility("hidden"))); static int caller_is_winebus(void *caller) { @@ -178,7 +178,7 @@ static int caller_is_winebus(void *caller) { return strstr(info.dli_fname, "winebus.so") != NULL; } -__attribute__((visibility("hidden"))) int bl_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd, +__attribute__((visibility("hidden"))) int dd_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request, void *arg, void *caller, int *rc) { struct ff_effect *effect = arg; @@ -204,7 +204,7 @@ char *realpath(const char *path, char *resolved) { } if (real_realpath == NULL) real_realpath = next_symbol("realpath"); if (real_realpath == NULL) return NULL; - return bl_cached_realpath(path, resolved, real_realpath); + return dd_cached_realpath(path, resolved, real_realpath); } void *udev_device_new_from_syspath(void *udev, const char *syspath) { diff --git a/tools/linuxfs/preload/kgslid.c b/tools/linuxfs/preload/kgslid.c index c909f4618d..6ab0d2fe32 100644 --- a/tools/linuxfs/preload/kgslid.c +++ b/tools/linuxfs/preload/kgslid.c @@ -28,7 +28,7 @@ static const struct { {0x44050A21, 0x44050A31}, }; -void bl_kgsl_chip_id_fixup(unsigned long request, void *arg, int rc) { +void dd_kgsl_chip_id_fixup(unsigned long request, void *arg, int rc) { if (rc != 0 || request != IOCTL_KGSL_DEVICE_GETPROPERTY || arg == NULL) return; struct kgsl_device_getproperty *prop = arg; if (prop->type != KGSL_PROP_DEVICE_INFO || prop->value == NULL diff --git a/tools/linuxfs/preload/kgslpoll.c b/tools/linuxfs/preload/kgslpoll.c index adc6fb28c4..41ea0e34ae 100644 --- a/tools/linuxfs/preload/kgslpoll.c +++ b/tools/linuxfs/preload/kgslpoll.c @@ -69,7 +69,7 @@ static int read_retired(int (*real)(int, unsigned long, void *), int fd, } /* Quest refuses some KGSL ioctls, and Mesa 27 turns a failed timestamp read into VK_ERROR_UNKNOWN. */ -__attribute__((visibility("hidden"))) void bl_kgsl_track(int (*real)(int, unsigned long, void *), +__attribute__((visibility("hidden"))) void dd_kgsl_track(int (*real)(int, unsigned long, void *), int fd, unsigned long request, void *arg, int *rc) { int saved = errno; @@ -113,12 +113,12 @@ static int enabled(void) { const char *off; if (cached >= 0) return cached; - off = getenv("BL_NO_KGSL_POLL_FIX"); + off = getenv("DD_NO_KGSL_POLL_FIX"); cached = !(off != NULL && off[0] == '1'); return cached; } -__attribute__((visibility("hidden"))) int bl_kgsl_poll(int (*real)(int, unsigned long, void *), +__attribute__((visibility("hidden"))) int dd_kgsl_poll(int (*real)(int, unsigned long, void *), int fd, unsigned long request, void *arg, int *rc) { const struct kgsl_device_waittimestamp_ctxtid *wait = arg; diff --git a/tools/linuxfs/preload/links.c b/tools/linuxfs/preload/links.c index 350990b61d..79293c7d85 100644 --- a/tools/linuxfs/preload/links.c +++ b/tools/linuxfs/preload/links.c @@ -19,7 +19,7 @@ static int lock_name(const char *path) { return n > 2 && strcmp(path + n - 2, "-l") == 0; } -__attribute__((visibility("hidden"))) int bl_link_lock(const char *oldpath, const char *newpath, int result) { +__attribute__((visibility("hidden"))) int dd_link_lock(const char *oldpath, const char *newpath, int result) { static int (*real_symlink)(const char *, const char *); if (result == 0 || !refused(errno)) return result; if (moves_instead()) return renameat2(AT_FDCWD, oldpath, AT_FDCWD, newpath, RENAME_NOREPLACE); @@ -32,7 +32,7 @@ __attribute__((visibility("hidden"))) int bl_link_lock(const char *oldpath, cons int link(const char *oldpath, const char *newpath) { static int (*real_link)(const char *, const char *); if (real_link == NULL) real_link = dlsym(RTLD_NEXT, "link"); - return bl_link_lock(oldpath, newpath, real_link(oldpath, newpath)); + return dd_link_lock(oldpath, newpath, real_link(oldpath, newpath)); } #endif diff --git a/tools/linuxfs/preload/lock.c b/tools/linuxfs/preload/lock.c index 6e36a1ee9c..feb95d72c0 100644 --- a/tools/linuxfs/preload/lock.c +++ b/tools/linuxfs/preload/lock.c @@ -61,8 +61,8 @@ static int is_lock_query(int cmd) { } } -int bl_nl_before_dup(int fd, void **state) __attribute__((visibility("hidden"))); -void bl_nl_after_dup(void *state, int fd) __attribute__((visibility("hidden"))); +int dd_nl_before_dup(int fd, void **state) __attribute__((visibility("hidden"))); +void dd_nl_after_dup(void *state, int fd) __attribute__((visibility("hidden"))); static int fcntl_with(int (**real_fcntl)(int, int, ...), const char *name, int fd, int cmd, void *arg) { int result; @@ -74,9 +74,9 @@ static int fcntl_with(int (**real_fcntl)(int, int, ...), const char *name, int f } void *nl_state = NULL; int duplicate = cmd == F_DUPFD || cmd == F_DUPFD_CLOEXEC; - if (duplicate && bl_nl_before_dup(fd, &nl_state) != 0) return -1; + if (duplicate && dd_nl_before_dup(fd, &nl_state) != 0) return -1; result = (*real_fcntl)(fd, cmd, arg); - if (duplicate) bl_nl_after_dup(nl_state, result); + if (duplicate) dd_nl_after_dup(nl_state, result); if (result >= 0 || !unsupported(errno)) return result; if (is_lock_command(cmd)) return 0; if (is_lock_query(cmd) && arg != NULL) { diff --git a/tools/linuxfs/preload/net.c b/tools/linuxfs/preload/net.c index e45ed9c5c0..f7c9db9406 100644 --- a/tools/linuxfs/preload/net.c +++ b/tools/linuxfs/preload/net.c @@ -20,7 +20,7 @@ static const char *net_dir(void) { static char dir[256]; if (!dir[0]) { - const char *base = getenv("BL_SYSV_DIR"); + const char *base = getenv("DD_SYSV_DIR"); snprintf(dir, sizeof(dir), "%s/net", base && *base ? base : "/dev/shm/wnsysv"); char parent[256]; snprintf(parent, sizeof(parent), "%s", dir); @@ -110,18 +110,18 @@ typedef int (*connect_fn)(int, const struct sockaddr *, socklen_t); typedef int (*accept4_fn)(int, struct sockaddr *, socklen_t *, int); static unsigned guarded_port(void); -__attribute__((visibility("hidden"))) int bl_udevmon_stand_in(int fd); -__attribute__((visibility("hidden"))) int bl_nl_bind(int fd, const struct sockaddr *addr, +__attribute__((visibility("hidden"))) int dd_udevmon_stand_in(int fd); +__attribute__((visibility("hidden"))) int dd_nl_bind(int fd, const struct sockaddr *addr, socklen_t len, int *rc); -__attribute__((visibility("hidden"))) int bl_nl_connect(int fd, const struct sockaddr *addr, +__attribute__((visibility("hidden"))) int dd_nl_connect(int fd, const struct sockaddr *addr, socklen_t len, int *rc); int bind(int fd, const struct sockaddr *addr, socklen_t len) { static bind_fn real; int nl_rc; if (!real) real = (bind_fn)dlsym(RTLD_NEXT, "bind"); - if (bl_nl_bind(fd, addr, len, &nl_rc)) return nl_rc; - if (bl_udevmon_stand_in(fd)) { + if (dd_nl_bind(fd, addr, len, &nl_rc)) return nl_rc; + if (dd_udevmon_stand_in(fd)) { if (addr == NULL || len < sizeof(struct sockaddr_nl) || addr->sa_family != AF_NETLINK) { errno = EINVAL; return -1; @@ -183,7 +183,7 @@ static void bind_before_loopback_connect(int fd, const struct sockaddr *addr, so static unsigned guarded_port(void) { static int port = -1; if (port < 0) { - const char *value = getenv("BL_CDP_GUARD"); + const char *value = getenv("DD_CDP_GUARD"); port = value && *value ? atoi(value) : 0; if (port < 0 || port > 65535) port = 0; } @@ -230,7 +230,7 @@ static int guest_peer(int fd) { int connect(int fd, const struct sockaddr *addr, socklen_t len) { static connect_fn real; int nl_rc; - if (bl_nl_connect(fd, addr, len, &nl_rc)) return nl_rc; + if (dd_nl_connect(fd, addr, len, &nl_rc)) return nl_rc; if (!real) real = (connect_fn)dlsym(RTLD_NEXT, "connect"); bind_before_loopback_connect(fd, addr, len); unsigned peer = loopback_family(addr, len) ? addr_port(addr, len) : 0; @@ -267,13 +267,13 @@ int accept(int fd, struct sockaddr *addr, socklen_t *len) { extern char **environ; typedef int (*spawn_fn)(pid_t *, const char *, const posix_spawn_file_actions_t *, const posix_spawnattr_t *, char *const[], char *const[]); -__attribute__((visibility("hidden"))) void bl_binfmt_before(const char *path, char *const argv[], char *const envp[]); -__attribute__((visibility("hidden"))) int bl_binfmt_retry(const char *path, char *const argv[], char *const envp[], int error); -__attribute__((visibility("hidden"))) void bl_binfmt_before_search(const char *file, char *const argv[], char *const envp[]); -__attribute__((visibility("hidden"))) int bl_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error); +__attribute__((visibility("hidden"))) void dd_binfmt_before(const char *path, char *const argv[], char *const envp[]); +__attribute__((visibility("hidden"))) int dd_binfmt_retry(const char *path, char *const argv[], char *const envp[], int error); +__attribute__((visibility("hidden"))) void dd_binfmt_before_search(const char *file, char *const argv[], char *const envp[]); +__attribute__((visibility("hidden"))) int dd_binfmt_after_search(const char *file, char *const argv[], char *const envp[], int error); __attribute__((visibility("hidden"))) -char *const *bl_webhelper_argv(const char *path, char *const argv[], char *const envp[]); -__attribute__((visibility("hidden"))) int bl_binfmt_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa, +char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]); +__attribute__((visibility("hidden"))) int dd_binfmt_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa, const posix_spawnattr_t *attr, char *const argv[], char *const envp[], spawn_fn real); @@ -320,7 +320,7 @@ static int maybe_answer_lsof(const char *path, char *const argv[]) { } static char **web_helper_redirect(const char *path, char *const argv[], const char **launcher) { - const char *want = getenv("BL_X64_ARM_WEBHELPER"); + const char *want = getenv("DD_X64_ARM_WEBHELPER"); if (!want || !*want || !path) return NULL; const char *base = strrchr(path, '/'); if (strcmp(base ? base + 1 : path, "steamwebhelper") != 0) return NULL; @@ -342,7 +342,7 @@ static char **web_helper_redirect(const char *path, char *const argv[], const ch } int execve(const char *path, char *const argv_in[], char *const envp[]) { - char *const *argv = bl_webhelper_argv(path, argv_in, envp); + char *const *argv = dd_webhelper_argv(path, argv_in, envp); static int (*real)(const char *, char *const[], char *const[]); if (!real) real = (int (*)(const char *, char *const[], char *const[]))dlsym(RTLD_NEXT, "execve"); maybe_answer_lsof(path, argv); @@ -352,9 +352,9 @@ int execve(const char *path, char *const argv_in[], char *const envp[]) { real(launcher, redirected, envp); free(redirected); } - bl_binfmt_before(path, argv, envp); + dd_binfmt_before(path, argv, envp); real(path, argv, envp); - return bl_binfmt_retry(path, argv, envp, errno); + return dd_binfmt_retry(path, argv, envp, errno); } static int answer_lsof_via_spawn(const char *path, char *const argv[], pid_t *pid) { @@ -373,17 +373,17 @@ static int answer_lsof_via_spawn(const char *path, char *const argv[], pid_t *pi } int execvp(const char *file, char *const argv_in[]) { - char *const *argv = bl_webhelper_argv(file, argv_in, environ); + char *const *argv = dd_webhelper_argv(file, argv_in, environ); static int (*real)(const char *, char *const[]); if (!real) real = (int (*)(const char *, char *const[]))dlsym(RTLD_NEXT, "execvp"); maybe_answer_lsof(file, argv); - bl_binfmt_before_search(file, argv, environ); + dd_binfmt_before_search(file, argv, environ); real(file, argv); - return bl_binfmt_after_search(file, argv, environ, errno); + return dd_binfmt_after_search(file, argv, environ, errno); } int execv(const char *path, char *const argv_in[]) { - char *const *argv = bl_webhelper_argv(path, argv_in, environ); + char *const *argv = dd_webhelper_argv(path, argv_in, environ); static int (*real)(const char *, char *const[]); if (!real) real = (int (*)(const char *, char *const[]))dlsym(RTLD_NEXT, "execv"); maybe_answer_lsof(path, argv); @@ -393,9 +393,9 @@ int execv(const char *path, char *const argv_in[]) { real(launcher, redirected); free(redirected); } - bl_binfmt_before(path, argv, environ); + dd_binfmt_before(path, argv, environ); real(path, argv); - return bl_binfmt_retry(path, argv, environ, errno); + return dd_binfmt_retry(path, argv, environ, errno); } int posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *fa, @@ -407,6 +407,6 @@ int posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t * } static spawn_fn real; if (!real) real = (spawn_fn)dlsym(RTLD_NEXT, "posix_spawn"); - char *const *adjusted = bl_webhelper_argv(path, argv, envp); - return bl_binfmt_spawn(pid, path, fa, attr, (char *const *)adjusted, envp, real); + char *const *adjusted = dd_webhelper_argv(path, argv, envp); + return dd_binfmt_spawn(pid, path, fa, attr, (char *const *)adjusted, envp, real); } diff --git a/tools/linuxfs/preload/netif.c b/tools/linuxfs/preload/netif.c index aeeeb9eb24..5be0dde22a 100644 --- a/tools/linuxfs/preload/netif.c +++ b/tools/linuxfs/preload/netif.c @@ -411,19 +411,19 @@ static int is_link_query(unsigned long request) { || request == SIOCGIFBRDADDR; } -void bl_kgsl_chip_id_fixup(unsigned long request, void *arg, int rc); +void dd_kgsl_chip_id_fixup(unsigned long request, void *arg, int rc); #include "../../quest/kgsl_compat.h" -int bl_kgsl_poll(int (*real)(int, unsigned long, void *), int fd, unsigned long request, +int dd_kgsl_poll(int (*real)(int, unsigned long, void *), int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden"))); -void bl_kgsl_track(int (*real)(int, unsigned long, void *), int fd, unsigned long request, +void dd_kgsl_track(int (*real)(int, unsigned long, void *), int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden"))); -int bl_ntsync_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden"))); -int bl_drm_gem_close(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden"))); -int bl_venc_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden"))); -int bl_vdec_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden"))); -int bl_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request, +int dd_ntsync_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden"))); +int dd_drm_gem_close(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden"))); +int dd_venc_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden"))); +int dd_vdec_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden"))); +int dd_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request, void *arg, void *caller, int *rc) __attribute__((visibility("hidden"))); -int bl_writewatch_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request, void *arg, +int dd_writewatch_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden"))); int ioctl(int fd, unsigned long request, ...) { @@ -435,16 +435,16 @@ int ioctl(int fd, unsigned long request, ...) { va_end(ap); int rc; - if (bl_ntsync_ioctl(fd, request, arg, &rc)) return rc; - if (bl_venc_ioctl(fd, request, arg, &rc)) return rc; - if (bl_vdec_ioctl(fd, request, arg, &rc)) return rc; - if (bl_drm_gem_close(fd, request, arg, &rc)) return rc; + if (dd_ntsync_ioctl(fd, request, arg, &rc)) return rc; + if (dd_venc_ioctl(fd, request, arg, &rc)) return rc; + if (dd_vdec_ioctl(fd, request, arg, &rc)) return rc; + if (dd_drm_gem_close(fd, request, arg, &rc)) return rc; if (real == NULL) real = (ioctl_fn) dlsym(RTLD_NEXT, "ioctl"); - if (bl_winebus_rumble_ioctl(real, fd, request, arg, __builtin_return_address(0), &rc)) return rc; - if (bl_writewatch_ioctl(real, fd, request, arg, &rc)) return rc; - if (!bl_kgsl_poll(real, fd, request, arg, &rc)) rc = quest_kgsl_ioctl(real, fd, request, arg); - bl_kgsl_track(real, fd, request, arg, &rc); - bl_kgsl_chip_id_fixup(request, arg, rc); + if (dd_winebus_rumble_ioctl(real, fd, request, arg, __builtin_return_address(0), &rc)) return rc; + if (dd_writewatch_ioctl(real, fd, request, arg, &rc)) return rc; + if (!dd_kgsl_poll(real, fd, request, arg, &rc)) rc = quest_kgsl_ioctl(real, fd, request, arg); + dd_kgsl_track(real, fd, request, arg, &rc); + dd_kgsl_chip_id_fixup(request, arg, rc); if (arg == NULL || !is_link_query(request)) return rc; int saved = errno; if (answer_ifreq(request, (struct ifreq *) arg, rc)) return 0; @@ -595,19 +595,19 @@ static FILE *synthesize(const char *table) { return out; } -int bl_status_without_tracer(const char *path, int flags, const void *caller) __attribute__((visibility("hidden"))); +int dd_status_without_tracer(const char *path, int flags, const void *caller) __attribute__((visibility("hidden"))); -const char *bl_oom_adj_redirect(const char *path, int writing) __attribute__((visibility("hidden"))); +const char *dd_oom_adj_redirect(const char *path, int writing) __attribute__((visibility("hidden"))); static FILE *open_stream(fopen_fn real, const char *path, const char *mode, const void *caller) { int status = mode && mode[0] == 'r' && !strchr(mode, '+') - ? bl_status_without_tracer(path, O_RDONLY | O_CLOEXEC, caller) : -1; + ? dd_status_without_tracer(path, O_RDONLY | O_CLOEXEC, caller) : -1; if (status >= 0) { FILE *copy = fdopen(status, "r"); if (copy == NULL) close(status); return copy; } - path = bl_oom_adj_redirect(path, mode && (mode[0] == 'w' || mode[0] == 'a' || strchr(mode, '+'))); + path = dd_oom_adj_redirect(path, mode && (mode[0] == 'w' || mode[0] == 'a' || strchr(mode, '+'))); int table = path && mode && mode[0] == 'r' ? denied_table(path) : -1; FILE *f; if (table >= 0 && denied_recently(table, path) && (f = synthesize(net_tables[table])) != NULL) return f; @@ -705,9 +705,9 @@ struct nl_reply { int overflow; }; -static const char nl_client_magic[12] = "bl-nl-c-v1"; -static const char nl_peer_magic[12] = "bl-nl-p-v1"; -static const char nl_reservation_magic[12] = "bl-nl-r-v1"; +static const char nl_client_magic[12] = "dd-nl-c-v1"; +static const char nl_peer_magic[12] = "dd-nl-p-v1"; +static const char nl_reservation_magic[12] = "dd-nl-r-v1"; static struct nl_socket *nl_sockets; static struct nl_fd *nl_fds; static struct nl_fd_page *nl_fd_pages[NL_FD_BUCKETS]; @@ -1206,36 +1206,36 @@ static unsigned nl_port_of(int fd) { return port; } -__attribute__((visibility("hidden"))) int bl_nl_socket(int type, int *fd); -__attribute__((visibility("hidden"))) int bl_nl_bind(int fd, const struct sockaddr *addr, +__attribute__((visibility("hidden"))) int dd_nl_socket(int type, int *fd); +__attribute__((visibility("hidden"))) int dd_nl_bind(int fd, const struct sockaddr *addr, socklen_t len, int *rc); -__attribute__((visibility("hidden"))) int bl_nl_getsockname(int fd, struct sockaddr *addr, +__attribute__((visibility("hidden"))) int dd_nl_getsockname(int fd, struct sockaddr *addr, socklen_t *len, int *rc); -__attribute__((visibility("hidden"))) int bl_nl_owns(int fd); -__attribute__((visibility("hidden"))) void bl_nl_closed(int fd); -__attribute__((visibility("hidden"))) void bl_nl_range_closed(unsigned int first, unsigned int last); -__attribute__((visibility("hidden"))) int bl_nl_before_dup(int fd, void **state); -__attribute__((visibility("hidden"))) void bl_nl_after_dup(void *state, int fd); -__attribute__((visibility("hidden"))) int bl_nl_connect(int fd, const struct sockaddr *addr, +__attribute__((visibility("hidden"))) int dd_nl_owns(int fd); +__attribute__((visibility("hidden"))) void dd_nl_closed(int fd); +__attribute__((visibility("hidden"))) void dd_nl_range_closed(unsigned int first, unsigned int last); +__attribute__((visibility("hidden"))) int dd_nl_before_dup(int fd, void **state); +__attribute__((visibility("hidden"))) void dd_nl_after_dup(void *state, int fd); +__attribute__((visibility("hidden"))) int dd_nl_connect(int fd, const struct sockaddr *addr, socklen_t len, int *rc); -__attribute__((visibility("hidden"))) int bl_nl_getpeername(int fd, struct sockaddr *addr, +__attribute__((visibility("hidden"))) int dd_nl_getpeername(int fd, struct sockaddr *addr, socklen_t *len, int *rc); -__attribute__((visibility("hidden"))) int bl_nl_setsockopt(int fd, int level, int option, +__attribute__((visibility("hidden"))) int dd_nl_setsockopt(int fd, int level, int option, const void *value, socklen_t len, int (*real)(int, int, int, const void *, socklen_t), int *rc); -__attribute__((visibility("hidden"))) int bl_nl_getsockopt(int fd, int level, int option, +__attribute__((visibility("hidden"))) int dd_nl_getsockopt(int fd, int level, int option, void *value, socklen_t *len, int (*real)(int, int, int, void *, socklen_t *), int *rc); -__attribute__((visibility("hidden"))) void bl_nl_received(struct msghdr *msg); -__attribute__((visibility("hidden"))) int bl_nl_recvmsg(int fd, struct msghdr *msg, int flags, +__attribute__((visibility("hidden"))) void dd_nl_received(struct msghdr *msg); +__attribute__((visibility("hidden"))) int dd_nl_recvmsg(int fd, struct msghdr *msg, int flags, ssize_t (*real)(int, struct msghdr *, int), ssize_t *rc); -int bl_nl_owns(int fd) { return nl_peer_of(fd) >= 0; } +int dd_nl_owns(int fd) { return nl_peer_of(fd) >= 0; } -int bl_nl_socket(int type, int *fd) { +int dd_nl_socket(int type, int *fd) { int kind = type & 0xf; *fd = -1; if (type & ~(0xf | SOCK_CLOEXEC | SOCK_NONBLOCK)) { @@ -1342,10 +1342,10 @@ static int nl_autobind(int fd) { return nl_bind_port(fd, 0, 1); } -int bl_nl_bind(int fd, const struct sockaddr *addr, socklen_t len, int *rc) { +int dd_nl_bind(int fd, const struct sockaddr *addr, socklen_t len, int *rc) { const struct sockaddr_nl *nl; if (addr && len >= sizeof(sa_family_t) && addr->sa_family == AF_NETLINK) nl_discover(fd); - if (!bl_nl_owns(fd)) return 0; + if (!dd_nl_owns(fd)) return 0; if (addr == NULL || len < sizeof(struct sockaddr_nl) || addr->sa_family != AF_NETLINK) { errno = EINVAL; *rc = -1; @@ -1361,10 +1361,10 @@ int bl_nl_bind(int fd, const struct sockaddr *addr, socklen_t len, int *rc) { return 1; } -int bl_nl_getsockname(int fd, struct sockaddr *addr, socklen_t *len, int *rc) { +int dd_nl_getsockname(int fd, struct sockaddr *addr, socklen_t *len, int *rc) { struct sockaddr_nl nl; socklen_t size; - if (!bl_nl_owns(fd)) return 0; + if (!dd_nl_owns(fd)) return 0; if (addr == NULL || len == NULL) { errno = EFAULT; *rc = -1; @@ -1380,13 +1380,13 @@ int bl_nl_getsockname(int fd, struct sockaddr *addr, socklen_t *len, int *rc) { return 1; } -void bl_nl_closed(int fd) { +void dd_nl_closed(int fd) { if (!nl_tracked(fd)) return; if (nl_foreign()) return; - bl_nl_range_closed((unsigned int) fd, (unsigned int) fd); + dd_nl_range_closed((unsigned int) fd, (unsigned int) fd); } -void bl_nl_range_closed(unsigned int first, unsigned int last) { +void dd_nl_range_closed(unsigned int first, unsigned int last) { if (__atomic_load_n(&nl_fd_count, __ATOMIC_ACQUIRE) == 0) return; if (nl_foreign()) return; pthread_mutex_lock(&nl_sockets_lock); @@ -1400,7 +1400,7 @@ void bl_nl_range_closed(unsigned int first, unsigned int last) { pthread_mutex_unlock(&nl_sockets_lock); } -int bl_nl_before_dup(int fd, void **state) { +int dd_nl_before_dup(int fd, void **state) { *state = NULL; if (!nl_tracked(fd)) return 0; if (nl_foreign()) return 0; @@ -1421,7 +1421,7 @@ int bl_nl_before_dup(int fd, void **state) { return 0; } -void bl_nl_after_dup(void *state, int fd) { +void dd_nl_after_dup(void *state, int fd) { int saved = errno; struct nl_fd *reserved = state; if (reserved == NULL && !nl_tracked(fd)) { @@ -1456,9 +1456,9 @@ int dup(int fd) { static int (*real)(int); void *state; if (real == NULL) real = (int (*)(int)) dlsym(RTLD_NEXT, "dup"); - if (bl_nl_before_dup(fd, &state) != 0) return -1; + if (dd_nl_before_dup(fd, &state) != 0) return -1; int result = real(fd); - bl_nl_after_dup(state, result); + dd_nl_after_dup(state, result); return result; } @@ -1470,9 +1470,9 @@ static int nl_destination(const struct sockaddr *addr, socklen_t len) { return destination->nl_pid == 0 ? 0 : -ECONNREFUSED; } -int bl_nl_connect(int fd, const struct sockaddr *addr, socklen_t len, int *rc) { +int dd_nl_connect(int fd, const struct sockaddr *addr, socklen_t len, int *rc) { if (addr && len >= sizeof(sa_family_t) && addr->sa_family == AF_NETLINK) nl_discover(fd); - if (!bl_nl_owns(fd)) return 0; + if (!dd_nl_owns(fd)) return 0; int disconnect = addr && len >= sizeof(sa_family_t) && addr->sa_family == AF_UNSPEC; int error = disconnect ? 0 : nl_destination(addr, len); if (error) { @@ -1493,8 +1493,8 @@ static void nl_source_name(struct sockaddr *addr, socklen_t *len) { *len = sizeof(source); } -int bl_nl_getpeername(int fd, struct sockaddr *addr, socklen_t *len, int *rc) { - if (!bl_nl_owns(fd)) return 0; +int dd_nl_getpeername(int fd, struct sockaddr *addr, socklen_t *len, int *rc) { + if (!dd_nl_owns(fd)) return 0; if (addr == NULL || len == NULL) { errno = EFAULT; *rc = -1; @@ -1505,7 +1505,7 @@ int bl_nl_getpeername(int fd, struct sockaddr *addr, socklen_t *len, int *rc) { return 1; } -int bl_nl_setsockopt(int fd, int level, int option, const void *value, socklen_t len, +int dd_nl_setsockopt(int fd, int level, int option, const void *value, socklen_t len, int (*real)(int, int, int, const void *, socklen_t), int *rc) { if (level == SOL_NETLINK) nl_discover(fd); int peer = nl_peer_of(fd); @@ -1542,7 +1542,7 @@ int bl_nl_setsockopt(int fd, int level, int option, const void *value, socklen_t return 1; } -int bl_nl_getsockopt(int fd, int level, int option, void *value, socklen_t *len, +int dd_nl_getsockopt(int fd, int level, int option, void *value, socklen_t *len, int (*real)(int, int, int, void *, socklen_t *), int *rc) { if (level != SOL_SOCKET || (option != SO_TYPE && option != SO_DOMAIN && option != SO_PROTOCOL)) return 0; @@ -1580,7 +1580,7 @@ int bl_nl_getsockopt(int fd, int level, int option, void *value, socklen_t *len, return 1; } -void bl_nl_received(struct msghdr *msg) { +void dd_nl_received(struct msghdr *msg) { for (struct cmsghdr *control = CMSG_FIRSTHDR(msg); control; control = CMSG_NXTHDR(msg, control)) { if (control->cmsg_len < CMSG_LEN(0)) break; if (control->cmsg_level != SOL_SOCKET || control->cmsg_type != SCM_RIGHTS) continue; @@ -1593,11 +1593,11 @@ void bl_nl_received(struct msghdr *msg) { } } -int bl_nl_recvmsg(int fd, struct msghdr *msg, int flags, +int dd_nl_recvmsg(int fd, struct msghdr *msg, int flags, ssize_t (*real)(int, struct msghdr *, int), ssize_t *rc) { ssize_t result; socklen_t capacity = 0; - if (!bl_nl_owns(fd)) return 0; + if (!dd_nl_owns(fd)) return 0; if (msg && msg->msg_name) capacity = msg->msg_namelen; result = real(fd, msg, flags); if (result >= 0 && msg && msg->msg_name) { @@ -1614,7 +1614,7 @@ ssize_t recvfrom(int fd, void *buffer, size_t length, int flags, if (real == NULL) real = (ssize_t (*)(int, void *, size_t, int, struct sockaddr *, socklen_t *)) dlsym(RTLD_NEXT, "recvfrom"); - int owned = bl_nl_owns(fd); + int owned = dd_nl_owns(fd); socklen_t capacity = owned && addr && addrlen ? *addrlen : 0; ssize_t result = real(fd, buffer, length, flags, addr, addrlen); if (result >= 0 && owned && addr && addrlen) { @@ -2108,7 +2108,7 @@ static ssize_t sendmsg_request(int fd, const struct msghdr *msg, int flags) { ssize_t sendmsg(int fd, const struct msghdr *msg, int flags) { static ssize_t (*real)(int, const struct msghdr *, int); - if (bl_nl_owns(fd)) { + if (dd_nl_owns(fd)) { int error = msg && msg->msg_name ? nl_destination(msg->msg_name, msg->msg_namelen) : 0; if (error) { errno = -error; @@ -2128,7 +2128,7 @@ ssize_t sendto(int fd, const void *buffer, size_t length, int flags, const struct sockaddr *addr, socklen_t addrlen) { static ssize_t (*real)(int, const void *, size_t, int, const struct sockaddr *, socklen_t); ssize_t rc; - if (bl_nl_owns(fd)) { + if (dd_nl_owns(fd)) { int error = addr ? nl_destination(addr, addrlen) : 0; if (error) { errno = -error; @@ -2149,7 +2149,7 @@ ssize_t sendto(int fd, const void *buffer, size_t length, int flags, ssize_t send(int fd, const void *buffer, size_t length, int flags) { static ssize_t (*real)(int, const void *, size_t, int); ssize_t rc; - if (bl_nl_owns(fd) && deliver(fd, buffer, length, flags, &rc)) return rc; + if (dd_nl_owns(fd) && deliver(fd, buffer, length, flags, &rc)) return rc; if (real == NULL) real = (ssize_t (*)(int, const void *, size_t, int)) dlsym(RTLD_NEXT, "send"); if (real == NULL) { errno = ENOSYS; @@ -2161,7 +2161,7 @@ ssize_t send(int fd, const void *buffer, size_t length, int flags) { ssize_t write(int fd, const void *buffer, size_t length) { static ssize_t (*real)(int, const void *, size_t); ssize_t rc; - if (bl_nl_owns(fd) && deliver(fd, buffer, length, 0, &rc)) return rc; + if (dd_nl_owns(fd) && deliver(fd, buffer, length, 0, &rc)) return rc; if (real == NULL) real = (ssize_t (*)(int, const void *, size_t)) dlsym(RTLD_NEXT, "write"); if (real == NULL) { errno = ENOSYS; @@ -2172,7 +2172,7 @@ ssize_t write(int fd, const void *buffer, size_t length) { ssize_t writev(int fd, const struct iovec *iov, int iovcnt) { static ssize_t (*real)(int, const struct iovec *, int); - if (iovcnt >= 0 && bl_nl_owns(fd)) { + if (iovcnt >= 0 && dd_nl_owns(fd)) { struct msghdr msg = { .msg_iov = (struct iovec *) iov, .msg_iovlen = (size_t) iovcnt }; return sendmsg_request(fd, &msg, 0); } diff --git a/tools/linuxfs/preload/noexec.c b/tools/linuxfs/preload/noexec.c index f77c15419c..e19d3c6725 100644 --- a/tools/linuxfs/preload/noexec.c +++ b/tools/linuxfs/preload/noexec.c @@ -25,7 +25,7 @@ static int in_fex(void) { return known; } -__attribute__((visibility("hidden"))) int bl_noexec_retry(int prot, int flags, int fd) { +__attribute__((visibility("hidden"))) int dd_noexec_retry(int prot, int flags, int fd) { int error = errno; struct statvfs vfs; int retry = (error == EACCES || error == EPERM) && (prot & PROT_EXEC) && fd >= 0 && !(flags & MAP_ANONYMOUS) && @@ -45,6 +45,7 @@ static size_t private_range(uintptr_t start, uintptr_t end, struct span *spans, char buf[4096]; size_t used = 0, count = 0; uintptr_t covered = start; + int file_backed = 0; int fd = open("/proc/self/maps", O_RDONLY | O_CLOEXEC); if (fd < 0) return 0; for (;;) { @@ -59,7 +60,13 @@ static size_t private_range(uintptr_t start, uintptr_t end, struct span *spans, char *p = line; uintptr_t lo = strtoull(p, &p, 16), hi = strtoull(p + 1, &p, 16); char perms[5] = {0}; - if (*p == ' ') memcpy(perms, p + 1, 4); + int inode = 0; + if (*p == ' ') { + memcpy(perms, p + 1, 4); + char *field = p + 5; + strtoull(field, &field, 16); + inode = *field && (field = strchr(field + 1, ' ')) && strtoull(field, NULL, 10); + } line = nl + 1; if (hi <= covered || lo >= end) continue; if (lo > covered || perms[3] != 'p' || count == cap) { @@ -68,11 +75,12 @@ static size_t private_range(uintptr_t start, uintptr_t end, struct span *spans, } spans[count].lo = covered; spans[count].hi = hi < end ? hi : end; + file_backed |= inode; spans[count].prot = (perms[0] == 'r' ? PROT_READ : 0) | (perms[1] == 'w' ? PROT_WRITE : 0) | (perms[2] == 'x' ? PROT_EXEC : 0); covered = spans[count++].hi; if (covered >= end) { close(fd); - return count; + return file_backed ? count : 0; } } used = strlen(line); @@ -138,7 +146,7 @@ int mprotect(void *addr, size_t len, int prot) { #else -__attribute__((visibility("hidden"))) int bl_noexec_retry(int prot, int flags, int fd) { +__attribute__((visibility("hidden"))) int dd_noexec_retry(int prot, int flags, int fd) { (void)prot, (void)flags, (void)fd; return 0; } diff --git a/tools/linuxfs/preload/ntsync.c b/tools/linuxfs/preload/ntsync.c index 6e012e3b6b..d5a8cc6853 100644 --- a/tools/linuxfs/preload/ntsync.c +++ b/tools/linuxfs/preload/ntsync.c @@ -189,7 +189,7 @@ static int (*ns_real_close)(int); static int ns_on(void) { if (ns_state < 0) { - const char *e = getenv("BL_SYNC"); + const char *e = getenv("DD_SYNC"); ns_state = e && e[0] == '1'; } return ns_state; @@ -276,7 +276,7 @@ static __thread struct ns_cs ns_cs; static uintptr_t ns_handlers[_NSIG]; static uint8_t ns_siginfo[_NSIG]; -int bl_from_ntdll(const void *caller) __attribute__((visibility("hidden"))); +int dd_from_ntdll(const void *caller) __attribute__((visibility("hidden"))); static int ns_deferrable(int sig) { return sig > 0 && sig < _NSIG && sig != SIGKILL && sig != SIGSTOP && sig != SIGSEGV && sig != SIGBUS && sig != SIGILL @@ -383,7 +383,7 @@ int sigaction(int sig, const struct sigaction *act, struct sigaction *old) { struct sigaction mine; const struct sigaction *use = act; if (act && act->sa_handler != SIG_DFL && act->sa_handler != SIG_IGN && !(act->sa_flags & SA_RESETHAND) && - bl_from_ntdll(__builtin_return_address(0))) { + dd_from_ntdll(__builtin_return_address(0))) { mine = *act; mine.sa_sigaction = ns_trampoline; mine.sa_flags |= SA_SIGINFO; @@ -1373,8 +1373,8 @@ static int ns_dev_ioctl(struct ns_dev *d, unsigned long req, void *arg, int *fd) return ENOTTY; } -int bl_ntsync_ioctl(int fd, unsigned long req, void *arg, int *rc) __attribute__((visibility("hidden"))); -int bl_ntsync_ioctl(int fd, unsigned long req, void *arg, int *rc) { +int dd_ntsync_ioctl(int fd, unsigned long req, void *arg, int *rc) __attribute__((visibility("hidden"))); +int dd_ntsync_ioctl(int fd, unsigned long req, void *arg, int *rc) { if (_IOC_TYPE(req) != 'N' || _IOC_NR(req) < 0x80 || _IOC_NR(req) > 0x8d) return 0; if (!__atomic_load_n(&ns_ndev, __ATOMIC_ACQUIRE) && !ns_on()) return 0; uint64_t e = ns_lookup(fd); @@ -1393,8 +1393,8 @@ int bl_ntsync_ioctl(int fd, unsigned long req, void *arg, int *rc) { return 1; } -int bl_ntsync_open(const char *path, int flags) __attribute__((visibility("hidden"))); -int bl_ntsync_open(const char *path, int flags) { +int dd_ntsync_open(const char *path, int flags) __attribute__((visibility("hidden"))); +int dd_ntsync_open(const char *path, int flags) { if (!path || strcmp(path, "/dev/ntsync") != 0 || !ns_on()) return -2; int fd = (int)syscall(SYS_openat, AT_FDCWD, path, flags, 0); if (fd >= 0) return fd; @@ -1440,41 +1440,41 @@ static void ns_received(struct msghdr *msg) { } } -int bl_udevmon_recvmsg(int fd, struct msghdr *msg, int flags, ssize_t (*real_recvmsg)(int, struct msghdr *, int), +int dd_udevmon_recvmsg(int fd, struct msghdr *msg, int flags, ssize_t (*real_recvmsg)(int, struct msghdr *, int), ssize_t *result) __attribute__((visibility("hidden"))); -int bl_nl_recvmsg(int fd, struct msghdr *msg, int flags, ssize_t (*real_recvmsg)(int, struct msghdr *, int), +int dd_nl_recvmsg(int fd, struct msghdr *msg, int flags, ssize_t (*real_recvmsg)(int, struct msghdr *, int), ssize_t *result) __attribute__((visibility("hidden"))); -void bl_nl_received(struct msghdr *msg) __attribute__((visibility("hidden"))); -void bl_nl_closed(int fd) __attribute__((visibility("hidden"))); -void bl_nl_range_closed(unsigned int first, unsigned int last) __attribute__((visibility("hidden"))); -int bl_nl_before_dup(int fd, void **state) __attribute__((visibility("hidden"))); -void bl_nl_after_dup(void *state, int fd) __attribute__((visibility("hidden"))); +void dd_nl_received(struct msghdr *msg) __attribute__((visibility("hidden"))); +void dd_nl_closed(int fd) __attribute__((visibility("hidden"))); +void dd_nl_range_closed(unsigned int first, unsigned int last) __attribute__((visibility("hidden"))); +int dd_nl_before_dup(int fd, void **state) __attribute__((visibility("hidden"))); +void dd_nl_after_dup(void *state, int fd) __attribute__((visibility("hidden"))); ssize_t recvmsg(int fd, struct msghdr *msg, int flags) { static ssize_t (*real)(int, struct msghdr *, int); if (!real) real = (ssize_t (*)(int, struct msghdr *, int))dlsym(RTLD_NEXT, "recvmsg"); ssize_t answered; - if (msg && bl_nl_recvmsg(fd, msg, flags, real, &answered)) return answered; - if (msg && bl_udevmon_recvmsg(fd, msg, flags, real, &answered)) return answered; + if (msg && dd_nl_recvmsg(fd, msg, flags, real, &answered)) return answered; + if (msg && dd_udevmon_recvmsg(fd, msg, flags, real, &answered)) return answered; ssize_t r = real(fd, msg, flags); if (r >= 0 && msg && msg->msg_control && msg->msg_controllen) { int saved = errno; - bl_nl_received(msg); + dd_nl_received(msg); if (ns_on()) ns_received(msg); errno = saved; } return r; } -void bl_fsync_fds_closed(unsigned int first, unsigned int last) __attribute__((visibility("hidden"))); -void bl_venc_closed(int fd) __attribute__((visibility("hidden"))); -void bl_vdec_closed(int fd) __attribute__((visibility("hidden"))); +void dd_fsync_fds_closed(unsigned int first, unsigned int last) __attribute__((visibility("hidden"))); +void dd_venc_closed(int fd) __attribute__((visibility("hidden"))); +void dd_vdec_closed(int fd) __attribute__((visibility("hidden"))); int close(int fd) { - if (fd >= 0) bl_fsync_fds_closed((unsigned int)fd, (unsigned int)fd); - bl_venc_closed(fd); - bl_vdec_closed(fd); - bl_nl_closed(fd); + if (fd >= 0) dd_fsync_fds_closed((unsigned int)fd, (unsigned int)fd); + dd_venc_closed(fd); + dd_vdec_closed(fd); + dd_nl_closed(fd); uint64_t *t = __atomic_load_n(&ns_fdt, __ATOMIC_ACQUIRE); if (t && fd >= 0 && fd < NS_FDS && __atomic_load_n(&t[fd], __ATOMIC_ACQUIRE)) ns_forget(fd); int saved = errno; @@ -1492,12 +1492,12 @@ int dup2(int oldfd, int newfd) { if (!real) real = (int (*)(int, int))dlsym(RTLD_NEXT, "dup2"); if (oldfd == newfd) return real(oldfd, newfd); void *nl_state; - if (bl_nl_before_dup(oldfd, &nl_state) != 0) return -1; - if (oldfd != newfd && newfd >= 0) bl_fsync_fds_closed((unsigned int)newfd, (unsigned int)newfd); + if (dd_nl_before_dup(oldfd, &nl_state) != 0) return -1; + if (oldfd != newfd && newfd >= 0) dd_fsync_fds_closed((unsigned int)newfd, (unsigned int)newfd); uint64_t *t = __atomic_load_n(&ns_fdt, __ATOMIC_ACQUIRE); if (t && oldfd != newfd && newfd >= 0 && newfd < NS_FDS && __atomic_load_n(&t[newfd], __ATOMIC_ACQUIRE)) ns_forget(newfd); int result = real(oldfd, newfd); - bl_nl_after_dup(nl_state, result); + dd_nl_after_dup(nl_state, result); return result; } @@ -1506,12 +1506,12 @@ int dup3(int oldfd, int newfd, int flags) { if (!real) real = (int (*)(int, int, int))dlsym(RTLD_NEXT, "dup3"); if (oldfd == newfd) return real(oldfd, newfd, flags); void *nl_state; - if (bl_nl_before_dup(oldfd, &nl_state) != 0) return -1; - if (oldfd != newfd && newfd >= 0) bl_fsync_fds_closed((unsigned int)newfd, (unsigned int)newfd); + if (dd_nl_before_dup(oldfd, &nl_state) != 0) return -1; + if (oldfd != newfd && newfd >= 0) dd_fsync_fds_closed((unsigned int)newfd, (unsigned int)newfd); uint64_t *t = __atomic_load_n(&ns_fdt, __ATOMIC_ACQUIRE); if (t && oldfd != newfd && newfd >= 0 && newfd < NS_FDS && __atomic_load_n(&t[newfd], __ATOMIC_ACQUIRE)) ns_forget(newfd); int result = real(oldfd, newfd, flags); - bl_nl_after_dup(nl_state, result); + dd_nl_after_dup(nl_state, result); return result; } @@ -1526,7 +1526,7 @@ int close_range(unsigned int first, unsigned int last, int flags) { static int (*real)(unsigned int, unsigned int, int); if (!real) real = (int (*)(unsigned int, unsigned int, int))dlsym(RTLD_NEXT, "close_range"); if (!(flags & CLOSE_RANGE_CLOEXEC)) { - bl_fsync_fds_closed(first, last); + dd_fsync_fds_closed(first, last); ns_forget_range(first, last); } if (!real) { @@ -1534,7 +1534,7 @@ int close_range(unsigned int first, unsigned int last, int flags) { return -1; } int result = real(first, last, flags); - if (result == 0 && !(flags & CLOSE_RANGE_CLOEXEC)) bl_nl_range_closed(first, last); + if (result == 0 && !(flags & CLOSE_RANGE_CLOEXEC)) dd_nl_range_closed(first, last); return result; } @@ -1542,12 +1542,12 @@ void closefrom(int lowfd) { static void (*real)(int); if (!real) real = (void (*)(int))dlsym(RTLD_NEXT, "closefrom"); if (lowfd >= 0) { - bl_fsync_fds_closed((unsigned int)lowfd, ~0u); + dd_fsync_fds_closed((unsigned int)lowfd, ~0u); ns_forget_range((unsigned int)lowfd, ~0u); } if (real) { real(lowfd); - if (lowfd >= 0) bl_nl_range_closed((unsigned int)lowfd, ~0u); + if (lowfd >= 0) dd_nl_range_closed((unsigned int)lowfd, ~0u); } } diff --git a/tools/linuxfs/preload/oomadj.c b/tools/linuxfs/preload/oomadj.c index 19e5f4251d..18dc592e9b 100644 --- a/tools/linuxfs/preload/oomadj.c +++ b/tools/linuxfs/preload/oomadj.c @@ -33,7 +33,7 @@ static int is_oom_score_adj(const char *path) { return strcmp(p, "oom_score_adj") == 0 || strcmp(p, "oom_adj") == 0; } -__attribute__((visibility("hidden"))) const char *bl_oom_adj_redirect(const char *path, int writing) { +__attribute__((visibility("hidden"))) const char *dd_oom_adj_redirect(const char *path, int writing) { static int logged; if (!writing || !is_oom_score_adj(path)) return path; if (!__atomic_exchange_n(&logged, 1, __ATOMIC_RELAXED)) { diff --git a/tools/linuxfs/preload/opens.c b/tools/linuxfs/preload/opens.c index 5b35396fcc..c9df092b40 100644 --- a/tools/linuxfs/preload/opens.c +++ b/tools/linuxfs/preload/opens.c @@ -11,13 +11,13 @@ #include #include -int bl_status_without_tracer(const char *path, int flags, const void *caller) __attribute__((visibility("hidden"))); -int bl_writable_retry(int dirfd, const char *path, int flags) __attribute__((visibility("hidden"))); -int bl_ntsync_open(const char *path, int flags) __attribute__((visibility("hidden"))); -const char *bl_oom_adj_redirect(const char *path, int writing) __attribute__((visibility("hidden"))); -int bl_venc_open(const char *path, int flags) __attribute__((visibility("hidden"))); -int bl_vdec_open(const char *path, int flags) __attribute__((visibility("hidden"))); -int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode, +int dd_status_without_tracer(const char *path, int flags, const void *caller) __attribute__((visibility("hidden"))); +int dd_writable_retry(int dirfd, const char *path, int flags) __attribute__((visibility("hidden"))); +int dd_ntsync_open(const char *path, int flags) __attribute__((visibility("hidden"))); +const char *dd_oom_adj_redirect(const char *path, int writing) __attribute__((visibility("hidden"))); +int dd_venc_open(const char *path, int flags) __attribute__((visibility("hidden"))); +int dd_vdec_open(const char *path, int flags) __attribute__((visibility("hidden"))); +int dd_dircache_create(int dirfd, const char *path, int flags, mode_t mode, int (*real)(int, const char *, int, mode_t)) __attribute__((visibility("hidden"))); static int (*real_open)(const char *, int, ...); @@ -49,19 +49,19 @@ static int open_from(const char *path, int flags, mode_t mode, const void *calle errno = EACCES; return -1; } - path = bl_oom_adj_redirect(path, (flags & O_ACCMODE) != O_RDONLY); - if ((fd = bl_status_without_tracer(path, flags, caller)) >= 0) return fd; - if ((fd = bl_ntsync_open(path, flags)) != -2) return fd; - if ((fd = bl_venc_open(path, flags)) != -2) return fd; - if ((fd = bl_vdec_open(path, flags)) != -2) return fd; + path = dd_oom_adj_redirect(path, (flags & O_ACCMODE) != O_RDONLY); + if ((fd = dd_status_without_tracer(path, flags, caller)) >= 0) return fd; + if ((fd = dd_ntsync_open(path, flags)) != -2) return fd; + if ((fd = dd_venc_open(path, flags)) != -2) return fd; + if ((fd = dd_vdec_open(path, flags)) != -2) return fd; if (real_open == NULL) real_open = dlsym(RTLD_NEXT, "open"); if (real_open == NULL) { errno = ENOSYS; return -1; } - fd = bl_dircache_create(AT_FDCWD, path, flags, mode, via_open); + fd = dd_dircache_create(AT_FDCWD, path, flags, mode, via_open); if (retry_without_noatime(fd, flags)) fd = real_open(path, flags & ~O_NOATIME, mode); - if (fd < 0 && bl_writable_retry(AT_FDCWD, path, flags)) fd = real_open(path, flags & ~O_NOATIME, mode); + if (fd < 0 && dd_writable_retry(AT_FDCWD, path, flags)) fd = real_open(path, flags & ~O_NOATIME, mode); return fd; } @@ -72,19 +72,19 @@ static int openat_from(int dirfd, const char *path, int flags, mode_t mode, cons errno = EACCES; return -1; } - path = bl_oom_adj_redirect(path, (flags & O_ACCMODE) != O_RDONLY); - if ((fd = bl_status_without_tracer(path, flags, caller)) >= 0) return fd; - if ((fd = bl_ntsync_open(path, flags)) != -2) return fd; - if ((fd = bl_venc_open(path, flags)) != -2) return fd; - if ((fd = bl_vdec_open(path, flags)) != -2) return fd; + path = dd_oom_adj_redirect(path, (flags & O_ACCMODE) != O_RDONLY); + if ((fd = dd_status_without_tracer(path, flags, caller)) >= 0) return fd; + if ((fd = dd_ntsync_open(path, flags)) != -2) return fd; + if ((fd = dd_venc_open(path, flags)) != -2) return fd; + if ((fd = dd_vdec_open(path, flags)) != -2) return fd; if (real_openat == NULL) real_openat = dlsym(RTLD_NEXT, "openat"); if (real_openat == NULL) { errno = ENOSYS; return -1; } - fd = bl_dircache_create(dirfd, path, flags, mode, via_openat); + fd = dd_dircache_create(dirfd, path, flags, mode, via_openat); if (retry_without_noatime(fd, flags)) fd = real_openat(dirfd, path, flags & ~O_NOATIME, mode); - if (fd < 0 && bl_writable_retry(dirfd, path, flags)) fd = real_openat(dirfd, path, flags & ~O_NOATIME, mode); + if (fd < 0 && dd_writable_retry(dirfd, path, flags)) fd = real_openat(dirfd, path, flags & ~O_NOATIME, mode); return fd; } diff --git a/tools/linuxfs/preload/owner.c b/tools/linuxfs/preload/owner.c index 1e493f8a80..9c5b290c57 100644 --- a/tools/linuxfs/preload/owner.c +++ b/tools/linuxfs/preload/owner.c @@ -13,7 +13,7 @@ #define EXFAT_MAGIC 0x2011bab0 __attribute__((visibility("hidden"))) -int bl_is_wineserver(void) { +int dd_is_wineserver(void) { static int cached = -1; char exe[PATH_MAX]; const char *base; @@ -40,11 +40,11 @@ static int has_no_unix_owner(int fd) { } __attribute__((visibility("hidden"))) -void bl_storage_owner(int fd, struct stat *st) { +void dd_storage_owner(int fd, struct stat *st) { int saved = errno; uid_t uid; - if (st != NULL && bl_is_wineserver()) { + if (st != NULL && dd_is_wineserver()) { uid = getuid(); if (st->st_uid != uid && has_no_unix_owner(fd)) st->st_uid = uid; } @@ -61,7 +61,7 @@ int fchmod(int fd, mode_t mode) { return -1; } result = next_fchmod(fd, mode); - if (result != 0 && errno == EPERM && bl_is_wineserver()) { + if (result != 0 && errno == EPERM && dd_is_wineserver()) { if (has_no_unix_owner(fd)) { errno = saved; return 0; diff --git a/tools/linuxfs/preload/pathcache.c b/tools/linuxfs/preload/pathcache.c index 59f2cbf069..400a1e5786 100644 --- a/tools/linuxfs/preload/pathcache.c +++ b/tools/linuxfs/preload/pathcache.c @@ -40,7 +40,7 @@ static int enabled(void) { const char *off; if (cached >= 0) return cached; - off = getenv("BL_NO_PATH_CACHE"); + off = getenv("DD_NO_PATH_CACHE"); cached = strcmp(program_invocation_short_name, "steam") == 0 && (strstr(program_invocation_name, "steamrtarm64") != NULL || strstr(program_invocation_name, "steamrt64") != NULL) && @@ -83,7 +83,7 @@ static void store(const char *path, int kind, int mode, int flags, unsigned h, c } __attribute__((visibility("hidden"))) -char *bl_cached_realpath(const char *path, char *resolved, char *(*real)(const char *, char *)) { +char *dd_cached_realpath(const char *path, char *resolved, char *(*real)(const char *, char *)) { char out[PATH_MAX]; unsigned h; struct entry *e; @@ -111,7 +111,7 @@ char *bl_cached_realpath(const char *path, char *resolved, char *(*real)(const c return strdup(out); } -int bl_dircache_absent(const char *path) __attribute__((weak, visibility("hidden"))); +int dd_dircache_absent(const char *path) __attribute__((weak, visibility("hidden"))); static int cached_access(const char *path, int mode, int flags, int (*check)(const char *, int, int)) { unsigned h; @@ -124,7 +124,7 @@ static int cached_access(const char *path, int mode, int flags, int (*check)(con hit = find(path, KIND_ACCESS, mode, flags, h) != NULL; pthread_mutex_unlock(&lock); if (hit) return 0; - if (bl_dircache_absent && bl_dircache_absent(path)) { + if (dd_dircache_absent && dd_dircache_absent(path)) { errno = ENOENT; return -1; } @@ -144,11 +144,11 @@ static int (*next_faccessat(void))(int, const char *, int, int) { return real; } -__attribute__((visibility("hidden"))) int bl_binfmt_runnable(const char *path, int mode); -__attribute__((visibility("hidden"))) int bl_writable_access(int dirfd, const char *path, int mode, int flags); +__attribute__((visibility("hidden"))) int dd_binfmt_runnable(const char *path, int mode); +__attribute__((visibility("hidden"))) int dd_writable_access(int dirfd, const char *path, int mode, int flags); static int writable_as_owner(int (*real)(int, const char *, int, int), int dirfd, const char *path, int mode, int flags) { - if (!bl_writable_access(dirfd, path, mode, flags)) return -1; + if (!dd_writable_access(dirfd, path, mode, flags)) return -1; if ((mode & ~W_OK) == 0 || real(dirfd, path, mode & ~W_OK, flags) == 0) return 0; return -1; } @@ -165,7 +165,7 @@ static int check_cwd(const char *path, int mode, int flags) { result = real(AT_FDCWD, path, mode, flags); if (result == 0) return 0; err = errno; - if (err == EACCES && bl_binfmt_runnable(path, mode)) return 0; + if (err == EACCES && dd_binfmt_runnable(path, mode)) return 0; errno = err; if (writable_as_owner(real, AT_FDCWD, path, mode, flags) == 0) return 0; errno = err; diff --git a/tools/linuxfs/preload/perms.c b/tools/linuxfs/preload/perms.c index e90bad6fe7..9ca5f6a9c0 100644 --- a/tools/linuxfs/preload/perms.c +++ b/tools/linuxfs/preload/perms.c @@ -60,7 +60,7 @@ static int grant_owner_write(int dirfd, const char *path) { } __attribute__((visibility("hidden"))) -int bl_writable_retry(int dirfd, const char *path, int flags) { +int dd_writable_retry(int dirfd, const char *path, int flags) { int saved = errno; int granted = 0; char parent[PATH_MAX]; @@ -84,7 +84,7 @@ int bl_writable_retry(int dirfd, const char *path, int flags) { } __attribute__((visibility("hidden"))) -int bl_writable_access(int dirfd, const char *path, int mode, int flags) { +int dd_writable_access(int dirfd, const char *path, int mode, int flags) { int saved = errno; struct stat st; int owned; diff --git a/tools/linuxfs/preload/robust.c b/tools/linuxfs/preload/robust.c index 377b895672..6d3393b506 100644 --- a/tools/linuxfs/preload/robust.c +++ b/tools/linuxfs/preload/robust.c @@ -21,22 +21,22 @@ #define SYS_openat2 437 #endif -#define BL_RESOLVE_BENEATH 0x08 -#define BL_RESOLVE_IN_ROOT 0x10 -#define BL_MAX_SYMLINKS 40 -#define BL_PROC_ROOT_INO 1 +#define DD_RESOLVE_BENEATH 0x08 +#define DD_RESOLVE_IN_ROOT 0x10 +#define DD_MAX_SYMLINKS 40 +#define DD_PROC_ROOT_INO 1 #ifdef SYS_newfstatat -#define BL_SYS_FSTATAT SYS_newfstatat -#define BL_FSTATAT_NAME "fstatat" -typedef struct stat bl_stat; +#define DD_SYS_FSTATAT SYS_newfstatat +#define DD_FSTATAT_NAME "fstatat" +typedef struct stat dd_stat; #else -#define BL_SYS_FSTATAT SYS_fstatat64 -#define BL_FSTATAT_NAME "fstatat64" -typedef struct stat64 bl_stat; +#define DD_SYS_FSTATAT SYS_fstatat64 +#define DD_FSTATAT_NAME "fstatat64" +typedef struct stat64 dd_stat; #endif -struct bl_open_how { +struct dd_open_how { uint64_t flags; uint64_t mode; uint64_t resolve; @@ -45,7 +45,7 @@ struct bl_open_how { static long (*real_syscall)(long, ...); static void *(*real_dlopen)(const char *, int); static int openat2_missing; -static int (*next_fstatat)(int, const char *, bl_stat *, int); +static int (*next_fstatat)(int, const char *, dd_stat *, int); static int (*next_openat)(int, const char *, int, ...); static ssize_t (*next_readlinkat)(int, const char *, char *, size_t); static int (*next_statx)(int, const char *, int, unsigned int, struct statx *); @@ -53,7 +53,7 @@ static int (*next_statx)(int, const char *, int, unsigned int, struct statx *); static int find_fastpath(struct dl_phdr_info *info, size_t size, void *name) { (void)size; const char *slash = strrchr(info->dlpi_name, '/'); - if (!slash || strcmp(slash + 1, "libblfastpath.so") != 0 || strlen(info->dlpi_name) >= PATH_MAX) { + if (!slash || strcmp(slash + 1, "libddfastpath.so") != 0 || strlen(info->dlpi_name) >= PATH_MAX) { return 0; } strcpy(name, info->dlpi_name); @@ -65,16 +65,16 @@ __attribute__((constructor)) static void find_fastpath_calls(void) { dl_iterate_phdr(find_fastpath, name); void *fastpath = *name ? dlopen(name, RTLD_NOLOAD | RTLD_LAZY) : NULL; if (fastpath) { - next_fstatat = (int (*)(int, const char *, bl_stat *, int))dlsym(fastpath, BL_FSTATAT_NAME); + next_fstatat = (int (*)(int, const char *, dd_stat *, int))dlsym(fastpath, DD_FSTATAT_NAME); next_openat = (int (*)(int, const char *, int, ...))dlsym(fastpath, "openat"); next_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(fastpath, "readlinkat"); next_statx = (int (*)(int, const char *, int, unsigned int, struct statx *))dlsym(fastpath, "statx"); } } -static long path_stat(int dirfd, const char *path, bl_stat *st, int flags) { +static long path_stat(int dirfd, const char *path, dd_stat *st, int flags) { if (!next_fstatat) { - return real_syscall(BL_SYS_FSTATAT, (long)dirfd, (long)path, (long)st, (long)flags); + return real_syscall(DD_SYS_FSTATAT, (long)dirfd, (long)path, (long)st, (long)flags); } return next_fstatat(dirfd, path, st, flags); } @@ -112,7 +112,7 @@ void *dlopen(const char *filename, int flags) { return real_dlopen(filename, flags); } -int bl_fsync_syscall(long number, const long *args, long *ret) __attribute__((visibility("hidden"))); +int dd_fsync_syscall(long number, const long *args, long *ret) __attribute__((visibility("hidden"))); static struct robust_list_head *thread_robust_head(void) { pthread_mutexattr_t attr; @@ -159,10 +159,10 @@ static int is_magic_link(int dirfd, char *link, size_t parent_len) { } char saved = link[parent_len]; link[parent_len] = 0; - bl_stat parent; + dd_stat parent; long result = path_stat(dirfd, (parent_len ? link : "."), &parent, 0); link[parent_len] = saved; - return result != 0 || parent.st_ino != BL_PROC_ROOT_INO; + return result != 0 || parent.st_ino != DD_PROC_ROOT_INO; } static long openat_in_root(int dirfd, const char *path, int flags, long mode) { @@ -217,16 +217,16 @@ static long openat_in_root(int dirfd, const char *path, int flags, long mode) { } memcpy(resolved + resolved_len + separator, name, len); resolved[candidate_len] = 0; - bl_stat st; + dd_stat st; int follow = !last || trailing_slash || !nofollow; long stat_result = follow ? path_stat(dirfd, resolved, &st, AT_SYMLINK_NOFOLLOW) : -1; if (stat_result == 0 && S_ISLNK(st.st_mode)) { - if (++symlinks > BL_MAX_SYMLINKS) { + if (++symlinks > DD_MAX_SYMLINKS) { errno = ELOOP; return -1; } if (!have_root) { - bl_stat root; + dd_stat root; struct statfs root_fs; if (path_stat(dirfd, ".", &root, 0) != 0) { return -1; @@ -265,7 +265,7 @@ static long openat_in_root(int dirfd, const char *path, int flags, long mode) { while (*inside == '/') { inside++; } - bl_stat probe; + dd_stat probe; int host = *inside && path_stat(dirfd, inside, &probe, AT_SYMLINK_NOFOLLOW) != 0 && errno == ENOENT && path_stat(AT_FDCWD, pending, &probe, 0) == 0; pending[target_len] = saved; @@ -302,22 +302,22 @@ static long openat_in_root(int dirfd, const char *path, int flags, long mode) { static long openat2_via_openat(const long *args) { const char *path = (const char *)args[1]; - const struct bl_open_how *how = (const struct bl_open_how *)args[2]; + const struct dd_open_how *how = (const struct dd_open_how *)args[2]; if (!path || !how || (size_t)args[3] < sizeof(*how)) { errno = EINVAL; return -1; } - if ((how->resolve & BL_RESOLVE_IN_ROOT) && (int)args[0] != AT_FDCWD) { + if ((how->resolve & DD_RESOLVE_IN_ROOT) && (int)args[0] != AT_FDCWD) { return openat_in_root((int)args[0], path, (int)how->flags, (long)how->mode); } - if (how->resolve & BL_RESOLVE_IN_ROOT) { + if (how->resolve & DD_RESOLVE_IN_ROOT) { while (*path == '/') { path++; } if (!*path) { path = "."; } - } else if ((how->resolve & BL_RESOLVE_BENEATH) && *path == '/') { + } else if ((how->resolve & DD_RESOLVE_BENEATH) && *path == '/') { errno = EXDEV; return -1; } @@ -346,14 +346,14 @@ static long openat2_call(const long *args) { return openat2_via_openat(args); } -int bl_openat2(int dirfd, const char *path, void *how, size_t size) __asm__("openat2"); -int bl_openat2(int dirfd, const char *path, void *how, size_t size) { +int dd_openat2(int dirfd, const char *path, void *how, size_t size) __asm__("openat2"); +int dd_openat2(int dirfd, const char *path, void *how, size_t size) { long args[6] = {dirfd, (long)path, (long)how, (long)size, 0, 0}; return (int)openat2_call(args); } -int bl_writewatch_syscall(long number, const long *args, long (*real)(long, ...), long *rc) __attribute__((visibility("hidden"))); -int bl_clock_syscall(long number, const long *args, long (*real)(long, ...), long *ret) __attribute__((visibility("hidden"))); +int dd_writewatch_syscall(long number, const long *args, long (*real)(long, ...), long *rc) __attribute__((visibility("hidden"))); +int dd_clock_syscall(long number, const long *args, long (*real)(long, ...), long *ret) __attribute__((visibility("hidden"))); long syscall(long number, ...) { va_list ap; @@ -374,16 +374,16 @@ long syscall(long number, ...) { return 0; } long handled; - if (bl_fsync_syscall(number, args, &handled)) { + if (dd_fsync_syscall(number, args, &handled)) { return handled; } if (!real_syscall) { real_syscall = (long (*)(long, ...)) dlsym(RTLD_NEXT, "syscall"); } - if (bl_clock_syscall(number, args, real_syscall, &handled)) { + if (dd_clock_syscall(number, args, real_syscall, &handled)) { return handled; } - if (bl_writewatch_syscall(number, args, real_syscall, &handled)) { + if (dd_writewatch_syscall(number, args, real_syscall, &handled)) { return handled; } if (number == SYS_openat2) { @@ -392,8 +392,8 @@ long syscall(long number, ...) { if (number == SYS_openat) { return path_open((int)args[0], (const char *)args[1], (int)args[2], args[3]); } - if (number == BL_SYS_FSTATAT) { - return path_stat((int)args[0], (const char *)args[1], (bl_stat *)args[2], (int)args[3]); + if (number == DD_SYS_FSTATAT) { + return path_stat((int)args[0], (const char *)args[1], (dd_stat *)args[2], (int)args[3]); } if (number == SYS_readlinkat) { return path_readlink((int)args[0], (const char *)args[1], (char *)args[2], (size_t)args[3]); diff --git a/tools/linuxfs/preload/rptouch.c b/tools/linuxfs/preload/rptouch.c index b8eb5ea90b..705195d528 100644 --- a/tools/linuxfs/preload/rptouch.c +++ b/tools/linuxfs/preload/rptouch.c @@ -9,8 +9,8 @@ #include "../../../app/src/main/cpp/venc/venc_proto.h" -int bl_venc_streaming(void) __attribute__((visibility("hidden"))); -int bl_venc_connect(void) __attribute__((visibility("hidden"))); +int dd_venc_streaming(void) __attribute__((visibility("hidden"))); +int dd_venc_connect(void) __attribute__((visibility("hidden"))); static pthread_mutex_t rt_lock = PTHREAD_MUTEX_INITIALIZER; static int rt_fd = -1, rt_down, rt_x, rt_y, rt_screen; @@ -18,10 +18,10 @@ static int rt_fd = -1, rt_down, rt_x, rt_y, rt_screen; static int rt_enabled(void) { static int enabled = -1; if (enabled < 0) { - const char *v = getenv("BL_REMOTE_TOUCH"); + const char *v = getenv("DD_REMOTE_TOUCH"); enabled = v == NULL || strcmp(v, "0") != 0; } - return enabled && bl_venc_streaming(); + return enabled && dd_venc_streaming(); } static uint32_t rt_fraction(int value, int extent) { @@ -40,7 +40,7 @@ static void rt_send(void *dpy, uint32_t action) { .x = rt_fraction(rt_x, width(dpy, rt_screen)), .y = rt_fraction(rt_y, height(dpy, rt_screen)), }; for (int attempt = 0; attempt < 2; attempt++) { - if (rt_fd < 0) rt_fd = bl_venc_connect(); + if (rt_fd < 0) rt_fd = dd_venc_connect(); if (rt_fd < 0) return; if (send(rt_fd, &m, sizeof m, MSG_NOSIGNAL) == (ssize_t)sizeof m) return; close(rt_fd); diff --git a/tools/linuxfs/preload/space.c b/tools/linuxfs/preload/space.c index 950197f655..e3da12a7fa 100644 --- a/tools/linuxfs/preload/space.c +++ b/tools/linuxfs/preload/space.c @@ -7,7 +7,7 @@ #include static const char *content_of(const char *path, char *buf, size_t len) { - const char *roots = getenv("BL_LIBRARY_SPACE"); + const char *roots = getenv("DD_LIBRARY_SPACE"); if (!path || !roots || !*roots) return NULL; diff --git a/tools/linuxfs/preload/storage.c b/tools/linuxfs/preload/storage.c index 53ce078e93..29737871a4 100644 --- a/tools/linuxfs/preload/storage.c +++ b/tools/linuxfs/preload/storage.c @@ -13,7 +13,7 @@ #include static int (*next_fstat)(int, struct stat *); -void bl_storage_owner(int fd, struct stat *st) __attribute__((visibility("hidden"))); +void dd_storage_owner(int fd, struct stat *st) __attribute__((visibility("hidden"))); static int (*next_fallocate)(int, int, off_t, off_t); static int (*next_posix_fallocate)(int, off_t, off_t); static ssize_t (*next_pwrite)(int, const void *, size_t, off_t); @@ -59,8 +59,8 @@ static void initialize(void) { while (__atomic_load_n(&init_state, __ATOMIC_ACQUIRE) != 2) { } return; } - const char *on = getenv("BL_STORAGE_DIAGNOSTICS"); - const char *device = getenv("BL_STORAGE_DEVICE"); + const char *on = getenv("DD_STORAGE_DIAGNOSTICS"); + const char *device = getenv("DD_STORAGE_DEVICE"); if (on != NULL && strcmp(on, "1") == 0 && device != NULL && *device != '\0') { char *end = NULL; errno = 0; @@ -105,7 +105,7 @@ static void comm_name(char *out, size_t size) { } static void append_line(const char *line, size_t length) { - const char *path = getenv("BL_STORAGE_LOG"); + const char *path = getenv("DD_STORAGE_LOG"); struct stat st; int saved = errno; if (path == NULL || *path == '\0' || length == 0 || length > 2048) goto done; @@ -288,7 +288,7 @@ int fstat(int fd, struct stat *out) { errno = entry_errno; if (!enabled) { int result = next_fstat(fd, out); - if (result == 0) bl_storage_owner(fd, out); + if (result == 0) dd_storage_owner(fd, out); return result; } uint64_t start = now_ns(); @@ -296,7 +296,7 @@ int fstat(int fd, struct stat *out) { int result = next_fstat(fd, out); int call_errno = errno; uint64_t elapsed = now_ns() - start; - if (result == 0) bl_storage_owner(fd, out); + if (result == 0) dd_storage_owner(fd, out); if (result == 0 && on_selected_device(fd, out)) { add(&stats.fstat_calls, 1); add(&stats.fstat_elapsed_ns, elapsed); diff --git a/tools/linuxfs/preload/subreaper.c b/tools/linuxfs/preload/subreaper.c index 90ed7548d3..5aea82a3f5 100644 --- a/tools/linuxfs/preload/subreaper.c +++ b/tools/linuxfs/preload/subreaper.c @@ -1,6 +1,6 @@ /* tools/linuxfs/preload/subreaper.c * - * Mark every process that loads libblsession.so as a child subreaper. + * Mark every process that loads libddsession.so as a child subreaper. * * wlroots starts Xwayland with a double fork: gamescope -> middle process * (exits immediately) -> Xwayland. With no subreaper in the tree, Xwayland @@ -18,7 +18,7 @@ #include __attribute__((constructor)) -static void bl_session_set_subreaper(void) +static void dd_session_set_subreaper(void) { (void)prctl(PR_SET_CHILD_SUBREAPER, 1); } diff --git a/tools/linuxfs/preload/sysv.c b/tools/linuxfs/preload/sysv.c index 4d3752f854..77d14d3e5a 100644 --- a/tools/linuxfs/preload/sysv.c +++ b/tools/linuxfs/preload/sysv.c @@ -48,7 +48,7 @@ static char g_dir[PATH_MAX - NAME_MAX - 2]; static const char *object_dir(void) { if (!g_dir[0]) { - const char *d = getenv("BL_SYSV_DIR"); + const char *d = getenv("DD_SYSV_DIR"); snprintf(g_dir, sizeof(g_dir), "%s", d && *d ? d : DIR_DEFAULT); mkdir(g_dir, 0700); } diff --git a/tools/linuxfs/preload/tracer.c b/tools/linuxfs/preload/tracer.c index 7f5ac8e8cd..ec8dd003f9 100644 --- a/tools/linuxfs/preload/tracer.c +++ b/tools/linuxfs/preload/tracer.c @@ -16,7 +16,7 @@ #define STATUS_MAX 16384 #define TRACER_FIELD "\nTracerPid:\t" -int bl_from_ntdll(const void *caller) __attribute__((visibility("hidden"))); +int dd_from_ntdll(const void *caller) __attribute__((visibility("hidden"))); static const char *skip_digits(const char *s) { const char *end = s; @@ -41,7 +41,7 @@ static int is_web_helper(const void *caller) { if (strcmp(program_invocation_short_name, "steamwebhelper") != 0 && strcmp(program_invocation_short_name, "vrwebhelper") != 0) return 0; - const char *hide = getenv("BL_WEBHELPER_HIDE_TRACER"); + const char *hide = getenv("DD_WEBHELPER_HIDE_TRACER"); Dl_info info; if (hide && hide[0] == '1' && caller && dladdr(caller, &info) && info.dli_fname && strstr(info.dli_fname, "libtier0_s.so")) @@ -72,14 +72,14 @@ static int read_only_copy(const char *data, size_t len, int flags) { return ro; } -__attribute__((visibility("hidden"))) int bl_status_without_tracer(const char *path, int flags, const void *caller) { +__attribute__((visibility("hidden"))) int dd_status_without_tracer(const char *path, int flags, const void *caller) { char text[STATUS_MAX]; size_t len = 0; int saved = errno; int out = -1; long pid; - if ((flags & O_ACCMODE) != O_RDONLY || (pid = status_pid(path)) < 0 || is_web_helper(caller) || bl_from_ntdll(caller)) + if ((flags & O_ACCMODE) != O_RDONLY || (pid = status_pid(path)) < 0 || is_web_helper(caller) || dd_from_ntdll(caller)) return -1; // through the next open(): the native userland's hook gives the app's ids as root's there static int (*next_open)(const char *, int, ...) = NULL; diff --git a/tools/linuxfs/preload/udevmon.c b/tools/linuxfs/preload/udevmon.c index 2d4e9bf70d..d3af29ef43 100644 --- a/tools/linuxfs/preload/udevmon.c +++ b/tools/linuxfs/preload/udevmon.c @@ -102,17 +102,17 @@ static int make_stand_in(int type) { return -1; } -__attribute__((visibility("hidden"))) int bl_nl_socket(int type, int *fd); -__attribute__((visibility("hidden"))) int bl_nl_owns(int fd); -__attribute__((visibility("hidden"))) int bl_nl_getsockname(int fd, struct sockaddr *addr, +__attribute__((visibility("hidden"))) int dd_nl_socket(int type, int *fd); +__attribute__((visibility("hidden"))) int dd_nl_owns(int fd); +__attribute__((visibility("hidden"))) int dd_nl_getsockname(int fd, struct sockaddr *addr, socklen_t *len, int *rc); -__attribute__((visibility("hidden"))) int bl_nl_getpeername(int fd, struct sockaddr *addr, +__attribute__((visibility("hidden"))) int dd_nl_getpeername(int fd, struct sockaddr *addr, socklen_t *len, int *rc); -__attribute__((visibility("hidden"))) int bl_nl_setsockopt(int fd, int level, int option, +__attribute__((visibility("hidden"))) int dd_nl_setsockopt(int fd, int level, int option, const void *value, socklen_t len, int (*real)(int, int, int, const void *, socklen_t), int *rc); -__attribute__((visibility("hidden"))) int bl_nl_getsockopt(int fd, int level, int option, +__attribute__((visibility("hidden"))) int dd_nl_getsockopt(int fd, int level, int option, void *value, socklen_t *len, int (*real)(int, int, int, void *, socklen_t *), int *rc); @@ -128,7 +128,7 @@ int socket(int domain, int type, int protocol) { } if (domain == AF_NETLINK && protocol == NETLINK_ROUTE) { int route_fd; - bl_nl_socket(type, &route_fd); + dd_nl_socket(type, &route_fd); return route_fd; } fd = real_socket(domain, type, protocol); @@ -142,7 +142,7 @@ int socket(int domain, int type, int protocol) { return make_stand_in(type); } -__attribute__((visibility("hidden"))) int bl_udevmon_stand_in(int fd) { +__attribute__((visibility("hidden"))) int dd_udevmon_stand_in(int fd) { return is_stand_in(fd); } @@ -151,7 +151,7 @@ int getsockname(int fd, struct sockaddr *addr, socklen_t *len) { struct sockaddr_nl nl; int route_rc; - if (bl_nl_getsockname(fd, addr, len, &route_rc)) return route_rc; + if (dd_nl_getsockname(fd, addr, len, &route_rc)) return route_rc; if (is_stand_in(fd)) { if (addr == NULL || len == NULL) { errno = EFAULT; @@ -175,7 +175,7 @@ int getsockname(int fd, struct sockaddr *addr, socklen_t *len) { int getpeername(int fd, struct sockaddr *addr, socklen_t *len) { static int (*real)(int, struct sockaddr *, socklen_t *); int route_rc; - if (bl_nl_getpeername(fd, addr, len, &route_rc)) return route_rc; + if (dd_nl_getpeername(fd, addr, len, &route_rc)) return route_rc; if (real == NULL) real = dlsym(RTLD_NEXT, "getpeername"); return real(fd, addr, len); } @@ -189,7 +189,7 @@ int setsockopt(int fd, int level, int optname, const void *optval, socklen_t opt errno = ENOSYS; return -1; } - if (bl_nl_setsockopt(fd, level, optname, optval, optlen, real_setsockopt, &route_rc)) return route_rc; + if (dd_nl_setsockopt(fd, level, optname, optval, optlen, real_setsockopt, &route_rc)) return route_rc; if (is_stand_in(fd)) { if (level == SOL_NETLINK) return 0; @@ -207,7 +207,7 @@ int getsockopt(int fd, int level, int option, void *value, socklen_t *len) { errno = ENOSYS; return -1; } - if (bl_nl_getsockopt(fd, level, option, value, len, real, &route_rc)) return route_rc; + if (dd_nl_getsockopt(fd, level, option, value, len, real, &route_rc)) return route_rc; return real(fd, level, option, value, len); } @@ -249,7 +249,7 @@ static unsigned murmur_hash2(const char *key, size_t len) { return h; } -__attribute__((visibility("default"))) int bl_udevmon_inject(const char *action, const char *devpath, +__attribute__((visibility("default"))) int dd_udevmon_inject(const char *action, const char *devpath, const char *subsystem, const char *devname, unsigned major, unsigned minor) { static unsigned long long seqnum = 900000; @@ -280,7 +280,7 @@ __attribute__((visibility("default"))) int bl_udevmon_inject(const char *action, return sent; } -__attribute__((visibility("hidden"))) int bl_udevmon_recvmsg(int fd, struct msghdr *msg, int flags, +__attribute__((visibility("hidden"))) int dd_udevmon_recvmsg(int fd, struct msghdr *msg, int flags, ssize_t (*real_recvmsg)(int, struct msghdr *, int), ssize_t *result) { if (!is_stand_in(fd)) return 0; diff --git a/tools/linuxfs/preload/usr2.c b/tools/linuxfs/preload/usr2.c index a7129fdc08..3a3cfd036f 100644 --- a/tools/linuxfs/preload/usr2.c +++ b/tools/linuxfs/preload/usr2.c @@ -28,7 +28,7 @@ static int find_ntdll(struct dl_phdr_info *info, size_t size, void *data) { return 0; } -__attribute__((visibility("hidden"))) int bl_from_ntdll(const void *caller) { +__attribute__((visibility("hidden"))) int dd_from_ntdll(const void *caller) { uintptr_t pc = (uintptr_t)caller, lo = __atomic_load_n(&ntdll_lo, __ATOMIC_ACQUIRE); if (!lo) { dl_iterate_phdr(find_ntdll, NULL); @@ -42,53 +42,53 @@ __attribute__((visibility("hidden"))) int bl_from_ntdll(const void *caller) { #include #include -#define BL_STR2(x) #x -#define BL_STR(x) BL_STR2(x) +#define DD_STR2(x) #x +#define DD_STR(x) DD_STR2(x) -#define BL_HWCAP_GCS (1UL << 32) -#define BL_FRAME_SIZE 4688 -#define BL_REGS 312 -#define BL_SP 560 -#define BL_PC 568 -#define BL_PSTATE 576 -#define BL_FPSIMD 592 +#define DD_HWCAP_GCS (1UL << 32) +#define DD_FRAME_SIZE 4688 +#define DD_REGS 312 +#define DD_SP 560 +#define DD_PC 568 +#define DD_PSTATE 576 +#define DD_FPSIMD 592 -struct bl_sigframe { +struct dd_sigframe { siginfo_t info; ucontext_t uc; }; -struct bl_kernel_sigaction { +struct dd_kernel_sigaction { void (*handler)(int, siginfo_t *, void *); unsigned long flags; void *restorer; uint64_t mask; }; -struct bl_usr2_call { +struct dd_usr2_call { void (*handler)(int, siginfo_t *, void *); uint64_t old_mask; }; -_Static_assert(sizeof(struct bl_sigframe) == BL_FRAME_SIZE, "rt_sigframe size"); -_Static_assert(offsetof(struct bl_sigframe, uc.uc_mcontext.regs) == BL_REGS, "regs offset"); -_Static_assert(offsetof(struct bl_sigframe, uc.uc_mcontext.sp) == BL_SP, "sp offset"); -_Static_assert(offsetof(struct bl_sigframe, uc.uc_mcontext.pc) == BL_PC, "pc offset"); -_Static_assert(offsetof(struct bl_sigframe, uc.uc_mcontext.pstate) == BL_PSTATE, "pstate offset"); -_Static_assert(offsetof(struct bl_sigframe, uc.uc_mcontext.__reserved) == BL_FPSIMD, "reserved offset"); +_Static_assert(sizeof(struct dd_sigframe) == DD_FRAME_SIZE, "rt_sigframe size"); +_Static_assert(offsetof(struct dd_sigframe, uc.uc_mcontext.regs) == DD_REGS, "regs offset"); +_Static_assert(offsetof(struct dd_sigframe, uc.uc_mcontext.sp) == DD_SP, "sp offset"); +_Static_assert(offsetof(struct dd_sigframe, uc.uc_mcontext.pc) == DD_PC, "pc offset"); +_Static_assert(offsetof(struct dd_sigframe, uc.uc_mcontext.pstate) == DD_PSTATE, "pstate offset"); +_Static_assert(offsetof(struct dd_sigframe, uc.uc_mcontext.__reserved) == DD_FPSIMD, "reserved offset"); _Static_assert(sizeof(struct fpsimd_context) + sizeof(struct _aarch64_ctx) <= sizeof(((mcontext_t *)0)->__reserved), "reserved space"); -__attribute__((visibility("hidden"))) void bl_usr2_frame(struct bl_usr2_call *call); -__attribute__((visibility("hidden"), used)) void bl_usr2_run(struct bl_usr2_call *call, struct bl_sigframe *frame); +__attribute__((visibility("hidden"))) void dd_usr2_frame(struct dd_usr2_call *call); +__attribute__((visibility("hidden"), used)) void dd_usr2_run(struct dd_usr2_call *call, struct dd_sigframe *frame); __asm__(".text\n" ".p2align 2\n" - ".type bl_usr2_frame, %function\n" - "bl_usr2_frame:\n" - " mov x16, #" BL_STR(BL_FRAME_SIZE) "\n" + ".type dd_usr2_frame, %function\n" + "dd_usr2_frame:\n" + " mov x16, #" DD_STR(DD_FRAME_SIZE) "\n" " sub sp, sp, x16\n" - " add x17, sp, #" BL_STR(BL_REGS) "\n" + " add x17, sp, #" DD_STR(DD_REGS) "\n" " stp x0, x1, [x17, #0]\n" " stp x2, x3, [x17, #16]\n" " stp x4, x5, [x17, #32]\n" @@ -107,12 +107,12 @@ __asm__(".text\n" " str x30, [x17, #240]\n" " str xzr, [x17, #0]\n" " add x16, sp, x16\n" - " str x16, [sp, #" BL_STR(BL_SP) "]\n" + " str x16, [sp, #" DD_STR(DD_SP) "]\n" " adr x16, 1f\n" - " str x16, [sp, #" BL_STR(BL_PC) "]\n" + " str x16, [sp, #" DD_STR(DD_PC) "]\n" " mrs x16, nzcv\n" - " str x16, [sp, #" BL_STR(BL_PSTATE) "]\n" - " add x17, sp, #" BL_STR(BL_FPSIMD) "\n" + " str x16, [sp, #" DD_STR(DD_PSTATE) "]\n" + " add x17, sp, #" DD_STR(DD_FPSIMD) "\n" " mrs x16, fpsr\n" " str w16, [x17, #8]\n" " mrs x16, fpcr\n" @@ -134,13 +134,13 @@ __asm__(".text\n" " stp q28, q29, [x17, #464]\n" " stp q30, q31, [x17, #496]\n" " mov x1, sp\n" - " bl bl_usr2_run\n" - " mov x8, #" BL_STR(__NR_rt_sigreturn) "\n" + " bl dd_usr2_run\n" + " mov x8, #" DD_STR(__NR_rt_sigreturn) "\n" " svc #0\n" " brk #0\n" "1:\n" " ret\n" - ".size bl_usr2_frame, .-bl_usr2_frame\n"); + ".size dd_usr2_frame, .-dd_usr2_frame\n"); static int (*usr2_real_raise)(int); @@ -160,7 +160,7 @@ static uint64_t usr2_ssbs(void) { return value & (1UL << 12); } -void bl_usr2_run(struct bl_usr2_call *call, struct bl_sigframe *frame) { +void dd_usr2_run(struct dd_usr2_call *call, struct dd_sigframe *frame) { struct fpsimd_context *fp = (struct fpsimd_context *)frame->uc.uc_mcontext.__reserved; struct _aarch64_ctx *end = (struct _aarch64_ctx *)(fp + 1); @@ -192,11 +192,11 @@ int raise(int sig) { real = (int (*)(int))dlsym(RTLD_NEXT, "raise"); __atomic_store_n(&usr2_real_raise, real, __ATOMIC_RELEASE); } - if (sig != SIGUSR2 || (getauxval(AT_HWCAP) & BL_HWCAP_GCS) || !bl_from_ntdll(__builtin_return_address(0))) { + if (sig != SIGUSR2 || (getauxval(AT_HWCAP) & DD_HWCAP_GCS) || !dd_from_ntdll(__builtin_return_address(0))) { return real(sig); } - struct bl_kernel_sigaction action; + struct dd_kernel_sigaction action; if (usr2_sys(__NR_rt_sigaction, SIGUSR2, 0, (long)&action, sizeof(action.mask)) != 0) return real(sig); if (!(action.flags & SA_SIGINFO) || (action.flags & SA_RESETHAND) || (uintptr_t)action.handler <= 1) { return real(sig); @@ -204,7 +204,7 @@ int raise(int sig) { uint64_t bit = 1ULL << (SIGUSR2 - 1); uint64_t block = action.mask | ((action.flags & SA_NODEFER) ? 0 : bit); - struct bl_usr2_call call = {action.handler, 0}; + struct dd_usr2_call call = {action.handler, 0}; if (usr2_sys(__NR_rt_sigprocmask, SIG_BLOCK, (long)&block, (long)&call.old_mask, sizeof(block)) != 0) { return real(sig); } @@ -212,7 +212,7 @@ int raise(int sig) { usr2_sys(__NR_rt_sigprocmask, SIG_SETMASK, (long)&call.old_mask, 0, sizeof(call.old_mask)); return real(sig); } - bl_usr2_frame(&call); + dd_usr2_frame(&call); return 0; } #endif diff --git a/tools/linuxfs/preload/vdec.c b/tools/linuxfs/preload/vdec.c index 9a0abbe504..7d3761e290 100644 --- a/tools/linuxfs/preload/vdec.c +++ b/tools/linuxfs/preload/vdec.c @@ -4,7 +4,7 @@ #include #include -#if defined(__aarch64__) || defined(BL_VDEC_ANY_ARCH) +#if defined(__aarch64__) || defined(DD_VDEC_ANY_ARCH) #include #include @@ -220,12 +220,12 @@ static int vd_have_ffmpeg(void) { return vd_ffmpeg > 0; } -__attribute__((visibility("hidden"))) int bl_venc_connect(void); +__attribute__((visibility("hidden"))) int dd_venc_connect(void); static int vd_enabled(void) { pthread_mutex_lock(&vd_lock); if (vd_state == 0) { - const char *flag = getenv("BL_REMOTE_PLAY_DECODE"), *socket = getenv("BL_VENC_SOCKET"); + const char *flag = getenv("DD_REMOTE_PLAY_DECODE"), *socket = getenv("DD_VENC_SOCKET"); vd_state = -1; if (strcmp(program_invocation_short_name, "streaming_client") == 0 && (flag == NULL || strcmp(flag, "0") != 0)) { vd_heap = open("/dev/dma_heap/system", O_RDONLY | O_CLOEXEC); @@ -245,7 +245,7 @@ static struct vdec *vd_find(int fd) { return NULL; } -__attribute__((visibility("hidden"))) int bl_vdec_open(const char *path, int flags) { +__attribute__((visibility("hidden"))) int dd_vdec_open(const char *path, int flags) { (void)flags; if (path == NULL || strcmp(path, VDEC_DEVICE) != 0 || !vd_enabled()) return -2; int fd = memfd_create("droiddeck-vdec", 0); @@ -314,7 +314,7 @@ static void vd_send_capture(struct vdec *v, uint32_t index) { static int vd_open_hardware(struct vdec *v) { if (v->hw_failed) return -1; - int sock = bl_venc_connect(); + int sock = dd_venc_connect(); if (sock < 0) return -1; struct vdec_config c = { .type = VDEC_CONFIG, .codec = v->fourcc == V4L2_PIX_FMT_HEVC ? VENC_HEVC : VENC_H264, @@ -740,7 +740,7 @@ static int vd_ioctl(struct vdec *v, unsigned long req, void *arg) { } } -__attribute__((visibility("hidden"))) int bl_vdec_ioctl(int fd, unsigned long req, void *arg, int *rc) { +__attribute__((visibility("hidden"))) int dd_vdec_ioctl(int fd, unsigned long req, void *arg, int *rc) { struct vdec *v = vd_find(fd); if (v == NULL) return 0; pthread_mutex_lock(&vd_lock); @@ -755,7 +755,7 @@ __attribute__((visibility("hidden"))) int bl_vdec_ioctl(int fd, unsigned long re return 1; } -__attribute__((visibility("hidden"))) void bl_vdec_closed(int fd) { +__attribute__((visibility("hidden"))) void dd_vdec_closed(int fd) { struct vdec *v = vd_find(fd); if (v == NULL) return; pthread_mutex_lock(&vd_lock); @@ -768,7 +768,7 @@ __attribute__((visibility("hidden"))) void bl_vdec_closed(int fd) { pthread_mutex_unlock(&vd_lock); } -__attribute__((visibility("hidden"))) int bl_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms, +__attribute__((visibility("hidden"))) int dd_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms, int (*real)(struct pollfd *, nfds_t, int), int *ret) { if (n != 1 || vd_find(fds[0].fd) == NULL) return 0; struct vdec *v = vd_find(fds[0].fd); @@ -949,13 +949,13 @@ void SDL_UnloadObject(void *handle) { #else -__attribute__((visibility("hidden"))) int bl_vdec_open(const char *path, int flags) { +__attribute__((visibility("hidden"))) int dd_vdec_open(const char *path, int flags) { (void)path; (void)flags; return -2; } -__attribute__((visibility("hidden"))) int bl_vdec_ioctl(int fd, unsigned long req, void *arg, int *rc) { +__attribute__((visibility("hidden"))) int dd_vdec_ioctl(int fd, unsigned long req, void *arg, int *rc) { (void)fd; (void)req; (void)arg; @@ -963,9 +963,9 @@ __attribute__((visibility("hidden"))) int bl_vdec_ioctl(int fd, unsigned long re return 0; } -__attribute__((visibility("hidden"))) void bl_vdec_closed(int fd) { (void)fd; } +__attribute__((visibility("hidden"))) void dd_vdec_closed(int fd) { (void)fd; } -__attribute__((visibility("hidden"))) int bl_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms, +__attribute__((visibility("hidden"))) int dd_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms, int (*real)(struct pollfd *, nfds_t, int), int *ret) { (void)fds; (void)n; diff --git a/tools/linuxfs/preload/venc.c b/tools/linuxfs/preload/venc.c index 92c60c3bff..63480b8146 100644 --- a/tools/linuxfs/preload/venc.c +++ b/tools/linuxfs/preload/venc.c @@ -115,14 +115,14 @@ static void vn_free_queue(struct vq *q) { memset(q, 0, sizeof *q); } -__attribute__((visibility("hidden"))) int bl_venc_streaming(void) { +__attribute__((visibility("hidden"))) int dd_venc_streaming(void) { return __atomic_load_n(&vn_open_count, __ATOMIC_ACQUIRE) > 0; } -__attribute__((visibility("hidden"))) int bl_venc_connect(void); +__attribute__((visibility("hidden"))) int dd_venc_connect(void); -int bl_venc_connect(void) { - const char *path = getenv("BL_VENC_SOCKET"); +int dd_venc_connect(void) { + const char *path = getenv("DD_VENC_SOCKET"); if (path == NULL || *path == '\0') return -1; struct sockaddr_un addr = { .sun_family = AF_UNIX }; if (strlen(path) >= sizeof addr.sun_path) return -1; @@ -138,10 +138,10 @@ int bl_venc_connect(void) { return fd; } -__attribute__((visibility("hidden"))) int bl_venc_open(const char *path, int flags) { +__attribute__((visibility("hidden"))) int dd_venc_open(const char *path, int flags) { (void)flags; if (path == NULL || strcmp(path, VENC_DEVICE) != 0) return -2; - int fd = bl_venc_connect(); + int fd = dd_venc_connect(); if (fd < 0) return -2; pthread_mutex_lock(&vn_lock); struct venc *v = NULL; @@ -546,7 +546,7 @@ static int vn_ioctl(struct venc *v, unsigned long req, void *arg) { } } -__attribute__((visibility("hidden"))) int bl_venc_ioctl(int fd, unsigned long req, void *arg, int *rc) { +__attribute__((visibility("hidden"))) int dd_venc_ioctl(int fd, unsigned long req, void *arg, int *rc) { struct venc *v = vn_find(fd); if (v == NULL) return 0; pthread_mutex_lock(&vn_lock); @@ -561,7 +561,7 @@ __attribute__((visibility("hidden"))) int bl_venc_ioctl(int fd, unsigned long re return 1; } -__attribute__((visibility("hidden"))) int bl_venc_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off, +__attribute__((visibility("hidden"))) int dd_venc_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off, void *(*real)(void *, size_t, int, int, int, off_t), void **out) { struct venc *v = vn_find(fd); if (v == NULL) return 0; @@ -579,7 +579,7 @@ __attribute__((visibility("hidden"))) int bl_venc_mmap(void *addr, size_t len, i return 1; } -__attribute__((visibility("hidden"))) void bl_venc_closed(int fd) { +__attribute__((visibility("hidden"))) void dd_venc_closed(int fd) { struct venc *v = vn_find(fd); if (v == NULL) return; pthread_mutex_lock(&vn_lock); @@ -623,14 +623,14 @@ static int vn_poll(struct pollfd *fds, nfds_t n, int timeout_ms, int (*real)(str return r + ready; } -__attribute__((weak, visibility("hidden"))) int bl_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms, +__attribute__((weak, visibility("hidden"))) int dd_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms, int (*real)(struct pollfd *, nfds_t, int), int *ret); int poll(struct pollfd *fds, nfds_t n, int timeout_ms) { static int (*real)(struct pollfd *, nfds_t, int); if (!real) real = (int (*)(struct pollfd *, nfds_t, int))dlsym(RTLD_NEXT, "poll"); int ret; - if (bl_vdec_poll && bl_vdec_poll(fds, n, timeout_ms, real, &ret)) return ret; + if (dd_vdec_poll && dd_vdec_poll(fds, n, timeout_ms, real, &ret)) return ret; if (__atomic_load_n(&vn_open_count, __ATOMIC_ACQUIRE) == 0) return real(fds, n, timeout_ms); return vn_poll(fds, n, timeout_ms, real); } diff --git a/tools/linuxfs/preload/venus.c b/tools/linuxfs/preload/venus.c index aae9ebbec2..9f76ad9a73 100644 --- a/tools/linuxfs/preload/venus.c +++ b/tools/linuxfs/preload/venus.c @@ -14,7 +14,7 @@ extern char **environ; -__attribute__((constructor)) static void bl_venus_keep_kopper(void) { +__attribute__((constructor)) static void dd_venus_keep_kopper(void) { static const char name[] = "LIBGL_KOPPER_DISABLE="; const char *debug = getenv("VN_DEBUG"); if (!debug || !strstr(debug, "vtest") || !environ) return; diff --git a/tools/linuxfs/preload/webhelper.c b/tools/linuxfs/preload/webhelper.c index 7642a34632..81aba8e8a5 100644 --- a/tools/linuxfs/preload/webhelper.c +++ b/tools/linuxfs/preload/webhelper.c @@ -57,10 +57,10 @@ static char *const *chromium_argv(const char *path, char *const argv[]) { } __attribute__((visibility("hidden"))) -char *const *bl_webhelper_argv(const char *path, char *const argv[], char *const envp[]) { +char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]) { if (electron_node_mode(envp)) return argv; if (!is_webhelper_browser(path, argv)) return chromium_argv(path, argv); - const char *spec = getenv("BL_WEBHELPER_ARGS"); + const char *spec = getenv("DD_WEBHELPER_ARGS"); if (!spec || !*spec) spec = WEBHELPER_DEFAULT; if (!strcmp(spec, "stock")) return argv; diff --git a/tools/linuxfs/preload/writewatch.c b/tools/linuxfs/preload/writewatch.c index b804e3f39c..eb1810f172 100644 --- a/tools/linuxfs/preload/writewatch.c +++ b/tools/linuxfs/preload/writewatch.c @@ -18,7 +18,7 @@ static int ww_uffd = -1; static int scan_blocked; #endif -__attribute__((visibility("hidden"))) int bl_writewatch_syscall(long number, const long *args, long (*real)(long, ...), long *rc) { +__attribute__((visibility("hidden"))) int dd_writewatch_syscall(long number, const long *args, long (*real)(long, ...), long *rc) { #if defined(__aarch64__) && defined(PAGEMAP_SCAN) && defined(UFFD_USER_MODE_ONLY) if (number != WINE_ARM64_USERFAULTFD || (args[0] & ~(long)(O_CLOEXEC | O_NONBLOCK | UFFD_USER_MODE_ONLY))) return 0; *rc = real(SYS_userfaultfd, args[0]); @@ -89,7 +89,7 @@ done: } #endif -__attribute__((visibility("hidden"))) int bl_writewatch_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request, +__attribute__((visibility("hidden"))) int dd_writewatch_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request, void *arg, int *rc) { #if defined(PAGEMAP_SCAN) && defined(UFFD_USER_MODE_ONLY) if (request != PAGEMAP_SCAN) return 0; diff --git a/tools/linuxfs/preload/xmode.c b/tools/linuxfs/preload/xmode.c index e6842d73ab..2d6d1c690b 100644 --- a/tools/linuxfs/preload/xmode.c +++ b/tools/linuxfs/preload/xmode.c @@ -15,7 +15,7 @@ typedef Atom (*intern_atom_fn)(Display *, const char *, Bool); static int following(void) { static int cached = -1; if (cached < 0) { - const char *v = getenv("BL_FOLLOW_OUTPUT"); + const char *v = getenv("DD_FOLLOW_OUTPUT"); cached = v && v[0] == '1'; } return cached; diff --git a/tools/linuxfs/preload/zram.c b/tools/linuxfs/preload/zram.c index af62c29413..177fe8efef 100644 --- a/tools/linuxfs/preload/zram.c +++ b/tools/linuxfs/preload/zram.c @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -16,15 +17,18 @@ #define MADV_PAGEOUT 21 #endif #ifndef ZR_CTL -#define ZR_CTL "/tmp/.bl-zram" +#define ZR_CTL "/tmp/.dd-zram" #endif #define ZR_SWAPPED (1ULL << 62) #define ZR_BATCH 512 +#define ZR_FUTEX_WAIT 0 +#define ZR_FUTEX_WAKE 1 static long (*zr_sys)(long, ...); static unsigned long zr_page; static int zr_busy; static int zr_pending; +static int zr_worker; static char zr_maps[8192]; static uint64_t zr_entries[ZR_BATCH]; static struct iovec zr_iov[ZR_BATCH]; @@ -143,19 +147,36 @@ static void zr_ack(int done) { zr_sys(SYS_close, fd); } +static void zr_request(void) { + int mode = zr_mode(); + if (mode == 1) zr_ack(0); + if (mode >= 0) zr_walk(mode); + if (mode == 1) zr_ack(1); +} + +static void *zr_worker_main(void *unused) { + (void)unused; + prctl(PR_SET_NAME, "zr-worker", 0, 0, 0); + for (;;) { + while (!__atomic_exchange_n(&zr_pending, 0, __ATOMIC_SEQ_CST)) + zr_sys(SYS_futex, &zr_pending, ZR_FUTEX_WAIT, 0, NULL, NULL, 0); + zr_request(); + } + return NULL; +} + static void zr_handler(int sig, siginfo_t *info, void *context) { (void)sig; (void)context; if (info == NULL || info->si_code != SI_USER) return; int saved = errno; __atomic_store_n(&zr_pending, 1, __ATOMIC_SEQ_CST); - while (__atomic_load_n(&zr_pending, __ATOMIC_SEQ_CST) - && !__atomic_exchange_n(&zr_busy, 1, __ATOMIC_SEQ_CST)) { + if (__atomic_load_n(&zr_worker, __ATOMIC_ACQUIRE)) { + zr_sys(SYS_futex, &zr_pending, ZR_FUTEX_WAKE, 1, NULL, NULL, 0); + } else while (__atomic_load_n(&zr_pending, __ATOMIC_SEQ_CST) + && !__atomic_exchange_n(&zr_busy, 1, __ATOMIC_SEQ_CST)) { __atomic_store_n(&zr_pending, 0, __ATOMIC_SEQ_CST); - int mode = zr_mode(); - if (mode == 1) zr_ack(0); - if (mode >= 0) zr_walk(mode); - if (mode == 1) zr_ack(1); + zr_request(); __atomic_store_n(&zr_busy, 0, __ATOMIC_SEQ_CST); } errno = saved; @@ -164,6 +185,7 @@ static void zr_handler(int sig, siginfo_t *info, void *context) { static void zr_child(void) { __atomic_store_n(&zr_busy, 0, __ATOMIC_SEQ_CST); __atomic_store_n(&zr_pending, 0, __ATOMIC_SEQ_CST); + __atomic_store_n(&zr_worker, 0, __ATOMIC_RELEASE); } __attribute__((constructor)) static void zr_init(void) { @@ -184,5 +206,21 @@ __attribute__((constructor)) static void zr_init(void) { sa.sa_sigaction = zr_handler; sa.sa_flags = SA_SIGINFO | SA_RESTART; sigemptyset(&sa.sa_mask); - if (sigaction(SIGURG, &sa, NULL) == 0) pthread_atfork(NULL, NULL, zr_child); + if (sigaction(SIGURG, &sa, NULL) == 0) { + pthread_atfork(NULL, NULL, zr_child); + pthread_attr_t attr; + if (pthread_attr_init(&attr) == 0) { + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); + pthread_t thread; + sigset_t blocked; + sigset_t previous; + if (sigfillset(&blocked) == 0 && + pthread_sigmask(SIG_SETMASK, &blocked, &previous) == 0) { + if (pthread_create(&thread, &attr, zr_worker_main, NULL) == 0) + __atomic_store_n(&zr_worker, 1, __ATOMIC_RELEASE); + pthread_sigmask(SIG_SETMASK, &previous, NULL); + } + pthread_attr_destroy(&attr); + } + } } diff --git a/tools/mangoapp/mangoapp b/tools/mangoapp/mangoapp index 755a7e44da..deb44bbb0a 100644 --- a/tools/mangoapp/mangoapp +++ b/tools/mangoapp/mangoapp @@ -8,10 +8,10 @@ if [ "$(wc -l < "$starts")" -gt 5 ]; then echo "mangoapp: started $(wc -l < "$starts") times in 60 s; the performance overlay stays off for this session" >&2 exec sleep infinity fi -# The system PowerVR route (BL_POWERVR_RENDER_NODE): Zink could not make mangoapp a swapchain there +# The system PowerVR route (DD_POWERVR_RENDER_NODE): Zink could not make mangoapp a swapchain there # ("zink: could not create swapchain", then GLXBadCurrentWindow) and it crashed at every start. The # overlay is a few text lines: llvmpipe draws it. -if [ -n "${BL_POWERVR_RENDER_NODE:-}" ]; then +if [ -n "${DD_POWERVR_RENDER_NODE:-}" ]; then export GALLIUM_DRIVER=llvmpipe LIBGL_ALWAYS_SOFTWARE=1 unset MESA_LOADER_DRIVER_OVERRIDE LIBGL_KOPPER_DRI2 fi diff --git a/tools/nativeguest/hook/fileops.c b/tools/nativeguest/hook/fileops.c index 9ee7976505..2632f0eefb 100644 --- a/tools/nativeguest/hook/fileops.c +++ b/tools/nativeguest/hook/fileops.c @@ -423,6 +423,9 @@ ssize_t readlink(const char *pathname, char *buf, size_t bufsiz) { if (is_proc_self_exe(pathname)) { ssize_t exe_len = handle_proc_self_exe(buf, bufsiz); if (exe_len >= 0) return exe_len; + } else { + ssize_t exe_len = handle_proc_other_exe(pathname, buf, bufsiz); + if (exe_len >= 0) return exe_len; } static ssize_t (*orig_readlink)(const char *, char *, size_t) = NULL; if (!orig_readlink) orig_readlink = (ssize_t (*)(const char *, char *, size_t))dlsym(RTLD_NEXT, "readlink"); @@ -443,9 +446,16 @@ ssize_t readlinkat(int dirfd, const char *pathname, char *buf, size_t bufsiz) { if (!orig_readlinkat) orig_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat"); DDNATV_AT_REMAP(dirfd, pathname); // after the remap: "proc/self/exe" relative to a descriptor for "/" is /proc/self/exe as well + { + ssize_t exe_len = handle_proc_exe_at(dirfd, pathname, buf, bufsiz); + if (exe_len >= 0) return exe_len; + } if (is_proc_self_exe(pathname)) { ssize_t exe_len = handle_proc_self_exe(buf, bufsiz); if (exe_len >= 0) return exe_len; + } else { + ssize_t exe_len = handle_proc_other_exe(pathname, buf, bufsiz); + if (exe_len >= 0) return exe_len; } char pbuf[PATH_MAX]; const char *target = (pathname && pathname[0] == '/') ? rewrite_path(pathname, pbuf, sizeof(pbuf)) : pathname; diff --git a/tools/nativeguest/hook/privileged.c b/tools/nativeguest/hook/privileged.c index 6b527ae4f3..7bf0a8b692 100644 --- a/tools/nativeguest/hook/privileged.c +++ b/tools/nativeguest/hook/privileged.c @@ -609,7 +609,7 @@ long syscall(long number, ...) { #ifdef __NR_close_range if (number == __NR_close_range) { - // libblsession's close_range() calls syscall() again: the nested call goes straight to the kernel + // libddsession's close_range() calls syscall() again: the nested call goes straight to the kernel if (t_syscall_redirect) return call_orig_syscall(number, arg1, arg2, arg3, 0, 0, 0); t_syscall_redirect++; long ret = (long)close_range((unsigned int)arg1, (unsigned int)arg2, (int)arg3); @@ -620,7 +620,7 @@ long syscall(long number, ...) { #ifdef __NR_openat2 if (number == __NR_openat2) { - // libblsession's openat2() calls syscall() again (an endless loop until the stack ran out): the nested + // libddsession's openat2() calls syscall() again (an endless loop until the stack ran out): the nested // call maps the path and goes straight to the kernel if (t_syscall_redirect) { char nested_buf[PATH_MAX]; diff --git a/tools/nativeguest/hook/setup.c b/tools/nativeguest/hook/setup.c index b217bd4b45..24f8a81317 100644 --- a/tools/nativeguest/hook/setup.c +++ b/tools/nativeguest/hook/setup.c @@ -165,64 +165,188 @@ static int is_proc_self_exe(const char *path) { return 0; } +static void exe_from_cmdline(const char *cmdline_path, char *out, size_t outsz) { + int fd = open(cmdline_path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return; + char cmdline[8192]; + ssize_t n = read(fd, cmdline, sizeof(cmdline) - 1); + close(fd); + if (n <= 0) return; + cmdline[n] = '\0'; + char *args[64] = {0}; + int ac = 0; + char *p = cmdline; + while (p < cmdline + n && ac < 64) { + args[ac++] = p; + p += strlen(p) + 1; + } + for (int i = 0; i < ac; i++) { + if (strcmp(args[i], "--argv0") == 0 && i + 2 < ac) { + ddnatv_copy_cstr(out, outsz, args[i + 2]); + return; + } + } + if (ac > 0 && args[0] && args[0][0] != '\0') ddnatv_copy_cstr(out, outsz, args[0]); +} + +static ssize_t copy_guest_exe(const char *real_exe, char *buf, size_t bufsiz) { + const char *out_path = real_exe; + if (g_ddnatv_root[0] != '\0') { + size_t rlen = g_ddnatv_root_len; + if (strncmp(real_exe, g_ddnatv_root, rlen) == 0 && + (real_exe[rlen] == '/' || real_exe[rlen] == '\0')) { + out_path = real_exe + rlen; + if (out_path[0] == '\0') out_path = "/"; + } + } + size_t len = strlen(out_path); + size_t copy_len = (len < bufsiz) ? len : bufsiz; + memcpy(buf, out_path, copy_len); + return (ssize_t)copy_len; +} + static ssize_t handle_proc_self_exe(char *buf, size_t bufsiz) { if (!buf || bufsiz == 0) { errno = EINVAL; return -1; } init_ddnatv_hook(); - if (g_real_exe[0] == '\0') { - int fd = open("/proc/self/cmdline", O_RDONLY); - if (fd >= 0) { - char cmdline[8192]; - ssize_t n = read(fd, cmdline, sizeof(cmdline) - 1); - close(fd); - if (n > 0) { - cmdline[n] = '\0'; - char *args[64] = {0}; - int ac = 0; - char *p = cmdline; - while (p < cmdline + n && ac < 64) { - args[ac++] = p; - p += strlen(p) + 1; - } - for (int i = 0; i < ac; i++) { - if (strcmp(args[i], "--argv0") == 0 && i + 2 < ac) { - strncpy(g_real_exe, args[i + 2], sizeof(g_real_exe) - 1); - g_real_exe[sizeof(g_real_exe) - 1] = '\0'; - break; - } - } - if (g_real_exe[0] == '\0' && ac > 0 && args[0] && args[0][0] != '\0') { - strncpy(g_real_exe, args[0], sizeof(g_real_exe) - 1); - g_real_exe[sizeof(g_real_exe) - 1] = '\0'; - } - } - } - } - - if (g_real_exe[0] != '\0') { - char stripped[PATH_MAX]; - const char *out_path = g_real_exe; - if (g_ddnatv_root[0] != '\0') { - size_t rlen = g_ddnatv_root_len; - if (strncmp(g_real_exe, g_ddnatv_root, rlen) == 0 && - (g_real_exe[rlen] == '/' || g_real_exe[rlen] == '\0')) { - out_path = g_real_exe + rlen; - if (out_path[0] == '\0') out_path = "/"; - } - } - strncpy(stripped, out_path, sizeof(stripped) - 1); - stripped[sizeof(stripped) - 1] = '\0'; - - size_t len = strlen(stripped); - size_t copy_len = (len < bufsiz) ? len : bufsiz; - memcpy(buf, stripped, copy_len); - return (ssize_t)copy_len; - } + if (g_real_exe[0] == '\0') exe_from_cmdline("/proc/self/cmdline", g_real_exe, sizeof(g_real_exe)); + if (g_real_exe[0] != '\0') return copy_guest_exe(g_real_exe, buf, bufsiz); return -1; } +static int is_ld_linux(const char *path); + +static ssize_t (*real_readlinkat_fn(void))(int, const char *, char *, size_t) { + static ssize_t (*fn)(int, const char *, char *, size_t) = NULL; + if (!fn) fn = (ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat"); + return fn; +} + +static int proc_env_value(pid_t pid, const char *key, char *out, size_t outsz) { + char path[64]; + snprintf(path, sizeof(path), "/proc/%d/environ", (int)pid); + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return 0; + size_t cap = 65536, used = 0, keylen = strlen(key); + char *env = malloc(cap + 1); + ssize_t got; + while (env && (got = read(fd, env + used, cap - used)) > 0) { + used += (size_t)got; + if (used == cap) { + char *bigger = cap < (8u << 20) ? realloc(env, cap * 2 + 1) : NULL; + if (!bigger) break; + env = bigger; + cap *= 2; + } + } + close(fd); + int found = 0; + if (env) { + env[used] = '\0'; + for (char *e = env; e < env + used; e += strlen(e) + 1) { + if (strncmp(e, key, keylen) == 0 && e[keylen] == '=' && e[keylen + 1] != '\0') { + ddnatv_copy_cstr(out, outsz, e + keylen + 1); + found = 1; + break; + } + } + free(env); + } + return found; +} + +// Overlay filesystems report a different device to stat() than in /proc//maps; the path, as the +// kernel resolved it, then stands in for the device. +static int proc_maps_file(pid_t pid, dev_t dev, ino_t ino, const char *resolved) { + char path[64]; + snprintf(path, sizeof(path), "/proc/%d/maps", (int)pid); + int fd = open(path, O_RDONLY | O_CLOEXEC); + if (fd < 0) return 0; + char chunk[4096], line[1024]; + size_t len = 0; + ssize_t got; + int found = 0; + while (!found && (got = read(fd, chunk, sizeof(chunk))) > 0) { + for (ssize_t i = 0; i < got && !found; i++) { + if (chunk[i] != '\n') { + if (len < sizeof(line) - 1) line[len++] = chunk[i]; + continue; + } + line[len] = '\0'; + len = 0; + unsigned long long offset, inode; + unsigned int major_nr, minor_nr; + int name_at = 0; + if (sscanf(line, "%*s %*s %llx %x:%x %llu %n", &offset, &major_nr, &minor_nr, &inode, &name_at) == 4 && + offset == 0 && inode == (unsigned long long)ino && + (makedev(major_nr, minor_nr) == dev || (resolved && name_at > 0 && strcmp(line + name_at, resolved) == 0))) { + found = 1; + } + } + } + close(fd); + return found; +} + +// The kernel's /proc//exe of every other guest program is the loader that started it. KWin +// grants privileged Wayland interfaces by matching that path to a desktop file's Exec, so it is the +// program the loader runs, as for the calling process. A process can set its environment and +// arguments, so the program they name counts only if that process has the file mapped from its start. +static ssize_t handle_proc_other_exe(const char *path, char *buf, size_t bufsiz) { + if (!path || !buf || bufsiz == 0 || strncmp(path, "/proc/", 6) != 0) return -1; + const char *p = path + 6; + if (*p < '1' || *p > '9') return -1; + while (*p >= '0' && *p <= '9') p++; + if (strcmp(p, "/exe") != 0) return -1; + pid_t pid = (pid_t)atoi(path + 6); + if (pid == getpid()) return -1; + init_ddnatv_hook(); + if (g_ddnatv_root[0] == '\0') return -1; + ssize_t (*real_readlinkat)(int, const char *, char *, size_t) = real_readlinkat_fn(); + static int (*real_fstatat)(int, const char *, struct stat *, int) = NULL; + if (!real_fstatat) real_fstatat = (int (*)(int, const char *, struct stat *, int))dlsym(RTLD_NEXT, "fstatat"); + if (!real_readlinkat || !real_fstatat) return -1; + char loader[PATH_MAX]; + ssize_t n = real_readlinkat(AT_FDCWD, path, loader, sizeof(loader) - 1); + if (n <= 0) return -1; + loader[n] = '\0'; + const char *base = strrchr(loader, '/'); + base = base ? base + 1 : loader; + if (strcmp(base, "libddexec.so") != 0 && !is_ld_linux(loader)) return -1; + + char real_exe[PATH_MAX] = ""; + if (!proc_env_value(pid, "DDNATV_REAL_EXE", real_exe, sizeof(real_exe))) { + char cmdline[64]; + snprintf(cmdline, sizeof(cmdline), "/proc/%d/cmdline", (int)pid); + exe_from_cmdline(cmdline, real_exe, sizeof(real_exe)); + } + static char *(*real_realpath)(const char *, char *) = NULL; + if (!real_realpath) real_realpath = (char *(*)(const char *, char *))dlsym(RTLD_NEXT, "realpath"); + struct stat st; + char resolved[PATH_MAX]; + if (real_exe[0] != '/' || real_fstatat(AT_FDCWD, real_exe, &st, 0) != 0) return -1; + if (!real_realpath || !real_realpath(real_exe, resolved)) resolved[0] = '\0'; + if (!proc_maps_file(pid, st.st_dev, st.st_ino, resolved[0] ? resolved : NULL)) return -1; + return copy_guest_exe(real_exe, buf, bufsiz); +} + +// readlinkat(>, "exe"), as the absolute path would be answered. +static ssize_t handle_proc_exe_at(int dirfd, const char *pathname, char *buf, size_t bufsiz) { + if (!pathname || pathname[0] == '/' || dirfd == AT_FDCWD || strcmp(pathname, "exe") != 0) return -1; + ssize_t (*real_readlinkat)(int, const char *, char *, size_t) = real_readlinkat_fn(); + if (!real_readlinkat) return -1; + char link[64], dir[PATH_MAX], full[PATH_MAX]; + snprintf(link, sizeof(link), "/proc/self/fd/%d", dirfd); + ssize_t n = real_readlinkat(AT_FDCWD, link, dir, sizeof(dir) - 1); + if (n <= 0) return -1; + dir[n] = '\0'; + if (strncmp(dir, "/proc/", 6) != 0 || snprintf(full, sizeof(full), "%s/exe", dir) >= (int)sizeof(full)) return -1; + if (is_proc_self_exe(full)) return handle_proc_self_exe(buf, bufsiz); + return handle_proc_other_exe(full, buf, bufsiz); +} + static const char *rewrite_path(const char *path, char *buffer, size_t bufsize) { if (!path) return NULL; // Relative paths must NEVER be rewritten to rootfs root diff --git a/tools/proot/PATCHES.md b/tools/proot/PATCHES.md index 7593ff6a9e..e7fc6d4adb 100644 --- a/tools/proot/PATCHES.md +++ b/tools/proot/PATCHES.md @@ -99,9 +99,15 @@ Added by DroidDeck: `get_robust_list`. proot still answers the first with `ENOSYS` but keeps the head each thread offered (cleared on `execve`, none in a new task), and answers the second for the calling thread with it. SteamVR's `vrclient.so` asks for the head through libc's `syscall()`, which - `libblsession.so`'s robust.c never sees: `libopenvr_api.so` opens it `RTLD_DEEPBIND`. Steam + `libddsession.so`'s robust.c never sees: `libopenvr_api.so` opens it `RTLD_DEEPBIND`. Steam aborted on "futex robust_list not initialized by pthreads" as soon as SteamVR was registered. +- `0029-proc-pid-root-guest.patch` - `/proc//root` of a tracee resolved to the rootfs's host + path, which does not exist inside the guest, so opening it failed with `ENOENT`. It now reads + as `/`, like `exe` and `cwd` read as guest paths. xdg-desktop-portal opens it for every caller to + tell sandboxed apps from host ones, so every portal request failed with "Unable to open + /proc//root", Sunshine's screen capture included. + Prototype (inert unless `PROOT_FASTPATH` is set; see `docs/development/proot-performance.md`): - `0014-fastpath-trampoline.patch` - with `PROOT_FASTPATH`, every `SECCOMP_RET_TRACE` in the filter diff --git a/tools/proot/patches/0029-proc-pid-root-guest.patch b/tools/proot/patches/0029-proc-pid-root-guest.patch new file mode 100644 index 0000000000..c1d1821071 --- /dev/null +++ b/tools/proot/patches/0029-proc-pid-root-guest.patch @@ -0,0 +1,11 @@ +--- a/src/path/proc.c ++++ b/src/path/proc.c +@@ -112,7 +112,7 @@ + * of tracee->???. */ + SUBSTITUTE(exe, known_tracee->exe); + SUBSTITUTE(cwd, known_tracee->fs->cwd); +- SUBSTITUTE(root, get_root(known_tracee)); ++ SUBSTITUTE(root, "/"); + #undef SUBSTITUTE + return DEFAULT; + diff --git a/tools/release/runtime_inputs.py b/tools/release/runtime_inputs.py index e2c11b6d43..16d4c9342c 100644 --- a/tools/release/runtime_inputs.py +++ b/tools/release/runtime_inputs.py @@ -79,13 +79,13 @@ def required(): paths = ['assets/graphics_driver/adrenotools-turnip25.1.0-quest1.tzst'] paths += [f'assets/graphics_driver/adrenotools-{name}.tzst' for name in ['turnip26.3.0-a6xx', 'turnip26.3.0-quest2']] - paths += ['assets/linuxfs/' + name for name in ['libfakeinput.so', 'libblsession.so', - 'libblfastpath.so', 'libddnatv-hook.so', 'libssbs.so', 'usr/local/bin/droiddeck-clipboard', + paths += ['assets/linuxfs/' + name for name in ['libfakeinput.so', 'libddsession.so', + 'libddfastpath.so', 'libddnatv-hook.so', 'libssbs.so', 'usr/local/bin/droiddeck-clipboard', 'usr/local/bin/droiddeck-gog-maintenance', 'usr/local/bin/gamescope', 'usr/local/lib/droiddeck/uruntime', 'usr/local/lib/droiddeck-pipewire.tzst']] for arch in ['x86_64', 'i386']: - paths += ['assets/linuxfs/' + arch + '/' + lib for lib in ['libfakeinput.so', 'libblsession.so']] + paths += ['assets/linuxfs/' + arch + '/' + lib for lib in ['libfakeinput.so', 'libddsession.so']] paths += ['assets/linuxfs/x86_64/' + lib for lib in ['libfaultreport.so', 'libvulkan-thunk.so', 'libwebkitinput.so']] paths += ['assets/linuxfs/i386/libfaultreport.so'] diff --git a/tools/release/sign-apk.sh b/tools/release/sign-apk.sh index 15fbb4e33c..0373e80ee5 100755 --- a/tools/release/sign-apk.sh +++ b/tools/release/sign-apk.sh @@ -29,7 +29,7 @@ else "$P=$pkg" "$P.androidx-startup=$pkg.androidx-startup" "$P.logs=$pkg.logs" \ "$P.pairingguide=$pkg.pairingguide" "$P.devicecode=$pkg.devicecode" "$P.pin=$pkg.pin" \ "$P.documents=$pkg.documents" "$P.home=$pkg.home" "$P.agent=$pkg.agent" \ - "$P.vr_recovery=$pkg.vr_recovery" "$P.dualscreen=$pkg.dualscreen" "$P.typing=$pkg.typing" \ + "$P.vr_recovery=$pkg.vr_recovery" "$P.dualscreen=$pkg.dualscreen" "$P.typing=$pkg.typing" "$P.keeptop=$pkg.keeptop" \ "$P.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION=$pkg.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION" fi got=$("$BUILD_TOOLS/aapt" dump badging "$work/renamed.apk" | sed -n "s/^package: name='\([^']*\)'.*/\1/p") diff --git a/tools/rockstar-launcher/README.md b/tools/rockstar-launcher/README.md index 62ae5642e6..020e21dcb7 100644 --- a/tools/rockstar-launcher/README.md +++ b/tools/rockstar-launcher/README.md @@ -6,7 +6,7 @@ The handoff is mode 0600, expires after 90 seconds and is deleted before startin GTA III, Vice City and San Andreas use body-length MTLX replies. GTA IV and L.A. Noire use total-length, terminated replies. Titles with installed Social Club metadata or SDK binaries use the SDK IPC adapter, including user-info, login, ticket, initialization and authorized title-state synchronization. The title metadata supplies the ROS identity and principal executable; it is checked against Rockstar's catalog before title authorization. Other titles retain Play and Steam shortcuts and attempt the normal executable launch path. -The SDK runtime is extracted from the game's own Social-Club-Setup.exe when present. Architecture-specific payloads are staged into the prefix, archive paths and sizes are checked, interrupted copies are retried, and both registry views are registered. The helper discovers launcher identity pipe names in the game executable and answers bounded INIT challenges from the launched process. No vendor executables or runtime files are bundled with this tool. SDK initialization has a 90-second deadline. SDK wire tests and fixture clients do not establish gameplay compatibility for every title; per-title ROS ticket exchange and secondary SDK channels remain unverified. +The SDK runtime is extracted from the game's own Social-Club-Setup.exe when present. Architecture-specific payloads are staged into the prefix, archive paths and sizes are checked, interrupted copies are retried, and both registry views are registered. The helper discovers launcher identity pipe names in the game executable and the executables beside it, because protected game executables resolve that name only at run time, and answers bounded INIT challenges from the launched process. No vendor executables or runtime files are bundled with this tool. SDK initialization has a 90-second deadline. SDK wire tests and fixture clients do not establish gameplay compatibility for every title; per-title ROS ticket exchange and secondary SDK channels remain unverified. GTA III defaults to full x87 precision for FEX before Wine starts, because reduced precision crashed new-game initialization on the test device. San Andreas defaults to WineD3D, because DXVK intermittently corrupted its textures; full precision and conservative memory ordering did not prevent that corruption. These defaults use DroidDeck's per-game settings and preserve explicit per-game overrides. diff --git a/tools/rockstar-launcher/src/identity.rs b/tools/rockstar-launcher/src/identity.rs index 795d56da1a..b059787b0d 100644 --- a/tools/rockstar-launcher/src/identity.rs +++ b/tools/rockstar-launcher/src/identity.rs @@ -1,5 +1,7 @@ -use std::collections::BTreeSet; +use std::collections::BTreeMap; +use std::fs::{self, File}; use std::io::{self, Read}; +use std::path::{Path, PathBuf}; const LIMIT: usize = 4096; @@ -10,7 +12,13 @@ fn invalid() -> io::Error { ) } -fn collect(bytes: &[u8], names: &mut BTreeSet) { +type Names = BTreeMap; + +const SCAN_LIMIT: u64 = 256 * 1024 * 1024; +const NAME_LIMIT: usize = 4; +const SIBLING_LIMIT: usize = 32; + +fn collect(bytes: &[u8], names: &mut Names) { let prefix = br"\\.\pipe\"; for (index, window) in bytes.windows(prefix.len()).enumerate() { if window != prefix { @@ -28,41 +36,95 @@ fn collect(bytes: &[u8], names: &mut BTreeSet) { { let name = std::str::from_utf8(name).unwrap(); if name.ends_with("LauncherPipe") || name.ends_with("Launcher_Pipe") { - names.insert(name.to_owned()); + names + .entry(name.to_ascii_lowercase()) + .or_insert_with(|| name.to_owned()); } } } } -pub fn pipe_names(reader: &mut impl Read) -> io::Result> { - let mut names = BTreeSet::new(); +pub fn title_pipe_names(exe: &Path) -> io::Result> { + discover(exe, SCAN_LIMIT) +} + +fn discover(exe: &Path, limit: u64) -> io::Result> { + let mut names = Names::new(); + let mut principal = limit; + scan(&mut File::open(exe)?, &mut names, &mut principal)?; + let mut extra = Names::new(); + let mut budget = limit; + for path in siblings(exe) { + if extra.len() >= NAME_LIMIT || budget == 0 { + break; + } + let Ok(mut file) = File::open(&path) else { + continue; + }; + if !file + .metadata() + .is_ok_and(|metadata| metadata.len() <= budget) + { + continue; + } + let mut own = Names::new(); + if scan(&mut file, &mut own, &mut budget).is_err() { + continue; + } + for (key, name) in own { + if extra.len() < NAME_LIMIT && !names.contains_key(&key) { + extra.entry(key).or_insert(name); + } + } + } + names.append(&mut extra); + Ok(names.into_values().collect()) +} + +fn siblings(exe: &Path) -> Vec { + let Some(entries) = exe.parent().and_then(|folder| fs::read_dir(folder).ok()) else { + return Vec::new(); + }; + let mut paths: Vec<_> = entries + .flatten() + .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_file())) + .map(|entry| entry.path()) + .filter(|path| { + path != exe + && path + .extension() + .is_some_and(|extension| extension.eq_ignore_ascii_case("exe")) + }) + .collect(); + paths.sort(); + paths.truncate(SIBLING_LIMIT); + paths +} + +fn scan(reader: &mut impl Read, names: &mut Names, budget: &mut u64) -> io::Result<()> { let mut carry = Vec::new(); let mut chunk = [0; 65536]; - let mut total = 0usize; loop { let count = reader.read(&mut chunk)?; if count == 0 { break; } - total += count; - if total > 256 * 1024 * 1024 { - return Err(invalid()); - } + *budget = budget.checked_sub(count as u64).ok_or_else(invalid)?; carry.extend_from_slice(&chunk[..count]); - collect(&carry, &mut names); + collect(&carry, names); for offset in 0..2 { let ascii: Vec<_> = carry[offset..] .chunks_exact(2) .map(|pair| if pair[1] == 0 { pair[0] } else { 0 }) .collect(); - collect(&ascii, &mut names); + collect(&ascii, names); } - if names.len() > 4 { + if names.len() > NAME_LIMIT { return Err(invalid()); } carry.drain(..carry.len().saturating_sub(256)); } - Ok(names.into_iter().collect()) + Ok(()) } pub fn exchange(reader: &mut impl Read) -> io::Result> { @@ -134,12 +196,165 @@ mod tests { } bytes.extend_from_slice(br"\\.\pipe\..\outsideLauncherPipe"); bytes.push(0); + let mut names = Names::new(); + scan(&mut Cursor::new(bytes), &mut names, &mut SCAN_LIMIT.clone()).unwrap(); assert_eq!( - pipe_names(&mut Cursor::new(bytes)).unwrap(), + names.into_values().collect::>(), ["GameLauncherPipe", "OtherLauncher_Pipe"] ); } + fn folder(name: &str) -> std::path::PathBuf { + let path = + std::env::temp_dir().join(format!("droiddeck-identity-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&path); + fs::create_dir(&path).unwrap(); + path + } + + #[test] + fn title_names_include_sibling_launcher_executables() { + let root = folder("siblings"); + let game = root.join("Game.exe"); + fs::write(&game, b"MZ obfuscated").unwrap(); + fs::write( + root.join("TitleLauncher.exe"), + [br"MZ \\.\pipe\TitleLauncher_Pipe".as_slice(), b"\0"].concat(), + ) + .unwrap(); + fs::write( + root.join("Data.dat"), + [br"\\.\pipe\DataLauncher_Pipe".as_slice(), b"\0"].concat(), + ) + .unwrap(); + fs::create_dir(root.join("Folder.exe")).unwrap(); + let names = title_pipe_names(&game).unwrap(); + fs::remove_dir_all(&root).unwrap(); + assert_eq!(names, ["TitleLauncher_Pipe"]); + } + + fn executable(path: &Path, names: &[&str]) { + let mut bytes = b"MZ ".to_vec(); + for name in names { + bytes.extend_from_slice(br"\\.\pipe\"); + bytes.extend_from_slice(name.as_bytes()); + bytes.push(0); + } + fs::write(path, bytes).unwrap(); + } + + #[test] + fn title_names_keep_the_game_executable_names_and_limits() { + let root = folder("principal"); + let game = root.join("Game.exe"); + executable(&game, &["GameLauncherPipe"]); + fs::write(root.join("Tool.exe"), b"MZ plain").unwrap(); + assert_eq!(title_pipe_names(&game).unwrap(), ["GameLauncherPipe"]); + for index in 0..40 { + fs::write(root.join(format!("Extra{index:02}.exe")), b"MZ").unwrap(); + } + executable(&root.join("Zz.exe"), &["LateLauncher_Pipe"]); + let crowded = title_pipe_names(&game); + executable( + &game, + &[ + "ALauncherPipe", + "BLauncherPipe", + "CLauncherPipe", + "DLauncherPipe", + "ELauncherPipe", + ], + ); + let overfull = title_pipe_names(&game); + fs::remove_dir_all(&root).unwrap(); + assert_eq!(crowded.unwrap(), ["GameLauncherPipe"]); + assert!(overfull.is_err()); + } + + #[test] + fn title_names_skip_siblings_that_cannot_be_scanned() { + use std::os::unix::fs::PermissionsExt; + let root = folder("unscannable"); + let game = root.join("Game.exe"); + executable(&game, &["GameLauncherPipe"]); + let locked = root.join("Locked.exe"); + executable(&locked, &["LockedLauncher_Pipe"]); + fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).unwrap(); + let locked_open = File::open(&locked).is_ok(); + File::create(root.join("Huge.exe")) + .unwrap() + .set_len(SCAN_LIMIT + 1) + .unwrap(); + executable( + &root.join("Noisy.exe"), + &[ + "NALauncherPipe", + "NBLauncherPipe", + "NCLauncherPipe", + "NDLauncherPipe", + "NELauncherPipe", + ], + ); + let names = title_pipe_names(&game); + fs::remove_dir_all(&root).unwrap(); + let mut expected = vec!["GameLauncherPipe".to_owned()]; + if locked_open { + expected.push("LockedLauncher_Pipe".to_owned()); + } + assert_eq!(names.unwrap(), expected); + } + + #[test] + fn title_names_bound_the_bytes_read_from_siblings() { + let root = folder("budget"); + let game = root.join("Game.exe"); + executable(&game, &["GameLauncherPipe"]); + executable(&root.join("First.exe"), &["FirstLauncherPipe"]); + executable(&root.join("Second.exe"), &["SecondLauncherPipe"]); + let size = fs::metadata(root.join("First.exe")).unwrap().len(); + let names = discover(&game, size + 8); + fs::remove_dir_all(&root).unwrap(); + assert_eq!(names.unwrap(), ["FirstLauncherPipe", "GameLauncherPipe"]); + } + + #[test] + fn title_names_merge_case_insensitively_and_cap_sibling_names() { + let root = folder("merge"); + let game = root.join("Game.exe"); + executable( + &game, + &[ + "ALauncherPipe", + "BLauncherPipe", + "CLauncherPipe", + "GTAVLauncher_Pipe", + ], + ); + executable( + &root.join("A.exe"), + &["gtavLauncher_Pipe", "ELauncherPipe", "FLauncherPipe"], + ); + executable( + &root.join("B.exe"), + &["GLauncherPipe", "HLauncherPipe", "ILauncherPipe"], + ); + let names = title_pipe_names(&game); + fs::remove_dir_all(&root).unwrap(); + assert_eq!( + names.unwrap(), + [ + "ALauncherPipe", + "BLauncherPipe", + "CLauncherPipe", + "ELauncherPipe", + "FLauncherPipe", + "GLauncherPipe", + "GTAVLauncher_Pipe", + "HLauncherPipe" + ] + ); + } + #[test] fn identity_replies_echo_only_a_valid_challenge() { struct Split(R); diff --git a/tools/rockstar-launcher/src/main.rs b/tools/rockstar-launcher/src/main.rs index 0913c6d548..cc2d294218 100644 --- a/tools/rockstar-launcher/src/main.rs +++ b/tools/rockstar-launcher/src/main.rs @@ -146,14 +146,21 @@ fn run() -> Result> { None }; let mut identity_listeners = Vec::new(); + let mut identity_names = Vec::new(); if session.is_some() { - for name in - droiddeck_rockstar_launcher::identity::pipe_names(&mut std::fs::File::open(&exe)?)? - { - identity_listeners.push(Listener::new(&name, Duration::from_secs(90))?); + identity_names = droiddeck_rockstar_launcher::identity::title_pipe_names(&exe)?; + for name in &identity_names { + identity_listeners.push(Listener::new(name, Duration::from_secs(90))?); } } - log("launcher pipes created"); + log(&format!( + "launcher pipes created, identity: {}", + if identity_names.is_empty() { + "none".to_owned() + } else { + identity_names.join(", ") + } + )); let mut command = std::process::Command::new(exe); command.current_dir(workdir).args(args?); if session.is_some() { @@ -256,7 +263,9 @@ fn run() -> Result> { } let _ = result.send(outcome); }); - Ok(wait_for_game(&mut child, handshake)?.code().unwrap_or(1)) + let code = wait_for_game(&mut child, handshake)?.code().unwrap_or(1); + log(&format!("game exited with code {code}")); + Ok(code) } fn main() { diff --git a/tools/tests/drm_handles_test.c b/tools/tests/drm_handles_test.c index 08d337f55e..fc3e7fff33 100644 --- a/tools/tests/drm_handles_test.c +++ b/tools/tests/drm_handles_test.c @@ -110,8 +110,8 @@ static long fixture_syscall(long number, ...) { if (number == SYS_ioctl) { (void)va_arg(ap, int); unsigned long request = va_arg(ap, unsigned long); - struct bl_drm_version *v = va_arg(ap, void *); - assert(request == BL_DRM_VERSION); + struct dd_drm_version *v = va_arg(ap, void *); + assert(request == DD_DRM_VERSION); snprintf(v->name, v->name_len, "%s", driver_name); v->name_len = strlen(driver_name); va_end(ap); @@ -184,23 +184,23 @@ static void *stress_fallback_imports(void *opaque) { int main(void) { int drm = test_open("/dev/null"), dma = test_open("/dev/zero"); uint32_t handle = 0; - unsetenv("BL_POWERVR_DRM_HANDLES"); - setenv("BL_POWERVR_RENDER_NODE", pvr_node, 1); + unsetenv("DD_POWERVR_DRM_HANDLES"); + setenv("DD_POWERVR_RENDER_NODE", pvr_node, 1); assert(drmPrimeFDToHandle(drm, dma, &handle) != 0); - setenv("BL_POWERVR_DRM_HANDLES", "yes", 1); + setenv("DD_POWERVR_DRM_HANDLES", "yes", 1); assert(drmPrimeFDToHandle(drm, dma, &handle) != 0); - setenv("BL_POWERVR_DRM_HANDLES", "1", 1); - unsetenv("BL_POWERVR_RENDER_NODE"); + setenv("DD_POWERVR_DRM_HANDLES", "1", 1); + unsetenv("DD_POWERVR_RENDER_NODE"); assert(drmPrimeFDToHandle(drm, dma, &handle) != 0); /* no selected node */ - setenv("BL_POWERVR_RENDER_NODE", "", 1); + setenv("DD_POWERVR_RENDER_NODE", "", 1); assert(drmPrimeFDToHandle(drm, dma, &handle) != 0); - setenv("BL_POWERVR_RENDER_NODE", "/dev/dri/renderD128", 1); + setenv("DD_POWERVR_RENDER_NODE", "/dev/dri/renderD128", 1); assert(drmPrimeFDToHandle(drm, dma, &handle) != 0); /* another GPU owns 128 */ - setenv("BL_POWERVR_RENDER_NODE", "/dev/dri/renderD130", 1); + setenv("DD_POWERVR_RENDER_NODE", "/dev/dri/renderD130", 1); assert(drmPrimeFDToHandle(drm, dma, &handle) != 0); /* selected node is absent */ - setenv("BL_POWERVR_RENDER_NODE", __FILE__, 1); + setenv("DD_POWERVR_RENDER_NODE", __FILE__, 1); assert(drmPrimeFDToHandle(drm, dma, &handle) != 0); /* regular files are not DRM nodes */ - setenv("BL_POWERVR_RENDER_NODE", pvr_node, 1); + setenv("DD_POWERVR_RENDER_NODE", pvr_node, 1); driver_name = "other"; assert(drmPrimeFDToHandle(drm, dma, &handle) != 0); driver_name = "pvr"; @@ -253,7 +253,7 @@ int main(void) { assert(drmPrimeHandleToFD(separate, handle, O_CLOEXEC | O_RDWR, &out) != 0); struct gem_close close_request = {.handle = handle}; int rc = 123; - assert(bl_drm_gem_close(separate, GEM_CLOSE, &close_request, &rc) == 0 && rc == 123); + assert(dd_drm_gem_close(separate, GEM_CLOSE, &close_request, &rc) == 0 && rc == 123); assert(drmPrimeHandleToFD(alias, handle, O_CLOEXEC | O_RDWR, &out) == 0); assert(fcntl(out, F_GETFD) & FD_CLOEXEC); struct stat src, dst; @@ -274,7 +274,7 @@ int main(void) { assert(drmCloseBufferHandle(drm, handle) != 0); assert(drmPrimeHandleToFD(alias, handle, O_CLOEXEC, &out) == 0); fixture_close(out); - assert(bl_drm_gem_close(alias, GEM_CLOSE, &close_request, &rc) == 1 && rc == 0); + assert(dd_drm_gem_close(alias, GEM_CLOSE, &close_request, &rc) == 1 && rc == 0); assert(drmPrimeHandleToFD(alias, handle, O_CLOEXEC, &out) != 0); fixture_close(alias); fixture_close(separate); @@ -288,7 +288,7 @@ int main(void) { assert(drmPrimeHandleToFD(drm, handle, O_CLOEXEC, &out) == 0); fixture_close(out); close_request.handle = handle; - assert(bl_drm_gem_close(drm, GEM_CLOSE, &close_request, &rc) == 0); + assert(dd_drm_gem_close(drm, GEM_CLOSE, &close_request, &rc) == 0); assert(drmCloseBufferHandle(drm, handle) == 0); assert(native_imports && native_exports && native_closes); kernel_error = EINVAL; @@ -321,19 +321,19 @@ int main(void) { /* Preserve the original device layout when PowerVR owns renderD128. */ pvr_node = "/dev/dri/renderD128"; - setenv("BL_POWERVR_RENDER_NODE", pvr_node, 1); + setenv("DD_POWERVR_RENDER_NODE", pvr_node, 1); assert(drmPrimeFDToHandle(drm, dma, &handle) == 0 && (handle & PVR_HANDLE_BIT)); assert(drmCloseBufferHandle(drm, handle) == 0); /* Retain the old KGSL path with the PowerVR opt-in unset. */ - unsetenv("BL_POWERVR_DRM_HANDLES"); + unsetenv("DD_POWERVR_DRM_HANDLES"); kgsl_present = 1; kgsl_state = 0; assert(drmPrimeFDToHandle(dma, drm, &handle) == 0 && !(handle & PVR_HANDLE_BIT)); assert(drmPrimeHandleToFD(dma, handle, O_CLOEXEC | O_RDWR, &out) == 0); fixture_close(out); close_request.handle = handle; - assert(bl_drm_gem_close(dma, GEM_CLOSE, &close_request, &rc) == 1 && rc == 0); + assert(dd_drm_gem_close(dma, GEM_CLOSE, &close_request, &rc) == 1 && rc == 0); assert(drmCloseBufferHandle(dma, handle) == -EINVAL); empty_table(); assert(count_fds() == baseline); diff --git a/tools/tests/netlink_stubs.c b/tools/tests/netlink_stubs.c index 58ba3bc61c..8cec065a2e 100644 --- a/tools/tests/netlink_stubs.c +++ b/tools/tests/netlink_stubs.c @@ -1,19 +1,19 @@ #include #include -int bl_nl_socket(int type, int *fd) { +int dd_nl_socket(int type, int *fd) { (void)type; *fd = -1; errno = ENOSYS; return 1; } -int bl_nl_owns(int fd) { +int dd_nl_owns(int fd) { (void)fd; return 0; } -int bl_nl_bind(int fd, const struct sockaddr *addr, socklen_t len, int *rc) { +int dd_nl_bind(int fd, const struct sockaddr *addr, socklen_t len, int *rc) { (void)fd; (void)addr; (void)len; @@ -21,20 +21,20 @@ int bl_nl_bind(int fd, const struct sockaddr *addr, socklen_t len, int *rc) { return 0; } -int bl_nl_connect(int fd, const struct sockaddr *addr, socklen_t len, int *rc) { - return bl_nl_bind(fd, addr, len, rc); +int dd_nl_connect(int fd, const struct sockaddr *addr, socklen_t len, int *rc) { + return dd_nl_bind(fd, addr, len, rc); } -int bl_nl_getsockname(int fd, struct sockaddr *addr, socklen_t *len, int *rc) { +int dd_nl_getsockname(int fd, struct sockaddr *addr, socklen_t *len, int *rc) { (void)len; - return bl_nl_bind(fd, addr, 0, rc); + return dd_nl_bind(fd, addr, 0, rc); } -int bl_nl_getpeername(int fd, struct sockaddr *addr, socklen_t *len, int *rc) { - return bl_nl_getsockname(fd, addr, len, rc); +int dd_nl_getpeername(int fd, struct sockaddr *addr, socklen_t *len, int *rc) { + return dd_nl_getsockname(fd, addr, len, rc); } -int bl_nl_setsockopt(int fd, int level, int option, const void *value, socklen_t len, +int dd_nl_setsockopt(int fd, int level, int option, const void *value, socklen_t len, int (*real)(int, int, int, const void *, socklen_t), int *rc) { (void)fd; (void)level; @@ -46,7 +46,7 @@ int bl_nl_setsockopt(int fd, int level, int option, const void *value, socklen_t return 0; } -int bl_nl_getsockopt(int fd, int level, int option, void *value, socklen_t *len, +int dd_nl_getsockopt(int fd, int level, int option, void *value, socklen_t *len, int (*real)(int, int, int, void *, socklen_t *), int *rc) { (void)fd; (void)level; diff --git a/tools/tests/subsurface_release_harness.c b/tools/tests/subsurface_release_harness.c new file mode 100644 index 0000000000..0921666d45 --- /dev/null +++ b/tools/tests/subsurface_release_harness.c @@ -0,0 +1,318 @@ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include +#include +#include "wayland-util.h" + +void wl_list_init(struct wl_list *list) { list->prev = list->next = list; } +void wl_list_insert(struct wl_list *list, struct wl_list *elm) { + elm->prev = list; + elm->next = list->next; + list->next = elm; + elm->next->prev = elm; +} +void wl_list_remove(struct wl_list *elm) { + elm->prev->next = elm->next; + elm->next->prev = elm->prev; + elm->next = elm->prev = NULL; +} +int wl_list_empty(const struct wl_list *list) { return list->next == list; } + +struct wl_listener { struct wl_list link; void (*notify)(struct wl_listener *, void *); }; +struct wl_resource { struct wl_list listeners; int acquired, releases, errors; }; +struct dmabuf_buffer { int unused; }; +enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE }; +struct surface { + struct wl_list link; + struct wl_resource *dmabuf; + struct dmabuf_buffer *dmabuf_buf; + struct wl_listener dmabuf_destroy; + int64_t next_release_ns; + int releases_pending; + enum surface_role role; + struct surface *parent; + int sub_desync; +}; + +#define TFD_TIMER_ABSTIME 1 +static struct wl_list g_surfaces; +static struct wl_list g_pending_releases; +static int g_release_timer_fd = 3; +static int g_fps_limit; +static int64_t g_refresh_ns = 8333333; +static int g_release_unpaced; +static int64_t g_now = 1000000000LL; +static int64_t g_armed; +static struct dmabuf_buffer g_buf; + +static int64_t now_ns(void) { return g_now; } +static void perf_note_release(int64_t since) { (void)since; } +static int buffer_release_blocked(struct wl_resource *b) { (void)b; return 0; } +static int ahb_swapchain_defer_release(struct dmabuf_buffer *b, struct wl_resource *r, struct surface *s, int paced) { + (void)b; (void)r; (void)s; (void)paced; + return 0; +} +static void dmabuf_buffer_unref(struct dmabuf_buffer *b) { (void)b; } +static void wl_resource_add_destroy_listener(struct wl_resource *r, struct wl_listener *l) { + wl_list_insert(r->listeners.prev, &l->link); +} +static int timerfd_settime(int fd, int flags, const struct itimerspec *its, struct itimerspec *old) { + (void)fd; (void)flags; (void)old; + g_armed = (int64_t)its->it_value.tv_sec * 1000000000LL + its->it_value.tv_nsec; + return 0; +} +static void send_buffer_release(struct wl_resource *b) { + b->releases++; + if (b->acquired) b->acquired = 0; + else b->errors++; +} + +#include "release.inc" + +static void present(struct wl_resource *b) { b->acquired = 1; } + +static void commit(struct surface *s, struct wl_resource *b) { + if (s->dmabuf != b) { + drop_dmabuf(s, 1); + if (b) { + pending_releases_cancel(b); + s->dmabuf = b; + s->dmabuf_buf = &g_buf; + wl_resource_add_destroy_listener(b, &s->dmabuf_destroy); + } + } + pending_releases_apply(s); +} + +static void timer_fires(int64_t at) { + if (g_now < at) g_now = at; + release_due_buffers(); + arm_release_timer(); +} + +static void surface_init(struct surface *s, enum surface_role role, struct surface *parent) { + memset(s, 0, sizeof(*s)); + s->role = role; + s->parent = parent; + wl_list_insert(g_surfaces.prev, &s->link); +} + +static void buffer_init(struct wl_resource *b) { + memset(b, 0, sizeof(*b)); + wl_list_init(&b->listeners); +} + +static void check(const struct wl_resource *b, int releases) { + if (b->releases != releases || b->errors) { + fprintf(stderr, "releases %d (want %d), released while not acquired %d\n", b->releases, releases, b->errors); + exit(1); + } +} + +static void moved_between_planes(void) { + struct surface root, low, high; + struct wl_resource a, b, c; + surface_init(&root, ROLE_TOPLEVEL, NULL); + surface_init(&low, ROLE_SUBSURFACE, &root); + surface_init(&high, ROLE_SUBSURFACE, &root); + buffer_init(&a); buffer_init(&b); buffer_init(&c); + + present(&a); present(&b); + commit(&high, &a); + commit(&low, &b); + commit(&root, NULL); + + present(&a); present(&b); + commit(&high, NULL); + timer_fires(g_now); + check(&a, 0); + commit(&low, &a); + timer_fires(g_now); + commit(&root, &b); + timer_fires(g_now + 100000000LL); + check(&a, 0); + check(&b, 0); + + present(&c); + commit(&high, NULL); + commit(&low, NULL); + commit(&root, &c); + timer_fires(g_now + 100000000LL); + check(&a, 1); + check(&b, 1); + check(&c, 0); +} + +static void reattached_before_release(void) { + struct surface s; + struct wl_resource a, b, c; + surface_init(&s, ROLE_TOPLEVEL, NULL); + buffer_init(&a); buffer_init(&b); buffer_init(&c); + g_fps_limit = 60; + present(&a); commit(&s, &a); + present(&b); commit(&s, &b); + present(&a); commit(&s, &a); + present(&c); commit(&s, &c); + timer_fires(g_now + 1000000000LL); + check(&a, 1); + check(&b, 1); + check(&c, 0); +} + +static void desync_child_not_held(void) { + struct surface root, child; + struct wl_resource a, b; + surface_init(&root, ROLE_TOPLEVEL, NULL); + surface_init(&child, ROLE_SUBSURFACE, &root); + child.sub_desync = 1; + buffer_init(&a); buffer_init(&b); + present(&a); commit(&child, &a); + present(&b); commit(&child, &b); + timer_fires(g_now + 100000000LL); + check(&a, 1); + check(&b, 0); +} + +static void toplevel_pacing_kept(void) { + struct surface s; + struct wl_resource a, b, c; + surface_init(&s, ROLE_TOPLEVEL, NULL); + buffer_init(&a); buffer_init(&b); buffer_init(&c); + g_fps_limit = 60; + const int64_t interval = 1000000000LL / 60; + present(&a); commit(&s, &a); + present(&b); commit(&s, &b); + present(&c); commit(&s, &c); + const int64_t start = g_now; + timer_fires(g_now); + check(&a, 1); + check(&b, 0); + assert(g_armed == start + interval); + timer_fires(start + interval / 2); + check(&b, 0); + timer_fires(g_armed); + check(&b, 1); + check(&c, 0); +} + +static void unpaced_sync_child(void) { + struct surface root, low, high; + struct wl_resource a, b; + surface_init(&root, ROLE_TOPLEVEL, NULL); + surface_init(&low, ROLE_SUBSURFACE, &root); + surface_init(&high, ROLE_SUBSURFACE, &root); + buffer_init(&a); buffer_init(&b); + g_release_unpaced = 1; + present(&a); commit(&high, &a); commit(&root, NULL); + present(&a); + commit(&high, NULL); + check(&a, 0); + commit(&low, &a); + commit(&root, NULL); + check(&a, 0); + commit(&low, NULL); + check(&a, 0); + commit(&root, NULL); + check(&a, 1); + present(&b); commit(&root, &b); + commit(&root, NULL); + check(&b, 1); +} + +static void holder_destroyed(void) { + struct surface root, child; + struct wl_resource a, b; + surface_init(&root, ROLE_TOPLEVEL, NULL); + surface_init(&child, ROLE_SUBSURFACE, &root); + buffer_init(&a); buffer_init(&b); + present(&a); commit(&child, &a); commit(&root, NULL); + present(&b); commit(&child, &b); + timer_fires(g_now + 100000000LL); + check(&a, 0); + child.parent = NULL; + wl_list_remove(&root.link); + pending_releases_forget_surface(&root); + check(&a, 1); +} + +static void cycled_faster_than_releases(void) { + struct surface s; + struct wl_resource a, b, c; + struct wl_resource *order[3] = {&a, &b, &c}; + surface_init(&s, ROLE_TOPLEVEL, NULL); + buffer_init(&a); buffer_init(&b); buffer_init(&c); + g_fps_limit = 60; + const int64_t interval = 1000000000LL / 60; + for (int i = 0; i < 30; i++) { + present(order[i % 3]); + commit(&s, order[i % 3]); + assert(s.releases_pending <= 2); + assert(g_armed <= g_now + 3 * interval); + } + timer_fires(g_now + 1000000000LL); + check(&a, 1); + check(&b, 1); + check(&c, 0); +} + +static void desync_parent_holds_sync_grandchild(void) { + struct surface root, middle, child; + struct wl_resource a, b; + surface_init(&root, ROLE_TOPLEVEL, NULL); + surface_init(&middle, ROLE_SUBSURFACE, &root); + surface_init(&child, ROLE_SUBSURFACE, &middle); + middle.sub_desync = 1; + buffer_init(&a); buffer_init(&b); + present(&a); commit(&child, &a); commit(&middle, NULL); + present(&b); commit(&child, &b); + timer_fires(g_now + 100000000LL); + check(&a, 0); + commit(&middle, NULL); + timer_fires(g_now + 100000000LL); + check(&a, 1); + check(&b, 0); +} + +static void set_desync_frees_held_release(void) { + struct surface root, outer, inner; + struct wl_resource a, b, c, d; + surface_init(&root, ROLE_TOPLEVEL, NULL); + surface_init(&outer, ROLE_SUBSURFACE, &root); + surface_init(&inner, ROLE_SUBSURFACE, &outer); + buffer_init(&a); buffer_init(&b); buffer_init(&c); buffer_init(&d); + present(&a); commit(&inner, &a); commit(&root, NULL); + present(&b); commit(&inner, &b); + present(&c); commit(&outer, &c); commit(&root, NULL); + present(&d); commit(&outer, &d); + inner.sub_desync = 1; + pending_releases_rehold(&inner); + timer_fires(g_now + 100000000LL); + check(&a, 1); + check(&c, 0); + outer.sub_desync = 1; + pending_releases_rehold(&outer); + timer_fires(g_now + 100000000LL); + check(&c, 1); + check(&b, 0); + check(&d, 0); +} + +int main(int argc, char **argv) { + assert(argc == 2); + wl_list_init(&g_surfaces); + wl_list_init(&g_pending_releases); + if (!strcmp(argv[1], "moved")) moved_between_planes(); + else if (!strcmp(argv[1], "reattached")) reattached_before_release(); + else if (!strcmp(argv[1], "cycled")) cycled_faster_than_releases(); + else if (!strcmp(argv[1], "desync")) desync_child_not_held(); + else if (!strcmp(argv[1], "toplevel")) toplevel_pacing_kept(); + else if (!strcmp(argv[1], "unpaced")) unpaced_sync_child(); + else if (!strcmp(argv[1], "destroyed")) holder_destroyed(); + else if (!strcmp(argv[1], "nested")) desync_parent_holds_sync_grandchild(); + else if (!strcmp(argv[1], "set-desync")) set_desync_frees_held_release(); + else return 2; + return 0; +} diff --git a/tools/tests/test_battlenet.py b/tools/tests/test_battlenet.py index 40c16bfcd4..ece44f60d6 100644 --- a/tools/tests/test_battlenet.py +++ b/tools/tests/test_battlenet.py @@ -56,7 +56,7 @@ class StoreDebugEnvironmentTest(Temp): def env(self, values=None): debug_dir = self.tmp / "session" debug_dir.mkdir(exist_ok=True) - base = {"HOME": str(self.tmp), "BL_DEBUG_DIR": str(debug_dir)} + base = {"HOME": str(self.tmp), "DD_DEBUG_DIR": str(debug_dir)} base.update(values or {}) return base @@ -180,7 +180,7 @@ class ConfigAndMenuTest(Temp): self.assertEqual(config["Client"]["Streaming"]["StreamingEnabled"], "false") self.assertEqual(config["Client"]["GameLaunchWindowBehavior"], "2") self.assertIsNone(BNET["write_config"](root)) - path.write_text('{"Client": {"HardwareAcceleration": "false", "GameLaunchWindowBehavior": "0"}, "Games": {"osi": {}}}') + path.write_text('{"Client": {"HardwareAcceleration": "false"}, "Games": {"osi": {}}}') self.assertEqual(BNET["write_config"](root), "launch 32-bit") config = json.loads(path.read_text()) self.assertEqual(config, {"Client": {"HardwareAcceleration": "false", "GameLaunchWindowBehavior": "2"}, @@ -189,6 +189,29 @@ class ConfigAndMenuTest(Temp): self.assertEqual(BNET["write_config"](root), "acceleration 32-bit") self.assertEqual(json.loads(path.read_text())["Client"]["HardwareAcceleration"], "false") + def test_a_launch_behavior_the_player_chose_is_kept(self): + root = str(self.tmp) + path = self.config_path() + path.parent.mkdir(parents=True) + for behavior in ("0", "1"): + with self.subTest(behavior): + path.write_text('{"Client": {"HardwareAcceleration": "false", "GameLaunchWindowBehavior": "%s"}, ' + '"Games": {"s1": {"Run64Bit": "false", "Run64BitSet": "true"}}}' % behavior) + self.assertIsNone(BNET["write_config"](root)) + self.assertEqual(json.loads(path.read_text())["Client"]["GameLaunchWindowBehavior"], behavior) + self.assertTrue(BNET["keeps_open"](root)) + + def test_only_a_launch_behavior_other_than_exit_keeps_battle_net_open(self): + root = str(self.tmp) + self.assertFalse(BNET["keeps_open"](root)) + path = self.config_path() + path.parent.mkdir(parents=True) + for text in ("{not json", "[1, 2]", '{"Client": "x"}', '{"Client": {}}', + '{"Client": {"GameLaunchWindowBehavior": "2"}}'): + with self.subTest(text): + path.write_text(text) + self.assertFalse(BNET["keeps_open"](root)) + def test_starcraft_starts_its_32_bit_client_until_a_player_picks_one(self): root = str(self.tmp) BNET["write_config"](root) @@ -656,6 +679,7 @@ class TidyTest(unittest.TestCase): "say": lambda message: None, "stop": lambda found, wait=0: self.stopped.append(sorted(pid for pid, _ in found)), "notify": lambda title, body, icon=None: self.notified.append(title), + "keeps_open": lambda root: False, }) patcher.start() self.addCleanup(patcher.stop) @@ -672,6 +696,14 @@ class TidyTest(unittest.TestCase): self.assertEqual(self.stopped, [[1, 2, 3]]) self.assertEqual(self.notified, []) + def test_battle_net_the_player_set_to_stay_open_is_left_open(self): + up = [self.CLIENT, self.PAGE, self.AGENT, self.WINE] + tidy = BNET["Tidy"](settle=20, gone=30) + with mock.patch.dict(BNET, {"keeps_open": lambda root: True}): + closed = self.run_tidy(tidy, [(0, up), (5, up + [self.GAME]), (25, up + [self.GAME]), (60, up + [self.GAME])]) + self.assertEqual(closed, [False, False, False, False]) + self.assertEqual(self.stopped, []) + def test_battle_net_beside_a_game_signing_in_with_its_token_is_left_open(self): d4 = (6, ["C:\\Program Files (x86)\\Diablo IV\\Diablo IV.exe", "-nostreamline", "-sso", "-launch", "-uid", "fenris"]) up = [self.CLIENT, self.PAGE, self.AGENT] @@ -871,7 +903,7 @@ class OpenTest(Temp): self.alive.extend([(50, [str(client)]), (51, ["C:\\ProgramData\\Battle.net\\Agent\\Agent.9824\\Agent.exe"])]) started = [] with mock.patch.object(BNET["subprocess"], "Popen", lambda cmd, **kw: started.append((cmd, kw)) or mock.Mock()), \ - mock.patch.dict(os.environ, {"BL_DESKTOP": "1"}), \ + mock.patch.dict(os.environ, {"DD_DESKTOP": "1"}), \ mock.patch.dict(BNET, {"CACHE": str(self.tmp / "cache"), "acquire": lambda: self.fail("took the lock")}): self.assertIsNone(BNET["show"](self.root, wait=60, poll=0)) cmd, kw = started[0] @@ -1076,7 +1108,7 @@ class LaunchTest(Harness): self.install() pfx = Path(self.root) / ("steamapps/compatdata/%s/pfx" % BNET["APP_ID"]) (pfx / "user.reg").write_text("WINE REGISTRY Version 2\n") - with mock.patch.dict(os.environ, {"BL_WIDTH": "160", "BL_HEIGHT": "90"}), \ + with mock.patch.dict(os.environ, {"DD_WIDTH": "160", "DD_HEIGHT": "90"}), \ mock.patch.dict(BNET, {"wallpaper_bmp": lambda w, h: b"BM%dx%d" % (w, h)}): self.assertTrue(BNET["wallpaper"](self.root)) self.assertTrue(BNET["wallpaper"](self.root)) @@ -1092,7 +1124,7 @@ class LaunchTest(Harness): self.install() pfx = Path(self.root) / ("steamapps/compatdata/%s/pfx" % BNET["APP_ID"]) (pfx / "user.reg").write_text("WINE REGISTRY Version 2\n") - with mock.patch.dict(os.environ, {"BL_WIDTH": "2560", "BL_HEIGHT": "1600"}), \ + with mock.patch.dict(os.environ, {"DD_WIDTH": "2560", "DD_HEIGHT": "1600"}), \ mock.patch.dict(BNET, {"wallpaper_bmp": lambda w, h: b"BM%dx%d" % (w, h)}): self.assertTrue(BNET["wallpaper"](self.root)) image = pfx / "drive_c/users/steamuser/AppData/Local/DroidDeck/wallpaper-1152x720.bmp" @@ -1145,17 +1177,17 @@ class LaunchTest(Harness): sizes = {("1280", "720"): 96, ("1920", "1080"): 96, ("2400", "1504"): 120, ("2448", "1848"): 120, ("1080", "2400"): 96, ("3840", "2160"): 192, ("2560", "1600"): 120} for (width, height), want in sizes.items(): - with mock.patch.dict(os.environ, {"BL_WIDTH": width, "BL_HEIGHT": height}): + with mock.patch.dict(os.environ, {"DD_WIDTH": width, "DD_HEIGHT": height}): self.assertEqual(BNET["desktop_dpi"](), want, (width, height)) def test_battle_nets_desktop_scale_is_written_once_and_follows_the_size(self): self.install() pfx = Path(self.root) / ("steamapps/compatdata/%s/pfx" % BNET["APP_ID"]) (pfx / "user.reg").write_text('WINE REGISTRY Version 2\n\n[Control Panel\\\\Desktop] 1\n"LogPixels"=dword:00000060\n') - with mock.patch.dict(os.environ, {"BL_WIDTH": "1280", "BL_HEIGHT": "720"}): + with mock.patch.dict(os.environ, {"DD_WIDTH": "1280", "DD_HEIGHT": "720"}): self.assertTrue(BNET["dpi"](self.root)) self.assertEqual((pfx / "user.reg").read_text().count("LogPixels"), 1) - with mock.patch.dict(os.environ, {"BL_WIDTH": "2448", "BL_HEIGHT": "1848"}): + with mock.patch.dict(os.environ, {"DD_WIDTH": "2448", "DD_HEIGHT": "1848"}): self.assertTrue(BNET["dpi"](self.root)) self.assertTrue(BNET["dpi"](self.root)) reg = (pfx / "user.reg").read_text() @@ -1206,10 +1238,10 @@ class LaunchTest(Harness): self.assertFalse(BNET["is_game"](argv)) def test_battle_net_shows_in_the_desktops_window_or_as_the_steam_launch(self): - with mock.patch.dict(os.environ, {"BL_DESKTOP": "1", "SteamGameId": "123"}): + with mock.patch.dict(os.environ, {"DD_DESKTOP": "1", "SteamGameId": "123"}): self.assertEqual(BNET["proton_options"](), ["--window"]) with mock.patch.dict(os.environ, {"SteamGameId": "11151176786366644224"}): - os.environ.pop("BL_DESKTOP", None) + os.environ.pop("DD_DESKTOP", None) self.assertEqual(BNET["proton_options"](), ["--game-id", "11151176786366644224"]) os.environ["SteamGameId"] = "0" self.assertEqual(BNET["proton_options"](), []) @@ -1220,32 +1252,32 @@ class LaunchTest(Harness): with open(gpu, "w") as out: out.write("#!/bin/sh\n") os.chmod(gpu, 0o755) - with mock.patch.dict(BNET, {"BIN": tmp}), mock.patch.dict(os.environ, {"BL_DESKTOP": "1"}): - os.environ.pop("BL_DESKTOP_GPU", None) - os.environ.pop("BL_DESKTOP_GPU_CHILD", None) + with mock.patch.dict(BNET, {"BIN": tmp}), mock.patch.dict(os.environ, {"DD_DESKTOP": "1"}): + os.environ.pop("DD_DESKTOP_GPU", None) + os.environ.pop("DD_DESKTOP_GPU_CHILD", None) self.assertEqual(BNET["desktop_gpu"](), gpu) for choice in ("off", "0", "No", "false"): - os.environ["BL_DESKTOP_GPU"] = choice + os.environ["DD_DESKTOP_GPU"] = choice self.assertIsNone(BNET["desktop_gpu"]()) - os.environ["BL_DESKTOP_GPU"] = "on" - os.environ["BL_DESKTOP_GPU_CHILD"] = "1" + os.environ["DD_DESKTOP_GPU"] = "on" + os.environ["DD_DESKTOP_GPU_CHILD"] = "1" self.assertIsNone(BNET["desktop_gpu"]()) - os.environ.pop("BL_DESKTOP_GPU_CHILD") - os.environ["BL_DESKTOP"] = "0" + os.environ.pop("DD_DESKTOP_GPU_CHILD") + os.environ["DD_DESKTOP"] = "0" self.assertIsNone(BNET["desktop_gpu"]()) - os.environ["BL_DESKTOP"] = "1" + os.environ["DD_DESKTOP"] = "1" os.chmod(gpu, 0o644) self.assertIsNone(BNET["desktop_gpu"]()) def test_on_the_gpu_battle_net_fills_the_screen_instead_of_a_window(self): - with mock.patch.dict(os.environ, {"BL_DESKTOP": "1", "BL_DESKTOP_GPU_CHILD": "1", "BL_WIDTH": "1280", "BL_HEIGHT": "720", "SteamGameId": "0"}): + with mock.patch.dict(os.environ, {"DD_DESKTOP": "1", "DD_DESKTOP_GPU_CHILD": "1", "DD_WIDTH": "1280", "DD_HEIGHT": "720", "SteamGameId": "0"}): self.assertEqual(BNET["proton_options"](), ["--desktop", "1280x720"]) def test_under_gamescope_battle_net_gets_a_desktop_of_the_screens_size(self): - with mock.patch.dict(os.environ, {"BL_WIDTH": "1280", "BL_HEIGHT": "720", "SteamGameId": "0"}): - os.environ.pop("BL_DESKTOP", None) + with mock.patch.dict(os.environ, {"DD_WIDTH": "1280", "DD_HEIGHT": "720", "SteamGameId": "0"}): + os.environ.pop("DD_DESKTOP", None) self.assertEqual(BNET["proton_options"](), ["--desktop", "1280x720"]) - os.environ["BL_DESKTOP"] = "1" + os.environ["DD_DESKTOP"] = "1" self.assertEqual(BNET["proton_options"](), ["--window"]) def test_the_library_comes_before_the_action(self): @@ -1263,7 +1295,7 @@ class LaunchTest(Harness): self.assertEqual(BNET["main"](argv), 2) self.assertEqual(BNET["main"](["launch", "Fen"]), 0) self.assertEqual(self.calls, [("launch", "Fen")]) - self.assertEqual(os.environ.get("BL_BATTLENET"), "1") + self.assertEqual(os.environ.get("DD_BATTLENET"), "1") class InstallGameTest(Harness): diff --git a/tools/tests/test_binfmt_preload.py b/tools/tests/test_binfmt_preload.py index 9966b28505..e207b5c9ca 100644 --- a/tools/tests/test_binfmt_preload.py +++ b/tools/tests/test_binfmt_preload.py @@ -107,7 +107,7 @@ class BinfmtPreloadTest(unittest.TestCase): def environment(self, desktop=True, **extra): env = {"PATH": "%s:/usr/bin:/bin" % self.dir, "LD_PRELOAD": str(self.library), "HANDLER_LOG": str(self.log)} if desktop: - env["BL_DESKTOP"] = "1" + env["DD_DESKTOP"] = "1" env.update(extra) return env @@ -192,21 +192,21 @@ class BinfmtPreloadTest(unittest.TestCase): tool = self.x86() for how in ("execve", "execvp"): self.log.unlink(missing_ok=True) - self.assertEqual(self.run_program(how, tool, "a", desktop=False, BL_BINFMT="1"), (7, "", ["--exec", str(tool), "a"])) + self.assertEqual(self.run_program(how, tool, "a", desktop=False, DD_BINFMT="1"), (7, "", ["--exec", str(tool), "a"])) self.log.unlink() - self.assertEqual(self.run_program("spawnp", "tool", "b", desktop=False, BL_BINFMT="1"), (0, "exit 7", ["--exec", str(tool), "b"])) + self.assertEqual(self.run_program("spawnp", "tool", "b", desktop=False, DD_BINFMT="1"), (0, "exit 7", ["--exec", str(tool), "b"])) def test_only_the_value_one_switches_the_hand_off_on(self): for value in ("0", "", "11", "yes"): with self.subTest(value=value): - self.assertEqual(self.run_program("execve", self.x86(), desktop=False, BL_BINFMT=value), (0, "", None)) + self.assertEqual(self.run_program("execve", self.x86(), desktop=False, DD_BINFMT=value), (0, "", None)) def test_the_desktop_hands_off_whatever_the_switch_says(self): tool = self.x86() for value in ("0", ""): with self.subTest(value=value): self.log.unlink(missing_ok=True) - self.assertEqual(self.run_program("execve", tool, BL_BINFMT=value), (7, "", ["--exec", str(tool)])) + self.assertEqual(self.run_program("execve", tool, DD_BINFMT=value), (7, "", ["--exec", str(tool)])) def script_child(self, *lines, **extra): script = self.file("start.sh", ("#!/bin/bash\ncd \"${0%%/*}\"\n%s\n" % "\n".join(lines)).encode()) @@ -216,15 +216,15 @@ class BinfmtPreloadTest(unittest.TestCase): @unittest.skipUnless(os.path.exists("/bin/bash"), "needs bash") def test_an_x86_program_a_native_script_runs_goes_to_the_handler(self): tool = self.x86() - self.assertEqual(self.script_child("./tool one", "echo after $?", desktop=False, BL_BINFMT="1"), + self.assertEqual(self.script_child("./tool one", "echo after $?", desktop=False, DD_BINFMT="1"), (0, "after 7", ["--exec", "./tool", "one"])) self.log.unlink() - self.assertEqual(self.script_child("exec ./tool two", desktop=False, BL_BINFMT="1"), (7, "", ["--exec", str(tool), "two"])) + self.assertEqual(self.script_child("exec ./tool two", desktop=False, DD_BINFMT="1"), (7, "", ["--exec", str(tool), "two"])) @unittest.skipUnless(os.path.exists("/bin/bash"), "needs bash") def test_native_children_of_a_script_run_as_themselves(self): self.file("child.sh", b"#!/bin/sh\nexit 5\n") - self.assertEqual(self.script_child("./child.sh", "echo $?", desktop=False, BL_BINFMT="1"), (0, "5", None)) + self.assertEqual(self.script_child("./child.sh", "echo $?", desktop=False, DD_BINFMT="1"), (0, "5", None)) @unittest.skipUnless(os.path.exists("/bin/bash"), "needs bash") def test_outside_the_desktop_and_script_runs_a_scripts_children_are_untouched(self): @@ -242,7 +242,7 @@ class ScriptRunTest(unittest.TestCase): (tmp / "app/entry").write_text("go.sh") if fex: (tmp / "app/fex").write_text(fex) - (tmp / "app/files/go.sh").write_text("#!/bin/bash\necho \"${BL_BINFMT-unset} ${BL_DESKTOP-unset}\"\n") + (tmp / "app/files/go.sh").write_text("#!/bin/bash\necho \"${DD_BINFMT-unset} ${DD_DESKTOP-unset}\"\n") runner = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-script-run" base = {"PATH": "/usr/bin:/bin", "DBUS_SESSION_BUS_ADDRESS": "unix:path=/nonexistent"} done = subprocess.run(["/bin/bash", str(runner), str(tmp / "app")], stdout=subprocess.PIPE, text=True, timeout=60, @@ -251,12 +251,12 @@ class ScriptRunTest(unittest.TestCase): def test_a_script_run_switches_the_hand_off_on_for_its_children_only(self): self.assertEqual(self.run_app({}), (0, "1 unset")) - self.assertEqual(self.run_app({"BL_BINFMT": "0", "BL_DESKTOP": "1"}), (0, "1 1")) + self.assertEqual(self.run_app({"DD_BINFMT": "0", "DD_DESKTOP": "1"}), (0, "1 1")) self.assertEqual(self.run_app({}, fex="on"), (0, "1 unset")) def test_fex_off_keeps_x86_children_away_from_the_hand_off(self): self.assertEqual(self.run_app({}, fex="off"), (0, "unset unset")) - self.assertEqual(self.run_app({"BL_BINFMT": "1"}, fex="off"), (0, "unset unset")) + self.assertEqual(self.run_app({"DD_BINFMT": "1"}, fex="off"), (0, "unset unset")) if __name__ == "__main__": diff --git a/tools/tests/test_cdp_guard.py b/tools/tests/test_cdp_guard.py index 8185abed8a..9dc5891f36 100644 --- a/tools/tests/test_cdp_guard.py +++ b/tools/tests/test_cdp_guard.py @@ -19,7 +19,7 @@ class CdpGuardTest(unittest.TestCase): subprocess.run(["cc", "-shared", "-fPIC", "-O2", str(SOURCE), str(SOURCE.parent / "binfmt.c"), str(SOURCE.parent / "webhelper.c"), str(Path(__file__).with_name("netlink_stubs.c")), "-x", "c", "-", "-ldl", "-o", str(cls.library)], - input=b"int bl_udevmon_stand_in(int fd) { return 0; }", check=True, capture_output=True) + input=b"int dd_udevmon_stand_in(int fd) { return 0; }", check=True, capture_output=True) @classmethod def tearDownClass(cls): @@ -37,7 +37,7 @@ class CdpGuardTest(unittest.TestCase): return s.getsockname()[1] def env(self, port): - return dict(os.environ, LD_PRELOAD=str(self.library), BL_CDP_GUARD=str(port), BL_SYSV_DIR=self.temp.name) + return dict(os.environ, LD_PRELOAD=str(self.library), DD_CDP_GUARD=str(port), DD_SYSV_DIR=self.temp.name) def test_guarded_ipv4_bind_is_loopback_only(self): port = self.port() diff --git a/tools/tests/test_ci_checks.py b/tools/tests/test_ci_checks.py index 125dba0398..bf3db6ec69 100644 --- a/tools/tests/test_ci_checks.py +++ b/tools/tests/test_ci_checks.py @@ -115,15 +115,15 @@ class CiChecksTest(unittest.TestCase): jobs = yaml.safe_load((ROOT / '.github/workflows/build.yml').read_text())['jobs'] gate = jobs['checks'] self.assertEqual(gate['name'], 'Compile and test APK') - self.assertEqual(set(gate['needs']), {'build', 'python-tests'}) + self.assertEqual(set(gate['needs']), {'build', 'python-tests', 'store-tests'}) self.assertIn('!cancelled()', gate['if']) - for build, python in itertools.product(('success', 'failure', 'cancelled', 'skipped'), repeat=2): - with self.subTest(build=build, python=python): + for build, python, store in itertools.product(('success', 'failure', 'cancelled', 'skipped'), repeat=3): + with self.subTest(build=build, python=python, store=store): result = subprocess.run( ['bash', '-c', gate['steps'][0]['run']], - env=dict(os.environ, BUILD_RESULT=build, PYTHON_RESULT=python), + env=dict(os.environ, BUILD_RESULT=build, PYTHON_RESULT=python, STORE_RESULT=store), capture_output=True) - self.assertEqual(result.returncode == 0, build == python == 'success') + self.assertEqual(result.returncode == 0, build == python == store == 'success') for publisher in ('sign', 'packs'): self.assertIn('checks', jobs[publisher]['needs']) diff --git a/tools/tests/test_client_zram_focus.py b/tools/tests/test_client_zram_focus.py index db2d3f80e1..4a69f47ed7 100644 --- a/tools/tests/test_client_zram_focus.py +++ b/tools/tests/test_client_zram_focus.py @@ -37,8 +37,8 @@ class ClientZramFocusTest(unittest.TestCase): task(5000014, ['/e/WebKitWebProcess', '4'], ['DROIDDECK_EPIC_HIDDEN=1']) task(5000015, [fex, '/e/usr/bin/EpicGamesLauncher'], ['DROIDDECK_EPIC_HIDDEN=10']) task(5000016, ['/s/reaper', 'SteamLaunch', 'AppId=413150', '--', 'game']) - source = function_source('bl_zram_scan').replace('/proc/[0-9]*', tmp + '/[0-9]*') - result = run_bash(source + '\nbl_zram_scan\necho "${_bl_pids[*]}|${_bl_others[*]}|$_bl_game|$_bl_apps"') + source = function_source('dd_zram_scan').replace('/proc/[0-9]*', tmp + '/[0-9]*') + result = run_bash(source + '\ndd_zram_scan\necho "${_dd_pids[*]}|${_dd_others[*]}|$_dd_game|$_dd_apps"') self.assertEqual(0, result.returncode, result.stderr) self.assertEqual('', result.stderr) self.assertEqual('5000010 5000011 5000012|5000013 5000014 5000015|1| 413150', result.stdout.strip()) @@ -47,8 +47,8 @@ class ClientZramFocusTest(unittest.TestCase): with tempfile.TemporaryDirectory() as tmp: for pid, argv in tasks: self.write_cmd(Path(tmp), pid, argv) - source = function_source('bl_zram_scan').replace('/proc/[0-9]*', tmp + '/[0-9]*') - return run_bash(source + '\nbl_zram_scan\necho "${_bl_pids[*]}|${_bl_others[*]}|$_bl_game"') + source = function_source('dd_zram_scan').replace('/proc/[0-9]*', tmp + '/[0-9]*') + return run_bash(source + '\ndd_zram_scan\necho "${_dd_pids[*]}|${_dd_others[*]}|$_dd_game"') def test_battlenet_is_compressed_with_the_client_while_one_of_its_games_runs(self): launcher = [ @@ -80,25 +80,25 @@ class ClientZramFocusTest(unittest.TestCase): def test_refocus_restarts_the_delay_and_game_exit_restores_a_packed_client(self): source = SCRIPT.read_text() - start = source.index(' if [ "$_bl_game" = 1 ] && bl_game_focused; then') - stop = source.index(' bl_watch_nap\n', start) + start = source.index(' _dd_focus=1\n') + stop = source.index(' dd_watch_nap\n', start) body = source[start:stop] harness = ''' -_bl_since=-1 _bl_since_apps= _bl_packed=-1 _bl_unpack=0 _bl_apps=" 413150" -_bl_pids=(123) -bl_game_focused() { [ "$focused" = 1 ]; } -bl_over_cap() { return 1; } -bl_client_can_pageout() { return 0; } -bl_client_can_readback() { return 0; } -bl_zram_send() { echo "send:$1"; } +_dd_since=-1 _dd_since_apps= _dd_packed=-1 _dd_unpack=0 _dd_apps=" 413150" +_dd_pids=(123) +dd_game_focused() { [ "$focused" = 1 ]; } +dd_over_cap() { return 1; } +dd_client_can_pageout() { return 0; } +dd_client_can_readback() { return 0; } +dd_zram_send() { echo "send:$1"; } tick() { - SECONDS=$1 _bl_game=$2 focused=$3 + SECONDS=$1 _dd_game=$2 focused=$3 ''' + body + ''' } tick 0 1 1 tick 5 1 0 tick 30 1 1 -echo "refocus:$_bl_packed" +echo "refocus:$_dd_packed" tick 49 1 1 tick 50 1 1 tick 55 1 0 @@ -111,31 +111,31 @@ tick 60 0 0 def monitor_harness(self): source = SCRIPT.read_text() - start = source.index(' bl_zram_scan\n bl_memory_read\n') - stop = source.index(' bl_watch_nap\n', start) + start = source.index(' dd_zram_scan\n dd_memory_read\n') + stop = source.index(' dd_watch_nap\n', start) return ''' -_bl_since=-1 _bl_since_apps= _bl_packed=-1 _bl_measured=-1 _bl_unpack=0 _bl_capped=-1 _bl_backoff=30 -_bl_apps=" 413150" -_bl_pids=(123) +_dd_since=-1 _dd_since_apps= _dd_packed=-1 _dd_measured=-1 _dd_unpack=0 _dd_capped=-1 _dd_backoff=30 +_dd_apps=" 413150" +_dd_pids=(123) step() { :; } -bl_zram_scan() { :; } -bl_memory_read() { :; } -bl_client_pressure() { :; } -bl_client_pressure_finish() { :; } -bl_session_pressure() { :; } -bl_client_can_pageout() { return 0; } -bl_client_can_readback() { [ "${readback:-1}" = 1 ]; } -bl_game_focused() { [ "$focused" = 1 ]; } -bl_cap_due() { [ "$cap_due" = 1 ]; } -bl_over_cap() { [ "$over_cap" = 1 ]; } -bl_zram_send() { echo "send:$1:$3"; } +dd_zram_scan() { :; } +dd_memory_read() { :; } +dd_client_pressure() { :; } +dd_client_pressure_finish() { :; } +dd_session_pressure() { :; } +dd_client_can_pageout() { return 0; } +dd_client_can_readback() { [ "${readback:-1}" = 1 ]; } +dd_game_focused() { [ "$focused" = 1 ] && return 0; [ "$focused" = 2 ] && return 2; return 1; } +dd_cap_due() { [ "$cap_due" = 1 ]; } +dd_over_cap() { [ "$over_cap" = 1 ]; } +dd_zram_send() { echo "send:$1:$3"; } tick() { - SECONDS=$1 _bl_game=$2 focused=$3 over_cap=$4 cap_due=$5 + SECONDS=$1 _dd_game=$2 focused=$3 over_cap=$4 cap_due=$5 ''' + source[start:stop] + '\n}\n' def test_client_toggle_still_disables_automatic_compression(self): result = run_bash(self.monitor_harness() + ''' -BL_ZRAM_CLIENT=0 +DD_ZRAM_CLIENT=0 tick 0 1 1 0 0 tick 25 1 1 0 0 tick 30 0 0 0 0 @@ -147,10 +147,10 @@ tick 30 0 0 0 0 def test_a_new_game_restarts_the_compression_delay(self): result = run_bash(self.monitor_harness() + ''' tick 0 1 1 0 0 -_bl_apps=" 413150 1245620" +_dd_apps=" 413150 1245620" tick 15 1 1 0 0 tick 20 1 1 0 0 -echo "starting:$_bl_packed" +echo "starting:$_dd_packed" tick 34 1 1 0 0 tick 35 1 1 0 0 ''') @@ -160,10 +160,10 @@ tick 35 1 1 0 0 def test_ram_cap_can_still_compress_an_unfocused_client(self): result = run_bash(self.monitor_harness() + ''' -BL_ZRAM_CLIENT=0 BL_RAM_CAP_MB=1024 -bl_zram_usage() { _bl_rss=$((768 * 1024)); } +DD_ZRAM_CLIENT=0 DD_RAM_CAP_MB=1024 +dd_zram_usage() { _dd_rss=$((768 * 1024)); } tick 0 1 0 1 1 -echo "cap:$_bl_packed:$_bl_since:$_bl_backoff" +echo "cap:$_dd_packed:$_dd_since:$_dd_backoff" tick 5 0 0 0 0 ''') self.assertEqual(0, result.returncode, result.stderr) @@ -176,9 +176,9 @@ tick 0 1 1 0 0 tick 20 1 1 0 0 tick 25 1 0 0 0 tick 30 0 0 1 0 -echo "deferred:$_bl_unpack:$_bl_packed" +echo "deferred:$_dd_unpack:$_dd_packed" tick 35 0 0 0 0 -echo "restored:$_bl_unpack" +echo "restored:$_dd_unpack" ''') self.assertEqual(0, result.returncode, result.stderr) self.assertEqual('', result.stderr) @@ -190,15 +190,106 @@ tick 0 1 1 0 0 tick 20 1 1 0 0 readback=0 tick 25 0 0 0 0 -echo "deferred:$_bl_unpack" +echo "deferred:$_dd_unpack" readback=1 tick 30 0 0 0 0 -echo "restored:$_bl_unpack" +echo "restored:$_dd_unpack" """) self.assertEqual(0, result.returncode, result.stderr) self.assertEqual('', result.stderr) self.assertEqual(['send:1:client', 'deferred:1', 'send:0:client', 'restored:0'], result.stdout.splitlines()) + def test_client_in_front_of_a_running_game_is_read_back_and_compressed_again_later(self): + result = run_bash(self.monitor_harness() + ''' +tick 0 1 1 0 0 +tick 20 1 1 0 0 +tick 25 1 0 0 0 +echo "away:$_dd_packed" +tick 30 1 0 0 0 +echo "read:$_dd_packed:$_dd_unpack" +tick 35 1 0 0 0 +tick 40 1 1 0 0 +tick 55 1 1 0 0 +tick 60 1 1 0 0 +echo "again:$_dd_packed" +tick 65 0 0 0 0 +''') + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('', result.stderr) + self.assertEqual(['send:1:client', 'away:20', 'send:0:client', 'read:-1:0', 'send:1:client', 'again:60', 'send:0:client'], + result.stdout.splitlines()) + + def test_unknown_focus_keeps_the_client_compressed(self): + result = run_bash(self.monitor_harness() + ''' +tick 0 1 1 0 0 +tick 20 1 1 0 0 +tick 25 1 2 0 0 +tick 40 1 2 0 0 +echo "unknown:$_dd_packed:$_dd_unpack" +tick 45 1 0 0 0 +tick 48 1 2 0 0 +tick 52 1 0 0 0 +tick 56 1 0 0 0 +echo "flicker:$_dd_packed" +tick 57 1 0 0 0 +echo "read:$_dd_packed" +tick 60 0 2 0 0 +''') + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('', result.stderr) + self.assertEqual(['send:1:client', 'unknown:20:1', 'flicker:20', 'send:0:client', 'read:-1'], + result.stdout.splitlines()) + + def test_a_short_look_at_the_client_keeps_it_compressed(self): + result = run_bash(self.monitor_harness() + ''' +tick 0 1 1 0 0 +tick 20 1 1 0 0 +tick 25 1 0 0 0 +tick 28 1 1 0 0 +tick 30 1 0 0 0 +tick 34 1 0 0 0 +echo "packed:$_dd_packed" +''') + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('', result.stderr) + self.assertEqual(['send:1:client', 'packed:20'], result.stdout.splitlines()) + + def test_client_in_front_waits_for_memory_and_a_ram_cap_keeps_it_compressed(self): + result = run_bash(self.monitor_harness() + ''' +tick 0 1 1 0 0 +tick 20 1 1 0 0 +readback=0 +tick 25 1 0 0 0 +tick 35 1 0 0 0 +echo "tight:$_dd_packed" +readback=1 +tick 40 1 0 0 0 +echo "eased:$_dd_packed" +_dd_ram_cap=1048576 +tick 60 1 1 0 0 +tick 80 1 1 0 0 +tick 85 1 0 0 0 +tick 100 1 0 0 0 +echo "capped:$_dd_packed" +tick 105 0 0 0 0 +''') + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('', result.stderr) + self.assertEqual(['send:1:client', 'tight:20', 'send:0:client', 'eased:-1', 'send:1:client', 'capped:80', 'send:0:client'], + result.stdout.splitlines()) + + def test_client_in_front_without_compression_reads_nothing_back(self): + result = run_bash(self.monitor_harness() + ''' +DD_ZRAM_CLIENT=0 +tick 0 1 1 0 0 +tick 25 1 0 0 0 +tick 40 1 0 0 0 +tick 45 0 0 0 0 +''') + self.assertEqual(0, result.returncode, result.stderr) + self.assertEqual('', result.stderr) + self.assertEqual('', result.stdout) + def test_scan_keeps_the_running_game_and_ignores_steams_own_reaper(self): temp = tempfile.TemporaryDirectory() self.addCleanup(temp.cleanup) @@ -208,18 +299,19 @@ echo "restored:$_bl_unpack" self.write_cmd(root, 30, ['/home/deck/.local/share/Steam/steamrtarm64/steam']) self.write_cmd(root, 40, ['/usr/bin/wine', 'game.exe']) self.write_cmd(root, 50, ['/usr/bin/FEXInterpreter', '/usr/bin/steamwebhelper']) - scan = function_source('bl_zram_scan').replace('for _d in /proc/[0-9]*', 'for _d in "$FAKE"/[0-9]*') - result = run_bash('FAKE=%s\n%s\nbl_zram_scan\necho "game=$_bl_game"\necho "apps=${_bl_apps# }"\necho "pids=${_bl_pids[*]}"\necho "others=${_bl_others[*]}"' % (root, scan)) + scan = function_source('dd_zram_scan').replace('for _d in /proc/[0-9]*', 'for _d in "$FAKE"/[0-9]*') + result = run_bash('FAKE=%s\n%s\ndd_zram_scan\necho "game=$_dd_game"\necho "apps=${_dd_apps# }"\necho "pids=${_dd_pids[*]}"\necho "others=${_dd_others[*]}"' % (root, scan)) self.assertEqual(0, result.returncode, result.stderr) self.assertEqual(['game=1', 'apps=1245620', 'pids=30 50', 'others=40'], result.stdout.splitlines()) def test_focus_must_be_the_running_game(self): - focus = function_source('bl_game_focused') + focus = function_source('dd_game_focused') script = ''' %s check() { - BL_DESKTOP=$1 BL_LAUNCH_DIR=$2 _bl_apps=$3 - if bl_game_focused; then echo yes; else echo no; fi + DD_DESKTOP=$1 DD_LAUNCH_DIR=$2 _dd_apps=$3 + dd_game_focused + echo $? } check "" "$dir" " 413150" check "" "$dir" " 1245620" @@ -227,7 +319,10 @@ printf '%%s\\n' '{"focusedApp": 999}' > "$dir/agent/focus.json" check "" "$dir" " 413150" printf '%%s\\n' '{"focusedApp": 769}' > "$dir/agent/focus.json" check "" "$dir" " 413150" +printf '%%s\\n' '{"t": 2}' > "$dir/agent/focus.json" +check "" "$dir" " 413150" rm -f "$dir/agent/focus.json" +check "" "$dir" " 413150" check 1 "$dir" " 413150" check "" "" " 413150" ''' % focus @@ -238,7 +333,7 @@ check "" "" " 413150" (launch / 'agent' / 'focus.json').write_text('{"t": 1, "focusedApp": 413150}\n') result = run_bash('dir=%s\n%s' % (launch, script)) self.assertEqual(0, result.returncode, result.stderr) - self.assertEqual(['yes', 'no', 'no', 'no', 'yes', 'yes'], result.stdout.splitlines()) + self.assertEqual(['0', '1', '1', '1', '2', '2', '0', '0'], result.stdout.splitlines()) @staticmethod def write_cmd(root, pid, args): diff --git a/tools/tests/test_clock_pause_preload.py b/tools/tests/test_clock_pause_preload.py index 06ddd65a49..3d3f0dd76b 100644 --- a/tools/tests/test_clock_pause_preload.py +++ b/tools/tests/test_clock_pause_preload.py @@ -15,12 +15,12 @@ PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload" def clock_reset_command(control): script = (PRELOAD.parent / "overlay/usr/local/bin/droiddeck-session").read_text() - start = script.index('if [ -z "${BL_INSIDE:-}" ]; then\n if [ "${BL_ZRAM:-0}"') + start = script.index('if [ -z "${DD_INSIDE:-}" ]; then\n if [ "${DD_ZRAM:-0}"') end = script.index("\nfi", start) + len("\nfi") - paths = {"/tmp/.bl-clock": shlex.quote(str(control)), - "/tmp/.bl-zram": shlex.quote(str(control.parent / "zram"))} + paths = {"/tmp/.dd-clock": shlex.quote(str(control)), + "/tmp/.dd-zram": shlex.quote(str(control.parent / "zram"))} pattern = "|".join(re.escape(token) for token in paths) - return 'BL_INSIDE=; BL_ZRAM=0; ' + re.sub(pattern, lambda match: paths[match.group(0)], script[start:end]) + return 'DD_INSIDE=; DD_ZRAM=0; ' + re.sub(pattern, lambda match: paths[match.group(0)], script[start:end]) PROGRAM = r""" #define _GNU_SOURCE @@ -120,8 +120,8 @@ class ClockPausePreloadTest(unittest.TestCase): build = cls.dir / "build" build.mkdir() (build / "program.c").write_text(PROGRAM) - cls.preload = build / "libblsession.so" - subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-DBL_CLOCK_ANY_ARCH", + cls.preload = build / "libddsession.so" + subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-DDD_CLOCK_ANY_ARCH", '-DCP_CTL="%s"' % cls.control, "-o", str(cls.preload), *map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True) cls.shell = build / "plasmashell" @@ -259,7 +259,7 @@ class ClockResetCommandTest(unittest.TestCase): def test_reset_does_not_rewrite_placeholders_inside_substituted_paths(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) - folder = root / "tmp/.bl-zram/$(touch injected)" + folder = root / "tmp/.dd-zram/$(touch injected)" folder.mkdir(parents=True) control = folder / "clock" control.write_bytes(struct.pack("" + card.mkdir() + usb.mkdir() + missing = self.home / "unplugged" + entries = [{"path": str(card), "label": "Card"}, {"path": str(usb), "label": "USB & "}, + {"path": str(missing), "label": "Gone"}, {"path": "relative", "label": "Invalid"}] + volumes = self.volumes(entries) + self.assertEqual({card.as_uri(): "Card", usb.as_uri(): "USB & "}, volumes) + root = self.update_volumes(volumes) + self.assertEqual(2, len(root.findall("bookmark"))) + self.assertEqual("USB & ", root.findall("bookmark")[1].findtext("title")) + self.assertFalse((card / "steamapps").exists()) + self.assertEqual("drive-removable-media", root.find("bookmark/info/metadata/{" + MODULE["ICON_NS"] + "}icon").get("name")) + + def test_main_adds_volumes_without_changing_gtk_or_steam_selection(self): + card = self.home / "card" + card.mkdir() + self.volumes([{"path": str(card), "label": "Card"}]) + with patch.object(Path, "home", return_value=self.home), patch.dict(os.environ, {"XDG_DATA_HOME": str(self.data)}): + MODULE["main"]() + root = ET.parse(self.places).getroot() + self.assertEqual({self.steam.as_uri(), card.as_uri()}, {b.get("href") for b in root.findall("bookmark")}) + self.assertFalse((self.home / ".config/gtk-3.0/bookmarks").exists()) + self.volumes([]) + MODULE["main"]() + root = ET.parse(self.places).getroot() + self.assertEqual([self.steam.as_uri()], [b.get("href") for b in root.findall("bookmark")]) + + def test_unreadable_volume_is_not_offered(self): + card = self.home / "card" + card.mkdir() + with patch("os.scandir", side_effect=PermissionError): + self.assertEqual({}, self.volumes([{"path": str(card), "label": "Card"}])) + + def test_volume_refresh_preserves_steam_personal_and_hidden_places(self): + card = self.home / "card" + card.mkdir() + self.update({self.steam.as_uri(): "Steam"}) + root = self.update_volumes({card.as_uri(): "Card"}) + volume = root.findall("bookmark")[1] + metadata = volume.find("info/metadata[@owner='http://www.kde.org']") + ET.SubElement(metadata, "IsHidden").text = "true" + ET.SubElement(root, "bookmark", {"href": "file:///root/Documents"}) + self.places.write_bytes(ET.tostring(root)) + root = self.update_volumes({card.as_uri(): "Renamed"}) + self.assertEqual("true", root.findall("bookmark")[1].findtext("info/metadata/IsHidden")) + before = self.places.read_bytes() + self.update_volumes({card.as_uri(): "Renamed"}) + self.assertEqual(before, self.places.read_bytes()) + self.update({self.steam.as_uri(): "Steam"}) + root = self.update_volumes({}) + self.assertEqual([self.steam.as_uri(), "file:///root/Documents"], [b.get("href") for b in root.findall("bookmark")]) + + def test_personal_volume_place_is_not_duplicated_or_removed(self): + card = self.home / "card" + card.mkdir() + self.places.write_text(f'My card') + before = self.places.read_bytes() + self.update_volumes({card.as_uri(): "Card"}) + self.update_volumes({}) + self.assertEqual(before, self.places.read_bytes()) + def test_invalid_xml_is_not_overwritten(self): self.places.write_text("unfinished") with self.assertRaises(ET.ParseError): diff --git a/tools/tests/test_desktop_gpu_window.py b/tools/tests/test_desktop_gpu_window.py index 5a1ccb5ff4..860b23f63c 100644 --- a/tools/tests/test_desktop_gpu_window.py +++ b/tools/tests/test_desktop_gpu_window.py @@ -10,7 +10,7 @@ import unittest TOOLS = Path(__file__).resolve().parents[1] GPU = TOOLS / "linuxfs/desktop/droiddeck-gpu" WINDOW = TOOLS / "linuxfs/overlay/usr/local/bin/droiddeck-gpu-window" -KEYS = ("MESA_VK_WSI_DEBUG", "SDL_VIDEODRIVER", "WAYLAND_DISPLAY", "BL_GPU_CHILD_WSI", "BL_DESKTOP_GPU_CHILD") +KEYS = ("MESA_VK_WSI_DEBUG", "SDL_VIDEODRIVER", "WAYLAND_DISPLAY", "DD_GPU_CHILD_WSI", "DD_DESKTOP_GPU_CHILD") class DesktopGpuWindowTest(unittest.TestCase): @@ -24,8 +24,8 @@ class DesktopGpuWindowTest(unittest.TestCase): fake.chmod(0o755) def run_gpu(self, **env): - base = {k: v for k, v in os.environ.items() if k not in KEYS + ("BL_DEBUG_DIR", "BL_DESKTOP_GPU_WINDOW")} - base.update(PATH="%s:%s" % (self.tmp, os.environ["PATH"]), BL_WIDTH="1280", BL_HEIGHT="720", **env) + base = {k: v for k, v in os.environ.items() if k not in KEYS + ("DD_DEBUG_DIR", "DD_DESKTOP_GPU_WINDOW")} + base.update(PATH="%s:%s" % (self.tmp, os.environ["PATH"]), DD_WIDTH="1280", DD_HEIGHT="720", **env) subprocess.run(["bash", str(GPU), "game.exe"], env=base, check=True, capture_output=True) return json.loads(self.out.read_text()) @@ -38,30 +38,30 @@ class DesktopGpuWindowTest(unittest.TestCase): self.assertEqual(run["env"]["WAYLAND_DISPLAY"], "wayland-1") self.assertEqual(run["env"]["SDL_VIDEODRIVER"], "wayland") self.assertEqual(run["env"]["MESA_VK_WSI_DEBUG"], "sw") - self.assertEqual(run["env"]["BL_GPU_CHILD_WSI"], "linear") - self.assertEqual(run["env"]["BL_DESKTOP_GPU_CHILD"], "1") + self.assertEqual(run["env"]["DD_GPU_CHILD_WSI"], "linear") + self.assertEqual(run["env"]["DD_DESKTOP_GPU_CHILD"], "1") def test_full_screen_stays_available(self): - for env in ({"WAYLAND_DISPLAY": "wayland-1", "BL_DESKTOP_GPU_WINDOW": "0"}, {"WAYLAND_DISPLAY": "wayland-0"}, {}): + for env in ({"WAYLAND_DISPLAY": "wayland-1", "DD_DESKTOP_GPU_WINDOW": "0"}, {"WAYLAND_DISPLAY": "wayland-0"}, {}): run = self.run_gpu(**env) self.assertEqual(run["args"][:2], ["--backend", "wayland"]) self.assertNotIn("--follow-game-window-mode", run["args"]) self.assertIn("-f", run["args"]) self.assertEqual(run["env"]["WAYLAND_DISPLAY"], "wayland-0") self.assertIsNone(run["env"]["MESA_VK_WSI_DEBUG"]) - self.assertIsNone(run["env"]["BL_GPU_CHILD_WSI"]) + self.assertIsNone(run["env"]["DD_GPU_CHILD_WSI"]) def test_the_game_inside_the_window_gets_its_own_settings_back(self): script = "import json, os; print(json.dumps({k: os.environ.get(k) for k in %r}))" % (KEYS,) for saved, expected in (("linear", "linear"), ("", None)): env = {k: v for k, v in os.environ.items() if k not in KEYS + ("DISPLAY",)} - env.update(BL_GPU_CHILD_WSI=saved, MESA_VK_WSI_DEBUG="sw", SDL_VIDEODRIVER="wayland") + env.update(DD_GPU_CHILD_WSI=saved, MESA_VK_WSI_DEBUG="sw", SDL_VIDEODRIVER="wayland") out = subprocess.run([sys.executable, str(WINDOW), sys.executable, "-c", script], env=env, check=True, capture_output=True, text=True).stdout child = json.loads(out) self.assertEqual(child["MESA_VK_WSI_DEBUG"], expected) self.assertEqual(child["SDL_VIDEODRIVER"], "x11") - self.assertIsNone(child["BL_GPU_CHILD_WSI"]) + self.assertIsNone(child["DD_GPU_CHILD_WSI"]) def test_outside_a_window_the_game_keeps_its_settings(self): script = "import os; print(os.environ.get('MESA_VK_WSI_DEBUG'), os.environ.get('SDL_VIDEODRIVER'))" diff --git a/tools/tests/test_desktop_ime.py b/tools/tests/test_desktop_ime.py index 7062e8c09b..d74ded7225 100644 --- a/tools/tests/test_desktop_ime.py +++ b/tools/tests/test_desktop_ime.py @@ -27,7 +27,7 @@ class DesktopImeTest(unittest.TestCase): self.session = Path(self.temp.name) self.server, client = socket.socketpair(socket.AF_UNIX, socket.SOCK_STREAM) self.addCleanup(self.server.close) - env = dict(os.environ, BL_LAUNCH_DIR=str(self.session), WAYLAND_SOCKET=str(client.fileno())) + env = dict(os.environ, DD_LAUNCH_DIR=str(self.session), WAYLAND_SOCKET=str(client.fileno())) self.proc = subprocess.Popen(['python3', str(IME)], env=env, pass_fds=[client.fileno()], stderr=subprocess.PIPE, text=True) client.close() diff --git a/tools/tests/test_desktop_open.py b/tools/tests/test_desktop_open.py index a7840cfa53..c05a12114a 100644 --- a/tools/tests/test_desktop_open.py +++ b/tools/tests/test_desktop_open.py @@ -67,7 +67,7 @@ class PlacementTest(Temp): patcher = mock.patch.dict(OPEN, {"GPU": str(self.gpu), "unattended": lambda env: False}) patcher.start() self.addCleanup(patcher.stop) - self.desktop = {"BL_DESKTOP": "1"} + self.desktop = {"DD_DESKTOP": "1"} def placed(self, what, mode, env=None): return OPEN["placed"](["cmd"], what, mode, self.desktop if env is None else env) @@ -110,7 +110,7 @@ class UnattendedTest(Temp): def test_only_output_nobody_reads_counts(self): log = self.write("session/desktop.log", b"") - env = {"BL_DEBUG_DIR": str(log.parent)} + env = {"DD_DEBUG_DIR": str(log.parent)} self.assertTrue(self.with_stdout(os.devnull, env)) self.assertTrue(self.with_stdout(str(log), env)) self.assertFalse(self.with_stdout(str(self.tmp / "out.txt"), env)) @@ -209,7 +209,7 @@ class ImportTest(Temp): worker = threading.Thread(target=app) worker.start() - with mock.patch.dict(os.environ, {"BL_LAUNCH_DIR": str(launch)}), mock.patch.dict(OPEN, {"notify": lambda *a: None}): + with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": str(launch)}), mock.patch.dict(OPEN, {"notify": lambda *a: None}): self.assertEqual(OPEN["imported"]("appimage", "/root/Storage/Eden.AppImage", "0123456789abcdef", "Eden"), str(folder)) worker.join() self.assertEqual(list(launch.iterdir()), []) @@ -218,12 +218,12 @@ class ImportTest(Temp): launch = self.tmp / "launch" launch.mkdir() (launch / "desktop-import-0123456789abcdef.result").write_text("error Not enough space\n") - with mock.patch.dict(os.environ, {"BL_LAUNCH_DIR": str(launch)}), mock.patch.dict(OPEN, {"notify": lambda *a: None}): + with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": str(launch)}), mock.patch.dict(OPEN, {"notify": lambda *a: None}): with self.assertRaisesRegex(RuntimeError, "^Not enough space$"): OPEN["imported"]("appimage", "/x.AppImage", "0123456789abcdef", "x") def test_outside_a_session_it_says_how_to_add_one(self): - with mock.patch.dict(os.environ, {"BL_LAUNCH_DIR": ""}): + with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": ""}): with self.assertRaisesRegex(RuntimeError, "Add an app"): OPEN["imported"]("folder", "/x/start.sh", "0123456789abcdef", "x") @@ -332,7 +332,7 @@ class GameFolderTest(Temp): worker = threading.Thread(target=app) worker.start() imports = {what: (str(self.tmp / "none"), made) for what, (_, made) in OPEN["IMPORTS"].items()} - with mock.patch.dict(os.environ, {"BL_LAUNCH_DIR": str(launch)}), \ + with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": str(launch)}), \ mock.patch.dict(OPEN, {"CACHE": str(self.tmp / "cache"), "IMPORTS": imports, "notify": lambda *a: None}): self.assertEqual(OPEN["command"](str(script), ["-x"], "folder"), ([OPEN["SCRIPT_RUN"], str(copy), "-x"], str(script.parent))) worker.join() @@ -348,7 +348,7 @@ class ExecTest(Temp): self.write("storage/Download/Game/helper.bin", elf(183), 0o755) self.write("storage/Download/Game/libhelper.so", elf(183)) self.copied = [] - env = {k: v for k, v in os.environ.items() if k not in ("BL_DESKTOP", "BL_BINFMT", "GAMESCOPE_WAYLAND_DISPLAY")} + env = {k: v for k, v in os.environ.items() if k not in ("DD_DESKTOP", "DD_BINFMT", "GAMESCOPE_WAYLAND_DISPLAY")} for patcher in (mock.patch.dict(OPEN, {"noexec": lambda path: True, "storage_root": lambda folder: str(self.storage), "copied_in": lambda path: self.copied.append(path) or "/opt/droiddeck-apps/game", "steam_title": lambda path: None, "notify": lambda *a: None, @@ -377,7 +377,7 @@ class ExecTest(Temp): def test_an_x86_program_a_running_program_starts_runs_under_fex_where_it_lies(self): program = str(self.storage / "Download/Game/game.x86_64") - for env in ({}, {"BL_BINFMT": "1"}): + for env in ({}, {"DD_BINFMT": "1"}): with self.subTest(env=env): self.assertEqual(self.open("--exec", program, "-x", env=env), [OPEN["FEX"], "run", "--mode", "auto", "--", program, "-x"]) self.assertEqual(self.copied, []) @@ -385,7 +385,7 @@ class ExecTest(Temp): def test_an_in_place_hand_off_keeps_the_callers_working_folder(self): program = str(self.storage / "Download/Game/game.x86_64") with mock.patch("os.chdir") as chdir: - self.open("--exec", program, env={"BL_BINFMT": "1"}) + self.open("--exec", program, env={"DD_BINFMT": "1"}) chdir.assert_not_called() self.open("--exec", str(self.storage / "Download/Game/helper.bin")) chdir.assert_called_once() @@ -397,7 +397,7 @@ class ExecTest(Temp): def test_opening_an_x86_program_from_the_desktop_still_copies_its_folder_in(self): program = str(self.storage / "Download/Game/game.x86_64") - self.assertEqual(self.open(program, env={"BL_DESKTOP": "1"}), [OPEN["SCRIPT_RUN"], "/opt/droiddeck-apps/game"]) + self.assertEqual(self.open(program, env={"DD_DESKTOP": "1"}), [OPEN["SCRIPT_RUN"], "/opt/droiddeck-apps/game"]) self.assertEqual(self.copied, [program]) @@ -681,7 +681,7 @@ class ProtonRunTest(Temp): appid = OPEN["steam_title"](program) self.assertEqual(appid, "413150") self.assertEqual(OPEN["command"](program, [], "steam", appid=appid)[0], [OPEN["STEAM_LAUNCH"], "desktop", "413150"]) - self.assertEqual(OPEN["placed"](["launch"], "steam", "run", {"BL_DESKTOP": "1"}), ["launch"]) + self.assertEqual(OPEN["placed"](["launch"], "steam", "run", {"DD_DESKTOP": "1"}), ["launch"]) self.assertIsNone(OPEN["steam_title"](str(self.write("Download/winemine.exe", b"MZ")))) def test_a_linux_steam_games_program_goes_to_steam_too(self): @@ -709,6 +709,7 @@ class ProtonRunTest(Temp): self.assertEqual(entry, str(self.root / "compatibilitytools.d/droiddeck-proton-11-arm64/droiddeck-proton")) self.assertEqual(argv, [entry, "waitforexitandrun", str(program), "-fullscreen"]) self.assertEqual(env["SteamAppId"], "413150") + self.assertEqual(env["DROIDDECK_DESKTOP_PROGRAM"], str(program)) self.assertTrue((self.root / "steamapps/compatdata/413150").is_dir()) def run_main(self, argv): @@ -737,6 +738,7 @@ class ProtonRunTest(Temp): self.assertEqual((env["SteamAppId"], env["STEAM_COMPAT_DATA_PATH"]), ("413150", str(self.root / "steamapps/compatdata/413150"))) self.assertEqual(dirs, [str(program.parent)]) + self.assertNotIn("DROIDDECK_DESKTOP_PROGRAM", env) def test_without_steam_a_game_steam_cannot_start_is_refused(self): self.write("Steam/appcache/appinfo.vdf", appinfo({413150: STARDEW})) diff --git a/tools/tests/test_desktop_pipewire.py b/tools/tests/test_desktop_pipewire.py index 6de6b9e802..03cebcb8c6 100644 --- a/tools/tests/test_desktop_pipewire.py +++ b/tools/tests/test_desktop_pipewire.py @@ -29,7 +29,7 @@ pipewire() { fi } ''' + block + ('echo "env:${PW_ENV:-unset}"\n' if probe_env else '') - environment = dict(os.environ, BL_BOTTOM_DESKTOP='1' if bottom else '0', + environment = dict(os.environ, DD_BOTTOM_DESKTOP='1' if bottom else '0', PW_START_STATUS=str(start_status)) result = subprocess.run(['bash', '-c', script], env=environment, capture_output=True, text=True, timeout=5) @@ -38,11 +38,9 @@ pipewire() { def test_desktop_serves_pipewire_before_plasma_and_stops_it_after(self): start = DESKTOP.index(HELPER + ' start') - env = DESKTOP.index(HELPER + ' env') plasma = DESKTOP.index('dbus-run-session -- startplasma-wayland') stop = DESKTOP.index(HELPER + ' stop') - self.assertLess(start, env) - self.assertLess(env, plasma) + self.assertLess(start, plasma) self.assertLess(plasma, stop) self.assertLess(stop, DESKTOP.index('droiddeck-steam-launch bigpicture')) @@ -51,23 +49,24 @@ pipewire() { self.assertIn('if [ "$mode" = steam ]; then\n if ' + HELPER + ' start', SESSION) def test_bottom_desktop_starts_and_stops_its_pipewire_service(self): - self.assertIn('export BL_BOTTOM_DESKTOP=1', BOTTOM_DESKTOP) - self.assertLess(BOTTOM_DESKTOP.index('export BL_BOTTOM_DESKTOP=1'), + self.assertIn('export DD_BOTTOM_DESKTOP=1', BOTTOM_DESKTOP) + self.assertLess(BOTTOM_DESKTOP.index('export DD_BOTTOM_DESKTOP=1'), BOTTOM_DESKTOP.index('exec /usr/local/bin/droiddeck-desktop')) self.assertIn('File(context.filesDir, ".wayland-rt-bottom")', BOTTOM_SESSION) - self.assertNotIn('if [ "${BL_BOTTOM_DESKTOP:-0}" != 1 ]; then', DESKTOP) + self.assertNotIn('if [ "${DD_BOTTOM_DESKTOP:-0}" != 1 ]; then', DESKTOP) for bottom in (False, True): self.assertEqual(['call:start'], self.run_lifecycle_block( - 'if ' + HELPER + ' start', + 'if ! ' + HELPER + ' start', 'echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"', bottom)) self.assertEqual(['call:stop'], self.run_lifecycle_block( HELPER + ' stop', 'echo "== droiddeck-desktop: Plasma ended ($rc)"', bottom)) - def test_successful_start_exports_the_client_environment(self): + def test_plasma_keeps_the_rootfs_pipewire_client_settings(self): + self.assertNotIn(HELPER + ' env', DESKTOP) for bottom in (False, True): - self.assertEqual(['call:start', 'env:set'], self.run_lifecycle_block( - 'if ' + HELPER + ' start', + self.assertEqual(['call:start', 'env:unset'], self.run_lifecycle_block( + 'if ! ' + HELPER + ' start', 'echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"', bottom, probe_env=True)) def test_failed_start_reports_it_and_leaves_the_environment_alone(self): @@ -75,7 +74,7 @@ pipewire() { self.assertEqual( ['call:start', '== pipewire: not running; screen capture has no picture', 'env:unset'], self.run_lifecycle_block( - 'if ' + HELPER + ' start', + 'if ! ' + HELPER + ' start', 'echo "== droiddeck-desktop: Plasma on $WAYLAND_DISPLAY"', bottom, start_status=1, probe_env=True)) diff --git a/tools/tests/test_desktop_program_diagnostics.py b/tools/tests/test_desktop_program_diagnostics.py new file mode 100644 index 0000000000..aafb89d20b --- /dev/null +++ b/tools/tests/test_desktop_program_diagnostics.py @@ -0,0 +1,121 @@ +import contextlib +import io +import os +from pathlib import Path +import runpy +import subprocess +import sys +import tempfile +import unittest + + +BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin" +DEBUG = runpy.run_path(str(BIN / "droiddeck-game-debug")) + + +class DesktopProgramDiagnosticsTest(unittest.TestCase): + def launch(self, folder, desktop=True, **settings): + env = dict(os.environ, DD_DEBUG_DIR=folder, WINEDEBUG="-all", PROTON_LOG="0") + env.pop("DROIDDECK_DESKTOP_PROGRAM", None) + if desktop: + env["DROIDDECK_DESKTOP_PROGRAM"] = "managed.exe" + env.update(settings) + child = "import os,sys; print(os.environ['WINEDEBUG']); sys.stderr.write('err:mscoree:CLRRuntimeInfo_GetRuntimeHost Wine Mono is not installed\\n'); sys.exit(7)" + wrapper = "import runpy,sys; g=runpy.run_path(sys.argv[1]); sys.exit(g['start']([sys.executable,'-c',sys.argv[2]],dict(__import__('os').environ),None))" + return subprocess.run([sys.executable, "-c", wrapper, str(BIN / "droiddeck-game-env"), child], + env=env, capture_output=True, text=True, timeout=15) + + def test_desktop_failure_keeps_reason_and_exit_status(self): + with tempfile.TemporaryDirectory() as folder: + result = self.launch(folder) + self.assertEqual(result.returncode, 7) + self.assertEqual(result.stdout.strip(), "-all,err+all,+mscoree,+loaddll") + logs = list(Path(folder).glob("desktop-program-*.log")) + self.assertEqual(len(logs), 1) + self.assertIn("Wine Mono is not installed", logs[0].read_text()) + self.assertIn("Wine Mono is not installed", result.stderr) + self.assertIn("exited with status 7", result.stderr) + + def test_games_and_explicit_debug_settings_stay_unchanged(self): + with tempfile.TemporaryDirectory() as folder: + ordinary = self.launch(folder, desktop=False) + self.assertEqual(ordinary.stdout.strip(), "-all") + self.assertEqual(list(Path(folder).glob("*.log")), []) + opted_in = self.launch(folder, PROTON_LOG="1", WINEDEBUG="+relay") + self.assertEqual(opted_in.stdout.strip(), "+relay") + self.assertEqual(list(Path(folder).glob("*.log")), []) + explicit = self.launch(folder, WINEDEBUG="-all,err+module") + self.assertEqual(explicit.stdout.strip(), "-all,err+module") + + def test_unavailable_log_directory_does_not_stop_program(self): + with tempfile.TemporaryDirectory() as folder: + result = self.launch(str(Path(folder) / "missing")) + self.assertEqual(result.returncode, 7) + self.assertEqual(result.stdout.strip(), "-all") + self.assertIn("diagnostics unavailable", result.stderr) + + def test_capped_log_drains_after_limit_and_preserves_following_output(self): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "program.log" + output, thread = DEBUG["capped_log"](str(path), 1024) + try: + child = subprocess.Popen([sys.executable, "-c", + "import os; os.write(2,b'x'*2097152); print('completed')"], + stderr=output, stdout=subprocess.PIPE, text=True) + stdout, _ = child.communicate(timeout=10) + self.assertEqual(child.returncode, 0) + self.assertEqual(stdout.strip(), "completed") + finally: + os.close(output) + thread.join(timeout=2) + self.assertFalse(thread.is_alive()) + self.assertEqual(path.read_bytes(), b"x" * 1024) + + def test_capped_log_continues_mirroring_after_file_limit_and_survives_mirror_errors(self): + with tempfile.TemporaryDirectory() as folder: + path = Path(folder) / "mirrored.log" + mirrored = io.StringIO() + with contextlib.redirect_stderr(mirrored): + output, thread = DEBUG["capped_log"](str(path), 4, mirror=True) + try: + os.write(output, b"abcdef") + finally: + os.close(output) + thread.join(timeout=2) + self.assertEqual(path.read_bytes(), b"abcd") + self.assertEqual(mirrored.getvalue(), "abcdef") + + def test_desktop_logs_have_unique_names_and_a_hard_byte_limit(self): + with tempfile.TemporaryDirectory() as folder, contextlib.redirect_stderr(io.StringIO()): + env = {"DROIDDECK_DESKTOP_PROGRAM": "managed.exe", "DD_DEBUG_DIR": folder} + for _ in range(2): + with DEBUG["desktop_program_logs"](env) as (launch_env, output): + self.assertNotIn("DROIDDECK_DESKTOP_PROGRAM", launch_env) + child = subprocess.Popen([sys.executable, "-c", "import os; os.write(2,b'x'*2097152)"], stderr=output) + self.assertEqual(child.wait(timeout=10), 0) + logs = list(Path(folder).glob("desktop-program-*.log")) + self.assertEqual(len(logs), 2) + self.assertTrue(all(path.stat().st_size == 1048576 for path in logs)) + + def test_broken_stderr_does_not_abort_launch_or_replace_exit_status(self): + class BrokenStderr: + def write(self, data): + raise BrokenPipeError("closed") + + def flush(self): + raise BrokenPipeError("closed") + + game_env = runpy.run_path(str(BIN / "droiddeck-game-env")) + with tempfile.TemporaryDirectory() as folder: + env = dict(os.environ, DD_DEBUG_DIR=folder, WINEDEBUG="-all", PROTON_LOG="0", + DROIDDECK_DESKTOP_PROGRAM="managed.exe") + with contextlib.redirect_stderr(BrokenStderr()): + code = game_env["start"]( + [sys.executable, "-c", "import sys; sys.stderr.write('err:child_line\\n'); sys.exit(7)"], + env, + None, + ) + self.assertEqual(code, 7) + logs = list(Path(folder).glob("desktop-program-*.log")) + self.assertEqual(len(logs), 1) + self.assertIn("err:child_line", logs[0].read_text()) diff --git a/tools/tests/test_diagnostic_session_integration.py b/tools/tests/test_diagnostic_session_integration.py index 2b55199092..6ec12727ee 100644 --- a/tools/tests/test_diagnostic_session_integration.py +++ b/tools/tests/test_diagnostic_session_integration.py @@ -23,10 +23,10 @@ class DiagnosticSessionIntegrationTest(unittest.TestCase): helper.chmod(0o755) env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'], MARKER=str(marker), DROIDDECK_ENHANCED_DIAGNOSTICS='1' if enabled else '0') - env['BL_INSIDE'] = '1' if inside else '' + env['DD_INSIDE'] = '1' if inside else '' script = match.group() + '\nstart_diagnostic_inventory\n' if installed and enabled and not inside: - script += 'wait "$_bl_diagnostic_inventory"\n' + script += 'wait "$_dd_diagnostic_inventory"\n' result = subprocess.run(['bash', '-c', script], env=env, capture_output=True, text=True, timeout=10) self.assertEqual(result.returncode, 0, result.stderr) return marker.read_text().splitlines() if marker.exists() else [], result.stdout diff --git a/tools/tests/test_dircache_preload.py b/tools/tests/test_dircache_preload.py index f7b2d9008a..9435922b40 100644 --- a/tools/tests/test_dircache_preload.py +++ b/tools/tests/test_dircache_preload.py @@ -326,7 +326,7 @@ class DirCachePreloadTest(unittest.TestCase): build.mkdir() (build / "fake.c").write_text(FAKE) (build / "program.c").write_text(PROGRAM) - cls.cache = build / "libblsession.so" + cls.cache = build / "libddsession.so" cls.fake = build / "fake.so" subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(cls.cache), *map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True) @@ -688,7 +688,7 @@ class DirCachePreloadTest(unittest.TestCase): def test_misses_reach_the_filesystem_when_turned_off(self): s = self.staging out = self.run_program("list", s, "access", s / "x.bundle", "access", s / "y.bundle", "accesses", - env={"BL_NO_DIR_CACHE": "1"}) + env={"DD_NO_DIR_CACHE": "1"}) self.assertEqual(["-1 2", "-1 2", "2"], out[1:]) def test_a_preload_below_calling_back_while_a_folder_is_watched_does_not_hang(self): @@ -706,7 +706,7 @@ class DirCachePreloadTest(unittest.TestCase): self.assertEqual(["a.bundle,b.bundle", "b.bundle", "b.bundle", "1"], out) def test_can_be_turned_off(self): - out = self.run_program("list", self.staging, "list", self.staging, "opens", env={"BL_NO_DIR_CACHE": "1"}) + out = self.run_program("list", self.staging, "list", self.staging, "opens", env={"DD_NO_DIR_CACHE": "1"}) self.assertEqual("2", out[-1]) diff --git a/tools/tests/test_droiddeck_agent.py b/tools/tests/test_droiddeck_agent.py index a1adca90c6..a84a54ca8b 100644 --- a/tools/tests/test_droiddeck_agent.py +++ b/tools/tests/test_droiddeck_agent.py @@ -203,7 +203,7 @@ class AgentTest(unittest.TestCase): def tag(self, wins, arch="arm64"): snap = {"displays": {":0": [], ":1": wins}} - with patch.dict(os.environ, {"DISPLAY": ":0", "BL_STEAM_CLIENT_ARCH": arch}), \ + with patch.dict(os.environ, {"DISPLAY": ":0", "DD_STEAM_CLIENT_ARCH": arch}), \ patch.object(agent.subprocess, "run") as run, patch.object(agent, "log"): run.return_value.returncode = 0 tagged = agent.tag_game_windows(snap, proc=self.dir / "proc") @@ -349,7 +349,7 @@ class AgentTest(unittest.TestCase): connect.assert_not_called() def test_cdp_without_a_port(self): - os.environ.pop("BL_CDP_PORT", None) + os.environ.pop("DD_CDP_PORT", None) self.assertEqual("NO_DEVTOOLS", self.ask({"kind": "cdp", "expression": "1"})["error"]["code"]) def test_cdp_eval(self): @@ -448,7 +448,7 @@ class AgentTest(unittest.TestCase): def test_shortcut_state_command_exits_with_the_state(self): game_id = str((3333273269 << 32) | 0x02000000) launch = self.dir.parent - with patch.dict(os.environ, {"BL_LAUNCH_DIR": str(launch)}): + with patch.dict(os.environ, {"DD_LAUNCH_DIR": str(launch)}): for state, code in (("ready", 0), ("missing", 4), ("not-shortcut", 3), ("loading", 1)): with self.subTest(state=state), patch.object(agent, "steam_shortcut_state", return_value=state) as ask: self.assertEqual(code, agent.main(["--steam-shortcut-state", game_id, "2"])) @@ -478,7 +478,7 @@ class AgentTest(unittest.TestCase): agent.steam_clear_pending_interstitial(self.dir, "0") def test_asleep_command_reports_steams_own_sleep_state(self): - with patch.dict(os.environ, {"BL_LAUNCH_DIR": str(self.dir.parent)}): + with patch.dict(os.environ, {"DD_LAUNCH_DIR": str(self.dir.parent)}): for value, code in (("yes", 0), ("no", 5), ("unknown", 1), (None, 1)): with self.subTest(value=value), patch.object(agent, "cdp_eval", return_value={"value": value}) as ask: self.assertEqual(code, agent.main(["--steam-asleep"])) @@ -488,7 +488,7 @@ class AgentTest(unittest.TestCase): self.assertEqual(1, agent.main(["--steam-asleep"])) def test_supports_vr_command_separates_vr_flat_and_unknown_apps(self): - with patch.dict(os.environ, {"BL_LAUNCH_DIR": str(self.dir.parent)}): + with patch.dict(os.environ, {"DD_LAUNCH_DIR": str(self.dir.parent)}): for value, code in ((True, 0), (False, 5), (None, 1)): with self.subTest(value=value), patch.object(agent, "cdp_eval", return_value={"value": value}) as ask: self.assertEqual(code, agent.main(["--steam-supports-vr", "204360"])) @@ -500,7 +500,7 @@ class AgentTest(unittest.TestCase): self.assertEqual(2, agent.main(["--steam-supports-vr"] + bad)) def test_idle_inhibit_command_reports_whether_steam_reached_the_state(self): - with patch.dict(os.environ, {"BL_LAUNCH_DIR": str(self.dir.parent)}): + with patch.dict(os.environ, {"DD_LAUNCH_DIR": str(self.dir.parent)}): for value, code in ((True, 0), (False, 1), (None, 1)): with self.subTest(value=value), patch.object(agent, "cdp_eval", return_value={"value": value}) as ask: self.assertEqual(code, agent.main(["--steam-idle-inhibit", "on"])) @@ -522,7 +522,7 @@ class AgentTest(unittest.TestCase): self.assertEqual(900, agent.steam_idle_suspend_seconds(self.dir, vpower)) with patch.object(agent, "cdp_eval", return_value={"value": None}): self.assertIsNone(agent.steam_idle_suspend_seconds(self.dir, vpower)) - with patch.dict(os.environ, {"BL_LAUNCH_DIR": str(self.dir.parent)}), \ + with patch.dict(os.environ, {"DD_LAUNCH_DIR": str(self.dir.parent)}), \ patch.object(agent, "steam_idle_suspend_seconds", return_value=None): self.assertEqual(1, agent.main(["--steam-idle-suspend-seconds"])) @@ -538,7 +538,7 @@ class AgentTest(unittest.TestCase): def test_serve_answers_request_files(self): server = subprocess.Popen([sys.executable, str(SCRIPT), "--no-focus"], - env=dict(os.environ, BL_LAUNCH_DIR=str(self.dir)), + env=dict(os.environ, DD_LAUNCH_DIR=str(self.dir)), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) def stop_server(): server.terminate() @@ -867,6 +867,82 @@ const value = subscribe => { return e +class FocusSnapshotTest(unittest.TestCase): + def test_publication_failure_retries_unknown_and_recovers(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'focus.json' + watcher = agent.FocusWatcher(path) + watcher.publish({'focusedApp': 42}) + write_json = agent.write_json + writes = [] + + def write(path, value): + writes.append(value) + if len(writes) == 1: + raise OSError('unavailable') + write_json(path, value) + + with patch.object(threading.Thread, 'start'), \ + patch.object(watcher.changed, 'wait', side_effect=[True, True, True, StopIteration]), \ + patch.object(agent, 'vr_scene_app', return_value=None), \ + patch.object(agent, 'focus_snapshot', side_effect=[OSError('unavailable'), OSError('unavailable'), {'focusedApp': 42}]), \ + patch.object(agent, 'write_json', side_effect=write), \ + patch.object(agent.time, 'sleep'), \ + patch.object(agent, 'log'): + with self.assertRaises(StopIteration): + watcher.run() + self.assertEqual(writes, [{'seq': 2}, {'seq': 2}, {'focusedApp': 42, 'seq': 3}]) + self.assertEqual(json.loads(path.read_text()), {'focusedApp': 42, 'seq': 3}) + + def test_successful_snapshot_write_failure_retries(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'focus.json' + watcher = agent.FocusWatcher(path) + with patch.object(agent, 'write_json', side_effect=OSError('unavailable')), patch.object(agent, 'log'): + watcher.publish({'focusedApp': 42}) + self.assertIsNone(watcher.last) + self.assertEqual(watcher.seq, 0) + self.assertTrue(watcher.changed.is_set()) + watcher.publish({'focusedApp': 42}) + self.assertEqual(json.loads(path.read_text()), {'focusedApp': 42, 'seq': 1}) + + def test_collection_failure_invalidates_and_recovery_republishes(self): + for error in (OSError('unavailable'), agent.AgentError('X', 'unavailable')): + with self.subTest(error=type(error).__name__), tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'focus.json' + watcher = agent.FocusWatcher(path) + snapshot = {'focusedApp': 42, 't': 1} + watcher.publish(snapshot) + observed = [] + + def collect(): + observed.append(json.loads(path.read_text())) + if len(observed) == 1: + raise error + return dict(snapshot, t=2) + + with patch.object(threading.Thread, 'start'), \ + patch.object(watcher.changed, 'wait', side_effect=[True, True, StopIteration]), \ + patch.object(agent, 'vr_scene_app', return_value=None), \ + patch.object(agent, 'focus_snapshot', side_effect=collect), \ + patch.object(agent.time, 'sleep'), \ + patch.object(agent, 'log'): + with self.assertRaises(StopIteration): + watcher.run() + self.assertEqual(observed, [dict(snapshot, seq=1), {'seq': 2}]) + self.assertEqual(json.loads(path.read_text()), {'focusedApp': 42, 't': 2, 'seq': 3}) + + def test_unchanged_successful_focus_stays_valid(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'focus.json' + watcher = agent.FocusWatcher(path) + watcher.publish({'focusedApp': 769, 't': 1}) + with patch.object(agent, 'write_json') as write: + watcher.publish({'focusedApp': 769, 't': 100}) + write.assert_not_called() + self.assertEqual(json.loads(path.read_text()), {'focusedApp': 769, 't': 1, 'seq': 1}) + + class VrFocusTest(unittest.TestCase): def test_scene_dashboard_and_external_focus_changes(self): focus = agent.VrSceneFocus() diff --git a/tools/tests/test_droiddeck_epic.py b/tools/tests/test_droiddeck_epic.py index 341df75142..e78de6280c 100644 --- a/tools/tests/test_droiddeck_epic.py +++ b/tools/tests/test_droiddeck_epic.py @@ -408,7 +408,7 @@ class SignInTest(EpicTestCase): def test_xdg_open_hands_sign_in_and_links_to_the_app(self): launch = self.tmp / "launch" - with mock.patch.dict(os.environ, {"BL_LAUNCH_DIR": str(launch)}): + with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": str(launch)}): self.assertEqual(0, G["shim_open"]([self.AUTH])) self.assertEqual(0, G["shim_open"](["https://store.epicgames.com/p/fig"])) self.assertEqual(1, G["shim_open"](["mailto:x@example.com"])) @@ -420,7 +420,7 @@ class SignInTest(EpicTestCase): def test_the_xdg_open_command_forwards_steam_links(self): launch = self.tmp / "cli-launch" - env = dict(os.environ, HOME=str(self.home), BL_LAUNCH_DIR=str(launch)) + env = dict(os.environ, HOME=str(self.home), DD_LAUNCH_DIR=str(launch)) def xdg_open(url): return subprocess.run([sys.executable, str(BIN / "droiddeck-epic"), "xdg-open", url], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30).returncode @@ -458,7 +458,7 @@ class SignInHandoffTest(EpicTestCase): def test_a_fresh_marker_makes_the_sign_in_automatic(self): launch = self.tmp / "launch" marker = Path(G["AUTO_SIGN_IN"]) - with mock.patch.dict(os.environ, {"BL_LAUNCH_DIR": str(launch)}): + with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": str(launch)}): G["shim_open"]([SignInTest.AUTH]) marker.parent.mkdir(parents=True) marker.write_text("1\n") @@ -560,7 +560,7 @@ class SignOutTest(EpicTestCase): launch = self.tmp / "launch" session = G["Session"]("visible") states = iter(states) - with mock.patch.dict(os.environ, {"BL_LAUNCH_DIR": str(launch)}), \ + with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": str(launch)}), \ mock.patch.dict(G, {"signed_in": lambda: next(states)}): for now in times: session.follow_sign_out(now) @@ -895,16 +895,16 @@ class BrokerTest(EpicTestCase): calls = [] def popen(command, env=None, cwd=None, start_new_session=False): - calls.append((command, env.get("DROIDDECK_EPIC_HANDLED"), env.get("BL_DEBUG_DIR"), + calls.append((command, env.get("DROIDDECK_EPIC_HANDLED"), env.get("DD_DEBUG_DIR"), env.get("PROTON_LOG"), env.get("WINEDEBUG"), start_new_session)) return mock.Mock(wait=mock.Mock(return_value=7)) running = [] - with mock.patch.dict(os.environ, {"HOME": str(self.home), "BL_DEBUG_DIR": str(debug_dir), + with mock.patch.dict(os.environ, {"HOME": str(self.home), "DD_DEBUG_DIR": str(debug_dir), "PROTON_LOG": "0", "WINEDEBUG": "-all"}), \ mock.patch.object(subprocess, "Popen", popen): code = G["run_game"]({"exe": str(folder / "Fig.exe"), "args": ["-epicapp=Fig"]}, - {"PATH": "/usr/bin", "BL_DEBUG_DIR": str(debug_dir)}, running) + {"PATH": "/usr/bin", "DD_DEBUG_DIR": str(debug_dir)}, running) self.assertEqual(7, code) self.assertEqual(([G["PROTON_RUN"], str(folder / ".droiddeck-launch.bat")], "1", str(debug_dir), "1", mock.ANY, True), calls[0]) @@ -923,7 +923,7 @@ class BrokerTest(EpicTestCase): return 5 result = [] - with mock.patch.dict(os.environ, {"BL_LAUNCH_DIR": str(launch)}), mock.patch.dict(G, {"run_game": run_game}): + with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": str(launch)}), mock.patch.dict(G, {"run_game": run_game}): self.shim(path, ["-epicapp=Fig"], result).join(10) self.assertEqual([True], seen) self.assertEqual([5], result) @@ -1041,7 +1041,7 @@ class BrokerTest(EpicTestCase): def test_the_open_mark_carries_the_steam_app_id(self): launch = self.tmp / "launch" - with mock.patch.dict(os.environ, {"BL_LAUNCH_DIR": str(launch)}): + with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": str(launch)}): with G["marked"](G["OPEN"], "3000000001"): self.assertEqual("3000000001\n", (launch / G["OPEN"]).read_text()) self.assertFalse((launch / G["OPEN"]).exists()) @@ -1147,7 +1147,7 @@ class BrokerTest(EpicTestCase): def test_the_playing_mark_goes_away_when_the_game_fails(self): launch = self.tmp / "launch" - with mock.patch.dict(os.environ, {"BL_LAUNCH_DIR": str(launch)}): + with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": str(launch)}): with self.assertRaises(OSError), G["playing"](): self.assertTrue((launch / G["PLAYING"]).is_file()) raise OSError("boom") @@ -1157,7 +1157,7 @@ class BrokerTest(EpicTestCase): launch = self.tmp / "launch" launch.mkdir() (launch / G["PLAYING"]).write_text("1\n") - with mock.patch.dict(os.environ, {"BL_LAUNCH_DIR": str(launch)}): + with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": str(launch)}): G["clear_playing"]() G["clear_playing"]() self.assertFalse((launch / G["PLAYING"]).exists()) @@ -1172,7 +1172,7 @@ class BrokerTest(EpicTestCase): broker.running.append(game) session = G["Session"]("visible") session.broker = broker - with mock.patch.dict(os.environ, {"BL_LAUNCH_DIR": str(launch)}): + with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": str(launch)}): session.stop() self.assertIsNotNone(game.poll()) self.assertFalse((launch / G["PLAYING"]).exists()) @@ -1316,9 +1316,9 @@ class StoreLaunchClientTest(unittest.TestCase): calls = [] sidecar = dict(self.sidecar, epic={"offline": True}) (self.folder / ".droiddeck-store.json").write_text(json.dumps(sidecar)) - with mock.patch.dict(os.environ, {"BL_LAUNCH_DIR": str(self.tmp / "launch"), "STEAM_COMPAT_DATA_PATH": ""}), \ + with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": str(self.tmp / "launch"), "STEAM_COMPAT_DATA_PATH": ""}), \ mock.patch.dict(S, {"client_wanted": lambda: calls.append("wanted") or True, - "ask": lambda channel, request, timeout=0: calls.append(request["op"]) or {"ok": True}}): + "ask": lambda channel, request, timeout=0, claim=False: calls.append(request["op"]) or {"ok": True}}): S["main"]([str(self.folder / ".droiddeck-launch.bat")]) self.assertNotIn("wanted", calls) self.assertNotIn("epic-code", calls) @@ -1337,11 +1337,11 @@ class StoreLaunchClientTest(unittest.TestCase): def test_epic_launch_falls_back_to_an_exchange_code(self): calls = [] - env = {"BL_LAUNCH_DIR": str(self.tmp / "launch"), "STEAM_COMPAT_DATA_PATH": ""} + env = {"DD_LAUNCH_DIR": str(self.tmp / "launch"), "STEAM_COMPAT_DATA_PATH": ""} with mock.patch.dict(os.environ, env), \ mock.patch.dict(S, {"client_wanted": lambda: True, "through_client": lambda folder, sidecar, timeout=0: calls.append("client") or "timeout", - "ask": lambda channel, request, timeout=0: calls.append(request["op"]) or {"ok": True, "code": True}}): + "ask": lambda channel, request, timeout=0, claim=False: calls.append(request["op"]) or {"ok": True, "code": True}}): S["main"]([str(self.folder / ".droiddeck-launch.bat")]) self.assertEqual(["client", "epic-code", "cloud-down"], calls) @@ -1354,9 +1354,9 @@ class StoreLaunchClientTest(unittest.TestCase): return "ok" (self.folder / ".droiddeck-epic-code").write_text("stale") - with mock.patch.dict(os.environ, {"BL_LAUNCH_DIR": str(self.tmp / "launch"), "STEAM_COMPAT_DATA_PATH": ""}), \ + with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": str(self.tmp / "launch"), "STEAM_COMPAT_DATA_PATH": ""}), \ mock.patch.dict(S, {"client_wanted": lambda: True, "through_client": through, - "ask": lambda channel, request, timeout=0: calls.append(request["op"]) or {"ok": True}}): + "ask": lambda channel, request, timeout=0, claim=False: calls.append(request["op"]) or {"ok": True}}): S["main"]([str(self.folder / ".droiddeck-launch.bat")]) self.assertEqual(["client", "cloud-down"], calls) self.assertFalse((self.folder / ".droiddeck-epic-code").exists()) @@ -1365,10 +1365,10 @@ class StoreLaunchClientTest(unittest.TestCase): def test_handled_launch_keeps_the_clients_args(self): calls = [] (self.folder / ".droiddeck-epic-args").write_text("-epicapp=Fig\r\n") - with mock.patch.dict(os.environ, {"BL_LAUNCH_DIR": str(self.tmp / "launch"), "DROIDDECK_EPIC_HANDLED": "1", + with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": str(self.tmp / "launch"), "DROIDDECK_EPIC_HANDLED": "1", "STEAM_COMPAT_DATA_PATH": ""}), \ mock.patch.dict(S, {"client_wanted": lambda: calls.append("wanted") or True, - "ask": lambda channel, request, timeout=0: calls.append(request["op"]) or {"ok": True}}): + "ask": lambda channel, request, timeout=0, claim=False: calls.append(request["op"]) or {"ok": True}}): S["main"]([str(self.folder / ".droiddeck-launch.bat")]) self.assertEqual(["cloud-down"], calls) self.assertTrue((self.folder / ".droiddeck-epic-args").exists()) @@ -1376,7 +1376,7 @@ class StoreLaunchClientTest(unittest.TestCase): def test_the_games_exit_code_reaches_the_epic_client(self): runs = [] bat = str(self.folder / ".droiddeck-launch.bat") - with mock.patch.dict(os.environ, {"BL_LAUNCH_DIR": ""}), mock.patch.dict(os.environ), \ + with mock.patch.dict(os.environ, {"DD_LAUNCH_DIR": ""}), mock.patch.dict(os.environ), \ mock.patch("os.access", return_value=True), \ mock.patch.object(subprocess, "run", lambda command, **kwargs: runs.append(command)): os.environ.pop("DROIDDECK_EPIC_HANDLED", None) diff --git a/tools/tests/test_droiddeck_fex.py b/tools/tests/test_droiddeck_fex.py index 35c8201d58..825cd8b8d4 100644 --- a/tools/tests/test_droiddeck_fex.py +++ b/tools/tests/test_droiddeck_fex.py @@ -8,6 +8,7 @@ import shutil import stat import struct import subprocess +import sys import tempfile import unittest from pathlib import Path @@ -220,7 +221,7 @@ class LocateTest(FexTestCase): tool = self.fex_tool(self.steam) self.own_fex("fex-2610-r7", loads=False) calls = [] - with mock.patch.dict(os.environ, {"BL_FEX_TAG": "fex-2610-r7"}), \ + with mock.patch.dict(os.environ, {"DD_FEX_TAG": "fex-2610-r7"}), \ mock.patch.object(G["subprocess"], "call", lambda args, **kw: calls.append(args) or 1): FEX["update_own_fex"]() self.assertEqual([[str(BIN / "droiddeck-fex-update")]], calls) @@ -235,7 +236,7 @@ class LocateTest(FexTestCase): def test_the_build_the_session_names_is_installed_once(self): self.own_fex("fex-2610-r6") calls = [] - with mock.patch.dict(os.environ, {"BL_FEX_TAG": "fex-2610-r7"}), \ + with mock.patch.dict(os.environ, {"DD_FEX_TAG": "fex-2610-r7"}), \ mock.patch.object(G["subprocess"], "call", lambda args, **kw: calls.append(args) or 0): FEX["update_own_fex"]() self.write(self.tmp / "own/share/fex-emu/.droiddeck-tag", "fex-2610-r7\n") @@ -246,22 +247,22 @@ class LocateTest(FexTestCase): self.own_fex("fex-2610-r6") Path(G["STATE"]).mkdir(parents=True, exist_ok=True) calls = [] - tag = {"BL_FEX_TAG": "fex-2610-r7"} + tag = {"DD_FEX_TAG": "fex-2610-r7"} with mock.patch.dict(os.environ, tag), \ - mock.patch.object(G["subprocess"], "call", lambda args, **kw: calls.append(os.environ["BL_FEX_TAG"]) or 1): + mock.patch.object(G["subprocess"], "call", lambda args, **kw: calls.append(os.environ["DD_FEX_TAG"]) or 1): FEX["update_own_fex"]() FEX["update_own_fex"]() failed = Path(G["STATE"]) / "update-failed" os.utime(failed, (failed.stat().st_atime, failed.stat().st_mtime - 3601)) FEX["update_own_fex"]() - os.environ["BL_FEX_TAG"] = "fex-2610-r8" + os.environ["DD_FEX_TAG"] = "fex-2610-r8" FEX["update_own_fex"]() self.assertEqual(["fex-2610-r7", "fex-2610-r7", "fex-2610-r8"], calls) def test_a_missing_updater_falls_back_to_the_fex_already_here(self): self.fex_tool(self.steam) Path(G["STATE"]).mkdir(parents=True, exist_ok=True) - with mock.patch.dict(os.environ, {"BL_FEX_TAG": "fex-2610-r7"}), \ + with mock.patch.dict(os.environ, {"DD_FEX_TAG": "fex-2610-r7"}), \ mock.patch.object(G["subprocess"], "call", mock.Mock(side_effect=FileNotFoundError)): FEX["update_own_fex"]() self.assertEqual(FEX["fex_install"]()["bin"], str(self.steam / "steamapps/common/FEX-Emu/usr/bin/FEX")) @@ -270,7 +271,7 @@ class LocateTest(FexTestCase): calls = [] with mock.patch.dict(os.environ, {}, clear=False), \ mock.patch.object(G["subprocess"], "call", lambda args, **kw: calls.append(args) or 0): - os.environ.pop("BL_FEX_TAG", None) + os.environ.pop("DD_FEX_TAG", None) FEX["update_own_fex"]() self.assertEqual([], calls) @@ -314,21 +315,21 @@ class PrepareTest(FexTestCase): def test_preloads_mirror_the_host_list(self): root = self.tmp / "root" for arch in ("x86_64", "i386"): - for name in ("libblsession.so", "libfakeinput.so"): + for name in ("libddsession.so", "libfakeinput.so"): self.write(self.tmp / "preloads" / arch / name, arch.encode() + name.encode()) self.write(self.tmp / "preloads/x86_64/libvulkan-thunk.so", b"pin") - self.write(self.tmp / "ld.so.preload", "/usr/local/lib/libblsession.so\n/usr/local/lib/libfakeinput.so\n") + self.write(self.tmp / "ld.so.preload", "/usr/local/lib/libddsession.so\n/usr/local/lib/libfakeinput.so\n") FEX["install_preloads"](str(root)) self.assertEqual((root / "lib/x86_64-linux-gnu/droiddeck/vulkan/libvulkan.so.1").read_bytes(), b"pin") self.assertEqual(os.readlink(root / "lib/x86_64-linux-gnu/droiddeck/vulkan/libvulkan.so"), "libvulkan.so.1") self.assertEqual((root / "etc/ld.so.preload").read_text(), - "/usr/$LIB/droiddeck/libblsession.so\n/usr/$LIB/droiddeck/libfakeinput.so\n") + "/usr/$LIB/droiddeck/libddsession.so\n/usr/$LIB/droiddeck/libfakeinput.so\n") self.assertEqual((root / "lib/i386-linux-gnu/droiddeck/libfakeinput.so").read_bytes(), b"i386libfakeinput.so") self.assertEqual((root / "etc/asound.conf").read_text(), "pcm.!default {\n type pulse\n}\nctl.!default {\n type pulse\n}\n") - self.write(self.tmp / "ld.so.preload", "/usr/local/lib/libblsession.so\n") + self.write(self.tmp / "ld.so.preload", "/usr/local/lib/libddsession.so\n") FEX["install_preloads"](str(root)) - self.assertEqual((root / "etc/ld.so.preload").read_text(), "/usr/$LIB/droiddeck/libblsession.so\n") + self.assertEqual((root / "etc/ld.so.preload").read_text(), "/usr/$LIB/droiddeck/libddsession.so\n") def test_only_x86_loaders_preload_the_fault_report(self): root = self.tmp / "root" @@ -451,6 +452,331 @@ class PrepareTest(FexTestCase): self.assertIn("built the x86 runtime", self.quiet(FEX["prepare"])[1]) self.assertEqual(sorted(os.listdir(root.parent)), ["config", "lock", "rootfs", "status.json"]) + def test_wayland_and_its_ffi_dependency_come_from_the_newer_runtime(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + names = ("libwayland-client.so.0", "libwayland-cursor.so.0", "libwayland-egl.so.1", + "libwayland-server.so.0", "libffi.so.8") + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + for name in names: + base = sniper / "files/lib" / arch / name + if name != "libffi.so.8": + self.write(base, b"old ABI") + source = provider / "files/lib" / arch / name + self.write(str(source) + ".new", b"new ABI " + name.encode()) + os.symlink(name + ".new", source) + self.write(sniper / "files/lib" / arch / "libffi.so.7", b"old ffi") + fex, _ = self.quiet(FEX["prepare"]) + root = Path(fex["rootfs"]) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + for name in names: + library = root / "lib" / arch / name + expected = sniper if name == "libwayland-cursor.so.0" else provider + self.assertEqual(library.read_bytes(), b"old ABI" if expected == sniper else b"new ABI " + name.encode()) + self.assertEqual((root / "lib" / arch / "libffi.so.7").read_bytes(), b"old ffi") + self.assertEqual((sniper / "files/lib/x86_64-linux-gnu/libwayland-client.so.0").read_bytes(), b"old ABI") + + @unittest.skipUnless(shutil.which("cc"), "C compiler unavailable") + def test_bundled_library_resolves_the_new_wayland_symbol(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + base = sniper / "files/lib/x86_64-linux-gnu" + newer = provider / "files/lib/x86_64-linux-gnu" + source = self.tmp / "library.c" + self.write(newer / "libffi.so.8", b"ffi") + for folder, symbol in ((base, "wl_proxy_marshal"), (newer, "wl_proxy_marshal_flags")): + source.write_text("void *%s(void) { return 0; }\n" % symbol) + subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-Wl,-soname,libwayland-client.so.0", + "-o", str(folder / "libwayland-client.so.0"), str(source)], check=True, capture_output=True) + fex, _ = self.quiet(FEX["prepare"]) + root = Path(fex["rootfs"]) / "lib/x86_64-linux-gnu" + source.write_text("extern void *wl_proxy_marshal_flags(void);\nvoid *probe(void) { return wl_proxy_marshal_flags(); }\n") + probe = self.tmp / "libprobe.so" + subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-o", str(probe), str(source), + "-L" + str(newer), "-l:libwayland-client.so.0", "-Wl,-rpath," + str(root)], + check=True, capture_output=True) + command = [sys.executable, "-c", + "import ctypes,sys; " + "ctypes.CDLL(sys.argv[2], mode=ctypes.RTLD_GLOBAL) if len(sys.argv) > 2 else None; " + "ctypes.CDLL(sys.argv[1]).probe()", + str(probe)] + env = {k: v for k, v in os.environ.items() if not k.startswith("LD_")} + broken = subprocess.run(command + [str(base / "libwayland-client.so.0")], env=env, capture_output=True, text=True) + self.assertNotEqual(broken.returncode, 0) + self.assertIn("undefined symbol: wl_proxy_marshal_flags", broken.stderr) + fixed = subprocess.run(command, env=env, capture_output=True, text=True) + self.assertEqual(fixed.returncode, 0, fixed.stderr) + + def test_gbm_and_its_dependencies_use_the_newer_runtime_on_both_architectures(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + names = ("libgbm.so.1", "libdrm.so.2", "libexpat.so.1") + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + for name in names: + self.write(sniper / "files/lib" / arch / name, b"old ABI") + self.write(provider / "files/lib" / arch / name, b"new ABI " + name.encode()) + fex, _ = self.quiet(FEX["prepare"]) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + for name in names: + self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / name).read_bytes(), b"new ABI " + name.encode()) + + def test_gbm_requires_usable_provider_dependencies_on_both_architectures(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + for name in ("libgbm.so.1", "libdrm.so.2"): + self.write(sniper / "files/lib" / arch / name, b"base") + self.write(provider / "files/lib" / arch / name, b"provider") + os.symlink("missing-expat.so", provider / "files/lib" / arch / "libexpat.so.1") + fex, _ = self.quiet(FEX["prepare"]) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + root = Path(fex["rootfs"]) / "lib" / arch + self.assertEqual((root / "libgbm.so.1").read_bytes(), b"base") + self.assertEqual((root / "libdrm.so.2").read_bytes(), b"provider") + + @unittest.skipUnless(shutil.which("cc"), "C compiler unavailable") + def test_bundled_library_resolves_the_new_gbm_symbol(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + base = sniper / "files/lib/x86_64-linux-gnu" + newer = provider / "files/lib/x86_64-linux-gnu" + source = self.tmp / "gbm.c" + self.write(newer / "libdrm.so.2", b"drm") + self.write(newer / "libexpat.so.1", b"expat") + for folder, symbol in ((base, "gbm_bo_create_with_modifiers"), (newer, "gbm_bo_create_with_modifiers2")): + source.write_text("void *%s(void) { return 0; }\n" % symbol) + subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-Wl,-soname,libgbm.so.1", + "-o", str(folder / "libgbm.so.1"), str(source)], check=True, capture_output=True) + fex, _ = self.quiet(FEX["prepare"]) + root = Path(fex["rootfs"]) / "lib/x86_64-linux-gnu" + source.write_text("extern void *gbm_bo_create_with_modifiers2(void);\n" + "void *probe(void) { return gbm_bo_create_with_modifiers2(); }\n") + probe = self.tmp / "libgbmprobe.so" + subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-o", str(probe), str(source), + "-L" + str(newer), "-l:libgbm.so.1", "-Wl,-rpath," + str(root)], + check=True, capture_output=True) + command = [sys.executable, "-c", + "import ctypes,sys; " + "ctypes.CDLL(sys.argv[2], mode=ctypes.RTLD_GLOBAL) if len(sys.argv) > 2 else None; " + "ctypes.CDLL(sys.argv[1]).probe()", + str(probe)] + env = {k: v for k, v in os.environ.items() if not k.startswith("LD_")} + broken = subprocess.run(command + [str(base / "libgbm.so.1")], env=env, capture_output=True, text=True) + self.assertNotEqual(broken.returncode, 0) + self.assertIn("undefined symbol: gbm_bo_create_with_modifiers2", broken.stderr) + fixed = subprocess.run(command, env=env, capture_output=True, text=True) + self.assertEqual(fixed.returncode, 0, fixed.stderr) + + def test_freetype_and_dependencies_use_the_newer_runtime_on_both_architectures(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + names = ("libfreetype.so.6", "libpng16.so.16", "libbrotlidec.so.1", + "libbrotlicommon.so.1", "libbz2.so.1.0", "libz.so.1") + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + for name in names: + self.write(sniper / "files/lib" / arch / name, b"base") + self.write(provider / "files/lib" / arch / name, b"new") + fex, _ = self.quiet(FEX["prepare"]) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + for name in names: + self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / name).read_bytes(), b"new") + self.assertEqual((sniper / "files/lib" / arch / name).read_bytes(), b"base") + + @unittest.skipUnless(shutil.which("cc"), "C compiler unavailable") + def test_bundled_library_resolves_the_new_freetype_symbol(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + base = sniper / "files/lib/x86_64-linux-gnu" + newer = provider / "files/lib/x86_64-linux-gnu" + source = self.tmp / "freetype.c" + for folder, symbol in ((base, "FT_Init_FreeType"), (newer, "FT_Get_Color_Glyph_Paint")): + source.write_text("void *%s(void) { return 0; }\n" % symbol) + subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-Wl,-soname,libfreetype.so.6", + "-o", str(folder / "libfreetype.so.6"), str(source)], check=True, capture_output=True) + fex, _ = self.quiet(FEX["prepare"]) + root = Path(fex["rootfs"]) / "lib/x86_64-linux-gnu" + source.write_text("extern void *FT_Get_Color_Glyph_Paint(void);\nvoid *probe(void) { return FT_Get_Color_Glyph_Paint(); }\n") + probe = self.tmp / "libprobe.so" + subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-o", str(probe), str(source), + "-L" + str(newer), "-l:libfreetype.so.6", "-Wl,-rpath," + str(root)], + check=True, capture_output=True) + command = [sys.executable, "-c", + "import ctypes,sys; " + "ctypes.CDLL(sys.argv[2], mode=ctypes.RTLD_GLOBAL) if len(sys.argv) > 2 else None; " + "ctypes.CDLL(sys.argv[1]).probe()", str(probe)] + env = {k: v for k, v in os.environ.items() if not k.startswith("LD_")} + broken = subprocess.run(command + [str(base / "libfreetype.so.6")], env=env, capture_output=True, text=True) + self.assertNotEqual(broken.returncode, 0) + self.assertIn("undefined symbol: FT_Get_Color_Glyph_Paint", broken.stderr) + fixed = subprocess.run(command, env=env, capture_output=True, text=True) + self.assertEqual(fixed.returncode, 0, fixed.stderr) + + def test_missing_freetype_provider_keeps_base_on_both_architectures(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + self.graphics(sniper) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + self.write(sniper / "files/lib" / arch / "libfreetype.so.6", b"base") + fex, _ = self.quiet(FEX["prepare"]) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / "libfreetype.so.6").read_bytes(), b"base") + + def test_missing_provider_libraries_keep_the_base_runtime_libraries(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + self.graphics(sniper) + base = self.write(sniper / "files/lib/x86_64-linux-gnu/libwayland-client.so.0", b"base wayland") + fex, _ = self.quiet(FEX["prepare"]) + self.assertEqual((Path(fex["rootfs"]) / "lib/x86_64-linux-gnu/libwayland-client.so.0").read_bytes(), b"base wayland") + + def test_provider_symlinks_require_existing_targets_on_both_architectures(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + base = sniper / "files/lib" / arch + newer = provider / "files/lib" / arch + self.write(base / "libwayland-client.so.0", b"base") + os.symlink("missing-client.so", newer / "libwayland-client.so.0") + os.symlink("missing-ffi.so", newer / "libffi.so.8") + self.write(newer / "wayland-server-real.so", b"provider") + os.symlink("wayland-server-real.so", newer / "libwayland-server.so.0") + fex, _ = self.quiet(FEX["prepare"]) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + root = Path(fex["rootfs"]) / "lib" / arch + self.assertEqual((root / "libwayland-client.so.0").read_bytes(), b"base") + self.assertFalse(os.path.lexists(root / "libffi.so.8")) + self.assertFalse(os.path.lexists(root / "libwayland-server.so.0")) + + def test_wayland_requires_usable_provider_ffi_on_both_architectures(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + for ffi_state in ("missing", "dangling"): + with self.subTest(ffi_state=ffi_state): + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + base = sniper / "files/lib" / arch + newer = provider / "files/lib" / arch + for name in ("libwayland-client.so.0", "libwayland-server.so.0", "libwayland-cursor.so.0"): + self.write(base / name, b"base") + self.write(newer / name, b"provider") + if ffi_state == "dangling": + os.symlink("missing-ffi.so", newer / "libffi.so.8") + marker = self.home / ".local/share/droiddeck-fex/rootfs/.droiddeck-fex" + if marker.exists(): + marker.unlink() + fex, _ = self.quiet(FEX["prepare"]) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + root = Path(fex["rootfs"]) / "lib" / arch + for name in ("libwayland-client.so.0", "libwayland-server.so.0", "libwayland-cursor.so.0"): + self.assertEqual((root / name).read_bytes(), b"base") + self.assertFalse(os.path.lexists(root / "libffi.so.8")) + + def test_wayland_cursor_requires_usable_provider_client_on_both_architectures(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + for client_state in ("missing", "dangling"): + with self.subTest(client_state=client_state): + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + base = sniper / "files/lib" / arch + newer = provider / "files/lib" / arch + self.write(base / "libwayland-client.so.0", b"base client") + self.write(base / "libwayland-cursor.so.0", b"base cursor") + self.write(newer / "libwayland-cursor.so.0", b"provider cursor") + self.write(newer / "libffi.so.8", b"provider ffi") + if client_state == "dangling": + os.symlink("missing-client.so", newer / "libwayland-client.so.0") + marker = self.home / ".local/share/droiddeck-fex/rootfs/.droiddeck-fex" + if marker.exists(): + marker.unlink() + fex, _ = self.quiet(FEX["prepare"]) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + root = Path(fex["rootfs"]) / "lib" / arch + self.assertEqual((root / "libwayland-client.so.0").read_bytes(), b"base client") + self.assertEqual((root / "libwayland-cursor.so.0").read_bytes(), b"base cursor") + self.assertEqual((root / "libffi.so.8").read_bytes(), b"provider ffi") + + def test_restored_provider_clients_rebuild_the_rootfs_without_marker_changes(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + self.write(sniper / "files/lib" / arch / "libwayland-client.so.0", b"base") + self.write(provider / "files/lib" / arch / "libffi.so.8", b"ffi") + os.symlink("client-real.so", provider / "files/lib" / arch / "libwayland-client.so.0") + fex, _ = self.quiet(FEX["prepare"]) + for arch in ("x86_64-linux-gnu", "i386-linux-gnu"): + self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / "libwayland-client.so.0").read_bytes(), b"base") + self.write(provider / "files/lib" / arch / "client-real.so", b"restored") + fex, said = self.quiet(FEX["prepare"]) + self.assertIn("built the x86 runtime", said) + self.assertEqual((Path(fex["rootfs"]) / "lib" / arch / "libwayland-client.so.0").read_bytes(), b"restored") + self.assertNotIn("built the x86 runtime", self.quiet(FEX["prepare"])[1]) + client = provider / "files/lib/i386-linux-gnu/client-real.so" + client.write_bytes(b"updated client") + fex, said = self.quiet(FEX["prepare"]) + self.assertIn("built the x86 runtime", said) + self.assertEqual((Path(fex["rootfs"]) / "lib/i386-linux-gnu/libwayland-client.so.0").read_bytes(), b"updated client") + + @unittest.skipUnless(shutil.which("cc"), "C compiler unavailable") + def test_base_cursor_works_with_guest_selected_old_client(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + provider = self.graphics(sniper) + base = sniper / "files/lib/x86_64-linux-gnu" + newer = provider / "files/lib/x86_64-linux-gnu" + source = self.tmp / "cursor.c" + self.write(newer / "libffi.so.8", b"ffi") + for folder, symbol in ((base, "wl_proxy_marshal"), (newer, "wl_proxy_marshal_flags")): + source.write_text("void %s(void) {}\n" % symbol) + subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-Wl,-soname,libwayland-client.so.0", + "-o", str(folder / "libwayland-client.so.0"), str(source)], check=True, capture_output=True) + source.write_text("extern void %s(void); void probe(void) { %s(); }\n" % (symbol, symbol)) + subprocess.run(["cc", "-shared", "-fPIC", "-nostdlib", "-o", str(folder / "libwayland-cursor.so.0"), + str(source), "-L" + str(folder), "-l:libwayland-client.so.0"], check=True, capture_output=True) + fex, _ = self.quiet(FEX["prepare"]) + cursor = Path(fex["rootfs"]) / "lib/x86_64-linux-gnu/libwayland-cursor.so.0" + command = [sys.executable, "-c", "import ctypes,sys; ctypes.CDLL(sys.argv[1], mode=ctypes.RTLD_GLOBAL); ctypes.CDLL(sys.argv[2]).probe()", str(base / "libwayland-client.so.0")] + env = {k: v for k, v in os.environ.items() if not k.startswith("LD_")} + broken = subprocess.run(command + [str(newer / "libwayland-cursor.so.0")], env=env, capture_output=True, text=True) + self.assertNotEqual(broken.returncode, 0) + self.assertIn("undefined symbol: wl_proxy_marshal_flags", broken.stderr) + fixed = subprocess.run(command + [str(cursor)], env=env, capture_output=True, text=True) + self.assertEqual(fixed.returncode, 0, fixed.stderr) + + def test_the_old_rootfs_layout_is_rebuilt(self): + self.fex_tool() + sniper = self.runtime() + FEX["materialize"](str(sniper)) + self.graphics(sniper) + with mock.patch.dict(G, {"ROOTFS_LAYOUT": 6}): + self.quiet(FEX["prepare"]) + _, said = self.quiet(FEX["prepare"]) + self.assertIn("built the x86 runtime", said) + self.assertNotIn("built the x86 runtime", self.quiet(FEX["prepare"])[1]) + def test_the_built_x86_runtime_holds_nothing_that_leaves_it(self): self.fex_tool() sniper = self.runtime() @@ -1040,13 +1366,13 @@ class AppInfoTest(unittest.TestCase): bin_dir.mkdir() (bin_dir / "taskset").write_text('#!/bin/sh\necho "taskset $*"\n') (bin_dir / "taskset").chmod(0o755) - env = dict(os.environ, PATH="%s:%s" % (bin_dir, os.environ.get("PATH", "")), BL_GAME_CPUS="2-7") + env = dict(os.environ, PATH="%s:%s" % (bin_dir, os.environ.get("PATH", "")), DD_GAME_CPUS="2-7") run = subprocess.run([str(tool / "droiddeck-fex-tool"), "waitforexitandrun", "/games/a/game"], env=env, capture_output=True, text=True, timeout=10) self.assertEqual(run.stdout, "taskset -c 2-7 /usr/local/bin/droiddeck-fex steam waitforexitandrun /games/a/game\n") self.assertIn("game cores 2-7", run.stderr) - self.assertIn('exec /usr/local/bin/droiddeck-steamvr-game ${BL_TASKSET:-} ' + self.assertIn('exec /usr/local/bin/droiddeck-steamvr-game ${DD_TASKSET:-} ' '/usr/local/bin/droiddeck-fex steam "$verb" "$@"', self.COMPAT["FEX_LAUNCHER_SH"]) diff --git a/tools/tests/test_effects_source_resolution.py b/tools/tests/test_effects_source_resolution.py index 043f392129..aae6052cec 100644 --- a/tools/tests/test_effects_source_resolution.py +++ b/tools/tests/test_effects_source_resolution.py @@ -33,7 +33,9 @@ class EffectsSourceResolutionTest(unittest.TestCase): 'static void effects_overlay_draws(', 'static int render_impl(', 'static int pass_begin_impl(')) functions = (re.search(r'static int spatial_mode\([^\n]+', effects).group() + '\n' + + re.search(r'static int cas_active\([^\n]+', effects).group() + '\n' + function(effects, 'int vkp_effects_upscaling(') + + function(effects, 'int vkp_effects_sharpening(') + function(effects, 'int vkp_effects_postprocessing(') + functions) image = source[source.index('struct vkp_image {'):source.index('\n};', source.index('struct vkp_image {')) + 3] draw = header[header.index('struct vkp_draw {'):header.index('\n};', header.index('struct vkp_draw {')) + 3] @@ -101,6 +103,9 @@ class EffectsSourceResolutionTest(unittest.TestCase): def test_postprocessing_keeps_foreground_inside_the_effect_chain(self): self.check_case('postprocessing') + def test_frame_generation_keeps_upscaling_and_sharpening_at_panel_size(self): + self.check_case('framegen-sharpening') + TYPES = r''' #include @@ -192,7 +197,8 @@ static struct vkp_img_slot g_hdrscene, g_fgscene; static struct { int active, rw, rh; VkImage result; } g_pass; static struct { int64_t present_ns, present_max_ns; unsigned presents; } g_perf; static int effects_active = 1, framegen, cardboard; -static struct { int scaling; } g_cur = {4}; +struct fx_settings { int scaling, cas_on, cas_pct; }; +static struct fx_settings g_cur = {4}; static int copy_count, effects_count, screen_count, hdr_count, fail_scene, fail_effects, postprocessing; static int copied_w, copied_h, target_w, target_h; static int effects_w, effects_h, output_w, output_h, logical_w, logical_h; @@ -276,7 +282,7 @@ static struct vkp_draw fullscreen(void) { } static void reset(void) { copy_count = effects_count = screen_count = hdr_count = barrier_count = 0; - effects_active = 1; g_cur.scaling = 4; + effects_active = 1; g_cur = (struct fx_settings){4}; framegen = cardboard = fail_scene = fail_effects = postprocessing = g_plain_frame = 0; g_pass.active = 0; g_extent = (VkExtent2D){1920, 1080}; image.w = 1280; image.h = 720; @@ -552,6 +558,25 @@ static void check_allocation(void) { assert(recorded_blits[1].dstOffsets[1].x == 1920 && recorded_blits[1].dstOffsets[1].y == 1080); assert(target_w == 1920 && target_h == 1080); } +static void check_framegen_output(int scaling, int cas, int grading, int panel) { + reset(); framegen = 1; postprocessing = grading; + g_cur = (struct fx_settings){scaling, cas, cas ? 60 : 0}; + g_extent = (VkExtent2D){2880, 1620}; + struct vkp_draw draw = fullscreen(); + run_path(0, &draw, 1, NULL); + assert(effects_count == 1); + assert(output_w == (panel ? 2880 : 1920) && output_h == (panel ? 1620 : 1080)); +} +static void check_framegen_sharpening(void) { + check_framegen_output(4, 0, 0, 1); + check_framegen_output(3, 0, 0, 1); + check_framegen_output(8, 0, 0, 1); + check_framegen_output(0, 1, 1, 1); + check_framegen_output(1, 1, 1, 1); + check_framegen_output(0, 0, 1, 0); + check_framegen_output(6, 0, 0, 0); + check_framegen_output(2, 0, 1, 0); +} int main(int argc, char **argv) { assert(argc == 2); reset(); if (!strcmp(argv[1], "helper")) check_helper(); @@ -567,6 +592,7 @@ int main(int argc, char **argv) { else if (!strcmp(argv[1], "effect-failure")) check_effect_failure(); else if (!strcmp(argv[1], "overlay-barriers")) check_overlay_barriers(); else if (!strcmp(argv[1], "postprocessing")) check_postprocessing(); + else if (!strcmp(argv[1], "framegen-sharpening")) check_framegen_sharpening(); else assert(0); puts("PASS"); } diff --git a/tools/tests/test_esync_packs.py b/tools/tests/test_esync_packs.py index b7667c5e8e..7679cd9280 100644 --- a/tools/tests/test_esync_packs.py +++ b/tools/tests/test_esync_packs.py @@ -28,7 +28,7 @@ RECORD = SYNC["RECORD"] VALVE_LINE = "1789159687 experimental-11.0-20260910b-arm64" GE_LINE = "1789520806 GE-Proton11-7" EXPORTS = ("NtClose", "NtCreateEvent", "wine_server_call") -WATCHED = ("WINESERVER", "BL_SYNC_PACK", "WINEESYNC", "PROTON_NO_ESYNC", "BL_SYNC", "CUSTOM") +WATCHED = ("WINESERVER", "DD_SYNC_PACK", "WINEESYNC", "PROTON_NO_ESYNC", "DD_SYNC", "CUSTOM") PROTON = ("#!/usr/bin/python3\nimport json, os, sys\n" "print(json.dumps([sys.argv[0], sys.argv[1:], {k: os.environ.get(k) for k in %r}]))\n" % (WATCHED,)) MANIFEST = '"manifest" { "commandline" "/proton %verb%" }' @@ -117,7 +117,7 @@ def concurrent_worker(barrier, queue, root, tool, pack, steam): try: with contextlib.redirect_stderr(io.StringIO()): path = SYNC["ensure_dist"](root, tool, pack) - SYNC["reconcile"](steam, {"HOME": str(Path(root).parents[2]), "BL_SYNC_FALLBACK": "1"}) + SYNC["reconcile"](steam, {"HOME": str(Path(root).parents[2]), "DD_SYNC_FALLBACK": "1"}) queue.put(path) except Exception as error: queue.put("error: %r" % error) @@ -138,7 +138,7 @@ class SyncTestCase(unittest.TestCase): return self.root def env(self, **extra): - env = {"HOME": str(self.home), "STEAM_COMPAT_DATA_PATH": "/compatdata/42", "BL_SYNC_FALLBACK": "1", "BL_SYNC_MIN_NOFILE": "1"} + env = {"HOME": str(self.home), "STEAM_COMPAT_DATA_PATH": "/compatdata/42", "DD_SYNC_FALLBACK": "1", "DD_SYNC_MIN_NOFILE": "1"} env.update(extra) return {name: value for name, value in env.items() if value is not None} @@ -358,8 +358,8 @@ class SelectTest(SyncTestCase): env = self.env() command, chosen_env, said = self.select(tool, env) self.assertEqual((command, chosen_env, said), ([str(tool / "proton"), "waitforexitandrun", "game.exe"], env, "")) - command, chosen_env, said = self.select(tool, self.env(PROTON_NO_NTSYNC="1", BL_SYNC="1")) - self.assertEqual(chosen_env, self.env(PROTON_NO_NTSYNC="1", BL_SYNC="0")) + command, chosen_env, said = self.select(tool, self.env(PROTON_NO_NTSYNC="1", DD_SYNC="1")) + self.assertEqual(chosen_env, self.env(PROTON_NO_NTSYNC="1", DD_SYNC="0")) self.assertIsNone(self.quiet(SYNC["reconcile"], str(self.tmp / "steam"), env)) self.assertEqual(SYNC["gc"](None), 0) self.assertIsNone(SYNC["store_root"](env)) @@ -385,7 +385,7 @@ class SelectTest(SyncTestCase): tool = make_tool(self.tools, "Proton Experimental (ARM64)") make_pack(root, tool, "valve-experimental-r1") for value in ("0", None, "yes"): - env = self.env(BL_SYNC_FALLBACK=value) + env = self.env(DD_SYNC_FALLBACK=value) command, chosen_env, said = self.select(tool, env) self.assertEqual((command[0], chosen_env), (str(tool / "proton"), SYNC["wineserver_only"](env))) self.assertEqual(said, "droiddeck-esync: off; wineserver sync only\n") @@ -398,10 +398,10 @@ class SelectTest(SyncTestCase): tool = make_tool(self.tools, "Proton Experimental (ARM64)") pack = make_pack(root, tool, "valve-experimental-r1") dist = self.dist_of(pack["id"], tool) - command, env, said = self.select(tool, self.env(BL_SYNC="1")) + command, env, said = self.select(tool, self.env(DD_SYNC="1")) self.assertEqual(command, [str(dist / "proton"), "waitforexitandrun", "game.exe"]) self.assertEqual(env["WINESERVER"], str(dist / WINESERVER)) - self.assertEqual(env["BL_SYNC_PACK"], pack["id"]) + self.assertEqual(env["DD_SYNC_PACK"], pack["id"]) self.assertEqual(env["WINEESYNC"], "1") self.assertNotIn("PROTON_NO_ESYNC", env) self.assertTrue(said.startswith("droiddeck-esync: pack %s for Proton Experimental (ARM64) (%s, exact match); " @@ -427,7 +427,7 @@ class SelectTest(SyncTestCase): {"WINEESYNC": "0", "PROTON_NO_ESYNC": "0"}) for extra in cases: command, env, _ = self.select(tool, self.env(**extra)) - self.assertEqual((env["WINEESYNC"], env["PROTON_NO_ESYNC"], env["BL_SYNC_PACK"]), ("0", "1", pack["id"]), extra) + self.assertEqual((env["WINEESYNC"], env["PROTON_NO_ESYNC"], env["DD_SYNC_PACK"]), ("0", "1", pack["id"]), extra) self.assertNotIn("PROTON_NO_FSYNC", env, extra) self.assertEqual(command[0], str(self.dist_of(pack["id"], tool) / "proton")) for extra in ({"PROTON_NO_ESYNC": "0"}, {"PROTON_NO_ESYNC": ""}, {"STEAM_COMPAT_APP_ID": "42", "SteamAppId": "2630"}, @@ -443,7 +443,7 @@ class SelectTest(SyncTestCase): ({"PROTON_NO_FSYNC": ""}, ""), ({"PROTON_NO_FSYNC": "1"}, "1")): env = self.select(tool, self.env(**extra))[1] self.assertEqual(env.get("PROTON_NO_FSYNC"), expected, extra) - stock = self.select(tool, self.env(BL_SYNC_FALLBACK="0"))[1] + stock = self.select(tool, self.env(DD_SYNC_FALLBACK="0"))[1] self.assertEqual((stock["PROTON_NO_FSYNC"], stock["WINEFSYNC"]), ("1", "0")) def test_open_file_limit_threshold(self): @@ -454,21 +454,21 @@ class SelectTest(SyncTestCase): ((1024, 4096), "junk", "0"), ((1024, 8192), None, "1"), ((1024, -1), "999999", "1")) for limits, minimum, expected in cases: with mock.patch("resource.getrlimit", return_value=limits): - command, env, said = self.select(tool, self.env(BL_SYNC_MIN_NOFILE=minimum)) + command, env, said = self.select(tool, self.env(DD_SYNC_MIN_NOFILE=minimum)) self.assertEqual(env["WINEESYNC"], expected, (limits, minimum)) self.assertIn("fds 1024/unlimited", said) def test_proton_no_ntsync_turns_emulation_off(self): tool = make_tool(self.tools, "Proton Experimental (ARM64)") - self.assertEqual(self.select(tool, self.env(PROTON_NO_NTSYNC="1", BL_SYNC="1"))[1]["BL_SYNC"], "0") - self.assertEqual(self.select(tool, self.env(PROTON_NO_NTSYNC="1"))[1]["BL_SYNC"], "0") - self.assertEqual(self.select(tool, self.env(PROTON_NO_NTSYNC="0", BL_SYNC="1"))[1]["BL_SYNC"], "1") + self.assertEqual(self.select(tool, self.env(PROTON_NO_NTSYNC="1", DD_SYNC="1"))[1]["DD_SYNC"], "0") + self.assertEqual(self.select(tool, self.env(PROTON_NO_NTSYNC="1"))[1]["DD_SYNC"], "0") + self.assertEqual(self.select(tool, self.env(PROTON_NO_NTSYNC="0", DD_SYNC="1"))[1]["DD_SYNC"], "1") root = self.store() - _, env, _ = self.select(tool, self.env(PROTON_NO_NTSYNC="1", BL_SYNC="1")) - self.assertEqual(env["BL_SYNC"], "0") + _, env, _ = self.select(tool, self.env(PROTON_NO_NTSYNC="1", DD_SYNC="1")) + self.assertEqual(env["DD_SYNC"], "0") pack = make_pack(root, tool, "valve-experimental-r1") - _, env, said = self.select(tool, self.env(PROTON_NO_NTSYNC="1", BL_SYNC="1")) - self.assertEqual((env["BL_SYNC"], env["BL_SYNC_PACK"]), ("0", pack["id"])) + _, env, said = self.select(tool, self.env(PROTON_NO_NTSYNC="1", DD_SYNC="1")) + self.assertEqual((env["DD_SYNC"], env["DD_SYNC_PACK"]), ("0", pack["id"])) self.assertIn("droiddeck-ntsync off", said) def test_internal_failure_launches_stock(self): @@ -483,52 +483,52 @@ class SelectTest(SyncTestCase): with mock.patch.dict(GLOBALS, {name: broken}): command, env, said = self.select(tool, self.env(PROTON_NO_NTSYNC="1")) self.assertEqual(command[0], str(tool / "proton"), name) - self.assertEqual(env, self.env(PROTON_NO_NTSYNC="1", BL_SYNC="0"), name) + self.assertEqual(env, self.env(PROTON_NO_NTSYNC="1", DD_SYNC="0"), name) self.assertIn("boom", said) def test_droiddeck_ntsync_stands_in_without_a_pack(self): root = self.store() tool = make_tool(self.tools, "Proton Experimental (ARM64)") - command, env, said = self.select(tool, self.env(BL_SYNC="0")) + command, env, said = self.select(tool, self.env(DD_SYNC="0")) self.assertEqual(command[0], str(tool / "proton")) - self.assertEqual(env, self.env(BL_SYNC="1")) + self.assertEqual(env, self.env(DD_SYNC="1")) self.assertTrue(said.endswith("; stock binaries with droiddeck-ntsync\n"), said) self.assertEqual((root / "launches.log").read_text().split("\n")[-2].split("\t")[6], "1") - command, env, said = self.select(tool, self.env(PROTON_NO_NTSYNC="1", BL_SYNC="1")) - self.assertEqual(env, self.env(PROTON_NO_NTSYNC="1", BL_SYNC="0")) + command, env, said = self.select(tool, self.env(PROTON_NO_NTSYNC="1", DD_SYNC="1")) + self.assertEqual(env, self.env(PROTON_NO_NTSYNC="1", DD_SYNC="0")) self.assertTrue(said.endswith("; stock binaries\n"), said) pack = make_pack(root, tool, "valve-experimental-r1") (root / "packs" / pack["id"] / NTDLL).write_bytes(b"tampered") - command, env, said = self.select(tool, self.env(BL_SYNC="0")) + command, env, said = self.select(tool, self.env(DD_SYNC="0")) self.assertEqual(command[0], str(tool / "proton")) - self.assertEqual(env, self.env(BL_SYNC="1")) + self.assertEqual(env, self.env(DD_SYNC="1")) self.assertIn("unusable", said) self.assertTrue(said.endswith("; stock binaries with droiddeck-ntsync\n"), said) def test_droiddeck_fsync_stands_in_without_a_pack(self): root = self.store() tool = make_tool(self.tools, "Proton Experimental (ARM64)", fsync=True) - command, env, said = self.select(tool, self.env(BL_SYNC="0")) + command, env, said = self.select(tool, self.env(DD_SYNC="0")) self.assertEqual(command, [str(tool / "proton"), "waitforexitandrun", "game.exe"]) - self.assertEqual(env, self.env(BL_SYNC="0", BL_FSYNC="1", WINEFSYNC="1")) + self.assertEqual(env, self.env(DD_SYNC="0", DD_FSYNC="1", WINEFSYNC="1")) self.assertEqual(said, "droiddeck-fsync: no pack for Proton Experimental (ARM64) (%s, ntdll %s); " "stock binaries with Proton's fsync\n" % (VALVE_LINE, sha(tool / NTDLL)[:12])) fields = (root / "launches.log").read_text().splitlines()[-1].split("\t") self.assertEqual((fields[4], fields[6], fields[8]), ("-", "0", "1")) self.assertEqual(len((root / "wanted.tsv").read_text().splitlines()), 1) - for extra in ({"BL_SYNC": "1"}, {"PROTON_NO_FSYNC": "1"}, {"STEAM_COMPAT_APP_ID": "2630"}, {"SteamAppId": "1233880"}): + for extra in ({"DD_SYNC": "1"}, {"PROTON_NO_FSYNC": "1"}, {"STEAM_COMPAT_APP_ID": "2630"}, {"SteamAppId": "1233880"}): command, env, said = self.select(tool, self.env(**extra)) - self.assertNotIn("BL_FSYNC", env, extra) - self.assertEqual(env["BL_SYNC"], "1", extra) + self.assertNotIn("DD_FSYNC", env, extra) + self.assertEqual(env["DD_SYNC"], "1", extra) self.assertTrue(said.endswith("; stock binaries with droiddeck-ntsync\n"), (extra, said)) - for extra in ({"STEAM_COMPAT_APP_ID": "2630", "PROTON_NO_FSYNC": "0"}, {"PROTON_NO_FSYNC": ""}, {"BL_SYNC": "0"}): - self.assertEqual(self.select(tool, self.env(**extra))[1]["BL_FSYNC"], "1", extra) + for extra in ({"STEAM_COMPAT_APP_ID": "2630", "PROTON_NO_FSYNC": "0"}, {"PROTON_NO_FSYNC": ""}, {"DD_SYNC": "0"}): + self.assertEqual(self.select(tool, self.env(**extra))[1]["DD_FSYNC"], "1", extra) env = self.select(tool, self.env(PROTON_NO_FSYNC="1", PROTON_NO_NTSYNC="1"))[1] - self.assertEqual((env["BL_SYNC"], "BL_FSYNC" in env), ("0", False)) + self.assertEqual((env["DD_SYNC"], "DD_FSYNC" in env), ("0", False)) pack = make_pack(root, tool, "valve-experimental-r1") (root / "packs" / pack["id"] / NTDLL).write_bytes(b"tampered") command, env, said = self.select(tool, self.env()) - self.assertEqual((command[0], env["BL_FSYNC"]), (str(tool / "proton"), "1")) + self.assertEqual((command[0], env["DD_FSYNC"]), (str(tool / "proton"), "1")) self.assertIn("\ndroiddeck-fsync: pack %s unusable for Proton Experimental (ARM64) (" % pack["id"], said) self.assertTrue(said.endswith("; stock binaries with Proton's fsync\n"), said) @@ -536,24 +536,24 @@ class SelectTest(SyncTestCase): root = self.store() tool = make_tool(self.tools, "Proton Experimental (ARM64)", fsync=True) pack = make_pack(root, tool, "valve-experimental-r1") - for extra in ({}, {"BL_SYNC_FALLBACK": None}, {"BL_SYNC_FALLBACK": "0"}, {"BL_FSYNC": "0"}): - command, env, said = self.select(tool, self.env(BL_FSYNC_FIRST="1", **extra)) + for extra in ({}, {"DD_SYNC_FALLBACK": None}, {"DD_SYNC_FALLBACK": "0"}, {"DD_FSYNC": "0"}): + command, env, said = self.select(tool, self.env(DD_FSYNC_FIRST="1", **extra)) self.assertEqual(command[0], str(tool / "proton"), extra) - self.assertEqual((env["BL_FSYNC"], env["BL_SYNC"], env["WINEFSYNC"]), ("1", "0", "1"), extra) - self.assertNotIn("BL_SYNC_PACK", env, extra) + self.assertEqual((env["DD_FSYNC"], env["DD_SYNC"], env["WINEFSYNC"]), ("1", "0", "1"), extra) + self.assertNotIn("DD_SYNC_PACK", env, extra) self.assertEqual(said, "droiddeck-fsync: chosen for Proton Experimental (ARM64); stock binaries with Proton's fsync\n") self.assertFalse((root / "wanted.tsv").exists()) - command, env, said = self.select(tool, self.env(BL_FSYNC_FIRST="1", BL_SYNC="1")) - self.assertEqual((command[0], env["BL_SYNC_PACK"], env["BL_SYNC"]), (str(self.dist_of(pack["id"], tool) / "proton"), pack["id"], "1")) - self.assertNotIn("BL_FSYNC", env) - command, env, said = self.select(tool, self.env(BL_FSYNC_FIRST="1", BL_FSYNC="1", STEAM_COMPAT_APP_ID="414740")) - self.assertEqual((env["BL_FSYNC"], env["BL_SYNC_PACK"], env["PROTON_NO_ESYNC"]), ("0", pack["id"], "1")) - command, env, said = self.select(tool, self.env(BL_FSYNC_FIRST="1", BL_FSYNC="1", BL_SYNC_FALLBACK="0", PROTON_NO_FSYNC="1")) - self.assertEqual((command[0], env["BL_FSYNC"], said), (str(tool / "proton"), "0", "droiddeck-esync: off\n")) + command, env, said = self.select(tool, self.env(DD_FSYNC_FIRST="1", DD_SYNC="1")) + self.assertEqual((command[0], env["DD_SYNC_PACK"], env["DD_SYNC"]), (str(self.dist_of(pack["id"], tool) / "proton"), pack["id"], "1")) + self.assertNotIn("DD_FSYNC", env) + command, env, said = self.select(tool, self.env(DD_FSYNC_FIRST="1", DD_FSYNC="1", STEAM_COMPAT_APP_ID="414740")) + self.assertEqual((env["DD_FSYNC"], env["DD_SYNC_PACK"], env["PROTON_NO_ESYNC"]), ("0", pack["id"], "1")) + command, env, said = self.select(tool, self.env(DD_FSYNC_FIRST="1", DD_FSYNC="1", DD_SYNC_FALLBACK="0", PROTON_NO_FSYNC="1")) + self.assertEqual((command[0], env["DD_FSYNC"], said), (str(tool / "proton"), "0", "droiddeck-esync: off\n")) plain = make_tool(self.tools, "GE-Proton11-9", "1790000000 GE-Proton11-9", builtin=True, ge=True) - command, env, said = self.select(plain, self.env(BL_FSYNC_FIRST="1")) + command, env, said = self.select(plain, self.env(DD_FSYNC_FIRST="1")) self.assertEqual((command[0], said), (str(plain / "proton"), "droiddeck-esync: GE-Proton11-9 has esync built in\n")) - self.assertNotIn("BL_FSYNC", env) + self.assertNotIn("DD_FSYNC", env) def test_fsync_takes_over_when_esync_is_off_for_a_game(self): root = self.store() @@ -561,18 +561,18 @@ class SelectTest(SyncTestCase): pack = make_pack(root, tool, "valve-experimental-r1") for extra in ({"PROTON_NO_ESYNC": "1"}, {"WINEESYNC": "0"}): command, env, said = self.select(tool, self.env(**extra)) - self.assertEqual((command[0], env["BL_FSYNC"]), (str(tool / "proton"), "1"), extra) + self.assertEqual((command[0], env["DD_FSYNC"]), (str(tool / "proton"), "1"), extra) self.assertEqual(said, "droiddeck-fsync: esync is off for this game; stock binaries with Proton's fsync\n") with mock.patch("resource.getrlimit", return_value=(1024, 4096)): - env = self.select(tool, self.env(BL_SYNC_MIN_NOFILE=None))[1] - self.assertEqual(env["BL_FSYNC"], "1") - for extra in ({"STEAM_COMPAT_APP_ID": "2630"}, {"PROTON_NO_ESYNC": "1", "PROTON_NO_FSYNC": "1"}, {"WINEESYNC": "0", "BL_SYNC": "1"}): + env = self.select(tool, self.env(DD_SYNC_MIN_NOFILE=None))[1] + self.assertEqual(env["DD_FSYNC"], "1") + for extra in ({"STEAM_COMPAT_APP_ID": "2630"}, {"PROTON_NO_ESYNC": "1", "PROTON_NO_FSYNC": "1"}, {"WINEESYNC": "0", "DD_SYNC": "1"}): command, env, said = self.select(tool, self.env(**extra)) - self.assertEqual((env["BL_SYNC_PACK"], env["WINEESYNC"]), (pack["id"], "0"), extra) - self.assertNotIn("BL_FSYNC", env, extra) + self.assertEqual((env["DD_SYNC_PACK"], env["WINEESYNC"]), (pack["id"], "0"), extra) + self.assertNotIn("DD_FSYNC", env, extra) command, env, said = self.select(tool, self.env()) - self.assertEqual((env["BL_SYNC_PACK"], env["WINEESYNC"], env["PROTON_NO_FSYNC"]), (pack["id"], "1", "1")) - self.assertNotIn("BL_FSYNC", env) + self.assertEqual((env["DD_SYNC_PACK"], env["WINEESYNC"], env["PROTON_NO_FSYNC"]), (pack["id"], "1", "1")) + self.assertNotIn("DD_FSYNC", env) def test_the_hash_cache_remembers_fsync(self): root = self.store() @@ -585,7 +585,7 @@ class SelectTest(SyncTestCase): self.assertEqual(rows[os.path.realpath(tool / NTDLL)][9], "0") (root / "hash-cache.tsv").write_text("\n".join("\t".join(row[:9]) for row in rows.values()) + "\n") self.assertEqual(SYNC["parse_cache"]((root / "hash-cache.tsv").read_text()), {}) - self.assertEqual(self.select(tool, self.env())[1]["BL_FSYNC"], "1") + self.assertEqual(self.select(tool, self.env())[1]["DD_FSYNC"], "1") def test_esync_off_games_get_droiddeck_ntsync_on_a_pack(self): root = self.store() @@ -593,49 +593,49 @@ class SelectTest(SyncTestCase): pack = make_pack(root, tool, "valve-experimental-r1") for extra in ({"PROTON_NO_ESYNC": "1"}, {"STEAM_COMPAT_APP_ID": "2630"}, {"WINEESYNC": "0"}): command, env, said = self.select(tool, self.env(**extra)) - self.assertEqual((env["BL_SYNC_PACK"], env["WINEESYNC"], env["BL_SYNC"]), (pack["id"], "0", "1"), extra) + self.assertEqual((env["DD_SYNC_PACK"], env["WINEESYNC"], env["DD_SYNC"]), (pack["id"], "0", "1"), extra) self.assertIn("droiddeck-ntsync on, droiddeck-esync off", said) env = self.select(tool, self.env(PROTON_NO_ESYNC="1", PROTON_NO_NTSYNC="1"))[1] - self.assertEqual((env["WINEESYNC"], env["BL_SYNC"]), ("0", "0")) - env = self.select(tool, self.env(BL_SYNC="0"))[1] - self.assertEqual((env["WINEESYNC"], env["BL_SYNC"]), ("1", "0")) + self.assertEqual((env["WINEESYNC"], env["DD_SYNC"]), ("0", "0")) + env = self.select(tool, self.env(DD_SYNC="0"))[1] + self.assertEqual((env["WINEESYNC"], env["DD_SYNC"]), ("1", "0")) def test_a_running_prefix_keeps_its_sync_choice(self): root = self.store() tool = make_tool(self.tools, "Proton Experimental (ARM64)", fsync=True) prefix = os.path.realpath("/compatdata/42/pfx") command, first, _ = self.select(tool, self.env()) - self.assertEqual(first["BL_FSYNC"], "1") + self.assertEqual(first["DD_FSYNC"], "1") rows = json.loads((root / "prefixes.json").read_text()) - self.assertEqual(rows[prefix]["env"]["BL_FSYNC"], "1") - self.assertIsNone(rows[prefix]["env"]["BL_SYNC_PACK"]) + self.assertEqual(rows[prefix]["env"]["DD_FSYNC"], "1") + self.assertIsNone(rows[prefix]["env"]["DD_SYNC_PACK"]) pack = make_pack(root, tool, "valve-experimental-r1") dist = self.dist_of(pack["id"], tool) running = [] with mock.patch.dict(GLOBALS, {"server_running": lambda path: running.append(path) or True}): - command, env, said = self.select(tool, self.env(BL_SYNC="0", WINEFSYNC=None)) + command, env, said = self.select(tool, self.env(DD_SYNC="0", WINEFSYNC=None)) self.assertEqual(running, [prefix]) self.assertEqual(command[0], str(tool / "proton")) - self.assertEqual(env, self.env(BL_SYNC="0", BL_FSYNC="1", WINEFSYNC="1")) + self.assertEqual(env, self.env(DD_SYNC="0", DD_FSYNC="1", WINEFSYNC="1")) self.assertEqual(said, "droiddeck-esync: Wine is still running in this prefix; keeping its sync choice (droiddeck-fsync)\n") command, env, said = self.select(tool, self.env()) - self.assertEqual((command[0], env["BL_SYNC_PACK"]), (str(dist / "proton"), pack["id"])) - self.assertNotIn("BL_FSYNC", env) + self.assertEqual((command[0], env["DD_SYNC_PACK"]), (str(dist / "proton"), pack["id"])) + self.assertNotIn("DD_FSYNC", env) with mock.patch.dict(GLOBALS, {"server_running": lambda path: True}): - command, env, said = self.select(tool, self.env(BL_FSYNC_FIRST="1")) - self.assertEqual((command[0], env["BL_SYNC_PACK"], env["WINESERVER"]), (str(dist / "proton"), pack["id"], str(dist / WINESERVER))) - self.assertNotIn("BL_FSYNC", env) + command, env, said = self.select(tool, self.env(DD_FSYNC_FIRST="1")) + self.assertEqual((command[0], env["DD_SYNC_PACK"], env["WINESERVER"]), (str(dist / "proton"), pack["id"], str(dist / WINESERVER))) + self.assertNotIn("DD_FSYNC", env) self.assertIn("(droiddeck-esync)", said) other = make_tool(self.tools, "Proton 11.0 (ARM64)", salt=b"11", fsync=True) - self.assertEqual(self.select(other, self.env())[1]["BL_FSYNC"], "1") + self.assertEqual(self.select(other, self.env())[1]["DD_FSYNC"], "1") shutil.rmtree(self.root / "dist") command, env, said = self.select(tool, self.env()) - self.assertEqual((command[0], env["BL_SYNC_PACK"]), (str(dist / "proton"), pack["id"])) + self.assertEqual((command[0], env["DD_SYNC_PACK"]), (str(dist / "proton"), pack["id"])) self.assertNotIn("keeping", said) (root / "prefixes.json").write_text("not json") with mock.patch.dict(GLOBALS, {"server_running": lambda path: True}): - self.assertEqual(self.select(tool, self.env())[1]["BL_SYNC_PACK"], pack["id"]) - self.assertEqual(json.loads((root / "prefixes.json").read_text())[prefix]["env"]["BL_SYNC_PACK"], pack["id"]) + self.assertEqual(self.select(tool, self.env())[1]["DD_SYNC_PACK"], pack["id"]) + self.assertEqual(json.loads((root / "prefixes.json").read_text())[prefix]["env"]["DD_SYNC_PACK"], pack["id"]) def test_a_running_prefix_drops_a_pack_that_no_longer_fits(self): root = self.store() @@ -645,31 +645,31 @@ class SelectTest(SyncTestCase): self.assertEqual(self.select(tool, self.env())[0][0], str(dist / "proton")) with mock.patch.dict(GLOBALS, {"server_running": lambda path: True}): command, env, said = self.select(tool, self.env()) - self.assertEqual((command[0], env["BL_SYNC_PACK"]), (str(dist / "proton"), pack["id"])) + self.assertEqual((command[0], env["DD_SYNC_PACK"]), (str(dist / "proton"), pack["id"])) self.assertIn("keeping its sync choice", said) (tool / NTDLL).write_bytes(elf(EXPORTS, salt=b"updated in place")) (tool / "version").write_text("1791000000 experimental-11.0-20261008-arm64\n") command, env, said = self.select(tool, self.env(), verb="run") - self.assertEqual((command[0], env["BL_SYNC_PACK"]), (str(dist / "proton"), pack["id"])) + self.assertEqual((command[0], env["DD_SYNC_PACK"]), (str(dist / "proton"), pack["id"])) self.assertIn("keeping its sync choice", said) command, env, said = self.select(tool, self.env()) self.assertEqual(command[0], str(tool / "proton")) - self.assertNotIn("BL_SYNC_PACK", env) + self.assertNotIn("DD_SYNC_PACK", env) self.assertNotIn("keeping", said) self.assertIn("no pack for Proton Experimental (ARM64)", said) other = make_tool(self.tools, "Proton 11.0 (ARM64)", "1788504814 proton-11.0-2c-arm64", salt=b"2c") pack = make_pack(root, other, "valve-proton-11.0-2c-arm64-r1") dist = self.dist_of(pack["id"], other) - self.assertEqual(self.select(other, self.env())[1]["BL_SYNC_PACK"], pack["id"]) + self.assertEqual(self.select(other, self.env())[1]["DD_SYNC_PACK"], pack["id"]) rev2 = make_pack(root, other, "valve-proton-11.0-2c-arm64-r2", rev=2) with mock.patch.dict(GLOBALS, {"server_running": lambda path: True}): - self.assertEqual(self.select(other, self.env(), verb="run")[1]["BL_SYNC_PACK"], pack["id"]) - self.assertEqual(self.select(other, self.env())[1]["BL_SYNC_PACK"], rev2["id"]) + self.assertEqual(self.select(other, self.env(), verb="run")[1]["DD_SYNC_PACK"], pack["id"]) + self.assertEqual(self.select(other, self.env())[1]["DD_SYNC_PACK"], rev2["id"]) for gone in (pack, rev2): data = json.loads((root / "packs" / gone["id"] / "pack.json").read_text()) (root / "packs" / gone["id"] / "pack.json").write_text(json.dumps(dict(data, revoked=True))) with mock.patch.dict(GLOBALS, {"server_running": lambda path: True}): - self.assertEqual(self.select(other, self.env(), verb="run")[1]["BL_SYNC_PACK"], rev2["id"]) + self.assertEqual(self.select(other, self.env(), verb="run")[1]["DD_SYNC_PACK"], rev2["id"]) command, env, said = self.select(other, self.env()) self.assertEqual(command[0], str(other / "proton")) self.assertNotIn("keeping", said) @@ -677,8 +677,8 @@ class SelectTest(SyncTestCase): def test_droiddeck_ntsync_does_not_stand_in_when_esync_is_off(self): self.store() tool = make_tool(self.tools, "Proton Experimental (ARM64)") - env = self.env(BL_SYNC="0") - env.pop("BL_SYNC_FALLBACK", None) + env = self.env(DD_SYNC="0") + env.pop("DD_SYNC_FALLBACK", None) command, chosen, said = self.select(tool, env) self.assertEqual(chosen, SYNC["wineserver_only"](env)) self.assertEqual(said, "droiddeck-esync: off; wineserver sync only\n") @@ -686,38 +686,38 @@ class SelectTest(SyncTestCase): def test_the_wineserver_tab_turns_proton_sync_off(self): self.store() tool = make_tool(self.tools, "GE-Proton11-9", "1790000000 GE-Proton11-9", builtin=True, ge=True, fsync=True) - command, env, said = self.select(tool, self.env(BL_SYNC_FALLBACK="0")) + command, env, said = self.select(tool, self.env(DD_SYNC_FALLBACK="0")) self.assertEqual(command[0], str(tool / "proton")) - self.assertEqual({name: env.get(name) for name in ("PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC", "WINEFSYNC", "BL_SYNC")}, - {"PROTON_NO_ESYNC": "1", "PROTON_NO_FSYNC": "1", "PROTON_NO_NTSYNC": "1", "WINEESYNC": "0", "WINEFSYNC": "0", "BL_SYNC": "0"}) - env = self.select(tool, self.env(BL_SYNC_FALLBACK="0", PROTON_NO_FSYNC="0"))[1] + self.assertEqual({name: env.get(name) for name in ("PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC", "WINEFSYNC", "DD_SYNC")}, + {"PROTON_NO_ESYNC": "1", "PROTON_NO_FSYNC": "1", "PROTON_NO_NTSYNC": "1", "WINEESYNC": "0", "WINEFSYNC": "0", "DD_SYNC": "0"}) + env = self.select(tool, self.env(DD_SYNC_FALLBACK="0", PROTON_NO_FSYNC="0"))[1] self.assertEqual((env["PROTON_NO_FSYNC"], "WINEFSYNC" in env, env["PROTON_NO_ESYNC"]), ("0", False, "1")) self.assertEqual(SYNC["describe"](SYNC["wineserver_only"]({})), "wineserver") def test_the_ntsync_tab_needs_a_wine_with_ntsync(self): root = self.store() tool = make_tool(self.tools, "Proton 11.0 (ARM64)", "1789000000 proton-11.0-3", fsync=True, ntsync=False) - command, env, said = self.select(tool, self.env(BL_SYNC="1")) - self.assertEqual((command[0], env["BL_SYNC"], env["BL_FSYNC"], env["WINEFSYNC"]), (str(tool / "proton"), "0", "1", "1")) + command, env, said = self.select(tool, self.env(DD_SYNC="1")) + self.assertEqual((command[0], env["DD_SYNC"], env["DD_FSYNC"], env["WINEFSYNC"]), (str(tool / "proton"), "0", "1", "1")) self.assertIn("droiddeck-ntsync: Proton 11.0 (ARM64) has no ntsync; trying droiddeck-fsync\n", said) plain = make_tool(self.tools, "Proton 10.0 (ARM64)", "1780000000 proton-10.0-1", salt=b"p", ntsync=False) - command, env, said = self.select(plain, self.env(BL_SYNC="1")) - self.assertEqual((env["BL_SYNC"], "BL_FSYNC" in env), ("0", False)) + command, env, said = self.select(plain, self.env(DD_SYNC="1")) + self.assertEqual((env["DD_SYNC"], "DD_FSYNC" in env), ("0", False)) self.assertTrue(said.endswith("; stock binaries (this Wine has no ntsync)\n"), said) pack = make_pack(root, plain, "valve-10-r1") command, env, said = self.select(plain, self.env(PROTON_NO_ESYNC="1")) - self.assertEqual((env["BL_SYNC_PACK"], env["WINEESYNC"], env.get("BL_SYNC")), (pack["id"], "0", None)) + self.assertEqual((env["DD_SYNC_PACK"], env["WINEESYNC"], env.get("DD_SYNC")), (pack["id"], "0", None)) def test_built_in_esync_still_falls_back_when_esync_is_off(self): self.store() tool = make_tool(self.tools, "GE-Proton11-9", "1790000000 GE-Proton11-9", builtin=True, ge=True, fsync=True) for extra in ({"PROTON_NO_ESYNC": "1"}, {"WINEESYNC": "0"}, {"STEAM_COMPAT_APP_ID": "2630", "PROTON_NO_FSYNC": "0"}): command, env, said = self.select(tool, self.env(**extra)) - self.assertEqual((command[0], env["BL_FSYNC"]), (str(tool / "proton"), "1"), extra) + self.assertEqual((command[0], env["DD_FSYNC"]), (str(tool / "proton"), "1"), extra) plain = make_tool(self.tools, "GE-Proton11-8", "1789900000 GE-Proton11-8", salt=b"g", builtin=True, ge=True) for extra in ({"PROTON_NO_ESYNC": "1"}, {"STEAM_COMPAT_APP_ID": "2630"}): command, env, said = self.select(plain, self.env(**extra)) - self.assertEqual((env["BL_SYNC"], env["PROTON_NO_ESYNC"], env["WINEESYNC"]), ("1", "1", "0"), extra) + self.assertEqual((env["DD_SYNC"], env["PROTON_NO_ESYNC"], env["WINEESYNC"]), ("1", "1", "0"), extra) self.assertTrue(said.endswith("; stock binaries with droiddeck-ntsync\n"), (extra, said)) command, env, said = self.select(plain, self.env()) self.assertEqual(said, "droiddeck-esync: GE-Proton11-8 has esync built in\n") @@ -729,11 +729,11 @@ class SelectTest(SyncTestCase): command, env, said = self.select(tool, self.env()) prefix = os.path.realpath("/compatdata/42/pfx") rows = json.loads((root / "prefixes.json").read_text()) - self.assertEqual(rows[prefix]["env"]["BL_SYNC_PACK"], pack["id"]) + self.assertEqual(rows[prefix]["env"]["DD_SYNC_PACK"], pack["id"]) stock = [str(tool / "proton"), "waitforexitandrun", "game.exe"] self.quiet(SYNC["record"], stock, self.env()) rows = json.loads((root / "prefixes.json").read_text()) - self.assertEqual((rows[prefix]["command"], rows[prefix]["env"]["BL_SYNC_PACK"]), (stock[0], None)) + self.assertEqual((rows[prefix]["command"], rows[prefix]["env"]["DD_SYNC_PACK"]), (stock[0], None)) def test_built_in_esync_never_uses_a_pack(self): root = self.store() @@ -751,7 +751,7 @@ class SelectTest(SyncTestCase): tool = make_tool(self.tools, "DroidDeck-Proton 11-7.5", "1791000000 DroidDeck-Proton-11-7.5", builtin=True, ge=True, fsync=True) command, env, said = self.select(tool, self.env()) self.assertEqual(command[0], str(tool / "proton")) - self.assertNotIn("BL_SYNC_PACK", env) + self.assertNotIn("DD_SYNC_PACK", env) self.assertEqual(said, "droiddeck-esync: DroidDeck-Proton 11-7.5 has esync built in\n") self.assertFalse((root / "wanted.tsv").exists()) self.assertFalse((root / "dist").exists()) @@ -763,7 +763,7 @@ class SelectTest(SyncTestCase): self.assertEqual(command[0], str(tool / "proton")) self.assertEqual(said, "droiddeck-esync: no pack for GE-Proton11-7 (%s, ntdll %s); stock binaries with droiddeck-ntsync\n" % (GE_LINE, sha(tool / NTDLL)[:12])) - self.assertEqual(env["BL_SYNC"], "1") + self.assertEqual(env["DD_SYNC"], "1") wanted = root / "wanted.tsv" rows = [line.split("\t") for line in wanted.read_text().splitlines()] self.assertEqual(len(rows), 1) @@ -904,13 +904,13 @@ class ReconcileTest(SyncTestCase): wanted = [line.split("\t") for line in (root / "wanted.tsv").read_text().splitlines()] self.assertEqual(sorted(row[4] for row in wanted), sorted([str(loose), str(ge)])) self.assertTrue((root / "hash-cache.tsv").is_file()) - summary = self.quiet(SYNC["reconcile"], str(steam), {"HOME": str(self.home), "BL_SYNC_FALLBACK": "1"}) + summary = self.quiet(SYNC["reconcile"], str(steam), {"HOME": str(self.home), "DD_SYNC_FALLBACK": "1"}) self.assertEqual(summary, "droiddeck-esync: 1 pack(s) in use, 2 wanted") dist = self.dist_of(pack["id"], valve) self.assertEqual(json.loads((dist / RECORD).read_text())["tool"], str(valve)) make_pack(root, ge, "ge-GE-Proton11-7-r1", flavor="ge") make_pack(root, loose, "ge-GE-Proton10-1-r1", flavor="ge") - summary = self.quiet(SYNC["reconcile"], str(steam), {"HOME": str(self.home), "BL_SYNC_FALLBACK": "1"}) + summary = self.quiet(SYNC["reconcile"], str(steam), {"HOME": str(self.home), "DD_SYNC_FALLBACK": "1"}) self.assertEqual(summary, "droiddeck-esync: 2 pack(s) in use, 0 wanted") self.assertEqual((root / "wanted.tsv").read_text(), "") self.assertTrue(self.dist_of("ge-GE-Proton11-7-r1", ge).is_dir()) @@ -928,7 +928,7 @@ class ReconcileTest(SyncTestCase): def test_steam_compatibility_reports_sync(self): steam = self.tmp / "steam" make_tool(steam / "steamapps/common", "Proton Experimental (ARM64)") - env = {"PATH": os.defpath, "HOME": str(self.home), "BL_SYNC_FALLBACK": "1"} + env = {"PATH": os.defpath, "HOME": str(self.home), "DD_SYNC_FALLBACK": "1"} result = subprocess.run([sys.executable, str(BIN / "steam-compatibility"), str(steam)], env=env, capture_output=True, text=True, check=True) self.assertNotIn("droiddeck-esync", result.stdout + result.stderr) @@ -970,7 +970,7 @@ class ReconcileTest(SyncTestCase): self.assertFalse(dist.exists()) new = make_pack(root, tool, "valve-experimental-20261008-r1") command, env, said = self.select(tool, self.env()) - self.assertEqual((command[0], env["BL_SYNC_PACK"]), (str(self.dist_of(new["id"], tool) / "proton"), new["id"])) + self.assertEqual((command[0], env["DD_SYNC_PACK"]), (str(self.dist_of(new["id"], tool) / "proton"), new["id"])) summary = self.quiet(SYNC["reconcile"], str(steam), {"HOME": str(self.home)}) self.assertEqual(summary, "droiddeck-esync: 1 pack(s) in use, 0 wanted") @@ -1033,7 +1033,7 @@ class GcTest(SyncTestCase): self.assertEqual(sorted(os.listdir(root / "dist")), [second_dist.name, second_dist.name + ".lock"]) self.assertTrue((root / "packs" / first["id"] / ".complete").is_file()) _, env, _ = self.select(tool, self.env()) - self.assertEqual(env["BL_SYNC_PACK"], second["id"]) + self.assertEqual(env["DD_SYNC_PACK"], second["id"]) class LauncherTest(SyncTestCase): @@ -1042,9 +1042,9 @@ class LauncherTest(SyncTestCase): config = self.home / ".config/droiddeck/game-environment.json" config.parent.mkdir(parents=True) config.write_text(json.dumps({"version": 1, "shared": {"PROTON_NO_NTSYNC": "1", "CUSTOM": "shared"}, - "games": {"42": {"WINEESYNC": "3", "BL_SYNC_FALLBACK": "1"}}})) - env = {"PATH": os.defpath, "HOME": str(self.home), "STEAM_COMPAT_DATA_PATH": "/compatdata/42", "BL_SYNC": "1", - "BL_SYNC_MIN_NOFILE": "1"} + "games": {"42": {"WINEESYNC": "3", "DD_SYNC_FALLBACK": "1"}}})) + env = {"PATH": os.defpath, "HOME": str(self.home), "STEAM_COMPAT_DATA_PATH": "/compatdata/42", "DD_SYNC": "1", + "DD_SYNC_MIN_NOFILE": "1"} def launch(verb): output = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(tool / "proton"), verb, "a b"], @@ -1053,7 +1053,7 @@ class LauncherTest(SyncTestCase): argv0, args, seen = launch("run") self.assertEqual((argv0, args), (str(tool / "proton"), ["run", "a b"])) - self.assertEqual((seen["CUSTOM"], seen["BL_SYNC"], seen["WINEESYNC"]), (None, "0", "3")) + self.assertEqual((seen["CUSTOM"], seen["DD_SYNC"], seen["WINEESYNC"]), (None, "0", "3")) self.assertEqual(launch("waitforexitandrun")[2]["CUSTOM"], "shared") root = self.store() pack = make_pack(root, tool, "valve-experimental-r1") @@ -1061,7 +1061,7 @@ class LauncherTest(SyncTestCase): for verb in ("run", "waitforexitandrun", "getcompatpath"): argv0, args, seen = launch(verb) self.assertEqual((argv0, args), (str(dist / "proton"), [verb, "a b"])) - self.assertEqual((seen["WINEESYNC"], seen["BL_SYNC_PACK"], seen["WINESERVER"]), ("3", pack["id"], str(dist / WINESERVER))) + self.assertEqual((seen["WINEESYNC"], seen["DD_SYNC_PACK"], seen["WINESERVER"]), ("3", pack["id"], str(dist / WINESERVER))) def test_failed_dist_exec_keeps_the_sync_choice(self): tool = make_tool(self.tools, "Proton Experimental (ARM64)") @@ -1077,7 +1077,7 @@ class LauncherTest(SyncTestCase): ) for inherited, expected in cases: with self.subTest(inherited=inherited): - env = self.env(STEAM_COMPAT_APP_ID="2630", PROTON_NO_NTSYNC="1", BL_SYNC="1", WINEESYNC="1", **inherited) + env = self.env(STEAM_COMPAT_APP_ID="2630", PROTON_NO_NTSYNC="1", DD_SYNC="1", WINEESYNC="1", **inherited) calls = [] def execvpe(path, args, environment): @@ -1092,8 +1092,8 @@ class LauncherTest(SyncTestCase): game_env["main"]() self.assertEqual([call[:2] for call in calls], [(str(dist / "proton"), [str(dist / "proton")] + command[1:]), (str(tool / "proton"), command)]) - self.assertEqual((calls[0][2]["WINEESYNC"], calls[0][2]["PROTON_NO_ESYNC"], calls[0][2]["BL_SYNC_PACK"]), ("0", "1", pack["id"])) - self.assertEqual(calls[1][2], self.env(STEAM_COMPAT_APP_ID="2630", PROTON_NO_NTSYNC="1", BL_SYNC="0", WINEESYNC="1", + self.assertEqual((calls[0][2]["WINEESYNC"], calls[0][2]["PROTON_NO_ESYNC"], calls[0][2]["DD_SYNC_PACK"]), ("0", "1", pack["id"])) + self.assertEqual(calls[1][2], self.env(STEAM_COMPAT_APP_ID="2630", PROTON_NO_NTSYNC="1", DD_SYNC="0", WINEESYNC="1", vblank_mode="0", GAMESCOPE_WSI_MIN_IMAGE_COUNT="8", GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT="1", **expected)) self.assertEqual(calls[0][2].get("WINEDLLOVERRIDES"), expected.get("WINEDLLOVERRIDES")) @@ -1112,7 +1112,7 @@ class LauncherTest(SyncTestCase): packs = {depot: make_pack(root, depot, "valve-experimental-r1"), extra: make_pack(root, extra, "ge-GE-Proton11-7-r1", flavor="ge")} wrappers = {depot: tools / COMPAT["TOOL"] / COMPAT["LAUNCHER"], extra: extra / COMPAT["EXTRA_WRAPPER"]} env = {"PATH": os.defpath, "HOME": str(self.home), "STEAM_COMPAT_DATA_PATH": "/compatdata/42", - "STEAM_COMPAT_CLIENT_INSTALL_PATH": str(steam), "BL_SYNC_FALLBACK": "1", "BL_SYNC_MIN_NOFILE": "1"} + "STEAM_COMPAT_CLIENT_INSTALL_PATH": str(steam), "DD_SYNC_FALLBACK": "1", "DD_SYNC_MIN_NOFILE": "1"} for tool, wrapper in wrappers.items(): wrapper.write_text(wrapper.read_text().replace("/usr/local/bin/droiddeck-game-env", str(BIN / "droiddeck-game-env"))) dist = self.dist_of(packs[tool]["id"], tool) @@ -1120,13 +1120,13 @@ class LauncherTest(SyncTestCase): self.assertEqual(result.returncode, 0, result.stderr) argv0, args, seen = json.loads(result.stdout) self.assertEqual((argv0, args), (str(dist / "proton"), ["waitforexitandrun", "game with spaces.exe"])) - self.assertEqual((seen["BL_SYNC_PACK"], seen["WINESERVER"], seen["WINEESYNC"]), + self.assertEqual((seen["DD_SYNC_PACK"], seen["WINESERVER"], seen["WINEESYNC"]), (packs[tool]["id"], str(dist / WINESERVER), "1")) self.assertIn("droiddeck-esync: pack %s" % packs[tool]["id"], result.stderr) for name in ("droiddeck-proton-wrap", "toolmanifest.vdf", "compatibilitytool.vdf", "toolmanifest.vdf.droiddeck-orig", "bannerlator-proton-wrap", "toolmanifest.vdf.bannerlator-orig"): self.assertFalse(os.path.lexists(dist / name), name) - result = subprocess.run([str(wrapper), "waitforexitandrun"], env={**env, "BL_SYNC_FALLBACK": "0"}, text=True, capture_output=True) + result = subprocess.run([str(wrapper), "waitforexitandrun"], env={**env, "DD_SYNC_FALLBACK": "0"}, text=True, capture_output=True) self.assertEqual(json.loads(result.stdout)[0], str(tool / "proton"), result.stderr) def test_session_collects_sync_tables(self): @@ -1134,7 +1134,7 @@ class LauncherTest(SyncTestCase): start = script.index("collect_steam_logs() {") function = script[start:script.index("\n}\n", start) + 3] debug = self.tmp / "debug" - env = {"PATH": os.defpath, "HOME": str(self.home), "BL_DEBUG_DIR": str(debug)} + env = {"PATH": os.defpath, "HOME": str(self.home), "DD_DEBUG_DIR": str(debug)} subprocess.run(["bash", "-c", "set -u\n" + function + "collect_steam_logs"], env=env, check=True, capture_output=True) self.assertFalse((debug / "droiddeck-esync").exists()) root = self.store() diff --git a/tools/tests/test_fex_gl_thunk_errors.py b/tools/tests/test_fex_gl_thunk_errors.py new file mode 100644 index 0000000000..3afa881e47 --- /dev/null +++ b/tools/tests/test_fex_gl_thunk_errors.py @@ -0,0 +1,474 @@ +import os +import re +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest +from unittest import mock + +PATCH = Path(__file__).resolve().parents[1] / "fex/patches/0005-gl-thunk-forward-x-errors.patch" + + +def added(path, start, end): + text = PATCH.read_text() + section = re.search(r"^diff --git a/%s .*?(?=^diff --git |\Z)" % re.escape(path), text, re.S | re.M) + lines = [line[1:] for line in section.group(0).splitlines() if line.startswith("+") and not line.startswith("+++")] + body = "\n".join(lines) + first = body.index(start) + last = body.index(end, first) + len(end) + return body[first:last] + + +HARNESS = r""" +#include +#include +#include +#include +#include +#include +#include +#include +using guest_long = long; + +static std::mutex host_user_lock; +static std::mutex guest_user_lock; +static void guest_lock(Display*) { guest_user_lock.lock(); } +static void guest_unlock(Display*) { guest_user_lock.unlock(); } +static _XLockPtrs guest_lock_fns {guest_lock, guest_unlock}; + +struct X11Manager { + MUTEX_SOURCE + std::map<_XDisplay*, _XDisplay*> displays; + FORWARD_SOURCE + FIND_SOURCE + static XErrorHandler HostXSetErrorHandler(XErrorHandler Handler) { return XSetErrorHandler(Handler); } + static void HostXLockDisplay(Display*) { host_user_lock.lock(); } + static void HostXUnlockDisplay(Display*) { host_user_lock.unlock(); } +}; + +static X11Manager x11_manager; +static int (*pending_forward)(void*, guest_long, int, int, int); + +template +static void MakeHostTrampolineForGuestFunctionAt(uintptr_t, uintptr_t, F** Func) { *Func = pending_forward; } + +static int guest_set_calls; +#define XSetErrorHandler(h) (guest_set_calls++, ::XSetErrorHandler(h)) +GUEST_SOURCE +#undef XSetErrorHandler + +HOST_SOURCE + +static Display* app_display; +static XErrorEvent app_event; +static int app_calls; +static int app_handler(Display* display, XErrorEvent* event) { + app_display = display; + app_event = *event; + app_calls++; + return 7; +} + +static int previous_calls; +static Display* previous_display; +static int previous_handler(Display* display, XErrorEvent*) { + previous_calls++; + previous_display = display; + return 3; +} + +static int guest_forward(void* display, guest_long resourceid, int error_code, int request_code, int minor_code) { + return ForwardXError(static_cast(display), resourceid, error_code, request_code, minor_code); +} + +static _XDisplay guest_connection; + +static int raise_on_host(XErrorHandler handler, Display* display, XErrorEvent* event) { + std::lock_guard held(host_user_lock); + return handler(display, event); +} + +int main(int argc, char** argv) { + auto host = reinterpret_cast(uintptr_t {0x1000}); + auto guest = &guest_connection; + auto other = reinterpret_cast(uintptr_t {0x3000}); + guest_connection.request = 44; + guest_connection.last_request_read = 44; + guest_connection.lock_fns = &guest_lock_fns; + x11_manager.displays[guest] = host; + pending_forward = guest_forward; + XSetErrorHandler(previous_handler); + fexfn_impl_libGL_GL_SetGuestXErrorForward(0, 0); + fexfn_impl_libGL_GL_SetGuestXErrorForward(0, 0); + XErrorHandler installed = XSetErrorHandler(nullptr); + XSetErrorHandler(installed); + + XErrorEvent event {}; + event.type = 0; + event.display = host; + event.resourceid = 0xffffffff; + event.serial = 9000; + event.error_code = 163; + event.request_code = 148; + event.minor_code = 0; + + XSetErrorHandler(app_handler); + if (argc > 1 && strcmp(argv[1], "reentry") == 0) { + std::unique_lock lock(x11_manager.mutex); + int reentry = raise_on_host(installed, host, &event); + printf("reentry=%d app_calls=%d\n", reentry, app_calls); + return 0; + } + if (argc > 1 && strcmp(argv[1], "crosslock") == 0) { + host_user_lock.lock(); + std::mutex ready_lock; + std::unique_lock ready(ready_lock); + std::condition_variable guest_held; + bool held = false; + std::thread other_thread([&] { + guest_user_lock.lock(); + { + std::lock_guard notify(ready_lock); + held = true; + } + guest_held.notify_one(); + host_user_lock.lock(); + host_user_lock.unlock(); + guest_user_lock.unlock(); + }); + guest_held.wait(ready, [&] { return held; }); + ready.unlock(); + int crossed = installed(host, &event); + host_user_lock.unlock(); + other_thread.join(); + printf("crosslock=%d app_calls=%d\n", crossed, app_calls); + return 0; + } + int owned = raise_on_host(installed, host, &event); + XErrorHandler after = XSetErrorHandler(installed); + int foreign = raise_on_host(installed, other, &event); + + printf("owned=%d app_calls=%d app_display_is_guest=%d serial=%lu error=%d request=%d minor=%d resource=%lx handler_kept=%d guest_set_calls=%d\n", + owned, app_calls, app_display == guest, app_event.serial, app_event.error_code, app_event.request_code, + app_event.minor_code, app_event.resourceid, after == app_handler, guest_set_calls); + printf("foreign=%d previous_calls=%d previous_display_is_other=%d\n", foreign, previous_calls, previous_display == other); + return 0; +} +""" + + +REAL_HARNESS = r""" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +using guest_long = long; + +struct X11Manager { + MUTEX_SOURCE + std::map<_XDisplay*, _XDisplay*> displays; + FORWARD_SOURCE + FIND_SOURCE + static XErrorHandler HostXSetErrorHandler(XErrorHandler Handler) { return XSetErrorHandler(Handler); } + static void HostXLockDisplay(Display* a) { XLockDisplay(a); } + static void HostXUnlockDisplay(Display* a) { XUnlockDisplay(a); } +}; + +static X11Manager x11_manager; +static int (*pending_forward)(void*, guest_long, int, int, int); + +template +static void MakeHostTrampolineForGuestFunctionAt(uintptr_t, uintptr_t, F** Func) { *Func = pending_forward; } + +GUEST_SOURCE + +HOST_SOURCE + +static Display* host; +static Display* guest; +static std::atomic app_calls; +static std::atomic guest_calls; +static unsigned long app_serial; +static int app_error; +static int app_minor; +static std::atomic forwarding_started {false}; + +static int guest_forward(void* display, guest_long resourceid, int error_code, int request_code, int minor_code) { + forwarding_started = true; + forwarding_started.notify_one(); + return ForwardXError(static_cast(display), resourceid, error_code, request_code, minor_code); +} + +static int app_handler(Display* display, XErrorEvent* event) { + if (display == guest) { + guest_calls++; + app_serial = event->serial; + app_error = event->error_code; + app_minor = event->minor_code; + } + app_calls++; + return 0; +} + +static bool host_usable_from_other_thread() { + std::atomic done {false}; + std::thread other([&] { + XNoOp(host); + XSync(host, False); + done = true; + }); + for (int i = 0; i < 300 && !done; i++) { + usleep(10000); + } + if (!done) { + return false; + } + other.join(); + return true; +} + +int main(int argc, char** argv) { + XInitThreads(); + host = XOpenDisplay(nullptr); + guest = XOpenDisplay(nullptr); + if (!host || !guest) { + return 2; + } + x11_manager.displays[guest] = host; + pending_forward = guest_forward; + XSetErrorHandler(app_handler); + fexfn_impl_libGL_GL_SetGuestXErrorForward(0, 0); + + if (argc > 1) { + auto library = dlopen("libGL.so.1", RTLD_NOW | RTLD_LOCAL); + if (!library) { + return 3; + } + auto choose = reinterpret_cast(dlsym(library, "glXChooseFBConfig")); + auto get_proc = reinterpret_cast(dlsym(library, "glXGetProcAddressARB")); + auto query = reinterpret_cast(dlsym(library, "glXQueryExtension")); + auto destroy = reinterpret_cast(dlsym(library, "glXDestroyContext")); + if (!choose || !get_proc || !query || !destroy) { + return 4; + } + auto create = reinterpret_cast(get_proc( + reinterpret_cast("glXCreateContextAttribsARB"))); + if (!create) { + return 5; + } + int error_base, event_base, count; + if (!query(host, &error_base, &event_base)) { + return 6; + } + const int config_attribs[] = {GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, None}; + auto configs = choose(host, DefaultScreen(host), config_attribs, &count); + if (!configs || count == 0) { + return 7; + } + const int supported[] = {GLX_CONTEXT_MAJOR_VERSION_ARB, 2, GLX_CONTEXT_MINOR_VERSION_ARB, 1, None}; + auto initial = create(host, configs[0], nullptr, True, supported); + if (!initial) { + return 8; + } + destroy(host, initial); + if (strcmp(argv[1], "default") == 0) { + XSetErrorHandler(nullptr); + fexfn_impl_libGL_GL_SetGuestXErrorForward(0, 0); + } + const int unsupported[] = {GLX_CONTEXT_MAJOR_VERSION_ARB, 4, GLX_CONTEXT_MINOR_VERSION_ARB, 6, None}; + auto rejected = create(host, configs[0], nullptr, True, unsupported); + XSync(host, False); + auto fallback = create(host, configs[0], nullptr, True, supported); + printf("valid_config=1 rejected=%d guest_errors=%d bad_fbconfig=%d minor_zero=%d fallback=%d\n", + rejected == nullptr, guest_calls.load(), app_error == error_base + GLXBadFBConfig, + app_minor == 0, fallback != nullptr); + if (fallback) { + destroy(host, fallback); + } + XFree(configs); + fflush(stdout); + _exit(0); + } + + std::atomic guest_held {false}; + std::atomic host_reached {false}; + std::thread contender([&] { + XLockDisplay(guest); + guest_held = true; + forwarding_started.wait(false); + XNoOp(host); + XFlush(host); + host_reached = true; + XUnlockDisplay(guest); + }); + while (!guest_held) { + usleep(1000); + } + XFreePixmap(host, 1); + XSync(host, False); + contender.join(); + bool usable = host_usable_from_other_thread(); + printf("app_calls=%d guest_calls=%d host_reached=%d usable=%d serial_from_guest=%d\n", app_calls.load(), + guest_calls.load(), host_reached.load(), usable, app_serial != 0 && app_serial <= guest->request); + fflush(stdout); + _exit(0); +} +""" + + +def compile_cpp(source, output): + return subprocess.run(["c++", "-std=c++20", "-O1", "-Wall", "-Werror", "-pthread", "-o", str(output), str(source), "-lX11"], + capture_output=True, text=True) + + +@unittest.skipUnless(shutil.which("c++"), "needs c++") +class FexGlThunkErrorForwardTest(unittest.TestCase): + HARNESS_SOURCE = HARNESS + DEPENDENCY_HEADERS = ("X11/Xlibint.h",) + + @classmethod + def setUpClass(cls): + guest = added("ThunkLibs/libGL/libGL_Guest.cpp", "static int ForwardXError(", "\n}") + host = added("ThunkLibs/libGL/libGL_Host.cpp", "static XErrorHandler HostPreviousXErrorHandler", + " HostPreviousXErrorHandler = Previous;\n }\n}") + manager = "ThunkLibs/include/common/X11Manager.h" + mutex = added(manager, "std::", " mutex;") + forward = added(manager, "int (*GuestXErrorForward)", "= nullptr;") + find = added(manager, "_XDisplay* FindGuestDisplay(", " return nullptr;\n }") + cls.tmp = Path(tempfile.mkdtemp()) + cls.addClassCleanup(shutil.rmtree, cls.tmp) + probe = cls.tmp / "probe.cpp" + probe.write_text("".join(f"#include <{header}>\n" for header in cls.DEPENDENCY_HEADERS) + + "int main() { return 0; }\n") + if compile_cpp(probe, cls.tmp / "probe").returncode != 0: + raise unittest.SkipTest("needs the native development files for this harness") + source = cls.tmp / "harness.cpp" + source.write_text(cls.HARNESS_SOURCE.replace("MUTEX_SOURCE", mutex).replace("FORWARD_SOURCE", forward) + .replace("FIND_SOURCE", find).replace("GUEST_SOURCE", guest).replace("HOST_SOURCE", host)) + cls.program = cls.tmp / "harness" + result = compile_cpp(source, cls.program) + if result.returncode != 0: + raise AssertionError(result.stderr) + + def run_harness(self, *args): + try: + result = subprocess.run([str(self.program), *args], capture_output=True, text=True, timeout=10) + except subprocess.TimeoutExpired: + self.fail("the host error handler blocked") + self.assertEqual(result.returncode, 0, result.stderr) + return result.stdout.splitlines() + + def test_error_on_a_host_display_reaches_the_programs_handler(self): + owned = self.run_harness()[0] + self.assertIn("owned=7 app_calls=1 app_display_is_guest=1", owned) + self.assertIn("error=163 request=148 minor=0 resource=ffffffff", owned) + self.assertIn("handler_kept=1", owned) + + def test_forwarded_error_carries_the_programs_own_serial(self): + self.assertIn(" serial=44 ", self.run_harness()[0]) + + def test_forwarding_never_swaps_the_programs_handler(self): + self.assertIn("guest_set_calls=0", self.run_harness()[0]) + + def test_error_while_the_display_lock_is_held_does_not_block(self): + self.assertEqual(self.run_harness("reentry"), ["reentry=7 app_calls=1"]) + + def test_error_while_another_thread_holds_the_programs_display_lock_does_not_deadlock(self): + self.assertEqual(self.run_harness("crosslock"), ["crosslock=7 app_calls=1"]) + + def test_error_on_a_display_the_gl_thunk_does_not_own_keeps_the_previous_handler(self): + self.assertEqual(self.run_harness()[1], "foreign=3 previous_calls=1 previous_display_is_other=1") + + +@unittest.skipUnless(shutil.which("c++") and shutil.which("Xvfb"), "needs c++ and Xvfb") +class FexGlThunkErrorForwardRealXlibTest(FexGlThunkErrorForwardTest): + HARNESS_SOURCE = REAL_HARNESS + DEPENDENCY_HEADERS = ("GL/glx.h", "GL/glxext.h", "X11/Xmd.h", "GL/glxproto.h", "X11/Xlibint.h") + + @classmethod + def setUpClass(cls): + super().setUpClass() + read, write = os.pipe() + cls.server = subprocess.Popen(["Xvfb", "-displayfd", str(write), "-nolisten", "tcp", "-screen", "0", "64x64x24"], + pass_fds=(write,), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + os.close(write) + with os.fdopen(read) as stream: + number = stream.readline().strip() + if not number: + cls.server.kill() + cls.server.wait() + raise unittest.SkipTest("Xvfb did not start") + cls.display = ":" + number + + @classmethod + def tearDownClass(cls): + cls.server.terminate() + cls.server.wait() + + def run_real(self, *args, expected_returncode=0): + try: + result = subprocess.run([str(self.program), *args], capture_output=True, text=True, timeout=20, + env={**os.environ, "DISPLAY": self.display, "LIBGL_ALWAYS_SOFTWARE": "1", + "MESA_GL_VERSION_OVERRIDE": "4.5"}) + except subprocess.TimeoutExpired: + self.fail("the host error handler deadlocked") + self.assertEqual(result.returncode, expected_returncode, result.stderr) + return result.stdout.strip() + + def test_real_error_reaches_the_program_while_another_thread_holds_its_display(self): + self.assertEqual(self.run_real(), + "app_calls=1 guest_calls=1 host_reached=1 usable=1 serial_from_guest=1") + + def test_valid_config_with_unsupported_version_reaches_handler_and_allows_fallback(self): + self.assertEqual(self.run_real("glx"), + "valid_config=1 rejected=1 guest_errors=1 bad_fbconfig=1 minor_zero=1 fallback=1") + + def test_program_without_error_handler_keeps_default_fatal_behavior(self): + self.run_real("default", expected_returncode=1) + + test_error_on_a_host_display_reaches_the_programs_handler = None + test_forwarded_error_carries_the_programs_own_serial = None + test_forwarding_never_swaps_the_programs_handler = None + test_error_while_the_display_lock_is_held_does_not_block = None + test_error_while_another_thread_holds_the_programs_display_lock_does_not_deadlock = None + test_error_on_a_display_the_gl_thunk_does_not_own_keeps_the_previous_handler = None + + +class FexGlThunkDependencyProbeTest(unittest.TestCase): + def test_missing_glx_headers_skip_the_real_harness(self): + def compile_without_glx(source, output): + self.assertEqual(source.name, "probe.cpp") + self.assertIn("#include ", source.read_text()) + return subprocess.CompletedProcess([], 1, "", "missing GLX headers") + + with mock.patch(__name__ + ".compile_cpp", side_effect=compile_without_glx): + try: + with self.assertRaises(unittest.SkipTest): + FexGlThunkErrorForwardRealXlibTest.setUpClass() + finally: + FexGlThunkErrorForwardRealXlibTest.doClassCleanups() + + def test_real_harness_compile_errors_are_failures(self): + results = [subprocess.CompletedProcess([], 0, "", ""), + subprocess.CompletedProcess([], 1, "", "harness compile error")] + with mock.patch(__name__ + ".compile_cpp", side_effect=results): + try: + with self.assertRaisesRegex(AssertionError, "harness compile error"): + FexGlThunkErrorForwardRealXlibTest.setUpClass() + finally: + FexGlThunkErrorForwardRealXlibTest.doClassCleanups() + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_fex_select.py b/tools/tests/test_fex_select.py index 3b351520e7..3168bd4e68 100644 --- a/tools/tests/test_fex_select.py +++ b/tools/tests/test_fex_select.py @@ -37,9 +37,9 @@ class FexSelectTest(unittest.TestCase): .replace("/usr/local/bin/FEX", "$ROOT/FEX")) script = HARNESS + body + 'if fex_ready; then echo "NOW $FEX_NOW|$FEX_FROM"; else echo FAILED; fi\n' env = dict(os.environ, ROOT=root, LOADS="1" if loads else "0", INSTALLABLE=" ".join(installable)) - env.pop("BL_FEX_TAG", None) + env.pop("DD_FEX_TAG", None) if catalog: - env.update(BL_FEX_TAG=catalog, BL_FEX_SHA256="catsha", BL_FEX_URLS="a b") + env.update(DD_FEX_TAG=catalog, DD_FEX_SHA256="catsha", DD_FEX_URLS="a b") out = subprocess.run(["bash", "-c", script], env=env, text=True, capture_output=True, timeout=10) self.assertEqual(0, out.returncode, out.stderr) lines = out.stdout.splitlines() diff --git a/tools/tests/test_fsync_preload.py b/tools/tests/test_fsync_preload.py index af8a51dc42..21c77611e9 100644 --- a/tools/tests/test_fsync_preload.py +++ b/tools/tests/test_fsync_preload.py @@ -331,13 +331,13 @@ class FsyncPreloadTest(unittest.TestCase): capture_output=True, text=True, timeout=120) def test_emulated_waits_wake_time_out_and_survive_dead_waiters(self): - result = self.run_program(BL_FSYNC="1") + result = self.run_program(DD_FSYNC="1") self.assertEqual(result.returncode, 0, result.stdout + result.stderr) self.assertIn("fsync emulation ok", result.stdout) self.assertIn("droiddeck-fsync: up and running.", result.stderr) def test_off_without_the_switch(self): - result = self.run_program(BL_FSYNC="0") + result = self.run_program(DD_FSYNC="0") self.assertNotIn("droiddeck-fsync", result.stderr) self.assertNotIn("fsync emulation ok", result.stdout) diff --git a/tools/tests/test_game_environment.py b/tools/tests/test_game_environment.py index 7108d6dbc3..6779efe8a8 100644 --- a/tools/tests/test_game_environment.py +++ b/tools/tests/test_game_environment.py @@ -491,7 +491,7 @@ class EgoCorePlanTest(unittest.TestCase): probe = Path(tmp) / "probe" probe.write_text('#!/bin/sh\ngrep -c \'value="5"\' "%s"\n' % self.path) probe.chmod(0o755) - env = {k: v for k, v in os.environ.items() if not k.startswith(("WINE", "PROTON", "DROIDDECK", "BL_", "STEAM"))} + env = {k: v for k, v in os.environ.items() if not k.startswith(("WINE", "PROTON", "DROIDDECK", "DD_", "STEAM"))} env.update(HOME=tmp, STEAM_COMPAT_DATA_PATH="/compatdata/3791535942", WINE_CPU_TOPOLOGY="5:7,3,4,5,6") result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(probe), "waitforexitandrun", self.command[2]], env=env, text=True, capture_output=True, check=True) @@ -629,7 +629,7 @@ class SystemGraphicsLaunchTest(unittest.TestCase): "STEAM_COMPAT_DATA_PATH": "/compatdata/42"} command = ["/stock/proton", "waitforexitandrun", "game.exe"] selected = ["/sync-pack/proton", *command[1:]] - selected_env = dict(env, WINESERVER="/sync-pack/wineserver", BL_SYNC_PACK="selected") + selected_env = dict(env, WINESERVER="/sync-pack/wineserver", DD_SYNC_PACK="selected") main = MODULE["main"] with patch.dict(os.environ, env, clear=True), patch.object(sys, "argv", ["game-env", *command]), \ patch.dict(main.__globals__, {"load_sync": lambda: {}, @@ -644,7 +644,7 @@ class SystemGraphicsLaunchTest(unittest.TestCase): self.assertEqual(path, str(runtime / "run-proton.py")) self.assertEqual(args, [path, *selected]) self.assertEqual(actual_env["WINESERVER"], "/sync-pack/wineserver") - self.assertEqual(actual_env["BL_SYNC_PACK"], "selected") + self.assertEqual(actual_env["DD_SYNC_PACK"], "selected") class GameDebugLoggingTest(unittest.TestCase): @@ -675,22 +675,22 @@ class GameDebugLoggingTest(unittest.TestCase): result = subprocess.run( [sys.executable, str(BIN / "droiddeck-game-env"), str(probe), "waitforexitandrun"], env={**os.environ, "HOME": tmp, "STEAM_COMPAT_DATA_PATH": str(home / "compatdata/42"), - "BL_DEBUG_DIR": tmp, "PROTON_LOG": "0"}, + "DD_DEBUG_DIR": tmp, "PROTON_LOG": "0"}, text=True, capture_output=True, check=True, ) self.assertEqual(result.stdout.strip(), "0") def test_game_debug_logs_override_only_diagnostic_values_and_keep_raw_settings(self): with tempfile.TemporaryDirectory(prefix="game logs '") as debug_dir: - inherited = {"BL_DEBUG_DIR": debug_dir, "PROTON_LOG": "0", "WINEDEBUG": "-all,+relay", + inherited = {"DD_DEBUG_DIR": debug_dir, "PROTON_LOG": "0", "WINEDEBUG": "-all,+relay", "PROTON_LOG_DIR": "/old", "PROTON_CRASH_REPORT_DIR": "/old-crashes", "DXVK_LOG_PATH": "/old-dxvk", "DXVK_LOG_LEVEL": "none", "VKD3D_DEBUG": "none", "CUSTOM": "$(touch never); 'quoted' = literal", "DXVK_CONFIG": "dxvk.tearFree = True"} config = {"version": 1, "gameDebugLogs": True, - "shared": {"PROTON_LOG": "0", "BL_DEBUG_DIR": "/profile-redirect"}, + "shared": {"PROTON_LOG": "0", "DD_DEBUG_DIR": "/profile-redirect"}, "games": {"42": {"PROTON_LOG_DIR": None, "DXVK_LOG_PATH": "/game-redirect"}}} normal = MODULE["apply_config"](inherited, config, "42") - debug = MODULE["apply_game_debug_logs"](normal, config, inherited["BL_DEBUG_DIR"]) + debug = MODULE["apply_game_debug_logs"](normal, config, inherited["DD_DEBUG_DIR"]) self.assertEqual(debug["PROTON_LOG"], "1") for key in ("PROTON_LOG_DIR", "PROTON_CRASH_REPORT_DIR", "DXVK_LOG_PATH"): self.assertEqual(debug[key], debug_dir) @@ -698,7 +698,7 @@ class GameDebugLoggingTest(unittest.TestCase): self.assertEqual(debug["VKD3D_DEBUG"], "info") self.assertIn("+relay", debug["WINEDEBUG"].split(",")) self.assertTrue(debug["WINEDEBUG"].endswith("+loaddll,+mscoree")) - for key in ("CUSTOM", "DXVK_CONFIG", "BL_DEBUG_DIR"): + for key in ("CUSTOM", "DXVK_CONFIG", "DD_DEBUG_DIR"): self.assertEqual(debug[key], normal[key]) self.assertEqual(normal["PROTON_LOG"], "0") self.assertEqual(inherited["PROTON_LOG_DIR"], "/old") @@ -747,9 +747,9 @@ class GameDebugLoggingTest(unittest.TestCase): literal = "$(touch " + str(home / "never-created") + "); 'literal'=value" config = {"version": 1, "gameDebugLogs": True, "shared": {"PROTON_LOG": "0", "WINEDEBUG": "-all,+relay", "CUSTOM": literal, - "BL_DEBUG_DIR": "/profile-must-not-redirect"}} + "DD_DEBUG_DIR": "/profile-must-not-redirect"}} env = {**os.environ, "HOME": tmp, "STEAM_COMPAT_DATA_PATH": str(home / "compatdata/42"), - "BL_DEBUG_DIR": str(debug_dir), "PROTON_LOG": "0", "WINEDEBUG": "-all"} + "DD_DEBUG_DIR": str(debug_dir), "PROTON_LOG": "0", "WINEDEBUG": "-all"} command = [str(probe), "waitforexitandrun", "game 'with quotes'.exe", "argument with spaces", "$(literal)", "%command%"] def launch(arguments, environment): @@ -803,11 +803,11 @@ class GameEnvironmentTest(unittest.TestCase): config.parent.mkdir(parents=True) config.write_text(json.dumps({"version": 1, "shared": {"PROTON_USE_ARM64": "1"}, "games": {"42": {"PROTON_USE_ARM64": "0"}}})) - seen_components, seen_repair, seen_start = [], [], [] + seen_components, seen_repair, seen_start, seen_mark = [], [], [], [] globals = MODULE["main"].__globals__ stubs = { "game_gpu": lambda env: env, - "mark_install_scripts": lambda command, env: [], + "mark_install_scripts": lambda command, env: seen_mark.append(env.copy()) or [], "install_scripts_done": lambda scripts, env: False, "scripts_digest": lambda scripts: None, "win_components": lambda *args: seen_components.append(args[3]) or "", @@ -844,6 +844,15 @@ class GameEnvironmentTest(unittest.TestCase): self.assertEqual(["0"], [env["PROTON_USE_ARM64"] for env in seen_components]) self.assertEqual(["0"], [env["PROTON_USE_ARM64"] for env in seen_repair]) self.assertEqual(["0"], [env["PROTON_USE_ARM64"] for env in seen_start]) + self.assertEqual(["0"], [env["PROTON_USE_ARM64"] for env in seen_mark]) + seen_mark.clear() + seen_start.clear() + command[1] = "run" + with patch.dict(os.environ, environment, clear=True), patch.object(sys, "argv", ["game-env", *command]), \ + patch.dict(globals, stubs): + self.assertEqual(MODULE["main"](), 7) + self.assertEqual(["1"], [env["PROTON_USE_ARM64"] for env in seen_mark]) + self.assertEqual(["1"], [env["PROTON_USE_ARM64"] for env in seen_start]) def test_keyboard_helper_is_off_unless_steam_keyboard_or_the_user_wants_it(self): cases = ( @@ -922,10 +931,10 @@ class GameEnvironmentTest(unittest.TestCase): for enabled, override, expected in (("1", None, "1"), ("0", "1", "0"), ("1", "0", "0")): with self.subTest(enabled=enabled, override=override): profile = {} if override is None else { - "AUDIO_DIRECT_MIC": override, "BL_MIC_ENABLED": override, + "AUDIO_DIRECT_MIC": override, "DD_MIC_ENABLED": override, } config.write_text(json.dumps({"version": 1, "games": {"42": profile}})) - env = dict(os.environ, HOME=tmp, BL_MIC_ENABLED=enabled, + env = dict(os.environ, HOME=tmp, DD_MIC_ENABLED=enabled, AUDIO_DIRECT_MIC="1", STEAM_COMPAT_DATA_PATH="/compatdata/42") result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(probe), "waitforexitandrun"], @@ -942,7 +951,7 @@ class GameEnvironmentTest(unittest.TestCase): config.parent.mkdir(parents=True) config.write_text(json.dumps({"version": 1, "games": {"42": {"AUDIO_DIRECT_MS": "80"}}})) base = {key: value for key, value in os.environ.items() if "AUDIO_DIRECT_" not in key} - base.update(HOME=tmp, BL_MIC_ENABLED="0", STEAM_COMPAT_DATA_PATH="/compatdata/42", + base.update(HOME=tmp, DD_MIC_ENABLED="0", STEAM_COMPAT_DATA_PATH="/compatdata/42", AUDIO_DIRECT_MS="60", AUDIO_DIRECT_PERIOD_MS="20", AUDIO_DIRECT_MIC="1", BANNER_AUDIO_DIRECT_MS="60", BANNER_AUDIO_DIRECT_MIC="1") for driver, expected in (("directaudio,pulse", "BANNER_AUDIO_DIRECT_MIC=0 BANNER_AUDIO_DIRECT_MS=80 BANNER_AUDIO_DIRECT_PERIOD_MS=20"), @@ -956,22 +965,22 @@ class GameEnvironmentTest(unittest.TestCase): with tempfile.TemporaryDirectory() as tmp: home = Path(tmp) gpu = home / "gpu" - gpu.write_text("#!/bin/bash\necho \"gpu LD_PRELOAD=${LD_PRELOAD-unset}\"\nexport BL_DESKTOP_GPU_CHILD=1\nexec \"$@\"\n") + gpu.write_text("#!/bin/bash\necho \"gpu LD_PRELOAD=${LD_PRELOAD-unset}\"\nexport DD_DESKTOP_GPU_CHILD=1\nexec \"$@\"\n") gpu.chmod(0o755) launcher = home / "launcher" - setup = COMPAT["BL_DESKTOP_GPU_SETUP"].replace("/usr/local/bin/droiddeck-gpu", str(gpu)) - launcher.write_text("#!/bin/bash\nverb=$1; shift\n" + setup + "echo \"game $verb $* LD_PRELOAD=${LD_PRELOAD-unset} saved=${BL_GPU_SAVED_LD_PRELOAD-unset}\"\n") + setup = COMPAT["DD_DESKTOP_GPU_SETUP"].replace("/usr/local/bin/droiddeck-gpu", str(gpu)) + launcher.write_text("#!/bin/bash\nverb=$1; shift\n" + setup + "echo \"game $verb $* LD_PRELOAD=${LD_PRELOAD-unset} saved=${DD_GPU_SAVED_LD_PRELOAD-unset}\"\n") launcher.chmod(0o755) - base = {key: value for key, value in os.environ.items() if not key.startswith("BL_")} + base = {key: value for key, value in os.environ.items() if not key.startswith("DD_")} base["LD_PRELOAD"] = "overlay.so" for extra, args, expected in ( - ({"BL_DESKTOP": "1"}, ["waitforexitandrun", "game.exe"], + ({"DD_DESKTOP": "1"}, ["waitforexitandrun", "game.exe"], ["gpu LD_PRELOAD=unset", "game waitforexitandrun game.exe LD_PRELOAD=overlay.so saved=unset"]), - ({"BL_DESKTOP": "1", "BL_DESKTOP_GPU": "Off"}, ["waitforexitandrun", "game.exe"], + ({"DD_DESKTOP": "1", "DD_DESKTOP_GPU": "Off"}, ["waitforexitandrun", "game.exe"], ["game waitforexitandrun game.exe LD_PRELOAD=overlay.so saved=unset"]), - ({"BL_DESKTOP": "1"}, ["run", "setup.exe"], + ({"DD_DESKTOP": "1"}, ["run", "setup.exe"], ["game run setup.exe LD_PRELOAD=overlay.so saved=unset"]), - ({"BL_DESKTOP": "1"}, ["waitforexitandrun", "iscriptevaluator.exe"], + ({"DD_DESKTOP": "1"}, ["waitforexitandrun", "iscriptevaluator.exe"], ["game waitforexitandrun iscriptevaluator.exe LD_PRELOAD=overlay.so saved=unset"]), ({}, ["waitforexitandrun", "game.exe"], ["game waitforexitandrun game.exe LD_PRELOAD=overlay.so saved=unset"]), @@ -984,6 +993,9 @@ class GameEnvironmentTest(unittest.TestCase): def test_the_install_script_evaluator_gets_its_scripts_marked_first(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) + (root / "files/bin-arm64").mkdir(parents=True) + (root / "files/bin-arm64/wineserver").write_text("") + (root / "files/bin-arm64/wineserver").chmod(0o755) script = root / "legacycompat/evaluatorscript_409710.vdf" script.parent.mkdir(parents=True) script.write_text("{}") @@ -991,14 +1003,140 @@ class GameEnvironmentTest(unittest.TestCase): run = MODULE["mark_install_scripts"].__globals__["subprocess"].run MODULE["mark_install_scripts"].__globals__["subprocess"].run = lambda args, **kw: calls.append((args, kw["env"])) try: - env = {"STEAM_COMPAT_CLIENT_INSTALL_PATH": str(root)} - MODULE["mark_install_scripts"](["/proton", "run", str(root / "legacycompat/iscriptevaluator.exe"), "legacycompat\\evaluatorscript_409710.vdf"], env) + env = {"STEAM_COMPAT_CLIENT_INSTALL_PATH": str(root), "STEAM_COMPAT_DATA_PATH": str(root / "compatdata/409710")} + evaluator = [str(root / "proton"), "run", str(root / "legacycompat/iscriptevaluator.exe"), "legacycompat\\evaluatorscript_409710.vdf"] + MODULE["mark_install_scripts"](evaluator, env) MODULE["mark_install_scripts"](["/proton", "waitforexitandrun", "/game/Game.exe"], env) + self.assertEqual(len(calls), 3) + self.assertEqual(calls[0][0], [str(root / "proton"), "run", "cmd.exe", "/c", "exit", "0"]) + self.assertEqual(calls[0][1], env) + self.assertEqual(calls[1][0], [str(root / "files/bin-arm64/wineserver"), "-w"]) + self.assertEqual(calls[1][1]["WINEPREFIX"], str(root / "compatdata/409710/pfx")) + self.assertEqual(calls[1][1].get("DROIDDECK_SEED_SCRIPTS"), None) + self.assertEqual(calls[2][0][1], str(root)) + self.assertEqual(calls[2][1]["DROIDDECK_SEED_SCRIPTS"], str(script)) + (root / "compatdata/409710/pfx").mkdir(parents=True) + (root / "compatdata/409710/pfx/system.reg").write_text("") + calls.clear() + MODULE["mark_install_scripts"](evaluator, env) + self.assertEqual([args[0] for args, _ in calls], [MODULE["SEED_REDISTS"]]) finally: MODULE["mark_install_scripts"].__globals__["subprocess"].run = run - self.assertEqual(len(calls), 1) - self.assertEqual(calls[0][0][1], str(root)) - self.assertEqual(calls[0][1]["DROIDDECK_SEED_SCRIPTS"], str(script)) + + def test_the_install_script_seeder_runs_when_prefix_probe_times_out(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / "files/bin-arm64").mkdir(parents=True) + (root / "files/bin-arm64/wineserver").write_text("") + (root / "files/bin-arm64/wineserver").chmod(0o755) + script = root / "legacycompat/evaluatorscript_409710.vdf" + script.parent.mkdir(parents=True) + script.write_text("{}") + calls = [] + run = MODULE["mark_install_scripts"].__globals__["subprocess"].run + + def fake_run(args, **kwargs): + calls.append((args, kwargs["env"])) + if len(calls) == 1: + raise subprocess.TimeoutExpired(args, 120) + + MODULE["mark_install_scripts"].__globals__["subprocess"].run = fake_run + try: + env = {"STEAM_COMPAT_CLIENT_INSTALL_PATH": str(root), "STEAM_COMPAT_DATA_PATH": str(root / "compatdata/409710")} + MODULE["mark_install_scripts"]([str(root / "proton"), "run", str(root / "legacycompat/iscriptevaluator.exe"), "legacycompat\\evaluatorscript_409710.vdf"], env) + self.assertEqual(calls[1][0], [str(root / "files/bin-arm64/wineserver"), "-w"]) + self.assertEqual(calls[2][0][0], MODULE["SEED_REDISTS"]) + finally: + MODULE["mark_install_scripts"].__globals__["subprocess"].run = run + + def test_the_install_script_seeder_skips_failed_wineserver_waits(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + script = root / "legacycompat/evaluatorscript_409710.vdf" + script.parent.mkdir(parents=True) + script.write_text("{}") + env = {"STEAM_COMPAT_CLIENT_INSTALL_PATH": str(root), "STEAM_COMPAT_DATA_PATH": str(root / "compatdata/409710")} + evaluator = [str(root / "proton"), "run", str(root / "legacycompat/iscriptevaluator.exe"), "legacycompat\\evaluatorscript_409710.vdf"] + wineserver = str(root / "files/bin-arm64/wineserver") + run = MODULE["mark_install_scripts"].__globals__["subprocess"].run + for failure in (subprocess.TimeoutExpired([wineserver, "-w"], 120), OSError("cannot start"), + subprocess.CalledProcessError(1, [wineserver, "-w"])): + with self.subTest(failure=type(failure).__name__): + calls = [] + + def fake_run(args, **kwargs): + calls.append((args, kwargs)) + if len(calls) == 2: + self.assertTrue(kwargs["check"]) + raise failure + + MODULE["mark_install_scripts"].__globals__["subprocess"].run = fake_run + try: + self.assertEqual(MODULE["mark_install_scripts"](evaluator, env), [str(script)]) + self.assertEqual(len(calls), 2) + self.assertEqual(calls[1][0], [wineserver, "-w"]) + self.assertEqual(calls[1][1]["env"]["WINEPREFIX"], str(root / "compatdata/409710/pfx")) + finally: + MODULE["mark_install_scripts"].__globals__["subprocess"].run = run + + def run_install_marker(self, root, env): + script = root / "legacycompat/evaluatorscript_409710.vdf" + script.parent.mkdir(parents=True, exist_ok=True) + script.write_text("{}") + calls = [] + module = MODULE["mark_install_scripts"].__globals__["subprocess"] + run = module.run + module.run = lambda args, **kw: calls.append((args, kw["env"])) + try: + evaluator = [str(root / "proton"), "run", str(root / "legacycompat/iscriptevaluator.exe"), "legacycompat\\evaluatorscript_409710.vdf"] + self.assertEqual(MODULE["mark_install_scripts"](evaluator, env), [str(script)]) + finally: + module.run = run + return calls + + def test_the_install_script_wait_finds_wineserver_in_files_bin(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / "files/bin").mkdir(parents=True) + (root / "files/bin/wineserver").write_text("") + (root / "files/bin/wineserver").chmod(0o755) + calls = self.run_install_marker(root, {"STEAM_COMPAT_CLIENT_INSTALL_PATH": str(root), + "STEAM_COMPAT_DATA_PATH": str(root / "compatdata/409710")}) + self.assertEqual(calls[1][0], [str(root / "files/bin/wineserver"), "-w"]) + self.assertEqual(calls[2][0][0], MODULE["SEED_REDISTS"]) + + def test_the_install_script_seeder_skips_the_probe_without_compat_data(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + calls = self.run_install_marker(root, {"STEAM_COMPAT_CLIENT_INSTALL_PATH": str(root)}) + self.assertEqual([args[0] for args, _ in calls], [MODULE["SEED_REDISTS"]]) + + def test_the_install_script_seeder_checks_only_the_selected_template(self): + for machine in ("aarch64", "x86_64"): + for setting in (None, "1", "0", ""): + for arm64_bin in (False, True): + for template in ("default_pfx", "default_pfx_arm64"): + with self.subTest(machine=machine, setting=setting, arm64_bin=arm64_bin, template=template): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + if arm64_bin: + (root / "files/bin-arm64").mkdir(parents=True) + reg = root / "files/share" / template / "system.reg" + reg.parent.mkdir(parents=True) + reg.write_text("") + env = {"STEAM_COMPAT_CLIENT_INSTALL_PATH": str(root), + "STEAM_COMPAT_DATA_PATH": str(root / "compatdata/409710")} + if setting is not None: + env["PROTON_USE_ARM64"] = setting + before = dict(env) + with patch("platform.machine", return_value=machine): + calls = self.run_install_marker(root, env) + selected = "default_pfx_arm64" if machine == "aarch64" and arm64_bin and setting in (None, "1") else "default_pfx" + expected = [MODULE["SEED_REDISTS"]] + if template != selected: + expected = [str(root / "proton"), str(root / ("files/bin-arm64/wineserver")), *expected] + self.assertEqual([args[0] for args, _ in calls], expected) + self.assertEqual(env, before) SCRIPT = ('"evaluatorscript" { "0" { "appid" "228980" "compat_installscript" { "run process" { ' '"x64 14.28.29334.0" { "hasrunkey" "HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\vcredist\\\\2019" ' @@ -1097,10 +1235,10 @@ class GameEnvironmentTest(unittest.TestCase): self.assertEqual(evaluate(text=self.SCRIPT.replace("x64.cmd", "x64-update.cmd")), (0, 3)) def test_the_mali_bridge_caps_the_vkd3d_feature_level(self): - bridge = {"BL_VKBRIDGE": "1", "VKD3D_FEATURE_LEVEL": "12_2"} + bridge = {"DD_VKBRIDGE": "1", "VKD3D_FEATURE_LEVEL": "12_2"} self.assertIn("capped", MODULE["bridge_feature_level"](bridge)) self.assertEqual(bridge["VKD3D_FEATURE_LEVEL"], "12_0") - for env in ({"BL_VKBRIDGE": "1", "VKD3D_FEATURE_LEVEL": "11_1"}, {"VKD3D_FEATURE_LEVEL": "12_2"}, {"BL_VKBRIDGE": "1"}): + for env in ({"DD_VKBRIDGE": "1", "VKD3D_FEATURE_LEVEL": "11_1"}, {"VKD3D_FEATURE_LEVEL": "12_2"}, {"DD_VKBRIDGE": "1"}): before = dict(env) self.assertIsNone(MODULE["bridge_feature_level"](env)) self.assertEqual(env, before) @@ -1122,6 +1260,22 @@ class GameEnvironmentTest(unittest.TestCase): env = gpu({"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": ""}) self.assertEqual(MODULE["apply_config"](env, config, "42")["TU_DEBUG"], "sysmem") self.assertNotIn("TU_DEBUG", MODULE["apply_config"](env, config, "43")) + def applied(config, app_id="42", env=None): + return MODULE["apply_config"](env or {"TU_DEBUG": "sysmem"}, config, app_id) + prefixed = "DROIDDECK_GAME_TU_DEBUG" + config = {"version": 1, "games": {"42": {prefixed: "gmem"}, "43": {prefixed: ""}}} + self.assertEqual(applied(config)["TU_DEBUG"], "gmem") + self.assertNotIn("TU_DEBUG", applied(config, "43")) + self.assertNotIn(prefixed, applied(config)) + shared = {"version": 1, "shared": {prefixed: "gmem"}, "games": {"42": {"TU_DEBUG": "nolrz"}, "43": {"TU_DEBUG": None}}} + self.assertEqual(applied(shared)["TU_DEBUG"], "nolrz") + self.assertNotIn("TU_DEBUG", applied(shared, "43")) + self.assertEqual(applied(shared, "44")["TU_DEBUG"], "gmem") + self.assertNotIn(prefixed, applied(shared, "44")) + both = {"version": 1, "games": {"42": {"TU_DEBUG": "sysmem", prefixed: ""}, "43": {"TU_DEBUG": None, prefixed: "gmem"}}} + self.assertEqual(applied(both)["TU_DEBUG"], "sysmem") + self.assertNotIn("TU_DEBUG", applied(both, "43", {"TU_DEBUG": "nolrz"})) + self.assertNotIn(prefixed, applied(both)) def test_games_run_with_gl_error_checks_unless_the_user_turns_them_off(self): gpu = MODULE["game_gpu"] @@ -1181,25 +1335,25 @@ class GameEnvironmentTest(unittest.TestCase): def test_the_vram_cap_comes_before_the_games_own_dxvk_settings(self): cap = MODULE["vram_cap"] - self.assertEqual(cap({"BL_VRAM_MB": "4096"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 4096; dxgi.maxSharedMemory = 4096") - self.assertEqual(cap({"BL_VRAM_MB": "8192"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 8192; dxgi.maxSharedMemory = 8192") - self.assertEqual(cap({"BL_VRAM_MB": "4095"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 4095; dxgi.maxSharedMemory = 4095; d3d9.maxAvailableMemory = 4095") - self.assertEqual(cap({"BL_VRAM_MB": "2048", "DXVK_CONFIG": "dxvk.maxFrameRate = 60;"})["DXVK_CONFIG"], + self.assertEqual(cap({"DD_VRAM_MB": "4096"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 4096; dxgi.maxSharedMemory = 4096") + self.assertEqual(cap({"DD_VRAM_MB": "8192"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 8192; dxgi.maxSharedMemory = 8192") + self.assertEqual(cap({"DD_VRAM_MB": "4095"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 4095; dxgi.maxSharedMemory = 4095; d3d9.maxAvailableMemory = 4095") + self.assertEqual(cap({"DD_VRAM_MB": "2048", "DXVK_CONFIG": "dxvk.maxFrameRate = 60;"})["DXVK_CONFIG"], "dxgi.maxDeviceMemory = 2048; dxgi.maxSharedMemory = 2048; d3d9.maxAvailableMemory = 2048; dxvk.maxFrameRate = 60") - for off in ({}, {"BL_VRAM_MB": "0"}, {"BL_VRAM_MB": "lots"}, {"BL_VRAM_MB": "²"}, {"BL_VRAM_MB": "-1"}): + for off in ({}, {"DD_VRAM_MB": "0"}, {"DD_VRAM_MB": "lots"}, {"DD_VRAM_MB": "²"}, {"DD_VRAM_MB": "-1"}): self.assertNotIn("DXVK_CONFIG", cap(off)) self.assertNotIn("DROIDDECK_VRAM_CAP", cap(off)) self.assertNotIn("DROIDDECK_VRAM_CAP_MB", cap(off)) def test_the_vram_cap_also_turns_on_the_vulkan_layer_that_holds_the_game_to_it(self): - env = MODULE["vram_cap"]({"BL_VRAM_MB": "3072", "DXVK_CONFIG": "dxgi.maxDeviceMemory = 16384"}) + env = MODULE["vram_cap"]({"DD_VRAM_MB": "3072", "DXVK_CONFIG": "dxgi.maxDeviceMemory = 16384"}) self.assertEqual((env["DROIDDECK_VRAM_CAP"], env["DROIDDECK_VRAM_CAP_MB"]), ("1", "3072")) def test_a_games_wine_sync_choice_also_reaches_its_setup_runs(self): - env = {"BL_SYNC": "1", "BL_SYNC_FALLBACK": "1", "BL_FSYNC_FIRST": "0", "OTHER": "kept"} - config = {"version": 1, "games": {"42": {"BL_SYNC": "0", "BL_FSYNC_FIRST": "1", "PROTON_NO_ESYNC": "1", "FEX_TSOENABLED": "1"}}} + env = {"DD_SYNC": "1", "DD_SYNC_FALLBACK": "1", "DD_FSYNC_FIRST": "0", "OTHER": "kept"} + config = {"version": 1, "games": {"42": {"DD_SYNC": "0", "DD_FSYNC_FIRST": "1", "PROTON_NO_ESYNC": "1", "FEX_TSOENABLED": "1"}}} chosen = MODULE["apply_config"](env, MODULE["sync_config"](config, "42"), "42") - self.assertEqual(chosen, {"BL_SYNC": "0", "BL_SYNC_FALLBACK": "1", "BL_FSYNC_FIRST": "1", "PROTON_NO_ESYNC": "1", "OTHER": "kept"}) + self.assertEqual(chosen, {"DD_SYNC": "0", "DD_SYNC_FALLBACK": "1", "DD_FSYNC_FIRST": "1", "PROTON_NO_ESYNC": "1", "OTHER": "kept"}) def test_component_profiles_override_general_and_restore_it_for_the_next_game(self): with tempfile.TemporaryDirectory() as tmp: @@ -1225,7 +1379,7 @@ class GameEnvironmentTest(unittest.TestCase): "42\tproton\tbuild-1\tdxvk\tfiles/lib/wine/dxvk/aarch64-windows/d3d8.dll\t-\t-\n" % (digest(general), general, digest(game), game) ) - script = COMPAT["BL_COMPONENTS_SETUP"] + '\nverb=waitforexitandrun; bl_components "$1"\n' + script = COMPAT["DD_COMPONENTS_SETUP"] + '\nverb=waitforexitandrun; dd_components "$1"\n' env = dict(os.environ, HOME=str(home), STEAM_COMPAT_DATA_PATH="/steam/compatdata/42") subprocess.run(["bash", "-c", script, "test", str(base)], env=env, check=True) self.assertEqual(target.read_text(), "game") @@ -1265,7 +1419,7 @@ class GameEnvironmentTest(unittest.TestCase): selection = component_dir / "desired.tsv" selection.write_text("".join(rows)) saved = selection.read_bytes() - script = COMPAT["BL_COMPONENTS_SETUP"] + '\nverb=waitforexitandrun; bl_components "$1"\n' + script = COMPAT["DD_COMPONENTS_SETUP"] + '\nverb=waitforexitandrun; dd_components "$1"\n' env = dict(os.environ, HOME=str(home), STEAM_COMPAT_DATA_PATH="/steam/compatdata/42", DROIDDECK_POWERVR_RUNTIME="/system_vulkan/runtime") @@ -1357,7 +1511,7 @@ class GameEnvironmentTest(unittest.TestCase): hashlib.sha256(source.read_bytes()).hexdigest(), source, )) (component_dir / "desired.tsv").write_text("".join(rows)) - script = COMPAT["BL_COMPONENTS_SETUP"] + '\nverb=waitforexitandrun; bl_components "$1"\n' + script = COMPAT["DD_COMPONENTS_SETUP"] + '\nverb=waitforexitandrun; dd_components "$1"\n' for value in ( "42", "00042", "43", "-1", "-0001", "4294967295", "-2147483648", "2147483648", "-1///", "0", "-0", "000", "-2147483649", "4294967296", @@ -1591,15 +1745,15 @@ class GameEnvironmentTest(unittest.TestCase): os_mod = MODULE["os"] online = {"online_cores": lambda: {0, 1, 2, 3, 4, 5, 6, 7}} cases = [ - ({"BL_GAME_CPUS": "6,7"}, {6, 7}, "2:6,7", "2:6,7"), + ({"DD_GAME_CPUS": "6,7"}, {6, 7}, "2:6,7", "2:6,7"), ({"DROIDDECK_GAME_CORES": "0-2"}, {0, 1, 2}, "3:0,1,2", "3:0,1,2"), - ({"BL_GAME_CPUS": "0-7"}, set(range(8)), None, None), + ({"DD_GAME_CPUS": "0-7"}, set(range(8)), None, None), ({}, {6, 7}, None, None), - ({"BL_GAME_CPUS": "6,7", "WINE_CPU_TOPOLOGY": "4:0,1,2,3"}, {6, 7}, "4:0,1,2,3", "4:0,1,2,3"), + ({"DD_GAME_CPUS": "6,7", "WINE_CPU_TOPOLOGY": "4:0,1,2,3"}, {6, 7}, "4:0,1,2,3", "4:0,1,2,3"), ({"WINE_CPU_TOPOLOGY": "2:0,1"}, set(range(8)), "2:0,1", "2:0,1"), - ({"BL_GAME_CPUS": "6,7", "WINE_CPU_TOPOLOGY": ""}, {6, 7}, "", None), - ({"BL_GAME_CPUS": "6,7", "PROTON_CPU_TOPOLOGY": "1:7"}, {6, 7}, None, "1:7"), - ({"BL_GAME_CPUS": "9"}, {9}, None, None), + ({"DD_GAME_CPUS": "6,7", "WINE_CPU_TOPOLOGY": ""}, {6, 7}, "", None), + ({"DD_GAME_CPUS": "6,7", "PROTON_CPU_TOPOLOGY": "1:7"}, {6, 7}, None, "1:7"), + ({"DD_GAME_CPUS": "9"}, {9}, None, None), ] for env, affinity, expected, proton in cases: env["DROIDDECK_FASTEST_CORES"] = "0" @@ -1688,9 +1842,9 @@ class GameEnvironmentTest(unittest.TestCase): command = [str(proton), "waitforexitandrun", "/game/game.exe"] cases = [ ({}, every, pocket_fit, "8:7,2,3,4,5,6,0,1", "8:7,2,3,4,5,6,0,1"), - ({"BL_GAME_CPUS": "6,7"}, {6, 7}, pocket_fit, "2:7,6", "2:7,6"), + ({"DD_GAME_CPUS": "6,7"}, {6, 7}, pocket_fit, "2:7,6", "2:7,6"), ({"DROIDDECK_GAME_CORES": "0-2"}, {0, 1, 2}, pocket_fit, "3:2,0,1", "3:2,0,1"), - ({"BL_GAME_CPUS": "0-7"}, every, pocket_fit, "8:7,2,3,4,5,6,0,1", "8:7,2,3,4,5,6,0,1"), + ({"DD_GAME_CPUS": "0-7"}, every, pocket_fit, "8:7,2,3,4,5,6,0,1", "8:7,2,3,4,5,6,0,1"), ({"WINE_CPU_TOPOLOGY": "2:0,1"}, every, pocket_fit, "2:0,1", "2:0,1"), ({"WINE_CPU_TOPOLOGY": ""}, every, pocket_fit, "", None), ({"PROTON_CPU_TOPOLOGY": "1:0"}, every, pocket_fit, None, "1:0"), @@ -1701,18 +1855,18 @@ class GameEnvironmentTest(unittest.TestCase): ({"SteamGameId": "1038250"}, every, pocket_fit, None, None), ({"SteamGameId": "618970"}, every, pocket_fit, "4:7,2,3,4", "4:7,2,3,4"), ({"SteamGameId": "620"}, every, pocket_fit, "8:7,2,3,4,5,6,0,1", "8:7,2,3,4,5,6,0,1"), - ({"SteamGameId": "2229830", "BL_GAME_CPUS": "0,1"}, {0, 1}, pocket_fit, "2:0,1", "2:0,1"), + ({"SteamGameId": "2229830", "DD_GAME_CPUS": "0,1"}, {0, 1}, pocket_fit, "2:0,1", "2:0,1"), ({"SteamGameId": "2229830", "DROIDDECK_GAME_CORES": "12-13"}, every, pocket_fit, "1:7", "1:7"), - ({"SteamGameId": "11440", "BL_GAME_CPUS": "0-7"}, every, pocket_fit, "4:7,2,3,4", "4:7,2,3,4"), + ({"SteamGameId": "11440", "DD_GAME_CPUS": "0-7"}, every, pocket_fit, "4:7,2,3,4", "4:7,2,3,4"), ({}, every, {core: 100 for core in every}, None, None), ({}, every, None, None, None), ({"SteamGameId": "11440"}, every, None, "4:0,1,2,3", "4:0,1,2,3"), - ({"BL_GAME_CPUS": "9"}, {9}, pocket_fit, None, None), + ({"DD_GAME_CPUS": "9"}, {9}, pocket_fit, None, None), ] cases += [ ({"STEAM_COMPAT_DATA_PATH": "/steam/compatdata/0"}, every, pocket_fit, None, None), ({"STEAM_COMPAT_DATA_PATH": ""}, every, pocket_fit, None, None), - ({"STEAM_COMPAT_DATA_PATH": "/steam/compatdata/0", "BL_GAME_CPUS": "6,7"}, {6, 7}, pocket_fit, "2:6,7", "2:6,7"), + ({"STEAM_COMPAT_DATA_PATH": "/steam/compatdata/0", "DD_GAME_CPUS": "6,7"}, {6, 7}, pocket_fit, "2:6,7", "2:6,7"), ] for env, affinity, speeds, expected, proton_topology in cases: env.setdefault("STEAM_COMPAT_DATA_PATH", "/steam/compatdata/3608888694") @@ -1781,6 +1935,18 @@ class GameEnvironmentTest(unittest.TestCase): config = {"version": 1, "shared": {}, "games": {"42": {"VKD3D_FEATURE_LEVEL": "12_1"}}} self.assertEqual(MODULE["apply_config"]({}, config, "42", env), {"VKD3D_FEATURE_LEVEL": "12_1"}) + def test_kcd2_runs_at_feature_level_12_2_by_app_id_unless_the_game_overrides_it(self): + with tempfile.TemporaryDirectory() as tmp: + exe = Path(tmp) / "Bin/Win64MasterMasterSteamPGO/KingdomCome.exe" + exe.parent.mkdir(parents=True) + exe.touch() + env, extra, notes = MODULE["engine_fixes"](str(exe), [], "1771300") + self.assertEqual(env, {"VKD3D_FEATURE_LEVEL": "12_2", "VKD3D_SHADER_MODEL": "6_9"}) + self.assertTrue(notes) + config = {"version": 1, "shared": {}, "games": {"1771300": {"VKD3D_FEATURE_LEVEL": "12_1"}}} + self.assertEqual(MODULE["apply_config"]({}, config, "1771300", env), {"VKD3D_FEATURE_LEVEL": "12_1", "VKD3D_SHADER_MODEL": "6_9"}) + self.assertEqual(MODULE["engine_fixes"](str(exe), [], "42")[0], {}) + def test_unity_players_keep_tso_over_the_preset(self): with tempfile.TemporaryDirectory() as tmp: def game(*names): @@ -1891,9 +2057,9 @@ class GameEnvironmentTest(unittest.TestCase): game_logs = MODULE["game_logs"] with tempfile.TemporaryDirectory() as tmp: command = ["/proton", "waitforexitandrun", "/games/Hades/Hades.exe"] - env = {"BL_DEBUG_DIR": tmp, "VK_DRIVER_FILES": "/icd.json"} + env = {"DD_DEBUG_DIR": tmp, "VK_DRIVER_FILES": "/icd.json"} self.assertEqual(game_logs(command, env, "1145360", now=0), env) - on = dict(env, BL_GAME_LOGS="1") + on = dict(env, DD_GAME_LOGS="1") self.assertEqual(game_logs(["/proton", "run", "x.exe"], on, "1145360", now=0), on) result = game_logs(command, on, "1145360", now=0) folder = Path(result["PROTON_LOG_DIR"]) @@ -1909,7 +2075,7 @@ class GameEnvironmentTest(unittest.TestCase): def test_rapid_game_launches_keep_separate_diagnostics(self): with tempfile.TemporaryDirectory() as tmp, mock.patch("subprocess.Popen"): - env = {"BL_GAME_LOGS": "1", "BL_DEBUG_DIR": tmp} + env = {"DD_GAME_LOGS": "1", "DD_DEBUG_DIR": tmp} first = MODULE["game_logs"](["/proton", "waitforexitandrun", "first.exe"], env, "42", now=0) second = MODULE["game_logs"](["/proton", "waitforexitandrun", "second.exe"], env, "42", now=0) self.assertNotEqual(first["PROTON_LOG_DIR"], second["PROTON_LOG_DIR"]) @@ -1922,11 +2088,11 @@ class GameEnvironmentTest(unittest.TestCase): "games": {"42": {"VKD3D_SHADER_MODEL": "6_6"}}} adreno = apply({}, config, "1") self.assertEqual(adreno["VKD3D_FEATURE_LEVEL"], "12_2") - pair = apply({"BL_OPEN_DRIVER": "1"}, config, "1") + pair = apply({"DD_OPEN_DRIVER": "1"}, config, "1") self.assertNotIn("VKD3D_FEATURE_LEVEL", pair) self.assertNotIn("VKD3D_SHADER_MODEL", pair) self.assertEqual(pair["DROIDDECK_VKD3D_CAPS"], "driver") - own = apply({"BL_OPEN_DRIVER": "1"}, config, "42") + own = apply({"DD_OPEN_DRIVER": "1"}, config, "42") self.assertEqual(own["VKD3D_SHADER_MODEL"], "6_6") self.assertNotIn("VKD3D_FEATURE_LEVEL", own) @@ -2114,11 +2280,11 @@ class GameEnvironmentTest(unittest.TestCase): self.assertEqual(changes, {"42": COMPAT["TOOL"]}) def test_both_proton_wrappers_call_environment_launcher(self): - self.assertIn('bl_directaudio "$depot" "$@"', COMPAT["LAUNCHER_SH"]) - self.assertIn('bl_directaudio "$here" "$@"', COMPAT["EXTRA_WRAPPER_SH"] % "proton") + self.assertIn('dd_directaudio "$depot" "$@"', COMPAT["LAUNCHER_SH"]) + self.assertIn('dd_directaudio "$here" "$@"', COMPAT["EXTRA_WRAPPER_SH"] % "proton") for script in (COMPAT["LAUNCHER_SH"], COMPAT["EXTRA_WRAPPER_SH"] % "proton"): subprocess.run(["bash", "-n"], input=script, text=True, check=True) - self.assertIn('bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env', script) + self.assertIn('dd_run ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env', script) def test_both_proton_wrappers_answer_steams_driver_query_without_wine(self): scripts = (COMPAT["launcher_sh"](), COMPAT["extra_wrapper_sh"]("proton")) @@ -2126,7 +2292,7 @@ class GameEnvironmentTest(unittest.TestCase): probe = "/root/.local/share/Steam/steamapps/compatdata/0" for script in scripts: subprocess.run(["bash", "-n"], input=script, text=True, check=True) - self.assertLess(script.index('case "$verb:${1##*/}:'), script.index("bl_components ")) + self.assertLess(script.index('case "$verb:${1##*/}:'), script.index("dd_components ")) for args, prefix in (([query, "-d3d12"], probe), ([query], probe + "/"), ([query.replace("64.exe", ".exe")], probe)): result = subprocess.run(["bash", "-s", "run"] + args, input=script, text=True, capture_output=True, @@ -2135,7 +2301,7 @@ class GameEnvironmentTest(unittest.TestCase): self.assertEqual(result.returncode, 1, result.stderr) self.assertEqual(result.stdout, "") self.assertIn("D3D driver query is not run", result.stderr) - skip = COMPAT["BL_DRIVER_QUERY_SKIP"] + skip = COMPAT["DD_DRIVER_QUERY_SKIP"] for verb, args, prefix in ( ("getcompatpath", [query], probe), ("run", [query], "/root/.local/share/Steam/steamapps/compatdata/2276548447"), @@ -2153,16 +2319,16 @@ class GameEnvironmentTest(unittest.TestCase): def test_wrappers_preload_the_session_library_before_the_input_shim(self): overlay = "/root/.local/share/Steam/ubuntu12_64/gameoverlayrenderer.so" with tempfile.TemporaryDirectory() as tmp: - for name in ("libblsession.so", "libfakeinput.so"): + for name in ("libddsession.so", "libfakeinput.so"): (Path(tmp) / name).write_bytes(b"") for script in (COMPAT["LAUNCHER_SH"], COMPAT["EXTRA_WRAPPER_SH"] % "proton"): start = script.index("for fake in ") block = script[start:script.index("\ndone\n", start) + 6].replace("/usr/local/lib/", tmp + "/") for inherited, expected in ( - (None, ["libblsession.so", "libfakeinput.so"]), - (overlay, ["libblsession.so", "libfakeinput.so", overlay]), - (tmp + "/libfakeinput.so:" + overlay, ["libblsession.so", "libfakeinput.so", overlay]), - (tmp + "/libblsession.so:" + tmp + "/libfakeinput.so", ["libblsession.so", "libfakeinput.so"])): + (None, ["libddsession.so", "libfakeinput.so"]), + (overlay, ["libddsession.so", "libfakeinput.so", overlay]), + (tmp + "/libfakeinput.so:" + overlay, ["libddsession.so", "libfakeinput.so", overlay]), + (tmp + "/libddsession.so:" + tmp + "/libfakeinput.so", ["libddsession.so", "libfakeinput.so"])): env = {"PATH": os.defpath} if inherited is not None: env["LD_PRELOAD"] = inherited @@ -2626,9 +2792,9 @@ class DirectAudioPrefixTest(unittest.TestCase): self.reg = self.compat / "pfx/user.reg" def run_setup(self, verb="waitforexitandrun", target="game.exe", cwd=None, extra=None): - script = COMPAT["BL_DIRECTAUDIO_SETUP"] + '\nverb=$2\nbl_directaudio "$1" "$3"\necho "WINEDLLPATH=$WINEDLLPATH"\necho "WINE_AUDIO_DRIVER=${WINE_AUDIO_DRIVER:-}"\nenv | grep "^BANNER_AUDIO_DIRECT_" | sort\n' + script = COMPAT["DD_DIRECTAUDIO_SETUP"] + '\nverb=$2\ndd_directaudio "$1" "$3"\necho "WINEDLLPATH=$WINEDLLPATH"\necho "WINE_AUDIO_DRIVER=${WINE_AUDIO_DRIVER:-}"\nenv | grep "^BANNER_AUDIO_DIRECT_" | sort\n' steam = self.compat.parent / "Steam" - env = dict(os.environ, BL_DIRECTAUDIO=str(self.sets), STEAM_COMPAT_DATA_PATH=str(self.compat), + env = dict(os.environ, DD_DIRECTAUDIO=str(self.sets), STEAM_COMPAT_DATA_PATH=str(self.compat), STEAM_COMPAT_CLIENT_INSTALL_PATH=str(steam), **(extra or {})) env.pop("WINEDLLPATH", None) env.pop("WINE_AUDIO_DRIVER", None) @@ -3250,7 +3416,7 @@ class ForeignSystemDllTest(unittest.TestCase): backup.write_bytes(pe_image(0x1234)) real = os.replace def flaky_with_backup(src, dst): - if str(src).endswith(".bl-new"): + if str(src).endswith(".dd-new"): raise OSError("boom") return real(src, dst) with mock.patch("os.replace", side_effect=flaky_with_backup): @@ -3263,7 +3429,7 @@ class ForeignSystemDllTest(unittest.TestCase): dll.write_bytes(pe_image(0x8664)) real = os.replace def flaky(src, dst): - if str(src).endswith(".bl-new"): + if str(src).endswith(".dd-new"): raise OSError("boom") return real(src, dst) with mock.patch("os.replace", side_effect=flaky): @@ -3271,7 +3437,7 @@ class ForeignSystemDllTest(unittest.TestCase): self.assertEqual(0x8664, MODULE["pe_machine"](dll)) self.assertFalse(dll.is_symlink()) self.assertFalse((windows / "system32/ucrtbase.dll.foreign-arch").exists()) - self.assertFalse((windows / "system32/ucrtbase.dll.bl-new").is_symlink()) + self.assertFalse((windows / "system32/ucrtbase.dll.dd-new").is_symlink()) def test_non_arm64_proton_and_missing_prefix_are_untouched(self): with tempfile.TemporaryDirectory() as tmp: @@ -3299,11 +3465,11 @@ class ForceSsbsTest(unittest.TestCase): old = g["SSBS_LIB"] g["SSBS_LIB"] = str(lib) try: - env = {"LD_PRELOAD": "/usr/local/lib/libblsession.so"} + env = {"LD_PRELOAD": "/usr/local/lib/libddsession.so"} self.assertEqual(MODULE["force_ssbs"]([str(arm / "proton"), "waitforexitandrun"], env), env) on = dict(env, DROIDDECK_FORCE_SSBS="1") got = MODULE["force_ssbs"]([str(arm / "proton"), "waitforexitandrun"], on) - self.assertEqual(got["LD_PRELOAD"], "/usr/local/lib/libblsession.so:" + str(lib)) + self.assertEqual(got["LD_PRELOAD"], "/usr/local/lib/libddsession.so:" + str(lib)) self.assertEqual(MODULE["force_ssbs"]([str(arm / "proton")], got)["LD_PRELOAD"], got["LD_PRELOAD"]) self.assertEqual(MODULE["force_ssbs"]([str(x86 / "proton")], on), on) finally: diff --git a/tools/tests/test_game_resolution.py b/tools/tests/test_game_resolution.py index 78c5fb3d98..bc654f625f 100644 --- a/tools/tests/test_game_resolution.py +++ b/tools/tests/test_game_resolution.py @@ -11,13 +11,13 @@ SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/d class GameResolutionTest(unittest.TestCase): def launch(self, mode, **overrides): source = SESSION.read_text() - start = source.index(' width=${BL_WIDTH:-1280}') - end = source.index('\nfi\n\nbl_displays()', start) + start = source.index(' width=${DD_WIDTH:-1280}') + end = source.index('\nfi\n\ndd_displays()', start) block = source[start:end].replace('/usr/local/bin/droiddeck-pipewire', 'pipewire_stub') with tempfile.TemporaryDirectory() as directory: - env = dict(os.environ, XDG_RUNTIME_DIR=directory, BL_REFRESH='60', BL_MANGOAPP='0', - BL_WIDTH='2560', BL_HEIGHT='1600') - for name in ('BL_GAME_WIDTH', 'BL_GAME_HEIGHT', 'BL_FOLLOW_OUTPUT', 'BL_GAMESCOPE_STRETCH_16X9'): + env = dict(os.environ, XDG_RUNTIME_DIR=directory, DD_REFRESH='60', DD_MANGOAPP='0', + DD_WIDTH='2560', DD_HEIGHT='1600') + for name in ('DD_GAME_WIDTH', 'DD_GAME_HEIGHT', 'DD_FOLLOW_OUTPUT', 'DD_GAMESCOPE_STRETCH_16X9'): env.pop(name, None) env.update(overrides) fake = Path(directory) / 'gamescope' @@ -35,7 +35,7 @@ run_gamescope() {{ printf 'ARG:%s\n' "$@"; }} return [line.removeprefix('ARG:') for line in result.stdout.splitlines() if line.startswith('ARG:')] def test_a_game_started_without_steam_runs_at_its_resolution_with_proportions_kept(self): - args = self.launch('run', BL_GAME_WIDTH='1280', BL_GAME_HEIGHT='720') + args = self.launch('run', DD_GAME_WIDTH='1280', DD_GAME_HEIGHT='720') self.assertEqual(['2560', '1600'], [args[args.index('-W') + 1], args[args.index('-H') + 1]]) self.assertEqual(['1280', '720'], [args[args.index('-w') + 1], args[args.index('-h') + 1]]) self.assertNotIn('-S', args) @@ -45,7 +45,7 @@ run_gamescope() {{ printf 'ARG:%s\n' "$@"; }} self.assertEqual(['2560', '1600'], [args[args.index('-w') + 1], args[args.index('-h') + 1]]) def test_steam_ignores_the_game_resolution(self): - args = self.launch('steam', BL_GAME_WIDTH='1280', BL_GAME_HEIGHT='720') + args = self.launch('steam', DD_GAME_WIDTH='1280', DD_GAME_HEIGHT='720') self.assertEqual(['2560', '1600'], [args[args.index('-w') + 1], args[args.index('-h') + 1]]) diff --git a/tools/tests/test_gamescope_backend.py b/tools/tests/test_gamescope_backend.py index 166ea94129..f9e2ec4551 100644 --- a/tools/tests/test_gamescope_backend.py +++ b/tools/tests/test_gamescope_backend.py @@ -15,15 +15,15 @@ DESKTOP_GPU = Path(__file__).resolve().parents[1] / "linuxfs/desktop/droiddeck-g class GamescopeBackendTest(unittest.TestCase): def select(self, backend=None): source = SESSION.read_text() - start = source.index(' backend=${BL_GAMESCOPE_BACKEND:-wayland}') + start = source.index(' backend=${DD_GAMESCOPE_BACKEND:-wayland}') end = source.index('\n', source.index(' args=(--backend ', start)) script = 'width=1280; height=720; nested=1280\n' + source[start:end] script += '\nprintf "%s\\n" "${args[0]}" "${args[1]}" "${SDL_VIDEODRIVER:-unset}"\n' env = dict(os.environ) - env.pop("BL_GAMESCOPE_BACKEND", None) + env.pop("DD_GAMESCOPE_BACKEND", None) env.pop("SDL_VIDEODRIVER", None) if backend is not None: - env["BL_GAMESCOPE_BACKEND"] = backend + env["DD_GAMESCOPE_BACKEND"] = backend return subprocess.run(["bash", "-c", script], env=env, text=True, capture_output=True, timeout=5) @@ -63,13 +63,13 @@ class DesktopGamescopeBackendTest(unittest.TestCase): ) gamescope.chmod(0o755) env = dict(os.environ) - for name in ("BL_GAMESCOPE_BACKEND", "BL_DEBUG_DIR", "BL_FPS", "BL_REFRESH", "BL_HDR"): + for name in ("DD_GAMESCOPE_BACKEND", "DD_DEBUG_DIR", "DD_FPS", "DD_REFRESH", "DD_HDR"): env.pop(name, None) env.update(PATH=f"{root}{os.pathsep}{env.get('PATH', '')}", - GAMESCOPE_CAPTURE=str(capture), WAYLAND_DISPLAY="desktop-0", BL_DESKTOP_GPU_WINDOW="0", + GAMESCOPE_CAPTURE=str(capture), WAYLAND_DISPLAY="desktop-0", DD_DESKTOP_GPU_WINDOW="0", SDL_VIDEODRIVER="dummy", GDK_BACKEND="wayland", QT_QPA_PLATFORM="wayland") if backend is not None: - env["BL_GAMESCOPE_BACKEND"] = backend + env["DD_GAMESCOPE_BACKEND"] = backend result = subprocess.run(["bash", str(DESKTOP_GPU), "demo", "one argument"], env=env, text=True, capture_output=True, timeout=5) return result, json.loads(capture.read_text()) if capture.exists() else None @@ -131,7 +131,7 @@ class DesktopGamescopeReaperTest(unittest.TestCase): script.write_text(source.replace("for dir in /usr/games ", f"for dir in {games} ", 1)) start_path = str(bin_dir) env = {"PATH": start_path, "HOME": directory, "GAMESCOPE_CAPTURE": str(capture), - "WAYLAND_DISPLAY": "desktop-0", "BL_DESKTOP_GPU_WINDOW": "0"} + "WAYLAND_DISPLAY": "desktop-0", "DD_DESKTOP_GPU_WINDOW": "0"} result = subprocess.run(["/bin/bash", str(script), "demo"], env=env, text=True, capture_output=True, timeout=5) lines = capture.read_text().splitlines() if capture.exists() else [] diff --git a/tools/tests/test_gog_maintenance.py b/tools/tests/test_gog_maintenance.py index 0465e91b42..70074948c4 100644 --- a/tools/tests/test_gog_maintenance.py +++ b/tools/tests/test_gog_maintenance.py @@ -121,12 +121,12 @@ class GogMaintenance(unittest.TestCase): proc = self.folder / "proc" row = proc / "10"; row.mkdir(parents=True) (row / "cmdline").write_bytes(b"/usr/bin/plasmashell\0") - (row / "environ").write_bytes(b"BL_DESKTOP=1\0XDG_RUNTIME_DIR=/run/session\0WAYLAND_DISPLAY=wayland-1\0DISPLAY=:0\0XAUTHORITY=/run/session/auth\0UNRELATED=value\0") + (row / "environ").write_bytes(b"DD_DESKTOP=1\0XDG_RUNTIME_DIR=/run/session\0WAYLAND_DISPLAY=wayland-1\0DISPLAY=:0\0XAUTHORITY=/run/session/auth\0UNRELATED=value\0") env = G["desktop_environment"]({"DROIDDECK_GOG_DESKTOP": "1", "XDG_RUNTIME_DIR": "/run/session", "WAYLAND_DISPLAY": "wayland-0"}, proc) self.assertEqual("wayland-1", env["WAYLAND_DISPLAY"]) self.assertEqual(":0", env["DISPLAY"]) self.assertEqual("/run/session/auth", env["XAUTHORITY"]) - self.assertEqual("1", env["BL_DESKTOP"]) + self.assertEqual("1", env["DD_DESKTOP"]) self.assertNotIn("UNRELATED", env) def test_maintenance_uses_full_x87_precision_without_changing_game_preferences(self): diff --git a/tools/tests/test_kgsl_read.c b/tools/tests/test_kgsl_read.c index 29353d7a71..3fb514544a 100644 --- a/tools/tests/test_kgsl_read.c +++ b/tools/tests/test_kgsl_read.c @@ -4,7 +4,7 @@ #include "../quest/kgsl_compat.h" -void bl_kgsl_track(int (*real)(int, unsigned long, void *), int fd, unsigned long request, +void dd_kgsl_track(int (*real)(int, unsigned long, void *), int fd, unsigned long request, void *arg, int *rc); static int read_error, wait_error, waits; @@ -37,14 +37,14 @@ static int mock(int fd, unsigned long request, void *arg) { static int issue(unsigned long request, void *arg) { int rc = mock(42, request, arg); - bl_kgsl_track(mock, 42, request, arg, &rc); + dd_kgsl_track(mock, 42, request, arg, &rc); return rc; } static void submit(unsigned int timestamp) { struct kgsl_gpu_command command = {.context_id = 3, .timestamp = timestamp}; int rc = 0; - bl_kgsl_track(mock, 42, IOCTL_KGSL_GPU_COMMAND, &command, &rc); + dd_kgsl_track(mock, 42, IOCTL_KGSL_GPU_COMMAND, &command, &rc); assert(rc == 0); } @@ -59,7 +59,7 @@ static int read_timestamp(unsigned int context, unsigned int *timestamp) { static void create_context(unsigned int context) { struct kgsl_drawctxt_create create = {.drawctxt_id = context}; int rc = 0; - bl_kgsl_track(mock, 42, IOCTL_KGSL_DRAWCTXT_CREATE, &create, &rc); + dd_kgsl_track(mock, 42, IOCTL_KGSL_DRAWCTXT_CREATE, &create, &rc); } int main(void) { @@ -87,7 +87,7 @@ int main(void) { struct kgsl_cmdstream_readtimestamp_ctxtid other = {.context_id = 3, .type = KGSL_TIMESTAMP_RETIRED}; int other_rc = mock(43, IOCTL_KGSL_CMDSTREAM_READTIMESTAMP_CTXTID, &other); - bl_kgsl_track(mock, 43, IOCTL_KGSL_CMDSTREAM_READTIMESTAMP_CTXTID, &other, &other_rc); + dd_kgsl_track(mock, 43, IOCTL_KGSL_CMDSTREAM_READTIMESTAMP_CTXTID, &other, &other_rc); assert(other_rc == -1 && errno == EACCES && waits == 0); submit(1); @@ -121,7 +121,7 @@ int main(void) { struct kgsl_gpu_aux_command aux = {.context_id = 3, .timestamp = 6}; int rc = 0; - bl_kgsl_track(mock, 42, IOCTL_KGSL_GPU_AUX_COMMAND, &aux, &rc); + dd_kgsl_track(mock, 42, IOCTL_KGSL_GPU_AUX_COMMAND, &aux, &rc); retired = 6; assert(read_timestamp(3, ×tamp) == 0 && timestamp == 6); @@ -136,11 +136,11 @@ int main(void) { assert(read_timestamp(3, ×tamp) == 0 && timestamp == 0 && waits == 1); struct kgsl_drawctxt_destroy destroy = {.drawctxt_id = 3}; - bl_kgsl_track(mock, 42, IOCTL_KGSL_DRAWCTXT_DESTROY, &destroy, &rc); + dd_kgsl_track(mock, 42, IOCTL_KGSL_DRAWCTXT_DESTROY, &destroy, &rc); assert(read_timestamp(3, ×tamp) == -1 && errno == EACCES); struct kgsl_drawctxt_create user = {.flags = KGSL_CONTEXT_USER_GENERATED_TS, .drawctxt_id = 3}; - bl_kgsl_track(mock, 42, IOCTL_KGSL_DRAWCTXT_CREATE, &user, &rc); + dd_kgsl_track(mock, 42, IOCTL_KGSL_DRAWCTXT_CREATE, &user, &rc); waits = 0; assert(read_timestamp(3, ×tamp) == -1 && errno == EACCES && waits == 0); diff --git a/tools/tests/test_largefile_preload.py b/tools/tests/test_largefile_preload.py index 50d6afced1..90e72ae5d3 100644 --- a/tools/tests/test_largefile_preload.py +++ b/tools/tests/test_largefile_preload.py @@ -104,7 +104,7 @@ class LargeFilePreloadTest(unittest.TestCase): self.skipTest("no %s toolchain" % bits) out = self.dir / bits.lstrip("-") out.mkdir(exist_ok=True) - lib, program = out / "libblsession.so", out / "program" + lib, program = out / "libddsession.so", out / "program" if not lib.exists(): sources = sorted(str(p) for p in PRELOAD.glob("*.c")) subprocess.run(["cc", bits, "-shared", "-fPIC", "-O2", "-pthread", "-o", str(lib)] + sources + ["-ldl"], check=True) @@ -116,7 +116,7 @@ class LargeFilePreloadTest(unittest.TestCase): def run_program(self, bits, preload): lib, program = self.build(bits) work = Path(tempfile.mkdtemp(dir=self.dir)) - env = {k: v for k, v in os.environ.items() if not k.startswith("BL_")} + env = {k: v for k, v in os.environ.items() if not k.startswith("DD_")} env.pop("LD_PRELOAD", None) if preload: env["LD_PRELOAD"] = str(lib) @@ -141,7 +141,7 @@ class LargeFilePreloadTest(unittest.TestCase): def locks_without_filesystem_support(self, bits): lib, program = self.build(bits) - env = {k: v for k, v in os.environ.items() if not k.startswith("BL_")} + env = {k: v for k, v in os.environ.items() if not k.startswith("DD_")} env["LD_PRELOAD"] = "%s:%s" % (lib, program.parent / "nolocks.so") work = Path(tempfile.mkdtemp(dir=self.dir)) result = subprocess.run([str(program.parent / "locks"), str(work / "file")], env=env, capture_output=True, text=True, timeout=60, check=True) diff --git a/tools/tests/test_login1.py b/tools/tests/test_login1.py index fe69c209e6..306a656692 100644 --- a/tools/tests/test_login1.py +++ b/tools/tests/test_login1.py @@ -35,7 +35,7 @@ class SleepHandshakeTest(unittest.TestCase): self.subscription = self.bus.signal_subscribe( NAME, IFACE, "PrepareForSleep", ROOT, None, Gio.DBusSignalFlags.NONE, lambda bus, sender, path, interface, name, body: self.signals.append(body.unpack()[0])) - env = dict(os.environ, BL_LAUNCH_DIR=str(self.dir), + env = dict(os.environ, DD_LAUNCH_DIR=str(self.dir), DBUS_SYSTEM_BUS_ADDRESS=os.environ["DBUS_SESSION_BUS_ADDRESS"]) script = SCRIPT if self.AGENT_EXIT is not None: diff --git a/tools/tests/test_memory_pressure.py b/tools/tests/test_memory_pressure.py index 29a2008866..d32fa1f809 100644 --- a/tools/tests/test_memory_pressure.py +++ b/tools/tests/test_memory_pressure.py @@ -20,18 +20,18 @@ class MemoryPressureTest(unittest.TestCase): def run_policy(self, body): functions = '\n'.join(function_source(name) for name in ( - 'bl_memory_read', 'bl_memory_tight', 'bl_memory_critical', 'bl_client_can_pageout', - 'bl_client_can_readback', 'bl_client_pressure', 'bl_client_pressure_result', 'bl_zram_has_room')) + 'dd_memory_read', 'dd_memory_tight', 'dd_memory_critical', 'dd_client_can_pageout', + 'dd_client_can_readback', 'dd_client_pressure', 'dd_client_pressure_result', 'dd_zram_has_room')) functions = functions.replace('/proc/meminfo', str(self.root / 'meminfo')) functions = functions.replace('/proc/pressure/memory', str(self.root / 'pressure')) harness = ''' set -u -_bl_pids=(123) _bl_game=1 _bl_packed=-1 _bl_pressure_at=-1 _bl_pressure_backoff=30 +_dd_pids=(123) _dd_game=1 _dd_packed=-1 _dd_pressure_at=-1 _dd_pressure_backoff=30 rss=$((384 * 1024)) client_swap=$((512 * 1024)) reclaimed=$((128 * 1024)) step() { :; } -bl_zram_usage() { _bl_rss=$rss _bl_anon=${anon:-$rss} _bl_swap=$client_swap; } -bl_zram_send() { echo "send:$1:$3"; rss=$((rss - reclaimed)); _bl_pageout_complete=${pageout_complete:-1}; } -''' + functions + '\nbl_memory_read\n' + body +dd_zram_usage() { _dd_rss=$rss _dd_anon=${anon:-$rss} _dd_swap=$client_swap; } +dd_zram_send() { echo "send:$1:$3"; rss=$((rss - reclaimed)); _dd_pageout_complete=${pageout_complete:-1}; } +''' + functions + '\ndd_memory_read\n' + body result = run_bash('NOW=0\n' + harness.replace('SECONDS', 'NOW')) self.assertEqual(0, result.returncode, result.stderr) self.assertEqual('', result.stderr) @@ -39,87 +39,87 @@ bl_zram_send() { echo "send:$1:$3"; rss=$((rss - reclaimed)); _bl_pageout_comple def test_pressure_reclaims_before_the_focus_delay_and_respects_cooldown(self): self.assertEqual(['send:1:client', 'send:1:client'], self.run_policy(''' -SECONDS=0; bl_client_pressure -SECONDS=5; bl_client_pressure -SECONDS=29; bl_client_pressure -SECONDS=30; bl_client_pressure +SECONDS=0; dd_client_pressure +SECONDS=5; dd_client_pressure +SECONDS=29; dd_client_pressure +SECONDS=30; dd_client_pressure ''')) def test_no_game_or_disabled_client_compression_does_not_reclaim(self): self.assertEqual([], self.run_policy(''' -_bl_game=0; bl_client_pressure -_bl_game=1 BL_ZRAM_CLIENT=0; bl_client_pressure +_dd_game=0; dd_client_pressure +_dd_game=1 DD_ZRAM_CLIENT=0; dd_client_pressure ''')) def test_high_available_memory_does_not_reclaim_even_with_stalls(self): self.memory(available=4096, psi='12.34') - self.assertEqual([], self.run_policy('bl_client_pressure')) + self.assertEqual([], self.run_policy('dd_client_pressure')) def test_psi_reclaims_with_moderate_headroom(self): self.memory(available=2048, psi='01.23') - self.assertEqual(['send:1:client'], self.run_policy('bl_client_pressure')) + self.assertEqual(['send:1:client'], self.run_policy('dd_client_pressure')) def test_missing_psi_still_uses_memory_headroom(self): (self.root / 'pressure').unlink() - self.assertEqual(['send:1:client'], self.run_policy('bl_client_pressure')) + self.assertEqual(['send:1:client'], self.run_policy('dd_client_pressure')) def test_missing_meminfo_never_reclaims_or_prefetches(self): (self.root / 'meminfo').write_text('SwapTotal: 6291456 kB\nSwapFree: 4194304 kB\n') self.assertEqual(['no'], self.run_policy(''' -bl_client_pressure -if bl_client_can_readback; then echo yes; else echo no; fi +dd_client_pressure +if dd_client_can_readback; then echo yes; else echo no; fi ''')) def test_missing_available_memory_does_not_trigger_pressure(self): p = self.root / 'meminfo' p.write_text('\n'.join(line for line in p.read_text().splitlines() if not line.startswith('MemAvailable:'))) - self.assertEqual([], self.run_policy('bl_client_pressure')) + self.assertEqual([], self.run_policy('dd_client_pressure')) def test_swap_reserve_includes_the_clients_resident_memory(self): self.memory(swap_free=1536) self.assertEqual(['no'], self.run_policy(''' -bl_client_pressure -if bl_client_can_pageout; then echo yes; else echo no; fi +dd_client_pressure +if dd_client_can_pageout; then echo yes; else echo no; fi ''')) def test_client_swap_budget_excludes_file_backed_memory(self): self.memory(swap_free=1536) self.assertEqual(['send:1:client'], self.run_policy(''' rss=$((2048 * 1024)) anon=$((256 * 1024)) -bl_client_pressure +dd_client_pressure ''')) def test_without_swap_automatic_pageout_is_disabled(self): self.memory(swap_total=0, swap_free=0) - self.assertEqual([], self.run_policy('bl_client_pressure')) + self.assertEqual([], self.run_policy('dd_client_pressure')) def test_recent_periodic_pageout_prevents_an_immediate_pressure_repeat(self): - self.assertEqual([], self.run_policy('_bl_packed=$SECONDS; bl_client_pressure')) + self.assertEqual([], self.run_policy('_dd_packed=$SECONDS; dd_client_pressure')) def test_ineffective_reclaim_backs_off_and_success_resets_it(self): self.assertEqual(['send:1:client', 'backoff:60', 'send:1:client', 'backoff:30'], self.run_policy(''' reclaimed=0 -SECONDS=0; bl_client_pressure -echo "backoff:$_bl_pressure_backoff" -SECONDS=30; bl_client_pressure +SECONDS=0; dd_client_pressure +echo "backoff:$_dd_pressure_backoff" +SECONDS=30; dd_client_pressure reclaimed=$((128 * 1024)) -SECONDS=60; bl_client_pressure -echo "backoff:$_bl_pressure_backoff" +SECONDS=60; dd_client_pressure +echo "backoff:$_dd_pressure_backoff" ''')) def test_readback_requires_room_for_the_swapped_client_plus_headroom(self): self.memory(available=2048) self.assertEqual(['yes', 'no'], self.run_policy(''' -if bl_client_can_readback; then echo yes; else echo no; fi +if dd_client_can_readback; then echo yes; else echo no; fi client_swap=$((1024 * 1024)) -if bl_client_can_readback; then echo yes; else echo no; fi +if dd_client_can_readback; then echo yes; else echo no; fi ''')) def test_unfinished_pageout_does_not_increase_the_ineffective_reclaim_backoff(self): self.assertEqual(['send:1:client', 'backoff:30'], self.run_policy(''' reclaimed=0 pageout_complete=0 -SECONDS=0; bl_client_pressure -echo "backoff:$_bl_pressure_backoff" +SECONDS=0; dd_client_pressure +echo "backoff:$_dd_pressure_backoff" ''')) def test_pageout_completion_requires_a_finished_ack_from_every_live_target(self): @@ -127,21 +127,21 @@ echo "backoff:$_bl_pressure_backoff" proc.mkdir() for pid in (123, 456): (proc / str(pid)).mkdir() - source = function_source('bl_zram_wait').replace('/proc/', str(proc) + '/') - source = source.replace('/tmp/.bl-zram.ack.', str(self.root / 'ack.')) + source = function_source('dd_zram_wait').replace('/proc/', str(proc) + '/') + source = source.replace('/tmp/.dd-zram.ack.', str(self.root / 'ack.')) for pending in ('done', 'running', 'not_started'): with self.subTest(pending=pending): (self.root / 'ack.123').write_text('1') if pending != 'not_started': (self.root / 'ack.456').write_text('1' if pending == 'done' else '') result = run_bash('nap() { SECONDS=$((SECONDS + 1)); }\n' + source + - '\nSECONDS=0; bl_zram_wait 123 456; echo "$_bl_pageout_complete"') + '\nSECONDS=0; dd_zram_wait 123 456; echo "$_dd_pageout_complete"') self.assertEqual(0, result.returncode, result.stderr) self.assertEqual('1' if pending == 'done' else '0', result.stdout.strip()) def test_pressure_prevents_prefetch_even_if_the_client_would_fit(self): self.memory(available=2048, psi='2.00') - self.assertEqual(['no'], self.run_policy('if bl_client_can_readback; then echo yes; else echo no; fi')) + self.assertEqual(['no'], self.run_policy('if dd_client_can_readback; then echo yes; else echo no; fi')) class SessionPressureTest(unittest.TestCase): @@ -159,24 +159,25 @@ class SessionPressureTest(unittest.TestCase): def run_policy(self, body): functions = '\n'.join(function_source(name) for name in ( - 'bl_memory_read', 'bl_memory_tight', 'bl_memory_critical', - 'bl_client_can_pageout', 'bl_client_pressure', 'bl_client_pressure_result', - 'bl_session_pressure', 'bl_zram_has_room', 'bl_watch_nap', 'bl_zram_pick', 'bl_tier_note', 'bl_tier_readback')) + 'dd_memory_read', 'dd_memory_tight', 'dd_memory_critical', + 'dd_client_can_pageout', 'dd_client_pressure', 'dd_client_pressure_result', + 'dd_session_pressure', 'dd_zram_has_room', 'dd_watch_nap', 'dd_zram_pick', 'dd_tier_note', 'dd_tier_readback')) functions = functions.replace('/proc/meminfo', str(self.root / 'meminfo')) functions = functions.replace('/proc/pressure/memory', str(self.root / 'pressure')) harness = ''' set -u -_bl_game=1 _bl_tier_at=-1 _bl_tier_backoff=30 _bl_tier_pushed=0 _bl_tier_back=0 _bl_tier_targets=() _bl_tier_swaps=() _bl_tier_starts=() _bl_pids=(999) -_bl_pressure_at=-1 _bl_pressure_backoff=30 _bl_packed=-1 +_dd_game=1 _dd_tier_at=-1 _dd_tier_backoff=30 _dd_tier_pushed=0 _dd_tier_back=0 _dd_tier_targets=() _dd_tier_swaps=() _dd_tier_starts=() _dd_pids=(999) +_dd_pressure_at=-1 _dd_pressure_backoff=30 _dd_packed=-1 rss=$((1536 * 1024)) swap=0 pushed=$((1024 * 1024)) alive="999 321 654" started=100 complete=1 step() { :; } -bl_game_focused() { [ "${focused:-1}" = 1 ]; } -bl_proc_start() { _bl_start=; case " $alive " in *" $1 "*) _bl_start=$started; return 0 ;; esac; return 1; } +meminfo=''' + repr(str(self.root / 'meminfo')) + ''' +dd_game_focused() { [ "${focused:-1}" = 1 ]; } +dd_proc_start() { _dd_start=; case " $alive " in *" $1 "*) _dd_start=$started; return 0 ;; esac; return 1; } nap() { echo "nap:$1"; } -bl_session_others() { _bl_session=(321 654); } -bl_zram_usage() { _bl_rss=$rss _bl_anon=${anon:-$rss} _bl_swap=$swap; } -bl_zram_send() { echo "send:$1:$3"; rss=$((rss - pushed)); swap=$((swap + pushed)); _bl_pageout_complete=$complete; } -''' + functions + '\nbl_memory_read\n' + body +dd_session_others() { _dd_session=(321 654); } +dd_zram_usage() { _dd_rss=$rss _dd_anon=${anon:-$rss} _dd_swap=$swap; } +dd_zram_send() { echo "send:$1:$3"; rss=$((rss - pushed)); swap=$((swap + pushed)); next_available=${available_after:-$(( $(awk '/^MemAvailable:/ { print $2 }' "$meminfo") / 1024 + 128 ))}; sed -i "s/^MemAvailable:.*/MemAvailable: $((next_available * 1024)) kB/" "$meminfo"; _dd_pageout_complete=$complete; } +''' + functions + '\ndd_memory_read\n' + body result = run_bash('NOW=0\n' + harness.replace('SECONDS', 'NOW')) self.assertEqual(0, result.returncode, result.stderr) self.assertEqual('', result.stderr) @@ -184,256 +185,345 @@ bl_zram_send() { echo "send:$1:$3"; rss=$((rss - pushed)); swap=$((swap + pushed def test_low_headroom_compresses_the_game_session_at_most_every_30_seconds(self): self.assertEqual(['send:1:session', 'send:1:session'], self.run_policy(''' -SECONDS=0; bl_session_pressure -SECONDS=10; bl_session_pressure -SECONDS=29; bl_session_pressure -SECONDS=30; bl_session_pressure +SECONDS=0; dd_session_pressure +SECONDS=10; dd_session_pressure +SECONDS=29; dd_session_pressure +SECONDS=30; dd_session_pressure ''')) def test_pressure_policy_is_independent_of_ram_size(self): for total, expected in ((11264, ['send:1:session']), (12288, ['send:1:session']), (16384, ['send:1:session'])): with self.subTest(total=total): self.memory(total=total) - self.assertEqual(expected, self.run_policy('bl_session_pressure')) + self.assertEqual(expected, self.run_policy('dd_session_pressure')) def test_large_device_with_real_headroom_does_not_reclaim(self): self.memory(total=16384, available=5120, psi='12.34') - self.assertEqual([], self.run_policy('bl_session_pressure')) + self.assertEqual([], self.run_policy('dd_session_pressure')) def test_large_device_with_psi_and_moderate_headroom_reclaims(self): self.memory(total=16384, available=3072, psi='1.23') - self.assertEqual(['send:1:session'], self.run_policy('bl_session_pressure')) + self.assertEqual(['send:1:session'], self.run_policy('dd_session_pressure')) + + def test_a_fast_fall_on_a_large_device_reclaims_above_the_fixed_headroom(self): + self.memory(total=15255, available=6176) + falling = self.root / 'falling' + falling.write_text( + f'MemTotal: {15255 * 1024} kB\nMemAvailable: {5367 * 1024} kB\n' + f'SwapTotal: {8192 * 1024} kB\nSwapFree: {6144 * 1024} kB\n') + meminfo = self.root / 'meminfo' + self.assertEqual(['send:1:session'], self.run_policy( + f'cp {falling} {meminfo}\nSECONDS=5; dd_session_pressure')) + + def test_a_fall_split_across_one_second_polls_still_reclaims(self): + self.memory(total=15255, available=6300) + steps = [] + for second, available in ((5, 6100), (6, 6020), (7, 5940), (8, 5860), (9, 5780)): + sample = self.root / f'meminfo-{second}' + sample.write_text( + f'MemTotal: {15255 * 1024} kB\nMemAvailable: {available * 1024} kB\n' + f'SwapTotal: {8192 * 1024} kB\nSwapFree: {6144 * 1024} kB\n') + steps.append(f'cp {sample} {self.root / "meminfo"}; SECONDS={second}; dd_session_pressure') + self.assertEqual(['send:1:session'], self.run_policy('\n'.join(steps))) def test_no_game_does_not_compress_the_session(self): - self.assertEqual([], self.run_policy('_bl_game=0; bl_session_pressure')) + self.assertEqual([], self.run_policy('_dd_game=0; dd_session_pressure')) def test_disabled_idle_compression_does_not_compress_the_session(self): - self.assertEqual(['send:1:client'], self.run_policy('BL_ZRAM_IDLE=0; bl_client_pressure; bl_session_pressure')) + self.assertEqual(['send:1:client'], self.run_policy('DD_ZRAM_IDLE=0; dd_client_pressure; dd_session_pressure')) def test_disabled_idle_compression_signals_only_launcher_processes(self): - sender = (function_source('bl_zram_send') + '\n' + function_source('bl_zram_finish')).replace('/tmp/.bl-zram', str(self.root / 'control')) + sender = (function_source('dd_zram_send') + '\n' + function_source('dd_zram_finish')).replace('/tmp/.dd-zram', str(self.root / 'control')) self.assertEqual(['kill:-URG 999 998', 'mode:1'], self.run_policy(''' -_bl_pids=(999 998) +_dd_pids=(999 998) kill() { echo "kill:$*"; } -bl_zram_wait() { _bl_pageout_complete=1; } -bl_zram_scan() { :; } +dd_zram_wait() { _dd_pageout_complete=1; } +dd_zram_scan() { :; } ''' + sender + ''' -BL_ZRAM_IDLE=0; bl_client_pressure; bl_session_pressure +DD_ZRAM_IDLE=0; dd_client_pressure; dd_session_pressure echo "mode:$(cat ''' + str(self.root / 'control') + ''')" ''')) def test_disabled_idle_compression_reclaims_only_the_launcher_before_focus(self): self.memory(available=1700) self.assertEqual(['send:1:client'], self.run_policy(''' -BL_ZRAM_IDLE=0 focused=0 -bl_client_pressure -bl_session_pressure +DD_ZRAM_IDLE=0 focused=0 +dd_client_pressure +dd_session_pressure ''')) def test_disabled_idle_compression_respects_launcher_setting_and_threshold(self): self.memory(available=1700) - self.assertEqual([], self.run_policy('BL_ZRAM_IDLE=0 BL_ZRAM_CLIENT=0; bl_client_pressure; bl_session_pressure')) + self.assertEqual([], self.run_policy('DD_ZRAM_IDLE=0 DD_ZRAM_CLIENT=0; dd_client_pressure; dd_session_pressure')) self.memory(available=1900) - self.assertEqual([], self.run_policy('BL_ZRAM_IDLE=0; bl_client_pressure; bl_session_pressure')) + self.assertEqual([], self.run_policy('DD_ZRAM_IDLE=0; dd_client_pressure; dd_session_pressure')) def test_game_reclaim_requires_focus(self): - self.assertEqual([], self.run_policy('focused=0; bl_session_pressure')) + self.assertEqual([], self.run_policy('focused=0; dd_session_pressure')) def test_game_reclaim_runs_when_focus_is_unknown(self): launch = self.root / 'launch' (launch / 'agent').mkdir(parents=True) - body = function_source('bl_game_focused') + f'\nBL_LAUNCH_DIR={launch} _bl_apps=7\n' - self.assertEqual(['send:1:session'], self.run_policy(body + 'bl_session_pressure')) + body = function_source('dd_game_focused') + f'\nDD_LAUNCH_DIR={launch} _dd_apps=7\n' + self.assertEqual(['send:1:session'], self.run_policy(body + 'dd_session_pressure')) (launch / 'agent' / 'focus.json').write_text('{"focusedApp": 9}') - self.assertEqual([], self.run_policy(body + 'bl_session_pressure')) - self.assertEqual(['unfocused'], self.run_policy(body + 'bl_game_focused || echo unfocused')) + self.assertEqual([], self.run_policy(body + 'dd_session_pressure')) + self.assertEqual(['unfocused'], self.run_policy(body + 'dd_game_focused || echo unfocused')) (launch / 'agent' / 'focus.json').unlink() - self.assertEqual(['unfocused'], self.run_policy(body + 'bl_game_focused || echo unfocused')) + self.assertEqual(['unfocused'], self.run_policy(body + 'dd_game_focused || echo unfocused')) def test_launcher_pressure_remains_available_on_larger_devices(self): self.memory(total=15360, available=1400) - self.assertEqual(['send:1:client'], self.run_policy('BL_ZRAM_IDLE=0; bl_client_pressure; bl_session_pressure')) + self.assertEqual(['send:1:client'], self.run_policy('DD_ZRAM_IDLE=0; dd_client_pressure; dd_session_pressure')) def test_enough_available_memory_does_not_compress_even_with_stalls(self): self.memory(available=3072, psi='5.00') - self.assertEqual([], self.run_policy('bl_session_pressure')) + self.assertEqual([], self.run_policy('dd_session_pressure')) def test_stalls_with_moderate_headroom_compress_before_the_hard_limit(self): self.memory(available=2048, psi='1.50') - self.assertEqual(['send:1:session'], self.run_policy('bl_session_pressure')) + self.assertEqual(['send:1:session'], self.run_policy('dd_session_pressure')) def test_moderate_headroom_without_stalls_waits(self): self.memory(available=2048) - self.assertEqual([], self.run_policy('bl_session_pressure')) + self.assertEqual([], self.run_policy('dd_session_pressure')) def test_same_second_memory_read_preserves_the_pressure_baseline(self): self.memory(available=2048) meminfo = self.root / 'meminfo' self.assertEqual(['1048576:524288:2097152'], self.run_policy(f''' SECONDS=100 -_bl_sample_at=100 _bl_sample_available=2097152 _bl_growth=0 _bl_fall=524288 +_dd_sample_at=100 _dd_sample_available=2097152 _dd_growth=0 _dd_fall=524288 sed -i 's/MemAvailable: 2097152 kB/MemAvailable: 1048576 kB/' {meminfo} -bl_memory_read -echo "$_bl_available:$_bl_fall:$_bl_sample_available" +dd_memory_read +echo "$_dd_available:$_dd_fall:$_dd_sample_available" ''')) def test_game_reading_back_most_of_a_pageout_skips_and_doubles_the_wait(self): self.assertEqual(['send:1:session', 'backoff:60', 'send:1:session', 'backoff:60', 'send:1:session', 'backoff:30'], self.run_policy(''' pushed=$((512 * 1024)) -SECONDS=0; bl_session_pressure +SECONDS=0; dd_session_pressure swap=$((swap / 4)) -SECONDS=30; bl_session_pressure -echo "backoff:$_bl_tier_backoff" -SECONDS=60; bl_session_pressure -SECONDS=90; bl_session_pressure -echo "backoff:$_bl_tier_backoff" -SECONDS=150; bl_session_pressure -echo "backoff:$_bl_tier_backoff" +SECONDS=30; dd_session_pressure +echo "backoff:$_dd_tier_backoff" +SECONDS=60; dd_session_pressure +SECONDS=90; dd_session_pressure +echo "backoff:$_dd_tier_backoff" +SECONDS=150; dd_session_pressure +echo "backoff:$_dd_tier_backoff" ''')) def test_repeated_read_back_keeps_doubling_up_to_five_minutes(self): self.assertEqual(['backoff:300'], self.run_policy(''' -_bl_tier_backoff=240 _bl_tier_at=0 _bl_tier_targets=(999) _bl_tier_swaps=($((1024 * 1024))) _bl_tier_starts=(100) _bl_tier_pushed=$((1024 * 1024)) swap=0 -SECONDS=240; bl_session_pressure -echo "backoff:$_bl_tier_backoff" +_dd_tier_backoff=240 _dd_tier_at=0 _dd_tier_targets=(999) _dd_tier_swaps=($((1024 * 1024))) _dd_tier_starts=(100) _dd_tier_pushed=$((1024 * 1024)) swap=0 +SECONDS=240; dd_session_pressure +echo "backoff:$_dd_tier_backoff" +''')) + + def test_no_gain_pageout_doubles_the_tier_wait(self): + self.assertEqual(['send:1:session', 'backoff:60', 'send:1:session', 'backoff:120'], self.run_policy(''' +available_after=1024 +SECONDS=0; dd_session_pressure +echo "backoff:$_dd_tier_backoff" +SECONDS=30; dd_session_pressure +SECONDS=60; dd_session_pressure +echo "backoff:$_dd_tier_backoff" +''')) + + def test_meaningful_available_gain_keeps_the_tier_wait(self): + self.assertEqual(['send:1:session', 'backoff:30', 'send:1:session', 'backoff:30'], self.run_policy(''' +available_after=1300 +SECONDS=0; dd_session_pressure +echo "backoff:$_dd_tier_backoff" +available_after=1600 +SECONDS=30; dd_session_pressure +echo "backoff:$_dd_tier_backoff" +''')) + + def test_recovered_available_memory_resets_the_tier_wait(self): + self.assertEqual(['send:1:session', 'backoff:60', 'backoff:30', 'send:1:session'], self.run_policy(''' +available_after=1024 +SECONDS=0; dd_session_pressure +echo "backoff:$_dd_tier_backoff" +available_after=2000 +sed -i "s/^MemAvailable:.*/MemAvailable: 2048000 kB/" "$meminfo" +SECONDS=30; dd_session_pressure +echo "backoff:$_dd_tier_backoff" +available_after=1024 +sed -i "s/^MemAvailable:.*/MemAvailable: 1048576 kB/" "$meminfo" +SECONDS=60; dd_session_pressure +''')) + + def test_critical_memory_still_compresses_after_a_no_gain_pass(self): + self.memory(available=512) + self.assertEqual(['send:1:session', 'send:1:session'], self.run_policy(''' +available_after=512 +SECONDS=0; dd_session_pressure +SECONDS=30; dd_session_pressure +''')) + + def test_a_no_gain_pass_still_skips_memory_the_game_read_back(self): + self.memory(available=512) + self.assertEqual(['send:1:session'], self.run_policy(''' +available_after=512 +SECONDS=0; dd_session_pressure +swap=0 +SECONDS=30; dd_session_pressure ''')) def test_nearly_out_of_memory_ignores_the_backoff_but_keeps_30_seconds(self): self.memory(available=512) self.assertEqual(['send:1:session', 'send:1:session'], self.run_policy(''' -_bl_tier_backoff=300 -SECONDS=0; bl_session_pressure -SECONDS=20; bl_session_pressure -SECONDS=30; bl_session_pressure +_dd_tier_backoff=300 +SECONDS=0; dd_session_pressure +SECONDS=20; dd_session_pressure +SECONDS=30; dd_session_pressure ''')) def test_nearly_out_of_memory_still_backs_off_when_the_game_reads_its_pageout_back(self): self.memory(available=512) self.assertEqual(['send:1:session', 'backoff:60', 'send:1:session'], self.run_policy(''' -SECONDS=0; bl_session_pressure +SECONDS=0; dd_session_pressure swap=0 -SECONDS=30; bl_session_pressure -echo "backoff:$_bl_tier_backoff" -SECONDS=59; bl_session_pressure -SECONDS=60; bl_session_pressure -SECONDS=90; bl_session_pressure +SECONDS=30; dd_session_pressure +echo "backoff:$_dd_tier_backoff" +SECONDS=59; dd_session_pressure +SECONDS=60; dd_session_pressure +SECONDS=90; dd_session_pressure ''')) def test_nearly_out_of_memory_retries_a_skipped_pageout_after_30_seconds(self): self.memory(available=512) self.assertEqual(['send:1:session', 'send:1:session'], self.run_policy(''' -SECONDS=0; bl_session_pressure +SECONDS=0; dd_session_pressure swap=0 -SECONDS=30; bl_session_pressure -_bl_tier_backoff=300 +SECONDS=30; dd_session_pressure +_dd_tier_backoff=300 saved=$rss; rss=$((128 * 1024)) -SECONDS=330; bl_session_pressure +SECONDS=330; dd_session_pressure rss=$saved -SECONDS=359; bl_session_pressure -SECONDS=360; bl_session_pressure +SECONDS=359; dd_session_pressure +SECONDS=360; dd_session_pressure ''')) def test_small_swap_headroom_skips_the_pageout(self): self.memory(swap_free=1536, swap_total=2048) - self.assertEqual([], self.run_policy('bl_session_pressure')) + self.assertEqual([], self.run_policy('dd_session_pressure')) def test_file_backed_resident_memory_does_not_consume_the_swap_budget(self): self.memory(swap_free=3088, swap_total=6144) self.assertEqual(['send:1:session'], self.run_policy(''' rss=$((4096 * 1024)) anon=$((1024 * 1024)) -bl_session_pressure +dd_session_pressure ''')) def test_anonymous_memory_and_pending_client_still_need_the_full_swap_reserve(self): self.memory(swap_free=3088, swap_total=6144) self.assertEqual([], self.run_policy(''' rss=$((4096 * 1024)) anon=$((2048 * 1024)) -bl_session_pressure +dd_session_pressure ''')) self.assertEqual([], self.run_policy(''' -rss=$((4096 * 1024)) anon=$((1536 * 1024)) _bl_client_reserve=$((512 * 1024)) -bl_session_pressure +rss=$((4096 * 1024)) anon=$((1536 * 1024)) _dd_client_reserve=$((512 * 1024)) +dd_session_pressure ''')) def test_small_session_is_left_alone(self): - self.assertEqual([], self.run_policy('rss=$((128 * 1024)); bl_session_pressure')) + self.assertEqual([], self.run_policy('rss=$((128 * 1024)); dd_session_pressure')) def test_watch_polls_every_second_near_the_limit_and_stops_when_critical(self): self.memory(available=2560) - self.assertEqual(['nap:1', 'nap:1', 'nap:1', 'nap:1', 'nap:1'], self.run_policy('bl_watch_nap')) + self.assertEqual(['nap:1', 'nap:1', 'nap:1', 'nap:1', 'nap:1'], self.run_policy('dd_watch_nap')) self.memory(available=1024) - self.assertEqual(['nap:1'], self.run_policy('_bl_available=$((2560 * 1024)); bl_watch_nap')) + self.assertEqual(['nap:1'], self.run_policy('_dd_available=$((2560 * 1024)); dd_watch_nap')) self.memory(available=4096) - self.assertEqual(['nap:5'], self.run_policy('bl_watch_nap')) - self.assertEqual(['nap:5'], self.run_policy('_bl_game=0; bl_watch_nap')) + self.assertEqual(['nap:5'], self.run_policy('dd_watch_nap')) + self.assertEqual(['nap:5'], self.run_policy('_dd_game=0; dd_watch_nap')) def test_session_push_preserves_client_timestamps(self): self.assertEqual(['send:1:session', 'pids:321 654', 'client:-1:-1'], self.run_policy(''' -SECONDS=0; bl_session_pressure -bl_zram_pick session; echo "pids:${_pids[*]}" -echo "client:$_bl_pressure_at:$_bl_packed" +SECONDS=0; dd_session_pressure +dd_zram_pick session; echo "pids:${_pids[*]}" +echo "client:$_dd_pressure_at:$_dd_packed" ''')) def test_launcher_compression_turned_off_keeps_the_launcher_out(self): self.assertEqual(['pids:321 654', 'client:-1:-1'], self.run_policy(''' -BL_ZRAM_CLIENT=0 -SECONDS=0; bl_session_pressure -bl_zram_pick session; echo "pids:${_pids[*]}" -echo "client:$_bl_pressure_at:$_bl_packed" +DD_ZRAM_CLIENT=0 +SECONDS=0; dd_session_pressure +dd_zram_pick session; echo "pids:${_pids[*]}" +echo "client:$_dd_pressure_at:$_dd_packed" ''')[1:]) def test_low_ram_devices_compress_with_a_quarter_of_memory_left(self): self.memory(available=1700) - self.assertEqual(['send:1:session'], self.run_policy('bl_session_pressure')) + self.assertEqual(['send:1:session'], self.run_policy('dd_session_pressure')) self.memory(available=1900) - self.assertEqual([], self.run_policy('bl_session_pressure')) + self.assertEqual([], self.run_policy('dd_session_pressure')) def test_a_compressed_process_that_exits_is_not_counted_as_read_back(self): self.assertEqual(['send:1:session', 'send:1:session', 'backoff:30'], self.run_policy(''' -SECONDS=0; bl_session_pressure +SECONDS=0; dd_session_pressure alive=""; swap=0 -SECONDS=30; bl_session_pressure -echo "backoff:$_bl_tier_backoff" +SECONDS=30; dd_session_pressure +echo "backoff:$_dd_tier_backoff" ''')) def test_a_process_that_starts_after_a_pageout_is_not_in_its_read_back(self): self.assertEqual(['send:1:session', 'targets:321 654', 'send:1:session', 'backoff:30'], self.run_policy(''' -SECONDS=0; bl_session_pressure -echo "targets:${_bl_tier_targets[*]}" +SECONDS=0; dd_session_pressure +echo "targets:${_dd_tier_targets[*]}" alive="999 1234" -SECONDS=30; bl_session_pressure -echo "backoff:$_bl_tier_backoff" +SECONDS=30; dd_session_pressure +echo "backoff:$_dd_tier_backoff" +''')) + + def test_read_back_wait_holds_above_the_critical_level(self): + self.assertEqual(['send:1:session', 't:60', 'send:1:session'], self.run_policy(''' +SECONDS=0; dd_session_pressure +swap=0 +SECONDS=30; dd_session_pressure +SECONDS=60; dd_session_pressure; echo t:60 +SECONDS=90; dd_session_pressure +''')) + + def test_a_no_gain_pageout_preserves_client_timestamps(self): + self.assertEqual(['send:1:session', 'backoff:60', 'client:-1:-1'], self.run_policy(''' +available_after=1024 +SECONDS=0; dd_session_pressure +echo "backoff:$_dd_tier_backoff" +echo "client:$_dd_pressure_at:$_dd_packed" ''')) def test_an_incomplete_pageout_does_not_restart_the_launcher_wait(self): self.assertEqual(['send:1:session', 'client:-1:-1'], self.run_policy(''' complete=0 -SECONDS=0; bl_session_pressure -echo "client:$_bl_pressure_at:$_bl_packed" +SECONDS=0; dd_session_pressure +echo "client:$_dd_pressure_at:$_dd_packed" ''')) def test_a_reused_process_id_is_not_counted_as_read_back(self): self.assertEqual(['send:1:session', 'send:1:session', 'backoff:30'], self.run_policy(''' -SECONDS=0; bl_session_pressure +SECONDS=0; dd_session_pressure started=200; swap=0 -SECONDS=30; bl_session_pressure -echo "backoff:$_bl_tier_backoff" +SECONDS=30; dd_session_pressure +echo "backoff:$_dd_tier_backoff" ''')) def test_process_start_comes_from_stat_and_zombies_have_none(self): stat = self.root / 'stat' - source = function_source('bl_proc_start').replace('/proc/$1/stat', str(stat)) + source = function_source('dd_proc_start').replace('/proc/$1/stat', str(stat)) fields = ' '.join(['0'] * 17) for state, expected in (('S', ['ok:4242']), ('Z', ['gone:'])): with self.subTest(state=state): stat.write_text(f'77 (Wow (arm64).exe) {state} 1 {fields} 4242 99 0\n') - result = run_bash(source + '\nif bl_proc_start 77; then echo "ok:$_bl_start"; else echo "gone:$_bl_start"; fi') + result = run_bash(source + '\nif dd_proc_start 77; then echo "ok:$_dd_start"; else echo "gone:$_dd_start"; fi') self.assertEqual(expected, result.stdout.split()) stat.unlink() - result = run_bash(source + '\nbl_proc_start 77 || echo gone') + result = run_bash(source + '\ndd_proc_start 77 || echo gone') self.assertEqual(['gone'], result.stdout.split()) @@ -445,49 +535,49 @@ class ReclaimDispatchTest(unittest.TestCase): f'MemTotal: 7340032 kB\nMemAvailable: {available * 1024} kB\n' 'SwapTotal: 6291456 kB\nSwapFree: 4194304 kB\n') (root / 'pressure').write_text('some avg10=0.00 avg60=0.00 avg300=0.00 total=0\n') - names = ('bl_memory_read', 'bl_memory_tight', 'bl_memory_critical', - 'bl_zram_has_room', 'bl_client_can_pageout', 'bl_client_pressure', - 'bl_client_pressure_result', 'bl_client_pressure_finish', - 'bl_session_pressure', 'bl_zram_send', 'bl_zram_finish', 'bl_zram_pick') + names = ('dd_memory_read', 'dd_memory_tight', 'dd_memory_critical', + 'dd_zram_has_room', 'dd_client_can_pageout', 'dd_client_pressure', + 'dd_client_pressure_result', 'dd_client_pressure_finish', + 'dd_session_pressure', 'dd_zram_send', 'dd_zram_finish', 'dd_zram_pick') source = '\n'.join(function_source(name) for name in names) source = source.replace('/proc/meminfo', str(root / 'meminfo')) source = source.replace('/proc/pressure/memory', str(root / 'pressure')) - source = source.replace('/tmp/.bl-zram', str(root / 'ctl')) + source = source.replace('/tmp/.dd-zram', str(root / 'ctl')) monitor = SCRIPT.read_text() - start = monitor.index(' _bl_preserved_growth=$_bl_growth', monitor.index('while kill -0 $$')) - stop = monitor.index(' if [ "$_bl_game" = 1 ] && bl_game_focused', start) + start = monitor.index(' _dd_preserved_growth=$_dd_growth', monitor.index('while kill -0 $$')) + stop = monitor.index(' _dd_focus=1\n', start) cycle = monitor[start:stop] if body is None else body script = f''' set -u -BL_ZRAM_CLIENT={client} _bl_game={game} _bl_pids=(123) _bl_others=(321) -_bl_pressure_at=-1 _bl_pressure_backoff=30 _bl_packed=-1 -_bl_tier_at=-1 _bl_tier_backoff=30 _bl_tier_pushed=0 -_bl_client_reserve=0 client_rss=393216 client_anon={anonymous * 1024} +DD_ZRAM_CLIENT={client} _dd_game={game} _dd_pids=(123) _dd_others=(321) +_dd_pressure_at=-1 _dd_pressure_backoff=30 _dd_packed=-1 +_dd_tier_at=-1 _dd_tier_backoff=30 _dd_tier_pushed=0 +_dd_client_reserve=0 client_rss=393216 client_anon={anonymous * 1024} step() {{ :; }} -bl_session_others() {{ _bl_session=(321); }} -bl_zram_scan() {{ _bl_pids=(456); }} +dd_session_others() {{ _dd_session=(321); }} +dd_zram_scan() {{ _dd_pids=(456); }} nap() {{ echo "nap:$*:at:$NOW"; }} -bl_zram_usage() {{ +dd_zram_usage() {{ if [ "$1" = 123 ]; then - _bl_rss=$client_rss _bl_anon=$client_anon _bl_swap=0 + _dd_rss=$client_rss _dd_anon=$client_anon _dd_swap=0 else - _bl_rss=3145728 _bl_anon=1572864 _bl_swap=0 + _dd_rss=3145728 _dd_anon=1572864 _dd_swap=0 fi }} kill() {{ echo "signal:$*:at:$NOW"; NOW=$((NOW + {tick})); }} -bl_zram_wait() {{ +dd_zram_wait() {{ echo "wait:$*:at:$NOW" NOW=$((NOW + 12)) - _bl_pageout_complete={complete} + _dd_pageout_complete={complete} [ "$1" != 123 ] || client_rss=$((client_rss - {reclaimed * 1024})) }} -bl_tier_note() {{ :; }} -bl_game_focused() {{ :; }} +dd_tier_note() {{ :; }} +dd_game_focused() {{ :; }} ''' + source + f''' -bl_memory_read -_bl_fall={fall * 1024} +dd_memory_read +_dd_fall={fall * 1024} ''' + cycle + ''' -echo "client:$_bl_pressure_backoff:${_bl_client_reserve:-0}:${_bl_client_pending:-0}" +echo "client:$_dd_pressure_backoff:${_dd_client_reserve:-0}:${_dd_client_pending:-0}" ''' result = run_bash('NOW=0\n' + script.replace('SECONDS', 'NOW')) self.assertEqual(0, result.returncode, result.stderr) @@ -523,13 +613,13 @@ echo "client:$_bl_pressure_backoff:${_bl_client_reserve:-0}:${_bl_client_pending def test_explicit_combined_send_keeps_its_synchronous_wait(self): self.assertEqual(['signal:-URG 321 123:at:0', 'wait:321 123:at:0', 'client:30:0:0'], - self.run_cycle(body='bl_zram_send 1 cap game\n')) + self.run_cycle(body='dd_zram_send 1 cap game\n')) self.assertEqual(['signal:-URG 321:at:0', 'wait:321:at:0', 'client:30:0:0'], - self.run_cycle(client=0, body='bl_zram_send 1 cap game\n')) + self.run_cycle(client=0, body='dd_zram_send 1 cap game\n')) def test_readback_keeps_its_synchronous_delay(self): self.assertEqual(['signal:-URG 123:at:0', 'nap:5:at:0', 'client:30:0:0'], - self.run_cycle(body='bl_zram_send 0 readback client\n')) + self.run_cycle(body='dd_zram_send 0 readback client\n')) def test_usage_sums_anonymous_rss_and_falls_back_per_process(self): with tempfile.TemporaryDirectory() as directory: @@ -539,8 +629,8 @@ echo "client:$_bl_pressure_backoff:${_bl_client_reserve:-0}:${_bl_client_pending (654, 'VmRSS: 1000 kB\nRssAnon: 0 kB\n')): (root / str(pid)).mkdir() (root / str(pid) / 'status').write_text(contents) - source = function_source('bl_zram_usage').replace('/proc/', str(root) + '/') - result = run_bash(source + '\nbl_zram_usage 123 321 654 > /dev/null; echo "$_bl_rss:$_bl_anon:$_bl_swap"') + source = function_source('dd_zram_usage').replace('/proc/', str(root) + '/') + result = run_bash(source + '\ndd_zram_usage 123 321 654 > /dev/null; echo "$_dd_rss:$_dd_anon:$_dd_swap"') self.assertEqual(0, result.returncode, result.stderr) self.assertEqual('7000:4300:300', result.stdout.strip()) diff --git a/tools/tests/test_native_hook_proc_exe.py b/tools/tests/test_native_hook_proc_exe.py new file mode 100644 index 0000000000..fdf6e615ab --- /dev/null +++ b/tools/tests/test_native_hook_proc_exe.py @@ -0,0 +1,127 @@ +import os +from pathlib import Path +import shutil +import subprocess +import tempfile +import unittest + +from tools.tests.test_usr2_preload import runner + +HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh" + +PROBE = r""" +#include +#include +#include +#include + +int main(int argc, char **argv) { + for (int i = 1; i < argc; i++) { + char buf[4096]; + ssize_t n; + if (strncmp(argv[i], "at:", 3) == 0) { + int dfd = open(argv[i] + 3, O_RDONLY | O_DIRECTORY); + n = dfd >= 0 ? readlinkat(dfd, "exe", buf, sizeof(buf) - 1) : -1; + if (dfd >= 0) close(dfd); + } else { + n = readlink(argv[i], buf, sizeof(buf) - 1); + } + buf[n > 0 ? n : 0] = 0; + printf("%s\t%s\n", argv[i], n > 0 ? buf : "-"); + } + return 0; +} +""" + +SLEEPER = r""" +#include +#include +int main(void) { puts("ready"); fflush(stdout); sleep(60); return 0; } +""" + + +class NativeHookProcExeTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cc, cls.prefix = runner() + if cls.cc is None: + raise unittest.SkipTest("no aarch64 compiler and runner") + cls.tmp = tempfile.TemporaryDirectory() + tmp = Path(cls.tmp.name) + cls.hook = tmp / "hook.so" + subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True) + for name, source in (("probe", PROBE), ("sleeper", SLEEPER)): + (tmp / f"{name}.c").write_text(source) + subprocess.run([cls.cc, "-O1", "-o", str(tmp / name), str(tmp / f"{name}.c")], check=True) + cls.root = tmp / "root" + (cls.root / "usr/bin").mkdir(parents=True) + cls.kwin = cls.root / "usr/bin/kwin_wayland" + shutil.copy(tmp / "sleeper", cls.kwin) + # The child's /proc//exe must name the loader, as DroidDeck's libddexec.so does. + cls.loader = tmp / "lib/libddexec.so" + cls.loader.parent.mkdir() + if cls.prefix: + shutil.copy(shutil.which(cls.prefix[0]), cls.loader) + cls.loader_args = list(cls.prefix[1:]) + else: + ld = next(p for p in ("/lib/ld-linux-aarch64.so.1", "/lib64/ld-linux-aarch64.so.1") if os.path.exists(p)) + shutil.copy(ld, cls.loader) + cls.loader_args = [] + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def start(self, loader, real_exe=None, program=None): + env = {k: v for k, v in os.environ.items() if k not in ("LD_PRELOAD", "DDNATV_REAL_EXE")} + if real_exe: + env["DDNATV_REAL_EXE"] = real_exe + program = program or Path(self.tmp.name) / "sleeper" + cmd = ([str(self.loader), *self.loader_args] if loader else list(self.prefix)) + [str(program)] + child = subprocess.Popen(cmd, env=env, stdout=subprocess.PIPE, text=True) + self.addCleanup(child.stdout.close) + self.addCleanup(child.wait) + self.addCleanup(child.kill) + self.assertEqual("ready", child.stdout.readline().strip()) + return child.pid + + def readlink(self, *paths): + hook_env = {"DDNATV_ROOT": str(self.root), "LD_PRELOAD": str(self.hook)} + env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"} + if self.prefix: + cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")] + else: + cmd = [] + env.update(hook_env) + out = subprocess.run(cmd + [str(Path(self.tmp.name) / "probe"), *paths], env=env, capture_output=True, + text=True, timeout=120) + self.assertEqual(out.returncode, 0, out.stderr) + return {line.split("\t")[0]: line.split("\t")[1] for line in out.stdout.splitlines()} + + def test_another_guest_program_names_the_program_its_loader_runs(self): + pid = self.start(loader=True, real_exe=str(self.kwin), program=self.kwin) + link = f"/proc/{pid}/exe" + self.assertEqual("/usr/bin/kwin_wayland", self.readlink(link)[link]) + + def test_a_descriptor_for_the_process_directory_gives_the_same_program(self): + pid = self.start(loader=True, real_exe=str(self.kwin), program=self.kwin) + at = f"at:/proc/{pid}" + self.assertEqual("/usr/bin/kwin_wayland", self.readlink(at)[at]) + + def test_a_program_named_only_in_the_environment_is_not_believed(self): + pid = self.start(loader=True, real_exe=str(self.kwin)) + link = f"/proc/{pid}/exe" + self.assertEqual(os.readlink(link), self.readlink(link)[link]) + + def test_a_process_not_started_by_the_loader_is_unchanged(self): + pid = self.start(loader=False, real_exe=str(self.kwin)) + link = f"/proc/{pid}/exe" + self.assertEqual(os.readlink(link), self.readlink(link)[link]) + + def test_a_loader_without_a_known_program_keeps_the_kernel_link(self): + pid = self.start(loader=True) + link = f"/proc/{pid}/exe" + self.assertEqual(os.readlink(link), self.readlink(link)[link]) + +if __name__ == "__main__": + unittest.main() diff --git a/tools/tests/test_netlink_preload.py b/tools/tests/test_netlink_preload.py index aedbdbd733..7c47c971f9 100644 --- a/tools/tests/test_netlink_preload.py +++ b/tools/tests/test_netlink_preload.py @@ -1107,7 +1107,7 @@ class NetlinkPreloadTest(unittest.TestCase): def setUpClass(cls): cls.temp = tempfile.TemporaryDirectory() cls.directory = Path(cls.temp.name) - cls.preload = cls.directory / "libblsession.so" + cls.preload = cls.directory / "libddsession.so" cls.shim = cls.directory / "libshim.so" cls.program = cls.directory / "program" (cls.directory / "shim.c").write_text(SHIM) @@ -1132,7 +1132,7 @@ class NetlinkPreloadTest(unittest.TestCase): def run_program(self, mode, *arguments, snapshot=None): env = dict(os.environ, LD_PRELOAD=f"{self.preload}:{self.shim}", NETLINK_TEST_SNAPSHOT=str(snapshot or self.snapshot), - BL_SYSV_DIR=str(self.directory / "sysv")) + DD_SYSV_DIR=str(self.directory / "sysv")) result = subprocess.run([str(self.program), mode, *arguments], env=env, capture_output=True, text=True, timeout=5) self.assertEqual(0, result.returncode, result.stdout + result.stderr) @@ -1280,7 +1280,7 @@ class NetlinkPreloadTest(unittest.TestCase): def test_iproute2_dumps_and_lookups_accept_the_replies(self): env = dict(os.environ, LD_PRELOAD=f"{self.preload}:{self.shim}", NETLINK_TEST_SNAPSHOT=str(self.snapshot), - BL_SYSV_DIR=str(self.directory / "sysv")) + DD_SYSV_DIR=str(self.directory / "sysv")) queries = ((["link", "show"], "wlan0"), (["link", "show", "wlan0"], "wlan0"), (["-d", "link", "show", "dev", "wlan0"], "wlan0"), diff --git a/tools/tests/test_noexec_preload.py b/tools/tests/test_noexec_preload.py index 6b220fa20f..29cf383bc5 100644 --- a/tools/tests/test_noexec_preload.py +++ b/tools/tests/test_noexec_preload.py @@ -127,12 +127,14 @@ static void mapping(void *addr, char *out) { fclose(maps); } int main(int argc, char **argv) { - if (argc != 2) return 2; + if (argc < 2) return 2; + int anonymous = argc > 2; size_t page = sysconf(_SC_PAGESIZE); int fd = open(argv[1], O_RDONLY); - char *addr = mmap(NULL, page * 2, PROT_NONE, MAP_PRIVATE, fd, 0); - if (addr == MAP_FAILED || mmap(addr + page, page, PROT_READ | PROT_WRITE, - MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0) != addr + page) return 3; + char *addr = anonymous ? mmap(NULL, page * 2, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0) + : mmap(NULL, page * 2, PROT_NONE, MAP_PRIVATE, fd, 0); + if (addr == MAP_FAILED || (!anonymous && mmap(addr + page, page, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0) != addr + page)) return 3; addr[page] = 73; char before[1024], after[1024], tail_before[1024], tail_after[1024]; mapping(addr, before); @@ -214,6 +216,12 @@ class NoexecPreloadTest(unittest.TestCase): capture_output=True, text=True, check=True) self.assertEqual(result.stdout.strip(), "result -1 13 preserved 1 1 tail 73 calls 0 0 1") + def test_anonymous_memory_is_never_replaced(self): + env = dict(os.environ, LD_PRELOAD=f"{self.lib}:{self.failures}", ALLOW_FIXED="1") + result = subprocess.run([str(self.tmp / "failure_image"), str(self.code), "anonymous"], env=env, + capture_output=True, text=True, check=True) + self.assertEqual(result.stdout.strip(), "result -1 13 preserved 1 1 tail 73 calls 0 0 1") + @unittest.skipUnless(platform.machine() in RETURN_42, "needs a known host instruction set") def test_replacement_installs_executable_pages_without_final_mprotect(self): env = dict(os.environ, LD_PRELOAD=f"{self.lib}:{self.failures}", ALLOW_FIXED="1") diff --git a/tools/tests/test_ntsync_preload.py b/tools/tests/test_ntsync_preload.py index a2c50a7d68..52d7666a64 100644 --- a/tools/tests/test_ntsync_preload.py +++ b/tools/tests/test_ntsync_preload.py @@ -549,20 +549,20 @@ class NtsyncPreloadTest(unittest.TestCase): (tmp / "ntdll.c").write_text(NTDLL) (tmp / "prog.c").write_text(PROGRAM) sources = sorted(str(p) for p in PRELOAD.glob("*.c")) - subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(tmp / "libblsession.so"), *sources, "-ldl"], + subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(tmp / "libddsession.so"), *sources, "-ldl"], check=True) subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(tmp / "ntdll.so"), str(tmp / "ntdll.c")], check=True) subprocess.run(["cc", "-O1", "-pthread", "-o", str(tmp / "prog"), str(tmp / "prog.c"), str(tmp / "ntdll.so"), "-Wl,-rpath," + str(tmp)], check=True) cls.program = tmp / "prog" - cls.preload = tmp / "libblsession.so" + cls.preload = tmp / "libddsession.so" @classmethod def tearDownClass(cls): cls.tmp.cleanup() def run_program(self): - env = dict(os.environ, LD_PRELOAD=str(self.preload), BL_SYNC="1") + env = dict(os.environ, LD_PRELOAD=str(self.preload), DD_SYNC="1") return subprocess.run([str(self.program)], env=env, capture_output=True, text=True, timeout=90) def test_emulation_matches_the_ntsync_driver(self): diff --git a/tools/tests/test_oom_adj_preload.py b/tools/tests/test_oom_adj_preload.py index f6fc25ce16..896c87b274 100644 --- a/tools/tests/test_oom_adj_preload.py +++ b/tools/tests/test_oom_adj_preload.py @@ -8,9 +8,9 @@ SOURCE = Path(__file__).resolve().parents[1] / "linuxfs/preload/oomadj.c" PROGRAM = r""" #include -const char *bl_oom_adj_redirect(const char *path, int writing); +const char *dd_oom_adj_redirect(const char *path, int writing); int main(int argc, char **argv) { - for (int i = 1; i + 1 < argc; i += 2) printf("%s\n", bl_oom_adj_redirect(argv[i + 1], argv[i][0] == 'w')); + for (int i = 1; i + 1 < argc; i += 2) printf("%s\n", dd_oom_adj_redirect(argv[i + 1], argv[i][0] == 'w')); return 0; } """ diff --git a/tools/tests/test_openat2_preload.py b/tools/tests/test_openat2_preload.py index cbaefaab24..81b18da8ba 100644 --- a/tools/tests/test_openat2_preload.py +++ b/tools/tests/test_openat2_preload.py @@ -329,12 +329,12 @@ class Openat2PreloadTest(unittest.TestCase): counter = cls.tmp / "counter.c" counter.write_text(COUNTER) (cls.tmp / "fp").mkdir() - subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-o", str(cls.tmp / "fp/libblfastpath.so"), + subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-o", str(cls.tmp / "fp/libddfastpath.so"), str(counter), "-ldl"], check=True) tree = cls.tmp / "counted" make_tree(tree, cls.outside) counted = subprocess.run([str(cls.tmp / "openat2"), str(tree), str(tree)], input=cases, capture_output=True, - text=True, env=dict(os.environ, LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "fp/libblfastpath.so")), + text=True, env=dict(os.environ, LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "fp/libddfastpath.so")), timeout=60) if counted.returncode != 0: raise AssertionError(counted.stdout + counted.stderr) @@ -345,7 +345,7 @@ class Openat2PreloadTest(unittest.TestCase): subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-o", str(cls.tmp / "raw_open"), str(raw)], check=True) cls.raw = subprocess.run([str(cls.tmp / "raw_open"), str(tree / "etc/hostname"), str(tree / "missing")], capture_output=True, text=True, timeout=60, - env=dict(os.environ, LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "fp/libblfastpath.so"))) + env=dict(os.environ, LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "fp/libddfastpath.so"))) lookup = cls.tmp / "raw_lookup.c" lookup.write_text(RAW_LOOKUP) subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-o", str(cls.tmp / "raw_lookup"), str(lookup)], check=True) @@ -353,16 +353,16 @@ class Openat2PreloadTest(unittest.TestCase): cls.lookup_plain = subprocess.run([str(cls.tmp / "raw_lookup"), *cls.lookup_args], capture_output=True, text=True, timeout=60, env=dict(os.environ, LD_PRELOAD=str(cls.lib))) cls.lookup = subprocess.run([str(cls.tmp / "raw_lookup"), *cls.lookup_args], capture_output=True, text=True, timeout=60, - env=dict(os.environ, LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "fp/libblfastpath.so"))) + env=dict(os.environ, LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "fp/libddfastpath.so"))) (cls.tmp / "real").mkdir() subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-pthread", "-o", - str(cls.tmp / "real/libblfastpath.so"), str(FASTPATH), "-ldl"], check=True) + str(cls.tmp / "real/libddfastpath.so"), str(FASTPATH), "-ldl"], check=True) shutil.copy(cls.tmp / "raw_open", cls.tmp / "FEX") try: cls.fex = subprocess.run([str(cls.tmp / "FEX"), str(tree / "etc/hostname"), str(tree / "missing")], capture_output=True, text=True, timeout=20, env=dict(os.environ, PROOT_FP_ROOT="/", PROOT_FP_KEY="test", - LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "real/libblfastpath.so"))) + LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "real/libddfastpath.so"))) except subprocess.TimeoutExpired: cls.fex = None wrapper = cls.tmp / "wrapper.c" @@ -376,7 +376,7 @@ class Openat2PreloadTest(unittest.TestCase): try: cls.fex_lookup = subprocess.run([str(cls.tmp / "fex-lookup/FEX"), *cls.lookup_args], capture_output=True, text=True, timeout=20, env=dict(os.environ, PROOT_FP_ROOT="/", PROOT_FP_KEY="test", - LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "real/libblfastpath.so"))) + LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "real/libddfastpath.so"))) except subprocess.TimeoutExpired: cls.fex_lookup = None diff --git a/tools/tests/test_pipewire_helper.py b/tools/tests/test_pipewire_helper.py index 5f87b11cb9..5e717e2db7 100644 --- a/tools/tests/test_pipewire_helper.py +++ b/tools/tests/test_pipewire_helper.py @@ -8,6 +8,7 @@ from pathlib import Path SOURCE = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-pipewire' +@unittest.skipIf(os.name == "nt", "the helper needs a POSIX shell, flock and Unix sockets") class PipeWireHelperTest(unittest.TestCase): def setUp(self): self.temporary = tempfile.TemporaryDirectory() diff --git a/tools/tests/test_preload_snapshots.py b/tools/tests/test_preload_snapshots.py index 2d0ee01642..41c8dd8327 100644 --- a/tools/tests/test_preload_snapshots.py +++ b/tools/tests/test_preload_snapshots.py @@ -123,7 +123,7 @@ class PreloadSnapshotTest(unittest.TestCase): def test_forged_binary_hash_cannot_prove_main_origin(self): data = copy.deepcopy(self.data) - data['outputs']['libblsession.so'] = 'f' * 64 + data['outputs']['libddsession.so'] = 'f' * 64 with patch.object(snapshots, 'artifact_bytes', return_value=self.binaries): with self.assertRaisesRegex(ValueError, 'original main APK'): snapshots.prove_origin(data, self.root / 'cache', self.root) @@ -179,7 +179,7 @@ class PreloadSnapshotTest(unittest.TestCase): snapshots.unpack(self.content + b'tampered', self.data) def test_missing_duplicate_or_traversal_entries_are_rejected(self): - for files in ({}, {'../escaped': b'bad'}, {'libblsession.so': b'wrong'}): + for files in ({}, {'../escaped': b'bad'}, {'libddsession.so': b'wrong'}): content = archive(files) data = dict(self.data, archive_sha256=snapshots.sha(content)) with self.subTest(names=list(files)), self.assertRaises(ValueError): diff --git a/tools/tests/test_session_cpu.py b/tools/tests/test_session_cpu.py index a5d741d16e..30bbea60a7 100644 --- a/tools/tests/test_session_cpu.py +++ b/tools/tests/test_session_cpu.py @@ -24,7 +24,7 @@ cat() { ''' paths = ' '.join(f'/sys/devices/system/cpu/cpu{i}/cpufreq/cpuinfo_max_freq' for i in range(8)) function = function.replace('/sys/devices/system/cpu/cpu[0-9]*/cpufreq/cpuinfo_max_freq', paths) - env = dict(os.environ, mode=mode, BL_GAME_CPUS=cpus, BL_PIN_CORES=pin) + env = dict(os.environ, mode=mode, DD_GAME_CPUS=cpus, DD_PIN_CORES=pin) result = subprocess.run(['bash', '-c', script + function + '\nprogram_cores\n'], env=env, capture_output=True, text=True, timeout=10) self.assertEqual(0, result.returncode, result.stderr) diff --git a/tools/tests/test_session_cursor_routing.py b/tools/tests/test_session_cursor_routing.py index dd2c77d944..05974b0cc2 100644 --- a/tools/tests/test_session_cursor_routing.py +++ b/tools/tests/test_session_cursor_routing.py @@ -7,7 +7,7 @@ import unittest SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session' SOURCE = SESSION.read_text() MATCH = re.search( - r'^ if \[ "\$mode" = steam \] && \[ "\$\{BL_CURSOR_COMPOSITE:-0\}" = 1 \]; then\n.*?^ fi\n', + r'^ if \[ "\$mode" = steam \] && \[ "\$\{DD_CURSOR_COMPOSITE:-0\}" = 1 \]; then\n.*?^ fi\n', SOURCE, re.M | re.S) assert MATCH is not None CURSOR_SETUP = MATCH.group(0) @@ -21,9 +21,9 @@ class SessionCursorRoutingTest(unittest.TestCase): else: env.pop('gamescope_cursor_composite', None) if composite is not None: - env['BL_CURSOR_COMPOSITE'] = composite + env['DD_CURSOR_COMPOSITE'] = composite else: - env.pop('BL_CURSOR_COMPOSITE', None) + env.pop('DD_CURSOR_COMPOSITE', None) result = subprocess.run( ['bash', '-c', CURSOR_SETUP + 'printf "%s\n" "${gamescope_cursor_composite-}"'], env=env, text=True, capture_output=True, check=True) diff --git a/tools/tests/test_session_log.py b/tools/tests/test_session_log.py index 19dbb27165..1bfe0409e6 100644 --- a/tools/tests/test_session_log.py +++ b/tools/tests/test_session_log.py @@ -20,7 +20,7 @@ class SessionLogTest(unittest.TestCase): self.log = self.tmp / "session.log" def run_session(self, body, cap=None): - script = "BL_LOG=%s\n%s%s\n%s\n" % (self.log, "BL_LOG_CAP=%d\n" % cap if cap else "", log_redirect(), body) + script = "DD_LOG=%s\n%s%s\n%s\n" % (self.log, "DD_LOG_CAP=%d\n" % cap if cap else "", log_redirect(), body) subprocess.run(["bash", "-c", script], timeout=30, check=False) def test_the_last_lines_survive_the_writer_being_killed(self): diff --git a/tools/tests/test_session_pacing.py b/tools/tests/test_session_pacing.py index 67b616669c..6b64810340 100644 --- a/tools/tests/test_session_pacing.py +++ b/tools/tests/test_session_pacing.py @@ -11,12 +11,12 @@ SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/d class SessionPacingTest(unittest.TestCase): def launch(self, refresh, **overrides): source = SESSION.read_text() - start = source.index(' width=${BL_WIDTH:-1280}') - end = source.index('\nfi\n\nbl_displays()', start) + start = source.index(' width=${DD_WIDTH:-1280}') + end = source.index('\nfi\n\ndd_displays()', start) block = source[start:end].replace('/usr/local/bin/droiddeck-pipewire', 'pipewire_stub') with tempfile.TemporaryDirectory() as directory: - env = dict(os.environ, XDG_RUNTIME_DIR=directory, BL_REFRESH=str(refresh), - BL_MANGOAPP='0', BL_FPS='0', DROIDDECK_GAME_FRAME_LIMIT='0') + env = dict(os.environ, XDG_RUNTIME_DIR=directory, DD_REFRESH=str(refresh), + DD_MANGOAPP='0', DD_FPS='0', DROIDDECK_GAME_FRAME_LIMIT='0') env.pop('GAMESCOPE_NESTED_REFRESH_FOLLOWS_HOST', None) env.update(overrides) script = ''' @@ -49,12 +49,12 @@ run_gamescope() { printf 'ARG:%s\\n' "$@"; printf 'FOLLOW:%s\\n' "${GAMESCOPE_NE def test_retired_cap_variables_do_not_override_the_display_rate(self): for performance in ('0', '1'): with self.subTest(performance=performance): - args = self.launch(120, BL_FPS='30', DROIDDECK_GAME_FRAME_LIMIT=performance) + args = self.launch(120, DD_FPS='30', DROIDDECK_GAME_FRAME_LIMIT=performance) self.assertEqual('120', args[args.index('-r') + 1]) self.assertNotIn('--framerate-limit', args) def test_retired_cap_cannot_set_the_rate_when_the_display_rate_is_unknown(self): - args = self.launch(0, BL_FPS='30', DROIDDECK_GAME_FRAME_LIMIT='1') + args = self.launch(0, DD_FPS='30', DROIDDECK_GAME_FRAME_LIMIT='1') self.assertNotIn('-r', args) self.assertNotIn('--framerate-limit', args) diff --git a/tools/tests/test_session_run_display.py b/tools/tests/test_session_run_display.py index 430a6a1373..d5e4e0d657 100644 --- a/tools/tests/test_session_run_display.py +++ b/tools/tests/test_session_run_display.py @@ -28,7 +28,7 @@ class SessionRunDisplayTest(unittest.TestCase): 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")} + "DD_LAUNCH_DIR")} seen = self.dir / "seen" script = ("program_cores() { :; }\nmode=run\ncase $mode in\n" + run_case() + "esac\n" + "echo unreachable\n") diff --git a/tools/tests/test_session_run_status.py b/tools/tests/test_session_run_status.py index b4c1914b7a..7080b81f2b 100644 --- a/tools/tests/test_session_run_status.py +++ b/tools/tests/test_session_run_status.py @@ -23,9 +23,9 @@ class RunStatusTest(unittest.TestCase): def run_with(self, command, launch_dir=True): env = dict(os.environ) - env.pop("BL_LAUNCH_DIR", None) + env.pop("DD_LAUNCH_DIR", None) if launch_dir: - env["BL_LAUNCH_DIR"] = str(self.dir) + env["DD_LAUNCH_DIR"] = str(self.dir) return subprocess.run(["bash", "-c", run_program_function() + "run_program " + command + "; echo unreachable"], env=env, capture_output=True, text=True, timeout=30) @@ -45,7 +45,7 @@ class RunStatusTest(unittest.TestCase): self.assertEqual([], os.listdir(self.dir)) def signalled(self, sig, program): - env = dict(os.environ, BL_LAUNCH_DIR=str(self.dir)) + env = dict(os.environ, DD_LAUNCH_DIR=str(self.dir)) ready = self.dir / "ready" proc = subprocess.Popen(["bash", "-c", run_program_function() + "run_program " + program], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) diff --git a/tools/tests/test_session_vkbridge_wait.py b/tools/tests/test_session_vkbridge_wait.py index bbd4fdb264..24ae01d89e 100644 --- a/tools/tests/test_session_vkbridge_wait.py +++ b/tools/tests/test_session_vkbridge_wait.py @@ -15,7 +15,7 @@ SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/d def wait_functions(): text = SESSION.read_text() found = [] - for name in ("bl_now_ms", "vkbridge_wait_socket"): + for name in ("dd_now_ms", "vkbridge_wait_socket"): match = re.search(r"^%s\(\) \{\n.*?^\}\n" % name, text, re.M | re.S) if match: found.append(match.group(0)) @@ -44,7 +44,7 @@ class VkBridgeSocketWaitTest(unittest.TestCase): def run_wait(self, limit_ms, prelude=""): functions = wait_functions() - self.assertEqual(2, len(functions), "droiddeck-session lacks bl_now_ms() or vkbridge_wait_socket()") + self.assertEqual(2, len(functions), "droiddeck-session lacks dd_now_ms() or vkbridge_wait_socket()") script = "set -u\n" + "".join(functions) + prelude script += 'if vkbridge_wait_socket "$1" "$2"; then echo USABLE; else echo FALLBACK; fi\n' started = time.monotonic() @@ -88,7 +88,7 @@ class VkBridgeSocketWaitTest(unittest.TestCase): self.assertTrue(out.endswith("FALLBACK\n"), out) def test_a_stopping_session_does_not_wait(self): - out, elapsed = self.run_wait(10000, prelude="bl_stopping=1\n") + out, elapsed = self.run_wait(10000, prelude="dd_stopping=1\n") self.assertTrue(out.endswith("FALLBACK\n"), out) self.assertIn("the session is stopping", out) self.assertLess(elapsed, 2) @@ -105,7 +105,7 @@ class VkBridgeSessionCheckTest(unittest.TestCase): def setUp(self): self.text = SESSION.read_text() - match = re.search(r'^if \[ "\$\{BL_VKBRIDGE:-0\}" = 1 \]; then\n.*?^fi\n', self.text, re.M | re.S) + match = re.search(r'^if \[ "\$\{DD_VKBRIDGE:-0\}" = 1 \]; then\n.*?^fi\n', self.text, re.M | re.S) self.assertIsNotNone(match) self.block = match.group(0) @@ -113,14 +113,14 @@ class VkBridgeSessionCheckTest(unittest.TestCase): wait = self.block.index("vkbridge_wait_socket") check = self.block.index('[ -S "${VKBRIDGE_SOCKET:-}" ]') self.assertLess(wait, check) - self.assertIn('[ -z "${BL_INSIDE:-}" ] && vkbridge_wait_socket', self.block) + self.assertIn('[ -z "${DD_INSIDE:-}" ] && vkbridge_wait_socket', self.block) def test_the_fallback_message_names_what_is_missing(self): self.assertIn("Mali bridge requested but NOT usable", self.block) - self.assertIn("missing:$bl_vkb_missing", self.block) + self.assertIn("missing:$dd_vkb_missing", self.block) def test_a_stop_ends_the_wait(self): - self.assertRegex(self.text, r"trap '[^']*bl_stopping=1[^']*' TERM INT HUP") + self.assertRegex(self.text, r"trap '[^']*dd_stopping=1[^']*' TERM INT HUP") if __name__ == "__main__": diff --git a/tools/tests/test_session_webhelper_layout.py b/tools/tests/test_session_webhelper_layout.py index 0a6ba0b27f..fe7b71105c 100644 --- a/tools/tests/test_session_webhelper_layout.py +++ b/tools/tests/test_session_webhelper_layout.py @@ -5,70 +5,70 @@ import unittest from pathlib import Path SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session" -KEYS = ("BL_VKBRIDGE_WEBHELPER_ARGS", "BL_VKBRIDGE_CEF_ANGLE", "BL_VKBRIDGE_CEF_VULKAN") +KEYS = ("DD_VKBRIDGE_WEBHELPER_ARGS", "DD_VKBRIDGE_CEF_ANGLE", "DD_VKBRIDGE_CEF_VULKAN") def layout_function(): - match = re.search(r"^bl_webhelper_layout\(\) \{\n.*?^\}\n", SESSION.read_text(), re.M | re.S) + match = re.search(r"^dd_webhelper_layout\(\) \{\n.*?^\}\n", SESSION.read_text(), re.M | re.S) return match.group(0) if match else None class WebhelperLayoutTest(unittest.TestCase): def layout(self, **settings): function = layout_function() - self.assertIsNotNone(function, "droiddeck-session lacks bl_webhelper_layout()") + self.assertIsNotNone(function, "droiddeck-session lacks dd_webhelper_layout()") env = {k: v for k, v in os.environ.items() if k not in KEYS} env.update(settings) - return subprocess.run(["bash", "-c", "set -u\n" + function + "bl_webhelper_layout\n"], env=env, + return subprocess.run(["bash", "-c", "set -u\n" + function + "dd_webhelper_layout\n"], env=env, capture_output=True, text=True, check=True).stdout.strip() def test_unset_keeps_steams_own_layout(self): self.assertEqual(self.layout(), "stock") def test_angle_on_vulkan_brings_chromiums_vulkan_compositing(self): - self.assertEqual(self.layout(BL_VKBRIDGE_CEF_ANGLE="vulkan"), + self.assertEqual(self.layout(DD_VKBRIDGE_CEF_ANGLE="vulkan"), "--use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan") def test_vulkan_compositing_can_be_left_off(self): - self.assertEqual(self.layout(BL_VKBRIDGE_CEF_ANGLE="vulkan", BL_VKBRIDGE_CEF_VULKAN="0"), + self.assertEqual(self.layout(DD_VKBRIDGE_CEF_ANGLE="vulkan", DD_VKBRIDGE_CEF_VULKAN="0"), "--use-gl=angle --use-angle=vulkan") def test_other_angle_backends_get_only_the_angle_switches(self): - self.assertEqual(self.layout(BL_VKBRIDGE_CEF_ANGLE="gl"), "--use-gl=angle --use-angle=gl") + self.assertEqual(self.layout(DD_VKBRIDGE_CEF_ANGLE="gl"), "--use-gl=angle --use-angle=gl") def test_explicit_layout_wins(self): - self.assertEqual(self.layout(BL_VKBRIDGE_CEF_ANGLE="vulkan", BL_VKBRIDGE_WEBHELPER_ARGS="--x +Y"), + self.assertEqual(self.layout(DD_VKBRIDGE_CEF_ANGLE="vulkan", DD_VKBRIDGE_WEBHELPER_ARGS="--x +Y"), "--x +Y") def test_the_steam_block_uses_it(self): - self.assertIn("BL_WEBHELPER_ARGS=$(bl_webhelper_layout)", SESSION.read_text()) + self.assertIn("DD_WEBHELPER_ARGS=$(dd_webhelper_layout)", SESSION.read_text()) def test_the_gpu_ui_on_the_bridge_defaults_to_angle_on_vulkan_without_vulkan_compositing(self): text = SESSION.read_text() - gpu = text.index('elif [ "${_bl_cef[0]}" = -cef-force-gpu ]; then') - software = text.rindex('_bl_cef=(-cef-disable-gpu -cef-disable-gpu-compositing)', 0, gpu) - defaults = text.index(': "${BL_VKBRIDGE_CEF_ANGLE=vulkan}" "${BL_VKBRIDGE_CEF_VULKAN=0}"', gpu) + gpu = text.index('elif [ "${_dd_cef[0]}" = -cef-force-gpu ]; then') + software = text.rindex('_dd_cef=(-cef-disable-gpu -cef-disable-gpu-compositing)', 0, gpu) + defaults = text.index(': "${DD_VKBRIDGE_CEF_ANGLE=vulkan}" "${DD_VKBRIDGE_CEF_VULKAN=0}"', gpu) self.assertLess(software, gpu) - self.assertLess(defaults, text.index("BL_WEBHELPER_ARGS=$(bl_webhelper_layout)", gpu)) + self.assertLess(defaults, text.index("DD_WEBHELPER_ARGS=$(dd_webhelper_layout)", gpu)) self.assertLess(defaults, text.index("\n fi\n", gpu)) def test_the_defaults_give_way_to_settings(self): - script = ': "${BL_VKBRIDGE_CEF_ANGLE=vulkan}" "${BL_VKBRIDGE_CEF_VULKAN=0}"\n' + layout_function() + "bl_webhelper_layout\n" + script = ': "${DD_VKBRIDGE_CEF_ANGLE=vulkan}" "${DD_VKBRIDGE_CEF_VULKAN=0}"\n' + layout_function() + "dd_webhelper_layout\n" env = {k: v for k, v in os.environ.items() if k not in KEYS} run = lambda **s: subprocess.run(["bash", "-c", "set -u\n" + script], env={**env, **s}, capture_output=True, text=True, check=True).stdout.strip() self.assertEqual(run(), "--use-gl=angle --use-angle=vulkan") - self.assertEqual(run(BL_VKBRIDGE_CEF_VULKAN="1"), + self.assertEqual(run(DD_VKBRIDGE_CEF_VULKAN="1"), "--use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan") - self.assertEqual(run(BL_VKBRIDGE_CEF_ANGLE="gl"), "--use-gl=angle --use-angle=gl") + self.assertEqual(run(DD_VKBRIDGE_CEF_ANGLE="gl"), "--use-gl=angle --use-angle=gl") def test_empty_settings_are_kept_as_set(self): - script = ': "${BL_VKBRIDGE_CEF_ANGLE=vulkan}" "${BL_VKBRIDGE_CEF_VULKAN=0}"\n' + layout_function() + "bl_webhelper_layout\n" + script = ': "${DD_VKBRIDGE_CEF_ANGLE=vulkan}" "${DD_VKBRIDGE_CEF_VULKAN=0}"\n' + layout_function() + "dd_webhelper_layout\n" env = {k: v for k, v in os.environ.items() if k not in KEYS} run = lambda **s: subprocess.run(["bash", "-c", "set -u\n" + script], env={**env, **s}, capture_output=True, text=True, check=True).stdout.strip() - self.assertEqual(run(BL_VKBRIDGE_CEF_ANGLE=""), "stock") - self.assertEqual(run(BL_VKBRIDGE_CEF_VULKAN=""), + self.assertEqual(run(DD_VKBRIDGE_CEF_ANGLE=""), "stock") + self.assertEqual(run(DD_VKBRIDGE_CEF_VULKAN=""), "--use-gl=angle --use-angle=vulkan +Vulkan +VulkanFromANGLE +DefaultANGLEVulkan") diff --git a/tools/tests/test_steam_adopt.py b/tools/tests/test_steam_adopt.py new file mode 100644 index 0000000000..50db1827c1 --- /dev/null +++ b/tools/tests/test_steam_adopt.py @@ -0,0 +1,147 @@ +import importlib.machinery +import importlib.util +import runpy +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin" +APPINFO = runpy.run_path(str(Path(__file__).with_name("test_droiddeck_fex.py")))["AppInfoTest"].appinfo + + +def load(name): + loader = importlib.machinery.SourceFileLoader(name.replace("-", "_"), str(BIN / name)) + spec = importlib.util.spec_from_loader(loader.name, loader) + module = importlib.util.module_from_spec(spec) + loader.exec_module(module) + return module + + +library = load("droiddeck-steam-library") + + +def record(kind, installdir, name): + return {"common": {"type": kind, "name": name}, "config": {"installdir": installdir}} + + +class AdoptTest(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + root = Path(temp.name) + self.steam = root / "Steam" + self.card = root / "card" + self.common = self.card / "steamapps/common" + self.common.mkdir(parents=True) + (self.steam / "appcache").mkdir(parents=True) + (self.steam / "steamapps").mkdir() + self.write_info({ + 10: record("Game", "Alpha", 'Alpha "Deluxe"'), + 20: record("Game", "Beta", "Beta"), + 30: record("Tool", "Proton Thing", "Proton Thing"), + 40: record("Game", "Shared", "Shared Game"), + 41: record("Demo", "Shared", "Shared Demo"), + 50: record("Game", "Twin", "Twin One"), + 51: record("Game", "Twin", "Twin Two"), + }) + for patcher in (patch.object(library, "BIN_DIR", str(BIN)), + patch("builtins.print")): + patcher.start() + self.addCleanup(patcher.stop) + + def write_info(self, apps): + (self.steam / "appcache/appinfo.vdf").write_bytes(APPINFO(apps)) + + def folder(self, name, files=("data.bin",)): + path = self.common / name + path.mkdir(parents=True, exist_ok=True) + for f in files: + (path / f).write_text("x") + + def manifest(self, app, root=None): + return (root or self.card) / ("steamapps/appmanifest_%s.acf" % app) + + def adopt(self): + return library.adopt(str(self.steam), str(self.card)) + + def test_matched_folder_gets_a_validating_manifest(self): + self.folder("Alpha") + self.assertEqual(self.adopt(), 1) + text = self.manifest(10).read_text() + for line in ('"appid" "10"', '"Universe" "1"', '"StateFlags" "4"', '"installdir" "Alpha"', + '"name" "Alpha \\"Deluxe\\""', '"AutoUpdateBehavior" "1"'): + self.assertIn(line, text) + self.assertNotIn("buildid", text) + self.assertNotIn("InstalledDepots", text) + + def test_existing_manifest_is_untouched(self): + self.folder("Alpha") + self.manifest(10).write_text("mine") + self.assertEqual(self.adopt(), 0) + self.assertEqual(self.manifest(10).read_text(), "mine") + + def test_unmatched_empty_and_hidden_folders_are_skipped(self): + self.folder("Unknown") + self.folder(".hidden") + (self.common / "Beta").mkdir() + (self.common / "file.txt").write_text("x") + self.assertEqual(self.adopt(), 0) + self.assertEqual(list((self.card / "steamapps").glob("appmanifest_*")), []) + + def test_unreadable_game_folder_is_skipped_without_aborting(self): + self.folder("Unreadable") + real = library.os.scandir + + def scandir(path): + if str(path).endswith("Unreadable"): + raise PermissionError(path) + return real(path) + + with patch.object(library.os, "scandir", scandir): + self.assertEqual(library.adoptable(str(self.card), set()), []) + + def test_tool_type_app_is_skipped(self): + self.folder("Proton Thing") + self.assertEqual(self.adopt(), 0) + self.assertFalse(self.manifest(30).exists()) + + def test_game_wins_over_demo_and_ambiguous_games_are_skipped(self): + self.folder("Shared") + self.folder("Twin") + self.assertEqual(self.adopt(), 1) + self.assertTrue(self.manifest(40).exists()) + self.assertFalse(self.manifest(41).exists()) + self.assertFalse(self.manifest(50).exists() or self.manifest(51).exists()) + + def test_app_installed_in_another_library_is_left_alone(self): + self.folder("Alpha") + other = self.steam / "steamapps/appmanifest_10.acf" + other.write_text('"AppState"\n{\n\t"appid"\t"10"\n\t"installdir"\t"Elsewhere"\n}\n') + self.assertEqual(self.adopt(), 0) + self.assertFalse(self.manifest(10).exists()) + self.assertEqual(len(list(self.steam.glob("steamapps/appmanifest_*"))), 1) + + def test_adoption_is_idempotent_and_only_touches_the_given_library(self): + self.folder("Alpha") + self.folder("Beta") + self.assertEqual(self.adopt(), 2) + first = {n: self.manifest(n).read_text() for n in (10, 20)} + self.assertEqual(self.adopt(), 0) + self.assertEqual({n: self.manifest(n).read_text() for n in (10, 20)}, first) + self.assertEqual(list(self.steam.glob("steamapps/appmanifest_*")), []) + + def test_main_adopts_every_registered_library(self): + self.folder("Beta") + listing = self.steam.parent / "libraries.json" + listing.write_text('[{"path": "%s", "label": "SD Card"}]' % self.card) + with patch.dict("os.environ", {"DD_STEAM_LIBRARIES": str(listing)}), \ + patch("sys.argv", ["droiddeck-steam-library", str(self.steam)]): + library.main() + self.assertTrue(self.manifest(20).exists()) + self.assertIn(str(self.card), (self.steam / "steamapps/libraryfolders.vdf").read_text()) + self.assertIn('"20"', (self.steam / "steamapps/libraryfolders.vdf").read_text()) + + +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 index 774e14aa4a..4ce8087f6a 100644 --- a/tools/tests/test_steam_client_setup_failure.py +++ b/tools/tests/test_steam_client_setup_failure.py @@ -32,13 +32,13 @@ class SteamClientSetupFailureTest(unittest.TestCase): script.chmod(0o755) def env(self, **extra): - base = {k: v for k, v in os.environ.items() if k != 'BL_STEAM_EXIT_FILE'} + base = {k: v for k, v in os.environ.items() if k != 'DD_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 {} + extra = {'DD_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) diff --git a/tools/tests/test_steam_cold_launch.py b/tools/tests/test_steam_cold_launch.py index 0fe085ff9e..dc94b025b4 100644 --- a/tools/tests/test_steam_cold_launch.py +++ b/tools/tests/test_steam_cold_launch.py @@ -8,7 +8,7 @@ import unittest SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session" SOURCE = SESSION.read_text() START = SOURCE.index(" steam_hold_launch() {") -END = SOURCE.index(' if [ -s "$HOME/.bl-autolaunch" ]; then', START) +END = SOURCE.index(' if [ -s "$HOME/.dd-autolaunch" ]; then', START) assert START >= 0 LAUNCH_BLOCK = textwrap.dedent(SOURCE[START:END]) SHORTCUT = str((3551182975 << 32) | 0x02000000) @@ -57,7 +57,7 @@ class SteamColdLaunchTest(unittest.TestCase): self.block = LAUNCH_BLOCK.replace("/usr/local/bin/droiddeck-agent", str(agent)) def run_launch(self, target, focus="769", helper_status=0, running_after=999, ready_status=0): - env = dict(os.environ, HOME=str(self.root), BL_LAUNCH_DIR=str(self.launch_dir), + env = dict(os.environ, HOME=str(self.root), DD_LAUNCH_DIR=str(self.launch_dir), PATH=str(self.bin) + os.pathsep + os.environ["PATH"], AGENT_ARGS=str(self.agent_args), SLEEP_ARGS=str(self.sleep_args), AGENT_COUNT=str(self.agent_count), AGENT_STATUS=str(helper_status), @@ -133,11 +133,11 @@ class SteamColdLaunchTest(unittest.TestCase): self.assertIn("--steam-ready", self.agent_args.read_text()) def test_a_restart_for_a_game_uses_the_same_hand_off(self): - loop = SOURCE[SOURCE.index(' if [ -s "$HOME/.bl-restart-game" ]; then'):SOURCE.index(' if [ -f "$HOME/.bl-restart-once" ]; then')] - self.assertIn('steam_hold_launch "$_bl_again" &', loop) + loop = SOURCE[SOURCE.index(' if [ -s "$HOME/.dd-restart-game" ]; then'):SOURCE.index(' if [ -f "$HOME/.dd-restart-once" ]; then')] + self.assertIn('steam_hold_launch "$_dd_again" &', loop) self.assertNotIn("set -- \"steam://rungameid/", loop) script = self.block + '\nsteam_hold_launch "%s"\n' % SHORTCUT - env = dict(os.environ, HOME=str(self.root), BL_LAUNCH_DIR=str(self.launch_dir), + env = dict(os.environ, HOME=str(self.root), DD_LAUNCH_DIR=str(self.launch_dir), PATH=str(self.bin) + os.pathsep + os.environ["PATH"], AGENT_ARGS=str(self.agent_args), SLEEP_ARGS=str(self.sleep_args), AGENT_COUNT=str(self.agent_count), AGENT_STATUS="1", diff --git a/tools/tests/test_steam_compat_environment.py b/tools/tests/test_steam_compat_environment.py index 5ecaba1772..f03b006939 100644 --- a/tools/tests/test_steam_compat_environment.py +++ b/tools/tests/test_steam_compat_environment.py @@ -12,7 +12,7 @@ BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin' class SteamCompatEnvironmentTest(unittest.TestCase): def test_library_launch_preserves_guest_environment_without_steam_client_libraries(self): source = (BIN / 'droiddeck-session').read_text() - setup = source[source.index(' _bl_compat_env='):source.index(' export SDL_VIDEO_X11_DGAMOUSE=')] + setup = source[source.index(' _dd_compat_env='):source.index(' export SDL_VIDEO_X11_DGAMOUSE=')] launch = next(line for line in source.splitlines() if 'droiddeck-steam-compat "$steam_root"' in line) with tempfile.TemporaryDirectory() as directory: @@ -57,7 +57,7 @@ class SteamCompatEnvironmentTest(unittest.TestCase): helper.chmod(0o755) env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'], PID_FILE=str(pid), steam_root='/steam', steam_x64='0') - subprocess.run(['bash', '-c', '_bl_compat_env=(env)\n' + launch + '\n' + subprocess.run(['bash', '-c', '_dd_compat_env=(env)\n' + launch + '\n' 'until [ -s "$PID_FILE" ]; do sleep 0.05; done\n' 'kill $(jobs -p)\nwait'], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10) @@ -83,7 +83,7 @@ class SteamCompatEnvironmentTest(unittest.TestCase): args = root / ('args-' + x64) env = dict(os.environ, PATH=str(root) + os.pathsep + os.environ['PATH'], ARGS_FILE=str(args), steam_root='/steam', steam_x64=x64) - subprocess.run(['bash', '-c', '_bl_compat_env=(env)\n' + block + 'wait\n'], env=env, timeout=10, check=True) + subprocess.run(['bash', '-c', '_dd_compat_env=(env)\n' + block + 'wait\n'], env=env, timeout=10, check=True) self.assertEqual(args.read_text().split('\n')[0], expected) def test_files_only_mode_installs_only_the_file_dialog_hook(self): diff --git a/tools/tests/test_steam_compat_mapping.py b/tools/tests/test_steam_compat_mapping.py index dd9ba22196..7c03b24de6 100644 --- a/tools/tests/test_steam_compat_mapping.py +++ b/tools/tests/test_steam_compat_mapping.py @@ -210,7 +210,7 @@ class MappingBatchIntegrationTest(unittest.TestCase): config = steam / "config/config.vdf" config.parent.mkdir(parents=True) config.write_text(config_text("".join('"%s" { "name" "proton_experimental" }' % app for app in apps))) - pending = Path(tmp) / ".bl-compat-pending" + pending = Path(tmp) / ".dd-compat-pending" pending.write_text("before\n") globals_ = COMPAT["x64_repoint"].__globals__ single = mock.Mock(wraps=COMPAT["set_mapping"]) diff --git a/tools/tests/test_steam_compat_x64.py b/tools/tests/test_steam_compat_x64.py index 9d9bf109e0..72b894dbac 100644 --- a/tools/tests/test_steam_compat_x64.py +++ b/tools/tests/test_steam_compat_x64.py @@ -92,7 +92,7 @@ class X64RepointTest(unittest.TestCase): def test_live_notes_pending_restart(self): COMPAT["x64_repoint"](str(self.root), "GE-Proton11-7-a64", live=True) - self.assertEqual((Path(self.home.name) / ".bl-compat-pending").read_text(), "550\n880\n") + self.assertEqual((Path(self.home.name) / ".dd-compat-pending").read_text(), "550\n880\n") def test_no_tool_changes_nothing(self): before = (self.root / "config" / "config.vdf").read_text() diff --git a/tools/tests/test_steam_desktop_launch.py b/tools/tests/test_steam_desktop_launch.py index 7d50640878..4d49c9dd47 100644 --- a/tools/tests/test_steam_desktop_launch.py +++ b/tools/tests/test_steam_desktop_launch.py @@ -17,10 +17,10 @@ class DesktopSteamLaunchTest(unittest.TestCase): self.session = self.root / 'session' self.session.mkdir() self.env = dict(os.environ, HOME=str(self.root), XDG_DATA_HOME=str(self.root / 'data'), - XDG_CACHE_HOME=str(self.root / 'cache'), BL_DESKTOP='1', - BL_LAUNCH_DIR=str(self.session)) + XDG_CACHE_HOME=str(self.root / 'cache'), DD_DESKTOP='1', + DD_LAUNCH_DIR=str(self.session)) supervisor = self.root / 'supervisor' - supervisor.write_text('#!/bin/bash\nprintf "%s\\n" "$BL_INSIDE" "$BL_STEAM_UI" "$DISPLAY" "$@"\n') + supervisor.write_text('#!/bin/bash\nprintf "%s\\n" "$DD_INSIDE" "$DD_STEAM_UI" "$DISPLAY" "$@"\n') supervisor.chmod(0o755) x64 = self.root / 'steam-x64' x64.write_text('#!/bin/bash\nprintf "%s\\n" x64 "$@"\n') @@ -102,7 +102,7 @@ class DesktopSteamLaunchTest(unittest.TestCase): def test_bottom_screen_desktop_hands_games_to_the_running_client(self): self._running_client() - self.env['BL_BOTTOM_DESKTOP'] = '1' + self.env['DD_BOTTOM_DESKTOP'] = '1' result = self.launch('desktop', '501590') self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(result.stdout.splitlines(), ['-nobigpicture', '-no-cef-sandbox', '-cef-ozone-platform=x11', @@ -110,7 +110,7 @@ class DesktopSteamLaunchTest(unittest.TestCase): self.assertFalse((self.root / 'cache/droiddeck/steam-desktop.lock').exists()) def test_bottom_screen_desktop_starts_its_own_client_when_none_runs(self): - self.env.update(BL_BOTTOM_DESKTOP='1', DISPLAY=':7') + self.env.update(DD_BOTTOM_DESKTOP='1', DISPLAY=':7') result = self.launch('desktop') self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(result.stdout.splitlines(), ['1', 'desktop', ':7', 'steam', 'steam://open/library']) @@ -122,7 +122,7 @@ class DesktopSteamLaunchTest(unittest.TestCase): (x64_home / '.steam').mkdir(parents=True) os.mkfifo(x64_home / '.steam/steam.pipe') (x64_home / '.steam/steam.pid').write_text(str(os.getpid())) - self.env.update(BL_STEAM_CLIENT_ARCH='x86_64', BL_X64_HOME=str(x64_home)) + self.env.update(DD_STEAM_CLIENT_ARCH='x86_64', DD_X64_HOME=str(x64_home)) with lock.open('w') as handle: fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) result = self.launch('desktop', '501590') @@ -164,7 +164,7 @@ class DesktopSteamLaunchTest(unittest.TestCase): self.assertEqual((self.session / 'steam-launch').read_text(), 'ui=bigpicture\nurl=\n') def test_outside_desktop_preserves_session_request(self): - self.env.pop('BL_DESKTOP') + self.env.pop('DD_DESKTOP') result = self.launch('desktop', 'steam://open/settings') self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual((self.session / 'steam-launch').read_text(), @@ -176,11 +176,11 @@ class DesktopSteamLaunchTest(unittest.TestCase): def test_cef_software_is_scoped_to_the_kde_client(self): source = (BIN / 'droiddeck-session').read_text() - setup = source[source.index(' _bl_ui=(-gamepadui)'):source.index(' if [ "${BL_STEAM_UI:-}" != desktop ]; then')] + setup = source[source.index(' _dd_ui=(-gamepadui)'):source.index(' if [ "${DD_STEAM_UI:-}" != desktop ]; then')] for desktop, ui, software in [('1', 'desktop', True), ('1', 'bigpicture', False), ('', 'desktop', False)]: with self.subTest(desktop=desktop, ui=ui): - env = dict(self.env, BL_DESKTOP=desktop, BL_STEAM_UI=ui) - result = subprocess.check_output(['bash', '-c', setup + '\nprintf "%s\\n" "${_bl_cef[@]}"'], + env = dict(self.env, DD_DESKTOP=desktop, DD_STEAM_UI=ui) + result = subprocess.check_output(['bash', '-c', setup + '\nprintf "%s\\n" "${_dd_cef[@]}"'], env=env, text=True) self.assertEqual('-cef-disable-gpu' in result, software) self.assertEqual('-cef-use-angle=vulkan' in result, not software) diff --git a/tools/tests/test_steam_devtools_port.py b/tools/tests/test_steam_devtools_port.py index 8015ba260d..3932486e42 100644 --- a/tools/tests/test_steam_devtools_port.py +++ b/tools/tests/test_steam_devtools_port.py @@ -29,7 +29,7 @@ class SteamDevtoolsPortTest(unittest.TestCase): function = devtools_function() self.assertIsNotNone(function, "droiddeck-session has no steam_devtools()") script = function + "steam_root=%s\nsteam_devtools %d\n" % (shlex.quote(str(self.root)), port) - script += 'echo "port=$BL_CDP_PORT"\necho "args=${_bl_cdp[*]}"\n' + script += 'echo "port=$DD_CDP_PORT"\necho "args=${_dd_cdp[*]}"\n' out = subprocess.run(["bash", "-c", script], capture_output=True, text=True, timeout=30, check=True).stdout lines = out.splitlines() port_line = next(l for l in lines if l.startswith("port=")) @@ -71,7 +71,7 @@ class SteamDevtoolsPortTest(unittest.TestCase): def test_the_x86_64_decky_exemption_only_covers_the_fixed_port(self): text = SESSION.read_text() - self.assertIn('[ "${decky_arch:-}" = x86_64 ] && [ ${#_bl_cdp[@]} = 0 ]', text) + self.assertIn('[ "${decky_arch:-}" = x86_64 ] && [ ${#_dd_cdp[@]} = 0 ]', text) if __name__ == "__main__": diff --git a/tools/tests/test_steam_exit_status.py b/tools/tests/test_steam_exit_status.py index 8cfc218ab3..580ee66a39 100644 --- a/tools/tests/test_steam_exit_status.py +++ b/tools/tests/test_steam_exit_status.py @@ -25,7 +25,7 @@ class SteamExitStatusTest(unittest.TestCase): compositor.chmod(0o755) child = root / 'steam' report_arg = '"$1"' if report_value is None else '"$2"' - report_line = ('printf "%s\\n" ' + report_arg + ' > "$BL_STEAM_EXIT_FILE"\n' + report_line = ('printf "%s\\n" ' + report_arg + ' > "$DD_STEAM_EXIT_FILE"\n' if report else '') child.write_text('#!/bin/bash\n' + report_line + 'exit "$1"\n') child.chmod(0o755) diff --git a/tools/tests/test_steam_games.py b/tools/tests/test_steam_games.py index 13235e68b4..08ffc90935 100644 --- a/tools/tests/test_steam_games.py +++ b/tools/tests/test_steam_games.py @@ -5,6 +5,7 @@ import os from pathlib import Path import shutil import subprocess +import runpy import tempfile import unittest import zlib @@ -26,6 +27,15 @@ shortcuts = load('droiddeck-steam-shortcuts') library = load('droiddeck-steam-library') +class ManifestTextTest(unittest.TestCase): + def test_minimal_and_bare_text_is_exact(self): + build = runpy.run_path(str(BIN / 'steam-compatibility'))['manifest_text'] + minimal = ('"AppState"\n{\n "appid" "7"\n "Universe" "1"\n "name" "A \\"B\\" C D"\n' + ' "StateFlags" "4"\n "installdir" "DroidDeck-7"\n}\n') + self.assertEqual(minimal, build(7, 'A "B"\nC\rD', 'DroidDeck-7')) + self.assertEqual(minimal[:-2] + ' "AutoUpdateBehavior" "1"\n}\n', build(7, 'A "B"\nC\rD', 'DroidDeck-7', True)) + + class ImportsTest(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory() diff --git a/tools/tests/test_steam_helper_affinity.py b/tools/tests/test_steam_helper_affinity.py index 97549ac05d..acdac3d51a 100644 --- a/tools/tests/test_steam_helper_affinity.py +++ b/tools/tests/test_steam_helper_affinity.py @@ -45,9 +45,9 @@ class SteamHelperAffinityTest(unittest.TestCase): elif form == "empty": args = [] env = dict(os.environ, TRACE=str(root / "trace"), STARTS=str(root / "starts")) - env.pop("BL_STEAM_WEBHELPER", None) + env.pop("DD_STEAM_WEBHELPER", None) if configured: - env["BL_STEAM_WEBHELPER"] = str(helper) + env["DD_STEAM_WEBHELPER"] = str(helper) result = subprocess.run(["bash", str(wrapper), *args], env=env, capture_output=True, text=True, timeout=5) trace = [json.loads(x) for x in (root / "trace").read_text().splitlines()] diff --git a/tools/tests/test_steam_install.py b/tools/tests/test_steam_install.py index 81e2724cbb..f888b7ed13 100644 --- a/tools/tests/test_steam_install.py +++ b/tools/tests/test_steam_install.py @@ -79,7 +79,7 @@ done(28 if end < len(data) else 0) self.env = dict(os.environ, HOME=str(self.home), XDG_DATA_HOME=str(self.data), PATH=str(self.bin) + os.pathsep + os.environ['PATH'], TEST_CDN=str(self.cdn), TEST_REQUESTS=str(self.requests), - TEST_PLAN=str(self.plan), BL_STEAM_RETRY_DELAYS='0 0 0') + TEST_PLAN=str(self.plan), DD_STEAM_RETRY_DELAYS='0 0 0') for channel in ('steamdeck_publicbeta', 'steamdeck_stable'): archive = self.cdn / (channel + '.zip') with zipfile.ZipFile(archive, 'w') as package: @@ -185,7 +185,7 @@ done(28 if end < len(data) else 0) self.requests.unlink() with (package / 'droiddeck-unconfirmed').open('a') as marker: marker.write('start\nstart\nstart\n') - self.assertEqual(0, self.install(BL_STEAM_CHANNEL='beta').returncode) + self.assertEqual(0, self.install(DD_STEAM_CHANNEL='beta').returncode) self.assertFalse(self.requests.exists()) def test_the_default_channel_is_the_deck_beta(self): @@ -226,8 +226,8 @@ done(28 if end < len(data) else 0) self.assertEqual(0, self.install().returncode) with (package / 'droiddeck-unconfirmed').open('a') as marker: marker.write('start\nstart\n') - self.assertEqual('steamdeck_publicbeta', self.channel(BL_STEAM_CHANNEL='beta')) - self.assertEqual(0, self.install(BL_STEAM_CHANNEL='beta').returncode) + self.assertEqual('steamdeck_publicbeta', self.channel(DD_STEAM_CHANNEL='beta')) + self.assertEqual(0, self.install(DD_STEAM_CHANNEL='beta').returncode) self.assertFalse((package / 'droiddeck-channel').exists()) def test_the_channel_setting_selects_stable(self): @@ -255,7 +255,7 @@ done(28 if end < len(data) else 0) def test_a_pinned_beta_manifest_without_an_arm64_client_fails_and_names_its_blocks(self): self.empty_beta_manifest() - result = self.install(BL_STEAM_CHANNEL='beta') + result = self.install(DD_STEAM_CHANNEL='beta') self.assertNotEqual(0, result.returncode) self.assertIn('client_steamrtarm64_linuxarm64', result.stderr) self.assertFalse((self.steam / 'package/droiddeck-installed').exists()) @@ -263,7 +263,7 @@ done(28 if end < len(data) else 0) def test_requested_repair_runs_once_and_is_retried_until_it_completes(self): package = self.break_client(0) (package / 'droiddeck-unconfirmed').unlink() - request = self.home / '.bl-steam-repair' + request = self.home / '.dd-steam-repair' request.write_text('1\n') archive = self.cdn / 'steamdeck_publicbeta.zip' original = archive.read_bytes() @@ -402,7 +402,7 @@ done(28 if end < len(data) else 0) def test_a_repair_unpacks_every_part_again_once(self): files = self.two_parts() self.assertEqual(0, self.install().returncode) - (self.home / '.bl-steam-repair').write_text('1\n') + (self.home / '.dd-steam-repair').write_text('1\n') self.requests.unlink() self.plan_for(files['client_linuxarm64_linuxarm64'], *['fail 7'] * 12) self.assertNotEqual(0, self.install().returncode) @@ -411,7 +411,7 @@ done(28 if end < len(data) else 0) self.assertEqual(0, self.install().returncode) self.assertEqual(['steam_client_steamdeck_publicbeta_linuxarm64', files['client_linuxarm64_linuxarm64']], self.requested()) - self.assertFalse((self.home / '.bl-steam-repair').exists()) + self.assertFalse((self.home / '.dd-steam-repair').exists()) self.assertFalse(self.download.exists()) diff --git a/tools/tests/test_steam_libraries.py b/tools/tests/test_steam_libraries.py index 18c477a78a..22955661d2 100644 --- a/tools/tests/test_steam_libraries.py +++ b/tools/tests/test_steam_libraries.py @@ -63,9 +63,9 @@ class LibraryListTest(unittest.TestCase): def run_main(self, listing=True): with patch.dict(os.environ), patch("sys.argv", ["droiddeck-steam-library", str(self.steam)]): - os.environ.pop("BL_STEAM_LIBRARIES", None) + os.environ.pop("DD_STEAM_LIBRARIES", None) if listing: - os.environ["BL_STEAM_LIBRARIES"] = str(self.listing) + os.environ["DD_STEAM_LIBRARIES"] = str(self.listing) library.main() return self.vdf.read_text() diff --git a/tools/tests/test_steam_presentation.py b/tools/tests/test_steam_presentation.py index 476b90779c..801c1d4688 100644 --- a/tools/tests/test_steam_presentation.py +++ b/tools/tests/test_steam_presentation.py @@ -12,19 +12,19 @@ SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/d class SteamPresentationTest(unittest.TestCase): def launch(self, enabled=None, inherited=None): source = SESSION.read_text() - begin = source.index(" bl_steam_path=$PATH") + begin = source.index(" dd_steam_path=$PATH") end = source.index("\n decky_loader=", begin) - command = source.index(' PATH="$bl_steam_path"') + command = source.index(' PATH="$dd_steam_path"') command_end = source.index("\n rc=$?", command) - script = (source[begin:end] + '\n_bl_ui=(-gamepadui); _bl_cdp=(); _bl_lang=()\n' + script = (source[begin:end] + '\n_dd_ui=(-gamepadui); _dd_cdp=(); _dd_lang=()\n' # 0.5.0 launches through steam_client (the arm64 client, or the x86-64 one under FEX). + 'steam_client=("$steam_root/steamrtarm64/steam")\n' + source[command:command_end]) env = dict(os.environ) - for key in ("BL_STEAM_GL_PRESENT", "BL_STEAM_SOFT_COMPOSITING", "DISABLE_GAMESCOPE_WSI", "LIBGL_KOPPER_DISABLE"): + for key in ("DD_STEAM_GL_PRESENT", "DD_STEAM_SOFT_COMPOSITING", "DISABLE_GAMESCOPE_WSI", "LIBGL_KOPPER_DISABLE"): env.pop(key, None) if enabled is not None: - env["BL_STEAM_GL_PRESENT"] = enabled + env["DD_STEAM_GL_PRESENT"] = enabled env.update(inherited or {}) with tempfile.TemporaryDirectory(prefix="droiddeck-steam-gl-") as tmp: program = Path(tmp) / "steamrtarm64/steam" @@ -34,7 +34,7 @@ class SteamPresentationTest(unittest.TestCase): '"disable":os.getenv("DISABLE_GAMESCOPE_WSI"),' '"kopper":os.getenv("LIBGL_KOPPER_DISABLE"),' '"path":os.getenv("PATH"),' - '"helper":os.getenv("BL_STEAM_WEBHELPER")}))\n') + '"helper":os.getenv("DD_STEAM_WEBHELPER")}))\n') program.chmod(0o755) env.update(steam_root=tmp, steam_channel="steamdeck_publicbeta") result = subprocess.run(["bash", "-c", script, "test", "steam://open/main"], @@ -64,20 +64,20 @@ class SteamPresentationTest(unittest.TestCase): self.assertEqual(result["args"][-1], "steam://open/main") def test_explicit_software_compositing_keeps_gpu_raster(self): - result = self.launch(inherited={"BL_STEAM_SOFT_COMPOSITING": "1"}) + result = self.launch(inherited={"DD_STEAM_SOFT_COMPOSITING": "1"}) self.assertIn("-cef-disable-gpu-compositing", result["args"]) self.assertIn("-cef-force-gpu", result["args"]) self.assertIn("-cef-use-angle=vulkan", result["args"]) self.assertNotIn("-cef-disable-gpu", result["args"]) def test_explicit_gpu_compositing_preserves_vulkan(self): - result = self.launch(inherited={"BL_STEAM_SOFT_COMPOSITING": "0"}) + result = self.launch(inherited={"DD_STEAM_SOFT_COMPOSITING": "0"}) self.assertNotIn("-cef-disable-gpu-compositing", result["args"]) self.assertIn("-cef-force-gpu", result["args"]) self.assertIn("-cef-use-angle=vulkan", result["args"]) def test_powervr_presentation_keeps_its_software_fallback(self): - result = self.launch("1", {"BL_STEAM_SOFT_COMPOSITING": "0"}) + result = self.launch("1", {"DD_STEAM_SOFT_COMPOSITING": "0"}) self.assertIn("-cef-disable-gpu-compositing", result["args"]) self.assertIn("-cef-use-angle=gl", result["args"]) diff --git a/tools/tests/test_steam_shortcut_recovery.py b/tools/tests/test_steam_shortcut_recovery.py index fc196e94f1..3b77c4207f 100644 --- a/tools/tests/test_steam_shortcut_recovery.py +++ b/tools/tests/test_steam_shortcut_recovery.py @@ -43,13 +43,13 @@ class SteamShortcutRecoveryTest(unittest.TestCase): script = "nap() { :; }\nsteam_root=%s\n%s%s\nsteam_launch_game %s\n" % ( self.root / "steam", "steam_client=(%s --exec)\n" % client if client else "", FUNCTIONS.replace("/usr/local/bin/droiddeck-agent", str(self.agent)), GAME) - env = dict(os.environ, HOME=str(self.root), BL_LAUNCH_DIR=str(self.launch), + env = dict(os.environ, HOME=str(self.root), DD_LAUNCH_DIR=str(self.launch), PATH=str(self.bin) + os.pathsep + os.environ["PATH"], STEAM_LOG=str(self.steam_log), AGENT_COUNT=str(self.root / "agent-count"), AGENT_STATES=states, **(extra or {})) result = subprocess.run(["bash", "-c", script], env=env, text=True, capture_output=True, timeout=10) self.assertEqual(0, result.returncode, result.stderr) steam = self.steam_log.read_text().splitlines() if self.steam_log.exists() else [] - restart = self.root / ".bl-restart-game" + restart = self.root / ".dd-restart-game" return steam, restart.read_text().strip() if restart.exists() else None, result.stdout def test_a_shortcut_that_stays_known_launches_once(self): @@ -83,7 +83,7 @@ class SteamShortcutRecoveryTest(unittest.TestCase): def test_steam_is_restarted_only_once_for_the_same_game(self): steam, restart, _ = self.launch_game("4") self.assertEqual(GAME, restart) - (self.root / ".bl-restart-game").unlink() + (self.root / ".dd-restart-game").unlink() self.steam_log.unlink() (self.root / "agent-count").unlink() steam, restart, out = self.launch_game("4") @@ -93,10 +93,10 @@ class SteamShortcutRecoveryTest(unittest.TestCase): def test_a_ready_shortcut_allows_a_later_restart_again(self): self.launch_game("4") - (self.root / ".bl-restart-game").unlink() + (self.root / ".dd-restart-game").unlink() (self.root / "agent-count").unlink() self.launch_game("0") - self.assertFalse((self.root / ".bl-restarted-for").exists()) + self.assertFalse((self.root / ".dd-restarted-for").exists()) def test_a_running_game_is_never_cut_off_by_a_restart(self): steam, restart, _ = self.launch_game("0 4", focusable="769,3703311242") @@ -112,10 +112,10 @@ class SteamShortcutRecoveryTest(unittest.TestCase): def test_the_launcher_without_its_steam_id_still_does_not_count_as_a_running_game(self): (self.launch / "epic-open").write_text("1\n") - launcher = {"BL_EPIC_APP_ID": "2702387189"} + launcher = {"DD_EPIC_APP_ID": "2702387189"} steam, restart, _ = self.launch_game("0 4", focusable="769,2702387189", extra=launcher) self.assertEqual(GAME, restart) - for marker in (".bl-restart-game", ".bl-restarted-for", "agent-count"): + for marker in (".dd-restart-game", ".dd-restarted-for", "agent-count"): (self.root / marker).unlink(missing_ok=True) steam, restart, _ = self.launch_game("4", focusable="769,2702387189,3703311242", extra=launcher) self.assertIsNone(restart) @@ -136,10 +136,10 @@ class SteamShortcutRecoveryTest(unittest.TestCase): "[ -n \"$line\" ] || exit 1\n" "printf '%s\\n' \"$line\"\n") pgrep.chmod(0o755) - script = "steam_root=%s\n%s\ndeclare -A _bl_ran=()\n_bl_exited=\n%s" % ( + script = "steam_root=%s\n%s\ndeclare -A _dd_ran=()\n_dd_exited=\n%s" % ( self.root / "steam", FUNCTIONS.replace("/usr/local/bin/droiddeck-agent", str(self.agent)), "steam_check_exits\n" * beats) - env = dict(os.environ, HOME=str(self.root), BL_LAUNCH_DIR=str(self.launch), + env = dict(os.environ, HOME=str(self.root), DD_LAUNCH_DIR=str(self.launch), PATH=str(self.bin) + os.pathsep + os.environ["PATH"], STEAM_LOG=str(self.steam_log), AGENT_COUNT=str(self.root / "agent-count"), AGENT_STATES=states, PGREP_COUNT=str(self.root / "pgrep-count"), PGREP_RUNS="|".join(listings)) @@ -147,7 +147,7 @@ class SteamShortcutRecoveryTest(unittest.TestCase): self.assertEqual(0, result.returncode, result.stderr) steam = self.steam_log.read_text().splitlines() if self.steam_log.exists() else [] agent = self.root / "agent-count" - return steam, (self.root / ".bl-restart-lost").exists(), int(agent.read_text()) if agent.exists() else 0, result.stdout + return steam, (self.root / ".dd-restart-lost").exists(), int(agent.read_text()) if agent.exists() else 0, result.stdout RUNNING = "41 /root/.local/share/Steam/steamrtarm64/reaper SteamLaunch AppId=3333273269 -- /x/.droiddeck-launch.bat" diff --git a/tools/tests/test_steam_tool_platforms.py b/tools/tests/test_steam_tool_platforms.py index 899b0b07e9..5eddeb3cee 100644 --- a/tools/tests/test_steam_tool_platforms.py +++ b/tools/tests/test_steam_tool_platforms.py @@ -104,7 +104,7 @@ class ToolPlatformsTest(unittest.TestCase): raise StopWatching() namespace = live.LIVE["main"].__globals__ - with mock.patch.dict(namespace, Watcher=capture), mock.patch.dict(os.environ, BL_CDP_PORT="1"), \ + with mock.patch.dict(namespace, Watcher=capture), mock.patch.dict(os.environ, DD_CDP_PORT="1"), \ mock.patch.object(live.LIVE["sys"], "argv", ["compat", str(self.steam)]): with self.assertRaises(StopWatching): live.LIVE["main"]() diff --git a/tools/tests/test_steam_x64_cpu.py b/tools/tests/test_steam_x64_cpu.py index ad8e2dc271..3bbd3cbbc8 100644 --- a/tools/tests/test_steam_x64_cpu.py +++ b/tools/tests/test_steam_x64_cpu.py @@ -29,11 +29,11 @@ class SteamX64CpuTest(unittest.TestCase): start = text.find('x64_arm_webhelper_cpu_supported() {') helper = text[start:text.index('x64_exec() {')] if start >= 0 else '' selection = text.split('x64_exec() {', 1)[1].split(' mkdir -p "$STEAM_X64/logs"', 1)[0] - shell = helper + '\nx64_env() { :; }\nx64_webhelper_gpu() { return 1; }\nselect_helper() {' + selection + '\nprintf "%s|%s\\n" "${BL_X64_ARM_WEBHELPER:-x86}" "${BL_WEBHELPER_ARGS:-}";\n}\nselect_helper\n' + shell = helper + '\nx64_env() { :; }\nx64_webhelper_gpu() { return 1; }\nselect_helper() {' + selection + '\nprintf "%s|%s\\n" "${DD_X64_ARM_WEBHELPER:-x86}" "${DD_WEBHELPER_ARGS:-}";\n}\nselect_helper\n' shell = shell.replace('/proc/cpuinfo', str(cpuinfo)).replace('/usr/local/bin/droiddeck-x64-arm-webhelper', str(shim)) - env = dict(os.environ, STEAM_X64=str(x64), ARM_STEAM=str(arm), X64_CHANNEL='publicbeta', BL_X64_X86_WEBHELPER='1' if forced else '0') - env.pop('BL_X64_ARM_WEBHELPER', None) - env.pop('BL_WEBHELPER_ARGS', None) + env = dict(os.environ, STEAM_X64=str(x64), ARM_STEAM=str(arm), X64_CHANNEL='publicbeta', DD_X64_X86_WEBHELPER='1' if forced else '0') + env.pop('DD_X64_ARM_WEBHELPER', None) + env.pop('DD_WEBHELPER_ARGS', None) result = subprocess.run(['bash', '-eu', '-c', shell], env=env, capture_output=True, text=True) self.assertEqual(result.returncode, 0, result.stderr) return result.stdout.strip(), str(shim) diff --git a/tools/tests/test_steam_x64_signin.py b/tools/tests/test_steam_x64_signin.py index ea761c68c8..3c8eff8c8f 100644 --- a/tools/tests/test_steam_x64_signin.py +++ b/tools/tests/test_steam_x64_signin.py @@ -50,7 +50,7 @@ class X64SignInTest(unittest.TestCase): def sync(self): env = dict(os.environ, HOME=str(self.home), PATH='%s:%s' % (self.bin, os.environ['PATH'])) env.pop('XDG_DATA_HOME', None) - env.pop('BL_X64_HOME', None) + env.pop('DD_X64_HOME', None) return subprocess.run(['bash', str(SCRIPT), '--sync-login'], env=env, capture_output=True, text=True, check=True) def test_a_refused_x64_sign_in_gets_the_token_account_and_auto_login(self): diff --git a/tools/tests/test_steamrt_shim.py b/tools/tests/test_steamrt_shim.py index 05f7345fe1..04f2a7fe06 100644 --- a/tools/tests/test_steamrt_shim.py +++ b/tools/tests/test_steamrt_shim.py @@ -43,11 +43,11 @@ class SteamrtShimTest(unittest.TestCase): self.assertEqual(0, self.sh(self.shim / 'bin/steam-runtime-check-requirements').returncode) self.assertEqual('info\n', self.sh(self.shim / 'bin/steam-runtime-system-info').stdout) self.assertEqual('runtime files', (self.shim / 'files/marker').read_text()) - launched = self.sh(self.shim / 'bin/steam-runtime-launch-client', '--env=BL_SHIM_TEST=yes', - f'--directory={self.root}', '--', 'sh', '-c', 'echo "$BL_SHIM_TEST $(basename "$PWD")"') + launched = self.sh(self.shim / 'bin/steam-runtime-launch-client', '--env=DD_SHIM_TEST=yes', + f'--directory={self.root}', '--', 'sh', '-c', 'echo "$DD_SHIM_TEST $(basename "$PWD")"') self.assertEqual(f'yes {self.root.name}\n', launched.stdout) - launched = self.sh(self.shim / 'bin/steam-runtime-launch-client', '--env', 'BL_SHIM_TEST=split', - '--directory', self.root, '--', 'sh', '-c', 'echo "$BL_SHIM_TEST $(basename "$PWD")"') + launched = self.sh(self.shim / 'bin/steam-runtime-launch-client', '--env', 'DD_SHIM_TEST=split', + '--directory', self.root, '--', 'sh', '-c', 'echo "$DD_SHIM_TEST $(basename "$PWD")"') self.assertEqual(f'split {self.root.name}\n', launched.stdout) missing = self.sh(self.shim / 'bin/steam-runtime-launch-client', '--directory', self.root / 'missing', '--', 'true') @@ -85,7 +85,7 @@ class SteamrtShimTest(unittest.TestCase): def test_both_clients_are_told_they_already_run_inside_the_container(self): guard = SESSION.index('export STEAM_STEAMRT_RECURSION_GUARD=1') - self.assertLess(guard, SESSION.index('"${steam_client[@]}" "${_bl_ui[@]}"')) + self.assertLess(guard, SESSION.index('"${steam_client[@]}" "${_dd_ui[@]}"')) self.assertIn('-u STEAM_STEAMRT_RECURSION_GUARD', SESSION[:guard]) self.assertIn('export STEAM_STEAMRT_RECURSION_GUARD=1', X64) self.assertIn('droiddeck-steamrt-shim "$STEAM_X64/steamrt64" "$X64_HOME/steamrt-shim" || rm -rf "$X64_HOME/steamrt-shim"', X64) diff --git a/tools/tests/test_storage_owner_preload.py b/tools/tests/test_storage_owner_preload.py index 42f66c61eb..83ac7872a8 100644 --- a/tools/tests/test_storage_owner_preload.py +++ b/tools/tests/test_storage_owner_preload.py @@ -85,7 +85,7 @@ class StorageOwnerPreloadTest(unittest.TestCase): build.mkdir() (build / "fake.c").write_text(FAKE) (build / "program.c").write_text(PROGRAM) - cls.preload = build / "libblsession.so" + cls.preload = build / "libddsession.so" cls.fake = build / "fake.so" subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(cls.preload), *map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True) @@ -104,7 +104,7 @@ class StorageOwnerPreloadTest(unittest.TestCase): def owners(self, program, *kinds): env = dict(os.environ, LD_PRELOAD="%s:%s" % (self.preload, self.fake)) - env.pop("BL_STORAGE_DIAGNOSTICS", None) + env.pop("DD_STORAGE_DIAGNOSTICS", None) paths = [str(self.dir / kind / "file") for kind in kinds] result = subprocess.run([str(program)] + paths, env=env, capture_output=True, text=True, check=True) return result.stdout.split() diff --git a/tools/tests/test_storage_preload.py b/tools/tests/test_storage_preload.py index f2408fd1e3..0279551039 100644 --- a/tools/tests/test_storage_preload.py +++ b/tools/tests/test_storage_preload.py @@ -104,7 +104,7 @@ class StoragePreloadTest(unittest.TestCase): def run_program(self, *steps, program=None): env = dict(os.environ, LD_PRELOAD="%s:%s" % (self.storage, self.fake), FAKE_LOG=str(self.log)) - env.pop("BL_STORAGE_DIAGNOSTICS", None) + env.pop("DD_STORAGE_DIAGNOSTICS", None) args = [str(program or self.steam)] for call, path, length in steps: args += [call, str(path), str(length)] diff --git a/tools/tests/test_store_launch.py b/tools/tests/test_store_launch.py index 36a1b7c9a1..84ce7dcfa6 100644 --- a/tools/tests/test_store_launch.py +++ b/tools/tests/test_store_launch.py @@ -1,6 +1,8 @@ import importlib.machinery import importlib.util import json +import shlex +import subprocess import os from pathlib import Path import tempfile @@ -63,13 +65,13 @@ class Detection(unittest.TestCase): folder = game(root, store_id='gog') sc = json.loads((folder / '.droiddeck-store.json').read_text()); sc['cloud'] = False (folder / '.droiddeck-store.json').write_text(json.dumps(sc)) - os.environ['BL_LAUNCH_DIR'] = str(Path(root) / 'session') + os.environ['DD_LAUNCH_DIR'] = str(Path(root) / 'session') try: with patch.object(store, 'ask', return_value={'ready': False, 'reason': 'off'}) as ask: self.assertEqual(0, store.main([str(folder / '.droiddeck-launch.bat')])) self.assertEqual('gog-achievements', ask.call_args.args[1]['op']) finally: - del os.environ['BL_LAUNCH_DIR'] + del os.environ['DD_LAUNCH_DIR'] @@ -104,6 +106,62 @@ class Asking(unittest.TestCase): self.assertIsNone(store.ask(channel, {'op': 'epic-code'}, timeout=0.2)) self.assertEqual([], list((channel / 'req').iterdir())) + def test_a_cloud_download_the_launcher_stops_waiting_for_loses_its_claim(self): + with tempfile.TemporaryDirectory() as root: + channel = Path(root) / 'stores' + taken = [] + handed = threading.Event() + + def app(): + deadline = time.monotonic() + 5 + while not taken and time.monotonic() < deadline: + for request in (channel / 'req').glob('*.json') if (channel / 'req').is_dir() else []: + target = channel / 'resp' / (request.stem + '.taken') + os.rename(request, target) + taken.append(target) + handed.set() + time.sleep(0.02) + + t = threading.Thread(target=app, daemon=True) + t.start() + try: + self.assertIsNone(store.ask(channel, {'op': 'cloud-down'}, timeout=2.0, claim=True)) + finally: + t.join(5) + self.assertTrue(handed.is_set(), 'the app never took the request') + with self.assertRaises(OSError): + os.rename(taken[0], taken[0].with_suffix('.writing')) + + def test_a_claimed_cloud_download_is_waited_for(self): + with tempfile.TemporaryDirectory() as root: + channel = Path(root) / 'stores' + handed = threading.Event() + + def app(): + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + names = list((channel / 'req').glob('*.json')) if (channel / 'req').is_dir() else [] + if names: + handed.set() + writing = channel / 'resp' / (names[0].stem + '.writing') + os.rename(names[0], writing) + time.sleep(0.6) + tmp = channel / 'resp' / (names[0].name + '.tmp') + tmp.write_text(json.dumps({'ok': True, 'result': 'ok'})) + os.rename(tmp, channel / 'resp' / names[0].name) + writing.unlink() + return + time.sleep(0.02) + + t = threading.Thread(target=app, daemon=True) + t.start() + try: + answer = store.ask(channel, {'op': 'cloud-down'}, timeout=0.2, claim=True) + finally: + t.join(5) + self.assertTrue(handed.is_set(), 'the app never took the request') + self.assertEqual({'ok': True, 'result': 'ok'}, answer) + def test_a_stale_code_is_dropped_before_asking(self): with tempfile.TemporaryDirectory() as root: folder = game(root) @@ -161,12 +219,12 @@ class Choices(unittest.TestCase): (compat / 'pfx').mkdir(parents=True) reg = compat / 'pfx/user.reg' reg.write_text('WINE REGISTRY Version 2\n\n[Software\\\\Epic Games\\\\EOS] 1\n"OverlayPath"="Z:\\\\x"\n"Other"="kept"\n') - os.environ['BL_LAUNCH_DIR'] = str(Path(root) / 'session') + os.environ['DD_LAUNCH_DIR'] = str(Path(root) / 'session') os.environ['STEAM_COMPAT_DATA_PATH'] = str(compat) try: self.assertEqual(0, store.main([str(folder / '.droiddeck-launch.bat')])) finally: - del os.environ['BL_LAUNCH_DIR'] + del os.environ['DD_LAUNCH_DIR'] del os.environ['STEAM_COMPAT_DATA_PATH'] self.assertFalse((Path(root) / 'session/stores/req').exists()) self.assertFalse((folder / '.droiddeck-epic-code').exists()) @@ -179,11 +237,11 @@ class Browser(unittest.TestCase): def test_a_web_address_is_handed_to_the_app(self): xdg = load_path(BIN / 'droiddeck-open-url', 'open_url') with tempfile.TemporaryDirectory() as root: - os.environ['BL_LAUNCH_DIR'] = root + os.environ['DD_LAUNCH_DIR'] = root try: self.assertEqual(0, xdg.main(['https://www.epicgames.com/activate'])) finally: - del os.environ['BL_LAUNCH_DIR'] + del os.environ['DD_LAUNCH_DIR'] reqs = list((Path(root) / 'stores/req').glob('*.json')) self.assertEqual(1, len(reqs)) self.assertEqual({'op': 'open-url', 'url': 'https://www.epicgames.com/activate'}, json.loads(reqs[0].read_text())) @@ -208,21 +266,70 @@ class CloudHooks(unittest.TestCase): with tempfile.TemporaryDirectory() as root: folder = game(root, store_id='gog', ident='1207664643') bat = str(folder / '.droiddeck-launch.bat') - os.environ['BL_LAUNCH_DIR'] = str(Path(root) / 'session') + os.environ['DD_LAUNCH_DIR'] = str(Path(root) / 'session') try: original = store.ask asked = [] - store.ask = lambda channel, request, timeout=5.0: asked.append((request, timeout)) or {'ok': True, 'files': 2, 'reason': 'ok'} + store.ask = lambda channel, request, timeout=5.0, claim=False: asked.append((request, timeout)) or {'ok': True, 'files': 2, 'reason': 'ok'} self.assertEqual(store.STORE_GAME, store.main([bat])) self.assertEqual(0, store.main(['--exited', bat])) finally: store.ask = original - del os.environ['BL_LAUNCH_DIR'] + del os.environ['DD_LAUNCH_DIR'] self.assertEqual('gog-achievements', asked[0][0]['op']) self.assertEqual({'op': 'cloud-down', 'store': 'gog', 'id': '1207664643'}, asked[1][0]) self.assertEqual(store.CLOUD_TIMEOUT, asked[1][1]) self.assertEqual('cloud-up', asked[2][0]['op']) + def test_a_cloud_request_that_cannot_be_written_still_starts_the_game_and_uploads_on_exit(self): + with tempfile.TemporaryDirectory() as root: + folder = game(root, store_id='ubisoft', ident='space-1') + sc = json.loads((folder / '.droiddeck-store.json').read_text()); sc['extra'] = {'productId': '109'} + (folder / '.droiddeck-store.json').write_text(json.dumps(sc)) + bat = str(folder / '.droiddeck-launch.bat') + asked = [] + + def ask(channel, request, timeout=5.0, claim=False): + asked.append(request['op']) + if request['op'] in ('cloud-down', 'cloud-up'): + raise PermissionError(13, 'read-only') + return {'ok': True} + + lines = [] + with patch.dict(os.environ, {'DD_LAUNCH_DIR': str(Path(root) / 'session')}), patch.object(store, 'ask', side_effect=ask), patch.object(store, 'prepare_ubisoft', return_value='ready'), patch.object(store, 'create_prefix', return_value='present'), patch.object(store, 'log', side_effect=lines.append): + self.assertEqual(store.STORE_GAME, store.main([bat])) + self.assertEqual(0, store.main(['--exited', bat])) + self.assertEqual(['cloud-down', 'cloud-up'], [op for op in asked if op.startswith('cloud-')]) + self.assertIn('cloud ubisoft space-1 down result=failed reason=PermissionError', lines) + self.assertIn('cloud ubisoft space-1 up not requested (PermissionError)', lines) + def test_an_ea_game_with_cloud_saves_asks_after_its_preparation_and_exit(self): + ident = 'Origin.OFR.50.0002694' + with tempfile.TemporaryDirectory() as root: + folder = game(root, store_id='ea', ident=ident) + bat = str(folder / '.droiddeck-launch.bat') + asked = [] + env = {'DD_LAUNCH_DIR': str(Path(root) / 'session')} + record = lambda channel, request, timeout=5.0, claim=False: asked.append(request) or {'result': 'ok'} + with patch.dict(os.environ, env), \ + patch.object(store, 'prepare_ea', side_effect=lambda *a: asked.append({'op': 'prepared'})), \ + patch.object(store, 'create_prefix', side_effect=AssertionError('EA prepares its own prefix')), \ + patch.object(store, 'ask', side_effect=record): + self.assertEqual(store.STORE_GAME, store.main([bat])) + self.assertEqual(['prepared', 'cloud-down'], [r['op'] for r in asked]) + self.assertEqual({'op': 'cloud-down', 'store': 'ea', 'id': ident}, asked[1]) + self.assertEqual(0, store.main(['--exited', bat])) + self.assertEqual(['ea-exited', 'cloud-up'], [r['op'] for r in asked[2:]]) + self.assertEqual({'op': 'cloud-up', 'store': 'ea', 'id': ident}, asked[3]) + sidecar = json.loads((folder / store.SIDECAR).read_text()) + sidecar['cloud'] = False + (folder / store.SIDECAR).write_text(json.dumps(sidecar)) + asked.clear() + with patch.dict(os.environ, env), patch.object(store, 'prepare_ea'), patch.object(store, 'ask', side_effect=record): + self.assertEqual(store.STORE_GAME, store.main([bat])) + self.assertEqual([], asked) + self.assertEqual(0, store.main(['--exited', bat])) + self.assertEqual(['ea-exited'], [r['op'] for r in asked]) + 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') @@ -240,9 +347,9 @@ class CloudHooks(unittest.TestCase): (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)} + env = {'DD_LAUNCH_DIR': root, 'STEAM_COMPAT_DATA_PATH': str(compat), 'DD_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'}): + patch.object(store, 'ask', side_effect=lambda channel, request, timeout=5.0, claim=False: 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]) @@ -272,11 +379,11 @@ class CloudHooks(unittest.TestCase): def test_both_launchers_wait_for_proton_only_for_a_store_game(self): for sh in (compat.LAUNCHER_SH, compat.EXTRA_WRAPPER_SH): - self.assertIn('bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env', sh) - self.assertNotIn('exec ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env', sh) - self.assertIn('[ $rc -eq 10 ] && BL_STORE_EXIT=1', compat.BL_STORE_SETUP) - self.assertIn('droiddeck-store-launch --exited --code "$rc" "${BL_STORE_ARGS[@]}"', compat.BL_STORE_SETUP) - self.assertIn('exec "$@"', compat.BL_STORE_SETUP) + self.assertIn('dd_run ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env', sh) + self.assertNotIn('exec ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env', sh) + self.assertIn('[ $rc -eq 10 ] && DD_STORE_EXIT=1', compat.DD_STORE_SETUP) + self.assertIn('droiddeck-store-launch --exited --code "$rc" "${DD_STORE_ARGS[@]}"', compat.DD_STORE_SETUP) + self.assertIn('exec "$@"', compat.DD_STORE_SETUP) BNET_EXE = '/root/.local/share/Steam/steamapps/compatdata/2596113170/pfx/drive_c/Program Files (x86)/Battle.net/Battle.net.exe' @@ -292,30 +399,57 @@ class BattleNet(unittest.TestCase): other = BNET_EXE.replace('2596113170', '123') self.assertIsNone(store.battlenet([other, '--exec=launch Fen'], env={})) self.assertIsNone(store.battlenet(['/x/Diablo IV/Diablo IV.exe'], env={})) - self.assertIsNone(store.battlenet([BNET_EXE, '--exec=launch Fen'], env={'BL_BATTLENET': '1'})) + self.assertIsNone(store.battlenet([BNET_EXE, '--exec=launch Fen'], env={'DD_BATTLENET': '1'})) self.assertEqual([store.BATTLENET, 'open'], store.battlenet([BNET_EXE, '--exec=launch Fen;rm'], env={})) def test_the_launch_runs_there_and_the_wrapper_ends_with_it(self): with patch.dict(os.environ, {}, clear=False), patch.object(store.subprocess, 'call', return_value=0) as call: - os.environ.pop('BL_BATTLENET', None) + os.environ.pop('DD_BATTLENET', None) self.assertEqual(store.RAN, store.main([BNET_EXE, '--exec=launch Pro'])) call.assert_called_once_with([store.BATTLENET, 'launch', 'Pro']) with patch.dict(os.environ, {}, clear=False), patch.object(store.subprocess, 'call', return_value=1): - os.environ.pop('BL_BATTLENET', None) + os.environ.pop('DD_BATTLENET', None) self.assertEqual(store.RAN_FAILED, store.main([BNET_EXE, '--exec=launch Pro'])) - self.assertIn('[ $rc -eq 11 ] && exit 0', compat.BL_STORE_SETUP) - self.assertIn('[ $rc -eq 12 ] && exit 1', compat.BL_STORE_SETUP) - self.assertLess(compat.BL_STORE_SETUP.index('droiddeck-store-launch "$@"'), compat.BL_STORE_SETUP.index('[ $rc -eq 11 ] && exit 0')) + self.assertIn('[ $rc -eq 11 ] && exit 0', compat.DD_STORE_SETUP) + self.assertIn('[ $rc -eq 12 ] && exit 1', compat.DD_STORE_SETUP) + self.assertLess(compat.DD_STORE_SETUP.index('droiddeck-store-launch "$@"'), compat.DD_STORE_SETUP.index('[ $rc -eq 11 ] && exit 0')) class Launchers(unittest.TestCase): def test_both_proton_launchers_ask_before_proton_starts(self): sh = compat.LAUNCHER_SH - self.assertIn('bl_store_launch() {', sh) - self.assertLess(sh.index('bl_store_launch "$@"'), sh.index('droiddeck-game-env "$depot/proton"')) - self.assertIn('bl_store_launch "$@"', compat.EXTRA_WRAPPER_SH) - self.assertIn('bl_store_launch() {', compat.BL_STORE_SETUP) - self.assertIn('waitforexitandrun', compat.BL_STORE_SETUP) + self.assertIn('dd_store_launch() {', sh) + self.assertLess(sh.index('dd_store_launch "$@"'), sh.index('droiddeck-game-env "$depot/proton"')) + self.assertIn('dd_store_launch "$@"', compat.EXTRA_WRAPPER_SH) + self.assertIn('dd_store_launch() {', compat.DD_STORE_SETUP) + self.assertIn('waitforexitandrun', compat.DD_STORE_SETUP) + + def run_store_game(self, game, store_exit=True): + with tempfile.TemporaryDirectory() as root: + hook = Path(root) / 'hook' + record = Path(root) / 'exited' + hook.write_text('#!/bin/sh\necho "$@" > "%s"\n' % record) + hook.chmod(0o755) + setup = compat.DD_STORE_SETUP.replace('/usr/local/bin/droiddeck-store-launch --exited', str(hook) + ' --exited') + script = setup + '\nDD_STORE_ARGS=(game.bat)\n%sdd_run sh -c %s\nexit 99\n' % ( + 'DD_STORE_EXIT=1\n' if store_exit else '', shlex.quote(game)) + done = subprocess.run(['bash', '-c', script], start_new_session=True, timeout=20) + return done.returncode, record.read_text().split() if record.exists() else None + + def test_a_store_game_ended_by_a_group_signal_still_reports_its_exit(self): + for signal_name, code in (('INT', '130'), ('TERM', '143'), ('HUP', '129')): + rc, hook = self.run_store_game('kill -%s 0; sleep 5' % signal_name) + self.assertEqual(['--exited', '--code', code, 'game.bat'], hook, signal_name) + self.assertEqual(int(code), rc, signal_name) + + def test_a_store_game_that_exits_by_itself_reports_its_code_once(self): + self.assertEqual((3, ['--exited', '--code', '3', 'game.bat']), self.run_store_game('exit 3')) + + def test_other_games_still_replace_the_wrapper_without_the_exit_hook(self): + self.assertEqual((4, None), self.run_store_game('exit 4', store_exit=False)) + rc, hook = self.run_store_game('kill -INT 0; sleep 5', store_exit=False) + self.assertIsNone(hook) + self.assertEqual(-2, rc) if __name__ == '__main__': @@ -329,7 +463,7 @@ class GogAchievements(unittest.TestCase): sidecar = json.loads((folder / store.SIDECAR).read_text()) sidecar['cloud'] = False (folder / store.SIDECAR).write_text(json.dumps(sidecar)) - with patch.dict(os.environ, {'BL_LAUNCH_DIR': root, 'STEAM_COMPAT_DATA_PATH': root + '/compat', 'BL_STORE_PROTON': '/chosen/proton'}), patch.object(store, 'ask', return_value={'ready': True}) as ask, patch.object(store, 'provision_galaxy', return_value='ready') as provision: + with patch.dict(os.environ, {'DD_LAUNCH_DIR': root, 'STEAM_COMPAT_DATA_PATH': root + '/compat', 'DD_STORE_PROTON': '/chosen/proton'}), patch.object(store, 'ask', return_value={'ready': True}) as ask, patch.object(store, 'provision_galaxy', return_value='ready') as provision: self.assertEqual(0, store.main([str(folder / store.LAUNCHER)])) ask.assert_called_once() provision.assert_called_once_with(root + '/compat', '/chosen/proton') @@ -790,7 +924,7 @@ class GogRegistry(unittest.TestCase): def test_every_gog_launch_brings_the_registry_in(self): with tempfile.TemporaryDirectory() as root: folder = game(root, store_id='gog') - with patch.dict(os.environ, {'BL_LAUNCH_DIR': root, 'STEAM_COMPAT_DATA_PATH': root + '/compat/', 'BL_STORE_PROTON': '/chosen/proton'}), \ + with patch.dict(os.environ, {'DD_LAUNCH_DIR': root, 'STEAM_COMPAT_DATA_PATH': root + '/compat/', 'DD_STORE_PROTON': '/chosen/proton'}), \ patch.object(store, 'prepare_gog', return_value=False), patch.object(store, 'ask', return_value=None), \ patch.object(store, 'apply_gog_registry', return_value='ready') as apply, \ patch.object(store, 'gog_support_data', return_value='ready') as support: diff --git a/tools/tests/test_store_launch_ea.py b/tools/tests/test_store_launch_ea.py index 9096d2d3c8..1dd912f0ab 100644 --- a/tools/tests/test_store_launch_ea.py +++ b/tools/tests/test_store_launch_ea.py @@ -147,12 +147,12 @@ class EaHook(unittest.TestCase): folder.mkdir() asked = {} - def fake_ask(channel, request, timeout=5.0): + def fake_ask(channel, request, timeout=5.0, claim=False): asked.update(request) return {'ok': True, 'lsx': True, 'license': 'ok v4', 'licenses': [{'path': 'ProgramData/L/x.dlf', 'data': base64.b64encode(b'z').decode()}]} with patch.object(store, 'ask', fake_ask), patch.object(store, 'ea_registry', lambda *a, **k: 'ready'), \ - patch.object(store, 'ea_touchup', lambda *a, **k: 'none'), patch.dict('os.environ', {'BL_STORE_PROTON': ''}): + patch.object(store, 'ea_touchup', lambda *a, **k: 'none'), patch.dict('os.environ', {'DD_STORE_PROTON': ''}): store.prepare_ea(folder, {'id': 'Origin.OFR.1'}, str(compat), str(Path(tmp) / 'launch')) self.assertEqual(asked['op'], 'ea-prepare') self.assertEqual(asked['hardware'], probe) diff --git a/tools/tests/test_store_launch_rockstar.py b/tools/tests/test_store_launch_rockstar.py index fe7d808f2a..277d2a9f2b 100644 --- a/tools/tests/test_store_launch_rockstar.py +++ b/tools/tests/test_store_launch_rockstar.py @@ -6,7 +6,7 @@ import time import unittest from unittest.mock import patch -from test_store_launch import store +from test_store_launch import game, store class RockstarLaunch(unittest.TestCase): @@ -217,6 +217,70 @@ class RockstarLaunch(unittest.TestCase): self.assertEqual([], requests) self.assertFalse(config.exists()) + def test_each_launch_starts_a_fresh_launcher_log(self): + with tempfile.TemporaryDirectory() as root: + stale = [] + + def ask(channel, request, timeout): + stale.append((config.parent / 'launcher.log').exists()) + return answer + + folder, sidecar, prefix, service, answer = self.setup_game(root) + config = prefix / 'pfx' / store.ROCKSTAR_FOLDER / 'launch.json' + config.parent.mkdir(parents=True) + (config.parent / 'launcher.log').write_bytes(b'x' * 70000) + with patch.object(store, 'ROCKSTAR_SERVICE', service), patch.object(store, 'rockstar_registry', return_value=True): + result = store.prepare_rockstar(folder, sidecar, str(prefix), str(Path(root) / 'channel'), ask_app=ask) + self.assertEqual('ready', result) + self.assertEqual([False], stale) + + def exit_game(self, root, store_id, log_text=None, link=None): + folder = game(root, store_id=store_id, ident='gta5') + prefix = Path(root) / 'prefix' + target = prefix / 'pfx' / store.ROCKSTAR_FOLDER + target.mkdir(parents=True) + if log_text is not None: + (target / 'launcher.log').write_text(log_text) + if link is not None: + (target / 'launcher.log').symlink_to(link) + lines = [] + with patch.dict(os.environ, {'DD_LAUNCH_DIR': str(Path(root) / 'session'), 'STEAM_COMPAT_DATA_PATH': str(prefix)}), \ + patch.object(store, 'ask', return_value={'ok': True}), patch.object(store, 'log', lines.append): + self.assertEqual(0, store.main(['--exited', str(folder / '.droiddeck-launch.bat')])) + return lines, target / 'launcher.log' + + def test_launcher_log_reaches_the_session_log_when_the_game_exits(self): + with tempfile.TemporaryDirectory() as root: + text = 'launch handoff accepted\r\nlauncher pipes created, identity: none\r\n\r\ngame exited with code 0\r\n' + lines, path = self.exit_game(root, 'rockstar', log_text=text) + self.assertEqual(['rockstar launcher: launch handoff accepted', + 'rockstar launcher: launcher pipes created, identity: none', + 'rockstar launcher: game exited with code 0'], lines) + self.assertFalse(path.exists()) + + def test_launcher_log_relay_does_not_follow_links(self): + with tempfile.TemporaryDirectory() as root: + outside = Path(root) / 'outside.txt' + outside.write_text('private\n') + lines, path = self.exit_game(root, 'rockstar', link=outside) + self.assertEqual([], lines) + self.assertTrue(path.is_symlink()) + self.assertEqual('private\n', outside.read_text()) + + def test_other_stores_do_not_relay_the_launcher_log(self): + with tempfile.TemporaryDirectory() as root: + lines, path = self.exit_game(root, 'gog', log_text='launch handoff accepted\n') + self.assertFalse(any(line.startswith('rockstar launcher:') for line in lines)) + self.assertTrue(path.exists()) + + def test_relay_is_bounded(self): + with tempfile.TemporaryDirectory() as root: + prefix = Path(root) / 'prefix' + target = prefix / 'pfx' / store.ROCKSTAR_FOLDER + target.mkdir(parents=True) + (target / 'launcher.log').write_text('a' * 10 + '\n' + 'b' * 100 + '\n') + self.assertEqual(['a' * 10, 'b' * 5], store.rockstar_launcher_log(str(prefix), limit=16)) + def test_writes_both_registry_views_and_escapes_values(self): with tempfile.TemporaryDirectory() as root: folder, _, prefix, _, _ = self.setup_game(root) diff --git a/tools/tests/test_subsurface_release.py b/tools/tests/test_subsurface_release.py new file mode 100644 index 0000000000..2254eb1a71 --- /dev/null +++ b/tools/tests/test_subsurface_release.py @@ -0,0 +1,96 @@ +import os +from pathlib import Path +import re +import shutil +import subprocess +import tempfile +import unittest + +REPO = Path(__file__).resolve().parents[2] +SOURCE = REPO / 'app/src/main/cpp/waylandcomp/src/compositor.c' +FUNCTIONS = ( + 'pending_release_free', 'pending_releases_forget_surface', 'pending_releases_cancel', + 'pending_releases_apply', 'sync_holder', 'pending_releases_rehold', 'on_pending_release_buffer_destroyed', + 'arm_release_timer', 'release_due_buffers', 'release_buffer', 'buffer_shown_elsewhere', + 'drop_dmabuf', +) + + +def extract_function(source, name): + match = re.search(r'^static [^\n;]*?\b' + re.escape(name) + r'\([^;{]*\) \{$', source, re.MULTILINE) + if match is None: + raise AssertionError(f'Missing compositor function: {name}') + cursor, depth = match.end(), 1 + while depth: + depth += (source[cursor] == '{') - (source[cursor] == '}') + cursor += 1 + return match.group(0)[:-2] + ';', source[match.start():cursor] + + +def function_body(source, name): + return extract_function(source, name)[1] + + +class SubsurfaceReleaseTest(unittest.TestCase): + @classmethod + def setUpClass(cls): + compiler = shutil.which(os.environ.get('CC', 'cc')) + if compiler is None: + raise unittest.SkipTest('A host C compiler is required') + cls.source = SOURCE.read_text() + start = cls.source.index('struct pending_release {') + end = cls.source.index('\n};\n', start) + 4 + parts = [extract_function(cls.source, name) for name in FUNCTIONS] + code = cls.source[start:end] + '\n'.join(p[0] for p in parts) + '\n' + '\n'.join(p[1] for p in parts) + '\n' + cls.temp = tempfile.TemporaryDirectory(prefix='droiddeck-subsurface-release-') + cls.addClassCleanup(cls.temp.cleanup) + folder = Path(cls.temp.name) + (folder / 'release.inc').write_text(code) + cls.binary = folder / 'release-test' + subprocess.run([compiler, '-std=c11', '-Wall', '-Werror', '-Wno-unused-function', + '-I', str(folder), '-I', str(REPO / 'app/src/main/cpp/waylandcomp/prebuilt/include'), + str(REPO / 'tools/tests/subsurface_release_harness.c'), '-o', str(cls.binary)], + check=True, capture_output=True, text=True) + + def check_case(self, case): + result = subprocess.run([str(self.binary), case], capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_buffer_moved_to_another_plane_is_released_once_after_the_parent_commit(self): + self.check_case('moved') + + def test_buffer_attached_again_before_its_paced_release_is_released_once(self): + self.check_case('reattached') + + def test_buffers_cycled_faster_than_their_paced_releases_are_released_once_each(self): + self.check_case('cycled') + + def test_unpaced_sync_child_waits_for_the_parent_commit(self): + self.check_case('unpaced') + + def test_desynchronized_child_is_released_without_a_parent_commit(self): + self.check_case('desync') + + def test_toplevel_release_pacing_is_unchanged(self): + self.check_case('toplevel') + + def test_held_release_is_sent_when_the_parent_is_destroyed(self): + self.check_case('destroyed') + + def test_desynchronized_parent_releases_its_synchronized_child(self): + self.check_case('nested') + + def test_set_desync_releases_what_the_old_parent_held(self): + self.check_case('set-desync') + + def test_compositor_attach_and_commit_use_the_release_hold(self): + self.assertIn('pending_releases_cancel(buffer);', function_body(self.source, 'take_dmabuf')) + commit = function_body(self.source, 'surface_commit') + self.assertIn('pending_releases_apply(s);', commit) + self.assertLess(commit.index('take_dmabuf(s, db, buffer);'), commit.index('pending_releases_apply(s);')) + self.assertLess(commit.index('buf_trace_attach(buffer);'), commit.index('if (s->role == ROLE_CURSOR)')) + self.assertIn('pending_releases_rehold(s);', function_body(self.source, 'subsurface_set_desync')) + + +if __name__ == '__main__': + unittest.main() diff --git a/tools/tests/test_sysv_preload.py b/tools/tests/test_sysv_preload.py index fc8b8cead8..f39a9daccd 100644 --- a/tools/tests/test_sysv_preload.py +++ b/tools/tests/test_sysv_preload.py @@ -16,7 +16,7 @@ class SysvPreloadTest(unittest.TestCase): binary = str(Path(folder) / 'test-sysv') subprocess.run(['gcc', '-Wall', '-Wextra', '-O2', '-pthread', '-o', binary, str(Path(__file__).resolve().parent / 'sysv_otime_harness.c'), str(PRELOAD / 'sysv.c')], check=True) - env = dict(os.environ, BL_SYSV_DIR=folder) + env = dict(os.environ, DD_SYSV_DIR=folder) result = subprocess.run([binary], capture_output=True, text=True, timeout=10, env=env) self.assertIn('PASS: sysv otime', result.stdout, result.stdout + result.stderr) @@ -25,7 +25,7 @@ class SysvPreloadTest(unittest.TestCase): binary = str(Path(folder) / 'test-sysv-msg') subprocess.run(['gcc', '-Wall', '-Wextra', '-O2', '-pthread', '-o', binary, str(Path(__file__).resolve().parent / 'sysv_msg_harness.c'), str(PRELOAD / 'sysv.c')], check=True) - env = dict(os.environ, BL_SYSV_DIR=folder) + env = dict(os.environ, DD_SYSV_DIR=folder) result = subprocess.run([binary], capture_output=True, text=True, timeout=20, env=env) self.assertIn('PASS: sysv msg', result.stdout, result.stdout + result.stderr) diff --git a/tools/tests/test_tracer_preload.py b/tools/tests/test_tracer_preload.py index 90a4442248..82ae9072ec 100644 --- a/tools/tests/test_tracer_preload.py +++ b/tools/tests/test_tracer_preload.py @@ -122,12 +122,12 @@ class TracerPreloadTest(unittest.TestCase): (tmp / "ntdll.c").write_text(NTDLL) (tmp / "prog.c").write_text(PROGRAM) sources = sorted(str(p) for p in PRELOAD.glob("*.c")) - subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(tmp / "libblsession.so"), *sources, "-ldl"], + subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(tmp / "libddsession.so"), *sources, "-ldl"], check=True) subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(tmp / "ntdll.so"), str(tmp / "ntdll.c")], check=True) subprocess.run(["cc", "-O1", "-o", str(tmp / "prog"), str(tmp / "prog.c"), str(tmp / "ntdll.so"), "-Wl,-rpath," + str(tmp)], check=True) - env = dict(os.environ, LD_PRELOAD=str(tmp / "libblsession.so")) + env = dict(os.environ, LD_PRELOAD=str(tmp / "libddsession.so")) out = subprocess.run([str(tmp / "prog")], env=env, capture_output=True, text=True, timeout=60) if out.returncode != 0: raise AssertionError(out.stdout + out.stderr) diff --git a/tools/tests/test_usr2_preload.py b/tools/tests/test_usr2_preload.py index 4a180df393..796c2390c9 100644 --- a/tools/tests/test_usr2_preload.py +++ b/tools/tests/test_usr2_preload.py @@ -251,13 +251,13 @@ class Usr2PreloadTest(unittest.TestCase): (tmp / "ntdll.c").write_text(NTDLL) (tmp / "prog.c").write_text(PROGRAM) sources = sorted(str(p) for p in PRELOAD.glob("*.c")) - subprocess.run([cls.cc, "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(tmp / "libblsession.so"), + subprocess.run([cls.cc, "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(tmp / "libddsession.so"), *sources, "-ldl"], check=True) subprocess.run([cls.cc, "-shared", "-fPIC", "-O2", "-o", str(tmp / "ntdll.so"), str(tmp / "ntdll.c")], check=True) subprocess.run([cls.cc, "-O1", "-U_FORTIFY_SOURCE", "-pthread", "-o", str(tmp / "prog"), str(tmp / "prog.c"), str(tmp / "ntdll.so"), "-Wl,-rpath," + str(tmp)], check=True) cls.program = tmp / "prog" - cls.preload = tmp / "libblsession.so" + cls.preload = tmp / "libddsession.so" @classmethod def tearDownClass(cls): diff --git a/tools/tests/test_vdec_emulator.py b/tools/tests/test_vdec_emulator.py index 8f9fbd6445..bf16a3fc39 100644 --- a/tools/tests/test_vdec_emulator.py +++ b/tools/tests/test_vdec_emulator.py @@ -28,9 +28,9 @@ DRIVER = r''' #include #include -int bl_vdec_open(const char *path, int flags); -int bl_vdec_ioctl(int fd, unsigned long req, void *arg, int *rc); -void bl_vdec_closed(int fd); +int dd_vdec_open(const char *path, int flags); +int dd_vdec_ioctl(int fd, unsigned long req, void *arg, int *rc); +void dd_vdec_closed(int fd); void *SDL_LoadObject(const char *name); void *SDL_LoadFunction(void *handle, const char *name); @@ -74,12 +74,12 @@ int ioctl(int fd, unsigned long req, ...) { static int vfd; static int call(unsigned long req, void *arg) { int rc; - if (!bl_vdec_ioctl(vfd, req, arg, &rc)) return -100; + if (!dd_vdec_ioctl(vfd, req, arg, &rc)) return -100; return rc < 0 ? -errno : 0; } int main(void) { - if (bl_vdec_open("/dev/video0", O_RDWR) != -2) return 2; + if (dd_vdec_open("/dev/video0", O_RDWR) != -2) return 2; void *drm = SDL_LoadObject("libdrm.so.2"); if (!drm) return 3; int (*devices)(uint32_t, struct drm_device **, int) = SDL_LoadFunction(drm, "drmGetDevices2"); @@ -90,7 +90,7 @@ int main(void) { int card = open(dev[0]->nodes[0], O_RDWR | O_CLOEXEC); if (card < 0) return 6; - vfd = bl_vdec_open("/dev/video-dec0", O_RDWR); + vfd = dd_vdec_open("/dev/video-dec0", O_RDWR); if (vfd < 0) return 7; struct v4l2_capability cap; if (call(VIDIOC_QUERYCAP, &cap) || (cap.capabilities & 0x04004000) != 0x04004000) return 8; @@ -184,7 +184,7 @@ int main(void) { if (call(VIDIOC_DQBUF, &db)) return 37; unsigned char *m = mmap(NULL, size, PROT_READ, MAP_SHARED, bh.fd, 0); printf("%ld %u %c%c\n", (long)db.timestamp.tv_usec, db.index, m[0], m[(size_t)1920 * 1088]); - bl_vdec_closed(vfd); + dd_vdec_closed(vfd); return 0; } ''' @@ -249,13 +249,13 @@ class VdecEmulatorTest(unittest.TestCase): driver = tmp / 'driver.c' driver.write_text(DRIVER) binary = tmp / 'streaming_client' - subprocess.run(['cc', '-O1', '-pthread', '-DBL_VDEC_ANY_ARCH', '-o', str(binary), str(driver), str(VDEC), + subprocess.run(['cc', '-O1', '-pthread', '-DDD_VDEC_ANY_ARCH', '-o', str(binary), str(driver), str(VDEC), str(VENC), '-ldl'], check=True) sock = tmp / 'venc.sock' server = FakeDecoder(str(sock)) self.addCleanup(server.listener.close) server.start() - done = subprocess.run([str(binary)], env=dict(os.environ, BL_VENC_SOCKET=str(sock)), + done = subprocess.run([str(binary)], env=dict(os.environ, DD_VENC_SOCKET=str(sock)), capture_output=True, text=True, timeout=20) self.assertEqual(done.returncode, 0, done.stdout + done.stderr) self.assertEqual(done.stdout.split('\n')[:6], @@ -272,7 +272,7 @@ class VdecEmulatorTest(unittest.TestCase): 'void *SDL_LoadObject(const char *);\n' 'int main(void) { return SDL_LoadObject("libdrm.so.2") != 0; }\n') binary = tmp / 'steam' - subprocess.run(['cc', '-O1', '-pthread', '-DBL_VDEC_ANY_ARCH', '-o', str(binary), str(tmp / 'main.c'), + subprocess.run(['cc', '-O1', '-pthread', '-DDD_VDEC_ANY_ARCH', '-o', str(binary), str(tmp / 'main.c'), str(VDEC), str(VENC), '-ldl'], check=True) done = subprocess.run([str(binary)], capture_output=True, text=True, timeout=20) self.assertEqual(done.returncode, 0, done.stderr) diff --git a/tools/tests/test_venc_emulator.py b/tools/tests/test_venc_emulator.py index 416f6b61b0..c601a3b2ee 100644 --- a/tools/tests/test_venc_emulator.py +++ b/tools/tests/test_venc_emulator.py @@ -21,22 +21,22 @@ DRIVER = r''' #include #include -int bl_venc_open(const char *path, int flags); -int bl_venc_ioctl(int fd, unsigned long req, void *arg, int *rc); -int bl_venc_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off, +int dd_venc_open(const char *path, int flags); +int dd_venc_ioctl(int fd, unsigned long req, void *arg, int *rc); +int dd_venc_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off, void *(*real)(void *, size_t, int, int, int, off_t), void **out); -void bl_venc_closed(int fd); +void dd_venc_closed(int fd); static int fd; static int call(unsigned long req, void *arg) { int rc; - if (!bl_venc_ioctl(fd, req, arg, &rc)) return -100; + if (!dd_venc_ioctl(fd, req, arg, &rc)) return -100; return rc < 0 ? -errno : 0; } int main(void) { - if (bl_venc_open("/dev/video0", 0) != -2) return 2; - fd = bl_venc_open("/dev/video-enc0", 0); + if (dd_venc_open("/dev/video0", 0) != -2) return 2; + fd = dd_venc_open("/dev/video-enc0", 0); if (fd < 0) return 3; struct v4l2_capability cap; if (call(VIDIOC_QUERYCAP, &cap) || !(cap.device_caps & V4L2_CAP_VIDEO_M2M_MPLANE)) return 4; @@ -58,7 +58,7 @@ int main(void) { struct v4l2_buffer b = { .index = i, .type = types[t], .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &p }; if (call(VIDIOC_QUERYBUF, &b)) return 9; void *m; - if (!bl_venc_mmap(NULL, p.length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, p.m.mem_offset, mmap, &m) || + if (!dd_venc_mmap(NULL, p.length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, p.m.mem_offset, mmap, &m) || m == MAP_FAILED) return 10; maps[t][i] = m; if (t == 1 && call(VIDIOC_QBUF, &b)) return 11; @@ -84,7 +84,7 @@ int main(void) { if (call(VIDIOC_DQBUF, &b)) return 16; if (call(VIDIOC_QBUF, &cb)) return 17; } - bl_venc_closed(fd); + dd_venc_closed(fd); return 0; } ''' @@ -95,8 +95,8 @@ TOUCH_DRIVER = r''' #include #include -int bl_venc_open(const char *path, int flags); -void bl_venc_closed(int fd); +int dd_venc_open(const char *path, int flags); +void dd_venc_closed(int fd); int XTestFakeMotionEvent(void *dpy, int screen, int x, int y, unsigned long delay); int XTestFakeButtonEvent(void *dpy, unsigned int button, int press, unsigned long delay); int XDisplayWidth(void *dpy, int screen) { return 1281; } @@ -105,7 +105,7 @@ int XDisplayHeight(void *dpy, int screen) { return 721; } int main(void) { XTestFakeButtonEvent(NULL, 1, 1, 0); XTestFakeButtonEvent(NULL, 1, 0, 0); - int fd = bl_venc_open("/dev/video-enc0", 0); + int fd = dd_venc_open("/dev/video-enc0", 0); if (fd < 0) return 3; XTestFakeMotionEvent(NULL, 0, 1280, 360, 0); XTestFakeButtonEvent(NULL, 1, 1, 0); @@ -116,11 +116,11 @@ int main(void) { snprintf(marker, sizeof marker, "%s/droiddeck-remote-play", getenv("XDG_RUNTIME_DIR")); if (access(marker, F_OK) != 0) return 4; pid_t child = fork(); - if (child == 0) { bl_venc_closed(fd); _exit(access(marker, F_OK) == 0 ? 0 : 1); } + if (child == 0) { dd_venc_closed(fd); _exit(access(marker, F_OK) == 0 ? 0 : 1); } int status; waitpid(child, &status, 0); if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) return 5; - bl_venc_closed(fd); + dd_venc_closed(fd); if (access(marker, F_OK) == 0) return 6; XTestFakeButtonEvent(NULL, 1, 1, 0); usleep(200000); @@ -191,7 +191,7 @@ class VencEmulatorTest(unittest.TestCase): server = FakeEncoder(str(sock)) self.addCleanup(server.listener.close) server.start() - done = subprocess.run([str(binary)], env=dict(os.environ, BL_VENC_SOCKET=str(sock)), + done = subprocess.run([str(binary)], env=dict(os.environ, DD_VENC_SOCKET=str(sock)), capture_output=True, text=True, timeout=20) self.assertEqual(done.returncode, 0, done.stdout + done.stderr) self.assertEqual(done.stdout.split('\n')[:3], @@ -217,7 +217,7 @@ class VencEmulatorTest(unittest.TestCase): server = FakeEncoder(str(sock)) self.addCleanup(server.listener.close) server.start() - done = subprocess.run([str(binary)], env=dict(os.environ, BL_VENC_SOCKET=str(sock), XDG_RUNTIME_DIR=str(tmp)), + done = subprocess.run([str(binary)], env=dict(os.environ, DD_VENC_SOCKET=str(sock), XDG_RUNTIME_DIR=str(tmp)), capture_output=True, text=True, timeout=20) self.assertEqual(done.returncode, 0, done.stderr) self.assertEqual(server.touches, [(0, 65535, 32767), (1, 32767, 0), (2, 32767, 0)]) diff --git a/tools/tests/test_vk_dmabuf_quarantine.py b/tools/tests/test_vk_dmabuf_quarantine.py index aeafada3ef..5bd0f1b016 100644 --- a/tools/tests/test_vk_dmabuf_quarantine.py +++ b/tools/tests/test_vk_dmabuf_quarantine.py @@ -51,6 +51,10 @@ class VkDmabufQuarantineTest(unittest.TestCase): # One surface per buffer in these scenarios: never shown elsewhere. helpers += ['static int buffer_shown_elsewhere(struct wl_resource *b, const struct surface *e) ' '{ (void)b; (void)e; return 0; }'] + if re.search(r'^static void release_due_buffers\(void\) \{', comp, re.M): + helpers += ['static void release_due_buffers(void);', 'static void arm_release_timer(void);', + function(comp, 'sync_holder')] + names.insert(names.index('on_release_timer'), 'release_due_buffers') if re.search(r'\bvolatile int g_release_unpaced;', comp): # Releases stay paced in these scenarios (fps limit -1 sends them at once). helpers.insert(0, 'static int g_release_unpaced;') diff --git a/tools/tests/test_vrclient_loader.py b/tools/tests/test_vrclient_loader.py index d3b41e5636..805ad6d3a8 100644 --- a/tools/tests/test_vrclient_loader.py +++ b/tools/tests/test_vrclient_loader.py @@ -31,9 +31,9 @@ int probe(void) { #define _GNU_SOURCE #include #include -int bl_fsync_syscall(long n, const long *a, long *r) { (void)n; (void)a; (void)r; return 0; } -int bl_writewatch_syscall(long n, const long *a, long (*real)(long, ...), long *r) { (void)n; (void)a; (void)real; (void)r; return 0; } -int bl_clock_syscall(long n, const long *a, long (*real)(long, ...), long *r) { (void)n; (void)a; (void)real; (void)r; return 0; } +int dd_fsync_syscall(long n, const long *a, long *r) { (void)n; (void)a; (void)r; return 0; } +int dd_writewatch_syscall(long n, const long *a, long (*real)(long, ...), long *r) { (void)n; (void)a; (void)real; (void)r; return 0; } +int dd_clock_syscall(long n, const long *a, long (*real)(long, ...), long *r) { (void)n; (void)a; (void)real; (void)r; return 0; } #include """ + '"' + robust.as_posix() + '"' + r""" int main(int argc, char **argv) { assert(argc == 3); diff --git a/tools/tests/test_wayland_clock_domain.py b/tools/tests/test_wayland_clock_domain.py index a805ff9c09..265b0b17b2 100644 --- a/tools/tests/test_wayland_clock_domain.py +++ b/tools/tests/test_wayland_clock_domain.py @@ -58,7 +58,7 @@ class WaylandClockDomainTest(unittest.TestCase): #include #include "clock_domain.h" -struct pending_release { void *buffer; int64_t at_ns; struct pending_release *next; }; +struct pending_release { void *buffer; int64_t at_ns; struct pending_release *next; void *held_by; }; static struct pending_release *g_pending_releases; static int g_release_timer_fd; #define wl_list_for_each(pr, list, link) for (pr = *(list); pr; pr = pr->next) @@ -79,8 +79,8 @@ int main(int argc, char **argv) { struct timespec started, ended; clock_gettime(CLOCK_MONOTONIC, &started); int64_t start = now_ns(); - struct pending_release blocked = {(void *)1, start + 1000000LL, NULL}; - struct pending_release release = {NULL, start + 60000000LL, &blocked}; + struct pending_release blocked = {(void *)1, start + 1000000LL, NULL, NULL}; + struct pending_release release = {NULL, start + 60000000LL, &blocked, NULL}; g_pending_releases = &release; arm_release_timer(); int64_t next_offset = offsets[i] + 10000000000LL; diff --git a/tools/tests/test_webhelper_preload.py b/tools/tests/test_webhelper_preload.py index a7476945ce..3847e9988f 100644 --- a/tools/tests/test_webhelper_preload.py +++ b/tools/tests/test_webhelper_preload.py @@ -10,7 +10,7 @@ PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload" PROGRAM = r""" #include #include -char *const *bl_webhelper_argv(const char *path, char *const argv[], char *const envp[]); +char *const *dd_webhelper_argv(const char *path, char *const argv[], char *const envp[]); int main(int argc, char **argv) { const char *mode = getenv("TEST_NODE_MODE_CHILD"); static char node[64]; @@ -18,7 +18,7 @@ int main(int argc, char **argv) { char *node_env[] = {node, NULL}; char *plain_env[] = {"PATH=/usr/bin", NULL}; char *const *envp = mode ? node_env : plain_env; - char *const *out = bl_webhelper_argv(argv[1], argv + 1, (char *const *)envp); + char *const *out = dd_webhelper_argv(argv[1], argv + 1, (char *const *)envp); for (int i = 0; out[i]; i++) printf("%s\n", out[i]); return 0; } @@ -43,10 +43,10 @@ class WebhelperPreloadTest(unittest.TestCase): shutil.rmtree(cls.tmp, ignore_errors=True) def argv(self, *args, spec=None, node_child=False, parent_node=False): - env = {k: v for k, v in os.environ.items() if k != "BL_WEBHELPER_ARGS"} + env = {k: v for k, v in os.environ.items() if k != "DD_WEBHELPER_ARGS"} env.pop("ELECTRON_RUN_AS_NODE", None) if spec is not None: - env["BL_WEBHELPER_ARGS"] = spec + env["DD_WEBHELPER_ARGS"] = spec if node_child is not False: env["TEST_NODE_MODE_CHILD"] = "1" if node_child is True else node_child else: diff --git a/tools/tests/test_winebus_rumble_preload.py b/tools/tests/test_winebus_rumble_preload.py index abd60c2743..a18f541e7a 100644 --- a/tools/tests/test_winebus_rumble_preload.py +++ b/tools/tests/test_winebus_rumble_preload.py @@ -67,7 +67,7 @@ class WinebusRumblePreloadTest(unittest.TestCase): build.mkdir() for name, text in (("shim.c", SHIM), ("upload.c", UPLOAD), ("program.c", PROGRAM)): (build / name).write_text(text) - cls.lib = cls.dir / "libblsession.so" + cls.lib = cls.dir / "libddsession.so" subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(cls.lib), *map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True) cls.shim = cls.dir / "libshim.so" diff --git a/tools/tests/test_writable_preload.py b/tools/tests/test_writable_preload.py index dd18f63650..8a38926d7b 100644 --- a/tools/tests/test_writable_preload.py +++ b/tools/tests/test_writable_preload.py @@ -49,7 +49,7 @@ class WritablePreloadTest(unittest.TestCase): build = cls.dir / "build" build.mkdir() (build / "program.c").write_text(PROGRAM) - cls.preload = build / "libblsession.so" + cls.preload = build / "libddsession.so" subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(cls.preload), *map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True) cls.editor = build / "kate" diff --git a/tools/tests/test_xbox_launch.py b/tools/tests/test_xbox_launch.py index 0e3fd2eca7..be2851fd31 100644 --- a/tools/tests/test_xbox_launch.py +++ b/tools/tests/test_xbox_launch.py @@ -57,7 +57,7 @@ class XboxLaunchTest(unittest.TestCase): patch.dict(xbox['launch'].__globals__, wine=unittest.mock.Mock(return_value=7)): launch = xbox['launch'] self.assertEqual(launch(['/proton', 'waitforexitandrun', '/encrypted/Game.exe'], - {'BL_LAUNCH_DIR': '/launch', 'DROIDDECK_XBOX_CREDENTIAL_SOCKET': 'stale', + {'DD_LAUNCH_DIR': '/launch', 'DROIDDECK_XBOX_CREDENTIAL_SOCKET': 'stale', 'DROIDDECK_XBOX_CREDENTIAL_PORT': '4100', 'DROIDDECK_XBOX_CREDENTIAL_KEY': 'stale-key'}), 7) wine = launch.__globals__['wine'] self.assertEqual(wine.call_args.args[0], ['/private/Game.exe']) @@ -80,7 +80,7 @@ class XboxLaunchTest(unittest.TestCase): with patch('runpy.run_path', return_value={'find_store_game': lambda argv: (root, {'store': 'xbox', 'id': 'GAME'}), 'ask': ask}), \ patch.dict(xbox['launch'].__globals__, RUNTIME=root, bridge=unittest.mock.Mock(side_effect=OSError('bind failed'))): with self.assertRaises(OSError): - xbox['launch'](['/proton', 'waitforexitandrun', '/Game.exe'], {'BL_LAUNCH_DIR': '/launch'}) + xbox['launch'](['/proton', 'waitforexitandrun', '/Game.exe'], {'DD_LAUNCH_DIR': '/launch'}) self.assertEqual(ask.call_args.args[1], {'op': 'xbox-released', 'lease': 'lease-1'}) def test_bridge_authenticates_before_forwarding(self): @@ -178,6 +178,101 @@ class XboxLaunchTest(unittest.TestCase): self.assertEqual(sorted(p.name for p in devices.iterdir()), ['v:', 'w:', 'x:']) self.assertEqual(xbox['view_drive'](root / 'pfx', '/games/Game.exe'), ('/games/Game.exe', None)) + def test_package_install_actions_run_once_and_stay_inside_the_game(self): + with tempfile.TemporaryDirectory() as root: + game, prefix = Path(root) / 'game', Path(root) / 'pfx' + (game / 'Installers').mkdir(parents=True) + (game / 'Installers' / 'GameInputRedist.msi').write_bytes(b'msi') + (game / 'Emu.exe').write_bytes(b'exe') + (Path(root) / 'outside.msi').write_bytes(b'msi') + (game / 'MicrosoftGame.config').write_text( + 'Installers' + '' + '' + '') + with patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child: + xbox['run_install_actions']('/selected/proton', prefix, str(game / 'Emu.exe'), {'A': '1'}) + xbox['run_install_actions']('/selected/proton', prefix, str(game / 'Emu.exe'), {'A': '1'}) + self.assertEqual(child.call_count, 1) + command = child.call_args.args[0] + self.assertEqual(command[:4], ['/selected/proton', 'run', 'msiexec', '/i']) + self.assertTrue(command[4].startswith('Z:') and command[4].endswith('GameInputRedist.msi')) + self.assertEqual(command[5:], ['/quiet']) + + def test_a_failed_install_action_is_retried_on_the_next_launch(self): + with tempfile.TemporaryDirectory() as root: + game, prefix = Path(root) / 'game', Path(root) / 'pfx' + game.mkdir() + (game / 'setup.exe').write_bytes(b'exe') + (game / 'MicrosoftGame.config').write_text( + '' + '') + with patch('subprocess.run', return_value=subprocess.CompletedProcess([], 1)) as child: + xbox['run_install_actions']('/p', prefix, str(game / 'setup.exe'), {}) + xbox['run_install_actions']('/p', prefix, str(game / 'setup.exe'), {}) + self.assertEqual(child.call_count, 2) + self.assertEqual(child.call_args.args[0][:2], ['/p', 'run']) + + def test_install_action_arguments_follow_windows_command_line_rules(self): + parse = xbox['windows_arguments'] + self.assertEqual(parse('/quiet /log "C:\\ProgramData\\Game Setup\\install.log"'), + ['/quiet', '/log', 'C:\\ProgramData\\Game Setup\\install.log']) + self.assertEqual(parse('a\\\\b "x\\"y" "\\\\" "" c""d "e""f"'), ['a\\\\b', 'x"y', '\\', '', 'cd', 'e"f']) + self.assertEqual(parse(' '), []) + with tempfile.TemporaryDirectory() as root: + game, prefix = Path(root) / 'game', Path(root) / 'pfx' + game.mkdir() + (game / 'setup.msi').write_bytes(b'msi') + (game / 'MicrosoftGame.config').write_text( + '' + '') + with patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child: + xbox['run_install_actions']('/p', prefix, str(game / 'setup.msi'), {}) + self.assertEqual(child.call_args.args[0][5:], ['/quiet', '/log', 'C:\\ProgramData\\Game Setup\\install.log']) + + def test_actions_whose_names_differ_only_in_punctuation_each_run(self): + with tempfile.TemporaryDirectory() as root: + game, prefix = Path(root) / 'game', Path(root) / 'pfx' + game.mkdir() + (game / 'setup.exe').write_bytes(b'exe') + (game / 'MicrosoftGame.config').write_text( + '' + '' + '' + '') + with patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child: + xbox['run_install_actions']('/p', prefix, str(game / 'setup.exe'), {}) + xbox['run_install_actions']('/p', prefix, str(game / 'setup.exe'), {}) + self.assertEqual([call.args[0][-1] for call in child.call_args_list], ['/a', '/b']) + + def test_an_install_action_error_never_stops_the_launch(self): + with tempfile.TemporaryDirectory() as root: + game, prefix = Path(root) / 'game', Path(root) / 'pfx' + game.mkdir() + (game / 'first.exe').write_bytes(b'exe') + (game / 'second.exe').write_bytes(b'exe') + (game / 'MicrosoftGame.config').write_text( + '' + '' + '') + real_open = Path.open + def unreadable(path, *args, **kwargs): + if path.name == 'first.exe': + raise PermissionError('denied') + return real_open(path, *args, **kwargs) + with patch.object(Path, 'open', unreadable), \ + patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child: + xbox['run_install_actions']('/p', prefix, str(game / 'first.exe'), {}) + self.assertEqual(child.call_count, 1) + self.assertTrue(child.call_args.args[0][2].endswith('second.exe')) + with patch('subprocess.run', side_effect=OSError('no proton')): + xbox['run_install_actions']('/p', prefix, str(game / 'first.exe'), {}) + with patch.object(Path, 'touch', side_effect=OSError('read-only')), \ + patch('subprocess.run', return_value=subprocess.CompletedProcess([], 0)) as child: + xbox['run_install_actions']('/p', prefix / 'other', str(game / 'first.exe'), {}) + self.assertEqual(child.call_count, 2) + def test_missing_runtime_classes_are_registered_once(self): with tempfile.TemporaryDirectory() as root: prefix = Path(root) @@ -391,6 +486,6 @@ class PlayFabProxyTest(unittest.TestCase): patch.dict(xbox['launch'].__globals__, RUNTIME=root, bridge=lambda path: (1, 'key', lambda: None), wine=wine, stage_playfab_proxy=stage): self.assertEqual(xbox['launch'](['/proton', 'waitforexitandrun', '/Game.exe'], - {'BL_LAUNCH_DIR': '/launch', 'WINEDLLOVERRIDES': 'd3d11=n'}), 0) + {'DD_LAUNCH_DIR': '/launch', 'WINEDLLOVERRIDES': 'd3d11=n'}), 0) self.assertEqual(wine.call_args.args[1]['WINEDLLOVERRIDES'], 'd3d11=n') self.assertEqual(staged, [root]) diff --git a/tools/tests/test_zram_preload.py b/tools/tests/test_zram_preload.py index 88d5c73020..8e4af1aa26 100644 --- a/tools/tests/test_zram_preload.py +++ b/tools/tests/test_zram_preload.py @@ -1,5 +1,6 @@ import os from pathlib import Path +import signal import shutil import subprocess import tempfile @@ -9,6 +10,7 @@ PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload" PROGRAM = r""" #define _GNU_SOURCE +#include #include #include #include @@ -17,12 +19,36 @@ PROGRAM = r""" #include #include #include +#include +#include +#include #include static const char *ctl; static size_t size, page; static volatile int stop; static unsigned char *shared; +static volatile sig_atomic_t urg_tid; +static volatile sig_atomic_t usr_tid; +static int urg_count, usr_count; +static int worker_tid; +static int worker_delivery; + +_Static_assert(__atomic_always_lock_free(sizeof(int), 0), "signal state must be lock-free"); + +static void signal_tid(int sig) { + sig_atomic_t tid = (sig_atomic_t)syscall(SYS_gettid); + if (tid == __atomic_load_n(&worker_tid, __ATOMIC_RELAXED)) + __atomic_store_n(&worker_delivery, 1, __ATOMIC_RELAXED); + if (sig == SIGURG) { + __atomic_store_n(&urg_tid, tid, __ATOMIC_RELAXED); + __atomic_add_fetch(&urg_count, 1, __ATOMIC_RELEASE); + } + if (sig == SIGUSR1) { + __atomic_store_n(&usr_tid, tid, __ATOMIC_RELAXED); + __atomic_add_fetch(&usr_count, 1, __ATOMIC_RELEASE); + } +} static long status(const char *key) { FILE *f = fopen("/proc/self/status", "r"); @@ -34,13 +60,37 @@ static long status(const char *key) { return v; } -static void request(char mode) { +static void send_request(char mode) { int fd = open(ctl, O_WRONLY | O_TRUNC); if (fd < 0 || write(fd, &mode, 1) != 1) exit(3); close(fd); kill(getpid(), SIGURG); } +static void wait_ack(void) { + char ack[256]; + snprintf(ack, sizeof(ack), "%s.ack.%d", ctl, getpid()); + for (int i = 0; i < 1200; i++) { + FILE *f = fopen(ack, "r"); + int done = 0; + if (f) { + done = fgetc(f) == '1'; + fclose(f); + } + if (done) return; + usleep(10000); + } + exit(5); +} + +static void request(char mode) { + send_request(mode); + if (mode == '1') { + wait_ack(); + } + usleep(1000000); +} + static uint64_t sum(const unsigned char *p, size_t n) { uint64_t s = 0; for (size_t i = 0; i < n; i += 64) s = s * 31 + p[i]; @@ -77,6 +127,106 @@ int main(int argc, char **argv) { sigaction(SIGURG, NULL, &sa); printf("handler %d\n", (sa.sa_flags & SA_SIGINFO) ? 1 : 0); if (argc > 4) { + if (!strcmp(argv[4], "signals")) { + struct sigaction signal_action; + memset(&signal_action, 0, sizeof(signal_action)); + signal_action.sa_handler = signal_tid; + sigemptyset(&signal_action.sa_mask); + sigaction(SIGURG, &signal_action, NULL); + sigaction(SIGUSR1, &signal_action, NULL); + printf("ready %d\n", getpid()); + fflush(stdout); + int id; + if (scanf("%d", &id) != 1) return 10; + __atomic_store_n(&worker_tid, id, __ATOMIC_RELAXED); + printf("armed 1\n"); + fflush(stdout); + for (int round = 1; round <= 100; round++) { + int i; + for (i = 0; i < 5000 && + (__atomic_load_n(&urg_count, __ATOMIC_ACQUIRE) < round || + __atomic_load_n(&usr_count, __ATOMIC_ACQUIRE) < round); i++) usleep(1000); + if (i == 5000) return 11; + printf("received %d\n", round); + fflush(stdout); + } + stop = 1; + for (int i = 0; i < 2; i++) pthread_join(t[i], NULL); + printf("urg %d\n", __atomic_load_n(&urg_tid, __ATOMIC_RELAXED)); + printf("usr %d\n", __atomic_load_n(&usr_tid, __ATOMIC_RELAXED)); + printf("worker %d\n", __atomic_load_n(&worker_delivery, __ATOMIC_RELAXED)); + return 0; + } else if (!strcmp(argv[4], "fork")) { + pid_t child = fork(); + if (child < 0) exit(6); + if (child == 0) { + request('0'); + request('1'); + _exit(0); + } + int status_code; + waitpid(child, &status_code, 0); + printf("childack %d\n", WIFEXITED(status_code) && WEXITSTATUS(status_code) == 0); + } else if (!strcmp(argv[4], "burst")) { + send_request('0'); + usleep(10000); + send_request('1'); + wait_ack(); + printf("burstack 1\n"); + } else if (!strcmp(argv[4], "timed-inline") || !strcmp(argv[4], "timed-inline-single")) { + pid_t child = fork(); + if (child < 0) exit(8); + if (child == 0) { + if (!strcmp(argv[4], "timed-inline-single")) { + if (munmap(data, size) || munmap(shared, size)) _exit(12); + data = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + shared = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (data == MAP_FAILED || shared == MAP_FAILED) _exit(13); + for (size_t i = 0; i < size; i++) data[i] = (unsigned char)(i * 7 + i / 4096); + memset(shared, 0, size); + } + struct timespec start, end; + int fd = open(ctl, O_WRONLY | O_TRUNC); + if (fd < 0 || write(fd, "1", 1) != 1) _exit(9); + close(fd); + clock_gettime(CLOCK_MONOTONIC, &start); + int requests = !strcmp(argv[4], "timed-inline-single") ? 1 : 64; + for (int i = 0; i < requests; i++) { + send_request('1'); + } + clock_gettime(CLOCK_MONOTONIC, &end); + long elapsed = (end.tv_sec - start.tv_sec) * 1000L + + (end.tv_nsec - start.tv_nsec) / 1000000L; + printf("inline %ld\n", elapsed); + printf("inline_swap %ld\n", status("VmSwap:")); + fflush(stdout); + _exit(0); + } + int status_code; + if (waitpid(child, &status_code, 0) != child || !WIFEXITED(status_code) || WEXITSTATUS(status_code)) exit(14); + } else if (!strcmp(argv[4], "timed")) { + struct timespec previous, current, deadline; + long max_gap = 0; + int fd = open(ctl, O_WRONLY | O_TRUNC); + if (fd < 0 || write(fd, "1", 1) != 1) exit(7); + close(fd); + clock_gettime(CLOCK_MONOTONIC, &previous); + kill(getpid(), SIGURG); + deadline = previous; + deadline.tv_sec += 1; + for (;;) { + clock_gettime(CLOCK_MONOTONIC, ¤t); + long gap = (current.tv_sec - previous.tv_sec) * 1000L + + (current.tv_nsec - previous.tv_nsec) / 1000000L; + if (gap > max_gap) max_gap = gap; + previous = current; + if (current.tv_sec > deadline.tv_sec || + (current.tv_sec == deadline.tv_sec && current.tv_nsec >= deadline.tv_nsec)) break; + } + wait_ack(); + printf("gap %ld\n", max_gap); + printf("out %ld\n", status("VmSwap:")); + } else { unsigned char *ro = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); memset(ro, 0x5a, size); mprotect(ro, size, PROT_READ); @@ -84,6 +234,7 @@ int main(int argc, char **argv) { printf("elsewhere %ld\n", status("VmSwap:")); request('0'); printf("back %ld\n", status("VmSwap:")); + } } for (int c = 0; c < cycles; c++) { request('1'); @@ -115,7 +266,7 @@ class ZramPreloadTest(unittest.TestCase): build = cls.dir / "build" build.mkdir() (build / "program.c").write_text(PROGRAM) - cls.lib = build / "libblsession.so" + cls.lib = build / "libddsession.so" subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-DZR_CTL=\"%s\"" % cls.ctl, "-o", str(cls.lib), *map(str, sorted(PRELOAD.glob("*.c"))), "-ldl"], check=True) cls.steam = cls.dir / "steam" @@ -173,6 +324,74 @@ class ZramPreloadTest(unittest.TestCase): self.assertEqual([1], out["intact"]) self.assertEqual(6, len(out["out"])) + def test_process_signals_do_not_reach_zram_worker(self): + environment = dict(os.environ, LD_PRELOAD=str(self.lib)) + process = subprocess.Popen([str(self.steam), str(self.ctl), "1", "0", "signals"], + env=environment, stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) + try: + process.stdout.readline() + ready = process.stdout.readline().split() + self.assertEqual("ready", ready[0]) + worker = None + task_dir = Path("/proc") / ready[1] / "task" + for task in task_dir.iterdir(): + if (task / "comm").read_text().strip() == "zr-worker": + worker = int(task.name) + break + self.assertIsNotNone(worker) + self.assertEqual(os.sched_getscheduler(process.pid), os.sched_getscheduler(worker)) + process.stdin.write(f"{worker}\n") + process.stdin.flush() + self.assertEqual("armed 1", process.stdout.readline().strip()) + for _ in range(100): + os.kill(process.pid, signal.SIGURG) + os.kill(process.pid, signal.SIGUSR1) + self.assertEqual(f"received {_ + 1}", process.stdout.readline().strip()) + output, _ = process.communicate(timeout=10) + values = dict(line.split() for line in output.splitlines()) + self.assertNotEqual(0, int(values["urg"])) + self.assertNotEqual(0, int(values["usr"])) + self.assertEqual(0, int(values["worker"])) + self.assertNotEqual(worker, int(values["urg"])) + self.assertNotEqual(worker, int(values["usr"])) + finally: + if process.poll() is None: + process.kill() + process.wait() + + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") + def test_signal_does_not_stall_the_main_thread(self): + out = self.run_program(None, 256, 0, "timed") + self.assertLess(out["gap"][0], 250) + self.assertGreater(out["out"][0], 32 * 1024) + + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") + def test_inline_pageout_exceeds_async_timing_tolerance(self): + out = self.run_program(None, 256, 0, "timed-inline") + if out["inline"][0] <= 250: + self.skipTest("inline page-out finished under the 250 ms timing threshold on this machine") + self.assertGreater(out["inline"][0], 250) + + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") + def test_single_request_timing_control(self): + asynchronous = self.run_program(None, 48, 0, "timed") + self.assertGreater(asynchronous["out"][0], 32 * 1024) + inline = self.run_program(None, 48, 0, "timed-inline-single") + self.assertGreater(inline["inline_swap"][0], 32 * 1024) + if inline["inline"][0] <= 250: + self.skipTest("single inline request did not establish the 250 ms timing threshold") + self.assertGreater(inline["inline"][0], 250) + self.assertLess(asynchronous["gap"][0], 250) + + @unittest.skipUnless(swap_total_kb() > 256 * 1024, "needs swap") + def test_forked_child_still_acknowledges_pageout(self): + out = self.run_program(None, 48, 0, "fork") + self.assertEqual([1], out["childack"]) + + def test_worker_acknowledges_back_to_back_requests(self): + out = self.run_program(None, 48, 0, "burst") + self.assertEqual([1], out["burstack"]) + if __name__ == "__main__": unittest.main() diff --git a/tools/tests/vk_dmabuf_quarantine_test.c b/tools/tests/vk_dmabuf_quarantine_test.c index cbcf724b19..f9dcf85bf0 100644 --- a/tools/tests/vk_dmabuf_quarantine_test.c +++ b/tools/tests/vk_dmabuf_quarantine_test.c @@ -25,7 +25,11 @@ struct dmabuf_buffer { struct vkp_image *img; void *ahb_state; }; +enum surface_role { ROLE_NONE, ROLE_TOPLEVEL, ROLE_SUBSURFACE }; struct surface { + enum surface_role role; + struct surface *parent; + int sub_desync; struct wl_resource *dmabuf; struct dmabuf_buffer *dmabuf_buf; struct wl_listener dmabuf_destroy; @@ -113,7 +117,7 @@ static void test_queue(int mixed, int client_gone) { g_release_timer_fd = 123; g_refresh_ns = 100000; drop_dmabuf(&s, 1); assert(s.releases_pending == 1 && !r.releases); assert(last_timer.it_value.tv_sec || last_timer.it_value.tv_nsec); - if (mixed) { init_resource(&shm, NULL); release_buffer(&s, &shm, now_ns()); } + if (mixed) { init_resource(&shm, NULL); droiddeck_release_buffer(&s, &shm, 1, now_ns()); } pending_releases_forget_surface(&s); g_dev_state = -3; fire_timer(); diff --git a/tools/tests/vk_terminal_callers_test.c b/tools/tests/vk_terminal_callers_test.c index c5857a7710..2398608bd2 100644 --- a/tools/tests/vk_terminal_callers_test.c +++ b/tools/tests/vk_terminal_callers_test.c @@ -72,6 +72,7 @@ PFN_vkGetInstanceProcAddr vk_loader_gipa(void) { return NULL; } void vkp_effects_bind_device(VkDevice d, VkPhysicalDevice p, const VkPhysicalDeviceMemoryProperties *m) {} int vkp_effects_active(void) { return 0; } int vkp_effects_upscaling(void) { return 0; } +int vkp_effects_sharpening(void) { return 0; } int vkp_effects_postprocessing(void) { return 0; } VkFilter vkp_effects_blit_filter(void) { return VK_FILTER_NEAREST; } void vkp_effects_set_formats(VkFormat a, VkFormat b) {} diff --git a/tools/ubisoft-launcher/src/bridge.rs b/tools/ubisoft-launcher/src/bridge.rs new file mode 100644 index 0000000000..361acb743f --- /dev/null +++ b/tools/ubisoft-launcher/src/bridge.rs @@ -0,0 +1,161 @@ +//! The file bridge DroidDeck answers Denuvo activations through. + +use std::path::Path; +use std::sync::{Condvar, Mutex}; +use std::thread; +use std::time::Duration; + +pub const INVALIDATE: &str = "denuvo-invalidate"; + +pub fn publish_invalidation(dir: &Path, account: &str, tries: u32, pause: Duration) -> bool { + let marker = dir.join(INVALIDATE); + let part = dir.join(format!("{INVALIDATE}.upc")); + for attempt in 0..tries { + if marker.is_file() { + return true; + } + if std::fs::write(&part, account.as_bytes()).is_ok() && std::fs::rename(&part, &marker).is_ok() { + return true; + } + let _ = std::fs::remove_file(&part); + if attempt + 1 < tries { + thread::sleep(pause); + } + } + false +} + +#[derive(Default)] +pub struct Generation { + state: Mutex<(u64, usize)>, + idle: Condvar, +} + +impl Generation { + pub fn current(&self) -> u64 { + self.state.lock().unwrap().0 + } + + pub fn invalidate(&self, wait: Duration, acknowledge: impl FnOnce() -> T) -> T { + let mut state = self.state.lock().unwrap(); + state.0 += 1; + let _ = self.idle.wait_timeout_while(state, wait, |s| s.1 > 0).unwrap(); + acknowledge() + } + + pub fn serve(&self, seen: u64, reply: impl FnOnce() -> T) -> Option { + { + let mut state = self.state.lock().unwrap(); + if state.0 != seen { + return None; + } + state.1 += 1; + } + let out = reply(); + self.state.lock().unwrap().1 -= 1; + self.idle.notify_all(); + Some(out) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Arc; + use std::time::Instant; + + fn dir(name: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("upc-bridge-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + #[test] + fn an_invalidation_is_published_as_the_marker() { + let d = dir("publish"); + assert!(publish_invalidation(&d, "user-a", 1, Duration::ZERO)); + assert_eq!(std::fs::read(d.join(INVALIDATE)).unwrap(), b"user-a"); + assert!(!d.join("denuvo-invalidate.upc").exists()); + } + + #[test] + fn a_marker_naming_its_account_is_kept() { + let d = dir("named"); + std::fs::write(d.join(INVALIDATE), b"user-a").unwrap(); + assert!(publish_invalidation(&d, "user-b", 1, Duration::ZERO)); + assert_eq!(std::fs::read(d.join(INVALIDATE)).unwrap(), b"user-a"); + } + + #[test] + fn a_marker_that_cannot_be_written_is_reported_after_every_try() { + let d = dir("missing").join("gone"); + let started = Instant::now(); + assert!(!publish_invalidation(&d, "user-a", 3, Duration::from_millis(20))); + assert!(started.elapsed() >= Duration::from_millis(40)); + assert!(!d.join(INVALIDATE).exists()); + } + + #[test] + fn a_marker_written_while_retrying_counts() { + let d = dir("late").join("bridge"); + let later = d.clone(); + let maker = thread::spawn(move || { + thread::sleep(Duration::from_millis(30)); + std::fs::create_dir_all(later).unwrap(); + }); + assert!(publish_invalidation(&d, "user-a", 50, Duration::from_millis(10))); + maker.join().unwrap(); + assert!(d.join(INVALIDATE).is_file()); + } + + #[test] + fn a_kept_token_asked_for_before_an_invalidation_is_not_served_after_it() { + let g = Generation::default(); + let seen = g.current(); + assert_eq!(g.invalidate(Duration::from_secs(1), || "acknowledged"), "acknowledged"); + assert_eq!(g.serve(seen, || "token"), None); + assert_eq!(g.serve(g.current(), || "token"), Some("token")); + } + + #[test] + fn a_reply_being_served_holds_the_acknowledgement_back() { + let g = Arc::new(Generation::default()); + let order = Arc::new(Mutex::new(Vec::new())); + let seen = g.current(); + let (g2, o2) = (g.clone(), order.clone()); + let served = g.serve(seen, || { + let ack = thread::spawn(move || g2.invalidate(Duration::from_secs(5), || o2.lock().unwrap().push("acknowledged"))); + thread::sleep(Duration::from_millis(50)); + order.lock().unwrap().push("token"); + ack + }); + served.unwrap().join().unwrap(); + assert_eq!(*order.lock().unwrap(), vec!["token", "acknowledged"]); + } + + #[test] + fn a_reply_that_stalls_never_blocks_other_connections_or_the_acknowledgement_for_long() { + let g = Arc::new(Generation::default()); + let seen = g.current(); + let (entered, inside) = std::sync::mpsc::channel(); + let (release, held) = std::sync::mpsc::channel::<()>(); + let stalled = { + let g = g.clone(); + thread::spawn(move || g.serve(seen, move || { + entered.send(()).unwrap(); + let _ = held.recv(); + })) + }; + inside.recv().unwrap(); + let started = Instant::now(); + assert_eq!(g.current(), seen); + assert_eq!(g.serve(seen, || "other"), Some("other")); + assert!(started.elapsed() < Duration::from_millis(200)); + assert_eq!(g.invalidate(Duration::from_millis(100), || "acknowledged"), "acknowledged"); + assert!(started.elapsed() < Duration::from_millis(450)); + assert_eq!(g.serve(seen, || "late"), None); + release.send(()).unwrap(); + assert!(stalled.join().unwrap().is_some()); + } +} diff --git a/tools/ubisoft-launcher/src/launcher.rs b/tools/ubisoft-launcher/src/launcher.rs index 343708dba0..d993ebe9f9 100644 --- a/tools/ubisoft-launcher/src/launcher.rs +++ b/tools/ubisoft-launcher/src/launcher.rs @@ -338,6 +338,8 @@ pub fn announced(body: &[u8]) -> Option<(Option, Option)> { pub enum AuxReq<'a> { Init(u64), Activate(u64, &'a [u8]), + Invalidate(u64), + BurnTicket(u64), Other(u64), } @@ -348,8 +350,14 @@ pub fn aux_request(body: &[u8]) -> AuxReq<'_> { let Some(activate) = pb::sub(&f, 3) else { return if pb::has(&f, 2) { AuxReq::Init(rid) } else { AuxReq::Other(rid) }; }; - let token = pb::fields(activate) - .and_then(|a| pb::sub(&a, 2).and_then(pb::fields)) + let Some(a) = pb::fields(activate) else { return AuxReq::Other(rid) }; + if pb::has(&a, 1) && !pb::has(&a, 2) { + return AuxReq::Invalidate(rid); + } + if pb::has(&a, 3) && !pb::has(&a, 2) { + return AuxReq::BurnTicket(rid); + } + let token = pb::sub(&a, 2).and_then(pb::fields) .and_then(|t| t.iter().find_map(|(n, v)| match v { Value::Bytes(b) if *n == 2 => Some(*b), _ => None })); match token { Some(t) => AuxReq::Activate(rid, t), @@ -365,6 +373,15 @@ pub fn aux_init(rid: u64, pid: u32) -> Vec { Msg::new().uint(1, rid).msg(2, init).0 } +pub fn aux_invalidated(rid: u64) -> Vec { + Msg::new().uint(1, rid).msg(3, Msg::new()).0 +} + +pub fn aux_no_burn_ticket(rid: u64) -> Vec { + let answer = Msg::new().uint(2, 3).uint(3, 3); + Msg::new().uint(1, rid).msg(3, Msg::new().msg(3, answer)).0 +} + pub fn aux_token(rid: u64, game_token: &[u8]) -> Vec { let answer = Msg::new().uint(2, 1).uint(3, 0).bytes(4, game_token).bytes(5, b""); Msg::new().uint(1, rid).msg(3, Msg::new().msg(2, answer)).0 @@ -476,6 +493,30 @@ mod tests { assert!(matches!(aux_request(&Msg::new().uint(1, 1).msg(2, Msg::new().uint(1, 109)).0), AuxReq::Init(1))); } + #[test] + fn an_invalidation_is_recognised_and_acknowledged_with_an_empty_activation() { + let req = Msg::new().uint(1, 5).msg(3, Msg::new().msg(1, Msg::new())); + assert!(matches!(aux_request(&req.0), AuxReq::Invalidate(5))); + let rsp = pb::fields(&aux_invalidated(5)).unwrap().into_iter().map(|(n, _)| n).collect::>(); + assert_eq!(rsp, vec![1, 3]); + assert_eq!(pb::sub(&pb::fields(&aux_invalidated(5)).unwrap(), 3), Some(&b""[..])); + let burn = Msg::new().uint(1, 6).msg(3, Msg::new().msg(3, Msg::new().bytes(2, b"t"))); + assert!(matches!(aux_request(&burn.0), AuxReq::BurnTicket(6))); + } + + #[test] + fn a_burn_ticket_request_is_answered_with_a_connection_error() { + let rsp = aux_no_burn_ticket(6); + let top = pb::fields(&rsp).unwrap(); + assert_eq!(pb::num(&top, 1), Some(6)); + let activate = pb::fields(pb::sub(&top, 3).unwrap()).unwrap(); + assert!(!pb::has(&activate, 2)); + let burn = pb::fields(pb::sub(&activate, 3).unwrap()).unwrap(); + assert_eq!(pb::num(&burn, 2), Some(3)); + assert_eq!(pb::num(&burn, 3), Some(3)); + assert!(!pb::has(&burn, 4)); + } + #[test] fn orbit_init_answers_with_the_save_folder() { let (rsp, what) = config().orbit(&[0x08, 0x01, 0x62, 0x03, 0x08, 0xcd, 0x01]).unwrap(); diff --git a/tools/ubisoft-launcher/src/main.rs b/tools/ubisoft-launcher/src/main.rs index 0b7126a919..e4442d7033 100644 --- a/tools/ubisoft-launcher/src/main.rs +++ b/tools/ubisoft-launcher/src/main.rs @@ -4,6 +4,7 @@ #![cfg_attr(windows, windows_subsystem = "windows")] +mod bridge; mod launcher; mod pb; #[cfg(windows)] @@ -22,12 +23,13 @@ fn main() { #[cfg(windows)] mod service { + use crate::bridge::{self, Generation}; use crate::launcher::{self, AuxReq, Config, SessionReq}; use crate::win::{self, Handle}; use std::fs::OpenOptions; use std::io::Write; - use std::path::PathBuf; - use std::sync::atomic::{AtomicU32, Ordering}; + use std::path::{Path, PathBuf}; + use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; use std::sync::{Arc, Mutex}; use std::thread; use std::time::{Duration, Instant}; @@ -36,6 +38,9 @@ mod service { const ANNOUNCE_WAIT: Duration = Duration::from_secs(120); const RESTART_WAIT: Duration = Duration::from_secs(15); const DENUVO_WAIT: Duration = Duration::from_secs(90); + const SERVE_WAIT: Duration = Duration::from_secs(10); + const MARKER_TRIES: u32 = 25; + const MARKER_PAUSE: Duration = Duration::from_millis(200); struct State { cfg: Config, @@ -43,6 +48,8 @@ mod service { log: Mutex>, event: Handle, game: AtomicU32, + stale_token: AtomicBool, + generation: Generation, started: Instant, } @@ -175,7 +182,8 @@ mod service { state.say("session: closed"); } - fn denuvo(state: &State, rid: u64, challenge: &[u8]) -> Option> { + /// The game token for an activation, with the invalidation count it was asked under when it may be a kept one. + fn denuvo(state: &State, rid: u64, challenge: &[u8], fresh: bool) -> Option<(Vec, Option)> { if state.cfg.bridge.is_empty() { return None; } @@ -185,12 +193,20 @@ mod service { let _ = std::fs::remove_file(&rsp); let part = dir.join(format!("denuvo-{rid}.req.part")); std::fs::write(&part, challenge).ok()?; - std::fs::rename(&part, dir.join(format!("denuvo-{rid}.req"))).ok()?; + let seen = state.generation.current(); + let stale = state.stale_token.swap(false, Ordering::SeqCst) || fresh; + let kind = if stale { "req" } else { "cache.req" }; + if std::fs::rename(&part, dir.join(format!("denuvo-{rid}.{kind}"))).is_err() { + if stale { + state.stale_token.store(true, Ordering::SeqCst); + } + return None; + } let deadline = Instant::now() + DENUVO_WAIT; while Instant::now() < deadline { if let Ok(token) = std::fs::read(&rsp) { let _ = std::fs::remove_file(&rsp); - return (!token.is_empty()).then_some(token); + return (!token.is_empty()).then_some((token, (!stale).then_some(seen))); } thread::sleep(Duration::from_millis(200)); } @@ -207,14 +223,48 @@ mod service { } AuxReq::Activate(rid, challenge) => { state.say(&format!("aux: activation {rid} with a {} B challenge", challenge.len())); - match denuvo(state, rid, challenge) { - Some(token) => { - send(&pipe, &launcher::aux_token(rid, &token)); + let mut fresh = false; + loop { + let Some((token, seen)) = denuvo(state, rid, challenge, fresh) else { + state.say(&format!("aux: no game token for activation {rid}")); + break; + }; + let answer = || send(&pipe, &launcher::aux_token(rid, &token)); + let served = match seen { + Some(g) => state.generation.serve(g, answer).is_some(), + None => { + answer(); + true + } + }; + if served { state.say(&format!("aux: activation {rid} answered ({} B)", token.len())); + break; } - None => state.say(&format!("aux: no game token for activation {rid}")), + state.say(&format!("aux: kept token for activation {rid} came back after an invalidation; asking afresh")); + fresh = true; } } + AuxReq::Invalidate(rid) => { + state.stale_token.store(true, Ordering::SeqCst); + let published = state.generation.invalidate(SERVE_WAIT, || { + let published = state.cfg.bridge.is_empty() + || bridge::publish_invalidation(Path::new(&state.cfg.bridge), &state.cfg.user_id, MARKER_TRIES, MARKER_PAUSE); + if published { + send(&pipe, &launcher::aux_invalidated(rid)); + } + published + }); + if published { + state.say(&format!("aux: token invalidated by request {rid}")); + } else { + state.say(&format!("aux: invalidation {rid} not acknowledged; the kept token could not be marked stale")); + } + } + AuxReq::BurnTicket(rid) => { + send(&pipe, &launcher::aux_no_burn_ticket(rid)); + state.say(&format!("aux: burn ticket {rid} answered as unavailable")); + } AuxReq::Other(rid) => state.say(&format!("aux: request {rid} not handled ({} B)", req.len())), } } @@ -304,6 +354,8 @@ mod service { log: Mutex::new(log), event: win::inheritable_event(), game: AtomicU32::new(0), + stale_token: AtomicBool::new(false), + generation: Generation::default(), started: Instant::now(), }); state.say(&format!("product {} on {}*", state.cfg.product, state.prefix)); diff --git a/tools/ubuntu/proc/version b/tools/ubuntu/proc/version index 5e6716a598..4a0c36fa35 100644 --- a/tools/ubuntu/proc/version +++ b/tools/ubuntu/proc/version @@ -1 +1 @@ -Linux version 6.1.0 (bannerlator@android) (gcc version 12.0) #1 SMP PREEMPT +Linux version 6.1.0 (droiddeck@android) (gcc version 12.0) #1 SMP PREEMPT diff --git a/tools/vr/src/driver_droiddeck.cpp b/tools/vr/src/driver_droiddeck.cpp index 2535e04cc2..05f3aec58b 100644 --- a/tools/vr/src/driver_droiddeck.cpp +++ b/tools/vr/src/driver_droiddeck.cpp @@ -438,7 +438,7 @@ private: if (paths && !strncmp(paths, "0=", 2)) path.assign(paths + 2, strcspn(paths + 2, ";")); } if (path.empty()) { - if (const char *dir = getenv("BL_LAUNCH_DIR")) path = std::string(dir) + "/dev/fakeinput-rings/ring0"; + if (const char *dir = getenv("DD_LAUNCH_DIR")) path = std::string(dir) + "/dev/fakeinput-rings/ring0"; } if (path.empty()) return false; int fd = open(path.c_str(), O_RDONLY | O_CLOEXEC); diff --git a/tools/xbox/README.md b/tools/xbox/README.md index 0f106585bc..c0a6636aba 100644 --- a/tools/xbox/README.md +++ b/tools/xbox/README.md @@ -108,11 +108,38 @@ lets ARM64EC Wine load the AMD64 modules through its normal native DLL path. Only each Xbox game's prefix receives these Windows modules. Existing Steam games and other store prefixes retain their selected runtimes. +`droiddeck-legacy-packages.patch` lets the plan, license and extract verbs handle a legacy +package. A bundle is expanded in place, nesting is bounded at three, and each inner EAppx +container is decrypted with the same content keys; inner files without an EAppx header are left +as extracted. `streaming` still serves MSIXVC only. + +`droiddeck-legacy-install.patch` adds `xodus-cli legacy-install`: resolve, license, download, +extract, hoist. Resolution asks the Xbox content service first and Windows Update +(`fe3cr.delivery.mp.microsoft.com`, SOAP) second, because some legacy products return no files +from the content service. The WU endpoint needs no Xbox credential but chains to Microsoft's ECC +Product Root CA 2018, which Android's CA bundle does not carry, so that one public root is +pinned in `wu-root.pem` for these requests. Only `.eappx`/`.eappxbundle` files from a WU result +are kept; the `.appx` framework packages and `.cab` metadata beside them are dropped. Licensing +runs before the first byte and must return content keys. Free space is checked against the +download plus two copies of the largest container, and each container is deleted once unpacked. +The download has no control channel: cancelling kills it and the next attempt starts that +container from zero. + +`droiddeck-msixvc2.patch` installs MSIXVC2 packages, the format Xbox 360 backward-compatible +titles ship in. The package Windows Update serves is only an index (`XboxPackage.cbor`, chunk and +file tables); the files are encrypted, Brotli-compressed segments inside `.box` blobs on the Xbox +content hosts. `streaming` unpacks the index, licenses its content id, derives the package key from +the content key (SP800-108 HMAC-SHA256, label `MSIXVC2:PackageData:AES_256_CBC`), unwraps each +segment key with AES-256-CBC, fetches adjacent segments in one ranged request, and checks the +SHA-384 of every stored segment, decompressed segment and finished file before it is renamed into +place. Files already complete are skipped on a retry. + Cloud saves and in-game identity use the reused XGameRuntime/service interfaces; those are game-dependent. Entitlements distinguish purchases from Game Pass access, and the backend performs a fresh license check for downloads and launch. -The store lists PC MSIXVC games only. It does not emulate Xbox consoles or add -support for UWP/APPX packages. Update / verify refreshes an installed package through the normal licensed +The store lists PC packages it can install: streamed MSIXVC, and the legacy EAppx bundles older +desktop titles still ship as. It does not emulate Xbox consoles or host UWP titles in a +packaged-app host. Update / verify refreshes an installed package through the normal licensed streaming path. Manage content resolves manifest-related licensed PC DLC into separate content roots and checks its parent identity after download. These flows still require game/account validation; runtime API presence does not diff --git a/tools/xbox/build-local.sh b/tools/xbox/build-local.sh index 979c95b12b..3e61e8eae9 100755 --- a/tools/xbox/build-local.sh +++ b/tools/xbox/build-local.sh @@ -10,6 +10,12 @@ build=' bash tools/xbox/build.sh ' if [[ $(uname -m) = x86_64 ]]; then + binfmt_magics=$(cat /proc/sys/fs/binfmt_misc/* 2>/dev/null || true) + if [[ $(uname -s) = Linux && $binfmt_magics != *'magic 7f454c460201010000000000000000000200b700'* ]]; then + echo "The Xbox backend tests re-execute their arm64 binaries, which needs an aarch64 binfmt handler on the host." >&2 + echo "Register one with: docker run --privileged --rm tonistiigi/binfmt --install arm64" >&2 + exit 1 + fi cache=${DROIDDECK_XBOX_CACHE:-"${HOME}/.cache/droiddeck-xbox-cross"} platform=linux/amd64 image=droiddeck-xbox-cross:$(shasum -a 256 "$repo/tools/xbox/cross.Dockerfile" | cut -c1-12) @@ -26,6 +32,10 @@ else '"$build" fi mkdir -p "$cache" +threads=() +[[ -n "${RUST_TEST_THREADS:-}" ]] && threads=(-e RUST_TEST_THREADS="$RUST_TEST_THREADS") docker run --rm --platform "$platform" -v "$repo:/src" -v "$cache:/work" -w /src \ - -e CARGO_HOME=/work/cargo -e RUSTUP_HOME=/work/rustup -e XBOX_BUILD_DIR=/work/build "$image" \ - bash -lc "set -euo pipefail$build" + -e CARGO_HOME=/work/cargo -e RUSTUP_HOME=/work/rustup -e XBOX_BUILD_DIR=/work/build \ + ${threads[@]+"${threads[@]}"} "$image" \ + bash -lc "set -euo pipefail + trap 'chown -R $(id -u):$(id -g) /work /src/app/src/main/assets/linuxfs /src/app/build 2>/dev/null || true' EXIT$build" diff --git a/tools/xbox/build.sh b/tools/xbox/build.sh index 99bee8c76b..85cdbd3c62 100755 --- a/tools/xbox/build.sh +++ b/tools/xbox/build.sh @@ -16,7 +16,9 @@ cargo build --locked --release --no-default-features --target aarch64-unknown-li if [[ $(uname -m) = aarch64 || -n ${CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_RUNNER:-} ]]; then cargo test --locked --release --no-default-features --target aarch64-unknown-linux-gnu -p xodus-cli cargo test --locked --release --no-default-features --target aarch64-unknown-linux-gnu -p xodus credential_ - cargo test --locked --release --no-default-features --target aarch64-unknown-linux-gnu -p msixvc streaming_ + msixvc_env=() + [[ $(uname -m) = aarch64 ]] || msixvc_env=(RUST_TEST_THREADS=1) + env "${msixvc_env[@]}" cargo test --locked --release --no-default-features --target aarch64-unknown-linux-gnu -p msixvc streaming_ fi for binary in xodus-cli xodus-service; do install -m755 "$CARGO_TARGET_DIR/aarch64-unknown-linux-gnu/release/$binary" "$out/$binary" diff --git a/tools/xbox/droiddeck-legacy-install.patch b/tools/xbox/droiddeck-legacy-install.patch new file mode 100644 index 0000000000..2d34e91679 --- /dev/null +++ b/tools/xbox/droiddeck-legacy-install.patch @@ -0,0 +1,2826 @@ +diff --git a/Cargo.lock b/Cargo.lock +index 0b0f1e0..5dfc09a 100644 +--- a/Cargo.lock ++++ b/Cargo.lock +@@ -7185,12 +7185,14 @@ dependencies = [ + "console-subscriber", + "ctrlc", + "eappx", ++ "flate2", + "fs2", + "futures-util", + "indicatif", + "inquire", + "msixvc", + "nix", ++ "quick-xml 0.42.0", + "reqwest 0.13.4", + "rustix", + "serde_json", +diff --git a/crates/xodus-cli/Cargo.toml b/crates/xodus-cli/Cargo.toml +index 5894ef9..f49470b 100644 +--- a/crates/xodus-cli/Cargo.toml ++++ b/crates/xodus-cli/Cargo.toml +@@ -5,6 +5,7 @@ edition = "2024" + default-run = "xodus-cli" + + [dependencies] ++quick-xml = "0.42.0" + xodus = { path = "../xodus" } + msixvc = { path = "../msixvc" } + eappx = { git = "https://github.com/tuxuser/eappx-rs" } +@@ -25,6 +26,7 @@ futures-util = "0.3.34" + uuid = "1.25.0" + indicatif = "0.18.6" + fs2 = "0.4.3" ++flate2 = "1.0.28" + tempfile = "3.27.0" + rustix = "1.1.4" + ctrlc = "3.5.2" +diff --git a/crates/xodus-cli/src/commands.rs b/crates/xodus-cli/src/commands.rs +index 088a6d0..825c24e 100644 +--- a/crates/xodus-cli/src/commands.rs ++++ b/crates/xodus-cli/src/commands.rs +@@ -2,11 +2,14 @@ pub mod clep; + pub mod download; + pub mod extract; + pub mod extract_eappx; ++pub mod unzip; + pub mod license; ++pub mod legacy_install; + pub mod login; + pub mod logout; + pub mod offline_pc; + pub mod profile; ++pub mod store_delivery; + pub mod cloud_token; + pub mod social; + pub mod game_activity; +diff --git a/crates/xodus-cli/src/commands/extract_eappx.rs b/crates/xodus-cli/src/commands/extract_eappx.rs +index 5ea43da..0bad98e 100644 +--- a/crates/xodus-cli/src/commands/extract_eappx.rs ++++ b/crates/xodus-cli/src/commands/extract_eappx.rs +@@ -51,6 +51,8 @@ pub struct Meter { + pub banked: std::sync::atomic::AtomicU64, + /// Bytes the package being unpacked now will write in total. + pub total: std::sync::atomic::AtomicU64, ++ /// Bytes that packages not yet opened will write. ++ pub planned: std::sync::atomic::AtomicU64, + turn: std::sync::Mutex<()>, + } + +@@ -61,7 +63,14 @@ impl Meter { + let _turn = self.turn.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + let banked = self.banked.load(Relaxed); + let total = self.total.load(Relaxed); +- (banked + self.written.load(Relaxed).min(total), banked + total) ++ (banked + self.written.load(Relaxed).min(total), banked + total + self.planned.load(Relaxed)) ++ } ++ ++ /// Announces packages that will be opened later, so the total does not grow when they are. ++ fn expect(&self, bytes: u64) { ++ use std::sync::atomic::Ordering::Relaxed; ++ let _turn = self.turn.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); ++ self.planned.fetch_add(bytes, Relaxed); + } + + pub fn done(&self) -> u64 { +@@ -79,6 +88,8 @@ impl Meter { + self.banked.fetch_add(self.total.load(Relaxed), Relaxed); + self.written.store(0, Relaxed); + self.total.store(total, Relaxed); ++ let planned = self.planned.load(Relaxed); ++ self.planned.store(planned.saturating_sub(total), Relaxed); + } + } + +@@ -260,6 +271,9 @@ fn derive( + return Err(Failure::at("nesting", infile, "bundle nesting exceeds the limit")); + } + ++ if let Some(meter) = meter { ++ meter.expect(nested.iter().map(|child| package_size(child)).sum()); ++ } + for child in nested { + let name = child + .file_stem() +@@ -275,6 +289,14 @@ fn derive( + Ok(()) + } + ++/// What a package's blockmap says it will write, or nothing when its header is unreadable. ++fn package_size(path: &Path) -> u64 { ++ let Ok(file) = std::fs::File::open(path) else { return 0 }; ++ EAppxFile::from_stream(&mut std::io::BufReader::new(file)) ++ .map(|package| package.blockmap.files.iter().map(|entry| entry.size).sum()) ++ .unwrap_or(0) ++} ++ + /// Bytes currently on disk under `dir`. + /// + /// A bundle member is written as one file, so a per-file counter says nothing +@@ -414,3 +436,29 @@ fn unpack( + } + Ok(()) + } ++ ++#[cfg(test)] ++mod meter_tests { ++ use super::Meter; ++ ++ #[test] ++ fn announced_packages_keep_the_total_from_growing() { ++ let meter = Meter::default(); ++ meter.roll(100); ++ meter.expect(300); ++ assert_eq!(meter.snapshot(), (0, 400)); ++ meter.written.store(100, std::sync::atomic::Ordering::Relaxed); ++ meter.roll(300); ++ assert_eq!(meter.snapshot(), (100, 400)); ++ meter.written.store(300, std::sync::atomic::Ordering::Relaxed); ++ assert_eq!(meter.snapshot(), (400, 400)); ++ } ++ ++ #[test] ++ fn written_bytes_never_exceed_the_package_being_unpacked() { ++ let meter = Meter::default(); ++ meter.roll(10); ++ meter.written.store(25, std::sync::atomic::Ordering::Relaxed); ++ assert_eq!(meter.snapshot(), (10, 10)); ++ } ++} +diff --git a/crates/xodus-cli/src/commands/legacy_install.rs b/crates/xodus-cli/src/commands/legacy_install.rs +new file mode 100755 +index 0000000..d43c5fc +--- /dev/null ++++ b/crates/xodus-cli/src/commands/legacy_install.rs +@@ -0,0 +1,1198 @@ ++//! Installs a legacy Store title: resolve, license, download, extract. ++//! ++//! `streaming` only understands MSIXVC, where the container *is* the game and ++//! the bytes arrive in the block layout the runtime reads. A legacy title ships ++//! as an EAppx bundle instead, so its bytes have to be fetched whole, licensed ++//! and decrypted before anything is launchable. ++//! ++//! Two delivery routes exist and both are needed in practice: the Xbox content ++//! service serves MSIXVC and some legacy packages, and Windows Update serves the ++//! legacy desktop bundles it refuses (see `store_delivery`). Each is tried in ++//! turn and whichever names a container is used. ++//! ++//! The three verbs under that (`license`, `download`, `extract-eappx`) are chained ++//! here rather than from the app because each process would restart the progress ++//! sequence, and the installer requires it to increase within one stream. ++ ++use std::path::{Path, PathBuf}; ++use std::process::ExitCode; ++use std::time::{Duration, Instant}; ++ ++use futures_util::StreamExt; ++use tokio::io::AsyncWriteExt; ++use xodus::tokens::TokenManager; ++ ++/// Downloaded containers live here until extraction succeeds. They are large and ++/// useless afterwards, so they are removed on success and kept on failure. ++const CONTAINER_DIR: &str = ".xodus-container"; ++/// Content keys for the containers above, removed alongside them. ++const KEYS_DIR: &str = ".xodus-keys"; ++/// The manifest the launcher resolves executables against, expected at the root. ++const MANIFEST: &str = "MicrosoftGame.config"; ++/// A legacy package carries this instead of the config above. ++const LEGACY_MANIFEST: &str = "AppxManifest.xml"; ++/// Framework packages unpack here, and their libraries are copied up beside the title. ++const FRAMEWORK_DIR: &str = ".droiddeck-frameworks"; ++/// Marks a framework whose libraries are already beside the title. ++const INSTALLED: &str = ".installed"; ++/// The libraries `copy_libraries` put beside the title, one name per line. ++const COPIED: &str = ".droiddeck-copied"; ++ ++fn is_legacy_name(name: &str) -> bool { ++ let name = name.to_ascii_lowercase(); ++ name.ends_with(".eappx") || name.ends_with(".eappxbundle") ++} ++ ++/// Free bytes on the filesystem holding `path`, or `None` when it cannot be read. ++/// ++/// The install runs inside the device's own Linux environment, where `df -P -k` is ++/// the one portable free-space query that needs no extra crate, and a failed read ++/// only skips the check rather than blocking a valid install. ++fn free_bytes(path: &Path) -> Option { ++ let output = std::process::Command::new("df").arg("-kP").arg(path).output().ok()?; ++ if !output.status.success() { ++ return None; ++ } ++ let text = String::from_utf8_lossy(&output.stdout); ++ let available = text.lines().nth(1)?.split_whitespace().nth(3)?; ++ available.parse::().ok().map(|kib| kib.saturating_mul(1024)) ++} ++ ++/// Reports why the install stopped without disclosing anything sensitive. ++/// ++/// The app only forwards stderr lines that are on a known allowlist, so a bare ++/// message is invisible there. Two lines are emitted instead: a stable stage code, ++/// and the message reduced to lowercase words with every token that could carry a ++/// path, URL or identifier dropped. ++fn fail(code: &str, message: &str) -> ExitCode { ++ eprintln!("NEXUS_LEGACY_INSTALL_DIAGNOSTIC_V1 {code}"); ++ let detail = bounded(&plain(message)); ++ if !detail.is_empty() { ++ eprintln!("NEXUS_LEGACY_INSTALL_DETAIL_V1 {detail}"); ++ } ++ eprintln!("{message}"); ++ ExitCode::FAILURE ++} ++ ++/// The message reduced to whatever can be shown over a diagnostic line. ++/// Android keeps a detail line only up to 220 characters, so the whole line is cut, not each part. ++fn bounded(line: &str) -> String { ++ let mut cut = line.len().min(220); ++ while !line.is_char_boundary(cut) { ++ cut -= 1; ++ } ++ line[..cut].trim_end().to_string() ++} ++ ++fn plain(message: &str) -> String { ++ let mut detail = String::new(); ++ for word in message.split_whitespace() { ++ if word.contains('/') || word.contains(':') || word.contains('\\') { ++ continue; ++ } ++ let cleaned: String = word ++ .chars() ++ .filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '.') ++ .collect::() ++ .to_ascii_lowercase(); ++ if cleaned.is_empty() { ++ continue; ++ } ++ if !detail.is_empty() { ++ detail.push(' '); ++ } ++ detail.push_str(&cleaned); ++ if detail.len() >= 200 { ++ break; ++ } ++ } ++ detail ++} ++ ++/// `plain` for callers outside this file. ++pub(crate) fn plain_for_log(message: &str) -> String { ++ bounded(&plain(message)) ++} ++ ++/// The installer parses this and only this, so it must match the streaming ++/// schema exactly; `phase` drives its stage display. ++struct Progress { ++ json: bool, ++ sequence: u64, ++ phase: &'static str, ++ completed: u64, ++ total: Option, ++ previous: u64, ++ last: Instant, ++} ++ ++impl Progress { ++ fn new(json: bool) -> Self { ++ let mut progress = Self { ++ json, ++ sequence: 0, ++ phase: "metadata", ++ completed: 0, ++ total: None, ++ previous: 0, ++ last: Instant::now(), ++ }; ++ progress.emit(); ++ progress ++ } ++ ++ fn total(&mut self, total: u64) { ++ self.total = Some(total); ++ self.emit(); ++ } ++ ++ /// Stage transitions are always reported; byte updates are rate limited so a ++ /// multi-gigabyte download cannot flood the pipe. ++ fn phase(&mut self, phase: &'static str) { ++ self.phase = phase; ++ self.completed = 0; ++ self.previous = 0; ++ self.emit(); ++ } ++ ++ fn advance(&mut self, delta: u64) { ++ self.completed = self.completed.saturating_add(delta); ++ if self.last.elapsed() >= Duration::from_millis(200) { ++ self.emit(); ++ } ++ } ++ ++ /// Reports unpacking, which counts bytes neither the download nor a file list ++ /// can see, so the bar advances while a multi-gigabyte member is decrypted. ++ fn bytes(&mut self, completed: u64, total: u64) { ++ self.phase = "installing"; ++ self.completed = completed; ++ self.total = Some(total); ++ if self.last.elapsed() >= Duration::from_millis(700) { ++ self.emit(); ++ } ++ } ++ ++ fn complete(&mut self, success: bool) { ++ self.phase = if success { "complete" } else { "failed" }; ++ self.emit(); ++ } ++ ++ fn emit(&mut self) { ++ let elapsed = self.last.elapsed(); ++ let rate = (self.completed.saturating_sub(self.previous) as f64 / elapsed.as_secs_f64().max(0.001)) as u64; ++ self.previous = self.completed; ++ self.last = Instant::now(); ++ if self.json { ++ let record = serde_json::json!({ ++ "schema": 1, ++ "event": "progress", ++ "sequence": self.sequence, ++ "phase": self.phase, ++ "paused": false, ++ "canPause": false, ++ "completedBytes": self.completed, ++ "totalBytes": self.total, ++ "bytesPerSecond": rate, ++ }); ++ println!("NEXUS_PROGRESS {record}"); ++ } else { ++ match self.total { ++ Some(total) => println!("{}: {}/{} bytes", self.phase, self.completed, total), ++ None => println!("{}: {} bytes", self.phase, self.completed), ++ } ++ } ++ self.sequence += 1; ++ } ++} ++ ++/// A container to fetch, wherever its location came from. ++struct Container { ++ name: String, ++ url: String, ++ size: u64, ++} ++ ++/// What to install and which content id its keys are licensed under. ++struct Install { ++ content_id: String, ++ containers: Vec, ++ /// Why the other route was not used, for the failure message. ++ note: String, ++ /// A Windows Update build whose download locations are asked for once it is licensed. ++ build: Option, ++} ++ ++/// Resolves the legacy containers the Xbox content service is willing to serve. ++/// ++/// Every legacy-format member of the offer is tried, because a product can carry ++/// more than one content id and only some of them are served files. Measured on ++/// FH4: the desktop EAppxBundle is acknowledged with an empty file list while the ++/// console XVC of the same product is served normally, so the empty answer is ++/// reported as such rather than as a title that is not owned. ++async fn from_xbox_service( ++ client: &reqwest::Client, ++ tokens: &TokenManager, ++ product: &str, ++ market: &str, ++ preferred: Option<&str>, ++) -> Result { ++ let region = market.to_uppercase(); ++ let mut candidates: Vec = Vec::new(); ++ if let Some(preferred) = preferred.filter(|id| uuid::Uuid::try_parse(id).is_ok()) { ++ candidates.push(preferred.to_string()); ++ } else if uuid::Uuid::try_parse(product).is_ok() { ++ candidates.push(product.to_string()); ++ } else { ++ let plan = crate::package_plan::resolve(client, &product.to_uppercase(), ®ion) ++ .await ++ .map_err(|error| format!("resolve {error}"))?; ++ for choice in &plan.choices { ++ let legacy_format = choice.format == "EAPPX" || choice.format == "EAPPXBUNDLE"; ++ if legacy_format && !candidates.contains(&choice.content_id) { ++ candidates.push(choice.content_id.clone()); ++ } ++ } ++ // The catalogue names the package a listing shows, which need not be the ++ // container the content service hands over, so the resolver's own choice ++ // is asked first and the rest of the offer is only a fallback. ++ if let Ok(pick) = plan.without_durable_selection().select(None) { ++ candidates.retain(|candidate| *candidate != pick); ++ candidates.insert(0, pick); ++ } ++ } ++ if candidates.is_empty() { ++ return Err("the Store offer names no legacy package".into()); ++ } ++ ++ let mut probe: Vec = Vec::new(); ++ for (index, candidate) in candidates.iter().take(4).enumerate() { ++ match crate::package::get_packages(client, tokens, candidate.clone()).await { ++ Ok(package) => { ++ let legacy: Vec<_> = package ++ .package_files ++ .iter() ++ .filter(|file| is_legacy_name(&file.file_name)) ++ .collect(); ++ probe.push(format!("c{index} n{} l{}", package.package_files.len(), legacy.len())); ++ if legacy.is_empty() { ++ continue; ++ } ++ let mut containers = Vec::new(); ++ for file in legacy { ++ let Some(root) = file.cdn_root_paths.first() else { ++ return Err("a package file has no download location".into()); ++ }; ++ containers.push(Container { ++ name: file.file_name.clone(), ++ url: format!("{root}{}", file.relative_url), ++ size: file.file_size.max(0) as u64, ++ }); ++ } ++ return Ok(Install { content_id: candidate.clone(), containers, note: probe.join(" "), build: None }); ++ } ++ Err(error) => probe.push(format!("c{index} {error}")), ++ } ++ } ++ Err(format!("{} candidates, {}", candidates.len(), probe.join(" "))) ++} ++ ++pub async fn run( ++ client: &reqwest::Client, ++ tokens: &TokenManager, ++ product: String, ++ destination: String, ++ market: Option, ++ selected_content_id: Option, ++ store_id: Option, ++ progress_json: bool, ++ resolve_only: bool, ++) -> ExitCode { ++ let destination = PathBuf::from(destination); ++ if let Err(error) = tokio::fs::create_dir_all(&destination).await { ++ return fail("destination-failed", &format!("Could not prepare the install folder: {error}")); ++ } ++ let _folder_lock = match std::fs::OpenOptions::new() ++ .write(true) ++ .create(true) ++ .truncate(false) ++ .open(destination.join(".nexus-streaming.lock")) ++ .and_then(|file| fs2::FileExt::try_lock_exclusive(&file).map(|()| file)) ++ { ++ Ok(file) => file, ++ Err(_) => return fail("folder-busy", "Another download is using this folder"), ++ }; ++ let mut progress = Progress::new(progress_json); ++ let region = market.clone().unwrap_or("US".into()).to_uppercase(); ++ ++ // One client covers both routes: a package the content service serves is also ++ // downloaded from a delivery host, so both download and update calls use it. ++ let delivery_client = match crate::commands::store_delivery::client() { ++ Ok(client) => client, ++ Err(error) => return fail("update-client-failed", &error), ++ }; ++ let mut update = None; ++ let mut builds: Vec = match from_xbox_service(client, tokens, &product, ®ion, selected_content_id.as_deref()).await { ++ Ok(install) => vec![install], ++ Err(xbox_error) => { ++ // The content service does not serve legacy desktop bundles, so the ++ // Windows Update route is the one that has to work. Its catalogue is ++ // keyed by the Store product, also for an add-on named by content id. ++ let catalogue = store_id.as_deref().unwrap_or(&product); ++ match crate::commands::store_delivery::resolve_builds(&delivery_client, catalogue, ®ion).await { ++ Ok(list) => { ++ let found = (0..list.len()) ++ .map(|index| Install { ++ content_id: list.content_id(index), ++ containers: Vec::new(), ++ note: "windows-update".into(), ++ build: Some(index), ++ }) ++ .collect(); ++ update = Some(list); ++ found ++ } ++ Err(update_error) => { ++ return fail( ++ "no-container", ++ &format!("{xbox_error}; windows update: {update_error}"), ++ ) ++ } ++ } ++ } ++ }; ++ if resolve_only { ++ // Printing locations is what makes a failure diagnosable without spending ++ // hours on a download, so this stops before any byte is written. ++ for install in &builds { ++ println!("content-id: {} ({})", install.content_id, install.note); ++ for container in &install.containers { ++ println!("{} {} {}", container.size, container.name, container.url); ++ } ++ if let (Some(index), Some(list)) = (install.build, update.as_ref()) { ++ match list.locate(&delivery_client, index).await { ++ Ok(files) => files.iter().for_each(|file| println!("{} {} {}", file.size, file.name, file.url)), ++ Err(error) => println!("unavailable: {error}"), ++ } ++ } ++ } ++ return ExitCode::SUCCESS; ++ } ++ ++ // The license verb already writes the [Keys] text eappx reads, so reuse it ++ // rather than re-deriving the content keys here. ++ let keys = destination.join(KEYS_DIR); ++ if let Err(error) = tokio::fs::create_dir_all(&keys).await { ++ return fail("keys-folder-failed", &format!("Could not prepare the key folder: {error}")); ++ } ++ // The standalone verb defaults to "neutral" and that is the market this path ++ // was proven against, so default the same way rather than forwarding a ++ // region the license service may not accept. ++ let license_market = market.clone().unwrap_or("neutral".into()); ++ let refused = xodus::licensing::content::LicenseContentError::DeviceUnregistrable.to_string(); ++ let install = loop { ++ let mut candidate = builds.remove(0); ++ match crate::commands::license::dump( ++ client, ++ tokens, ++ candidate.content_id.clone(), ++ license_market.clone(), ++ keys.display().to_string(), ++ ) ++ .await ++ { ++ Ok(()) => { ++ let (Some(index), Some(list)) = (candidate.build, update.as_ref()) else { break candidate }; ++ match list.locate(&delivery_client, index).await { ++ Ok(files) => { ++ candidate.containers = files ++ .into_iter() ++ .map(|file| Container { name: file.name, url: file.url, size: file.size }) ++ .collect(); ++ break candidate; ++ } ++ Err(_) if !builds.is_empty() => { ++ eprintln!("NEXUS_LEGACY_INSTALL_DETAIL_V1 a licensed build has no download location, trying an older build"); ++ } ++ Err(error) => return fail("no-container", &error), ++ } ++ } ++ Err(error) if error == refused && !builds.is_empty() => { ++ eprintln!("NEXUS_LEGACY_INSTALL_DETAIL_V1 newest build has no license for this device, trying an older build"); ++ } ++ Err(error) => { ++ eprintln!("{error}"); ++ return fail("license-failed", &format!("No license for content {} ({})", candidate.content_id, candidate.note)); ++ } ++ } ++ }; ++ if install.containers.is_empty() { ++ return fail("no-container", "No package files were listed for this title"); ++ } ++ let total: u64 = install.containers.iter().map(|container| container.size).sum(); ++ let largest = install.containers.iter().map(|container| container.size).max().unwrap_or(0); ++ progress.total(total); ++ let mut names = std::collections::HashSet::new(); ++ for container in &install.containers { ++ let Some(name) = Path::new(&container.name).file_name() else { ++ return fail("unusable-name", "Microsoft returned an unusable package name"); ++ }; ++ if !names.insert(name.to_string_lossy().to_ascii_lowercase()) { ++ return fail("duplicate-container", "Microsoft listed two packages under one name"); ++ } ++ } ++ if let Ok(entries) = std::fs::read_dir(destination.join(CONTAINER_DIR)) { ++ for entry in entries.flatten() { ++ let name = entry.file_name().to_string_lossy().to_ascii_lowercase(); ++ if !names.contains(&name) && entry.file_type().is_ok_and(|kind| kind.is_file()) { ++ let _ = std::fs::remove_file(entry.path()); ++ } ++ } ++ } ++ let mut held = 0u64; ++ for container in &install.containers { ++ let Some(name) = Path::new(&container.name).file_name() else { continue }; ++ let staged = destination.join(CONTAINER_DIR).join(name); ++ let Ok(meta) = std::fs::symlink_metadata(&staged) else { continue }; ++ if meta.is_file() && container.size > 0 && meta.len() == container.size { ++ held = held.saturating_add(meta.len()); ++ continue; ++ } ++ if std::fs::remove_file(&staged).is_err() ++ && !(meta.is_file() && std::fs::OpenOptions::new().write(true).truncate(true).open(&staged).is_ok()) ++ { ++ return fail("staging-failed", "Could not clear an unfinished download from the staging folder"); ++ } ++ } ++ if let Some(free) = free_bytes(&destination) { ++ let needed = total.saturating_add(largest).saturating_add(largest / 10); ++ if free.saturating_add(held) < needed { ++ return fail( ++ "insufficient-space", ++ &format!( ++ "An install this size needs about {} GB free to unpack, and {} GB is available", ++ needed / 1_000_000_000, ++ free.saturating_add(held) / 1_000_000_000 ++ ), ++ ); ++ } ++ } ++ let key_file = keys.join("eappx-keys.txt"); ++ if !key_file.is_file() { ++ return fail("no-keys", "The license contained no content keys for this title"); ++ } ++ ++ let store = destination.join(CONTAINER_DIR); ++ if let Err(error) = tokio::fs::create_dir_all(&store).await { ++ return fail("staging-folder-failed", &format!("Could not prepare the staging folder: {error}")); ++ } ++ progress.phase("downloading"); ++ let mut downloaded: Vec = Vec::new(); ++ for container in &install.containers { ++ // Only the container's own name is used, never a server-provided path. ++ let Some(name) = Path::new(&container.name).file_name() else { ++ return fail("unusable-name", "Microsoft returned an unusable package name"); ++ }; ++ let target = store.join(name); ++ // A container a stopped attempt finished is not fetched again: it is most ++ // of an install this size, and the failure that stopped the run was almost ++ // never in its bytes. ++ if let Ok(meta) = tokio::fs::metadata(&target).await { ++ if container.size > 0 && meta.len() == container.size { ++ progress.advance(meta.len()); ++ downloaded.push(target); ++ continue; ++ } ++ } ++ let response = match delivery_client.get(&container.url).send().await { ++ Ok(response) => response, ++ Err(_) => return fail("download-request-failed", "Could not reach the download server"), ++ }; ++ if !response.status().is_success() { ++ return fail( ++ &format!("download-refused-{}", response.status().as_u16()), ++ "The download server refused this package", ++ ); ++ } ++ let mut file = match tokio::fs::File::create(&target).await { ++ Ok(file) => file, ++ Err(error) => return fail("download-write-failed", &format!("Could not write the package: {error}")), ++ }; ++ let mut stream = response.bytes_stream(); ++ while let Some(chunk) = stream.next().await { ++ let Ok(chunk) = chunk else { ++ return fail("download-interrupted", "The transfer was interrupted; resume to retry"); ++ }; ++ if let Err(error) = file.write_all(&chunk).await { ++ return fail("download-write-failed", &format!("Could not write the package: {error}")); ++ } ++ progress.advance(chunk.len() as u64); ++ } ++ if let Err(error) = file.flush().await { ++ return fail("download-flush-failed", &format!("Could not finish writing the package: {error}")); ++ } ++ downloaded.push(target); ++ } ++ ++ progress.phase("installing"); ++ let key_file_text = key_file.display().to_string(); ++ let meter = std::sync::Arc::new(crate::commands::extract_eappx::Meter::default()); ++ // Taken before the first byte is written, so growth of the folder is the ++ // progress of the unpack and not the container that was already downloaded. ++ let baseline = crate::commands::extract_eappx::tree_size(&destination); ++ let mut high = 0u64; ++ for container in &downloaded { ++ let source = container.display().to_string(); ++ // Unpacking never yields, so it runs on a blocking thread and this task ++ // reports the counter while it works. Without that, the phase would only ++ // be visible once it had finished. ++ let unpacking = tokio::task::spawn_blocking({ ++ let destination = destination.clone(); ++ let key_file_text = key_file_text.clone(); ++ let meter = meter.clone(); ++ move || { ++ crate::commands::extract_eappx::run_blocking( ++ source, ++ destination.display().to_string(), ++ Some(key_file_text), ++ Some(&meter), ++ // A full title is tens of gigabytes. Holding the container ++ // while its members are decrypted can fill the device. ++ true, ++ ) ++ } ++ }); ++ let extracted = loop { ++ if unpacking.is_finished() { ++ break unpacking.await.unwrap_or(ExitCode::FAILURE); ++ } ++ tokio::time::sleep(Duration::from_millis(700)).await; ++ let (mut done, total) = meter.snapshot(); ++ if total == 0 { ++ continue; ++ } ++ // A bundle member is one file, so its bytes are only visible on disk. ++ if meter.written.load(std::sync::atomic::Ordering::Relaxed) == 0 { ++ let on_disk = crate::commands::extract_eappx::tree_size(&destination).saturating_sub(baseline); ++ done = done.max(on_disk); ++ } ++ // Deleting the container takes bytes off the disk, so the reported ++ // figure only ever moves forward. ++ high = high.max(done.min(total)); ++ progress.bytes(high, total); ++ }; ++ if extracted != ExitCode::SUCCESS { ++ return fail("extract-failed", "Could not unpack the package; the download is kept for a retry"); ++ } ++ // Drop each container as soon as it is unpacked: a full title is tens of ++ // gigabytes, and holding the archive and its contents at once can fill ++ // the device mid-install. ++ tokio::fs::remove_file(container).await.ok(); ++ } ++ ++ // A bundle extracts each member into its own directory, so the manifest ends ++ // up one level down. The launcher resolves executables relative to the game ++ // folder and requires the manifest at its root, so lift a lone member up. ++ if let Err(error) = hoist(&destination) { ++ return fail("hoist-failed", &error); ++ } ++ ++ tokio::fs::remove_dir_all(&store).await.ok(); ++ ++ // An installed package gets its frameworks from the package graph. Nothing ++ // puts them there for an unpacked folder, and a title that needs one refuses ++ // to load without it, so they are fetched and unpacked beside the title. ++ progress.phase("frameworks"); ++ if let Err(error) = ensure_frameworks(&delivery_client, &destination, ®ion).await { ++ progress.phase("frameworks"); ++ eprintln!("NEXUS_LEGACY_INSTALL_DETAIL_V1 {}", bounded(&format!("dependency skipped; {}", plain(&error)))); ++ } ++ ++ tokio::fs::remove_dir_all(&keys).await.ok(); ++ progress.complete(true); ++ ExitCode::SUCCESS ++} ++ ++/// Installs every framework the title declares that is not there yet. ++/// ++/// Reports the first failure rather than stopping: a title whose framework is ++/// missing still installs, and the launch tries again. ++pub(crate) async fn ensure_frameworks( ++ delivery: &reqwest::Client, ++ destination: &Path, ++ region: &str, ++) -> Result<(), String> { ++ let mut failure = None; ++ for dependency in dependencies(destination) { ++ let marker = destination.join(FRAMEWORK_DIR).join(&dependency).join(INSTALLED); ++ if marker.is_file() { ++ continue; ++ } ++ match install_framework(delivery, destination, &dependency, region).await { ++ Ok(()) => eprintln!("NEXUS_LEGACY_INSTALL_DETAIL_V1 {}", bounded(&format!("framework {} installed", plain(&dependency)))), ++ Err(error) => { ++ eprintln!("NEXUS_LEGACY_INSTALL_DETAIL_V1 {}", bounded(&format!("framework {} skipped {}", plain(&dependency), plain(&error)))); ++ failure.get_or_insert(format!("{dependency}: {error}")); ++ } ++ } ++ } ++ match failure { ++ Some(error) => Err(error), ++ None => Ok(()), ++ } ++} ++/// Framework packages the manifest asks for, in declaration order. ++/// ++/// Reading the attribute rather than parsing XML keeps this off a new dependency; ++/// the manifest is small and the element has one shape. ++pub(crate) fn dependencies(destination: &Path) -> Vec { ++ let Some(manifest) = [LEGACY_MANIFEST, MANIFEST] ++ .iter() ++ .map(|name| destination.join(name)) ++ .find(|path| path.is_file()) ++ else { ++ return Vec::new(); ++ }; ++ let Ok(text) = std::fs::read_to_string(manifest) else { ++ return Vec::new(); ++ }; ++ let mut names: Vec = Vec::new(); ++ for chunk in text.split("').next() else { continue }; ++ let Some(start) = tag.find("Name=\"") else { continue }; ++ let rest = &tag[start + "Name=\"".len()..]; ++ let Some(end) = rest.find('"') else { continue }; ++ let name = rest[..end].trim(); ++ if !name.is_empty() && !names.iter().any(|seen| seen == name) { ++ names.push(name.to_string()); ++ } ++ } ++ names ++} ++ ++/// The COM class the manifest names as the application's entry point. ++/// ++/// A packaged Win32 program names `Windows.FullTrustApplication` and starts like ++/// any other executable. A UWP application names its own class instead and expects ++/// the app model to create it, which no Win32 loader does. ++pub(crate) fn entry_point(destination: &Path) -> Option { ++ let manifest = [LEGACY_MANIFEST, MANIFEST] ++ .iter() ++ .map(|name| destination.join(name)) ++ .find(|path| path.is_file())?; ++ application_entry(&std::fs::read_to_string(manifest).ok()?) ++} ++ ++/// The activation of a manifest's first application: its `EntryPoint`, or `windowsApp` ++/// when it declares that runtime behaviour instead of an entry point. ++fn application_entry(text: &str) -> Option { ++ use quick_xml::events::Event; ++ let mut reader = quick_xml::Reader::from_str(text); ++ loop { ++ match reader.read_event().ok()? { ++ Event::Start(tag) | Event::Empty(tag) if tag.local_name().into_inner() == "Application" => { ++ let mut entry = None; ++ let mut behavior = None; ++ for attribute in tag.attributes().flatten() { ++ let value = attribute.unescape_value().ok()?.trim().to_string(); ++ match attribute.key.local_name().into_inner() { ++ "EntryPoint" => entry = Some(value), ++ "RuntimeBehavior" => behavior = Some(value), ++ _ => {} ++ } ++ } ++ return match behavior.as_deref() { ++ Some(value) if value.eq_ignore_ascii_case("windowsApp") => Some("windowsApp".to_string()), ++ Some(value) if value.eq_ignore_ascii_case("packagedClassicApp") || value.eq_ignore_ascii_case("win32App") => None, ++ _ => entry.filter(|entry| !entry.is_empty()), ++ }; ++ } ++ Event::Eof => return None, ++ _ => {} ++ } ++ } ++} ++ ++/// Downloads one framework package and lays its DLLs beside the title. ++/// ++/// Windows resolves a packaged title's frameworks through the package graph. An ++/// unpacked folder has no graph, and the loader searches the executable's own ++/// directory, so the framework's libraries go there. ++/// ++/// The catalogue names the product but not a package the Xbox Live content ++/// service serves, so the bytes come from the same Windows Update category the ++/// Store client would use, and they arrive as a plain zip rather than EAppx. ++async fn install_framework( ++ delivery: &reqwest::Client, ++ destination: &Path, ++ name: &str, ++ region: &str, ++) -> Result<(), String> { ++ // Framework products from Microsoft publish under this publisher hash; any ++ // other publisher cannot be located by family name alone. ++ let family = format!("{name}_8wekyb3d8bbwe"); ++ let lookup = format!( ++ "https://displaycatalog.mp.microsoft.com/v7.0/products/lookup?alternateId=PackageFamilyName&value={family}&market={region}&languages=en-US&fieldsTemplate=Details" ++ ); ++ let response = delivery ++ .get(lookup) ++ .timeout(Duration::from_secs(20)) ++ .send() ++ .await ++ .map_err(|_| "catalogue unreachable".to_string())?; ++ if !response.status().is_success() { ++ return Err(format!("catalogue answered {}", response.status().as_u16())); ++ } ++ let document: serde_json::Value = response.json().await.map_err(|_| "catalogue answer unreadable".to_string())?; ++ let category = framework_category(&document).ok_or_else(|| "no update category was listed".to_string())?; ++ ++ let published = crate::commands::store_delivery::resolve_frameworks(delivery, &category).await?; ++ if published.files.is_empty() { ++ return Err("the category listed no files".to_string()); ++ } ++ ++ let staging = destination.join(CONTAINER_DIR); ++ tokio::fs::create_dir_all(&staging).await.map_err(|error| format!("staging folder failed: {error}"))?; ++ let unpacked = destination.join(FRAMEWORK_DIR).join(name); ++ if let Some(parent) = unpacked.parent() { ++ tokio::fs::create_dir_all(parent).await.map_err(|error| format!("framework folder failed: {error}"))?; ++ } ++ let trial = staging.join("framework-trial"); ++ // The category lists one package per architecture under names that are only ++ // identifiers, so each is unpacked until one declares x64 in its manifest. ++ if unpacked.is_dir() { ++ withdraw_libraries(&unpacked, destination); ++ } ++ let mut reasons: Vec = Vec::new(); ++ for file in published.files.iter().take(8) { ++ let Some(file_name) = Path::new(&file.name).file_name() else { continue }; ++ let container = staging.join(file_name); ++ let response = match delivery.get(&file.url).send().await { ++ Ok(response) if response.status().is_success() => response, ++ Ok(response) => { ++ reasons.push(format!("file refused with {}", response.status().as_u16())); ++ continue; ++ } ++ Err(_) => { ++ reasons.push("file unreachable".to_string()); ++ continue; ++ } ++ }; ++ let written = tokio::fs::File::create(&container) ++ .await ++ .map_err(|error| format!("download write failed: {error}"))?; ++ let mut written = written; ++ let mut stream = response.bytes_stream(); ++ let mut failed = None; ++ while let Some(chunk) = stream.next().await { ++ match chunk { ++ Ok(chunk) => { ++ if let Err(error) = written.write_all(&chunk).await { ++ failed = Some(format!("download write failed: {error}")); ++ break; ++ } ++ } ++ Err(_) => { ++ failed = Some("download interrupted".to_string()); ++ break; ++ } ++ } ++ } ++ written.flush().await.ok(); ++ drop(written); ++ if let Some(error) = failed { ++ tokio::fs::remove_file(&container).await.ok(); ++ reasons.push(error); ++ continue; ++ } ++ ++ let attempt = trial.join("a"); ++ tokio::fs::remove_dir_all(&attempt).await.ok(); ++ let unpacked_ok = crate::commands::unzip::extract(&container, &attempt); ++ tokio::fs::remove_file(&container).await.ok(); ++ if let Err(error) = unpacked_ok { ++ reasons.push(plain(&error)); ++ continue; ++ } ++ let Some(chosen) = x64_package(&attempt) else { ++ reasons.push("not x64".to_string()); ++ continue; ++ }; ++ tokio::fs::remove_dir_all(&unpacked).await.ok(); ++ tokio::fs::rename(&chosen, &unpacked).await.map_err(|error| format!("framework move failed: {error}"))?; ++ copy_libraries(&unpacked, destination)?; ++ std::fs::write(unpacked.join(INSTALLED), name.as_bytes()).map_err(|error| format!("framework mark failed: {error}"))?; ++ tokio::fs::remove_dir_all(&trial).await.ok(); ++ return Ok(()); ++ } ++ tokio::fs::remove_dir_all(&trial).await.ok(); ++ Err(plain(&format!("no x64 package among {} listed {}", published.files.len(), reasons.join(" ")))) ++} ++ ++/// The folder holding the package that declares x64, however deep a bundle wraps it. ++fn x64_package(root: &Path) -> Option { ++ let mut level = vec![root.to_path_buf()]; ++ for _ in 0..3 { ++ let mut next = Vec::new(); ++ for folder in level { ++ let manifest = folder.join(LEGACY_MANIFEST); ++ if manifest.is_file() { ++ let text = std::fs::read_to_string(&manifest).unwrap_or_default().to_ascii_lowercase(); ++ if text.contains("processorarchitecture=\"x64\"") { ++ return Some(folder); ++ } ++ } ++ if let Ok(entries) = std::fs::read_dir(&folder) { ++ next.extend(entries.filter_map(Result::ok).map(|entry| entry.path()).filter(|path| path.is_dir())); ++ } ++ } ++ if next.is_empty() { ++ break; ++ } ++ level = next; ++ } ++ None ++} ++ ++/// The Windows Update category of the framework's x64 package, or of whichever ++/// package the product lists first when no package names an architecture. ++fn framework_category(document: &serde_json::Value) -> Option { ++ let mut fallback: Option = None; ++ for product in document["Products"].as_array()? { ++ for sku in product["DisplaySkuAvailabilities"].as_array().into_iter().flatten() { ++ for package in sku["Sku"]["Properties"]["Packages"].as_array().into_iter().flatten() { ++ let Some(category) = package["FulfillmentData"]["WuCategoryId"].as_str() else { continue }; ++ if category.is_empty() { ++ continue; ++ } ++ let x64 = package["Architectures"] ++ .as_array() ++ .into_iter() ++ .flatten() ++ .any(|arch| arch.as_str() == Some("x64")); ++ if x64 { ++ return Some(category.to_string()); ++ } ++ fallback.get_or_insert_with(|| category.to_string()); ++ } ++ } ++ } ++ fallback ++} ++ ++/// Removes the libraries an earlier attempt copied, so a replaced framework does ++/// not leave the old architecture's files beside the title. ++/// ++/// Only names this code recorded as copied are removed. A title can ship a DLL of ++/// the same name, and `copy_libraries` leaves such a file alone; deleting by ++/// basename would then remove the title's own library. ++fn withdraw_libraries(from: &Path, to: &Path) { ++ let Ok(list) = std::fs::read_to_string(from.join(COPIED)) else { return }; ++ for name in list.lines().filter(|line| !line.trim().is_empty()) { ++ if Path::new(name).components().count() != 1 { ++ continue; ++ } ++ let _ = std::fs::remove_file(to.join(name)); ++ } ++} ++ ++/// Copies the framework's libraries next to the title, never over its own files, ++/// and records what it copied so a later attempt can take exactly that back. ++fn copy_libraries(from: &Path, to: &Path) -> Result<(), String> { ++ let mut copied: Vec = Vec::new(); ++ copy_libraries_into(from, to, &mut copied)?; ++ std::fs::write(from.join(COPIED), copied.join("\n")).map_err(|error| format!("framework copy list failed: {error}"))?; ++ Ok(()) ++} ++ ++fn copy_libraries_into(from: &Path, to: &Path, copied: &mut Vec) -> Result<(), String> { ++ let entries = std::fs::read_dir(from).map_err(|error| format!("framework read failed: {error}"))?; ++ for entry in entries.filter_map(Result::ok) { ++ let path = entry.path(); ++ if path.is_dir() { ++ copy_libraries_into(&path, to, copied)?; ++ continue; ++ } ++ let named = path.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("dll")); ++ if !named { ++ continue; ++ } ++ let Some(file_name) = path.file_name() else { continue }; ++ let target = to.join(file_name); ++ if target.exists() { ++ continue; ++ } ++ std::fs::copy(&path, &target).map_err(|error| format!("framework copy failed: {error}"))?; ++ copied.push(file_name.to_string_lossy().into_owned()); ++ } ++ Ok(()) ++} ++ ++fn has_manifest(folder: &Path) -> bool { std::fs::read_dir(folder).is_ok_and(|entries| { ++ entries.filter_map(Result::ok).any(|entry| { ++ let name = entry.file_name(); ++ let named = name.eq_ignore_ascii_case(MANIFEST) || name.eq_ignore_ascii_case(LEGACY_MANIFEST); ++ named && entry.file_type().is_ok_and(|kind| kind.is_file()) ++ }) ++ }) ++} ++ ++/// Lifts the contents of a single nested package directory to the game folder. ++/// Add-on content is stored without a manifest, so nothing to lift is not an ++/// error; anything other than exactly one candidate is, because a wrong guess ++/// here would move game files. ++/// ++/// An install over a folder that already holds a manifest is an update: the new ++/// package is lifted over the old one file by file, since leaving it nested would ++/// report success while the previous version stayed in place. ++fn hoist(destination: &Path) -> Result<(), String> { ++ let updating = has_manifest(destination); ++ let mut candidates = nested_packages(destination); ++ if candidates.is_empty() { ++ return Ok(()); ++ } ++ if candidates.len() != 1 { ++ return Err(format!( ++ "Extraction left {} package folders; expected exactly one", ++ candidates.len() ++ )); ++ } ++ let inner = candidates.remove(0); ++ for entry in std::fs::read_dir(&inner) ++ .map_err(|error| format!("Could not list the package folder: {error}"))? ++ .filter_map(Result::ok) ++ { ++ let target = destination.join(entry.file_name()); ++ if target.exists() { ++ if !updating { ++ return Err(format!("Extraction would overwrite {}", target.display())); ++ } ++ let replaced = if target.is_dir() { ++ std::fs::remove_dir_all(&target) ++ } else { ++ std::fs::remove_file(&target) ++ }; ++ replaced.map_err(|error| format!("Could not replace an installed file: {error}"))?; ++ } ++ std::fs::rename(entry.path(), &target) ++ .map_err(|error| format!("Could not move an extracted file: {error}"))?; ++ } ++ std::fs::remove_dir(&inner).map_err(|error| format!("Could not remove the package folder: {error}"))?; ++ Ok(()) ++} ++ ++/// Folders below [root] that carry a manifest, at the depth a nested bundle can ++/// write one. A bundle of a bundle is the deepest the extractor produces. ++fn nested_packages(root: &Path) -> Vec { ++ let mut found = Vec::new(); ++ let mut level = vec![root.to_path_buf()]; ++ for _ in 0..3 { ++ let mut next = Vec::new(); ++ for folder in level { ++ let Ok(entries) = std::fs::read_dir(&folder) else { continue }; ++ for entry in entries.filter_map(Result::ok) { ++ let path = entry.path(); ++ if !path.is_dir() || path.ends_with(CONTAINER_DIR) || path.ends_with(KEYS_DIR) || path.ends_with(FRAMEWORK_DIR) { ++ continue; ++ } ++ if has_manifest(&path) { ++ found.push(path); ++ } else { ++ next.push(path); ++ } ++ } ++ } ++ if next.is_empty() { ++ break; ++ } ++ level = next; ++ } ++ found ++} ++ ++#[cfg(test)] ++mod tests { ++ use super::*; ++ ++ fn scratch(name: &str) -> PathBuf { ++ let path = std::env::temp_dir().join(format!("xodus-legacy-{name}-{}", std::process::id())); ++ let _ = std::fs::remove_dir_all(&path); ++ std::fs::create_dir_all(&path).unwrap(); ++ path ++ } ++ ++ #[test] ++ fn only_eappx_containers_are_treated_as_legacy() { ++ for name in ["a.eappx", "A.EAPPX", "game.eappxbundle", "Game.EAppxBundle"] { ++ assert!(is_legacy_name(name), "{name} should be legacy"); ++ } ++ for name in ["game.msixvc", "game.appx", "game.zip", "eappx", "notes.txt"] { ++ assert!(!is_legacy_name(name), "{name} should not be legacy"); ++ } ++ } ++ ++ #[test] ++ fn free_bytes_reads_the_available_column() { ++ let root = scratch("free"); ++ let free = free_bytes(&root).expect("df should answer for an existing folder"); ++ assert!(free > 0, "a writable filesystem reports some free space"); ++ std::fs::remove_dir_all(&root).ok(); ++ } ++ ++ #[test] ++ fn hoist_lifts_a_lone_bundle_member_to_the_game_folder() { ++ let root = scratch("hoist"); ++ let inner = root.join("Microsoft.SunriseBaseGame"); ++ std::fs::create_dir_all(&inner).unwrap(); ++ std::fs::write(inner.join(MANIFEST), "").unwrap(); ++ std::fs::write(inner.join("ForzaHorizon4.exe"), b"MZ").unwrap(); ++ ++ hoist(&root).unwrap(); ++ ++ assert!(root.join(MANIFEST).is_file()); ++ assert!(root.join("ForzaHorizon4.exe").is_file()); ++ assert!(!inner.exists()); ++ std::fs::remove_dir_all(&root).ok(); ++ } ++ ++ #[test] ++ fn hoist_lifts_a_legacy_package_folder_too() { ++ let root = scratch("legacy-hoist"); ++ let inner = root.join("Microsoft.SunriseBaseGame_2023.1122.1704.2_x64__8wekyb3d8bbwe"); ++ std::fs::create_dir_all(&inner).unwrap(); ++ std::fs::write(inner.join(LEGACY_MANIFEST), "").unwrap(); ++ std::fs::write(inner.join("ForzaHorizon4.exe"), b"MZ").unwrap(); ++ ++ hoist(&root).unwrap(); ++ ++ assert!(root.join(LEGACY_MANIFEST).is_file()); ++ assert!(root.join("ForzaHorizon4.exe").is_file()); ++ assert!(!inner.exists()); ++ std::fs::remove_dir_all(&root).ok(); ++ } ++ ++ #[test] ++ fn hoist_leaves_a_folder_that_already_has_the_manifest_alone() { ++ let root = scratch("flat"); ++ std::fs::write(root.join(MANIFEST), "").unwrap(); ++ std::fs::create_dir_all(root.join("Content")).unwrap(); ++ ++ hoist(&root).unwrap(); ++ ++ assert!(root.join("Content").is_dir()); ++ std::fs::remove_dir_all(&root).ok(); ++ } ++ ++ #[test] ++ fn hoist_replaces_the_previous_install_when_the_manifest_is_already_there() { ++ let root = scratch("update"); ++ std::fs::write(root.join(LEGACY_MANIFEST), "").unwrap(); ++ std::fs::write(root.join("ForzaHorizon4.exe"), b"old").unwrap(); ++ let inner = root.join("Microsoft.SunriseBaseGame"); ++ std::fs::create_dir_all(root.join("Content")).unwrap(); ++ std::fs::create_dir_all(inner.join("Content")).unwrap(); ++ std::fs::write(inner.join(LEGACY_MANIFEST), "").unwrap(); ++ std::fs::write(inner.join("ForzaHorizon4.exe"), b"new").unwrap(); ++ std::fs::write(inner.join("Content").join("pack.bin"), b"data").unwrap(); ++ ++ hoist(&root).unwrap(); ++ ++ assert_eq!(std::fs::read(root.join("ForzaHorizon4.exe")).unwrap(), b"new"); ++ assert!(root.join("Content").join("pack.bin").is_file()); ++ assert!(!inner.exists()); ++ std::fs::remove_dir_all(&root).ok(); ++ } ++ ++ #[test] ++ fn hoist_finds_a_manifest_inside_a_nested_bundle() { ++ let root = scratch("deep"); ++ let inner = root.join("bundle").join("Microsoft.SunriseBaseGame"); ++ std::fs::create_dir_all(&inner).unwrap(); ++ std::fs::write(inner.join(LEGACY_MANIFEST), "").unwrap(); ++ std::fs::write(inner.join("ForzaHorizon4.exe"), b"MZ").unwrap(); ++ ++ hoist(&root).unwrap(); ++ ++ assert!(root.join(LEGACY_MANIFEST).is_file()); ++ assert!(root.join("ForzaHorizon4.exe").is_file()); ++ std::fs::remove_dir_all(&root).ok(); ++ } ++ ++ #[test] ++ fn withdrawing_a_framework_keeps_a_dll_it_never_copied() { ++ let root = scratch("withdraw"); ++ let framework = root.join("framework"); ++ std::fs::create_dir_all(&framework).unwrap(); ++ std::fs::write(framework.join("vcruntime140.dll"), b"framework").unwrap(); ++ std::fs::write(framework.join("title-only.dll"), b"framework").unwrap(); ++ std::fs::write(root.join("title-only.dll"), b"title").unwrap(); ++ ++ std::fs::write(framework.join(COPIED), "vcruntime140.dll").unwrap(); ++ withdraw_libraries(&framework, &root); ++ ++ assert!(!root.join("vcruntime140.dll").exists()); ++ assert_eq!(std::fs::read(root.join("title-only.dll")).unwrap(), b"title"); ++ std::fs::remove_dir_all(&root).ok(); ++ } ++ ++ #[test] ++ fn hoist_refuses_to_guess_between_two_package_folders() { ++ let root = scratch("ambiguous"); ++ for name in ["one", "two"] { ++ let inner = root.join(name); ++ std::fs::create_dir_all(&inner).unwrap(); ++ std::fs::write(inner.join(MANIFEST), "").unwrap(); ++ } ++ ++ assert!(hoist(&root).is_err()); ++ std::fs::remove_dir_all(&root).ok(); ++ } ++ ++ #[test] ++ fn entry_point_separates_a_uwp_application_from_a_packaged_desktop_one() { ++ let root = scratch("entry"); ++ std::fs::write( ++ root.join(LEGACY_MANIFEST), ++ r#""#, ++ ) ++ .unwrap(); ++ assert_eq!(entry_point(&root).as_deref(), Some("Windows.FullTrustApplication")); ++ ++ std::fs::write( ++ root.join(LEGACY_MANIFEST), ++ r#""#, ++ ) ++ .unwrap(); ++ assert_eq!(entry_point(&root).as_deref(), Some("Forza.App")); ++ assert_eq!(application_entry("").as_deref(), Some("Forza.App")); ++ assert_eq!(application_entry(r#""#).as_deref(), Some("windowsApp")); ++ assert_eq!(application_entry(r#""#), None); ++ assert_eq!(application_entry(r#""#), None); ++ assert_eq!(application_entry(r#""#).as_deref(), Some("windowsApp")); ++ std::fs::remove_dir_all(&root).ok(); ++ } ++ ++ #[test] ++ fn download_staging_folders_are_never_hoisted() { ++ let root = scratch("staging"); ++ std::fs::create_dir_all(root.join(CONTAINER_DIR)).unwrap(); ++ std::fs::write(root.join(CONTAINER_DIR).join(MANIFEST), "").unwrap(); ++ ++ hoist(&root).unwrap(); ++ ++ assert!(root.join(CONTAINER_DIR).join(MANIFEST).is_file()); ++ std::fs::remove_dir_all(&root).ok(); ++ } ++ ++ #[test] ++ fn add_on_content_without_a_manifest_is_left_in_place() { ++ let root = scratch("content"); ++ std::fs::create_dir_all(root.join("Content")).unwrap(); ++ std::fs::write(root.join("Content").join("pack.bin"), b"data").unwrap(); ++ ++ hoist(&root).unwrap(); ++ ++ assert!(root.join("Content").join("pack.bin").is_file()); ++ std::fs::remove_dir_all(&root).ok(); ++ } ++} +diff --git a/crates/xodus-cli/src/commands/license.rs b/crates/xodus-cli/src/commands/license.rs +index b9fd91c..fbae301 100644 +--- a/crates/xodus-cli/src/commands/license.rs ++++ b/crates/xodus-cli/src/commands/license.rs +@@ -1,8 +1,6 @@ + use std::process::ExitCode; + + use base64::{Engine, engine::general_purpose::STANDARD}; +-use tokio::fs::OpenOptions; +-use tokio::io::AsyncWriteExt; + use xodus::tokens::TokenManager; + + use crate::license::get_license; +@@ -14,45 +12,47 @@ pub async fn run( + market: String, + ciks: String, + ) -> ExitCode { +- let license = get_license(client, tokens, content_id, market, None, false).await; +- if let Err(err) = license { +- eprintln!("{}", err); +- return ExitCode::FAILURE; ++ match dump(client, tokens, content_id, market, ciks).await { ++ Ok(()) => ExitCode::SUCCESS, ++ Err(err) => { ++ eprintln!("{}", err); ++ ExitCode::FAILURE ++ } + } ++} + +- let (key, game_splicense) = license.unwrap(); +- tokio::fs::create_dir_all(&ciks).await.unwrap(); ++/// Writes the content keys of `content_id` to `ciks`, or returns why Microsoft refused them. ++pub async fn dump( ++ client: &reqwest::Client, ++ tokens: &TokenManager, ++ content_id: String, ++ market: String, ++ ciks: String, ++) -> Result<(), String> { ++ let (key, game_splicense) = get_license(client, tokens, content_id, market, None, false).await?; ++ let unwritten = |error: std::io::Error| format!("The license was granted, but its content keys could not be written: {error}"); ++ tokio::fs::create_dir_all(&ciks).await.map_err(unwritten)?; + // eappx-rs reads a text [Keys] file with base64 Key IDs, while the .cik + // format below is the binary form other tools expect. Write both so the + // same license dump serves either extractor. +- let mut eappx_keys = String::from("[Keys]\n"); ++ let mut eappx_keys = String::from("[Keys] ++"); + for (uuid, content_key) in game_splicense.content_keys { +- let unpacked = content_key.unpack(&key).expect("failed to unpack"); +- let mut file = OpenOptions::new() +- .create(true) +- .write(true) +- .open(format!("{ciks}/{uuid}.cik")) +- .await +- .unwrap(); ++ let unpacked = content_key ++ .unpack(&key) ++ .map_err(|_| "The content key could not be authenticated. Retry the installation or sign in again.".to_string())?; + let uuid_buf = uuid.to_bytes_le(); +- file.write_all(&uuid_buf).await.unwrap(); +- file.write_all(&*unpacked).await.unwrap(); +- file.flush().await.unwrap(); ++ let mut cik = uuid_buf.to_vec(); ++ cik.extend_from_slice(&*unpacked); ++ tokio::fs::write(format!("{ciks}/{uuid}.cik"), cik).await.map_err(unwritten)?; + eappx_keys.push_str(&format!( +- "\"{}\" \"{}\"\n", ++ "\"{}\" \"{}\" ++", + STANDARD.encode(uuid_buf), + STANDARD.encode(&*unpacked), + )); + } +- let mut keys_file = OpenOptions::new() +- .create(true) +- .write(true) +- .truncate(true) +- .open(format!("{ciks}/eappx-keys.txt")) +- .await +- .unwrap(); +- keys_file.write_all(eappx_keys.as_bytes()).await.unwrap(); +- keys_file.flush().await.unwrap(); ++ tokio::fs::write(format!("{ciks}/eappx-keys.txt"), eappx_keys).await.map_err(unwritten)?; + +- ExitCode::SUCCESS ++ Ok(()) + } +diff --git a/crates/xodus-cli/src/commands/store_delivery.rs b/crates/xodus-cli/src/commands/store_delivery.rs +new file mode 100644 +index 0000000..7fec6e5 +--- /dev/null ++++ b/crates/xodus-cli/src/commands/store_delivery.rs +@@ -0,0 +1,577 @@ ++//! Windows Update delivery for Store packages. ++//! ++//! The Xbox content service (`GetBasePackage`) serves MSIXVC titles but answers a ++//! legacy desktop bundle with `PackageFound: true` and an empty file list, on every ++//! request shape. Measured on Forza Horizon 4: its EAppxBundle (85.2 GB) is never ++//! served that way, while the same product's console XVC is served normally as ++//! `.xsp` chunks. ++//! ++//! Those bytes are delivered through Windows Update instead, which is what the ++//! Store client itself uses for legacy packages and which needs no Xbox Live auth. ++//! Three SOAP calls do it: an anonymous cookie, a sync scoped to the product's ++//! `WuCategoryId`, then a signed URL for each file whose digest matches. ++//! ++//! Two details cost time to learn and are relied on below: ++//! * the update fragments inside `` are escaped twice, so they have to be ++//! decoded twice before they contain any tags; ++//! * a file's content digest, not its id, is what ties it to a return URL. ++ ++use std::time::Duration; ++ ++/// The service the Store client talks to. `fe3cr` and `fe3` are both live. ++const BASE: &str = "https://fe3cr.delivery.mp.microsoft.com/ClientWebService/client.asmx"; ++const SECURED: &str = "https://fe3cr.delivery.mp.microsoft.com/ClientWebService/client.asmx/secured"; ++const NAMESPACE: &str = "http://www.microsoft.com/SoftwareDistribution/Server/ClientWebService"; ++const AGENT: &str = "Windows-Update-Agent/10.0.10011.16384 Client-Protocol/2.1"; ++ ++/// The update service is issued from Microsoft's Windows Update PKI, whose root is ++/// distributed by Windows Update itself rather than by Mozilla, so neither this ++/// device's bundle nor a normal Linux install trusts it and every handshake ends ++/// with "unable to get local issuer certificate". Only the roots those hosts chain ++/// to are added, on a client used for this path alone. ++/// ++/// `wu-root.pem` is Microsoft ECC Product Root Certificate Authority 2018, fetched ++/// from the issuer URL in the server's own authority-information extension ++/// (`www.microsoft.com/pkiops/certs/...`). Its serial 14982666DC7CCD8F4053677BB999EC85 ++/// and SHA-1 06F1AA330B927B753A40E68CDF22E34BCBEF3352 match the copy Windows ships ++/// in its own root store, and 2043-02-27 20:50:46 GMT is its expiry. ++const UPDATE_ROOT: &str = include_str!("wu-root.pem"); ++ ++/// A client for the update service and its download hosts: the system trust store ++/// plus the one root above. ++pub fn client() -> Result { ++ let root = reqwest::Certificate::from_pem(UPDATE_ROOT.as_bytes()) ++ .map_err(|error| format!("the pinned update root could not be read: {error}"))?; ++ reqwest::Client::builder() ++ .user_agent(AGENT) ++ .add_root_certificate(root) ++ .build() ++ .map_err(|error| format!("the update client could not be created: {error}")) ++} ++ ++/// Timestamps are not validated by the service, so fixed values keep this free of ++/// a date dependency, as the working reference implementations do. ++const CREATED: &str = "2017-08-05T02:03:05.038Z"; ++const EXPIRES: &str = "2044-08-02T20:09:03Z"; ++ ++/// The device reports itself as a retail Windows desktop: the catalogue serves the ++/// desktop package for this shape, and `App=WU_STORE` is what exposes app categories. ++const ATTRIBUTES: &str = concat!( ++ "BranchReadinessLevel=CB;CurrentBranch=;OEMModel=Virtual Machine;FlightRing=Retail;", ++ "AttrDataVer=21;SystemManufacturer=Microsoft Corporation;InstallLanguage=en-US;", ++ "OSUILocale=en-US;InstallationType=Client;FlightingBranchName=;", ++ "FirmwareVersion=Hyper-V UEFI Release v2.5;SystemProductName=Virtual Machine;OSSkuId=48;", ++ "FlightContent=Mainline;App=WU_STORE;OEMName_Uncleaned=Microsoft Corporation;", ++ "AppVer=0.0.0.0;OSArchitecture=AMD64;SystemSKU=None;UpdateManagementGroup=2;", ++ "IsFlightingEnabled=0;IsDeviceRetailDemo=0;TelemetryLevel=3;OSVersion=10.0.22621.1;", ++ "DeviceFamily=Windows.Desktop;" ++); ++ ++/// Baseline category ids a Windows client always claims to have installed. The ++/// service silently expects them; without them the sync returns no metadata. ++const BASELINE: &[u32] = &[ ++ 1, 2, 3, 10, 11, 17, 19, 2359974, 2359977, 5143990, 5169043, 5169044, 5169047, 8788830, 8806526, ++ 9125350, 9154769, 10809856, 23110993, 23110994, 23110995, 23110996, 23110999, 23111000, ++ 23111001, 23111002, 23111003, 23111004, 24513870, 28880263, 30077688, 30486944, 59830006, ++ 59830007, 59830008, 60484010, 62450018, 62450019, 62450020, 98959022, 98959023, 98959024, ++ 98959025, 98959026, 105939029, 105995585, 106017178, 107825194, 117765322, 129905029, ++ 130040030, 130040031, 130040032, 130040033, 133399034, 138372035, 138372036, 139536037, ++ 139536038, 139536039, 139536040, 142045136, 158941041, 158941042, 158941043, 158941044, ++ 159776047, 160733048, 160733049, 160733050, 160733051, 160733055, 160733056, 161870057, ++ 161870058, 161870059, ++]; ++ ++/// One downloadable package file. ++pub struct DeliveryFile { ++ pub name: String, ++ pub url: String, ++ pub size: u64, ++} ++ ++/// A product's installable files, plus the content id its keys are licensed under. ++pub struct Delivery { ++ pub content_id: String, ++ pub files: Vec, ++} ++ ++fn unescape(text: &str) -> String { ++ // Fragments are escaped twice, so a single pass leaves `<Files>` behind. ++ let mut current = text.to_string(); ++ for _ in 0..3 { ++ let next = current ++ .replace("<", "<") ++ .replace(">", ">") ++ .replace(""", "\"") ++ .replace("'", "'") ++ .replace("&", "&"); ++ if next == current { ++ break; ++ } ++ current = next; ++ } ++ current ++} ++ ++fn element(text: &str, tag: &str) -> Option { ++ let open = format!("<{tag}>"); ++ let close = format!(""); ++ let start = text.find(&open)? + open.len(); ++ let end = start + text[start..].find(&close)?; ++ Some(text[start..end].to_string()) ++} ++ ++fn blocks(text: &str, tag: &str) -> Vec { ++ let open = format!("<{tag}>"); ++ let close = format!(""); ++ let mut found = Vec::new(); ++ let mut rest = text; ++ while let Some(start) = rest.find(&open) { ++ let after = start + open.len(); ++ let Some(length) = rest[after..].find(&close) else { break }; ++ found.push(rest[after..after + length].to_string()); ++ rest = &rest[after + length + close.len()..]; ++ } ++ found ++} ++ ++fn attribute(text: &str, name: &str) -> Option { ++ let needle = format!("{name}=\""); ++ let start = text.find(&needle)? + needle.len(); ++ let end = start + text[start..].find('"')?; ++ Some(text[start..end].to_string()) ++} ++ ++async fn soap(client: &reqwest::Client, url: &str, body: &str) -> Result { ++ let response = client ++ .post(url) ++ .header("Content-Type", "application/soap+xml; charset=utf-8") ++ .header("User-Agent", AGENT) ++ .timeout(Duration::from_secs(60)) ++ .body(body.to_string()) ++ .send() ++ .await ++ .map_err(|error| format!("update service unreachable: {error}"))?; ++ if !response.status().is_success() { ++ return Err(format!("update service returned HTTP {}", response.status().as_u16())); ++ } ++ let text = response.text().await.map_err(|_| "update service reply unreadable".to_string())?; ++ Ok(unescape(&text)) ++} ++ ++fn envelope(action: &str, to: &str, body: &str) -> String { ++ format!( ++ r#"http://www.microsoft.com/SoftwareDistribution/Server/ClientWebService/{action}urn:uuid:{message}{to}{CREATED}{EXPIRES}{body}"#, ++ action = action, ++ to = to, ++ message = uuid::Uuid::new_v4(), ++ body = body, ++ ) ++} ++ ++/// Reads the `WuCategoryId` the catalogue carries for the product's packages. ++async fn category(client: &reqwest::Client, product: &str, market: &str) -> Result { ++ let url = format!( ++ "https://displaycatalog.mp.microsoft.com/v7.0/products/{product}?market={market}&languages=en,neutral" ++ ); ++ let text = client ++ .get(url) ++ .timeout(Duration::from_secs(30)) ++ .send() ++ .await ++ .map_err(|_| "Store metadata request failed".to_string())? ++ .text() ++ .await ++ .map_err(|_| "Store metadata reply unreadable".to_string())?; ++ let start = text ++ .find("\"WuCategoryId\":\"") ++ .ok_or("This product has no Windows Update category, so it has no legacy package")?; ++ let rest = &text[start + "\"WuCategoryId\":\"".len()..]; ++ let end = rest.find('"').ok_or("Unreadable Windows Update category")?; ++ Ok(rest[..end].to_string()) ++} ++ ++async fn cookie(client: &reqwest::Client) -> Result<(String, String), String> { ++ let body = format!( ++ r#"2016-07-27T07:18:09Z2015-10-21T17:01:07.1472913Z{CREATED}2.50"# ++ ); ++ let reply = soap(client, BASE, &envelope("GetCookie", BASE, &body)).await?; ++ let encrypted = element(&reply, "EncryptedData").ok_or("Update service issued no session cookie")?; ++ let expiration = element(&reply, "Expiration").unwrap_or_else(|| EXPIRES.to_string()); ++ Ok((encrypted, expiration)) ++} ++ ++struct Revision { ++ update_id: String, ++ revision: String, ++ digest: String, ++ name: String, ++ size: u64, ++ moniker: String, ++ content_id: String, ++} ++ ++fn package_identity(moniker: &str) -> Option<((String, String), Vec)> { ++ let mut parts = moniker.split('_'); ++ let name = parts.next()?.to_ascii_lowercase(); ++ let version = parts.next()?.split('.').map(|part| part.parse::().ok()).collect::>>()?; ++ let arch = parts.next()?.to_ascii_lowercase(); ++ if name.is_empty() { ++ return None; ++ } ++ Some(((name, arch), version)) ++} ++ ++fn newest_builds(revisions: Vec) -> Vec { ++ let desktop: std::collections::HashSet = revisions ++ .iter() ++ .filter_map(|revision| package_identity(&revision.moniker)) ++ .filter(|((_, arch), _)| arch == "x64" || arch == "neutral") ++ .map(|((name, _), _)| name) ++ .collect(); ++ let mut newest: std::collections::HashMap<(String, String), Vec> = std::collections::HashMap::new(); ++ for revision in &revisions { ++ if let Some((key, version)) = package_identity(&revision.moniker) { ++ let entry = newest.entry(key).or_default(); ++ if version > *entry { ++ *entry = version; ++ } ++ } ++ } ++ let mut seen = std::collections::HashSet::new(); ++ revisions ++ .into_iter() ++ .filter(|revision| match package_identity(&revision.moniker) { ++ Some((key, version)) => { ++ newest.get(&key) == Some(&version) ++ && (!desktop.contains(&key.0) || key.1 == "x64" || key.1 == "neutral") ++ } ++ None => true, ++ }) ++ .filter(|revision| seen.insert(revision.name.to_ascii_lowercase())) ++ .collect() ++} ++ ++/// One packager per file: the revision identity and the digest are what the ++/// download URL is issued against. ++async fn revisions( ++ client: &reqwest::Client, ++ cookie: &str, ++ expiration: &str, ++ content_id: &str, ++ wanted: fn(&str) -> bool, ++) -> Result<(Vec, String), String> { ++ let baseline: String = BASELINE.iter().map(|id| format!("{id}")).collect(); ++ let body = format!( ++ r#"{expiration}{cookie}false{baseline}falsetrue{content_id}truefalseExtendeden-USenen-USfalse{ATTRIBUTES}Interactive=1;IsSeeker=0;"# ++ ); ++ let reply = soap(client, BASE, &envelope("SyncUpdates", BASE, &body)).await?; ++ ++ let core = blocks(&reply, "UpdateInfo"); ++ let extended = blocks(&reply, "ExtendedUpdateInfo"); ++ let Some(extended) = extended.first() else { ++ return Err("Update service returned no package metadata for this category".into()); ++ }; ++ let mut core_by_id: Vec<(String, String)> = Vec::new(); ++ for entries in &core { ++ if let (Some(id), Some(xml)) = (element(entries, "ID"), element(entries, "Xml")) { ++ core_by_id.push((id, xml)); ++ } ++ } ++ ++ let mut found = Vec::new(); ++ let mut package_content_id = String::new(); ++ for entries in blocks(extended, "Update") { ++ let (Some(id), Some(xml)) = (element(&entries, "ID"), element(&entries, "Xml")) else { continue }; ++ // The file list lives in one fragment and the identity the URL is issued ++ // against in the other, so both are needed for the same revision. ++ let Some((_, core_xml)) = core_by_id.iter().find(|(key, _)| *key == id) else { continue }; ++ let combined = format!("{xml}{core_xml}"); ++ if !combined.contains("` node. ++fn file_attributes(text: &str) -> Vec { ++ let mut found = Vec::new(); ++ let mut rest = text; ++ while let Some(start) = rest.find("') else { break }; ++ found.push(after[..end].trim_end_matches('/').to_string()); ++ rest = &after[end..]; ++ } ++ found ++} ++ ++async fn download_url( ++ client: &reqwest::Client, ++ cookie: &str, ++ expiration: &str, ++ revision: &Revision, ++) -> Result { ++ let body = format!( ++ r#"{expiration}{cookie}{update}{number}FileUrlFileDecryption{ATTRIBUTES}"#, ++ update = revision.update_id, ++ number = revision.revision ++ ); ++ let reply = soap(client, SECURED, &envelope("GetExtendedUpdateInfo2", SECURED, &body)).await?; ++ for location in blocks(&reply, "FileLocation") { ++ if element(&location, "FileDigest").as_deref() != Some(revision.digest.as_str()) { ++ continue; ++ } ++ if let Some(url) = element(&location, "Url") { ++ return Ok(url); ++ } ++ } ++ Err(format!("No download location was issued for {}", revision.name)) ++} ++ ++/// Resolves the legacy packages of a Store product through Windows Update. ++pub async fn resolve( ++ client: &reqwest::Client, ++ product: &str, ++ market: &str, ++) -> Result { ++ let category = category(client, product, market).await?; ++ resolve_category(client, &category).await ++} ++ ++/// Every build of a Store product Windows Update lists, newest first. Each build ++/// has its own content id, and Microsoft can refuse keys for one but not another. ++pub struct Builds { ++ cookie: String, ++ expiration: String, ++ category: String, ++ groups: Vec>, ++} ++ ++impl Builds { ++ pub fn len(&self) -> usize { ++ self.groups.len() ++ } ++ ++ pub fn content_id(&self, index: usize) -> String { ++ self.groups[index] ++ .first() ++ .map(|revision| revision.content_id.clone()) ++ .filter(|id| !id.is_empty()) ++ .unwrap_or_else(|| self.category.clone()) ++ } ++ ++ /// Download locations for one build, asked for only when that build is used. ++ pub async fn locate(&self, client: &reqwest::Client, index: usize) -> Result, String> { ++ let mut files = Vec::new(); ++ for revision in &self.groups[index] { ++ let url = download_url(client, &self.cookie, &self.expiration, revision).await?; ++ files.push(DeliveryFile { name: revision.name.clone(), url, size: revision.size }); ++ } ++ Ok(files) ++ } ++} ++ ++pub async fn resolve_builds(client: &reqwest::Client, product: &str, market: &str) -> Result { ++ let category = category(client, product, market).await?; ++ let (cookie, expiration) = cookie(client).await?; ++ let (found, _) = revisions(client, &cookie, &expiration, &category, title_container).await?; ++ let groups = builds_newest_first(found); ++ if groups.is_empty() { ++ return Err("Windows Update lists no package files for this product".into()); ++ } ++ Ok(Builds { cookie, expiration, category, groups }) ++} ++ ++fn title_container(name: &str) -> bool { ++ let lower = name.to_ascii_lowercase(); ++ lower.ends_with(".eappx") || lower.ends_with(".eappxbundle") ++} ++ ++fn builds_newest_first(revisions: Vec) -> Vec> { ++ let mut groups: Vec<(String, Vec)> = Vec::new(); ++ for revision in revisions { ++ match groups.iter_mut().find(|(id, _)| *id == revision.content_id) { ++ Some((_, group)) => group.push(revision), ++ None => groups.push((revision.content_id.clone(), vec![revision])), ++ } ++ } ++ let mut groups: Vec> = groups.into_iter().map(|(_, group)| newest_builds(group)).collect(); ++ let newest = |group: &Vec| { ++ group.iter().filter_map(|revision| package_identity(&revision.moniker)).map(|(_, version)| version).max() ++ }; ++ groups.sort_by(|a, b| newest(b).cmp(&newest(a))); ++ groups.into_iter().filter(|group| !group.is_empty()).collect() ++} ++ ++/// The packages a Windows Update category lists, in the containers a title is ++/// packed in. ++pub async fn resolve_category(client: &reqwest::Client, category: &str) -> Result { ++ resolve_wanted(client, category, true, |name| { ++ let lower = name.to_ascii_lowercase(); ++ lower.ends_with(".eappx") || lower.ends_with(".eappxbundle") ++ }) ++ .await ++} ++ ++/// The plain `.appx` packages a category lists, which is how a framework ships. ++pub async fn resolve_frameworks(client: &reqwest::Client, category: &str) -> Result { ++ resolve_wanted(client, category, false, |name| name.to_ascii_lowercase().ends_with(".appx")).await ++} ++ ++async fn resolve_wanted( ++ client: &reqwest::Client, ++ category: &str, ++ newest_only: bool, ++ wanted: fn(&str) -> bool, ++) -> Result { ++ let (cookie, expiration) = cookie(client).await?; ++ let (revisions, package_content_id) = revisions(client, &cookie, &expiration, category, wanted).await?; ++ let revisions = if newest_only { newest_builds(revisions) } else { revisions }; ++ if revisions.is_empty() { ++ return Err("Windows Update lists no package files for this product".into()); ++ } ++ let mut files = Vec::new(); ++ for revision in &revisions { ++ let url = download_url(client, &cookie, &expiration, revision).await?; ++ files.push(DeliveryFile { name: revision.name.clone(), url, size: revision.size }); ++ } ++ Ok(Delivery { ++ // A framework's revision carries no package content id, and only a title's ++ // keys are licensed, so the category stands in when none was named. ++ content_id: if package_content_id.is_empty() { ++ category.to_string() ++ } else { ++ package_content_id ++ }, ++ files, ++ }) ++} ++ ++#[cfg(test)] ++mod tests { ++ use super::*; ++ ++ #[test] ++ fn the_pinned_root_is_the_expected_microsoft_update_authority() { ++ // The PEM travels with the patch, so a swapped or truncated file must fail ++ // here rather than silently widening what the update client trusts. ++ assert_eq!(UPDATE_ROOT.matches("BEGIN CERTIFICATE").count(), 1); ++ let der = UPDATE_ROOT ++ .lines() ++ .filter(|line| !line.starts_with("-----")) ++ .collect::(); ++ use base64::{Engine, engine::general_purpose::STANDARD}; ++ let der = STANDARD.decode(der).expect("the pinned root is not valid base64"); ++ assert!(der.len() > 500 && der[0] == 0x30, "the pinned root is not a DER SEQUENCE"); ++ // Serial number and subject live verbatim in the DER for this certificate. ++ assert!(der.windows(4).any(|w| w == [0x14, 0x98, 0x26, 0x66]), "unexpected serial"); ++ let subject = b"Microsoft ECC Product Root Certificate Authority 2018"; ++ assert!( ++ der.windows(subject.len()).any(|window| window == subject), ++ "unexpected subject" ++ ); ++ assert!(client().is_ok()); ++ } ++ ++ fn build(name: &str, moniker: &str) -> Revision { ++ Revision { update_id: String::new(), revision: "1".into(), digest: String::new(), name: name.into(), size: 1, moniker: moniker.into(), content_id: String::new() } ++ } ++ ++ fn licensed(name: &str, moniker: &str, content_id: &str) -> Revision { ++ Revision { content_id: content_id.into(), ..build(name, moniker) } ++ } ++ ++ #[test] ++ fn each_build_is_offered_under_its_own_content_id_newest_first() { ++ let builds = builds_newest_first(vec![ ++ licensed("old.eappx", "Microsoft.MSEsper_1.3.25854.2_x64__8wekyb3d8bbwe", "old-id"), ++ licensed("new.eappx", "Microsoft.MSEsper_1.3.25854.70_x64__8wekyb3d8bbwe", "new-id"), ++ licensed("new-arm.eappx", "Microsoft.MSEsper_1.3.25854.70_arm64__8wekyb3d8bbwe", "new-id"), ++ ]); ++ let shape: Vec<(String, Vec)> = builds ++ .iter() ++ .map(|group| (group[0].content_id.clone(), group.iter().map(|r| r.name.clone()).collect())) ++ .collect(); ++ assert_eq!(shape, [("new-id".to_string(), vec!["new.eappx".to_string()]), ("old-id".to_string(), vec!["old.eappx".to_string()])]); ++ } ++ ++ #[test] ++ fn only_the_newest_desktop_build_of_each_package_is_kept() { ++ let kept = newest_builds(vec![ ++ build("old.eappx", "Microsoft.MSEsper_1.3.25854.2_x64__8wekyb3d8bbwe"), ++ build("new.eappx", "Microsoft.MSEsper_1.3.25854.70_x64__8wekyb3d8bbwe"), ++ build("arm.eappx", "Microsoft.MSEsper_1.3.25854.70_arm64__8wekyb3d8bbwe"), ++ build("bare.eappxbundle", ""), ++ build("NEW.eappx", "Microsoft.MSEsper_1.3.25854.70_x64__8wekyb3d8bbwe"), ++ ]); ++ let names: Vec<_> = kept.iter().map(|r| r.name.as_str()).collect(); ++ assert_eq!(names, ["new.eappx", "bare.eappxbundle"]); ++ assert_eq!(newest_builds(vec![build("x86.eappx", "Game_1.0.0.0_x86__p")]).len(), 1); ++ } ++ ++ #[test] ++ fn fragments_escaped_twice_are_decoded_until_stable() { ++ assert_eq!(unescape("&lt;Files&gt;"), ""); ++ assert_eq!(unescape("<File FileName="a.eappxbundle"/>"), ""); ++ assert_eq!(unescape("plain text"), "plain text"); ++ } ++ ++ #[test] ++ fn self_closing_file_nodes_yield_their_attributes() { ++ let text = r#""#; ++ let attributes = file_attributes(text); ++ assert_eq!(attributes.len(), 2); ++ assert_eq!(attribute(&attributes[0], "FileName").as_deref(), Some("x.eappxbundle")); ++ assert_eq!(attribute(&attributes[0], "Size").as_deref(), Some("99")); ++ assert_eq!(attribute(&attributes[1], "FileName").as_deref(), Some("Abm_1.cab")); ++ } ++ ++ #[test] ++ fn blocks_stop_at_the_matching_close_tag() { ++ let text = "12"; ++ let updates = blocks(text, "Update"); ++ assert_eq!(updates.len(), 2); ++ assert_eq!(element(&updates[1], "ID").as_deref(), Some("2")); ++ } ++ ++ #[test] ++ fn element_returns_none_when_absent() { ++ assert!(element("1", "B").is_none()); ++ assert_eq!(element("", "A").as_deref(), Some("")); ++ } ++} +diff --git a/crates/xodus-cli/src/commands/streaming.rs b/crates/xodus-cli/src/commands/streaming.rs +index a0136f8..8e9d0e0 100644 +--- a/crates/xodus-cli/src/commands/streaming.rs ++++ b/crates/xodus-cli/src/commands/streaming.rs +@@ -9,7 +9,7 @@ use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; + use msixvc::streaming; + use msixvc::xvd::{SegmentFile, XvdFile}; + use tokio::fs::{File, OpenOptions}; +-use tokio::io::AsyncRead; ++use tokio::io::{AsyncRead, AsyncReadExt, AsyncSeekExt}; + use tokio::sync::mpsc::{Receiver, Sender}; + use uuid::Uuid; + use xodus::tokens::TokenManager; +@@ -354,6 +354,15 @@ where + Ok(file) => file, + Err(error) => { failure::report(&error); return ExitCode::FAILURE; } + }; ++ let mut magic = [0u8; 4]; ++ let plain = remote_file.read_exact(&mut magic).await.is_ok() && magic == [0x50, 0x4b, 0x03, 0x04]; ++ if let Err(error) = remote_file.seek(std::io::SeekFrom::Start(0)).await { ++ failure::report(&error); ++ return ExitCode::FAILURE; ++ } ++ if plain { ++ return plain_package(remote_file, l, out).await; ++ } + let remote_xvd = match XvdFile::parse(&mut remote_file).await { + Ok(xvd) => xvd, + Err(error) => { failure::report_metadata(error.as_ref()); return ExitCode::FAILURE; } +@@ -692,3 +701,369 @@ where + } + ExitCode::SUCCESS + } ++ ++const PLAIN_LIMIT: u64 = 1 << 30; ++ ++const PENDING: &str = ".pending"; ++ ++fn publish(staging: &Path, out: &Path) -> Result<(), String> { ++ let previous = out.join(".xodus-plain-previous"); ++ if previous.join(PENDING).exists() { ++ restore(&previous, out).map_err(|error| format!("an earlier replacement could not be undone: {error}"))?; ++ } else if previous.exists() && std::fs::remove_dir_all(&previous).is_err() { ++ let stale = out.join(format!(".xodus-plain-stale-{}", std::process::id())); ++ std::fs::rename(&previous, &stale).map_err(|error| format!("an earlier replacement left files behind: {error}"))?; ++ } ++ std::fs::create_dir_all(&previous).map_err(|error| format!("could not prepare the replacement: {error}"))?; ++ std::fs::write(previous.join(PENDING), b"").map_err(|error| format!("could not prepare the replacement: {error}"))?; ++ let mut names: Vec = std::fs::read_dir(staging) ++ .map_err(|error| format!("staged package unreadable: {error}"))? ++ .map(|entry| entry.map(|entry| entry.file_name())) ++ .collect::>() ++ .map_err(|error| format!("staged package unreadable: {error}"))?; ++ names.retain(|name| name != PENDING); ++ names.sort(); ++ let mut placed = Vec::new(); ++ let result = (|| { ++ for name in &names { ++ let target = out.join(name); ++ if std::fs::symlink_metadata(&target).is_ok() { ++ std::fs::rename(&target, previous.join(name)) ++ .map_err(|error| format!("could not replace {}: {error}", target.display()))?; ++ } ++ std::fs::rename(staging.join(name), &target) ++ .map_err(|error| format!("could not place {}: {error}", target.display()))?; ++ placed.push(name.clone()); ++ } ++ Ok::<(), String>(()) ++ })(); ++ match result { ++ Ok(()) => release(&previous), ++ Err(error) => { ++ let stuck: Vec = placed ++ .iter() ++ .filter(|name| remove(&out.join(name)).is_err()) ++ .map(|name| name.to_string_lossy().into_owned()) ++ .collect(); ++ if !stuck.is_empty() { ++ let listed = std::fs::write(previous.join(PENDING), stuck.join(" ++")); ++ let names = stuck.join(", "); ++ return Err(match listed { ++ Ok(()) => format!("{error}; {names} could not be removed, the previous files are kept in {}", previous.display()), ++ Err(write) => format!("{error}; {names} could not be removed and could not be recorded ({write})"), ++ }); ++ } ++ match restore(&previous, out) { ++ Ok(()) => Err(error), ++ Err(undo) => Err(format!("{error}; the previous files are kept in {} ({undo})", previous.display())), ++ } ++ } ++ } ++} ++ ++/// Moves every entry kept in `previous` back into `out`, then removes `previous`. ++/// On any failure `previous` stays, holding what has not been put back. ++fn release(previous: &Path) -> Result<(), String> { ++ std::fs::remove_file(previous.join(PENDING)) ++ .map_err(|error| format!("the replacement finished but its backup could not be released: {error}"))?; ++ std::fs::remove_dir_all(previous).ok(); ++ Ok(()) ++} ++ ++fn restore(previous: &Path, out: &Path) -> Result<(), String> { ++ restore_with(previous, out, &mut |from, to| std::fs::rename(from, to)) ++} ++ ++fn restore_with( ++ previous: &Path, ++ out: &Path, ++ move_entry: &mut dyn FnMut(&Path, &Path) -> std::io::Result<()>, ++) -> Result<(), String> { ++ let placed = std::fs::read_to_string(previous.join(PENDING)).map_err(|error| error.to_string())?; ++ for name in placed.lines().filter(|name| !name.is_empty() && !name.contains(['/', '\\']) && *name != "." && *name != "..") { ++ let target = out.join(name); ++ if std::fs::symlink_metadata(&target).is_ok() { ++ remove(&target).map_err(|error| format!("could not clear {}: {error}", target.display()))?; ++ } ++ } ++ if !placed.is_empty() { ++ std::fs::write(previous.join(PENDING), b"").map_err(|error| error.to_string())?; ++ } ++ let entries = std::fs::read_dir(previous).map_err(|error| error.to_string())?; ++ for entry in entries { ++ let entry = entry.map_err(|error| error.to_string())?; ++ if entry.file_name() == PENDING { ++ continue; ++ } ++ let target = out.join(entry.file_name()); ++ if std::fs::symlink_metadata(&target).is_ok() { ++ remove(&target).map_err(|error| format!("could not clear {}: {error}", target.display()))?; ++ } ++ move_entry(&entry.path(), &target).map_err(|error| format!("could not restore {}: {error}", target.display()))?; ++ } ++ std::fs::remove_file(previous.join(PENDING)).map_err(|error| error.to_string())?; ++ std::fs::remove_dir(previous).map_err(|error| error.to_string()) ++} ++ ++fn remove(path: &Path) -> std::io::Result<()> { ++ if std::fs::symlink_metadata(path)?.is_dir() { std::fs::remove_dir_all(path) } else { std::fs::remove_file(path) } ++} ++ ++async fn plain_package(mut remote: R, length: u64, out: &Path) -> ExitCode { ++ if length > PLAIN_LIMIT { ++ eprintln!("NEXUS_TRANSFER_DIAGNOSTIC_V1 plain-package-too-large 0"); ++ eprintln!("This package is a plain archive larger than this installer unpacks."); ++ return ExitCode::FAILURE; ++ } ++ let archive = out.join(".xodus-plain-package.zip"); ++ let written = async { ++ let mut file = File::create(&archive).await?; ++ let copied = tokio::io::copy(&mut remote, &mut file).await?; ++ tokio::io::AsyncWriteExt::flush(&mut file).await?; ++ Ok::(copied) ++ } ++ .await; ++ match written { ++ Ok(copied) if copied == length => {} ++ Ok(_) => { ++ std::fs::remove_file(&archive).ok(); ++ eprintln!("NEXUS_TRANSFER_DIAGNOSTIC_V1 transfer-short 0"); ++ eprintln!("The package ended early. Retry this installation to obtain a fresh package link."); ++ return ExitCode::FAILURE; ++ } ++ Err(error) => { ++ std::fs::remove_file(&archive).ok(); ++ failure::report(&error); ++ return ExitCode::FAILURE; ++ } ++ } ++ let staging = out.join(".xodus-plain-staging"); ++ std::fs::remove_dir_all(&staging).ok(); ++ let unpacked = crate::commands::unzip::extract(&archive, &staging).and_then(|()| publish(&staging, out)); ++ std::fs::remove_file(&archive).ok(); ++ std::fs::remove_dir_all(&staging).ok(); ++ match unpacked { ++ Ok(()) => ExitCode::SUCCESS, ++ Err(error) => { ++ eprintln!("NEXUS_TRANSFER_DIAGNOSTIC_V1 plain-package-invalid 0"); ++ eprintln!("Could not unpack the package: {error}"); ++ ExitCode::FAILURE ++ } ++ } ++} ++ ++#[cfg(test)] ++mod plain_tests { ++ fn stored_zip(name: &str, data: &[u8]) -> Vec { ++ let mut out = Vec::new(); ++ let n = name.len() as u16; ++ let size = data.len() as u32; ++ out.extend_from_slice(&[0x50, 0x4b, 0x03, 0x04, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); ++ out.extend_from_slice(&size.to_le_bytes()); ++ out.extend_from_slice(&size.to_le_bytes()); ++ out.extend_from_slice(&n.to_le_bytes()); ++ out.extend_from_slice(&0u16.to_le_bytes()); ++ out.extend_from_slice(name.as_bytes()); ++ out.extend_from_slice(data); ++ let central = out.len() as u32; ++ out.extend_from_slice(&[0x50, 0x4b, 0x01, 0x02, 20, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); ++ out.extend_from_slice(&size.to_le_bytes()); ++ out.extend_from_slice(&size.to_le_bytes()); ++ out.extend_from_slice(&n.to_le_bytes()); ++ out.extend_from_slice(&[0u8; 12]); ++ out.extend_from_slice(&0u32.to_le_bytes()); ++ out.extend_from_slice(name.as_bytes()); ++ let central_size = out.len() as u32 - central; ++ out.extend_from_slice(&[0x50, 0x4b, 0x05, 0x06, 0, 0, 0, 0, 1, 0, 1, 0]); ++ out.extend_from_slice(¢ral_size.to_le_bytes()); ++ out.extend_from_slice(¢ral.to_le_bytes()); ++ out.extend_from_slice(&0u16.to_le_bytes()); ++ out ++ } ++ ++ fn stored_zip_of(entries: &[(&str, &[u8], u32)]) -> Vec { ++ let mut out = Vec::new(); ++ let mut central = Vec::new(); ++ for (name, data, declared) in entries { ++ let offset = out.len() as u32; ++ let n = name.len() as u16; ++ out.extend_from_slice(&[0x50, 0x4b, 0x03, 0x04, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); ++ out.extend_from_slice(&declared.to_le_bytes()); ++ out.extend_from_slice(&declared.to_le_bytes()); ++ out.extend_from_slice(&n.to_le_bytes()); ++ out.extend_from_slice(&0u16.to_le_bytes()); ++ out.extend_from_slice(name.as_bytes()); ++ out.extend_from_slice(data); ++ central.extend_from_slice(&[0x50, 0x4b, 0x01, 0x02, 20, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); ++ central.extend_from_slice(&declared.to_le_bytes()); ++ central.extend_from_slice(&declared.to_le_bytes()); ++ central.extend_from_slice(&n.to_le_bytes()); ++ central.extend_from_slice(&[0u8; 12]); ++ central.extend_from_slice(&offset.to_le_bytes()); ++ central.extend_from_slice(name.as_bytes()); ++ } ++ let at = out.len() as u32; ++ let size = central.len() as u32; ++ out.extend_from_slice(¢ral); ++ let count = entries.len() as u16; ++ out.extend_from_slice(&[0x50, 0x4b, 0x05, 0x06, 0, 0, 0, 0]); ++ out.extend_from_slice(&count.to_le_bytes()); ++ out.extend_from_slice(&count.to_le_bytes()); ++ out.extend_from_slice(&size.to_le_bytes()); ++ out.extend_from_slice(&at.to_le_bytes()); ++ out.extend_from_slice(&0u16.to_le_bytes()); ++ out ++ } ++ ++ #[tokio::test] ++ async fn an_entry_that_runs_into_the_next_header_is_refused() { ++ let out = std::env::temp_dir().join(format!("xodus-plain-next-{}", std::process::id())); ++ std::fs::create_dir_all(&out).unwrap(); ++ let fine = stored_zip_of(&[("a.txt", b"aaaa", 4), ("b.txt", b"bbbb", 4)]); ++ let code = super::plain_package(std::io::Cursor::new(fine.clone()), fine.len() as u64, &out).await; ++ assert_eq!(code, std::process::ExitCode::SUCCESS); ++ assert_eq!(std::fs::read(out.join("b.txt")).unwrap(), b"bbbb"); ++ let bad = stored_zip_of(&[("a.txt", b"zzzz", 10), ("b.txt", b"yyyy", 4)]); ++ let code = super::plain_package(std::io::Cursor::new(bad.clone()), bad.len() as u64, &out).await; ++ assert_eq!(code, std::process::ExitCode::FAILURE); ++ assert_eq!(std::fs::read(out.join("a.txt")).unwrap(), b"aaaa"); ++ std::fs::remove_dir_all(&out).ok(); ++ } ++ ++ #[test] ++ fn a_failed_swap_puts_every_replaced_entry_back() { ++ let root = tempfile::tempdir().unwrap(); ++ let (staging, out) = (root.path().join("staging"), root.path().join("out")); ++ std::fs::create_dir_all(staging.join(".xodus-plain-previous")).unwrap(); ++ std::fs::create_dir_all(&out).unwrap(); ++ std::fs::write(staging.join("+a"), b"new").unwrap(); ++ std::fs::write(out.join("+a"), b"old").unwrap(); ++ assert!(super::publish(&staging, &out).is_err()); ++ assert_eq!(std::fs::read(out.join("+a")).unwrap(), b"old"); ++ assert!(!out.join(".xodus-plain-previous").exists()); ++ } ++ ++ #[test] ++ fn entries_a_rollback_could_not_remove_are_cleared_before_the_backup_returns() { ++ let root = tempfile::tempdir().unwrap(); ++ let (staging, out) = (root.path().join("staging"), root.path().join("out")); ++ let previous = out.join(".xodus-plain-previous"); ++ std::fs::create_dir_all(&staging).unwrap(); ++ std::fs::create_dir_all(previous.join("data")).unwrap(); ++ std::fs::write(previous.join(".pending"), "stray").unwrap(); ++ std::fs::write(previous.join("data").join("old"), b"old").unwrap(); ++ std::fs::create_dir_all(out.join("stray")).unwrap(); ++ std::fs::write(out.join("stray").join("new"), b"new").unwrap(); ++ std::fs::create_dir_all(out.join("data")).unwrap(); ++ std::fs::write(staging.join("fresh"), b"new").unwrap(); ++ super::publish(&staging, &out).unwrap(); ++ assert!(!out.join("stray").exists()); ++ assert_eq!(std::fs::read(out.join("data").join("old")).unwrap(), b"old"); ++ assert!(!previous.exists()); ++ } ++ ++ #[test] ++ fn a_restore_interrupted_after_its_removals_never_deletes_what_it_put_back() { ++ let root = tempfile::tempdir().unwrap(); ++ let out = root.path().join("out"); ++ let previous = out.join(".xodus-plain-previous"); ++ std::fs::create_dir_all(&previous).unwrap(); ++ std::fs::write(previous.join(".pending"), "a ++b").unwrap(); ++ std::fs::write(previous.join("a"), b"old-a").unwrap(); ++ std::fs::write(previous.join("b"), b"old-b").unwrap(); ++ std::fs::write(out.join("a"), b"new-a").unwrap(); ++ std::fs::write(out.join("b"), b"new-b").unwrap(); ++ let mut moves = 0; ++ let interrupted = super::restore_with(&previous, &out, &mut |from, to| { ++ moves += 1; ++ if moves == 2 { return Err(std::io::Error::other("interrupted")) } ++ std::fs::rename(from, to) ++ }); ++ assert!(interrupted.is_err()); ++ let restored = ["a", "b"].into_iter().find(|name| out.join(name).exists()).unwrap(); ++ super::restore(&previous, &out).unwrap(); ++ assert_eq!(std::fs::read(out.join(restored)).unwrap(), format!("old-{restored}").as_bytes()); ++ assert_eq!(std::fs::read(out.join("a")).unwrap(), b"old-a"); ++ assert_eq!(std::fs::read(out.join("b")).unwrap(), b"old-b"); ++ assert!(!previous.exists()); ++ } ++ ++ #[test] ++ fn a_backup_whose_marker_cannot_be_removed_is_kept_and_reported() { ++ let root = tempfile::tempdir().unwrap(); ++ let previous = root.path().join(".xodus-plain-previous"); ++ std::fs::create_dir_all(previous.join(".pending").join("held")).unwrap(); ++ std::fs::write(previous.join("kept"), b"old").unwrap(); ++ assert!(super::release(&previous).is_err()); ++ assert!(previous.join("kept").exists()); ++ std::fs::remove_dir_all(previous.join(".pending")).unwrap(); ++ std::fs::write(previous.join(".pending"), b"").unwrap(); ++ super::release(&previous).unwrap(); ++ assert!(!previous.exists()); ++ } ++ ++ #[test] ++ fn a_backup_left_by_a_finished_swap_is_discarded_not_restored() { ++ let root = tempfile::tempdir().unwrap(); ++ let (staging, out) = (root.path().join("staging"), root.path().join("out")); ++ std::fs::create_dir_all(&staging).unwrap(); ++ std::fs::create_dir_all(out.join(".xodus-plain-previous")).unwrap(); ++ std::fs::write(out.join(".xodus-plain-previous").join("kept"), b"old").unwrap(); ++ std::fs::write(out.join("kept"), b"installed").unwrap(); ++ std::fs::write(staging.join("fresh"), b"new").unwrap(); ++ super::publish(&staging, &out).unwrap(); ++ assert_eq!(std::fs::read(out.join("kept")).unwrap(), b"installed"); ++ assert!(!out.join(".xodus-plain-previous").exists()); ++ } ++ ++ #[test] ++ fn a_backup_left_by_an_interrupted_swap_is_restored_first() { ++ let root = tempfile::tempdir().unwrap(); ++ let (staging, out) = (root.path().join("staging"), root.path().join("out")); ++ std::fs::create_dir_all(&staging).unwrap(); ++ std::fs::create_dir_all(out.join(".xodus-plain-previous")).unwrap(); ++ std::fs::write(out.join(".xodus-plain-previous").join(".pending"), b"").unwrap(); ++ std::fs::write(out.join(".xodus-plain-previous").join("kept"), b"old").unwrap(); ++ std::fs::write(out.join("kept"), b"half").unwrap(); ++ std::fs::write(staging.join("fresh"), b"new").unwrap(); ++ super::publish(&staging, &out).unwrap(); ++ assert_eq!(std::fs::read(out.join("kept")).unwrap(), b"old"); ++ assert_eq!(std::fs::read(out.join("fresh")).unwrap(), b"new"); ++ assert!(!out.join(".xodus-plain-previous").exists()); ++ } ++ ++ #[tokio::test] ++ async fn a_plain_archive_is_downloaded_whole_and_unpacked() { ++ let out = std::env::temp_dir().join(format!("xodus-plain-{}", std::process::id())); ++ std::fs::create_dir_all(&out).unwrap(); ++ let zip = stored_zip("AppxManifest.xml", b""); ++ let code = super::plain_package(std::io::Cursor::new(zip.clone()), zip.len() as u64, &out).await; ++ assert_eq!(code, std::process::ExitCode::SUCCESS); ++ assert_eq!(std::fs::read(out.join("AppxManifest.xml")).unwrap(), b""); ++ assert!(!out.join(".xodus-plain-package.zip").exists()); ++ let short = super::plain_package(std::io::Cursor::new(zip[..10].to_vec()), zip.len() as u64, &out).await; ++ assert_eq!(short, std::process::ExitCode::FAILURE); ++ let mut lying = stored_zip("AppxManifest.xml", b""); ++ lying[18] = 0xff; ++ lying[22] = 0xff; ++ let length = lying.len() as u64; ++ let central = lying.windows(4).position(|w| w == [0x50, 0x4b, 0x01, 0x02]).unwrap(); ++ lying[central + 20] = 0xff; ++ lying[central + 24] = 0xff; ++ let truncated = super::plain_package(std::io::Cursor::new(lying), length, &out).await; ++ assert_eq!(truncated, std::process::ExitCode::FAILURE); ++ let mut overrun = stored_zip("AppxManifest.xml", b""); ++ let central = overrun.windows(4).position(|w| w == [0x50, 0x4b, 0x01, 0x02]).unwrap(); ++ for at in [18, 22, central + 20, central + 24] { ++ overrun[at] = 11; ++ } ++ let length = overrun.len() as u64; ++ let overran = super::plain_package(std::io::Cursor::new(overrun), length, &out).await; ++ assert_eq!(overran, std::process::ExitCode::FAILURE); ++ assert_eq!(std::fs::read(out.join("AppxManifest.xml")).unwrap(), b""); ++ assert!(!out.join(".xodus-plain-staging").exists()); ++ std::fs::remove_dir_all(&out).ok(); ++ } ++} +diff --git a/crates/xodus-cli/src/commands/unzip.rs b/crates/xodus-cli/src/commands/unzip.rs +new file mode 100644 +index 0000000..10e92fb +--- /dev/null ++++ b/crates/xodus-cli/src/commands/unzip.rs +@@ -0,0 +1,219 @@ ++//! Plain ZIP packages, which is what the store serves for a framework. ++//! ++//! Framework packages (`Microsoft.VCLibs.140.00` and its siblings) arrive from the ++//! delivery service as ordinary `.appx` zips, not the EAppx containers a title is ++//! packed in: there is nothing to decrypt and no header to parse. The packager ++//! writes them in the ZIP64 form, so the central directory and each entry may name ++//! its sizes and offset in an extra field instead of the fixed header. ++ ++use std::io::{Read, Seek, SeekFrom, Write}; ++use std::path::Path; ++ ++/// The end record is 22 bytes and its comment field can push it back 64 KiB. ++const TAIL: u64 = 65_557; ++const END: &[u8; 4] = b"PK\x05\x06"; ++const ZIP64_END: &[u8; 4] = b"PK\x06\x06"; ++const ZIP64_LOCATOR: &[u8; 4] = b"PK\x06\x07"; ++const CENTRAL: &[u8; 4] = b"PK\x01\x02"; ++const SATURATED: u32 = 0xFFFF_FFFF; ++ ++pub fn extract(archive: &Path, destination: &Path) -> Result<(), String> { ++ let mut file = std::fs::File::open(archive).map_err(|error| format!("package open failed: {error}"))?; ++ let length = file.metadata().map_err(|error| format!("package size failed: {error}"))?.len(); ++ if length < 22 { ++ return Err("the package is too small to be an archive".into()); ++ } ++ let tail = length.min(TAIL); ++ file.seek(SeekFrom::Start(length - tail)).map_err(|error| format!("package seek failed: {error}"))?; ++ let mut buffer = vec![0u8; tail as usize]; ++ file.read_exact(&mut buffer).map_err(|error| format!("package read failed: {error}"))?; ++ let end = buffer ++ .windows(END.len()) ++ .rposition(|window| window == END) ++ .ok_or("the package is not a zip archive")?; ++ if end + 22 > buffer.len() { ++ return Err("the package end record is truncated".into()); ++ } ++ let mut entries = u16::from_le_bytes([buffer[end + 10], buffer[end + 11]]) as u64; ++ let mut offset = u32::from_le_bytes([buffer[end + 16], buffer[end + 17], buffer[end + 18], buffer[end + 19]]) as u64; ++ if entries == 0xFFFF || offset == u64::from(SATURATED) || offset > length { ++ let (zip64_entries, zip64_offset) = zip64(&mut file, length, &buffer, end)?; ++ entries = zip64_entries; ++ offset = zip64_offset; ++ } ++ if offset >= length { ++ return Err(format!("the package directory starts past the archive at {offset} of {length}")); ++ } ++ std::fs::create_dir_all(destination).map_err(|error| format!("package folder failed: {error}"))?; ++ let directory = offset; ++ let mut listed = Vec::new(); ++ for _ in 0..entries { ++ file.seek(SeekFrom::Start(offset)).map_err(|error| format!("package seek failed: {error}"))?; ++ let mut header = [0u8; 46]; ++ file.read_exact(&mut header).map_err(|error| format!("package header failed at {offset} of the directory, {error}"))?; ++ if &header[0..4] != CENTRAL { ++ return Err(format!("the package directory is malformed at {offset}")); ++ } ++ let method = u16::from_le_bytes([header[10], header[11]]); ++ let uncompressed = u32::from_le_bytes([header[24], header[25], header[26], header[27]]); ++ let mut compressed = u64::from(u32::from_le_bytes([header[20], header[21], header[22], header[23]])); ++ let name_length = u16::from_le_bytes([header[28], header[29]]) as usize; ++ let extra_length = u16::from_le_bytes([header[30], header[31]]) as usize; ++ let comment_length = u16::from_le_bytes([header[32], header[33]]) as usize; ++ let mut local = u64::from(u32::from_le_bytes([header[42], header[43], header[44], header[45]])); ++ let mut size = u64::from(uncompressed); ++ let mut name = vec![0u8; name_length]; ++ file.read_exact(&mut name).map_err(|error| format!("package name failed: {error}"))?; ++ let mut extra = vec![0u8; extra_length]; ++ file.read_exact(&mut extra).map_err(|error| format!("package extra failed: {error}"))?; ++ offset += 46 + name_length as u64 + extra_length as u64 + comment_length as u64; ++ if compressed == u64::from(SATURATED) || local == u64::from(SATURATED) || uncompressed == SATURATED { ++ let wide = zip64_entry(&extra, uncompressed == SATURATED, compressed == u64::from(SATURATED), local == u64::from(SATURATED)); ++ if compressed == u64::from(SATURATED) { ++ compressed = wide.compressed.ok_or("a package entry has no wide size")?; ++ } ++ if local == u64::from(SATURATED) { ++ local = wide.local.ok_or("a package entry has no wide offset")?; ++ } ++ if uncompressed == SATURATED { ++ size = wide.size.ok_or("a package entry has no wide uncompressed size")?; ++ } ++ } ++ let name = String::from_utf8(name).map_err(|_| "a package entry has an unreadable name".to_string())?; ++ listed.push(Listed { name, method, compressed, size, local }); ++ } ++ let mut starts: Vec = listed.iter().map(|entry| entry.local).collect(); ++ starts.sort_unstable(); ++ starts.dedup(); ++ for Listed { name, method, compressed, size, local } in listed { ++ let limit = starts.get(starts.partition_point(|start| *start <= local)).copied().unwrap_or(directory).min(directory); ++ if name.ends_with('/') { ++ continue; ++ } ++ let Some(relative) = safe(&name) else { continue }; ++ let target = destination.join(relative); ++ if let Some(parent) = target.parent() { ++ std::fs::create_dir_all(parent).map_err(|error| format!("package folder failed: {error}"))?; ++ } ++ file.seek(SeekFrom::Start(local)).map_err(|error| format!("package seek failed: {error}"))?; ++ let mut local_header = [0u8; 30]; ++ file.read_exact(&mut local_header).map_err(|error| format!("package header failed: {error}"))?; ++ let local_name = u16::from_le_bytes([local_header[26], local_header[27]]) as usize; ++ let local_extra = u16::from_le_bytes([local_header[28], local_header[29]]) as usize; ++ let data = local + 30 + local_name as u64 + local_extra as u64; ++ if data.checked_add(compressed).is_none_or(|end| end > limit) { ++ return Err(format!("the package entry {name} runs past its data")); ++ } ++ if method == 0 && compressed != size { ++ return Err(format!("the package entry {name} has inconsistent sizes")); ++ } ++ file.seek(SeekFrom::Start(data)).map_err(|error| format!("package seek failed: {error}"))?; ++ let mut body = (&mut file).take(compressed); ++ let mut written = std::fs::File::create(&target).map_err(|error| format!("package write failed: {error}"))?; ++ match method { ++ 0 => { ++ let copied = std::io::copy(&mut body, &mut written).map_err(|error| format!("package copy failed: {error}"))?; ++ if copied != compressed { ++ return Err(format!("the package entry {name} is truncated")); ++ } ++ } ++ 8 => { ++ let mut inflate = flate2::read::DeflateDecoder::new(body); ++ let copied = std::io::copy(&mut inflate, &mut written).map_err(|error| format!("package inflate failed: {error}"))?; ++ if copied != size { ++ return Err(format!("the package entry {name} is truncated")); ++ } ++ } ++ _ => return Err(format!("a package entry uses compression {method}, which is not supported")), ++ } ++ written.flush().ok(); ++ } ++ Ok(()) ++} ++ ++/// The end record of the ZIP64 archive that precedes the ordinary one. ++fn zip64(file: &mut std::fs::File, length: u64, buffer: &[u8], end: usize) -> Result<(u64, u64), String> { ++ let locator = buffer[..end] ++ .windows(ZIP64_LOCATOR.len()) ++ .rposition(|window| window == ZIP64_LOCATOR) ++ .ok_or("the package names a wide directory with no locator")?; ++ if locator + 20 > buffer.len() { ++ return Err("the package locator is truncated".into()); ++ } ++ let at = u64::from_le_bytes(buffer[locator + 8..locator + 16].try_into().map_err(|_| "unreadable locator")?); ++ if at + 56 > length { ++ return Err(format!("the package names a wide end record past the archive at {at} of {length}")); ++ } ++ file.seek(SeekFrom::Start(at)).map_err(|error| format!("package seek failed: {error}"))?; ++ let mut record = [0u8; 56]; ++ file.read_exact(&mut record).map_err(|error| format!("package end record failed: {error}"))?; ++ if &record[0..4] != ZIP64_END { ++ return Err("the package wide end record is malformed".into()); ++ } ++ let entries = u64::from_le_bytes(record[32..40].try_into().map_err(|_| "unreadable entry count")?); ++ let offset = u64::from_le_bytes(record[48..56].try_into().map_err(|_| "unreadable directory offset")?); ++ Ok((entries, offset)) ++} ++ ++/// The compressed size and local header offset a ZIP64 entry keeps in its extra, ++/// in the order the format wrote them: only the fields that were saturated. ++fn zip64_entry(extra: &[u8], has_size: bool, has_compressed: bool, has_local: bool) -> Wide { ++ let mut wide = Wide::default(); ++ let mut at = 0; ++ while at + 4 <= extra.len() { ++ let id = u16::from_le_bytes([extra[at], extra[at + 1]]); ++ let size = u16::from_le_bytes([extra[at + 2], extra[at + 3]]) as usize; ++ let body = at + 4; ++ if body + size > extra.len() { ++ break; ++ } ++ if id == 0x0001 { ++ let fields = &extra[body..body + size]; ++ let mut cursor = 0usize; ++ let mut take = |present: bool| -> Option { ++ if !present || cursor + 8 > fields.len() { ++ return None; ++ } ++ let value = u64::from_le_bytes(fields[cursor..cursor + 8].try_into().ok()?); ++ cursor += 8; ++ Some(value) ++ }; ++ wide.size = take(has_size); ++ wide.compressed = take(has_compressed); ++ wide.local = take(has_local); ++ return wide; ++ } ++ at = body + size; ++ } ++ wide ++} ++ ++struct Listed { ++ name: String, ++ method: u16, ++ compressed: u64, ++ size: u64, ++ local: u64, ++} ++ ++#[derive(Default)] ++struct Wide { ++ size: Option, ++ compressed: Option, ++ local: Option, ++} ++ ++/// The entry's relative path, or nothing when it would land outside the folder. ++fn safe(name: &str) -> Option { ++ let mut parts = Vec::new(); ++ for part in name.split('/') { ++ if part.is_empty() || part == "." { ++ continue; ++ } ++ if part == ".." || part.contains('\\') || part.contains(':') { ++ return None; ++ } ++ parts.push(part); ++ } ++ if parts.is_empty() { None } else { Some(parts.iter().collect()) } ++} +diff --git a/crates/xodus-cli/src/commands/wu-root.pem b/crates/xodus-cli/src/commands/wu-root.pem +new file mode 100644 +index 0000000..63467d7 +--- /dev/null ++++ b/crates/xodus-cli/src/commands/wu-root.pem +@@ -0,0 +1,19 @@ ++-----BEGIN CERTIFICATE----- ++MIIDIzCCAqigAwIBAgIQFJgmZtx8zY9AU2d7uZnshTAKBggqhkjOPQQDAzCBlDEL ++MAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcTB1JlZG1v ++bmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjE+MDwGA1UEAxM1TWlj ++cm9zb2Z0IEVDQyBQcm9kdWN0IFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIw ++MTgwHhcNMTgwMjI3MjA0MjA4WhcNNDMwMjI3MjA1MDQ2WjCBlDELMAkGA1UEBhMC ++VVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNV ++BAoTFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjE+MDwGA1UEAxM1TWljcm9zb2Z0IEVD ++QyBQcm9kdWN0IFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5IDIwMTgwdjAQBgcq ++hkjOPQIBBgUrgQQAIgNiAATHERYqdh1Wjr65YmXUw8608MMw7I9t1245vMhJq6u4 ++40N41YEGXe/HfZ/O1rOQdd4MsJDeI7rI0T5n4BmpG4YxHl80Le4X/RX7fieKMqHq ++yY/JfhjLLzssSHp9pvQBB6yjgbwwgbkwDgYDVR0PAQH/BAQDAgGGMA8GA1UdEwEB ++/wQFMAMBAf8wHQYDVR0OBBYEFEPvcIe4nb/siBncxsRrdQ11NDMIMBAGCSsGAQQB ++gjcVAQQDAgEAMGUGA1UdIAReMFwwBgYEVR0gADBSBgwrBgEEAYI3TIN9AQEwQjBA ++BggrBgEFBQcCARY0aHR0cDovL3d3dy5taWNyb3NvZnQuY29tL3BraW9wcy9Eb2Nz ++L1JlcG9zaXRvcnkuaHRtADAKBggqhkjOPQQDAwNpADBmAjEAocBJRF0yVSfMPpBu ++JSKdJFubUTXHkUlJKqP5b08czd2c4bVXyZ7CIkWbBhVwHEW/AjEAxdMo63LHPrCs ++Jwl/Yj1geeWS8UUquaUC5GC7/nornGCntZkU8rC+8LsFllZWj8Fo ++-----END CERTIFICATE----- +diff --git a/crates/xodus-cli/src/main.rs b/crates/xodus-cli/src/main.rs +index b2a3383..855f667 100644 +--- a/crates/xodus-cli/src/main.rs ++++ b/crates/xodus-cli/src/main.rs +@@ -166,6 +166,29 @@ enum SubCommand { + #[arg(short, long)] + market: Option, + }, ++ #[command( ++ about = "Install a legacy EAppx/EAppxBundle title: license, download, extract" ++ )] ++ LegacyInstall { ++ product: String, ++ destination: String, ++ #[arg(short, long)] ++ market: Option, ++ #[arg(long, help = "Content ID explicitly selected from resolve-package for this Store product")] ++ selected_content_id: Option, ++ #[arg(long, help = "Store product ID for the Windows Update catalogue when PRODUCT is a content ID")] ++ store_id: Option, ++ #[arg( ++ long, ++ help = "Emit Nexus progress protocol v1 as newline-delimited JSON" ++ )] ++ progress_json: bool, ++ #[arg( ++ long, ++ help = "Resolve the download locations and stop without downloading" ++ )] ++ resolve_only: bool, ++ }, + #[cfg(unix)] + #[command(about = "Run a Game with xodus wine")] + Run { +@@ -435,6 +458,28 @@ async fn main() -> ExitCode { + ) + .await + } ++ SubCommand::LegacyInstall { ++ product, ++ destination, ++ market, ++ selected_content_id, ++ store_id, ++ progress_json, ++ resolve_only, ++ } => { ++ commands::legacy_install::run( ++ &client, ++ &tokens, ++ product, ++ destination, ++ market, ++ selected_content_id, ++ store_id, ++ progress_json, ++ resolve_only, ++ ) ++ .await ++ } + #[cfg(unix)] + SubCommand::Run { + source, +diff --git a/crates/xodus/src/licensing/content_response.rs b/crates/xodus/src/licensing/content_response.rs +index e87421d..8b5b570 100644 +--- a/crates/xodus/src/licensing/content_response.rs ++++ b/crates/xodus/src/licensing/content_response.rs +@@ -53,6 +53,10 @@ pub enum LicenseContentError { + "Microsoft Store device limit reached. Open https://account.microsoft.com/devices/content, unlink an old device you no longer use, then try again. You do not need to sign out or reset the wallet." + )] + DeviceLimit, ++ #[error( ++ "Microsoft refused a license for this version of the package on this device." ++ )] ++ DeviceUnregistrable, + #[error( + "Microsoft returned a content license without a key. Share the backend diagnostic log." + )] +@@ -87,6 +91,7 @@ impl LicenseContentError { + Self::Schema => "content-schema", + Self::NotEntitled => "content-not-entitled", + Self::DeviceLimit => "content-device-limit", ++ Self::DeviceUnregistrable => "content-device-name", + Self::EmptyKeys => "content-empty-keys", + Self::Base64 => "content-base64", + Self::Utf8 => "content-utf8", +@@ -133,6 +138,12 @@ async fn receive( + let result = async { + // A valid-looking license inside a refused HTTP response is not permission. + if !response.status().is_success() { ++ if status == 400 ++ && let Some(body) = bounded_body(&mut response, REFUSAL_BODY).await ++ && unregistrable(&body) ++ { ++ return Err(LicenseContentError::DeviceUnregistrable); ++ } + return Err(LicenseContentError::http(status)); + } + if response +@@ -167,6 +178,27 @@ async fn receive( + result + } + ++const REFUSAL_BODY: usize = 64 * 1024; ++ ++async fn bounded_body(response: &mut reqwest::Response, limit: usize) -> Option> { ++ if response.content_length().is_some_and(|length| length > limit as u64) { ++ return None; ++ } ++ let mut body = Vec::new(); ++ while let Some(chunk) = response.chunk().await.ok()? { ++ if chunk.len() > limit - body.len() { ++ return None; ++ } ++ body.extend_from_slice(&chunk); ++ } ++ Some(body) ++} ++ ++fn unregistrable(body: &[u8]) -> bool { ++ serde_json::from_slice::(body) ++ .is_ok_and(|value| value["innererror"]["code"] == "DeviceNameNotHexBinary") ++} ++ + fn parse(bytes: &[u8]) -> Result<(LicenseContent, License), LicenseContentError> { + if bytes.len() > MAX_BODY { + return Err(LicenseContentError::Size); +diff --git a/crates/xodus/src/licensing/content_response_tests.rs b/crates/xodus/src/licensing/content_response_tests.rs +index 205aab3..93c138b 100644 +--- a/crates/xodus/src/licensing/content_response_tests.rs ++++ b/crates/xodus/src/licensing/content_response_tests.rs +@@ -373,3 +373,18 @@ async fn content_license_transport_timeout_and_cancellation_have_no_background_r + ); + server.await.unwrap(); + } ++ ++#[tokio::test] ++async fn a_refused_device_name_claim_has_its_own_stage() { ++ let refused = serde_json::to_vec(&json!({"code":"BadRequest","innererror":{"faultcode":3043,"code":"DeviceNameNotHexBinary","message":"private"}})).unwrap(); ++ let other = serde_json::to_vec(&json!({"code":"BadRequest","innererror":{"code":"Other"}})).unwrap(); ++ let mut oversized = refused.clone(); ++ oversized.splice(1..1, std::iter::repeat_n(b' ', 70 * 1024)); ++ for (body, expected) in [(refused, "content-device-name"), (other, "content-http"), (b"not json".to_vec(), "content-http"), (oversized, "content-http")] { ++ let (url, server) = server(format!("HTTP/1.1 400 Fixture\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", body.len()), body).await; ++ let error = fetch(reqwest::Client::new().get(url)).await.err().unwrap(); ++ assert_eq!(error.stage(), expected); ++ assert!(!error.to_string().contains("private")); ++ server.await.unwrap(); ++ } ++} diff --git a/tools/xbox/droiddeck-legacy-packages.patch b/tools/xbox/droiddeck-legacy-packages.patch new file mode 100644 index 0000000000..daec856e54 --- /dev/null +++ b/tools/xbox/droiddeck-legacy-packages.patch @@ -0,0 +1,570 @@ +diff --git a/crates/xodus-cli/src/commands/extract_eappx.rs b/crates/xodus-cli/src/commands/extract_eappx.rs +index c8d5ebf..5ea43da 100644 +--- a/crates/xodus-cli/src/commands/extract_eappx.rs ++++ b/crates/xodus-cli/src/commands/extract_eappx.rs +@@ -1,80 +1,416 @@ +-use std::path::PathBuf; ++use std::path::{Path, PathBuf}; + use std::process::ExitCode; + + use eappx::EAppxFile; +-use eappx::keys::KeyCollection; ++use eappx::keys::{KeyCollection, KeyId}; ++ ++/// A bundle header names each content key as a pair of GUIDs, `(content id, ++/// package id)`, while the licence names the same key by its 16-byte content id ++/// alone. The crate reads a 16-byte id as `(static prefix, content id)`, so the ++/// two never compare equal and a complete key file looks incomplete. Pair every ++/// key the header asks for with the licence entry that carries its content id. ++const SHORT_KEY_PREFIX: uuid::Uuid = uuid::uuid!("BB1755DB-5052-4B10-B2AB-F3ABF5CA5B41"); ++ ++fn align_keys(keys: &mut KeyCollection, needed: &[KeyId]) { ++ for id in needed { ++ if keys.keys.contains_key(id) { ++ continue; ++ } ++ let KeyId::Guid((content, _)) = id else { continue }; ++ let carried = keys.keys.get(&KeyId::Guid((SHORT_KEY_PREFIX, *content))).cloned(); ++ if let Some(data) = carried { ++ keys.add(id.clone(), data); ++ } ++ } ++} ++ ++/// A bundle can hold another bundle, but nesting is bounded so a malformed ++/// archive cannot drive unbounded recursion. ++const MAX_BUNDLE_DEPTH: usize = 3; + + /// Extracts a locally-stored EAppx/EMSIX package. + /// +-/// This is intentionally local-only for now: no store lookup or download. +-/// See issue #91 - the initial goal is understanding/unpacking the format, +-/// not full download integration, which can build on this once it lands. ++/// A bundle is extracted in place, then each inner package that is itself an ++/// EAppx container is decrypted with the same content keys. Inner files that ++/// are plain ZIP-based packages are left as extracted: they carry no EAppx ++/// header, so there is nothing to decrypt. + pub async fn run(path: String, destination: String, key_file: Option) -> ExitCode { +- let infile = PathBuf::from(&path); +- let outdir = PathBuf::from(&destination); +- +- let file = match std::fs::File::open(&infile) { +- Ok(f) => f, +- Err(e) => { +- eprintln!("Failed to open {:?}: {e}", infile); +- return ExitCode::FAILURE; +- } +- }; +- let mut reader = std::io::BufReader::new(file); ++ run_metered(path, destination, key_file, None).await ++} + +- let mut eappx = match EAppxFile::from_stream(&mut reader) { +- Ok(e) => e, +- Err(e) => { +- eprintln!("Failed to parse EAppx header: {e}"); +- return ExitCode::FAILURE; +- } +- }; ++/// Where the extraction of the current package begins and how much it will write. ++/// ++/// A bundle's inner package is one enormous member, so counting finished files ++/// leaves the bar frozen for the whole of it. The counter is exact: it advances by ++/// each file's declared length as that file is written. ++#[derive(Default)] ++pub struct Meter { ++ /// Bytes written by the package being unpacked now. ++ pub written: std::sync::atomic::AtomicU64, ++ /// Bytes written by packages that already finished. ++ pub banked: std::sync::atomic::AtomicU64, ++ /// Bytes the package being unpacked now will write in total. ++ pub total: std::sync::atomic::AtomicU64, ++ turn: std::sync::Mutex<()>, ++} + +- println!("{eappx}"); ++impl Meter { ++ /// Bytes written and bytes to write, read as one consistent pair. ++ pub fn snapshot(&self) -> (u64, u64) { ++ use std::sync::atomic::Ordering::Relaxed; ++ let _turn = self.turn.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); ++ let banked = self.banked.load(Relaxed); ++ let total = self.total.load(Relaxed); ++ (banked + self.written.load(Relaxed).min(total), banked + total) ++ } + ++ pub fn done(&self) -> u64 { ++ self.snapshot().0 ++ } ++ ++ pub fn all(&self) -> u64 { ++ self.snapshot().1 ++ } ++ ++ /// Closes the package being unpacked and opens the next one. ++ fn roll(&self, total: u64) { ++ use std::sync::atomic::Ordering::Relaxed; ++ let _turn = self.turn.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); ++ self.banked.fetch_add(self.total.load(Relaxed), Relaxed); ++ self.written.store(0, Relaxed); ++ self.total.store(total, Relaxed); ++ } ++} ++ ++/// Extracts a package, publishing the size of the work in progress to `meter`. ++/// ++/// `release` deletes the container once its members are on disk. A bundle of a ++/// full title is tens of gigabytes, and holding it while the members are ++/// decrypted can fill the device partway through. ++pub async fn run_metered( ++ path: String, ++ destination: String, ++ key_file: Option, ++ meter: Option<&Meter>, ++) -> ExitCode { ++ run_blocking(path, destination, key_file, meter, false) ++} ++ ++/// The extraction itself, without the async wrapper. ++/// ++/// Callers that keep reporting while it works run this on a blocking thread, ++/// because it never yields: decryption and inflation are plain synchronous work. ++pub fn run_blocking( ++ path: String, ++ destination: String, ++ key_file: Option, ++ meter: Option<&Meter>, ++ release: bool, ++) -> ExitCode { + let mut key_collection = KeyCollection::default(); + if let Some(key_file) = key_file { + let mut keyfile = match std::fs::File::open(&key_file) { + Ok(f) => f, + Err(e) => { +- eprintln!("Failed to open key file {:?}: {e}", key_file); +- return ExitCode::FAILURE; ++ return report_failure( ++ &Failure::new("key-file-open", &key_file, &e.to_string()), ++ ExitCode::FAILURE, ++ ); + } + }; + match KeyCollection::from_reader(&mut keyfile) { + Ok(loaded) => key_collection.extend(loaded.keys), + Err(e) => { +- eprintln!("Failed to parse key file: {e}"); +- return ExitCode::FAILURE; ++ return report_failure( ++ &Failure::new("key-file-parse", &key_file, &e.to_string()), ++ ExitCode::FAILURE, ++ ); + } + } + } + +- if !key_collection.has_required_keys(&eappx.header.key_ids) { +- eprintln!("Missing one or more required content keys for this package"); +- return ExitCode::FAILURE; ++ match derive( ++ Path::new(&path), ++ Path::new(&destination), ++ &key_collection, ++ 0, ++ meter, ++ release, ++ ) { ++ Ok(()) => ExitCode::SUCCESS, ++ Err(failure) => report_failure(&failure, ExitCode::FAILURE), + } ++} ++ ++/// A failure the launcher can name without printing a device path. ++/// ++/// The app only forwards stderr lines that are on a known allowlist, so the two ++/// lines below are what make a stopped install say why it stopped. The reason is ++/// reduced to letters, digits and a few punctuation marks, which keeps a path or ++/// a key out of the log while still naming the cause. ++struct Failure { ++ code: &'static str, ++ name: String, ++ reason: String, ++} + +- if let Err(e) = eappx.load_keys(&key_collection) { +- eprintln!("Failed to load keys: {e}"); +- return ExitCode::FAILURE; ++impl Failure { ++ fn new(code: &'static str, name: &str, reason: &str) -> Self { ++ Self { ++ code, ++ name: sanitize(name, 60), ++ reason: sanitize(reason, 120), ++ } + } + +- if !outdir.exists() { +- if let Err(e) = std::fs::create_dir_all(&outdir) { +- eprintln!("Failed to create output directory {:?}: {e}", outdir); +- return ExitCode::FAILURE; ++ fn at(code: &'static str, path: &Path, reason: &str) -> Self { ++ let name = path.file_name().map(|name| name.to_string_lossy().into_owned()); ++ Self::new(code, &name.unwrap_or_default(), reason) ++ } ++} ++ ++fn sanitize(text: &str, limit: usize) -> String { ++ text.chars() ++ .map(|c| if c.is_ascii_alphanumeric() || matches!(c, ' ' | '.' | '_' | '-') { c } else { '?' }) ++ .take(limit) ++ .collect::() ++ .trim() ++ .to_string() ++} ++ ++fn report_failure(failure: &Failure, code: ExitCode) -> ExitCode { ++ eprintln!("NEXUS_EXTRACT_DIAGNOSTIC_V1 {}", failure.code); ++ eprintln!("NEXUS_EXTRACT_DETAIL_V1 {} {}", failure.name, failure.reason); ++ eprintln!("Extraction failed: {}: {}: {}", failure.code, failure.name, failure.reason); ++ code ++} ++ ++// EAppxMagic is EXPH (single), EXSH and EXBH (bundle). Anything else is not an ++// EAppx container, so a bundle's plain ZIP members are not recursed into. ++fn is_eappx(path: &Path) -> bool { ++ use std::io::Read; ++ let Ok(mut file) = std::fs::File::open(path) else { return false }; ++ let mut magic = [0u8; 4]; ++ if file.read_exact(&mut magic).is_err() { ++ return false; ++ } ++ matches!(&magic, b"EXPH" | b"EXSH" | b"EXBH") ++} ++ ++fn derive( ++ infile: &Path, ++ outdir: &Path, ++ keys: &KeyCollection, ++ depth: usize, ++ meter: Option<&Meter>, ++ release: bool, ++) -> Result<(), Failure> { ++ let file = std::fs::File::open(infile) ++ .map_err(|e| Failure::at("open", infile, &e.to_string()))?; ++ let mut reader = std::io::BufReader::new(file); ++ ++ let mut eappx = EAppxFile::from_stream(&mut reader) ++ .map_err(|e| Failure::at("header", infile, &e.to_string()))?; ++ ++ println!("{eappx}"); ++ ++ // The licence and the header name the same key differently, so the set is ++ // rebuilt per package and reconciled before the header is judged. ++ let mut required = KeyCollection::new(&keys.keys); ++ align_keys(&mut required, &eappx.header.key_ids); ++ ++ if !required.has_required_keys(&eappx.header.key_ids) { ++ // The count is the useful part: a license that carries one key cannot ++ // open a bundle whose members each declare their own. ++ return Err(Failure::new( ++ "missing-keys", ++ &infile.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default(), ++ &format!("{} of {} content keys present", required.keys.len(), eappx.header.key_ids.len()), ++ )); ++ } ++ ++ eappx ++ .load_keys(&required) ++ .map_err(|e| Failure::at("load-keys", infile, &e.to_string()))?; ++ ++ std::fs::create_dir_all(outdir) ++ .map_err(|e| Failure::at("create-dir", outdir, &e.to_string()))?; ++ ++ unpack(infile, &eappx, &mut reader, outdir, meter, release)?; ++ // The handle must close before a released container gives its space back. ++ drop(reader); ++ ++ println!("Extracted {}", infile.file_name().unwrap_or_default().to_string_lossy()); ++ ++ let mut nested: Vec = std::fs::read_dir(outdir) ++ .map_err(|e| Failure::at("list", outdir, &e.to_string()))? ++ .filter_map(|entry| entry.ok().map(|entry| entry.path())) ++ // The container being unpacked may itself sit in the destination, which is ++ // what `extract-eappx ./title.eappx .` asks for. Re-entering it would ++ // recurse into the same bytes and then delete the caller's file. ++ .filter(|path| std::fs::canonicalize(path).ok() != std::fs::canonicalize(infile).ok()) ++ .filter(|path| path.is_file() && is_eappx(path)) ++ .collect(); ++ nested.sort(); ++ ++ if nested.is_empty() { ++ return Ok(()); ++ } ++ if depth >= MAX_BUNDLE_DEPTH { ++ return Err(Failure::at("nesting", infile, "bundle nesting exceeds the limit")); ++ } ++ ++ for child in nested { ++ let name = child ++ .file_stem() ++ .map(|name| name.to_string_lossy().into_owned()) ++ .ok_or_else(|| Failure::at("no-name", &child, "package without a usable name"))?; ++ derive(&child, &outdir.join(&name), keys, depth + 1, meter, release)?; ++ // The member's bytes are no longer needed once its contents are on disk. ++ // A bundle of a full title holds tens of gigabytes, and keeping every ++ // member beside the decrypted copy doubles what the install occupies. ++ std::fs::remove_file(&child).ok(); ++ } ++ ++ Ok(()) ++} ++ ++/// Bytes currently on disk under `dir`. ++/// ++/// A bundle member is written as one file, so a per-file counter says nothing ++/// until it is finished. Measuring the destination catches the bytes as they ++/// land, whatever is writing them. ++pub fn tree_size(dir: &Path) -> u64 { ++ let mut total = 0; ++ let Ok(entries) = std::fs::read_dir(dir) else { return 0 }; ++ for entry in entries.flatten() { ++ let Ok(kind) = entry.file_type() else { continue }; ++ if kind.is_dir() { ++ total += tree_size(&entry.path()); ++ } else if let Ok(meta) = entry.metadata() { ++ total += meta.len(); + } + } ++ total ++} ++ ++/// Buffer sizes for each worker's own handle on the container. ++/// ++/// The crate's default 8 KiB reader turns one 64 KiB block into eight system ++/// calls, and a full title is millions of blocks. ++const READ_BUFFER: usize = 1 << 20; ++ ++/// Workers used to unpack one package. ++/// ++/// Files sit at independent offsets, so each worker opens its own handle and ++/// takes every Nth file. Decryption and inflation are both CPU-bound and one ++/// core was saturated, so this is where the headroom is. The limit is the ++/// device's write speed, which is reached a few workers in. ++fn workers() -> usize { ++ std::thread::available_parallelism() ++ .map(|count| count.get()) ++ .unwrap_or(1) ++ .clamp(1, 4) ++} + +- match eappx.extract(&mut reader, &outdir) { +- Ok(_) => { +- println!("Extracted {:?} to {:?}", infile, outdir); +- ExitCode::SUCCESS ++/// Writes a package's files, publishing what is left to write. ++/// ++/// This is the crate's own `extract`, split across workers and reported as it ++/// goes. The blockmap already totals every file's uncompressed length, so the ++/// end point is known before the first byte is written. ++fn unpack( ++ infile: &Path, ++ eappx: &EAppxFile, ++ reader: &mut std::io::BufReader, ++ outdir: &Path, ++ meter: Option<&Meter>, ++ release: bool, ++) -> Result<(), Failure> { ++ let total: u64 = eappx.blockmap.files.iter().map(|package| package.size).sum(); ++ if let Some(meter) = meter { ++ meter.roll(total); ++ } ++ ++ eappx ++ .extract_footprint_files(reader, outdir) ++ .map_err(|e| Failure::at("extract", infile, &e.to_string()))?; ++ ++ if eappx.header.is_bundle() { ++ eappx ++ .extract_blockmap_files(reader, outdir) ++ .map_err(|e| Failure::at("extract", infile, &e.to_string()))?; ++ eappx ++ .extract_bundle_files(reader, outdir) ++ .map_err(|e| Failure::at("extract", infile, &e.to_string()))?; ++ if release { ++ std::fs::remove_file(infile).ok(); + } +- Err(e) => { +- eprintln!("Extraction failed: {e}"); +- ExitCode::FAILURE ++ return Ok(()); ++ } ++ ++ let count = workers().min(eappx.blockmap.files.len().max(1)); ++ let failure = std::sync::Mutex::new(None::); ++ std::thread::scope(|scope| { ++ for shard in 0..count { ++ let failure = &failure; ++ scope.spawn(move || { ++ let Ok(handle) = std::fs::File::open(infile) else { ++ if let Ok(mut slot) = failure.lock() { ++ *slot = Some("a worker could not reopen the package".to_string()); ++ } ++ return; ++ }; ++ let mut stream = std::io::BufReader::with_capacity(READ_BUFFER, handle); ++ for (index, package) in eappx.blockmap.files.iter().enumerate() { ++ if index % count != shard { ++ continue; ++ } ++ if failure.lock().map(|slot| slot.is_some()).unwrap_or(true) { ++ return; ++ } ++ let Some(footer) = eappx.find_footer_for_file(package.id()) else { ++ if let Ok(mut slot) = failure.lock() { ++ *slot = Some("the blockmap names a file the package does not hold".to_string()); ++ } ++ return; ++ }; ++ let mut info = eappx::FileInfo::from(footer); ++ // The crate checks these only when asked, but filling them ++ // keeps the per-file path identical to its own extraction. ++ info.filehash = package.filehash_bytes(); ++ info.block_hashes = Some(package.block_hashes()); ++ // The blockmap's length and the footer's must agree, or the ++ // file written would be silently short. ++ if info.uncompressed_length != package.size { ++ if let Ok(mut slot) = failure.lock() { ++ *slot = Some("a package entry disagrees with its blockmap about its size".to_string()); ++ } ++ return; ++ } ++ if let Err(error) = eappx.save_file_to_fs(&mut stream, info, outdir, &package.name) { ++ if let Ok(mut slot) = failure.lock() { ++ *slot = Some(error.to_string()); ++ } ++ return; ++ } ++ if let Some(meter) = meter { ++ meter ++ .written ++ .fetch_add(package.size, std::sync::atomic::Ordering::Relaxed); ++ } ++ } ++ }); + } ++ }); ++ ++ if let Some(reason) = failure.into_inner().unwrap_or(None) { ++ return Err(Failure::at("extract", infile, &reason)); ++ } ++ ++ if release { ++ // The files are on disk; the container is not read again unless the ++ // install is retried from scratch. ++ std::fs::remove_file(infile).ok(); + } ++ Ok(()) + } +diff --git a/crates/xodus-cli/src/commands/license.rs b/crates/xodus-cli/src/commands/license.rs +index 4540549..b9fd91c 100644 +--- a/crates/xodus-cli/src/commands/license.rs ++++ b/crates/xodus-cli/src/commands/license.rs +@@ -1,5 +1,6 @@ + use std::process::ExitCode; + ++use base64::{Engine, engine::general_purpose::STANDARD}; + use tokio::fs::OpenOptions; + use tokio::io::AsyncWriteExt; + use xodus::tokens::TokenManager; +@@ -21,6 +22,10 @@ pub async fn run( + + let (key, game_splicense) = license.unwrap(); + tokio::fs::create_dir_all(&ciks).await.unwrap(); ++ // eappx-rs reads a text [Keys] file with base64 Key IDs, while the .cik ++ // format below is the binary form other tools expect. Write both so the ++ // same license dump serves either extractor. ++ let mut eappx_keys = String::from("[Keys]\n"); + for (uuid, content_key) in game_splicense.content_keys { + let unpacked = content_key.unpack(&key).expect("failed to unpack"); + let mut file = OpenOptions::new() +@@ -33,7 +38,21 @@ pub async fn run( + file.write_all(&uuid_buf).await.unwrap(); + file.write_all(&*unpacked).await.unwrap(); + file.flush().await.unwrap(); ++ eappx_keys.push_str(&format!( ++ "\"{}\" \"{}\"\n", ++ STANDARD.encode(uuid_buf), ++ STANDARD.encode(&*unpacked), ++ )); + } ++ let mut keys_file = OpenOptions::new() ++ .create(true) ++ .write(true) ++ .truncate(true) ++ .open(format!("{ciks}/eappx-keys.txt")) ++ .await ++ .unwrap(); ++ keys_file.write_all(eappx_keys.as_bytes()).await.unwrap(); ++ keys_file.flush().await.unwrap(); + + ExitCode::SUCCESS + } +diff --git a/crates/xodus-cli/src/commands/streaming.rs b/crates/xodus-cli/src/commands/streaming.rs +index 66e4135..a0136f8 100644 +--- a/crates/xodus-cli/src/commands/streaming.rs ++++ b/crates/xodus-cli/src/commands/streaming.rs +@@ -160,7 +160,19 @@ pub async fn run( + .iter() + .find(|p| p.file_name.ends_with(".msixvc")) + else { +- eprintln!("No .msixvc file found"); ++ // Legacy EAppx titles carry no .msixvc member: their bytes come ++ // from the download command and are unpacked by extract-eappx. ++ let legacy = package.package_files.iter().any(|p| { ++ let name = p.file_name.to_ascii_lowercase(); ++ name.ends_with(".eappx") || name.ends_with(".eappxbundle") ++ }); ++ if legacy { ++ eprintln!( ++ "This title uses a legacy EAppx package; use download then extract-eappx for this title" ++ ); ++ } else { ++ eprintln!("No .msixvc file found"); ++ } + return ExitCode::FAILURE; + }; + let Some(root) = file.cdn_root_paths.first() else { +diff --git a/crates/xodus-cli/src/package_plan.rs b/crates/xodus-cli/src/package_plan.rs +index 6187d56..f784c07 100644 +--- a/crates/xodus-cli/src/package_plan.rs ++++ b/crates/xodus-cli/src/package_plan.rs +@@ -93,7 +93,11 @@ fn inspect(product: &Value, id: &str) -> Result<(Vec, Vec), Stri + .filter(|name| package_family(name)).map(str::to_string); + let durable = kind == "Durable" && parent_product_id.is_some() && main_package_family_name.is_some() + && list(package, "Architectures").iter().any(|arch| arch.as_str() == Some("x64")); +- let supported = desktop && format == "MSIXVC" ++ // Legacy Store packages are installable on PC too. FH4 and other ++ // pre-MSIXVC titles ship as EAPPXBUNDLE/EAPPX and were refused here, ++ // which made the Store offer look unavailable even when owned. ++ let supported = desktop ++ && matches!(format.as_str(), "MSIXVC" | "EAPPX" | "EAPPXBUNDLE") + && (kind == "Game" || kind == "GameAddOn" || durable) + && properties["IsTrial"].as_bool() != Some(true) + && properties["IsPreOrder"].as_bool() != Some(true); +@@ -326,6 +330,17 @@ mod tests { + assert!(plan.select(None).is_err()); assert!(plan.select(Some(CID)).is_ok()); + assert_eq!(plan.json("9CCCCCCCCCCC","US")["status"],"choice"); + } ++ #[test] fn legacy_desktop_package_formats_are_installable() { ++ for format in ["EAPPX", "EAPPXBUNDLE"] { ++ let plan = from_products(ROOT,&BTreeMap::from([(ROOT.into(),package(ROOT,"Windows.Desktop",format))])).unwrap(); ++ assert_eq!(plan.select(None).unwrap(), CID, "{format}"); ++ assert_eq!(plan.json(ROOT,"US")["status"], "ready", "{format}"); ++ } ++ // A console legacy package is still not installable on PC. ++ let plan = from_products(ROOT,&BTreeMap::from([(ROOT.into(),package(ROOT,"Xbox.One","EAPPXBUNDLE"))])).unwrap(); ++ assert!(plan.select(None).is_err()); ++ assert!(plan.select(Some(CID)).is_err()); ++ } + #[test] fn durable_entitlement_back_references_do_not_form_bundle_cycles() { + const DURABLE: &str = "9DDDDDDDDDDD"; + let durable = json!({"ProductId":DURABLE,"ProductType":"Durable", diff --git a/tools/xbox/droiddeck-legacy-run.patch b/tools/xbox/droiddeck-legacy-run.patch new file mode 100644 index 0000000000..d7fbed5853 --- /dev/null +++ b/tools/xbox/droiddeck-legacy-run.patch @@ -0,0 +1,124 @@ +diff --git a/crates/xodus-cli/src/commands/run.rs b/crates/xodus-cli/src/commands/run.rs +index 44ea870..1d8e218 100644 +--- a/crates/xodus-cli/src/commands/run.rs ++++ b/crates/xodus-cli/src/commands/run.rs +@@ -20,6 +20,7 @@ use tokio::process::Command; + use xodus::models::secrets::Token; + use xodus::tokens::TokenManager; + ++use crate::commands::legacy_install::{dependencies, ensure_frameworks}; + use crate::license::get_license; + + const PLAYFAB_RELYING_PARTY: &str = "http://playfab.xboxlive.com/"; +@@ -135,6 +136,98 @@ fn wine_exit_code(status: std::process::ExitStatus) -> u8 { + status.code().unwrap_or_else(|| 128 + status.signal().unwrap_or(1)) as u8 + } + ++/// Start a title that was unpacked into its install folder. ++/// ++/// There is no container to read a content key for or to build a launch view ++/// from, so the named executable runs as it lies, with the PlayFab header the ++/// game signs in with. ++async fn run_unpacked( ++ client: &reqwest::Client, ++ tokens: &TokenManager, ++ folder: &Path, ++ wine: String, ++ exe: Option<&str>, ++ materialize_chain: bool, ++ market: Option, ++) -> ExitCode { ++ let Some(name) = exe.filter(|name| !name.is_empty()) else { ++ eprintln!("no executable was named for the unpacked folder {}", folder.display()); ++ return ExitCode::FAILURE; ++ }; ++ let image = folder.join(name); ++ if !image.is_file() { ++ eprintln!("{} is not in the unpacked folder {}", name, folder.display()); ++ return ExitCode::FAILURE; ++ } ++ // A packaged Win32 program starts like any executable. A UWP application ++ // expects the app model to activate a view first, and this runtime has none, ++ // so say so when the launch dies instead of leaving a loader failure. ++ if let Some(entry) = crate::commands::legacy_install::entry_point(folder) { ++ if !entry.eq_ignore_ascii_case("Windows.FullTrustApplication") { ++ eprintln!("NEXUS_LEGACY_INSTALL_DIAGNOSTIC_V1 uwp-entry-point"); ++ eprintln!("NEXUS_LEGACY_INSTALL_DETAIL_V1 {name} is activated by {entry}, a UWP app model this runtime has no host for"); ++ } ++ } ++ // An unpacked title gets no package graph, so the frameworks its manifest ++ // declares are fetched here the first time it launches. ++ let declared = dependencies(folder); ++ eprintln!("NEXUS_LEGACY_INSTALL_DETAIL_V1 unpacked launch {name} with {} declared frameworks", declared.len()); ++ if !declared.is_empty() { ++ if let Ok(delivery) = crate::commands::store_delivery::client() { ++ let region = market.unwrap_or_else(|| "US".into()).to_uppercase(); ++ if let Err(error) = ensure_frameworks(&delivery, folder, ®ion).await { ++ eprintln!("NEXUS_LEGACY_INSTALL_DETAIL_V1 framework install failed {}", crate::commands::legacy_install::plain_for_log(&error)); ++ } ++ } ++ } ++ let playfab = playfab_auth_header(client, tokens).await; ++ ++ if wine == "droiddeck:prepare" { ++ use std::io::Write; ++ if !materialize_chain { ++ return ExitCode::FAILURE; ++ } ++ let ready = serde_json::json!({ ++ "exe": image, ++ "playfab": playfab, ++ }); ++ println!("DROIDDECK_LAUNCH_V1 {}", ready); ++ let _ = std::io::stdout().flush(); ++ let mut release = String::new(); ++ let _ = std::io::stdin().read_line(&mut release); ++ return ExitCode::SUCCESS; ++ } ++ ++ let mut command = Command::new(&wine); ++ command.arg(&image); ++ match playfab { ++ Some(header) => { ++ command.env("XODUS_XSTS_PLAYFAB", header); ++ } ++ None => eprintln!("could not authorise a PlayFab token; in-game sign-in may fail"), ++ } ++ ++ let mut wn = match command.spawn() { ++ Ok(child) => child, ++ Err(err) => { ++ eprintln!("failed to start Wine: {}", err); ++ return ExitCode::FAILURE; ++ } ++ }; ++ ++ let pid = wn.id().unwrap_or(0); ++ ++ if pid > 0 { ++ let _ = ctrlc::set_handler(move || { ++ let _ = kill(Pid::from_raw(pid as i32), Signal::SIGINT); ++ }); ++ } ++ ++ let status = wn.wait().await.unwrap(); ++ ++ ExitCode::from(wine_exit_code(status)) ++} ++ + // Real files in a full launch view must not be redirected back into memfds. + // Keep source mappings and encrypted DLL mappings; no title/EAC special case. + fn launch_file_maps( +@@ -542,6 +635,12 @@ pub async fn run( + let out_absolute = std::fs::canonicalize(out).unwrap(); + let final_path = out.join(".xodus-streaming.msixvc"); + ++ // A legacy package unpacks where it was installed and keeps no streaming ++ // container, so the folder itself is what gets launched. ++ if !final_path.is_file() { ++ return run_unpacked(client, tokens, &out_absolute, wine, exe.as_deref(), materialize_chain, market).await; ++ } ++ + let mut file = OpenOptions::new() + .read(true) + .open(final_path.to_owned()) diff --git a/tools/xbox/droiddeck-msixvc2.patch b/tools/xbox/droiddeck-msixvc2.patch new file mode 100644 index 0000000000..b02ec68bbb --- /dev/null +++ b/tools/xbox/droiddeck-msixvc2.patch @@ -0,0 +1,1131 @@ +diff --git a/Cargo.lock b/Cargo.lock +index 5dfc09a..15198af 100644 +--- a/Cargo.lock ++++ b/Cargo.lock +@@ -83,6 +83,21 @@ dependencies = [ + "memchr", + ] + ++[[package]] ++name = "alloc-no-stdlib" ++version = "2.0.4" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" ++ ++[[package]] ++name = "alloc-stdlib" ++version = "0.2.4" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" ++dependencies = [ ++ "alloc-no-stdlib", ++] ++ + [[package]] + name = "android_system_properties" + version = "0.1.6" +@@ -586,6 +601,16 @@ dependencies = [ + "objc2", + ] + ++[[package]] ++name = "brotli-decompressor" ++version = "5.0.3" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" ++dependencies = [ ++ "alloc-no-stdlib", ++ "alloc-stdlib", ++] ++ + [[package]] + name = "bstr" + version = "1.13.1" +@@ -728,6 +753,33 @@ dependencies = [ + "windows-link 0.2.1", + ] + ++[[package]] ++name = "ciborium" ++version = "0.2.2" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" ++dependencies = [ ++ "ciborium-io", ++ "ciborium-ll", ++ "serde", ++] ++ ++[[package]] ++name = "ciborium-io" ++version = "0.2.2" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" ++ ++[[package]] ++name = "ciborium-ll" ++version = "0.2.2" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" ++dependencies = [ ++ "ciborium-io", ++ "half", ++] ++ + [[package]] + name = "cipher" + version = "0.4.4" +@@ -1055,6 +1107,12 @@ dependencies = [ + "winapi", + ] + ++[[package]] ++name = "crunchy" ++version = "0.2.4" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" ++ + [[package]] + name = "crypto-bigint" + version = "0.5.5" +@@ -2370,6 +2428,17 @@ dependencies = [ + "tracing", + ] + ++[[package]] ++name = "half" ++version = "2.7.1" ++source = "registry+https://github.com/rust-lang/crates.io-index" ++checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" ++dependencies = [ ++ "cfg-if", ++ "crunchy", ++ "zerocopy", ++] ++ + [[package]] + name = "hash2curve" + version = "0.14.0" +@@ -7178,9 +7247,13 @@ dependencies = [ + name = "xodus-cli" + version = "0.1.0" + dependencies = [ ++ "aes 0.9.3", + "async-trait", + "base64 0.23.1", ++ "brotli-decompressor", ++ "cbc 0.2.1", + "chrono", ++ "ciborium", + "clap", + "console-subscriber", + "ctrlc", +@@ -7188,6 +7261,7 @@ dependencies = [ + "flate2", + "fs2", + "futures-util", ++ "hmac 0.13.0", + "indicatif", + "inquire", + "msixvc", +@@ -7196,6 +7270,7 @@ dependencies = [ + "reqwest 0.13.4", + "rustix", + "serde_json", ++ "sha2 0.11.0", + "tao", + "tempfile", + "tokio", +diff --git a/crates/xodus-cli/Cargo.toml b/crates/xodus-cli/Cargo.toml +index f49470b..3579838 100644 +--- a/crates/xodus-cli/Cargo.toml ++++ b/crates/xodus-cli/Cargo.toml +@@ -31,6 +31,12 @@ tempfile = "3.27.0" + rustix = "1.1.4" + ctrlc = "3.5.2" + nix = "0.31.3" ++aes = "0.9.2" ++cbc = "0.2.1" ++hmac = "0.13.0" ++sha2 = "0.11.0" ++ciborium = "0.2.2" ++brotli-decompressor = "5.0.0" + + [features] + default = ["native-webview"] +diff --git a/crates/xodus-cli/src/commands.rs b/crates/xodus-cli/src/commands.rs +index 825c24e..c23f637 100644 +--- a/crates/xodus-cli/src/commands.rs ++++ b/crates/xodus-cli/src/commands.rs +@@ -20,6 +20,7 @@ pub mod library; + #[cfg(unix)] + pub mod run; + pub mod splicense; ++pub mod msixvc2; + pub mod streaming; + + pub mod native_social; +diff --git a/crates/xodus-cli/src/commands/msixvc2.rs b/crates/xodus-cli/src/commands/msixvc2.rs +new file mode 100644 +index 0000000..5caab57 +--- /dev/null ++++ b/crates/xodus-cli/src/commands/msixvc2.rs +@@ -0,0 +1,820 @@ ++use std::collections::HashMap; ++use std::io::{ErrorKind, Read, Seek, SeekFrom, Write}; ++use std::path::{Component, Path, PathBuf}; ++ ++use aes::cipher::{BlockModeDecrypt, KeyIvInit, block_padding::NoPadding}; ++use ciborium::Value; ++use futures_util::{StreamExt, stream}; ++use hmac::{Hmac, Mac}; ++use sha2::{Digest, Sha256, Sha384}; ++ ++const HOSTS: [&str; 4] = ["assets1.xboxlive.com", "assets2.xboxlive.com", "xvcf1.xboxlive.com", "xvcf2.xboxlive.com"]; ++const KDF_LABEL: &[u8] = b"MSIXVC2:PackageData:AES_256_CBC"; ++const MAX_REQUEST: u64 = 16 * 1024 * 1024; ++const PARALLEL: usize = 6; ++const BROTLI: u64 = 2; ++const DEFLATE: u64 = 1; ++const STATE: &str = ".droiddeck-install"; ++const PARTIAL: &str = "partial"; ++const VERIFIED: &str = "verified"; ++ ++pub fn is_package(folder: &Path) -> bool { ++ folder.join("XboxPackage.cbor").is_file() ++} ++ ++pub fn content_id(folder: &Path) -> Result { ++ let package = read_cbor(&folder.join("XboxPackage.cbor"))?; ++ text(&package, 260).map(str::to_owned).ok_or_else(|| "The package names no content id".to_string()) ++} ++ ++#[derive(Clone)] ++pub struct Segment { ++ hash: Vec, ++ length: u64, ++ compression: u64, ++ stored: u64, ++ key: Option>, ++ wrapped: Option>, ++ wrap_iv: [u8; 16], ++ box_hash: Option>, ++ box_index: usize, ++ offset: u64, ++ span: u64, ++} ++ ++pub struct Entry { ++ pub path: PathBuf, ++ size: u64, ++ hash: Option>, ++ segments: Vec, ++} ++ ++pub struct Plan { ++ pub entries: Vec, ++ boxes: Vec, ++ package_key: [u8; 32], ++} ++ ++impl Plan { ++ pub fn total(&self) -> u64 { ++ self.entries.iter().map(|entry| entry.size).sum() ++ } ++ ++ pub fn remaining(&self, out: &Path) -> u64 { ++ let root = out.canonicalize().unwrap_or_else(|_| out.to_path_buf()); ++ let verified = verified(&root); ++ self.entries.iter().filter(|entry| !complete(&root, entry, &verified)).map(|entry| entry.size).sum() ++ } ++} ++ ++fn identity(entry: &Entry) -> String { ++ let mut digest = Sha384::new(); ++ digest.update(entry.path.to_string_lossy().as_bytes()); ++ digest.update([0]); ++ digest.update(entry.size.to_be_bytes()); ++ match &entry.hash { ++ Some(hash) => digest.update(hash), ++ None => entry.segments.iter().for_each(|segment| digest.update(&segment.hash)), ++ } ++ digest.finalize().iter().map(|byte| format!("{byte:02x}")).collect() ++} ++ ++fn key(path: &Path) -> String { ++ Sha256::digest(path.to_string_lossy().as_bytes()).iter().map(|byte| format!("{byte:02x}")).collect() ++} ++ ++fn verified(root: &Path) -> HashMap { ++ let record = root.join(STATE).join(VERIFIED); ++ if !std::fs::symlink_metadata(&record).is_ok_and(|meta| meta.is_file()) { ++ return HashMap::new(); ++ } ++ let text = std::fs::read_to_string(record).unwrap_or_default(); ++ text[..text.rfind('\n').map_or(0, |end| end + 1)] ++ .lines() ++ .filter_map(|line| line.split_once(' ')) ++ .map(|(path, identity)| (path.to_owned(), identity.to_owned())) ++ .collect() ++} ++ ++fn complete(root: &Path, entry: &Entry, verified: &HashMap) -> bool { ++ verified.get(&key(&entry.path)) == Some(&identity(entry)) ++ && std::fs::symlink_metadata(root.join(&entry.path)).is_ok_and(|meta| meta.is_file() && meta.len() == entry.size) ++} ++ ++fn note(record: &Path, path: &Path, identity: &str) -> Result<(), String> { ++ std::fs::OpenOptions::new() ++ .create(true) ++ .read(true) ++ .append(true) ++ .open(record) ++ .and_then(|mut file| { ++ let length = file.metadata()?.len(); ++ let mut last = [0u8; 1]; ++ if length > 0 { ++ file.seek(SeekFrom::Start(length - 1))?; ++ file.read_exact(&mut last)?; ++ } ++ if length > 0 && last[0] != b'\n' { ++ let mut end = length; ++ let mut keep = 0; ++ let mut chunk = vec![0u8; 4096]; ++ while end > 0 { ++ let start = end.saturating_sub(chunk.len() as u64); ++ let part = &mut chunk[..(end - start) as usize]; ++ file.seek(SeekFrom::Start(start))?; ++ file.read_exact(part)?; ++ if let Some(at) = part.iter().rposition(|byte| *byte == b'\n') { ++ keep = start + at as u64 + 1; ++ break; ++ } ++ end = start; ++ } ++ file.set_len(keep)?; ++ } ++ writeln!(file, "{} {identity}", key(path))?; ++ file.sync_all() ++ }) ++ .map_err(|error| format!("Could not record a finished game file: {error}")) ++} ++ ++fn folder(root: &Path, relative: &Path) -> Result { ++ let mut at = root.to_path_buf(); ++ for part in relative.components() { ++ at.push(part); ++ match std::fs::symlink_metadata(&at) { ++ Ok(meta) if meta.is_dir() => {} ++ Ok(_) => return Err("The game folder holds a link or file where a folder belongs".into()), ++ Err(error) if error.kind() == ErrorKind::NotFound => match std::fs::create_dir(&at) { ++ Ok(()) => {} ++ Err(error) if error.kind() == ErrorKind::AlreadyExists && std::fs::symlink_metadata(&at).is_ok_and(|meta| meta.is_dir()) => {} ++ Err(error) => return Err(format!("Could not create a game folder: {error}")), ++ }, ++ Err(error) => return Err(format!("Could not read the game folder: {error}")), ++ } ++ } ++ Ok(at) ++} ++ ++fn place(root: &Path, relative: &Path) -> Result { ++ let parent = folder(root, relative.parent().unwrap_or(Path::new("")))?; ++ let target = parent.join(relative.file_name().ok_or("The package names an unusable file path")?); ++ match std::fs::symlink_metadata(&target) { ++ Ok(meta) if !meta.is_file() => Err("The game folder holds a link or folder where a file belongs".into()), ++ _ => Ok(target), ++ } ++} ++ ++pub fn reclaim(out: &Path) -> Result<(), String> { ++ let root = out.canonicalize().map_err(|error| format!("Could not open the game folder: {error}"))?; ++ let state = root.join(STATE); ++ match std::fs::symlink_metadata(&state) { ++ Ok(meta) if meta.is_dir() => {} ++ Ok(_) => return Err("The game folder holds a link or file where the install state belongs".into()), ++ Err(_) => return Ok(()), ++ } ++ let partial = state.join(PARTIAL); ++ match std::fs::symlink_metadata(&partial) { ++ Ok(meta) if meta.is_dir() => std::fs::remove_dir_all(&partial), ++ Ok(_) => std::fs::remove_file(&partial), ++ Err(_) => Ok(()), ++ } ++ .map_err(|error| format!("Could not clear an unfinished download: {error}")) ++} ++ ++pub async fn plan(client: &reqwest::Client, folder: &Path, content_keys: &HashMap<[u8; 16], [u8; 32]>) -> Result { ++ let package = read_cbor(&folder.join("XboxPackage.cbor"))?; ++ let boxes: Vec = list(&package, 264) ++ .ok_or("The package lists no content boxes")? ++ .iter() ++ .map(|item| text(item, 25).map(str::to_owned).ok_or("A content box has no location".to_string())) ++ .collect::>()?; ++ for location in &boxes { ++ if !location.starts_with('/') || location.contains("..") || location.contains("://") { ++ return Err("The package lists an unusable box location".into()); ++ } ++ } ++ let package_key = package_key(&package, content_keys)?; ++ let initial = iv(&package, 27).unwrap_or([0; 16]); ++ let chunks = list(&package, 265).ok_or("The package lists no chunks")?; ++ let mut entries = Vec::new(); ++ for chunk in chunks { ++ let id = int(chunk, 24).ok_or("A chunk has no id")?; ++ let secret = get(chunk, 26).ok_or("A chunk has no details")?; ++ let details = secret_details(client, &boxes, secret, initial, &package_key, chunks.len()).await?; ++ let names: Vec = list(&details, 28) ++ .ok_or("A chunk's details list no files")? ++ .iter() ++ .map(|item| text(item, 25).map(str::to_owned).ok_or("A file has no name".to_string())) ++ .collect::>()?; ++ let layout = read_cbor(&folder.join("Chunks").join(format!("{id}.cbor")))?; ++ let files = list(&layout, 28).ok_or("A chunk lists no files")?; ++ if files.len() != names.len() { ++ return Err("A chunk's names and files disagree".into()); ++ } ++ let mut rolling = iv(&layout, 27).unwrap_or([0; 16]); ++ for (file, name) in files.iter().zip(names) { ++ let size = int(file, 2).ok_or("A file has no size")?; ++ let hash = hash(file, 1); ++ let segments = match list(file, 29) { ++ Some(items) => segments(items, &mut rolling)?, ++ None => { ++ let file_id = int(file, 24).ok_or("A file has no id")?; ++ let detail = read_cbor(&folder.join("Files").join(format!("{file_id}.cbor")))?; ++ let mut own = iv(&detail, 27).unwrap_or([0; 16]); ++ segments(list(&detail, 29).ok_or("A file lists no segments")?, &mut own)? ++ } ++ }; ++ if segments.iter().map(|segment| segment.length).sum::() != size { ++ return Err("A file's segments do not add up to its size".into()); ++ } ++ entries.push(Entry { path: relative(&name)?, size, hash, segments }); ++ } ++ } ++ Ok(Plan { entries, boxes, package_key }) ++} ++ ++pub async fn install(client: &reqwest::Client, plan: &Plan, out: &Path, progress: &(dyn Fn(u64) + Sync)) -> Result<(), String> { ++ let root = out.canonicalize().map_err(|error| format!("Could not open the game folder: {error}"))?; ++ let verified = verified(&root); ++ let record = place(&root, &Path::new(STATE).join(VERIFIED))?; ++ for (index, entry) in plan.entries.iter().enumerate() { ++ if complete(&root, entry, &verified) { ++ progress(entry.size); ++ continue; ++ } ++ let target = place(&root, &entry.path)?; ++ let partial = folder(&root, &Path::new(STATE).join(PARTIAL))?.join(index.to_string()); ++ match std::fs::remove_file(&partial) { ++ Err(error) if error.kind() != ErrorKind::NotFound => return Err(format!("Could not clear an unfinished download: {error}")), ++ _ => {} ++ } ++ let mut file = std::fs::OpenOptions::new() ++ .write(true) ++ .create_new(true) ++ .open(&partial) ++ .map_err(|error| format!("Could not write a game file: {error}"))?; ++ let mut digest = Sha384::new(); ++ let mut results = stream::iter(requests(&entry.segments)) ++ .map(|request| fetch_request(client, plan, request)) ++ .buffered(PARALLEL); ++ while let Some(result) = results.next().await { ++ for plain in result? { ++ digest.update(&plain); ++ file.write_all(&plain).map_err(|error| format!("Could not write a game file: {error}"))?; ++ progress(plain.len() as u64); ++ } ++ } ++ file.sync_all().map_err(|error| format!("Could not write a game file: {error}"))?; ++ drop(file); ++ if let Some(expected) = &entry.hash ++ && digest.finalize().as_slice() != expected.as_slice() ++ { ++ std::fs::remove_file(&partial).ok(); ++ return Err("A downloaded game file failed verification".into()); ++ } ++ if place(&root, &entry.path)? != target { ++ return Err("The game folder changed during the install".into()); ++ } ++ note(&record, &entry.path, "-")?; ++ std::fs::rename(&partial, &target).map_err(|error| format!("Could not finish a game file: {error}"))?; ++ note(&record, &entry.path, &identity(entry))?; ++ } ++ reclaim(&root) ++} ++ ++struct Request<'a> { ++ box_index: usize, ++ offset: u64, ++ length: u64, ++ segments: &'a [Segment], ++} ++ ++fn requests(segments: &[Segment]) -> Vec> { ++ let mut found: Vec> = Vec::new(); ++ let mut start = 0; ++ while start < segments.len() { ++ let first = &segments[start]; ++ let mut end = start + 1; ++ let mut length = first.span; ++ while end < segments.len() { ++ let next = &segments[end]; ++ if next.box_index != first.box_index || next.offset != first.offset + length || length + next.span > MAX_REQUEST { ++ break; ++ } ++ length += next.span; ++ end += 1; ++ } ++ found.push(Request { box_index: first.box_index, offset: first.offset, length, segments: &segments[start..end] }); ++ start = end; ++ } ++ found ++} ++ ++async fn fetch_request(client: &reqwest::Client, plan: &Plan, request: Request<'_>) -> Result>, String> { ++ let bytes = fetch(client, &plan.boxes[request.box_index], request.offset, request.length).await?; ++ let mut at = 0usize; ++ let mut plain = Vec::with_capacity(request.segments.len()); ++ for segment in request.segments { ++ let stored = &bytes[at..at + segment.span as usize]; ++ at += segment.span as usize; ++ plain.push(open(segment, stored, &plan.package_key)?); ++ } ++ Ok(plain) ++} ++ ++async fn fetch(client: &reqwest::Client, location: &str, offset: u64, length: u64) -> Result, String> { ++ let mut last = String::new(); ++ for attempt in 0..HOSTS.len() * 2 { ++ let host = HOSTS[attempt % HOSTS.len()]; ++ let response = client ++ .get(format!("http://{host}{location}")) ++ .header("Range", format!("bytes={}-{}", offset, offset + length - 1)) ++ .send() ++ .await; ++ match response { ++ Ok(response) if response.status().as_u16() == 206 => match response.bytes().await { ++ Ok(body) if body.len() as u64 == length => return Ok(body.to_vec()), ++ Ok(_) => last = "the content host sent a short range".into(), ++ Err(error) => last = error.to_string(), ++ }, ++ Ok(response) => last = format!("the content host answered HTTP {}", response.status().as_u16()), ++ Err(error) => last = error.to_string(), ++ } ++ tokio::time::sleep(std::time::Duration::from_millis(500 * (attempt as u64 + 1))).await; ++ } ++ Err(format!("Could not download game data: {last}")) ++} ++ ++fn open(segment: &Segment, stored: &[u8], package_key: &[u8; 32]) -> Result, String> { ++ if let Some(expected) = &segment.box_hash ++ && Sha384::digest(stored).as_slice() != expected.as_slice() ++ { ++ return Err("Downloaded game data failed verification".into()); ++ } ++ let key = match (&segment.key, &segment.wrapped) { ++ (Some(key), _) => Some(key32(key)?), ++ (None, Some(wrapped)) => Some(key32(&cbc(package_key, &segment.wrap_iv, wrapped)?)?), ++ (None, None) => None, ++ }; ++ let decrypted = match key { ++ Some(key) => { ++ let mut iv = [0u8; 16]; ++ iv.copy_from_slice(segment.hash.get(..16).ok_or("A segment hash is too short")?); ++ cbc(&key, &iv, stored)? ++ } ++ None => stored.to_vec(), ++ }; ++ let body = decrypted.get(..segment.stored as usize).ok_or("A segment is shorter than its stored size")?; ++ let plain = match segment.compression { ++ 0 => body.to_vec(), ++ BROTLI => { ++ let mut out = Vec::with_capacity(segment.length as usize); ++ brotli_decompressor::Decompressor::new(body, 4096) ++ .take(segment.length + 1) ++ .read_to_end(&mut out) ++ .map_err(|_| "A segment could not be decompressed".to_string())?; ++ out ++ } ++ DEFLATE => { ++ let mut out = Vec::with_capacity(segment.length as usize); ++ flate2::read::DeflateDecoder::new(body) ++ .take(segment.length + 1) ++ .read_to_end(&mut out) ++ .map_err(|_| "A segment could not be decompressed".to_string())?; ++ out ++ } ++ _ => return Err("A segment uses an unsupported compression".into()), ++ }; ++ if plain.len() as u64 != segment.length || Sha384::digest(&plain).as_slice() != segment.hash.as_slice() { ++ return Err("A game data segment failed verification".into()); ++ } ++ Ok(plain) ++} ++ ++async fn secret_details( ++ client: &reqwest::Client, ++ boxes: &[String], ++ secret: &Value, ++ initial: [u8; 16], ++ package_key: &[u8; 32], ++ chunks: usize, ++) -> Result { ++ let mut base = initial; ++ let segment = segment(secret, &mut base)?; ++ let stored = fetch(client, boxes.get(segment.box_index).ok_or("A chunk refers to a missing box")?, segment.offset, segment.span).await?; ++ for step in 0..=chunks as u128 { ++ let mut candidate = segment.clone(); ++ if get(secret, 7).is_none() { ++ candidate.wrap_iv = (u128::from_be_bytes(initial).wrapping_add(step)).to_be_bytes(); ++ } ++ if let Ok(plain) = open(&candidate, &stored, package_key) { ++ return ciborium::de::from_reader::(plain.as_slice()) ++ .map(untag) ++ .map_err(|_| "A chunk's details are not readable".to_string()); ++ } ++ if candidate.wrapped.is_none() { ++ break; ++ } ++ } ++ Err("Could not decrypt a chunk's details with this license".into()) ++} ++ ++fn package_key(package: &Value, content_keys: &HashMap<[u8; 16], [u8; 32]>) -> Result<[u8; 32], String> { ++ let groups = list(package, 262).ok_or("The package lists no keys")?; ++ for group in groups { ++ let sources = match group { ++ Value::Array(items) => items.as_slice(), ++ _ => continue, ++ }; ++ for source in sources { ++ let Some(id) = text(source, 288).and_then(|id| hex(id).ok()) else { continue }; ++ let Some(short) = id.get(..16).and_then(|bytes| <[u8; 16]>::try_from(bytes).ok()) else { continue }; ++ let Some(master) = content_keys.get(&short) else { continue }; ++ let context = bytes(source, 286).ok_or("A package key has no derivation context")?; ++ let wrap_iv = iv(source, 7).ok_or("A package key has no wrapping IV")?; ++ let wrapped = bytes(source, 6).ok_or("A package key is missing")?; ++ let kek = derive(master, context); ++ return key32(&cbc(&kek, &wrap_iv, wrapped)?); ++ } ++ } ++ Err("The license holds no key for this package".into()) ++} ++ ++fn derive(master: &[u8; 32], context: &[u8]) -> [u8; 32] { ++ let mut message = Vec::with_capacity(4 + KDF_LABEL.len() + 1 + context.len() + 4); ++ message.extend_from_slice(&1u32.to_be_bytes()); ++ message.extend_from_slice(KDF_LABEL); ++ message.push(0); ++ message.extend_from_slice(context); ++ message.extend_from_slice(&256u32.to_be_bytes()); ++ let mut mac = as hmac::KeyInit>::new_from_slice(master).expect("HMAC takes any key length"); ++ mac.update(&message); ++ mac.finalize().into_bytes().into() ++} ++ ++fn cbc(key: &[u8; 32], iv: &[u8; 16], data: &[u8]) -> Result, String> { ++ if data.len() % 16 != 0 { ++ return Err("Encrypted game data is not block aligned".into()); ++ } ++ let mut out = data.to_vec(); ++ cbc::Decryptor::::new(key.into(), iv.into()) ++ .decrypt_padded::(&mut out) ++ .map_err(|_| "Game data could not be decrypted".to_string())?; ++ Ok(out) ++} ++ ++fn segments(items: &[Value], rolling: &mut [u8; 16]) -> Result, String> { ++ items.iter().map(|item| segment(item, rolling)).collect() ++} ++ ++fn segment(item: &Value, rolling: &mut [u8; 16]) -> Result { ++ let length = int(item, 2).ok_or("A segment has no length")?; ++ let segment = Segment { ++ hash: hash(item, 1).ok_or("A segment has no hash")?, ++ length, ++ compression: int(item, 3).unwrap_or(0), ++ stored: int(item, 4).unwrap_or(length), ++ key: bytes(item, 5).map(<[u8]>::to_vec), ++ wrapped: bytes(item, 6).map(<[u8]>::to_vec), ++ wrap_iv: iv(item, 7).unwrap_or(*rolling), ++ box_hash: hash(item, 8), ++ box_index: int(item, 9).unwrap_or(0) as usize, ++ offset: int(item, 10).unwrap_or(0), ++ span: int(item, 11).unwrap_or(length), ++ }; ++ if segment.stored > segment.span { ++ return Err("A segment is larger than its stored range".into()); ++ } ++ *rolling = u128::from_be_bytes(*rolling).wrapping_add(1).to_be_bytes(); ++ Ok(segment) ++} ++ ++fn relative(name: &str) -> Result { ++ let path = PathBuf::from(name.replace('\\', "/")); ++ if name.is_empty() ++ || name.contains(':') ++ || !path.components().all(|part| matches!(part, Component::Normal(_))) ++ || path.components().next().is_some_and(|part| part.as_os_str().to_string_lossy().eq_ignore_ascii_case(STATE)) ++ { ++ return Err("The package names an unusable file path".into()); ++ } ++ Ok(path) ++} ++ ++fn read_cbor(path: &Path) -> Result { ++ let file = std::fs::File::open(path).map_err(|_| "The package index is incomplete".to_string())?; ++ ciborium::de::from_reader::(std::io::BufReader::new(file)) ++ .map(untag) ++ .map_err(|_| "The package index is not readable".to_string()) ++} ++ ++fn untag(value: Value) -> Value { ++ match value { ++ Value::Tag(_, inner) => untag(*inner), ++ other => other, ++ } ++} ++ ++fn get(value: &Value, key: u64) -> Option<&Value> { ++ let Value::Map(entries) = value else { return None }; ++ entries.iter().find_map(|(k, v)| match k { ++ Value::Integer(number) if u64::try_from(*number).ok() == Some(key) => Some(v), ++ _ => None, ++ }) ++} ++ ++fn int(value: &Value, key: u64) -> Option { ++ match get(value, key)? { ++ Value::Integer(number) => u64::try_from(*number).ok(), ++ _ => None, ++ } ++} ++ ++fn text(value: &Value, key: u64) -> Option<&str> { ++ match get(value, key)? { ++ Value::Text(text) => Some(text), ++ _ => None, ++ } ++} ++ ++fn bytes(value: &Value, key: u64) -> Option<&[u8]> { ++ match get(value, key)? { ++ Value::Bytes(bytes) => Some(bytes), ++ Value::Tag(_, inner) => match inner.as_ref() { ++ Value::Bytes(bytes) => Some(bytes), ++ _ => None, ++ }, ++ _ => None, ++ } ++} ++ ++fn hash(value: &Value, key: u64) -> Option> { ++ bytes(value, key).filter(|bytes| bytes.len() == 48).map(<[u8]>::to_vec) ++} ++ ++fn iv(value: &Value, key: u64) -> Option<[u8; 16]> { ++ bytes(value, key).and_then(|bytes| <[u8; 16]>::try_from(bytes).ok()) ++} ++ ++fn list(value: &Value, key: u64) -> Option<&[Value]> { ++ match get(value, key)? { ++ Value::Array(items) => Some(items), ++ _ => None, ++ } ++} ++ ++fn key32(bytes: &[u8]) -> Result<[u8; 32], String> { ++ <[u8; 32]>::try_from(bytes.get(..32).ok_or("A key is too short")?).map_err(|_| "A key is too short".to_string()) ++} ++ ++fn hex(text: &str) -> Result, ()> { ++ if text.len() % 2 != 0 { ++ return Err(()); ++ } ++ (0..text.len()).step_by(2).map(|at| u8::from_str_radix(&text[at..at + 2], 16).map_err(|_| ())).collect() ++} ++ ++#[cfg(test)] ++mod tests { ++ use super::*; ++ use aes::cipher::BlockModeEncrypt; ++ ++ fn encrypt(key: &[u8; 32], iv: &[u8; 16], data: &[u8]) -> Vec { ++ let mut out = data.to_vec(); ++ cbc::Encryptor::::new(key.into(), iv.into()).encrypt_padded::(&mut out, data.len()).unwrap(); ++ out ++ } ++ ++ fn sealed(plain: &[u8], segment_key: &[u8; 32]) -> (Segment, Vec) { ++ let hash = Sha384::digest(plain).to_vec(); ++ let mut padded = plain.to_vec(); ++ padded.resize(plain.len().div_ceil(16) * 16, 0); ++ let mut iv = [0u8; 16]; ++ iv.copy_from_slice(&hash[..16]); ++ let stored = encrypt(segment_key, &iv, &padded); ++ let segment = Segment { ++ hash, ++ length: plain.len() as u64, ++ compression: 0, ++ stored: plain.len() as u64, ++ key: Some(segment_key.to_vec()), ++ wrapped: None, ++ wrap_iv: [0; 16], ++ box_hash: Some(Sha384::digest(&stored).to_vec()), ++ box_index: 0, ++ offset: 0, ++ span: stored.len() as u64, ++ }; ++ (segment, stored) ++ } ++ ++ #[test] ++ fn a_segment_opens_only_with_its_key_and_hashes() { ++ let (segment, stored) = sealed(b"game data that is not block aligned", &[7; 32]); ++ assert_eq!(open(&segment, &stored, &[0; 32]).unwrap(), b"game data that is not block aligned"); ++ let mut tampered = stored.clone(); ++ tampered[3] ^= 1; ++ assert!(open(&segment, &tampered, &[0; 32]).is_err()); ++ let wrong = Segment { key: Some(vec![8; 32]), box_hash: None, ..segment }; ++ assert!(open(&wrong, &stored, &[0; 32]).is_err()); ++ } ++ ++ #[test] ++ fn a_wrapped_segment_key_is_unwrapped_with_the_package_key() { ++ let package_key = [3u8; 32]; ++ let segment_key = [9u8; 32]; ++ let wrap_iv = [5u8; 16]; ++ let (segment, stored) = sealed(b"wrapped", &segment_key); ++ let wrapped = Segment { key: None, wrapped: Some(encrypt(&package_key, &wrap_iv, &segment_key)), wrap_iv, ..segment }; ++ assert_eq!(open(&wrapped, &stored, &package_key).unwrap(), b"wrapped"); ++ } ++ ++ #[test] ++ fn adjacent_segments_in_one_box_share_a_request() { ++ let (segment, _) = sealed(b"x", &[1; 32]); ++ let at = |box_index: usize, offset: u64| Segment { box_index, offset, span: 16, ..segment.clone() }; ++ let parts = [at(0, 0), at(0, 16), at(0, 48), at(1, 64)]; ++ let shape: Vec<(usize, u64, u64, usize)> = ++ requests(&parts).iter().map(|r| (r.box_index, r.offset, r.length, r.segments.len())).collect(); ++ assert_eq!(shape, [(0, 0, 32, 2), (0, 48, 16, 1), (1, 64, 16, 1)]); ++ } ++ ++ #[test] ++ fn the_rolling_wrap_iv_advances_per_segment_and_an_explicit_one_wins() { ++ let item = |explicit: bool| { ++ let mut map = vec![ ++ (Value::Integer(1.into()), Value::Bytes(vec![0; 48])), ++ (Value::Integer(2.into()), Value::Integer(4.into())), ++ ]; ++ if explicit { ++ map.push((Value::Integer(7.into()), Value::Bytes(vec![0xee; 16]))); ++ } ++ Value::Map(map) ++ }; ++ let mut rolling = [0u8; 16]; ++ rolling[15] = 0xff; ++ let found = segments(&[item(false), item(true), item(false)], &mut rolling).unwrap(); ++ assert_eq!(found[0].wrap_iv[14..], [0x00, 0xff]); ++ assert_eq!(found[1].wrap_iv, [0xee; 16]); ++ assert_eq!(found[2].wrap_iv[14..], [0x01, 0x01]); ++ } ++ ++ fn empty(path: &str) -> Entry { ++ Entry { path: PathBuf::from(path), size: 0, hash: Some(Sha384::digest(b"").to_vec()), segments: vec![] } ++ } ++ ++ fn plan_of(entries: Vec) -> Plan { ++ Plan { entries, boxes: vec![], package_key: [0; 32] } ++ } ++ ++ async fn run(plan: &Plan, out: &Path) -> Result<(), String> { ++ install(&reqwest::Client::new(), plan, out, &|_| {}).await ++ } ++ ++ #[test] ++ fn only_files_verified_by_an_install_count_as_complete() { ++ let root = tempfile::tempdir().unwrap(); ++ let (segment, _) = sealed(b"x", &[1; 32]); ++ let entry = |path: &str, size: u64| Entry { path: PathBuf::from(path), size, hash: None, segments: vec![segment.clone()] }; ++ let plan = plan_of(vec![entry("done.bin", 4), entry("partial.bin", 10), entry("missing.bin", 7)]); ++ std::fs::write(root.path().join("done.bin"), b"abcd").unwrap(); ++ std::fs::write(root.path().join("partial.bin"), b"abc").unwrap(); ++ assert_eq!(plan.total(), 21); ++ assert_eq!(plan.remaining(root.path()), 21); ++ std::fs::create_dir(root.path().join(STATE)).unwrap(); ++ let record = root.path().join(STATE).join(VERIFIED); ++ note(&record, Path::new("done.bin"), &identity(&plan.entries[0])).unwrap(); ++ assert_eq!(plan.remaining(root.path()), 17); ++ std::fs::write(root.path().join("done.bin"), b"abcde").unwrap(); ++ assert_eq!(plan.remaining(root.path()), 21); ++ } ++ ++ #[test] ++ fn an_interrupted_record_never_swallows_the_next_one() { ++ let root = tempfile::tempdir().unwrap(); ++ let (older, _) = sealed(b"old", &[1; 32]); ++ let (newer, _) = sealed(b"new", &[1; 32]); ++ let entry = |segment: &Segment| Entry { path: PathBuf::from("game.bin"), size: 3, hash: None, segments: vec![segment.clone()] }; ++ let (old, new) = (plan_of(vec![entry(&older)]), plan_of(vec![entry(&newer)])); ++ let (kept, _) = sealed(b"keep", &[1; 32]); ++ let other = plan_of(vec![Entry { path: PathBuf::from("other.bin"), size: 4, hash: None, segments: vec![kept] }]); ++ std::fs::write(root.path().join("game.bin"), b"new").unwrap(); ++ std::fs::write(root.path().join("other.bin"), b"keep").unwrap(); ++ std::fs::create_dir(root.path().join(STATE)).unwrap(); ++ let record = root.path().join(STATE).join(VERIFIED); ++ note(&record, Path::new("other.bin"), &identity(&other.entries[0])).unwrap(); ++ note(&record, Path::new("game.bin"), &identity(&old.entries[0])).unwrap(); ++ let mut torn = std::fs::read(&record).unwrap(); ++ torn.extend_from_slice(&key(Path::new("game.bin")).as_bytes()[..20]); ++ std::fs::write(&record, &torn).unwrap(); ++ assert_eq!(old.remaining(root.path()), 0); ++ note(&record, Path::new("game.bin"), "-").unwrap(); ++ assert_eq!(old.remaining(root.path()), 3); ++ assert_eq!(new.remaining(root.path()), 3); ++ assert_eq!(other.remaining(root.path()), 0); ++ assert!(std::fs::read(&record).unwrap().ends_with(b"\n")); ++ } ++ ++ #[test] ++ fn only_the_latest_record_for_a_path_describes_its_file() { ++ let root = tempfile::tempdir().unwrap(); ++ let (older, _) = sealed(b"old", &[1; 32]); ++ let (newer, _) = sealed(b"new", &[1; 32]); ++ let entry = |segment: &Segment| Entry { path: PathBuf::from("game.bin"), size: 3, hash: None, segments: vec![segment.clone()] }; ++ let (old, new) = (plan_of(vec![entry(&older)]), plan_of(vec![entry(&newer)])); ++ std::fs::write(root.path().join("game.bin"), b"new").unwrap(); ++ std::fs::create_dir(root.path().join(STATE)).unwrap(); ++ let record = root.path().join(STATE).join(VERIFIED); ++ note(&record, Path::new("game.bin"), &identity(&old.entries[0])).unwrap(); ++ note(&record, Path::new("game.bin"), "-").unwrap(); ++ assert_eq!(old.remaining(root.path()), 3); ++ note(&record, Path::new("game.bin"), &identity(&new.entries[0])).unwrap(); ++ assert_eq!(new.remaining(root.path()), 0); ++ assert_eq!(old.remaining(root.path()), 3); ++ } ++ ++ #[tokio::test] ++ async fn a_planned_name_never_serves_as_another_files_partial() { ++ let root = tempfile::tempdir().unwrap(); ++ let plan = plan_of(vec![empty("data.bin.part"), empty("data.bin")]); ++ run(&plan, root.path()).await.unwrap(); ++ assert!(root.path().join("data.bin.part").is_file()); ++ assert!(root.path().join("data.bin").is_file()); ++ assert_eq!(plan.remaining(root.path()), 0); ++ assert!(!root.path().join(STATE).join(PARTIAL).exists()); ++ } ++ ++ #[cfg(unix)] ++ #[tokio::test] ++ async fn a_linked_folder_inside_the_install_is_refused_and_a_linked_root_is_followed() { ++ let root = tempfile::tempdir().unwrap(); ++ let outside = tempfile::tempdir().unwrap(); ++ std::os::unix::fs::symlink(outside.path(), root.path().join("Data")).unwrap(); ++ assert!(run(&plan_of(vec![empty("Data/game.bin")]), root.path()).await.is_err()); ++ assert_eq!(std::fs::read_dir(outside.path()).unwrap().count(), 0); ++ std::fs::create_dir_all(root.path().join(STATE).join(PARTIAL)).unwrap(); ++ std::fs::write(outside.path().join("victim"), b"keep").unwrap(); ++ std::os::unix::fs::symlink(outside.path().join("victim"), root.path().join(STATE).join(PARTIAL).join("0")).unwrap(); ++ run(&plan_of(vec![empty("game.bin")]), root.path()).await.unwrap(); ++ assert_eq!(std::fs::read(outside.path().join("victim")).unwrap(), b"keep"); ++ let real = tempfile::tempdir().unwrap(); ++ let link = root.path().join("linked-root"); ++ std::os::unix::fs::symlink(real.path(), &link).unwrap(); ++ run(&plan_of(vec![empty("Bin/game.bin")]), &link).await.unwrap(); ++ assert!(real.path().join("Bin/game.bin").is_file()); ++ } ++ ++ #[test] ++ fn reclaiming_clears_only_unfinished_downloads() { ++ let root = tempfile::tempdir().unwrap(); ++ std::fs::create_dir_all(root.path().join(STATE).join(PARTIAL)).unwrap(); ++ std::fs::write(root.path().join(STATE).join(PARTIAL).join("0"), vec![0; 4096]).unwrap(); ++ std::fs::write(root.path().join(STATE).join(VERIFIED), b"x y\n").unwrap(); ++ std::fs::write(root.path().join("game.bin"), b"done").unwrap(); ++ reclaim(root.path()).unwrap(); ++ assert!(!root.path().join(STATE).join(PARTIAL).exists()); ++ assert!(root.path().join(STATE).join(VERIFIED).is_file()); ++ assert!(root.path().join("game.bin").is_file()); ++ reclaim(root.path()).unwrap(); ++ } ++ ++ #[cfg(unix)] ++ #[test] ++ fn reclaiming_never_follows_a_linked_state_folder() { ++ let root = tempfile::tempdir().unwrap(); ++ let outside = tempfile::tempdir().unwrap(); ++ std::fs::create_dir(outside.path().join(PARTIAL)).unwrap(); ++ std::fs::write(outside.path().join(PARTIAL).join("keep"), b"keep").unwrap(); ++ std::os::unix::fs::symlink(outside.path(), root.path().join(STATE)).unwrap(); ++ assert!(reclaim(root.path()).is_err()); ++ assert!(outside.path().join(PARTIAL).join("keep").is_file()); ++ let linked_root = tempfile::tempdir().unwrap(); ++ let real = tempfile::tempdir().unwrap(); ++ std::fs::create_dir_all(real.path().join(STATE).join(PARTIAL)).unwrap(); ++ let link = linked_root.path().join("game"); ++ std::os::unix::fs::symlink(real.path(), &link).unwrap(); ++ reclaim(&link).unwrap(); ++ assert!(!real.path().join(STATE).join(PARTIAL).exists()); ++ } ++ ++ #[test] ++ fn package_paths_stay_inside_the_install_folder() { ++ assert_eq!(relative("EmuMenu\\EmuMenu.exe").unwrap(), PathBuf::from("EmuMenu/EmuMenu.exe")); ++ for bad in ["", "..\\x", "/abs", "a\\..\\..\\b", "C:\\x", ".DroidDeck-Install\\verified"] { ++ assert!(relative(bad).is_err(), "{bad}"); ++ } ++ } ++ ++ #[test] ++ fn the_key_derivation_matches_sp800_108_counter_mode() { ++ let derived = derive(&[0x42; 32], b"ctx"); ++ let mut message = 1u32.to_be_bytes().to_vec(); ++ message.extend_from_slice(KDF_LABEL); ++ message.push(0); ++ message.extend_from_slice(b"ctx"); ++ message.extend_from_slice(&256u32.to_be_bytes()); ++ let mut mac = as hmac::KeyInit>::new_from_slice(&[0x42; 32]).unwrap(); ++ mac.update(&message); ++ assert_eq!(derived.as_slice(), mac.finalize().into_bytes().as_slice()); ++ } ++} +diff --git a/crates/xodus-cli/src/commands/store_delivery.rs b/crates/xodus-cli/src/commands/store_delivery.rs +index 7fec6e5..d34b402 100644 +--- a/crates/xodus-cli/src/commands/store_delivery.rs ++++ b/crates/xodus-cli/src/commands/store_delivery.rs +@@ -363,16 +363,6 @@ async fn download_url( + Err(format!("No download location was issued for {}", revision.name)) + } + +-/// Resolves the legacy packages of a Store product through Windows Update. +-pub async fn resolve( +- client: &reqwest::Client, +- product: &str, +- market: &str, +-) -> Result { +- let category = category(client, product, market).await?; +- resolve_category(client, &category).await +-} +- + /// Every build of a Store product Windows Update lists, newest first. Each build + /// has its own content id, and Microsoft can refuse keys for one but not another. + pub struct Builds { +@@ -438,16 +428,6 @@ fn builds_newest_first(revisions: Vec) -> Vec> { + groups.into_iter().filter(|group| !group.is_empty()).collect() + } + +-/// The packages a Windows Update category lists, in the containers a title is +-/// packed in. +-pub async fn resolve_category(client: &reqwest::Client, category: &str) -> Result { +- resolve_wanted(client, category, true, |name| { +- let lower = name.to_ascii_lowercase(); +- lower.ends_with(".eappx") || lower.ends_with(".eappxbundle") +- }) +- .await +-} +- + /// The plain `.appx` packages a category lists, which is how a framework ships. + pub async fn resolve_frameworks(client: &reqwest::Client, category: &str) -> Result { + resolve_wanted(client, category, false, |name| name.to_ascii_lowercase().ends_with(".appx")).await +diff --git a/crates/xodus-cli/src/commands/streaming.rs b/crates/xodus-cli/src/commands/streaming.rs +index 8e9d0e0..426de96 100644 +--- a/crates/xodus-cli/src/commands/streaming.rs ++++ b/crates/xodus-cli/src/commands/streaming.rs +@@ -361,7 +361,11 @@ where + return ExitCode::FAILURE; + } + if plain { +- return plain_package(remote_file, l, out).await; ++ let code = plain_package(remote_file, l, out).await; ++ if code != ExitCode::SUCCESS || !crate::commands::msixvc2::is_package(out) { ++ return code; ++ } ++ return boxed_package(client, tokens, out, market, tx).await; + } + let remote_xvd = match XvdFile::parse(&mut remote_file).await { + Ok(xvd) => xvd, +@@ -853,6 +857,82 @@ async fn plain_package(mut remote: R, length: u64, out: &P + } + } + ++async fn boxed_package( ++ client: &reqwest::Client, ++ tokens: &TokenManager, ++ out: &Path, ++ market: Option, ++ tx: &Sender, ++) -> ExitCode { ++ let fail = |message: &str| { ++ eprintln!("NEXUS_TRANSFER_DIAGNOSTIC_V1 boxed-package-failed 0"); ++ eprintln!("{message}"); ++ ExitCode::FAILURE ++ }; ++ let content_id = match crate::commands::msixvc2::content_id(out) { ++ Ok(id) => id, ++ Err(error) => return fail(&error), ++ }; ++ let (device_key, license) = match get_license(client, tokens, content_id, market.unwrap_or("neutral".to_string()), None, false).await { ++ Ok(found) => found, ++ Err(error) => { ++ eprintln!("{error}"); ++ return ExitCode::FAILURE; ++ } ++ }; ++ let mut keys = HashMap::new(); ++ for (id, packed) in license.content_keys { ++ let Ok(key) = packed.unpack(&device_key) else { ++ return fail("The content key could not be authenticated. Retry the installation or sign in again."); ++ }; ++ if let Ok(key) = <[u8; 32]>::try_from(&key[..]) { ++ keys.insert(id.to_bytes_le(), key); ++ } ++ } ++ tx.send(ProgressEvent::UpdateStatus { name: "Preparing".to_owned() }).await.ok(); ++ let plan = match crate::commands::msixvc2::plan(client, out, &keys).await { ++ Ok(plan) => plan, ++ Err(error) => return fail(&error), ++ }; ++ if let Err(error) = crate::commands::msixvc2::reclaim(out) { ++ return fail(&error); ++ } ++ let total = plan.total(); ++ let needed = plan.remaining(out); ++ if let Ok(free) = available_space(out) ++ && free < needed ++ { ++ eprintln!("NEXUS_LEGACY_INSTALL_DIAGNOSTIC_V1 insufficient-space"); ++ eprintln!( ++ "NEXUS_LEGACY_INSTALL_DETAIL_V1 an install this size needs about {} GB free, and {} GB is available", ++ needed.div_ceil(1_000_000_000), ++ free / 1_000_000_000 ++ ); ++ return ExitCode::FAILURE; ++ } ++ tx.send(ProgressEvent::UpdateRemaining { name: "Downloading".to_owned(), total }).await.ok(); ++ tx.send(ProgressEvent::Started { id: 0, name: "Game files".to_owned(), total }).await.ok(); ++ let pending = std::sync::atomic::AtomicU64::new(0); ++ let report = |written: u64| { ++ let delta = pending.fetch_add(written, std::sync::atomic::Ordering::Relaxed) + written; ++ if tx.try_send(ProgressEvent::Advanced { id: 0, delta }).is_ok() { ++ pending.fetch_sub(delta, std::sync::atomic::Ordering::Relaxed); ++ } ++ }; ++ let installed = crate::commands::msixvc2::install(client, &plan, out, &report).await; ++ let rest = pending.swap(0, std::sync::atomic::Ordering::Relaxed); ++ if rest > 0 { ++ tx.send(ProgressEvent::Advanced { id: 0, delta: rest }).await.ok(); ++ } ++ match installed { ++ Ok(()) => { ++ tx.send(ProgressEvent::Finished { id: 0 }).await.ok(); ++ ExitCode::SUCCESS ++ } ++ Err(error) => fail(&error), ++ } ++} ++ + #[cfg(test)] + mod plain_tests { + fn stored_zip(name: &str, data: &[u8]) -> Vec { diff --git a/tools/xbox/prepare.py b/tools/xbox/prepare.py index 3066d9edda..5ff45b9c64 100755 --- a/tools/xbox/prepare.py +++ b/tools/xbox/prepare.py @@ -10,7 +10,9 @@ cache = Path(sys.argv[1]).resolve() lock = json.loads((recipe / 'backend.lock.json').read_text()) local_patches = ['droiddeck-credentials.patch', 'droiddeck-launch-view.patch', 'droiddeck-library-subscriptions.patch', 'droiddeck-credential-fallback.patch', 'droiddeck-credential-diagnostics.patch', 'droiddeck-cloud-token.patch', - 'droiddeck-licensing-device-ticket.patch', 'droiddeck-dlc-mount.patch'] + 'droiddeck-licensing-device-ticket.patch', 'droiddeck-dlc-mount.patch', + 'droiddeck-legacy-packages.patch', 'droiddeck-legacy-install.patch', 'droiddeck-legacy-run.patch', + 'droiddeck-msixvc2.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():