mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 12:35:42 +00:00
Compare commits
73
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d7b36f5a4f | ||
|
|
ffb2a3d6e6 | ||
|
|
aff81a13e3 | ||
|
|
570d40f825 | ||
|
|
3dbcefc14c | ||
|
|
9cbad0b1ac | ||
|
|
f524ffc3d6 | ||
|
|
1fe92c978a | ||
|
|
1f016211f2 | ||
|
|
49c5ff188b | ||
|
|
46f99b9e08 | ||
|
|
dcb1a3001b | ||
|
|
dbfcd764f3 | ||
|
|
96e4bd4eab | ||
|
|
d788afc126 | ||
|
|
50a7b1b9f5 | ||
|
|
79027970e1 | ||
|
|
6e9853add5 | ||
|
|
07f2dc8e8f | ||
|
|
0f924aebb0 | ||
|
|
8ec499ae3f | ||
|
|
53c1933ac8 | ||
|
|
4df3f775e1 | ||
|
|
6b570c573b | ||
|
|
d164749a7f | ||
|
|
50c5fd79f7 | ||
|
|
c6169cba80 | ||
|
|
017c1c6b31 | ||
|
|
a8df9a7ae1 | ||
|
|
d38fd373f0 | ||
|
|
a6fe10d8ff | ||
|
|
953549704a | ||
|
|
19d8819137 | ||
|
|
1b80b506cb | ||
|
|
4b289a4802 | ||
|
|
09288e9a1e | ||
|
|
238ef76c5c | ||
|
|
906e66e3cf | ||
|
|
c0d14f9632 | ||
|
|
70bda85dd5 | ||
|
|
9e6f81540f | ||
|
|
3e1fc3e60e | ||
|
|
826853fff5 | ||
|
|
9be131cf6d | ||
|
|
5ed97915c7 | ||
|
|
d8654ae1be | ||
|
|
8f4744398d | ||
|
|
8f4cefd3bd | ||
|
|
01dc415f10 | ||
|
|
af1fe6c61c | ||
|
|
7bf75af8a1 | ||
|
|
c08952dff9 | ||
|
|
58430cd393 | ||
|
|
46d42f9ca9 | ||
|
|
43ff1db06b | ||
|
|
f934feb457 | ||
|
|
79d41b29ad | ||
|
|
bb6523cd9c | ||
|
|
925e9743a8 | ||
|
|
049c4be6e5 | ||
|
|
e36cf24ba9 | ||
|
|
1772291da7 | ||
|
|
3c4ac03656 | ||
|
|
7248d01b1b | ||
|
|
f1f98c3bab | ||
|
|
4405e2a389 | ||
|
|
67b82ad9b4 | ||
|
|
33bdc75a99 | ||
|
|
a573f8b14f | ||
|
|
7630173b24 | ||
|
|
7d942367fd | ||
|
|
da0a01a25b | ||
|
|
9a7cb70969 |
No files matched your search
@@ -0,0 +1,35 @@
|
|||||||
|
name: Build bionic runtime pack and DroidDeck-Bionic tool
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
paths:
|
||||||
|
- 'tools/bionic-runtime/**'
|
||||||
|
- 'tools/gamescope/patches/0117-wsi-cache-present-bypass-check.patch'
|
||||||
|
- 'tools/gamescope/patches/0119-wsi-default-images-under-limiter.patch'
|
||||||
|
- 'app/src/main/cpp/fakeinput_steam.cpp'
|
||||||
|
- 'tools/gpuload/**'
|
||||||
|
- '.github/workflows/build-bionic-runtime.yml'
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
timeout-minutes: 45
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Host tools
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
sudo apt-get update -qq
|
||||||
|
sudo apt-get install -y -qq --no-install-recommends libwayland-bin libwayland-dev libx11-dev libx11-xcb-dev \
|
||||||
|
libxcb1-dev libxcb-composite0-dev libglm-dev zstd
|
||||||
|
- name: Build
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
export NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
|
||||||
|
export BUILD_NUMBER=${{ github.run_number }}
|
||||||
|
tools/bionic-runtime/build.sh "$RUNNER_TEMP/bionic-runtime" "$PWD/out"
|
||||||
|
- uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: droiddeck-bionic-runtime-${{ github.sha }}
|
||||||
|
path: out/*
|
||||||
@@ -754,12 +754,17 @@ jobs:
|
|||||||
ln -sfn "$(cd "$jars" && pwd)" "$m2"
|
ln -sfn "$(cd "$jars" && pwd)" "$m2"
|
||||||
echo "cache=true" >> "$GITHUB_OUTPUT"
|
echo "cache=true" >> "$GITHUB_OUTPUT"
|
||||||
fi
|
fi
|
||||||
- name: Cache Robolectric's Android jars
|
- name: Restore Robolectric's Android jars
|
||||||
|
id: robolectric-cache
|
||||||
if: steps.robolectric-jars.outputs.cache == 'true'
|
if: steps.robolectric-jars.outputs.cache == 'true'
|
||||||
uses: actions/cache@v4
|
uses: actions/cache/restore@v4
|
||||||
with:
|
with:
|
||||||
path: ../robolectric-jars
|
path: ../robolectric-jars
|
||||||
key: robolectric-android-all-v2-${{ steps.robolectric.outputs.version }}
|
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
|
||||||
|
restore-keys: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-
|
||||||
|
- name: Count the restored Robolectric jars
|
||||||
|
if: steps.robolectric-jars.outputs.cache == 'true'
|
||||||
|
run: echo "ROBOLECTRIC_JARS_BEFORE=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)" >> "$GITHUB_ENV"
|
||||||
- name: Unit tests
|
- name: Unit tests
|
||||||
id: unit-tests
|
id: unit-tests
|
||||||
env:
|
env:
|
||||||
@@ -770,6 +775,34 @@ jobs:
|
|||||||
mkdir -p app/build
|
mkdir -p app/build
|
||||||
./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log
|
./gradlew testReleaseUnitTest --console=plain --info --stacktrace -Drobolectric.logging=stderr -PndkVersion="$NDK_VERSION" 2>&1 | tee app/build/unit-tests.log
|
||||||
|
|
||||||
|
# actions/cache only saves when the job succeeds, so a run whose tests died on a Maven 429 never filled the cache.
|
||||||
|
# Save the complete jars even after a failed test step, when this run added some; a partial download is dropped first.
|
||||||
|
- name: Save Robolectric's Android jars
|
||||||
|
id: robolectric-jars-final
|
||||||
|
if: always() && steps.robolectric-jars.outputs.cache == 'true'
|
||||||
|
run: |
|
||||||
|
python3 - <<'PY'
|
||||||
|
import glob, os, zipfile
|
||||||
|
root = os.path.join(os.environ['GITHUB_WORKSPACE'], '..', 'robolectric-jars')
|
||||||
|
for f in glob.glob(os.path.join(root, '**', '*'), recursive=True):
|
||||||
|
if not os.path.isfile(f):
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
ok = f.endswith('.jar') and zipfile.ZipFile(f).testzip() is None
|
||||||
|
except Exception:
|
||||||
|
ok = False
|
||||||
|
if not ok:
|
||||||
|
os.remove(f)
|
||||||
|
PY
|
||||||
|
after=$(find "$GITHUB_WORKSPACE/../robolectric-jars" -name '*.jar' | wc -l)
|
||||||
|
[ "$after" -gt "${ROBOLECTRIC_JARS_BEFORE:-0}" ] && echo "save=true" >> "$GITHUB_OUTPUT" || true
|
||||||
|
- name: Store Robolectric's Android jars
|
||||||
|
if: always() && steps.robolectric-jars-final.outputs.save == 'true'
|
||||||
|
uses: actions/cache/save@v4
|
||||||
|
with:
|
||||||
|
path: ../robolectric-jars
|
||||||
|
key: robolectric-android-all-v3-${{ steps.robolectric.outputs.version }}-${{ github.run_id }}
|
||||||
|
|
||||||
- name: Upload unit test diagnostics
|
- name: Upload unit test diagnostics
|
||||||
id: unit-test-diagnostics
|
id: unit-test-diagnostics
|
||||||
if: always() && steps.unit-tests.outcome != 'skipped'
|
if: always() && steps.unit-tests.outcome != 'skipped'
|
||||||
|
|||||||
@@ -7,10 +7,10 @@
|
|||||||
|
|
||||||
DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linux desktop, integration with GOG, Epic Games, Xbox, and other storefronts, Steam VR, and more!
|
DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linux desktop, integration with GOG, Epic Games, Xbox, and other storefronts, Steam VR, and more!
|
||||||
|
|
||||||
<p align="center"><b>100% open source. No ads. No telemetry. No proprietary components. No source withheld.</b></p>
|
<p align="center"><b>100% open source. No ads. No Subscriptions. No telemetry. No proprietary components. No source withheld.</b></p>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.1/DroidDeck-0.7.1.apk"><img src="https://img.shields.io/badge/Download-DroidDeck%200.7.1%20APK-3DDC84?style=for-the-badge&logo=android&logoColor=white" alt="Download DroidDeck 0.7.1"></a>
|
<a href="https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.11/DroidDeck-0.7.11.apk"><img src="https://img.shields.io/badge/Download-DroidDeck%200.7.11%20APK-3DDC84?style=for-the-badge&logo=android&logoColor=white" alt="Download DroidDeck 0.7.11"></a>
|
||||||
<a href="https://discord.gg/JRGAvawjsm"><img src="https://img.shields.io/badge/Discord-Join%20us-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Join the DroidDeck Discord"></a>
|
<a href="https://discord.gg/JRGAvawjsm"><img src="https://img.shields.io/badge/Discord-Join%20us-5865F2?style=for-the-badge&logo=discord&logoColor=white" alt="Join the DroidDeck Discord"></a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linu
|
|||||||
<a href="https://trendshift.io/repositories/267852"><img src="https://trendshift.io/api/badge/trendshift/repositories/267852/daily?language=Kotlin" alt="Droid-Deck%2FDroidDeck | Trendshift" width="250" height="55"></a>
|
<a href="https://trendshift.io/repositories/267852"><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>
|
||||||
|
|
||||||
<p align="center"><img src="docs/media/steam-to-desktop.gif" width="100%" alt="On a Retroid Pocket Duo: Play Steam from the DroidDeck launcher, open Pac-Man in Steam Big Picture and play it, exit the game, then Switch to Desktop from the Power menu"></p>
|
<p align="center"><a href="https://www.youtube.com/watch?v=ruaTSm_7a2c"><img src="docs/media/droiddeck-showcase.gif" width="60%" alt="A table of handhelds and phones all running DroidDeck, one waking to the Steam menu, the AYN Thor's bottom screen used as a touchpad, and scrolling around Steam on a phone before swiping to the home screen. Footage from Cyber Dopamine's video, linked."></a></p>
|
||||||
|
|
||||||
> The official website is [droid-deck.dev](https://droid-deck.dev). Only download DroidDeck from this repository's [Releases](https://github.com/Droid-Deck/DroidDeck/releases).
|
> The official website is [droid-deck.dev](https://droid-deck.dev). Only download DroidDeck from this repository's [Releases](https://github.com/Droid-Deck/DroidDeck/releases).
|
||||||
|
|
||||||
@@ -38,7 +38,7 @@ DroidDeck brings the SteamOS experience to Android: Steam Gaming Mode, full Linu
|
|||||||
|
|
||||||
1. Android 9 or newer on Adreno 730 or newer, or any 8xx. Adreno 6xx, Mali, Xclipse and PowerVR are experimental. Adreno 710 is currently unsupported. No root needed.
|
1. Android 9 or newer on Adreno 730 or newer, or any 8xx. Adreno 6xx, Mali, Xclipse and PowerVR are experimental. Adreno 710 is currently unsupported. No root needed.
|
||||||
2. About 3 GB free for the runtime, plus 1.1 GB for the desktop and emulators.
|
2. About 3 GB free for the runtime, plus 1.1 GB for the desktop and emulators.
|
||||||
3. Install the [APK](https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.1/DroidDeck-0.7.1.apk), install the Linux runtime, press **Play** and sign in to Steam.
|
3. Install the [APK](https://github.com/Droid-Deck/DroidDeck/releases/download/0.7.11/DroidDeck-0.7.11.apk), install the Linux runtime, press **Play** and sign in to Steam.
|
||||||
4. On Android 14 and newer, turn on **Disable child process restrictions** in Developer options. On Android 12 and 13, Steam's first launch shows a **Fix it for me** button that walks you through it.
|
4. On Android 14 and newer, turn on **Disable child process restrictions** in Developer options. On Android 12 and 13, Steam's first launch shows a **Fix it for me** button that walks you through it.
|
||||||
|
|
||||||
Smart glasses setup is in the [support matrix](docs/smart-glasses-support.md). Release notes are in [docs/releases](docs/releases).
|
Smart glasses setup is in the [support matrix](docs/smart-glasses-support.md). Release notes are in [docs/releases](docs/releases).
|
||||||
@@ -57,9 +57,6 @@ The APK lands in `app/build/outputs/apk/release/`. Install it with `tools/deploy
|
|||||||
|
|
||||||
On Windows, see `tools/run_windows.ps1` and `tools/prepare_windows_runtime.py`.
|
On Windows, see `tools/run_windows.ps1` and `tools/prepare_windows_runtime.py`.
|
||||||
|
|
||||||
## Limits
|
|
||||||
|
|
||||||
Compatibility and performance vary by device. Desktop compositing is software rendered, and Firefox sandboxing is reduced under proot.
|
|
||||||
|
|
||||||
## Credits and licence
|
## Credits and licence
|
||||||
|
|
||||||
@@ -71,7 +68,9 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
|
|||||||
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
|
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
|
||||||
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
|
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
|
||||||
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122).
|
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122).
|
||||||
|
- x86-64 programs on Wayland reach the GPU through FEX's Wayland client, wayland-egl and EGL thunks. The guest `wl_list` and `wl_array` helpers follow [libwayland](https://gitlab.freedesktop.org/wayland/wayland)'s `src/wayland-util.c` (MIT). The EGL extension table comes from the [Khronos EGL registry](https://github.com/KhronosGroup/EGL-Registry) (Apache-2.0) and Mesa's `egl_other.xml` (MIT).
|
||||||
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
|
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
|
||||||
|
- DwarFS AppImages are unpacked without proot by `dwarfsextract` from [DwarFS](https://github.com/mhx/dwarfs) by Marcus Holland-Moritz (MIT), the release binary uruntime embeds, taken out of its self-extracting wrapper and shipped with its licence.
|
||||||
- x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes.
|
- x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes.
|
||||||
- `WriteProcessMemory` hooks fall back to `/proc/<pid>/mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11.
|
- `WriteProcessMemory` hooks fall back to `/proc/<pid>/mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11.
|
||||||
- Windows programs on noexec storage get executable copies of their image pages, following [@yujikaido](https://github.com/yujikaido)'s finding in [droiddeck-rp4pro](https://github.com/yujikaido/droiddeck-rp4pro) that Wine's own processes need the noexec shim.
|
- Windows programs on noexec storage get executable copies of their image pages, following [@yujikaido](https://github.com/yujikaido)'s finding in [droiddeck-rp4pro](https://github.com/yujikaido/droiddeck-rp4pro) that Wine's own processes need the noexec shim.
|
||||||
|
|||||||
+2
-2
@@ -132,8 +132,8 @@ android {
|
|||||||
applicationId "com.droiddeck.launcher"
|
applicationId "com.droiddeck.launcher"
|
||||||
minSdkVersion 26
|
minSdkVersion 26
|
||||||
targetSdkVersion 34
|
targetSdkVersion 34
|
||||||
versionCode 19
|
versionCode 20
|
||||||
versionName "0.7.1"
|
versionName "0.7.11"
|
||||||
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
|
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
|
||||||
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
|
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
|
||||||
buildConfigField "int", "PR_NUMBER", "${prNumber}"
|
buildConfigField "int", "PR_NUMBER", "${prNumber}"
|
||||||
|
|||||||
@@ -58,6 +58,59 @@
|
|||||||
|
|
||||||
#define EXPORT extern "C" __attribute__((visibility("default")))
|
#define EXPORT extern "C" __attribute__((visibility("default")))
|
||||||
|
|
||||||
|
struct SymbolSlot {
|
||||||
|
std::atomic<void *> fn{nullptr};
|
||||||
|
std::atomic<bool> resolved{false};
|
||||||
|
};
|
||||||
|
|
||||||
|
template <typename Fn> static Fn resolved_symbol(SymbolSlot &slot, void *handle, const char *name) {
|
||||||
|
if (!slot.resolved.load(std::memory_order_acquire)) {
|
||||||
|
slot.fn.store(dlsym(handle, name), std::memory_order_relaxed);
|
||||||
|
slot.resolved.store(true, std::memory_order_release);
|
||||||
|
}
|
||||||
|
return reinterpret_cast<Fn>(slot.fn.load(std::memory_order_relaxed));
|
||||||
|
}
|
||||||
|
|
||||||
|
enum class Next : size_t {
|
||||||
|
open,
|
||||||
|
openat,
|
||||||
|
close,
|
||||||
|
write,
|
||||||
|
ioctl,
|
||||||
|
poll,
|
||||||
|
ppoll,
|
||||||
|
select,
|
||||||
|
stat,
|
||||||
|
stat64,
|
||||||
|
fstat,
|
||||||
|
fstat64,
|
||||||
|
xstat,
|
||||||
|
xstat64,
|
||||||
|
fxstat,
|
||||||
|
fxstat64,
|
||||||
|
statx,
|
||||||
|
statfs,
|
||||||
|
fstatfs,
|
||||||
|
access,
|
||||||
|
faccessat,
|
||||||
|
opendir,
|
||||||
|
scandir,
|
||||||
|
inotify_add_watch,
|
||||||
|
count
|
||||||
|
};
|
||||||
|
|
||||||
|
static const char *const next_names[] = {"open", "openat", "close", "write", "ioctl", "poll", "ppoll", "select", "stat", "stat64", "fstat", "fstat64", "__xstat", "__xstat64", "__fxstat", "__fxstat64", "statx", "statfs", "fstatfs", "access", "faccessat", "opendir", "scandir", "inotify_add_watch"};
|
||||||
|
static_assert(sizeof(next_names) / sizeof(next_names[0]) == static_cast<size_t>(Next::count), "next_names");
|
||||||
|
static SymbolSlot next_slots[static_cast<size_t>(Next::count)];
|
||||||
|
|
||||||
|
template <typename Fn> static Fn next_symbol(Next which) {
|
||||||
|
return resolved_symbol<Fn>(next_slots[static_cast<size_t>(which)], RTLD_NEXT, next_names[static_cast<size_t>(which)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void resolve_next_symbols() {
|
||||||
|
for (size_t i = 0; i < static_cast<size_t>(Next::count); i++) next_symbol<void *>(static_cast<Next>(i));
|
||||||
|
}
|
||||||
|
|
||||||
#ifdef __GLIBC__
|
#ifdef __GLIBC__
|
||||||
typedef unsigned long ioctl_request_t;
|
typedef unsigned long ioctl_request_t;
|
||||||
#else
|
#else
|
||||||
@@ -205,6 +258,11 @@ static void controller_fork_prepare();
|
|||||||
static void controller_fork_parent();
|
static void controller_fork_parent();
|
||||||
static void controller_fork_child();
|
static void controller_fork_child();
|
||||||
|
|
||||||
|
// bionic: libc's own start-up calls hooked functions (access) before environ is set. Settings read
|
||||||
|
// then would be empty and cached for good, so until environ exists hooks see defaults, uncached.
|
||||||
|
extern "C" char **environ;
|
||||||
|
static bool env_ready() { return environ != nullptr; }
|
||||||
|
|
||||||
struct FakeConfig {
|
struct FakeConfig {
|
||||||
const char *hook_dir;
|
const char *hook_dir;
|
||||||
const char *udev_data_dir;
|
const char *udev_data_dir;
|
||||||
@@ -218,6 +276,10 @@ struct FakeConfig {
|
|||||||
// would throw a recursive-init error there, so the fields are filled without allocating, and a
|
// would throw a recursive-init error there, so the fields are filled without allocating, and a
|
||||||
// reentry on the initializing thread gets them while other threads wait for the fork handlers.
|
// reentry on the initializing thread gets them while other threads wait for the fork handlers.
|
||||||
static FakeConfig &config() {
|
static FakeConfig &config() {
|
||||||
|
if (!env_ready()) {
|
||||||
|
static FakeConfig early = {"/data/data/com.termux/files/home/fake-input", nullptr, false, false, false};
|
||||||
|
return early;
|
||||||
|
}
|
||||||
static FakeConfig cfg;
|
static FakeConfig cfg;
|
||||||
static std::atomic<int> state{0};
|
static std::atomic<int> state{0};
|
||||||
static __thread bool initializing __attribute__((tls_model("initial-exec")));
|
static __thread bool initializing __attribute__((tls_model("initial-exec")));
|
||||||
@@ -433,6 +495,7 @@ void log(const char *message, ...) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
__attribute__((constructor)) static void library_init() {
|
__attribute__((constructor)) static void library_init() {
|
||||||
|
resolve_next_symbols();
|
||||||
config();
|
config();
|
||||||
controller_mutex();
|
controller_mutex();
|
||||||
controller_map();
|
controller_map();
|
||||||
@@ -587,7 +650,7 @@ get_fake_input_rdev(const char *event) {
|
|||||||
|
|
||||||
__attribute__((visibility("hidden"))) static void load_ring_paths() {
|
__attribute__((visibility("hidden"))) static void load_ring_paths() {
|
||||||
std::lock_guard<std::recursive_mutex> guard(controller_mutex());
|
std::lock_guard<std::recursive_mutex> guard(controller_mutex());
|
||||||
if (ring_paths_loaded)
|
if (ring_paths_loaded || !env_ready())
|
||||||
return;
|
return;
|
||||||
|
|
||||||
const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS");
|
const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS");
|
||||||
@@ -724,7 +787,7 @@ open_fake_input_ring(const char *event, int flags) {
|
|||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||||
|
|
||||||
int fd = my_open(ring_path.c_str(), O_RDWR | (flags & (O_NONBLOCK | O_CLOEXEC)));
|
int fd = my_open(ring_path.c_str(), O_RDWR | (flags & (O_NONBLOCK | O_CLOEXEC)));
|
||||||
if (fd < 0)
|
if (fd < 0)
|
||||||
@@ -807,12 +870,25 @@ __attribute__((visibility("hidden"))) static bool is_steam_client() {
|
|||||||
__attribute__((visibility("hidden"))) static bool presents_steam_virtual() {
|
__attribute__((visibility("hidden"))) static bool presents_steam_virtual() {
|
||||||
static int known;
|
static int known;
|
||||||
if (known == 0) {
|
if (known == 0) {
|
||||||
|
if (!env_ready()) return false;
|
||||||
const char *enabled = getenv("FAKE_EVDEV_STEAM_VIRTUAL");
|
const char *enabled = getenv("FAKE_EVDEV_STEAM_VIRTUAL");
|
||||||
known = enabled && atoi(enabled) && !is_steam_client() ? 1 : -1;
|
known = enabled && atoi(enabled) && !is_steam_client() ? 1 : -1;
|
||||||
}
|
}
|
||||||
return known == 1;
|
return known == 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The bionic Proton layer's winebus has no udev bus, and its SDL bus skips 28de:11ff (Proton reads Steam's virtual
|
||||||
|
// pad through udev/evdev), so with FAKE_EVDEV_STEAM_PAD_AS_X360=1 other processes see that pad as a plain Xbox 360 pad.
|
||||||
|
__attribute__((visibility("hidden"))) static bool steam_pad_as_x360() {
|
||||||
|
static int known;
|
||||||
|
if (known == 0) {
|
||||||
|
if (!env_ready()) return false;
|
||||||
|
const char *v = getenv("FAKE_EVDEV_STEAM_PAD_AS_X360");
|
||||||
|
known = v && atoi(v) && !is_steam_client() ? 1 : -1;
|
||||||
|
}
|
||||||
|
return known == 1;
|
||||||
|
}
|
||||||
|
|
||||||
__attribute__((visibility("hidden"))) static bool
|
__attribute__((visibility("hidden"))) static bool
|
||||||
presents_xbox_triggers(const FakeController &fake) {
|
presents_xbox_triggers(const FakeController &fake) {
|
||||||
return fake.uinput || !is_steam_client();
|
return fake.uinput || !is_steam_client();
|
||||||
@@ -978,7 +1054,7 @@ __attribute__((visibility("hidden"))) static void unpublish_uinput(UinputWriter
|
|||||||
}
|
}
|
||||||
|
|
||||||
__attribute__((visibility("hidden"))) static int claim_uinput_node(int *fd_out) {
|
__attribute__((visibility("hidden"))) static int claim_uinput_node(int *fd_out) {
|
||||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||||
for (int node = UINPUT_EVENT_BASE; node < UINPUT_EVENT_LIMIT; node++) {
|
for (int node = UINPUT_EVENT_BASE; node < UINPUT_EVENT_LIMIT; node++) {
|
||||||
std::string path = uinput_ring_path(node);
|
std::string path = uinput_ring_path(node);
|
||||||
int fd = my_open(path.c_str(), O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0644);
|
int fd = my_open(path.c_str(), O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0644);
|
||||||
@@ -1005,7 +1081,7 @@ __attribute__((visibility("hidden"))) static int claim_uinput_node(int *fd_out)
|
|||||||
}
|
}
|
||||||
|
|
||||||
__attribute__((visibility("hidden"))) static int publish_uinput(UinputWriter &w) {
|
__attribute__((visibility("hidden"))) static int publish_uinput(UinputWriter &w) {
|
||||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||||
int fd = -1;
|
int fd = -1;
|
||||||
int node = claim_uinput_node(&fd);
|
int node = claim_uinput_node(&fd);
|
||||||
if (node < 0) return -1;
|
if (node < 0) return -1;
|
||||||
@@ -1391,6 +1467,7 @@ static std::unordered_map<int, std::shared_ptr<DeckHidraw>> &deck_map() {
|
|||||||
|
|
||||||
static bool fake_deck_enabled() {
|
static bool fake_deck_enabled() {
|
||||||
static int enabled = -1;
|
static int enabled = -1;
|
||||||
|
if (enabled < 0 && !env_ready()) return false;
|
||||||
if (enabled < 0) enabled = getenv("FAKE_EVDEV_DECK") && atoi(getenv("FAKE_EVDEV_DECK")) ? 1 : 0;
|
if (enabled < 0) enabled = getenv("FAKE_EVDEV_DECK") && atoi(getenv("FAKE_EVDEV_DECK")) ? 1 : 0;
|
||||||
return enabled == 1;
|
return enabled == 1;
|
||||||
}
|
}
|
||||||
@@ -1398,6 +1475,7 @@ static bool fake_deck_enabled() {
|
|||||||
__attribute__((visibility("hidden"))) static uint32_t session_pad_type() {
|
__attribute__((visibility("hidden"))) static uint32_t session_pad_type() {
|
||||||
static int type = -1;
|
static int type = -1;
|
||||||
if (type < 0) {
|
if (type < 0) {
|
||||||
|
if (!env_ready()) return PAD_TYPE_DECK;
|
||||||
const char *env = getenv("FAKE_EVDEV_PAD_TYPE");
|
const char *env = getenv("FAKE_EVDEV_PAD_TYPE");
|
||||||
type = env && !strcmp(env, "steamcontroller") ? PAD_TYPE_STEAM
|
type = env && !strcmp(env, "steamcontroller") ? PAD_TYPE_STEAM
|
||||||
: env && !strcmp(env, "xbox360") ? PAD_TYPE_XBOX
|
: env && !strcmp(env, "xbox360") ? PAD_TYPE_XBOX
|
||||||
@@ -1416,7 +1494,7 @@ __attribute__((visibility("hidden"))) static const uint8_t *ring_blocks() {
|
|||||||
std::lock_guard<std::mutex> guard(lock);
|
std::lock_guard<std::mutex> guard(lock);
|
||||||
if ((mapped = block.load(std::memory_order_acquire))) return mapped;
|
if ((mapped = block.load(std::memory_order_acquire))) return mapped;
|
||||||
tries.fetch_add(1, std::memory_order_relaxed);
|
tries.fetch_add(1, std::memory_order_relaxed);
|
||||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||||
std::string path = get_ring_path_for_slot(0);
|
std::string path = get_ring_path_for_slot(0);
|
||||||
int fd = path.empty() ? -1 : my_open(path.c_str(), O_RDONLY | O_CLOEXEC);
|
int fd = path.empty() ? -1 : my_open(path.c_str(), O_RDONLY | O_CLOEXEC);
|
||||||
if (fd < 0) return nullptr;
|
if (fd < 0) return nullptr;
|
||||||
@@ -1470,6 +1548,7 @@ __attribute__((visibility("hidden"))) static uint64_t monotonic_us() {
|
|||||||
|
|
||||||
static bool fake_triton_enabled() {
|
static bool fake_triton_enabled() {
|
||||||
static int enabled = -1;
|
static int enabled = -1;
|
||||||
|
if (enabled < 0 && !env_ready()) return false;
|
||||||
if (enabled < 0)
|
if (enabled < 0)
|
||||||
enabled = fake_deck_enabled() && getenv("FAKE_EVDEV_TRITON") && atoi(getenv("FAKE_EVDEV_TRITON")) ? 1 : 0;
|
enabled = fake_deck_enabled() && getenv("FAKE_EVDEV_TRITON") && atoi(getenv("FAKE_EVDEV_TRITON")) ? 1 : 0;
|
||||||
return enabled == 1;
|
return enabled == 1;
|
||||||
@@ -1768,7 +1847,7 @@ __attribute__((visibility("hidden"))) static void *sony_report_thread(void *arg)
|
|||||||
|
|
||||||
__attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags, uint8_t sony = 0) {
|
__attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags, uint8_t sony = 0) {
|
||||||
const char *path = sony == 4 ? DS4_HIDRAW_PATH : sony == 5 ? DUALSENSE_HIDRAW_PATH : DECK_HIDRAW_PATH;
|
const char *path = sony == 4 ? DS4_HIDRAW_PATH : sony == 5 ? DUALSENSE_HIDRAW_PATH : DECK_HIDRAW_PATH;
|
||||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||||
if (!process_reads_pads()) {
|
if (!process_reads_pads()) {
|
||||||
Logger::log("deck: %s refused: not the Steam client\n", path);
|
Logger::log("deck: %s refused: not the Steam client\n", path);
|
||||||
errno = ENOENT;
|
errno = ENOENT;
|
||||||
@@ -1977,7 +2056,7 @@ __attribute__((visibility("hidden"))) static void *triton_pad_thread(void *arg)
|
|||||||
}
|
}
|
||||||
|
|
||||||
__attribute__((visibility("hidden"))) static int open_triton_hidraw(int flags, bool emulated) {
|
__attribute__((visibility("hidden"))) static int open_triton_hidraw(int flags, bool emulated) {
|
||||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||||
if (!process_reads_pads()) {
|
if (!process_reads_pads()) {
|
||||||
errno = ENOENT;
|
errno = ENOENT;
|
||||||
return -1;
|
return -1;
|
||||||
@@ -2091,11 +2170,12 @@ static_assert(sizeof(TouchRingFile) <= TOUCH_RING_SIZE, "TouchRingFile layout");
|
|||||||
|
|
||||||
__attribute__((visibility("hidden"))) static TouchRingFile *touch_ring() {
|
__attribute__((visibility("hidden"))) static TouchRingFile *touch_ring() {
|
||||||
static TouchRingFile *ring = nullptr;
|
static TouchRingFile *ring = nullptr;
|
||||||
|
if (!env_ready()) return nullptr;
|
||||||
static std::once_flag once;
|
static std::once_flag once;
|
||||||
std::call_once(once, [] {
|
std::call_once(once, [] {
|
||||||
const char *path = getenv("FAKE_TOUCHCTL_RING");
|
const char *path = getenv("FAKE_TOUCHCTL_RING");
|
||||||
if (!path || !*path || !fake_deck_enabled()) return;
|
if (!path || !*path || !fake_deck_enabled()) return;
|
||||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||||
int fd = my_open(path, O_RDWR | O_CLOEXEC);
|
int fd = my_open(path, O_RDWR | O_CLOEXEC);
|
||||||
if (fd < 0) {
|
if (fd < 0) {
|
||||||
Logger::log("touch: %s not openable (%s)\n", path, strerror(errno));
|
Logger::log("touch: %s not openable (%s)\n", path, strerror(errno));
|
||||||
@@ -2312,7 +2392,8 @@ __attribute__((visibility("hidden"))) static int inject_uevent(const char *actio
|
|||||||
const char *subsystem, const char *devname,
|
const char *subsystem, const char *devname,
|
||||||
unsigned major, unsigned minor) {
|
unsigned major, unsigned minor) {
|
||||||
using inject_fn = int (*)(const char *, const char *, const char *, const char *, unsigned, unsigned);
|
using inject_fn = int (*)(const char *, const char *, const char *, const char *, unsigned, unsigned);
|
||||||
static auto inject = reinterpret_cast<inject_fn>(dlsym(RTLD_DEFAULT, "dd_udevmon_inject"));
|
static SymbolSlot inject_slot;
|
||||||
|
const auto inject = resolved_symbol<inject_fn>(inject_slot, RTLD_DEFAULT, "dd_udevmon_inject");
|
||||||
return inject ? inject(action, devpath, subsystem, devname, major, minor) : -1;
|
return inject ? inject(action, devpath, subsystem, devname, major, minor) : -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2434,6 +2515,7 @@ __attribute__((constructor)) static void start_touch_controller() {
|
|||||||
static constexpr long SYSFS_FS_MAGIC = 0x62656572;
|
static constexpr long SYSFS_FS_MAGIC = 0x62656572;
|
||||||
|
|
||||||
__attribute__((visibility("hidden"))) static const char *deck_listing_dir() {
|
__attribute__((visibility("hidden"))) static const char *deck_listing_dir() {
|
||||||
|
if (!env_ready()) return nullptr;
|
||||||
static const char *dir = getenv("FAKE_DECK_SYSFS_LISTING");
|
static const char *dir = getenv("FAKE_DECK_SYSFS_LISTING");
|
||||||
return dir && *dir ? dir : nullptr;
|
return dir && *dir ? dir : nullptr;
|
||||||
}
|
}
|
||||||
@@ -2469,7 +2551,7 @@ __attribute__((visibility("hidden"))) static void note_deck_sysfs(const char *ho
|
|||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int fstatfs(int fd, struct statfs *buf) {
|
EXPORT int fstatfs(int fd, struct statfs *buf) {
|
||||||
static auto real = reinterpret_cast<int (*)(int, struct statfs *)>(dlsym(RTLD_NEXT, "fstatfs"));
|
const auto real = next_symbol<int (*)(int, struct statfs *)>(Next::fstatfs);
|
||||||
int result = real(fd, buf);
|
int result = real(fd, buf);
|
||||||
if (fake_deck_enabled() && is_deck_sysfs_fd(fd)) {
|
if (fake_deck_enabled() && is_deck_sysfs_fd(fd)) {
|
||||||
note_deck_sysfs("fstatfs", result);
|
note_deck_sysfs("fstatfs", result);
|
||||||
@@ -2479,7 +2561,7 @@ EXPORT int fstatfs(int fd, struct statfs *buf) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int statfs(const char *path, struct statfs *buf) {
|
EXPORT int statfs(const char *path, struct statfs *buf) {
|
||||||
static auto real = reinterpret_cast<int (*)(const char *, struct statfs *)>(dlsym(RTLD_NEXT, "statfs"));
|
const auto real = next_symbol<int (*)(const char *, struct statfs *)>(Next::statfs);
|
||||||
int result = real(path, buf);
|
int result = real(path, buf);
|
||||||
if (fake_deck_enabled() && is_deck_sysfs_path(path)) {
|
if (fake_deck_enabled() && is_deck_sysfs_path(path)) {
|
||||||
note_deck_sysfs(path, result);
|
note_deck_sysfs(path, result);
|
||||||
@@ -2528,7 +2610,7 @@ __attribute__((visibility("hidden"))) static int deck_imu_mode_change(const uint
|
|||||||
}
|
}
|
||||||
|
|
||||||
__attribute__((visibility("hidden"))) static void publish_imu_mode(const DeckHidraw &deck, int mode) {
|
__attribute__((visibility("hidden"))) static void publish_imu_mode(const DeckHidraw &deck, int mode) {
|
||||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||||
if (deck.mapping_size < FAKE_INPUT_RING_SIZE + DECK_IMU_BLOCK_SIZE) return;
|
if (deck.mapping_size < FAKE_INPUT_RING_SIZE + DECK_IMU_BLOCK_SIZE) return;
|
||||||
std::string path = get_ring_path_for_slot(0);
|
std::string path = get_ring_path_for_slot(0);
|
||||||
int fd = path.empty() ? -1 : my_open(path.c_str(), O_WRONLY | O_CLOEXEC);
|
int fd = path.empty() ? -1 : my_open(path.c_str(), O_WRONLY | O_CLOEXEC);
|
||||||
@@ -3037,7 +3119,7 @@ static int real_fstat(int fd, struct stat *buf);
|
|||||||
|
|
||||||
__attribute__((visibility("hidden"))) static bool deck_mount_id_from_fdinfo(
|
__attribute__((visibility("hidden"))) static bool deck_mount_id_from_fdinfo(
|
||||||
int dirfd, const char *path, int flags, struct statx *buf) {
|
int dirfd, const char *path, int flags, struct statx *buf) {
|
||||||
static auto real_openat = reinterpret_cast<decltype(&::openat)>(dlsym(RTLD_NEXT, "openat"));
|
const auto real_openat = next_symbol<decltype(&::openat)>(Next::openat);
|
||||||
int target;
|
int target;
|
||||||
if (!path || !*path) {
|
if (!path || !*path) {
|
||||||
if (!(flags & AT_EMPTY_PATH)) return false;
|
if (!(flags & AT_EMPTY_PATH)) return false;
|
||||||
@@ -3075,7 +3157,7 @@ __attribute__((visibility("hidden"))) static bool deck_mount_id_from_fdinfo(
|
|||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int statx(int dirfd, const char *path, int flags, unsigned mask, struct statx *buf) {
|
EXPORT int statx(int dirfd, const char *path, int flags, unsigned mask, struct statx *buf) {
|
||||||
static auto real = reinterpret_cast<decltype(&::statx)>(dlsym(RTLD_NEXT, "statx"));
|
const auto real = next_symbol<decltype(&::statx)>(Next::statx);
|
||||||
int result = real(dirfd, path, flags, mask, buf);
|
int result = real(dirfd, path, flags, mask, buf);
|
||||||
int saved_errno = errno;
|
int saved_errno = errno;
|
||||||
constexpr unsigned unique_mount_id = 0x4000;
|
constexpr unsigned unique_mount_id = 0x4000;
|
||||||
@@ -3096,7 +3178,7 @@ EXPORT int statx(int dirfd, const char *path, int flags, unsigned mask, struct s
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
EXPORT DIR *opendir(const char *name) {
|
EXPORT DIR *opendir(const char *name) {
|
||||||
static auto real = reinterpret_cast<DIR *(*)(const char *)>(dlsym(RTLD_NEXT, "opendir"));
|
const auto real = next_symbol<DIR *(*)(const char *)>(Next::opendir);
|
||||||
DIR *dir = real(name);
|
DIR *dir = real(name);
|
||||||
if (!dir) {
|
if (!dir) {
|
||||||
note_sys_failure(AT_FDCWD, name);
|
note_sys_failure(AT_FDCWD, name);
|
||||||
@@ -3126,7 +3208,7 @@ EXPORT int open(const char *pathname, int flags, ...) {
|
|||||||
|
|
||||||
va_end(va);
|
va_end(va);
|
||||||
|
|
||||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||||
|
|
||||||
if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags);
|
if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags);
|
||||||
if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags);
|
if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags);
|
||||||
@@ -3204,7 +3286,7 @@ EXPORT int openat(int dirfd, const char *pathname, int flags, ...) {
|
|||||||
|
|
||||||
va_end(va);
|
va_end(va);
|
||||||
|
|
||||||
static auto my_openat = reinterpret_cast<int (*)(int, const char *, int, ...)>(dlsym(RTLD_NEXT, "openat"));
|
const auto my_openat = next_symbol<int (*)(int, const char *, int, ...)>(Next::openat);
|
||||||
|
|
||||||
if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags);
|
if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags);
|
||||||
if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags);
|
if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags);
|
||||||
@@ -3363,10 +3445,10 @@ static int fake_stat_fd(int fd, S *buf, Real real) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static int real_stat(const char *pathname, struct stat *statbuf) {
|
static int real_stat(const char *pathname, struct stat *statbuf) {
|
||||||
static auto fn = reinterpret_cast<int (*)(const char *, struct stat *)>(dlsym(RTLD_NEXT, "stat"));
|
const auto fn = next_symbol<int (*)(const char *, struct stat *)>(Next::stat);
|
||||||
if (fn) return fn(pathname, statbuf);
|
if (fn) return fn(pathname, statbuf);
|
||||||
#ifdef _STAT_VER
|
#ifdef _STAT_VER
|
||||||
static auto xfn = reinterpret_cast<int (*)(int, const char *, struct stat *)>(dlsym(RTLD_NEXT, "__xstat"));
|
const auto xfn = next_symbol<int (*)(int, const char *, struct stat *)>(Next::xstat);
|
||||||
if (xfn) return xfn(_STAT_VER, pathname, statbuf);
|
if (xfn) return xfn(_STAT_VER, pathname, statbuf);
|
||||||
#endif
|
#endif
|
||||||
errno = ENOSYS;
|
errno = ENOSYS;
|
||||||
@@ -3374,10 +3456,10 @@ static int real_stat(const char *pathname, struct stat *statbuf) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static int real_fstat(int fd, struct stat *buf) {
|
static int real_fstat(int fd, struct stat *buf) {
|
||||||
static auto fn = reinterpret_cast<int (*)(int, struct stat *)>(dlsym(RTLD_NEXT, "fstat"));
|
const auto fn = next_symbol<int (*)(int, struct stat *)>(Next::fstat);
|
||||||
if (fn) return fn(fd, buf);
|
if (fn) return fn(fd, buf);
|
||||||
#ifdef _STAT_VER
|
#ifdef _STAT_VER
|
||||||
static auto xfn = reinterpret_cast<int (*)(int, int, struct stat *)>(dlsym(RTLD_NEXT, "__fxstat"));
|
const auto xfn = next_symbol<int (*)(int, int, struct stat *)>(Next::fxstat);
|
||||||
if (xfn) return xfn(_STAT_VER, fd, buf);
|
if (xfn) return xfn(_STAT_VER, fd, buf);
|
||||||
#endif
|
#endif
|
||||||
errno = ENOSYS;
|
errno = ENOSYS;
|
||||||
@@ -3393,7 +3475,7 @@ EXPORT int fstat(int fd, struct stat *buf) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int access(const char *pathname, int mode) {
|
EXPORT int access(const char *pathname, int mode) {
|
||||||
static auto my_access = reinterpret_cast<decltype(&::access)>(dlsym(RTLD_NEXT, "access"));
|
const auto my_access = next_symbol<decltype(&::access)>(Next::access);
|
||||||
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
|
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
|
||||||
if (is_deck_hidraw_path(pathname) && process_reads_pads()) return 0;
|
if (is_deck_hidraw_path(pathname) && process_reads_pads()) return 0;
|
||||||
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
|
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
|
||||||
@@ -3434,7 +3516,7 @@ EXPORT int access(const char *pathname, int mode) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int faccessat(int dirfd, const char *pathname, int mode, int flags) {
|
EXPORT int faccessat(int dirfd, const char *pathname, int mode, int flags) {
|
||||||
static auto my_faccessat = reinterpret_cast<decltype(&::faccessat)>(dlsym(RTLD_NEXT, "faccessat"));
|
const auto my_faccessat = next_symbol<decltype(&::faccessat)>(Next::faccessat);
|
||||||
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
|
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
|
||||||
if (is_deck_hidraw_path(pathname) && process_reads_pads()) return 0;
|
if (is_deck_hidraw_path(pathname) && process_reads_pads()) return 0;
|
||||||
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
|
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
|
||||||
@@ -3478,7 +3560,7 @@ EXPORT int scandir(const char *dirp, struct dirent ***namelist,
|
|||||||
int (*filter)(const struct dirent *),
|
int (*filter)(const struct dirent *),
|
||||||
int (*compar)(const struct dirent **,
|
int (*compar)(const struct dirent **,
|
||||||
const struct dirent **)) {
|
const struct dirent **)) {
|
||||||
static auto my_scandir = reinterpret_cast<decltype(&::scandir)>(dlsym(RTLD_NEXT, "scandir"));
|
const auto my_scandir = next_symbol<decltype(&::scandir)>(Next::scandir);
|
||||||
|
|
||||||
if (dirp) {
|
if (dirp) {
|
||||||
if (!strcmp(dirp, "/dev/input")) {
|
if (!strcmp(dirp, "/dev/input")) {
|
||||||
@@ -3492,7 +3574,7 @@ EXPORT int scandir(const char *dirp, struct dirent ***namelist,
|
|||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int inotify_add_watch(int fd, const char *pathname, uint32_t mask) {
|
EXPORT int inotify_add_watch(int fd, const char *pathname, uint32_t mask) {
|
||||||
static auto my_inotify_add_watch = reinterpret_cast<decltype(&::inotify_add_watch)>(dlsym(RTLD_NEXT, "inotify_add_watch"));
|
const auto my_inotify_add_watch = next_symbol<decltype(&::inotify_add_watch)>(Next::inotify_add_watch);
|
||||||
|
|
||||||
char *fake_path = nullptr;
|
char *fake_path = nullptr;
|
||||||
if (pathname) {
|
if (pathname) {
|
||||||
@@ -3631,7 +3713,7 @@ static bool wait_snapshot(std::shared_ptr<FakeController> fake,
|
|||||||
|
|
||||||
static int forward_ioctl(int fd, ioctl_request_t op, void *argp) {
|
static int forward_ioctl(int fd, ioctl_request_t op, void *argp) {
|
||||||
using ioctl_fn = int (*)(int, ioctl_request_t, ...);
|
using ioctl_fn = int (*)(int, ioctl_request_t, ...);
|
||||||
static const auto next = reinterpret_cast<ioctl_fn>(dlsym(RTLD_NEXT, "ioctl"));
|
const auto next = next_symbol<ioctl_fn>(Next::ioctl);
|
||||||
return next ? next(fd, op, argp) : static_cast<int>(syscall(SYS_ioctl, fd, op, argp));
|
return next ? next(fd, op, argp) : static_cast<int>(syscall(SYS_ioctl, fd, op, argp));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3689,6 +3771,10 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
|
|||||||
id.bustype = 0x03;
|
id.bustype = 0x03;
|
||||||
if (made) {
|
if (made) {
|
||||||
id = made->id;
|
id = made->id;
|
||||||
|
if (steam_pad_as_x360() && id.vendor == STEAM_VIRTUAL_VENDOR_ID && id.product == STEAM_VIRTUAL_PRODUCT_ID) {
|
||||||
|
id.vendor = X360_VENDOR_ID;
|
||||||
|
id.product = X360_PRODUCT_ID;
|
||||||
|
}
|
||||||
} else if (presents_steam_virtual()) {
|
} else if (presents_steam_virtual()) {
|
||||||
id.vendor = STEAM_VIRTUAL_VENDOR_ID;
|
id.vendor = STEAM_VIRTUAL_VENDOR_ID;
|
||||||
id.product = STEAM_VIRTUAL_PRODUCT_ID;
|
id.product = STEAM_VIRTUAL_PRODUCT_ID;
|
||||||
@@ -3866,7 +3952,7 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int close(int fd) {
|
EXPORT int close(int fd) {
|
||||||
static auto my_close = reinterpret_cast<decltype(&::close)>(dlsym(RTLD_NEXT, "close"));
|
const auto my_close = next_symbol<decltype(&::close)>(Next::close);
|
||||||
|
|
||||||
if (!watched(fd)) return my_close(fd);
|
if (!watched(fd)) return my_close(fd);
|
||||||
close_uinput(fd);
|
close_uinput(fd);
|
||||||
@@ -4054,7 +4140,7 @@ EXPORT ssize_t readv(int fd, const struct iovec *iov, int iovcnt) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
EXPORT ssize_t write(int fd, const void *buf, size_t count) {
|
EXPORT ssize_t write(int fd, const void *buf, size_t count) {
|
||||||
static auto my_write = reinterpret_cast<decltype(&::write)>(dlsym(RTLD_NEXT, "write"));
|
const auto my_write = next_symbol<decltype(&::write)>(Next::write);
|
||||||
|
|
||||||
if (!watched(fd)) return my_write(fd, buf, count);
|
if (!watched(fd)) return my_write(fd, buf, count);
|
||||||
std::unique_lock<std::recursive_mutex> guard(controller_mutex());
|
std::unique_lock<std::recursive_mutex> guard(controller_mutex());
|
||||||
@@ -4129,8 +4215,8 @@ EXPORT ssize_t writev(int fd, const struct iovec *iov, int iovcnt) {
|
|||||||
|
|
||||||
static int poll_fake(struct pollfd *fds, nfds_t nfds, int timeout,
|
static int poll_fake(struct pollfd *fds, nfds_t nfds, int timeout,
|
||||||
const sigset_t *sigmask) {
|
const sigset_t *sigmask) {
|
||||||
static auto my_poll = reinterpret_cast<decltype(&::poll)>(dlsym(RTLD_NEXT, "poll"));
|
const auto my_poll = next_symbol<decltype(&::poll)>(Next::poll);
|
||||||
static auto my_ppoll = reinterpret_cast<decltype(&::ppoll)>(dlsym(RTLD_NEXT, "ppoll"));
|
const auto my_ppoll = next_symbol<decltype(&::ppoll)>(Next::ppoll);
|
||||||
|
|
||||||
nfds_t first = 0;
|
nfds_t first = 0;
|
||||||
while (first < nfds && !watched(fds[first].fd)) first++;
|
while (first < nfds && !watched(fds[first].fd)) first++;
|
||||||
@@ -4234,7 +4320,7 @@ EXPORT int poll(struct pollfd *fds, nfds_t nfds, int timeout) {
|
|||||||
|
|
||||||
EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
|
EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
|
||||||
const struct timespec *timeout, const sigset_t *sigmask) {
|
const struct timespec *timeout, const sigset_t *sigmask) {
|
||||||
static auto my_ppoll = reinterpret_cast<decltype(&::ppoll)>(dlsym(RTLD_NEXT, "ppoll"));
|
const auto my_ppoll = next_symbol<decltype(&::ppoll)>(Next::ppoll);
|
||||||
if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) {
|
if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) {
|
||||||
errno = EINVAL;
|
errno = EINVAL;
|
||||||
return -1;
|
return -1;
|
||||||
@@ -4261,7 +4347,7 @@ EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
|
|||||||
|
|
||||||
EXPORT int select(int nfds, fd_set *readfds, fd_set *writefds,
|
EXPORT int select(int nfds, fd_set *readfds, fd_set *writefds,
|
||||||
fd_set *exceptfds, struct timeval *timeout) {
|
fd_set *exceptfds, struct timeval *timeout) {
|
||||||
static auto my_select = reinterpret_cast<decltype(&::select)>(dlsym(RTLD_NEXT, "select"));
|
const auto my_select = next_symbol<decltype(&::select)>(Next::select);
|
||||||
|
|
||||||
fd_set original_readfds;
|
fd_set original_readfds;
|
||||||
fd_set original_writefds;
|
fd_set original_writefds;
|
||||||
@@ -4423,10 +4509,10 @@ EXPORT int openat64(int dirfd, const char *pathname, int flags, ...) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static int real_stat64(const char *pathname, struct stat64 *statbuf) {
|
static int real_stat64(const char *pathname, struct stat64 *statbuf) {
|
||||||
static auto fn = reinterpret_cast<int (*)(const char *, struct stat64 *)>(dlsym(RTLD_NEXT, "stat64"));
|
const auto fn = next_symbol<int (*)(const char *, struct stat64 *)>(Next::stat64);
|
||||||
if (fn) return fn(pathname, statbuf);
|
if (fn) return fn(pathname, statbuf);
|
||||||
#ifdef _STAT_VER
|
#ifdef _STAT_VER
|
||||||
static auto xfn = reinterpret_cast<int (*)(int, const char *, struct stat64 *)>(dlsym(RTLD_NEXT, "__xstat64"));
|
const auto xfn = next_symbol<int (*)(int, const char *, struct stat64 *)>(Next::xstat64);
|
||||||
if (xfn) return xfn(_STAT_VER, pathname, statbuf);
|
if (xfn) return xfn(_STAT_VER, pathname, statbuf);
|
||||||
#endif
|
#endif
|
||||||
errno = ENOSYS;
|
errno = ENOSYS;
|
||||||
@@ -4434,10 +4520,10 @@ static int real_stat64(const char *pathname, struct stat64 *statbuf) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
static int real_fstat64(int fd, struct stat64 *buf) {
|
static int real_fstat64(int fd, struct stat64 *buf) {
|
||||||
static auto fn = reinterpret_cast<int (*)(int, struct stat64 *)>(dlsym(RTLD_NEXT, "fstat64"));
|
const auto fn = next_symbol<int (*)(int, struct stat64 *)>(Next::fstat64);
|
||||||
if (fn) return fn(fd, buf);
|
if (fn) return fn(fd, buf);
|
||||||
#ifdef _STAT_VER
|
#ifdef _STAT_VER
|
||||||
static auto xfn = reinterpret_cast<int (*)(int, int, struct stat64 *)>(dlsym(RTLD_NEXT, "__fxstat64"));
|
const auto xfn = next_symbol<int (*)(int, int, struct stat64 *)>(Next::fxstat64);
|
||||||
if (xfn) return xfn(_STAT_VER, fd, buf);
|
if (xfn) return xfn(_STAT_VER, fd, buf);
|
||||||
#endif
|
#endif
|
||||||
errno = ENOSYS;
|
errno = ENOSYS;
|
||||||
@@ -4453,27 +4539,27 @@ EXPORT int fstat64(int fd, struct stat64 *buf) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int __xstat(int version, const char *pathname, struct stat *statbuf) {
|
EXPORT int __xstat(int version, const char *pathname, struct stat *statbuf) {
|
||||||
static auto real = reinterpret_cast<int (*)(int, const char *, struct stat *)>(dlsym(RTLD_NEXT, "__xstat"));
|
const auto real = next_symbol<int (*)(int, const char *, struct stat *)>(Next::xstat);
|
||||||
if (!real) return stat(pathname, statbuf);
|
if (!real) return stat(pathname, statbuf);
|
||||||
return fake_stat_path(pathname, statbuf, [version](const char *path, struct stat *buf) { return real(version, path, buf); });
|
return fake_stat_path(pathname, statbuf, [version, real](const char *path, struct stat *buf) { return real(version, path, buf); });
|
||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int __xstat64(int version, const char *pathname, struct stat64 *statbuf) {
|
EXPORT int __xstat64(int version, const char *pathname, struct stat64 *statbuf) {
|
||||||
static auto real = reinterpret_cast<int (*)(int, const char *, struct stat64 *)>(dlsym(RTLD_NEXT, "__xstat64"));
|
const auto real = next_symbol<int (*)(int, const char *, struct stat64 *)>(Next::xstat64);
|
||||||
if (!real) return stat64(pathname, statbuf);
|
if (!real) return stat64(pathname, statbuf);
|
||||||
return fake_stat_path(pathname, statbuf, [version](const char *path, struct stat64 *buf) { return real(version, path, buf); });
|
return fake_stat_path(pathname, statbuf, [version, real](const char *path, struct stat64 *buf) { return real(version, path, buf); });
|
||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int __fxstat(int version, int fd, struct stat *buf) {
|
EXPORT int __fxstat(int version, int fd, struct stat *buf) {
|
||||||
static auto real = reinterpret_cast<int (*)(int, int, struct stat *)>(dlsym(RTLD_NEXT, "__fxstat"));
|
const auto real = next_symbol<int (*)(int, int, struct stat *)>(Next::fxstat);
|
||||||
if (!real) return fstat(fd, buf);
|
if (!real) return fstat(fd, buf);
|
||||||
return fake_stat_fd(fd, buf, [version](int f, struct stat *b) { return real(version, f, b); });
|
return fake_stat_fd(fd, buf, [version, real](int f, struct stat *b) { return real(version, f, b); });
|
||||||
}
|
}
|
||||||
|
|
||||||
EXPORT int __fxstat64(int version, int fd, struct stat64 *buf) {
|
EXPORT int __fxstat64(int version, int fd, struct stat64 *buf) {
|
||||||
static auto real = reinterpret_cast<int (*)(int, int, struct stat64 *)>(dlsym(RTLD_NEXT, "__fxstat64"));
|
const auto real = next_symbol<int (*)(int, int, struct stat64 *)>(Next::fxstat64);
|
||||||
if (!real) return fstat64(fd, buf);
|
if (!real) return fstat64(fd, buf);
|
||||||
return fake_stat_fd(fd, buf, [version](int f, struct stat64 *b) { return real(version, f, b); });
|
return fake_stat_fd(fd, buf, [version, real](int f, struct stat64 *b) { return real(version, f, b); });
|
||||||
}
|
}
|
||||||
|
|
||||||
#if defined(__x86_64__) || defined(__i386__)
|
#if defined(__x86_64__) || defined(__i386__)
|
||||||
@@ -4487,18 +4573,37 @@ static const char *const interposed_names[] = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
static dlsym_fn next_dlsym() {
|
static dlsym_fn next_dlsym() {
|
||||||
static const dlsym_fn fn = [] {
|
static std::atomic<dlsym_fn> fn{nullptr};
|
||||||
|
static std::atomic<bool> resolved{false};
|
||||||
|
if (!resolved.load(std::memory_order_acquire)) {
|
||||||
#ifdef __x86_64__
|
#ifdef __x86_64__
|
||||||
const char *base = "GLIBC_2.2.5";
|
const char *base = "GLIBC_2.2.5";
|
||||||
#else
|
#else
|
||||||
const char *base = "GLIBC_2.0";
|
const char *base = "GLIBC_2.0";
|
||||||
#endif
|
#endif
|
||||||
|
dlsym_fn found{};
|
||||||
for (const char *version : {base, "GLIBC_2.34"}) {
|
for (const char *version : {base, "GLIBC_2.34"}) {
|
||||||
if (auto found = reinterpret_cast<dlsym_fn>(dlvsym(RTLD_NEXT, "dlsym", version))) return found;
|
if ((found = reinterpret_cast<dlsym_fn>(dlvsym(RTLD_NEXT, "dlsym", version)))) break;
|
||||||
}
|
}
|
||||||
return dlsym_fn{};
|
fn.store(found, std::memory_order_relaxed);
|
||||||
}();
|
resolved.store(true, std::memory_order_release);
|
||||||
return fn;
|
}
|
||||||
|
return fn.load(std::memory_order_relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void *libc_handle() {
|
||||||
|
static std::atomic<void *> handle{nullptr};
|
||||||
|
static std::atomic<bool> resolved{false};
|
||||||
|
if (!resolved.load(std::memory_order_acquire)) {
|
||||||
|
handle.store(dlopen(LIBC_SO, RTLD_LAZY | RTLD_NOLOAD), std::memory_order_relaxed);
|
||||||
|
resolved.store(true, std::memory_order_release);
|
||||||
|
}
|
||||||
|
return handle.load(std::memory_order_relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
__attribute__((constructor)) static void resolve_dlsym_targets() {
|
||||||
|
next_dlsym();
|
||||||
|
libc_handle();
|
||||||
}
|
}
|
||||||
|
|
||||||
static void *global_dlsym(void *, const char *name) { return next_dlsym()(RTLD_DEFAULT, name); }
|
static void *global_dlsym(void *, const char *name) { return next_dlsym()(RTLD_DEFAULT, name); }
|
||||||
@@ -4516,8 +4621,7 @@ extern "C" __attribute__((visibility("hidden"), used)) void *fakeinput_dlsym_tar
|
|||||||
dlsym_fn next = next_dlsym();
|
dlsym_fn next = next_dlsym();
|
||||||
if (!next) return reinterpret_cast<void *>(missing_dlsym);
|
if (!next) return reinterpret_cast<void *>(missing_dlsym);
|
||||||
if (handle == RTLD_DEFAULT || handle == RTLD_NEXT || name == nullptr) return reinterpret_cast<void *>(next);
|
if (handle == RTLD_DEFAULT || handle == RTLD_NEXT || name == nullptr) return reinterpret_cast<void *>(next);
|
||||||
static void *const libc = dlopen(LIBC_SO, RTLD_LAZY | RTLD_NOLOAD);
|
if (handle != libc_handle() || !interposed(name)) return reinterpret_cast<void *>(next);
|
||||||
if (handle != libc || !interposed(name)) return reinterpret_cast<void *>(next);
|
|
||||||
return reinterpret_cast<void *>(global_dlsym);
|
return reinterpret_cast<void *>(global_dlsym);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -620,7 +620,8 @@ static void cursor_publish_shown(void) {
|
|||||||
|
|
||||||
static void cursor_publish_hidden(void) {
|
static void cursor_publish_hidden(void) {
|
||||||
pthread_mutex_lock(&g_cursor_lock);
|
pthread_mutex_lock(&g_cursor_lock);
|
||||||
if (!g_cursor_hidden) { g_cursor_hidden = 1; g_cursor_serial++; }
|
// A client that hides the cursor before ever showing one (gamescope drawing its own) must still be reported.
|
||||||
|
if (!g_cursor_hidden || g_cursor_serial == 0) { g_cursor_hidden = 1; g_cursor_serial++; }
|
||||||
pthread_mutex_unlock(&g_cursor_lock);
|
pthread_mutex_unlock(&g_cursor_lock);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -163,6 +163,7 @@ struct layer {
|
|||||||
ARect geo_src, geo_dst;
|
ARect geo_src, geo_dst;
|
||||||
int geo_valid;
|
int geo_valid;
|
||||||
int alloc_tier;
|
int alloc_tier;
|
||||||
|
unsigned import_failed_fmts;
|
||||||
uint64_t pool_modifier;
|
uint64_t pool_modifier;
|
||||||
int first_logged;
|
int first_logged;
|
||||||
int64_t drop_logged_ns;
|
int64_t drop_logged_ns;
|
||||||
@@ -487,7 +488,8 @@ static const char *tier_name(int tier) {
|
|||||||
|
|
||||||
static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fmt) {
|
static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fmt) {
|
||||||
g_alloc_failed = 0;
|
g_alloc_failed = 0;
|
||||||
while (l->alloc_tier <= TIER_LINEAR) {
|
const unsigned fmt_bit = fmt == AHB_RGB10A2 ? 2u : 1u;
|
||||||
|
while (l->alloc_tier <= TIER_LINEAR && !(l->import_failed_fmts & fmt_bit)) {
|
||||||
const int tier = l->alloc_tier;
|
const int tier = l->alloc_tier;
|
||||||
AHardwareBuffer_Desc d = {
|
AHardwareBuffer_Desc d = {
|
||||||
.width = (uint32_t)w, .height = (uint32_t)h, .layers = 1,
|
.width = (uint32_t)w, .height = (uint32_t)h, .layers = 1,
|
||||||
@@ -560,6 +562,7 @@ static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fm
|
|||||||
nh ? nh->numFds : -1, nh ? nh->numInts : -1, hd);
|
nh ? nh->numFds : -1, nh ? nh->numInts : -1, hd);
|
||||||
AHardwareBuffer_release(ahb);
|
AHardwareBuffer_release(ahb);
|
||||||
if (tier < TIER_LINEAR) { l->alloc_tier = tier + 1; continue; }
|
if (tier < TIER_LINEAR) { l->alloc_tier = tier + 1; continue; }
|
||||||
|
l->import_failed_fmts |= fmt_bit;
|
||||||
g_alloc_failed = 1;
|
g_alloc_failed = 1;
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1494,7 +1494,7 @@ struct vkp_image *vkp_image_from_ahb(AHardwareBuffer *ahb) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
int vkp_can_import_ahb(void) {
|
int vkp_can_import_ahb(void) {
|
||||||
return dev_init() == 0 && g_vendor_id != VKP_VENDOR_QUALCOMM && g_ahb_import &&
|
return dev_init() == 0 && g_vendor_id != VKP_VENDOR_QUALCOMM && !g_library_name && g_ahb_import &&
|
||||||
g_vk.GetAndroidHardwareBufferPropertiesANDROID;
|
g_vk.GetAndroidHardwareBufferPropertiesANDROID;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ class App : Application() {
|
|||||||
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
|
com.droiddeck.launcher.session.QuestExperimental.initialize(this)
|
||||||
com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
|
com.droiddeck.launcher.session.SessionPrefs.applyNtsyncDefault(this)
|
||||||
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
|
com.droiddeck.launcher.session.SessionPrefs.settleGpuDriverMode(this)
|
||||||
com.droiddeck.launcher.session.SessionPrefs.settleStoresTabOrder(this, com.droiddeck.launcher.stores.Store.entries.map { it.id })
|
com.droiddeck.launcher.session.SessionPrefs.settleStoresTabOrder(this, com.droiddeck.launcher.stores.Store.tabbed.map { it.id })
|
||||||
com.droiddeck.launcher.update.AppUpdates.init(this)
|
com.droiddeck.launcher.update.AppUpdates.init(this)
|
||||||
com.droiddeck.launcher.update.UpdateWatch.sync(this, com.droiddeck.launcher.update.AppUpdates.follow(this, null))
|
com.droiddeck.launcher.update.UpdateWatch.sync(this, com.droiddeck.launcher.update.AppUpdates.follow(this, null))
|
||||||
com.droiddeck.launcher.core.DownloadSource.init(this)
|
com.droiddeck.launcher.core.DownloadSource.init(this)
|
||||||
@@ -80,6 +80,7 @@ class App : Application() {
|
|||||||
com.droiddeck.launcher.stores.ea.EaBackend.app = this
|
com.droiddeck.launcher.stores.ea.EaBackend.app = this
|
||||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.ea.EaBackend)
|
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.ea.EaBackend)
|
||||||
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.rockstar.RockstarBackend)
|
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.rockstar.RockstarBackend)
|
||||||
|
com.droiddeck.launcher.stores.StoresState.register(com.droiddeck.launcher.stores.steam.SteamBackend)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun prefetchAddonPacks() {
|
private fun prefetchAddonPacks() {
|
||||||
|
|||||||
@@ -53,6 +53,8 @@ import com.droiddeck.launcher.session.SessionLogShare
|
|||||||
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 com.droiddeck.launcher.session.SteamRepair
|
import com.droiddeck.launcher.session.SteamRepair
|
||||||
|
import com.droiddeck.launcher.session.LaunchCoordinator
|
||||||
|
import com.droiddeck.launcher.session.LaunchTicket
|
||||||
import com.droiddeck.launcher.core.CpuCores
|
import com.droiddeck.launcher.core.CpuCores
|
||||||
import com.droiddeck.launcher.core.DownloadSource
|
import com.droiddeck.launcher.core.DownloadSource
|
||||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||||
@@ -139,6 +141,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
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 valveProtonOnDemand by mutableStateOf(true)
|
||||||
private var shaderPrecache by mutableStateOf<Boolean?>(null)
|
private var shaderPrecache by mutableStateOf<Boolean?>(null)
|
||||||
private var steamRepairQueued by mutableStateOf(false)
|
private var steamRepairQueued by mutableStateOf(false)
|
||||||
private var mangoapp by mutableStateOf(true)
|
private var mangoapp by mutableStateOf(true)
|
||||||
@@ -166,6 +169,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
private var battleNetInstalled 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 offlineAuto by mutableStateOf(true)
|
||||||
private var showPerformance by mutableStateOf(false)
|
private var showPerformance by mutableStateOf(false)
|
||||||
private var clientOverride by mutableStateOf(false)
|
private var clientOverride by mutableStateOf(false)
|
||||||
private var clientCores by mutableStateOf<Set<Int>>(emptySet())
|
private var clientCores by mutableStateOf<Set<Int>>(emptySet())
|
||||||
@@ -188,7 +192,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
private var prootNoSeccomp by mutableStateOf(false)
|
private var prootNoSeccomp by mutableStateOf(false)
|
||||||
private var prootFastPath by mutableStateOf(true)
|
private var prootFastPath by mutableStateOf(true)
|
||||||
private var nativeUserland by mutableStateOf(true)
|
private var nativeUserland by mutableStateOf(true)
|
||||||
private var cursorComposite by mutableStateOf(false)
|
private var cursorComposite by mutableStateOf(true)
|
||||||
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
|
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
|
||||||
private var phantomWarning by mutableStateOf<String?>(null)
|
private var phantomWarning by mutableStateOf<String?>(null)
|
||||||
private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE)
|
private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE)
|
||||||
@@ -215,7 +219,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
private var soundtracksLoaded by mutableStateOf(false)
|
private var soundtracksLoaded by mutableStateOf(false)
|
||||||
private var gameStoresSpeedTier by mutableStateOf("fast")
|
private var gameStoresSpeedTier by mutableStateOf("fast")
|
||||||
private var navRequest by mutableStateOf<String?>(null)
|
private var navRequest by mutableStateOf<String?>(null)
|
||||||
private val gameLaunchRequest = java.util.concurrent.atomic.AtomicLong()
|
private val launchCoordinator = LaunchCoordinator<Intent, com.droiddeck.launcher.frontend.GameRequest>()
|
||||||
private var preparingGames by mutableStateOf(emptySet<String>())
|
private var preparingGames by mutableStateOf(emptySet<String>())
|
||||||
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())
|
||||||
@@ -897,7 +901,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
runCatching { com.droiddeck.launcher.frontend.AutoComponents.restoreMissing(this) }.onFailure { Log.w(TAG, "components: restore failed", it) }
|
runCatching { com.droiddeck.launcher.frontend.AutoComponents.restoreMissing(this) }.onFailure { Log.w(TAG, "components: restore failed", it) }
|
||||||
}, "components-restore").start()
|
}, "components-restore").start()
|
||||||
}
|
}
|
||||||
private var pendingGameLink: com.droiddeck.launcher.frontend.GameRequest? = null
|
|
||||||
private var gameLinkReading = false
|
private var gameLinkReading = false
|
||||||
private var gameLinkTried = false
|
private var gameLinkTried = false
|
||||||
private var gameSyncFolder by mutableStateOf<String?>(null)
|
private var gameSyncFolder by mutableStateOf<String?>(null)
|
||||||
@@ -951,7 +954,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
else "settings:" + (com.droiddeck.launcher.ui.SettingsSection.of(section) ?: com.droiddeck.launcher.ui.SettingsSection.OVERVIEW).key
|
else "settings:" + (com.droiddeck.launcher.ui.SettingsSection.of(section) ?: com.droiddeck.launcher.ui.SettingsSection.OVERVIEW).key
|
||||||
request.data = null
|
request.data = null
|
||||||
gameLinkReading = false
|
gameLinkReading = false
|
||||||
pendingGameLink = null
|
|
||||||
syncDualPanel()
|
syncDualPanel()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -964,7 +966,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
steamGames = emptyList()
|
steamGames = emptyList()
|
||||||
shortcutLibraryScanning = true
|
shortcutLibraryScanning = true
|
||||||
} else shortcutLibraryScanning = false
|
} else shortcutLibraryScanning = false
|
||||||
pendingGameLink = null
|
|
||||||
gameLinkReading = false
|
gameLinkReading = false
|
||||||
gameLinkTried = false
|
gameLinkTried = false
|
||||||
soundtrackLaunch = false
|
soundtrackLaunch = false
|
||||||
@@ -977,6 +978,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (GameLaunchIntent.accepts(request.action)) {
|
if (GameLaunchIntent.accepts(request.action)) {
|
||||||
|
val ticket = launchCoordinator.beginLink(request)
|
||||||
gameLinkReading = true
|
gameLinkReading = true
|
||||||
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
|
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
|
||||||
val copy = Intent(request)
|
val copy = Intent(request)
|
||||||
@@ -985,12 +987,17 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
ui.post {
|
ui.post {
|
||||||
if (intent === request && !isDestroyed) {
|
if (intent === request && !isDestroyed) {
|
||||||
gameLinkReading = false
|
gameLinkReading = false
|
||||||
pendingGameLink = game
|
if (!launchCoordinator.resolve(ticket, game)) {
|
||||||
|
clearGameLinkIntent(request)
|
||||||
|
syncDualPanel()
|
||||||
|
return@post
|
||||||
|
}
|
||||||
if (game == null) {
|
if (game == null) {
|
||||||
|
launchCoordinator.consume(ticket)
|
||||||
syncDualPanel()
|
syncDualPanel()
|
||||||
android.widget.Toast.makeText(this, R.string.game_link_invalid, android.widget.Toast.LENGTH_LONG).show()
|
android.widget.Toast.makeText(this, R.string.game_link_invalid, android.widget.Toast.LENGTH_LONG).show()
|
||||||
} else {
|
} else {
|
||||||
handleGameLink(steamGames, scanned = false)
|
handleGameLink(steamGames, scanned = false, ticket = ticket)
|
||||||
refresh()
|
refresh()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -999,37 +1006,66 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}, onSettled: () -> Unit = {}) {
|
private fun beginUiLaunch(): LaunchTicket {
|
||||||
val request = gameLaunchRequest.incrementAndGet()
|
val dropped = launchCoordinator.pendingLink()
|
||||||
|
val ticket = launchCoordinator.beginLaunch()
|
||||||
|
dropped?.let { if (intent === it.owner) clearGameLinkIntent(it.owner) }
|
||||||
|
return ticket
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun clearGameLinkIntent(link: Intent) {
|
||||||
|
link.data = null
|
||||||
|
link.action = Intent.ACTION_MAIN
|
||||||
|
link.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun launchGame(
|
||||||
|
game: Library.SteamGame,
|
||||||
|
returnHome: Boolean = false,
|
||||||
|
onHandled: () -> Unit = {},
|
||||||
|
onSettled: () -> Unit = {},
|
||||||
|
ticket: LaunchTicket? = null,
|
||||||
|
) {
|
||||||
if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this)
|
if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this)
|
||||||
if (pkgStage != null) {
|
if (pkgStage != null) {
|
||||||
|
ticket?.let(launchCoordinator::releaseHandling)
|
||||||
onHandled()
|
onHandled()
|
||||||
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
|
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
val request = ticket ?: beginUiLaunch()
|
||||||
|
if (!launchCoordinator.isCurrent(request)) {
|
||||||
|
onHandled()
|
||||||
|
return
|
||||||
|
}
|
||||||
val files = game.gameFiles
|
val files = game.gameFiles
|
||||||
if (game.source != com.droiddeck.launcher.stores.Store.XBOX.id || files == null) {
|
if (game.source != com.droiddeck.launcher.stores.Store.XBOX.id || files == null) {
|
||||||
if (startGame(game, returnHome, onHandled)) onSettled()
|
if (startGame(game, returnHome, onHandled, request)) onSettled()
|
||||||
|
else launchCoordinator.releaseHandling(request)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
Thread({
|
Thread({
|
||||||
val refused = com.droiddeck.launcher.stores.xbox.XboxManifest.needsAppModel(files)
|
val refused = com.droiddeck.launcher.stores.xbox.XboxManifest.needsAppModel(files)
|
||||||
ui.post {
|
ui.post {
|
||||||
when {
|
when {
|
||||||
request != gameLaunchRequest.get() || isFinishing || isDestroyed -> onHandled()
|
!launchCoordinator.isCurrent(request) || isFinishing || isDestroyed -> {
|
||||||
|
launchCoordinator.releaseHandling(request)
|
||||||
|
onHandled()
|
||||||
|
}
|
||||||
refused -> {
|
refused -> {
|
||||||
onHandled()
|
onHandled()
|
||||||
android.widget.Toast.makeText(this, getString(R.string.game_needs_app_model, game.name), android.widget.Toast.LENGTH_LONG).show()
|
android.widget.Toast.makeText(this, getString(R.string.game_needs_app_model, game.name), android.widget.Toast.LENGTH_LONG).show()
|
||||||
onSettled()
|
onSettled()
|
||||||
}
|
}
|
||||||
startGame(game, returnHome, onHandled) -> onSettled()
|
startGame(game, returnHome, onHandled, request) -> onSettled()
|
||||||
|
else -> launchCoordinator.releaseHandling(request)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, "xbox-app-model").start()
|
}, "xbox-app-model").start()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun startGame(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit): Boolean {
|
private fun startGame(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit, ticket: LaunchTicket): Boolean {
|
||||||
if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled)
|
if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled, ticket)
|
||||||
onHandled()
|
onHandled()
|
||||||
if (SessionState.running) {
|
if (SessionState.running) {
|
||||||
if (SessionState.mode != SessionService.MODE_STEAM || SessionState.stopRequested) {
|
if (SessionState.mode != SessionService.MODE_STEAM || SessionState.stopRequested) {
|
||||||
@@ -1074,15 +1110,34 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
.apply { if (returnHome) putExtra(SessionActivity.EXTRA_LINK_TASK, task) }
|
.apply { if (returnHome) putExtra(SessionActivity.EXTRA_LINK_TASK, task) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun launchWithoutSteam(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit = {}): Boolean {
|
private fun launchWithoutSteam(
|
||||||
|
game: Library.SteamGame,
|
||||||
|
returnHome: Boolean,
|
||||||
|
onHandled: () -> Unit = {},
|
||||||
|
ticket: LaunchTicket? = null,
|
||||||
|
): Boolean {
|
||||||
|
if (pkgStage != null) {
|
||||||
|
onHandled()
|
||||||
|
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
|
||||||
|
return false
|
||||||
|
}
|
||||||
val app = applicationContext
|
val app = applicationContext
|
||||||
|
val request = ticket ?: beginUiLaunch()
|
||||||
|
if (!launchCoordinator.isCurrent(request)) {
|
||||||
|
onHandled()
|
||||||
|
return false
|
||||||
|
}
|
||||||
Thread({
|
Thread({
|
||||||
val added = if (com.droiddeck.launcher.session.NoSteamLaunch.needsAddedGame(game)) runCatching { com.droiddeck.launcher.session.NoSteamLaunch.addedGame(app, game) }.getOrNull() else null
|
val added = if (com.droiddeck.launcher.session.NoSteamLaunch.needsAddedGame(game)) runCatching { com.droiddeck.launcher.session.NoSteamLaunch.addedGame(app, game) }.getOrNull() else null
|
||||||
val command = com.droiddeck.launcher.session.NoSteamLaunch.command(game, added)
|
val command = com.droiddeck.launcher.session.NoSteamLaunch.command(game, added)
|
||||||
ui.post {
|
ui.post {
|
||||||
onHandled()
|
onHandled()
|
||||||
if (isDestroyed) return@post
|
if (!launchCoordinator.isCurrent(request) || isFinishing || isDestroyed) {
|
||||||
|
launchCoordinator.releaseHandling(request)
|
||||||
|
return@post
|
||||||
|
}
|
||||||
if (command == null) {
|
if (command == null) {
|
||||||
|
launchCoordinator.releaseHandling(request)
|
||||||
android.widget.Toast.makeText(this, R.string.game_link_failed, android.widget.Toast.LENGTH_LONG).show()
|
android.widget.Toast.makeText(this, R.string.game_link_failed, android.widget.Toast.LENGTH_LONG).show()
|
||||||
return@post
|
return@post
|
||||||
}
|
}
|
||||||
@@ -1204,6 +1259,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun startAfterSession(next: Intent) {
|
private fun startAfterSession(next: Intent) {
|
||||||
|
if (com.droiddeck.launcher.stores.steam.SteamStore.blocksSession(next)) {
|
||||||
|
android.widget.Toast.makeText(this, R.string.steam_store_session_wait, android.widget.Toast.LENGTH_SHORT).show()
|
||||||
|
return
|
||||||
|
}
|
||||||
SessionService.stop(this)
|
SessionService.stop(this)
|
||||||
awaitSessionEnd(next, android.os.SystemClock.uptimeMillis() + SESSION_SWITCH_WAIT_MS)
|
awaitSessionEnd(next, android.os.SystemClock.uptimeMillis() + SESSION_SWITCH_WAIT_MS)
|
||||||
}
|
}
|
||||||
@@ -1234,22 +1293,27 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
ui.postDelayed(poll, SESSION_SWITCH_POLL_MS)
|
ui.postDelayed(poll, SESSION_SWITCH_POLL_MS)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleGameLink(games: List<Library.SteamGame>, scanned: Boolean = true) {
|
private fun handleGameLink(games: List<Library.SteamGame>, scanned: Boolean = true, ticket: LaunchTicket? = null) {
|
||||||
if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) return
|
if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) return
|
||||||
val request = pendingGameLink ?: return
|
val link = launchCoordinator.pendingLink() ?: return
|
||||||
|
if (ticket != null && link.ticket !== ticket) return
|
||||||
|
val request = link.request ?: return
|
||||||
|
if (launchCoordinator.isHandling(link.ticket)) return
|
||||||
|
if (ticket == null && !link.ownedBy(intent)) {
|
||||||
|
// A refresh may only finish the link that belongs to the intent this activity shows.
|
||||||
|
launchCoordinator.consume(link.ticket)
|
||||||
|
return
|
||||||
|
}
|
||||||
val game = request.find(games, byTitle = scanned)
|
val game = request.find(games, byTitle = scanned)
|
||||||
if (!scanned && game == null) return
|
if (!scanned && game == null) return
|
||||||
gameLinkTried = true
|
gameLinkTried = true
|
||||||
ui.postDelayed({
|
ui.postDelayed({
|
||||||
if (!isDestroyed && lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) syncDualPanel()
|
if (!isDestroyed && lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) syncDualPanel()
|
||||||
}, LINK_PANEL_MS)
|
}, LINK_PANEL_MS)
|
||||||
val link = intent
|
val linkIntent = link.owner
|
||||||
fun consume() {
|
fun consume() {
|
||||||
if (intent !== link || pendingGameLink !== request) return
|
if (!launchCoordinator.consume(link.ticket)) return
|
||||||
pendingGameLink = null
|
if (intent === linkIntent) clearGameLinkIntent(linkIntent)
|
||||||
link.data = null
|
|
||||||
link.action = Intent.ACTION_MAIN
|
|
||||||
link.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
|
|
||||||
}
|
}
|
||||||
if (game == null) {
|
if (game == null) {
|
||||||
consume()
|
consume()
|
||||||
@@ -1257,7 +1321,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
android.widget.Toast.makeText(this,
|
android.widget.Toast.makeText(this,
|
||||||
if (request.program != null) R.string.game_link_program_unknown else R.string.game_link_missing,
|
if (request.program != null) R.string.game_link_program_unknown else R.string.game_link_missing,
|
||||||
android.widget.Toast.LENGTH_LONG).show()
|
android.widget.Toast.LENGTH_LONG).show()
|
||||||
} else launchGame(game, returnHome = true, onSettled = ::consume)
|
} else {
|
||||||
|
if (!launchCoordinator.beginHandling(link.ticket)) return
|
||||||
|
launchGame(game, returnHome = true, onSettled = ::consume, ticket = link.ticket)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun chooseGameShortcut(game: Library.SteamGame) {
|
private fun chooseGameShortcut(game: Library.SteamGame) {
|
||||||
@@ -1282,6 +1349,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
val shortcutsFilter = android.content.IntentFilter(SteamIntegration.SHORTCUTS_STATUS)
|
val shortcutsFilter = android.content.IntentFilter(SteamIntegration.SHORTCUTS_STATUS)
|
||||||
if (android.os.Build.VERSION.SDK_INT >= 33) registerReceiver(shortcutsInstallStatus, shortcutsFilter, RECEIVER_NOT_EXPORTED)
|
if (android.os.Build.VERSION.SDK_INT >= 33) registerReceiver(shortcutsInstallStatus, shortcutsFilter, RECEIVER_NOT_EXPORTED)
|
||||||
else registerReceiver(shortcutsInstallStatus, shortcutsFilter)
|
else registerReceiver(shortcutsInstallStatus, shortcutsFilter)
|
||||||
|
if (GameLaunchIntent.accepts(intent.action) &&
|
||||||
|
GameLaunchIntent.replayed(intent, savedInstanceState != null, savedInstanceState?.getString(STATE_PROCESS), PROCESS))
|
||||||
|
clearGameLinkIntent(intent)
|
||||||
readGameIntent(intent)
|
readGameIntent(intent)
|
||||||
// A Lab build is usually the agent's work, so the app comes back where the agent is.
|
// A Lab build is usually the agent's work, so the app comes back where the agent is.
|
||||||
if (savedInstanceState == null && navRequest == null && com.droiddeck.launcher.lab.LabOverlay.promoted && com.droiddeck.launcher.agent.AgentTab.visible) navRequest = "agent"
|
if (savedInstanceState == null && navRequest == null && com.droiddeck.launcher.lab.LabOverlay.promoted && com.droiddeck.launcher.agent.AgentTab.visible) navRequest = "agent"
|
||||||
@@ -1354,7 +1424,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
gameSyncFolder = gameSyncFolder,
|
gameSyncFolder = gameSyncFolder,
|
||||||
busy = busy, stage = stage, percent = percent,
|
busy = busy, stage = stage, percent = percent,
|
||||||
desktopInstalled = desktopInstalled, desktopPresent = desktopPresent,
|
desktopInstalled = desktopInstalled, desktopPresent = desktopPresent,
|
||||||
offlineAccount = offlineAccount, offline = offline,
|
offlineAccount = offlineAccount, offline = offline, offlineAuto = offlineAuto,
|
||||||
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
|
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
|
||||||
enhancedDiagnosticsArmed = enhancedDiagnosticsArmed,
|
enhancedDiagnosticsArmed = enhancedDiagnosticsArmed,
|
||||||
gameDebugLogsEnabled = gameDebugLogsEnabled, gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart,
|
gameDebugLogsEnabled = gameDebugLogsEnabled, gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart,
|
||||||
@@ -1448,16 +1518,20 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
},
|
},
|
||||||
onStoreGame = { store, id ->
|
onStoreGame = { store, id ->
|
||||||
val key = "${store.id}:$id"
|
val key = "${store.id}:$id"
|
||||||
if (key !in preparingGames) {
|
if (pkgStage != null) {
|
||||||
|
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
|
||||||
|
} else if (key !in preparingGames) {
|
||||||
preparingGames = preparingGames + key
|
preparingGames = preparingGames + key
|
||||||
|
val ticket = beginUiLaunch()
|
||||||
val app = applicationContext
|
val app = applicationContext
|
||||||
Thread({
|
Thread({
|
||||||
val g = runCatching { com.droiddeck.launcher.stores.StoreLaunch.installedGame(app, store, id) }.getOrNull()
|
val g = runCatching { com.droiddeck.launcher.stores.StoreLaunch.installedGame(app, store, id) }.getOrNull()
|
||||||
runOnUiThread {
|
runOnUiThread {
|
||||||
if (g != null && !isFinishing && !isDestroyed) prepareAndLaunch(g, key)
|
if (g != null && launchCoordinator.isCurrent(ticket) && !isFinishing && !isDestroyed) {
|
||||||
else {
|
prepareAndLaunch(g, key, ticket)
|
||||||
|
} else {
|
||||||
preparingGames = preparingGames - key
|
preparingGames = preparingGames - key
|
||||||
if (g == null && !isFinishing && !isDestroyed) android.widget.Toast.makeText(this, R.string.stores_launch_not_registered, android.widget.Toast.LENGTH_LONG).show()
|
if (g == null && launchCoordinator.isCurrent(ticket) && !isFinishing && !isDestroyed) android.widget.Toast.makeText(this, R.string.stores_launch_not_registered, android.widget.Toast.LENGTH_LONG).show()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, "store-play").start()
|
}, "store-play").start()
|
||||||
@@ -1688,6 +1762,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
OfflineMode.setEnabled(this, !OfflineMode.enabled(this))
|
OfflineMode.setEnabled(this, !OfflineMode.enabled(this))
|
||||||
offline = OfflineMode.enabled(this)
|
offline = OfflineMode.enabled(this)
|
||||||
},
|
},
|
||||||
|
onOfflineAuto = {
|
||||||
|
OfflineMode.setAuto(this, !OfflineMode.auto(this))
|
||||||
|
offlineAuto = OfflineMode.auto(this)
|
||||||
|
offline = OfflineMode.enabled(this)
|
||||||
|
},
|
||||||
onPageBack = { showPerformance = false; showComponents = false; showMapping = false },
|
onPageBack = { showPerformance = false; showComponents = false; showMapping = false },
|
||||||
onSoundtracksIngame = { on ->
|
onSoundtracksIngame = { on ->
|
||||||
SessionPrefs.setSoundtracksIngame(this, on)
|
SessionPrefs.setSoundtracksIngame(this, on)
|
||||||
@@ -1960,10 +2039,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
override fun onNewIntent(intent: Intent) {
|
override fun onNewIntent(intent: Intent) {
|
||||||
super.onNewIntent(intent)
|
super.onNewIntent(intent)
|
||||||
setIntent(intent)
|
setIntent(intent)
|
||||||
gameLaunchRequest.incrementAndGet()
|
supersedeUncommittedLaunch()
|
||||||
if (intent.action == SteamIntegration.ACTION_SETUP) {
|
if (intent.action == SteamIntegration.ACTION_SETUP) {
|
||||||
gameLinkReading = false
|
gameLinkReading = false
|
||||||
pendingGameLink = null
|
|
||||||
syncDualPanel()
|
syncDualPanel()
|
||||||
readIntegrationIntent(intent)
|
readIntegrationIntent(intent)
|
||||||
return
|
return
|
||||||
@@ -1973,6 +2051,11 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
startSteamAtStartupIfEnabled()
|
startSteamAtStartupIfEnabled()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A replacement activity intent supersedes anything this activity has not dispatched yet. */
|
||||||
|
private fun supersedeUncommittedLaunch() {
|
||||||
|
launchCoordinator.cancelAll()
|
||||||
|
}
|
||||||
|
|
||||||
private var soundtrackLaunch = false
|
private var soundtrackLaunch = false
|
||||||
|
|
||||||
// A restarted launcher starts before the old one stops, so each clears the hooks only if they are still its own.
|
// A restarted launcher starts before the old one stops, so each clears the hooks only if they are still its own.
|
||||||
@@ -2101,6 +2184,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
if (!triggerKeys.synthesizing && triggerKeys.nativeKey(event)) return true
|
if (!triggerKeys.synthesizing && triggerKeys.nativeKey(event)) return true
|
||||||
val tabStep = com.droiddeck.launcher.ui.dualPageStep(event)
|
val tabStep = com.droiddeck.launcher.ui.dualPageStep(event)
|
||||||
val tabs = com.droiddeck.launcher.ui.MainTabSteps.handler
|
val tabs = com.droiddeck.launcher.ui.MainTabSteps.handler
|
||||||
|
if (tabStep == null && event.action == KeyEvent.ACTION_DOWN) com.droiddeck.launcher.ui.MainTabSteps.otherKeys++
|
||||||
if (tabStep != null && tabs != null) {
|
if (tabStep != null && tabs != null) {
|
||||||
if (controllerHaptics) com.droiddeck.launcher.ui.ControllerHaptics.onKey(this, event)
|
if (controllerHaptics) com.droiddeck.launcher.ui.ControllerHaptics.onKey(this, event)
|
||||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) tabs(tabStep)
|
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) tabs(tabStep)
|
||||||
@@ -2231,6 +2315,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun saveLauncherState(outState: Bundle) {
|
private fun saveLauncherState(outState: Bundle) {
|
||||||
|
outState.putString(STATE_PROCESS, PROCESS)
|
||||||
outState.putBoolean(STATE_HOME_CHOICE_OPEN, homeChoiceOpen)
|
outState.putBoolean(STATE_HOME_CHOICE_OPEN, homeChoiceOpen)
|
||||||
outState.putBoolean(STATE_GAME_SPACE_OFFERED, gameSpaceOffered)
|
outState.putBoolean(STATE_GAME_SPACE_OFFERED, gameSpaceOffered)
|
||||||
pendingSessionLogExport?.let { outState.putString(KEY_PENDING_SESSION_LOG_EXPORT, it.absolutePath) }
|
pendingSessionLogExport?.let { outState.putString(KEY_PENDING_SESSION_LOG_EXPORT, it.absolutePath) }
|
||||||
@@ -2251,13 +2336,22 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
if (Build.VERSION.SDK_INT >= 33) state.getParcelable(key, Intent::class.java)
|
if (Build.VERSION.SDK_INT >= 33) state.getParcelable(key, Intent::class.java)
|
||||||
else @Suppress("DEPRECATION") state.getParcelable(key)
|
else @Suppress("DEPRECATION") state.getParcelable(key)
|
||||||
|
|
||||||
private fun prepareAndLaunch(g: Library.SteamGame, key: String) {
|
private fun prepareAndLaunch(g: Library.SteamGame, key: String, ticket: LaunchTicket? = null) {
|
||||||
val request = gameLaunchRequest.incrementAndGet()
|
if (pkgStage != null) {
|
||||||
|
preparingGames = preparingGames - key
|
||||||
|
android.widget.Toast.makeText(this, R.string.main_wait_install_game, android.widget.Toast.LENGTH_SHORT).show()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val request = ticket ?: beginUiLaunch()
|
||||||
|
if (!launchCoordinator.isCurrent(request)) {
|
||||||
|
preparingGames = preparingGames - key
|
||||||
|
return
|
||||||
|
}
|
||||||
val done = { preparingGames = preparingGames - key }
|
val done = { preparingGames = preparingGames - key }
|
||||||
com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g, onBlocked = done) {
|
com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g, onBlocked = done) {
|
||||||
if (request != gameLaunchRequest.get() || isFinishing || isDestroyed) { done(); return@beforeLaunch }
|
if (!launchCoordinator.isCurrent(request) || isFinishing || isDestroyed) { done(); return@beforeLaunch }
|
||||||
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) {
|
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) {
|
||||||
if (request == gameLaunchRequest.get() && !isFinishing && !isDestroyed) launchGame(g, onHandled = done)
|
if (launchCoordinator.isCurrent(request) && !isFinishing && !isDestroyed) launchGame(g, onHandled = done, ticket = request)
|
||||||
else done()
|
else done()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2267,7 +2361,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
// The queued launch was saved before this; a restored activity keeps its copy, and this one must not start it too.
|
// The queued launch was saved before this; a restored activity keeps its copy, and this one must not start it too.
|
||||||
queuedLaunchRunner.destroy()
|
queuedLaunchRunner.destroy()
|
||||||
triggerKeys.cancel()
|
triggerKeys.cancel()
|
||||||
gameLaunchRequest.incrementAndGet()
|
launchCoordinator.cancelAll()
|
||||||
cancelCompatLaunch()
|
cancelCompatLaunch()
|
||||||
updates.unregister()
|
updates.unregister()
|
||||||
runCatching { unregisterReceiver(shortcutsInstallStatus) }
|
runCatching { unregisterReceiver(shortcutsInstallStatus) }
|
||||||
@@ -2305,6 +2399,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
homeScreenEnabled = HomeApp.isHomeScreenEnabled(this)
|
homeScreenEnabled = HomeApp.isHomeScreenEnabled(this)
|
||||||
homeAppSelected = homeScreenEnabled && HomeApp.isDefault(this)
|
homeAppSelected = homeScreenEnabled && HomeApp.isDefault(this)
|
||||||
defaultHomeLabel = HomeApp.defaultLabel(this)
|
defaultHomeLabel = HomeApp.defaultLabel(this)
|
||||||
|
com.droiddeck.launcher.ui.NavTabs.syncHomeApps(this, homeAppSelected)
|
||||||
refreshAndroidApps()
|
refreshAndroidApps()
|
||||||
integrationState = readIntegration()
|
integrationState = readIntegration()
|
||||||
}
|
}
|
||||||
@@ -2346,7 +2441,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
else com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
|
else com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun launchPending(): Boolean = gameLinkReading || (pendingGameLink != null && !gameLinkTried)
|
private fun launchPending(): Boolean = gameLinkReading || (launchCoordinator.hasPending() && !gameLinkTried)
|
||||||
|
|
||||||
private fun launchAndroidApp(app: HomeApp.LaunchableApp, displayId: Int?) {
|
private fun launchAndroidApp(app: HomeApp.LaunchableApp, displayId: Int?) {
|
||||||
val onOwnScreen = displayId == null || displayId == (display?.displayId ?: Display.DEFAULT_DISPLAY)
|
val onOwnScreen = displayId == null || displayId == (display?.displayId ?: Display.DEFAULT_DISPLAY)
|
||||||
@@ -2705,6 +2800,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
steamClientArch = if (mode == SessionService.MODE_STEAM) steamClientArch else null,
|
steamClientArch = if (mode == SessionService.MODE_STEAM) steamClientArch else null,
|
||||||
returnAfterGame = if (mode == SessionService.MODE_STEAM) returnAfterGame else null,
|
returnAfterGame = if (mode == SessionService.MODE_STEAM) returnAfterGame else null,
|
||||||
shaderPrecache = if (mode == SessionService.MODE_STEAM) shaderPrecache else null,
|
shaderPrecache = if (mode == SessionService.MODE_STEAM) shaderPrecache else null,
|
||||||
|
valveProtonOnDemand = if (mode == SessionService.MODE_STEAM) valveProtonOnDemand else null,
|
||||||
steamRepairQueued = steamRepairQueued,
|
steamRepairQueued = steamRepairQueued,
|
||||||
mangoapp = mangoapp,
|
mangoapp = mangoapp,
|
||||||
steamController = if (mode == SessionService.MODE_STEAM) steamController else null,
|
steamController = if (mode == SessionService.MODE_STEAM) steamController else null,
|
||||||
@@ -2812,6 +2908,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
onMangoapp = { on -> SessionPrefs.setMangoapp(this, on); mangoapp = on },
|
onMangoapp = { on -> SessionPrefs.setMangoapp(this, on); mangoapp = on },
|
||||||
onReturnAfterGame = { on -> SessionPrefs.setReturnAfterGame(this, on); returnAfterGame = on },
|
onReturnAfterGame = { on -> SessionPrefs.setReturnAfterGame(this, on); returnAfterGame = on },
|
||||||
onShaderPrecache = { on -> SessionPrefs.setShaderPrecache(this, on); shaderPrecache = on },
|
onShaderPrecache = { on -> SessionPrefs.setShaderPrecache(this, on); shaderPrecache = on },
|
||||||
|
onValveProtonOnDemand = { on -> SessionPrefs.setValveProtonOnDemand(this, on); valveProtonOnDemand = on },
|
||||||
onSteamController = { id -> SessionPrefs.setSteamController(this, id); steamController = id },
|
onSteamController = { id -> SessionPrefs.setSteamController(this, id); steamController = id },
|
||||||
onStartupSession = { id ->
|
onStartupSession = { id ->
|
||||||
SessionPrefs.setStartupSession(this, id)
|
SessionPrefs.setStartupSession(this, id)
|
||||||
@@ -3007,6 +3104,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
val target = com.droiddeck.launcher.frontend.GameRemoval.steamFiles(g) ?: return
|
val target = com.droiddeck.launcher.frontend.GameRemoval.steamFiles(g) ?: return
|
||||||
|
if (Library.fromSteamClient(g)) {
|
||||||
|
com.droiddeck.launcher.stores.steam.SteamStore.uninstall(this, g.appId, target.manifest, fallback = { com.droiddeck.launcher.frontend.GameRemoval.delete(target) }) { refreshAddedGames(); refresh() }
|
||||||
|
return
|
||||||
|
}
|
||||||
Thread({
|
Thread({
|
||||||
com.droiddeck.launcher.frontend.GameRemoval.delete(target)
|
com.droiddeck.launcher.frontend.GameRemoval.delete(target)
|
||||||
ui.post { refreshAddedGames(); refresh() }
|
ui.post { refreshAddedGames(); refresh() }
|
||||||
@@ -3084,6 +3185,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
steamRepairQueued = SteamRepair.queued(this)
|
steamRepairQueued = SteamRepair.queued(this)
|
||||||
mangoapp = SessionPrefs.mangoapp(this)
|
mangoapp = SessionPrefs.mangoapp(this)
|
||||||
returnAfterGame = SessionPrefs.returnAfterGame(this)
|
returnAfterGame = SessionPrefs.returnAfterGame(this)
|
||||||
|
valveProtonOnDemand = SessionPrefs.valveProtonOnDemand(this)
|
||||||
loadShaderPrecache(mode)
|
loadShaderPrecache(mode)
|
||||||
steamController = SessionPrefs.steamController(this)
|
steamController = SessionPrefs.steamController(this)
|
||||||
startupSession = SessionPrefs.startupSession(this)
|
startupSession = SessionPrefs.startupSession(this)
|
||||||
@@ -3235,6 +3337,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
battleNetInstalled = com.droiddeck.launcher.runtime.BattleNet.installed(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)
|
||||||
|
offlineAuto = OfflineMode.auto(this)
|
||||||
installed = LinuxRuntimeInstaller.installedVersion(this)
|
installed = LinuxRuntimeInstaller.installedVersion(this)
|
||||||
ready = LinuxRuntime.isInstalled(this)
|
ready = LinuxRuntime.isInstalled(this)
|
||||||
vkBridge = SessionPrefs.vkBridge(this)
|
vkBridge = SessionPrefs.vkBridge(this)
|
||||||
@@ -3380,6 +3483,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
android.widget.Toast.makeText(this, R.string.storage_cleanup_busy, android.widget.Toast.LENGTH_SHORT).show()
|
android.widget.Toast.makeText(this, R.string.storage_cleanup_busy, android.widget.Toast.LENGTH_SHORT).show()
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
if (!SessionState.running && com.droiddeck.launcher.stores.steam.SteamStore.blocksSession(intent)) {
|
||||||
|
android.widget.Toast.makeText(this, R.string.steam_store_session_wait, android.widget.Toast.LENGTH_SHORT).show()
|
||||||
|
return false
|
||||||
|
}
|
||||||
refreshPhantomStatus()
|
refreshPhantomStatus()
|
||||||
if (steamSession && PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
|
if (steamSession && PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
|
||||||
if (queueIfBlocked) queuedLaunch.queue(intent, System.currentTimeMillis())
|
if (queueIfBlocked) queuedLaunch.queue(intent, System.currentTimeMillis())
|
||||||
@@ -3442,9 +3549,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
retryMs = GATE_LAUNCH_RETRY_MS,
|
retryMs = GATE_LAUNCH_RETRY_MS,
|
||||||
)
|
)
|
||||||
|
|
||||||
/** The conditions under which a Steam start waits instead of being refused: setup, a runtime or desktop install, or a storage cleanup. */
|
/** The conditions under which a Steam start waits instead of being refused: setup, a runtime or desktop install, a storage cleanup, or a Steam store download. */
|
||||||
private fun steamStartBusy(): Boolean = busy || LinuxRuntimeInstaller.isBusy() || com.droiddeck.launcher.session.Onboarding.settling() ||
|
private fun steamStartBusy(): Boolean = busy || LinuxRuntimeInstaller.isBusy() || com.droiddeck.launcher.session.Onboarding.settling() ||
|
||||||
(SessionState.installing != null && !SessionState.running) || com.droiddeck.launcher.storage.StorageState.cleaning
|
(SessionState.installing != null && !SessionState.running) || com.droiddeck.launcher.storage.StorageState.cleaning ||
|
||||||
|
(!SessionState.running && com.droiddeck.launcher.stores.steam.SteamStore.downloading())
|
||||||
|
|
||||||
private fun refreshPhantomStatus() {
|
private fun refreshPhantomStatus() {
|
||||||
phantomProcessStatus = PhantomProcessLimit.read(this)
|
phantomProcessStatus = PhantomProcessLimit.read(this)
|
||||||
@@ -3580,6 +3688,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
|||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
private val PROCESS = java.util.UUID.randomUUID().toString()
|
||||||
|
private const val STATE_PROCESS = "process"
|
||||||
private const val REQUEST_NOTIFICATIONS = 7103
|
private const val REQUEST_NOTIFICATIONS = 7103
|
||||||
private const val EXTRA_RESTARTED = "com.droiddeck.launcher.extra.RESTARTED"
|
private const val EXTRA_RESTARTED = "com.droiddeck.launcher.extra.RESTARTED"
|
||||||
private const val STATE_HOME_CHOICE_OPEN = "home_choice_open"
|
private const val STATE_HOME_CHOICE_OPEN = "home_choice_open"
|
||||||
|
|||||||
@@ -49,7 +49,7 @@ internal class ProtonMenu(
|
|||||||
@VisibleForTesting internal var latestCheck: (Boolean) -> Boolean = { force -> ProtonExtras.checkLatest(activity, force) }
|
@VisibleForTesting internal var latestCheck: (Boolean) -> Boolean = { force -> ProtonExtras.checkLatest(activity, force) }
|
||||||
@VisibleForTesting internal var experimentalRefresh: () -> List<ExperimentalProtons.Release>? = { ExperimentalProtons.refresh(activity) }
|
@VisibleForTesting internal var experimentalRefresh: () -> List<ExperimentalProtons.Release>? = { ExperimentalProtons.refresh(activity) }
|
||||||
@VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
|
@VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
|
||||||
{ tool, progress -> ProtonExtras.install(activity, tool, progress) }
|
{ tool, progress -> ProtonExtras.install(activity, tool, onProgress = progress) }
|
||||||
|
|
||||||
fun installProton(id: String, automatic: Boolean = false) {
|
fun installProton(id: String, automatic: Boolean = false) {
|
||||||
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
||||||
@@ -156,7 +156,7 @@ internal class ProtonMenu(
|
|||||||
|
|
||||||
fun refreshProtons() {
|
fun refreshProtons() {
|
||||||
refreshExperimental()
|
refreshExperimental()
|
||||||
protonRows = ProtonExtras.tools.map {
|
protonRows = ProtonExtras.offered(activity).map {
|
||||||
val all = ProtonExtras.installedAll(activity, it)
|
val all = ProtonExtras.installedAll(activity, it)
|
||||||
ProtonRow(it.id, it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it))
|
ProtonRow(it.id, it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -842,6 +842,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
finish()
|
finish()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if (!SessionState.running && com.droiddeck.launcher.stores.steam.SteamStore.blocksSession(intent)) {
|
||||||
|
runtimeRemovalBlocked = true
|
||||||
|
android.widget.Toast.makeText(this, R.string.steam_store_session_wait, android.widget.Toast.LENGTH_SHORT).show()
|
||||||
|
finish()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (savedInstanceState == null && !SessionState.running && !com.droiddeck.launcher.stores.steam.SteamStore.downloading()) {
|
||||||
|
// The Steam client signs in itself; the store's own sign-in must not overlap it.
|
||||||
|
Thread({ com.droiddeck.launcher.stores.steam.SteamEngine.forget() }, "steam-store-signout").start()
|
||||||
|
}
|
||||||
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
|
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
|
||||||
val mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
|
val mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
|
||||||
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
|
SessionState.programArgs = intent.getStringArrayExtra(SessionService.EXTRA_PROGRAM_ARGS)?.toList().orEmpty()
|
||||||
@@ -875,9 +885,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
cornerTap = SessionPrefs.drawerCornerTap(this)
|
cornerTap = SessionPrefs.drawerCornerTap(this)
|
||||||
applyOutputPacing()
|
applyOutputPacing()
|
||||||
if (!SessionState.running) {
|
if (!SessionState.running) {
|
||||||
SessionState.followScreen = followChoice()
|
SessionState.followScales = SessionPrefs.followScales(this, displayMode(),
|
||||||
SessionState.followScale = followScale()
|
com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
|
||||||
}
|
}
|
||||||
|
applyFollowChoice()
|
||||||
applyFollowOrientation(resources.configuration)
|
applyFollowOrientation(resources.configuration)
|
||||||
goFullscreen()
|
goFullscreen()
|
||||||
volumeControlStream = android.media.AudioManager.STREAM_MUSIC
|
volumeControlStream = android.media.AudioManager.STREAM_MUSIC
|
||||||
@@ -2833,6 +2844,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
|
|
||||||
private fun installProton(): String? {
|
private fun installProton(): String? {
|
||||||
uiHandler.post { loading.percent = -1; loading.say(getString(PROTON_LINES.downloading), PROTON_LINES.topic, readable = true) }
|
uiHandler.post { loading.percent = -1; loading.say(getString(PROTON_LINES.downloading), PROTON_LINES.topic, readable = true) }
|
||||||
|
if (com.droiddeck.launcher.session.SessionPrefs.ownProtonFirst(this)) return installOwnProton()
|
||||||
val catalog = com.droiddeck.launcher.runtime.DesktopCatalog
|
val catalog = com.droiddeck.launcher.runtime.DesktopCatalog
|
||||||
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
|
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
|
||||||
SessionState.installCancellation = cancellation
|
SessionState.installCancellation = cancellation
|
||||||
@@ -2845,6 +2857,24 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun installOwnProton(): String? {
|
||||||
|
val extras = com.droiddeck.launcher.session.ProtonExtras
|
||||||
|
while ((extras.prefetching || extras.installInProgress) && !SessionState.stopRequested) {
|
||||||
|
try { Thread.sleep(250) } catch (_: InterruptedException) { Thread.currentThread().interrupt(); return "interrupted" }
|
||||||
|
}
|
||||||
|
if (SessionState.stopRequested) return "cancelled"
|
||||||
|
if (!com.droiddeck.launcher.runtime.DesktopCatalog.ownProtonMissing(this)) return null
|
||||||
|
val cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
|
||||||
|
SessionState.installCancellation = cancellation
|
||||||
|
return try {
|
||||||
|
extras.install(this, extras.tools.first { it.id == extras.OWN }, cancellation) { label, percent ->
|
||||||
|
uiHandler.post { loading.percent = percent; loading.say(label, PROTON_LINES.topic, readable = true) }
|
||||||
|
}.also { if (it == null) com.droiddeck.launcher.session.Onboarding.recheck(this) }
|
||||||
|
} finally {
|
||||||
|
if (SessionState.installCancellation === cancellation) SessionState.installCancellation = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun surfaceCreated(holder: SurfaceHolder) {
|
override fun surfaceCreated(holder: SurfaceHolder) {
|
||||||
if (holder !== outputHolder()) return
|
if (holder !== outputHolder()) return
|
||||||
if (installingRuntime || SessionState.stopRequested || ended) return
|
if (installingRuntime || SessionState.stopRequested || ended) return
|
||||||
@@ -2995,16 +3025,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
|
|
||||||
private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this)
|
private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this)
|
||||||
|
|
||||||
private fun followScale(): Float {
|
private fun applyFollowChoice() {
|
||||||
val mode = displayMode()
|
val scale = SessionState.followScales.let { if (followPortrait()) it.second else it.first }
|
||||||
val choice = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), followPortrait())
|
SessionState.followScreen = scale != null
|
||||||
return com.droiddeck.launcher.session.SessionDisplay.followScale(choice) ?: 1f
|
SessionState.followScale = scale ?: 1f
|
||||||
}
|
|
||||||
|
|
||||||
private fun followChoice(): Boolean {
|
|
||||||
val mode = displayMode()
|
|
||||||
return com.droiddeck.launcher.session.SessionDisplay.isFollow(
|
|
||||||
SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), followPortrait()))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun applyFollowOrientation(config: android.content.res.Configuration) {
|
private fun applyFollowOrientation(config: android.content.res.Configuration) {
|
||||||
@@ -3018,6 +3042,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
SessionService.setActivityDisplay(this, sessionActivityDisplayId)
|
SessionService.setActivityDisplay(this, sessionActivityDisplayId)
|
||||||
}
|
}
|
||||||
cancelTouchGestures()
|
cancelTouchGestures()
|
||||||
|
applyFollowChoice()
|
||||||
applyFollowOrientation(newConfig)
|
applyFollowOrientation(newConfig)
|
||||||
applyNotchInset()
|
applyNotchInset()
|
||||||
applyUnfoldedControls()
|
applyUnfoldedControls()
|
||||||
@@ -3399,8 +3424,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
if (status == 0) SessionState.takeRelaunch()?.let { next ->
|
if (status == 0) SessionState.takeRelaunch()?.let { next ->
|
||||||
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))
|
next.putExtra(EXTRA_LINK_TASK, intent.getIntExtra(EXTRA_LINK_TASK, -1))
|
||||||
setIntent(next)
|
relaunch(next)
|
||||||
recreate()
|
|
||||||
return@runOnUiThread
|
return@runOnUiThread
|
||||||
}
|
}
|
||||||
showEnded(status, hint)
|
showEnded(status, hint)
|
||||||
@@ -3408,6 +3432,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
}, "session-end-hint").start()
|
}, "session-end-hint").start()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// recreate() keeps this window, and Compose content added to it afterwards never recomposes, so the
|
||||||
|
// loading screen of the next session stays up over a running session. A new instance gets its own window.
|
||||||
|
// This instance finishes first because the activity is singleTask and would otherwise take the intent itself.
|
||||||
|
private fun relaunch(next: Intent) {
|
||||||
|
closeAtOnce = true
|
||||||
|
super.finish()
|
||||||
|
startActivity(next)
|
||||||
|
overridePendingTransition(0, 0)
|
||||||
|
}
|
||||||
|
|
||||||
private fun showEnded(status: Int, hint: EndHint?) {
|
private fun showEnded(status: Int, hint: EndHint?) {
|
||||||
if (status == 0 && hint?.evenOnSuccess != true) {
|
if (status == 0 && hint?.evenOnSuccess != true) {
|
||||||
finish()
|
finish()
|
||||||
@@ -5162,10 +5196,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
private var sessionTouchDown = false
|
private var sessionTouchDown = false
|
||||||
private var screenTapsClick = true
|
private var screenTapsClick = true
|
||||||
|
|
||||||
private fun onScreenMouseButtonShown(): Boolean = listOfNotNull(
|
private fun onScreenLeftMouseButtonShown(): Boolean = listOfNotNull(
|
||||||
onScreenControls?.inputSurface, bottomInputControls?.inputSurface, unfoldedPanel?.inputSurface, unfoldedDeckSurface,
|
onScreenControls?.inputSurface, bottomInputControls?.inputSurface, unfoldedPanel?.inputSurface, unfoldedDeckSurface,
|
||||||
secondScreenPresentation?.controlsView, swappedInputSurface,
|
secondScreenPresentation?.controlsView, swappedInputSurface,
|
||||||
).any { it.isShown && inputProfile.showsMouseButton(it.inputRole, it.shownElements, stockInputProfile) }
|
).any { it.isShown && inputProfile.showsLeftMouseButton(it.inputRole, it.shownElements, stockInputProfile) }
|
||||||
|
|
||||||
override fun onTouchEvent(event: MotionEvent): Boolean = inSurfaceSpace(event) { handleTouch(event) }
|
override fun onTouchEvent(event: MotionEvent): Boolean = inSurfaceSpace(event) { handleTouch(event) }
|
||||||
|
|
||||||
@@ -5201,7 +5235,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
val snapshot = fingerTouchSnapshot(uiBlocking)
|
val snapshot = fingerTouchSnapshot(uiBlocking)
|
||||||
val route = com.droiddeck.launcher.input.TouchRouter.decide(snapshot)
|
val route = com.droiddeck.launcher.input.TouchRouter.decide(snapshot)
|
||||||
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
|
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
|
||||||
screenTapsClick = !onScreenMouseButtonShown()
|
screenTapsClick = !onScreenLeftMouseButtonShown()
|
||||||
if (::touchpad.isInitialized) touchpad.clicks = screenTapsClick
|
if (::touchpad.isInitialized) touchpad.clicks = screenTapsClick
|
||||||
if (::scrollTouch.isInitialized) scrollTouch.clicks = screenTapsClick
|
if (::scrollTouch.isInitialized) scrollTouch.clicks = screenTapsClick
|
||||||
}
|
}
|
||||||
@@ -6035,8 +6069,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
|||||||
Log.w(TAG, "ignoring agent start while session phase is ${SessionState.phase}")
|
Log.w(TAG, "ignoring agent start while session phase is ${SessionState.phase}")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
setIntent(intent)
|
relaunch(android.content.Intent(intent).setClass(this, SessionActivity::class.java))
|
||||||
recreate()
|
|
||||||
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)
|
||||||
|
|||||||
@@ -293,6 +293,7 @@ object DeviceReport {
|
|||||||
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
|
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
|
||||||
k("Avoid notch", SessionPrefs.avoidNotch(context))
|
k("Avoid notch", SessionPrefs.avoidNotch(context))
|
||||||
k("Return to launcher after a game", SessionPrefs.returnAfterGame(context))
|
k("Return to launcher after a game", SessionPrefs.returnAfterGame(context))
|
||||||
|
k("Valve Proton only when needed", SessionPrefs.valveProtonOnDemand(context))
|
||||||
k("Microphone", SessionPrefs.micEnabled(context))
|
k("Microphone", SessionPrefs.micEnabled(context))
|
||||||
k("On-screen controls", SessionPrefs.oscMode(context))
|
k("On-screen controls", SessionPrefs.oscMode(context))
|
||||||
k("Touch mode", SessionPrefs.touchMode(context))
|
k("Touch mode", SessionPrefs.touchMode(context))
|
||||||
|
|||||||
@@ -28,7 +28,9 @@ object DeviceSupport {
|
|||||||
com.droiddeck.launcher.gpu.GpuInfo.detect().family.name.startsWith("MALI"))
|
com.droiddeck.launcher.gpu.GpuInfo.detect().family.name.startsWith("MALI"))
|
||||||
}
|
}
|
||||||
|
|
||||||
fun bridgeUsable(): Boolean = !adreno() && !SystemVulkanDriver.isAvailable() && File("/dev/mali0").exists()
|
fun bridgeUsable(): Boolean = bridgeUsable(adreno(), SystemVulkanDriver.isAvailable())
|
||||||
|
|
||||||
|
internal fun bridgeUsable(adreno: Boolean, systemDriverReady: Boolean): Boolean = !adreno && !systemDriverReady
|
||||||
|
|
||||||
fun openDriverActive(context: Context): Boolean {
|
fun openDriverActive(context: Context): Boolean {
|
||||||
if (adreno()) return false
|
if (adreno()) return false
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ object AddedGames {
|
|||||||
val exeUncertain: Boolean = false,
|
val exeUncertain: Boolean = false,
|
||||||
val launchOptions: String = "",
|
val launchOptions: String = "",
|
||||||
val single: Boolean = false,
|
val single: Boolean = false,
|
||||||
|
val steamProgram: Boolean = true,
|
||||||
) {
|
) {
|
||||||
fun folderName(): String = folder.name
|
fun folderName(): String = folder.name
|
||||||
}
|
}
|
||||||
@@ -238,6 +239,7 @@ object AddedGames {
|
|||||||
for (entry in AddedExes.list(context)) {
|
for (entry in AddedExes.list(context)) {
|
||||||
val folder = File(entry.folder)
|
val folder = File(entry.folder)
|
||||||
if (folder.path in removed || !folder.isDirectory) continue
|
if (folder.path in removed || !folder.isDirectory) continue
|
||||||
|
if (StoreGameSidecar.read(folder)?.isInstalled == false) continue
|
||||||
scanGame(context, folder, out, single = entry, reuse = true)
|
scanGame(context, folder, out, single = entry, reuse = true)
|
||||||
}
|
}
|
||||||
for (folder in libraryDepotInstalls(context)) if (folder.path !in removed) scanGame(context, folder, out, reuse = true)
|
for (folder in libraryDepotInstalls(context)) if (folder.path !in removed) scanGame(context, folder, out, reuse = true)
|
||||||
@@ -336,7 +338,11 @@ object AddedGames {
|
|||||||
val owner = ownerFolder(app, exe)
|
val owner = ownerFolder(app, exe)
|
||||||
if (owner != null && owner.path !in SessionPrefs.removedAddedGames(app)) {
|
if (owner != null && owner.path !in SessionPrefs.removedAddedGames(app)) {
|
||||||
single(app, owner.path)?.takeIf { canonical(it.exe) == path }?.let {
|
single(app, owner.path)?.takeIf { canonical(it.exe) == path }?.let {
|
||||||
if (guestPath(app, exe) != null) AddedExes.put(app, AddedExes.Entry(owner.path, exe.path))
|
val keep = listOf(it.exe, exe).firstOrNull { f -> guestPath(app, f) != null }
|
||||||
|
if (keep != null) {
|
||||||
|
SessionPrefs.setAddedGameExe(app, owner.path, keep.path)
|
||||||
|
AddedExes.put(app, AddedExes.Entry(owner.path, keep.path))
|
||||||
|
}
|
||||||
return AddResult.Existing(it)
|
return AddResult.Existing(it)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -442,9 +448,9 @@ object AddedGames {
|
|||||||
val chosen = picked.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
|
val chosen = picked.takeIf { it.isNotEmpty() }?.let { File(it) }?.takeIf { it.isFile }
|
||||||
?: single?.takeIf { it.picked }?.let { File(it.exe) }?.takeIf { it.isFile }
|
?: single?.takeIf { it.picked }?.let { File(it.exe) }?.takeIf { it.isFile }
|
||||||
val found = chosen ?: sidecar?.exeFile(folder)?.takeIf { it.isFile } ?: candidates.firstOrNull() ?: return
|
val found = chosen ?: sidecar?.exeFile(folder)?.takeIf { it.isFile } ?: candidates.firstOrNull() ?: return
|
||||||
val epicLauncher = sidecar?.takeIf { it.store == Store.EPIC && (chosen == null || canonical(chosen) == canonical(it.exeFile(folder))) }
|
val storeLauncher = sidecar?.takeIf { chosen == null || canonical(chosen) == canonical(it.exeFile(folder)) }
|
||||||
?.launcherFile(folder)?.takeIf { it.isFile }
|
?.launcherFile(folder)?.takeIf { it.isFile }
|
||||||
val launch = epicLauncher ?: if (chosen == null) sidecar?.launcherFile(folder)?.takeIf { it.isFile } ?: found else found
|
val launch = storeLauncher ?: found
|
||||||
val foundGuest = guestPath(context, launch)
|
val foundGuest = guestPath(context, launch)
|
||||||
if (foundGuest == null) { Log.w(TAG, "${folder.name}: the session cannot see ${launch.path}"); return }
|
if (foundGuest == null) { Log.w(TAG, "${folder.name}: the session cannot see ${launch.path}"); return }
|
||||||
val autoName = sidecar?.title ?: identifiedName(folder, found) ?: folder.name
|
val autoName = sidecar?.title ?: identifiedName(folder, found) ?: folder.name
|
||||||
@@ -470,7 +476,13 @@ object AddedGames {
|
|||||||
val guestDir = SessionPrefs.addedGameStartIn(context, folder.path).takeIf { sidecar == null && it.isNotEmpty() }
|
val guestDir = SessionPrefs.addedGameStartIn(context, folder.path).takeIf { sidecar == null && it.isNotEmpty() }
|
||||||
?: sidecarDir
|
?: sidecarDir
|
||||||
?: guestPath(context, (if (adopted != null) adopted else launch).parentFile ?: folder) ?: return
|
?: guestPath(context, (if (adopted != null) adopted else launch).parentFile ?: folder) ?: return
|
||||||
val steamId = config?.let { steamRoute(it, appId) }
|
if (adopted == null && SessionPrefs.addedGameAdopted(context, folder.path, "Exe") == null &&
|
||||||
|
guestPath(context, folder)?.let { steamEditedTo(it, record, guestExe) } == true) {
|
||||||
|
SessionPrefs.setAddedGameAdopted(context, folder.path, "Exe", exe.path)
|
||||||
|
}
|
||||||
|
val steamProgram = candidates.firstOrNull()?.let { canonical(it) == canonical(exe) } ?: true ||
|
||||||
|
SessionPrefs.addedGameAdopted(context, folder.path, "Exe")?.let { canonical(File(it)) == canonical(exe) } == true
|
||||||
|
val steamId = config?.takeIf { steamProgram }?.let { steamRoute(it, appId) }
|
||||||
out.add(Game(folder, name, exe, guestExe, guestDir, appId,
|
out.add(Game(folder, name, exe, guestExe, guestDir, appId,
|
||||||
steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId,
|
steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId,
|
||||||
source = sidecar?.store?.id ?: Library.ADDED, storeId = sidecar?.id,
|
source = sidecar?.store?.id ?: Library.ADDED, storeId = sidecar?.id,
|
||||||
@@ -480,7 +492,7 @@ object AddedGames {
|
|||||||
sidecar.store == Store.UBISOFT -> com.droiddeck.launcher.stores.ubisoft.UbisoftConnect.launchOptions(context)
|
sidecar.store == Store.UBISOFT -> com.droiddeck.launcher.stores.ubisoft.UbisoftConnect.launchOptions(context)
|
||||||
else -> ""
|
else -> ""
|
||||||
},
|
},
|
||||||
single = single != null))
|
single = single != null, steamProgram = steamProgram))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -520,6 +532,11 @@ object AddedGames {
|
|||||||
return file.takeIf { inside && it.isFile }
|
return file.takeIf { inside && it.isFile }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun steamEditedTo(folderGuest: String, record: JSONObject?, guestExe: String): Boolean {
|
||||||
|
val steam = unquote(record?.optJSONObject("steam")?.optString("Exe"))
|
||||||
|
return steam == guestExe && steam != unquote(record?.optJSONObject("app")?.optString("Exe")) && steam.startsWith("$folderGuest/")
|
||||||
|
}
|
||||||
|
|
||||||
private fun unquote(value: String?): String = value.orEmpty().trim().trim('"')
|
private fun unquote(value: String?): String = value.orEmpty().trim().trim('"')
|
||||||
|
|
||||||
internal fun adoptSteamEdits(context: Context, folder: File, record: JSONObject) {
|
internal fun adoptSteamEdits(context: Context, folder: File, record: JSONObject) {
|
||||||
@@ -568,6 +585,7 @@ object AddedGames {
|
|||||||
.append(",\"seen\":").append(SessionPrefs.addedGameExeSeen(context, g.folder.path))
|
.append(",\"seen\":").append(SessionPrefs.addedGameExeSeen(context, g.folder.path))
|
||||||
if (g.launchOptions.isNotEmpty()) json.append(",\"launch\":").append(quote(g.launchOptions))
|
if (g.launchOptions.isNotEmpty()) json.append(",\"launch\":").append(quote(g.launchOptions))
|
||||||
if (g.source != Library.ADDED) json.append(",\"store\":").append(quote(g.source))
|
if (g.source != Library.ADDED) json.append(",\"store\":").append(quote(g.source))
|
||||||
|
if (!g.steamProgram) json.append(",\"route\":false")
|
||||||
val art = AddedGameArt.resolve(context, g)
|
val art = AddedGameArt.resolve(context, g)
|
||||||
val pieces = listOf("p" to art.portrait, "header" to art.header, "hero" to art.hero, "logo" to art.logo, "icon" to art.icon)
|
val pieces = listOf("p" to art.portrait, "header" to art.header, "hero" to art.hero, "logo" to art.logo, "icon" to art.icon)
|
||||||
.mapNotNull { (k, f) -> f?.let { file -> artGuestPath(context, file)?.let { k to it } } }
|
.mapNotNull { (k, f) -> f?.let { file -> artGuestPath(context, file)?.let { k to it } } }
|
||||||
|
|||||||
@@ -11,6 +11,10 @@ object GameLaunchIntent {
|
|||||||
|
|
||||||
fun accepts(action: String?): Boolean = action == Intent.ACTION_VIEW || action == ACTION || action == GAMENATIVE_ACTION
|
fun accepts(action: String?): Boolean = action == Intent.ACTION_VIEW || action == ACTION || action == GAMENATIVE_ACTION
|
||||||
|
|
||||||
|
fun replayed(intent: Intent, restored: Boolean, savedProcess: String?, process: String): Boolean =
|
||||||
|
!(intent.data?.scheme == "droiddeck" && intent.data?.host == "settings") &&
|
||||||
|
(intent.flags and Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY != 0 || restored && savedProcess != process)
|
||||||
|
|
||||||
fun read(context: Context, intent: Intent): GameRequest? = when (intent.action) {
|
fun read(context: Context, intent: Intent): GameRequest? = when (intent.action) {
|
||||||
Intent.ACTION_VIEW -> GameFiles.readIntent(context, intent)
|
Intent.ACTION_VIEW -> GameFiles.readIntent(context, intent)
|
||||||
ACTION, GAMENATIVE_ACTION -> readExtras(intent)
|
ACTION, GAMENATIVE_ACTION -> readExtras(intent)
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ object GamesFolderMigration {
|
|||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun run(context: Context) {
|
fun run(context: Context) {
|
||||||
|
repathInternalGuest(context)
|
||||||
val dirs = SessionPrefs.addedGamesDirs(context)
|
val dirs = SessionPrefs.addedGamesDirs(context)
|
||||||
if (dirs.isEmpty()) return
|
if (dirs.isEmpty()) return
|
||||||
val roots = legacyRoots(SessionPrefs.gameFolderBinds(context).map { it.first } + dirs)
|
val roots = legacyRoots(SessionPrefs.gameFolderBinds(context).map { it.first } + dirs)
|
||||||
@@ -58,12 +59,30 @@ object GamesFolderMigration {
|
|||||||
SessionPrefs.setGamesFoldersMigrated(context)
|
SessionPrefs.setGamesFoldersMigrated(context)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun repathInternalGuest(context: Context) {
|
||||||
|
val binds = SessionPrefs.gameFolderBinds(context)
|
||||||
|
if (binds.none { it.second == StoreInstallRoot.INTERNAL_GUEST }) return
|
||||||
|
val hosts = binds.map { it.first }
|
||||||
|
val roots = legacyRoots(hosts).associateBy { it.host.path }
|
||||||
|
val taken = binds.map { it.second }.filter { it != StoreInstallRoot.INTERNAL_GUEST }.toMutableSet()
|
||||||
|
SessionPrefs.setGameFolderBinds(context, binds.map { (host, guest) ->
|
||||||
|
if (guest != StoreInstallRoot.INTERNAL_GUEST) return@map host to guest
|
||||||
|
val base = roots.getValue(host).guest
|
||||||
|
var next = base
|
||||||
|
var n = 2
|
||||||
|
while (next in taken) next = "$base-${n++}"
|
||||||
|
taken.add(next)
|
||||||
|
host to next
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
internal fun legacyRoots(paths: List<String>): List<AddedGames.Root> {
|
internal fun legacyRoots(paths: List<String>): List<AddedGames.Root> {
|
||||||
val hosts = paths.distinct().map { File(it) }
|
val hosts = paths.distinct().map { File(it) }
|
||||||
val names = hosts.groupingBy { it.name.lowercase() }.eachCount()
|
val names = hosts.groupingBy { it.name.lowercase() }.eachCount()
|
||||||
return hosts.map { host ->
|
return hosts.map { host ->
|
||||||
val name = host.name.ifEmpty { "games" }
|
val name = host.name.ifEmpty { "games" }
|
||||||
val guestName = if ((names[name.lowercase()] ?: 0) > 1) name + "-" + "%08x".format(CRC32().apply { update(host.path.toByteArray()) }.value).take(4) else name
|
val clash = (names[name.lowercase()] ?: 0) > 1 || "${AddedGames.GUEST_DIR}/$name" == StoreInstallRoot.INTERNAL_GUEST
|
||||||
|
val guestName = if (clash) name + "-" + "%08x".format(CRC32().apply { update(host.path.toByteArray()) }.value).take(4) else name
|
||||||
AddedGames.Root(host, "${AddedGames.GUEST_DIR}/$guestName")
|
AddedGames.Root(host, "${AddedGames.GUEST_DIR}/$guestName")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,17 +7,21 @@ object SocNames {
|
|||||||
"SM8150" to "Snapdragon 855", "SM8250" to "Snapdragon 865", "SM8250-AC" to "Snapdragon 870",
|
"SM8150" to "Snapdragon 855", "SM8250" to "Snapdragon 865", "SM8250-AC" to "Snapdragon 870",
|
||||||
"SM8350" to "Snapdragon 888", "SM8450" to "Snapdragon 8 Gen 1", "SM8475" to "Snapdragon 8+ Gen 1",
|
"SM8350" to "Snapdragon 888", "SM8450" to "Snapdragon 8 Gen 1", "SM8475" to "Snapdragon 8+ Gen 1",
|
||||||
"SM8550" to "Snapdragon 8 Gen 2", "QCS8550" to "Snapdragon 8 Gen 2", "SM8650" to "Snapdragon 8 Gen 3",
|
"SM8550" to "Snapdragon 8 Gen 2", "QCS8550" to "Snapdragon 8 Gen 2", "SM8650" to "Snapdragon 8 Gen 3",
|
||||||
|
"SM8635" to "Snapdragon 8s Gen 3", "SM8735" to "Snapdragon 8s Gen 4",
|
||||||
"SM8750" to "Snapdragon 8 Elite", "SM8750P" to "Snapdragon 8 Elite",
|
"SM8750" to "Snapdragon 8 Elite", "SM8750P" to "Snapdragon 8 Elite",
|
||||||
"SM8850" to "Snapdragon 8 Elite Gen 5",
|
"SM8850" to "Snapdragon 8 Elite Gen 5",
|
||||||
"SM8975" to "Snapdragon 8 Elite Extreme Gen 6",
|
"SM8975" to "Snapdragon 8 Elite Extreme Gen 6",
|
||||||
"SM7325" to "Snapdragon 778G", "SM7450" to "Snapdragon 7 Gen 1", "SM7550" to "Snapdragon 7 Gen 3",
|
"SM7325" to "Snapdragon 778G", "SM7450" to "Snapdragon 7 Gen 1", "SM7550" to "Snapdragon 7 Gen 3",
|
||||||
|
"SM7675" to "Snapdragon 7+ Gen 3",
|
||||||
"SM6375" to "Snapdragon 695",
|
"SM6375" to "Snapdragon 695",
|
||||||
|
// Handheld parts: AYANEO Pocket FIT (SG8350P), Retroid Pocket Duo (CQ7790S).
|
||||||
|
"SG8350P" to "Snapdragon G3 Gen 3", "CQ7790S" to "Dragonwing Q-7790",
|
||||||
)
|
)
|
||||||
|
|
||||||
private val PLATFORMS = mapOf(
|
private val PLATFORMS = mapOf(
|
||||||
"msmnile" to "Snapdragon 855/860", "kona" to "Snapdragon 865/870", "lahaina" to "Snapdragon 888",
|
"msmnile" to "Snapdragon 855/860", "kona" to "Snapdragon 865/870", "lahaina" to "Snapdragon 888",
|
||||||
"taro" to "Snapdragon 8 Gen 1", "cape" to "Snapdragon 8+ Gen 1", "kalama" to "Snapdragon 8 Gen 2",
|
"taro" to "Snapdragon 8 Gen 1", "cape" to "Snapdragon 8+ Gen 1", "kalama" to "Snapdragon 8 Gen 2",
|
||||||
"pineapple" to "Snapdragon 8 Gen 3", "sun" to "Snapdragon 8 Elite",
|
"pineapple" to "Snapdragon 8 Gen 3", "sun" to "Snapdragon 8 Elite", "canoe" to "Snapdragon 8 Elite Gen 5",
|
||||||
)
|
)
|
||||||
|
|
||||||
fun model(prop: (String) -> String = GpuInfo::systemProperty): String {
|
fun model(prop: (String) -> String = GpuInfo::systemProperty): String {
|
||||||
@@ -30,8 +34,23 @@ object SocNames {
|
|||||||
|
|
||||||
internal fun normalizedModel(model: String): String = model.trim().uppercase().removePrefix("QTI ").trim()
|
internal fun normalizedModel(model: String): String = model.trim().uppercase().removePrefix("QTI ").trim()
|
||||||
|
|
||||||
fun name(model: String, platform: String = GpuInfo.systemProperty("ro.board.platform")): String? =
|
/**
|
||||||
MODELS[normalizedModel(model)] ?: PLATFORMS[platform.lowercase()]?.let { "$it family" }
|
* The exact model's name; the board platform's family only for an empty model or a phone "SM" part, since
|
||||||
|
* different chips share a platform (the Retroid Pocket Duo's CQ7790S and the Snapdragon 8 Elite are both "sun").
|
||||||
|
*/
|
||||||
|
fun name(model: String, platform: String = GpuInfo.systemProperty("ro.board.platform")): String? {
|
||||||
|
val m = normalizedModel(model)
|
||||||
|
MODELS[m]?.let { return it }
|
||||||
|
if (m.isNotEmpty() && !m.startsWith("SM")) return null
|
||||||
|
return PLATFORMS[platform.lowercase()]?.let { "$it family" }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Without label's platform-family guess: a rebadged chip such as the Duo's CQ7790S reports a platform it is not.
|
||||||
|
fun plainName(model: String = model(), maker: String = manufacturer()): String =
|
||||||
|
MODELS[normalizedModel(model)]?.let { "$it ($model)" } ?: "$maker $model".trim()
|
||||||
|
|
||||||
|
private fun manufacturer(): String =
|
||||||
|
if (Build.VERSION.SDK_INT >= 31) Build.SOC_MANUFACTURER.takeIf { it != Build.UNKNOWN }.orEmpty() else ""
|
||||||
|
|
||||||
fun label(model: String = model(), platform: String = GpuInfo.systemProperty("ro.board.platform")): String {
|
fun label(model: String = model(), platform: String = GpuInfo.systemProperty("ro.board.platform")): String {
|
||||||
val name = name(model, platform)
|
val name = name(model, platform)
|
||||||
|
|||||||
@@ -308,8 +308,7 @@ public final class TurnipDriver {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (chosen != null && !chosen.isEmpty()) {
|
if (chosen != null && !chosen.isEmpty()) {
|
||||||
if (SessionPrefs.GPU_DRIVERS_AUTO.equals(SessionPrefs.INSTANCE.gpuDriverMode(context))
|
if (SessionPrefs.INSTANCE.displayDriverFromAuto(context)
|
||||||
&& SessionPrefs.INSTANCE.gpuAutoInstalled(context).contains(chosen)
|
|
||||||
&& gpuDetector.get().getFamily() == GpuInfo.Family.A7XX_LOW) {
|
&& gpuDetector.get().getFamily() == GpuInfo.Family.A7XX_LOW) {
|
||||||
Log.i(TAG, "Auto-selected display driver does not cover Adreno 710/720/722; leaving the display driver to the system");
|
Log.i(TAG, "Auto-selected display driver does not cover Adreno 710/720/722; leaving the display driver to the system");
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package com.droiddeck.launcher.input
|
||||||
|
|
||||||
|
internal class AxisPacing(private val intervalMs: Long) {
|
||||||
|
private var lastWriteAt = 0L
|
||||||
|
private var written = false
|
||||||
|
private var heldUntil = NOT_HELD
|
||||||
|
|
||||||
|
fun dueAt(now: Long, axesOnly: Boolean): Long =
|
||||||
|
if (axesOnly && written && now - lastWriteAt < intervalMs) lastWriteAt + intervalMs else now
|
||||||
|
|
||||||
|
fun wrote(at: Long) {
|
||||||
|
lastWriteAt = at
|
||||||
|
written = true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun hold(due: Long): Boolean {
|
||||||
|
if (heldUntil != NOT_HELD) return false
|
||||||
|
heldUntil = due
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun release(now: Long): Boolean {
|
||||||
|
if (heldUntil == NOT_HELD || now < heldUntil) return false
|
||||||
|
heldUntil = NOT_HELD
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun cancel(): Boolean {
|
||||||
|
if (heldUntil == NOT_HELD) return false
|
||||||
|
heldUntil = NOT_HELD
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val NOT_HELD = Long.MIN_VALUE
|
||||||
|
|
||||||
|
@JvmStatic fun keepsMoving(before: Int, after: Int): Boolean = before == after || (before != 0 && after != 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,9 @@
|
|||||||
package com.droiddeck.launcher.input;
|
package com.droiddeck.launcher.input;
|
||||||
|
|
||||||
|
import android.os.Handler;
|
||||||
|
import android.os.HandlerThread;
|
||||||
|
import android.os.Process;
|
||||||
|
import android.os.SystemClock;
|
||||||
import android.util.Log;
|
import android.util.Log;
|
||||||
|
|
||||||
import java.io.File;
|
import java.io.File;
|
||||||
@@ -128,6 +132,16 @@ public class FakeInputWriter {
|
|||||||
|
|
||||||
private static final Object RING_LOCK = new Object();
|
private static final Object RING_LOCK = new Object();
|
||||||
private static final RingSlot[] RING_SLOTS = new RingSlot[MAX_FAKE_INPUT_SLOTS];
|
private static final RingSlot[] RING_SLOTS = new RingSlot[MAX_FAKE_INPUT_SLOTS];
|
||||||
|
private static final long AXIS_REPORT_INTERVAL_MS = 4;
|
||||||
|
|
||||||
|
private static final class Pacing {
|
||||||
|
static final Handler HANDLER;
|
||||||
|
static {
|
||||||
|
HandlerThread thread = new HandlerThread("pad-pacing", Process.THREAD_PRIORITY_DISPLAY);
|
||||||
|
thread.start();
|
||||||
|
HANDLER = new Handler(thread.getLooper());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
static {
|
static {
|
||||||
System.loadLibrary("sdnative");
|
System.loadLibrary("sdnative");
|
||||||
@@ -156,6 +170,9 @@ public class FakeInputWriter {
|
|||||||
private boolean hasChanges = false;
|
private boolean hasChanges = false;
|
||||||
private boolean pendingFullResend = false;
|
private boolean pendingFullResend = false;
|
||||||
private boolean forceResend = false;
|
private boolean forceResend = false;
|
||||||
|
private final AxisPacing axisPacing = new AxisPacing(AXIS_REPORT_INTERVAL_MS);
|
||||||
|
private final PadState pacedPad = new PadState();
|
||||||
|
private final Runnable pacedWrite = this::writePacedPad;
|
||||||
|
|
||||||
public FakeInputWriter(String fakeInputPath, int slot) {
|
public FakeInputWriter(String fakeInputPath, int slot) {
|
||||||
this.slot = slot;
|
this.slot = slot;
|
||||||
@@ -711,10 +728,12 @@ public class FakeInputWriter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void close() {
|
public synchronized void close() {
|
||||||
|
cancelPacedWrite();
|
||||||
isOpen = false;
|
isOpen = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void reset() {
|
public synchronized void reset() {
|
||||||
|
cancelPacedWrite();
|
||||||
if (!isOpen && !open())
|
if (!isOpen && !open())
|
||||||
return;
|
return;
|
||||||
|
|
||||||
@@ -822,6 +841,53 @@ public class FakeInputWriter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public synchronized void writePad(PadState state) {
|
public synchronized void writePad(PadState state) {
|
||||||
|
long now = SystemClock.uptimeMillis();
|
||||||
|
long due = axisPacing.dueAt(now, !pendingFullResend && onlyAxesMove(state));
|
||||||
|
if (due > now) {
|
||||||
|
pacedPad.copyFrom(state);
|
||||||
|
if (axisPacing.hold(due))
|
||||||
|
Pacing.HANDLER.postAtTime(pacedWrite, due);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
cancelPacedWrite();
|
||||||
|
writePadNow(state);
|
||||||
|
}
|
||||||
|
|
||||||
|
private synchronized void writePacedPad() {
|
||||||
|
if (axisPacing.release(SystemClock.uptimeMillis()))
|
||||||
|
writePadNow(pacedPad);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void cancelPacedWrite() {
|
||||||
|
if (axisPacing.cancel())
|
||||||
|
Pacing.HANDLER.removeCallbacks(pacedWrite);
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean onlyAxesMove(PadState state) {
|
||||||
|
for (int i = 0; i < 10; i++) {
|
||||||
|
if (prevButtonStates[i] != state.isDown(i))
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return prevButtonStates[SNAPSHOT_IDX_MODE] == state.isDown(PadState.GUIDE)
|
||||||
|
&& prevQam == state.isDown(PadState.QAM)
|
||||||
|
&& prevHatX == state.hatX() && prevHatY == state.hatY()
|
||||||
|
&& AxisPacing.keepsMoving(prevThumbLX, stickValue(state.leftX))
|
||||||
|
&& AxisPacing.keepsMoving(prevThumbLY, stickValue(state.leftY))
|
||||||
|
&& AxisPacing.keepsMoving(prevThumbRX, stickValue(state.rightX))
|
||||||
|
&& AxisPacing.keepsMoving(prevThumbRY, stickValue(state.rightY))
|
||||||
|
&& AxisPacing.keepsMoving(prevTriggerL, triggerValue(state.leftTrigger))
|
||||||
|
&& AxisPacing.keepsMoving(prevTriggerR, triggerValue(state.rightTrigger));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int stickValue(float value) {
|
||||||
|
return (int) (value * 32767);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int triggerValue(float value) {
|
||||||
|
return (int) (value * 255);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void writePadNow(PadState state) {
|
||||||
if (!isOpen && !open())
|
if (!isOpen && !open())
|
||||||
return;
|
return;
|
||||||
|
|
||||||
@@ -845,10 +911,10 @@ public class FakeInputWriter {
|
|||||||
hasChanges = true;
|
hasChanges = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
int lx = (int) (state.leftX * 32767);
|
int lx = stickValue(state.leftX);
|
||||||
int ly = (int) (state.leftY * 32767);
|
int ly = stickValue(state.leftY);
|
||||||
int rx = (int) (state.rightX * 32767);
|
int rx = stickValue(state.rightX);
|
||||||
int ry = (int) (state.rightY * 32767);
|
int ry = stickValue(state.rightY);
|
||||||
|
|
||||||
if (forceResend || lx != prevThumbLX) {
|
if (forceResend || lx != prevThumbLX) {
|
||||||
prevThumbLX = lx;
|
prevThumbLX = lx;
|
||||||
@@ -867,8 +933,8 @@ public class FakeInputWriter {
|
|||||||
writeEvent(EV_ABS, ABS_RY, ry);
|
writeEvent(EV_ABS, ABS_RY, ry);
|
||||||
}
|
}
|
||||||
|
|
||||||
int tl = (int) (state.leftTrigger * 255);
|
int tl = triggerValue(state.leftTrigger);
|
||||||
int tr = (int) (state.rightTrigger * 255);
|
int tr = triggerValue(state.rightTrigger);
|
||||||
if (forceResend || tl != prevTriggerL) {
|
if (forceResend || tl != prevTriggerL) {
|
||||||
prevTriggerL = tl;
|
prevTriggerL = tl;
|
||||||
writeEvent(EV_ABS, ABS_BRAKE, tl);
|
writeEvent(EV_ABS, ABS_BRAKE, tl);
|
||||||
@@ -895,6 +961,8 @@ public class FakeInputWriter {
|
|||||||
if (!flushBuffer()) {
|
if (!flushBuffer()) {
|
||||||
Log.e(TAG, "Gamepad write error: fake input mmap ring unavailable");
|
Log.e(TAG, "Gamepad write error: fake input mmap ring unavailable");
|
||||||
pendingFullResend = true;
|
pendingFullResend = true;
|
||||||
|
} else {
|
||||||
|
axisPacing.wrote(SystemClock.uptimeMillis());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
forceResend = false;
|
forceResend = false;
|
||||||
|
|||||||
@@ -53,14 +53,14 @@ data class InputProfile(
|
|||||||
fun elementClickAction(role: InputRole, element: InputSurfaceElement): InputAction = clicks[role]?.get(element.id)
|
fun elementClickAction(role: InputRole, element: InputSurfaceElement): InputAction = clicks[role]?.get(element.id)
|
||||||
?: defaultElementClick(element, elementAction(role, element.id, element.control)) { action(role, it) }
|
?: defaultElementClick(element, elementAction(role, element.id, element.control)) { action(role, it) }
|
||||||
|
|
||||||
fun showsMouseButton(role: InputRole, shown: List<InputSurfaceElement>, stock: InputProfile): Boolean = shown.any { element ->
|
fun showsLeftMouseButton(role: InputRole, shown: List<InputSurfaceElement>, stock: InputProfile): Boolean = shown.any { element ->
|
||||||
val action = elementAction(role, element.id, element.control).takeIf {
|
val action = elementAction(role, element.id, element.control).takeIf {
|
||||||
elements[role]?.get(element.id) != stock.elements[role]?.get(element.id) || it != stock.elementAction(role, element.id, element.control)
|
elements[role]?.get(element.id) != stock.elements[role]?.get(element.id) || it != stock.elementAction(role, element.id, element.control)
|
||||||
}
|
}
|
||||||
val click = elementClickAction(role, element).takeIf {
|
val click = elementClickAction(role, element).takeIf {
|
||||||
clicks[role]?.get(element.id) != stock.clicks[role]?.get(element.id) || it != stock.elementClickAction(role, element)
|
clicks[role]?.get(element.id) != stock.clicks[role]?.get(element.id) || it != stock.elementClickAction(role, element)
|
||||||
}
|
}
|
||||||
listOfNotNull(action, click).any { it is InputAction.MouseButton && it.validFor(element.control) }
|
listOfNotNull(action, click).any { it is InputAction.MouseButton && it.code == PointerGestures.BTN_LEFT }
|
||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
|
|||||||
@@ -273,7 +273,8 @@ public final class PadBridge {
|
|||||||
static boolean isSystemVirtualInputName(String name) {
|
static boolean isSystemVirtualInputName(String name) {
|
||||||
if (name == null) return false;
|
if (name == null) return false;
|
||||||
String lower = name.trim().toLowerCase(java.util.Locale.ROOT);
|
String lower = name.trim().toLowerCase(java.util.Locale.ROOT);
|
||||||
return lower.startsWith("uinput-") || lower.startsWith("uinput_");
|
// Xiaomi's "ui-input-xiaomi" is a system uinput device that also reports gamepad sources.
|
||||||
|
return lower.startsWith("uinput-") || lower.startsWith("uinput_") || lower.equals("ui-input-xiaomi");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static boolean isFromController(InputDevice device) {
|
public static boolean isFromController(InputDevice device) {
|
||||||
|
|||||||
@@ -207,7 +207,8 @@ object BattleNet {
|
|||||||
val taken = HashSet<File>()
|
val taken = HashSet<File>()
|
||||||
fun options(title: Title, folder: File) = listOfNotNull(folder, title.flavor?.let { File(folder, it) }?.takeIf { it.isDirectory })
|
fun options(title: Title, folder: File) = listOfNotNull(folder, title.flavor?.let { File(folder, it) }?.takeIf { it.isDirectory })
|
||||||
for ((code, game) in games) {
|
for ((code, game) in games) {
|
||||||
val keep = saved[code]?.let(::File)?.takeIf { it in options(game.first, game.second) && it !in taken } ?: continue
|
val want = saved[code]?.let { runCatching { File(it).canonicalFile }.getOrNull() } ?: continue
|
||||||
|
val keep = options(game.first, game.second).firstOrNull { runCatching { it.canonicalFile }.getOrNull() == want }?.takeIf { it !in taken } ?: continue
|
||||||
out[code] = keep
|
out[code] = keep
|
||||||
taken.add(keep)
|
taken.add(keep)
|
||||||
}
|
}
|
||||||
@@ -244,6 +245,14 @@ object BattleNet {
|
|||||||
"/" + rootfs.relativize(resolved).joinToString("/")
|
"/" + rootfs.relativize(resolved).joinToString("/")
|
||||||
}
|
}
|
||||||
}.trimEnd('/')
|
}.trimEnd('/')
|
||||||
|
if (mapped?.startsWith("/") == true) {
|
||||||
|
val rootfs = LinuxRuntime.rootDir(context)
|
||||||
|
runCatching {
|
||||||
|
val home = rootfs.canonicalFile.toPath()
|
||||||
|
val host = File("$target/$relative").canonicalFile.toPath()
|
||||||
|
if (host.startsWith(home)) File(rootfs, home.relativize(host).toString()) else null
|
||||||
|
}.getOrNull()?.let { return it }
|
||||||
|
}
|
||||||
return com.droiddeck.launcher.frontend.AddedGames.hostPath(context, "$target/$relative")
|
return com.droiddeck.launcher.frontend.AddedGames.hostPath(context, "$target/$relative")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -436,6 +436,7 @@ object BwrapSpawner {
|
|||||||
"DDNATV_ROOT" to sandbox,
|
"DDNATV_ROOT" to sandbox,
|
||||||
"DDNATV_EXEC" to NativeGuest.execLoader.orEmpty(),
|
"DDNATV_EXEC" to NativeGuest.execLoader.orEmpty(),
|
||||||
"DDNATV_LINK_ROOT" to rootfs.path,
|
"DDNATV_LINK_ROOT" to rootfs.path,
|
||||||
|
"DDNATV_REAL_EXE" to program.path,
|
||||||
"DDNATV_BINDS" to plan.binds.joinToString("|") { "${it.host}:${it.guest}" },
|
"DDNATV_BINDS" to plan.binds.joinToString("|") { "${it.host}:${it.guest}" },
|
||||||
"DDNATV_HOSTNAME" to SessionPrefs.guestHostname(context),
|
"DDNATV_HOSTNAME" to SessionPrefs.guestHostname(context),
|
||||||
"LD_LIBRARY_PATH" to SANDBOX_LIB_DIRS.map(::host).filter { it.isDirectory }.joinToString(":") { it.path },
|
"LD_LIBRARY_PATH" to SANDBOX_LIB_DIRS.map(::host).filter { it.isDirectory }.joinToString(":") { it.path },
|
||||||
|
|||||||
@@ -90,13 +90,16 @@ object CurseForgeApp {
|
|||||||
return out;
|
return out;
|
||||||
})()"""
|
})()"""
|
||||||
|
|
||||||
internal fun expression(service: String, method: String, args: JSONArray?, pick: String = "r => r"): String {
|
private val CORE = JSONObject.quote("CoreService")
|
||||||
|
|
||||||
|
internal fun expression(service: String, method: String, args: JSONArray?, pick: String = "r => r", connect: Boolean = true): String {
|
||||||
val name = JSONObject.quote(method)
|
val name = JSONObject.quote(method)
|
||||||
val run = if (args == null) "true" else "($pick)(await s[$name](...$args))"
|
val run = if (args == null) "true" else "($pick)(await s[$name](...$args))"
|
||||||
val key = JSONObject.quote(service)
|
val key = JSONObject.quote(service)
|
||||||
|
val link = if (connect && args != null) "const c = m[$CORE]; if (!c || typeof c.connect !== 'function') return { missing: true }; await c.connect(); " else ""
|
||||||
val inner = "(async () => { let m = globalThis.$CACHE; if (!m || !m[$key]) m = globalThis.$CACHE = $SERVICES; const s = m[$key]; " +
|
val inner = "(async () => { let m = globalThis.$CACHE; if (!m || !m[$key]) m = globalThis.$CACHE = $SERVICES; const s = m[$key]; " +
|
||||||
"if (!s || typeof s[$name] !== 'function') return { missing: true }; " +
|
"if (!s || typeof s[$name] !== 'function') return { missing: true }; " +
|
||||||
"return { value: $run }; })()"
|
link + "return { value: $run }; })()"
|
||||||
return "(() => { const w = require('electron').BrowserWindow.getAllWindows()" +
|
return "(() => { const w = require('electron').BrowserWindow.getAllWindows()" +
|
||||||
".find(w => !w.isDestroyed() && w.webContents.getURL().includes('desktop.html')); " +
|
".find(w => !w.isDestroyed() && w.webContents.getURL().includes('desktop.html')); " +
|
||||||
"if (!w) return JSON.stringify({ missing: true }); " +
|
"if (!w) return JSON.stringify({ missing: true }); " +
|
||||||
@@ -173,7 +176,6 @@ object CurseForgeApp {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private val holds = ConcurrentHashMap<String, AtomicBoolean>()
|
private val holds = ConcurrentHashMap<String, AtomicBoolean>()
|
||||||
private val connected = ConcurrentHashMap.newKeySet<String>()
|
|
||||||
|
|
||||||
private fun lines(context: Context, argv: List<String>): List<String> {
|
private fun lines(context: Context, argv: List<String>): List<String> {
|
||||||
val out = ArrayList<String>()
|
val out = ArrayList<String>()
|
||||||
@@ -181,8 +183,8 @@ object CurseForgeApp {
|
|||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r"): Any? =
|
private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r", connect: Boolean = true): Any? =
|
||||||
unwrap(lastJson(lines(context, evalArgv(inspector, expression(service, method, args, pick), timeoutMs))) ?: throw Failure("CurseForge gave no answer"))
|
unwrap(lastJson(lines(context, evalArgv(inspector, expression(service, method, args, pick, connect), timeoutMs))) ?: throw Failure("CurseForge gave no answer"))
|
||||||
|
|
||||||
private sealed class Launch {
|
private sealed class Launch {
|
||||||
class Url(val inspector: String) : Launch()
|
class Url(val inspector: String) : Launch()
|
||||||
@@ -234,24 +236,16 @@ object CurseForgeApp {
|
|||||||
hold.set(true)
|
hold.set(true)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") }
|
if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true", connect = false) }
|
||||||
hold.set(true)
|
hold.set(true)
|
||||||
inspector?.let(connected::remove)
|
|
||||||
if (holds.remove(dir, hold)) runCatching { lines(context, helperArgv("stop", dir)) }
|
if (holds.remove(dir, hold)) runCatching { lines(context, helperArgv("stop", dir)) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun connect(context: Context, inspector: String) {
|
|
||||||
if (inspector in connected) return
|
|
||||||
call(context, inspector, "CoreService", "connect", JSONArray(), 120_000, "r => true")
|
|
||||||
connected += inspector
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun instances(context: Context, inspector: String): Any? =
|
private fun instances(context: Context, inspector: String): Any? =
|
||||||
call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 30_000,
|
call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 120_000,
|
||||||
"r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))")
|
"r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))")
|
||||||
|
|
||||||
fun instance(context: Context, inspector: String, root: String, flavorDir: String): String {
|
fun instance(context: Context, inspector: String, root: String, flavorDir: String): String {
|
||||||
connect(context, inspector)
|
|
||||||
instanceFor(instances(context, inspector), flavorDir, null)?.let { return it }
|
instanceFor(instances(context, inspector), flavorDir, null)?.let { return it }
|
||||||
val detected = call(context, inspector, "GameDetectionAppService", "detectGameFromPath", JSONArray().put(root).put(WOW), 60_000) as? JSONObject
|
val detected = call(context, inspector, "GameDetectionAppService", "detectGameFromPath", JSONArray().put(root).put(WOW), 60_000) as? JSONObject
|
||||||
return instanceFor(instances(context, inspector), flavorDir, detected?.optString("gameInstanceGuid")) ?: throw Failure("CurseForge did not find $flavorDir")
|
return instanceFor(instances(context, inspector), flavorDir, detected?.optString("gameInstanceGuid")) ?: throw Failure("CurseForge did not find $flavorDir")
|
||||||
@@ -261,7 +255,6 @@ object CurseForgeApp {
|
|||||||
parseSearch(call(context, inspector, "ProjectAppService", "search", JSONArray().put(searchRequest(guid, text, sort, page)), 60_000))
|
parseSearch(call(context, inspector, "ProjectAppService", "search", JSONArray().put(searchRequest(guid, text, sort, page)), 60_000))
|
||||||
|
|
||||||
fun projects(context: Context, inspector: String, guid: String, rescan: Boolean = false): List<Project> {
|
fun projects(context: Context, inspector: String, guid: String, rescan: Boolean = false): List<Project> {
|
||||||
connect(context, inspector)
|
|
||||||
if (rescan) call(context, inspector, "GameDetectionAppService", "scanGameInstance", JSONArray().put(guid), 120_000)
|
if (rescan) call(context, inspector, "GameDetectionAppService", "scanGameInstance", JSONArray().put(guid), 120_000)
|
||||||
return parseProjects(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, PROJECTS))
|
return parseProjects(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, PROJECTS))
|
||||||
}
|
}
|
||||||
@@ -283,19 +276,16 @@ object CurseForgeApp {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun install(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
|
fun install(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
|
||||||
connect(context, inspector)
|
|
||||||
if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return null
|
if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return null
|
||||||
return settle(context, inspector, guid) { list -> list.any { it.id == projectId } }
|
return settle(context, inspector, guid) { list -> list.any { it.id == projectId } }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun update(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
|
fun update(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
|
||||||
connect(context, inspector)
|
|
||||||
if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return null
|
if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return null
|
||||||
return settle(context, inspector, guid) { list -> list.any { it.id == projectId && !it.update } }
|
return settle(context, inspector, guid) { list -> list.any { it.id == projectId && !it.update } }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun uninstall(context: Context, inspector: String, guid: String, project: Project): List<Project>? {
|
fun uninstall(context: Context, inspector: String, guid: String, project: Project): List<Project>? {
|
||||||
connect(context, inspector)
|
|
||||||
val failed = call(context, inspector, "InstalledProjectsAppService", "deleteMods", JSONArray().put(guid).put(JSONArray().put(project.installedModId)), 120_000) as? JSONArray
|
val failed = call(context, inspector, "InstalledProjectsAppService", "deleteMods", JSONArray().put(guid).put(JSONArray().put(project.installedModId)), 120_000) as? JSONArray
|
||||||
if (failed == null || failed.length() > 0) return null
|
if (failed == null || failed.length() > 0) return null
|
||||||
return settle(context, inspector, guid) { list -> list.none { it.id == project.id } }
|
return settle(context, inspector, guid) { list -> list.none { it.id == project.id } }
|
||||||
|
|||||||
@@ -109,9 +109,15 @@ object DesktopCatalog {
|
|||||||
FileUtils.readString(marker(context, id))?.trim()?.takeIf { it.isNotEmpty() }
|
FileUtils.readString(marker(context, id))?.trim()?.takeIf { it.isNotEmpty() }
|
||||||
|
|
||||||
fun protonSeedNeeded(context: Context): Boolean =
|
fun protonSeedNeeded(context: Context): Boolean =
|
||||||
installed(context, PROTON_SEED_ID) == null &&
|
if (com.droiddeck.launcher.session.SessionPrefs.ownProtonFirst(context)) ownProtonMissing(context)
|
||||||
|
else installed(context, PROTON_SEED_ID) == null &&
|
||||||
!File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/appmanifest_4427310.acf").isFile
|
!File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/appmanifest_4427310.acf").isFile
|
||||||
|
|
||||||
|
fun ownProtonMissing(context: Context): Boolean {
|
||||||
|
val extras = com.droiddeck.launcher.session.ProtonExtras
|
||||||
|
return extras.installedAll(context, extras.tools.first { it.id == extras.OWN }).isEmpty()
|
||||||
|
}
|
||||||
|
|
||||||
const val DESKTOP_ID = "desktop-kde"
|
const val DESKTOP_ID = "desktop-kde"
|
||||||
const val EMULATORS_ID = "emulators"
|
const val EMULATORS_ID = "emulators"
|
||||||
private const val EMULATORS_SCRIPT = "/usr/local/bin/droiddeck-emulators"
|
private const val EMULATORS_SCRIPT = "/usr/local/bin/droiddeck-emulators"
|
||||||
|
|||||||
@@ -199,6 +199,7 @@ public final class LinuxRuntime {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public static List<String> prootPrefix(Context context, File root, String cwd, boolean fakeRoot) {
|
public static List<String> prootPrefix(Context context, File root, String cwd, boolean fakeRoot) {
|
||||||
|
NativeGuest.relinkAfterProot(root);
|
||||||
List<String> cmd = new ArrayList<>();
|
List<String> cmd = new ArrayList<>();
|
||||||
cmd.addAll(com.droiddeck.launcher.core.HostProcess.dataExecutable(prootBinary(context).getPath()));
|
cmd.addAll(com.droiddeck.launcher.core.HostProcess.dataExecutable(prootBinary(context).getPath()));
|
||||||
cmd.add("--kill-on-exit");
|
cmd.add("--kill-on-exit");
|
||||||
|
|||||||
@@ -73,9 +73,10 @@ object NativeGuest {
|
|||||||
fun libraryPath(root: File): String = LIB_DIRS.joinToString(":") { File(root, it).path }
|
fun libraryPath(root: File): String = LIB_DIRS.joinToString(":") { File(root, it).path }
|
||||||
|
|
||||||
/** Environment every native process starts with; a guest `env -i` is re-seeded by the hook. */
|
/** Environment every native process starts with; a guest `env -i` is re-seeded by the hook. */
|
||||||
fun environment(root: File, preload: List<String> = emptyList()): Map<String, String> = linkedMapOf(
|
fun environment(root: File, program: String, preload: List<String> = emptyList()): Map<String, String> = linkedMapOf(
|
||||||
"DDNATV_ROOT" to root.path,
|
"DDNATV_ROOT" to root.path,
|
||||||
"DDNATV_EXEC" to execLoader.orEmpty(),
|
"DDNATV_EXEC" to execLoader.orEmpty(),
|
||||||
|
"DDNATV_REAL_EXE" to hostProgram(root, program).path,
|
||||||
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
|
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
|
||||||
).filterValues { it.isNotEmpty() }
|
).filterValues { it.isNotEmpty() }
|
||||||
|
|
||||||
@@ -85,17 +86,20 @@ object NativeGuest {
|
|||||||
*/
|
*/
|
||||||
fun command(root: File, program: String, args: List<String>, libraryPath: String = libraryPath(root)): List<String> {
|
fun command(root: File, program: String, args: List<String>, libraryPath: String = libraryPath(root)): List<String> {
|
||||||
val loader = checkNotNull(loader(root)) { "no glibc loader in ${root.path}" }
|
val loader = checkNotNull(loader(root)) { "no glibc loader in ${root.path}" }
|
||||||
val host = File(root, program.removePrefix("/"))
|
val host = hostProgram(root, program)
|
||||||
val launch = listOf(loader.path, "--library-path", libraryPath, "--argv0", host.name, host.path) + args
|
val launch = listOf(loader.path, "--library-path", libraryPath, "--argv0", host.name, host.path) + args
|
||||||
return simulator(root)?.let { it + launch } ?: (execPrefix(loader.path) + launch)
|
return simulator(root)?.let { it + launch } ?: (execPrefix(loader.path) + launch)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun hostProgram(root: File, program: String): File = File(root, program.removePrefix("/"))
|
||||||
|
|
||||||
/** The environment of the session process: the hook's root, the mounts proot used to make, the preload list. */
|
/** The environment of the session process: the hook's root, the mounts proot used to make, the preload list. */
|
||||||
fun sessionEnvironment(root: File, binds: List<String>, hostname: String? = null): Map<String, String> {
|
fun sessionEnvironment(root: File, binds: List<String>, program: String, hostname: String? = null): Map<String, String> {
|
||||||
val preload = preloadList(root)
|
val preload = preloadList(root)
|
||||||
return linkedMapOf(
|
return linkedMapOf(
|
||||||
"DDNATV_ROOT" to root.path,
|
"DDNATV_ROOT" to root.path,
|
||||||
"DDNATV_EXEC" to execLoader.orEmpty(),
|
"DDNATV_EXEC" to execLoader.orEmpty(),
|
||||||
|
"DDNATV_REAL_EXE" to hostProgram(root, program).path,
|
||||||
"DDNATV_HOSTNAME" to hostname.orEmpty(),
|
"DDNATV_HOSTNAME" to hostname.orEmpty(),
|
||||||
"DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" },
|
"DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" },
|
||||||
"DDNATV_PRELOAD" to preload.joinToString(":"),
|
"DDNATV_PRELOAD" to preload.joinToString(":"),
|
||||||
@@ -114,7 +118,7 @@ object NativeGuest {
|
|||||||
.also { builder ->
|
.also { builder ->
|
||||||
builder.environment().apply {
|
builder.environment().apply {
|
||||||
remove("LD_AUDIT")
|
remove("LD_AUDIT")
|
||||||
putAll(sessionEnvironment(root, binds, SessionPrefs.guestHostname(context)))
|
putAll(sessionEnvironment(root, binds, guest.first(), SessionPrefs.guestHostname(context)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -165,8 +169,15 @@ object NativeGuest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private const val RELINK_STAMP = "etc/droiddeck/native-symlinks"
|
||||||
|
|
||||||
|
@JvmStatic
|
||||||
|
fun relinkAfterProot(root: File) {
|
||||||
|
File(root, RELINK_STAMP).delete()
|
||||||
|
}
|
||||||
|
|
||||||
private val HOST_LINK_TARGETS = listOf("/proc", "/dev", "/sys", "/sdcard", "/storage", "/data", "/system", "/vendor", "/apex",
|
private val HOST_LINK_TARGETS = listOf("/proc", "/dev", "/sys", "/sdcard", "/storage", "/data", "/system", "/vendor", "/apex",
|
||||||
"/system_ext", "/product", "/odm", "/linkerconfig", "/mnt")
|
"/system_ext", "/product", "/odm", "/linkerconfig", "/mnt", "/root/Storage")
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Symbolic links the kernel follows by itself (ld.so, Steam, anything that skips the hook) read
|
* Symbolic links the kernel follows by itself (ld.so, Steam, anything that skips the hook) read
|
||||||
@@ -174,9 +185,9 @@ object NativeGuest {
|
|||||||
* which reads the target inside the rootfs, so each is rewritten as a relative link, which
|
* which reads the target inside the rootfs, so each is rewritten as a relative link, which
|
||||||
* resolves the same way under proot and without it. Rerun when the runtime changes.
|
* resolves the same way under proot and without it. Rerun when the runtime changes.
|
||||||
*/
|
*/
|
||||||
fun relinkAbsoluteSymlinks(context: Context, root: File): Int {
|
fun relinkAbsoluteSymlinks(context: Context, root: File, commands: () -> Sequence<List<String>> = ::procCommands): Int {
|
||||||
val stamp = File(root, "etc/droiddeck/native-symlinks")
|
val stamp = File(root, RELINK_STAMP)
|
||||||
val version = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.installedVersion(context).orEmpty() + "/2"
|
val version = com.droiddeck.launcher.runtime.LinuxRuntimeInstaller.installedVersion(context).orEmpty() + "/3"
|
||||||
if (stamp.isFile && stamp.readText() == version) return 0
|
if (stamp.isFile && stamp.readText() == version) return 0
|
||||||
val rootPath = root.toPath()
|
val rootPath = root.toPath()
|
||||||
var rewritten = 0
|
var rewritten = 0
|
||||||
@@ -202,11 +213,20 @@ object NativeGuest {
|
|||||||
|
|
||||||
override fun visitFileFailed(file: java.nio.file.Path, exc: java.io.IOException) = java.nio.file.FileVisitResult.CONTINUE
|
override fun visitFileFailed(file: java.nio.file.Path, exc: java.io.IOException) = java.nio.file.FileVisitResult.CONTINUE
|
||||||
})
|
})
|
||||||
stamp.parentFile?.mkdirs()
|
if (!prootRunning(LinuxRuntime.prootBinary(context).path, commands())) {
|
||||||
stamp.writeText(version)
|
stamp.parentFile?.mkdirs()
|
||||||
|
stamp.writeText(version)
|
||||||
|
}
|
||||||
return rewritten
|
return rewritten
|
||||||
}
|
}
|
||||||
|
|
||||||
|
internal fun prootRunning(proot: String, commands: Sequence<List<String>>): Boolean =
|
||||||
|
commands.any { args -> args.take(2).any { it == proot } }
|
||||||
|
|
||||||
|
private fun procCommands(): Sequence<List<String>> = (File("/proc").listFiles() ?: emptyArray()).asSequence()
|
||||||
|
.filter { it.name.all(Char::isDigit) }
|
||||||
|
.mapNotNull { runCatching { File(it, "cmdline").readText().split('\u0000') }.getOrNull() }
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The guest path that host path [target] stands for in a session with [binds] ("src:dst"), or null
|
* The guest path that host path [target] stands for in a session with [binds] ("src:dst"), or null
|
||||||
* when it is a guest path already: the rootfs, or the longest mount source holding it (the first
|
* when it is a guest path already: the rootfs, or the longest mount source holding it (the first
|
||||||
@@ -278,7 +298,7 @@ object NativeGuest {
|
|||||||
builder.directory(File(root, cwd.removePrefix("/")).takeIf { it.isDirectory } ?: root)
|
builder.directory(File(root, cwd.removePrefix("/")).takeIf { it.isDirectory } ?: root)
|
||||||
builder.environment().apply {
|
builder.environment().apply {
|
||||||
clear()
|
clear()
|
||||||
putAll(environment(root, preload))
|
putAll(environment(root, program, preload))
|
||||||
putAll(env)
|
putAll(env)
|
||||||
}
|
}
|
||||||
return builder
|
return builder
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ class RuntimeInstallService : Service() {
|
|||||||
if (intent?.action == ACTION_PACKAGE) return holdPackage(startId)
|
if (intent?.action == ACTION_PACKAGE) return holdPackage(startId)
|
||||||
val removal = intent?.action == ACTION_REMOVE
|
val removal = intent?.action == ACTION_REMOVE
|
||||||
val release = intent?.let(::releaseFrom)
|
val release = intent?.let(::releaseFrom)
|
||||||
startForeground(NOTIFICATION_ID, notification(getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else if (removal) R.string.rtinst_removing else R.string.user_apps_starting), -1))
|
val foreground = enterForeground(notification(getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else if (removal) R.string.rtinst_removing else R.string.user_apps_starting), -1))
|
||||||
if (release == null && !removal) {
|
if (release == null && !removal) {
|
||||||
stopSelf(startId)
|
stopSelf(startId)
|
||||||
return START_NOT_STICKY
|
return START_NOT_STICKY
|
||||||
@@ -31,7 +31,7 @@ class RuntimeInstallService : Service() {
|
|||||||
val manager = getSystemService(NotificationManager::class.java)
|
val manager = getSystemService(NotificationManager::class.java)
|
||||||
var shown = ""
|
var shown = ""
|
||||||
val progress = LinuxRuntimeInstaller.ProgressListener { stage, percent ->
|
val progress = LinuxRuntimeInstaller.ProgressListener { stage, percent ->
|
||||||
if ("$stage:$percent" != shown) {
|
if (foreground && "$stage:$percent" != shown) {
|
||||||
shown = "$stage:$percent"
|
shown = "$stage:$percent"
|
||||||
manager?.notify(NOTIFICATION_ID, notification(stage, percent))
|
manager?.notify(NOTIFICATION_ID, notification(stage, percent))
|
||||||
}
|
}
|
||||||
@@ -46,7 +46,10 @@ class RuntimeInstallService : Service() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun holdPackage(startId: Int): Int {
|
private fun holdPackage(startId: Int): Int {
|
||||||
startForeground(NOTIFICATION_ID, notification(packageStage, packagePercent, packageTitle))
|
if (!enterForeground(notification(packageStage, packagePercent, packageTitle))) {
|
||||||
|
stopSelf(startId)
|
||||||
|
return START_NOT_STICKY
|
||||||
|
}
|
||||||
Thread({
|
Thread({
|
||||||
val manager = getSystemService(NotificationManager::class.java)
|
val manager = getSystemService(NotificationManager::class.java)
|
||||||
var shown = ""
|
var shown = ""
|
||||||
@@ -65,6 +68,15 @@ class RuntimeInstallService : Service() {
|
|||||||
return START_NOT_STICKY
|
return START_NOT_STICKY
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Android 12+ refuses a foreground start while the app is in the background; the work then goes on without the notification. */
|
||||||
|
private fun enterForeground(notification: Notification): Boolean = try {
|
||||||
|
startForeground(NOTIFICATION_ID, notification)
|
||||||
|
true
|
||||||
|
} catch (e: IllegalStateException) {
|
||||||
|
android.util.Log.w("RuntimeInstallService", "running without a foreground service: $e")
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
private fun notification(stage: String, percent: Int, title: String? = null): Notification {
|
private fun notification(stage: String, percent: Int, title: String? = null): Notification {
|
||||||
val manager = getSystemService(NotificationManager::class.java)
|
val manager = getSystemService(NotificationManager::class.java)
|
||||||
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, getString(R.string.setup_runtime),
|
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, getString(R.string.setup_runtime),
|
||||||
|
|||||||
@@ -328,7 +328,7 @@ object BottomDesktop {
|
|||||||
LinuxRuntime.commandWithBinds(context, current.root, binds, guest)
|
LinuxRuntime.commandWithBinds(context, current.root, binds, guest)
|
||||||
}
|
}
|
||||||
val environment = if (current.nativeUserland) {
|
val environment = if (current.nativeUserland) {
|
||||||
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, SessionPrefs.guestHostname(context))
|
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, guest.first(), SessionPrefs.guestHostname(context))
|
||||||
.map { (k, v) -> "$k=$v" }.toTypedArray()
|
.map { (k, v) -> "$k=$v" }.toTypedArray()
|
||||||
} else current.hostEnvironment
|
} else current.hostEnvironment
|
||||||
val line = command.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") }
|
val line = command.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") }
|
||||||
|
|||||||
@@ -88,8 +88,8 @@ object ComponentUpdater {
|
|||||||
logLines(context).mapNotNull { STAMP.find(it)?.groupValues?.get(1) }.maxOrNull() ?: "0"
|
logLines(context).mapNotNull { STAMP.find(it)?.groupValues?.get(1) }.maxOrNull() ?: "0"
|
||||||
|
|
||||||
private fun lineOf(context: Context, state: JSONObject, p: ComponentsManager.Proton, comp: String): ComponentUpdates.Line? {
|
private fun lineOf(context: Context, state: JSONObject, p: ComponentsManager.Proton, comp: String): ComponentUpdates.Line? {
|
||||||
if (!ComponentUpdates.follows(p) || !ComponentsManager.supports(p, comp)) return null
|
if (!ComponentUpdates.autoFollows(p, comp) || !ComponentsManager.supports(p, comp)) return null
|
||||||
if (comp == "fex") return ComponentUpdates.line("fex", false)
|
if (comp == "fex") return ComponentUpdates.fexLine(p)
|
||||||
val key = "${p.id}|${p.version}"
|
val key = "${p.id}|${p.version}"
|
||||||
val flavors = state.obj("flavors").obj(key)
|
val flavors = state.obj("flavors").obj(key)
|
||||||
val arm64ec = if (flavors.has(comp)) flavors.optBoolean(comp) else ComponentsManager.arm64ec(context, p, comp)?.also { flavors.put(comp, it) }
|
val arm64ec = if (flavors.has(comp)) flavors.optBoolean(comp) else ComponentsManager.arm64ec(context, p, comp)?.also { flavors.put(comp, it) }
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ object ComponentUpdates {
|
|||||||
const val BOOTED_SECONDS = 60L
|
const val BOOTED_SECONDS = 60L
|
||||||
const val FAILED_BOOTS_BEFORE_ROLLBACK = 2
|
const val FAILED_BOOTS_BEFORE_ROLLBACK = 2
|
||||||
|
|
||||||
data class Line(val key: String, val comp: String, val prefix: String)
|
data class Line(val key: String, val comp: String, val prefix: String, val release: String = ComponentsManager.DD_NIGHTLY)
|
||||||
|
|
||||||
val LINES = listOf(
|
val LINES = listOf(
|
||||||
Line("dxvk", "dxvk", "DD-dxvk-"),
|
Line("dxvk", "dxvk", "DD-dxvk-"),
|
||||||
@@ -21,12 +21,19 @@ object ComponentUpdates {
|
|||||||
Line("vkd3d", "vkd3d", "DD-vkd3d-proton-"),
|
Line("vkd3d", "vkd3d", "DD-vkd3d-proton-"),
|
||||||
Line("vkd3d-arm64ec", "vkd3d", "DD-vkd3d-proton-arm64ec-"),
|
Line("vkd3d-arm64ec", "vkd3d", "DD-vkd3d-proton-arm64ec-"),
|
||||||
Line("fex", "fex", "DD-FEXCore-"),
|
Line("fex", "fex", "DD-FEXCore-"),
|
||||||
|
Line("fex-bionic", "fex", "FEXCore-", ComponentsManager.DD_BIONIC),
|
||||||
)
|
)
|
||||||
|
|
||||||
private val OWN_PREFIX = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }.prefix
|
private val OWN_PREFIX = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }.prefix
|
||||||
|
|
||||||
fun follows(p: ComponentsManager.Proton): Boolean = !p.valve && p.dir.name.startsWith(OWN_PREFIX)
|
fun follows(p: ComponentsManager.Proton): Boolean = !p.valve && p.dir.name.startsWith(OWN_PREFIX)
|
||||||
|
|
||||||
|
fun autoFollows(p: ComponentsManager.Proton, comp: String): Boolean =
|
||||||
|
follows(p) || (comp == "fex" && !p.valve && ComponentsManager.bionicTool(p.dir.name))
|
||||||
|
|
||||||
|
fun fexLine(p: ComponentsManager.Proton): Line =
|
||||||
|
if (ComponentsManager.bionicTool(p.dir.name)) LINES.first { it.release == ComponentsManager.DD_BIONIC } else line("fex", false)
|
||||||
|
|
||||||
fun ownId(protonId: String): Boolean = protonId.startsWith(ComponentsManager.safeName(OWN_PREFIX))
|
fun ownId(protonId: String): Boolean = protonId.startsWith(ComponentsManager.safeName(OWN_PREFIX))
|
||||||
|
|
||||||
fun strays(
|
fun strays(
|
||||||
@@ -34,8 +41,8 @@ object ComponentUpdates {
|
|||||||
choices: Map<String, Map<String, ComponentsManager.Choice>>,
|
choices: Map<String, Map<String, ComponentsManager.Choice>>,
|
||||||
placed: Set<String>,
|
placed: Set<String>,
|
||||||
): List<Pair<ComponentsManager.Proton, String>> =
|
): List<Pair<ComponentsManager.Proton, String>> =
|
||||||
protons.filterNot(::follows).flatMap { p ->
|
protons.flatMap { p ->
|
||||||
choices[p.id].orEmpty().filter { (_, c) -> !c.auto && c.protonVersion == p.version && c.file in placed }.keys.map { p to it }
|
choices[p.id].orEmpty().filter { (comp, c) -> !autoFollows(p, comp) && !c.auto && c.protonVersion == p.version && c.file in placed }.keys.map { p to it }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun unseen(
|
fun unseen(
|
||||||
@@ -53,13 +60,14 @@ object ComponentUpdates {
|
|||||||
|
|
||||||
fun pick(items: List<ComponentsManager.CatalogItem>, line: Line, bad: Set<String>): ComponentsManager.CatalogItem? {
|
fun pick(items: List<ComponentsManager.CatalogItem>, line: Line, bad: Set<String>): ComponentsManager.CatalogItem? {
|
||||||
val newestBad = bad.filter { belongs(it, line) }.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a, b) }
|
val newestBad = bad.filter { belongs(it, line) }.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a, b) }
|
||||||
return items.filter { it.release == ComponentsManager.DD_NIGHTLY && it.comp == line.comp && belongs(it.file, line) }
|
return items.filter { it.release == line.release && it.comp == line.comp && belongs(it.file, line) }
|
||||||
.filter { newestBad == null || ProtonExtras.compareVersions(it.file, newestBad) > 0 }
|
.filter { newestBad == null || ProtonExtras.compareVersions(it.file, newestBad) > 0 }
|
||||||
.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a.file, b.file) }
|
.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a.file, b.file) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun belongs(file: String, line: Line): Boolean =
|
fun belongs(file: String, line: Line): Boolean =
|
||||||
file.startsWith(line.prefix) && file.removePrefix(line.prefix).firstOrNull()?.isDigit() == true
|
file.startsWith(line.prefix) && file.removePrefix(line.prefix).firstOrNull()?.isDigit() == true &&
|
||||||
|
(line.comp != "fex" || ComponentsManager.bionicFex(file) == (line.release == ComponentsManager.DD_BIONIC))
|
||||||
|
|
||||||
fun arm64ec(pe: ByteArray): Boolean? = runCatching {
|
fun arm64ec(pe: ByteArray): Boolean? = runCatching {
|
||||||
val b = ByteBuffer.wrap(pe).order(ByteOrder.LITTLE_ENDIAN)
|
val b = ByteBuffer.wrap(pe).order(ByteOrder.LITTLE_ENDIAN)
|
||||||
@@ -161,7 +169,7 @@ object ComponentUpdates {
|
|||||||
fun stale(line: Line?, owned: Set<String>, stored: List<String>, keep: Set<String>, current: String, bad: Set<String> = emptySet()): List<String> {
|
fun stale(line: Line?, owned: Set<String>, stored: List<String>, keep: Set<String>, current: String, bad: Set<String> = emptySet()): List<String> {
|
||||||
val ranked = line?.takeIf { belongs(current, it) }
|
val ranked = line?.takeIf { belongs(current, it) }
|
||||||
fun newer(file: String) = ranked != null && belongs(file, ranked) && ProtonExtras.compareVersions(file, current) > 0
|
fun newer(file: String) = ranked != null && belongs(file, ranked) && ProtonExtras.compareVersions(file, current) > 0
|
||||||
return (owned + stored.filter { ranked != null && belongs(it, ranked) })
|
return (owned + stored.filter { ranked != null && ranked.release == ComponentsManager.DD_NIGHTLY && belongs(it, ranked) })
|
||||||
.filter { it !in keep && ((it in bad && it in owned) || !newer(it)) }.distinct()
|
.filter { it !in keep && ((it in bad && it in owned) || !newer(it)) }.distinct()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -29,6 +29,7 @@ object ComponentsManager {
|
|||||||
private const val NIGHTLIES = "The412Banner/Nightlies"
|
private const val NIGHTLIES = "The412Banner/Nightlies"
|
||||||
private const val DD_COMPONENTS = "Droid-Deck/DroidDeck-Components"
|
private const val DD_COMPONENTS = "Droid-Deck/DroidDeck-Components"
|
||||||
internal const val DD_NIGHTLY = "linux-nightly"
|
internal const val DD_NIGHTLY = "linux-nightly"
|
||||||
|
internal const val DD_BIONIC = "bionic-stable"
|
||||||
private val RELEASES = linkedMapOf(
|
private val RELEASES = linkedMapOf(
|
||||||
"FexCore-Linux" to "fex",
|
"FexCore-Linux" to "fex",
|
||||||
"Dxvk-Linux" to "dxvk",
|
"Dxvk-Linux" to "dxvk",
|
||||||
@@ -37,9 +38,9 @@ object ComponentsManager {
|
|||||||
"Vkd3d-proton-Linux" to "vkd3d",
|
"Vkd3d-proton-Linux" to "vkd3d",
|
||||||
)
|
)
|
||||||
private val NIGHTLY_PREFIXES = linkedMapOf("DD-dxvk-" to "dxvk", "DD-vkd3d-proton-" to "vkd3d", "DD-FEXCore-" to "fex")
|
private val NIGHTLY_PREFIXES = linkedMapOf("DD-dxvk-" to "dxvk", "DD-vkd3d-proton-" to "vkd3d", "DD-FEXCore-" to "fex")
|
||||||
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY)
|
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY) + (DD_COMPONENTS to DD_BIONIC)
|
||||||
private val DOWNLOAD_REPOS = listOf(NIGHTLIES, DD_COMPONENTS)
|
private val DOWNLOAD_REPOS = listOf(NIGHTLIES, DD_COMPONENTS)
|
||||||
private val TYPES = mapOf("FEXCore-Linux" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d")
|
private val TYPES = mapOf("FEXCore-Linux" to "fex", "FEXCore-Bionic" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d")
|
||||||
private val TYPE_OF = mapOf("fex" to "FEXCore-Linux", "dxvk" to "DXVK-Linux", "vkd3d" to "VKD3D-Linux")
|
private val TYPE_OF = mapOf("fex" to "FEXCore-Linux", "dxvk" to "DXVK-Linux", "vkd3d" to "VKD3D-Linux")
|
||||||
val COMPONENTS = listOf("fex", "dxvk", "vkd3d")
|
val COMPONENTS = listOf("fex", "dxvk", "vkd3d")
|
||||||
val LABEL = mapOf("fex" to "FEX", "dxvk" to "DXVK", "vkd3d" to "VKD3D-Proton")
|
val LABEL = mapOf("fex" to "FEX", "dxvk" to "DXVK", "vkd3d" to "VKD3D-Proton")
|
||||||
@@ -201,8 +202,34 @@ object ComponentsManager {
|
|||||||
COMPONENTS.mapNotNull { comp -> profile.optString(comp).takeIf(String::isNotEmpty)?.let { comp to it } }.toMap()
|
COMPONENTS.mapNotNull { comp -> profile.optString(comp).takeIf(String::isNotEmpty)?.let { comp to it } }.toMap()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) =
|
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) {
|
||||||
setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) }
|
setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) }
|
||||||
|
if (comp == "fex" && file != null) fetchFexTwin(context, safeName(file))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Twin downloads in flight: one worker per name, so two profile changes cannot share one partial download.
|
||||||
|
private val twinDownloads = HashSet<String>()
|
||||||
|
|
||||||
|
private fun fetchFexTwin(context: Context, file: String) {
|
||||||
|
val twin = fexTwin(file) ?: return
|
||||||
|
if (protons(context).all { fexFits(it.dir.name, file) }) return
|
||||||
|
synchronized(lock) { if (isStored(context, twin) || !twinDownloads.add(twin)) return }
|
||||||
|
val app = context.applicationContext
|
||||||
|
Thread({
|
||||||
|
try {
|
||||||
|
runCatching {
|
||||||
|
val item = catalogItem(app, twin, if (bionicFex(twin)) DD_BIONIC else "FexCore-Linux")
|
||||||
|
if (item == null) Log.i(TAG, "$twin is not listed")
|
||||||
|
else {
|
||||||
|
download(app, item) {}
|
||||||
|
republish(app)
|
||||||
|
}
|
||||||
|
}.onFailure { Log.w(TAG, "download $twin", it) }
|
||||||
|
} finally {
|
||||||
|
synchronized(lock) { twinDownloads.remove(twin) }
|
||||||
|
}
|
||||||
|
}, "fex-twin").start()
|
||||||
|
}
|
||||||
|
|
||||||
internal fun setGameComponent(context: Context, scope: String, comp: String, file: String?, managed: (String) -> Boolean) = synchronized(lock) {
|
internal fun setGameComponent(context: Context, scope: String, comp: String, file: String?, managed: (String) -> Boolean) = synchronized(lock) {
|
||||||
require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L)
|
require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L)
|
||||||
@@ -413,7 +440,7 @@ object ComponentsManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
require(File(staged, "files").isDirectory) { "${wcp.name} has no files/" }
|
require(File(staged, "files").isDirectory) { "${wcp.name} has no files/" }
|
||||||
if (comp == "fex") FEX_FILES.filter { it.endsWith(".so") && !File(staged, it).isFile }.forEach { File(dir, it).delete() }
|
if (comp == "fex" && !bionicTool(dir.name)) FEX_FILES.filter { it.endsWith(".so") && !File(staged, it).isFile }.forEach { File(dir, it).delete() }
|
||||||
COMP_DIR[comp]?.let { compDir ->
|
COMP_DIR[comp]?.let { compDir ->
|
||||||
for (arch in PE_ARCHES) {
|
for (arch in PE_ARCHES) {
|
||||||
val target = File(dir, "$compDir/$arch")
|
val target = File(dir, "$compDir/$arch")
|
||||||
@@ -603,7 +630,9 @@ object ComponentsManager {
|
|||||||
File(base, "files").walkTopDown().filter { it.isFile }.map { it.relativeTo(base).invariantSeparatorsPath }
|
File(base, "files").walkTopDown().filter { it.isFile }.map { it.relativeTo(base).invariantSeparatorsPath }
|
||||||
.filter { owned(comp, it) }.associateWith { File(base, it) }
|
.filter { owned(comp, it) }.associateWith { File(base, it) }
|
||||||
}
|
}
|
||||||
for (rel in managed(comp) - files.keys) {
|
// A bionic tool never loses a FEX file: its launch.sh would put the whole bundled FEX back.
|
||||||
|
val removed = if (comp == "fex" && bionicTool(p.dir.name)) emptySet() else managed(comp) - files.keys
|
||||||
|
for (rel in removed) {
|
||||||
lines.append(scope).append('\t').append(p.dir.name).append('\t').append(p.version).append('\t').append(comp)
|
lines.append(scope).append('\t').append(p.dir.name).append('\t').append(p.version).append('\t').append(comp)
|
||||||
.append('\t').append(rel).append("\t-\t-\n")
|
.append('\t').append(rel).append("\t-\t-\n")
|
||||||
}
|
}
|
||||||
@@ -620,7 +649,8 @@ object ComponentsManager {
|
|||||||
val version = safeName(file.removePrefix("original "))
|
val version = safeName(file.removePrefix("original "))
|
||||||
"original-${p.id}-$version-$comp" to File(originalsDir(context), "${p.id}/$version/$comp.wcp")
|
"original-${p.id}-$version-$comp" to File(originalsDir(context), "${p.id}/$version/$comp.wcp")
|
||||||
} else {
|
} else {
|
||||||
safeName(file.removeSuffix(".wcp")) to File(packagesDir(context), file)
|
val fit = (if (comp == "fex") launchFex(p.dir.name, file) { File(packagesDir(context), it).isFile } else file) ?: return null
|
||||||
|
safeName(fit.removeSuffix(".wcp")) to File(packagesDir(context), fit)
|
||||||
}.takeIf { it.second.isFile }
|
}.takeIf { it.second.isFile }
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -651,12 +681,14 @@ object ComponentsManager {
|
|||||||
for (scope in profiles.keys()) {
|
for (scope in profiles.keys()) {
|
||||||
val profile = profiles.optJSONObject(scope) ?: continue
|
val profile = profiles.optJSONObject(scope) ?: continue
|
||||||
for (comp in COMPONENTS) {
|
for (comp in COMPONENTS) {
|
||||||
val file = profile.optString(comp)
|
val chosen = profile.optString(comp)
|
||||||
if (file.isEmpty()) continue
|
if (chosen.isEmpty()) continue
|
||||||
val wcp = File(packagesDir(context), file)
|
for (p in all) {
|
||||||
if (!wcp.isFile) continue
|
val file = (if (comp == "fex") launchFex(p.dir.name, chosen) { File(packagesDir(context), it).isFile } else chosen) ?: continue
|
||||||
val key = safeName(file.removeSuffix(".wcp"))
|
val wcp = File(packagesDir(context), file)
|
||||||
for (p in all) append(scope, p, comp, key, wcp)
|
if (!wcp.isFile) continue
|
||||||
|
append(scope, p, comp, safeName(file.removeSuffix(".wcp")), wcp)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return PreparedLaunchState(lines.toString(), keep)
|
return PreparedLaunchState(lines.toString(), keep)
|
||||||
@@ -677,6 +709,7 @@ object ComponentsManager {
|
|||||||
val wcp = File(packagesDir(context), safeName(file))
|
val wcp = File(packagesDir(context), safeName(file))
|
||||||
val info = packageInfo(context, wcp)
|
val info = packageInfo(context, wcp)
|
||||||
requireSelectable(context, info.comp)
|
requireSelectable(context, info.comp)
|
||||||
|
requireFits(p, info)
|
||||||
val state = loadState(context)
|
val state = loadState(context)
|
||||||
if (inUse(context, p)) {
|
if (inUse(context, p)) {
|
||||||
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version)
|
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version)
|
||||||
@@ -690,7 +723,11 @@ object ComponentsManager {
|
|||||||
context.getString(R.string.cmgr_swap_done, LABEL[info.comp], info.version, p.name)
|
context.getString(R.string.cmgr_swap_done, LABEL[info.comp], info.version, p.name)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun requireFits(p: Proton, info: Package) =
|
||||||
|
check(info.comp != "fex" || fexFits(p.dir.name, info.file)) { "${info.file} is not a FEX build for ${p.name}" }
|
||||||
|
|
||||||
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject, auto: Boolean = false) {
|
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject, auto: Boolean = false) {
|
||||||
|
requireFits(p, info)
|
||||||
ensureOriginal(context, p, info.comp, state)
|
ensureOriginal(context, p, info.comp, state)
|
||||||
val hashes = installFiles(context, p.dir, info.comp, wcp)
|
val hashes = installFiles(context, p.dir, info.comp, wcp)
|
||||||
state.sub("active").sub(p.id).put(info.comp, JSONObject()
|
state.sub("active").sub(p.id).put(info.comp, JSONObject()
|
||||||
@@ -803,6 +840,18 @@ object ComponentsManager {
|
|||||||
internal fun liveOnAny(key: String, entry: JSONObject, installs: List<Proton>?): Boolean =
|
internal fun liveOnAny(key: String, entry: JSONObject, installs: List<Proton>?): Boolean =
|
||||||
installs?.any { liveSelection(key, entry, it) } == true
|
installs?.any { liveSelection(key, entry, it) } == true
|
||||||
|
|
||||||
|
// An installed tool that launches with `name` as the stored twin of a game's FEX choice (a Linux choice on
|
||||||
|
// DroidDeck-Bionic, a -bionic one on another Proton): deleting the twin would drop that choice for that tool.
|
||||||
|
internal fun twinUser(state: JSONObject, installed: List<Proton>, name: String): Proton? {
|
||||||
|
val profiles = state.optJSONObject("profiles") ?: return null
|
||||||
|
for (scope in profiles.keys()) {
|
||||||
|
val chosen = profiles.optJSONObject(scope)?.optString("fex")?.takeIf { it.isNotEmpty() } ?: continue
|
||||||
|
if (fexTwin(chosen) != name) continue
|
||||||
|
installed.firstOrNull { !fexFits(it.dir.name, chosen) }?.let { return it }
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
internal fun packagesInUse(state: JSONObject, installed: List<Proton>): Set<String> {
|
internal fun packagesInUse(state: JSONObject, installed: List<Proton>): Set<String> {
|
||||||
val byId = installed.groupBy { it.id }
|
val byId = installed.groupBy { it.id }
|
||||||
val names = HashSet<String>()
|
val names = HashSet<String>()
|
||||||
@@ -819,7 +868,11 @@ object ComponentsManager {
|
|||||||
val profiles = state.optJSONObject("profiles")
|
val profiles = state.optJSONObject("profiles")
|
||||||
for (scope in profiles?.keys() ?: emptyList<String>().iterator()) {
|
for (scope in profiles?.keys() ?: emptyList<String>().iterator()) {
|
||||||
val profile = profiles?.optJSONObject(scope) ?: continue
|
val profile = profiles?.optJSONObject(scope) ?: continue
|
||||||
COMPONENTS.forEach { comp -> profile.optString(comp).takeIf { it.isNotEmpty() }?.let(names::add) }
|
COMPONENTS.forEach { comp ->
|
||||||
|
val file = profile.optString(comp).takeIf { it.isNotEmpty() } ?: return@forEach
|
||||||
|
names.add(file)
|
||||||
|
if (comp == "fex" && installed.any { !fexFits(it.dir.name, file) }) fexTwin(file)?.let(names::add)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return names
|
return names
|
||||||
}
|
}
|
||||||
@@ -890,6 +943,7 @@ object ComponentsManager {
|
|||||||
val queued = state.sub("queued").sub(target.id)
|
val queued = state.sub("queued").sub(target.id)
|
||||||
var changed = false
|
var changed = false
|
||||||
wanted.forEach { (comp, entry) ->
|
wanted.forEach { (comp, entry) ->
|
||||||
|
if (comp == "fex" && !fexFits(target.dir.name, entry.optString("file"))) return@forEach
|
||||||
if (active?.has(comp) != true && !queued.has(comp)) {
|
if (active?.has(comp) != true && !queued.has(comp)) {
|
||||||
queued.put(comp, entry)
|
queued.put(comp, entry)
|
||||||
changed = true
|
changed = true
|
||||||
@@ -970,6 +1024,8 @@ object ComponentsManager {
|
|||||||
fun deletePackage(context: Context, file: String): String = synchronized(lock) {
|
fun deletePackage(context: Context, file: String): String = synchronized(lock) {
|
||||||
val name = safeName(file)
|
val name = safeName(file)
|
||||||
val state = loadState(context)
|
val state = loadState(context)
|
||||||
|
val twinTool = twinUser(state, protons(context), name)
|
||||||
|
check(twinTool == null) { context.getString(R.string.cmgr_package_in_use, name, twinTool?.name ?: "") }
|
||||||
val installed = protons(context).groupBy { it.id }
|
val installed = protons(context).groupBy { it.id }
|
||||||
var changed = false
|
var changed = false
|
||||||
for (key in listOf("queued", "active")) {
|
for (key in listOf("queued", "active")) {
|
||||||
@@ -1066,8 +1122,11 @@ object ComponentsManager {
|
|||||||
return Catalog(items, o.optLong("fetchedAt"))
|
return Catalog(items, o.optLong("fetchedAt"))
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun assetComp(release: String, name: String): String? =
|
internal fun assetComp(release: String, name: String): String? = RELEASES[release] ?: when (release) {
|
||||||
RELEASES[release] ?: if (release == DD_NIGHTLY) NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value else null
|
DD_NIGHTLY -> NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value
|
||||||
|
DD_BIONIC -> "fex"
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
|
||||||
internal val CATALOG_ORDER: Comparator<CatalogItem> =
|
internal val CATALOG_ORDER: Comparator<CatalogItem> =
|
||||||
compareBy<CatalogItem> { it.comp }.thenBy { it.release == DD_NIGHTLY }.then(newestFirst { it.file })
|
compareBy<CatalogItem> { it.comp }.thenBy { it.release == DD_NIGHTLY }.then(newestFirst { it.file })
|
||||||
@@ -1155,6 +1214,25 @@ object ComponentsManager {
|
|||||||
return runCatching { readWcpEntry(original, rel) }.getOrNull()
|
return runCatching { readWcpEntry(original, rel) }.getOrNull()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DroidDeck-Bionic loads only Android builds of FEX's unix libraries; other Protons only glibc builds.
|
||||||
|
internal fun bionicTool(dirName: String?): Boolean = dirName?.startsWith("DroidDeck-Bionic") == true
|
||||||
|
|
||||||
|
internal fun bionicFex(file: String): Boolean = file.endsWith("-bionic.wcp", ignoreCase = true)
|
||||||
|
|
||||||
|
internal fun fexFits(toolDir: String?, file: String): Boolean = bionicTool(toolDir) == bionicFex(file)
|
||||||
|
|
||||||
|
internal fun fexTwin(file: String): String? = when {
|
||||||
|
file.endsWith("-linux.wcp", ignoreCase = true) -> file.dropLast("-linux.wcp".length) + "-bionic.wcp"
|
||||||
|
file.endsWith("-bionic.wcp", ignoreCase = true) -> file.dropLast("-bionic.wcp".length) + "-linux.wcp"
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun launchFex(toolDir: String, file: String, stored: (String) -> Boolean): String? =
|
||||||
|
if (fexFits(toolDir, file)) file else fexTwin(file)?.takeIf(stored)
|
||||||
|
|
||||||
|
internal fun <T> forTool(comp: String, toolDir: String?, items: List<T>, selected: String? = null, file: (T) -> String): List<T> =
|
||||||
|
if (comp != "fex") items else items.filter { file(it) == selected || fexFits(toolDir, file(it)) }
|
||||||
|
|
||||||
fun supports(p: Proton, comp: String): Boolean =
|
fun supports(p: Proton, comp: String): Boolean =
|
||||||
if (comp == "fex") File(p.dir, FEX_FILES.first()).isFile else File(p.dir, "${COMP_DIR.getValue(comp)}/aarch64-windows").isDirectory
|
if (comp == "fex") File(p.dir, FEX_FILES.first()).isFile else File(p.dir, "${COMP_DIR.getValue(comp)}/aarch64-windows").isDirectory
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package com.droiddeck.launcher.session
|
||||||
|
|
||||||
|
import android.util.Log
|
||||||
|
import com.droiddeck.launcher.stores.StoreInstalls
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
object CpuCacheSysfs {
|
||||||
|
private const val TAG = "SessionService"
|
||||||
|
private val FEX_CPUID_SIZE_KB = mapOf(1 to 32, 2 to 512, 3 to 8192)
|
||||||
|
|
||||||
|
private val PROCESS = java.util.UUID.randomUUID().toString()
|
||||||
|
private val STARTS = java.util.concurrent.atomic.AtomicInteger()
|
||||||
|
|
||||||
|
fun binds(root: File, start: Int = STARTS.incrementAndGet(), host: File = File("/sys/devices/system/cpu"), process: String = PROCESS): List<String> = try {
|
||||||
|
root.listFiles()?.forEach { old -> if (old.name != process) StoreInstalls.deleteTree(old) }
|
||||||
|
val dir = File(root, "$process/$start")
|
||||||
|
StoreInstalls.deleteTree(dir)
|
||||||
|
val cpus = host.list { _, name -> name.matches(Regex("cpu\\d+")) }?.sorted().orEmpty()
|
||||||
|
val binds = cpus.mapNotNull { cpu ->
|
||||||
|
val staged = try {
|
||||||
|
stage(File(host, "$cpu/cache"), File(dir, cpu))
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "cpu cache: could not stage $cpu: $e")
|
||||||
|
false
|
||||||
|
}
|
||||||
|
if (staged) File(dir, cpu).path + ":" + File(host, "$cpu/cache").path else null
|
||||||
|
}
|
||||||
|
Log.i(TAG, "cpu cache: ${binds.size} of ${cpus.size} cores report the sizes the x86 CPUID reports")
|
||||||
|
binds
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "cpu cache: could not stage the core caches: $e")
|
||||||
|
emptyList()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun stage(cache: File, out: File): Boolean {
|
||||||
|
val indexes = cache.listFiles { f -> f.isDirectory && f.name.matches(Regex("index\\d+")) } ?: return false
|
||||||
|
var staged = false
|
||||||
|
for (index in indexes) {
|
||||||
|
val target = File(out, index.name).apply { mkdirs() }
|
||||||
|
val kb = runCatching { File(index, "level").readText().trim().toInt() }.getOrNull()?.let { FEX_CPUID_SIZE_KB[it] }
|
||||||
|
val files = index.listFiles { f -> f.isFile } ?: throw java.io.IOException("cannot list $index")
|
||||||
|
for (f in files) {
|
||||||
|
if (kb != null && f.name == "size") continue
|
||||||
|
File(target, f.name).writeText(f.readText())
|
||||||
|
}
|
||||||
|
if (kb == null) continue
|
||||||
|
File(target, "size").writeText("${kb}K\n")
|
||||||
|
staged = true
|
||||||
|
}
|
||||||
|
return staged
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -935,9 +935,9 @@ internal object EnhancedSessionLogShare {
|
|||||||
|
|
||||||
private fun category(entry: String): Category {
|
private fun category(entry: String): Category {
|
||||||
val value = entry.lowercase(Locale.US)
|
val value = entry.lowercase(Locale.US)
|
||||||
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") ||
|
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") || value.startsWith("rpcs3/") ||
|
||||||
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
|
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
|
||||||
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug").any(value::contains)) return Category.GAMES
|
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug", "bionic").any(value::contains)) return Category.GAMES
|
||||||
if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS
|
if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS
|
||||||
return Category.SESSION
|
return Category.SESSION
|
||||||
}
|
}
|
||||||
@@ -948,8 +948,9 @@ internal object EnhancedSessionLogShare {
|
|||||||
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
|
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
|
||||||
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log",
|
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log",
|
||||||
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
|
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
|
||||||
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt",
|
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt", "droiddeck-bionic.log",
|
||||||
"console_log.txt", "webhelper_js.txt", "controller_support.txt", "systemperfmanager.txt",
|
"console_log.txt", "webhelper_js.txt", "controller_support.txt", "systemperfmanager.txt",
|
||||||
|
"rpcs3", "RPCS3.log",
|
||||||
)
|
)
|
||||||
private val KNOWN_COMPONENT_PATTERNS = listOf(
|
private val KNOWN_COMPONENT_PATTERNS = listOf(
|
||||||
Regex("[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2,}-[a-z0-9-]{1,24}"),
|
Regex("[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2,}-[a-z0-9-]{1,24}"),
|
||||||
|
|||||||
@@ -74,10 +74,16 @@ object ExperimentalProtons {
|
|||||||
return PREFIX + base + (tag?.let { "-$it" } ?: "")
|
return PREFIX + base + (tag?.let { "-$it" } ?: "")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** DroidDeck-Bionic test builds are prereleases of the same repository and have their own row in the Proton list. */
|
||||||
|
internal fun listed(assets: List<ProtonExtras.Asset>): List<ProtonExtras.Asset> {
|
||||||
|
val bionic = ProtonExtras.tools.first { it.id == ProtonExtras.BIONIC }
|
||||||
|
return assets.filterNot { bionic.assetPattern.containsMatchIn(it.name) }
|
||||||
|
}
|
||||||
|
|
||||||
fun refresh(context: Context): List<Release>? {
|
fun refresh(context: Context): List<Release>? {
|
||||||
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
|
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
|
||||||
val fetched = ProtonExtras.releasesForRemoval(tool) ?: return null
|
val fetched = ProtonExtras.releasesForRemoval(tool) ?: return null
|
||||||
val assets = ProtonExtras.assets(tool, fetched.releases, prerelease = true)
|
val assets = listed(ProtonExtras.assets(tool, fetched.releases, prerelease = true))
|
||||||
val rows = assets.map { Release(it.tag, it.name, it.url, it.sha512, it.size, it.releaseName) }.distinctBy { it.tag }
|
val rows = assets.map { Release(it.tag, it.name, it.url, it.sha512, it.size, it.releaseName) }.distinctBy { it.tag }
|
||||||
if (!SessionState.running) {
|
if (!SessionState.running) {
|
||||||
reconcile(context, fetched)
|
reconcile(context, fetched)
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
package com.droiddeck.launcher.session
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Orders launch attempts and at most one pending game link.
|
||||||
|
*
|
||||||
|
* This is main-thread state: call it from the UI thread. A ticket is an identity,
|
||||||
|
* not a counter comparison, so a stale callback can only act on its own request.
|
||||||
|
*/
|
||||||
|
internal class LaunchTicket internal constructor(val serial: Long)
|
||||||
|
|
||||||
|
internal class LaunchCoordinator<O : Any, R : Any> {
|
||||||
|
internal class Link<O : Any, R : Any> internal constructor(
|
||||||
|
val ticket: LaunchTicket,
|
||||||
|
val owner: O,
|
||||||
|
val request: R?,
|
||||||
|
) {
|
||||||
|
/** Only the activity intent that delivered this link may finish it by a refresh. */
|
||||||
|
fun ownedBy(owner: O?): Boolean = this.owner === owner
|
||||||
|
}
|
||||||
|
|
||||||
|
private var next = 0L
|
||||||
|
private var current: LaunchTicket? = null
|
||||||
|
private var pending: Link<O, R>? = null
|
||||||
|
private var handling: LaunchTicket? = null
|
||||||
|
|
||||||
|
/** A launch that is allowed to proceed; it supersedes any pending link. */
|
||||||
|
fun beginLaunch(): LaunchTicket {
|
||||||
|
val ticket = LaunchTicket(++next)
|
||||||
|
current = ticket
|
||||||
|
pending = null
|
||||||
|
handling = null
|
||||||
|
return ticket
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A game-link intent; it supersedes any earlier launch or link. */
|
||||||
|
fun beginLink(owner: O): LaunchTicket {
|
||||||
|
val ticket = LaunchTicket(++next)
|
||||||
|
current = ticket
|
||||||
|
pending = Link(ticket, owner, null)
|
||||||
|
handling = null
|
||||||
|
return ticket
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The asynchronous link read returned; false means a newer request won. */
|
||||||
|
fun resolve(ticket: LaunchTicket, request: R?): Boolean {
|
||||||
|
val link = pending ?: return false
|
||||||
|
if (link.ticket !== ticket) return false
|
||||||
|
pending = Link(ticket, link.owner, request)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun beginHandling(ticket: LaunchTicket): Boolean {
|
||||||
|
val link = pending ?: return false
|
||||||
|
if (link.ticket !== ticket || link.request == null) return false
|
||||||
|
handling = ticket
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun releaseHandling(ticket: LaunchTicket) {
|
||||||
|
if (handling === ticket) handling = null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun isHandling(ticket: LaunchTicket): Boolean = handling === ticket
|
||||||
|
fun isCurrent(ticket: LaunchTicket): Boolean = current === ticket
|
||||||
|
fun hasPending(): Boolean = pending != null
|
||||||
|
fun pendingLink(): Link<O, R>? = pending
|
||||||
|
|
||||||
|
fun consume(ticket: LaunchTicket): Boolean {
|
||||||
|
val link = pending ?: return false
|
||||||
|
if (link.ticket !== ticket) return false
|
||||||
|
pending = null
|
||||||
|
handling = null
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
fun cancelAll() {
|
||||||
|
next++
|
||||||
|
current = null
|
||||||
|
pending = null
|
||||||
|
handling = null
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,16 +2,20 @@ package com.droiddeck.launcher.session
|
|||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.util.Log
|
import android.util.Log
|
||||||
|
import com.droiddeck.launcher.agent.AgentGuest
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
|
||||||
object OfflineMode {
|
object OfflineMode {
|
||||||
private const val TAG = "OfflineMode"
|
private const val TAG = "OfflineMode"
|
||||||
private const val KEY = "steam_offline"
|
private const val KEY = "steam_offline"
|
||||||
|
private const val AUTO_KEY = "steam_offline_auto"
|
||||||
|
private const val NETWORK_KEY = "steam_offline_by_network"
|
||||||
private val WANTS = Regex("""^(\s*"WantsOfflineMode"\s*")([01])(".*)$""")
|
private val WANTS = Regex("""^(\s*"WantsOfflineMode"\s*")([01])(".*)$""")
|
||||||
private val SKIP = Regex("""^(\s*"SkipOfflineModeWarning"\s*")([01])(".*)$""")
|
private val SKIP = Regex("""^(\s*"SkipOfflineModeWarning"\s*")([01])(".*)$""")
|
||||||
private val REMEMBER = Regex(""""RememberPassword"\s*"1"""")
|
private val REMEMBER = Regex(""""RememberPassword"\s*"1"""")
|
||||||
private val PERSONA = Regex(""""PersonaName"\s*"([^"]*)"""")
|
private val PERSONA = Regex(""""PersonaName"\s*"([^"]*)"""")
|
||||||
|
private const val EVAL_TIMEOUT_MS = 10_000L
|
||||||
|
|
||||||
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
private fun prefs(context: Context) = context.getSharedPreferences("session", Context.MODE_PRIVATE)
|
||||||
|
|
||||||
@@ -19,10 +23,12 @@ object OfflineMode {
|
|||||||
|
|
||||||
private fun x64LoginUsers(root: File) = File(root, "root/.droiddeck-x64/.local/share/Steam/config/loginusers.vdf")
|
private fun x64LoginUsers(root: File) = File(root, "root/.droiddeck-x64/.local/share/Steam/config/loginusers.vdf")
|
||||||
|
|
||||||
fun account(context: Context): String? {
|
private fun activeLoginUsers(context: Context, root: File) =
|
||||||
val root = LinuxRuntime.rootDir(context)
|
x64LoginUsers(root).takeIf { SessionPrefs.activeSteamClientArch(context) == "x86_64" && it.isFile }
|
||||||
val file = x64LoginUsers(root).takeIf { SessionPrefs.activeSteamClientArch(context) == "x86_64" && it.isFile }
|
|
||||||
?: loginUsers(root)
|
?: loginUsers(root)
|
||||||
|
|
||||||
|
fun account(context: Context): String? {
|
||||||
|
val file = activeLoginUsers(context, LinuxRuntime.rootDir(context))
|
||||||
val text = try {
|
val text = try {
|
||||||
if (file.isFile) file.readText() else return null
|
if (file.isFile) file.readText() else return null
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
@@ -32,21 +38,114 @@ object OfflineMode {
|
|||||||
return PERSONA.find(text)?.groupValues?.get(1)?.takeIf { it.isNotBlank() }.orEmpty()
|
return PERSONA.find(text)?.groupValues?.get(1)?.takeIf { it.isNotBlank() }.orEmpty()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun enabled(context: Context): Boolean = prefs(context).getBoolean(KEY, false)
|
private fun steamWants(context: Context, root: File): Boolean? {
|
||||||
|
val file = activeLoginUsers(context, root)
|
||||||
|
val lines = try {
|
||||||
|
if (file.isFile) file.readLines() else return null
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "could not read loginusers.vdf", e); return null
|
||||||
|
}
|
||||||
|
val values = lines.mapNotNull { WANTS.matchEntire(it)?.groupValues?.get(2) }
|
||||||
|
return if (values.isEmpty()) null else "1" in values
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun manual(steamWants: Boolean?, automatic: Boolean, saved: Boolean): Boolean =
|
||||||
|
if (steamWants == null) saved else steamWants && !automatic
|
||||||
|
|
||||||
|
internal fun offline(manual: Boolean, online: Boolean, auto: Boolean = true): Boolean = manual || (auto && !online)
|
||||||
|
|
||||||
|
internal fun afterNetworkChange(manual: Boolean, online: Boolean): Boolean = manual && !online
|
||||||
|
|
||||||
|
fun auto(context: Context): Boolean = prefs(context).getBoolean(AUTO_KEY, true)
|
||||||
|
|
||||||
|
fun enabled(context: Context): Boolean = saved(context, LinuxRuntime.rootDir(context))
|
||||||
|
|
||||||
|
fun active(context: Context): Boolean =
|
||||||
|
offline(enabled(context), isOnline(context), auto(context))
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
fun setEnabled(context: Context, on: Boolean) {
|
fun setEnabled(context: Context, on: Boolean) {
|
||||||
prefs(context).edit().putBoolean(KEY, on).apply()
|
write(context, LinuxRuntime.rootDir(context), on)
|
||||||
apply(context, LinuxRuntime.rootDir(context))
|
SteamOfflineFollow.request()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun apply(context: Context, root: File) {
|
@Synchronized
|
||||||
applyTo(context, loginUsers(root))
|
fun setAuto(context: Context, on: Boolean) {
|
||||||
applyTo(context, x64LoginUsers(root))
|
val manual = if (on) false else steamWants(context, LinuxRuntime.rootDir(context)) ?: active(context)
|
||||||
|
prefs(context).edit().putBoolean(AUTO_KEY, on).commit()
|
||||||
|
setEnabled(context, manual)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun applyTo(context: Context, file: File) {
|
fun apply(context: Context, root: File): Boolean = write(context, root, saved(context, root))
|
||||||
|
|
||||||
|
fun sync(context: Context): Boolean? {
|
||||||
|
val root = LinuxRuntime.rootDir(context)
|
||||||
|
val offline = synchronized(this) { write(context, root, saved(context, root)) }
|
||||||
|
return switchLive(context, offline)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun follow(context: Context): Boolean? {
|
||||||
|
val root = LinuxRuntime.rootDir(context)
|
||||||
|
val (byNetwork, offline) = synchronized(this) {
|
||||||
|
if (!auto(context)) return false
|
||||||
|
prefs(context).getBoolean(NETWORK_KEY, false) to
|
||||||
|
write(context, root, afterNetworkChange(saved(context, root), isOnline(context)))
|
||||||
|
}
|
||||||
|
val result = switchLive(context, offline)
|
||||||
|
if (result == null && !offline && byNetwork) restoreNetworkOffline(context)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
internal fun restoreNetworkOffline(context: Context) {
|
||||||
|
val prefs = prefs(context)
|
||||||
|
if (!auto(context) || prefs.getBoolean(KEY, false) || prefs.getBoolean(NETWORK_KEY, false)) return
|
||||||
|
prefs.edit().putBoolean(NETWORK_KEY, true).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isOnline(context: Context) = com.droiddeck.launcher.frontend.AutoComponents.isOnline(context)
|
||||||
|
|
||||||
|
private fun saved(context: Context, root: File): Boolean {
|
||||||
|
val prefs = prefs(context)
|
||||||
|
return manual(steamWants(context, root), prefs.getBoolean(NETWORK_KEY, false), prefs.getBoolean(KEY, false))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
private fun remember(context: Context, manual: Boolean): Boolean {
|
||||||
|
val online = isOnline(context)
|
||||||
|
val auto = auto(context)
|
||||||
|
val offline = offline(manual, online, auto)
|
||||||
|
prefs(context).edit().putBoolean(KEY, manual).putBoolean(NETWORK_KEY, offline && !manual).apply()
|
||||||
|
Log.i(TAG, "auto=$auto manual=$manual online=$online offline=$offline")
|
||||||
|
return offline
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun switchLive(context: Context, offline: Boolean): Boolean? {
|
||||||
|
val answer = try {
|
||||||
|
AgentGuest.steamEval(context, "$SWITCH($offline)", EVAL_TIMEOUT_MS)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
Log.w(TAG, "steam not reachable: ${e.javaClass.simpleName}: ${e.message}")
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
val result = if (answer.optBoolean("ok")) answer.optString("value") else answer.optJSONObject("error")?.optString("message")
|
||||||
|
Log.i(TAG, "live offline=$offline: $result")
|
||||||
|
return when (result) {
|
||||||
|
"switched" -> true
|
||||||
|
"same" -> false
|
||||||
|
else -> null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun write(context: Context, root: File, manual: Boolean): Boolean {
|
||||||
|
val offline = remember(context, manual)
|
||||||
|
applyTo(loginUsers(root), offline)
|
||||||
|
applyTo(x64LoginUsers(root), offline)
|
||||||
|
return offline
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun applyTo(file: File, offline: Boolean) {
|
||||||
if (!file.isFile) return
|
if (!file.isFile) return
|
||||||
val want = if (enabled(context)) "1" else "0"
|
val want = if (offline) "1" else "0"
|
||||||
try {
|
try {
|
||||||
val lines = file.readLines()
|
val lines = file.readLines()
|
||||||
val out = ArrayList<String>(lines.size + 4)
|
val out = ArrayList<String>(lines.size + 4)
|
||||||
@@ -94,4 +193,25 @@ object OfflineMode {
|
|||||||
Log.w(TAG, "could not write loginusers.vdf", e)
|
Log.w(TAG, "could not write loginusers.vdf", e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private val SWITCH = """(async want => {
|
||||||
|
const user = globalThis.SteamClient?.User;
|
||||||
|
if (typeof user?.GoOffline !== 'function' || typeof user?.GoOnline !== 'function') return "missing";
|
||||||
|
const seen = globalThis.__droiddeckSteamOffline ??= { value: null };
|
||||||
|
seen.want = want;
|
||||||
|
if (!seen.registered) {
|
||||||
|
seen.registered = true;
|
||||||
|
user.RegisterForCurrentUserChanges(u => { seen.value = !!u?.bIsOfflineMode; });
|
||||||
|
globalThis.SteamClient.GameSessions?.RegisterForAppLifetimeNotifications?.(n => {
|
||||||
|
if (n?.bRunning) return;
|
||||||
|
setTimeout(() => { if (seen.want === true && seen.value === false) user.GoOffline(); }, 2000);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for (let waited = 0; seen.value === null && waited < 4000; waited += 100) await new Promise(done => setTimeout(done, 100));
|
||||||
|
const current = seen.value;
|
||||||
|
if (current === null) return "unknown";
|
||||||
|
if (current === want) return "same";
|
||||||
|
if (want) user.GoOffline(); else user.GoOnline();
|
||||||
|
return "switched";
|
||||||
|
})"""
|
||||||
}
|
}
|
||||||
@@ -14,7 +14,8 @@ object ProtonDefault {
|
|||||||
|
|
||||||
data class Tool(val name: String, val display: String, val dir: String, val valve: Boolean)
|
data class Tool(val name: String, val display: String, val dir: String, val valve: Boolean)
|
||||||
data class Request(val seq: Long, val valve: Boolean, val dir: String)
|
data class Request(val seq: Long, val valve: Boolean, val dir: String)
|
||||||
data class State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>)
|
data class State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>,
|
||||||
|
val source: String? = null)
|
||||||
data class GameChoice(val valve: Boolean, val dir: String)
|
data class GameChoice(val valve: Boolean, val dir: String)
|
||||||
|
|
||||||
enum class Outcome { LIVE, NEXT_START, NOT_RUNNABLE }
|
enum class Outcome { LIVE, NEXT_START, NOT_RUNNABLE }
|
||||||
@@ -34,6 +35,7 @@ object ProtonDefault {
|
|||||||
Tool(t.optString("name"), t.optString("display"), t.optString("dir"), t.optBoolean("valve"))
|
Tool(t.optString("name"), t.optString("display"), t.optString("dir"), t.optBoolean("valve"))
|
||||||
}?.takeIf { it.name.isNotEmpty() }
|
}?.takeIf { it.name.isNotEmpty() }
|
||||||
},
|
},
|
||||||
|
source = o.optString("source").ifEmpty { null },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,7 +101,13 @@ object ProtonDefault {
|
|||||||
if (!runnable(state, proton)) return Outcome.NOT_RUNNABLE
|
if (!runnable(state, proton)) return Outcome.NOT_RUNNABLE
|
||||||
val d = dir(context)
|
val d = dir(context)
|
||||||
val seq = nextSeq(System.currentTimeMillis(), state, parseRequest(read(File(d, "request.json"))))
|
val seq = nextSeq(System.currentTimeMillis(), state, parseRequest(read(File(d, "request.json"))))
|
||||||
val body = JSONObject().put("seq", seq).put("valve", proton.valve).put("dir", proton.dir.name).toString(1) + "\n"
|
writeRequest(d, Request(seq, proton.valve, proton.dir.name))
|
||||||
|
val tool = state.tools.firstOrNull { it.valve == proton.valve && it.dir == proton.dir.name }
|
||||||
|
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun writeRequest(d: File, request: Request) {
|
||||||
|
val body = JSONObject().put("seq", request.seq).put("valve", request.valve).put("dir", request.dir).toString(1) + "\n"
|
||||||
val staged = File(d, "request.json.staged")
|
val staged = File(d, "request.json.staged")
|
||||||
try {
|
try {
|
||||||
d.mkdirs()
|
d.mkdirs()
|
||||||
@@ -110,8 +118,45 @@ object ProtonDefault {
|
|||||||
Log.w(TAG, "could not write the Proton request", e)
|
Log.w(TAG, "could not write the Proton request", e)
|
||||||
throw e
|
throw e
|
||||||
}
|
}
|
||||||
val tool = state.tools.firstOrNull { it.valve == proton.valve && it.dir == proton.dir.name }
|
}
|
||||||
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
|
|
||||||
|
// The default that names a tool an update replaces moves to the new one, as the per-game picks do: otherwise the guest
|
||||||
|
// no longer finds it and falls back to DroidDeck-Proton.
|
||||||
|
internal fun movedDefault(state: State, request: Request?, from: Set<String>, to: String, now: Long): Request? {
|
||||||
|
val (valve, dir) = chosen(state, request) ?: return null
|
||||||
|
if (valve || dir !in from) return null
|
||||||
|
return Request(nextSeq(now, state, request), false, to)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Synchronized
|
||||||
|
fun moveDefault(context: Context, from: Set<String>, to: String) {
|
||||||
|
val d = dir(context)
|
||||||
|
val moved = movedDefault(state(context), parseRequest(read(File(d, "request.json"))), from, to, System.currentTimeMillis()) ?: return
|
||||||
|
writeRequest(d, moved)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DroidDeck-Bionic keeps one build. A default naming another one moves to the installed build: an app from before
|
||||||
|
// updates carried the default over left it, or the guest fell back to its own tool when that build was gone (the
|
||||||
|
// request the app last wrote still names it).
|
||||||
|
internal fun bionicDefault(state: State, request: Request?, prefix: String, newest: String, now: Long): Request? {
|
||||||
|
val current = chosen(state, request)
|
||||||
|
val stale = when {
|
||||||
|
current != null && !current.first && current.second.startsWith(prefix) -> current.second
|
||||||
|
state.source == "fallback" && request != null && !request.valve && request.dir.startsWith(prefix) -> request.dir
|
||||||
|
else -> return null
|
||||||
|
}
|
||||||
|
return if (stale == newest) null else Request(nextSeq(now, state, request), false, newest)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The default and the per-game picks that name a DroidDeck-Bionic build other than [newest] move to it. */
|
||||||
|
@Synchronized
|
||||||
|
fun keepBionicCurrent(context: Context, prefix: String, newest: String) {
|
||||||
|
val d = dir(context)
|
||||||
|
bionicDefault(state(context), parseRequest(read(File(d, "request.json"))), prefix, newest, System.currentTimeMillis())
|
||||||
|
?.let { writeRequest(d, it) }
|
||||||
|
val games = parseGames(read(File(d, GAMES)))
|
||||||
|
val stale = games.values.filterNotNull().filter { !it.valve && it.dir.startsWith(prefix) && it.dir != newest }.map { it.dir }.toSet()
|
||||||
|
if (stale.isNotEmpty()) movedGames(games, stale, newest)?.let { writeGames(d, it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun movedGames(choices: Map<String, GameChoice?>, from: Set<String>, to: String): Map<String, GameChoice?>? {
|
internal fun movedGames(choices: Map<String, GameChoice?>, from: Set<String>, to: String): Map<String, GameChoice?>? {
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import android.util.Log
|
|||||||
import com.droiddeck.launcher.core.Downloader
|
import com.droiddeck.launcher.core.Downloader
|
||||||
import com.droiddeck.launcher.core.FileUtils
|
import com.droiddeck.launcher.core.FileUtils
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
|
import com.droiddeck.launcher.runtime.NativeGuest
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.util.Locale
|
import java.util.Locale
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
@@ -32,20 +33,27 @@ object ProtonExtras {
|
|||||||
@Volatile
|
@Volatile
|
||||||
private var replacing = false
|
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,
|
||||||
|
val prereleases: Boolean = false)
|
||||||
|
|
||||||
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 releaseName: String = tag)
|
val sha256: String? = null, val releaseName: String = tag)
|
||||||
internal data class ReleaseFetch(val releases: JSONArray, val complete: Boolean)
|
internal data class ReleaseFetch(val releases: JSONArray, val complete: Boolean)
|
||||||
|
|
||||||
const val OWN = "droiddeck"
|
const val OWN = "droiddeck"
|
||||||
|
const val BIONIC = "bionic"
|
||||||
|
|
||||||
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)$")),
|
||||||
Tool("droiddeck", "DroidDeck-Proton", "DroidDeck-Proton", "Droid-Deck/DroidDeck-Proton", Regex("aarch64\\.tar\\.(gz|xz)$")),
|
Tool("droiddeck", "DroidDeck-Proton", "DroidDeck-Proton", "Droid-Deck/DroidDeck-Proton", Regex("^DroidDeck-Proton-.*aarch64\\.tar\\.(gz|xz)$")),
|
||||||
|
// Bionic (Android libc) Proton started outside the Linux userland; test builds are prereleases. No-proot only.
|
||||||
|
Tool(BIONIC, "DroidDeck-Bionic", "DroidDeck-Bionic", "Droid-Deck/DroidDeck-Proton", Regex("^DroidDeck-Bionic-.*aarch64\\.tar\\.(gz|xz)$"), prereleases = true),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/** The sources offered on this device: DroidDeck-Bionic only with Run without proot on. */
|
||||||
|
fun offered(context: Context): List<Tool> = tools.filter { it.id != BIONIC || NativeGuest.enabled(context) }
|
||||||
|
|
||||||
private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root")
|
private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root")
|
||||||
private fun requests(context: Context) = File(home(context), ".dd-proton-extra")
|
private fun requests(context: Context) = File(home(context), ".dd-proton-extra")
|
||||||
private fun toolsDir(context: Context) = File(home(context), ".local/share/Steam/compatibilitytools.d")
|
private fun toolsDir(context: Context) = File(home(context), ".local/share/Steam/compatibilitytools.d")
|
||||||
@@ -120,10 +128,11 @@ object ProtonExtras {
|
|||||||
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 {
|
||||||
|
keepBionicCurrent(context)
|
||||||
synchronized(checkLock) {
|
synchronized(checkLock) {
|
||||||
val file = latestFile(context)
|
val file = latestFile(context)
|
||||||
val cache = readJson(file)
|
val cache = readJson(file)
|
||||||
val due = tools.filter { tool ->
|
val due = offered(context).filter { tool ->
|
||||||
val at = cache.optJSONObject(tool.id)?.optLong("at", 0L) ?: 0L
|
val at = cache.optJSONObject(tool.id)?.optLong("at", 0L) ?: 0L
|
||||||
force || (now - at) !in 0 until CHECK_EVERY_MS
|
force || (now - at) !in 0 until CHECK_EVERY_MS
|
||||||
}
|
}
|
||||||
@@ -173,15 +182,32 @@ 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)
|
if (deleteTool(context, name)) ComponentsManager.forgetProton(context, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A tool folder can hold links that point out of it (a prefix template's dosdevices/z: -> /), and
|
||||||
|
// File.deleteRecursively() follows links into directories: remove each link itself, never what it points to.
|
||||||
|
private fun deleteTool(context: Context, name: String): Boolean {
|
||||||
|
val dir = File(toolsDir(context), name)
|
||||||
|
FileUtils.delete(dir)
|
||||||
|
return !dir.exists() && !java.nio.file.Files.isSymbolicLink(dir.toPath())
|
||||||
}
|
}
|
||||||
|
|
||||||
fun removeOlder(context: Context, tool: Tool) {
|
fun removeOlder(context: Context, tool: Tool) {
|
||||||
installedAll(context, tool).dropLast(1).forEach {
|
installedAll(context, tool).dropLast(1).forEach {
|
||||||
if (File(toolsDir(context), it).deleteRecursively()) ComponentsManager.forgetProton(context, it)
|
if (deleteTool(context, it)) ComponentsManager.forgetProton(context, it)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// DroidDeck-Bionic: the default and the game picks name the installed build, also when they were left on one an
|
||||||
|
// older app deleted without moving them.
|
||||||
|
private fun keepBionicCurrent(context: Context) {
|
||||||
|
if (SessionState.running) return
|
||||||
|
val tool = tools.firstOrNull { it.id == BIONIC } ?: return
|
||||||
|
val newest = installedAll(context, tool).lastOrNull() ?: return
|
||||||
|
runCatching { ProtonDefault.keepBionicCurrent(context, tool.prefix, newest) }.onFailure { Log.w(TAG, "bionic default and picks", it) }
|
||||||
|
}
|
||||||
|
|
||||||
private fun replaceOlder(context: Context, tool: Tool) {
|
private fun replaceOlder(context: Context, tool: Tool) {
|
||||||
val all = installedAll(context, tool)
|
val all = installedAll(context, tool)
|
||||||
val newest = all.lastOrNull() ?: return
|
val newest = all.lastOrNull() ?: return
|
||||||
@@ -194,7 +220,9 @@ object ProtonExtras {
|
|||||||
if (runCatching { ComponentsManager.carryOver(context, old, newest) }.onFailure { Log.w(TAG, "components of $old", it) }.isFailure) continue
|
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 { 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 (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)
|
// DroidDeck-Bionic only: the guest finds no default for a deleted Bionic build and falls back to DroidDeck-Proton
|
||||||
|
if (tool.id == BIONIC && runCatching { ProtonDefault.moveDefault(context, setOf(old), newest) }.onFailure { Log.w(TAG, "default pick of $old", it) }.isFailure) continue
|
||||||
|
if (deleteTool(context, old)) ComponentsManager.forgetProton(context, old)
|
||||||
else Log.w(TAG, "could not remove $old")
|
else Log.w(TAG, "could not remove $old")
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
@@ -221,21 +249,24 @@ object ProtonExtras {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Synchronized
|
@Synchronized
|
||||||
fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
fun install(context: Context, tool: Tool, cancelled: java.util.function.BooleanSupplier? = null,
|
||||||
|
onProgress: (String, Int) -> Unit): String? {
|
||||||
if (installInProgress || prefetching) return context.getString(R.string.pextra_busy)
|
if (installInProgress || prefetching) return context.getString(R.string.pextra_busy)
|
||||||
installInProgress = true
|
installInProgress = true
|
||||||
return try { installNow(context, tool, onProgress) } finally { installInProgress = false }
|
return try { installNow(context, tool, cancelled, onProgress) } finally { installInProgress = false }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun fetchArchive(context: Context, tool: Tool, asset: Asset, archive: File, onProgress: (String, Int) -> Unit): String? {
|
private fun fetchArchive(context: Context, tool: Tool, asset: Asset, archive: File, onProgress: (String, Int) -> Unit,
|
||||||
|
cancelled: java.util.function.BooleanSupplier? = null): String? {
|
||||||
val downloading = context.getString(R.string.pextra_downloading, tool.name, asset.tag)
|
val downloading = context.getString(R.string.pextra_downloading, tool.name, asset.tag)
|
||||||
onProgress(downloading, 0)
|
onProgress(downloading, 0)
|
||||||
var downloaded = false
|
var downloaded = false
|
||||||
for (attempt in 0 until 5) {
|
for (attempt in 0 until 5) {
|
||||||
downloaded = Downloader.downloadFile(asset.url, archive, true, asset.sha256) { fraction ->
|
downloaded = Downloader.downloadFile(asset.url, archive, true, asset.sha256, cancelled) { fraction ->
|
||||||
onProgress(downloading, if (fraction < 0) -1 else (fraction * 100f).toInt().coerceIn(0, 100))
|
onProgress(downloading, if (fraction < 0) -1 else (fraction * 100f).toInt().coerceIn(0, 100))
|
||||||
}
|
}
|
||||||
if (downloaded) break
|
if (downloaded) break
|
||||||
|
if (cancelled?.asBoolean == true) return context.getString(R.string.pextra_interrupted)
|
||||||
if (attempt < 4) {
|
if (attempt < 4) {
|
||||||
onProgress(context.getString(R.string.pextra_retrying, attempt + 2, 5), -1)
|
onProgress(context.getString(R.string.pextra_retrying, attempt + 2, 5), -1)
|
||||||
try { Thread.sleep(3_000) } catch (_: InterruptedException) {
|
try { Thread.sleep(3_000) } catch (_: InterruptedException) {
|
||||||
@@ -269,7 +300,8 @@ object ProtonExtras {
|
|||||||
return problem
|
return problem
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
private fun installNow(context: Context, tool: Tool, cancelled: java.util.function.BooleanSupplier?,
|
||||||
|
onProgress: (String, Int) -> Unit): String? {
|
||||||
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
|
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
|
||||||
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
|
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
|
||||||
|
|
||||||
@@ -284,7 +316,7 @@ object ProtonExtras {
|
|||||||
|
|
||||||
val checked = asset.sha256 != null && asset.size > 0 && checkedArchive == fingerprint(archive) &&
|
val checked = asset.sha256 != null && asset.size > 0 && checkedArchive == fingerprint(archive) &&
|
||||||
checkedDigest.equals(asset.sha256, ignoreCase = true)
|
checkedDigest.equals(asset.sha256, ignoreCase = true)
|
||||||
if (!checked) fetchArchive(context, tool, asset, archive, onProgress)?.let { return it }
|
if (!checked) fetchArchive(context, tool, asset, archive, onProgress, cancelled)?.let { return it }
|
||||||
if (asset.size > 0 && archive.length() != asset.size) {
|
if (asset.size > 0 && archive.length() != asset.size) {
|
||||||
if (archive.length() > asset.size) {
|
if (archive.length() > asset.size) {
|
||||||
archive.delete()
|
archive.delete()
|
||||||
@@ -342,7 +374,7 @@ 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 (tool.id == OWN || tool.id == BIONIC) 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 {
|
||||||
@@ -427,7 +459,7 @@ object ProtonExtras {
|
|||||||
internal fun pickAsset(tool: Tool, array: JSONArray): Asset? {
|
internal fun pickAsset(tool: Tool, array: JSONArray): Asset? {
|
||||||
val candidates = (0 until array.length()).asSequence()
|
val candidates = (0 until array.length()).asSequence()
|
||||||
.mapNotNull { array.optJSONObject(it) }
|
.mapNotNull { array.optJSONObject(it) }
|
||||||
.filter { !it.optBoolean("draft", false) && !it.optBoolean("prerelease", false) }
|
.filter { !it.optBoolean("draft", false) && (tool.prereleases || !it.optBoolean("prerelease", false)) }
|
||||||
return candidates.firstNotNullOfOrNull { assetOf(tool, it) }
|
return candidates.firstNotNullOfOrNull { assetOf(tool, it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -75,6 +75,7 @@ object SessionArtifacts {
|
|||||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||||
val record = Record(dir)
|
val record = Record(dir)
|
||||||
copySteamLogs(context, dir, record, steamArch)
|
copySteamLogs(context, dir, record, steamArch)
|
||||||
|
copyRpcs3Log(context, dir, record)
|
||||||
VacDiagnostics.collect(context, dir)
|
VacDiagnostics.collect(context, dir)
|
||||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||||
SessionLogCapture.dumpMemoryPressure(File(dir, "memory-pressure.log"))
|
SessionLogCapture.dumpMemoryPressure(File(dir, "memory-pressure.log"))
|
||||||
@@ -321,6 +322,9 @@ object SessionArtifacts {
|
|||||||
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 LOG_MARKS = "steam-log-marks.txt"
|
||||||
|
private const val RPCS3_LOG_MARKS = "rpcs3-log-marks.txt"
|
||||||
|
private const val RPCS3_LOGS = "root/.cache/rpcs3"
|
||||||
|
private const val RPCS3_LOG = "RPCS3.log"
|
||||||
private const val MAX_STEAM_LOG = 8L * 1024 * 1024
|
private const val MAX_STEAM_LOG = 8L * 1024 * 1024
|
||||||
private const val HEAD = 4096L
|
private const val HEAD = 4096L
|
||||||
|
|
||||||
@@ -328,11 +332,19 @@ object SessionArtifacts {
|
|||||||
private class CopyResult(val files: List<File>, val failed: Boolean, val deferred: Boolean)
|
private class CopyResult(val files: List<File>, val failed: Boolean, val deferred: Boolean)
|
||||||
|
|
||||||
fun markSteamLogs(dir: File, logs: File) {
|
fun markSteamLogs(dir: File, logs: File) {
|
||||||
val lines = logs.listFiles { f -> f.isFile }?.mapNotNull { f ->
|
logs.listFiles { f -> f.isFile }?.let { markLogs(dir, LOG_MARKS, it.toList()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun markRpcs3Log(dir: File, root: File) {
|
||||||
|
markLogs(dir, RPCS3_LOG_MARKS, listOf(File(root, "$RPCS3_LOGS/$RPCS3_LOG")).filter { it.isFile })
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun markLogs(dir: File, marks: String, files: List<File>) {
|
||||||
|
val lines = files.mapNotNull { f ->
|
||||||
val size = f.length()
|
val size = f.length()
|
||||||
head(f, size)?.let { "$size\t$it\t${f.name}" }
|
head(f, size)?.let { "$size\t$it\t${f.name}" }
|
||||||
} ?: return
|
}
|
||||||
runCatching { File(dir, LOG_MARKS).writeText(lines.joinToString("") { "$it\n" }) }
|
runCatching { File(dir, marks).writeText(lines.joinToString("") { "$it\n" }) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun head(f: File, length: Long): String? = runCatching {
|
private fun head(f: File, length: Long): String? = runCatching {
|
||||||
@@ -348,8 +360,8 @@ object SessionArtifacts {
|
|||||||
java.security.MessageDigest.getInstance("SHA-1").digest(buf).joinToString("") { "%02x".format(it) }
|
java.security.MessageDigest.getInstance("SHA-1").digest(buf).joinToString("") { "%02x".format(it) }
|
||||||
}.getOrNull()
|
}.getOrNull()
|
||||||
|
|
||||||
private fun steamLogMarks(dir: File): List<Mark>? = runCatching {
|
private fun logMarks(dir: File, marks: String): List<Mark>? = runCatching {
|
||||||
File(dir, LOG_MARKS).readLines().mapNotNull { line ->
|
File(dir, marks).readLines().mapNotNull { line ->
|
||||||
val parts = line.split('\t', limit = 3)
|
val parts = line.split('\t', limit = 3)
|
||||||
parts.getOrNull(0)?.toLongOrNull()?.let { size -> parts.getOrNull(1)?.let { Mark(size, it) } }
|
parts.getOrNull(0)?.toLongOrNull()?.let { size -> parts.getOrNull(1)?.let { Mark(size, it) } }
|
||||||
}
|
}
|
||||||
@@ -371,11 +383,32 @@ object SessionArtifacts {
|
|||||||
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() }
|
||||||
val result = copySessionLogsResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running }
|
addCopied(record, copySessionLogsResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running })
|
||||||
|
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun copyRpcs3Log(context: Context, dir: File, record: Record, stopWhenSessionStarts: Boolean = false) {
|
||||||
|
val out = File(dir, "rpcs3")
|
||||||
|
val logs = File(LinuxRuntime.rootDir(context), RPCS3_LOGS)
|
||||||
|
val copied = copyRpcs3LogResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running } ?: return
|
||||||
|
addCopied(record, copied)
|
||||||
|
if (copied.files.isNotEmpty()) Log.i(TAG, "collected RPCS3's log, scrubbed, into $out")
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun copyRpcs3Log(logs: File, dir: File, out: File): List<File> = copyRpcs3LogResult(logs, dir, out) { false }?.files.orEmpty()
|
||||||
|
|
||||||
|
private fun copyRpcs3LogResult(logs: File, dir: File, out: File, shouldStop: () -> Boolean): CopyResult? {
|
||||||
|
if (!File(dir, RPCS3_LOG_MARKS).isFile || !File(logs, RPCS3_LOG).isFile) return null
|
||||||
|
out.mkdirs()
|
||||||
|
val result = copySessionLogsResult(logs, dir, out, marksName = RPCS3_LOG_MARKS, accept = { it.name == RPCS3_LOG }, shouldStop = shouldStop)
|
||||||
|
if (result.files.isEmpty()) out.delete()
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun addCopied(record: Record, result: CopyResult) {
|
||||||
result.files.forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) }
|
result.files.forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) }
|
||||||
record.failed = record.failed || result.failed
|
record.failed = record.failed || result.failed
|
||||||
record.deferred = record.deferred || result.deferred
|
record.deferred = record.deferred || result.deferred
|
||||||
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun copySessionLogs(
|
internal fun copySessionLogs(
|
||||||
@@ -383,20 +416,22 @@ object SessionArtifacts {
|
|||||||
dir: File,
|
dir: File,
|
||||||
out: File,
|
out: File,
|
||||||
openWriter: (File) -> Writer = { it.bufferedWriter() },
|
openWriter: (File) -> Writer = { it.bufferedWriter() },
|
||||||
): List<File> = copySessionLogsResult(logs, dir, out, openWriter) { false }.files
|
): List<File> = copySessionLogsResult(logs, dir, out, openWriter = openWriter) { false }.files
|
||||||
|
|
||||||
private fun copySessionLogsResult(
|
private fun copySessionLogsResult(
|
||||||
logs: File,
|
logs: File,
|
||||||
dir: File,
|
dir: File,
|
||||||
out: File,
|
out: File,
|
||||||
|
marksName: String = LOG_MARKS,
|
||||||
|
accept: (File) -> Boolean = { true },
|
||||||
openWriter: (File) -> Writer = { it.bufferedWriter() },
|
openWriter: (File) -> Writer = { it.bufferedWriter() },
|
||||||
shouldStop: () -> Boolean,
|
shouldStop: () -> Boolean,
|
||||||
): CopyResult {
|
): CopyResult {
|
||||||
val marks = steamLogMarks(dir)
|
val marks = logMarks(dir, marksName)
|
||||||
val copied = ArrayList<File>()
|
val copied = ArrayList<File>()
|
||||||
var failed = false
|
var failed = false
|
||||||
var deferred = false
|
var deferred = false
|
||||||
val sources = logs.listFiles { f -> f.isFile } ?: return CopyResult(copied, true, false)
|
val sources = logs.listFiles { f -> f.isFile && accept(f) } ?: return CopyResult(copied, true, false)
|
||||||
for (src in sources) {
|
for (src in sources) {
|
||||||
if (shouldStop()) {
|
if (shouldStop()) {
|
||||||
failed = true
|
failed = true
|
||||||
@@ -567,6 +602,7 @@ object SessionArtifacts {
|
|||||||
steamArch = recordedClient(dir),
|
steamArch = recordedClient(dir),
|
||||||
stopWhenSessionStarts = stopWhenSessionStarts,
|
stopWhenSessionStarts = stopWhenSessionStarts,
|
||||||
)
|
)
|
||||||
|
copyRpcs3Log(context, dir, record, stopWhenSessionStarts)
|
||||||
if (!record.deferred && (!stopWhenSessionStarts || !SessionState.running)) {
|
if (!record.deferred && (!stopWhenSessionStarts || !SessionState.running)) {
|
||||||
if (!record.failed && VacDiagnostics.collect(context, dir)) {
|
if (!record.failed && VacDiagnostics.collect(context, dir)) {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -28,12 +28,14 @@ object SessionFiles {
|
|||||||
"usr/local/bin/droiddeck-bottom-desktop" to "usr/local/bin/droiddeck-bottom-desktop",
|
"usr/local/bin/droiddeck-bottom-desktop" to "usr/local/bin/droiddeck-bottom-desktop",
|
||||||
"usr/local/bin/droiddeck-gpu" to "usr/local/bin/droiddeck-gpu",
|
"usr/local/bin/droiddeck-gpu" to "usr/local/bin/droiddeck-gpu",
|
||||||
"usr/local/bin/droiddeck-desktop-gpu" to "usr/local/bin/droiddeck-desktop-gpu",
|
"usr/local/bin/droiddeck-desktop-gpu" to "usr/local/bin/droiddeck-desktop-gpu",
|
||||||
|
"usr/local/bin/droiddeck-device-info" to "usr/local/bin/droiddeck-device-info",
|
||||||
"usr/local/bin/droiddeck-desktop-window-rules" to "usr/local/bin/droiddeck-desktop-window-rules",
|
"usr/local/bin/droiddeck-desktop-window-rules" to "usr/local/bin/droiddeck-desktop-window-rules",
|
||||||
"usr/local/bin/droiddeck-library-perms" to "usr/local/bin/droiddeck-library-perms",
|
"usr/local/bin/droiddeck-library-perms" to "usr/local/bin/droiddeck-library-perms",
|
||||||
"usr/local/bin/droiddeck-ime" to "usr/local/bin/droiddeck-ime",
|
"usr/local/bin/droiddeck-ime" to "usr/local/bin/droiddeck-ime",
|
||||||
"usr/local/bin/kwin_wayland_wrapper" to "usr/local/bin/kwin_wayland_wrapper",
|
"usr/local/bin/kwin_wayland_wrapper" to "usr/local/bin/kwin_wayland_wrapper",
|
||||||
"usr/lib/firefox/defaults/pref/droiddeck.js" to "usr/lib/firefox/defaults/pref/droiddeck.js",
|
"usr/lib/firefox/defaults/pref/droiddeck.js" to "usr/lib/firefox/defaults/pref/droiddeck.js",
|
||||||
"etc/xdg/autostart/droiddeck-clipboard.desktop" to "etc/xdg/autostart/droiddeck-clipboard.desktop",
|
"etc/xdg/autostart/droiddeck-clipboard.desktop" to "etc/xdg/autostart/droiddeck-clipboard.desktop",
|
||||||
|
"etc/xdg/fastfetch/config.jsonc" to "etc/xdg/fastfetch/config.jsonc",
|
||||||
)
|
)
|
||||||
|
|
||||||
private val SERVICE_PACKS = mapOf(
|
private val SERVICE_PACKS = mapOf(
|
||||||
@@ -143,6 +145,7 @@ object SessionFiles {
|
|||||||
"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",
|
||||||
"usr/local/bin/droiddeck-netmanager" to "usr/local/bin/droiddeck-netmanager",
|
"usr/local/bin/droiddeck-netmanager" to "usr/local/bin/droiddeck-netmanager",
|
||||||
"usr/local/bin/droiddeck-login1" to "usr/local/bin/droiddeck-login1",
|
"usr/local/bin/droiddeck-login1" to "usr/local/bin/droiddeck-login1",
|
||||||
|
"usr/local/bin/droiddeck-documents" to "usr/local/bin/droiddeck-documents",
|
||||||
"usr/local/bin/droiddeck-steam-launch" to "usr/local/bin/droiddeck-steam-launch",
|
"usr/local/bin/droiddeck-steam-launch" to "usr/local/bin/droiddeck-steam-launch",
|
||||||
"usr/local/bin/droiddeck-desktop-games" to "usr/local/bin/droiddeck-desktop-games",
|
"usr/local/bin/droiddeck-desktop-games" to "usr/local/bin/droiddeck-desktop-games",
|
||||||
"usr/local/bin/droiddeck-desktop-programs" to "usr/local/bin/droiddeck-desktop-programs",
|
"usr/local/bin/droiddeck-desktop-programs" to "usr/local/bin/droiddeck-desktop-programs",
|
||||||
@@ -154,6 +157,7 @@ object SessionFiles {
|
|||||||
"usr/local/bin/droiddeck-emulators" to "usr/local/bin/droiddeck-emulators",
|
"usr/local/bin/droiddeck-emulators" to "usr/local/bin/droiddeck-emulators",
|
||||||
"usr/local/bin/droiddeck-snap-run" to "usr/local/bin/droiddeck-snap-run",
|
"usr/local/bin/droiddeck-snap-run" to "usr/local/bin/droiddeck-snap-run",
|
||||||
"usr/local/bin/droiddeck-snap-confine" to "usr/local/bin/droiddeck-snap-confine",
|
"usr/local/bin/droiddeck-snap-confine" to "usr/local/bin/droiddeck-snap-confine",
|
||||||
|
"usr/local/bin/droiddeck-diversion-stub" to "usr/local/bin/droiddeck-diversion-stub",
|
||||||
"usr/local/bin/droiddeck-snapctl" to "usr/local/bin/droiddeck-snapctl",
|
"usr/local/bin/droiddeck-snapctl" to "usr/local/bin/droiddeck-snapctl",
|
||||||
"usr/local/bin/droiddeck-systemd-run" to "usr/local/bin/systemd-run",
|
"usr/local/bin/droiddeck-systemd-run" to "usr/local/bin/systemd-run",
|
||||||
"usr/local/bin/droiddeck-snap-cli" to "usr/local/bin/snap",
|
"usr/local/bin/droiddeck-snap-cli" to "usr/local/bin/snap",
|
||||||
@@ -263,7 +267,9 @@ object SessionFiles {
|
|||||||
"usr/local/share/vkbridge/droidbridge_icd.json" to "usr/local/share/vkbridge/droidbridge_icd.json",
|
"usr/local/share/vkbridge/droidbridge_icd.json" to "usr/local/share/vkbridge/droidbridge_icd.json",
|
||||||
"usr/local/bin/droiddeck-vkbridge-smoke" to "usr/local/bin/droiddeck-vkbridge-smoke",
|
"usr/local/bin/droiddeck-vkbridge-smoke" to "usr/local/bin/droiddeck-vkbridge-smoke",
|
||||||
"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/dwarfsextract" to "usr/local/lib/droiddeck/dwarfsextract",
|
||||||
"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/dwarfs/LICENSE" to "usr/local/share/licenses/dwarfs/LICENSE",
|
||||||
"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",
|
||||||
) + mangoapp + xclipse.map { it to it } + maliCompat + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) ->
|
) + mangoapp + xclipse.map { it to it } + maliCompat + msitools.map { it to it } + vr + gpuLoad + fexPreloads).filter { (asset, _) ->
|
||||||
val dir = asset.substringBeforeLast('/')
|
val dir = asset.substringBeforeLast('/')
|
||||||
|
|||||||
@@ -448,6 +448,13 @@ object SessionPrefs {
|
|||||||
prefs(context).edit().putString("navTabHidden", keys.joinToString(",")).apply()
|
prefs(context).edit().putString("navTabHidden", keys.joinToString(",")).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun appsTabHomeSeen(context: Context): Boolean? =
|
||||||
|
prefs(context).takeIf { it.contains("appsTabHomeSeen") }?.getBoolean("appsTabHomeSeen", false)
|
||||||
|
|
||||||
|
fun setAppsTabHomeSeen(context: Context, seen: Boolean) {
|
||||||
|
prefs(context).edit().putBoolean("appsTabHomeSeen", seen).apply()
|
||||||
|
}
|
||||||
|
|
||||||
private fun idList(raw: String?): List<String> = raw.orEmpty().split(',').map { it.trim() }.filter { it.isNotEmpty() }
|
private fun idList(raw: String?): List<String> = raw.orEmpty().split(',').map { it.trim() }.filter { it.isNotEmpty() }
|
||||||
|
|
||||||
val STORES_SORTS = listOf("lastPlayed", "recentlyInstalled", "titleAsc", "titleDesc", "sizeDesc", "sizeAsc", "releaseDateDesc")
|
val STORES_SORTS = listOf("lastPlayed", "recentlyInstalled", "titleAsc", "titleDesc", "sizeDesc", "sizeAsc", "releaseDateDesc")
|
||||||
@@ -814,6 +821,11 @@ object SessionPrefs {
|
|||||||
prefs(context).edit().putStringSet("gpuAutoInstalled", ids.toSet()).apply()
|
prefs(context).edit().putStringSet("gpuAutoInstalled", ids.toSet()).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun displayDriverFromAuto(context: Context): Boolean {
|
||||||
|
val id = androidDriver(context)
|
||||||
|
return id.isEmpty() || (gpuDriverMode(context) == GPU_DRIVERS_AUTO && id in gpuAutoInstalled(context))
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
fun picturePosition(context: Context): String =
|
fun picturePosition(context: Context): String =
|
||||||
prefs(context).getString("picturePosition", "center")
|
prefs(context).getString("picturePosition", "center")
|
||||||
@@ -833,6 +845,15 @@ object SessionPrefs {
|
|||||||
|
|
||||||
fun returnAfterGame(context: Context): Boolean = prefs(context).getBoolean("returnAfterGame", true)
|
fun returnAfterGame(context: Context): Boolean = prefs(context).getBoolean("returnAfterGame", true)
|
||||||
|
|
||||||
|
fun valveProtonOnDemand(context: Context): Boolean = prefs(context).getBoolean("valveProtonOnDemand", true)
|
||||||
|
|
||||||
|
fun setValveProtonOnDemand(context: Context, on: Boolean) {
|
||||||
|
prefs(context).edit().putBoolean("valveProtonOnDemand", on).apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** DroidDeck-Proton is the Proton placed before the client starts; Valve's ARM64 Proton waits for a title that needs it. */
|
||||||
|
fun ownProtonFirst(context: Context): Boolean = valveProtonOnDemand(context) && !ProtonExtras.declined(context)
|
||||||
|
|
||||||
fun setReturnAfterGame(context: Context, on: Boolean) {
|
fun setReturnAfterGame(context: Context, on: Boolean) {
|
||||||
prefs(context).edit().putBoolean("returnAfterGame", on).apply()
|
prefs(context).edit().putBoolean("returnAfterGame", on).apply()
|
||||||
}
|
}
|
||||||
@@ -1037,7 +1058,7 @@ object SessionPrefs {
|
|||||||
prefs(context).edit().putBoolean("prootFastPath", on).apply()
|
prefs(context).edit().putBoolean("prootFastPath", on).apply()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun cursorComposite(context: Context): Boolean = prefs(context).getBoolean("cursorComposite", false)
|
fun cursorComposite(context: Context): Boolean = prefs(context).getBoolean("cursorComposite", true)
|
||||||
|
|
||||||
fun setCursorComposite(context: Context, on: Boolean) {
|
fun setCursorComposite(context: Context, on: Boolean) {
|
||||||
prefs(context).edit().putBoolean("cursorComposite", on).apply()
|
prefs(context).edit().putBoolean("cursorComposite", on).apply()
|
||||||
@@ -1343,6 +1364,10 @@ object SessionPrefs {
|
|||||||
SessionDisplay.effectiveChoice(
|
SessionDisplay.effectiveChoice(
|
||||||
resolutionStored(context, mode, panel, false), resolutionStored(context, mode, panel, true), portrait)
|
resolutionStored(context, mode, panel, false), resolutionStored(context, mode, panel, true), portrait)
|
||||||
|
|
||||||
|
fun followScales(context: Context, mode: String, panel: Pair<Int, Int>): Pair<Float?, Float?> =
|
||||||
|
SessionDisplay.followScale(resolutionChoice(context, mode, panel, false)) to
|
||||||
|
SessionDisplay.followScale(resolutionChoice(context, mode, panel, true))
|
||||||
|
|
||||||
fun resolutionStored(context: Context, mode: String, panel: Pair<Int, Int>, portrait: Boolean): String {
|
fun resolutionStored(context: Context, mode: String, panel: Pair<Int, Int>, portrait: Boolean): String {
|
||||||
if (!portrait) return landscapeResolutionStored(context, mode, panel)
|
if (!portrait) return landscapeResolutionStored(context, mode, panel)
|
||||||
val value = prefs(context).getString("displayResolution.portrait.$mode", null) ?: return SessionDisplay.LINK_LANDSCAPE
|
val value = prefs(context).getString("displayResolution.portrait.$mode", null) ?: return SessionDisplay.LINK_LANDSCAPE
|
||||||
@@ -1553,7 +1578,7 @@ object SessionPrefs {
|
|||||||
fun adoptAddedGameExe(context: Context, folderPath: String, expected: String, path: String, seen: Int): Boolean =
|
fun adoptAddedGameExe(context: Context, folderPath: String, expected: String, path: String, seen: Int): Boolean =
|
||||||
synchronized(addedGameLock) {
|
synchronized(addedGameLock) {
|
||||||
val unchanged = addedGameExe(context, folderPath) == expected
|
val unchanged = addedGameExe(context, folderPath) == expected
|
||||||
if (unchanged) prefs(context).edit().putString("addedExe:$folderPath", path).putInt("addedExeSeen:$folderPath", seen).apply()
|
if (unchanged) prefs(context).edit().putString("addedExe:$folderPath", path).putString("addedAdopted:Exe:$folderPath", path).putInt("addedExeSeen:$folderPath", seen).apply()
|
||||||
unchanged
|
unchanged
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -669,6 +669,8 @@ class SessionService : Service() {
|
|||||||
guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=100")
|
guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=100")
|
||||||
guest.add("WINE_OFFSCREEN_CHECK_MS=100")
|
guest.add("WINE_OFFSCREEN_CHECK_MS=100")
|
||||||
guest.add("DD_REFRESH=" + Math.round(SessionState.refreshHz))
|
guest.add("DD_REFRESH=" + Math.round(SessionState.refreshHz))
|
||||||
|
guest.add("DD_DEVICE_NAME=" + android.os.Build.MODEL)
|
||||||
|
com.droiddeck.launcher.gpu.SocNames.plainName().takeIf { it.isNotEmpty() }?.let { guest.add("DD_SOC_NAME=$it") }
|
||||||
guest.add("DD_LOG=" + sessionLog.path)
|
guest.add("DD_LOG=" + sessionLog.path)
|
||||||
guest.add("DD_DEBUG_DIR=" + sessionDir.path)
|
guest.add("DD_DEBUG_DIR=" + sessionDir.path)
|
||||||
if (EnhancedDiagnostics.isActive(this, sessionDir)) guest.add("DROIDDECK_ENHANCED_DIAGNOSTICS=1")
|
if (EnhancedDiagnostics.isActive(this, sessionDir)) guest.add("DROIDDECK_ENHANCED_DIAGNOSTICS=1")
|
||||||
@@ -694,7 +696,7 @@ class SessionService : Service() {
|
|||||||
val added = SessionEvents.step("added-games-scan") { com.droiddeck.launcher.frontend.AddedGames.scan(this) }
|
val added = SessionEvents.step("added-games-scan") { com.droiddeck.launcher.frontend.AddedGames.scan(this) }
|
||||||
val listing = SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) }
|
val listing = SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) }
|
||||||
guest.add("DD_ADDED_GAMES=" + listing.path)
|
guest.add("DD_ADDED_GAMES=" + listing.path)
|
||||||
if (OfflineMode.enabled(this)) guest.add("DD_STEAM_OFFLINE=1")
|
if (OfflineMode.active(this)) guest.add("DD_STEAM_OFFLINE=1")
|
||||||
if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("DD_LOSSLESS_OWNED=1")
|
if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("DD_LOSSLESS_OWNED=1")
|
||||||
if (added.isNotEmpty()) Log.i(TAG, "added games: " + added.joinToString { "${it.name} (${it.exe.name})" })
|
if (added.isNotEmpty()) Log.i(TAG, "added games: " + added.joinToString { "${it.name} (${it.exe.name})" })
|
||||||
}
|
}
|
||||||
@@ -784,7 +786,7 @@ class SessionService : Service() {
|
|||||||
if (drives > 0) Log.i(TAG, "$drives Wine drive links given their guest paths back")
|
if (drives > 0) Log.i(TAG, "$drives Wine drive links given their guest paths back")
|
||||||
val hostEnv = if (nativeUserland) HostEnvironment().also { env ->
|
val hostEnv = if (nativeUserland) HostEnvironment().also { env ->
|
||||||
Log.i(TAG, "native userland: no proot (${sessionBindSpecs.size} mounts)")
|
Log.i(TAG, "native userland: no proot (${sessionBindSpecs.size} mounts)")
|
||||||
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, SessionPrefs.guestHostname(this))
|
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, guest.first(), SessionPrefs.guestHostname(this))
|
||||||
.forEach { (k, v) -> env[k] = v }
|
.forEach { (k, v) -> env[k] = v }
|
||||||
} else prootEnv
|
} else prootEnv
|
||||||
|
|
||||||
@@ -813,6 +815,11 @@ class SessionService : Service() {
|
|||||||
.onFailure { Log.w(TAG, "desktop language pack: $it") }
|
.onFailure { Log.w(TAG, "desktop language pack: $it") }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (SessionState.mode == MODE_STEAM || SessionState.mode == MODE_DESKTOP) {
|
||||||
|
val steamOffline = SteamOfflineFollow()
|
||||||
|
steamOffline.attach(this)
|
||||||
|
components.add(steamOffline)
|
||||||
|
}
|
||||||
val networkLink = LinuxNetworkLinkComponent(this, root)
|
val networkLink = LinuxNetworkLinkComponent(this, root)
|
||||||
networkLink.attach(this)
|
networkLink.attach(this)
|
||||||
networkLink.publish()
|
networkLink.publish()
|
||||||
@@ -1002,6 +1009,7 @@ class SessionService : Service() {
|
|||||||
))
|
))
|
||||||
guest.add("TZ=" + java.util.TimeZone.getDefault().id)
|
guest.add("TZ=" + java.util.TimeZone.getDefault().id)
|
||||||
if (SessionState.mode == MODE_STEAM) SessionPrefs.pendingShaderPrecache(this)?.let { guest.add("DD_SHADER_PRECACHE=" + if (it) "1" else "0") }
|
if (SessionState.mode == MODE_STEAM) SessionPrefs.pendingShaderPrecache(this)?.let { guest.add("DD_SHADER_PRECACHE=" + if (it) "1" else "0") }
|
||||||
|
guest.add("DD_VALVE_PROTON=" + if (SessionPrefs.ownProtonFirst(this)) "0" else "1")
|
||||||
guest.add("XDG_RUNTIME_DIR=" + LinuxRuntime.GUEST_RUNTIME_DIR)
|
guest.add("XDG_RUNTIME_DIR=" + LinuxRuntime.GUEST_RUNTIME_DIR)
|
||||||
guest.add("XDG_SESSION_TYPE=wayland")
|
guest.add("XDG_SESSION_TYPE=wayland")
|
||||||
guest.add("WAYLAND_DISPLAY=wayland-0")
|
guest.add("WAYLAND_DISPLAY=wayland-0")
|
||||||
@@ -1033,6 +1041,9 @@ class SessionService : Service() {
|
|||||||
)
|
)
|
||||||
(if (bridge || venus) null else LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId))
|
(if (bridge || venus) null else LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId))
|
||||||
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
|
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
|
||||||
|
// DroidDeck-Bionic games load an Android driver build; this is the one the display uses, for a runtime driver
|
||||||
|
// that has none.
|
||||||
|
guest.add("DROIDDECK_DISPLAY_DRIVER=" + com.droiddeck.launcher.gpu.TurnipDriver(this).effectiveId())
|
||||||
if (!com.droiddeck.launcher.core.DeviceSupport.adreno() && lastXwaylandCrashed()) {
|
if (!com.droiddeck.launcher.core.DeviceSupport.adreno() && lastXwaylandCrashed()) {
|
||||||
guest.add("XWAYLAND_NO_GLAMOR=1")
|
guest.add("XWAYLAND_NO_GLAMOR=1")
|
||||||
Log.w(TAG, "xwayland: the last session's Xwayland crashed; glamor off for this one (XWAYLAND_NO_GLAMOR=1)")
|
Log.w(TAG, "xwayland: the last session's Xwayland crashed; glamor off for this one (XWAYLAND_NO_GLAMOR=1)")
|
||||||
@@ -1070,6 +1081,7 @@ class SessionService : Service() {
|
|||||||
guest.addAll(GpuStatsComponent.guestEnv(LinuxRuntime.rootDir(this)))
|
guest.addAll(GpuStatsComponent.guestEnv(LinuxRuntime.rootDir(this)))
|
||||||
guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216")
|
guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216")
|
||||||
if (SessionState.mode == MODE_STEAM) guest.add("DD_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0"))
|
if (SessionState.mode == MODE_STEAM) guest.add("DD_MANGOAPP=" + (if (SessionPrefs.mangoapp(this)) "1" else "0"))
|
||||||
|
SessionPaths.current()?.let { SessionArtifacts.markRpcs3Log(it, LinuxRuntime.rootDir(this)) }
|
||||||
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("DD_STEAM_CLIENT_ARCH=$arch")
|
guest.add("DD_STEAM_CLIENT_ARCH=$arch")
|
||||||
@@ -1263,6 +1275,7 @@ class SessionService : Service() {
|
|||||||
components.add(hwmon)
|
components.add(hwmon)
|
||||||
binds.add(hwmon.dir.path + ":/sys/class/hwmon")
|
binds.add(hwmon.dir.path + ":/sys/class/hwmon")
|
||||||
}
|
}
|
||||||
|
binds.addAll(CpuCacheSysfs.binds(File(filesDir, "session/sys/cpu-cache")))
|
||||||
val cpuStat = CpuStatComponent(File(filesDir, "session/proc-stat"))
|
val cpuStat = CpuStatComponent(File(filesDir, "session/proc-stat"))
|
||||||
if (cpuStat.prepare()) {
|
if (cpuStat.prepare()) {
|
||||||
cpuStat.attach(this)
|
cpuStat.attach(this)
|
||||||
|
|||||||
@@ -148,6 +148,9 @@ object SessionState {
|
|||||||
@Volatile
|
@Volatile
|
||||||
var outputSize: Pair<Int, Int> = Pair(1920, 1080)
|
var outputSize: Pair<Int, Int> = Pair(1920, 1080)
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
var followScales: Pair<Float?, Float?> = null to null
|
||||||
|
|
||||||
@Volatile
|
@Volatile
|
||||||
var followScreen = false
|
var followScreen = false
|
||||||
var followScale = 1f
|
var followScale = 1f
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ object SettingsReset {
|
|||||||
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "nativeUserland", "cursorComposite",
|
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "nativeUserland", "cursorComposite",
|
||||||
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics", "buildWatermark",
|
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics", "buildWatermark",
|
||||||
"upscaler", "upscaleSharpness", "screenEffects", "blackFrameInsertion", "textureAnisotropy", "textureLodBias",
|
"upscaler", "upscaleSharpness", "screenEffects", "blackFrameInsertion", "textureAnisotropy", "textureLodBias",
|
||||||
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds", "skipBootMovie",
|
"steamDownloadsInBackground", "steam_offline", "steam_offline_auto", "steam_offline_by_network", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds", "skipBootMovie",
|
||||||
"bootMovieApplyNext", "bootMovieSteamSeen", "bootMovieShuffle",
|
"bootMovieApplyNext", "bootMovieSteamSeen", "bootMovieShuffle",
|
||||||
"questDefaultsV1", "telemetryAuto", "telemetryOff", "statsStrip", "statsHud", "bottomHud", "bottomStripMetrics", "bottomStripTabs", "statsDash", "statsSpeedUnit",
|
"questDefaultsV1", "telemetryAuto", "telemetryOff", "statsStrip", "statsHud", "bottomHud", "bottomStripMetrics", "bottomStripTabs", "statsDash", "statsSpeedUnit",
|
||||||
)
|
)
|
||||||
@@ -67,7 +67,7 @@ object SettingsReset {
|
|||||||
}
|
}
|
||||||
|
|
||||||
QuestExperimental.initialize(context)
|
QuestExperimental.initialize(context)
|
||||||
runCatching { OfflineMode.apply(context, LinuxRuntime.rootDir(context)) }
|
runCatching { OfflineMode.setEnabled(context, false) }
|
||||||
.onFailure { ok = false; Log.w(TAG, "Could not turn offline mode off", it) }
|
.onFailure { ok = false; Log.w(TAG, "Could not turn offline mode off", it) }
|
||||||
runCatching { GameEnvironmentStore.publish(context) }
|
runCatching { GameEnvironmentStore.publish(context) }
|
||||||
.onFailure { ok = false; Log.w(TAG, "Could not update game environment", it) }
|
.onFailure { ok = false; Log.w(TAG, "Could not update game environment", it) }
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package com.droiddeck.launcher.session
|
||||||
|
|
||||||
|
import android.net.ConnectivityManager
|
||||||
|
import android.net.Network
|
||||||
|
import android.net.NetworkCapabilities
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.HandlerThread
|
||||||
|
import android.util.Log
|
||||||
|
import com.droiddeck.launcher.core.SessionPart
|
||||||
|
import com.droiddeck.launcher.frontend.AutoComponents
|
||||||
|
|
||||||
|
class SteamOfflineFollow : SessionPart() {
|
||||||
|
private var thread: HandlerThread? = null
|
||||||
|
@Volatile private var handler: Handler? = null
|
||||||
|
private var callback: ConnectivityManager.NetworkCallback? = null
|
||||||
|
private var online: Boolean? = null
|
||||||
|
private var retries = 0
|
||||||
|
private var requested = false
|
||||||
|
|
||||||
|
private val check = object : Runnable {
|
||||||
|
override fun run() {
|
||||||
|
val handler = handler ?: return
|
||||||
|
if (SessionState.running && SessionState.suspended) {
|
||||||
|
handler.postDelayed(this, SUSPENDED_POLL_MS)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val result = if (requested) OfflineMode.sync(app()) else OfflineMode.follow(app())
|
||||||
|
if (result != null) requested = false
|
||||||
|
if (result == null && retries < MAX_RETRIES) {
|
||||||
|
retries++
|
||||||
|
handler.postDelayed(this, RETRY_MS)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun start() {
|
||||||
|
val started = HandlerThread("steam-offline").also { it.start() }
|
||||||
|
val handler = Handler(started.looper)
|
||||||
|
thread = started
|
||||||
|
this.handler = handler
|
||||||
|
val registered = object : ConnectivityManager.NetworkCallback() {
|
||||||
|
override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) =
|
||||||
|
changed(capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
|
||||||
|
capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED))
|
||||||
|
override fun onLost(network: Network) = changed(false)
|
||||||
|
}
|
||||||
|
callback = registered
|
||||||
|
active = this
|
||||||
|
online = AutoComponents.isOnline(app())
|
||||||
|
app().getSystemService(ConnectivityManager::class.java).registerDefaultNetworkCallback(registered, handler)
|
||||||
|
sync()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun changed(now: Boolean) {
|
||||||
|
val handler = handler ?: return
|
||||||
|
if (now == online) return
|
||||||
|
online = now
|
||||||
|
handler.removeCallbacks(check)
|
||||||
|
retries = 0
|
||||||
|
if (OfflineMode.auto(app())) requested = false
|
||||||
|
handler.postDelayed(check, if (now) ONLINE_DELAY_MS else OFFLINE_DELAY_MS)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sync() {
|
||||||
|
handler?.post {
|
||||||
|
val handler = handler ?: return@post
|
||||||
|
handler.removeCallbacks(check)
|
||||||
|
retries = 0
|
||||||
|
requested = true
|
||||||
|
handler.post(check)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun stop() {
|
||||||
|
if (active === this) active = null
|
||||||
|
val registered = callback
|
||||||
|
callback = null
|
||||||
|
if (registered != null) {
|
||||||
|
try {
|
||||||
|
app().getSystemService(ConnectivityManager::class.java).unregisterNetworkCallback(registered)
|
||||||
|
} catch (e: IllegalArgumentException) {
|
||||||
|
Log.w(TAG, "network callback was already gone", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
handler?.removeCallbacksAndMessages(null)
|
||||||
|
handler = null
|
||||||
|
thread?.quitSafely()
|
||||||
|
thread = null
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val TAG = "SteamOfflineFollow"
|
||||||
|
@Volatile private var active: SteamOfflineFollow? = null
|
||||||
|
const val ONLINE_DELAY_MS = 2_000L
|
||||||
|
const val OFFLINE_DELAY_MS = 10_000L
|
||||||
|
const val RETRY_MS = 15_000L
|
||||||
|
const val MAX_RETRIES = 8
|
||||||
|
const val SUSPENDED_POLL_MS = 1_000L
|
||||||
|
|
||||||
|
fun request() {
|
||||||
|
active?.sync()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -113,7 +113,7 @@ object CloudSaves {
|
|||||||
}
|
}
|
||||||
Store.UBISOFT -> UBISOFT_TEMPLATE
|
Store.UBISOFT -> UBISOFT_TEMPLATE
|
||||||
Store.EA -> eaRules(context, id) ?: return null
|
Store.EA -> eaRules(context, id) ?: return null
|
||||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.ROCKSTAR -> ""
|
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.ROCKSTAR, Store.STEAM -> ""
|
||||||
} ?: return null
|
} ?: return null
|
||||||
p.edit()
|
p.edit()
|
||||||
.putString("cloud_template_$id", fetched.ifEmpty { TEMPLATE_NONE })
|
.putString("cloud_template_$id", fetched.ifEmpty { TEMPLATE_NONE })
|
||||||
@@ -181,7 +181,7 @@ object CloudSaves {
|
|||||||
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.EA -> if (sidecar.extra["masterTitleId"].isNullOrEmpty()) null
|
Store.EA -> if (sidecar.extra["masterTitleId"].isNullOrEmpty()) null
|
||||||
else EaSaveRules.parse(template)?.base()?.let(EaSaveRules::template)?.let { CloudSavePaths.gog(it, pfx, folder) }
|
else EaSaveRules.parse(template)?.base()?.let(EaSaveRules::template)?.let { CloudSavePaths.gog(it, pfx, folder) }
|
||||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR -> null
|
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR, Store.STEAM -> null
|
||||||
}
|
}
|
||||||
return dir to (if (dir == null) "unresolved" else "ok")
|
return dir to (if (dir == null) "unresolved" else "ok")
|
||||||
}
|
}
|
||||||
@@ -221,7 +221,7 @@ object CloudSaves {
|
|||||||
if (rules == null || base == null || token == null || uid.isEmpty() || master.isEmpty()) null
|
if (rules == null || base == null || token == null || uid.isEmpty() || master.isEmpty()) null
|
||||||
else EaCloud(token, uid, EaCloud.keys(master, sidecar?.extra?.get("multiplayerId").orEmpty()), base, rules, saveFolder(context, store, id).first)
|
else EaCloud(token, uid, EaCloud.keys(master, sidecar?.extra?.get("multiplayerId").orEmpty()), base, rules, saveFolder(context, store, id).first)
|
||||||
}
|
}
|
||||||
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.ROCKSTAR -> null
|
Store.AMAZON, Store.ITCH, Store.GAMEJOLT, Store.XBOX, Store.BATTLENET, Store.ROCKSTAR, Store.STEAM -> null
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun signedIn(context: Context, store: Store): Boolean = when (store) {
|
private fun signedIn(context: Context, store: Store): Boolean = when (store) {
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ internal object LoginFlows {
|
|||||||
Store.UBISOFT -> ubisoftFlow(browserUserAgent)
|
Store.UBISOFT -> ubisoftFlow(browserUserAgent)
|
||||||
Store.EA -> eaFlow(browserUserAgent)
|
Store.EA -> eaFlow(browserUserAgent)
|
||||||
Store.ROCKSTAR -> rockstarFlow(browserUserAgent)
|
Store.ROCKSTAR -> rockstarFlow(browserUserAgent)
|
||||||
Store.ITCH, Store.XBOX, Store.BATTLENET -> null
|
Store.ITCH, Store.XBOX, Store.BATTLENET, Store.STEAM -> null
|
||||||
}
|
}
|
||||||
|
|
||||||
@Volatile var epicFlow: () -> StoreLoginActivity.Flow? = { null }
|
@Volatile var epicFlow: () -> StoreLoginActivity.Flow? = { null }
|
||||||
|
|||||||
@@ -10,11 +10,18 @@ enum class Store(val id: String, val label: String, val shortLabel: String) {
|
|||||||
UBISOFT("ubisoft", "Ubisoft Connect", "Ubisoft"),
|
UBISOFT("ubisoft", "Ubisoft Connect", "Ubisoft"),
|
||||||
AMAZON("amazon", "Amazon Games", "Amazon"),
|
AMAZON("amazon", "Amazon Games", "Amazon"),
|
||||||
BATTLENET("battlenet", "Battle.net", "Battle.net"),
|
BATTLENET("battlenet", "Battle.net", "Battle.net"),
|
||||||
GAMEJOLT("gamejolt", "Game Jolt", "Game Jolt");
|
GAMEJOLT("gamejolt", "Game Jolt", "Game Jolt"),
|
||||||
|
STEAM("steamstore", "Steam", "Steam");
|
||||||
|
|
||||||
val folder: String get() = if (this == ITCH) "itch" else shortLabel
|
val folder: String get() = if (this == ITCH) "itch" else shortLabel
|
||||||
|
|
||||||
|
/** The Library tab its games list under: Steam's are the Steam client's own tab. */
|
||||||
|
val librarySource: String get() = if (this == STEAM) com.droiddeck.launcher.frontend.Library.SOURCE_STEAM else id
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
fun byId(id: String?): Store? = entries.firstOrNull { it.id == id }
|
fun byId(id: String?): Store? = entries.firstOrNull { it.id == id }
|
||||||
|
|
||||||
|
/** The stores with a tab of their own; Steam's games list in the Library's Steam tab. */
|
||||||
|
val tabbed: List<Store> get() = entries - STEAM
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -90,7 +90,7 @@ object StoreAccounts {
|
|||||||
fun signedInAs(context: Context, store: Store): String? {
|
fun signedInAs(context: Context, store: Store): String? {
|
||||||
val json = read(context, store) ?: return if (isUnavailable(store)) store.label else null
|
val json = read(context, store) ?: return if (isUnavailable(store)) store.label else null
|
||||||
if (store == Store.XBOX) return json.optString("username").takeIf { it.isNotBlank() }
|
if (store == Store.XBOX) return json.optString("username").takeIf { it.isNotBlank() }
|
||||||
if (store == Store.BATTLENET) return json.optString("display_name").takeIf { it.isNotBlank() }
|
if (store == Store.BATTLENET || store == Store.STEAM) return json.optString("display_name").takeIf { it.isNotBlank() }
|
||||||
if (json.optString("access_token", "").isEmpty()) return null
|
if (json.optString("access_token", "").isEmpty()) return null
|
||||||
return json.optString("display_name", "").ifEmpty { json.optString("username", "") }.ifEmpty { store.label }
|
return json.optString("display_name", "").ifEmpty { json.optString("username", "") }.ifEmpty { store.label }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,8 +3,10 @@ package com.droiddeck.launcher.stores
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.os.StatFs
|
import android.os.StatFs
|
||||||
import android.os.storage.StorageManager
|
import android.os.storage.StorageManager
|
||||||
|
import com.droiddeck.launcher.frontend.AddedGames
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
import com.droiddeck.launcher.session.GameStorage
|
import com.droiddeck.launcher.session.GameStorage
|
||||||
|
import com.droiddeck.launcher.session.SecondaryLibrary
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.util.zip.CRC32
|
import java.util.zip.CRC32
|
||||||
@@ -12,6 +14,7 @@ import java.util.zip.CRC32
|
|||||||
object StoreInstallRoot {
|
object StoreInstallRoot {
|
||||||
const val SPACE_UNKNOWN = -1L
|
const val SPACE_UNKNOWN = -1L
|
||||||
private const val INTERNAL = "root/Games/Stores"
|
private const val INTERNAL = "root/Games/Stores"
|
||||||
|
const val INTERNAL_GUEST = "/$INTERNAL"
|
||||||
private const val ON_VOLUME = "Games"
|
private const val ON_VOLUME = "Games"
|
||||||
const val GUEST_EXTERNAL = "/mnt/droiddeck-stores"
|
const val GUEST_EXTERNAL = "/mnt/droiddeck-stores"
|
||||||
|
|
||||||
@@ -179,6 +182,24 @@ object StoreInstallRoot {
|
|||||||
fun externalBindSpecsForXodus(context: Context): List<String> =
|
fun externalBindSpecsForXodus(context: Context): List<String> =
|
||||||
externalBindSpecs(externalRootsForXodus(context), LinuxRuntime.rootDir(context))
|
externalBindSpecs(externalRootsForXodus(context), LinuxRuntime.rootDir(context))
|
||||||
|
|
||||||
|
fun guestBinds(context: Context): List<String> {
|
||||||
|
val out = ArrayList<String>(externalBindSpecs(context))
|
||||||
|
val root = LinuxRuntime.rootDir(context)
|
||||||
|
GameStorage.effective(context)?.takeIf { File(it.path).isDirectory }?.let { library ->
|
||||||
|
val content = SecondaryLibrary.contentPath(File(library.path)).path
|
||||||
|
for (guest in SecondaryLibrary.CARD_GUESTS) {
|
||||||
|
File(root, guest.removePrefix("/")).mkdirs()
|
||||||
|
out += "$content:$guest"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (folder in AddedGames.roots(context)) {
|
||||||
|
if (!folder.host.isDirectory || !folder.host.canRead()) continue
|
||||||
|
File(root, folder.guest.removePrefix("/")).mkdirs()
|
||||||
|
out += folder.host.path + ":" + folder.guest
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
internal fun externalBindSpecs(roots: List<Pair<File, String>>, guestRoot: File): List<String> =
|
internal fun externalBindSpecs(roots: List<Pair<File, String>>, guestRoot: File): List<String> =
|
||||||
roots.mapNotNull { (host, guest) ->
|
roots.mapNotNull { (host, guest) ->
|
||||||
if (!host.isDirectory || !host.canRead()) return@mapNotNull null
|
if (!host.isDirectory || !host.canRead()) return@mapNotNull null
|
||||||
@@ -226,7 +247,7 @@ object StoreInstallRoot {
|
|||||||
fun storeDir(root: File, store: Store): File = File(root, store.folder)
|
fun storeDir(root: File, store: Store): File = File(root, store.folder)
|
||||||
|
|
||||||
fun gameFolders(context: Context): List<File> = roots(context).flatMap { root ->
|
fun gameFolders(context: Context): List<File> = roots(context).flatMap { root ->
|
||||||
Store.entries.flatMap { store ->
|
Store.entries.filter { it != Store.STEAM }.flatMap { store ->
|
||||||
storeDir(root, store).listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()
|
storeDir(root, store).listFiles { f -> f.isDirectory }?.sortedBy { it.name.lowercase() } ?: emptyList()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -246,7 +267,7 @@ object StoreInstallRoot {
|
|||||||
fun isFinished(folder: File): Boolean = StoreGameSidecar.read(folder)?.isInstalled == true
|
fun isFinished(folder: File): Boolean = StoreGameSidecar.read(folder)?.isInstalled == true
|
||||||
|
|
||||||
fun unfinished(context: Context): List<Unfinished> = roots(context).flatMap { root ->
|
fun unfinished(context: Context): List<Unfinished> = roots(context).flatMap { root ->
|
||||||
Store.entries.filter { it != Store.BATTLENET }.flatMap { store ->
|
Store.entries.filter { it != Store.BATTLENET && it != Store.STEAM }.flatMap { store ->
|
||||||
storeDir(root, store).listFiles { f -> f.isDirectory }.orEmpty().mapNotNull { folder ->
|
storeDir(root, store).listFiles { f -> f.isDirectory }.orEmpty().mapNotNull { folder ->
|
||||||
val sidecar = StoreGameSidecar.read(folder)
|
val sidecar = StoreGameSidecar.read(folder)
|
||||||
when {
|
when {
|
||||||
|
|||||||
@@ -12,8 +12,11 @@ object StoreLaunch {
|
|||||||
const val EPIC_CODE = ".droiddeck-epic-code"
|
const val EPIC_CODE = ".droiddeck-epic-code"
|
||||||
const val EPIC_ARGS = ".droiddeck-epic-args"
|
const val EPIC_ARGS = ".droiddeck-epic-args"
|
||||||
const val UBISOFT_LAUNCH = ".droiddeck-ubisoft.json"
|
const val UBISOFT_LAUNCH = ".droiddeck-ubisoft.json"
|
||||||
private const val UBISOFT_SERVICE = "Z:\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe"
|
/** DroidDeck-Bionic's Wine has Android's root on Z:; that tool sets this to the guest's root as its Wine names it. */
|
||||||
const val EPIC_PARENT = "Z:\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe"
|
const val GUEST_ROOT = "DROIDDECK_GUEST_ROOT"
|
||||||
|
private const val ROOT_VAR = "DD_R"
|
||||||
|
private const val UBISOFT_SERVICE = "%$ROOT_VAR%\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe"
|
||||||
|
const val EPIC_PARENT = "%$ROOT_VAR%\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe"
|
||||||
/** Per-game environment switch: 1 starts any Epic game under [EPIC_PARENT], 0 never does. */
|
/** Per-game environment switch: 1 starts any Epic game under [EPIC_PARENT], 0 never does. */
|
||||||
const val EPIC_PARENT_SWITCH = "DD_EPIC_PARENT"
|
const val EPIC_PARENT_SWITCH = "DD_EPIC_PARENT"
|
||||||
/** Epic app names whose launchers treat the game as unowned unless a process named EpicGamesLauncher.exe started it. */
|
/** Epic app names whose launchers treat the game as unowned unless a process named EpicGamesLauncher.exe started it. */
|
||||||
@@ -47,6 +50,10 @@ object StoreLaunch {
|
|||||||
for ((k, v) in sidecar.env) if (ENV_NAME.matches(k)) lines += "set \"$k=${v.replace("\"", "")}\""
|
for ((k, v) in sidecar.env) if (ENV_NAME.matches(k)) lines += "set \"$k=${v.replace("\"", "")}\""
|
||||||
val args = sidecar.args.joinToString(" ") { if (sidecar.store == Store.ROCKSTAR) batchArg(it) else quoteArg(it) }
|
val args = sidecar.args.joinToString(" ") { if (sidecar.store == Store.ROCKSTAR) batchArg(it) else quoteArg(it) }
|
||||||
val run = "\"%~dp0$exe\"" + (if (args.isNotEmpty()) " $args" else "")
|
val run = "\"%~dp0$exe\"" + (if (args.isNotEmpty()) " $args" else "")
|
||||||
|
if (sidecar.store == Store.EPIC || sidecar.store == Store.UBISOFT) {
|
||||||
|
lines += "set \"$ROOT_VAR=Z:\""
|
||||||
|
lines += "if defined $GUEST_ROOT set \"$ROOT_VAR=%$GUEST_ROOT%\""
|
||||||
|
}
|
||||||
if (sidecar.store == Store.EPIC) {
|
if (sidecar.store == Store.EPIC) {
|
||||||
lines += "set \"$PARENT_VAR=${if (sidecar.id in EPIC_PARENT_TITLES) "1" else ""}\""
|
lines += "set \"$PARENT_VAR=${if (sidecar.id in EPIC_PARENT_TITLES) "1" else ""}\""
|
||||||
lines += "if \"%$EPIC_PARENT_SWITCH%\"==\"1\" set \"$PARENT_VAR=1\""
|
lines += "if \"%$EPIC_PARENT_SWITCH%\"==\"1\" set \"$PARENT_VAR=1\""
|
||||||
@@ -137,7 +144,6 @@ object StoreLaunch {
|
|||||||
if (sidecar.store !in listOf(Store.UBISOFT, Store.ROCKSTAR) || !sidecar.isInstalled) return sidecar
|
if (sidecar.store !in listOf(Store.UBISOFT, Store.ROCKSTAR) || !sidecar.isInstalled) return sidecar
|
||||||
if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(File(folder, LAUNCHER).toPath())) return sidecar.copy(launcher = null)
|
if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(File(folder, LAUNCHER).toPath())) return sidecar.copy(launcher = null)
|
||||||
val wrongExe = !sidecar.exeFile(folder).isFile || sidecar.exe.contains("installer", ignoreCase = true) || sidecar.exe.contains("autorun", ignoreCase = true)
|
val wrongExe = !sidecar.exeFile(folder).isFile || sidecar.exe.contains("installer", ignoreCase = true) || sidecar.exe.contains("autorun", ignoreCase = true)
|
||||||
if (sidecar.store == Store.UBISOFT && sidecar.launcher == LAUNCHER && !wrongExe) return sidecar
|
|
||||||
val metadataExe = if (sidecar.store == Store.ROCKSTAR) com.droiddeck.launcher.stores.rockstar.RockstarMetadata.find(folder)?.exe
|
val metadataExe = if (sidecar.store == Store.ROCKSTAR) com.droiddeck.launcher.stores.rockstar.RockstarMetadata.find(folder)?.exe
|
||||||
?.takeIf { File(folder, it).isFile && File(folder, it).canonicalPath.startsWith(folder.canonicalPath + File.separator) } else null
|
?.takeIf { File(folder, it).isFile && File(folder, it).canonicalPath.startsWith(folder.canonicalPath + File.separator) } else null
|
||||||
val exe = metadataExe ?: if (wrongExe) StoreExe.pick(folder, null, sidecar.title).ifEmpty { sidecar.exe } else sidecar.exe
|
val exe = metadataExe ?: if (wrongExe) StoreExe.pick(folder, null, sidecar.title).ifEmpty { sidecar.exe } else sidecar.exe
|
||||||
|
|||||||
@@ -65,6 +65,7 @@ class StoreLoginActivity : ComponentActivity() {
|
|||||||
val readsPage: Boolean get() = false
|
val readsPage: Boolean get() = false
|
||||||
val pageScript: String get() = "(function(){ try { return document.body.innerText; } catch(e){ return ''; } })()"
|
val pageScript: String get() = "(function(){ try { return document.body.innerText; } catch(e){ return ''; } })()"
|
||||||
fun pageReady(result: String): Boolean = true
|
fun pageReady(result: String): Boolean = true
|
||||||
|
fun browserStep(page: String): String? = null
|
||||||
fun forgetSignIn(done: () -> Unit) = done()
|
fun forgetSignIn(done: () -> Unit) = done()
|
||||||
fun pageFinished(view: WebView, url: String) {}
|
fun pageFinished(view: WebView, url: String) {}
|
||||||
}
|
}
|
||||||
@@ -72,6 +73,7 @@ class StoreLoginActivity : ComponentActivity() {
|
|||||||
private var store: Store? = null
|
private var store: Store? = null
|
||||||
private var clientUrl: String? = null
|
private var clientUrl: String? = null
|
||||||
private var flow: Flow? = null
|
private var flow: Flow? = null
|
||||||
|
private var pendingBrowserStep: String? = null
|
||||||
private var webViewRef: WebView? = null
|
private var webViewRef: WebView? = null
|
||||||
private var popupWebView: WebView? = null
|
private var popupWebView: WebView? = null
|
||||||
private lateinit var contentHost: FrameLayout
|
private lateinit var contentHost: FrameLayout
|
||||||
@@ -211,6 +213,7 @@ class StoreLoginActivity : ComponentActivity() {
|
|||||||
|
|
||||||
private fun reloadLogin() {
|
private fun reloadLogin() {
|
||||||
dismissPopup(); clearError()
|
dismissPopup(); clearError()
|
||||||
|
pendingBrowserStep = null
|
||||||
captured.set(false)
|
captured.set(false)
|
||||||
val fresh = generateState()
|
val fresh = generateState()
|
||||||
oauthState = fresh
|
oauthState = fresh
|
||||||
@@ -332,9 +335,13 @@ class StoreLoginActivity : ComponentActivity() {
|
|||||||
|
|
||||||
private fun readPage(view: WebView, f: Flow, left: Int) {
|
private fun readPage(view: WebView, f: Flow, left: Int) {
|
||||||
view.evaluateJavascript(f.pageScript) { json ->
|
view.evaluateJavascript(f.pageScript) { json ->
|
||||||
|
if (flow !== f) return@evaluateJavascript
|
||||||
val result = json ?: ""
|
val result = json ?: ""
|
||||||
if (!f.pageReady(result) && left > 0) view.postDelayed({ readPage(view, f, left - 1) }, PAGE_RETRY_MS)
|
if (!f.pageReady(result) && left > 0) view.postDelayed({ readPage(view, f, left - 1) }, PAGE_RETRY_MS)
|
||||||
else Thread({ settle(f.finish(this, view, result)) }, "store-login").start()
|
else {
|
||||||
|
val step = f.browserStep(result)
|
||||||
|
if (step == null || !continueInBrowser(step)) Thread({ settle(f.finish(this, view, result)) }, "store-login").start()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -350,6 +357,21 @@ class StoreLoginActivity : ComponentActivity() {
|
|||||||
if (f.readsPage) readPage(view, f, PAGE_TRIES) else Thread({ settle(f.finish(this, view, url)) }, "store-login").start()
|
if (f.readsPage) readPage(view, f, PAGE_TRIES) else Thread({ settle(f.finish(this, view, url)) }, "store-login").start()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun continueInBrowser(url: String): Boolean {
|
||||||
|
if (isFinishing || isDestroyed) return false
|
||||||
|
if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.STARTED)) {
|
||||||
|
pendingBrowserStep = url
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
val opened = runCatching { startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, Uri.parse(url))) }
|
||||||
|
.onFailure { Log.w(TAG, "no browser took the sign-in step: ${it.javaClass.simpleName}") }
|
||||||
|
.isSuccess
|
||||||
|
if (!opened) return false
|
||||||
|
titleText.text = getString(R.string.stores_login_title, store?.label ?: "")
|
||||||
|
showError(getString(R.string.stores_login_continue_in_browser, store?.label ?: ""))
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
private fun settle(problem: String?) {
|
private fun settle(problem: String?) {
|
||||||
runOnUiThread {
|
runOnUiThread {
|
||||||
if (problem == null) { StoresState.refresh(this); finish(); return@runOnUiThread }
|
if (problem == null) { StoresState.refresh(this); finish(); return@runOnUiThread }
|
||||||
@@ -367,6 +389,10 @@ class StoreLoginActivity : ComponentActivity() {
|
|||||||
|
|
||||||
override fun onStart() {
|
override fun onStart() {
|
||||||
super.onStart()
|
super.onStart()
|
||||||
|
pendingBrowserStep?.let { step ->
|
||||||
|
pendingBrowserStep = null
|
||||||
|
if (!continueInBrowser(step)) reloadLogin()
|
||||||
|
}
|
||||||
if (clientUrl != null && !isFinishing) com.droiddeck.launcher.session.SessionService.holdForSignIn(this, true)
|
if (clientUrl != null && !isFinishing) com.droiddeck.launcher.session.SessionService.holdForSignIn(this, true)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ object StoreSizes {
|
|||||||
Store.AMAZON -> AmazonPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
|
Store.AMAZON -> AmazonPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
|
||||||
Store.ITCH, Store.GAMEJOLT -> {}
|
Store.ITCH, Store.GAMEJOLT -> {}
|
||||||
Store.EA -> com.droiddeck.launcher.stores.ea.EaPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
|
Store.EA -> com.droiddeck.launcher.stores.ea.EaPrefs.get(app).edit().putLong("size_${item.id}", it).apply()
|
||||||
Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR -> {}
|
Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR, Store.STEAM -> {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}, pool).exceptionally { error ->
|
}, pool).exceptionally { error ->
|
||||||
@@ -142,5 +142,6 @@ object StoreSizes {
|
|||||||
Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR -> 0L
|
Store.GOG, Store.XBOX, Store.BATTLENET, Store.UBISOFT, Store.ROCKSTAR -> 0L
|
||||||
Store.ITCH -> com.droiddeck.launcher.stores.itch.ItchLibrary.size(context, item)
|
Store.ITCH -> com.droiddeck.launcher.stores.itch.ItchLibrary.size(context, item)
|
||||||
Store.GAMEJOLT -> com.droiddeck.launcher.stores.gamejolt.GameJoltBuilds.size(context, item)
|
Store.GAMEJOLT -> com.droiddeck.launcher.stores.gamejolt.GameJoltBuilds.size(context, item)
|
||||||
|
Store.STEAM -> com.droiddeck.launcher.stores.steam.SteamStore.plannedBytes(context, item)
|
||||||
} }
|
} }
|
||||||
}
|
}
|
||||||
@@ -3,7 +3,7 @@ package com.droiddeck.launcher.stores
|
|||||||
data class StoreTab(val store: Store, val shown: Boolean)
|
data class StoreTab(val store: Store, val shown: Boolean)
|
||||||
|
|
||||||
fun arrangeStoreTabs(order: List<String>, hidden: Set<String>): List<StoreTab> {
|
fun arrangeStoreTabs(order: List<String>, hidden: Set<String>): List<StoreTab> {
|
||||||
val known = Store.entries.associateBy { it.id }
|
val known = Store.tabbed.associateBy { it.id }
|
||||||
val listed = order.mapNotNull { known[it] }.distinct()
|
val listed = order.mapNotNull { known[it] }.distinct()
|
||||||
return (listed + Store.entries.filterNot { it in listed }).map { StoreTab(it, it.id !in hidden) }
|
return (listed + Store.tabbed.filterNot { it in listed }).map { StoreTab(it, it.id !in hidden) }
|
||||||
}
|
}
|
||||||
@@ -85,6 +85,7 @@ object StoresState {
|
|||||||
do {
|
do {
|
||||||
seen = refreshRequests.get()
|
seen = refreshRequests.get()
|
||||||
runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetClient.syncAccount(app) }
|
runCatching { com.droiddeck.launcher.stores.battlenet.BattleNetClient.syncAccount(app) }
|
||||||
|
runCatching { com.droiddeck.launcher.stores.steam.SteamStore.syncAccount(app) }
|
||||||
val found = Store.entries.mapNotNull { store -> StoreAccounts.displayName(app, store)?.let { store to it } }
|
val found = Store.entries.mapNotNull { store -> StoreAccounts.displayName(app, store)?.let { store to it } }
|
||||||
val onDisk = StoreInstallRoot.gameFolders(app).mapNotNull { folder ->
|
val onDisk = StoreInstallRoot.gameFolders(app).mapNotNull { folder ->
|
||||||
StoreGameSidecar.read(folder)?.takeIf { it.isInstalled || it.state == StoreGameSidecar.STATE_UPDATING }?.let { InstalledStoreGame(it, folder) }
|
StoreGameSidecar.read(folder)?.takeIf { it.isInstalled || it.state == StoreGameSidecar.STATE_UPDATING }?.let { InstalledStoreGame(it, folder) }
|
||||||
@@ -260,6 +261,7 @@ object StoresState {
|
|||||||
|
|
||||||
fun requestInstall(context: Context, item: CatalogItem) {
|
fun requestInstall(context: Context, item: CatalogItem) {
|
||||||
askForNotifications(context)
|
askForNotifications(context)
|
||||||
|
if (item.store == Store.STEAM) { com.droiddeck.launcher.stores.steam.SteamStore.requestInstall(context, item); return }
|
||||||
if (item.store == Store.ITCH && item.extra["uploadId"].isNullOrEmpty()) { itchPicking = item; return }
|
if (item.store == Store.ITCH && item.extra["uploadId"].isNullOrEmpty()) { itchPicking = item; return }
|
||||||
if (item.store == Store.GAMEJOLT && item.extra["buildId"].isNullOrEmpty()) { gameJoltPicking = item; return }
|
if (item.store == Store.GAMEJOLT && item.extra["buildId"].isNullOrEmpty()) { gameJoltPicking = item; return }
|
||||||
if (isUnfinished(item)) { install(context, item); return }
|
if (isUnfinished(item)) { install(context, item); return }
|
||||||
@@ -278,6 +280,7 @@ object StoresState {
|
|||||||
|
|
||||||
fun install(context: Context, item: CatalogItem, root: java.io.File? = null, language: String? = null) {
|
fun install(context: Context, item: CatalogItem, root: java.io.File? = null, language: String? = null) {
|
||||||
val app = context.applicationContext
|
val app = context.applicationContext
|
||||||
|
if (item.store == Store.STEAM) { com.droiddeck.launcher.stores.steam.SteamStore.restore(app, item); return }
|
||||||
val targetRoot = root ?: StoreInstallRoot.defaultTarget(app)?.root ?: StoreInstallRoot.installRoot(app)
|
val targetRoot = root ?: StoreInstallRoot.defaultTarget(app)?.root ?: StoreInstallRoot.installRoot(app)
|
||||||
if (item.store == Store.BATTLENET && !com.droiddeck.launcher.stores.battlenet.BattleNetInstall.headless(item)) {
|
if (item.store == Store.BATTLENET && !com.droiddeck.launcher.stores.battlenet.BattleNetInstall.headless(item)) {
|
||||||
backends[item.store]?.install(app, item, targetRoot)
|
backends[item.store]?.install(app, item, targetRoot)
|
||||||
|
|||||||
@@ -7,9 +7,7 @@ import com.droiddeck.launcher.R
|
|||||||
import com.droiddeck.launcher.frontend.AddedGames
|
import com.droiddeck.launcher.frontend.AddedGames
|
||||||
import com.droiddeck.launcher.runtime.BattleNet
|
import com.droiddeck.launcher.runtime.BattleNet
|
||||||
import com.droiddeck.launcher.runtime.GuestCommand
|
import com.droiddeck.launcher.runtime.GuestCommand
|
||||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
|
||||||
import com.droiddeck.launcher.session.GameStorage
|
import com.droiddeck.launcher.session.GameStorage
|
||||||
import com.droiddeck.launcher.session.SecondaryLibrary
|
|
||||||
import com.droiddeck.launcher.stores.CatalogItem
|
import com.droiddeck.launcher.stores.CatalogItem
|
||||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||||
import com.droiddeck.launcher.stores.Store
|
import com.droiddeck.launcher.stores.Store
|
||||||
@@ -75,22 +73,10 @@ object BattleNetInstall {
|
|||||||
}
|
}
|
||||||
|
|
||||||
internal fun binds(context: Context): List<String> {
|
internal fun binds(context: Context): List<String> {
|
||||||
val out = ArrayList<String>(StoreInstallRoot.externalBindSpecs(context))
|
|
||||||
val root = LinuxRuntime.rootDir(context)
|
|
||||||
GameStorage.effective(context)?.let { library ->
|
GameStorage.effective(context)?.let { library ->
|
||||||
if (!File(library.path).isDirectory) throw IllegalStateException(context.getString(R.string.game_sync_err_game_storage))
|
if (!File(library.path).isDirectory) throw IllegalStateException(context.getString(R.string.game_sync_err_game_storage))
|
||||||
val content = SecondaryLibrary.contentPath(File(library.path)).path
|
|
||||||
for (guest in SecondaryLibrary.CARD_GUESTS) {
|
|
||||||
File(root, guest.removePrefix("/")).mkdirs()
|
|
||||||
out += "$content:$guest"
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
for (folder in AddedGames.roots(context)) {
|
return StoreInstallRoot.guestBinds(context)
|
||||||
if (!folder.host.isDirectory || !folder.host.canRead()) continue
|
|
||||||
File(root, folder.guest.removePrefix("/")).mkdirs()
|
|
||||||
out += folder.host.path + ":" + folder.guest
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun run(context: Context, args: List<String>, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int =
|
internal fun run(context: Context, args: List<String>, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int =
|
||||||
|
|||||||
@@ -159,6 +159,7 @@ object DownloadQueue {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun holdPaused(key: String) = synchronized(lock) { heldPaused.add(key) }
|
fun holdPaused(key: String) = synchronized(lock) { heldPaused.add(key) }
|
||||||
|
fun dropHeld(key: String) = synchronized(lock) { heldPaused.remove(key) }
|
||||||
private var running = 0
|
private var running = 0
|
||||||
|
|
||||||
fun parallel(context: Context): Int = SessionPrefs.gameStoresParallel(context)
|
fun parallel(context: Context): Int = SessionPrefs.gameStoresParallel(context)
|
||||||
|
|||||||
@@ -5,8 +5,9 @@ import android.webkit.WebView
|
|||||||
import com.droiddeck.launcher.R
|
import com.droiddeck.launcher.R
|
||||||
import com.droiddeck.launcher.stores.StoreLoginActivity
|
import com.droiddeck.launcher.stores.StoreLoginActivity
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
|
import org.json.JSONTokener
|
||||||
|
|
||||||
internal class EpicLogin private constructor(
|
internal class EpicLogin internal constructor(
|
||||||
override val startUrl: String,
|
override val startUrl: String,
|
||||||
override val userAgent: String,
|
override val userAgent: String,
|
||||||
private val redirectPrefix: String,
|
private val redirectPrefix: String,
|
||||||
@@ -15,6 +16,12 @@ internal class EpicLogin private constructor(
|
|||||||
|
|
||||||
override fun isRedirect(url: String): Boolean = url.startsWith(redirectPrefix)
|
override fun isRedirect(url: String): Boolean = url.startsWith(redirectPrefix)
|
||||||
|
|
||||||
|
override fun browserStep(page: String): String? {
|
||||||
|
val action = correctiveAction(page) ?: return null
|
||||||
|
Log.i(TAG, "the redirect page asks for a corrective action: $action")
|
||||||
|
return ACCOUNT_SIGN_IN_URL
|
||||||
|
}
|
||||||
|
|
||||||
override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? {
|
override fun finish(activity: StoreLoginActivity, view: WebView, url: String): String? {
|
||||||
val code = EpicNative.call("auth.codeFromPage", JSONObject().put("text", url))?.optString("code", "").orEmpty()
|
val code = EpicNative.call("auth.codeFromPage", JSONObject().put("text", url))?.optString("code", "").orEmpty()
|
||||||
if (code.isEmpty()) {
|
if (code.isEmpty()) {
|
||||||
@@ -38,6 +45,15 @@ internal class EpicLogin private constructor(
|
|||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
private const val TAG = "EpicLogin"
|
private const val TAG = "EpicLogin"
|
||||||
|
private const val CORRECTIVE_ACTION_REQUIRED = "errors.com.epicgames.oauth.corrective_action_required"
|
||||||
|
internal const val ACCOUNT_SIGN_IN_URL = "https://www.epicgames.com/id/login?redirectUrl=https%3A%2F%2Fwww.epicgames.com%2Faccount%2Fpersonal"
|
||||||
|
|
||||||
|
internal fun correctiveAction(page: String): String? {
|
||||||
|
val text = runCatching { JSONTokener(page).nextValue() }.getOrNull() as? String ?: page
|
||||||
|
val body = runCatching { JSONObject(text.trim()) }.getOrNull() ?: return null
|
||||||
|
if (body.optString("errorCode") != CORRECTIVE_ACTION_REQUIRED) return null
|
||||||
|
return body.optJSONObject("metadata")?.optString("correctiveAction").orEmpty().ifEmpty { "unknown" }
|
||||||
|
}
|
||||||
|
|
||||||
fun create(): StoreLoginActivity.Flow? {
|
fun create(): StoreLoginActivity.Flow? {
|
||||||
val config = EpicNative.call("auth.config") ?: return null
|
val config = EpicNative.call("auth.config") ?: return null
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import android.content.Context;
|
|||||||
import android.util.Log;
|
import android.util.Log;
|
||||||
|
|
||||||
import com.droiddeck.launcher.frontend.AddedGames;
|
import com.droiddeck.launcher.frontend.AddedGames;
|
||||||
import com.droiddeck.launcher.runtime.GuestCommand;
|
|
||||||
import com.droiddeck.launcher.stores.StoreLanguage;
|
import com.droiddeck.launcher.stores.StoreLanguage;
|
||||||
import com.droiddeck.launcher.stores.StoreLog;
|
import com.droiddeck.launcher.stores.StoreLog;
|
||||||
import com.droiddeck.launcher.stores.download.StoreDownloadTier;
|
import com.droiddeck.launcher.stores.download.StoreDownloadTier;
|
||||||
@@ -271,11 +270,10 @@ public final class GogDownloadManager {
|
|||||||
long planned = 0;
|
long planned = 0;
|
||||||
boolean sized = true;
|
boolean sized = true;
|
||||||
for (InstallerPart part : parts) { planned += part.size; if (part.size <= 0) sized = false; }
|
for (InstallerPart part : parts) { planned += part.size; if (part.size <= 0) sized = false; }
|
||||||
if (sized) {
|
long needed = installerBytesNeeded(knownPartBytes(parts), GogLibrary.INSTANCE.sizeOf(ctx, game.gameId));
|
||||||
long usable = com.droiddeck.launcher.stores.StoreInstallRoot.availableBytes(installPath);
|
long usable = com.droiddeck.launcher.stores.StoreInstallRoot.availableBytes(installPath);
|
||||||
if (com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(planned, usable)) {
|
if (com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(needed, usable)) {
|
||||||
throw new InstallException("Not enough free space: need " + formatBytes(planned) + ", only " + formatBytes(usable) + " free");
|
throw new InstallException("Not enough free space: need " + formatBytes(needed) + ", only " + formatBytes(usable) + " free");
|
||||||
}
|
|
||||||
}
|
}
|
||||||
long total = 0;
|
long total = 0;
|
||||||
for (InstallerPart part : parts) {
|
for (InstallerPart part : parts) {
|
||||||
@@ -327,10 +325,7 @@ public final class GogDownloadManager {
|
|||||||
cb.onProgress("Extracting installer…", 95);
|
cb.onProgress("Extracting installer…", 95);
|
||||||
int rc;
|
int rc;
|
||||||
try {
|
try {
|
||||||
rc = GuestCommand.INSTANCE.run(ctx, Arrays.asList(
|
rc = GogInnoextract.extract(ctx, guestSetup, guestDir, "gog-innoextract", cancelled,
|
||||||
"/usr/local/bin/droiddeck-innoextract", "--gog", "--silent",
|
|
||||||
"-d", guestDir, guestSetup),
|
|
||||||
false, "gog-innoextract", null, null, false, cancelled, null,
|
|
||||||
line -> { cb.onLog("gog innoextract: " + line); return kotlin.Unit.INSTANCE; });
|
line -> { cb.onLog("gog innoextract: " + line); return kotlin.Unit.INSTANCE; });
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new InstallException("The installer could not be extracted: " + e.getClass().getSimpleName());
|
throw new InstallException("The installer could not be extracted: " + e.getClass().getSimpleName());
|
||||||
@@ -339,6 +334,16 @@ public final class GogDownloadManager {
|
|||||||
if (rc != 0) throw new InstallException("The installer could not be extracted (innoextract exit " + rc + ")");
|
if (rc != 0) throw new InstallException("The installer could not be extracted (innoextract exit " + rc + ")");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static long knownPartBytes(List<InstallerPart> parts) {
|
||||||
|
long known = 0;
|
||||||
|
for (InstallerPart part : parts) if (part.size > 0) known += part.size;
|
||||||
|
return known;
|
||||||
|
}
|
||||||
|
|
||||||
|
static long installerBytesNeeded(long downloadBytes, long installedBytes) {
|
||||||
|
return Math.max(0, downloadBytes) + Math.max(0, installedBytes);
|
||||||
|
}
|
||||||
|
|
||||||
static final class InstallerPart {
|
static final class InstallerPart {
|
||||||
final String url;
|
final String url;
|
||||||
final String filename;
|
final String filename;
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
package com.droiddeck.launcher.stores.gog
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import com.droiddeck.launcher.runtime.GuestCommand
|
||||||
|
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
|
||||||
|
internal object GogInnoextract {
|
||||||
|
private const val PROGRAM = "/usr/local/bin/droiddeck-innoextract"
|
||||||
|
|
||||||
|
@JvmStatic
|
||||||
|
fun extract(context: Context, setup: String, target: String, logName: String, cancelled: AtomicBoolean, onLine: (String) -> Unit): Int =
|
||||||
|
GuestCommand.run(context, argv(setup, target), logName = logName,
|
||||||
|
extraBinds = StoreInstallRoot.guestBinds(context), cancelled = cancelled, onLine = onLine)
|
||||||
|
|
||||||
|
internal fun argv(setup: String, target: String): List<String> = listOf(PROGRAM, "--gog", "--silent", "-d", target, setup)
|
||||||
|
}
|
||||||
@@ -3,11 +3,9 @@ package com.droiddeck.launcher.stores.gog
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import com.droiddeck.launcher.agent.AgentGuest
|
import com.droiddeck.launcher.agent.AgentGuest
|
||||||
import com.droiddeck.launcher.frontend.AddedGames
|
import com.droiddeck.launcher.frontend.AddedGames
|
||||||
import com.droiddeck.launcher.runtime.GuestCommand
|
|
||||||
import com.droiddeck.launcher.session.SessionService
|
import com.droiddeck.launcher.session.SessionService
|
||||||
import com.droiddeck.launcher.session.SessionState
|
import com.droiddeck.launcher.session.SessionState
|
||||||
import com.droiddeck.launcher.stores.StoreGameSidecar
|
import com.droiddeck.launcher.stores.StoreGameSidecar
|
||||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
|
||||||
import com.droiddeck.launcher.stores.download.DownloadQueue
|
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||||
import com.droiddeck.launcher.stores.download.DownloadStage
|
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||||
import org.json.JSONArray
|
import org.json.JSONArray
|
||||||
@@ -71,8 +69,7 @@ internal object GogOffline {
|
|||||||
val source = AddedGames.guestPath(context, installer) ?: error("The GOG installer is not visible to Linux")
|
val source = AddedGames.guestPath(context, installer) ?: error("The GOG installer is not visible to Linux")
|
||||||
val target = AddedGames.guestPath(context, extracted) ?: error("The GOG staging folder is not visible to Linux")
|
val target = AddedGames.guestPath(context, extracted) ?: error("The GOG staging folder is not visible to Linux")
|
||||||
handle.stage(DownloadStage.INSTALL, "Extracting the full offline installer")
|
handle.stage(DownloadStage.INSTALL, "Extracting the full offline installer")
|
||||||
val rc = GuestCommand.run(context, listOf("/usr/local/bin/droiddeck-innoextract", "--gog", "--silent", "-d", target, source),
|
val rc = GogInnoextract.extract(context, source, target, "gog-refresh", stop, handle::log)
|
||||||
extraBinds = StoreInstallRoot.externalBindSpecs(context), cancelled = stop, logName = "gog-refresh", onLine = handle::log)
|
|
||||||
if (stop.get()) return
|
if (stop.get()) return
|
||||||
check(rc == 0) { "GOG installer extraction failed (exit $rc)" }
|
check(rc == 0) { "GOG installer extraction failed (exit $rc)" }
|
||||||
applyRefresh(proposal, extracted, handle, stop)
|
applyRefresh(proposal, extracted, handle, stop)
|
||||||
|
|||||||
@@ -0,0 +1,130 @@
|
|||||||
|
package com.droiddeck.launcher.stores.steam
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.os.Environment
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
|
import com.droiddeck.launcher.frontend.AddedGames
|
||||||
|
import com.droiddeck.launcher.frontend.Library
|
||||||
|
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||||
|
import com.droiddeck.launcher.session.GameStorage
|
||||||
|
import com.droiddeck.launcher.session.SecondaryLibrary
|
||||||
|
import com.droiddeck.launcher.session.SessionPhase
|
||||||
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
|
import com.droiddeck.launcher.session.SessionService
|
||||||
|
import com.droiddeck.launcher.session.SessionState
|
||||||
|
import com.droiddeck.launcher.session.SteamLibraries
|
||||||
|
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
/** The active Steam client's folders as the app sees them. Reads storage; call off the main thread. */
|
||||||
|
internal object SteamClient {
|
||||||
|
const val X86_64 = "x86_64"
|
||||||
|
|
||||||
|
class Target(
|
||||||
|
val library: SteamLibraryFolders.Library, val engineHost: File, val label: String,
|
||||||
|
val freeBytes: Long, val removable: Boolean, val folder: Boolean,
|
||||||
|
)
|
||||||
|
|
||||||
|
fun activeArch(context: Context): String = SessionPrefs.activeSteamClientArch(context)
|
||||||
|
|
||||||
|
private fun guestHome(arch: String) = if (arch == X86_64) "/root/.droiddeck-x64" else "/root"
|
||||||
|
|
||||||
|
fun guestRoot(arch: String) = "${guestHome(arch)}/.local/share/Steam"
|
||||||
|
|
||||||
|
private fun aliases(arch: String) = listOf(guestRoot(arch), "${guestHome(arch)}/.steam/steam", "${guestHome(arch)}/.steam/root")
|
||||||
|
|
||||||
|
/** [guest] names [library]; the main library also answers to the client's other spellings of its root. */
|
||||||
|
fun sameLibrary(context: Context, library: SteamLibraryFolders.Library, guest: String): Boolean {
|
||||||
|
if (library.guest == guest) return true
|
||||||
|
if (!library.main) return false
|
||||||
|
val arch = activeArch(context)
|
||||||
|
val wanted = SteamLibraryFolders.normalize(guest) ?: return false
|
||||||
|
return (aliases(arch) + guestRoot(arch)).mapNotNull(SteamLibraryFolders::normalize).contains(wanted)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun root(context: Context, arch: String = activeArch(context)): File = SessionPrefs.steamRoot(context, arch)
|
||||||
|
|
||||||
|
fun registry(context: Context, arch: String = activeArch(context)): File =
|
||||||
|
File(LinuxRuntime.rootDir(context), guestHome(arch).removePrefix("/") + "/.steam/registry.vdf")
|
||||||
|
|
||||||
|
fun loginUsers(context: Context, arch: String = activeArch(context)): File = File(root(context, arch), "config/loginusers.vdf")
|
||||||
|
|
||||||
|
fun language(context: Context): String =
|
||||||
|
runCatching { SteamLibraryFolders.language(registry(context).readText()) }.getOrNull() ?: "english"
|
||||||
|
|
||||||
|
fun mounts(context: Context): List<SteamLibraryFolders.Mount> {
|
||||||
|
val out = ArrayList<SteamLibraryFolders.Mount>()
|
||||||
|
GameStorage.effective(context)?.let { card -> SecondaryLibrary.CARD_GUESTS.forEach { out += SteamLibraryFolders.Mount(it, File(card.path)) } }
|
||||||
|
SteamLibraries.list(context).forEach { out += SteamLibraryFolders.Mount(it.guest, it.host) }
|
||||||
|
AddedGames.roots(context).forEach { out += SteamLibraryFolders.Mount(it.guest, it.host) }
|
||||||
|
StoreInstallRoot.externalRoots(context).forEach { (host, guest) -> out += SteamLibraryFolders.Mount(guest, host) }
|
||||||
|
out += SteamLibraryFolders.Mount("/root/Storage", Environment.getExternalStorageDirectory())
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every library the client lists in libraryfolders.vdf that maps to a folder of the app. */
|
||||||
|
fun libraries(context: Context, arch: String = activeArch(context)): List<SteamLibraryFolders.Library> {
|
||||||
|
val root = root(context, arch)
|
||||||
|
val text = runCatching { File(root, "steamapps/libraryfolders.vdf").readText() }.getOrNull().orEmpty()
|
||||||
|
return SteamLibraryFolders.resolve(
|
||||||
|
SteamLibraryFolders.parse(text), guestRoot(arch), aliases(arch), root, mounts(context), LinuxRuntime.rootDir(context),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun canonical(file: File): String = runCatching { file.canonicalPath }.getOrDefault(file.absolutePath)
|
||||||
|
|
||||||
|
/** The card and added libraries are written through the raw card view when Android allows it, as the session binds them. */
|
||||||
|
private fun engineView(context: Context): (File) -> File {
|
||||||
|
val bases = listOfNotNull(GameStorage.effective(context)?.let { File(it.path) }) + SteamLibraries.list(context).map { it.host }
|
||||||
|
val seen = HashMap<String, File>()
|
||||||
|
return { host ->
|
||||||
|
val path = host.absolutePath
|
||||||
|
val base = bases.filter { path == it.absolutePath || path.startsWith(it.absolutePath + "/") }.maxByOrNull { it.absolutePath.length }
|
||||||
|
if (base == null) host else {
|
||||||
|
val content = seen.getOrPut(base.absolutePath) { SecondaryLibrary.contentPath(base) }
|
||||||
|
if (content.absolutePath == base.absolutePath) host
|
||||||
|
else path.removePrefix(base.absolutePath).trimStart('/').let { if (it.isEmpty()) content else File(content, it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class EngineLibraries(val libraries: List<Pair<SteamLibraryFolders.Library, File>>) {
|
||||||
|
val json: String get() = JSONArray().apply {
|
||||||
|
for ((library, host) in libraries) put(JSONObject().put("host", host.absolutePath).put("guest", library.guest))
|
||||||
|
}.toString()
|
||||||
|
|
||||||
|
fun hostOf(library: SteamLibraryFolders.Library): File =
|
||||||
|
libraries.firstOrNull { it.first.guest == library.guest }?.second ?: library.host
|
||||||
|
}
|
||||||
|
|
||||||
|
fun engineLibraries(context: Context, arch: String = activeArch(context)): EngineLibraries {
|
||||||
|
val view = engineView(context)
|
||||||
|
return EngineLibraries(libraries(context, arch).filter { it.host.isDirectory }.map { it to view(it.host) })
|
||||||
|
}
|
||||||
|
|
||||||
|
fun targets(context: Context): List<Target> {
|
||||||
|
val arch = activeArch(context)
|
||||||
|
val card = GameStorage.effective(context)?.let { canonical(File(it.path)) }
|
||||||
|
val known = Library.steamLibraries(context, arch).associate { (host, label) ->
|
||||||
|
canonical(host) to if (label == "internal") context.getString(R.string.games_internal) else label
|
||||||
|
}
|
||||||
|
val engine = engineLibraries(context)
|
||||||
|
return engine.libraries.mapNotNull { (library, host) ->
|
||||||
|
if (!library.host.isDirectory || !library.host.canWrite()) return@mapNotNull null
|
||||||
|
val path = canonical(library.host)
|
||||||
|
val onCard = card != null && (path == card || path.startsWith("$card/"))
|
||||||
|
val label = library.label.ifBlank {
|
||||||
|
if (library.main) context.getString(R.string.stores_target_internal) else known[path] ?: File(library.guest).name
|
||||||
|
}
|
||||||
|
Target(library, host, label, StoreInstallRoot.availableBytes(host), removable = onCard, folder = !library.main && !onCard)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True while a session that can run the Steam client is up or starting. */
|
||||||
|
fun clientMayRun(): Boolean {
|
||||||
|
val up = SessionState.running || (SessionState.phase != SessionPhase.IDLE && SessionState.phase != SessionPhase.FAILED)
|
||||||
|
return up && SessionState.mode != SessionService.MODE_RUN
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package com.droiddeck.launcher.stores.steam
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.os.SystemClock
|
||||||
|
import android.util.Log
|
||||||
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
|
import com.droiddeck.launcher.stores.StoresNative
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
/** Blocking calls into the Rust engine; they reach the network, so never on the main thread. */
|
||||||
|
internal object SteamEngine {
|
||||||
|
private const val TAG = "SteamEngine"
|
||||||
|
const val MISSING = "engine_missing"
|
||||||
|
const val MISSING_TEXT = "Steam: the store engine is not available"
|
||||||
|
|
||||||
|
private const val RETRY_MS = 60_000L
|
||||||
|
/** After Steam refuses sign-ins for coming too often, wait well past its limit. */
|
||||||
|
private const val THROTTLED_MS = 30 * 60_000L
|
||||||
|
|
||||||
|
private val lock = Any()
|
||||||
|
@Volatile private var signedIn = false
|
||||||
|
/** The saved login the last sign-in attempt read, so a refusal rejects that login and not one saved since. */
|
||||||
|
@Volatile var attempted: String? = null
|
||||||
|
private set
|
||||||
|
private var failed: JSONObject? = null
|
||||||
|
private var failedAt = 0L
|
||||||
|
|
||||||
|
fun failure(error: String): JSONObject = JSONObject().put("ok", false).put("error", error)
|
||||||
|
|
||||||
|
private fun call(op: String, block: () -> String): JSONObject {
|
||||||
|
if (!StoresNative.ensureLoaded()) return failure(MISSING)
|
||||||
|
val text = try {
|
||||||
|
block()
|
||||||
|
} catch (e: UnsatisfiedLinkError) {
|
||||||
|
Log.w(TAG, "$op: not in this engine build")
|
||||||
|
return failure(MISSING)
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
Log.w(TAG, "$op: ${t.javaClass.simpleName}")
|
||||||
|
return failure(t.javaClass.simpleName)
|
||||||
|
}
|
||||||
|
return runCatching { JSONObject(text) }.getOrElse { failure("$op: unreadable answer") }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun signIn(context: Context): JSONObject {
|
||||||
|
synchronized(lock) {
|
||||||
|
if (signedIn) return JSONObject().put("ok", true)
|
||||||
|
failed?.takeIf { SystemClock.elapsedRealtime() - failedAt < waitAfter(it) }?.let { return it }
|
||||||
|
val roots = JSONArray()
|
||||||
|
.put(SessionPrefs.steamRoot(context, "arm64").absolutePath)
|
||||||
|
.put(SessionPrefs.steamRoot(context, SteamClient.X86_64).absolutePath)
|
||||||
|
val registry = SteamClient.registry(context).absolutePath
|
||||||
|
attempted = SteamStore.fingerprint(context)
|
||||||
|
val answer = call("signIn") { SteamNative.nativeSignIn(roots.toString(), registry, "") }
|
||||||
|
signedIn = answer.optBoolean("ok")
|
||||||
|
failed = if (signedIn) null else answer
|
||||||
|
failedAt = SystemClock.elapsedRealtime()
|
||||||
|
if (!signedIn) Log.w(TAG, "sign-in: ${answer.optString("error")}")
|
||||||
|
return answer
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun waitAfter(failure: JSONObject): Long {
|
||||||
|
val error = failure.optString("error")
|
||||||
|
return if ("RateLimitExceeded" in error || "Throttle" in error) THROTTLED_MS else RETRY_MS
|
||||||
|
}
|
||||||
|
|
||||||
|
fun forget() {
|
||||||
|
synchronized(lock) {
|
||||||
|
failed = null
|
||||||
|
if (!signedIn) return
|
||||||
|
signedIn = false
|
||||||
|
try {
|
||||||
|
SteamNative.nativeSignOut()
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
Log.w(TAG, "sign-out: ${t.javaClass.simpleName}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun signedCall(context: Context, op: String, block: () -> String): JSONObject {
|
||||||
|
synchronized(lock) {
|
||||||
|
val signIn = signIn(context)
|
||||||
|
if (!signIn.optBoolean("ok")) return signIn
|
||||||
|
val answer = call(op, block)
|
||||||
|
val error = answer.optString("error").lowercase()
|
||||||
|
if (!answer.optBoolean("ok") && listOf("logon", "sign", "session", "connect").any { it in error }) signedIn = false
|
||||||
|
return answer
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun library(context: Context): JSONObject = signedCall(context, "library") { SteamNative.nativeLibrary() }
|
||||||
|
|
||||||
|
fun plan(context: Context, appId: Int, language: String): JSONObject =
|
||||||
|
signedCall(context, "plan") { SteamNative.nativePlan(appId, language) }
|
||||||
|
|
||||||
|
fun uninstall(appId: Int, steamRoot: String, host: String, guest: String, roots: String): JSONObject {
|
||||||
|
synchronized(lock) {
|
||||||
|
return call("uninstall") { SteamNative.nativeUninstall(appId, steamRoot, host, guest, roots) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
package com.droiddeck.launcher.stores.steam
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
|
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||||
|
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||||
|
import com.droiddeck.launcher.stores.download.StoreDownloadTier
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
import java.util.concurrent.CountDownLatch
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
import java.util.concurrent.atomic.AtomicBoolean
|
||||||
|
import java.util.concurrent.atomic.AtomicReference
|
||||||
|
|
||||||
|
/** Called by the engine on its own threads. */
|
||||||
|
interface SteamInstallListener {
|
||||||
|
fun onProgress(doneBytes: Long, totalBytes: Long, phase: String?)
|
||||||
|
fun onComplete(ok: Boolean, result: String?)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal class SteamInstallJob(
|
||||||
|
private val app: Context,
|
||||||
|
private val appId: Int,
|
||||||
|
private val libraryGuest: String,
|
||||||
|
) : DownloadQueue.DownloadJob {
|
||||||
|
private val cancelled = AtomicBoolean(false)
|
||||||
|
private val started = AtomicBoolean(false)
|
||||||
|
@Volatile private var discard = false
|
||||||
|
@Volatile private var installDir: String? = null
|
||||||
|
@Volatile private var createdDir = false
|
||||||
|
|
||||||
|
override fun run(handle: DownloadQueue.JobHandle): String? {
|
||||||
|
started.set(true)
|
||||||
|
try {
|
||||||
|
return install(handle)
|
||||||
|
} finally {
|
||||||
|
if (discard) SteamStore.discardPartial(app, appId, libraryGuest, installDir, createdDir)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun install(handle: DownloadQueue.JobHandle): String? {
|
||||||
|
handle.stage(DownloadStage.MANIFEST)
|
||||||
|
if (SteamClient.clientMayRun()) throw IllegalStateException(app.getString(R.string.steam_store_close_steam))
|
||||||
|
val engine = SteamClient.engineLibraries(app)
|
||||||
|
val target = engine.libraries.firstOrNull { SteamClient.sameLibrary(app, it.first, libraryGuest) }
|
||||||
|
?: throw IllegalStateException(app.getString(R.string.game_sync_err_steam_library))
|
||||||
|
val signIn = SteamEngine.signIn(app)
|
||||||
|
if (!signIn.optBoolean("ok")) {
|
||||||
|
SteamStore.signInFailed(app, signIn.optString("error"))
|
||||||
|
throw IllegalStateException(SteamStore.errorText(app, signIn))
|
||||||
|
}
|
||||||
|
val language = SteamClient.language(app)
|
||||||
|
val (plan, planned) = SteamStore.plan(app, appId, language)
|
||||||
|
if (plan == null) throw IllegalStateException(SteamStore.errorText(app, planned))
|
||||||
|
installDir = plan.installDir
|
||||||
|
createdDir = SteamStore.claimFolder(app, appId, libraryGuest, File(target.second, "steamapps/common/${plan.installDir}"))
|
||||||
|
if (plan.installBytes > 0) handle.diskSize(plan.installBytes)
|
||||||
|
if (cancelled.get()) return null
|
||||||
|
|
||||||
|
val tier = StoreDownloadTier.current(app)
|
||||||
|
val journal = File(app.filesDir, "${SteamStore.JOURNAL}/$appId").apply { mkdirs() }
|
||||||
|
handle.log("steam: $appId tier=${tier.id} window=${tier.networkWindow} process_workers=${tier.processWorkers}")
|
||||||
|
val done = CountDownLatch(1)
|
||||||
|
val succeeded = AtomicBoolean(false)
|
||||||
|
val answer = AtomicReference("")
|
||||||
|
val listener = object : SteamInstallListener {
|
||||||
|
private var stage: DownloadStage? = null
|
||||||
|
private var shown = -1L
|
||||||
|
|
||||||
|
override fun onProgress(doneBytes: Long, totalBytes: Long, phase: String?) {
|
||||||
|
synchronized(this) {
|
||||||
|
val now = SteamLibraryFolders.stageOf(phase.orEmpty())
|
||||||
|
if (now != stage) {
|
||||||
|
stage = now
|
||||||
|
shown = -1L
|
||||||
|
}
|
||||||
|
if (doneBytes < shown) return
|
||||||
|
shown = doneBytes
|
||||||
|
if (now == DownloadStage.DOWNLOAD) handle.progress(doneBytes, totalBytes)
|
||||||
|
else {
|
||||||
|
handle.stage(now)
|
||||||
|
if (totalBytes > 0) handle.stageProgress(doneBytes, totalBytes, bytes = true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onComplete(ok: Boolean, result: String?) {
|
||||||
|
answer.set(result.orEmpty())
|
||||||
|
succeeded.set(ok)
|
||||||
|
done.countDown()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val native = try {
|
||||||
|
SteamNative.nativeStart(
|
||||||
|
appId, language, SteamClient.root(app).absolutePath, target.second.absolutePath, target.first.guest, engine.json,
|
||||||
|
journal.absolutePath, "", tier.networkWindow.coerceIn(1, 128), tier.processWorkers, listener,
|
||||||
|
)
|
||||||
|
} catch (e: UnsatisfiedLinkError) {
|
||||||
|
throw IllegalStateException(SteamEngine.MISSING_TEXT)
|
||||||
|
}
|
||||||
|
if (native == 0L && done.count > 0L) throw IllegalStateException(SteamStore.errorText(app, parse(answer.get())))
|
||||||
|
if (native != 0L) {
|
||||||
|
try {
|
||||||
|
var forwarded = false
|
||||||
|
while (true) {
|
||||||
|
val finished = try {
|
||||||
|
done.await(CANCEL_POLL_MS, TimeUnit.MILLISECONDS)
|
||||||
|
} catch (e: InterruptedException) {
|
||||||
|
cancelled.set(true)
|
||||||
|
false
|
||||||
|
}
|
||||||
|
if (finished) break
|
||||||
|
if (!forwarded && cancelled.get()) {
|
||||||
|
runCatching { SteamNative.nativeCancel(native) }
|
||||||
|
forwarded = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
runCatching { SteamNative.nativeRelease(native) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val result = parse(answer.get())
|
||||||
|
if (succeeded.get() && result.optBoolean("ok", true)) {
|
||||||
|
SteamStore.forgetJournal(app, appId, libraryGuest, target.first.guest)
|
||||||
|
return File(target.first.host, "steamapps/common/${plan.installDir}").path
|
||||||
|
}
|
||||||
|
if (cancelled.get() || result.optString("error") == "cancelled") return null
|
||||||
|
throw IllegalStateException(SteamStore.errorText(app, result))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parse(text: String): JSONObject =
|
||||||
|
runCatching { JSONObject(text) }.getOrElse { SteamEngine.failure(text.ifBlank { "install failed" }) }
|
||||||
|
|
||||||
|
override fun cancel(deleteFiles: Boolean) {
|
||||||
|
cancelled.set(true)
|
||||||
|
if (!deleteFiles) return
|
||||||
|
discard = true
|
||||||
|
if (!started.get()) SteamStore.discardPartial(app, appId, libraryGuest, null, SteamStore.createdFolder(app, appId, libraryGuest))
|
||||||
|
}
|
||||||
|
|
||||||
|
private companion object {
|
||||||
|
const val CANCEL_POLL_MS = 250L
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
package com.droiddeck.launcher.stores.steam
|
||||||
|
|
||||||
|
import com.droiddeck.launcher.storage.SteamStorage
|
||||||
|
import com.droiddeck.launcher.stores.download.DownloadStage
|
||||||
|
import java.io.File
|
||||||
|
|
||||||
|
internal object SteamLibraryFolders {
|
||||||
|
data class Folder(val path: String, val label: String)
|
||||||
|
|
||||||
|
class Mount(guest: String, val host: File) {
|
||||||
|
val guest: String = guest.trimEnd('/')
|
||||||
|
}
|
||||||
|
|
||||||
|
data class Library(val guest: String, val host: File, val label: String, val main: Boolean)
|
||||||
|
|
||||||
|
data class Installed(val appId: Int, val name: String, val installDir: String?, val library: Library, val sizeOnDisk: Long)
|
||||||
|
|
||||||
|
/** Guest folders that exist only as binds of the session; without their bind they are empty mount points in the rootfs. */
|
||||||
|
val BIND_ONLY = listOf("/mnt", "/media", "/storage", "/sdcard", "/root/Storage", "/root/ROMs", "/root/Games")
|
||||||
|
|
||||||
|
private val TOKEN = Regex("\"((?:\\\\.|[^\"\\\\])*)\"|[{}]|//[^\n]*")
|
||||||
|
private val ACF = Regex("appmanifest_\\d+\\.acf")
|
||||||
|
private val SIZE_ON_DISK = Regex("^\\s*\"SizeOnDisk\"\\s*\"(\\d+)\"", setOf(RegexOption.MULTILINE, RegexOption.IGNORE_CASE))
|
||||||
|
|
||||||
|
private fun walk(text: String, pair: (blocks: List<String>, key: String, value: String) -> Unit, closed: (blocks: List<String>) -> Unit = {}) {
|
||||||
|
val blocks = ArrayList<String>()
|
||||||
|
var key: String? = null
|
||||||
|
for (m in TOKEN.findAll(text)) {
|
||||||
|
val token = m.value
|
||||||
|
when {
|
||||||
|
token.startsWith("//") -> {}
|
||||||
|
token == "{" -> { blocks.add(key.orEmpty()); key = null }
|
||||||
|
token == "}" -> { if (blocks.isNotEmpty()) { closed(blocks); blocks.removeAt(blocks.lastIndex) }; key = null }
|
||||||
|
key == null -> key = unescape(m.groupValues[1])
|
||||||
|
else -> { pair(blocks, key, unescape(m.groupValues[1])); key = null }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun unescape(s: String): String {
|
||||||
|
if ('\\' !in s) return s
|
||||||
|
val out = StringBuilder(s.length)
|
||||||
|
var i = 0
|
||||||
|
while (i < s.length) {
|
||||||
|
if (s[i] == '\\' && i + 1 < s.length) { out.append(s[i + 1]); i += 2 } else { out.append(s[i]); i++ }
|
||||||
|
}
|
||||||
|
return out.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun inRoot(blocks: List<String>) = blocks.firstOrNull()?.equals("libraryfolders", ignoreCase = true) == true
|
||||||
|
|
||||||
|
fun parse(text: String): List<Folder> {
|
||||||
|
val out = ArrayList<Folder>()
|
||||||
|
var path: String? = null
|
||||||
|
var label = ""
|
||||||
|
walk(text, pair = { blocks, key, value ->
|
||||||
|
if (!inRoot(blocks)) return@walk
|
||||||
|
if (blocks.size == 1 && key.isNotEmpty() && key.all(Char::isDigit)) out += Folder(value, "")
|
||||||
|
if (blocks.size == 2) when (key.lowercase()) {
|
||||||
|
"path" -> path = value
|
||||||
|
"label" -> label = value
|
||||||
|
}
|
||||||
|
}, closed = { blocks ->
|
||||||
|
if (blocks.size == 2 && inRoot(blocks)) path?.let { out += Folder(it, label) }
|
||||||
|
if (blocks.size == 2) { path = null; label = "" }
|
||||||
|
})
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
fun normalize(path: String): String? {
|
||||||
|
val p = path.trim().replace(Regex("/+"), "/").trimEnd('/')
|
||||||
|
if (!p.startsWith("/") || p.split('/').any { it == ".." || it == "." }) return null
|
||||||
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun under(path: String, prefix: String) = path == prefix || path.startsWith("$prefix/")
|
||||||
|
|
||||||
|
fun hostFor(guest: String, mounts: List<Mount>, rootfs: File): File? {
|
||||||
|
val path = normalize(guest) ?: return null
|
||||||
|
mounts.filter { it.guest.isNotEmpty() && under(path, it.guest) }.maxByOrNull { it.guest.length }?.let { m ->
|
||||||
|
val rest = path.removePrefix(m.guest).trimStart('/')
|
||||||
|
return if (rest.isEmpty()) m.host else File(m.host, rest)
|
||||||
|
}
|
||||||
|
if (BIND_ONLY.any { under(path, it) } || !under(path, "/root")) return null
|
||||||
|
return File(rootfs, path.removePrefix("/"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fun resolve(folders: List<Folder>, mainGuest: String, aliases: Collection<String>, mainHost: File, mounts: List<Mount>, rootfs: File): List<Library> {
|
||||||
|
val mains = (aliases + mainGuest).mapNotNull(::normalize).toSet()
|
||||||
|
val listed = if (folders.any { normalize(it.path) in mains }) folders else listOf(Folder(mainGuest, "")) + folders
|
||||||
|
val out = ArrayList<Library>()
|
||||||
|
// The main library first, so an entry reaching the same folder under another path cannot take its place.
|
||||||
|
for (f in listed.sortedByDescending { normalize(it.path) in mains }) {
|
||||||
|
val guest = normalize(f.path) ?: continue
|
||||||
|
val main = guest in mains
|
||||||
|
val host = if (main) mainHost else hostFor(guest, mounts, rootfs) ?: continue
|
||||||
|
if (out.any { it.host.path == host.path || (main && it.main) }) continue
|
||||||
|
out += Library(guest, host, f.label.trim(), main)
|
||||||
|
}
|
||||||
|
return out.sortedByDescending { it.main }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun installed(libraries: List<Library>, read: (File) -> String? = { runCatching { it.readText() }.getOrNull() }): Map<Int, Installed> {
|
||||||
|
val out = LinkedHashMap<Int, Installed>()
|
||||||
|
for (library in libraries) {
|
||||||
|
val apps = File(library.host, "steamapps")
|
||||||
|
val names = apps.list() ?: continue
|
||||||
|
for (name in names.sorted()) {
|
||||||
|
if (!ACF.matches(name)) continue
|
||||||
|
val file = File(apps, name)
|
||||||
|
val text = read(file) ?: continue
|
||||||
|
val manifest = SteamStorage.parseManifest(file, text) ?: continue
|
||||||
|
if (!manifest.installed || SteamStorage.isTool(manifest) || manifest.appId in out) continue
|
||||||
|
val size = SIZE_ON_DISK.find(text)?.groupValues?.get(1)?.toLongOrNull() ?: 0L
|
||||||
|
out[manifest.appId] = Installed(manifest.appId, manifest.name, manifest.installDir, library, size)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
data class SavedAccount(val id: String, val name: String)
|
||||||
|
|
||||||
|
fun savedAccount(loginUsers: String): String? = savedLogin(loginUsers)?.name
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The account the client signs in with by itself, chosen as the engine does: `AutoLoginUser`, else the most recent, else the newest;
|
||||||
|
* none when that account opted out of Remember me. [SavedAccount.id] is its SteamID64.
|
||||||
|
*/
|
||||||
|
fun savedLogin(loginUsers: String, registry: String = ""): SavedAccount? {
|
||||||
|
val users = LinkedHashMap<String, HashMap<String, String>>()
|
||||||
|
walk(loginUsers, pair = { blocks, key, value ->
|
||||||
|
if (blocks.size == 2 && blocks[0].equals("users", ignoreCase = true)) users.getOrPut(blocks[1]) { HashMap() }[key.lowercase()] = value
|
||||||
|
})
|
||||||
|
val accounts = users.entries.filter { it.key.all(Char::isDigit) && !it.value["accountname"].isNullOrBlank() }
|
||||||
|
val auto = autoLoginUser(registry)
|
||||||
|
val (id, user) = auto?.let { name -> accounts.firstOrNull { it.value["accountname"].equals(name, ignoreCase = true) } }
|
||||||
|
?: accounts.firstOrNull { it.value["mostrecent"] == "1" }
|
||||||
|
?: accounts.maxByOrNull { it.value["timestamp"]?.toLongOrNull() ?: 0L }
|
||||||
|
?: return null
|
||||||
|
if (user["rememberpassword"] == "0") return null
|
||||||
|
val name = user["personaname"]?.takeIf { it.isNotBlank() } ?: user["accountname"]?.takeIf { it.isNotBlank() } ?: return null
|
||||||
|
return SavedAccount(id, name)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun autoLoginUser(registry: String): String? {
|
||||||
|
var found: String? = null
|
||||||
|
walk(registry, pair = { blocks, key, value ->
|
||||||
|
if (found == null && key.equals("AutoLoginUser", ignoreCase = true) && blocks.lastOrNull().equals("Steam", ignoreCase = true) && value.isNotBlank()) found = value
|
||||||
|
})
|
||||||
|
return found
|
||||||
|
}
|
||||||
|
|
||||||
|
fun language(registry: String): String? {
|
||||||
|
var found: String? = null
|
||||||
|
walk(registry, pair = { blocks, key, value ->
|
||||||
|
if (found == null && key.equals("language", ignoreCase = true) && blocks.lastOrNull().equals("Steam", ignoreCase = true) && value.isNotBlank()) found = value
|
||||||
|
})
|
||||||
|
return found
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stageOf(phase: String): DownloadStage {
|
||||||
|
val p = phase.lowercase()
|
||||||
|
return when {
|
||||||
|
"verif" in p || "validat" in p -> DownloadStage.VERIFY
|
||||||
|
listOf("install", "regist", "final", "commit", "acf", "apply").any { it in p } -> DownloadStage.INSTALL
|
||||||
|
listOf("manifest", "plan", "prepar", "check", "scan", "clean", "alloc", "connect", "logon", "login", "sign").any { it in p } -> DownloadStage.MANIFEST
|
||||||
|
else -> DownloadStage.DOWNLOAD
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
package com.droiddeck.launcher.stores.steam
|
||||||
|
|
||||||
|
object SteamNative {
|
||||||
|
@JvmStatic external fun nativeSignIn(steamRootsJson: String, registryVdfPath: String, caBundlePath: String): String
|
||||||
|
@JvmStatic external fun nativeSignOut()
|
||||||
|
@JvmStatic external fun nativeLibrary(): String
|
||||||
|
@JvmStatic external fun nativePlan(appId: Int, language: String): String
|
||||||
|
@JvmStatic external fun nativeStart(appId: Int, language: String, steamRoot: String, gameLibraryHost: String, gameLibraryGuest: String, libraryRootsJson: String, journalDir: String, caBundlePath: String, maxWorkers: Int, processWorkers: Int, listener: Any): Long
|
||||||
|
@JvmStatic external fun nativeCancel(handle: Long)
|
||||||
|
@JvmStatic external fun nativeRelease(handle: Long)
|
||||||
|
@JvmStatic external fun nativeUninstall(appId: Int, steamRoot: String, gameLibraryHost: String, gameLibraryGuest: String, libraryRootsJson: String): String
|
||||||
|
}
|
||||||
@@ -0,0 +1,399 @@
|
|||||||
|
package com.droiddeck.launcher.stores.steam
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.net.Uri
|
||||||
|
import android.util.Log
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.annotation.StringRes
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
|
import com.droiddeck.launcher.frontend.Library
|
||||||
|
import com.droiddeck.launcher.session.SessionService
|
||||||
|
import com.droiddeck.launcher.storage.SteamStorage
|
||||||
|
import com.droiddeck.launcher.stores.CatalogItem
|
||||||
|
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||||
|
import com.droiddeck.launcher.stores.Store
|
||||||
|
import com.droiddeck.launcher.stores.StoreAccounts
|
||||||
|
import com.droiddeck.launcher.stores.StoreBackend
|
||||||
|
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||||
|
import com.droiddeck.launcher.stores.StoreInstalls
|
||||||
|
import com.droiddeck.launcher.stores.StoreSizes
|
||||||
|
import com.droiddeck.launcher.stores.StoresState
|
||||||
|
import com.droiddeck.launcher.stores.download.DownloadEntry
|
||||||
|
import com.droiddeck.launcher.stores.download.DownloadQueue
|
||||||
|
import com.droiddeck.launcher.stores.download.DownloadState
|
||||||
|
import com.droiddeck.launcher.stores.download.SavedQueue
|
||||||
|
import com.droiddeck.launcher.stores.formatBytes
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
import java.util.concurrent.Executors
|
||||||
|
|
||||||
|
/** Games land in the active client's own libraries, registered as the client does, and only while no session can run the client. */
|
||||||
|
internal object SteamStore {
|
||||||
|
private const val TAG = "SteamStore"
|
||||||
|
private const val PREFS = "steam-store"
|
||||||
|
internal const val JOURNAL = "steam-store/journal"
|
||||||
|
private const val CDN = "https://cdn.cloudflare.steamstatic.com/steam/apps/"
|
||||||
|
private const val LIBRARY = "library"
|
||||||
|
private const val LIBRARY_LABEL = "libraryLabel"
|
||||||
|
private val SIGNED_OUT = setOf("no_saved_login", "remember_me_off", "decrypt_failed")
|
||||||
|
private val REFUSED = Regex("logon_failed: eresult=(-?\\d+).*")
|
||||||
|
/** InvalidPassword, AccessDenied, AccountNotFound, Revoked, Expired, AccountLogonDenied. */
|
||||||
|
private val REFUSALS = setOf(5, 15, 18, 26, 27, 63)
|
||||||
|
|
||||||
|
var picking by mutableStateOf<CatalogItem?>(null)
|
||||||
|
|
||||||
|
class Plan(val installDir: String, val downloadBytes: Long, val installBytes: Long, val buildId: String, val linuxBuild: Boolean) {
|
||||||
|
companion object {
|
||||||
|
fun of(json: JSONObject): Plan? {
|
||||||
|
if (!json.optBoolean("ok")) return null
|
||||||
|
val dir = json.optString("installDir").takeIf { SteamStore.validDir(it) } ?: return null
|
||||||
|
return Plan(dir, json.optLong("downloadBytes"), json.optLong("installBytes"), json.optString("buildId"), json.optBoolean("linuxBuild"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal const val LINUX_BUILD = "linux_build"
|
||||||
|
|
||||||
|
/** Each plan with the language it was made for. */
|
||||||
|
private val plans = ConcurrentHashMap<Int, Pair<String, Plan>>()
|
||||||
|
private val work = Executors.newSingleThreadExecutor { r -> Thread(r, "steam-store") }
|
||||||
|
@Volatile private var rejectedThisRun: String? = null
|
||||||
|
|
||||||
|
fun key(appId: Int): String = "${Store.STEAM.id}:$appId"
|
||||||
|
|
||||||
|
private fun validDir(dir: String) = dir.isNotBlank() && dir != "." && dir != ".." && '/' !in dir && '\\' !in dir
|
||||||
|
|
||||||
|
private fun prefs(context: Context) = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||||
|
|
||||||
|
private fun toast(context: Context, @StringRes text: Int) {
|
||||||
|
val app = context.applicationContext
|
||||||
|
StoresState.post { Toast.makeText(app, text, Toast.LENGTH_LONG).show() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Steam refusing the saved login; a connection failure or a throttled logon leaves the account as it is. */
|
||||||
|
internal fun isSignInError(error: String) =
|
||||||
|
error in SIGNED_OUT || REFUSED.matchEntire(error)?.groupValues?.get(1)?.toIntOrNull() in REFUSALS
|
||||||
|
|
||||||
|
internal fun errorText(context: Context, answer: JSONObject): String {
|
||||||
|
val error = answer.optString("error")
|
||||||
|
return when {
|
||||||
|
error == SteamEngine.MISSING -> SteamEngine.MISSING_TEXT
|
||||||
|
error == LINUX_BUILD -> context.getString(R.string.steam_store_linux_build)
|
||||||
|
isSignInError(error) -> context.getString(R.string.stores_login_title, Store.STEAM.label)
|
||||||
|
error.isBlank() -> "Steam: install failed"
|
||||||
|
else -> error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun fingerprint(context: Context): String {
|
||||||
|
val users = SteamClient.loginUsers(context)
|
||||||
|
val registry = SteamClient.registry(context)
|
||||||
|
return "${SteamClient.activeArch(context)}:${users.lastModified()}:${users.length()}:${registry.lastModified()}:${registry.length()}"
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun savedAccount(context: Context): SteamLibraryFolders.SavedAccount? {
|
||||||
|
val print = fingerprint(context)
|
||||||
|
if (print == rejectedThisRun || print == prefs(context).getString("rejected", null)) return null
|
||||||
|
val registry = runCatching { SteamClient.registry(context).readText() }.getOrDefault("")
|
||||||
|
return runCatching { SteamLibraryFolders.savedLogin(SteamClient.loginUsers(context).readText(), registry) }.getOrNull()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mirrors the client's saved sign-in into the store account; reads storage. A new name for the same account only relabels it. */
|
||||||
|
fun syncAccount(context: Context): Boolean {
|
||||||
|
val saved = savedAccount(context)
|
||||||
|
val stored = StoreAccounts.read(context, Store.STEAM)
|
||||||
|
val storedId = stored?.optString("steam_id").orEmpty()
|
||||||
|
if (saved != null && saved.id == storedId) {
|
||||||
|
if (saved.name != stored?.optString("display_name")) {
|
||||||
|
StoreAccounts.write(context, Store.STEAM, JSONObject().put("display_name", saved.name).put("steam_id", saved.id))
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if (saved == null && stored == null) return false
|
||||||
|
if (saved == null) StoreAccounts.clear(context, Store.STEAM)
|
||||||
|
else StoreAccounts.write(context, Store.STEAM, JSONObject().put("display_name", saved.name).put("steam_id", saved.id))
|
||||||
|
plans.clear()
|
||||||
|
SteamEngine.forget()
|
||||||
|
StoresState.post {
|
||||||
|
StoresState.library.remove(Store.STEAM)
|
||||||
|
StoresState.problems.remove(Store.STEAM)
|
||||||
|
}
|
||||||
|
Log.i(TAG, if (saved == null) "no saved Steam sign-in" else "Steam sign-in found")
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun signInFailed(context: Context, error: String) {
|
||||||
|
if (!isSignInError(error)) return
|
||||||
|
val print = fingerprint(context)
|
||||||
|
if (SteamEngine.attempted?.let { it != print } == true) return
|
||||||
|
rejectedThisRun = print
|
||||||
|
if (error in SIGNED_OUT) prefs(context).edit().putString("rejected", print).apply()
|
||||||
|
StoreAccounts.clear(context, Store.STEAM)
|
||||||
|
StoresState.logLine("Steam: the saved sign-in was not accepted ($error)")
|
||||||
|
StoresState.post {
|
||||||
|
StoresState.accounts.remove(Store.STEAM)
|
||||||
|
StoresState.library.remove(Store.STEAM)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun downloading(): Boolean = StoresState.latestDownloads.any {
|
||||||
|
it.store == Store.STEAM && (it.state == DownloadState.RUNNING || it.state == DownloadState.QUEUED)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A Steam store download holds every session that could start the Steam client. */
|
||||||
|
fun blocksSession(intent: Intent?): Boolean {
|
||||||
|
val mode = intent?.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM
|
||||||
|
return mode != SessionService.MODE_RUN && (downloading() || StoresState.uninstalling.keys.any { it.startsWith("${Store.STEAM.id}:") })
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun syncLibrary(context: Context, force: Boolean) {
|
||||||
|
val app = context.applicationContext
|
||||||
|
if (force) plans.clear()
|
||||||
|
work.execute {
|
||||||
|
val answer = SteamEngine.library(app)
|
||||||
|
if (!answer.optBoolean("ok")) {
|
||||||
|
val error = answer.optString("error")
|
||||||
|
if (isSignInError(error)) signInFailed(app, error)
|
||||||
|
else StoresState.post {
|
||||||
|
StoresState.problems[Store.STEAM] = errorText(app, answer)
|
||||||
|
StoresState.library[Store.STEAM] = emptyList()
|
||||||
|
}
|
||||||
|
return@execute
|
||||||
|
}
|
||||||
|
val art = runCatching { Library.steamLibraryArt(app).toMap() }.getOrDefault(emptyMap())
|
||||||
|
val items = items(answer.optJSONArray("games"), art)
|
||||||
|
StoresState.logLine("Steam: library has ${items.size} games")
|
||||||
|
StoresState.post {
|
||||||
|
StoresState.problems.remove(Store.STEAM)
|
||||||
|
StoresState.library[Store.STEAM] = items
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun items(games: JSONArray?, art: Map<Int, File>): List<CatalogItem> {
|
||||||
|
val out = ArrayList<CatalogItem>()
|
||||||
|
for (i in 0 until (games?.length() ?: 0)) {
|
||||||
|
val game = games?.optJSONObject(i) ?: continue
|
||||||
|
val id = game.optInt("appId").takeIf { it > 0 } ?: continue
|
||||||
|
val type = game.optString("type").lowercase()
|
||||||
|
if (type.isNotEmpty() && type != "game") continue
|
||||||
|
val name = game.optString("name").takeIf { it.isNotBlank() } ?: continue
|
||||||
|
out += CatalogItem(
|
||||||
|
Store.STEAM, id.toString(), name,
|
||||||
|
imageUrl = "$CDN$id/header.jpg",
|
||||||
|
tallImageUrl = art[id]?.let { Uri.fromFile(it).toString() } ?: "$CDN$id/library_600x900.jpg",
|
||||||
|
isFree = game.optBoolean("free"),
|
||||||
|
storeUrl = "https://store.steampowered.com/app/$id/",
|
||||||
|
owned = true,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return out.distinctBy { it.id }.sortedBy { it.title.lowercase() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Reaches the network; call off the main thread. */
|
||||||
|
internal fun plan(context: Context, appId: Int, language: String = SteamClient.language(context)): Pair<Plan?, JSONObject> {
|
||||||
|
val plan = plans[appId]?.takeIf { it.first == language }?.second ?: run {
|
||||||
|
val answer = SteamEngine.plan(context, appId, language)
|
||||||
|
val error = answer.optString("error")
|
||||||
|
if (isSignInError(error)) signInFailed(context, error)
|
||||||
|
Plan.of(answer)?.also { plans[appId] = language to it } ?: return null to answer
|
||||||
|
}
|
||||||
|
if (plan.linuxBuild && !protonMapped(context, appId)) return null to SteamEngine.failure(LINUX_BUILD)
|
||||||
|
return plan to JSONObject().put("ok", true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The engine installs the Windows depots; a game with a Linux build gets those from the client only when it is mapped to a Proton. */
|
||||||
|
private fun protonMapped(context: Context, appId: Int): Boolean {
|
||||||
|
val config = runCatching { File(SteamClient.root(context), "config/config.vdf").readText() }.getOrNull() ?: return false
|
||||||
|
return SteamStorage.compatMappings(config)[appId.toString()]?.contains("proton", ignoreCase = true) == true
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun plannedBytes(context: Context, item: CatalogItem): Long =
|
||||||
|
item.id.toIntOrNull()?.let { plan(context, it).first?.installBytes } ?: 0L
|
||||||
|
|
||||||
|
fun requestInstall(context: Context, item: CatalogItem) {
|
||||||
|
if (SteamClient.clientMayRun()) {
|
||||||
|
toast(context, R.string.steam_store_close_steam)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
picking = item
|
||||||
|
}
|
||||||
|
|
||||||
|
fun install(context: Context, item: CatalogItem, target: SteamClient.Target) {
|
||||||
|
val app = context.applicationContext
|
||||||
|
val appId = item.id.toIntOrNull() ?: return
|
||||||
|
if (SteamClient.clientMayRun()) {
|
||||||
|
toast(app, R.string.steam_store_close_steam)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val plan = plans[appId]?.second
|
||||||
|
val needed = plan?.installBytes ?: 0L
|
||||||
|
val tagged = item.copy(extra = item.extra + mapOf(LIBRARY to target.library.guest, LIBRARY_LABEL to target.label))
|
||||||
|
val entry = DownloadEntry(
|
||||||
|
Store.STEAM, item.id, item.title, cover = item.imageUrl,
|
||||||
|
bytesTotal = plan?.downloadBytes ?: 0L, location = target.label,
|
||||||
|
)
|
||||||
|
SavedQueue.remember(app, tagged, target.library.host)
|
||||||
|
if (StoreInstallRoot.insufficientSpace(needed, target.freeBytes)) {
|
||||||
|
val error = app.getString(R.string.stores_storage_insufficient, formatBytes(needed), formatBytes(target.freeBytes))
|
||||||
|
DownloadQueue.recordFailed(app, entry, error) { requestInstall(app, item) }
|
||||||
|
return
|
||||||
|
}
|
||||||
|
DownloadQueue.enqueue(app, entry) { SteamInstallJob(app, appId, target.library.guest) }
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun restore(context: Context, item: CatalogItem) {
|
||||||
|
val app = context.applicationContext
|
||||||
|
val appId = item.id.toIntOrNull() ?: return
|
||||||
|
val guest = item.extra[LIBRARY] ?: return
|
||||||
|
work.execute {
|
||||||
|
// Either client may have finished the install from where this download was paused.
|
||||||
|
if (installedByAClient(app, appId)) {
|
||||||
|
DownloadQueue.dropHeld(key(appId))
|
||||||
|
StoresState.logLine("Steam: \"${item.title}\" was finished by Steam; its saved download is dropped")
|
||||||
|
return@execute
|
||||||
|
}
|
||||||
|
StoresState.post {
|
||||||
|
SavedQueue.remember(app, item, null)
|
||||||
|
val entry = DownloadEntry(Store.STEAM, item.id, item.title, cover = item.imageUrl, location = item.extra[LIBRARY_LABEL].orEmpty())
|
||||||
|
DownloadQueue.enqueue(app, entry) { SteamInstallJob(app, appId, guest) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun installedByAClient(context: Context, appId: Int): Boolean = listOf("arm64", SteamClient.X86_64).any { arch ->
|
||||||
|
runCatching { appId in SteamLibraryFolders.installed(SteamClient.libraries(context, arch)) }.getOrDefault(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Removes a game like the client does; [fallback] deletes it when the engine cannot (no engine, or a library it does not map). */
|
||||||
|
fun uninstall(context: Context, appId: Int, manifest: File?, fallback: () -> Boolean, onDone: () -> Unit = {}) {
|
||||||
|
val app = context.applicationContext
|
||||||
|
if (SteamClient.clientMayRun()) {
|
||||||
|
toast(app, R.string.steam_store_close_steam)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val key = key(appId)
|
||||||
|
if (key in StoresState.uninstalling) return
|
||||||
|
StoresState.uninstalling[key] = 0f
|
||||||
|
Thread({
|
||||||
|
if (!DownloadQueue.holdForRemovalWhenFree(key)) {
|
||||||
|
StoresState.logLine("Steam: kept $appId, its download is still running")
|
||||||
|
StoresState.post { StoresState.uninstalling.remove(key); onDone() }
|
||||||
|
return@Thread
|
||||||
|
}
|
||||||
|
val answer = try { runCatching {
|
||||||
|
val apps = manifest?.parentFile?.let(::canonical)
|
||||||
|
// The game may sit in the other client's library; that client's files are the ones to update.
|
||||||
|
val active = SteamClient.activeArch(app)
|
||||||
|
val found = listOf(active, if (active == SteamClient.X86_64) "arm64" else SteamClient.X86_64).firstNotNullOfOrNull { arch ->
|
||||||
|
val libraries = SteamClient.libraries(app, arch)
|
||||||
|
val chosen = if (apps == null) libraries else libraries.filter { canonical(File(it.host, "steamapps")) == apps }
|
||||||
|
SteamLibraryFolders.installed(chosen)[appId]?.let { arch to it }
|
||||||
|
}
|
||||||
|
val answer = if (found == null) SteamEngine.failure(SteamEngine.MISSING) else {
|
||||||
|
val (arch, game) = found
|
||||||
|
val engine = SteamClient.engineLibraries(app, arch)
|
||||||
|
SteamEngine.uninstall(appId, SteamClient.root(app, arch).absolutePath, engine.hostOf(game.library).absolutePath, game.library.guest, engine.json)
|
||||||
|
}
|
||||||
|
when {
|
||||||
|
answer.optString("error") != SteamEngine.MISSING -> answer
|
||||||
|
fallback() -> JSONObject().put("ok", true)
|
||||||
|
else -> SteamEngine.failure("remove_failed")
|
||||||
|
}
|
||||||
|
}.getOrElse { SteamEngine.failure(it.javaClass.simpleName) } } finally { DownloadQueue.releaseRemoval(key) }
|
||||||
|
val ok = answer.optBoolean("ok")
|
||||||
|
StoresState.logLine(if (ok) "Steam: uninstalled $appId" else "Steam: uninstall of $appId failed: ${answer.optString("error")}")
|
||||||
|
StoresState.post {
|
||||||
|
StoresState.uninstalling.remove(key)
|
||||||
|
if (ok) StoreSizes.onDisk.remove(key)
|
||||||
|
else Toast.makeText(app, errorText(app, answer), Toast.LENGTH_LONG).show()
|
||||||
|
onDone()
|
||||||
|
}
|
||||||
|
}, "steam-uninstall").start()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun canonical(file: File): String = runCatching { file.canonicalPath }.getOrDefault(file.absolutePath)
|
||||||
|
|
||||||
|
/** The engine keys an app's resume journal by library as `<journal>/<appId>/<appId>/<crc32 of the guest path>`. */
|
||||||
|
private fun libraryKey(guest: String): String =
|
||||||
|
"%08x".format(java.util.zip.CRC32().apply { update(guest.trimEnd('/').toByteArray()) }.value)
|
||||||
|
|
||||||
|
private fun createdMarker(context: Context, appId: Int, guest: String) =
|
||||||
|
File(context.filesDir, "$JOURNAL/$appId/created-${libraryKey(guest)}")
|
||||||
|
|
||||||
|
/** Drops the resume state of one app in one library; other libraries' downloads of the app keep theirs. */
|
||||||
|
internal fun forgetJournal(context: Context, appId: Int, guest: String, engineGuest: String? = null) {
|
||||||
|
val app = File(context.filesDir, "$JOURNAL/$appId")
|
||||||
|
val spelled = engineGuest ?: runCatching {
|
||||||
|
SteamClient.engineLibraries(context).libraries.firstOrNull { SteamClient.sameLibrary(context, it.first, guest) }?.first?.guest
|
||||||
|
}.getOrNull() ?: guest
|
||||||
|
File(app, "$appId/${libraryKey(spelled)}").deleteRecursively()
|
||||||
|
createdMarker(context, appId, guest).delete()
|
||||||
|
File(app, "$appId").delete()
|
||||||
|
app.delete()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Whether this install made the game folder in that library: decided by its first attempt and kept for every resume. */
|
||||||
|
internal fun claimFolder(context: Context, appId: Int, guest: String, folder: File): Boolean {
|
||||||
|
val marker = createdMarker(context, appId, guest)
|
||||||
|
if (marker.isFile) return true
|
||||||
|
if (folder.exists()) return false
|
||||||
|
marker.parentFile?.mkdirs()
|
||||||
|
return runCatching { marker.writeText(folder.name); true }.getOrDefault(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun createdFolder(context: Context, appId: Int, guest: String): Boolean = createdMarker(context, appId, guest).isFile
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes what a cancelled download left; a finished install stays. The game folder goes only when this download made it
|
||||||
|
* ([createdDir]) and no other installed game uses it.
|
||||||
|
*/
|
||||||
|
internal fun discardPartial(context: Context, appId: Int, guest: String, installDir: String?, createdDir: Boolean) {
|
||||||
|
// An unmounted library keeps its journal and ownership record, so a later cancel can still clean it up.
|
||||||
|
val library = runCatching {
|
||||||
|
SteamClient.engineLibraries(context).libraries.firstOrNull { SteamClient.sameLibrary(context, it.first, guest) }?.second
|
||||||
|
}.getOrNull() ?: return
|
||||||
|
val apps = File(library, "steamapps")
|
||||||
|
val acf = File(apps, "appmanifest_$appId.acf")
|
||||||
|
val manifest = acf.takeIf { it.isFile }?.let { f -> runCatching { SteamStorage.parseManifest(f, f.readText()) }.getOrNull() }
|
||||||
|
if (manifest?.installed == true) { forgetJournal(context, appId, guest); return }
|
||||||
|
val claimed = runCatching { createdMarker(context, appId, guest).readText() }.getOrNull()?.ifEmpty { null }
|
||||||
|
val dir = (installDir ?: claimed ?: manifest?.installDir ?: plans[appId]?.second?.installDir)?.takeIf { validDir(it) }
|
||||||
|
val shared = dir != null && apps.listFiles { f -> f.name.startsWith("appmanifest_") && f.name != acf.name }.orEmpty().any { f ->
|
||||||
|
runCatching { SteamStorage.parseManifest(f, f.readText()) }.getOrNull()?.installDir == dir
|
||||||
|
}
|
||||||
|
if (dir != null && createdDir && !shared) StoreInstalls.deleteTree(File(apps, "common/$dir"))
|
||||||
|
StoreInstalls.deleteTree(File(apps, "downloading/$appId"))
|
||||||
|
File(apps, "downloading").listFiles { f -> f.name.startsWith("state_${appId}_") && f.name.endsWith(".patch") }?.forEach { it.delete() }
|
||||||
|
if (manifest != null) acf.delete()
|
||||||
|
forgetJournal(context, appId, guest)
|
||||||
|
StoresState.logLine("Steam: removed the unfinished download of $appId")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal object SteamBackend : StoreBackend {
|
||||||
|
override val store: Store = Store.STEAM
|
||||||
|
|
||||||
|
override fun signIn(context: Context) {
|
||||||
|
StoresState.logLine("Steam: sign in from the Steam client")
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun signOut(context: Context) = SteamEngine.forget()
|
||||||
|
|
||||||
|
override fun syncLibrary(context: Context, force: Boolean) = SteamStore.syncLibrary(context, force)
|
||||||
|
|
||||||
|
override fun loadShelves(context: Context, force: Boolean) {}
|
||||||
|
|
||||||
|
override fun search(context: Context, query: String): List<CatalogItem> =
|
||||||
|
StoresState.library[store].orEmpty().filter { it.title.contains(query, ignoreCase = true) }
|
||||||
|
|
||||||
|
override fun install(context: Context, item: CatalogItem, root: File) = SteamStore.restore(context, item)
|
||||||
|
|
||||||
|
override fun uninstall(context: Context, game: InstalledStoreGame) {}
|
||||||
|
}
|
||||||
@@ -58,17 +58,30 @@ object XboxBackend : StoreBackend {
|
|||||||
if (cached != null && !cached.needsRefresh(force)) { XboxGamertag.ensure(app); return@Thread }
|
if (cached != null && !cached.needsRefresh(force)) { XboxGamertag.ensure(app); return@Thread }
|
||||||
val response = Xodus.run(app, listOf("library", "--json", "--market", market))
|
val response = Xodus.run(app, listOf("library", "--json", "--market", market))
|
||||||
val licenses = XboxCatalog.access(response, account, market, report = { StoresState.logLine("Xbox: $it") })
|
val licenses = XboxCatalog.access(response, account, market, report = { StoresState.logLine("Xbox: $it") })
|
||||||
val products = XboxCatalog.rawProducts(licenses.keys.toList(), market)
|
|
||||||
val cloud = runCatching { XboxCatalog.cloudCatalog(market) }
|
val cloud = runCatching { XboxCatalog.cloudCatalog(market) }
|
||||||
.onFailure { StoresState.logLine("Xbox: cloud lists unavailable (${it.javaClass.simpleName})") }.getOrNull()
|
.onFailure { StoresState.logLine("Xbox: cloud lists unavailable (${it.javaClass.simpleName})") }.getOrNull()
|
||||||
val games = mergeEditions(products.mapNotNull { XboxCatalog.product(it, licenses, cloud) }).sortedBy { it.title.lowercase() }
|
// The PC entitlement list leaves out console purchases and free games; the streaming service lists them.
|
||||||
StoresState.logLine("Xbox: library catalog requested=${licenses.size} returned=${products.size} supported=${games.size} " +
|
val titles = runCatching { XboxCloudSession.titleList(XboxCloudSession.get(app, account), fresh = true) }
|
||||||
"filtered=${products.size - games.size} backend-skipped=${response.optInt("skippedEntitlements")} " +
|
.onFailure { StoresState.logLine("Xbox: cloud titles unavailable (${it.javaClass.simpleName})") }.getOrNull()
|
||||||
|
// Without the Game Pass lists an entitled title cannot be told apart from a purchase, so none are added.
|
||||||
|
val added = if (cloud == null) emptyMap<String, String>() else titles?.entitled.orEmpty().filter { it !in licenses }
|
||||||
|
.associateWith { if (it in cloud.gamePass) "gamepass" else "owned" }
|
||||||
|
StoresState.logLine("Xbox: cloud titles=${titles?.ids?.size ?: -1} entitled=${titles?.entitled?.size ?: -1} " +
|
||||||
|
"added=${added.size} (owned ${added.values.count { it == "owned" }}, gamepass ${added.values.count { it == "gamepass" }})")
|
||||||
|
val entitlements = licenses + added
|
||||||
|
val returned = java.util.concurrent.atomic.AtomicInteger()
|
||||||
|
val supported = XboxCatalog.productBatches(entitlements.keys.toList(), market) { batch ->
|
||||||
|
returned.addAndGet(batch.size)
|
||||||
|
batch.mapNotNull { XboxCatalog.product(it, entitlements, cloud) }
|
||||||
|
}
|
||||||
|
val games = mergeEditions(supported).sortedBy { it.title.lowercase() }
|
||||||
|
StoresState.logLine("Xbox: library catalog requested=${entitlements.size} returned=${returned.get()} supported=${supported.size} " +
|
||||||
|
"shown=${games.size} backend-skipped=${response.optInt("skippedEntitlements")} " +
|
||||||
"pc=${games.count { it.xboxPc }} cloud=${games.count { it.xboxCloud }} cloud-only=${games.count { !it.xboxPc }} " +
|
"pc=${games.count { it.xboxPc }} cloud=${games.count { it.xboxCloud }} cloud-only=${games.count { !it.xboxPc }} " +
|
||||||
"cloud-lists=${cloud?.gamePass?.size ?: -1}/${cloud?.all?.size ?: -1}")
|
"cloud-lists=${cloud?.gamePass?.size ?: -1}/${cloud?.all?.size ?: -1}")
|
||||||
synchronized(this) {
|
synchronized(this) {
|
||||||
if (current != generation || StoreAccounts.signedInAs(app, store) != account) return@Thread
|
if (current != generation || StoreAccounts.signedInAs(app, store) != account) return@Thread
|
||||||
access = licenses
|
access = entitlements
|
||||||
runCatching { XboxLibraryCache.write(app, account, market, games) }
|
runCatching { XboxLibraryCache.write(app, account, market, games) }
|
||||||
.onFailure { StoresState.logLine("Xbox: library cache could not be saved") }
|
.onFailure { StoresState.logLine("Xbox: library cache could not be saved") }
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -84,10 +84,42 @@ internal object XboxCatalog {
|
|||||||
return rawProducts(ids, market).mapNotNull { product(it, access) }
|
return rawProducts(ids, market).mapNotNull { product(it, access) }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun rawProducts(ids: List<String>, market: String = Xodus.market()): List<JSONObject> {
|
fun launchArt(id: String, market: String = Xodus.market()): List<String> =
|
||||||
return ids.map { it.uppercase() }.filter { productId.matches(it) }.distinct().chunked(25).flatMap { batch ->
|
rawProducts(listOf(id.uppercase()), market).firstOrNull()?.let(::launchArtUrls).orEmpty()
|
||||||
|
|
||||||
|
internal fun launchArtUrls(json: JSONObject): List<String> {
|
||||||
|
val images = objects(objects(json.optJSONArray("LocalizedProperties")).firstOrNull()?.optJSONArray("Images"))
|
||||||
|
val order = listOf("SuperHeroArt", "TitledHeroArt", "Screenshot", "Hero")
|
||||||
|
return images.filter { it.optString("ImagePurpose") in order }
|
||||||
|
.sortedBy { order.indexOf(it.optString("ImagePurpose")) }
|
||||||
|
.mapNotNull { image ->
|
||||||
|
val raw = image.optString("Uri")
|
||||||
|
val url = if (raw.startsWith("//")) "https:$raw" else raw
|
||||||
|
runCatching { java.net.URI(url) }.getOrNull()?.takeIf {
|
||||||
|
it.scheme == "https" && it.host in setOf("store-images.s-microsoft.com", "store-images.microsoft.com") && it.userInfo == null && it.port == -1
|
||||||
|
}?.toString()
|
||||||
|
}.distinct().take(12)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun rawProducts(ids: List<String>, market: String = Xodus.market()): List<JSONObject> = productBatches(ids, market) { it }
|
||||||
|
|
||||||
|
// 25 ids per request, up to 4 requests at a time; each batch is mapped as it arrives (a whole library of raw entries is large).
|
||||||
|
fun <T> productBatches(ids: List<String>, market: String = Xodus.market(), map: (List<JSONObject>) -> List<T>): List<T> {
|
||||||
|
val batches = ids.map { it.uppercase() }.filter { productId.matches(it) }.distinct().chunked(25)
|
||||||
|
fun fetchBatch(batch: List<String>): List<T> {
|
||||||
val body = get("https://displaycatalog.mp.microsoft.com/v7.0/products?bigIds=${batch.joinToString(",")}&market=$market&languages=en-us,neutral")
|
val body = get("https://displaycatalog.mp.microsoft.com/v7.0/products?bigIds=${batch.joinToString(",")}&market=$market&languages=en-us,neutral")
|
||||||
objects(body.optJSONArray("Products")).filter { it.optString("ProductId").uppercase() in batch }
|
return map(objects(body.optJSONArray("Products")).filter { it.optString("ProductId").uppercase() in batch })
|
||||||
|
}
|
||||||
|
if (batches.size <= 1) return batches.flatMap(::fetchBatch)
|
||||||
|
val pool = java.util.concurrent.Executors.newFixedThreadPool(4)
|
||||||
|
try {
|
||||||
|
val tasks = batches.map { batch -> pool.submit(java.util.concurrent.Callable { fetchBatch(batch) }) }
|
||||||
|
return tasks.flatMap { task ->
|
||||||
|
try { task.get(60, java.util.concurrent.TimeUnit.SECONDS) }
|
||||||
|
catch (e: java.util.concurrent.ExecutionException) { throw e.cause ?: e }
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
pool.shutdownNow()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -180,16 +212,28 @@ val CatalogItem.xboxPc: Boolean get() = extra["pc"] != "0"
|
|||||||
val CatalogItem.xboxCloud: Boolean get() = extra["cloud"] == "1"
|
val CatalogItem.xboxCloud: Boolean get() = extra["cloud"] == "1"
|
||||||
val CatalogItem.xboxCloudId: String get() = extra["cloudId"]?.takeIf { it.isNotEmpty() } ?: id
|
val CatalogItem.xboxCloudId: String get() = extra["cloudId"]?.takeIf { it.isNotEmpty() } ?: id
|
||||||
|
|
||||||
|
// One card per title: a cloud-only edition folds into the PC card (which then streams, and counts as owned when
|
||||||
|
// the cloud edition is); cloud-only editions with the same title become one card, owned first.
|
||||||
internal fun mergeEditions(games: List<CatalogItem>): List<CatalogItem> {
|
internal fun mergeEditions(games: List<CatalogItem>): List<CatalogItem> {
|
||||||
fun key(title: String) = title.lowercase().replace(Regex("[^a-z0-9]+"), "")
|
fun key(title: String): String {
|
||||||
|
val lower = title.lowercase()
|
||||||
|
val letters = StringBuilder().apply { lower.codePoints().filter { Character.isLetterOrDigit(it) }.forEach { appendCodePoint(it) } }
|
||||||
|
return letters.toString().ifEmpty { lower.trim() }
|
||||||
|
}
|
||||||
|
val pcKeys = games.filter { it.xboxPc }.map { key(it.title) }.toSet()
|
||||||
val cloudOnly = games.filter { !it.xboxPc && it.xboxCloud }.groupBy { key(it.title) }
|
val cloudOnly = games.filter { !it.xboxPc && it.xboxCloud }.groupBy { key(it.title) }
|
||||||
val folded = HashSet<String>()
|
.mapValues { (_, list) -> list.sortedByDescending { it.owned }.first() }
|
||||||
val merged = games.map { game ->
|
return games.mapNotNull { game ->
|
||||||
if (!game.xboxPc || game.xboxCloud) game
|
val console = cloudOnly[key(game.title)]
|
||||||
else cloudOnly[key(game.title)]?.firstOrNull()?.let { console ->
|
when {
|
||||||
folded.add(console.id)
|
!game.xboxPc -> game.takeIf { key(game.title) !in pcKeys && (console == null || console === game) }
|
||||||
game.copy(extra = game.extra + mapOf("cloud" to "1", "cloudId" to console.id))
|
console == null -> game
|
||||||
} ?: game
|
else -> {
|
||||||
|
val cloudId = if (game.xboxCloud) game.extra["cloudId"].orEmpty() else console.id
|
||||||
|
val merged = game.copy(extra = game.extra + mapOf("cloud" to "1", "cloudId" to cloudId))
|
||||||
|
if (console.owned && !game.owned) merged.copy(owned = true, subscription = false, extra = merged.extra + ("access" to "owned"))
|
||||||
|
else merged
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return merged.filter { it.id !in folded }
|
|
||||||
}
|
}
|
||||||
@@ -6,6 +6,7 @@ import android.content.Intent
|
|||||||
import android.graphics.Color
|
import android.graphics.Color
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.view.Gravity
|
import android.view.Gravity
|
||||||
|
import android.view.View
|
||||||
import android.view.KeyEvent
|
import android.view.KeyEvent
|
||||||
import android.view.WindowManager
|
import android.view.WindowManager
|
||||||
import android.webkit.JavascriptInterface
|
import android.webkit.JavascriptInterface
|
||||||
@@ -47,6 +48,8 @@ class XboxCloudPlayerActivity : ComponentActivity() {
|
|||||||
private lateinit var root: FrameLayout
|
private lateinit var root: FrameLayout
|
||||||
private var web: WebView? = null
|
private var web: WebView? = null
|
||||||
private var notice: LinearLayout? = null
|
private var notice: LinearLayout? = null
|
||||||
|
private lateinit var art: XboxLaunchArt
|
||||||
|
private lateinit var artStatus: TextView
|
||||||
private val worker = Executors.newSingleThreadExecutor()
|
private val worker = Executors.newSingleThreadExecutor()
|
||||||
private val signalling = Executors.newCachedThreadPool()
|
private val signalling = Executors.newCachedThreadPool()
|
||||||
@Volatile private var session: XboxCloudSession.Session? = null
|
@Volatile private var session: XboxCloudSession.Session? = null
|
||||||
@@ -68,15 +71,24 @@ class XboxCloudPlayerActivity : ComponentActivity() {
|
|||||||
root = FrameLayout(this).apply { setBackgroundColor(Color.BLACK) }
|
root = FrameLayout(this).apply { setBackgroundColor(Color.BLACK) }
|
||||||
setContentView(root)
|
setContentView(root)
|
||||||
val requested = intent.getStringExtra("product").orEmpty()
|
val requested = intent.getStringExtra("product").orEmpty()
|
||||||
|
art = XboxLaunchArt(this) { diag("cloud player $it") }
|
||||||
|
root.addView(art.view(intent.getStringExtra("title").orEmpty()) { cancelLaunch() }, FrameLayout.LayoutParams(-1, -1))
|
||||||
|
artStatus = TextView(this).apply {
|
||||||
|
setTextColor(Color.WHITE); textSize = 16f; gravity = Gravity.CENTER; setShadowLayer(10f, 0f, 0f, Color.BLACK); visibility = View.GONE
|
||||||
|
}
|
||||||
|
root.addView(artStatus, FrameLayout.LayoutParams(-1, -2, Gravity.BOTTOM).apply { bottomMargin = 120 })
|
||||||
|
art.load(requested)
|
||||||
showNotice("Signing in to Xbox Cloud Gaming…", withButtons = false)
|
showNotice("Signing in to Xbox Cloud Gaming…", withButtons = false)
|
||||||
worker.execute {
|
worker.execute {
|
||||||
val result = runCatching {
|
val result = runCatching {
|
||||||
val account = StoreAccounts.signedInAs(applicationContext, Store.XBOX) ?: error("Sign in to the Xbox store first.")
|
val account = StoreAccounts.signedInAs(applicationContext, Store.XBOX) ?: error("Sign in to the Xbox store first.")
|
||||||
val cached = XboxLibraryCache.read(applicationContext, account, Xodus.market())?.games?.firstOrNull { it.id == requested }
|
val cached = XboxLibraryCache.read(applicationContext, account, Xodus.market())?.games?.firstOrNull { it.id == requested }
|
||||||
val product = cached?.extra?.get("cloudId")?.takeIf { it.isNotEmpty() } ?: requested
|
val product = cached?.extra?.get("cloudId")?.takeIf { it.isNotEmpty() } ?: requested
|
||||||
webUrl = XboxCatalog.cloudUrl(requested, cached?.title ?: intent.getStringExtra("title").orEmpty(), product)
|
val name = cached?.title ?: intent.getStringExtra("title").orEmpty()
|
||||||
|
webUrl = XboxCatalog.cloudUrl(requested, name, product)
|
||||||
val active = XboxCloudSession.get(applicationContext, account)
|
val active = XboxCloudSession.get(applicationContext, account)
|
||||||
val title = XboxCloudSession.titles(active)[product] ?: error("This game can't be streamed with this account here.")
|
val title = XboxCloudSession.titleFor(active, product, name) { diag("cloud player: $it") }
|
||||||
|
?: error("This game can't be streamed with this account here.")
|
||||||
settings = XboxCloudSettings.load(applicationContext)
|
settings = XboxCloudSettings.load(applicationContext)
|
||||||
startedWith = settings
|
startedWith = settings
|
||||||
session = active.forStream(settings.region, settings.osName); titleId = title
|
session = active.forStream(settings.region, settings.osName); titleId = title
|
||||||
@@ -86,6 +98,7 @@ class XboxCloudPlayerActivity : ComponentActivity() {
|
|||||||
if (closed) return@runOnUiThread
|
if (closed) return@runOnUiThread
|
||||||
result.onSuccess { openPlayer() }.onFailure {
|
result.onSuccess { openPlayer() }.onFailure {
|
||||||
diag("cloud player not started: ${it.javaClass.simpleName}: ${it.message?.take(160)}")
|
diag("cloud player not started: ${it.javaClass.simpleName}: ${it.message?.take(160)}")
|
||||||
|
hideArt()
|
||||||
showNotice(it.message ?: "Xbox Cloud Gaming could not start.", withButtons = true)
|
showNotice(it.message ?: "Xbox Cloud Gaming could not start.", withButtons = true)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -130,6 +143,12 @@ class XboxCloudPlayerActivity : ComponentActivity() {
|
|||||||
fun call(id: Int, op: String, arg: String) {
|
fun call(id: Int, op: String, arg: String) {
|
||||||
signalling.execute {
|
signalling.execute {
|
||||||
val reply = runCatching { handle(op, arg) }.getOrElse { XboxCloudSession.Reply(0, it.javaClass.simpleName) }
|
val reply = runCatching { handle(op, arg) }.getOrElse { XboxCloudSession.Reply(0, it.javaClass.simpleName) }
|
||||||
|
if (closed && op == "start") {
|
||||||
|
val active = session; val path = sessionPath
|
||||||
|
if (active != null && path != null) runCatching { XboxCloudSession.request(active, "DELETE", "/$path") }
|
||||||
|
.onSuccess { diag("cloud player cancelled: session closed ${it.status}") }
|
||||||
|
return@execute
|
||||||
|
}
|
||||||
if (reply.status !in 200..299) diag("cloud player $op: ${reply.status} ${reply.body.take(300)}")
|
if (reply.status !in 200..299) diag("cloud player $op: ${reply.status} ${reply.body.take(300)}")
|
||||||
else if (op != "state" && op != "keepalive") diag("cloud player $op: ${reply.status}")
|
else if (op != "state" && op != "keepalive") diag("cloud player $op: ${reply.status}")
|
||||||
runOnUiThread { web?.evaluateJavascript("window.__ddResolve($id, ${reply.status}, ${JSONObject.quote(reply.body)})", null) }
|
runOnUiThread { web?.evaluateJavascript("window.__ddResolve($id, ${reply.status}, ${JSONObject.quote(reply.body)})", null) }
|
||||||
@@ -137,12 +156,24 @@ class XboxCloudPlayerActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@JavascriptInterface
|
@JavascriptInterface
|
||||||
fun status(text: String) { android.util.Log.i("XboxCloudPlayer", "status: ${text.take(120)}") }
|
fun status(text: String) {
|
||||||
|
android.util.Log.i("XboxCloudPlayer", "status: ${text.take(120)}")
|
||||||
|
if (art.shown) runOnUiThread { if (art.shown) { artStatus.text = text; artStatus.visibility = if (text.isEmpty()) View.GONE else View.VISIBLE } }
|
||||||
|
}
|
||||||
|
|
||||||
@JavascriptInterface
|
@JavascriptInterface
|
||||||
fun playing() {
|
fun playing() {
|
||||||
diag("cloud player streaming")
|
diag("cloud player streaming")
|
||||||
runOnUiThread { web?.requestFocus() }
|
runOnUiThread {
|
||||||
|
web?.requestFocus()
|
||||||
|
if (art.shown) { web?.evaluateJavascript(FIRST_FRAME_JS, null); root.postDelayed({ hideArt() }, 6000) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@JavascriptInterface
|
||||||
|
fun firstFrame() {
|
||||||
|
if (art.shown) diag("cloud player first frame")
|
||||||
|
hideArt()
|
||||||
}
|
}
|
||||||
|
|
||||||
@JavascriptInterface
|
@JavascriptInterface
|
||||||
@@ -154,6 +185,7 @@ class XboxCloudPlayerActivity : ComponentActivity() {
|
|||||||
@JavascriptInterface
|
@JavascriptInterface
|
||||||
fun failed(stage: String, detail: String) {
|
fun failed(stage: String, detail: String) {
|
||||||
diag("cloud player failed at ${stage.take(40)}: ${detail.take(300)}")
|
diag("cloud player failed at ${stage.take(40)}: ${detail.take(300)}")
|
||||||
|
hideArt()
|
||||||
runOnUiThread { if (!closed) showNotice("The stream could not start ($stage).", withButtons = true) }
|
runOnUiThread { if (!closed) showNotice("The stream could not start ($stage).", withButtons = true) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -164,6 +196,13 @@ class XboxCloudPlayerActivity : ComponentActivity() {
|
|||||||
return signals.op(op, arg).also { sessionPath = signals.path }
|
return signals.op(op, arg).also { sessionPath = signals.path }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun hideArt() {
|
||||||
|
art.hide()
|
||||||
|
runOnUiThread { artStatus.visibility = View.GONE }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun cancelLaunch() { if (!isFinishing) { diag("cloud player launch cancelled"); finish() } }
|
||||||
|
|
||||||
private fun showNotice(text: String, withButtons: Boolean) {
|
private fun showNotice(text: String, withButtons: Boolean) {
|
||||||
notice?.let { root.removeView(it) }
|
notice?.let { root.removeView(it) }
|
||||||
val box = LinearLayout(this).apply {
|
val box = LinearLayout(this).apply {
|
||||||
@@ -264,6 +303,10 @@ class XboxCloudPlayerActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
return super.dispatchKeyEvent(event)
|
return super.dispatchKeyEvent(event)
|
||||||
}
|
}
|
||||||
|
if (art.shown && (event.keyCode == KeyEvent.KEYCODE_BUTTON_B || event.keyCode == KeyEvent.KEYCODE_BACK)) {
|
||||||
|
if (event.action == KeyEvent.ACTION_UP) cancelLaunch()
|
||||||
|
return true
|
||||||
|
}
|
||||||
if (notice == null && guideKey(event)) return true
|
if (notice == null && guideKey(event)) return true
|
||||||
if (event.keyCode == KeyEvent.KEYCODE_BACK) {
|
if (event.keyCode == KeyEvent.KEYCODE_BACK) {
|
||||||
if (event.action == KeyEvent.ACTION_UP) { if (notice == null) openMenu() else finish() }
|
if (event.action == KeyEvent.ACTION_UP) { if (notice == null) openMenu() else finish() }
|
||||||
@@ -379,6 +422,10 @@ class XboxCloudPlayerActivity : ComponentActivity() {
|
|||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
private const val DOUBLE_PRESS_MS = 350L
|
private const val DOUBLE_PRESS_MS = 350L
|
||||||
|
// Calls DDCloud.firstFrame() once the page's video has decoded a frame (or after 6 s).
|
||||||
|
private const val FIRST_FRAME_JS = "(function(){var t=Date.now();(function poll(){var v=document.querySelector('video');" +
|
||||||
|
"var n=v&&v.getVideoPlaybackQuality?v.getVideoPlaybackQuality().totalVideoFrames:0;" +
|
||||||
|
"if(n>0||(v&&v.currentTime>0)||Date.now()-t>6000){DDCloud.firstFrame();return;}setTimeout(poll,100);})();})()"
|
||||||
|
|
||||||
fun intent(context: Context, productId: String, title: String): Intent = Intent(context, XboxCloudPlayerActivity::class.java)
|
fun intent(context: Context, productId: String, title: String): Intent = Intent(context, XboxCloudPlayerActivity::class.java)
|
||||||
.putExtra("product", productId.uppercase()).putExtra("title", title)
|
.putExtra("product", productId.uppercase()).putExtra("title", title)
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ internal object XboxCloudSession {
|
|||||||
json.optString("userToken").takeIf { !json.isNull("userToken") && it.isNotEmpty() }, System.currentTimeMillis() + seconds * 1000).also { cached = it }
|
json.optString("userToken").takeIf { !json.isNull("userToken") && it.isNotEmpty() }, System.currentTimeMillis() + seconds * 1000).also { cached = it }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun clear() { cached = null; titleIds = null }
|
fun clear() { cached = null; titleList = null; looked = null }
|
||||||
|
|
||||||
fun fromMainProcess(app: Context, account: String, timeoutSeconds: Long = 90): Session? {
|
fun fromMainProcess(app: Context, account: String, timeoutSeconds: Long = 90): Session? {
|
||||||
cached?.takeIf { it.account == account && it.fresh }?.let { return it }
|
cached?.takeIf { it.account == account && it.fresh }?.let { return it }
|
||||||
@@ -61,21 +61,64 @@ internal object XboxCloudSession {
|
|||||||
b.getString("baseUri").orEmpty(), regions, b.getString("userToken"), b.getLong("expiresAt"))
|
b.getString("baseUri").orEmpty(), regions, b.getString("userToken"), b.getLong("expiresAt"))
|
||||||
}
|
}
|
||||||
|
|
||||||
@Volatile private var titleIds: Pair<String, Map<String, String>>? = null
|
class Titles(val ids: Map<String, String>, val entitled: Set<String>)
|
||||||
|
|
||||||
fun titles(session: Session): Map<String, String> {
|
@Volatile private var titleList: Pair<String, Titles>? = null
|
||||||
titleIds?.takeIf { it.first == session.account }?.let { return it.second }
|
|
||||||
|
fun titles(session: Session): Map<String, String> = titleList(session).ids
|
||||||
|
|
||||||
|
// Entitled = details.hasEntitlement or isFreeInStore, as Greenlight's xcloud.ts by unknownskl (MIT).
|
||||||
|
fun titleList(session: Session, fresh: Boolean = false): Titles {
|
||||||
|
if (!fresh) titleList?.takeIf { it.first == session.account }?.let { return it.second }
|
||||||
val reply = request(session, "GET", "/v2/titles")
|
val reply = request(session, "GET", "/v2/titles")
|
||||||
check(reply.status == 200) { "Xbox Cloud Gaming answered ${reply.status}" }
|
check(reply.status == 200) { "Xbox Cloud Gaming answered ${reply.status}" }
|
||||||
val results = JSONObject(reply.body).optJSONArray("results") ?: JSONArray()
|
val results = JSONObject(reply.body).optJSONArray("results") ?: JSONArray()
|
||||||
val map = (0 until results.length()).mapNotNull { index ->
|
val ids = LinkedHashMap<String, String>()
|
||||||
val row = results.optJSONObject(index) ?: return@mapNotNull null
|
val entitled = LinkedHashSet<String>()
|
||||||
val product = row.optJSONObject("details")?.optString("productId")?.uppercase().orEmpty()
|
for (index in 0 until results.length()) {
|
||||||
|
val row = results.optJSONObject(index) ?: continue
|
||||||
|
val details = row.optJSONObject("details")
|
||||||
|
val product = details?.optString("productId")?.uppercase().orEmpty()
|
||||||
val title = row.optString("titleId")
|
val title = row.optString("titleId")
|
||||||
if (product.matches(Regex("[A-Z0-9]{12}")) && title.isNotBlank() && title.length <= 64) product to title else null
|
if (!product.matches(Regex("[A-Z0-9]{12}")) || title.isBlank() || title.length > 64) continue
|
||||||
}.toMap()
|
ids.putIfAbsent(product, title)
|
||||||
titleIds = session.account to map
|
if (details?.optBoolean("hasEntitlement") == true || details?.optBoolean("isFreeInStore") == true) entitled += product
|
||||||
return map
|
}
|
||||||
|
return Titles(ids, entitled).also { titleList = session.account to it }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Volatile private var looked: Pair<String, MutableMap<String, String>>? = null
|
||||||
|
|
||||||
|
// Lookup by product id (POST /v2/titles with alternateIds) as Better xCloud's getTitleInfo (MIT).
|
||||||
|
fun titleFor(session: Session, productId: String, name: String = "", log: (String) -> Unit = {}): String? {
|
||||||
|
val product = productId.uppercase()
|
||||||
|
val list = titles(session)
|
||||||
|
list[product]?.let { return it }
|
||||||
|
val cache = looked?.takeIf { it.first == session.account }?.second ?: HashMap<String, String>().also { looked = session.account to it }
|
||||||
|
cache[product]?.let { return it }
|
||||||
|
val body = JSONObject().put("alternateIds", JSONArray().put(product)).put("alternateIdType", "productId").toString()
|
||||||
|
val reply = runCatching { request(session, "POST", "/v2/titles", body) }.getOrNull()
|
||||||
|
val rows = reply?.takeIf { it.status == 200 }?.let { runCatching { JSONObject(it.body).optJSONArray("results") }.getOrNull() }
|
||||||
|
val row = rows?.optJSONObject(0)
|
||||||
|
val title = row?.optString("titleId").orEmpty()
|
||||||
|
val rowProduct = row?.optJSONObject("details")?.optString("productId")?.uppercase().orEmpty()
|
||||||
|
log("title lookup $product: http ${reply?.status ?: -1}, results ${rows?.length() ?: -1}, title ${title.ifEmpty { "-" }}, product ${rowProduct.ifEmpty { "-" }}")
|
||||||
|
if (title.isNotBlank() && title.length <= 64) { cache[product] = title; return title }
|
||||||
|
val key = nameKey(name)
|
||||||
|
if (key.length >= 4) {
|
||||||
|
val byName = list.values.filter { it.uppercase() == key }.distinct()
|
||||||
|
log("title by name $key: ${byName.joinToString().ifEmpty { "none" }}")
|
||||||
|
if (byName.size == 1) { cache[product] = byName[0]; return byName[0] }
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
private val EDITION_WORDS = Regex("(STANDARD|DELUXE|PREMIUM|ULTIMATE|GOLD|COMPLETE|DEFINITIVE|ENHANCED|ANNIVERSARY|GAMEOFTHEYEAR|GOTY)?EDITION$|GAMEPREVIEW$|FORWINDOWS(10)?$|XBOXSERIESXS$|XBOXONE$|PC$")
|
||||||
|
|
||||||
|
internal fun nameKey(name: String): String {
|
||||||
|
var key = name.uppercase().replace(Regex("[^A-Z0-9]"), "")
|
||||||
|
repeat(3) { key = key.replace(EDITION_WORDS, "") }
|
||||||
|
return key
|
||||||
}
|
}
|
||||||
|
|
||||||
class Reply(val status: Int, val body: String)
|
class Reply(val status: Int, val body: String)
|
||||||
|
|||||||
@@ -0,0 +1,142 @@
|
|||||||
|
package com.droiddeck.launcher.stores.xbox
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import androidx.compose.animation.AnimatedVisibility
|
||||||
|
import androidx.compose.animation.Crossfade
|
||||||
|
import androidx.compose.animation.core.Animatable
|
||||||
|
import androidx.compose.animation.core.LinearEasing
|
||||||
|
import androidx.compose.animation.core.tween
|
||||||
|
import androidx.compose.animation.fadeIn
|
||||||
|
import androidx.compose.animation.fadeOut
|
||||||
|
import androidx.compose.foundation.background
|
||||||
|
import androidx.compose.foundation.gestures.detectTapGestures
|
||||||
|
import androidx.compose.foundation.layout.Arrangement
|
||||||
|
import androidx.compose.foundation.layout.Row
|
||||||
|
import androidx.compose.foundation.layout.size
|
||||||
|
import androidx.compose.foundation.shape.CircleShape
|
||||||
|
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||||
|
import androidx.compose.foundation.layout.Box
|
||||||
|
import androidx.compose.foundation.layout.fillMaxSize
|
||||||
|
import androidx.compose.foundation.layout.padding
|
||||||
|
import androidx.compose.material3.MaterialTheme
|
||||||
|
import androidx.compose.material3.Text
|
||||||
|
import androidx.compose.runtime.Composable
|
||||||
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
|
import androidx.compose.runtime.getValue
|
||||||
|
import androidx.compose.runtime.mutableIntStateOf
|
||||||
|
import androidx.compose.runtime.mutableStateListOf
|
||||||
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.compose.runtime.setValue
|
||||||
|
import androidx.compose.ui.Alignment
|
||||||
|
import androidx.compose.ui.Modifier
|
||||||
|
import androidx.compose.ui.draw.clip
|
||||||
|
import androidx.compose.ui.input.pointer.pointerInput
|
||||||
|
import androidx.compose.ui.res.stringResource
|
||||||
|
import androidx.compose.ui.semantics.Role
|
||||||
|
import androidx.compose.ui.semantics.onClick
|
||||||
|
import androidx.compose.ui.semantics.role
|
||||||
|
import androidx.compose.ui.semantics.semantics
|
||||||
|
import androidx.compose.ui.text.font.FontWeight
|
||||||
|
import androidx.compose.ui.unit.sp
|
||||||
|
import androidx.compose.ui.graphics.Brush
|
||||||
|
import androidx.compose.ui.graphics.Color
|
||||||
|
import androidx.compose.ui.graphics.graphicsLayer
|
||||||
|
import androidx.compose.ui.layout.ContentScale
|
||||||
|
import androidx.compose.ui.platform.ComposeView
|
||||||
|
import androidx.compose.ui.platform.LocalContext
|
||||||
|
import androidx.compose.ui.text.style.TextOverflow
|
||||||
|
import androidx.compose.ui.unit.dp
|
||||||
|
import coil.compose.AsyncImage
|
||||||
|
import coil.request.ImageRequest
|
||||||
|
import com.droiddeck.launcher.R
|
||||||
|
import com.droiddeck.launcher.stores.Store
|
||||||
|
import com.droiddeck.launcher.stores.StoreAccounts
|
||||||
|
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||||
|
import kotlinx.coroutines.delay
|
||||||
|
|
||||||
|
// The game's art as a slow slideshow while a cloud stream connects, until the first video frame.
|
||||||
|
// From Even Better Xcloud (BannerCloud) 7ec2a75.
|
||||||
|
internal class XboxLaunchArt(private val activity: Activity, private val log: (String) -> Unit) {
|
||||||
|
private val urls = mutableStateListOf<String>()
|
||||||
|
private var visible by mutableStateOf(true)
|
||||||
|
@Volatile var shown = true
|
||||||
|
private set
|
||||||
|
|
||||||
|
fun view(title: String, onCancel: () -> Unit): ComposeView = ComposeView(activity).apply {
|
||||||
|
setContent { DroidDeckTheme { LaunchArt(urls, title, visible, onCancel) } }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun load(product: String) {
|
||||||
|
if (product.isEmpty()) return
|
||||||
|
val app = activity.applicationContext
|
||||||
|
Thread({
|
||||||
|
runCatching {
|
||||||
|
val account = StoreAccounts.signedInAs(app, Store.XBOX) ?: return@runCatching
|
||||||
|
val game = XboxLibraryCache.read(app, account, Xodus.market())?.games?.firstOrNull { it.id == product }
|
||||||
|
game?.imageUrl?.let { url -> activity.runOnUiThread { if (urls.isEmpty()) urls.add(url) } }
|
||||||
|
val more = XboxCatalog.launchArt(product)
|
||||||
|
if (more.isNotEmpty()) activity.runOnUiThread { urls.addAll(more.filter { it !in urls }) }
|
||||||
|
}.onFailure { log("launch art: ${it.javaClass.simpleName}") }
|
||||||
|
}, "launch-art").start()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun hide() {
|
||||||
|
shown = false
|
||||||
|
activity.runOnUiThread { visible = false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun LaunchArt(images: List<String>, title: String, visible: Boolean, onCancel: () -> Unit) {
|
||||||
|
AnimatedVisibility(visible, enter = fadeIn(tween(400)), exit = fadeOut(tween(700))) {
|
||||||
|
Box(Modifier.fillMaxSize().background(Color.Black)) {
|
||||||
|
var index by remember { mutableIntStateOf(0) }
|
||||||
|
LaunchedEffect(images.size) {
|
||||||
|
while (true) {
|
||||||
|
delay(SLIDE_MS)
|
||||||
|
if (images.size > 1) index = (index + 1) % images.size
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Crossfade(targetState = images.getOrNull(index % images.size.coerceAtLeast(1)), animationSpec = tween(1400),
|
||||||
|
label = "launch-art") { url ->
|
||||||
|
if (url != null) Slide(url, index)
|
||||||
|
}
|
||||||
|
Box(Modifier.fillMaxSize().background(Brush.verticalGradient(
|
||||||
|
0f to Color(0x66000000), 0.45f to Color(0x22000000), 0.78f to Color(0xB3000000), 1f to Color(0xF2000000))))
|
||||||
|
Text(title, style = MaterialTheme.typography.headlineSmall, color = Color.White, maxLines = 2,
|
||||||
|
overflow = TextOverflow.Ellipsis,
|
||||||
|
modifier = Modifier.align(Alignment.BottomStart).padding(start = 40.dp, end = 220.dp, bottom = 34.dp))
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp),
|
||||||
|
modifier = Modifier.align(Alignment.BottomEnd).padding(end = 40.dp, bottom = 30.dp)
|
||||||
|
.clip(RoundedCornerShape(50)).background(Color(0x99000000))
|
||||||
|
.pointerInput(Unit) { detectTapGestures { onCancel() } }
|
||||||
|
.semantics(mergeDescendants = true) { role = Role.Button; onClick { onCancel(); true } }
|
||||||
|
.padding(start = 8.dp, end = 18.dp, top = 8.dp, bottom = 8.dp)) {
|
||||||
|
Box(Modifier.size(28.dp).clip(CircleShape).background(Color(0xFFE5484D)), contentAlignment = Alignment.Center) {
|
||||||
|
Text("B", color = Color.White, fontWeight = FontWeight.Bold, fontSize = 15.sp)
|
||||||
|
}
|
||||||
|
Text(stringResource(R.string.common_cancel), color = Color.White, fontSize = 16.sp, fontWeight = FontWeight.SemiBold)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
private fun Slide(url: String, index: Int) {
|
||||||
|
val ctx = LocalContext.current
|
||||||
|
val progress = remember(url) { Animatable(0f) }
|
||||||
|
LaunchedEffect(url) { progress.animateTo(1f, tween((SLIDE_MS + 1600).toInt(), easing = LinearEasing)) }
|
||||||
|
val dir = if (index % 2 == 0) 1f else -1f
|
||||||
|
AsyncImage(
|
||||||
|
model = ImageRequest.Builder(ctx).data(url).crossfade(500).build(),
|
||||||
|
contentDescription = null, contentScale = ContentScale.Crop,
|
||||||
|
modifier = Modifier.fillMaxSize().graphicsLayer {
|
||||||
|
val p = progress.value
|
||||||
|
val s = 1.06f + 0.10f * p
|
||||||
|
scaleX = s; scaleY = s
|
||||||
|
translationX = dir * (p - 0.5f) * size.width * 0.04f
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
private const val SLIDE_MS = 5200L
|
||||||
@@ -5,6 +5,7 @@ import com.droiddeck.launcher.ui.focusGlide
|
|||||||
import android.content.Context
|
import android.content.Context
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.graphics.Color
|
import android.graphics.Color
|
||||||
|
import android.media.AudioAttributes
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.os.VibrationEffect
|
import android.os.VibrationEffect
|
||||||
@@ -75,6 +76,7 @@ class XboxNativePlayerActivity : ComponentActivity() {
|
|||||||
@Volatile private var connectedOnce = false
|
@Volatile private var connectedOnce = false
|
||||||
@Volatile private var endedInBackground = false
|
@Volatile private var endedInBackground = false
|
||||||
private var backgroundEnd: Runnable? = null
|
private var backgroundEnd: Runnable? = null
|
||||||
|
private lateinit var art: XboxLaunchArt
|
||||||
private var notice: androidx.compose.ui.platform.ComposeView? = null
|
private var notice: androidx.compose.ui.platform.ComposeView? = null
|
||||||
@Volatile private var regionNames = emptyList<String>()
|
@Volatile private var regionNames = emptyList<String>()
|
||||||
@Volatile private var serverName: String? = null
|
@Volatile private var serverName: String? = null
|
||||||
@@ -103,7 +105,10 @@ class XboxNativePlayerActivity : ComponentActivity() {
|
|||||||
root = FrameLayout(this).apply { setBackgroundColor(Color.BLACK) }
|
root = FrameLayout(this).apply { setBackgroundColor(Color.BLACK) }
|
||||||
surfaceView = SurfaceView(this)
|
surfaceView = SurfaceView(this)
|
||||||
root.addView(surfaceView, FrameLayout.LayoutParams(-1, -1))
|
root.addView(surfaceView, FrameLayout.LayoutParams(-1, -1))
|
||||||
status = TextView(this).apply { setTextColor(Color.WHITE); textSize = 16f; gravity = Gravity.CENTER }
|
art = XboxLaunchArt(this) { log(it) }
|
||||||
|
root.addView(art.view(intent.getStringExtra("title").orEmpty()) { cancelLaunch() }, FrameLayout.LayoutParams(-1, -1))
|
||||||
|
art.load(intent.getStringExtra("product").orEmpty())
|
||||||
|
status = TextView(this).apply { setTextColor(Color.WHITE); textSize = 16f; gravity = Gravity.CENTER; setShadowLayer(10f, 0f, 0f, Color.BLACK) }
|
||||||
root.addView(status, FrameLayout.LayoutParams(-1, -2, Gravity.BOTTOM).apply { bottomMargin = 120 })
|
root.addView(status, FrameLayout.LayoutParams(-1, -2, Gravity.BOTTOM).apply { bottomMargin = 120 })
|
||||||
overlay = TextView(this).apply {
|
overlay = TextView(this).apply {
|
||||||
setTextColor(Color.WHITE); textSize = 12f; typeface = android.graphics.Typeface.MONOSPACE
|
setTextColor(Color.WHITE); textSize = 12f; typeface = android.graphics.Typeface.MONOSPACE
|
||||||
@@ -118,6 +123,7 @@ class XboxNativePlayerActivity : ComponentActivity() {
|
|||||||
|
|
||||||
val egl = EglBase.create().also { eglBase = it }
|
val egl = EglBase.create().also { eglBase = it }
|
||||||
val nativeVideo = XboxNativeVideo(this, egl) { log(it) }.also { video = it }
|
val nativeVideo = XboxNativeVideo(this, egl) { log(it) }.also { video = it }
|
||||||
|
nativeVideo.onFirstFrame = { hideArt() }
|
||||||
surfaceView.holder.addCallback(object : SurfaceHolder.Callback {
|
surfaceView.holder.addCallback(object : SurfaceHolder.Callback {
|
||||||
override fun surfaceCreated(holder: SurfaceHolder) {}
|
override fun surfaceCreated(holder: SurfaceHolder) {}
|
||||||
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
|
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
|
||||||
@@ -137,9 +143,12 @@ class XboxNativePlayerActivity : ComponentActivity() {
|
|||||||
|
|
||||||
private fun log(text: String) = com.droiddeck.launcher.stores.StoresState.logLine("Xbox: native player: ${text.take(240)}")
|
private fun log(text: String) = com.droiddeck.launcher.stores.StoresState.logLine("Xbox: native player: ${text.take(240)}")
|
||||||
private fun show(text: String) = runOnUiThread { status.text = text; status.visibility = if (text.isEmpty()) android.view.View.GONE else android.view.View.VISIBLE }
|
private fun show(text: String) = runOnUiThread { status.text = text; status.visibility = if (text.isEmpty()) android.view.View.GONE else android.view.View.VISIBLE }
|
||||||
|
private fun hideArt() { if (art.shown) { art.hide(); show("") } }
|
||||||
|
private fun cancelLaunch() { if (!isFinishing) { log("launch cancelled"); finish() } }
|
||||||
|
|
||||||
private fun fail(stage: String, detail: String) {
|
private fun fail(stage: String, detail: String) {
|
||||||
log("failed at $stage: $detail")
|
log("failed at $stage: $detail")
|
||||||
|
art.hide()
|
||||||
if (closed) return
|
if (closed) return
|
||||||
if (connectedOnce) showNotice("The connection to the cloud console was lost",
|
if (connectedOnce) showNotice("The connection to the cloud console was lost",
|
||||||
"The stream stopped reaching this device ($detail). Restart the stream to play again: the game starts over, " +
|
"The stream stopped reaching this device ($detail). Restart the stream to play again: the game starts over, " +
|
||||||
@@ -232,12 +241,14 @@ class XboxNativePlayerActivity : ComponentActivity() {
|
|||||||
val active = (shared ?: XboxCloudSession.get(applicationContext, account)).forStream(settings.region, settings.osName)
|
val active = (shared ?: XboxCloudSession.get(applicationContext, account)).forStream(settings.region, settings.osName)
|
||||||
regionNames = active.regionList.map { it.name }
|
regionNames = active.regionList.map { it.name }
|
||||||
serverName = active.regionList.firstOrNull { it.baseUri == active.baseUri }?.name
|
serverName = active.regionList.firstOrNull { it.baseUri == active.baseUri }?.name
|
||||||
val title = XboxCloudSession.titles(active)[product] ?: error("This game can't be streamed with this account here.")
|
val title = XboxCloudSession.titleFor(active, product, cached?.title ?: intent.getStringExtra("title").orEmpty()) { log(it) }
|
||||||
|
?: error("This game can't be streamed with this account here.")
|
||||||
val signals = XboxCloudSignalling(active, title, settings).also { signalling = it }
|
val signals = XboxCloudSignalling(active, title, settings).also { signalling = it }
|
||||||
log("$product -> $title, region ${java.net.URI(active.baseUri).host}, frame gen ${settings.frameGen}")
|
log("$product -> $title, region ${java.net.URI(active.baseUri).host}, frame gen ${settings.frameGen}")
|
||||||
|
|
||||||
show("Starting the game on Xbox Cloud Gaming…")
|
show("Starting the game on Xbox Cloud Gaming…")
|
||||||
expect("start", signals.start())
|
expect("start", signals.start())
|
||||||
|
if (closed) { runCatching { signals.stop() }.onSuccess { log("cancelled: session closed ${it?.status}") }; return }
|
||||||
var connected = false
|
var connected = false
|
||||||
var waited = 0
|
var waited = 0
|
||||||
while (!closed) {
|
while (!closed) {
|
||||||
@@ -270,7 +281,15 @@ class XboxNativePlayerActivity : ComponentActivity() {
|
|||||||
log("latency: instant input ${settings.instantInput}, small buffer ${settings.smallBuffer}, fast decoder ${settings.fastDecoder}, " +
|
log("latency: instant input ${settings.instantInput}, small buffer ${settings.smallBuffer}, fast decoder ${settings.fastDecoder}, " +
|
||||||
"zero-copy ${zeroSurface != null}")
|
"zero-copy ${zeroSurface != null}")
|
||||||
val f = PeerConnectionFactory.builder()
|
val f = PeerConnectionFactory.builder()
|
||||||
.setAudioDeviceModule(JavaAudioDeviceModule.builder(applicationContext).createAudioDeviceModule())
|
// WebRTC defaults to voice-call audio (mono, speaker/earpiece only); game audio follows
|
||||||
|
// the normal output (HDMI, USB, Bluetooth) and keeps the stream's stereo.
|
||||||
|
.setAudioDeviceModule(JavaAudioDeviceModule.builder(applicationContext)
|
||||||
|
.setAudioAttributes(AudioAttributes.Builder()
|
||||||
|
.setUsage(AudioAttributes.USAGE_GAME)
|
||||||
|
.setContentType(AudioAttributes.CONTENT_TYPE_MOVIE)
|
||||||
|
.build())
|
||||||
|
.setUseStereoOutput(true)
|
||||||
|
.createAudioDeviceModule())
|
||||||
.setVideoDecoderFactory(org.webrtc.DroidDeckLowLatencyDecoderFactory(egl.eglBaseContext, settings.fastDecoder, zeroSurface) { zeroCopyFrames++ }
|
.setVideoDecoderFactory(org.webrtc.DroidDeckLowLatencyDecoderFactory(egl.eglBaseContext, settings.fastDecoder, zeroSurface) { zeroCopyFrames++ }
|
||||||
.also { decoders = it })
|
.also { decoders = it })
|
||||||
.setVideoEncoderFactory(DefaultVideoEncoderFactory(egl.eglBaseContext, true, true))
|
.setVideoEncoderFactory(DefaultVideoEncoderFactory(egl.eglBaseContext, true, true))
|
||||||
@@ -365,7 +384,7 @@ class XboxNativePlayerActivity : ComponentActivity() {
|
|||||||
when (state) {
|
when (state) {
|
||||||
PeerConnection.PeerConnectionState.CONNECTED -> {
|
PeerConnection.PeerConnectionState.CONNECTED -> {
|
||||||
connectedOnce = true
|
connectedOnce = true
|
||||||
show("")
|
if (art.shown) root.postDelayed({ hideArt() }, 6000) else show("")
|
||||||
video?.setFpsTarget(settings.fpsTarget)
|
video?.setFpsTarget(settings.fpsTarget)
|
||||||
video?.setFrameGeneration(effectiveFrameGen())
|
video?.setFrameGeneration(effectiveFrameGen())
|
||||||
}
|
}
|
||||||
@@ -427,6 +446,10 @@ class XboxNativePlayerActivity : ComponentActivity() {
|
|||||||
}
|
}
|
||||||
return super.dispatchKeyEvent(event)
|
return super.dispatchKeyEvent(event)
|
||||||
}
|
}
|
||||||
|
if (art.shown && (event.keyCode == KeyEvent.KEYCODE_BUTTON_B || event.keyCode == KeyEvent.KEYCODE_BACK)) {
|
||||||
|
if (event.action == KeyEvent.ACTION_UP) cancelLaunch()
|
||||||
|
return true
|
||||||
|
}
|
||||||
if (isGuide(event)) {
|
if (isGuide(event)) {
|
||||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||||
val pending = pendingNexus
|
val pending = pendingNexus
|
||||||
|
|||||||
@@ -54,6 +54,7 @@ internal class XboxNativeVideo(private val context: Context, eglBase: EglBase, p
|
|||||||
private var nextDueNs = 0L
|
private var nextDueNs = 0L
|
||||||
@Volatile var frames = 0L
|
@Volatile var frames = 0L
|
||||||
private set
|
private set
|
||||||
|
@Volatile var onFirstFrame: (() -> Unit)? = null
|
||||||
|
|
||||||
fun setSurface(target: Surface?, width: Int, height: Int, displayRefreshHz: Float) = synchronized(lock) {
|
fun setSurface(target: Surface?, width: Int, height: Int, displayRefreshHz: Float) = synchronized(lock) {
|
||||||
refreshHz = displayRefreshHz
|
refreshHz = displayRefreshHz
|
||||||
@@ -126,7 +127,10 @@ internal class XboxNativeVideo(private val context: Context, eglBase: EglBase, p
|
|||||||
if (nextDueNs == 0L || now - nextDueNs > interval) nextDueNs = now
|
if (nextDueNs == 0L || now - nextDueNs > interval) nextDueNs = now
|
||||||
if (now + 4_000_000L < nextDueNs) true else { nextDueNs += interval; false }
|
if (now + 4_000_000L < nextDueNs) true else { nextDueNs += interval; false }
|
||||||
}
|
}
|
||||||
if (attached && buffer != null && !skip) { WaylandCompositor.nativeStreamFrame(buffer); frames++ }
|
if (attached && buffer != null && !skip) {
|
||||||
|
WaylandCompositor.nativeStreamFrame(buffer); frames++
|
||||||
|
onFirstFrame?.let { onFirstFrame = null; it() }
|
||||||
|
}
|
||||||
buffer?.close()
|
buffer?.close()
|
||||||
held.addLast(image)
|
held.addLast(image)
|
||||||
while (held.size > 2) held.removeFirst().close()
|
while (held.size > 2) held.removeFirst().close()
|
||||||
|
|||||||
@@ -273,7 +273,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
|||||||
var text by remember { mutableStateOf("") }
|
var text by remember { mutableStateOf("") }
|
||||||
var category by remember { mutableStateOf<WowAddonCatalog.Category?>(null) }
|
var category by remember { mutableStateOf<WowAddonCatalog.Category?>(null) }
|
||||||
var sort by remember { mutableStateOf(WowAddonCatalog.Sort.POPULAR) }
|
var sort by remember { mutableStateOf(WowAddonCatalog.Sort.POPULAR) }
|
||||||
var source by remember { mutableStateOf(AddonSource.WOWI) }
|
var source by remember(curseForge != null) { mutableStateOf(if (curseForge != null) AddonSource.CURSE else AddonSource.WOWI) }
|
||||||
val curse = if (source == AddonSource.CURSE && link != null) curseForge else null
|
val curse = if (source == AddonSource.CURSE && link != null) curseForge else null
|
||||||
LaunchedEffect(link) { link?.refresh() }
|
LaunchedEffect(link) { link?.refresh() }
|
||||||
var notice by remember { mutableStateOf<Int?>(null) }
|
var notice by remember { mutableStateOf<Int?>(null) }
|
||||||
@@ -425,8 +425,8 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
|
|||||||
}
|
}
|
||||||
val sourceChip: @Composable () -> Unit = {
|
val sourceChip: @Composable () -> Unit = {
|
||||||
if (curseForge != null) BrowseDropdown(sourceName) { first, done ->
|
if (curseForge != null) BrowseDropdown(sourceName) { first, done ->
|
||||||
MenuItem(stringResource(R.string.addons_source_wowi), source == AddonSource.WOWI, focusRequester = first) { source = AddonSource.WOWI; done() }
|
MenuItem(stringResource(R.string.addons_source_wowi), curse == null, focusRequester = first) { source = AddonSource.WOWI; done() }
|
||||||
MenuItem(stringResource(R.string.addons_source_curse), source == AddonSource.CURSE) { source = AddonSource.CURSE; done() }
|
MenuItem(stringResource(R.string.addons_source_curse), curse != null) { source = AddonSource.CURSE; done() }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val categoryChip: @Composable () -> Unit = {
|
val categoryChip: @Composable () -> Unit = {
|
||||||
|
|||||||
@@ -117,6 +117,7 @@ import com.droiddeck.launcher.IconPack
|
|||||||
import android.content.pm.ShortcutInfo
|
import android.content.pm.ShortcutInfo
|
||||||
import android.graphics.Bitmap
|
import android.graphics.Bitmap
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
import kotlinx.coroutines.flow.drop
|
import kotlinx.coroutines.flow.drop
|
||||||
import kotlinx.coroutines.withContext
|
import kotlinx.coroutines.withContext
|
||||||
import com.droiddeck.launcher.HomeWidgets
|
import com.droiddeck.launcher.HomeWidgets
|
||||||
@@ -388,21 +389,49 @@ internal fun AndroidAppsPage(s: FrontEndState, a: FrontEndActions, modifier: Mod
|
|||||||
}
|
}
|
||||||
val front = LocalFrontFocus.current
|
val front = LocalFrontFocus.current
|
||||||
val steer = rememberCoroutineScope()
|
val steer = rememberCoroutineScope()
|
||||||
// Down goes to the tile straight below. The grid's own search only sees the tiles laid out so far, so above a short or
|
// The tile a move is heading to, by its id so that a list update cannot shift it, and the number of the latest move.
|
||||||
|
val aim = remember { arrayOfNulls<String>(1) }
|
||||||
|
val moves = remember { intArrayOf(0) }
|
||||||
|
val move = remember { arrayOfNulls<Job>(1) }
|
||||||
|
// Up and Down go to the tile straight above or below. The grid's own search works from where the tiles are drawn at that
|
||||||
|
// moment, so while a scroll is still catching up with fast presses it skips a row or drifts a column, and above a short or
|
||||||
// unseen last row it lands on a tile further left; above a gap in a short last row the row's last tile takes it.
|
// unseen last row it lands on a tile further left; above a gap in a short last row the row's last tile takes it.
|
||||||
|
// Presses aim from the tile a move is already heading to, so none is lost before the focus lands.
|
||||||
Box(Modifier.weight(1f).fillMaxWidth().onPreviewKeyEvent { event ->
|
Box(Modifier.weight(1f).fillMaxWidth().onPreviewKeyEvent { event ->
|
||||||
val k = event.nativeKeyEvent
|
val k = event.nativeKeyEvent
|
||||||
if (k.keyCode != KeyEvent.KEYCODE_DPAD_DOWN || front == null) return@onPreviewKeyEvent false
|
val down = k.keyCode == KeyEvent.KEYCODE_DPAD_DOWN
|
||||||
val from = entries.indexOfFirst { tileId(it) == front.last }
|
if ((!down && k.keyCode != KeyEvent.KEYCODE_DPAD_UP) || front == null) return@onPreviewKeyEvent false
|
||||||
|
val aimed = aim[0]?.let { id -> entries.indexOfFirst { tileId(it) == id } } ?: -1
|
||||||
|
if (aim[0] != null && aimed < 0) {
|
||||||
|
// The tile a move was heading to has left the list: that move is dropped and the press aims from the focus.
|
||||||
|
move[0]?.cancel()
|
||||||
|
aim[0] = null
|
||||||
|
}
|
||||||
|
val from = aimed.takeIf { it >= 0 } ?: entries.indexOfFirst { tileId(it) == front.last }
|
||||||
val columns = (grid.layoutInfo.visibleItemsInfo.maxOfOrNull { it.column } ?: 0) + 1
|
val columns = (grid.layoutInfo.visibleItemsInfo.maxOfOrNull { it.column } ?: 0) + 1
|
||||||
if (from < 0 || from / columns == entries.lastIndex / columns) return@onPreviewKeyEvent false
|
if (from < 0) return@onPreviewKeyEvent false
|
||||||
|
// At the first or last row the press leaves the grid, unless a move has not landed yet: then it waits for it.
|
||||||
|
val edge = if (down) from / columns == entries.lastIndex / columns else from < columns
|
||||||
|
if (edge) return@onPreviewKeyEvent aim[0] != null
|
||||||
if (k.action == KeyEvent.ACTION_DOWN) {
|
if (k.action == KeyEvent.ACTION_DOWN) {
|
||||||
val id = tileId(entries[minOf(from + columns, entries.lastIndex)])
|
val to = if (down) minOf(from + columns, entries.lastIndex) else from - columns
|
||||||
val shown = (front.attached[id] ?: 0) > 0
|
val id = tileId(entries[to])
|
||||||
if (!shown || runCatching { front.items.getValue(id).requestFocus() }.isFailure) steer.launch {
|
aim[0] = id
|
||||||
// The row below is not laid out yet: bring it in, then take it.
|
val mine = ++moves[0]
|
||||||
if (!shown) grid.scrollBy((grid.layoutInfo.visibleItemsInfo.firstOrNull { it.index == from + leadItems }?.size?.height ?: 0).toFloat())
|
// A newer move replaces the one still on its way, so an older target cannot take focus after it lands.
|
||||||
focusSoon { front.items.getValue(id) }
|
move[0]?.cancel()
|
||||||
|
move[0] = steer.launch {
|
||||||
|
try {
|
||||||
|
// Show the row before it takes focus. The grid composes rows ahead of the view without placing them, and a
|
||||||
|
// tile focused there neither scrolls in nor has a place for the next search to start from.
|
||||||
|
grid.reveal(to + leadItems)
|
||||||
|
if (moves[0] != mine) return@launch
|
||||||
|
focusSoon { front.items.getValue(id) }
|
||||||
|
} finally {
|
||||||
|
// Also when a touch scroll cancels the reveal, so the edge rows do not keep waiting for a move that ended.
|
||||||
|
// Only the latest move clears it: a cancelled one finishing late must not clear a newer move's target.
|
||||||
|
if (moves[0] == mine) aim[0] = null
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
true
|
true
|
||||||
@@ -558,6 +587,26 @@ private fun HeaderChoiceButton(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Scrolls the least that shows item [index] whole inside the padding, a row at a time while it is still outside the laid out items. */
|
||||||
|
private suspend fun LazyGridState.reveal(index: Int) {
|
||||||
|
repeat(4) {
|
||||||
|
val info = layoutInfo
|
||||||
|
val shown = info.visibleItemsInfo
|
||||||
|
val item = shown.firstOrNull { it.index == index }
|
||||||
|
val by = when {
|
||||||
|
item != null -> {
|
||||||
|
val bottom = item.offset.y + item.size.height - (info.viewportEndOffset - info.afterContentPadding)
|
||||||
|
if (item.offset.y < 0) item.offset.y else maxOf(bottom, 0)
|
||||||
|
}
|
||||||
|
index > (shown.lastOrNull() ?: return).index -> shown.last().size.height
|
||||||
|
index < shown.first().index -> -shown.first().size.height
|
||||||
|
else -> return
|
||||||
|
}
|
||||||
|
if (by == 0) return
|
||||||
|
scrollBy(by.toFloat())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun AlphabetScroller(entries: List<AppEntry>, grid: LazyGridState, leadItems: Int, modifier: Modifier) {
|
private fun AlphabetScroller(entries: List<AppEntry>, grid: LazyGridState, leadItems: Int, modifier: Modifier) {
|
||||||
val colors = MaterialTheme.colorScheme
|
val colors = MaterialTheme.colorScheme
|
||||||
|
|||||||
@@ -526,11 +526,11 @@ fun ComponentsPage(
|
|||||||
val availableTitle: @Composable (String) -> String = { l ->
|
val availableTitle: @Composable (String) -> String = { l ->
|
||||||
when (l) {
|
when (l) {
|
||||||
PROTON_TAB -> stringResource(R.string.comp_available_count, protons.rows.count(ProtonRow::available))
|
PROTON_TAB -> stringResource(R.string.comp_available_count, protons.rows.count(ProtonRow::available))
|
||||||
else -> stringResource(R.string.comp_nightlies_count, availableRows(l, catalog, snapshot).size)
|
else -> stringResource(R.string.comp_nightlies_count, availableRows(l, catalog, snapshot, view?.proton?.dir?.name).size)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
val followed = view?.proton?.let(ComponentUpdates::follows) == true
|
val followed: (String) -> Boolean = { l -> view?.proton?.let { ComponentUpdates.autoFollows(it, l) } == true }
|
||||||
val moded: (String) -> Boolean = { followed && it in compModes && it !in compAutoHeld && !ComponentsManager.runtimeManaged(it, gpu.systemPowerVr) }
|
val moded: (String) -> Boolean = { followed(it) && it in compModes && it !in compAutoHeld && !ComponentsManager.runtimeManaged(it, gpu.systemPowerVr) }
|
||||||
val automatic: (String) -> Boolean = { moded(it) && compModes[it] == ComponentUpdates.AUTO }
|
val automatic: (String) -> Boolean = { moded(it) && compModes[it] == ComponentUpdates.AUTO }
|
||||||
val installedRows: @Composable ColumnScope.(String, Boolean) -> Unit = { l, right ->
|
val installedRows: @Composable ColumnScope.(String, Boolean) -> Unit = { l, right ->
|
||||||
when (l) {
|
when (l) {
|
||||||
@@ -614,7 +614,7 @@ fun ComponentsPage(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
else -> {
|
else -> {
|
||||||
val available = availableRows(l, catalog, snapshot)
|
val available = availableRows(l, catalog, snapshot, view?.proton?.dir?.name)
|
||||||
if (available.isEmpty()) EmptyLine(if (catalogAt == 0L) stringResource(R.string.comp_refresh_to_list) else stringResource(R.string.comp_nothing_new))
|
if (available.isEmpty()) EmptyLine(if (catalogAt == 0L) stringResource(R.string.comp_refresh_to_list) else stringResource(R.string.comp_nothing_new))
|
||||||
for ((stable, nightly) in available) {
|
for ((stable, nightly) in available) {
|
||||||
val d = if (nightly != null && nightlyPicked[stable.file] == true) nightly else stable
|
val d = if (nightly != null && nightlyPicked[stable.file] == true) nightly else stable
|
||||||
@@ -974,18 +974,18 @@ private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapsho
|
|||||||
o.label.substringAfterLast(" · ", "").ifEmpty { o.label }.let { if (isCurrent) stringResource(R.string.comp_this_build, it) else stringResource(R.string.comp_earlier_build, it) },
|
o.label.substringAfterLast(" · ", "").ifEmpty { o.label }.let { if (isCurrent) stringResource(R.string.comp_this_build, it) else stringResource(R.string.comp_earlier_build, it) },
|
||||||
"ORIGINAL", activeIsOriginal && isCurrent, !isCurrent, null, o.protonVersion,
|
"ORIGINAL", activeIsOriginal && isCurrent, !isCurrent, null, o.protonVersion,
|
||||||
)
|
)
|
||||||
} + (snapshot?.packages ?: emptyList()).filter { it.comp == l }.map { s ->
|
} + ComponentsManager.forTool(l, view.proton.dir.name, (snapshot?.packages ?: emptyList()).filter { it.comp == l }, st.activeFile) { it.file }.map { s ->
|
||||||
InstalledItem(s.version, stringResource(R.string.common_size_mb, s.size / 1048576.0), "STORED", !runtimeManaged && s.file == st.activeFile, true, s.file, null)
|
InstalledItem(s.version, stringResource(R.string.common_size_mb, s.size / 1048576.0), "STORED", !runtimeManaged && s.file == st.activeFile, true, s.file, null)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun availableFor(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?): List<CatalogItem> {
|
private fun availableFor(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?, toolDir: String?): List<CatalogItem> {
|
||||||
val stored = (snapshot?.packages ?: emptyList()).map { it.file }.toSet()
|
val stored = (snapshot?.packages ?: emptyList()).map { it.file }.toSet()
|
||||||
return catalog.filter { it.comp == l && ComponentsManager.safeName(it.file) !in stored }
|
return ComponentsManager.forTool(l, toolDir, catalog.filter { it.comp == l && ComponentsManager.safeName(it.file) !in stored }) { it.file }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun availableRows(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?): List<Pair<CatalogItem, CatalogItem?>> {
|
private fun availableRows(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?, toolDir: String?): List<Pair<CatalogItem, CatalogItem?>> {
|
||||||
val available = availableFor(l, catalog, snapshot)
|
val available = availableFor(l, catalog, snapshot, toolDir)
|
||||||
val pairs = ComponentsManager.nightlyPairs(available)
|
val pairs = ComponentsManager.nightlyPairs(available)
|
||||||
val paired = pairs.values.toSet()
|
val paired = pairs.values.toSet()
|
||||||
return available.filter { it !in paired }.map { it to pairs[it] }
|
return available.filter { it !in paired }.map { it to pairs[it] }
|
||||||
@@ -1201,7 +1201,7 @@ private fun GameComponentOverrides(
|
|||||||
}
|
}
|
||||||
GamePackageRow(
|
GamePackageRow(
|
||||||
comp = "fex",
|
comp = "fex",
|
||||||
packages = packages,
|
packages = ComponentsManager.forTool("fex", protonChoice?.dir ?: generalProton?.dir?.name, packages, componentChoices["fex"]) { it.file },
|
||||||
selectedFile = componentChoices["fex"],
|
selectedFile = componentChoices["fex"],
|
||||||
open = componentMenu == "fex",
|
open = componentMenu == "fex",
|
||||||
busy = busy,
|
busy = busy,
|
||||||
|
|||||||
@@ -60,7 +60,8 @@ import androidx.compose.ui.unit.Dp
|
|||||||
import androidx.compose.ui.unit.dp
|
import androidx.compose.ui.unit.dp
|
||||||
import androidx.compose.ui.unit.sp
|
import androidx.compose.ui.unit.sp
|
||||||
import com.droiddeck.launcher.R
|
import com.droiddeck.launcher.R
|
||||||
import com.droiddeck.launcher.session.GameStorage
|
import com.droiddeck.launcher.files.StorageRoot
|
||||||
|
import com.droiddeck.launcher.files.StorageRoots
|
||||||
import com.droiddeck.launcher.stores.formatBytes
|
import com.droiddeck.launcher.stores.formatBytes
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
|
||||||
@@ -74,10 +75,16 @@ internal class PickVolume(val root: File, val label: String, val removable: Bool
|
|||||||
}
|
}
|
||||||
|
|
||||||
internal fun pickVolumes(context: Context): List<PickVolume> =
|
internal fun pickVolumes(context: Context): List<PickVolume> =
|
||||||
listOf(PickVolume(Environment.getExternalStorageDirectory(), context.getString(R.string.games_internal), removable = false)) +
|
pickVolumes(Environment.getExternalStorageDirectory(), context.getString(R.string.games_internal), StorageRoots.list(context))
|
||||||
GameStorage.options(context).mapNotNull { o ->
|
|
||||||
File(o.path.substringBefore("/Android/")).takeIf { it.isDirectory }?.let { PickVolume(it, o.name, removable = true) }
|
internal fun pickVolumes(internal: File, internalLabel: String, roots: List<StorageRoot>): List<PickVolume> {
|
||||||
}.distinctBy { it.root.absolutePath }
|
val internalPath = internal.absolutePath.trimEnd('/')
|
||||||
|
fun overlapsInternal(path: String) = path == internalPath || path.startsWith("$internalPath/") || internalPath.startsWith("$path/")
|
||||||
|
return listOf(PickVolume(internal, internalLabel, removable = false)) +
|
||||||
|
roots.filter { it.readable && !overlapsInternal(it.dir.absolutePath.trimEnd('/')) }
|
||||||
|
.map { PickVolume(it.dir, it.label, removable = true) }
|
||||||
|
.distinctBy { it.root.absolutePath }
|
||||||
|
}
|
||||||
|
|
||||||
internal class PickFolder(val dir: File, val readable: Boolean)
|
internal class PickFolder(val dir: File, val readable: Boolean)
|
||||||
|
|
||||||
|
|||||||
@@ -58,6 +58,7 @@ import androidx.compose.runtime.mutableStateOf
|
|||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.snapshotFlow
|
import androidx.compose.runtime.snapshotFlow
|
||||||
import androidx.compose.runtime.withFrameNanos
|
import androidx.compose.runtime.withFrameNanos
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
import androidx.compose.runtime.saveable.rememberSaveable
|
import androidx.compose.runtime.saveable.rememberSaveable
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
@@ -102,6 +103,7 @@ class FrontEndState(
|
|||||||
val desktopPresent: Boolean = desktopInstalled,
|
val desktopPresent: Boolean = desktopInstalled,
|
||||||
val offlineAccount: String?,
|
val offlineAccount: String?,
|
||||||
val offline: Boolean,
|
val offline: Boolean,
|
||||||
|
val offlineAuto: Boolean = true,
|
||||||
val frameGenLabel: String,
|
val frameGenLabel: String,
|
||||||
val romsDir: String?,
|
val romsDir: String?,
|
||||||
val logsEnabled: Boolean,
|
val logsEnabled: Boolean,
|
||||||
@@ -272,6 +274,7 @@ class FrontEndActions(
|
|||||||
val onClearLogs: () -> Unit = {},
|
val onClearLogs: () -> Unit = {},
|
||||||
val onResetSettings: () -> Unit = {},
|
val onResetSettings: () -> Unit = {},
|
||||||
val onOffline: () -> Unit,
|
val onOffline: () -> Unit,
|
||||||
|
val onOfflineAuto: () -> Unit = {},
|
||||||
val onPageBack: () -> Unit = {},
|
val onPageBack: () -> Unit = {},
|
||||||
val onTheme: (String) -> Unit = {},
|
val onTheme: (String) -> Unit = {},
|
||||||
val onLanguage: (String) -> Unit = {},
|
val onLanguage: (String) -> Unit = {},
|
||||||
@@ -764,12 +767,31 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
|||||||
focusManager.clearFocus(force = true)
|
focusManager.clearFocus(force = true)
|
||||||
onRailSelect(key)
|
onRailSelect(key)
|
||||||
}, a)
|
}, a)
|
||||||
|
val stepScope = androidx.compose.runtime.rememberCoroutineScope()
|
||||||
|
val pageKeyNow = androidx.compose.runtime.rememberUpdatedState(s.pageKey)
|
||||||
|
var railHold by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
|
||||||
val tabStep = androidx.compose.runtime.rememberUpdatedState { step: Int ->
|
val tabStep = androidx.compose.runtime.rememberUpdatedState { step: Int ->
|
||||||
if (!processSettingsPageVisible) {
|
if (!processSettingsPageVisible) {
|
||||||
val keys = navigationKeys(s)
|
val keys = navigationKeys(s)
|
||||||
keys.getOrNull(keys.indexOf(railSelectionNow.value) + step)?.let { key ->
|
keys.getOrNull(keys.indexOf(railSelectionNow.value) + step)?.let { key ->
|
||||||
PageSwipe.direction = step
|
PageSwipe.direction = step
|
||||||
onRailSelect(key)
|
if (s.dualScreen) { onRailSelect(key); return@let }
|
||||||
|
showRailPage(key, false)
|
||||||
|
if (inputModeManager.inputMode != InputMode.Keyboard) inputModeManager.requestInputMode(InputMode.Keyboard)
|
||||||
|
val since = MainTabSteps.otherKeys
|
||||||
|
val owner = selected
|
||||||
|
val ownPage = if (key == "components") "components" else null
|
||||||
|
railHold?.cancel()
|
||||||
|
// Pages focus their own first control as they appear; the ring stays on the rail until another key moves it.
|
||||||
|
railHold = stepScope.launch {
|
||||||
|
var pageShown = false
|
||||||
|
repeat(RAIL_HOLD_FRAMES) {
|
||||||
|
withFrameNanos { }
|
||||||
|
if (MainTabSteps.otherKeys != since || selected != owner) return@launch
|
||||||
|
if (pageKeyNow.value == ownPage) pageShown = true else if (pageShown) return@launch
|
||||||
|
if (frontFocus.focusedRail != key) runCatching { frontFocus.railFor(key).requestFocus() }
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -820,6 +842,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
|||||||
com.droiddeck.launcher.stores.StoresState.pendingInstall?.let { item -> StoreTheme(item.store) { InstallWhere(item) } }
|
com.droiddeck.launcher.stores.StoresState.pendingInstall?.let { item -> StoreTheme(item.store) { InstallWhere(item) } }
|
||||||
com.droiddeck.launcher.stores.StoresState.itchPicking?.let { item -> StoreTheme(item.store) { ItchBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.itchPicking = null } } }
|
com.droiddeck.launcher.stores.StoresState.itchPicking?.let { item -> StoreTheme(item.store) { ItchBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.itchPicking = null } } }
|
||||||
com.droiddeck.launcher.stores.StoresState.gameJoltPicking?.let { item -> StoreTheme(item.store) { GameJoltBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.gameJoltPicking = null } } }
|
com.droiddeck.launcher.stores.StoresState.gameJoltPicking?.let { item -> StoreTheme(item.store) { GameJoltBuildPicker(item) { com.droiddeck.launcher.stores.StoresState.gameJoltPicking = null } } }
|
||||||
|
com.droiddeck.launcher.stores.steam.SteamStore.picking?.let { item -> StoreTheme(item.store) { SteamInstallWhereDialog(item) { com.droiddeck.launcher.stores.steam.SteamStore.picking = null } } }
|
||||||
StepsLayer(screenAt)
|
StepsLayer(screenAt)
|
||||||
UiZooSheet()
|
UiZooSheet()
|
||||||
SessionDrawerPreview(s.secondScreenDisplays)
|
SessionDrawerPreview(s.secondScreenDisplays)
|
||||||
@@ -900,4 +923,7 @@ internal object ChildProcessSetup {
|
|||||||
|
|
||||||
internal object MainTabSteps {
|
internal object MainTabSteps {
|
||||||
@Volatile var handler: ((Int) -> Unit)? = null
|
@Volatile var handler: ((Int) -> Unit)? = null
|
||||||
|
@Volatile var otherKeys = 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private const val RAIL_HOLD_FRAMES = 60
|
||||||
@@ -1098,8 +1098,6 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
|
|||||||
|
|
||||||
internal const val GAME_SETTINGS_MENU = "game-settings"
|
internal const val GAME_SETTINGS_MENU = "game-settings"
|
||||||
|
|
||||||
private const val EPIC_RESOLVE_URL = "https://www.epicgames.com/id/login?redirectUrl=https%3A%2F%2Fwww.epicgames.com%2Faccount%2Fpersonal"
|
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.droiddeck.launcher.stores.Store) {
|
private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.droiddeck.launcher.stores.Store) {
|
||||||
val appContext = androidx.compose.ui.platform.LocalContext.current.applicationContext
|
val appContext = androidx.compose.ui.platform.LocalContext.current.applicationContext
|
||||||
@@ -1149,7 +1147,7 @@ private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.dro
|
|||||||
MenuItem(stringResource(R.string.epic_resolve), checked = false) {
|
MenuItem(stringResource(R.string.epic_resolve), checked = false) {
|
||||||
host.open = null
|
host.open = null
|
||||||
runCatching {
|
runCatching {
|
||||||
appContext.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(EPIC_RESOLVE_URL)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK))
|
appContext.startActivity(android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(com.droiddeck.launcher.stores.epic.EpicLogin.ACCOUNT_SIGN_IN_URL)).addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -56,6 +56,7 @@ import androidx.compose.runtime.DisposableEffect
|
|||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.SideEffect
|
import androidx.compose.runtime.SideEffect
|
||||||
import androidx.compose.runtime.key
|
import androidx.compose.runtime.key
|
||||||
|
import androidx.compose.runtime.mutableStateMapOf
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
import androidx.compose.runtime.produceState
|
import androidx.compose.runtime.produceState
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
@@ -139,6 +140,7 @@ import androidx.compose.foundation.layout.offset
|
|||||||
internal class GameRef(val appId: Int?, val store: Store?, val storeId: String?) {
|
internal class GameRef(val appId: Int?, val store: Store?, val storeId: String?) {
|
||||||
fun game(games: List<Library.SteamGame>): Library.SteamGame? = when {
|
fun game(games: List<Library.SteamGame>): Library.SteamGame? = when {
|
||||||
appId != null -> games.firstOrNull { it.appId == appId }
|
appId != null -> games.firstOrNull { it.appId == appId }
|
||||||
|
store == Store.STEAM && storeId != null -> games.firstOrNull { Library.fromSteamClient(it) && it.appId.toString() == storeId }
|
||||||
store != null && storeId != null -> games.firstOrNull { it.source == store.id && it.storeId == storeId }
|
store != null && storeId != null -> games.firstOrNull { it.source == store.id && it.storeId == storeId }
|
||||||
else -> null
|
else -> null
|
||||||
}
|
}
|
||||||
@@ -182,7 +184,7 @@ internal fun GameDetail(
|
|||||||
if (nothing) return
|
if (nothing) return
|
||||||
val source = game?.source ?: store?.id ?: Library.SOURCE_STEAM
|
val source = game?.source ?: store?.id ?: Library.SOURCE_STEAM
|
||||||
val title = game?.name ?: item?.title ?: installed?.sidecar?.title ?: id.orEmpty()
|
val title = game?.name ?: item?.title ?: installed?.sidecar?.title ?: id.orEmpty()
|
||||||
val favoriteKey = if (store != null && id != null) "${store.id}:$id" else game?.let { GameRef.key(it) } ?: key
|
val favoriteKey = if (store == Store.STEAM && id != null) "app:$id" else if (store != null && id != null) "${store.id}:$id" else game?.let { GameRef.key(it) } ?: key
|
||||||
val scores = if (source != Library.ADDED) rememberGameScores(title.takeIf { it.isNotBlank() && it != id }) else null
|
val scores = if (source != Library.ADDED) rememberGameScores(title.takeIf { it.isNotBlank() && it != id }) else null
|
||||||
val achievements = remember(store, id, item?.accessible, installed) {
|
val achievements = remember(store, id, item?.accessible, installed) {
|
||||||
when {
|
when {
|
||||||
@@ -1068,8 +1070,36 @@ private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, ses
|
|||||||
runCatching { CurseForgeApp.byFolder(link.installed(context, target, scanKey)) }.getOrDefault(emptyMap())
|
runCatching { CurseForgeApp.byFolder(link.installed(context, target, scanKey)) }.getOrDefault(emptyMap())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
val progress = remember(target.addOns) { mutableStateMapOf<String, Int>() }
|
||||||
|
val curseOf = { item: WowAddons.Installed -> link?.let { l -> managed[item.name.lowercase()]?.let { it to l } } }
|
||||||
|
val outdated = names.filter { item -> curseOf(item)?.first?.update ?: (updates[item.name] != null) }
|
||||||
|
val scope = rememberCoroutineScope()
|
||||||
if (targets.size > 1) SectionLabel(target.flavor)
|
if (targets.size > 1) SectionLabel(target.flavor)
|
||||||
MenuItem(stringResource(R.string.addons_download), checked = false) { browsing = target }
|
MenuItem(stringResource(R.string.addons_download), checked = false) { browsing = target }
|
||||||
|
if (outdated.size > 1 && !SessionState.running) MenuItem(
|
||||||
|
stringResource(R.string.store_update_all, outdated.size), checked = false, enabled = progress.isEmpty(),
|
||||||
|
) {
|
||||||
|
val plan = outdated.groupBy { item -> curseOf(item)?.first?.id?.let { "curse:$it" } ?: "folder:${item.name}" }.values.map { group ->
|
||||||
|
Triple(group.map { it.name }, updates[group.first().name], curseOf(group.first()))
|
||||||
|
}
|
||||||
|
plan.forEach { (folders) -> folders.forEach { progress[it] = 0 } }
|
||||||
|
val owned = plan.flatMap { it.first }.toMutableSet()
|
||||||
|
scope.launch {
|
||||||
|
try {
|
||||||
|
plan.forEach { (folders, wowi, curse) ->
|
||||||
|
val name = folders.first()
|
||||||
|
val (message, ok) = updateAddon(context, name, wowi.takeIf { curse == null }, target, curse) { pct ->
|
||||||
|
scope.launch { folders.forEach { progress[it] = pct } }
|
||||||
|
}
|
||||||
|
folders.forEach { progress.remove(it) }
|
||||||
|
owned.removeAll(folders.toSet())
|
||||||
|
if (!ok && message != null) android.widget.Toast.makeText(context, message, android.widget.Toast.LENGTH_LONG).show()
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
owned.forEach { progress.remove(it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
MenuItem(
|
MenuItem(
|
||||||
stringResource(R.string.games_import_addons), checked = false,
|
stringResource(R.string.games_import_addons), checked = false,
|
||||||
detail = pluralStringResource(R.plurals.games_addons_count, names.size, names.size),
|
detail = pluralStringResource(R.plurals.games_addons_count, names.size, names.size),
|
||||||
@@ -1078,7 +1108,7 @@ private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, ses
|
|||||||
target.addOns.mkdirs()
|
target.addOns.mkdirs()
|
||||||
a.onBrowseFiles(target.addOns)
|
a.onBrowseFiles(target.addOns)
|
||||||
}
|
}
|
||||||
names.forEach { item -> key(target.addOns, item.name) { AddonRow(item, updates[item.name], target, a, link?.let { l -> managed[item.name.lowercase()]?.let { it to l } }) } }
|
names.forEach { item -> key(target.addOns, item.name) { AddonRow(item, updates[item.name], target, a, progress, curseOf(item)) } }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1132,12 +1162,12 @@ private fun CurseForgeEntry(a: FrontEndActions) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions, curse: Pair<CurseForgeApp.Project, CurseLink>? = null) {
|
internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions, progresses: MutableMap<String, Int>, curse: Pair<CurseForgeApp.Project, CurseLink>? = null) {
|
||||||
val name = item.name
|
val name = item.name
|
||||||
val update = wowiUpdate.takeIf { curse == null }
|
val update = wowiUpdate.takeIf { curse == null }
|
||||||
val outdated = update != null || curse?.first?.update == true
|
val outdated = update != null || curse?.first?.update == true
|
||||||
var asking by remember(target.addOns, name) { mutableStateOf(false) }
|
var asking by remember(target.addOns, name) { mutableStateOf(false) }
|
||||||
var progress by remember(target.addOns, name) { mutableStateOf<Int?>(null) }
|
val progress = progresses[name]
|
||||||
val context = LocalContext.current
|
val context = LocalContext.current
|
||||||
val scope = rememberCoroutineScope()
|
val scope = rememberCoroutineScope()
|
||||||
val delete = stringResource(R.string.common_delete)
|
val delete = stringResource(R.string.common_delete)
|
||||||
@@ -1152,31 +1182,39 @@ internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Add
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
if (outdated && !SessionState.running) IconAction(Icons.Outlined.Download, stringResource(R.string.common_update), "addon:update:${target.flavor}:$name", enabled = progress == null) {
|
if (outdated && !SessionState.running) IconAction(Icons.Outlined.Download, stringResource(R.string.common_update), "addon:update:${target.flavor}:$name", enabled = progress == null) {
|
||||||
progress = 0
|
progresses[name] = 0
|
||||||
scope.launch {
|
scope.launch {
|
||||||
val message = withContext(Dispatchers.IO) {
|
try {
|
||||||
if (curse != null) {
|
val message = updateAddon(context, name, update, target, curse) { pct -> scope.launch { progresses[name] = pct } }.first
|
||||||
val (project, link) = curse
|
if (message != null) android.widget.Toast.makeText(context, message, android.widget.Toast.LENGTH_LONG).show()
|
||||||
val done = runCatching { link.change(context, target) { CurseForgeApp.update(context, it.inspector, it.guid, project.id) } }.getOrDefault(false)
|
} finally {
|
||||||
WowAddons.changed()
|
progresses.remove(name)
|
||||||
if (done) context.getString(R.string.user_apps_updated, name) else context.getString(R.string.stores_dl_failed_reason, name)
|
|
||||||
} else update?.let { installAddon(context, it, target) { pct -> scope.launch { progress = pct } }.first }
|
|
||||||
}
|
}
|
||||||
progress = null
|
|
||||||
if (message != null) android.widget.Toast.makeText(context, message, android.widget.Toast.LENGTH_LONG).show()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!SessionState.running) IconAction(Icons.Outlined.Delete, if (curse != null) stringResource(R.string.common_uninstall) else delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true }
|
if (!SessionState.running) IconAction(Icons.Outlined.Delete, if (curse != null) stringResource(R.string.common_uninstall) else delete, "addon:delete:${target.flavor}:$name", danger = true, enabled = progress == null) { asking = true }
|
||||||
}
|
}
|
||||||
if (asking) ConfirmDialog(
|
if (asking) ConfirmDialog(
|
||||||
title = if (curse != null) stringResource(R.string.stores_uninstall_title, name) else stringResource(R.string.games_delete_addon_title, name),
|
title = if (curse != null) stringResource(R.string.stores_uninstall_title, name) else stringResource(R.string.games_delete_addon_title, name),
|
||||||
text = stringResource(R.string.games_delete_addon_body),
|
text = stringResource(R.string.games_delete_addon_body),
|
||||||
confirm = if (curse != null) stringResource(R.string.common_uninstall) else delete,
|
confirm = if (curse != null) stringResource(R.string.common_uninstall) else delete,
|
||||||
onConfirm = { a.onAddonDelete(target, name) },
|
onConfirm = { asking = false; if (progresses[name] == null) a.onAddonDelete(target, name) },
|
||||||
onDismiss = { asking = false },
|
onDismiss = { asking = false },
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private suspend fun updateAddon(
|
||||||
|
context: android.content.Context, name: String, update: WowAddonCatalog.Addon?, target: WowAddons.Target,
|
||||||
|
curse: Pair<CurseForgeApp.Project, CurseLink>?, onProgress: (Int) -> Unit,
|
||||||
|
): Pair<String?, Boolean> = withContext(Dispatchers.IO) {
|
||||||
|
if (curse != null) {
|
||||||
|
val (project, link) = curse
|
||||||
|
val done = runCatching { link.change(context, target) { CurseForgeApp.update(context, it.inspector, it.guid, project.id) } }.getOrDefault(false)
|
||||||
|
WowAddons.changed()
|
||||||
|
(if (done) context.getString(R.string.user_apps_updated, name) else context.getString(R.string.stores_dl_failed_reason, name)) to done
|
||||||
|
} else update?.let { installAddon(context, it, target, onProgress).let { (message, version) -> message to (version != null) } } ?: (null to false)
|
||||||
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun CloudRows(g: Library.SteamGame, onSynced: () -> Unit = {}) {
|
private fun CloudRows(g: Library.SteamGame, onSynced: () -> Unit = {}) {
|
||||||
val store = Store.byId(g.source)?.takeIf { it != Store.AMAZON } ?: return
|
val store = Store.byId(g.source)?.takeIf { it != Store.AMAZON } ?: return
|
||||||
|
|||||||
@@ -38,8 +38,10 @@ import com.droiddeck.launcher.input.InputButtonShape
|
|||||||
import com.droiddeck.launcher.input.InputButtonImages
|
import com.droiddeck.launcher.input.InputButtonImages
|
||||||
import com.droiddeck.launcher.input.PadBridge
|
import com.droiddeck.launcher.input.PadBridge
|
||||||
import com.droiddeck.launcher.input.PadKit
|
import com.droiddeck.launcher.input.PadKit
|
||||||
|
import com.droiddeck.launcher.input.ThrottledRedraw
|
||||||
import com.droiddeck.launcher.input.pcKeyLabel
|
import com.droiddeck.launcher.input.pcKeyLabel
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
|
import kotlin.math.abs
|
||||||
import kotlin.math.atan2
|
import kotlin.math.atan2
|
||||||
import kotlin.math.hypot
|
import kotlin.math.hypot
|
||||||
import kotlin.math.min
|
import kotlin.math.min
|
||||||
@@ -581,6 +583,10 @@ class InputSurfaceView(
|
|||||||
private var originY = 0f
|
private var originY = 0f
|
||||||
private var knobX = 0f
|
private var knobX = 0f
|
||||||
private var knobY = 0f
|
private var knobY = 0f
|
||||||
|
private var drawnX = 0f
|
||||||
|
private var drawnY = 0f
|
||||||
|
private var atRim = false
|
||||||
|
private val redraw = ThrottledRedraw(this, STICK_REDRAW_MS)
|
||||||
private val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
|
private val ring = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.STROKE }
|
||||||
private val knob = Paint(Paint.ANTI_ALIAS_FLAG)
|
private val knob = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||||
|
|
||||||
@@ -663,6 +669,7 @@ class InputSurfaceView(
|
|||||||
MotionEvent.ACTION_MOVE -> follow(event.getX(0), event.getY(0), r)
|
MotionEvent.ACTION_MOVE -> follow(event.getX(0), event.getY(0), r)
|
||||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
||||||
touching = false
|
touching = false
|
||||||
|
atRim = false
|
||||||
val cancelled = event.actionMasked == MotionEvent.ACTION_CANCEL || event.flags and MotionEvent.FLAG_CANCELED != 0
|
val cancelled = event.actionMasked == MotionEvent.ACTION_CANCEL || event.flags and MotionEvent.FLAG_CANCELED != 0
|
||||||
travel = maxOf(travel, hypot(event.x - downX, event.y - downY))
|
travel = maxOf(travel, hypot(event.x - downX, event.y - downY))
|
||||||
lastUp = if (!clicking && !cancelled && event.eventTime - downAt <= STICK_TAP_MS && travel <= tapSlop) event.eventTime else 0L
|
lastUp = if (!clicking && !cancelled && event.eventTime - downAt <= STICK_TAP_MS && travel <= tapSlop) event.eventTime else 0L
|
||||||
@@ -678,15 +685,27 @@ class InputSurfaceView(
|
|||||||
var dx = x - originX
|
var dx = x - originX
|
||||||
var dy = y - originY
|
var dy = y - originY
|
||||||
val length = hypot(dx, dy)
|
val length = hypot(dx, dy)
|
||||||
if (length > r) { dx *= r / length; dy *= r / length }
|
val rim = length > r
|
||||||
if (force || dx != knobX || dy != knobY) move(dx, dy, r)
|
if (rim) { dx *= r / length; dy *= r / length }
|
||||||
|
val reachedRim = rim && !atRim
|
||||||
|
atRim = rim
|
||||||
|
if (force || dx != knobX || dy != knobY) move(dx, dy, r, throttled = !force && !reachedRim, rim = rim)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun move(dx: Float, dy: Float, r: Float) {
|
private fun move(dx: Float, dy: Float, r: Float, throttled: Boolean = false, rim: Boolean = false) {
|
||||||
knobX = dx
|
knobX = dx
|
||||||
knobY = dy
|
knobY = dy
|
||||||
source?.update(dx / r, dy / r)
|
source?.update(dx / r, dy / r)
|
||||||
invalidate()
|
if (!throttled) {
|
||||||
|
redraw.cancel()
|
||||||
|
drawnX = dx
|
||||||
|
drawnY = dy
|
||||||
|
invalidate()
|
||||||
|
} else if (rim || abs(dx - drawnX) >= MIN_STICK_MOVE_PX || abs(dy - drawnY) >= MIN_STICK_MOVE_PX) {
|
||||||
|
drawnX = dx
|
||||||
|
drawnY = dy
|
||||||
|
redraw.request()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun setClick(down: Boolean) {
|
private fun setClick(down: Boolean) {
|
||||||
@@ -699,6 +718,7 @@ class InputSurfaceView(
|
|||||||
override fun onDetachedFromWindow() {
|
override fun onDetachedFromWindow() {
|
||||||
setClick(false)
|
setClick(false)
|
||||||
if (knobX != 0f || knobY != 0f) move(0f, 0f, 1f)
|
if (knobX != 0f || knobY != 0f) move(0f, 0f, 1f)
|
||||||
|
redraw.cancel()
|
||||||
super.onDetachedFromWindow()
|
super.onDetachedFromWindow()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -766,6 +786,8 @@ class InputSurfaceView(
|
|||||||
companion object {
|
companion object {
|
||||||
private const val CLICK_MS = 300L
|
private const val CLICK_MS = 300L
|
||||||
private const val STICK_TAP_MS = 200L
|
private const val STICK_TAP_MS = 200L
|
||||||
|
private const val STICK_REDRAW_MS = 33L
|
||||||
|
private const val MIN_STICK_MOVE_PX = 1f
|
||||||
private const val CLASSIC_REACH = 0.5f
|
private const val CLASSIC_REACH = 0.5f
|
||||||
private const val PANEL_REACH = 0.30f
|
private const val PANEL_REACH = 0.30f
|
||||||
private const val HIT_SLACK = 0.25f
|
private const val HIT_SLACK = 0.25f
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import com.droiddeck.launcher.frontend.AddedGames
|
|||||||
import com.droiddeck.launcher.frontend.Library
|
import com.droiddeck.launcher.frontend.Library
|
||||||
import com.droiddeck.launcher.frontend.SteamHidden
|
import com.droiddeck.launcher.frontend.SteamHidden
|
||||||
import com.droiddeck.launcher.session.SessionPrefs
|
import com.droiddeck.launcher.session.SessionPrefs
|
||||||
|
import com.droiddeck.launcher.stores.Store
|
||||||
|
|
||||||
internal const val LIBRARY_HIDDEN = "hidden"
|
internal const val LIBRARY_HIDDEN = "hidden"
|
||||||
internal val HIDDEN_DOT = androidx.compose.ui.graphics.Color(0xFF9AA0A6)
|
internal val HIDDEN_DOT = androidx.compose.ui.graphics.Color(0xFF9AA0A6)
|
||||||
@@ -46,14 +47,18 @@ internal object LibraryHidden {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun steamId(game: Library.SteamGame?): Long? = game?.takeIf { Library.fromSteamClient(it) }?.appId?.toLong()
|
/** The Steam client's own id for a game it lists, or for an owned Steam game it has not installed ([key] `steamstore:<appid>`). */
|
||||||
|
fun steamId(game: Library.SteamGame?, key: String = ""): Long? =
|
||||||
|
game?.takeIf { Library.fromSteamClient(it) }?.appId?.toLong()
|
||||||
|
?: key.takeIf { game == null && it.startsWith("${Store.STEAM.id}:") }?.substringAfter(':')?.toLongOrNull()
|
||||||
|
|
||||||
fun isHidden(key: String, game: Library.SteamGame?): Boolean = key in keys || steamId(game)?.let { it in steam } == true
|
fun isHidden(key: String, game: Library.SteamGame?): Boolean = key in keys || steamId(game, key)?.let { it in steam } == true
|
||||||
|
|
||||||
fun isHidden(entry: LibraryEntry): Boolean = isHidden(entry.favoriteKey, entry.game)
|
fun isHidden(entry: LibraryEntry): Boolean =
|
||||||
|
isHidden(entry.favoriteKey, entry.game) || entry.item?.takeIf { it.store == Store.STEAM }?.let { it.key in keys || it.id.toLongOrNull()?.let { id -> id in steam } == true } == true
|
||||||
|
|
||||||
fun set(context: Context, key: String, game: Library.SteamGame?, hidden: Boolean): Boolean {
|
fun set(context: Context, key: String, game: Library.SteamGame?, hidden: Boolean): Boolean {
|
||||||
val id = steamId(game)
|
val id = steamId(game, key)
|
||||||
val root = SessionPrefs.activeSteamRoot(context)
|
val root = SessionPrefs.activeSteamRoot(context)
|
||||||
val written = id?.let { SteamHidden.write(root, it, hidden) }
|
val written = id?.let { SteamHidden.write(root, it, hidden) }
|
||||||
if (id != null) {
|
if (id != null) {
|
||||||
|
|||||||
@@ -139,7 +139,8 @@ internal class LibraryEntry(
|
|||||||
val game: Library.SteamGame?, val item: CatalogItem?, val installed: Boolean,
|
val game: Library.SteamGame?, val item: CatalogItem?, val installed: Boolean,
|
||||||
) {
|
) {
|
||||||
val storeKey: String? get() = item?.key ?: game?.storeId?.let { "${game.source}:$it" }
|
val storeKey: String? get() = item?.key ?: game?.storeId?.let { "${game.source}:$it" }
|
||||||
val favoriteKey: String get() = storeKey ?: key
|
/** A Steam game keeps the key it has once the Steam client lists it, so favoriting it before the install carries over. */
|
||||||
|
val favoriteKey: String get() = if (item?.store == Store.STEAM) "app:${item.id}" else storeKey ?: key
|
||||||
}
|
}
|
||||||
|
|
||||||
internal fun libraryEntries(
|
internal fun libraryEntries(
|
||||||
@@ -149,6 +150,7 @@ internal fun libraryEntries(
|
|||||||
val out = ArrayList<LibraryEntry>()
|
val out = ArrayList<LibraryEntry>()
|
||||||
for (g in games.sortedBy { it.library == Library.XBOX_CLOUD }) {
|
for (g in games.sortedBy { it.library == Library.XBOX_CLOUD }) {
|
||||||
if (g.library == Library.EPIC_LAUNCHER) continue
|
if (g.library == Library.EPIC_LAUNCHER) continue
|
||||||
|
if (Library.fromSteamClient(g)) claimed.add("${Store.STEAM.id}:${g.appId}")
|
||||||
val storeKey = g.storeId?.let { "${g.source}:$it" }
|
val storeKey = g.storeId?.let { "${g.source}:$it" }
|
||||||
val item = storeKey?.let { k -> Store.byId(g.source)?.let { st -> owned[st]?.firstOrNull { it.key == k } } }
|
val item = storeKey?.let { k -> Store.byId(g.source)?.let { st -> owned[st]?.firstOrNull { it.key == k } } }
|
||||||
if (storeKey != null) {
|
if (storeKey != null) {
|
||||||
@@ -160,7 +162,7 @@ internal fun libraryEntries(
|
|||||||
}
|
}
|
||||||
for (store in Store.entries) for (item in owned[store].orEmpty()) {
|
for (store in Store.entries) for (item in owned[store].orEmpty()) {
|
||||||
if (!claimed.add(item.key)) continue
|
if (!claimed.add(item.key)) continue
|
||||||
out += LibraryEntry(GameRef.key(item), store.id, item.title, null, item, installed = item.key in installedStore)
|
out += LibraryEntry(GameRef.key(item), store.librarySource, item.title, null, item, installed = item.key in installedStore)
|
||||||
}
|
}
|
||||||
return out.distinctBy { it.key }
|
return out.distinctBy { it.key }
|
||||||
}
|
}
|
||||||
@@ -297,7 +299,7 @@ internal object LibraryView {
|
|||||||
fun showOwned(context: android.content.Context, store: Store) {
|
fun showOwned(context: android.content.Context, store: Store) {
|
||||||
SessionPrefs.setLibraryShowUninstalled(context, true)
|
SessionPrefs.setLibraryShowUninstalled(context, true)
|
||||||
ownedRequest++
|
ownedRequest++
|
||||||
source = store.id
|
source = store.librarySource
|
||||||
query = ""
|
query = ""
|
||||||
focusFirst = true
|
focusFirst = true
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ internal object StoreTabsState {
|
|||||||
private set
|
private set
|
||||||
|
|
||||||
fun load(context: android.content.Context) {
|
fun load(context: android.content.Context) {
|
||||||
SessionPrefs.settleStoresTabOrder(context, Store.entries.map { it.id })
|
SessionPrefs.settleStoresTabOrder(context, Store.tabbed.map { it.id })
|
||||||
tabs = arrangeStoreTabs(SessionPrefs.storesTabOrder(context), SessionPrefs.storesTabHidden(context))
|
tabs = arrangeStoreTabs(SessionPrefs.storesTabOrder(context), SessionPrefs.storesTabHidden(context))
|
||||||
libraryPlaces = SessionPrefs.libraryTabPlaces(context) ?: DEFAULT_LIBRARY_PLACES
|
libraryPlaces = SessionPrefs.libraryTabPlaces(context) ?: DEFAULT_LIBRARY_PLACES
|
||||||
libraryHidden = SessionPrefs.libraryTabsHidden(context) + listOfNotNull(LIBRARY_HIDDEN.takeUnless { SessionPrefs.libraryShowHidden(context) })
|
libraryHidden = SessionPrefs.libraryTabsHidden(context) + listOfNotNull(LIBRARY_HIDDEN.takeUnless { SessionPrefs.libraryShowHidden(context) })
|
||||||
|
|||||||
@@ -93,6 +93,7 @@ class ModeSettings(
|
|||||||
val steamClientArch: String? = null,
|
val steamClientArch: String? = null,
|
||||||
val returnAfterGame: Boolean? = null,
|
val returnAfterGame: Boolean? = null,
|
||||||
val shaderPrecache: Boolean? = null,
|
val shaderPrecache: Boolean? = null,
|
||||||
|
val valveProtonOnDemand: Boolean? = null,
|
||||||
val steamRepairQueued: Boolean = false,
|
val steamRepairQueued: Boolean = false,
|
||||||
val mangoapp: Boolean = true,
|
val mangoapp: Boolean = true,
|
||||||
val steamController: String? = null,
|
val steamController: String? = null,
|
||||||
@@ -158,6 +159,7 @@ class ModeSettingsActions(
|
|||||||
val onMangoapp: (Boolean) -> Unit = {},
|
val onMangoapp: (Boolean) -> Unit = {},
|
||||||
val onReturnAfterGame: (Boolean) -> Unit = {},
|
val onReturnAfterGame: (Boolean) -> Unit = {},
|
||||||
val onShaderPrecache: (Boolean) -> Unit = {},
|
val onShaderPrecache: (Boolean) -> Unit = {},
|
||||||
|
val onValveProtonOnDemand: (Boolean) -> Unit = {},
|
||||||
val onSteamController: (String) -> Unit = {},
|
val onSteamController: (String) -> Unit = {},
|
||||||
val onUnfoldedControls: (Boolean) -> Unit = {},
|
val onUnfoldedControls: (Boolean) -> Unit = {},
|
||||||
val onUnfoldedControlsWithController: (Boolean) -> Unit = {},
|
val onUnfoldedControlsWithController: (Boolean) -> Unit = {},
|
||||||
@@ -534,6 +536,10 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
|||||||
stringResource(R.string.mode_shader_precache_hint),
|
stringResource(R.string.mode_shader_precache_hint),
|
||||||
s.shaderPrecache, onChange = a.onShaderPrecache,
|
s.shaderPrecache, onChange = a.onShaderPrecache,
|
||||||
)
|
)
|
||||||
|
if (s.valveProtonOnDemand != null) ToggleRow(
|
||||||
|
host, "valveprotonondemand", stringResource(R.string.mode_valve_proton_on_demand), null,
|
||||||
|
s.valveProtonOnDemand, onChange = a.onValveProtonOnDemand,
|
||||||
|
)
|
||||||
SettingsRow(
|
SettingsRow(
|
||||||
stringResource(R.string.mode_steam_repair),
|
stringResource(R.string.mode_steam_repair),
|
||||||
stringResource(if (s.steamRepairQueued) R.string.mode_steam_repair_queued else R.string.mode_steam_repair_hint),
|
stringResource(if (s.steamRepairQueued) R.string.mode_steam_repair_queued else R.string.mode_steam_repair_hint),
|
||||||
|
|||||||
@@ -27,9 +27,9 @@ internal object DeveloperTools {
|
|||||||
internal object NavTabs {
|
internal object NavTabs {
|
||||||
const val MORE = "more"
|
const val MORE = "more"
|
||||||
val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
|
val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
|
||||||
val DEFAULT_SHELVED = setOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent")
|
val DEFAULT_SHELVED = setOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies", "agent")
|
||||||
val DEFAULT_HIDDEN = setOf("android-apps", "agent")
|
val DEFAULT_HIDDEN = setOf("android-apps", "agent")
|
||||||
private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "android-apps", "agent")
|
private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "agent")
|
||||||
private val OLD_ORDER = listOf("steam", "games", "soundtracks", "stores", "downloads", "desktop", "agent", "components", "android-apps", "storage", "sync", "setup", "updates")
|
private val OLD_ORDER = listOf("steam", "games", "soundtracks", "stores", "downloads", "desktop", "agent", "components", "android-apps", "storage", "sync", "setup", "updates")
|
||||||
private val OLD_SHELVED = setOf("soundtracks", "agent", "storage", "sync")
|
private val OLD_SHELVED = setOf("soundtracks", "agent", "storage", "sync")
|
||||||
private const val LAYOUT_VERSION = 2
|
private const val LAYOUT_VERSION = 2
|
||||||
@@ -95,6 +95,15 @@ internal object NavTabs {
|
|||||||
else -> true
|
else -> true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Apps only has content when DroidDeck is the home app, so it follows that state on each change and
|
||||||
|
// otherwise stays wherever the user put it.
|
||||||
|
fun syncHomeApps(context: Context, homeSelected: Boolean) {
|
||||||
|
val seen = SessionPrefs.appsTabHomeSeen(context)
|
||||||
|
SessionPrefs.setAppsTabHomeSeen(context, homeSelected)
|
||||||
|
if (seen == homeSelected || (seen == null && !homeSelected)) return
|
||||||
|
setHidden(context, "android-apps", !homeSelected)
|
||||||
|
}
|
||||||
|
|
||||||
fun hideable(key: String) = key != "setup"
|
fun hideable(key: String) = key != "setup"
|
||||||
|
|
||||||
fun place(s: FrontEndState, key: String): TabPlace = when {
|
fun place(s: FrontEndState, key: String): TabPlace = when {
|
||||||
|
|||||||
@@ -1787,12 +1787,15 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
|
|||||||
chipModifier = track("cmp-proton"),
|
chipModifier = track("cmp-proton"),
|
||||||
onPick = { id -> a.onGameProton(gameProfile.appId, id) },
|
onPick = { id -> a.onGameProton(gameProfile.appId, id) },
|
||||||
)
|
)
|
||||||
|
val gameTool = snap.protons.firstOrNull { it.proton.id == gameProfile.protonId }?.proton?.dir?.name
|
||||||
for (comp in ComponentsManager.COMPONENTS) {
|
for (comp in ComponentsManager.COMPONENTS) {
|
||||||
val value = gameProfile.components.getValue(comp)
|
val value = gameProfile.components.getValue(comp)
|
||||||
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
|
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
|
||||||
val options: List<Pair<String?, String>> =
|
val options: List<Pair<String?, String>> =
|
||||||
listOf(null to stringResource(R.string.comp_game_use_general)) +
|
listOf(null to stringResource(R.string.comp_game_use_general)) +
|
||||||
if (managedDxvk) emptyList() else snap.packages.filter { it.comp == comp }.map { it.file to it.version }
|
if (managedDxvk) emptyList() else ComponentsManager.forTool(
|
||||||
|
comp, gameTool, snap.packages.filter { it.comp == comp }, gameProfile.componentFiles[comp],
|
||||||
|
) { it.file }.map { it.file to it.version }
|
||||||
DrawerStackedChoice(
|
DrawerStackedChoice(
|
||||||
host = host,
|
host = host,
|
||||||
key = "game-cmp-$comp",
|
key = "game-cmp-$comp",
|
||||||
@@ -1875,7 +1878,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
|
|||||||
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
|
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
|
||||||
val originals = view.originals.filter { it.comp == comp }
|
val originals = view.originals.filter { it.comp == comp }
|
||||||
val options = originals.map { "orig:${it.protonVersion}" to (if (it.protonVersion == build) originalLabel else stringResource(R.string.comp_original, it.protonVersion)) } +
|
val options = originals.map { "orig:${it.protonVersion}" to (if (it.protonVersion == build) originalLabel else stringResource(R.string.comp_original, it.protonVersion)) } +
|
||||||
snap.packages.filter { it.comp == comp }.map { it.file to it.version }
|
ComponentsManager.forTool(comp, p.dir.name, snap.packages.filter { it.comp == comp }, st.activeFile) { it.file }.map { it.file to it.version }
|
||||||
if (options.isEmpty() && !managedDxvk) continue
|
if (options.isEmpty() && !managedDxvk) continue
|
||||||
val current = st.activeFile ?: "orig:$build"
|
val current = st.activeFile ?: "orig:$build"
|
||||||
val shown = options.firstOrNull { it.first == current }?.second
|
val shown = options.firstOrNull { it.first == current }?.second
|
||||||
|
|||||||
@@ -115,10 +115,11 @@ internal fun SteamHome(s: FrontEndState, a: FrontEndActions, modifier: Modifier)
|
|||||||
account = { host ->
|
account = { host ->
|
||||||
SettingsGroup(stringResource(R.string.setup_account)) {
|
SettingsGroup(stringResource(R.string.setup_account)) {
|
||||||
ToggleRow(
|
ToggleRow(
|
||||||
host, "offline", stringResource(R.string.setup_offline),
|
host, "offline-auto", stringResource(R.string.setup_offline_auto),
|
||||||
s.offlineAccount?.let { if (it.isEmpty()) stringResource(R.string.setup_signed_in_unnamed) else stringResource(R.string.setup_signed_in, it) } ?: stringResource(R.string.setup_sign_in_first),
|
s.offlineAccount?.let { if (it.isEmpty()) stringResource(R.string.setup_signed_in_unnamed) else stringResource(R.string.setup_signed_in, it) } ?: stringResource(R.string.setup_sign_in_first),
|
||||||
s.offline, enabled = s.offlineAccount != null,
|
s.offlineAuto, enabled = s.offlineAccount != null,
|
||||||
) { a.onOffline() }
|
) { a.onOfflineAuto() }
|
||||||
|
if (!s.offlineAuto) ToggleRow(host, "offline", stringResource(R.string.setup_offline), null, s.offline, enabled = s.offlineAccount != null) { a.onOffline() }
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ internal fun sourceColours(source: String): SourceColours = when (source) {
|
|||||||
Store.UBISOFT.id -> SourceColours(Color(0xFF0B1E44), Color(0xFFA8C6FF), Color(0xFF2E7DFF))
|
Store.UBISOFT.id -> SourceColours(Color(0xFF0B1E44), Color(0xFFA8C6FF), Color(0xFF2E7DFF))
|
||||||
Store.EA.id -> SourceColours(Color(0xFF3A0E12), Color(0xFFFF9A9A), Color(0xFFFF4747))
|
Store.EA.id -> SourceColours(Color(0xFF3A0E12), Color(0xFFFF9A9A), Color(0xFFFF4747))
|
||||||
Store.ROCKSTAR.id -> SourceColours(Color(0xFF3A2A06), Color(0xFFFFD780), Color(0xFFFCAF17))
|
Store.ROCKSTAR.id -> SourceColours(Color(0xFF3A2A06), Color(0xFFFFD780), Color(0xFFFCAF17))
|
||||||
Library.SOURCE_STEAM -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF))
|
Library.SOURCE_STEAM, Store.STEAM.id -> SourceColours(Color(0xFF16293D), Color(0xFF7CC4FF), Color(0xFF1A9FFF))
|
||||||
Library.SOURCE_COLLECTION -> SourceColours(Color(0xFF2B1A3D), Color(0xFFD2A8FF), Color(0xFFA25BFF))
|
Library.SOURCE_COLLECTION -> SourceColours(Color(0xFF2B1A3D), Color(0xFFD2A8FF), Color(0xFFA25BFF))
|
||||||
FLATHUB -> SourceColours(Color(0xFF0B2E2B), Color(0xFF9FE3DD), FlathubTeal)
|
FLATHUB -> SourceColours(Color(0xFF0B2E2B), Color(0xFF9FE3DD), FlathubTeal)
|
||||||
else -> SourceColours(Color(0xFF1A1D22), Color(0xFF9AA3AF), Color(0xFF9AA3AF))
|
else -> SourceColours(Color(0xFF1A1D22), Color(0xFF9AA3AF), Color(0xFF9AA3AF))
|
||||||
@@ -47,7 +47,7 @@ internal fun sourceColours(source: String): SourceColours = when (source) {
|
|||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
internal fun sourceLabel(source: String): String = when (source) {
|
internal fun sourceLabel(source: String): String = when (source) {
|
||||||
Library.SOURCE_STEAM -> stringResource(R.string.source_steam)
|
Library.SOURCE_STEAM, Store.STEAM.id -> stringResource(R.string.source_steam)
|
||||||
Library.SOURCE_COLLECTION -> stringResource(R.string.soundtracks_collections)
|
Library.SOURCE_COLLECTION -> stringResource(R.string.soundtracks_collections)
|
||||||
Store.GOG.id -> Store.GOG.label
|
Store.GOG.id -> Store.GOG.label
|
||||||
Store.EPIC.id -> Store.EPIC.label
|
Store.EPIC.id -> Store.EPIC.label
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import androidx.compose.runtime.Composable
|
|||||||
import androidx.compose.runtime.LaunchedEffect
|
import androidx.compose.runtime.LaunchedEffect
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.mutableStateOf
|
import androidx.compose.runtime.mutableStateOf
|
||||||
|
import androidx.compose.runtime.produceState
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
import androidx.compose.runtime.setValue
|
import androidx.compose.runtime.setValue
|
||||||
import androidx.compose.ui.Alignment
|
import androidx.compose.ui.Alignment
|
||||||
@@ -46,7 +47,10 @@ import com.droiddeck.launcher.session.SessionPrefs
|
|||||||
import com.droiddeck.launcher.stores.CatalogItem
|
import com.droiddeck.launcher.stores.CatalogItem
|
||||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||||
import com.droiddeck.launcher.stores.StoreLanguage
|
import com.droiddeck.launcher.stores.StoreLanguage
|
||||||
|
import com.droiddeck.launcher.stores.StoreSizes
|
||||||
import com.droiddeck.launcher.stores.StoresState
|
import com.droiddeck.launcher.stores.StoresState
|
||||||
|
import com.droiddeck.launcher.stores.steam.SteamClient
|
||||||
|
import com.droiddeck.launcher.stores.steam.SteamStore
|
||||||
import com.droiddeck.launcher.stores.formatBytes
|
import com.droiddeck.launcher.stores.formatBytes
|
||||||
import com.droiddeck.launcher.stores.gog.GogDownloadManager
|
import com.droiddeck.launcher.stores.gog.GogDownloadManager
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
@@ -133,6 +137,61 @@ internal fun InstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Composable
|
||||||
|
internal fun SteamInstallWhereDialog(item: CatalogItem, onDismiss: () -> Unit) {
|
||||||
|
val ctx = LocalContext.current
|
||||||
|
val colors = MaterialTheme.colorScheme
|
||||||
|
val shown = rememberShown(onDismiss)
|
||||||
|
val close = { shown.targetState = false }
|
||||||
|
val targets by produceState<List<SteamClient.Target>?>(null, item.key) {
|
||||||
|
value = withContext(Dispatchers.IO) { runCatching { SteamClient.targets(ctx) }.getOrDefault(emptyList()) }
|
||||||
|
}
|
||||||
|
val needed by produceState(StoreSizes.size(item), item.key) {
|
||||||
|
val bytes = withContext(Dispatchers.IO) { runCatching { SteamStore.plannedBytes(ctx, item) }.getOrDefault(0L) }
|
||||||
|
if (bytes > 0L) value = bytes
|
||||||
|
}
|
||||||
|
val list = targets
|
||||||
|
val focus = remember(list?.size) { List(list?.size ?: 0) { FocusRequester() } }
|
||||||
|
LaunchedEffect(focus) { if (focus.isNotEmpty()) focusWithinFrames({ false }) { focus[0] } }
|
||||||
|
AppDialog(shown, close, "steamInstallWhere", wide = false, maxWidth = 440.dp) {
|
||||||
|
Rise(0) {
|
||||||
|
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
|
||||||
|
Text(
|
||||||
|
stringResource(R.string.stores_install_title, item.title), fontSize = 15.sp, color = colors.onBackground,
|
||||||
|
maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f),
|
||||||
|
)
|
||||||
|
Text(
|
||||||
|
stringResource(R.string.common_cancel), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onSurfaceVariant,
|
||||||
|
modifier = Modifier.clip(Shape12).focusGlide().clickable(role = Role.Button, onClick = close).controllerConfirm(onClick = close).padding(horizontal = 10.dp, vertical = 6.dp),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Rise(1) {
|
||||||
|
when {
|
||||||
|
list == null -> androidx.compose.material3.LinearProgressIndicator(Modifier.fillMaxWidth().height(3.dp))
|
||||||
|
list.isEmpty() -> Note(stringResource(R.string.game_sync_err_steam_library))
|
||||||
|
else -> Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth()) {
|
||||||
|
list.forEachIndexed { i, t ->
|
||||||
|
val isLow = StoreInstallRoot.insufficientSpace(needed, t.freeBytes)
|
||||||
|
val freeText = when {
|
||||||
|
t.freeBytes < 0L -> stringResource(R.string.stores_target_free_unknown)
|
||||||
|
isLow -> stringResource(R.string.stores_storage_low, formatBytes(t.freeBytes), formatBytes(needed))
|
||||||
|
else -> stringResource(R.string.stores_target_free, formatBytes(t.freeBytes))
|
||||||
|
}
|
||||||
|
TargetRow(
|
||||||
|
label = t.label, free = freeText, removable = t.removable, folder = t.folder, focus = focus[i],
|
||||||
|
modifier = Modifier.fillMaxWidth(), warning = isLow,
|
||||||
|
) {
|
||||||
|
SteamStore.install(ctx, item, t)
|
||||||
|
close()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
private fun TargetRow(label: String, free: String, removable: Boolean, folder: Boolean, focus: FocusRequester, modifier: Modifier, warning: Boolean = false, onPick: () -> Unit) {
|
private fun TargetRow(label: String, free: String, removable: Boolean, folder: Boolean, focus: FocusRequester, modifier: Modifier, warning: Boolean = false, onPick: () -> Unit) {
|
||||||
val colors = MaterialTheme.colorScheme
|
val colors = MaterialTheme.colorScheme
|
||||||
|
|||||||
@@ -1031,6 +1031,7 @@ internal fun storePalette(base: Palette, store: Store?): Palette {
|
|||||||
Store.UBISOFT -> Color(0xFF2E7DFF) to Color(0xFF1A5BD6)
|
Store.UBISOFT -> Color(0xFF2E7DFF) to Color(0xFF1A5BD6)
|
||||||
Store.EA -> Color(0xFFFF4747) to Color(0xFFE03030)
|
Store.EA -> Color(0xFFFF4747) to Color(0xFFE03030)
|
||||||
Store.ROCKSTAR -> Color(0xFFFCAF17) to Color(0xFFD98E00)
|
Store.ROCKSTAR -> Color(0xFFFCAF17) to Color(0xFFD98E00)
|
||||||
|
Store.STEAM -> Color(0xFF1A9FFF) to Color(0xFF0F6FC0)
|
||||||
null -> return base
|
null -> return base
|
||||||
}
|
}
|
||||||
val on = if (accent.luminance() > 0.18f) Color(0xFF0B0B0D) else Color.White
|
val on = if (accent.luminance() > 0.18f) Color(0xFF0B0B0D) else Color.White
|
||||||
@@ -1323,6 +1324,6 @@ internal fun openUrl(ctx: android.content.Context, url: String) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
internal fun launchStoreGame(store: Store, id: String, s: FrontEndState, a: FrontEndActions) {
|
internal fun launchStoreGame(store: Store, id: String, s: FrontEndState, a: FrontEndActions) {
|
||||||
val game = s.steamGames.firstOrNull { it.source == store.id && it.storeId == id }
|
val game = GameRef(null, store, id).game(s.steamGames)
|
||||||
if (game != null) a.onSteamGame(game) else a.onStoreGame(store, id)
|
if (game != null) a.onSteamGame(game) else a.onStoreGame(store, id)
|
||||||
}
|
}
|
||||||
@@ -84,7 +84,7 @@ object CompositorHost {
|
|||||||
com.droiddeck.launcher.gpu.TpUbwcHint.applyToProcess(context)
|
com.droiddeck.launcher.gpu.TpUbwcHint.applyToProcess(context)
|
||||||
WaylandCompositor.nativeStartWithSurface(
|
WaylandCompositor.nativeStartWithSurface(
|
||||||
surface, xdgRuntimeDir, driverPath, libraryName, nativeLibDir,
|
surface, xdgRuntimeDir, driverPath, libraryName, nativeLibDir,
|
||||||
SessionPrefs.androidDriver(context).isEmpty(),
|
SessionPrefs.displayDriverFromAuto(context),
|
||||||
)
|
)
|
||||||
attached = surface
|
attached = surface
|
||||||
started = true
|
started = true
|
||||||
|
|||||||
@@ -934,6 +934,7 @@
|
|||||||
<string name="setup_reset_settings_session_running">أوقف الجلسة قبل إعادة تعيين الإعدادات.</string>
|
<string name="setup_reset_settings_session_running">أوقف الجلسة قبل إعادة تعيين الإعدادات.</string>
|
||||||
<string name="setup_reset_settings_partial">أُعيد تعيين الإعدادات، لكن ليس كلها. التفاصيل في السجلات.</string>
|
<string name="setup_reset_settings_partial">أُعيد تعيين الإعدادات، لكن ليس كلها. التفاصيل في السجلات.</string>
|
||||||
<string name="setup_offline">وضع عدم الاتصال</string>
|
<string name="setup_offline">وضع عدم الاتصال</string>
|
||||||
|
<string name="setup_offline_auto">وضع عدم الاتصال التلقائي</string>
|
||||||
<string name="setup_sign_in_first">سجّل الدخول إلى Steam أولًا</string>
|
<string name="setup_sign_in_first">سجّل الدخول إلى Steam أولًا</string>
|
||||||
<string name="setup_launcher">المشغّل</string>
|
<string name="setup_launcher">المشغّل</string>
|
||||||
<string name="setup_language">اللغة</string>
|
<string name="setup_language">اللغة</string>
|
||||||
@@ -2818,6 +2819,7 @@
|
|||||||
<string name="stores_login_error_ssl">الاتصال بصفحة تسجيل الدخول غير آمن.</string>
|
<string name="stores_login_error_ssl">الاتصال بصفحة تسجيل الدخول غير آمن.</string>
|
||||||
<string name="stores_login_error_verification">تعذّر التحقّق من تسجيل الدخول. حاوِل مرة أخرى.</string>
|
<string name="stores_login_error_verification">تعذّر التحقّق من تسجيل الدخول. حاوِل مرة أخرى.</string>
|
||||||
<string name="stores_login_error_generic">فشل تسجيل الدخول. حاوِل مرة أخرى.</string>
|
<string name="stores_login_error_generic">فشل تسجيل الدخول. حاوِل مرة أخرى.</string>
|
||||||
|
<string name="stores_login_continue_in_browser">يحتاج %1$s إلى خطوة أخرى. أكملها في المتصفح الذي فُتح، ثم حاول مرة أخرى.</string>
|
||||||
<string name="common_close">إغلاق</string>
|
<string name="common_close">إغلاق</string>
|
||||||
<string name="common_back">رجوع</string>
|
<string name="common_back">رجوع</string>
|
||||||
<string name="common_edit">تعديل</string>
|
<string name="common_edit">تعديل</string>
|
||||||
@@ -4239,4 +4241,7 @@
|
|||||||
<string name="theme_custom_error">خطأ</string>
|
<string name="theme_custom_error">خطأ</string>
|
||||||
<string name="hud_only_during_game">عرض HUD أثناء اللعب فقط</string>
|
<string name="hud_only_during_game">عرض HUD أثناء اللعب فقط</string>
|
||||||
<string name="hud_only_during_game_hint">إخفاء HUD عند عدم اكتشاف إطارات اللعبة.</string>
|
<string name="hud_only_during_game_hint">إخفاء HUD عند عدم اكتشاف إطارات اللعبة.</string>
|
||||||
|
<string name="steam_store_close_steam">أغلق Steam أولاً</string>
|
||||||
|
<string name="steam_store_session_wait">أوقف تنزيل Steam مؤقتًا أولاً</string>
|
||||||
|
<string name="steam_store_linux_build">تثبّت هذه اللعبة إصدار Linux الخاص بها. ثبّتها من Steam.</string>
|
||||||
</resources>
|
</resources>
|
||||||
@@ -952,6 +952,7 @@
|
|||||||
<string name="setup_reset_settings_session_running">Detén la sesión antes de restablecer los ajustes.</string>
|
<string name="setup_reset_settings_session_running">Detén la sesión antes de restablecer los ajustes.</string>
|
||||||
<string name="setup_reset_settings_partial">Los ajustes se restablecieron, pero algunas partes no se pudieron restablecer. Los registros tienen los detalles.</string>
|
<string name="setup_reset_settings_partial">Los ajustes se restablecieron, pero algunas partes no se pudieron restablecer. Los registros tienen los detalles.</string>
|
||||||
<string name="setup_offline">Modo sin conexión</string>
|
<string name="setup_offline">Modo sin conexión</string>
|
||||||
|
<string name="setup_offline_auto">Modo sin conexión automático</string>
|
||||||
<string name="setup_sign_in_first">Inicia sesión en Steam primero</string>
|
<string name="setup_sign_in_first">Inicia sesión en Steam primero</string>
|
||||||
<string name="setup_launcher">Launcher</string>
|
<string name="setup_launcher">Launcher</string>
|
||||||
<string name="setup_language">Idioma</string>
|
<string name="setup_language">Idioma</string>
|
||||||
@@ -2784,6 +2785,7 @@
|
|||||||
<string name="stores_login_error_ssl">La conexión con la página de inicio de sesión no es segura.</string>
|
<string name="stores_login_error_ssl">La conexión con la página de inicio de sesión no es segura.</string>
|
||||||
<string name="stores_login_error_verification">No se pudo verificar el inicio de sesión. Inténtalo de nuevo.</string>
|
<string name="stores_login_error_verification">No se pudo verificar el inicio de sesión. Inténtalo de nuevo.</string>
|
||||||
<string name="stores_login_error_generic">No se pudo iniciar sesión. Inténtalo de nuevo.</string>
|
<string name="stores_login_error_generic">No se pudo iniciar sesión. Inténtalo de nuevo.</string>
|
||||||
|
<string name="stores_login_continue_in_browser">%1$s necesita un paso más. Complétalo en el navegador que se abrió y vuelve a intentarlo.</string>
|
||||||
<string name="common_close">Cerrar</string>
|
<string name="common_close">Cerrar</string>
|
||||||
<string name="common_back">Atrás</string>
|
<string name="common_back">Atrás</string>
|
||||||
<string name="common_edit">Editar</string>
|
<string name="common_edit">Editar</string>
|
||||||
@@ -4119,4 +4121,7 @@
|
|||||||
<string name="theme_custom_error">Error</string>
|
<string name="theme_custom_error">Error</string>
|
||||||
<string name="hud_only_during_game">Mostrar el HUD solo durante una partida</string>
|
<string name="hud_only_during_game">Mostrar el HUD solo durante una partida</string>
|
||||||
<string name="hud_only_during_game_hint">Ocultar el HUD cuando no se detecten fotogramas del juego.</string>
|
<string name="hud_only_during_game_hint">Ocultar el HUD cuando no se detecten fotogramas del juego.</string>
|
||||||
|
<string name="steam_store_close_steam">Cierra Steam primero</string>
|
||||||
|
<string name="steam_store_session_wait">Pausa primero la descarga de Steam</string>
|
||||||
|
<string name="steam_store_linux_build">Este juego instala su versión para Linux. Instálalo desde Steam.</string>
|
||||||
</resources>
|
</resources>
|
||||||
@@ -922,6 +922,7 @@
|
|||||||
<string name="setup_reset_settings_session_running">Спри сесията, преди да нулираш настройките.</string>
|
<string name="setup_reset_settings_session_running">Спри сесията, преди да нулираш настройките.</string>
|
||||||
<string name="setup_reset_settings_partial">Настройките са нулирани, но не всички. Подробностите са в логовете.</string>
|
<string name="setup_reset_settings_partial">Настройките са нулирани, но не всички. Подробностите са в логовете.</string>
|
||||||
<string name="setup_offline">Офлайн режим</string>
|
<string name="setup_offline">Офлайн режим</string>
|
||||||
|
<string name="setup_offline_auto">Автоматичен офлайн режим</string>
|
||||||
<string name="setup_sign_in_first">Първо влезте в Steam</string>
|
<string name="setup_sign_in_first">Първо влезте в Steam</string>
|
||||||
<string name="setup_launcher">Лаунчър</string>
|
<string name="setup_launcher">Лаунчър</string>
|
||||||
<string name="setup_language">Език</string>
|
<string name="setup_language">Език</string>
|
||||||
@@ -2714,6 +2715,7 @@
|
|||||||
<string name="stores_login_error_ssl">Връзката със страницата за вход не е защитена.</string>
|
<string name="stores_login_error_ssl">Връзката със страницата за вход не е защитена.</string>
|
||||||
<string name="stores_login_error_verification">Входът не можа да бъде потвърден. Опитай отново.</string>
|
<string name="stores_login_error_verification">Входът не можа да бъде потвърден. Опитай отново.</string>
|
||||||
<string name="stores_login_error_generic">Входът се провали. Опитай отново.</string>
|
<string name="stores_login_error_generic">Входът се провали. Опитай отново.</string>
|
||||||
|
<string name="stores_login_continue_in_browser">%1$s изисква още една стъпка. Завърши я в браузъра, който се отвори, и опитай отново.</string>
|
||||||
<string name="common_close">Затвори</string>
|
<string name="common_close">Затвори</string>
|
||||||
<string name="common_back">Назад</string>
|
<string name="common_back">Назад</string>
|
||||||
<string name="common_edit">Редактирай</string>
|
<string name="common_edit">Редактирай</string>
|
||||||
@@ -4079,4 +4081,7 @@
|
|||||||
<string name="theme_custom_error">Грешка</string>
|
<string name="theme_custom_error">Грешка</string>
|
||||||
<string name="hud_only_during_game">Показвай HUD само по време на игра</string>
|
<string name="hud_only_during_game">Показвай HUD само по време на игра</string>
|
||||||
<string name="hud_only_during_game_hint">Скривай HUD, когато не се засичат кадри от играта.</string>
|
<string name="hud_only_during_game_hint">Скривай HUD, когато не се засичат кадри от играта.</string>
|
||||||
|
<string name="steam_store_close_steam">Първо затворете Steam</string>
|
||||||
|
<string name="steam_store_session_wait">Първо поставете на пауза изтеглянето от Steam</string>
|
||||||
|
<string name="steam_store_linux_build">Тази игра инсталира версията си за Linux. Инсталирайте я от Steam.</string>
|
||||||
</resources>
|
</resources>
|
||||||
@@ -928,6 +928,7 @@
|
|||||||
<string name="setup_reset_settings_session_running">Před obnovením nastavení zastav relaci.</string>
|
<string name="setup_reset_settings_session_running">Před obnovením nastavení zastav relaci.</string>
|
||||||
<string name="setup_reset_settings_partial">Nastavení byla obnovena, ale ne všechna. Podrobnosti jsou v logech.</string>
|
<string name="setup_reset_settings_partial">Nastavení byla obnovena, ale ne všechna. Podrobnosti jsou v logech.</string>
|
||||||
<string name="setup_offline">Režim offline</string>
|
<string name="setup_offline">Režim offline</string>
|
||||||
|
<string name="setup_offline_auto">Automatický režim offline</string>
|
||||||
<string name="setup_sign_in_first">Nejprve se přihlaste ke Steamu</string>
|
<string name="setup_sign_in_first">Nejprve se přihlaste ke Steamu</string>
|
||||||
<string name="setup_launcher">Spouštěč</string>
|
<string name="setup_launcher">Spouštěč</string>
|
||||||
<string name="setup_language">Jazyk</string>
|
<string name="setup_language">Jazyk</string>
|
||||||
@@ -2766,6 +2767,7 @@
|
|||||||
<string name="stores_login_error_ssl">Spojení s přihlašovací stránkou není zabezpečené.</string>
|
<string name="stores_login_error_ssl">Spojení s přihlašovací stránkou není zabezpečené.</string>
|
||||||
<string name="stores_login_error_verification">Přihlášení se nepodařilo ověřit. Zkuste to znovu.</string>
|
<string name="stores_login_error_verification">Přihlášení se nepodařilo ověřit. Zkuste to znovu.</string>
|
||||||
<string name="stores_login_error_generic">Přihlášení se nezdařilo. Zkuste to znovu.</string>
|
<string name="stores_login_error_generic">Přihlášení se nezdařilo. Zkuste to znovu.</string>
|
||||||
|
<string name="stores_login_continue_in_browser">%1$s vyžaduje ještě jeden krok. Dokončete ho v prohlížeči, který se otevřel, a zkuste to znovu.</string>
|
||||||
<string name="common_close">Zavřít</string>
|
<string name="common_close">Zavřít</string>
|
||||||
<string name="common_back">Zpět</string>
|
<string name="common_back">Zpět</string>
|
||||||
<string name="common_edit">Upravit</string>
|
<string name="common_edit">Upravit</string>
|
||||||
@@ -4159,4 +4161,7 @@
|
|||||||
<string name="theme_custom_error">Chyba</string>
|
<string name="theme_custom_error">Chyba</string>
|
||||||
<string name="hud_only_during_game">Zobrazovat HUD pouze během hry</string>
|
<string name="hud_only_during_game">Zobrazovat HUD pouze během hry</string>
|
||||||
<string name="hud_only_during_game_hint">Skrýt HUD, když nejsou detekovány snímky hry.</string>
|
<string name="hud_only_during_game_hint">Skrýt HUD, když nejsou detekovány snímky hry.</string>
|
||||||
|
<string name="steam_store_close_steam">Nejprve zavřete Steam</string>
|
||||||
|
<string name="steam_store_session_wait">Nejprve pozastavte stahování ze Steamu</string>
|
||||||
|
<string name="steam_store_linux_build">Tato hra instaluje svou verzi pro Linux. Nainstalujte ji ze Steamu.</string>
|
||||||
</resources>
|
</resources>
|
||||||
Loaded 100 of 349 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user