Compare commits

..
Author SHA1 Message Date
The412Banner 49381484dd fix(bionic): put the game's logs where Share logs finds them
Shared session logs never held DroidDeck-Bionic's own log or its
graphics logs. launch.sh wrote them into the game's prefix, which Share
logs does not read, and dropped the log locations Detailed graphics logs
sets along with the rest of the guest environment.

- proton: names a game launch's folder in the session folder (the
  game's log folder when Detailed graphics logs made one, else
  games/<date>-bionic-<appid>) and passes the graphics log locations as
  Android paths.
- launch.sh: writes the game's log into that folder; the prefix's
  droiddeck-bionic.log points to it, since Share logs takes only files
  with one name. Keeps DXVK_LOG_PATH, VKD3D_LOG_FILE and MESA_LOG_FILE.
- EnhancedSessionLogShare: keeps the name droiddeck-bionic.log and
  files it with the games.
2026-11-23 01:32:33 +00:00
The412Banner f17d3ddaad fix(bionic): name guest files by their Android paths in store launches
DroidDeck-Bionic's Wine has Android's root on Z:, but DroidDeck's store
launch files and helpers name guest files by guest Z: paths. A Ubisoft
game then skipped its service and started directly (Watch_Dogs exited at
launch); the Epic parent stand-in, GOG/Rockstar registry values, reg.exe
imports and the EA probe pointed at the wrong tree in the same way.
Reported by 2-Shar on PR #3037.

- proton: map guest Z: paths in every run argument (also NAME=Z:..., as
  in an installer's /DIR=) and export DROIDDECK_GUEST_ROOT, the guest's
  root as this Wine names it; launch.sh keeps it.
- StoreLaunch: the Ubisoft service and the Epic parent stand-in start
  from %DD_R% (DROIDDECK_GUEST_ROOT, else Z:). An installed Ubisoft
  game's older launch file is rewritten at the next library scan.
- droiddeck-store-launch: windows_path() asks DroidDeck-Bionic's
  getcompatpath when that tool runs the game.
- droiddeck-gog-maintenance: name the tool for the registry step.
2026-11-23 00:44:48 +00:00
The412Banner 2aae4b2284 fix(bionic): address review findings
Launcher (tools/bionic-runtime/tool/launch.sh)
- The FEX code cache is also cleared when another FEX build wrote to it since this tool last ran the prefix:
  the stamp now holds the FEX ID and a fingerprint of the caches, saved after each run (also after
  runinprefix and when Steam stops the game).
- A game started by a launcher that then exits keeps the tool waiting: the wait goes on while any program
  of the prefix runs, apart from Wine's own services. The game is looked up in this prefix only, by its
  name as fixed text.
- The tool exits with Wine's status instead of 0.

Install scripts (droiddeck-game-env)
- A "run process" entry counts as done only when its hasrunkey value is a DWORD of at least its
  MinimumHasRunValue (1 by default), as Steam's evaluator decides; a 0 or a value of another type no longer
  lets the evaluator be skipped.

Helpers
- execshim: non-regular files (a FIFO) go to libc without a blocking open; libc functions are bound at load
  through atomic slots; relative posix_spawn paths with file actions are left to libc; the argument vector
  has room for its terminator when argv is empty.
- gstag: replies and errors are matched to their request's sequence number per connection; one bounded
  packet reader; destroyed windows leave the candidate and tagged lists; the focus override needs a live
  tagged window and a successful focus read; only gone candidates are pruned.
- steamshm: a new shared object is created and sized under a private name and then put in place in one
  step; both code redirects go in or neither, and unused trampolines are released.
- check-needed.py fails when readelf fails and ignores dangling links.
- The bionic runtime workflow also runs for tools/gpuload changes.

App and tool wrapper
- FEX twin downloads run once per name; a twin that a game's FEX choice still needs on an installed tool
  cannot be deleted.
- With proot on and no DroidDeck-Proton installed, a launch sent to DroidDeck-Bionic stops with a message
  instead of starting the bionic tool.
2026-11-22 17:56:19 -05:00
The412Banner dca443e3aa feat(bionic): DroidDeck-Bionic compatibility tool (Wine on Android's libc, no proot)
DroidDeck-Bionic is a Steam compatibility tool that runs the game itself with
Android's own libc (bionic) instead of glibc inside proot. Steam, the stores and
the session stay on DroidDeck's Linux side unchanged; only the game process
leaves proot. It is listed in the Proton list only when "Run without proot" is
on, and it is shipped as a pre-release runtime pack (DroidDeck-Bionic-12.8-rNN
on Droid-Deck/DroidDeck-Proton), never as the default for other users.

Runtime pack (tools/bionic-runtime, .github/workflows/build-bionic-runtime.yml)
- CI builds an aarch64 bionic pack: the Wine layer from The412Banner/proton-wine
  (bionic build), an exec shim, launcher (tool/launch.sh + proton verbs run,
  runinprefix, waitforexitandrun), gamescope's WSI layer (patches 0117 + 0119),
  DroidDeck's GPU-load layer, fake input (fakeinput_steam.cpp), GStreamer
  plugins, Zink/Fast OpenGL Mesa, DXVK, VKD3D-Proton, D7VK and FEX (ARM64EC).
- Games run on gamescope's X server; Steam store games reach DroidDeck's Steam
  (lsteamclient), Steam Input works (shared /dev/shm via libsteamshm), and
  Steam Cloud maps Windows save folders (tool name contains "Proton").
- DroidDeck's game settings, game-environment fixes, in-game layers and DXVK /
  VKD3D / FEX choices reach bionic games the same way they reach
  DroidDeck-Proton games (DD_* setting names).
- Prefixes stay compatible both ways with DroidDeck-Proton: dead links are
  removed, the tool's .NET stubs and comctl32 v6 survive Wine updates, a stale
  FEX code cache from another FEX build is cleared, drive Z: is the whole device.
- Store launches: Xbox (Windows exe path + Xbox runtime environment), GOG and
  Epic (.bat launchers, games that rename their process).

App changes (all additive)
- ProtonExtras / ProtonMenu / ExperimentalProtons / droiddeck-proton-extra:
  DroidDeck-Bionic pre-releases are checked and listed only with Run without
  proot on, in their own row (not under Experimental); updates replace the
  older build and carry the default tool and per-game picks over; deleting a
  tool removes links inside it, never what they point to.
- ProtonDefault: a default or game pick left on an older bionic build moves to
  the installed one; bionic picks start on DroidDeck-Proton when Run without
  proot is off.
- ComponentsManager / ComponentUpdates / ComponentUpdater / ComponentsPage /
  SessionOverlay: FEX components for DroidDeck-Bionic (bionic-stable on
  DroidDeck-Components); each tool is offered only FEX builds that fit it.
- SessionService: DROIDDECK_DISPLAY_DRIVER tells bionic games which Turnip the
  display uses when the chosen runtime driver has no Android build.
- steam-compatibility: with proot on, a launch sent to a DroidDeck-Bionic tool
  goes to the newest DroidDeck-Proton (picks stay as set); glibc FEX rows are
  never applied to a DroidDeck-Bionic tool.
- droiddeck-game-env: Steam's install-script evaluator is skipped when its
  scripts only run processes already marked as done.

Tests
- New: ComponentsBionicFexTest; extended ComponentsRepublishTest,
  ExperimentalProtonsTest, ProtonDefaultTest, ProtonExtrasTest,
  test_game_environment.py, test_proton_extra.py.

Device testing (Pocket FIT, Adreno 750; Pocket FIT Elite, Adreno 830)
- Steam (Brawlhalla online, Left 4 Dead 2 controller, Black Ops II, Steam
  Cloud), Xbox, GOG, Epic and Amazon games run; saves carry both ways between
  DroidDeck-Bionic and DroidDeck-Proton on Xbox, GOG, Epic and Amazon.
- Not tested: EA, Ubisoft, Battle.net (no owned game / not signed in).
2026-11-22 17:12:43 -05:00
353 changed files with 7379 additions and 14655 deletions

No files matched your search

-1
View File
@@ -6,4 +6,3 @@ KeegantheVeganat0r
kingokksa kingokksa
ovurrsl ovurrsl
KeegantheVeganat0r KeegantheVeganat0r
EnzoDLofi
@@ -0,0 +1,35 @@
name: Build bionic runtime pack and DroidDeck-Bionic tool
on:
push:
paths:
- 'tools/bionic-runtime/**'
- 'tools/gamescope/patches/0117-wsi-cache-present-bypass-check.patch'
- 'tools/gamescope/patches/0119-wsi-default-images-under-limiter.patch'
- 'app/src/main/cpp/fakeinput_steam.cpp'
- 'tools/gpuload/**'
- '.github/workflows/build-bionic-runtime.yml'
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-24.04
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
- name: Host tools
run: |
set -euo pipefail
sudo apt-get update -qq
sudo apt-get install -y -qq --no-install-recommends libwayland-bin libwayland-dev libx11-dev libx11-xcb-dev \
libxcb1-dev libxcb-composite0-dev libglm-dev zstd
- name: Build
run: |
set -euo pipefail
export NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
export BUILD_NUMBER=${{ github.run_number }}
tools/bionic-runtime/build.sh "$RUNNER_TEMP/bionic-runtime" "$PWD/out"
- uses: actions/upload-artifact@v4
with:
name: droiddeck-bionic-runtime-${{ github.sha }}
path: out/*
-75
View File
@@ -164,9 +164,6 @@ jobs:
!/docs/releases/media/ !/docs/releases/media/
sparse-checkout-cone-mode: false sparse-checkout-cone-mode: false
persist-credentials: false persist-credentials: false
- name: Clear scratch earlier runs left behind
if: runner.environment == 'self-hosted'
run: bash tools/ci/clear-runner-scratch.sh "$GITHUB_WORKSPACE"
- name: Merge the pinned APK base - name: Merge the pinned APK base
if: github.event_name == 'pull_request' if: github.event_name == 'pull_request'
env: env:
@@ -370,10 +367,6 @@ jobs:
persist-credentials: false persist-credentials: false
submodules: recursive submodules: recursive
- name: Clear scratch earlier runs left behind
if: runner.environment == 'self-hosted'
run: bash tools/ci/clear-runner-scratch.sh "$GITHUB_WORKSPACE"
- name: Check human authorship - name: Check human authorship
env: env:
EVENT_NAME: ${{ github.event_name }} EVENT_NAME: ${{ github.event_name }}
@@ -572,65 +565,23 @@ jobs:
SOURCE_TREE: ${{ needs.source.outputs.tree-sha }} SOURCE_TREE: ${{ needs.source.outputs.tree-sha }}
run: python3 tools/components/prepare.py unpack --tree "$SOURCE_TREE" 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) - name: Ubisoft launcher service (x86_64-pc-windows-gnu)
if: steps.ubisoft-cache.outputs.cache-hit != 'true'
run: | run: |
set -euo pipefail 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; } 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 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) - name: Rockstar launcher service (32-bit and 64-bit)
if: steps.rockstar-cache.outputs.cache-hit != 'true'
run: | run: |
set -euo pipefail 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 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 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) - name: Epic Games Launcher parent stand-in (x86_64-pc-windows-gnu)
if: steps.epic-cache.outputs.cache-hit != 'true'
run: | run: |
set -euo pipefail 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; } 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 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 - uses: actions/download-artifact@v4
with: with:
@@ -734,32 +685,6 @@ jobs:
if-no-files-found: ignore if-no-files-found: ignore
overwrite: true overwrite: true
- name: Resolve the Robolectric version
id: robolectric
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: Cache Robolectric's Android jars
if: steps.robolectric-jars.outputs.cache == 'true'
uses: actions/cache@v4
with:
path: ../robolectric-jars
key: robolectric-android-all-v2-${{ steps.robolectric.outputs.version }}
- name: Unit tests - name: Unit tests
id: unit-tests id: unit-tests
env: env:
+1 -36
View File
@@ -2,42 +2,7 @@
- Comments should be rare, factual, and explain only non-obvious external constraints or business invariants. - Comments should be rare, factual, and explain only non-obvious external constraints or business invariants.
# Building and testing # Working on the device
- For an install-and-look iteration, use `tools/quick_deploy.sh` (build without lint, sign, install, about 30 s). Run `tools/build_local.sh` once to prepare the runtime and again only before a PR. It is not a per-change step.
- `tools/build_local.sh` reuses the components a main CI run prepared when every recipe identity matches the local tree (it prints `components: … reusing`). It builds them locally when no usable CI artifact matches (after you change their inputs, or when the lookup fails) or with `DROIDDECK_CI_COMPONENTS=0`.
- Helper scripts (`tools/linuxfs/overlay`, `tools/linuxfs/desktop`) are staged on every Gradle build, so editing them needs no `build_local.sh`. After preloads or other runtime components change, the fast loop warns and reuses the old binaries; run `tools/build_local.sh` when those matter. "Missing or changed runtime input" means the prepared files themselves changed: run `tools/build_local.sh` once. Do not revert scripts or copy `app/build` between checkouts; `tools/seed_worktree.sh` seeds a new worktree from the main checkout.
- Every build defaults to the NDK in `tools/ci/toolchains.env`, as CI does. CI runs `testReleaseUnitTest`; when a test fails only in CI, run the release variant locally.
- Run the tests that cover what you changed, including unchanged tests of code you edited: `./gradlew -PskipRust=true :app:testDebugUnitTest --tests '<class>'` and `python3 -m unittest discover -s tools/tests -p 'test_<area>*.py'`. The full Python suite takes about 9 minutes, and some preload tests fail on any host without zram/ntsync. Leave full runs to CI.
- For UI screenshots without a device, run `./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*PreviewRenderTest'` and read `app/build/preview-renders/{handheld,portrait}/`. Add cases per `docs/compose-previews.md`. Check portrait, not just landscape.
- After changing `SettingsIndex`, regenerate the doc: `UPDATE_SETTINGS_MAP=1 ./gradlew -PskipRust=true :app:testDebugUnitTest --tests '*SettingsMapTest*'`.
- Compile errors in code you didn't touch, after switching branches, are usually stale incremental state. Rebuild once before you change anything.
# Worktrees and shared machines
- After `git worktree add`, run `git submodule update --init --recursive`. Without it, `buildVkBridgeServer` fails on missing `external/MaliBridge`. Do not commit the `tools/syncthing/syncthing-android` pointer the build dirties.
- Other agents may be building on the same machine. Never run `./gradlew --stop` or kill Gradle/Kotlin daemons you did not start. If you need isolation, use `GRADLE_USER_HOME=<own dir> GRADLE_RO_DEP_CACHE=$HOME/.gradle/caches`.
# Driving the app and device
- Do it yourself with `tools/droiddeckctl` (see `docs/agent-control.md`) instead of asking the user: `cdp eval` for Steam's UI (`SteamClient.Apps.TerminateApp('<appid>', false)` quits a game, including on a Remote Play host), `input`, `quit`, `displays`, `screenshot --display <id>`.
- A stream has started only when the session state reads `Streaming`. `SteamClient.Apps.StreamGame` alone can leave Steam on its menu, so open the game page and press Stream.
- Test controller navigation with `tools/droiddeckctl input gamepad ...`, a real uinput pad. `adb shell input keyevent DPAD_*` does not arrive as a joystick event and hides d-pad/stick bugs.
- A release-signed build installs over a release-signed install with `adb install -r`. Don't back up, uninstall or clear data to update. Scope `pm` and permission resets to `com.droiddeck.launcher`, never the whole device.
# 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.
- `gh run view --log-failed` truncates the unit-test log, so the failing test may not show. Read the whole job log with `gh api repos/Droid-Deck/DroidDeck/actions/jobs/<job-id>/logs`, or `gh run download <run> -n unit-test-results`. Don't call a failure a runner problem until you have read it.
- Only these are known flakes worth a `gh run rerun <run> --failed`: `ProtonMenuAutoTest` "Proton work did not finish", Robolectric `HTTP response code: 429` from Maven, `Gradle Test Executor N finished with non-zero exit value 2`, apt mirror and GitHub API rate-limit errors. Treat any other failure as real.
- A workflow step that names a script your branch lacks means the branch predates a CI change. Rebase onto `main`.
# Agents running on the device (DroidDeck's in-app agent)
These apply only where `dd-lab-build` exists. Agents on a dev host use `tools/quick_deploy.sh` instead.
- `dd-lab-build` builds only committed work. Check `git status` and `gh api user` for the identity before committing; if `git config user.name` is empty, use the `gh` login's name and noreply email for this repo, never a guess. - `dd-lab-build` builds only committed work. Check `git status` and `gh api user` for the identity before committing; if `git config user.name` is empty, use the `gh` login's name and noreply email for this repo, never a guess.
- Do not commit or start a build in the same step: a build started next to a failed commit fails too. Commit first, check it, then build. - Do not commit or start a build in the same step: a build started next to a failed commit fails too. Commit first, check it, then build.
+2 -2
View File
@@ -70,7 +70,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. - Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). - mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122). - [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source.
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence. - x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
- x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes. - x86 programs linking OpenSSL 3 use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt). x86 Linux games get the `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes.
- `WriteProcessMemory` hooks fall back to `/proc/<pid>/mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11. - `WriteProcessMemory` hooks fall back to `/proc/<pid>/mem` the way [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` did before Wine 11.
@@ -91,7 +91,7 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
<details> <details>
<summary><b>Stores</b></summary> <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. - 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). - 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`. - 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`.
+6 -8
View File
@@ -125,8 +125,7 @@ def variantSuffixes = rootProject.file('tools/release/variants.txt').readLines()
android { android {
namespace 'com.droiddeck.launcher' namespace 'com.droiddeck.launcher'
compileSdk 34 compileSdk 34
ndkVersion project.findProperty('ndkVersion') ?: providers.fileContents(rootProject.layout.projectDirectory.file('tools/ci/toolchains.env')) ndkVersion project.findProperty('ndkVersion') ?: '27.3.13750724'
.asText.get().readLines().find { it.startsWith('CI_ANDROID_NDK_VERSION=') }.split('=', 2)[1].trim()
defaultConfig { defaultConfig {
applicationId "com.droiddeck.launcher" applicationId "com.droiddeck.launcher"
@@ -233,9 +232,6 @@ android {
} }
maxHeapSize = '2g' maxHeapSize = '2g'
maxParallelForks = 2 maxParallelForks = 2
def jvmTemp = new File(temporaryDir, 'jvm')
systemProperty 'java.io.tmpdir', jvmTemp.absolutePath
doFirst { jvmTemp.mkdirs() }
def logTarget = providers.systemProperty('robolectric.logging').orNull def logTarget = providers.systemProperty('robolectric.logging').orNull
if (logTarget != null) systemProperty 'robolectric.logging', logTarget if (logTarget != null) systemProperty 'robolectric.logging', logTarget
} }
@@ -265,9 +261,11 @@ if (vitureSdkDir) {
tasks.named('preBuild').configure { dependsOn(stageVitureNotices) } tasks.named('preBuild').configure { dependsOn(stageVitureNotices) }
} }
def stageSessionScripts = tasks.register('stageSessionScripts', Exec) { def stageSessionScripts = tasks.register('stageSessionScripts', Copy) {
workingDir rootProject.projectDir from(rootProject.file('tools/linuxfs/overlay')) {
commandLine pythonExecutable, 'tools/release/check_session_assets.py', '--stage' include 'usr/local/bin/droiddeck-*', 'usr/local/bin/steam-compatibility', 'usr/bin/**'
}
into(layout.projectDirectory.dir('src/main/assets/linuxfs'))
} }
tasks.named('preBuild').configure { dependsOn(stageSessionScripts) } tasks.named('preBuild').configure { dependsOn(stageSessionScripts) }
@@ -15,7 +15,6 @@ private fun Launcher(tab: String, games: List<com.droiddeck.launcher.frontend.Li
PreviewHost { FrontEndScreen(sampleState(games = games, navigate = tab, ready = ready), sampleActions) } PreviewHost { FrontEndScreen(sampleState(games = games, navigate = tab, ready = ready), sampleActions) }
@DroidDeckPreviews @Composable private fun SteamTabPreview() = Launcher("steam") @DroidDeckPreviews @Composable private fun SteamTabPreview() = Launcher("steam")
@DroidDeckPreviews @Composable private fun SteamEmptyPreview() = Launcher("steam", games = emptyList())
@DroidDeckPreviews @Composable private fun LibraryPreview() = Launcher("games") @DroidDeckPreviews @Composable private fun LibraryPreview() = Launcher("games")
@DroidDeckPreviews @Composable private fun LibraryEmptyPreview() = Launcher("games", games = emptyList()) @DroidDeckPreviews @Composable private fun LibraryEmptyPreview() = Launcher("games", games = emptyList())
@DroidDeckPreviews @Composable private fun StoresPreview() = Launcher("stores") @DroidDeckPreviews @Composable private fun StoresPreview() = Launcher("stores")
@@ -61,7 +61,7 @@ internal val sampleActions: FrontEndActions = FrontEndActions(
onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {}, onSteamSettings = {}, onDesktopSettings = {}, onInstallPackage = {}, onRemovePackage = {}, onRuntime = {},
onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {}, onFrameGenPick = {}, onImportLossless = {}, onProtons = {}, onComponents = {}, onPerformance = {}, onRoms = {},
onFiles = {}, onLogs = {}, onOffline = {}, onFiles = {}, onLogs = {}, onOffline = {},
onSetPhantomProcessLimit = { _, _ -> }, onWirelessAdbPair = { _, _, _, _ -> }, onWirelessAdbApply = { _, _, _, _ -> }, onSetPhantomProcessLimit = { _, _ -> },
) )
/** The in-game menu's actions with settled sample values; its switches do nothing. */ /** The in-game menu's actions with settled sample values; its switches do nothing. */
-1
View File
@@ -232,7 +232,6 @@
android:exported="false" android:exported="false"
android:screenOrientation="user" android:screenOrientation="user"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density" android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|density"
android:windowSoftInputMode="adjustResize"
android:theme="@style/AppTheme" /> android:theme="@style/AppTheme" />
<activity <activity
+24 -128
View File
@@ -21,7 +21,6 @@
#define SYS_munmap 215 #define SYS_munmap 215
#define SYS_mmap 222 #define SYS_mmap 222
#define SYS_mprotect 226 #define SYS_mprotect 226
#define SYS_getpid 172
#define AT_FDCWD_ (-100) #define AT_FDCWD_ (-100)
#define O_RDONLY_ 0 #define O_RDONLY_ 0
@@ -53,21 +52,6 @@ static size_t slen(const char *s) {
return n; return n;
} }
static int seq(const char *a, const char *b) {
while (*a && *a == *b) a++, b++;
return *a == *b;
}
static const char *env_get(char **envp, const char *name) {
size_t n = slen(name);
for (; *envp; envp++) {
size_t i = 0;
while (i < n && (*envp)[i] == name[i]) i++;
if (i == n && (*envp)[n] == '=') return *envp + n + 1;
}
return 0;
}
static void out(const char *s) { sys6(SYS_write, 2, (long)s, (long)slen(s), 0, 0, 0); } static void out(const char *s) { sys6(SYS_write, 2, (long)s, (long)slen(s), 0, 0, 0); }
static void out_num(long v) { static void out_num(long v) {
@@ -128,43 +112,19 @@ static int prot_of(uint32_t flags) {
static void map_failed(const char *path, long r) { die("cannot map a segment", path, r); } static void map_failed(const char *path, long r) { die("cannot map a segment", path, r); }
static void read_interp(int fd, const Elf64_Phdr *ph, int phnum, char *interp, size_t size, const char *path) { static void load(const char *path, struct image *im, uintptr_t page) {
interp[0] = 0;
for (int i = 0; i < phnum; i++) {
if (ph[i].p_type != PT_INTERP) continue;
if (ph[i].p_filesz == 0 || ph[i].p_filesz >= size) die("bad PT_INTERP", path, 0);
if (xpread(fd, interp, ph[i].p_filesz, (long)ph[i].p_offset) != (long)ph[i].p_filesz)
die("truncated PT_INTERP", path, 0);
interp[ph[i].p_filesz] = 0;
}
}
static int read_headers(const char *path, Elf64_Ehdr *eh, Elf64_Phdr *ph) {
int fd = (int)sys6(SYS_openat, AT_FDCWD_, (long)path, O_RDONLY_ | O_CLOEXEC_, 0, 0, 0); int fd = (int)sys6(SYS_openat, AT_FDCWD_, (long)path, O_RDONLY_ | O_CLOEXEC_, 0, 0, 0);
if (fd < 0) die("cannot open", path, fd); if (fd < 0) die("cannot open", path, fd);
if (xpread(fd, eh, sizeof(*eh), 0) != (long)sizeof(*eh)) die("not an ELF file", path, 0); Elf64_Ehdr eh;
if (eh->e_ident[EI_MAG0] != ELFMAG0 || eh->e_ident[EI_MAG1] != ELFMAG1 || eh->e_ident[EI_MAG2] != ELFMAG2 || if (xpread(fd, &eh, sizeof(eh), 0) != (long)sizeof(eh)) die("not an ELF file", path, 0);
eh->e_ident[EI_MAG3] != ELFMAG3 || eh->e_ident[EI_CLASS] != ELFCLASS64 || eh->e_machine != EM_AARCH64 || if (eh.e_ident[EI_MAG0] != ELFMAG0 || eh.e_ident[EI_MAG1] != ELFMAG1 || eh.e_ident[EI_MAG2] != ELFMAG2 ||
(eh->e_type != ET_EXEC && eh->e_type != ET_DYN) || eh->e_phentsize != sizeof(Elf64_Phdr) || eh.e_ident[EI_MAG3] != ELFMAG3 || eh.e_ident[EI_CLASS] != ELFCLASS64 || eh.e_machine != EM_AARCH64 ||
eh->e_phnum == 0 || eh->e_phnum > MAX_PHDRS) (eh.e_type != ET_EXEC && eh.e_type != ET_DYN) || eh.e_phentsize != sizeof(Elf64_Phdr) ||
eh.e_phnum == 0 || eh.e_phnum > MAX_PHDRS)
die("not a 64-bit ARM ELF program", path, 0); die("not a 64-bit ARM ELF program", path, 0);
long size = (long)eh->e_phnum * (long)sizeof(Elf64_Phdr);
if (xpread(fd, ph, (size_t)size, (long)eh->e_phoff) != size) die("truncated program headers", path, 0);
return fd;
}
static void interp_of(const char *path, char *interp, size_t size) {
Elf64_Ehdr eh;
Elf64_Phdr ph[MAX_PHDRS]; Elf64_Phdr ph[MAX_PHDRS];
int fd = read_headers(path, &eh, ph); long size = (long)eh.e_phnum * (long)sizeof(Elf64_Phdr);
read_interp(fd, ph, eh.e_phnum, interp, size, path); if (xpread(fd, ph, (size_t)size, (long)eh.e_phoff) != size) die("truncated program headers", path, 0);
sys6(SYS_close, fd, 0, 0, 0, 0, 0);
}
static void load(const char *path, struct image *im, uintptr_t page) {
Elf64_Ehdr eh;
Elf64_Phdr ph[MAX_PHDRS];
int fd = read_headers(path, &eh, ph);
uintptr_t lo = UINTPTR_MAX, hi = 0; uintptr_t lo = UINTPTR_MAX, hi = 0;
for (int i = 0; i < eh.e_phnum; i++) { for (int i = 0; i < eh.e_phnum; i++) {
@@ -213,9 +173,16 @@ static void load(const char *path, struct image *im, uintptr_t page) {
im->phnum = eh.e_phnum; im->phnum = eh.e_phnum;
im->phent = eh.e_phentsize; im->phent = eh.e_phentsize;
im->phdr = 0; im->phdr = 0;
read_interp(fd, ph, eh.e_phnum, im->interp, sizeof(im->interp), path); im->interp[0] = 0;
for (int i = 0; i < eh.e_phnum; i++) for (int i = 0; i < eh.e_phnum; i++) {
if (ph[i].p_type == PT_PHDR) im->phdr = bias + ph[i].p_vaddr; if (ph[i].p_type == PT_PHDR) im->phdr = bias + ph[i].p_vaddr;
if (ph[i].p_type == PT_INTERP) {
if (ph[i].p_filesz == 0 || ph[i].p_filesz >= sizeof(im->interp)) die("bad PT_INTERP", path, 0);
if (xpread(fd, im->interp, ph[i].p_filesz, (long)ph[i].p_offset) != (long)ph[i].p_filesz)
die("truncated PT_INTERP", path, 0);
im->interp[ph[i].p_filesz] = 0;
}
}
if (!im->phdr) { if (!im->phdr) {
for (int i = 0; i < eh.e_phnum; i++) { for (int i = 0; i < eh.e_phnum; i++) {
Elf64_Phdr *p = &ph[i]; Elf64_Phdr *p = &ph[i];
@@ -235,36 +202,6 @@ static unsigned long auxv_get(const uintptr_t *auxv, unsigned long type, unsigne
return fallback; return fallback;
} }
static int is_self_exe(const char *execfn) {
if (!execfn) return 0;
if (seq(execfn, "/proc/self/exe") || seq(execfn, "/proc/thread-self/exe")) return 1;
const char *p = "/proc/";
while (*p && *p == *execfn) p++, execfn++;
if (*p) return 0;
char num[24];
int i = (int)sizeof(num) - 1;
num[i] = 0;
unsigned long pid = (unsigned long)sys6(SYS_getpid, 0, 0, 0, 0, 0, 0);
do {
num[--i] = (char)('0' + pid % 10);
pid /= 10;
} while (pid && i > 0);
const char *d = num + i;
while (*d && *d == *execfn) d++, execfn++;
return !*d && seq(execfn, "/exe");
}
static const char *guest_interp(char **envp, const char *interp, char *buf, size_t size) {
const char *root = env_get(envp, "DDNATV_ROOT");
if (!root || interp[0] != '/') return interp;
size_t a = slen(root), b = slen(interp);
if (a + b + 1 > size) return interp;
for (size_t i = 0; i < a; i++) buf[i] = root[i];
for (size_t i = 0; i <= b; i++) buf[a + i] = interp[i];
if (sys6(SYS_faccessat, AT_FDCWD_, (long)buf, 0, 0, 0, 0) != 0) return interp;
return buf;
}
__attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) { __attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) {
long argc = (long)sp[0]; long argc = (long)sp[0];
char **argv = (char **)(sp + 1); char **argv = (char **)(sp + 1);
@@ -274,66 +211,25 @@ __attribute__((used, noreturn)) void ddexec_main(uintptr_t *sp) {
uintptr_t *auxv = (uintptr_t *)(envp + nenv + 1); uintptr_t *auxv = (uintptr_t *)(envp + nenv + 1);
long naux = 0; long naux = 0;
while (auxv[naux * 2] != AT_NULL) naux++; while (auxv[naux * 2] != AT_NULL) naux++;
int reexec = is_self_exe((const char *)auxv_get(auxv, AT_EXECFN, 0)); if (argc < 3) die("usage: libddexec.so <file> <argv0> [args...]", 0, 0);
const char *path;
char **args = argv + 2;
long nargs = argc - 2;
char interp_buf[4096];
char hook_buf[4096];
if (reexec) {
path = env_get(envp, "DDNATV_REAL_EXE");
if (!path || !path[0]) die("re-executed without DDNATV_REAL_EXE", 0, 0);
args = argv;
nargs = argc;
const char *lib_path = env_get(envp, "DDNATV_LIBRARY_PATH");
char prog_interp[256];
interp_of(path, prog_interp, sizeof(prog_interp));
if (prog_interp[0] && lib_path && lib_path[0]) {
const char *ld_so = guest_interp(envp, prog_interp, interp_buf, sizeof(interp_buf));
const char *hook = guest_interp(envp, "/usr/lib/libddnatv-hook.so", hook_buf, sizeof(hook_buf));
if (hook != (const char *)hook_buf) hook = guest_interp(envp, "/lib/libddnatv-hook.so", hook_buf, sizeof(hook_buf));
long n = argc > 1 ? argc - 1 : 0;
char **v = (char **)__builtin_alloca((size_t)(n + 9) * sizeof(char *));
long k = 0;
v[k++] = (char *)ld_so;
if (hook == (const char *)hook_buf) {
v[k++] = (char *)"--preload";
v[k++] = (char *)hook;
}
v[k++] = (char *)"--library-path";
v[k++] = (char *)lib_path;
v[k++] = (char *)"--argv0";
v[k++] = argc > 0 ? argv[0] : (char *)path;
v[k++] = (char *)path;
for (long i = 0; i < n; i++) v[k++] = argv[1 + i];
v[k] = 0;
args = v;
nargs = k;
path = ld_so;
}
} else if (argc < 3) {
die("usage: libddexec.so <file> <argv0> [args...]", 0, 0);
} else {
path = argv[1];
}
uintptr_t page = auxv_get(auxv, AT_PAGESZ, 4096); uintptr_t page = auxv_get(auxv, AT_PAGESZ, 4096);
const char *path = argv[1];
struct image prog, interp; struct image prog, interp;
load(path, &prog, page); load(path, &prog, page);
int has_interp = prog.interp[0] != 0; int has_interp = prog.interp[0] != 0;
if (has_interp) load(reexec ? guest_interp(envp, prog.interp, interp_buf, sizeof(interp_buf)) : prog.interp, &interp, page); if (has_interp) load(prog.interp, &interp, page);
// The new stack: argc, argv, envp and auxv as the kernel lays them out, below the current one. // The new stack: argc, argv, envp and auxv as the kernel lays them out, below the current one.
// The strings stay where the kernel put them. // The strings stay where the kernel put them.
static const unsigned long replaced[] = {AT_PHDR, AT_PHENT, AT_PHNUM, AT_BASE, AT_ENTRY, AT_EXECFN}; static const unsigned long replaced[] = {AT_PHDR, AT_PHENT, AT_PHNUM, AT_BASE, AT_ENTRY, AT_EXECFN};
long nreplaced = (long)(sizeof(replaced) / sizeof(replaced[0])); long nreplaced = (long)(sizeof(replaced) / sizeof(replaced[0]));
long new_argc = nargs; long new_argc = argc - 2;
long words = 1 + (new_argc + 1) + (nenv + 1) + (naux + nreplaced + 1) * 2; long words = 1 + (new_argc + 1) + (nenv + 1) + (naux + nreplaced + 1) * 2;
uintptr_t top = (uintptr_t)args < (uintptr_t)sp ? (uintptr_t)args : (uintptr_t)sp; uintptr_t *nsp = (uintptr_t *)(((uintptr_t)sp - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15);
uintptr_t *nsp = (uintptr_t *)((top - STACK_GAP - (uintptr_t)words * sizeof(uintptr_t)) & ~(uintptr_t)15);
uintptr_t *w = nsp; uintptr_t *w = nsp;
*w++ = (uintptr_t)new_argc; *w++ = (uintptr_t)new_argc;
for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)args[i]; for (long i = 0; i < new_argc; i++) *w++ = (uintptr_t)argv[i + 2];
*w++ = 0; *w++ = 0;
for (long i = 0; i < nenv; i++) *w++ = (uintptr_t)envp[i]; for (long i = 0; i < nenv; i++) *w++ = (uintptr_t)envp[i];
*w++ = 0; *w++ = 0;
+32 -1
View File
@@ -205,6 +205,11 @@ static void controller_fork_prepare();
static void controller_fork_parent(); static void controller_fork_parent();
static void controller_fork_child(); static void controller_fork_child();
// bionic: libc's own start-up calls hooked functions (access) before environ is set. Settings read
// then would be empty and cached for good, so until environ exists hooks see defaults, uncached.
extern "C" char **environ;
static bool env_ready() { return environ != nullptr; }
struct FakeConfig { struct FakeConfig {
const char *hook_dir; const char *hook_dir;
const char *udev_data_dir; const char *udev_data_dir;
@@ -218,6 +223,10 @@ struct FakeConfig {
// would throw a recursive-init error there, so the fields are filled without allocating, and a // would throw a recursive-init error there, so the fields are filled without allocating, and a
// reentry on the initializing thread gets them while other threads wait for the fork handlers. // reentry on the initializing thread gets them while other threads wait for the fork handlers.
static FakeConfig &config() { static FakeConfig &config() {
if (!env_ready()) {
static FakeConfig early = {"/data/data/com.termux/files/home/fake-input", nullptr, false, false, false};
return early;
}
static FakeConfig cfg; static FakeConfig cfg;
static std::atomic<int> state{0}; static std::atomic<int> state{0};
static __thread bool initializing __attribute__((tls_model("initial-exec"))); static __thread bool initializing __attribute__((tls_model("initial-exec")));
@@ -587,7 +596,7 @@ get_fake_input_rdev(const char *event) {
__attribute__((visibility("hidden"))) static void load_ring_paths() { __attribute__((visibility("hidden"))) static void load_ring_paths() {
std::lock_guard<std::recursive_mutex> guard(controller_mutex()); std::lock_guard<std::recursive_mutex> guard(controller_mutex());
if (ring_paths_loaded) if (ring_paths_loaded || !env_ready())
return; return;
const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS"); const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS");
@@ -807,12 +816,25 @@ __attribute__((visibility("hidden"))) static bool is_steam_client() {
__attribute__((visibility("hidden"))) static bool presents_steam_virtual() { __attribute__((visibility("hidden"))) static bool presents_steam_virtual() {
static int known; static int known;
if (known == 0) { if (known == 0) {
if (!env_ready()) return false;
const char *enabled = getenv("FAKE_EVDEV_STEAM_VIRTUAL"); const char *enabled = getenv("FAKE_EVDEV_STEAM_VIRTUAL");
known = enabled && atoi(enabled) && !is_steam_client() ? 1 : -1; known = enabled && atoi(enabled) && !is_steam_client() ? 1 : -1;
} }
return known == 1; return known == 1;
} }
// The bionic Proton layer's winebus has no udev bus, and its SDL bus skips 28de:11ff (Proton reads Steam's virtual
// pad through udev/evdev), so with FAKE_EVDEV_STEAM_PAD_AS_X360=1 other processes see that pad as a plain Xbox 360 pad.
__attribute__((visibility("hidden"))) static bool steam_pad_as_x360() {
static int known;
if (known == 0) {
if (!env_ready()) return false;
const char *v = getenv("FAKE_EVDEV_STEAM_PAD_AS_X360");
known = v && atoi(v) && !is_steam_client() ? 1 : -1;
}
return known == 1;
}
__attribute__((visibility("hidden"))) static bool __attribute__((visibility("hidden"))) static bool
presents_xbox_triggers(const FakeController &fake) { presents_xbox_triggers(const FakeController &fake) {
return fake.uinput || !is_steam_client(); return fake.uinput || !is_steam_client();
@@ -1391,6 +1413,7 @@ static std::unordered_map<int, std::shared_ptr<DeckHidraw>> &deck_map() {
static bool fake_deck_enabled() { static bool fake_deck_enabled() {
static int enabled = -1; static int enabled = -1;
if (enabled < 0 && !env_ready()) return false;
if (enabled < 0) enabled = getenv("FAKE_EVDEV_DECK") && atoi(getenv("FAKE_EVDEV_DECK")) ? 1 : 0; if (enabled < 0) enabled = getenv("FAKE_EVDEV_DECK") && atoi(getenv("FAKE_EVDEV_DECK")) ? 1 : 0;
return enabled == 1; return enabled == 1;
} }
@@ -1398,6 +1421,7 @@ static bool fake_deck_enabled() {
__attribute__((visibility("hidden"))) static uint32_t session_pad_type() { __attribute__((visibility("hidden"))) static uint32_t session_pad_type() {
static int type = -1; static int type = -1;
if (type < 0) { if (type < 0) {
if (!env_ready()) return PAD_TYPE_DECK;
const char *env = getenv("FAKE_EVDEV_PAD_TYPE"); const char *env = getenv("FAKE_EVDEV_PAD_TYPE");
type = env && !strcmp(env, "steamcontroller") ? PAD_TYPE_STEAM type = env && !strcmp(env, "steamcontroller") ? PAD_TYPE_STEAM
: env && !strcmp(env, "xbox360") ? PAD_TYPE_XBOX : env && !strcmp(env, "xbox360") ? PAD_TYPE_XBOX
@@ -1470,6 +1494,7 @@ __attribute__((visibility("hidden"))) static uint64_t monotonic_us() {
static bool fake_triton_enabled() { static bool fake_triton_enabled() {
static int enabled = -1; static int enabled = -1;
if (enabled < 0 && !env_ready()) return false;
if (enabled < 0) if (enabled < 0)
enabled = fake_deck_enabled() && getenv("FAKE_EVDEV_TRITON") && atoi(getenv("FAKE_EVDEV_TRITON")) ? 1 : 0; enabled = fake_deck_enabled() && getenv("FAKE_EVDEV_TRITON") && atoi(getenv("FAKE_EVDEV_TRITON")) ? 1 : 0;
return enabled == 1; return enabled == 1;
@@ -2091,6 +2116,7 @@ static_assert(sizeof(TouchRingFile) <= TOUCH_RING_SIZE, "TouchRingFile layout");
__attribute__((visibility("hidden"))) static TouchRingFile *touch_ring() { __attribute__((visibility("hidden"))) static TouchRingFile *touch_ring() {
static TouchRingFile *ring = nullptr; static TouchRingFile *ring = nullptr;
if (!env_ready()) return nullptr;
static std::once_flag once; static std::once_flag once;
std::call_once(once, [] { std::call_once(once, [] {
const char *path = getenv("FAKE_TOUCHCTL_RING"); const char *path = getenv("FAKE_TOUCHCTL_RING");
@@ -2434,6 +2460,7 @@ __attribute__((constructor)) static void start_touch_controller() {
static constexpr long SYSFS_FS_MAGIC = 0x62656572; static constexpr long SYSFS_FS_MAGIC = 0x62656572;
__attribute__((visibility("hidden"))) static const char *deck_listing_dir() { __attribute__((visibility("hidden"))) static const char *deck_listing_dir() {
if (!env_ready()) return nullptr;
static const char *dir = getenv("FAKE_DECK_SYSFS_LISTING"); static const char *dir = getenv("FAKE_DECK_SYSFS_LISTING");
return dir && *dir ? dir : nullptr; return dir && *dir ? dir : nullptr;
} }
@@ -3689,6 +3716,10 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
id.bustype = 0x03; id.bustype = 0x03;
if (made) { if (made) {
id = made->id; id = made->id;
if (steam_pad_as_x360() && id.vendor == STEAM_VIRTUAL_VENDOR_ID && id.product == STEAM_VIRTUAL_PRODUCT_ID) {
id.vendor = X360_VENDOR_ID;
id.product = X360_PRODUCT_ID;
}
} else if (presents_steam_virtual()) { } else if (presents_steam_virtual()) {
id.vendor = STEAM_VIRTUAL_VENDOR_ID; id.vendor = STEAM_VIRTUAL_VENDOR_ID;
id.product = STEAM_VIRTUAL_PRODUCT_ID; id.product = STEAM_VIRTUAL_PRODUCT_ID;
+3 -14
View File
@@ -737,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); 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) { static struct surface *toplevel_by_hwnd(uint32_t hwnd) {
struct surface *s; struct surface *s;
wl_list_for_each(s, &g_toplevels, toplevel_link) wl_list_for_each(s, &g_toplevels, toplevel_link)
@@ -899,7 +894,6 @@ int droiddeck_hud_frame_times(float *out, int len, int64_t *total) {
static uint64_t g_game_frames; static uint64_t g_game_frames;
extern void droiddeck_on_game_surface(const char *window, const char *gpu); extern void droiddeck_on_game_surface(const char *window, const char *gpu);
extern void droiddeck_on_game_frame(void); extern void droiddeck_on_game_frame(void);
extern void droiddeck_on_compositor_frame(void);
extern void droiddeck_on_content_rate(int fps); extern void droiddeck_on_content_rate(int fps);
static int64_t g_cadence_ns; static int64_t g_cadence_ns;
static int64_t g_cadence_frames; static int64_t g_cadence_frames;
@@ -955,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 = s;
g_hud_shm_ns = now; g_hud_shm_ns = now;
g_hud_new = 1; 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) { static void take_pixel(struct surface *s, const uint8_t bgra[4], struct wl_resource *buffer) {
@@ -1032,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)", droiddeck_log("error", "could not import GPU frames from %s (%dx%d, modifier %#llx)",
name, b->width, b->height, (unsigned long long)b->modifier); name, b->width, b->height, (unsigned long long)b->modifier);
} }
if (s != g_hud_surface && !is_steam_client_surface(s) && if (s != g_hud_surface && (b->img || ahb_swapchain_has_ahb(b)) &&
(b->img || ahb_swapchain_has_ahb(b)) &&
(!g_hud_surface || now_ns() - g_hud_alive_ns > 1000000000LL || (!repeat && below_surface(s, g_hud_surface)) || (!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) && (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))) { (int64_t)b->width * b->height >= (int64_t)g_hud_surface->buf_w * g_hud_surface->buf_h))) {
@@ -1058,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)"); : "the compositor's driver could NOT import it (nothing can show it)");
s->hdr_fmt_logged = b->format; 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(); 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(); } 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();
} }
} }
@@ -63,7 +63,6 @@ static jclass g_compositor_cls;
static jmethodID g_on_first_frame; static jmethodID g_on_first_frame;
static jmethodID g_on_game_surface; static jmethodID g_on_game_surface;
static jmethodID g_on_game_frame; static jmethodID g_on_game_frame;
static jmethodID g_on_compositor_frame;
static jmethodID g_on_game_program; static jmethodID g_on_game_program;
static jmethodID g_on_pointer_lock; static jmethodID g_on_pointer_lock;
static jmethodID g_on_clipboard; 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", g_on_game_surface = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameSurface",
"(Ljava/lang/String;Ljava/lang/String;)V"); "(Ljava/lang/String;Ljava/lang/String;)V");
g_on_game_frame = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameFrame", "()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", g_on_game_program = (*env)->GetStaticMethodID(env, g_compositor_cls, "onGameProgram",
"(ILjava/lang/String;)V"); "(ILjava/lang/String;)V");
if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionClear(env); g_on_game_program = NULL; } 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); 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) { void droiddeck_on_refresh_target(int refresh, int frame_rate) {
JNIEnv *env; JNIEnv *env;
if (!g_compositor_cls || !g_on_refresh_target || !(env = thread_env())) return; if (!g_compositor_cls || !g_on_refresh_target || !(env = thread_env())) return;
@@ -21,7 +21,6 @@ class App : Application() {
override fun onCreate() { override fun onCreate() {
super.onCreate() super.onCreate()
com.droiddeck.launcher.runtime.NativeGuest.init(this) com.droiddeck.launcher.runtime.NativeGuest.init(this)
com.droiddeck.launcher.session.Onboarding.attach(this)
Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start() Thread({ runCatching { EnhancedSessionLogShare.cleanupAbandonedStages(this) } }, "diagnostic-stage-cleanup").start()
com.droiddeck.launcher.ui.Themes.loadGradient(this) com.droiddeck.launcher.ui.Themes.loadGradient(this)
com.droiddeck.launcher.ui.BuildWatermark.install(this) com.droiddeck.launcher.ui.BuildWatermark.install(this)
@@ -79,7 +79,7 @@ internal class ComponentsMenu(private val activity: android.app.Activity, privat
checkAgain = null checkAgain = null
checkComponentUpdates(again) checkComponentUpdates(again)
} }
if (notes.isNotEmpty()) Log.i(TAG, notes.joinToString("; ")) if (notes.isNotEmpty()) android.widget.Toast.makeText(activity, notes.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show()
refreshComponents() refreshComponents()
} }
}, "component-updates").start() }, "component-updates").start()
@@ -6,7 +6,6 @@ import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import com.droiddeck.launcher.runtime.DeckyManager import com.droiddeck.launcher.runtime.DeckyManager
import com.droiddeck.launcher.runtime.DeckyStore
import com.droiddeck.launcher.session.SessionState import com.droiddeck.launcher.session.SessionState
import java.io.File import java.io.File
@@ -22,59 +21,6 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val
var deckySupervisor by mutableStateOf(false) var deckySupervisor by mutableStateOf(false)
var deckyPendingZip by mutableStateOf<File?>(null) var deckyPendingZip by mutableStateOf<File?>(null)
var deckyReleaseRequest = 0 var deckyReleaseRequest = 0
var deckyPlugins by mutableStateOf<List<DeckyStore.Installed>>(emptyList())
var deckyStore by mutableStateOf<List<DeckyStore.Plugin>?>(null)
var deckyStoreFailed by mutableStateOf(false)
private var storeRequest = 0
fun refreshPlugins() {
Thread({
val found = DeckyStore.installed(activity)
ui.post { deckyPlugins = found }
}, "decky-plugins").start()
}
fun refreshStore() {
val request = ++storeRequest
deckyStore = null; deckyStoreFailed = false
Thread({
val listing = DeckyStore.fetch()
ui.post {
if (request != storeRequest) return@post
deckyStore = listing.orEmpty(); deckyStoreFailed = listing == null
}
}, "decky-store").start()
}
fun installStorePlugin(plugin: DeckyStore.Plugin) {
val version = plugin.latest ?: return
if (deckyStage != null || SessionState.running || deckyInstalled == null) return
deckyStage = activity.getString(R.string.decky_plugin_starting); deckyPercent = -1
Thread({
val problem = runCatching {
DeckyStore.install(activity, plugin, version) { label, value ->
val binary = DeckyManager.downloadingBinary
ui.post { deckyStage = label; deckyPercent = value; deckyDownloadingBinary = binary }
}
}.getOrElse { error -> activity.getString(R.string.decky_plugin_failed, error.message ?: error.javaClass.simpleName) }
ui.post {
deckyStage = null; deckyPercent = -1; deckyDownloadingBinary = false
android.widget.Toast.makeText(activity, problem ?: activity.getString(R.string.decky_plugin_installed), android.widget.Toast.LENGTH_LONG).show()
refreshPlugins()
}
}, "install-decky-store").start()
}
fun removePlugin(plugin: DeckyStore.Installed) {
if (deckyStage != null || SessionState.running) return
Thread({
val problem = DeckyStore.remove(activity, plugin)
ui.post {
if (problem != null) android.widget.Toast.makeText(activity, problem, android.widget.Toast.LENGTH_LONG).show()
refreshPlugins()
}
}, "remove-decky-plugin").start()
}
fun refreshDecky() { fun refreshDecky() {
val request = ++deckyReleaseRequest val request = ++deckyReleaseRequest
@@ -144,7 +90,6 @@ internal class DeckyMenu(private val activity: android.app.Activity, private val
deckyStage = null; deckyPercent = -1; deckyDownloadingBinary = false deckyStage = null; deckyPercent = -1; deckyDownloadingBinary = false
val message = problem ?: activity.getString(R.string.decky_plugin_installed) val message = problem ?: activity.getString(R.string.decky_plugin_installed)
android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show() android.widget.Toast.makeText(activity, message, android.widget.Toast.LENGTH_LONG).show()
refreshPlugins()
} }
}, "import-decky-plugin").start() }, "import-decky-plugin").start()
} }
@@ -187,7 +187,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var gpuClockPin by mutableStateOf(false) private var gpuClockPin by mutableStateOf(false)
private var prootNoSeccomp by mutableStateOf(false) private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true) private var prootFastPath by mutableStateOf(true)
private var nativeUserland by mutableStateOf(true) private var nativeUserland by mutableStateOf(false)
private var cursorComposite by mutableStateOf(false) private var cursorComposite by mutableStateOf(false)
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME) private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
private var phantomWarning by mutableStateOf<String?>(null) private var phantomWarning by mutableStateOf<String?>(null)
@@ -254,12 +254,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
SessionPrefs.setWifiDiscoveryEnabled(this, WifiDiscovery.permissionGranted(this)) SessionPrefs.setWifiDiscoveryEnabled(this, WifiDiscovery.permissionGranted(this))
refreshWifiDiscovery() refreshWifiDiscovery()
} }
private val bluetoothPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->
if (!granted && !shouldShowRequestPermissionRationale(android.Manifest.permission.BLUETOOTH_CONNECT)) {
integrationSettings(SteamIntegration.appInfo(this))
}
integrationState = readIntegration()
}
private val cameraPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) { private val cameraPermission = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
com.droiddeck.launcher.handtracking.HandTracking.refreshPermission(this) com.droiddeck.launcher.handtracking.HandTracking.refreshPermission(this)
} }
@@ -381,10 +375,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
SteamIntegration.Feature.SHORTCUTS -> { SteamIntegration.Feature.SHORTCUTS -> {
if (integrationState.shortcuts) openShortcutSettings() else installShortcuts() if (integrationState.shortcuts) openShortcutSettings() else installShortcuts()
} }
SteamIntegration.Feature.BLUETOOTH -> {
if (SteamIntegration.bluetoothAllowed(this)) integrationSettings(SteamIntegration.appInfo(this))
else bluetoothPermission.launch(android.Manifest.permission.BLUETOOTH_CONNECT)
}
} }
} }
@@ -637,7 +627,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
} }
private var storageDiagnostics by mutableStateOf(false) private var storageDiagnostics by mutableStateOf(false)
private var storageOptions by mutableStateOf<List<GameStorage.Option>>(emptyList()) private var storageOptions by mutableStateOf<List<GameStorage.Option>>(emptyList())
private var storageFat32 by mutableStateOf(false)
private val pickGameStorage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> private val pickGameStorage = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r ->
if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> setGameStorage(path, GameStorage.labelFor(this, path)) } if (r.resultCode == RESULT_OK) InAppFilePicker.pickedPath(r.data)?.let { path -> setGameStorage(path, GameStorage.labelFor(this, path)) }
} }
@@ -653,7 +642,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private fun addSteamLibrary(path: String) { private fun addSteamLibrary(path: String) {
Thread({ Thread({
val result = SteamLibraries.add(this, path) val result = SteamLibraries.add(this, path)
val fat32 = result is SteamLibraries.AddResult.Added && GameStorage.isFat32(result.entry.path)
ui.post { ui.post {
steamLibraries = SteamLibraries.list(this) steamLibraries = SteamLibraries.list(this)
refreshFoundSteamLibraries() refreshFoundSteamLibraries()
@@ -664,7 +652,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
result is SteamLibraries.AddResult.Added && result.entry.path != path -> 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() 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() }, "steam-library-add").start()
} }
@@ -720,7 +707,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
} }
} }
private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList()) private var secondScreenDisplays by mutableStateOf<List<SecondScreenDisplay>>(emptyList())
private var ownScreen by mutableStateOf<SecondScreenDisplay?>(null)
private var dualDisplayId by mutableStateOf(-1) private var dualDisplayId by mutableStateOf(-1)
private var dualScreenDevice by mutableStateOf(false) private var dualScreenDevice by mutableStateOf(false)
private var dualScreenMode by mutableStateOf(com.droiddeck.launcher.input.DualScreen.MODE_AUTO) private var dualScreenMode by mutableStateOf(com.droiddeck.launcher.input.DualScreen.MODE_AUTO)
@@ -923,31 +909,19 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
LauncherIcon.set(this, style) LauncherIcon.set(this, style)
launcherIcon = LauncherIcon.current(this) launcherIcon = LauncherIcon.current(this)
if (launcherIcon == before) return false 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) startActivity(Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
.setComponent(LauncherIcon.activity(this)) .setComponent(LauncherIcon.activity(this))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
.putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "setup:launcher") .putExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV, "setup:launcher"))
.putExtra(EXTRA_RESTARTED, true))
finishAndRemoveTask() finishAndRemoveTask()
return true
} }
private fun readGameIntent(request: Intent) { private fun readGameIntent(request: Intent) {
request.getStringExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV)?.let { navRequest = it; request.removeExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV) } request.getStringExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV)?.let { navRequest = it; request.removeExtra(com.droiddeck.launcher.stores.download.StoreDownloadService.EXTRA_NAV) }
request.data?.takeIf { it.scheme == "droiddeck" && it.host == "settings" }?.let { uri -> request.data?.takeIf { it.scheme == "droiddeck" && it.host == "settings" }?.let { uri ->
val section = uri.pathSegments.firstOrNull() val section = uri.pathSegments.firstOrNull()
navRequest = if (section in setOf("storage", "sync", "downloads", "decky", "boot-movies")) section navRequest = if (section in setOf("storage", "sync", "downloads")) section
else "settings:" + (com.droiddeck.launcher.ui.SettingsSection.of(section) ?: com.droiddeck.launcher.ui.SettingsSection.OVERVIEW).key else "settings:" + (com.droiddeck.launcher.ui.SettingsSection.of(section) ?: com.droiddeck.launcher.ui.SettingsSection.OVERVIEW).key
request.data = null request.data = null
gameLinkReading = false gameLinkReading = false
@@ -1269,15 +1243,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
super.onCreate(savedInstanceState) super.onCreate(savedInstanceState)
drivers.restartBlocked = ::runtimeChangesBlocked drivers.restartBlocked = ::runtimeChangesBlocked
drivers.loadTpUbwcMode() drivers.loadTpUbwcMode()
val handoff = if (savedInstanceState == null && intent.getBooleanExtra(EXTRA_RESTARTED, false)) LauncherHandoff.take() else null pendingSessionLogExport = savedInstanceState?.getString(KEY_PENDING_SESSION_LOG_EXPORT)?.let(::File)
val saved = savedInstanceState ?: handoff homeChoiceOpen = savedInstanceState?.getBoolean(STATE_HOME_CHOICE_OPEN) == true
pendingSessionLogExport = saved?.getString(KEY_PENDING_SESSION_LOG_EXPORT)?.let(::File) gameSpaceOffered = savedInstanceState?.getBoolean(STATE_GAME_SPACE_OFFERED) == true
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
if (savedInstanceState == null) readIntegrationIntent(intent) if (savedInstanceState == null) readIntegrationIntent(intent)
val shortcutsFilter = android.content.IntentFilter(SteamIntegration.SHORTCUTS_STATUS) val shortcutsFilter = android.content.IntentFilter(SteamIntegration.SHORTCUTS_STATUS)
if (android.os.Build.VERSION.SDK_INT >= 33) registerReceiver(shortcutsInstallStatus, shortcutsFilter, RECEIVER_NOT_EXPORTED) if (android.os.Build.VERSION.SDK_INT >= 33) registerReceiver(shortcutsInstallStatus, shortcutsFilter, RECEIVER_NOT_EXPORTED)
@@ -1377,7 +1345,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
integrationFocus = integrationFocus, integrationFocus = integrationFocus,
androidApps = androidApps, androidApps = androidApps,
secondScreenDisplays = secondScreenDisplays, secondScreenDisplays = secondScreenDisplays,
ownScreen = ownScreen,
dualScreen = dualDisplayId >= 0 && com.droiddeck.launcher.ui.DualScreenPanel.available, dualScreen = dualDisplayId >= 0 && com.droiddeck.launcher.ui.DualScreenPanel.available,
dualScreenDevice = dualScreenDevice, dualScreenDevice = dualScreenDevice,
dualScreenMode = dualScreenMode, dualScreenMode = dualScreenMode,
@@ -1425,9 +1392,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
), ),
FrontEndActions( FrontEndActions(
onPlay = { playSteam() }, onPlay = { playSteam() },
onQueuePlaySteam = {
queuedLaunch.queue(Intent(this, SessionActivity::class.java).putExtra(SessionActivity.EXTRA_STEAMVR, false), System.currentTimeMillis())
},
onPlaySteamVr = { playSteamVr() }, onPlaySteamVr = { playSteamVr() },
onSteamUrl = { url -> onSteamUrl = { url ->
if (!SessionState.running) startSession( if (!SessionState.running) startSession(
@@ -1567,7 +1531,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onAddonImport = { sg, target -> importAddons(sg.name, target) }, onAddonImport = { sg, target -> importAddons(sg.name, target) },
onAddonDelete = { target, name -> onAddonDelete = { target, name ->
saveAction(getString(R.string.main_addons_deleting, name)) { saveAction(getString(R.string.main_addons_deleting, name)) {
com.droiddeck.launcher.ui.deleteAddon(this, target, name) com.droiddeck.launcher.runtime.WowAddons.delete(target, name)
getString(R.string.main_addons_deleted, name) getString(R.string.main_addons_deleted, name)
} }
}, },
@@ -1702,7 +1666,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
onLanguage = { tag -> onLanguage = { tag ->
if (tag != com.droiddeck.launcher.core.AppLanguage.chosen(this)) { if (tag != com.droiddeck.launcher.core.AppLanguage.chosen(this)) {
com.droiddeck.launcher.core.AppLanguage.setChosen(this, tag) com.droiddeck.launcher.core.AppLanguage.setChosen(this, tag)
restartLauncher() recreate()
} }
}, },
onAppScale = { percent -> onAppScale = { percent ->
@@ -1799,6 +1763,31 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
}, },
onRefreshPhantomStatus = { refreshPhantomStatus() }, onRefreshPhantomStatus = { refreshPhantomStatus() },
onOpenDeveloperOptions = { displayId -> openDeveloperOptions(displayId) }, 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 -> onSetPhantomProcessLimit = { enabled, complete ->
Thread({ Thread({
val result = runCatching { WirelessAdbFix.setUsingSavedPairing(this@FrontEndActivity, enabled) } val result = runCatching { WirelessAdbFix.setUsingSavedPairing(this@FrontEndActivity, enabled) }
@@ -1815,14 +1804,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() 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 = { onShowPhantomGate = {
refreshPhantomStatus() refreshPhantomStatus()
showPhantomGate = true showPhantomGate = true
}, },
onStartWirelessAdbPairing = { enabled -> WirelessAdbPairingService.start(this, enabled) }, onStartWirelessAdbPairing = { WirelessAdbPairingService.start(this) },
onStartPairingGuide = { displayId, toggleOnly -> PairingGuideActivity.start(this, displayId, toggleOnly) }, 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(), updates = updates.actions(),
controller = ControllerActions( controller = ControllerActions(
onMapping = { showPerformance = false; showComponents = false; showMapping = true }, onMapping = { showPerformance = false; showComponents = false; showMapping = true },
@@ -1918,11 +1911,10 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
!SessionPrefs.allFilesAsked(this) !SessionPrefs.allFilesAsked(this)
if (savedInstanceState == null) { if (savedInstanceState == null) {
if (!askAllFiles) ui.post { startSteamAtStartupIfEnabled(cold = true) } if (!askAllFiles) ui.post { startSteamAtStartupIfEnabled(cold = true) }
} } else {
saved?.let { state -> restoreCompatLaunch(savedInstanceState)
restoreCompatLaunch(state) pendingSwitch = savedIntent(savedInstanceState, KEY_PENDING_SWITCH)
pendingSwitch = savedIntent(state, KEY_PENDING_SWITCH) savedIntent(savedInstanceState, KEY_SWITCHING_TO)?.let { awaitSessionEnd(it, savedInstanceState.getLong(KEY_SWITCH_DEADLINE)) }
savedIntent(state, KEY_SWITCHING_TO)?.let { awaitSessionEnd(it, state.getLong(KEY_SWITCH_DEADLINE)) }
} }
val wanted = ArrayList<String>() val wanted = ArrayList<String>()
@@ -1975,12 +1967,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var soundtrackLaunch = false private var soundtrackLaunch = false
// A restarted launcher starts before the old one stops, so each clears the hooks only if they are still its own.
private val libraryHook: () -> Unit = { refreshAddedGames(); refresh() }
private val battleNetHook: (List<String>) -> Unit = { args -> openBattleNet(args) }
private fun startSteamAtStartupIfEnabled(cold: Boolean = false) { 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 (intent.action != Intent.ACTION_MAIN && !(cold && intent.action == null)) return
if (isFinishing || isDestroyed) return if (isFinishing || isDestroyed) return
when (SessionPrefs.startupSession(this)) { when (SessionPrefs.startupSession(this)) {
@@ -2007,7 +1995,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
} }
private fun startSteamSession(steamVr: Boolean = false) { 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") @Suppress("OVERRIDE_DEPRECATION")
@@ -2155,8 +2143,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this) homePage = com.droiddeck.launcher.core.AppUiPrefs.homePage(this)
refreshWifiDiscovery() refreshWifiDiscovery()
com.droiddeck.launcher.stores.StoresState.refresh(this) com.droiddeck.launcher.stores.StoresState.refresh(this)
com.droiddeck.launcher.stores.StoresState.libraryListener = libraryHook com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() }
com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = battleNetHook com.droiddeck.launcher.stores.battlenet.BattleNetClient.opener = { args -> openBattleNet(args) }
com.droiddeck.launcher.ui.Motion.refresh(this) com.droiddeck.launcher.ui.Motion.refresh(this)
com.droiddeck.launcher.ui.QuitFlood.take()?.let { c -> com.droiddeck.launcher.ui.QuitFlood.take()?.let { c ->
returning = ReturningFlood(c, com.droiddeck.launcher.ui.LaunchOrigin.takeReturn()) returning = ReturningFlood(c, com.droiddeck.launcher.ui.LaunchOrigin.takeReturn())
@@ -2178,7 +2166,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
if (!OfflineMode.enabled(this)) { if (!OfflineMode.enabled(this)) {
val updated = runCatching { ComponentUpdater.ensure(this, force = false) } val updated = runCatching { ComponentUpdater.ensure(this, force = false) }
.onFailure { android.util.Log.w("ComponentUpdater", "automatic component updates", it) }.getOrDefault(emptyList()) .onFailure { android.util.Log.w("ComponentUpdater", "automatic component updates", it) }.getOrDefault(emptyList())
if (updated.isNotEmpty()) android.util.Log.i("ComponentUpdater", updated.joinToString("; ")) if (updated.isNotEmpty()) ui.post {
android.widget.Toast.makeText(this, updated.joinToString("\n"), android.widget.Toast.LENGTH_LONG).show()
}
} }
ui.post { ui.post {
componentsQueueBusy = false componentsQueueBusy = false
@@ -2227,17 +2217,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
override fun onSaveInstanceState(outState: Bundle) { override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState) super.onSaveInstanceState(outState)
saveLauncherState(outState)
}
private fun saveLauncherState(outState: Bundle) {
outState.putBoolean(STATE_HOME_CHOICE_OPEN, homeChoiceOpen) outState.putBoolean(STATE_HOME_CHOICE_OPEN, homeChoiceOpen)
outState.putBoolean(STATE_GAME_SPACE_OFFERED, gameSpaceOffered) outState.putBoolean(STATE_GAME_SPACE_OFFERED, gameSpaceOffered)
pendingSessionLogExport?.let { outState.putString(KEY_PENDING_SESSION_LOG_EXPORT, it.absolutePath) } pendingSessionLogExport?.let { outState.putString(KEY_PENDING_SESSION_LOG_EXPORT, it.absolutePath) }
queuedLaunch.launch?.let {
outState.putParcelable(STATE_PENDING_GATE_LAUNCH, it)
outState.putLong(STATE_PENDING_GATE_LAUNCH_AT, queuedLaunch.queuedAt)
}
if (slowUsbNever) SessionPrefs.setSlowUsbWarningOff(this) if (slowUsbNever) SessionPrefs.setSlowUsbWarningOff(this)
saveCompatLaunch(outState) saveCompatLaunch(outState)
pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) } pendingSwitch?.let { outState.putParcelable(KEY_PENDING_SWITCH, it) }
@@ -2264,8 +2246,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
} }
override fun onDestroy() { 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() triggerKeys.cancel()
gameLaunchRequest.incrementAndGet() gameLaunchRequest.incrementAndGet()
cancelCompatLaunch() cancelCompatLaunch()
@@ -2287,8 +2267,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
getSystemService(android.content.pm.LauncherApps::class.java).unregisterCallback(packageCallback) getSystemService(android.content.pm.LauncherApps::class.java).unregisterCallback(packageCallback)
HomeWidgets.stopListening(this) HomeWidgets.stopListening(this)
ui.removeCallbacks(mediaRefresh) ui.removeCallbacks(mediaRefresh)
if (com.droiddeck.launcher.stores.StoresState.libraryListener === libraryHook) com.droiddeck.launcher.stores.StoresState.libraryListener = null 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.battlenet.BattleNetClient.opener = null
displayManager.unregisterDisplayListener(secondScreenDisplayListener) displayManager.unregisterDisplayListener(secondScreenDisplayListener)
com.droiddeck.launcher.input.DualScreen.unwatchTaken(bottomScreenListener) com.droiddeck.launcher.input.DualScreen.unwatchTaken(bottomScreenListener)
getSystemService(android.hardware.input.InputManager::class.java)?.unregisterInputDeviceListener(secondScreenTouchListener) getSystemService(android.hardware.input.InputManager::class.java)?.unregisterInputDeviceListener(secondScreenTouchListener)
@@ -2328,9 +2308,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 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) dualScreenMode = SessionPrefs.dualScreenMode(this)
secondScreenDisplays = SecondScreenDisplays.available(displayManager, ownDisplayId) 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 dualScreenDevice = com.droiddeck.launcher.input.DualScreen.anyDisplay(displayManager, ownDisplayId) != null
dualScreenSessions = SessionPrefs.dualScreenSessionMode(this) dualScreenSessions = SessionPrefs.dualScreenSessionMode(this)
dualScreenControls = SessionPrefs.dualScreenSessionControls(this) dualScreenControls = SessionPrefs.dualScreenSessionControls(this)
@@ -2351,24 +2328,17 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private fun launchAndroidApp(app: HomeApp.LaunchableApp, displayId: Int?) { private fun launchAndroidApp(app: HomeApp.LaunchableApp, displayId: Int?) {
val onOwnScreen = displayId == null || displayId == (display?.displayId ?: Display.DEFAULT_DISPLAY) val onOwnScreen = displayId == null || displayId == (display?.displayId ?: Display.DEFAULT_DISPLAY)
if (onOwnScreen) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, true) if (onOwnScreen) com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, true)
val open = { try {
try { HomeApp.launch(this, app, displayId)
HomeApp.launch(this, app, displayId) } catch (_: Exception) {
} catch (_: Exception) { com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false)
com.droiddeck.launcher.ui.DualScreenPanel.yieldTo(taskId, false) val label = secondScreenDisplays.firstOrNull { it.id == displayId }?.label
val label = secondScreenDisplays.firstOrNull { it.id == displayId }?.label val message = when {
val message = when { displayId == null || displayId == Display.DEFAULT_DISPLAY -> getString(R.string.android_app_open_failed_primary, app.label)
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)
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)
else -> getString(R.string.android_app_open_failed_display, app.label, displayId)
}
android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show()
} }
} android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show()
if (displayId != null && displayId == com.droiddeck.launcher.ui.DualScreenPanel.shownOn) {
com.droiddeck.launcher.ui.DualScreenPanel.makeRoomForApp(this, displayId, open)
} else {
open()
} }
} }
@@ -2694,7 +2664,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
mic = if (mode == SessionService.MODE_STEAM) mic else null, mic = if (mode == SessionService.MODE_STEAM) mic else null,
gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null, gameStorage = if (mode == SessionService.MODE_STEAM) gameStorage else null,
storageOptions = storageOptions, storageOptions = storageOptions,
storageFat32 = storageFat32,
steamLibraries = steamLibraries, steamLibraries = steamLibraries,
foundSteamLibraries = foundSteamLibraries, foundSteamLibraries = foundSteamLibraries,
allFilesAccessMissing = allFilesAccessMissing, allFilesAccessMissing = allFilesAccessMissing,
@@ -2721,7 +2690,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
deckyChecking = decky.deckyChecking, deckyStage = decky.deckyStage, deckyPercent = decky.deckyPercent, deckyChecking = decky.deckyChecking, deckyStage = decky.deckyStage, deckyPercent = decky.deckyPercent,
deckyDownloadingBinary = decky.deckyDownloadingBinary, deckyDownloadingBinary = decky.deckyDownloadingBinary,
deckyEnabled = decky.deckySupervisor, deckySessionRunning = SessionState.running, deckyEnabled = decky.deckySupervisor, deckySessionRunning = SessionState.running,
deckyPlugins = decky.deckyPlugins, deckyStore = decky.deckyStore, deckyStoreFailed = decky.deckyStoreFailed,
), ),
ModeSettingsActions( ModeSettingsActions(
onIntegration = ::configureIntegration, onIntegration = ::configureIntegration,
@@ -2832,9 +2800,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
decky.deckyInstalled = null decky.deckyInstalled = null
decky.deckySupervisor = false decky.deckySupervisor = false
}, },
onDeckyStoreRefresh = { decky.refreshStore() },
onDeckyStoreInstall = { plugin -> decky.installStorePlugin(plugin) },
onDeckyRemove = { plugin -> decky.removePlugin(plugin) },
onPickDeckyPluginZip = { onPickDeckyPluginZip = {
pickDeckyPluginZip.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, getString(R.string.main_pick_decky_zip))) pickDeckyPluginZip.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, getString(R.string.main_pick_decky_zip)))
}, },
@@ -3117,17 +3082,14 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
Thread({ Thread({
drivers.refreshDrivers() drivers.refreshDrivers()
val storage = GameStorage.options(this) 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 deckyInstalled = if (mode == SessionService.MODE_STEAM) DeckyManager.installed(this) else null
val deckySupervisor = mode == SessionService.MODE_STEAM && DeckyManager.supervisorEnabled(this) val deckySupervisor = mode == SessionService.MODE_STEAM && DeckyManager.supervisorEnabled(this)
ui.post { ui.post {
storageOptions = storage storageOptions = storage
storageFat32 = fat32
if (mode == SessionService.MODE_STEAM) { if (mode == SessionService.MODE_STEAM) {
decky.deckyInstalled = deckyInstalled decky.deckyInstalled = deckyInstalled
decky.deckySupervisor = deckySupervisor decky.deckySupervisor = deckySupervisor
decky.refreshDecky() decky.refreshDecky()
decky.refreshPlugins()
} }
fetchAddedGameArt() fetchAddedGameArt()
} }
@@ -3144,8 +3106,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
} }
SessionPrefs.setGameStorage(this, path, label) SessionPrefs.setGameStorage(this, path, label)
gameStorage = path 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() checkUsbLink()
if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries() if (settingsMode == SessionService.MODE_STEAM) refreshFoundSteamLibraries()
} }
@@ -3244,7 +3204,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this) bridgeProtonDxvk = SessionPrefs.bridgeProtonDxvk(this)
removalPending = LinuxRuntimeInstaller.hasRemovalPending(this) removalPending = LinuxRuntimeInstaller.hasRemovalPending(this)
ui.post { autoUpdateRuntime() } ui.post { autoUpdateRuntime() }
Thread({ com.droiddeck.launcher.session.Onboarding.recheck(this) }, "onboarding-recheck").start()
frameGenLabel = FrameGen.label(this) frameGenLabel = FrameGen.label(this)
romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() } romsDir = SessionPrefs.romsDir(this).takeIf { it.isNotEmpty() }
logsEnabled = SessionPrefs.logsEnabled(this) logsEnabled = SessionPrefs.logsEnabled(this)
@@ -3370,7 +3329,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
install(release) 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 (busy || LinuxRuntimeInstaller.isBusy()) return false
if (SessionState.installing != null && !SessionState.running) { if (SessionState.installing != null && !SessionState.running) {
android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show() android.widget.Toast.makeText(this, R.string.main_wait_desktop_install, android.widget.Toast.LENGTH_SHORT).show()
@@ -3382,7 +3341,6 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
} }
refreshPhantomStatus() refreshPhantomStatus()
if (steamSession && PhantomProcessLimit.blocksSteam(phantomProcessStatus)) { if (steamSession && PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
if (queueIfBlocked) queuedLaunch.queue(intent, System.currentTimeMillis())
showPhantomGate = true showPhantomGate = true
return false return false
} }
@@ -3392,64 +3350,8 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
return true 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() { private fun refreshPhantomStatus() {
phantomProcessStatus = PhantomProcessLimit.read(this) phantomProcessStatus = PhantomProcessLimit.read(this)
if (queuedLaunch.launch != null && !PhantomProcessLimit.blocksSteam(phantomProcessStatus)) showPhantomGate = false
queuedLaunchRunner.poke()
adbPaired = WirelessAdbFix.hasSavedPairing(this) adbPaired = WirelessAdbFix.hasSavedPairing(this)
phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) { phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
getString( getString(
@@ -3461,7 +3363,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private fun openDeveloperOptions(displayId: Int?) { private fun openDeveloperOptions(displayId: Int?) {
val highlight = if (PhantomProcessLimit.hasDeveloperToggle() && 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) val intent = Intent(android.provider.Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.apply { if (highlight != null) putExtra(":settings:fragment_args_key", highlight) } .apply { if (highlight != null) putExtra(":settings:fragment_args_key", highlight) }
@@ -3507,7 +3409,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
com.droiddeck.launcher.ui.Motion.refresh(this) com.droiddeck.launcher.ui.Motion.refresh(this)
com.droiddeck.launcher.ui.DeveloperTools.load(this) com.droiddeck.launcher.ui.DeveloperTools.load(this)
com.droiddeck.launcher.ui.NavTabs.load(this) com.droiddeck.launcher.ui.NavTabs.load(this)
if (!switchLauncherIcon(LauncherIcon.DARK)) restartLauncher() if (!switchLauncherIcon(LauncherIcon.DARK)) recreate()
} }
}, "reset-settings").start() }, "reset-settings").start()
} }
@@ -3523,24 +3425,18 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private fun install(release: LinuxRuntimeInstaller.Release) { private fun install(release: LinuxRuntimeInstaller.Release) {
com.droiddeck.launcher.runtime.RuntimeInstallService.start(this, release) com.droiddeck.launcher.runtime.RuntimeInstallService.start(this, release)
followRuntimeOperation(onboarding = true) { listener -> LinuxRuntimeInstaller.install(this, release, listener) } followRuntimeOperation { listener -> LinuxRuntimeInstaller.install(this, release, listener) }
} }
private fun followRuntimeOperation(onboarding: Boolean = false, run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) { private fun followRuntimeOperation(run: (LinuxRuntimeInstaller.ProgressListener) -> Boolean?) {
busy = true busy = true
failed = false failed = false
stage = getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else if (LinuxRuntimeInstaller.isRemoving()) R.string.main_removing_runtime else R.string.store_starting) stage = getString(if (LinuxRuntimeInstaller.isMaintaining()) R.string.desktop_removing else if (LinuxRuntimeInstaller.isRemoving()) R.string.main_removing_runtime else R.string.store_starting)
percent = -1 percent = -1
Thread({ Thread({
val ok = run(LinuxRuntimeInstaller.ProgressListener { s, p -> val ok = run(LinuxRuntimeInstaller.ProgressListener { s, p ->
if (onboarding) com.droiddeck.launcher.session.Onboarding.report(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME, s, p)
ui.post { stage = s; percent = p } ui.post { stage = s; percent = p }
}) })
if (onboarding) {
if (ok == false) com.droiddeck.launcher.session.Onboarding.fail(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME, LinuxRuntimeInstaller.removalError() ?: "")
else com.droiddeck.launcher.session.Onboarding.finish(com.droiddeck.launcher.session.Onboarding.Step.RUNTIME)
}
com.droiddeck.launcher.session.Onboarding.recheck(this)
ui.post { ui.post {
busy = false busy = false
if (ok != null) failed = !ok if (ok != null) failed = !ok
@@ -3549,7 +3445,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
} }
refresh() refresh()
com.droiddeck.launcher.agent.AgentHost.refresh(this) com.droiddeck.launcher.agent.AgentHost.refresh(this)
if (ok == true && LinuxRuntime.isInstalled(this)) { protons.checkUpdates(); protons.ensureSteamClient() } if (ok == true && LinuxRuntime.isInstalled(this)) protons.checkUpdates()
} }
}, "runtime-operation").start() }, "runtime-operation").start()
} }
@@ -3560,10 +3456,9 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
if (installed != null) com.droiddeck.launcher.runtime.RuntimeAutoUpdate.seed(this) if (installed != null) com.droiddeck.launcher.runtime.RuntimeAutoUpdate.seed(this)
if (release.version == installed) return if (release.version == installed) return
if (installed == null && (OfflineMode.enabled(this) || !com.droiddeck.launcher.core.DeviceSupport.canDraw(this) || if (installed == null && (OfflineMode.enabled(this) || !com.droiddeck.launcher.core.DeviceSupport.canDraw(this) ||
!com.droiddeck.launcher.frontend.AutoComponents.online(this) || com.droiddeck.launcher.frontend.AutoComponents.firstRunHeldBack(this))) return !com.droiddeck.launcher.frontend.AutoComponents.online(this) || com.droiddeck.launcher.frontend.AutoComponents.unfavourable(this))) return
if (com.droiddeck.launcher.runtime.RuntimeAutoUpdate.claim(this, installed, release.version)) { if (com.droiddeck.launcher.runtime.RuntimeAutoUpdate.claim(this, installed, release.version)) {
Log.i(TAG, "runtime: installing ${release.version} over ${installed ?: "nothing"} by itself") Log.i(TAG, "runtime: installing ${release.version} over ${installed ?: "nothing"} by itself")
if (installed == null) protons.prefetchOwn()
install(release) install(release)
} }
} }
@@ -3580,13 +3475,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
} }
companion object { 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_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 KEY_PENDING_SESSION_LOG_EXPORT = "pending_session_log_export"
private const val STATE_GAME_SPACE_OFFERED = "game_space_offered" private const val STATE_GAME_SPACE_OFFERED = "game_space_offered"
private const val TAG = "MainActivity" private const val TAG = "MainActivity"
@@ -118,18 +118,12 @@ object HomeWidgets {
if (live.size != parsed.size) save(context) if (live.size != parsed.size) save(context)
} }
private val listeners: MutableSet<Any> = java.util.Collections.newSetFromMap(java.util.IdentityHashMap())
fun startListening(context: Context) { fun startListening(context: Context) {
listeners.add(context)
load(context) load(context)
runCatching { host(context).startListening() } 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) { fun stopListening(context: Context) {
listeners.remove(context)
if (listeners.isNotEmpty()) return
runCatching { host(context).stopListening() } 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 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() { override fun onResume() {
super.onResume() super.onResume()
if (!launchPending) return if (!launchPending) return
@@ -8,9 +8,7 @@ import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import com.droiddeck.launcher.session.ExperimentalProtons import com.droiddeck.launcher.session.ExperimentalProtons
import com.droiddeck.launcher.session.Onboarding
import com.droiddeck.launcher.session.ProtonExtras import com.droiddeck.launcher.session.ProtonExtras
import com.droiddeck.launcher.session.SteamClientPrefetch
import com.droiddeck.launcher.ui.ProtonRow import com.droiddeck.launcher.ui.ProtonRow
import com.droiddeck.launcher.session.SessionState import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.session.SessionPhase import com.droiddeck.launcher.session.SessionPhase
@@ -62,15 +60,10 @@ internal class ProtonMenu(
Thread({ Thread({
val problem = runCatching { val problem = runCatching {
installer(tool) { label, value -> installer(tool) { label, value ->
if (tool.id == ProtonExtras.OWN) Onboarding.report(Onboarding.Step.PROTON, label, value)
ui.post { protonStage = label; protonPercent = value } ui.post { protonStage = label; protonPercent = value }
} }
}.getOrElse { it.message ?: it.javaClass.simpleName } }.getOrElse { it.message ?: it.javaClass.simpleName }
if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false) if (problem == null && !automatic && tool.id == ProtonExtras.OWN) ProtonExtras.setDeclined(activity, false)
if (tool.id == ProtonExtras.OWN) {
if (problem == null) Onboarding.finish(Onboarding.Step.PROTON) else Onboarding.fail(Onboarding.Step.PROTON, problem)
Onboarding.recheck(activity)
}
ui.post { ui.post {
protonProblem = problem protonProblem = problem
protonBusyId = null protonBusyId = null
@@ -156,7 +149,7 @@ internal class ProtonMenu(
fun refreshProtons() { fun refreshProtons() {
refreshExperimental() refreshExperimental()
protonRows = ProtonExtras.tools.map { protonRows = ProtonExtras.offered(activity).map {
val all = ProtonExtras.installedAll(activity, it) val all = ProtonExtras.installedAll(activity, it)
ProtonRow(it.id, it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it)) ProtonRow(it.id, it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it))
} }
@@ -177,46 +170,16 @@ internal class ProtonMenu(
Operation.checking.set(false) Operation.checking.set(false)
} }
ensureAutoUpdates() ensureAutoUpdates()
ensureSteamClient()
} }
if (!published) Operation.checking.set(false) if (!published) Operation.checking.set(false)
}, "proton-updates").start() }, "proton-updates").start()
} }
/** Downloads the DroidDeck Proton archive while the runtime installs; the install step later finds it whole. */
fun prefetchOwn() {
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
if (ProtonExtras.declined(activity) || ProtonExtras.installedAll(activity, tool).isNotEmpty() ||
ProtonExtras.installInProgress || !AutoComponents.online(activity) || AutoComponents.firstRunHeldBack(activity)) return
Thread({
val problem = runCatching {
ProtonExtras.prefetch(activity, tool) { label, value -> Onboarding.report(Onboarding.Step.PROTON, label, value) }
}.getOrElse { it.message ?: it.javaClass.simpleName }
if (problem == null) Onboarding.finish(Onboarding.Step.PROTON) else Onboarding.fail(Onboarding.Step.PROTON, problem)
Onboarding.recheck(activity)
ui.post { ensureAutoUpdates() }
}, "proton-prefetch").start()
}
/** Fetches Steam's client in the background once the runtime exists, so the first Play does not wait for it. */
fun ensureSteamClient() {
if (activity.isFinishing || activity.isDestroyed || !idle() || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) || !LinuxRuntime.isInstalled(activity) ||
!AutoComponents.online(activity) || AutoComponents.firstRunHeldBack(activity) || SteamClientPrefetch.running()) return
SteamClientPrefetch.start(
activity,
{ mb -> activity.getString(if (mb > 0) R.string.onboarding_steam_downloading_mb else R.string.onboarding_steam_downloading, mb) },
activity.getString(R.string.onboarding_steam_failed),
)
}
internal fun ensureAutoUpdates(now: Long = System.currentTimeMillis()) { internal fun ensureAutoUpdates(now: Long = System.currentTimeMillis()) {
if (activity.isFinishing || activity.isDestroyed || !idle() || protonBusyId != null || if (activity.isFinishing || activity.isDestroyed || !idle() || protonBusyId != null ||
ProtonExtras.installInProgress || ProtonExtras.prefetching || SessionState.running || LinuxRuntimeInstaller.isBusy() || ProtonExtras.installInProgress || SessionState.running || LinuxRuntimeInstaller.isBusy() ||
SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) || SessionState.phase !in setOf(SessionPhase.IDLE, SessionPhase.FAILED) ||
!LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity)) return !LinuxRuntime.isInstalled(activity) || !AutoComponents.online(activity) || AutoComponents.unfavourable(activity)) return
val firstInstall = !ProtonExtras.declined(activity) && ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).isEmpty()
if (if (firstInstall) AutoComponents.firstRunHeldBack(activity) else AutoComponents.unfavourable(activity)) return
if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) { if (ProtonExtras.installedAll(activity, ProtonExtras.tools.first { it.id == ProtonExtras.OWN }).size > 1) {
protonBusyId = ProtonExtras.OWN protonBusyId = ProtonExtras.OWN
protonProblem = null protonProblem = null
@@ -154,8 +154,6 @@ import com.droiddeck.launcher.session.ComponentsManager
import com.droiddeck.launcher.session.LatestRequestCoordinator import com.droiddeck.launcher.session.LatestRequestCoordinator
import com.droiddeck.launcher.ui.SessionDrawerPage import com.droiddeck.launcher.ui.SessionDrawerPage
import com.droiddeck.launcher.ui.sessionDrawerPages import com.droiddeck.launcher.ui.sessionDrawerPages
import com.droiddeck.launcher.ui.strip
import com.droiddeck.launcher.ui.tabFor
import com.droiddeck.launcher.ui.step import com.droiddeck.launcher.ui.step
import kotlin.math.abs import kotlin.math.abs
@@ -596,7 +594,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var backHold by mutableStateOf(true) private var backHold by mutableStateOf(true)
private var dockedMenuController by mutableStateOf(false) private var dockedMenuController by mutableStateOf(false)
private var sessionOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE) private var sessionOrientation by mutableStateOf(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE)
private var dualScreenSessionMode by mutableStateOf(com.droiddeck.launcher.input.DualScreen.MODE_AUTO)
private var backActionsInverted by mutableStateOf(false) private var backActionsInverted by mutableStateOf(false)
private var backDoubleTapMs by mutableStateOf(500) private var backDoubleTapMs by mutableStateOf(500)
private var lowLatency by mutableStateOf(true) private var lowLatency by mutableStateOf(true)
@@ -850,8 +847,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
SessionState.bottomMenu = false SessionState.bottomMenu = false
SessionState.secondScreenProvisional = false SessionState.secondScreenProvisional = false
SessionState.secondScreenAutomatic = false SessionState.secondScreenAutomatic = false
SessionState.gameOnBottom = SessionPrefs.dualScreenSessionMode(this) == com.droiddeck.launcher.input.DualScreen.MODE_SWAPPED SessionState.gameOnBottom = false
gameOnBottom = SessionState.gameOnBottom gameOnBottom = false
} }
if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) { if (!SessionState.running && SessionState.phase in setOf(SessionPhase.IDLE, SessionPhase.FAILED)) {
SessionState.program = intent.getStringExtra(SessionService.EXTRA_PROGRAM) SessionState.program = intent.getStringExtra(SessionService.EXTRA_PROGRAM)
@@ -936,6 +933,11 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
} }
SteamControllerBle.listener = { uiHandler.post { updatePadMotion(); refreshControls() } } SteamControllerBle.listener = { uiHandler.post { updatePadMotion(); refreshControls() } }
steamController = SteamControllerBle(this, inputRouter).also { it.start() } steamController = SteamControllerBle(this, inputRouter).also { it.start() }
if (Build.VERSION.SDK_INT >= 31 && checkSelfPermission(BLUETOOTH_CONNECT) != android.content.pm.PackageManager.PERMISSION_GRANTED &&
!SessionPrefs.bluetoothAsked(this)) {
SessionPrefs.setBluetoothAsked(this)
requestPermissions(arrayOf(BLUETOOTH_CONNECT), REQUEST_BLUETOOTH)
}
padMotion = com.droiddeck.launcher.input.PadMotion(this) { padMotion = com.droiddeck.launcher.input.PadMotion(this) {
@Suppress("DEPRECATION") @Suppress("DEPRECATION")
(if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0 (if (Build.VERSION.SDK_INT >= 30) display else windowManager.defaultDisplay)?.rotation ?: android.view.Surface.ROTATION_0
@@ -1533,8 +1535,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
fexPreset = fexPreset, fexPreset = fexPreset,
secondScreenMode = secondScreenMode, secondScreenMode = secondScreenMode,
secondScreenNone = !bottomOutputActive && !dockDrawer(), secondScreenNone = !bottomOutputActive && !dockDrawer(),
dualScreenMode = dualScreenSessionMode,
onDualScreenMode = ::chooseDualScreenSessionMode,
gameOnBottom = bottomOutputActive, gameOnBottom = bottomOutputActive,
gameSwapAvailable = bottomSwapAvailable, gameSwapAvailable = bottomSwapAvailable,
gameSwapBuiltIn = !::displayManager.isInitialized || displayManager.getDisplay(selectedSecondScreenDisplay) gameSwapBuiltIn = !::displayManager.isInitialized || displayManager.getDisplay(selectedSecondScreenDisplay)
@@ -1545,10 +1545,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
secondScreenDisplays = secondScreenDisplays, secondScreenDisplays = secondScreenDisplays,
selectedSecondScreenDisplay = selectedSecondScreenDisplay, selectedSecondScreenDisplay = selectedSecondScreenDisplay,
onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() }, onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() },
onHudOnlyDuringGame = { on ->
SessionPrefs.setHudOnlyDuringGame(this@SessionActivity, on)
hud.refresh()
},
onGpuClockPin = { on -> onGpuClockPin = { on ->
SessionPrefs.setGpuClockPin(this@SessionActivity, on) SessionPrefs.setGpuClockPin(this@SessionActivity, on)
gpuClockPin = on gpuClockPin = on
@@ -2663,7 +2659,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
backHold = SessionPrefs.backHold(this) backHold = SessionPrefs.backHold(this)
dockedMenuController = SessionPrefs.dockedMenuController(this) dockedMenuController = SessionPrefs.dockedMenuController(this)
sessionOrientation = SessionPrefs.orientation(this) sessionOrientation = SessionPrefs.orientation(this)
dualScreenSessionMode = SessionPrefs.dualScreenSessionMode(this)
backActionsInverted = SessionPrefs.backActionsInverted(this) backActionsInverted = SessionPrefs.backActionsInverted(this)
physicalShortcuts.bindings = PhysicalShortcuts.read(this) physicalShortcuts.bindings = PhysicalShortcuts.read(this)
backDoubleTapMs = SessionPrefs.backDoubleTapMs(this) backDoubleTapMs = SessionPrefs.backDoubleTapMs(this)
@@ -2851,17 +2846,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (!SessionState.running) { if (!SessionState.running) {
SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting") SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting")
} }
val runtimeDir = File(filesDir, ".wayland-rt").apply { mkdirs() } val output = CompositorHost.prepare(this)
FileUtils.copyAsset(this, "wayland/keymap.xkb", File(runtimeDir, "keymap.xkb"))
com.droiddeck.launcher.input.VrControllers.publish(this)
val turnip = TurnipDriver(this)
com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "surface.driver-setup")
if (!CompositorHost.isStarted) {
CompositorHost.displayChoice = SessionPrefs.androidDriver(this)
com.droiddeck.launcher.gpu.AutoDriverTrial.displayStarting(this, SessionPrefs.androidDriver(this))
}
val driverId = if (CompositorHost.isStarted) null else turnip.install()
val previous = SessionState.outputSize val previous = SessionState.outputSize
val live = windowOutputSize(holder.surfaceFrame.width(), holder.surfaceFrame.height()) val live = windowOutputSize(holder.surfaceFrame.width(), holder.surfaceFrame.height())
@@ -2888,15 +2873,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
pushCardboard(activeCardboard) pushCardboard(activeCardboard)
WaylandCompositor.nativeSetCardboardPoseFile(File(filesDir, ".wayland-rt/droiddeck-headpose").path) WaylandCompositor.nativeSetCardboardPoseFile(File(filesDir, ".wayland-rt/droiddeck-headpose").path)
com.droiddeck.launcher.glasses.SpatialTracking.attachPublisher(File(filesDir, ".wayland-rt/droiddeck-spatialpose").path) com.droiddeck.launcher.glasses.SpatialTracking.attachPublisher(File(filesDir, ".wayland-rt/droiddeck-spatialpose").path)
if (!SessionState.running) { if (!SessionState.running) CompositorHost.logToSession(this)
val waylandLog = File(SessionPaths.beginOrCurrent(this), "wayland.log")
WaylandCompositor.setSessionLogFile(waylandLog)
try {
android.system.Os.setenv("DD_WAYLAND_LOG", waylandLog.path, true)
} catch (e: Exception) {
Log.w(TAG, "could not point the compositor's log at $waylandLog", e)
}
}
val mode = hdrPrefMode() val mode = hdrPrefMode()
if (probe != null) { if (probe != null) {
WaylandCompositor.nativeSetHdrDisplay( WaylandCompositor.nativeSetHdrDisplay(
@@ -2916,19 +2893,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
) )
Log.i(TAG, "hdr: " + (if (tonemap) "tone-mapped (${probe.reason})" else if (capable) "available" else "unavailable") + " · display ${probe.formats.ifEmpty { "SDR" }}") Log.i(TAG, "hdr: " + (if (tonemap) "tone-mapped (${probe.reason})" else if (capable) "available" else "unavailable") + " · display ${probe.formats.ifEmpty { "SDR" }}")
} }
if (!SessionState.running) { if (!SessionState.running) CompositorHost.applyHdr(this, mode)
val on = SessionState.hdrCapable && SessionPrefs.hdr(this, mode) CompositorHost.start(this, output, holder.surface, size, refreshHz(holder), outputFpsLimit())
SessionState.hdr = on
WaylandCompositor.nativeSetHdrOutput(on)
WaylandCompositor.nativeSetZeroCopy(on || SessionPrefs.zeroCopy(this, mode))
Log.i(TAG, "hdr: " + (if (on) "on" else "off") + " for this $mode session")
}
com.droiddeck.launcher.gpu.DriverSetupLog.write(this, "compositor.start driver=$driverId")
CompositorHost.startOrAttach(
this, holder.surface, runtimeDir.path,
driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) },
applicationInfo.nativeLibraryDir, size.first, size.second, refreshHz(holder), outputFpsLimit(),
)
onOutputAttached(holder) onOutputAttached(holder)
if (SessionState.running && size != previous) { if (SessionState.running && size != previous) {
Log.i(TAG, "output resized: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface") Log.i(TAG, "output resized: ${previous.first}x${previous.second} -> ${size.first}x${size.second} on a new surface")
@@ -3552,15 +3518,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
override fun dispatchKeyEvent(event: KeyEvent): Boolean { 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 if (com.droiddeck.launcher.ui.AgentPet.handleBack(this, event)) return true
when (event.keyCode) { when (event.keyCode) {
KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> { KeyEvent.KEYCODE_VOLUME_UP, KeyEvent.KEYCODE_VOLUME_DOWN, KeyEvent.KEYCODE_VOLUME_MUTE -> {
@@ -3678,9 +3635,8 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (drawerOpen && (menuOwnsController || (!fromController && !(dockedTouchOnly && event.keyCode == KeyEvent.KEYCODE_BACK)))) { if (drawerOpen && (menuOwnsController || (!fromController && !(dockedTouchOnly && event.keyCode == KeyEvent.KEYCODE_BACK)))) {
if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) { if (fromController && (event.keyCode == KeyEvent.KEYCODE_BUTTON_L1 || event.keyCode == KeyEvent.KEYCODE_BUTTON_R1)) {
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) { if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) {
// The bumpers walk the tabs on the strip; a page kept inside More counts as the More tab. drawerPage = sessionDrawerPages(glasses.present)
val pages = sessionDrawerPages(glasses.present) .step(drawerPage, if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
drawerPage = pages.strip().step(pages.tabFor(drawerPage), if (event.keyCode == KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
releaseDrawerDirection() releaseDrawerDirection()
} }
return true return true
@@ -4411,32 +4367,6 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
} else if (wanted != secondScreenMode) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal() } else if (wanted != secondScreenMode) selectSecondScreenMode(wanted) else secondScreenPresentation?.retryTerminal()
} }
private fun chooseDualScreenSessionMode(mode: String) {
if (mode !in com.droiddeck.launcher.input.DualScreen.modes || mode == dualScreenSessionMode) return
SessionPrefs.setDualScreenSessionMode(this, mode)
dualScreenSessionMode = mode
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)
if (menuOnBottom) drawerOpen = true
} else if (menuOnTop) {
// The menu moves to the second screen as the menu itself, not as one of the control panels.
SessionState.secondScreenAutoOpened = true
refreshSecondScreenDisplays()
pinDockedMenu()
return
}
refreshSecondScreenDisplays()
}
private fun selectSecondScreenDisplay(displayId: Int) { private fun selectSecondScreenDisplay(displayId: Int) {
if (secondScreenDisplays.none { it.id == displayId }) return if (secondScreenDisplays.none { it.id == displayId }) return
selectedSecondScreenDisplay = displayId selectedSecondScreenDisplay = displayId
@@ -5999,11 +5929,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
if (secondScreenPresentation == null) showSecondScreen(secondScreenMode) if (secondScreenPresentation == null) showSecondScreen(secondScreenMode)
if (com.droiddeck.launcher.input.DualScreen.menuReturnsOnStart(openingPanel(), SessionState.bottomMenu, menuShownOnBottom())) pinDockedMenu() if (com.droiddeck.launcher.input.DualScreen.menuReturnsOnStart(openingPanel(), SessionState.bottomMenu, menuShownOnBottom())) pinDockedMenu()
SessionState.bottomMenu = false SessionState.bottomMenu = false
} else { } else openDualScreenControls()
if (SessionState.bottomMenu && !menuShownOnBottom()) pinDockedMenu()
SessionState.bottomMenu = false
if (!menuShownOnBottom()) openDualScreenControls()
}
startedScreens++ startedScreens++
SessionService.setActivityVisible(this, true, sessionActivityDisplayId) SessionService.setActivityVisible(this, true, sessionActivityDisplayId)
Glasses.rescan() Glasses.rescan()
@@ -143,9 +143,9 @@ object AgentSetup {
listOf("sh", "-c", "set -e; export DEBIAN_FRONTEND=noninteractive; " + listOf("sh", "-c", "set -e; export DEBIAN_FRONTEND=noninteractive; " +
"apt() { apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 \"\$@\"; }; " + "apt() { apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 \"\$@\"; }; " +
"dpkg --configure -a || echo 'Some packages are not configured yet; repairing dependencies'; " + "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 -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.SIGN_IN -> harness.signIn
Step.GITHUB -> listOf("dd-gh-login") Step.GITHUB -> listOf("dd-gh-login")
@@ -16,7 +16,7 @@ object SteamIntegration {
const val EXTRA_FEATURE = "integration_feature" const val EXTRA_FEATURE = "integration_feature"
const val SHORTCUTS_STATUS = "com.droiddeck.launcher.SHORTCUTS_INSTALL_STATUS" const val SHORTCUTS_STATUS = "com.droiddeck.launcher.SHORTCUTS_INSTALL_STATUS"
private const val SHORTCUTS_ASSET = "shortcuts.apk" private const val SHORTCUTS_ASSET = "shortcuts.apk"
enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS, BLUETOOTH } enum class Feature { WIFI, BRIGHTNESS, HOME, SHORTCUTS }
data class State( data class State(
val wifi: Boolean = false, val wifi: Boolean = false,
@@ -28,7 +28,6 @@ object SteamIntegration {
val shortcuts: Boolean = false, val shortcuts: Boolean = false,
val shortcutsRestricted: Boolean = false, val shortcutsRestricted: Boolean = false,
val shortcutsTried: Boolean = false, val shortcutsTried: Boolean = false,
val bluetooth: Boolean = false,
val suggested: Boolean = true, val suggested: Boolean = true,
) )
@@ -40,16 +39,9 @@ object SteamIntegration {
home = HomeApp.isDefault(context), home = HomeApp.isDefault(context),
shortcuts = shortcutsEnabled(context) && shortcutsCurrent(context), shortcuts = shortcutsEnabled(context) && shortcutsCurrent(context),
shortcutsRestricted = restrictedSettings(context), shortcutsRestricted = restrictedSettings(context),
bluetooth = bluetoothAllowed(context),
suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false), suggested = !SessionPrefs.sessionPrefs(context).getBoolean("steam_integration_seen", false),
) )
fun bluetoothAllowed(context: Context): Boolean =
android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.S ||
context.checkSelfPermission(android.Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED
fun appInfo(context: Context) = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:${context.packageName}"))
private fun restrictedSettings(context: Context): Boolean { private fun restrictedSettings(context: Context): Boolean {
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.TIRAMISU) return false
val mode = runCatching { val mode = runCatching {
@@ -38,8 +38,6 @@ class WirelessAdbPairingService : Service() {
private var pairingHost: String? = null private var pairingHost: String? = null
private var pairingPort: Int? = null private var pairingPort: Int? = null
@Volatile private var working = false @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))) } private val timeout = Runnable { finish(Stage.Failed(getString(R.string.adbpair_timed_out))) }
override fun onBind(intent: Intent?): IBinder? = null override fun onBind(intent: Intent?): IBinder? = null
@@ -52,15 +50,12 @@ class WirelessAdbPairingService : Service() {
onCode(code) onCode(code)
} }
ACTION_CANCEL -> finish(Stage.Idle) ACTION_CANCEL -> finish(Stage.Idle)
else -> begin(intent?.getBooleanExtra(EXTRA_ENABLE_LIMIT, false) == true) else -> begin()
} }
return START_NOT_STICKY return START_NOT_STICKY
} }
private fun begin(enableLimit: Boolean) { private fun begin() {
if (working) return
session++
limitEnabled = enableLimit
pairingHost = null pairingHost = null
pairingPort = null pairingPort = null
working = false working = false
@@ -73,13 +68,12 @@ class WirelessAdbPairingService : Service() {
private fun startDiscovery() { private fun startDiscovery() {
stopDiscovery() stopDiscovery()
val owner = session
val manager = getSystemService(Context.NSD_SERVICE) as NsdManager val manager = getSystemService(Context.NSD_SERVICE) as NsdManager
val listener = object : NsdManager.DiscoveryListener { val listener = object : NsdManager.DiscoveryListener {
override fun onDiscoveryStarted(serviceType: String) = Unit override fun onDiscoveryStarted(serviceType: String) = Unit
override fun onServiceFound(serviceInfo: NsdServiceInfo) { override fun onServiceFound(serviceInfo: NsdServiceInfo) {
if (serviceInfo.serviceType?.contains(PAIRING_TYPE) != true) return 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 onServiceLost(serviceInfo: NsdServiceInfo) = Unit
override fun onDiscoveryStopped(serviceType: String) = 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()))) } .onFailure { finish(Stage.Failed(getString(R.string.adbpair_discovery_failed, it.localizedMessage.toString()))) }
} }
private fun resolveListener(owner: Int): NsdManager.ResolveListener { private fun resolveListener() = object : NsdManager.ResolveListener {
return object : NsdManager.ResolveListener {
override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) = Unit override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) = Unit
override fun onServiceResolved(serviceInfo: NsdServiceInfo) { override fun onServiceResolved(serviceInfo: NsdServiceInfo) {
val address = serviceInfo.host ?: return val address = serviceInfo.host ?: return
if (!WirelessAdbFix.isLocalAddress(address)) return if (!WirelessAdbFix.isLocalAddress(address)) return
main.post { main.post {
if (owner != session || working || current.value == Stage.Done) return@post if (working || current.value == Stage.Done) return@post
pairingHost = address.hostAddress pairingHost = address.hostAddress
pairingPort = serviceInfo.port pairingPort = serviceInfo.port
if (current.value !is Stage.CodeNeeded) show(Stage.CodeNeeded()) if (current.value !is Stage.CodeNeeded) show(Stage.CodeNeeded())
} }
} }
}
} }
private fun onCode(code: String) { private fun onCode(code: String) {
@@ -122,34 +114,29 @@ class WirelessAdbPairingService : Service() {
return return
} }
working = true working = true
val owner = session
val enable = limitEnabled
show(Stage.Working(getString(R.string.adbpair_pairing))) show(Stage.Working(getString(R.string.adbpair_pairing)))
Thread({ Thread({
val paired = runCatching { kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@WirelessAdbPairingService, WirelessAdbFix.LOOPBACK, port, code) } } val paired = runCatching { kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@WirelessAdbPairingService, WirelessAdbFix.LOOPBACK, port, code) } }
if (paired.isFailure) { if (paired.isFailure) {
main.post { main.post {
working = false working = false
if (owner != session) return@post
pairingPort = null pairingPort = null
show(Stage.CodeNeeded(getString(R.string.adbpair_code_rejected))) show(Stage.CodeNeeded(getString(R.string.adbpair_code_rejected)))
} }
return@Thread return@Thread
} }
main.post { main.post {
if (owner != session) return@post
stopDiscovery() stopDiscovery()
show(Stage.Working(getString(R.string.adbpair_connecting))) show(Stage.Working(getString(R.string.adbpair_connecting)))
} }
val result = runCatching { val result = runCatching {
val connectPort = WirelessAdbFix.localConnectPort(this) val connectPort = WirelessAdbFix.localConnectPort(this)
?: error(getString(R.string.adbpair_port_not_found)) ?: error(getString(R.string.adbpair_port_not_found))
main.post { if (owner == session) show(Stage.Working(getString(R.string.adbpair_applying))) } main.post { show(Stage.Working(getString(R.string.adbpair_applying))) }
WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, enable) WirelessAdbFix.setChildProcessLimit(this, WirelessAdbFix.LOOPBACK, connectPort, false)
} }
main.post { main.post {
working = false working = false
if (owner != session) return@post
finish(result.exceptionOrNull()?.let { Stage.Failed(it.localizedMessage ?: getString(R.string.adbpair_command_failed)) } ?: Stage.Done) finish(result.exceptionOrNull()?.let { Stage.Failed(it.localizedMessage ?: getString(R.string.adbpair_command_failed)) } ?: Stage.Done)
} }
}, "wireless-adb-pairing").start() }, "wireless-adb-pairing").start()
@@ -161,7 +148,6 @@ class WirelessAdbPairingService : Service() {
} }
private fun finish(stage: Stage) { private fun finish(stage: Stage) {
session++
main.removeCallbacks(timeout) main.removeCallbacks(timeout)
stopDiscovery() stopDiscovery()
publish(stage) 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_CODE = "com.droiddeck.launcher.action.WIRELESS_ADB_CODE"
private const val ACTION_CANCEL = "com.droiddeck.launcher.action.WIRELESS_ADB_CANCEL" private const val ACTION_CANCEL = "com.droiddeck.launcher.action.WIRELESS_ADB_CANCEL"
private const val KEY_CODE = "code" private const val KEY_CODE = "code"
private const val EXTRA_ENABLE_LIMIT = "enable_limit"
private const val TIMEOUT_MS = 5 * 60_000L private const val TIMEOUT_MS = 5 * 60_000L
private val current = MutableStateFlow<Stage>(Stage.Idle) private val current = MutableStateFlow<Stage>(Stage.Idle)
@@ -270,10 +255,10 @@ class WirelessAdbPairingService : Service() {
private fun publish(stage: Stage) { current.value = stage } 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) context.getSystemService(NotificationManager::class.java)?.cancel(NOTIFICATION_ID)
publish(Stage.Waiting) 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) 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 = fun notificationsEnabled(context: Context): Boolean =
context.getSystemService(NotificationManager::class.java)?.areNotificationsEnabled() != false && !channelBlocked(context) context.getSystemService(NotificationManager::class.java)?.areNotificationsEnabled() != false
/** 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
} }
} }
@@ -28,7 +28,6 @@ import androidx.compose.material.icons.filled.ArrowUpward
import androidx.compose.material.icons.filled.Checklist import androidx.compose.material.icons.filled.Checklist
import androidx.compose.material.icons.filled.Delete import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.FileCopy import androidx.compose.material.icons.filled.FileCopy
import androidx.compose.material.icons.filled.FileOpen
import androidx.compose.material.icons.filled.Folder import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.Info import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.InsertDriveFile import androidx.compose.material.icons.filled.InsertDriveFile
@@ -102,18 +101,8 @@ private fun FileContextMenuItems(
onToggleFavorite: () -> Unit, onToggleFavorite: () -> Unit,
onProperties: () -> Unit, onProperties: () -> Unit,
onDismissMenu: () -> Unit, onDismissMenu: () -> Unit,
onOpen: () -> Unit,
) { ) {
val isDir = file.isDirectory val isDir = file.isDirectory
if (!isDir) {
DropdownMenuItem(
text = { Text(stringResource(R.string.fm_edit_open)) },
leadingIcon = { Icon(Icons.Filled.FileOpen, null, tint = MaterialTheme.colorScheme.primary) },
onClick = { onDismissMenu(); onOpen() },
modifier = Modifier.focusGlide(),
)
MenuItemDivider()
}
DropdownMenuItem( DropdownMenuItem(
text = { Text(stringResource(R.string.fm_select)) }, text = { Text(stringResource(R.string.fm_select)) },
leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) }, leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) },
@@ -191,7 +180,6 @@ internal fun FileItemRow(
onCut: () -> Unit, onCut: () -> Unit,
onDelete: () -> Unit, onDelete: () -> Unit,
onRename: () -> Unit, onRename: () -> Unit,
onOpen: () -> Unit = {},
isFavorite: Boolean = false, isFavorite: Boolean = false,
onToggleFavorite: () -> Unit = {}, onToggleFavorite: () -> Unit = {},
onProperties: () -> Unit = {}, onProperties: () -> Unit = {},
@@ -303,7 +291,6 @@ internal fun FileItemRow(
file = file, file = file,
isFavorite = isFavorite, isFavorite = isFavorite,
onSelect = onSelect, onSelect = onSelect,
onOpen = onOpen,
onRename = onRename, onRename = onRename,
onCopy = onCopy, onCopy = onCopy,
onCut = onCut, onCut = onCut,
@@ -530,7 +517,6 @@ internal fun FileGridTile(
isFavorite: Boolean = false, isFavorite: Boolean = false,
onSelect: () -> Unit = {}, onSelect: () -> Unit = {},
onRename: () -> Unit = {}, onRename: () -> Unit = {},
onOpen: () -> Unit = {},
onCopy: () -> Unit = {}, onCopy: () -> Unit = {},
onCut: () -> Unit = {}, onCut: () -> Unit = {},
onDelete: () -> Unit = {}, onDelete: () -> Unit = {},
@@ -619,7 +605,6 @@ internal fun FileGridTile(
file = file, file = file,
isFavorite = isFavorite, isFavorite = isFavorite,
onSelect = onSelect, onSelect = onSelect,
onOpen = onOpen,
onRename = onRename, onRename = onRename,
onCopy = onCopy, onCopy = onCopy,
onCut = onCut, onCut = onCut,
@@ -191,7 +191,6 @@ fun FileManagerScreen(
var compactRows by remember { mutableStateOf(browsePrefs.getBoolean("fmCompactRows", false)) } var compactRows by remember { mutableStateOf(browsePrefs.getBoolean("fmCompactRows", false)) }
var showNewFolderDialog by remember { mutableStateOf(false) } var showNewFolderDialog by remember { mutableStateOf(false) }
var renameTarget by remember { mutableStateOf<File?>(null) } var renameTarget by remember { mutableStateOf<File?>(null) }
var editingTarget by remember { mutableStateOf<File?>(null) }
var propertiesTarget by remember { mutableStateOf<File?>(null) } var propertiesTarget by remember { mutableStateOf<File?>(null) }
var isOperationRunning by remember { mutableStateOf(false) } var isOperationRunning by remember { mutableStateOf(false) }
var operationLabel by remember { mutableStateOf("") } var operationLabel by remember { mutableStateOf("") }
@@ -295,7 +294,7 @@ fun FileManagerScreen(
if (isOperationActive()) pendingNavigation = action else navigate(action) if (isOperationActive()) pendingNavigation = action else navigate(action)
} }
BackHandler(enabled = editingTarget == null && (operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty())) { BackHandler(enabled = operationActive || cancellingNavigation || showFavorites || currentDir != currentRoot || history.isNotEmpty()) {
requestNavigation(FileManagerNavigation.BACK) requestNavigation(FileManagerNavigation.BACK)
} }
@@ -697,14 +696,6 @@ fun FileManagerScreen(
val compactToolbar = LocalConfiguration.current.screenWidthDp < 600 val compactToolbar = LocalConfiguration.current.screenWidthDp < 600
Column(modifier = Modifier.fillMaxSize()) { Column(modifier = Modifier.fillMaxSize()) {
editingTarget?.let { target ->
TextEditorScreen(
file = target,
onExit = { editingTarget = null },
modifier = Modifier.fillMaxSize(),
)
return@Column
}
if (pickMode && !pickerTitle.isNullOrEmpty()) { if (pickMode && !pickerTitle.isNullOrEmpty()) {
Text( Text(
text = pickerTitle, text = pickerTitle,
@@ -1203,8 +1194,6 @@ fun FileManagerScreen(
pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply() pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply()
onPick?.invoke(file) onPick?.invoke(file)
} }
} else {
editingTarget = file
} }
}, },
onMenu = { showMenuFor = file }, onMenu = { showMenuFor = file },
@@ -1216,7 +1205,6 @@ fun FileManagerScreen(
selectedPaths = selectedPaths + file.absolutePath selectedPaths = selectedPaths + file.absolutePath
showMenuFor = null showMenuFor = null
}, },
onOpen = { editingTarget = file; showMenuFor = null },
onRename = { renameTarget = file; showMenuFor = null }, onRename = { renameTarget = file; showMenuFor = null },
onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null }, onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null },
onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null }, onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null },
@@ -1285,8 +1273,6 @@ fun FileManagerScreen(
pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply() pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply()
onPick?.invoke(file) onPick?.invoke(file)
} }
} else {
editingTarget = file
} }
}, },
onMenu = { showMenuFor = file }, onMenu = { showMenuFor = file },
@@ -1300,7 +1286,6 @@ fun FileManagerScreen(
onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null }, onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null },
onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null }, onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null },
onDelete = { selectedEntry = file; showMenuFor = null }, onDelete = { selectedEntry = file; showMenuFor = null },
onOpen = { editingTarget = file; showMenuFor = null },
onRename = { renameTarget = file; showMenuFor = null }, onRename = { renameTarget = file; showMenuFor = null },
isFavorite = isFav, isFavorite = isFav,
onToggleFavorite = { onToggleFavorite = {
@@ -1,726 +0,0 @@
package com.droiddeck.launcher.files
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
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.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.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material.icons.filled.Save
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
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.ui.focusGlide
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.InputStream
import java.nio.ByteBuffer
import java.nio.charset.CharacterCodingException
import java.nio.charset.Charset
import java.nio.charset.CodingErrorAction
import java.nio.file.Files
import kotlin.math.roundToInt
internal const val EDITOR_FONT_SIZE_SP = 13
internal const val EDITOR_LINE_HEIGHT_SP = 18
internal const val EDITOR_TAB_WIDTH = 4
internal const val EDITOR_MAX_OPEN_BYTES = 4L * 1024 * 1024
internal const val EDITOR_MAX_EDIT_BYTES = 512L * 1024
internal enum class EditorCharset(val label: String, private val charsetName: String) {
UTF8("UTF-8", "UTF-8"),
GB18030("GB18030", "GB18030"),
;
val charset: Charset get() = Charset.forName(charsetName)
}
internal enum class EditorLock { NONE, BINARY, TOO_LARGE, PERMISSION, LOSSY }
internal enum class EditorLoadState { LOADING, READY, TOO_LARGE, UNREADABLE }
internal data class DecodedEditorText(val text: String, val charset: EditorCharset, val lossy: Boolean)
internal fun editorIsBinary(bytes: ByteArray, sample: Int = 8192): Boolean {
val limit = minOf(bytes.size, sample)
for (i in 0 until limit) if (bytes[i].toInt() == 0) return true
return false
}
private fun strictDecode(bytes: ByteArray, charset: Charset): String? = try {
charset.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(bytes))
.toString()
} catch (e: CharacterCodingException) {
null
}
internal fun decodeEditorText(bytes: ByteArray): DecodedEditorText {
strictDecode(bytes, Charsets.UTF_8)?.let { return DecodedEditorText(it, EditorCharset.UTF8, false) }
strictDecode(bytes, EditorCharset.GB18030.charset)?.let { return DecodedEditorText(it, EditorCharset.GB18030, false) }
return DecodedEditorText(String(bytes, Charsets.UTF_8), EditorCharset.UTF8, true)
}
internal fun resolveEditorSaveTarget(file: File): File {
val isLink = runCatching { Files.isSymbolicLink(file.toPath()) }.getOrDefault(false)
if (!isLink) return file
// rename(2) replaces the link itself, so stage next to and rename onto the real target
return runCatching { file.canonicalFile }.getOrDefault(file)
}
internal fun readCapped(input: InputStream, limit: Long): ByteArray? {
val out = ByteArrayOutputStream()
val buffer = ByteArray(64 * 1024)
var total = 0L
while (true) {
val n = input.read(buffer)
if (n < 0) return out.toByteArray()
total += n
if (total > limit) return null
out.write(buffer, 0, n)
}
}
internal fun expandEditorTabs(text: String, width: Int = EDITOR_TAB_WIDTH): String {
if (text.indexOf('\t') < 0) return text
val out = StringBuilder(text.length)
var column = 0
for (c in text) {
when (c) {
'\n' -> {
out.append(c)
column = 0
}
'\t' -> {
val pad = width - (column % width)
repeat(pad) { out.append(' ') }
column += pad
}
else -> {
out.append(c)
column++
}
}
}
return out.toString()
}
internal fun lineCountOf(text: String): Int {
var lines = 1
for (i in text.indices) if (text[i] == '\n') lines++
return lines
}
internal fun lineIndexOfOffset(text: String, offset: Int): Int {
val end = offset.coerceIn(0, text.length)
var line = 0
var i = 0
while (i < end) {
if (text[i] == '\n') line++
i++
}
return line
}
internal fun columnOfOffset(text: String, offset: Int): Int {
val end = offset.coerceIn(0, text.length)
var start = end
while (start > 0 && text[start - 1] != '\n') start--
return end - start + 1
}
internal fun findEditorMatches(
text: String,
query: String,
matchCase: Boolean = false,
limit: Int = 10000,
): List<IntRange> {
if (query.isEmpty()) return emptyList()
val out = ArrayList<IntRange>()
var at = 0
while (out.size < limit) {
val found = text.indexOf(query, at, ignoreCase = !matchCase)
if (found < 0) break
out.add(found until found + query.length)
at = found + query.length
}
return out
}
internal fun replaceEditorMatches(text: String, matches: List<IntRange>, replacement: String): String {
if (matches.isEmpty()) return text
val out = StringBuilder(text.length)
var cursor = 0
for (m in matches) {
if (m.first < cursor || m.last >= text.length) continue
out.append(text, cursor, m.first).append(replacement)
cursor = m.last + 1
}
out.append(text, cursor, text.length)
return out.toString()
}
@Composable
internal fun TextEditorScreen(
file: File,
onExit: () -> Unit,
modifier: Modifier = Modifier,
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val density = LocalDensity.current
var text by remember { mutableStateOf("") }
var selection by remember { mutableStateOf(TextRange.Zero) }
var composing by remember { mutableStateOf<TextRange?>(null) }
var loadState by remember { mutableStateOf(EditorLoadState.LOADING) }
var lock by remember { mutableStateOf(EditorLock.NONE) }
var charset by remember { mutableStateOf(EditorCharset.UTF8) }
var dirty by remember { mutableStateOf(false) }
var saving by remember { mutableStateOf(false) }
var showDiscard by remember { mutableStateOf(false) }
var showSearch by remember { mutableStateOf(false) }
var query by remember { mutableStateOf("") }
var replacement by remember { mutableStateOf("") }
var matchCase by remember { mutableStateOf(false) }
var matchIndex by remember { mutableIntStateOf(0) }
val scrollState = rememberScrollState()
val textHorizontalState = rememberScrollState()
var viewportHeight by remember { mutableIntStateOf(0) }
var viewportWidth by remember { mutableIntStateOf(0) }
val lineHeightDp = with(density) { EDITOR_LINE_HEIGHT_SP.sp.toDp() }
val lineHeightPx = with(density) { lineHeightDp.toPx() }
val totalLines = remember(text) { lineCountOf(text) }
val cursorLine = lineIndexOfOffset(text, selection.end)
val cursorColumn = columnOfOffset(text, selection.end)
val matches = remember(text, query, matchCase) { findEditorMatches(text, query, matchCase) }
val readOnly = lock != EditorLock.NONE
val bodyStyle = TextStyle(
fontFamily = FontFamily.Monospace,
fontSize = EDITOR_FONT_SIZE_SP.sp,
lineHeight = EDITOR_LINE_HEIGHT_SP.sp,
color = MaterialTheme.colorScheme.onBackground,
)
val textMeasurer = rememberTextMeasurer()
val charWidthPx = remember(bodyStyle) { textMeasurer.measure(text = "0", style = bodyStyle).size.width.toFloat() }
LaunchedEffect(file) {
loadState = EditorLoadState.LOADING
val size = withContext(Dispatchers.IO) { file.length() }
if (size > EDITOR_MAX_OPEN_BYTES) {
loadState = EditorLoadState.TOO_LARGE
return@LaunchedEffect
}
val read = withContext(Dispatchers.IO) {
runCatching { file.inputStream().use { readCapped(it, EDITOR_MAX_OPEN_BYTES) } }
}
val bytes = read.getOrNull()
if (bytes == null) {
loadState = if (read.isFailure) EditorLoadState.UNREADABLE else EditorLoadState.TOO_LARGE
return@LaunchedEffect
}
val decoded = decodeEditorText(bytes)
text = expandEditorTabs(decoded.text)
charset = decoded.charset
lock = when {
editorIsBinary(bytes) -> EditorLock.BINARY
decoded.lossy -> EditorLock.LOSSY
bytes.size > EDITOR_MAX_EDIT_BYTES -> EditorLock.TOO_LARGE
!file.canWrite() -> EditorLock.PERMISSION
else -> EditorLock.NONE
}
selection = TextRange.Zero
loadState = EditorLoadState.READY
}
suspend fun revealLine(line: Int) {
val current = scrollState.value
val top = line * lineHeightPx
val target = when {
top < current -> top
top + lineHeightPx > current + viewportHeight -> top + lineHeightPx - viewportHeight
else -> return
}
val clamped = target.roundToInt().coerceIn(0, scrollState.maxValue)
if (clamped != current) scrollState.scrollTo(clamped)
}
LaunchedEffect(text, selection.end, viewportHeight, viewportWidth) {
if (loadState != EditorLoadState.READY) return@LaunchedEffect
revealLine(lineIndexOfOffset(text, selection.end))
if (viewportWidth > 0 && charWidthPx > 0) {
val x = (columnOfOffset(text, selection.end) - 1) * charWidthPx
val current = textHorizontalState.value
val target = when {
x < current -> x
x + charWidthPx > current + viewportWidth -> x + charWidthPx - viewportWidth
else -> null
}
if (target != null) {
val clamped = target.roundToInt().coerceIn(0, textHorizontalState.maxValue)
if (clamped != current) textHorizontalState.scrollTo(clamped)
}
}
}
LaunchedEffect(query, matchCase) {
if (query.isEmpty()) return@LaunchedEffect
matchIndex = 0
val first = matches.firstOrNull() ?: return@LaunchedEffect
selection = TextRange(first.first, first.last + 1)
composing = TextRange.Zero
}
LaunchedEffect(text) { matchIndex = 0 }
fun gotoMatch(delta: Int) {
if (matches.isEmpty()) return
matchIndex = Math.floorMod(matchIndex + delta, matches.size)
val m = matches[matchIndex]
selection = TextRange(m.first, m.last + 1)
composing = TextRange.Zero
}
fun replaceCurrent() {
if (readOnly) return
val m = matches.getOrNull(matchIndex) ?: return
text = text.replaceRange(m.first, m.last + 1, replacement)
dirty = true
matchIndex = 0
selection = TextRange(m.first + replacement.length)
composing = TextRange.Zero
}
fun replaceAll() {
if (readOnly || matches.isEmpty()) return
val all = findEditorMatches(text, query, matchCase, limit = Int.MAX_VALUE)
text = replaceEditorMatches(text, all, replacement)
dirty = true
matchIndex = 0
selection = TextRange.Zero
composing = TextRange.Zero
}
fun save() {
if (readOnly || saving || loadState != EditorLoadState.READY) return
val snapshot = text
val bytes = snapshot.toByteArray(charset.charset)
saving = true
scope.launch {
val ok = withContext(Dispatchers.IO) {
runCatching {
val target = resolveEditorSaveTarget(file)
val parent = target.parentFile
if (parent == null) {
target.writeBytes(bytes)
} else {
val tmp = File.createTempFile(".${target.name}.", ".droiddeck-tmp", parent)
try {
tmp.writeBytes(bytes)
runCatching {
Files.setPosixFilePermissions(tmp.toPath(), Files.getPosixFilePermissions(target.toPath()))
}
if (!tmp.renameTo(target)) error("rename to ${target.name} failed")
} finally {
tmp.delete()
}
}
}.isSuccess
}
saving = false
if (ok) {
if (text == snapshot) dirty = false
} else {
Toast.makeText(context, context.getString(R.string.fm_edit_save_failed, file.name), Toast.LENGTH_SHORT).show()
}
}
}
fun tryExit() {
if (saving) return
if (dirty && !readOnly) showDiscard = true else onExit()
}
BackHandler { tryExit() }
if (showDiscard) {
OutlinedAlertDialog(
onDismissRequest = { showDiscard = false },
title = { Text(stringResource(R.string.fm_edit_discard_title)) },
text = { Text(stringResource(R.string.fm_edit_discard_text, file.name)) },
confirmButton = {
TextButton(onClick = onExit, modifier = Modifier.focusGlide(CircleShape)) {
Text(stringResource(R.string.fm_edit_discard))
}
},
dismissButton = {
TextButton(onClick = { showDiscard = false }, modifier = Modifier.focusGlide(CircleShape)) {
Text(stringResource(R.string.common_cancel))
}
},
)
}
Column(
modifier = modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.background),
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.surfaceContainer)
.padding(horizontal = 8.dp, vertical = 6.dp),
) {
IconButton(onClick = { tryExit() }, modifier = Modifier.focusGlide(CircleShape)) {
Icon(
Icons.Filled.ArrowBack,
stringResource(R.string.fm_back),
tint = MaterialTheme.colorScheme.primary,
)
}
Column(modifier = Modifier.weight(1f).padding(horizontal = 4.dp)) {
Text(
text = file.name,
color = MaterialTheme.colorScheme.onBackground,
fontSize = 14.sp,
fontWeight = FontWeight.Medium,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
if (dirty) {
Text(
text = "\u2022 " + stringResource(R.string.fm_edit_modified),
color = MaterialTheme.colorScheme.primary,
fontSize = 11.sp,
maxLines = 1,
)
}
}
if (loadState == EditorLoadState.READY && lock != EditorLock.NONE) {
Text(
text = stringResource(
if (lock == EditorLock.BINARY) R.string.fm_edit_binary else R.string.fm_edit_read_only,
),
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 10.sp,
maxLines = 1,
modifier = Modifier
.background(MaterialTheme.colorScheme.surfaceVariant, MaterialTheme.shapes.small)
.padding(horizontal = 6.dp, vertical = 2.dp),
)
Spacer(Modifier.width(6.dp))
}
IconButton(
onClick = { showSearch = !showSearch },
enabled = loadState == EditorLoadState.READY,
modifier = Modifier.focusGlide(CircleShape),
) {
Icon(
Icons.Filled.Search,
stringResource(R.string.fm_edit_find),
tint = if (showSearch) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
IconButton(
onClick = { save() },
enabled = loadState == EditorLoadState.READY && !readOnly && dirty && !saving,
modifier = Modifier.focusGlide(CircleShape),
) {
Icon(
Icons.Filled.Save,
stringResource(R.string.fm_edit_save),
tint = if (dirty) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
)
}
}
if (showSearch && loadState == EditorLoadState.READY) {
Column(Modifier.fillMaxWidth().background(MaterialTheme.colorScheme.surfaceContainer)) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(start = 8.dp, end = 4.dp, top = 4.dp),
) {
OutlinedTextField(
value = query,
onValueChange = { query = it; matchIndex = 0 },
singleLine = true,
placeholder = { Text(stringResource(R.string.fm_edit_find), fontSize = 13.sp) },
textStyle = MaterialTheme.typography.bodySmall,
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
keyboardActions = KeyboardActions(onSearch = { gotoMatch(1) }),
modifier = Modifier.weight(1f).focusGlide(),
)
Text(
text = if (matches.isEmpty()) "0/${matches.size}" else "${matchIndex.coerceAtMost(matches.size - 1) + 1}/${matches.size}",
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(horizontal = 6.dp).widthIn(min = 44.dp, max = 80.dp),
)
IconButton(
onClick = { gotoMatch(-1) },
enabled = matches.isNotEmpty(),
modifier = Modifier.focusGlide(CircleShape),
) {
Icon(
Icons.Filled.KeyboardArrowUp,
stringResource(R.string.fm_edit_find_previous),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(20.dp),
)
}
IconButton(
onClick = { gotoMatch(1) },
enabled = matches.isNotEmpty(),
modifier = Modifier.focusGlide(CircleShape),
) {
Icon(
Icons.Filled.KeyboardArrowDown,
stringResource(R.string.fm_edit_find_next),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(20.dp),
)
}
TextButton(onClick = { matchCase = !matchCase }, modifier = Modifier.focusGlide(CircleShape)) {
Text(
text = "Aa",
color = if (matchCase) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 13.sp,
)
}
IconButton(onClick = { showSearch = false }, modifier = Modifier.focusGlide(CircleShape)) {
Icon(
Icons.Filled.Close,
stringResource(R.string.common_cancel),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.size(20.dp),
)
}
}
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(start = 8.dp, top = 2.dp, end = 4.dp, bottom = 2.dp),
) {
OutlinedTextField(
value = replacement,
onValueChange = { replacement = it },
singleLine = true,
placeholder = { Text(stringResource(R.string.fm_edit_replace), fontSize = 13.sp) },
textStyle = MaterialTheme.typography.bodySmall,
modifier = Modifier.weight(1f).focusGlide(),
)
TextButton(
onClick = { replaceCurrent() },
enabled = !readOnly && matches.isNotEmpty(),
modifier = Modifier.focusGlide(CircleShape),
) {
Text(stringResource(R.string.fm_edit_replace), fontSize = 13.sp)
}
TextButton(
onClick = { replaceAll() },
enabled = !readOnly && matches.isNotEmpty(),
modifier = Modifier.focusGlide(CircleShape),
) {
Text(stringResource(R.string.fm_edit_replace_all), fontSize = 13.sp)
}
}
}
}
Box(
modifier = Modifier
.weight(1f)
.fillMaxWidth()
.onSizeChanged { viewportHeight = it.height },
) {
when (loadState) {
EditorLoadState.LOADING -> CircularProgressIndicator(
modifier = Modifier.align(Alignment.Center),
)
EditorLoadState.TOO_LARGE, EditorLoadState.UNREADABLE -> Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.align(Alignment.Center).padding(24.dp),
) {
Text(
text = stringResource(
if (loadState == EditorLoadState.TOO_LARGE) R.string.fm_edit_too_large
else R.string.fm_edit_open_failed,
if (loadState == EditorLoadState.TOO_LARGE) FileOps.formatBytes(context, file.length())
else file.name,
),
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 14.sp,
textAlign = TextAlign.Center,
)
}
EditorLoadState.READY -> Column(
modifier = Modifier
.fillMaxSize()
.verticalScroll(scrollState),
) {
Row(modifier = Modifier.fillMaxWidth().height(lineHeightDp * totalLines.toFloat())) {
LineNumbers(
scrollState = scrollState,
viewportHeight = viewportHeight,
lineHeightDp = lineHeightDp,
lineHeightPx = lineHeightPx,
totalLines = totalLines,
cursorLine = cursorLine,
style = bodyStyle,
mutedColor = MaterialTheme.colorScheme.onSurfaceVariant,
cursorColor = MaterialTheme.colorScheme.primary,
)
Box(modifier = Modifier.weight(1f).onSizeChanged { viewportWidth = it.width }.horizontalScroll(textHorizontalState)) {
BasicTextField(
value = TextFieldValue(text = text, selection = selection, composition = composing),
onValueChange = { next ->
val changed = next.text != text
text = next.text
selection = next.selection
composing = next.composition
if (changed) dirty = true
},
readOnly = readOnly,
textStyle = bodyStyle,
cursorBrush = SolidColor(MaterialTheme.colorScheme.primary),
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Text,
capitalization = KeyboardCapitalization.None,
),
modifier = Modifier.fillMaxHeight().focusGlide(),
)
}
}
}
}
}
if (loadState == EditorLoadState.READY) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),
) {
Text(
text = stringResource(R.string.fm_edit_position, cursorLine + 1, cursorColumn),
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp,
maxLines = 1,
)
Spacer(Modifier.weight(1f))
Text(
text = charset.label + " \u2022 " + FileOps.formatBytes(context, file.length()),
color = MaterialTheme.colorScheme.onSurfaceVariant,
fontSize = 12.sp,
maxLines = 1,
)
}
}
}
}
@Composable
private fun LineNumbers(
scrollState: ScrollState,
viewportHeight: Int,
lineHeightDp: Dp,
lineHeightPx: Float,
totalLines: Int,
cursorLine: Int,
style: TextStyle,
mutedColor: Color,
cursorColor: Color,
modifier: Modifier = Modifier,
) {
val firstLine = (scrollState.value / lineHeightPx).toInt().coerceIn(0, totalLines - 1)
val lastLine = ((scrollState.value + viewportHeight) / lineHeightPx)
.toInt()
.coerceIn(firstLine, totalLines - 1)
Column(
horizontalAlignment = Alignment.End,
modifier = modifier
.width(IntrinsicSize.Min)
.padding(top = lineHeightDp * firstLine.toFloat()),
) {
for (line in firstLine..lastLine) {
Text(
text = (line + 1).toString(),
color = if (line == cursorLine) cursorColor else mutedColor,
textAlign = TextAlign.End,
maxLines = 1,
style = style,
modifier = Modifier.fillMaxWidth().height(lineHeightDp),
)
}
}
}
@@ -47,7 +47,6 @@ object AutoComponents {
{ c, comp, all, progress -> WinComponents.install(c, comp, all, progress) } { c, comp, all, progress -> WinComponents.install(c, comp, all, progress) }
@VisibleForTesting internal var sessionRunning: () -> Boolean = { SessionState.running } @VisibleForTesting internal var sessionRunning: () -> Boolean = { SessionState.running }
@VisibleForTesting internal var unfavourable: (Context) -> Boolean = { c -> constrained(c) } @VisibleForTesting internal var unfavourable: (Context) -> Boolean = { c -> constrained(c) }
@VisibleForTesting internal var firstRunHeldBack: (Context) -> Boolean = { c -> powerSaveOrMetered(c) }
@VisibleForTesting internal var online: (Context) -> Boolean = { c -> isOnline(c) } @VisibleForTesting internal var online: (Context) -> Boolean = { c -> isOnline(c) }
@VisibleForTesting @Volatile internal var runNow = false @VisibleForTesting @Volatile internal var runNow = false
@@ -534,10 +533,6 @@ object AutoComponents {
caps.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED) caps.hasCapability(android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED)
} }
fun powerSaveOrMetered(context: Context): Boolean =
context.getSystemService(PowerManager::class.java)?.isPowerSaveMode == true ||
context.getSystemService(ConnectivityManager::class.java)?.isActiveNetworkMetered == true
fun constrained(context: Context): Boolean { fun constrained(context: Context): Boolean {
val power = context.getSystemService(PowerManager::class.java) val power = context.getSystemService(PowerManager::class.java)
if (power?.isPowerSaveMode == true) return true if (power?.isPowerSaveMode == true) return true
@@ -20,12 +20,6 @@ object SteamRedists {
val SCRIPTED = mapOf( val SCRIPTED = mapOf(
72850 to listOf("xact" to "DirectX XACT audio"), 72850 to listOf("xact" to "DirectX XACT audio"),
489830 to listOf("xact_x64" to "DirectX XACT audio (64-bit)"), 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 BLOCK = Regex("\"SharedDepots\"\\s*\\{([^}]*)\\}", RegexOption.IGNORE_CASE)
private val ENTRY = Regex("\"(\\d+)\"\\s+\"\\d+\"") private val ENTRY = Regex("\"(\\d+)\"\\s+\"\\d+\"")
@@ -45,8 +45,9 @@ internal class XrealLink internal constructor(
if (msgId == VitureProtocol.MSG_GET_IMU) return true if (msgId == VitureProtocol.MSG_GET_IMU) return true
val valid = when (msgId) { val valid = when (msgId) {
VitureProtocol.MSG_GET_DISPLAY -> true VitureProtocol.MSG_GET_DISPLAY -> true
VitureProtocol.MSG_DISPLAY -> model.supportsDisplayMode(value) VitureProtocol.MSG_DISPLAY -> if (model.stereoOnlyControl) value == 5 || value == XrealModel.NATIVE_60HZ
VitureProtocol.MSG_BRIGHTNESS -> model.hardwareControls && value in 0..model.brightnessMax 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 VitureProtocol.MSG_FILM -> !model.stereoOnlyControl && value in 0..1
else -> false else -> false
} }
@@ -63,12 +64,12 @@ internal class XrealLink internal constructor(
channels = connector.connect() channels = connector.connect()
connection.set(channels) connection.set(channels)
if (!running) break if (!running) break
val control = XrealControl(channels, model = model) val control = XrealControl(channels, stereoOnly = model.stereoOnlyControl)
listener.onValue(VitureProtocol.MSG_GET_DISPLAY, control.display()) listener.onValue(VitureProtocol.MSG_GET_DISPLAY, control.display())
val current = channels val current = channels
reports = Thread({ reports = Thread({
try { try {
var filter = XrealOrientationFilter(model) var filter = XrealOrientationFilter(model.flipsYz)
var wasTracking = false var wasTracking = false
var lastSensor = System.nanoTime() var lastSensor = System.nanoTime()
while (running && connection.get() === current) { while (running && connection.get() === current) {
@@ -77,7 +78,7 @@ internal class XrealLink internal constructor(
if (sample != null) { if (sample != null) {
lastSensor = System.nanoTime() lastSensor = System.nanoTime()
val enabled = tracking val enabled = tracking
if (enabled && !wasTracking) filter = XrealOrientationFilter(model) if (enabled && !wasTracking) filter = XrealOrientationFilter(model.flipsYz)
wasTracking = enabled wasTracking = enabled
if (enabled) filter.update(sample)?.let { if (enabled) filter.update(sample)?.let {
if (running && ready && tracking && connection.get() === current) if (running && ready && tracking && connection.get() === current)
@@ -154,9 +155,8 @@ internal class XrealLink internal constructor(
internal class XrealControl( internal class XrealControl(
private val channels: XrealChannels, private val channels: XrealChannels,
private val settleDelayMs: Long = 150, 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 var transaction = 0
private fun exchange(command: Int, value: Int? = null): ByteArray { private fun exchange(command: Int, value: Int? = null): ByteArray {
transaction = if (transaction == Int.MAX_VALUE) 1 else transaction + 1 transaction = if (transaction == Int.MAX_VALUE) 1 else transaction + 1
@@ -172,7 +172,7 @@ internal class XrealControl(
fun display(): Int { fun display(): Int {
if (stereoOnly) return stereoDisplay() if (stereoOnly) return stereoDisplay()
val reply = exchange(XrealProtocol.GET_DISPLAY) 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) }}") ?: throw IOException("Unsupported XREAL display response: ${reply.take(32).joinToString("") { "%02x".format(it) }}")
} }
private fun stereoDisplay(): Int { private fun stereoDisplay(): Int {
@@ -187,7 +187,6 @@ internal class XrealControl(
} }
} }
fun changeDisplay(mode: Int): Int { fun changeDisplay(mode: Int): Int {
require(model.supportsDisplayMode(mode))
val stereo = mode == 5 val stereo = mode == 5
set(XrealProtocol.SET_INPUT, if (stereo) 1 else 0) set(XrealProtocol.SET_INPUT, if (stereo) 1 else 0)
val current = awaitDisplay { (it == 5) == stereo } val current = awaitDisplay { (it == 5) == stereo }
@@ -4,7 +4,6 @@ internal class XrealModel private constructor(
override val name: String, override val name: String,
val family: Family, val family: Family,
override val diagonalFovDeg: Float, override val diagonalFovDeg: Float,
private val native60Hz: Int = NATIVE_60HZ,
) : GlassesModel { ) : GlassesModel {
enum class Family { enum class Family {
ONE_S, ONE_S,
@@ -15,25 +14,23 @@ internal class XrealModel private constructor(
override val controllable = true override val controllable = true
override val brightnessMax = 9 override val brightnessMax = 9
override val volumeMax = 0 override val volumeMax = 0
override val hasSunblock get() = !stereoOnlyControl override val hasSunblock get() = family == Family.ONE_S
override val hardwareControls get() = !stereoOnlyControl override val hardwareControls get() = family == Family.ONE_S
override val sbs90 = false 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 // 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
internal fun supportsDisplayMode(mode: Int) = if (stereoOnlyControl) mode == 5 || mode == native60Hz
else mode in 3..5 || mode == native60Hz || (this === ONE_S && mode == 2)
// The Aura reports x right, y up, z back; the rest of the One family is a half turn about x from it. // 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 val flipsYz get() = family != Family.AURA
override fun mode(hz: Int, sbs: Boolean) = when { override fun mode(hz: Int, sbs: Boolean) = when {
sbs -> 5 sbs -> 5
stereoOnlyControl -> native60Hz stereoOnlyControl -> NATIVE_60HZ
hz >= 120 -> 4 hz >= 120 -> 4
hz >= 90 -> 3 hz >= 90 -> 3
else -> native60Hz else -> NATIVE_60HZ
} }
override fun modeForStep(step: Int): Int? = null 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_S = XrealModel("XREAL 1S", Family.ONE_S, 52f)
val ONE = XrealModel("XREAL One", Family.ONE, 50f) val ONE = XrealModel("XREAL One", Family.ONE, 50f)
val ONE_PRO = XrealModel("XREAL One Pro", Family.ONE, 57f) 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) val AURA = XrealModel("XREAL Aura", Family.AURA, 70f)
// The odd product ids one below these are the glasses' recovery mode. // 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 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 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, fun update(sample: XrealProtocol.Sample): FloatArray? = fusion.update(sample.timeNs,
sample.accel.headAxes(), sample.gyro.headAxes()) sample.accel.headAxes(), sample.gyro.headAxes())
private fun Vec3.headAxes(): Vec3 { private fun Vec3.headAxes() = if (flipYz) Vec3(x, -y, -z) else this
val display = sensorToDisplay?.rotate(this) ?: this
return if (model.flipsYz) Vec3(display.x, -display.y, -display.z) else display
}
} }
internal class ImuFusion { internal class ImuFusion {
@@ -7,8 +7,7 @@ object SocNames {
"SM8150" to "Snapdragon 855", "SM8250" to "Snapdragon 865", "SM8250-AC" to "Snapdragon 870", "SM8150" to "Snapdragon 855", "SM8250" to "Snapdragon 865", "SM8250-AC" to "Snapdragon 870",
"SM8350" to "Snapdragon 888", "SM8450" to "Snapdragon 8 Gen 1", "SM8475" to "Snapdragon 8+ Gen 1", "SM8350" to "Snapdragon 888", "SM8450" to "Snapdragon 8 Gen 1", "SM8475" to "Snapdragon 8+ Gen 1",
"SM8550" to "Snapdragon 8 Gen 2", "QCS8550" to "Snapdragon 8 Gen 2", "SM8650" to "Snapdragon 8 Gen 3", "SM8550" to "Snapdragon 8 Gen 2", "QCS8550" to "Snapdragon 8 Gen 2", "SM8650" to "Snapdragon 8 Gen 3",
"SM8750" to "Snapdragon 8 Elite", "SM8750P" to "Snapdragon 8 Elite", "SM8750" to "Snapdragon 8 Elite", "SM8850" to "Snapdragon 8 Elite Gen 5",
"SM8850" to "Snapdragon 8 Elite Gen 5",
"SM8975" to "Snapdragon 8 Elite Extreme Gen 6", "SM8975" to "Snapdragon 8 Elite Extreme Gen 6",
"SM7325" to "Snapdragon 778G", "SM7450" to "Snapdragon 7 Gen 1", "SM7550" to "Snapdragon 7 Gen 3", "SM7325" to "Snapdragon 778G", "SM7450" to "Snapdragon 7 Gen 1", "SM7550" to "Snapdragon 7 Gen 3",
"SM6375" to "Snapdragon 695", "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 "" 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")) return listOf(prop("ro.soc.model"), prop("ro.vendor.qti.soc_model"), sdk, prop("ro.fota.platform"))
.map { it.trim() } .map { it.trim() }
.firstOrNull { it.isNotEmpty() && !it.equals(Build.UNKNOWN, ignoreCase = true) && !Regex("(?i)^msm_\\d").containsMatchIn(it) } .firstOrNull { it.isNotEmpty() && !Regex("(?i)^msm_\\d").containsMatchIn(it) }.orEmpty()
.orEmpty()
} }
internal fun normalizedModel(model: String): String = model.trim().uppercase().removePrefix("QTI ").trim() internal fun normalizedModel(model: String): String = model.trim().uppercase().removePrefix("QTI ").trim()
@@ -44,35 +44,6 @@ class DroidDeckHudHost(context: Context) {
private var protonPid = 0 private var protonPid = 0
private var proton = "" private var proton = ""
@Volatile private var lastWindow: String? = null @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 var onPresentingWindowChanged: (() -> Unit)? = null
@@ -95,12 +66,6 @@ class DroidDeckHudHost(context: Context) {
} }
override fun onGameFrame() { override fun onGameFrame() {
if (feed.live && (!feed.steamFocusKnown || feed.steamFocused)) return
lastCompositorFrameNanos = System.nanoTime()
feed.onCompositorFrame(lastCompositorFrameNanos)
}
override fun onCompositorFrame() {
feed.onCompositorFrame(System.nanoTime()) feed.onCompositorFrame(System.nanoTime())
} }
} }
@@ -108,9 +73,7 @@ class DroidDeckHudHost(context: Context) {
private val frameCallback = object : Choreographer.FrameCallback { private val frameCallback = object : Choreographer.FrameCallback {
override fun doFrame(frameTimeNanos: Long) { override fun doFrame(frameTimeNanos: Long) {
if (!running || !polling) return if (!running || !polling) return
reconcileGameActivity()
if (feed.poll(System.nanoTime())) view?.onFrames() if (feed.poll(System.nanoTime())) view?.onFrames()
reconcileGameActivity()
Choreographer.getInstance().postFrameCallback(this) Choreographer.getInstance().postFrameCallback(this)
} }
} }
@@ -188,7 +151,7 @@ class DroidDeckHudHost(context: Context) {
fun refresh() { fun refresh() {
applyConfig() applyConfig()
if (!enabled) stop() else if (!running) start() else applyShown() if (!enabled) stop() else if (!running) start()
} }
fun start() { fun start() {
@@ -218,26 +181,14 @@ class DroidDeckHudHost(context: Context) {
applyShown() applyShown()
} }
private fun reconcileGameActivity() {
if (!SessionPrefs.hudOnlyDuringGame(context)) {
lastVisibilityGameActive = isGameActive()
return
}
if (isGameActive() != lastVisibilityGameActive) applyShown()
}
private fun applyShown() { private fun applyShown() {
if (!running) return if (!running) return
val onlyDuringGame = SessionPrefs.hudOnlyDuringGame(context) val show = !hidden && !backgrounded
val gameActive = isGameActive()
val show = !hidden && !backgrounded && (!onlyDuringGame || gameActive)
view?.visibility = if (show) View.VISIBLE else View.GONE view?.visibility = if (show) View.VISIBLE else View.GONE
showing = show showing = show
lastVisibilityGameActive = gameActive if (show != polling) {
val shouldPoll = !hidden && !backgrounded && (show || onlyDuringGame) polling = show
if (shouldPoll != polling) { if (show) Choreographer.getInstance().postFrameCallback(frameCallback)
polling = shouldPoll
if (shouldPoll) Choreographer.getInstance().postFrameCallback(frameCallback)
else Choreographer.getInstance().removeFrameCallback(frameCallback) else Choreographer.getInstance().removeFrameCallback(frameCallback)
} }
} }
@@ -581,7 +532,6 @@ class DroidDeckHudHost(context: Context) {
} }
companion object { companion object {
private const val GAME_ACTIVITY_STABLE_NS = 350_000_000L
private const val DOCK_OVERHANG = 0.4f private const val DOCK_OVERHANG = 0.4f
private const val PREVIEW_FROM = 0.55f private const val PREVIEW_FROM = 0.55f
private const val STRIP_PULL_ACROSS_DP = 360f private const val STRIP_PULL_ACROSS_DP = 360f
@@ -183,8 +183,6 @@ internal class GameFrameFeed(
private set private set
@Volatile var steamFocused = false @Volatile var steamFocused = false
private set private set
@Volatile var steamFocusKnown = false
private set
@Volatile var pid = 0 @Volatile var pid = 0
private set private set
@Volatile var outputWidth = 0 @Volatile var outputWidth = 0
@@ -200,16 +198,10 @@ internal class GameFrameFeed(
val compositorAdded = compositorFrames != seenCompositorFrames val compositorAdded = compositorFrames != seenCompositorFrames
seenCompositorFrames = compositorFrames seenCompositorFrames = compositorFrames
if (handle == 0L) { if (handle == 0L) {
if (nowNs < nextOpenNs) { if (nowNs < nextOpenNs) return compositorAdded
return compositorAdded
}
nextOpenNs = nowNs + REOPEN_NS nextOpenNs = nowNs + REOPEN_NS
handle = runCatching { HudFrames.nativeOpen(file.path) }.getOrDefault(0L) handle = runCatching { HudFrames.nativeOpen(file.path) }.getOrDefault(0L)
if (handle == 0L) { if (handle == 0L) return compositorAdded
return compositorAdded
}
HudFrames.nativePoll(handle, frametimes, times) HudFrames.nativePoll(handle, frametimes, times)
} }
val n = HudFrames.nativePoll(handle, frametimes, times) val n = HudFrames.nativePoll(handle, frametimes, times)
@@ -227,7 +219,6 @@ internal class GameFrameFeed(
fromGamescope = false fromGamescope = false
} }
if (n <= 0 && nowNs - maxOf(lastRingFrameNs, nextOpenNs - REOPEN_NS) > STALE_NS) close() if (n <= 0 && nowNs - maxOf(lastRingFrameNs, nextOpenNs - REOPEN_NS) > STALE_NS) close()
if (nowNs - lastInfoNs >= INFO_NS) { if (nowNs - lastInfoNs >= INFO_NS) {
lastInfoNs = nowNs lastInfoNs = nowNs
readInfo() readInfo()
@@ -259,7 +250,6 @@ internal class GameFrameFeed(
} }
fun close() { fun close() {
fromGamescope = false
if (handle != 0L) HudFrames.nativeClose(handle) if (handle != 0L) HudFrames.nativeClose(handle)
handle = 0L handle = 0L
} }
@@ -275,7 +265,6 @@ internal class GameFrameFeed(
outputHeight = info[2] outputHeight = info[2]
refreshMilliHz = info[3] refreshMilliHz = info[3]
steamFocused = info[4] != 0 steamFocused = info[4] != 0
steamFocusKnown = true
engine = engineLabel(name) engine = engineLabel(name)
} }
@@ -14,8 +14,7 @@ object DualScreen {
const val MODE_AUTO = "auto" const val MODE_AUTO = "auto"
const val MODE_ON = "on" const val MODE_ON = "on"
const val MODE_OFF = "off" const val MODE_OFF = "off"
const val MODE_SWAPPED = "swapped" val modes = listOf(MODE_AUTO, MODE_ON, MODE_OFF)
val modes = listOf(MODE_AUTO, MODE_ON, MODE_SWAPPED, MODE_OFF)
private const val TYPE_INTERNAL = 1 private const val TYPE_INTERNAL = 1
private const val TYPE_EXTERNAL = 2 private const val TYPE_EXTERNAL = 2
private val knownModels = setOf("retroid pocket duo", "ayn thor") 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? = fun display(context: Context, displayManager: DisplayManager, primaryDisplayId: Int, mode: String = SessionPrefs.dualScreenMode(context)): Display? =
when (mode) { when (mode) {
MODE_OFF -> null 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) else -> if (dockedToDisplay(displayManager, primaryDisplayId)) null else builtInDisplay(displayManager, primaryDisplayId)
}?.takeUnless { taken(it.displayId) } }?.takeUnless { taken(it.displayId) }
@@ -3,12 +3,6 @@ package com.droiddeck.launcher.input
import android.view.KeyEvent import android.view.KeyEvent
object GuestKeys { 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. */ /** 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 { fun send(event: KeyEvent, sendKey: (code: Int, down: Boolean) -> Unit): Boolean {
val down = event.action == KeyEvent.ACTION_DOWN val down = event.action == KeyEvent.ACTION_DOWN
@@ -56,7 +56,7 @@ object BattleNet {
Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed", product = "aqua"), Title("aqua", "Avowed", "AQUA", 2457220, shop = "avowed", product = "aqua"),
) )
val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" } val STORE: List<Title> get() = TITLES.distinctBy { it.code }.filter { it.uid != "d3cn" && it.code != "WoWC" && it.code != "WoWF" }
// Blizzard's China client installs some products under a CN uid; they are the same games and keep their store identity. // Blizzard's China client installs some products under a CN uid; they are the same games and keep their store identity.
private val CN_UIDS = mapOf("s2_cn" to "s2", "osic" to "osi", "anbs_cn" to "anbs") private val CN_UIDS = mapOf("s2_cn" to "s2", "osic" to "osi", "anbs_cn" to "anbs")
@@ -112,16 +112,9 @@ object BwrapSpawner {
return out 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 { internal fun plan(context: Context, request: JSONObject, dir: File): Plan {
val rootfs = LinuxRuntime.rootDir(context).path 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 root = File(dir, "root").apply { mkdirs() }
val binds = ArrayList<Bind>() val binds = ArrayList<Bind>()
var scratch = 0 var scratch = 0
@@ -191,10 +184,7 @@ object BwrapSpawner {
request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> env[k] = e.getString(k) } } request.optJSONObject("env")?.let { e -> e.keys().forEach { k -> env[k] = e.getString(k) } }
withoutRootfsSettings(env, rootfs) withoutRootfsSettings(env, rootfs)
val envTool = request.optString("envTool").takeIf { it.startsWith("/") } val envTool = request.optString("envTool").takeIf { it.startsWith("/") }
if (envTool == null && binds.any { it.guest == "/dev" }) { if (envTool == null && binds.any { it.guest == "/dev" }) gpu(rootfs, root, env)?.forEach { addBind(it) }
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) }
}
val libc = listOf("/usr/lib/aarch64-linux-gnu/libc.so.6", "/lib/aarch64-linux-gnu/libc.so.6").map { hostPath(binds, root.path, 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) } 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) } zypakShims(binds, root, dir).forEach { addBind(it) }
@@ -221,7 +211,6 @@ object BwrapSpawner {
} }
private const val GPU_DIR = "/run/droiddeck-gpu" 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 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") 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( internal fun gpu(
rootfs: String, root: File, env: MutableMap<String, String>, 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>? { ): 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") val driver = runtimeLib(rootfs, "libvulkan_freedreno.so")
if (driver == null || !kgslAvailable) return null if (driver == null || !kgslAvailable) return null
if (env.containsKey("VK_ICD_FILENAMES") || env.containsKey("VK_DRIVER_FILES")) 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") 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") 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")) 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_DRIVER_FILES"] = "$GPU_DIR/freedreno_icd.json"
env["VK_ICD_FILENAMES"] = "$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")) { if (!env.containsKey("MESA_LOADER_DRIVER_OVERRIDE") && !env.containsKey("GALLIUM_DRIVER")) {
@@ -257,14 +245,7 @@ object BwrapSpawner {
return binds return binds
} }
private fun icdDir(root: File, icd: File): Bind { private fun bridgeGpu(rootfs: String, root: File, env: MutableMap<String, String>, socket: String): List<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>? {
val driver = File(rootfs, "usr/local/lib/vkbridge/libvulkan_droidbridge.so") 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 } if (!driver.isFile) { Log.w(TAG, "gpu: vkbridge session but no bridge ICD in the runtime"); return null }
val binds = ArrayList<Bind>() 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 } }.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") 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")) 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_DRIVER_FILES"] = "$GPU_DIR/vkbridge_icd.json"
env["VK_ICD_FILENAMES"] = "$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")) { if (!env.containsKey("MESA_LOADER_DRIVER_OVERRIDE") && !env.containsKey("GALLIUM_DRIVER")) {
@@ -557,9 +537,6 @@ object BwrapSpawner {
return f 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) { private fun run(context: Context, plan: Plan, client: LocalSocket, out: DataOutputStream, id: Int) {
val verbose = plan.env["DROIDDECK_PROOT_VERBOSE"]?.toIntOrNull() val verbose = plan.env["DROIDDECK_PROOT_VERBOSE"]?.toIntOrNull()
val native = if (NativeGuest.forSession(context)) nativeLaunch(context, plan) else null val native = if (NativeGuest.forSession(context)) nativeLaunch(context, plan) else null
@@ -581,7 +558,7 @@ object BwrapSpawner {
ProcessBuilder(cmd).redirectErrorStream(true).directory(plan.root).also { b -> ProcessBuilder(cmd).redirectErrorStream(true).directory(plan.root).also { b ->
b.environment().apply { b.environment().apply {
clear() clear()
putAll(prootEnvironment(plan, envTool)) if (!envTool) putAll(plan.env)
put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path) put("PROOT_LOADER", LinuxRuntime.prootLoader(context).path)
put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path) put("PROOT_TMP_DIR", LinuxRuntime.prootTempDir(context).path)
if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1") if (SessionPrefs.prootNoSeccomp(context)) put("PROOT_NO_SECCOMP", "1")
@@ -1,33 +1,25 @@
package com.droiddeck.launcher.runtime package com.droiddeck.launcher.runtime
import android.content.Context import android.content.Context
import com.droiddeck.launcher.stores.battlenet.BattleNetInstall import com.droiddeck.launcher.agent.AgentException
import com.droiddeck.launcher.agent.AgentGuest
import org.json.JSONArray import org.json.JSONArray
import org.json.JSONObject import org.json.JSONObject
import java.io.File
import java.time.Instant import java.time.Instant
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.LinkedBlockingQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
object CurseForgeApp { object CurseForgeApp {
const val NAME = "CurseForge" const val NAME = "CurseForge"
const val FEED = "https://curseforge.overwolf.com/electron/linux/latest-linux.yml" const val FEED = "https://curseforge.overwolf.com/electron/linux/latest-linux.yml"
internal const val WOW = 1 internal const val WOW = 1
const val HELPER = "/usr/local/bin/droiddeck-curseforge" const val HELPER = "/usr/local/bin/droiddeck-curseforge"
internal const val AGENT = "/usr/local/bin/droiddeck-agent"
private const val READY_MS = 120_000L private const val READY_MS = 120_000L
private const val INSTALL_MS = 300_000L private const val INSTALL_MS = 300_000L
private const val OUT_OF_DATE = 2
enum class Start { READY, BUSY, FAILED } enum class Start { READY, BUSY, NO_DISPLAY, FAILED }
class Started(val state: Start, val inspector: String? = null) class Started(val state: Start, val inspector: String? = null)
class Project(val id: String, val installedModId: String, val folders: List<String>, val update: Boolean) private val INSPECTOR = Regex("ws://127\\.0\\.0\\.1:[0-9]{4,5}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
internal val INSPECTOR = Regex("ws://127\\.0\\.0\\.1:[0-9]{4,5}/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
class Failure(message: String, val code: String? = null) : Exception(message) { class Failure(message: String, val code: String? = null) : Exception(message) {
val gone get() = code == "DEVTOOLS_UNREACHABLE" val gone get() = code == "DEVTOOLS_UNREACHABLE"
@@ -39,19 +31,14 @@ object CurseForgeApp {
internal fun dir(app: UserApps.App): String? = app.args.firstOrNull()?.takeIf { it.startsWith("/") } internal fun dir(app: UserApps.App): String? = app.args.firstOrNull()?.takeIf { it.startsWith("/") }
internal fun helperArgv(command: String, dir: String): List<String> = listOf(HELPER, command, dir) fun holdArgs(app: UserApps.App): List<String>? = dir(app)?.let { listOf("hold", it) }
internal fun evalArgv(inspector: String, expression: String, timeoutMs: Long): List<String> =
listOf(AGENT, "--cdp-inspector", inspector, (timeoutMs / 1000.0).toString(), expression)
internal fun lastJson(lines: List<String>): JSONObject? =
lines.asReversed().firstNotNullOfOrNull { line -> runCatching { JSONObject(line.trim()) }.getOrNull() }
internal fun inspectorUrl(stdout: String): String? = stdout.lineSequence().map { it.trim() }.lastOrNull { INSPECTOR.matches(it) } internal fun inspectorUrl(stdout: String): String? = stdout.lineSequence().map { it.trim() }.lastOrNull { INSPECTOR.matches(it) }
internal fun startState(exitCode: Int): Start = when (exitCode) { internal fun startState(exitCode: Int): Start = when (exitCode) {
0 -> Start.READY 0 -> Start.READY
3 -> Start.BUSY 3 -> Start.BUSY
4 -> Start.NO_DISPLAY
else -> Start.FAILED else -> Start.FAILED
} }
@@ -72,8 +59,6 @@ object CurseForgeApp {
JSONObject().put("instanceId", guid).put("projectId", projectId.toLong()).put("categoryClassId", 1) JSONObject().put("instanceId", guid).put("projectId", projectId.toLong()).put("categoryClassId", 1)
.put("installLatestFile", true).put("installSource", 4) .put("installLatestFile", true).put("installSource", 4)
private const val CACHE = "__droiddeckServices"
private const val SERVICES = """(() => { private const val SERVICES = """(() => {
const seen = new Set(), out = {}; const seen = new Set(), out = {};
const walk = (o, d) => { const walk = (o, d) => {
@@ -93,8 +78,7 @@ object CurseForgeApp {
internal fun expression(service: String, method: String, args: JSONArray?, pick: String = "r => r"): String { internal fun expression(service: String, method: String, args: JSONArray?, pick: String = "r => r"): String {
val name = JSONObject.quote(method) val name = JSONObject.quote(method)
val run = if (args == null) "true" else "($pick)(await s[$name](...$args))" val run = if (args == null) "true" else "($pick)(await s[$name](...$args))"
val key = JSONObject.quote(service) val inner = "(async () => { const s = $SERVICES[${JSONObject.quote(service)}]; " +
val inner = "(async () => { let m = globalThis.$CACHE; if (!m || !m[$key]) m = globalThis.$CACHE = $SERVICES; const s = m[$key]; " +
"if (!s || typeof s[$name] !== 'function') return { missing: true }; " + "if (!s || typeof s[$name] !== 'function') return { missing: true }; " +
"return { value: $run }; })()" "return { value: $run }; })()"
return "(() => { const w = require('electron').BrowserWindow.getAllWindows()" + return "(() => { const w = require('electron').BrowserWindow.getAllWindows()" +
@@ -148,156 +132,85 @@ object CurseForgeApp {
return detected?.takeIf { it.isNotBlank() } return detected?.takeIf { it.isNotBlank() }
} }
internal fun parseProjects(value: Any?): List<Project> { internal fun projectIds(value: Any?): Set<String> {
val list = value as? JSONArray ?: return emptyList() val list = value as? JSONArray ?: return emptySet()
return (0 until list.length()).mapNotNull { list.optJSONObject(it) }.mapNotNull { p -> return (0 until list.length()).mapNotNull { list.opt(it)?.toString()?.takeIf { id -> id.isNotBlank() && id != "null" } }.toSet()
val id = p.optString("id").takeIf { it.isNotBlank() && it != "null" } ?: return@mapNotNull null
val folders = p.optJSONArray("folders")?.let { f -> (0 until f.length()).mapNotNull { f.optString(it).takeIf(String::isNotBlank) } }.orEmpty()
Project(id, p.optString("installedModId"), folders, p.optInt("status") == OUT_OF_DATE && !p.optBoolean("locked"))
}
} }
internal fun owner(projects: List<Project>, folder: String): Project? = private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r"): Any? {
projects.firstOrNull { project -> project.folders.any { it.equals(folder, ignoreCase = true) } } val request = JSONObject().put("kind", "cdp").put("inspector", inspector).put("commandLineApi", true)
.put("expression", expression(service, method, args, pick)).put("timeout", timeoutMs / 1000.0)
internal fun byFolder(projects: List<Project>): Map<String, Project> = projects.flatMap { project -> project.folders.map { it.lowercase() to project } }.toMap() return unwrap(AgentGuest.call(context, request, timeoutMs + 3_000, trusted = true))
internal fun onDisk(projects: List<Project>, addOns: File): List<Project> {
val names = addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }.map { it.name.lowercase() }.toSet()
return projects.filter { project -> WowAddons.present(project.folders) { it.lowercase() in names } }
} }
internal var guest: (Context, List<String>, AtomicBoolean?, (String) -> Unit) -> Int = { context, argv, cancelled, onLine -> private fun helper(context: Context, command: String, dir: String, timeoutMs: Long): JSONObject? {
GuestCommand.run(context, argv, logName = "curseforge", extraBinds = BattleNetInstall.binds(context), fastPath = true, val request = JSONObject().put("kind", "exec").put("argv", JSONArray(listOf(HELPER, command, dir))).put("timeout", timeoutMs / 1000.0)
cancelled = cancelled, redact = INSPECTOR, onLine = onLine) return runCatching { AgentGuest.call(context, request, timeoutMs + 5_000, trusted = true) }.getOrNull()
} }
private val holds = ConcurrentHashMap<String, AtomicBoolean>() fun start(context: Context, app: UserApps.App): Started {
private val connected = ConcurrentHashMap.newKeySet<String>()
private fun lines(context: Context, argv: List<String>): List<String> {
val out = ArrayList<String>()
guest(context, argv, null) { out += it }
return out
}
private fun call(context: Context, inspector: String, service: String, method: String, args: JSONArray?, timeoutMs: Long, pick: String = "r => r"): Any? =
unwrap(lastJson(lines(context, evalArgv(inspector, expression(service, method, args, pick), timeoutMs))) ?: throw Failure("CurseForge gave no answer"))
private sealed class Launch {
class Url(val inspector: String) : Launch()
class Exit(val code: Int) : Launch()
}
private fun launch(context: Context, dir: String, hold: AtomicBoolean): Launch? {
val first = LinkedBlockingQueue<Launch>()
Thread({
val code = runCatching {
guest(context, helperArgv("start", dir), hold) { line -> inspectorUrl(line)?.let { first.offer(Launch.Url(it)) } }
}.getOrDefault(-1)
first.offer(Launch.Exit(code))
}, "curseforge-headless").apply { isDaemon = true; start() }
return first.poll(READY_MS, TimeUnit.MILLISECONDS)
}
fun start(context: Context, app: UserApps.App, hold: AtomicBoolean): Started {
val dir = dir(app) ?: return Started(Start.FAILED) val dir = dir(app) ?: return Started(Start.FAILED)
if (hold.get()) return Started(Start.FAILED) val answer = helper(context, "start", dir, 90_000)
holds.put(dir, hold)?.takeIf { it !== hold }?.let { if (answer == null || !answer.optBoolean("ok") || answer.optBoolean("timedOut")) {
it.set(true) stop(context, app, null)
runCatching { lines(context, helperArgv("stop", dir)) } return Started(Start.FAILED)
} }
val inspector = when (val first = launch(context, dir, hold)) { val state = startState(answer.optInt("exitCode", -1))
is Launch.Url -> first.inspector if (state == Start.BUSY || state == Start.NO_DISPLAY) return Started(state)
is Launch.Exit -> if (startState(first.code) == Start.BUSY) { val inspector = inspectorUrl(answer.optJSONObject("stdout")?.optString("text").orEmpty())
holds.remove(dir, hold) if (state != Start.READY || inspector == null) {
return Started(Start.BUSY) stop(context, app, null)
} else null
null -> null
}
if (inspector == null) {
stop(context, app, null, hold)
return Started(Start.FAILED) return Started(Start.FAILED)
} }
val deadline = System.currentTimeMillis() + READY_MS val deadline = System.currentTimeMillis() + READY_MS
while (System.currentTimeMillis() < deadline && !hold.get()) { while (System.currentTimeMillis() < deadline) {
if (runCatching { call(context, inspector, "InstalledProjectsAppService", "installAddon", null, 10_000) }.isSuccess) return Started(Start.READY, inspector) val ready = runCatching { call(context, inspector, "InstalledProjectsAppService", "installAddon", null, 10_000) }
if (ready.isSuccess) return Started(Start.READY, inspector)
val error = ready.exceptionOrNull()
if (error is AgentException && error.code == "NO_ACTIVE_SESSION") break
Thread.sleep(1_000) Thread.sleep(1_000)
} }
stop(context, app, inspector, hold) stop(context, app, inspector)
return Started(Start.FAILED) return Started(Start.FAILED)
} }
fun stop(context: Context, app: UserApps.App, inspector: String?, hold: AtomicBoolean) { fun stop(context: Context, app: UserApps.App, inspector: String?) {
val dir = dir(app) ?: return val dir = dir(app) ?: return
if (holds[dir] !== hold) {
hold.set(true)
return
}
if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") } if (inspector != null) runCatching { call(context, inspector, "CoreService", "shutdown", JSONArray(), 30_000, "r => true") }
hold.set(true) helper(context, "stop", dir, 30_000)
inspector?.let(connected::remove)
if (holds.remove(dir, hold)) runCatching { lines(context, helperArgv("stop", dir)) }
} }
private fun connect(context: Context, inspector: String) { private fun connect(context: Context, inspector: String) {
if (inspector in connected) return
call(context, inspector, "CoreService", "connect", JSONArray(), 120_000, "r => true") call(context, inspector, "CoreService", "connect", JSONArray(), 120_000, "r => true")
connected += inspector
} }
private fun instances(context: Context, inspector: String): Any? =
call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 30_000,
"r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))")
fun instance(context: Context, inspector: String, root: String, flavorDir: String): String { fun instance(context: Context, inspector: String, root: String, flavorDir: String): String {
connect(context, inspector) connect(context, inspector)
instanceFor(instances(context, inspector), flavorDir, null)?.let { return it }
val detected = call(context, inspector, "GameDetectionAppService", "detectGameFromPath", JSONArray().put(root).put(WOW), 60_000) as? JSONObject val detected = call(context, inspector, "GameDetectionAppService", "detectGameFromPath", JSONArray().put(root).put(WOW), 60_000) as? JSONObject
return instanceFor(instances(context, inspector), flavorDir, detected?.optString("gameInstanceGuid")) ?: throw Failure("CurseForge did not find $flavorDir") val instances = call(context, inspector, "GameAppService", "getGameInstances", JSONArray().put(WOW), 30_000,
"r => (r || []).map(i => ({ guid: i.guid, installPath: i.installPath }))")
return instanceFor(instances, flavorDir, detected?.optString("gameInstanceGuid")) ?: throw Failure("CurseForge did not find $flavorDir")
} }
fun search(context: Context, inspector: String, guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): WowAddonCatalog.Page = fun search(context: Context, inspector: String, guid: String, text: String, sort: WowAddonCatalog.Sort, page: Int): WowAddonCatalog.Page =
parseSearch(call(context, inspector, "ProjectAppService", "search", JSONArray().put(searchRequest(guid, text, sort, page)), 60_000)) parseSearch(call(context, inspector, "ProjectAppService", "search", JSONArray().put(searchRequest(guid, text, sort, page)), 60_000))
fun projects(context: Context, inspector: String, guid: String, rescan: Boolean = false): List<Project> { fun installed(context: Context, inspector: String, guid: String): Set<String> {
connect(context, inspector) connect(context, inspector)
if (rescan) call(context, inspector, "GameDetectionAppService", "scanGameInstance", JSONArray().put(guid), 120_000) return projectIds(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, "r => (r || []).map(p => String(p.id))"))
return parseProjects(call(context, inspector, "InstalledProjectsAppService", "getProjects", JSONArray().put(guid), 30_000, PROJECTS))
} }
private const val PROJECTS = "r => (r || []).map(p => ({ id: String(p.id), installedModId: p.installedModId, status: p.status, " + fun install(context: Context, inspector: String, guid: String, projectId: String): Boolean {
"locked: !!(p.installedVersion && p.installedVersion.isLocked), " + connect(context, inspector)
"folders: ((p.installedVersion && p.installedVersion.addonFolders) || []).map(f => f.name) }))" if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return false
private fun settle(context: Context, inspector: String, guid: String, done: (List<Project>) -> Boolean): List<Project>? {
val deadline = System.currentTimeMillis() + INSTALL_MS val deadline = System.currentTimeMillis() + INSTALL_MS
while (System.currentTimeMillis() < deadline) { while (System.currentTimeMillis() < deadline) {
val listed = runCatching { projects(context, inspector, guid) } val listed = runCatching { installed(context, inspector, guid) }
val error = listed.exceptionOrNull() val error = listed.exceptionOrNull()
if (error is Failure && error.gone) throw error if (error is Failure && error.gone || error is AgentException && error.code == "NO_ACTIVE_SESSION") throw error
listed.getOrNull()?.let { if (done(it)) return it } if (projectId in listed.getOrDefault(emptySet())) return true
Thread.sleep(1_000) Thread.sleep(1_000)
} }
return null return false
}
fun install(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
connect(context, inspector)
if (call(context, inspector, "InstalledProjectsAppService", "installAddon", JSONArray().put(installRequest(guid, projectId)), 300_000) != true) return null
return settle(context, inspector, guid) { list -> list.any { it.id == projectId } }
}
fun update(context: Context, inspector: String, guid: String, projectId: String): List<Project>? {
connect(context, inspector)
if (call(context, inspector, "InstalledProjectsAppService", "updateMod", JSONArray().put(guid).put(projectId.toLong()), 300_000) != true) return null
return settle(context, inspector, guid) { list -> list.any { it.id == projectId && !it.update } }
}
fun uninstall(context: Context, inspector: String, guid: String, project: Project): List<Project>? {
connect(context, inspector)
val failed = call(context, inspector, "InstalledProjectsAppService", "deleteMods", JSONArray().put(guid).put(JSONArray().put(project.installedModId)), 120_000) as? JSONArray
if (failed == null || failed.length() > 0) return null
return settle(context, inspector, guid) { list -> list.none { it.id == project.id } }
} }
} }
@@ -1,102 +0,0 @@
package com.droiddeck.launcher.runtime
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.R
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.session.SessionState
import java.io.File
import org.json.JSONArray
import org.json.JSONObject
object DeckyStore {
private const val TAG = "DeckyStore"
private const val LISTING = "https://plugins.deckbrew.xyz/plugins"
private const val ARTIFACTS = "https://cdn.tzatzikiweeb.moe/file/steam-deck-homebrew/versions/"
data class Version(val name: String, val hash: String)
data class Plugin(val name: String, val author: String, val description: String, val tags: List<String>, val downloads: Long, val imageUrl: String, val versions: List<Version>) {
val latest: Version? get() = versions.firstOrNull()
}
data class Installed(val name: String, val folder: String, val author: String, val version: String)
fun parseListing(body: String): List<Plugin> {
val array = JSONArray(body)
return (0 until array.length()).mapNotNull { i ->
val row = array.optJSONObject(i) ?: return@mapNotNull null
val name = row.optString("name").takeIf { it.isNotBlank() } ?: return@mapNotNull null
val versions = row.optJSONArray("versions")?.let { list ->
(0 until list.length()).mapNotNull { v ->
val version = list.optJSONObject(v) ?: return@mapNotNull null
val hash = version.optString("hash")
if (!hash.matches(Regex("(?i)[0-9a-f]{64}"))) null else Version(version.optString("name"), hash.lowercase())
}
}.orEmpty()
if (versions.isEmpty()) return@mapNotNull null
val tags = row.optJSONArray("tags")?.let { list -> (0 until list.length()).map { list.optString(it) } }.orEmpty()
val downloads = row.optJSONArray("versions")?.let { list -> (0 until list.length()).sumOf { list.optJSONObject(it)?.optLong("downloads") ?: 0L } } ?: 0L
val image = row.optString("image_url").takeIf { it.startsWith("https://") }.orEmpty()
Plugin(name, row.optString("author"), row.optString("description"), tags, downloads, image, versions)
}
}
fun fetch(): List<Plugin>? {
val body = Downloader.downloadString(LISTING) ?: return null
return runCatching { parseListing(body) }.onFailure { Log.w(TAG, "store listing", it) }.getOrNull()
}
fun pluginsDir(context: Context) = File(LinuxRuntime.rootDir(context), "root/homebrew/plugins")
fun installed(context: Context): List<Installed> =
pluginsDir(context).listFiles().orEmpty()
.filter { it.isDirectory && !it.name.startsWith(".droiddeck-") }
.mapNotNull { folder ->
runCatching {
val meta = JSONObject(File(folder, "plugin.json").readText())
val version = runCatching { JSONObject(File(folder, "package.json").readText()).optString("version") }.getOrDefault("")
Installed(meta.getString("name"), folder.name, meta.optString("author"), version)
}.getOrNull()
}
.sortedBy { it.name.lowercase() }
fun updateAvailable(installed: Installed, plugin: Plugin?): Boolean {
val latest = plugin?.latest?.name ?: return false
return installed.version.isNotEmpty() && latest != installed.version
}
fun install(context: Context, plugin: Plugin, version: Version, progress: (String, Int) -> Unit): String? {
if (SessionState.running) return context.getString(R.string.deckymgr_stop_session_plugin)
if (DeckyManager.installed(context) == null) return context.getString(R.string.deckymgr_loader_required)
val cache = File(context.cacheDir, "decky-store").apply { mkdirs() }
val zip = File(cache, "${version.hash}.zip")
try {
val label = context.getString(R.string.decky_store_downloading, plugin.name)
progress(label, -1)
val ok = Downloader.downloadFile("$ARTIFACTS${version.hash}.zip", zip, true, version.hash) { fraction ->
progress(label, if (fraction < 0) -1 else (fraction * 100).toInt().coerceIn(0, 100))
}
if (!ok) return context.getString(R.string.decky_store_download_failed, plugin.name)
return DeckyManager.installPluginZip(context, zip, progress)
} finally {
zip.delete()
}
}
fun remove(context: Context, plugin: Installed): String? {
if (SessionState.running) return context.getString(R.string.deckymgr_stop_session_plugin)
val plugins = pluginsDir(context)
val folder = File(plugins, plugin.folder)
if (folder.parentFile?.canonicalFile != plugins.canonicalFile) return context.getString(R.string.decky_store_remove_failed)
if (!folder.deleteRecursively()) return context.getString(R.string.decky_store_remove_failed)
val settings = File(plugins.parentFile, "settings/loader.json")
runCatching {
val json = JSONObject(settings.readText())
for (key in listOf("pluginOrder", "frozenPlugins", "hiddenPlugins", "disabled_plugins")) {
val values = json.optJSONArray(key) ?: continue
json.put(key, JSONArray((0 until values.length()).map { values.get(it) }.filter { it != plugin.name }))
}
settings.writeText(json.toString(4))
}
return null
}
}
@@ -32,9 +32,6 @@ object DesktopLanguage {
internal fun baseUrl(desktopUrl: String) = desktopUrl.substringBeforeLast('/') + "/" 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") 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. */ /** 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 } val pending = candidates(locale).filterNot { marker(root, tag, it).isFile }
if (pending.isEmpty()) return true if (pending.isEmpty()) return true
val base = baseUrl(BuildConfig.DESKTOP_KDE_URL) 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 var complete = true
for (name in pending) { for (name in pending) {
val pack = index[name] val pack = index[name]
@@ -14,22 +14,20 @@ import java.util.concurrent.atomic.AtomicBoolean
object GuestCommand { object GuestCommand {
fun run(context: Context, argv: List<String>, fakeRoot: Boolean = false, logName: String? = null, fun run(context: Context, argv: List<String>, fakeRoot: Boolean = false, logName: String? = null,
linkDir: File? = null, extraBinds: List<String>? = null, fastPath: Boolean = false, cancelled: AtomicBoolean? = null, linkDir: File? = null, extraBinds: List<String>? = null, fastPath: Boolean = false, cancelled: AtomicBoolean? = null,
redact: Regex? = null, onLine: (String) -> Unit): Int { onLine: (String) -> Unit): Int {
val log = logName?.let { val log = logName?.let {
try { try {
File(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter() File(File(LinuxRuntime.logDir(context), SessionPaths.TOOLS_DIR).apply { mkdirs() }, "$it.log").printWriter()
} catch (e: Exception) { null } } catch (e: Exception) { null }
} }
log?.println("== ${java.util.Date()} ${redacted(argv.joinToString(" "), redact)}") log?.println("== ${java.util.Date()} ${argv.joinToString(" ")}")
try { try {
return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(redacted(line, redact)); log?.flush(); onLine(line) } return runLogged(context, argv, fakeRoot, linkDir, extraBinds, fastPath, cancelled) { line -> log?.println(line); log?.flush(); onLine(line) }
} finally { } finally {
log?.close() log?.close()
} }
} }
internal fun redacted(text: String, redact: Regex?): String = redact?.replace(text, "<redacted>") ?: text
private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, linkDir: File?, extraBinds: List<String>?, private fun runLogged(context: Context, argv: List<String>, fakeRoot: Boolean, linkDir: File?, extraBinds: List<String>?,
fastPath: Boolean, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int { fastPath: Boolean, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int {
val root = LinuxRuntime.rootDir(context) val root = LinuxRuntime.rootDir(context)
@@ -275,15 +275,12 @@ class LinuxNetworkLinkComponent(
* crash or power cut can keep the rename and lose the data, leaving a file of NUL bytes. * crash or power cut can keep the rename and lose the data, leaving a file of NUL bytes.
*/ */
private fun replace(file: File, text: String) { private fun replace(file: File, text: String) {
synchronized(WRITES) { val staged = File(file.path + ".staged")
if (runCatching { file.isFile && file.readText() == text }.getOrDefault(false)) return java.io.FileOutputStream(staged).use { out ->
val staged = File(file.path + ".staged") out.write(text.toByteArray())
java.io.FileOutputStream(staged).use { out -> out.fd.sync()
out.write(text.toByteArray())
out.fd.sync()
}
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
} }
if (!staged.renameTo(file)) throw IOException("Could not replace $file")
} }
private fun writeResolver(properties: LinkProperties?) { private fun writeResolver(properties: LinkProperties?) {
@@ -336,8 +333,6 @@ class LinuxNetworkLinkComponent(
seededMac { Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID) } seededMac { Settings.Secure.getString(appContext.contentResolver, Settings.Secure.ANDROID_ID) }
companion object { companion object {
private val WRITES = Any()
internal fun gateways(properties: LinkProperties?, capabilities: NetworkCapabilities?): List<InetAddress> = internal fun gateways(properties: LinkProperties?, capabilities: NetworkCapabilities?): List<InetAddress> =
listOf(Inet4Address::class.java, Inet6Address::class.java).mapNotNull { family -> listOf(Inet4Address::class.java, Inet6Address::class.java).mapNotNull { family ->
properties?.routes.orEmpty() properties?.routes.orEmpty()
@@ -76,6 +76,7 @@ object NativeGuest {
fun environment(root: File, 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_ROOT" to root.path,
"DDNATV_EXEC" to execLoader.orEmpty(), "DDNATV_EXEC" to execLoader.orEmpty(),
"LD_LIBRARY_PATH" to libraryPath(root),
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"), "LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
).filterValues { it.isNotEmpty() } ).filterValues { it.isNotEmpty() }
@@ -83,10 +84,10 @@ object NativeGuest {
* The host command line for the guest program at [program] (an absolute guest path to a real * The host command line for the guest program at [program] (an absolute guest path to a real
* file, not a symlink). * 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 loader = checkNotNull(loader(root)) { "no glibc loader in ${root.path}" }
val host = File(root, program.removePrefix("/")) val host = File(root, program.removePrefix("/"))
val launch = listOf(loader.path, "--library-path", libraryPath, "--argv0", host.name, host.path) + args val launch = listOf(loader.path, "--argv0", host.name, host.path) + args
return simulator(root)?.let { it + launch } ?: (execPrefix(loader.path) + launch) return simulator(root)?.let { it + launch } ?: (execPrefix(loader.path) + launch)
} }
@@ -99,6 +100,7 @@ object NativeGuest {
"DDNATV_HOSTNAME" to hostname.orEmpty(), "DDNATV_HOSTNAME" to hostname.orEmpty(),
"DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" }, "DDNATV_BINDS" to binds.joinToString("|") { if (it.contains(':')) it else "$it:$it" },
"DDNATV_PRELOAD" to preload.joinToString(":"), "DDNATV_PRELOAD" to preload.joinToString(":"),
"LD_LIBRARY_PATH" to libraryPath(root),
"LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"), "LD_PRELOAD" to (preload.map { File(root, it.removePrefix("/")).path } + hook(root).path).joinToString(":"),
).filterValues { it.isNotEmpty() } ).filterValues { it.isNotEmpty() }
} }
@@ -271,9 +273,7 @@ object NativeGuest {
fun builder(root: File, cwd: String, argv: List<String>, env: Map<String, String>, preload: List<String> = emptyList()): ProcessBuilder { fun builder(root: File, cwd: String, argv: List<String>, env: Map<String, String>, preload: List<String> = emptyList()): ProcessBuilder {
val program = argv.first() val program = argv.first()
val callerDirs = env["LD_LIBRARY_PATH"]?.takeIf { it.isNotEmpty() }?.split(':').orEmpty() val cmd = command(root, program, argv.drop(1))
val rootDirs = libraryPath(root).split(':').filterNot { it in callerDirs }
val cmd = command(root, program, argv.drop(1), (callerDirs + rootDirs).joinToString(":"))
val builder = ProcessBuilder(cmd).redirectErrorStream(false) val builder = ProcessBuilder(cmd).redirectErrorStream(false)
builder.directory(File(root, cwd.removePrefix("/")).takeIf { it.isDirectory } ?: root) builder.directory(File(root, cwd.removePrefix("/")).takeIf { it.isDirectory } ?: root)
builder.environment().apply { builder.environment().apply {
@@ -29,7 +29,6 @@ object WowAddonCatalog {
val downloads: Long, val downloads: Long,
val updated: Long, val updated: Long,
val thumb: String?, val thumb: String?,
val folders: List<String> = emptyList(),
) )
class Page(val items: List<Addon>, val more: Boolean) class Page(val items: List<Addon>, val more: Boolean)
@@ -115,11 +114,9 @@ object WowAddonCatalog {
} }
val thumbs = o.optJSONArray("UIIMG_Thumbs") val thumbs = o.optJSONArray("UIIMG_Thumbs")
val thumb = if (thumbs != null && thumbs.length() > 0) thumbs.optString(0).ifEmpty { null } else null val thumb = if (thumbs != null && thumbs.length() > 0) thumbs.optString(0).ifEmpty { null } else null
val dirs = o.optJSONArray("UIDir")
val folders = if (dirs == null) emptyList() else (0 until dirs.length()).map { dirs.optString(it).trim() }.filter { it.isNotEmpty() }
val addon = Addon( val addon = Addon(
id, o.optString("UIName"), o.optString("UIAuthorName"), o.optString("UIVersion"), id, o.optString("UIName"), o.optString("UIAuthorName"), o.optString("UIVersion"),
o.optString("UIDownloadTotal").toLongOrNull() ?: 0L, o.optLong("UIDate"), thumb, folders, o.optString("UIDownloadTotal").toLongOrNull() ?: 0L, o.optLong("UIDate"), thumb,
) )
out.add(Entry(addon, o.optString("UICATID"), flavors, o.optString("UIDownloadMonthly").toLongOrNull() ?: 0L)) out.add(Entry(addon, o.optString("UICATID"), flavors, o.optString("UIDownloadMonthly").toLongOrNull() ?: 0L))
} }
@@ -244,32 +241,9 @@ object WowAddonCatalog {
return details.version return details.version
} }
private fun normVersion(v: String) = v.trim().removePrefix("v").removePrefix("V").trim().lowercase() internal fun sameVersion(a: String, b: String): Boolean {
fun norm(v: String) = v.trim().removePrefix("v").removePrefix("V").trim().lowercase()
internal fun sameVersion(a: String, b: String): Boolean = normVersion(a) == normVersion(b) return norm(a) == norm(b)
private val NUMERIC_VERSION = Regex("""^(\d+(?:\.\d+)*)(.*)$""")
private fun numericVersion(v: String): Pair<List<Long>, String>? {
val match = NUMERIC_VERSION.matchEntire(normVersion(v)) ?: return null
val parts = match.groupValues[1].split('.').map { it.toLongOrNull() ?: return null }
return parts to match.groupValues[2]
}
internal fun newer(have: String, latest: String): Boolean? {
val (a, aRest) = numericVersion(have) ?: return null
val (b, bRest) = numericVersion(latest) ?: return null
for (i in 0 until maxOf(a.size, b.size)) {
val x = a.getOrElse(i) { 0L }
val y = b.getOrElse(i) { 0L }
if (x != y) return y > x
}
return if (aRest == bRest) false else null
}
internal fun offersUpdate(have: String?, latest: String, sameSource: Boolean): Boolean {
if (have.isNullOrBlank() || latest.isBlank() || sameVersion(have, latest)) return false
return newer(have, latest) ?: sameSource
} }
internal fun findUpdates(entries: List<Entry>, installed: List<WowAddons.Installed>): Map<String, Addon> { internal fun findUpdates(entries: List<Entry>, installed: List<WowAddons.Installed>): Map<String, Addon> {
@@ -279,7 +253,7 @@ object WowAddonCatalog {
val id = item.wowiId ?: return@mapNotNull null val id = item.wowiId ?: return@mapNotNull null
val version = item.version ?: return@mapNotNull null val version = item.version ?: return@mapNotNull null
val latest = byId[id]?.addon?.takeIf { it.summary.isNotBlank() } ?: return@mapNotNull null val latest = byId[id]?.addon?.takeIf { it.summary.isNotBlank() } ?: return@mapNotNull null
if (!offersUpdate(version, latest.summary, sameSource = true) || !seen.add(id)) null else item.name to latest if (sameVersion(version, latest.summary) || !seen.add(id)) null else item.name to latest
}.toMap() }.toMap()
} }
@@ -40,15 +40,11 @@ object WowAddons {
class Addon(val name: String, val root: String) class Addon(val name: String, val root: String)
class Installed(val name: String, val version: String?, val wowiId: String?, val curseId: String? = null) class Installed(val name: String, val version: String?, val wowiId: String?)
class Origin(val id: String, val version: String) class Origin(val id: String, val version: String)
private const val ORIGINS = ".droiddeck-sources" private const val ORIGINS = ".droiddeck-sources"
private const val TOC_VERSION = "Version"
private const val TOC_WOWI_ID = "X-WoWI-ID"
private const val TOC_CURSE_ID = "X-Curse-Project-ID"
private val TOC_KEYS = setOf(TOC_VERSION, TOC_WOWI_ID, TOC_CURSE_ID)
internal const val MAX_EXPANDED_BYTES = 4L * 1024 * 1024 * 1024 internal const val MAX_EXPANDED_BYTES = 4L * 1024 * 1024 * 1024
@@ -73,52 +69,33 @@ object WowAddons {
target.addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") } target.addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }
.map { it.name }.sortedBy { it.lowercase() } .map { it.name }.sortedBy { it.lowercase() }
fun present(folders: List<String>, exists: (String) -> Boolean): Boolean = folders.isNotEmpty() && folders.all(exists)
fun folder(addOns: File, name: String): File? {
val dirs = addOns.listFiles().orEmpty().filter { it.isDirectory && !it.name.startsWith(".") }
return dirs.firstOrNull { it.name == name } ?: dirs.firstOrNull { it.name.equals(name, ignoreCase = true) }
}
fun details(target: Target): List<Installed> { fun details(target: Target): List<Installed> {
val origins = origins(target) val origins = origins(target)
return installed(target).map { name -> return installed(target).map { name ->
val toc = toc(File(target.addOns, name)) val toc = toc(File(target.addOns, name))
val origin = origins[name] val origin = origins[name]
Installed(name, origin?.version ?: toc[TOC_VERSION], origin?.id ?: toc[TOC_WOWI_ID], toc[TOC_CURSE_ID]) Installed(name, origin?.version ?: toc["Version"], origin?.id ?: toc["X-WoWI-ID"])
} }
} }
internal fun tocFields(lines: Sequence<String>, keys: Set<String> = TOC_KEYS): Map<String, String> { internal fun tocFields(text: String): Map<String, String> {
val out = LinkedHashMap<String, String>() val out = LinkedHashMap<String, String>()
for (raw in lines) { for (raw in text.lineSequence()) {
val line = raw.trim().removePrefix("\uFEFF") val line = raw.trim().removePrefix("\uFEFF")
if (!line.startsWith("##") || ':' !in line) continue if (!line.startsWith("##") || ':' !in line) continue
val key = line.removePrefix("##").substringBefore(':').trim() val key = line.removePrefix("##").substringBefore(':').trim()
if (key !in keys || key in out) continue
val value = line.substringAfter(':').trim() val value = line.substringAfter(':').trim()
if (value.isNotEmpty() && '@' !in value) out[key] = value if (key.isNotEmpty() && value.isNotEmpty() && '@' !in value) out.putIfAbsent(key, value)
if (out.size == keys.size) break
} }
return out return out
} }
private fun toc(folder: File): Map<String, String> { private fun toc(folder: File): Map<String, String> {
val tocs = folder.listFiles().orEmpty().filter { it.isFile && it.name.endsWith(".toc", ignoreCase = true) }.sortedWith( val tocs = folder.listFiles().orEmpty().filter { it.isFile && it.name.endsWith(".toc", ignoreCase = true) }
compareBy<File>( val main = tocs.firstOrNull { it.name.dropLast(4).equals(folder.name, ignoreCase = true) }
{ !it.name.dropLast(4).equals(folder.name, ignoreCase = true) }, ?: tocs.firstOrNull { it.name.dropLast(4).replace(SUFFIX, "").equals(folder.name, ignoreCase = true) }
{ !it.name.dropLast(4).replace(SUFFIX, "").equals(folder.name, ignoreCase = true) }, ?: tocs.minByOrNull { it.name.length } ?: return emptyMap()
{ it.name.length }, return runCatching { tocFields(main.readText()) }.getOrDefault(emptyMap())
{ it.name },
),
)
val out = LinkedHashMap<String, String>()
for (file in tocs) {
if (out.size == TOC_KEYS.size) break
val missing = TOC_KEYS - out.keys
runCatching { file.bufferedReader().useLines { tocFields(it, missing) } }.getOrNull()?.let(out::putAll)
}
return out
} }
internal fun parseOrigins(text: String): Map<String, Origin> = text.lineSequence().mapNotNull { line -> internal fun parseOrigins(text: String): Map<String, Origin> = text.lineSequence().mapNotNull { line ->
@@ -0,0 +1,119 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.graphics.PixelFormat
import android.media.ImageReader
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.droiddeck.launcher.agent.AgentGuest
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
import com.droiddeck.launcher.storage.StorageState
import com.droiddeck.launcher.wayland.CompositorHost
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
object BackgroundSession {
private const val TAG = "BackgroundSession"
private const val WIDTH = 1280
private const val HEIGHT = 720
private const val REFRESH_HZ = 60f
private const val BEGIN_MS = 30_000L
private const val AGENT_MS = 120_000L
private const val STOP_MS = 30_000L
private val ended = setOf(SessionPhase.IDLE, SessionPhase.FAILED)
private val main by lazy { Handler(Looper.getMainLooper()) }
private var reader: ImageReader? = null
fun start(context: Context, program: String, args: List<String>): String? {
val app = context.applicationContext
val claim = AtomicBoolean(false)
val began = CountDownLatch(1)
var own: String? = null
main.post {
if (claim.compareAndSet(false, true)) {
own = runCatching { begin(app, program, args) }
.onFailure { Log.w(TAG, "could not start a hidden session for $program", it) }
.getOrNull()
}
began.countDown()
}
if (!began.await(BEGIN_MS, TimeUnit.MILLISECONDS) && claim.compareAndSet(false, true)) return null
began.await()
val session = own ?: return null
val deadline = System.currentTimeMillis() + AGENT_MS
val settle = System.currentTimeMillis() + 5_000
while (System.currentTimeMillis() < deadline) {
if (SessionState.sessionId != session) return null
if (SessionState.running && AgentGuest.hello(app) != null && SessionState.sessionId == session) return session
if (SessionState.phase == SessionPhase.FAILED) break
if (!SessionState.running && SessionState.phase in ended && System.currentTimeMillis() > settle) break
Thread.sleep(250)
}
stop(app, session)
return null
}
fun stop(context: Context, session: String) {
val app = context.applicationContext
if (SessionState.sessionId != session) return
main.post { if (SessionState.sessionId == session) SessionService.stop(app) }
val deadline = System.currentTimeMillis() + STOP_MS
while (live(session) && System.currentTimeMillis() < deadline) Thread.sleep(250)
if (!live(session)) {
main.post { release() }
return
}
Thread {
while (live(session)) Thread.sleep(1_000)
main.post { release() }
}.start()
}
private fun live(session: String) =
SessionState.sessionId == session && (SessionState.running || SessionState.phase !in ended)
private fun begin(context: Context, program: String, args: List<String>): String? {
if (SessionState.running || SessionState.phase !in ended || LinuxRuntimeInstaller.isBusy() ||
SessionState.installing != null || StorageState.cleaning) return null
release()
SessionEvents.begin(context, SessionService.MODE_RUN, SessionPaths.label(SessionService.MODE_RUN, program))
val session = SessionState.sessionId ?: return null
SessionState.stopRequested = false
SessionEvents.transition(SessionPhase.STARTING_COMPOSITOR, "compositor.starting")
var requested = false
try {
val output = CompositorHost.prepare(context)
val size = WIDTH to HEIGHT
SessionState.outputSize = size
SessionState.refreshHz = REFRESH_HZ
CompositorHost.logToSession(context)
CompositorHost.applyHdr(context, SessionPrefs.prefMode(SessionService.MODE_RUN))
val offscreen = ImageReader.newInstance(WIDTH, HEIGHT, PixelFormat.RGBA_8888, 2)
reader = offscreen
offscreen.setOnImageAvailableListener({ it.acquireLatestImage()?.close() }, main)
CompositorHost.start(context, output, offscreen.surface, size, REFRESH_HZ, 0)
CompositorHost.detach(offscreen.surface)
SessionEvents.record("compositor.started")
SessionEvents.transition(SessionPhase.STARTING_GUEST, "guest.starting")
requested = true
SessionService.start(context, SessionService.MODE_RUN, program, programArgs = args.toTypedArray())
return session
} catch (e: Exception) {
if (requested) SessionService.stop(context)
if (!SessionState.running) {
reader?.close()
reader = null
SessionEvents.transition(SessionPhase.FAILED, "hidden.failed", mapOf("error" to e.toString()))
}
throw e
}
}
private fun release() {
if (SessionState.running) return
reader?.close()
reader = null
}
}
@@ -88,8 +88,8 @@ object ComponentUpdater {
logLines(context).mapNotNull { STAMP.find(it)?.groupValues?.get(1) }.maxOrNull() ?: "0" logLines(context).mapNotNull { STAMP.find(it)?.groupValues?.get(1) }.maxOrNull() ?: "0"
private fun lineOf(context: Context, state: JSONObject, p: ComponentsManager.Proton, comp: String): ComponentUpdates.Line? { private fun lineOf(context: Context, state: JSONObject, p: ComponentsManager.Proton, comp: String): ComponentUpdates.Line? {
if (!ComponentUpdates.follows(p) || !ComponentsManager.supports(p, comp)) return null if (!ComponentUpdates.autoFollows(p, comp) || !ComponentsManager.supports(p, comp)) return null
if (comp == "fex") return ComponentUpdates.line("fex", false) if (comp == "fex") return ComponentUpdates.fexLine(p)
val key = "${p.id}|${p.version}" val key = "${p.id}|${p.version}"
val flavors = state.obj("flavors").obj(key) val flavors = state.obj("flavors").obj(key)
val arm64ec = if (flavors.has(comp)) flavors.optBoolean(comp) else ComponentsManager.arm64ec(context, p, comp)?.also { flavors.put(comp, it) } val arm64ec = if (flavors.has(comp)) flavors.optBoolean(comp) else ComponentsManager.arm64ec(context, p, comp)?.also { flavors.put(comp, it) }
@@ -13,7 +13,7 @@ object ComponentUpdates {
const val BOOTED_SECONDS = 60L const val BOOTED_SECONDS = 60L
const val FAILED_BOOTS_BEFORE_ROLLBACK = 2 const val FAILED_BOOTS_BEFORE_ROLLBACK = 2
data class Line(val key: String, val comp: String, val prefix: String) data class Line(val key: String, val comp: String, val prefix: String, val release: String = ComponentsManager.DD_NIGHTLY)
val LINES = listOf( val LINES = listOf(
Line("dxvk", "dxvk", "DD-dxvk-"), Line("dxvk", "dxvk", "DD-dxvk-"),
@@ -21,12 +21,19 @@ object ComponentUpdates {
Line("vkd3d", "vkd3d", "DD-vkd3d-proton-"), Line("vkd3d", "vkd3d", "DD-vkd3d-proton-"),
Line("vkd3d-arm64ec", "vkd3d", "DD-vkd3d-proton-arm64ec-"), Line("vkd3d-arm64ec", "vkd3d", "DD-vkd3d-proton-arm64ec-"),
Line("fex", "fex", "DD-FEXCore-"), Line("fex", "fex", "DD-FEXCore-"),
Line("fex-bionic", "fex", "FEXCore-", ComponentsManager.DD_BIONIC),
) )
private val OWN_PREFIX = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }.prefix private val OWN_PREFIX = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }.prefix
fun follows(p: ComponentsManager.Proton): Boolean = !p.valve && p.dir.name.startsWith(OWN_PREFIX) fun follows(p: ComponentsManager.Proton): Boolean = !p.valve && p.dir.name.startsWith(OWN_PREFIX)
fun autoFollows(p: ComponentsManager.Proton, comp: String): Boolean =
follows(p) || (comp == "fex" && !p.valve && ComponentsManager.bionicTool(p.dir.name))
fun fexLine(p: ComponentsManager.Proton): Line =
if (ComponentsManager.bionicTool(p.dir.name)) LINES.first { it.release == ComponentsManager.DD_BIONIC } else line("fex", false)
fun ownId(protonId: String): Boolean = protonId.startsWith(ComponentsManager.safeName(OWN_PREFIX)) fun ownId(protonId: String): Boolean = protonId.startsWith(ComponentsManager.safeName(OWN_PREFIX))
fun strays( fun strays(
@@ -34,8 +41,8 @@ object ComponentUpdates {
choices: Map<String, Map<String, ComponentsManager.Choice>>, choices: Map<String, Map<String, ComponentsManager.Choice>>,
placed: Set<String>, placed: Set<String>,
): List<Pair<ComponentsManager.Proton, String>> = ): List<Pair<ComponentsManager.Proton, String>> =
protons.filterNot(::follows).flatMap { p -> protons.flatMap { p ->
choices[p.id].orEmpty().filter { (_, c) -> !c.auto && c.protonVersion == p.version && c.file in placed }.keys.map { p to it } choices[p.id].orEmpty().filter { (comp, c) -> !autoFollows(p, comp) && !c.auto && c.protonVersion == p.version && c.file in placed }.keys.map { p to it }
} }
fun unseen( fun unseen(
@@ -53,13 +60,14 @@ object ComponentUpdates {
fun pick(items: List<ComponentsManager.CatalogItem>, line: Line, bad: Set<String>): ComponentsManager.CatalogItem? { fun pick(items: List<ComponentsManager.CatalogItem>, line: Line, bad: Set<String>): ComponentsManager.CatalogItem? {
val newestBad = bad.filter { belongs(it, line) }.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a, b) } val newestBad = bad.filter { belongs(it, line) }.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a, b) }
return items.filter { it.release == ComponentsManager.DD_NIGHTLY && it.comp == line.comp && belongs(it.file, line) } return items.filter { it.release == line.release && it.comp == line.comp && belongs(it.file, line) }
.filter { newestBad == null || ProtonExtras.compareVersions(it.file, newestBad) > 0 } .filter { newestBad == null || ProtonExtras.compareVersions(it.file, newestBad) > 0 }
.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a.file, b.file) } .maxWithOrNull { a, b -> ProtonExtras.compareVersions(a.file, b.file) }
} }
fun belongs(file: String, line: Line): Boolean = fun belongs(file: String, line: Line): Boolean =
file.startsWith(line.prefix) && file.removePrefix(line.prefix).firstOrNull()?.isDigit() == true file.startsWith(line.prefix) && file.removePrefix(line.prefix).firstOrNull()?.isDigit() == true &&
(line.comp != "fex" || ComponentsManager.bionicFex(file) == (line.release == ComponentsManager.DD_BIONIC))
fun arm64ec(pe: ByteArray): Boolean? = runCatching { fun arm64ec(pe: ByteArray): Boolean? = runCatching {
val b = ByteBuffer.wrap(pe).order(ByteOrder.LITTLE_ENDIAN) val b = ByteBuffer.wrap(pe).order(ByteOrder.LITTLE_ENDIAN)
@@ -161,7 +169,7 @@ object ComponentUpdates {
fun stale(line: Line?, owned: Set<String>, stored: List<String>, keep: Set<String>, current: String, bad: Set<String> = emptySet()): List<String> { fun stale(line: Line?, owned: Set<String>, stored: List<String>, keep: Set<String>, current: String, bad: Set<String> = emptySet()): List<String> {
val ranked = line?.takeIf { belongs(current, it) } val ranked = line?.takeIf { belongs(current, it) }
fun newer(file: String) = ranked != null && belongs(file, ranked) && ProtonExtras.compareVersions(file, current) > 0 fun newer(file: String) = ranked != null && belongs(file, ranked) && ProtonExtras.compareVersions(file, current) > 0
return (owned + stored.filter { ranked != null && belongs(it, ranked) }) return (owned + stored.filter { ranked != null && ranked.release == ComponentsManager.DD_NIGHTLY && belongs(it, ranked) })
.filter { it !in keep && ((it in bad && it in owned) || !newer(it)) }.distinct() .filter { it !in keep && ((it in bad && it in owned) || !newer(it)) }.distinct()
} }
} }
@@ -29,6 +29,7 @@ object ComponentsManager {
private const val NIGHTLIES = "The412Banner/Nightlies" private const val NIGHTLIES = "The412Banner/Nightlies"
private const val DD_COMPONENTS = "Droid-Deck/DroidDeck-Components" private const val DD_COMPONENTS = "Droid-Deck/DroidDeck-Components"
internal const val DD_NIGHTLY = "linux-nightly" internal const val DD_NIGHTLY = "linux-nightly"
internal const val DD_BIONIC = "bionic-stable"
private val RELEASES = linkedMapOf( private val RELEASES = linkedMapOf(
"FexCore-Linux" to "fex", "FexCore-Linux" to "fex",
"Dxvk-Linux" to "dxvk", "Dxvk-Linux" to "dxvk",
@@ -37,9 +38,9 @@ object ComponentsManager {
"Vkd3d-proton-Linux" to "vkd3d", "Vkd3d-proton-Linux" to "vkd3d",
) )
private val NIGHTLY_PREFIXES = linkedMapOf("DD-dxvk-" to "dxvk", "DD-vkd3d-proton-" to "vkd3d", "DD-FEXCore-" to "fex") private val NIGHTLY_PREFIXES = linkedMapOf("DD-dxvk-" to "dxvk", "DD-vkd3d-proton-" to "vkd3d", "DD-FEXCore-" to "fex")
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY) private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY) + (DD_COMPONENTS to DD_BIONIC)
private val DOWNLOAD_REPOS = listOf(NIGHTLIES, DD_COMPONENTS) private val DOWNLOAD_REPOS = listOf(NIGHTLIES, DD_COMPONENTS)
private val TYPES = mapOf("FEXCore-Linux" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d") private val TYPES = mapOf("FEXCore-Linux" to "fex", "FEXCore-Bionic" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d")
private val TYPE_OF = mapOf("fex" to "FEXCore-Linux", "dxvk" to "DXVK-Linux", "vkd3d" to "VKD3D-Linux") private val TYPE_OF = mapOf("fex" to "FEXCore-Linux", "dxvk" to "DXVK-Linux", "vkd3d" to "VKD3D-Linux")
val COMPONENTS = listOf("fex", "dxvk", "vkd3d") val COMPONENTS = listOf("fex", "dxvk", "vkd3d")
val LABEL = mapOf("fex" to "FEX", "dxvk" to "DXVK", "vkd3d" to "VKD3D-Proton") val LABEL = mapOf("fex" to "FEX", "dxvk" to "DXVK", "vkd3d" to "VKD3D-Proton")
@@ -201,8 +202,34 @@ object ComponentsManager {
COMPONENTS.mapNotNull { comp -> profile.optString(comp).takeIf(String::isNotEmpty)?.let { comp to it } }.toMap() COMPONENTS.mapNotNull { comp -> profile.optString(comp).takeIf(String::isNotEmpty)?.let { comp to it } }.toMap()
} }
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) = fun setGameComponent(context: Context, scope: String, comp: String, file: String?) {
setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) } setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) }
if (comp == "fex" && file != null) fetchFexTwin(context, safeName(file))
}
// Twin downloads in flight: one worker per name, so two profile changes cannot share one partial download.
private val twinDownloads = HashSet<String>()
private fun fetchFexTwin(context: Context, file: String) {
val twin = fexTwin(file) ?: return
if (protons(context).all { fexFits(it.dir.name, file) }) return
synchronized(lock) { if (isStored(context, twin) || !twinDownloads.add(twin)) return }
val app = context.applicationContext
Thread({
try {
runCatching {
val item = catalogItem(app, twin, if (bionicFex(twin)) DD_BIONIC else "FexCore-Linux")
if (item == null) Log.i(TAG, "$twin is not listed")
else {
download(app, item) {}
republish(app)
}
}.onFailure { Log.w(TAG, "download $twin", it) }
} finally {
synchronized(lock) { twinDownloads.remove(twin) }
}
}, "fex-twin").start()
}
internal fun setGameComponent(context: Context, scope: String, comp: String, file: String?, managed: (String) -> Boolean) = synchronized(lock) { internal fun setGameComponent(context: Context, scope: String, comp: String, file: String?, managed: (String) -> Boolean) = synchronized(lock) {
require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L) require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L)
@@ -413,7 +440,7 @@ object ComponentsManager {
} }
} }
require(File(staged, "files").isDirectory) { "${wcp.name} has no files/" } require(File(staged, "files").isDirectory) { "${wcp.name} has no files/" }
if (comp == "fex") FEX_FILES.filter { it.endsWith(".so") && !File(staged, it).isFile }.forEach { File(dir, it).delete() } if (comp == "fex" && !bionicTool(dir.name)) FEX_FILES.filter { it.endsWith(".so") && !File(staged, it).isFile }.forEach { File(dir, it).delete() }
COMP_DIR[comp]?.let { compDir -> COMP_DIR[comp]?.let { compDir ->
for (arch in PE_ARCHES) { for (arch in PE_ARCHES) {
val target = File(dir, "$compDir/$arch") val target = File(dir, "$compDir/$arch")
@@ -603,7 +630,9 @@ object ComponentsManager {
File(base, "files").walkTopDown().filter { it.isFile }.map { it.relativeTo(base).invariantSeparatorsPath } File(base, "files").walkTopDown().filter { it.isFile }.map { it.relativeTo(base).invariantSeparatorsPath }
.filter { owned(comp, it) }.associateWith { File(base, it) } .filter { owned(comp, it) }.associateWith { File(base, it) }
} }
for (rel in managed(comp) - files.keys) { // A bionic tool never loses a FEX file: its launch.sh would put the whole bundled FEX back.
val removed = if (comp == "fex" && bionicTool(p.dir.name)) emptySet() else managed(comp) - files.keys
for (rel in removed) {
lines.append(scope).append('\t').append(p.dir.name).append('\t').append(p.version).append('\t').append(comp) lines.append(scope).append('\t').append(p.dir.name).append('\t').append(p.version).append('\t').append(comp)
.append('\t').append(rel).append("\t-\t-\n") .append('\t').append(rel).append("\t-\t-\n")
} }
@@ -620,7 +649,8 @@ object ComponentsManager {
val version = safeName(file.removePrefix("original ")) val version = safeName(file.removePrefix("original "))
"original-${p.id}-$version-$comp" to File(originalsDir(context), "${p.id}/$version/$comp.wcp") "original-${p.id}-$version-$comp" to File(originalsDir(context), "${p.id}/$version/$comp.wcp")
} else { } else {
safeName(file.removeSuffix(".wcp")) to File(packagesDir(context), file) val fit = (if (comp == "fex") launchFex(p.dir.name, file) { File(packagesDir(context), it).isFile } else file) ?: return null
safeName(fit.removeSuffix(".wcp")) to File(packagesDir(context), fit)
}.takeIf { it.second.isFile } }.takeIf { it.second.isFile }
} }
@@ -651,12 +681,14 @@ object ComponentsManager {
for (scope in profiles.keys()) { for (scope in profiles.keys()) {
val profile = profiles.optJSONObject(scope) ?: continue val profile = profiles.optJSONObject(scope) ?: continue
for (comp in COMPONENTS) { for (comp in COMPONENTS) {
val file = profile.optString(comp) val chosen = profile.optString(comp)
if (file.isEmpty()) continue if (chosen.isEmpty()) continue
val wcp = File(packagesDir(context), file) for (p in all) {
if (!wcp.isFile) continue val file = (if (comp == "fex") launchFex(p.dir.name, chosen) { File(packagesDir(context), it).isFile } else chosen) ?: continue
val key = safeName(file.removeSuffix(".wcp")) val wcp = File(packagesDir(context), file)
for (p in all) append(scope, p, comp, key, wcp) if (!wcp.isFile) continue
append(scope, p, comp, safeName(file.removeSuffix(".wcp")), wcp)
}
} }
} }
return PreparedLaunchState(lines.toString(), keep) return PreparedLaunchState(lines.toString(), keep)
@@ -677,6 +709,7 @@ object ComponentsManager {
val wcp = File(packagesDir(context), safeName(file)) val wcp = File(packagesDir(context), safeName(file))
val info = packageInfo(context, wcp) val info = packageInfo(context, wcp)
requireSelectable(context, info.comp) requireSelectable(context, info.comp)
requireFits(p, info)
val state = loadState(context) val state = loadState(context)
if (inUse(context, p)) { if (inUse(context, p)) {
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version) state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version)
@@ -690,7 +723,11 @@ object ComponentsManager {
context.getString(R.string.cmgr_swap_done, LABEL[info.comp], info.version, p.name) context.getString(R.string.cmgr_swap_done, LABEL[info.comp], info.version, p.name)
} }
private fun requireFits(p: Proton, info: Package) =
check(info.comp != "fex" || fexFits(p.dir.name, info.file)) { "${info.file} is not a FEX build for ${p.name}" }
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject, auto: Boolean = false) { private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject, auto: Boolean = false) {
requireFits(p, info)
ensureOriginal(context, p, info.comp, state) ensureOriginal(context, p, info.comp, state)
val hashes = installFiles(context, p.dir, info.comp, wcp) val hashes = installFiles(context, p.dir, info.comp, wcp)
state.sub("active").sub(p.id).put(info.comp, JSONObject() state.sub("active").sub(p.id).put(info.comp, JSONObject()
@@ -803,6 +840,18 @@ object ComponentsManager {
internal fun liveOnAny(key: String, entry: JSONObject, installs: List<Proton>?): Boolean = internal fun liveOnAny(key: String, entry: JSONObject, installs: List<Proton>?): Boolean =
installs?.any { liveSelection(key, entry, it) } == true installs?.any { liveSelection(key, entry, it) } == true
// An installed tool that launches with `name` as the stored twin of a game's FEX choice (a Linux choice on
// DroidDeck-Bionic, a -bionic one on another Proton): deleting the twin would drop that choice for that tool.
internal fun twinUser(state: JSONObject, installed: List<Proton>, name: String): Proton? {
val profiles = state.optJSONObject("profiles") ?: return null
for (scope in profiles.keys()) {
val chosen = profiles.optJSONObject(scope)?.optString("fex")?.takeIf { it.isNotEmpty() } ?: continue
if (fexTwin(chosen) != name) continue
installed.firstOrNull { !fexFits(it.dir.name, chosen) }?.let { return it }
}
return null
}
internal fun packagesInUse(state: JSONObject, installed: List<Proton>): Set<String> { internal fun packagesInUse(state: JSONObject, installed: List<Proton>): Set<String> {
val byId = installed.groupBy { it.id } val byId = installed.groupBy { it.id }
val names = HashSet<String>() val names = HashSet<String>()
@@ -819,7 +868,11 @@ object ComponentsManager {
val profiles = state.optJSONObject("profiles") val profiles = state.optJSONObject("profiles")
for (scope in profiles?.keys() ?: emptyList<String>().iterator()) { for (scope in profiles?.keys() ?: emptyList<String>().iterator()) {
val profile = profiles?.optJSONObject(scope) ?: continue val profile = profiles?.optJSONObject(scope) ?: continue
COMPONENTS.forEach { comp -> profile.optString(comp).takeIf { it.isNotEmpty() }?.let(names::add) } COMPONENTS.forEach { comp ->
val file = profile.optString(comp).takeIf { it.isNotEmpty() } ?: return@forEach
names.add(file)
if (comp == "fex" && installed.any { !fexFits(it.dir.name, file) }) fexTwin(file)?.let(names::add)
}
} }
return names return names
} }
@@ -890,6 +943,7 @@ object ComponentsManager {
val queued = state.sub("queued").sub(target.id) val queued = state.sub("queued").sub(target.id)
var changed = false var changed = false
wanted.forEach { (comp, entry) -> wanted.forEach { (comp, entry) ->
if (comp == "fex" && !fexFits(target.dir.name, entry.optString("file"))) return@forEach
if (active?.has(comp) != true && !queued.has(comp)) { if (active?.has(comp) != true && !queued.has(comp)) {
queued.put(comp, entry) queued.put(comp, entry)
changed = true changed = true
@@ -970,6 +1024,8 @@ object ComponentsManager {
fun deletePackage(context: Context, file: String): String = synchronized(lock) { fun deletePackage(context: Context, file: String): String = synchronized(lock) {
val name = safeName(file) val name = safeName(file)
val state = loadState(context) val state = loadState(context)
val twinTool = twinUser(state, protons(context), name)
check(twinTool == null) { context.getString(R.string.cmgr_package_in_use, name, twinTool?.name ?: "") }
val installed = protons(context).groupBy { it.id } val installed = protons(context).groupBy { it.id }
var changed = false var changed = false
for (key in listOf("queued", "active")) { for (key in listOf("queued", "active")) {
@@ -1066,8 +1122,11 @@ object ComponentsManager {
return Catalog(items, o.optLong("fetchedAt")) return Catalog(items, o.optLong("fetchedAt"))
} }
internal fun assetComp(release: String, name: String): String? = internal fun assetComp(release: String, name: String): String? = RELEASES[release] ?: when (release) {
RELEASES[release] ?: if (release == DD_NIGHTLY) NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value else null DD_NIGHTLY -> NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value
DD_BIONIC -> "fex"
else -> null
}
internal val CATALOG_ORDER: Comparator<CatalogItem> = internal val CATALOG_ORDER: Comparator<CatalogItem> =
compareBy<CatalogItem> { it.comp }.thenBy { it.release == DD_NIGHTLY }.then(newestFirst { it.file }) compareBy<CatalogItem> { it.comp }.thenBy { it.release == DD_NIGHTLY }.then(newestFirst { it.file })
@@ -1155,6 +1214,25 @@ object ComponentsManager {
return runCatching { readWcpEntry(original, rel) }.getOrNull() return runCatching { readWcpEntry(original, rel) }.getOrNull()
} }
// DroidDeck-Bionic loads only Android builds of FEX's unix libraries; other Protons only glibc builds.
internal fun bionicTool(dirName: String?): Boolean = dirName?.startsWith("DroidDeck-Bionic") == true
internal fun bionicFex(file: String): Boolean = file.endsWith("-bionic.wcp", ignoreCase = true)
internal fun fexFits(toolDir: String?, file: String): Boolean = bionicTool(toolDir) == bionicFex(file)
internal fun fexTwin(file: String): String? = when {
file.endsWith("-linux.wcp", ignoreCase = true) -> file.dropLast("-linux.wcp".length) + "-bionic.wcp"
file.endsWith("-bionic.wcp", ignoreCase = true) -> file.dropLast("-bionic.wcp".length) + "-linux.wcp"
else -> null
}
internal fun launchFex(toolDir: String, file: String, stored: (String) -> Boolean): String? =
if (fexFits(toolDir, file)) file else fexTwin(file)?.takeIf(stored)
internal fun <T> forTool(comp: String, toolDir: String?, items: List<T>, selected: String? = null, file: (T) -> String): List<T> =
if (comp != "fex") items else items.filter { file(it) == selected || fexFits(toolDir, file(it)) }
fun supports(p: Proton, comp: String): Boolean = fun supports(p: Proton, comp: String): Boolean =
if (comp == "fex") File(p.dir, FEX_FILES.first()).isFile else File(p.dir, "${COMP_DIR.getValue(comp)}/aarch64-windows").isDirectory if (comp == "fex") File(p.dir, FEX_FILES.first()).isFile else File(p.dir, "${COMP_DIR.getValue(comp)}/aarch64-windows").isDirectory
@@ -937,7 +937,7 @@ internal object EnhancedSessionLogShare {
val value = entry.lowercase(Locale.US) val value = entry.lowercase(Locale.US)
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") || if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") ||
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) || value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug").any(value::contains)) return Category.GAMES listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug", "bionic").any(value::contains)) return Category.GAMES
if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS
return Category.SESSION return Category.SESSION
} }
@@ -948,7 +948,7 @@ internal object EnhancedSessionLogShare {
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log", "droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log", "device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log",
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json", "frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt", "battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt", "droiddeck-bionic.log",
"console_log.txt", "webhelper_js.txt", "controller_support.txt", "systemperfmanager.txt", "console_log.txt", "webhelper_js.txt", "controller_support.txt", "systemperfmanager.txt",
) )
private val KNOWN_COMPONENT_PATTERNS = listOf( private val KNOWN_COMPONENT_PATTERNS = listOf(
@@ -74,10 +74,16 @@ object ExperimentalProtons {
return PREFIX + base + (tag?.let { "-$it" } ?: "") return PREFIX + base + (tag?.let { "-$it" } ?: "")
} }
/** DroidDeck-Bionic test builds are prereleases of the same repository and have their own row in the Proton list. */
internal fun listed(assets: List<ProtonExtras.Asset>): List<ProtonExtras.Asset> {
val bionic = ProtonExtras.tools.first { it.id == ProtonExtras.BIONIC }
return assets.filterNot { bionic.assetPattern.containsMatchIn(it.name) }
}
fun refresh(context: Context): List<Release>? { fun refresh(context: Context): List<Release>? {
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN } val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
val fetched = ProtonExtras.releasesForRemoval(tool) ?: return null val fetched = ProtonExtras.releasesForRemoval(tool) ?: return null
val assets = ProtonExtras.assets(tool, fetched.releases, prerelease = true) val assets = listed(ProtonExtras.assets(tool, fetched.releases, prerelease = true))
val rows = assets.map { Release(it.tag, it.name, it.url, it.sha512, it.size, it.releaseName) }.distinctBy { it.tag } val rows = assets.map { Release(it.tag, it.name, it.url, it.sha512, it.size, it.releaseName) }.distinctBy { it.tag }
if (!SessionState.running) { if (!SessionState.running) {
reconcile(context, fetched) reconcile(context, fetched)
@@ -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? { fun effective(context: Context): Option? {
val pref = SessionPrefs.gameStorage(context) val pref = SessionPrefs.gameStorage(context)
return when { return when {
@@ -27,14 +27,14 @@ object GameThreadHints {
private const val PACE_TOLERANCE = 0.08 private const val PACE_TOLERANCE = 0.08
private val NOT_GAMES = setOf("steam", "steamwebhelper") 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 private var worker: Thread? = null
@Synchronized @Synchronized
fun start(context: Context): String { fun start(context: Context): String {
if (!SessionPrefs.gameThreadHints(context)) return "game thread hints: off" 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) val hm = context.getSystemService(PerformanceHintManager::class.java)
?: return "game thread hints: no PerformanceHintManager" ?: return "game thread hints: no PerformanceHintManager"
val pm = context.getSystemService(PowerManager::class.java) val pm = context.getSystemService(PowerManager::class.java)
@@ -11,15 +11,7 @@ import java.io.RandomAccessFile
import java.nio.charset.StandardCharsets import java.nio.charset.StandardCharsets
class LoadingState(context: Context, private val steam: Boolean = true) { class LoadingState(context: Context, private val steam: Boolean = true) {
private val prefs = context.getSharedPreferences("loading", Context.MODE_PRIVATE) var visible by mutableStateOf(true)
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 step by mutableStateOf(context.getString(com.droiddeck.launcher.R.string.loadstate_starting)) var step by mutableStateOf(context.getString(com.droiddeck.launcher.R.string.loadstate_starting))
private set private set
var topic by mutableStateOf(Topic.SESSION) var topic by mutableStateOf(Topic.SESSION)
@@ -41,7 +33,7 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
fun tick() { fun tick() {
val seconds = (SystemClock.elapsedRealtime() - startedAt) / 1000 val seconds = (SystemClock.elapsedRealtime() - startedAt) / 1000
elapsed = res.getString(com.droiddeck.launcher.R.string.loadstate_elapsed, seconds / 60, seconds % 60) 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) { 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 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? { private fun read(context: Context, log: File?): Line? {
if (log == null || !log.isFile) return null if (log == null || !log.isFile) return null
val text = try { val text = try {
@@ -91,7 +81,6 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
var clientDownloadAt = -1 var clientDownloadAt = -1
var clientDownload: String? = null var clientDownload: String? = null
var clientPercent = -1 var clientPercent = -1
var unknownAt = -1
var offset = 0 var offset = 0
for (line in text.split('\n')) { for (line in text.split('\n')) {
val at = offset val at = offset
@@ -106,34 +95,16 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
} }
} else { } else {
val m = UPDATE_PROGRESS.find(line) val m = UPDATE_PROGRESS.find(line)
val p = if (m == null && steam) UPDATE_PERCENT.find(line) else null
if (m != null) { if (m != null) {
downloadAt = at downloadAt = at
val done = m.groupValues[1].replace(",", "").toLong() val done = m.groupValues[1].toLong()
val total = maxOf(1L, m.groupValues[2].replace(",", "").toLong()) val total = maxOf(1L, m.groupValues[2].toLong())
downloadPercent = (done * 100 / total).toInt() 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)) { } else if (steam && UPDATE_APPLYING.matches(line)) {
applyingAt = at 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 { return when {
applyingAt > stepAt && applyingAt > downloadAt -> Line( applyingAt > stepAt && applyingAt > downloadAt -> Line(
context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update_applying), -1, 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, context.getString(com.droiddeck.launcher.R.string.loadstate_steam_update, downloadPercent), downloadPercent,
Topic.STEAM, readable = true, Topic.STEAM, readable = true,
) )
stepLine != null -> stepLine clientDownloadAt == stepAt && clientDownload != null -> Line(
unknownAt >= 0 -> scriptStep ?: Line( context.getString(com.droiddeck.launcher.R.string.loadstate_steam_client, clientDownload), clientPercent,
context.getString(com.droiddeck.launcher.R.string.loadstate_starting), -1, Topic.SESSION, readable = false, Topic.STEAM, readable = true,
) )
stepText != null -> Line(stepText, -1, topicOf(stepText, steam), readableScriptStep(stepText))
else -> null 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 } enum class Topic { RUNTIME, SESSION, DESKTOP, STEAM, STEAM_STARTING, OTHER }
companion object { companion object {
private const val FIRST_DONE = "first_done"
internal fun topicOf(scriptStep: String, steam: Boolean): Topic { internal fun topicOf(scriptStep: String, steam: Boolean): Topic {
val t = scriptStep.lowercase() val t = scriptStep.lowercase()
return when { return when {
@@ -186,8 +157,7 @@ class LoadingState(context: Context, private val steam: Boolean = true) {
} }
private const val TAIL_BYTES = 48L * 1024 private const val TAIL_BYTES = 48L * 1024
private val UPDATE_PROGRESS = Regex("""Downloading update \(([\d,]+) of ([\d,]+) KB\)""") private val UPDATE_PROGRESS = Regex("""Downloading update \((\d+) of (\d+) KB\)""")
private val UPDATE_PERCENT = Regex("""^\[[^\]]+\] Set percent complete: (-?\d+)\s*$""")
private val UPDATE_APPLYING = Regex("""^\s*(?:\[[^\]]+\]\s*)*(?:Extracting package|Installing update)\.\.\.\s*$""") 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_COUNT = Regex("""downloading Steam: (\S+) \((\d+)/(\d+)\)""")
private val INSTALL_MEGABYTES = Regex("""^, (\d+) of (\d+) MB""") private val INSTALL_MEGABYTES = Regex("""^, (\d+) of (\d+) MB""")
@@ -1,157 +0,0 @@
package com.droiddeck.launcher.session
import android.content.Context
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.LinuxRuntimeInstaller
import com.droiddeck.launcher.runtime.RuntimeInstallService
import kotlinx.coroutines.flow.MutableStateFlow
/** What first run installs by itself, in the order it is needed, and how far each part has got. */
object Onboarding {
enum class Step { RUNTIME, PROTON, STEAM }
data class Progress(val label: String, val percent: Int)
data class Facts(val runtime: Boolean = true, val proton: Boolean = true, val steam: Boolean = true)
enum class State { DONE, ACTIVE, WAITING, FAILED }
data class Row(val step: Step, val state: State, val label: String?, val percent: Int)
val active = MutableStateFlow<Map<Step, Progress>>(emptyMap())
val failed = MutableStateFlow<Map<Step, String>>(emptyMap())
val facts = MutableStateFlow(Facts())
@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. */
@Synchronized private fun keepAlive() {
val context = appContext ?: return
val running = active.value
if (running.isNotEmpty() && !LinuxRuntimeInstaller.isBusy()) {
if (hold == null) hold = RuntimeInstallService.holdForPackage(context, context.getString(R.string.onboarding_title))
val rows = rows(running, failed.value, facts.value)
RuntimeInstallService.packageProgress(running.values.first().label, overall(rows))
} else {
hold?.invoke()
hold = null
}
}
@Synchronized fun recheck(context: Context) {
val runtime = LinuxRuntime.isInstalled(context)
val own = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
facts.value = Facts(
runtime = runtime,
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) {
failed.value = failed.value - step
active.value = active.value + (step to Progress(label, percent))
keepAlive()
}
fun finish(step: Step) {
active.value = active.value - step
failed.value = failed.value - step
keepAlive()
}
fun fail(step: Step, message: String) {
active.value = active.value - step
failed.value = failed.value + (step to message)
keepAlive()
}
fun rows(active: Map<Step, Progress>, failed: Map<Step, String>, facts: Facts): List<Row> = Step.entries.map { step ->
val ready = when (step) { Step.RUNTIME -> facts.runtime; Step.PROTON -> facts.proton; Step.STEAM -> facts.steam }
val progress = active[step]
when {
progress != null -> Row(step, State.ACTIVE, progress.label, progress.percent)
failed[step] != null -> Row(step, State.FAILED, failed[step], -1)
ready -> Row(step, State.DONE, null, 100)
else -> Row(step, State.WAITING, null, -1)
}
}
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)
val total = weights.values.sum()
val got = rows.sumOf { row ->
val w = weights.getValue(row.step)
when (row.state) {
State.DONE -> w
State.ACTIVE -> if (row.percent >= 0) w * row.percent / 100 else 0
else -> 0
}
}
return got * 100 / total
}
}
@@ -14,7 +14,8 @@ object ProtonDefault {
data class Tool(val name: String, val display: String, val dir: String, val valve: Boolean) data class Tool(val name: String, val display: String, val dir: String, val valve: Boolean)
data class Request(val seq: Long, val valve: Boolean, val dir: String) data class Request(val seq: Long, val valve: Boolean, val dir: String)
data class State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>) data class State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>,
val source: String? = null)
data class GameChoice(val valve: Boolean, val dir: String) data class GameChoice(val valve: Boolean, val dir: String)
enum class Outcome { LIVE, NEXT_START, NOT_RUNNABLE } enum class Outcome { LIVE, NEXT_START, NOT_RUNNABLE }
@@ -34,6 +35,7 @@ object ProtonDefault {
Tool(t.optString("name"), t.optString("display"), t.optString("dir"), t.optBoolean("valve")) Tool(t.optString("name"), t.optString("display"), t.optString("dir"), t.optBoolean("valve"))
}?.takeIf { it.name.isNotEmpty() } }?.takeIf { it.name.isNotEmpty() }
}, },
source = o.optString("source").ifEmpty { null },
) )
} }
@@ -99,7 +101,13 @@ object ProtonDefault {
if (!runnable(state, proton)) return Outcome.NOT_RUNNABLE if (!runnable(state, proton)) return Outcome.NOT_RUNNABLE
val d = dir(context) val d = dir(context)
val seq = nextSeq(System.currentTimeMillis(), state, parseRequest(read(File(d, "request.json")))) val seq = nextSeq(System.currentTimeMillis(), state, parseRequest(read(File(d, "request.json"))))
val body = JSONObject().put("seq", seq).put("valve", proton.valve).put("dir", proton.dir.name).toString(1) + "\n" writeRequest(d, Request(seq, proton.valve, proton.dir.name))
val tool = state.tools.firstOrNull { it.valve == proton.valve && it.dir == proton.dir.name }
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
}
private fun writeRequest(d: File, request: Request) {
val body = JSONObject().put("seq", request.seq).put("valve", request.valve).put("dir", request.dir).toString(1) + "\n"
val staged = File(d, "request.json.staged") val staged = File(d, "request.json.staged")
try { try {
d.mkdirs() d.mkdirs()
@@ -110,8 +118,45 @@ object ProtonDefault {
Log.w(TAG, "could not write the Proton request", e) Log.w(TAG, "could not write the Proton request", e)
throw e throw e
} }
val tool = state.tools.firstOrNull { it.valve == proton.valve && it.dir == proton.dir.name } }
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
// The default that names a tool an update replaces moves to the new one, as the per-game picks do: otherwise the guest
// no longer finds it and falls back to DroidDeck-Proton.
internal fun movedDefault(state: State, request: Request?, from: Set<String>, to: String, now: Long): Request? {
val (valve, dir) = chosen(state, request) ?: return null
if (valve || dir !in from) return null
return Request(nextSeq(now, state, request), false, to)
}
@Synchronized
fun moveDefault(context: Context, from: Set<String>, to: String) {
val d = dir(context)
val moved = movedDefault(state(context), parseRequest(read(File(d, "request.json"))), from, to, System.currentTimeMillis()) ?: return
writeRequest(d, moved)
}
// DroidDeck-Bionic keeps one build. A default naming another one moves to the installed build: an app from before
// updates carried the default over left it, or the guest fell back to its own tool when that build was gone (the
// request the app last wrote still names it).
internal fun bionicDefault(state: State, request: Request?, prefix: String, newest: String, now: Long): Request? {
val current = chosen(state, request)
val stale = when {
current != null && !current.first && current.second.startsWith(prefix) -> current.second
state.source == "fallback" && request != null && !request.valve && request.dir.startsWith(prefix) -> request.dir
else -> return null
}
return if (stale == newest) null else Request(nextSeq(now, state, request), false, newest)
}
/** The default and the per-game picks that name a DroidDeck-Bionic build other than [newest] move to it. */
@Synchronized
fun keepBionicCurrent(context: Context, prefix: String, newest: String) {
val d = dir(context)
bionicDefault(state(context), parseRequest(read(File(d, "request.json"))), prefix, newest, System.currentTimeMillis())
?.let { writeRequest(d, it) }
val games = parseGames(read(File(d, GAMES)))
val stale = games.values.filterNotNull().filter { !it.valve && it.dir.startsWith(prefix) && it.dir != newest }.map { it.dir }.toSet()
if (stale.isNotEmpty()) movedGames(games, stale, newest)?.let { writeGames(d, it) }
} }
internal fun movedGames(choices: Map<String, GameChoice?>, from: Set<String>, to: String): Map<String, GameChoice?>? { internal fun movedGames(choices: Map<String, GameChoice?>, from: Set<String>, to: String): Map<String, GameChoice?>? {
@@ -8,6 +8,7 @@ import android.util.Log
import com.droiddeck.launcher.core.Downloader import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.FileUtils import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.NativeGuest
import java.io.File import java.io.File
import java.util.Locale import java.util.Locale
import org.json.JSONArray import org.json.JSONArray
@@ -23,29 +24,31 @@ object ProtonExtras {
const val CHECK_EVERY_MS = 60L * 60 * 1000 const val CHECK_EVERY_MS = 60L * 60 * 1000
@Volatile @Volatile
var installInProgress = false var installInProgress = false
@Volatile var prefetching = false
private set 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 @Volatile
private var replacing = false private var replacing = false
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex) class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex,
val prereleases: Boolean = false)
internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long, internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
val sha256: String? = null, val releaseName: String = tag) val sha256: String? = null, val releaseName: String = tag)
internal data class ReleaseFetch(val releases: JSONArray, val complete: Boolean) internal data class ReleaseFetch(val releases: JSONArray, val complete: Boolean)
const val OWN = "droiddeck" const val OWN = "droiddeck"
const val BIONIC = "bionic"
val tools = listOf( val tools = listOf(
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")), Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")), Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")),
Tool("droiddeck", "DroidDeck-Proton", "DroidDeck-Proton", "Droid-Deck/DroidDeck-Proton", Regex("aarch64\\.tar\\.(gz|xz)$")), Tool("droiddeck", "DroidDeck-Proton", "DroidDeck-Proton", "Droid-Deck/DroidDeck-Proton", Regex("^DroidDeck-Proton-.*aarch64\\.tar\\.(gz|xz)$")),
// Bionic (Android libc) Proton started outside the Linux userland; test builds are prereleases. No-proot only.
Tool(BIONIC, "DroidDeck-Bionic", "DroidDeck-Bionic", "Droid-Deck/DroidDeck-Proton", Regex("^DroidDeck-Bionic-.*aarch64\\.tar\\.(gz|xz)$"), prereleases = true),
) )
/** The sources offered on this device: DroidDeck-Bionic only with Run without proot on. */
fun offered(context: Context): List<Tool> = tools.filter { it.id != BIONIC || NativeGuest.enabled(context) }
private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root") private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root")
private fun requests(context: Context) = File(home(context), ".dd-proton-extra") private fun requests(context: Context) = File(home(context), ".dd-proton-extra")
private fun toolsDir(context: Context) = File(home(context), ".local/share/Steam/compatibilitytools.d") private fun toolsDir(context: Context) = File(home(context), ".local/share/Steam/compatibilitytools.d")
@@ -120,10 +123,11 @@ object ProtonExtras {
private var lastAttempt = 0L private var lastAttempt = 0L
fun checkLatest(context: Context, force: Boolean = false, now: Long = System.currentTimeMillis()): Boolean { fun checkLatest(context: Context, force: Boolean = false, now: Long = System.currentTimeMillis()): Boolean {
keepBionicCurrent(context)
synchronized(checkLock) { synchronized(checkLock) {
val file = latestFile(context) val file = latestFile(context)
val cache = readJson(file) val cache = readJson(file)
val due = tools.filter { tool -> val due = offered(context).filter { tool ->
val at = cache.optJSONObject(tool.id)?.optLong("at", 0L) ?: 0L val at = cache.optJSONObject(tool.id)?.optLong("at", 0L) ?: 0L
force || (now - at) !in 0 until CHECK_EVERY_MS force || (now - at) !in 0 until CHECK_EVERY_MS
} }
@@ -173,15 +177,32 @@ object ProtonExtras {
fun remove(context: Context, tool: Tool, dir: String? = null) { fun remove(context: Context, tool: Tool, dir: String? = null) {
val name = if (dir != null) dir.takeIf { it in installedAll(context, tool) } ?: return else installed(context, tool) ?: return val name = if (dir != null) dir.takeIf { it in installedAll(context, tool) } ?: return else installed(context, tool) ?: return
if (File(toolsDir(context), name).deleteRecursively()) ComponentsManager.forgetProton(context, name) if (deleteTool(context, name)) ComponentsManager.forgetProton(context, name)
}
// A tool folder can hold links that point out of it (a prefix template's dosdevices/z: -> /), and
// File.deleteRecursively() follows links into directories: remove each link itself, never what it points to.
private fun deleteTool(context: Context, name: String): Boolean {
val dir = File(toolsDir(context), name)
FileUtils.delete(dir)
return !dir.exists() && !java.nio.file.Files.isSymbolicLink(dir.toPath())
} }
fun removeOlder(context: Context, tool: Tool) { fun removeOlder(context: Context, tool: Tool) {
installedAll(context, tool).dropLast(1).forEach { installedAll(context, tool).dropLast(1).forEach {
if (File(toolsDir(context), it).deleteRecursively()) ComponentsManager.forgetProton(context, it) if (deleteTool(context, it)) ComponentsManager.forgetProton(context, it)
} }
} }
// DroidDeck-Bionic: the default and the game picks name the installed build, also when they were left on one an
// older app deleted without moving them.
private fun keepBionicCurrent(context: Context) {
if (SessionState.running) return
val tool = tools.firstOrNull { it.id == BIONIC } ?: return
val newest = installedAll(context, tool).lastOrNull() ?: return
runCatching { ProtonDefault.keepBionicCurrent(context, tool.prefix, newest) }.onFailure { Log.w(TAG, "bionic default and picks", it) }
}
private fun replaceOlder(context: Context, tool: Tool) { private fun replaceOlder(context: Context, tool: Tool) {
val all = installedAll(context, tool) val all = installedAll(context, tool)
val newest = all.lastOrNull() ?: return val newest = all.lastOrNull() ?: return
@@ -194,7 +215,9 @@ object ProtonExtras {
if (runCatching { ComponentsManager.carryOver(context, old, newest) }.onFailure { Log.w(TAG, "components of $old", it) }.isFailure) continue if (runCatching { ComponentsManager.carryOver(context, old, newest) }.onFailure { Log.w(TAG, "components of $old", it) }.isFailure) continue
if (runCatching { keepUserSettings(context, old, newest) }.onFailure { Log.w(TAG, "user settings of $old", it) }.isFailure) continue if (runCatching { keepUserSettings(context, old, newest) }.onFailure { Log.w(TAG, "user settings of $old", it) }.isFailure) continue
if (runCatching { ProtonDefault.moveGames(context, setOf(old), newest) }.onFailure { Log.w(TAG, "per-game picks of $old", it) }.isFailure) continue if (runCatching { ProtonDefault.moveGames(context, setOf(old), newest) }.onFailure { Log.w(TAG, "per-game picks of $old", it) }.isFailure) continue
if (File(toolsDir(context), old).deleteRecursively()) ComponentsManager.forgetProton(context, old) // DroidDeck-Bionic only: the guest finds no default for a deleted Bionic build and falls back to DroidDeck-Proton
if (tool.id == BIONIC && runCatching { ProtonDefault.moveDefault(context, setOf(old), newest) }.onFailure { Log.w(TAG, "default pick of $old", it) }.isFailure) continue
if (deleteTool(context, old)) ComponentsManager.forgetProton(context, old)
else Log.w(TAG, "could not remove $old") else Log.w(TAG, "could not remove $old")
} }
} finally { } finally {
@@ -222,12 +245,24 @@ object ProtonExtras {
@Synchronized @Synchronized
fun install(context: Context, tool: Tool, 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) if (installInProgress) return context.getString(R.string.pextra_busy)
installInProgress = true installInProgress = true
return try { installNow(context, tool, onProgress) } finally { installInProgress = false } return try { installNow(context, tool, onProgress) } finally { installInProgress = false }
} }
private fun fetchArchive(context: Context, tool: Tool, asset: Asset, archive: File, 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)
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
val archive = File(downloads, "${tool.id}-${asset.name}")
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) {
return context.getString(R.string.pextra_no_space, tool.name)
}
val downloading = context.getString(R.string.pextra_downloading, tool.name, asset.tag) val downloading = context.getString(R.string.pextra_downloading, tool.name, asset.tag)
onProgress(downloading, 0) onProgress(downloading, 0)
var downloaded = false var downloaded = false
@@ -245,46 +280,6 @@ object ProtonExtras {
} }
} }
if (!downloaded) return context.getString(R.string.pextra_download_failed) if (!downloaded) return context.getString(R.string.pextra_download_failed)
return null
}
/** Downloads the newest build of [tool] ahead of the runtime it installs into; [install] verifies and unpacks it later. */
@Synchronized
fun prefetch(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
if (installInProgress) return context.getString(R.string.pextra_busy)
prefetching = true
try { return prefetchNow(context, tool, onProgress) } finally { prefetching = false }
}
private fun prefetchNow(context: Context, tool: Tool, onProgress: (String, Int) -> Unit): String? {
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
val archive = File(downloads, "${tool.id}-${asset.name}")
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
}
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)
val asset = releases(tool)?.let { pickAsset(tool, it) } ?: return context.getString(R.string.pextra_no_release, tool.name)
val downloads = File(context.filesDir, "proton-downloads").apply { mkdirs() }
val archive = File(downloads, "${tool.id}-${asset.name}")
if (asset.size > 0 && archive.length() > asset.size) archive.delete()
val missing = (asset.size - archive.length()).coerceAtLeast(0L)
if (StatFs(LinuxRuntime.rootDir(context).path).availableBytes < NEED_BYTES + missing) {
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)?.let { return it }
if (asset.size > 0 && archive.length() != asset.size) { if (asset.size > 0 && archive.length() != asset.size) {
if (archive.length() > asset.size) { if (archive.length() > asset.size) {
archive.delete() archive.delete()
@@ -295,7 +290,6 @@ object ProtonExtras {
onProgress(context.getString(R.string.pextra_verifying), -1) onProgress(context.getString(R.string.pextra_verifying), -1)
val verified = when { val verified = when {
checked -> true
asset.sha256 != null -> asset.sha256.equals(Hashes.sha256(archive), ignoreCase = true) asset.sha256 != null -> asset.sha256.equals(Hashes.sha256(archive), ignoreCase = true)
asset.sha512 != null -> { asset.sha512 != null -> {
val expected = Downloader.downloadDirect(asset.sha512)?.let { Regex("(?i)\\b[0-9a-f]{128}\\b").find(it)?.value } val expected = Downloader.downloadDirect(asset.sha512)?.let { Regex("(?i)\\b[0-9a-f]{128}\\b").find(it)?.value }
@@ -342,7 +336,7 @@ object ProtonExtras {
archive.delete() archive.delete()
unqueue(context, tool) unqueue(context, tool)
record(context, tool, placed, asset.tag) record(context, tool, placed, asset.tag)
if (tool.id == OWN) replaceOlder(context, tool) if (tool.id == OWN || tool.id == BIONIC) replaceOlder(context, tool)
if (EsyncPacks.enabled(context)) { if (EsyncPacks.enabled(context)) {
onProgress(context.getString(R.string.esync_fetching), -1) onProgress(context.getString(R.string.esync_fetching), -1)
try { try {
@@ -427,7 +421,7 @@ object ProtonExtras {
internal fun pickAsset(tool: Tool, array: JSONArray): Asset? { internal fun pickAsset(tool: Tool, array: JSONArray): Asset? {
val candidates = (0 until array.length()).asSequence() val candidates = (0 until array.length()).asSequence()
.mapNotNull { array.optJSONObject(it) } .mapNotNull { array.optJSONObject(it) }
.filter { !it.optBoolean("draft", false) && !it.optBoolean("prerelease", false) } .filter { !it.optBoolean("draft", false) && (tool.prereleases || !it.optBoolean("prerelease", false)) }
return candidates.firstNotNullOfOrNull { assetOf(tool, it) } return candidates.firstNotNullOfOrNull { assetOf(tool, it) }
} }
@@ -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
}
}
@@ -95,11 +95,7 @@ object SessionFiles {
return all return all
} }
private val STAGE_LOCK = Any() fun stage(context: Context, root: File, startsSession: Boolean = false) {
fun stage(context: Context, root: File, startsSession: Boolean = false) = synchronized(STAGE_LOCK) { stageNow(context, root, startsSession) }
private fun stageNow(context: Context, root: File, startsSession: Boolean) {
if (DesktopCatalog.desktopInstalled(root) && !DesktopCatalog.desktopFromPack(root)) try { DesktopCatalog.cleanLegacy(context) } if (DesktopCatalog.desktopInstalled(root) && !DesktopCatalog.desktopFromPack(root)) try { DesktopCatalog.cleanLegacy(context) }
catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) } catch (e: Exception) { Log.w(TAG, "LXQt cleanup will retry next session", e) }
GameEnvironmentStore.publish(context) GameEnvironmentStore.publish(context)
@@ -130,7 +126,6 @@ object SessionFiles {
"usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard", "usr/local/bin/droiddeck-desktop-clipboard" to "usr/local/bin/droiddeck-desktop-clipboard",
"usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window", "usr/local/bin/droiddeck-gpu-window" to "usr/local/bin/droiddeck-gpu-window",
"usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install", "usr/local/bin/droiddeck-steam-install" to "usr/local/bin/droiddeck-steam-install",
"usr/local/bin/droiddeck-steam-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-ui-scale" to "usr/local/bin/droiddeck-steam-ui-scale",
"usr/local/bin/droiddeck-steam-language" to "usr/local/bin/droiddeck-steam-language", "usr/local/bin/droiddeck-steam-language" to "usr/local/bin/droiddeck-steam-language",
"usr/local/bin/droiddeck-steam-shaders" to "usr/local/bin/droiddeck-steam-shaders", "usr/local/bin/droiddeck-steam-shaders" to "usr/local/bin/droiddeck-steam-shaders",
@@ -186,7 +181,6 @@ object SessionFiles {
"usr/local/bin/droiddeck-appimage-run" to "usr/local/bin/droiddeck-appimage-run", "usr/local/bin/droiddeck-appimage-run" to "usr/local/bin/droiddeck-appimage-run",
"usr/local/bin/droiddeck-appimage-exec" to "usr/local/bin/droiddeck-appimage-exec", "usr/local/bin/droiddeck-appimage-exec" to "usr/local/bin/droiddeck-appimage-exec",
"usr/local/bin/droiddeck-curseforge" to "usr/local/bin/droiddeck-curseforge", "usr/local/bin/droiddeck-curseforge" to "usr/local/bin/droiddeck-curseforge",
"usr/local/bin/droiddeck-headless" to "usr/local/bin/droiddeck-headless",
"usr/local/bin/droiddeck-script-run" to "usr/local/bin/droiddeck-script-run", "usr/local/bin/droiddeck-script-run" to "usr/local/bin/droiddeck-script-run",
"usr/local/bin/droiddeck-open" to "usr/local/bin/droiddeck-open", "usr/local/bin/droiddeck-open" to "usr/local/bin/droiddeck-open",
"usr/local/bin/droiddeck-proton-run" to "usr/local/bin/droiddeck-proton-run", "usr/local/bin/droiddeck-proton-run" to "usr/local/bin/droiddeck-proton-run",
@@ -665,7 +659,6 @@ object SessionFiles {
private const val UI_STATE = "UIStoreLocalSteamUIState" private const val UI_STATE = "UIStoreLocalSteamUIState"
private const val SORT_RECENT_OFF = "\\\"bSortedByRecent\\\":false" private const val SORT_RECENT_OFF = "\\\"bSortedByRecent\\\":false"
private const val SORT_RECENT_ON = "\\\"bSortedByRecent\\\":true" private const val SORT_RECENT_ON = "\\\"bSortedByRecent\\\":true"
private const val LIBRARY_BIG_ART = "LibraryHomeBigArt"
private const val BATTERY_PERCENT_ON = "{\\\"bShowBatteryPercentage\\\":true}" private const val BATTERY_PERCENT_ON = "{\\\"bShowBatteryPercentage\\\":true}"
/** /**
@@ -715,12 +708,7 @@ object SessionFiles {
val block = out.substring(web.keyStart, web.close + 1) val block = out.substring(web.keyStart, web.close + 1)
out = out.replaceRange(web.keyStart, web.close + 1, setScalar(block, BATTERY_PREFERENCES, BATTERY_PERCENT_ON, newline)) out = out.replaceRange(web.keyStart, web.close + 1, setScalar(block, BATTERY_PREFERENCES, BATTERY_PERCENT_ON, newline))
} }
out = seedRecentSort(out, newline) return seedRecentSort(out, newline)
val last = findObject(out, "UserLocalConfigStore", 0, out.length) ?: return out
if (!hasKey(out.substring(last.open + 1, last.close), LIBRARY_BIG_ART)) {
out = insertInto(out, last, listOf("\"$LIBRARY_BIG_ART\"\t\t\"1\""), newline)
}
return out
} }
// The library sort lives inside a JSON string; Steam writes bSortedByRecent:false until the player picks a sort, // The library sort lives inside a JSON string; Steam writes bSortedByRecent:false until the player picks a sort,
@@ -740,11 +728,9 @@ object SessionFiles {
private fun insertInto(text: String, parent: VdfBlock, lines: List<String>, newline: String): String { private fun insertInto(text: String, parent: VdfBlock, lines: List<String>, newline: String): String {
val lineStart = text.lastIndexOf('\n', parent.close).let { if (it < 0) 0 else it + 1 } val lineStart = text.lastIndexOf('\n', parent.close).let { if (it < 0) 0 else it + 1 }
val before = text.substring(lineStart, parent.close) val indent = text.substring(lineStart, parent.close).takeWhile { it == '\t' || it == ' ' } + "\t"
val indent = before.takeWhile { it == '\t' || it == ' ' } + "\t"
val section = lines.joinToString(newline) { indent + it } + newline val section = lines.joinToString(newline) { indent + it } + newline
if (before.isBlank()) return text.substring(0, lineStart) + section + text.substring(lineStart) return text.substring(0, lineStart) + section + text.substring(lineStart)
return text.substring(0, parent.close) + newline + section + text.substring(parent.close)
} }
private val IDLE_SLEEP_TIMERS = listOf("IdleSuspendBatterySeconds", "IdleSuspendACSeconds") private val IDLE_SLEEP_TIMERS = listOf("IdleSuspendBatterySeconds", "IdleSuspendACSeconds")
@@ -63,13 +63,6 @@ object SessionPrefs {
.takeIf { value -> orientationOptions.any { it.first == value } } .takeIf { value -> orientationOptions.any { it.first == value } }
?: ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE ?: ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
/** The session menu's width in dp the user dragged it to; null keeps the default. */
fun drawerWidthDp(context: Context): Int? = prefs(context).getInt("drawerWidthDp", 0).takeIf { it > 0 }
fun setDrawerWidthDp(context: Context, dp: Int) {
prefs(context).edit().putInt("drawerWidthDp", dp).apply()
}
fun setOrientation(context: Context, orientation: Int) { fun setOrientation(context: Context, orientation: Int) {
require(orientationOptions.any { it.first == orientation }) require(orientationOptions.any { it.first == orientation })
prefs(context).edit().putInt("orientation", orientation).apply() prefs(context).edit().putInt("orientation", orientation).apply()
@@ -502,13 +495,6 @@ object SessionPrefs {
fun hudEnabled(context: Context): Boolean = prefs(context).getBoolean(hudKey(context), false) 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) { fun setHudEnabled(context: Context, on: Boolean) {
prefs(context).edit().putBoolean(hudKey(context), on).apply() prefs(context).edit().putBoolean(hudKey(context), on).apply()
} }
@@ -1025,7 +1011,7 @@ object SessionPrefs {
prefs(context).edit().putBoolean("prootNoSeccomp", on).apply() prefs(context).edit().putBoolean("prootNoSeccomp", on).apply()
} }
fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", true) fun nativeUserland(context: Context): Boolean = prefs(context).getBoolean("nativeUserland", false)
fun setNativeUserland(context: Context, on: Boolean) { fun setNativeUserland(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("nativeUserland", on).apply() prefs(context).edit().putBoolean("nativeUserland", on).apply()
@@ -1033,6 +1033,9 @@ class SessionService : Service() {
) )
(if (bridge || venus) null else LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId)) (if (bridge || venus) null else LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId))
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) } ?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
// DroidDeck-Bionic games load an Android driver build; this is the one the display uses, for a runtime driver
// that has none.
guest.add("DROIDDECK_DISPLAY_DRIVER=" + com.droiddeck.launcher.gpu.TurnipDriver(this).effectiveId())
if (!com.droiddeck.launcher.core.DeviceSupport.adreno() && lastXwaylandCrashed()) { if (!com.droiddeck.launcher.core.DeviceSupport.adreno() && lastXwaylandCrashed()) {
guest.add("XWAYLAND_NO_GLAMOR=1") guest.add("XWAYLAND_NO_GLAMOR=1")
Log.w(TAG, "xwayland: the last session's Xwayland crashed; glamor off for this one (XWAYLAND_NO_GLAMOR=1)") Log.w(TAG, "xwayland: the last session's Xwayland crashed; glamor off for this one (XWAYLAND_NO_GLAMOR=1)")
@@ -2705,7 +2708,6 @@ class SessionService : Service() {
gameId: String? = null, gameId: String? = null,
displayId: Int = Display.DEFAULT_DISPLAY, displayId: Int = Display.DEFAULT_DISPLAY,
) { ) {
SteamClientPrefetch.cancel()
SessionState.activityDisplayId = displayId SessionState.activityDisplayId = displayId
val intent = Intent(context, SessionService::class.java).putExtra(EXTRA_MODE, mode) val intent = Intent(context, SessionService::class.java).putExtra(EXTRA_MODE, mode)
.putExtra(EXTRA_DISPLAY_ID, displayId) .putExtra(EXTRA_DISPLAY_ID, displayId)
@@ -13,7 +13,7 @@ object SettingsReset {
internal val SESSION_KEYS = setOf( internal val SESSION_KEYS = setOf(
"orientation", "launcherFullscreen", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt", "orientation", "launcherFullscreen", "controllerHaptics", "animations", "lowStorageWarning", "theme", "runSteamAtStartup", "startupSession", "addedGamesArt",
"drawerWidthDp", "dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard", "dualScreenMode", "dualScreenSessionMode", "dualScreenLauncher", "dualScreenSessionControls", "androidTextFieldKeyboard",
"soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature", "soundtracksIngame", "gameStoresSpeedTier", "gameStoresParallel", "storesOpenTab", "storesShowMature",
"storesInstallLanguage", "storesInstallLanguage",
"hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "dockedMenuController", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController", "hud", "hudDeck", "hudFps", "hudBattery", "hudGraph", "hudColor", "hudOpacity", "__KEEP_droidDeckHud__", "__KEEP_droidDeckHudPos__", "backHold", "dockedMenuController", "backActionsInverted", "backDoubleTapMs", "touch", "pen", "penButton", "osc", "shape", "steamController",
@@ -1,103 +0,0 @@
package com.droiddeck.launcher.session
import android.content.Context
import android.util.Log
import com.droiddeck.launcher.runtime.LinuxRuntime
import java.io.File
import kotlinx.coroutines.flow.update
/**
* Downloads Valve's Steam client while the session is stopped, so the first Play does not wait on it.
* It runs the same droiddeck-steam-install the session runs, which keeps what arrived when it is cut
* short and resumes from there.
*/
object SteamClientPrefetch {
private const val TAG = "SteamClientPrefetch"
private val DOWNLOADING = Regex("""downloading Steam: .*, (\d+) of (\d+) MB""")
private const val CANCELLED = "cancelled"
private val lock = Any()
private var process: Process? = null
private var cancelled = false
@Volatile private var thread: Thread? = null
internal fun parse(line: String): Pair<Int, Int>? {
val match = DOWNLOADING.find(line) ?: return null
val done = match.groupValues[1].toLongOrNull() ?: return null
val total = match.groupValues[2].toLongOrNull()?.takeIf { it > 0 } ?: return null
return (done * 100 / total).toInt().coerceIn(0, 100) to total.toInt()
}
fun running(): Boolean = thread?.isAlive == true
private const val CACHED = "root/.local/share/Steam/package/droiddeck-cached"
fun installPending(context: Context): Boolean = SteamDownloadMonitor.clientInstallPending(LinuxRuntime.rootDir(context))
fun pending(context: Context): Boolean =
installPending(context) || !File(LinuxRuntime.rootDir(context), CACHED).isFile
/** Stops a running download so a session can take over; the script resumes the partial files. */
fun cancel() {
synchronized(lock) {
cancelled = true
process?.destroy()
}
}
private fun isCancelled() = synchronized(lock) { cancelled }
@Synchronized
fun start(context: Context, label: (Int) -> String, failedLabel: String) {
if (running() || SessionState.running || !LinuxRuntime.isInstalled(context) || !pending(context)) return
val app = context.applicationContext
synchronized(lock) { cancelled = false }
thread = Thread({
Onboarding.report(Onboarding.Step.STEAM, label(-1), -1)
val problem = runCatching { run(app, label) }.getOrElse { it.message ?: it.javaClass.simpleName }
synchronized(lock) { process = null }
if (problem == null && !pending(app)) Onboarding.finish(Onboarding.Step.STEAM)
else if (SessionState.running || problem == CANCELLED || isCancelled()) Onboarding.finish(Onboarding.Step.STEAM)
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() }
}
private fun run(context: Context, label: (Int) -> String): String? {
if (isCancelled()) return CANCELLED
val root = LinuxRuntime.rootDir(context)
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)
}
private fun script(context: Context, args: List<String>, label: (Int) -> String, from: Int, to: Int): String? {
val guest = listOf(
"/usr/bin/env", "-i", "HOME=/root", "USER=root", "PATH=/usr/local/bin:/usr/bin:/bin",
"LANG=C.UTF-8", "XDG_DATA_HOME=/root/.local/share", "/usr/local/bin/droiddeck-steam-install",
) + args
if (isCancelled()) return CANCELLED
val child = ProtonExtras.guestProcess(context, guest).start()
synchronized(lock) {
if (cancelled) {
child.destroy()
return CANCELLED
}
process = child
}
child.inputStream.bufferedReader().useLines { lines ->
lines.forEach { line ->
Log.i(TAG, line)
val progress = parse(line)
if (progress != null) Onboarding.report(Onboarding.Step.STEAM, label(progress.second), from + progress.first * (to - from) / 100)
}
}
val status = child.waitFor()
return if (status == 0) null else "droiddeck-steam-install exited $status"
}
}
@@ -36,14 +36,13 @@ object CloudPlan {
return Plan(transfer, conflicts, same) 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") if (baseline == null) return Plan(emptyList(), emptyList(), emptyList(), refused = "no-baseline")
val transfer = ArrayList<String>(); val conflicts = ArrayList<String>(); val same = ArrayList<String>() val transfer = ArrayList<String>(); val conflicts = ArrayList<String>(); val same = ArrayList<String>()
for ((name, l) in local) { for ((name, l) in local) {
val r = remote[name] val r = remote[name]
val b = baseline[name] val b = baseline[name]
when { when {
r == null && name in deleted && !localChanged(l, b) -> Unit
r == null -> transfer += name r == null -> transfer += name
same(l, r) -> same += name same(l, r) -> same += name
localChanged(l, b) && cloudChanged(r, b) -> conflicts += 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) } 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): Map<String, CloudFile> {
private fun remote(cloud: CloudTransport, wanted: (String) -> Boolean): Listing {
val files = cloud.list() val files = cloud.list()
val pool = Executors.newFixedThreadPool(PARALLEL, com.droiddeck.launcher.stores.download.DownloadQueue.workerFactory("cloud")) 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) } } for (f in files) if (wanted(f.name)) pool.execute { runCatching { cloud.details(f) } }
pool.shutdown(); pool.awaitTermination(2, TimeUnit.MINUTES) pool.shutdown(); pool.awaitTermination(2, TimeUnit.MINUTES)
val (gone, live) = files.partition(cloud::deleted) return files.associateBy { it.name }
return Listing(live.associateBy { it.name }, gone.mapTo(HashSet()) { it.name })
} }
internal fun downWith(context: Context, store: Store, id: String, dir: File, cloud: CloudTransport, force: Boolean, claim: () -> Boolean = { true }): Result { 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 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 local = files.mapValues { CloudPlan.Local(md5(it.value)) }
val key = scope(store, id, dir) val key = scope(store, id, dir)
val base = baseline(context, store, key) 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 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 } 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") if (files.isEmpty()) return Result("skipped", 0, 0, "nothing-local")
val listing = remote(cloud) { it in files } val remote = remote(cloud) { it in files }
val remote = listing.live
val local = files.mapValues { CloudPlan.Local(md5(it.value)) } 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 alike = alike(cloud, planned.conflicts, local, remote)
val plan = settled(planned, alike) val plan = settled(planned, alike)
val saved = savedConflicts(context, store, key).filter { it !in alike && it !in plan.same } 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 } send = send.filter { it in stamped }
for ((name, t) in stamped) if (t > 0) files[name]?.setLastModified(t) 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) { for (name in send) {
val r = cloud.committed(name) ?: after[name] val r = cloud.committed(name) ?: after[name]
next[name] = CloudPlan.Entry(sentMd5.getValue(name), r?.md5, r?.modifiedMs ?: stamped[name] ?: -1L) 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 val contentDigests: Boolean get() = true
fun committed(name: String): CloudFile? = null fun committed(name: String): CloudFile? = null
fun wants(name: String): Boolean = true fun wants(name: String): Boolean = true
fun deleted(file: CloudFile): Boolean = false
fun list(): List<CloudFile> fun list(): List<CloudFile>
fun details(file: CloudFile) {} fun details(file: CloudFile) {}
fun get(file: CloudFile): Pair<ByteArray, Long> 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" 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". */ /** 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) 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> { override fun list(): List<CloudFile> {
val c = open(base, "GET", token, ua) val c = open(base, "GET", token, ua)
c.setRequestProperty("Accept", "application/json")
val code = c.responseCode val code = c.responseCode
if (code == 404) { c.disconnect(); return emptyList() } if (code == 404) { c.disconnect(); return emptyList() }
if (code !in 200..299) { if (code !in 200..299) {
@@ -306,7 +300,7 @@ class GogCloud(
lm > 0 -> lm * 1000 lm > 0 -> lm * 1000
iso > 0 -> iso iso > 0 -> iso
else -> -1L else -> -1L
}, o.optString("hash").trim().ifEmpty { null }) })
} }
} else { } else {
text.lines().map { it.trim() }.filter { it.isNotEmpty() }.map { CloudFile(it, -1L) } text.lines().map { it.trim() }.filter { it.isNotEmpty() }.map { CloudFile(it, -1L) }
@@ -12,8 +12,11 @@ object StoreLaunch {
const val EPIC_CODE = ".droiddeck-epic-code" const val EPIC_CODE = ".droiddeck-epic-code"
const val EPIC_ARGS = ".droiddeck-epic-args" const val EPIC_ARGS = ".droiddeck-epic-args"
const val UBISOFT_LAUNCH = ".droiddeck-ubisoft.json" const val UBISOFT_LAUNCH = ".droiddeck-ubisoft.json"
private const val UBISOFT_SERVICE = "Z:\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe" /** DroidDeck-Bionic's Wine has Android's root on Z:; that tool sets this to the guest's root as its Wine names it. */
const val EPIC_PARENT = "Z:\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe" const val GUEST_ROOT = "DROIDDECK_GUEST_ROOT"
private const val ROOT_VAR = "DD_R"
private const val UBISOFT_SERVICE = "%$ROOT_VAR%\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe"
const val EPIC_PARENT = "%$ROOT_VAR%\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe"
/** Per-game environment switch: 1 starts any Epic game under [EPIC_PARENT], 0 never does. */ /** Per-game environment switch: 1 starts any Epic game under [EPIC_PARENT], 0 never does. */
const val EPIC_PARENT_SWITCH = "DD_EPIC_PARENT" const val EPIC_PARENT_SWITCH = "DD_EPIC_PARENT"
/** Epic app names whose launchers treat the game as unowned unless a process named EpicGamesLauncher.exe started it. */ /** Epic app names whose launchers treat the game as unowned unless a process named EpicGamesLauncher.exe started it. */
@@ -47,6 +50,10 @@ object StoreLaunch {
for ((k, v) in sidecar.env) if (ENV_NAME.matches(k)) lines += "set \"$k=${v.replace("\"", "")}\"" for ((k, v) in sidecar.env) if (ENV_NAME.matches(k)) lines += "set \"$k=${v.replace("\"", "")}\""
val args = sidecar.args.joinToString(" ") { if (sidecar.store == Store.ROCKSTAR) batchArg(it) else quoteArg(it) } val args = sidecar.args.joinToString(" ") { if (sidecar.store == Store.ROCKSTAR) batchArg(it) else quoteArg(it) }
val run = "\"%~dp0$exe\"" + (if (args.isNotEmpty()) " $args" else "") val run = "\"%~dp0$exe\"" + (if (args.isNotEmpty()) " $args" else "")
if (sidecar.store == Store.EPIC || sidecar.store == Store.UBISOFT) {
lines += "set \"$ROOT_VAR=Z:\""
lines += "if defined $GUEST_ROOT set \"$ROOT_VAR=%$GUEST_ROOT%\""
}
if (sidecar.store == Store.EPIC) { if (sidecar.store == Store.EPIC) {
lines += "set \"$PARENT_VAR=${if (sidecar.id in EPIC_PARENT_TITLES) "1" else ""}\"" lines += "set \"$PARENT_VAR=${if (sidecar.id in EPIC_PARENT_TITLES) "1" else ""}\""
lines += "if \"%$EPIC_PARENT_SWITCH%\"==\"1\" set \"$PARENT_VAR=1\"" lines += "if \"%$EPIC_PARENT_SWITCH%\"==\"1\" set \"$PARENT_VAR=1\""
@@ -137,7 +144,6 @@ object StoreLaunch {
if (sidecar.store !in listOf(Store.UBISOFT, Store.ROCKSTAR) || !sidecar.isInstalled) return sidecar if (sidecar.store !in listOf(Store.UBISOFT, Store.ROCKSTAR) || !sidecar.isInstalled) return sidecar
if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(File(folder, LAUNCHER).toPath())) return sidecar.copy(launcher = null) if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(File(folder, LAUNCHER).toPath())) return sidecar.copy(launcher = null)
val wrongExe = !sidecar.exeFile(folder).isFile || sidecar.exe.contains("installer", ignoreCase = true) || sidecar.exe.contains("autorun", ignoreCase = true) val wrongExe = !sidecar.exeFile(folder).isFile || sidecar.exe.contains("installer", ignoreCase = true) || sidecar.exe.contains("autorun", ignoreCase = true)
if (sidecar.store == Store.UBISOFT && sidecar.launcher == LAUNCHER && !wrongExe) return sidecar
val metadataExe = if (sidecar.store == Store.ROCKSTAR) com.droiddeck.launcher.stores.rockstar.RockstarMetadata.find(folder)?.exe val metadataExe = if (sidecar.store == Store.ROCKSTAR) com.droiddeck.launcher.stores.rockstar.RockstarMetadata.find(folder)?.exe
?.takeIf { File(folder, it).isFile && File(folder, it).canonicalPath.startsWith(folder.canonicalPath + File.separator) } else null ?.takeIf { File(folder, it).isFile && File(folder, it).canonicalPath.startsWith(folder.canonicalPath + File.separator) } else null
val exe = metadataExe ?: if (wrongExe) StoreExe.pick(folder, null, sidecar.title).ifEmpty { sidecar.exe } else sidecar.exe val exe = metadataExe ?: if (wrongExe) StoreExe.pick(folder, null, sidecar.title).ifEmpty { sidecar.exe } else sidecar.exe
@@ -100,7 +100,6 @@ internal object GogContent {
val manifest = metadata(build.link, token) val manifest = metadata(build.link, token)
onManifest(manifest) onManifest(manifest)
val files = JSONArray() 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") 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" } check(depots != null) { "GOG build has no depot list" }
val resolvedLanguage = StoreLanguage.pick(StoreLanguage.codesFromDepots(depots), old.language) val resolvedLanguage = StoreLanguage.pick(StoreLanguage.codesFromDepots(depots), old.language)
@@ -133,15 +132,10 @@ internal object GogContent {
val directory = type == "DepotDirectory" || entry.has("directory") val directory = type == "DepotDirectory" || entry.has("directory")
val chunks = entry.optJSONArray("chunks") ?: JSONArray() val chunks = entry.optJSONArray("chunks") ?: JSONArray()
val size = if (build.generation == 2) chunks.objects().sumOf { it.optLong("size") } else entry.optLong("size") 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("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("sha256", entry.optString("sha256")).put("chunks", chunks).put("product", product)
.put("offset", entry.optLong("offset")).put("remotePath", entry.optString("url").substringBefore('?')) .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)
}
} }
} }
check(files.length() > 0) { "GOG build contains no matching files" } check(files.length() > 0) { "GOG build contains no matching files" }
@@ -330,7 +330,7 @@ public final class GogDownloadManager {
rc = GuestCommand.INSTANCE.run(ctx, Arrays.asList( rc = GuestCommand.INSTANCE.run(ctx, Arrays.asList(
"/usr/local/bin/droiddeck-innoextract", "--gog", "--silent", "/usr/local/bin/droiddeck-innoextract", "--gog", "--silent",
"-d", guestDir, guestSetup), "-d", guestDir, guestSetup),
false, "gog-innoextract", null, null, false, cancelled, null, false, "gog-innoextract", null, null, false, cancelled,
line -> { cb.onLog("gog innoextract: " + line); return kotlin.Unit.INSTANCE; }); line -> { cb.onLog("gog innoextract: " + line); return kotlin.Unit.INSTANCE; });
} catch (Exception e) { } catch (Exception e) {
throw new InstallException("The installer could not be extracted: " + e.getClass().getSimpleName()); throw new InstallException("The installer could not be extracted: " + e.getClass().getSimpleName());
@@ -103,9 +103,7 @@ internal class XboxInstaller(private val app: Context, private val item: Catalog
XboxContent.complete(app, item, folder) XboxContent.complete(app, item, folder)
return folder.path return folder.path
} }
val exe = runCatching { executable(folder) }.onFailure { val exe = executable(folder)
StoresState.logLine("Xbox: install folder holds ${folder.list().orEmpty().sorted().take(MAX_ERROR_LINES).joinToString()}")
}.getOrThrow()
StoreInstalls.complete(app, folder, StoreGameSidecar(Store.XBOX, item.id, item.title, exe, StoreInstalls.complete(app, folder, StoreGameSidecar(Store.XBOX, item.id, item.title, exe,
installVersion = XboxManifest.read(folder).version, installedAt = System.currentTimeMillis(), cover = item.tallImageUrl, hero = item.imageUrl, installVersion = XboxManifest.read(folder).version, installedAt = System.currentTimeMillis(), cover = item.tallImageUrl, hero = item.imageUrl,
extra = item.extra + mapOf("contentId" to selected, "market" to market))) extra = item.extra + mapOf("contentId" to selected, "market" to market)))
@@ -21,9 +21,8 @@ internal object XboxManifest {
val files = folder.listFiles().orEmpty() val files = folder.listFiles().orEmpty()
val config = files.filter { it.name.equals(GAME_CONFIG, true) && it.isFile } val config = files.filter { it.name.equals(GAME_CONFIG, true) && it.isFile }
val legacy = files.filter { it.name.equals(APPX_MANIFEST, true) && it.isFile } val legacy = files.filter { it.name.equals(APPX_MANIFEST, true) && it.isFile }
val manifests = config.ifEmpty { legacy } require(config.size + legacy.size == 1) { "Missing or ambiguous game manifest." }
require(manifests.size == 1) { "Missing or ambiguous game manifest." } val manifest = (config + legacy).single()
val manifest = manifests.single()
val rootTag = if (config.isEmpty()) "Package" else "Game" val rootTag = if (config.isEmpty()) "Package" else "Game"
require(manifest.length() <= 1_048_576) require(manifest.length() <= 1_048_576)
val parser = android.util.Xml.newPullParser().apply { setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, false) } val parser = android.util.Xml.newPullParser().apply { setFeature(XmlPullParser.FEATURE_PROCESS_DOCDECL, false) }
@@ -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
}
@@ -37,7 +37,6 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.produceState import androidx.compose.runtime.produceState
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.withFrameNanos
import androidx.compose.runtime.setValue import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment import androidx.compose.ui.Alignment
@@ -54,7 +53,6 @@ import androidx.compose.ui.input.InputMode
import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalInputModeManager import androidx.compose.ui.platform.LocalInputModeManager
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.ImeAction
@@ -62,8 +60,6 @@ import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import coil.compose.AsyncImage import coil.compose.AsyncImage
import com.droiddeck.launcher.R import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.AddedGames import com.droiddeck.launcher.frontend.AddedGames
@@ -71,19 +67,14 @@ import com.droiddeck.launcher.runtime.CurseForgeApp
import com.droiddeck.launcher.runtime.UserApps import com.droiddeck.launcher.runtime.UserApps
import com.droiddeck.launcher.runtime.WowAddonCatalog import com.droiddeck.launcher.runtime.WowAddonCatalog
import com.droiddeck.launcher.runtime.WowAddons import com.droiddeck.launcher.runtime.WowAddons
import com.droiddeck.launcher.session.BackgroundSession
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState import com.droiddeck.launcher.session.SessionState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext import kotlinx.coroutines.withContext
import java.io.File import java.io.File
import java.io.IOException
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
private class AddonResults { private class AddonResults {
val items = mutableStateListOf<WowAddonCatalog.Addon>() val items = mutableStateListOf<WowAddonCatalog.Addon>()
@@ -93,69 +84,26 @@ private class AddonResults {
var more by mutableStateOf(false) var more by mutableStateOf(false)
} }
internal enum class AddonStatus { INSTALL, UPDATE, INSTALLED } private enum class AddonStatus { INSTALL, UPDATE, INSTALLED }
private enum class AddonSource { WOWI, CURSE } private enum class AddonSource { WOWI, CURSE }
internal class CurseState(val notice: Int? = null) : Exception() private class CurseState(val notice: Int? = null) : Exception()
internal class CurseLink(val app: UserApps.App) { private class CurseLink(val app: UserApps.App) {
class Linked(val inspector: String, val guid: String) class Linked(val inspector: String, val guid: String)
private val lock = Object() private val lock = Object()
private val work = SupervisorJob()
@Volatile private var closed = false @Volatile private var closed = false
@Volatile private var hold: AtomicBoolean? = null private var held = false
private var ownSession: String? = null
private var started = false
@Volatile private var launching = false
@Volatile private var inspector: String? = null @Volatile private var inspector: String? = null
private val guids = HashMap<String, String>() private val guids = HashMap<String, String>()
private val scanLock = Object()
private val scans = HashMap<String, Pair<Any, List<CurseForgeApp.Project>>>()
private val settleLock = Object()
private val settled = HashMap<String, Pair<Int, List<CurseForgeApp.Project>>>()
private val turns = HashMap<String, Int>()
var generation by mutableIntStateOf(0)
private set
fun refresh() { fun <T> call(context: Context, target: WowAddons.Target, block: (Linked) -> T): T {
generation++ val linked = synchronized(lock) { link(context, target) }
}
fun installed(context: Context, target: WowAddons.Target, key: Any): List<CurseForgeApp.Project> = CurseForgeApp.onDisk(
synchronized(scanLock) {
scans[target.addOns.path]?.takeIf { it.first == key }?.second
?: (settledFor(target) ?: call(context, target) { CurseForgeApp.projects(context, it.inspector, it.guid, rescan = true) }).also {
scans[target.addOns.path] = key to it
report(target, it)
}
},
target.addOns,
)
fun marks(context: Context, target: WowAddons.Target, key: Any): Map<String, String?> =
runCatching { installed(context, target, key).associate { it.id to curseMark(it) } }.getOrElse { lastReported(target) }
private fun settledFor(target: WowAddons.Target): List<CurseForgeApp.Project>? = synchronized(settleLock) {
settled.remove(target.addOns.path)?.takeIf { it.first == generation }?.second
}
fun change(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> List<CurseForgeApp.Project>?): Boolean {
val path = target.addOns.path
val turn = synchronized(settleLock) {
settled.remove(path)
((turns[path] ?: 0) + 1).also { turns[path] = it }
}
val projects = call(context, target, launch, block) ?: return false
synchronized(settleLock) {
if (turns[path] == turn) {
settled[path] = generation to projects
report(target, projects)
}
}
return true
}
fun <T> call(context: Context, target: WowAddons.Target, launch: Boolean = true, block: (Linked) -> T): T {
val linked = synchronized(lock) { link(context, target, launch) }
try { try {
return block(linked) return block(linked)
} catch (e: CurseForgeApp.Failure) { } catch (e: CurseForgeApp.Failure) {
@@ -163,25 +111,38 @@ internal class CurseLink(val app: UserApps.App) {
if (inspector == linked.inspector) { if (inspector == linked.inspector) {
inspector = null inspector = null
guids.clear() guids.clear()
current.compareAndSet(this, null)
} }
} }
throw e throw e
} }
} }
private fun link(context: Context, target: WowAddons.Target, launch: Boolean): Linked { private fun link(context: Context, target: WowAddons.Target): Linked {
if (closed) throw CurseState() if (closed) throw CurseState()
if (!SessionState.running) {
started = false
launching = false
held = false
ownSession = null
inspector = null
guids.clear()
val args = CurseForgeApp.holdArgs(app) ?: throw CurseState()
ownSession = BackgroundSession.start(context, CurseForgeApp.HELPER, args) ?: throw CurseState()
}
if (closed) throw CurseState()
if (!held) {
held = true
SessionService.holdForSignIn(context, true)
}
val awake = System.currentTimeMillis() + 30_000
while ((SessionState.suspended || SessionState.suspending) && System.currentTimeMillis() < awake) Thread.sleep(250)
val url = inspector ?: run { val url = inspector ?: run {
if (!launch) throw CurseState() launching = true
val hold = AtomicBoolean(false) val done = CurseForgeApp.start(context, app)
this.hold = hold
if (closed) throw CurseState()
val done = CurseForgeApp.start(context, app, hold)
when (done.state) { when (done.state) {
CurseForgeApp.Start.READY -> { CurseForgeApp.Start.READY -> {
started = true
inspector = done.inspector inspector = done.inspector
if (!closed) current.set(this)
done.inspector ?: throw CurseState() done.inspector ?: throw CurseState()
} }
CurseForgeApp.Start.BUSY -> throw CurseState(R.string.addons_curse_busy) CurseForgeApp.Start.BUSY -> throw CurseState(R.string.addons_curse_busy)
@@ -197,74 +158,29 @@ internal class CurseLink(val app: UserApps.App) {
return Linked(url, guid) return Linked(url, guid)
} }
fun uninstall(context: Context, target: WowAddons.Target, folder: String): Boolean = change(context, target, launch = false) { linked -> fun close(context: Context) {
val projects = CurseForgeApp.onDisk(CurseForgeApp.projects(context, linked.inspector, linked.guid), target.addOns)
CurseForgeApp.owner(projects, folder)?.let { CurseForgeApp.uninstall(context, linked.inspector, linked.guid, it) ?: throw CurseState() }
}
internal val stopped: Job get() = work
fun close(context: Context): Job {
closed = true closed = true
current.compareAndSet(this, null) Thread {
val launch = hold if (launching) CurseForgeApp.stop(context, app, inspector)
return CoroutineScope(work + Dispatchers.IO).launch {
if (launch != null) CurseForgeApp.stop(context, app, inspector, launch)
synchronized(lock) { synchronized(lock) {
hold = null if (started) CurseForgeApp.stop(context, app, inspector)
val owned = ownSession
if (owned != null) BackgroundSession.stop(context, owned)
else if (held) SessionService.holdForSignIn(context, false)
started = false
launching = false
ownSession = null
held = false
inspector = null inspector = null
} }
}.also { work.complete() } }.start()
}
companion object {
private val current = AtomicReference<CurseLink?>()
private val reported = ConcurrentHashMap<String, List<CurseForgeApp.Project>>()
fun lastReported(target: WowAddons.Target, disk: () -> List<WowAddons.Installed> = { WowAddons.details(target) }): Map<String, String?> {
val last = reported[target.addOns.path] ?: return disk().mapNotNull { it.curseId }.associateWith { null }
return CurseForgeApp.onDisk(last, target.addOns).associate { it.id to null }
}
internal fun report(target: WowAddons.Target, projects: List<CurseForgeApp.Project>) {
reported[target.addOns.path] = projects
}
fun live(): CurseLink? = current.get()
} }
} }
private const val PAGES_AHEAD = 8 private const val PAGES_AHEAD = 8
private const val CURSE_UPDATE = "update"
private const val UNINSTALLING = -1
private fun curseMark(project: CurseForgeApp.Project): String? = CURSE_UPDATE.takeIf { project.update }
private class Present(val curse: Map<String, String?> = emptyMap(), val disk: Map<String, WowAddons.Installed> = emptyMap())
@Composable @Composable
internal fun rememberCurseLink(app: UserApps.App?, sessionRunning: Boolean): CurseLink? { internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, curseForge: UserApps.App?, onDismiss: () -> Unit) {
val context = LocalContext.current.applicationContext
val owner = LocalLifecycleOwner.current
var visible by remember(owner) { mutableStateOf(owner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) }
DisposableEffect(owner) {
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_START) visible = true
if (event == Lifecycle.Event.ON_STOP) visible = false
}
owner.lifecycle.addObserver(observer)
onDispose { owner.lifecycle.removeObserver(observer) }
}
val active = visible && !sessionRunning
val link = remember(app?.key, active) { app?.takeIf { active }?.let(::CurseLink) }
DisposableEffect(link) {
onDispose { link?.close(context) }
}
return link
}
@Composable
internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAddons.Target, curseForge: UserApps.App?, link: CurseLink?, onDismiss: () -> Unit) {
val context = LocalContext.current.applicationContext val context = LocalContext.current.applicationContext
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
val shown = rememberShown(onDismiss) val shown = rememberShown(onDismiss)
@@ -274,8 +190,11 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
var category by remember { mutableStateOf<WowAddonCatalog.Category?>(null) } var category by remember { mutableStateOf<WowAddonCatalog.Category?>(null) }
var sort by remember { mutableStateOf(WowAddonCatalog.Sort.POPULAR) } var sort by remember { mutableStateOf(WowAddonCatalog.Sort.POPULAR) }
var source by remember { mutableStateOf(AddonSource.WOWI) } var source by remember { mutableStateOf(AddonSource.WOWI) }
val curse = if (source == AddonSource.CURSE && link != null) curseForge else null val curse = if (source == AddonSource.CURSE) curseForge else null
LaunchedEffect(link) { link?.refresh() } val link = remember(curseForge?.key) { curseForge?.let(::CurseLink) }
DisposableEffect(link) {
onDispose { link?.close(context) }
}
var notice by remember { mutableStateOf<Int?>(null) } var notice by remember { mutableStateOf<Int?>(null) }
var curseInstalls by remember { mutableIntStateOf(0) } var curseInstalls by remember { mutableIntStateOf(0) }
val results = remember(text, category, sort, target, curse) { AddonResults() } val results = remember(text, category, sort, target, curse) { AddonResults() }
@@ -285,21 +204,20 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
value = withContext(Dispatchers.IO) { runCatching { WowAddonCatalog.categories(context) }.getOrDefault(emptyList()) } value = withContext(Dispatchers.IO) { runCatching { WowAddonCatalog.categories(context) }.getOrDefault(emptyList()) }
} }
val presentKey = curse to target.addOns val presentKey = curse to target.addOns
val scanKey = link?.generation to WowAddons.imports val snapshot by produceState(presentKey to emptyMap<String, String?>(), target.addOns, WowAddons.imports, curse, curseInstalls, results.items.isEmpty()) {
val snapshot by produceState(presentKey to Present(), target.addOns, scanKey, curse, curseInstalls, curse == null && results.items.isEmpty()) {
val into = target val into = target
val key = curse to into.addOns val key = curse to into.addOns
if (curse != null && link != null && value.first != key) value = key to withContext(Dispatchers.IO) { Present(curse = CurseLink.lastReported(into)) }
value = key to withContext(Dispatchers.IO) { value = key to withContext(Dispatchers.IO) {
if (curse != null && link != null) Present(curse = link.marks(context, into, scanKey)) if (curse != null && link != null) runCatching { link.call(context, into) { CurseForgeApp.installed(context, it.inspector, it.guid) }.associateWith { null } }.getOrDefault(emptyMap())
else Present(disk = WowAddons.details(into).associateBy { it.name.lowercase() }) else WowAddons.details(into).mapNotNull { item -> item.wowiId?.let { it to item.version } }.toMap()
} }
} }
val present = snapshot.second.takeIf { snapshot.first == presentKey } ?: Present() val present = snapshot.second.takeIf { snapshot.first == presentKey } ?: emptyMap()
fun status(addon: WowAddonCatalog.Addon): AddonStatus { fun status(addon: WowAddonCatalog.Addon): AddonStatus {
if (curse != null) return if (addon.id !in present.curse) AddonStatus.INSTALL else if (present.curse[addon.id] == CURSE_UPDATE) AddonStatus.UPDATE else AddonStatus.INSTALLED if (addon.id !in present) return AddonStatus.INSTALL
val have = present[addon.id]
val latest = installed[installKey(addon, target)]?.takeIf { it.first == addon.summary }?.second ?: addon.summary val latest = installed[installKey(addon, target)]?.takeIf { it.first == addon.summary }?.second ?: addon.summary
return diskStatus(addon.folders, present.disk, latest, addon.id) return if (have == null || latest.isBlank() || WowAddonCatalog.sameVersion(have, latest)) AddonStatus.INSTALLED else AddonStatus.UPDATE
} }
fun load(page: Int) { fun load(page: Int) {
if (results.loading) return if (results.loading) return
@@ -338,23 +256,16 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
val via = link?.takeIf { curse != null } val via = link?.takeIf { curse != null }
if (via != null) { if (via != null) {
val into = target val into = target
val updating = status(addon) == AddonStatus.UPDATE
installing[key] = 0 installing[key] = 0
scope.launch { scope.launch {
val done = withContext(Dispatchers.IO) { val done = withContext(Dispatchers.IO) { runCatching { via.call(context, into) { CurseForgeApp.install(context, it.inspector, it.guid, addon.id) } } }
runCatching {
via.change(context, into) {
if (updating) CurseForgeApp.update(context, it.inspector, it.guid, addon.id)
else CurseForgeApp.install(context, it.inspector, it.guid, addon.id)
}
}
}
installing.remove(key) installing.remove(key)
val ok = done.getOrNull() == true val ok = done.getOrNull() == true
WowAddons.changed() if (ok) {
curseInstalls++ WowAddons.changed()
curseInstalls++
}
val message = when { val message = when {
ok && updating -> context.getString(R.string.user_apps_updated, addon.name)
ok -> context.resources.getQuantityString(R.plurals.main_addons_imported, 1, 1, into.flavor) ok -> context.resources.getQuantityString(R.plurals.main_addons_imported, 1, 1, into.flavor)
else -> (done.exceptionOrNull() as? CurseState)?.notice?.let(context::getString) else -> (done.exceptionOrNull() as? CurseState)?.notice?.let(context::getString)
?: context.getString(R.string.stores_dl_failed_reason, done.exceptionOrNull()?.message ?: addon.name) ?: context.getString(R.string.stores_dl_failed_reason, done.exceptionOrNull()?.message ?: addon.name)
@@ -376,32 +287,6 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
Toast.makeText(context, message.first, Toast.LENGTH_LONG).show() Toast.makeText(context, message.first, Toast.LENGTH_LONG).show()
} }
} }
fun uninstall(addon: WowAddonCatalog.Addon) {
val key = installKey(addon, target)
if (key in installing) return
if (SessionState.running) {
Toast.makeText(context, R.string.main_addons_close_session, Toast.LENGTH_LONG).show()
return
}
val into = target
val via = link?.takeIf { curse != null }
installing[key] = UNINSTALLING
scope.launch {
val done = withContext(Dispatchers.IO) {
runCatching {
val folders = if (via != null) curseFolders(into, addon.id, via.call(context, into) { linked ->
CurseForgeApp.projects(context, linked.inspector, linked.guid).firstOrNull { it.id == addon.id }?.folders.orEmpty()
}) else addon.folders
deleteAddons(context, into, folders, link)
}
}
installing.remove(key)
installed.remove(key)
WowAddons.changed()
curseInstalls++
if (done.isFailure) Toast.makeText(context, R.string.fm_delete_failed, Toast.LENGTH_LONG).show()
}
}
val sourceName = stringResource(if (curse != null) R.string.addons_source_curse else R.string.addons_source_wowi) val sourceName = stringResource(if (curse != null) R.string.addons_source_curse else R.string.addons_source_wowi)
val grid = rememberLazyGridState() val grid = rememberLazyGridState()
LaunchedEffect(results, grid) { LaunchedEffect(results, grid) {
@@ -483,7 +368,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
) { ) {
items(results.items, key = { it.id }) { addon -> items(results.items, key = { it.id }) { addon ->
val key = installKey(addon, target) val key = installKey(addon, target)
AddonRow(addon, status(addon), installing[key], if (addon.id == results.items.firstOrNull()?.id) Modifier.focusRequester(firstAction) else Modifier, { uninstall(addon) }) { install(addon) } AddonRow(addon, status(addon), installing[key], if (addon.id == results.items.firstOrNull()?.id) Modifier.focusRequester(firstAction) else Modifier) { install(addon) }
} }
item(span = { GridItemSpan(maxLineSpan) }) { item(span = { GridItemSpan(maxLineSpan) }) {
Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) { Column(Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp)) {
@@ -506,22 +391,7 @@ internal fun AddonBrowserDialog(targets: List<WowAddons.Target>, initial: WowAdd
} }
@Composable @Composable
internal fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress: Int?, action: Modifier, onUninstall: () -> Unit, onInstall: () -> Unit) { private fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progress: Int?, action: Modifier, onInstall: () -> Unit) {
var asking by remember(addon.id) { mutableStateOf(false) }
val first = remember(addon.id) { FocusRequester() }
var refocus by remember(addon.id) { mutableStateOf(false) }
val inputMode = LocalInputModeManager.current
LaunchedEffect(status, progress) {
if (!refocus) return@LaunchedEffect
withFrameNanos { }
runCatching { first.requestFocus() }
if (progress == null) refocus = false
}
fun act(block: () -> Unit) {
refocus = inputMode.inputMode == InputMode.Keyboard
block()
}
val lead = action.focusRequester(first)
val colors = MaterialTheme.colorScheme val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current val pal = LocalPalette.current
Row( Row(
@@ -539,24 +409,13 @@ internal fun AddonRow(addon: WowAddonCatalog.Addon, status: AddonStatus, progres
fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
) )
} }
val uninstall = stringResource(R.string.common_uninstall) val size = action
when { when {
progress == UNINSTALLING -> SecondaryButton(stringResource(R.string.stores_uninstalling), compact = true, modifier = lead) {} progress != null -> SecondaryButton(stringResource(R.string.store_installing), compact = true, modifier = size, progress = progress / 100f, onClick = onInstall)
progress != null -> SecondaryButton(stringResource(R.string.store_installing), compact = true, modifier = lead, progress = progress / 100f, onClick = onInstall) status == AddonStatus.INSTALLED -> SecondaryButton(stringResource(R.string.stores_installed_chip), enabled = false, compact = true, modifier = size) {}
status == AddonStatus.INSTALL -> PrimaryButton(stringResource(R.string.store_install), compact = true, modifier = lead) { act(onInstall) } else -> PrimaryButton(stringResource(if (status == AddonStatus.UPDATE) R.string.common_update else R.string.store_install), compact = true, modifier = size, onClick = onInstall)
else -> {
if (status == AddonStatus.UPDATE) PrimaryButton(stringResource(R.string.common_update), compact = true, modifier = lead) { act(onInstall) }
SecondaryButton(uninstall, compact = true, modifier = if (status == AddonStatus.UPDATE) Modifier else lead) { asking = true }
}
} }
} }
if (asking) ConfirmDialog(
title = stringResource(R.string.stores_uninstall_title, addon.name),
text = stringResource(R.string.games_delete_addon_body),
confirm = stringResource(R.string.common_uninstall),
onConfirm = { asking = false; act(onUninstall) },
onDismiss = { asking = false },
)
} }
private fun Modifier.scrollThumb(state: LazyGridState, color: Color): Modifier = drawWithContent { private fun Modifier.scrollThumb(state: LazyGridState, color: Color): Modifier = drawWithContent {
@@ -605,25 +464,4 @@ internal fun installAddon(context: Context, addon: WowAddonCatalog.Addon, target
} }
} }
internal fun diskStatus(folders: List<String>, onDisk: Map<String, WowAddons.Installed>, latest: String, id: String): AddonStatus {
if (!WowAddons.present(folders) { it.lowercase() in onDisk }) return AddonStatus.INSTALL
val have = onDisk.getValue(folders.first().lowercase())
return if (WowAddonCatalog.offersUpdate(have.version, latest, sameSource = have.wowiId == id)) AddonStatus.UPDATE else AddonStatus.INSTALLED
}
internal fun curseFolders(target: WowAddons.Target, id: String, listed: List<String>): List<String> =
listed.ifEmpty { WowAddons.details(target).filter { it.curseId == id }.map { it.name } }
internal fun deleteAddons(context: Context, target: WowAddons.Target, folders: List<String>, link: CurseLink?) {
val found = folders.mapNotNull { WowAddons.folder(target.addOns, it) }
if (found.isEmpty()) throw IOException("No addon folder to delete")
found.forEach { deleteAddon(context, target, it.name, link) }
}
internal fun deleteAddon(context: Context, target: WowAddons.Target, folder: String, link: CurseLink? = CurseLink.live()) {
val managed = link?.let { runCatching { it.uninstall(context, target, folder) }.getOrDefault(false) } == true
val left = WowAddons.folder(target.addOns, folder)
if (managed || left == null) WowAddons.changed() else WowAddons.delete(target, left.name)
}
private fun installKey(addon: WowAddonCatalog.Addon, target: WowAddons.Target) = addon.id + "|" + target.addOns.path private fun installKey(addon: WowAddonCatalog.Addon, target: WowAddons.Target) = addon.id + "|" + target.addOns.path
@@ -11,7 +11,6 @@ import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.animation.expandVertically import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeIn
import androidx.compose.animation.shrinkHorizontally import androidx.compose.animation.shrinkHorizontally
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandHorizontally import androidx.compose.animation.expandHorizontally
import androidx.compose.animation.fadeOut import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically import androidx.compose.animation.shrinkVertically
@@ -229,14 +228,8 @@ private fun AgentPageContent(
} }
val topBar: @Composable () -> Unit = { AgentTopBar(panel, togglePanel, inputModifier, menu) } val topBar: @Composable () -> Unit = { AgentTopBar(panel, togglePanel, inputModifier, menu) }
val inlineControls: (@Composable () -> Unit)? = if (inline) ({ val inlineControls: (@Composable () -> Unit)? = if (inline) ({
// The open menu needs the row's width for its own buttons. ModelChip(panel, togglePanel, inputModifier, compact = true)
androidx.compose.animation.AnimatedVisibility(!menuOpen, enter = expandHorizontally(expandFrom = Alignment.Start) + fadeIn(), ContextRing("agent-usage", onClick = { togglePanel(AgentPanel.USAGE) })
exit = shrinkHorizontally(shrinkTowards = Alignment.Start) + fadeOut()) {
Row(verticalAlignment = Alignment.CenterVertically) {
ModelChip(panel, togglePanel, inputModifier, compact = true)
ContextRing("agent-usage", onClick = { togglePanel(AgentPanel.USAGE) })
}
}
menu() menu()
}) else null }) else null
// A host with a title bar shows the top bar there. // A host with a title bar shows the top bar there.
@@ -252,11 +245,8 @@ private fun AgentPageContent(
LaunchedEffect(AgentHost.approvals.size, panel) { LaunchedEffect(AgentHost.approvals.size, panel) {
if (AgentHost.approvals.isNotEmpty() && (panel == AgentPanel.HISTORY || panel == AgentPanel.PROCESSES || panel == AgentPanel.TOOLS)) panel = AgentPanel.NONE if (AgentHost.approvals.isNotEmpty() && (panel == AgentPanel.HISTORY || panel == AgentPanel.PROCESSES || panel == AgentPanel.TOOLS)) panel = AgentPanel.NONE
} }
androidx.compose.foundation.layout.BoxWithConstraints(modifier.fillMaxSize()) {
// On a short page the picker would take it all and leave no conversation, so it scrolls within a share of the page.
val panelMax = maxHeight * 0.5f
Column( Column(
Modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e -> modifier.fillMaxSize().imePadding().onPreviewKeyEvent { e ->
val k = e.nativeKeyEvent val k = e.nativeKeyEvent
if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y || composer.focused) return@onPreviewKeyEvent false if (k.keyCode != KeyEvent.KEYCODE_BUTTON_Y || composer.focused) return@onPreviewKeyEvent false
if (k.action == KeyEvent.ACTION_UP) composer.open() if (k.action == KeyEvent.ACTION_UP) composer.open()
@@ -279,8 +269,8 @@ private fun AgentPageContent(
else -> { else -> {
if (menuSlot == null && !inline) Box(Modifier.padding(bottom = 6.dp)) { topBar() } if (menuSlot == null && !inline) Box(Modifier.padding(bottom = 6.dp)) { topBar() }
when (panel) { when (panel) {
AgentPanel.MODEL -> Box(Modifier.heightIn(max = panelMax).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { AgentModelPicker() } AgentPanel.MODEL -> Box(Modifier.padding(bottom = 8.dp)) { AgentModelPicker() }
AgentPanel.USAGE -> Box(Modifier.heightIn(max = panelMax).verticalScroll(rememberScrollState()).padding(bottom = 8.dp)) { AgentUsage() } AgentPanel.USAGE -> Box(Modifier.padding(bottom = 8.dp)) { AgentUsage() }
else -> Unit else -> Unit
} }
val list = rememberLazyListState() val list = rememberLazyListState()
@@ -332,12 +322,11 @@ private fun AgentPageContent(
} }
} }
androidx.compose.animation.AnimatedVisibility(!hidden, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) { androidx.compose.animation.AnimatedVisibility(!hidden, enter = expandVertically() + fadeIn(), exit = shrinkVertically() + fadeOut()) {
AgentComposer(composer, draft, visible && started, inlineControls, onPanel = { panel = it }, onSent = toLatest, hideAttach = inline && menuOpen) AgentComposer(composer, draft, visible && started, inlineControls, onPanel = { panel = it }, onSent = toLatest)
} }
} }
} }
} }
}
} }
/** Whether the editor has the cursor; [open] puts it there. */ /** Whether the editor has the cursor; [open] puts it there. */
@@ -408,12 +397,10 @@ private fun AgentMenu(open: Boolean, onOpen: (Boolean) -> Unit, onPanel: (AgentP
val colors = MaterialTheme.colorScheme val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current val pal = LocalPalette.current
val working = AgentHost.state == AgentHost.State.WORKING val working = AgentHost.state == AgentHost.State.WORKING
// Closed, the outline sits flush against the lone button.
val shape = if (open) Shape16 else Shape12
Row( Row(
verticalAlignment = Alignment.CenterVertically, verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.clip(shape).background(colors.surface.copy(alpha = if (open) 0.97f else 0.88f)) modifier = Modifier.clip(Shape16).background(colors.surface.copy(alpha = if (open) 0.97f else 0.88f))
.border(1.dp, pal.line, shape).then(if (open) Modifier.padding(top = 3.dp, bottom = 3.dp, end = 4.dp) else Modifier), .border(1.dp, pal.line, Shape16).padding(end = 2.dp),
) { ) {
androidx.compose.animation.AnimatedVisibility(open, enter = expandHorizontally(expandFrom = Alignment.End) + fadeIn(), androidx.compose.animation.AnimatedVisibility(open, enter = expandHorizontally(expandFrom = Alignment.End) + fadeIn(),
exit = shrinkHorizontally(shrinkTowards = Alignment.End) + fadeOut()) { exit = shrinkHorizontally(shrinkTowards = Alignment.End) + fadeOut()) {
@@ -436,7 +423,7 @@ private fun AgentMenu(open: Boolean, onOpen: (Boolean) -> Unit, onPanel: (AgentP
} }
} }
} }
HeaderAction(Icons.Outlined.MoreHoriz, stringResource(R.string.agent_more), selected = open, size = 36.dp, tag = "agent-menu", startPadding = if (open) null else 0.dp) { onOpen(!open) } HeaderAction(Icons.Outlined.MoreHoriz, stringResource(R.string.agent_more), selected = open, size = 36.dp, tag = "agent-menu") { onOpen(!open) }
} }
} }
@@ -450,13 +437,12 @@ private fun AgentPanelBar(title: String, onClose: () -> Unit) {
@Composable @Composable
internal fun HeaderAction( internal fun HeaderAction(
icon: ImageVector, label: String, enabled: Boolean = true, selected: Boolean = false, tag: String? = null, size: Dp = 44.dp, icon: ImageVector, label: String, enabled: Boolean = true, selected: Boolean = false, tag: String? = null, size: Dp = 44.dp, onClick: () -> Unit,
startPadding: Dp? = null, onClick: () -> Unit,
) { ) {
val pal = LocalPalette.current val pal = LocalPalette.current
Box( Box(
contentAlignment = Alignment.Center, contentAlignment = Alignment.Center,
modifier = Modifier.padding(start = startPadding ?: if (size < 44.dp) 4.dp else 8.dp).size(size).clip(Shape12) modifier = Modifier.padding(start = if (size < 44.dp) 4.dp else 8.dp).size(size).clip(Shape12)
.background(if (selected) pal.primary.copy(alpha = 0.2f) else pal.surfaceVariant) .background(if (selected) pal.primary.copy(alpha = 0.2f) else pal.surfaceVariant)
.clickable(enabled = enabled, onClick = onClick) .clickable(enabled = enabled, onClick = onClick)
.then(if (tag != null) Modifier.testTag(tag) else Modifier), .then(if (tag != null) Modifier.testTag(tag) else Modifier),
@@ -729,7 +715,7 @@ internal fun liveUsed(limit: AgentHost.Limit) = if (limit.resetsAt > 0 && limit.
@Composable @Composable
private fun AgentComposer( private fun AgentComposer(
composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?,
onPanel: (AgentPanel) -> Unit, onSent: () -> Unit, hideAttach: Boolean = false, onPanel: (AgentPanel) -> Unit, onSent: () -> Unit,
) { ) {
val context = LocalContext.current val context = LocalContext.current
var draft by draftState var draft by draftState
@@ -761,13 +747,13 @@ private fun AgentComposer(
horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()), modifier = Modifier.padding(top = 8.dp).fillMaxWidth().horizontalScroll(rememberScrollState()),
) { AgentActivity(labOpen) { labOpen = !labOpen } } ) { AgentActivity(labOpen) { labOpen = !labOpen } }
AgentEditor(composer, draftState, visible, controls, send, hideAttach) AgentEditor(composer, draftState, visible, controls, send)
} }
} }
/** The text with attach, stop and send beside it, and [controls] while the text is not being typed in. */ /** The text with attach, stop and send beside it, and [controls] while the text is not being typed in. */
@Composable @Composable
private fun AgentEditor(composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, send: () -> Unit, hideAttach: Boolean = false) { private fun AgentEditor(composer: ComposerState, draftState: MutableState<String>, visible: Boolean, controls: (@Composable () -> Unit)?, send: () -> Unit) {
val context = LocalContext.current val context = LocalContext.current
val colors = MaterialTheme.colorScheme val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current val pal = LocalPalette.current
@@ -866,14 +852,14 @@ private fun AgentEditor(composer: ComposerState, draftState: MutableState<String
if (stacked) Column { if (stacked) Column {
text(Modifier.fillMaxWidth()) text(Modifier.fillMaxWidth())
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() } if (attach) AttachButton()
AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() } if (AgentAttachments.gameFrame != null) GameFrameButton()
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp).horizontalScroll(rememberScrollState(), reverseScrolling = true)) { if (controls != null && !focused) controls() } Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.weight(1f).height(42.dp)) { if (controls != null && !focused) controls() }
actions() actions()
} }
} else Row(verticalAlignment = Alignment.Bottom) { } else Row(verticalAlignment = Alignment.Bottom) {
AnimatedVisibility(attach && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { AttachButton() } if (attach) AttachButton()
AnimatedVisibility(AgentAttachments.gameFrame != null && !hideAttach, enter = expandHorizontally() + fadeIn(), exit = shrinkHorizontally() + fadeOut()) { GameFrameButton() } if (AgentAttachments.gameFrame != null) GameFrameButton()
text(Modifier.weight(1f)) text(Modifier.weight(1f))
if (controls != null && !focused) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(42.dp)) { controls() } if (controls != null && !focused) Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.height(42.dp)) { controls() }
actions() actions()
@@ -117,7 +117,7 @@ private fun rememberMovies(refresh: Int, onSelectionChanged: () -> Unit): MovieS
} }
@Composable @Composable
internal fun TabChip(label: String, selected: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) { private fun TabChip(label: String, selected: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) {
val pal = LocalPalette.current val pal = LocalPalette.current
val src = remember { MutableInteractionSource() } val src = remember { MutableInteractionSource() }
val hot = rememberHot(src) val hot = rememberHot(src)
@@ -526,11 +526,11 @@ fun ComponentsPage(
val availableTitle: @Composable (String) -> String = { l -> val availableTitle: @Composable (String) -> String = { l ->
when (l) { when (l) {
PROTON_TAB -> stringResource(R.string.comp_available_count, protons.rows.count(ProtonRow::available)) PROTON_TAB -> stringResource(R.string.comp_available_count, protons.rows.count(ProtonRow::available))
else -> stringResource(R.string.comp_nightlies_count, availableRows(l, catalog, snapshot).size) else -> stringResource(R.string.comp_nightlies_count, availableRows(l, catalog, snapshot, view?.proton?.dir?.name).size)
} }
} }
val followed = view?.proton?.let(ComponentUpdates::follows) == true val followed: (String) -> Boolean = { l -> view?.proton?.let { ComponentUpdates.autoFollows(it, l) } == true }
val moded: (String) -> Boolean = { followed && it in compModes && it !in compAutoHeld && !ComponentsManager.runtimeManaged(it, gpu.systemPowerVr) } val moded: (String) -> Boolean = { followed(it) && it in compModes && it !in compAutoHeld && !ComponentsManager.runtimeManaged(it, gpu.systemPowerVr) }
val automatic: (String) -> Boolean = { moded(it) && compModes[it] == ComponentUpdates.AUTO } val automatic: (String) -> Boolean = { moded(it) && compModes[it] == ComponentUpdates.AUTO }
val installedRows: @Composable ColumnScope.(String, Boolean) -> Unit = { l, right -> val installedRows: @Composable ColumnScope.(String, Boolean) -> Unit = { l, right ->
when (l) { when (l) {
@@ -614,7 +614,7 @@ fun ComponentsPage(
} }
} }
else -> { else -> {
val available = availableRows(l, catalog, snapshot) val available = availableRows(l, catalog, snapshot, view?.proton?.dir?.name)
if (available.isEmpty()) EmptyLine(if (catalogAt == 0L) stringResource(R.string.comp_refresh_to_list) else stringResource(R.string.comp_nothing_new)) if (available.isEmpty()) EmptyLine(if (catalogAt == 0L) stringResource(R.string.comp_refresh_to_list) else stringResource(R.string.comp_nothing_new))
for ((stable, nightly) in available) { for ((stable, nightly) in available) {
val d = if (nightly != null && nightlyPicked[stable.file] == true) nightly else stable val d = if (nightly != null && nightlyPicked[stable.file] == true) nightly else stable
@@ -974,18 +974,18 @@ private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapsho
o.label.substringAfterLast(" · ", "").ifEmpty { o.label }.let { if (isCurrent) stringResource(R.string.comp_this_build, it) else stringResource(R.string.comp_earlier_build, it) }, o.label.substringAfterLast(" · ", "").ifEmpty { o.label }.let { if (isCurrent) stringResource(R.string.comp_this_build, it) else stringResource(R.string.comp_earlier_build, it) },
"ORIGINAL", activeIsOriginal && isCurrent, !isCurrent, null, o.protonVersion, "ORIGINAL", activeIsOriginal && isCurrent, !isCurrent, null, o.protonVersion,
) )
} + (snapshot?.packages ?: emptyList()).filter { it.comp == l }.map { s -> } + ComponentsManager.forTool(l, view.proton.dir.name, (snapshot?.packages ?: emptyList()).filter { it.comp == l }, st.activeFile) { it.file }.map { s ->
InstalledItem(s.version, stringResource(R.string.common_size_mb, s.size / 1048576.0), "STORED", !runtimeManaged && s.file == st.activeFile, true, s.file, null) InstalledItem(s.version, stringResource(R.string.common_size_mb, s.size / 1048576.0), "STORED", !runtimeManaged && s.file == st.activeFile, true, s.file, null)
} }
} }
private fun availableFor(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?): List<CatalogItem> { private fun availableFor(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?, toolDir: String?): List<CatalogItem> {
val stored = (snapshot?.packages ?: emptyList()).map { it.file }.toSet() val stored = (snapshot?.packages ?: emptyList()).map { it.file }.toSet()
return catalog.filter { it.comp == l && ComponentsManager.safeName(it.file) !in stored } return ComponentsManager.forTool(l, toolDir, catalog.filter { it.comp == l && ComponentsManager.safeName(it.file) !in stored }) { it.file }
} }
private fun availableRows(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?): List<Pair<CatalogItem, CatalogItem?>> { private fun availableRows(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?, toolDir: String?): List<Pair<CatalogItem, CatalogItem?>> {
val available = availableFor(l, catalog, snapshot) val available = availableFor(l, catalog, snapshot, toolDir)
val pairs = ComponentsManager.nightlyPairs(available) val pairs = ComponentsManager.nightlyPairs(available)
val paired = pairs.values.toSet() val paired = pairs.values.toSet()
return available.filter { it !in paired }.map { it to pairs[it] } return available.filter { it !in paired }.map { it to pairs[it] }
@@ -1201,7 +1201,7 @@ private fun GameComponentOverrides(
} }
GamePackageRow( GamePackageRow(
comp = "fex", comp = "fex",
packages = packages, packages = ComponentsManager.forTool("fex", protonChoice?.dir ?: generalProton?.dir?.name, packages, componentChoices["fex"]) { it.file },
selectedFile = componentChoices["fex"], selectedFile = componentChoices["fex"],
open = componentMenu == "fex", open = componentMenu == "fex",
busy = busy, busy = busy,
@@ -1,16 +0,0 @@
package com.droiddeck.launcher.ui
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.addPathNodes
import androidx.compose.ui.unit.dp
internal val DeckyIcon: ImageVector = ImageVector.Builder("Decky", 24.dp, 24.dp, 24f, 24f).apply {
for (d in listOf(
"M8,2h2v6H8Z",
"M14,2h2v6h-2Z",
"M5,8h14v3a7,7 0 0 1 -5,6.7V19h-4v-1.3A7,7 0 0 1 5,11Z",
"M11,19h2v3h-2Z",
)) addPath(addPathNodes(d), fill = SolidColor(Color.Black))
}.build()
@@ -1,245 +0,0 @@
package com.droiddeck.launcher.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import coil.compose.AsyncImage
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.droiddeck.launcher.R
import com.droiddeck.launcher.runtime.DeckyManager
import com.droiddeck.launcher.runtime.DeckyStore
private enum class DeckyTab { INSTALLED, STORE, ZIP }
private const val STORE_PAGE = 30
internal fun deckyStoreMatches(plugins: List<DeckyStore.Plugin>, query: String): List<DeckyStore.Plugin> {
val words = query.trim().lowercase().split(Regex("\\s+")).filter { it.isNotEmpty() }
return plugins.filter { p ->
val haystack = (p.name + " " + p.author + " " + p.description + " " + p.tags.joinToString(" ")).lowercase()
words.all { it in haystack }
}.sortedByDescending { it.downloads }
}
@Composable
internal fun DeckyGroups(s: ModeSettings, a: ModeSettingsActions, host: MenuHost) {
val idle = s.deckyStage == null && !s.deckySessionRunning
SettingsGroup(stringResource(R.string.mode_decky_loader)) {
val updateAvailable = s.deckyInstalled != null && s.deckyLatestRelease != null &&
s.deckyInstalled != s.deckyLatestRelease.tag
val status = when {
s.deckyStage != null -> s.deckyStage
s.deckyChecking -> stringResource(R.string.mode_decky_checking)
s.deckyInstalled == null && s.deckyLatestRelease != null -> stringResource(R.string.mode_decky_ready, s.deckyLatestRelease.tag)
s.deckyInstalled == null -> stringResource(R.string.mode_decky_none)
s.deckyLatestRelease == null -> stringResource(R.string.mode_decky_installed, s.deckyInstalled)
updateAvailable -> stringResource(R.string.mode_decky_update, s.deckyLatestRelease.tag)
else -> stringResource(R.string.mode_decky_current, s.deckyInstalled)
}
SettingsRow(stringResource(R.string.decky_status), status) {
val action = when {
s.deckyStage != null -> stringResource(R.string.common_working)
s.deckyChecking -> stringResource(R.string.common_checking)
s.deckyInstalled == null && s.deckyLatestRelease != null -> stringResource(R.string.mode_decky_install_latest)
s.deckyInstalled != null && updateAvailable -> stringResource(R.string.common_update)
else -> stringResource(R.string.common_check)
}
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
SecondaryButton(action, enabled = s.deckyStage == null && !s.deckyChecking && !s.deckySessionRunning) {
if (s.deckyLatestRelease == null || (s.deckyInstalled != null && !updateAvailable)) a.onDeckyCheck()
else s.deckyLatestRelease?.let(a.onDeckyInstall)
}
if (s.deckyInstalled != null) DeckyUninstall(enabled = idle, onUninstall = a.onDeckyUninstall)
}
}
if (s.deckyInstalled != null) ToggleRow(
host, "decky-enabled", stringResource(R.string.decky_enable),
null,
s.deckyEnabled,
enabled = idle,
onChange = a.onDeckyEnabled,
)
ChoiceRow(
host, "decky-channel", stringResource(R.string.decky_release_channel),
null,
listOf(
DeckyManager.BRANCH_STABLE to stringResource(R.string.decky_channel_stable),
DeckyManager.BRANCH_PRERELEASE to stringResource(R.string.decky_channel_prerelease),
) + if (s.deckyBranch == DeckyManager.BRANCH_TESTING) listOf(
DeckyManager.BRANCH_TESTING to stringResource(R.string.decky_channel_testing),
) else emptyList(),
s.deckyBranch,
enabled = idle,
onPick = a.onDeckyBranch,
)
if (s.deckyStage != null && s.deckyPercent >= 0) {
LinearProgressIndicator(
progress = { s.deckyPercent / 100f },
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp),
)
}
}
if (s.deckyInstalled == null) return
var tab by rememberSaveable { mutableStateOf(DeckyTab.INSTALLED) }
SettingsGroup(stringResource(R.string.mode_decky_plugins)) {
Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 10.dp)) {
TabChip(stringResource(R.string.decky_tab_installed, s.deckyPlugins.size), tab == DeckyTab.INSTALLED, Modifier.weight(1f)) { tab = DeckyTab.INSTALLED }
TabChip(stringResource(R.string.decky_tab_store), tab == DeckyTab.STORE, Modifier.weight(1f)) { tab = DeckyTab.STORE }
TabChip(stringResource(R.string.decky_tab_zip), tab == DeckyTab.ZIP, Modifier.weight(1f)) { tab = DeckyTab.ZIP }
}
LaunchedEffect(tab) { if (tab != DeckyTab.ZIP && s.deckyStore == null && !s.deckyStoreFailed) a.onDeckyStoreRefresh() }
when (tab) {
DeckyTab.INSTALLED -> InstalledPlugins(s, a, idle)
DeckyTab.STORE -> PluginStore(s, a, idle)
DeckyTab.ZIP -> SettingsRow(
stringResource(R.string.decky_tab_zip),
stringResource(R.string.mode_decky_plugins_hint),
) {
SecondaryButton(
if (s.deckyStage != null && s.deckyDownloadingBinary) stringResource(R.string.mode_decky_plugin_downloading) else stringResource(R.string.mode_decky_plugin_install_zip),
enabled = idle,
modifier = Modifier.testTag("decky-install-zip"),
onClick = a.onPickDeckyPluginZip,
)
}
}
}
}
@Composable
private fun InstalledPlugins(s: ModeSettings, a: ModeSettingsActions, idle: Boolean) {
var removing by remember { mutableStateOf<DeckyStore.Installed?>(null) }
if (s.deckyPlugins.isEmpty()) {
Text(stringResource(R.string.decky_none_installed), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp))
}
for (plugin in s.deckyPlugins) {
val listed = s.deckyStore?.firstOrNull { it.name == plugin.name }
val update = listed?.takeIf { DeckyStore.updateAvailable(plugin, it) }
PluginRow(
plugin.name,
listOf(plugin.version, plugin.author).filter { it.isNotBlank() }.joinToString(" · ") +
(update?.latest?.let { " · " + stringResource(R.string.decky_update_to, it.name) } ?: ""),
listed?.imageUrl.orEmpty(),
) {
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
if (update != null) SecondaryButton(stringResource(R.string.common_update), enabled = idle, compact = true) { a.onDeckyStoreInstall(update) }
SecondaryButton(stringResource(R.string.decky_remove), enabled = idle, compact = true, modifier = Modifier.testTag("decky-remove-${plugin.folder}")) { removing = plugin }
}
}
}
if (s.deckyPlugins.isNotEmpty()) Text(stringResource(R.string.decky_changes_next_session), fontSize = 12.sp,
color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp))
removing?.let { plugin ->
androidx.compose.material3.AlertDialog(
onDismissRequest = { removing = null },
title = { Text(stringResource(R.string.decky_remove_confirm, plugin.name)) },
text = { Text(stringResource(R.string.decky_remove_confirm_body)) },
confirmButton = { androidx.compose.material3.TextButton(onClick = { removing = null; a.onDeckyRemove(plugin) }) { Text(stringResource(R.string.decky_remove)) } },
dismissButton = { androidx.compose.material3.TextButton(onClick = { removing = null }) { Text(stringResource(R.string.common_cancel)) } },
)
}
}
@Composable
private fun PluginStore(s: ModeSettings, a: ModeSettingsActions, idle: Boolean) {
var query by rememberSaveable { mutableStateOf("") }
var searching by remember { mutableStateOf(false) }
var shown by rememberSaveable { mutableIntStateOf(STORE_PAGE) }
val plugins = s.deckyStore
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp).padding(bottom = 12.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) {
Box(Modifier.weight(1f)) {
ListRow(tall = true, onClick = { searching = true }) {
androidx.compose.material3.Icon(Icons.Filled.Search, contentDescription = null,
tint = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.size(18.dp))
Text(
query.ifEmpty { stringResource(R.string.decky_store_search) }, fontSize = 14.sp, maxLines = 1, overflow = TextOverflow.Ellipsis,
color = if (query.isEmpty()) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.onBackground,
modifier = Modifier.weight(1f),
)
}
}
if (query.isNotEmpty()) SecondaryButton(stringResource(R.string.boot_movie_repo_clear), compact = true) { query = ""; shown = STORE_PAGE }
}
when {
plugins == null -> Text(stringResource(R.string.common_working), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 12.dp))
s.deckyStoreFailed -> Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
Text(stringResource(R.string.decky_store_failed), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.weight(1f))
SecondaryButton(stringResource(R.string.boot_movie_repo_retry), compact = true) { a.onDeckyStoreRefresh() }
}
else -> {
val matches = remember(plugins, query) { deckyStoreMatches(plugins, query) }
if (matches.isEmpty()) Text(stringResource(R.string.decky_store_empty), fontSize = 13.sp, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(vertical = 12.dp))
for (plugin in matches.take(shown)) {
val have = s.deckyPlugins.firstOrNull { it.name == plugin.name }
val current = have != null && !DeckyStore.updateAvailable(have, plugin)
PluginRow(
plugin.name,
listOf(plugin.latest?.name.orEmpty(), plugin.author, plugin.description).filter { it.isNotBlank() }.joinToString(" · "),
plugin.imageUrl,
) {
SecondaryButton(
stringResource(when { current -> R.string.setup_installed; have != null -> R.string.common_update; else -> R.string.boot_movie_repo_install }),
enabled = idle && !current, compact = true,
modifier = Modifier.testTag("decky-store-${plugin.name}"),
) { a.onDeckyStoreInstall(plugin) }
}
}
if (matches.size > shown) SecondaryButton(stringResource(R.string.decky_store_more, matches.size - shown), compact = true) { shown += STORE_PAGE }
}
}
}
if (searching) TextEntryDialog(
stringResource(R.string.decky_store_search), query, number = false, confirm = stringResource(R.string.stores_search_open),
onSubmit = { query = it; shown = STORE_PAGE; searching = false }, onDismiss = { searching = false }, id = "decky-store-entry",
)
}
@Composable
private fun PluginRow(name: String, detail: String, imageUrl: String, actions: @Composable () -> Unit) {
val colors = MaterialTheme.colorScheme
Column(verticalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp)) {
Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) {
val shape = RoundedCornerShape(8.dp)
Box(Modifier.width(96.dp).aspectRatio(16f / 9f).clip(shape).background(Color(0xFF0E1218))) {
if (imageUrl.isNotEmpty()) AsyncImage(model = imageUrl, contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier.fillMaxSize())
}
Column(Modifier.weight(1f)) {
Text(name, fontSize = 15.sp, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
Text(detail, fontSize = 12.sp, color = colors.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
}
Row(horizontalArrangement = Arrangement.End, modifier = Modifier.fillMaxWidth()) { actions() }
}
}
@@ -175,7 +175,7 @@ internal fun SessionDrawerPreview(secondScreens: List<SecondScreenDisplay>) {
val code = e.nativeKeyEvent.keyCode val code = e.nativeKeyEvent.keyCode
if (code != android.view.KeyEvent.KEYCODE_BUTTON_L1 && code != android.view.KeyEvent.KEYCODE_BUTTON_R1) return@onPreviewKeyEvent false if (code != android.view.KeyEvent.KEYCODE_BUTTON_L1 && code != android.view.KeyEvent.KEYCODE_BUTTON_R1) return@onPreviewKeyEvent false
if (e.type == KeyEventType.KeyDown && e.nativeKeyEvent.repeatCount == 0) { if (e.type == KeyEventType.KeyDown && e.nativeKeyEvent.repeatCount == 0) {
page = sessionDrawerPages().let { it.strip().step(it.tabFor(page), if (code == android.view.KeyEvent.KEYCODE_BUTTON_R1) 1 else -1) } page = sessionDrawerPages().step(page, if (code == android.view.KeyEvent.KEYCODE_BUTTON_R1) 1 else -1)
} }
true true
} }
@@ -21,21 +21,11 @@ import com.droiddeck.launcher.session.StripMetric
@Composable @Composable
internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { internal fun DroidDeckHudSettings(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) {
val cfg = a.hudConfig val cfg = a.hudConfig
val context = LocalContext.current
var onlyDuringGame by remember { mutableStateOf(SessionPrefs.hudOnlyDuringGame(context)) }
fun on(key: String) = cfg[key] == "1" fun on(key: String) = cfg[key] == "1"
fun int(key: String, fallback: Int) = cfg[key]?.toIntOrNull() ?: fallback fun int(key: String, fallback: Int) = cfg[key]?.toIntOrNull() ?: fallback
SettingsGroup(stringResource(R.string.drawer_hud)) { SettingsGroup(stringResource(R.string.drawer_hud)) {
ToggleRow(host, "hud", stringResource(R.string.drawer_hud), null, a.hudOn, chipModifier = track("hud"), onChange = a.onHud) 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 if (!a.hudOn) return@SettingsGroup
val size = DroidDeckHudSize.from(cfg["hudSize"]) val size = DroidDeckHudSize.from(cfg["hudSize"])
ChoiceRow(host, "hud-size", stringResource(R.string.hud_size), stringResource(R.string.hud_size_hint), 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 } }.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() { fun hide() {
dropLaunches()
stopTyping() stopTyping()
launching = false launching = false
displayId = -1 displayId = -1
@@ -223,9 +169,6 @@ object DualScreenPanel {
if (activity !== host) activity?.finishAndRemoveTask() if (activity !== host) activity?.finishAndRemoveTask()
activity = host activity = host
launching = false launching = false
val waiting = pendingLaunches
val generation = host.intent?.getIntExtra(EXTRA_HANDOFF, -1) ?: -1
handoffHandler.post { if (pendingLaunches === waiting && generation == handoffGeneration) releaseLaunches() }
return true return true
} }
@@ -33,9 +33,7 @@ import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.graphics.lerp import androidx.compose.ui.graphics.lerp
import androidx.compose.ui.hapticfeedback.HapticFeedbackType import androidx.compose.ui.hapticfeedback.HapticFeedbackType
import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.onSizeChanged import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.platform.LocalHapticFeedback
import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.dp
@@ -49,30 +47,21 @@ import kotlin.math.sin
@Composable @Composable
internal fun EmptyLibrary(avoid: Rect?, wall: (@Composable () -> Unit)? = null, fade: @Composable () -> Unit) { internal fun EmptyLibrary(avoid: Rect?, wall: (@Composable () -> Unit)? = null, fade: @Composable () -> Unit) {
var origin by remember { mutableStateOf(Offset.Zero) } val clock = rememberMarkClock(avoid)
val clock = rememberMarkClock(avoid?.translate(-origin.x, -origin.y)) Box(Modifier.fillMaxSize().onSizeChanged { clock.page = Size(it.width.toFloat(), it.height.toFloat()) }) {
Box(
Modifier.fillMaxSize()
.onGloballyPositioned { origin = it.positionInRoot() }
.onSizeChanged { clock.page = Size(it.width.toFloat(), it.height.toFloat()) },
) {
if (wall != null) wall() else EmptyWall(clock) if (wall != null) wall() else EmptyWall(clock)
fade() fade()
Mark(clock) Mark(clock)
} }
} }
private const val TRACE_MS = 1250f
private const val FILL_FROM = 450f
private const val POP_FROM = 900f private const val POP_FROM = 900f
private const val IMPACT = 2200f private const val IMPACT = 2200f
private const val RIPPLE_MS = 1250f private const val RIPPLE_MS = 1250f
private const val HIT_MS = 900f private const val HIT_MS = 900f
private const val END = 3600f private const val END = 3600f
private const val REVEAL_MS = 2300f
private const val TRACE_DRAW_MS = 900f
private const val TRACE_FADE_MS = 500f
private const val REVEAL_FILL_FROM = 600f
private const val REVEAL_FILL_MS = 450f
private const val REVEAL_FADE_FROM = 1700f
private const val POKE = 880f private const val POKE = 880f
private const val DRIFT_MS = 75_000f private const val DRIFT_MS = 75_000f
@@ -93,7 +82,8 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
val haptics = LocalHapticFeedback.current val haptics = LocalHapticFeedback.current
val keepOff by rememberUpdatedState(avoid) val keepOff by rememberUpdatedState(avoid)
val speed = with(LocalDensity.current) { 64.dp.toPx() } val speed = with(LocalDensity.current) { 64.dp.toPx() }
val clearance = with(LocalDensity.current) { 4.dp.toPx() } val inset = with(LocalDensity.current) { 10.dp.toPx() }
val clearance = with(LocalDensity.current) { 16.dp.toPx() }
LaunchedEffect(clock) { LaunchedEffect(clock) {
var last = -1L var last = -1L
var vx = speed * 0.8f var vx = speed * 0.8f
@@ -119,28 +109,16 @@ private fun rememberMarkClock(avoid: Rect?): MarkClock {
var x = clock.at.x + vx * dt / 1000f var x = clock.at.x + vx * dt / 1000f
var y = clock.at.y + vy * dt / 1000f var y = clock.at.y + vy * dt / 1000f
val hw = f.ball val hw = f.halfWidth
val hh = f.ball val hh = f.halfHeight
if (x - hw < 0f) { x = hw; vx = abs(vx) } if (x - hw < inset) { x = inset + hw; vx = abs(vx) }
if (x + hw > clock.page.width) { x = clock.page.width - hw; vx = -abs(vx) } if (x + hw > clock.page.width - inset) { x = clock.page.width - inset - hw; vx = -abs(vx) }
if (y - hh < 0f) { y = hh; vy = abs(vy) } if (y - hh < inset) { y = inset + hh; vy = abs(vy) }
if (y + hh > clock.page.height) { y = clock.page.height - hh; vy = -abs(vy) } if (y + hh > clock.page.height - inset) { y = clock.page.height - inset - hh; vy = -abs(vy) }
keepOff?.inflate(clearance)?.let { r -> keepOff?.inflate(clearance)?.let { r ->
val nearX = x.coerceIn(r.left, r.right) if (x + hw > r.left && x - hw < r.right && y + hh > r.top && y - hh < r.bottom) {
val nearY = y.coerceIn(r.top, r.bottom) val outX = if (x < r.center.x) r.left - (x + hw) else r.right - (x - hw)
val gapX = x - nearX val outY = if (y < r.center.y) r.top - (y + hh) else r.bottom - (y - hh)
val gapY = y - nearY
val gap = hypot(gapX, gapY)
if (gap in 0.0001f..f.ball) {
val nx = gapX / gap
val ny = gapY / gap
x = nearX + nx * f.ball
y = nearY + ny * f.ball
val into = vx * nx + vy * ny
if (into < 0f) { vx -= 2f * into * nx; vy -= 2f * into * ny }
} else if (gap <= 0.0001f) {
val outX = if (x < r.center.x) r.left - f.ball - x else r.right + f.ball - x
val outY = if (y < r.center.y) r.top - f.ball - y else r.bottom + f.ball - y
if (abs(outX) < abs(outY)) { x += outX; vx = if (outX < 0) -abs(vx) else abs(vx) } if (abs(outX) < abs(outY)) { x += outX; vx = if (outX < 0) -abs(vx) else abs(vx) }
else { y += outY; vy = if (outY < 0) -abs(vy) else abs(vy) } else { y += outY; vy = if (outY < 0) -abs(vy) else abs(vy) }
} }
@@ -316,33 +294,30 @@ private fun Mark(clock: MarkClock) {
} else 0f } else 0f
translate(0f, shake) { translate(0f, shake) {
val since = t - IMPACT val fill = Out.transform(clamp01((intro - FILL_FROM) / 450f))
if (since in 0f..REVEAL_MS) { if (fill > 0f) {
val fade = 1f - clamp01((since - REVEAL_FADE_FROM) / (REVEAL_MS - REVEAL_FADE_FROM)) val lift = 8f * k * (1f - fill)
val fill = Out.transform(clamp01((since - REVEAL_FILL_FROM) / REVEAL_FILL_MS)) * fade val edge = 5f * f.s
if (fill > 0f) { LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift + edge) }
val lift = 8f * k * (1f - fill / fade) LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift + edge) }
val edge = 5f * f.s drawPath(left, slabEdge.copy(alpha = fill))
LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift + edge) } drawPath(right, slabEdge.copy(alpha = fill))
LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift + edge) } LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift) }
drawPath(left, slabEdge.copy(alpha = fill)) LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift) }
drawPath(right, slabEdge.copy(alpha = fill)) drawPath(left, ink.copy(alpha = fill))
LogoShape.left(left, 0f) { x, y -> f.px(x, y) + Offset(0f, lift) } drawPath(right, ink.copy(alpha = fill))
LogoShape.right(right) { x, y -> f.px(x, y) + Offset(0f, lift) } }
drawPath(left, ink.copy(alpha = fill))
drawPath(right, ink.copy(alpha = fill)) if (intro < TRACE_MS) {
} val drawn = TraceEase.transform(clamp01(intro / 775f))
val drawn = TraceEase.transform(clamp01(since / TRACE_DRAW_MS)) val alpha = if (intro < 775f) 1f else 1f - (intro - 775f) / 475f
val alpha = (if (since < TRACE_DRAW_MS) 1f else 1f - (since - TRACE_DRAW_MS) / TRACE_FADE_MS).coerceIn(0f, 1f) * fade LogoShape.left(left, 0f, f::px)
if (alpha > 0f) { LogoShape.right(right, f::px)
LogoShape.left(left, 0f, f::px) for (half in listOf(left, right)) {
LogoShape.right(right, f::px) measure.setPath(half, false)
for (half in listOf(left, right)) { piece.reset()
measure.setPath(half, false) measure.getSegment(0f, measure.length * drawn, piece, true)
piece.reset() drawPath(piece, pal.signal.copy(alpha = alpha), style = Stroke(2f * f.s))
measure.getSegment(0f, measure.length * drawn, piece, true)
drawPath(piece, pal.signal.copy(alpha = alpha), style = Stroke(3f * f.s))
}
} }
} }
@@ -33,8 +33,6 @@ import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Outline import androidx.compose.ui.graphics.Outline
import androidx.compose.ui.graphics.Shape import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.geometry.RoundRect
import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalDensity
@@ -111,21 +109,13 @@ internal fun VeilRing() {
} }
} }
private fun cornersOf(shape: Shape, size: Size, dir: LayoutDirection, density: Density): FloatArray = private fun cornerOf(shape: Shape, size: Size, dir: LayoutDirection, density: Density): Float =
when (val o = shape.createOutline(size, dir, density)) { when (val o = shape.createOutline(size, dir, density)) {
is Outline.Rounded -> o.roundRect.run { is Outline.Rounded -> o.roundRect.topLeftCornerRadius.x
floatArrayOf(topLeftCornerRadius.x, topRightCornerRadius.x, bottomRightCornerRadius.x, bottomLeftCornerRadius.x) is Outline.Rectangle -> 0f
} is Outline.Generic -> minOf(size.width, size.height) / 2f
is Outline.Rectangle -> FloatArray(4)
is Outline.Generic -> FloatArray(4) { minOf(size.width, size.height) / 2f }
} }
private fun ringRect(l: Float, t: Float, w: Float, h: Float, radii: FloatArray, inset: Float): Path {
// Radii are not capped one by one: the path scales corners whose neighbours overlap, as the outline does.
fun r(i: Int) = CornerRadius((radii[i] - inset).coerceAtLeast(0f))
return Path().apply { addRoundRect(RoundRect(Rect(l, t, l + w, t + h), r(0), r(1), r(2), r(3))) }
}
@Composable @Composable
internal fun Modifier.glideBorder( internal fun Modifier.glideBorder(
hot: Boolean, hot: Boolean,
@@ -200,7 +190,7 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
val density = LocalDensity.current val density = LocalDensity.current
val dir = LocalLayoutDirection.current val dir = LocalLayoutDirection.current
val edges = remember { List(4) { Animatable(0f) } } val edges = remember { List(4) { Animatable(0f) } }
val corners = remember { List(4) { Animatable(0f) } } val corner = remember { Animatable(0f) }
val solid = remember { Animatable(0f) } val solid = remember { Animatable(0f) }
val alpha = remember { Animatable(0f) } val alpha = remember { Animatable(0f) }
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
@@ -269,14 +259,14 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
fun droplet(s: GlideSource, b: Rect) { fun droplet(s: GlideSource, b: Rect) {
jobs.forEach { it?.cancel() } jobs.forEach { it?.cancel() }
val size = s.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size val size = s.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size
val endCorners = cornersOf(s.shape, size, dir, density) val endCorner = cornerOf(s.shape, size, dir, density)
jobs[5] = scope.launch { jobs[5] = scope.launch {
val r = with(density) { 6.dp.toPx() } val r = with(density) { 6.dp.toPx() }
fun dot(c: Offset) = listOf(c.x - r, c.y - r, c.x + r, c.y + r) fun dot(c: Offset) = listOf(c.x - r, c.y - r, c.x + r, c.y + r)
val here = Offset((edges[0].value + edges[2].value) / 2f, (edges[1].value + edges[3].value) / 2f) val here = Offset((edges[0].value + edges[2].value) / 2f, (edges[1].value + edges[3].value) / 2f)
coroutineScope { coroutineScope {
launch { solid.animateTo(1f, Motion.tw(80)) } launch { solid.animateTo(1f, Motion.tw(80)) }
corners.forEach { c -> launch { c.animateTo(r, Motion.tw(90)) } } launch { corner.animateTo(r, Motion.tw(90)) }
dot(here).forEachIndexed { i, v -> launch { edges[i].animateTo(v, Motion.tw(90)) } } dot(here).forEachIndexed { i, v -> launch { edges[i].animateTo(v, Motion.tw(90)) } }
} }
val distance = hypot(b.center.x - here.x, b.center.y - here.y) / density.density val distance = hypot(b.center.x - here.x, b.center.y - here.y) / density.density
@@ -291,9 +281,7 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
flight.cancel() flight.cancel()
val at = glide.boundsOf(s) ?: b val at = glide.boundsOf(s) ?: b
launch { solid.animateTo(0f, Motion.tw(150)) } launch { solid.animateTo(0f, Motion.tw(150)) }
// The droplet job is cancelled by the next move, so the shape settles on the corner job instead. launch { corner.animateTo(endCorner, Motion.sp(0.8f, 600f)) }
jobs[4]?.cancel()
jobs[4] = scope.launch { corners.forEachIndexed { i, c -> launch { c.animateTo(endCorners[i], Motion.sp(0.8f, 600f)) } } }
listOf(at.left, at.top, at.right, at.bottom).forEachIndexed { i, v -> listOf(at.left, at.top, at.right, at.bottom).forEachIndexed { i, v ->
jobs[i] = launch { edges[i].animateTo(v, Motion.sp(0.7f, 750f)) } jobs[i] = launch { edges[i].animateTo(v, Motion.sp(0.7f, 750f)) }
} }
@@ -301,11 +289,9 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
} }
fun cornerTo(s: GlideSource, b: Rect, snap: Boolean) { fun cornerTo(s: GlideSource, b: Rect, snap: Boolean) {
val size = s.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size val size = s.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size
val r = cornersOf(s.shape, size, dir, density) val r = cornerOf(s.shape, size, dir, density)
jobs[4]?.cancel() jobs[4]?.cancel()
jobs[4] = scope.launch { jobs[4] = scope.launch { if (snap) corner.snapTo(r) else corner.animateTo(r, Motion.sp(0.8f, 500f)) }
corners.forEachIndexed { i, c -> launch { if (snap) c.snapTo(r[i]) else c.animateTo(r[i], Motion.sp(0.8f, 500f)) } }
}
} }
snapshotFlow { Triple(glide.current, glide.moves, glide.hidden || RingVeil.count > 0) }.collectLatest { (src, _, hidden) -> snapshotFlow { Triple(glide.current, glide.moves, glide.hidden || RingVeil.count > 0) }.collectLatest { (src, _, hidden) ->
if (Motion.scale == 0f) { if (Motion.scale == 0f) {
@@ -316,7 +302,7 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
else { else {
listOf(b.left, b.top, b.right, b.bottom).forEachIndexed { i, v -> edges[i].snapTo(v) } listOf(b.left, b.top, b.right, b.bottom).forEachIndexed { i, v -> edges[i].snapTo(v) }
val size = src.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size val size = src.coords?.size?.let { Size(it.width.toFloat(), it.height.toFloat()) } ?: b.size
cornersOf(src.shape, size, dir, density).forEachIndexed { i, v -> corners[i].snapTo(v) } corner.snapTo(cornerOf(src.shape, size, dir, density))
alpha.snapTo(1f) alpha.snapTo(1f)
} }
shown = src shown = src
@@ -357,11 +343,10 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
val out = with(density) { 3.dp.toPx() } val out = with(density) { 3.dp.toPx() }
val grown = listOf(b.left - out, b.top - out, b.right + out, b.bottom + out) val grown = listOf(b.left - out, b.top - out, b.right + out, b.bottom + out)
jobs.forEach { it?.cancel() } jobs.forEach { it?.cancel() }
// Set before the join: a move of the target restarts this block there, after shown is already set.
cornerTo(src, b, snap = true)
scope.launch { solid.snapTo(0f); edges.forEachIndexed { i, e -> e.snapTo(grown[i]) } }.join() scope.launch { solid.snapTo(0f); edges.forEachIndexed { i, e -> e.snapTo(grown[i]) } }.join()
dirSpecs = List(4) { Edge(0.6f, 700f) } dirSpecs = List(4) { Edge(0.6f, 700f) }
delays = LongArray(4) delays = LongArray(4)
cornerTo(src, b, snap = true)
scope.launch { alpha.animateTo(1f, Motion.tw(140)) } scope.launch { alpha.animateTo(1f, Motion.tw(140)) }
} else { } else {
val dx = b.center.x - (edges[0].value + edges[2].value) / 2f val dx = b.center.x - (edges[0].value + edges[2].value) / 2f
@@ -409,13 +394,21 @@ private fun Modifier.focusGlideOverlay(glide: FocusGlide): Modifier {
val l = edges[0].value; val t = edges[1].value; val r = edges[2].value; val b = edges[3].value val l = edges[0].value; val t = edges[1].value; val r = edges[2].value; val b = edges[3].value
val sw = (r - l - w).coerceAtLeast(0f) val sw = (r - l - w).coerceAtLeast(0f)
val sh = (b - t - w).coerceAtLeast(0f) val sh = (b - t - w).coerceAtLeast(0f)
val radii = FloatArray(4) { corners[it].value } val rad = (corner.value - w / 2f).coerceIn(0f, minOf(sw, sh) / 2f)
val f = solid.value val f = solid.value
if (f > 0.01f) drawPath(ringRect(l, t, r - l, b - t, radii, 0f), color, alpha = a * f) if (f > 0.01f) drawRoundRect(
color, topLeft = Offset(l, t), size = Size(r - l, b - t),
cornerRadius = CornerRadius(corner.value), alpha = a * f,
)
if (f < 0.99f) { if (f < 0.99f) {
val inner = ringRect(l + w / 2f, t + w / 2f, sw, sh, radii, w / 2f) drawRoundRect(
drawPath(inner, color, alpha = a * (1f - f) * fillAlpha) color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
drawPath(inner, color, style = Stroke(w), alpha = a) cornerRadius = CornerRadius(rad), alpha = a * (1f - f) * fillAlpha,
)
drawRoundRect(
color, topLeft = Offset(l + w / 2f, t + w / 2f), size = Size(sw, sh),
cornerRadius = CornerRadius(rad), style = Stroke(w), alpha = a,
)
} }
} }
} }
@@ -263,10 +263,6 @@ private fun Content(
SyncTabPage(s, modifier.padding(horizontal = padH).padding(top = padV)) SyncTabPage(s, modifier.padding(horizontal = padH).padding(top = padV))
return return
} }
if (selected == "decky" || selected == "boot-movies") {
SteamTabPage(selected, a, modifier.padding(horizontal = padH).padding(top = padV))
return
}
if (selected == "updates") { if (selected == "updates") {
UpdatesPage(s, a, modifier.padding(horizontal = padH).padding(top = padV)) UpdatesPage(s, a, modifier.padding(horizontal = padH).padding(top = padV))
return return
@@ -56,9 +56,9 @@ import androidx.compose.material.icons.filled.Terminal
import androidx.compose.material.icons.filled.Apps import androidx.compose.material.icons.filled.Apps
import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.SdStorage 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.Sync
import androidx.compose.material.icons.filled.MoreHoriz import androidx.compose.material.icons.filled.MoreHoriz
import androidx.compose.material.icons.filled.SystemUpdate
import androidx.compose.material.icons.automirrored.outlined.ArrowBack import androidx.compose.material.icons.automirrored.outlined.ArrowBack
import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.material3.Icon import androidx.compose.material3.Icon
@@ -207,10 +207,8 @@ internal fun railLabelIcon(key: String): Pair<Int, ImageVector> = when (key) {
"setup" -> R.string.rail_setup to Icons.Filled.Settings "setup" -> R.string.rail_setup to Icons.Filled.Settings
"storage" -> R.string.rail_storage to Icons.Filled.SdStorage "storage" -> R.string.rail_storage to Icons.Filled.SdStorage
"sync" -> R.string.rail_sync to Icons.Filled.Sync "sync" -> R.string.rail_sync to Icons.Filled.Sync
"decky" -> R.string.rail_decky to DeckyIcon
"boot-movies" -> R.string.rail_boot_movies to Icons.Filled.Movie
NavTabs.MORE -> R.string.rail_more to Icons.Filled.MoreHoriz NavTabs.MORE -> R.string.rail_more to Icons.Filled.MoreHoriz
else -> R.string.rail_updates to updatesIcon(RunningBuild.kind()) else -> R.string.rail_updates to Icons.Filled.SystemUpdate
} }
internal fun setupNeedsAttention(s: FrontEndState): Boolean = !s.ready || (s.available != null && s.available != s.installed) || internal fun setupNeedsAttention(s: FrontEndState): Boolean = !s.ready || (s.available != null && s.available != s.installed) ||
@@ -143,7 +143,6 @@ class FrontEndState(
val integrationFocus: com.droiddeck.launcher.core.SteamIntegration.Feature? = null, val integrationFocus: com.droiddeck.launcher.core.SteamIntegration.Feature? = null,
val androidApps: List<HomeApp.LaunchableApp> = emptyList(), val androidApps: List<HomeApp.LaunchableApp> = emptyList(),
val secondScreenDisplays: List<SecondScreenDisplay> = emptyList(), val secondScreenDisplays: List<SecondScreenDisplay> = emptyList(),
val ownScreen: SecondScreenDisplay? = null,
val dualScreen: Boolean = false, val dualScreen: Boolean = false,
val dualScreenDevice: Boolean = false, val dualScreenDevice: Boolean = false,
val dualScreenMode: String = com.droiddeck.launcher.input.DualScreen.MODE_AUTO, val dualScreenMode: String = com.droiddeck.launcher.input.DualScreen.MODE_AUTO,
@@ -314,14 +313,16 @@ class FrontEndActions(
val onBackActionsInverted: (Boolean) -> Unit = {}, val onBackActionsInverted: (Boolean) -> Unit = {},
val onRefreshPhantomStatus: () -> Unit = {}, val onRefreshPhantomStatus: () -> Unit = {},
val onOpenDeveloperOptions: (Int?) -> 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 onSetPhantomProcessLimit: (Boolean, (String?) -> Unit) -> Unit,
val onCopyPhantomCommand: (Boolean) -> Unit = {}, val onCopyPhantomCommand: (Boolean) -> Unit = {},
val onDismissPhantomGate: () -> Unit = {}, val onDismissPhantomGate: () -> Unit = {},
val onStartWirelessAdbPairing: (Boolean) -> Unit = {}, val onStartWirelessAdbPairing: () -> Unit = {},
val onStartPairingGuide: (Int?, Boolean) -> Boolean = { _, _ -> false }, val onStartPairingGuide: (Int?, Boolean) -> Boolean = { _, _ -> false },
val onShowPhantomGate: () -> Unit = {}, val onShowPhantomGate: () -> Unit = {},
val onQueuePlaySteam: () -> Unit = {}, val onOpenNotificationSettings: () -> Unit = {},
val onEnsureNotifications: ((Boolean) -> Unit) -> Unit = { it(true) },
val controller: ControllerActions? = null, val controller: ControllerActions? = null,
val updates: UpdatesActions = UpdatesActions(), val updates: UpdatesActions = UpdatesActions(),
) )
@@ -453,7 +454,6 @@ internal suspend fun focusSoon(target: () -> FocusRequester) {
@Composable @Composable
fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)? = null) { fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)? = null) {
val frontFocus = remember { FrontFocus() } val frontFocus = remember { FrontFocus() }
androidx.compose.runtime.SideEffect { RunningBuild.channel = s.updates.follow.channel }
val textInput = androidx.compose.ui.platform.LocalTextInputService.current val textInput = androidx.compose.ui.platform.LocalTextInputService.current
val bottomTextInput = remember(textInput) { textInput?.let { androidx.compose.ui.text.input.TextInputService(BottomScreenTextInput(it)) } } val bottomTextInput = remember(textInput) { textInput?.let { androidx.compose.ui.text.input.TextInputService(BottomScreenTextInput(it)) } }
androidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxSize().pointerInput(Unit) { androidx.compose.foundation.layout.BoxWithConstraints(Modifier.fillMaxSize().pointerInput(Unit) {
@@ -507,16 +507,17 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
LaunchedEffect(com.droiddeck.launcher.stores.StoresState.openGameRequest) { LaunchedEffect(com.droiddeck.launcher.stores.StoresState.openGameRequest) {
if (com.droiddeck.launcher.stores.StoresState.openGameRequest != null) selected = "stores" if (com.droiddeck.launcher.stores.StoresState.openGameRequest != null) selected = "stores"
} }
var showWirelessAdbFix by rememberSaveable { mutableStateOf(false) }
var showDeveloperDisplayChoice by rememberSaveable { mutableStateOf(false) } var showDeveloperDisplayChoice by rememberSaveable { mutableStateOf(false) }
var developerChoiceGuided by rememberSaveable { mutableStateOf(false) } var developerChoiceGuided by rememberSaveable { mutableStateOf(false) }
var developerChoiceToggle 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) } var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
val colors = MaterialTheme.colorScheme val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current val pal = LocalPalette.current
val ctx = LocalContext.current val ctx = LocalContext.current
val phantomGateVisible = s.showPhantomGate && PhantomProcessLimit.blocksSteam(s.phantomProcessStatus) val phantomGateVisible = s.showPhantomGate && PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
val processSettingsPageVisible = phantomGateVisible || showDeveloperDisplayChoice val processSettingsPageVisible = phantomGateVisible || showWirelessAdbFix || showDeveloperDisplayChoice
val requestDeveloperOptions = { val requestDeveloperOptions = {
developerChoiceGuided = false developerChoiceGuided = false
developerChoiceToggle = false developerChoiceToggle = false
@@ -524,7 +525,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
else showDeveloperDisplayChoice = true else showDeveloperDisplayChoice = true
} }
val openDeveloperOptionsOn: (Int?) -> Unit = { displayId -> val openDeveloperOptionsOn: (Int?) -> Unit = { displayId ->
if (developerChoiceGuided) a.onStartWirelessAdbPairing(guidedLimitEnabled) if (developerChoiceGuided) a.onStartWirelessAdbPairing()
val guided = developerChoiceGuided || developerChoiceToggle val guided = developerChoiceGuided || developerChoiceToggle
if (!guided || !a.onStartPairingGuide(displayId, developerChoiceToggle)) a.onOpenDeveloperOptions(displayId) if (!guided || !a.onStartPairingGuide(displayId, developerChoiceToggle)) a.onOpenDeveloperOptions(displayId)
developerChoiceGuided = false developerChoiceGuided = false
@@ -540,35 +541,31 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
else showDeveloperDisplayChoice = true else showDeveloperDisplayChoice = true
} }
} }
val startGuidedPairing: (Boolean) -> Unit = { enabled -> val startGuidedPairing = {
a.onEnsureNotifications { granted -> if (!com.droiddeck.launcher.core.WirelessAdbPairingService.notificationsEnabled(ctx)) {
if (granted) { wirelessAdbDesiredEnabled = false
guidedLimitEnabled = enabled showWirelessAdbFix = true
developerChoiceGuided = true } else {
if (s.secondScreenDisplays.isEmpty()) openDeveloperOptionsOn(null) developerChoiceGuided = true
else showDeveloperDisplayChoice = 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) } var applyingSavedPairing by remember { mutableStateOf(false) }
val fixPhantomLimit = { 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) { else if (!applyingSavedPairing) {
applyingSavedPairing = true applyingSavedPairing = true
a.onSetPhantomProcessLimit(false) { error -> a.onSetPhantomProcessLimit(false) { error ->
applyingSavedPairing = false 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) { LaunchedEffect(s.showPhantomGate, s.phantomProcessStatus) {
if (phantomGateVisible) { if (phantomGateVisible) {
while (true) { while (true) {
@@ -804,12 +801,12 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
}, },
{ selected = it }, { selected = it },
onAndroidAppClick = { app -> onAndroidAppClick = { app ->
if (s.secondScreenDisplays.isEmpty() && s.ownScreen == null) a.onAndroidApp(app, null) if (s.secondScreenDisplays.isEmpty()) a.onAndroidApp(app, null)
else appToChooseDisplay = app else appToChooseDisplay = app
}, },
onOpenDeveloperOptions = requestChildProcessToggle, onOpenDeveloperOptions = requestChildProcessToggle,
onPairWirelessDebugging = { startGuidedPairing(false) }, onRequestWirelessAdb = requestWirelessAdbFix,
onRequestWirelessAdb = startGuidedPairing, onPairWirelessDebugging = startGuidedPairing,
) )
} }
@@ -825,7 +822,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
SessionDrawerPreview(s.secondScreenDisplays) SessionDrawerPreview(s.secondScreenDisplays)
appToChooseDisplay?.let { app -> appToChooseDisplay?.let { app ->
val secondaryDisplay = s.secondScreenDisplays.firstOrNull() ?: s.ownScreen val secondaryDisplay = s.secondScreenDisplays.firstOrNull()
ChooseAppDisplayDialog( ChooseAppDisplayDialog(
app = app, app = app,
secondaryDisplay = secondaryDisplay, secondaryDisplay = secondaryDisplay,
@@ -840,7 +837,7 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
onDismiss = { appToChooseDisplay = null }, onDismiss = { appToChooseDisplay = null },
) )
} }
if (phantomGateVisible) { if (phantomGateVisible && !showWirelessAdbFix) {
Box(Modifier.fillMaxSize().background(colors.background)) { Box(Modifier.fillMaxSize().background(colors.background)) {
PhantomProcessGatePage( PhantomProcessGatePage(
status = s.phantomProcessStatus, status = s.phantomProcessStatus,
@@ -848,7 +845,21 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
onOpenDeveloperOptions = requestChildProcessToggle, onOpenDeveloperOptions = requestChildProcessToggle,
applyingSavedPairing = applyingSavedPairing, applyingSavedPairing = applyingSavedPairing,
onFixWithWirelessDebugging = fixPhantomLimit, onFixWithWirelessDebugging = fixPhantomLimit,
onEnterAddressManually = { requestWirelessAdbFix(false) },
onCopyCommand = { a.onCopyPhantomCommand(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,
) )
} }
} }
@@ -894,10 +905,6 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
} }
} }
internal object ChildProcessSetup {
@Volatile var request: (() -> Unit)? = null
}
internal object MainTabSteps { internal object MainTabSteps {
@Volatile var handler: ((Int) -> Unit)? = null @Volatile var handler: ((Int) -> Unit)? = null
} }
@@ -51,7 +51,6 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember import androidx.compose.runtime.remember
@@ -249,7 +248,6 @@ internal fun SetupPanel(
if (listing) SettingsSearchResults(query) { section -> pick(section.ordinal) } if (listing) SettingsSearchResults(query) { section -> pick(section.ordinal) }
else when (tab) { else when (tab) {
OVERVIEW_TAB -> { OVERVIEW_TAB -> {
OnboardingCard(limitBlocks, a.onShowPhantomGate)
// Setup's "Safe mode" row, under the GPU row while the bridge is on and can be used here. // Setup's "Safe mode" row, under the GPU row while the bridge is on and can be used here.
val bridgeModeRow = !s.adreno && s.vkBridge && com.droiddeck.launcher.core.DeviceSupport.bridgeUsable() val bridgeModeRow = !s.adreno && s.vkBridge && com.droiddeck.launcher.core.DeviceSupport.bridgeUsable()
val gpuCheck: @Composable (Boolean) -> Unit = { divider -> val gpuCheck: @Composable (Boolean) -> Unit = { divider ->
@@ -542,7 +540,7 @@ internal fun SetupPanel(
) )
ChoiceRow( ChoiceRow(
host, "dual-screen-sessions", stringResource(R.string.setup_dual_screen_sessions), stringResource(R.string.setup_dual_screen_sessions_hint), 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) { if (s.dualScreenSessions != com.droiddeck.launcher.input.DualScreen.MODE_OFF) {
ToggleRow(host, "dual-screen-controls", stringResource(R.string.setup_dual_screen_controls), ToggleRow(host, "dual-screen-controls", stringResource(R.string.setup_dual_screen_controls),
@@ -1275,66 +1273,3 @@ private fun CustomColorRows() {
} }
} }
} }
@Composable
internal fun OnboardingCard(limitBlocks: Boolean = false, onSetUpLimit: () -> Unit = {}) {
val active by com.droiddeck.launcher.session.Onboarding.active.collectAsState()
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)
if (!settling) return
val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current
val overall = com.droiddeck.launcher.session.Onboarding.overall(rows)
Column(Modifier.fillMaxWidth().padding(top = 8.dp).clip(Shape14).background(colors.surface).border(1.dp, pal.line, Shape14)) {
Column(Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 12.dp)) {
Text(stringResource(R.string.onboarding_title), fontSize = 17.sp, fontWeight = FontWeight.Bold, color = colors.onBackground)
Text(stringResource(R.string.onboarding_summary, overall), fontSize = 13.sp, color = colors.onSurfaceVariant)
LinearProgressIndicator(progress = { overall / 100f }, modifier = Modifier.fillMaxWidth().padding(top = 8.dp).height(4.dp))
}
rows.forEach { row ->
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp),
) {
Column(Modifier.weight(1f)) {
Text(
stringResource(when (row.step) {
com.droiddeck.launcher.session.Onboarding.Step.RUNTIME -> R.string.onboarding_step_runtime
com.droiddeck.launcher.session.Onboarding.Step.PROTON -> R.string.onboarding_step_proton
com.droiddeck.launcher.session.Onboarding.Step.STEAM -> R.string.onboarding_step_steam
}),
fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground,
)
val detail = when (row.state) {
com.droiddeck.launcher.session.Onboarding.State.ACTIVE -> row.label.orEmpty()
com.droiddeck.launcher.session.Onboarding.State.FAILED -> stringResource(R.string.onboarding_failed)
com.droiddeck.launcher.session.Onboarding.State.WAITING -> stringResource(R.string.onboarding_waiting)
com.droiddeck.launcher.session.Onboarding.State.DONE -> stringResource(R.string.onboarding_done)
}
Text(detail, fontSize = 13.sp, color = colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)
if (row.state == com.droiddeck.launcher.session.Onboarding.State.ACTIVE) {
if (row.percent >= 0) LinearProgressIndicator(progress = { row.percent / 100f }, modifier = Modifier.fillMaxWidth().padding(top = 6.dp).height(3.dp))
else LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(top = 6.dp).height(3.dp))
}
}
}
}
if (limitBlocks) {
Box(Modifier.fillMaxWidth().height(1.dp).background(pal.line))
Row(
verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp),
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 10.dp),
) {
Column(Modifier.weight(1f)) {
Text(stringResource(R.string.setup_limit), fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
Text(stringResource(R.string.onboarding_limit_reason), fontSize = 13.sp, color = colors.onSurfaceVariant)
}
PrimaryButton(stringResource(R.string.onboarding_limit_action), compact = true, onClick = onSetUpLimit)
}
}
}
}
@@ -205,12 +205,10 @@ internal fun PrimaryButton(
large: Boolean = false, large: Boolean = false,
icon: ImageVector? = null, icon: ImageVector? = null,
fill: Boolean = false, fill: Boolean = false,
progress: Float? = null,
onClick: () -> Unit, onClick: () -> Unit,
) { ) {
val colors = MaterialTheme.colorScheme val colors = MaterialTheme.colorScheme
val pal = LocalPalette.current val pal = LocalPalette.current
val shownProgress by animateFloatAsState(progress?.coerceIn(0f, 1f) ?: 0f, Motion.tw(300), label = "btnProgress")
val pillMode = LocalPillButtons.current val pillMode = LocalPillButtons.current
val btnShape = if (pillMode) CircleShape else Shape12 val btnShape = if (pillMode) CircleShape else Shape12
val outlined = LocalGradientOutline.current && enabled 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 } .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) .clip(btnShape)
.background(if (enabled) Brush.linearGradient(listOf(colors.primary, pal.primary2)) else Brush.linearGradient(listOf(colors.surfaceVariant, colors.surfaceVariant))) .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 (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) .then(if (outlined) Modifier.border(2.dp, Brush.linearGradient(listOf(pal.primary2, colors.primary)), btnShape) else Modifier)
.glideBorder(hot, btnShape, pal.signal, hotFillAlpha = 0f) .glideBorder(hot, btnShape, pal.signal, hotFillAlpha = 0f)
@@ -295,7 +295,7 @@ internal fun GameDetail(
GameTab.ACHIEVEMENTS -> achievementState?.let { st -> AchievementsTab(StoreAchievements.forSource(store?.id)?.label.orEmpty(), st) } GameTab.ACHIEVEMENTS -> achievementState?.let { st -> AchievementsTab(StoreAchievements.forSource(store?.id)?.label.orEmpty(), st) }
GameTab.LAUNCH -> if (game != null) LaunchTab(game, s, a, hopRail) GameTab.LAUNCH -> if (game != null) LaunchTab(game, s, a, hopRail)
GameTab.SAVES -> if (game != null && prefix != null) SavesTab(game, prefix, a) GameTab.SAVES -> if (game != null && prefix != null) SavesTab(game, prefix, a)
GameTab.ADDONS -> if (game != null) AddonsTab(game, addonTargets, s.sessionRunning, a) GameTab.ADDONS -> if (game != null) AddonsTab(game, addonTargets, a)
GameTab.INSTALL -> InstallTab(game, installed, item, store) GameTab.INSTALL -> InstallTab(game, installed, item, store)
} }
} }
@@ -1047,11 +1047,9 @@ private fun SavesTab(g: Library.SteamGame, prefix: File, a: FrontEndActions) {
} }
@Composable @Composable
private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, sessionRunning: Boolean, a: FrontEndActions) { private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, a: FrontEndActions) {
var browsing by remember(g.gameId) { mutableStateOf<WowAddons.Target?>(null) } var browsing by remember(g.gameId) { mutableStateOf<WowAddons.Target?>(null) }
val curseForge = CurseForgeApp.find(UserAppsState.items) browsing?.let { AddonBrowserDialog(targets, it, CurseForgeApp.find(UserAppsState.items)) { browsing = null } }
val link = rememberCurseLink(curseForge, sessionRunning)
browsing?.let { AddonBrowserDialog(targets, it, curseForge, link) { browsing = null } }
Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) { Column(Modifier.fillMaxWidth().tabPanel(), verticalArrangement = Arrangement.spacedBy(2.dp)) {
CurseForgeEntry(a) CurseForgeEntry(a)
targets.forEach { target -> targets.forEach { target ->
@@ -1062,12 +1060,6 @@ private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, ses
val updates by produceState(emptyMap<String, WowAddonCatalog.Addon>(), names) { val updates by produceState(emptyMap<String, WowAddonCatalog.Addon>(), names) {
value = withContext(Dispatchers.IO) { WowAddonCatalog.updates(context, names, target) } value = withContext(Dispatchers.IO) { WowAddonCatalog.updates(context, names, target) }
} }
val scanKey = link?.generation to WowAddons.imports
val managed by produceState(emptyMap<String, CurseForgeApp.Project>(), link, target.addOns, scanKey) {
value = if (link == null) emptyMap() else withContext(Dispatchers.IO) {
runCatching { CurseForgeApp.byFolder(link.installed(context, target, scanKey)) }.getOrDefault(emptyMap())
}
}
if (targets.size > 1) SectionLabel(target.flavor) if (targets.size > 1) SectionLabel(target.flavor)
MenuItem(stringResource(R.string.addons_download), checked = false) { browsing = target } MenuItem(stringResource(R.string.addons_download), checked = false) { browsing = target }
MenuItem( MenuItem(
@@ -1078,7 +1070,7 @@ private fun AddonsTab(g: Library.SteamGame, targets: List<WowAddons.Target>, ses
target.addOns.mkdirs() target.addOns.mkdirs()
a.onBrowseFiles(target.addOns) a.onBrowseFiles(target.addOns)
} }
names.forEach { item -> key(target.addOns, item.name) { AddonRow(item, updates[item.name], target, a, link?.let { l -> managed[item.name.lowercase()]?.let { it to l } }) } } names.forEach { item -> key(target.addOns, item.name) { AddonRow(item, updates[item.name], target, a) } }
} }
} }
} }
@@ -1132,10 +1124,8 @@ private fun CurseForgeEntry(a: FrontEndActions) {
} }
@Composable @Composable
internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions, curse: Pair<CurseForgeApp.Project, CurseLink>? = null) { private fun AddonRow(item: WowAddons.Installed, update: WowAddonCatalog.Addon?, target: WowAddons.Target, a: FrontEndActions) {
val name = item.name val name = item.name
val update = wowiUpdate.takeIf { curse == null }
val outdated = update != null || curse?.first?.update == true
var asking by remember(target.addOns, name) { mutableStateOf(false) } var asking by remember(target.addOns, name) { mutableStateOf(false) }
var progress by remember(target.addOns, name) { mutableStateOf<Int?>(null) } var progress by remember(target.addOns, name) { mutableStateOf<Int?>(null) }
val context = LocalContext.current val context = LocalContext.current
@@ -1145,33 +1135,26 @@ internal fun AddonRow(item: WowAddons.Installed, wowiUpdate: WowAddonCatalog.Add
Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(start = 16.dp, top = 2.dp, bottom = 2.dp)) { Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(start = 16.dp, top = 2.dp, bottom = 2.dp)) {
Column(Modifier.weight(1f)) { Column(Modifier.weight(1f)) {
Text(name, fontSize = 14.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) Text(name, fontSize = 14.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis)
val detail = listOfNotNull(item.version, if (outdated) stringResource(R.string.upd_available) else null).joinToString(" · ") val detail = listOfNotNull(item.version, update?.let { stringResource(R.string.upd_available) }).joinToString(" · ")
if (detail.isNotEmpty()) Text( if (detail.isNotEmpty()) Text(
progress?.let { stringResource(R.string.ctrl_percent, it) } ?: detail, fontSize = 12.sp, progress?.let { stringResource(R.string.ctrl_percent, it) } ?: detail, fontSize = 12.sp,
color = if (outdated) LocalPalette.current.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis, color = if (update != null) LocalPalette.current.signal else colors.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis,
) )
} }
if (outdated && !SessionState.running) IconAction(Icons.Outlined.Download, stringResource(R.string.common_update), "addon:update:${target.flavor}:$name", enabled = progress == null) { if (update != null && !SessionState.running) IconAction(Icons.Outlined.Download, stringResource(R.string.common_update), "addon:update:${target.flavor}:$name", enabled = progress == null) {
progress = 0 progress = 0
scope.launch { scope.launch {
val message = withContext(Dispatchers.IO) { val message = withContext(Dispatchers.IO) { installAddon(context, update, target) { pct -> scope.launch { progress = pct } } }
if (curse != null) {
val (project, link) = curse
val done = runCatching { link.change(context, target) { CurseForgeApp.update(context, it.inspector, it.guid, project.id) } }.getOrDefault(false)
WowAddons.changed()
if (done) context.getString(R.string.user_apps_updated, name) else context.getString(R.string.stores_dl_failed_reason, name)
} else update?.let { installAddon(context, it, target) { pct -> scope.launch { progress = pct } }.first }
}
progress = null progress = null
if (message != null) android.widget.Toast.makeText(context, message, android.widget.Toast.LENGTH_LONG).show() android.widget.Toast.makeText(context, message.first, android.widget.Toast.LENGTH_LONG).show()
} }
} }
if (!SessionState.running) IconAction(Icons.Outlined.Delete, if (curse != null) stringResource(R.string.common_uninstall) else delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true } if (!SessionState.running) IconAction(Icons.Outlined.Delete, delete, "addon:delete:${target.flavor}:$name", danger = true) { asking = true }
} }
if (asking) ConfirmDialog( if (asking) ConfirmDialog(
title = if (curse != null) stringResource(R.string.stores_uninstall_title, name) else stringResource(R.string.games_delete_addon_title, name), title = stringResource(R.string.games_delete_addon_title, name),
text = stringResource(R.string.games_delete_addon_body), text = stringResource(R.string.games_delete_addon_body),
confirm = if (curse != null) stringResource(R.string.common_uninstall) else delete, confirm = delete,
onConfirm = { a.onAddonDelete(target, name) }, onConfirm = { a.onAddonDelete(target, name) },
onDismiss = { asking = false }, onDismiss = { asking = false },
) )
@@ -126,8 +126,6 @@ internal object SheetTab {
const val LIBRARY = "library" const val LIBRARY = "library"
const val STEAM = "steam" const val STEAM = "steam"
const val FILES = "files" const val FILES = "files"
const val DECKY = "decky"
const val BOOT_MOVIES = "boot-movies"
} }
internal fun sheetTop(paneH: Float, buttonH: Float, minAbove: Float, ride: Float): Float = internal fun sheetTop(paneH: Float, buttonH: Float, minAbove: Float, ride: Float): Float =
@@ -191,7 +189,6 @@ internal fun LiftHero(
onOpenChange: (Boolean) -> Unit = {}, onOpenChange: (Boolean) -> Unit = {},
start: Dp = 44.dp, start: Dp = 44.dp,
bottom: Dp = 44.dp, bottom: Dp = 44.dp,
onTextBounds: (Rect) -> Unit = {},
drop: DropSheetState? = null, drop: DropSheetState? = null,
overlay: @Composable BoxWithConstraintsScope.(lifted: () -> Float) -> Unit = {}, overlay: @Composable BoxWithConstraintsScope.(lifted: () -> Float) -> Unit = {},
) { ) {
@@ -576,7 +573,7 @@ internal fun LiftHero(
} }
} }
Column(Modifier.align(Alignment.BottomStart).padding(start = start, bottom = bottom, end = 20.dp).onGloballyPositioned { onTextBounds(it.boundsInRoot()) }) { Column(Modifier.align(Alignment.BottomStart).padding(start = start, bottom = bottom, end = 20.dp)) {
Box(Modifier.graphicsLayer { alpha = 1f - wallSink() }) { words() } Box(Modifier.graphicsLayer { alpha = 1f - wallSink() }) { words() }
Spacer(Modifier.height(18.dp)) Spacer(Modifier.height(18.dp))
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) { Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
@@ -57,7 +57,7 @@ internal fun ManageDrawerPages(offeredNow: List<SessionDrawerPage>, modifier: Mo
SortableRows( SortableRows(
rows = { current.map { it.name } }, rows = { current.map { it.name } },
commit = { names -> DrawerPages.rearrange(ctx, names.mapNotNull { n -> current.firstOrNull { it.name == n } }) }, commit = { names -> DrawerPages.rearrange(ctx, names.mapNotNull { n -> current.firstOrNull { it.name == n } }) },
movable = { it != SessionDrawerPage.MORE.name }, movable = { true },
rowHeight = STORE_ROW, handleWidth = STORE_HANDLE, rowHeight = STORE_ROW, handleWidth = STORE_HANDLE,
releaseSignal = releaseSignal, releaseSignal = releaseSignal,
onGrab = { before -> DrawerPages.heldFrom = before?.mapNotNull { n -> current.firstOrNull { it.name == n } } }, onGrab = { before -> DrawerPages.heldFrom = before?.mapNotNull { n -> current.firstOrNull { it.name == n } } },
@@ -66,8 +66,6 @@ internal fun ManageDrawerPages(offeredNow: List<SessionDrawerPage>, modifier: Mo
}, },
) { name, held, offset, hint, rowModifier, onFocus -> ) { name, held, offset, hint, rowModifier, onFocus ->
val page = current.first { it.name == name } val page = current.first { it.name == name }
// The same divider the launcher's Edit tabs uses: pages above it are tabs, pages below it are kept in More.
if (page == SessionDrawerPage.MORE) { MoreLine(STORE_ROW); return@SortableRows }
val shown = page !in DrawerPages.hidden val shown = page !in DrawerPages.hidden
val pal = LocalPalette.current val pal = LocalPalette.current
val label = stringResource(page.title) val label = stringResource(page.title)
@@ -202,7 +202,7 @@ internal fun SideSheet(open: Boolean, onClose: () -> Unit, returnFocus: FocusReq
if (!pad) return@LaunchedEffect if (!pad) return@LaunchedEffect
repeat(60) { repeat(60) {
androidx.compose.runtime.withFrameNanos { } androidx.compose.runtime.withFrameNanos { }
if (holds || !open || Steps.open) return@LaunchedEffect if (holds || !open) return@LaunchedEffect
runCatching { inside.requestFocus() } runCatching { inside.requestFocus() }
} }
} }
@@ -210,7 +210,7 @@ internal fun SideSheet(open: Boolean, onClose: () -> Unit, returnFocus: FocusReq
Modifier.width(width).fillMaxHeight() Modifier.width(width).fillMaxHeight()
.onFocusChanged { holds = it.hasFocus } .onFocusChanged { holds = it.hasFocus }
.focusRequester(inside) .focusRequester(inside)
.focusProperties { exit = { if (open && !Steps.open) FocusRequester.Cancel else FocusRequester.Default } } .focusProperties { exit = { if (open) FocusRequester.Cancel else FocusRequester.Default } }
.focusGroup() .focusGroup()
.background(MaterialTheme.colorScheme.background) .background(MaterialTheme.colorScheme.background)
.border(1.dp, pal.line).padding(horizontal = 18.dp, vertical = 16.dp).testTag(tag), .border(1.dp, pal.line).padding(horizontal = 18.dp, vertical = 16.dp).testTag(tag),
@@ -78,7 +78,6 @@ class ModeSettings(
val mic: Boolean?, val mic: Boolean?,
val gameStorage: String? = null, val gameStorage: String? = null,
val storageOptions: List<com.droiddeck.launcher.session.GameStorage.Option> = emptyList(), 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 steamLibraries: List<com.droiddeck.launcher.session.SteamLibraries.Entry> = emptyList(),
val foundSteamLibraries: List<com.droiddeck.launcher.session.SteamLibraries.Found> = emptyList(), val foundSteamLibraries: List<com.droiddeck.launcher.session.SteamLibraries.Found> = emptyList(),
val allFilesAccessMissing: Boolean = false, val allFilesAccessMissing: Boolean = false,
@@ -114,9 +113,6 @@ class ModeSettings(
val deckyDownloadingBinary: Boolean = false, val deckyDownloadingBinary: Boolean = false,
val deckyEnabled: Boolean = false, val deckyEnabled: Boolean = false,
val deckySessionRunning: Boolean = false, val deckySessionRunning: Boolean = false,
val deckyPlugins: List<com.droiddeck.launcher.runtime.DeckyStore.Installed> = emptyList(),
val deckyStore: List<com.droiddeck.launcher.runtime.DeckyStore.Plugin>? = null,
val deckyStoreFailed: Boolean = false,
) )
class ModeSettingsActions( class ModeSettingsActions(
@@ -175,9 +171,6 @@ class ModeSettingsActions(
val onDeckyEnabled: (Boolean) -> Unit = {}, val onDeckyEnabled: (Boolean) -> Unit = {},
val onDeckyUninstall: () -> Unit = {}, val onDeckyUninstall: () -> Unit = {},
val onPickDeckyPluginZip: () -> Unit = {}, val onPickDeckyPluginZip: () -> Unit = {},
val onDeckyStoreRefresh: () -> Unit = {},
val onDeckyStoreInstall: (com.droiddeck.launcher.runtime.DeckyStore.Plugin) -> Unit = {},
val onDeckyRemove: (com.droiddeck.launcher.runtime.DeckyStore.Installed) -> Unit = {},
val onDismiss: () -> Unit, val onDismiss: () -> Unit,
) )
@@ -227,8 +220,6 @@ class SheetExtras(
fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: SheetExtras = SheetExtras()) { fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras: SheetExtras = SheetExtras()) {
val steam = s.mode == SessionService.MODE_STEAM val steam = s.mode == SessionService.MODE_STEAM
val host = rememberMenuHost() val host = rememberMenuHost()
if (tab == SheetTab.DECKY) { DeckyGroups(s, a, host); return }
if (tab == SheetTab.BOOT_MOVIES) { if (s.bootMovie != null) BootMovieGroup(s, a, host); return }
Text( Text(
stringResource(when (s.mode) { stringResource(when (s.mode) {
SessionService.MODE_STEAM -> R.string.sheet_scope_steam SessionService.MODE_STEAM -> R.string.sheet_scope_steam
@@ -456,7 +447,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" } ValueChip(options.firstOrNull { it.path == s.gameStorage }?.chip ?: "-", open) { host.open = if (open) null else "storage" }
AnchoredMenu( AnchoredMenu(
open, onDismiss = { if (host.open == "storage") host.open = null }, title = stringResource(R.string.mode_second_library), 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 -> ) { firstItemFocus ->
options.forEachIndexed { index, choice -> options.forEachIndexed { index, choice ->
MenuItem(choice.label, checked = choice.path == s.gameStorage, focusRequester = if (index == 0) firstItemFocus else null) { MenuItem(choice.label, checked = choice.path == s.gameStorage, focusRequester = if (index == 0) firstItemFocus else null) {
@@ -518,6 +509,75 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
} }
if (tab == SheetTab.STEAM && steam) { if (tab == SheetTab.STEAM && steam) {
extras.account(host) extras.account(host)
SettingsGroup(stringResource(R.string.mode_decky)) {
val updateAvailable = s.deckyInstalled != null && s.deckyLatestRelease != null &&
s.deckyInstalled != s.deckyLatestRelease.tag
val status = when {
s.deckyStage != null -> s.deckyStage
s.deckyChecking -> stringResource(R.string.mode_decky_checking)
s.deckyInstalled == null && s.deckyLatestRelease != null -> stringResource(R.string.mode_decky_ready, s.deckyLatestRelease.tag)
s.deckyInstalled == null -> stringResource(R.string.mode_decky_none)
s.deckyLatestRelease == null -> stringResource(R.string.mode_decky_installed, s.deckyInstalled)
updateAvailable -> stringResource(R.string.mode_decky_update, s.deckyLatestRelease.tag)
else -> stringResource(R.string.mode_decky_current, s.deckyInstalled)
}
SettingsRow(stringResource(R.string.mode_decky_loader), status) {
val action = when {
s.deckyStage != null -> stringResource(R.string.common_working)
s.deckyChecking -> stringResource(R.string.common_checking)
s.deckyInstalled == null && s.deckyLatestRelease != null -> stringResource(R.string.mode_decky_install_latest)
s.deckyInstalled != null && updateAvailable -> stringResource(R.string.common_update)
else -> stringResource(R.string.common_check)
}
Row(horizontalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(6.dp)) {
SecondaryButton(
action,
enabled = s.deckyStage == null && !s.deckyChecking && !s.deckySessionRunning,
) {
if (s.deckyLatestRelease == null || (s.deckyInstalled != null && !updateAvailable)) a.onDeckyCheck()
else s.deckyLatestRelease?.let(a.onDeckyInstall)
}
if (s.deckyInstalled != null) DeckyUninstall(enabled = s.deckyStage == null && !s.deckySessionRunning, onUninstall = a.onDeckyUninstall)
}
}
ChoiceRow(
host, "decky-channel", stringResource(R.string.decky_channel),
stringResource(R.string.decky_channel_hint),
listOf(
DeckyManager.BRANCH_STABLE to stringResource(R.string.decky_channel_stable),
DeckyManager.BRANCH_PRERELEASE to stringResource(R.string.decky_channel_prerelease),
) + if (s.deckyBranch == DeckyManager.BRANCH_TESTING) listOf(
DeckyManager.BRANCH_TESTING to stringResource(R.string.decky_channel_testing),
) else emptyList(),
s.deckyBranch,
enabled = s.deckyStage == null && !s.deckySessionRunning,
onPick = a.onDeckyBranch,
)
if (s.deckyInstalled != null) ToggleRow(
host, "decky-enabled", stringResource(R.string.mode_decky),
if (s.deckyEnabled) stringResource(R.string.mode_decky_on)
else stringResource(R.string.mode_decky_off),
s.deckyEnabled,
enabled = !s.deckySessionRunning && s.deckyStage == null,
onChange = a.onDeckyEnabled,
)
SettingsRow(
stringResource(R.string.mode_decky_plugins),
stringResource(R.string.mode_decky_plugins_hint),
) {
SecondaryButton(
if (s.deckyStage != null && s.deckyDownloadingBinary) stringResource(R.string.mode_decky_plugin_downloading) else stringResource(R.string.mode_decky_plugin_install_zip),
enabled = s.deckyInstalled != null && s.deckyStage == null && !s.deckySessionRunning,
onClick = a.onPickDeckyPluginZip,
)
}
if (s.deckyStage != null && s.deckyPercent >= 0) {
LinearProgressIndicator(
progress = { s.deckyPercent / 100f },
modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp),
)
}
}
SettingsGroup(stringResource(R.string.mode_client)) { SettingsGroup(stringResource(R.string.mode_client)) {
ToggleRow( ToggleRow(
host, "mangoapp", stringResource(R.string.mode_mangoapp), host, "mangoapp", stringResource(R.string.mode_mangoapp),
@@ -547,6 +607,7 @@ fun ModeSheetRows(s: ModeSettings, a: ModeSettingsActions, tab: String, extras:
onPick = a.onSteamClientArch, onPick = a.onSteamClientArch,
) )
} }
if (s.bootMovie != null) BootMovieGroup(s, a, host)
if (s.integration != null) SteamIntegrationGroup(s.integration, if (s.integration != null) SteamIntegrationGroup(s.integration,
onFeature = a.onIntegration, onAppInfo = a.onIntegrationAppInfo, onLocation = a.onIntegrationLocation) onFeature = a.onIntegration, onAppInfo = a.onIntegrationAppInfo, onLocation = a.onIntegrationLocation)
} }
@@ -608,7 +669,7 @@ internal fun DeckyZipWarningDialog(onConfirm: () -> Unit, onCancel: () -> Unit)
private const val DECKY_ZIP_WARNING_SECONDS = 5 private const val DECKY_ZIP_WARNING_SECONDS = 5
@Composable @Composable
internal fun DeckyUninstall(enabled: Boolean, onUninstall: () -> Unit) { private fun DeckyUninstall(enabled: Boolean, onUninstall: () -> Unit) {
val colors = MaterialTheme.colorScheme val colors = MaterialTheme.colorScheme
val label = stringResource(R.string.common_uninstall) val label = stringResource(R.string.common_uninstall)
val title = stringResource(R.string.mode_decky_remove_title) val title = stringResource(R.string.mode_decky_remove_title)
@@ -26,10 +26,10 @@ internal object DeveloperTools {
internal object NavTabs { internal object NavTabs {
const val MORE = "more" const val MORE = "more"
val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent") val ALL = listOf("steam", "desktop", "games", "downloads", "setup", "updates", "stores", "soundtracks", "components", "storage", "sync", "android-apps", "agent")
val DEFAULT_SHELVED = setOf("soundtracks", "components", "storage", "sync", "decky", "boot-movies", "android-apps", "agent") val DEFAULT_SHELVED = setOf("stores", "soundtracks", "components", "storage", "sync", "android-apps", "agent")
val DEFAULT_HIDDEN = setOf("android-apps", "agent") val DEFAULT_HIDDEN = setOf("android-apps", "agent")
private val SHELVED_WHEN_NEW = setOf("storage", "sync", "decky", "boot-movies", "android-apps", "agent") private val SHELVED_WHEN_NEW = setOf("storage", "sync", "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_ORDER = listOf("steam", "games", "soundtracks", "stores", "downloads", "desktop", "agent", "components", "android-apps", "storage", "sync", "setup", "updates")
private val OLD_SHELVED = setOf("soundtracks", "agent", "storage", "sync") private val OLD_SHELVED = setOf("soundtracks", "agent", "storage", "sync")
private const val LAYOUT_VERSION = 2 private const val LAYOUT_VERSION = 2
@@ -50,7 +50,9 @@ fun PhantomProcessGatePage(
onDismiss: () -> Unit, onDismiss: () -> Unit,
onOpenDeveloperOptions: () -> Unit, onOpenDeveloperOptions: () -> Unit,
onFixWithWirelessDebugging: () -> Unit, onFixWithWirelessDebugging: () -> Unit,
onEnterAddressManually: () -> Unit,
onCopyCommand: () -> Unit, onCopyCommand: () -> Unit,
onOpenNotificationSettings: () -> Unit,
) { ) {
BackHandler(onBack = onDismiss) BackHandler(onBack = onDismiss)
val context = LocalContext.current val context = LocalContext.current
@@ -80,11 +82,11 @@ fun PhantomProcessGatePage(
val fix: @Composable ColumnScope.() -> Unit = { val fix: @Composable ColumnScope.() -> Unit = {
if (sideQuest) SideQuestGroup(compact, onCopyCommand) if (sideQuest) SideQuestGroup(compact, onCopyCommand)
else FixGroup(hasToggle, stage, environment, compact, applyingSavedPairing, onOpenDeveloperOptions, onFixWithWirelessDebugging, else FixGroup(hasToggle, stage, environment, compact, applyingSavedPairing, onOpenDeveloperOptions, onFixWithWirelessDebugging,
onCancel = { WirelessAdbPairingService.cancel(context) }) onOpenNotificationSettings, onCancel = { WirelessAdbPairingService.cancel(context) })
} }
val side: @Composable ColumnScope.() -> Unit = { val side: @Composable ColumnScope.() -> Unit = {
StatusGroup(status, compact) StatusGroup(status, compact)
if (!sideQuest) OtherWays(hasToggle, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging, onCopyCommand) if (!sideQuest) OtherWays(hasToggle, compact, onOpenDeveloperOptions, onFixWithWirelessDebugging, onEnterAddressManually, onCopyCommand)
} }
if (wide) { if (wide) {
Row(horizontalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth()) { 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 { companion object {
fun read(context: Context): GateEnvironment { fun read(context: Context): GateEnvironment {
val connectivity = context.getSystemService(ConnectivityManager::class.java) val connectivity = context.getSystemService(ConnectivityManager::class.java)
val wifi = runCatching { val wifi = runCatching {
connectivity?.allNetworks?.any { network -> connectivity?.getNetworkCapabilities(connectivity.activeNetwork)
connectivity.getNetworkCapabilities(network)?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true ?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true
} == true
}.getOrDefault(true) }.getOrDefault(true)
return GateEnvironment(wifi) return GateEnvironment(wifi, WirelessAdbPairingService.notificationsEnabled(context))
} }
} }
} }
@@ -125,6 +126,7 @@ private fun FixGroup(
applyingSavedPairing: Boolean, applyingSavedPairing: Boolean,
onOpenDeveloperOptions: () -> Unit, onOpenDeveloperOptions: () -> Unit,
onFixWithWirelessDebugging: () -> Unit, onFixWithWirelessDebugging: () -> Unit,
onOpenNotificationSettings: () -> Unit,
onCancel: () -> Unit, onCancel: () -> Unit,
) { ) {
val pairing = stage is Stage.Waiting || stage is Stage.CodeNeeded || stage is Stage.Working val pairing = stage is Stage.Waiting || stage is Stage.CodeNeeded || stage is Stage.Working
@@ -142,7 +144,6 @@ private fun FixGroup(
hasToggle -> { hasToggle -> {
Body(stringResource(R.string.gate_toggle_steps)) Body(stringResource(R.string.gate_toggle_steps))
PrimaryButton(stringResource(R.string.gate_open_dev), compact = compact, onClick = onOpenDeveloperOptions) 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 -> { else -> {
Body(stringResource(R.string.gate_no_toggle)) Body(stringResource(R.string.gate_no_toggle))
@@ -150,7 +151,7 @@ private fun FixGroup(
PrimaryButton( PrimaryButton(
if (stage is Stage.Failed) stringResource(R.string.store_try_again) else stringResource(R.string.gate_fix_for_me), if (stage is Stage.Failed) stringResource(R.string.store_try_again) else stringResource(R.string.gate_fix_for_me),
compact = compact, compact = compact,
enabled = environment.onWifi, enabled = environment.onWifi && environment.notifications,
onClick = onFixWithWirelessDebugging, onClick = onFixWithWirelessDebugging,
) )
} }
@@ -159,6 +160,10 @@ private fun FixGroup(
if (!environment.onWifi) { if (!environment.onWifi) {
Body(stringResource(R.string.gate_needs_wifi), warn = true) 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, compact: Boolean,
onOpenDeveloperOptions: () -> Unit, onOpenDeveloperOptions: () -> Unit,
onFixWithWirelessDebugging: () -> Unit, onFixWithWirelessDebugging: () -> Unit,
onEnterAddressManually: () -> Unit,
onCopyCommand: () -> Unit, onCopyCommand: () -> Unit,
) { ) {
var open by rememberSaveable { mutableStateOf(false) } 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), modifier = Modifier.fillMaxWidth().padding(start = 14.dp, end = 14.dp, bottom = 14.dp),
verticalArrangement = Arrangement.spacedBy(8.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)) Body(stringResource(R.string.gate_some_roms))
SecondaryButton(stringResource(R.string.gate_open_dev), compact = true, onClick = onOpenDeveloperOptions) 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)) Body(stringResource(R.string.gate_from_computer))
AdbCommand() AdbCommand()
SecondaryButton(stringResource(R.string.gate_copy_command), compact = true, onClick = onCopyCommand) SecondaryButton(stringResource(R.string.gate_copy_command), compact = true, onClick = onCopyCommand)
@@ -75,19 +75,6 @@ internal fun SyncTabPage(s: FrontEndState, modifier: Modifier) {
} }
} }
@Composable
internal fun SteamTabPage(key: String, a: FrontEndActions, modifier: Modifier) {
LaunchedEffect(Unit) { a.onSteamSettings() }
Column(modifier.verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) {
PageHeader(stringResource(if (key == "decky") R.string.rail_decky else R.string.rail_boot_movies))
a.modeSheet(
com.droiddeck.launcher.session.SessionService.MODE_STEAM,
if (key == "decky") SheetTab.DECKY else SheetTab.BOOT_MOVIES,
SheetExtras(),
)
}
}
@Composable @Composable
private fun ResetTabsRow() { private fun ResetTabsRow() {
val ctx = androidx.compose.ui.platform.LocalContext.current val ctx = androidx.compose.ui.platform.LocalContext.current
Loaded 100 of 353 files, more files were not shown because too many files have changed in this diff. Show more