Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
33ebc24647 | ||
|
|
f9729d10e4 | ||
|
|
c98be87383 | ||
|
|
e854bf8403 | ||
|
|
bdb240b640 | ||
|
|
0a6060d409 | ||
|
|
81d2643a88 | ||
|
|
1099b82044 | ||
|
|
dae53c29e0 | ||
|
|
d168705954 | ||
|
|
8ba8b12e78 | ||
|
|
aade03b7cf | ||
|
|
eaa12a3594 | ||
|
|
b3fc6b9a2c | ||
|
|
643496ae70 | ||
|
|
1288874810 | ||
|
|
2510b5e113 | ||
|
|
38cda8131d | ||
|
|
4cebd09aa6 | ||
|
|
fce3daaf45 | ||
|
|
88a648c273 | ||
|
|
6ead4af37e |
No files matched your search
@@ -6,4 +6,3 @@ KeegantheVeganat0r
|
||||
kingokksa
|
||||
ovurrsl
|
||||
KeegantheVeganat0r
|
||||
EnzoDLofi
|
||||
@@ -1,35 +0,0 @@
|
||||
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/*
|
||||
@@ -572,65 +572,23 @@ jobs:
|
||||
SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
|
||||
run: python3 tools/components/prepare.py unpack --tree "$SOURCE_TREE"
|
||||
|
||||
# A hosted runner needs over 20 minutes per launcher; rebuild only when its sources change, and save each
|
||||
# build as soon as it finishes so a later timeout cannot discard it.
|
||||
- name: Restore the Ubisoft launcher build
|
||||
id: ubisoft-cache
|
||||
uses: actions/cache/restore@v4
|
||||
with:
|
||||
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-ubisoft
|
||||
key: ubisoft-launcher-v1-${{ steps.rust.outputs.rustc }}-${{ hashFiles('tools/ubisoft-launcher/src/**', 'tools/ubisoft-launcher/Cargo.toml', 'tools/ubisoft-launcher/Cargo.lock', 'tools/ubisoft-launcher/build.sh', 'tools/ubisoft-launcher/build.rs', 'tools/ubisoft-launcher/.cargo/**') }}
|
||||
- name: Ubisoft launcher service (x86_64-pc-windows-gnu)
|
||||
if: steps.ubisoft-cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; }
|
||||
bash tools/ubisoft-launcher/build.sh
|
||||
- name: Save the Ubisoft launcher build
|
||||
if: steps.ubisoft-cache.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@v4
|
||||
with:
|
||||
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-ubisoft
|
||||
key: ${{ steps.ubisoft-cache.outputs.cache-primary-key }}
|
||||
|
||||
- name: Restore the Rockstar launcher build
|
||||
id: rockstar-cache
|
||||
uses: actions/cache/restore@v4
|
||||
with:
|
||||
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-rockstar
|
||||
key: rockstar-launcher-v1-${{ steps.rust.outputs.rustc }}-${{ hashFiles('tools/rockstar-launcher/src/**', 'tools/rockstar-launcher/Cargo.toml', 'tools/rockstar-launcher/Cargo.lock', 'tools/rockstar-launcher/build.sh', 'tools/rockstar-launcher/build.rs', 'tools/rockstar-launcher/.cargo/**') }}
|
||||
- name: Rockstar launcher service (32-bit and 64-bit)
|
||||
if: steps.rockstar-cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
command -v i686-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-i686; }
|
||||
command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; }
|
||||
bash tools/rockstar-launcher/build.sh
|
||||
- name: Save the Rockstar launcher build
|
||||
if: steps.rockstar-cache.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@v4
|
||||
with:
|
||||
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-rockstar
|
||||
key: ${{ steps.rockstar-cache.outputs.cache-primary-key }}
|
||||
|
||||
- name: Restore the Epic launcher build
|
||||
id: epic-cache
|
||||
uses: actions/cache/restore@v4
|
||||
with:
|
||||
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic
|
||||
key: epic-launcher-v1-${{ steps.rust.outputs.rustc }}-${{ hashFiles('tools/epic-launcher/src/**', 'tools/epic-launcher/Cargo.toml', 'tools/epic-launcher/Cargo.lock', 'tools/epic-launcher/build.sh', 'tools/epic-launcher/build.rs', 'tools/epic-launcher/.cargo/**') }}
|
||||
- name: Epic Games Launcher parent stand-in (x86_64-pc-windows-gnu)
|
||||
if: steps.epic-cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
command -v x86_64-w64-mingw32-gcc >/dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq gcc-mingw-w64-x86-64; }
|
||||
bash tools/epic-launcher/build.sh
|
||||
- name: Save the Epic launcher build
|
||||
if: steps.epic-cache.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@v4
|
||||
with:
|
||||
path: app/src/main/assets/linuxfs/usr/local/lib/droiddeck-epic
|
||||
key: ${{ steps.epic-cache.outputs.cache-primary-key }}
|
||||
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
@@ -739,32 +697,11 @@ jobs:
|
||||
run: |
|
||||
echo "version=$(grep -o "org.robolectric:robolectric:[0-9.]*" app/build.gradle | cut -d: -f3)" >> "$GITHUB_OUTPUT"
|
||||
# Robolectric downloads these from Maven Central on first use without retrying, and 429s fail whole test classes.
|
||||
# The cache path sits beside the workspace because runner homes are at different depths from it, and
|
||||
# actions/cache stores paths relative to the workspace. Runners that keep their own ~/.m2 skip the cache.
|
||||
- name: Place Robolectric's Android jars beside the workspace
|
||||
id: robolectric-jars
|
||||
run: |
|
||||
set -euo pipefail
|
||||
jars="$GITHUB_WORKSPACE/../robolectric-jars"
|
||||
m2="$HOME/.m2/repository/org/robolectric/android-all-instrumented"
|
||||
if [ -d "$m2" ] && [ ! -L "$m2" ]; then
|
||||
echo "cache=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
mkdir -p "$jars" "$(dirname "$m2")"
|
||||
ln -sfn "$(cd "$jars" && pwd)" "$m2"
|
||||
echo "cache=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- name: Restore Robolectric's Android jars
|
||||
id: robolectric-cache
|
||||
if: steps.robolectric-jars.outputs.cache == 'true'
|
||||
uses: actions/cache/restore@v4
|
||||
- name: Cache Robolectric's Android jars
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ../robolectric-jars
|
||||
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"
|
||||
path: ~/.m2/repository/org/robolectric/android-all-instrumented
|
||||
key: robolectric-android-all-${{ steps.robolectric.outputs.version }}
|
||||
- name: Unit tests
|
||||
id: unit-tests
|
||||
env:
|
||||
@@ -775,34 +712,6 @@ jobs:
|
||||
mkdir -p app/build
|
||||
./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
|
||||
id: unit-test-diagnostics
|
||||
if: always() && steps.unit-tests.outcome != 'skipped'
|
||||
|
||||
@@ -27,7 +27,6 @@
|
||||
|
||||
# CI
|
||||
|
||||
- Before pushing a PR, run `tools/pre_pr.sh`. It checks authorship and the merge onto `main`, then, when app sources change, compiles and runs lint as CI does. It picks tests by name: `<File>*Test` for changed Kotlin files, and `tools/tests` modules that mention a changed path. Add any other tests that cover your change, and leave the full suites to CI.
|
||||
- CI builds the PR merged onto `main`. Before pushing, merge or rebase onto `origin/main` and compile: most "works locally" Kotlin failures come from that merge.
|
||||
- Before a PR that touches strings or resources, run `./gradlew :app:lintVitalRelease`. The fast loop skips lint, and lint catches `ExtraTranslation` and missing-locale errors.
|
||||
- Commit messages and PR bodies must not carry `Co-Authored-By` or other bot trailers. `tools/release/check_authorship.py` fails the build on them.
|
||||
|
||||
@@ -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!
|
||||
|
||||
<p align="center"><b>100% open source. No ads. No Subscriptions. No telemetry. No proprietary components. No source withheld.</b></p>
|
||||
<p align="center"><b>100% open source. No ads. No telemetry. No proprietary components. No source withheld.</b></p>
|
||||
|
||||
<p align="center">
|
||||
<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://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://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>
|
||||
|
||||
@@ -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>
|
||||
</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>
|
||||
<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>
|
||||
|
||||
> 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.
|
||||
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.11/DroidDeck-0.7.11.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.1/DroidDeck-0.7.1.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.
|
||||
|
||||
Smart glasses setup is in the [support matrix](docs/smart-glasses-support.md). Release notes are in [docs/releases](docs/releases).
|
||||
@@ -57,6 +57,9 @@ 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`.
|
||||
|
||||
## Limits
|
||||
|
||||
Compatibility and performance vary by device. Desktop compositing is software rendered, and Firefox sandboxing is reduced under proot.
|
||||
|
||||
## Credits and licence
|
||||
|
||||
@@ -68,9 +71,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
|
||||
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
|
||||
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
|
||||
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), 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.
|
||||
- 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.
|
||||
- `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.
|
||||
@@ -90,7 +91,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
|
||||
<details>
|
||||
<summary><b>Stores</b></summary>
|
||||
|
||||
- Epic Games and GOG build on [Phobos](https://github.com/phobos665)'s adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl). GOG install script registry entries are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher) (GPL-3.0) reads them. GOG cloud storage requests send the Galaxy communication-service User-Agent that gogdl and [Lutris](https://github.com/lutris/lutris) (GPL-3.0) send. Deleted GOG cloud saves are recognised by the empty-gzip deletion hash gogdl and Lutris skip.
|
||||
- Epic Games and GOG build on [Phobos](https://github.com/phobos665)'s adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl). GOG install script registry entries are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher) (GPL-3.0) reads them. GOG cloud storage requests send the Galaxy communication-service User-Agent that gogdl and [Lutris](https://github.com/lutris/lutris) (GPL-3.0) send.
|
||||
- Epic's official Linux launcher preview runs through FEX. That setup is outside Epic's listed Linux support.
|
||||
- The launcher's .deb gets the WebKitGTK and GTK 3 libraries it needs from unmodified [Debian](https://www.debian.org) 13 packages, following [@zooluis](https://github.com/zooluis)'s research in [#2268](https://github.com/Droid-Deck/DroidDeck/pull/2268).
|
||||
- Battle.net is by [@kayakyakr](https://github.com/kayakyakr). It runs Blizzard's own client in Proton (downloaded from Blizzard, not included) and shows key art from the [Battle.net Shop](https://shop.battle.net). Without Steam, its games see the pad as an Xbox 360 controller via `PROTON_SPOOF_STEAMINPUT_VIDPID` in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/winebus.sys`.
|
||||
|
||||
+2
-2
@@ -132,8 +132,8 @@ android {
|
||||
applicationId "com.droiddeck.launcher"
|
||||
minSdkVersion 26
|
||||
targetSdkVersion 34
|
||||
versionCode 20
|
||||
versionName "0.7.11"
|
||||
versionCode 19
|
||||
versionName "0.7.1"
|
||||
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
|
||||
buildConfigField "String", "SOURCE_COMMIT", "\"${sourceCommit}\""
|
||||
buildConfigField "int", "PR_NUMBER", "${prNumber}"
|
||||
|
||||
@@ -61,7 +61,7 @@ internal val sampleActions: FrontEndActions = FrontEndActions(
|
||||
onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {},
|
||||
onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {},
|
||||
onFiles = {}, onLogs = {}, onOffline = {},
|
||||
onSetPhantomProcessLimit = { _, _ -> },
|
||||
onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, onSetPhantomProcessLimit = { _, _ -> },
|
||||
)
|
||||
|
||||
/** The in-game menu's actions with settled sample values; its switches do nothing. */
|
||||
|
||||
@@ -57,7 +57,10 @@
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
|
||||
<uses-feature android:name="android.hardware.vulkan.version" android:version="0x401000" android:required="true" />
|
||||
@@ -118,6 +121,14 @@
|
||||
</intent-filter>
|
||||
</activity>
|
||||
|
||||
<activity
|
||||
android:name=".BtControllerActivity"
|
||||
android:exported="false"
|
||||
android:launchMode="singleTask"
|
||||
android:resizeableActivity="true"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density|keyboard|keyboardHidden|navigation|uiMode"
|
||||
android:theme="@style/AppTheme" />
|
||||
|
||||
<activity
|
||||
android:name=".DeviceCodeActivity"
|
||||
android:exported="false"
|
||||
|
||||
@@ -58,59 +58,6 @@
|
||||
|
||||
#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__
|
||||
typedef unsigned long ioctl_request_t;
|
||||
#else
|
||||
@@ -258,11 +205,6 @@ static void controller_fork_prepare();
|
||||
static void controller_fork_parent();
|
||||
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 {
|
||||
const char *hook_dir;
|
||||
const char *udev_data_dir;
|
||||
@@ -276,10 +218,6 @@ struct FakeConfig {
|
||||
// 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.
|
||||
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 std::atomic<int> state{0};
|
||||
static __thread bool initializing __attribute__((tls_model("initial-exec")));
|
||||
@@ -495,7 +433,6 @@ void log(const char *message, ...) {
|
||||
}
|
||||
|
||||
__attribute__((constructor)) static void library_init() {
|
||||
resolve_next_symbols();
|
||||
config();
|
||||
controller_mutex();
|
||||
controller_map();
|
||||
@@ -650,7 +587,7 @@ get_fake_input_rdev(const char *event) {
|
||||
|
||||
__attribute__((visibility("hidden"))) static void load_ring_paths() {
|
||||
std::lock_guard<std::recursive_mutex> guard(controller_mutex());
|
||||
if (ring_paths_loaded || !env_ready())
|
||||
if (ring_paths_loaded)
|
||||
return;
|
||||
|
||||
const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS");
|
||||
@@ -787,7 +724,7 @@ open_fake_input_ring(const char *event, int flags) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
||||
|
||||
int fd = my_open(ring_path.c_str(), O_RDWR | (flags & (O_NONBLOCK | O_CLOEXEC)));
|
||||
if (fd < 0)
|
||||
@@ -870,25 +807,12 @@ __attribute__((visibility("hidden"))) static bool is_steam_client() {
|
||||
__attribute__((visibility("hidden"))) static bool presents_steam_virtual() {
|
||||
static int known;
|
||||
if (known == 0) {
|
||||
if (!env_ready()) return false;
|
||||
const char *enabled = getenv("FAKE_EVDEV_STEAM_VIRTUAL");
|
||||
known = enabled && atoi(enabled) && !is_steam_client() ? 1 : -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
|
||||
presents_xbox_triggers(const FakeController &fake) {
|
||||
return fake.uinput || !is_steam_client();
|
||||
@@ -1054,7 +978,7 @@ __attribute__((visibility("hidden"))) static void unpublish_uinput(UinputWriter
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static int claim_uinput_node(int *fd_out) {
|
||||
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
||||
for (int node = UINPUT_EVENT_BASE; node < UINPUT_EVENT_LIMIT; node++) {
|
||||
std::string path = uinput_ring_path(node);
|
||||
int fd = my_open(path.c_str(), O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0644);
|
||||
@@ -1081,7 +1005,7 @@ __attribute__((visibility("hidden"))) static int claim_uinput_node(int *fd_out)
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static int publish_uinput(UinputWriter &w) {
|
||||
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
||||
int fd = -1;
|
||||
int node = claim_uinput_node(&fd);
|
||||
if (node < 0) return -1;
|
||||
@@ -1467,7 +1391,6 @@ static std::unordered_map<int, std::shared_ptr<DeckHidraw>> &deck_map() {
|
||||
|
||||
static bool fake_deck_enabled() {
|
||||
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;
|
||||
return enabled == 1;
|
||||
}
|
||||
@@ -1475,7 +1398,6 @@ static bool fake_deck_enabled() {
|
||||
__attribute__((visibility("hidden"))) static uint32_t session_pad_type() {
|
||||
static int type = -1;
|
||||
if (type < 0) {
|
||||
if (!env_ready()) return PAD_TYPE_DECK;
|
||||
const char *env = getenv("FAKE_EVDEV_PAD_TYPE");
|
||||
type = env && !strcmp(env, "steamcontroller") ? PAD_TYPE_STEAM
|
||||
: env && !strcmp(env, "xbox360") ? PAD_TYPE_XBOX
|
||||
@@ -1494,7 +1416,7 @@ __attribute__((visibility("hidden"))) static const uint8_t *ring_blocks() {
|
||||
std::lock_guard<std::mutex> guard(lock);
|
||||
if ((mapped = block.load(std::memory_order_acquire))) return mapped;
|
||||
tries.fetch_add(1, std::memory_order_relaxed);
|
||||
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
||||
std::string path = get_ring_path_for_slot(0);
|
||||
int fd = path.empty() ? -1 : my_open(path.c_str(), O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return nullptr;
|
||||
@@ -1548,7 +1470,6 @@ __attribute__((visibility("hidden"))) static uint64_t monotonic_us() {
|
||||
|
||||
static bool fake_triton_enabled() {
|
||||
static int enabled = -1;
|
||||
if (enabled < 0 && !env_ready()) return false;
|
||||
if (enabled < 0)
|
||||
enabled = fake_deck_enabled() && getenv("FAKE_EVDEV_TRITON") && atoi(getenv("FAKE_EVDEV_TRITON")) ? 1 : 0;
|
||||
return enabled == 1;
|
||||
@@ -1847,7 +1768,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) {
|
||||
const char *path = sony == 4 ? DS4_HIDRAW_PATH : sony == 5 ? DUALSENSE_HIDRAW_PATH : DECK_HIDRAW_PATH;
|
||||
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
||||
if (!process_reads_pads()) {
|
||||
Logger::log("deck: %s refused: not the Steam client\n", path);
|
||||
errno = ENOENT;
|
||||
@@ -2056,7 +1977,7 @@ __attribute__((visibility("hidden"))) static void *triton_pad_thread(void *arg)
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) static int open_triton_hidraw(int flags, bool emulated) {
|
||||
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
||||
if (!process_reads_pads()) {
|
||||
errno = ENOENT;
|
||||
return -1;
|
||||
@@ -2170,12 +2091,11 @@ static_assert(sizeof(TouchRingFile) <= TOUCH_RING_SIZE, "TouchRingFile layout");
|
||||
|
||||
__attribute__((visibility("hidden"))) static TouchRingFile *touch_ring() {
|
||||
static TouchRingFile *ring = nullptr;
|
||||
if (!env_ready()) return nullptr;
|
||||
static std::once_flag once;
|
||||
std::call_once(once, [] {
|
||||
const char *path = getenv("FAKE_TOUCHCTL_RING");
|
||||
if (!path || !*path || !fake_deck_enabled()) return;
|
||||
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
||||
int fd = my_open(path, O_RDWR | O_CLOEXEC);
|
||||
if (fd < 0) {
|
||||
Logger::log("touch: %s not openable (%s)\n", path, strerror(errno));
|
||||
@@ -2392,8 +2312,7 @@ __attribute__((visibility("hidden"))) static int inject_uevent(const char *actio
|
||||
const char *subsystem, const char *devname,
|
||||
unsigned major, unsigned minor) {
|
||||
using inject_fn = int (*)(const char *, const char *, const char *, const char *, unsigned, unsigned);
|
||||
static SymbolSlot inject_slot;
|
||||
const auto inject = resolved_symbol<inject_fn>(inject_slot, RTLD_DEFAULT, "dd_udevmon_inject");
|
||||
static auto inject = reinterpret_cast<inject_fn>(dlsym(RTLD_DEFAULT, "dd_udevmon_inject"));
|
||||
return inject ? inject(action, devpath, subsystem, devname, major, minor) : -1;
|
||||
}
|
||||
|
||||
@@ -2515,7 +2434,6 @@ __attribute__((constructor)) static void start_touch_controller() {
|
||||
static constexpr long SYSFS_FS_MAGIC = 0x62656572;
|
||||
|
||||
__attribute__((visibility("hidden"))) static const char *deck_listing_dir() {
|
||||
if (!env_ready()) return nullptr;
|
||||
static const char *dir = getenv("FAKE_DECK_SYSFS_LISTING");
|
||||
return dir && *dir ? dir : nullptr;
|
||||
}
|
||||
@@ -2551,7 +2469,7 @@ __attribute__((visibility("hidden"))) static void note_deck_sysfs(const char *ho
|
||||
}
|
||||
|
||||
EXPORT int fstatfs(int fd, struct statfs *buf) {
|
||||
const auto real = next_symbol<int (*)(int, struct statfs *)>(Next::fstatfs);
|
||||
static auto real = reinterpret_cast<int (*)(int, struct statfs *)>(dlsym(RTLD_NEXT, "fstatfs"));
|
||||
int result = real(fd, buf);
|
||||
if (fake_deck_enabled() && is_deck_sysfs_fd(fd)) {
|
||||
note_deck_sysfs("fstatfs", result);
|
||||
@@ -2561,7 +2479,7 @@ EXPORT int fstatfs(int fd, struct statfs *buf) {
|
||||
}
|
||||
|
||||
EXPORT int statfs(const char *path, struct statfs *buf) {
|
||||
const auto real = next_symbol<int (*)(const char *, struct statfs *)>(Next::statfs);
|
||||
static auto real = reinterpret_cast<int (*)(const char *, struct statfs *)>(dlsym(RTLD_NEXT, "statfs"));
|
||||
int result = real(path, buf);
|
||||
if (fake_deck_enabled() && is_deck_sysfs_path(path)) {
|
||||
note_deck_sysfs(path, result);
|
||||
@@ -2610,7 +2528,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) {
|
||||
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
||||
if (deck.mapping_size < FAKE_INPUT_RING_SIZE + DECK_IMU_BLOCK_SIZE) return;
|
||||
std::string path = get_ring_path_for_slot(0);
|
||||
int fd = path.empty() ? -1 : my_open(path.c_str(), O_WRONLY | O_CLOEXEC);
|
||||
@@ -3119,7 +3037,7 @@ static int real_fstat(int fd, struct stat *buf);
|
||||
|
||||
__attribute__((visibility("hidden"))) static bool deck_mount_id_from_fdinfo(
|
||||
int dirfd, const char *path, int flags, struct statx *buf) {
|
||||
const auto real_openat = next_symbol<decltype(&::openat)>(Next::openat);
|
||||
static auto real_openat = reinterpret_cast<decltype(&::openat)>(dlsym(RTLD_NEXT, "openat"));
|
||||
int target;
|
||||
if (!path || !*path) {
|
||||
if (!(flags & AT_EMPTY_PATH)) return false;
|
||||
@@ -3157,7 +3075,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) {
|
||||
const auto real = next_symbol<decltype(&::statx)>(Next::statx);
|
||||
static auto real = reinterpret_cast<decltype(&::statx)>(dlsym(RTLD_NEXT, "statx"));
|
||||
int result = real(dirfd, path, flags, mask, buf);
|
||||
int saved_errno = errno;
|
||||
constexpr unsigned unique_mount_id = 0x4000;
|
||||
@@ -3178,7 +3096,7 @@ EXPORT int statx(int dirfd, const char *path, int flags, unsigned mask, struct s
|
||||
#endif
|
||||
|
||||
EXPORT DIR *opendir(const char *name) {
|
||||
const auto real = next_symbol<DIR *(*)(const char *)>(Next::opendir);
|
||||
static auto real = reinterpret_cast<DIR *(*)(const char *)>(dlsym(RTLD_NEXT, "opendir"));
|
||||
DIR *dir = real(name);
|
||||
if (!dir) {
|
||||
note_sys_failure(AT_FDCWD, name);
|
||||
@@ -3208,7 +3126,7 @@ EXPORT int open(const char *pathname, int flags, ...) {
|
||||
|
||||
va_end(va);
|
||||
|
||||
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
|
||||
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
|
||||
|
||||
if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags);
|
||||
if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags);
|
||||
@@ -3286,7 +3204,7 @@ EXPORT int openat(int dirfd, const char *pathname, int flags, ...) {
|
||||
|
||||
va_end(va);
|
||||
|
||||
const auto my_openat = next_symbol<int (*)(int, const char *, int, ...)>(Next::openat);
|
||||
static auto my_openat = reinterpret_cast<int (*)(int, const char *, int, ...)>(dlsym(RTLD_NEXT, "openat"));
|
||||
|
||||
if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags);
|
||||
if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags);
|
||||
@@ -3445,10 +3363,10 @@ static int fake_stat_fd(int fd, S *buf, Real real) {
|
||||
}
|
||||
|
||||
static int real_stat(const char *pathname, struct stat *statbuf) {
|
||||
const auto fn = next_symbol<int (*)(const char *, struct stat *)>(Next::stat);
|
||||
static auto fn = reinterpret_cast<int (*)(const char *, struct stat *)>(dlsym(RTLD_NEXT, "stat"));
|
||||
if (fn) return fn(pathname, statbuf);
|
||||
#ifdef _STAT_VER
|
||||
const auto xfn = next_symbol<int (*)(int, const char *, struct stat *)>(Next::xstat);
|
||||
static auto xfn = reinterpret_cast<int (*)(int, const char *, struct stat *)>(dlsym(RTLD_NEXT, "__xstat"));
|
||||
if (xfn) return xfn(_STAT_VER, pathname, statbuf);
|
||||
#endif
|
||||
errno = ENOSYS;
|
||||
@@ -3456,10 +3374,10 @@ static int real_stat(const char *pathname, struct stat *statbuf) {
|
||||
}
|
||||
|
||||
static int real_fstat(int fd, struct stat *buf) {
|
||||
const auto fn = next_symbol<int (*)(int, struct stat *)>(Next::fstat);
|
||||
static auto fn = reinterpret_cast<int (*)(int, struct stat *)>(dlsym(RTLD_NEXT, "fstat"));
|
||||
if (fn) return fn(fd, buf);
|
||||
#ifdef _STAT_VER
|
||||
const auto xfn = next_symbol<int (*)(int, int, struct stat *)>(Next::fxstat);
|
||||
static auto xfn = reinterpret_cast<int (*)(int, int, struct stat *)>(dlsym(RTLD_NEXT, "__fxstat"));
|
||||
if (xfn) return xfn(_STAT_VER, fd, buf);
|
||||
#endif
|
||||
errno = ENOSYS;
|
||||
@@ -3475,7 +3393,7 @@ EXPORT int fstat(int fd, struct stat *buf) {
|
||||
}
|
||||
|
||||
EXPORT int access(const char *pathname, int mode) {
|
||||
const auto my_access = next_symbol<decltype(&::access)>(Next::access);
|
||||
static auto my_access = reinterpret_cast<decltype(&::access)>(dlsym(RTLD_NEXT, "access"));
|
||||
if (fake_uinput_enabled() && is_uinput_path(pathname)) 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)) &&
|
||||
@@ -3516,7 +3434,7 @@ EXPORT int access(const char *pathname, int mode) {
|
||||
}
|
||||
|
||||
EXPORT int faccessat(int dirfd, const char *pathname, int mode, int flags) {
|
||||
const auto my_faccessat = next_symbol<decltype(&::faccessat)>(Next::faccessat);
|
||||
static auto my_faccessat = reinterpret_cast<decltype(&::faccessat)>(dlsym(RTLD_NEXT, "faccessat"));
|
||||
if (fake_uinput_enabled() && is_uinput_path(pathname)) 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)) &&
|
||||
@@ -3560,7 +3478,7 @@ EXPORT int scandir(const char *dirp, struct dirent ***namelist,
|
||||
int (*filter)(const struct dirent *),
|
||||
int (*compar)(const struct dirent **,
|
||||
const struct dirent **)) {
|
||||
const auto my_scandir = next_symbol<decltype(&::scandir)>(Next::scandir);
|
||||
static auto my_scandir = reinterpret_cast<decltype(&::scandir)>(dlsym(RTLD_NEXT, "scandir"));
|
||||
|
||||
if (dirp) {
|
||||
if (!strcmp(dirp, "/dev/input")) {
|
||||
@@ -3574,7 +3492,7 @@ EXPORT int scandir(const char *dirp, struct dirent ***namelist,
|
||||
}
|
||||
|
||||
EXPORT int inotify_add_watch(int fd, const char *pathname, uint32_t mask) {
|
||||
const auto my_inotify_add_watch = next_symbol<decltype(&::inotify_add_watch)>(Next::inotify_add_watch);
|
||||
static auto my_inotify_add_watch = reinterpret_cast<decltype(&::inotify_add_watch)>(dlsym(RTLD_NEXT, "inotify_add_watch"));
|
||||
|
||||
char *fake_path = nullptr;
|
||||
if (pathname) {
|
||||
@@ -3713,7 +3631,7 @@ static bool wait_snapshot(std::shared_ptr<FakeController> fake,
|
||||
|
||||
static int forward_ioctl(int fd, ioctl_request_t op, void *argp) {
|
||||
using ioctl_fn = int (*)(int, ioctl_request_t, ...);
|
||||
const auto next = next_symbol<ioctl_fn>(Next::ioctl);
|
||||
static const auto next = reinterpret_cast<ioctl_fn>(dlsym(RTLD_NEXT, "ioctl"));
|
||||
return next ? next(fd, op, argp) : static_cast<int>(syscall(SYS_ioctl, fd, op, argp));
|
||||
}
|
||||
|
||||
@@ -3771,10 +3689,6 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
|
||||
id.bustype = 0x03;
|
||||
if (made) {
|
||||
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()) {
|
||||
id.vendor = STEAM_VIRTUAL_VENDOR_ID;
|
||||
id.product = STEAM_VIRTUAL_PRODUCT_ID;
|
||||
@@ -3952,7 +3866,7 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
|
||||
}
|
||||
|
||||
EXPORT int close(int fd) {
|
||||
const auto my_close = next_symbol<decltype(&::close)>(Next::close);
|
||||
static auto my_close = reinterpret_cast<decltype(&::close)>(dlsym(RTLD_NEXT, "close"));
|
||||
|
||||
if (!watched(fd)) return my_close(fd);
|
||||
close_uinput(fd);
|
||||
@@ -4140,7 +4054,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) {
|
||||
const auto my_write = next_symbol<decltype(&::write)>(Next::write);
|
||||
static auto my_write = reinterpret_cast<decltype(&::write)>(dlsym(RTLD_NEXT, "write"));
|
||||
|
||||
if (!watched(fd)) return my_write(fd, buf, count);
|
||||
std::unique_lock<std::recursive_mutex> guard(controller_mutex());
|
||||
@@ -4215,8 +4129,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,
|
||||
const sigset_t *sigmask) {
|
||||
const auto my_poll = next_symbol<decltype(&::poll)>(Next::poll);
|
||||
const auto my_ppoll = next_symbol<decltype(&::ppoll)>(Next::ppoll);
|
||||
static auto my_poll = reinterpret_cast<decltype(&::poll)>(dlsym(RTLD_NEXT, "poll"));
|
||||
static auto my_ppoll = reinterpret_cast<decltype(&::ppoll)>(dlsym(RTLD_NEXT, "ppoll"));
|
||||
|
||||
nfds_t first = 0;
|
||||
while (first < nfds && !watched(fds[first].fd)) first++;
|
||||
@@ -4320,7 +4234,7 @@ EXPORT int poll(struct pollfd *fds, nfds_t nfds, int timeout) {
|
||||
|
||||
EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
|
||||
const struct timespec *timeout, const sigset_t *sigmask) {
|
||||
const auto my_ppoll = next_symbol<decltype(&::ppoll)>(Next::ppoll);
|
||||
static auto my_ppoll = reinterpret_cast<decltype(&::ppoll)>(dlsym(RTLD_NEXT, "ppoll"));
|
||||
if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) {
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
@@ -4347,7 +4261,7 @@ EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
|
||||
|
||||
EXPORT int select(int nfds, fd_set *readfds, fd_set *writefds,
|
||||
fd_set *exceptfds, struct timeval *timeout) {
|
||||
const auto my_select = next_symbol<decltype(&::select)>(Next::select);
|
||||
static auto my_select = reinterpret_cast<decltype(&::select)>(dlsym(RTLD_NEXT, "select"));
|
||||
|
||||
fd_set original_readfds;
|
||||
fd_set original_writefds;
|
||||
@@ -4509,10 +4423,10 @@ EXPORT int openat64(int dirfd, const char *pathname, int flags, ...) {
|
||||
}
|
||||
|
||||
static int real_stat64(const char *pathname, struct stat64 *statbuf) {
|
||||
const auto fn = next_symbol<int (*)(const char *, struct stat64 *)>(Next::stat64);
|
||||
static auto fn = reinterpret_cast<int (*)(const char *, struct stat64 *)>(dlsym(RTLD_NEXT, "stat64"));
|
||||
if (fn) return fn(pathname, statbuf);
|
||||
#ifdef _STAT_VER
|
||||
const auto xfn = next_symbol<int (*)(int, const char *, struct stat64 *)>(Next::xstat64);
|
||||
static auto xfn = reinterpret_cast<int (*)(int, const char *, struct stat64 *)>(dlsym(RTLD_NEXT, "__xstat64"));
|
||||
if (xfn) return xfn(_STAT_VER, pathname, statbuf);
|
||||
#endif
|
||||
errno = ENOSYS;
|
||||
@@ -4520,10 +4434,10 @@ static int real_stat64(const char *pathname, struct stat64 *statbuf) {
|
||||
}
|
||||
|
||||
static int real_fstat64(int fd, struct stat64 *buf) {
|
||||
const auto fn = next_symbol<int (*)(int, struct stat64 *)>(Next::fstat64);
|
||||
static auto fn = reinterpret_cast<int (*)(int, struct stat64 *)>(dlsym(RTLD_NEXT, "fstat64"));
|
||||
if (fn) return fn(fd, buf);
|
||||
#ifdef _STAT_VER
|
||||
const auto xfn = next_symbol<int (*)(int, int, struct stat64 *)>(Next::fxstat64);
|
||||
static auto xfn = reinterpret_cast<int (*)(int, int, struct stat64 *)>(dlsym(RTLD_NEXT, "__fxstat64"));
|
||||
if (xfn) return xfn(_STAT_VER, fd, buf);
|
||||
#endif
|
||||
errno = ENOSYS;
|
||||
@@ -4539,27 +4453,27 @@ EXPORT int fstat64(int fd, struct stat64 *buf) {
|
||||
}
|
||||
|
||||
EXPORT int __xstat(int version, const char *pathname, struct stat *statbuf) {
|
||||
const auto real = next_symbol<int (*)(int, const char *, struct stat *)>(Next::xstat);
|
||||
static auto real = reinterpret_cast<int (*)(int, const char *, struct stat *)>(dlsym(RTLD_NEXT, "__xstat"));
|
||||
if (!real) return stat(pathname, statbuf);
|
||||
return fake_stat_path(pathname, statbuf, [version, real](const char *path, struct stat *buf) { return real(version, path, buf); });
|
||||
return fake_stat_path(pathname, statbuf, [version](const char *path, struct stat *buf) { return real(version, path, buf); });
|
||||
}
|
||||
|
||||
EXPORT int __xstat64(int version, const char *pathname, struct stat64 *statbuf) {
|
||||
const auto real = next_symbol<int (*)(int, const char *, struct stat64 *)>(Next::xstat64);
|
||||
static auto real = reinterpret_cast<int (*)(int, const char *, struct stat64 *)>(dlsym(RTLD_NEXT, "__xstat64"));
|
||||
if (!real) return stat64(pathname, statbuf);
|
||||
return fake_stat_path(pathname, statbuf, [version, real](const char *path, struct stat64 *buf) { return real(version, path, buf); });
|
||||
return fake_stat_path(pathname, statbuf, [version](const char *path, struct stat64 *buf) { return real(version, path, buf); });
|
||||
}
|
||||
|
||||
EXPORT int __fxstat(int version, int fd, struct stat *buf) {
|
||||
const auto real = next_symbol<int (*)(int, int, struct stat *)>(Next::fxstat);
|
||||
static auto real = reinterpret_cast<int (*)(int, int, struct stat *)>(dlsym(RTLD_NEXT, "__fxstat"));
|
||||
if (!real) return fstat(fd, buf);
|
||||
return fake_stat_fd(fd, buf, [version, real](int f, struct stat *b) { return real(version, f, b); });
|
||||
return fake_stat_fd(fd, buf, [version](int f, struct stat *b) { return real(version, f, b); });
|
||||
}
|
||||
|
||||
EXPORT int __fxstat64(int version, int fd, struct stat64 *buf) {
|
||||
const auto real = next_symbol<int (*)(int, int, struct stat64 *)>(Next::fxstat64);
|
||||
static auto real = reinterpret_cast<int (*)(int, int, struct stat64 *)>(dlsym(RTLD_NEXT, "__fxstat64"));
|
||||
if (!real) return fstat64(fd, buf);
|
||||
return fake_stat_fd(fd, buf, [version, real](int f, struct stat64 *b) { return real(version, f, b); });
|
||||
return fake_stat_fd(fd, buf, [version](int f, struct stat64 *b) { return real(version, f, b); });
|
||||
}
|
||||
|
||||
#if defined(__x86_64__) || defined(__i386__)
|
||||
@@ -4573,37 +4487,18 @@ static const char *const interposed_names[] = {
|
||||
};
|
||||
|
||||
static dlsym_fn next_dlsym() {
|
||||
static std::atomic<dlsym_fn> fn{nullptr};
|
||||
static std::atomic<bool> resolved{false};
|
||||
if (!resolved.load(std::memory_order_acquire)) {
|
||||
static const dlsym_fn fn = [] {
|
||||
#ifdef __x86_64__
|
||||
const char *base = "GLIBC_2.2.5";
|
||||
#else
|
||||
const char *base = "GLIBC_2.0";
|
||||
#endif
|
||||
dlsym_fn found{};
|
||||
for (const char *version : {base, "GLIBC_2.34"}) {
|
||||
if ((found = reinterpret_cast<dlsym_fn>(dlvsym(RTLD_NEXT, "dlsym", version)))) break;
|
||||
if (auto found = reinterpret_cast<dlsym_fn>(dlvsym(RTLD_NEXT, "dlsym", version))) return found;
|
||||
}
|
||||
fn.store(found, std::memory_order_relaxed);
|
||||
resolved.store(true, std::memory_order_release);
|
||||
}
|
||||
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();
|
||||
return dlsym_fn{};
|
||||
}();
|
||||
return fn;
|
||||
}
|
||||
|
||||
static void *global_dlsym(void *, const char *name) { return next_dlsym()(RTLD_DEFAULT, name); }
|
||||
@@ -4621,7 +4516,8 @@ extern "C" __attribute__((visibility("hidden"), used)) void *fakeinput_dlsym_tar
|
||||
dlsym_fn next = next_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 != libc_handle() || !interposed(name)) return reinterpret_cast<void *>(next);
|
||||
static void *const libc = dlopen(LIBC_SO, RTLD_LAZY | RTLD_NOLOAD);
|
||||
if (handle != libc || !interposed(name)) return reinterpret_cast<void *>(next);
|
||||
return reinterpret_cast<void *>(global_dlsym);
|
||||
}
|
||||
|
||||
|
||||
@@ -620,8 +620,7 @@ static void cursor_publish_shown(void) {
|
||||
|
||||
static void cursor_publish_hidden(void) {
|
||||
pthread_mutex_lock(&g_cursor_lock);
|
||||
// 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++; }
|
||||
if (!g_cursor_hidden) { g_cursor_hidden = 1; g_cursor_serial++; }
|
||||
pthread_mutex_unlock(&g_cursor_lock);
|
||||
}
|
||||
|
||||
@@ -738,11 +737,6 @@ static void describe(const struct surface *s, char *out, size_t size) {
|
||||
else snprintf(out, size, "window %#x (%s)", w->hwnd, prog);
|
||||
}
|
||||
|
||||
static int is_steam_client_surface(const struct surface *s) {
|
||||
const char *name = client_name(wl_resource_get_client(s->resource));
|
||||
return strcmp(name, "steam") == 0 || strstr(name, "steamwebhelper") != NULL;
|
||||
}
|
||||
|
||||
static struct surface *toplevel_by_hwnd(uint32_t hwnd) {
|
||||
struct surface *s;
|
||||
wl_list_for_each(s, &g_toplevels, toplevel_link)
|
||||
@@ -900,7 +894,6 @@ int droiddeck_hud_frame_times(float *out, int len, int64_t *total) {
|
||||
static uint64_t g_game_frames;
|
||||
extern void droiddeck_on_game_surface(const char *window, const char *gpu);
|
||||
extern void droiddeck_on_game_frame(void);
|
||||
extern void droiddeck_on_compositor_frame(void);
|
||||
extern void droiddeck_on_content_rate(int fps);
|
||||
static int64_t g_cadence_ns;
|
||||
static int64_t g_cadence_frames;
|
||||
@@ -956,10 +949,9 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
|
||||
g_hud_shm = s;
|
||||
g_hud_shm_ns = now;
|
||||
g_hud_new = 1;
|
||||
droiddeck_on_game_frame();
|
||||
}
|
||||
}
|
||||
if (s == g_hud_shm && (!g_hud_surface || now_ns() - g_hud_last_ns > 1000000000LL))
|
||||
droiddeck_on_compositor_frame();
|
||||
}
|
||||
|
||||
static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resource *buffer) {
|
||||
@@ -1033,8 +1025,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
||||
droiddeck_log("error", "could not import GPU frames from %s (%dx%d, modifier %#llx)",
|
||||
name, b->width, b->height, (unsigned long long)b->modifier);
|
||||
}
|
||||
if (s != g_hud_surface && !is_steam_client_surface(s) &&
|
||||
(b->img || ahb_swapchain_has_ahb(b)) &&
|
||||
if (s != g_hud_surface && (b->img || ahb_swapchain_has_ahb(b)) &&
|
||||
(!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL || (!repeat && below_surface(s, g_hud_surface)) ||
|
||||
(announced_now && !below_surface(g_hud_surface, s) &&
|
||||
(int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) {
|
||||
@@ -1059,12 +1050,9 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
||||
: "the compositor's driver could NOT import it (nothing can show it)");
|
||||
s->hdr_fmt_logged = b->format;
|
||||
}
|
||||
if (s == g_hud_surface && !is_steam_client_surface(s)) {
|
||||
if (s == g_hud_surface) {
|
||||
g_hud_alive_ns = now_ns();
|
||||
if (!repeat) { g_hud_last_ns = g_hud_alive_ns; g_hud_fresh = 1; g_hud_new = 1; g_game_frames++; note_game_frame_gap(); droiddeck_on_game_frame(); }
|
||||
} else if (is_steam_client_surface(s) && !repeat &&
|
||||
(!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL)) {
|
||||
droiddeck_on_compositor_frame();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -163,7 +163,6 @@ struct layer {
|
||||
ARect geo_src, geo_dst;
|
||||
int geo_valid;
|
||||
int alloc_tier;
|
||||
unsigned import_failed_fmts;
|
||||
uint64_t pool_modifier;
|
||||
int first_logged;
|
||||
int64_t drop_logged_ns;
|
||||
@@ -488,8 +487,7 @@ static const char *tier_name(int tier) {
|
||||
|
||||
static int alloc_slot(struct layer *l, struct slot *s, int w, int h, uint32_t fmt) {
|
||||
g_alloc_failed = 0;
|
||||
const unsigned fmt_bit = fmt == AHB_RGB10A2 ? 2u : 1u;
|
||||
while (l->alloc_tier <= TIER_LINEAR && !(l->import_failed_fmts & fmt_bit)) {
|
||||
while (l->alloc_tier <= TIER_LINEAR) {
|
||||
const int tier = l->alloc_tier;
|
||||
AHardwareBuffer_Desc d = {
|
||||
.width = (uint32_t)w, .height = (uint32_t)h, .layers = 1,
|
||||
@@ -562,7 +560,6 @@ 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);
|
||||
AHardwareBuffer_release(ahb);
|
||||
if (tier < TIER_LINEAR) { l->alloc_tier = tier + 1; continue; }
|
||||
l->import_failed_fmts |= fmt_bit;
|
||||
g_alloc_failed = 1;
|
||||
return -1;
|
||||
}
|
||||
|
||||
@@ -1494,7 +1494,7 @@ struct vkp_image *vkp_image_from_ahb(AHardwareBuffer *ahb) {
|
||||
}
|
||||
|
||||
int vkp_can_import_ahb(void) {
|
||||
return dev_init() == 0 && g_vendor_id != VKP_VENDOR_QUALCOMM && !g_library_name && g_ahb_import &&
|
||||
return dev_init() == 0 && g_vendor_id != VKP_VENDOR_QUALCOMM && g_ahb_import &&
|
||||
g_vk.GetAndroidHardwareBufferPropertiesANDROID;
|
||||
}
|
||||
|
||||
|
||||
@@ -63,7 +63,6 @@ static jclass g_compositor_cls;
|
||||
static jmethodID g_on_first_frame;
|
||||
static jmethodID g_on_game_surface;
|
||||
static jmethodID g_on_game_frame;
|
||||
static jmethodID g_on_compositor_frame;
|
||||
static jmethodID g_on_game_program;
|
||||
static jmethodID g_on_pointer_lock;
|
||||
static jmethodID g_on_clipboard;
|
||||
@@ -85,7 +84,6 @@ JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
|
||||
g_on_game_surface = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameSurface",
|
||||
"(Ljava/lang/String;Ljava/lang/String;)V");
|
||||
g_on_game_frame = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameFrame", "()V");
|
||||
g_on_compositor_frame = (*env)->GetStaticMethodID(env, g_compositor_cls, "onCompositorFrame", "()V");
|
||||
g_on_game_program = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameProgram",
|
||||
"(ILjava/lang/String;)V");
|
||||
if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); g_on_game_program = NULL; }
|
||||
@@ -156,13 +154,6 @@ void droiddeck_on_game_frame(void) {
|
||||
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
|
||||
}
|
||||
|
||||
void droiddeck_on_compositor_frame(void) {
|
||||
JNIEnv *env;
|
||||
if (!g_compositor_cls || !g_on_compositor_frame || !(env = thread_env())) return;
|
||||
(*env)->CallStaticVoidMethod(env, g_compositor_cls, g_on_compositor_frame);
|
||||
if ((*env)->ExceptionCheck(env)) (*env)->ExceptionClear(env);
|
||||
}
|
||||
|
||||
void droiddeck_on_refresh_target(int refresh, int frame_rate) {
|
||||
JNIEnv *env;
|
||||
if (!g_compositor_cls || !g_on_refresh_target || !(env = thread_env())) return;
|
||||
|
||||
@@ -0,0 +1,589 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import android.view.InputDevice
|
||||
import android.view.KeyEvent
|
||||
import android.view.MotionEvent
|
||||
import android.view.WindowManager
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.clickable
|
||||
import androidx.compose.foundation.gestures.awaitEachGesture
|
||||
import androidx.compose.foundation.gestures.awaitFirstDown
|
||||
import androidx.compose.foundation.gestures.waitForUpOrCancellation
|
||||
import androidx.compose.foundation.horizontalScroll
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.Spacer
|
||||
import androidx.compose.foundation.layout.fillMaxHeight
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.offset
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.LaunchedEffect
|
||||
import androidx.compose.runtime.collectAsState
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.draw.clip
|
||||
import androidx.compose.ui.geometry.Offset
|
||||
import androidx.compose.ui.graphics.Color
|
||||
import androidx.compose.ui.input.pointer.pointerInput
|
||||
import androidx.compose.ui.platform.LocalDensity
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.style.TextOverflow
|
||||
import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.IntOffset
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.core.AppLanguage
|
||||
import com.droiddeck.launcher.input.bt.BtGamepad
|
||||
import com.droiddeck.launcher.input.bt.BtPadProfile
|
||||
import com.droiddeck.launcher.input.bt.BtPadState
|
||||
import com.droiddeck.launcher.ui.DroidDeckTheme
|
||||
import com.droiddeck.launcher.ui.LocalPalette
|
||||
import com.droiddeck.launcher.ui.PrimaryButton
|
||||
import com.droiddeck.launcher.ui.SecondaryButton
|
||||
import kotlin.math.hypot
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class BtControllerActivity : ComponentActivity() {
|
||||
private val physical = BtPadState()
|
||||
private val touch = BtPadState()
|
||||
private val merged = BtPadState()
|
||||
private var keyButtons = 0
|
||||
private var hatButtons = 0
|
||||
private var touchEpoch by mutableStateOf(0)
|
||||
private val main = Handler(Looper.getMainLooper())
|
||||
private val exitHold = Runnable { finish() }
|
||||
private var exitArmed = false
|
||||
private var profile by mutableStateOf(BtPadProfile.GENERIC)
|
||||
private var showTouch by mutableStateOf(true)
|
||||
private var permissionDenied by mutableStateOf(false)
|
||||
private var locationDenied by mutableStateOf(false)
|
||||
|
||||
override fun attachBaseContext(newBase: Context) = super.attachBaseContext(AppLanguage.wrap(newBase))
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||
val prefs = prefs(this)
|
||||
profile = BtPadProfile.byId(prefs.getString(KEY_PROFILE, null))
|
||||
showTouch = prefs.getBoolean(KEY_TOUCH, true)
|
||||
val wanted = if (Build.VERSION.SDK_INT >= 31) NEARBY + LOCATION else LOCATION
|
||||
val missing = wanted.filter { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
|
||||
if (missing.isEmpty()) startPad() else requestPermissions(missing.toTypedArray(), REQUEST_NEARBY)
|
||||
setContent { DroidDeckTheme { Screen() } }
|
||||
}
|
||||
|
||||
private fun openAppInfo() {
|
||||
runCatching {
|
||||
startActivity(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, android.net.Uri.fromParts("package", packageName, null)))
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
locationDenied = LOCATION.any { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
|
||||
if (permissionDenied && Build.VERSION.SDK_INT >= 31 && NEARBY.all { checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED }) {
|
||||
permissionDenied = false
|
||||
startPad()
|
||||
}
|
||||
}
|
||||
|
||||
private fun startPad() {
|
||||
BtGamepad.start(this, profile)
|
||||
BtGamepad.openPairingWindow()
|
||||
}
|
||||
|
||||
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
|
||||
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
|
||||
if (requestCode != REQUEST_NEARBY) return
|
||||
val nearbyDenied = Build.VERSION.SDK_INT >= 31 && NEARBY.any { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
|
||||
permissionDenied = nearbyDenied
|
||||
locationDenied = LOCATION.any { checkSelfPermission(it) != PackageManager.PERMISSION_GRANTED }
|
||||
if (!nearbyDenied) startPad()
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
if (hasFocus) return
|
||||
physical.set(BtPadState())
|
||||
touch.set(BtPadState())
|
||||
touchEpoch++
|
||||
keyButtons = 0
|
||||
hatButtons = 0
|
||||
push()
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
main.removeCallbacks(exitHold)
|
||||
if (isFinishing) BtGamepad.stop()
|
||||
super.onDestroy()
|
||||
}
|
||||
|
||||
private fun pickProfile(p: BtPadProfile) {
|
||||
if (p == profile) return
|
||||
profile = p
|
||||
prefs(this).edit().putString(KEY_PROFILE, p.id).apply()
|
||||
BtGamepad.switchProfile(p)
|
||||
}
|
||||
|
||||
private fun push() {
|
||||
physical.buttons = keyButtons or hatButtons
|
||||
merged.merge(physical, touch)
|
||||
BtGamepad.update(merged)
|
||||
val combo = BtPadState.SELECT or BtPadState.START
|
||||
val held = physical.buttons and combo == combo
|
||||
if (held && !exitArmed) main.postDelayed(exitHold, EXIT_HOLD_MS)
|
||||
else if (!held && exitArmed) main.removeCallbacks(exitHold)
|
||||
exitArmed = held
|
||||
}
|
||||
|
||||
private fun isPad(event: KeyEvent): Boolean {
|
||||
val s = event.source
|
||||
return s and InputDevice.SOURCE_GAMEPAD == InputDevice.SOURCE_GAMEPAD ||
|
||||
s and InputDevice.SOURCE_JOYSTICK == InputDevice.SOURCE_JOYSTICK ||
|
||||
KeyEvent.isGamepadButton(event.keyCode)
|
||||
}
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
val bit = KEYS[event.keyCode]
|
||||
if (bit == null || event.keyCode in DPAD_KEYS && !isPad(event) && event.source and InputDevice.SOURCE_DPAD != InputDevice.SOURCE_DPAD) {
|
||||
return super.dispatchKeyEvent(event)
|
||||
}
|
||||
when (event.action) {
|
||||
KeyEvent.ACTION_DOWN -> keyButtons = keyButtons or bit
|
||||
KeyEvent.ACTION_UP -> keyButtons = keyButtons and bit.inv()
|
||||
}
|
||||
push()
|
||||
return true
|
||||
}
|
||||
|
||||
override fun dispatchGenericMotionEvent(event: MotionEvent): Boolean {
|
||||
if (event.source and InputDevice.SOURCE_JOYSTICK != InputDevice.SOURCE_JOYSTICK || event.action != MotionEvent.ACTION_MOVE) {
|
||||
return super.dispatchGenericMotionEvent(event)
|
||||
}
|
||||
val device = event.device
|
||||
fun axis(code: Int): Float {
|
||||
val range = device?.getMotionRange(code, event.source) ?: return 0f
|
||||
val v = event.getAxisValue(code)
|
||||
return if (Math.abs(v) > maxOf(range.flat, 0.04f)) v else 0f
|
||||
}
|
||||
val hasZ = device?.getMotionRange(MotionEvent.AXIS_Z, event.source) != null
|
||||
physical.lx = axis(MotionEvent.AXIS_X); physical.ly = axis(MotionEvent.AXIS_Y)
|
||||
physical.rx = axis(if (hasZ) MotionEvent.AXIS_Z else MotionEvent.AXIS_RX)
|
||||
physical.ry = axis(if (hasZ) MotionEvent.AXIS_RZ else MotionEvent.AXIS_RY)
|
||||
physical.lt = maxOf(axis(MotionEvent.AXIS_LTRIGGER), axis(MotionEvent.AXIS_BRAKE))
|
||||
physical.rt = maxOf(axis(MotionEvent.AXIS_RTRIGGER), axis(MotionEvent.AXIS_GAS))
|
||||
val hx = event.getAxisValue(MotionEvent.AXIS_HAT_X)
|
||||
val hy = event.getAxisValue(MotionEvent.AXIS_HAT_Y)
|
||||
hatButtons = (if (hy < -0.5f) BtPadState.UP else 0) or (if (hy > 0.5f) BtPadState.DOWN else 0) or
|
||||
(if (hx < -0.5f) BtPadState.LEFT else 0) or (if (hx > 0.5f) BtPadState.RIGHT else 0)
|
||||
push()
|
||||
return true
|
||||
}
|
||||
|
||||
private fun touchButton(bit: Int, down: Boolean) {
|
||||
touch.buttons = if (down) touch.buttons or bit else touch.buttons and bit.inv()
|
||||
if (bit == BtPadState.LT) touch.lt = if (down) 1f else 0f
|
||||
if (bit == BtPadState.RT) touch.rt = if (down) 1f else 0f
|
||||
push()
|
||||
}
|
||||
|
||||
private fun touchStick(left: Boolean, x: Float, y: Float) {
|
||||
if (left) { touch.lx = x; touch.ly = y } else { touch.rx = x; touch.ry = y }
|
||||
push()
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Screen() {
|
||||
val status by BtGamepad.status.collectAsState()
|
||||
val colors = MaterialTheme.colorScheme
|
||||
Column(Modifier.fillMaxSize().background(colors.background).padding(horizontal = 12.dp, vertical = 8.dp)) {
|
||||
Panel(status)
|
||||
if (showTouch) {
|
||||
TouchPad(Modifier.weight(1f).fillMaxWidth().padding(top = 6.dp), status)
|
||||
} else {
|
||||
Column(Modifier.weight(1f).fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp, Alignment.CenterVertically),
|
||||
horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
Instructions(status, Modifier.widthIn(max = 480.dp))
|
||||
Text(stringResource(R.string.btpad_physical_hint), fontSize = 15.sp, color = colors.onSurfaceVariant)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Panel(status: BtGamepad.Status) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val connected = status.phase == BtGamepad.Phase.CONNECTED
|
||||
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||
val narrow = maxWidth < 600.dp
|
||||
val types: @Composable (Modifier) -> Unit = { m ->
|
||||
Row(m.horizontalScroll(rememberScrollState()), horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {
|
||||
BtPadProfile.entries.forEach { p -> Chip(profileLabel(p), p == profile) { pickProfile(p) } }
|
||||
Chip(stringResource(R.string.btpad_touch), showTouch) {
|
||||
showTouch = !showTouch
|
||||
prefs(this@BtControllerActivity).edit().putBoolean(KEY_TOUCH, showTouch).apply()
|
||||
}
|
||||
}
|
||||
}
|
||||
Column {
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Box(Modifier.size(10.dp).clip(CircleShape).background(status.lightbar?.let { Color(it) } ?: if (connected) pal.signal else colors.onSurfaceVariant.copy(alpha = 0.4f)))
|
||||
Column(if (narrow) Modifier.weight(1f) else Modifier.widthIn(max = 220.dp)) {
|
||||
Text(shortStatus(status), fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
Text(stringResource(if (connected) R.string.btpad_exit_hint else R.string.btpad_switch_hint), fontSize = 11.sp,
|
||||
color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
if (!narrow) types(Modifier.weight(1f))
|
||||
if (locationDenied && !permissionDenied && !connected) SecondaryButton(stringResource(R.string.btpad_permission_open), compact = true) { openAppInfo() }
|
||||
if (permissionDenied) PrimaryButton(stringResource(R.string.btpad_permission_open), compact = true) { openAppInfo() }
|
||||
else if (connected) SecondaryButton(stringResource(R.string.btpad_disconnect), compact = true) { BtGamepad.disconnect() }
|
||||
else PrimaryButton(stringResource(R.string.btpad_pair), compact = true, enabled = status.phase == BtGamepad.Phase.READY) { BtGamepad.openPairingWindow() }
|
||||
SecondaryButton(stringResource(R.string.btpad_close), compact = true) { finish() }
|
||||
}
|
||||
if (narrow) types(Modifier.padding(top = 6.dp))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun shortStatus(status: BtGamepad.Status): String =
|
||||
if (status.phase == BtGamepad.Phase.READY && !permissionDenied) stringResource(R.string.btpad_status_waiting) else statusText(status)
|
||||
|
||||
@Composable
|
||||
private fun Instructions(status: BtGamepad.Status, modifier: Modifier, size: androidx.compose.ui.unit.TextUnit = 14.sp) {
|
||||
if (status.phase == BtGamepad.Phase.CONNECTED) return
|
||||
val text = statusText(status) + if (locationDenied && !permissionDenied) "\n\n" + stringResource(R.string.btpad_location_hint) else ""
|
||||
Text(text, fontSize = size, color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
textAlign = androidx.compose.ui.text.style.TextAlign.Center, modifier = modifier)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun statusText(status: BtGamepad.Status): String = if (permissionDenied) stringResource(R.string.btpad_status_permission) else when (status.phase) {
|
||||
BtGamepad.Phase.OFF, BtGamepad.Phase.STARTING -> stringResource(R.string.btpad_status_starting)
|
||||
BtGamepad.Phase.BLUETOOTH_OFF -> stringResource(R.string.btpad_status_bt_off)
|
||||
BtGamepad.Phase.UNSUPPORTED -> stringResource(R.string.btpad_status_unsupported)
|
||||
BtGamepad.Phase.READY -> stringResource(R.string.btpad_status_ready, status.name ?: "")
|
||||
BtGamepad.Phase.CONNECTING -> stringResource(R.string.btpad_status_connecting, status.host ?: "")
|
||||
BtGamepad.Phase.CONNECTED -> stringResource(R.string.btpad_status_connected, status.host ?: "")
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun profileLabel(p: BtPadProfile) = stringResource(when (p) {
|
||||
BtPadProfile.GENERIC -> R.string.btpad_profile_generic
|
||||
BtPadProfile.XBOX -> R.string.btpad_profile_xbox
|
||||
BtPadProfile.DUALSHOCK4 -> R.string.btpad_profile_ds4
|
||||
BtPadProfile.DUALSENSE -> R.string.btpad_profile_dualsense
|
||||
BtPadProfile.STEAM -> R.string.btpad_profile_steam
|
||||
})
|
||||
|
||||
@Composable
|
||||
private fun Chip(label: String, on: Boolean, enabled: Boolean = true, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Text(label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold,
|
||||
color = if (on) colors.background else if (enabled) colors.onBackground else colors.onSurfaceVariant,
|
||||
modifier = Modifier.clip(CircleShape).background(if (on) pal.signal else colors.surface)
|
||||
.border(1.dp, if (on) pal.signal else pal.line2, CircleShape)
|
||||
.clickable(enabled = enabled, onClick = onClick).padding(horizontal = 12.dp, vertical = 6.dp))
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun TouchPad(modifier: Modifier, status: BtGamepad.Status) {
|
||||
val lightbar = status.lightbar
|
||||
val sony = profile == BtPadProfile.DUALSHOCK4 || profile == BtPadProfile.DUALSENSE
|
||||
val steam = profile == BtPadProfile.STEAM
|
||||
BoxWithConstraints(modifier) {
|
||||
val w = maxWidth
|
||||
val h = maxHeight
|
||||
val stick = minOf(h * (if (steam) 0.38f else 0.46f), w * 0.2f)
|
||||
val face = stick * 0.4f
|
||||
val cluster = face * 3f
|
||||
val shoulderW = minOf(w * 0.09f, stick * 0.75f)
|
||||
val shoulderH = minOf(h * 0.13f, 44.dp)
|
||||
val small = shoulderH * 0.85f
|
||||
@Composable
|
||||
fun at(fx: Float, fy: Float, bw: Dp, bh: Dp, content: @Composable () -> Unit) {
|
||||
val x = (w * fx - bw / 2).coerceIn(0.dp, w - bw)
|
||||
val y = (h * fy - bh / 2).coerceIn(0.dp, h - bh)
|
||||
Box(Modifier.offset(x, y).size(bw, bh), contentAlignment = Alignment.Center) { content() }
|
||||
}
|
||||
val shoulderY = shoulderH / h / 2f
|
||||
at(0.0f, shoulderY, shoulderW, shoulderH) { PadButton(if (sony) "L2" else "LT", BtPadState.LT, shoulderW, shoulderH) }
|
||||
val second = (shoulderW * 1.5f + 8.dp) / w
|
||||
at(second, shoulderY, shoulderW, shoulderH) { PadButton(if (sony) "L1" else "LB", BtPadState.LB, shoulderW, shoulderH) }
|
||||
at(1f - second, shoulderY, shoulderW, shoulderH) { PadButton(if (sony) "R1" else "RB", BtPadState.RB, shoulderW, shoulderH) }
|
||||
at(1.0f, shoulderY, shoulderW, shoulderH) { PadButton(if (sony) "R2" else "RT", BtPadState.RT, shoulderW, shoulderH) }
|
||||
val menuW = shoulderW * 0.95f
|
||||
val menu = listOfNotNull(
|
||||
Triple(if (sony) "Share" else "View", BtPadState.SELECT, null),
|
||||
Triple(if (sony) "PS" else if (steam) "Steam" else "Home", BtPadState.GUIDE, lightbar),
|
||||
if (steam) Triple("···", BtPadState.SHARE, null) else null,
|
||||
Triple(if (sony) "Options" else "Menu", BtPadState.START, null),
|
||||
)
|
||||
menu.forEachIndexed { i, (label, bit, tint) ->
|
||||
val fx = 0.5f + (i - (menu.size - 1) / 2f) * ((menuW + 8.dp) / w)
|
||||
at(fx, shoulderY, menuW, small) { PadButton(label, bit, menuW, small, tint = tint?.let { Color(it) }) }
|
||||
}
|
||||
val steamPad = minOf(h * 0.4f, w * 0.2f)
|
||||
val infoW = if (steam) w * 0.4f - steamPad - 12.dp else w * 0.3f
|
||||
val infoH = if (steam) h * 0.3f else h * 0.22f
|
||||
at(0.5f, if (steam) 0.72f else 0.3f, infoW, infoH) { Instructions(status, Modifier.fillMaxWidth(), if (steam) 12.sp else 14.sp) }
|
||||
if (steam) {
|
||||
val rearY = (shoulderH * 1.6f) / h
|
||||
at(0.0f, rearY, shoulderW, small) { PadButton("L5", BtPadState.L5, shoulderW, small) }
|
||||
at(second, rearY, shoulderW, small) { PadButton("L4", BtPadState.L4, shoulderW, small) }
|
||||
at(1f - second, rearY, shoulderW, small) { PadButton("R4", BtPadState.R4, shoulderW, small) }
|
||||
at(1.0f, rearY, shoulderW, small) { PadButton("R5", BtPadState.R5, shoulderW, small) }
|
||||
val pad = steamPad
|
||||
at(0.11f, 0.5f, stick, stick) { Stick(stick, left = true) }
|
||||
at(0.89f, 0.5f, stick, stick) { Stick(stick, left = false) }
|
||||
at(0.3f, 0.34f, cluster, cluster) { Cross(face) }
|
||||
at(0.7f, 0.34f, cluster, cluster) { Diamond(face, false) }
|
||||
at(0.3f, 1f, pad, pad) { Trackpad(pad, left = true) }
|
||||
at(0.7f, 1f, pad, pad) { Trackpad(pad, left = false) }
|
||||
at(0.44f, 0.94f, menuW, small) { PadButton("L3", BtPadState.L3, menuW, small) }
|
||||
at(0.56f, 0.94f, menuW, small) { PadButton("R3", BtPadState.R3, menuW, small) }
|
||||
} else {
|
||||
at(0.12f, 0.45f, stick, stick) { Stick(stick, left = true) }
|
||||
at(0.88f, 0.45f, cluster, cluster) { Diamond(face, sony) }
|
||||
at(0.32f, 0.78f, cluster, cluster) { Cross(face) }
|
||||
at(0.68f, 0.78f, stick, stick) { Stick(stick, left = false) }
|
||||
at(0.42f, 0.5f, menuW, small) { PadButton("L3", BtPadState.L3, menuW, small) }
|
||||
at(0.58f, 0.5f, menuW, small) { PadButton("R3", BtPadState.R3, menuW, small) }
|
||||
if (sony) at(0.5f, 0.68f, menuW * 1.6f, small * 1.4f) { PadButton("Touchpad", BtPadState.TOUCHPAD, menuW * 1.6f, small * 1.4f) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Trackpad(size: Dp, left: Boolean) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
var dot by remember { mutableStateOf<Offset?>(null) }
|
||||
val px = with(LocalDensity.current) { size.toPx() }
|
||||
Box(
|
||||
Modifier.size(size).clip(RoundedCornerShape(18.dp)).background(colors.surface).border(1.dp, pal.line2, RoundedCornerShape(18.dp))
|
||||
.pointerInput(left, touchEpoch) {
|
||||
awaitEachGesture {
|
||||
val first = awaitFirstDown(requireUnconsumed = false)
|
||||
val started = first.uptimeMillis
|
||||
fun norm(p: Offset) = Offset((p.x / this.size.width * 2f - 1f).coerceIn(-1f, 1f), (p.y / this.size.height * 2f - 1f).coerceIn(-1f, 1f))
|
||||
var moved = 0f
|
||||
var last = norm(first.position)
|
||||
dot = last
|
||||
touchPad(left, last, true)
|
||||
var upTime = started
|
||||
try {
|
||||
while (true) {
|
||||
val change = awaitPointerEvent().changes.firstOrNull { it.id == first.id } ?: break
|
||||
if (!change.pressed) { upTime = change.uptimeMillis; break }
|
||||
change.consume()
|
||||
val p = norm(change.position)
|
||||
moved += (p - last).getDistance()
|
||||
last = p
|
||||
dot = p
|
||||
touchPad(left, p, true)
|
||||
}
|
||||
} catch (e: kotlinx.coroutines.CancellationException) {
|
||||
dot = null
|
||||
touchPad(left, last, false)
|
||||
throw e
|
||||
}
|
||||
dot = null
|
||||
if (upTime - started < TAP_MS && moved < 0.15f) clickPad(left, last)
|
||||
else touchPad(left, last, false)
|
||||
}
|
||||
},
|
||||
) {
|
||||
dot?.let { d ->
|
||||
val r = px * 0.08f
|
||||
Box(Modifier.offset { IntOffset(((d.x + 1f) / 2f * px - r).roundToInt(), ((d.y + 1f) / 2f * px - r).roundToInt()) }
|
||||
.size(size * 0.16f).clip(CircleShape).background(pal.signal))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun touchPad(left: Boolean, p: Offset, down: Boolean) {
|
||||
val bit = if (left) BtPadState.LPAD_TOUCH else BtPadState.RPAD_TOUCH
|
||||
touch.buttons = if (down) touch.buttons or bit else touch.buttons and bit.inv()
|
||||
if (left) { touch.lpx = p.x; touch.lpy = p.y } else { touch.rpx = p.x; touch.rpy = p.y }
|
||||
push()
|
||||
}
|
||||
|
||||
private fun clickPad(left: Boolean, p: Offset) {
|
||||
val click = if (left) BtPadState.LPAD_CLICK else BtPadState.RPAD_CLICK
|
||||
touch.buttons = touch.buttons or click
|
||||
touchPad(left, p, true)
|
||||
main.postDelayed({
|
||||
touch.buttons = touch.buttons and click.inv()
|
||||
touchPad(left, p, false)
|
||||
}, CLICK_MS)
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Cross(size: Dp) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
PadButton("▲", BtPadState.UP, size, size)
|
||||
Row {
|
||||
PadButton("◀", BtPadState.LEFT, size, size)
|
||||
Spacer(Modifier.size(size))
|
||||
PadButton("▶", BtPadState.RIGHT, size, size)
|
||||
}
|
||||
PadButton("▼", BtPadState.DOWN, size, size)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Diamond(size: Dp, sony: Boolean) {
|
||||
Column(horizontalAlignment = Alignment.CenterHorizontally) {
|
||||
PadButton(if (sony) "△" else "Y", BtPadState.Y, size, size, round = true)
|
||||
Row {
|
||||
PadButton(if (sony) "□" else "X", BtPadState.X, size, size, round = true)
|
||||
Spacer(Modifier.size(size))
|
||||
PadButton(if (sony) "○" else "B", BtPadState.B, size, size, round = true)
|
||||
}
|
||||
PadButton(if (sony) "✕" else "A", BtPadState.A, size, size, round = true)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun PadButton(label: String, bit: Int, width: Dp, height: Dp, round: Boolean = false, tint: Color? = null) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
var down by remember { mutableStateOf(false) }
|
||||
val shape = if (round) CircleShape else RoundedCornerShape(10.dp)
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.size(width, height).clip(shape)
|
||||
.background(if (down) pal.signal else tint?.copy(alpha = 0.35f) ?: colors.surface)
|
||||
.border(1.dp, pal.line2, shape)
|
||||
.pointerInput(bit, touchEpoch) {
|
||||
awaitEachGesture {
|
||||
awaitFirstDown(requireUnconsumed = false)
|
||||
down = true; touchButton(bit, true)
|
||||
try {
|
||||
waitForUpOrCancellation()
|
||||
} finally {
|
||||
down = false; touchButton(bit, false)
|
||||
}
|
||||
}
|
||||
},
|
||||
) {
|
||||
Text(label, fontSize = 14.sp, fontWeight = FontWeight.Bold, color = if (down) colors.background else colors.onBackground)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun Stick(size: Dp, left: Boolean) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
var knob by remember { mutableStateOf(Offset.Zero) }
|
||||
val px = with(LocalDensity.current) { size.toPx() }
|
||||
val knobSize = size * 0.42f
|
||||
Box(
|
||||
contentAlignment = Alignment.Center,
|
||||
modifier = Modifier.size(size).clip(CircleShape).background(colors.surface).border(1.dp, pal.line2, CircleShape)
|
||||
.pointerInput(left, touchEpoch) {
|
||||
awaitEachGesture {
|
||||
val first = awaitFirstDown(requireUnconsumed = false)
|
||||
val radius = this.size.width / 2f
|
||||
val center = Offset(radius, this.size.height / 2f)
|
||||
fun move(p: Offset) {
|
||||
var d = (p - center) / (radius * 0.8f)
|
||||
val len = hypot(d.x, d.y)
|
||||
if (len > 1f) d /= len
|
||||
knob = d
|
||||
touchStick(left, d.x, d.y)
|
||||
}
|
||||
move(first.position)
|
||||
try {
|
||||
while (true) {
|
||||
val change = awaitPointerEvent().changes.firstOrNull { it.id == first.id } ?: break
|
||||
if (!change.pressed) break
|
||||
change.consume()
|
||||
move(change.position)
|
||||
}
|
||||
} finally {
|
||||
knob = Offset.Zero
|
||||
touchStick(left, 0f, 0f)
|
||||
}
|
||||
}
|
||||
},
|
||||
) {
|
||||
val travel = px * 0.29f
|
||||
Box(Modifier.offset { IntOffset((knob.x * travel).roundToInt(), (knob.y * travel).roundToInt()) }
|
||||
.size(knobSize).clip(CircleShape).background(if (knob != Offset.Zero) pal.signal else colors.onSurfaceVariant.copy(alpha = 0.5f)))
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val EXIT_HOLD_MS = 1_500L
|
||||
private const val TAP_MS = 200L
|
||||
private const val CLICK_MS = 90L
|
||||
private const val REQUEST_NEARBY = 41
|
||||
private val NEARBY = listOf("android.permission.BLUETOOTH_ADVERTISE", "android.permission.BLUETOOTH_CONNECT", "android.permission.BLUETOOTH_SCAN")
|
||||
private val LOCATION = listOf("android.permission.ACCESS_FINE_LOCATION")
|
||||
private const val KEY_PROFILE = "btpad_profile"
|
||||
private const val KEY_TOUCH = "btpad_touch"
|
||||
|
||||
private fun prefs(c: Context) = c.getSharedPreferences("trinkets", Context.MODE_PRIVATE)
|
||||
|
||||
private val DPAD_KEYS = setOf(KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT)
|
||||
|
||||
private val KEYS = mapOf(
|
||||
KeyEvent.KEYCODE_BUTTON_A to BtPadState.A,
|
||||
KeyEvent.KEYCODE_BUTTON_B to BtPadState.B,
|
||||
KeyEvent.KEYCODE_BUTTON_X to BtPadState.X,
|
||||
KeyEvent.KEYCODE_BUTTON_Y to BtPadState.Y,
|
||||
KeyEvent.KEYCODE_BUTTON_L1 to BtPadState.LB,
|
||||
KeyEvent.KEYCODE_BUTTON_R1 to BtPadState.RB,
|
||||
KeyEvent.KEYCODE_BUTTON_L2 to BtPadState.LT,
|
||||
KeyEvent.KEYCODE_BUTTON_R2 to BtPadState.RT,
|
||||
KeyEvent.KEYCODE_BUTTON_SELECT to BtPadState.SELECT,
|
||||
KeyEvent.KEYCODE_BUTTON_START to BtPadState.START,
|
||||
KeyEvent.KEYCODE_BUTTON_MODE to BtPadState.GUIDE,
|
||||
KeyEvent.KEYCODE_BUTTON_THUMBL to BtPadState.L3,
|
||||
KeyEvent.KEYCODE_BUTTON_THUMBR to BtPadState.R3,
|
||||
KeyEvent.KEYCODE_BUTTON_C to BtPadState.L4,
|
||||
KeyEvent.KEYCODE_BUTTON_Z to BtPadState.R4,
|
||||
KeyEvent.KEYCODE_BUTTON_1 to BtPadState.L4,
|
||||
KeyEvent.KEYCODE_BUTTON_2 to BtPadState.R4,
|
||||
KeyEvent.KEYCODE_BUTTON_3 to BtPadState.L5,
|
||||
KeyEvent.KEYCODE_BUTTON_4 to BtPadState.R5,
|
||||
KeyEvent.KEYCODE_DPAD_UP to BtPadState.UP,
|
||||
KeyEvent.KEYCODE_DPAD_DOWN to BtPadState.DOWN,
|
||||
KeyEvent.KEYCODE_DPAD_LEFT to BtPadState.LEFT,
|
||||
KeyEvent.KEYCODE_DPAD_RIGHT to BtPadState.RIGHT,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -53,8 +53,6 @@ import com.droiddeck.launcher.session.SessionLogShare
|
||||
import com.droiddeck.launcher.session.SessionPaths
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
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.DownloadSource
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
@@ -141,7 +139,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
private var glThread by mutableStateOf(true)
|
||||
private var noGlError by mutableStateOf(true)
|
||||
private var returnAfterGame by mutableStateOf(true)
|
||||
private var valveProtonOnDemand by mutableStateOf(true)
|
||||
private var shaderPrecache by mutableStateOf<Boolean?>(null)
|
||||
private var steamRepairQueued by mutableStateOf(false)
|
||||
private var mangoapp by mutableStateOf(true)
|
||||
@@ -169,7 +166,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
private var battleNetInstalled by mutableStateOf(false)
|
||||
private var offlineAccount by mutableStateOf<String?>(null)
|
||||
private var offline by mutableStateOf(false)
|
||||
private var offlineAuto by mutableStateOf(true)
|
||||
private var showPerformance by mutableStateOf(false)
|
||||
private var clientOverride by mutableStateOf(false)
|
||||
private var clientCores by mutableStateOf<Set<Int>>(emptySet())
|
||||
@@ -192,7 +188,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
private var prootNoSeccomp by mutableStateOf(false)
|
||||
private var prootFastPath by mutableStateOf(true)
|
||||
private var nativeUserland by mutableStateOf(true)
|
||||
private var cursorComposite by mutableStateOf(true)
|
||||
private var cursorComposite by mutableStateOf(false)
|
||||
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
|
||||
private var phantomWarning by mutableStateOf<String?>(null)
|
||||
private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE)
|
||||
@@ -219,7 +215,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
private var soundtracksLoaded by mutableStateOf(false)
|
||||
private var gameStoresSpeedTier by mutableStateOf("fast")
|
||||
private var navRequest by mutableStateOf<String?>(null)
|
||||
private val launchCoordinator = LaunchCoordinator<Intent, com.droiddeck.launcher.frontend.GameRequest>()
|
||||
private val gameLaunchRequest = java.util.concurrent.atomic.AtomicLong()
|
||||
private var preparingGames by mutableStateOf(emptySet<String>())
|
||||
private var storesShowMature by mutableStateOf(false)
|
||||
private var storesSort by mutableStateOf(SessionPrefs.STORES_SORTS.first())
|
||||
@@ -641,7 +637,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
private var storageDiagnostics by mutableStateOf(false)
|
||||
private var storageOptions by mutableStateOf<List<GameStorage.Option>>(emptyList())
|
||||
private var storageFat32 by mutableStateOf(false)
|
||||
private val pickGameStorage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
|
||||
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> setGameStorage(path, GameStorage.labelFor(this, path)) }
|
||||
}
|
||||
@@ -657,7 +652,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
private fun addSteamLibrary(path: String) {
|
||||
Thread({
|
||||
val result = SteamLibraries.add(this, path)
|
||||
val fat32 = result is SteamLibraries.AddResult.Added && GameStorage.isFat32(result.entry.path)
|
||||
ui.post {
|
||||
steamLibraries = SteamLibraries.list(this)
|
||||
refreshFoundSteamLibraries()
|
||||
@@ -668,7 +662,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
result is SteamLibraries.AddResult.Added && result.entry.path != path ->
|
||||
android.widget.Toast.makeText(this, getString(R.string.libraries_used_inner, result.entry.label), android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
if (fat32) android.widget.Toast.makeText(this, R.string.main_storage_fat32, android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}, "steam-library-add").start()
|
||||
}
|
||||
@@ -724,7 +717,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
}
|
||||
private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList())
|
||||
private var ownScreen by mutableStateOf<SecondScreenDisplay?>(null)
|
||||
private var dualDisplayId by mutableStateOf(-1)
|
||||
private var dualScreenDevice by mutableStateOf(false)
|
||||
private var dualScreenMode by mutableStateOf(com.droiddeck.launcher.input.DualScreen.MODE_AUTO)
|
||||
@@ -901,6 +893,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
runCatching { com.droiddeck.launcher.frontend.AutoComponents.restoreMissing(this) }.onFailure { Log.w(TAG, "components: restore failed", it) }
|
||||
}, "components-restore").start()
|
||||
}
|
||||
private var pendingGameLink: com.droiddeck.launcher.frontend.GameRequest? = null
|
||||
private var gameLinkReading = false
|
||||
private var gameLinkTried = false
|
||||
private var gameSyncFolder by mutableStateOf<String?>(null)
|
||||
@@ -926,24 +919,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
LauncherIcon.set(this, style)
|
||||
launcherIcon = LauncherIcon.current(this)
|
||||
if (launcherIcon == before) return false
|
||||
restartLauncher()
|
||||
return true
|
||||
}
|
||||
|
||||
// recreate() leaves this activity's window drawing nothing and ignoring input on some devices (#2668).
|
||||
private fun restartLauncher() {
|
||||
LauncherHandoff.put(Bundle().also(::saveLauncherState))
|
||||
switchPoll?.let { ui.removeCallbacks(it) }
|
||||
switchPoll = null
|
||||
switchingTo = null
|
||||
queuedLaunch.clear()
|
||||
cancelCompatLaunch()
|
||||
startActivity(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
.setComponent(LauncherIcon.activity(this))
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
|
||||
.putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "setup:launcher")
|
||||
.putExtra(EXTRA_RESTARTED, true))
|
||||
.putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "setup:launcher"))
|
||||
finishAndRemoveTask()
|
||||
return true
|
||||
}
|
||||
|
||||
private fun readGameIntent(request: Intent) {
|
||||
@@ -954,6 +935,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
else "settings:" + (com.droiddeck.launcher.ui.SettingsSection.of(section) ?: com.droiddeck.launcher.ui.SettingsSection.OVERVIEW).key
|
||||
request.data = null
|
||||
gameLinkReading = false
|
||||
pendingGameLink = null
|
||||
syncDualPanel()
|
||||
return
|
||||
}
|
||||
@@ -966,6 +948,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
steamGames = emptyList()
|
||||
shortcutLibraryScanning = true
|
||||
} else shortcutLibraryScanning = false
|
||||
pendingGameLink = null
|
||||
gameLinkReading = false
|
||||
gameLinkTried = false
|
||||
soundtrackLaunch = false
|
||||
@@ -978,7 +961,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
return
|
||||
}
|
||||
if (GameLaunchIntent.accepts(request.action)) {
|
||||
val ticket = launchCoordinator.beginLink(request)
|
||||
gameLinkReading = true
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
|
||||
val copy = Intent(request)
|
||||
@@ -987,17 +969,12 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
ui.post {
|
||||
if (intent === request && !isDestroyed) {
|
||||
gameLinkReading = false
|
||||
if (!launchCoordinator.resolve(ticket, game)) {
|
||||
clearGameLinkIntent(request)
|
||||
syncDualPanel()
|
||||
return@post
|
||||
}
|
||||
pendingGameLink = game
|
||||
if (game == null) {
|
||||
launchCoordinator.consume(ticket)
|
||||
syncDualPanel()
|
||||
android.widget.Toast.makeText(this, R.string.game_link_invalid, android.widget.Toast.LENGTH_LONG).show()
|
||||
} else {
|
||||
handleGameLink(steamGames, scanned = false, ticket = ticket)
|
||||
handleGameLink(steamGames, scanned = false)
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
@@ -1006,66 +983,37 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
}
|
||||
|
||||
private fun beginUiLaunch(): LaunchTicket {
|
||||
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,
|
||||
) {
|
||||
private fun launchGame(game: Library.SteamGame, returnHome: Boolean = false, onHandled: () -> Unit = {}, onSettled: () -> Unit = {}) {
|
||||
val request = gameLaunchRequest.incrementAndGet()
|
||||
if (!SessionPrefs.soundtracksIngame(this)) com.droiddeck.launcher.playback.SoundtrackController.pause(this)
|
||||
if (pkgStage != null) {
|
||||
ticket?.let(launchCoordinator::releaseHandling)
|
||||
onHandled()
|
||||
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)) {
|
||||
onHandled()
|
||||
return
|
||||
}
|
||||
val files = game.gameFiles
|
||||
if (game.source != com.droiddeck.launcher.stores.Store.XBOX.id || files == null) {
|
||||
if (startGame(game, returnHome, onHandled, request)) onSettled()
|
||||
else launchCoordinator.releaseHandling(request)
|
||||
if (startGame(game, returnHome, onHandled)) onSettled()
|
||||
return
|
||||
}
|
||||
Thread({
|
||||
val refused = com.droiddeck.launcher.stores.xbox.XboxManifest.needsAppModel(files)
|
||||
ui.post {
|
||||
when {
|
||||
!launchCoordinator.isCurrent(request) || isFinishing || isDestroyed -> {
|
||||
launchCoordinator.releaseHandling(request)
|
||||
onHandled()
|
||||
}
|
||||
request != gameLaunchRequest.get() || isFinishing || isDestroyed -> onHandled()
|
||||
refused -> {
|
||||
onHandled()
|
||||
android.widget.Toast.makeText(this, getString(R.string.game_needs_app_model, game.name), android.widget.Toast.LENGTH_LONG).show()
|
||||
onSettled()
|
||||
}
|
||||
startGame(game, returnHome, onHandled, request) -> onSettled()
|
||||
else -> launchCoordinator.releaseHandling(request)
|
||||
startGame(game, returnHome, onHandled) -> onSettled()
|
||||
}
|
||||
}
|
||||
}, "xbox-app-model").start()
|
||||
}
|
||||
|
||||
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, ticket)
|
||||
private fun startGame(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit): Boolean {
|
||||
if (com.droiddeck.launcher.session.NoSteamLaunch.enabled(this, game)) return launchWithoutSteam(game, returnHome, onHandled)
|
||||
onHandled()
|
||||
if (SessionState.running) {
|
||||
if (SessionState.mode != SessionService.MODE_STEAM || SessionState.stopRequested) {
|
||||
@@ -1110,34 +1058,15 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
.apply { if (returnHome) putExtra(SessionActivity.EXTRA_LINK_TASK, task) }
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
private fun launchWithoutSteam(game: Library.SteamGame, returnHome: Boolean, onHandled: () -> Unit = {}): Boolean {
|
||||
val app = applicationContext
|
||||
val request = ticket ?: beginUiLaunch()
|
||||
if (!launchCoordinator.isCurrent(request)) {
|
||||
onHandled()
|
||||
return false
|
||||
}
|
||||
Thread({
|
||||
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)
|
||||
ui.post {
|
||||
onHandled()
|
||||
if (!launchCoordinator.isCurrent(request) || isFinishing || isDestroyed) {
|
||||
launchCoordinator.releaseHandling(request)
|
||||
return@post
|
||||
}
|
||||
if (isDestroyed) return@post
|
||||
if (command == null) {
|
||||
launchCoordinator.releaseHandling(request)
|
||||
android.widget.Toast.makeText(this, R.string.game_link_failed, android.widget.Toast.LENGTH_LONG).show()
|
||||
return@post
|
||||
}
|
||||
@@ -1289,27 +1218,22 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
ui.postDelayed(poll, SESSION_SWITCH_POLL_MS)
|
||||
}
|
||||
|
||||
private fun handleGameLink(games: List<Library.SteamGame>, scanned: Boolean = true, ticket: LaunchTicket? = null) {
|
||||
private fun handleGameLink(games: List<Library.SteamGame>, scanned: Boolean = true) {
|
||||
if (!lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) 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 request = pendingGameLink ?: return
|
||||
val game = request.find(games, byTitle = scanned)
|
||||
if (!scanned && game == null) return
|
||||
gameLinkTried = true
|
||||
ui.postDelayed({
|
||||
if (!isDestroyed && lifecycle.currentState.isAtLeast(androidx.lifecycle.Lifecycle.State.RESUMED)) syncDualPanel()
|
||||
}, LINK_PANEL_MS)
|
||||
val linkIntent = link.owner
|
||||
val link = intent
|
||||
fun consume() {
|
||||
if (!launchCoordinator.consume(link.ticket)) return
|
||||
if (intent === linkIntent) clearGameLinkIntent(linkIntent)
|
||||
if (intent !== link || pendingGameLink !== request) return
|
||||
pendingGameLink = null
|
||||
link.data = null
|
||||
link.action = Intent.ACTION_MAIN
|
||||
link.removeExtra(GameLaunchIntent.EXTRA_APP_ID)
|
||||
}
|
||||
if (game == null) {
|
||||
consume()
|
||||
@@ -1317,10 +1241,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
android.widget.Toast.makeText(this,
|
||||
if (request.program != null) R.string.game_link_program_unknown else R.string.game_link_missing,
|
||||
android.widget.Toast.LENGTH_LONG).show()
|
||||
} else {
|
||||
if (!launchCoordinator.beginHandling(link.ticket)) return
|
||||
launchGame(game, returnHome = true, onSettled = ::consume, ticket = link.ticket)
|
||||
}
|
||||
} else launchGame(game, returnHome = true, onSettled = ::consume)
|
||||
}
|
||||
|
||||
private fun chooseGameShortcut(game: Library.SteamGame) {
|
||||
@@ -1332,15 +1253,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
super.onCreate(savedInstanceState)
|
||||
drivers.restartBlocked = ::runtimeChangesBlocked
|
||||
drivers.loadTpUbwcMode()
|
||||
val handoff = if (savedInstanceState == null && intent.getBooleanExtra(EXTRA_RESTARTED, false)) LauncherHandoff.take() else null
|
||||
val saved = savedInstanceState ?: handoff
|
||||
pendingSessionLogExport = saved?.getString(KEY_PENDING_SESSION_LOG_EXPORT)?.let(::File)
|
||||
queuedLaunch.restore(
|
||||
saved?.let { androidx.core.os.BundleCompat.getParcelable(it, STATE_PENDING_GATE_LAUNCH, Intent::class.java) },
|
||||
saved?.getLong(STATE_PENDING_GATE_LAUNCH_AT, 0L) ?: 0L, System.currentTimeMillis(),
|
||||
)
|
||||
homeChoiceOpen = saved?.getBoolean(STATE_HOME_CHOICE_OPEN) == true
|
||||
gameSpaceOffered = saved?.getBoolean(STATE_GAME_SPACE_OFFERED) == true
|
||||
pendingSessionLogExport = savedInstanceState?.getString(KEY_PENDING_SESSION_LOG_EXPORT)?.let(::File)
|
||||
homeChoiceOpen = savedInstanceState?.getBoolean(STATE_HOME_CHOICE_OPEN) == true
|
||||
gameSpaceOffered = savedInstanceState?.getBoolean(STATE_GAME_SPACE_OFFERED) == true
|
||||
if (savedInstanceState == null) readIntegrationIntent(intent)
|
||||
val shortcutsFilter = android.content.IntentFilter(SteamIntegration.SHORTCUTS_STATUS)
|
||||
if (android.os.Build.VERSION.SDK_INT >= 33) registerReceiver(shortcutsInstallStatus, shortcutsFilter, RECEIVER_NOT_EXPORTED)
|
||||
@@ -1417,7 +1332,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
gameSyncFolder = gameSyncFolder,
|
||||
busy = busy, stage = stage, percent = percent,
|
||||
desktopInstalled = desktopInstalled, desktopPresent = desktopPresent,
|
||||
offlineAccount = offlineAccount, offline = offline, offlineAuto = offlineAuto,
|
||||
offlineAccount = offlineAccount, offline = offline,
|
||||
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
|
||||
enhancedDiagnosticsArmed = enhancedDiagnosticsArmed,
|
||||
gameDebugLogsEnabled = gameDebugLogsEnabled, gameDebugLogsNeedsRestart = gameDebugLogsNeedsRestart,
|
||||
@@ -1440,7 +1355,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
integrationFocus = integrationFocus,
|
||||
androidApps = androidApps,
|
||||
secondScreenDisplays = secondScreenDisplays,
|
||||
ownScreen = ownScreen,
|
||||
dualScreen = dualDisplayId >= 0 && com.droiddeck.launcher.ui.DualScreenPanel.available,
|
||||
dualScreenDevice = dualScreenDevice,
|
||||
dualScreenMode = dualScreenMode,
|
||||
@@ -1488,9 +1402,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
),
|
||||
FrontEndActions(
|
||||
onPlay = { playSteam() },
|
||||
onQueuePlaySteam = {
|
||||
queuedLaunch.queue(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, false), System.currentTimeMillis())
|
||||
},
|
||||
onPlaySteamVr = { playSteamVr() },
|
||||
onSteamUrl = { url ->
|
||||
if (!SessionState.running) startSession(
|
||||
@@ -1511,20 +1422,16 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
},
|
||||
onStoreGame = { store, id ->
|
||||
val key = "${store.id}:$id"
|
||||
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) {
|
||||
if (key !in preparingGames) {
|
||||
preparingGames = preparingGames + key
|
||||
val ticket = beginUiLaunch()
|
||||
val app = applicationContext
|
||||
Thread({
|
||||
val g = runCatching { com.droiddeck.launcher.stores.StoreLaunch.installedGame(app, store, id) }.getOrNull()
|
||||
runOnUiThread {
|
||||
if (g != null && launchCoordinator.isCurrent(ticket) && !isFinishing && !isDestroyed) {
|
||||
prepareAndLaunch(g, key, ticket)
|
||||
} else {
|
||||
if (g != null && !isFinishing && !isDestroyed) prepareAndLaunch(g, key)
|
||||
else {
|
||||
preparingGames = preparingGames - key
|
||||
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()
|
||||
if (g == null && !isFinishing && !isDestroyed) android.widget.Toast.makeText(this, R.string.stores_launch_not_registered, android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
}, "store-play").start()
|
||||
@@ -1755,11 +1662,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
OfflineMode.setEnabled(this, !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 },
|
||||
onSoundtracksIngame = { on ->
|
||||
SessionPrefs.setSoundtracksIngame(this, on)
|
||||
@@ -1774,7 +1676,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
onLanguage = { tag ->
|
||||
if (tag != com.droiddeck.launcher.core.AppLanguage.chosen(this)) {
|
||||
com.droiddeck.launcher.core.AppLanguage.setChosen(this, tag)
|
||||
restartLauncher()
|
||||
recreate()
|
||||
}
|
||||
},
|
||||
onAppScale = { percent ->
|
||||
@@ -1871,6 +1773,31 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
},
|
||||
onRefreshPhantomStatus = { refreshPhantomStatus() },
|
||||
onOpenDeveloperOptions = { displayId -> openDeveloperOptions(displayId) },
|
||||
onWirelessAdbPair = { host, port, code, complete ->
|
||||
Thread({
|
||||
val result = runCatching {
|
||||
kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@FrontEndActivity, host, port, code) }
|
||||
}
|
||||
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: getString(R.string.main_wadb_pair_failed) }
|
||||
ui.post { complete(error) }
|
||||
}, "wireless-adb-pair").start()
|
||||
},
|
||||
onFindWirelessAdbPort = { host, complete ->
|
||||
Thread({
|
||||
val port = WirelessAdbFix.findConnectPort(this@FrontEndActivity, host)
|
||||
ui.post { complete(port) }
|
||||
}, "wireless-adb-discovery").start()
|
||||
},
|
||||
onWirelessAdbApply = { host, port, enabled, complete ->
|
||||
Thread({
|
||||
val result = runCatching { WirelessAdbFix.setChildProcessLimit(this@FrontEndActivity, host, port, enabled) }
|
||||
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: getString(R.string.main_wadb_command_failed) }
|
||||
ui.post {
|
||||
if (error == null) refreshPhantomStatus()
|
||||
complete(error)
|
||||
}
|
||||
}, "wireless-adb-fix").start()
|
||||
},
|
||||
onSetPhantomProcessLimit = { enabled, complete ->
|
||||
Thread({
|
||||
val result = runCatching { WirelessAdbFix.setUsingSavedPairing(this@FrontEndActivity, enabled) }
|
||||
@@ -1887,14 +1814,18 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
)
|
||||
android.widget.Toast.makeText(this, R.string.main_adb_copied, android.widget.Toast.LENGTH_SHORT).show()
|
||||
},
|
||||
onDismissPhantomGate = { queuedLaunch.clear(); showPhantomGate = false },
|
||||
onDismissPhantomGate = { showPhantomGate = false },
|
||||
onShowPhantomGate = {
|
||||
refreshPhantomStatus()
|
||||
showPhantomGate = true
|
||||
},
|
||||
onStartWirelessAdbPairing = { enabled -> WirelessAdbPairingService.start(this, enabled) },
|
||||
onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) },
|
||||
onStartPairingGuide = { displayId, toggleOnly -> PairingGuideActivity.start(this, displayId, toggleOnly) },
|
||||
onEnsureNotifications = { done -> ensureNotifications(done) },
|
||||
onOpenNotificationSettings = {
|
||||
startActivity(Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS)
|
||||
.putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
},
|
||||
updates = updates.actions(),
|
||||
controller = ControllerActions(
|
||||
onMapping = { showPerformance = false; showComponents = false; showMapping = true },
|
||||
@@ -1990,11 +1921,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
!SessionPrefs.allFilesAsked(this)
|
||||
if (savedInstanceState == null) {
|
||||
if (!askAllFiles) ui.post { startSteamAtStartupIfEnabled(cold = true) }
|
||||
}
|
||||
saved?.let { state ->
|
||||
restoreCompatLaunch(state)
|
||||
pendingSwitch = savedIntent(state, KEY_PENDING_SWITCH)
|
||||
savedIntent(state, KEY_SWITCHING_TO)?.let { awaitSessionEnd(it, state.getLong(KEY_SWITCH_DEADLINE)) }
|
||||
} else {
|
||||
restoreCompatLaunch(savedInstanceState)
|
||||
pendingSwitch = savedIntent(savedInstanceState, KEY_PENDING_SWITCH)
|
||||
savedIntent(savedInstanceState, KEY_SWITCHING_TO)?.let { awaitSessionEnd(it, savedInstanceState.getLong(KEY_SWITCH_DEADLINE)) }
|
||||
}
|
||||
|
||||
val wanted = ArrayList<String>()
|
||||
@@ -2032,9 +1962,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
setIntent(intent)
|
||||
supersedeUncommittedLaunch()
|
||||
gameLaunchRequest.incrementAndGet()
|
||||
if (intent.action == SteamIntegration.ACTION_SETUP) {
|
||||
gameLinkReading = false
|
||||
pendingGameLink = null
|
||||
syncDualPanel()
|
||||
readIntegrationIntent(intent)
|
||||
return
|
||||
@@ -2044,19 +1975,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
startSteamAtStartupIfEnabled()
|
||||
}
|
||||
|
||||
/** A replacement activity intent supersedes anything this activity has not dispatched yet. */
|
||||
private fun supersedeUncommittedLaunch() {
|
||||
launchCoordinator.cancelAll()
|
||||
}
|
||||
|
||||
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.
|
||||
private val libraryHook: () -> Unit = { refreshAddedGames(); refresh() }
|
||||
private val battleNetHook: (List<String>) -> Unit = { args -> openBattleNet(args) }
|
||||
|
||||
private fun startSteamAtStartupIfEnabled(cold: Boolean = false) {
|
||||
if (soundtrackLaunch || intent.getBooleanExtra(EXTRA_RESTARTED, false)) return
|
||||
if (soundtrackLaunch) return
|
||||
if (intent.action != Intent.ACTION_MAIN && !(cold && intent.action == null)) return
|
||||
if (isFinishing || isDestroyed) return
|
||||
when (SessionPrefs.startupSession(this)) {
|
||||
@@ -2083,7 +2005,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
|
||||
private fun startSteamSession(steamVr: Boolean = false) {
|
||||
startSession(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, steamVr), steamSession = true, queueIfBlocked = !steamVr)
|
||||
startSession(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, steamVr), steamSession = true)
|
||||
}
|
||||
|
||||
@Suppress("OVERRIDE_DEPRECATION")
|
||||
@@ -2177,7 +2099,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
if (!triggerKeys.synthesizing && triggerKeys.nativeKey(event)) return true
|
||||
val tabStep = com.droiddeck.launcher.ui.dualPageStep(event)
|
||||
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 (controllerHaptics) com.droiddeck.launcher.ui.ControllerHaptics.onKey(this, event)
|
||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) tabs(tabStep)
|
||||
@@ -2232,8 +2153,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this)
|
||||
refreshWifiDiscovery()
|
||||
com.droiddeck.launcher.stores.StoresState.refresh(this)
|
||||
com.droiddeck.launcher.stores.StoresState.libraryListener = libraryHook
|
||||
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = battleNetHook
|
||||
com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() }
|
||||
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = { args -> openBattleNet(args) }
|
||||
com.droiddeck.launcher.ui.Motion.refresh(this)
|
||||
com.droiddeck.launcher.ui.QuitFlood.take()?.let { c ->
|
||||
returning = ReturningFlood(c, com.droiddeck.launcher.ui.LaunchOrigin.takeReturn())
|
||||
@@ -2304,17 +2225,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
|
||||
override fun onSaveInstanceState(outState: Bundle) {
|
||||
super.onSaveInstanceState(outState)
|
||||
saveLauncherState(outState)
|
||||
}
|
||||
|
||||
private fun saveLauncherState(outState: Bundle) {
|
||||
outState.putBoolean(STATE_HOME_CHOICE_OPEN, homeChoiceOpen)
|
||||
outState.putBoolean(STATE_GAME_SPACE_OFFERED, gameSpaceOffered)
|
||||
pendingSessionLogExport?.let { outState.putString(KEY_PENDING_SESSION_LOG_EXPORT, it.absolutePath) }
|
||||
queuedLaunch.launch?.let {
|
||||
outState.putParcelable(STATE_PENDING_GATE_LAUNCH, it)
|
||||
outState.putLong(STATE_PENDING_GATE_LAUNCH_AT, queuedLaunch.queuedAt)
|
||||
}
|
||||
if (slowUsbNever) SessionPrefs.setSlowUsbWarningOff(this)
|
||||
saveCompatLaunch(outState)
|
||||
pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) }
|
||||
@@ -2328,32 +2241,21 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
if (Build.VERSION.SDK_INT >= 33) state.getParcelable(key, Intent::class.java)
|
||||
else @Suppress("DEPRECATION") state.getParcelable(key)
|
||||
|
||||
private fun prepareAndLaunch(g: Library.SteamGame, key: String, ticket: LaunchTicket? = null) {
|
||||
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
|
||||
}
|
||||
private fun prepareAndLaunch(g: Library.SteamGame, key: String) {
|
||||
val request = gameLaunchRequest.incrementAndGet()
|
||||
val done = { preparingGames = preparingGames - key }
|
||||
com.droiddeck.launcher.frontend.AutoComponents.beforeLaunch(this, g, onBlocked = done) {
|
||||
if (!launchCoordinator.isCurrent(request) || isFinishing || isDestroyed) { done(); return@beforeLaunch }
|
||||
if (request != gameLaunchRequest.get() || isFinishing || isDestroyed) { done(); return@beforeLaunch }
|
||||
com.droiddeck.launcher.stores.StoreLaunch.prepare(this, g) {
|
||||
if (launchCoordinator.isCurrent(request) && !isFinishing && !isDestroyed) launchGame(g, onHandled = done, ticket = request)
|
||||
if (request == gameLaunchRequest.get() && !isFinishing && !isDestroyed) launchGame(g, onHandled = done)
|
||||
else done()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
// The queued launch was saved before this; a restored activity keeps its copy, and this one must not start it too.
|
||||
queuedLaunchRunner.destroy()
|
||||
triggerKeys.cancel()
|
||||
launchCoordinator.cancelAll()
|
||||
gameLaunchRequest.incrementAndGet()
|
||||
cancelCompatLaunch()
|
||||
updates.unregister()
|
||||
runCatching { unregisterReceiver(shortcutsInstallStatus) }
|
||||
@@ -2373,8 +2275,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
getSystemService(android.content.pm.LauncherApps::class.java).unregisterCallback(packageCallback)
|
||||
HomeWidgets.stopListening(this)
|
||||
ui.removeCallbacks(mediaRefresh)
|
||||
if (com.droiddeck.launcher.stores.StoresState.libraryListener === libraryHook) com.droiddeck.launcher.stores.StoresState.libraryListener = null
|
||||
if (com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener === battleNetHook) com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null
|
||||
com.droiddeck.launcher.stores.StoresState.libraryListener = null
|
||||
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = null
|
||||
displayManager.unregisterDisplayListener(secondScreenDisplayListener)
|
||||
com.droiddeck.launcher.input.DualScreen.unwatchTaken(bottomScreenListener)
|
||||
getSystemService(android.hardware.input.InputManager::class.java)?.unregisterInputDeviceListener(secondScreenTouchListener)
|
||||
@@ -2391,7 +2293,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
homeScreenEnabled = HomeApp.isHomeScreenEnabled(this)
|
||||
homeAppSelected = homeScreenEnabled && HomeApp.isDefault(this)
|
||||
defaultHomeLabel = HomeApp.defaultLabel(this)
|
||||
com.droiddeck.launcher.ui.NavTabs.syncHomeApps(this, homeAppSelected)
|
||||
refreshAndroidApps()
|
||||
integrationState = readIntegration()
|
||||
}
|
||||
@@ -2415,9 +2316,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
val ownDisplayId = if (android.os.Build.VERSION.SDK_INT >= 30) display?.displayId ?: android.view.Display.DEFAULT_DISPLAY else @Suppress("DEPRECATION") windowManager.defaultDisplay.displayId
|
||||
dualScreenMode = SessionPrefs.dualScreenMode(this)
|
||||
secondScreenDisplays = SecondScreenDisplays.available(displayManager, ownDisplayId)
|
||||
ownScreen = ownDisplayId.takeIf { it != Display.DEFAULT_DISPLAY }?.let { id ->
|
||||
displayManager.getDisplay(id)?.takeIf { it.isValid }?.let { SecondScreenDisplay(id, "${it.name} · ${it.mode.physicalWidth}×${it.mode.physicalHeight}") }
|
||||
}
|
||||
dualScreenDevice = com.droiddeck.launcher.input.DualScreen.anyDisplay(displayManager, ownDisplayId) != null
|
||||
dualScreenSessions = SessionPrefs.dualScreenSessionMode(this)
|
||||
dualScreenControls = SessionPrefs.dualScreenSessionControls(this)
|
||||
@@ -2433,29 +2331,22 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
else com.droiddeck.launcher.ui.DualScreenPanel.hide(taskId)
|
||||
}
|
||||
|
||||
private fun launchPending(): Boolean = gameLinkReading || (launchCoordinator.hasPending() && !gameLinkTried)
|
||||
private fun launchPending(): Boolean = gameLinkReading || (pendingGameLink != null && !gameLinkTried)
|
||||
|
||||
private fun launchAndroidApp(app: HomeApp.LaunchableApp, displayId: Int?) {
|
||||
val onOwnScreen = displayId == null || displayId == (display?.displayId ?: Display.DEFAULT_DISPLAY)
|
||||
if (onOwnScreen) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, true)
|
||||
val open = {
|
||||
try {
|
||||
HomeApp.launch(this, app, displayId)
|
||||
} catch (_: Exception) {
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
|
||||
val label = secondScreenDisplays.firstOrNull { it.id == displayId }?.label
|
||||
val message = when {
|
||||
displayId == null || displayId == Display.DEFAULT_DISPLAY -> getString(R.string.android_app_open_failed_primary, app.label)
|
||||
label != null -> getString(R.string.android_app_open_failed_on, app.label, label)
|
||||
else -> getString(R.string.android_app_open_failed_display, app.label, displayId)
|
||||
}
|
||||
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show()
|
||||
try {
|
||||
HomeApp.launch(this, app, displayId)
|
||||
} catch (_: Exception) {
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
|
||||
val label = secondScreenDisplays.firstOrNull { it.id == displayId }?.label
|
||||
val message = when {
|
||||
displayId == null || displayId == Display.DEFAULT_DISPLAY -> getString(R.string.android_app_open_failed_primary, app.label)
|
||||
label != null -> getString(R.string.android_app_open_failed_on, app.label, label)
|
||||
else -> getString(R.string.android_app_open_failed_display, app.label, displayId)
|
||||
}
|
||||
}
|
||||
if (displayId != null && displayId == com.droiddeck.launcher.ui.DualScreenPanel.shownOn) {
|
||||
com.droiddeck.launcher.ui.DualScreenPanel.makeRoomForApp(this, displayId, open)
|
||||
} else {
|
||||
open()
|
||||
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2781,7 +2672,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
mic = if (mode == SessionService.MODE_STEAM) mic else null,
|
||||
gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null,
|
||||
storageOptions = storageOptions,
|
||||
storageFat32 = storageFat32,
|
||||
steamLibraries = steamLibraries,
|
||||
foundSteamLibraries = foundSteamLibraries,
|
||||
allFilesAccessMissing = allFilesAccessMissing,
|
||||
@@ -2792,7 +2682,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
steamClientArch = if (mode == SessionService.MODE_STEAM) steamClientArch else null,
|
||||
returnAfterGame = if (mode == SessionService.MODE_STEAM) returnAfterGame else null,
|
||||
shaderPrecache = if (mode == SessionService.MODE_STEAM) shaderPrecache else null,
|
||||
valveProtonOnDemand = if (mode == SessionService.MODE_STEAM) valveProtonOnDemand else null,
|
||||
steamRepairQueued = steamRepairQueued,
|
||||
mangoapp = mangoapp,
|
||||
steamController = if (mode == SessionService.MODE_STEAM) steamController else null,
|
||||
@@ -2900,7 +2789,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
onMangoapp = { on -> SessionPrefs.setMangoapp(this, on); mangoapp = on },
|
||||
onReturnAfterGame = { on -> SessionPrefs.setReturnAfterGame(this, on); returnAfterGame = 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 },
|
||||
onStartupSession = { id ->
|
||||
SessionPrefs.setStartupSession(this, id)
|
||||
@@ -3173,7 +3061,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
steamRepairQueued = SteamRepair.queued(this)
|
||||
mangoapp = SessionPrefs.mangoapp(this)
|
||||
returnAfterGame = SessionPrefs.returnAfterGame(this)
|
||||
valveProtonOnDemand = SessionPrefs.valveProtonOnDemand(this)
|
||||
loadShaderPrecache(mode)
|
||||
steamController = SessionPrefs.steamController(this)
|
||||
startupSession = SessionPrefs.startupSession(this)
|
||||
@@ -3207,12 +3094,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
Thread({
|
||||
drivers.refreshDrivers()
|
||||
val storage = GameStorage.options(this)
|
||||
val fat32 = GameStorage.effective(this)?.path?.let(GameStorage::isFat32) == true
|
||||
val deckyInstalled = if (mode == SessionService.MODE_STEAM) DeckyManager.installed(this) else null
|
||||
val deckySupervisor = mode == SessionService.MODE_STEAM && DeckyManager.supervisorEnabled(this)
|
||||
ui.post {
|
||||
storageOptions = storage
|
||||
storageFat32 = fat32
|
||||
if (mode == SessionService.MODE_STEAM) {
|
||||
decky.deckyInstalled = deckyInstalled
|
||||
decky.deckySupervisor = deckySupervisor
|
||||
@@ -3234,8 +3119,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
SessionPrefs.setGameStorage(this, path, label)
|
||||
gameStorage = path
|
||||
storageFat32 = GameStorage.effective(this)?.path?.let(GameStorage::isFat32) == true
|
||||
if (storageFat32) android.widget.Toast.makeText(this, R.string.main_storage_fat32, android.widget.Toast.LENGTH_LONG).show()
|
||||
checkUsbLink()
|
||||
if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries()
|
||||
}
|
||||
@@ -3325,7 +3208,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
battleNetInstalled = com.droiddeck.launcher.runtime.BattleNet.installed(this)
|
||||
offlineAccount = OfflineMode.account(this)
|
||||
offline = OfflineMode.enabled(this)
|
||||
offlineAuto = OfflineMode.auto(this)
|
||||
installed = LinuxRuntimeInstaller.installedVersion(this)
|
||||
ready = LinuxRuntime.isInstalled(this)
|
||||
vkBridge = SessionPrefs.vkBridge(this)
|
||||
@@ -3461,7 +3343,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
install(release)
|
||||
}
|
||||
|
||||
private fun startSession(intent: Intent, steamSession: Boolean = false, queueIfBlocked: Boolean = false): Boolean {
|
||||
private fun startSession(intent: Intent, steamSession: Boolean = false): Boolean {
|
||||
if (busy || LinuxRuntimeInstaller.isBusy()) return false
|
||||
if (SessionState.installing != null && !SessionState.running) {
|
||||
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
|
||||
@@ -3473,7 +3355,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
refreshPhantomStatus()
|
||||
if (steamSession && PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
|
||||
if (queueIfBlocked) queuedLaunch.queue(intent, System.currentTimeMillis())
|
||||
showPhantomGate = true
|
||||
return false
|
||||
}
|
||||
@@ -3483,64 +3364,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
return true
|
||||
}
|
||||
|
||||
private var notificationsDone: ((Boolean) -> Unit)? = null
|
||||
|
||||
private fun ensureNotifications(done: (Boolean) -> Unit) {
|
||||
if (WirelessAdbPairingService.notificationsEnabled(this)) {
|
||||
done(true)
|
||||
return
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {
|
||||
notificationsDone = done
|
||||
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), REQUEST_NOTIFICATIONS)
|
||||
return
|
||||
}
|
||||
openNotificationSettings()
|
||||
done(false)
|
||||
}
|
||||
|
||||
private fun openNotificationSettings() {
|
||||
android.widget.Toast.makeText(this, R.string.gate_notifications_toast, android.widget.Toast.LENGTH_LONG).show()
|
||||
val appAllowed = getSystemService(android.app.NotificationManager::class.java)?.areNotificationsEnabled() != false
|
||||
val intent = if (appAllowed && WirelessAdbPairingService.channelBlocked(this)) {
|
||||
Intent(android.provider.Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS)
|
||||
.putExtra(android.provider.Settings.EXTRA_CHANNEL_ID, WirelessAdbPairingService.channelId())
|
||||
} else {
|
||||
Intent(android.provider.Settings.ACTION_APP_NOTIFICATION_SETTINGS)
|
||||
}
|
||||
startActivity(intent.putExtra(android.provider.Settings.EXTRA_APP_PACKAGE, packageName).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
}
|
||||
|
||||
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
|
||||
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
|
||||
if (requestCode != REQUEST_NOTIFICATIONS) return
|
||||
val done = notificationsDone ?: return
|
||||
notificationsDone = null
|
||||
val granted = WirelessAdbPairingService.notificationsEnabled(this)
|
||||
if (!granted) openNotificationSettings()
|
||||
done(granted)
|
||||
}
|
||||
|
||||
private val queuedLaunch = com.droiddeck.launcher.session.QueuedLaunch<Intent>(GATE_LAUNCH_MS)
|
||||
private val queuedLaunchRunner = com.droiddeck.launcher.session.QueuedLaunchRunner(
|
||||
queue = queuedLaunch,
|
||||
now = System::currentTimeMillis,
|
||||
blocked = { PhantomProcessLimit.blocksSteam(phantomProcessStatus) },
|
||||
busy = ::steamStartBusy,
|
||||
schedule = { delay, task -> if (delay <= 0L) ui.post(task) else ui.postDelayed(task, delay) },
|
||||
unschedule = ui::removeCallbacks,
|
||||
start = { launch -> startSession(launch, steamSession = true, queueIfBlocked = true) },
|
||||
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. */
|
||||
private fun steamStartBusy(): Boolean = busy || LinuxRuntimeInstaller.isBusy() || com.droiddeck.launcher.session.Onboarding.settling() ||
|
||||
(SessionState.installing != null && !SessionState.running) || com.droiddeck.launcher.storage.StorageState.cleaning
|
||||
|
||||
private fun refreshPhantomStatus() {
|
||||
phantomProcessStatus = PhantomProcessLimit.read(this)
|
||||
if (queuedLaunch.launch != null && !PhantomProcessLimit.blocksSteam(phantomProcessStatus)) showPhantomGate = false
|
||||
queuedLaunchRunner.poke()
|
||||
adbPaired = WirelessAdbFix.hasSavedPairing(this)
|
||||
phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
|
||||
getString(
|
||||
@@ -3552,7 +3377,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
|
||||
private fun openDeveloperOptions(displayId: Int?) {
|
||||
val highlight = if (PhantomProcessLimit.hasDeveloperToggle() &&
|
||||
WirelessAdbPairingService.stage.value == WirelessAdbPairingService.Stage.Idle) "disable_phantom_process_monitor" else "toggle_adb_wireless"
|
||||
WirelessAdbPairingService.stage.value == WirelessAdbPairingService.Stage.Idle) null else "toggle_adb_wireless"
|
||||
val intent = Intent(android.provider.Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
.apply { if (highlight != null) putExtra(":settings:fragment_args_key", highlight) }
|
||||
@@ -3598,7 +3423,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
com.droiddeck.launcher.ui.Motion.refresh(this)
|
||||
com.droiddeck.launcher.ui.DeveloperTools.load(this)
|
||||
com.droiddeck.launcher.ui.NavTabs.load(this)
|
||||
if (!switchLauncherIcon(LauncherIcon.DARK)) restartLauncher()
|
||||
if (!switchLauncherIcon(LauncherIcon.DARK)) recreate()
|
||||
}
|
||||
}, "reset-settings").start()
|
||||
}
|
||||
@@ -3671,13 +3496,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val REQUEST_NOTIFICATIONS = 7103
|
||||
private const val EXTRA_RESTARTED = "com.droiddeck.launcher.extra.RESTARTED"
|
||||
private const val STATE_HOME_CHOICE_OPEN = "home_choice_open"
|
||||
private const val STATE_PENDING_GATE_LAUNCH = "pending_gate_launch"
|
||||
private const val STATE_PENDING_GATE_LAUNCH_AT = "pending_gate_launch_at"
|
||||
private const val GATE_LAUNCH_MS = 15 * 60_000L
|
||||
private const val GATE_LAUNCH_RETRY_MS = 2_000L
|
||||
private const val KEY_PENDING_SESSION_LOG_EXPORT = "pending_session_log_export"
|
||||
private const val STATE_GAME_SPACE_OFFERED = "game_space_offered"
|
||||
private const val TAG = "MainActivity"
|
||||
|
||||
@@ -118,18 +118,12 @@ object HomeWidgets {
|
||||
if (live.size != parsed.size) save(context)
|
||||
}
|
||||
|
||||
private val listeners: MutableSet<Any> = java.util.Collections.newSetFromMap(java.util.IdentityHashMap())
|
||||
|
||||
fun startListening(context: Context) {
|
||||
listeners.add(context)
|
||||
load(context)
|
||||
runCatching { host(context).startListening() }
|
||||
}
|
||||
|
||||
// A restarted launcher starts before the old one stops; the host keeps listening until the last owner stops.
|
||||
fun stopListening(context: Context) {
|
||||
listeners.remove(context)
|
||||
if (listeners.isNotEmpty()) return
|
||||
runCatching { host(context).stopListening() }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.os.Bundle
|
||||
import android.os.SystemClock
|
||||
|
||||
/**
|
||||
* State a restarting launcher passes to its replacement inside this process. Intent extras are not used
|
||||
* because FrontEndActivity is exported and any app could fill them.
|
||||
*/
|
||||
internal object LauncherHandoff {
|
||||
private const val LIFETIME_MS = 10_000L
|
||||
private var state: Bundle? = null
|
||||
private var at = 0L
|
||||
|
||||
@Synchronized
|
||||
fun put(carried: Bundle) {
|
||||
state = carried
|
||||
at = SystemClock.elapsedRealtime()
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun take(): Bundle? {
|
||||
val carried = state
|
||||
state = null
|
||||
return carried?.takeIf { SystemClock.elapsedRealtime() - at <= LIFETIME_MS }
|
||||
}
|
||||
}
|
||||
@@ -93,14 +93,6 @@ class PairingGuideActivity : ComponentActivity() {
|
||||
launchPending = true
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
val stage = WirelessAdbPairingService.stage.value
|
||||
if (isFinishing && (stage is WirelessAdbPairingService.Stage.Waiting || stage is WirelessAdbPairingService.Stage.CodeNeeded)) {
|
||||
WirelessAdbPairingService.cancel(this)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (!launchPending) return
|
||||
|
||||
@@ -49,7 +49,7 @@ internal class ProtonMenu(
|
||||
@VisibleForTesting internal var latestCheck: (Boolean) -> Boolean = { force -> ProtonExtras.checkLatest(activity, force) }
|
||||
@VisibleForTesting internal var experimentalRefresh: () -> List<ExperimentalProtons.Release>? = { ExperimentalProtons.refresh(activity) }
|
||||
@VisibleForTesting internal var installer: (ProtonExtras.Tool, (String, Int) -> Unit) -> String? =
|
||||
{ tool, progress -> ProtonExtras.install(activity, tool, onProgress = progress) }
|
||||
{ tool, progress -> ProtonExtras.install(activity, tool, progress) }
|
||||
|
||||
fun installProton(id: String, automatic: Boolean = false) {
|
||||
val tool = ProtonExtras.tools.firstOrNull { it.id == id } ?: return
|
||||
@@ -156,7 +156,7 @@ internal class ProtonMenu(
|
||||
|
||||
fun refreshProtons() {
|
||||
refreshExperimental()
|
||||
protonRows = ProtonExtras.offered(activity).map {
|
||||
protonRows = ProtonExtras.tools.map {
|
||||
val all = ProtonExtras.installedAll(activity, it)
|
||||
ProtonRow(it.id, it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it))
|
||||
}
|
||||
|
||||
@@ -850,8 +850,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
SessionState.bottomMenu = false
|
||||
SessionState.secondScreenProvisional = false
|
||||
SessionState.secondScreenAutomatic = false
|
||||
SessionState.gameOnBottom = SessionPrefs.dualScreenSessionMode(this) == com.droiddeck.launcher.input.DualScreen.MODE_SWAPPED
|
||||
gameOnBottom = SessionState.gameOnBottom
|
||||
SessionState.gameOnBottom = false
|
||||
gameOnBottom = false
|
||||
}
|
||||
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
|
||||
SessionState.program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
|
||||
@@ -875,10 +875,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
cornerTap = SessionPrefs.drawerCornerTap(this)
|
||||
applyOutputPacing()
|
||||
if (!SessionState.running) {
|
||||
SessionState.followScales = SessionPrefs.followScales(this, displayMode(),
|
||||
com.droiddeck.launcher.session.SessionDisplay.panelSize(this))
|
||||
SessionState.followScreen = followChoice()
|
||||
SessionState.followScale = followScale()
|
||||
}
|
||||
applyFollowChoice()
|
||||
applyFollowOrientation(resources.configuration)
|
||||
goFullscreen()
|
||||
volumeControlStream = android.media.AudioManager.STREAM_MUSIC
|
||||
@@ -1546,10 +1545,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
secondScreenDisplays = secondScreenDisplays,
|
||||
selectedSecondScreenDisplay = selectedSecondScreenDisplay,
|
||||
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
|
||||
onHudOnlyDuringGame = { on ->
|
||||
SessionPrefs.setHudOnlyDuringGame(this@SessionActivity, on)
|
||||
hud.refresh()
|
||||
},
|
||||
onGpuClockPin = { on ->
|
||||
SessionPrefs.setGpuClockPin(this@SessionActivity, on)
|
||||
gpuClockPin = on
|
||||
@@ -2834,7 +2829,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
|
||||
private fun installProton(): String? {
|
||||
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 cancellation = com.droiddeck.launcher.core.Downloader.Cancellation { SessionState.stopRequested }
|
||||
SessionState.installCancellation = cancellation
|
||||
@@ -2847,24 +2841,6 @@ 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) {
|
||||
if (holder !== outputHolder()) return
|
||||
if (installingRuntime || SessionState.stopRequested || ended) return
|
||||
@@ -3015,10 +2991,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
|
||||
private fun followPortrait(): Boolean = glassesScreen == null && SessionPrefs.portrait(this)
|
||||
|
||||
private fun applyFollowChoice() {
|
||||
val scale = SessionState.followScales.let { if (followPortrait()) it.second else it.first }
|
||||
SessionState.followScreen = scale != null
|
||||
SessionState.followScale = scale ?: 1f
|
||||
private fun followScale(): Float {
|
||||
val mode = displayMode()
|
||||
val choice = SessionPrefs.resolutionChoice(this, mode, com.droiddeck.launcher.session.SessionDisplay.panelSize(this), followPortrait())
|
||||
return com.droiddeck.launcher.session.SessionDisplay.followScale(choice) ?: 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) {
|
||||
@@ -3032,7 +3014,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
SessionService.setActivityDisplay(this, sessionActivityDisplayId)
|
||||
}
|
||||
cancelTouchGestures()
|
||||
applyFollowChoice()
|
||||
applyFollowOrientation(newConfig)
|
||||
applyNotchInset()
|
||||
applyUnfoldedControls()
|
||||
@@ -3414,7 +3395,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
if (status == 0) SessionState.takeRelaunch()?.let { next ->
|
||||
next.putExtra(EXTRA_RETURN_HOME, intent.getBooleanExtra(EXTRA_RETURN_HOME, false))
|
||||
next.putExtra(EXTRA_LINK_TASK, intent.getIntExtra(EXTRA_LINK_TASK, -1))
|
||||
relaunch(next)
|
||||
setIntent(next)
|
||||
recreate()
|
||||
return@runOnUiThread
|
||||
}
|
||||
showEnded(status, hint)
|
||||
@@ -3422,16 +3404,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
}, "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?) {
|
||||
if (status == 0 && hint?.evenOnSuccess != true) {
|
||||
finish()
|
||||
@@ -3576,15 +3548,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
|
||||
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
val normalized = com.droiddeck.launcher.input.GuestKeys.normalizeKeyboardEscape(event)
|
||||
if (normalized === event) return dispatchSessionKeyEvent(event)
|
||||
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||
Log.i(TAG, "hardware Esc normalized from Back device=${event.deviceId} scan=${event.scanCode}")
|
||||
}
|
||||
return dispatchSessionKeyEvent(normalized)
|
||||
}
|
||||
|
||||
private fun dispatchSessionKeyEvent(event: KeyEvent): Boolean {
|
||||
if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true
|
||||
when (event.keyCode) {
|
||||
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> {
|
||||
@@ -4442,11 +4405,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
SessionState.secondScreenAutoOpened = false
|
||||
val menuOnBottom = drawerDocked
|
||||
val menuOnTop = drawerOpenState && !drawerDocked
|
||||
if (mode == com.droiddeck.launcher.input.DualScreen.MODE_SWAPPED) {
|
||||
putGameOnBottom(true)
|
||||
} else if (gameOnBottom && mode != com.droiddeck.launcher.input.DualScreen.MODE_OFF) {
|
||||
putGameOnBottom(false)
|
||||
}
|
||||
if (mode == com.droiddeck.launcher.input.DualScreen.MODE_OFF) {
|
||||
if (gameOnBottom) putGameOnBottom(false)
|
||||
if (secondScreenMode != SecondScreenMode.NONE || menuOnBottom) closeSecondScreen(reset = true)
|
||||
@@ -5186,10 +5144,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
private var sessionTouchDown = false
|
||||
private var screenTapsClick = true
|
||||
|
||||
private fun onScreenLeftMouseButtonShown(): Boolean = listOfNotNull(
|
||||
private fun onScreenMouseButtonShown(): Boolean = listOfNotNull(
|
||||
onScreenControls?.inputSurface, bottomInputControls?.inputSurface, unfoldedPanel?.inputSurface, unfoldedDeckSurface,
|
||||
secondScreenPresentation?.controlsView, swappedInputSurface,
|
||||
).any { it.isShown && inputProfile.showsLeftMouseButton(it.inputRole, it.shownElements, stockInputProfile) }
|
||||
).any { it.isShown && inputProfile.showsMouseButton(it.inputRole, it.shownElements, stockInputProfile) }
|
||||
|
||||
override fun onTouchEvent(event: MotionEvent): Boolean = inSurfaceSpace(event) { handleTouch(event) }
|
||||
|
||||
@@ -5225,7 +5183,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
val snapshot = fingerTouchSnapshot(uiBlocking)
|
||||
val route = com.droiddeck.launcher.input.TouchRouter.decide(snapshot)
|
||||
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
|
||||
screenTapsClick = !onScreenLeftMouseButtonShown()
|
||||
screenTapsClick = !onScreenMouseButtonShown()
|
||||
if (::touchpad.isInitialized) touchpad.clicks = screenTapsClick
|
||||
if (::scrollTouch.isInitialized) scrollTouch.clicks = screenTapsClick
|
||||
}
|
||||
@@ -6059,7 +6017,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
|
||||
Log.w(TAG, "ignoring agent start while session phase is ${SessionState.phase}")
|
||||
return
|
||||
}
|
||||
relaunch(android.content.Intent(intent).setClass(this, SessionActivity::class.java))
|
||||
setIntent(intent)
|
||||
recreate()
|
||||
return
|
||||
}
|
||||
if (this.intent.getBooleanExtra(EXTRA_RETURN_HOME, false)) intent.putExtra(EXTRA_RETURN_HOME, true)
|
||||
|
||||
@@ -143,9 +143,9 @@ object AgentSetup {
|
||||
listOf("sh", "-c", "set -e; export DEBIAN_FRONTEND=noninteractive; " +
|
||||
"apt() { apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 \"\$@\"; }; " +
|
||||
"dpkg --configure -a || echo 'Some packages are not configured yet; repairing dependencies'; " +
|
||||
"for i in 1 2 3; do apt -o APT::Update::Error-Mode=any update -q && break; echo 'Some package sources could not be refreshed; retrying'; sleep 3; done; " +
|
||||
"for i in 1 2 3; do apt update -q && break; echo 'Some package sources could not be refreshed; retrying'; sleep 3; done; " +
|
||||
"apt -f install -y --fix-missing; " +
|
||||
"apt install -y --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}")
|
||||
"apt install -y --fix-missing --no-install-recommends git gh adb curl ca-certificates python3; ${harness.install}")
|
||||
}
|
||||
Step.SIGN_IN -> harness.signIn
|
||||
Step.GITHUB -> listOf("dd-gh-login")
|
||||
|
||||
@@ -293,7 +293,6 @@ object DeviceReport {
|
||||
k("Stretch 16:9 to panel", SessionPrefs.stretch16x9(context))
|
||||
k("Avoid notch", SessionPrefs.avoidNotch(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("On-screen controls", SessionPrefs.oscMode(context))
|
||||
k("Touch mode", SessionPrefs.touchMode(context))
|
||||
|
||||
@@ -28,9 +28,7 @@ object DeviceSupport {
|
||||
com.droiddeck.launcher.gpu.GpuInfo.detect().family.name.startsWith("MALI"))
|
||||
}
|
||||
|
||||
fun bridgeUsable(): Boolean = bridgeUsable(adreno(), SystemVulkanDriver.isAvailable())
|
||||
|
||||
internal fun bridgeUsable(adreno: Boolean, systemDriverReady: Boolean): Boolean = !adreno && !systemDriverReady
|
||||
fun bridgeUsable(): Boolean = !adreno() && !SystemVulkanDriver.isAvailable() && File("/dev/mali0").exists()
|
||||
|
||||
fun openDriverActive(context: Context): Boolean {
|
||||
if (adreno()) return false
|
||||
|
||||
@@ -38,8 +38,6 @@ class WirelessAdbPairingService : Service() {
|
||||
private var pairingHost: String? = null
|
||||
private var pairingPort: Int? = null
|
||||
@Volatile private var working = false
|
||||
@Volatile private var limitEnabled = false
|
||||
@Volatile private var session = 0
|
||||
private val timeout = Runnable { finish(Stage.Failed(getString(R.string.adbpair_timed_out))) }
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
@@ -52,15 +50,12 @@ class WirelessAdbPairingService : Service() {
|
||||
onCode(code)
|
||||
}
|
||||
ACTION_CANCEL -> finish(Stage.Idle)
|
||||
else -> begin(intent?.getBooleanExtra(EXTRA_ENABLE_LIMIT, false) == true)
|
||||
else -> begin()
|
||||
}
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
private fun begin(enableLimit: Boolean) {
|
||||
if (working) return
|
||||
session++
|
||||
limitEnabled = enableLimit
|
||||
private fun begin() {
|
||||
pairingHost = null
|
||||
pairingPort = null
|
||||
working = false
|
||||
@@ -73,13 +68,12 @@ class WirelessAdbPairingService : Service() {
|
||||
|
||||
private fun startDiscovery() {
|
||||
stopDiscovery()
|
||||
val owner = session
|
||||
val manager = getSystemService(Context.NSD_SERVICE) as NsdManager
|
||||
val listener = object : NsdManager.DiscoveryListener {
|
||||
override fun onDiscoveryStarted(serviceType: String) = Unit
|
||||
override fun onServiceFound(serviceInfo: NsdServiceInfo) {
|
||||
if (serviceInfo.serviceType?.contains(PAIRING_TYPE) != true) return
|
||||
runCatching { manager.resolveService(serviceInfo, resolveListener(owner)) }
|
||||
runCatching { manager.resolveService(serviceInfo, resolveListener()) }
|
||||
}
|
||||
override fun onServiceLost(serviceInfo: NsdServiceInfo) = Unit
|
||||
override fun onDiscoveryStopped(serviceType: String) = Unit
|
||||
@@ -93,20 +87,18 @@ class WirelessAdbPairingService : Service() {
|
||||
.onFailure { finish(Stage.Failed(getString(R.string.adbpair_discovery_failed, it.localizedMessage.toString()))) }
|
||||
}
|
||||
|
||||
private fun resolveListener(owner: Int): NsdManager.ResolveListener {
|
||||
return object : NsdManager.ResolveListener {
|
||||
private fun resolveListener() = object : NsdManager.ResolveListener {
|
||||
override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) = Unit
|
||||
override fun onServiceResolved(serviceInfo: NsdServiceInfo) {
|
||||
val address = serviceInfo.host ?: return
|
||||
if (!WirelessAdbFix.isLocalAddress(address)) return
|
||||
main.post {
|
||||
if (owner != session || working || current.value == Stage.Done) return@post
|
||||
if (working || current.value == Stage.Done) return@post
|
||||
pairingHost = address.hostAddress
|
||||
pairingPort = serviceInfo.port
|
||||
if (current.value !is Stage.CodeNeeded) show(Stage.CodeNeeded())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun onCode(code: String) {
|
||||
@@ -122,34 +114,29 @@ class WirelessAdbPairingService : Service() {
|
||||
return
|
||||
}
|
||||
working = true
|
||||
val owner = session
|
||||
val enable = limitEnabled
|
||||
show(Stage.Working(getString(R.string.adbpair_pairing)))
|
||||
Thread({
|
||||
val paired = runCatching { kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@WirelessAdbPairingService, WirelessAdbFix.LOOPBACK, port, code) } }
|
||||
if (paired.isFailure) {
|
||||
main.post {
|
||||
working = false
|
||||
if (owner != session) return@post
|
||||
pairingPort = null
|
||||
show(Stage.CodeNeeded(getString(R.string.adbpair_code_rejected)))
|
||||
}
|
||||
return@Thread
|
||||
}
|
||||
main.post {
|
||||
if (owner != session) return@post
|
||||
stopDiscovery()
|
||||
show(Stage.Working(getString(R.string.adbpair_connecting)))
|
||||
}
|
||||
val result = runCatching {
|
||||
val connectPort = WirelessAdbFix.localConnectPort(this)
|
||||
?: error(getString(R.string.adbpair_port_not_found))
|
||||
main.post { if (owner == session) show(Stage.Working(getString(R.string.adbpair_applying))) }
|
||||
WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, enable)
|
||||
main.post { show(Stage.Working(getString(R.string.adbpair_applying))) }
|
||||
WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, false)
|
||||
}
|
||||
main.post {
|
||||
working = false
|
||||
if (owner != session) return@post
|
||||
finish(result.exceptionOrNull()?.let { Stage.Failed(it.localizedMessage ?: getString(R.string.adbpair_command_failed)) } ?: Stage.Done)
|
||||
}
|
||||
}, "wireless-adb-pairing").start()
|
||||
@@ -161,7 +148,6 @@ class WirelessAdbPairingService : Service() {
|
||||
}
|
||||
|
||||
private fun finish(stage: Stage) {
|
||||
session++
|
||||
main.removeCallbacks(timeout)
|
||||
stopDiscovery()
|
||||
publish(stage)
|
||||
@@ -262,7 +248,6 @@ class WirelessAdbPairingService : Service() {
|
||||
private const val ACTION_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE"
|
||||
private const val ACTION_CANCEL = "com.droiddeck.launcher.action.WIRELESS_ADB_CANCEL"
|
||||
private const val KEY_CODE = "code"
|
||||
private const val EXTRA_ENABLE_LIMIT = "enable_limit"
|
||||
private const val TIMEOUT_MS = 5 * 60_000L
|
||||
|
||||
private val current = MutableStateFlow<Stage>(Stage.Idle)
|
||||
@@ -270,10 +255,10 @@ class WirelessAdbPairingService : Service() {
|
||||
|
||||
private fun publish(stage: Stage) { current.value = stage }
|
||||
|
||||
fun start(context: Context, enableLimit: Boolean = false) {
|
||||
fun start(context: Context) {
|
||||
context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID)
|
||||
publish(Stage.Waiting)
|
||||
val intent = Intent(context, WirelessAdbPairingService::class.java).putExtra(EXTRA_ENABLE_LIMIT, enableLimit)
|
||||
val intent = Intent(context, WirelessAdbPairingService::class.java)
|
||||
if (Build.VERSION.SDK_INT >= 26) context.startForegroundService(intent) else context.startService(intent)
|
||||
}
|
||||
|
||||
@@ -286,12 +271,6 @@ class WirelessAdbPairingService : Service() {
|
||||
}
|
||||
|
||||
fun notificationsEnabled(context: Context): Boolean =
|
||||
context.getSystemService(NotificationManager::class.java)?.areNotificationsEnabled() != false && !channelBlocked(context)
|
||||
|
||||
/** The code is typed into a notification on this channel; a channel the user switched off leaves pairing with nothing to type into. */
|
||||
fun channelBlocked(context: Context): Boolean =
|
||||
context.getSystemService(NotificationManager::class.java)?.getNotificationChannel(CHANNEL_ID)?.importance == NotificationManager.IMPORTANCE_NONE
|
||||
|
||||
fun channelId(): String = CHANNEL_ID
|
||||
context.getSystemService(NotificationManager::class.java)?.areNotificationsEnabled() != false
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,6 @@ object AddedGames {
|
||||
val exeUncertain: Boolean = false,
|
||||
val launchOptions: String = "",
|
||||
val single: Boolean = false,
|
||||
val steamProgram: Boolean = true,
|
||||
) {
|
||||
fun folderName(): String = folder.name
|
||||
}
|
||||
@@ -239,7 +238,6 @@ object AddedGames {
|
||||
for (entry in AddedExes.list(context)) {
|
||||
val folder = File(entry.folder)
|
||||
if (folder.path in removed || !folder.isDirectory) continue
|
||||
if (StoreGameSidecar.read(folder)?.isInstalled == false) continue
|
||||
scanGame(context, folder, out, single = entry, reuse = true)
|
||||
}
|
||||
for (folder in libraryDepotInstalls(context)) if (folder.path !in removed) scanGame(context, folder, out, reuse = true)
|
||||
@@ -338,11 +336,7 @@ object AddedGames {
|
||||
val owner = ownerFolder(app, exe)
|
||||
if (owner != null && owner.path !in SessionPrefs.removedAddedGames(app)) {
|
||||
single(app, owner.path)?.takeIf { canonical(it.exe) == path }?.let {
|
||||
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))
|
||||
}
|
||||
if (guestPath(app, exe) != null) AddedExes.put(app, AddedExes.Entry(owner.path, exe.path))
|
||||
return AddResult.Existing(it)
|
||||
}
|
||||
}
|
||||
@@ -448,9 +442,9 @@ object AddedGames {
|
||||
val chosen = picked.takeIf { it.isNotEmpty() }?.let { File(it) }?.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 storeLauncher = sidecar?.takeIf { chosen == null || canonical(chosen) == canonical(it.exeFile(folder)) }
|
||||
val epicLauncher = sidecar?.takeIf { it.store == Store.EPIC && (chosen == null || canonical(chosen) == canonical(it.exeFile(folder))) }
|
||||
?.launcherFile(folder)?.takeIf { it.isFile }
|
||||
val launch = storeLauncher ?: found
|
||||
val launch = epicLauncher ?: if (chosen == null) sidecar?.launcherFile(folder)?.takeIf { it.isFile } ?: found else found
|
||||
val foundGuest = guestPath(context, launch)
|
||||
if (foundGuest == null) { Log.w(TAG, "${folder.name}: the session cannot see ${launch.path}"); return }
|
||||
val autoName = sidecar?.title ?: identifiedName(folder, found) ?: folder.name
|
||||
@@ -476,13 +470,7 @@ object AddedGames {
|
||||
val guestDir = SessionPrefs.addedGameStartIn(context, folder.path).takeIf { sidecar == null && it.isNotEmpty() }
|
||||
?: sidecarDir
|
||||
?: guestPath(context, (if (adopted != null) adopted else launch).parentFile ?: folder) ?: return
|
||||
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) }
|
||||
val steamId = config?.let { steamRoute(it, appId) }
|
||||
out.add(Game(folder, name, exe, guestExe, guestDir, appId,
|
||||
steamId?.toLong() ?: ((appId shl 32) or 0x02000000L), candidates, steamId,
|
||||
source = sidecar?.store?.id ?: Library.ADDED, storeId = sidecar?.id,
|
||||
@@ -492,7 +480,7 @@ object AddedGames {
|
||||
sidecar.store == Store.UBISOFT -> com.droiddeck.launcher.stores.ubisoft.UbisoftConnect.launchOptions(context)
|
||||
else -> ""
|
||||
},
|
||||
single = single != null, steamProgram = steamProgram))
|
||||
single = single != null))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -532,11 +520,6 @@ object AddedGames {
|
||||
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('"')
|
||||
|
||||
internal fun adoptSteamEdits(context: Context, folder: File, record: JSONObject) {
|
||||
@@ -585,7 +568,6 @@ object AddedGames {
|
||||
.append(",\"seen\":").append(SessionPrefs.addedGameExeSeen(context, g.folder.path))
|
||||
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.steamProgram) json.append(",\"route\":false")
|
||||
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)
|
||||
.mapNotNull { (k, f) -> f?.let { file -> artGuestPath(context, file)?.let { k to it } } }
|
||||
|
||||
@@ -13,7 +13,6 @@ object GamesFolderMigration {
|
||||
|
||||
@Synchronized
|
||||
fun run(context: Context) {
|
||||
repathInternalGuest(context)
|
||||
val dirs = SessionPrefs.addedGamesDirs(context)
|
||||
if (dirs.isEmpty()) return
|
||||
val roots = legacyRoots(SessionPrefs.gameFolderBinds(context).map { it.first } + dirs)
|
||||
@@ -59,30 +58,12 @@ object GamesFolderMigration {
|
||||
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> {
|
||||
val hosts = paths.distinct().map { File(it) }
|
||||
val names = hosts.groupingBy { it.name.lowercase() }.eachCount()
|
||||
return hosts.map { host ->
|
||||
val name = host.name.ifEmpty { "games" }
|
||||
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
|
||||
val guestName = if ((names[name.lowercase()] ?: 0) > 1) name + "-" + "%08x".format(CRC32().apply { update(host.path.toByteArray()) }.value).take(4) else name
|
||||
AddedGames.Root(host, "${AddedGames.GUEST_DIR}/$guestName")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,12 +20,6 @@ object SteamRedists {
|
||||
val SCRIPTED = mapOf(
|
||||
72850 to listOf("xact" to "DirectX XACT audio"),
|
||||
489830 to listOf("xact_x64" to "DirectX XACT audio (64-bit)"),
|
||||
// Warband compiles its postFX .fx effects at launch through d3dx9_42; Wine's own d3dcompiler_42 stops with E5017/E5033 on fx_2_0.
|
||||
48700 to listOf("d3dx9" to "DirectX 9 (d3dx9)", "d3dcompiler_42" to "D3DCompiler 42"),
|
||||
// DST's bundled ANGLE compiles SM3 shaders through d3dcompiler_43; DXVK's SM3 parser asserts on what Wine's own one emits.
|
||||
322330 to listOf("d3dcompiler_43" to "D3DCompiler 43"),
|
||||
// EU4 builds its map effects through native d3dx9_43, which calls d3dcompiler_43; Wine's own one fails them with E5005, so the map draws black.
|
||||
236850 to listOf("d3dx9" to "DirectX 9 (d3dx9)", "d3dcompiler_43" to "D3DCompiler 43"),
|
||||
)
|
||||
private val BLOCK = Regex("\"SharedDepots\"\\s*\\{([^}]*)\\}", RegexOption.IGNORE_CASE)
|
||||
private val ENTRY = Regex("\"(\\d+)\"\\s+\"\\d+\"")
|
||||
|
||||
@@ -45,8 +45,9 @@ internal class XrealLink internal constructor(
|
||||
if (msgId == VitureProtocol.MSG_GET_IMU) return true
|
||||
val valid = when (msgId) {
|
||||
VitureProtocol.MSG_GET_DISPLAY -> true
|
||||
VitureProtocol.MSG_DISPLAY -> model.supportsDisplayMode(value)
|
||||
VitureProtocol.MSG_BRIGHTNESS -> model.hardwareControls && value in 0..model.brightnessMax
|
||||
VitureProtocol.MSG_DISPLAY -> if (model.stereoOnlyControl) value == 5 || value == XrealModel.NATIVE_60HZ
|
||||
else value in 2..5 || value == XrealModel.NATIVE_60HZ
|
||||
VitureProtocol.MSG_BRIGHTNESS -> !model.stereoOnlyControl && value in 0..9
|
||||
VitureProtocol.MSG_FILM -> !model.stereoOnlyControl && value in 0..1
|
||||
else -> false
|
||||
}
|
||||
@@ -63,12 +64,12 @@ internal class XrealLink internal constructor(
|
||||
channels = connector.connect()
|
||||
connection.set(channels)
|
||||
if (!running) break
|
||||
val control = XrealControl(channels, model = model)
|
||||
val control = XrealControl(channels, stereoOnly = model.stereoOnlyControl)
|
||||
listener.onValue(VitureProtocol.MSG_GET_DISPLAY, control.display())
|
||||
val current = channels
|
||||
reports = Thread({
|
||||
try {
|
||||
var filter = XrealOrientationFilter(model)
|
||||
var filter = XrealOrientationFilter(model.flipsYz)
|
||||
var wasTracking = false
|
||||
var lastSensor = System.nanoTime()
|
||||
while (running && connection.get() === current) {
|
||||
@@ -77,7 +78,7 @@ internal class XrealLink internal constructor(
|
||||
if (sample != null) {
|
||||
lastSensor = System.nanoTime()
|
||||
val enabled = tracking
|
||||
if (enabled && !wasTracking) filter = XrealOrientationFilter(model)
|
||||
if (enabled && !wasTracking) filter = XrealOrientationFilter(model.flipsYz)
|
||||
wasTracking = enabled
|
||||
if (enabled) filter.update(sample)?.let {
|
||||
if (running && ready && tracking && connection.get() === current)
|
||||
@@ -154,9 +155,8 @@ internal class XrealLink internal constructor(
|
||||
internal class XrealControl(
|
||||
private val channels: XrealChannels,
|
||||
private val settleDelayMs: Long = 150,
|
||||
private val model: XrealModel = XrealModel.ONE_S,
|
||||
private val stereoOnly: Boolean = false,
|
||||
) {
|
||||
private val stereoOnly get() = model.stereoOnlyControl
|
||||
private var transaction = 0
|
||||
private fun exchange(command: Int, value: Int? = null): ByteArray {
|
||||
transaction = if (transaction == Int.MAX_VALUE) 1 else transaction + 1
|
||||
@@ -172,7 +172,7 @@ internal class XrealControl(
|
||||
fun display(): Int {
|
||||
if (stereoOnly) return stereoDisplay()
|
||||
val reply = exchange(XrealProtocol.GET_DISPLAY)
|
||||
return XrealProtocol.numeric(reply)?.takeIf(model::supportsDisplayMode)
|
||||
return XrealProtocol.numeric(reply)?.takeIf { it in 2..5 || it == XrealModel.NATIVE_60HZ }
|
||||
?: throw IOException("Unsupported XREAL display response: ${reply.take(32).joinToString("") { "%02x".format(it) }}")
|
||||
}
|
||||
private fun stereoDisplay(): Int {
|
||||
@@ -187,7 +187,6 @@ internal class XrealControl(
|
||||
}
|
||||
}
|
||||
fun changeDisplay(mode: Int): Int {
|
||||
require(model.supportsDisplayMode(mode))
|
||||
val stereo = mode == 5
|
||||
set(XrealProtocol.SET_INPUT, if (stereo) 1 else 0)
|
||||
val current = awaitDisplay { (it == 5) == stereo }
|
||||
|
||||
@@ -4,7 +4,6 @@ internal class XrealModel private constructor(
|
||||
override val name: String,
|
||||
val family: Family,
|
||||
override val diagonalFovDeg: Float,
|
||||
private val native60Hz: Int = NATIVE_60HZ,
|
||||
) : GlassesModel {
|
||||
enum class Family {
|
||||
ONE_S,
|
||||
@@ -15,25 +14,23 @@ internal class XrealModel private constructor(
|
||||
override val controllable = true
|
||||
override val brightnessMax = 9
|
||||
override val volumeMax = 0
|
||||
override val hasSunblock get() = !stereoOnlyControl
|
||||
override val hardwareControls get() = !stereoOnlyControl
|
||||
override val hasSunblock get() = family == Family.ONE_S
|
||||
override val hardwareControls get() = family == Family.ONE_S
|
||||
override val sbs90 = false
|
||||
override val rates2d get() = if (stereoOnlyControl) listOf(60) else super.rates2d
|
||||
override val rates2d get() = if (family == Family.ONE_S) super.rates2d else listOf(60)
|
||||
|
||||
val stereoOnlyControl get() = family != Family.ONE_S && this !== ONE_PRO_PLUS
|
||||
|
||||
internal fun supportsDisplayMode(mode: Int) = if (stereoOnlyControl) mode == 5 || mode == native60Hz
|
||||
else mode in 3..5 || mode == native60Hz || (this === ONE_S && mode == 2)
|
||||
// Only the 1S has been exercised with SET_DISPLAY; the Aura is known to reboot on an unexpected index.
|
||||
val stereoOnlyControl get() = family != Family.ONE_S
|
||||
|
||||
// The Aura reports x right, y up, z back; the rest of the One family is a half turn about x from it.
|
||||
val flipsYz get() = family != Family.AURA
|
||||
|
||||
override fun mode(hz: Int, sbs: Boolean) = when {
|
||||
sbs -> 5
|
||||
stereoOnlyControl -> native60Hz
|
||||
stereoOnlyControl -> NATIVE_60HZ
|
||||
hz >= 120 -> 4
|
||||
hz >= 90 -> 3
|
||||
else -> native60Hz
|
||||
else -> NATIVE_60HZ
|
||||
}
|
||||
override fun modeForStep(step: Int): Int? = null
|
||||
|
||||
@@ -47,7 +44,7 @@ internal class XrealModel private constructor(
|
||||
val ONE_S = XrealModel("XREAL 1S", Family.ONE_S, 52f)
|
||||
val ONE = XrealModel("XREAL One", Family.ONE, 50f)
|
||||
val ONE_PRO = XrealModel("XREAL One Pro", Family.ONE, 57f)
|
||||
val ONE_PRO_PLUS = XrealModel("XREAL One Pro+", Family.ONE, 57f, 9)
|
||||
val ONE_PRO_PLUS = XrealModel("XREAL One Pro+", Family.ONE, 57f)
|
||||
val AURA = XrealModel("XREAL Aura", Family.AURA, 70f)
|
||||
|
||||
// The odd product ids one below these are the glasses' recovery mode.
|
||||
|
||||
@@ -2,18 +2,13 @@ package com.droiddeck.launcher.glasses
|
||||
|
||||
import kotlin.math.abs
|
||||
|
||||
internal class XrealOrientationFilter(private val model: XrealModel = XrealModel.ONE_S) {
|
||||
internal class XrealOrientationFilter(private val flipYz: Boolean = true) {
|
||||
private val fusion = ImuFusion()
|
||||
private val sensorToDisplay = if (model === XrealModel.ONE_PRO_PLUS)
|
||||
Quaternion.fromAxisAngle(Vec3(1f, 0f, 0f), Math.toRadians(35.0).toFloat()) else null
|
||||
|
||||
fun update(sample: XrealProtocol.Sample): FloatArray? = fusion.update(sample.timeNs,
|
||||
sample.accel.headAxes(), sample.gyro.headAxes())
|
||||
|
||||
private fun Vec3.headAxes(): Vec3 {
|
||||
val display = sensorToDisplay?.rotate(this) ?: this
|
||||
return if (model.flipsYz) Vec3(display.x, -display.y, -display.z) else display
|
||||
}
|
||||
private fun Vec3.headAxes() = if (flipYz) Vec3(x, -y, -z) else this
|
||||
}
|
||||
|
||||
internal class ImuFusion {
|
||||
|
||||
@@ -7,8 +7,7 @@ object SocNames {
|
||||
"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",
|
||||
"SM8550" to "Snapdragon 8 Gen 2", "QCS8550" to "Snapdragon 8 Gen 2", "SM8650" to "Snapdragon 8 Gen 3",
|
||||
"SM8750" to "Snapdragon 8 Elite", "SM8750P" to "Snapdragon 8 Elite",
|
||||
"SM8850" to "Snapdragon 8 Elite Gen 5",
|
||||
"SM8750" to "Snapdragon 8 Elite", "SM8850" to "Snapdragon 8 Elite Gen 5",
|
||||
"SM8975" to "Snapdragon 8 Elite Extreme Gen 6",
|
||||
"SM7325" to "Snapdragon 778G", "SM7450" to "Snapdragon 7 Gen 1", "SM7550" to "Snapdragon 7 Gen 3",
|
||||
"SM6375" to "Snapdragon 695",
|
||||
@@ -24,8 +23,7 @@ object SocNames {
|
||||
val sdk = if (Build.VERSION.SDK_INT >= 31) Build.SOC_MODEL.takeIf { it != Build.UNKNOWN }.orEmpty() else ""
|
||||
return listOf(prop("ro.soc.model"), prop("ro.vendor.qti.soc_model"), sdk, prop("ro.fota.platform"))
|
||||
.map { it.trim() }
|
||||
.firstOrNull { it.isNotEmpty() && !it.equals(Build.UNKNOWN, ignoreCase = true) && !Regex("(?i)^msm_\\d").containsMatchIn(it) }
|
||||
.orEmpty()
|
||||
.firstOrNull { it.isNotEmpty() && !Regex("(?i)^msm_\\d").containsMatchIn(it) }.orEmpty()
|
||||
}
|
||||
|
||||
internal fun normalizedModel(model: String): String = model.trim().uppercase().removePrefix("QTI ").trim()
|
||||
@@ -33,13 +31,6 @@ object SocNames {
|
||||
fun name(model: String, platform: String = GpuInfo.systemProperty("ro.board.platform")): String? =
|
||||
MODELS[normalizedModel(model)] ?: 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 {
|
||||
val name = name(model, platform)
|
||||
return when {
|
||||
|
||||
@@ -308,7 +308,8 @@ public final class TurnipDriver {
|
||||
}
|
||||
}
|
||||
if (chosen != null && !chosen.isEmpty()) {
|
||||
if (SessionPrefs.INSTANCE.displayDriverFromAuto(context)
|
||||
if (SessionPrefs.GPU_DRIVERS_AUTO.equals(SessionPrefs.INSTANCE.gpuDriverMode(context))
|
||||
&& SessionPrefs.INSTANCE.gpuAutoInstalled(context).contains(chosen)
|
||||
&& 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");
|
||||
return null;
|
||||
|
||||
@@ -44,35 +44,6 @@ class DroidDeckHudHost(context: Context) {
|
||||
private var protonPid = 0
|
||||
private var proton = ""
|
||||
@Volatile private var lastWindow: String? = null
|
||||
@Volatile private var lastCompositorFrameNanos = 0L
|
||||
@Volatile private var lastVisibilityGameActive = false
|
||||
private var candidateGameActive = false
|
||||
private var candidateGameActiveSinceNs = 0L
|
||||
private var stableGameActive = false
|
||||
|
||||
private fun isGameActive(): Boolean {
|
||||
val now = System.nanoTime()
|
||||
val compositorLive = lastCompositorFrameNanos > 0L &&
|
||||
now - lastCompositorFrameNanos <= 1_000_000_000L
|
||||
val detected = if (feed.live) {
|
||||
feed.steamFocusKnown && !feed.steamFocused
|
||||
} else {
|
||||
compositorLive
|
||||
}
|
||||
|
||||
if (detected != candidateGameActive) {
|
||||
candidateGameActive = detected
|
||||
candidateGameActiveSinceNs = now
|
||||
}
|
||||
|
||||
if (detected != stableGameActive &&
|
||||
now - candidateGameActiveSinceNs >= GAME_ACTIVITY_STABLE_NS
|
||||
) {
|
||||
stableGameActive = detected
|
||||
}
|
||||
|
||||
return stableGameActive
|
||||
}
|
||||
|
||||
var onPresentingWindowChanged: (() -> Unit)? = null
|
||||
|
||||
@@ -95,12 +66,6 @@ class DroidDeckHudHost(context: Context) {
|
||||
}
|
||||
|
||||
override fun onGameFrame() {
|
||||
if (feed.live && (!feed.steamFocusKnown || feed.steamFocused)) return
|
||||
lastCompositorFrameNanos = System.nanoTime()
|
||||
feed.onCompositorFrame(lastCompositorFrameNanos)
|
||||
}
|
||||
|
||||
override fun onCompositorFrame() {
|
||||
feed.onCompositorFrame(System.nanoTime())
|
||||
}
|
||||
}
|
||||
@@ -108,9 +73,7 @@ class DroidDeckHudHost(context: Context) {
|
||||
private val frameCallback = object : Choreographer.FrameCallback {
|
||||
override fun doFrame(frameTimeNanos: Long) {
|
||||
if (!running || !polling) return
|
||||
reconcileGameActivity()
|
||||
if (feed.poll(System.nanoTime())) view?.onFrames()
|
||||
reconcileGameActivity()
|
||||
Choreographer.getInstance().postFrameCallback(this)
|
||||
}
|
||||
}
|
||||
@@ -188,7 +151,7 @@ class DroidDeckHudHost(context: Context) {
|
||||
|
||||
fun refresh() {
|
||||
applyConfig()
|
||||
if (!enabled) stop() else if (!running) start() else applyShown()
|
||||
if (!enabled) stop() else if (!running) start()
|
||||
}
|
||||
|
||||
fun start() {
|
||||
@@ -218,26 +181,14 @@ class DroidDeckHudHost(context: Context) {
|
||||
applyShown()
|
||||
}
|
||||
|
||||
private fun reconcileGameActivity() {
|
||||
if (!SessionPrefs.hudOnlyDuringGame(context)) {
|
||||
lastVisibilityGameActive = isGameActive()
|
||||
return
|
||||
}
|
||||
if (isGameActive() != lastVisibilityGameActive) applyShown()
|
||||
}
|
||||
|
||||
private fun applyShown() {
|
||||
if (!running) return
|
||||
val onlyDuringGame = SessionPrefs.hudOnlyDuringGame(context)
|
||||
val gameActive = isGameActive()
|
||||
val show = !hidden && !backgrounded && (!onlyDuringGame || gameActive)
|
||||
val show = !hidden && !backgrounded
|
||||
view?.visibility = if (show) View.VISIBLE else View.GONE
|
||||
showing = show
|
||||
lastVisibilityGameActive = gameActive
|
||||
val shouldPoll = !hidden && !backgrounded && (show || onlyDuringGame)
|
||||
if (shouldPoll != polling) {
|
||||
polling = shouldPoll
|
||||
if (shouldPoll) Choreographer.getInstance().postFrameCallback(frameCallback)
|
||||
if (show != polling) {
|
||||
polling = show
|
||||
if (show) Choreographer.getInstance().postFrameCallback(frameCallback)
|
||||
else Choreographer.getInstance().removeFrameCallback(frameCallback)
|
||||
}
|
||||
}
|
||||
@@ -581,7 +532,6 @@ class DroidDeckHudHost(context: Context) {
|
||||
}
|
||||
|
||||
companion object {
|
||||
private const val GAME_ACTIVITY_STABLE_NS = 350_000_000L
|
||||
private const val DOCK_OVERHANG = 0.4f
|
||||
private const val PREVIEW_FROM = 0.55f
|
||||
private const val STRIP_PULL_ACROSS_DP = 360f
|
||||
|
||||
@@ -183,8 +183,6 @@ internal class GameFrameFeed(
|
||||
private set
|
||||
@Volatile var steamFocused = false
|
||||
private set
|
||||
@Volatile var steamFocusKnown = false
|
||||
private set
|
||||
@Volatile var pid = 0
|
||||
private set
|
||||
@Volatile var outputWidth = 0
|
||||
@@ -200,16 +198,10 @@ internal class GameFrameFeed(
|
||||
val compositorAdded = compositorFrames != seenCompositorFrames
|
||||
seenCompositorFrames = compositorFrames
|
||||
if (handle == 0L) {
|
||||
if (nowNs < nextOpenNs) {
|
||||
|
||||
return compositorAdded
|
||||
}
|
||||
if (nowNs < nextOpenNs) return compositorAdded
|
||||
nextOpenNs = nowNs + REOPEN_NS
|
||||
handle = runCatching { HudFrames.nativeOpen(file.path) }.getOrDefault(0L)
|
||||
if (handle == 0L) {
|
||||
|
||||
return compositorAdded
|
||||
}
|
||||
if (handle == 0L) return compositorAdded
|
||||
HudFrames.nativePoll(handle, frametimes, times)
|
||||
}
|
||||
val n = HudFrames.nativePoll(handle, frametimes, times)
|
||||
@@ -227,7 +219,6 @@ internal class GameFrameFeed(
|
||||
fromGamescope = false
|
||||
}
|
||||
if (n <= 0 && nowNs - maxOf(lastRingFrameNs, nextOpenNs - REOPEN_NS) > STALE_NS) close()
|
||||
|
||||
if (nowNs - lastInfoNs >= INFO_NS) {
|
||||
lastInfoNs = nowNs
|
||||
readInfo()
|
||||
@@ -259,7 +250,6 @@ internal class GameFrameFeed(
|
||||
}
|
||||
|
||||
fun close() {
|
||||
fromGamescope = false
|
||||
if (handle != 0L) HudFrames.nativeClose(handle)
|
||||
handle = 0L
|
||||
}
|
||||
@@ -275,7 +265,6 @@ internal class GameFrameFeed(
|
||||
outputHeight = info[2]
|
||||
refreshMilliHz = info[3]
|
||||
steamFocused = info[4] != 0
|
||||
steamFocusKnown = true
|
||||
engine = engineLabel(name)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -14,8 +14,7 @@ object DualScreen {
|
||||
const val MODE_AUTO = "auto"
|
||||
const val MODE_ON = "on"
|
||||
const val MODE_OFF = "off"
|
||||
const val MODE_SWAPPED = "swapped"
|
||||
val modes = listOf(MODE_AUTO, MODE_ON, MODE_SWAPPED, MODE_OFF)
|
||||
val modes = listOf(MODE_AUTO, MODE_ON, MODE_OFF)
|
||||
private const val TYPE_INTERNAL = 1
|
||||
private const val TYPE_EXTERNAL = 2
|
||||
private val knownModels = setOf("retroid pocket duo", "ayn thor")
|
||||
@@ -100,7 +99,7 @@ object DualScreen {
|
||||
fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, mode: String = SessionPrefs.dualScreenMode(context)): Display? =
|
||||
when (mode) {
|
||||
MODE_OFF -> null
|
||||
MODE_ON, MODE_SWAPPED -> internalDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId)
|
||||
MODE_ON -> internalDisplay(displayManager, primaryDisplayId) ?: anyDisplay(displayManager, primaryDisplayId)
|
||||
else -> if (dockedToDisplay(displayManager, primaryDisplayId)) null else builtInDisplay(displayManager, primaryDisplayId)
|
||||
}?.takeUnless { taken(it.displayId) }
|
||||
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
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 java.io.File;
|
||||
@@ -132,16 +128,6 @@ public class FakeInputWriter {
|
||||
|
||||
private static final Object RING_LOCK = new Object();
|
||||
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 {
|
||||
System.loadLibrary("sdnative");
|
||||
@@ -170,9 +156,6 @@ public class FakeInputWriter {
|
||||
private boolean hasChanges = false;
|
||||
private boolean pendingFullResend = 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) {
|
||||
this.slot = slot;
|
||||
@@ -728,12 +711,10 @@ public class FakeInputWriter {
|
||||
}
|
||||
|
||||
public synchronized void close() {
|
||||
cancelPacedWrite();
|
||||
isOpen = false;
|
||||
}
|
||||
|
||||
public synchronized void reset() {
|
||||
cancelPacedWrite();
|
||||
if (!isOpen && !open())
|
||||
return;
|
||||
|
||||
@@ -841,53 +822,6 @@ public class FakeInputWriter {
|
||||
}
|
||||
|
||||
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())
|
||||
return;
|
||||
|
||||
@@ -911,10 +845,10 @@ public class FakeInputWriter {
|
||||
hasChanges = true;
|
||||
}
|
||||
|
||||
int lx = stickValue(state.leftX);
|
||||
int ly = stickValue(state.leftY);
|
||||
int rx = stickValue(state.rightX);
|
||||
int ry = stickValue(state.rightY);
|
||||
int lx = (int) (state.leftX * 32767);
|
||||
int ly = (int) (state.leftY * 32767);
|
||||
int rx = (int) (state.rightX * 32767);
|
||||
int ry = (int) (state.rightY * 32767);
|
||||
|
||||
if (forceResend || lx != prevThumbLX) {
|
||||
prevThumbLX = lx;
|
||||
@@ -933,8 +867,8 @@ public class FakeInputWriter {
|
||||
writeEvent(EV_ABS, ABS_RY, ry);
|
||||
}
|
||||
|
||||
int tl = triggerValue(state.leftTrigger);
|
||||
int tr = triggerValue(state.rightTrigger);
|
||||
int tl = (int) (state.leftTrigger * 255);
|
||||
int tr = (int) (state.rightTrigger * 255);
|
||||
if (forceResend || tl != prevTriggerL) {
|
||||
prevTriggerL = tl;
|
||||
writeEvent(EV_ABS, ABS_BRAKE, tl);
|
||||
@@ -961,8 +895,6 @@ public class FakeInputWriter {
|
||||
if (!flushBuffer()) {
|
||||
Log.e(TAG, "Gamepad write error: fake input mmap ring unavailable");
|
||||
pendingFullResend = true;
|
||||
} else {
|
||||
axisPacing.wrote(SystemClock.uptimeMillis());
|
||||
}
|
||||
}
|
||||
forceResend = false;
|
||||
|
||||
@@ -3,12 +3,6 @@ package com.droiddeck.launcher.input
|
||||
import android.view.KeyEvent
|
||||
|
||||
object GuestKeys {
|
||||
fun normalizeKeyboardEscape(event: KeyEvent): KeyEvent {
|
||||
if (!isKeyboardEscape(event.keyCode, event.scanCode)) return event
|
||||
return KeyEvent(event.downTime, event.eventTime, event.action, KeyEvent.KEYCODE_ESCAPE,
|
||||
event.repeatCount, event.metaState, event.deviceId, event.scanCode, event.flags, event.source)
|
||||
}
|
||||
|
||||
/** Sends [event] as evdev presses, with Shift around characters typed by a keyboard that has no Shift key; false when it has no evdev code. */
|
||||
fun send(event: KeyEvent, sendKey: (code: Int, down: Boolean) -> Unit): Boolean {
|
||||
val down = event.action == KeyEvent.ACTION_DOWN
|
||||
|
||||
@@ -53,14 +53,14 @@ data class InputProfile(
|
||||
fun elementClickAction(role: InputRole, element: InputSurfaceElement): InputAction = clicks[role]?.get(element.id)
|
||||
?: defaultElementClick(element, elementAction(role, element.id, element.control)) { action(role, it) }
|
||||
|
||||
fun showsLeftMouseButton(role: InputRole, shown: List<InputSurfaceElement>, stock: InputProfile): Boolean = shown.any { element ->
|
||||
fun showsMouseButton(role: InputRole, shown: List<InputSurfaceElement>, stock: InputProfile): Boolean = shown.any { element ->
|
||||
val action = elementAction(role, element.id, element.control).takeIf {
|
||||
elements[role]?.get(element.id) != stock.elements[role]?.get(element.id) || it != stock.elementAction(role, element.id, element.control)
|
||||
}
|
||||
val click = elementClickAction(role, element).takeIf {
|
||||
clicks[role]?.get(element.id) != stock.clicks[role]?.get(element.id) || it != stock.elementClickAction(role, element)
|
||||
}
|
||||
listOfNotNull(action, click).any { it is InputAction.MouseButton && it.code == PointerGestures.BTN_LEFT }
|
||||
listOfNotNull(action, click).any { it is InputAction.MouseButton && it.validFor(element.control) }
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
@@ -0,0 +1,609 @@
|
||||
package com.droiddeck.launcher.input.bt
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.bluetooth.BluetoothAdapter
|
||||
import android.bluetooth.BluetoothDevice
|
||||
import android.bluetooth.BluetoothGatt
|
||||
import android.bluetooth.BluetoothGattCallback
|
||||
import android.bluetooth.BluetoothGattCharacteristic
|
||||
import android.bluetooth.BluetoothGattDescriptor
|
||||
import android.bluetooth.BluetoothGattServer
|
||||
import android.bluetooth.BluetoothGattServerCallback
|
||||
import android.bluetooth.BluetoothGattService
|
||||
import android.bluetooth.BluetoothManager
|
||||
import android.bluetooth.BluetoothProfile
|
||||
import android.bluetooth.le.AdvertiseData
|
||||
import android.bluetooth.le.AdvertisingSet
|
||||
import android.bluetooth.le.AdvertisingSetCallback
|
||||
import android.bluetooth.le.AdvertisingSetParameters
|
||||
import android.content.BroadcastReceiver
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.content.IntentFilter
|
||||
import android.os.Build
|
||||
import android.os.Handler
|
||||
import android.os.HandlerThread
|
||||
import android.os.ParcelUuid
|
||||
import android.os.SystemClock
|
||||
import android.os.VibrationEffect
|
||||
import android.os.Vibrator
|
||||
import android.util.Log
|
||||
import kotlinx.coroutines.flow.MutableStateFlow
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import java.util.ArrayDeque
|
||||
import java.util.UUID
|
||||
|
||||
@SuppressLint("MissingPermission")
|
||||
object BtGamepad {
|
||||
enum class Phase { OFF, STARTING, BLUETOOTH_OFF, UNSUPPORTED, READY, CONNECTING, CONNECTED }
|
||||
|
||||
data class Status(val phase: Phase, val host: String? = null, val lightbar: Int? = null, val name: String? = null)
|
||||
|
||||
private const val TAG = "BtGamepad"
|
||||
|
||||
private val _status = MutableStateFlow(Status(Phase.OFF))
|
||||
val status: StateFlow<Status> = _status
|
||||
|
||||
private var handler: Handler? = null
|
||||
private var app: Context? = null
|
||||
private var server: BluetoothGattServer? = null
|
||||
private var advertising = false
|
||||
private var profile = BtPadProfile.GENERIC
|
||||
private var encoder: BtPadEncoder = profile.encoder()
|
||||
private val pendingServices = ArrayDeque<BluetoothGattService>()
|
||||
private val reportRefs = HashMap<BluetoothGattCharacteristic, Pair<Int, Int>>()
|
||||
private val inputChars = HashMap<Int, BluetoothGattCharacteristic>()
|
||||
private val longReads = HashMap<Pair<String, BluetoothGattCharacteristic>, ByteArray>()
|
||||
private val preparedWrites = HashMap<BluetoothGattCharacteristic, ByteArray>()
|
||||
private var host: BluetoothDevice? = null
|
||||
private var priorityLink: BluetoothGatt? = null
|
||||
private var notifyPending = false
|
||||
private var dirty = false
|
||||
private var mtu = 23
|
||||
private val latest = BtPadState()
|
||||
private val sent = BtPadState()
|
||||
private var sentOnce = false
|
||||
private var vibrator: Vibrator? = null
|
||||
@Volatile private var running = false
|
||||
private var pairingUntil = 0L
|
||||
private var pendingHost: BluetoothDevice? = null
|
||||
private var fastLinkPending = false
|
||||
private var notifiedAt = 0L
|
||||
private const val NOTIFY_TIMEOUT_MS = 100L
|
||||
private const val PAIRING_WINDOW_MS = 120_000L
|
||||
private const val MAX_MTU = 517
|
||||
private const val FAST_LINK_DELAY_MS = 1_500L
|
||||
|
||||
fun start(context: Context, p: BtPadProfile) {
|
||||
val h = handler ?: init(context)
|
||||
h.post {
|
||||
running = true
|
||||
if (server != null && p == profile) {
|
||||
val attached = host
|
||||
if (attached != null) publish(Phase.CONNECTED, attached) else publish(Phase.READY)
|
||||
startAdvertising()
|
||||
} else {
|
||||
close()
|
||||
profile = p
|
||||
publish(Phase.STARTING)
|
||||
open()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun init(context: Context): Handler {
|
||||
val ctx = context.applicationContext
|
||||
app = ctx
|
||||
vibrator = ctx.getSystemService(Vibrator::class.java)
|
||||
val t = HandlerThread("bt-gamepad").apply { start() }
|
||||
val h = Handler(t.looper)
|
||||
handler = h
|
||||
val receiver = object : BroadcastReceiver() {
|
||||
override fun onReceive(c: Context, intent: Intent) {
|
||||
when (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1)) {
|
||||
BluetoothAdapter.STATE_ON -> h.post { if (running) open() }
|
||||
BluetoothAdapter.STATE_TURNING_OFF, BluetoothAdapter.STATE_OFF -> h.post {
|
||||
close()
|
||||
publish(Phase.BLUETOOTH_OFF)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.registerReceiver(receiver, IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED), null, h)
|
||||
val bonds = object : BroadcastReceiver() {
|
||||
override fun onReceive(c: Context, intent: Intent) {
|
||||
if (intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1) != BluetoothDevice.BOND_BONDED) return
|
||||
h.post {
|
||||
val waiting = pendingHost ?: return@post
|
||||
if (waiting.bondState == BluetoothDevice.BOND_BONDED) attach(waiting)
|
||||
}
|
||||
}
|
||||
}
|
||||
ctx.registerReceiver(bonds, IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED), null, h)
|
||||
return h
|
||||
}
|
||||
|
||||
fun stop() {
|
||||
val h = handler ?: return
|
||||
h.post {
|
||||
running = false
|
||||
rumble(0, 0)
|
||||
pairingUntil = 0
|
||||
keepScanning()
|
||||
stopAdvertising()
|
||||
h.removeCallbacks(periodic)
|
||||
dropFastLink()
|
||||
pendingHost?.let { d -> runCatching { server?.cancelConnection(d) } }
|
||||
pendingHost = null
|
||||
host?.let { d -> runCatching { server?.cancelConnection(d) } }
|
||||
host = null
|
||||
longReads.clear()
|
||||
_status.value = Status(Phase.OFF)
|
||||
}
|
||||
}
|
||||
|
||||
fun switchProfile(p: BtPadProfile) {
|
||||
val h = handler ?: return
|
||||
h.post {
|
||||
if (p == profile && server != null) return@post
|
||||
profile = p
|
||||
close()
|
||||
publish(Phase.STARTING)
|
||||
h.postDelayed(::open, 300)
|
||||
}
|
||||
}
|
||||
|
||||
fun update(s: BtPadState) {
|
||||
val h = handler ?: return
|
||||
synchronized(latest) { latest.set(s) }
|
||||
h.post(::sendIfChanged)
|
||||
}
|
||||
|
||||
fun openPairingWindow() {
|
||||
val h = handler ?: return
|
||||
h.post {
|
||||
pairingUntil = System.currentTimeMillis() + PAIRING_WINDOW_MS
|
||||
keepScanning()
|
||||
if (host == null) {
|
||||
stopAdvertising()
|
||||
startAdvertising()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun keepScanning() {
|
||||
val adapter = adapter() ?: return
|
||||
val h = handler ?: return
|
||||
h.removeCallbacks(scanTick)
|
||||
if (host != null || System.currentTimeMillis() > pairingUntil) {
|
||||
runCatching { if (adapter.isDiscovering) adapter.cancelDiscovery() }
|
||||
return
|
||||
}
|
||||
runCatching { if (!adapter.isDiscovering) adapter.startDiscovery() }
|
||||
h.postDelayed(scanTick, 2_000)
|
||||
}
|
||||
|
||||
private val scanTick = Runnable { keepScanning() }
|
||||
|
||||
fun disconnect() {
|
||||
handler?.post { host?.let { d -> server?.cancelConnection(d) } }
|
||||
}
|
||||
|
||||
private fun manager() = app?.getSystemService(Context.BLUETOOTH_SERVICE) as? BluetoothManager
|
||||
|
||||
private fun adapter(): BluetoothAdapter? = manager()?.adapter
|
||||
|
||||
private fun open() {
|
||||
val ctx = app ?: return
|
||||
if (server != null || !running) return
|
||||
val manager = manager()
|
||||
val adapter = manager?.adapter
|
||||
if (adapter == null || !ctx.packageManager.hasSystemFeature("android.hardware.bluetooth_le")) {
|
||||
publish(Phase.UNSUPPORTED)
|
||||
return
|
||||
}
|
||||
if (!adapter.isEnabled) {
|
||||
publish(Phase.BLUETOOTH_OFF)
|
||||
return
|
||||
}
|
||||
if (adapter.bluetoothLeAdvertiser == null) {
|
||||
publish(Phase.UNSUPPORTED)
|
||||
return
|
||||
}
|
||||
encoder = profile.encoder()
|
||||
sentOnce = false
|
||||
val s = runCatching { manager.openGattServer(ctx, serverCallback) }
|
||||
.onFailure { Log.w(TAG, "no GATT server", it) }.getOrNull()
|
||||
if (s == null) {
|
||||
publish(Phase.UNSUPPORTED)
|
||||
return
|
||||
}
|
||||
server = s
|
||||
pendingServices.clear()
|
||||
pendingServices.add(deviceInfoService())
|
||||
pendingServices.add(hidService())
|
||||
addNextService()
|
||||
}
|
||||
|
||||
private fun close() {
|
||||
stopAdvertising()
|
||||
pairingUntil = 0
|
||||
keepScanning()
|
||||
dropFastLink()
|
||||
server?.let { s ->
|
||||
runCatching { manager()?.getConnectedDevices(BluetoothProfile.GATT_SERVER)?.forEach { s.cancelConnection(it) } }
|
||||
runCatching { s.clearServices(); s.close() }
|
||||
}
|
||||
server = null
|
||||
host = null
|
||||
pendingHost = null
|
||||
notifyPending = false
|
||||
dirty = false
|
||||
reportRefs.clear()
|
||||
inputChars.clear()
|
||||
longReads.clear()
|
||||
preparedWrites.clear()
|
||||
}
|
||||
|
||||
private fun addNextService() {
|
||||
val s = server ?: return
|
||||
val next = pendingServices.pollFirst()
|
||||
if (next == null) {
|
||||
Log.i(TAG, "${profile.id}: services ready")
|
||||
startAdvertising()
|
||||
return
|
||||
}
|
||||
if (!s.addService(next)) {
|
||||
Log.w(TAG, "addService ${next.uuid} refused")
|
||||
publish(Phase.UNSUPPORTED)
|
||||
}
|
||||
}
|
||||
|
||||
private fun deviceInfoService(): BluetoothGattService {
|
||||
val service = BluetoothGattService(uuid16(0x180A), BluetoothGattService.SERVICE_TYPE_PRIMARY)
|
||||
val pnp = BtPadEncoder.bytes(0x02, profile.vendorId and 0xFF, profile.vendorId shr 8,
|
||||
profile.productId and 0xFF, profile.productId shr 8, profile.version and 0xFF, profile.version shr 8)
|
||||
service.addCharacteristic(readOnly(0x2A50, pnp))
|
||||
service.addCharacteristic(readOnly(0x2A29, "DroidDeck".toByteArray()))
|
||||
return service
|
||||
}
|
||||
|
||||
private fun hidService(): BluetoothGattService {
|
||||
val service = BluetoothGattService(uuid16(0x1812), BluetoothGattService.SERVICE_TYPE_PRIMARY)
|
||||
service.addCharacteristic(readOnly(0x2A4A, BtPadEncoder.bytes(0x11, 0x01, 0x00, 0x02)))
|
||||
service.addCharacteristic(readOnly(0x2A4B, encoder.descriptor))
|
||||
service.addCharacteristic(BluetoothGattCharacteristic(uuid16(0x2A4C),
|
||||
BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE, BluetoothGattCharacteristic.PERMISSION_WRITE))
|
||||
for ((id, type) in encoder.reports) {
|
||||
val props = when (type) {
|
||||
BtPadEncoder.INPUT -> BluetoothGattCharacteristic.PROPERTY_READ or BluetoothGattCharacteristic.PROPERTY_NOTIFY
|
||||
BtPadEncoder.OUTPUT -> BluetoothGattCharacteristic.PROPERTY_READ or BluetoothGattCharacteristic.PROPERTY_WRITE or
|
||||
BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE
|
||||
else -> BluetoothGattCharacteristic.PROPERTY_READ or BluetoothGattCharacteristic.PROPERTY_WRITE
|
||||
}
|
||||
val chr = BluetoothGattCharacteristic(uuid16(0x2A4D), props,
|
||||
BluetoothGattCharacteristic.PERMISSION_READ or BluetoothGattCharacteristic.PERMISSION_WRITE)
|
||||
if (type == BtPadEncoder.INPUT) {
|
||||
chr.addDescriptor(cccd())
|
||||
inputChars[id] = chr
|
||||
}
|
||||
val ref = BluetoothGattDescriptor(uuid16(0x2908), BluetoothGattDescriptor.PERMISSION_READ)
|
||||
@Suppress("DEPRECATION")
|
||||
ref.value = BtPadEncoder.bytes(id, type)
|
||||
chr.addDescriptor(ref)
|
||||
reportRefs[chr] = id to type
|
||||
service.addCharacteristic(chr)
|
||||
}
|
||||
return service
|
||||
}
|
||||
|
||||
private fun readOnly(uuid: Int, value: ByteArray): BluetoothGattCharacteristic {
|
||||
val chr = BluetoothGattCharacteristic(uuid16(uuid), BluetoothGattCharacteristic.PROPERTY_READ, BluetoothGattCharacteristic.PERMISSION_READ)
|
||||
@Suppress("DEPRECATION")
|
||||
chr.value = value
|
||||
return chr
|
||||
}
|
||||
|
||||
private fun cccd() = BluetoothGattDescriptor(uuid16(0x2902),
|
||||
BluetoothGattDescriptor.PERMISSION_READ or BluetoothGattDescriptor.PERMISSION_WRITE)
|
||||
|
||||
private fun uuid16(v: Int): UUID = UUID.fromString("%08x-0000-1000-8000-00805f9b34fb".format(v))
|
||||
|
||||
private fun startAdvertising() {
|
||||
val advertiser = adapter()?.bluetoothLeAdvertiser ?: return
|
||||
if (advertising || server == null || host != null || !running) return
|
||||
val params = AdvertisingSetParameters.Builder()
|
||||
.setLegacyMode(true)
|
||||
.setConnectable(true)
|
||||
.setScannable(true)
|
||||
.setInterval(AdvertisingSetParameters.INTERVAL_LOW)
|
||||
.setTxPowerLevel(AdvertisingSetParameters.TX_POWER_HIGH)
|
||||
.build()
|
||||
val data = AdvertiseData.Builder()
|
||||
.addServiceUuid(ParcelUuid(uuid16(0x1812)))
|
||||
.setIncludeDeviceName(true)
|
||||
.build()
|
||||
advertising = runCatching { advertiser.startAdvertisingSet(params, data, null, null, null, advertiseCallback); true }
|
||||
.onFailure { Log.w(TAG, "advertising refused", it) }.getOrDefault(false)
|
||||
if (!advertising) publish(Phase.UNSUPPORTED)
|
||||
}
|
||||
|
||||
private fun stopAdvertising() {
|
||||
if (!advertising) return
|
||||
advertising = false
|
||||
runCatching { adapter()?.bluetoothLeAdvertiser?.stopAdvertisingSet(advertiseCallback) }
|
||||
}
|
||||
|
||||
private val advertiseCallback = object : AdvertisingSetCallback() {
|
||||
override fun onAdvertisingSetStarted(set: AdvertisingSet?, txPower: Int, status: Int) {
|
||||
Log.i(TAG, "advertising status $status")
|
||||
handler?.post {
|
||||
if (status == ADVERTISE_SUCCESS) {
|
||||
if (host == null) publish(Phase.READY)
|
||||
} else {
|
||||
advertising = false
|
||||
publish(Phase.UNSUPPORTED)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private val serverCallback = object : BluetoothGattServerCallback() {
|
||||
override fun onServiceAdded(status: Int, service: BluetoothGattService) {
|
||||
handler?.post {
|
||||
if (status != BluetoothGatt.GATT_SUCCESS) {
|
||||
Log.w(TAG, "service ${service.uuid} failed: $status")
|
||||
publish(Phase.UNSUPPORTED)
|
||||
} else addNextService()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onConnectionStateChange(device: BluetoothDevice, status: Int, newState: Int) {
|
||||
handler?.post {
|
||||
Log.i(TAG, "${device.address}: state $newState status $status bond ${device.bondState}")
|
||||
if (newState == BluetoothProfile.STATE_CONNECTED) {
|
||||
stopAdvertising()
|
||||
if (!running) {
|
||||
server?.cancelConnection(device)
|
||||
return@post
|
||||
}
|
||||
mtu = 23
|
||||
if (device.bondState == BluetoothDevice.BOND_BONDED) attach(device)
|
||||
else if (host == null) publish(Phase.CONNECTING, device)
|
||||
} else if (newState == BluetoothProfile.STATE_DISCONNECTED && pendingHost == device && host == null) {
|
||||
pendingHost = null
|
||||
publish(Phase.READY)
|
||||
startAdvertising()
|
||||
} else if (newState == BluetoothProfile.STATE_DISCONNECTED && host == device) {
|
||||
host = null
|
||||
rumble(0, 0)
|
||||
dropFastLink()
|
||||
publish(Phase.READY)
|
||||
startAdvertising()
|
||||
} else if (newState == BluetoothProfile.STATE_DISCONNECTED && host == null) {
|
||||
publish(Phase.READY)
|
||||
startAdvertising()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onMtuChanged(device: BluetoothDevice, newMtu: Int) {
|
||||
handler?.post {
|
||||
mtu = newMtu
|
||||
Log.i(TAG, "mtu $newMtu")
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCharacteristicReadRequest(device: BluetoothDevice, requestId: Int, offset: Int, chr: BluetoothGattCharacteristic) {
|
||||
handler?.post {
|
||||
val key = device.address to chr
|
||||
val value = if (offset > 0) longReads[key] ?: valueOf(chr, device) else valueOf(chr, device).also { longReads[key] = it }
|
||||
val reply = if (offset >= value.size) ByteArray(0) else value.copyOfRange(offset, value.size)
|
||||
server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, reply)
|
||||
if (chr.uuid == uuid16(0x2A4B)) attach(device)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDescriptorReadRequest(device: BluetoothDevice, requestId: Int, offset: Int, descriptor: BluetoothGattDescriptor) {
|
||||
handler?.post {
|
||||
@Suppress("DEPRECATION")
|
||||
val value = descriptor.value ?: if (descriptor.uuid == uuid16(0x2902)) BtPadEncoder.bytes(1, 0) else ByteArray(0)
|
||||
val reply = if (offset >= value.size) ByteArray(0) else value.copyOfRange(offset, value.size)
|
||||
server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, reply)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDescriptorWriteRequest(device: BluetoothDevice, requestId: Int, descriptor: BluetoothGattDescriptor,
|
||||
preparedWrite: Boolean, responseNeeded: Boolean, offset: Int, value: ByteArray) {
|
||||
handler?.post {
|
||||
if (responseNeeded) server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value)
|
||||
if (descriptor.uuid == uuid16(0x2902) && descriptor.characteristic in reportRefs && value.isNotEmpty() &&
|
||||
value[0].toInt() and 1 != 0) {
|
||||
attach(device)
|
||||
handler?.postDelayed({ startFastLink(device) }, FAST_LINK_DELAY_MS)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override fun onCharacteristicWriteRequest(device: BluetoothDevice, requestId: Int, chr: BluetoothGattCharacteristic,
|
||||
preparedWrite: Boolean, responseNeeded: Boolean, offset: Int, value: ByteArray) {
|
||||
handler?.post {
|
||||
if (device == host && preparedWrite) {
|
||||
val old = preparedWrites[chr] ?: ByteArray(0)
|
||||
val merged = old.copyOf(maxOf(old.size, offset + value.size))
|
||||
value.copyInto(merged, offset)
|
||||
preparedWrites[chr] = merged
|
||||
} else if (device == host) written(chr, value)
|
||||
if (responseNeeded) server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onExecuteWrite(device: BluetoothDevice, requestId: Int, execute: Boolean) {
|
||||
handler?.post {
|
||||
if (execute && device == host) preparedWrites.forEach { (chr, v) -> written(chr, v) }
|
||||
preparedWrites.clear()
|
||||
server?.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, 0, null)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onNotificationSent(device: BluetoothDevice, status: Int) {
|
||||
handler?.post {
|
||||
notifyPending = false
|
||||
if (dirty) sendNow()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun valueOf(chr: BluetoothGattCharacteristic, device: BluetoothDevice): ByteArray {
|
||||
val ref = reportRefs[chr]
|
||||
if (ref == null) {
|
||||
@Suppress("DEPRECATION")
|
||||
return chr.value ?: ByteArray(0)
|
||||
}
|
||||
val (id, type) = ref
|
||||
return when (type) {
|
||||
BtPadEncoder.INPUT -> if (id == encoder.inputId() && device == host) encoder.input(current()) else ByteArray(0)
|
||||
BtPadEncoder.FEATURE -> {
|
||||
host?.let { d -> handler?.postDelayed({ startFastLink(d) }, FAST_LINK_DELAY_MS) }
|
||||
encoder.feature(id).also { Log.i(TAG, "feature 0x%02x read -> %d".format(id, it?.size ?: -1)) } ?: ByteArray(0)
|
||||
}
|
||||
else -> ByteArray(0)
|
||||
}
|
||||
}
|
||||
|
||||
private fun written(chr: BluetoothGattCharacteristic, value: ByteArray) {
|
||||
val (id, type) = reportRefs[chr] ?: return
|
||||
when (type) {
|
||||
BtPadEncoder.FEATURE -> {
|
||||
Log.i(TAG, "feature 0x%02x write %d bytes".format(id, value.size))
|
||||
encoder.setFeature(id, value)
|
||||
}
|
||||
BtPadEncoder.OUTPUT -> feedback(encoder.output(id, value))
|
||||
}
|
||||
}
|
||||
|
||||
private fun attach(device: BluetoothDevice) {
|
||||
if (host != null || !running) return
|
||||
if (device.bondState != BluetoothDevice.BOND_BONDED) {
|
||||
pendingHost = device
|
||||
publish(Phase.CONNECTING, device)
|
||||
return
|
||||
}
|
||||
pendingHost = null
|
||||
host = device
|
||||
stopAdvertising()
|
||||
pairingUntil = 0
|
||||
keepScanning()
|
||||
sentOnce = false
|
||||
notifyPending = false
|
||||
Log.i(TAG, "host ${device.address} attached")
|
||||
publish(Phase.CONNECTED, device)
|
||||
fastLinkPending = true
|
||||
handler?.removeCallbacks(periodic)
|
||||
handler?.post(periodic)
|
||||
}
|
||||
|
||||
private fun startFastLink(device: BluetoothDevice) {
|
||||
if (host != device || !fastLinkPending) return
|
||||
fastLinkPending = false
|
||||
requestFastLink(device)
|
||||
}
|
||||
|
||||
private fun requestFastLink(device: BluetoothDevice) {
|
||||
val ctx = app ?: return
|
||||
dropFastLink()
|
||||
priorityLink = runCatching {
|
||||
device.connectGatt(ctx, false, object : BluetoothGattCallback() {
|
||||
override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
|
||||
if (newState == BluetoothProfile.STATE_CONNECTED && !gatt.requestMtu(MAX_MTU)) {
|
||||
gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onMtuChanged(gatt: BluetoothGatt, newMtu: Int, status: Int) {
|
||||
handler?.post {
|
||||
if (newMtu > mtu) mtu = newMtu
|
||||
Log.i(TAG, "link mtu $newMtu")
|
||||
}
|
||||
gatt.requestConnectionPriority(BluetoothGatt.CONNECTION_PRIORITY_HIGH)
|
||||
}
|
||||
}, BluetoothDevice.TRANSPORT_LE)
|
||||
}.getOrNull()
|
||||
}
|
||||
|
||||
private fun dropFastLink() {
|
||||
priorityLink?.let { runCatching { it.disconnect(); it.close() } }
|
||||
priorityLink = null
|
||||
}
|
||||
|
||||
private fun current(): BtPadState = BtPadState().also { s -> synchronized(latest) { s.set(latest) } }
|
||||
|
||||
private fun sendIfChanged() {
|
||||
if (encoder.periodMs > 0) return
|
||||
if (sentOnce && current().sameAs(sent)) return
|
||||
sendNow()
|
||||
}
|
||||
|
||||
private fun sendNow() {
|
||||
val s = server ?: return
|
||||
val device = host ?: return
|
||||
if (notifyPending && SystemClock.elapsedRealtime() - notifiedAt < NOTIFY_TIMEOUT_MS) {
|
||||
dirty = true
|
||||
return
|
||||
}
|
||||
val state = current()
|
||||
val (id, value) = encoder.report(state, mtu - 3)
|
||||
val chr = inputChars[id] ?: return
|
||||
val ok = runCatching {
|
||||
if (Build.VERSION.SDK_INT >= 33) {
|
||||
s.notifyCharacteristicChanged(device, chr, false, value) == BluetoothGatt.GATT_SUCCESS
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
chr.value = value
|
||||
@Suppress("DEPRECATION")
|
||||
s.notifyCharacteristicChanged(device, chr, false)
|
||||
}
|
||||
}.getOrDefault(false)
|
||||
dirty = !ok
|
||||
notifyPending = ok
|
||||
notifiedAt = SystemClock.elapsedRealtime()
|
||||
if (ok) {
|
||||
sent.set(state)
|
||||
sentOnce = true
|
||||
}
|
||||
}
|
||||
|
||||
private val periodic: Runnable = object : Runnable {
|
||||
override fun run() {
|
||||
val h = handler ?: return
|
||||
if (host == null) return
|
||||
if (encoder.periodMs > 0 || dirty) sendNow()
|
||||
h.postDelayed(this, if (encoder.periodMs > 0) encoder.periodMs else 50)
|
||||
}
|
||||
}
|
||||
|
||||
private fun feedback(f: BtFeedback?) {
|
||||
f ?: return
|
||||
if (f.strong >= 0) rumble(f.strong, f.weak)
|
||||
if (f.lightbar != null) _status.value = _status.value.copy(lightbar = f.lightbar)
|
||||
}
|
||||
|
||||
private fun rumble(strong: Int, weak: Int) {
|
||||
val v = vibrator ?: return
|
||||
val amplitude = maxOf(strong, weak * 2 / 3).coerceIn(0, 255)
|
||||
runCatching {
|
||||
if (amplitude == 0) v.cancel()
|
||||
else v.vibrate(VibrationEffect.createOneShot(1_000, amplitude))
|
||||
}
|
||||
}
|
||||
|
||||
private fun publish(phase: Phase, device: BluetoothDevice? = null) {
|
||||
if (!running) {
|
||||
_status.value = Status(Phase.OFF)
|
||||
return
|
||||
}
|
||||
val name = device?.let { runCatching { it.name }.getOrNull() ?: it.address }
|
||||
val own = runCatching { adapter()?.name }.getOrNull()
|
||||
_status.value = Status(phase, name, _status.value.lightbar.takeIf { phase == Phase.CONNECTED }, own)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,559 @@
|
||||
package com.droiddeck.launcher.input.bt
|
||||
|
||||
import java.util.zip.CRC32
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
class BtPadState {
|
||||
@JvmField var buttons = 0
|
||||
@JvmField var lx = 0f
|
||||
@JvmField var ly = 0f
|
||||
@JvmField var rx = 0f
|
||||
@JvmField var ry = 0f
|
||||
@JvmField var lt = 0f
|
||||
@JvmField var rt = 0f
|
||||
@JvmField var lpx = 0f
|
||||
@JvmField var lpy = 0f
|
||||
@JvmField var rpx = 0f
|
||||
@JvmField var rpy = 0f
|
||||
|
||||
fun isDown(bit: Int) = buttons and bit != 0
|
||||
|
||||
fun set(other: BtPadState) {
|
||||
buttons = other.buttons; lx = other.lx; ly = other.ly; rx = other.rx; ry = other.ry; lt = other.lt; rt = other.rt
|
||||
lpx = other.lpx; lpy = other.lpy; rpx = other.rpx; rpy = other.rpy
|
||||
}
|
||||
|
||||
fun merge(a: BtPadState, b: BtPadState) {
|
||||
buttons = a.buttons or b.buttons
|
||||
lx = stronger(a.lx, b.lx); ly = stronger(a.ly, b.ly)
|
||||
rx = stronger(a.rx, b.rx); ry = stronger(a.ry, b.ry)
|
||||
lt = maxOf(a.lt, b.lt, if (isDown(LT)) 1f else 0f)
|
||||
rt = maxOf(a.rt, b.rt, if (isDown(RT)) 1f else 0f)
|
||||
val left = if (b.isDown(LPAD_TOUCH)) b else a
|
||||
lpx = left.lpx; lpy = left.lpy
|
||||
val right = if (b.isDown(RPAD_TOUCH)) b else a
|
||||
rpx = right.rpx; rpy = right.rpy
|
||||
}
|
||||
|
||||
fun sameAs(o: BtPadState) = buttons == o.buttons && lx == o.lx && ly == o.ly && rx == o.rx && ry == o.ry && lt == o.lt && rt == o.rt &&
|
||||
lpx == o.lpx && lpy == o.lpy && rpx == o.rpx && rpy == o.rpy
|
||||
|
||||
fun hat(): Int {
|
||||
val x = (if (isDown(RIGHT)) 1 else 0) - (if (isDown(LEFT)) 1 else 0)
|
||||
val y = (if (isDown(DOWN)) 1 else 0) - (if (isDown(UP)) 1 else 0)
|
||||
return when {
|
||||
x == 0 && y == -1 -> 0
|
||||
x == 1 && y == -1 -> 1
|
||||
x == 1 && y == 0 -> 2
|
||||
x == 1 && y == 1 -> 3
|
||||
x == 0 && y == 1 -> 4
|
||||
x == -1 && y == 1 -> 5
|
||||
x == -1 && y == 0 -> 6
|
||||
x == -1 && y == -1 -> 7
|
||||
else -> -1
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
const val A = 1 shl 0
|
||||
const val B = 1 shl 1
|
||||
const val X = 1 shl 2
|
||||
const val Y = 1 shl 3
|
||||
const val LB = 1 shl 4
|
||||
const val RB = 1 shl 5
|
||||
const val LT = 1 shl 6
|
||||
const val RT = 1 shl 7
|
||||
const val SELECT = 1 shl 8
|
||||
const val START = 1 shl 9
|
||||
const val GUIDE = 1 shl 10
|
||||
const val L3 = 1 shl 11
|
||||
const val R3 = 1 shl 12
|
||||
const val UP = 1 shl 13
|
||||
const val DOWN = 1 shl 14
|
||||
const val LEFT = 1 shl 15
|
||||
const val RIGHT = 1 shl 16
|
||||
const val L4 = 1 shl 17
|
||||
const val R4 = 1 shl 18
|
||||
const val L5 = 1 shl 19
|
||||
const val R5 = 1 shl 20
|
||||
const val TOUCHPAD = 1 shl 21
|
||||
const val SHARE = 1 shl 22
|
||||
const val LPAD_TOUCH = 1 shl 23
|
||||
const val RPAD_TOUCH = 1 shl 24
|
||||
const val LPAD_CLICK = 1 shl 25
|
||||
const val RPAD_CLICK = 1 shl 26
|
||||
|
||||
private fun stronger(a: Float, b: Float) = if (Math.abs(b) > Math.abs(a)) b else a
|
||||
}
|
||||
}
|
||||
|
||||
class BtFeedback(val strong: Int, val weak: Int, val lightbar: Int? = null)
|
||||
|
||||
enum class BtPadProfile(val id: String, val vendorId: Int, val productId: Int, val version: Int) {
|
||||
GENERIC("generic", 0x1209, 0x0001, 0x0100),
|
||||
XBOX("xbox", 0x045E, 0x0B13, 0x0509),
|
||||
DUALSHOCK4("dualshock4", 0x054C, 0x09CC, 0x0100),
|
||||
DUALSENSE("dualsense", 0x054C, 0x0CE6, 0x0100),
|
||||
STEAM("steam", 0x28DE, 0x1303, 0x0100);
|
||||
|
||||
fun encoder(): BtPadEncoder = when (this) {
|
||||
GENERIC -> GenericEncoder()
|
||||
XBOX -> XboxEncoder()
|
||||
DUALSHOCK4 -> DualShock4Encoder()
|
||||
DUALSENSE -> DualSenseEncoder()
|
||||
STEAM -> SteamControllerEncoder()
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun byId(id: String?) = entries.firstOrNull { it.id == id } ?: GENERIC
|
||||
}
|
||||
}
|
||||
|
||||
abstract class BtPadEncoder {
|
||||
abstract val descriptor: ByteArray
|
||||
abstract val reports: List<Pair<Int, Int>>
|
||||
abstract fun inputId(): Int
|
||||
abstract fun input(s: BtPadState): ByteArray
|
||||
open val periodMs = 0L
|
||||
|
||||
open fun report(s: BtPadState, limit: Int): Pair<Int, ByteArray> {
|
||||
val v = input(s)
|
||||
return inputId() to if (v.size > limit) v.copyOf(limit) else v
|
||||
}
|
||||
open fun feature(id: Int): ByteArray? = null
|
||||
open fun setFeature(id: Int, data: ByteArray) {}
|
||||
open fun output(id: Int, data: ByteArray): BtFeedback? = null
|
||||
|
||||
protected fun axis8(v: Float) = ((v.coerceIn(-1f, 1f) + 1f) * 127.5f).roundToInt().coerceIn(0, 255)
|
||||
protected fun trigger8(v: Float) = (v.coerceIn(0f, 1f) * 255f).roundToInt()
|
||||
|
||||
protected fun ByteArray.le16(at: Int, v: Int) { this[at] = v.toByte(); this[at + 1] = (v shr 8).toByte() }
|
||||
protected fun ByteArray.le32(at: Int, v: Long) { for (i in 0 until 4) this[at + i] = (v shr (8 * i)).toByte() }
|
||||
|
||||
protected fun ByteArray.sealCrc(seed: Int, id: Int): ByteArray {
|
||||
val crc = CRC32()
|
||||
crc.update(seed)
|
||||
crc.update(id)
|
||||
crc.update(this, 0, size - 4)
|
||||
le32(size - 4, crc.value)
|
||||
return this
|
||||
}
|
||||
|
||||
|
||||
companion object {
|
||||
const val INPUT = 1
|
||||
const val OUTPUT = 2
|
||||
const val FEATURE = 3
|
||||
|
||||
fun bytes(vararg v: Int) = ByteArray(v.size) { v[it].toByte() }
|
||||
}
|
||||
}
|
||||
|
||||
private class GenericEncoder : BtPadEncoder() {
|
||||
override val reports = listOf(1 to INPUT)
|
||||
|
||||
override val descriptor = bytes(
|
||||
0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, 0x85, 0x01,
|
||||
0x05, 0x09, 0x19, 0x01, 0x29, 0x18, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x18, 0x81, 0x02,
|
||||
0x05, 0x01, 0x09, 0x39, 0x15, 0x00, 0x25, 0x07, 0x35, 0x00, 0x46, 0x3B, 0x01, 0x65, 0x14, 0x75, 0x04, 0x95, 0x01, 0x81, 0x42,
|
||||
0x65, 0x00, 0x75, 0x04, 0x95, 0x01, 0x81, 0x03,
|
||||
0x09, 0x30, 0x09, 0x31, 0x09, 0x32, 0x09, 0x35, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x04, 0x81, 0x02,
|
||||
0x05, 0x02, 0x09, 0xC5, 0x09, 0xC4, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x02, 0x81, 0x02,
|
||||
0xC0,
|
||||
)
|
||||
|
||||
override fun inputId() = 1
|
||||
|
||||
override fun input(s: BtPadState): ByteArray {
|
||||
var b = 0
|
||||
GENERIC_ORDER.forEachIndexed { i, bit -> if (s.isDown(bit)) b = b or (1 shl i) }
|
||||
val hat = s.hat().let { if (it < 0) 8 else it }
|
||||
return bytes(
|
||||
b and 0xFF, (b shr 8) and 0xFF, (b shr 16) and 0xFF, hat,
|
||||
axis8(s.lx), axis8(s.ly), axis8(s.rx), axis8(s.ry), trigger8(s.lt), trigger8(s.rt),
|
||||
)
|
||||
}
|
||||
|
||||
companion object {
|
||||
private val GENERIC_ORDER = intArrayOf(
|
||||
BtPadState.A, BtPadState.B, 0, BtPadState.X, BtPadState.Y, 0, BtPadState.LB, BtPadState.RB,
|
||||
BtPadState.LT, BtPadState.RT, BtPadState.SELECT, BtPadState.START, BtPadState.GUIDE, BtPadState.L3, BtPadState.R3, 0,
|
||||
BtPadState.L4, BtPadState.R4, BtPadState.L5, BtPadState.R5, BtPadState.TOUCHPAD, BtPadState.SHARE, 0, 0,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private class XboxEncoder : BtPadEncoder() {
|
||||
override val reports = listOf(1 to INPUT, 3 to OUTPUT)
|
||||
|
||||
override val descriptor = bytes(
|
||||
0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, 0x85, 0x01,
|
||||
0x09, 0x01, 0xA1, 0x00, 0x09, 0x30, 0x09, 0x31, 0x15, 0x00, 0x27, 0xFF, 0xFF, 0x00, 0x00, 0x95, 0x02, 0x75, 0x10, 0x81, 0x02, 0xC0,
|
||||
0x09, 0x01, 0xA1, 0x00, 0x09, 0x32, 0x09, 0x35, 0x15, 0x00, 0x27, 0xFF, 0xFF, 0x00, 0x00, 0x95, 0x02, 0x75, 0x10, 0x81, 0x02, 0xC0,
|
||||
0x05, 0x02, 0x09, 0xC5, 0x15, 0x00, 0x26, 0xFF, 0x03, 0x95, 0x01, 0x75, 0x0A, 0x81, 0x02, 0x15, 0x00, 0x25, 0x00, 0x75, 0x06, 0x95, 0x01, 0x81, 0x03,
|
||||
0x05, 0x02, 0x09, 0xC4, 0x15, 0x00, 0x26, 0xFF, 0x03, 0x95, 0x01, 0x75, 0x0A, 0x81, 0x02, 0x15, 0x00, 0x25, 0x00, 0x75, 0x06, 0x95, 0x01, 0x81, 0x03,
|
||||
0x05, 0x01, 0x09, 0x39, 0x15, 0x01, 0x25, 0x08, 0x35, 0x00, 0x46, 0x3B, 0x01, 0x66, 0x14, 0x00, 0x75, 0x04, 0x95, 0x01, 0x81, 0x42,
|
||||
0x75, 0x04, 0x95, 0x01, 0x15, 0x00, 0x25, 0x00, 0x35, 0x00, 0x45, 0x00, 0x65, 0x00, 0x81, 0x03,
|
||||
0x05, 0x09, 0x19, 0x01, 0x29, 0x0F, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x0F, 0x81, 0x02,
|
||||
0x15, 0x00, 0x25, 0x00, 0x75, 0x01, 0x95, 0x01, 0x81, 0x03,
|
||||
0x05, 0x0C, 0x0A, 0xB2, 0x00, 0x15, 0x00, 0x25, 0x01, 0x95, 0x01, 0x75, 0x01, 0x81, 0x02,
|
||||
0x15, 0x00, 0x25, 0x00, 0x75, 0x07, 0x95, 0x01, 0x81, 0x03,
|
||||
0x05, 0x0F, 0x09, 0x21, 0x85, 0x03, 0xA1, 0x02,
|
||||
0x09, 0x97, 0x15, 0x00, 0x25, 0x01, 0x75, 0x04, 0x95, 0x01, 0x91, 0x02,
|
||||
0x15, 0x00, 0x25, 0x00, 0x75, 0x04, 0x95, 0x01, 0x91, 0x03,
|
||||
0x09, 0x70, 0x15, 0x00, 0x25, 0x64, 0x75, 0x08, 0x95, 0x04, 0x91, 0x02,
|
||||
0x09, 0x50, 0x66, 0x01, 0x10, 0x55, 0x0E, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x01, 0x91, 0x02,
|
||||
0x09, 0xA7, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x01, 0x91, 0x02,
|
||||
0x65, 0x00, 0x55, 0x00, 0x09, 0x7C, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x01, 0x91, 0x02,
|
||||
0xC0, 0xC0,
|
||||
)
|
||||
|
||||
override fun inputId() = 1
|
||||
|
||||
override fun input(s: BtPadState): ByteArray {
|
||||
val r = ByteArray(16)
|
||||
r.le16(0, axis16(s.lx)); r.le16(2, axis16(s.ly)); r.le16(4, axis16(s.rx)); r.le16(6, axis16(s.ry))
|
||||
r.le16(8, (s.lt.coerceIn(0f, 1f) * 1023f).roundToInt())
|
||||
r.le16(10, (s.rt.coerceIn(0f, 1f) * 1023f).roundToInt())
|
||||
r[12] = (s.hat() + 1).toByte()
|
||||
var b = 0
|
||||
XBOX_ORDER.forEachIndexed { i, bit -> if (bit != 0 && s.isDown(bit)) b = b or (1 shl i) }
|
||||
r.le16(13, b)
|
||||
r[15] = if (s.isDown(BtPadState.SHARE)) 1 else 0
|
||||
return r
|
||||
}
|
||||
|
||||
override fun output(id: Int, data: ByteArray): BtFeedback? {
|
||||
if (id != 3) return null
|
||||
val d = data
|
||||
if (d.size < 5) return null
|
||||
val enable = d[0].toInt()
|
||||
val strong = if (enable and 0x02 != 0) d[3].toInt() and 0xFF else 0
|
||||
val weak = if (enable and 0x01 != 0) d[4].toInt() and 0xFF else 0
|
||||
return BtFeedback(strong * 255 / 100, weak * 255 / 100)
|
||||
}
|
||||
|
||||
private fun axis16(v: Float) = ((v.coerceIn(-1f, 1f) + 1f) * 32767.5f).roundToInt().coerceIn(0, 65535)
|
||||
|
||||
companion object {
|
||||
private val XBOX_ORDER = intArrayOf(
|
||||
BtPadState.A, BtPadState.B, 0, BtPadState.X, BtPadState.Y, 0, BtPadState.LB, BtPadState.RB,
|
||||
0, 0, BtPadState.SELECT, BtPadState.START, BtPadState.GUIDE, BtPadState.L3, BtPadState.R3,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private abstract class SonyEncoder : BtPadEncoder() {
|
||||
@Volatile protected var enhanced = false
|
||||
protected var counter = 0
|
||||
protected var timestamp = 0L
|
||||
|
||||
override val periodMs = 8L
|
||||
|
||||
protected fun buttons(s: BtPadState): IntArray {
|
||||
val hat = s.hat().let { if (it < 0) 8 else it }
|
||||
var b0 = hat
|
||||
if (s.isDown(BtPadState.X)) b0 = b0 or 0x10
|
||||
if (s.isDown(BtPadState.A)) b0 = b0 or 0x20
|
||||
if (s.isDown(BtPadState.B)) b0 = b0 or 0x40
|
||||
if (s.isDown(BtPadState.Y)) b0 = b0 or 0x80
|
||||
var b1 = 0
|
||||
if (s.isDown(BtPadState.LB)) b1 = b1 or 0x01
|
||||
if (s.isDown(BtPadState.RB)) b1 = b1 or 0x02
|
||||
if (s.lt > 0.05f) b1 = b1 or 0x04
|
||||
if (s.rt > 0.05f) b1 = b1 or 0x08
|
||||
if (s.isDown(BtPadState.SELECT) || s.isDown(BtPadState.SHARE)) b1 = b1 or 0x10
|
||||
if (s.isDown(BtPadState.START)) b1 = b1 or 0x20
|
||||
if (s.isDown(BtPadState.L3)) b1 = b1 or 0x40
|
||||
if (s.isDown(BtPadState.R3)) b1 = b1 or 0x80
|
||||
var b2 = 0
|
||||
if (s.isDown(BtPadState.GUIDE)) b2 = b2 or 0x01
|
||||
if (s.isDown(BtPadState.TOUCHPAD)) b2 = b2 or 0x02
|
||||
return intArrayOf(b0, b1, b2)
|
||||
}
|
||||
|
||||
override fun report(s: BtPadState, limit: Int): Pair<Int, ByteArray> {
|
||||
val full = input(s)
|
||||
return if (full.size <= limit) inputId() to full else 1 to simple(s)
|
||||
}
|
||||
|
||||
protected fun simple(s: BtPadState): ByteArray {
|
||||
val b = buttons(s)
|
||||
counter = (counter + 1) and 0x3F
|
||||
return bytes(axis8(s.lx), axis8(s.ly), axis8(s.rx), axis8(s.ry), b[0], b[1], b[2] or (counter shl 2), trigger8(s.lt), trigger8(s.rt))
|
||||
}
|
||||
|
||||
protected fun calibration(): ByteArray {
|
||||
val r = ByteArray(40)
|
||||
val v = intArrayOf(0, 0, 0, GYRO, -GYRO, GYRO, -GYRO, GYRO, -GYRO, GYRO_SPEED, GYRO_SPEED, ACCEL, -ACCEL, ACCEL, -ACCEL, ACCEL, -ACCEL)
|
||||
v.forEachIndexed { i, x -> r.le16(i * 2, x) }
|
||||
return r.sealCrc(FEATURE_SEED, 0x05)
|
||||
}
|
||||
|
||||
override fun feature(id: Int): ByteArray? {
|
||||
val reply = reply(id) ?: return null
|
||||
enhanced = true
|
||||
return reply
|
||||
}
|
||||
|
||||
protected abstract fun reply(id: Int): ByteArray?
|
||||
|
||||
companion object {
|
||||
const val INPUT_SEED = 0xA1
|
||||
const val OUTPUT_SEED = 0xA2
|
||||
const val FEATURE_SEED = 0xA3
|
||||
const val GYRO = 8800
|
||||
const val GYRO_SPEED = 540
|
||||
const val ACCEL = 8192
|
||||
}
|
||||
}
|
||||
|
||||
private class DualShock4Encoder : SonyEncoder() {
|
||||
override val reports = listOf(0x01 to INPUT, 0x11 to INPUT, 0x11 to OUTPUT, 0x02 to FEATURE, 0xA3 to FEATURE, 0x05 to FEATURE, 0x12 to FEATURE)
|
||||
|
||||
override val descriptor = bytes(
|
||||
0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, 0x85, 0x01,
|
||||
0x09, 0x30, 0x09, 0x31, 0x09, 0x32, 0x09, 0x35, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x04, 0x81, 0x02,
|
||||
0x09, 0x39, 0x15, 0x00, 0x25, 0x07, 0x35, 0x00, 0x46, 0x3B, 0x01, 0x65, 0x14, 0x75, 0x04, 0x95, 0x01, 0x81, 0x42, 0x65, 0x00,
|
||||
0x05, 0x09, 0x19, 0x01, 0x29, 0x0E, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x0E, 0x81, 0x02,
|
||||
0x06, 0x00, 0xFF, 0x09, 0x20, 0x75, 0x06, 0x95, 0x01, 0x15, 0x00, 0x25, 0x7F, 0x81, 0x02,
|
||||
0x05, 0x01, 0x09, 0x33, 0x09, 0x34, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x02, 0x81, 0x02,
|
||||
0x06, 0x04, 0xFF,
|
||||
0x85, 0x02, 0x09, 0x24, 0x95, 0x24, 0xB1, 0x02,
|
||||
0x85, 0xA3, 0x09, 0x25, 0x95, 0x30, 0xB1, 0x02,
|
||||
0x85, 0x05, 0x09, 0x26, 0x95, 0x28, 0xB1, 0x02,
|
||||
0x85, 0x12, 0x09, 0x27, 0x95, 0x0F, 0xB1, 0x02,
|
||||
0x85, 0x11, 0x09, 0x22, 0x95, 0x4D, 0x81, 0x02,
|
||||
0x09, 0x23, 0x95, 0x4D, 0x91, 0x02,
|
||||
0xC0,
|
||||
)
|
||||
|
||||
override fun inputId() = if (enhanced) 0x11 else 0x01
|
||||
|
||||
override fun input(s: BtPadState): ByteArray {
|
||||
if (!enhanced) return simple(s)
|
||||
val r = ByteArray(77)
|
||||
r[0] = 0xC0.toByte()
|
||||
val b = buttons(s)
|
||||
counter = (counter + 1) and 0x3F
|
||||
timestamp += 1500
|
||||
val c = 2
|
||||
r[c] = axis8(s.lx).toByte(); r[c + 1] = axis8(s.ly).toByte(); r[c + 2] = axis8(s.rx).toByte(); r[c + 3] = axis8(s.ry).toByte()
|
||||
r[c + 4] = b[0].toByte(); r[c + 5] = b[1].toByte(); r[c + 6] = (b[2] or (counter shl 2)).toByte()
|
||||
r[c + 7] = trigger8(s.lt).toByte(); r[c + 8] = trigger8(s.rt).toByte()
|
||||
r.le16(c + 9, timestamp.toInt())
|
||||
r.le16(c + 20, ACCEL)
|
||||
r[c + 29] = 0x09
|
||||
r[c + 32] = 1
|
||||
r[c + 34] = 0x80.toByte()
|
||||
r[c + 38] = 0x80.toByte()
|
||||
return r.sealCrc(INPUT_SEED, 0x11)
|
||||
}
|
||||
|
||||
override fun reply(id: Int): ByteArray? = when (id) {
|
||||
0x02 -> ByteArray(36).also { r ->
|
||||
val v = intArrayOf(0, 0, 0, GYRO, GYRO, GYRO, -GYRO, -GYRO, -GYRO, GYRO_SPEED, GYRO_SPEED, ACCEL, -ACCEL, ACCEL, -ACCEL, ACCEL, -ACCEL)
|
||||
v.forEachIndexed { i, x -> r.le16(i * 2, x) }
|
||||
}
|
||||
0x05 -> calibration()
|
||||
0xA3 -> ByteArray(48).also { r ->
|
||||
"Sep 21 2018".toByteArray().copyInto(r, 0)
|
||||
"04:50:51".toByteArray().copyInto(r, 16)
|
||||
r.le16(34, 0x0100)
|
||||
r.le16(40, 0xA00A)
|
||||
}
|
||||
0x12 -> ByteArray(15).also { r -> FAKE_MAC.copyInto(r, 0); r[6] = 0x08; r[7] = 0x25 }
|
||||
else -> null
|
||||
}
|
||||
|
||||
override fun output(id: Int, data: ByteArray): BtFeedback? {
|
||||
if (id != 0x11) return null
|
||||
enhanced = true
|
||||
val d = data
|
||||
if (d.size < 10) return null
|
||||
val flags = d[2].toInt()
|
||||
val light = if (flags and 0x02 != 0) rgb(d[7], d[8], d[9]) else null
|
||||
return BtFeedback(d[6].toInt() and 0xFF, d[5].toInt() and 0xFF, light)
|
||||
}
|
||||
}
|
||||
|
||||
private class DualSenseEncoder : SonyEncoder() {
|
||||
override val reports = listOf(0x01 to INPUT, 0x31 to INPUT, 0x31 to OUTPUT, 0x05 to FEATURE, 0x09 to FEATURE, 0x20 to FEATURE)
|
||||
|
||||
override val descriptor = bytes(
|
||||
0x05, 0x01, 0x09, 0x05, 0xA1, 0x01, 0x85, 0x01,
|
||||
0x09, 0x30, 0x09, 0x31, 0x09, 0x32, 0x09, 0x35, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x04, 0x81, 0x02,
|
||||
0x09, 0x39, 0x15, 0x00, 0x25, 0x07, 0x35, 0x00, 0x46, 0x3B, 0x01, 0x65, 0x14, 0x75, 0x04, 0x95, 0x01, 0x81, 0x42, 0x65, 0x00,
|
||||
0x05, 0x09, 0x19, 0x01, 0x29, 0x0E, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x0E, 0x81, 0x02,
|
||||
0x06, 0x00, 0xFF, 0x09, 0x20, 0x75, 0x06, 0x95, 0x01, 0x15, 0x00, 0x25, 0x7F, 0x81, 0x02,
|
||||
0x05, 0x01, 0x09, 0x33, 0x09, 0x34, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x02, 0x81, 0x02,
|
||||
0x06, 0x00, 0xFF,
|
||||
0x85, 0x31, 0x09, 0x31, 0x95, 0x4D, 0x81, 0x02,
|
||||
0x09, 0x32, 0x95, 0x4D, 0x91, 0x02,
|
||||
0x85, 0x05, 0x09, 0x33, 0x95, 0x28, 0xB1, 0x02,
|
||||
0x85, 0x09, 0x09, 0x34, 0x95, 0x13, 0xB1, 0x02,
|
||||
0x85, 0x20, 0x09, 0x35, 0x95, 0x3F, 0xB1, 0x02,
|
||||
0xC0,
|
||||
)
|
||||
|
||||
private var sequence = 0
|
||||
|
||||
override fun inputId() = if (enhanced) 0x31 else 0x01
|
||||
|
||||
override fun input(s: BtPadState): ByteArray {
|
||||
if (!enhanced) return simple(s)
|
||||
val r = ByteArray(77)
|
||||
sequence = (sequence + 1) and 0xFF
|
||||
timestamp += 24000
|
||||
r[0] = 0x10
|
||||
val c = 1
|
||||
r[c] = axis8(s.lx).toByte(); r[c + 1] = axis8(s.ly).toByte(); r[c + 2] = axis8(s.rx).toByte(); r[c + 3] = axis8(s.ry).toByte()
|
||||
r[c + 4] = trigger8(s.lt).toByte(); r[c + 5] = trigger8(s.rt).toByte()
|
||||
r[c + 6] = sequence.toByte()
|
||||
val b = buttons(s)
|
||||
r[c + 7] = b[0].toByte(); r[c + 8] = b[1].toByte(); r[c + 9] = b[2].toByte()
|
||||
r.le16(c + 23, ACCEL)
|
||||
r.le32(c + 27, timestamp)
|
||||
r[c + 32] = 0x80.toByte()
|
||||
r[c + 36] = 0x80.toByte()
|
||||
r[c + 52] = 0x09
|
||||
return r.sealCrc(INPUT_SEED, 0x31)
|
||||
}
|
||||
|
||||
override fun reply(id: Int): ByteArray? = when (id) {
|
||||
0x05 -> calibration()
|
||||
0x09 -> ByteArray(19).also { r -> FAKE_MAC.copyInto(r, 0) }.sealCrc(FEATURE_SEED, 0x09)
|
||||
0x20 -> ByteArray(63).also { r ->
|
||||
"Jun 19 2023".toByteArray().copyInto(r, 0)
|
||||
"14:47:34".toByteArray().copyInto(r, 11)
|
||||
r.le16(19, 0x0003)
|
||||
r.le32(23, 0x00000615L)
|
||||
r.le32(27, 0x0110002AL)
|
||||
r.le16(43, 0x0630)
|
||||
}.sealCrc(FEATURE_SEED, 0x20)
|
||||
else -> null
|
||||
}
|
||||
|
||||
override fun output(id: Int, data: ByteArray): BtFeedback? {
|
||||
if (id != 0x31) return null
|
||||
enhanced = true
|
||||
val d = data
|
||||
if (d.size < 49) return null
|
||||
val flags0 = d[2].toInt()
|
||||
val flags1 = d[3].toInt()
|
||||
val light = if (flags1 and 0x04 != 0) rgb(d[46], d[47], d[48]) else null
|
||||
return if (flags0 and 0x03 != 0) BtFeedback(d[5].toInt() and 0xFF, d[4].toInt() and 0xFF, light)
|
||||
else if (light != null) BtFeedback(-1, -1, light) else null
|
||||
}
|
||||
}
|
||||
|
||||
private class SteamControllerEncoder : BtPadEncoder() {
|
||||
override val descriptor = bytes(
|
||||
0x06, 0x00, 0xFF, 0x09, 0x01, 0xA1, 0x01, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08,
|
||||
0x85, 0x45, 0x09, 0x02, 0x95, 0x2D, 0x81, 0x02, 0x85, 0x47, 0x09, 0x03, 0x95, 0x2D, 0x81, 0x02,
|
||||
0x85, 0x80, 0x09, 0x04, 0x95, 0x09, 0x91, 0x02, 0x85, 0x81, 0x09, 0x05, 0x95, 0x07, 0x91, 0x02,
|
||||
0x85, 0x82, 0x09, 0x06, 0x95, 0x03, 0x91, 0x02, 0x85, 0x83, 0x09, 0x07, 0x95, 0x09, 0x91, 0x02,
|
||||
0x85, 0x84, 0x09, 0x08, 0x95, 0x08, 0x91, 0x02, 0x85, 0x85, 0x09, 0x09, 0x95, 0x03, 0x91, 0x02,
|
||||
0x85, 0x01, 0x09, 0x0A, 0x95, 0x3F, 0xB1, 0x02, 0xC0,
|
||||
)
|
||||
override val reports = listOf(0x45 to INPUT, 0x47 to INPUT, 0x80 to OUTPUT, 0x81 to OUTPUT, 0x82 to OUTPUT,
|
||||
0x83 to OUTPUT, 0x84 to OUTPUT, 0x85 to OUTPUT, 0x01 to FEATURE)
|
||||
override val periodMs = 8L
|
||||
|
||||
@Volatile private var pending = 0
|
||||
private var packet = 0
|
||||
private val start = System.nanoTime()
|
||||
|
||||
override fun inputId() = 0x45
|
||||
|
||||
override fun input(s: BtPadState): ByteArray {
|
||||
val r = ByteArray(45)
|
||||
packet++
|
||||
r[0] = packet.toByte()
|
||||
var b = LGRIP_TOUCH or RGRIP_TOUCH
|
||||
BUTTONS.forEach { (mine, theirs) -> if (s.isDown(mine)) b = b or theirs }
|
||||
if (s.lt >= 0.98f) b = b or LTRIGGER_CLICK
|
||||
if (s.rt >= 0.98f) b = b or RTRIGGER_CLICK
|
||||
if (Math.abs(s.lx) > 0.06f || Math.abs(s.ly) > 0.06f) b = b or LSTICK_TOUCH
|
||||
if (Math.abs(s.rx) > 0.06f || Math.abs(s.ry) > 0.06f) b = b or RSTICK_TOUCH
|
||||
r.le32(1, b.toLong())
|
||||
r.le16(5, (s.lt.coerceIn(0f, 1f) * 32767f).roundToInt())
|
||||
r.le16(7, (s.rt.coerceIn(0f, 1f) * 32767f).roundToInt())
|
||||
r.le16(9, stick(s.lx)); r.le16(11, stick(-s.ly)); r.le16(13, stick(s.rx)); r.le16(15, stick(-s.ry))
|
||||
if (s.isDown(BtPadState.LPAD_TOUCH)) {
|
||||
r.le16(17, stick(s.lpx)); r.le16(19, stick(-s.lpy))
|
||||
r.le16(21, if (s.isDown(BtPadState.LPAD_CLICK)) 32767 else 4000)
|
||||
}
|
||||
if (s.isDown(BtPadState.RPAD_TOUCH)) {
|
||||
r.le16(23, stick(s.rpx)); r.le16(25, stick(-s.rpy))
|
||||
r.le16(27, if (s.isDown(BtPadState.RPAD_CLICK)) 32767 else 4000)
|
||||
}
|
||||
r.le32(29, (System.nanoTime() - start) / 1000)
|
||||
r.le16(37, 16384)
|
||||
return r
|
||||
}
|
||||
|
||||
override fun setFeature(id: Int, data: ByteArray) {
|
||||
val d = data
|
||||
if (id == 1 && d.isNotEmpty()) pending = d[0].toInt() and 0xFF
|
||||
}
|
||||
|
||||
override fun feature(id: Int): ByteArray? {
|
||||
if (id != 1) return null
|
||||
val r = ByteArray(63)
|
||||
r[0] = pending.toByte()
|
||||
when (pending) {
|
||||
0x83 -> {
|
||||
val ids = intArrayOf(0x01, 0x02, 0x04, 0x09, 0x0A, 0x0B)
|
||||
val values = longArrayOf(0x1303, 0, FW_TIMESTAMP, 72, 0, 4000)
|
||||
r[1] = (ids.size * 5).toByte()
|
||||
ids.forEachIndexed { i, a -> r[2 + i * 5] = a.toByte(); r.le32(3 + i * 5, values[i]) }
|
||||
}
|
||||
0xAE -> { r[1] = 0x14; r[2] = 0x01; SERIAL.toByteArray().copyInto(r, 3) }
|
||||
0xBA -> { r[1] = 0x11; "DROIDDECKCHIP02".toByteArray().copyInto(r, 3) }
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
override fun output(id: Int, data: ByteArray): BtFeedback? {
|
||||
val d = data
|
||||
return when (id) {
|
||||
0x80 -> if (d.size >= 8) {
|
||||
val left = (d[3].toInt() and 0xFF) or ((d[4].toInt() and 0xFF) shl 8)
|
||||
val right = (d[6].toInt() and 0xFF) or ((d[7].toInt() and 0xFF) shl 8)
|
||||
BtFeedback(left shr 8, right shr 8)
|
||||
} else null
|
||||
in 0x81..0x85 -> BtFeedback(0, 120)
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
private fun stick(v: Float) = (v.coerceIn(-1f, 1f) * 32767f).roundToInt()
|
||||
|
||||
companion object {
|
||||
private const val LGRIP_TOUCH = 0x20000000
|
||||
private const val RGRIP_TOUCH = 0x10000000
|
||||
private const val LTRIGGER_CLICK = 0x08000000
|
||||
private const val RTRIGGER_CLICK = 0x00800000
|
||||
private const val LSTICK_TOUCH = 0x01000000
|
||||
private const val RSTICK_TOUCH = 0x00100000
|
||||
private const val FW_TIMESTAMP = 0x6AC686B3L
|
||||
private const val SERIAL = "DROIDDECKSC01"
|
||||
private val BUTTONS = listOf(
|
||||
BtPadState.A to 0x00000001, BtPadState.B to 0x00000002, BtPadState.X to 0x00000004, BtPadState.Y to 0x00000008,
|
||||
BtPadState.SHARE to 0x00000010, BtPadState.R3 to 0x00000020, BtPadState.SELECT to 0x00000040,
|
||||
BtPadState.R4 to 0x00000080, BtPadState.R5 to 0x00000100, BtPadState.RB to 0x00000200,
|
||||
BtPadState.DOWN to 0x00000400, BtPadState.RIGHT to 0x00000800, BtPadState.LEFT to 0x00001000,
|
||||
BtPadState.UP to 0x00002000, BtPadState.START to 0x00004000, BtPadState.L3 to 0x00008000,
|
||||
BtPadState.GUIDE to 0x00010000, BtPadState.L4 to 0x00020000, BtPadState.L5 to 0x00040000,
|
||||
BtPadState.LB to 0x00080000,
|
||||
BtPadState.RPAD_TOUCH to 0x00200000, BtPadState.RPAD_CLICK to 0x00400000,
|
||||
BtPadState.LPAD_TOUCH to 0x02000000, BtPadState.LPAD_CLICK to 0x04000000,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private val FAKE_MAC = BtPadEncoder.bytes(0x5D, 0x44, 0x33, 0x22, 0x11, 0xD0)
|
||||
|
||||
private fun rgb(r: Byte, g: Byte, b: Byte) =
|
||||
(0xFF shl 24) or ((r.toInt() and 0xFF) shl 16) or ((g.toInt() and 0xFF) shl 8) or (b.toInt() and 0xFF)
|
||||
@@ -207,8 +207,7 @@ object BattleNet {
|
||||
val taken = HashSet<File>()
|
||||
fun options(title: Title, folder: File) = listOfNotNull(folder, title.flavor?.let { File(folder, it) }?.takeIf { it.isDirectory })
|
||||
for ((code, game) in games) {
|
||||
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
|
||||
val keep = saved[code]?.let(::File)?.takeIf { it in options(game.first, game.second) && it !in taken } ?: continue
|
||||
out[code] = keep
|
||||
taken.add(keep)
|
||||
}
|
||||
@@ -245,14 +244,6 @@ object BattleNet {
|
||||
"/" + rootfs.relativize(resolved).joinToString("/")
|
||||
}
|
||||
}.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")
|
||||
}
|
||||
|
||||
|
||||
@@ -112,16 +112,9 @@ object BwrapSpawner {
|
||||
return out
|
||||
}
|
||||
|
||||
internal fun withKernelPaths(sessionBinds: List<Bind>, canonical: (String) -> String): List<Bind> =
|
||||
sessionBinds + sessionBinds.filter { it.host == it.guest }.mapNotNull { bind ->
|
||||
runCatching { canonical(bind.host) }.getOrNull()
|
||||
?.takeIf { it != bind.guest && sessionBinds.none { other -> other.guest == it } }
|
||||
?.let { Bind(bind.host, it) }
|
||||
}
|
||||
|
||||
internal fun plan(context: Context, request: JSONObject, dir: File): Plan {
|
||||
val rootfs = LinuxRuntime.rootDir(context).path
|
||||
val session = withKernelPaths(LinuxRuntime.lastBinds(context).map { Bind.parse(it) }) { File(it).canonicalPath }
|
||||
val session = LinuxRuntime.lastBinds(context).map { Bind.parse(it) }
|
||||
val root = File(dir, "root").apply { mkdirs() }
|
||||
val binds = ArrayList<Bind>()
|
||||
var scratch = 0
|
||||
@@ -191,10 +184,7 @@ object BwrapSpawner {
|
||||
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> env[k] = e.getString(k) } }
|
||||
withoutRootfsSettings(env, rootfs)
|
||||
val envTool = request.optString("envTool").takeIf { it.startsWith("/") }
|
||||
if (envTool == null && binds.any { it.guest == "/dev" }) {
|
||||
val glIcd = coveringBind(GL_ICD_DIR) != null && File(hostPath(binds, root.path, GL_ICD_DIR)).isDirectory
|
||||
gpu(rootfs, root, env, glIcd = glIcd)?.forEach { addBind(it) }
|
||||
}
|
||||
if (envTool == null && binds.any { it.guest == "/dev" }) gpu(rootfs, root, env)?.forEach { addBind(it) }
|
||||
val libc = listOf("/usr/lib/aarch64-linux-gnu/libc.so.6", "/lib/aarch64-linux-gnu/libc.so.6").map { hostPath(binds, root.path, it) }
|
||||
if (envTool == null && preloadFits(rootfs, libc.firstOrNull { File(it).isFile } ?: libc.first())) preload(session, rootfs, env).forEach { addBind(it) }
|
||||
zypakShims(binds, root, dir).forEach { addBind(it) }
|
||||
@@ -221,7 +211,6 @@ object BwrapSpawner {
|
||||
}
|
||||
|
||||
private const val GPU_DIR = "/run/droiddeck-gpu"
|
||||
private const val GL_ICD_DIR = "/usr/lib/aarch64-linux-gnu/GL/vulkan/icd.d"
|
||||
|
||||
private val LIB_DIRS = listOf("usr/lib/aarch64-linux-gnu", "usr/lib")
|
||||
private val GPU_LIBS = listOf("libdisplay-info.so.3", "libdisplay-info.so.2", "libSPIRV-Tools.so", "libSPIRV-Tools-opt.so")
|
||||
@@ -231,9 +220,9 @@ object BwrapSpawner {
|
||||
|
||||
internal fun gpu(
|
||||
rootfs: String, root: File, env: MutableMap<String, String>,
|
||||
kgslAvailable: Boolean = File("/dev/kgsl-3d0").exists(), glIcd: Boolean = false,
|
||||
kgslAvailable: Boolean = File("/dev/kgsl-3d0").exists(),
|
||||
): List<Bind>? {
|
||||
env["VKBRIDGE_SOCKET"]?.let { sock -> if (File(sock).exists()) return bridgeGpu(rootfs, root, env, sock, glIcd) }
|
||||
env["VKBRIDGE_SOCKET"]?.let { sock -> if (File(sock).exists()) return bridgeGpu(rootfs, root, env, sock) }
|
||||
val driver = runtimeLib(rootfs, "libvulkan_freedreno.so")
|
||||
if (driver == null || !kgslAvailable) return null
|
||||
if (env.containsKey("VK_ICD_FILENAMES") || env.containsKey("VK_DRIVER_FILES")) return null
|
||||
@@ -246,7 +235,6 @@ object BwrapSpawner {
|
||||
val icd = File(root.parentFile, "freedreno_icd.json")
|
||||
icd.writeText("{\"file_format_version\": \"1.0.0\", \"ICD\": {\"library_path\": \"$GPU_DIR/libvulkan_freedreno.so\", \"api_version\": \"1.4.0\"}}\n")
|
||||
binds.add(Bind(icd.path, "$GPU_DIR/freedreno_icd.json"))
|
||||
if (glIcd) binds.add(icdDir(root, icd))
|
||||
env["VK_DRIVER_FILES"] = "$GPU_DIR/freedreno_icd.json"
|
||||
env["VK_ICD_FILENAMES"] = "$GPU_DIR/freedreno_icd.json"
|
||||
if (!env.containsKey("MESA_LOADER_DRIVER_OVERRIDE") && !env.containsKey("GALLIUM_DRIVER")) {
|
||||
@@ -257,14 +245,7 @@ object BwrapSpawner {
|
||||
return binds
|
||||
}
|
||||
|
||||
private fun icdDir(root: File, icd: File): Bind {
|
||||
val dir = File(root.parentFile, "icd.d")
|
||||
dir.mkdirs()
|
||||
icd.copyTo(File(dir, icd.name), overwrite = true)
|
||||
return Bind(dir.path, GL_ICD_DIR)
|
||||
}
|
||||
|
||||
private fun bridgeGpu(rootfs: String, root: File, env: MutableMap<String, String>, socket: String, glIcd: Boolean): List<Bind>? {
|
||||
private fun bridgeGpu(rootfs: String, root: File, env: MutableMap<String, String>, socket: String): List<Bind>? {
|
||||
val driver = File(rootfs, "usr/local/lib/vkbridge/libvulkan_droidbridge.so")
|
||||
if (!driver.isFile) { Log.w(TAG, "gpu: vkbridge session but no bridge ICD in the runtime"); return null }
|
||||
val binds = ArrayList<Bind>()
|
||||
@@ -277,7 +258,6 @@ object BwrapSpawner {
|
||||
}.getOrNull() ?: run { Log.w(TAG, "gpu: vkbridge session but the runtime's bridge manifest is unreadable"); return null }
|
||||
icd.writeText("{\"file_format_version\": \"1.0.0\", \"ICD\": {\"library_path\": \"$GPU_DIR/libvulkan_droidbridge.so\", \"api_version\": \"$api\"}}\n")
|
||||
binds.add(Bind(icd.path, "$GPU_DIR/vkbridge_icd.json"))
|
||||
if (glIcd) binds.add(icdDir(root, icd))
|
||||
env["VK_DRIVER_FILES"] = "$GPU_DIR/vkbridge_icd.json"
|
||||
env["VK_ICD_FILENAMES"] = "$GPU_DIR/vkbridge_icd.json"
|
||||
if (!env.containsKey("MESA_LOADER_DRIVER_OVERRIDE") && !env.containsKey("GALLIUM_DRIVER")) {
|
||||
@@ -436,7 +416,6 @@ object BwrapSpawner {
|
||||
"DDNATV_ROOT" to sandbox,
|
||||
"DDNATV_EXEC" to NativeGuest.execLoader.orEmpty(),
|
||||
"DDNATV_LINK_ROOT" to rootfs.path,
|
||||
"DDNATV_REAL_EXE" to program.path,
|
||||
"DDNATV_BINDS" to plan.binds.joinToString("|") { "${it.host}:${it.guest}" },
|
||||
"DDNATV_HOSTNAME" to SessionPrefs.guestHostname(context),
|
||||
"LD_LIBRARY_PATH" to SANDBOX_LIB_DIRS.map(::host).filter { it.isDirectory }.joinToString(":") { it.path },
|
||||
@@ -558,9 +537,6 @@ object BwrapSpawner {
|
||||
return f
|
||||
}
|
||||
|
||||
internal fun prootEnvironment(plan: Plan, startsThroughEnvTool: Boolean): Map<String, String> =
|
||||
if (startsThroughEnvTool) emptyMap() else plan.env - "LD_PRELOAD"
|
||||
|
||||
private fun run(context: Context, plan: Plan, client: LocalSocket, out: DataOutputStream, id: Int) {
|
||||
val verbose = plan.env["DROIDDECK_PROOT_VERBOSE"]?.toIntOrNull()
|
||||
val native = if (NativeGuest.forSession(context)) nativeLaunch(context, plan) else null
|
||||
@@ -582,7 +558,7 @@ object BwrapSpawner {
|
||||
ProcessBuilder(cmd).redirectErrorStream(true).directory(plan.root).also { b ->
|
||||
b.environment().apply {
|
||||
clear()
|
||||
putAll(prootEnvironment(plan, envTool))
|
||||
if (!envTool) putAll(plan.env)
|
||||
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
|
||||
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
|
||||
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
|
||||
|
||||
@@ -109,15 +109,9 @@ object DesktopCatalog {
|
||||
FileUtils.readString(marker(context, id))?.trim()?.takeIf { it.isNotEmpty() }
|
||||
|
||||
fun protonSeedNeeded(context: Context): Boolean =
|
||||
if (com.droiddeck.launcher.session.SessionPrefs.ownProtonFirst(context)) ownProtonMissing(context)
|
||||
else installed(context, PROTON_SEED_ID) == null &&
|
||||
installed(context, PROTON_SEED_ID) == null &&
|
||||
!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 EMULATORS_ID = "emulators"
|
||||
private const val EMULATORS_SCRIPT = "/usr/local/bin/droiddeck-emulators"
|
||||
|
||||
@@ -32,9 +32,6 @@ object DesktopLanguage {
|
||||
|
||||
internal fun baseUrl(desktopUrl: String) = desktopUrl.substringBeforeLast('/') + "/"
|
||||
|
||||
/** The index carries every pack's sha256, so it never goes through a download mirror. */
|
||||
internal fun fetchIndex(base: String): Map<String, Pack>? = Downloader.downloadDirect(base + INDEX)?.let(::parseIndex)
|
||||
|
||||
private fun marker(root: File, tag: String, name: String) = File(root, ".droiddeck-i18n-$tag-$name")
|
||||
|
||||
/** Installs the desktop's translations for [locale]; false when a download failed and is worth retrying. */
|
||||
@@ -47,7 +44,7 @@ object DesktopLanguage {
|
||||
val pending = candidates(locale).filterNot { marker(root, tag, it).isFile }
|
||||
if (pending.isEmpty()) return true
|
||||
val base = baseUrl(BuildConfig.DESKTOP_KDE_URL)
|
||||
val index = fetchIndex(base) ?: return false
|
||||
val index = parseIndex(Downloader.downloadString(base + INDEX) ?: return false)
|
||||
var complete = true
|
||||
for (name in pending) {
|
||||
val pack = index[name]
|
||||
|
||||
@@ -73,10 +73,10 @@ object NativeGuest {
|
||||
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. */
|
||||
fun environment(root: File, program: String, preload: List<String> = emptyList()): Map<String, String> = linkedMapOf(
|
||||
fun environment(root: File, preload: List<String> = emptyList()): Map<String, String> = linkedMapOf(
|
||||
"DDNATV_ROOT" to root.path,
|
||||
"DDNATV_EXEC" to execLoader.orEmpty(),
|
||||
"DDNATV_REAL_EXE" to hostProgram(root, program).path,
|
||||
"LD_LIBRARY_PATH" to libraryPath(root),
|
||||
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
|
||||
).filterValues { it.isNotEmpty() }
|
||||
|
||||
@@ -84,25 +84,23 @@ object NativeGuest {
|
||||
* The host command line for the guest program at [program] (an absolute guest path to a real
|
||||
* file, not a symlink).
|
||||
*/
|
||||
fun command(root: File, program: String, args: List<String>, libraryPath: String = libraryPath(root)): List<String> {
|
||||
fun command(root: File, program: String, args: List<String>): List<String> {
|
||||
val loader = checkNotNull(loader(root)) { "no glibc loader in ${root.path}" }
|
||||
val host = hostProgram(root, program)
|
||||
val launch = listOf(loader.path, "--library-path", libraryPath, "--argv0", host.name, host.path) + args
|
||||
val host = File(root, program.removePrefix("/"))
|
||||
val launch = listOf(loader.path, "--argv0", host.name, host.path) + args
|
||||
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. */
|
||||
fun sessionEnvironment(root: File, binds: List<String>, program: String, hostname: String? = null): Map<String, String> {
|
||||
fun sessionEnvironment(root: File, binds: List<String>, hostname: String? = null): Map<String, String> {
|
||||
val preload = preloadList(root)
|
||||
return linkedMapOf(
|
||||
"DDNATV_ROOT" to root.path,
|
||||
"DDNATV_EXEC" to execLoader.orEmpty(),
|
||||
"DDNATV_REAL_EXE" to hostProgram(root, program).path,
|
||||
"DDNATV_HOSTNAME" to hostname.orEmpty(),
|
||||
"DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" },
|
||||
"DDNATV_PRELOAD" to preload.joinToString(":"),
|
||||
"LD_LIBRARY_PATH" to libraryPath(root),
|
||||
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
|
||||
).filterValues { it.isNotEmpty() }
|
||||
}
|
||||
@@ -118,7 +116,7 @@ object NativeGuest {
|
||||
.also { builder ->
|
||||
builder.environment().apply {
|
||||
remove("LD_AUDIT")
|
||||
putAll(sessionEnvironment(root, binds, guest.first(), SessionPrefs.guestHostname(context)))
|
||||
putAll(sessionEnvironment(root, binds, SessionPrefs.guestHostname(context)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -275,14 +273,12 @@ object NativeGuest {
|
||||
|
||||
fun builder(root: File, cwd: String, argv: List<String>, env: Map<String, String>, preload: List<String> = emptyList()): ProcessBuilder {
|
||||
val program = argv.first()
|
||||
val callerDirs = env["LD_LIBRARY_PATH"]?.takeIf { it.isNotEmpty() }?.split(':').orEmpty()
|
||||
val rootDirs = libraryPath(root).split(':').filterNot { it in callerDirs }
|
||||
val cmd = command(root, program, argv.drop(1), (callerDirs + rootDirs).joinToString(":"))
|
||||
val cmd = command(root, program, argv.drop(1))
|
||||
val builder = ProcessBuilder(cmd).redirectErrorStream(false)
|
||||
builder.directory(File(root, cwd.removePrefix("/")).takeIf { it.isDirectory } ?: root)
|
||||
builder.environment().apply {
|
||||
clear()
|
||||
putAll(environment(root, program, preload))
|
||||
putAll(environment(root, preload))
|
||||
putAll(env)
|
||||
}
|
||||
return builder
|
||||
|
||||
@@ -22,7 +22,7 @@ class RuntimeInstallService : Service() {
|
||||
if (intent?.action == ACTION_PACKAGE) return holdPackage(startId)
|
||||
val removal = intent?.action == ACTION_REMOVE
|
||||
val release = intent?.let(::releaseFrom)
|
||||
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))
|
||||
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))
|
||||
if (release == null && !removal) {
|
||||
stopSelf(startId)
|
||||
return START_NOT_STICKY
|
||||
@@ -31,7 +31,7 @@ class RuntimeInstallService : Service() {
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
var shown = ""
|
||||
val progress = LinuxRuntimeInstaller.ProgressListener { stage, percent ->
|
||||
if (foreground && "$stage:$percent" != shown) {
|
||||
if ("$stage:$percent" != shown) {
|
||||
shown = "$stage:$percent"
|
||||
manager?.notify(NOTIFICATION_ID, notification(stage, percent))
|
||||
}
|
||||
@@ -46,10 +46,7 @@ class RuntimeInstallService : Service() {
|
||||
}
|
||||
|
||||
private fun holdPackage(startId: Int): Int {
|
||||
if (!enterForeground(notification(packageStage, packagePercent, packageTitle))) {
|
||||
stopSelf(startId)
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
startForeground(NOTIFICATION_ID, notification(packageStage, packagePercent, packageTitle))
|
||||
Thread({
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
var shown = ""
|
||||
@@ -68,15 +65,6 @@ class RuntimeInstallService : Service() {
|
||||
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 {
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
manager?.createNotificationChannel(NotificationChannel(CHANNEL_ID, getString(R.string.setup_runtime),
|
||||
|
||||
@@ -328,7 +328,7 @@ object BottomDesktop {
|
||||
LinuxRuntime.commandWithBinds(context, current.root, binds, guest)
|
||||
}
|
||||
val environment = if (current.nativeUserland) {
|
||||
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, guest.first(), SessionPrefs.guestHostname(context))
|
||||
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(current.root, binds, SessionPrefs.guestHostname(context))
|
||||
.map { (k, v) -> "$k=$v" }.toTypedArray()
|
||||
} else current.hostEnvironment
|
||||
val line = command.joinToString(" ") { it.replace("\\", "\\\\").replace(" ", "\\ ") }
|
||||
|
||||
@@ -88,8 +88,8 @@ object ComponentUpdater {
|
||||
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? {
|
||||
if (!ComponentUpdates.autoFollows(p, comp) || !ComponentsManager.supports(p, comp)) return null
|
||||
if (comp == "fex") return ComponentUpdates.fexLine(p)
|
||||
if (!ComponentUpdates.follows(p) || !ComponentsManager.supports(p, comp)) return null
|
||||
if (comp == "fex") return ComponentUpdates.line("fex", false)
|
||||
val key = "${p.id}|${p.version}"
|
||||
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) }
|
||||
|
||||
@@ -13,7 +13,7 @@ object ComponentUpdates {
|
||||
const val BOOTED_SECONDS = 60L
|
||||
const val FAILED_BOOTS_BEFORE_ROLLBACK = 2
|
||||
|
||||
data class Line(val key: String, val comp: String, val prefix: String, val release: String = ComponentsManager.DD_NIGHTLY)
|
||||
data class Line(val key: String, val comp: String, val prefix: String)
|
||||
|
||||
val LINES = listOf(
|
||||
Line("dxvk", "dxvk", "DD-dxvk-"),
|
||||
@@ -21,19 +21,12 @@ object ComponentUpdates {
|
||||
Line("vkd3d", "vkd3d", "DD-vkd3d-proton-"),
|
||||
Line("vkd3d-arm64ec", "vkd3d", "DD-vkd3d-proton-arm64ec-"),
|
||||
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
|
||||
|
||||
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 strays(
|
||||
@@ -41,8 +34,8 @@ object ComponentUpdates {
|
||||
choices: Map<String, Map<String, ComponentsManager.Choice>>,
|
||||
placed: Set<String>,
|
||||
): List<Pair<ComponentsManager.Proton, String>> =
|
||||
protons.flatMap { p ->
|
||||
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 }
|
||||
protons.filterNot(::follows).flatMap { p ->
|
||||
choices[p.id].orEmpty().filter { (_, c) -> !c.auto && c.protonVersion == p.version && c.file in placed }.keys.map { p to it }
|
||||
}
|
||||
|
||||
fun unseen(
|
||||
@@ -60,14 +53,13 @@ object ComponentUpdates {
|
||||
|
||||
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) }
|
||||
return items.filter { it.release == line.release && it.comp == line.comp && belongs(it.file, line) }
|
||||
return items.filter { it.release == ComponentsManager.DD_NIGHTLY && it.comp == line.comp && belongs(it.file, line) }
|
||||
.filter { newestBad == null || ProtonExtras.compareVersions(it.file, newestBad) > 0 }
|
||||
.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a.file, b.file) }
|
||||
}
|
||||
|
||||
fun belongs(file: String, line: Line): Boolean =
|
||||
file.startsWith(line.prefix) && file.removePrefix(line.prefix).firstOrNull()?.isDigit() == true &&
|
||||
(line.comp != "fex" || ComponentsManager.bionicFex(file) == (line.release == ComponentsManager.DD_BIONIC))
|
||||
file.startsWith(line.prefix) && file.removePrefix(line.prefix).firstOrNull()?.isDigit() == true
|
||||
|
||||
fun arm64ec(pe: ByteArray): Boolean? = runCatching {
|
||||
val b = ByteBuffer.wrap(pe).order(ByteOrder.LITTLE_ENDIAN)
|
||||
@@ -169,7 +161,7 @@ object ComponentUpdates {
|
||||
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) }
|
||||
fun newer(file: String) = ranked != null && belongs(file, ranked) && ProtonExtras.compareVersions(file, current) > 0
|
||||
return (owned + stored.filter { ranked != null && ranked.release == ComponentsManager.DD_NIGHTLY && belongs(it, ranked) })
|
||||
return (owned + stored.filter { ranked != null && belongs(it, ranked) })
|
||||
.filter { it !in keep && ((it in bad && it in owned) || !newer(it)) }.distinct()
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,6 @@ object ComponentsManager {
|
||||
private const val NIGHTLIES = "The412Banner/Nightlies"
|
||||
private const val DD_COMPONENTS = "Droid-Deck/DroidDeck-Components"
|
||||
internal const val DD_NIGHTLY = "linux-nightly"
|
||||
internal const val DD_BIONIC = "bionic-stable"
|
||||
private val RELEASES = linkedMapOf(
|
||||
"FexCore-Linux" to "fex",
|
||||
"Dxvk-Linux" to "dxvk",
|
||||
@@ -38,9 +37,9 @@ object ComponentsManager {
|
||||
"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 SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY) + (DD_COMPONENTS to DD_BIONIC)
|
||||
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY)
|
||||
private val DOWNLOAD_REPOS = listOf(NIGHTLIES, DD_COMPONENTS)
|
||||
private val TYPES = mapOf("FEXCore-Linux" to "fex", "FEXCore-Bionic" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d")
|
||||
private val TYPES = mapOf("FEXCore-Linux" 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")
|
||||
val COMPONENTS = listOf("fex", "dxvk", "vkd3d")
|
||||
val LABEL = mapOf("fex" to "FEX", "dxvk" to "DXVK", "vkd3d" to "VKD3D-Proton")
|
||||
@@ -202,34 +201,8 @@ object ComponentsManager {
|
||||
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) }
|
||||
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) {
|
||||
require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L)
|
||||
@@ -440,7 +413,7 @@ object ComponentsManager {
|
||||
}
|
||||
}
|
||||
require(File(staged, "files").isDirectory) { "${wcp.name} has no files/" }
|
||||
if (comp == "fex" && !bionicTool(dir.name)) FEX_FILES.filter { it.endsWith(".so") && !File(staged, it).isFile }.forEach { File(dir, it).delete() }
|
||||
if (comp == "fex") FEX_FILES.filter { it.endsWith(".so") && !File(staged, it).isFile }.forEach { File(dir, it).delete() }
|
||||
COMP_DIR[comp]?.let { compDir ->
|
||||
for (arch in PE_ARCHES) {
|
||||
val target = File(dir, "$compDir/$arch")
|
||||
@@ -630,9 +603,7 @@ object ComponentsManager {
|
||||
File(base, "files").walkTopDown().filter { it.isFile }.map { it.relativeTo(base).invariantSeparatorsPath }
|
||||
.filter { owned(comp, it) }.associateWith { File(base, it) }
|
||||
}
|
||||
// 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) {
|
||||
for (rel in managed(comp) - files.keys) {
|
||||
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")
|
||||
}
|
||||
@@ -649,8 +620,7 @@ object ComponentsManager {
|
||||
val version = safeName(file.removePrefix("original "))
|
||||
"original-${p.id}-$version-$comp" to File(originalsDir(context), "${p.id}/$version/$comp.wcp")
|
||||
} else {
|
||||
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)
|
||||
safeName(file.removeSuffix(".wcp")) to File(packagesDir(context), file)
|
||||
}.takeIf { it.second.isFile }
|
||||
}
|
||||
|
||||
@@ -681,14 +651,12 @@ object ComponentsManager {
|
||||
for (scope in profiles.keys()) {
|
||||
val profile = profiles.optJSONObject(scope) ?: continue
|
||||
for (comp in COMPONENTS) {
|
||||
val chosen = profile.optString(comp)
|
||||
if (chosen.isEmpty()) continue
|
||||
for (p in all) {
|
||||
val file = (if (comp == "fex") launchFex(p.dir.name, chosen) { File(packagesDir(context), it).isFile } else chosen) ?: continue
|
||||
val wcp = File(packagesDir(context), file)
|
||||
if (!wcp.isFile) continue
|
||||
append(scope, p, comp, safeName(file.removeSuffix(".wcp")), wcp)
|
||||
}
|
||||
val file = profile.optString(comp)
|
||||
if (file.isEmpty()) continue
|
||||
val wcp = File(packagesDir(context), file)
|
||||
if (!wcp.isFile) continue
|
||||
val key = safeName(file.removeSuffix(".wcp"))
|
||||
for (p in all) append(scope, p, comp, key, wcp)
|
||||
}
|
||||
}
|
||||
return PreparedLaunchState(lines.toString(), keep)
|
||||
@@ -709,7 +677,6 @@ object ComponentsManager {
|
||||
val wcp = File(packagesDir(context), safeName(file))
|
||||
val info = packageInfo(context, wcp)
|
||||
requireSelectable(context, info.comp)
|
||||
requireFits(p, info)
|
||||
val state = loadState(context)
|
||||
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)
|
||||
@@ -723,11 +690,7 @@ object ComponentsManager {
|
||||
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) {
|
||||
requireFits(p, info)
|
||||
ensureOriginal(context, p, info.comp, state)
|
||||
val hashes = installFiles(context, p.dir, info.comp, wcp)
|
||||
state.sub("active").sub(p.id).put(info.comp, JSONObject()
|
||||
@@ -840,18 +803,6 @@ object ComponentsManager {
|
||||
internal fun liveOnAny(key: String, entry: JSONObject, installs: List<Proton>?): Boolean =
|
||||
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> {
|
||||
val byId = installed.groupBy { it.id }
|
||||
val names = HashSet<String>()
|
||||
@@ -868,11 +819,7 @@ object ComponentsManager {
|
||||
val profiles = state.optJSONObject("profiles")
|
||||
for (scope in profiles?.keys() ?: emptyList<String>().iterator()) {
|
||||
val profile = profiles?.optJSONObject(scope) ?: continue
|
||||
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)
|
||||
}
|
||||
COMPONENTS.forEach { comp -> profile.optString(comp).takeIf { it.isNotEmpty() }?.let(names::add) }
|
||||
}
|
||||
return names
|
||||
}
|
||||
@@ -943,7 +890,6 @@ object ComponentsManager {
|
||||
val queued = state.sub("queued").sub(target.id)
|
||||
var changed = false
|
||||
wanted.forEach { (comp, entry) ->
|
||||
if (comp == "fex" && !fexFits(target.dir.name, entry.optString("file"))) return@forEach
|
||||
if (active?.has(comp) != true && !queued.has(comp)) {
|
||||
queued.put(comp, entry)
|
||||
changed = true
|
||||
@@ -1024,8 +970,6 @@ object ComponentsManager {
|
||||
fun deletePackage(context: Context, file: String): String = synchronized(lock) {
|
||||
val name = safeName(file)
|
||||
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 }
|
||||
var changed = false
|
||||
for (key in listOf("queued", "active")) {
|
||||
@@ -1122,11 +1066,8 @@ object ComponentsManager {
|
||||
return Catalog(items, o.optLong("fetchedAt"))
|
||||
}
|
||||
|
||||
internal fun assetComp(release: String, name: String): String? = RELEASES[release] ?: when (release) {
|
||||
DD_NIGHTLY -> NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value
|
||||
DD_BIONIC -> "fex"
|
||||
else -> null
|
||||
}
|
||||
internal fun assetComp(release: String, name: String): String? =
|
||||
RELEASES[release] ?: if (release == DD_NIGHTLY) NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value else null
|
||||
|
||||
internal val CATALOG_ORDER: Comparator<CatalogItem> =
|
||||
compareBy<CatalogItem> { it.comp }.thenBy { it.release == DD_NIGHTLY }.then(newestFirst { it.file })
|
||||
@@ -1214,25 +1155,6 @@ object ComponentsManager {
|
||||
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 =
|
||||
if (comp == "fex") File(p.dir, FEX_FILES.first()).isFile else File(p.dir, "${COMP_DIR.getValue(comp)}/aarch64-windows").isDirectory
|
||||
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
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 {
|
||||
val value = entry.lowercase(Locale.US)
|
||||
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") || value.startsWith("rpcs3/") ||
|
||||
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") ||
|
||||
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
|
||||
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug", "bionic").any(value::contains)) return Category.GAMES
|
||||
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug").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
|
||||
return Category.SESSION
|
||||
}
|
||||
@@ -948,9 +948,8 @@ internal object EnhancedSessionLogShare {
|
||||
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.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",
|
||||
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt", "droiddeck-bionic.log",
|
||||
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt",
|
||||
"console_log.txt", "webhelper_js.txt", "controller_support.txt", "systemperfmanager.txt",
|
||||
"rpcs3", "RPCS3.log",
|
||||
)
|
||||
private val KNOWN_COMPONENT_PATTERNS = listOf(
|
||||
Regex("[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{2,}-[a-z0-9-]{1,24}"),
|
||||
|
||||
@@ -74,16 +74,10 @@ object ExperimentalProtons {
|
||||
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>? {
|
||||
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
|
||||
val fetched = ProtonExtras.releasesForRemoval(tool) ?: return null
|
||||
val assets = listed(ProtonExtras.assets(tool, fetched.releases, prerelease = true))
|
||||
val assets = 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 }
|
||||
if (!SessionState.running) {
|
||||
reconcile(context, fetched)
|
||||
|
||||
@@ -43,17 +43,6 @@ object GameStorage {
|
||||
}
|
||||
}
|
||||
|
||||
fun isFat32(path: String): Boolean = runCatching { isFat32(path, File("/proc/mounts").readText()) }.getOrDefault(false)
|
||||
|
||||
/** Android mounts FAT32 as vfat and exFAT as exfat; /storage is a FUSE view, so the lookup uses the raw mount. */
|
||||
internal fun isFat32(path: String, mounts: String): Boolean {
|
||||
val raw = UsbLink.rawPath(path)
|
||||
return mounts.lineSequence().map { it.split(' ') }
|
||||
.filter { it.size >= 3 }
|
||||
.filter { val point = it[1].replace("\\040", " "); raw == point || raw.startsWith("${point.trimEnd('/')}/") }
|
||||
.maxByOrNull { it[1].length }?.get(2) == "vfat"
|
||||
}
|
||||
|
||||
fun effective(context: Context): Option? {
|
||||
val pref = SessionPrefs.gameStorage(context)
|
||||
return when {
|
||||
|
||||
@@ -27,14 +27,14 @@ object GameThreadHints {
|
||||
private const val PACE_TOLERANCE = 0.08
|
||||
|
||||
private val NOT_GAMES = setOf("steam", "steamwebhelper")
|
||||
private val SOCS = setOf("CQ8725S", "SM8750", "SM8750P")
|
||||
private val SOCS = setOf("CQ8725S", "SM8750")
|
||||
|
||||
private var worker: Thread? = null
|
||||
|
||||
@Synchronized
|
||||
fun start(context: Context): String {
|
||||
if (!SessionPrefs.gameThreadHints(context)) return "game thread hints: off"
|
||||
if (Build.VERSION.SDK_INT < 31 || !supported(SocNames.model())) return "game thread hints: Snapdragon 8 Elite only"
|
||||
if (Build.VERSION.SDK_INT < 31 || !supported(Build.SOC_MODEL)) return "game thread hints: Snapdragon 8 Elite only"
|
||||
val hm = context.getSystemService(PerformanceHintManager::class.java)
|
||||
?: return "game thread hints: no PerformanceHintManager"
|
||||
val pm = context.getSystemService(PowerManager::class.java)
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -11,15 +11,7 @@ import java.io.RandomAccessFile
|
||||
import java.nio.charset.StandardCharsets
|
||||
|
||||
class LoadingState(context: Context, private val steam: Boolean = true) {
|
||||
private val prefs = context.getSharedPreferences("loading", Context.MODE_PRIVATE)
|
||||
private val firstRun = steam && !prefs.getBoolean(FIRST_DONE, false)
|
||||
private var shown by mutableStateOf(true)
|
||||
var visible: Boolean
|
||||
get() = shown
|
||||
set(value) {
|
||||
shown = value
|
||||
if (!value && steam) prefs.edit().putBoolean(FIRST_DONE, true).apply()
|
||||
}
|
||||
var visible by mutableStateOf(true)
|
||||
var step by mutableStateOf(context.getString(com.droiddeck.launcher.R.string.loadstate_starting))
|
||||
private set
|
||||
var topic by mutableStateOf(Topic.SESSION)
|
||||
@@ -41,7 +33,7 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
||||
fun tick() {
|
||||
val seconds = (SystemClock.elapsedRealtime() - startedAt) / 1000
|
||||
elapsed = res.getString(com.droiddeck.launcher.R.string.loadstate_elapsed, seconds / 60, seconds % 60)
|
||||
hint = if (firstRun) res.getString(com.droiddeck.launcher.R.string.loading_first_run) else hints[((seconds / 8) % hints.size).toInt()]
|
||||
hint = hints[((seconds / 8) % hints.size).toInt()]
|
||||
}
|
||||
|
||||
fun say(line: String, topic: Topic, readable: Boolean) {
|
||||
@@ -67,8 +59,6 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
||||
|
||||
private class Line(val line: String, val percent: Int, val topic: Topic, val readable: Boolean)
|
||||
|
||||
private var scriptStep: Line? = null
|
||||
|
||||
private fun read(context: Context, log: File?): Line? {
|
||||
if (log == null || !log.isFile) return null
|
||||
val text = try {
|
||||
@@ -91,7 +81,6 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
||||
var clientDownloadAt = -1
|
||||
var clientDownload: String? = null
|
||||
var clientPercent = -1
|
||||
var unknownAt = -1
|
||||
var offset = 0
|
||||
for (line in text.split('\n')) {
|
||||
val at = offset
|
||||
@@ -106,34 +95,16 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
||||
}
|
||||
} else {
|
||||
val m = UPDATE_PROGRESS.find(line)
|
||||
val p = if (m == null && steam) UPDATE_PERCENT.find(line) else null
|
||||
if (m != null) {
|
||||
downloadAt = at
|
||||
val done = m.groupValues[1].replace(",", "").toLong()
|
||||
val total = maxOf(1L, m.groupValues[2].replace(",", "").toLong())
|
||||
val done = m.groupValues[1].toLong()
|
||||
val total = maxOf(1L, m.groupValues[2].toLong())
|
||||
downloadPercent = (done * 100 / total).toInt()
|
||||
} else if (p != null) {
|
||||
val percent = p.groupValues[1].toIntOrNull() ?: continue
|
||||
if (percent < 0) {
|
||||
downloadAt = -1
|
||||
unknownAt = at
|
||||
} else if (percent > 0 && applyingAt <= stepAt) {
|
||||
downloadAt = at
|
||||
downloadPercent = percent.coerceAtMost(100)
|
||||
}
|
||||
} else if (steam && UPDATE_APPLYING.matches(line)) {
|
||||
applyingAt = at
|
||||
}
|
||||
}
|
||||
}
|
||||
val stepLine = when {
|
||||
clientDownloadAt == stepAt && clientDownload != null -> Line(
|
||||
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_client, clientDownload), clientPercent,
|
||||
Topic.STEAM, readable = true,
|
||||
)
|
||||
stepText != null -> Line(stepText, -1, topicOf(stepText, steam), readableScriptStep(stepText))
|
||||
else -> null
|
||||
}?.also { scriptStep = it }
|
||||
return when {
|
||||
applyingAt > stepAt && applyingAt > downloadAt -> Line(
|
||||
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update_applying), -1,
|
||||
@@ -143,10 +114,11 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
||||
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update, downloadPercent), downloadPercent,
|
||||
Topic.STEAM, readable = true,
|
||||
)
|
||||
stepLine != null -> stepLine
|
||||
unknownAt >= 0 -> scriptStep ?: Line(
|
||||
context.getString(com.droiddeck.launcher.R.string.loadstate_starting), -1, Topic.SESSION, readable = false,
|
||||
clientDownloadAt == stepAt && clientDownload != null -> Line(
|
||||
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_client, clientDownload), clientPercent,
|
||||
Topic.STEAM, readable = true,
|
||||
)
|
||||
stepText != null -> Line(stepText, -1, topicOf(stepText, steam), readableScriptStep(stepText))
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
@@ -154,7 +126,6 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
||||
enum class Topic { RUNTIME, SESSION, DESKTOP, STEAM, STEAM_STARTING, OTHER }
|
||||
|
||||
companion object {
|
||||
private const val FIRST_DONE = "first_done"
|
||||
internal fun topicOf(scriptStep: String, steam: Boolean): Topic {
|
||||
val t = scriptStep.lowercase()
|
||||
return when {
|
||||
@@ -186,8 +157,7 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
|
||||
}
|
||||
|
||||
private const val TAIL_BYTES = 48L * 1024
|
||||
private val UPDATE_PROGRESS = Regex("""Downloading update \(([\d,]+) of ([\d,]+) KB\)""")
|
||||
private val UPDATE_PERCENT = Regex("""^\[[^\]]+\] Set percent complete: (-?\d+)\s*$""")
|
||||
private val UPDATE_PROGRESS = Regex("""Downloading update \((\d+) of (\d+) KB\)""")
|
||||
private val UPDATE_APPLYING = Regex("""^\s*(?:\[[^\]]+\]\s*)*(?:Extracting package|Installing update)\.\.\.\s*$""")
|
||||
private val INSTALL_COUNT = Regex("""downloading Steam: (\S+) \((\d+)/(\d+)\)""")
|
||||
private val INSTALL_MEGABYTES = Regex("""^, (\d+) of (\d+) MB""")
|
||||
|
||||
@@ -2,20 +2,16 @@ package com.droiddeck.launcher.session
|
||||
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.agent.AgentGuest
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import java.io.File
|
||||
|
||||
object OfflineMode {
|
||||
private const val TAG = "OfflineMode"
|
||||
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 SKIP = Regex("""^(\s*"SkipOfflineModeWarning"\s*")([01])(".*)$""")
|
||||
private val REMEMBER = Regex(""""RememberPassword"\s*"1"""")
|
||||
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)
|
||||
|
||||
@@ -23,12 +19,10 @@ object OfflineMode {
|
||||
|
||||
private fun x64LoginUsers(root: File) = File(root, "root/.droiddeck-x64/.local/share/Steam/config/loginusers.vdf")
|
||||
|
||||
private fun activeLoginUsers(context: Context, root: File) =
|
||||
x64LoginUsers(root).takeIf { SessionPrefs.activeSteamClientArch(context) == "x86_64" && it.isFile }
|
||||
?: loginUsers(root)
|
||||
|
||||
fun account(context: Context): String? {
|
||||
val file = activeLoginUsers(context, LinuxRuntime.rootDir(context))
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
val file = x64LoginUsers(root).takeIf { SessionPrefs.activeSteamClientArch(context) == "x86_64" && it.isFile }
|
||||
?: loginUsers(root)
|
||||
val text = try {
|
||||
if (file.isFile) file.readText() else return null
|
||||
} catch (e: Exception) {
|
||||
@@ -38,114 +32,21 @@ object OfflineMode {
|
||||
return PERSONA.find(text)?.groupValues?.get(1)?.takeIf { it.isNotBlank() }.orEmpty()
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
fun enabled(context: Context): Boolean = prefs(context).getBoolean(KEY, false)
|
||||
|
||||
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) {
|
||||
write(context, LinuxRuntime.rootDir(context), on)
|
||||
SteamOfflineFollow.request()
|
||||
prefs(context).edit().putBoolean(KEY, on).apply()
|
||||
apply(context, LinuxRuntime.rootDir(context))
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun setAuto(context: Context, on: Boolean) {
|
||||
val manual = if (on) false else steamWants(context, LinuxRuntime.rootDir(context)) ?: active(context)
|
||||
prefs(context).edit().putBoolean(AUTO_KEY, on).commit()
|
||||
setEnabled(context, manual)
|
||||
fun apply(context: Context, root: File) {
|
||||
applyTo(context, loginUsers(root))
|
||||
applyTo(context, x64LoginUsers(root))
|
||||
}
|
||||
|
||||
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) {
|
||||
private fun applyTo(context: Context, file: File) {
|
||||
if (!file.isFile) return
|
||||
val want = if (offline) "1" else "0"
|
||||
val want = if (enabled(context)) "1" else "0"
|
||||
try {
|
||||
val lines = file.readLines()
|
||||
val out = ArrayList<String>(lines.size + 4)
|
||||
@@ -193,25 +94,4 @@ object OfflineMode {
|
||||
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";
|
||||
})"""
|
||||
}
|
||||
@@ -26,34 +26,8 @@ object Onboarding {
|
||||
@Volatile private var appContext: Context? = null
|
||||
private var hold: (() -> Unit)? = null
|
||||
|
||||
/** The setup screens belong to the first run; later runtime, Proton and Steam client updates keep the usual Play button. */
|
||||
val firstRun = MutableStateFlow(true)
|
||||
|
||||
fun attach(context: Context) {
|
||||
appContext = context.applicationContext
|
||||
val prefs = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
||||
var done = prefs.getBoolean(KEY_FIRST_RUN_DONE, false)
|
||||
if (!done && runCatching { installedAndReady(context) }.getOrDefault(false)) {
|
||||
done = true
|
||||
prefs.edit().putBoolean(KEY_FIRST_RUN_DONE, true).apply()
|
||||
}
|
||||
firstRun.value = !done
|
||||
}
|
||||
|
||||
/** Everything first run installs is in place, with the same Proton rule as [recheck]. */
|
||||
private fun installedAndReady(context: Context): Boolean {
|
||||
val own = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
|
||||
return LinuxRuntime.isInstalled(context) && !SteamClientPrefetch.pending(context) &&
|
||||
(ProtonExtras.declined(context) || ProtonExtras.installedAll(context, own).isNotEmpty())
|
||||
}
|
||||
|
||||
private const val PREFS = "onboarding"
|
||||
private const val KEY_FIRST_RUN_DONE = "first_run_done"
|
||||
|
||||
private fun markFirstRunDone() {
|
||||
val context = appContext ?: return
|
||||
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(KEY_FIRST_RUN_DONE, true).apply()
|
||||
firstRun.value = false
|
||||
}
|
||||
|
||||
/** Keeps the process in the foreground, with one notification, while a step downloads and the runtime installer is not already doing so. */
|
||||
@@ -78,15 +52,6 @@ object Onboarding {
|
||||
proton = ProtonExtras.declined(context) || ProtonExtras.installedAll(context, own).isNotEmpty(),
|
||||
steam = runtime && !SteamClientPrefetch.pending(context),
|
||||
)
|
||||
settle()
|
||||
}
|
||||
|
||||
/** A new attempt starts from zero once everything is ready, whichever screen is showing. */
|
||||
@Synchronized fun settle() {
|
||||
if (!pending(rows(active.value, failed.value, facts.value))) {
|
||||
resetProgress()
|
||||
markFirstRunDone()
|
||||
}
|
||||
}
|
||||
|
||||
fun report(step: Step, label: String, percent: Int) {
|
||||
@@ -120,29 +85,9 @@ object Onboarding {
|
||||
|
||||
fun pending(rows: List<Row>): Boolean = rows.any { it.state != State.DONE }
|
||||
|
||||
/** Whether first-run downloads are under way, as the home screen decides it. */
|
||||
fun settling(): Boolean = firstRun.value && active.value.isNotEmpty() && pending(rows(active.value, failed.value, facts.value))
|
||||
|
||||
@Volatile private var highWater = 0
|
||||
|
||||
@Synchronized internal fun resetProgress() { highWater = 0 }
|
||||
|
||||
/**
|
||||
* The aggregate fraction of the whole first-run work, weighting each step by what it downloads: about 290 MB, 630 MB and 1,050 MB.
|
||||
* Steps download first and install later, restarting their own percent, so the figure only moves forward until everything is done.
|
||||
*/
|
||||
@Synchronized fun overall(rows: List<Row>): Int {
|
||||
val measured = measure(rows)
|
||||
if (!pending(rows)) {
|
||||
highWater = 0
|
||||
return measured
|
||||
}
|
||||
highWater = maxOf(highWater, measured)
|
||||
return highWater
|
||||
}
|
||||
|
||||
internal fun measure(rows: List<Row>): Int {
|
||||
val weights = mapOf(Step.RUNTIME to 20, Step.PROTON to 30, Step.STEAM to 50)
|
||||
/** The aggregate fraction of the whole first-run work, weighting each step by what it downloads. */
|
||||
fun overall(rows: List<Row>): Int {
|
||||
val weights = mapOf(Step.RUNTIME to 60, Step.PROTON to 15, Step.STEAM to 25)
|
||||
val total = weights.values.sum()
|
||||
val got = rows.sumOf { row ->
|
||||
val w = weights.getValue(row.step)
|
||||
|
||||
@@ -14,8 +14,7 @@ object ProtonDefault {
|
||||
|
||||
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 State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>,
|
||||
val source: String? = null)
|
||||
data class State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>)
|
||||
data class GameChoice(val valve: Boolean, val dir: String)
|
||||
|
||||
enum class Outcome { LIVE, NEXT_START, NOT_RUNNABLE }
|
||||
@@ -35,7 +34,6 @@ object ProtonDefault {
|
||||
Tool(t.optString("name"), t.optString("display"), t.optString("dir"), t.optBoolean("valve"))
|
||||
}?.takeIf { it.name.isNotEmpty() }
|
||||
},
|
||||
source = o.optString("source").ifEmpty { null },
|
||||
)
|
||||
}
|
||||
|
||||
@@ -101,13 +99,7 @@ object ProtonDefault {
|
||||
if (!runnable(state, proton)) return Outcome.NOT_RUNNABLE
|
||||
val d = dir(context)
|
||||
val seq = nextSeq(System.currentTimeMillis(), state, parseRequest(read(File(d, "request.json"))))
|
||||
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 body = JSONObject().put("seq", seq).put("valve", proton.valve).put("dir", proton.dir.name).toString(1) + "\n"
|
||||
val staged = File(d, "request.json.staged")
|
||||
try {
|
||||
d.mkdirs()
|
||||
@@ -118,45 +110,8 @@ object ProtonDefault {
|
||||
Log.w(TAG, "could not write the Proton request", e)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
// 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) }
|
||||
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
|
||||
}
|
||||
|
||||
internal fun movedGames(choices: Map<String, GameChoice?>, from: Set<String>, to: String): Map<String, GameChoice?>? {
|
||||
|
||||
@@ -8,7 +8,6 @@ import android.util.Log
|
||||
import com.droiddeck.launcher.core.Downloader
|
||||
import com.droiddeck.launcher.core.FileUtils
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.runtime.NativeGuest
|
||||
import java.io.File
|
||||
import java.util.Locale
|
||||
import org.json.JSONArray
|
||||
@@ -26,34 +25,23 @@ object ProtonExtras {
|
||||
var installInProgress = false
|
||||
@Volatile var prefetching = false
|
||||
private set
|
||||
@Volatile private var checkedArchive: Triple<String, Long, Long>? = null
|
||||
@Volatile private var checkedDigest: String? = null
|
||||
|
||||
private fun fingerprint(archive: File) = Triple(archive.path, archive.length(), archive.lastModified())
|
||||
@Volatile
|
||||
private var replacing = false
|
||||
|
||||
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex,
|
||||
val prereleases: Boolean = false)
|
||||
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
|
||||
|
||||
internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
|
||||
val sha256: String? = null, val releaseName: String = tag)
|
||||
internal data class ReleaseFetch(val releases: JSONArray, val complete: Boolean)
|
||||
|
||||
const val OWN = "droiddeck"
|
||||
const val BIONIC = "bionic"
|
||||
|
||||
val tools = listOf(
|
||||
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("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),
|
||||
Tool("droiddeck", "DroidDeck-Proton", "DroidDeck-Proton", "Droid-Deck/DroidDeck-Proton", Regex("aarch64\\.tar\\.(gz|xz)$")),
|
||||
)
|
||||
|
||||
/** 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 requests(context: Context) = File(home(context), ".dd-proton-extra")
|
||||
private fun toolsDir(context: Context) = File(home(context), ".local/share/Steam/compatibilitytools.d")
|
||||
@@ -128,11 +116,10 @@ object ProtonExtras {
|
||||
private var lastAttempt = 0L
|
||||
|
||||
fun checkLatest(context: Context, force: Boolean = false, now: Long = System.currentTimeMillis()): Boolean {
|
||||
keepBionicCurrent(context)
|
||||
synchronized(checkLock) {
|
||||
val file = latestFile(context)
|
||||
val cache = readJson(file)
|
||||
val due = offered(context).filter { tool ->
|
||||
val due = tools.filter { tool ->
|
||||
val at = cache.optJSONObject(tool.id)?.optLong("at", 0L) ?: 0L
|
||||
force || (now - at) !in 0 until CHECK_EVERY_MS
|
||||
}
|
||||
@@ -182,32 +169,15 @@ object ProtonExtras {
|
||||
|
||||
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
|
||||
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())
|
||||
if (File(toolsDir(context), name).deleteRecursively()) ComponentsManager.forgetProton(context, name)
|
||||
}
|
||||
|
||||
fun removeOlder(context: Context, tool: Tool) {
|
||||
installedAll(context, tool).dropLast(1).forEach {
|
||||
if (deleteTool(context, it)) ComponentsManager.forgetProton(context, it)
|
||||
if (File(toolsDir(context), it).deleteRecursively()) 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) {
|
||||
val all = installedAll(context, tool)
|
||||
val newest = all.lastOrNull() ?: return
|
||||
@@ -220,9 +190,7 @@ object ProtonExtras {
|
||||
if (runCatching { ComponentsManager.carryOver(context, old, newest) }.onFailure { Log.w(TAG, "components of $old", it) }.isFailure) continue
|
||||
if (runCatching { keepUserSettings(context, old, newest) }.onFailure { Log.w(TAG, "user settings of $old", it) }.isFailure) continue
|
||||
if (runCatching { ProtonDefault.moveGames(context, setOf(old), newest) }.onFailure { Log.w(TAG, "per-game picks of $old", it) }.isFailure) continue
|
||||
// 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)
|
||||
if (File(toolsDir(context), old).deleteRecursively()) ComponentsManager.forgetProton(context, old)
|
||||
else Log.w(TAG, "could not remove $old")
|
||||
}
|
||||
} finally {
|
||||
@@ -249,24 +217,21 @@ object ProtonExtras {
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun install(context: Context, tool: Tool, cancelled: java.util.function.BooleanSupplier? = null,
|
||||
onProgress: (String, Int) -> Unit): String? {
|
||||
fun install(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
if (installInProgress || prefetching) return context.getString(R.string.pextra_busy)
|
||||
installInProgress = true
|
||||
return try { installNow(context, tool, cancelled, onProgress) } finally { installInProgress = false }
|
||||
return try { installNow(context, tool, onProgress) } finally { installInProgress = false }
|
||||
}
|
||||
|
||||
private fun fetchArchive(context: Context, tool: Tool, asset: Asset, archive: File, onProgress: (String, Int) -> Unit,
|
||||
cancelled: java.util.function.BooleanSupplier? = null): String? {
|
||||
private fun fetchArchive(context: Context, tool: Tool, asset: Asset, archive: File, onProgress: (String, Int) -> Unit): String? {
|
||||
val downloading = context.getString(R.string.pextra_downloading, tool.name, asset.tag)
|
||||
onProgress(downloading, 0)
|
||||
var downloaded = false
|
||||
for (attempt in 0 until 5) {
|
||||
downloaded = Downloader.downloadFile(asset.url, archive, true, asset.sha256, cancelled) { fraction ->
|
||||
downloaded = Downloader.downloadFile(asset.url, archive, true, asset.sha256) { fraction ->
|
||||
onProgress(downloading, if (fraction < 0) -1 else (fraction * 100f).toInt().coerceIn(0, 100))
|
||||
}
|
||||
if (downloaded) break
|
||||
if (cancelled?.asBoolean == true) return context.getString(R.string.pextra_interrupted)
|
||||
if (attempt < 4) {
|
||||
onProgress(context.getString(R.string.pextra_retrying, attempt + 2, 5), -1)
|
||||
try { Thread.sleep(3_000) } catch (_: InterruptedException) {
|
||||
@@ -294,14 +259,10 @@ object ProtonExtras {
|
||||
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
|
||||
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
|
||||
if (StatFs(context.filesDir.path).availableBytes < NEED_BYTES + missing) return context.getString(R.string.pextra_no_space, tool.name)
|
||||
val problem = fetchArchive(context, tool, asset, archive, onProgress)
|
||||
checkedArchive = if (problem == null && asset.sha256 != null && asset.size > 0 && archive.length() == asset.size) fingerprint(archive) else null
|
||||
checkedDigest = if (checkedArchive != null) asset.sha256 else null
|
||||
return problem
|
||||
return fetchArchive(context, tool, asset, archive, onProgress)
|
||||
}
|
||||
|
||||
private fun installNow(context: Context, tool: Tool, cancelled: java.util.function.BooleanSupplier?,
|
||||
onProgress: (String, Int) -> Unit): String? {
|
||||
private fun installNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
|
||||
if (SessionState.running) return context.getString(R.string.pextra_stop_session)
|
||||
if (!LinuxRuntime.isInstalled(context)) return context.getString(R.string.user_apps_runtime_required)
|
||||
|
||||
@@ -314,9 +275,7 @@ object ProtonExtras {
|
||||
return context.getString(R.string.pextra_no_space, tool.name)
|
||||
}
|
||||
|
||||
val checked = asset.sha256 != null && asset.size > 0 && checkedArchive == fingerprint(archive) &&
|
||||
checkedDigest.equals(asset.sha256, ignoreCase = true)
|
||||
if (!checked) fetchArchive(context, tool, asset, archive, onProgress, cancelled)?.let { return it }
|
||||
fetchArchive(context, tool, asset, archive, onProgress)?.let { return it }
|
||||
if (asset.size > 0 && archive.length() != asset.size) {
|
||||
if (archive.length() > asset.size) {
|
||||
archive.delete()
|
||||
@@ -327,7 +286,6 @@ object ProtonExtras {
|
||||
|
||||
onProgress(context.getString(R.string.pextra_verifying), -1)
|
||||
val verified = when {
|
||||
checked -> true
|
||||
asset.sha256 != null -> asset.sha256.equals(Hashes.sha256(archive), ignoreCase = true)
|
||||
asset.sha512 != null -> {
|
||||
val expected = Downloader.downloadDirect(asset.sha512)?.let { Regex("(?i)\\b[0-9a-f]{128}\\b").find(it)?.value }
|
||||
@@ -374,7 +332,7 @@ object ProtonExtras {
|
||||
archive.delete()
|
||||
unqueue(context, tool)
|
||||
record(context, tool, placed, asset.tag)
|
||||
if (tool.id == OWN || tool.id == BIONIC) replaceOlder(context, tool)
|
||||
if (tool.id == OWN) replaceOlder(context, tool)
|
||||
if (EsyncPacks.enabled(context)) {
|
||||
onProgress(context.getString(R.string.esync_fetching), -1)
|
||||
try {
|
||||
@@ -459,7 +417,7 @@ object ProtonExtras {
|
||||
internal fun pickAsset(tool: Tool, array: JSONArray): Asset? {
|
||||
val candidates = (0 until array.length()).asSequence()
|
||||
.mapNotNull { array.optJSONObject(it) }
|
||||
.filter { !it.optBoolean("draft", false) && (tool.prereleases || !it.optBoolean("prerelease", false)) }
|
||||
.filter { !it.optBoolean("draft", false) && !it.optBoolean("prerelease", false) }
|
||||
return candidates.firstNotNullOfOrNull { assetOf(tool, it) }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
/** A launch the user asked for that waits for something else to finish first, and is forgotten if it waits too long. */
|
||||
class QueuedLaunch<T : Any>(private val lifetimeMs: Long = 15 * 60_000L) {
|
||||
var launch: T? = null
|
||||
private set
|
||||
var queuedAt: Long = 0L
|
||||
private set
|
||||
|
||||
fun queue(launch: T, now: Long) {
|
||||
this.launch = launch
|
||||
queuedAt = now
|
||||
}
|
||||
|
||||
/** Takes back a saved launch with the time it was first queued; one without a valid time or past its lifetime is dropped. */
|
||||
fun restore(launch: T?, queuedAt: Long, now: Long) {
|
||||
if (launch != null && fresh(queuedAt, now)) {
|
||||
this.launch = launch
|
||||
this.queuedAt = queuedAt
|
||||
} else {
|
||||
clear()
|
||||
}
|
||||
}
|
||||
|
||||
/** The launch if it is still wanted; an expired one is cleared. */
|
||||
fun current(now: Long): T? {
|
||||
val queued = launch ?: return null
|
||||
if (fresh(queuedAt, now)) return queued
|
||||
clear()
|
||||
return null
|
||||
}
|
||||
|
||||
fun clear() {
|
||||
launch = null
|
||||
}
|
||||
|
||||
private fun fresh(queuedAt: Long, now: Long) = now - queuedAt in 0..lifetimeMs
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package com.droiddeck.launcher.session
|
||||
|
||||
/**
|
||||
* Starts a queued launch once nothing stands in its way and retries until it can or it expires. One runner belongs to one
|
||||
* activity: destroying it clears its queue and cancels its retry, so a restored activity is the only one that starts the launch.
|
||||
*/
|
||||
class QueuedLaunchRunner<T : Any>(
|
||||
private val queue: QueuedLaunch<T>,
|
||||
private val now: () -> Long,
|
||||
private val blocked: () -> Boolean,
|
||||
private val busy: () -> Boolean,
|
||||
private val schedule: (delayMs: Long, task: Runnable) -> Unit,
|
||||
private val unschedule: (Runnable) -> Unit,
|
||||
private val start: (T) -> Unit,
|
||||
private val retryMs: Long = 2_000L,
|
||||
) {
|
||||
private var posted = false
|
||||
private var retry: Runnable? = null
|
||||
private var destroyed = false
|
||||
|
||||
/** Call whenever the blocking setting may have changed. */
|
||||
fun poke() {
|
||||
if (destroyed || posted) return
|
||||
val launch = queue.current(now()) ?: return
|
||||
if (blocked()) return
|
||||
posted = true
|
||||
schedule(0L, Runnable {
|
||||
posted = false
|
||||
attempt(launch)
|
||||
})
|
||||
}
|
||||
|
||||
private fun attempt(launch: T) {
|
||||
if (destroyed || queue.current(now()) !== launch) return
|
||||
if (busy()) {
|
||||
val again = Runnable { if (!destroyed && queue.launch === launch) poke() }
|
||||
retry = again
|
||||
schedule(retryMs, again)
|
||||
return
|
||||
}
|
||||
queue.clear()
|
||||
start(launch)
|
||||
}
|
||||
|
||||
fun destroy() {
|
||||
destroyed = true
|
||||
queue.clear()
|
||||
retry?.let(unschedule)
|
||||
retry = null
|
||||
}
|
||||
}
|
||||
@@ -75,7 +75,6 @@ object SessionArtifacts {
|
||||
LogRedactor.learnFromRuntime(LinuxRuntime.rootDir(context))
|
||||
val record = Record(dir)
|
||||
copySteamLogs(context, dir, record, steamArch)
|
||||
copyRpcs3Log(context, dir, record)
|
||||
VacDiagnostics.collect(context, dir)
|
||||
SessionLogCapture.dumpCrashBuffer(File(dir, "crash.log"))
|
||||
SessionLogCapture.dumpMemoryPressure(File(dir, "memory-pressure.log"))
|
||||
@@ -322,9 +321,6 @@ object SessionArtifacts {
|
||||
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 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 HEAD = 4096L
|
||||
|
||||
@@ -332,19 +328,11 @@ object SessionArtifacts {
|
||||
private class CopyResult(val files: List<File>, val failed: Boolean, val deferred: Boolean)
|
||||
|
||||
fun markSteamLogs(dir: File, logs: File) {
|
||||
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 lines = logs.listFiles { f -> f.isFile }?.mapNotNull { f ->
|
||||
val size = f.length()
|
||||
head(f, size)?.let { "$size\t$it\t${f.name}" }
|
||||
}
|
||||
runCatching { File(dir, marks).writeText(lines.joinToString("") { "$it\n" }) }
|
||||
} ?: return
|
||||
runCatching { File(dir, LOG_MARKS).writeText(lines.joinToString("") { "$it\n" }) }
|
||||
}
|
||||
|
||||
private fun head(f: File, length: Long): String? = runCatching {
|
||||
@@ -360,8 +348,8 @@ object SessionArtifacts {
|
||||
java.security.MessageDigest.getInstance("SHA-1").digest(buf).joinToString("") { "%02x".format(it) }
|
||||
}.getOrNull()
|
||||
|
||||
private fun logMarks(dir: File, marks: String): List<Mark>? = runCatching {
|
||||
File(dir, marks).readLines().mapNotNull { line ->
|
||||
private fun steamLogMarks(dir: File): List<Mark>? = runCatching {
|
||||
File(dir, LOG_MARKS).readLines().mapNotNull { line ->
|
||||
val parts = line.split('\t', limit = 3)
|
||||
parts.getOrNull(0)?.toLongOrNull()?.let { size -> parts.getOrNull(1)?.let { Mark(size, it) } }
|
||||
}
|
||||
@@ -383,32 +371,11 @@ object SessionArtifacts {
|
||||
val logs = File(steamArch?.let { SessionPrefs.steamRoot(context, it) } ?: SessionPrefs.activeSteamRoot(context), "logs")
|
||||
if (!logs.isDirectory) return
|
||||
val out = File(dir, "steam").apply { mkdirs() }
|
||||
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) {
|
||||
val result = copySessionLogsResult(logs, dir, out) { stopWhenSessionStarts && SessionState.running }
|
||||
result.files.forEach { dst -> record.files[dst] = Scrubbed(dst.length(), dst.lastModified()) }
|
||||
record.failed = record.failed || result.failed
|
||||
record.deferred = record.deferred || result.deferred
|
||||
Log.i(TAG, "collected ${out.listFiles()?.size ?: 0} Steam log(s), scrubbed, into $out")
|
||||
}
|
||||
|
||||
internal fun copySessionLogs(
|
||||
@@ -416,22 +383,20 @@ object SessionArtifacts {
|
||||
dir: File,
|
||||
out: File,
|
||||
openWriter: (File) -> Writer = { it.bufferedWriter() },
|
||||
): List<File> = copySessionLogsResult(logs, dir, out, openWriter = openWriter) { false }.files
|
||||
): List<File> = copySessionLogsResult(logs, dir, out, openWriter) { false }.files
|
||||
|
||||
private fun copySessionLogsResult(
|
||||
logs: File,
|
||||
dir: File,
|
||||
out: File,
|
||||
marksName: String = LOG_MARKS,
|
||||
accept: (File) -> Boolean = { true },
|
||||
openWriter: (File) -> Writer = { it.bufferedWriter() },
|
||||
shouldStop: () -> Boolean,
|
||||
): CopyResult {
|
||||
val marks = logMarks(dir, marksName)
|
||||
val marks = steamLogMarks(dir)
|
||||
val copied = ArrayList<File>()
|
||||
var failed = false
|
||||
var deferred = false
|
||||
val sources = logs.listFiles { f -> f.isFile && accept(f) } ?: return CopyResult(copied, true, false)
|
||||
val sources = logs.listFiles { f -> f.isFile } ?: return CopyResult(copied, true, false)
|
||||
for (src in sources) {
|
||||
if (shouldStop()) {
|
||||
failed = true
|
||||
@@ -602,7 +567,6 @@ object SessionArtifacts {
|
||||
steamArch = recordedClient(dir),
|
||||
stopWhenSessionStarts = stopWhenSessionStarts,
|
||||
)
|
||||
copyRpcs3Log(context, dir, record, stopWhenSessionStarts)
|
||||
if (!record.deferred && (!stopWhenSessionStarts || !SessionState.running)) {
|
||||
if (!record.failed && VacDiagnostics.collect(context, dir)) {
|
||||
try {
|
||||
|
||||
@@ -28,14 +28,12 @@ object SessionFiles {
|
||||
"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-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-library-perms" to "usr/local/bin/droiddeck-library-perms",
|
||||
"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/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/fastfetch/config.jsonc" to "etc/xdg/fastfetch/config.jsonc",
|
||||
)
|
||||
|
||||
private val SERVICE_PACKS = mapOf(
|
||||
@@ -132,7 +130,6 @@ object SessionFiles {
|
||||
"usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard",
|
||||
"usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window",
|
||||
"usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install",
|
||||
"usr/local/bin/droiddeck-steam-preapply" to "usr/local/bin/droiddeck-steam-preapply",
|
||||
"usr/local/bin/droiddeck-steam-ui-scale" to "usr/local/bin/droiddeck-steam-ui-scale",
|
||||
"usr/local/bin/droiddeck-steam-language" to "usr/local/bin/droiddeck-steam-language",
|
||||
"usr/local/bin/droiddeck-steam-shaders" to "usr/local/bin/droiddeck-steam-shaders",
|
||||
@@ -145,7 +142,6 @@ object SessionFiles {
|
||||
"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-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-desktop-games" to "usr/local/bin/droiddeck-desktop-games",
|
||||
"usr/local/bin/droiddeck-desktop-programs" to "usr/local/bin/droiddeck-desktop-programs",
|
||||
@@ -157,7 +153,6 @@ object SessionFiles {
|
||||
"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-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-systemd-run" to "usr/local/bin/systemd-run",
|
||||
"usr/local/bin/droiddeck-snap-cli" to "usr/local/bin/snap",
|
||||
@@ -267,9 +262,7 @@ object SessionFiles {
|
||||
"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/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/share/licenses/dwarfs/LICENSE" to "usr/local/share/licenses/dwarfs/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, _) ->
|
||||
val dir = asset.substringBeforeLast('/')
|
||||
|
||||
@@ -448,13 +448,6 @@ object SessionPrefs {
|
||||
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() }
|
||||
|
||||
val STORES_SORTS = listOf("lastPlayed", "recentlyInstalled", "titleAsc", "titleDesc", "sizeDesc", "sizeAsc", "releaseDateDesc")
|
||||
@@ -509,13 +502,6 @@ object SessionPrefs {
|
||||
|
||||
fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean(hudKey(context), false)
|
||||
|
||||
fun hudOnlyDuringGame(context: Context): Boolean =
|
||||
prefs(context).getBoolean("hudOnlyDuringGame", false)
|
||||
|
||||
fun setHudOnlyDuringGame(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("hudOnlyDuringGame", on).apply()
|
||||
}
|
||||
|
||||
fun setHudEnabled(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean(hudKey(context), on).apply()
|
||||
}
|
||||
@@ -821,11 +807,6 @@ object SessionPrefs {
|
||||
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 =
|
||||
prefs(context).getString("picturePosition", "center")
|
||||
@@ -845,15 +826,6 @@ object SessionPrefs {
|
||||
|
||||
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) {
|
||||
prefs(context).edit().putBoolean("returnAfterGame", on).apply()
|
||||
}
|
||||
@@ -1058,7 +1030,7 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("prootFastPath", on).apply()
|
||||
}
|
||||
|
||||
fun cursorComposite(context: Context): Boolean = prefs(context).getBoolean("cursorComposite", true)
|
||||
fun cursorComposite(context: Context): Boolean = prefs(context).getBoolean("cursorComposite", false)
|
||||
|
||||
fun setCursorComposite(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("cursorComposite", on).apply()
|
||||
@@ -1364,10 +1336,6 @@ object SessionPrefs {
|
||||
SessionDisplay.effectiveChoice(
|
||||
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 {
|
||||
if (!portrait) return landscapeResolutionStored(context, mode, panel)
|
||||
val value = prefs(context).getString("displayResolution.portrait.$mode", null) ?: return SessionDisplay.LINK_LANDSCAPE
|
||||
@@ -1578,7 +1546,7 @@ object SessionPrefs {
|
||||
fun adoptAddedGameExe(context: Context, folderPath: String, expected: String, path: String, seen: Int): Boolean =
|
||||
synchronized(addedGameLock) {
|
||||
val unchanged = addedGameExe(context, folderPath) == expected
|
||||
if (unchanged) prefs(context).edit().putString("addedExe:$folderPath", path).putString("addedAdopted:Exe:$folderPath", path).putInt("addedExeSeen:$folderPath", seen).apply()
|
||||
if (unchanged) prefs(context).edit().putString("addedExe:$folderPath", path).putInt("addedExeSeen:$folderPath", seen).apply()
|
||||
unchanged
|
||||
}
|
||||
|
||||
|
||||
@@ -669,8 +669,6 @@ class SessionService : Service() {
|
||||
guest.add("DROIDDECK_WSI_BYPASS_CHECK_MS=100")
|
||||
guest.add("WINE_OFFSCREEN_CHECK_MS=100")
|
||||
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_DEBUG_DIR=" + sessionDir.path)
|
||||
if (EnhancedDiagnostics.isActive(this, sessionDir)) guest.add("DROIDDECK_ENHANCED_DIAGNOSTICS=1")
|
||||
@@ -696,7 +694,7 @@ class SessionService : Service() {
|
||||
val added = SessionEvents.step("added-games-scan") { com.droiddeck.launcher.frontend.AddedGames.scan(this) }
|
||||
val listing = SessionEvents.step("added-games-listing") { com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added) }
|
||||
guest.add("DD_ADDED_GAMES=" + listing.path)
|
||||
if (OfflineMode.active(this)) guest.add("DD_STEAM_OFFLINE=1")
|
||||
if (OfflineMode.enabled(this)) guest.add("DD_STEAM_OFFLINE=1")
|
||||
if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("DD_LOSSLESS_OWNED=1")
|
||||
if (added.isNotEmpty()) Log.i(TAG, "added games: " + added.joinToString { "${it.name} (${it.exe.name})" })
|
||||
}
|
||||
@@ -786,7 +784,7 @@ class SessionService : Service() {
|
||||
if (drives > 0) Log.i(TAG, "$drives Wine drive links given their guest paths back")
|
||||
val hostEnv = if (nativeUserland) HostEnvironment().also { env ->
|
||||
Log.i(TAG, "native userland: no proot (${sessionBindSpecs.size} mounts)")
|
||||
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, guest.first(), SessionPrefs.guestHostname(this))
|
||||
com.droiddeck.launcher.runtime.NativeGuest.sessionEnvironment(root, sessionBindSpecs, SessionPrefs.guestHostname(this))
|
||||
.forEach { (k, v) -> env[k] = v }
|
||||
} else prootEnv
|
||||
|
||||
@@ -815,11 +813,6 @@ class SessionService : Service() {
|
||||
.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)
|
||||
networkLink.attach(this)
|
||||
networkLink.publish()
|
||||
@@ -1009,7 +1002,6 @@ class SessionService : Service() {
|
||||
))
|
||||
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") }
|
||||
guest.add("DD_VALVE_PROTON=" + if (SessionPrefs.ownProtonFirst(this)) "0" else "1")
|
||||
guest.add("XDG_RUNTIME_DIR=" + LinuxRuntime.GUEST_RUNTIME_DIR)
|
||||
guest.add("XDG_SESSION_TYPE=wayland")
|
||||
guest.add("WAYLAND_DISPLAY=wayland-0")
|
||||
@@ -1041,9 +1033,6 @@ class SessionService : Service() {
|
||||
)
|
||||
(if (bridge || venus) null else LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId))
|
||||
?.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()) {
|
||||
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)")
|
||||
@@ -1081,7 +1070,6 @@ class SessionService : Service() {
|
||||
guest.addAll(GpuStatsComponent.guestEnv(LinuxRuntime.rootDir(this)))
|
||||
guest.add("GLIBC_TUNABLES=glibc.pthread.rseq=0:glibc.malloc.top_pad=16777216")
|
||||
if (SessionState.mode == MODE_STEAM) guest.add("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?.let { arch ->
|
||||
guest.add("DD_STEAM_CLIENT_ARCH=$arch")
|
||||
@@ -1275,7 +1263,6 @@ class SessionService : Service() {
|
||||
components.add(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"))
|
||||
if (cpuStat.prepare()) {
|
||||
cpuStat.attach(this)
|
||||
|
||||
@@ -148,9 +148,6 @@ object SessionState {
|
||||
@Volatile
|
||||
var outputSize: Pair<Int, Int> = Pair(1920, 1080)
|
||||
|
||||
@Volatile
|
||||
var followScales: Pair<Float?, Float?> = null to null
|
||||
|
||||
@Volatile
|
||||
var followScreen = false
|
||||
var followScale = 1f
|
||||
|
||||
@@ -25,7 +25,7 @@ object SettingsReset {
|
||||
"noXalia", "fastSync", "fsyncFirst", "syncFallback", "prootNoSeccomp", "prootFastPath", "nativeUserland", "cursorComposite",
|
||||
"guestHostname", "fexPreset", "forceSsbs", "logs", "gameDebugLogsEnabled", "enhancedDiagnosticsNext", "storageDiagnostics", "buildWatermark",
|
||||
"upscaler", "upscaleSharpness", "screenEffects", "blackFrameInsertion", "textureAnisotropy", "textureLodBias",
|
||||
"steamDownloadsInBackground", "steam_offline", "steam_offline_auto", "steam_offline_by_network", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds", "skipBootMovie",
|
||||
"steamDownloadsInBackground", "steam_offline", "bootMovie", "bootMovieSound", "bootMovieVolume", "bootMovieSeconds", "skipBootMovie",
|
||||
"bootMovieApplyNext", "bootMovieSteamSeen", "bootMovieShuffle",
|
||||
"questDefaultsV1", "telemetryAuto", "telemetryOff", "statsStrip", "statsHud", "bottomHud", "bottomStripMetrics", "bottomStripTabs", "statsDash", "statsSpeedUnit",
|
||||
)
|
||||
@@ -67,7 +67,7 @@ object SettingsReset {
|
||||
}
|
||||
|
||||
QuestExperimental.initialize(context)
|
||||
runCatching { OfflineMode.setEnabled(context, false) }
|
||||
runCatching { OfflineMode.apply(context, LinuxRuntime.rootDir(context)) }
|
||||
.onFailure { ok = false; Log.w(TAG, "Could not turn offline mode off", it) }
|
||||
runCatching { GameEnvironmentStore.publish(context) }
|
||||
.onFailure { ok = false; Log.w(TAG, "Could not update game environment", it) }
|
||||
|
||||
@@ -61,7 +61,6 @@ object SteamClientPrefetch {
|
||||
else Onboarding.fail(Onboarding.Step.STEAM, problem ?: failedLabel)
|
||||
val steamReady = !pending(app)
|
||||
Onboarding.facts.update { it.copy(steam = steamReady) }
|
||||
Onboarding.settle()
|
||||
}, "steam-client-prefetch").also { it.start() }
|
||||
}
|
||||
|
||||
@@ -71,9 +70,11 @@ object SteamClientPrefetch {
|
||||
LinuxRuntime.writeAccounts(context)
|
||||
SessionFiles.stage(context, root)
|
||||
val install = installPending(context)
|
||||
val cacheProblem = script(context, listOf("--cache"), label, 0, if (install) 90 else 100)
|
||||
if (cacheProblem == CANCELLED || !install) return cacheProblem
|
||||
return script(context, emptyList(), label, 90, 100)
|
||||
if (install) {
|
||||
val problem = script(context, emptyList(), label, 0, 35)
|
||||
if (problem != null) return problem
|
||||
}
|
||||
return script(context, listOf("--cache"), label, if (install) 35 else 0, 100)
|
||||
}
|
||||
|
||||
private fun script(context: Context, args: List<String>, label: (Int) -> String, from: Int, to: Int): String? {
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,14 +36,13 @@ object CloudPlan {
|
||||
return Plan(transfer, conflicts, same)
|
||||
}
|
||||
|
||||
fun up(local: Map<String, Local>, remote: Map<String, Remote>, baseline: Map<String, Entry>?, deleted: Set<String> = emptySet()): Plan {
|
||||
fun up(local: Map<String, Local>, remote: Map<String, Remote>, baseline: Map<String, Entry>?): Plan {
|
||||
if (baseline == null) return Plan(emptyList(), emptyList(), emptyList(), refused = "no-baseline")
|
||||
val transfer = ArrayList<String>(); val conflicts = ArrayList<String>(); val same = ArrayList<String>()
|
||||
for ((name, l) in local) {
|
||||
val r = remote[name]
|
||||
val b = baseline[name]
|
||||
when {
|
||||
r == null && name in deleted && !localChanged(l, b) -> Unit
|
||||
r == null -> transfer += name
|
||||
same(l, r) -> same += name
|
||||
localChanged(l, b) && cloudChanged(r, b) -> conflicts += name
|
||||
|
||||
@@ -430,20 +430,17 @@ object CloudSaves {
|
||||
|
||||
internal fun md5(data: ByteArray): String = MessageDigest.getInstance("MD5").digest(data).joinToString("") { "%02x".format(it) }
|
||||
|
||||
private class Listing(val live: Map<String, CloudFile>, val deleted: Set<String>)
|
||||
|
||||
private fun remote(cloud: CloudTransport, wanted: (String) -> Boolean): Listing {
|
||||
private fun remote(cloud: CloudTransport, wanted: (String) -> Boolean): Map<String, CloudFile> {
|
||||
val files = cloud.list()
|
||||
val pool = Executors.newFixedThreadPool(PARALLEL, com.droiddeck.launcher.stores.download.DownloadQueue.workerFactory("cloud"))
|
||||
for (f in files) if (wanted(f.name)) pool.execute { runCatching { cloud.details(f) } }
|
||||
pool.shutdown(); pool.awaitTermination(2, TimeUnit.MINUTES)
|
||||
val (gone, live) = files.partition(cloud::deleted)
|
||||
return Listing(live.associateBy { it.name }, gone.mapTo(HashSet()) { it.name })
|
||||
return files.associateBy { it.name }
|
||||
}
|
||||
|
||||
internal fun downWith(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport, force: Boolean, claim: () -> Boolean = { true }): Result {
|
||||
val files = localFiles(dir).filterKeys(cloud::wants)
|
||||
val remote = remote(cloud) { it in files }.live
|
||||
val remote = remote(cloud) { it in files }
|
||||
val local = files.mapValues { CloudPlan.Local(md5(it.value)) }
|
||||
val key = scope(store, id, dir)
|
||||
val base = baseline(context, store, key)
|
||||
@@ -501,10 +498,9 @@ object CloudSaves {
|
||||
val base = baseline(context, store, key) ?: return Result("skipped", 0, 0, "no-baseline")
|
||||
val files = localFiles(dir).filterKeys(cloud::wants).let { all -> if (cloud is UbisoftCloudTransport) all.filterValues(::markUbisoftSave) else all }
|
||||
if (files.isEmpty()) return Result("skipped", 0, 0, "nothing-local")
|
||||
val listing = remote(cloud) { it in files }
|
||||
val remote = listing.live
|
||||
val remote = remote(cloud) { it in files }
|
||||
val local = files.mapValues { CloudPlan.Local(md5(it.value)) }
|
||||
val planned = CloudPlan.up(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base, listing.deleted)
|
||||
val planned = CloudPlan.up(local, remote.mapValues { CloudPlan.Remote(it.value.md5, it.value.modifiedMs) }, base)
|
||||
val alike = alike(cloud, planned.conflicts, local, remote)
|
||||
val plan = settled(planned, alike)
|
||||
val saved = savedConflicts(context, store, key).filter { it !in alike && it !in plan.same }
|
||||
@@ -551,7 +547,7 @@ object CloudSaves {
|
||||
send = send.filter { it in stamped }
|
||||
for ((name, t) in stamped) if (t > 0) files[name]?.setLastModified(t)
|
||||
}
|
||||
val after = if (send.all { cloud.committed(it) != null }) emptyMap() else remote(cloud) { it in send && cloud.committed(it) == null }.live
|
||||
val after = if (send.all { cloud.committed(it) != null }) emptyMap() else remote(cloud) { it in send && cloud.committed(it) == null }
|
||||
for (name in send) {
|
||||
val r = cloud.committed(name) ?: after[name]
|
||||
next[name] = CloudPlan.Entry(sentMd5.getValue(name), r?.md5, r?.modifiedMs ?: stamped[name] ?: -1L)
|
||||
|
||||
@@ -31,7 +31,6 @@ interface CloudTransport {
|
||||
val contentDigests: Boolean get() = true
|
||||
fun committed(name: String): CloudFile? = null
|
||||
fun wants(name: String): Boolean = true
|
||||
fun deleted(file: CloudFile): Boolean = false
|
||||
fun list(): List<CloudFile>
|
||||
fun details(file: CloudFile) {}
|
||||
fun get(file: CloudFile): Pair<ByteArray, Long>
|
||||
@@ -253,8 +252,6 @@ private fun gzipFile(src: File, dst: File): GzipFile {
|
||||
}
|
||||
}
|
||||
|
||||
internal const val GOG_DELETED_MD5 = "aadd86936a80ee8a369579c3926f1b3c"
|
||||
|
||||
internal const val GOG_CLOUD_UA = "GOGGalaxyCommunicationService/2.0.13.27 (Windows_32bit) dont_sync_marker/true installation_source/gog"
|
||||
|
||||
/** GOG Galaxy parses `X-Object-Meta-LocalLastModified`; objects without it fail as "invalid data". */
|
||||
@@ -279,11 +276,8 @@ class GogCloud(
|
||||
|
||||
private fun cloudKey(name: String) = key((prefix ?: "") + name)
|
||||
|
||||
override fun deleted(file: CloudFile): Boolean = file.md5.equals(GOG_DELETED_MD5, ignoreCase = true)
|
||||
|
||||
override fun list(): List<CloudFile> {
|
||||
val c = open(base, "GET", token, ua)
|
||||
c.setRequestProperty("Accept", "application/json")
|
||||
val code = c.responseCode
|
||||
if (code == 404) { c.disconnect(); return emptyList() }
|
||||
if (code !in 200..299) {
|
||||
@@ -306,7 +300,7 @@ class GogCloud(
|
||||
lm > 0 -> lm * 1000
|
||||
iso > 0 -> iso
|
||||
else -> -1L
|
||||
}, o.optString("hash").trim().ifEmpty { null })
|
||||
})
|
||||
}
|
||||
} else {
|
||||
text.lines().map { it.trim() }.filter { it.isNotEmpty() }.map { CloudFile(it, -1L) }
|
||||
|
||||
@@ -3,10 +3,8 @@ package com.droiddeck.launcher.stores
|
||||
import android.content.Context
|
||||
import android.os.StatFs
|
||||
import android.os.storage.StorageManager
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
import com.droiddeck.launcher.session.SecondaryLibrary
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
import java.util.zip.CRC32
|
||||
@@ -14,7 +12,6 @@ import java.util.zip.CRC32
|
||||
object StoreInstallRoot {
|
||||
const val SPACE_UNKNOWN = -1L
|
||||
private const val INTERNAL = "root/Games/Stores"
|
||||
const val INTERNAL_GUEST = "/$INTERNAL"
|
||||
private const val ON_VOLUME = "Games"
|
||||
const val GUEST_EXTERNAL = "/mnt/droiddeck-stores"
|
||||
|
||||
@@ -182,24 +179,6 @@ object StoreInstallRoot {
|
||||
fun externalBindSpecsForXodus(context: Context): List<String> =
|
||||
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> =
|
||||
roots.mapNotNull { (host, guest) ->
|
||||
if (!host.isDirectory || !host.canRead()) return@mapNotNull null
|
||||
|
||||
@@ -12,11 +12,8 @@ object StoreLaunch {
|
||||
const val EPIC_CODE = ".droiddeck-epic-code"
|
||||
const val EPIC_ARGS = ".droiddeck-epic-args"
|
||||
const val UBISOFT_LAUNCH = ".droiddeck-ubisoft.json"
|
||||
/** 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 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"
|
||||
private const val UBISOFT_SERVICE = "Z:\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe"
|
||||
const val EPIC_PARENT = "Z:\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe"
|
||||
/** Per-game environment switch: 1 starts any Epic game under [EPIC_PARENT], 0 never does. */
|
||||
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. */
|
||||
@@ -50,10 +47,6 @@ object StoreLaunch {
|
||||
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 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) {
|
||||
lines += "set \"$PARENT_VAR=${if (sidecar.id in EPIC_PARENT_TITLES) "1" else ""}\""
|
||||
lines += "if \"%$EPIC_PARENT_SWITCH%\"==\"1\" set \"$PARENT_VAR=1\""
|
||||
@@ -144,6 +137,7 @@ object StoreLaunch {
|
||||
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)
|
||||
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
|
||||
?.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
|
||||
|
||||
@@ -65,7 +65,6 @@ class StoreLoginActivity : ComponentActivity() {
|
||||
val readsPage: Boolean get() = false
|
||||
val pageScript: String get() = "(function(){ try { return document.body.innerText; } catch(e){ return ''; } })()"
|
||||
fun pageReady(result: String): Boolean = true
|
||||
fun browserStep(page: String): String? = null
|
||||
fun forgetSignIn(done: () -> Unit) = done()
|
||||
fun pageFinished(view: WebView, url: String) {}
|
||||
}
|
||||
@@ -73,7 +72,6 @@ class StoreLoginActivity : ComponentActivity() {
|
||||
private var store: Store? = null
|
||||
private var clientUrl: String? = null
|
||||
private var flow: Flow? = null
|
||||
private var pendingBrowserStep: String? = null
|
||||
private var webViewRef: WebView? = null
|
||||
private var popupWebView: WebView? = null
|
||||
private lateinit var contentHost: FrameLayout
|
||||
@@ -213,7 +211,6 @@ class StoreLoginActivity : ComponentActivity() {
|
||||
|
||||
private fun reloadLogin() {
|
||||
dismissPopup(); clearError()
|
||||
pendingBrowserStep = null
|
||||
captured.set(false)
|
||||
val fresh = generateState()
|
||||
oauthState = fresh
|
||||
@@ -335,13 +332,9 @@ class StoreLoginActivity : ComponentActivity() {
|
||||
|
||||
private fun readPage(view: WebView, f: Flow, left: Int) {
|
||||
view.evaluateJavascript(f.pageScript) { json ->
|
||||
if (flow !== f) return@evaluateJavascript
|
||||
val result = json ?: ""
|
||||
if (!f.pageReady(result) && left > 0) view.postDelayed({ readPage(view, f, left - 1) }, PAGE_RETRY_MS)
|
||||
else {
|
||||
val step = f.browserStep(result)
|
||||
if (step == null || !continueInBrowser(step)) Thread({ settle(f.finish(this, view, result)) }, "store-login").start()
|
||||
}
|
||||
else Thread({ settle(f.finish(this, view, result)) }, "store-login").start()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -357,21 +350,6 @@ class StoreLoginActivity : ComponentActivity() {
|
||||
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?) {
|
||||
runOnUiThread {
|
||||
if (problem == null) { StoresState.refresh(this); finish(); return@runOnUiThread }
|
||||
@@ -389,10 +367,6 @@ class StoreLoginActivity : ComponentActivity() {
|
||||
|
||||
override fun onStart() {
|
||||
super.onStart()
|
||||
pendingBrowserStep?.let { step ->
|
||||
pendingBrowserStep = null
|
||||
if (!continueInBrowser(step)) reloadLogin()
|
||||
}
|
||||
if (clientUrl != null && !isFinishing) com.droiddeck.launcher.session.SessionService.holdForSignIn(this, true)
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,9 @@ import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.runtime.BattleNet
|
||||
import com.droiddeck.launcher.runtime.GuestCommand
|
||||
import com.droiddeck.launcher.runtime.LinuxRuntime
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
import com.droiddeck.launcher.session.SecondaryLibrary
|
||||
import com.droiddeck.launcher.stores.CatalogItem
|
||||
import com.droiddeck.launcher.stores.InstalledStoreGame
|
||||
import com.droiddeck.launcher.stores.Store
|
||||
@@ -73,10 +75,22 @@ object BattleNetInstall {
|
||||
}
|
||||
|
||||
internal fun binds(context: Context): List<String> {
|
||||
val out = ArrayList<String>(StoreInstallRoot.externalBindSpecs(context))
|
||||
val root = LinuxRuntime.rootDir(context)
|
||||
GameStorage.effective(context)?.let { library ->
|
||||
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"
|
||||
}
|
||||
}
|
||||
return StoreInstallRoot.guestBinds(context)
|
||||
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 run(context: Context, args: List<String>, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int =
|
||||
|
||||
@@ -5,9 +5,8 @@ import android.webkit.WebView
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.stores.StoreLoginActivity
|
||||
import org.json.JSONObject
|
||||
import org.json.JSONTokener
|
||||
|
||||
internal class EpicLogin internal constructor(
|
||||
internal class EpicLogin private constructor(
|
||||
override val startUrl: String,
|
||||
override val userAgent: String,
|
||||
private val redirectPrefix: String,
|
||||
@@ -16,12 +15,6 @@ internal class EpicLogin internal constructor(
|
||||
|
||||
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? {
|
||||
val code = EpicNative.call("auth.codeFromPage", JSONObject().put("text", url))?.optString("code", "").orEmpty()
|
||||
if (code.isEmpty()) {
|
||||
@@ -45,15 +38,6 @@ internal class EpicLogin internal constructor(
|
||||
|
||||
companion object {
|
||||
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? {
|
||||
val config = EpicNative.call("auth.config") ?: return null
|
||||
|
||||
@@ -100,7 +100,6 @@ internal object GogContent {
|
||||
val manifest = metadata(build.link, token)
|
||||
onManifest(manifest)
|
||||
val files = JSONArray()
|
||||
val overlayPositions = HashMap<String, Int>()
|
||||
val depots = if (build.generation == 1) manifest.optJSONObject("product")?.optJSONArray("depots") ?: manifest.optJSONArray("depot") else manifest.optJSONArray("depots")
|
||||
check(depots != null) { "GOG build has no depot list" }
|
||||
val resolvedLanguage = StoreLanguage.pick(StoreLanguage.codesFromDepots(depots), old.language)
|
||||
@@ -133,15 +132,10 @@ internal object GogContent {
|
||||
val directory = type == "DepotDirectory" || entry.has("directory")
|
||||
val chunks = entry.optJSONArray("chunks") ?: JSONArray()
|
||||
val size = if (build.generation == 2) chunks.objects().sumOf { it.optLong("size") } else entry.optLong("size")
|
||||
val file = JSONObject().put("path", path).put("size", size).put("directory", directory)
|
||||
files.put(JSONObject().put("path", path).put("size", size).put("directory", directory)
|
||||
.put("md5", entry.optString("md5").ifBlank { entry.optString("hash") }.takeIf { it.matches(Regex("[a-fA-F0-9]{32}")) }.orEmpty())
|
||||
.put("sha256", entry.optString("sha256")).put("chunks", chunks).put("product", product)
|
||||
.put("offset", entry.optLong("offset")).put("remotePath", entry.optString("url").substringBefore('?'))
|
||||
val position = if (build.generation == 2) overlayPositions.putIfAbsent(path, files.length()) else null
|
||||
if (position == null) files.put(file) else {
|
||||
require(files.getJSONObject(position).getBoolean("directory") == directory)
|
||||
files.put(position, file)
|
||||
}
|
||||
.put("offset", entry.optLong("offset")).put("remotePath", entry.optString("url").substringBefore('?')))
|
||||
}
|
||||
}
|
||||
check(files.length() > 0) { "GOG build contains no matching files" }
|
||||
|
||||
@@ -4,6 +4,7 @@ import android.content.Context;
|
||||
import android.util.Log;
|
||||
|
||||
import com.droiddeck.launcher.frontend.AddedGames;
|
||||
import com.droiddeck.launcher.runtime.GuestCommand;
|
||||
import com.droiddeck.launcher.stores.StoreLanguage;
|
||||
import com.droiddeck.launcher.stores.StoreLog;
|
||||
import com.droiddeck.launcher.stores.download.StoreDownloadTier;
|
||||
@@ -270,10 +271,11 @@ public final class GogDownloadManager {
|
||||
long planned = 0;
|
||||
boolean sized = true;
|
||||
for (InstallerPart part : parts) { planned += part.size; if (part.size <= 0) sized = false; }
|
||||
long needed = installerBytesNeeded(knownPartBytes(parts), GogLibrary.INSTANCE.sizeOf(ctx, game.gameId));
|
||||
long usable = com.droiddeck.launcher.stores.StoreInstallRoot.availableBytes(installPath);
|
||||
if (com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(needed, usable)) {
|
||||
throw new InstallException("Not enough free space: need " + formatBytes(needed) + ", only " + formatBytes(usable) + " free");
|
||||
if (sized) {
|
||||
long usable = com.droiddeck.launcher.stores.StoreInstallRoot.availableBytes(installPath);
|
||||
if (com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(planned, usable)) {
|
||||
throw new InstallException("Not enough free space: need " + formatBytes(planned) + ", only " + formatBytes(usable) + " free");
|
||||
}
|
||||
}
|
||||
long total = 0;
|
||||
for (InstallerPart part : parts) {
|
||||
@@ -325,7 +327,10 @@ public final class GogDownloadManager {
|
||||
cb.onProgress("Extracting installer…", 95);
|
||||
int rc;
|
||||
try {
|
||||
rc = GogInnoextract.extract(ctx, guestSetup, guestDir, "gog-innoextract", cancelled,
|
||||
rc = GuestCommand.INSTANCE.run(ctx, Arrays.asList(
|
||||
"/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; });
|
||||
} catch (Exception e) {
|
||||
throw new InstallException("The installer could not be extracted: " + e.getClass().getSimpleName());
|
||||
@@ -334,16 +339,6 @@ public final class GogDownloadManager {
|
||||
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 {
|
||||
final String url;
|
||||
final String filename;
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
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,9 +3,11 @@ package com.droiddeck.launcher.stores.gog
|
||||
import android.content.Context
|
||||
import com.droiddeck.launcher.agent.AgentGuest
|
||||
import com.droiddeck.launcher.frontend.AddedGames
|
||||
import com.droiddeck.launcher.runtime.GuestCommand
|
||||
import com.droiddeck.launcher.session.SessionService
|
||||
import com.droiddeck.launcher.session.SessionState
|
||||
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.DownloadStage
|
||||
import org.json.JSONArray
|
||||
@@ -69,7 +71,8 @@ internal object GogOffline {
|
||||
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")
|
||||
handle.stage(DownloadStage.INSTALL, "Extracting the full offline installer")
|
||||
val rc = GogInnoextract.extract(context, source, target, "gog-refresh", stop, handle::log)
|
||||
val rc = GuestCommand.run(context, listOf("/usr/local/bin/droiddeck-innoextract", "--gog", "--silent", "-d", target, source),
|
||||
extraBinds = StoreInstallRoot.externalBindSpecs(context), cancelled = stop, logName = "gog-refresh", onLine = handle::log)
|
||||
if (stop.get()) return
|
||||
check(rc == 0) { "GOG installer extraction failed (exit $rc)" }
|
||||
applyRefresh(proposal, extracted, handle, stop)
|
||||
|
||||
@@ -1,239 +0,0 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import com.droiddeck.launcher.R
|
||||
import android.text.Editable
|
||||
import android.text.InputType
|
||||
import android.text.TextWatcher
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.widget.EditText
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.DisposableEffect
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.text.TextRange
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.ImeOptions
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.text.input.TextFieldValue
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
@Composable
|
||||
internal fun AdbTextField(
|
||||
value: String,
|
||||
onValueChange: (String) -> Unit,
|
||||
label: String,
|
||||
keyboardType: KeyboardType,
|
||||
imeAction: ImeAction,
|
||||
modifier: Modifier = Modifier,
|
||||
placeholder: String? = null,
|
||||
compact: Boolean = false,
|
||||
onFocusChange: (Boolean) -> Unit = {},
|
||||
clearFocus: Boolean = false,
|
||||
onNext: (() -> Unit)? = null,
|
||||
onDone: (() -> Unit)? = null,
|
||||
focusOnShow: Boolean = false,
|
||||
showLabel: Boolean = true,
|
||||
focusAtTap: Int? = null,
|
||||
onBack: (() -> Unit)? = null,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val onBackLatest = rememberUpdatedState(onBack)
|
||||
val focusAsked = remember { booleanArrayOf(false) }
|
||||
val focusTapAsked = remember { arrayOfNulls<Int>(1) }
|
||||
val palette = LocalPalette.current
|
||||
val onValueChangeLatest = rememberUpdatedState(onValueChange)
|
||||
val onNextLatest = rememberUpdatedState(onNext)
|
||||
val onDoneLatest = rememberUpdatedState(onDone)
|
||||
val onFocusChangeLatest = rememberUpdatedState(onFocusChange)
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
val shape = RoundedCornerShape(8.dp)
|
||||
val inputHeight = if (compact) 44.dp else 52.dp
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val bottomTyping = LocalBottomTyping.current
|
||||
val bottomTypingLatest = rememberUpdatedState(bottomTyping)
|
||||
val typingRequest = remember { arrayOfNulls<TypingRequest>(1) }
|
||||
|
||||
fun typeOnBottom(editText: EditText): Boolean {
|
||||
if (!bottomTypingLatest.value || !DualScreenPanel.attached) return false
|
||||
val text = editText.text.toString()
|
||||
lateinit var request: TypingRequest
|
||||
request = TypingRequest(
|
||||
TextFieldValue(text, TextRange(editText.selectionStart.coerceIn(0, text.length), editText.selectionEnd.coerceIn(0, text.length))),
|
||||
ImeOptions(singleLine = true, keyboardType = keyboardType, imeAction = imeAction),
|
||||
{ next ->
|
||||
if (editText.text.toString() != next.text) editText.setText(next.text)
|
||||
editText.setSelection(next.selection.start.coerceIn(0, next.text.length), next.selection.end.coerceIn(0, next.text.length))
|
||||
},
|
||||
{ action -> editText.onEditorAction(imeActionFlag(action)) },
|
||||
{ editText.post { if (typingRequest[0] === request) onBackLatest.value?.invoke() ?: editText.clearFocus() } },
|
||||
)
|
||||
typingRequest[0] = request
|
||||
DualScreenPanel.startTyping(request)
|
||||
return true
|
||||
}
|
||||
|
||||
DisposableEffect(Unit) {
|
||||
onDispose { typingRequest[0]?.let { DualScreenPanel.stopTyping(it) } }
|
||||
}
|
||||
|
||||
Column(modifier = modifier.fillMaxWidth()) {
|
||||
if (showLabel) Text(
|
||||
label,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = colors.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(inputHeight)
|
||||
.background(colors.surfaceVariant, shape)
|
||||
.glideBorder(focused, shape, palette.signal, palette.line2)
|
||||
.padding(horizontal = 10.dp),
|
||||
contentAlignment = Alignment.CenterStart,
|
||||
) {
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
factory = { viewContext ->
|
||||
EditText(viewContext).apply {
|
||||
isSingleLine = true
|
||||
setHorizontallyScrolling(true)
|
||||
background = null
|
||||
setPadding((2 * context.resources.displayMetrics.density).roundToInt(), 0, 0, 0)
|
||||
setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, if (compact) 13f else 14f)
|
||||
setTextColor(colors.onBackground.toArgb())
|
||||
setHintTextColor(colors.onSurfaceVariant.toArgb())
|
||||
contentDescription = label
|
||||
inputType = if (keyboardType == KeyboardType.Number) {
|
||||
InputType.TYPE_CLASS_NUMBER
|
||||
} else {
|
||||
InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
|
||||
}
|
||||
imeOptions = imeActionFlag(imeAction) or EditorInfo.IME_FLAG_NO_FULLSCREEN or EditorInfo.IME_FLAG_NO_EXTRACT_UI
|
||||
hint = placeholder
|
||||
setOnEditorActionListener { _, actionId, event ->
|
||||
val isEnter = event?.keyCode == android.view.KeyEvent.KEYCODE_ENTER
|
||||
when {
|
||||
imeAction == ImeAction.Next && (actionId == EditorInfo.IME_ACTION_NEXT || isEnter) -> {
|
||||
onNextLatest.value?.invoke()
|
||||
true
|
||||
}
|
||||
imeAction == ImeAction.Done && (actionId == EditorInfo.IME_ACTION_DONE || isEnter) -> {
|
||||
onDoneLatest.value?.invoke()
|
||||
true
|
||||
}
|
||||
// Search and Go are terminal: leaving them unhandled
|
||||
// keeps focus in the field, so the keyboard would stay
|
||||
// up over the results it was used to find.
|
||||
imeAction in setOf(ImeAction.Search, ImeAction.Go) &&
|
||||
(actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_GO || isEnter) -> {
|
||||
onDoneLatest.value?.invoke()
|
||||
post {
|
||||
clearFocus()
|
||||
(context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE)
|
||||
as? android.view.inputmethod.InputMethodManager)
|
||||
?.hideSoftInputFromWindow(windowToken, 0)
|
||||
}
|
||||
true
|
||||
}
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
showSoftInputOnFocus = !bottomTyping
|
||||
// B on a controller puts the keyboard away first; with no keyboard up it goes back as usual.
|
||||
var hidingKeyboard = false
|
||||
setOnKeyListener { view, keyCode, event ->
|
||||
if (keyCode != android.view.KeyEvent.KEYCODE_BUTTON_B) return@setOnKeyListener false
|
||||
if (event.action == android.view.KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
|
||||
hidingKeyboard = androidx.core.view.ViewCompat.getRootWindowInsets(view)
|
||||
?.isVisible(androidx.core.view.WindowInsetsCompat.Type.ime()) == true
|
||||
if (hidingKeyboard) (view.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
|
||||
?.hideSoftInputFromWindow(view.windowToken, 0)
|
||||
onBackLatest.value?.let { hidingKeyboard = true; it() }
|
||||
}
|
||||
hidingKeyboard
|
||||
}
|
||||
setOnClickListener { if (hasFocus() && !typeOnBottom(this) && bottomTypingLatest.value) showKeyboardHere(this) }
|
||||
setOnFocusChangeListener { _, hasFocus ->
|
||||
focused = hasFocus
|
||||
if (hasFocus) { if (!typeOnBottom(this) && bottomTypingLatest.value) showKeyboardHere(this) }
|
||||
else typingRequest[0]?.let { DualScreenPanel.stopTyping(it) }
|
||||
onFocusChangeLatest.value(hasFocus)
|
||||
}
|
||||
addTextChangedListener(object : TextWatcher {
|
||||
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
|
||||
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
|
||||
override fun afterTextChanged(s: Editable?) {
|
||||
onValueChangeLatest.value(s?.toString().orEmpty())
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
update = { editText ->
|
||||
editText.showSoftInputOnFocus = !bottomTyping
|
||||
// A new tap may ask again: a field still on screen while it closes can be opened once more.
|
||||
val fresh = if (focusAtTap != null) focusTapAsked[0] != focusAtTap else !focusAsked[0]
|
||||
if (focusOnShow && fresh) {
|
||||
if (focusAtTap != null) focusTapAsked[0] = focusAtTap else focusAsked[0] = true
|
||||
editText.post {
|
||||
if (focusAtTap != null && focusAtTap != ScreenTaps.count) return@post
|
||||
editText.requestFocus()
|
||||
if (!bottomTypingLatest.value) (editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
|
||||
?.showSoftInput(editText, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT)
|
||||
}
|
||||
}
|
||||
if (clearFocus && editText.hasFocus()) {
|
||||
editText.clearFocus()
|
||||
(editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
|
||||
?.hideSoftInputFromWindow(editText.windowToken, 0)
|
||||
}
|
||||
editText.setTextColor(colors.onBackground.toArgb())
|
||||
editText.setHintTextColor(colors.onSurfaceVariant.toArgb())
|
||||
editText.hint = placeholder
|
||||
editText.contentDescription = label
|
||||
if (editText.text.toString() != value) {
|
||||
val cursor = if (editText.hasFocus()) editText.selectionStart.coerceAtLeast(0) else value.length
|
||||
editText.setText(value)
|
||||
editText.setSelection(min(cursor, value.length))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private fun showKeyboardHere(editText: EditText) {
|
||||
(editText.context.getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as? android.view.inputmethod.InputMethodManager)
|
||||
?.showSoftInput(editText, android.view.inputmethod.InputMethodManager.SHOW_IMPLICIT)
|
||||
}
|
||||
|
||||
private fun imeActionFlag(action: ImeAction): Int = when (action) {
|
||||
ImeAction.Next -> EditorInfo.IME_ACTION_NEXT
|
||||
ImeAction.Done -> EditorInfo.IME_ACTION_DONE
|
||||
ImeAction.Go -> EditorInfo.IME_ACTION_GO
|
||||
ImeAction.Search -> EditorInfo.IME_ACTION_SEARCH
|
||||
else -> EditorInfo.IME_ACTION_UNSPECIFIED
|
||||
}
|
||||
@@ -117,7 +117,6 @@ import com.droiddeck.launcher.IconPack
|
||||
import android.content.pm.ShortcutInfo
|
||||
import android.graphics.Bitmap
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.Job
|
||||
import kotlinx.coroutines.flow.drop
|
||||
import kotlinx.coroutines.withContext
|
||||
import com.droiddeck.launcher.HomeWidgets
|
||||
@@ -389,49 +388,21 @@ internal fun AndroidAppsPage(s: FrontEndState, a: FrontEndActions, modifier: Mod
|
||||
}
|
||||
val front = LocalFrontFocus.current
|
||||
val steer = rememberCoroutineScope()
|
||||
// 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
|
||||
// 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
|
||||
// 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 ->
|
||||
val k = event.nativeKeyEvent
|
||||
val down = k.keyCode == KeyEvent.KEYCODE_DPAD_DOWN
|
||||
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 }
|
||||
if (k.keyCode != KeyEvent.KEYCODE_DPAD_DOWN || front == null) return@onPreviewKeyEvent false
|
||||
val from = entries.indexOfFirst { tileId(it) == front.last }
|
||||
val columns = (grid.layoutInfo.visibleItemsInfo.maxOfOrNull { it.column } ?: 0) + 1
|
||||
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 (from < 0 || from / columns == entries.lastIndex / columns) return@onPreviewKeyEvent false
|
||||
if (k.action == KeyEvent.ACTION_DOWN) {
|
||||
val to = if (down) minOf(from + columns, entries.lastIndex) else from - columns
|
||||
val id = tileId(entries[to])
|
||||
aim[0] = id
|
||||
val mine = ++moves[0]
|
||||
// A newer move replaces the one still on its way, so an older target cannot take focus after it lands.
|
||||
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
|
||||
}
|
||||
val id = tileId(entries[minOf(from + columns, entries.lastIndex)])
|
||||
val shown = (front.attached[id] ?: 0) > 0
|
||||
if (!shown || runCatching { front.items.getValue(id).requestFocus() }.isFailure) steer.launch {
|
||||
// The row below is not laid out yet: bring it in, then take it.
|
||||
if (!shown) grid.scrollBy((grid.layoutInfo.visibleItemsInfo.firstOrNull { it.index == from + leadItems }?.size?.height ?: 0).toFloat())
|
||||
focusSoon { front.items.getValue(id) }
|
||||
}
|
||||
}
|
||||
true
|
||||
@@ -587,26 +558,6 @@ 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
|
||||
private fun AlphabetScroller(entries: List<AppEntry>, grid: LazyGridState, leadItems: Int, modifier: Modifier) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
|
||||
@@ -526,11 +526,11 @@ fun ComponentsPage(
|
||||
val availableTitle: @Composable (String) -> String = { l ->
|
||||
when (l) {
|
||||
PROTON_TAB -> stringResource(R.string.comp_available_count, protons.rows.count(ProtonRow::available))
|
||||
else -> stringResource(R.string.comp_nightlies_count, availableRows(l, catalog, snapshot, view?.proton?.dir?.name).size)
|
||||
else -> stringResource(R.string.comp_nightlies_count, availableRows(l, catalog, snapshot).size)
|
||||
}
|
||||
}
|
||||
val followed: (String) -> Boolean = { l -> view?.proton?.let { ComponentUpdates.autoFollows(it, l) } == true }
|
||||
val moded: (String) -> Boolean = { followed(it) && it in compModes && it !in compAutoHeld && !ComponentsManager.runtimeManaged(it, gpu.systemPowerVr) }
|
||||
val followed = view?.proton?.let(ComponentUpdates::follows) == true
|
||||
val moded: (String) -> Boolean = { followed && it in compModes && it !in compAutoHeld && !ComponentsManager.runtimeManaged(it, gpu.systemPowerVr) }
|
||||
val automatic: (String) -> Boolean = { moded(it) && compModes[it] == ComponentUpdates.AUTO }
|
||||
val installedRows: @Composable ColumnScope.(String, Boolean) -> Unit = { l, right ->
|
||||
when (l) {
|
||||
@@ -614,7 +614,7 @@ fun ComponentsPage(
|
||||
}
|
||||
}
|
||||
else -> {
|
||||
val available = availableRows(l, catalog, snapshot, view?.proton?.dir?.name)
|
||||
val available = availableRows(l, catalog, snapshot)
|
||||
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) {
|
||||
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) },
|
||||
"ORIGINAL", activeIsOriginal && isCurrent, !isCurrent, null, o.protonVersion,
|
||||
)
|
||||
} + ComponentsManager.forTool(l, view.proton.dir.name, (snapshot?.packages ?: emptyList()).filter { it.comp == l }, st.activeFile) { it.file }.map { s ->
|
||||
} + (snapshot?.packages ?: emptyList()).filter { it.comp == l }.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)
|
||||
}
|
||||
}
|
||||
|
||||
private fun availableFor(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?, toolDir: String?): List<CatalogItem> {
|
||||
private fun availableFor(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?): List<CatalogItem> {
|
||||
val stored = (snapshot?.packages ?: emptyList()).map { it.file }.toSet()
|
||||
return ComponentsManager.forTool(l, toolDir, catalog.filter { it.comp == l && ComponentsManager.safeName(it.file) !in stored }) { it.file }
|
||||
return catalog.filter { it.comp == l && ComponentsManager.safeName(it.file) !in stored }
|
||||
}
|
||||
|
||||
private fun availableRows(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?, toolDir: String?): List<Pair<CatalogItem, CatalogItem?>> {
|
||||
val available = availableFor(l, catalog, snapshot, toolDir)
|
||||
private fun availableRows(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?): List<Pair<CatalogItem, CatalogItem?>> {
|
||||
val available = availableFor(l, catalog, snapshot)
|
||||
val pairs = ComponentsManager.nightlyPairs(available)
|
||||
val paired = pairs.values.toSet()
|
||||
return available.filter { it !in paired }.map { it to pairs[it] }
|
||||
@@ -1201,7 +1201,7 @@ private fun GameComponentOverrides(
|
||||
}
|
||||
GamePackageRow(
|
||||
comp = "fex",
|
||||
packages = ComponentsManager.forTool("fex", protonChoice?.dir ?: generalProton?.dir?.name, packages, componentChoices["fex"]) { it.file },
|
||||
packages = packages,
|
||||
selectedFile = componentChoices["fex"],
|
||||
open = componentMenu == "fex",
|
||||
busy = busy,
|
||||
|
||||
@@ -21,21 +21,11 @@ import com.droiddeck.launcher.session.StripMetric
|
||||
@Composable
|
||||
internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
|
||||
val cfg = a.hudConfig
|
||||
val context = LocalContext.current
|
||||
var onlyDuringGame by remember { mutableStateOf(SessionPrefs.hudOnlyDuringGame(context)) }
|
||||
fun on(key: String) = cfg[key] == "1"
|
||||
fun int(key: String, fallback: Int) = cfg[key]?.toIntOrNull() ?: fallback
|
||||
|
||||
SettingsGroup(stringResource(R.string.drawer_hud)) {
|
||||
ToggleRow(host, "hud", stringResource(R.string.drawer_hud), null, a.hudOn, chipModifier = track("hud"), onChange = a.onHud)
|
||||
if (a.hudOn) ToggleRow(
|
||||
host, "hud-only-during-game", stringResource(R.string.hud_only_during_game),
|
||||
stringResource(R.string.hud_only_during_game_hint), onlyDuringGame,
|
||||
chipModifier = track("hud-only-during-game")
|
||||
) { on ->
|
||||
onlyDuringGame = on
|
||||
a.onHudOnlyDuringGame(on)
|
||||
}
|
||||
if (!a.hudOn) return@SettingsGroup
|
||||
val size = DroidDeckHudSize.from(cfg["hudSize"])
|
||||
ChoiceRow(host, "hud-size", stringResource(R.string.hud_size), stringResource(R.string.hud_size_hint),
|
||||
|
||||
@@ -148,61 +148,7 @@ object DualScreenPanel {
|
||||
}.onFailure { launching = false; displayId = -1 }
|
||||
}
|
||||
|
||||
/**
|
||||
* The panel on a presentation window sits above every activity on its screen, so an app launched there stays hidden behind it.
|
||||
* Swapping the panel for a task of its own puts the app above it, and closing the app shows the panel again.
|
||||
* Launches requested while the swap is under way wait for it and run in the order they were asked for.
|
||||
*/
|
||||
fun makeRoomForApp(context: Context, display: Int, launch: () -> Unit) {
|
||||
pendingLaunches?.let { it.add(launch); return }
|
||||
val shown = presentation
|
||||
if (shown == null || displayId != display) { launch(); return }
|
||||
pendingLaunches = mutableListOf(launch)
|
||||
val generation = ++handoffGeneration
|
||||
handoffWaited = 0
|
||||
presentation = null
|
||||
shown.dismiss()
|
||||
launching = true
|
||||
val intent = Intent(context, DualScreenActivity::class.java)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK or Intent.FLAG_ACTIVITY_NO_ANIMATION)
|
||||
.putExtra(EXTRA_HANDOFF, generation)
|
||||
val started = runCatching {
|
||||
context.startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(display).toBundle())
|
||||
}.isSuccess
|
||||
if (!started) { launching = false; displayId = -1; releaseLaunches(); return }
|
||||
handoffPoll.run()
|
||||
}
|
||||
|
||||
private var pendingLaunches: MutableList<() -> Unit>? = null
|
||||
private var handoffWaited = 0
|
||||
private var handoffGeneration = 0
|
||||
internal const val EXTRA_HANDOFF = "handoff"
|
||||
private val handoffHandler = android.os.Handler(android.os.Looper.getMainLooper())
|
||||
private val handoffPoll = object : Runnable {
|
||||
override fun run() {
|
||||
if (pendingLaunches == null) return
|
||||
if (activity != null || handoffWaited >= APP_WAIT_MS) releaseLaunches()
|
||||
else { handoffWaited += APP_POLL_MS; handoffHandler.postDelayed(this, APP_POLL_MS.toLong()) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun releaseLaunches() {
|
||||
val waiting = pendingLaunches ?: return
|
||||
pendingLaunches = null
|
||||
handoffHandler.removeCallbacks(handoffPoll)
|
||||
waiting.forEach { it() }
|
||||
}
|
||||
|
||||
private fun dropLaunches() {
|
||||
pendingLaunches = null
|
||||
handoffHandler.removeCallbacks(handoffPoll)
|
||||
}
|
||||
|
||||
private const val APP_POLL_MS = 100
|
||||
private const val APP_WAIT_MS = 2000
|
||||
|
||||
fun hide() {
|
||||
dropLaunches()
|
||||
stopTyping()
|
||||
launching = false
|
||||
displayId = -1
|
||||
@@ -223,9 +169,6 @@ object DualScreenPanel {
|
||||
if (activity !== host) activity?.finishAndRemoveTask()
|
||||
activity = host
|
||||
launching = false
|
||||
val waiting = pendingLaunches
|
||||
val generation = host.intent?.getIntExtra(EXTRA_HANDOFF, -1) ?: -1
|
||||
handoffHandler.post { if (pendingLaunches === waiting && generation == handoffGeneration) releaseLaunches() }
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -60,8 +60,7 @@ import androidx.compose.ui.unit.Dp
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.files.StorageRoot
|
||||
import com.droiddeck.launcher.files.StorageRoots
|
||||
import com.droiddeck.launcher.session.GameStorage
|
||||
import com.droiddeck.launcher.stores.formatBytes
|
||||
import java.io.File
|
||||
|
||||
@@ -75,16 +74,10 @@ internal class PickVolume(val root: File, val label: String, val removable: Bool
|
||||
}
|
||||
|
||||
internal fun pickVolumes(context: Context): List<PickVolume> =
|
||||
pickVolumes(Environment.getExternalStorageDirectory(), context.getString(R.string.games_internal), StorageRoots.list(context))
|
||||
|
||||
internal fun pickVolumes(internal: File, internalLabel: String, roots: List<StorageRoot>): List<PickVolume> {
|
||||
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 }
|
||||
}
|
||||
listOf(PickVolume(Environment.getExternalStorageDirectory(), context.getString(R.string.games_internal), removable = false)) +
|
||||
GameStorage.options(context).mapNotNull { o ->
|
||||
File(o.path.substringBefore("/Android/")).takeIf { it.isDirectory }?.let { PickVolume(it, o.name, removable = true) }
|
||||
}.distinctBy { it.root.absolutePath }
|
||||
|
||||
internal class PickFolder(val dir: File, val readable: Boolean)
|
||||
|
||||
|
||||
@@ -271,6 +271,10 @@ private fun Content(
|
||||
UpdatesPage(s, a, modifier.padding(horizontal = padH).padding(top = padV))
|
||||
return
|
||||
}
|
||||
if (selected == "trinkets") {
|
||||
TrinketsPage(modifier.padding(horizontal = padH).padding(top = padV))
|
||||
return
|
||||
}
|
||||
if (selected == "steam") {
|
||||
SteamHome(s, a, modifier)
|
||||
return
|
||||
|
||||
@@ -59,6 +59,7 @@ import androidx.compose.material.icons.filled.SdStorage
|
||||
import androidx.compose.material.icons.filled.Movie
|
||||
import androidx.compose.material.icons.filled.Sync
|
||||
import androidx.compose.material.icons.filled.MoreHoriz
|
||||
import androidx.compose.material.icons.filled.Toys
|
||||
import androidx.compose.material.icons.automirrored.outlined.ArrowBack
|
||||
import androidx.compose.ui.graphics.vector.ImageVector
|
||||
import androidx.compose.material3.Icon
|
||||
@@ -205,6 +206,7 @@ internal fun railLabelIcon(key: String): Pair<Int, ImageVector> = when (key) {
|
||||
"agent" -> R.string.rail_agent to Icons.Filled.Terminal
|
||||
"android-apps" -> R.string.rail_apps to Icons.Filled.Apps
|
||||
"setup" -> R.string.rail_setup to Icons.Filled.Settings
|
||||
"trinkets" -> R.string.rail_trinkets to Icons.Filled.Toys
|
||||
"storage" -> R.string.rail_storage to Icons.Filled.SdStorage
|
||||
"sync" -> R.string.rail_sync to Icons.Filled.Sync
|
||||
"decky" -> R.string.rail_decky to DeckyIcon
|
||||
|
||||
@@ -58,7 +58,6 @@ import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.snapshotFlow
|
||||
import androidx.compose.runtime.withFrameNanos
|
||||
import kotlinx.coroutines.launch
|
||||
import kotlinx.coroutines.flow.first
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
@@ -103,7 +102,6 @@ class FrontEndState(
|
||||
val desktopPresent: Boolean = desktopInstalled,
|
||||
val offlineAccount: String?,
|
||||
val offline: Boolean,
|
||||
val offlineAuto: Boolean = true,
|
||||
val frameGenLabel: String,
|
||||
val romsDir: String?,
|
||||
val logsEnabled: Boolean,
|
||||
@@ -145,7 +143,6 @@ class FrontEndState(
|
||||
val integrationFocus: com.droiddeck.launcher.core.SteamIntegration.Feature? = null,
|
||||
val androidApps: List<HomeApp.LaunchableApp> = emptyList(),
|
||||
val secondScreenDisplays: List<SecondScreenDisplay> = emptyList(),
|
||||
val ownScreen: SecondScreenDisplay? = null,
|
||||
val dualScreen: Boolean = false,
|
||||
val dualScreenDevice: Boolean = false,
|
||||
val dualScreenMode: String = com.droiddeck.launcher.input.DualScreen.MODE_AUTO,
|
||||
@@ -274,7 +271,6 @@ class FrontEndActions(
|
||||
val onClearLogs: () -> Unit = {},
|
||||
val onResetSettings: () -> Unit = {},
|
||||
val onOffline: () -> Unit,
|
||||
val onOfflineAuto: () -> Unit = {},
|
||||
val onPageBack: () -> Unit = {},
|
||||
val onTheme: (String) -> Unit = {},
|
||||
val onLanguage: (String) -> Unit = {},
|
||||
@@ -317,14 +313,16 @@ class FrontEndActions(
|
||||
val onBackActionsInverted: (Boolean) -> Unit = {},
|
||||
val onRefreshPhantomStatus: () -> Unit = {},
|
||||
val onOpenDeveloperOptions: (Int?) -> Unit = {},
|
||||
val onWirelessAdbPair: (String, Int, String, (String?) -> Unit) -> Unit,
|
||||
val onFindWirelessAdbPort: (String, (Int?) -> Unit) -> Unit = { _, done -> done(null) },
|
||||
val onWirelessAdbApply: (String, Int, Boolean, (String?) -> Unit) -> Unit,
|
||||
val onSetPhantomProcessLimit: (Boolean, (String?) -> Unit) -> Unit,
|
||||
val onCopyPhantomCommand: (Boolean) -> Unit = {},
|
||||
val onDismissPhantomGate: () -> Unit = {},
|
||||
val onStartWirelessAdbPairing: (Boolean) -> Unit = {},
|
||||
val onStartWirelessAdbPairing: () -> Unit = {},
|
||||
val onStartPairingGuide: (Int?, Boolean) -> Boolean = { _, _ -> false },
|
||||
val onShowPhantomGate: () -> Unit = {},
|
||||
val onQueuePlaySteam: () -> Unit = {},
|
||||
val onEnsureNotifications: ((Boolean) -> Unit) -> Unit = { it(true) },
|
||||
val onOpenNotificationSettings: () -> Unit = {},
|
||||
val controller: ControllerActions? = null,
|
||||
val updates: UpdatesActions = UpdatesActions(),
|
||||
)
|
||||
@@ -510,16 +508,17 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
LaunchedEffect(com.droiddeck.launcher.stores.StoresState.openGameRequest) {
|
||||
if (com.droiddeck.launcher.stores.StoresState.openGameRequest != null) selected = "stores"
|
||||
}
|
||||
var showWirelessAdbFix by rememberSaveable { mutableStateOf(false) }
|
||||
var showDeveloperDisplayChoice by rememberSaveable { mutableStateOf(false) }
|
||||
var developerChoiceGuided by rememberSaveable { mutableStateOf(false) }
|
||||
var developerChoiceToggle by rememberSaveable { mutableStateOf(false) }
|
||||
var guidedLimitEnabled by rememberSaveable { mutableStateOf(false) }
|
||||
var wirelessAdbDesiredEnabled by rememberSaveable { mutableStateOf(false) }
|
||||
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val ctx = LocalContext.current
|
||||
val phantomGateVisible = s.showPhantomGate && PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
|
||||
val processSettingsPageVisible = phantomGateVisible || showDeveloperDisplayChoice
|
||||
val processSettingsPageVisible = phantomGateVisible || showWirelessAdbFix || showDeveloperDisplayChoice
|
||||
val requestDeveloperOptions = {
|
||||
developerChoiceGuided = false
|
||||
developerChoiceToggle = false
|
||||
@@ -527,7 +526,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
else showDeveloperDisplayChoice = true
|
||||
}
|
||||
val openDeveloperOptionsOn: (Int?) -> Unit = { displayId ->
|
||||
if (developerChoiceGuided) a.onStartWirelessAdbPairing(guidedLimitEnabled)
|
||||
if (developerChoiceGuided) a.onStartWirelessAdbPairing()
|
||||
val guided = developerChoiceGuided || developerChoiceToggle
|
||||
if (!guided || !a.onStartPairingGuide(displayId, developerChoiceToggle)) a.onOpenDeveloperOptions(displayId)
|
||||
developerChoiceGuided = false
|
||||
@@ -543,35 +542,31 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
else showDeveloperDisplayChoice = true
|
||||
}
|
||||
}
|
||||
val startGuidedPairing: (Boolean) -> Unit = { enabled ->
|
||||
a.onEnsureNotifications { granted ->
|
||||
if (granted) {
|
||||
guidedLimitEnabled = enabled
|
||||
developerChoiceGuided = true
|
||||
if (s.secondScreenDisplays.isEmpty()) openDeveloperOptionsOn(null)
|
||||
else showDeveloperDisplayChoice = true
|
||||
}
|
||||
val startGuidedPairing = {
|
||||
if (!com.droiddeck.launcher.core.WirelessAdbPairingService.notificationsEnabled(ctx)) {
|
||||
wirelessAdbDesiredEnabled = false
|
||||
showWirelessAdbFix = true
|
||||
} else {
|
||||
developerChoiceGuided = true
|
||||
if (s.secondScreenDisplays.isEmpty()) openDeveloperOptionsOn(null)
|
||||
else showDeveloperDisplayChoice = true
|
||||
}
|
||||
}
|
||||
val childProcessRequest = androidx.compose.runtime.rememberUpdatedState {
|
||||
if (PhantomProcessLimit.hasDeveloperToggle()) requestChildProcessToggle() else a.onShowPhantomGate()
|
||||
}
|
||||
DisposableEffect(Unit) {
|
||||
val handler: () -> Unit = { childProcessRequest.value() }
|
||||
ChildProcessSetup.request = handler
|
||||
onDispose { if (ChildProcessSetup.request === handler) ChildProcessSetup.request = null }
|
||||
}
|
||||
var applyingSavedPairing by remember { mutableStateOf(false) }
|
||||
val fixPhantomLimit = {
|
||||
if (!s.adbPaired || !com.droiddeck.launcher.core.GlobalSettings.wirelessDebuggingOn(ctx)) startGuidedPairing(false)
|
||||
if (!s.adbPaired || !com.droiddeck.launcher.core.GlobalSettings.wirelessDebuggingOn(ctx)) startGuidedPairing()
|
||||
else if (!applyingSavedPairing) {
|
||||
applyingSavedPairing = true
|
||||
a.onSetPhantomProcessLimit(false) { error ->
|
||||
applyingSavedPairing = false
|
||||
if (error != null) startGuidedPairing(false)
|
||||
if (error != null) startGuidedPairing()
|
||||
}
|
||||
}
|
||||
}
|
||||
val requestWirelessAdbFix: (Boolean) -> Unit = { enabled ->
|
||||
wirelessAdbDesiredEnabled = enabled
|
||||
showWirelessAdbFix = true
|
||||
}
|
||||
LaunchedEffect(s.showPhantomGate, s.phantomProcessStatus) {
|
||||
if (phantomGateVisible) {
|
||||
while (true) {
|
||||
@@ -767,31 +762,12 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
focusManager.clearFocus(force = true)
|
||||
onRailSelect(key)
|
||||
}, 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 ->
|
||||
if (!processSettingsPageVisible) {
|
||||
val keys = navigationKeys(s)
|
||||
keys.getOrNull(keys.indexOf(railSelectionNow.value) + step)?.let { key ->
|
||||
PageSwipe.direction = step
|
||||
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() }
|
||||
}
|
||||
}
|
||||
onRailSelect(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -826,12 +802,12 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
},
|
||||
{ selected = it },
|
||||
onAndroidAppClick = { app ->
|
||||
if (s.secondScreenDisplays.isEmpty() && s.ownScreen == null) a.onAndroidApp(app, null)
|
||||
if (s.secondScreenDisplays.isEmpty()) a.onAndroidApp(app, null)
|
||||
else appToChooseDisplay = app
|
||||
},
|
||||
onOpenDeveloperOptions = requestChildProcessToggle,
|
||||
onPairWirelessDebugging = { startGuidedPairing(false) },
|
||||
onRequestWirelessAdb = startGuidedPairing,
|
||||
onRequestWirelessAdb = requestWirelessAdbFix,
|
||||
onPairWirelessDebugging = startGuidedPairing,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -847,7 +823,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
SessionDrawerPreview(s.secondScreenDisplays)
|
||||
|
||||
appToChooseDisplay?.let { app ->
|
||||
val secondaryDisplay = s.secondScreenDisplays.firstOrNull() ?: s.ownScreen
|
||||
val secondaryDisplay = s.secondScreenDisplays.firstOrNull()
|
||||
ChooseAppDisplayDialog(
|
||||
app = app,
|
||||
secondaryDisplay = secondaryDisplay,
|
||||
@@ -862,7 +838,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
onDismiss = { appToChooseDisplay = null },
|
||||
)
|
||||
}
|
||||
if (phantomGateVisible) {
|
||||
if (phantomGateVisible && !showWirelessAdbFix) {
|
||||
Box(Modifier.fillMaxSize().background(colors.background)) {
|
||||
PhantomProcessGatePage(
|
||||
status = s.phantomProcessStatus,
|
||||
@@ -870,7 +846,21 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
onOpenDeveloperOptions = requestChildProcessToggle,
|
||||
applyingSavedPairing = applyingSavedPairing,
|
||||
onFixWithWirelessDebugging = fixPhantomLimit,
|
||||
onEnterAddressManually = { requestWirelessAdbFix(false) },
|
||||
onCopyCommand = { a.onCopyPhantomCommand(false) },
|
||||
onOpenNotificationSettings = a.onOpenNotificationSettings,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (showWirelessAdbFix) {
|
||||
Box(Modifier.fillMaxSize().background(colors.background)) {
|
||||
WirelessAdbFixPage(
|
||||
onBack = { showWirelessAdbFix = false },
|
||||
desiredEnabled = wirelessAdbDesiredEnabled,
|
||||
onOpenDeveloperOptions = requestDeveloperOptions,
|
||||
onPair = a.onWirelessAdbPair,
|
||||
onFindConnectPort = a.onFindWirelessAdbPort,
|
||||
onApply = a.onWirelessAdbApply,
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -916,13 +906,6 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
}
|
||||
}
|
||||
|
||||
internal object ChildProcessSetup {
|
||||
@Volatile var request: (() -> Unit)? = null
|
||||
}
|
||||
|
||||
internal object MainTabSteps {
|
||||
@Volatile var handler: ((Int) -> Unit)? = null
|
||||
@Volatile var otherKeys = 0
|
||||
}
|
||||
|
||||
private const val RAIL_HOLD_FRAMES = 60
|
||||
@@ -542,7 +542,7 @@ internal fun SetupPanel(
|
||||
)
|
||||
ChoiceRow(
|
||||
host, "dual-screen-sessions", stringResource(R.string.setup_dual_screen_sessions), stringResource(R.string.setup_dual_screen_sessions_hint),
|
||||
dualModes.take(2) + (com.droiddeck.launcher.input.DualScreen.MODE_SWAPPED to stringResource(R.string.setup_dual_screen_swapped)) + dualModes.drop(2), s.dualScreenSessions, onPick = a.onDualScreenSessions,
|
||||
dualModes, s.dualScreenSessions, onPick = a.onDualScreenSessions,
|
||||
)
|
||||
if (s.dualScreenSessions != com.droiddeck.launcher.input.DualScreen.MODE_OFF) {
|
||||
ToggleRow(host, "dual-screen-controls", stringResource(R.string.setup_dual_screen_controls),
|
||||
@@ -1098,6 +1098,8 @@ internal fun GameSettingsMenus(host: MenuHost, game: com.droiddeck.launcher.fron
|
||||
|
||||
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
|
||||
private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.droiddeck.launcher.stores.Store) {
|
||||
val appContext = androidx.compose.ui.platform.LocalContext.current.applicationContext
|
||||
@@ -1147,7 +1149,7 @@ private fun StoreLaunchCard(host: MenuHost, folder: java.io.File, store: com.dro
|
||||
MenuItem(stringResource(R.string.epic_resolve), checked = false) {
|
||||
host.open = null
|
||||
runCatching {
|
||||
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))
|
||||
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))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1280,8 +1282,7 @@ internal fun OnboardingCard(limitBlocks: Boolean = false, onSetUpLimit: () -> Un
|
||||
val failed by com.droiddeck.launcher.session.Onboarding.failed.collectAsState()
|
||||
val facts by com.droiddeck.launcher.session.Onboarding.facts.collectAsState()
|
||||
val rows = com.droiddeck.launcher.session.Onboarding.rows(active, failed, facts)
|
||||
val firstRun by com.droiddeck.launcher.session.Onboarding.firstRun.collectAsState()
|
||||
val settling = firstRun && com.droiddeck.launcher.session.Onboarding.pending(rows)
|
||||
val settling = com.droiddeck.launcher.session.Onboarding.pending(rows)
|
||||
if (!settling) return
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
|
||||
@@ -205,12 +205,10 @@ internal fun PrimaryButton(
|
||||
large: Boolean = false,
|
||||
icon: ImageVector? = null,
|
||||
fill: Boolean = false,
|
||||
progress: Float? = null,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
val shownProgress by animateFloatAsState(progress?.coerceIn(0f, 1f) ?: 0f, Motion.tw(300), label = "btnProgress")
|
||||
val pillMode = LocalPillButtons.current
|
||||
val btnShape = if (pillMode) CircleShape else Shape12
|
||||
val outlined = LocalGradientOutline.current && enabled
|
||||
@@ -236,11 +234,6 @@ internal fun PrimaryButton(
|
||||
.graphicsLayer { alpha = if (LaunchOrigin.flooding === placed) 0f else 1f; scaleX = scale; scaleY = scale; shadowElevation = if (enabled) lift.dp.toPx() else 0f; shape = btnShape; clip = false; ambientShadowColor = pal.signal; spotShadowColor = pal.signal }
|
||||
.clip(btnShape)
|
||||
.background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant)))
|
||||
.then(if (progress != null) Modifier.drawBehind {
|
||||
val done = size.width * shownProgress
|
||||
if (enabled) drawRect(Color.Black.copy(alpha = 0.32f), topLeft = androidx.compose.ui.geometry.Offset(done, 0f), size = androidx.compose.ui.geometry.Size(size.width - done, size.height))
|
||||
else drawRect(pal.signal.copy(alpha = 0.4f), size = androidx.compose.ui.geometry.Size(done, size.height))
|
||||
} else Modifier)
|
||||
.then(if (enabled) Modifier else Modifier.border(1.dp, pal.line2, btnShape))
|
||||
.then(if (outlined) Modifier.border(2.dp, Brush.linearGradient(listOf(pal.primary2, colors.primary)), btnShape) else Modifier)
|
||||
.glideBorder(hot, btnShape, pal.signal, hotFillAlpha = 0f)
|
||||
|
||||
@@ -38,10 +38,8 @@ import com.droiddeck.launcher.input.InputButtonShape
|
||||
import com.droiddeck.launcher.input.InputButtonImages
|
||||
import com.droiddeck.launcher.input.PadBridge
|
||||
import com.droiddeck.launcher.input.PadKit
|
||||
import com.droiddeck.launcher.input.ThrottledRedraw
|
||||
import com.droiddeck.launcher.input.pcKeyLabel
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.atan2
|
||||
import kotlin.math.hypot
|
||||
import kotlin.math.min
|
||||
@@ -583,10 +581,6 @@ class InputSurfaceView(
|
||||
private var originY = 0f
|
||||
private var knobX = 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 knob = Paint(Paint.ANTI_ALIAS_FLAG)
|
||||
|
||||
@@ -669,7 +663,6 @@ class InputSurfaceView(
|
||||
MotionEvent.ACTION_MOVE -> follow(event.getX(0), event.getY(0), r)
|
||||
MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
|
||||
touching = false
|
||||
atRim = false
|
||||
val cancelled = event.actionMasked == MotionEvent.ACTION_CANCEL || event.flags and MotionEvent.FLAG_CANCELED != 0
|
||||
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
|
||||
@@ -685,27 +678,15 @@ class InputSurfaceView(
|
||||
var dx = x - originX
|
||||
var dy = y - originY
|
||||
val length = hypot(dx, dy)
|
||||
val rim = length > 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)
|
||||
if (length > r) { dx *= r / length; dy *= r / length }
|
||||
if (force || dx != knobX || dy != knobY) move(dx, dy, r)
|
||||
}
|
||||
|
||||
private fun move(dx: Float, dy: Float, r: Float, throttled: Boolean = false, rim: Boolean = false) {
|
||||
private fun move(dx: Float, dy: Float, r: Float) {
|
||||
knobX = dx
|
||||
knobY = dy
|
||||
source?.update(dx / r, dy / r)
|
||||
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()
|
||||
}
|
||||
invalidate()
|
||||
}
|
||||
|
||||
private fun setClick(down: Boolean) {
|
||||
@@ -718,7 +699,6 @@ class InputSurfaceView(
|
||||
override fun onDetachedFromWindow() {
|
||||
setClick(false)
|
||||
if (knobX != 0f || knobY != 0f) move(0f, 0f, 1f)
|
||||
redraw.cancel()
|
||||
super.onDetachedFromWindow()
|
||||
}
|
||||
}
|
||||
@@ -786,8 +766,6 @@ class InputSurfaceView(
|
||||
companion object {
|
||||
private const val CLICK_MS = 300L
|
||||
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 PANEL_REACH = 0.30f
|
||||
private const val HIT_SLACK = 0.25f
|
||||
|
||||
@@ -78,7 +78,6 @@ class ModeSettings(
|
||||
val mic: Boolean?,
|
||||
val gameStorage: String? = null,
|
||||
val storageOptions: List<com.droiddeck.launcher.session.GameStorage.Option> = emptyList(),
|
||||
val storageFat32: Boolean = false,
|
||||
val steamLibraries: List<com.droiddeck.launcher.session.SteamLibraries.Entry> = emptyList(),
|
||||
val foundSteamLibraries: List<com.droiddeck.launcher.session.SteamLibraries.Found> = emptyList(),
|
||||
val allFilesAccessMissing: Boolean = false,
|
||||
@@ -93,7 +92,6 @@ class ModeSettings(
|
||||
val steamClientArch: String? = null,
|
||||
val returnAfterGame: Boolean? = null,
|
||||
val shaderPrecache: Boolean? = null,
|
||||
val valveProtonOnDemand: Boolean? = null,
|
||||
val steamRepairQueued: Boolean = false,
|
||||
val mangoapp: Boolean = true,
|
||||
val steamController: String? = null,
|
||||
@@ -159,7 +157,6 @@ class ModeSettingsActions(
|
||||
val onMangoapp: (Boolean) -> Unit = {},
|
||||
val onReturnAfterGame: (Boolean) -> Unit = {},
|
||||
val onShaderPrecache: (Boolean) -> Unit = {},
|
||||
val onValveProtonOnDemand: (Boolean) -> Unit = {},
|
||||
val onSteamController: (String) -> Unit = {},
|
||||
val onUnfoldedControls: (Boolean) -> Unit = {},
|
||||
val onUnfoldedControlsWithController: (Boolean) -> Unit = {},
|
||||
@@ -458,7 +455,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
ValueChip(options.firstOrNull { it.path == s.gameStorage }?.chip ?: "-", open) { host.open = if (open) null else "storage" }
|
||||
AnchoredMenu(
|
||||
open, onDismiss = { if (host.open == "storage") host.open = null }, title = stringResource(R.string.mode_second_library),
|
||||
note = stringResource(R.string.mode_storage_note).let { if (s.storageFat32) stringResource(R.string.main_storage_fat32) + "\n" + it else it },
|
||||
note = stringResource(R.string.mode_storage_note),
|
||||
) { firstItemFocus ->
|
||||
options.forEachIndexed { index, choice ->
|
||||
MenuItem(choice.label, checked = choice.path == s.gameStorage, focusRequester = if (index == 0) firstItemFocus else null) {
|
||||
@@ -536,10 +533,6 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
|
||||
stringResource(R.string.mode_shader_precache_hint),
|
||||
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(
|
||||
stringResource(R.string.mode_steam_repair),
|
||||
stringResource(if (s.steamRepairQueued) R.string.mode_steam_repair_queued else R.string.mode_steam_repair_hint),
|
||||
|
||||
@@ -26,10 +26,10 @@ internal object DeveloperTools {
|
||||
|
||||
internal object NavTabs {
|
||||
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 DEFAULT_SHELVED = setOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies", "agent")
|
||||
val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "trinkets", "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_HIDDEN = setOf("android-apps", "agent")
|
||||
private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "agent")
|
||||
private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "android-apps", "agent")
|
||||
private val OLD_ORDER = listOf("steam", "games", "soundtracks", "stores", "downloads", "desktop", "agent", "components", "android-apps", "storage", "sync", "setup", "updates")
|
||||
private val OLD_SHELVED = setOf("soundtracks", "agent", "storage", "sync")
|
||||
private const val LAYOUT_VERSION = 2
|
||||
@@ -95,15 +95,6 @@ internal object NavTabs {
|
||||
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 place(s: FrontEndState, key: String): TabPlace = when {
|
||||
|
||||
@@ -50,7 +50,9 @@ fun PhantomProcessGatePage(
|
||||
onDismiss: () -> Unit,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onFixWithWirelessDebugging: () -> Unit,
|
||||
onEnterAddressManually: () -> Unit,
|
||||
onCopyCommand: () -> Unit,
|
||||
onOpenNotificationSettings: () -> Unit,
|
||||
) {
|
||||
BackHandler(onBack = onDismiss)
|
||||
val context = LocalContext.current
|
||||
@@ -80,11 +82,11 @@ fun PhantomProcessGatePage(
|
||||
val fix: @Composable ColumnScope.() -> Unit = {
|
||||
if (sideQuest) SideQuestGroup(compact, onCopyCommand)
|
||||
else FixGroup(hasToggle, stage, environment, compact, applyingSavedPairing, onOpenDeveloperOptions, onFixWithWirelessDebugging,
|
||||
onCancel = { WirelessAdbPairingService.cancel(context) })
|
||||
onOpenNotificationSettings, onCancel = { WirelessAdbPairingService.cancel(context) })
|
||||
}
|
||||
val side: @Composable ColumnScope.() -> Unit = {
|
||||
StatusGroup(status, compact)
|
||||
if (!sideQuest) OtherWays(hasToggle, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging, onCopyCommand)
|
||||
if (!sideQuest) OtherWays(hasToggle, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging, onEnterAddressManually, onCopyCommand)
|
||||
}
|
||||
if (wide) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth()) {
|
||||
@@ -102,16 +104,15 @@ fun PhantomProcessGatePage(
|
||||
}
|
||||
}
|
||||
|
||||
private data class GateEnvironment(val onWifi: Boolean) {
|
||||
private data class GateEnvironment(val onWifi: Boolean, val notifications: Boolean) {
|
||||
companion object {
|
||||
fun read(context: Context): GateEnvironment {
|
||||
val connectivity = context.getSystemService(ConnectivityManager::class.java)
|
||||
val wifi = runCatching {
|
||||
connectivity?.allNetworks?.any { network ->
|
||||
connectivity.getNetworkCapabilities(network)?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true
|
||||
} == true
|
||||
connectivity?.getNetworkCapabilities(connectivity.activeNetwork)
|
||||
?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true
|
||||
}.getOrDefault(true)
|
||||
return GateEnvironment(wifi)
|
||||
return GateEnvironment(wifi, WirelessAdbPairingService.notificationsEnabled(context))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -125,6 +126,7 @@ private fun FixGroup(
|
||||
applyingSavedPairing: Boolean,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onFixWithWirelessDebugging: () -> Unit,
|
||||
onOpenNotificationSettings: () -> Unit,
|
||||
onCancel: () -> Unit,
|
||||
) {
|
||||
val pairing = stage is Stage.Waiting || stage is Stage.CodeNeeded || stage is Stage.Working
|
||||
@@ -142,7 +144,6 @@ private fun FixGroup(
|
||||
hasToggle -> {
|
||||
Body(stringResource(R.string.gate_toggle_steps))
|
||||
PrimaryButton(stringResource(R.string.gate_open_dev), compact = compact, onClick = onOpenDeveloperOptions)
|
||||
SecondaryButton(stringResource(R.string.gate_use_wireless_instead), compact = compact, enabled = environment.onWifi, onClick = onFixWithWirelessDebugging)
|
||||
}
|
||||
else -> {
|
||||
Body(stringResource(R.string.gate_no_toggle))
|
||||
@@ -150,7 +151,7 @@ private fun FixGroup(
|
||||
PrimaryButton(
|
||||
if (stage is Stage.Failed) stringResource(R.string.store_try_again) else stringResource(R.string.gate_fix_for_me),
|
||||
compact = compact,
|
||||
enabled = environment.onWifi,
|
||||
enabled = environment.onWifi && environment.notifications,
|
||||
onClick = onFixWithWirelessDebugging,
|
||||
)
|
||||
}
|
||||
@@ -159,6 +160,10 @@ private fun FixGroup(
|
||||
if (!environment.onWifi) {
|
||||
Body(stringResource(R.string.gate_needs_wifi), warn = true)
|
||||
}
|
||||
if (!environment.notifications) {
|
||||
Body(stringResource(R.string.gate_needs_notifications), warn = true)
|
||||
SecondaryButton(stringResource(R.string.gate_allow_notifications), compact = compact, onClick = onOpenNotificationSettings)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -219,6 +224,7 @@ private fun OtherWays(
|
||||
compact: Boolean,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onFixWithWirelessDebugging: () -> Unit,
|
||||
onEnterAddressManually: () -> Unit,
|
||||
onCopyCommand: () -> Unit,
|
||||
) {
|
||||
var open by rememberSaveable { mutableStateOf(false) }
|
||||
@@ -234,10 +240,14 @@ private fun OtherWays(
|
||||
modifier = Modifier.fillMaxWidth().padding(start = 14.dp, end = 14.dp, bottom = 14.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
if (!hasToggle) {
|
||||
if (hasToggle) {
|
||||
SecondaryButton(stringResource(R.string.gate_use_wireless_instead), compact = true, onClick = onFixWithWirelessDebugging)
|
||||
} else {
|
||||
Body(stringResource(R.string.gate_some_roms))
|
||||
SecondaryButton(stringResource(R.string.gate_open_dev), compact = true, onClick = onOpenDeveloperOptions)
|
||||
}
|
||||
Body(stringResource(R.string.gate_manual_hint))
|
||||
SecondaryButton(stringResource(R.string.gate_enter_manually), compact = true, onClick = onEnterAddressManually)
|
||||
Body(stringResource(R.string.gate_from_computer))
|
||||
AdbCommand()
|
||||
SecondaryButton(stringResource(R.string.gate_copy_command), compact = true, onClick = onCopyCommand)
|
||||
|
||||
@@ -283,7 +283,6 @@ class DrawerActions(
|
||||
val secondScreenDisplays: List<SecondScreenDisplay>,
|
||||
val selectedSecondScreenDisplay: Int,
|
||||
val onHud: (Boolean) -> Unit,
|
||||
val onHudOnlyDuringGame: (Boolean) -> Unit = {},
|
||||
val onHudSetting: (String, String) -> Unit = { _, _ -> },
|
||||
val onGpuClockPin: (Boolean) -> Unit = {},
|
||||
val onHudOrder: (Map<String, Boolean>, List<String>) -> Unit = { _, _ -> },
|
||||
@@ -1520,7 +1519,6 @@ private fun SecondScreenGroup(host: MenuHost, a: DrawerActions, track: (String)
|
||||
listOf(
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_AUTO to stringResource(R.string.setup_dual_screen_auto),
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_ON to stringResource(R.string.setup_dual_screen_on),
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_SWAPPED to stringResource(R.string.setup_dual_screen_swapped),
|
||||
com.droiddeck.launcher.input.DualScreen.MODE_OFF to stringResource(R.string.setup_dual_screen_off),
|
||||
), a.dualScreenMode, chipModifier = track("dual-screen-mode"), onPick = a.onDualScreenMode)
|
||||
if (swapsGame) ChoiceRow(host, "game-screen", stringResource(R.string.swap_game_screen), null,
|
||||
@@ -1787,15 +1785,12 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
|
||||
chipModifier = track("cmp-proton"),
|
||||
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) {
|
||||
val value = gameProfile.components.getValue(comp)
|
||||
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
|
||||
val options: List<Pair<String?, String>> =
|
||||
listOf(null to stringResource(R.string.comp_game_use_general)) +
|
||||
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 }
|
||||
if (managedDxvk) emptyList() else snap.packages.filter { it.comp == comp }.map { it.file to it.version }
|
||||
DrawerStackedChoice(
|
||||
host = host,
|
||||
key = "game-cmp-$comp",
|
||||
@@ -1878,7 +1873,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
|
||||
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
|
||||
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)) } +
|
||||
ComponentsManager.forTool(comp, p.dir.name, snap.packages.filter { it.comp == comp }, st.activeFile) { it.file }.map { it.file to it.version }
|
||||
snap.packages.filter { it.comp == comp }.map { it.file to it.version }
|
||||
if (options.isEmpty() && !managedDxvk) continue
|
||||
val current = st.activeFile ?: "orig:$build"
|
||||
val shown = options.firstOrNull { it.first == current }?.second
|
||||
|
||||
Loaded 100 of 363 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user