Compare commits

..
482 changed files with 3163 additions and 36367 deletions

No files matched your search

-2
View File
@@ -10,5 +10,3 @@ tools/mangoapp/mangoapp text eol=lf
app/src/main/assets/desktop-removal/*.json text eol=lf app/src/main/assets/desktop-removal/*.json text eol=lf
app/src/main/assets/desktop-removal/*.txt text eol=lf app/src/main/assets/desktop-removal/*.txt text eol=lf
*.pdf binary *.pdf binary
# Patches are applied by the Linux build roots and pinned by hash.
tools/qualcomm/**/*.patch text eol=lf
+8 -1
View File
@@ -450,7 +450,7 @@ jobs:
~/.cargo/git/db ~/.cargo/git/db
~/.cargo/bin/cargo-ndk ~/.cargo/bin/cargo-ndk
app/src/main/rust/stores/target app/src/main/rust/stores/target
key: stores-v2-${{ runner.os }}-${{ runner.arch }}-${{ env.NDK_VERSION }}-${{ steps.rust.outputs.rustc }}-${{ hashFiles('app/src/main/rust/stores/Cargo.lock') }}-${{ hashFiles('app/src/main/rust/stores/src/**', 'app/src/main/rust/stores/Cargo.toml', 'app/src/main/rust/stores/build.rs', 'app/src/main/rust/stores/.cargo/**', 'app/build.gradle') }} key: stores-v2-${{ runner.os }}-${{ runner.arch }}-${{ env.NDK_VERSION }}-${{ steps.rust.outputs.rustc }}-${{ hashFiles('app/src/main/rust/stores/Cargo.lock') }}-${{ hashFiles('app/src/main/rust/stores/amazon/**', 'tools/stores/**', 'app/src/main/rust/stores/src/**', 'app/src/main/rust/stores/Cargo.toml', 'app/src/main/rust/stores/build.rs', 'app/src/main/rust/stores/.cargo/**', 'app/build.gradle') }}
restore-keys: | restore-keys: |
stores-v2-${{ runner.os }}-${{ runner.arch }}-${{ env.NDK_VERSION }}-${{ steps.rust.outputs.rustc }}-${{ hashFiles('app/src/main/rust/stores/Cargo.lock') }}- stores-v2-${{ runner.os }}-${{ runner.arch }}-${{ env.NDK_VERSION }}-${{ steps.rust.outputs.rustc }}-${{ hashFiles('app/src/main/rust/stores/Cargo.lock') }}-
stores-v2-${{ runner.os }}-${{ runner.arch }}-${{ env.NDK_VERSION }}-${{ steps.rust.outputs.rustc }}- stores-v2-${{ runner.os }}-${{ runner.arch }}-${{ env.NDK_VERSION }}-${{ steps.rust.outputs.rustc }}-
@@ -523,6 +523,13 @@ jobs:
cd app/src/main/rust/stores cd app/src/main/rust/stores
cargo test --locked 2>&1 | tail -60 cargo test --locked 2>&1 | tail -60
- name: Amazon engine host tests
timeout-minutes: 10
run: |
set -euo pipefail
export CARGO_TARGET_DIR="$PWD/app/src/main/rust/stores/target"
cargo test --manifest-path app/src/main/rust/stores/amazon/Cargo.toml --locked
- name: Upload the regenerated Cargo.lock - name: Upload the regenerated Cargo.lock
if: failure() if: failure()
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
+1 -1
View File
@@ -61,7 +61,7 @@ jobs:
jq -r --arg n "$2" '.assets // [] | .[] | select(.name == $n) | .digest // empty' jq -r --arg n "$2" '.assets // [] | .[] | select(.name == $n) | .digest // empty'
} }
commit=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$BUILD_RUN" --jq .head_sha 2>/dev/null || echo "$GITHUB_SHA") commit=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$BUILD_RUN" --jq .head_sha 2>/dev/null || echo "$GITHUB_SHA")
for name in proot directaudio tracking xbox comet; do for name in proot directaudio tracking xbox comet amazon; do
file="packs/$name.tar.zst" file="packs/$name.tar.zst"
[ -f "$file" ] || { echo "::error::$name.tar.zst is missing from Build APK run $BUILD_RUN"; exit 1; } [ -f "$file" ] || { echo "::error::$name.tar.zst is missing from Build APK run $BUILD_RUN"; exit 1; }
sha=$(sha256sum "$file" | cut -d' ' -f1) sha=$(sha256sum "$file" | cut -d' ' -f1)
+1
View File
@@ -15,6 +15,7 @@ app/src/main/jniLibs/arm64-v8a/.proot-outputs
app/src/main/jniLibs/arm64-v8a/libproot-loader.so app/src/main/jniLibs/arm64-v8a/libproot-loader.so
app/src/main/jniLibs/arm64-v8a/libdirectaudiorelay.so app/src/main/jniLibs/arm64-v8a/libdirectaudiorelay.so
app/src/main/rust/stores/target/ app/src/main/rust/stores/target/
app/src/main/rust/amazon/target/
app/src/main/assets/droiddeck-esync/ app/src/main/assets/droiddeck-esync/
.kotlin/ .kotlin/
-1
View File
@@ -1,4 +1,3 @@
# Rules # Rules
- Comments should be rare, factual, and explain only non-obvious external constraints or business invariants. - Comments should be rare, factual, and explain only non-obvious external constraints or business invariants.
- Always compile APKs with the prepared Linux runtime assets and valid add-on pack checksums so a fresh installation on another phone can install the runtime. Never use `reuseInstalledRuntime` or rely on runtime files already installed on a connected device. Run APK runtime-input verification before sharing a build.
+1 -19
View File
@@ -9,20 +9,6 @@ DroidDeck brings the SteamOS experience to Android: Valve's Steam client in Big
<p align="center"><a href="https://discord.gg/JRGAvawjsm"><img src="https://img.shields.io/badge/Discord-Join%20the%20community-5865F2?logo=discord&logoColor=white" alt="Join the DroidDeck Discord"></a></p> <p align="center"><a href="https://discord.gg/JRGAvawjsm"><img src="https://img.shields.io/badge/Discord-Join%20the%20community-5865F2?logo=discord&logoColor=white" alt="Join the DroidDeck Discord"></a></p>
<p align="center">
<a href="https://www.star-history.com/droid-deck/droiddeck"><img src="https://api.star-history.com/badge?repo=Droid-Deck/DroidDeck&type=rank&theme=dark" alt="Star History Rank" /></a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/267852?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-267852" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/daily?language=C" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"/></a>
<a href="https://trendshift.io/repositories/267852?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-267852" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/daily?language=Kotlin" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"/></a>
</p>
<p align="center">
<a href="https://trendshift.io/repositories/267852?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-267852" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/weekly?language=C" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"/></a>
<a href="https://trendshift.io/repositories/267852?utm_source=trendshift-badge&amp;utm_medium=badge&amp;utm_campaign=badge-trendshift-267852" target="_blank" rel="noopener noreferrer"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/weekly?language=Kotlin" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"/></a>
</p>
<p align="center"><img src="docs/releases/media/0.2.0/launch-into-steam.gif" width="80%" alt="Tapping DroidDeck on the Android home screen and landing in Steam Big Picture"></p> <p align="center"><img src="docs/releases/media/0.2.0/launch-into-steam.gif" width="80%" alt="Tapping DroidDeck on the Android home screen and landing in Steam Big Picture"></p>
> Note: DroidDeck does not have a stand-alone website. Do not click on any download links from websites claiming to be the DroidDeck team. > Note: DroidDeck does not have a stand-alone website. Do not click on any download links from websites claiming to be the DroidDeck team.
@@ -61,7 +47,7 @@ Compatibility and performance vary by device; hardware validation is limited. De
## Credits and licence ## Credits and licence
GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. Battle.net support is [@kayakyakr](https://github.com/kayakyakr)'s: it runs Blizzard's own Battle.net client, downloaded from Blizzard and not included, in Proton, and shows the key art from each game's [Battle.net Shop](https://shop.battle.net) page; without the Steam client its games see DroidDeck's pad as an Xbox 360 controller through `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`. The registry entries a GOG game's install script (`goggame-<id>.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc/<pid>/mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and is already on through Proton. The proot fast path picks the guest name of a host file bound under several names in the order [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later) sorts its bindings, so links and `/proc/self/fd` read back as they do through proot. The session's [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) opens its sockets with the per-socket access settings documented in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions through its `access.rules`. Wine write watches use the userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later): libblsession gives it the arm64 syscall number and answers its `PAGEMAP_SCAN` from `/proc/self/pagemap` where Android refuses the ioctl. Wine on arm64 sets a thread's full context by raising `SIGUSR2` from `syscall_dispatcher_return_slowpath` in [Wine](https://gitlab.winehq.org/wine/wine)'s `dlls/ntdll/unix/signal_arm64.c` (LGPL-2.1-or-later); libblsession runs that handler in place on a frame laid out as the [Linux](https://github.com/torvalds/linux) kernel's `arch/arm64/kernel/signal.c` builds it and returns through `rt_sigreturn`, so proot does not stop the thread for it. Wine's process list reads each process's memory counters from `/proc/<pid>/status` in `fill_vm_counters` ([Wine](https://gitlab.winehq.org/wine/wine) `dlls/ntdll/unix/process.c`, LGPL-2.1-or-later), so libblsession gives those reads the kernel's file instead of a copy with `TracerPid` cleared. droiddeck-ntsync is checked against the object, wait and error semantics documented for the [Linux](https://github.com/torvalds/linux) ntsync driverLine truncated GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. The registry entries a GOG game's install script (`goggame-<id>.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc/<pid>/mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and is already on through Proton. The proot fast path picks the guest name of a host file bound under several names in the order [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later) sorts its bindings, so links and `/proc/self/fd` read back as they do through proot. The session's [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) opens its sockets with the per-socket access settings documented in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions through its `access.rules`. Wine write watches use the userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later): libblsession gives it the arm64 syscall number and answers its `PAGEMAP_SCAN` from `/proc/self/pagemap` where Android refuses the ioctl. Wine on arm64 sets a thread's full context by raising `SIGUSR2` from `syscall_dispatcher_return_slowpath` in [Wine](https://gitlab.winehq.org/wine/wine)'s `dlls/ntdll/unix/signal_arm64.c` (LGPL-2.1-or-later); libblsession runs that handler in place on a frame laid out as the [Linux](https://github.com/torvalds/linux) kernel's `arch/arm64/kernel/signal.c` builds it and returns through `rt_sigreturn`, so proot does not stop the thread for it. Wine's process list reads each process's memory counters from `/proc/<pid>/status` in `fill_vm_counters` ([Wine](https://gitlab.winehq.org/wine/wine) `dlls/ntdll/unix/process.c`, LGPL-2.1-or-later), so libblsession gives those reads the kernel's file instead of a copy with `TracerPid` cleared. droiddeck-ntsync is checked against the object, wait and error semantics documented for the [Linux](https://github.com/torvalds/linux) ntsync driver in `Documentation/userspace-api/ntsync.rst` (GPL-2.0). See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve.
XR glasses support builds on WinNative's VITURE glasses work. VITURE protocol details were checked against [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) by [@wheaney](https://github.com/wheaney), including the VITURE protocol header it ships, [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) by [@badicsalex](https://github.com/badicsalex) and the [go-macos/iokit VITURE package](https://pkg.go.dev/github.com/go-macos/iokit/viture); the optional VITURE SDK belongs to VITURE and is not included. RayNeo support adapts [@informalTechCode](https://github.com/informalTechCode)'s [RayNeo-Air-Series-3DoF-Scaffold](https://github.com/informalTechCode/RayNeo-Air-Series-3DoF-Scaffold) (Apache-2.0) and references [@verncat](https://github.com/verncat)'s [RayNeo-Air-3S-Pro-OpenVR](https://github.com/verncat/RayNeo-Air-3S-Pro-OpenVR) (MIT) and [Monado](https://gitlab.freedesktop.org/monado/monado) (BSL-1.0); see [docs/third-party/rayneo](docs/third-party/rayneo/README.md). XREAL 1S support references [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) and [xrealOneDeviceKit](https://github.com/wheaney/xrealOneDeviceKit) by @wheaney, [xreal_one_driver](https://github.com/rohitsangwan01/xreal_one_driver) by [@rohitsangwan01](https://github.com/rohitsangwan01) (MIT) and [xr-tools](https://github.com/0xcaff/xr-tools) by [@0xcaff](https://github.com/0xcaff). Rokid support follows the Rokid protocol notes in [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) and @badicsalex's [Void Computing write-ups](https://voidcomputing.hu/blog/worse-better-prettier/), and [Monado](https://gitlab.freedesktop.org/monado/monado)'s Rokid driver. The REDMAGIC glasses-display findings draw on [@mekhontsev](https://github.com/mekhontsev)'s [MagicDesk investigation](https://github.com/mekhontsev/magicdesk/blob/main/docs/xr-resolution-fix.md) and [@Coding-BR](https://github.com/Coding-BR)'s [decompiled Nubia kernel](https://github.com/Coding-BR/android_kernel_nubia_sm8850_qwjujube). VITURE, RayNeo, XREAL, Rokid and REDMAGIC are trademarks of their owners; this project is not affiliated with them. XR glasses support builds on WinNative's VITURE glasses work. VITURE protocol details were checked against [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) by [@wheaney](https://github.com/wheaney), including the VITURE protocol header it ships, [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) by [@badicsalex](https://github.com/badicsalex) and the [go-macos/iokit VITURE package](https://pkg.go.dev/github.com/go-macos/iokit/viture); the optional VITURE SDK belongs to VITURE and is not included. RayNeo support adapts [@informalTechCode](https://github.com/informalTechCode)'s [RayNeo-Air-Series-3DoF-Scaffold](https://github.com/informalTechCode/RayNeo-Air-Series-3DoF-Scaffold) (Apache-2.0) and references [@verncat](https://github.com/verncat)'s [RayNeo-Air-3S-Pro-OpenVR](https://github.com/verncat/RayNeo-Air-3S-Pro-OpenVR) (MIT) and [Monado](https://gitlab.freedesktop.org/monado/monado) (BSL-1.0); see [docs/third-party/rayneo](docs/third-party/rayneo/README.md). XREAL 1S support references [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) and [xrealOneDeviceKit](https://github.com/wheaney/xrealOneDeviceKit) by @wheaney, [xreal_one_driver](https://github.com/rohitsangwan01/xreal_one_driver) by [@rohitsangwan01](https://github.com/rohitsangwan01) (MIT) and [xr-tools](https://github.com/0xcaff/xr-tools) by [@0xcaff](https://github.com/0xcaff). Rokid support follows the Rokid protocol notes in [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) and @badicsalex's [Void Computing write-ups](https://voidcomputing.hu/blog/worse-better-prettier/), and [Monado](https://gitlab.freedesktop.org/monado/monado)'s Rokid driver. The REDMAGIC glasses-display findings draw on [@mekhontsev](https://github.com/mekhontsev)'s [MagicDesk investigation](https://github.com/mekhontsev/magicdesk/blob/main/docs/xr-resolution-fix.md) and [@Coding-BR](https://github.com/Coding-BR)'s [decompiled Nubia kernel](https://github.com/Coding-BR/android_kernel_nubia_sm8850_qwjujube). VITURE, RayNeo, XREAL, Rokid and REDMAGIC are trademarks of their owners; this project is not affiliated with them.
@@ -70,7 +56,3 @@ Joy-Con VR controllers port the arm model of Google's [Google VR SDK for Unity](
Camera hand tracking runs Google's [MediaPipe](https://github.com/google-ai-edge/mediapipe) Tasks Vision library with its Pose Landmarker (Lite) model, BlazePose GHUM 3D, and its Hand Landmarker model (all Apache-2.0), on frames from AndroidX [CameraX](https://developer.android.com/jetpack/androidx/releases/camera) (Apache-2.0); MediaPipe's usage reports are switched off. The design was checked against [@F8LEFT](https://github.com/F8LEFT)'s [JoyConVr](https://github.com/F8LEFT/JoyConVr) camera app (MIT), and the short Joy-Con movements follow the accelerometer mode of the [Google VR SDK for Unity](https://github.com/googlevr/gvr-unity-sdk)'s arm model, Eric Foxlin's zero-velocity updates and Frosio, Pedersini and Borghese's accelerometer autocalibration, and the camera and Joy-Con are joined by a Kalman filter (R. E. Kalman, 1960). Bare camera hands take their gestures after [ALVR](https://github.com/alvr-org/ALVR)'s `hand_gestures.rs` (MIT) and Meta Quest's menu pinch, with distances checked on photos from the [HaGRID](https://github.com/hukenovs/hagrid) gesture set (CC BY-SA 4.0, not included), fit the palm with Horn's quaternion method (1987) and smooth it with the 1€ filter (Casiez, Roussel and Vogel, 2012); the white glove model follows Valve's OpenVR render model reference and Index controller poses, is meshed with surface nets (Gibson, 1998; Mikola Lysenko) and blends and shades it with Inigo Quilez's smooth minimum and distance-field ambient occlusion, porting his polygon distance (MIT); see [docs/third-party/handtracking](docs/third-party/handtracking/README.md). Camera hand tracking runs Google's [MediaPipe](https://github.com/google-ai-edge/mediapipe) Tasks Vision library with its Pose Landmarker (Lite) model, BlazePose GHUM 3D, and its Hand Landmarker model (all Apache-2.0), on frames from AndroidX [CameraX](https://developer.android.com/jetpack/androidx/releases/camera) (Apache-2.0); MediaPipe's usage reports are switched off. The design was checked against [@F8LEFT](https://github.com/F8LEFT)'s [JoyConVr](https://github.com/F8LEFT/JoyConVr) camera app (MIT), and the short Joy-Con movements follow the accelerometer mode of the [Google VR SDK for Unity](https://github.com/googlevr/gvr-unity-sdk)'s arm model, Eric Foxlin's zero-velocity updates and Frosio, Pedersini and Borghese's accelerometer autocalibration, and the camera and Joy-Con are joined by a Kalman filter (R. E. Kalman, 1960). Bare camera hands take their gestures after [ALVR](https://github.com/alvr-org/ALVR)'s `hand_gestures.rs` (MIT) and Meta Quest's menu pinch, with distances checked on photos from the [HaGRID](https://github.com/hukenovs/hagrid) gesture set (CC BY-SA 4.0, not included), fit the palm with Horn's quaternion method (1987) and smooth it with the 1€ filter (Casiez, Roussel and Vogel, 2012); the white glove model follows Valve's OpenVR render model reference and Index controller poses, is meshed with surface nets (Gibson, 1998; Mikola Lysenko) and blends and shades it with Inigo Quilez's smooth minimum and distance-field ambient occlusion, porting his polygon distance (MIT); see [docs/third-party/handtracking](docs/third-party/handtracking/README.md).
The Store installs and runs apps with [Flatpak](https://github.com/flatpak/flatpak) (LGPL-2.1). Its sandbox goes through DroidDeck's own bubblewrap shim, which follows how Flatpak hands bwrap its environment. Chromium and Electron apps from Flathub start their browser processes through [zypak](https://github.com/refi64/zypak) by [@refi64](https://github.com/refi64) (BSD-3-Clause); its source was read to see that it always spawns them through Flatpak's spawn portal, which is why DroidDeck starts them directly without Chromium's sandbox instead. The Store installs and runs apps with [Flatpak](https://github.com/flatpak/flatpak) (LGPL-2.1). Its sandbox goes through DroidDeck's own bubblewrap shim, which follows how Flatpak hands bwrap its environment. Chromium and Electron apps from Flathub start their browser processes through [zypak](https://github.com/refi64/zypak) by [@refi64](https://github.com/refi64) (BSD-3-Clause); its source was read to see that it always spawns them through Flatpak's spawn portal, which is why DroidDeck starts them directly without Chromium's sandbox instead.
Steam's Browse buttons open a GTK 3 file chooser through PyGObject (LGPL-2.1-or-later). It runs under Steam's own `reaper` with Steam's app ID, which [gamescope](https://github.com/ValveSoftware/gamescope) (BSD-2-Clause) reads from the process tree (`GetAppIdFromReaper` in `src/Utils/Process.cpp`) to show it over Steam.
Black Ops III and Dark Souls Remastered start without [umu-protonfixes](https://github.com/Open-Wine-Components/umu-protonfixes) (BSD-2-Clause), whose fixes for them (`311210.py` sets ALSA audio, `570940.py` installs VC++ 2017) fail under ARM64 Proton.
+4 -66
View File
@@ -79,12 +79,6 @@ def sourceCommit = providers.environmentVariable('DROIDDECK_SOURCE_COMMIT').getO
?: providers.environmentVariable('GITHUB_SHA').getOrNull() ?: gitValue(['rev-parse', 'HEAD']) ?: '' ?: providers.environmentVariable('GITHUB_SHA').getOrNull() ?: gitValue(['rev-parse', 'HEAD']) ?: ''
def prNumber = (providers.environmentVariable('DROIDDECK_PR_NUMBER').getOrNull() ?: '0').with { it.isInteger() ? it : '0' } def prNumber = (providers.environmentVariable('DROIDDECK_PR_NUMBER').getOrNull() ?: '0').with { it.isInteger() ? it : '0' }
def ciBuild = providers.environmentVariable('GITHUB_ACTIONS').getOrNull() == 'true' def ciBuild = providers.environmentVariable('GITHUB_ACTIONS').getOrNull() == 'true'
if (project.hasProperty('reuseInstalledRuntime')) throw new GradleException('All APKs require prepared Linux runtime packages; runtime reuse is not allowed')
def qualcommRuntime = new groovy.json.JsonSlurper().parse(rootProject.file('tools/qualcomm/runtime.json'))
def qualcommSources = fileTree(rootProject.file('tools/qualcomm')) { include '*.py', '*.c', '*.json', '*.sh', '**/*.patch' }
def qualcommDigest = java.security.MessageDigest.getInstance('SHA-256')
qualcommSources.files.sort { it.name }.each { qualcommDigest.update(it.bytes) }
def qualcommRevision = qualcommDigest.digest().encodeHex().toString()
def releaseSigner = rootProject.file('keystore/release-signer.sha256').text.trim() def releaseSigner = rootProject.file('keystore/release-signer.sha256').text.trim()
def commitTime = (gitValue(['show', '-s', '--format=%ct', '--end-of-options', sourceCommit]) ?: '0').with { it.isLong() ? it : '0' } def commitTime = (gitValue(['show', '-s', '--format=%ct', '--end-of-options', sourceCommit]) ?: '0').with { it.isLong() ? it : '0' }
def desktopKde = rootProject.file('tools/desktop-kde/release.env').readLines() def desktopKde = rootProject.file('tools/desktop-kde/release.env').readLines()
@@ -93,7 +87,7 @@ def desktopKde = rootProject.file('tools/desktop-kde/release.env').readLines()
def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLines() def trackingPack = rootProject.file('tools/packs/tracking/release.env').readLines()
.findAll { it.contains('=') && !it.startsWith('#') } .findAll { it.contains('=') && !it.startsWith('#') }
.collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] } .collectEntries { def kv = it.split('=', 2); [(kv[0].trim()): kv[1].trim()] }
def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet'].collectEntries { name -> def addonPacks = ['proot', 'directaudio', 'tracking', 'xbox', 'comet', 'amazon'].collectEntries { name ->
def pack = file("build/packs/${name}.tar.zst") def pack = file("build/packs/${name}.tar.zst")
if (!pack.isFile()) { if (!pack.isFile()) {
if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs") if (ciBuild) throw new GradleException("Add-on pack ${pack} is missing: run tools/packs/build.sh app/build/packs")
@@ -134,9 +128,6 @@ android {
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\"" buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
buildConfigField "int", "PR_NUMBER", "${prNumber}" buildConfigField "int", "PR_NUMBER", "${prNumber}"
buildConfigField "boolean", "CI_BUILD", "${ciBuild}" buildConfigField "boolean", "CI_BUILD", "${ciBuild}"
buildConfigField "String", "QUALCOMM_BRIDGE_SHA256", "\"${qualcommRuntime.sha256}\""
buildConfigField "String", "QUALCOMM_GAMESCOPE_SHA256", "\"${qualcommRuntime.gamescope.member_sha256}\""
buildConfigField "String", "QUALCOMM_FIXES_REVISION", "\"${qualcommRevision}\""
buildConfigField "String", "RELEASE_SIGNER", "\"${releaseSigner}\"" buildConfigField "String", "RELEASE_SIGNER", "\"${releaseSigner}\""
buildConfigField "long", "COMMIT_TIME", "${commitTime}L * 1000L" buildConfigField "long", "COMMIT_TIME", "${commitTime}L * 1000L"
buildConfigField "String", "VARIANT_SUFFIXES", "\"${variantSuffixes}\"" buildConfigField "String", "VARIANT_SUFFIXES", "\"${variantSuffixes}\""
@@ -263,16 +254,6 @@ def stageSessionScripts = tasks.register('stageSessionScripts', Copy) {
from(rootProject.file('tools/linuxfs/overlay')) { from(rootProject.file('tools/linuxfs/overlay')) {
include 'usr/local/bin/droiddeck-*', 'usr/local/bin/steam-compatibility', 'usr/bin/**' include 'usr/local/bin/droiddeck-*', 'usr/local/bin/steam-compatibility', 'usr/bin/**'
} }
from(rootProject.file('tools/linuxfs/desktop')) {
include 'droiddeck-gpu', 'droiddeck-desktop', 'droiddeck-desktop-gpu', 'kwin_wayland_wrapper'
into 'usr/local/bin'
}
from(rootProject.file('tools/linuxfs/desktop/firefox-droiddeck.js')) {
into 'usr/lib/firefox/defaults/pref'
rename { 'droiddeck.js' }
}
from(rootProject.file('tools/linuxfs/desktop/droiddeck-clipboard.desktop')) { into 'etc/xdg/autostart' }
from(rootProject.file('tools/mangoapp/mangoapp')) { into 'usr/local/bin' }
into(layout.projectDirectory.dir('src/main/assets/linuxfs')) into(layout.projectDirectory.dir('src/main/assets/linuxfs'))
} }
tasks.named('preBuild').configure { dependsOn(stageSessionScripts) } tasks.named('preBuild').configure { dependsOn(stageSessionScripts) }
@@ -281,40 +262,10 @@ def runtimeAssetsDir = layout.buildDirectory.dir('runtimeAssets')
def stageRuntimeAssets = tasks.register('stageRuntimeAssets', Sync) { def stageRuntimeAssets = tasks.register('stageRuntimeAssets', Sync) {
dependsOn(stageSessionScripts) dependsOn(stageSessionScripts)
from(layout.projectDirectory.dir('src/main/assets')) { exclude 'pulseaudio.tzst' } from(layout.projectDirectory.dir('src/main/assets')) { exclude 'pulseaudio.tzst' }
from(rootProject.file('tools/linuxfs/innoextract'))
from(layout.buildDirectory.dir('prepared-assets')) from(layout.buildDirectory.dir('prepared-assets'))
into(runtimeAssetsDir) into(runtimeAssetsDir)
} }
android.sourceSets.main.assets.setSrcDirs([runtimeAssetsDir]) android.sourceSets.main.assets.setSrcDirs([runtimeAssetsDir])
def fetchQualcommBuilds = tasks.register('fetchQualcommBuilds', Exec) {
workingDir rootProject.projectDir
commandLine pythonExecutable, 'tools/qualcomm/fetch_runtime.py', '--builds-only',
'--cache', rootProject.file('build/qualcomm-cache').absolutePath
}
def stageQualcommRuntime = tasks.register('stageQualcommRuntime', Exec) {
dependsOn fetchQualcommBuilds
workingDir rootProject.projectDir
inputs.files(qualcommSources)
if (qualcommRuntime.gamescope.build) {
inputs.file(rootProject.file(qualcommRuntime.gamescope.build.binary))
inputs.file(rootProject.file(qualcommRuntime.gamescope.build.source))
}
if (qualcommRuntime.mesa) {
inputs.dir(rootProject.file(qualcommRuntime.mesa.directory))
}
if (qualcommRuntime.wsi?.build) {
inputs.dir(rootProject.file(qualcommRuntime.wsi.build.directory))
}
inputs.property('ndkVersion', android.ndkVersion)
outputs.dir(layout.buildDirectory.dir('qualcommAssets'))
commandLine pythonExecutable, 'tools/qualcomm/fetch_runtime.py',
'--output', layout.buildDirectory.dir('qualcommAssets/qualcomm').get().asFile.absolutePath,
'--cache', rootProject.file('build/qualcomm-cache').absolutePath,
'--ndk', android.ndkDirectory.absolutePath
}
android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('qualcommAssets'))
tasks.named('preBuild').configure { dependsOn(stageQualcommRuntime) }
tasks.matching { it.name.toLowerCase(Locale.ROOT).contains('lint') }.configureEach { dependsOn(stageQualcommRuntime) }
if (vitureSdkDir) android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('vitureAssets')) if (vitureSdkDir) android.sourceSets.main.assets.srcDir(layout.buildDirectory.dir('vitureAssets'))
if (uvcDir) { if (uvcDir) {
def stageUvcNotices = tasks.register('stageUvcNotices', Copy) { def stageUvcNotices = tasks.register('stageUvcNotices', Copy) {
@@ -332,19 +283,7 @@ def verifyRuntimeInputs = tasks.register('verifyRuntimeInputs', Exec) {
commandLine pythonExecutable, 'tools/release/runtime_inputs.py', 'verify' commandLine pythonExecutable, 'tools/release/runtime_inputs.py', 'verify'
} }
tasks.configureEach { task -> tasks.configureEach { task ->
if (task.name == 'packageRelease') { if (task.name in ['packageDebug', 'packageRelease']) task.dependsOn(verifyRuntimeInputs)
task.dependsOn(verifyRuntimeInputs)
}
if (task.name == 'packageDebug') task.dependsOn(verifyRuntimeInputs)
}
['Debug', 'Release'].each { variant ->
def verifyApk = tasks.register("verify${variant}PackagedRuntime", Exec) {
workingDir rootProject.projectDir
commandLine pythonExecutable, 'tools/release/runtime_inputs.py', 'apk',
layout.buildDirectory.file("outputs/apk/${variant.toLowerCase()}/app-${variant.toLowerCase()}.apk").get().asFile.absolutePath
}
tasks.matching { it.name == "assemble${variant}" }.configureEach { finalizedBy(verifyApk) }
} }
def rustCrateDir = layout.projectDirectory.dir('src/main/rust/stores') def rustCrateDir = layout.projectDirectory.dir('src/main/rust/stores')
@@ -357,6 +296,7 @@ def buildRustStores = tasks.register('buildRustStores', Exec) {
inputs.dir(rustCrateDir.dir('src')) inputs.dir(rustCrateDir.dir('src'))
inputs.files(rustCrateDir.file('Cargo.toml'), rustCrateDir.file('Cargo.lock')) inputs.files(rustCrateDir.file('Cargo.toml'), rustCrateDir.file('Cargo.lock'))
inputs.property('ndkVersion', android.ndkVersion) inputs.property('ndkVersion', android.ndkVersion)
inputs.property('storeFeatures', 'gog,epic')
if (!skipRust) inputs.property('rustToolchain', providers.exec { if (!skipRust) inputs.property('rustToolchain', providers.exec {
environment 'PATH', "${System.getProperty('user.home')}/.cargo/bin${File.pathSeparator}${System.getenv('PATH')}" environment 'PATH', "${System.getProperty('user.home')}/.cargo/bin${File.pathSeparator}${System.getenv('PATH')}"
commandLine 'rustup', 'run', 'stable', 'rustc', '-Vv' commandLine 'rustup', 'run', 'stable', 'rustc', '-Vv'
@@ -372,7 +312,7 @@ def buildRustStores = tasks.register('buildRustStores', Exec) {
}.standardOutput.asText.get().trim() }.standardOutput.asText.get().trim()
commandLine 'rustup', 'run', 'stable', 'cargo', 'ndk', '--target', 'arm64-v8a', '--platform', '26', commandLine 'rustup', 'run', 'stable', 'cargo', 'ndk', '--target', 'arm64-v8a', '--platform', '26',
'--output-dir', rustJniLibsDir.get().asFile.absolutePath, '--output-dir', rustJniLibsDir.get().asFile.absolutePath,
'build', '--release', '--locked' 'build', '--release', '--locked', '--no-default-features', '--features', 'gog,epic'
} }
if (!skipRust) android.sourceSets.main.jniLibs.srcDir(rustJniLibsDir) if (!skipRust) android.sourceSets.main.jniLibs.srcDir(rustJniLibsDir)
tasks.named('preBuild').configure { dependsOn(buildRustStores) } tasks.named('preBuild').configure { dependsOn(buildRustStores) }
@@ -398,8 +338,6 @@ dependencies {
implementation 'androidx.camera:camera-camera2:1.4.2' implementation 'androidx.camera:camera-camera2:1.4.2'
implementation 'androidx.camera:camera-lifecycle:1.4.2' implementation 'androidx.camera:camera-lifecycle:1.4.2'
implementation 'androidx.webkit:webkit:1.12.1' implementation 'androidx.webkit:webkit:1.12.1'
// Google's WebRTC (BSD) for the native Xbox Cloud Gaming player (XboxNativePlayerActivity).
implementation 'io.github.webrtc-sdk:android:125.6422.07'
implementation("com.google.mediapipe:tasks-vision:${trackingPack.MEDIAPIPE_VERSION}") { implementation("com.google.mediapipe:tasks-vision:${trackingPack.MEDIAPIPE_VERSION}") {
exclude group: 'com.google.auto.value', module: 'auto-value' exclude group: 'com.google.auto.value', module: 'auto-value'
} }
-31
View File
@@ -2,15 +2,6 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" <manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"> xmlns:tools="http://schemas.android.com/tools">
<queries>
<intent>
<action android:name="android.content.pm.action.CONFIRM_INSTALL" />
</intent>
<intent>
<action android:name="android.content.pm.action.CONFIRM_PERMISSIONS" />
</intent>
</queries>
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" /> <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
@@ -43,7 +34,6 @@
android:localeConfig="@xml/locales_config" android:localeConfig="@xml/locales_config"
android:networkSecurityConfig="@xml/network_security_config" android:networkSecurityConfig="@xml/network_security_config"
android:allowBackup="false" android:allowBackup="false"
android:allowAudioPlaybackCapture="true"
android:icon="@mipmap/ic_launcher" android:icon="@mipmap/ic_launcher"
android:label="@string/app_name" android:label="@string/app_name"
android:theme="@style/AppTheme" android:theme="@style/AppTheme"
@@ -161,27 +151,6 @@
android:process=":xboxlogin" android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density" android:process=":xboxlogin" android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
android:theme="@style/AppTheme" /> android:theme="@style/AppTheme" />
<activity android:name=".stores.xbox.XboxCloudPlayerActivity" android:exported="false"
android:screenOrientation="sensorLandscape" android:hardwareAccelerated="true"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|density|navigation|uiMode"
android:theme="@style/AppTheme" />
<service android:name=".stores.xbox.XboxCloudTokenService" android:exported="false" />
<activity android:name=".stores.xbox.XboxNativePlayerActivity" android:exported="false"
android:process=":xcloudnative" android:screenOrientation="sensorLandscape" android:hardwareAccelerated="true"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|density|navigation|uiMode"
android:theme="@style/AppTheme" />
<activity android:name=".stores.xbox.XboxCloudActivity" android:exported="false"
android:process=":xboxcloud" android:launchMode="singleTop" android:screenOrientation="sensorLandscape"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout|smallestScreenSize|density|navigation|uiMode"
android:theme="@style/AppTheme" />
<activity android:name=".stores.xbox.XboxCloudSettingsActivity" android:exported="false"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
android:theme="@style/AppTheme" />
<activity <activity
android:name=".stores.StoreLoginActivity" android:name=".stores.StoreLoginActivity"
android:exported="false" android:exported="false"
-18
View File
@@ -1,18 +0,0 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<style>
html, body { margin: 0; height: 100%; background: #000; overflow: hidden; }
#player { position: absolute; inset: 0; }
#status { position: absolute; left: 0; right: 0; bottom: 12%; text-align: center; color: #ddd;
font: 16px sans-serif; text-shadow: 0 0 4px #000; pointer-events: none; }
</style>
</head>
<body>
<div id="player"></div>
<div id="status"></div>
<script src="player.js"></script>
</body>
</html>
-187
View File
@@ -1,187 +0,0 @@
/* DroidDeck Xbox Cloud Gaming player. Includes Greenlight's player (c) UnknownSKL (Jim Kroon), MIT. */
(()=>{var _=class{_player;_dataChannel;constructor(e){this._player=e,this._dataChannel=this._player._peerConnection.createDataChannel(this.getChannelName(),this.getChannelConfig()),this._dataChannel.onopen=this.onOpen.bind(this),this._dataChannel.onmessage=this.onMessage.bind(this),this._dataChannel.onclosing=this.onClosing.bind(this),this._dataChannel.onclose=this.onClose.bind(this),this._dataChannel.onerror=this.onError.bind(this)}getChannelName(){return"channel"}getChannelConfig(){return{}}onOpen(e){console.log(this.getChannelName(),"Opening channel:",e)}onMessage(e){console.log(this.getChannelName(),"Message channel:",e)}onClosing(e){console.log(this.getChannelName(),"Closing channel:",e)}onClose(e){console.log(this.getChannelName(),"Closed channel:",e)}onError(e){console.log(this.getChannelName(),"Error channel:",e)}send(e){if(this._dataChannel.readyState!=="open"){console.log("["+this.getChannelName()+"] Tried to send data while channel is not open. readyState is:",this._dataChannel.readyState);return}return typeof e=="string"&&(e=new TextEncoder().encode(e)),this._dataChannel.send(e)}getPlayer(){return this._player}destroy(){}};var S=class extends _{_micPermissions="prompt";_micStream;constructor(e){super(e),navigator.permissions.query({name:"microphone"}).then(t=>{this._micPermissions=t.state,t.onchange=()=>{this._micPermissions=t.state}})}getChannelName(){return"chat"}getChannelConfig(){return{ordered:!0,protocol:"chatV1"}}destroy(){}};var v=class r{_player;_index;_physicalGamepadId=-1;_rumbleInterval;_isFocused=!0;_gamepadOverride={buttons:{}};_options={enable_keyboard:!1,enable_gamepad:!0,enable_vibration:!0,keyboard_mapping:{A:"Enter",B:"Backspace",X:"x",Y:"y",DPadUp:"ArrowUp",DPadDown:"ArrowDown",DPadLeft:"ArrowLeft",DPadRight:"ArrowRight",LeftShoulder:"[",RightShoulder:"]",LeftThumb:"l",RightThumb:"r",LeftTrigger:"-",RightTrigger:"=",Menu:"m",View:"v",Nexus:"n"},gamepad_mapping:{A:"0",B:"1",X:"2",Y:"3",DPadUp:"12",DPadDown:"13",DPadLeft:"14",DPadRight:"15",LeftShoulder:"4",RightShoulder:"5",LeftThumb:"10",RightThumb:"11",LeftTrigger:"6",RightTrigger:"7",Menu:"9",View:"8",Nexus:"16"},gamepad_axes_mapping:{LeftThumbXAxis:"0",LeftThumbYAxis:"1",RightThumbXAxis:"2",RightThumbYAxis:"3"},gamepad_deadzone:.08,gamepad_force_capture:!1};_listener={keyDown:this.onKeyDown.bind(this),keyUp:this.onKeyUp.bind(this),gamepadConnected:this.onGamepadConnected.bind(this),gamepadDisconnected:this.onGamepadDisconnected.bind(this),windowFocus:this.onWindowFocus.bind(this),windowBlur:this.onWindowBlur.bind(this)};constructor(e,t={}){this._index=e,this._options={...this._options,...t}}attach(e){this._player=e,this._player._channels.control.sendGamepadState(this._index,!0,this),this._options.enable_keyboard===!0&&(window.addEventListener("keydown",this._listener.keyDown),window.addEventListener("keyup",this._listener.keyUp)),this._options.enable_gamepad===!0&&(window.addEventListener("gamepadconnected",this._listener.gamepadConnected),window.addEventListener("gamepaddisconnected",this._listener.gamepadDisconnected)),this._options.enable_gamepad===!0&&this._options.gamepad_force_capture===!1&&(window.addEventListener("blur",this._listener.windowBlur),window.addEventListener("focus",this._listener.windowFocus)),this.detectActiveGamepad()}detach(){if(this._player===void 0){console.log("[Gamepad] Player is not attached. this._player is:",this._player);return}this._player._channels.control.sendGamepadState(this._index,!1),this._physicalGamepadId=-1,this._rumbleInterval!==void 0&&clearInterval(this._rumbleInterval),this._options.enable_keyboard===!0&&(window.removeEventListener("keydown",this._listener.keyDown),window.removeEventListener("keyup",this._listener.keyUp)),this._options.enable_gamepad===!0&&(window.removeEventListener("gamepadconnected",this._listener.gamepadConnected),window.removeEventListener("gamepaddisconnected",this._listener.gamepadDisconnected)),this._options.enable_gamepad===!0&&this._options.gamepad_force_capture===!1&&(window.removeEventListener("blur",this._listener.windowBlur),window.removeEventListener("focus",this._listener.windowFocus))}sendButtonState(e,t){if(this._player===void 0){console.log("[Gamepad] Player is not attached. this._player is:",this._player);return}if(!(e in this.getDefaultFamepadFrame())){console.log("[Gamepad] Invalid button:",e);return}let n=this.getDefaultFamepadFrame();n.GamepadIndex=this._index,this._gamepadOverride.buttons[e]=t}onKeyDown(e){if(this._isFocused!==!1)for(let t in this._options.keyboard_mapping)this._options.keyboard_mapping[t]===e.key&&(this._gamepadOverride.buttons[t]=1,e.preventDefault())}onKeyUp(e){if(this._isFocused!==!1)for(let t in this._options.keyboard_mapping)this._options.keyboard_mapping[t]===e.key&&(this._gamepadOverride.buttons[t]=0,e.preventDefault())}onWindowFocus(){this._isFocused=!0}onWindowBlur(){}getDefaultFamepadFrame(){return{GamepadIndex:0,Nexus:0,Menu:0,View:0,A:0,B:0,X:0,Y:0,DPadUp:0,DPadDown:0,DPadLeft:0,DPadRight:0,LeftShoulder:0,Line truncated
`+t.ContentText)?this.completeTransaction(e.id,{Result:0}):this.completeTransaction(e.id,{Result:1})}};var M=class extends _{_handshakeCompleted=!1;getChannelName(){return"message"}getChannelConfig(){return{protocol:"messageV1",ordered:!0}}onOpen(){console.log("[MessageChannel] Sending handshake...");let e=JSON.stringify({type:"Handshake",version:"messageV1",id:"be0bfc6d-1e83-4c8a-90ed-fa8601c5a179",cv:"0"});this.send(e)}onMessage(e){let t=JSON.parse(e.data);switch(t.type){case"HandshakeAck":console.log("[MessageChannel] Handshake completed"),this._handshakeCompleted=!0,this.getPlayer()._channels.control.sendAuthorization(),this.getPlayer()._channels.input.start(),this.sendConfig();break;case"TransactionStart":case"Message":new D(this,t);break;default:console.log("[MessageChannel] Unhandled message type:",t.type,t)}}sendConfig(){let e=[],t=[0,2,0],n=JSON.stringify(this.generateMessage("/streaming/systemUi/configuration",{version:t,systemUis:e}));this.send(n);let i=JSON.stringify(this.generateMessage("/streaming/properties/clientappinstallidchanged",{clientAppInstallId:"c97d7ee0-73b2-4239-bf1d-9d805a338429"}));this.send(i);let a=JSON.stringify(this.generateMessage("/streaming/characteristics/orientationchanged",{orientation:0}));this.send(a);let s=JSON.stringify(this.generateMessage("/streaming/characteristics/touchinputenabledchanged",{touchInputEnabled:!1}));this.send(s);let o=JSON.stringify(this.generateMessage("/streaming/characteristics/clientdevicecapabilities",{}));this.send(o);let d=JSON.stringify(this.generateMessage("/streaming/characteristics/dimensionschanged",{horizontal:1920,vertical:1080,preferredWidth:1920,preferredHeight:1080,safeAreaLeft:0,safeAreaTop:0,safeAreaRight:1920,safeAreaBottom:1080,supportsCustomResolution:!0}));this.send(d)}generateMessage(e,t){return{type:"Message",content:JSON.stringify(t),id:Q(),target:e,cv:""}}destroy(){}};var E=class{_address;_ipv4Address;_ipv4Port;constructor(e){this._address=e;let t=this._address.split(":"),n=t[6]+t[7],i=t[5],a=~parseInt(n.substring(0,2),16)&255,s=~parseInt(n.substring(2,4),16)&255,o=~parseInt(n.substring(4,6),16)&255,d=~parseInt(n.substring(6,8),16)&255,u=~parseInt(i.substring(0,4),16)&65535;this._ipv4Address=a+"."+s+"."+o+"."+d,this._ipv4Port=u}getIpv4Address(){return this._ipv4Address}getIpv4Port(){return this._ipv4Port}};var R=class{_peerConnection;_iceCandidates=[];constructor(e){this._peerConnection=e._peerConnection,this._peerConnection.addEventListener("icecandidate",t=>{t.candidate&&this._iceCandidates.push(t.candidate)})}getCandidates(){return this._iceCandidates}setRemoteCandidates(e){e.length===0&&console.warn("Error: No candidates received!");for(let t in e){if(e[t].candidate==="a=end-of-candidates")continue;let n=e[t].candidate.split(" ");if(n.length>4&&n[4].substr(0,4)==="2001"){let i=new E(n[4]);this._peerConnection.addIceCandidate({candidate:"a=candidate:10 1 UDP 1 "+i.getIpv4Address()+" 9002 typ host ",sdpMLineIndex:e[t].sdpMLineIndex,sdpMid:e[t].sdpMid}),this._peerConnection.addIceCandidate({candidate:"a=candidate:11 1 UDP 1 "+i.getIpv4Address()+" "+i.getIpv4Port()+" typ host ",sdpMLineIndex:e[t].sdpMLineIndex,sdpMid:e[t].sdpMid})}this._peerConnection.addIceCandidate({candidate:e[t].candidate,sdpMid:e[t].sdpMid,sdpMLineIndex:e[t].sdpMLineIndex})}}};var I=class{_player;_peerConnection;constructor(e){this._player=e,this._peerConnection=e._peerConnection}getAvailableCodecs(){let e=RTCRtpReceiver.getCapabilities("video")?.codecs;if(e===void 0)return[];let t=[];for(let n in e)t.includes(e[n].mimeType)||t.push(e[n].mimeType);return t}setLocalSDP(e){return console.log("[SDP] setLocalSDP() Setting local SDP:",e),e.sdp=e.sdp?.replace("useinbandfec=1","useinbandfec=1; stereo=1"),e}setRemoteSDP(e){return console.log("[SDP] setRemoteSDP() Setting remote SDP:",e),e}getDefaultCodecPreferences(){let e=RTCRtpReceiver.getCapabilities("video")?.codecs;if(e===void 0)return[];let t=[],n=[],i=[],a=[];for(let o in e)e[o].mimeType.includes("H264")?e[o].sdpFmtpLine?.includes("profile-level-id=4d")?t.push(e[o]):e[o].sdpFmtpLine?.includes("profile-level-id=42e")?n.push(e[o]):e[o].sdpFmtpLine?.includes("profile-level-id=420")&&i.push(e[o]):(e[o].mimeType.includes("ulpfec")||e[o].mimeType.includes("flexfec")||e[o].mimeType.includes("VP9")||e[o].mimeType.includes("VP8"))&&a.push(e[o]);return[...t,...n,...i,...a]}_setBitrate(e,t,n){let i=e.split(`
`),a=-1;for(let o=0;o<i.length;o++)if(i[o].indexOf("m="+t)===0){a=o;break}if(a===-1)return console.debug("Could not find the m line for",t),e;for(a++;i[a].indexOf("i=")===0||i[a].indexOf("c=")===0;)a++;if(i[a].indexOf("b")===0)return i[a]="b=AS:"+n,i.join(`
`);let s=i.slice(0,a);return s.push("b=AS:"+n),s=s.concat(i.slice(a,i.length)),s.join(`
`)}};var P=class{_player;_peerConnection;_videoCodec="";_audioCodec="";_videoWidth=0;_videoHeight=0;_videoFps=0;_rtt=0;_remoteHost="";_remotePort=0;_remoteIsLocal=!1;_remoteIsIpv6=!1;_activeRemoteCandidate="";constructor(e){this._player=e,this._peerConnection=e._peerConnection,setInterval(this.loop.bind(this),1e3)}loop(){this._peerConnection.getStats().then(e=>{e.forEach(t=>{t.type==="inbound-rtp"?this.readInboundRtp(t):t.type==="candidate-pair"&&t.packetsReceived!==void 0&&t.packetsReceived>0?this.readCandidatePair(t):t.type==="remote-candidate"&&this.readRemoteCandidate(t)})})}readInboundRtp(e){e.kind==="video"&&e.codecId&&e.packetsReceived!==void 0&&e.packetsReceived>0?(e.codecId.includes("profile-level-id=4d")?this._videoCodec="H264 (High)":e.codecId.includes("profile-level-id=42e")?this._videoCodec="H264 (Normal)":e.codecId.includes("profile-level-id=420")?this._videoCodec="H264 (Low)":this._videoCodec="Other ("+e.codecId+")",e.frameWidth&&(this._videoWidth=e.frameWidth),e.frameHeight&&(this._videoHeight=e.frameHeight),e.framesPerSecond&&(this._videoFps=e.framesPerSecond)):e.kind==="audio"&&e.codecId&&e.packetsReceived!==void 0&&e.packetsReceived>0&&(this._audioCodec=e.codecId)}readCandidatePair(e){this._activeRemoteCandidate=e.remoteCandidateId,this._rtt=e.currentRoundTripTime}readRemoteCandidate(e){e.id===this._activeRemoteCandidate&&(this.isPrivateIP(e.address)?this._remoteIsLocal=!0:this._remoteIsLocal=!1,this.isIpv6(e.address)?this._remoteIsIpv6=!0:this._remoteIsIpv6=!1,this._remoteHost=e.address,this._remotePort=e.port)}isPrivateIP(e){let t=e.split(".");return t[0]==="10"||t[0]==="172"&&parseInt(t[1],10)>=16&&parseInt(t[1],10)<=31||t[0]==="192"&&t[1]==="168"}isIpv6(e){return e.split(":").length>3}};var G=class{_player;_videoComponent;_overlays={debug:void 0};constructor(e,t){this._videoComponent=e,this._player=t}toggleDebug(){this._overlays.debug===void 0?this.createDebugOverlay():this.destroy()}createDebugOverlay(){this._overlays.debug=document.createElement("div"),this._overlays.debug.id="playerDebugOverlay",this._overlays.debug.style.position="absolute",this._overlays.debug.style.top="0",this._overlays.debug.style.left="0",this._overlays.debug.style.width=this._videoComponent.getElement()?.style.width||"100%",this._overlays.debug.style.height=this._videoComponent.getElement()?.style.height||"auto",this._overlays.debug.style.background="linear-gradient(0deg, rgba(0,0,0, 0) 0%, rgba(0,0,0, 0) 75%, rgba(0,0,0, 0.5) 100%)",this._overlays.debug.style.padding="10px",this._overlays.debug.style.pointerEvents="none",document.getElementById(this._player.getElementId())?.appendChild(this._overlays.debug),setTimeout(()=>{this.refreshDebugOverlay()},500),this.refreshDebugOverlay()}destroy(){this._overlays.debug?.remove(),this._overlays.debug=void 0}refreshDebugOverlay(){if(this._overlays.debug!==void 0){this._overlays.debug.innerHTML="",this._overlays.debug.appendChild(this.createLabel("Local Play",this._player.getStats()._remoteIsLocal?"Local":"Remote","ok")),this._overlays.debug.appendChild(this.createLabel("Resolution",this._player.getStats()._videoWidth+"x"+this._player.getStats()._videoHeight,"ok")),this._overlays.debug.appendChild(this.createLabel("Stream FPS",this._player.getStats()._videoFps.toString(),this._player.getStats()._videoFps>=58?"ok":"warning"));let e=this._videoComponent.getFrameStats?.();e&&(this._overlays.debug.appendChild(this.createLabel("Render FPS",e.renderingFps.toString(),e.renderingFps>=58?"ok":"warning")),this._overlays.debug.appendChild(this.createLabel("Render Delay",e.renderDelayMs.toString()+" ms",e.renderDelayMs<16?"ok":e.renderDelayMs<33?"warning":"error")),this._overlays.debug.appendChild(this.createLabel("Dropped Frames",e.droppedFrames.toString(),e.droppedFrames===0?"ok":e.droppedFrames<30?"warning":"error"))),this._overlays.debug.appendChild(this.createLabel("Connection",this._player.getStats()._remoteIsIpv6?"IPv6":"IPv4","ok")),this._overlays.debug.appendChild(this.createLabel("Video",this._player.getStats()._videoCodec,"ok"));let t=this._player.getStats()._rtt*1e3>75?"error":this._player.getStats()._rtt*1e3>40?"warning":"ok";this._overlays.debug.appendChild(this.createLabel("RTT",(this._player.getStats()._rtt*1e3).toString()+" ms",t)),setTimeout(()=>{this.refreshDebugOverlay()},500)}}createLabel(e,t="",n=""){let i={borderRadius:"5px",background:"linear-gradient(0deg, rgba(28,26,26,1) 0%, rgba(47,45,45,1) 100%)",padding:"10px",fontSize:"12px",marginTop:"3px",marginRight:"10px",marginBottom:"2px",textTransform:"uppercase",color:"white",display:"inline-block"},a=document.createElement("span"),s={error:"rgb(220, 53, 69)",warning:"rgb(255, 193, 7)",ok:"rgb(25, 135, 84)"};t!==""?a.innerHTML=`${e}: <span style="background: ${s[n]}; border-radius: 5px; padding: 4px; padding-left: 8px; padding-right: 8px;">${t}</span>`:a.innerText=e;for(let o in i)a.style[o]=i[o];return a}};var L=class{_player;_element;_overlay;constructor(e){this._player=e,this._overlay=new G(this,this._pLine truncated
in vec2 position;
out vec2 vUV;
void main() { vUV = position * 0.5 + 0.5; gl_Position = vec4(position, 0.0, 1.0); }`,j=`attribute vec2 position;
varying vec2 vUV;
void main() { vUV = position * 0.5 + 0.5; gl_Position = vec4(position, 0.0, 1.0); }`,Z=`#version 300 es
precision mediump float;
uniform sampler2D screenTexture;
uniform vec2 resolution;
uniform int filterId;
uniform float sharpenFactor;
uniform float brightness;
uniform float contrast;
uniform float gamma;
uniform float saturation;
uniform float deband;
out vec4 fragColor;
const float CAS_CONTRAST_PEAK = 0.8 * -3.0 + 8.0;
vec3 sharpen(vec2 coord, vec3 e) {
vec2 px = 1.0 / resolution;
vec3 b = texture(screenTexture, coord + px * vec2(0, 1)).rgb;
vec3 d = texture(screenTexture, coord + px * vec2(-1, 0)).rgb;
vec3 f = texture(screenTexture, coord + px * vec2(1, 0)).rgb;
vec3 h = texture(screenTexture, coord + px * vec2(0, -1)).rgb;
vec3 a = texture(screenTexture, coord + px * vec2(-1, 1)).rgb;
vec3 c = texture(screenTexture, coord + px * vec2(1, 1)).rgb;
vec3 g = texture(screenTexture, coord + px * vec2(-1, -1)).rgb;
vec3 i = texture(screenTexture, coord + px * vec2(1, -1)).rgb;
if (filterId == 1) {
vec3 blur = ((a + c + g + i) + (b + d + f + h) * 2.0 + e * 4.0) / 16.0;
return e + (e - blur) * sharpenFactor / 3.0;
}
vec3 minRgb = min(min(min(d, e), min(f, b)), h) + min(min(a, c), min(g, i));
vec3 maxRgb = max(max(max(d, e), max(f, b)), h) + max(max(a, c), max(g, i));
vec3 amplify = inversesqrt(clamp(min(minRgb, 2.0 - maxRgb) / maxRgb, 0.0, 1.0));
vec3 weight = -(1.0 / (amplify * CAS_CONTRAST_PEAK));
vec3 outColor = clamp(((b + d + f + h) * weight + e) / (4.0 * weight + 1.0), 0.0, 1.0);
return mix(e, outColor, sharpenFactor / 2.0);
}
float ign(vec2 p) { return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); }
void main() {
vec2 uv = gl_FragCoord.xy / resolution;
vec3 color = texture(screenTexture, uv).rgb;
if (sharpenFactor > 0.0) color = sharpen(uv, color);
color = clamp(color + brightness, 0.0, 1.0);
color = (color - 0.5) * clamp(contrast + 1.0, 0.5, 2.0) + 0.5;
color = mix(vec3(dot(color, vec3(0.2126, 0.7152, 0.0722))), color, saturation);
color = pow(max(color, 0.0), vec3(1.0 / gamma));
if (deband > 0.0) color += vec3(((ign(gl_FragCoord.xy) + ign(gl_FragCoord.xy + vec2(11.0, 17.0))) - 1.0) * (deband / 255.0));
fragColor = vec4(color, 1.0);
}`,ee=`precision highp float;
#define FXAA_MIN_REDUCE (1.0 / 128.0)
#define FXAA_MUL_REDUCE (1.0 / 8.0)
#define MAX_SPAN 8.0
uniform sampler2D screenTexture;
uniform vec2 resolution;
const vec3 luma = vec3(0.299, 0.587, 0.114);
void main() {
vec2 invResolution = 1.0 / resolution;
vec3 rgbNW = texture2D(screenTexture, (gl_FragCoord.xy + vec2(-1.0, -1.0)) * invResolution).rgb;
vec3 rgbNE = texture2D(screenTexture, (gl_FragCoord.xy + vec2( 1.0, -1.0)) * invResolution).rgb;
vec3 rgbSW = texture2D(screenTexture, (gl_FragCoord.xy + vec2(-1.0, 1.0)) * invResolution).rgb;
vec3 rgbSE = texture2D(screenTexture, (gl_FragCoord.xy + vec2( 1.0, 1.0)) * invResolution).rgb;
vec3 rgbM = texture2D(screenTexture, gl_FragCoord.xy * invResolution).rgb;
float lumaNW = dot(rgbNW, luma);
float lumaNE = dot(rgbNE, luma);
float lumaSW = dot(rgbSW, luma);
float lumaSE = dot(rgbSE, luma);
float lumaM = dot(rgbM, luma);
float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));
float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));
vec2 dir;
dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));
dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));
float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) * 0.25 * FXAA_MUL_REDUCE, FXAA_MIN_REDUCE);
float minDirFactor = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);
dir = clamp(dir * minDirFactor, vec2(-MAX_SPAN), vec2(MAX_SPAN)) * invResolution;
vec4 rgbA = 0.5 * (
texture2D(screenTexture, gl_FragCoord.xy * invResolution + dir * (1.0 / 3.0 - 0.5)) +
texture2D(screenTexture, gl_FragCoord.xy * invResolution + dir * (2.0 / 3.0 - 0.5)));
vec4 rgbB = rgbA * 0.5 + 0.25 * (
texture2D(screenTexture, gl_FragCoord.xy * invResolution + dir * -0.5) +
texture2D(screenTexture, gl_FragCoord.xy * invResolution + dir * 0.5));
float lumaB = dot(rgbB, vec4(luma, 0.0));
gl_FragColor = lumaB < lumaMin || lumaB > lumaMax ? rgbA : rgbB;
}`,te=`precision highp float;
uniform sampler2D screenTexture;
uniform vec2 resolution;
void main() {
vec2 uv = gl_FragCoord.xy / resolution;
float edgeThreshold = 0.2;
vec2 offset = vec2(1.0) / resolution;
vec3 colorCenter = texture2D(screenTexture, uv).rgb;
vec3 colorLeft = texture2D(screenTexture, uv - vec2(offset.x, 0.0)).rgb;
vec3 colorRight = texture2D(screenTexture, uv + vec2(offset.x, 0.0)).rgb;
vec3 colorUp = texture2D(screenTexture, uv - vec2(0.0, offset.y)).rgb;
vec3 colorDown = texture2D(screenTexture, uv + vec2(0.0, offset.y)).rgb;
float diffHorizontal = length(colorRight - colorLeft);
float diffVertical = length(colorUp - colorDown);
float edgeFactor = step(edgeThreshold, diffHorizontal + diffVertical);
vec3 outlineColor = mix(colorCenter, vec3(0.0), edgeFactor);
gl_FragColor = vec4(outlineColor, 1.0);
}`,ne=`precision highp float;
#define CA_AMOUNT 1.0025
#define SCANLINE_INTENSITY_X 0.125
#define SCANLINE_INTENSITY_Y 0.375
#define SCANLINE_SIZE 1024.0
uniform sampler2D screenTexture;
varying vec2 vUV;
void main() {
vec4 finalColor = texture2D(screenTexture, vUV);
finalColor.rgb = vec3(
texture2D(screenTexture, (vUV - 0.5) * CA_AMOUNT + 0.5).r,
finalColor.g,
texture2D(screenTexture, (vUV - 0.5) / CA_AMOUNT + 0.5).b
);
float scanlineX = abs(sin(vUV.x * SCANLINE_SIZE) * 0.5 * SCANLINE_INTENSITY_X);
float scanlineY = abs(sin(vUV.y * SCANLINE_SIZE) * 0.5 * SCANLINE_INTENSITY_Y);
gl_FragColor = vec4(mix(finalColor.rgb, vec3(0.0), scanlineX + scanlineY), finalColor.a);
}`,ie=`precision highp float;
#define PI 3.14159265
#define SCANLINE_INTENSITY 0.35
#define CHROMA_OFFSET 0.005
#define BLUR_RADIUS 0.002
#define WARP_AMOUNT 0.01
#define SCANLINE_DARKEN 0.5
uniform sampler2D screenTexture;
uniform int FrameCount;
uniform vec2 TextureSize;
uniform vec2 resolution;
varying vec2 vUV;
const mat3 yiq_mat = mat3(
0.299, 0.587, 0.114,
0.596, -0.275, -0.321,
0.212, -0.523, 0.311
);
const mat3 yiq2rgb_mat = mat3(
1.0, 0.956, 0.621,
1.0, -0.272, -0.647,
1.0, -1.106, 1.705
);
vec3 applyNTSC(vec2 uv) {
vec3 col = texture2D(screenTexture, uv).rgb;
vec3 yiq = col * yiq_mat;
float chromaPhase = PI * (mod(uv.y * TextureSize.y, 2.0) + float(FrameCount));
yiq.y *= cos(chromaPhase * 0.5);
yiq.z *= sin(chromaPhase * 0.5);
vec3 rgb = yiq * yiq2rgb_mat;
vec3 finalColor;
finalColor.r = texture2D(screenTexture, uv + vec2(CHROMA_OFFSET, 0.0)).r;
finalColor.g = texture2D(screenTexture, uv + vec2(0.0, BLUR_RADIUS)).g;
finalColor.b = texture2D(screenTexture, uv - vec2(CHROMA_OFFSET, 0.0)).b;
return finalColor;
}
vec3 applyScanlines(vec2 uv) {
vec3 col = texture2D(screenTexture, uv).rgb;
float scanline = abs(sin(uv.y * resolution.y * 2.0)) * SCANLINE_INTENSITY;
col *= 1.0 - (scanline * SCANLINE_DARKEN);
return col;
}
vec2 applyWarp(vec2 uv) {
uv = uv * 2.0 - 1.0;
float r = sqrt(uv.x * uv.x + uv.y * uv.y);
uv += uv * (r * r) * WARP_AMOUNT;
return uv * 0.5 + 0.5;
}
void main() {
vec2 warpedUV = applyWarp(vUV);
vec3 ntscColor = applyNTSC(warpedUV);
vec3 scanlineColor = applyScanlines(warpedUV);
vec3 finalColor = mix(ntscColor, scanlineColor, 0.7);
gl_FragColor = vec4(finalColor, 1.0);
}`,H=class{constructor(e,t){this.video=e;this.effects=t;this.canvas=document.createElement("canvas"),Object.assign(this.canvas.style,{position:"absolute",inset:"0",width:"100%",height:"100%",objectFit:"contain",zIndex:"1"}),e.parentElement?.appendChild(this.canvas);let n=this.canvas.getContext("webgl2",{alpha:!1,antialias:!1,depth:!1,desynchronized:!0,powerPreference:"high-performance"});if(n===null)throw new Error("WebGL2 unavailable");this.gl=n;let i=n.createBuffer();n.bindBuffer(n.ARRAY_BUFFER,i),n.bufferData(n.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),n.STATIC_DRAW),this.passes.set("base",this.compile(J,Z,["screenTexture","resolution","filterId","sharpenFactor","brightness","contrast","gamma","saturation","deband"])),this.videoTexture=this.texture(),this.schedule()}canvas;gl;passes=new Map;videoTexture;targets=[];width=0;height=0;frame=0;lastDraw=0;stopped=!1;idle=!1;pending=!1;update(e){this.effects=e}pause(){this.idle||this.stopped||(this.idle=!0,this.canvas.style.display="none")}resume(e){this.effects=e,!(!this.idle||this.stopped)&&(this.idle=!1,this.canvas.style.display="",this.schedule())}schedule(){this.pending||(this.pending=!0,this.video.requestVideoFrameCallback(this.onFrame))}compile(e,t,n){let i=this.gl,a=(o,d)=>{let u=i.createShader(o);if(i.shaderSource(u,d),i.compileShader(u),!i.getShaderParameter(u,i.COMPILE_STATUS))throw new Error(`shader: ${i.getShaderInfoLog(u)}`);return u},s=i.createProgram();if(i.attachShader(s,a(i.VERTEX_SHADER,e)),i.attachShader(s,a(i.FRAGMENT_SHADER,t)),i.bindAttribLocation(s,0,"position"),i.linkProgram(s),!i.getProgramParameter(s,i.LINK_STATUS))throw new Error(`program: ${i.getProgramInfoLog(s)}`);return{program:s,uniforms:new Map(n.map(o=>[o,i.getUniformLocation(s,o)]))}}extra(e){let t=this.passes.get(e);if(t===void 0){let n={fxaa:ee,toon:te,crt:ne,ntsc:ie}[e];t=this.compile(j,n,["screenTexture","resolution","TextureSize","FrameCount"]),this.passes.set(e,t)}return t}texture(){let e=this.gl,t=e.createTexture();return e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),t}resize(e,t){let n=this.gl;this.width=e,this.height=t,this.canvas.width=e,this.canvas.height=t;for(let i of this.targets)n.deleteFramebuffer(i.framebuffer),n.deleteTexture(i.texture);this.targets=[0,1].map(()=>{let i=this.texture();n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e,t,0,n.RGBA,n.UNSIGNED_BYTE,null);let a=n.createFramebuffer();return n.bindFramebuffer(n.FRAMEBUFFER,a),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,i,0),{framebuffer:a,texture:i}}),n.bindFramebuffer(n.FRAMEBUFFER,null)}onFrame=e=>{if(this.pending=!1,this.stopped||this.idle)return;this.schedule();let t=this.effects.maxFps;if(!(t>0&&e-this.lastDraw<1e3/t-2)){this.lastDraw=e;try{this.draw()}catch(n){window.DDCloud?.log(`effects: ${String(n).slice(0,200)}`),this.destroy()}}};draw(){let e=this.gl,t=this.effects,n=this.video.videoWidth,i=this.video.videoHeight;if(n===0||i===0)return;(n!==this.width||i!==this.height)&&this.resize(n,i),this.frame++,e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,this.videoTexture),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,!0),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,this.video);let a=["fxaa","toon","crt","ntsc"].filter(d=>t[d]);e.viewport(0,0,n,i),e.enableVertexAttribArray(0),e.vertexAttribPointer(0,2,e.FLOAT,!1,0,0);let s=this.passes.get("base");e.bindFramebuffer(e.FRAMEBUFFER,a.length>0?this.targets[0].framebuffer:null),e.useProgram(s.program);let o=s.uniforms;e.uniform1i(o.get("screenTexture"),0),e.uniform2f(o.get("resolution"),n,i),e.uniform1i(o.get("filterId"),t.sharpenMode==="usm"?1:2),e.uniform1f(o.get("sharpenFactor"),t.sharpen),e.uniform1f(o.get("brightness"),t.brightness/100),e.uniform1f(o.get("contrast"),t.contrast/100),e.uniform1f(o.get("gamma"),Math.min(5,Math.max(.1,t.gamma))),e.uniform1f(o.get("saturation"),t.saturation/100),e.uniform1f(o.get("deband"),t.deband),e.drawArrays(e.TRIANGLES,0,3),a.forEach((d,u)=>{let h=this.extra(d),g=this.targets[u%2],p=u===a.length-1;e.bindFramebuffer(e.FRAMEBUFFER,p?null:this.targets[(u+1)%2].framebuffer),e.useProgram(h.program),e.bindTexture(e.TEXTURE_2D,g.texture);let c=h.uniforms;e.uniform1i(c.get("screenTexture")??null,0),e.uniform2f(c.get("resolution")??null,n,i),e.uniform2f(c.get("TextureSize")??null,n,i),e.uniform1i(c.get("FrameCount")??null,this.frame),e.drawArrays(e.TRIANGLES,0,3)})}destroy(){this.stopped=!0,this.canvas.remove(),this.gl.getExtension("WEBGL_lose_context")?.loseContext()}};var V=class{constructor(e){this.pc=e;this.element=document.createElement("div"),Object.assign(this.element.style,{position:"absolute",top:"8px",right:"8px",zIndex:"3",padding:"4px 8px",borderRadius:"6px",background:"rgba(0,0,0,0.55)",color:"#e8e8e8",font:"12px monospace",lineHeight:"16px",pointerEvent Line truncated
`:" \xB7 ")}destroy(){this.show(0,this.vertical,this.server,this.left),this.element.remove()}};function z(r,e){let t=e==="high"?"4d":e==="low"?"420":"42e",n=[];for(let d of r.matchAll(/a=fmtp:(\d+).*profile-level-id=([0-9a-f]{6})/g))d[2].startsWith(t)&&n.push(d[1]);if(n.length===0)return r;let i=r.split(`\r
`),a=i.findIndex(d=>d.startsWith("m=video"));if(a<0)return r;let s=i[a].trim().split(" "),o=s.slice(3).filter(d=>!n.includes(d));return i[a]=s.slice(0,3).concat(n,o).join(" "),i.join(`\r
`)}function K(r,e){let t=r.split(`\r
`),n=t.findIndex(a=>a.startsWith("m=video"));if(n<0)return r;let i=`b=AS:${e}`;for(let a=n+1;a<=t.length;a++){let s=t[a];if(s===void 0||s.startsWith("m=")){t.splice(a,0,i);break}if(!(s.startsWith("i=")||s.startsWith("c="))){if(s.startsWith("b=AS:")){t[a]=i;break}t.splice(a,0,i);break}}return t.join(`\r
`)}var m=JSON.parse(DDCloud.settings()),ae=RTCPeerConnection.prototype.setLocalDescription;RTCPeerConnection.prototype.setLocalDescription=function(r){return r?.sdp&&((m.codec==="high"||m.codec==="normal"||m.codec==="low")&&(r.sdp=z(r.sdp,m.codec)),m.bitrateMbps>0&&(r.sdp=K(r.sdp,m.bitrateMbps*1e3))),ae.call(this,r)};window.__ddRumble=m.rumble/100;window.addEventListener("error",r=>DDCloud.log(`error: ${r.message} @${r.lineno}`));window.addEventListener("unhandledrejection",r=>DDCloud.log(`rejection: ${String(r.reason).slice(0,200)}`));window.addEventListener("gamepadconnected",r=>DDCloud.log(`controller: ${r.gamepad.id.slice(0,60)} mapping=${r.gamepad.mapping||"none"} buttons=${r.gamepad.buttons.length} axes=${r.gamepad.axes.length}`));var W=new Map,re=1;window.__ddResolve=(r,e,t)=>{let n=W.get(r);W.delete(r),n&&n({status:e,body:t})};function C(r,e=""){return new Promise(t=>{let n=re++;W.set(n,t),DDCloud.call(n,r,typeof e=="string"?e:JSON.stringify(e))})}var B=r=>new Promise(e=>setTimeout(e,r)),se=r=>r.status>=200&&r.status<300;function x(r){let e=document.getElementById("status");e&&(e.textContent=r),DDCloud.status(r)}var T=class extends Error{constructor(t,n){super(t);this.stage=t;this.detail=n}};function k(r,e){if(!se(e))throw new T(r,`${e.status} ${e.body.slice(0,300)}`);return e}function oe(r,e){return new Promise(t=>{if(r.iceGatheringState==="complete")return t();let n=setTimeout(t,e);r.addEventListener("icegatheringstatechange",()=>{r.iceGatheringState==="complete"&&(clearTimeout(n),t())})})}async function de(){x("Starting the game on Xbox Cloud Gaming\u2026"),k("start",await C("start"));let r=!1,e=0;for(;;){let l=k("state",await C("state")),f=JSON.parse(l.body||"{}");if(f.state==="Provisioned")break;if(f.state==="Failed")throw new T("provision",JSON.stringify(f.errorDetails??{}).slice(0,300));f.state==="ReadyToConnect"&&!r?(r=!0,x("Signing in to the cloud console\u2026"),k("connect",await C("connect"))):f.state==="WaitingForResources"?x(`In the queue for a cloud console\u2026 ${Math.round(e/1e3)} s`):x(`Getting a cloud console ready\u2026 ${Math.round(e/1e3)} s`),await B(1e3),e+=1e3}x("Connecting\u2026");let t=new U("player");t.init();let n=t._peerConnection,i=t._channels.input,a=i.queueMetadataFrame.bind(i);i.queueMetadataFrame=l=>{if(m.preventDrops){let f=l.frameRenderedTimeMs-l.frameDecodedTimeMs;l.frameDecodedTimeMs=l.frameSubmittedTimeMs+10,l.frameRenderedTimeMs=l.frameDecodedTimeMs+f}a(l)};let s,o,d=()=>{if(!(o===void 0||s===void 0&&m.volume===100)){if(s===void 0){let l=new AudioContext;s=l.createGain(),l.createMediaStreamSource(o).connect(s).connect(l.destination);let f=document.querySelector("#player audio");f&&(f.muted=!0)}s.gain.value=m.volume/100}};n.addEventListener("track",l=>{l.track.kind==="audio"&&(o=l.streams[0],d())});let u=new V(n),h,g=()=>{let l=t.getVideoElement();if(l!==void 0){if(!X(m)){h?.pause();return}if(h===void 0)try{h=new H(l,m)}catch(f){DDCloud.log(`effects unavailable: ${String(f).slice(0,200)}`)}else h.resume(m)}};window.__ddApply=l=>{m=JSON.parse(l),window.__ddRumble=m.rumble/100,u.show(m.statsLevel,m.statsLayout==="vertical",m.server,m.statsCorner==="left"),d(),g()},n.addEventListener("connectionstatechange",()=>{n.connectionState==="connected"?(x(""),DDCloud.playing(),u.show(m.statsLevel,m.statsLayout==="vertical",m.server,m.statsCorner==="left"),setTimeout(g,500)):n.connectionState==="failed"?DDCloud.failed("webrtc","connection failed"):n.connectionState==="disconnected"&&x("Connection lost\u2026")});let p=await t.createOffer(),c=k("sdp",await C("sdp",p.sdp??"")),O=JSON.parse(JSON.parse(c.body).exchangeResponse);if(O.status&&O.status!=="success")throw new T("sdp-answer",JSON.stringify(O).slice(0,300));await t.setRemoteSDP(O.sdp),await oe(n,3e3);let Y=(await t.getICECandidates()).map(l=>JSON.stringify({candidate:l.candidate,sdpMid:l.sdpMid,sdpMLineIndex:l.sdpMLineIndex,usernameFragment:l.usernameFragment})),$=k("ice",await C("ice",Y));t.setRemoteIceCandidates(JSON.parse(JSON.parse($.body).exchangeResponse));let q=Date.now();for(;!t._channels.message._handshakeCompleted&&Date.now()-q<2e4;)await B(100);DDCloud.log(`handshake ${t._channels.message._handshakeCompleted?"done":"missing"} after ${Date.now()-q} ms`),await B(300);let b=new v(0,{enable_keyboard:!1});b.attach(t),DDCloud.log(`controllers at attach: ${Array.from(navigator.getGamepads()).filter(Boolean).length}`),window.__ddNexus=()=>{b.sendButtonState("Nexus",1),setTimeout(()=>b.sendButtonState("Nexus",0),200)},window.__ddButton=(l,f)=>b.sendButtonState(l,f),window.__ddInput=l=>{l?b.onWindowFocus():b.onWindowBlur()},setInterval(()=>{C("keepalive")},3e4),window.__ddStop=()=>{try{h?.destroy(),u.destroy(),b.detach(),t.destroy()}catch{}}}de().catch(r=>{r instanceof T?DDCloud.failed(r.stage,r.detail):DDCloud.failed("page",String(r).slice(0,300))});})();
-2
View File
@@ -75,13 +75,11 @@ Java_com_droiddeck_launcher_gpu_VulkanInfo_nativeQuery(JNIEnv *env, jclass clazz
VkPhysicalDeviceDriverProperties driver = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES }; VkPhysicalDeviceDriverProperties driver = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES };
VkPhysicalDeviceProperties2 p2 = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, .pNext = &driver }; VkPhysicalDeviceProperties2 p2 = { .sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, .pNext = &driver };
vkGetPhysicalDeviceProperties2(device, &p2); vkGetPhysicalDeviceProperties2(device, &p2);
LINE("driver_id=%u\n", driver.driverID);
LINE("driver_name=%s\n", driver.driverName); LINE("driver_name=%s\n", driver.driverName);
LINE("driver_info=%s\n", driver.driverInfo); LINE("driver_info=%s\n", driver.driverInfo);
LINE("conformance=%u.%u.%u.%u\n", driver.conformanceVersion.major, driver.conformanceVersion.minor, LINE("conformance=%u.%u.%u.%u\n", driver.conformanceVersion.major, driver.conformanceVersion.minor,
driver.conformanceVersion.subminor, driver.conformanceVersion.patch); driver.conformanceVersion.subminor, driver.conformanceVersion.patch);
} }
LINE("driver_version_raw=%u\n", p.driverVersion);
LINE("extension_count=%u\n", extCount); LINE("extension_count=%u\n", extCount);
for (size_t e = 0; e < sizeof(EXTENSIONS) / sizeof(*EXTENSIONS); e++) { for (size_t e = 0; e < sizeof(EXTENSIONS) / sizeof(*EXTENSIONS); e++) {
int has = 0; int has = 0;
@@ -10,8 +10,6 @@ add_library(droiddeckwayland SHARED
src/waylandcomp_jni.c src/waylandcomp_jni.c
src/gpu_clock_pin.c src/gpu_clock_pin.c
src/droiddeck_ext.c src/droiddeck_ext.c
src/wl_android_buffer.c
generated/wayland-android-protocol.c
src/wl_dmabuf.c src/wl_dmabuf.c
src/wl_clipboard.c src/wl_clipboard.c
src/wl_text_input.c src/wl_text_input.c
@@ -97,5 +95,4 @@ target_link_libraries(droiddeckwayland
dl dl
log log
android android
nativewindow
) )
@@ -1,104 +0,0 @@
/* Generated by wayland-scanner 1.26.0 */
/*
* Copyright © 2012 Collabora, Ltd.
*
* Permission to use, copy, modify, distribute, and sell this
* software and its documentation for any purpose is hereby granted
* without fee, provided that the above copyright notice appear in
* all copies and that both that copyright notice and this permission
* notice appear in supporting documentation, and that the name of
* the copyright holders not be used in advertising or publicity
* pertaining to distribution of the software without specific,
* written prior permission. The copyright holders make no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied
* warranty.
*
* THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
* SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
* THIS SOFTWARE.
*/
#include <stdbool.h>
#include <stdlib.h>
#include <stdint.h>
#include "wayland-util.h"
#ifndef __has_attribute
# define __has_attribute(x) 0 /* Compatibility with non-clang compilers. */
#endif
#if (__has_attribute(visibility) || defined(__GNUC__) && __GNUC__ >= 4)
#define WL_PRIVATE __attribute__ ((visibility("hidden")))
#else
#define WL_PRIVATE
#endif
extern const struct wl_interface android_wlegl_handle_interface;
extern const struct wl_interface android_wlegl_server_buffer_handle_interface;
extern const struct wl_interface wl_buffer_interface;
static const struct wl_interface *android_types[] = {
NULL,
NULL,
&android_wlegl_handle_interface,
NULL,
NULL,
&wl_buffer_interface,
NULL,
NULL,
NULL,
NULL,
NULL,
&android_wlegl_handle_interface,
&android_wlegl_server_buffer_handle_interface,
NULL,
NULL,
NULL,
NULL,
&wl_buffer_interface,
NULL,
NULL,
};
static const struct wl_message android_wlegl_requests[] = {
{ "create_handle", "nia", android_types + 2 },
{ "create_buffer", "niiiiio", android_types + 5 },
{ "get_server_buffer_handle", "2niiii", android_types + 12 },
};
WL_PRIVATE const struct wl_interface android_wlegl_interface = {
"android_wlegl", 3,
3, android_wlegl_requests,
0, NULL,
};
static const struct wl_message android_wlegl_handle_requests[] = {
{ "add_fd", "h", android_types + 0 },
{ "destroy", "", android_types + 0 },
};
WL_PRIVATE const struct wl_interface android_wlegl_handle_interface = {
"android_wlegl_handle", 1,
2, android_wlegl_handle_requests,
0, NULL,
};
static const struct wl_message android_wlegl_server_buffer_handle_events[] = {
{ "buffer_fd", "h", android_types + 0 },
{ "buffer_ints", "a", android_types + 0 },
{ "buffer", "nii", android_types + 17 },
{ "linear_layout", "3uu", android_types + 0 },
};
WL_PRIVATE const struct wl_interface android_wlegl_server_buffer_handle_interface = {
"android_wlegl_server_buffer_handle", 3,
0, NULL,
4, android_wlegl_server_buffer_handle_events,
};
@@ -1,341 +0,0 @@
/* Generated by wayland-scanner 1.26.0 */
#ifndef ANDROID_SERVER_PROTOCOL_H
#define ANDROID_SERVER_PROTOCOL_H
#include <stdint.h>
#include <stddef.h>
#include "wayland-server.h"
#ifdef __cplusplus
extern "C" {
#endif
struct wl_client;
struct wl_resource;
/**
* @page page_android The android protocol
* @section page_ifaces_android Interfaces
* - @subpage page_iface_android_wlegl - Android EGL graphics buffer support
* - @subpage page_iface_android_wlegl_handle - An Android native_handle_t object
* - @subpage page_iface_android_wlegl_server_buffer_handle - a server allocated buffer
* @section page_copyright_android Copyright
* <pre>
*
* Copyright © 2012 Collabora, Ltd.
*
* Permission to use, copy, modify, distribute, and sell this
* software and its documentation for any purpose is hereby granted
* without fee, provided that the above copyright notice appear in
* all copies and that both that copyright notice and this permission
* notice appear in supporting documentation, and that the name of
* the copyright holders not be used in advertising or publicity
* pertaining to distribution of the software without specific,
* written prior permission. The copyright holders make no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied
* warranty.
*
* THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
* SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
* SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
* AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
* THIS SOFTWARE.
* </pre>
*/
struct android_wlegl;
struct android_wlegl_handle;
struct android_wlegl_server_buffer_handle;
struct wl_buffer;
#ifndef ANDROID_WLEGL_INTERFACE
#define ANDROID_WLEGL_INTERFACE
/**
* @page page_iface_android_wlegl android_wlegl
* @section page_iface_android_wlegl_desc Description
*
* Interface used in the Android wrapper libEGL to share
* graphics buffers between the server and the client.
* @section page_iface_android_wlegl_api API
* See @ref iface_android_wlegl.
*/
/**
* @defgroup iface_android_wlegl The android_wlegl interface
*
* Interface used in the Android wrapper libEGL to share
* graphics buffers between the server and the client.
*/
extern const struct wl_interface android_wlegl_interface;
#endif
#ifndef ANDROID_WLEGL_HANDLE_INTERFACE
#define ANDROID_WLEGL_HANDLE_INTERFACE
/**
* @page page_iface_android_wlegl_handle android_wlegl_handle
* @section page_iface_android_wlegl_handle_desc Description
*
* The Android native_handle_t is a semi-opaque object, that
* contains an EGL implementation specific number of int32
* values and file descriptors.
*
* We cannot send a variable size array of file descriptors
* over the Wayland protocol, so we send them one by one.
* @section page_iface_android_wlegl_handle_api API
* See @ref iface_android_wlegl_handle.
*/
/**
* @defgroup iface_android_wlegl_handle The android_wlegl_handle interface
*
* The Android native_handle_t is a semi-opaque object, that
* contains an EGL implementation specific number of int32
* values and file descriptors.
*
* We cannot send a variable size array of file descriptors
* over the Wayland protocol, so we send them one by one.
*/
extern const struct wl_interface android_wlegl_handle_interface;
#endif
#ifndef ANDROID_WLEGL_SERVER_BUFFER_HANDLE_INTERFACE
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_INTERFACE
/**
* @page page_iface_android_wlegl_server_buffer_handle android_wlegl_server_buffer_handle
* @section page_iface_android_wlegl_server_buffer_handle_desc Description
*
* On creation a server_side_buffer object will immediately send
* the "buffer_fd" and "buffer_ints" events needed by the client to
* reference the gralloc buffer, followed by the "buffer" event carrying
* the wl_buffer object.
* @section page_iface_android_wlegl_server_buffer_handle_api API
* See @ref iface_android_wlegl_server_buffer_handle.
*/
/**
* @defgroup iface_android_wlegl_server_buffer_handle The android_wlegl_server_buffer_handle interface
*
* On creation a server_side_buffer object will immediately send
* the "buffer_fd" and "buffer_ints" events needed by the client to
* reference the gralloc buffer, followed by the "buffer" event carrying
* the wl_buffer object.
*/
extern const struct wl_interface android_wlegl_server_buffer_handle_interface;
#endif
#ifndef ANDROID_WLEGL_ERROR_ENUM
#define ANDROID_WLEGL_ERROR_ENUM
enum android_wlegl_error {
ANDROID_WLEGL_ERROR_BAD_HANDLE = 0,
ANDROID_WLEGL_ERROR_BAD_VALUE = 1,
};
#endif /* ANDROID_WLEGL_ERROR_ENUM */
#ifndef ANDROID_WLEGL_ERROR_ENUM_IS_VALID
#define ANDROID_WLEGL_ERROR_ENUM_IS_VALID
/**
* @ingroup iface_android_wlegl
* Validate a android_wlegl error value.
*
* @return true on success, false on error.
* @ref android_wlegl_error
*/
static inline bool
android_wlegl_error_is_valid(uint32_t value, uint32_t version) {
switch (value) {
case ANDROID_WLEGL_ERROR_BAD_HANDLE:
return version >= 1;
case ANDROID_WLEGL_ERROR_BAD_VALUE:
return version >= 1;
default:
return false;
}
}
#endif /* ANDROID_WLEGL_ERROR_ENUM_IS_VALID */
/**
* @ingroup iface_android_wlegl
* @struct android_wlegl_interface
*/
struct android_wlegl_interface {
/**
* Create an Android native_handle_t object
*
* This creator method initialises the native_handle_t object
* with everything except the file descriptors, which have to be
* submitted separately.
* @param ints an array of int32_t
*/
void (*create_handle)(struct wl_client *client,
struct wl_resource *resource,
uint32_t id,
int32_t num_fds,
struct wl_array *ints);
/**
* Create a wl_buffer from the native handle
*
* Pass the Android native_handle_t to the server and attach it
* to the new wl_buffer object.
*
* The android_wlegl_handle object must be destroyed immediately
* after this request.
*/
void (*create_buffer)(struct wl_client *client,
struct wl_resource *resource,
uint32_t id,
int32_t width,
int32_t height,
int32_t stride,
int32_t format,
int32_t usage,
struct wl_resource *native_handle);
/**
* @since 2
*/
void (*get_server_buffer_handle)(struct wl_client *client,
struct wl_resource *resource,
uint32_t id,
int32_t width,
int32_t height,
int32_t format,
int32_t usage);
};
/**
* @ingroup iface_android_wlegl
*/
#define ANDROID_WLEGL_CREATE_HANDLE_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl
*/
#define ANDROID_WLEGL_CREATE_BUFFER_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl
*/
#define ANDROID_WLEGL_GET_SERVER_BUFFER_HANDLE_SINCE_VERSION 2
#ifndef ANDROID_WLEGL_HANDLE_ERROR_ENUM
#define ANDROID_WLEGL_HANDLE_ERROR_ENUM
enum android_wlegl_handle_error {
ANDROID_WLEGL_HANDLE_ERROR_TOO_MANY_FDS = 0,
};
#endif /* ANDROID_WLEGL_HANDLE_ERROR_ENUM */
#ifndef ANDROID_WLEGL_HANDLE_ERROR_ENUM_IS_VALID
#define ANDROID_WLEGL_HANDLE_ERROR_ENUM_IS_VALID
/**
* @ingroup iface_android_wlegl_handle
* Validate a android_wlegl_handle error value.
*
* @return true on success, false on error.
* @ref android_wlegl_handle_error
*/
static inline bool
android_wlegl_handle_error_is_valid(uint32_t value, uint32_t version) {
switch (value) {
case ANDROID_WLEGL_HANDLE_ERROR_TOO_MANY_FDS:
return version >= 1;
default:
return false;
}
}
#endif /* ANDROID_WLEGL_HANDLE_ERROR_ENUM_IS_VALID */
/**
* @ingroup iface_android_wlegl_handle
* @struct android_wlegl_handle_interface
*/
struct android_wlegl_handle_interface {
/**
*/
void (*add_fd)(struct wl_client *client,
struct wl_resource *resource,
int32_t fd);
/**
*/
void (*destroy)(struct wl_client *client,
struct wl_resource *resource);
};
/**
* @ingroup iface_android_wlegl_handle
*/
#define ANDROID_WLEGL_HANDLE_ADD_FD_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl_handle
*/
#define ANDROID_WLEGL_HANDLE_DESTROY_SINCE_VERSION 1
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_FD 0
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_INTS 1
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER 2
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_LINEAR_LAYOUT 3
/**
* @ingroup iface_android_wlegl_server_buffer_handle
*/
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_FD_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl_server_buffer_handle
*/
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_INTS_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl_server_buffer_handle
*/
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_SINCE_VERSION 1
/**
* @ingroup iface_android_wlegl_server_buffer_handle
*/
#define ANDROID_WLEGL_SERVER_BUFFER_HANDLE_LINEAR_LAYOUT_SINCE_VERSION 3
/**
* @ingroup iface_android_wlegl_server_buffer_handle
* Sends an buffer_fd event to the client owning the resource.
* @param resource_ The client's resource
*/
static inline void
android_wlegl_server_buffer_handle_send_buffer_fd(struct wl_resource *resource_, int32_t fd)
{
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_FD, fd);
}
/**
* @ingroup iface_android_wlegl_server_buffer_handle
* Sends an buffer_ints event to the client owning the resource.
* @param resource_ The client's resource
*/
static inline void
android_wlegl_server_buffer_handle_send_buffer_ints(struct wl_resource *resource_, struct wl_array *ints)
{
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER_INTS, ints);
}
/**
* @ingroup iface_android_wlegl_server_buffer_handle
* Sends an buffer event to the client owning the resource.
* @param resource_ The client's resource
*/
static inline void
android_wlegl_server_buffer_handle_send_buffer(struct wl_resource *resource_, struct wl_resource *buffer, int32_t format, int32_t stride)
{
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_BUFFER, buffer, format, stride);
}
/**
* @ingroup iface_android_wlegl_server_buffer_handle
* Sends an linear_layout event to the client owning the resource.
* @param resource_ The client's resource
*/
static inline void
android_wlegl_server_buffer_handle_send_linear_layout(struct wl_resource *resource_, uint32_t drm_format, uint32_t stride)
{
wl_resource_post_event(resource_, ANDROID_WLEGL_SERVER_BUFFER_HANDLE_LINEAR_LAYOUT, drm_format, stride);
}
#ifdef __cplusplus
}
#endif
#endif
@@ -1,139 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<protocol name="android">
<copyright>
Copyright © 2012 Collabora, Ltd.
Permission to use, copy, modify, distribute, and sell this
software and its documentation for any purpose is hereby granted
without fee, provided that the above copyright notice appear in
all copies and that both that copyright notice and this permission
notice appear in supporting documentation, and that the name of
the copyright holders not be used in advertising or publicity
pertaining to distribution of the software without specific,
written prior permission. The copyright holders make no
representations about the suitability of this software for any
purpose. It is provided "as is" without express or implied
warranty.
THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
THIS SOFTWARE.
</copyright>
<interface name="android_wlegl" version="3">
<description summary="Android EGL graphics buffer support">
Interface used in the Android wrapper libEGL to share
graphics buffers between the server and the client.
</description>
<enum name="error">
<entry name="bad_handle" value="0" />
<entry name="bad_value" value="1" />
</enum>
<request name="create_handle">
<description summary="Create an Android native_handle_t object">
This creator method initialises the native_handle_t object
with everything except the file descriptors, which have to be
submitted separately.
</description>
<arg name="id" type="new_id" interface="android_wlegl_handle" />
<arg name="num_fds" type="int" />
<arg name="ints" type="array" summary="an array of int32_t" />
</request>
<request name="create_buffer">
<description summary="Create a wl_buffer from the native handle">
Pass the Android native_handle_t to the server and attach it
to the new wl_buffer object.
The android_wlegl_handle object must be destroyed immediately
after this request.
</description>
<arg name="id" type="new_id" interface="wl_buffer" />
<arg name="width" type="int" />
<arg name="height" type="int" />
<arg name="stride" type="int" />
<arg name="format" type="int" />
<arg name="usage" type="int" />
<arg name="native_handle" type="object" interface="android_wlegl_handle" />
</request>
<request name="get_server_buffer_handle" since="2">
<arg name="id" type="new_id" interface="android_wlegl_server_buffer_handle"/>
<arg name="width" type="int"/>
<arg name="height" type="int"/>
<arg name="format" type="int"/>
<arg name="usage" type="int"/>
</request>
</interface>
<interface name="android_wlegl_handle" version="1">
<description summary="An Android native_handle_t object">
The Android native_handle_t is a semi-opaque object, that
contains an EGL implementation specific number of int32
values and file descriptors.
We cannot send a variable size array of file descriptors
over the Wayland protocol, so we send them one by one.
</description>
<enum name="error">
<entry name="too_many_fds" value="0" />
</enum>
<request name="add_fd">
<arg name="fd" type="fd" />
</request>
<request name="destroy" type="destructor" />
</interface>
<interface name="android_wlegl_server_buffer_handle" version="3">
<description summary="a server allocated buffer">
On creation a server_side_buffer object will immediately send
the "buffer_fd" and "buffer_ints" events needed by the client to
reference the gralloc buffer, followed by the "buffer" event carrying
the wl_buffer object.
</description>
<event name="buffer_fd">
<arg name="fd" type="fd"/>
</event>
<event name="buffer_ints">
<arg name="ints" type="array"/>
</event>
<event name="buffer">
<description summary="the wl_buffer">
This event will be sent after the ints and all the fds have been sent
</description>
<arg name="buffer" type="new_id" interface="wl_buffer"/>
<arg name="format" type="int"/>
<arg name="stride" type="int"/>
</event>
<event name="linear_layout" since="3">
<description summary="verified single-plane linear allocation">
Optional metadata sent before the buffer event. The first buffer_fd
contains one uncompressed 32-bit RGB plane at byte offset zero.
drm_format is its DRM FourCC and stride is its row pitch in bytes.
The server has verified the layout and allocation bounds using
Android mapper metadata, not inferred them from opaque handle ints.
Absence of this event means the layout is unspecified.
</description>
<arg name="drm_format" type="uint"/>
<arg name="stride" type="uint"/>
</event>
</interface>
</protocol>
+5 -130
View File
@@ -16,7 +16,6 @@
#include <sys/syscall.h> #include <sys/syscall.h>
#include <sys/sysmacros.h> #include <sys/sysmacros.h>
#include <android/log.h> #include <android/log.h>
#include <android/hardware_buffer.h>
#include <wayland-server.h> #include <wayland-server.h>
#include "xdg-shell-server-protocol.h" #include "xdg-shell-server-protocol.h"
@@ -264,8 +263,6 @@ static struct wl_event_source *g_fallback_timer;
static int g_fallback_armed; static int g_fallback_armed;
volatile int g_fps_limit; volatile int g_fps_limit;
/* fps limit -1 (Performance mode without a limit): replaced buffers go back to the client at once instead of once per refresh. */
volatile int g_release_unpaced;
volatile int g_hide_shell; volatile int g_hide_shell;
@@ -373,7 +370,7 @@ static int on_release_timer(int fd, uint32_t mask, void *data) {
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) {
const int limit = g_fps_limit; const int limit = g_fps_limit;
const int64_t interval = limit > 0 ? 1000000000LL / limit : g_refresh_ns; const int64_t interval = limit > 0 ? 1000000000LL / limit : g_refresh_ns;
if (g_release_unpaced || interval <= 0 || g_release_timer_fd < 0) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; } if (interval <= 0 || g_release_timer_fd < 0) { wl_buffer_send_release(buffer); perf_note_release(since_ns); return; }
int64_t now = now_ns(); int64_t now = now_ns();
int64_t at = s->next_release_ns + interval; int64_t at = s->next_release_ns + interval;
int64_t latest = now + interval * (int64_t)(s->releases_pending + 1); int64_t latest = now + interval * (int64_t)(s->releases_pending + 1);
@@ -811,14 +808,10 @@ static uint32_t nominal_refresh_ns(void) {
} }
static int64_t presented_ns(int64_t render_ns) { static int64_t presented_ns(int64_t render_ns) {
int64_t tick = g_tick_vsync_ns; if (!g_tick_vsync_ns || render_ns - g_last_vsync_ns > (int64_t)nominal_refresh_ns() ||
int64_t refresh = (int64_t)nominal_refresh_ns(); render_ns < g_tick_vsync_ns)
if (!tick || render_ns - g_last_vsync_ns > refresh)
return render_ns; return render_ns;
int64_t delta = render_ns - tick; return g_tick_vsync_ns;
if (delta > refresh || -delta > refresh)
return render_ns;
return tick;
} }
static void feedback_present_all(struct wl_list *list, int64_t t) { static void feedback_present_all(struct wl_list *list, int64_t t) {
@@ -1848,121 +1841,7 @@ static void hdr_count_copied(const struct draw_list *dl, const char *reason) {
} }
} }
/*
* Stream mode (the Xbox Cloud Gaming native player, in its own process): no Wayland clients, the scene is one
* picture handed over as AHardwareBuffers (ImageReader images of the decoded video). Each buffer is imported once
* and kept while the reader cycles through its few buffers; the newest frame is the scene, so the screen effects
* and frame generation apply to it as to a game.
*/
#define STREAM_SLOTS 6
static pthread_mutex_t g_stream_lock = PTHREAD_MUTEX_INITIALIZER;
static atomic_int g_stream_on;
static AHardwareBuffer *g_stream_pending;
static struct { AHardwareBuffer *ahb; struct vkp_image *img; uint64_t used; } g_stream_slots[STREAM_SLOTS];
static struct vkp_image *g_stream_img;
static uint64_t g_stream_seq;
static atomic_uint g_stream_frames;
static void stream_forget_all(void) {
vkp_wait_idle();
for (int i = 0; i < STREAM_SLOTS; i++) {
if (g_stream_slots[i].img) vkp_image_destroy(g_stream_slots[i].img);
if (g_stream_slots[i].ahb) AHardwareBuffer_release(g_stream_slots[i].ahb);
g_stream_slots[i].img = NULL; g_stream_slots[i].ahb = NULL; g_stream_slots[i].used = 0;
}
g_stream_img = NULL;
}
/* Compositor thread: the newest handed-over buffer becomes the scene picture. */
static void stream_take(void) {
pthread_mutex_lock(&g_stream_lock);
AHardwareBuffer *ahb = g_stream_pending;
g_stream_pending = NULL;
pthread_mutex_unlock(&g_stream_lock);
if (!ahb) return;
if (!atomic_load(&g_stream_on)) { AHardwareBuffer_release(ahb); return; }
int slot = -1, oldest = 0;
for (int i = 0; i < STREAM_SLOTS; i++) {
if (g_stream_slots[i].ahb == ahb) { slot = i; break; }
if (g_stream_slots[i].used < g_stream_slots[oldest].used) oldest = i;
}
if (slot >= 0) {
AHardwareBuffer_release(ahb); /* the slot keeps its own reference */
} else {
struct vkp_image *img = vkp_image_from_ahb(ahb);
if (!img) {
static int said;
if (!said) { said = 1; droiddeck_log("stream", "a decoded frame could not be imported: nothing to show"); }
AHardwareBuffer_release(ahb);
return;
}
droiddeck_log("stream", "decoded frame buffer imported (%dx%d)", vkp_image_width(img), vkp_image_height(img));
slot = oldest;
if (g_stream_slots[slot].img) {
vkp_wait_idle(); /* the GPU may still read the picture being replaced */
if (g_stream_img == g_stream_slots[slot].img) g_stream_img = NULL;
vkp_image_destroy(g_stream_slots[slot].img);
}
if (g_stream_slots[slot].ahb) AHardwareBuffer_release(g_stream_slots[slot].ahb);
g_stream_slots[slot].ahb = ahb;
g_stream_slots[slot].img = img;
}
g_stream_slots[slot].used = ++g_stream_seq;
g_stream_img = g_stream_slots[slot].img;
atomic_fetch_add(&g_stream_frames, 1);
schedule_render();
}
static void render_stream(void) {
g_dirty = 0;
struct vkp_image *img = g_stream_img;
if (!img) return;
int w = vkp_image_width(img), h = vkp_image_height(img);
if (w != g_scene_w || h != g_scene_h) {
droiddeck_log("stream", "picture %dx%d", w, h);
g_scene_w = w;
g_scene_h = h;
}
struct vkp_draw d = {.img = img, .sx = 0, .sy = 0, .sw = (float)w, .sh = (float)h, .dx = 0, .dy = 0, .dw = w, .dh = h, .blend = 0};
vkp_apply_window_request();
sc_layer_hide();
int r = vkp_render(w, h, &d, 1);
if (r == 0) {
g_stat_frames++;
static int first;
if (!first) { first = 1; droiddeck_log("stream", "first stream frame presented"); }
} else {
static int failed;
if (failed++ % 600 == 0) droiddeck_log("stream", "presenting a stream frame failed (%d, %d times)", r, failed);
}
}
void droiddeck_stream_set(int on) {
atomic_store(&g_stream_on, on ? 1 : 0);
if (g_input_pipe[1] < 0) return;
struct input_msg m = { 21, on ? 1 : 0, 0, 0, 0 };
ssize_t n = write(g_input_pipe[1], &m, sizeof(m));
(void)n;
}
/* Any thread: hands over one decoded frame (acquires its own reference). */
void droiddeck_stream_frame(AHardwareBuffer *ahb) {
if (!ahb || !atomic_load(&g_stream_on) || g_input_pipe[1] < 0) return;
AHardwareBuffer_acquire(ahb);
pthread_mutex_lock(&g_stream_lock);
AHardwareBuffer *dropped = g_stream_pending;
g_stream_pending = ahb;
pthread_mutex_unlock(&g_stream_lock);
if (dropped) { AHardwareBuffer_release(dropped); return; } /* a wake-up is already queued */
struct input_msg m = { 20, 0, 0, 0, 0 };
ssize_t n = write(g_input_pipe[1], &m, sizeof(m));
(void)n;
}
unsigned droiddeck_stream_frames(void) { return atomic_load(&g_stream_frames); }
static void render_scene(void) { static void render_scene(void) {
if (atomic_load(&g_stream_on)) { render_stream(); return; }
struct draw_list dl = {0}; struct draw_list dl = {0};
struct surface *s; struct surface *s;
int w, h; int w, h;
@@ -3122,8 +3001,6 @@ static int on_input_readable(int fd, uint32_t mask, void *data) {
break; break;
case 10: break; case 10: break;
case 11: axis_event(m.p1, m.p2); break; case 11: axis_event(m.p1, m.p2); break;
case 20: stream_take(); break;
case 21: if (!m.p1) stream_forget_all(); schedule_render(); break;
default: deliver_pointer(&m); break; default: deliver_pointer(&m); break;
} }
} }
@@ -3390,9 +3267,7 @@ int droiddeck_wayland_run(void) {
wl_global_create(display, &wl_output_interface, 4, NULL, bind_output); wl_global_create(display, &wl_output_interface, 4, NULL, bind_output);
wl_global_create(display, &xdg_wm_base_interface, 1, NULL, bind_xdg_wm_base); wl_global_create(display, &xdg_wm_base_interface, 1, NULL, bind_xdg_wm_base);
if (vkp_dmabuf_supported()) wl_global_create(display, &zwp_linux_dmabuf_v1_interface, 4, NULL, bind_dmabuf);
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, &wl_seat_interface, 9, NULL, bind_seat);
wl_global_create(display, &banner_desktop_v1_interface, 1, NULL, bind_desktop); wl_global_create(display, &banner_desktop_v1_interface, 1, NULL, bind_desktop);
wl_global_create(display, &wp_presentation_interface, 2, NULL, bind_presentation); wl_global_create(display, &wp_presentation_interface, 2, NULL, bind_presentation);
@@ -61,6 +61,3 @@ extern volatile int g_no_render_node;
COMPOSITOR_INTERNAL extern dev_t g_main_device; COMPOSITOR_INTERNAL extern dev_t g_main_device;
COMPOSITOR_INTERNAL void bind_dmabuf(struct wl_client *c, void *data, uint32_t ver, uint32_t id); COMPOSITOR_INTERNAL void bind_dmabuf(struct wl_client *c, void *data, uint32_t ver, uint32_t id);
/* ---- wl_android_buffer.c */
COMPOSITOR_INTERNAL void droiddeck_android_wlegl_init(struct wl_display *display);
@@ -1,47 +0,0 @@
#ifndef VK_EXTERNAL_IMAGE_SYNC_H
#define VK_EXTERNAL_IMAGE_SYNC_H
#include <vulkan/vulkan.h>
struct vkp_external_client_barrier_pair {
VkImageMemoryBarrier acquire;
VkImageMemoryBarrier release;
};
static inline int vkp_is_external_client_image(int dmabuf, int blit_dst) {
return dmabuf && !blit_dst;
}
/* Client-owned dma-bufs, including AHardwareBuffers, live in GENERAL while
* FOREIGN owns them. Layer pool dma-bufs are destinations with a separate
* acquire/release lifecycle and must never take this source-image path. */
static inline int vkp_external_client_barrier_pair(
VkImage image, uint32_t queue_family, int dmabuf, int blit_dst,
struct vkp_external_client_barrier_pair *pair) {
if (!vkp_is_external_client_image(dmabuf, blit_dst) || !pair) return 0;
const VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
pair->acquire = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.oldLayout = VK_IMAGE_LAYOUT_GENERAL,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
.dstQueueFamilyIndex = queue_family,
.image = image,
.subresourceRange = range,
.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT,
};
pair->release = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER,
.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL,
.srcQueueFamilyIndex = queue_family,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT,
.image = image,
.subresourceRange = range,
.srcAccessMask = VK_ACCESS_MEMORY_READ_BIT,
};
return 1;
}
#endif
+1 -1
View File
@@ -21,7 +21,7 @@
X(BindImageMemory) X(DestroyImage) X(FreeMemory) X(AcquireNextImageKHR) \ X(BindImageMemory) X(DestroyImage) X(FreeMemory) X(AcquireNextImageKHR) \
X(ResetCommandBuffer) X(BeginCommandBuffer) X(CmdPipelineBarrier) X(CmdBlitImage) \ X(ResetCommandBuffer) X(BeginCommandBuffer) X(CmdPipelineBarrier) X(CmdBlitImage) \
X(EndCommandBuffer) X(ResetFences) X(QueueSubmit) X(QueuePresentKHR) X(WaitForFences) \ X(EndCommandBuffer) X(ResetFences) X(QueueSubmit) X(QueuePresentKHR) X(WaitForFences) \
X(QueueWaitIdle) X(GetMemoryFdPropertiesKHR) X(GetAndroidHardwareBufferPropertiesANDROID) \ X(QueueWaitIdle) X(GetMemoryFdPropertiesKHR) \
X(GetImageSubresourceLayout) X(MapMemory) X(UnmapMemory) X(CmdClearColorImage) \ X(GetImageSubresourceLayout) X(MapMemory) X(UnmapMemory) X(CmdClearColorImage) \
\ \
X(CreateShaderModule) X(DestroyShaderModule) X(CreatePipelineLayout) X(DestroyPipelineLayout) \ X(CreateShaderModule) X(DestroyShaderModule) X(CreatePipelineLayout) X(DestroyPipelineLayout) \
+41 -228
View File
@@ -1,7 +1,6 @@
#define _POSIX_C_SOURCE 200809L #define _POSIX_C_SOURCE 200809L
#include "vk_present.h" #include "vk_present.h"
#include "vk_loader.h" #include "vk_loader.h"
#include "vk_external_image_sync.h"
#include "sc_layer.h" #include "sc_layer.h"
#include "effects_chain.h" #include "effects_chain.h"
#include "cardboard.h" #include "cardboard.h"
@@ -20,7 +19,6 @@
#include <time.h> #include <time.h>
#include <pthread.h> #include <pthread.h>
#include <android/log.h> #include <android/log.h>
#include <android/hardware_buffer.h>
#define TAG "DroidDeckWayland" #define TAG "DroidDeckWayland"
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__) #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
@@ -38,18 +36,15 @@ struct vkp_image {
int in_general; int in_general;
VkFormat fmt; VkFormat fmt;
int sampled; int sampled;
AHardwareBuffer *android_buffer;
}; };
static ANativeWindow *g_window; static ANativeWindow *g_window;
static int g_ahb_import;
static char *g_driver_path, *g_library_name, *g_native_lib_dir; static char *g_driver_path, *g_library_name, *g_native_lib_dir;
static int g_dev_state; static int g_dev_state;
static VkInstance g_inst; static VkInstance g_inst;
static VkPhysicalDevice g_pd; static VkPhysicalDevice g_pd;
static VkDevice g_dev; static VkDevice g_dev;
static VkQueue g_queue; static VkQueue g_queue;
static int g_dmabuf_supported;
static uint32_t g_qfam; static uint32_t g_qfam;
static VkCommandPool g_pool; static VkCommandPool g_pool;
#define MAX_PRESENTS (1 + VKP_FG_MAX_GENERATIONS) #define MAX_PRESENTS (1 + VKP_FG_MAX_GENERATIONS)
@@ -464,26 +459,17 @@ static int dev_init(void) {
} }
g_vk.GetPhysicalDeviceMemoryProperties(g_pd, &g_memprops); g_vk.GetPhysicalDeviceMemoryProperties(g_pd, &g_memprops);
static const char *const import_exts[4] = {"VK_KHR_external_memory_fd", "VK_EXT_external_memory_dma_buf", const char *dev_exts[7] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME, "VK_KHR_external_memory_fd",
"VK_EXT_image_drm_format_modifier", "VK_KHR_image_format_list"}; "VK_EXT_external_memory_dma_buf", "VK_EXT_image_drm_format_modifier",
const char *dev_exts[10] = {VK_KHR_SWAPCHAIN_EXTENSION_NAME}; "VK_KHR_image_format_list", NULL, NULL};
uint32_t n_dev_exts = 1; uint32_t n_dev_exts = 5;
uint32_t ne = 0; uint32_t ne = 0;
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, NULL); g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, NULL);
VkExtensionProperties *exts = calloc(ne ? ne : 1, sizeof(*exts)); VkExtensionProperties *exts = calloc(ne ? ne : 1, sizeof(*exts));
if (!exts) { g_dev_state = -1; return -1; }
g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, exts); g_vk.EnumerateDeviceExtensionProperties(g_pd, NULL, &ne, exts);
/* Only what the driver has: the system driver lacks the dma-buf ones, which the cloud player and for (unsigned i = 0; i < 5; i++)
* android_wlegl clients never need. */ if (!has_ext(exts, ne, dev_exts[i]))
g_dmabuf_supported = 1; LOGE("present: driver MISSING %s (dmabuf import will fail)", dev_exts[i]);
for (unsigned i = 0; i < 4; i++) {
if (has_ext(exts, ne, import_exts[i])) {
dev_exts[n_dev_exts++] = import_exts[i];
} else {
LOGE("present: driver MISSING %s (dmabuf import will fail)", import_exts[i]);
if (i < 3) g_dmabuf_supported = 0;
}
}
int want_hdr_md = 0; int want_hdr_md = 0;
if (droiddeck_color_requested()) { if (droiddeck_color_requested()) {
want_hdr_md = has_ext(exts, ne, VK_EXT_HDR_METADATA_EXTENSION_NAME); want_hdr_md = has_ext(exts, ne, VK_EXT_HDR_METADATA_EXTENSION_NAME);
@@ -491,14 +477,6 @@ static int dev_init(void) {
} }
const int want_sem_fd = has_ext(exts, ne, VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME); const int want_sem_fd = has_ext(exts, ne, VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME);
if (want_sem_fd) dev_exts[n_dev_exts++] = VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME; if (want_sem_fd) dev_exts[n_dev_exts++] = VK_KHR_EXTERNAL_SEMAPHORE_FD_EXTENSION_NAME;
/* The cloud player's decoded frames (vkp_image_from_ahb) and android_wlegl clients
* (vkp_image_from_android_buffer) arrive as AHardwareBuffers. */
g_ahb_import = has_ext(exts, ne, VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME) &&
has_ext(exts, ne, VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME);
if (g_ahb_import) {
dev_exts[n_dev_exts++] = VK_ANDROID_EXTERNAL_MEMORY_ANDROID_HARDWARE_BUFFER_EXTENSION_NAME;
dev_exts[n_dev_exts++] = VK_EXT_QUEUE_FAMILY_FOREIGN_EXTENSION_NAME;
}
free(exts); free(exts);
float prio = 1.0f; float prio = 1.0f;
@@ -928,107 +906,12 @@ struct vkp_image *vkp_image_from_dmabuf(int fd, uint32_t drm_format, uint64_t mo
return vkp_image_import_dmabuf(fd, drm_format, modifier, w, h, stride, offset, 0); return vkp_image_import_dmabuf(fd, drm_format, modifier, w, h, stride, offset, 0);
} }
/* Return client sources to FOREIGN after their final read. The consuming paths int vkp_image_is_dmabuf(const struct vkp_image *img) { return img && img->dmabuf && !img->blit_dst; }
* wait for our fence before Wayland can release an ordinary dma-buf or an
* android_wlegl AHardwareBuffer. Producer-fence synchronization is separate from
* these image-layout and ownership transfers. */
static void release_external_client_image(VkCommandBuffer cmd, struct vkp_image *img) {
struct vkp_external_client_barrier_pair pair;
if (!img || !vkp_external_client_barrier_pair(
img->image, g_qfam, img->dmabuf, img->blit_dst, &pair))
return;
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &pair.release);
}
static void release_external_client_draws(VkCommandBuffer cmd, const struct vkp_draw *draws, int count) {
for (int i = 0; i < count; i++) {
int seen = 0;
for (int j = 0; j < i; j++) if (draws[j].img == draws[i].img) { seen = 1; break; }
if (!seen) release_external_client_image(cmd, draws[i].img);
}
}
int vkp_image_is_dmabuf(const struct vkp_image *img) {
return img && vkp_is_external_client_image(img->dmabuf, img->blit_dst);
}
int vkp_android_buffer_supported(void) {
return dev_init() == 0 && g_ahb_import && g_vk.GetAndroidHardwareBufferPropertiesANDROID != NULL;
}
int vkp_dmabuf_supported(void) {
return dev_init() == 0 && g_dmabuf_supported;
}
struct vkp_image *vkp_image_from_android_buffer(AHardwareBuffer *buffer) {
if (!buffer || !vkp_android_buffer_supported()) return NULL;
AHardwareBuffer_Desc desc;
AHardwareBuffer_describe(buffer, &desc);
if (!desc.width || !desc.height || desc.layers != 1 ||
(desc.usage & (AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT | AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE)) ||
!(desc.usage & AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE)) return NULL;
VkAndroidHardwareBufferFormatPropertiesANDROID format = {
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID};
VkAndroidHardwareBufferPropertiesANDROID props = {
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID, .pNext = &format};
VkResult result = g_vk.GetAndroidHardwareBufferPropertiesANDROID(g_dev, buffer, &props);
if (result != VK_SUCCESS ||
(format.format != VK_FORMAT_R8G8B8A8_UNORM && format.format != VK_FORMAT_R8G8B8A8_SRGB &&
format.format != VK_FORMAT_B8G8R8A8_UNORM && format.format != VK_FORMAT_B8G8R8A8_SRGB) ||
!props.memoryTypeBits ||
!(format.formatFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT)) {
LOGE("android_wlegl: unsupported Android buffer import (%s, format %d)",
vk_result_name(result), format.format);
return NULL;
}
struct vkp_image *img = calloc(1, sizeof(*img));
if (!img) return NULL;
img->w = (int)desc.width; img->h = (int)desc.height;
img->fmt = format.format; img->dmabuf = 1;
const VkFormatFeatureFlags sampled = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT |
VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
img->sampled = (format.formatFeatures & sampled) == sampled;
VkExternalMemoryImageCreateInfo external = {
.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID};
VkImageCreateInfo create = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = &external,
.imageType = VK_IMAGE_TYPE_2D, .format = img->fmt,
.extent = {desc.width, desc.height, 1}, .mipLevels = 1, .arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | (img->sampled ? VK_IMAGE_USAGE_SAMPLED_BIT : 0),
.sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
result = g_vk.CreateImage(g_dev, &create, NULL, &img->image);
if (result != VK_SUCCESS) goto fail;
/* AHB image requirements are not queryable before binding. The AHB query supplies them. */
uint32_t memory_type = 0;
while (!(props.memoryTypeBits & (1u << memory_type))) memory_type++;
VkImportAndroidHardwareBufferInfoANDROID import = {
.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, .buffer = buffer};
VkMemoryDedicatedAllocateInfo dedicated = {
.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
.pNext = &import, .image = img->image};
VkMemoryAllocateInfo allocate = {
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .pNext = &dedicated,
.allocationSize = props.allocationSize, .memoryTypeIndex = memory_type};
result = g_vk.AllocateMemory(g_dev, &allocate, NULL, &img->mem);
if (result != VK_SUCCESS) goto fail;
result = g_vk.BindImageMemory(g_dev, img->image, img->mem, 0);
if (result != VK_SUCCESS) goto fail;
AHardwareBuffer_acquire(buffer);
img->android_buffer = buffer;
return img;
fail:
LOGE("android_wlegl: Vulkan buffer import failed: %s", vk_result_name(result));
vkp_image_destroy(img);
return NULL;
}
struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t modifier, int w, int h, struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t modifier, int w, int h,
uint32_t stride, uint32_t offset, int as_blit_dst) { uint32_t stride, uint32_t offset, int as_blit_dst) {
if (modifier == MOD_INVALID || w <= 0 || h <= 0) return NULL; if (modifier == MOD_INVALID || w <= 0 || h <= 0) return NULL;
if (dev_init() != 0 || !g_dmabuf_supported) return NULL; if (dev_init() != 0) return NULL;
struct vkp_image *img = calloc(1, sizeof(*img)); struct vkp_image *img = calloc(1, sizeof(*img));
if (!img) return NULL; if (!img) return NULL;
@@ -1104,60 +987,6 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
return img; return img;
} }
void vkp_wait_idle(void) {
if (g_dev && g_vk.DeviceWaitIdle) g_vk.DeviceWaitIdle(g_dev);
}
struct vkp_image *vkp_image_from_ahb(AHardwareBuffer *ahb) {
if (!ahb || dev_init() != 0) return NULL;
if (!g_ahb_import || !g_vk.GetAndroidHardwareBufferPropertiesANDROID) {
static int said;
if (!said) { said = 1; LOGE("ahb: the driver cannot import AHardwareBuffers (VK_ANDROID_external_memory_android_hardware_buffer)"); }
return NULL;
}
AHardwareBuffer_Desc desc;
AHardwareBuffer_describe(ahb, &desc);
VkAndroidHardwareBufferFormatPropertiesANDROID fp = {
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID};
VkAndroidHardwareBufferPropertiesANDROID props = {
.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID, .pNext = &fp};
VkResult pr = g_vk.GetAndroidHardwareBufferPropertiesANDROID(g_dev, ahb, &props);
if (pr != VK_SUCCESS || fp.format == VK_FORMAT_UNDEFINED) {
LOGE("ahb: %ux%u format %u: properties %s, Vulkan format %d", desc.width, desc.height, desc.format,
vk_result_name(pr), (int)fp.format);
return NULL;
}
struct vkp_image *img = calloc(1, sizeof(*img));
if (!img) return NULL;
img->w = (int)desc.width; img->h = (int)desc.height; img->dmabuf = 1; img->fmt = fp.format; img->sampled = 1;
VkExternalMemoryImageCreateInfo ext = {
.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO,
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID};
VkImageCreateInfo ici = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = &ext,
.imageType = VK_IMAGE_TYPE_2D, .format = fp.format, .extent = {desc.width, desc.height, 1},
.mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_OPTIMAL,
.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
VkResult cr = g_vk.CreateImage(g_dev, &ici, NULL, &img->image);
if (cr != VK_SUCCESS) { LOGE("ahb: vkCreateImage %ux%u -> %s", desc.width, desc.height, vk_result_name(cr)); free(img); return NULL; }
int idx = -1;
for (int i = 0; i < 32; i++) if (props.memoryTypeBits & (1u << i)) { idx = i; break; }
VkImportAndroidHardwareBufferInfoANDROID imp = {
.sType = VK_STRUCTURE_TYPE_IMPORT_ANDROID_HARDWARE_BUFFER_INFO_ANDROID, .buffer = ahb};
VkMemoryDedicatedAllocateInfo ded = {.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO,
.pNext = &imp, .image = img->image};
VkMemoryAllocateInfo mai = {.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .pNext = &ded,
.allocationSize = props.allocationSize, .memoryTypeIndex = (uint32_t)(idx < 0 ? 0 : idx)};
VkResult mr = idx < 0 ? VK_ERROR_FEATURE_NOT_PRESENT : g_vk.AllocateMemory(g_dev, &mai, NULL, &img->mem);
if (mr != VK_SUCCESS || g_vk.BindImageMemory(g_dev, img->image, img->mem, 0) != VK_SUCCESS) {
LOGE("ahb: importing %ux%u -> %s", desc.width, desc.height, vk_result_name(mr));
if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL);
g_vk.DestroyImage(g_dev, img->image, NULL); free(img); return NULL;
}
return img;
}
static int shm_sampled(void) { static int shm_sampled(void) {
static int known; static int known;
if (!known) { if (!known) {
@@ -1231,7 +1060,6 @@ void vkp_image_destroy(struct vkp_image *img) {
if (img->image) g_vk.DestroyImage(g_dev, img->image, NULL); if (img->image) g_vk.DestroyImage(g_dev, img->image, NULL);
if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL); if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL);
} }
if (img->android_buffer) AHardwareBuffer_release(img->android_buffer);
free(img); free(img);
} }
@@ -1276,14 +1104,11 @@ static int draw_to_scene_blit(const struct vkp_draw *d, int scene_w, int scene_h
static void record_draw(VkCommandBuffer cmd, const struct vkp_draw *d, const VkImageBlit *blit, VkImage target, static void record_draw(VkCommandBuffer cmd, const struct vkp_draw *d, const VkImageBlit *blit, VkImage target,
VkFormat target_fmt, int target_w, int target_h, VkFilter filter) { VkFormat target_fmt, int target_w, int target_h, VkFilter filter) {
const struct vkp_image *im = d->img; const struct vkp_image *im = d->img;
const int external_client = vkp_image_is_dmabuf(im);
if (d->blend && im->sampled && if (d->blend && im->sampled &&
blendp_draw(cmd, im->image, im->fmt, im->w, im->h, !external_client, blendp_draw(cmd, im->image, im->fmt, im->w, im->h, !im->dmabuf, target, target_fmt, target_w, target_h,
target, target_fmt, target_w, target_h,
blit) == 0) blit) == 0)
return; return;
g_vk.CmdBlitImage(cmd, im->image, g_vk.CmdBlitImage(cmd, im->image, im->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
external_client ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
target, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, blit, filter); target, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, blit, filter);
} }
@@ -1722,11 +1547,13 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
int seen = 0; int seen = 0;
for (int j = 0; j < i; j++) if (draws[j].img == im) { seen = 1; break; } for (int j = 0; j < i; j++) if (draws[j].img == im) { seen = 1; break; }
if (seen || !im) continue; if (seen || !im) continue;
struct vkp_external_client_barrier_pair pair; if (im->dmabuf) {
if (vkp_external_client_barrier_pair( bars[nb++] = (VkImageMemoryBarrier){
im->image, g_qfam, im->dmabuf, im->blit_dst, &pair)) { .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
bars[nb++] = pair.acquire; .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
} else if (!im->blit_dst && !im->in_general) { .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
.image = im->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
} else if (!im->in_general) {
bars[nb++] = (VkImageMemoryBarrier){ bars[nb++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED, .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .newLayout = VK_IMAGE_LAYOUT_GENERAL,
@@ -1783,7 +1610,6 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
drawn++; drawn++;
} }
release_external_client_draws(cmd, draws, n);
int ngen = 0; int ngen = 0;
VkImage gens[VKP_FG_MAX_GENERATIONS] = {VK_NULL_HANDLE}; VkImage gens[VKP_FG_MAX_GENERATIONS] = {VK_NULL_HANDLE};
VkImage result = scene_img; VkImage result = scene_img;
@@ -1986,7 +1812,7 @@ int vkp_map_draw(const struct vkp_draw *d, int out[8]) {
} }
int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) { int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
if (!src || src->blit_dst || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) { if (!src || !dst || !dst->blit_dst || g_dev_state == -2 || dev_init() != 0) {
if (wait_fd >= 0) close(wait_fd); if (wait_fd >= 0) close(wait_fd);
return -1; return -1;
} }
@@ -1999,21 +1825,17 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
g_vk.BeginCommandBuffer(g_cmd, &bi); g_vk.BeginCommandBuffer(g_cmd, &bi);
struct vkp_external_client_barrier_pair src_pair;
const int src_external = vkp_external_client_barrier_pair(
src->image, g_qfam, src->dmabuf, src->blit_dst, &src_pair);
VkImageMemoryBarrier acq[2] = { VkImageMemoryBarrier acq[2] = {
src_external ? src_pair.acquire : (VkImageMemoryBarrier){ {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .srcQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT}, .image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT},
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, .newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
.image = dst->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}}; .image = dst->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT}};
if (!src_external) { if (!src->dmabuf) {
acq[0].oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED; acq[0].oldLayout = src->in_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_PREINITIALIZED;
acq[0].newLayout = VK_IMAGE_LAYOUT_GENERAL; acq[0].newLayout = VK_IMAGE_LAYOUT_GENERAL;
acq[0].srcAccessMask = VK_ACCESS_HOST_WRITE_BIT; acq[0].srcAccessMask = VK_ACCESS_HOST_WRITE_BIT;
@@ -2027,9 +1849,8 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
.dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}, .dstSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1},
.dstOffsets = {{0, 0, 0}, {bw, bh, 1}}}; .dstOffsets = {{0, 0, 0}, {bw, bh, 1}}};
g_vk.CmdBlitImage(g_cmd, src->image, g_vk.CmdBlitImage(g_cmd, src->image,
src_external ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL, src->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
dst->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST); dst->image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_NEAREST);
release_external_client_image(g_cmd, src);
VkImageMemoryBarrier rel = { VkImageMemoryBarrier rel = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam, .newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = g_qfam,
@@ -2064,7 +1885,7 @@ int vkp_blit_image(struct vkp_image *src, struct vkp_image *dst, int wait_fd) {
static struct vkp_image *g_rb; static struct vkp_image *g_rb;
int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) { int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
if (!src || src->blit_dst || !out || src->w <= 0 || src->h <= 0 || src->w * src->h > max_px || if (!src || !out || src->w <= 0 || src->h <= 0 || src->w * src->h > max_px ||
g_dev_state == -2 || dev_init() != 0) g_dev_state == -2 || dev_init() != 0)
return -1; return -1;
if (g_rb && (g_rb->w != src->w || g_rb->h != src->h)) { vkp_image_destroy(g_rb); g_rb = NULL; } if (g_rb && (g_rb->w != src->w || g_rb->h != src->h)) { vkp_image_destroy(g_rb); g_rb = NULL; }
@@ -2105,15 +1926,11 @@ int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; .flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
g_vk.BeginCommandBuffer(cmd, &bi); g_vk.BeginCommandBuffer(cmd, &bi);
struct vkp_external_client_barrier_pair src_pair;
const int src_external = vkp_external_client_barrier_pair(
src->image, g_qfam, src->dmabuf, src->blit_dst, &src_pair);
VkImageMemoryBarrier acq[2] = { VkImageMemoryBarrier acq[2] = {
src_external ? src_pair.acquire : (VkImageMemoryBarrier){ {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .srcQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT}, .image = src->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT},
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED, {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
@@ -2131,20 +1948,15 @@ int vkp_image_readback(struct vkp_image *src, uint32_t *out, int max_px) {
{.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_GENERAL, {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_GENERAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .newLayout = VK_IMAGE_LAYOUT_GENERAL, .srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = g_rb->image, .subresourceRange = range, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .image = g_rb->image, .subresourceRange = range,
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, .dstAccessMask = VK_ACCESS_HOST_READ_BIT}}; .srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT, .dstAccessMask = VK_ACCESS_HOST_READ_BIT},
uint32_t done_count = 1; {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
if (!src_external) {
done[done_count++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .newLayout = VK_IMAGE_LAYOUT_GENERAL,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .srcQueueFamilyIndex = src->dmabuf ? g_qfam : VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = src->dmabuf ? VK_QUEUE_FAMILY_FOREIGN_EXT : VK_QUEUE_FAMILY_IGNORED,
.image = src->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT}; .image = src->image, .subresourceRange = range, .srcAccessMask = VK_ACCESS_TRANSFER_READ_BIT}};
}
g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, g_vk.CmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT,
VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_HOST_BIT | VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,
0, 0, NULL, 0, NULL, done_count, done); 0, 0, NULL, 0, NULL, 2, done);
release_external_client_image(cmd, src);
g_vk.EndCommandBuffer(cmd); g_vk.EndCommandBuffer(cmd);
VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &cmd}; VkSubmitInfo si = {.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO, .commandBufferCount = 1, .pCommandBuffers = &cmd};
g_vk.ResetFences(g_dev, 1, &g_fence); g_vk.ResetFences(g_dev, 1, &g_fence);
@@ -2216,11 +2028,13 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
int seen = 0; int seen = 0;
for (int j = 0; j < i; j++) if (draws[j].img == im) { seen = 1; break; } for (int j = 0; j < i; j++) if (draws[j].img == im) { seen = 1; break; }
if (seen || !im) continue; if (seen || !im) continue;
struct vkp_external_client_barrier_pair pair; if (im->dmabuf) {
if (vkp_external_client_barrier_pair( bars[nb++] = (VkImageMemoryBarrier){
im->image, g_qfam, im->dmabuf, im->blit_dst, &pair)) { .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_UNDEFINED,
bars[nb++] = pair.acquire; .newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
} else if (!im->blit_dst && !im->in_general) { .srcQueueFamilyIndex = VK_QUEUE_FAMILY_FOREIGN_EXT, .dstQueueFamilyIndex = g_qfam,
.image = im->image, .subresourceRange = range, .dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT};
} else if (!im->in_general) {
bars[nb++] = (VkImageMemoryBarrier){ bars[nb++] = (VkImageMemoryBarrier){
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED, .sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = VK_IMAGE_LAYOUT_PREINITIALIZED,
.newLayout = VK_IMAGE_LAYOUT_GENERAL, .newLayout = VK_IMAGE_LAYOUT_GENERAL,
@@ -2259,7 +2073,6 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
if (vkp_effects_active()) vkp_effects_set_formats(VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM); if (vkp_effects_active()) vkp_effects_set_formats(VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM);
} }
release_external_client_draws(cmd, draws, n);
int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f); int mapped_w = (int)(scene_w * g_map.kx + 0.5f), mapped_h = (int)(scene_h * g_map.ky + 0.5f);
g_pass.rw = scene_w; g_pass.rh = scene_h; g_pass.rw = scene_w; g_pass.rh = scene_h;
g_pass.result = vkp_effects_run(cmd, scene_img, scene_w, scene_h, mapped_w, mapped_h, g_pass.result = vkp_effects_run(cmd, scene_img, scene_w, scene_h, mapped_w, mapped_h,
@@ -2,7 +2,6 @@
#define VK_PRESENT_H #define VK_PRESENT_H
#include <stdint.h> #include <stdint.h>
#include <android/native_window.h> #include <android/native_window.h>
#include <android/hardware_buffer.h>
void vk_present_set_driver(const char *driver_path, const char *library_name, void vk_present_set_driver(const char *driver_path, const char *library_name,
const char *native_lib_dir); const char *native_lib_dir);
@@ -21,10 +20,6 @@ void vkp_output_size(int *w, int *h);
struct vkp_image; struct vkp_image;
int vkp_android_buffer_supported(void);
int vkp_dmabuf_supported(void);
struct vkp_image *vkp_image_from_android_buffer(AHardwareBuffer *buffer);
#define VKP_MOD_LINEAR 0x0000000000000000ULL #define VKP_MOD_LINEAR 0x0000000000000000ULL
#define VKP_MOD_QCOM_COMPRESSED 0x0500000000000001ULL #define VKP_MOD_QCOM_COMPRESSED 0x0500000000000001ULL
#define VKP_MOD_INVALID 0x00ffffffffffffffULL #define VKP_MOD_INVALID 0x00ffffffffffffffULL
@@ -39,9 +34,6 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
int vkp_image_is_dmabuf(const struct vkp_image *img); int vkp_image_is_dmabuf(const struct vkp_image *img);
struct vkp_image *vkp_image_create_shm(int w, int h); struct vkp_image *vkp_image_create_shm(int w, int h);
struct AHardwareBuffer;
struct vkp_image *vkp_image_from_ahb(struct AHardwareBuffer *ahb);
void vkp_wait_idle(void);
void vkp_image_upload_shm(struct vkp_image *img, const void *data, int stride); void vkp_image_upload_shm(struct vkp_image *img, const void *data, int stride);
int vkp_image_width(const struct vkp_image *img); int vkp_image_width(const struct vkp_image *img);
@@ -9,7 +9,6 @@
#include <sys/resource.h> #include <sys/resource.h>
#include <android/log.h> #include <android/log.h>
#include <android/native_window_jni.h> #include <android/native_window_jni.h>
#include <android/hardware_buffer_jni.h>
#include "vk_present.h" #include "vk_present.h"
#include "droiddeck_ext.h" #include "droiddeck_ext.h"
#include "ahb_swapchain.h" #include "ahb_swapchain.h"
@@ -28,13 +27,9 @@ extern int droiddeck_cursor_serial(void);
extern void droiddeck_wayland_send_key(int evdev, int state); extern void droiddeck_wayland_send_key(int evdev, int state);
extern void droiddeck_wayland_send_scene_input(int type, int a, int b); extern void droiddeck_wayland_send_scene_input(int type, int a, int b);
extern void droiddeck_wayland_vsync(int64_t frame_time_ns); extern void droiddeck_wayland_vsync(int64_t frame_time_ns);
extern void droiddeck_stream_set(int on);
extern void droiddeck_stream_frame(AHardwareBuffer *ahb);
extern unsigned droiddeck_stream_frames(void);
extern void droiddeck_wayland_output_resized(void); extern void droiddeck_wayland_output_resized(void);
extern void droiddeck_wayland_set_output_refresh_rate(int mhz); extern void droiddeck_wayland_set_output_refresh_rate(int mhz);
extern volatile int g_fps_limit; extern volatile int g_fps_limit;
extern volatile int g_release_unpaced;
extern volatile int g_hide_shell; extern volatile int g_hide_shell;
extern volatile int g_zero_copy; extern volatile int g_zero_copy;
extern volatile unsigned g_zero_copy_last; extern volatile unsigned g_zero_copy_last;
@@ -575,7 +570,6 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetLookName(JNIEnv *
JNIEXPORT void JNICALL JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFpsLimit(JNIEnv *env, jclass clazz, jint fps) { Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetFpsLimit(JNIEnv *env, jclass clazz, jint fps) {
g_fps_limit = fps > 0 ? fps : 0; g_fps_limit = fps > 0 ? fps : 0;
g_release_unpaced = fps < 0;
__android_log_print(ANDROID_LOG_INFO, TAG, "fps limit %d", fps); __android_log_print(ANDROID_LOG_INFO, TAG, "fps limit %d", fps);
} }
@@ -673,21 +667,3 @@ Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeSetCardboardSpatialP
(*env)->GetFloatArrayRegion(env, pos, 0, 3, p); (*env)->GetFloatArrayRegion(env, pos, 0, 3, p);
vkp_cardboard_set_spatial_pose(m, p, live ? 1 : 0); vkp_cardboard_set_spatial_pose(m, p, live ? 1 : 0);
} }
/* The Xbox Cloud Gaming native player: its decoded frames are the whole scene (no Wayland clients). */
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamMode(JNIEnv *env, jclass clazz, jboolean on) {
droiddeck_stream_set(on ? 1 : 0);
}
JNIEXPORT void JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamFrame(JNIEnv *env, jclass clazz, jobject hardwareBuffer) {
if (!hardwareBuffer) return;
AHardwareBuffer *ahb = AHardwareBuffer_fromHardwareBuffer(env, hardwareBuffer);
if (ahb) droiddeck_stream_frame(ahb);
}
JNIEXPORT jint JNICALL
Java_com_droiddeck_launcher_wayland_WaylandCompositor_nativeStreamFrames(JNIEnv *env, jclass clazz) {
return (jint)droiddeck_stream_frames();
}
@@ -1,216 +0,0 @@
/* android_wlegl buffer import for the existing libhybris Wayland WSI.
* Protocol: Collabora/libhybris, vendored with its license in protocols/wayland-android.xml.
* Native handles are cloned through Android; opaque vendor integers are never interpreted. */
#include "compositor_internal.h"
#include "droiddeck_ext.h"
#include "wayland-android-server-protocol.h"
#include <android/hardware_buffer.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/* Stable native_handle_t ABI, unavailable in the public NDK. */
struct android_native_handle {
int version, num_fds, num_ints;
int data[];
};
struct wire_handle {
struct android_native_handle *handle;
int received;
};
enum { MAX_HANDLE_FDS = 64, MAX_HANDLE_INTS = 256, MAX_BUFFER_SIDE = 8192 };
/* VNDK ABI (not exposed by the NDK): frameworks/native/libs/nativewindow/include/
* vndk/hardware_buffer.h, AHARDWAREBUFFER_CREATE_FROM_HANDLE_METHOD_CLONE = 3.
* Method 1 is not accepted by AHardwareBuffer_createFromHandle. */
enum { CREATE_FROM_HANDLE_CLONE = 3 };
static int (*import_handle)(const AHardwareBuffer_Desc *, const struct android_native_handle *,
int32_t, AHardwareBuffer **);
static const struct android_native_handle *(*native_handle)(const AHardwareBuffer *);
static int valid_description(int32_t width, int32_t height, int32_t stride, int32_t format) {
return width > 0 && height > 0 && width <= MAX_BUFFER_SIDE && height <= MAX_BUFFER_SIDE &&
stride >= width && stride <= MAX_BUFFER_SIDE * 4 &&
(format == 1 || format == 2 || format == 5);
}
static void handle_resource_destroy(struct wl_resource *resource) {
struct wire_handle *wire = wl_resource_get_user_data(resource);
if (!wire) return;
for (int i = 0; i < wire->received; i++) close(wire->handle->data[i]);
free(wire->handle);
free(wire);
}
static void handle_add_fd(struct wl_client *client, struct wl_resource *resource, int32_t fd) {
struct wire_handle *wire = wl_resource_get_user_data(resource);
if (wire->received >= wire->handle->num_fds) {
close(fd);
wl_resource_post_error(resource, ANDROID_WLEGL_HANDLE_ERROR_TOO_MANY_FDS,
"more native handle descriptors than declared");
return;
}
wire->handle->data[wire->received++] = fd;
}
static void handle_destroy(struct wl_client *client, struct wl_resource *resource) {
wl_resource_destroy(resource);
}
static const struct android_wlegl_handle_interface handle_impl = {
.add_fd = handle_add_fd, .destroy = handle_destroy,
};
static void create_handle(struct wl_client *client, struct wl_resource *resource,
uint32_t id, int32_t fds, struct wl_array *ints) {
if (fds < 0 || fds > MAX_HANDLE_FDS || ints->size % sizeof(int32_t) ||
ints->size > MAX_HANDLE_INTS * sizeof(int32_t)) {
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "invalid native handle size");
return;
}
struct wire_handle *wire = calloc(1, sizeof(*wire));
if (!wire) { wl_client_post_no_memory(client); return; }
wire->handle = calloc(1, sizeof(*wire->handle) + (size_t)fds * sizeof(int32_t) + ints->size);
if (!wire->handle) { free(wire); wl_client_post_no_memory(client); return; }
wire->handle->version = sizeof(*wire->handle);
wire->handle->num_fds = fds;
wire->handle->num_ints = (int)(ints->size / sizeof(int32_t));
if (ints->size) memcpy(wire->handle->data + fds, ints->data, ints->size);
struct wl_resource *handle = wl_resource_create(client, &android_wlegl_handle_interface, 1, id);
if (!handle) {
free(wire->handle); free(wire); wl_client_post_no_memory(client); return;
}
wl_resource_set_implementation(handle, &handle_impl, wire, handle_resource_destroy);
}
static void buffer_resource_destroy(struct wl_resource *resource) {
dmabuf_buffer_unref(wl_resource_get_user_data(resource));
}
static struct wl_resource *create_android_buffer(struct wl_client *client, uint32_t id,
AHardwareBuffer *hardware) {
AHardwareBuffer_Desc desc;
AHardwareBuffer_describe(hardware, &desc);
struct vkp_image *image = vkp_image_from_android_buffer(hardware);
if (!image) return NULL;
struct dmabuf_buffer *buffer = calloc(1, sizeof(*buffer));
if (!buffer) { vkp_image_destroy(image); wl_client_post_no_memory(client); return NULL; }
buffer->refs = 1;
buffer->width = (int32_t)desc.width; buffer->height = (int32_t)desc.height;
buffer->format = desc.format == 5 ? DRM_ARGB8888 : desc.format == 2 ? DRM_XBGR8888 : DRM_ABGR8888;
buffer->modifier = MOD_INVALID; /* No DMA-BUF layout was inferred from the native handle. */
buffer->img = image;
for (int i = 0; i < MAX_PLANES; i++) buffer->fd[i] = -1;
struct wl_resource *result = wl_resource_create(client, &wl_buffer_interface, 1, id);
if (!result) { dmabuf_buffer_unref(buffer); wl_client_post_no_memory(client); return NULL; }
wl_resource_set_implementation(result, &dbuf_buffer_impl, buffer, buffer_resource_destroy);
struct client_info *info = client_info_of(client);
if (info) info->dmabuf_buffers++;
return result;
}
static void create_buffer(struct wl_client *client, struct wl_resource *resource, uint32_t id,
int32_t width, int32_t height, int32_t stride, int32_t format,
int32_t usage, struct wl_resource *handle_resource) {
/* Some vendor allocators (Samsung Xclipse) record no stride for GPU-only buffers. The import
* must pass that 0 back unchanged: gralloc validates it against the handle's own value. */
if (!valid_description(width, height, stride ? stride : width, format) ||
!wl_resource_instance_of(handle_resource, &android_wlegl_handle_interface, &handle_impl)) {
droiddeck_log("display", "android_wlegl rejected: %dx%d stride=%d format=%d usage=0x%x",
width, height, stride, format, (uint32_t)usage);
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "invalid Android buffer description");
return;
}
struct wire_handle *wire = wl_resource_get_user_data(handle_resource);
if (wire->received != wire->handle->num_fds || !wire->received) {
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "incomplete native handle");
return;
}
AHardwareBuffer_Desc desc = {
.width = (uint32_t)width, .height = (uint32_t)height, .layers = 1,
.format = (uint32_t)format, .usage = (uint32_t)usage, .stride = (uint32_t)stride};
AHardwareBuffer *hardware = NULL;
int status = import_handle(&desc, wire->handle, CREATE_FROM_HANDLE_CLONE, &hardware);
if (status != 0 || !hardware) {
droiddeck_log("display", "android_wlegl import failed: status=%d %dx%d stride=%d format=%d usage=0x%x fds=%d ints=%d",
status, width, height, stride, format, (uint32_t)usage,
wire->handle->num_fds, wire->handle->num_ints);
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE,
"Android rejected the native handle (status %d)", status);
return;
}
struct wl_resource *buffer = create_android_buffer(client, id, hardware);
AHardwareBuffer_release(hardware);
if (!buffer) wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "Vulkan cannot import this buffer");
}
static void get_server_buffer(struct wl_client *client, struct wl_resource *resource, uint32_t id,
int32_t width, int32_t height, int32_t format, int32_t usage) {
if (!format) format = 1;
if (!valid_description(width, height, width, format)) {
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "invalid buffer allocation request");
return;
}
AHardwareBuffer_Desc desc = {
.width = (uint32_t)width, .height = (uint32_t)height, .layers = 1,
.format = (uint32_t)format,
.usage = (uint32_t)usage | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT};
AHardwareBuffer *hardware = NULL;
if (AHardwareBuffer_allocate(&desc, &hardware) != 0 || !hardware) {
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_VALUE, "Android buffer allocation failed");
return;
}
AHardwareBuffer_describe(hardware, &desc);
const struct android_native_handle *handle = native_handle(hardware);
if (!handle || handle->num_fds < 1 || handle->num_fds > MAX_HANDLE_FDS ||
handle->num_ints < 0 || handle->num_ints > MAX_HANDLE_INTS) {
AHardwareBuffer_release(hardware);
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "invalid allocated native handle");
return;
}
struct wl_resource *buffer = create_android_buffer(client, 0, hardware);
if (!buffer) {
AHardwareBuffer_release(hardware);
wl_resource_post_error(resource, ANDROID_WLEGL_ERROR_BAD_HANDLE, "Vulkan cannot import allocated buffer");
return;
}
struct wl_resource *reply = wl_resource_create(client, &android_wlegl_server_buffer_handle_interface,
wl_resource_get_version(resource), id);
if (!reply) {
wl_resource_destroy(buffer); AHardwareBuffer_release(hardware);
wl_client_post_no_memory(client); return;
}
struct wl_array ints = {.size = (size_t)handle->num_ints * sizeof(int32_t),
.alloc = 0, .data = (void *)(handle->data + handle->num_fds)};
android_wlegl_server_buffer_handle_send_buffer_ints(reply, &ints);
for (int i = 0; i < handle->num_fds; i++)
android_wlegl_server_buffer_handle_send_buffer_fd(reply, handle->data[i]);
/* No linear_layout event: Android's opaque allocation need not be linear. */
android_wlegl_server_buffer_handle_send_buffer(reply, buffer, (int32_t)desc.format, (int32_t)desc.stride);
wl_resource_destroy(reply);
AHardwareBuffer_release(hardware);
}
static const struct android_wlegl_interface wlegl_impl = {
.create_handle = create_handle, .create_buffer = create_buffer,
.get_server_buffer_handle = get_server_buffer,
};
static void bind_android_wlegl(struct wl_client *client, void *data, uint32_t version, uint32_t id) {
struct wl_resource *resource = wl_resource_create(client, &android_wlegl_interface,
version < 3 ? version : 3, id);
if (!resource) { wl_client_post_no_memory(client); return; }
wl_resource_set_implementation(resource, &wlegl_impl, NULL, NULL);
}
void droiddeck_android_wlegl_init(struct wl_display *display) {
if (!vkp_android_buffer_supported()) return;
void *library = dlopen("libnativewindow.so", RTLD_NOW | RTLD_LOCAL);
if (!library) return;
import_handle = dlsym(library, "AHardwareBuffer_createFromHandle");
native_handle = dlsym(library, "AHardwareBuffer_getNativeHandle");
if (!import_handle || !native_handle) { dlclose(library); return; }
/* Keep the platform entry points valid for the compositor's lifetime. */
if (wl_global_create(display, &android_wlegl_interface, 3, NULL, bind_android_wlegl))
droiddeck_log("display", "android_wlegl v3: Android buffer import available");
}
@@ -25,15 +25,6 @@ class App : Application() {
if (android.os.Build.VERSION.SDK_INT >= 28) android.webkit.WebView.setDataDirectorySuffix("xbox") if (android.os.Build.VERSION.SDK_INT >= 28) android.webkit.WebView.setDataDirectorySuffix("xbox")
return return
} }
if (process == "$packageName:xboxcloud") {
if (android.os.Build.VERSION.SDK_INT >= 28) android.webkit.WebView.setDataDirectorySuffix("xboxcloud")
return
}
if (process == "$packageName:xcloudnative") {
// The native cloud player: the stores log and nothing that touches the Linux session.
com.droiddeck.launcher.stores.StoresState.init(this)
return
}
if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic") return if (process == "$packageName:vr_recovery" || process == "$packageName:rgb_diagnostic") return
CrashHandler.install(this) CrashHandler.install(this)
com.droiddeck.launcher.session.QuestExperimental.initialize(this) com.droiddeck.launcher.session.QuestExperimental.initialize(this)
@@ -53,7 +44,6 @@ class App : Application() {
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend) com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.amazon.AmazonBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.itch.ItchBackend) com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.itch.ItchBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend) com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.xbox.XboxBackend)
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.battlenet.BattleNetBackend)
} }
/** Fetches the packs an existing setup already relies on, so the first use after an update does not wait. */ /** Fetches the packs an existing setup already relies on, so the first use after an update does not wait. */
@@ -19,8 +19,6 @@ import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.gpu.LinuxVulkanDriver import com.droiddeck.launcher.gpu.LinuxVulkanDriver
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
import com.droiddeck.launcher.gpu.TurnipDriver import com.droiddeck.launcher.gpu.TurnipDriver
import com.droiddeck.launcher.gpu.QualcommSystemDriver
import com.droiddeck.launcher.gpu.QualcommDriverPackage
import com.droiddeck.launcher.gpu.TurnipReleases import com.droiddeck.launcher.gpu.TurnipReleases
import com.droiddeck.launcher.session.SessionService import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SessionPrefs
@@ -145,10 +143,6 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
} }
linuxRows = LinuxVulkanDriver.optionValues(activity).map { id -> linuxRows = LinuxVulkanDriver.optionValues(activity).map { id ->
if (id.isEmpty()) DriverRow("", activity.getString(R.string.gpu_runtime_default), activity.getString(R.string.drivers_runtime_builtin), false) if (id.isEmpty()) DriverRow("", activity.getString(R.string.gpu_runtime_default), activity.getString(R.string.drivers_runtime_builtin), false)
else if (id == QualcommSystemDriver.ID) DriverRow(id, "System Qualcomm driver", QualcommSystemDriver.label(), false)
else if (QualcommDriverPackage.isRuntimeId(id)) DriverRow(id,
QualcommDriverPackage.label(activity, id), listOf(QualcommDriverPackage.version(activity, id),
activity.getString(R.string.drivers_qualcomm_runtime_display)).filter { it.isNotEmpty() }.joinToString(" · "), false, DriverRow.IMPORTED)
else bundleRow(id, linux = true) ?: DriverRow( else bundleRow(id, linux = true) ?: DriverRow(
id, lm.getDriverName(id), id, lm.getDriverName(id),
listOfNotNull( listOfNotNull(
@@ -163,8 +157,6 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
val td = TurnipDriver(activity) val td = TurnipDriver(activity)
val auto = td.autoId() val auto = td.autoId()
androidRows = buildList { androidRows = buildList {
if (QualcommSystemDriver.detected()) add(DriverRow(TurnipDriver.SYSTEM,
"System Qualcomm driver", QualcommSystemDriver.label(), false))
add(DriverRow( add(DriverRow(
TurnipDriver.AUTO, activity.getString(R.string.gpu_auto_by_gpu), TurnipDriver.AUTO, activity.getString(R.string.gpu_auto_by_gpu),
if (auto == "system") activity.getString(R.string.drivers_system_vulkan) else activity.getString(R.string.drivers_bundled, td.displayName(auto)), if (auto == "system") activity.getString(R.string.drivers_system_vulkan) else activity.getString(R.string.drivers_bundled, td.displayName(auto)),
@@ -439,10 +431,7 @@ internal class DriverMenus(private val activity: Activity, private val ui: Handl
val bundle = DriverBundle.containing(activity, id, linux) val bundle = DriverBundle.containing(activity, id, linux)
when { when {
bundle != null -> useBundle(bundle) bundle != null -> useBundle(bundle)
linux -> { linux -> SessionPrefs.setLinuxDriver(activity, id)
SessionPrefs.setLinuxDriver(activity, id)
if (QualcommSystemDriver.handles(id)) SessionPrefs.setAndroidDriver(activity, TurnipDriver.SYSTEM)
}
else -> SessionPrefs.setAndroidDriver(activity, id) else -> SessionPrefs.setAndroidDriver(activity, id)
} }
pairModeOpen = false pairModeOpen = false
@@ -91,7 +91,7 @@ class FrontEndActivity : ComponentActivity() {
private val components = ComponentsMenu(this, ui) private val components = ComponentsMenu(this, ui)
private val decky = DeckyMenu(this, ui) private val decky = DeckyMenu(this, ui)
private val updates = UpdatesMenu(this, ui) private val updates = UpdatesMenu(this, ui)
private val protons = ProtonMenu(this, ui) { !busy && flood == null && pkgStage == null && components.compBusy == null } private val protons = ProtonMenu(this, ui)
private var installed by mutableStateOf<String?>(null) private var installed by mutableStateOf<String?>(null)
private var flood by mutableStateOf<PendingFlood?>(null) private var flood by mutableStateOf<PendingFlood?>(null)
@@ -120,7 +120,7 @@ class FrontEndActivity : ComponentActivity() {
private var glThread by mutableStateOf(true) private var glThread by mutableStateOf(true)
private var noGlError by mutableStateOf(true) private var noGlError by mutableStateOf(true)
private var returnAfterGame by mutableStateOf(true) private var returnAfterGame by mutableStateOf(true)
private var shaderPrecache by mutableStateOf<Boolean?>(null) private var shaderPrecache by mutableStateOf(true)
private var steamRepairQueued by mutableStateOf(false) private var steamRepairQueued by mutableStateOf(false)
private var mangoapp by mutableStateOf(true) private var mangoapp by mutableStateOf(true)
private var steamController by mutableStateOf(SessionPrefs.CONTROLLER_DECK) private var steamController by mutableStateOf(SessionPrefs.CONTROLLER_DECK)
@@ -139,7 +139,6 @@ class FrontEndActivity : ComponentActivity() {
private var pkgPercent by mutableIntStateOf(-1) private var pkgPercent by mutableIntStateOf(-1)
private var desktopInstalled by mutableStateOf(false) private var desktopInstalled by mutableStateOf(false)
private var desktopPresent by mutableStateOf(false) private var desktopPresent by mutableStateOf(false)
private var battleNetInstalled by mutableStateOf(false)
private var offlineAccount by mutableStateOf<String?>(null) private var offlineAccount by mutableStateOf<String?>(null)
private var offline by mutableStateOf(false) private var offline by mutableStateOf(false)
private var showPerformance by mutableStateOf(false) private var showPerformance by mutableStateOf(false)
@@ -153,9 +152,6 @@ class FrontEndActivity : ComponentActivity() {
private var syncFallback by mutableStateOf(true) private var syncFallback by mutableStateOf(true)
private var fsyncFirst by mutableStateOf(false) private var fsyncFirst by mutableStateOf(false)
private var gamescopeRealtime by mutableStateOf(false) private var gamescopeRealtime by mutableStateOf(false)
private var ramCapMb by mutableStateOf(0)
private var zramClient by mutableStateOf(true)
private var vramCapMb by mutableStateOf(0)
private var gpuClockPin by mutableStateOf(false) private var gpuClockPin by mutableStateOf(false)
private var prootNoSeccomp by mutableStateOf(false) private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true) private var prootFastPath by mutableStateOf(true)
@@ -172,11 +168,11 @@ class FrontEndActivity : ComponentActivity() {
private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO) private var downloadSource by mutableStateOf(DownloadSource.MODE_AUTO)
private var downloadMirror by mutableStateOf("") private var downloadMirror by mutableStateOf("")
private var downloadPrefix by mutableStateOf("") private var downloadPrefix by mutableStateOf("")
private var downloadProxy by mutableStateOf("")
private var animationsEnabled by mutableStateOf(true) private var animationsEnabled by mutableStateOf(true)
private var launcherIcon by mutableStateOf(LauncherIcon.DARK) private var launcherIcon by mutableStateOf(LauncherIcon.DARK)
private var gameStoresEnabled by mutableStateOf(true) private var gameStoresEnabled by mutableStateOf(true)
private var gameStoresSpeedTier by mutableStateOf("fast") private var gameStoresSpeedTier by mutableStateOf("fast")
private var storesOpenTab by mutableStateOf(SessionPrefs.STORES_OPEN_LIBRARY)
private var navRequest by mutableStateOf<String?>(null) private var navRequest by mutableStateOf<String?>(null)
private var storesShowMature by mutableStateOf(false) private var storesShowMature by mutableStateOf(false)
private var storesSort by mutableStateOf(SessionPrefs.STORES_SORTS.first()) private var storesSort by mutableStateOf(SessionPrefs.STORES_SORTS.first())
@@ -392,7 +388,6 @@ class FrontEndActivity : ComponentActivity() {
private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE) private var appScale by mutableStateOf(com.droiddeck.launcher.core.AppUiPrefs.DEFAULT_SCALE)
private var hdrOn by mutableStateOf(false) private var hdrOn by mutableStateOf(false)
private var fpsLimit by mutableStateOf(0) private var fpsLimit by mutableStateOf(0)
private var performanceMode by mutableStateOf(false)
private var upscaler by mutableStateOf(0) private var upscaler by mutableStateOf(0)
private var upscaleSharpness by mutableStateOf(75) private var upscaleSharpness by mutableStateOf(75)
private var hdrReason by mutableStateOf<String?>(null) private var hdrReason by mutableStateOf<String?>(null)
@@ -417,10 +412,6 @@ class FrontEndActivity : ComponentActivity() {
private var logsEnabled by mutableStateOf(true) private var logsEnabled by mutableStateOf(true)
private var vacDiagnostics by mutableStateOf(false) private var vacDiagnostics by mutableStateOf(false)
private var agentCommands by mutableStateOf(false) private var agentCommands by mutableStateOf(false)
private var clearCachedApps by mutableStateOf(false)
private var adbPaired by mutableStateOf(false)
private var memoryHud by mutableStateOf(SessionPrefs.MEMORY_HUD_OFF)
private var backgroundAppLimit by mutableStateOf(com.droiddeck.launcher.core.BackgroundAppLimit.OFF)
private var showRoms by mutableStateOf(false) private var showRoms by mutableStateOf(false)
private var homeAppSelected by mutableStateOf(false) private var homeAppSelected by mutableStateOf(false)
private var homeScreenEnabled by mutableStateOf(false) private var homeScreenEnabled by mutableStateOf(false)
@@ -469,13 +460,7 @@ class FrontEndActivity : ComponentActivity() {
} }
private fun launchFlooded(f: PendingFlood) { private fun launchFlooded(f: PendingFlood) {
if (busy || LinuxRuntimeInstaller.isBusy() || protons.protonBusyId != null || if (busy || LinuxRuntimeInstaller.isBusy()) { flood = null; floodProgress = 0f; return }
ProtonExtras.installInProgress || pkgStage != null) {
flood = null
floodProgress = 0f
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
return
}
val signal = com.droiddeck.launcher.ui.Themes.byId(theme).signal val signal = com.droiddeck.launcher.ui.Themes.byId(theme).signal
super.startActivity(f.intent.putExtra(com.droiddeck.launcher.ui.EXTRA_FLOOD, signal.toArgb())) super.startActivity(f.intent.putExtra(com.droiddeck.launcher.ui.EXTRA_FLOOD, signal.toArgb()))
overridePendingTransition(0, 0) overridePendingTransition(0, 0)
@@ -559,12 +544,12 @@ class FrontEndActivity : ComponentActivity() {
} }
startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME) startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
.putExtra(SessionActivity.EXTRA_STEAMVR, steamVr) .putExtra(SessionActivity.EXTRA_STEAMVR, steamVr)
.returnTo(returnHome) .putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
return true return true
} }
return startSession(Intent(this, SessionActivity::class.java) return startSession(Intent(this, SessionActivity::class.java)
.returnTo(returnHome) .putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
.apply { .apply {
if (game.gameIdString == com.droiddeck.launcher.gpu.SteamVr.APP_ID) { if (game.gameIdString == com.droiddeck.launcher.gpu.SteamVr.APP_ID) {
putExtra(SessionActivity.EXTRA_STEAMVR, true) putExtra(SessionActivity.EXTRA_STEAMVR, true)
@@ -575,12 +560,6 @@ class FrontEndActivity : ComponentActivity() {
}, steamSession = true) }, steamSession = true)
} }
private fun Intent.returnTo(returnHome: Boolean): Intent {
val task = taskId
return putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
.apply { if (returnHome) putExtra(SessionActivity.EXTRA_LINK_TASK, task) }
}
private fun launchWithoutSteam(game: Library.SteamGame, returnHome: Boolean): Boolean { private fun launchWithoutSteam(game: Library.SteamGame, returnHome: Boolean): Boolean {
val app = applicationContext val app = applicationContext
Thread({ Thread({
@@ -594,18 +573,16 @@ class FrontEndActivity : ComponentActivity() {
} }
com.droiddeck.launcher.session.NoSteamLaunch.remember(command) com.droiddeck.launcher.session.NoSteamLaunch.remember(command)
val next = Intent(this, SessionActivity::class.java) val next = Intent(this, SessionActivity::class.java)
.returnTo(returnHome) .putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN) .putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
.putExtra(SessionService.EXTRA_PROGRAM, command.program) .putExtra(SessionService.EXTRA_PROGRAM, command.program)
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, command.args.toTypedArray()) .putExtra(SessionService.EXTRA_PROGRAM_ARGS, command.args.toTypedArray())
.putExtra(SessionService.EXTRA_GAME_ID, com.droiddeck.launcher.session.NoSteamLaunch.scope(game))
when { when {
!SessionState.running -> startSessionOrWait(next) !SessionState.running -> startSessionOrWait(next)
SessionState.stopRequested -> android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show() SessionState.stopRequested -> android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
command.program == com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET && handToBattleNet(command.args, returnHome) { pendingSwitch = next } -> {}
SessionState.mode == SessionService.MODE_RUN && SessionState.program == command.program && SessionState.programArgs == command.args -> SessionState.mode == SessionService.MODE_RUN && SessionState.program == command.program && SessionState.programArgs == command.args ->
startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME) startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
.returnTo(returnHome) .putExtra(SessionActivity.EXTRA_RETURN_HOME, returnHome)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
else -> pendingSwitch = next else -> pendingSwitch = next
} }
@@ -700,8 +677,7 @@ class FrontEndActivity : ComponentActivity() {
} }
private fun startSessionOrWait(next: Intent): Boolean { private fun startSessionOrWait(next: Intent): Boolean {
val started = startSession(next, steamSession = next.hasExtra(SessionService.EXTRA_STEAM_URL) || val started = startSession(next, steamSession = next.hasExtra(SessionService.EXTRA_STEAM_URL))
next.getStringExtra(SessionService.EXTRA_PROGRAM) in setOf(com.droiddeck.launcher.session.NoSteamLaunch.PROTON_RUN, com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET))
if (!started && (busy || LinuxRuntimeInstaller.isBusy())) android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show() if (!started && (busy || LinuxRuntimeInstaller.isBusy())) android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return started return started
} }
@@ -766,7 +742,6 @@ class FrontEndActivity : ComponentActivity() {
gameSyncFolder = GameFileSync.folder(this) gameSyncFolder = GameFileSync.folder(this)
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
refreshPhantomStatus() refreshPhantomStatus()
if (!SessionState.running) com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(this)
theme = SessionPrefs.theme(this) theme = SessionPrefs.theme(this)
frameGenLabel = getString(R.string.frame_gen_off) frameGenLabel = getString(R.string.frame_gen_off)
appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this) appScale = com.droiddeck.launcher.core.AppUiPrefs.scale(this)
@@ -780,13 +755,13 @@ class FrontEndActivity : ComponentActivity() {
downloadSource = DownloadSource.mode(this) downloadSource = DownloadSource.mode(this)
downloadMirror = DownloadSource.mirror(this) downloadMirror = DownloadSource.mirror(this)
downloadPrefix = DownloadSource.custom(this) downloadPrefix = DownloadSource.custom(this)
downloadProxy = DownloadSource.proxyHostPort(this)
DownloadSource.probe() DownloadSource.probe()
animationsEnabled = SessionPrefs.animationsEnabled(this) animationsEnabled = SessionPrefs.animationsEnabled(this)
LauncherIcon.repair(this, intent?.component) LauncherIcon.repair(this, intent?.component)
launcherIcon = LauncherIcon.current(this) launcherIcon = LauncherIcon.current(this)
gameStoresEnabled = SessionPrefs.gameStoresEnabled(this) gameStoresEnabled = SessionPrefs.gameStoresEnabled(this)
gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this) gameStoresSpeedTier = SessionPrefs.gameStoresSpeedTier(this)
storesOpenTab = SessionPrefs.storesOpenTab(this)
storesShowMature = SessionPrefs.storesShowMature(this) storesShowMature = SessionPrefs.storesShowMature(this)
storesSort = SessionPrefs.storesSort(this) storesSort = SessionPrefs.storesSort(this)
storesView = SessionPrefs.storesView(this) storesView = SessionPrefs.storesView(this)
@@ -816,7 +791,6 @@ class FrontEndActivity : ComponentActivity() {
offlineAccount = offlineAccount, offline = offline, offlineAccount = offlineAccount, offline = offline,
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled, frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
vacDiagnostics = vacDiagnostics, agentCommands = agentCommands, vacDiagnostics = vacDiagnostics, agentCommands = agentCommands,
clearCachedApps = clearCachedApps, adbPaired = adbPaired, memoryHud = memoryHud, backgroundAppLimit = backgroundAppLimit,
steamGames = steamGames, steamGamesX64 = steamGamesX64, emulators = emulatorList, running = runningLabel, steamGames = steamGames, steamGamesX64 = steamGamesX64, emulators = emulatorList, running = runningLabel,
frameGen = FrameGen.mode(this), frameGen = FrameGen.mode(this),
lossless = lossless, lossless = lossless,
@@ -835,7 +809,6 @@ class FrontEndActivity : ComponentActivity() {
packageStage = pkgStage, packageStage = pkgStage,
packagePercent = pkgPercent, packagePercent = pkgPercent,
sessionRunning = SessionState.running, sessionRunning = SessionState.running,
battleNetInstalled = battleNetInstalled,
backActionsInverted = backActionsInverted, backActionsInverted = backActionsInverted,
buildLabel = BuildConfig.BUILD_LABEL, buildLabel = BuildConfig.BUILD_LABEL,
oscMode = oscMode, oscMode = oscMode,
@@ -848,11 +821,11 @@ class FrontEndActivity : ComponentActivity() {
downloadSource = downloadSource, downloadSource = downloadSource,
downloadMirror = downloadMirror, downloadMirror = downloadMirror,
downloadPrefix = downloadPrefix, downloadPrefix = downloadPrefix,
downloadProxy = downloadProxy,
animationsEnabled = animationsEnabled, animationsEnabled = animationsEnabled,
launcherIcon = launcherIcon, launcherIcon = launcherIcon,
gameStoresEnabled = gameStoresEnabled, gameStoresEnabled = gameStoresEnabled,
gameStoresSpeedTier = gameStoresSpeedTier, gameStoresSpeedTier = gameStoresSpeedTier,
storesOpenTab = storesOpenTab,
navigate = navRequest, navigate = navRequest,
addedGamesArt = addedGamesArt, addedGamesArt = addedGamesArt,
sgdbUserKey = sgdbUserKey, sgdbUserKey = sgdbUserKey,
@@ -924,7 +897,6 @@ class FrontEndActivity : ComponentActivity() {
.putExtra(SessionService.EXTRA_PROGRAM, app.program) .putExtra(SessionService.EXTRA_PROGRAM, app.program)
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, app.args.toTypedArray())) .putExtra(SessionService.EXTRA_PROGRAM_ARGS, app.args.toTypedArray()))
}, },
onBattleNet = { openBattleNet() },
onFlatpakApp = { id, name -> onFlatpakApp = { id, name ->
Library.flatpakNames[id] = name Library.flatpakNames[id] = name
startActivity(Intent(this, SessionActivity::class.java) startActivity(Intent(this, SessionActivity::class.java)
@@ -979,12 +951,6 @@ class FrontEndActivity : ComponentActivity() {
com.droiddeck.launcher.agent.AgentAccess.setCommandsEnabled(this, !com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)) com.droiddeck.launcher.agent.AgentAccess.setCommandsEnabled(this, !com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this))
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this) agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
}, },
onClearCachedApps = { on -> SessionPrefs.setClearCachedApps(this, on); clearCachedApps = on },
onMemoryHud = { value -> SessionPrefs.setMemoryHud(this, value); memoryHud = value },
onBackgroundAppLimit = { limit ->
SessionPrefs.setBackgroundAppLimit(this, limit); backgroundAppLimit = limit
if (limit == com.droiddeck.launcher.core.BackgroundAppLimit.OFF) com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(this)
},
onShareLogs = { onShareLogs = {
SessionLogShare.prepare(this, { SessionLogShare.latest(this) }) { zip -> SessionLogShare.prepare(this, { SessionLogShare.latest(this) }) { zip ->
if (zip == null) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show() if (zip == null) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
@@ -1034,6 +1000,7 @@ class FrontEndActivity : ComponentActivity() {
applyLauncherFullscreen() applyLauncherFullscreen()
}, },
onGameStoresSpeedTier = { tier -> SessionPrefs.setGameStoresSpeedTier(this, tier); gameStoresSpeedTier = tier }, onGameStoresSpeedTier = { tier -> SessionPrefs.setGameStoresSpeedTier(this, tier); gameStoresSpeedTier = tier },
onStoresOpenTab = { tab -> SessionPrefs.setStoresOpenTab(this, tab); storesOpenTab = tab },
onNavigated = { navRequest = null }, onNavigated = { navRequest = null },
onStoresShowMature = { show -> SessionPrefs.setStoresShowMature(this, show); storesShowMature = show }, onStoresShowMature = { show -> SessionPrefs.setStoresShowMature(this, show); storesShowMature = show },
onStoresSort = { sort -> SessionPrefs.setStoresSort(this, sort); storesSort = sort }, onStoresSort = { sort -> SessionPrefs.setStoresSort(this, sort); storesSort = sort },
@@ -1056,10 +1023,6 @@ class FrontEndActivity : ComponentActivity() {
DownloadSource.setCustom(this, prefix) DownloadSource.setCustom(this, prefix)
downloadPrefix = DownloadSource.custom(this) downloadPrefix = DownloadSource.custom(this)
}, },
onDownloadProxy = { value ->
DownloadSource.setProxy(this, value)
downloadProxy = DownloadSource.proxyHostPort(this)
},
onHomeApp = { manageHomeApp() }, onHomeApp = { manageHomeApp() },
onHomeScreen = { on -> onHomeScreen = { on ->
HomeApp.setHomeScreenEnabled(this, on) HomeApp.setHomeScreenEnabled(this, on)
@@ -1301,23 +1264,6 @@ class FrontEndActivity : ComponentActivity() {
} }
} }
override fun onUserInteraction() {
super.onUserInteraction()
com.droiddeck.launcher.ui.Ambient.poke()
}
override fun dispatchTouchEvent(event: android.view.MotionEvent): Boolean {
if (event.actionMasked == android.view.MotionEvent.ACTION_UP || event.actionMasked == android.view.MotionEvent.ACTION_CANCEL) {
com.droiddeck.launcher.ui.Ambient.poke()
}
return super.dispatchTouchEvent(event)
}
override fun dispatchGenericMotionEvent(event: android.view.MotionEvent): Boolean {
com.droiddeck.launcher.ui.Ambient.poke()
return super.dispatchGenericMotionEvent(event)
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean { override fun dispatchKeyEvent(event: KeyEvent): Boolean {
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A) com.droiddeck.launcher.ui.HeldKeys.confirm = event.action == KeyEvent.ACTION_DOWN if (event.keyCode == KeyEvent.KEYCODE_BUTTON_A) com.droiddeck.launcher.ui.HeldKeys.confirm = event.action == KeyEvent.ACTION_DOWN
if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) { if (showComponents && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
@@ -1342,9 +1288,7 @@ class FrontEndActivity : ComponentActivity() {
refreshWifiDiscovery() refreshWifiDiscovery()
com.droiddeck.launcher.stores.StoresState.refresh(this) com.droiddeck.launcher.stores.StoresState.refresh(this)
com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() } com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() }
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = { args -> openBattleNet(args) }
com.droiddeck.launcher.ui.Motion.refresh(this) com.droiddeck.launcher.ui.Motion.refresh(this)
com.droiddeck.launcher.ui.Ambient.poke()
com.droiddeck.launcher.ui.QuitFlood.take()?.let { c -> com.droiddeck.launcher.ui.QuitFlood.take()?.let { c ->
returning = ReturningFlood(c, com.droiddeck.launcher.ui.LaunchOrigin.takeReturn()) returning = ReturningFlood(c, com.droiddeck.launcher.ui.LaunchOrigin.takeReturn())
} }
@@ -1410,7 +1354,6 @@ class FrontEndActivity : ComponentActivity() {
unregisterReceiver(mediaReceiver) unregisterReceiver(mediaReceiver)
ui.removeCallbacks(mediaRefresh) ui.removeCallbacks(mediaRefresh)
com.droiddeck.launcher.stores.StoresState.libraryListener = null com.droiddeck.launcher.stores.StoresState.libraryListener = null
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null
displayManager.unregisterDisplayListener(secondScreenDisplayListener) displayManager.unregisterDisplayListener(secondScreenDisplayListener)
flood = null flood = null
returning = null returning = null
@@ -1604,50 +1547,6 @@ class FrontEndActivity : ComponentActivity() {
desktopPresent = DesktopCatalog.desktopPresent(this) desktopPresent = DesktopCatalog.desktopPresent(this)
} }
private fun openBattleNet(args: List<String> = emptyList()) {
if (protons.protonBusyId != null || ProtonExtras.installInProgress || pkgStage != null) {
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
return
}
val app = applicationContext
Thread({
val full = if (args.firstOrNull() == "--library") args else com.droiddeck.launcher.stores.battlenet.BattleNetClient.library(app) + args
ui.post {
if (isDestroyed) return@post
val next = Intent(this, SessionActivity::class.java)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
.putExtra(SessionService.EXTRA_PROGRAM, com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET)
.putExtra(SessionService.EXTRA_PROGRAM_ARGS, full.toTypedArray())
when {
!SessionState.running -> startSessionOrWait(next)
SessionState.stopRequested -> android.widget.Toast.makeText(this, R.string.game_link_session_busy, android.widget.Toast.LENGTH_LONG).show()
handToBattleNet(full) { pendingSwitch = next } -> {}
else -> pendingSwitch = next
}
}
}, "battlenet-open").start()
}
private fun handToBattleNet(args: List<String>, returnHome: Boolean = false, otherwise: () -> Unit): Boolean {
if (SessionState.mode != SessionService.MODE_RUN || SessionState.program != com.droiddeck.launcher.session.NoSteamLaunch.BATTLENET) return false
val library = args.takeIf { it.firstOrNull() == "--library" }?.getOrNull(1)
val sessionLibrary = SessionState.programArgs.takeIf { it.firstOrNull() == "--library" }?.getOrNull(1)
if (library != null && sessionLibrary != null && library != sessionLibrary) return false
val request = if (library != null) args.drop(2) else args
val app = applicationContext
Thread({
val handed = request.isEmpty() || com.droiddeck.launcher.stores.battlenet.BattleNetClient.request(LinuxRuntime.sessionRoot(app), request)
ui.post {
if (isDestroyed) return@post
if (!handed) otherwise()
else startActivity(Intent(this, SessionActivity::class.java).setAction(SessionService.ACTION_RESUME)
.returnTo(returnHome)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP))
}
}, "battlenet-request").start()
return true
}
private fun launchProgram(path: String) { private fun launchProgram(path: String) {
startActivity(Intent(this, SessionActivity::class.java) startActivity(Intent(this, SessionActivity::class.java)
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN) .putExtra(SessionService.EXTRA_MODE, SessionService.MODE_RUN)
@@ -1713,7 +1612,7 @@ class FrontEndActivity : ComponentActivity() {
ModeSettings( ModeSettings(
mode = mode, resolution = resolution, mode = mode, resolution = resolution,
panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this), panelSize = com.droiddeck.launcher.session.SessionDisplay.panelSize(this),
hdr = hdrOn, hdrReason = hdrReason, fpsLimit = fpsLimit, performanceMode = performanceMode, hdr = hdrOn, hdrReason = hdrReason, fpsLimit = fpsLimit,
upscaler = upscaler, upscaleSharpness = upscaleSharpness, upscaler = upscaler, upscaleSharpness = upscaleSharpness,
gpuDrivers = drivers.summary(), gpuDrivers = drivers.summary(),
touchMode = touchMode, touchMode = touchMode,
@@ -1780,7 +1679,6 @@ class FrontEndActivity : ComponentActivity() {
onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on }, onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on },
onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) }, onGpuDrivers = { openComponents(focusContent = true, tab = com.droiddeck.launcher.ui.GPU_TAB) },
onFpsLimit = { fps -> SessionPrefs.setFpsLimit(this, mode, fps); fpsLimit = fps }, onFpsLimit = { fps -> SessionPrefs.setFpsLimit(this, mode, fps); fpsLimit = fps },
onPerformanceMode = { on -> SessionPrefs.setPerformanceMode(this, mode, on); performanceMode = on },
onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m }, onUpscaler = { m -> SessionPrefs.setUpscaler(this, m); upscaler = m },
onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct }, onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this, pct); upscaleSharpness = pct },
onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t }, onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t },
@@ -1829,7 +1727,7 @@ class FrontEndActivity : ComponentActivity() {
onSteamClientArch = { id -> onSteamClientArch = { id ->
SessionPrefs.setSteamClientArch(this, id) SessionPrefs.setSteamClientArch(this, id)
steamClientArch = id steamClientArch = id
loadShaderPrecache(mode) shaderPrecache = SessionPrefs.shaderPrecache(this)
refresh() refresh()
}, },
onMangoapp = { on -> SessionPrefs.setMangoapp(this, on); mangoapp = on }, onMangoapp = { on -> SessionPrefs.setMangoapp(this, on); mangoapp = on },
@@ -1875,10 +1773,6 @@ class FrontEndActivity : ComponentActivity() {
fsyncFirst = fsyncFirst, fsyncFirst = fsyncFirst,
gamescopeRealtime = gamescopeRealtime, gamescopeRealtime = gamescopeRealtime,
gpuClockPin = gpuClockPin, gpuClockPin = gpuClockPin,
ramCapMb = ramCapMb, vramCapMb = vramCapMb, zramClient = zramClient,
deviceRamMb = (android.app.ActivityManager.MemoryInfo()
.also((getSystemService(ACTIVITY_SERVICE) as android.app.ActivityManager)::getMemoryInfo).totalMem / (1024 * 1024)).toInt(),
ramCapAvailable = com.droiddeck.launcher.core.ZramSupport.supported(),
prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, cursorComposite = cursorComposite, prootNoSeccomp = prootNoSeccomp, prootFastPath = prootFastPath, cursorComposite = cursorComposite,
guestHostname = guestHostname, phantomWarning = phantomWarning, guestHostname = guestHostname, phantomWarning = phantomWarning,
onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on }, onClientOverride = { on -> SessionPrefs.setClientCpusOverride(this, on); clientOverride = on },
@@ -1892,9 +1786,6 @@ class FrontEndActivity : ComponentActivity() {
onFsyncFirst = { on -> SessionPrefs.setFsyncFirst(this, on); fsyncFirst = on }, onFsyncFirst = { on -> SessionPrefs.setFsyncFirst(this, on); fsyncFirst = on },
onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on }, onGamescopeRealtime = { on -> SessionPrefs.setGamescopeRealtime(this, on); gamescopeRealtime = on },
onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on }, onGpuClockPin = { on -> SessionPrefs.setGpuClockPin(this, on); gpuClockPin = on },
onRamCapMb = { mb -> SessionPrefs.setRamCapMb(this, mb); ramCapMb = mb },
onZramClient = { on -> SessionPrefs.setZramClient(this, on); zramClient = on },
onVramCapMb = { mb -> SessionPrefs.setVramCapMb(this, mb); vramCapMb = mb },
onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on }, onProotNoSeccomp = { on -> SessionPrefs.setProotNoSeccomp(this, on); prootNoSeccomp = on },
onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on }, onProotFastPath = { on -> SessionPrefs.setProotFastPath(this, on); prootFastPath = on },
onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on }, onCursorComposite = { on -> SessionPrefs.setCursorComposite(this, on); cursorComposite = on },
@@ -1998,19 +1889,6 @@ class FrontEndActivity : ComponentActivity() {
private var pipAutoEnter by mutableStateOf(false) private var pipAutoEnter by mutableStateOf(false)
private var unfoldedControls by mutableStateOf(false) private var unfoldedControls by mutableStateOf(false)
private var unfoldedControlsWithController by mutableStateOf(false) private var unfoldedControlsWithController by mutableStateOf(false)
private var shaderPrecacheGeneration = 0
private fun loadShaderPrecache(mode: String) {
val generation = ++shaderPrecacheGeneration
shaderPrecache = null
if (mode != SessionService.MODE_STEAM) return
Thread({
val precache = SessionPrefs.shaderPrecache(this)
ui.post {
if (!isDestroyed && generation == shaderPrecacheGeneration) shaderPrecache = precache
}
}, "shader-precache").start()
}
private fun loadModeSettings(mode: String) { private fun loadModeSettings(mode: String) {
pipAutoEnter = SessionPrefs.pipAutoEnter(this) pipAutoEnter = SessionPrefs.pipAutoEnter(this)
@@ -2026,13 +1904,12 @@ class FrontEndActivity : ComponentActivity() {
steamRepairQueued = SteamRepair.queued(this) steamRepairQueued = SteamRepair.queued(this)
mangoapp = SessionPrefs.mangoapp(this) mangoapp = SessionPrefs.mangoapp(this)
returnAfterGame = SessionPrefs.returnAfterGame(this) returnAfterGame = SessionPrefs.returnAfterGame(this)
loadShaderPrecache(mode) shaderPrecache = SessionPrefs.shaderPrecache(this)
steamController = SessionPrefs.steamController(this) steamController = SessionPrefs.steamController(this)
runSteamAtStartup = SessionPrefs.runSteamAtStartup(this) runSteamAtStartup = SessionPrefs.runSteamAtStartup(this)
loadBootMovie() loadBootMovie()
hdrOn = SessionPrefs.hdr(this, mode) hdrOn = SessionPrefs.hdr(this, mode)
fpsLimit = SessionPrefs.fpsLimit(this, mode) fpsLimit = SessionPrefs.fpsLimit(this, mode)
performanceMode = SessionPrefs.performanceMode(this, mode)
upscaler = SessionPrefs.upscaler(this) upscaler = SessionPrefs.upscaler(this)
upscaleSharpness = SessionPrefs.upscaleSharpness(this) upscaleSharpness = SessionPrefs.upscaleSharpness(this)
hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason hdrReason = com.droiddeck.launcher.wayland.HdrSupport.probe(this).reason
@@ -2091,9 +1968,6 @@ class FrontEndActivity : ComponentActivity() {
syncFallback = SessionPrefs.syncFallback(this) syncFallback = SessionPrefs.syncFallback(this)
fsyncFirst = SessionPrefs.fsyncFirst(this) fsyncFirst = SessionPrefs.fsyncFirst(this)
gamescopeRealtime = SessionPrefs.gamescopeRealtime(this) gamescopeRealtime = SessionPrefs.gamescopeRealtime(this)
ramCapMb = SessionPrefs.ramCapMb(this)
zramClient = SessionPrefs.zramClient(this)
vramCapMb = SessionPrefs.vramCapMb(this)
gpuClockPin = SessionPrefs.gpuClockPin(this) gpuClockPin = SessionPrefs.gpuClockPin(this)
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this) prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
prootFastPath = SessionPrefs.prootFastPath(this) prootFastPath = SessionPrefs.prootFastPath(this)
@@ -2114,7 +1988,6 @@ class FrontEndActivity : ComponentActivity() {
addedGamesArt = SessionPrefs.addedGamesArt(this) addedGamesArt = SessionPrefs.addedGamesArt(this)
desktopInstalled = DesktopCatalog.desktopInstalled(this) desktopInstalled = DesktopCatalog.desktopInstalled(this)
desktopPresent = DesktopCatalog.desktopPresent(this) desktopPresent = DesktopCatalog.desktopPresent(this)
battleNetInstalled = com.droiddeck.launcher.runtime.BattleNet.installed(this)
offlineAccount = OfflineMode.account(this) offlineAccount = OfflineMode.account(this)
offline = OfflineMode.enabled(this) offline = OfflineMode.enabled(this)
installed = LinuxRuntimeInstaller.installedVersion(this) installed = LinuxRuntimeInstaller.installedVersion(this)
@@ -2125,10 +1998,6 @@ class FrontEndActivity : ComponentActivity() {
logsEnabled = SessionPrefs.logsEnabled(this) logsEnabled = SessionPrefs.logsEnabled(this)
vacDiagnostics = SessionPrefs.vacDiagnostics(this) vacDiagnostics = SessionPrefs.vacDiagnostics(this)
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this) agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
clearCachedApps = SessionPrefs.clearCachedApps(this)
adbPaired = WirelessAdbFix.hasSavedPairing(this)
memoryHud = SessionPrefs.memoryHud(this)
backgroundAppLimit = SessionPrefs.backgroundAppLimit(this)
runningLabel = if (SessionState.running) when (SessionState.mode) { runningLabel = if (SessionState.running) when (SessionState.mode) {
SessionService.MODE_DESKTOP -> getString(R.string.rail_desktop) SessionService.MODE_DESKTOP -> getString(R.string.rail_desktop)
SessionService.MODE_RUN -> Library.nameForProgram(SessionState.program) SessionService.MODE_RUN -> Library.nameForProgram(SessionState.program)
@@ -2226,7 +2095,6 @@ class FrontEndActivity : ComponentActivity() {
private fun refreshPhantomStatus() { private fun refreshPhantomStatus() {
phantomProcessStatus = PhantomProcessLimit.read(this) phantomProcessStatus = PhantomProcessLimit.read(this)
adbPaired = WirelessAdbFix.hasSavedPairing(this)
phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) { phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
getString( getString(
R.string.phantom_warning, PhantomProcessLimit.title(this, phantomProcessStatus), R.string.phantom_warning, PhantomProcessLimit.title(this, phantomProcessStatus),
@@ -1,8 +1,6 @@
package com.droiddeck.launcher package com.droiddeck.launcher
import android.os.Handler import android.os.Handler
import android.util.Log
import androidx.annotation.VisibleForTesting
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
@@ -10,48 +8,31 @@ import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.ProtonExtras import com.droiddeck.launcher.session.ProtonExtras
import com.droiddeck.launcher.ui.ProtonRow import com.droiddeck.launcher.ui.ProtonRow
import com.droiddeck.launcher.session.SessionState import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.frontend.AutoComponents
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
internal class ProtonMenu( internal class ProtonMenu(private val activity: android.app.Activity, private val ui: android.os.Handler) {
private val activity: android.app.Activity,
private val ui: Handler,
private val idle: () -> Boolean = { true },
) {
var protonRows by mutableStateOf<List<ProtonRow>>(emptyList()) var protonRows by mutableStateOf<List<ProtonRow>>(emptyList())
var protonBusyId by mutableStateOf<String?>(null) var protonBusyId by mutableStateOf<String?>(null)
var protonStage by mutableStateOf<String?>(null) var protonStage by mutableStateOf<String?>(null)
var protonPercent by mutableIntStateOf(-1) var protonPercent by mutableIntStateOf(-1)
private val checking = java.util.concurrent.atomic.AtomicBoolean(false) private val checking = java.util.concurrent.atomic.AtomicBoolean(false)
@VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
{ tool, progress -> ProtonExtras.install(activity, tool, progress) }
fun installProton(id: String, automatic: Boolean = false) { fun installProton(id: String) {
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
if (protonBusyId != null || ProtonExtras.installInProgress || SessionState.running) return if (protonBusyId != null || SessionState.running) return
ProtonExtras.unqueue(activity, tool) ProtonExtras.unqueue(activity, tool)
protonBusyId = id protonBusyId = id
protonStage = activity.getString(R.string.store_starting) protonStage = activity.getString(R.string.store_starting)
protonPercent = -1 protonPercent = -1
Thread({ Thread({
val problem = runCatching { val problem = ProtonExtras.install(activity, tool) { label, value ->
installer(tool) { label, value -> ui.post { protonStage = label; protonPercent = value }
ui.post { protonStage = label; protonPercent = value } }
}
}.getOrElse { it.message ?: it.javaClass.simpleName }
if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false)
ui.post { ui.post {
protonBusyId = null protonBusyId = null
protonStage = null protonStage = null
protonPercent = -1 protonPercent = -1
refreshProtons() refreshProtons()
if (problem != null) { if (problem != null) android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
if (automatic) Log.w("ProtonMenu", "auto-update ${tool.id}: $problem")
else android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
}
if (automatic) ensureAutoUpdates()
} }
}, "install-proton-$id").start() }, "install-proton-$id").start()
} }
@@ -64,7 +45,6 @@ internal class ProtonMenu(
protonPercent = -1 protonPercent = -1
Thread({ Thread({
if (older) ProtonExtras.removeOlder(activity, tool) else ProtonExtras.remove(activity, tool, dir) if (older) ProtonExtras.removeOlder(activity, tool) else ProtonExtras.remove(activity, tool, dir)
if (tool.id == ProtonExtras.OWN && ProtonExtras.installedAll(activity, tool).isEmpty()) ProtonExtras.setDeclined(activity, true)
ui.post { ui.post {
protonBusyId = null protonBusyId = null
protonStage = null protonStage = null
@@ -84,38 +64,7 @@ internal class ProtonMenu(
if (!checking.compareAndSet(false, true)) return if (!checking.compareAndSet(false, true)) return
Thread({ Thread({
val asked = try { ProtonExtras.checkLatest(activity, force) } catch (_: Throwable) { false } finally { checking.set(false) } val asked = try { ProtonExtras.checkLatest(activity, force) } catch (_: Throwable) { false } finally { checking.set(false) }
ui.post { if (asked) ui.post { refreshProtons() }
if (asked) refreshProtons()
ensureAutoUpdates()
}
}, "proton-updates").start() }, "proton-updates").start()
} }
internal fun ensureAutoUpdates(now: Long = System.currentTimeMillis()) {
if (activity.isFinishing || activity.isDestroyed || !idle() || protonBusyId != null ||
ProtonExtras.installInProgress || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) ||
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return
if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) {
protonBusyId = ProtonExtras.OWN
Thread({
ProtonExtras.tidy(activity)
val tidied = ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size <= 1
ui.post {
protonBusyId = null
refreshProtons()
if (tidied) ensureAutoUpdates()
}
}, "proton-tidy").start()
return
}
val attempts = activity.getSharedPreferences("proton-auto-updates", android.content.Context.MODE_PRIVATE)
val (tool, update) = ProtonExtras.tools.firstNotNullOfOrNull { tool ->
val update = ProtonExtras.update(activity, tool) ?: ProtonExtras.missing(activity, tool) ?: return@firstNotNullOfOrNull null
val previous = attempts.getLong("${tool.id}.at", 0L)
if (attempts.getString("${tool.id}.tag", null) != update || now - previous !in 0 until 15L * 60 * 1000) tool to update else null
} ?: return
attempts.edit().putString("${tool.id}.tag", update).putLong("${tool.id}.at", now).apply()
installProton(tool.id, automatic = true)
}
} }
@@ -75,10 +75,8 @@ import com.droiddeck.launcher.input.OnScreenControls
import com.droiddeck.launcher.input.PadBridge import com.droiddeck.launcher.input.PadBridge
import com.droiddeck.launcher.input.PadMouse import com.droiddeck.launcher.input.PadMouse
import com.droiddeck.launcher.input.PadState import com.droiddeck.launcher.input.PadState
import com.droiddeck.launcher.input.ScreenKeys
import com.droiddeck.launcher.input.SteamControllerBle import com.droiddeck.launcher.input.SteamControllerBle
import com.droiddeck.launcher.input.DirectTouchHold import com.droiddeck.launcher.input.DirectTouchHold
import com.droiddeck.launcher.input.GestureTouchStreamGate
import com.droiddeck.launcher.input.PointerGestures import com.droiddeck.launcher.input.PointerGestures
import com.droiddeck.launcher.input.SecondScreenDisplay import com.droiddeck.launcher.input.SecondScreenDisplay
import com.droiddeck.launcher.input.SecondScreenDisplays import com.droiddeck.launcher.input.SecondScreenDisplays
@@ -157,7 +155,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private lateinit var sessionOverlay: ComposeView private lateinit var sessionOverlay: ComposeView
private lateinit var loading: LoadingState private lateinit var loading: LoadingState
private lateinit var hud: PerfHud private lateinit var hud: PerfHud
private lateinit var memoryHud: com.droiddeck.launcher.session.MemoryHud
private var padBridge: PadBridge? = null private var padBridge: PadBridge? = null
private var joyConVr: com.droiddeck.launcher.input.JoyConVr? = null private var joyConVr: com.droiddeck.launcher.input.JoyConVr? = null
private var handCamera: com.droiddeck.launcher.handtracking.HandCamera? = null private var handCamera: com.droiddeck.launcher.handtracking.HandCamera? = null
@@ -201,20 +198,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var gestureConfig = com.droiddeck.launcher.input.TouchGestureConfig() private var gestureConfig = com.droiddeck.launcher.input.TouchGestureConfig()
private var gestureGame: String? = null private var gestureGame: String? = null
private var gestureSettingsOpen by mutableStateOf(false) private var gestureSettingsOpen by mutableStateOf(false)
private var screenKeyPickerOpen by mutableStateOf(false)
private var screenKeyBind: List<Int>? = null
private var screenKeyDir: Int? = null
private var screenKeyTextFocus = false
private var screenKeyEdit by mutableStateOf<com.droiddeck.launcher.input.ScreenKey?>(null)
private var screenLayoutsOpen by mutableStateOf(false)
private var screenKeysShown by mutableStateOf(true)
private var screenLayoutNames by mutableStateOf(listOf<String>())
private var screenKeys: ScreenKeys? = null
private var recognizedGesture by mutableStateOf<TouchscreenGestures.Gesture?>(null) private var recognizedGesture by mutableStateOf<TouchscreenGestures.Gesture?>(null)
private var gesturePointerX = 0f private var gesturePointerX = 0f
private var gesturePointerY = 0f private var gesturePointerY = 0f
private var gesturePointerReady = false private var gesturePointerReady = false
private val gestureTouchStreamGate = GestureTouchStreamGate()
private val clearRecognizedGesture = Runnable { recognizedGesture = null } private val clearRecognizedGesture = Runnable { recognizedGesture = null }
private val gestureKeysDown = mutableSetOf<Int>() private val gestureKeysDown = mutableSetOf<Int>()
private lateinit var scrollTouch: ScrollTouchGestures private lateinit var scrollTouch: ScrollTouchGestures
@@ -283,7 +270,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
} }
} }
private val resumeKeysDown = mutableSetOf<Pair<Int, Int>>() private val resumeKeysDown = mutableSetOf<Pair<Int, Int>>()
private val drawerShortcutKeysDown = mutableSetOf<Pair<Int, Int>>()
private var drawerOpen by mutableStateOf(false) private var drawerOpen by mutableStateOf(false)
private var quitFrom by mutableStateOf<androidx.compose.ui.geometry.Rect?>(null) private var quitFrom by mutableStateOf<androidx.compose.ui.geometry.Rect?>(null)
@@ -294,9 +280,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private var drawerDefaultProton by mutableStateOf<String?>(null) private var drawerDefaultProton by mutableStateOf<String?>(null)
private val drawerComponentMenu by lazy { ComponentsMenu(this, uiHandler) } private val drawerComponentMenu by lazy { ComponentsMenu(this, uiHandler) }
private var drawerGameProfileId by mutableStateOf<Long?>(null) private var drawerGameProfileId by mutableStateOf<Long?>(null)
private fun noSteamSession(): Boolean = SessionState.mode == SessionService.MODE_RUN &&
SessionState.program in setOf(com.droiddeck.launcher.session.NoSteamLaunch.PROTON_RUN, com.droiddeck.launcher.session.NoSteamLaunch.EPIC)
private val drawerGameInventory = GameProfileInventoryCache<Library.SteamGame>() private val drawerGameInventory = GameProfileInventoryCache<Library.SteamGame>()
private var drawerGameInventoryRevision = 0L private var drawerGameInventoryRevision = 0L
private var drawerGameFexPresetSaving by mutableStateOf(false) private var drawerGameFexPresetSaving by mutableStateOf(false)
@@ -492,9 +475,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
com.droiddeck.launcher.gpu.SteamVrHealth.begin(this, SessionState.sessionId) com.droiddeck.launcher.gpu.SteamVrHealth.begin(this, SessionState.sessionId)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
if (!SessionState.running) { if (!SessionState.running) {
val prefMode = SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM) SessionState.fpsLimit = SessionPrefs.fpsLimit(
SessionState.fpsLimit = SessionPrefs.fpsLimit(this, prefMode) this, SessionPrefs.prefMode(intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM),
SessionState.performanceMode = SessionPrefs.performanceMode(this, prefMode) )
} }
applyOutputPacing() applyOutputPacing()
if (!SessionState.running) SessionState.followScreen = followChoice() if (!SessionState.running) SessionState.followScreen = followChoice()
@@ -551,21 +534,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
cursorVisible = false cursorVisible = false
} }
onScreenControls = OnScreenControls(this, bridge, onKeyboard = ::togglePcKeyboard).also { root.addView(it) } onScreenControls = OnScreenControls(this, bridge, onKeyboard = ::togglePcKeyboard).also { root.addView(it) }
screenKeysShown = com.droiddeck.launcher.input.ControllerPrefs.screenKeysShown(this)
screenKeys = ScreenKeys(this) { code, down -> if (CompositorHost.isStarted) sendGuestKey(code, down) }.also { keys ->
keys.onTouchMiss = miss@{ event ->
if (routedTouchMode == SessionPrefs.TOUCH_GESTURES &&
!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SCREEN_KEYS, event)) return@miss
event.offsetLocation(keys.left - surfaceView.left.toFloat(), keys.top - surfaceView.top.toFloat())
onTouchEvent(event)
}
keys.onAdd = { screenKeyPickerOpen = true }
keys.onSelect = { codes -> screenKeyEdit = screenKeys?.stateOf(codes) }
keys.onEditingChanged = { if (!it) screenKeyEdit = null }
keys.steamStyle = { steamTouchControls?.style }
keys.visibility = if (screenKeysShown) View.VISIBLE else View.GONE
root.addView(keys)
}
keyboard = KeyboardHost(this).also { root.addView(it) } keyboard = KeyboardHost(this).also { root.addView(it) }
touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener) touchpad = TouchpadGestures(PointerGestures.slop(this), pointerListener)
directTouchHold = DirectTouchHold(PointerGestures.slop(this), pointerListener) { directTouchHold = DirectTouchHold(PointerGestures.slop(this), pointerListener) {
@@ -580,12 +548,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
// game surface and on-screen buttons, in either finger-down order. // game surface and on-screen buttons, in either finger-down order.
root.isMotionEventSplittingEnabled = true root.isMotionEventSplittingEnabled = true
surfaceView.setOnTouchListener { _, event -> surfaceView.setOnTouchListener { _, event ->
if (routedTouchMode != SessionPrefs.TOUCH_GESTURES) { routedTouchMode == SessionPrefs.TOUCH_GESTURES && onTouchEvent(event)
gestureTouchStreamGate.reset()
false
} else if (!gestureTouchStreamGate.accepts(GestureTouchStreamGate.Source.SURFACE, event)) {
false
} else onTouchEvent(event)
} }
padMouse = PadMouse(padMouseListener) padMouse = PadMouse(padMouseListener)
bridge.setTouchRoute(object : PadBridge.TouchRoute { bridge.setTouchRoute(object : PadBridge.TouchRoute {
@@ -609,21 +572,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val needResume = !needRuntime && com.droiddeck.launcher.runtime.DesktopCatalog.interrupted(this).isNotEmpty() val needResume = !needRuntime && com.droiddeck.launcher.runtime.DesktopCatalog.interrupted(this).isNotEmpty()
val needDesktop = intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_DESKTOP && val needDesktop = intent.getStringExtra(SessionService.EXTRA_MODE) == SessionService.MODE_DESKTOP &&
(repair || !com.droiddeck.launcher.runtime.DesktopCatalog.desktopInstalled(this)) (repair || !com.droiddeck.launcher.runtime.DesktopCatalog.desktopInstalled(this))
val program = intent.getStringExtra(SessionService.EXTRA_PROGRAM) val needProton = (intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM) == SessionService.MODE_STEAM &&
val protonUser = (intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM) == SessionService.MODE_STEAM || com.droiddeck.launcher.runtime.DesktopCatalog.protonSeedNeeded(this)
program == com.droiddeck.launcher.runtime.BattleNet.PROGRAM || program == com.droiddeck.launcher.session.NoSteamLaunch.PROTON_RUN
val needProton = protonUser && com.droiddeck.launcher.runtime.DesktopCatalog.protonSeedNeeded(this)
if (needRuntime || needResume || needDesktop || needProton) installThenStart(needRuntime, needDesktop, needProton, needResume) if (needRuntime || needResume || needDesktop || needProton) installThenStart(needRuntime, needDesktop, needProton, needResume)
} }
hud = PerfHud(this) hud = PerfHud(this)
memoryHud = com.droiddeck.launcher.session.MemoryHud(this)
hud.onPresentingWindowChanged = { hud.onPresentingWindowChanged = {
if (FrameGen.engine(this) != FrameGen.ENGINE_OFF) CompositorHost.rearmFrameGen { applyFrameGen() } if (FrameGen.engine(this) != FrameGen.ENGINE_OFF) CompositorHost.rearmFrameGen { applyFrameGen() }
} }
if (SessionState.running && SessionState.firstFrameSeen) { if (SessionState.running && SessionState.firstFrameSeen) {
loading.visible = false loading.visible = false
hud.start() hud.start()
memoryHud.start()
} }
readPrefs() readPrefs()
@@ -718,9 +677,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) { com.droiddeck.launcher.ui.FocusGlideHost(androidx.compose.ui.Modifier.fillMaxSize()) {
CursorOverlay({ cursorPos }, cursorVisible, resources.displayMetrics.density, CursorOverlay({ cursorPos }, cursorVisible, resources.displayMetrics.density,
cursorImage, cursorHotX, cursorHotY, cursorImageScale) cursorImage, cursorHotX, cursorHotY, cursorImageScale)
val hudLines = listOf(hud.text, memoryHud.text).filter { it.isNotEmpty() } if (hud.text.isNotEmpty() || hud.graph.size >= 2) HudText(hud.text, hud.graph, hudColor, hudOpacity)
if (hudLines.isNotEmpty() || hud.graph.size >= 2)
HudText(hudLines.joinToString("\n"), hud.graph, hudColor, hudOpacity)
val phonePanel = glassesOutputActive && !loading.visible && !drawerOpen && !pcKeyboardOpen val phonePanel = glassesOutputActive && !loading.visible && !drawerOpen && !pcKeyboardOpen
if (phonePanel) GlassesPhonePanel(glasses, steamVrStatus == SteamVr.Status.RUNNING, headTracking) if (phonePanel) GlassesPhonePanel(glasses, steamVrStatus == SteamVr.Status.RUNNING, headTracking)
if (trackingRecovery != null && !drawerOpen && !pcKeyboardOpen && !loading.visible) { if (trackingRecovery != null && !drawerOpen && !pcKeyboardOpen && !loading.visible) {
@@ -776,7 +733,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, pipUi, SessionState.suspended) { LaunchedEffect(drawerOpen, pcKeyboardOpen, achievementsOpen, gestureSettingsOpen, pipUi, SessionState.suspended) {
if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended) { if (drawerOpen || pcKeyboardOpen || achievementsOpen || gestureSettingsOpen || pipUi || SessionState.suspended) {
cancelTouchGestures() cancelTouchGestures()
screenKeys?.stopEditing()
} }
} }
com.droiddeck.launcher.ui.GestureFeedback(recognizedGesture) com.droiddeck.launcher.ui.GestureFeedback(recognizedGesture)
@@ -785,84 +741,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onDismiss = { gestureSettingsOpen = false }, onDismiss = { gestureSettingsOpen = false },
onSaved = { gestureSettingsOpen = false; refreshGestureConfig() }, onSaved = { gestureSettingsOpen = false; refreshGestureConfig() },
) )
if (screenKeyPickerOpen) {
val dir = screenKeyDir
com.droiddeck.launcher.ui.ScreenKeyPicker(
initial = if (dir != null) {
listOfNotNull((screenKeyEdit?.codes?.getOrNull(dir) ?: 0).takeIf { it != 0 })
} else {
screenKeyBind ?: emptyList()
},
onDismiss = { screenKeyPickerOpen = false; screenKeyBind = null; screenKeyDir = null },
onAdd = { codes ->
val bind = screenKeyBind
if (dir != null && bind != null) {
screenKeys?.setDirection(bind, dir, codes.lastOrNull() ?: 0)?.let { screenKeyEdit = it }
} else if (bind != null) {
screenKeys?.setCodes(bind, codes)?.let { screenKeyEdit = it }
} else {
screenKeys?.add(codes)
screenKeyEdit = screenKeys?.stateOf(codes)
}
screenKeyPickerOpen = false
screenKeyBind = null
screenKeyDir = null
},
)
}
screenKeyEdit?.let { key ->
com.droiddeck.launcher.ui.ScreenKeyEditor(
codes = key.codes, keyY = key.y,
size = key.size, opacity = key.opacity, shape = key.shape, toggle = key.toggle,
labels = key.labels,
text = key.text, hasImage = key.image.isNotEmpty(),
onResize = { screenKeys?.resize(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) },
onOpacity = { screenKeys?.setOpacity(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) },
onShape = { screenKeys?.setShape(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) },
onToggle = { on -> screenKeys?.setToggle(key.codes, on); screenKeyEdit = screenKeys?.stateOf(key.codes) },
onLabels = { on -> screenKeys?.setLabels(key.codes, on); screenKeyEdit = screenKeys?.stateOf(key.codes) },
onDirection = { index -> screenKeyBind = key.codes; screenKeyDir = index; screenKeyPickerOpen = true },
onText = { screenKeys?.setText(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) },
onImage = { screenKeys?.setImage(key.codes, it); screenKeyEdit = screenKeys?.stateOf(key.codes) },
onClearImage = { screenKeys?.setImage(key.codes, ""); screenKeyEdit = screenKeys?.stateOf(key.codes) },
onBind = { screenKeyBind = key.codes; screenKeyDir = null; screenKeyPickerOpen = true },
onTextFocus = { screenKeyTextFocus = true; keyboard?.hide() },
onTextBlur = { screenKeyTextFocus = false },
onRemove = { screenKeys?.remove(key.codes); screenKeyEdit = null },
onDismiss = { screenKeyEdit = null; screenKeyTextFocus = false; screenKeys?.deselect() },
)
}
if (screenLayoutsOpen) com.droiddeck.launcher.ui.ScreenLayoutPanel(
layouts = screenLayoutNames,
onSave = { name ->
screenKeys?.let { keys ->
com.droiddeck.launcher.input.ControllerPrefs.saveScreenLayout(this@SessionActivity, name, keys.export())
}
screenLayoutNames = layoutNames()
},
onLoad = { name ->
com.droiddeck.launcher.input.ControllerPrefs.screenLayouts(this@SessionActivity)[name]?.let { screenKeys?.load(it) }
screenLayoutsOpen = false
},
onDelete = { name ->
com.droiddeck.launcher.input.ControllerPrefs.deleteScreenLayout(this@SessionActivity, name)
screenLayoutNames = layoutNames()
},
onImport = { text ->
val width = (screenKeys?.width ?: 0).takeIf { it > 0 } ?: resources.displayMetrics.widthPixels
val keys = com.droiddeck.launcher.input.importScreenLayout(text, width, resources.displayMetrics.density)
if (keys != null) {
screenKeys?.load(com.droiddeck.launcher.input.ControllerPrefs.encodeScreenKeys(keys))
screenLayoutsOpen = false
}
},
exportText = {
val width = (screenKeys?.width ?: 0).takeIf { it > 0 } ?: resources.displayMetrics.widthPixels
val keys = com.droiddeck.launcher.input.ControllerPrefs.decodeScreenKeys(screenKeys?.export().orEmpty())
com.droiddeck.launcher.input.exportScreenLayout(keys, width, resources.displayMetrics.density)
},
onDismiss = { screenLayoutsOpen = false },
)
androidx.compose.runtime.LaunchedEffect(drawerOpen) { androidx.compose.runtime.LaunchedEffect(drawerOpen) {
if (drawerOpen) { if (drawerOpen) {
syncLossless() syncLossless()
@@ -909,7 +787,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
) )
SessionDrawer(drawerOpen, drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, a = DrawerActions( SessionDrawer(drawerOpen, drawerPage, drawerControllerActive, onPageChange = { drawerPage = it }, a = DrawerActions(
steam = SessionState.mode == SessionService.MODE_STEAM, steam = SessionState.mode == SessionService.MODE_STEAM,
direct = noSteamSession(),
title = if (SessionState.mode == SessionService.MODE_RUN) title = if (SessionState.mode == SessionService.MODE_RUN)
com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_title_game) else null, com.droiddeck.launcher.frontend.Library.nameForProgram(SessionState.program) ?: getString(R.string.session_title_game) else null,
isHomeApp = isHomeApp, isHomeApp = isHomeApp,
@@ -941,9 +818,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
lossless = lossless, lossless = lossless,
oscMode = oscMode, onScreenButtonsVisible = onScreenButtonsVisible, suspendPolicy = suspendPolicy, oscMode = oscMode, onScreenButtonsVisible = onScreenButtonsVisible, suspendPolicy = suspendPolicy,
steamDownloadsInBackground = steamDownloadsInBackground, touchMode = touchMode, steamDownloadsInBackground = steamDownloadsInBackground, touchMode = touchMode,
micAvailable = SessionState.micAvailable && !SessionState.suspended,
micEnabled = SessionState.micEnabled,
onMicEnabled = { SessionService.setMicEnabled(this@SessionActivity, it) },
touchAuto = getString(if (usingTouchpad()) R.string.session_touch_auto_touchpad else R.string.session_touch_auto_direct), touchAuto = getString(if (usingTouchpad()) R.string.session_touch_auto_touchpad else R.string.session_touch_auto_direct),
fexPreset = fexPreset, fexPreset = fexPreset,
secondScreenMode = secondScreenMode, secondScreenMode = secondScreenMode,
@@ -1054,19 +928,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
}, },
onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() }, onTouch = { v -> SessionPrefs.setTouchMode(this@SessionActivity, v); readPrefs() },
onGestureSettings = { drawerOpen = false; gestureSettingsOpen = true }, onGestureSettings = { drawerOpen = false; gestureSettingsOpen = true },
onScreenKeys = { drawerOpen = false; screenKeys?.startEditing() },
screenKeysShown = screenKeysShown,
onScreenKeysShown = { shown ->
screenKeysShown = shown
com.droiddeck.launcher.input.ControllerPrefs.setScreenKeysShown(this@SessionActivity, shown)
screenKeys?.stopEditing()
screenKeys?.visibility = if (shown) View.VISIBLE else View.GONE
},
onScreenLayouts = {
drawerOpen = false
screenLayoutNames = layoutNames()
screenLayoutsOpen = true
},
onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() }, onFexPreset = { v -> SessionPrefs.setFexPreset(this@SessionActivity, v); readPrefs() },
onSecondScreenMode = ::selectSecondScreenMode, onSecondScreenMode = ::selectSecondScreenMode,
onSecondScreenDisplay = ::selectSecondScreenDisplay, onSecondScreenDisplay = ::selectSecondScreenDisplay,
@@ -1377,7 +1238,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
val activeAppId = AgentGuest.activeSteamAppId(this, installedAppIds) val activeAppId = AgentGuest.activeSteamAppId(this, installedAppIds)
val selectedSteamAppId = runCatching { AgentGuest.selectedSteamAppId(this) } val selectedSteamAppId = runCatching { AgentGuest.selectedSteamAppId(this) }
AgentGuest.selectedOrActiveInstalledSteamAppId(selectedSteamAppId, activeAppId, installedAppIds) AgentGuest.selectedOrActiveInstalledSteamAppId(selectedSteamAppId, activeAppId, installedAppIds)
?: SessionState.gameId?.toLongOrNull()
?: refresh.requestedAppId ?: refresh.requestedAppId
} else { } else {
refresh.requestedAppId refresh.requestedAppId
@@ -1624,9 +1484,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (nextTouchMode == SessionPrefs.TOUCH_OFF || !usingTouchpad()) cursorVisible = false if (nextTouchMode == SessionPrefs.TOUCH_OFF || !usingTouchpad()) cursorVisible = false
} }
touchMode = nextTouchMode touchMode = nextTouchMode
val nextRoutedTouchMode = effectiveTouchMode() routedTouchMode = effectiveTouchMode()
if (routedTouchMode != nextRoutedTouchMode) gestureTouchStreamGate.reset()
routedTouchMode = nextRoutedTouchMode
frameGen = FrameGen.mode(this) frameGen = FrameGen.mode(this)
fexPreset = SessionPrefs.fexPreset(this) fexPreset = SessionPrefs.fexPreset(this)
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode) suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
@@ -1866,7 +1724,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
intent.getStringExtra(SessionService.EXTRA_STEAM_UI), intent.getStringExtra(SessionService.EXTRA_STEAM_UI),
intent.getStringExtra(SessionService.EXTRA_STEAM_URL), intent.getStringExtra(SessionService.EXTRA_STEAM_URL),
intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS), intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS),
intent.getStringExtra(SessionService.EXTRA_GAME_ID),
sessionActivityDisplayId, sessionActivityDisplayId,
) )
} }
@@ -1983,9 +1840,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun mirrorRefreshLimit(): Int = private fun mirrorRefreshLimit(): Int =
GlassesRendering.mirrorRefreshLimit(glassesSettings, glasses, glassesScreen != null) GlassesRendering.mirrorRefreshLimit(glassesSettings, glasses, glassesScreen != null)
private fun outputFpsLimit(): Int = SessionPrefs.compositorFpsLimit( private fun outputFpsLimit(): Int = GlassesRendering.fpsLimit(SessionState.fpsLimit, mirrorRefreshLimit())
GlassesRendering.fpsLimit(SessionState.fpsLimit, mirrorRefreshLimit()), SessionState.performanceMode,
)
private fun applyOutputPacing() { private fun applyOutputPacing() {
Log.i(TAG, "perf: " + PerfMode.apply(this, outputFpsLimit(), mirrorRefreshLimit())) Log.i(TAG, "perf: " + PerfMode.apply(this, outputFpsLimit(), mirrorRefreshLimit()))
@@ -2038,8 +1893,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
override fun run() { override fun run() {
if (!watching) return if (!watching) return
if (::pip.isInitialized) pip.refresh() if (::pip.isInitialized) pip.refresh()
if (SessionState.stopRequested && !SessionState.running && !installingRuntime && if (SessionState.stopRequested && !SessionState.running && !installingRuntime) {
SessionState.phase != SessionPhase.STOPPING) {
SessionState.stopRequested = false SessionState.stopRequested = false
SessionEvents.transition(SessionPhase.IDLE, "session.cancelled") SessionEvents.transition(SessionPhase.IDLE, "session.cancelled")
collectStartArtifacts("session start cancelled") collectStartArtifacts("session start cancelled")
@@ -2072,7 +1926,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionState.relaunch?.let { next -> SessionState.relaunch?.let { next ->
SessionState.relaunch = null SessionState.relaunch = null
next.putExtra(EXTRA_RETURN_HOME, intent.getBooleanExtra(EXTRA_RETURN_HOME, false)) next.putExtra(EXTRA_RETURN_HOME, intent.getBooleanExtra(EXTRA_RETURN_HOME, false))
next.putExtra(EXTRA_LINK_TASK, intent.getIntExtra(EXTRA_LINK_TASK, -1))
setIntent(next) setIntent(next)
recreate() recreate()
return@runOnUiThread return@runOnUiThread
@@ -2081,9 +1934,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
} }
return return
} }
val driverHint = runtimeDriverHint()
Thread({ Thread({
val hint = driverHint ?: runtimeDamageHint() ?: sessionEndHint(SessionState.logFile) val hint = runtimeDamageHint() ?: sessionEndHint(SessionState.logFile)
runOnUiThread { runOnUiThread {
if (isFinishing || isDestroyed) return@runOnUiThread if (isFinishing || isDestroyed) return@runOnUiThread
showEnded(status, hint) showEnded(status, hint)
@@ -2105,9 +1957,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
repairOffered = hint?.repair == true repairOffered = hint?.repair == true
loading.showEnded( loading.showEnded(
hint?.text ?: stopped, hint?.text ?: stopped,
getString(R.string.session_ended_detail, status, getString(R.string.session_ended_detail, status, SessionState.logFile?.path ?: getString(R.string.session_ended_no_log)),
SessionState.logFile?.path?.let { android.text.BidiFormatter.getInstance().unicodeWrap(it, android.text.TextDirectionHeuristics.LTR) }
?: getString(R.string.session_ended_no_log)),
) )
focusEndedScreen() focusEndedScreen()
} }
@@ -2139,12 +1989,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private class EndHint(val text: String, val evenOnSuccess: Boolean = false, val repair: Boolean = false) private class EndHint(val text: String, val evenOnSuccess: Boolean = false, val repair: Boolean = false)
private fun runtimeDriverHint(): EndHint? {
if (SessionState.failureCode != SessionService.FAILURE_RUNTIME_DRIVER) return null
val message = getString(R.string.session_end_runtime_driver, getString(R.string.gpu_mode_mix), getString(R.string.gpu_change_runtime))
return EndHint(listOfNotNull(message, SessionState.failureMessage?.takeIf { it.isNotBlank() }).joinToString("\n"))
}
private fun runtimeDamageHint(): EndHint? { private fun runtimeDamageHint(): EndHint? {
val broken = runCatching { com.droiddeck.launcher.runtime.RuntimeHealth.brokenLibraryLinks(this) }.getOrDefault(emptyList()) val broken = runCatching { com.droiddeck.launcher.runtime.RuntimeHealth.brokenLibraryLinks(this) }.getOrDefault(emptyList())
if (broken.isEmpty()) return null if (broken.isEmpty()) return null
@@ -2192,7 +2036,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return super.dispatchKeyEvent(event) return super.dispatchKeyEvent(event)
} }
if (pipUi) return true if (pipUi) return true
if (screenKeyTextFocus) return super.dispatchKeyEvent(event)
val pad = com.droiddeck.launcher.input.JoyCon.normalize(event) val pad = com.droiddeck.launcher.input.JoyCon.normalize(event)
if (pad !== event) return dispatchKeyEvent(pad) if (pad !== event) return dispatchKeyEvent(pad)
val fromController = PadBridge.isControllerKeyEvent(event) val fromController = PadBridge.isControllerKeyEvent(event)
@@ -2214,20 +2057,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
} }
return super.dispatchKeyEvent(event) return super.dispatchKeyEvent(event)
} }
val drawerShortcutKey = event.deviceId to event.keyCode
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_SELECT || event.keyCode == KeyEvent.KEYCODE_BUTTON_START) &&
((drawerOpen && SessionState.mode == SessionService.MODE_STEAM) || drawerShortcutKey in drawerShortcutKeysDown)) {
if (event.action == KeyEvent.ACTION_DOWN) {
drawerShortcutKeysDown.add(drawerShortcutKey)
if (event.repeatCount == 0) {
releaseDrawerDirection()
if (event.keyCode == KeyEvent.KEYCODE_BUTTON_SELECT) sendSteamGuide() else triggerSteamQam()
}
} else if (event.action == KeyEvent.ACTION_UP) {
drawerShortcutKeysDown.remove(drawerShortcutKey)
}
return true
}
if (drawerOpen) { if (drawerOpen) {
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) { if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) { if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
@@ -2394,14 +2223,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
super.dispatchKeyEvent(event) super.dispatchKeyEvent(event)
} }
private fun layoutNames(): List<String> =
com.droiddeck.launcher.input.ControllerPrefs.screenLayouts(this).keys.sorted()
private fun refreshGestureConfig() { private fun refreshGestureConfig() {
gestureConfig = com.droiddeck.launcher.input.GesturePrefs.read(this, gestureGame) gestureConfig = com.droiddeck.launcher.input.GesturePrefs.read(this, gestureGame)
gestureTouchStreamGate.reset()
if (::touchscreenGestures.isInitialized) touchscreenGestures.configure(gestureConfig) if (::touchscreenGestures.isInitialized) touchscreenGestures.configure(gestureConfig)
if (::directTouchHold.isInitialized) directTouchHold.configure(gestureConfig)
gesturePointerReady = false gesturePointerReady = false
recognizedGesture = null recognizedGesture = null
} }
@@ -2689,7 +2513,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
private fun refreshControls() { private fun refreshControls() {
applyUnfoldedControls() applyUnfoldedControls()
updateOnScreenControls() updateOnScreenControls()
screenKeys?.refreshAppearance()
} }
private fun applyUnfoldedControls() { private fun applyUnfoldedControls() {
@@ -2775,7 +2598,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (::scrollTouch.isInitialized) scrollTouch.cancel() if (::scrollTouch.isInitialized) scrollTouch.cancel()
if (CompositorHost.isStarted) WaylandCompositor.nativeSendTouch(3, -1, 0, 0) if (CompositorHost.isStarted) WaylandCompositor.nativeSendTouch(3, -1, 0, 0)
if (next == SessionPrefs.TOUCH_OFF) cursorVisible = false if (next == SessionPrefs.TOUCH_OFF) cursorVisible = false
gestureTouchStreamGate.reset()
routedTouchMode = next routedTouchMode = next
} }
@@ -2966,7 +2788,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
device.plugged = false device.plugged = false
uiHandler.postDelayed({ updateOnScreenControls() }, 700) uiHandler.postDelayed({ updateOnScreenControls() }, 700)
} }
view.onStyle = { screenKeys?.refreshAppearance() }
root.addView(view, root.indexOfChild(onScreenControls) + 1) root.addView(view, root.indexOfChild(onScreenControls) + 1)
steamTouchControls = view steamTouchControls = view
steamTouchAvailable = true steamTouchAvailable = true
@@ -2997,7 +2818,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
controls.visibility = View.GONE controls.visibility = View.GONE
steamTouchControls?.let { it.releaseAll(); it.visibility = View.GONE } steamTouchControls?.let { it.releaseAll(); it.visibility = View.GONE }
com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false com.droiddeck.launcher.input.SteamTouchDevice.current?.plugged = false
screenKeys?.followSteam = false
applyTouchRouting() applyTouchRouting()
return return
} }
@@ -3026,7 +2846,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
onScreenButtonsVisible = show onScreenButtonsVisible = show
val drawn = show && !keyboardCoversPad() val drawn = show && !keyboardCoversPad()
if (steam != null) { if (steam != null) {
screenKeys?.followSteam = drawn
if (controls.visibility == View.VISIBLE) { controls.releaseAll(); controls.visibility = View.GONE } if (controls.visibility == View.VISIBLE) { controls.releaseAll(); controls.visibility = View.GONE }
if (!drawn) steam.releaseAll() if (!drawn) steam.releaseAll()
steam.visibility = if (drawn) View.VISIBLE else View.GONE steam.visibility = if (drawn) View.VISIBLE else View.GONE
@@ -3035,7 +2854,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
Log.i(TAG, "on-screen controls: Steam's touch controller " + if (drawn) "shown" else "hidden") Log.i(TAG, "on-screen controls: Steam's touch controller " + if (drawn) "shown" else "hidden")
return return
} }
screenKeys?.followSteam = false
if (drawn == (controls.visibility == View.VISIBLE)) return if (drawn == (controls.visibility == View.VISIBLE)) return
if (!drawn) controls.releaseAll() if (!drawn) controls.releaseAll()
controls.visibility = if (drawn) View.VISIBLE else View.GONE controls.visibility = if (drawn) View.VISIBLE else View.GONE
@@ -3121,7 +2939,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
pendingBackAction = null pendingBackAction = null
releaseDrawerDirection() releaseDrawerDirection()
onScreenControls?.releaseAll() onScreenControls?.releaseAll()
screenKeys?.releaseAll()
releasePads() releasePads()
touchpad.cancel() touchpad.cancel()
scrollTouch.cancel() scrollTouch.cancel()
@@ -3210,7 +3027,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
return return
} }
if (this.intent.getBooleanExtra(EXTRA_RETURN_HOME, false)) intent.putExtra(EXTRA_RETURN_HOME, true) if (this.intent.getBooleanExtra(EXTRA_RETURN_HOME, false)) intent.putExtra(EXTRA_RETURN_HOME, true)
if (!intent.hasExtra(EXTRA_LINK_TASK)) intent.putExtra(EXTRA_LINK_TASK, this.intent.getIntExtra(EXTRA_LINK_TASK, -1))
setIntent(intent) setIntent(intent)
if (intent.getBooleanExtra(EXTRA_STEAMVR, false) && SessionState.mode == SessionService.MODE_STEAM) { if (intent.getBooleanExtra(EXTRA_STEAMVR, false) && SessionState.mode == SessionService.MODE_STEAM) {
SessionState.steamVr = true SessionState.steamVr = true
@@ -3234,7 +3050,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
if (!SessionState.suspended) pausedFrame = null if (!SessionState.suspended) pausedFrame = null
com.droiddeck.launcher.ui.Motion.refresh(this) com.droiddeck.launcher.ui.Motion.refresh(this)
refreshHomeApp() refreshHomeApp()
if (::memoryHud.isInitialized && SessionState.running && SessionState.firstFrameSeen) memoryHud.refresh()
if (intent?.action == SessionService.ACTION_RESUME) { if (intent?.action == SessionService.ACTION_RESUME) {
intent.action = null intent.action = null
SessionService.resume(this) SessionService.resume(this)
@@ -3680,10 +3495,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
SessionEvents.firstFrame() SessionEvents.firstFrame()
if (SessionState.mode == SessionService.MODE_STEAM) SteamRepair.clientShown(this) if (SessionState.mode == SessionService.MODE_STEAM) SteamRepair.clientShown(this)
runOnUiThread { runOnUiThread {
if (isFinishing || isDestroyed) return@runOnUiThread
loading.visible = false loading.visible = false
hud.start() hud.start()
memoryHud.start()
} }
} }
@@ -3701,7 +3514,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
glassesScreen?.let { screen -> glassesScreen = null; runCatching { screen.dismiss() } } glassesScreen?.let { screen -> glassesScreen = null; runCatching { screen.dismiss() } }
headTracker?.stop() headTracker?.stop()
if (::hud.isInitialized) hud.stop() if (::hud.isInitialized) hud.stop()
if (::memoryHud.isInitialized) memoryHud.stop()
joyConVr?.close() joyConVr?.close()
joyConVr = null joyConVr = null
handCamera?.stop() handCamera?.stop()
@@ -3737,33 +3549,17 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
} }
return return
} }
super.finish()
if (!closeAtOnce && intent.getBooleanExtra(EXTRA_RETURN_HOME, false)) { if (!closeAtOnce && intent.getBooleanExtra(EXTRA_RETURN_HOME, false)) {
com.droiddeck.launcher.ui.QuitFlood.take() com.droiddeck.launcher.ui.QuitFlood.take()
com.droiddeck.launcher.ui.LaunchOrigin.flooding = null com.droiddeck.launcher.ui.LaunchOrigin.flooding = null
closeLinkTasks() startActivity(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME)
if (!isTaskRoot) moveTaskToBack(true) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
super.finishAndRemoveTask() }
} else super.finish()
if (quitFlooded) overridePendingTransition(0, 0) if (quitFlooded) overridePendingTransition(0, 0)
else overridePendingTransition(R.anim.session_hold, R.anim.session_sink) else overridePendingTransition(R.anim.session_hold, R.anim.session_sink)
} }
private fun closeLinkTasks() {
val linkTask = intent.getIntExtra(EXTRA_LINK_TASK, -1)
if (linkTask == -1) return
val tasks = runCatching { getSystemService(android.app.ActivityManager::class.java)?.appTasks }.getOrNull().orEmpty()
for (task in tasks) {
runCatching {
val info = task.taskInfo
@Suppress("DEPRECATION")
val id = if (android.os.Build.VERSION.SDK_INT >= 29) info.taskId else info.persistentId
val base = info.baseIntent
if (id == linkTask && base.component?.className == FrontEndActivity::class.java.name &&
com.droiddeck.launcher.frontend.GameLaunchIntent.accepts(base.action)) task.finishAndRemoveTask()
}
}
}
private fun completeLeave() { private fun completeLeave() {
if (isFinishing) return if (isFinishing) return
val signal = com.droiddeck.launcher.ui.Themes.current(this).signal val signal = com.droiddeck.launcher.ui.Themes.current(this).signal
@@ -3775,7 +3571,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback {
companion object { companion object {
const val EXTRA_RETURN_HOME = "returnHome" const val EXTRA_RETURN_HOME = "returnHome"
const val EXTRA_LINK_TASK = "linkTask"
const val EXTRA_STEAMVR = "steamVr" const val EXTRA_STEAMVR = "steamVr"
const val EXTRA_REPAIR_RUNTIME = "repairRuntime" const val EXTRA_REPAIR_RUNTIME = "repairRuntime"
private const val LEAVE_TIMEOUT_MS = 1_500L private const val LEAVE_TIMEOUT_MS = 1_500L
@@ -29,7 +29,6 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
private var pending: AppUpdates.Release? = null private var pending: AppUpdates.Release? = null
private var lastCheck = 0L private var lastCheck = 0L
private var request = 0 private var request = 0
@Volatile private var session = -1
fun state() = UpdatesState(catalog, follow, checking, error, stage, percent, askPermission) fun state() = UpdatesState(catalog, follow, checking, error, stage, percent, askPermission)
@@ -88,14 +87,13 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
if (SessionState.running) { error = activity.getString(R.string.upd_stop_first); return } if (SessionState.running) { error = activity.getString(R.string.upd_stop_first); return }
if (!SelfInstaller.canInstall(activity)) { pending = r; askPermission = true; return } if (!SelfInstaller.canInstall(activity)) { pending = r; askPermission = true; return }
error = null error = null
session = -1
stage = activity.getString(R.string.upd_stage_downloading) stage = activity.getString(R.string.upd_stage_downloading)
percent = 0 percent = 0
Thread({ Thread({
val result = runCatching { val result = runCatching {
val file = SelfInstaller.download(activity, apk) { pct -> ui.post { percent = pct } } val file = SelfInstaller.download(activity, apk) { pct -> ui.post { percent = pct } }
ui.post { stage = activity.getString(R.string.upd_stage_installing); percent = -1 } ui.post { stage = activity.getString(R.string.upd_stage_installing); percent = -1 }
SelfInstaller.install(activity, file) { id -> session = id } SelfInstaller.install(activity, file)
} }
result.onFailure { e -> ui.post { stage = null; error = e.message ?: activity.getString(R.string.upd_failed) } } result.onFailure { e -> ui.post { stage = null; error = e.message ?: activity.getString(R.string.upd_failed) } }
}, "app-update-install").start() }, "app-update-install").start()
@@ -103,15 +101,13 @@ internal class UpdatesMenu(private val activity: Activity, private val ui: Handl
private val receiver = object : BroadcastReceiver() { private val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) { override fun onReceive(context: Context, intent: Intent) {
if (intent.getIntExtra(PackageInstaller.EXTRA_SESSION_ID, -1).let { it < 0 || it != session }) return
when (val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)) { when (val status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, PackageInstaller.STATUS_FAILURE)) {
PackageInstaller.STATUS_PENDING_USER_ACTION -> { PackageInstaller.STATUS_PENDING_USER_ACTION -> {
val confirm = if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java) val confirm = if (Build.VERSION.SDK_INT >= 33) intent.getParcelableExtra(Intent.EXTRA_INTENT, Intent::class.java)
else @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_INTENT) else @Suppress("DEPRECATION") intent.getParcelableExtra(Intent.EXTRA_INTENT)
val safe = confirm?.let { SelfInstaller.safeConfirmIntent(activity, it) } if (confirm == null) { stage = null; error = activity.getString(R.string.upd_not_offered); return }
if (safe == null) { stage = null; error = activity.getString(R.string.upd_not_offered); return }
stage = activity.getString(R.string.upd_stage_confirm) stage = activity.getString(R.string.upd_stage_confirm)
if (runCatching { activity.startActivity(safe) }.isFailure) { stage = null; error = activity.getString(R.string.upd_not_offered) } activity.startActivity(confirm.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
} }
PackageInstaller.STATUS_SUCCESS -> stage = null PackageInstaller.STATUS_SUCCESS -> stage = null
else -> { else -> {
@@ -3,13 +3,9 @@ package com.droiddeck.launcher.agent
import android.content.Context import android.content.Context
import android.util.Log import android.util.Log
import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.ProotFastPath
import com.droiddeck.launcher.session.SessionPhase
import com.droiddeck.launcher.session.SessionState
import org.json.JSONArray import org.json.JSONArray
import org.json.JSONObject import org.json.JSONObject
import java.io.File import java.io.File
import java.security.MessageDigest
import java.nio.file.Files import java.nio.file.Files
import java.nio.file.LinkOption.NOFOLLOW_LINKS import java.nio.file.LinkOption.NOFOLLOW_LINKS
import java.nio.file.StandardOpenOption.READ import java.nio.file.StandardOpenOption.READ
@@ -59,9 +55,6 @@ object AgentEnv {
fun override(context: Context, name: String): JSONObject = synchronized(lock) { fun override(context: Context, name: String): JSONObject = synchronized(lock) {
AgentAccess.requireCommands(context) AgentAccess.requireCommands(context)
if (NAME.matchEntire(name) == null || name in setOf(".", "..")) throw AgentException("INVALID_NAME", "Override names are letters, digits, '.', '_' and '-'") 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)) {
throw AgentException("SESSION_ACTIVE", "Stop the session before installing a fast-path library")
}
val source = File(inbox(context), name) val source = File(inbox(context), name)
if (Files.isSymbolicLink(source.toPath())) throw AgentException("INVALID_NAME", "The override must be a regular file") if (Files.isSymbolicLink(source.toPath())) throw AgentException("INVALID_NAME", "The override must be a regular file")
if (!source.isFile) throw AgentException("NO_SUCH_FILE", "Push the binary to ${source.path} first") if (!source.isFile) throw AgentException("NO_SUCH_FILE", "Push the binary to ${source.path} first")
@@ -74,10 +67,6 @@ object AgentEnv {
staged.delete() staged.delete()
throw AgentException("OVERRIDE_FAILED", "Could not stage the override") throw AgentException("OVERRIDE_FAILED", "Could not stage the override")
} }
if (name == "libblfastpath.so" && !arm64SharedLibrary(staged)) {
staged.delete()
throw AgentException("INVALID_LIBRARY", "The fast path must be a 64-bit little-endian ARM64 ELF shared library")
}
if (!staged.setExecutable(true, false) || !staged.renameTo(target)) { if (!staged.setExecutable(true, false) || !staged.renameTo(target)) {
staged.delete() staged.delete()
throw AgentException("OVERRIDE_FAILED", "Could not install $name in the rootfs") throw AgentException("OVERRIDE_FAILED", "Could not install $name in the rootfs")
@@ -87,40 +76,6 @@ object AgentEnv {
state.put("pendingOverrides", JSONArray(merge(strings(state.optJSONArray("pendingOverrides")), listOf(name)))) state.put("pendingOverrides", JSONArray(merge(strings(state.optJSONArray("pendingOverrides")), listOf(name))))
save(context, state) save(context, state)
state.put("installed", "$GUEST_BIN/$name") state.put("installed", "$GUEST_BIN/$name")
if (name == "libblfastpath.so") {
val digest = MessageDigest.getInstance("SHA-256")
target.inputStream().use { input ->
val buffer = ByteArray(65536)
while (true) {
val count = input.read(buffer)
if (count < 0) break
digest.update(buffer, 0, count)
}
}
state.put("sha256", digest.digest().joinToString("") { "%02x".format(it) })
}
state
}
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 (!file.isFile || Files.isSymbolicLink(file.toPath())) return@synchronized ProotFastPath.LIBRARY
"$GUEST_BIN/libblfastpath.so"
}
private fun arm64SharedLibrary(file: File): Boolean = file.inputStream().use { input ->
val header = ByteArray(20)
var count = 0
while (count < header.size) {
val read = input.read(header, count, header.size - count)
if (read < 0) return@use false
count += read
}
header.take(7) == listOf<Byte>(0x7f, 0x45, 0x4c, 0x46, 2, 1, 1) &&
header[16] == 3.toByte() && header[17] == 0.toByte() &&
header[18] == 183.toByte() && header[19] == 0.toByte()
} }
fun beginSession(context: Context): List<String> = synchronized(lock) { fun beginSession(context: Context): List<String> = synchronized(lock) {
@@ -131,13 +86,13 @@ object AgentEnv {
val state = load(context) val state = load(context)
val active = strings(state.optJSONArray("pending")) val active = strings(state.optJSONArray("pending"))
val overrides = strings(state.optJSONArray("pendingOverrides")) val overrides = strings(state.optJSONArray("pendingOverrides"))
bin(context).listFiles()
?.filter { it.name !in overrides }?.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)}"
state.put("active", JSONArray(active)).put("pending", JSONArray()) state.put("active", JSONArray(active)).put("pending", JSONArray())
state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray()) state.put("activeOverrides", JSONArray(overrides)).put("pendingOverrides", JSONArray())
save(context, state) save(context, state)
bin(context).listFiles()
?.filter { it.name !in overrides }?.forEach { it.delete() }
val lines = strings(state.optJSONArray("persistent")) + active
val withPath = if (overrides.isEmpty()) lines else lines + "PATH=$GUEST_BIN:${pathOf(lines)}"
if (withPath.isNotEmpty()) Log.i(TAG, "agent environment keys for this session: ${withPath.map { it.substringBefore('=') }}") if (withPath.isNotEmpty()) Log.i(TAG, "agent environment keys for this session: ${withPath.map { it.substringBefore('=') }}")
withPath withPath
} }
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.audio;
import android.os.Process; import android.os.Process;
import android.util.Log; import android.util.Log;
import com.droiddeck.launcher.core.FileUtils;
import com.droiddeck.launcher.core.SessionPart; import com.droiddeck.launcher.core.SessionPart;
import com.droiddeck.launcher.core.HostProcess; import com.droiddeck.launcher.core.HostProcess;
@@ -20,13 +19,10 @@ public class DirectAudioRelayComponent extends SessionPart {
private volatile int pid = -1; private volatile int pid = -1;
private final Object micLock = new Object(); private final Object micLock = new Object();
private boolean micHot; private boolean micHot;
private final File micControl;
public java.util.function.Consumer<Boolean> onMicEnabled;
public DirectAudioRelayComponent(File socketPath, File micFifoPath) { public DirectAudioRelayComponent(File socketPath, File micFifoPath) {
this.socketPath = socketPath; this.socketPath = socketPath;
this.micFifoPath = micFifoPath; this.micFifoPath = micFifoPath;
this.micControl = micFifoPath == null ? null : new File(micFifoPath.getParentFile(), "mic-enabled");
} }
public void setLogFile(File file) { public void setLogFile(File file) {
@@ -67,13 +63,8 @@ public class DirectAudioRelayComponent extends SessionPart {
StringBuilder command = new StringBuilder(binary.getAbsolutePath()); StringBuilder command = new StringBuilder(binary.getAbsolutePath());
command.append(" --socket ").append(socketPath.getAbsolutePath()); command.append(" --socket ").append(socketPath.getAbsolutePath());
command.append(" --log"); command.append(" --log");
final boolean withMic = micFifoPath != null && setMicEnabled(true); if (micFifoPath != null) {
if (withMic) {
command.append(" --mic-fifo ").append(micFifoPath.getAbsolutePath()); command.append(" --mic-fifo ").append(micFifoPath.getAbsolutePath());
command.append(" --mic-control ").append(micControl.getAbsolutePath());
} else if (micFifoPath != null) {
Log.w(TAG, "microphone control unavailable; starting with capture disabled");
command.append(" --mic-control /dev/null");
} }
ArrayList<String> env = new ArrayList<>(); ArrayList<String> env = new ArrayList<>();
env.add("HOME=" + app().getFilesDir()); env.add("HOME=" + app().getFilesDir());
@@ -82,7 +73,7 @@ public class DirectAudioRelayComponent extends SessionPart {
try { try {
out = new java.io.PrintWriter(new java.io.FileWriter(logFile, true)); out = new java.io.PrintWriter(new java.io.FileWriter(logFile, true));
out.println("== DirectAudio relay helper starting" out.println("== DirectAudio relay helper starting"
+ (withMic ? " with the microphone" : " (no microphone)")); + (micFifoPath != null ? " with the microphone" : " (no microphone)"));
out.flush(); out.flush();
} catch (Exception e) { } catch (Exception e) {
Log.w(TAG, "could not open " + logFile, e); Log.w(TAG, "could not open " + logFile, e);
@@ -93,23 +84,14 @@ public class DirectAudioRelayComponent extends SessionPart {
app().getFilesDir(), null, app().getFilesDir(), null,
line -> { line -> {
Log.i(TAG, line); Log.i(TAG, line);
if (withMic) trackMic(line); trackMic(line);
if (log != null) synchronized (log) { log.println(line); log.flush(); } if (log != null) synchronized (log) { log.println(line); log.flush(); }
}); });
Log.i(TAG, "started pid=" + pid + " socket=" + socketPath Log.i(TAG, "started pid=" + pid + " socket=" + socketPath
+ (withMic ? " mic=" + micFifoPath : " (no microphone)")); + (micFifoPath != null ? " mic=" + micFifoPath : " (no microphone)"));
}
public synchronized boolean setMicEnabled(boolean enabled) {
if (micControl == null) return false;
File next = new File(micControl.getPath() + ".new");
return FileUtils.writeString(next, enabled ? "1" : "0") && next.renameTo(micControl);
} }
private void trackMic(String line) { private void trackMic(String line) {
if (line.startsWith("DA-Relay: mic enabled=") && onMicEnabled != null) {
onMicEnabled.accept(line.equals("DA-Relay: mic enabled=1"));
}
boolean start = line.startsWith("DA-Relay: mic start "); boolean start = line.startsWith("DA-Relay: mic start ");
if (!start && !line.startsWith("DA-Relay: mic stop ")) return; if (!start && !line.startsWith("DA-Relay: mic stop ")) return;
synchronized (micLock) { synchronized (micLock) {
@@ -146,5 +146,7 @@ internal class AddonPack(
listOf("version", "xodus-cli", "xodus-service")) listOf("version", "xodus-cli", "xodus-service"))
val COMET = AddonPack("comet", BuildConfig.PACK_COMET_SHA256, BuildConfig.PACK_COMET_SIZE, val COMET = AddonPack("comet", BuildConfig.PACK_COMET_SHA256, BuildConfig.PACK_COMET_SIZE,
listOf("version", "comet")) listOf("version", "comet"))
val AMAZON = AddonPack("amazon", BuildConfig.PACK_AMAZON_SHA256, BuildConfig.PACK_AMAZON_SIZE,
listOf("engine.json", "libdroiddeckamazon.so"), reuseDeviceCopy = false)
} }
} }
@@ -1,59 +0,0 @@
package com.droiddeck.launcher.core
import android.content.Context
import android.util.Log
import java.util.concurrent.Executors
object BackgroundAppLimit {
private const val TAG = "BackgroundAppLimit"
const val OFF = -1
val CHOICES = listOf(OFF, 4, 1, 0)
private const val KEY = "max_cached_processes"
private const val STATE = "background-app-limit"
private const val APPLIED = "applied"
private const val PREVIOUS = "previous"
private val worker = Executors.newSingleThreadExecutor { Thread(it, "background-app-limit").apply { isDaemon = true } }
internal fun readCommand() = "device_config get activity_manager $KEY"
internal fun setCommand(limit: Int): String {
require(limit in 0..1024)
return "device_config put activity_manager $KEY $limit"
}
internal fun restoreCommand(previous: String?) =
if (previous == null) "device_config delete activity_manager $KEY" else "device_config put activity_manager $KEY $previous"
internal fun parse(output: String): String? = output.trim().takeIf { it.toIntOrNull() != null }
private fun state(context: Context) = context.applicationContext.getSharedPreferences(STATE, Context.MODE_PRIVATE)
fun applied(context: Context): Boolean = state(context).getBoolean(APPLIED, false)
fun applyAsync(context: Context, limit: Int) {
val app = context.applicationContext
worker.execute {
runCatching {
if (!applied(app)) {
val previous = parse(WirelessAdbFix.shell(app, readCommand()))
check(state(app).edit().putBoolean(APPLIED, true).putString(PREVIOUS, previous).commit()) { "previous value not saved" }
}
WirelessAdbFix.shell(app, setCommand(limit))
}.onSuccess { Log.i(TAG, "at most $limit cached app(s) while the session runs") }
.onFailure { Log.w(TAG, "limit not set: ${it.message}") }
}
}
fun restoreAsync(context: Context) {
val app = context.applicationContext
worker.execute {
if (!applied(app)) return@execute
val previous = state(app).getString(PREVIOUS, null)
runCatching { WirelessAdbFix.shell(app, restoreCommand(previous)) }
.onSuccess {
state(app).edit().putBoolean(APPLIED, false).remove(PREVIOUS).commit()
Log.i(TAG, "cached-app limit put back (${previous ?: "Android's own"})")
}
.onFailure { Log.w(TAG, "limit not put back yet: ${it.message}") }
}
}
}
@@ -0,0 +1,27 @@
package com.droiddeck.launcher.core
import com.droiddeck.launcher.gpu.GpuInfo
import com.droiddeck.launcher.gpu.SocNames
object CpuAllocationDefaults {
data class Allocation(val client: String, val game: String)
val device: Allocation? by lazy {
forDevice(SocNames.model(), GpuInfo.systemProperty("ro.board.platform"),
CpuCores.all.associateWith(CpuCores::maxGhz))
}
fun forDevice(model: String, platform: String, frequencies: Map<Int, Double?>): Allocation? {
val chip = model.trim().uppercase().substringBefore('-')
val gen2 = chip in setOf("SM8550", "QCS8550") ||
(chip.isEmpty() && platform.trim().equals("kalama", ignoreCase = true))
if (!gen2 || frequencies.size != 8 || frequencies.keys.any { it < 0 } ||
frequencies.values.any { it == null || !it.isFinite() || it <= 0.0 }) return null
val clusters = frequencies.entries.groupBy { it.value }.toSortedMap(compareBy { it ?: 0.0 }).values.toList()
if (clusters.map { it.size } != listOf(3, 4, 1)) return null
return Allocation(
client = CpuCores.format(clusters[2].map { it.key }.toSet()),
game = CpuCores.format(clusters[1].map { it.key }.toSet()),
)
}
}
@@ -152,17 +152,13 @@ object DeviceReport {
k("RAM total", FileUtils.sizeToString(mi.totalMem)) k("RAM total", FileUtils.sizeToString(mi.totalMem))
k("RAM available", FileUtils.sizeToString(mi.availMem)) k("RAM available", FileUtils.sizeToString(mi.availMem))
} }
val pm = runCatching { context.getSystemService(Context.POWER_SERVICE) as? PowerManager }.getOrNull() runCatching {
if (pm != null) { val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) k("Thermal status", thermalStatusName(pm.currentThermalStatus))
k("Thermal status", runCatching { thermalStatusName(pm.currentThermalStatus) }.getOrNull())
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
k("Thermal headroom (10 s)", runCatching { k("Thermal headroom (10 s)", pm.getThermalHeadroom(10).let { if (it.isNaN()) "not reported" else String.format(Locale.US, "%.2f", it) })
pm.getThermalHeadroom(10).let { if (it.isNaN()) "not reported" else String.format(Locale.US, "%.2f", it) }
}.getOrNull())
} }
k("Power saver", runCatching { pm.isPowerSaveMode }.getOrNull()) k("Power saver", pm.isPowerSaveMode)
} }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
val rate = runCatching { context.getSystemService(PerformanceHintManager::class.java)?.preferredUpdateRateNanos }.getOrNull() val rate = runCatching { context.getSystemService(PerformanceHintManager::class.java)?.preferredUpdateRateNanos }.getOrNull()
@@ -222,10 +218,7 @@ object DeviceReport {
val lm = LinuxVulkanDriverManager(context) val lm = LinuxVulkanDriverManager(context)
run { run {
val id = SessionPrefs.linuxDriver(context) val id = SessionPrefs.linuxDriver(context)
val label = if (id == com.droiddeck.launcher.gpu.QualcommSystemDriver.ID) com.droiddeck.launcher.gpu.QualcommSystemDriver.label() val label = if (id.isEmpty()) "runtime default (the Turnip built into the runtime)"
else if (com.droiddeck.launcher.gpu.QualcommDriverPackage.isRuntimeId(id))
"${com.droiddeck.launcher.gpu.QualcommDriverPackage.label(context, id)} ${com.droiddeck.launcher.gpu.QualcommDriverPackage.version(context, id)}"
else if (id.isEmpty()) "runtime default (the Turnip built into the runtime)"
else "${lm.getDriverName(id)} ${lm.getDriverVersion(id)}".trim() + else "${lm.getDriverName(id)} ${lm.getDriverVersion(id)}".trim() +
lm.getMinGlibc(id).let { if (it.isEmpty()) "" else " (glibc $it+)" } + lm.getMinGlibc(id).let { if (it.isEmpty()) "" else " (glibc $it+)" } +
if (lm.isInstalled(id)) "" else " [MISSING - falls back to the runtime's own]" if (lm.isInstalled(id)) "" else " [MISSING - falls back to the runtime's own]"
@@ -259,9 +252,6 @@ object DeviceReport {
EsyncPacks.status(LinuxRuntime.rootDir(context)).let { k("droiddeck-esync packs", "${it.installed} installed, ${it.wanted} wanted") } EsyncPacks.status(LinuxRuntime.rootDir(context)).let { k("droiddeck-esync packs", "${it.installed} installed, ${it.wanted} wanted") }
k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up") k("Linux x86 (FEX)", if (com.droiddeck.launcher.runtime.LinuxFex.ready(context)) "ready" else "not set up")
k("gamescope realtime", SessionPrefs.gamescopeRealtime(context)) k("gamescope realtime", SessionPrefs.gamescopeRealtime(context))
k("zRAM: compress Steam during games", SessionPrefs.zramClient(context))
k("RAM cap", SessionPrefs.ramCapMb(context).let { if (it > 0) "$it MB" else "off" })
k("VRAM cap", SessionPrefs.vramCapMb(context).let { if (it > 0) "$it MB" else "driver default" })
k("proot without seccomp", SessionPrefs.prootNoSeccomp(context)) k("proot without seccomp", SessionPrefs.prootNoSeccomp(context))
k("proot fast path", SessionPrefs.prootFastPath(context)) k("proot fast path", SessionPrefs.prootFastPath(context))
k("Guest host name", SessionPrefs.guestHostname(context)) k("Guest host name", SessionPrefs.guestHostname(context))
@@ -3,8 +3,6 @@ package com.droiddeck.launcher.core
import android.content.Context import android.content.Context
import android.content.SharedPreferences import android.content.SharedPreferences
import java.net.HttpURLConnection import java.net.HttpURLConnection
import java.net.InetSocketAddress
import java.net.Proxy
import java.net.URL import java.net.URL
import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.CountDownLatch import java.util.concurrent.CountDownLatch
@@ -22,7 +20,6 @@ object DownloadSource {
private const val KEY_MODE = "mode" private const val KEY_MODE = "mode"
private const val KEY_MIRROR = "mirror" private const val KEY_MIRROR = "mirror"
private const val KEY_CUSTOM = "custom" private const val KEY_CUSTOM = "custom"
private const val KEY_PROXY = "proxy"
private const val KEY_FASTEST = "fastest" private const val KEY_FASTEST = "fastest"
private const val PROBE = "https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/README.md" private const val PROBE = "https://raw.githubusercontent.com/Droid-Deck/DroidDeck/main/README.md"
@@ -178,22 +175,6 @@ object DownloadSource {
prefs(context)?.edit()?.putString(KEY_CUSTOM, normalizePrefix(prefix))?.apply() prefs(context)?.edit()?.putString(KEY_CUSTOM, normalizePrefix(prefix))?.apply()
} }
fun proxyHostPort(context: Context): String = prefs(context)?.getString(KEY_PROXY, "") ?: ""
fun setProxy(context: Context, value: String) {
prefs(context)?.edit()?.putString(KEY_PROXY, normalizeProxy(value))?.apply()
}
/** An HTTP proxy every Downloader connection uses, or null when none is configured. */
fun httpProxy(): Proxy? = proxyOf(prefs()?.getString(KEY_PROXY, "") ?: "")
internal fun proxyOf(value: String): Proxy? {
val host = value.substringBefore(':')
val port = value.substringAfter(':', "").toIntOrNull() ?: return null
if (host.isEmpty()) return null
return Proxy(Proxy.Type.HTTP, InetSocketAddress(host, port))
}
fun reset(context: Context) { fun reset(context: Context) {
lastGood = null lastGood = null
prefs(context)?.edit()?.clear()?.apply() prefs(context)?.edit()?.clear()?.apply()
@@ -224,11 +205,4 @@ object DownloadSource {
if (trimmed.isEmpty() || trimmed.startsWith("http://")) return "" if (trimmed.isEmpty() || trimmed.startsWith("http://")) return ""
return if (trimmed.startsWith("https://")) trimmed else "https://$trimmed" return if (trimmed.startsWith("https://")) trimmed else "https://$trimmed"
} }
internal fun normalizeProxy(value: String): String {
val trimmed = value.trim().removePrefix("http://").trimEnd('/')
val host = trimmed.substringBefore(':')
val port = trimmed.substringAfter(':', "").toIntOrNull() ?: 0
return if (host.isNotEmpty() && port in 1..65535) "$host:$port" else ""
}
} }
@@ -11,7 +11,6 @@ import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL; import java.net.URL;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.List; import java.util.List;
@@ -278,10 +277,7 @@ public final class Downloader {
} }
private static HttpURLConnection open(String url, int readTimeoutMs) throws java.io.IOException { private static HttpURLConnection open(String url, int readTimeoutMs) throws java.io.IOException {
// An explicit Proxy routes the connection through the app setting instead of the system-wide proxy. HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
Proxy proxy = DownloadSource.INSTANCE.httpProxy();
HttpURLConnection connection = (HttpURLConnection) (proxy != null
? new URL(url).openConnection(proxy) : new URL(url).openConnection());
connection.setConnectTimeout(CONNECT_TIMEOUT_MS); connection.setConnectTimeout(CONNECT_TIMEOUT_MS);
connection.setReadTimeout(readTimeoutMs); connection.setReadTimeout(readTimeoutMs);
connection.setInstanceFollowRedirects(true); connection.setInstanceFollowRedirects(true);
@@ -14,8 +14,6 @@ object GameEnvironmentOptions {
Option("MESA_SHADER_CACHE_MAX_SIZE", "1G", R.string.game_env_cache_size, Type.CHOICE, listOf("512M", "1G", "2G", "4G")), Option("MESA_SHADER_CACHE_MAX_SIZE", "1G", R.string.game_env_cache_size, Type.CHOICE, listOf("512M", "1G", "2G", "4G")),
Option("PROTON_LOG", "1", R.string.game_env_proton_log, Type.TOGGLE, listOf("0", "1")), Option("PROTON_LOG", "1", R.string.game_env_proton_log, Type.TOGGLE, listOf("0", "1")),
Option("PROTON_USE_WINED3D", "1", R.string.game_env_wined3d, Type.TOGGLE, listOf("0", "1")), Option("PROTON_USE_WINED3D", "1", R.string.game_env_wined3d, Type.TOGGLE, listOf("0", "1")),
Option("PROTON_DXVK_D3D8", "1", R.string.game_env_dxvk_d3d8, Type.TOGGLE, listOf("0", "1")),
Option("WINE_D3D_CONFIG", "renderer=vulkan", R.string.game_env_wined3d_renderer, Type.CHOICE, listOf("renderer=vulkan", "renderer=gl")),
Option("PROTON_USE_XALIA", "0", R.string.game_env_xalia, Type.TOGGLE, listOf("0", "1")), Option("PROTON_USE_XALIA", "0", R.string.game_env_xalia, Type.TOGGLE, listOf("0", "1")),
Option("PROTON_NO_NTSYNC", "1", R.string.game_env_no_ntsync, Type.TOGGLE, listOf("0", "1")), 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_ESYNC", "1", R.string.game_env_no_esync, Type.TOGGLE, listOf("0", "1")),
@@ -34,7 +32,6 @@ object GameEnvironmentOptions {
Option("MESA_EXTENSION_MAX_YEAR", "", 0, Type.TEXT), Option("MESA_EXTENSION_MAX_YEAR", "", 0, Type.TEXT),
Option("MESA_GL_VERSION_OVERRIDE", "", 0, Type.TEXT), Option("MESA_GL_VERSION_OVERRIDE", "", 0, Type.TEXT),
Option("PULSE_LATENCY_MSEC", "", 0, Type.NUMBER), Option("PULSE_LATENCY_MSEC", "", 0, Type.NUMBER),
Option("DROIDDECK_GAME_CORES", "", R.string.game_env_cores, Type.TEXT),
Option("DROIDDECK_ANTICHEAT_OFFLINE", "1", R.string.game_env_anticheat_offline, Type.TOGGLE, listOf("0", "1")), Option("DROIDDECK_ANTICHEAT_OFFLINE", "1", R.string.game_env_anticheat_offline, Type.TOGGLE, listOf("0", "1")),
Option("WINE_LARGE_ADDRESS_AWARE", "0", 0, Type.TOGGLE, listOf("0", "1")), Option("WINE_LARGE_ADDRESS_AWARE", "0", 0, Type.TOGGLE, listOf("0", "1")),
Option("WINEDLLOVERRIDES", "", 0, Type.TEXT), Option("WINEDLLOVERRIDES", "", 0, Type.TEXT),
@@ -8,11 +8,7 @@ object HostProcess {
private const val TAG = "HostProcess" private const val TAG = "HostProcess"
@JvmStatic @JvmStatic
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?): Int = fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?): Int {
start(command, env, dir, onExit, onLine, null)
@JvmStatic
fun start(command: String, env: Array<String>?, dir: File?, onExit: Consumer<Int>?, onLine: Consumer<String>?, outputFile: File?): Int {
val argv = split(command) val argv = split(command)
if (argv.isEmpty()) return -1 if (argv.isEmpty()) return -1
return try { return try {
@@ -23,10 +19,7 @@ object HostProcess {
if (eq > 0) builder.environment()[line.substring(0, eq)] = line.substring(eq + 1) if (eq > 0) builder.environment()[line.substring(0, eq)] = line.substring(eq + 1)
} }
builder.redirectErrorStream(true) builder.redirectErrorStream(true)
if (onLine == null) { if (onLine == null) builder.redirectOutput(File("/dev/null"))
if (outputFile == null) builder.redirectOutput(File("/dev/null"))
else builder.redirectOutput(ProcessBuilder.Redirect.appendTo(outputFile))
}
val process = builder.start() val process = builder.start()
val pid = pidOf(process) val pid = pidOf(process)
Log.i(TAG, "started pid $pid: ${argv.first()} (${argv.size - 1} arguments)") Log.i(TAG, "started pid $pid: ${argv.first()} (${argv.size - 1} arguments)")
@@ -76,7 +76,7 @@ object LogRedactor {
private const val ACCOUNT_VALUE = "(\"[^\"<\\r\\n]+\"|'[^'<\\r\\n]+'|[^\\s\"'<>&;,}]+)" private const val ACCOUNT_VALUE = "(\"[^\"<\\r\\n]+\"|'[^'<\\r\\n]+'|[^\\s\"'<>&;,}]+)"
private val ACCOUNT_KV = Regex( private val ACCOUNT_KV = Regex(
"(?i)(?<![A-Za-z0-9_])(account[_-]?name|account[_-]?id|user[_-]?name|epicusername)" + "(?i)(?<![A-Za-z0-9_])(account[_-]?name|user[_-]?name|epicusername)" +
"([\"']?\\s*[=:]\\s*|[\"']\\s+)" + ACCOUNT_VALUE "([\"']?\\s*[=:]\\s*|[\"']\\s+)" + ACCOUNT_VALUE
) )
private val LOGIN_KV = Regex( private val LOGIN_KV = Regex(
@@ -182,47 +182,25 @@ object WirelessAdbFix {
} }
fun setUsingSavedPairing(context: Context, enabled: Boolean) { fun setUsingSavedPairing(context: Context, enabled: Boolean) {
withSavedPairing(context) { appContext, host, port -> setChildProcessLimit(appContext, host, port, enabled) }
}
fun hasSavedPairing(context: Context): Boolean = savedConnection(context.applicationContext) != null
fun clearCachedApps(context: Context) {
shell(context, "am kill-all")
}
fun shell(context: Context, command: String): String {
var output = ""
withSavedPairing(context) { appContext, host, port ->
loadOrCreateIdentity(appContext)
Kadb.create(host, port).use { adb ->
val result = adb.shell(command)
check(result.exitCode == 0) { result.allOutput.ifBlank { appContext.getString(R.string.adbfix_command_failed, result.exitCode) } }
output = result.output
}
saveConnection(appContext, host, port)
}
return output
}
private fun withSavedPairing(context: Context, action: (Context, String, Int) -> Unit) {
val appContext = context.applicationContext val appContext = context.applicationContext
val saved = savedConnection(appContext) val saved = savedConnection(appContext)
?: error(appContext.getString(R.string.adbfix_no_pairing)) ?: error(appContext.getString(R.string.adbfix_no_pairing))
val cachedPort = saved.port val cachedPort = saved.port
if (cachedPort != null) { if (cachedPort != null) {
val cachedResult = runCatching { action(appContext, saved.host, cachedPort) } val cachedResult = runCatching {
setChildProcessLimit(appContext, saved.host, cachedPort, enabled)
}
if (cachedResult.isSuccess) return if (cachedResult.isSuccess) return
val discoveredPort = findConnectPort(appContext, saved.host) val discoveredPort = findConnectPort(appContext, saved.host)
if (discoveredPort != null && discoveredPort != cachedPort) { if (discoveredPort != null && discoveredPort != cachedPort) {
action(appContext, saved.host, discoveredPort) setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
} else { } else {
cachedResult.getOrThrow() cachedResult.getOrThrow()
} }
} else { } else {
val discoveredPort = findConnectPort(appContext, saved.host) val discoveredPort = findConnectPort(appContext, saved.host)
?: error(appContext.getString(R.string.adbfix_enter_address)) ?: error(appContext.getString(R.string.adbfix_enter_address))
action(appContext, saved.host, discoveredPort) setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
} }
} }
} }
@@ -70,7 +70,6 @@ import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberCoroutineScope
@@ -100,9 +99,7 @@ import kotlinx.coroutines.withContext
import java.io.File import java.io.File
import java.util.Date import java.util.Date
private enum class FileManagerNavigation { EXIT, RETURN_TO_START, BACK, UP } private enum class FileManagerNavigation { EXIT, RETURN_TO_START, BACK }
private const val HISTORY_LIMIT = 50
internal fun canNavigateUp(currentDir: File, currentRoot: File): Boolean = internal fun canNavigateUp(currentDir: File, currentRoot: File): Boolean =
currentDir != currentRoot && currentDir.parentFile?.exists() == true currentDir != currentRoot && currentDir.parentFile?.exists() == true
@@ -196,17 +193,10 @@ fun FileManagerScreen(
var favTick by remember { mutableIntStateOf(0) } var favTick by remember { mutableIntStateOf(0) }
var listingJob by remember { mutableStateOf<Job?>(null) } var listingJob by remember { mutableStateOf<Job?>(null) }
val history = remember { mutableStateListOf<Pair<File, File>>() }
var shownRoot by remember { mutableStateOf(initialRoot) }
fun loadDirectory(dir: File, resetScroll: Boolean = true, record: Boolean = true) { fun loadDirectory(dir: File, resetScroll: Boolean = true) {
if (cancellingNavigation) return if (cancellingNavigation) return
if (record && dir != currentDir) {
history.add(currentDir to shownRoot)
if (history.size > HISTORY_LIMIT) history.removeAt(0)
}
currentDir = dir currentDir = dir
shownRoot = currentRoot
if (pickMode) pickPrefs.edit().putString("lastFilePickerDir", dir.absolutePath).apply() if (pickMode) pickPrefs.edit().putString("lastFilePickerDir", dir.absolutePath).apply()
listingJob?.cancel() listingJob?.cancel()
listingJob = scope.launch { listingJob = scope.launch {
@@ -261,18 +251,6 @@ fun FileManagerScreen(
FileManagerNavigation.EXIT -> onExit?.invoke() FileManagerNavigation.EXIT -> onExit?.invoke()
FileManagerNavigation.RETURN_TO_START -> returnToStart() FileManagerNavigation.RETURN_TO_START -> returnToStart()
FileManagerNavigation.BACK -> { FileManagerNavigation.BACK -> {
if (showFavorites) showFavorites = false
else {
while (history.isNotEmpty() && !history.last().first.isDirectory) history.removeAt(history.lastIndex)
val previous = history.removeLastOrNull()
if (previous != null) {
currentRoot = previous.second
loadDirectory(previous.first, record = false)
} else if (canNavigateUp(currentDir, currentRoot)) currentDir.parentFile?.let { loadDirectory(it, record = false) }
else onExit?.invoke()
}
}
FileManagerNavigation.UP -> {
if (showFavorites) showFavorites = false if (showFavorites) showFavorites = false
else if (canNavigateUp(currentDir, currentRoot)) currentDir.parentFile?.let { loadDirectory(it) } else if (canNavigateUp(currentDir, currentRoot)) currentDir.parentFile?.let { loadDirectory(it) }
else onExit?.invoke() else onExit?.invoke()
@@ -285,7 +263,7 @@ fun FileManagerScreen(
if (isOperationActive()) pendingNavigation = action else navigate(action) if (isOperationActive()) pendingNavigation = action else navigate(action)
} }
BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty()) { BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot) {
requestNavigation(FileManagerNavigation.BACK) requestNavigation(FileManagerNavigation.BACK)
} }
@@ -695,7 +673,7 @@ fun FileManagerScreen(
.background(MaterialTheme.colorScheme.surfaceContainer) .background(MaterialTheme.colorScheme.surfaceContainer)
.padding(horizontal = 8.dp, vertical = 6.dp), .padding(horizontal = 8.dp, vertical = 6.dp),
) { ) {
IconButton(onClick = { requestNavigation(FileManagerNavigation.UP) }, enabled = canGoUp && !cancellingNavigation) { IconButton(onClick = { requestNavigation(FileManagerNavigation.BACK) }, enabled = canGoUp && !cancellingNavigation) {
Icon(Icons.Filled.ArrowBack, stringResource(R.string.fm_back), tint = MaterialTheme.colorScheme.primary) Icon(Icons.Filled.ArrowBack, stringResource(R.string.fm_back), tint = MaterialTheme.colorScheme.primary)
} }
@@ -1111,7 +1089,7 @@ fun FileManagerScreen(
contentPadding = PaddingValues(8.dp), contentPadding = PaddingValues(8.dp),
) { ) {
if (canGoUp) item(key = "..", span = { GridItemSpan(maxLineSpan) }) { if (canGoUp) item(key = "..", span = { GridItemSpan(maxLineSpan) }) {
ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.UP) }) ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.BACK) })
} }
items(shownEntries, key = { it.absolutePath }) { file -> items(shownEntries, key = { it.absolutePath }) { file ->
val isFav = remember(file.absolutePath, favTick) { val isFav = remember(file.absolutePath, favTick) {
@@ -1177,7 +1155,7 @@ fun FileManagerScreen(
} else } else
LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) { LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) {
if (canGoUp) item(key = "..") { if (canGoUp) item(key = "..") {
ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.UP) }) ParentFolderRow(compact = compactRows, onTap = { requestNavigation(FileManagerNavigation.BACK) })
} }
if (entries.isEmpty()) { if (entries.isEmpty()) {
item { item {
@@ -29,50 +29,6 @@ object StorageRoots {
val seeds = LinkedHashSet<File>() val seeds = LinkedHashSet<File>()
} }
private val EXTERNAL_MOUNT_TYPES = setOf(
"vfat", "exfat", "texfat", "ntfs", "ntfs3", "fuseblk", "fuse", "sdcardfs",
)
internal data class MountPoint(val target: File, val type: String)
internal fun parseMountPoints(mounts: String): List<MountPoint> {
val out = ArrayList<MountPoint>()
for (line in mounts.lineSequence()) {
val parts = line.split(' ')
if (parts.size < 3) continue
out.add(MountPoint(File(parts[1].replace("\\040", " ")), parts[2].lowercase()))
}
return out.distinct()
}
internal fun isExternalMount(mount: MountPoint): Boolean {
val path = mount.target.path
val name = when {
path.startsWith("/storage/") -> path.removePrefix("/storage/")
path.startsWith("/mnt/media_rw/") -> path.removePrefix("/mnt/media_rw/")
path.startsWith("/mnt/") -> path.removePrefix("/mnt/")
else -> return false
}
if ('/' in name || name.isEmpty() || name == "emulated" || name == "self") return false
if (mount.type in EXTERNAL_MOUNT_TYPES) {
if (path.startsWith("/mnt/") && !path.startsWith("/mnt/media_rw/")) {
val lower = name.lowercase()
if (!lower.contains("usb") && !lower.contains("otg") &&
!lower.contains("udisk") && !lower.contains("disk")
) return false
}
return true
}
// vold-managed locations only hold removable volumes, whatever the fstype is.
return path.startsWith("/storage/") || path.startsWith("/mnt/media_rw/")
}
internal fun parseExternalMounts(mounts: String): List<File> =
parseMountPoints(mounts).filter(::isExternalMount).map { it.target }
fun externalMounts(): List<File> =
runCatching { parseExternalMounts(File("/proc/mounts").readText()) }.getOrDefault(emptyList())
fun list(context: Context): List<StorageRoot> { fun list(context: Context): List<StorageRoot> {
val volumes = LinkedHashMap<String, Volume>() val volumes = LinkedHashMap<String, Volume>()
@@ -88,31 +44,21 @@ object StorageRoots {
val storageManager = context.getSystemService(StorageManager::class.java) val storageManager = context.getSystemService(StorageManager::class.java)
storageManager?.storageVolumes.orEmpty() storageManager?.storageVolumes.orEmpty()
.filter { present(it.state) } .filter { isMounted(it.state) }
.forEachIndexed { index, volume -> .forEach { volume ->
val uuid = volume.uuid?.takeIf { it.isNotBlank() } val uuid = volume.uuid?.takeIf { it.isNotBlank() }
val dirName = volume.directory?.name?.takeIf { it.isNotBlank() } val entry = volumeOf(if (volume.isPrimary) PRIMARY_KEY else uuid ?: return@forEach)
// Unmounted volumes often report neither uuid nor directory; never drop the
// volume or a plugged-in drive stays invisible with no explanation.
val descSlug = volume.getDescription(context)?.trim()
?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) }
?.replace(Regex("[^A-Za-z0-9._-]+"), "-")
val entry = volumeOf(if (volume.isPrimary) PRIMARY_KEY else uuid ?: dirName ?: descSlug ?: "volume-$index")
entry.removable = !volume.isPrimary && volume.isRemovable entry.removable = !volume.isPrimary && volume.isRemovable
if (entry.label == null) entry.label = labelFor(context, volume, uuid ?: dirName ?: descSlug) if (entry.label == null) entry.label = labelFor(context, volume, uuid)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
volume.directory?.let { entry.candidates += it } volume.directory?.let { entry.candidates += it }
} }
val name = uuid ?: dirName if (uuid != null) {
if (name != null) { entry.candidates += File("/storage/$uuid")
entry.candidates += File("/storage/$name") entry.candidates += File("/mnt/media_rw/$uuid")
entry.candidates += File("/mnt/media_rw/$name")
// Only strict uuid matches own an app directory; a loose match would
// attach another volume's folder to this entry.
if (uuid != null) appDirs.filter { belongsTo(storageManager!!, it, volume) }
.forEach { entry.seeds += it }
} }
appDirs.filter { belongsTo(storageManager!!, it, volume) }.forEach { entry.seeds += it }
} }
File("/storage").listFiles().orEmpty().forEach { child -> File("/storage").listFiles().orEmpty().forEach { child ->
@@ -122,13 +68,6 @@ object StorageRoots {
File("/mnt/media_rw").listFiles().orEmpty().forEach { child -> File("/mnt/media_rw").listFiles().orEmpty().forEach { child ->
if (child.isDirectory) volumeOf(child.name).candidates += child if (child.isDirectory) volumeOf(child.name).candidates += child
} }
// USB OTG drives do not always appear as storage volumes or under /storage for
// third-party apps, but their kernel mounts are still visible in /proc/mounts.
for (mount in externalMounts()) {
val entry = volumeOf(mount.name)
if (entry.label == null) entry.label = mount.name
entry.candidates += mount
}
appDirs.forEach { dir -> appDirs.forEach { dir ->
val root = volumeRootOf(dir) ?: return@forEach val root = volumeRootOf(dir) ?: return@forEach
@@ -202,19 +141,15 @@ object StorageRoots {
private fun labelFor(context: Context, volume: StorageVolume, uuid: String?): String { private fun labelFor(context: Context, volume: StorageVolume, uuid: String?): String {
if (volume.isPrimary) return context.getString(R.string.fm_drive_internal) if (volume.isPrimary) return context.getString(R.string.fm_drive_internal)
val description = volume.getDescription(context)?.trim()
if (!description.isNullOrBlank() && !description.equals("android", ignoreCase = true)) return description
if (volume.isRemovable) return context.getString(R.string.fm_drive_sd) if (volume.isRemovable) return context.getString(R.string.fm_drive_sd)
return uuid val description = volume.getDescription(context)?.trim()
return description?.takeIf { it.isNotBlank() && !it.equals("android", ignoreCase = true) }
?: uuid
?: context.getString(R.string.fm_drive_storage) ?: context.getString(R.string.fm_drive_storage)
} }
private fun isEmulated(dir: File): Boolean = dir.absolutePath.startsWith(EMULATED_PREFIX) private fun isEmulated(dir: File): Boolean = dir.absolutePath.startsWith(EMULATED_PREFIX)
private fun present(state: String?): Boolean =
isMounted(state) || state == Environment.MEDIA_UNMOUNTED || state == Environment.MEDIA_CHECKING ||
state == Environment.MEDIA_NOFS || state == Environment.MEDIA_UNMOUNTABLE
private fun isMounted(state: String?): Boolean = private fun isMounted(state: String?): Boolean =
state == Environment.MEDIA_MOUNTED || state == Environment.MEDIA_MOUNTED_READ_ONLY state == Environment.MEDIA_MOUNTED || state == Environment.MEDIA_MOUNTED_READ_ONLY
@@ -4,9 +4,7 @@ import android.content.Context
import android.graphics.Bitmap import android.graphics.Bitmap
import android.util.Log import android.util.Log
import com.droiddeck.launcher.files.PeIconExtractor import com.droiddeck.launcher.files.PeIconExtractor
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreArt import com.droiddeck.launcher.stores.StoreArt
import com.droiddeck.launcher.stores.StoreGameSidecar import com.droiddeck.launcher.stores.StoreGameSidecar
import org.json.JSONObject import org.json.JSONObject
@@ -77,18 +75,14 @@ object AddedGameArt {
) )
} }
private fun storeArt(context: Context, game: AddedGames.Game): BattleNet.Art? =
if (game.source != Store.BATTLENET.id) null else game.storeId?.let(BattleNet::title)?.let { BattleNet.art(context, it) }
fun resolve(context: Context, game: AddedGames.Game): Art { fun resolve(context: Context, game: AddedGames.Game): Art {
val own = local(game) val own = local(game)
val cache = cacheDir(context, game) val cache = cacheDir(context, game)
val store = storeArt(context, game)
fun cached(name: String) = File(cache, name).takeIf { it.isFile } fun cached(name: String) = File(cache, name).takeIf { it.isFile }
return Art( return Art(
portrait = chosen(cache, Slot.COVER) ?: own.portrait ?: store?.cover ?: cached("p.jpg") ?: exeArt(context, game, cover = true), portrait = chosen(cache, Slot.COVER) ?: own.portrait ?: cached("p.jpg") ?: exeArt(context, game, cover = true),
header = chosen(cache, Slot.WIDE) ?: own.header ?: store?.header ?: cached("header.jpg") ?: exeArt(context, game, cover = false), header = chosen(cache, Slot.WIDE) ?: own.header ?: cached("header.jpg") ?: exeArt(context, game, cover = false),
hero = chosen(cache, Slot.BACKGROUND) ?: own.hero ?: store?.header ?: cached("hero.jpg"), hero = chosen(cache, Slot.BACKGROUND) ?: own.hero ?: cached("hero.jpg"),
logo = chosen(cache, Slot.LOGO) ?: own.logo ?: cached("logo.png"), logo = chosen(cache, Slot.LOGO) ?: own.logo ?: cached("logo.png"),
icon = chosen(cache, Slot.ICON) ?: own.icon ?: cached("icon-sgdb.png") ?: exeIcon(context, game), icon = chosen(cache, Slot.ICON) ?: own.icon ?: cached("icon-sgdb.png") ?: exeIcon(context, game),
) )
@@ -97,16 +91,15 @@ object AddedGameArt {
fun describe(context: Context, game: AddedGames.Game): List<SlotState> { fun describe(context: Context, game: AddedGames.Game): List<SlotState> {
val own = local(game) val own = local(game)
val cache = cacheDir(context, game) val cache = cacheDir(context, game)
val store = storeArt(context, game)
fun cached(name: String): Pair<File, String>? = File(cache, name).takeIf { it.isFile }?.let { f -> fun cached(name: String): Pair<File, String>? = File(cache, name).takeIf { it.isFile }?.let { f ->
f to (File(cache, "$name.src").takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: STEAM) f to (File(cache, "$name.src").takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: STEAM)
} }
return Slot.values().map { slot -> return Slot.values().map { slot ->
chosen(cache, slot)?.let { return@map SlotState(slot, it, chosenSource(context, game, slot).first.ifEmpty { FILE }, true) } chosen(cache, slot)?.let { return@map SlotState(slot, it, chosenSource(context, game, slot).first.ifEmpty { FILE }, true) }
val auto: Pair<File, String>? = when (slot) { val auto: Pair<File, String>? = when (slot) {
Slot.COVER -> own.portrait?.let { it to FOLDER } ?: store?.cover?.let { it to AUTO } ?: cached("p.jpg") ?: exeArt(context, game, cover = true)?.let { it to EXE } Slot.COVER -> own.portrait?.let { it to FOLDER } ?: cached("p.jpg") ?: exeArt(context, game, cover = true)?.let { it to EXE }
Slot.WIDE -> own.header?.let { it to FOLDER } ?: store?.header?.let { it to AUTO } ?: cached("header.jpg") ?: exeArt(context, game, cover = false)?.let { it to EXE } Slot.WIDE -> own.header?.let { it to FOLDER } ?: cached("header.jpg") ?: exeArt(context, game, cover = false)?.let { it to EXE }
Slot.BACKGROUND -> own.hero?.let { it to FOLDER } ?: store?.header?.let { it to AUTO } ?: cached("hero.jpg") Slot.BACKGROUND -> own.hero?.let { it to FOLDER } ?: cached("hero.jpg")
Slot.LOGO -> own.logo?.let { it to FOLDER } ?: cached("logo.png") Slot.LOGO -> own.logo?.let { it to FOLDER } ?: cached("logo.png")
Slot.ICON -> own.icon?.let { it to FOLDER } ?: File(cache, "icon-sgdb.png").takeIf { it.isFile }?.let { it to SGDB } Slot.ICON -> own.icon?.let { it to FOLDER } ?: File(cache, "icon-sgdb.png").takeIf { it.isFile }?.let { it to SGDB }
?: exeIcon(context, game)?.let { it to EXE } ?: exeIcon(context, game)?.let { it to EXE }
@@ -260,13 +253,12 @@ object AddedGameArt {
internal fun missing(context: Context, game: AddedGames.Game): Set<Slot> { internal fun missing(context: Context, game: AddedGames.Game): Set<Slot> {
val own = local(game) val own = local(game)
val cache = cacheDir(context, game) val cache = cacheDir(context, game)
val store = storeArt(context, game)
fun has(slot: Slot, mine: File?, cached: String) = chosen(cache, slot) != null || mine != null || File(cache, cached).isFile fun has(slot: Slot, mine: File?, cached: String) = chosen(cache, slot) != null || mine != null || File(cache, cached).isFile
return Slot.values().filterNot { slot -> return Slot.values().filterNot { slot ->
when (slot) { when (slot) {
Slot.COVER -> has(slot, own.portrait ?: store?.cover, "p.jpg") Slot.COVER -> has(slot, own.portrait, "p.jpg")
Slot.WIDE -> has(slot, own.header ?: store?.header, "header.jpg") Slot.WIDE -> has(slot, own.header, "header.jpg")
Slot.BACKGROUND -> has(slot, own.hero ?: store?.header, "hero.jpg") Slot.BACKGROUND -> has(slot, own.hero, "hero.jpg")
Slot.LOGO -> has(slot, own.logo, "logo.png") Slot.LOGO -> has(slot, own.logo, "logo.png")
Slot.ICON -> has(slot, own.icon, "icon-sgdb.png") Slot.ICON -> has(slot, own.icon, "icon-sgdb.png")
} }
@@ -330,10 +322,6 @@ object AddedGameArt {
} }
internal fun steamMatch(context: Context, game: AddedGames.Game, search: (String) -> Int?): SteamMatch.Match { internal fun steamMatch(context: Context, game: AddedGames.Game, search: (String) -> Int?): SteamMatch.Match {
if (game.source == Store.BATTLENET.id) {
val id = game.storeId?.let(BattleNet::title)?.steam
return SteamMatch.Match(id, if (id == null) SteamMatch.Certainty.NONE else SteamMatch.Certainty.FILES, Store.BATTLENET.id, System.currentTimeMillis())
}
val match = SteamMatch.resolve(context, game.folder.path, game.exe, game.name, legacy = File(cacheDir(context, game), "steam-appid"), search = search) val match = SteamMatch.resolve(context, game.folder.path, game.exe, game.name, legacy = File(cacheDir(context, game), "steam-appid"), search = search)
match.appId?.let { Log.i(TAG, "${game.name}: Steam app $it (${match.certainty.name.lowercase()})") } match.appId?.let { Log.i(TAG, "${game.name}: Steam app $it (${match.certainty.name.lowercase()})") }
return match return match
@@ -373,14 +361,14 @@ object AddedGameArt {
.filter { it.second > 0 && it.first.isNotEmpty() } .filter { it.second > 0 && it.first.isNotEmpty() }
.maxByOrNull { it.second }?.first .maxByOrNull { it.second }?.first
internal fun search(name: String): String? { private fun search(name: String): String? {
val term = name.replace(EDITION, " ").trim().ifEmpty { name } val term = name.replace(EDITION, " ").trim().ifEmpty { name }
val json = get(STORE_SEARCH + URLEncoder.encode(term, "UTF-8"))?.toString(Charsets.UTF_8) ?: return null val json = get(STORE_SEARCH + URLEncoder.encode(term, "UTF-8"))?.toString(Charsets.UTF_8) ?: return null
val items = JSONObject(json).optJSONArray("items") ?: return null val items = JSONObject(json).optJSONArray("items") ?: return null
return pickStoreResult(name, (0 until items.length()).map { items.getJSONObject(it) }.map { it.optString("id") to it.optString("name") }) return pickStoreResult(name, (0 until items.length()).map { items.getJSONObject(it) }.map { it.optString("id") to it.optString("name") })
} }
internal fun download(id: String, cache: File, slots: Set<Slot> = Slot.entries.toSet()): Boolean { private fun download(id: String, cache: File, slots: Set<Slot>): Boolean {
var got = false var got = false
for ((slot, remote, localName) in listOf( for ((slot, remote, localName) in listOf(
Triple(Slot.COVER, "library_600x900.jpg", "p.jpg"), Triple(Slot.WIDE, "header.jpg", "header.jpg"), Triple(Slot.COVER, "library_600x900.jpg", "p.jpg"), Triple(Slot.WIDE, "header.jpg", "header.jpg"),
@@ -79,18 +79,6 @@ object AddedGames {
return null return null
} }
fun hostPath(context: Context, guest: String): File? {
if (!guest.startsWith("/") || guest.split('/').any { it == ".." }) return null
val mapped = roots(context).map { it.host to it.guest } + StoreInstallRoot.externalRoots(context) +
listOfNotNull(GameStorage.effective(context)?.let { File(it.path) to LIBRARY }) +
(android.os.Environment.getExternalStorageDirectory() to "/root/Storage")
for ((host, root) in mapped.sortedByDescending { it.second.length }) {
if (guest == root) return host
if (guest.startsWith("$root/")) return File(host, guest.removePrefix("$root/"))
}
return File(LinuxRuntime.rootDir(context), guest.removePrefix("/"))
}
fun candidates(folder: File): List<File> = rank(folder).exes fun candidates(folder: File): List<File> = rank(folder).exes
fun rank(folder: File): GameExePicker.Ranking { fun rank(folder: File): GameExePicker.Ranking {
@@ -189,9 +177,6 @@ object AddedGames {
scanGame(context, folder, out, single = entry) scanGame(context, folder, out, single = entry)
} }
for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out) for (folder in StoreInstallRoot.gameFolders(context)) if (StoreInstallRoot.isFinished(folder)) scanGame(context, folder, out)
for (game in com.droiddeck.launcher.runtime.BattleNet.games(context)) {
if (game.folder.path !in removed) com.droiddeck.launcher.runtime.BattleNet.shortcut(context, game)?.let(out::add)
}
return out.distinctBy { it.folder.canonicalPath } return out.distinctBy { it.folder.canonicalPath }
} }
@@ -402,17 +387,11 @@ object AddedGames {
} }
} }
private class LoginUser(val id: String, val mostRecent: Boolean, val autoLogin: Boolean, val timestamp: Long)
internal fun accountConfig(root: File): File? { internal fun accountConfig(root: File): File? {
val users = runCatching { File(root, "config/loginusers.vdf").readText() }.getOrDefault("") val users = runCatching { File(root, "config/loginusers.vdf").readText() }.getOrDefault("")
val recent = Regex(""""(\d{5,})"\s*\{([^}]*)\}""").findAll(users).map { val recent = Regex(""""(\d{5,})"\s*\{([^}]*)\}""").findAll(users)
val body = it.groupValues[2] .lastOrNull { Regex(""""MostRecent"\s*"1"""").containsMatchIn(it.groupValues[2]) }
LoginUser(it.groupValues[1], Regex(""""MostRecent"\s*"1"""").containsMatchIn(body), Regex(""""AutoLogin"\s*"1"""").containsMatchIn(body), val account = recent?.groupValues?.get(1)?.toLongOrNull()?.let { (it - 76561197960265728L).toString() }
Regex(""""timestamp"\s*"(\d+)"""").find(body)?.groupValues?.get(1)?.toLongOrNull() ?: 0L)
}.filter { it.mostRecent || it.autoLogin || it.timestamp > 0 }.toList().asReversed()
.maxWithOrNull(compareBy<LoginUser>({ it.mostRecent }, { it.autoLogin }, { it.timestamp }))
val account = recent?.id?.toLongOrNull()?.let { (it - 76561197960265728L).toString() }
?: File(root, "userdata").list()?.filter { it.isNotEmpty() && it.all(Char::isDigit) && it != "0" }?.singleOrNull() ?: File(root, "userdata").list()?.filter { it.isNotEmpty() && it.all(Char::isDigit) && it != "0" }?.singleOrNull()
return account?.let { File(root, "userdata/$it/config") } return account?.let { File(root, "userdata/$it/config") }
} }
@@ -257,18 +257,14 @@ object AutoComponents {
private const val FINDINGS = "wincomp-findings.json" private const val FINDINGS = "wincomp-findings.json"
private const val DETECTORS = "d3"
internal fun signature(context: Context, game: Library.SteamGame): String { internal fun signature(context: Context, game: Library.SteamGame): String {
val folder = game.gameFiles val folder = game.gameFiles
val parts = listOfNotNull( val parts = listOfNotNull(
DETECTORS,
folder?.lastModified(), folder?.lastModified(),
folder?.let { SteamRedists.manifest(it, game.appId)?.lastModified() }, folder?.let { SteamRedists.manifest(it, game.appId)?.lastModified() },
folder?.let { StoreGameSidecar.file(it).lastModified() }, folder?.let { StoreGameSidecar.file(it).lastModified() },
folder?.let { File(it, "fuel.json").lastModified() }, folder?.let { File(it, "fuel.json").lastModified() },
folder?.listFiles { f -> f.name.lowercase().let { it.startsWith("installscript") && it.endsWith(".vdf") } }
?.maxOfOrNull { it.lastModified() },
SteamAppInfo.appinfoFile(context).lastModified(), SteamAppInfo.appinfoFile(context).lastModified(),
folder?.let { SteamMatch.get(context, it.path) }?.let { "${it.appId}/${it.certainty}" }, folder?.let { SteamMatch.get(context, it.path) }?.let { "${it.appId}/${it.certainty}" },
steamAppOf(context, game)?.let { SteamAppInfo.state(context, it) }, steamAppOf(context, game)?.let { SteamAppInfo.state(context, it) },
@@ -11,7 +11,7 @@ object GameRemoval {
enum class Kind { STORE, SHORTCUT, LAUNCHER } enum class Kind { STORE, SHORTCUT, LAUNCHER }
fun kind(game: Library.SteamGame): Kind = when { fun kind(game: Library.SteamGame): Kind = when {
game.library == Library.EPIC_LAUNCHER || game.library == Library.BATTLENET_LAUNCHER -> Kind.LAUNCHER game.library == Library.EPIC_LAUNCHER -> Kind.LAUNCHER
game.library == Library.ADDED && game.source == Library.ADDED -> Kind.SHORTCUT game.library == Library.ADDED && game.source == Library.ADDED -> Kind.SHORTCUT
else -> Kind.STORE else -> Kind.STORE
} }
@@ -22,17 +22,11 @@ object Library {
SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId, logo) SteamGame(appId, name, art, library, gameId, hero, lastPlayed, gameFiles, protonPrefix, icon, source, storeId, logo)
val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId) val gameIdString: String get() = java.lang.Long.toUnsignedString(gameId)
val profileKey: String get() = when { val profileKey: String get() = if (library == ADDED) java.lang.Integer.toUnsignedString(appId) else appId.toString()
source == com.droiddeck.launcher.stores.Store.BATTLENET.id -> com.droiddeck.launcher.runtime.BattleNet.APP_ID.toString()
library == ADDED -> java.lang.Integer.toUnsignedString(appId)
else -> appId.toString()
}
} }
const val ADDED = "added" const val ADDED = "added"
const val EPIC_LAUNCHER = "epic-launcher" const val EPIC_LAUNCHER = "epic-launcher"
const val EPIC_LAUNCHER_NAME = "Epic Games Launcher" const val EPIC_LAUNCHER_NAME = "Epic Games Launcher"
const val BATTLENET_LAUNCHER = "battlenet-launcher"
const val XBOX_CLOUD = "xbox-cloud"
const val SOURCE_STEAM = "steam" const val SOURCE_STEAM = "steam"
class Rom(val name: String, val hostPath: File, val guestPath: String, val emulatorId: String, val art: File? = null) class Rom(val name: String, val hostPath: File, val guestPath: String, val emulatorId: String, val art: File? = null)
@@ -52,14 +46,12 @@ object Library {
1054830, 1054830,
1070560, 1070560,
1113280, 1113280,
1161040,
1245040, 1245040,
1391110, 1391110,
1420170, 1420170,
1493710, 1493710,
1580130, 1580130,
1628350, 1628350,
1826330,
1887720, 1887720,
2180100, 2180100,
228980, 228980,
@@ -112,10 +104,7 @@ object Library {
.firstOrNull { it.isDirectory } .firstOrNull { it.isDirectory }
} }
fun steamGames( fun steamGames(context: Context, strictRead: Boolean = false, arch: String = SessionPrefs.activeSteamClientArch(context)): List<SteamGame> {
context: Context, strictRead: Boolean = false, arch: String = SessionPrefs.activeSteamClientArch(context),
withShared: Boolean = true,
): List<SteamGame> {
val root = SessionPrefs.steamRoot(context, arch) val root = SessionPrefs.steamRoot(context, arch)
val cache = File(root, "appcache/librarycache") val cache = File(root, "appcache/librarycache")
val libraries = steamLibraries(context, arch) val libraries = steamLibraries(context, arch)
@@ -132,9 +121,8 @@ object Library {
val name = NAME.find(text)?.groupValues?.get(1)?.trim().orEmpty() val name = NAME.find(text)?.groupValues?.get(1)?.trim().orEmpty()
val flags = STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0 val flags = STATE.find(text)?.groupValues?.get(1)?.toIntOrNull() ?: 0
if (name.isEmpty() || flags and 4 == 0) return@forEach if (name.isEmpty() || flags and 4 == 0) return@forEach
val images = SteamCacheImages(File(cache, appId.toString())) val art = steamCacheImage(cache, appId, STEAM_CAPSULES)
val art = images.find(STEAM_CAPSULES) val hero = steamCacheImage(cache, appId, STEAM_HEROES)
val hero = images.find(STEAM_HEROES)
val lastPlayed = LAST_PLAYED.find(text)?.groupValues?.get(1)?.toLongOrNull() ?: 0L val lastPlayed = LAST_PLAYED.find(text)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
val installDir = INSTALL_DIR.find(text)?.groupValues?.get(1)?.trim() val installDir = INSTALL_DIR.find(text)?.groupValues?.get(1)?.trim()
?.takeIf { it.isNotEmpty() && it != "." && it != ".." && '/' !in it && '\\' !in it } ?.takeIf { it.isNotEmpty() && it != "." && it != ".." && '/' !in it && '\\' !in it }
@@ -143,25 +131,15 @@ object Library {
appId, name, art, label, hero = hero, lastPlayed = lastPlayed, appId, name, art, label, hero = hero, lastPlayed = lastPlayed,
gameFiles = gameFiles, gameFiles = gameFiles,
protonPrefix = protonPrefix(context, appId.toLong(), library, roots), protonPrefix = protonPrefix(context, appId.toLong(), library, roots),
icon = images.icon(), icon = steamCacheImage(cache, appId, listOf("icon.jpg", "icon.png"))
logo = images.find(STEAM_LOGOS), ?: File(cache, appId.toString()).listFiles()?.firstOrNull { it.isFile && STEAM_ICON.matches(it.name) },
logo = steamCacheImage(cache, appId, STEAM_LOGOS),
)) ))
} }
} }
if (withShared) {
val other = if (arch == "x86_64") "arm64" else "x86_64"
val shared = sharedApps(context, arch) - out.keys
if (shared.isNotEmpty()) runCatching { steamGames(context, arch = other, withShared = false) }.getOrDefault(emptyList())
.filter { it.appId in shared }.forEach { out[it.appId] = it }
}
return out.values.toList() return out.values.toList()
} }
internal fun sharedApps(context: Context, arch: String): Set<Int> {
val view = File(LinuxRuntime.rootDir(context), "root/.droiddeck-x64/shared/${if (arch == "x86_64") "arm64" else "x86-64"}/steamapps")
return view.list().orEmpty().mapNotNull { Regex("appmanifest_(\\d+)\\.acf").matchEntire(it)?.groupValues?.get(1)?.toIntOrNull() }.toSet()
}
fun steamLibraryArt(context: Context): List<Pair<Int, File>> { fun steamLibraryArt(context: Context): List<Pair<Int, File>> {
val root = SessionPrefs.activeSteamRoot(context) val root = SessionPrefs.activeSteamRoot(context)
val cache = File(root, "appcache/librarycache") val cache = File(root, "appcache/librarycache")
@@ -209,24 +187,9 @@ object Library {
(runCatching { g.folder.canonicalPath }.getOrDefault(g.folder.absolutePath) !in claimed && (runCatching { g.folder.canonicalPath }.getOrDefault(g.folder.absolutePath) !in claimed &&
AddedGames.guestPath(context, g.folder).let { it == null || it !in claimed }) AddedGames.guestPath(context, g.folder).let { it == null || it !in claimed })
} }
val played = shortcutsLastPlayed(SessionPrefs.steamRoot(context, arch)) return (steam + own.map { g -> addedGame(context, g, roots) }).distinctBy { it.gameId }
return (steam + own.map { g -> addedGame(context, g, roots, played[g.appId] ?: 0L) }).distinctBy { it.gameId }
} }
/** Steam's LastPlayTime for each non-Steam shortcut, by its unsigned shortcut app id. */
internal fun shortcutsLastPlayed(root: File): Map<Long, Long> = runCatching {
val config = AddedGames.accountConfig(root) ?: return emptyMap()
val bytes = File(config, "shortcuts.vdf").takeIf { it.isFile }?.readBytes() ?: return emptyMap()
val vdf = SteamAppInfo.readMap(java.nio.ByteBuffer.wrap(bytes).order(java.nio.ByteOrder.LITTLE_ENDIAN), null)
(vdf["shortcuts"] as? Map<*, *>)?.values?.filterIsInstance<Map<*, *>>()?.mapNotNull { s ->
fun int(key: String) = s.entries.firstOrNull { (it.key as? String).equals(key, ignoreCase = true) }
?.let { (it.value as? String)?.toLongOrNull() }?.and(0xFFFFFFFFL)
val id = int("appid") ?: return@mapNotNull null
val time = int("LastPlayTime")?.takeIf { it > 0L } ?: return@mapNotNull null
id to time
}?.toMap()
}.getOrNull().orEmpty()
fun claimedFolders(steam: List<SteamGame>): Set<String> = steam.filter(::fromSteamClient).flatMap { g -> fun claimedFolders(steam: List<SteamGame>): Set<String> = steam.filter(::fromSteamClient).flatMap { g ->
val dir = g.gameFiles ?: return@flatMap emptyList() val dir = g.gameFiles ?: return@flatMap emptyList()
listOfNotNull( listOfNotNull(
@@ -235,35 +198,25 @@ object Library {
) )
}.toSet() }.toSet()
fun addedGame( fun addedGame(context: Context, g: AddedGames.Game, roots: List<File> = steamLibraries(context).map { it.first }): SteamGame =
context: Context, g: AddedGames.Game, roots: List<File> = steamLibraries(context).map { it.first },
lastPlayed: Long = 0L,
): SteamGame =
AddedGameArt.resolve(context, g).let { art -> AddedGameArt.resolve(context, g).let { art ->
SteamGame( SteamGame(
g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, ADDED, g.gameId, g.steamAppId ?: g.appId.toInt(), g.name, art.portrait ?: art.header, ADDED, g.gameId,
hero = art.hero ?: art.header, lastPlayed = lastPlayed, gameFiles = g.folder, hero = art.hero ?: art.header, 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 } protonPrefix = protonPrefix(context, g.steamAppId?.toLong() ?: g.appId, libraries = roots),
else protonPrefix(context, g.steamAppId?.toLong() ?: g.appId, libraries = roots),
icon = art.icon?.takeIf { it.extension.lowercase() != "ico" }, icon = art.icon?.takeIf { it.extension.lowercase() != "ico" },
source = g.source, storeId = g.storeId, source = g.source, storeId = g.storeId,
logo = art.logo, logo = art.logo,
) )
} }
internal fun steamCacheImage(cache: File, appId: Int, names: List<String>): File? = internal fun steamCacheImage(cache: File, appId: Int, names: List<String>): File? {
SteamCacheImages(File(cache, appId.toString())).find(names) val appDir = File(cache, appId.toString())
val dirs = listOf(appDir) + appDir.listFiles()
internal class SteamCacheImages(appDir: File) { .orEmpty().filter { it.isDirectory }.sortedBy { it.name }
private val entries = appDir.listFiles().orEmpty() return names.asSequence()
private val dirs = listOf(appDir) + entries.filter { it.isDirectory }.sortedBy { it.name }
fun find(names: List<String>): File? = names.asSequence()
.flatMap { name -> dirs.asSequence().map { File(it, name) } } .flatMap { name -> dirs.asSequence().map { File(it, name) } }
.firstOrNull { it.isFile && it.length() > 0L } .firstOrNull { it.isFile && it.length() > 0L }
fun icon(): File? = find(listOf("icon.jpg", "icon.png"))
?: entries.firstOrNull { it.isFile && STEAM_ICON.matches(it.name) }
} }
private class Spec(val id: String, val name: String, val system: String, val program: String, val folders: List<String>, val exts: Set<String>, val atPanel: Boolean = false) private class Spec(val id: String, val name: String, val system: String, val program: String, val folders: List<String>, val exts: Set<String>, val atPanel: Boolean = false)
@@ -5,7 +5,6 @@ import android.util.Log
import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SessionPrefs
import org.json.JSONObject import org.json.JSONObject
import java.io.File import java.io.File
import java.util.UUID
/** Steam keeps a game's custom art in `userdata/<account>/config/grid`; this is where DroidDeck's choices and Steam's meet. */ /** Steam keeps a game's custom art in `userdata/<account>/config/grid`; this is where DroidDeck's choices and Steam's meet. */
object SteamGrid { object SteamGrid {
@@ -42,42 +41,14 @@ object SteamGrid {
private fun sigFile(context: Context, target: Target, slot: AddedGameArt.Slot) = File(target.artDir, sigName(context, slot.key)) private fun sigFile(context: Context, target: Target, slot: AddedGameArt.Slot) = File(target.artDir, sigName(context, slot.key))
private const val GRID_ID = ".droiddeck-grid" private fun recorded(context: Context, target: Target, slot: AddedGameArt.Slot): String? =
private const val UNKNOWN_GRID = "?" sigFile(context, target, slot).takeIf { it.isFile }?.readText()
/** private fun record(context: Context, target: Target, slot: AddedGameArt.Slot, value: String) {
* A random id kept in the grid folder, so a record made against another account's folder, or one wiped with the
* runtime, reads as "not seen yet" instead of "removed in Steam". "?" never matches, so nothing is dropped.
*/
private fun gridId(grid: File): String = runCatching {
val f = File(grid, GRID_ID)
f.takeIf { it.isFile }?.readText()?.trim()?.takeIf { it.isNotEmpty() } ?: UUID.randomUUID().toString().also { id ->
grid.mkdirs()
val tmp = File(grid, "$GRID_ID.tmp")
tmp.writeText(id)
if (f.isFile) f.delete()
if (!tmp.renameTo(f)) error("grid id")
}
}.getOrDefault(UNKNOWN_GRID)
private fun readRecord(grid: File, file: File): String? {
val text = file.takeIf { it.isFile }?.readText() ?: return null
val cut = text.indexOf('\n')
val id = gridId(grid)
return if (cut > 0 && id != UNKNOWN_GRID && text.substring(0, cut) == id) text.substring(cut + 1) else null
}
private fun writeRecord(grid: File, target: Target, file: File, value: String) {
target.artDir.mkdirs() target.artDir.mkdirs()
file.writeText("${gridId(grid)}\n$value") sigFile(context, target, slot).writeText(value)
} }
private fun recorded(context: Context, grid: File, target: Target, slot: AddedGameArt.Slot): String? =
readRecord(grid, sigFile(context, target, slot))
private fun record(context: Context, grid: File, target: Target, slot: AddedGameArt.Slot, value: String) =
writeRecord(grid, target, sigFile(context, target, slot), value)
private fun writtenByDroidDeck(grid: File): Set<String> = runCatching { private fun writtenByDroidDeck(grid: File): Set<String> = runCatching {
val manifest = JSONObject(File(grid, MANIFEST).readText()) val manifest = JSONObject(File(grid, MANIFEST).readText())
manifest.keys().asSequence().filter { name -> File(grid, name).let { it.isFile && it.length() == manifest.optLong(name, -1L) } }.toSet() manifest.keys().asSequence().filter { name -> File(grid, name).let { it.isFile && it.length() == manifest.optLong(name, -1L) } }.toSet()
@@ -91,7 +62,7 @@ object SteamGrid {
val grid = dir(context) ?: return true val grid = dir(context) ?: return true
if (file == null) { if (file == null) {
if (files(grid, target.id, slot).map { it.delete() }.any { !it }) return false if (files(grid, target.id, slot).map { it.delete() }.any { !it }) return false
record(context, grid, target, slot, "") record(context, target, slot, "")
return true return true
} }
val ext = file.extension.lowercase().let { if (it == "jpeg") "jpg" else it } val ext = file.extension.lowercase().let { if (it == "jpeg") "jpg" else it }
@@ -105,7 +76,7 @@ object SteamGrid {
return false return false
} }
if (files(grid, target.id, slot).filter { it != dst }.map { it.delete() }.any { !it }) return false if (files(grid, target.id, slot).filter { it != dst }.map { it.delete() }.any { !it }) return false
record(context, grid, target, slot, signature(placed)) record(context, target, slot, signature(placed))
return true return true
} }
@@ -119,11 +90,13 @@ object SteamGrid {
/** The logo position chosen here (or taken over from Steam) for a game; null when Steam's own default applies. */ /** The logo position chosen here (or taken over from Steam) for a game; null when Steam's own default applies. */
fun position(target: Target): LogoPosition.Value? = positionIn(File(target.artDir, POSITION)) fun position(target: Target): LogoPosition.Value? = positionIn(File(target.artDir, POSITION))
private fun positionRecorded(context: Context, grid: File, target: Target): String? = private fun positionRecorded(context: Context, target: Target): String? =
readRecord(grid, File(target.artDir, sigName(context, POSITION_SIG))) File(target.artDir, sigName(context, POSITION_SIG)).takeIf { it.isFile }?.readText()
private fun recordPosition(context: Context, grid: File, target: Target, value: String) = private fun recordPosition(context: Context, target: Target, value: String) {
writeRecord(grid, target, File(target.artDir, sigName(context, POSITION_SIG)), value) target.artDir.mkdirs()
File(target.artDir, sigName(context, POSITION_SIG)).writeText(value)
}
private fun storePosition(target: Target, value: LogoPosition.Value?): Boolean { private fun storePosition(target: Target, value: LogoPosition.Value?): Boolean {
val file = File(target.artDir, POSITION) val file = File(target.artDir, POSITION)
@@ -146,7 +119,7 @@ object SteamGrid {
val next = if (value == null) existing?.let(LogoPosition::without) else LogoPosition.toJson(value, existing ?: JSONObject()) val next = if (value == null) existing?.let(LogoPosition::without) else LogoPosition.toJson(value, existing ?: JSONObject())
if (next == null) { if (next == null) {
if (file.isFile && !file.delete()) return false if (file.isFile && !file.delete()) return false
recordPosition(context, grid, target, "") recordPosition(context, target, "")
return true return true
} }
grid.mkdirs() grid.mkdirs()
@@ -156,7 +129,7 @@ object SteamGrid {
tmp.delete() tmp.delete()
return false return false
} }
recordPosition(context, grid, target, signature(file)) recordPosition(context, target, signature(file))
return true return true
} }
@@ -171,16 +144,16 @@ object SteamGrid {
if (hasUnknownPosition(file)) return if (hasUnknownPosition(file)) return
val theirs = positionIn(file) val theirs = positionIn(file)
val now = if (theirs != null) signature(file) else "" val now = if (theirs != null) signature(file) else ""
val before = positionRecorded(context, grid, target) val before = positionRecorded(context, target)
val own = position(target) val own = position(target)
when { when {
before == null && own != null && theirs == null -> placePosition(context, target, own) before == null && own != null && theirs == null -> placePosition(context, target, own)
before == null || now != before -> { before == null || now != before -> {
// Recorded only once the local side agrees, so a failed take-over is tried again on the next scan. // Recorded only once the local side agrees, so a failed take-over is tried again on the next scan.
if (theirs != null) { if (theirs != null) {
if (own == theirs || storePosition(target, theirs)) recordPosition(context, grid, target, now) if (own == theirs || storePosition(target, theirs)) recordPosition(context, target, now)
} else { } else {
if (own == null || storePosition(target, null)) recordPosition(context, grid, target, "") if (own == null || storePosition(target, null)) recordPosition(context, target, "")
} }
} }
own != null && own != theirs -> placePosition(context, target, own) own != null && own != theirs -> placePosition(context, target, own)
@@ -200,20 +173,20 @@ object SteamGrid {
val present = files(grid, target.id, slot) val present = files(grid, target.id, slot)
val theirs = present.filter { it.name !in ours }.maxByOrNull { it.lastModified() } val theirs = present.filter { it.name !in ours }.maxByOrNull { it.lastModified() }
val now = signature(theirs) val now = signature(theirs)
val before = recorded(context, grid, target, slot) val before = recorded(context, target, slot)
when { when {
before == null && own != null && theirs == null -> write(context, target, slot, own) before == null && own != null && theirs == null -> write(context, target, slot, own)
before == null || now != before -> { before == null || now != before -> {
if (theirs != null) { if (theirs != null) {
if (own != null && own.length() == theirs.length() && own.readBytes().contentEquals(theirs.readBytes())) record(context, grid, target, slot, now) if (own != null && own.length() == theirs.length() && own.readBytes().contentEquals(theirs.readBytes())) record(context, target, slot, now)
else if (AddedGameArt.store(target.artDir, slot, AddedGameArt.Option(AddedGameArt.STEAM, theirs.path, theirs.path))) { else if (AddedGameArt.store(target.artDir, slot, AddedGameArt.Option(AddedGameArt.STEAM, theirs.path, theirs.path))) {
target.setSource(slot, AddedGameArt.STEAM + "|steam-client") target.setSource(slot, AddedGameArt.STEAM + "|steam-client")
record(context, grid, target, slot, now) record(context, target, slot, now)
changed = true changed = true
} }
} else { } else {
if (own != null && present.isEmpty()) { own.delete(); target.setSource(slot, ""); changed = true } if (own != null && present.isEmpty()) { own.delete(); target.setSource(slot, ""); changed = true }
record(context, grid, target, slot, "") record(context, target, slot, "")
} }
} }
own != null && theirs != null && now == before && own.length() != theirs.length() -> write(context, target, slot, own) own != null && theirs != null && now == before && own.length() != theirs.length() -> write(context, target, slot, own)
@@ -15,11 +15,6 @@ object SteamRedists {
"228989" to ("vcredist2022_dll" to "VC++ 2022"), "228989" to ("vcredist2022_dll" to "VC++ 2022"),
"228990" to ("d3dx9" to "DirectX (June 2010)"), "228990" to ("d3dx9" to "DirectX (June 2010)"),
) )
/** Redists a game's own install script runs on Windows that its shared depots don't name. */
val SCRIPTED = mapOf(
72850 to listOf("xact" to "DirectX XACT audio"),
489830 to listOf("xact_x64" to "DirectX XACT audio (64-bit)"),
)
private val BLOCK = Regex("\"SharedDepots\"\\s*\\{([^}]*)\\}", RegexOption.IGNORE_CASE) private val BLOCK = Regex("\"SharedDepots\"\\s*\\{([^}]*)\\}", RegexOption.IGNORE_CASE)
private val ENTRY = Regex("\"(\\d+)\"\\s+\"\\d+\"") private val ENTRY = Regex("\"(\\d+)\"\\s+\"\\d+\"")
@@ -28,17 +23,6 @@ object SteamRedists {
return File(steamapps, "appmanifest_$appId.acf").takeIf { it.isFile } return File(steamapps, "appmanifest_$appId.acf").takeIf { it.isFile }
} }
/** Redists the game's own install script has Steam run on Windows, from its "Run Process" entries. */
fun installScript(gameDir: File?): List<Pair<String, String>> =
gameDir?.listFiles { f ->
f.isFile && f.length() < 1L shl 20 && f.name.lowercase().let { it.startsWith("installscript") && it.endsWith(".vdf") }
}.orEmpty().sortedBy { it.name }.flatMap { file ->
val root = runCatching { com.droiddeck.launcher.input.KeyValues.parse(file.readText()) }.getOrNull() ?: return@flatMap emptyList()
(root.child("InstallScript") ?: root).children("Run Process")
.flatMap { run -> run.entries.mapNotNull { (it.second as? com.droiddeck.launcher.input.KeyValues.Node)?.string("process 1") } }
.flatMap { path -> DependencyDetector.componentsFor(path).map { it to DependencyDetector.label(it) } }
}.distinctBy { it.first }
fun detect(gameDir: File?, appId: Int): List<DependencyDetector.Recommendation> { fun detect(gameDir: File?, appId: Int): List<DependencyDetector.Recommendation> {
val text = try { val text = try {
manifest(gameDir, appId)?.takeIf { it.length() < 1L shl 20 }?.readText() ?: return emptyList() manifest(gameDir, appId)?.takeIf { it.length() < 1L shl 20 }?.readText() ?: return emptyList()
@@ -3,13 +3,12 @@ package com.droiddeck.launcher.frontend
import android.content.Context import android.content.Context
import com.droiddeck.launcher.stores.Store import com.droiddeck.launcher.stores.Store
import com.droiddeck.launcher.stores.StoreGameSidecar import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.session.WinComponents
import org.json.JSONObject import org.json.JSONObject
import java.io.File import java.io.File
import java.util.Locale import java.util.Locale
object WinCompSources { object WinCompSources {
enum class Origin { STEAM, GOG, EPIC, AMAZON, STEAM_NAME, FOLDER, XBOX } enum class Origin { STEAM, GOG, EPIC, AMAZON, STEAM_NAME, FOLDER }
data class Finding(val component: String?, val original: String, val origin: Origin, val auto: Boolean, val args: List<String> = emptyList()) data class Finding(val component: String?, val original: String, val origin: Origin, val auto: Boolean, val args: List<String> = emptyList())
@@ -50,17 +49,6 @@ object WinCompSources {
fun installer(path: String): List<String> = if (UE_PREREQ.containsMatchIn(path)) listOf("vcredist2022", "d3dx9") else DependencyDetector.componentsFor(path) fun installer(path: String): List<String> = if (UE_PREREQ.containsMatchIn(path)) listOf("vcredist2022", "d3dx9") else DependencyDetector.componentsFor(path)
private val XBOX_KNOWN = Regex("""<KnownDependency\s+Name="([A-Za-z0-9_.-]{1,40})"""")
// VC14 also registers the ARM64 runtime: launchers running as ARM64EC look for it and stop when it is missing.
private val XBOX_COMPONENTS = mapOf("VC14" to listOf("vcredist2022", WinComponents.VCREDIST_ARM64))
/** Microsoft installs a PC Game Pass game's declared runtimes with it; VC14 is wanted by nearly all and is always added. */
fun xbox(folder: File?): List<Pair<String, String>> {
val config = folder?.listFiles().orEmpty().firstOrNull { it.isFile && it.name.equals("MicrosoftGame.config", ignoreCase = true) && it.length() < 1L shl 20 }
val declared = config?.let { file -> runCatching { XBOX_KNOWN.findAll(file.readText()).map { it.groupValues[1] }.toList() }.getOrNull() }.orEmpty()
return (listOf("VC14") + declared).flatMap { name -> XBOX_COMPONENTS[name].orEmpty().map { it to name } }.distinctBy { it.first }
}
fun steamDepots(ids: List<String>): List<Pair<String, String>> = ids.mapNotNull { SteamRedists.DEPOTS[it] }.distinctBy { it.first } fun steamDepots(ids: List<String>): List<Pair<String, String>> = ids.mapNotNull { SteamRedists.DEPOTS[it] }.distinctBy { it.first }
@@ -77,10 +65,9 @@ object WinCompSources {
fun steamList(context: Context, gameDir: File?, appId: Int, gameName: String, auto: Boolean): List<Finding> { fun steamList(context: Context, gameDir: File?, appId: Int, gameName: String, auto: Boolean): List<Finding> {
val local = SteamRedists.detect(gameDir, appId) val local = SteamRedists.detect(gameDir, appId)
val pairs = (if (local.isNotEmpty()) local.map { it.componentName to it.label } val pairs = if (local.isNotEmpty()) local.map { it.componentName to it.label }
else SteamAppInfo.info(context, appId)?.let { steamDepots(it.sharedDepots) }.orEmpty()) + else SteamAppInfo.info(context, appId)?.let { steamDepots(it.sharedDepots) }.orEmpty()
SteamRedists.installScript(gameDir) + SteamRedists.SCRIPTED[appId].orEmpty() return pairs.map { (component, label) ->
return pairs.distinctBy { it.first.removeSuffix("_dll") }.map { (component, label) ->
Finding(component, label, if (auto) Origin.STEAM else Origin.STEAM_NAME, auto, listOf(label, gameName, appId.toString())) Finding(component, label, if (auto) Origin.STEAM else Origin.STEAM_NAME, auto, listOf(label, gameName, appId.toString()))
} }
} }
@@ -107,7 +94,6 @@ object WinCompSources {
parts.forEach { out += Finding(it, original, Origin.EPIC, true) } parts.forEach { out += Finding(it, original, Origin.EPIC, true) }
} }
} }
store == Store.XBOX -> xbox(folder).forEach { (component, original) -> out += Finding(component, original, Origin.XBOX, true) }
store == Store.AMAZON -> folder?.let { amazonPostInstall(it) }?.forEach { command -> store == Store.AMAZON -> folder?.let { amazonPostInstall(it) }?.forEach { command ->
val parts = installer(command) val parts = installer(command)
val original = command.replace('\\', '/').substringAfterLast('/') val original = command.replace('\\', '/').substringAfterLast('/')
@@ -3,7 +3,7 @@ package com.droiddeck.launcher.glasses
import java.nio.ByteBuffer import java.nio.ByteBuffer
import java.nio.ByteOrder import java.nio.ByteOrder
/** Rokid Air/Max share one USB identity; Max 2 has a separate product ID. */ /** Rokid Air/Max share one USB identity; the product string distinguishes them. */
internal class RokidModel private constructor(override val name: String, private val max: Boolean) : GlassesModel { internal class RokidModel private constructor(override val name: String, private val max: Boolean) : GlassesModel {
override val controllable = true override val controllable = true
override val brightnessMax = BRIGHTNESS_STEPS override val brightnessMax = BRIGHTNESS_STEPS
@@ -33,7 +33,6 @@ internal class RokidModel private constructor(override val name: String, private
companion object { companion object {
const val VENDOR_ID = 0x04d2 const val VENDOR_ID = 0x04d2
const val PRODUCT_ID = 0x162f const val PRODUCT_ID = 0x162f
const val MAX2_PRODUCT_ID = 0x2002
const val BRIGHTNESS_STEPS = 10 const val BRIGHTNESS_STEPS = 10
// Vendor control requests, device recipient. // Vendor control requests, device recipient.
@@ -53,9 +52,9 @@ internal class RokidModel private constructor(override val name: String, private
// 0x04d2 is a shared vendor ID, so the Rokid product string is required too. // 0x04d2 is a shared vendor ID, so the Rokid product string is required too.
fun model(vid: Int, pid: Int, name: String?): GlassesModel? { fun model(vid: Int, pid: Int, name: String?): GlassesModel? {
if (vid != VENDOR_ID || (pid != PRODUCT_ID && pid != MAX2_PRODUCT_ID)) return null if (vid != VENDOR_ID || pid != PRODUCT_ID) return null
val product = name?.trim()?.takeIf { it.startsWith("Rokid", ignoreCase = true) } ?: return null val product = name?.trim()?.takeIf { it.startsWith("Rokid", ignoreCase = true) } ?: return null
return RokidModel(product, pid == MAX2_PRODUCT_ID || product.contains("Max", ignoreCase = true)) return RokidModel(product, product.contains("Max", ignoreCase = true))
} }
fun isDisplay(name: String) = name.contains("Rokid", ignoreCase = true) fun isDisplay(name: String) = name.contains("Rokid", ignoreCase = true)
@@ -149,9 +149,7 @@ object DeviceInfo {
add("Display driver", "${turnip.displayName(choice)} ${turnip.driverVersion(choice)}".trim()) add("Display driver", "${turnip.displayName(choice)} ${turnip.driverVersion(choice)}".trim())
val linux = LinuxVulkanDriverManager(context) val linux = LinuxVulkanDriverManager(context)
val id = SessionPrefs.linuxDriver(context) val id = SessionPrefs.linuxDriver(context)
add("Game driver", if (id == QualcommSystemDriver.ID) QualcommSystemDriver.label() add("Game driver", if (id.isEmpty()) "the runtime's own Turnip" else "${linux.getDriverName(id)} ${linux.getDriverVersion(id)}".trim())
else if (QualcommDriverPackage.isRuntimeId(id)) "${QualcommDriverPackage.label(context, id)} ${QualcommDriverPackage.version(context, id)}"
else if (id.isEmpty()) "the runtime's own Turnip" else "${linux.getDriverName(id)} ${linux.getDriverVersion(id)}".trim())
if (gpu.oneUi8Gen2) add("Note", "One UI on an 8 Gen 2: needs the OneUI Turnip build") if (gpu.oneUi8Gen2) add("Note", "One UI on an 8 Gen 2: needs the OneUI Turnip build")
}) })
} }
@@ -50,10 +50,8 @@ object FrameGen {
else -> context.getString(R.string.frame_gen_off) else -> context.getString(R.string.frame_gen_off)
} }
fun apply(context: Context, refreshHz: Float): String? = apply(context, mode(context), refreshHz) fun apply(context: Context, refreshHz: Float): String? {
val mode = mode(context)
/** Arms [mode] in this process's compositor; the cloud player passes its own mode and frame-rate cap. */
fun apply(context: Context, mode: Mode, refreshHz: Float): String? {
when (mode.engine) { when (mode.engine) {
ENGINE_LSFG -> { ENGINE_LSFG -> {
val status = Lossless.sync(context) val status = Lossless.sync(context)
@@ -12,8 +12,8 @@ public final class LinuxVulkanDriver {
public static final String HELP_TEXT = public static final String HELP_TEXT =
"The driver the Steam client, the games it launches and the desktop's programs render on, " "The driver the Steam client, the games it launches and the desktop's programs render on, "
+ "inside the Linux runtime. Import \"-Linux\" Turnip zips, or select the experimental system " + "inside the Linux runtime. Imported \"-Linux\" Turnip zips only: these are Linux processes "
+ "Qualcomm bridge or a Qualcomm package already imported as an AdrenoTools zip. Frames reach the screen through the " + "and cannot load an Android or Wayland driver. Frames still reach the screen through the "
+ "display driver below. Takes effect at the next session start."; + "display driver below. Takes effect at the next session start.";
private LinuxVulkanDriver() {} private LinuxVulkanDriver() {}
@@ -21,18 +21,12 @@ public final class LinuxVulkanDriver {
public static List<String> optionValues(Context context) { public static List<String> optionValues(Context context) {
ArrayList<String> values = new ArrayList<>(); ArrayList<String> values = new ArrayList<>();
values.add(""); values.add("");
if (QualcommSystemDriver.detected()) {
values.add(QualcommSystemDriver.ID);
values.addAll(QualcommDriverPackage.available(context));
}
values.addAll(new LinuxVulkanDriverManager(context).enumerateInstalledDrivers()); values.addAll(new LinuxVulkanDriverManager(context).enumerateInstalledDrivers());
return values; return values;
} }
public static String optionLabel(Context context, String value) { public static String optionLabel(Context context, String value) {
if (value == null || value.isEmpty()) return "Runtime default (built into the runtime)"; if (value == null || value.isEmpty()) return "Runtime default (built into the runtime)";
if (QualcommSystemDriver.ID.equals(value)) return QualcommSystemDriver.label();
if (QualcommDriverPackage.isRuntimeId(value)) return QualcommDriverPackage.label(context, value);
LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context); LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context);
if (!m.isInstalled(value)) return value + " (imported, missing - uses the runtime default)"; if (!m.isInstalled(value)) return value + " (imported, missing - uses the runtime default)";
String ver = m.getDriverVersion(value); String ver = m.getDriverVersion(value);
@@ -41,11 +35,6 @@ public final class LinuxVulkanDriver {
public static String resolveIcdPath(Context context, String value) { public static String resolveIcdPath(Context context, String value) {
if (value == null || value.isEmpty()) return null; if (value == null || value.isEmpty()) return null;
if (QualcommSystemDriver.handles(value)) {
if (QualcommDriverPackage.isRuntimeId(value) && !QualcommDriverPackage.isInstalled(context, value))
throw new QualcommSystemDriver.Unavailable("The selected Qualcomm AdrenoTools package is missing or incompatible");
return QualcommSystemDriver.prepare(context).getAbsolutePath();
}
LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context); LinuxVulkanDriverManager m = new LinuxVulkanDriverManager(context);
String icd = m.getIcdPath(value); String icd = m.getIcdPath(value);
if (icd == null) { if (icd == null) {
@@ -1,73 +0,0 @@
package com.droiddeck.launcher.gpu
import android.content.Context
import android.os.Build
import com.droiddeck.launcher.core.FileUtils
import org.json.JSONObject
import java.io.File
object QualcommDriverPackage {
private const val PREFIX = "qualcomm-adrenotools:"
@JvmStatic fun runtimeId(importedId: String): String {
require(validName(importedId)) { "Invalid imported driver ID" }
return PREFIX + importedId
}
@JvmStatic fun importedId(runtimeId: String?): String? = runtimeId
?.takeIf { it.startsWith(PREFIX) }?.removePrefix(PREFIX)?.takeIf(::validName)
@JvmStatic fun isRuntimeId(id: String?): Boolean = id?.startsWith(PREFIX) == true
private fun validName(name: String): Boolean = name.isNotBlank() && name != "." && !name.contains("..") &&
name.none { it == '/' || it == '\\' || it == ':' || it == '\u0000' }
private fun metadata(context: Context, id: String): JSONObject? {
if (!validName(id)) return null
return runCatching { JSONObject(FileUtils.readString(File(TurnipDriver(context).driverPath(id), "meta.json"))) }.getOrNull()
}
@JvmStatic fun available(context: Context): List<String> = TurnipDriver(context).enumerateImported()
.filter { isInstalled(context, runtimeId(it)) }.map(::runtimeId)
@JvmStatic fun isInstalled(context: Context, runtimeId: String): Boolean {
val id = importedId(runtimeId) ?: return false
val meta = metadata(context, id) ?: return false
val vendor = meta.optString("vendor")
val description = listOf(meta.optString("name"), meta.optString("description"), meta.optString("libraryName")).joinToString(" ")
if (!vendor.equals("Qualcomm", true) || description.contains("turnip", true) || description.contains("mesa", true)) return false
if (meta.optInt("minApi", 0) > Build.VERSION.SDK_INT) return false
val library = meta.optString("libraryName")
return validName(library) && library.endsWith(".so") && TurnipDriver(context).isInstalled(id) &&
LinuxVulkanDriverManager.isAarch64Elf(File(TurnipDriver(context).driverPath(id), library))
}
@JvmStatic fun label(context: Context, runtimeId: String): String {
val id = importedId(runtimeId) ?: return "Invalid Qualcomm package"
val driver = TurnipDriver(context)
return "${driver.displayName(id)} · Qualcomm (AdrenoTools, experimental)" +
if (isInstalled(context, runtimeId)) "" else " [missing or incompatible]"
}
@JvmStatic fun version(context: Context, runtimeId: String): String = importedId(runtimeId)
?.let { TurnipDriver(context).driverVersion(it) }.orEmpty()
@JvmStatic fun mounts(context: Context, runtimeId: String): List<String> {
ensureAvailable(isInstalled(context, runtimeId)) { "The selected Qualcomm AdrenoTools package is missing or incompatible" }
val id = importedId(runtimeId)!!
val driver = TurnipDriver(context)
val directory = File(driver.driverPath(id))
val primary = driver.libraryName(id)!!
val mounts = arrayListOf("${File(directory, primary).path}:${QualcommSystemDriver.HAL}")
for (library in directory.listFiles().orEmpty().sortedBy { it.name }) {
val name = library.name
if (name == primary || !name.endsWith(".so") || !validName(name) ||
name in setOf("libc.so", "libdl.so", "libm.so", "liblog.so", "libvulkan.so") ||
!LinuxVulkanDriverManager.isAarch64Elf(library)) continue
mounts.add("${library.path}:/vendor/lib64/$name")
// The SP-HAL namespace resolves libc++ from system before vendor.
if (name == "libc++.so") mounts.add("${library.path}:/system/lib64/$name")
}
return mounts
}
}
@@ -1,125 +0,0 @@
package com.droiddeck.launcher.gpu
import android.content.Context
import android.os.Build
import com.droiddeck.launcher.BuildConfig
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.core.TarZst
import com.droiddeck.launcher.session.SessionPrefs
import org.json.JSONObject
import java.io.File
internal inline fun ensureAvailable(condition: Boolean, message: () -> String) {
if (!condition) throw QualcommSystemDriver.Unavailable(message())
}
object QualcommSystemDriver {
class Unavailable(message: String) : IllegalStateException(message)
const val ID = "system-qualcomm"
const val HAL = "/vendor/lib64/hw/vulkan.adreno.so"
private val required = listOf("lib/libhybris-vulkan-icd.so.0", "lib/libhybris-common.so.1", "lib/libhybris/linker/q.so",
"bin/gamescope", "shaders/qualcomm-shaders.so", "wsi/libVkLayer_window_system_integration.so",
"mesa/libgallium-26.2.3.so", "mesa/dri/zink_dri.so", "mesa/libGLX_droiddeck_qualcomm.so.0",
"mesa/libEGL_droiddeck_qualcomm.so.0", "mesa/libgbm.so.1", "mesa/gbm/dri_gbm.so",
"mesa/egl-vendor.json", "mesa/qualcomm-gl.sh")
@JvmStatic fun detected(): Boolean {
if (Build.VERSION.SDK_INT < 29 || !File(HAL).canRead()) return false
val vk = VulkanInfo.query()
return isQualcomm(vk)
}
internal fun isQualcomm(vk: Map<String, String>): Boolean =
vk["vendor_id"] == "0x5143" && (vk["driver_id"] == "8" ||
(vk["driver_id"] == null && vk["driver_name"]?.contains("Qualcomm", ignoreCase = true) == true))
@JvmStatic fun handles(id: String?) = id == ID || QualcommDriverPackage.isRuntimeId(id)
@JvmStatic fun selected(context: Context) = handles(SessionPrefs.linuxDriver(context))
@JvmStatic fun mounts(context: Context, id: String): List<String> = androidPaths() +
if (QualcommDriverPackage.isRuntimeId(id)) QualcommDriverPackage.mounts(context, id) else emptyList()
@JvmStatic fun label(): String {
val vk = VulkanInfo.query()
val version = vk["driver_version_raw"]?.toULongOrNull()?.let { "${(it shr 22) and 0x7fu}.${(it shr 12) and 0x3ffu}.${it and 0xfffu}" }
?: vk["driver_version"] ?: "unknown version"
return "System Qualcomm · ${vk["device"] ?: "Adreno"} · $version (experimental)"
}
@JvmStatic @Synchronized fun prepare(context: Context): File {
ensureAvailable(detected()) { "The installed Vulkan driver is not a supported Qualcomm Android driver" }
val sha = BuildConfig.QUALCOMM_BRIDGE_SHA256 + "-" + BuildConfig.QUALCOMM_FIXES_REVISION.take(16)
val root = File(context.filesDir, "qualcomm-system")
val dir = File(root, sha)
if (!File(dir, ".complete").isFile || required.any { !File(dir, it).isFile }) {
val staging = File(root, "$sha.partial")
FileUtils.delete(staging)
ensureAvailable(TarZst.extractAsset(context, "qualcomm/runtime.tzst", staging)) { "Cannot extract the Qualcomm Vulkan bridge" }
val gamescope = File(staging, "bin/gamescope")
gamescope.parentFile!!.mkdirs()
ensureAvailable(FileUtils.copyAsset(context, "qualcomm/gamescope", gamescope)) { "Cannot prepare Qualcomm Gamescope" }
ensureAvailable(gamescope.setExecutable(true, false)) { "Cannot prepare Qualcomm Gamescope" }
copyAssets(context, "qualcomm/wsi", File(staging, "wsi"))
copyAssets(context, "qualcomm/shaders", File(staging, "shaders"))
copyAssets(context, "qualcomm/licenses", File(staging, "licenses"))
copyAssets(context, "qualcomm/mesa", File(staging, "mesa"))
ensureAvailable(required.all { File(staging, it).isFile }) { "The Qualcomm Vulkan bridge is incomplete" }
File(staging, ".complete").writeText(sha)
FileUtils.delete(dir)
ensureAvailable(staging.renameTo(dir)) { "Cannot install the Qualcomm Vulkan bridge" }
}
val manifest = JSONObject().put("file_format_version", "1.0.0").put("ICD", JSONObject()
.put("library_path", File(dir, "lib/libhybris-vulkan-icd.so.0").path)
.put("api_version", VulkanInfo.query()["api"] ?: "1.1.0"))
val icd = File(dir, "icd.json")
if (!icd.isFile || icd.readText() != manifest.toString()) icd.writeText(manifest.toString())
return icd
}
@JvmStatic @JvmOverloads fun addEnvironment(context: Context, environment: MutableList<String>, id: String = SessionPrefs.linuxDriver(context)) {
if (QualcommDriverPackage.isRuntimeId(id)) ensureAvailable(QualcommDriverPackage.isInstalled(context, id)) {
"The selected Qualcomm AdrenoTools package is missing or incompatible"
}
val icd = prepare(context)
val source = if (id == ID) label() else QualcommDriverPackage.label(context, id)
android.util.Log.i("QualcommSystemDriver", "$source; Android mounts: ${mounts(context, id).joinToString()}")
environment.addAll(sessionEnvironment(icd, id))
}
internal fun sessionEnvironment(icd: File, id: String): List<String> {
val dir = icd.parentFile!!
return listOf(
"VK_DRIVER_FILES=${icd.path}", "VK_ICD_FILENAMES=${icd.path}",
"HYBRIS_ANDROID_SDK_VERSION=${Build.VERSION.SDK_INT}", "HYBRIS_VULKAN_HAL=$HAL",
"HYBRIS_LINKER_DIR=${File(dir, "lib/libhybris/linker").path}",
"HYBRIS_LD_LIBRARY_PATH=/system/lib64:/system_ext/lib64:/vendor/lib64/egl:/vendor/lib64/hw:/vendor/lib64",
// The compat layer's Mali-only image-bounds pass rewrites unrelated OpSelects; DXVK comparisons become constants on Adreno.
"HYBRIS_VULKAN_COMPAT_IMAGE_BOUNDS=0",
"DROIDDECK_SYSTEM_QUALCOMM=1", "BL_GAMESCOPE_BACKEND=sdl",
"DROIDDECK_QUALCOMM_DRIVER=$id",
"BL_GAMESCOPE_BINARY=${File(dir, "bin/gamescope").path}",
"DROIDDECK_QUALCOMM_ROOT=${dir.path}",
"DROIDDECK_QUALCOMM_SHADERS=${File(dir, "shaders").path}",
"VK_LAYER_PATH=${File(dir, "shaders").path}",
"VK_INSTANCE_LAYERS=VK_LAYER_DROIDDECK_qualcomm_shaders",
"PATH=${File(dir, "bin").path}:/usr/local/bin:/usr/bin:/bin",
)
}
private fun copyAssets(context: Context, path: String, destination: File) {
val children = context.assets.list(path) ?: emptyArray()
if (children.isEmpty()) {
ensureAvailable(FileUtils.copyAsset(context, path, destination)) { "Cannot prepare $path" }
} else {
ensureAvailable(destination.isDirectory || destination.mkdirs()) { "Cannot prepare $path" }
for (child in children) copyAssets(context, "$path/$child", File(destination, child))
}
}
@JvmStatic fun androidPaths(): List<String> = listOf(
"/system", "/vendor", "/odm", "/system_ext", "/product", "/apex", "/linkerconfig",
"/dev/__properties__"
).filter { File(it).exists() }
}
@@ -37,7 +37,6 @@ public final class TurnipDriver {
private static final String PREFS = "graphics_driver"; private static final String PREFS = "graphics_driver";
private static final String KEY_HIDDEN = "hiddenBundled"; private static final String KEY_HIDDEN = "hiddenBundled";
public static final String AUTO = ""; public static final String AUTO = "";
public static final String SYSTEM = "system";
public static final String HELP_TEXT = public static final String HELP_TEXT =
"The driver the app's compositor puts frames on the screen with - the last step of every " "The driver the app's compositor puts frames on the screen with - the last step of every "
@@ -140,8 +139,6 @@ public final class TurnipDriver {
Log.d(TAG, "removing imported driver " + driverId); Log.d(TAG, "removing imported driver " + driverId);
FileUtils.delete(new File(contentDir, driverId)); FileUtils.delete(new File(contentDir, driverId));
if (driverId.equals(SessionPrefs.androidDriver(context))) SessionPrefs.setAndroidDriver(context, AUTO); if (driverId.equals(SessionPrefs.androidDriver(context))) SessionPrefs.setAndroidDriver(context, AUTO);
if (driverId.equals(QualcommDriverPackage.importedId(SessionPrefs.INSTANCE.linuxDriver(context))))
SessionPrefs.INSTANCE.setLinuxDriver(context, "");
} }
public String installFromZip(Uri zipUri, String displayName) throws IOException { public String installFromZip(Uri zipUri, String displayName) throws IOException {
@@ -260,7 +257,6 @@ public final class TurnipDriver {
private String choose() { private String choose() {
String chosen = SessionPrefs.androidDriver(context); String chosen = SessionPrefs.androidDriver(context);
if (SYSTEM.equals(chosen)) return null;
if (chosen != null && !chosen.isEmpty()) { if (chosen != null && !chosen.isEmpty()) {
if (BUNDLED.contains(chosen)) { if (BUNDLED.contains(chosen)) {
Log.i(TAG, "driver pinned by the user: " + chosen); Log.i(TAG, "driver pinned by the user: " + chosen);
@@ -157,56 +157,6 @@ object ControllerPrefs {
prefs(context).edit().remove("layout.${width}x$height").apply() prefs(context).edit().remove("layout.${width}x$height").apply()
} }
fun screenKeysShown(context: Context): Boolean = prefs(context).getBoolean("screenKeysShown", true)
fun setScreenKeysShown(context: Context, shown: Boolean) {
prefs(context).edit().putBoolean("screenKeysShown", shown).apply()
}
fun screenKeys(context: Context): List<ScreenKey> = decodeScreenKeys(prefs(context).getString("screenKeys", null).orEmpty())
fun setScreenKeys(context: Context, keys: List<ScreenKey>) {
prefs(context).edit().putString("screenKeys", encodeScreenKeys(keys)).apply()
}
fun encodeScreenKeys(keys: List<ScreenKey>): String = keys.joinToString(";") {
"${it.codes.joinToString("+")}:${it.x},${it.y},${it.size}:${escape(it.glyph)}:${escape(it.text)}:${escape(it.image)}:${it.opacity}:${it.shape}:${if (it.toggle) 1 else 0}:${if (it.labels) 1 else 0}"
}
fun decodeScreenKeys(raw: String): List<ScreenKey> = raw.split(';').mapNotNull { entry ->
val parts = entry.split(':')
if (parts.size < 2) return@mapNotNull null
val keys = parts[0].split('+').mapNotNull { it.toIntOrNull() }.takeIf { it.isNotEmpty() } ?: return@mapNotNull null
val nums = parts[1].split(',').mapNotNull { it.toFloatOrNull() }.takeIf { it.size == 3 } ?: return@mapNotNull null
ScreenKey(
keys, nums[0], nums[1], nums[2].toInt(),
parts.getOrNull(2)?.let(::unescape).orEmpty(),
parts.getOrNull(3)?.let(::unescape).orEmpty(),
parts.getOrNull(4)?.let(::unescape).orEmpty(),
parts.getOrNull(5)?.toFloatOrNull()?.coerceIn(0.2f, 1f) ?: 1f,
parts.getOrNull(6)?.toIntOrNull()?.coerceIn(SCREEN_KEY_PILL, SCREEN_KEY_STICK) ?: SCREEN_KEY_PILL,
parts.getOrNull(7) == "1",
parts.getOrNull(8) != "0",
)
}
fun screenLayouts(context: Context): Map<String, String> =
prefs(context).all.mapNotNull { (key, value) ->
if (!key.startsWith("screenLayout.") || value !is String) null else key.removePrefix("screenLayout.") to value
}.toMap()
fun saveScreenLayout(context: Context, name: String, raw: String) {
prefs(context).edit().putString("screenLayout.$name", raw).apply()
}
fun deleteScreenLayout(context: Context, name: String) {
prefs(context).edit().remove("screenLayout.$name").apply()
}
private fun escape(value: String) = value.replace("%", "%25").replace(";", "%3B").replace(":", "%3A").replace(",", "%2C")
private fun unescape(value: String) = value.replace("%2C", ",").replace("%3A", ":").replace("%3B", ";").replace("%25", "%")
fun resetAll(context: Context) { fun resetAll(context: Context) {
prefs(context).edit().clear().putBoolean("rumble", true).apply() prefs(context).edit().clear().putBoolean("rumble", true).apply()
} }
@@ -15,7 +15,6 @@ class DirectTouchHold(
private var y = 0f private var y = 0f
private var consumed = false private var consumed = false
private var pressed = false private var pressed = false
private var delayMs = 0L
private val release = Runnable { private val release = Runnable {
if (pressed) listener.onButton(PointerGestures.BTN_RIGHT, false, x, y) if (pressed) listener.onButton(PointerGestures.BTN_RIGHT, false, x, y)
pressed = false pressed = false
@@ -29,11 +28,6 @@ class DirectTouchHold(
handler.postDelayed(release, 50L) handler.postDelayed(release, 50L)
} }
fun configure(config: TouchGestureConfig) {
cancel()
delayMs = if (config.longPressEnabled) config.longPressDelay.toLong().coerceAtLeast(1L) else 0L
}
fun cancel() { fun cancel() {
handler.removeCallbacks(hold) handler.removeCallbacks(hold)
handler.removeCallbacks(release) handler.removeCallbacks(release)
@@ -46,7 +40,7 @@ class DirectTouchHold(
MotionEvent.ACTION_DOWN -> { MotionEvent.ACTION_DOWN -> {
cancel() cancel()
x = event.x; y = event.y x = event.x; y = event.y
if (delayMs > 0L) handler.postDelayed(hold, delayMs) handler.postDelayed(hold, 500L)
} }
MotionEvent.ACTION_MOVE -> if (event.pointerCount > 1 || MotionEvent.ACTION_MOVE -> if (event.pointerCount > 1 ||
abs(event.x - x) > slopPx || abs(event.y - y) > slopPx) handler.removeCallbacks(hold) abs(event.x - x) > slopPx || abs(event.y - y) > slopPx) handler.removeCallbacks(hold)
@@ -1,21 +0,0 @@
package com.droiddeck.launcher.input
import android.view.MotionEvent
/** Keeps split Android touch targets from restarting one shared gesture recognizer. */
internal class GestureTouchStreamGate {
enum class Source { SURFACE, SCREEN_KEYS }
private var owner: Source? = null
fun accepts(source: Source, event: MotionEvent): Boolean {
if (owner == null && event.actionMasked == MotionEvent.ACTION_DOWN) owner = source
val accepted = owner == source
if (accepted && (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL)) {
owner = null
}
return accepted
}
fun reset() { owner = null }
}
@@ -1,6 +1,5 @@
package com.droiddeck.launcher.input; package com.droiddeck.launcher.input;
import android.os.Build;
import android.os.Handler; import android.os.Handler;
import android.os.Looper; import android.os.Looper;
import android.util.Log; import android.util.Log;
@@ -309,10 +308,10 @@ public final class PadBridge {
case KeyEvent.KEYCODE_BUTTON_MODE: case KeyEvent.KEYCODE_BUTTON_MODE:
case KeyEvent.KEYCODE_HOME: pad.press(PadState.GUIDE, pressed); break; case KeyEvent.KEYCODE_HOME: pad.press(PadState.GUIDE, pressed); break;
case KeyEvent.KEYCODE_BUTTON_Z: case KeyEvent.KEYCODE_BUTTON_Z:
if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(event.getDevice()) ? DeckControls.R4 : DeckControls.L4, pressed); if (isPrimary(event)) DeckControls.INSTANCE.setGrip(DeckControls.L4, pressed);
break; break;
case KeyEvent.KEYCODE_BUTTON_C: case KeyEvent.KEYCODE_BUTTON_C:
if (isPrimary(event)) DeckControls.INSTANCE.setGrip(isNovaController(event.getDevice()) ? DeckControls.L4 : DeckControls.R4, pressed); if (isPrimary(event)) DeckControls.INSTANCE.setGrip(DeckControls.R4, pressed);
break; break;
case KeyEvent.KEYCODE_BUTTON_L2: pad.leftTrigger = pressed ? 1f : 0f; break; case KeyEvent.KEYCODE_BUTTON_L2: pad.leftTrigger = pressed ? 1f : 0f; break;
case KeyEvent.KEYCODE_BUTTON_R2: pad.rightTrigger = pressed ? 1f : 0f; break; case KeyEvent.KEYCODE_BUTTON_R2: pad.rightTrigger = pressed ? 1f : 0f; break;
@@ -574,12 +573,6 @@ public final class PadBridge {
return slot == 0 ? state : playerStates[slot]; return slot == 0 ? state : playerStates[slot];
} }
private static boolean isNovaController(InputDevice device) {
return "Retroid Pocket Nova".equalsIgnoreCase(Build.MODEL)
&& device.getVendorId() == 0x2022
&& (device.getProductId() == 0x3001 || device.getProductId() == 0x3002);
}
private boolean isPrimary(KeyEvent event) { private boolean isPrimary(KeyEvent event) {
int id = event.getDevice().getId(); int id = event.getDevice().getId();
int first = firstPlayerSlot(); int first = firstPlayerSlot();
@@ -1,60 +0,0 @@
package com.droiddeck.launcher.input
import android.content.Context
import androidx.annotation.StringRes
import com.droiddeck.launcher.R
data class PcKey(
val label: String,
val code: Int,
val weight: Float = 1f,
val shifted: String? = null,
@StringRes val labelRes: Int = 0,
)
internal fun k(label: String, code: Int, weight: Float = 1f, shifted: String? = null) = PcKey(label, code, weight, shifted)
internal fun k(@StringRes labelRes: Int, code: Int, weight: Float = 1f) = PcKey("", code, weight, null, labelRes)
val PC_KEY_ROWS: List<List<PcKey>> = listOf(
listOf(
k(R.string.pckb_key_esc, 1), k("F1", 59), k("F2", 60), k("F3", 61), k("F4", 62), k("F5", 63), k("F6", 64),
k("F7", 65), k("F8", 66), k("F9", 67), k("F10", 68), k("F11", 87), k("F12", 88),
k(R.string.pckb_key_ins, 110), k(R.string.pckb_key_del, 111), k(R.string.pckb_key_home, 102), k(R.string.pckb_key_end, 107), k(R.string.pckb_key_pgup, 104), k(R.string.pckb_key_pgdn, 109),
),
listOf(
k("`", 41, shifted = "~"), k("1", 2, shifted = "!"), k("2", 3, shifted = "@"), k("3", 4, shifted = "#"),
k("4", 5, shifted = "$"), k("5", 6, shifted = "%"), k("6", 7, shifted = "^"), k("7", 8, shifted = "&"),
k("8", 9, shifted = "*"), k("9", 10, shifted = "("), k("0", 11, shifted = ")"), k("-", 12, shifted = "_"),
k("=", 13, shifted = "+"), k(R.string.pckb_key_backspace, 14, 2f),
),
listOf(
k(R.string.pckb_key_tab, 15, 1.5f), k("q", 16), k("w", 17), k("e", 18), k("r", 19), k("t", 20), k("y", 21),
k("u", 22), k("i", 23), k("o", 24), k("p", 25), k("[", 26, shifted = "{"), k("]", 27, shifted = "}"),
k("\\", 43, 1.5f, shifted = "|"),
),
listOf(
k(R.string.pckb_key_caps, 58, 1.75f), k("a", 30), k("s", 31), k("d", 32), k("f", 33), k("g", 34), k("h", 35),
k("j", 36), k("k", 37), k("l", 38), k(";", 39, shifted = ":"), k("'", 40, shifted = "\""),
k(R.string.pckb_key_enter, 28, 2.25f),
),
listOf(
k(R.string.pckb_key_shift, 42, 2.25f), k("z", 44), k("x", 45), k("c", 46), k("v", 47), k("b", 48), k("n", 49),
k("m", 50), k(",", 51, shifted = "<"), k(".", 52, shifted = ">"), k("/", 53, shifted = "?"),
k(R.string.pckb_key_shift, 54, 1.75f), k("↑", 103),
),
listOf(
k(R.string.pckb_key_ctrl, 29, 1.5f), k(R.string.pckb_key_super, 125, 1.25f), k(R.string.pckb_key_alt, 56, 1.25f), k(R.string.pckb_key_space, 57, 6.25f),
k(R.string.pckb_key_altgr, 100, 1.25f), k(R.string.pckb_key_ctrl, 97, 1.25f), k("←", 105), k("↓", 108), k("→", 106),
),
)
val PC_MODIFIERS: Set<Int> = setOf(42, 54, 29, 97, 56, 100, 125)
val PC_KEYS: Map<Int, PcKey> = PC_KEY_ROWS.flatten().associateBy { it.code }
fun pcKeyLabel(context: Context, code: Int): String {
val key = PC_KEYS[code] ?: return code.toString()
val text = if (key.labelRes != 0) context.getString(key.labelRes) else key.label
return if (text.length == 1 && text[0].isLetter()) text.uppercase() else text
}
@@ -1,63 +0,0 @@
package com.droiddeck.launcher.input
import android.content.Context
fun screenKeyLabel(context: Context, codes: List<Int>): String =
codes.filter { it != 0 }.joinToString("+") { short(context, it) }
private fun short(context: Context, code: Int): String = when (code) {
28 -> "⏎"
14 -> "⌫"
15 -> "Tab"
57 -> "Space"
58 -> "Caps"
42, 54 -> "Shift"
29, 97 -> "Ctrl"
56 -> "Alt"
100 -> "AltGr"
125 -> "Super"
else -> pcKeyLabel(context, code)
}
const val SCREEN_KEY_PILL = 0
const val SCREEN_KEY_ROUND = 1
const val SCREEN_KEY_CIRCLE = 2
const val SCREEN_KEY_RECT = 3
const val SCREEN_KEY_TRIGGER = 4
const val SCREEN_KEY_DPAD = 5
const val SCREEN_KEY_STICK = 6
val SCREEN_KEY_DPAD_DIRS = listOf("↑", "→", "↓", "←")
val SCREEN_KEY_STICK_DIRS = listOf("↑", "↗", "→", "↘", "↓", "↙", "←", "↖")
fun screenKeyDirections(shape: Int): List<String> = when (shape) {
SCREEN_KEY_DPAD -> SCREEN_KEY_DPAD_DIRS
SCREEN_KEY_STICK -> SCREEN_KEY_STICK_DIRS
else -> emptyList()
}
val SCREEN_KEY_SHAPES =
listOf(
SCREEN_KEY_PILL, SCREEN_KEY_ROUND, SCREEN_KEY_CIRCLE, SCREEN_KEY_RECT,
SCREEN_KEY_TRIGGER, SCREEN_KEY_DPAD, SCREEN_KEY_STICK,
)
data class ScreenKey(
val codes: List<Int>,
val x: Float,
val y: Float,
val size: Int,
val glyph: String = "",
val text: String = "",
val image: String = "",
val opacity: Float = 1f,
val shape: Int = SCREEN_KEY_PILL,
val toggle: Boolean = false,
val labels: Boolean = true,
) {
fun shownLabel(context: Context): String = when {
text.isNotEmpty() -> text
glyph.isNotEmpty() -> glyph
else -> screenKeyLabel(context, codes)
}
}
@@ -1,148 +0,0 @@
package com.droiddeck.launcher.input
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
object ScreenKeyIcons {
fun has(code: Int): Boolean = code in SET
private val SET = setOf(28, 14, 15, 57, 42, 54, 29, 97, 125, 103, 108, 105, 106)
fun draw(canvas: Canvas, code: Int, cx: Float, cy: Float, box: Float, paint: Paint): Boolean {
if (!has(code)) return false
val h = box / 2f
val stroke = box * 0.085f
val path = Path()
paint.style = Paint.Style.STROKE
paint.strokeWidth = stroke
paint.strokeCap = Paint.Cap.ROUND
paint.strokeJoin = Paint.Join.ROUND
when (code) {
28 -> {
path.moveTo(cx - 0.34f * h, cy - 0.22f * h)
path.lineTo(cx + 0.30f * h, cy - 0.22f * h)
path.lineTo(cx + 0.30f * h, cy + 0.24f * h)
path.lineTo(cx - 0.04f * h, cy + 0.24f * h)
canvas.drawPath(path, paint)
path.reset()
path.moveTo(cx + 0.12f * h, cy + 0.06f * h)
path.lineTo(cx - 0.04f * h, cy + 0.24f * h)
path.lineTo(cx + 0.12f * h, cy + 0.42f * h)
canvas.drawPath(path, paint)
}
14 -> {
path.moveTo(cx - 0.72f * h, cy)
path.lineTo(cx - 0.10f * h, cy - 0.50f * h)
path.lineTo(cx + 0.74f * h, cy - 0.50f * h)
path.lineTo(cx + 0.74f * h, cy + 0.50f * h)
path.lineTo(cx - 0.10f * h, cy + 0.50f * h)
path.close()
canvas.drawPath(path, paint)
path.reset()
path.moveTo(cx + 0.10f * h, cy - 0.20f * h)
path.lineTo(cx + 0.44f * h, cy + 0.20f * h)
path.moveTo(cx + 0.44f * h, cy - 0.20f * h)
path.lineTo(cx + 0.10f * h, cy + 0.20f * h)
canvas.drawPath(path, paint)
}
15 -> {
path.moveTo(cx - 0.72f * h, cy)
path.lineTo(cx + 0.44f * h, cy)
path.moveTo(cx + 0.14f * h, cy - 0.30f * h)
path.lineTo(cx + 0.46f * h, cy)
path.lineTo(cx + 0.14f * h, cy + 0.30f * h)
canvas.drawPath(path, paint)
path.reset()
path.moveTo(cx + 0.70f * h, cy - 0.48f * h)
path.lineTo(cx + 0.70f * h, cy + 0.48f * h)
canvas.drawPath(path, paint)
}
57 -> {
path.moveTo(cx - 0.64f * h, cy - 0.22f * h)
path.lineTo(cx - 0.64f * h, cy + 0.20f * h)
path.lineTo(cx + 0.64f * h, cy + 0.20f * h)
path.lineTo(cx + 0.64f * h, cy - 0.22f * h)
canvas.drawPath(path, paint)
}
42, 54 -> {
paint.style = Paint.Style.FILL
path.moveTo(cx, cy - 0.55f * h)
path.lineTo(cx + 0.62f * h, cy + 0.02f * h)
path.lineTo(cx + 0.26f * h, cy + 0.02f * h)
path.lineTo(cx + 0.26f * h, cy + 0.32f * h)
path.lineTo(cx - 0.26f * h, cy + 0.32f * h)
path.lineTo(cx - 0.26f * h, cy + 0.02f * h)
path.lineTo(cx - 0.62f * h, cy + 0.02f * h)
path.close()
canvas.drawPath(path, paint)
path.reset()
path.moveTo(cx - 0.26f * h, cy + 0.44f * h)
path.lineTo(cx + 0.26f * h, cy + 0.44f * h)
path.lineTo(cx + 0.26f * h, cy + 0.58f * h)
path.lineTo(cx - 0.26f * h, cy + 0.58f * h)
path.close()
canvas.drawPath(path, paint)
}
29, 97 -> {
path.moveTo(cx - 0.58f * h, cy + 0.26f * h)
path.lineTo(cx, cy - 0.28f * h)
path.lineTo(cx + 0.58f * h, cy + 0.26f * h)
canvas.drawPath(path, paint)
}
125 -> {
paint.style = Paint.Style.FILL
val gap = 0.07f * h
val side = 0.34f * h
for (dxi in -1..1 step 2) for (dyi in -1..1 step 2) {
val left = cx + dxi * (gap + side / 2f) - side / 2f
val top = cy + dyi * (gap + side / 2f) - side / 2f
path.addRect(left, top, left + side, top + side, Path.Direction.CW)
}
canvas.drawPath(path, paint)
}
103, 108, 105, 106 -> {
paint.style = Paint.Style.FILL
val r = 0.52f * h
when (code) {
103 -> {
path.moveTo(cx, cy - r)
path.lineTo(cx + r * 0.80f, cy + r * 0.55f)
path.lineTo(cx - r * 0.80f, cy + r * 0.55f)
}
108 -> {
path.moveTo(cx, cy + r)
path.lineTo(cx + r * 0.80f, cy - r * 0.55f)
path.lineTo(cx - r * 0.80f, cy - r * 0.55f)
}
105 -> {
path.moveTo(cx - r, cy)
path.lineTo(cx + r * 0.55f, cy - r * 0.80f)
path.lineTo(cx + r * 0.55f, cy + r * 0.80f)
}
else -> {
path.moveTo(cx + r, cy)
path.lineTo(cx - r * 0.55f, cy - r * 0.80f)
path.lineTo(cx - r * 0.55f, cy + r * 0.80f)
}
}
path.close()
canvas.drawPath(path, paint)
}
}
paint.style = Paint.Style.FILL
paint.strokeCap = Paint.Cap.BUTT
paint.strokeJoin = Paint.Join.MITER
return true
}
}
File diff suppressed because it is too large. Load diff
@@ -1,140 +0,0 @@
package com.droiddeck.launcher.input
import org.json.JSONArray
import org.json.JSONObject
import kotlin.math.roundToInt
private val ICP_NAMES: Map<Int, String> = mapOf(
103 to "KEY_UP", 106 to "KEY_RIGHT", 108 to "KEY_DOWN", 105 to "KEY_LEFT",
28 to "KEY_ENTER", 1 to "KEY_ESC", 14 to "KEY_BKSP", 111 to "KEY_DEL", 15 to "KEY_TAB",
57 to "KEY_SPACE", 29 to "KEY_CTRL_L", 97 to "KEY_CTRL_R", 110 to "KEY_INSERT",
42 to "KEY_SHIFT_L", 54 to "KEY_SHIFT_R", 56 to "KEY_ALT_L", 100 to "KEY_ALT_R",
102 to "KEY_HOME", 107 to "KEY_END", 99 to "KEY_PRTSCN", 104 to "KEY_PG_UP", 109 to "KEY_PG_DOWN",
58 to "KEY_CAPS_LOCK", 69 to "KEY_NUM_LOCK", 41 to "KEY_GRAVE", 12 to "KEY_MINUS",
11 to "KEY_0", 2 to "KEY_1", 3 to "KEY_2", 4 to "KEY_3", 5 to "KEY_4", 6 to "KEY_5",
7 to "KEY_6", 8 to "KEY_7", 9 to "KEY_8", 10 to "KEY_9",
30 to "KEY_A", 48 to "KEY_B", 46 to "KEY_C", 32 to "KEY_D", 18 to "KEY_E", 33 to "KEY_F",
34 to "KEY_G", 35 to "KEY_H", 23 to "KEY_I", 36 to "KEY_J", 37 to "KEY_K", 38 to "KEY_L",
50 to "KEY_M", 49 to "KEY_N", 24 to "KEY_O", 25 to "KEY_P", 16 to "KEY_Q", 19 to "KEY_R",
31 to "KEY_S", 20 to "KEY_T", 22 to "KEY_U", 47 to "KEY_V", 17 to "KEY_W", 45 to "KEY_X",
21 to "KEY_Y", 44 to "KEY_Z",
26 to "KEY_BRACKET_LEFT", 27 to "KEY_BRACKET_RIGHT", 43 to "KEY_BACKSLASH", 53 to "KEY_SLASH",
39 to "KEY_SEMICOLON", 51 to "KEY_COMMA", 52 to "KEY_PERIOD", 40 to "KEY_APOSTROPHE",
59 to "KEY_F1", 60 to "KEY_F2", 61 to "KEY_F3", 62 to "KEY_F4", 63 to "KEY_F5", 64 to "KEY_F6",
65 to "KEY_F7", 66 to "KEY_F8", 67 to "KEY_F9", 68 to "KEY_F10", 87 to "KEY_F11", 88 to "KEY_F12",
79 to "KEY_KP_1", 80 to "KEY_KP_2", 81 to "KEY_KP_3", 75 to "KEY_KP_4", 76 to "KEY_KP_5",
77 to "KEY_KP_6", 71 to "KEY_KP_7", 72 to "KEY_KP_8", 73 to "KEY_KP_9", 82 to "KEY_KP_0",
)
private val ICP_CODES: Map<String, Int> = ICP_NAMES.entries.associate { (code, name) -> name to code }
private fun icpShape(shape: Int): String = when (shape) {
SCREEN_KEY_CIRCLE -> "CIRCLE"
SCREEN_KEY_RECT -> "RECT"
SCREEN_KEY_ROUND -> "ROUND_RECT"
SCREEN_KEY_DPAD -> "ROUND_RECT"
SCREEN_KEY_STICK -> "ROUND_RECT"
SCREEN_KEY_TRIGGER -> "ROUND_RECT"
else -> "ROUND_RECT"
}
private fun screenKeyShape(shape: String): Int = when (shape) {
"CIRCLE" -> SCREEN_KEY_CIRCLE
"RECT" -> SCREEN_KEY_RECT
"SQUARE" -> SCREEN_KEY_ROUND
else -> SCREEN_KEY_PILL
}
fun exportScreenLayout(keys: List<ScreenKey>, widthPx: Int, density: Float): String {
val snap = widthPx / 100f
val elements = JSONArray()
keys.forEach { key ->
val binds = JSONArray()
val directional = key.shape == SCREEN_KEY_DPAD || key.shape == SCREEN_KEY_STICK
key.codes.forEach { code ->
val name = ICP_NAMES[code]
if (name != null) binds.put(name) else if (directional) binds.put("")
}
if (binds.length() == 0) return@forEach
val shape = icpShape(key.shape)
val sizePx = key.size * density
val scale = when {
key.shape == SCREEN_KEY_DPAD -> sizePx * 2.3f / (14f * snap)
key.shape == SCREEN_KEY_STICK -> sizePx * 2.3f / (14f * snap)
shape == "CIRCLE" -> sizePx / (6f * snap)
else -> sizePx / (4f * snap)
}
elements.put(
JSONObject()
.put(
"type",
when (key.shape) {
SCREEN_KEY_DPAD -> "D_PAD"
SCREEN_KEY_STICK -> "STICK"
else -> "BUTTON"
},
)
.put("shape", shape)
.put("customColor", 0)
.put("bindings", binds)
.put("scale", scale)
.put("x", key.x)
.put("y", key.y)
.put("toggleSwitch", key.toggle)
.put("swipeable", false)
.put("text", key.text)
.put("iconId", 0)
.apply { if (key.opacity < 1f) put("opacity", key.opacity) },
)
}
return JSONObject()
.put("id", 0)
.put("name", "DroidDeck")
.put("cursorSpeed", 1.5f)
.put("elements", elements)
.toString()
}
fun importScreenLayout(raw: String, widthPx: Int, density: Float): List<ScreenKey>? {
val root = runCatching { JSONObject(raw) }.getOrNull() ?: return null
val elements = root.optJSONArray("elements") ?: return null
val snap = widthPx / 100f
val keys = mutableListOf<ScreenKey>()
for (i in 0 until elements.length()) {
val element = elements.optJSONObject(i) ?: continue
val type = element.optString("type", "BUTTON")
if (type != "BUTTON" && type != "D_PAD" && type != "STICK") continue
val binds = element.optJSONArray("bindings") ?: continue
val raw = (0 until binds.length()).map { ICP_CODES[binds.optString(it)] ?: 0 }
val codes = if (type == "D_PAD" || type == "STICK") {
raw.dropLastWhile { it == 0 }.ifEmpty { listOf(0) }
} else {
raw.filter { it != 0 }
}
if (codes.isEmpty()) continue
val dpad = type == "D_PAD"
val stick = type == "STICK"
val shape = when {
dpad -> SCREEN_KEY_DPAD
stick -> SCREEN_KEY_STICK
else -> screenKeyShape(element.optString("shape"))
}
val scale = element.optDouble("scale", 1.0).toFloat().takeIf { it > 0f } ?: 1f
val sizePx = when {
dpad || stick -> 14f * snap * scale / 2.3f
shape == SCREEN_KEY_CIRCLE -> 6f * snap * scale
else -> 4f * snap * scale
}
keys += ScreenKey(
codes = codes,
x = element.optDouble("x", 0.5).toFloat().coerceIn(0f, 1f),
y = element.optDouble("y", 0.5).toFloat().coerceIn(0f, 1f),
size = (sizePx / density).roundToInt().coerceIn(ScreenKeys.MIN_SIZE, ScreenKeys.MAX_SIZE),
text = element.optString("text").take(24),
opacity = element.optDouble("opacity", 1.0).toFloat().coerceIn(0.2f, 1f),
shape = shape,
toggle = element.optBoolean("toggleSwitch"),
)
}
return keys
}
@@ -93,10 +93,7 @@ class SteamTouchControls(
private var opened = 0 private var opened = 0
private var elements: List<Element> = emptyList() private var elements: List<Element> = emptyList()
private var tint = Color.WHITE private var tint = Color.WHITE
private var alphaScale = 0.99f private var alphaScale = 0.45f
var style: Pair<Int, Float> = Color.WHITE to 0.99f
private set
var onStyle: (() -> Unit)? = null
private class Visual(val ref: SteamTouchBindings.Ref?, val binding: SteamTouchBindings.Binding?) private class Visual(val ref: SteamTouchBindings.Ref?, val binding: SteamTouchBindings.Binding?)
private var visuals: Map<Int, List<Visual>> = emptyMap() private var visuals: Map<Int, List<Visual>> = emptyMap()
@@ -194,8 +191,6 @@ class SteamTouchControls(
private fun applyColor(color: FloatArray?) { private fun applyColor(color: FloatArray?) {
tint = if (color != null) Color.rgb((color[0] * 255).toInt(), (color[1] * 255).toInt(), (color[2] * 255).toInt()) else Color.WHITE tint = if (color != null) Color.rgb((color[0] * 255).toInt(), (color[1] * 255).toInt(), (color[2] * 255).toInt()) else Color.WHITE
alphaScale = ((color?.get(3) ?: 0.45f) * 2.2f).coerceIn(0.15f, 1f) alphaScale = ((color?.get(3) ?: 0.45f) * 2.2f).coerceIn(0.15f, 1f)
style = tint to alphaScale
onStyle?.invoke()
} }
private fun rebuildVisuals() { private fun rebuildVisuals() {
@@ -1,410 +0,0 @@
package com.droiddeck.launcher.runtime
import android.app.ActivityManager
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.session.GameEnvironmentStore
import java.io.File
object BattleNet {
private const val TAG = "BattleNet"
const val APP_ID = 2596113170L
const val FEX_REQUEST = "battlenet-fex.request"
const val FEX_RESULT = "battlenet-fex.result"
const val PROGRAM = "/usr/local/bin/droiddeck-battlenet"
class Title(val uid: String, val name: String, val code: String, val steam: Int? = null, val shop: String? = null)
internal val TITLES = listOf(
Title("wow", "World of Warcraft", "WoW", shop = "world-of-warcraft-midnight"),
Title("wow_classic", "World of Warcraft Classic", "WoWC", shop = "world-of-warcraft-burning-crusade-classic-anniversary-edition-upgrades"),
Title("wow_classic_era", "World of Warcraft Classic", "WoWC"),
Title("wow_classic_anniversary", "World of Warcraft Classic", "WoWC"),
Title("diablo3", "Diablo III", "D3", shop = "diablo-iii"),
Title("d3cn", "Diablo III", "D3CN", shop = "diablo-iii"),
Title("s2", "StarCraft II", "S2", shop = "starcraft-ii"),
Title("s1", "StarCraft", "S1", shop = "starcraft-remastered"),
Title("hs_beta", "Hearthstone", "WTCG", shop = "hearthstone"),
Title("heroes", "Heroes of the Storm", "Hero", shop = "heroes-of-the-storm"),
Title("prometheus", "Overwatch 2", "Pro", 2357570, shop = "overwatch"),
Title("w3", "Warcraft III: Reforged", "W3", shop = "warcraft-3-reforged"),
Title("viper", "Call of Duty: Black Ops 4", "VIPR", shop = "call-of-duty-black-ops-4"),
Title("odin", "Call of Duty: Modern Warfare", "ODIN", 2000950, shop = "call-of-duty-modern-warfare"),
Title("lazarus", "Call of Duty: Modern Warfare 2 Campaign Remastered", "LAZR", shop = "call-of-duty-modern-warfare-2-campaign-remastered"),
Title("zeus", "Call of Duty: Black Ops Cold War", "ZEUS", shop = "call-of-duty-black-ops-cold-war"),
Title("fore", "Call of Duty: Vanguard", "FORE", shop = "call-of-duty-vanguard"),
Title("auks", "Call of Duty: Modern Warfare II", "AUKS", shop = "call-of-duty-modern-warfare-ii"),
Title("pinta", "Call of Duty: Modern Warfare III", "PNTA", 2519060, shop = "call-of-duty-modern-warfare-iii"),
Title("wlby", "Crash Bandicoot 4: It's About Time", "WLBY", 1378990, shop = "crash-bandicoot-4"),
Title("osi", "Diablo II: Resurrected", "OSI"),
Title("rtro", "Blizzard Arcade Collection", "RTRO", shop = "blizzard-arcade-collection"),
Title("anbs", "Diablo Immortal", "ANBS", shop = "diablo-immortal"),
Title("fenris", "Diablo IV", "Fen", 2344520, shop = "diablo-iv"),
Title("fen", "Diablo IV", "Fen", 2344520, shop = "diablo-iv"),
Title("d1", "Diablo", "D1", shop = "diablo"),
Title("w1", "Warcraft: Orcs & Humans", "W1", shop = "warcraft-orcs-and-humans"),
Title("w2", "Warcraft II: Battle.net Edition", "W2", shop = "warcraft-2-battle-net-edition"),
Title("w1r", "Warcraft: Remastered", "W1R", shop = "warcraft-1-remastered"),
Title("w2r", "Warcraft II: Remastered", "W2R", shop = "warcraft-2-remastered"),
Title("gryphon", "Warcraft Rumble", "GRY", shop = "warcraft-rumble"),
Title("aris", "Doom: The Dark Ages", "ARIS", 3017860, shop = "doom-the-dark-ages"),
Title("scorpio", "Sea of Thieves", "SCOR", 1172620, shop = "sea-of-thieves"),
Title("arkansas", "The Outer Worlds 2", "ARK", 1449110, shop = "the-outer-worlds-2"),
Title("libra", "Tony Hawk's Pro Skater 3 + 4", "LBRA", 2545710),
Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed"),
)
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" }
fun notInstalled(title: Title, installedIds: Collection<String?>) =
installedIds.mapNotNull { id -> id?.let(::title)?.code }.none { it == title.code }
private const val COVER_RETRY_MS = 24 * 3600_000L
private fun coverDir(context: Context, title: Title) =
File(context.filesDir, "battlenet-art/${(TITLES.firstOrNull { it.code == title.code } ?: title).uid}")
fun cover(context: Context, title: Title): File? = art(context, title).cover
private val coverLock = Any()
fun fetchCovers(context: Context, titles: List<Title> = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" }): Boolean = synchronized(coverLock) {
val art = com.droiddeck.launcher.frontend.AddedGameArt
val key = com.droiddeck.launcher.frontend.SteamGridDb.key(context)
var got = false
for (title in titles) {
val dir = coverDir(context, title)
val tried = File(dir, ".tried")
val wide = File(dir, BLIZZARD)
val done = File(dir, "p.jpg").isFile && (title.shop == null || wide.isFile)
if (done || System.currentTimeMillis() - tried.lastModified() < COVER_RETRY_MS) continue
dir.mkdirs()
if (title.steam != null && runCatching { art.download(title.steam.toString(), dir) }.getOrDefault(false)) got = true
if (title.shop != null && !wide.isFile) {
val cover = File(dir, BLIZZARD_COVER).takeUnless { File(dir, "p.jpg").isFile }
if (runCatching { com.droiddeck.launcher.stores.battlenet.BlizzardArt.fetch(title.shop, wide, cover) }
.onFailure { Log.w(TAG, "Blizzard art for ${title.uid}: ${it.javaClass.simpleName}") }.getOrDefault(false)) got = true
}
if (!File(dir, "p.jpg").isFile && !File(dir, BLIZZARD_COVER).isFile && key.isNotEmpty()) {
val id = runCatching { com.droiddeck.launcher.frontend.SteamGridDb.gameId(key, title.steam, title.name) }.getOrNull()
if (id != null && runCatching { com.droiddeck.launcher.frontend.SteamGridDb.download(key, id, dir) }.getOrDefault(false)) got = true
}
runCatching { tried.writeText("") ; tried.setLastModified(System.currentTimeMillis()) }
}
got
}
private val LOCALES = setOf(
"enus", "engb", "dede", "eses", "esmx", "frfr", "itit", "kokr", "plpl", "ptbr", "ptpt", "ruru", "zhcn", "zhtw", "jajp", "thth", "trtr", "arsa",
)
private val NOT_GAMES = setOf("agent", "bna", "battle.net")
class Game(val uid: String, val name: String, val code: String, val folder: File) {
val title: Title get() = title(uid) ?: Title(uid, name, code)
}
class Art(val cover: File?, val header: File?)
private const val BLIZZARD = "blizzard.jpg"
private const val BLIZZARD_COVER = "p-blizzard.jpg"
fun art(context: Context, title: Title): Art {
val dir = coverDir(context, title)
fun first(vararg names: String) = names.map { File(dir, it) }.firstOrNull { it.isFile }
return Art(first("p.jpg", BLIZZARD_COVER), first(BLIZZARD, "header.jpg"))
}
fun prefix(context: Context) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/compatdata/$APP_ID")
fun client(context: Context) = File(prefix(context), "pfx/drive_c/Program Files (x86)/Battle.net/Battle.net.exe")
fun installed(context: Context) = File(prefix(context), "pfx/drive_c/Program Files (x86)/Battle.net/Battle.net Launcher.exe").isFile
fun profile(context: Context): Pair<String, String>? =
(APP_ID.toString() to context.getString(com.droiddeck.launcher.R.string.bnet_name)).takeIf { installed(context) }
fun icon(context: Context): File? {
val out = File(context.filesDir, "battlenet-art/launcher/icon.png")
if (out.isFile) return out
val exe = client(context).takeIf { it.isFile } ?: return null
val bitmap = runCatching { com.droiddeck.launcher.files.PeIconExtractor.extract(exe) }.getOrNull() ?: return null
return runCatching {
out.parentFile?.mkdirs()
val tmp = File(out.path + ".tmp")
tmp.outputStream().use { check(bitmap.compress(android.graphics.Bitmap.CompressFormat.PNG, 100, it)) }
check(tmp.renameTo(out))
out
}.getOrNull()
}
fun launcherEntry(installed: Boolean, art: File? = null): com.droiddeck.launcher.frontend.Library.SteamGame? =
if (!installed) null
else com.droiddeck.launcher.frontend.Library.SteamGame(
appId = APP_ID.toInt(), name = com.droiddeck.launcher.stores.Store.BATTLENET.label, art = art,
library = com.droiddeck.launcher.frontend.Library.BATTLENET_LAUNCHER, gameId = APP_ID,
source = com.droiddeck.launcher.stores.Store.BATTLENET.id,
)
fun fexInUse(context: Context): String? = ComponentsManager.gameComponents(context, APP_ID.toString())["fex"]
internal fun title(uid: String): Title? {
val id = uid.lowercase()
TITLES.firstOrNull { it.uid == id }?.let { return it }
val base = id.substringBeforeLast('_', "")
return if (base.isNotEmpty() && id.substringAfterLast('_') in LOCALES) TITLES.firstOrNull { it.uid == base } else null
}
fun games(context: Context): List<Game> {
val pfx = File(prefix(context), "pfx")
val entries = runCatching { File(pfx, "system.reg").useLines { uninstallEntries(it) } }.getOrDefault(emptyList()) +
runCatching { productDbEntries(File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").readBytes()) }.getOrDefault(emptyList())
val found = LinkedHashMap<String, Game>()
for ((uid, path) in entries) {
val title = title(uid)
if (title == null) {
if (uid.lowercase() !in NOT_GAMES) Log.i(TAG, "not listed: $uid (no launch code known)")
continue
}
if (title.code in found) continue
val folder = hostFolder(context, path)?.takeIf { it.isDirectory } ?: continue
found[title.code] = Game(title.uid, title.name, title.code, folder)
}
return found.values.toList()
}
internal fun hostFolder(context: Context, path: String): File? {
val drive = Regex("""^([CcZz]):[\\/](.*)$""").matchEntire(path.trim()) ?: return null
val relative = drive.groupValues[2].replace('\\', '/').trim('/')
if (relative.isEmpty() || relative.split('/').any { it == ".." }) return null
return if (drive.groupValues[1].equals("c", ignoreCase = true)) File(prefix(context), "pfx/drive_c/$relative")
else com.droiddeck.launcher.frontend.AddedGames.hostPath(context, "/$relative")
}
private val KEY = Regex("""^\[(.+)\](?:\s+\d+)?\s*$""")
private val UNINSTALL = Regex("""(?i)\\CurrentVersion\\Uninstall\\[^\\]+$""")
private val VALUE = Regex("""^"((?:[^"\\]|\\.)*)"=(?:str\(\d+\):)?"((?:[^"\\]|\\.)*)"\s*$""")
private val UID = Regex("""--uid=([A-Za-z0-9_.-]+)""")
internal fun uninstallEntries(lines: Sequence<String>): List<Pair<String, String>> {
val out = ArrayList<Pair<String, String>>()
var inside = false
var uid: String? = null
var location: String? = null
fun flush() {
val u = uid
val l = location
if (u != null && l != null) out.add(u to l)
uid = null
location = null
}
for (line in lines) {
if (line.startsWith("[")) {
flush()
inside = KEY.matchEntire(line)?.groupValues?.get(1)?.let { UNINSTALL.containsMatchIn(unescape(it)) } == true
continue
}
if (!inside) continue
val value = VALUE.matchEntire(line) ?: continue
val text = unescape(value.groupValues[2])
when (unescape(value.groupValues[1]).lowercase()) {
"uninstallstring" -> if (text.contains("battle.net", ignoreCase = true)) uid = UID.find(text)?.groupValues?.get(1)
"installlocation" -> location = text
}
}
flush()
return out
}
private fun unescape(s: String): String {
val out = StringBuilder(s.length)
var i = 0
while (i < s.length) {
val c = s[i++]
if (c != '\\' || i >= s.length) { out.append(c); continue }
when (val e = s[i++]) {
'n' -> out.append('\n')
'r' -> out.append('\r')
't' -> out.append('\t')
'0' -> out.append('\u0000')
'x' -> {
var end = i
while (end < s.length && end - i < 4 && s[end].lowercaseChar() in "0123456789abcdef") end++
if (end > i) { out.append(s.substring(i, end).toInt(16).toChar()); i = end } else out.append('x')
}
else -> out.append(e)
}
}
return out.toString()
}
internal fun productDbEntries(bytes: ByteArray): List<Pair<String, String>> {
val installs = runCatching { fields(bytes, 0, bytes.size) }.getOrDefault(emptyList()).filter { it.first == 1 }
return installs.mapNotNull { (_, start, end) ->
runCatching {
val install = fields(bytes, start, end)
val uid = install.firstOrNull { it.first == 1 }?.let { String(bytes, it.second, it.third - it.second) }
val path = install.firstOrNull { it.first == 3 }?.let { s -> fields(bytes, s.second, s.third).firstOrNull { it.first == 1 } }
?.let { String(bytes, it.second, it.third - it.second) }
val installed = install.firstOrNull { it.first == 4 }?.let { s -> fields(bytes, s.second, s.third).firstOrNull { it.first == 1 } }
?.let { s -> varints(bytes, s.second, s.third)[1] }
if (uid.isNullOrEmpty() || path.isNullOrEmpty() || installed == 0L) null else uid to path
}.getOrNull()
}
}
private fun fields(bytes: ByteArray, from: Int, to: Int): List<Triple<Int, Int, Int>> = walk(bytes, from, to) { _, _ -> }
private fun varints(bytes: ByteArray, from: Int, to: Int): Map<Int, Long> =
HashMap<Int, Long>().also { found -> walk(bytes, from, to) { field, value -> found.putIfAbsent(field, value) } }
private fun walk(bytes: ByteArray, from: Int, to: Int, varint: (Int, Long) -> Unit): List<Triple<Int, Int, Int>> {
val out = ArrayList<Triple<Int, Int, Int>>()
var i = from
fun next(): Long {
var value = 0L
var shift = 0
while (true) {
require(i < to && shift < 64) { "truncated" }
val b = bytes[i++].toInt() and 0xff
value = value or ((b and 0x7f).toLong() shl shift)
if (b < 0x80) return value
shift += 7
}
}
while (i < to) {
val key = next()
when ((key and 7).toInt()) {
0 -> varint((key ushr 3).toInt(), next())
1 -> { require(to - i >= 8) { "truncated" }; i += 8 }
2 -> {
val n = next()
require(n in 0..(to - i).toLong()) { "truncated" }
out.add(Triple((key ushr 3).toInt(), i, i + n.toInt()))
i += n.toInt()
}
5 -> { require(to - i >= 4) { "truncated" }; i += 4 }
else -> error("wire type ${key and 7}")
}
}
return out
}
fun shortcut(context: Context, game: Game): com.droiddeck.launcher.frontend.AddedGames.Game? {
val added = com.droiddeck.launcher.frontend.AddedGames
val client = client(context)
val guestExe = added.guestPath(context, client) ?: return null
val guestDir = added.guestPath(context, client.parentFile ?: return null) ?: return null
val guestPrefix = added.guestPath(context, prefix(context)) ?: return null
val crc = java.util.zip.CRC32().apply { update("\"$guestExe\"${game.name}".toByteArray()) }.value
val appId = com.droiddeck.launcher.session.SessionPrefs.addedGameAppId(context, game.folder.path, crc or 0x80000000L)
val exe = added.candidates(game.folder).firstOrNull() ?: client
return com.droiddeck.launcher.frontend.AddedGames.Game(
game.folder, game.name, exe, guestExe, guestDir, appId, (appId shl 32) or 0x02000000L, listOf(exe),
source = com.droiddeck.launcher.stores.Store.BATTLENET.id, storeId = game.uid,
launchOptions = "STEAM_COMPAT_DATA_PATH=$guestPrefix %command% --exec=\"launch ${game.code}\"",
)
}
fun remove(context: Context) {
val root = LinuxRuntime.rootDir(context)
com.droiddeck.launcher.core.FileUtils.delete(prefix(context))
File(root, "usr/local/share/applications/droiddeck-battlenet.desktop").delete()
com.droiddeck.launcher.core.FileUtils.delete(File(root, "root/.cache/droiddeck/battlenet"))
ComponentsManager.clearGameComponents(context, APP_ID.toString())
Log.i(TAG, "removed")
}
private val D2RFIX = Regex("""(?i)FEXCore-(\d+(?:\.\d+)*)-d2rfix(\d+)-linux\.wcp""")
private const val LISTING_MAX_AGE = 6 * 3600L
private val NEWEST = Comparator<Pair<List<Long>, Long>> { a, b ->
for (i in 0 until minOf(a.first.size, b.first.size)) if (a.first[i] != b.first[i]) return@Comparator a.first[i].compareTo(b.first[i])
if (a.first.size != b.first.size) a.first.size.compareTo(b.first.size) else a.second.compareTo(b.second)
}
internal fun d2rfix(file: String): Pair<List<Long>, Long>? {
val m = D2RFIX.matchEntire(file) ?: return null
val version = m.groupValues[1].split('.').map { it.toLongOrNull() ?: return null }
return version to (m.groupValues[2].toLongOrNull() ?: return null)
}
internal fun newestD2rFix(items: List<ComponentsManager.CatalogItem>): ComponentsManager.CatalogItem? =
items.filter { it.comp == "fex" }.mapNotNull { item -> d2rfix(item.file)?.let { item to it } }
.maxWithOrNull { a, b -> NEWEST.compare(a.second, b.second) }?.first
fun ensureFex(context: Context): String = ensureFex(context) { ComponentsManager.catalog(it, true).items }
@Synchronized
internal fun ensureFex(context: Context, refresh: (Context) -> List<ComponentsManager.CatalogItem>): String {
val item = newestD2rFix(listing(context, refresh)) ?: error("no d2rfix FEXCore build in the Nightlies listing")
val file = ComponentsManager.safeName(item.file)
if (ComponentsManager.packages(context).none { it.file == file }) {
Log.i(TAG, "downloading ${item.file}")
ComponentsManager.download(context, item) {}
}
val scope = APP_ID.toString()
if (ComponentsManager.gameComponents(context, scope)["fex"] != file) {
ComponentsManager.setGameComponent(context, scope, "fex", file)
Log.i(TAG, "FEX for the Battle.net prefix: $file")
}
return file
}
private fun listing(context: Context, refresh: (Context) -> List<ComponentsManager.CatalogItem>): List<ComponentsManager.CatalogItem> {
val cached = ComponentsManager.catalog(context, false)
val age = System.currentTimeMillis() / 1000 - cached.fetchedAt
if (age in 0 until LISTING_MAX_AGE && newestD2rFix(cached.items) != null) return cached.items
val fetched = runCatching { refresh(context) }
.onFailure { Log.w(TAG, "Nightlies listing: ${it.message}") }.getOrNull().orEmpty()
return if (newestD2rFix(fetched) != null) fetched else cached.items
}
internal fun videoMemory(totalMb: Long): Int = (totalMb / 5 / 512 * 512).coerceIn(1536, 3584).toInt()
internal fun videoMemoryOptions(megabytes: Int): String =
"dxgi.maxDeviceMemory = $megabytes; dxgi.maxSharedMemory = $megabytes; d3d9.maxAvailableMemory = $megabytes"
fun ensureVideoMemory(context: Context): Boolean {
val memory = ActivityManager.MemoryInfo()
context.getSystemService(ActivityManager::class.java)?.getMemoryInfo(memory) ?: return false
if (memory.totalMem <= 0) return false
val options = videoMemoryOptions(videoMemory(memory.totalMem / (1024 * 1024)))
val set = GameEnvironmentStore.setDefault(context, APP_ID.toString(), DXVK_CONFIG, options)
if (set) Log.i(TAG, "DXVK_CONFIG for the Battle.net profile: $options")
return set
}
private const val DXVK_CONFIG = "DXVK_CONFIG"
fun ensureNoSteam(context: Context): Boolean {
if (com.droiddeck.launcher.session.SessionPrefs.battleNetNoSteamSet(context)) return false
GameEnvironmentStore.setGameNoSteam(context, APP_ID.toString(), true)
com.droiddeck.launcher.session.SessionPrefs.setBattleNetNoSteamSet(context)
Log.i(TAG, "Start without Steam for the Battle.net profile")
return true
}
fun answerFexRequest(context: Context, dir: File) {
val app = context.applicationContext
Thread({
runCatching { ensureVideoMemory(app) }.onFailure { Log.w(TAG, "video memory cap for the Battle.net profile", it) }
runCatching { ensureNoSteam(app) }.onFailure { Log.w(TAG, "Start without Steam for the Battle.net profile", it) }
val answer = try {
"ok " + ensureFex(app)
} catch (e: Exception) {
Log.w(TAG, "FEX for the Battle.net prefix", e)
"error " + (e.message ?: e.javaClass.simpleName)
}
Log.i(TAG, "FEX request: $answer")
val result = File(dir, FEX_RESULT)
val partial = File(dir, "$FEX_RESULT.tmp")
runCatching { partial.writeText(answer.replace('\n', ' ') + "\n"); partial.renameTo(result) }
}, "battlenet-fex").start()
}
}
@@ -179,15 +179,6 @@ object BwrapSpawner {
val argv = request.getJSONArray("argv").let { a -> (0 until a.length()).map { a.getString(it) } } val argv = request.getJSONArray("argv").let { a -> (0 until a.length()).map { a.getString(it) } }
val env = LinkedHashMap<String, String>() val env = LinkedHashMap<String, String>()
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> env[k] = e.getString(k) } } request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> env[k] = e.getString(k) } }
val runtimeDriver = com.droiddeck.launcher.session.SessionState.runtimeDriver
if (com.droiddeck.launcher.gpu.QualcommSystemDriver.handles(runtimeDriver)) {
val driver = com.droiddeck.launcher.gpu.QualcommSystemDriver
val variables = ArrayList<String>()
driver.addEnvironment(context, variables, runtimeDriver!!)
for (entry in variables) env.putIfAbsent(entry.substringBefore('='), entry.substringAfter('='))
for (path in driver.mounts(context, runtimeDriver) + File(context.filesDir, "qualcomm-system").path)
addBind(Bind.parse(path))
}
if (binds.any { it.guest == "/dev" }) gpu(rootfs, root, env)?.forEach { addBind(it) } if (binds.any { it.guest == "/dev" }) gpu(rootfs, root, env)?.forEach { addBind(it) }
preload(session, rootfs, env).forEach { addBind(it) } preload(session, rootfs, env).forEach { addBind(it) }
zypakShims(binds, root, dir).forEach { addBind(it) } zypakShims(binds, root, dir).forEach { addBind(it) }
@@ -229,7 +220,6 @@ object BwrapSpawner {
val binds = ArrayList<Bind>() val binds = ArrayList<Bind>()
val paths = libs.map { lib -> "$PRELOAD_DIR/${lib.substringAfterLast('/')}".also { binds.add(Bind(rootfs + lib, it)) } } val paths = libs.map { lib -> "$PRELOAD_DIR/${lib.substringAfterLast('/')}".also { binds.add(Bind(rootfs + lib, it)) } }
env["LD_PRELOAD"] = (paths + listOfNotNull(env["LD_PRELOAD"]?.takeIf { it.isNotBlank() })).joinToString(":") env["LD_PRELOAD"] = (paths + listOfNotNull(env["LD_PRELOAD"]?.takeIf { it.isNotBlank() })).joinToString(":")
File(rootfs, NET_LINK).takeIf { it.isFile }?.let { binds.add(Bind(it.path, "/$NET_LINK")) }
env["FAKE_EVDEV_DIR"]?.let { File(it).parent }?.let { dev -> env["FAKE_EVDEV_DIR"]?.let { File(it).parent }?.let { dev ->
binds.addAll(bindsFor(session, rootfs, dev, dev)) binds.addAll(bindsFor(session, rootfs, dev, dev))
} }
@@ -237,7 +227,6 @@ object BwrapSpawner {
} }
private const val PRELOAD_DIR = "/run/droiddeck-preload" private const val PRELOAD_DIR = "/run/droiddeck-preload"
private const val NET_LINK = "etc/droiddeck-net"
private const val ZYPAK_SHIM = "#!/bin/sh\nprogram=\$1\nshift\nexec \"\$program\" --no-sandbox \"\$@\"\n" private const val ZYPAK_SHIM = "#!/bin/sh\nprogram=\$1\nshift\nexec \"\$program\" --no-sandbox \"\$@\"\n"
@@ -2,19 +2,16 @@ package com.droiddeck.launcher.runtime
import android.content.Context import android.content.Context
import android.os.Environment import android.os.Environment
import com.droiddeck.launcher.core.DownloadSource
import com.droiddeck.launcher.core.HostProcess import com.droiddeck.launcher.core.HostProcess
import com.droiddeck.launcher.session.OrphanReaper import com.droiddeck.launcher.session.OrphanReaper
import com.droiddeck.launcher.session.SessionFiles import com.droiddeck.launcher.session.SessionFiles
import com.droiddeck.launcher.session.SessionPaths import com.droiddeck.launcher.session.SessionPaths
import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SessionPrefs
import java.io.File import java.io.File
import java.util.concurrent.atomic.AtomicBoolean
object GuestCommand { object GuestCommand {
fun run(context: Context, argv: List<String>, fakeRoot: Boolean = false, logName: String? = null, fun run(context: Context, argv: List<String>, fakeRoot: Boolean = false, logName: String? = null,
linkDir: File? = null, extraBinds: List<String>? = null, fastPath: Boolean = false, cancelled: AtomicBoolean? = null, linkDir: File? = null, extraBinds: List<String>? = null, fastPath: Boolean = false, onLine: (String) -> Unit): Int {
onLine: (String) -> Unit): Int {
val log = logName?.let { val log = logName?.let {
try { try {
File(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter() File(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
@@ -22,14 +19,14 @@ object GuestCommand {
} }
log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}") log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}")
try { try {
return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(line); log?.flush(); onLine(line) } return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath) { line -> log?.println(line); log?.flush(); onLine(line) }
} finally { } finally {
log?.close() log?.close()
} }
} }
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, linkDir: File?, extraBinds: List<String>?, private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, linkDir: File?, extraBinds: List<String>?,
fastPath: Boolean, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int { fastPath: Boolean, onLine: (String) -> Unit): Int {
val root = LinuxRuntime.rootDir(context) val root = LinuxRuntime.rootDir(context)
LinuxRuntime.writeAccounts(context) LinuxRuntime.writeAccounts(context)
SessionFiles.stage(context, root) SessionFiles.stage(context, root)
@@ -48,15 +45,6 @@ object GuestCommand {
"DROIDDECK_BWRAP_SOCKET=${BwrapSpawner.socket(context)}", "DROIDDECK_BWRAP_SOCKET=${BwrapSpawner.socket(context)}",
"XDG_DATA_DIRS=/root/.local/share/flatpak/exports/share:/usr/local/share:/usr/share", "XDG_DATA_DIRS=/root/.local/share/flatpak/exports/share:/usr/local/share:/usr/share",
) )
// The Steam client installer and the package tools inside the guest fetch over plain curl,
// so the app proxy has to reach them through the environment proot starts them with.
DownloadSource.proxyHostPort(context).takeIf { it.isNotEmpty() }?.let { hostPort ->
cmd += listOf(
"http_proxy=http://$hostPort", "https_proxy=http://$hostPort",
"HTTP_PROXY=http://$hostPort", "HTTPS_PROXY=http://$hostPort",
"no_proxy=localhost,127.0.0.1,::1", "NO_PROXY=localhost,127.0.0.1,::1",
)
}
fastPathKey?.let { cmd += ProotFastPath.guestEnv(root, binds, it) } fastPathKey?.let { cmd += ProotFastPath.guestEnv(root, binds, it) }
cmd += argv cmd += argv
val builder = ProcessBuilder(cmd).directory(root).redirectErrorStream(true) val builder = ProcessBuilder(cmd).directory(root).redirectErrorStream(true)
@@ -68,32 +56,13 @@ object GuestCommand {
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> put(k, v) } } fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> put(k, v) } }
LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) } LinuxRuntime.prootLibraryPath(context).takeIf { it.isNotEmpty() }?.let { put("LD_LIBRARY_PATH", it) }
} }
if (cancelled?.get() == true) return 130
val process = builder.start() val process = builder.start()
val pid = HostProcess.pidOf(process) val pid = HostProcess.pidOf(process)
OrphanReaper.keep(pid) OrphanReaper.keep(pid)
val watcher = cancelled?.let { flag ->
Thread({
try {
while (process.isAlive && !flag.get()) Thread.sleep(200)
if (flag.get()) {
// PRoot ignores SIGTERM; SIGQUIT makes it kill its tracees and exit cleanly.
if (pid > 0) {
runCatching { android.system.Os.kill(pid, android.system.OsConstants.SIGQUIT) }
} else {
process.destroy()
}
if (!process.waitFor(3, java.util.concurrent.TimeUnit.SECONDS)) process.destroyForcibly()
}
} catch (_: InterruptedException) {
}
}, "guest-cancel").apply { isDaemon = true; start() }
}
try { try {
process.inputStream.bufferedReader().useLines { lines -> lines.forEach(onLine) } process.inputStream.bufferedReader().useLines { lines -> lines.forEach(onLine) }
return process.waitFor() return process.waitFor()
} finally { } finally {
watcher?.interrupt()
OrphanReaper.release(pid) OrphanReaper.release(pid)
} }
} }
@@ -110,11 +110,6 @@ public final class LinuxRuntime {
File root = rootDir(context); File root = rootDir(context);
List<String> binds = binds(context, sessionRoot, runtimeDir, externalStorage, extraBinds); List<String> binds = binds(context, sessionRoot, runtimeDir, externalStorage, extraBinds);
if (sessionRoot != null) lastBinds = binds; if (sessionRoot != null) lastBinds = binds;
return commandWithBinds(context, root, binds, guestCommand);
}
public static List<String> commandWithBinds(Context context, File root, List<String> binds,
List<String> guestCommand) {
List<String> cmd = prootPrefix(context, root, "/root"); List<String> cmd = prootPrefix(context, root, "/root");
for (String spec : binds) bind(cmd, spec); for (String spec : binds) bind(cmd, spec);
cmd.addAll(guestCommand); cmd.addAll(guestCommand);
@@ -160,10 +155,6 @@ public final class LinuxRuntime {
bind(cmd, "/dev"); bind(cmd, "/dev");
bind(cmd, "/proc"); bind(cmd, "/proc");
bind(cmd, "/sys"); bind(cmd, "/sys");
if (com.droiddeck.launcher.gpu.QualcommSystemDriver.selected(context)) {
for (String path : com.droiddeck.launcher.gpu.QualcommSystemDriver.mounts(context,
SessionPrefs.INSTANCE.linuxDriver(context))) bind(cmd, path);
}
bind(cmd, "/dev/urandom:/dev/random"); bind(cmd, "/dev/urandom:/dev/random");
bind(cmd, "/proc/self/fd:/dev/fd"); bind(cmd, "/proc/self/fd:/dev/fd");
bind(cmd, "/proc/self/fd/0:/dev/stdin"); bind(cmd, "/proc/self/fd/0:/dev/stdin");
@@ -299,50 +299,27 @@ public final class LinuxRuntimeInstaller {
discard(staging, null); discard(staging, null);
return false; return false;
} }
java.util.List<String> carryPaths = root.isDirectory()
? RuntimeFileTree.existingUserPaths(root, staging) : java.util.Collections.emptyList();
if (root.isDirectory() && !root.renameTo(old)) { if (root.isDirectory() && !root.renameTo(old)) {
RuntimeFileTree.delete(staging, null); RuntimeFileTree.delete(staging, null);
return false; return false;
} }
File carryMarker = new File(staging, CARRY_MARKER);
java.util.List<String> encodedPaths = new java.util.ArrayList<>();
for (String rel : carryPaths) encodedPaths.add(java.net.URLEncoder.encode(rel, "UTF-8"));
if (!FileUtils.writeString(carryMarker, String.join("\n", encodedPaths))) {
if (old.isDirectory() && !old.renameTo(root))
Log.w(TAG, "could not restore the previous runtime; retained at " + old);
discard(staging, null);
return false;
}
java.util.List<String> carried;
try { try {
carried = RuntimeFileTree.carryUserData(old, staging, false, carryPaths); RuntimeFileTree.carryHome(old, staging);
} catch (IOException e) { } catch (IOException e) {
Log.w(TAG, "could not carry user data across the update; rolling back", e); Log.w(TAG, "could not carry root across the update; rolling back", e);
if (old.isDirectory() && !old.renameTo(root)) old.renameTo(root);
Log.w(TAG, "could not restore the previous runtime; retained at " + old); try { RuntimeFileTree.delete(staging, null); }
if (e.getSuppressed().length == 0) { catch (IOException cleanup) { Log.w(TAG, "could not clear the failed staging tree", cleanup); }
new File(staging, CARRY_MARKER).delete();
try { RuntimeFileTree.delete(staging, null); }
catch (IOException cleanup) { Log.w(TAG, "could not clear the failed staging tree", cleanup); }
} else {
Log.w(TAG, "incomplete rollback; retaining user data in " + staging);
}
return false; return false;
} }
if (!staging.renameTo(root)) { if (!staging.renameTo(root)) {
if (old.isDirectory()) { File keptTo = new File(staging, USER_DATA);
try { if (keptTo.isDirectory() && old.isDirectory()) keptTo.renameTo(new File(old, USER_DATA));
RuntimeFileTree.carryBack(staging, old, carried); if (old.isDirectory()) old.renameTo(root);
new File(staging, CARRY_MARKER).delete();
} catch (IOException e) { Log.w(TAG, "could not move all user data back after a failed swap", e); }
old.renameTo(root);
}
return false; return false;
} }
new File(root, CARRY_MARKER).delete();
discard(old, null); discard(old, null);
return LinuxRuntime.isInstalled(context); return LinuxRuntime.isInstalled(context);
} catch (Exception e) { } catch (Exception e) {
@@ -353,41 +330,17 @@ public final class LinuxRuntimeInstaller {
} }
} }
static final String CARRY_MARKER = ".droiddeck-carry";
static void recoverInterruptedSwap(File root, File staging, File old) throws IOException { static void recoverInterruptedSwap(File root, File staging, File old) throws IOException {
if (!root.isDirectory() && old.isDirectory()) {
if (!old.renameTo(root)) throw new IOException("Cannot restore the previous runtime at " + old);
Log.w(TAG, "restored the previous runtime after an interrupted update");
}
File marker = new File(staging, CARRY_MARKER);
if (!RuntimeFileTree.exists(marker.toPath())) return;
File target = root.isDirectory() ? root : old; File target = root.isDirectory() ? root : old;
String markerContent = FileUtils.readString(marker);
if (markerContent == null) throw new IOException("Cannot read runtime recovery marker: " + marker);
if (!markerContent.equals("1")) {
java.util.List<String> intended = new java.util.ArrayList<>();
for (String rel : markerContent.split("\\n"))
if (!rel.isEmpty()) intended.add(java.net.URLDecoder.decode(rel, "UTF-8"));
if (target.isDirectory()) RuntimeFileTree.recoverCarriedPaths(staging, target, intended);
if (staging.isDirectory() && RuntimeFileTree.hasPaths(staging, intended))
throw new IOException("User data still needs recovery from " + staging);
marker.delete();
return;
}
File stagedHome = new File(staging, USER_DATA); File stagedHome = new File(staging, USER_DATA);
File home = new File(target, USER_DATA); File home = new File(target, USER_DATA);
if (target.isDirectory() && stagedHome.isDirectory() && (!RuntimeFileTree.exists(home.toPath()) || isEmptyDir(home))) { if (target.isDirectory() && stagedHome.isDirectory() && (!home.exists() || isEmptyDir(home))) {
RuntimeFileTree.carryHome(staging, target); RuntimeFileTree.carryHome(staging, target);
Log.w(TAG, "recovered " + USER_DATA + " from an interrupted update"); Log.w(TAG, "recovered " + USER_DATA + " from an interrupted update");
} }
if (target.isDirectory() && staging.isDirectory()) { if (!root.isDirectory() && old.isDirectory() && old.renameTo(root)) {
java.util.List<String> rest = RuntimeFileTree.carryUserData(staging, target, true); Log.w(TAG, "restored the previous runtime after an interrupted update");
if (!rest.isEmpty()) Log.w(TAG, "recovered " + rest + " from an interrupted update");
} }
if (staging.isDirectory() && RuntimeFileTree.hasUserData(staging, target))
throw new IOException("User data still needs recovery from " + staging);
new File(staging, CARRY_MARKER).delete();
} }
static final String TRASH = ".runtime-trash"; static final String TRASH = ".runtime-trash";
@@ -411,10 +364,9 @@ public final class LinuxRuntimeInstaller {
Log.i(TAG, "some runtime leftovers still cannot be deleted: " + trash); Log.i(TAG, "some runtime leftovers still cannot be deleted: " + trash);
} }
private static boolean isEmptyDir(File dir) throws IOException { private static boolean isEmptyDir(File dir) {
try (java.nio.file.DirectoryStream<java.nio.file.Path> entries = java.nio.file.Files.newDirectoryStream(dir.toPath())) { String[] names = dir.list();
return !entries.iterator().hasNext(); return dir.isDirectory() && names != null && names.length == 0;
}
} }
public static Removal beginUninstall(Context context) { public static Removal beginUninstall(Context context) {
@@ -74,163 +74,6 @@ public final class RuntimeFileTree {
throw new IOException("Cannot make directory removable: " + dir); throw new IOException("Cannot make directory removable: " + dir);
} }
/**
* Paths in a runtime tree that belong to the user: the home folder, imported AppImages and script apps, and catalog
* AppImages with their menu entries and markers. Tar-kind catalog packages (the desktop) unpack over /usr and cannot
* be carried.
*/
static java.util.List<String> userPaths(File tree) throws IOException {
java.util.List<String> paths = new java.util.ArrayList<>(java.util.Arrays.asList("root", "opt/appimages/user", "opt/droiddeck-apps"));
for (String n : children(new File(tree, "usr/local/share/applications"))) {
if (n.endsWith(".desktop") && (n.startsWith("droiddeck-app-") || n.startsWith("droiddeck-appimage-")))
paths.add("usr/local/share/applications/" + n);
}
for (String n : children(new File(tree, "opt/appimages"))) {
if (!n.endsWith(".AppImage")) continue;
String id = n.substring(0, n.length() - ".AppImage".length());
java.util.Collections.addAll(paths, "opt/appimages/" + n,
"usr/share/applications/droiddeck-" + id + ".desktop", ".droiddeck-pkg-" + id);
}
for (String n : children(new File(tree, "usr/share/applications"))) {
if (!n.startsWith("droiddeck-") || !n.endsWith(".desktop")) continue;
String id = n.substring("droiddeck-".length(), n.length() - ".desktop".length());
if (!exists(new File(tree, "opt/appimages/" + id + ".AppImage").toPath()))
paths.add("usr/share/applications/" + n);
}
for (String n : children(tree)) {
if (!n.startsWith(".droiddeck-pkg-")) continue;
String id = n.substring(".droiddeck-pkg-".length());
boolean hasMenu = exists(new File(tree, "usr/share/applications/droiddeck-" + id + ".desktop").toPath());
if (hasMenu && !exists(new File(tree, "opt/appimages/" + id + ".AppImage").toPath()))
paths.add(n);
}
return paths;
}
static java.util.List<String> existingUserPaths(File from, File to) throws IOException {
java.util.List<String> paths = new java.util.ArrayList<>();
for (String rel : userPaths(from, to)) if (exists(safePath(from, rel).toPath())) paths.add(rel);
return paths;
}
private static java.util.List<String> children(File dir) throws IOException {
java.util.List<String> names = new java.util.ArrayList<>();
try (DirectoryStream<Path> entries = Files.newDirectoryStream(dir.toPath())) {
for (Path entry : entries) names.add(entry.getFileName().toString());
} catch (NoSuchFileException e) {
return names;
}
return names;
}
static boolean exists(Path path) throws IOException {
try { Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); return true; }
catch (NoSuchFileException e) { return false; }
}
private static java.util.Set<String> userPaths(File from, File to) throws IOException {
java.util.Set<String> paths = new java.util.LinkedHashSet<>(userPaths(from));
paths.addAll(userPaths(to));
return paths;
}
static boolean hasUserData(File from, File to) throws IOException {
for (String rel : userPaths(from, to)) if (exists(new File(from, rel).toPath())) return true;
return false;
}
/**
* Moves each user path that exists in {@code from} into {@code to}, replacing what {@code to} ships there. With
* {@code onlyMissing}, a path already present in {@code to} is left alone. On failure the paths already moved go back
* before the exception is thrown. Rollback failures are suppressed on that exception; callers must retain the source
* of any incomplete rollback.
* Returns the moved paths.
*/
static java.util.List<String> carryUserData(File from, File to, boolean onlyMissing) throws IOException {
return carryUserData(from, to, onlyMissing, new java.util.ArrayList<>(userPaths(from, to)));
}
static java.util.List<String> carryUserData(File from, File to, boolean onlyMissing, java.util.List<String> paths) throws IOException {
java.util.List<String> moved = new java.util.ArrayList<>();
try {
for (String rel : paths) {
File src = safePath(from, rel);
if (!exists(src.toPath())) continue;
File dst = safePath(to, rel);
if (onlyMissing && exists(dst.toPath())) continue;
move(from, to, rel);
moved.add(rel);
}
} catch (IOException e) {
for (int i = moved.size() - 1; i >= 0; i--) {
try { move(to, from, moved.get(i)); }
catch (IOException back) { e.addSuppressed(back); }
}
throw e;
}
return moved;
}
/** Puts the given paths back from {@code from} into {@code to}; failures are collected, not stopped on. */
static void carryBack(File from, File to, java.util.List<String> paths) throws IOException {
IOException failed = null;
for (int i = paths.size() - 1; i >= 0; i--) {
try { move(from, to, paths.get(i)); }
catch (IOException e) { if (failed == null) failed = e; else failed.addSuppressed(e); }
}
if (failed != null) throw failed;
}
private static void move(File from, File to, String rel) throws IOException {
File src = safePath(from, rel);
File dst = safePath(to, rel);
File parent = src.getParentFile();
if (parent != null) makeWritable(parent);
java.util.List<File> made = new java.util.ArrayList<>();
for (File d = dst.getParentFile(); d != null; d = d.getParentFile()) {
made.add(d);
if (d.equals(to)) break;
}
for (int i = made.size() - 1; i >= 0; i--) {
File d = made.get(i);
if (!d.isDirectory() && !d.mkdirs()) throw new IOException("Cannot create " + d);
makeWritable(d);
}
delete(dst, null);
if (!src.renameTo(dst)) throw new IOException("Cannot carry " + rel + " across the update");
}
static void recoverCarriedPaths(File staging, File target, java.util.List<String> paths) throws IOException {
for (String rel : paths) {
File src = safePath(staging, rel);
if (!exists(src.toPath())) continue;
File dst = safePath(target, rel);
if (!exists(dst.toPath())) move(staging, target, rel);
}
}
static boolean hasPaths(File tree, java.util.List<String> paths) throws IOException {
for (String rel : paths) if (exists(safePath(tree, rel).toPath())) return true;
return false;
}
private static File safePath(File tree, String rel) throws IOException {
Path relative = java.nio.file.Paths.get(rel);
if (relative.isAbsolute() || relative.getNameCount() == 0) throw new IOException("Invalid runtime path: " + rel);
for (Path part : relative) if (part.toString().equals("..")) throw new IOException("Invalid runtime path: " + rel);
Path current = tree.toPath();
for (int i = 0; i < relative.getNameCount() - 1; i++) {
current = current.resolve(relative.getName(i));
try {
BasicFileAttributes attrs = Files.readAttributes(current, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
if (!attrs.isDirectory()) throw new IOException("Runtime path has a non-directory parent: " + current);
} catch (NoSuchFileException ignored) {
break;
}
}
return tree.toPath().resolve(relative).toFile();
}
static void carryHome(File old, File staging) throws IOException { static void carryHome(File old, File staging) throws IOException {
File home = new File(old, "root"); File home = new File(old, "root");
if (!home.isDirectory()) return; if (!home.isDirectory()) return;
@@ -56,9 +56,8 @@ class BatteryComponent(val dir: File, private val vpowerDir: File) : SessionPart
val timeToEmptyS = if (discharging && chargeNowUah > 0 && abs(currentAvgUa) > 0) chargeNowUah * 3600L / abs(currentAvgUa) else 0L val timeToEmptyS = if (discharging && chargeNowUah > 0 && abs(currentAvgUa) > 0) chargeNowUah * 3600L / abs(currentAvgUa) else 0L
val charging = status == BatteryManager.BATTERY_STATUS_CHARGING val charging = status == BatteryManager.BATTERY_STATUS_CHARGING
val timeToFullS = if (charging && chargeFullUah > chargeNowUah && abs(currentAvgUa) > 0) (chargeFullUah - chargeNowUah) * 3600L / abs(currentAvgUa) else 0L val timeToFullS = if (charging && chargeFullUah > chargeNowUah && abs(currentAvgUa) > 0) (chargeFullUah - chargeNowUah) * 3600L / abs(currentAvgUa) else 0L
// Android can keep reporting charging at 100%; Linux reports Full there, and Steam shows 99% until it does.
val statusText = when (status) { val statusText = when (status) {
BatteryManager.BATTERY_STATUS_CHARGING -> if (pct >= 100) "Full" else "Charging" BatteryManager.BATTERY_STATUS_CHARGING -> "Charging"
BatteryManager.BATTERY_STATUS_DISCHARGING -> "Discharging" BatteryManager.BATTERY_STATUS_DISCHARGING -> "Discharging"
BatteryManager.BATTERY_STATUS_FULL -> "Full" BatteryManager.BATTERY_STATUS_FULL -> "Full"
BatteryManager.BATTERY_STATUS_NOT_CHARGING -> "Not charging" BatteryManager.BATTERY_STATUS_NOT_CHARGING -> "Not charging"
@@ -51,7 +51,7 @@ object BootMovie {
SessionPrefs.setBootMovieApplyNext(context, true) SessionPrefs.setBootMovieApplyNext(context, true)
BootMovieReport.note(context, "picked $id here; Steam names ${SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context))}") BootMovieReport.note(context, "picked $id here; Steam names ${SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context))}")
// Whatever Steam names right now is about to be replaced, so it is not a pick to adopt later. // Whatever Steam names right now is about to be replaced, so it is not a pick to adopt later.
SessionFiles.startupMovieLocalPath(BootMovieLibrary.steamConfig(context))?.let { SessionPrefs.setBootMovieSteamSeen(context, it) } SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context))?.let { SessionPrefs.setBootMovieSteamSeen(context, it) }
} }
fun customName(context: Context): String? = fun customName(context: Context): String? =
@@ -167,12 +167,10 @@ object BootMovie {
* that movie becomes the choice here. Steam already plays it, so nothing is staged over it. True when the choice changed. * that movie becomes the choice here. Steam already plays it, so nothing is staged over it. True when the choice changed.
*/ */
fun syncFromSteam(context: Context): Boolean { fun syncFromSteam(context: Context): Boolean {
val named = SessionFiles.startupMovieLocalPath(BootMovieLibrary.steamConfig(context)) ?: return false val path = SessionFiles.startupMoviePath(BootMovieLibrary.steamConfig(context)) ?: return false
val seen = SessionPrefs.bootMovieSteamSeen(context) if (path == SessionPrefs.bootMovieSteamSeen(context)) return false
if (named == seen) return false SessionPrefs.setBootMovieSteamSeen(context, path)
SessionPrefs.setBootMovieSteamSeen(context, named) if (path == SessionFiles.BOOT_MOVIE_PATH) return false
if (named == SessionFiles.BOOT_MOVIE_PATH || (named.isEmpty() && seen == null)) return false
val path = named.ifEmpty { "/movies/steam_os_startup.webm" }
val prefix = "/uioverrides/movies/" val prefix = "/uioverrides/movies/"
// The list names a bought movie from the Steam folder (/config/communityitemscache/...), Steam's config from its config folder. // The list names a bought movie from the Steam folder (/config/communityitemscache/...), Steam's config from its config folder.
val id = if (path.startsWith(prefix)) BootMovieLibrary.idOf(path.removePrefix(prefix)) else { val id = if (path.startsWith(prefix)) BootMovieLibrary.idOf(path.removePrefix(prefix)) else {
@@ -79,9 +79,8 @@ object BootMovieLibrary {
return customMovieDirs(context).map { File(it, name) }.firstOrNull { it.isFile && it.length() > 0L } return customMovieDirs(context).map { File(it, name) }.firstOrNull { it.isFile && it.length() > 0L }
} }
private fun isMovie(file: File) = isWebm(file) && file.name !in STAGED private fun isMovie(file: File) = file.isFile && file.length() > 0L && file.name.endsWith(".webm", ignoreCase = true) &&
file.name !in STAGED && !file.name.startsWith(".")
private fun isWebm(file: File) = file.isFile && file.length() > 0L && file.name.endsWith(".webm", ignoreCase = true) && !file.name.startsWith(".")
private fun readMeta(context: Context): JSONObject = private fun readMeta(context: Context): JSONObject =
runCatching { JSONObject(metaFile(context).readText()) }.getOrDefault(JSONObject()) runCatching { JSONObject(metaFile(context).readText()) }.getOrDefault(JSONObject())
@@ -137,7 +136,7 @@ object BootMovieLibrary {
} }
val bought = HashMap<String, String>() val bought = HashMap<String, String>()
for (root in steamRoots(context)) { for (root in steamRoots(context)) {
File(root, "steamui/movies").listFiles { f -> isWebm(f) && f.nameWithoutExtension.lowercase() in NATIVE }.orEmpty() File(root, "steamui/movies").listFiles { f -> isMovie(f) && f.nameWithoutExtension.lowercase() in NATIVE }.orEmpty()
.sortedBy { it.name.lowercase() }.forEach { steam.putIfAbsent(STEAM_PREFIX + "/movies/" + it.name, it) } .sortedBy { it.name.lowercase() }.forEach { steam.putIfAbsent(STEAM_PREFIX + "/movies/" + it.name, it) }
val scan = pointShopMovies(root) val scan = pointShopMovies(root)
bought.putAll(scan.titles) bought.putAll(scan.titles)
@@ -145,8 +144,8 @@ object BootMovieLibrary {
} }
val seen = HashSet<String>() val seen = HashSet<String>()
for ((id, file) in steam) { for ((id, file) in steam) {
if (file.name in STAGED || !seen.add(file.canonicalPath)) continue
val native = file.nameWithoutExtension.lowercase() in NATIVE val native = file.nameWithoutExtension.lowercase() in NATIVE
if ((file.name in STAGED && !native) || !seen.add(file.canonicalPath)) continue
// Steam names a bought movie by an item number and a hash; the points shop's own title is shown when Steam has it. // Steam names a bought movie by an item number and a hash; the points shop's own title is shown when Steam has it.
val title = if (native) NATIVE[file.nameWithoutExtension.lowercase()] ?: file.nameWithoutExtension else bought[file.path] ?: boughtId(file)?.let { "#$it" } ?: file.nameWithoutExtension val title = if (native) NATIVE[file.nameWithoutExtension.lowercase()] ?: file.nameWithoutExtension else bought[file.path] ?: boughtId(file)?.let { "#$it" } ?: file.nameWithoutExtension
out.add(Entry(id, title, if (native) SOURCE_STEAM else SOURCE_POINTSHOP, file, removable = false)) out.add(Entry(id, title, if (native) SOURCE_STEAM else SOURCE_POINTSHOP, file, removable = false))
@@ -154,11 +153,8 @@ object BootMovieLibrary {
return out return out
} }
/** The four startup movies Steam ships with; Steam's movies folder holds many more videos that are not startup movies. */ /** The three startup movies Steam ships with; Steam's movies folder holds many more videos that are not startup movies. */
private val NATIVE = mapOf( private val NATIVE = mapOf("deck_startup" to "Deck startup", "oled_startup" to "Oled startup", "startup_machine" to "Machine startup")
"deck_startup" to "Deck startup", "oled_startup" to "Oled startup", "startup_machine" to "Machine startup",
"steam_os_startup" to "SteamOS startup",
)
private val skippedFolders = setOf("uioverrides", "steamapps", "librarycache", "httpcache", "logs", "compatdata", "shadercache") private val skippedFolders = setOf("uioverrides", "steamapps", "librarycache", "httpcache", "logs", "compatdata", "shadercache")
@@ -721,19 +721,13 @@ object ComponentsManager {
class StoredOriginal(val protonId: String, val protonName: String?, val comp: String, val protonVersion: String, val size: Long, val kept: Boolean) class StoredOriginal(val protonId: String, val protonName: String?, val comp: String, val protonVersion: String, val size: Long, val kept: Boolean)
class Stored(val packages: List<StoredPackage>, val originals: List<StoredOriginal>) class Stored(val packages: List<StoredPackage>, val originals: List<StoredOriginal>)
internal fun liveSelection(key: String, entry: JSONObject, proton: Proton?): Boolean = private fun packagesInUse(state: JSONObject): Set<String> {
proton != null && (key == "queued" || entry.optString("protonVersion") == proton.version)
private fun packagesInUse(state: JSONObject, installed: Map<String, Proton>): Set<String> {
val names = HashSet<String>() val names = HashSet<String>()
for (key in listOf("active", "queued")) { for (key in listOf("active", "queued")) {
val byProton = state.optJSONObject(key) ?: continue val byProton = state.optJSONObject(key) ?: continue
for (pid in byProton.keys()) { for (pid in byProton.keys()) {
val comps = byProton.optJSONObject(pid) ?: continue val comps = byProton.optJSONObject(pid) ?: continue
for (comp in comps.keys()) { for (comp in comps.keys()) comps.optJSONObject(comp)?.optString("file")?.takeIf { it.isNotEmpty() }?.let(names::add)
val entry = comps.optJSONObject(comp) ?: continue
if (liveSelection(key, entry, installed[pid])) entry.optString("file").takeIf { it.isNotEmpty() }?.let(names::add)
}
} }
} }
val profiles = state.optJSONObject("profiles") val profiles = state.optJSONObject("profiles")
@@ -753,8 +747,8 @@ object ComponentsManager {
fun stored(context: Context): Stored = synchronized(lock) { fun stored(context: Context): Stored = synchronized(lock) {
val state = loadState(context) val state = loadState(context)
val installed = protons(context).distinctBy { it.id }.associateBy { it.id } val used = packagesInUse(state)
val used = packagesInUse(state, installed) val installed = protons(context).associateBy { it.id }
val originals = originalsDir(context).listFiles()?.filter { it.isDirectory }?.flatMap { proton -> val originals = originalsDir(context).listFiles()?.filter { it.isDirectory }?.flatMap { proton ->
proton.listFiles()?.filter { it.isDirectory }?.flatMap { version -> proton.listFiles()?.filter { it.isDirectory }?.flatMap { version ->
COMPONENTS.mapNotNull { comp -> COMPONENTS.mapNotNull { comp ->
@@ -780,135 +774,27 @@ object ComponentsManager {
true true
} }
private fun checkPackageUnused(context: Context, state: JSONObject, name: String) { fun deletePackage(context: Context, file: String): String = synchronized(lock) {
val installed = protons(context).distinctBy { it.id }.associateBy { it.id } val name = safeName(file)
for (key in listOf("queued", "active")) { val state = loadState(context)
val byProton = state.sub(key) val queued = state.sub("queued")
for (pid in byProton.keys()) { for (pid in queued.keys()) {
val comps = byProton.optJSONObject(pid) ?: continue val comps = queued.optJSONObject(pid) ?: continue
for (comp in comps.keys()) { for (comp in comps.keys()) check(comps.optJSONObject(comp)?.optString("file") != name) { context.getString(R.string.cmgr_package_in_use, name, pid) }
val entry = comps.optJSONObject(comp) ?: continue }
check(entry.optString("file") != name || !liveSelection(key, entry, installed[pid])) { val active = state.sub("active")
context.getString(R.string.cmgr_package_in_use, name, installed[pid]?.name ?: pid) for (pid in active.keys()) {
} val comps = active.optJSONObject(pid) ?: continue
} for (comp in comps.keys()) check(comps.optJSONObject(comp)?.optString("file") != name) { context.getString(R.string.cmgr_package_in_use, name, pid) }
}
} }
val profiles = state.sub("profiles") val profiles = state.sub("profiles")
for (scope in profiles.keys()) { for (scope in profiles.keys()) {
val profile = profiles.optJSONObject(scope) ?: continue val profile = profiles.optJSONObject(scope) ?: continue
check(COMPONENTS.none { profile.optString(it) == name }) { context.getString(R.string.cmgr_package_in_use, name, scope) } check(COMPONENTS.none { profile.optString(it) == name }) { context.getString(R.string.cmgr_package_in_use, name, scope) }
} }
}
fun carryOver(context: Context, fromDir: String, toDir: String) {
synchronized(lock) {
val target = protons(context).firstOrNull { it.id == safeName(toDir) } ?: return
val state = loadState(context)
val wanted = carried(state, safeName(fromDir)) { File(packagesDir(context), it).isFile }
val active = state.sub("active").optJSONObject(target.id)
val queued = state.sub("queued").sub(target.id)
var changed = false
wanted.forEach { (comp, entry) ->
if (active?.has(comp) != true && !queued.has(comp)) {
queued.put(comp, entry)
changed = true
}
}
if (queued.length() == 0) state.sub("queued").remove(target.id)
if (changed) saveState(context, state)
}
}
internal fun carried(state: JSONObject, from: String, present: (String) -> Boolean): Map<String, JSONObject> = buildMap {
state.optJSONObject("active")?.optJSONObject(from)?.let { active ->
active.keys().forEach { comp ->
val entry = active.optJSONObject(comp) ?: return@forEach
val file = entry.optString("file")
if (comp in COMPONENTS && file.endsWith(".wcp") && present(file)) {
put(comp, JSONObject().put("kind", "package").put("file", file).put("label", entry.optString("label")))
}
}
}
state.optJSONObject("queued")?.optJSONObject(from)?.let { queued ->
queued.keys().forEach { comp ->
val entry = queued.optJSONObject(comp) ?: return@forEach
if (comp in COMPONENTS && entry.optString("kind") == "package" && present(entry.optString("file"))) put(comp, entry)
}
}
}
fun forgetProton(context: Context, dirName: String) {
synchronized(lock) {
val id = safeName(dirName)
if (protons(context).any { it.id == id }) return
val state = loadState(context)
val selected = listOf("active", "queued").map { state.sub(it).remove(id) != null }.any { it }
if (selected && runCatching { saveState(context, state) }.onFailure { Log.w(TAG, "forget $id", it) }.isFailure) return
File(originalsDir(context), id).deleteRecursively()
}
}
private fun storePackage(context: Context, part: File, dest: File) {
try {
if (dest.isFile && runCatching { Hashes.sha256(dest) }.getOrNull()?.equals(Hashes.sha256(part), true) == true) return
if (dest.exists()) checkPackageUnused(context, loadState(context), dest.name)
val store = File(launchDir(context), "store").canonicalFile
val cacheKey = unpackedCacheKey(dest.name)
val unpacked = File(store, cacheKey).canonicalFile
check(unpacked.parentFile == store) { "Invalid unpacked component cache path for ${dest.name}" }
val complete = File(unpacked, ".complete")
if (complete.exists()) check(complete.delete()) { "Could not invalidate unpacked component ${dest.name}" }
if (!part.renameTo(dest)) {
dest.delete()
check(part.renameTo(dest)) { "Could not store ${dest.name}" }
}
if (!unpacked.deleteRecursively() && unpacked.exists()) {
check(!complete.exists()) { "Could not invalidate unpacked component ${dest.name}" }
Log.w(TAG, "Could not remove stale unpacked files for ${dest.name}; cache marker is invalidated")
}
} finally {
part.delete()
}
}
internal fun unpackedCacheKey(filename: String): String = safeName(filename.removeSuffix(".wcp")).also {
require(it != "." && it != "..") { "Invalid component cache name" }
}
fun deletePackage(context: Context, file: String): String = synchronized(lock) {
val name = safeName(file)
val state = loadState(context)
val installed = protons(context).distinctBy { it.id }.associateBy { it.id }
var changed = false
for (key in listOf("queued", "active")) {
val byProton = state.sub(key)
for (pid in byProton.keys().asSequence().toList()) {
val comps = byProton.optJSONObject(pid) ?: continue
for (comp in comps.keys().asSequence().toList()) {
val entry = comps.optJSONObject(comp) ?: continue
if (entry.optString("file") != name) continue
check(!liveSelection(key, entry, installed[pid])) { context.getString(R.string.cmgr_package_in_use, name, installed[pid]?.name ?: pid) }
comps.remove(comp)
changed = true
}
if (comps.length() == 0) byProton.remove(pid)
}
}
val f = File(packagesDir(context), name) val f = File(packagesDir(context), name)
check(f.isFile) { context.getString(R.string.cmgr_package_not_stored, name) } check(f.isFile) { context.getString(R.string.cmgr_package_not_stored, name) }
val profiles = state.sub("profiles") f.delete()
for (scope in profiles.keys().asSequence().toList()) {
val profile = profiles.optJSONObject(scope) ?: continue
for (comp in COMPONENTS.filter { profile.optString(it) == name }) {
rememberProfiledComponent(state, comp)
profile.remove(comp)
changed = true
}
if (profile.length() == 0) profiles.remove(scope)
}
check(f.delete()) { name }
if (changed) saveState(context, state)
context.getString(R.string.cmgr_deleted, name) context.getString(R.string.cmgr_deleted, name)
} }
@@ -925,7 +811,7 @@ object ComponentsManager {
fun importPackage(context: Context, source: File, name: String): Package = synchronized(lock) { fun importPackage(context: Context, source: File, name: String): Package = synchronized(lock) {
val info = packageInfo(context, source) val info = packageInfo(context, source)
val dest = File(packagesDir(context), safeName(name).let { if (it.endsWith(".wcp")) it else "$it.wcp" }) val dest = File(packagesDir(context), safeName(name).let { if (it.endsWith(".wcp")) it else "$it.wcp" })
storePackage(context, source.copyTo(File(dest.parentFile, dest.name + ".part"), overwrite = true), dest) source.copyTo(File(dest.parentFile, dest.name + ".part"), overwrite = true).renameTo(dest)
info.copy(file = dest.name) info.copy(file = dest.name)
} }
@@ -948,7 +834,6 @@ object ComponentsManager {
.put("url", a.optString("browser_download_url")).put("size", a.optLong("size")).put("digest", a.optString("digest"))) .put("url", a.optString("browser_download_url")).put("size", a.optLong("size")).put("digest", a.optString("digest")))
} }
} }
if (items.length() == 0 && cache.isFile) runCatching { return parseCatalog(JSONObject(cache.readText())) }
val out = JSONObject().put("items", items).put("fetchedAt", System.currentTimeMillis() / 1000) val out = JSONObject().put("items", items).put("fetchedAt", System.currentTimeMillis() / 1000)
val tmp = File(cache.parentFile, cache.name + ".tmp") val tmp = File(cache.parentFile, cache.name + ".tmp")
tmp.writeText(out.toString()); tmp.renameTo(cache) tmp.writeText(out.toString()); tmp.renameTo(cache)
@@ -1078,7 +963,7 @@ object ComponentsManager {
} }
if (!Hashes.sha256(part).equals(item.digest.substringAfter(':'), true)) { part.delete(); error(context.getString(R.string.cmgr_checksum_mismatch)) } if (!Hashes.sha256(part).equals(item.digest.substringAfter(':'), true)) { part.delete(); error(context.getString(R.string.cmgr_checksum_mismatch)) }
val info = runCatching { packageInfo(context, part) }.getOrElse { part.delete(); throw it } val info = runCatching { packageInfo(context, part) }.getOrElse { part.delete(); throw it }
synchronized(lock) { storePackage(context, part, dest) } synchronized(lock) { part.renameTo(dest) }
return info.copy(file = dest.name) return info.copy(file = dest.name)
} }
} }
@@ -78,14 +78,6 @@ object GameEnvironmentStore {
return config return config
} }
@Synchronized
fun setDefault(context: Context, scope: String, name: String, value: String): Boolean {
val config = read(context)
if (GameEnvironment.hasOverride(config, scope, name)) return false
save(context, GameEnvironment.withScopeValue(config, scope, name, value))
return true
}
@Synchronized @Synchronized
fun publish(context: Context, config: GameEnvironment.Config = read(context)) { fun publish(context: Context, config: GameEnvironment.Config = read(context)) {
val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + config.shared) val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context), SessionPrefs.forceSsbs(context)) + config.shared)
@@ -14,12 +14,9 @@ object GameStorage {
fun options(context: Context): List<Option> { fun options(context: Context): List<Option> {
val sm = context.getSystemService(StorageManager::class.java) val sm = context.getSystemService(StorageManager::class.java)
val primary = context.getExternalFilesDir(null)?.absolutePath
val primaryStorage = Environment.getExternalStorageDirectory()?.absolutePath
return context.getExternalFilesDirs(null).orEmpty().filterNotNull().mapNotNull { dir -> return context.getExternalFilesDirs(null).orEmpty().filterNotNull().mapNotNull { dir ->
// Non-primary app dirs are usable even when Android reports the volume as non-removable (USB SSDs often do). val removable = try { Environment.isExternalStorageRemovable(dir) } catch (e: Exception) { false }
if (primary != null && dir.absolutePath == primary) return@mapNotNull null if (!removable) return@mapNotNull null
if (!primaryStorage.isNullOrBlank() && dir.absolutePath.startsWith("$primaryStorage/")) return@mapNotNull null
val volume = try { sm?.getStorageVolume(dir) } catch (e: Exception) { null } val volume = try { sm?.getStorageVolume(dir) } catch (e: Exception) { null }
val name = volume?.getDescription(context)?.takeIf { it.isNotBlank() && !it.equals("android", true) } ?: context.getString(R.string.gstore_sd_card) val name = volume?.getDescription(context)?.takeIf { it.isNotBlank() && !it.equals("android", true) } ?: context.getString(R.string.gstore_sd_card)
Option(context.getString(R.string.gstore_volume_free, name, free(dir)), File(dir, "steam").absolutePath, name) Option(context.getString(R.string.gstore_volume_free, name, free(dir)), File(dir, "steam").absolutePath, name)
@@ -87,10 +87,11 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
if (line.startsWith("== STEP ")) { if (line.startsWith("== STEP ")) {
stepAt = at stepAt = at
stepText = line.substringAfter("== STEP ").substringAfter(' ') stepText = line.substringAfter("== STEP ").substringAfter(' ')
clientDownload(line)?.let { (what, percent) -> val m = INSTALL_COUNT.find(line)
if (m != null) {
clientDownloadAt = at clientDownloadAt = at
clientDownload = what clientDownload = m.groupValues[1]
clientPercent = percent clientPercent = m.groupValues[2].toInt() * 100 / maxOf(1, m.groupValues[3].toInt())
} }
} else { } else {
val m = UPDATE_PROGRESS.find(line) val m = UPDATE_PROGRESS.find(line)
@@ -131,19 +132,6 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
} }
} }
internal fun clientDownload(line: String): Pair<String, Int>? {
val count = INSTALL_COUNT.find(line) ?: return null
val mb = INSTALL_MEGABYTES.find(line.substring(count.range.last + 1))
val done = mb?.groupValues?.get(1)?.toLongOrNull()
val total = mb?.groupValues?.get(2)?.toLongOrNull()
if (done != null && total != null && total > 0) {
return "$done / $total MB" to (done * 100 / total).toInt().coerceIn(0, 100)
}
val part = count.groupValues[2].toIntOrNull() ?: return null
val all = count.groupValues[3].toIntOrNull() ?: return null
return count.groupValues[1] to (part.toLong() * 100 / maxOf(1, all)).coerceIn(0L, 100L).toInt()
}
internal fun readableScriptStep(scriptStep: String): Boolean { internal fun readableScriptStep(scriptStep: String): Boolean {
val t = scriptStep.lowercase() val t = scriptStep.lowercase()
return t.startsWith("download") || t.startsWith("checking the linux") || t.startsWith("unpacking") || t.startsWith("installing") return t.startsWith("download") || t.startsWith("checking the linux") || t.startsWith("unpacking") || t.startsWith("installing")
@@ -152,6 +140,5 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
private const val TAIL_BYTES = 48L * 1024 private const val TAIL_BYTES = 48L * 1024
private val UPDATE_PROGRESS = Regex("""Downloading update \((\d+) of (\d+) KB\)""") private val UPDATE_PROGRESS = Regex("""Downloading update \((\d+) of (\d+) KB\)""")
private val INSTALL_COUNT = Regex("""downloading Steam: (\S+) \((\d+)/(\d+)\)""") private val INSTALL_COUNT = Regex("""downloading Steam: (\S+) \((\d+)/(\d+)\)""")
private val INSTALL_MEGABYTES = Regex("""^, (\d+) of (\d+) MB""")
} }
} }
@@ -1,175 +0,0 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.os.Handler
import android.os.Looper
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import com.droiddeck.launcher.R
import java.io.File
import java.util.Locale
internal object MemoryReadout {
data class Device(val totalKb: Long, val availableKb: Long, val swapTotalKb: Long, val swapFreeKb: Long) {
val usedKb get() = (totalKb - availableKb).coerceAtLeast(0)
val swapUsedKb get() = (swapTotalKb - swapFreeKb).coerceAtLeast(0)
}
data class Split(val gameKb: Long, val droiddeckKb: Long, val gpuKb: Long?)
fun parseMeminfo(text: String): Device? {
fun field(name: String) = Regex("""(?m)^$name:\s+(\d+) kB""").find(text)?.groupValues?.get(1)?.toLongOrNull()
val total = field("MemTotal") ?: return null
val available = field("MemAvailable") ?: return null
return Device(total, available, field("SwapTotal") ?: 0, field("SwapFree") ?: 0)
}
fun residentKb(status: String): Long {
fun field(name: String) = Regex("""(?m)^$name:\s+(\d+) kB""").find(status)?.groupValues?.get(1)?.toLongOrNull() ?: 0
return field("RssAnon") + field("RssShmem")
}
fun inWinePrefix(environ: ByteArray): Boolean {
var start = 0
val key = "WINEPREFIX=".toByteArray()
for (i in 0..environ.size) {
if (i == environ.size || environ[i] == 0.toByte()) {
if (i - start >= key.size && (key.indices).all { environ[start + it] == key[it] }) return true
start = i + 1
}
}
return false
}
fun androidKb(device: Device, split: Split): Long =
(device.usedKb - split.gameKb - split.droiddeckKb - (split.gpuKb ?: 0)).coerceAtLeast(0)
fun gb(kb: Long): String = String.format(Locale.US, "%.1f", kb / (1024.0 * 1024.0))
fun availableMb(): Long? = runCatching { parseMeminfo(File("/proc/meminfo").readText())?.availableKb?.div(1024) }.getOrNull()
fun device(): Device? = runCatching { parseMeminfo(File("/proc/meminfo").readText()) }.getOrNull()
fun split(root: Int = android.os.Process.myPid()): Split {
val parents = HashMap<Int, Int>()
File("/proc").listFiles()?.forEach { entry ->
val pid = entry.name.toIntOrNull() ?: return@forEach
parentOf(pid)?.let { parents[pid] = it }
}
val children = parents.entries.groupBy({ it.value }, { it.key })
var game = 0L
var droiddeck = 0L
val queue = ArrayDeque<Int>().apply { add(root) }
val seen = HashSet<Int>()
while (queue.isNotEmpty()) {
val pid = queue.removeFirst()
if (!seen.add(pid)) continue
val status = runCatching { File("/proc/$pid/status").readText() }.getOrNull()
if (status != null) {
val kb = residentKb(status)
val windows = pid != root && runCatching { inWinePrefix(File("/proc/$pid/environ").readBytes()) }.getOrDefault(false)
if (windows) game += kb else droiddeck += kb
}
children[pid]?.let(queue::addAll)
}
return Split(game, droiddeck, gpuKb())
}
private fun parentOf(pid: Int): Int? {
val stat = runCatching { File("/proc/$pid/stat").readText() }.getOrNull() ?: return null
val close = stat.lastIndexOf(')')
if (close < 0 || close + 2 >= stat.length) return null
return stat.substring(close + 2).split(' ').getOrNull(1)?.toIntOrNull()
}
private fun gpuKb(): Long? = runCatching {
File("/sys/class/kgsl/kgsl/page_alloc").readText().trim().split(Regex("\\s+"))[0].toLong() / 1024
}.getOrNull()
}
object MemoryLog {
private const val TAG = "Memory"
private const val PERIOD_MS = 10_000L
@Volatile private var thread: Thread? = null
internal fun line(device: MemoryReadout.Device, split: MemoryReadout.Split): String =
"used ${device.usedKb / 1024}/${device.totalKb / 1024} MB, available ${device.availableKb / 1024} MB, " +
"swap ${device.swapUsedKb / 1024}/${device.swapTotalKb / 1024} MB | game ${split.gameKb / 1024}, " +
"droiddeck ${split.droiddeckKb / 1024}, android ${MemoryReadout.androidKb(device, split) / 1024}, " +
"gpu ${split.gpuKb?.div(1024) ?: "?"} MB"
@Synchronized
fun start() {
if (thread != null) return
thread = Thread({
while (!Thread.currentThread().isInterrupted) {
runCatching { MemoryReadout.device()?.let { android.util.Log.i(TAG, line(it, MemoryReadout.split())) } }
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
}
}, "memory-log").apply { isDaemon = true; start() }
}
@Synchronized
fun stop() {
thread?.interrupt()
thread = null
}
}
class MemoryHud(context: Context) {
var text by mutableStateOf("")
private set
private val context = context.applicationContext
private val handler = Handler(Looper.getMainLooper())
@Volatile private var running = false
@Volatile private var generation = 0
private var thread: Thread? = null
fun refresh() {
if (SessionPrefs.memoryHud(context) == SessionPrefs.MEMORY_HUD_OFF) stop() else start()
}
fun start() {
if (running || SessionPrefs.memoryHud(context) == SessionPrefs.MEMORY_HUD_OFF) return
running = true
val token = ++generation
thread = Thread({
while (running && generation == token) {
val line = runCatching { sample() }.getOrDefault("")
handler.post { if (running && generation == token) text = line }
try { Thread.sleep(PERIOD_MS) } catch (e: InterruptedException) { break }
}
}, "memory-hud").apply { isDaemon = true; start() }
}
fun stop() {
running = false
generation++
thread?.interrupt()
thread = null
text = ""
}
private fun sample(): String {
val device = MemoryReadout.device() ?: return ""
val memory = context.getString(
R.string.memory_hud_simple,
MemoryReadout.gb(device.usedKb), MemoryReadout.gb(device.totalKb),
MemoryReadout.gb(device.swapUsedKb), MemoryReadout.gb(device.swapTotalKb),
)
if (SessionPrefs.memoryHud(context) != SessionPrefs.MEMORY_HUD_ADVANCED) return memory
val split = MemoryReadout.split()
val parts = context.getString(
R.string.memory_hud_split,
MemoryReadout.gb(split.gameKb), MemoryReadout.gb(split.droiddeckKb), MemoryReadout.gb(MemoryReadout.androidKb(device, split)),
)
val gpu = split.gpuKb?.let { context.getString(R.string.memory_hud_gpu, MemoryReadout.gb(it)) }
return listOfNotNull(memory, parts, gpu).joinToString("\n")
}
private companion object {
const val PERIOD_MS = 2000L
}
}
@@ -9,13 +9,11 @@ import com.droiddeck.launcher.stores.epic.EpicClient
object NoSteamLaunch { object NoSteamLaunch {
const val PROTON_RUN = "/usr/local/bin/droiddeck-proton-run" const val PROTON_RUN = "/usr/local/bin/droiddeck-proton-run"
const val EPIC = "/usr/local/bin/droiddeck-epic" const val EPIC = "/usr/local/bin/droiddeck-epic"
const val BATTLENET = com.droiddeck.launcher.runtime.BattleNet.PROGRAM
class Command(val program: String, val args: List<String>, val name: String) class Command(val program: String, val args: List<String>, val name: String)
fun scope(game: Library.SteamGame): String? = when { fun scope(game: Library.SteamGame): String? = when {
game.library == Library.EPIC_LAUNCHER -> EpicClient.shortcutAppId.toString() game.library == Library.EPIC_LAUNCHER -> EpicClient.shortcutAppId.toString()
game.library == Library.BATTLENET_LAUNCHER -> com.droiddeck.launcher.runtime.BattleNet.APP_ID.toString()
game.library == Library.ADDED || game.appId > 0 -> game.profileKey game.library == Library.ADDED || game.appId > 0 -> game.profileKey
else -> null else -> null
}?.takeIf { it.isNotEmpty() && GameEnvironment.validScope(it) } }?.takeIf { it.isNotEmpty() && GameEnvironment.validScope(it) }
@@ -32,8 +30,6 @@ object NoSteamLaunch {
fun command(game: Library.SteamGame, added: AddedGames.Game?): Command? = when { fun command(game: Library.SteamGame, added: AddedGames.Game?): Command? = when {
game.library == Library.EPIC_LAUNCHER -> Command(EPIC, listOf("run"), game.name) game.library == Library.EPIC_LAUNCHER -> Command(EPIC, listOf("run"), game.name)
game.library == Library.ADDED && game.source == com.droiddeck.launcher.stores.Store.BATTLENET.id ->
game.storeId?.let(com.droiddeck.launcher.runtime.BattleNet::title)?.let { Command(BATTLENET, listOf("launch", it.code), game.name) }
game.library == Library.ADDED -> added?.let { a -> a.steamAppId?.let { Command(PROTON_RUN, listOf("--app", it.toString()), a.name) } ?: addedCommand(a) } game.library == Library.ADDED -> added?.let { a -> a.steamAppId?.let { Command(PROTON_RUN, listOf("--app", it.toString()), a.name) } ?: addedCommand(a) }
game.appId > 0 -> Command(PROTON_RUN, listOf("--app", game.appId.toString()), game.name) game.appId > 0 -> Command(PROTON_RUN, listOf("--app", game.appId.toString()), game.name)
else -> null else -> null
@@ -41,9 +37,7 @@ object NoSteamLaunch {
fun addedCommand(game: AddedGames.Game): Command = Command( fun addedCommand(game: AddedGames.Game): Command = Command(
PROTON_RUN, PROTON_RUN,
listOf("--app", (game.appId and 0xFFFFFFFFL).toString(), "--dir", game.guestDir) + listOf("--app", (game.appId and 0xFFFFFFFFL).toString(), "--dir", game.guestDir, "--options", game.launchOptions, "--", game.guestExe),
(if (game.launchOptions.isEmpty()) emptyList() else listOf("--options", game.launchOptions)) +
listOf("--", game.guestExe),
game.name, game.name,
) )
@@ -56,7 +50,6 @@ object NoSteamLaunch {
fun nameFor(program: String?, args: List<String>): String? = when (program) { fun nameFor(program: String?, args: List<String>): String? = when (program) {
EPIC -> Library.EPIC_LAUNCHER_NAME EPIC -> Library.EPIC_LAUNCHER_NAME
BATTLENET -> args.getOrNull(args.indexOf("launch") + 1)?.takeIf { args.contains("launch") }?.let { names[it] } ?: com.droiddeck.launcher.stores.Store.BATTLENET.label
PROTON_RUN -> args.getOrNull(args.indexOf("--app") + 1)?.takeIf { args.contains("--app") }?.let { names[it] } PROTON_RUN -> args.getOrNull(args.indexOf("--app") + 1)?.takeIf { args.contains("--app") }?.let { names[it] }
else -> null else -> null
} }
@@ -65,6 +58,5 @@ object NoSteamLaunch {
fun remember(command: Command) { fun remember(command: Command) {
if (command.program == PROTON_RUN) command.args.getOrNull(command.args.indexOf("--app") + 1)?.let { names[it] = command.name } if (command.program == PROTON_RUN) command.args.getOrNull(command.args.indexOf("--app") + 1)?.let { names[it] = command.name }
if (command.program == BATTLENET) command.args.getOrNull(command.args.indexOf("launch") + 1)?.takeIf { command.args.contains("launch") }?.let { names[it] = command.name }
} }
} }
@@ -114,19 +114,12 @@ object ProtonDefault {
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
} }
internal fun movedGames(choices: Map<String, GameChoice?>, from: Set<String>, to: String): Map<String, GameChoice?>? {
if (choices.values.none { it != null && !it.valve && it.dir in from }) return null
return choices.mapValues { (_, choice) -> if (choice != null && !choice.valve && choice.dir in from) GameChoice(false, to) else choice }
}
@Synchronized @Synchronized
fun moveGames(context: Context, from: Set<String>, to: String) { fun requestGame(context: Context, scope: String, proton: ComponentsManager.Proton?): Outcome {
require(GameEnvironment.validScope(scope))
val d = dir(context) val d = dir(context)
val moved = movedGames(parseGames(read(File(d, GAMES))), from, to) ?: return val choices = parseGames(read(File(d, GAMES))).toMutableMap()
writeGames(d, moved) choices[scope] = proton?.let { GameChoice(it.valve, it.dir.name) }
}
private fun writeGames(d: File, choices: Map<String, GameChoice?>) {
val games = JSONObject() val games = JSONObject()
choices.forEach { (id, choice) -> choices.forEach { (id, choice) ->
games.put(id, choice?.let { JSONObject().put("valve", it.valve).put("dir", it.dir) } ?: JSONObject.NULL) games.put(id, choice?.let { JSONObject().put("valve", it.valve).put("dir", it.dir) } ?: JSONObject.NULL)
@@ -141,15 +134,6 @@ object ProtonDefault {
Log.w(TAG, "could not write the per-game Proton request", e) Log.w(TAG, "could not write the per-game Proton request", e)
throw e throw e
} }
}
@Synchronized
fun requestGame(context: Context, scope: String, proton: ComponentsManager.Proton?): Outcome {
require(GameEnvironment.validScope(scope))
val d = dir(context)
val choices = parseGames(read(File(d, GAMES))).toMutableMap()
choices[scope] = proton?.let { GameChoice(it.valve, it.dir.name) }
writeGames(d, choices)
val state = state(context) val state = state(context)
val tool = proton?.let { selected -> state.tools.firstOrNull { it.valve == selected.valve && it.dir == selected.dir.name } } val tool = proton?.let { selected -> state.tools.firstOrNull { it.valve == selected.valve && it.dir == selected.dir.name } }
return if (SessionState.running && state.live && (proton == null || tool != null && state.pending != tool.name)) { return if (SessionState.running && state.live && (proton == null || tool != null && state.pending != tool.name)) {
@@ -16,20 +16,16 @@ object ProtonExtras {
private const val TAG = "ProtonExtras" private const val TAG = "ProtonExtras"
private const val NEED_BYTES = 4L * 1024 * 1024 * 1024 private const val NEED_BYTES = 4L * 1024 * 1024 * 1024
private const val RELEASES = "https://api.github.com/repos/%s/releases?per_page=15" private const val RELEASES = "https://api.github.com/repos/%s/releases?per_page=15"
const val CHECK_EVERY_MS = 60L * 60 * 1000 const val CHECK_EVERY_MS = 6L * 60 * 60 * 1000
@Volatile @Volatile
var installInProgress = false var installInProgress = false
private set private set
@Volatile
private var replacing = false
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex) class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long, internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
val sha256: String? = null) val sha256: String? = null)
const val OWN = "droiddeck"
val tools = listOf( val tools = listOf(
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")), Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")), Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")),
@@ -82,23 +78,11 @@ object ProtonExtras {
fun update(context: Context, tool: Tool): String? = updateFor(installedTags(context, tool), cachedLatest(context, tool)) fun update(context: Context, tool: Tool): String? = updateFor(installedTags(context, tool), cachedLatest(context, tool))
fun missing(context: Context, tool: Tool): String? =
if (tool.id == OWN && !declined(context) && installedAll(context, tool).isEmpty()) cachedLatest(context, tool) else null
private fun choices(context: Context) = context.getSharedPreferences("proton-auto-updates", Context.MODE_PRIVATE)
fun declined(context: Context): Boolean = choices(context).getBoolean("$OWN.declined", false)
fun setDeclined(context: Context, declined: Boolean) {
choices(context).edit().putBoolean("$OWN.declined", declined).apply()
}
fun cachedLatest(context: Context, tool: Tool): String? = fun cachedLatest(context: Context, tool: Tool): String? =
readJson(latestFile(context)).optJSONObject(tool.id)?.optString("tag")?.ifEmpty { null } readJson(latestFile(context)).optJSONObject(tool.id)?.optString("tag")?.ifEmpty { null }
private val checkLock = Any() private val checkLock = Any()
private const val RETRY_MS = 15L * 60 * 1000 private const val RETRY_MS = 15L * 60 * 1000
private const val USER_SETTINGS = "user_settings.py"
private var lastAttempt = 0L private var lastAttempt = 0L
fun checkLatest(context: Context, force: Boolean = false, now: Long = System.currentTimeMillis()): Boolean { fun checkLatest(context: Context, force: Boolean = false, now: Long = System.currentTimeMillis()): Boolean {
@@ -152,51 +136,11 @@ object ProtonExtras {
fun remove(context: Context, tool: Tool, dir: String? = null) { fun remove(context: Context, tool: Tool, dir: String? = null) {
val name = if (dir != null) dir.takeIf { it in installedAll(context, tool) } ?: return else installed(context, tool) ?: return val name = if (dir != null) dir.takeIf { it in installedAll(context, tool) } ?: return else installed(context, tool) ?: return
if (File(toolsDir(context), name).deleteRecursively()) ComponentsManager.forgetProton(context, name) File(toolsDir(context), name).deleteRecursively()
} }
fun removeOlder(context: Context, tool: Tool) { fun removeOlder(context: Context, tool: Tool) {
installedAll(context, tool).dropLast(1).forEach { installedAll(context, tool).dropLast(1).forEach { File(toolsDir(context), it).deleteRecursively() }
if (File(toolsDir(context), it).deleteRecursively()) ComponentsManager.forgetProton(context, it)
}
}
private fun replaceOlder(context: Context, tool: Tool) {
val all = installedAll(context, tool)
val newest = all.lastOrNull() ?: return
val older = all.dropLast(1)
if (older.isEmpty()) return
replacing = true
try {
for (old in older.asReversed()) {
if (SessionState.running) break
if (runCatching { ComponentsManager.carryOver(context, old, newest) }.onFailure { Log.w(TAG, "components of $old", it) }.isFailure) continue
if (runCatching { keepUserSettings(context, old, newest) }.onFailure { Log.w(TAG, "user settings of $old", it) }.isFailure) continue
if (runCatching { ProtonDefault.moveGames(context, setOf(old), newest) }.onFailure { Log.w(TAG, "per-game picks of $old", it) }.isFailure) continue
if (File(toolsDir(context), old).deleteRecursively()) ComponentsManager.forgetProton(context, old)
else Log.w(TAG, "could not remove $old")
}
} finally {
replacing = false
}
}
private fun keepUserSettings(context: Context, old: String, newest: String) {
val from = File(File(toolsDir(context), old), USER_SETTINGS)
val to = File(File(toolsDir(context), newest), USER_SETTINGS)
if (from.isFile && !to.exists()) from.copyTo(to)
}
fun tidy(context: Context) {
val tool = tools.firstOrNull { it.id == OWN } ?: return
if (installedAll(context, tool).size > 1) replaceOlder(context, tool)
}
fun awaitReplacement(timeoutMs: Long) {
val until = System.currentTimeMillis() + timeoutMs
while (replacing && System.currentTimeMillis() < until) {
try { Thread.sleep(50) } catch (_: InterruptedException) { Thread.currentThread().interrupt(); return }
}
} }
@Synchronized @Synchronized
@@ -300,7 +244,6 @@ object ProtonExtras {
archive.delete() archive.delete()
unqueue(context, tool) unqueue(context, tool)
record(context, tool, placed, asset.tag) record(context, tool, placed, asset.tag)
if (tool.id == OWN) replaceOlder(context, tool)
if (EsyncPacks.enabled(context)) { if (EsyncPacks.enabled(context)) {
onProgress(context.getString(R.string.esync_fetching), -1) onProgress(context.getString(R.string.esync_fetching), -1)
try { try {
@@ -200,86 +200,22 @@ object SessionArtifacts {
internal fun recordedClient(dir: File): String? = internal fun recordedClient(dir: File): String? =
runCatching { File(dir, CLIENT_FILE).readText().trim() }.getOrNull()?.takeIf { it == "arm64" || it == "x86_64" } runCatching { File(dir, CLIENT_FILE).readText().trim() }.getOrNull()?.takeIf { it == "arm64" || it == "x86_64" }
private const val LOG_MARKS = "steam-log-marks.txt"
private const val MAX_STEAM_LOG = 8L * 1024 * 1024
private const val HEAD = 4096L
private class Mark(val size: Long, val head: String)
fun markSteamLogs(dir: File, logs: File) {
val lines = logs.listFiles { f -> f.isFile }?.mapNotNull { f ->
val size = f.length()
head(f, size)?.let { "$size\t$it\t${f.name}" }
} ?: return
runCatching { File(dir, LOG_MARKS).writeText(lines.joinToString("") { "$it\n" }) }
}
private fun head(f: File, length: Long): String? = runCatching {
val buf = ByteArray(minOf(length, HEAD).toInt())
f.inputStream().use { input ->
var off = 0
while (off < buf.size) {
val n = input.read(buf, off, buf.size - off)
if (n < 0) return@runCatching null
off += n
}
}
java.security.MessageDigest.getInstance("SHA-1").digest(buf).joinToString("") { "%02x".format(it) }
}.getOrNull()
private fun steamLogMarks(dir: File): List<Mark>? = runCatching {
File(dir, LOG_MARKS).readLines().mapNotNull { line ->
val parts = line.split('\t', limit = 3)
parts.getOrNull(0)?.toLongOrNull()?.let { size -> parts.getOrNull(1)?.let { Mark(size, it) } }
}
}.getOrNull()
private fun startOf(src: File, size: Long, marks: List<Mark>): Long {
val heads = HashMap<Long, String?>()
return marks.filter { it.size <= size }.sortedByDescending { it.size }
.firstOrNull { m -> heads.getOrPut(minOf(m.size, HEAD)) { head(src, m.size) } == m.head }?.size ?: 0L
}
private fun copySteamLogs(context: Context, dir: File, record: Record, steamArch: String? = null) { private fun copySteamLogs(context: Context, dir: File, record: Record, steamArch: String? = null) {
val logs = File(steamArch?.let { SessionPrefs.steamRoot(context, it) } ?: SessionPrefs.activeSteamRoot(context), "logs") val logs = File(steamArch?.let { SessionPrefs.steamRoot(context, it) } ?: SessionPrefs.activeSteamRoot(context), "logs")
if (!logs.isDirectory) return if (!logs.isDirectory) return
val out = File(dir, "steam").apply { mkdirs() } val out = File(dir, "steam").apply { mkdirs() }
copySessionLogs(logs, dir, out).forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) } logs.listFiles { f -> f.isFile && f.length() < 8L * 1024 * 1024 }?.forEach { src ->
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
}
internal fun copySessionLogs(logs: File, dir: File, out: File): List<File> {
val marks = steamLogMarks(dir)
val copied = ArrayList<File>()
logs.listFiles { f -> f.isFile }?.forEach { src ->
val size = src.length()
val from = marks?.let { startOf(src, size, it) } ?: 0L
if (marks != null && from == size || size - from >= MAX_STEAM_LOG) return@forEach
try { try {
val dst = File(out, src.name) val dst = File(out, src.name)
src.inputStream().buffered().use { input -> dst.bufferedWriter().use { w ->
var left = if (from > 0) from - 1 else 0L src.forEachLine { line -> w.write(LogRedactor.redact(line)); w.newLine() }
while (left > 0) {
val skipped = input.skip(left)
if (skipped <= 0) break
left -= skipped
}
if (from > 0 && input.read() != '\n'.code) {
while (true) {
val c = input.read()
if (c < 0 || c == '\n'.code) break
}
}
dst.bufferedWriter().use { w ->
input.bufferedReader().forEachLine { line -> w.write(LogRedactor.redact(line)); w.newLine() }
}
} }
copied.add(dst) record.files[dst] = Scrubbed(dst.length(), dst.lastModified())
} catch (e: Exception) { } catch (e: Exception) {
Log.w(TAG, "could not scrub ${src.name}", e) Log.w(TAG, "could not scrub ${src.name}", e)
} }
} }
return copied Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
} }
@Synchronized @Synchronized
@@ -79,5 +79,5 @@ object SessionDisplay {
} }
fun canStretch16x9(size: Pair<Int, Int>): Boolean = fun canStretch16x9(size: Pair<Int, Int>): Boolean =
(size.second * 16 + 4) / 9 / 2 * 2 > size.first || (size.first * 9 + 8) / 16 / 2 * 2 > size.second (size.second * 16 + 4) / 9 / 2 * 2 > size.first
} }
@@ -56,15 +56,11 @@ object SessionFiles {
"usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard", "usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard",
"usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window", "usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window",
"usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install", "usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install",
"usr/local/bin/droiddeck-steam-taskset" to "usr/local/bin/droiddeck-steam-taskset",
"usr/local/bin/droiddeck-steam-taskset" to "usr/local/libexec/droiddeck-steam/taskset",
"usr/local/bin/droiddeck-qualcomm-caps" to "usr/local/bin/droiddeck-qualcomm-caps",
"usr/local/bin/droiddeck-steam-ui-scale" to "usr/local/bin/droiddeck-steam-ui-scale", "usr/local/bin/droiddeck-steam-ui-scale" to "usr/local/bin/droiddeck-steam-ui-scale",
"usr/local/bin/droiddeck-steam-language" to "usr/local/bin/droiddeck-steam-language", "usr/local/bin/droiddeck-steam-language" to "usr/local/bin/droiddeck-steam-language",
"usr/local/bin/droiddeck-steam-shaders" to "usr/local/bin/droiddeck-steam-shaders", "usr/local/bin/droiddeck-steam-shaders" to "usr/local/bin/droiddeck-steam-shaders",
"usr/local/bin/droiddeck-steam-desktop-ui" to "usr/local/bin/droiddeck-steam-desktop-ui", "usr/local/bin/droiddeck-steam-desktop-ui" to "usr/local/bin/droiddeck-steam-desktop-ui",
"usr/local/bin/droiddeck-steam-library" to "usr/local/bin/droiddeck-steam-library", "usr/local/bin/droiddeck-steam-library" to "usr/local/bin/droiddeck-steam-library",
"usr/local/bin/droiddeck-steam-share" to "usr/local/bin/droiddeck-steam-share",
"usr/local/bin/droiddeck-seed-redists" to "usr/local/bin/droiddeck-seed-redists", "usr/local/bin/droiddeck-seed-redists" to "usr/local/bin/droiddeck-seed-redists",
"usr/local/bin/droiddeck-launcher-cores" to "usr/local/bin/droiddeck-launcher-cores", "usr/local/bin/droiddeck-launcher-cores" to "usr/local/bin/droiddeck-launcher-cores",
"usr/local/bin/droiddeck-proton-extra" to "usr/local/bin/droiddeck-proton-extra", "usr/local/bin/droiddeck-proton-extra" to "usr/local/bin/droiddeck-proton-extra",
@@ -77,7 +73,6 @@ object SessionFiles {
"usr/local/bin/droiddeck-steam-shortcuts" to "usr/local/bin/droiddeck-steam-shortcuts", "usr/local/bin/droiddeck-steam-shortcuts" to "usr/local/bin/droiddeck-steam-shortcuts",
"usr/local/bin/droiddeck-xbox" to "usr/local/bin/droiddeck-xbox", "usr/local/bin/droiddeck-xbox" to "usr/local/bin/droiddeck-xbox",
"usr/local/bin/droiddeck-store-launch" to "usr/local/bin/droiddeck-store-launch", "usr/local/bin/droiddeck-store-launch" to "usr/local/bin/droiddeck-store-launch",
"usr/local/bin/droiddeck-battlenet" to "usr/local/bin/droiddeck-battlenet",
"usr/local/bin/droiddeck-epic" to "usr/local/bin/droiddeck-epic", "usr/local/bin/droiddeck-epic" to "usr/local/bin/droiddeck-epic",
"usr/local/bin/droiddeck-epic-steam" to "usr/local/bin/droiddeck-epic-steam", "usr/local/bin/droiddeck-epic-steam" to "usr/local/bin/droiddeck-epic-steam",
"usr/local/bin/droiddeck-open-url" to "usr/local/bin/droiddeck-open-url", "usr/local/bin/droiddeck-open-url" to "usr/local/bin/droiddeck-open-url",
@@ -101,15 +96,6 @@ object SessionFiles {
"usr/local/bin/droiddeck-script-run" to "usr/local/bin/droiddeck-script-run", "usr/local/bin/droiddeck-script-run" to "usr/local/bin/droiddeck-script-run",
"usr/local/bin/droiddeck-open" to "usr/local/bin/droiddeck-open", "usr/local/bin/droiddeck-open" to "usr/local/bin/droiddeck-open",
"usr/local/bin/droiddeck-proton-run" to "usr/local/bin/droiddeck-proton-run", "usr/local/bin/droiddeck-proton-run" to "usr/local/bin/droiddeck-proton-run",
"usr/local/bin/droiddeck-innoextract" to "usr/local/bin/droiddeck-innoextract",
"usr/local/lib/droiddeck-inno/innoextract" to "usr/local/lib/droiddeck-inno/innoextract",
"usr/local/lib/droiddeck-inno/libboost_container.so.1.92.0" to "usr/local/lib/droiddeck-inno/libboost_container.so.1.92.0",
"usr/local/lib/droiddeck-inno/libboost_filesystem.so.1.92.0" to "usr/local/lib/droiddeck-inno/libboost_filesystem.so.1.92.0",
"usr/local/lib/droiddeck-inno/libboost_iostreams.so.1.92.0" to "usr/local/lib/droiddeck-inno/libboost_iostreams.so.1.92.0",
"usr/local/lib/droiddeck-inno/libboost_program_options.so.1.92.0" to "usr/local/lib/droiddeck-inno/libboost_program_options.so.1.92.0",
"usr/local/lib/droiddeck-inno/libboost_random.so.1.92.0" to "usr/local/lib/droiddeck-inno/libboost_random.so.1.92.0",
"usr/local/share/licenses/droiddeck-inno/LICENSE.innoextract" to "usr/local/share/licenses/droiddeck-inno/LICENSE.innoextract",
"usr/local/share/licenses/droiddeck-inno/LICENSE.boost" to "usr/local/share/licenses/droiddeck-inno/LICENSE.boost",
"usr/bin/steamos-update" to "usr/bin/steamos-update", "usr/bin/steamos-update" to "usr/bin/steamos-update",
"usr/bin/steamos-select-branch" to "usr/bin/steamos-select-branch", "usr/bin/steamos-select-branch" to "usr/bin/steamos-select-branch",
"usr/bin/steamos-session-select" to "usr/bin/steamos-session-select", "usr/bin/steamos-session-select" to "usr/bin/steamos-session-select",
@@ -154,8 +140,6 @@ object SessionFiles {
} + listOf("libvulkan-thunk.so", "libwebkitinput.so").map { "x86_64/$it" to "usr/local/lib/droiddeck-fex/x86_64/$it" } } + listOf("libvulkan-thunk.so", "libwebkitinput.so").map { "x86_64/$it" to "usr/local/lib/droiddeck-fex/x86_64/$it" }
val optional = (arrayOf( val optional = (arrayOf(
"usr/local/bin/gamescope" to "usr/local/bin/gamescope", "usr/local/bin/gamescope" to "usr/local/bin/gamescope",
// The gamescope pack carries its own WSI layer (patch 0117); it replaces the runtime's stock copy.
"usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so" to "usr/lib/libVkLayer_FROG_gamescope_wsi_aarch64.so",
"usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime", "usr/local/lib/droiddeck/uruntime" to "usr/local/lib/droiddeck/uruntime",
"usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst", "usr/local/lib/droiddeck-pipewire.tzst" to "usr/local/lib/droiddeck-pipewire.tzst",
"usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE", "usr/local/share/licenses/uruntime/LICENSE" to "usr/local/share/licenses/uruntime/LICENSE",
@@ -220,11 +204,7 @@ object SessionFiles {
if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) { if (!File(Environment.getExternalStorageDirectory(), NO_PAD_SWITCH).exists()) {
preload.append("/usr/local/lib/libfakeinput.so\n") preload.append("/usr/local/lib/libfakeinput.so\n")
} }
if (ProotFastPath.enabled(context)) { if (ProotFastPath.enabled(context)) preload.append(ProotFastPath.LIBRARY + "\n")
val library = com.droiddeck.launcher.agent.AgentEnv.fastPathLibrary(context)
preload.append(library + "\n")
if (startsSession && library != ProotFastPath.LIBRARY) Log.i(TAG, "fast path preload: $library (debugging override)")
}
val etc = File(root, "etc").apply { mkdirs() } val etc = File(root, "etc").apply { mkdirs() }
val staged = File(etc, "ld.so.preload.staged") val staged = File(etc, "ld.so.preload.staged")
if (!FileUtils.writeString(staged, preload.toString()) if (!FileUtils.writeString(staged, preload.toString())
@@ -410,12 +390,10 @@ object SessionFiles {
private fun activeStartupMovie(text: String): VdfBlock? = customizationMovie(text) ?: olderMovie(text) private fun activeStartupMovie(text: String): VdfBlock? = customizationMovie(text) ?: olderMovie(text)
/** The movie Steam's config selects, as a path like `/uioverrides/movies/x.webm`; null when none is named. */ /** The movie Steam's config selects, as a path like `/uioverrides/movies/x.webm`; null when none is named. */
internal fun startupMoviePath(config: File): String? = startupMovieLocalPath(config)?.takeIf { it.isNotEmpty() } internal fun startupMoviePath(config: File): String? {
internal fun startupMovieLocalPath(config: File): String? {
val text = runCatching { config.readText() }.getOrNull() ?: return null val text = runCatching { config.readText() }.getOrNull() ?: return null
val movie = activeStartupMovie(text) ?: return null val movie = activeStartupMovie(text) ?: return null
return scalar(text.substring(movie.keyStart, movie.close + 1), "LocalPath") return scalar(text.substring(movie.keyStart, movie.close + 1), "LocalPath")?.takeIf { it.isNotEmpty() }
} }
/** Both `StartupMovie` sections of Steam's config as written there, for the report; null when there is none. */ /** Both `StartupMovie` sections of Steam's config as written there, for the report; null when there is none. */
@@ -12,7 +12,6 @@ import androidx.compose.runtime.setValue
import androidx.core.content.FileProvider import androidx.core.content.FileProvider
import com.droiddeck.launcher.R import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.LogRedactor import com.droiddeck.launcher.core.LogRedactor
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File import java.io.File
import java.util.zip.ZipEntry import java.util.zip.ZipEntry
@@ -50,8 +49,7 @@ object SessionLogShare {
val logs = LinuxRuntime.logDir(context) val logs = LinuxRuntime.logDir(context)
val stores = recent(File(logs, STORES_DIR)) val stores = recent(File(logs, STORES_DIR))
val tools = recent(File(logs, SessionPaths.TOOLS_DIR)) val tools = recent(File(logs, SessionPaths.TOOLS_DIR))
val battleNet = battleNetLogs(context) val total = (files + live + stores + tools).sumOf { it.length() }.coerceAtLeast(1L)
val total = (files + live + stores + tools + battleNet.map { it.second }).sumOf { it.length() }.coerceAtLeast(1L)
var done = 0L var done = 0L
var shown = -1 var shown = -1
fun advance(f: File) { fun advance(f: File) {
@@ -64,7 +62,6 @@ object SessionLogShare {
live.forEach { f -> addEntry(z, folder.name + "/steam/" + f.name, f); advance(f) } live.forEach { f -> addEntry(z, folder.name + "/steam/" + f.name, f); advance(f) }
stores.forEach { f -> addEntry(z, "$STORES_DIR/" + f.name, f); advance(f) } stores.forEach { f -> addEntry(z, "$STORES_DIR/" + f.name, f); advance(f) }
tools.forEach { f -> addEntry(z, SessionPaths.TOOLS_DIR + "/" + f.name, f); advance(f) } tools.forEach { f -> addEntry(z, SessionPaths.TOOLS_DIR + "/" + f.name, f); advance(f) }
battleNet.forEach { (name, f) -> addEntry(z, "$BATTLENET_DIR/$name", f); advance(f) }
} }
return zip return zip
} }
@@ -91,27 +88,6 @@ object SessionLogShare {
private fun shareDir(context: Context): File = File(context.cacheDir, "share") private fun shareDir(context: Context): File = File(context.cacheDir, "share")
private const val BATTLENET_DIR = "battlenet"
private fun battleNetLogs(context: Context): List<Pair<String, File>> {
val drive = File(BattleNet.prefix(context), "pfx/drive_c")
val data = File(drive, "ProgramData/Battle.net")
fun logsUnder(dir: File, prefix: String) = dir.listFiles { f -> f.isDirectory && f.name.startsWith(prefix) }.orEmpty().map { File(it, "Logs") }
return newest("droiddeck", listOf(File(LinuxRuntime.rootDir(context), "root/.cache/droiddeck/battlenet")), 2, setOf("battlenet.log", "spawned.log")) +
newest("client", listOf(File(drive, "users/steamuser/AppData/Local/Battle.net/Logs")), 6) +
newest("agent", listOf(File(data, "Agent/Logs")) + logsUnder(File(data, "Agent"), "Agent."), 10, byDir = true) +
newest("setup", logsUnder(File(data, "Setup"), ""), 3, byDir = true)
}
private fun newest(folder: String, dirs: List<File>, count: Int, names: Set<String>? = null, byDir: Boolean = false): List<Pair<String, File>> {
val since = System.currentTimeMillis() - RECENT_DAYS * 86_400_000L
return dirs.flatMap { dir ->
dir.listFiles { f -> f.isFile && f.name.endsWith(".log") && (names == null || f.name in names) && f.lastModified() >= since && f.length() <= STEAM_LOG_MAX_BYTES }.orEmpty().toList()
}.sortedByDescending { it.lastModified() }.take(count).map { f ->
(if (byDir) "$folder/${f.parentFile?.parentFile?.name}/${f.name}" else "$folder/${f.name}") to f
}
}
private fun recent(dir: File): List<File> { private fun recent(dir: File): List<File> {
val since = System.currentTimeMillis() - RECENT_DAYS * 86_400_000L val since = System.currentTimeMillis() - RECENT_DAYS * 86_400_000L
return dir.listFiles { f -> f.isFile && f.lastModified() >= since }?.sortedBy { it.name }.orEmpty() return dir.listFiles { f -> f.isFile && f.lastModified() >= since }?.sortedBy { it.name }.orEmpty()
@@ -4,6 +4,7 @@ import android.content.Context
import android.content.pm.ActivityInfo import android.content.pm.ActivityInfo
import androidx.annotation.StringRes import androidx.annotation.StringRes
import com.droiddeck.launcher.R import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.CpuAllocationDefaults
import com.droiddeck.launcher.core.GameEnvironment import com.droiddeck.launcher.core.GameEnvironment
import com.droiddeck.launcher.core.TextureFiltering import com.droiddeck.launcher.core.TextureFiltering
import com.droiddeck.launcher.gpu.Cardboard import com.droiddeck.launcher.gpu.Cardboard
@@ -91,6 +92,13 @@ object SessionPrefs {
*/ */
fun storesEpicMode(context: Context): String = prefs(context).getString("storesEpicMode", "adaptive") ?: "adaptive" fun storesEpicMode(context: Context): String = prefs(context).getString("storesEpicMode", "adaptive") ?: "adaptive"
fun storesOpenTab(context: Context): String =
prefs(context).getString("storesOpenTab", STORES_OPEN_LIBRARY)?.takeIf { it == STORES_OPEN_STORE } ?: STORES_OPEN_LIBRARY
fun setStoresOpenTab(context: Context, tab: String) {
prefs(context).edit().putString("storesOpenTab", if (tab == STORES_OPEN_STORE) STORES_OPEN_STORE else STORES_OPEN_LIBRARY).apply()
}
fun storesShowMature(context: Context): Boolean = prefs(context).getBoolean("storesShowMature", false) fun storesShowMature(context: Context): Boolean = prefs(context).getBoolean("storesShowMature", false)
fun setStoresShowMature(context: Context, show: Boolean) { fun setStoresShowMature(context: Context, show: Boolean) {
@@ -128,6 +136,9 @@ object SessionPrefs {
val STORES_SORTS = listOf("lastPlayed", "recentlyInstalled", "titleAsc", "titleDesc", "sizeDesc", "sizeAsc", "releaseDateDesc") val STORES_SORTS = listOf("lastPlayed", "recentlyInstalled", "titleAsc", "titleDesc", "sizeDesc", "sizeAsc", "releaseDateDesc")
val STORES_VIEWS = listOf("cards", "capsules", "list") val STORES_VIEWS = listOf("cards", "capsules", "list")
const val STORES_OPEN_LIBRARY = "library"
const val STORES_OPEN_STORE = "store"
fun storesInstallTarget(context: Context): String = prefs(context).getString("storesInstallTarget", "") ?: "" fun storesInstallTarget(context: Context): String = prefs(context).getString("storesInstallTarget", "") ?: ""
fun setStoresInstallTarget(context: Context, path: String) { fun setStoresInstallTarget(context: Context, path: String) {
@@ -141,34 +152,6 @@ object SessionPrefs {
prefs(context).edit().putString("storesInstallLanguage", code).apply() prefs(context).edit().putString("storesInstallLanguage", code).apply()
} }
const val DEFAULT_STORAGE_ASK = "ask"
const val DEFAULT_STORAGE_INTERNAL = "internal"
const val DEFAULT_STORAGE_EXTERNAL = "external"
private val DEFAULT_STORAGE_VALUES = setOf(DEFAULT_STORAGE_ASK, DEFAULT_STORAGE_INTERNAL, DEFAULT_STORAGE_EXTERNAL)
fun defaultStorage(context: Context): String =
prefs(context).getString("defaultStorage", DEFAULT_STORAGE_ASK)
?.takeIf { it in DEFAULT_STORAGE_VALUES } ?: DEFAULT_STORAGE_ASK
fun setDefaultStorage(context: Context, value: String) {
prefs(context).edit().putString("defaultStorage", value.takeIf { it in DEFAULT_STORAGE_VALUES } ?: DEFAULT_STORAGE_ASK).apply()
}
fun defaultStorageFolder(context: Context): String = prefs(context).getString("defaultStorageFolder", "") ?: ""
fun defaultStorageFolderLabel(context: Context): String = prefs(context).getString("defaultStorageFolderLabel", "") ?: ""
fun setDefaultStorageFolder(context: Context, path: String, label: String) {
prefs(context).edit()
.putString("defaultStorageFolder", path)
.putString("defaultStorageFolderLabel", label)
.apply()
}
fun clearDefaultStorageFolder(context: Context) {
prefs(context).edit().remove("defaultStorageFolder").remove("defaultStorageFolderLabel").apply()
}
fun gameStoresParallel(context: Context): Int = prefs(context).getInt("gameStoresParallel", 1).coerceIn(1, 3) fun gameStoresParallel(context: Context): Int = prefs(context).getInt("gameStoresParallel", 1).coerceIn(1, 3)
fun setGameStoresParallel(context: Context, count: Int) { fun setGameStoresParallel(context: Context, count: Int) {
@@ -399,19 +382,30 @@ object SessionPrefs {
prefs(context).edit().putBoolean("wifiDiscoveryAsked", true).apply() prefs(context).edit().putBoolean("wifiDiscoveryAsked", true).apply()
} }
fun clientCpusOverride(context: Context): Boolean = prefs(context).getBoolean("clientCpusOverride", false) internal data class CoreAllocation(val clientOverride: Boolean, val clientCpus: String, val gameCpus: String)
internal fun coreAllocation(context: Context, defaults: CpuAllocationDefaults.Allocation? = CpuAllocationDefaults.device): CoreAllocation {
val saved = prefs(context)
return CoreAllocation(
saved.getBoolean("clientCpusOverride", defaults != null && !saved.contains("clientCpus")),
saved.getString("clientCpus", defaults?.client.orEmpty()).orEmpty(),
saved.getString("gameCpus", defaults?.game.orEmpty()).orEmpty(),
)
}
fun clientCpusOverride(context: Context): Boolean = coreAllocation(context).clientOverride
fun setClientCpusOverride(context: Context, on: Boolean) { fun setClientCpusOverride(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("clientCpusOverride", on).apply() prefs(context).edit().putBoolean("clientCpusOverride", on).apply()
} }
fun clientCpus(context: Context): String = prefs(context).getString("clientCpus", "").orEmpty() fun clientCpus(context: Context): String = coreAllocation(context).clientCpus
fun setClientCpus(context: Context, list: String) { fun setClientCpus(context: Context, list: String) {
prefs(context).edit().putString("clientCpus", list).apply() prefs(context).edit().putString("clientCpus", list).apply()
} }
fun gameCpus(context: Context): String = prefs(context).getString("gameCpus", "").orEmpty() fun gameCpus(context: Context): String = coreAllocation(context).gameCpus
fun setGameCpus(context: Context, list: String) { fun setGameCpus(context: Context, list: String) {
prefs(context).edit().putString("gameCpus", list).apply() prefs(context).edit().putString("gameCpus", list).apply()
@@ -481,24 +475,6 @@ object SessionPrefs {
prefs(context).edit().putBoolean("gamescopeRealtime", on).apply() prefs(context).edit().putBoolean("gamescopeRealtime", on).apply()
} }
fun ramCapMb(context: Context): Int = prefs(context).getInt("ramCapMb", 0).coerceAtLeast(0)
fun setRamCapMb(context: Context, mb: Int) {
prefs(context).edit().putInt("ramCapMb", mb.coerceAtLeast(0)).apply()
}
fun zramClient(context: Context): Boolean = prefs(context).getBoolean("zramClient", true)
fun setZramClient(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("zramClient", on).apply()
}
fun vramCapMb(context: Context): Int = prefs(context).getInt("vramCapMb", 0).coerceAtLeast(0)
fun setVramCapMb(context: Context, mb: Int) {
prefs(context).edit().putInt("vramCapMb", mb.coerceAtLeast(0)).apply()
}
fun gpuClockPin(context: Context): Boolean = prefs(context).getBoolean("gpuClockPin", false) fun gpuClockPin(context: Context): Boolean = prefs(context).getBoolean("gpuClockPin", false)
fun setGpuClockPin(context: Context, on: Boolean) { fun setGpuClockPin(context: Context, on: Boolean) {
@@ -600,32 +576,6 @@ object SessionPrefs {
prefs(context).edit().putBoolean("logs", on).apply() prefs(context).edit().putBoolean("logs", on).apply()
} }
fun battleNetNoSteamSet(context: Context): Boolean = prefs(context).getBoolean("battleNetNoSteamSet", false)
fun setBattleNetNoSteamSet(context: Context) { prefs(context).edit().putBoolean("battleNetNoSteamSet", true).apply() }
fun clearCachedApps(context: Context): Boolean = prefs(context).getBoolean("clearCachedApps", false)
fun setClearCachedApps(context: Context, on: Boolean) { prefs(context).edit().putBoolean("clearCachedApps", on).apply() }
fun backgroundAppLimit(context: Context): Int =
prefs(context).getInt("backgroundAppLimit", com.droiddeck.launcher.core.BackgroundAppLimit.OFF)
.takeIf { it in com.droiddeck.launcher.core.BackgroundAppLimit.CHOICES } ?: com.droiddeck.launcher.core.BackgroundAppLimit.OFF
fun setBackgroundAppLimit(context: Context, limit: Int) {
require(limit in com.droiddeck.launcher.core.BackgroundAppLimit.CHOICES)
prefs(context).edit().putInt("backgroundAppLimit", limit).apply()
}
const val MEMORY_HUD_OFF = "off"
const val MEMORY_HUD_SIMPLE = "simple"
const val MEMORY_HUD_ADVANCED = "advanced"
fun memoryHud(context: Context): String =
prefs(context).getString("memoryHud", MEMORY_HUD_OFF)
?.takeIf { it == MEMORY_HUD_SIMPLE || it == MEMORY_HUD_ADVANCED } ?: MEMORY_HUD_OFF
fun setMemoryHud(context: Context, value: String) {
require(value == MEMORY_HUD_OFF || value == MEMORY_HUD_SIMPLE || value == MEMORY_HUD_ADVANCED)
prefs(context).edit().putString("memoryHud", value).apply()
}
fun storageDiagnosticsEnabled(context: Context): Boolean = fun storageDiagnosticsEnabled(context: Context): Boolean =
prefs(context).getBoolean("storageDiagnostics", false) prefs(context).getBoolean("storageDiagnostics", false)
@@ -903,7 +853,7 @@ object SessionPrefs {
prefs(context).edit().putBoolean("hdr.$mode", on).apply() prefs(context).edit().putBoolean("hdr.$mode", on).apply()
} }
fun fpsLimit(context: Context, mode: String): Int = prefs(context).getInt("fpsLimit.$mode", 0).coerceAtLeast(0) fun fpsLimit(context: Context, mode: String): Int = prefs(context).getInt("fpsLimit.$mode", 0)
fun setFpsLimit(context: Context, mode: String, fps: Int) { fun setFpsLimit(context: Context, mode: String, fps: Int) {
prefs(context).edit().putInt("fpsLimit.$mode", fps.coerceAtLeast(0)).apply() prefs(context).edit().putInt("fpsLimit.$mode", fps.coerceAtLeast(0)).apply()
@@ -914,22 +864,6 @@ object SessionPrefs {
fun fpsLimitChoices(context: Context): List<Pair<Int, String>> = fun fpsLimitChoices(context: Context): List<Pair<Int, String>> =
fpsLimitChoices.map { (fps, label) -> fps to if (fps == 0) context.getString(R.string.frame_gen_off) else label } fpsLimitChoices.map { (fps, label) -> fps to if (fps == 0) context.getString(R.string.frame_gen_off) else label }
/**
* Performance mode: without a frame limit, buffers go back to the game as soon as they are replaced
* instead of once per refresh, and gamescope's WSI layer and winex11 reuse their per-present window checks.
*/
fun performanceMode(context: Context, mode: String): Boolean = prefs(context).getBoolean("performanceMode.$mode", false)
fun setPerformanceMode(context: Context, mode: String, on: Boolean) {
prefs(context).edit().putBoolean("performanceMode.$mode", on).apply()
}
/** Compositor frame limit that releases buffers to the game unpaced. */
const val FPS_UNPACED = -1
/** The limit handed to the compositor: Performance mode without a limit is unpaced, a chosen limit still paces. */
fun compositorFpsLimit(limit: Int, performanceMode: Boolean): Int = if (performanceMode && limit <= 0) FPS_UNPACED else limit
val upscalerChoices = listOf( val upscalerChoices = listOf(
0 to "Linear", 2 to "Nearest", 4 to "AMD FSR 1", 3 to "Snapdragon GSR", 0 to "Linear", 2 to "Nearest", 4 to "AMD FSR 1", 3 to "Snapdragon GSR",
8 to "Snapdragon GSR (quality)", 7 to "NVIDIA NIS", 6 to "Sharpen only", 8 to "Snapdragon GSR (quality)", 7 to "NVIDIA NIS", 6 to "Sharpen only",
@@ -71,7 +71,6 @@ class SessionService : Service() {
private val steamDownloadMonitor = SteamDownloadMonitor() private val steamDownloadMonitor = SteamDownloadMonitor()
private var downloadMonitorTask: Runnable? = null private var downloadMonitorTask: Runnable? = null
private var downloadActive = false private var downloadActive = false
private var clientInstallActive = false
@Volatile private var steamLibraryMounts = emptyMap<String, File>() @Volatile private var steamLibraryMounts = emptyMap<String, File>()
private var suspendDownloadNow = false private var suspendDownloadNow = false
private var suspendPolicy = SessionPrefs.SUSPEND_MANUAL private var suspendPolicy = SessionPrefs.SUSPEND_MANUAL
@@ -278,16 +277,6 @@ class SessionService : Service() {
updateSuspendPolicy() updateSuspendPolicy()
return START_NOT_STICKY return START_NOT_STICKY
} }
ACTION_MIC_CHANGED -> {
if (SessionState.running && SessionState.micAvailable && !SessionState.suspended) {
val enabled = intent.getBooleanExtra("enabled", false)
val relay = components.firstNotNullOfOrNull { it as? DirectAudioRelayComponent }
if (relay?.setMicEnabled(enabled) != true) {
android.widget.Toast.makeText(this, R.string.drawer_mic_failed, android.widget.Toast.LENGTH_LONG).show()
}
}
return START_NOT_STICKY
}
ACTION_SUSPEND_POLICY_CHANGED -> { ACTION_SUSPEND_POLICY_CHANGED -> {
if (!SessionState.running) return START_NOT_STICKY if (!SessionState.running) return START_NOT_STICKY
suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode) suspendPolicy = SessionPrefs.suspendPolicy(this, SessionState.mode)
@@ -332,15 +321,12 @@ class SessionService : Service() {
suspendDownloadNow = false suspendDownloadNow = false
steamDownloadMonitor.reset() steamDownloadMonitor.reset()
downloadActive = false downloadActive = false
clientInstallActive = false
steamSleepToken = null steamSleepToken = null
completeNativeSleep() completeNativeSleep()
suspendOperationPending = false suspendOperationPending = false
freezePending = false freezePending = false
suspendAttemptFailed = false suspendAttemptFailed = false
suspendController = null suspendController = null
SessionState.micAvailable = false
SessionState.micEnabled = false
SessionState.suspended = false SessionState.suspended = false
SessionState.resumeRequested = false SessionState.resumeRequested = false
SessionState.resuming = false SessionState.resuming = false
@@ -349,10 +335,8 @@ class SessionService : Service() {
pipTask = false pipTask = false
SessionState.program = intent?.getStringExtra(EXTRA_PROGRAM) SessionState.program = intent?.getStringExtra(EXTRA_PROGRAM)
SessionState.programArgs = intent?.getStringArrayExtra(EXTRA_PROGRAM_ARGS)?.toList().orEmpty() SessionState.programArgs = intent?.getStringArrayExtra(EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
SessionState.gameId = intent?.getStringExtra(EXTRA_GAME_ID)
SessionState.steamUi = intent?.getStringExtra(EXTRA_STEAM_UI) SessionState.steamUi = intent?.getStringExtra(EXTRA_STEAM_UI)
SessionState.steamUrl = intent?.getStringExtra(EXTRA_STEAM_URL) SessionState.steamUrl = intent?.getStringExtra(EXTRA_STEAM_URL)
com.droiddeck.launcher.stores.battlenet.BattleNetClient.clearRequests(LinuxRuntime.sessionRoot(this))
synchronized(stopLock) { synchronized(stopLock) {
SessionState.steamClientArch = null SessionState.steamClientArch = null
SessionState.running = true SessionState.running = true
@@ -367,9 +351,6 @@ class SessionService : Service() {
SessionEvents.transition(SessionPhase.STARTING_GUEST, "service.started", mapOf("mode" to SessionState.mode)) SessionEvents.transition(SessionPhase.STARTING_GUEST, "service.started", mapOf("mode" to SessionState.mode))
com.droiddeck.launcher.wayland.CompositorHost.newSession() com.droiddeck.launcher.wayland.CompositorHost.newSession()
val gen = ++sessionGen val gen = ++sessionGen
SessionPrefs.backgroundAppLimit(this).takeIf { it != com.droiddeck.launcher.core.BackgroundAppLimit.OFF }
?.let { com.droiddeck.launcher.core.BackgroundAppLimit.applyAsync(this, it) }
if (SessionPrefs.clearCachedApps(this)) clearCachedApps()
cancelQueuedSteamGame(clearMailbox = false) cancelQueuedSteamGame(clearMailbox = false)
clearSteamGameMailbox() clearSteamGameMailbox()
if (SessionState.mode == MODE_STEAM) SessionState.steamUrl if (SessionState.mode == MODE_STEAM) SessionState.steamUrl
@@ -377,16 +358,7 @@ class SessionService : Service() {
acquireLocks() acquireLocks()
Thread({ Thread({
OrphanReaper.reap("session starting") OrphanReaper.reap("session starting")
ProtonExtras.awaitReplacement(120_000) runSession(gen)
try {
runSession(gen)
} catch (e: com.droiddeck.launcher.gpu.QualcommSystemDriver.Unavailable) {
Log.e(TAG, "runtime driver unavailable", e)
if (gen == sessionGen) {
SessionEvents.fail(FAILURE_RUNTIME_DRIVER, e.message.orEmpty())
stopSession(-1)
}
}
}, "session-start").start() }, "session-start").start()
return START_NOT_STICKY return START_NOT_STICKY
} }
@@ -440,9 +412,6 @@ class SessionService : Service() {
killStragglers() killStragglers()
for (pack in listOf(AddonPack.PROOT, AddonPack.DIRECTAUDIO)) for (pack in listOf(AddonPack.PROOT, AddonPack.DIRECTAUDIO))
if (!pack.await(this, { gen == sessionGen && SessionState.running })) Log.w(TAG, "${pack.name} pack unavailable") if (!pack.await(this, { gen == sessionGen && SessionState.running })) Log.w(TAG, "${pack.name} pack unavailable")
val agentEnvironment = runCatching { com.droiddeck.launcher.agent.AgentEnv.beginSession(this) }
.onFailure { Log.w(TAG, "agent environment skipped", it) }
.getOrDefault(emptyList())
SessionFiles.stage(this, root, startsSession = true) SessionFiles.stage(this, root, startsSession = true)
// Earlier sessions' reports still read the Steam logs and VAC marker this session replaces. // Earlier sessions' reports still read the Steam logs and VAC marker this session replaces.
SessionArtifacts.awaitCollections() SessionArtifacts.awaitCollections()
@@ -466,7 +435,7 @@ class SessionService : Service() {
.onSuccess { if (it != null) Log.i(TAG, it) } .onSuccess { if (it != null) Log.i(TAG, it) }
.onFailure { Log.w(TAG, "forced components", it) } .onFailure { Log.w(TAG, "forced components", it) }
} }
addClientEnvironment(guest, steamHere, agentEnvironment) addClientEnvironment(guest, steamHere)
if (steamHere) guest.add("BL_EPIC_APP_ID=" + com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId) if (steamHere) guest.add("BL_EPIC_APP_ID=" + com.droiddeck.launcher.stores.epic.EpicClient.shortcutAppId)
val fastPathAt = guest.size val fastPathAt = guest.size
@@ -487,16 +456,6 @@ class SessionService : Service() {
Log.i(TAG, "hdr: gamescope --hdr-enabled, DXVK_HDR=1") Log.i(TAG, "hdr: gamescope --hdr-enabled, DXVK_HDR=1")
} }
guest.add("BL_FPS=" + SessionState.fpsLimit) guest.add("BL_FPS=" + SessionState.fpsLimit)
// gamescope's WSI layer and winex11 reuse their per-present window checks for this long; 0 checks on every present.
val windowCheckMs = if (SessionState.performanceMode) 100 else 0
guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=$windowCheckMs")
guest.add("WINE_OFFSCREEN_CHECK_MS=$windowCheckMs")
if (SessionPrefs.compositorFpsLimit(SessionState.fpsLimit, SessionState.performanceMode) == SessionPrefs.FPS_UNPACED) {
// gamescope turns buffers around slower than an unpaced game draws; more images keep it drawing.
guest.add("GAMESCOPE_WSI_MIN_IMAGE_COUNT=8")
guest.add("GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT=1")
}
Log.i(TAG, "performance mode " + (if (SessionState.performanceMode) "on" else "off") + ", frame limit " + SessionState.fpsLimit)
guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz)) guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz))
guest.add("BL_LOG=" + sessionLog.path) guest.add("BL_LOG=" + sessionLog.path)
guest.add("BL_DEBUG_DIR=" + sessionDir.path) guest.add("BL_DEBUG_DIR=" + sessionDir.path)
@@ -586,9 +545,6 @@ class SessionService : Service() {
Log.i(TAG, "proot: seccomp acceleration off by request") Log.i(TAG, "proot: seccomp acceleration off by request")
} }
fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> hostEnv[k] = v } } fastPathKey?.let { ProotFastPath.hostEnv(it).let { (k, v) -> hostEnv[k] = v } }
for (key in listOf("PROOT_PROFILE", "PROOT_PROFILE_SLOW_US")) {
guest.lastOrNull { it.startsWith("$key=") }?.substringAfter('=')?.let { hostEnv[key] = it }
}
val prootLibs = LinuxRuntime.prootLibraryPath(this) val prootLibs = LinuxRuntime.prootLibraryPath(this)
if (prootLibs.isNotEmpty()) hostEnv["LD_LIBRARY_PATH"] = prootLibs if (prootLibs.isNotEmpty()) hostEnv["LD_LIBRARY_PATH"] = prootLibs
@@ -631,7 +587,7 @@ class SessionService : Service() {
val program = programStatus(sessionRoot) val program = programStatus(sessionRoot)
Log.i(TAG, "session ended: $status" + if (program != null) " (program $program)" else "") Log.i(TAG, "session ended: $status" + if (program != null) " (program $program)" else "")
stopSession(program ?: status ?: -1) stopSession(program ?: status ?: -1)
}, null, sessionLog.takeIf { "PROOT_PROFILE=1" in hostEnv.asArray() }) }, null)
Log.i(TAG, "session pid $pid, log ${sessionLog.path}") Log.i(TAG, "session pid $pid, log ${sessionLog.path}")
if (gen != sessionGen || !SessionState.running) { if (gen != sessionGen || !SessionState.running) {
Log.i(TAG, "session stopped while its guest was starting; taking it down") Log.i(TAG, "session stopped while its guest was starting; taking it down")
@@ -684,8 +640,8 @@ class SessionService : Service() {
} }
}, },
) )
updateDownloadMonitoring()
mainHandler.post { updateSuspendPolicy() } mainHandler.post { updateSuspendPolicy() }
updateDownloadMonitoring()
} }
} }
@@ -700,11 +656,10 @@ class SessionService : Service() {
DeviceReport.write(this, File(sessionDir, "device.txt"), SessionState.mode) DeviceReport.write(this, File(sessionDir, "device.txt"), SessionState.mode)
NetworkReport.write(this, File(sessionDir, "network.txt")) NetworkReport.write(this, File(sessionDir, "network.txt"))
SessionLogCapture.start(File(sessionDir, "app.log")) SessionLogCapture.start(File(sessionDir, "app.log"))
MemoryLog.start()
return sessionDir return sessionDir
} }
private fun addClientEnvironment(guest: MutableList<String>, steamHere: Boolean, agentEnvironment: List<String>) { private fun addClientEnvironment(guest: MutableList<String>, steamHere: Boolean) {
guest.add("/usr/bin/env") guest.add("/usr/bin/env")
guest.add("-i") guest.add("-i")
guest.add("DROIDDECK_BWRAP_SOCKET=" + com.droiddeck.launcher.runtime.BwrapSpawner.socket(this)) guest.add("DROIDDECK_BWRAP_SOCKET=" + com.droiddeck.launcher.runtime.BwrapSpawner.socket(this))
@@ -727,10 +682,8 @@ class SessionService : Service() {
guest.add("MESA_LOADER_DRIVER_OVERRIDE=zink") guest.add("MESA_LOADER_DRIVER_OVERRIDE=zink")
guest.add("GALLIUM_DRIVER=zink") guest.add("GALLIUM_DRIVER=zink")
guest.add("LIBGL_KOPPER_DRI2=true") guest.add("LIBGL_KOPPER_DRI2=true")
LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
val linuxDriverId = SessionPrefs.linuxDriver(this) val linuxDriverId = SessionPrefs.linuxDriver(this)
val systemQualcomm = com.droiddeck.launcher.gpu.QualcommSystemDriver.handles(linuxDriverId)
if (systemQualcomm) com.droiddeck.launcher.gpu.QualcommSystemDriver.addEnvironment(this, guest)
else LinuxRuntime.vulkanIcd(this)?.let { guest.add("VK_ICD_FILENAMES=" + it.path) }
SessionState.runtimeDriver = linuxDriverId SessionState.runtimeDriver = linuxDriverId
com.droiddeck.launcher.gpu.AutoDriverTrial.sessionStarting( com.droiddeck.launcher.gpu.AutoDriverTrial.sessionStarting(
this, this,
@@ -740,9 +693,9 @@ class SessionService : Service() {
) )
LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId) LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) } ?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
val tuOverride = if (systemQualcomm) null else tuDebugOverride() val tuOverride = tuDebugOverride()
val tuDriver = sysmemDriver(linuxDriverId) val tuDriver = sysmemDriver(linuxDriverId)
if (!systemQualcomm) (tuOverride ?: "sysmem".takeIf { tuDriver || SessionPrefs.tuSysmem(this) })?.let { guest.add("TU_DEBUG=$it") } (tuOverride ?: "sysmem".takeIf { tuDriver || SessionPrefs.tuSysmem(this) })?.let { guest.add("TU_DEBUG=$it") }
if (SessionPrefs.zinkLazy(this)) { if (SessionPrefs.zinkLazy(this)) {
guest.add("ZINK_DESCRIPTORS=lazy") guest.add("ZINK_DESCRIPTORS=lazy")
guest.add("ZINK_DEBUG=compact") guest.add("ZINK_DEBUG=compact")
@@ -750,17 +703,12 @@ class SessionService : Service() {
if (SessionPrefs.glThread(this)) guest.add("mesa_glthread=true") if (SessionPrefs.glThread(this)) guest.add("mesa_glthread=true")
if (SessionPrefs.noGlError(this)) guest.add("MESA_NO_ERROR=1") if (SessionPrefs.noGlError(this)) guest.add("MESA_NO_ERROR=1")
guest.add("MESA_DISK_CACHE_DATABASE=1") guest.add("MESA_DISK_CACHE_DATABASE=1")
// Steam loads libhybris after other TLS users; its Bionic TLS bridge requires static storage. guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216")
val staticTls = if (systemQualcomm) ":glibc.rtld.optional_static_tls=16384" else ""
guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216$staticTls")
if (SessionState.mode == MODE_STEAM) guest.add("BL_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0")) if (SessionState.mode == MODE_STEAM) guest.add("BL_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0"))
SessionState.steamClientArch = if (steamHere) SessionPrefs.steamClientArch(this) else null SessionState.steamClientArch = if (steamHere) SessionPrefs.steamClientArch(this) else null
SessionState.steamClientArch?.let { arch -> SessionState.steamClientArch?.let { arch ->
guest.add("BL_STEAM_CLIENT_ARCH=$arch") guest.add("BL_STEAM_CLIENT_ARCH=$arch")
SessionPaths.current()?.let { SessionPaths.current()?.let { SessionArtifacts.recordClient(it, arch) }
SessionArtifacts.recordClient(it, arch)
SessionArtifacts.markSteamLogs(it, File(SessionPrefs.steamRoot(this, arch), "logs"))
}
if (arch == "x86_64") FexCatalog.cached(this)?.let { guest.addAll(FexCatalog.environment(it)) } if (arch == "x86_64") FexCatalog.cached(this)?.let { guest.addAll(FexCatalog.environment(it)) }
} }
if (SessionState.mode == MODE_STEAM) { if (SessionState.mode == MODE_STEAM) {
@@ -772,14 +720,9 @@ class SessionService : Service() {
guest.add("BL_FSYNC_FIRST=" + (if (SessionPrefs.fsyncFirst(this)) "1" else "0")) guest.add("BL_FSYNC_FIRST=" + (if (SessionPrefs.fsyncFirst(this)) "1" else "0"))
guest.add("BL_GAMESCOPE_REALTIME=" + (if (SessionPrefs.gamescopeRealtime(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") if (SessionPrefs.cursorComposite(this)) guest.add("BL_CURSOR_COMPOSITE=1")
if (com.droiddeck.launcher.core.ZramSupport.supported()) { if (com.droiddeck.launcher.core.ZramSupport.supported()) guest.add("BL_ZRAM=1")
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")
}
SessionPrefs.vramCapMb(this).takeIf { it > 0 }?.let { guest.add("BL_VRAM_MB=$it") }
guest.add("BANNER_AUDIO_DIRECT_DECAY=0") guest.add("BANNER_AUDIO_DIRECT_DECAY=0")
val extra = extraEnv() + agentEnvironment val extra = extraEnv() + com.droiddeck.launcher.agent.AgentEnv.beginSession(this)
if (extra.none { it.startsWith("TU_DEBUG=") }) guest.add("$GAME_TU_DEBUG=" + (tuOverride ?: if (tuDriver) "sysmem" else "")) if (extra.none { it.startsWith("TU_DEBUG=") }) guest.add("$GAME_TU_DEBUG=" + (tuOverride ?: if (tuDriver) "sysmem" else ""))
extra.forEach { guest.add(it) } extra.forEach { guest.add(it) }
com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice(this)?.let { guest.add("${com.droiddeck.launcher.gpu.TpUbwcHint.ENV}=$it") } com.droiddeck.launcher.gpu.TpUbwcHint.forThisDevice(this)?.let { guest.add("${com.droiddeck.launcher.gpu.TpUbwcHint.ENV}=$it") }
@@ -792,7 +735,7 @@ class SessionService : Service() {
} }
private fun noSteamGame(): Boolean = private fun noSteamGame(): Boolean =
SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC, NoSteamLaunch.BATTLENET) SessionState.mode == MODE_RUN && SessionState.program in setOf(NoSteamLaunch.PROTON_RUN, NoSteamLaunch.EPIC)
private fun startAudio(guest: MutableList<String>, sessionDir: File): PulseAudioComponent { private fun startAudio(guest: MutableList<String>, sessionDir: File): PulseAudioComponent {
val wantsDirectAudio = (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || noSteamGame()) && val wantsDirectAudio = (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || noSteamGame()) &&
@@ -813,15 +756,6 @@ class SessionService : Service() {
components.add(pulse) components.add(pulse)
if (wantsDirectAudio || wantsMic) { if (wantsDirectAudio || wantsMic) {
val relay = DirectAudioRelayComponent(relaySocket, micFifo) val relay = DirectAudioRelayComponent(relaySocket, micFifo)
val gen = sessionGen
relay.onMicEnabled = java.util.function.Consumer { enabled ->
mainHandler.post {
if (gen == sessionGen && SessionState.running && wantsMic) {
SessionState.micAvailable = true
SessionState.micEnabled = enabled
}
}
}
relay.setLogFile(audioLog) relay.setLogFile(audioLog)
relay.attach(this) relay.attach(this)
components.add(relay) components.add(relay)
@@ -1092,7 +1026,6 @@ class SessionService : Service() {
if (!stillSameProcess()) return if (!stillSameProcess()) return
val tree = descendants(prootPid) val tree = descendants(prootPid)
if (!stillSameProcess()) return if (!stillSameProcess()) return
saveWineRegistries(tree)
android.os.Process.sendSignal(prootPid, 15) android.os.Process.sendSignal(prootPid, 15)
if (!waitForExit(prootPid, GRACE_MS)) { if (!waitForExit(prootPid, GRACE_MS)) {
if (!stillSameProcess()) return if (!stillSameProcess()) return
@@ -1109,31 +1042,6 @@ class SessionService : Service() {
if (killed > 0) Log.i(TAG, "swept $killed process(es) proot left behind") if (killed > 0) Log.i(TAG, "swept $killed process(es) proot left behind")
} }
private fun clearCachedApps() {
val app = applicationContext
Thread({
val before = MemoryReadout.availableMb()
val result = runCatching { com.droiddeck.launcher.core.WirelessAdbFix.clearCachedApps(app) }
val after = MemoryReadout.availableMb()
result.onSuccess { Log.i(TAG, "cached apps closed: available memory $before -> $after MB") }
.onFailure { Log.w(TAG, "cached apps not closed: ${it.message}") }
}, "clear-cached-apps").start()
}
private fun saveWineRegistries(tree: List<Pair<Int, Long>>) {
val servers = tree.filter { (pid, started) ->
readStat(pid)?.second == started && WineProcesses.isWineserver(
runCatching { File("/proc/$pid/cmdline").readBytes() }.getOrNull(),
runCatching { File("/proc/$pid/comm").readText() }.getOrNull(),
)
}
if (servers.isEmpty()) return
servers.forEach { (pid, _) -> android.os.Process.sendSignal(pid, 15) }
val deadline = System.currentTimeMillis() + WINE_SAVE_MS
val saved = servers.count { (pid, _) -> waitForExit(pid, (deadline - System.currentTimeMillis()).coerceAtLeast(0)) }
Log.i(TAG, "wineserver registry save: $saved of ${servers.size} exited after SIGTERM")
}
private fun descendants(root: Int): List<Pair<Int, Long>> { private fun descendants(root: Int): List<Pair<Int, Long>> {
val started = HashMap<Int, Long>() val started = HashMap<Int, Long>()
val children = HashMap<Int, MutableList<Int>>() val children = HashMap<Int, MutableList<Int>>()
@@ -1413,11 +1321,6 @@ class SessionService : Service() {
} }
return return
} }
if (path == com.droiddeck.launcher.runtime.BattleNet.FEX_REQUEST) {
File(dir, path).delete()
com.droiddeck.launcher.runtime.BattleNet.answerFexRequest(this@SessionService, dir)
return
}
if (path != null && path.startsWith("desktop-import-") && path.endsWith(".request")) { if (path != null && path.startsWith("desktop-import-") && path.endsWith(".request")) {
val request = File(dir, path) val request = File(dir, path)
val text = runCatching { request.readText() }.getOrNull() ?: return val text = runCatching { request.readText() }.getOrNull() ?: return
@@ -1510,7 +1413,8 @@ class SessionService : Service() {
private fun updateSuspendPolicy() { private fun updateSuspendPolicy() {
if (!SessionState.running) return if (!SessionState.running) return
val hidden = !hasVisibleSurface val hidden = !hasVisibleSurface
val downloadsBlockingSuspend = downloadsKeepAwake() && hidden && !suspendDownloadNow val downloadsBlockingSuspend = steamDownloadsInBackground && SessionState.mode == MODE_STEAM &&
suspendPolicy != SessionPrefs.SUSPEND_NEVER && hidden && downloadActive && !suspendDownloadNow
if (suspendPolicy == SessionPrefs.SUSPEND_MANUAL && hidden && !downloadsBlockingSuspend) { if (suspendPolicy == SessionPrefs.SUSPEND_MANUAL && hidden && !downloadsBlockingSuspend) {
manualPauseRequested = true manualPauseRequested = true
} else if (!hidden && !SessionState.suspended) { } else if (!hidden && !SessionState.suspended) {
@@ -1701,8 +1605,6 @@ class SessionService : Service() {
runCatching { com.droiddeck.launcher.agent.AgentEnv.endSession(this) } runCatching { com.droiddeck.launcher.agent.AgentEnv.endSession(this) }
.onFailure { Log.w(TAG, "clearing the agent's session environment", it) } .onFailure { Log.w(TAG, "clearing the agent's session environment", it) }
releaseLocks() releaseLocks()
MemoryLog.stop()
com.droiddeck.launcher.core.BackgroundAppLimit.restoreAsync(applicationContext)
if (status == 0) { if (status == 0) {
SessionEvents.transition(SessionPhase.IDLE, "session.stopped", mapOf("status" to status)) SessionEvents.transition(SessionPhase.IDLE, "session.stopped", mapOf("status" to status))
} else { } else {
@@ -1745,22 +1647,19 @@ class SessionService : Service() {
completeNativeSleep() completeNativeSleep()
val (ended, endedArch) = synchronized(stopLock) { val (ended, endedArch) = synchronized(stopLock) {
if (!SessionState.running) return if (!SessionState.running) return
SessionEvents.record("guest.exited", mapOf("status" to status))
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
SessionState.running = false SessionState.running = false
SessionPaths.take() to SessionState.steamClientArch SessionPaths.take() to SessionState.steamClientArch
} }
SessionState.micAvailable = false
SessionState.micEnabled = false
xrActivityVisible = false xrActivityVisible = false
updateDownloadMonitoring() updateDownloadMonitoring()
val stoppedGen = sessionGen val stoppedGen = sessionGen
val stoppedSession = SessionState.sessionId val stoppedSession = SessionState.sessionId
val launcherEnded = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || SessionState.program == NoSteamLaunch.EPIC || val launcherEnded = SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP || SessionState.program == NoSteamLaunch.EPIC
SessionState.program == NoSteamLaunch.BATTLENET
SessionState.stopRequested = false SessionState.stopRequested = false
SessionEvents.record("guest.exited", mapOf("status" to status))
GpuClockPin.stop(this) GpuClockPin.stop(this)
GameThreadHints.stop() GameThreadHints.stop()
SessionEvents.transition(SessionPhase.STOPPING, "session.stopping", mapOf("status" to status))
suspendOperationPending = false suspendOperationPending = false
freezePending = false freezePending = false
launchWatcher?.stopWatching() launchWatcher?.stopWatching()
@@ -1817,9 +1716,6 @@ class SessionService : Service() {
private fun importLauncherGames() { private fun importLauncherGames() {
runCatching { com.droiddeck.launcher.stores.epic.EpicClientLibrary.importClientGames(this) } runCatching { com.droiddeck.launcher.stores.epic.EpicClientLibrary.importClientGames(this) }
.onFailure { Log.w(TAG, "client library scan failed: ${it.javaClass.simpleName}") } .onFailure { Log.w(TAG, "client library scan failed: ${it.javaClass.simpleName}") }
runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetClient.syncAccount(this) }
.onFailure { Log.w(TAG, "Battle.net sign-in check failed: ${it.javaClass.simpleName}") }
com.droiddeck.launcher.stores.StoresState.notifyLibraryChanged(this)
} }
override fun onTaskRemoved(rootIntent: Intent?) { override fun onTaskRemoved(rootIntent: Intent?) {
@@ -1932,7 +1828,8 @@ class SessionService : Service() {
.setContentText(getString( .setContentText(getString(
when { when {
SessionState.suspended -> R.string.session_notification_paused SessionState.suspended -> R.string.session_notification_paused
downloadsKeepAwake() -> R.string.session_notification_downloads downloadActive && steamDownloadsInBackground &&
suspendPolicy != SessionPrefs.SUSPEND_NEVER -> R.string.session_notification_downloads
else -> R.string.session_notification else -> R.string.session_notification
} }
)) ))
@@ -1940,7 +1837,8 @@ class SessionService : Service() {
.apply { .apply {
if (SessionState.suspended) { if (SessionState.suspended) {
addAction(Notification.Action.Builder(null, getString(R.string.resume_session), resume).build()) addAction(Notification.Action.Builder(null, getString(R.string.resume_session), resume).build())
} else if (downloadsKeepAwake()) { } else if (downloadActive && steamDownloadsInBackground &&
suspendPolicy != SessionPrefs.SUSPEND_NEVER) {
val suspend = PendingIntent.getService( val suspend = PendingIntent.getService(
this@SessionService, 3, this@SessionService, 3,
Intent(this@SessionService, SessionService::class.java).setAction(ACTION_SUSPEND_NOW), Intent(this@SessionService, SessionService::class.java).setAction(ACTION_SUSPEND_NOW),
@@ -1960,50 +1858,33 @@ class SessionService : Service() {
getSystemService(NotificationManager::class.java)?.notify(NOTIFICATION_ID, buildNotification()) getSystemService(NotificationManager::class.java)?.notify(NOTIFICATION_ID, buildNotification())
} }
private fun downloadsKeepAwake(): Boolean =
downloadActive && (steamDownloadsInBackground || clientInstallActive) &&
SessionState.mode == MODE_STEAM && suspendPolicy != SessionPrefs.SUSPEND_NEVER
private fun downloadWatchWanted(): Boolean =
SessionState.running && SessionState.mode == MODE_STEAM && suspendPolicy != SessionPrefs.SUSPEND_NEVER &&
(steamDownloadsInBackground || !SessionState.firstFrameSeen)
private fun updateDownloadMonitoring() { private fun updateDownloadMonitoring() {
if (!downloadWatchWanted()) { val enabled = SessionState.running && SessionState.mode == MODE_STEAM &&
steamDownloadsInBackground && suspendPolicy != SessionPrefs.SUSPEND_NEVER
if (!enabled) {
val wasActive = downloadActive val wasActive = downloadActive
downloadMonitorTask?.let(mainHandler::removeCallbacks) downloadMonitorTask?.let(mainHandler::removeCallbacks)
downloadMonitorTask = null downloadMonitorTask = null
steamDownloadMonitor.reset() steamDownloadMonitor.reset()
downloadActive = false downloadActive = false
if (clientInstallActive) SessionEvents.record("steam.client_download", mapOf("active" to false))
clientInstallActive = false
if (wasActive) refreshNotification() if (wasActive) refreshNotification()
return return
} }
if (downloadMonitorTask != null) return if (downloadMonitorTask != null) return
val poll = object : Runnable { val poll = object : Runnable {
override fun run() { override fun run() {
if (downloadMonitorTask !== this) return if (downloadMonitorTask !== this || !SessionState.running ||
if (!downloadWatchWanted()) { SessionState.mode != MODE_STEAM || !steamDownloadsInBackground ||
downloadMonitorTask = null suspendPolicy == SessionPrefs.SUSPEND_NEVER) {
updateDownloadMonitoring()
updateSuspendPolicy()
return return
} }
val root = LinuxRuntime.rootDir(this@SessionService)
val wasActive = downloadActive val wasActive = downloadActive
val wasInstalling = clientInstallActive downloadActive = steamDownloadMonitor.poll(
clientInstallActive = !SessionState.firstFrameSeen && LinuxRuntime.rootDir(this@SessionService),
(clientInstallActive || SteamDownloadMonitor.clientInstallPending(root))
downloadActive = clientInstallActive || steamDownloadsInBackground && steamDownloadMonitor.poll(
root,
receivedBytes = TrafficStats.getUidRxBytes(android.os.Process.myUid()), receivedBytes = TrafficStats.getUidRxBytes(android.os.Process.myUid()),
client = SessionState.steamClientArch, client = SessionState.steamClientArch,
mounts = steamLibraryMounts, mounts = steamLibraryMounts,
) )
if (wasInstalling != clientInstallActive) {
SessionEvents.record("steam.client_download", mapOf("active" to clientInstallActive))
}
if (wasActive != downloadActive) refreshNotification() if (wasActive != downloadActive) refreshNotification()
updateSuspendPolicy() updateSuspendPolicy()
mainHandler.postDelayed(this, DOWNLOAD_POLL_MS) mainHandler.postDelayed(this, DOWNLOAD_POLL_MS)
@@ -2048,7 +1929,6 @@ class SessionService : Service() {
const val ACTION_LAUNCH_GAME = "com.droiddeck.launcher.LAUNCH_STEAM_GAME" const val ACTION_LAUNCH_GAME = "com.droiddeck.launcher.LAUNCH_STEAM_GAME"
const val ACTION_HOME_GUIDE = "com.droiddeck.launcher.HOME_GUIDE" const val ACTION_HOME_GUIDE = "com.droiddeck.launcher.HOME_GUIDE"
const val ACTION_AGENT_START = "com.droiddeck.launcher.AGENT_START" const val ACTION_AGENT_START = "com.droiddeck.launcher.AGENT_START"
private const val ACTION_MIC_CHANGED = "com.droiddeck.launcher.MIC_CHANGED"
private const val ACTION_SUSPEND_POLICY_CHANGED = "com.droiddeck.launcher.SUSPEND_POLICY_CHANGED" private const val ACTION_SUSPEND_POLICY_CHANGED = "com.droiddeck.launcher.SUSPEND_POLICY_CHANGED"
private const val ACTION_ACTIVITY_VISIBLE = "com.droiddeck.launcher.ACTIVITY_VISIBLE" private const val ACTION_ACTIVITY_VISIBLE = "com.droiddeck.launcher.ACTIVITY_VISIBLE"
private const val ACTION_ACTIVITY_HIDDEN = "com.droiddeck.launcher.ACTIVITY_HIDDEN" private const val ACTION_ACTIVITY_HIDDEN = "com.droiddeck.launcher.ACTIVITY_HIDDEN"
@@ -2067,7 +1947,6 @@ class SessionService : Service() {
private val STRAGGLERS = listOf("droiddeck-session", "gamescope", "Xwayland", "steamrtarm64", private val STRAGGLERS = listOf("droiddeck-session", "gamescope", "Xwayland", "steamrtarm64",
"steamwebhelper", "linuxfs/opt/android-host/proot", "/libproot.so", "pulseaudio/libpulseaudio.so") "steamwebhelper", "linuxfs/opt/android-host/proot", "/libproot.so", "pulseaudio/libpulseaudio.so")
private const val GRACE_MS = 1200L private const val GRACE_MS = 1200L
private const val WINE_SAVE_MS = 3000L
private const val STEAM_PICKUP_MS = 1500L private const val STEAM_PICKUP_MS = 1500L
private const val STEAM_EXIT_MS = 10_000L private const val STEAM_EXIT_MS = 10_000L
private const val GAME_LAUNCH_RETRY_MS = 250L private const val GAME_LAUNCH_RETRY_MS = 250L
@@ -2089,7 +1968,6 @@ class SessionService : Service() {
const val MODE_STEAM = "steam" const val MODE_STEAM = "steam"
const val MODE_DESKTOP = "lxqt" const val MODE_DESKTOP = "lxqt"
const val MODE_RUN = "run" const val MODE_RUN = "run"
const val FAILURE_RUNTIME_DRIVER = "RUNTIME_DRIVER_UNAVAILABLE"
const val EXTRA_PROGRAM = "program" const val EXTRA_PROGRAM = "program"
private const val RUN_STATUS = "run-status" private const val RUN_STATUS = "run-status"
const val EXTRA_PROGRAM_ARGS = "programArgs" const val EXTRA_PROGRAM_ARGS = "programArgs"
@@ -2100,7 +1978,6 @@ class SessionService : Service() {
fun start( fun start(
context: Context, mode: String = MODE_STEAM, program: String? = null, context: Context, mode: String = MODE_STEAM, program: String? = null,
steamUi: String? = null, steamUrl: String? = null, programArgs: Array<String>? = null, steamUi: String? = null, steamUrl: String? = null, programArgs: Array<String>? = null,
gameId: String? = null,
displayId: Int = Display.DEFAULT_DISPLAY, displayId: Int = Display.DEFAULT_DISPLAY,
) { ) {
SessionState.activityDisplayId = displayId SessionState.activityDisplayId = displayId
@@ -2111,7 +1988,6 @@ class SessionService : Service() {
if (programArgs != null) intent.putExtra(EXTRA_PROGRAM_ARGS, programArgs) if (programArgs != null) intent.putExtra(EXTRA_PROGRAM_ARGS, programArgs)
if (steamUi != null) intent.putExtra(EXTRA_STEAM_UI, steamUi) if (steamUi != null) intent.putExtra(EXTRA_STEAM_UI, steamUi)
if (steamUrl != null) intent.putExtra(EXTRA_STEAM_URL, steamUrl) if (steamUrl != null) intent.putExtra(EXTRA_STEAM_URL, steamUrl)
if (gameId != null) intent.putExtra(EXTRA_GAME_ID, gameId)
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent)
else context.startService(intent) else context.startService(intent)
} }
@@ -2183,11 +2059,6 @@ class SessionService : Service() {
}.getOrDefault(false) }.getOrDefault(false)
} }
fun setMicEnabled(context: Context, enabled: Boolean) {
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_MIC_CHANGED)
.putExtra("enabled", enabled))
}
fun suspendPolicyChanged(context: Context) { fun suspendPolicyChanged(context: Context) {
if (!SessionState.running) return if (!SessionState.running) return
context.startService(Intent(context, SessionService::class.java).setAction(ACTION_SUSPEND_POLICY_CHANGED)) context.startService(Intent(context, SessionService::class.java).setAction(ACTION_SUSPEND_POLICY_CHANGED))
@@ -46,8 +46,6 @@ object SessionState {
var activityDisplayId = 0 var activityDisplayId = 0
@Volatile @Volatile
var runtimeDriver: String? = null var runtimeDriver: String? = null
var micAvailable by mutableStateOf(false)
var micEnabled by mutableStateOf(false)
var suspended by mutableStateOf(false) var suspended by mutableStateOf(false)
var resumeRequested by mutableStateOf(false) var resumeRequested by mutableStateOf(false)
var resuming by mutableStateOf(false) var resuming by mutableStateOf(false)
@@ -59,8 +57,6 @@ object SessionState {
@Volatile @Volatile
var programArgs: List<String> = emptyList() var programArgs: List<String> = emptyList()
@Volatile @Volatile
var gameId: String? = null
@Volatile
var steamUi: String? = null var steamUi: String? = null
@Volatile @Volatile
var steamUrl: String? = null var steamUrl: String? = null
@@ -106,9 +102,6 @@ object SessionState {
@Volatile @Volatile
var fpsLimit: Int = 0 var fpsLimit: Int = 0
@Volatile
var performanceMode = false
@Volatile @Volatile
var firstFrameSeen = false var firstFrameSeen = false
@@ -18,7 +18,7 @@ object SettingsReset {
"gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController", "gamepadLeft", "gamepadRight", "pipAutoEnter", "unfoldedControls", "unfoldedControlsWithController",
"stretch16x9", "picturePosition", "stretch16x9", "picturePosition",
"gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop", "gpuDriverMode", "androidDriver", "linuxDriver", "linuxDriver.steam", "linuxDriver.desktop",
"tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime", "ramCapMb", "vramCapMb", "zramClient", "tuSysmem", "glThread", "noGlError", "zinkLazy", "mangoapp", "gpuClockPin", "gamescopeRealtime",
"directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus", "directAudio", "mic", "wifiDiscovery", "clientCpusOverride", "clientCpus", "gameCpus",
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "cursorComposite", "noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "cursorComposite",
"guestHostname", "fexPreset", "forceSsbs", "logs", "storageDiagnostics", "guestHostname", "fexPreset", "forceSsbs", "logs", "storageDiagnostics",
@@ -29,7 +29,7 @@ object SettingsReset {
) )
internal val SESSION_PREFIXES = listOf( internal val SESSION_PREFIXES = listOf(
"resolutionCap.", "displayResolution.", "customRes.", "hdr.", "fpsLimit.", "performanceMode.", "suspendPolicy.", "resolutionCap.", "displayResolution.", "customRes.", "hdr.", "fpsLimit.", "suspendPolicy.",
) )
private val STEAM_TOUCH_KEYS = listOf("feedback", "autoFade", "gyro", "shake") private val STEAM_TOUCH_KEYS = listOf("feedback", "autoFade", "gyro", "shake")
@@ -1,7 +1,7 @@
package com.droiddeck.launcher.session package com.droiddeck.launcher.session
import java.io.File import java.io.File
import java.io.FileInputStream import java.io.RandomAccessFile
internal class SteamDownloadMonitor { internal class SteamDownloadMonitor {
private data class ManifestState( private data class ManifestState(
@@ -63,17 +63,16 @@ internal class SteamDownloadMonitor {
lastContentActivityAt = 0L lastContentActivityAt = 0L
} }
runCatching { runCatching {
FileInputStream(log).use { input -> RandomAccessFile(log, "r").use { input ->
input.channel.position(contentLogOffset) input.seek(contentLogOffset)
val reader = input.bufferedReader(Charsets.ISO_8859_1)
while (true) { while (true) {
val line = reader.readLine() ?: break val line = input.readLine() ?: break
when { when {
"Client version:" in line -> { "Client version:" in line -> {
activeContentUpdates.clear() activeContentUpdates.clear()
lastContentActivityAt = 0L lastContentActivityAt = 0L
} }
" update changed : " in line && CONTENT_UPDATE.find(line)?.let { match -> CONTENT_UPDATE.find(line)?.let { match ->
val appId = match.groupValues[1] val appId = match.groupValues[1]
val updateType = match.groupValues[2] val updateType = match.groupValues[2]
val state = match.groupValues[3] val state = match.groupValues[3]
@@ -86,15 +85,14 @@ internal class SteamDownloadMonitor {
} }
true true
} == true -> Unit } == true -> Unit
"Current download rate: " in line && CURRENT_RATE.find(line)?.groupValues?.get(1)?.toDoubleOrNull()?.let { it > 0.0 } == true ->
CURRENT_RATE.find(line)?.groupValues?.get(1)?.toDoubleOrNull()?.let { it > 0.0 } == true ->
lastContentActivityAt = now lastContentActivityAt = now
"Downloading " in line && " chunks for depot " in line -> "Downloading " in line && " chunks for depot " in line ->
lastContentActivityAt = now lastContentActivityAt = now
} }
if (activeContentUpdates.isNotEmpty()) lastContentActivityAt = now if (activeContentUpdates.isNotEmpty()) lastContentActivityAt = now
} }
contentLogOffset = input.channel.position() contentLogOffset = input.filePointer
} }
} }
return activeContentUpdates.isNotEmpty() && lastContentActivityAt > 0L && return activeContentUpdates.isNotEmpty() && lastContentActivityAt > 0L &&
@@ -140,21 +138,13 @@ internal class SteamDownloadMonitor {
private fun value(text: String, key: String): String? = private fun value(text: String, key: String): String? =
Regex("\"$key\"\\s+\"([^\"]*)\"").find(text)?.groupValues?.get(1) Regex("\"$key\"\\s+\"([^\"]*)\"").find(text)?.groupValues?.get(1)
companion object { private companion object {
fun clientInstallPending(runtimeRoot: File): Boolean { const val MANIFEST_PROGRESS_GRACE_MS = 8_000L
val home = File(runtimeRoot, "root") const val CONTENT_ACTIVITY_GRACE_MS = 90_000L
val steam = File(home, ".local/share/Steam") const val MIN_RECEIVE_BYTES_PER_SEC = 64L * 1024L
val stamped = File(steam, "package/droiddeck-installed").isFile || val PATH = Regex("\"path\"\\s+\"([^\"]+)\"")
File(steam, "package/bannerlator-installed").isFile val STEAM_HOMES = listOf("root/.local/share/Steam", "root/.droiddeck-x64/.local/share/Steam")
return !(stamped && File(steam, "steamrtarm64/steam").isFile) || File(home, ".bl-steam-repair").exists() val CONTENT_UPDATE = Regex("""AppID (\d+) (App|Workshop|Shader) update changed : (.*)""")
} val CURRENT_RATE = Regex("""Current download rate: ([\d.]+) Mbps""")
private const val MANIFEST_PROGRESS_GRACE_MS = 8_000L
private const val CONTENT_ACTIVITY_GRACE_MS = 90_000L
private const val MIN_RECEIVE_BYTES_PER_SEC = 64L * 1024L
private val PATH = Regex("\"path\"\\s+\"([^\"]+)\"")
private val STEAM_HOMES = listOf("root/.local/share/Steam", "root/.droiddeck-x64/.local/share/Steam")
private val CONTENT_UPDATE = Regex("""AppID (\d+) (App|Workshop|Shader) update changed : (.*)""")
private val CURRENT_RATE = Regex("""Current download rate: ([\d.]+) Mbps""")
} }
} }
@@ -101,28 +101,10 @@ object WinComponents {
fun cached(context: Context): List<Component>? = fun cached(context: Context): List<Component>? =
runCatching { parse(File(context.filesDir, CATALOG_CACHE).readText()) }.getOrNull() runCatching { parse(File(context.filesDir, CATALOG_CACHE).readText()) }.getOrNull()
const val VCREDIST_ARM64 = "vcredist2022_arm64"
/**
* The ARM64 Visual C++ 2015-2022 runtime as registry values only (the version a 14.44.35211 installer writes, in both
* registry views). Xbox games' launchers running as ARM64EC check for it; Wine's own CRT does the work. Same approach as
* MGamer404's Bannerlator #627. Used until the catalog carries a component of this name.
*/
internal fun builtInArm64Runtime(): Component {
fun value(view: String, name: String, type: String, data: String) = Step("set_register_key", JSONObject()
.put("action", "set_register_key").put("key", "HKLM\\Software\\${view}Microsoft\\VisualStudio\\14.0\\VC\\Runtimes\\arm64")
.put("value", name).put("type", type).put("data", data))
val steps = listOf("", "Wow6432Node\\").flatMap { view ->
listOf(value(view, "Installed", "REG_DWORD", "1"), value(view, "Major", "REG_DWORD", "14"), value(view, "Minor", "REG_DWORD", "44"),
value(view, "Bld", "REG_DWORD", "35211"), value(view, "Rbld", "REG_DWORD", "0"), value(view, "Version", "REG_SZ", "v14.44.35211.00"))
}
return Component(VCREDIST_ARM64, "Microsoft Visual C++ 2015-2022 ARM64 runtime 14.44.35211 (registry entries only)", "Microsoft", "ready", emptyList(), steps)
}
private fun parse(body: String): List<Component>? { private fun parse(body: String): List<Component>? {
return try { return try {
val arr = JSONObject(body).getJSONArray("components") val arr = JSONObject(body).getJSONArray("components")
val listed = (0 until arr.length()).mapNotNull { i -> (0 until arr.length()).mapNotNull { i ->
val o = arr.getJSONObject(i) val o = arr.getJSONObject(i)
val name = o.optString("name") val name = o.optString("name")
if (!validId(name)) return@mapNotNull null if (!validId(name)) return@mapNotNull null
@@ -135,7 +117,6 @@ object WinComponents {
o.optString("snapshot"), o.optString("snapshot"),
) )
} }
if (listed.any { it.name == VCREDIST_ARM64 }) listed else listed + builtInArm64Runtime()
} catch (e: Exception) { } catch (e: Exception) {
Log.w(TAG, "catalog: $e"); null Log.w(TAG, "catalog: $e"); null
} }
@@ -1,13 +0,0 @@
package com.droiddeck.launcher.session
internal object WineProcesses {
private const val WINESERVER = "wineserver"
fun isWineserver(cmdline: ByteArray?, comm: String?): Boolean {
val program = cmdline?.let { bytes ->
val end = bytes.indexOf(0.toByte()).let { if (it < 0) bytes.size else it }
String(bytes, 0, end, Charsets.UTF_8).substringAfterLast('/')
}
return program == WINESERVER || comm?.trim() == WINESERVER
}
}
@@ -3,28 +3,8 @@ package com.droiddeck.launcher.stores
import java.io.File import java.io.File
object CloudSavePaths { object CloudSavePaths {
const val GOG_DEFAULT_NAMESPACE = "__default"
fun profile(prefix: File): File = File(prefix, "drive_c/users/steamuser") fun profile(prefix: File): File = File(prefix, "drive_c/users/steamuser")
fun gogGalaxySdkTemplate(clientId: String) =
"%LocalAppData%/GOG.com/Galaxy/Applications/$clientId/Storage/Shared/Files"
class GogCloudLocation(val name: String, val template: String)
/**
* cloudStorage.enabled with an empty locations list is Galaxy SDK IStorage, whose objects the
* API names under a location called `__default`.
*/
fun gogSaveFromRemote(enabled: Boolean, locations: List<Pair<String, String>>, clientId: String): GogCloudLocation? {
if (!enabled) return null
val named = locations.filter { it.second.isNotEmpty() }
val pick = named.firstOrNull { it.first.equals("saves", true) } ?: named.firstOrNull()
if (pick != null) return GogCloudLocation(pick.first, pick.second)
if (clientId.isEmpty()) return null
return GogCloudLocation(GOG_DEFAULT_NAMESPACE, gogGalaxySdkTemplate(clientId))
}
fun gog(template: String, prefix: File, install: File): File? { fun gog(template: String, prefix: File, install: File): File? {
val norm = template.replace('\\', '/').trim().trimStart('/') val norm = template.replace('\\', '/').trim().trimStart('/')
val match = Regex("^(<\\?[^?>]+\\?>|%[^%]+%)").find(norm) ?: return null val match = Regex("^(<\\?[^?>]+\\?>|%[^%]+%)").find(norm) ?: return null
@@ -1,7 +1,6 @@
package com.droiddeck.launcher.stores package com.droiddeck.launcher.stores
import android.content.Context import android.content.Context
import android.content.SharedPreferences
import android.util.Log import android.util.Log
import com.droiddeck.launcher.frontend.AddedGames import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.frontend.Library import com.droiddeck.launcher.frontend.Library
@@ -23,7 +22,6 @@ object CloudSaves {
private const val TAG = "CloudSaves" private const val TAG = "CloudSaves"
private const val BACKUPS = 3 private const val BACKUPS = 3
private const val PARALLEL = 6 private const val PARALLEL = 6
private const val CLOUD_LAYOUT = 2
class Result(val result: String, val files: Int, val bytes: Long, val reason: String, val conflicts: Int = 0) { class Result(val result: String, val files: Int, val bytes: Long, val reason: String, val conflicts: Int = 0) {
val ok: Boolean get() = result != "failed" val ok: Boolean get() = result != "failed"
@@ -49,54 +47,20 @@ object CloudSaves {
private fun markSynced(context: Context, store: Store, id: String) = prefs(context, store).edit().putLong("cloud_sync_$id", System.currentTimeMillis()).apply() private fun markSynced(context: Context, store: Store, id: String) = prefs(context, store).edit().putLong("cloud_sync_$id", System.currentTimeMillis()).apply()
private const val TEMPLATE_NONE = "none"
internal const val TEMPLATE_NONE_TTL_MS = 24 * 60 * 60 * 1000L
internal fun noneTemplateIsCurrent(storedAtMs: Long, nowMs: Long) =
storedAtMs > 0L && nowMs - storedAtMs < TEMPLATE_NONE_TTL_MS
private fun rememberNoCloud(p: SharedPreferences, id: String) {
p.edit().putString("cloud_template_$id", TEMPLATE_NONE)
.putLong("cloud_template_at_$id", System.currentTimeMillis()).apply()
}
fun template(context: Context, store: Store, id: String, folder: File, sidecar: StoreGameSidecar): String? { fun template(context: Context, store: Store, id: String, folder: File, sidecar: StoreGameSidecar): String? {
val p = prefs(context, store) val p = prefs(context, store)
var retryNone = false if (p.contains("cloud_template_$id")) return p.getString("cloud_template_$id", "")
if (p.contains("cloud_template_$id")) {
val cached = p.getString("cloud_template_$id", "") ?: ""
if (cached == TEMPLATE_NONE) {
if (noneTemplateIsCurrent(p.getLong("cloud_template_at_$id", 0L), System.currentTimeMillis())) return ""
retryNone = true
} else if (cached.isNotEmpty()) return cached
}
var gogLocation = ""
val fetched = when (store) { val fetched = when (store) {
Store.GOG -> { Store.GOG -> gogTemplate(context, id, folder)
val config = gogConfig(context, id, folder)
if (config == null) {
if (retryNone) { rememberNoCloud(p, id); return "" }
return null
}
gogLocation = config.name
config.location
}
Store.EPIC -> { Store.EPIC -> {
val token = EpicCredentialStore.getValidAccessToken(context) ?: return null val token = EpicCredentialStore.getValidAccessToken(context) ?: return null
val ns = sidecar.extra["namespace"].orEmpty() val ns = sidecar.extra["namespace"].orEmpty()
val item = sidecar.extra["catalogItemId"].orEmpty() val item = sidecar.extra["catalogItemId"].orEmpty()
if (ns.isEmpty() || item.isEmpty()) "" else EpicApiClient.getCustomAttribute(token, ns, item, "CloudSaveFolder") if (ns.isEmpty() || item.isEmpty()) "" else EpicApiClient.getCustomAttribute(token, ns, item, "CloudSaveFolder")
} }
Store.AMAZON, Store.ITCH, Store.XBOX, Store.BATTLENET -> "" Store.AMAZON, Store.ITCH, Store.XBOX -> ""
} ?: return null } ?: return null
p.edit() p.edit().putString("cloud_template_$id", fetched).apply()
.putString("cloud_template_$id", fetched.ifEmpty { TEMPLATE_NONE })
.apply {
if (fetched.isEmpty()) putLong("cloud_template_at_$id", System.currentTimeMillis())
else remove("cloud_template_at_$id")
if (store == Store.GOG && gogLocation.isNotEmpty()) putString("cloud_location_$id", gogLocation)
}
.apply()
Log.i(TAG, "cloud ${store.id} $id template ${if (fetched.isEmpty()) "none" else "found"}") Log.i(TAG, "cloud ${store.id} $id template ${if (fetched.isEmpty()) "none" else "found"}")
return fetched return fetched
} }
@@ -105,10 +69,8 @@ object CloudSaves {
GogPrefs.get(context).getString("client_id_$id", null)?.ifEmpty { null } GogPrefs.get(context).getString("client_id_$id", null)?.ifEmpty { null }
?: runCatching { JSONObject(File(folder, "goggame-$id.info").readText()).optString("clientId").ifEmpty { null } }.getOrNull() ?: runCatching { JSONObject(File(folder, "goggame-$id.info").readText()).optString("clientId").ifEmpty { null } }.getOrNull()
private class GogConfig(val name: String, val location: String) private fun gogTemplate(context: Context, id: String, folder: File): String? {
val clientId = gogClientId(context, id, folder) ?: return ""
private fun gogConfig(context: Context, id: String, folder: File): GogConfig? {
val clientId = gogClientId(context, id, folder) ?: return GogConfig("", "")
return try { return try {
val c = URL("https://remote-config.gog.com/components/galaxy_client/clients/$clientId?component_version=2.0.45").openConnection() as HttpURLConnection val c = URL("https://remote-config.gog.com/components/galaxy_client/clients/$clientId?component_version=2.0.45").openConnection() as HttpURLConnection
c.connectTimeout = 15_000; c.readTimeout = 15_000 c.connectTimeout = 15_000; c.readTimeout = 15_000
@@ -116,34 +78,16 @@ object CloudSaves {
if (c.responseCode !in 200..299) { c.disconnect(); return null } if (c.responseCode !in 200..299) { c.disconnect(); return null }
val cloud = JSONObject(c.inputStream.bufferedReader().readText()).optJSONObject("content")?.optJSONObject("Windows")?.optJSONObject("cloudStorage") val cloud = JSONObject(c.inputStream.bufferedReader().readText()).optJSONObject("content")?.optJSONObject("Windows")?.optJSONObject("cloudStorage")
c.disconnect() c.disconnect()
val locations = cloud?.optJSONArray("locations") if (cloud?.optBoolean("enabled", false) != true) return ""
val picked = CloudSavePaths.gogSaveFromRemote( val locations = cloud.optJSONArray("locations") ?: return ""
enabled = cloud?.optBoolean("enabled", false) == true, val all = (0 until locations.length()).mapNotNull { locations.optJSONObject(it) }
locations = (0 until (locations?.length() ?: 0)).mapNotNull { i -> (all.firstOrNull { it.optString("name").equals("saves", true) } ?: all.firstOrNull())?.optString("location").orEmpty()
locations!!.optJSONObject(i)?.let { it.optString("name") to it.optString("location") }
},
clientId = clientId,
)
if (picked == null) GogConfig("", "") else GogConfig(picked.name, picked.template)
} catch (e: Exception) { } catch (e: Exception) {
Log.w(TAG, "gog remote-config: ${e.javaClass.simpleName}") Log.w(TAG, "gog remote-config: ${e.javaClass.simpleName}")
null null
} }
} }
/**
* The selected cloud location's name: GOG prefixes every cloud file with it, and the local folder
* is the location itself. Older builds had no name cached; fetch it once for those.
*/
private fun gogLocationName(context: Context, id: String, folder: File): String? {
val p = GogPrefs.get(context)
p.getString("cloud_location_$id", null)?.ifEmpty { null }?.let { return it }
if (p.getString("cloud_template_$id", null)?.let { it.isEmpty() || it == TEMPLATE_NONE } == true) return null
val config = gogConfig(context, id, folder) ?: return null
if (config.name.isNotEmpty()) p.edit().putString("cloud_location_$id", config.name).apply()
return config.name.ifEmpty { null }
}
private fun saveFolder(context: Context, store: Store, id: String): Pair<File?, String> { private fun saveFolder(context: Context, store: Store, id: String): Pair<File?, String> {
val (folder, sidecar) = game(context, store, id) ?: return null to "not-installed" 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" val template = template(context, store, id, folder, sidecar) ?: return null to "store-unreachable"
@@ -152,7 +96,7 @@ object CloudSaves {
val dir = when (store) { val dir = when (store) {
Store.GOG -> CloudSavePaths.gog(template, pfx, folder) Store.GOG -> CloudSavePaths.gog(template, pfx, folder)
Store.EPIC -> CloudSavePaths.epic(template, pfx, folder, EpicCredentialStore.load(context)?.accountId.orEmpty(), id) Store.EPIC -> CloudSavePaths.epic(template, pfx, folder, EpicCredentialStore.load(context)?.accountId.orEmpty(), id)
Store.AMAZON, Store.ITCH, Store.XBOX, Store.BATTLENET -> null Store.AMAZON, Store.ITCH, Store.XBOX -> null
} }
return dir to (if (dir == null) "unresolved" else "ok") return dir to (if (dir == null) "unresolved" else "ok")
} }
@@ -170,14 +114,14 @@ object CloudSaves {
val galaxy = GogAuth.validToken(context) val galaxy = GogAuth.validToken(context)
val clientId = gogClientId(context, id, folder) val clientId = gogClientId(context, id, folder)
if (userId.isEmpty() || galaxy == null || clientId == null) null if (userId.isEmpty() || galaxy == null || clientId == null) null
else GogCloud(userId, clientId, gogScopedToken(context, id, clientId) ?: galaxy, gogLocationName(context, id, folder)) else GogCloud(userId, clientId, gogScopedToken(context, id, clientId) ?: galaxy)
} }
Store.EPIC -> { Store.EPIC -> {
val token = EpicCredentialStore.getValidAccessToken(context) val token = EpicCredentialStore.getValidAccessToken(context)
val account = EpicCredentialStore.load(context)?.accountId.orEmpty() val account = EpicCredentialStore.load(context)?.accountId.orEmpty()
if (token == null || account.isEmpty()) null else EpicCloud(account, id, token) if (token == null || account.isEmpty()) null else EpicCloud(account, id, token)
} }
Store.AMAZON, Store.ITCH, Store.XBOX, Store.BATTLENET -> null Store.AMAZON, Store.ITCH, Store.XBOX -> null
} }
private fun gogScopedToken(context: Context, id: String, clientId: String): String? { private fun gogScopedToken(context: Context, id: String, clientId: String): String? {
@@ -192,83 +136,6 @@ object CloudSaves {
private fun saveBaseline(context: Context, store: Store, id: String, b: Map<String, CloudPlan.Entry>) = private fun saveBaseline(context: Context, store: Store, id: String, b: Map<String, CloudPlan.Entry>) =
prefs(context, store).edit().putString("cloud_baseline_$id", CloudPlan.toJson(b)).apply() prefs(context, store).edit().putString("cloud_baseline_$id", CloudPlan.toJson(b)).apply()
internal class Migration(val baseline: Map<String, CloudPlan.Entry>, val moved: Int, val cleaned: Int, val failed: Int)
/**
* Moves only files whose `"<location>/<path>"` key proves the old mapping wrote them; anything
* the game itself created under that name is left where it is. Identical duplicates are removed
* only when they prove the same. The name must be one path segment: it comes from remote config.
*/
internal fun migrateNested(dir: File, name: String, base: Map<String, CloudPlan.Entry>): Migration? {
if (name.isEmpty() || name == "." || name == ".." || name.contains('/') || name.contains('\\')) return null
val nested = File(dir, name)
if (!nested.isDirectory) return null
val root = runCatching { dir.canonicalFile }.getOrNull() ?: return null
if (runCatching { nested.canonicalFile }.getOrNull()?.parentFile != root) return null
val prefix = "$name/"
val next = HashMap(base)
var moved = 0
var cleaned = 0
var failed = 0
for (src in nested.walkTopDown().filter { it.isFile }.toList()) {
if (runCatching { java.nio.file.Files.isSymbolicLink(src.toPath()) }.getOrDefault(true)) continue
val srcCanon = runCatching { src.canonicalFile }.getOrNull() ?: continue
if (!srcCanon.path.startsWith(root.path + File.separator)) continue
val rel = src.relativeTo(nested).path.replace(File.separatorChar, '/')
val key = prefix + rel
val entry = base[key] ?: continue
val dest = File(dir, rel)
val destCanon = runCatching { dest.canonicalFile }.getOrNull() ?: continue
if (!destCanon.path.startsWith(root.path + File.separator)) continue
if (dest.isFile && runCatching { md5(dest) == md5(src) }.getOrDefault(false)) {
if (!src.delete()) { failed++; continue }
cleaned++
next[rel] = entry
next.remove(key)
continue
}
if (dest.exists()) continue
val copied = runCatching {
dest.parentFile?.mkdirs()
val tmp = File.createTempFile(dest.name + ".", ".migrate", dest.parentFile)
try {
src.copyTo(tmp, overwrite = true)
if (md5(tmp) != md5(src)) false
else {
java.nio.file.Files.move(tmp.toPath(), dest.toPath(), java.nio.file.StandardCopyOption.ATOMIC_MOVE)
true
}
} finally {
if (tmp.exists()) tmp.delete()
}
}.getOrDefault(false)
if (!copied) { failed++; continue }
if (!src.delete()) { failed++; continue }
moved++
next[rel] = entry
next.remove(key)
}
if (nested.walkTopDown().none { it.isFile }) nested.deleteRecursively()
return Migration(next, moved, cleaned, failed)
}
private fun migrateGogNested(context: Context, id: String, folder: File, dir: File) {
val p = GogPrefs.get(context)
// Run once per game: after this the flat layout is authoritative, even if the game itself
// keeps a folder named like the cloud location.
if (p.getInt("cloud_layout_$id", 0) >= CLOUD_LAYOUT) return
val name = gogLocationName(context, id, folder) ?: return
val base = baseline(context, Store.GOG, id).orEmpty()
val result = migrateNested(dir, name, base)
if (result != null) {
if (result.baseline != base) saveBaseline(context, Store.GOG, id, result.baseline)
if (result.moved + result.cleaned > 0) {
StoresState.logLine("cloud gog $id migrate result=ok moved=${result.moved} cleaned=${result.cleaned} from=$name")
}
}
if (result == null || result.failed == 0) p.edit().putInt("cloud_layout_$id", CLOUD_LAYOUT).apply()
}
fun conflicts(context: Context, store: Store, id: String): List<String> = fun conflicts(context: Context, store: Store, id: String): List<String> =
prefs(context, store).getString("cloud_conflicts_$id", "").orEmpty().split('\n').filter { it.isNotEmpty() } prefs(context, store).getString("cloud_conflicts_$id", "").orEmpty().split('\n').filter { it.isNotEmpty() }
@@ -313,7 +180,6 @@ object CloudSaves {
!g.second.cloud -> Result("skipped", 0, 0, "off") !g.second.cloud -> Result("skipped", 0, 0, "off")
else -> { else -> {
val (dir, reason) = saveFolder(context, store, id) val (dir, reason) = saveFolder(context, store, id)
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 val cloud = if (dir != null) transport(context, store, id, g.first) else null
when { when {
dir == null -> Result("skipped", 0, 0, reason) dir == null -> Result("skipped", 0, 0, reason)
@@ -323,7 +189,7 @@ object CloudSaves {
} }
} }
} catch (e: NoCloudSaves) { } catch (e: NoCloudSaves) {
rememberNoCloud(prefs(context, store), id) prefs(context, store).edit().putString("cloud_template_$id", "").apply()
Result("skipped", 0, 0, "no-cloud-saves") Result("skipped", 0, 0, "no-cloud-saves")
} catch (e: Exception) { } catch (e: Exception) {
Result("failed", 0, 0, e.javaClass.simpleName) Result("failed", 0, 0, e.javaClass.simpleName)
@@ -7,8 +7,6 @@ import java.net.URLEncoder
import java.text.SimpleDateFormat import java.text.SimpleDateFormat
import java.util.Locale import java.util.Locale
import java.util.TimeZone import java.util.TimeZone
import java.util.zip.CRC32
import java.util.zip.Deflater
import org.json.JSONArray import org.json.JSONArray
import org.json.JSONObject import org.json.JSONObject
@@ -40,101 +38,25 @@ private fun httpDate(s: String?): Long = try {
SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US).apply { timeZone = TimeZone.getTimeZone("GMT") }.parse(s!!.trim())?.time ?: -1L SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US).apply { timeZone = TimeZone.getTimeZone("GMT") }.parse(s!!.trim())?.time ?: -1L
} catch (e: Exception) { -1L } } catch (e: Exception) { -1L }
internal fun isGzip(data: ByteArray) =
data.size >= 10 && data[0] == 0x1f.toByte() && data[1] == 0x8b.toByte() && data[2] == 0x08.toByte()
internal fun gunzip(data: ByteArray): ByteArray? = try {
java.util.zip.GZIPInputStream(data.inputStream()).use { it.readBytes() }
} catch (e: Exception) { null }
/** Same gzip GOG uses on PUT: deflate level 6, mtime 0, OS Unix. */
internal fun gzipGogPut(data: ByteArray): ByteArray {
val deflater = Deflater(6, true)
val raw = ByteArrayOutputStream()
try {
deflater.setInput(data)
deflater.finish()
val buf = ByteArray(512)
while (!deflater.finished()) {
val n = deflater.deflate(buf)
if (n > 0) raw.write(buf, 0, n)
}
} finally {
deflater.end()
}
val crc = CRC32().also { it.update(data) }
return ByteArrayOutputStream(18 + raw.size()).apply {
write(byteArrayOf(0x1f, 0x8b.toByte(), 8, 0, 0, 0, 0, 0, 0, 3))
write(raw.toByteArray())
writeIntLe(crc.value.toInt())
writeIntLe(data.size)
}.toByteArray()
}
private fun ByteArrayOutputStream.writeIntLe(v: Int) {
write(v and 0xff)
write(v ushr 8 and 0xff)
write(v ushr 16 and 0xff)
write(v ushr 24 and 0xff)
}
internal fun gogDecodeCloudBody(data: ByteArray, contentEncoding: String?): ByteArray {
val encodings = contentEncoding.orEmpty().split(',').map { it.trim().lowercase() }
if ("gzip" in encodings || "x-gzip" in encodings) {
if (!isGzip(data)) return data
return gunzip(data) ?: throw java.io.IOException("Invalid GOG cloud gzip body")
}
if (!isGzip(data)) return data
val inflated = gunzip(data) ?: return data
return if (gzipGogPut(inflated).contentEquals(data)) inflated else data
}
internal fun isoDate(s: String?): Long { internal fun isoDate(s: String?): Long {
if (s == null) return -1L if (s == null || s.length < 19) return -1L
return runCatching { java.time.OffsetDateTime.parse(s).toInstant().toEpochMilli() } return try {
.recoverCatching { java.time.LocalDateTime.parse(s).toInstant(java.time.ZoneOffset.UTC).toEpochMilli() } java.util.Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply {
.getOrDefault(-1L) clear()
set(s.substring(0, 4).toInt(), s.substring(5, 7).toInt() - 1, s.substring(8, 10).toInt(),
s.substring(11, 13).toInt(), s.substring(14, 16).toInt(), s.substring(17, 19).toInt())
}.timeInMillis
} catch (e: Exception) { -1L }
} }
class NoCloudSaves : Exception("no cloud saves") class NoCloudSaves : Exception("no cloud saves")
/** GOG cloud names are `<location name>/<path under that location>`; the name is not part of the folder. */ class GogCloud(private val userId: String, private val clientId: String, private val token: String) : CloudTransport {
internal fun splitGogName(name: String): Pair<String?, String> {
val slash = name.indexOf('/')
return if (slash <= 0 || slash == name.length - 1) null to name
else name.substring(0, slash) to name.substring(slash + 1)
}
/** Maps cloud names to paths under the selected location's folder; the chosen location name is returned. */
internal fun gogRelativeNames(files: List<CloudFile>, location: String?): Pair<String?, List<CloudFile>> {
val locations = files.mapNotNull { splitGogName(it.name).first }.distinct()
// Only infer a location when every name is prefixed; a mixed listing keeps its old shape.
val allPrefixed = files.isNotEmpty() && files.all { splitGogName(it.name).first != null }
val chosen = when {
location != null && (location in locations || allPrefixed) -> location
location == null && allPrefixed -> locations.singleOrNull()
else -> null
} ?: return null to files
return chosen to files.mapNotNull { file ->
val (dir, rel) = splitGogName(file.name)
if (dir == chosen) CloudFile(rel, file.modifiedMs, file.md5, file.readLink) else null
}
}
class GogCloud(
private val userId: String,
private val clientId: String,
private val token: String,
private val location: String? = null,
) : CloudTransport {
private val base = "https://cloudstorage.gog.com/v1/$userId/$clientId" private val base = "https://cloudstorage.gog.com/v1/$userId/$clientId"
private val ua = "GOG Galaxy" private val ua = "GOG Galaxy"
private var prefix: String? = location?.let { "$it/" }
private fun key(name: String) = URLEncoder.encode(name, "UTF-8").replace("+", "%20") private fun key(name: String) = URLEncoder.encode(name, "UTF-8").replace("+", "%20")
private fun cloudKey(name: String) = key((prefix ?: "") + name)
override fun list(): List<CloudFile> { override fun list(): List<CloudFile> {
val c = open(base, "GET", token, ua) val c = open(base, "GET", token, ua)
val code = c.responseCode val code = c.responseCode
@@ -148,38 +70,20 @@ class GogCloud(
val text = c.body().decodeToString().trim() val text = c.body().decodeToString().trim()
c.disconnect() c.disconnect()
if (text.isEmpty() || text == "[]") return emptyList() if (text.isEmpty() || text == "[]") return emptyList()
val raw = if (text.startsWith("[")) { if (text.startsWith("[")) {
val a = JSONArray(text) val a = JSONArray(text)
(0 until a.length()).mapNotNull { a.optJSONObject(it) }.mapNotNull { o -> return (0 until a.length()).mapNotNull { a.optJSONObject(it) }.mapNotNull { o ->
val n = o.optString("name").ifEmpty { return@mapNotNull null } val n = o.optString("name").ifEmpty { return@mapNotNull null }
val lm = o.optLong("last_modified", 0L) val lm = o.optLong("last_modified", 0L)
val iso = isoDate(o.optString("last_modified").takeIf { it.isNotEmpty() }) CloudFile(n, if (lm > 1_000_000_000_000L) lm else if (lm > 0) lm * 1000 else -1L)
CloudFile(n, when {
lm > 1_000_000_000_000L -> lm
lm > 0 -> lm * 1000
iso > 0 -> iso
else -> -1L
})
} }
} else {
text.lines().map { it.trim() }.filter { it.isNotEmpty() }.map { CloudFile(it, -1L) }
} }
return relative(raw) return text.lines().map { it.trim() }.filter { it.isNotEmpty() }.map { CloudFile(it, -1L) }
}
/**
* The API names every file `<location>/<path>`. The location's folder is the sync root, so the
* first segment is dropped. Older builds kept it, writing saves one folder too deep.
*/
private fun relative(raw: List<CloudFile>): List<CloudFile> {
val (chosen, files) = gogRelativeNames(raw, location)
prefix = chosen?.let { "$it/" }
return files
} }
override fun details(file: CloudFile) { override fun details(file: CloudFile) {
if (file.modifiedMs > 0 && file.md5 != null) return if (file.modifiedMs > 0 && file.md5 != null) return
val c = open("$base/${cloudKey(file.name)}", "HEAD", token, ua) val c = open("$base/${key(file.name)}", "HEAD", token, ua)
if (c.responseCode in 200..299) { if (c.responseCode in 200..299) {
httpDate(c.getHeaderField("Last-Modified")).takeIf { it > 0 }?.let { file.modifiedMs = it } httpDate(c.getHeaderField("Last-Modified")).takeIf { it > 0 }?.let { file.modifiedMs = it }
c.getHeaderField("ETag")?.replace("\"", "")?.trim()?.ifEmpty { null }?.let { file.md5 = it } c.getHeaderField("ETag")?.replace("\"", "")?.trim()?.ifEmpty { null }?.let { file.md5 = it }
@@ -188,18 +92,14 @@ class GogCloud(
} }
override fun get(file: CloudFile): Pair<ByteArray, Long> { override fun get(file: CloudFile): Pair<ByteArray, Long> {
val c = open("$base/${cloudKey(file.name)}", "GET", token, ua) val c = open("$base/${key(file.name)}", "GET", token, ua)
c.setRequestProperty("Accept-Encoding", "identity")
if (c.responseCode !in 200..299) { val code = c.responseCode; c.disconnect(); throw java.io.IOException("GOG cloud get HTTP $code") } if (c.responseCode !in 200..299) { val code = c.responseCode; c.disconnect(); throw java.io.IOException("GOG cloud get HTTP $code") }
val modified = httpDate(c.getHeaderField("Last-Modified")) val modified = httpDate(c.getHeaderField("Last-Modified"))
val encoding = c.getHeaderField("Content-Encoding") return c.body().also { c.disconnect() } to modified
val data = c.body()
c.disconnect()
return gogDecodeCloudBody(data, encoding) to modified
} }
override fun put(files: Map<String, ByteArray>): Map<String, Long> = files.mapValues { (name, data) -> override fun put(files: Map<String, ByteArray>): Map<String, Long> = files.mapValues { (name, data) ->
val c = open("$base/${cloudKey(name)}", "PUT", token, ua) val c = open("$base/${key(name)}", "PUT", token, ua)
c.doOutput = true c.doOutput = true
c.setRequestProperty("Content-Type", "application/octet-stream") c.setRequestProperty("Content-Type", "application/octet-stream")
c.setFixedLengthStreamingMode(data.size) c.setFixedLengthStreamingMode(data.size)
@@ -1,5 +1,6 @@
package com.droiddeck.launcher.stores package com.droiddeck.launcher.stores
import android.os.Build
import android.security.keystore.KeyGenParameterSpec import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties import android.security.keystore.KeyProperties
import android.util.Base64 import android.util.Base64
@@ -12,8 +13,6 @@ import javax.crypto.spec.GCMParameterSpec
object CredentialCipher { object CredentialCipher {
const val VERSION = 1 const val VERSION = 1
/** Sealed with the hardware-keystore (TEE) key; [VERSION] envelopes keep opening with the older, possibly StrongBox, key. */
const val VERSION_TEE = 2
const val ALG = "AES/GCM" const val ALG = "AES/GCM"
private const val TRANSFORMATION = "AES/GCM/NoPadding" private const val TRANSFORMATION = "AES/GCM/NoPadding"
private const val TAG_BITS = 128 private const val TAG_BITS = 128
@@ -22,11 +21,6 @@ object CredentialCipher {
fun key(): SecretKey fun key(): SecretKey
fun existing(): SecretKey = key() fun existing(): SecretKey = key()
/** Key for [VERSION] envelopes written before [VERSION_TEE]. */
fun legacy(): SecretKey = existing()
val version: Int get() = VERSION
} }
class KeyMissing : java.security.GeneralSecurityException("no key") class KeyMissing : java.security.GeneralSecurityException("no key")
@@ -35,33 +29,33 @@ object CredentialCipher {
e is android.security.keystore.KeyPermanentlyInvalidatedException || e is android.security.keystore.KeyPermanentlyInvalidatedException ||
e is KeyMissing || e is org.json.JSONException || e is IllegalArgumentException e is KeyMissing || e is org.json.JSONException || e is IllegalArgumentException
// StrongBox took over 10 s per Xbox credential write on a tester's phone, past the backend's
// 10 s reply timeout, so new writes use a TEE key. The old alias stays readable.
object Keystore : KeyProvider { object Keystore : KeyProvider {
private const val LEGACY_ALIAS = "droiddeck-store-credentials" private const val ALIAS = "droiddeck-store-credentials"
private const val ALIAS = "droiddeck-store-credentials-tee"
private const val PROVIDER = "AndroidKeyStore" private const val PROVIDER = "AndroidKeyStore"
override val version: Int get() = VERSION_TEE @Synchronized
override fun existing(): SecretKey {
val ks = KeyStore.getInstance(PROVIDER).apply { load(null) }
return ks.getKey(ALIAS, null) as? SecretKey ?: throw KeyMissing()
}
@Synchronized @Synchronized
override fun existing(): SecretKey = stored(ALIAS) ?: throw KeyMissing() override fun key(): SecretKey {
val ks = KeyStore.getInstance(PROVIDER).apply { load(null) }
(ks.getKey(ALIAS, null) as? SecretKey)?.let { return it }
if (Build.VERSION.SDK_INT >= 28) {
try { return generate(strongBox = true) } catch (e: Exception) { }
}
return generate(strongBox = false)
}
@Synchronized private fun generate(strongBox: Boolean): SecretKey {
override fun legacy(): SecretKey = stored(LEGACY_ALIAS) ?: throw KeyMissing()
@Synchronized
override fun key(): SecretKey = stored(ALIAS) ?: generate()
private fun stored(alias: String): SecretKey? =
KeyStore.getInstance(PROVIDER).apply { load(null) }.getKey(alias, null) as? SecretKey
private fun generate(): SecretKey {
val spec = KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) val spec = KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setKeySize(256) .setKeySize(256)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM) .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setUserAuthenticationRequired(false) .setUserAuthenticationRequired(false)
.apply { if (strongBox && Build.VERSION.SDK_INT >= 28) setIsStrongBoxBacked(true) }
.build() .build()
return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, PROVIDER).run { init(spec); generateKey() } return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, PROVIDER).run { init(spec); generateKey() }
} }
@@ -70,16 +64,15 @@ object CredentialCipher {
fun seal(plain: String, keys: KeyProvider): JSONObject { fun seal(plain: String, keys: KeyProvider): JSONObject {
val cipher = Cipher.getInstance(TRANSFORMATION).apply { init(Cipher.ENCRYPT_MODE, keys.key()) } val cipher = Cipher.getInstance(TRANSFORMATION).apply { init(Cipher.ENCRYPT_MODE, keys.key()) }
val ct = cipher.doFinal(plain.toByteArray(Charsets.UTF_8)) val ct = cipher.doFinal(plain.toByteArray(Charsets.UTF_8))
return JSONObject().put("v", keys.version).put("alg", ALG) return JSONObject().put("v", VERSION).put("alg", ALG)
.put("iv", b64(cipher.iv)).put("ct", b64(ct)) .put("iv", b64(cipher.iv)).put("ct", b64(ct))
} }
fun open(envelope: JSONObject, keys: KeyProvider): String { fun open(envelope: JSONObject, keys: KeyProvider): String {
val version = envelope.optInt("v", -1) require(envelope.optInt("v", -1) == VERSION && envelope.optString("alg") == ALG) { "unknown envelope" }
require((version == VERSION || version == VERSION_TEE) && envelope.optString("alg") == ALG) { "unknown envelope" }
val iv = Base64.decode(envelope.getString("iv"), Base64.NO_WRAP) val iv = Base64.decode(envelope.getString("iv"), Base64.NO_WRAP)
val ct = Base64.decode(envelope.getString("ct"), Base64.NO_WRAP) val ct = Base64.decode(envelope.getString("ct"), Base64.NO_WRAP)
val cipher = Cipher.getInstance(TRANSFORMATION).apply { init(Cipher.DECRYPT_MODE, if (version == VERSION) keys.legacy() else keys.existing(), GCMParameterSpec(TAG_BITS, iv)) } val cipher = Cipher.getInstance(TRANSFORMATION).apply { init(Cipher.DECRYPT_MODE, keys.existing(), GCMParameterSpec(TAG_BITS, iv)) }
return String(cipher.doFinal(ct), Charsets.UTF_8) return String(cipher.doFinal(ct), Charsets.UTF_8)
} }
Loaded 100 of 482 files, more files were not shown because too many files have changed in this diff. Show more